all repos — mgba @ 8266f54d7674ec7fdbe263efea163481c8b33571

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