all repos — mgba @ 7015f38b37a7d33fc8412e4ef66911aae7e4936b

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