all repos — mgba @ 57999df85e710b3172b8a74593409c6025b025d0

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_RUN_ON) {
278				if (threadContext->run) {
279					threadContext->run(threadContext);
280				}
281				threadContext->state = THREAD_RUNNING;
282				ConditionWake(&threadContext->stateCond);
283			}
284			if (threadContext->state == THREAD_RESETING) {
285				threadContext->state = THREAD_RUNNING;
286				resetScheduled = 1;
287			}
288			while (threadContext->state == THREAD_PAUSED || threadContext->state == THREAD_INTERRUPTED) {
289				ConditionWait(&threadContext->stateCond, &threadContext->stateMutex);
290			}
291		}
292		MutexUnlock(&threadContext->stateMutex);
293		if (resetScheduled) {
294			ARMReset(&cpu);
295			if (threadContext->skipBios) {
296				GBASkipBIOS(&cpu);
297			}
298		}
299	}
300
301	while (threadContext->state < THREAD_SHUTDOWN) {
302		_changeState(threadContext, THREAD_SHUTDOWN, false);
303	}
304
305	if (threadContext->cleanCallback) {
306		threadContext->cleanCallback(threadContext);
307	}
308
309	threadContext->gba = 0;
310	ARMDeinit(&cpu);
311	GBADestroy(&gba);
312	if (&cheatDevice == threadContext->cheats) {
313		GBACheatDeviceDestroy(&cheatDevice);
314	}
315
316	if (movie) {
317		movie->destroy(movie);
318		free(movie);
319	}
320
321	threadContext->sync.videoFrameOn = false;
322	ConditionWake(&threadContext->sync.videoFrameAvailableCond);
323	ConditionWake(&threadContext->sync.audioRequiredCond);
324
325	return 0;
326}
327
328void GBAMapOptionsToContext(const struct GBAOptions* opts, struct GBAThread* threadContext) {
329	if (opts->useBios) {
330		threadContext->bios = VFileOpen(opts->bios, O_RDONLY);
331	} else {
332		threadContext->bios = 0;
333	}
334	threadContext->frameskip = opts->frameskip;
335	threadContext->volume = opts->volume;
336	threadContext->mute = opts->mute;
337	threadContext->logLevel = opts->logLevel;
338	if (opts->rewindEnable) {
339		threadContext->rewindBufferCapacity = opts->rewindBufferCapacity;
340		threadContext->rewindBufferInterval = opts->rewindBufferInterval;
341	} else {
342		threadContext->rewindBufferCapacity = 0;
343	}
344	threadContext->skipBios = opts->skipBios;
345	threadContext->sync.audioWait = opts->audioSync;
346	threadContext->sync.videoFrameWait = opts->videoSync;
347
348	if (opts->fpsTarget) {
349		threadContext->fpsTarget = opts->fpsTarget;
350	}
351
352	if (opts->audioBuffers) {
353		threadContext->audioBuffers = opts->audioBuffers;
354	}
355
356	threadContext->idleOptimization = opts->idleOptimization;
357}
358
359void GBAMapArgumentsToContext(const struct GBAArguments* args, struct GBAThread* threadContext) {
360	if (args->dirmode) {
361		threadContext->gameDir = VDirOpen(args->fname);
362		threadContext->stateDir = threadContext->gameDir;
363	} else {
364		threadContext->rom = VFileOpen(args->fname, O_RDONLY);
365		threadContext->gameDir = 0;
366#if USE_LIBZIP
367		if (!threadContext->gameDir) {
368			threadContext->gameDir = VDirOpenZip(args->fname, 0);
369		}
370#endif
371#if USE_LZMA
372		if (!threadContext->gameDir) {
373			threadContext->gameDir = VDirOpen7z(args->fname, 0);
374		}
375#endif
376	}
377	threadContext->fname = args->fname;
378	threadContext->patch = VFileOpen(args->patch, O_RDONLY);
379	threadContext->cheatsFile = VFileOpen(args->cheatsFile, O_RDONLY);
380	threadContext->movie = args->movie;
381}
382
383bool GBAThreadStart(struct GBAThread* threadContext) {
384	// TODO: error check
385	threadContext->activeKeys = 0;
386	threadContext->state = THREAD_INITIALIZED;
387	threadContext->sync.videoFrameOn = true;
388	threadContext->sync.videoFrameSkip = 0;
389
390	threadContext->rewindBuffer = 0;
391	threadContext->rewindScreenBuffer = 0;
392	int newCapacity = threadContext->rewindBufferCapacity;
393	int newInterval = threadContext->rewindBufferInterval;
394	threadContext->rewindBufferCapacity = 0;
395	threadContext->rewindBufferInterval = 0;
396	GBARewindSettingsChanged(threadContext, newCapacity, newInterval);
397
398	if (!threadContext->fpsTarget) {
399		threadContext->fpsTarget = _defaultFPSTarget;
400	}
401
402	if (threadContext->rom && !GBAIsROM(threadContext->rom)) {
403		threadContext->rom->close(threadContext->rom);
404		threadContext->rom = 0;
405	}
406
407	if (threadContext->gameDir) {
408		threadContext->gameDir->rewind(threadContext->gameDir);
409		struct VDirEntry* dirent = threadContext->gameDir->listNext(threadContext->gameDir);
410		while (dirent) {
411			struct Patch patchTemp;
412			struct VFile* vf = threadContext->gameDir->openFile(threadContext->gameDir, dirent->name(dirent), O_RDONLY);
413			if (!vf) {
414				dirent = threadContext->gameDir->listNext(threadContext->gameDir);
415				continue;
416			}
417			if (!threadContext->rom && GBAIsROM(vf)) {
418				threadContext->rom = vf;
419			} else if (!threadContext->patch && loadPatch(vf, &patchTemp)) {
420				threadContext->patch = vf;
421			} else {
422				vf->close(vf);
423			}
424			dirent = threadContext->gameDir->listNext(threadContext->gameDir);
425		}
426
427	}
428
429	if (!threadContext->rom) {
430		threadContext->state = THREAD_SHUTDOWN;
431		return false;
432	}
433
434	threadContext->save = VDirOptionalOpenFile(threadContext->stateDir, threadContext->fname, "sram", ".sav", O_CREAT | O_RDWR);
435
436	MutexInit(&threadContext->stateMutex);
437	ConditionInit(&threadContext->stateCond);
438
439	MutexInit(&threadContext->sync.videoFrameMutex);
440	ConditionInit(&threadContext->sync.videoFrameAvailableCond);
441	ConditionInit(&threadContext->sync.videoFrameRequiredCond);
442	MutexInit(&threadContext->sync.audioBufferMutex);
443	ConditionInit(&threadContext->sync.audioRequiredCond);
444
445	threadContext->interruptDepth = 0;
446
447#ifndef _WIN32
448	sigset_t signals;
449	sigemptyset(&signals);
450	sigaddset(&signals, SIGINT);
451	sigaddset(&signals, SIGTRAP);
452	pthread_sigmask(SIG_BLOCK, &signals, 0);
453#endif
454
455	MutexLock(&threadContext->stateMutex);
456	ThreadCreate(&threadContext->thread, _GBAThreadRun, threadContext);
457	while (threadContext->state < THREAD_RUNNING) {
458		ConditionWait(&threadContext->stateCond, &threadContext->stateMutex);
459	}
460	MutexUnlock(&threadContext->stateMutex);
461
462	return true;
463}
464
465bool GBAThreadHasStarted(struct GBAThread* threadContext) {
466	bool hasStarted;
467	MutexLock(&threadContext->stateMutex);
468	hasStarted = threadContext->state > THREAD_INITIALIZED;
469	MutexUnlock(&threadContext->stateMutex);
470	return hasStarted;
471}
472
473bool GBAThreadHasExited(struct GBAThread* threadContext) {
474	bool hasExited;
475	MutexLock(&threadContext->stateMutex);
476	hasExited = threadContext->state > THREAD_EXITING;
477	MutexUnlock(&threadContext->stateMutex);
478	return hasExited;
479}
480
481bool GBAThreadHasCrashed(struct GBAThread* threadContext) {
482	bool hasExited;
483	MutexLock(&threadContext->stateMutex);
484	hasExited = threadContext->state == THREAD_CRASHED;
485	MutexUnlock(&threadContext->stateMutex);
486	return hasExited;
487}
488
489void GBAThreadEnd(struct GBAThread* threadContext) {
490	MutexLock(&threadContext->stateMutex);
491	_waitOnInterrupt(threadContext);
492	threadContext->state = THREAD_EXITING;
493	if (threadContext->gba) {
494		threadContext->gba->cpu->halted = false;
495	}
496	ConditionWake(&threadContext->stateCond);
497	MutexUnlock(&threadContext->stateMutex);
498	MutexLock(&threadContext->sync.audioBufferMutex);
499	threadContext->sync.audioWait = 0;
500	ConditionWake(&threadContext->sync.audioRequiredCond);
501	MutexUnlock(&threadContext->sync.audioBufferMutex);
502
503	MutexLock(&threadContext->sync.videoFrameMutex);
504	threadContext->sync.videoFrameWait = false;
505	threadContext->sync.videoFrameOn = false;
506	ConditionWake(&threadContext->sync.videoFrameRequiredCond);
507	ConditionWake(&threadContext->sync.videoFrameAvailableCond);
508	MutexUnlock(&threadContext->sync.videoFrameMutex);
509}
510
511void GBAThreadReset(struct GBAThread* threadContext) {
512	MutexLock(&threadContext->stateMutex);
513	_waitOnInterrupt(threadContext);
514	threadContext->state = THREAD_RESETING;
515	ConditionWake(&threadContext->stateCond);
516	MutexUnlock(&threadContext->stateMutex);
517}
518
519void GBAThreadJoin(struct GBAThread* threadContext) {
520	ThreadJoin(threadContext->thread);
521
522	MutexDeinit(&threadContext->stateMutex);
523	ConditionDeinit(&threadContext->stateCond);
524
525	MutexDeinit(&threadContext->sync.videoFrameMutex);
526	ConditionWake(&threadContext->sync.videoFrameAvailableCond);
527	ConditionDeinit(&threadContext->sync.videoFrameAvailableCond);
528	ConditionWake(&threadContext->sync.videoFrameRequiredCond);
529	ConditionDeinit(&threadContext->sync.videoFrameRequiredCond);
530
531	ConditionWake(&threadContext->sync.audioRequiredCond);
532	ConditionDeinit(&threadContext->sync.audioRequiredCond);
533	MutexDeinit(&threadContext->sync.audioBufferMutex);
534
535	int i;
536	for (i = 0; i < threadContext->rewindBufferCapacity; ++i) {
537		if (threadContext->rewindBuffer[i]) {
538			GBADeallocateState(threadContext->rewindBuffer[i]);
539		}
540	}
541	free(threadContext->rewindBuffer);
542	free(threadContext->rewindScreenBuffer);
543
544	if (threadContext->rom) {
545		threadContext->rom->close(threadContext->rom);
546		threadContext->rom = 0;
547	}
548
549	if (threadContext->save) {
550		threadContext->save->close(threadContext->save);
551		threadContext->save = 0;
552	}
553
554	if (threadContext->bios) {
555		threadContext->bios->close(threadContext->bios);
556		threadContext->bios = 0;
557	}
558
559	if (threadContext->patch) {
560		threadContext->patch->close(threadContext->patch);
561		threadContext->patch = 0;
562	}
563
564	if (threadContext->gameDir) {
565		if (threadContext->stateDir == threadContext->gameDir) {
566			threadContext->stateDir = 0;
567		}
568		threadContext->gameDir->close(threadContext->gameDir);
569		threadContext->gameDir = 0;
570	}
571
572	if (threadContext->stateDir) {
573		threadContext->stateDir->close(threadContext->stateDir);
574		threadContext->stateDir = 0;
575	}
576}
577
578bool GBAThreadIsActive(struct GBAThread* threadContext) {
579	return threadContext->state >= THREAD_RUNNING && threadContext->state < THREAD_EXITING;
580}
581
582void GBAThreadInterrupt(struct GBAThread* threadContext) {
583	MutexLock(&threadContext->stateMutex);
584	++threadContext->interruptDepth;
585	if (threadContext->interruptDepth > 1 || !GBAThreadIsActive(threadContext)) {
586		MutexUnlock(&threadContext->stateMutex);
587		return;
588	}
589	threadContext->savedState = threadContext->state;
590	_waitOnInterrupt(threadContext);
591	threadContext->state = THREAD_INTERRUPTING;
592	threadContext->gba->cpu->nextEvent = 0;
593	ConditionWake(&threadContext->stateCond);
594	_waitUntilNotState(threadContext, THREAD_INTERRUPTING);
595	MutexUnlock(&threadContext->stateMutex);
596}
597
598void GBAThreadContinue(struct GBAThread* threadContext) {
599	MutexLock(&threadContext->stateMutex);
600	--threadContext->interruptDepth;
601	if (threadContext->interruptDepth < 1 && GBAThreadIsActive(threadContext)) {
602		threadContext->state = threadContext->savedState;
603		ConditionWake(&threadContext->stateCond);
604	}
605	MutexUnlock(&threadContext->stateMutex);
606}
607
608void GBARunOnThread(struct GBAThread* threadContext, void (*run)(struct GBAThread*)) {
609	MutexLock(&threadContext->stateMutex);
610	threadContext->run = run;
611	_waitOnInterrupt(threadContext);
612	threadContext->state = THREAD_RUN_ON;
613	threadContext->gba->cpu->nextEvent = 0;
614	ConditionWake(&threadContext->stateCond);
615	_waitUntilNotState(threadContext, THREAD_RUN_ON);
616	MutexUnlock(&threadContext->stateMutex);
617}
618
619void GBAThreadPause(struct GBAThread* threadContext) {
620	bool frameOn = true;
621	MutexLock(&threadContext->stateMutex);
622	_waitOnInterrupt(threadContext);
623	if (threadContext->state == THREAD_RUNNING) {
624		_pauseThread(threadContext, false);
625		frameOn = false;
626	}
627	MutexUnlock(&threadContext->stateMutex);
628
629	_changeVideoSync(&threadContext->sync, frameOn);
630}
631
632void GBAThreadUnpause(struct GBAThread* threadContext) {
633	MutexLock(&threadContext->stateMutex);
634	_waitOnInterrupt(threadContext);
635	if (threadContext->state == THREAD_PAUSED || threadContext->state == THREAD_PAUSING) {
636		threadContext->state = THREAD_RUNNING;
637		ConditionWake(&threadContext->stateCond);
638	}
639	MutexUnlock(&threadContext->stateMutex);
640
641	_changeVideoSync(&threadContext->sync, true);
642}
643
644bool GBAThreadIsPaused(struct GBAThread* threadContext) {
645	bool isPaused;
646	MutexLock(&threadContext->stateMutex);
647	_waitOnInterrupt(threadContext);
648	isPaused = threadContext->state == THREAD_PAUSED;
649	MutexUnlock(&threadContext->stateMutex);
650	return isPaused;
651}
652
653void GBAThreadTogglePause(struct GBAThread* threadContext) {
654	bool frameOn = true;
655	MutexLock(&threadContext->stateMutex);
656	_waitOnInterrupt(threadContext);
657	if (threadContext->state == THREAD_PAUSED || threadContext->state == THREAD_PAUSING) {
658		threadContext->state = THREAD_RUNNING;
659		ConditionWake(&threadContext->stateCond);
660	} else if (threadContext->state == THREAD_RUNNING) {
661		_pauseThread(threadContext, false);
662		frameOn = false;
663	}
664	MutexUnlock(&threadContext->stateMutex);
665
666	_changeVideoSync(&threadContext->sync, frameOn);
667}
668
669void GBAThreadPauseFromThread(struct GBAThread* threadContext) {
670	bool frameOn = true;
671	MutexLock(&threadContext->stateMutex);
672	_waitOnInterrupt(threadContext);
673	if (threadContext->state == THREAD_RUNNING) {
674		_pauseThread(threadContext, true);
675		frameOn = false;
676	}
677	MutexUnlock(&threadContext->stateMutex);
678
679	_changeVideoSync(&threadContext->sync, frameOn);
680}
681
682#ifdef USE_PTHREADS
683struct GBAThread* GBAThreadGetContext(void) {
684	pthread_once(&_contextOnce, _createTLS);
685	return pthread_getspecific(_contextKey);
686}
687#elif _WIN32
688struct GBAThread* GBAThreadGetContext(void) {
689	InitOnceExecuteOnce(&_contextOnce, _createTLS, NULL, 0);
690	return TlsGetValue(_contextKey);
691}
692#endif
693
694#ifdef USE_PNG
695void GBAThreadTakeScreenshot(struct GBAThread* threadContext) {
696	unsigned stride;
697	void* pixels = 0;
698	struct VFile* vf = VDirOptionalOpenIncrementFile(threadContext->stateDir, threadContext->gba->activeFile, "screenshot", "-", ".png", O_CREAT | O_TRUNC | O_WRONLY);
699	threadContext->gba->video.renderer->getPixels(threadContext->gba->video.renderer, &stride, &pixels);
700	png_structp png = PNGWriteOpen(vf);
701	png_infop info = PNGWriteHeader(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
702	bool success = PNGWritePixels(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, stride, pixels);
703	PNGWriteClose(png, info);
704	vf->close(vf);
705	if (success) {
706		GBALog(threadContext->gba, GBA_LOG_STATUS, "Screenshot saved");
707	}
708}
709#endif
710
711#else
712struct GBAThread* GBAThreadGetContext(void) {
713	return 0;
714}
715#endif
716
717void GBASyncPostFrame(struct GBASync* sync) {
718	if (!sync) {
719		return;
720	}
721
722	MutexLock(&sync->videoFrameMutex);
723	++sync->videoFramePending;
724	--sync->videoFrameSkip;
725	if (sync->videoFrameSkip < 0) {
726		do {
727			ConditionWake(&sync->videoFrameAvailableCond);
728			if (sync->videoFrameWait) {
729				ConditionWait(&sync->videoFrameRequiredCond, &sync->videoFrameMutex);
730			}
731		} while (sync->videoFrameWait && sync->videoFramePending);
732	}
733	MutexUnlock(&sync->videoFrameMutex);
734}
735
736void GBASyncForceFrame(struct GBASync* sync) {
737	if (!sync) {
738		return;
739	}
740
741	MutexLock(&sync->videoFrameMutex);
742	ConditionWake(&sync->videoFrameAvailableCond);
743	MutexUnlock(&sync->videoFrameMutex);
744}
745
746bool GBASyncWaitFrameStart(struct GBASync* sync, int frameskip) {
747	if (!sync) {
748		return true;
749	}
750
751	MutexLock(&sync->videoFrameMutex);
752	ConditionWake(&sync->videoFrameRequiredCond);
753	if (!sync->videoFrameOn && !sync->videoFramePending) {
754		return false;
755	}
756	if (sync->videoFrameOn) {
757		if (ConditionWaitTimed(&sync->videoFrameAvailableCond, &sync->videoFrameMutex, 50)) {
758			return false;
759		}
760	}
761	sync->videoFramePending = 0;
762	sync->videoFrameSkip = frameskip;
763	return true;
764}
765
766void GBASyncWaitFrameEnd(struct GBASync* sync) {
767	if (!sync) {
768		return;
769	}
770
771	MutexUnlock(&sync->videoFrameMutex);
772}
773
774bool GBASyncDrawingFrame(struct GBASync* sync) {
775	if (!sync) {
776		return true;
777	}
778
779	return sync->videoFrameSkip <= 0;
780}
781
782void GBASyncSuspendDrawing(struct GBASync* sync) {
783	if (!sync) {
784		return;
785	}
786
787	_changeVideoSync(sync, false);
788}
789
790void GBASyncResumeDrawing(struct GBASync* sync) {
791	if (!sync) {
792		return;
793	}
794
795	_changeVideoSync(sync, true);
796}
797
798void GBASyncProduceAudio(struct GBASync* sync, bool wait) {
799	if (!sync) {
800		return;
801	}
802
803	if (sync->audioWait && wait) {
804		// TODO loop properly in event of spurious wakeups
805		ConditionWait(&sync->audioRequiredCond, &sync->audioBufferMutex);
806	}
807	MutexUnlock(&sync->audioBufferMutex);
808}
809
810void GBASyncLockAudio(struct GBASync* sync) {
811	if (!sync) {
812		return;
813	}
814
815	MutexLock(&sync->audioBufferMutex);
816}
817
818void GBASyncUnlockAudio(struct GBASync* sync) {
819	if (!sync) {
820		return;
821	}
822
823	MutexUnlock(&sync->audioBufferMutex);
824}
825
826void GBASyncConsumeAudio(struct GBASync* sync) {
827	if (!sync) {
828		return;
829	}
830
831	ConditionWake(&sync->audioRequiredCond);
832	MutexUnlock(&sync->audioBufferMutex);
833}