all repos — mgba @ eb21dd722f3660e0f832e11225048304a15b1d07

mGBA Game Boy Advance Emulator

src/gba/supervisor/thread.c (view raw)

  1/* Copyright (c) 2013-2015 Jeffrey Pfau
  2 *
  3 * This Source Code Form is subject to the terms of the Mozilla Public
  4 * License, v. 2.0. If a copy of the MPL was not distributed with this
  5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  6#include "thread.h"
  7
  8#include "arm.h"
  9#include "gba/gba.h"
 10#include "gba/cheats.h"
 11#include "gba/serialize.h"
 12#include "gba/supervisor/config.h"
 13#include "gba/rr/mgm.h"
 14#include "gba/rr/vbm.h"
 15
 16#include "debugger/debugger.h"
 17
 18#include "util/patch.h"
 19#include "util/png-io.h"
 20#include "util/vfs.h"
 21
 22#include "platform/commandline.h"
 23
 24#include <signal.h>
 25
 26static const float _defaultFPSTarget = 60.f;
 27
 28#ifdef USE_PTHREADS
 29static pthread_key_t _contextKey;
 30static pthread_once_t _contextOnce = PTHREAD_ONCE_INIT;
 31
 32static void _createTLS(void) {
 33	pthread_key_create(&_contextKey, 0);
 34}
 35#elif _WIN32
 36static DWORD _contextKey;
 37static INIT_ONCE _contextOnce = INIT_ONCE_STATIC_INIT;
 38
 39static BOOL CALLBACK _createTLS(PINIT_ONCE once, PVOID param, PVOID* context) {
 40	UNUSED(once);
 41	UNUSED(param);
 42	UNUSED(context);
 43	_contextKey = TlsAlloc();
 44	return TRUE;
 45}
 46#endif
 47
 48#ifndef DISABLE_THREADING
 49static void _changeState(struct GBAThread* threadContext, enum ThreadState newState, bool broadcast) {
 50	MutexLock(&threadContext->stateMutex);
 51	threadContext->state = newState;
 52	if (broadcast) {
 53		ConditionWake(&threadContext->stateCond);
 54	}
 55	MutexUnlock(&threadContext->stateMutex);
 56}
 57
 58static void _waitOnInterrupt(struct GBAThread* threadContext) {
 59	while (threadContext->state == THREAD_INTERRUPTED) {
 60		ConditionWait(&threadContext->stateCond, &threadContext->stateMutex);
 61	}
 62}
 63
 64static void _waitUntilNotState(struct GBAThread* threadContext, enum ThreadState oldState) {
 65	MutexLock(&threadContext->sync.videoFrameMutex);
 66	bool videoFrameWait = threadContext->sync.videoFrameWait;
 67	threadContext->sync.videoFrameWait = false;
 68	MutexUnlock(&threadContext->sync.videoFrameMutex);
 69
 70	while (threadContext->state == oldState) {
 71		MutexUnlock(&threadContext->stateMutex);
 72
 73		MutexLock(&threadContext->sync.videoFrameMutex);
 74		ConditionWake(&threadContext->sync.videoFrameRequiredCond);
 75		MutexUnlock(&threadContext->sync.videoFrameMutex);
 76
 77		MutexLock(&threadContext->sync.audioBufferMutex);
 78		ConditionWake(&threadContext->sync.audioRequiredCond);
 79		MutexUnlock(&threadContext->sync.audioBufferMutex);
 80
 81		MutexLock(&threadContext->stateMutex);
 82		ConditionWake(&threadContext->stateCond);
 83	}
 84
 85	MutexLock(&threadContext->sync.videoFrameMutex);
 86	threadContext->sync.videoFrameWait = videoFrameWait;
 87	MutexUnlock(&threadContext->sync.videoFrameMutex);
 88}
 89
 90static void _pauseThread(struct GBAThread* threadContext, bool onThread) {
 91	threadContext->state = THREAD_PAUSING;
 92	if (!onThread) {
 93		_waitUntilNotState(threadContext, THREAD_PAUSING);
 94	}
 95}
 96#endif
 97
 98static void _changeVideoSync(struct GBASync* sync, bool frameOn) {
 99	// Make sure the video thread can process events while the GBA thread is paused
100	MutexLock(&sync->videoFrameMutex);
101	if (frameOn != sync->videoFrameOn) {
102		sync->videoFrameOn = frameOn;
103		ConditionWake(&sync->videoFrameAvailableCond);
104	}
105	MutexUnlock(&sync->videoFrameMutex);
106}
107
108#ifndef DISABLE_THREADING
109static THREAD_ENTRY _GBAThreadRun(void* context) {
110#ifdef USE_PTHREADS
111	pthread_once(&_contextOnce, _createTLS);
112#else
113	InitOnceExecuteOnce(&_contextOnce, _createTLS, NULL, 0);
114#endif
115
116	struct GBA gba;
117	struct ARMCore cpu;
118	struct Patch patch;
119	struct GBACheatDevice cheatDevice;
120	struct GBAThread* threadContext = context;
121	struct ARMComponent* components[GBA_COMPONENT_MAX] = {};
122	struct GBARRContext* movie = 0;
123	int numComponents = GBA_COMPONENT_MAX;
124
125#if !defined(_WIN32) && defined(USE_PTHREADS)
126	sigset_t signals;
127	sigemptyset(&signals);
128	pthread_sigmask(SIG_SETMASK, &signals, 0);
129#endif
130
131	GBACreate(&gba);
132	ARMSetComponents(&cpu, &gba.d, numComponents, components);
133	ARMInit(&cpu);
134	gba.sync = &threadContext->sync;
135	threadContext->gba = &gba;
136	gba.logLevel = threadContext->logLevel;
137	gba.logHandler = threadContext->logHandler;
138	gba.idleOptimization = threadContext->idleOptimization;
139#ifdef USE_PTHREADS
140	pthread_setspecific(_contextKey, threadContext);
141#else
142	TlsSetValue(_contextKey, threadContext);
143#endif
144
145	if (threadContext->audioBuffers) {
146		GBAAudioResizeBuffer(&gba.audio, threadContext->audioBuffers);
147	} else {
148		threadContext->audioBuffers = GBA_AUDIO_SAMPLES;
149	}
150
151	if (threadContext->renderer) {
152		GBAVideoAssociateRenderer(&gba.video, threadContext->renderer);
153	}
154
155	if (threadContext->rom) {
156		GBALoadROM(&gba, threadContext->rom, threadContext->save, threadContext->fname);
157
158		struct GBACartridgeOverride override;
159		const struct GBACartridge* cart = (const struct GBACartridge*) gba.memory.rom;
160		memcpy(override.id, &cart->id, sizeof(override.id));
161		if (GBAOverrideFind(threadContext->overrides, &override)) {
162			GBAOverrideApply(&gba, &override);
163		}
164		if (threadContext->hasOverride) {
165			GBAOverrideApply(&gba, &threadContext->override);
166		}
167
168		if (threadContext->bios && GBAIsBIOS(threadContext->bios)) {
169			GBALoadBIOS(&gba, threadContext->bios);
170		}
171
172		if (threadContext->patch && loadPatch(threadContext->patch, &patch)) {
173			GBAApplyPatch(&gba, &patch);
174		}
175	}
176
177	if (threadContext->movie) {
178		struct VDir* movieDir = VDirOpen(threadContext->movie);
179#ifdef ENABLE_LIBZIP
180		if (!movieDir) {
181			movieDir = VDirOpenZip(threadContext->movie, 0);
182		}
183#endif
184		if (movieDir) {
185			struct GBAMGMContext* mgm = malloc(sizeof(*mgm));
186			GBAMGMContextCreate(mgm);
187			if (!GBAMGMSetStream(mgm, movieDir)) {
188				mgm->d.destroy(&mgm->d);
189			} else {
190				movie = &mgm->d;
191			}
192		} else {
193			struct VFile* movieFile = VFileOpen(threadContext->movie, O_RDONLY);
194			if (movieFile) {
195				struct GBAVBMContext* vbm = malloc(sizeof(*vbm));
196				GBAVBMContextCreate(vbm);
197				if (!GBAVBMSetStream(vbm, movieFile)) {
198					vbm->d.destroy(&vbm->d);
199				} else {
200					movie = &vbm->d;
201				}
202			}
203		}
204	}
205
206	ARMReset(&cpu);
207
208	if (movie) {
209		gba.rr = movie;
210		movie->startPlaying(movie, false);
211		GBARRInitPlay(&gba);
212	}
213
214	if (threadContext->skipBios) {
215		GBASkipBIOS(&cpu);
216	}
217
218	if (!threadContext->cheats) {
219		GBACheatDeviceCreate(&cheatDevice);
220		threadContext->cheats = &cheatDevice;
221	}
222	if (threadContext->cheatsFile) {
223		GBACheatParseFile(threadContext->cheats, threadContext->cheatsFile);
224	}
225	GBACheatAttachDevice(&gba, threadContext->cheats);
226
227	if (threadContext->debugger) {
228		threadContext->debugger->log = GBADebuggerLogShim;
229		GBAAttachDebugger(&gba, threadContext->debugger);
230		ARMDebuggerEnter(threadContext->debugger, DEBUGGER_ENTER_ATTACHED, 0);
231	}
232
233	GBASIOSetDriverSet(&gba.sio, &threadContext->sioDrivers);
234
235	gba.keySource = &threadContext->activeKeys;
236
237	if (threadContext->startCallback) {
238		threadContext->startCallback(threadContext);
239	}
240
241	_changeState(threadContext, THREAD_RUNNING, true);
242
243	while (threadContext->state < THREAD_EXITING) {
244		if (threadContext->debugger) {
245			struct ARMDebugger* debugger = threadContext->debugger;
246			ARMDebuggerRun(debugger);
247			if (debugger->state == DEBUGGER_SHUTDOWN) {
248				_changeState(threadContext, THREAD_EXITING, false);
249			}
250		} else {
251			while (threadContext->state == THREAD_RUNNING) {
252				ARMRunLoop(&cpu);
253			}
254		}
255
256		int resetScheduled = 0;
257		MutexLock(&threadContext->stateMutex);
258		while (threadContext->state > THREAD_RUNNING && threadContext->state < THREAD_EXITING) {
259			if (threadContext->state == THREAD_PAUSING) {
260				threadContext->state = THREAD_PAUSED;
261				ConditionWake(&threadContext->stateCond);
262			}
263			if (threadContext->state == THREAD_INTERRUPTING) {
264				threadContext->state = THREAD_INTERRUPTED;
265				ConditionWake(&threadContext->stateCond);
266			}
267			if (threadContext->state == THREAD_RESETING) {
268				threadContext->state = THREAD_RUNNING;
269				resetScheduled = 1;
270			}
271			while (threadContext->state == THREAD_PAUSED || threadContext->state == THREAD_INTERRUPTED) {
272				ConditionWait(&threadContext->stateCond, &threadContext->stateMutex);
273			}
274		}
275		MutexUnlock(&threadContext->stateMutex);
276		if (resetScheduled) {
277			ARMReset(&cpu);
278			if (threadContext->skipBios) {
279				GBASkipBIOS(&cpu);
280			}
281		}
282	}
283
284	while (threadContext->state < THREAD_SHUTDOWN) {
285		_changeState(threadContext, THREAD_SHUTDOWN, false);
286	}
287
288	if (threadContext->cleanCallback) {
289		threadContext->cleanCallback(threadContext);
290	}
291
292	threadContext->gba = 0;
293	ARMDeinit(&cpu);
294	GBADestroy(&gba);
295	if (&cheatDevice == threadContext->cheats) {
296		GBACheatDeviceDestroy(&cheatDevice);
297	}
298
299	if (movie) {
300		movie->destroy(movie);
301		free(movie);
302	}
303
304	threadContext->sync.videoFrameOn = false;
305	ConditionWake(&threadContext->sync.videoFrameAvailableCond);
306	ConditionWake(&threadContext->sync.audioRequiredCond);
307
308	return 0;
309}
310
311void GBAMapOptionsToContext(const struct GBAOptions* opts, struct GBAThread* threadContext) {
312	threadContext->bios = VFileOpen(opts->bios, O_RDONLY);
313	threadContext->frameskip = opts->frameskip;
314	threadContext->logLevel = opts->logLevel;
315	if (opts->rewindEnable) {
316		threadContext->rewindBufferCapacity = opts->rewindBufferCapacity;
317		threadContext->rewindBufferInterval = opts->rewindBufferInterval;
318	} else {
319		threadContext->rewindBufferCapacity = 0;
320	}
321	threadContext->skipBios = opts->skipBios;
322	threadContext->sync.audioWait = opts->audioSync;
323	threadContext->sync.videoFrameWait = opts->videoSync;
324
325	if (opts->fpsTarget) {
326		threadContext->fpsTarget = opts->fpsTarget;
327	}
328
329	if (opts->audioBuffers) {
330		threadContext->audioBuffers = opts->audioBuffers;
331	}
332
333	threadContext->idleOptimization = opts->idleOptimization;
334}
335
336void GBAMapArgumentsToContext(const struct GBAArguments* args, struct GBAThread* threadContext) {
337	if (args->dirmode) {
338		threadContext->gameDir = VDirOpen(args->fname);
339		threadContext->stateDir = threadContext->gameDir;
340	} else {
341		threadContext->rom = VFileOpen(args->fname, O_RDONLY);
342		threadContext->gameDir = 0;
343#if ENABLE_LIBZIP
344		if (!threadContext->gameDir) {
345			threadContext->gameDir = VDirOpenZip(args->fname, 0);
346		}
347#endif
348#if ENABLE_LZMA
349		if (!threadContext->gameDir) {
350			threadContext->gameDir = VDirOpen7z(args->fname, 0);
351		}
352#endif
353	}
354	threadContext->fname = args->fname;
355	threadContext->patch = VFileOpen(args->patch, O_RDONLY);
356	threadContext->cheatsFile = VFileOpen(args->cheatsFile, O_RDONLY);
357	threadContext->movie = args->movie;
358}
359
360bool GBAThreadStart(struct GBAThread* threadContext) {
361	// TODO: error check
362	threadContext->activeKeys = 0;
363	threadContext->state = THREAD_INITIALIZED;
364	threadContext->sync.videoFrameOn = true;
365	threadContext->sync.videoFrameSkip = 0;
366
367	threadContext->rewindBuffer = 0;
368	int newCapacity = threadContext->rewindBufferCapacity;
369	int newInterval = threadContext->rewindBufferInterval;
370	threadContext->rewindBufferCapacity = 0;
371	threadContext->rewindBufferInterval = 0;
372	GBARewindSettingsChanged(threadContext, newCapacity, newInterval);
373
374	if (!threadContext->fpsTarget) {
375		threadContext->fpsTarget = _defaultFPSTarget;
376	}
377
378	if (threadContext->rom && !GBAIsROM(threadContext->rom)) {
379		threadContext->rom->close(threadContext->rom);
380		threadContext->rom = 0;
381	}
382
383	if (threadContext->gameDir) {
384		threadContext->gameDir->rewind(threadContext->gameDir);
385		struct VDirEntry* dirent = threadContext->gameDir->listNext(threadContext->gameDir);
386		while (dirent) {
387			struct Patch patchTemp;
388			struct VFile* vf = threadContext->gameDir->openFile(threadContext->gameDir, dirent->name(dirent), O_RDONLY);
389			if (!vf) {
390				dirent = threadContext->gameDir->listNext(threadContext->gameDir);
391				continue;
392			}
393			if (!threadContext->rom && GBAIsROM(vf)) {
394				threadContext->rom = vf;
395			} else if (!threadContext->patch && loadPatch(vf, &patchTemp)) {
396				threadContext->patch = vf;
397			} else {
398				vf->close(vf);
399			}
400			dirent = threadContext->gameDir->listNext(threadContext->gameDir);
401		}
402
403	}
404
405	if (!threadContext->rom) {
406		threadContext->state = THREAD_SHUTDOWN;
407		return false;
408	}
409
410	threadContext->save = VDirOptionalOpenFile(threadContext->stateDir, threadContext->fname, "sram", ".sav", O_CREAT | O_RDWR);
411
412	MutexInit(&threadContext->stateMutex);
413	ConditionInit(&threadContext->stateCond);
414
415	MutexInit(&threadContext->sync.videoFrameMutex);
416	ConditionInit(&threadContext->sync.videoFrameAvailableCond);
417	ConditionInit(&threadContext->sync.videoFrameRequiredCond);
418	MutexInit(&threadContext->sync.audioBufferMutex);
419	ConditionInit(&threadContext->sync.audioRequiredCond);
420
421	threadContext->interruptDepth = 0;
422
423#ifndef _WIN32
424	sigset_t signals;
425	sigemptyset(&signals);
426	sigaddset(&signals, SIGINT);
427	sigaddset(&signals, SIGTRAP);
428	pthread_sigmask(SIG_BLOCK, &signals, 0);
429#endif
430
431	MutexLock(&threadContext->stateMutex);
432	ThreadCreate(&threadContext->thread, _GBAThreadRun, threadContext);
433	while (threadContext->state < THREAD_RUNNING) {
434		ConditionWait(&threadContext->stateCond, &threadContext->stateMutex);
435	}
436	MutexUnlock(&threadContext->stateMutex);
437
438	return true;
439}
440
441bool GBAThreadHasStarted(struct GBAThread* threadContext) {
442	bool hasStarted;
443	MutexLock(&threadContext->stateMutex);
444	hasStarted = threadContext->state > THREAD_INITIALIZED;
445	MutexUnlock(&threadContext->stateMutex);
446	return hasStarted;
447}
448
449bool GBAThreadHasExited(struct GBAThread* threadContext) {
450	bool hasExited;
451	MutexLock(&threadContext->stateMutex);
452	hasExited = threadContext->state > THREAD_EXITING;
453	MutexUnlock(&threadContext->stateMutex);
454	return hasExited;
455}
456
457bool GBAThreadHasCrashed(struct GBAThread* threadContext) {
458	bool hasExited;
459	MutexLock(&threadContext->stateMutex);
460	hasExited = threadContext->state == THREAD_CRASHED;
461	MutexUnlock(&threadContext->stateMutex);
462	return hasExited;
463}
464
465void GBAThreadEnd(struct GBAThread* threadContext) {
466	MutexLock(&threadContext->stateMutex);
467	_waitOnInterrupt(threadContext);
468	threadContext->state = THREAD_EXITING;
469	if (threadContext->gba) {
470		threadContext->gba->cpu->halted = false;
471	}
472	ConditionWake(&threadContext->stateCond);
473	MutexUnlock(&threadContext->stateMutex);
474	MutexLock(&threadContext->sync.audioBufferMutex);
475	threadContext->sync.audioWait = 0;
476	ConditionWake(&threadContext->sync.audioRequiredCond);
477	MutexUnlock(&threadContext->sync.audioBufferMutex);
478
479	MutexLock(&threadContext->sync.videoFrameMutex);
480	threadContext->sync.videoFrameWait = false;
481	threadContext->sync.videoFrameOn = false;
482	ConditionWake(&threadContext->sync.videoFrameRequiredCond);
483	ConditionWake(&threadContext->sync.videoFrameAvailableCond);
484	MutexUnlock(&threadContext->sync.videoFrameMutex);
485}
486
487void GBAThreadReset(struct GBAThread* threadContext) {
488	MutexLock(&threadContext->stateMutex);
489	_waitOnInterrupt(threadContext);
490	threadContext->state = THREAD_RESETING;
491	ConditionWake(&threadContext->stateCond);
492	MutexUnlock(&threadContext->stateMutex);
493}
494
495void GBAThreadJoin(struct GBAThread* threadContext) {
496	ThreadJoin(threadContext->thread);
497
498	MutexDeinit(&threadContext->stateMutex);
499	ConditionDeinit(&threadContext->stateCond);
500
501	MutexDeinit(&threadContext->sync.videoFrameMutex);
502	ConditionWake(&threadContext->sync.videoFrameAvailableCond);
503	ConditionDeinit(&threadContext->sync.videoFrameAvailableCond);
504	ConditionWake(&threadContext->sync.videoFrameRequiredCond);
505	ConditionDeinit(&threadContext->sync.videoFrameRequiredCond);
506
507	ConditionWake(&threadContext->sync.audioRequiredCond);
508	ConditionDeinit(&threadContext->sync.audioRequiredCond);
509	MutexDeinit(&threadContext->sync.audioBufferMutex);
510
511	int i;
512	for (i = 0; i < threadContext->rewindBufferCapacity; ++i) {
513		if (threadContext->rewindBuffer[i]) {
514			GBADeallocateState(threadContext->rewindBuffer[i]);
515		}
516	}
517	free(threadContext->rewindBuffer);
518
519	if (threadContext->rom) {
520		threadContext->rom->close(threadContext->rom);
521		threadContext->rom = 0;
522	}
523
524	if (threadContext->save) {
525		threadContext->save->close(threadContext->save);
526		threadContext->save = 0;
527	}
528
529	if (threadContext->bios) {
530		threadContext->bios->close(threadContext->bios);
531		threadContext->bios = 0;
532	}
533
534	if (threadContext->patch) {
535		threadContext->patch->close(threadContext->patch);
536		threadContext->patch = 0;
537	}
538
539	if (threadContext->gameDir) {
540		if (threadContext->stateDir == threadContext->gameDir) {
541			threadContext->stateDir = 0;
542		}
543		threadContext->gameDir->close(threadContext->gameDir);
544		threadContext->gameDir = 0;
545	}
546
547	if (threadContext->stateDir) {
548		threadContext->stateDir->close(threadContext->stateDir);
549		threadContext->stateDir = 0;
550	}
551}
552
553bool GBAThreadIsActive(struct GBAThread* threadContext) {
554	return threadContext->state >= THREAD_RUNNING && threadContext->state < THREAD_EXITING;
555}
556
557void GBAThreadInterrupt(struct GBAThread* threadContext) {
558	MutexLock(&threadContext->stateMutex);
559	++threadContext->interruptDepth;
560	if (threadContext->interruptDepth > 1 || !GBAThreadIsActive(threadContext)) {
561		MutexUnlock(&threadContext->stateMutex);
562		return;
563	}
564	threadContext->savedState = threadContext->state;
565	_waitOnInterrupt(threadContext);
566	threadContext->state = THREAD_INTERRUPTING;
567	threadContext->gba->cpu->nextEvent = 0;
568	ConditionWake(&threadContext->stateCond);
569	_waitUntilNotState(threadContext, THREAD_INTERRUPTING);
570	MutexUnlock(&threadContext->stateMutex);
571}
572
573void GBAThreadContinue(struct GBAThread* threadContext) {
574	MutexLock(&threadContext->stateMutex);
575	--threadContext->interruptDepth;
576	if (threadContext->interruptDepth < 1 && GBAThreadIsActive(threadContext)) {
577		threadContext->state = threadContext->savedState;
578		ConditionWake(&threadContext->stateCond);
579	}
580	MutexUnlock(&threadContext->stateMutex);
581}
582
583void GBAThreadPause(struct GBAThread* threadContext) {
584	bool frameOn = true;
585	MutexLock(&threadContext->stateMutex);
586	_waitOnInterrupt(threadContext);
587	if (threadContext->state == THREAD_RUNNING) {
588		_pauseThread(threadContext, false);
589		frameOn = false;
590	}
591	MutexUnlock(&threadContext->stateMutex);
592
593	_changeVideoSync(&threadContext->sync, frameOn);
594}
595
596void GBAThreadUnpause(struct GBAThread* threadContext) {
597	MutexLock(&threadContext->stateMutex);
598	_waitOnInterrupt(threadContext);
599	if (threadContext->state == THREAD_PAUSED || threadContext->state == THREAD_PAUSING) {
600		threadContext->state = THREAD_RUNNING;
601		ConditionWake(&threadContext->stateCond);
602	}
603	MutexUnlock(&threadContext->stateMutex);
604
605	_changeVideoSync(&threadContext->sync, true);
606}
607
608bool GBAThreadIsPaused(struct GBAThread* threadContext) {
609	bool isPaused;
610	MutexLock(&threadContext->stateMutex);
611	_waitOnInterrupt(threadContext);
612	isPaused = threadContext->state == THREAD_PAUSED;
613	MutexUnlock(&threadContext->stateMutex);
614	return isPaused;
615}
616
617void GBAThreadTogglePause(struct GBAThread* threadContext) {
618	bool frameOn = true;
619	MutexLock(&threadContext->stateMutex);
620	_waitOnInterrupt(threadContext);
621	if (threadContext->state == THREAD_PAUSED || threadContext->state == THREAD_PAUSING) {
622		threadContext->state = THREAD_RUNNING;
623		ConditionWake(&threadContext->stateCond);
624	} else if (threadContext->state == THREAD_RUNNING) {
625		_pauseThread(threadContext, false);
626		frameOn = false;
627	}
628	MutexUnlock(&threadContext->stateMutex);
629
630	_changeVideoSync(&threadContext->sync, frameOn);
631}
632
633void GBAThreadPauseFromThread(struct GBAThread* threadContext) {
634	bool frameOn = true;
635	MutexLock(&threadContext->stateMutex);
636	_waitOnInterrupt(threadContext);
637	if (threadContext->state == THREAD_RUNNING) {
638		_pauseThread(threadContext, true);
639		frameOn = false;
640	}
641	MutexUnlock(&threadContext->stateMutex);
642
643	_changeVideoSync(&threadContext->sync, frameOn);
644}
645
646#ifdef USE_PTHREADS
647struct GBAThread* GBAThreadGetContext(void) {
648	pthread_once(&_contextOnce, _createTLS);
649	return pthread_getspecific(_contextKey);
650}
651#elif _WIN32
652struct GBAThread* GBAThreadGetContext(void) {
653	InitOnceExecuteOnce(&_contextOnce, _createTLS, NULL, 0);
654	return TlsGetValue(_contextKey);
655}
656#endif
657
658#ifdef USE_PNG
659void GBAThreadTakeScreenshot(struct GBAThread* threadContext) {
660	unsigned stride;
661	void* pixels = 0;
662	struct VFile* vf = VDirOptionalOpenIncrementFile(threadContext->stateDir, threadContext->gba->activeFile, "screenshot", "-", ".png", O_CREAT | O_TRUNC | O_WRONLY);
663	threadContext->gba->video.renderer->getPixels(threadContext->gba->video.renderer, &stride, &pixels);
664	png_structp png = PNGWriteOpen(vf);
665	png_infop info = PNGWriteHeader(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
666	PNGWritePixels(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, stride, pixels);
667	PNGWriteClose(png, info);
668	vf->close(vf);
669}
670#endif
671
672#else
673struct GBAThread* GBAThreadGetContext(void) {
674	return 0;
675}
676#endif
677
678void GBASyncPostFrame(struct GBASync* sync) {
679	if (!sync) {
680		return;
681	}
682
683	MutexLock(&sync->videoFrameMutex);
684	++sync->videoFramePending;
685	--sync->videoFrameSkip;
686	if (sync->videoFrameSkip < 0) {
687		do {
688			ConditionWake(&sync->videoFrameAvailableCond);
689			if (sync->videoFrameWait) {
690				ConditionWait(&sync->videoFrameRequiredCond, &sync->videoFrameMutex);
691			}
692		} while (sync->videoFrameWait && sync->videoFramePending);
693	}
694	MutexUnlock(&sync->videoFrameMutex);
695}
696
697bool GBASyncWaitFrameStart(struct GBASync* sync, int frameskip) {
698	if (!sync) {
699		return true;
700	}
701
702	MutexLock(&sync->videoFrameMutex);
703	ConditionWake(&sync->videoFrameRequiredCond);
704	if (!sync->videoFrameOn && !sync->videoFramePending) {
705		return false;
706	}
707	if (sync->videoFrameOn) {
708		if (ConditionWaitTimed(&sync->videoFrameAvailableCond, &sync->videoFrameMutex, 50)) {
709			return false;
710		}
711	}
712	sync->videoFramePending = 0;
713	sync->videoFrameSkip = frameskip;
714	return true;
715}
716
717void GBASyncWaitFrameEnd(struct GBASync* sync) {
718	if (!sync) {
719		return;
720	}
721
722	MutexUnlock(&sync->videoFrameMutex);
723}
724
725bool GBASyncDrawingFrame(struct GBASync* sync) {
726	if (!sync) {
727		return true;
728	}
729
730	return sync->videoFrameSkip <= 0;
731}
732
733void GBASyncSuspendDrawing(struct GBASync* sync) {
734	if (!sync) {
735		return;
736	}
737
738	_changeVideoSync(sync, false);
739}
740
741void GBASyncResumeDrawing(struct GBASync* sync) {
742	if (!sync) {
743		return;
744	}
745
746	_changeVideoSync(sync, true);
747}
748
749void GBASyncProduceAudio(struct GBASync* sync, bool wait) {
750	if (!sync) {
751		return;
752	}
753
754	if (sync->audioWait && wait) {
755		// TODO loop properly in event of spurious wakeups
756		ConditionWait(&sync->audioRequiredCond, &sync->audioBufferMutex);
757	}
758	MutexUnlock(&sync->audioBufferMutex);
759}
760
761void GBASyncLockAudio(struct GBASync* sync) {
762	if (!sync) {
763		return;
764	}
765
766	MutexLock(&sync->audioBufferMutex);
767}
768
769void GBASyncUnlockAudio(struct GBASync* sync) {
770	if (!sync) {
771		return;
772	}
773
774	MutexUnlock(&sync->audioBufferMutex);
775}
776
777void GBASyncConsumeAudio(struct GBASync* sync) {
778	if (!sync) {
779		return;
780	}
781
782	ConditionWake(&sync->audioRequiredCond);
783	MutexUnlock(&sync->audioBufferMutex);
784}