all repos — mgba @ a623bcadc3933fcd21c31376b3ccc0264efa40fc

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
144	struct GBAThreadStop stop;
145	if (threadContext->stopCallback) {
146		stop.d.stop = _stopCallback;
147		stop.p = threadContext;
148		gba.stopCallback = &stop.d;
149	}
150
151	gba.idleOptimization = threadContext->idleOptimization;
152#ifdef USE_PTHREADS
153	pthread_setspecific(_contextKey, threadContext);
154#elif _WIN32
155	TlsSetValue(_contextKey, threadContext);
156#endif
157
158	if (threadContext->audioBuffers) {
159		GBAAudioResizeBuffer(&gba.audio, threadContext->audioBuffers);
160	} else {
161		threadContext->audioBuffers = GBA_AUDIO_SAMPLES;
162	}
163
164	if (threadContext->renderer) {
165		GBAVideoAssociateRenderer(&gba.video, threadContext->renderer);
166	}
167
168	if (threadContext->rom) {
169		GBALoadROM(&gba, threadContext->rom, threadContext->save, threadContext->fname);
170
171		struct GBACartridgeOverride override;
172		const struct GBACartridge* cart = (const struct GBACartridge*) gba.memory.rom;
173		memcpy(override.id, &cart->id, sizeof(override.id));
174		if (GBAOverrideFind(threadContext->overrides, &override)) {
175			GBAOverrideApply(&gba, &override);
176		}
177		if (threadContext->hasOverride) {
178			GBAOverrideApply(&gba, &threadContext->override);
179		}
180
181		if (threadContext->patch && loadPatch(threadContext->patch, &patch)) {
182			GBAApplyPatch(&gba, &patch);
183		}
184	}
185
186	if (threadContext->bios && GBAIsBIOS(threadContext->bios)) {
187		GBALoadBIOS(&gba, threadContext->bios);
188	}
189
190	if (threadContext->movie) {
191		struct VDir* movieDir = VDirOpen(threadContext->movie);
192#ifdef USE_LIBZIP
193		if (!movieDir) {
194			movieDir = VDirOpenZip(threadContext->movie, 0);
195		}
196#endif
197		if (movieDir) {
198			struct GBAMGMContext* mgm = malloc(sizeof(*mgm));
199			GBAMGMContextCreate(mgm);
200			if (!GBAMGMSetStream(mgm, movieDir)) {
201				mgm->d.destroy(&mgm->d);
202			} else {
203				movie = &mgm->d;
204			}
205		} else {
206			struct VFile* movieFile = VFileOpen(threadContext->movie, O_RDONLY);
207			if (movieFile) {
208				struct GBAVBMContext* vbm = malloc(sizeof(*vbm));
209				GBAVBMContextCreate(vbm);
210				if (!GBAVBMSetStream(vbm, movieFile)) {
211					vbm->d.destroy(&vbm->d);
212				} else {
213					movie = &vbm->d;
214				}
215			}
216		}
217	}
218
219	ARMReset(&cpu);
220
221	if (movie) {
222		gba.rr = movie;
223		movie->startPlaying(movie, false);
224		GBARRInitPlay(&gba);
225	}
226
227	if (threadContext->skipBios && gba.memory.rom) {
228		GBASkipBIOS(&cpu);
229	}
230
231	if (!threadContext->cheats) {
232		GBACheatDeviceCreate(&cheatDevice);
233		threadContext->cheats = &cheatDevice;
234	}
235	if (threadContext->cheatsFile) {
236		GBACheatParseFile(threadContext->cheats, threadContext->cheatsFile);
237	}
238	GBACheatAttachDevice(&gba, threadContext->cheats);
239
240	if (threadContext->debugger) {
241		threadContext->debugger->log = GBADebuggerLogShim;
242		GBAAttachDebugger(&gba, threadContext->debugger);
243		ARMDebuggerEnter(threadContext->debugger, DEBUGGER_ENTER_ATTACHED, 0);
244	}
245
246	GBASIOSetDriverSet(&gba.sio, &threadContext->sioDrivers);
247
248	if (threadContext->volume == 0) {
249		threadContext->volume = GBA_AUDIO_VOLUME_MAX;
250	}
251	if (threadContext->mute) {
252		gba.audio.masterVolume = 0;
253	} else {
254		gba.audio.masterVolume = threadContext->volume;
255	}
256
257	gba.keySource = &threadContext->activeKeys;
258
259	if (threadContext->startCallback) {
260		threadContext->startCallback(threadContext);
261	}
262
263	_changeState(threadContext, THREAD_RUNNING, true);
264
265	while (threadContext->state < THREAD_EXITING) {
266		if (threadContext->debugger) {
267			struct ARMDebugger* debugger = threadContext->debugger;
268			ARMDebuggerRun(debugger);
269			if (debugger->state == DEBUGGER_SHUTDOWN) {
270				_changeState(threadContext, THREAD_EXITING, false);
271			}
272		} else {
273			while (threadContext->state == THREAD_RUNNING) {
274				ARMRunLoop(&cpu);
275			}
276		}
277
278		int resetScheduled = 0;
279		MutexLock(&threadContext->stateMutex);
280		while (threadContext->state > THREAD_RUNNING && threadContext->state < THREAD_EXITING) {
281			if (threadContext->state == THREAD_PAUSING) {
282				threadContext->state = THREAD_PAUSED;
283				ConditionWake(&threadContext->stateCond);
284			}
285			if (threadContext->state == THREAD_INTERRUPTING) {
286				threadContext->state = THREAD_INTERRUPTED;
287				ConditionWake(&threadContext->stateCond);
288			}
289			if (threadContext->state == THREAD_RUN_ON) {
290				if (threadContext->run) {
291					threadContext->run(threadContext);
292				}
293				threadContext->state = threadContext->savedState;
294				ConditionWake(&threadContext->stateCond);
295			}
296			if (threadContext->state == THREAD_RESETING) {
297				threadContext->state = THREAD_RUNNING;
298				resetScheduled = 1;
299			}
300			while (threadContext->state == THREAD_PAUSED || threadContext->state == THREAD_INTERRUPTED) {
301				ConditionWait(&threadContext->stateCond, &threadContext->stateMutex);
302			}
303		}
304		MutexUnlock(&threadContext->stateMutex);
305		if (resetScheduled) {
306			ARMReset(&cpu);
307			if (threadContext->skipBios && gba.memory.rom) {
308				GBASkipBIOS(&cpu);
309			}
310		}
311	}
312
313	while (threadContext->state < THREAD_SHUTDOWN) {
314		_changeState(threadContext, THREAD_SHUTDOWN, false);
315	}
316
317	if (threadContext->cleanCallback) {
318		threadContext->cleanCallback(threadContext);
319	}
320
321	threadContext->gba = 0;
322	ARMDeinit(&cpu);
323	GBADestroy(&gba);
324	if (&cheatDevice == threadContext->cheats) {
325		GBACheatDeviceDestroy(&cheatDevice);
326	}
327
328	if (movie) {
329		movie->destroy(movie);
330		free(movie);
331	}
332
333	threadContext->sync.videoFrameOn = false;
334	ConditionWake(&threadContext->sync.videoFrameAvailableCond);
335	ConditionWake(&threadContext->sync.audioRequiredCond);
336
337	return 0;
338}
339
340void GBAMapOptionsToContext(const struct GBAOptions* opts, struct GBAThread* threadContext) {
341	if (opts->useBios) {
342		threadContext->bios = VFileOpen(opts->bios, O_RDONLY);
343	} else {
344		threadContext->bios = 0;
345	}
346	threadContext->frameskip = opts->frameskip;
347	threadContext->volume = opts->volume;
348	threadContext->mute = opts->mute;
349	threadContext->logLevel = opts->logLevel;
350	if (opts->rewindEnable) {
351		threadContext->rewindBufferCapacity = opts->rewindBufferCapacity;
352		threadContext->rewindBufferInterval = opts->rewindBufferInterval;
353	} else {
354		threadContext->rewindBufferCapacity = 0;
355	}
356	threadContext->skipBios = opts->skipBios;
357	threadContext->sync.audioWait = opts->audioSync;
358	threadContext->sync.videoFrameWait = opts->videoSync;
359
360	if (opts->fpsTarget) {
361		threadContext->fpsTarget = opts->fpsTarget;
362	}
363
364	if (opts->audioBuffers) {
365		threadContext->audioBuffers = opts->audioBuffers;
366	}
367
368	threadContext->idleOptimization = opts->idleOptimization;
369}
370
371void GBAMapArgumentsToContext(const struct GBAArguments* args, struct GBAThread* threadContext) {
372	if (args->dirmode) {
373		threadContext->gameDir = VDirOpen(args->fname);
374		threadContext->stateDir = threadContext->gameDir;
375	} else {
376		GBAThreadLoadROM(threadContext, args->fname);
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		_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 USE_LIBZIP
687	if (!threadContext->gameDir) {
688		threadContext->gameDir = VDirOpenZip(fname, 0);
689	}
690#endif
691#if USE_LZMA
692	if (!threadContext->gameDir) {
693		threadContext->gameDir = VDirOpen7z(fname, 0);
694	}
695#endif
696}
697
698static void _loadGameDir(struct GBAThread* threadContext) {
699	threadContext->gameDir->rewind(threadContext->gameDir);
700	struct VDirEntry* dirent = threadContext->gameDir->listNext(threadContext->gameDir);
701	while (dirent) {
702		struct Patch patchTemp;
703		struct VFile* vf = threadContext->gameDir->openFile(threadContext->gameDir, dirent->name(dirent), O_RDONLY);
704		if (!vf) {
705			dirent = threadContext->gameDir->listNext(threadContext->gameDir);
706			continue;
707		}
708		if (!threadContext->rom && GBAIsROM(vf)) {
709			threadContext->rom = vf;
710		} else if (!threadContext->patch && loadPatch(vf, &patchTemp)) {
711			threadContext->patch = vf;
712		} else {
713			vf->close(vf);
714		}
715		dirent = threadContext->gameDir->listNext(threadContext->gameDir);
716	}
717}
718
719void GBAThreadReplaceROM(struct GBAThread* threadContext, const char* fname) {
720	GBAUnloadROM(threadContext->gba);
721
722	if (threadContext->rom) {
723		threadContext->rom->close(threadContext->rom);
724		threadContext->rom = 0;
725	}
726
727	if (threadContext->save) {
728		threadContext->save->close(threadContext->save);
729		threadContext->save = 0;
730	}
731
732	GBAThreadLoadROM(threadContext, fname);
733	if (threadContext->gameDir) {
734		_loadGameDir(threadContext);
735	}
736
737	threadContext->fname = fname;
738	threadContext->save = VDirOptionalOpenFile(threadContext->stateDir, threadContext->fname, "sram", ".sav", O_CREAT | O_RDWR);
739
740	GBARaiseIRQ(threadContext->gba, IRQ_GAMEPAK);
741	GBALoadROM(threadContext->gba, threadContext->rom, threadContext->save, threadContext->fname);
742}
743
744#ifdef USE_PTHREADS
745struct GBAThread* GBAThreadGetContext(void) {
746	pthread_once(&_contextOnce, _createTLS);
747	return pthread_getspecific(_contextKey);
748}
749#elif _WIN32
750struct GBAThread* GBAThreadGetContext(void) {
751	InitOnceExecuteOnce(&_contextOnce, _createTLS, NULL, 0);
752	return TlsGetValue(_contextKey);
753}
754#endif
755
756void GBAThreadTakeScreenshot(struct GBAThread* threadContext) {
757	GBATakeScreenshot(threadContext->gba, threadContext->stateDir);
758}
759
760#else
761struct GBAThread* GBAThreadGetContext(void) {
762	return 0;
763}
764#endif