all repos — mgba @ 79e06612cb77d31bfaaa1a5506703158b4a2f989

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