all repos — mgba @ 50402c830729f2ba5a6fc3e6facfd8b258f7f97d

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/context/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/vfs.h"
 20
 21#include "platform/commandline.h"
 22
 23#include <signal.h>
 24
 25static void _loadGameDir(struct GBAThread* threadContext);
 26
 27static const float _defaultFPSTarget = 60.f;
 28
 29#ifndef DISABLE_THREADING
 30#ifdef USE_PTHREADS
 31static pthread_key_t _contextKey;
 32static pthread_once_t _contextOnce = PTHREAD_ONCE_INIT;
 33
 34static void _createTLS(void) {
 35	pthread_key_create(&_contextKey, 0);
 36}
 37#elif _WIN32
 38static DWORD _contextKey;
 39static INIT_ONCE _contextOnce = INIT_ONCE_STATIC_INIT;
 40
 41static BOOL CALLBACK _createTLS(PINIT_ONCE once, PVOID param, PVOID* context) {
 42	UNUSED(once);
 43	UNUSED(param);
 44	UNUSED(context);
 45	_contextKey = TlsAlloc();
 46	return TRUE;
 47}
 48#endif
 49
 50static void _changeState(struct GBAThread* threadContext, enum ThreadState newState, bool broadcast) {
 51	MutexLock(&threadContext->stateMutex);
 52	threadContext->state = newState;
 53	if (broadcast) {
 54		ConditionWake(&threadContext->stateCond);
 55	}
 56	MutexUnlock(&threadContext->stateMutex);
 57}
 58
 59static void _waitOnInterrupt(struct GBAThread* threadContext) {
 60	while (threadContext->state == THREAD_INTERRUPTED) {
 61		ConditionWait(&threadContext->stateCond, &threadContext->stateMutex);
 62	}
 63}
 64
 65static void _waitUntilNotState(struct GBAThread* threadContext, enum ThreadState oldState) {
 66	MutexLock(&threadContext->sync.videoFrameMutex);
 67	bool videoFrameWait = threadContext->sync.videoFrameWait;
 68	threadContext->sync.videoFrameWait = false;
 69	MutexUnlock(&threadContext->sync.videoFrameMutex);
 70
 71	while (threadContext->state == oldState) {
 72		MutexUnlock(&threadContext->stateMutex);
 73
 74		MutexLock(&threadContext->sync.videoFrameMutex);
 75		ConditionWake(&threadContext->sync.videoFrameRequiredCond);
 76		MutexUnlock(&threadContext->sync.videoFrameMutex);
 77
 78		MutexLock(&threadContext->sync.audioBufferMutex);
 79		ConditionWake(&threadContext->sync.audioRequiredCond);
 80		MutexUnlock(&threadContext->sync.audioBufferMutex);
 81
 82		MutexLock(&threadContext->stateMutex);
 83		ConditionWake(&threadContext->stateCond);
 84	}
 85
 86	MutexLock(&threadContext->sync.videoFrameMutex);
 87	threadContext->sync.videoFrameWait = videoFrameWait;
 88	MutexUnlock(&threadContext->sync.videoFrameMutex);
 89}
 90
 91static void _pauseThread(struct GBAThread* threadContext, bool onThread) {
 92	threadContext->state = THREAD_PAUSING;
 93	if (!onThread) {
 94		_waitUntilNotState(threadContext, THREAD_PAUSING);
 95	}
 96}
 97
 98struct GBAThreadStop {
 99	struct GBAStopCallback d;
100	struct GBAThread* p;
101};
102
103static void _stopCallback(struct GBAStopCallback* stop) {
104	struct GBAThreadStop* callback = (struct GBAThreadStop*) stop;
105	if (callback->p->stopCallback(callback->p)) {
106		_changeState(callback->p, THREAD_EXITING, false);
107	}
108}
109
110static THREAD_ENTRY _GBAThreadRun(void* context) {
111#ifdef USE_PTHREADS
112	pthread_once(&_contextOnce, _createTLS);
113#elif _WIN32
114	InitOnceExecuteOnce(&_contextOnce, _createTLS, NULL, 0);
115#endif
116
117	struct GBA gba;
118	struct ARMCore cpu;
119	struct Patch patch;
120	struct GBACheatDevice cheatDevice;
121	struct GBAThread* threadContext = context;
122	struct ARMComponent* components[GBA_COMPONENT_MAX] = { 0 };
123	struct GBARRContext* movie = 0;
124	int numComponents = GBA_COMPONENT_MAX;
125
126	ThreadSetName("CPU Thread");
127
128#if !defined(_WIN32) && defined(USE_PTHREADS)
129	sigset_t signals;
130	sigemptyset(&signals);
131	pthread_sigmask(SIG_SETMASK, &signals, 0);
132#endif
133
134	GBACreate(&gba);
135	ARMSetComponents(&cpu, &gba.d, numComponents, components);
136	ARMInit(&cpu);
137	gba.sync = &threadContext->sync;
138	threadContext->gba = &gba;
139	threadContext->cpu = &cpu;
140	gba.logLevel = threadContext->logLevel;
141	gba.logHandler = threadContext->logHandler;
142	gba.stream = threadContext->stream;
143	gba.video.frameskip = threadContext->frameskip;
144
145	struct GBAThreadStop stop;
146	if (threadContext->stopCallback) {
147		stop.d.stop = _stopCallback;
148		stop.p = threadContext;
149		gba.stopCallback = &stop.d;
150	}
151
152	gba.idleOptimization = threadContext->idleOptimization;
153#ifdef USE_PTHREADS
154	pthread_setspecific(_contextKey, threadContext);
155#elif _WIN32
156	TlsSetValue(_contextKey, threadContext);
157#endif
158
159	if (threadContext->audioBuffers) {
160		GBAAudioResizeBuffer(&gba.audio, threadContext->audioBuffers);
161	} else {
162		threadContext->audioBuffers = GBA_AUDIO_SAMPLES;
163	}
164
165	if (threadContext->renderer) {
166		GBAVideoAssociateRenderer(&gba.video, threadContext->renderer);
167	}
168
169	if (threadContext->rom) {
170		GBALoadROM(&gba, threadContext->rom, threadContext->save, threadContext->fname);
171
172		struct GBACartridgeOverride override;
173		const struct GBACartridge* cart = (const struct GBACartridge*) gba.memory.rom;
174		memcpy(override.id, &cart->id, sizeof(override.id));
175		if (GBAOverrideFind(threadContext->overrides, &override)) {
176			GBAOverrideApply(&gba, &override);
177		}
178		if (threadContext->hasOverride) {
179			GBAOverrideApply(&gba, &threadContext->override);
180		}
181
182		if (threadContext->patch && loadPatch(threadContext->patch, &patch)) {
183			GBAApplyPatch(&gba, &patch);
184		}
185	}
186
187	if (threadContext->bios && GBAIsBIOS(threadContext->bios)) {
188		GBALoadBIOS(&gba, threadContext->bios);
189	}
190
191	if (threadContext->movie) {
192		struct VDir* movieDir = VDirOpen(threadContext->movie);
193#ifdef USE_LIBZIP
194		if (!movieDir) {
195			movieDir = VDirOpenZip(threadContext->movie, 0);
196		}
197#endif
198		if (movieDir) {
199			struct GBAMGMContext* mgm = malloc(sizeof(*mgm));
200			GBAMGMContextCreate(mgm);
201			if (!GBAMGMSetStream(mgm, movieDir)) {
202				mgm->d.destroy(&mgm->d);
203			} else {
204				movie = &mgm->d;
205			}
206		} else {
207			struct VFile* movieFile = VFileOpen(threadContext->movie, O_RDONLY);
208			if (movieFile) {
209				struct GBAVBMContext* vbm = malloc(sizeof(*vbm));
210				GBAVBMContextCreate(vbm);
211				if (!GBAVBMSetStream(vbm, movieFile)) {
212					vbm->d.destroy(&vbm->d);
213				} else {
214					movie = &vbm->d;
215				}
216			}
217		}
218	}
219
220	ARMReset(&cpu);
221
222	if (movie) {
223		gba.rr = movie;
224		movie->startPlaying(movie, false);
225		GBARRInitPlay(&gba);
226	}
227
228	if (threadContext->skipBios && gba.memory.rom) {
229		GBASkipBIOS(&cpu);
230	}
231
232	if (!threadContext->cheats) {
233		GBACheatDeviceCreate(&cheatDevice);
234		threadContext->cheats = &cheatDevice;
235	}
236	if (threadContext->cheatsFile) {
237		GBACheatParseFile(threadContext->cheats, threadContext->cheatsFile);
238	}
239	GBACheatAttachDevice(&gba, threadContext->cheats);
240
241	if (threadContext->debugger) {
242		threadContext->debugger->log = GBADebuggerLogShim;
243		GBAAttachDebugger(&gba, threadContext->debugger);
244		ARMDebuggerEnter(threadContext->debugger, DEBUGGER_ENTER_ATTACHED, 0);
245	}
246
247	GBASIOSetDriverSet(&gba.sio, &threadContext->sioDrivers);
248
249	if (threadContext->volume == 0) {
250		threadContext->volume = GBA_AUDIO_VOLUME_MAX;
251	}
252	if (threadContext->mute) {
253		gba.audio.masterVolume = 0;
254	} else {
255		gba.audio.masterVolume = threadContext->volume;
256	}
257
258	gba.keySource = &threadContext->activeKeys;
259
260	if (threadContext->startCallback) {
261		threadContext->startCallback(threadContext);
262	}
263
264	_changeState(threadContext, THREAD_RUNNING, true);
265
266	while (threadContext->state < THREAD_EXITING) {
267		if (threadContext->debugger) {
268			struct ARMDebugger* debugger = threadContext->debugger;
269			ARMDebuggerRun(debugger);
270			if (debugger->state == DEBUGGER_SHUTDOWN) {
271				_changeState(threadContext, THREAD_EXITING, false);
272			}
273		} else {
274			while (threadContext->state == THREAD_RUNNING) {
275				ARMRunLoop(&cpu);
276			}
277		}
278
279		int resetScheduled = 0;
280		MutexLock(&threadContext->stateMutex);
281		while (threadContext->state > THREAD_RUNNING && threadContext->state < THREAD_EXITING) {
282			if (threadContext->state == THREAD_PAUSING) {
283				threadContext->state = THREAD_PAUSED;
284				ConditionWake(&threadContext->stateCond);
285			}
286			if (threadContext->state == THREAD_INTERRUPTING) {
287				threadContext->state = THREAD_INTERRUPTED;
288				ConditionWake(&threadContext->stateCond);
289			}
290			if (threadContext->state == THREAD_RUN_ON) {
291				if (threadContext->run) {
292					threadContext->run(threadContext);
293				}
294				threadContext->state = threadContext->savedState;
295				ConditionWake(&threadContext->stateCond);
296			}
297			if (threadContext->state == THREAD_RESETING) {
298				threadContext->state = THREAD_RUNNING;
299				resetScheduled = 1;
300			}
301			while (threadContext->state == THREAD_PAUSED || threadContext->state == THREAD_INTERRUPTED) {
302				ConditionWait(&threadContext->stateCond, &threadContext->stateMutex);
303			}
304		}
305		MutexUnlock(&threadContext->stateMutex);
306		if (resetScheduled) {
307			ARMReset(&cpu);
308			if (threadContext->skipBios && gba.memory.rom) {
309				GBASkipBIOS(&cpu);
310			}
311		}
312	}
313
314	while (threadContext->state < THREAD_SHUTDOWN) {
315		_changeState(threadContext, THREAD_SHUTDOWN, false);
316	}
317
318	if (threadContext->cleanCallback) {
319		threadContext->cleanCallback(threadContext);
320	}
321
322	threadContext->gba = 0;
323	ARMDeinit(&cpu);
324	GBADestroy(&gba);
325	if (&cheatDevice == threadContext->cheats) {
326		GBACheatDeviceDestroy(&cheatDevice);
327	}
328
329	if (movie) {
330		movie->destroy(movie);
331		free(movie);
332	}
333
334	threadContext->sync.videoFrameOn = false;
335	ConditionWake(&threadContext->sync.videoFrameAvailableCond);
336	ConditionWake(&threadContext->sync.audioRequiredCond);
337
338	return 0;
339}
340
341void GBAMapOptionsToContext(const struct GBAOptions* opts, struct GBAThread* threadContext) {
342	if (opts->useBios) {
343		threadContext->bios = VFileOpen(opts->bios, O_RDONLY);
344	} else {
345		threadContext->bios = 0;
346	}
347	threadContext->frameskip = opts->frameskip;
348	threadContext->volume = opts->volume;
349	threadContext->mute = opts->mute;
350	threadContext->logLevel = opts->logLevel;
351	if (opts->rewindEnable) {
352		threadContext->rewindBufferCapacity = opts->rewindBufferCapacity;
353		threadContext->rewindBufferInterval = opts->rewindBufferInterval;
354	} else {
355		threadContext->rewindBufferCapacity = 0;
356	}
357	threadContext->skipBios = opts->skipBios;
358	threadContext->sync.audioWait = opts->audioSync;
359	threadContext->sync.videoFrameWait = opts->videoSync;
360
361	if (opts->fpsTarget) {
362		threadContext->fpsTarget = opts->fpsTarget;
363	}
364
365	if (opts->audioBuffers) {
366		threadContext->audioBuffers = opts->audioBuffers;
367	}
368
369	threadContext->idleOptimization = opts->idleOptimization;
370}
371
372void GBAMapArgumentsToContext(const struct GBAArguments* args, struct GBAThread* threadContext) {
373	if (args->dirmode) {
374		threadContext->gameDir = VDirOpen(args->fname);
375		threadContext->stateDir = threadContext->gameDir;
376	} else {
377		GBAThreadLoadROM(threadContext, args->fname);
378	}
379	threadContext->fname = args->fname;
380	threadContext->patch = VFileOpen(args->patch, O_RDONLY);
381	threadContext->cheatsFile = VFileOpen(args->cheatsFile, O_RDONLY);
382	threadContext->movie = args->movie;
383}
384
385bool GBAThreadStart(struct GBAThread* threadContext) {
386	// TODO: error check
387	threadContext->activeKeys = 0;
388	threadContext->state = THREAD_INITIALIZED;
389	threadContext->sync.videoFrameOn = true;
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		_loadGameDir(threadContext);
412	}
413
414	if (!threadContext->rom && !bootBios) {
415		threadContext->state = THREAD_SHUTDOWN;
416		return false;
417	}
418
419	threadContext->save = VDirOptionalOpenFile(threadContext->stateDir, threadContext->fname, "sram", ".sav", O_CREAT | O_RDWR);
420
421	if (!threadContext->patch) {
422		threadContext->patch = VDirOptionalOpenFile(threadContext->stateDir, threadContext->fname, "patch", ".ups", O_RDONLY);
423	}
424	if (!threadContext->patch) {
425		threadContext->patch = VDirOptionalOpenFile(threadContext->stateDir, threadContext->fname, "patch", ".ips", O_RDONLY);
426	}
427	if (!threadContext->patch) {
428		threadContext->patch = VDirOptionalOpenFile(threadContext->stateDir, threadContext->fname, "patch", ".bps", O_RDONLY);
429	}
430
431	MutexInit(&threadContext->stateMutex);
432	ConditionInit(&threadContext->stateCond);
433
434	MutexInit(&threadContext->sync.videoFrameMutex);
435	ConditionInit(&threadContext->sync.videoFrameAvailableCond);
436	ConditionInit(&threadContext->sync.videoFrameRequiredCond);
437	MutexInit(&threadContext->sync.audioBufferMutex);
438	ConditionInit(&threadContext->sync.audioRequiredCond);
439
440	threadContext->interruptDepth = 0;
441
442#ifdef USE_PTHREADS
443	sigset_t signals;
444	sigemptyset(&signals);
445	sigaddset(&signals, SIGINT);
446	sigaddset(&signals, SIGTRAP);
447	pthread_sigmask(SIG_BLOCK, &signals, 0);
448#endif
449
450	MutexLock(&threadContext->stateMutex);
451	ThreadCreate(&threadContext->thread, _GBAThreadRun, threadContext);
452	while (threadContext->state < THREAD_RUNNING) {
453		ConditionWait(&threadContext->stateCond, &threadContext->stateMutex);
454	}
455	MutexUnlock(&threadContext->stateMutex);
456
457	return true;
458}
459
460bool GBAThreadHasStarted(struct GBAThread* threadContext) {
461	bool hasStarted;
462	MutexLock(&threadContext->stateMutex);
463	hasStarted = threadContext->state > THREAD_INITIALIZED;
464	MutexUnlock(&threadContext->stateMutex);
465	return hasStarted;
466}
467
468bool GBAThreadHasExited(struct GBAThread* threadContext) {
469	bool hasExited;
470	MutexLock(&threadContext->stateMutex);
471	hasExited = threadContext->state > THREAD_EXITING;
472	MutexUnlock(&threadContext->stateMutex);
473	return hasExited;
474}
475
476bool GBAThreadHasCrashed(struct GBAThread* threadContext) {
477	bool hasExited;
478	MutexLock(&threadContext->stateMutex);
479	hasExited = threadContext->state == THREAD_CRASHED;
480	MutexUnlock(&threadContext->stateMutex);
481	return hasExited;
482}
483
484void GBAThreadEnd(struct GBAThread* threadContext) {
485	MutexLock(&threadContext->stateMutex);
486	_waitOnInterrupt(threadContext);
487	threadContext->state = THREAD_EXITING;
488	if (threadContext->gba) {
489		threadContext->gba->cpu->halted = false;
490	}
491	ConditionWake(&threadContext->stateCond);
492	MutexUnlock(&threadContext->stateMutex);
493	MutexLock(&threadContext->sync.audioBufferMutex);
494	threadContext->sync.audioWait = 0;
495	ConditionWake(&threadContext->sync.audioRequiredCond);
496	MutexUnlock(&threadContext->sync.audioBufferMutex);
497
498	MutexLock(&threadContext->sync.videoFrameMutex);
499	threadContext->sync.videoFrameWait = false;
500	threadContext->sync.videoFrameOn = false;
501	ConditionWake(&threadContext->sync.videoFrameRequiredCond);
502	ConditionWake(&threadContext->sync.videoFrameAvailableCond);
503	MutexUnlock(&threadContext->sync.videoFrameMutex);
504}
505
506void GBAThreadReset(struct GBAThread* threadContext) {
507	MutexLock(&threadContext->stateMutex);
508	_waitOnInterrupt(threadContext);
509	threadContext->state = THREAD_RESETING;
510	ConditionWake(&threadContext->stateCond);
511	MutexUnlock(&threadContext->stateMutex);
512}
513
514void GBAThreadJoin(struct GBAThread* threadContext) {
515	ThreadJoin(threadContext->thread);
516
517	MutexDeinit(&threadContext->stateMutex);
518	ConditionDeinit(&threadContext->stateCond);
519
520	MutexDeinit(&threadContext->sync.videoFrameMutex);
521	ConditionWake(&threadContext->sync.videoFrameAvailableCond);
522	ConditionDeinit(&threadContext->sync.videoFrameAvailableCond);
523	ConditionWake(&threadContext->sync.videoFrameRequiredCond);
524	ConditionDeinit(&threadContext->sync.videoFrameRequiredCond);
525
526	ConditionWake(&threadContext->sync.audioRequiredCond);
527	ConditionDeinit(&threadContext->sync.audioRequiredCond);
528	MutexDeinit(&threadContext->sync.audioBufferMutex);
529
530	int i;
531	for (i = 0; i < threadContext->rewindBufferCapacity; ++i) {
532		if (threadContext->rewindBuffer[i]) {
533			GBADeallocateState(threadContext->rewindBuffer[i]);
534		}
535	}
536	free(threadContext->rewindBuffer);
537	free(threadContext->rewindScreenBuffer);
538
539	if (threadContext->rom) {
540		threadContext->rom->close(threadContext->rom);
541		threadContext->rom = 0;
542	}
543
544	if (threadContext->save) {
545		threadContext->save->close(threadContext->save);
546		threadContext->save = 0;
547	}
548
549	if (threadContext->bios) {
550		threadContext->bios->close(threadContext->bios);
551		threadContext->bios = 0;
552	}
553
554	if (threadContext->patch) {
555		threadContext->patch->close(threadContext->patch);
556		threadContext->patch = 0;
557	}
558
559	if (threadContext->gameDir) {
560		if (threadContext->stateDir == threadContext->gameDir) {
561			threadContext->stateDir = 0;
562		}
563		threadContext->gameDir->close(threadContext->gameDir);
564		threadContext->gameDir = 0;
565	}
566
567	if (threadContext->stateDir) {
568		threadContext->stateDir->close(threadContext->stateDir);
569		threadContext->stateDir = 0;
570	}
571}
572
573bool GBAThreadIsActive(struct GBAThread* threadContext) {
574	return threadContext->state >= THREAD_RUNNING && threadContext->state < THREAD_EXITING;
575}
576
577void GBAThreadInterrupt(struct GBAThread* threadContext) {
578	MutexLock(&threadContext->stateMutex);
579	++threadContext->interruptDepth;
580	if (threadContext->interruptDepth > 1 || !GBAThreadIsActive(threadContext)) {
581		MutexUnlock(&threadContext->stateMutex);
582		return;
583	}
584	threadContext->savedState = threadContext->state;
585	_waitOnInterrupt(threadContext);
586	threadContext->state = THREAD_INTERRUPTING;
587	threadContext->gba->cpu->nextEvent = 0;
588	ConditionWake(&threadContext->stateCond);
589	_waitUntilNotState(threadContext, THREAD_INTERRUPTING);
590	MutexUnlock(&threadContext->stateMutex);
591}
592
593void GBAThreadContinue(struct GBAThread* threadContext) {
594	MutexLock(&threadContext->stateMutex);
595	--threadContext->interruptDepth;
596	if (threadContext->interruptDepth < 1 && GBAThreadIsActive(threadContext)) {
597		threadContext->state = threadContext->savedState;
598		ConditionWake(&threadContext->stateCond);
599	}
600	MutexUnlock(&threadContext->stateMutex);
601}
602
603void GBARunOnThread(struct GBAThread* threadContext, void (*run)(struct GBAThread*)) {
604	MutexLock(&threadContext->stateMutex);
605	threadContext->run = run;
606	_waitOnInterrupt(threadContext);
607	threadContext->savedState = threadContext->state;
608	threadContext->state = THREAD_RUN_ON;
609	threadContext->gba->cpu->nextEvent = 0;
610	ConditionWake(&threadContext->stateCond);
611	_waitUntilNotState(threadContext, THREAD_RUN_ON);
612	MutexUnlock(&threadContext->stateMutex);
613}
614
615void GBAThreadPause(struct GBAThread* threadContext) {
616	bool frameOn = threadContext->sync.videoFrameOn;
617	MutexLock(&threadContext->stateMutex);
618	_waitOnInterrupt(threadContext);
619	if (threadContext->state == THREAD_RUNNING) {
620		_pauseThread(threadContext, false);
621		threadContext->frameWasOn = frameOn;
622		frameOn = false;
623	}
624	MutexUnlock(&threadContext->stateMutex);
625
626	GBASyncSetVideoSync(&threadContext->sync, frameOn);
627}
628
629void GBAThreadUnpause(struct GBAThread* threadContext) {
630	bool frameOn = threadContext->sync.videoFrameOn;
631	MutexLock(&threadContext->stateMutex);
632	_waitOnInterrupt(threadContext);
633	if (threadContext->state == THREAD_PAUSED || threadContext->state == THREAD_PAUSING) {
634		threadContext->state = THREAD_RUNNING;
635		ConditionWake(&threadContext->stateCond);
636		frameOn = threadContext->frameWasOn;
637	}
638	MutexUnlock(&threadContext->stateMutex);
639
640	GBASyncSetVideoSync(&threadContext->sync, frameOn);
641}
642
643bool GBAThreadIsPaused(struct GBAThread* threadContext) {
644	bool isPaused;
645	MutexLock(&threadContext->stateMutex);
646	_waitOnInterrupt(threadContext);
647	isPaused = threadContext->state == THREAD_PAUSED;
648	MutexUnlock(&threadContext->stateMutex);
649	return isPaused;
650}
651
652void GBAThreadTogglePause(struct GBAThread* threadContext) {
653	bool frameOn = threadContext->sync.videoFrameOn;
654	MutexLock(&threadContext->stateMutex);
655	_waitOnInterrupt(threadContext);
656	if (threadContext->state == THREAD_PAUSED || threadContext->state == THREAD_PAUSING) {
657		threadContext->state = THREAD_RUNNING;
658		ConditionWake(&threadContext->stateCond);
659		frameOn = threadContext->frameWasOn;
660	} else if (threadContext->state == THREAD_RUNNING) {
661		_pauseThread(threadContext, false);
662		threadContext->frameWasOn = frameOn;
663		frameOn = false;
664	}
665	MutexUnlock(&threadContext->stateMutex);
666
667	GBASyncSetVideoSync(&threadContext->sync, frameOn);
668}
669
670void GBAThreadPauseFromThread(struct GBAThread* threadContext) {
671	bool frameOn = true;
672	MutexLock(&threadContext->stateMutex);
673	_waitOnInterrupt(threadContext);
674	if (threadContext->state == THREAD_RUNNING) {
675		_pauseThread(threadContext, true);
676		frameOn = false;
677	}
678	MutexUnlock(&threadContext->stateMutex);
679
680	GBASyncSetVideoSync(&threadContext->sync, frameOn);
681}
682
683void GBAThreadLoadROM(struct GBAThread* threadContext, const char* fname) {
684	threadContext->rom = VFileOpen(fname, O_RDONLY);
685	threadContext->gameDir = 0;
686	if (!threadContext->gameDir) {
687		threadContext->gameDir = VDirOpenArchive(fname);
688	}
689}
690
691static void _loadGameDir(struct GBAThread* threadContext) {
692	threadContext->gameDir->rewind(threadContext->gameDir);
693	struct VDirEntry* dirent = threadContext->gameDir->listNext(threadContext->gameDir);
694	while (dirent) {
695		struct Patch patchTemp;
696		struct VFile* vf = threadContext->gameDir->openFile(threadContext->gameDir, dirent->name(dirent), O_RDONLY);
697		if (!vf) {
698			dirent = threadContext->gameDir->listNext(threadContext->gameDir);
699			continue;
700		}
701		if (!threadContext->rom && GBAIsROM(vf)) {
702			threadContext->rom = vf;
703		} else if (!threadContext->patch && loadPatch(vf, &patchTemp)) {
704			threadContext->patch = vf;
705		} else {
706			vf->close(vf);
707		}
708		dirent = threadContext->gameDir->listNext(threadContext->gameDir);
709	}
710}
711
712void GBAThreadReplaceROM(struct GBAThread* threadContext, const char* fname) {
713	GBAUnloadROM(threadContext->gba);
714
715	if (threadContext->rom) {
716		threadContext->rom->close(threadContext->rom);
717		threadContext->rom = 0;
718	}
719
720	if (threadContext->save) {
721		threadContext->save->close(threadContext->save);
722		threadContext->save = 0;
723	}
724
725	GBAThreadLoadROM(threadContext, fname);
726	if (threadContext->gameDir) {
727		_loadGameDir(threadContext);
728	}
729
730	threadContext->fname = fname;
731	threadContext->save = VDirOptionalOpenFile(threadContext->stateDir, threadContext->fname, "sram", ".sav", O_CREAT | O_RDWR);
732
733	GBARaiseIRQ(threadContext->gba, IRQ_GAMEPAK);
734	GBALoadROM(threadContext->gba, threadContext->rom, threadContext->save, threadContext->fname);
735}
736
737#ifdef USE_PTHREADS
738struct GBAThread* GBAThreadGetContext(void) {
739	pthread_once(&_contextOnce, _createTLS);
740	return pthread_getspecific(_contextKey);
741}
742#elif _WIN32
743struct GBAThread* GBAThreadGetContext(void) {
744	InitOnceExecuteOnce(&_contextOnce, _createTLS, NULL, 0);
745	return TlsGetValue(_contextKey);
746}
747#endif
748
749void GBAThreadTakeScreenshot(struct GBAThread* threadContext) {
750	GBATakeScreenshot(threadContext->gba, threadContext->stateDir);
751}
752
753#else
754struct GBAThread* GBAThreadGetContext(void) {
755	return 0;
756}
757#endif