all repos — mgba @ 910ff621b32c461a6210aca06f94f38de95b76b3

mGBA Game Boy Advance Emulator

src/gba/supervisor/thread.c (view raw)

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