all repos — mgba @ bdc72bb73b1988de6d96132f40e887918d75d539

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	threadContext->cpu = &cpu;
137	gba.logLevel = threadContext->logLevel;
138	gba.logHandler = threadContext->logHandler;
139	gba.stream = threadContext->stream;
140	gba.idleOptimization = threadContext->idleOptimization;
141#ifdef USE_PTHREADS
142	pthread_setspecific(_contextKey, threadContext);
143#else
144	TlsSetValue(_contextKey, threadContext);
145#endif
146
147	if (threadContext->audioBuffers) {
148		GBAAudioResizeBuffer(&gba.audio, threadContext->audioBuffers);
149	} else {
150		threadContext->audioBuffers = GBA_AUDIO_SAMPLES;
151	}
152
153	if (threadContext->renderer) {
154		GBAVideoAssociateRenderer(&gba.video, threadContext->renderer);
155	}
156
157	if (threadContext->rom) {
158		GBALoadROM(&gba, threadContext->rom, threadContext->save, threadContext->fname);
159
160		struct GBACartridgeOverride override;
161		const struct GBACartridge* cart = (const struct GBACartridge*) gba.memory.rom;
162		memcpy(override.id, &cart->id, sizeof(override.id));
163		if (GBAOverrideFind(threadContext->overrides, &override)) {
164			GBAOverrideApply(&gba, &override);
165		}
166		if (threadContext->hasOverride) {
167			GBAOverrideApply(&gba, &threadContext->override);
168		}
169
170		if (threadContext->bios && GBAIsBIOS(threadContext->bios)) {
171			GBALoadBIOS(&gba, threadContext->bios);
172		}
173
174		if (threadContext->patch && loadPatch(threadContext->patch, &patch)) {
175			GBAApplyPatch(&gba, &patch);
176		}
177	}
178
179	if (threadContext->movie) {
180		struct VDir* movieDir = VDirOpen(threadContext->movie);
181#ifdef USE_LIBZIP
182		if (!movieDir) {
183			movieDir = VDirOpenZip(threadContext->movie, 0);
184		}
185#endif
186		if (movieDir) {
187			struct GBAMGMContext* mgm = malloc(sizeof(*mgm));
188			GBAMGMContextCreate(mgm);
189			if (!GBAMGMSetStream(mgm, movieDir)) {
190				mgm->d.destroy(&mgm->d);
191			} else {
192				movie = &mgm->d;
193			}
194		} else {
195			struct VFile* movieFile = VFileOpen(threadContext->movie, O_RDONLY);
196			if (movieFile) {
197				struct GBAVBMContext* vbm = malloc(sizeof(*vbm));
198				GBAVBMContextCreate(vbm);
199				if (!GBAVBMSetStream(vbm, movieFile)) {
200					vbm->d.destroy(&vbm->d);
201				} else {
202					movie = &vbm->d;
203				}
204			}
205		}
206	}
207
208	ARMReset(&cpu);
209
210	if (movie) {
211		gba.rr = movie;
212		movie->startPlaying(movie, false);
213		GBARRInitPlay(&gba);
214	}
215
216	if (threadContext->skipBios) {
217		GBASkipBIOS(&cpu);
218	}
219
220	if (!threadContext->cheats) {
221		GBACheatDeviceCreate(&cheatDevice);
222		threadContext->cheats = &cheatDevice;
223	}
224	if (threadContext->cheatsFile) {
225		GBACheatParseFile(threadContext->cheats, threadContext->cheatsFile);
226	}
227	GBACheatAttachDevice(&gba, threadContext->cheats);
228
229	if (threadContext->debugger) {
230		threadContext->debugger->log = GBADebuggerLogShim;
231		GBAAttachDebugger(&gba, threadContext->debugger);
232		ARMDebuggerEnter(threadContext->debugger, DEBUGGER_ENTER_ATTACHED, 0);
233	}
234
235	GBASIOSetDriverSet(&gba.sio, &threadContext->sioDrivers);
236
237	if (threadContext->volume == 0) {
238		threadContext->volume = GBA_AUDIO_VOLUME_MAX;
239	}
240	if (threadContext->mute) {
241		gba.audio.masterVolume = 0;
242	} else {
243		gba.audio.masterVolume = threadContext->volume;
244	}
245
246	gba.keySource = &threadContext->activeKeys;
247
248	if (threadContext->startCallback) {
249		threadContext->startCallback(threadContext);
250	}
251
252	_changeState(threadContext, THREAD_RUNNING, true);
253
254	while (threadContext->state < THREAD_EXITING) {
255		if (threadContext->debugger) {
256			struct ARMDebugger* debugger = threadContext->debugger;
257			ARMDebuggerRun(debugger);
258			if (debugger->state == DEBUGGER_SHUTDOWN) {
259				_changeState(threadContext, THREAD_EXITING, false);
260			}
261		} else {
262			while (threadContext->state == THREAD_RUNNING) {
263				ARMRunLoop(&cpu);
264			}
265		}
266
267		int resetScheduled = 0;
268		MutexLock(&threadContext->stateMutex);
269		while (threadContext->state > THREAD_RUNNING && threadContext->state < THREAD_EXITING) {
270			if (threadContext->state == THREAD_PAUSING) {
271				threadContext->state = THREAD_PAUSED;
272				ConditionWake(&threadContext->stateCond);
273			}
274			if (threadContext->state == THREAD_INTERRUPTING) {
275				threadContext->state = THREAD_INTERRUPTED;
276				ConditionWake(&threadContext->stateCond);
277			}
278			if (threadContext->state == THREAD_RUN_ON) {
279				if (threadContext->run) {
280					threadContext->run(threadContext);
281				}
282				threadContext->state = THREAD_RUNNING;
283				ConditionWake(&threadContext->stateCond);
284			}
285			if (threadContext->state == THREAD_RESETING) {
286				threadContext->state = THREAD_RUNNING;
287				resetScheduled = 1;
288			}
289			while (threadContext->state == THREAD_PAUSED || threadContext->state == THREAD_INTERRUPTED) {
290				ConditionWait(&threadContext->stateCond, &threadContext->stateMutex);
291			}
292		}
293		MutexUnlock(&threadContext->stateMutex);
294		if (resetScheduled) {
295			ARMReset(&cpu);
296			if (threadContext->skipBios) {
297				GBASkipBIOS(&cpu);
298			}
299		}
300	}
301
302	while (threadContext->state < THREAD_SHUTDOWN) {
303		_changeState(threadContext, THREAD_SHUTDOWN, false);
304	}
305
306	if (threadContext->cleanCallback) {
307		threadContext->cleanCallback(threadContext);
308	}
309
310	threadContext->gba = 0;
311	ARMDeinit(&cpu);
312	GBADestroy(&gba);
313	if (&cheatDevice == threadContext->cheats) {
314		GBACheatDeviceDestroy(&cheatDevice);
315	}
316
317	if (movie) {
318		movie->destroy(movie);
319		free(movie);
320	}
321
322	threadContext->sync.videoFrameOn = false;
323	ConditionWake(&threadContext->sync.videoFrameAvailableCond);
324	ConditionWake(&threadContext->sync.audioRequiredCond);
325
326	return 0;
327}
328
329void GBAMapOptionsToContext(const struct GBAOptions* opts, struct GBAThread* threadContext) {
330	if (opts->useBios) {
331		threadContext->bios = VFileOpen(opts->bios, O_RDONLY);
332	} else {
333		threadContext->bios = 0;
334	}
335	threadContext->frameskip = opts->frameskip;
336	threadContext->volume = opts->volume;
337	threadContext->mute = opts->mute;
338	threadContext->logLevel = opts->logLevel;
339	if (opts->rewindEnable) {
340		threadContext->rewindBufferCapacity = opts->rewindBufferCapacity;
341		threadContext->rewindBufferInterval = opts->rewindBufferInterval;
342	} else {
343		threadContext->rewindBufferCapacity = 0;
344	}
345	threadContext->skipBios = opts->skipBios;
346	threadContext->sync.audioWait = opts->audioSync;
347	threadContext->sync.videoFrameWait = opts->videoSync;
348
349	if (opts->fpsTarget) {
350		threadContext->fpsTarget = opts->fpsTarget;
351	}
352
353	if (opts->audioBuffers) {
354		threadContext->audioBuffers = opts->audioBuffers;
355	}
356
357	threadContext->idleOptimization = opts->idleOptimization;
358}
359
360void GBAMapArgumentsToContext(const struct GBAArguments* args, struct GBAThread* threadContext) {
361	if (args->dirmode) {
362		threadContext->gameDir = VDirOpen(args->fname);
363		threadContext->stateDir = threadContext->gameDir;
364	} else {
365		threadContext->rom = VFileOpen(args->fname, O_RDONLY);
366		threadContext->gameDir = 0;
367#if USE_LIBZIP
368		if (!threadContext->gameDir) {
369			threadContext->gameDir = VDirOpenZip(args->fname, 0);
370		}
371#endif
372#if USE_LZMA
373		if (!threadContext->gameDir) {
374			threadContext->gameDir = VDirOpen7z(args->fname, 0);
375		}
376#endif
377	}
378	threadContext->fname = args->fname;
379	threadContext->patch = VFileOpen(args->patch, O_RDONLY);
380	threadContext->cheatsFile = VFileOpen(args->cheatsFile, O_RDONLY);
381	threadContext->movie = args->movie;
382}
383
384bool GBAThreadStart(struct GBAThread* threadContext) {
385	// TODO: error check
386	threadContext->activeKeys = 0;
387	threadContext->state = THREAD_INITIALIZED;
388	threadContext->sync.videoFrameOn = true;
389	threadContext->sync.videoFrameSkip = 0;
390
391	threadContext->rewindBuffer = 0;
392	threadContext->rewindScreenBuffer = 0;
393	int newCapacity = threadContext->rewindBufferCapacity;
394	int newInterval = threadContext->rewindBufferInterval;
395	threadContext->rewindBufferCapacity = 0;
396	threadContext->rewindBufferInterval = 0;
397	GBARewindSettingsChanged(threadContext, newCapacity, newInterval);
398
399	if (!threadContext->fpsTarget) {
400		threadContext->fpsTarget = _defaultFPSTarget;
401	}
402
403	if (threadContext->rom && !GBAIsROM(threadContext->rom)) {
404		threadContext->rom->close(threadContext->rom);
405		threadContext->rom = 0;
406	}
407
408	if (threadContext->gameDir) {
409		threadContext->gameDir->rewind(threadContext->gameDir);
410		struct VDirEntry* dirent = threadContext->gameDir->listNext(threadContext->gameDir);
411		while (dirent) {
412			struct Patch patchTemp;
413			struct VFile* vf = threadContext->gameDir->openFile(threadContext->gameDir, dirent->name(dirent), O_RDONLY);
414			if (!vf) {
415				dirent = threadContext->gameDir->listNext(threadContext->gameDir);
416				continue;
417			}
418			if (!threadContext->rom && GBAIsROM(vf)) {
419				threadContext->rom = vf;
420			} else if (!threadContext->patch && loadPatch(vf, &patchTemp)) {
421				threadContext->patch = vf;
422			} else {
423				vf->close(vf);
424			}
425			dirent = threadContext->gameDir->listNext(threadContext->gameDir);
426		}
427
428	}
429
430	if (!threadContext->rom) {
431		threadContext->state = THREAD_SHUTDOWN;
432		return false;
433	}
434
435	threadContext->save = VDirOptionalOpenFile(threadContext->stateDir, threadContext->fname, "sram", ".sav", O_CREAT | O_RDWR);
436
437	MutexInit(&threadContext->stateMutex);
438	ConditionInit(&threadContext->stateCond);
439
440	MutexInit(&threadContext->sync.videoFrameMutex);
441	ConditionInit(&threadContext->sync.videoFrameAvailableCond);
442	ConditionInit(&threadContext->sync.videoFrameRequiredCond);
443	MutexInit(&threadContext->sync.audioBufferMutex);
444	ConditionInit(&threadContext->sync.audioRequiredCond);
445
446	threadContext->interruptDepth = 0;
447
448#ifndef _WIN32
449	sigset_t signals;
450	sigemptyset(&signals);
451	sigaddset(&signals, SIGINT);
452	sigaddset(&signals, SIGTRAP);
453	pthread_sigmask(SIG_BLOCK, &signals, 0);
454#endif
455
456	MutexLock(&threadContext->stateMutex);
457	ThreadCreate(&threadContext->thread, _GBAThreadRun, threadContext);
458	while (threadContext->state < THREAD_RUNNING) {
459		ConditionWait(&threadContext->stateCond, &threadContext->stateMutex);
460	}
461	MutexUnlock(&threadContext->stateMutex);
462
463	return true;
464}
465
466bool GBAThreadHasStarted(struct GBAThread* threadContext) {
467	bool hasStarted;
468	MutexLock(&threadContext->stateMutex);
469	hasStarted = threadContext->state > THREAD_INITIALIZED;
470	MutexUnlock(&threadContext->stateMutex);
471	return hasStarted;
472}
473
474bool GBAThreadHasExited(struct GBAThread* threadContext) {
475	bool hasExited;
476	MutexLock(&threadContext->stateMutex);
477	hasExited = threadContext->state > THREAD_EXITING;
478	MutexUnlock(&threadContext->stateMutex);
479	return hasExited;
480}
481
482bool GBAThreadHasCrashed(struct GBAThread* threadContext) {
483	bool hasExited;
484	MutexLock(&threadContext->stateMutex);
485	hasExited = threadContext->state == THREAD_CRASHED;
486	MutexUnlock(&threadContext->stateMutex);
487	return hasExited;
488}
489
490void GBAThreadEnd(struct GBAThread* threadContext) {
491	MutexLock(&threadContext->stateMutex);
492	_waitOnInterrupt(threadContext);
493	threadContext->state = THREAD_EXITING;
494	if (threadContext->gba) {
495		threadContext->gba->cpu->halted = false;
496	}
497	ConditionWake(&threadContext->stateCond);
498	MutexUnlock(&threadContext->stateMutex);
499	MutexLock(&threadContext->sync.audioBufferMutex);
500	threadContext->sync.audioWait = 0;
501	ConditionWake(&threadContext->sync.audioRequiredCond);
502	MutexUnlock(&threadContext->sync.audioBufferMutex);
503
504	MutexLock(&threadContext->sync.videoFrameMutex);
505	threadContext->sync.videoFrameWait = false;
506	threadContext->sync.videoFrameOn = false;
507	ConditionWake(&threadContext->sync.videoFrameRequiredCond);
508	ConditionWake(&threadContext->sync.videoFrameAvailableCond);
509	MutexUnlock(&threadContext->sync.videoFrameMutex);
510}
511
512void GBAThreadReset(struct GBAThread* threadContext) {
513	MutexLock(&threadContext->stateMutex);
514	_waitOnInterrupt(threadContext);
515	threadContext->state = THREAD_RESETING;
516	ConditionWake(&threadContext->stateCond);
517	MutexUnlock(&threadContext->stateMutex);
518}
519
520void GBAThreadJoin(struct GBAThread* threadContext) {
521	ThreadJoin(threadContext->thread);
522
523	MutexDeinit(&threadContext->stateMutex);
524	ConditionDeinit(&threadContext->stateCond);
525
526	MutexDeinit(&threadContext->sync.videoFrameMutex);
527	ConditionWake(&threadContext->sync.videoFrameAvailableCond);
528	ConditionDeinit(&threadContext->sync.videoFrameAvailableCond);
529	ConditionWake(&threadContext->sync.videoFrameRequiredCond);
530	ConditionDeinit(&threadContext->sync.videoFrameRequiredCond);
531
532	ConditionWake(&threadContext->sync.audioRequiredCond);
533	ConditionDeinit(&threadContext->sync.audioRequiredCond);
534	MutexDeinit(&threadContext->sync.audioBufferMutex);
535
536	int i;
537	for (i = 0; i < threadContext->rewindBufferCapacity; ++i) {
538		if (threadContext->rewindBuffer[i]) {
539			GBADeallocateState(threadContext->rewindBuffer[i]);
540		}
541	}
542	free(threadContext->rewindBuffer);
543	free(threadContext->rewindScreenBuffer);
544
545	if (threadContext->rom) {
546		threadContext->rom->close(threadContext->rom);
547		threadContext->rom = 0;
548	}
549
550	if (threadContext->save) {
551		threadContext->save->close(threadContext->save);
552		threadContext->save = 0;
553	}
554
555	if (threadContext->bios) {
556		threadContext->bios->close(threadContext->bios);
557		threadContext->bios = 0;
558	}
559
560	if (threadContext->patch) {
561		threadContext->patch->close(threadContext->patch);
562		threadContext->patch = 0;
563	}
564
565	if (threadContext->gameDir) {
566		if (threadContext->stateDir == threadContext->gameDir) {
567			threadContext->stateDir = 0;
568		}
569		threadContext->gameDir->close(threadContext->gameDir);
570		threadContext->gameDir = 0;
571	}
572
573	if (threadContext->stateDir) {
574		threadContext->stateDir->close(threadContext->stateDir);
575		threadContext->stateDir = 0;
576	}
577}
578
579bool GBAThreadIsActive(struct GBAThread* threadContext) {
580	return threadContext->state >= THREAD_RUNNING && threadContext->state < THREAD_EXITING;
581}
582
583void GBAThreadInterrupt(struct GBAThread* threadContext) {
584	MutexLock(&threadContext->stateMutex);
585	++threadContext->interruptDepth;
586	if (threadContext->interruptDepth > 1 || !GBAThreadIsActive(threadContext)) {
587		MutexUnlock(&threadContext->stateMutex);
588		return;
589	}
590	threadContext->savedState = threadContext->state;
591	_waitOnInterrupt(threadContext);
592	threadContext->state = THREAD_INTERRUPTING;
593	threadContext->gba->cpu->nextEvent = 0;
594	ConditionWake(&threadContext->stateCond);
595	_waitUntilNotState(threadContext, THREAD_INTERRUPTING);
596	MutexUnlock(&threadContext->stateMutex);
597}
598
599void GBAThreadContinue(struct GBAThread* threadContext) {
600	MutexLock(&threadContext->stateMutex);
601	--threadContext->interruptDepth;
602	if (threadContext->interruptDepth < 1 && GBAThreadIsActive(threadContext)) {
603		threadContext->state = threadContext->savedState;
604		ConditionWake(&threadContext->stateCond);
605	}
606	MutexUnlock(&threadContext->stateMutex);
607}
608
609void GBARunOnThread(struct GBAThread* threadContext, void (*run)(struct GBAThread*)) {
610	MutexLock(&threadContext->stateMutex);
611	threadContext->run = run;
612	_waitOnInterrupt(threadContext);
613	threadContext->state = THREAD_RUN_ON;
614	threadContext->gba->cpu->nextEvent = 0;
615	ConditionWake(&threadContext->stateCond);
616	_waitUntilNotState(threadContext, THREAD_RUN_ON);
617	MutexUnlock(&threadContext->stateMutex);
618}
619
620void GBAThreadPause(struct GBAThread* threadContext) {
621	bool frameOn = true;
622	MutexLock(&threadContext->stateMutex);
623	_waitOnInterrupt(threadContext);
624	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 GBAThreadUnpause(struct GBAThread* threadContext) {
634	MutexLock(&threadContext->stateMutex);
635	_waitOnInterrupt(threadContext);
636	if (threadContext->state == THREAD_PAUSED || threadContext->state == THREAD_PAUSING) {
637		threadContext->state = THREAD_RUNNING;
638		ConditionWake(&threadContext->stateCond);
639	}
640	MutexUnlock(&threadContext->stateMutex);
641
642	_changeVideoSync(&threadContext->sync, true);
643}
644
645bool GBAThreadIsPaused(struct GBAThread* threadContext) {
646	bool isPaused;
647	MutexLock(&threadContext->stateMutex);
648	_waitOnInterrupt(threadContext);
649	isPaused = threadContext->state == THREAD_PAUSED;
650	MutexUnlock(&threadContext->stateMutex);
651	return isPaused;
652}
653
654void GBAThreadTogglePause(struct GBAThread* threadContext) {
655	bool frameOn = true;
656	MutexLock(&threadContext->stateMutex);
657	_waitOnInterrupt(threadContext);
658	if (threadContext->state == THREAD_PAUSED || threadContext->state == THREAD_PAUSING) {
659		threadContext->state = THREAD_RUNNING;
660		ConditionWake(&threadContext->stateCond);
661	} else if (threadContext->state == THREAD_RUNNING) {
662		_pauseThread(threadContext, false);
663		frameOn = false;
664	}
665	MutexUnlock(&threadContext->stateMutex);
666
667	_changeVideoSync(&threadContext->sync, frameOn);
668}
669
670void GBAThreadPauseFromThread(struct GBAThread* threadContext) {
671	bool frameOn = true;
672	MutexLock(&threadContext->stateMutex);
673	_waitOnInterrupt(threadContext);
674	if (threadContext->state == THREAD_RUNNING) {
675		_pauseThread(threadContext, true);
676		frameOn = false;
677	}
678	MutexUnlock(&threadContext->stateMutex);
679
680	_changeVideoSync(&threadContext->sync, frameOn);
681}
682
683#ifdef USE_PTHREADS
684struct GBAThread* GBAThreadGetContext(void) {
685	pthread_once(&_contextOnce, _createTLS);
686	return pthread_getspecific(_contextKey);
687}
688#elif _WIN32
689struct GBAThread* GBAThreadGetContext(void) {
690	InitOnceExecuteOnce(&_contextOnce, _createTLS, NULL, 0);
691	return TlsGetValue(_contextKey);
692}
693#endif
694
695#ifdef USE_PNG
696void GBAThreadTakeScreenshot(struct GBAThread* threadContext) {
697	unsigned stride;
698	void* pixels = 0;
699	struct VFile* vf = VDirOptionalOpenIncrementFile(threadContext->stateDir, threadContext->gba->activeFile, "screenshot", "-", ".png", O_CREAT | O_TRUNC | O_WRONLY);
700	threadContext->gba->video.renderer->getPixels(threadContext->gba->video.renderer, &stride, &pixels);
701	png_structp png = PNGWriteOpen(vf);
702	png_infop info = PNGWriteHeader(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
703	bool success = PNGWritePixels(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, stride, pixels);
704	PNGWriteClose(png, info);
705	vf->close(vf);
706	if (success) {
707		GBALog(threadContext->gba, GBA_LOG_STATUS, "Screenshot saved");
708	}
709}
710#endif
711
712#else
713struct GBAThread* GBAThreadGetContext(void) {
714	return 0;
715}
716#endif
717
718void GBASyncPostFrame(struct GBASync* sync) {
719	if (!sync) {
720		return;
721	}
722
723	MutexLock(&sync->videoFrameMutex);
724	++sync->videoFramePending;
725	--sync->videoFrameSkip;
726	if (sync->videoFrameSkip < 0) {
727		do {
728			ConditionWake(&sync->videoFrameAvailableCond);
729			if (sync->videoFrameWait) {
730				ConditionWait(&sync->videoFrameRequiredCond, &sync->videoFrameMutex);
731			}
732		} while (sync->videoFrameWait && sync->videoFramePending);
733	}
734	MutexUnlock(&sync->videoFrameMutex);
735}
736
737void GBASyncForceFrame(struct GBASync* sync) {
738	if (!sync) {
739		return;
740	}
741
742	MutexLock(&sync->videoFrameMutex);
743	ConditionWake(&sync->videoFrameAvailableCond);
744	MutexUnlock(&sync->videoFrameMutex);
745}
746
747bool GBASyncWaitFrameStart(struct GBASync* sync, int frameskip) {
748	if (!sync) {
749		return true;
750	}
751
752	MutexLock(&sync->videoFrameMutex);
753	ConditionWake(&sync->videoFrameRequiredCond);
754	if (!sync->videoFrameOn && !sync->videoFramePending) {
755		return false;
756	}
757	if (sync->videoFrameOn) {
758		if (ConditionWaitTimed(&sync->videoFrameAvailableCond, &sync->videoFrameMutex, 50)) {
759			return false;
760		}
761	}
762	sync->videoFramePending = 0;
763	sync->videoFrameSkip = frameskip;
764	return true;
765}
766
767void GBASyncWaitFrameEnd(struct GBASync* sync) {
768	if (!sync) {
769		return;
770	}
771
772	MutexUnlock(&sync->videoFrameMutex);
773}
774
775bool GBASyncDrawingFrame(struct GBASync* sync) {
776	if (!sync) {
777		return true;
778	}
779
780	return sync->videoFrameSkip <= 0;
781}
782
783void GBASyncSuspendDrawing(struct GBASync* sync) {
784	if (!sync) {
785		return;
786	}
787
788	_changeVideoSync(sync, false);
789}
790
791void GBASyncResumeDrawing(struct GBASync* sync) {
792	if (!sync) {
793		return;
794	}
795
796	_changeVideoSync(sync, true);
797}
798
799void GBASyncProduceAudio(struct GBASync* sync, bool wait) {
800	if (!sync) {
801		return;
802	}
803
804	if (sync->audioWait && wait) {
805		// TODO loop properly in event of spurious wakeups
806		ConditionWait(&sync->audioRequiredCond, &sync->audioBufferMutex);
807	}
808	MutexUnlock(&sync->audioBufferMutex);
809}
810
811void GBASyncLockAudio(struct GBASync* sync) {
812	if (!sync) {
813		return;
814	}
815
816	MutexLock(&sync->audioBufferMutex);
817}
818
819void GBASyncUnlockAudio(struct GBASync* sync) {
820	if (!sync) {
821		return;
822	}
823
824	MutexUnlock(&sync->audioBufferMutex);
825}
826
827void GBASyncConsumeAudio(struct GBASync* sync) {
828	if (!sync) {
829		return;
830	}
831
832	ConditionWake(&sync->audioRequiredCond);
833	MutexUnlock(&sync->audioBufferMutex);
834}