all repos — mgba @ f52d91c6c8b93f82827254fa46c2a16c799fa2ae

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	threadContext->rewindScreenBuffer = 0;
385	int newCapacity = threadContext->rewindBufferCapacity;
386	int newInterval = threadContext->rewindBufferInterval;
387	threadContext->rewindBufferCapacity = 0;
388	threadContext->rewindBufferInterval = 0;
389	GBARewindSettingsChanged(threadContext, newCapacity, newInterval);
390
391	if (!threadContext->fpsTarget) {
392		threadContext->fpsTarget = _defaultFPSTarget;
393	}
394
395	if (threadContext->rom && !GBAIsROM(threadContext->rom)) {
396		threadContext->rom->close(threadContext->rom);
397		threadContext->rom = 0;
398	}
399
400	if (threadContext->gameDir) {
401		threadContext->gameDir->rewind(threadContext->gameDir);
402		struct VDirEntry* dirent = threadContext->gameDir->listNext(threadContext->gameDir);
403		while (dirent) {
404			struct Patch patchTemp;
405			struct VFile* vf = threadContext->gameDir->openFile(threadContext->gameDir, dirent->name(dirent), O_RDONLY);
406			if (!vf) {
407				dirent = threadContext->gameDir->listNext(threadContext->gameDir);
408				continue;
409			}
410			if (!threadContext->rom && GBAIsROM(vf)) {
411				threadContext->rom = vf;
412			} else if (!threadContext->patch && loadPatch(vf, &patchTemp)) {
413				threadContext->patch = vf;
414			} else {
415				vf->close(vf);
416			}
417			dirent = threadContext->gameDir->listNext(threadContext->gameDir);
418		}
419
420	}
421
422	if (!threadContext->rom) {
423		threadContext->state = THREAD_SHUTDOWN;
424		return false;
425	}
426
427	threadContext->save = VDirOptionalOpenFile(threadContext->stateDir, threadContext->fname, "sram", ".sav", O_CREAT | O_RDWR);
428
429	MutexInit(&threadContext->stateMutex);
430	ConditionInit(&threadContext->stateCond);
431
432	MutexInit(&threadContext->sync.videoFrameMutex);
433	ConditionInit(&threadContext->sync.videoFrameAvailableCond);
434	ConditionInit(&threadContext->sync.videoFrameRequiredCond);
435	MutexInit(&threadContext->sync.audioBufferMutex);
436	ConditionInit(&threadContext->sync.audioRequiredCond);
437
438	threadContext->interruptDepth = 0;
439
440#ifndef _WIN32
441	sigset_t signals;
442	sigemptyset(&signals);
443	sigaddset(&signals, SIGINT);
444	sigaddset(&signals, SIGTRAP);
445	pthread_sigmask(SIG_BLOCK, &signals, 0);
446#endif
447
448	MutexLock(&threadContext->stateMutex);
449	ThreadCreate(&threadContext->thread, _GBAThreadRun, threadContext);
450	while (threadContext->state < THREAD_RUNNING) {
451		ConditionWait(&threadContext->stateCond, &threadContext->stateMutex);
452	}
453	MutexUnlock(&threadContext->stateMutex);
454
455	return true;
456}
457
458bool GBAThreadHasStarted(struct GBAThread* threadContext) {
459	bool hasStarted;
460	MutexLock(&threadContext->stateMutex);
461	hasStarted = threadContext->state > THREAD_INITIALIZED;
462	MutexUnlock(&threadContext->stateMutex);
463	return hasStarted;
464}
465
466bool GBAThreadHasExited(struct GBAThread* threadContext) {
467	bool hasExited;
468	MutexLock(&threadContext->stateMutex);
469	hasExited = threadContext->state > THREAD_EXITING;
470	MutexUnlock(&threadContext->stateMutex);
471	return hasExited;
472}
473
474bool GBAThreadHasCrashed(struct GBAThread* threadContext) {
475	bool hasExited;
476	MutexLock(&threadContext->stateMutex);
477	hasExited = threadContext->state == THREAD_CRASHED;
478	MutexUnlock(&threadContext->stateMutex);
479	return hasExited;
480}
481
482void GBAThreadEnd(struct GBAThread* threadContext) {
483	MutexLock(&threadContext->stateMutex);
484	_waitOnInterrupt(threadContext);
485	threadContext->state = THREAD_EXITING;
486	if (threadContext->gba) {
487		threadContext->gba->cpu->halted = false;
488	}
489	ConditionWake(&threadContext->stateCond);
490	MutexUnlock(&threadContext->stateMutex);
491	MutexLock(&threadContext->sync.audioBufferMutex);
492	threadContext->sync.audioWait = 0;
493	ConditionWake(&threadContext->sync.audioRequiredCond);
494	MutexUnlock(&threadContext->sync.audioBufferMutex);
495
496	MutexLock(&threadContext->sync.videoFrameMutex);
497	threadContext->sync.videoFrameWait = false;
498	threadContext->sync.videoFrameOn = false;
499	ConditionWake(&threadContext->sync.videoFrameRequiredCond);
500	ConditionWake(&threadContext->sync.videoFrameAvailableCond);
501	MutexUnlock(&threadContext->sync.videoFrameMutex);
502}
503
504void GBAThreadReset(struct GBAThread* threadContext) {
505	MutexLock(&threadContext->stateMutex);
506	_waitOnInterrupt(threadContext);
507	threadContext->state = THREAD_RESETING;
508	ConditionWake(&threadContext->stateCond);
509	MutexUnlock(&threadContext->stateMutex);
510}
511
512void GBAThreadJoin(struct GBAThread* threadContext) {
513	ThreadJoin(threadContext->thread);
514
515	MutexDeinit(&threadContext->stateMutex);
516	ConditionDeinit(&threadContext->stateCond);
517
518	MutexDeinit(&threadContext->sync.videoFrameMutex);
519	ConditionWake(&threadContext->sync.videoFrameAvailableCond);
520	ConditionDeinit(&threadContext->sync.videoFrameAvailableCond);
521	ConditionWake(&threadContext->sync.videoFrameRequiredCond);
522	ConditionDeinit(&threadContext->sync.videoFrameRequiredCond);
523
524	ConditionWake(&threadContext->sync.audioRequiredCond);
525	ConditionDeinit(&threadContext->sync.audioRequiredCond);
526	MutexDeinit(&threadContext->sync.audioBufferMutex);
527
528	int i;
529	for (i = 0; i < threadContext->rewindBufferCapacity; ++i) {
530		if (threadContext->rewindBuffer[i]) {
531			GBADeallocateState(threadContext->rewindBuffer[i]);
532		}
533	}
534	free(threadContext->rewindBuffer);
535	free(threadContext->rewindScreenBuffer);
536
537	if (threadContext->rom) {
538		threadContext->rom->close(threadContext->rom);
539		threadContext->rom = 0;
540	}
541
542	if (threadContext->save) {
543		threadContext->save->close(threadContext->save);
544		threadContext->save = 0;
545	}
546
547	if (threadContext->bios) {
548		threadContext->bios->close(threadContext->bios);
549		threadContext->bios = 0;
550	}
551
552	if (threadContext->patch) {
553		threadContext->patch->close(threadContext->patch);
554		threadContext->patch = 0;
555	}
556
557	if (threadContext->gameDir) {
558		if (threadContext->stateDir == threadContext->gameDir) {
559			threadContext->stateDir = 0;
560		}
561		threadContext->gameDir->close(threadContext->gameDir);
562		threadContext->gameDir = 0;
563	}
564
565	if (threadContext->stateDir) {
566		threadContext->stateDir->close(threadContext->stateDir);
567		threadContext->stateDir = 0;
568	}
569}
570
571bool GBAThreadIsActive(struct GBAThread* threadContext) {
572	return threadContext->state >= THREAD_RUNNING && threadContext->state < THREAD_EXITING;
573}
574
575void GBAThreadInterrupt(struct GBAThread* threadContext) {
576	MutexLock(&threadContext->stateMutex);
577	++threadContext->interruptDepth;
578	if (threadContext->interruptDepth > 1 || !GBAThreadIsActive(threadContext)) {
579		MutexUnlock(&threadContext->stateMutex);
580		return;
581	}
582	threadContext->savedState = threadContext->state;
583	_waitOnInterrupt(threadContext);
584	threadContext->state = THREAD_INTERRUPTING;
585	threadContext->gba->cpu->nextEvent = 0;
586	ConditionWake(&threadContext->stateCond);
587	_waitUntilNotState(threadContext, THREAD_INTERRUPTING);
588	MutexUnlock(&threadContext->stateMutex);
589}
590
591void GBAThreadContinue(struct GBAThread* threadContext) {
592	MutexLock(&threadContext->stateMutex);
593	--threadContext->interruptDepth;
594	if (threadContext->interruptDepth < 1 && GBAThreadIsActive(threadContext)) {
595		threadContext->state = threadContext->savedState;
596		ConditionWake(&threadContext->stateCond);
597	}
598	MutexUnlock(&threadContext->stateMutex);
599}
600
601void GBAThreadPause(struct GBAThread* threadContext) {
602	bool frameOn = true;
603	MutexLock(&threadContext->stateMutex);
604	_waitOnInterrupt(threadContext);
605	if (threadContext->state == THREAD_RUNNING) {
606		_pauseThread(threadContext, false);
607		frameOn = false;
608	}
609	MutexUnlock(&threadContext->stateMutex);
610
611	_changeVideoSync(&threadContext->sync, frameOn);
612}
613
614void GBAThreadUnpause(struct GBAThread* threadContext) {
615	MutexLock(&threadContext->stateMutex);
616	_waitOnInterrupt(threadContext);
617	if (threadContext->state == THREAD_PAUSED || threadContext->state == THREAD_PAUSING) {
618		threadContext->state = THREAD_RUNNING;
619		ConditionWake(&threadContext->stateCond);
620	}
621	MutexUnlock(&threadContext->stateMutex);
622
623	_changeVideoSync(&threadContext->sync, true);
624}
625
626bool GBAThreadIsPaused(struct GBAThread* threadContext) {
627	bool isPaused;
628	MutexLock(&threadContext->stateMutex);
629	_waitOnInterrupt(threadContext);
630	isPaused = threadContext->state == THREAD_PAUSED;
631	MutexUnlock(&threadContext->stateMutex);
632	return isPaused;
633}
634
635void GBAThreadTogglePause(struct GBAThread* threadContext) {
636	bool frameOn = true;
637	MutexLock(&threadContext->stateMutex);
638	_waitOnInterrupt(threadContext);
639	if (threadContext->state == THREAD_PAUSED || threadContext->state == THREAD_PAUSING) {
640		threadContext->state = THREAD_RUNNING;
641		ConditionWake(&threadContext->stateCond);
642	} else if (threadContext->state == THREAD_RUNNING) {
643		_pauseThread(threadContext, false);
644		frameOn = false;
645	}
646	MutexUnlock(&threadContext->stateMutex);
647
648	_changeVideoSync(&threadContext->sync, frameOn);
649}
650
651void GBAThreadPauseFromThread(struct GBAThread* threadContext) {
652	bool frameOn = true;
653	MutexLock(&threadContext->stateMutex);
654	_waitOnInterrupt(threadContext);
655	if (threadContext->state == THREAD_RUNNING) {
656		_pauseThread(threadContext, true);
657		frameOn = false;
658	}
659	MutexUnlock(&threadContext->stateMutex);
660
661	_changeVideoSync(&threadContext->sync, frameOn);
662}
663
664#ifdef USE_PTHREADS
665struct GBAThread* GBAThreadGetContext(void) {
666	pthread_once(&_contextOnce, _createTLS);
667	return pthread_getspecific(_contextKey);
668}
669#elif _WIN32
670struct GBAThread* GBAThreadGetContext(void) {
671	InitOnceExecuteOnce(&_contextOnce, _createTLS, NULL, 0);
672	return TlsGetValue(_contextKey);
673}
674#endif
675
676#ifdef USE_PNG
677void GBAThreadTakeScreenshot(struct GBAThread* threadContext) {
678	unsigned stride;
679	void* pixels = 0;
680	struct VFile* vf = VDirOptionalOpenIncrementFile(threadContext->stateDir, threadContext->gba->activeFile, "screenshot", "-", ".png", O_CREAT | O_TRUNC | O_WRONLY);
681	threadContext->gba->video.renderer->getPixels(threadContext->gba->video.renderer, &stride, &pixels);
682	png_structp png = PNGWriteOpen(vf);
683	png_infop info = PNGWriteHeader(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
684	PNGWritePixels(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, stride, pixels);
685	PNGWriteClose(png, info);
686	vf->close(vf);
687}
688#endif
689
690#else
691struct GBAThread* GBAThreadGetContext(void) {
692	return 0;
693}
694#endif
695
696void GBASyncPostFrame(struct GBASync* sync) {
697	if (!sync) {
698		return;
699	}
700
701	MutexLock(&sync->videoFrameMutex);
702	++sync->videoFramePending;
703	--sync->videoFrameSkip;
704	if (sync->videoFrameSkip < 0) {
705		do {
706			ConditionWake(&sync->videoFrameAvailableCond);
707			if (sync->videoFrameWait) {
708				ConditionWait(&sync->videoFrameRequiredCond, &sync->videoFrameMutex);
709			}
710		} while (sync->videoFrameWait && sync->videoFramePending);
711	}
712	MutexUnlock(&sync->videoFrameMutex);
713}
714
715void GBASyncForceFrame(struct GBASync* sync) {
716	if (!sync) {
717		return;
718	}
719
720	MutexLock(&sync->videoFrameMutex);
721	ConditionWake(&sync->videoFrameAvailableCond);
722	MutexUnlock(&sync->videoFrameMutex);
723}
724
725bool GBASyncWaitFrameStart(struct GBASync* sync, int frameskip) {
726	if (!sync) {
727		return true;
728	}
729
730	MutexLock(&sync->videoFrameMutex);
731	ConditionWake(&sync->videoFrameRequiredCond);
732	if (!sync->videoFrameOn && !sync->videoFramePending) {
733		return false;
734	}
735	if (sync->videoFrameOn) {
736		if (ConditionWaitTimed(&sync->videoFrameAvailableCond, &sync->videoFrameMutex, 50)) {
737			return false;
738		}
739	}
740	sync->videoFramePending = 0;
741	sync->videoFrameSkip = frameskip;
742	return true;
743}
744
745void GBASyncWaitFrameEnd(struct GBASync* sync) {
746	if (!sync) {
747		return;
748	}
749
750	MutexUnlock(&sync->videoFrameMutex);
751}
752
753bool GBASyncDrawingFrame(struct GBASync* sync) {
754	if (!sync) {
755		return true;
756	}
757
758	return sync->videoFrameSkip <= 0;
759}
760
761void GBASyncSuspendDrawing(struct GBASync* sync) {
762	if (!sync) {
763		return;
764	}
765
766	_changeVideoSync(sync, false);
767}
768
769void GBASyncResumeDrawing(struct GBASync* sync) {
770	if (!sync) {
771		return;
772	}
773
774	_changeVideoSync(sync, true);
775}
776
777void GBASyncProduceAudio(struct GBASync* sync, bool wait) {
778	if (!sync) {
779		return;
780	}
781
782	if (sync->audioWait && wait) {
783		// TODO loop properly in event of spurious wakeups
784		ConditionWait(&sync->audioRequiredCond, &sync->audioBufferMutex);
785	}
786	MutexUnlock(&sync->audioBufferMutex);
787}
788
789void GBASyncLockAudio(struct GBASync* sync) {
790	if (!sync) {
791		return;
792	}
793
794	MutexLock(&sync->audioBufferMutex);
795}
796
797void GBASyncUnlockAudio(struct GBASync* sync) {
798	if (!sync) {
799		return;
800	}
801
802	MutexUnlock(&sync->audioBufferMutex);
803}
804
805void GBASyncConsumeAudio(struct GBASync* sync) {
806	if (!sync) {
807		return;
808	}
809
810	ConditionWake(&sync->audioRequiredCond);
811	MutexUnlock(&sync->audioBufferMutex);
812}