all repos — mgba @ 3182b5e35d418fe281eca092e8c53263184920c8

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