all repos — mgba @ 3a9ac188d40abee8689126bc0bf1a5b85054f625

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 void _loadGameDir(struct GBAThread* threadContext);
 27
 28static const float _defaultFPSTarget = 60.f;
 29
 30#ifndef DISABLE_THREADING
 31#ifdef USE_PTHREADS
 32static pthread_key_t _contextKey;
 33static pthread_once_t _contextOnce = PTHREAD_ONCE_INIT;
 34
 35static void _createTLS(void) {
 36	pthread_key_create(&_contextKey, 0);
 37}
 38#elif _WIN32
 39static DWORD _contextKey;
 40static INIT_ONCE _contextOnce = INIT_ONCE_STATIC_INIT;
 41
 42static BOOL CALLBACK _createTLS(PINIT_ONCE once, PVOID param, PVOID* context) {
 43	UNUSED(once);
 44	UNUSED(param);
 45	UNUSED(context);
 46	_contextKey = TlsAlloc();
 47	return TRUE;
 48}
 49#endif
 50
 51static void _changeState(struct GBAThread* threadContext, enum ThreadState newState, bool broadcast) {
 52	MutexLock(&threadContext->stateMutex);
 53	threadContext->state = newState;
 54	if (broadcast) {
 55		ConditionWake(&threadContext->stateCond);
 56	}
 57	MutexUnlock(&threadContext->stateMutex);
 58}
 59
 60static void _waitOnInterrupt(struct GBAThread* threadContext) {
 61	while (threadContext->state == THREAD_INTERRUPTED) {
 62		ConditionWait(&threadContext->stateCond, &threadContext->stateMutex);
 63	}
 64}
 65
 66static void _waitUntilNotState(struct GBAThread* threadContext, enum ThreadState oldState) {
 67	MutexLock(&threadContext->sync.videoFrameMutex);
 68	bool videoFrameWait = threadContext->sync.videoFrameWait;
 69	threadContext->sync.videoFrameWait = false;
 70	MutexUnlock(&threadContext->sync.videoFrameMutex);
 71
 72	while (threadContext->state == oldState) {
 73		MutexUnlock(&threadContext->stateMutex);
 74
 75		MutexLock(&threadContext->sync.videoFrameMutex);
 76		ConditionWake(&threadContext->sync.videoFrameRequiredCond);
 77		MutexUnlock(&threadContext->sync.videoFrameMutex);
 78
 79		MutexLock(&threadContext->sync.audioBufferMutex);
 80		ConditionWake(&threadContext->sync.audioRequiredCond);
 81		MutexUnlock(&threadContext->sync.audioBufferMutex);
 82
 83		MutexLock(&threadContext->stateMutex);
 84		ConditionWake(&threadContext->stateCond);
 85	}
 86
 87	MutexLock(&threadContext->sync.videoFrameMutex);
 88	threadContext->sync.videoFrameWait = videoFrameWait;
 89	MutexUnlock(&threadContext->sync.videoFrameMutex);
 90}
 91
 92static void _pauseThread(struct GBAThread* threadContext, bool onThread) {
 93	threadContext->state = THREAD_PAUSING;
 94	if (!onThread) {
 95		_waitUntilNotState(threadContext, THREAD_PAUSING);
 96	}
 97}
 98
 99struct GBAThreadStop {
100	struct GBAStopCallback d;
101	struct GBAThread* p;
102};
103
104static void _stopCallback(struct GBAStopCallback* stop) {
105	struct GBAThreadStop* callback = (struct GBAThreadStop*) stop;
106	if (callback->p->stopCallback(callback->p)) {
107		_changeState(callback->p, THREAD_EXITING, false);
108	}
109}
110
111static THREAD_ENTRY _GBAThreadRun(void* context) {
112#ifdef USE_PTHREADS
113	pthread_once(&_contextOnce, _createTLS);
114#elif _WIN32
115	InitOnceExecuteOnce(&_contextOnce, _createTLS, NULL, 0);
116#endif
117
118	struct GBA gba;
119	struct ARMCore cpu;
120	struct Patch patch;
121	struct GBACheatDevice cheatDevice;
122	struct GBAThread* threadContext = context;
123	struct ARMComponent* components[GBA_COMPONENT_MAX] = { 0 };
124	struct GBARRContext* movie = 0;
125	int numComponents = GBA_COMPONENT_MAX;
126
127	ThreadSetName("CPU Thread");
128
129#if !defined(_WIN32) && defined(USE_PTHREADS)
130	sigset_t signals;
131	sigemptyset(&signals);
132	pthread_sigmask(SIG_SETMASK, &signals, 0);
133#endif
134
135	GBACreate(&gba);
136	ARMSetComponents(&cpu, &gba.d, numComponents, components);
137	ARMInit(&cpu);
138	gba.sync = &threadContext->sync;
139	threadContext->gba = &gba;
140	threadContext->cpu = &cpu;
141	gba.logLevel = threadContext->logLevel;
142	gba.logHandler = threadContext->logHandler;
143	gba.stream = threadContext->stream;
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) {
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) {
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	threadContext->sync.videoFrameSkip = 0;
391
392	threadContext->rewindBuffer = 0;
393	threadContext->rewindScreenBuffer = 0;
394	int newCapacity = threadContext->rewindBufferCapacity;
395	int newInterval = threadContext->rewindBufferInterval;
396	threadContext->rewindBufferCapacity = 0;
397	threadContext->rewindBufferInterval = 0;
398	GBARewindSettingsChanged(threadContext, newCapacity, newInterval);
399
400	if (!threadContext->fpsTarget) {
401		threadContext->fpsTarget = _defaultFPSTarget;
402	}
403
404	bool bootBios = threadContext->bootBios && threadContext->bios;
405
406	if (threadContext->rom && (!GBAIsROM(threadContext->rom) || bootBios)) {
407		threadContext->rom->close(threadContext->rom);
408		threadContext->rom = 0;
409	}
410
411	if (threadContext->gameDir) {
412		_loadGameDir(threadContext);
413	}
414
415	if (!threadContext->rom && !bootBios) {
416		threadContext->state = THREAD_SHUTDOWN;
417		return false;
418	}
419
420	threadContext->save = VDirOptionalOpenFile(threadContext->stateDir, threadContext->fname, "sram", ".sav", O_CREAT | O_RDWR);
421
422	if (!threadContext->patch) {
423		threadContext->patch = VDirOptionalOpenFile(threadContext->stateDir, threadContext->fname, "patch", ".ups", O_RDONLY);
424	}
425	if (!threadContext->patch) {
426		threadContext->patch = VDirOptionalOpenFile(threadContext->stateDir, threadContext->fname, "patch", ".ips", O_RDONLY);
427	}
428	if (!threadContext->patch) {
429		threadContext->patch = VDirOptionalOpenFile(threadContext->stateDir, threadContext->fname, "patch", ".bps", O_RDONLY);
430	}
431
432	MutexInit(&threadContext->stateMutex);
433	ConditionInit(&threadContext->stateCond);
434
435	MutexInit(&threadContext->sync.videoFrameMutex);
436	ConditionInit(&threadContext->sync.videoFrameAvailableCond);
437	ConditionInit(&threadContext->sync.videoFrameRequiredCond);
438	MutexInit(&threadContext->sync.audioBufferMutex);
439	ConditionInit(&threadContext->sync.audioRequiredCond);
440
441	threadContext->interruptDepth = 0;
442
443#ifdef USE_PTHREADS
444	sigset_t signals;
445	sigemptyset(&signals);
446	sigaddset(&signals, SIGINT);
447	sigaddset(&signals, SIGTRAP);
448	pthread_sigmask(SIG_BLOCK, &signals, 0);
449#endif
450
451	MutexLock(&threadContext->stateMutex);
452	ThreadCreate(&threadContext->thread, _GBAThreadRun, threadContext);
453	while (threadContext->state < THREAD_RUNNING) {
454		ConditionWait(&threadContext->stateCond, &threadContext->stateMutex);
455	}
456	MutexUnlock(&threadContext->stateMutex);
457
458	return true;
459}
460
461bool GBAThreadHasStarted(struct GBAThread* threadContext) {
462	bool hasStarted;
463	MutexLock(&threadContext->stateMutex);
464	hasStarted = threadContext->state > THREAD_INITIALIZED;
465	MutexUnlock(&threadContext->stateMutex);
466	return hasStarted;
467}
468
469bool GBAThreadHasExited(struct GBAThread* threadContext) {
470	bool hasExited;
471	MutexLock(&threadContext->stateMutex);
472	hasExited = threadContext->state > THREAD_EXITING;
473	MutexUnlock(&threadContext->stateMutex);
474	return hasExited;
475}
476
477bool GBAThreadHasCrashed(struct GBAThread* threadContext) {
478	bool hasExited;
479	MutexLock(&threadContext->stateMutex);
480	hasExited = threadContext->state == THREAD_CRASHED;
481	MutexUnlock(&threadContext->stateMutex);
482	return hasExited;
483}
484
485void GBAThreadEnd(struct GBAThread* threadContext) {
486	MutexLock(&threadContext->stateMutex);
487	_waitOnInterrupt(threadContext);
488	threadContext->state = THREAD_EXITING;
489	if (threadContext->gba) {
490		threadContext->gba->cpu->halted = false;
491	}
492	ConditionWake(&threadContext->stateCond);
493	MutexUnlock(&threadContext->stateMutex);
494	MutexLock(&threadContext->sync.audioBufferMutex);
495	threadContext->sync.audioWait = 0;
496	ConditionWake(&threadContext->sync.audioRequiredCond);
497	MutexUnlock(&threadContext->sync.audioBufferMutex);
498
499	MutexLock(&threadContext->sync.videoFrameMutex);
500	threadContext->sync.videoFrameWait = false;
501	threadContext->sync.videoFrameOn = false;
502	ConditionWake(&threadContext->sync.videoFrameRequiredCond);
503	ConditionWake(&threadContext->sync.videoFrameAvailableCond);
504	MutexUnlock(&threadContext->sync.videoFrameMutex);
505}
506
507void GBAThreadReset(struct GBAThread* threadContext) {
508	MutexLock(&threadContext->stateMutex);
509	_waitOnInterrupt(threadContext);
510	threadContext->state = THREAD_RESETING;
511	ConditionWake(&threadContext->stateCond);
512	MutexUnlock(&threadContext->stateMutex);
513}
514
515void GBAThreadJoin(struct GBAThread* threadContext) {
516	ThreadJoin(threadContext->thread);
517
518	MutexDeinit(&threadContext->stateMutex);
519	ConditionDeinit(&threadContext->stateCond);
520
521	MutexDeinit(&threadContext->sync.videoFrameMutex);
522	ConditionWake(&threadContext->sync.videoFrameAvailableCond);
523	ConditionDeinit(&threadContext->sync.videoFrameAvailableCond);
524	ConditionWake(&threadContext->sync.videoFrameRequiredCond);
525	ConditionDeinit(&threadContext->sync.videoFrameRequiredCond);
526
527	ConditionWake(&threadContext->sync.audioRequiredCond);
528	ConditionDeinit(&threadContext->sync.audioRequiredCond);
529	MutexDeinit(&threadContext->sync.audioBufferMutex);
530
531	int i;
532	for (i = 0; i < threadContext->rewindBufferCapacity; ++i) {
533		if (threadContext->rewindBuffer[i]) {
534			GBADeallocateState(threadContext->rewindBuffer[i]);
535		}
536	}
537	free(threadContext->rewindBuffer);
538	free(threadContext->rewindScreenBuffer);
539
540	if (threadContext->rom) {
541		threadContext->rom->close(threadContext->rom);
542		threadContext->rom = 0;
543	}
544
545	if (threadContext->save) {
546		threadContext->save->close(threadContext->save);
547		threadContext->save = 0;
548	}
549
550	if (threadContext->bios) {
551		threadContext->bios->close(threadContext->bios);
552		threadContext->bios = 0;
553	}
554
555	if (threadContext->patch) {
556		threadContext->patch->close(threadContext->patch);
557		threadContext->patch = 0;
558	}
559
560	if (threadContext->gameDir) {
561		if (threadContext->stateDir == threadContext->gameDir) {
562			threadContext->stateDir = 0;
563		}
564		threadContext->gameDir->close(threadContext->gameDir);
565		threadContext->gameDir = 0;
566	}
567
568	if (threadContext->stateDir) {
569		threadContext->stateDir->close(threadContext->stateDir);
570		threadContext->stateDir = 0;
571	}
572}
573
574bool GBAThreadIsActive(struct GBAThread* threadContext) {
575	return threadContext->state >= THREAD_RUNNING && threadContext->state < THREAD_EXITING;
576}
577
578void GBAThreadInterrupt(struct GBAThread* threadContext) {
579	MutexLock(&threadContext->stateMutex);
580	++threadContext->interruptDepth;
581	if (threadContext->interruptDepth > 1 || !GBAThreadIsActive(threadContext)) {
582		MutexUnlock(&threadContext->stateMutex);
583		return;
584	}
585	threadContext->savedState = threadContext->state;
586	_waitOnInterrupt(threadContext);
587	threadContext->state = THREAD_INTERRUPTING;
588	threadContext->gba->cpu->nextEvent = 0;
589	ConditionWake(&threadContext->stateCond);
590	_waitUntilNotState(threadContext, THREAD_INTERRUPTING);
591	MutexUnlock(&threadContext->stateMutex);
592}
593
594void GBAThreadContinue(struct GBAThread* threadContext) {
595	MutexLock(&threadContext->stateMutex);
596	--threadContext->interruptDepth;
597	if (threadContext->interruptDepth < 1 && GBAThreadIsActive(threadContext)) {
598		threadContext->state = threadContext->savedState;
599		ConditionWake(&threadContext->stateCond);
600	}
601	MutexUnlock(&threadContext->stateMutex);
602}
603
604void GBARunOnThread(struct GBAThread* threadContext, void (*run)(struct GBAThread*)) {
605	MutexLock(&threadContext->stateMutex);
606	threadContext->run = run;
607	_waitOnInterrupt(threadContext);
608	threadContext->savedState = threadContext->state;
609	threadContext->state = THREAD_RUN_ON;
610	threadContext->gba->cpu->nextEvent = 0;
611	ConditionWake(&threadContext->stateCond);
612	_waitUntilNotState(threadContext, THREAD_RUN_ON);
613	MutexUnlock(&threadContext->stateMutex);
614}
615
616void GBAThreadPause(struct GBAThread* threadContext) {
617	bool frameOn = threadContext->sync.videoFrameOn;
618	MutexLock(&threadContext->stateMutex);
619	_waitOnInterrupt(threadContext);
620	if (threadContext->state == THREAD_RUNNING) {
621		_pauseThread(threadContext, false);
622		threadContext->frameWasOn = frameOn;
623		frameOn = false;
624	}
625	MutexUnlock(&threadContext->stateMutex);
626
627	GBASyncSetVideoSync(&threadContext->sync, frameOn);
628}
629
630void GBAThreadUnpause(struct GBAThread* threadContext) {
631	bool frameOn = threadContext->sync.videoFrameOn;
632	MutexLock(&threadContext->stateMutex);
633	_waitOnInterrupt(threadContext);
634	if (threadContext->state == THREAD_PAUSED || threadContext->state == THREAD_PAUSING) {
635		threadContext->state = THREAD_RUNNING;
636		ConditionWake(&threadContext->stateCond);
637		frameOn = threadContext->frameWasOn;
638	}
639	MutexUnlock(&threadContext->stateMutex);
640
641	GBASyncSetVideoSync(&threadContext->sync, frameOn);
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 = threadContext->sync.videoFrameOn;
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		frameOn = threadContext->frameWasOn;
661	} else if (threadContext->state == THREAD_RUNNING) {
662		_pauseThread(threadContext, false);
663		threadContext->frameWasOn = frameOn;
664		frameOn = false;
665	}
666	MutexUnlock(&threadContext->stateMutex);
667
668	GBASyncSetVideoSync(&threadContext->sync, frameOn);
669}
670
671void GBAThreadPauseFromThread(struct GBAThread* threadContext) {
672	bool frameOn = true;
673	MutexLock(&threadContext->stateMutex);
674	_waitOnInterrupt(threadContext);
675	if (threadContext->state == THREAD_RUNNING) {
676		_pauseThread(threadContext, true);
677		frameOn = false;
678	}
679	MutexUnlock(&threadContext->stateMutex);
680
681	GBASyncSetVideoSync(&threadContext->sync, frameOn);
682}
683
684void GBAThreadLoadROM(struct GBAThread* threadContext, const char* fname) {
685	threadContext->rom = VFileOpen(fname, O_RDONLY);
686	threadContext->gameDir = 0;
687#if USE_LIBZIP
688	if (!threadContext->gameDir) {
689		threadContext->gameDir = VDirOpenZip(fname, 0);
690	}
691#endif
692#if USE_LZMA
693	if (!threadContext->gameDir) {
694		threadContext->gameDir = VDirOpen7z(fname, 0);
695	}
696#endif
697}
698
699static void _loadGameDir(struct GBAThread* threadContext) {
700	threadContext->gameDir->rewind(threadContext->gameDir);
701	struct VDirEntry* dirent = threadContext->gameDir->listNext(threadContext->gameDir);
702	while (dirent) {
703		struct Patch patchTemp;
704		struct VFile* vf = threadContext->gameDir->openFile(threadContext->gameDir, dirent->name(dirent), O_RDONLY);
705		if (!vf) {
706			dirent = threadContext->gameDir->listNext(threadContext->gameDir);
707			continue;
708		}
709		if (!threadContext->rom && GBAIsROM(vf)) {
710			threadContext->rom = vf;
711		} else if (!threadContext->patch && loadPatch(vf, &patchTemp)) {
712			threadContext->patch = vf;
713		} else {
714			vf->close(vf);
715		}
716		dirent = threadContext->gameDir->listNext(threadContext->gameDir);
717	}
718}
719
720void GBAThreadReplaceROM(struct GBAThread* threadContext, const char* fname) {
721	GBAUnloadROM(threadContext->gba);
722
723	if (threadContext->rom) {
724		threadContext->rom->close(threadContext->rom);
725		threadContext->rom = 0;
726	}
727
728	if (threadContext->save) {
729		threadContext->save->close(threadContext->save);
730		threadContext->save = 0;
731	}
732
733	GBAThreadLoadROM(threadContext, fname);
734	if (threadContext->gameDir) {
735		_loadGameDir(threadContext);
736	}
737
738	threadContext->fname = fname;
739	threadContext->save = VDirOptionalOpenFile(threadContext->stateDir, threadContext->fname, "sram", ".sav", O_CREAT | O_RDWR);
740
741	GBARaiseIRQ(threadContext->gba, IRQ_GAMEPAK);
742	GBALoadROM(threadContext->gba, threadContext->rom, threadContext->save, threadContext->fname);
743}
744
745#ifdef USE_PTHREADS
746struct GBAThread* GBAThreadGetContext(void) {
747	pthread_once(&_contextOnce, _createTLS);
748	return pthread_getspecific(_contextKey);
749}
750#elif _WIN32
751struct GBAThread* GBAThreadGetContext(void) {
752	InitOnceExecuteOnce(&_contextOnce, _createTLS, NULL, 0);
753	return TlsGetValue(_contextKey);
754}
755#else
756struct GBAThread* GBAThreadGetContext(void) {
757	return 0;
758}
759#endif
760
761#ifdef USE_PNG
762void GBAThreadTakeScreenshot(struct GBAThread* threadContext) {
763	unsigned stride;
764	void* pixels = 0;
765	struct VFile* vf = VDirOptionalOpenIncrementFile(threadContext->stateDir, threadContext->gba->activeFile, "screenshot", "-", ".png", O_CREAT | O_TRUNC | O_WRONLY);
766	threadContext->gba->video.renderer->getPixels(threadContext->gba->video.renderer, &stride, &pixels);
767	png_structp png = PNGWriteOpen(vf);
768	png_infop info = PNGWriteHeader(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
769	bool success = PNGWritePixels(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, stride, pixels);
770	PNGWriteClose(png, info);
771	vf->close(vf);
772	if (success) {
773		GBALog(threadContext->gba, GBA_LOG_STATUS, "Screenshot saved");
774	}
775}
776#endif
777
778#else
779struct GBAThread* GBAThreadGetContext(void) {
780	return 0;
781}
782#endif