all repos — mgba @ bbcf40e0e740a5e2cf6d2c240a6435945f522bc7

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#endif
 97
 98static void _changeVideoSync(struct GBASync* sync, bool frameOn) {
 99	// Make sure the video thread can process events while the GBA thread is paused
100	MutexLock(&sync->videoFrameMutex);
101	if (frameOn != sync->videoFrameOn) {
102		sync->videoFrameOn = frameOn;
103		ConditionWake(&sync->videoFrameAvailableCond);
104	}
105	MutexUnlock(&sync->videoFrameMutex);
106}
107
108#ifndef DISABLE_THREADING
109static THREAD_ENTRY _GBAThreadRun(void* context) {
110#ifdef USE_PTHREADS
111	pthread_once(&_contextOnce, _createTLS);
112#else
113	InitOnceExecuteOnce(&_contextOnce, _createTLS, NULL, 0);
114#endif
115
116	struct GBA gba;
117	struct ARMCore cpu;
118	struct Patch patch;
119	struct GBACheatDevice cheatDevice;
120	struct GBAThread* threadContext = context;
121	struct ARMComponent* components[GBA_COMPONENT_MAX] = {};
122	struct GBARRContext* movie = 0;
123	int numComponents = GBA_COMPONENT_MAX;
124
125#if !defined(_WIN32) && defined(USE_PTHREADS)
126	sigset_t signals;
127	sigemptyset(&signals);
128	pthread_sigmask(SIG_SETMASK, &signals, 0);
129#endif
130
131	GBACreate(&gba);
132	ARMSetComponents(&cpu, &gba.d, numComponents, components);
133	ARMInit(&cpu);
134	gba.sync = &threadContext->sync;
135	threadContext->gba = &gba;
136	threadContext->cpu = &cpu;
137	gba.logLevel = threadContext->logLevel;
138	gba.logHandler = threadContext->logHandler;
139	gba.stream = threadContext->stream;
140	gba.idleOptimization = threadContext->idleOptimization;
141#ifdef USE_PTHREADS
142	pthread_setspecific(_contextKey, threadContext);
143#else
144	TlsSetValue(_contextKey, threadContext);
145#endif
146
147	if (threadContext->audioBuffers) {
148		GBAAudioResizeBuffer(&gba.audio, threadContext->audioBuffers);
149	} else {
150		threadContext->audioBuffers = GBA_AUDIO_SAMPLES;
151	}
152
153	if (threadContext->renderer) {
154		GBAVideoAssociateRenderer(&gba.video, threadContext->renderer);
155	}
156
157	if (threadContext->rom) {
158		GBALoadROM(&gba, threadContext->rom, threadContext->save, threadContext->fname);
159
160		struct GBACartridgeOverride override;
161		const struct GBACartridge* cart = (const struct GBACartridge*) gba.memory.rom;
162		memcpy(override.id, &cart->id, sizeof(override.id));
163		if (GBAOverrideFind(threadContext->overrides, &override)) {
164			GBAOverrideApply(&gba, &override);
165		}
166		if (threadContext->hasOverride) {
167			GBAOverrideApply(&gba, &threadContext->override);
168		}
169
170		if (threadContext->bios && GBAIsBIOS(threadContext->bios)) {
171			GBALoadBIOS(&gba, threadContext->bios);
172		}
173
174		if (threadContext->patch && loadPatch(threadContext->patch, &patch)) {
175			GBAApplyPatch(&gba, &patch);
176		}
177	}
178
179	if (threadContext->movie) {
180		struct VDir* movieDir = VDirOpen(threadContext->movie);
181#ifdef USE_LIBZIP
182		if (!movieDir) {
183			movieDir = VDirOpenZip(threadContext->movie, 0);
184		}
185#endif
186		if (movieDir) {
187			struct GBAMGMContext* mgm = malloc(sizeof(*mgm));
188			GBAMGMContextCreate(mgm);
189			if (!GBAMGMSetStream(mgm, movieDir)) {
190				mgm->d.destroy(&mgm->d);
191			} else {
192				movie = &mgm->d;
193			}
194		} else {
195			struct VFile* movieFile = VFileOpen(threadContext->movie, O_RDONLY);
196			if (movieFile) {
197				struct GBAVBMContext* vbm = malloc(sizeof(*vbm));
198				GBAVBMContextCreate(vbm);
199				if (!GBAVBMSetStream(vbm, movieFile)) {
200					vbm->d.destroy(&vbm->d);
201				} else {
202					movie = &vbm->d;
203				}
204			}
205		}
206	}
207
208	ARMReset(&cpu);
209
210	if (movie) {
211		gba.rr = movie;
212		movie->startPlaying(movie, false);
213		GBARRInitPlay(&gba);
214	}
215
216	if (threadContext->skipBios) {
217		GBASkipBIOS(&cpu);
218	}
219
220	if (!threadContext->cheats) {
221		GBACheatDeviceCreate(&cheatDevice);
222		threadContext->cheats = &cheatDevice;
223	}
224	if (threadContext->cheatsFile) {
225		GBACheatParseFile(threadContext->cheats, threadContext->cheatsFile);
226	}
227	GBACheatAttachDevice(&gba, threadContext->cheats);
228
229	if (threadContext->debugger) {
230		threadContext->debugger->log = GBADebuggerLogShim;
231		GBAAttachDebugger(&gba, threadContext->debugger);
232		ARMDebuggerEnter(threadContext->debugger, DEBUGGER_ENTER_ATTACHED, 0);
233	}
234
235	GBASIOSetDriverSet(&gba.sio, &threadContext->sioDrivers);
236
237	if (threadContext->volume == 0) {
238		threadContext->volume = GBA_AUDIO_VOLUME_MAX;
239	}
240	if (threadContext->mute) {
241		gba.audio.masterVolume = 0;
242	} else {
243		gba.audio.masterVolume = threadContext->volume;
244	}
245
246	gba.keySource = &threadContext->activeKeys;
247
248	if (threadContext->startCallback) {
249		threadContext->startCallback(threadContext);
250	}
251
252	_changeState(threadContext, THREAD_RUNNING, true);
253
254	while (threadContext->state < THREAD_EXITING) {
255		if (threadContext->debugger) {
256			struct ARMDebugger* debugger = threadContext->debugger;
257			ARMDebuggerRun(debugger);
258			if (debugger->state == DEBUGGER_SHUTDOWN) {
259				_changeState(threadContext, THREAD_EXITING, false);
260			}
261		} else {
262			while (threadContext->state == THREAD_RUNNING) {
263				ARMRunLoop(&cpu);
264			}
265		}
266
267		int resetScheduled = 0;
268		MutexLock(&threadContext->stateMutex);
269		while (threadContext->state > THREAD_RUNNING && threadContext->state < THREAD_EXITING) {
270			if (threadContext->state == THREAD_PAUSING) {
271				threadContext->state = THREAD_PAUSED;
272				ConditionWake(&threadContext->stateCond);
273			}
274			if (threadContext->state == THREAD_INTERRUPTING) {
275				threadContext->state = THREAD_INTERRUPTED;
276				ConditionWake(&threadContext->stateCond);
277			}
278			if (threadContext->state == THREAD_RUN_ON) {
279				if (threadContext->run) {
280					threadContext->run(threadContext);
281				}
282				threadContext->state = threadContext->savedState;
283				ConditionWake(&threadContext->stateCond);
284			}
285			if (threadContext->state == THREAD_RESETING) {
286				threadContext->state = THREAD_RUNNING;
287				resetScheduled = 1;
288			}
289			while (threadContext->state == THREAD_PAUSED || threadContext->state == THREAD_INTERRUPTED) {
290				ConditionWait(&threadContext->stateCond, &threadContext->stateMutex);
291			}
292		}
293		MutexUnlock(&threadContext->stateMutex);
294		if (resetScheduled) {
295			ARMReset(&cpu);
296			if (threadContext->skipBios) {
297				GBASkipBIOS(&cpu);
298			}
299		}
300	}
301
302	while (threadContext->state < THREAD_SHUTDOWN) {
303		_changeState(threadContext, THREAD_SHUTDOWN, false);
304	}
305
306	if (threadContext->cleanCallback) {
307		threadContext->cleanCallback(threadContext);
308	}
309
310	threadContext->gba = 0;
311	ARMDeinit(&cpu);
312	GBADestroy(&gba);
313	if (&cheatDevice == threadContext->cheats) {
314		GBACheatDeviceDestroy(&cheatDevice);
315	}
316
317	if (movie) {
318		movie->destroy(movie);
319		free(movie);
320	}
321
322	threadContext->sync.videoFrameOn = false;
323	ConditionWake(&threadContext->sync.videoFrameAvailableCond);
324	ConditionWake(&threadContext->sync.audioRequiredCond);
325
326	return 0;
327}
328
329void GBAMapOptionsToContext(const struct GBAOptions* opts, struct GBAThread* threadContext) {
330	if (opts->useBios) {
331		threadContext->bios = VFileOpen(opts->bios, O_RDONLY);
332	} else {
333		threadContext->bios = 0;
334	}
335	threadContext->frameskip = opts->frameskip;
336	threadContext->volume = opts->volume;
337	threadContext->mute = opts->mute;
338	threadContext->logLevel = opts->logLevel;
339	if (opts->rewindEnable) {
340		threadContext->rewindBufferCapacity = opts->rewindBufferCapacity;
341		threadContext->rewindBufferInterval = opts->rewindBufferInterval;
342	} else {
343		threadContext->rewindBufferCapacity = 0;
344	}
345	threadContext->skipBios = opts->skipBios;
346	threadContext->sync.audioWait = opts->audioSync;
347	threadContext->sync.videoFrameWait = opts->videoSync;
348
349	if (opts->fpsTarget) {
350		threadContext->fpsTarget = opts->fpsTarget;
351	}
352
353	if (opts->audioBuffers) {
354		threadContext->audioBuffers = opts->audioBuffers;
355	}
356
357	threadContext->idleOptimization = opts->idleOptimization;
358}
359
360void GBAMapArgumentsToContext(const struct GBAArguments* args, struct GBAThread* threadContext) {
361	if (args->dirmode) {
362		threadContext->gameDir = VDirOpen(args->fname);
363		threadContext->stateDir = threadContext->gameDir;
364	} else {
365		threadContext->rom = VFileOpen(args->fname, O_RDONLY);
366		threadContext->gameDir = 0;
367#if USE_LIBZIP
368		if (!threadContext->gameDir) {
369			threadContext->gameDir = VDirOpenZip(args->fname, 0);
370		}
371#endif
372#if USE_LZMA
373		if (!threadContext->gameDir) {
374			threadContext->gameDir = VDirOpen7z(args->fname, 0);
375		}
376#endif
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	if (threadContext->rom && !GBAIsROM(threadContext->rom)) {
404		threadContext->rom->close(threadContext->rom);
405		threadContext->rom = 0;
406	}
407
408	if (threadContext->gameDir) {
409		threadContext->gameDir->rewind(threadContext->gameDir);
410		struct VDirEntry* dirent = threadContext->gameDir->listNext(threadContext->gameDir);
411		while (dirent) {
412			struct Patch patchTemp;
413			struct VFile* vf = threadContext->gameDir->openFile(threadContext->gameDir, dirent->name(dirent), O_RDONLY);
414			if (!vf) {
415				dirent = threadContext->gameDir->listNext(threadContext->gameDir);
416				continue;
417			}
418			if (!threadContext->rom && GBAIsROM(vf)) {
419				threadContext->rom = vf;
420			} else if (!threadContext->patch && loadPatch(vf, &patchTemp)) {
421				threadContext->patch = vf;
422			} else {
423				vf->close(vf);
424			}
425			dirent = threadContext->gameDir->listNext(threadContext->gameDir);
426		}
427
428	}
429
430	if (!threadContext->rom) {
431		threadContext->state = THREAD_SHUTDOWN;
432		return false;
433	}
434
435	threadContext->save = VDirOptionalOpenFile(threadContext->stateDir, threadContext->fname, "sram", ".sav", O_CREAT | O_RDWR);
436
437	MutexInit(&threadContext->stateMutex);
438	ConditionInit(&threadContext->stateCond);
439
440	MutexInit(&threadContext->sync.videoFrameMutex);
441	ConditionInit(&threadContext->sync.videoFrameAvailableCond);
442	ConditionInit(&threadContext->sync.videoFrameRequiredCond);
443	MutexInit(&threadContext->sync.audioBufferMutex);
444	ConditionInit(&threadContext->sync.audioRequiredCond);
445
446	threadContext->interruptDepth = 0;
447
448#ifndef _WIN32
449	sigset_t signals;
450	sigemptyset(&signals);
451	sigaddset(&signals, SIGINT);
452	sigaddset(&signals, SIGTRAP);
453	pthread_sigmask(SIG_BLOCK, &signals, 0);
454#endif
455
456	MutexLock(&threadContext->stateMutex);
457	ThreadCreate(&threadContext->thread, _GBAThreadRun, threadContext);
458	while (threadContext->state < THREAD_RUNNING) {
459		ConditionWait(&threadContext->stateCond, &threadContext->stateMutex);
460	}
461	MutexUnlock(&threadContext->stateMutex);
462
463	return true;
464}
465
466bool GBAThreadHasStarted(struct GBAThread* threadContext) {
467	bool hasStarted;
468	MutexLock(&threadContext->stateMutex);
469	hasStarted = threadContext->state > THREAD_INITIALIZED;
470	MutexUnlock(&threadContext->stateMutex);
471	return hasStarted;
472}
473
474bool GBAThreadHasExited(struct GBAThread* threadContext) {
475	bool hasExited;
476	MutexLock(&threadContext->stateMutex);
477	hasExited = threadContext->state > THREAD_EXITING;
478	MutexUnlock(&threadContext->stateMutex);
479	return hasExited;
480}
481
482bool GBAThreadHasCrashed(struct GBAThread* threadContext) {
483	bool hasExited;
484	MutexLock(&threadContext->stateMutex);
485	hasExited = threadContext->state == THREAD_CRASHED;
486	MutexUnlock(&threadContext->stateMutex);
487	return hasExited;
488}
489
490void GBAThreadEnd(struct GBAThread* threadContext) {
491	MutexLock(&threadContext->stateMutex);
492	_waitOnInterrupt(threadContext);
493	threadContext->state = THREAD_EXITING;
494	if (threadContext->gba) {
495		threadContext->gba->cpu->halted = false;
496	}
497	ConditionWake(&threadContext->stateCond);
498	MutexUnlock(&threadContext->stateMutex);
499	MutexLock(&threadContext->sync.audioBufferMutex);
500	threadContext->sync.audioWait = 0;
501	ConditionWake(&threadContext->sync.audioRequiredCond);
502	MutexUnlock(&threadContext->sync.audioBufferMutex);
503
504	MutexLock(&threadContext->sync.videoFrameMutex);
505	threadContext->sync.videoFrameWait = false;
506	threadContext->sync.videoFrameOn = false;
507	ConditionWake(&threadContext->sync.videoFrameRequiredCond);
508	ConditionWake(&threadContext->sync.videoFrameAvailableCond);
509	MutexUnlock(&threadContext->sync.videoFrameMutex);
510}
511
512void GBAThreadReset(struct GBAThread* threadContext) {
513	MutexLock(&threadContext->stateMutex);
514	_waitOnInterrupt(threadContext);
515	threadContext->state = THREAD_RESETING;
516	ConditionWake(&threadContext->stateCond);
517	MutexUnlock(&threadContext->stateMutex);
518}
519
520void GBAThreadJoin(struct GBAThread* threadContext) {
521	ThreadJoin(threadContext->thread);
522
523	MutexDeinit(&threadContext->stateMutex);
524	ConditionDeinit(&threadContext->stateCond);
525
526	MutexDeinit(&threadContext->sync.videoFrameMutex);
527	ConditionWake(&threadContext->sync.videoFrameAvailableCond);
528	ConditionDeinit(&threadContext->sync.videoFrameAvailableCond);
529	ConditionWake(&threadContext->sync.videoFrameRequiredCond);
530	ConditionDeinit(&threadContext->sync.videoFrameRequiredCond);
531
532	ConditionWake(&threadContext->sync.audioRequiredCond);
533	ConditionDeinit(&threadContext->sync.audioRequiredCond);
534	MutexDeinit(&threadContext->sync.audioBufferMutex);
535
536	int i;
537	for (i = 0; i < threadContext->rewindBufferCapacity; ++i) {
538		if (threadContext->rewindBuffer[i]) {
539			GBADeallocateState(threadContext->rewindBuffer[i]);
540		}
541	}
542	free(threadContext->rewindBuffer);
543	free(threadContext->rewindScreenBuffer);
544
545	if (threadContext->rom) {
546		threadContext->rom->close(threadContext->rom);
547		threadContext->rom = 0;
548	}
549
550	if (threadContext->save) {
551		threadContext->save->close(threadContext->save);
552		threadContext->save = 0;
553	}
554
555	if (threadContext->bios) {
556		threadContext->bios->close(threadContext->bios);
557		threadContext->bios = 0;
558	}
559
560	if (threadContext->patch) {
561		threadContext->patch->close(threadContext->patch);
562		threadContext->patch = 0;
563	}
564
565	if (threadContext->gameDir) {
566		if (threadContext->stateDir == threadContext->gameDir) {
567			threadContext->stateDir = 0;
568		}
569		threadContext->gameDir->close(threadContext->gameDir);
570		threadContext->gameDir = 0;
571	}
572
573	if (threadContext->stateDir) {
574		threadContext->stateDir->close(threadContext->stateDir);
575		threadContext->stateDir = 0;
576	}
577}
578
579bool GBAThreadIsActive(struct GBAThread* threadContext) {
580	return threadContext->state >= THREAD_RUNNING && threadContext->state < THREAD_EXITING;
581}
582
583void GBAThreadInterrupt(struct GBAThread* threadContext) {
584	MutexLock(&threadContext->stateMutex);
585	++threadContext->interruptDepth;
586	if (threadContext->interruptDepth > 1 || !GBAThreadIsActive(threadContext)) {
587		MutexUnlock(&threadContext->stateMutex);
588		return;
589	}
590	threadContext->savedState = threadContext->state;
591	_waitOnInterrupt(threadContext);
592	threadContext->state = THREAD_INTERRUPTING;
593	threadContext->gba->cpu->nextEvent = 0;
594	ConditionWake(&threadContext->stateCond);
595	_waitUntilNotState(threadContext, THREAD_INTERRUPTING);
596	MutexUnlock(&threadContext->stateMutex);
597}
598
599void GBAThreadContinue(struct GBAThread* threadContext) {
600	MutexLock(&threadContext->stateMutex);
601	--threadContext->interruptDepth;
602	if (threadContext->interruptDepth < 1 && GBAThreadIsActive(threadContext)) {
603		threadContext->state = threadContext->savedState;
604		ConditionWake(&threadContext->stateCond);
605	}
606	MutexUnlock(&threadContext->stateMutex);
607}
608
609void GBARunOnThread(struct GBAThread* threadContext, void (*run)(struct GBAThread*)) {
610	MutexLock(&threadContext->stateMutex);
611	threadContext->run = run;
612	_waitOnInterrupt(threadContext);
613	threadContext->savedState = threadContext->state;
614	threadContext->state = THREAD_RUN_ON;
615	threadContext->gba->cpu->nextEvent = 0;
616	ConditionWake(&threadContext->stateCond);
617	_waitUntilNotState(threadContext, THREAD_RUN_ON);
618	MutexUnlock(&threadContext->stateMutex);
619}
620
621void GBAThreadPause(struct GBAThread* threadContext) {
622	bool frameOn = true;
623	MutexLock(&threadContext->stateMutex);
624	_waitOnInterrupt(threadContext);
625	if (threadContext->state == THREAD_RUNNING) {
626		_pauseThread(threadContext, false);
627		frameOn = false;
628	}
629	MutexUnlock(&threadContext->stateMutex);
630
631	_changeVideoSync(&threadContext->sync, frameOn);
632}
633
634void GBAThreadUnpause(struct GBAThread* threadContext) {
635	MutexLock(&threadContext->stateMutex);
636	_waitOnInterrupt(threadContext);
637	if (threadContext->state == THREAD_PAUSED || threadContext->state == THREAD_PAUSING) {
638		threadContext->state = THREAD_RUNNING;
639		ConditionWake(&threadContext->stateCond);
640	}
641	MutexUnlock(&threadContext->stateMutex);
642
643	_changeVideoSync(&threadContext->sync, true);
644}
645
646bool GBAThreadIsPaused(struct GBAThread* threadContext) {
647	bool isPaused;
648	MutexLock(&threadContext->stateMutex);
649	_waitOnInterrupt(threadContext);
650	isPaused = threadContext->state == THREAD_PAUSED;
651	MutexUnlock(&threadContext->stateMutex);
652	return isPaused;
653}
654
655void GBAThreadTogglePause(struct GBAThread* threadContext) {
656	bool frameOn = true;
657	MutexLock(&threadContext->stateMutex);
658	_waitOnInterrupt(threadContext);
659	if (threadContext->state == THREAD_PAUSED || threadContext->state == THREAD_PAUSING) {
660		threadContext->state = THREAD_RUNNING;
661		ConditionWake(&threadContext->stateCond);
662	} else if (threadContext->state == THREAD_RUNNING) {
663		_pauseThread(threadContext, false);
664		frameOn = false;
665	}
666	MutexUnlock(&threadContext->stateMutex);
667
668	_changeVideoSync(&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	_changeVideoSync(&threadContext->sync, frameOn);
682}
683
684#ifdef USE_PTHREADS
685struct GBAThread* GBAThreadGetContext(void) {
686	pthread_once(&_contextOnce, _createTLS);
687	return pthread_getspecific(_contextKey);
688}
689#elif _WIN32
690struct GBAThread* GBAThreadGetContext(void) {
691	InitOnceExecuteOnce(&_contextOnce, _createTLS, NULL, 0);
692	return TlsGetValue(_contextKey);
693}
694#endif
695
696#ifdef USE_PNG
697void GBAThreadTakeScreenshot(struct GBAThread* threadContext) {
698	unsigned stride;
699	void* pixels = 0;
700	struct VFile* vf = VDirOptionalOpenIncrementFile(threadContext->stateDir, threadContext->gba->activeFile, "screenshot", "-", ".png", O_CREAT | O_TRUNC | O_WRONLY);
701	threadContext->gba->video.renderer->getPixels(threadContext->gba->video.renderer, &stride, &pixels);
702	png_structp png = PNGWriteOpen(vf);
703	png_infop info = PNGWriteHeader(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
704	bool success = PNGWritePixels(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, stride, pixels);
705	PNGWriteClose(png, info);
706	vf->close(vf);
707	if (success) {
708		GBALog(threadContext->gba, GBA_LOG_STATUS, "Screenshot saved");
709	}
710}
711#endif
712
713#else
714struct GBAThread* GBAThreadGetContext(void) {
715	return 0;
716}
717#endif
718
719void GBASyncPostFrame(struct GBASync* sync) {
720	if (!sync) {
721		return;
722	}
723
724	MutexLock(&sync->videoFrameMutex);
725	++sync->videoFramePending;
726	--sync->videoFrameSkip;
727	if (sync->videoFrameSkip < 0) {
728		do {
729			ConditionWake(&sync->videoFrameAvailableCond);
730			if (sync->videoFrameWait) {
731				ConditionWait(&sync->videoFrameRequiredCond, &sync->videoFrameMutex);
732			}
733		} while (sync->videoFrameWait && sync->videoFramePending);
734	}
735	MutexUnlock(&sync->videoFrameMutex);
736}
737
738void GBASyncForceFrame(struct GBASync* sync) {
739	if (!sync) {
740		return;
741	}
742
743	MutexLock(&sync->videoFrameMutex);
744	ConditionWake(&sync->videoFrameAvailableCond);
745	MutexUnlock(&sync->videoFrameMutex);
746}
747
748bool GBASyncWaitFrameStart(struct GBASync* sync, int frameskip) {
749	if (!sync) {
750		return true;
751	}
752
753	MutexLock(&sync->videoFrameMutex);
754	ConditionWake(&sync->videoFrameRequiredCond);
755	if (!sync->videoFrameOn && !sync->videoFramePending) {
756		return false;
757	}
758	if (sync->videoFrameOn) {
759		if (ConditionWaitTimed(&sync->videoFrameAvailableCond, &sync->videoFrameMutex, 50)) {
760			return false;
761		}
762	}
763	sync->videoFramePending = 0;
764	sync->videoFrameSkip = frameskip;
765	return true;
766}
767
768void GBASyncWaitFrameEnd(struct GBASync* sync) {
769	if (!sync) {
770		return;
771	}
772
773	MutexUnlock(&sync->videoFrameMutex);
774}
775
776bool GBASyncDrawingFrame(struct GBASync* sync) {
777	if (!sync) {
778		return true;
779	}
780
781	return sync->videoFrameSkip <= 0;
782}
783
784void GBASyncSuspendDrawing(struct GBASync* sync) {
785	if (!sync) {
786		return;
787	}
788
789	_changeVideoSync(sync, false);
790}
791
792void GBASyncResumeDrawing(struct GBASync* sync) {
793	if (!sync) {
794		return;
795	}
796
797	_changeVideoSync(sync, true);
798}
799
800void GBASyncProduceAudio(struct GBASync* sync, bool wait) {
801	if (!sync) {
802		return;
803	}
804
805	if (sync->audioWait && wait) {
806		// TODO loop properly in event of spurious wakeups
807		ConditionWait(&sync->audioRequiredCond, &sync->audioBufferMutex);
808	}
809	MutexUnlock(&sync->audioBufferMutex);
810}
811
812void GBASyncLockAudio(struct GBASync* sync) {
813	if (!sync) {
814		return;
815	}
816
817	MutexLock(&sync->audioBufferMutex);
818}
819
820void GBASyncUnlockAudio(struct GBASync* sync) {
821	if (!sync) {
822		return;
823	}
824
825	MutexUnlock(&sync->audioBufferMutex);
826}
827
828void GBASyncConsumeAudio(struct GBASync* sync) {
829	if (!sync) {
830		return;
831	}
832
833	ConditionWake(&sync->audioRequiredCond);
834	MutexUnlock(&sync->audioBufferMutex);
835}