all repos — mgba @ 870417d46eaef714f88e89bd6a1594895d0f7a0c

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] = {0};
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 = threadContext->sync.videoFrameOn;
623	MutexLock(&threadContext->stateMutex);
624	_waitOnInterrupt(threadContext);
625	if (threadContext->state == THREAD_RUNNING) {
626		_pauseThread(threadContext, false);
627		threadContext->frameWasOn = frameOn;
628		frameOn = false;
629	}
630	MutexUnlock(&threadContext->stateMutex);
631
632	_changeVideoSync(&threadContext->sync, frameOn);
633}
634
635void GBAThreadUnpause(struct GBAThread* threadContext) {
636	bool frameOn = threadContext->sync.videoFrameOn;
637	MutexLock(&threadContext->stateMutex);
638	_waitOnInterrupt(threadContext);
639	if (threadContext->state == THREAD_PAUSED || threadContext->state == THREAD_PAUSING) {
640		threadContext->state = THREAD_RUNNING;
641		ConditionWake(&threadContext->stateCond);
642		frameOn = threadContext->frameWasOn;
643	}
644	MutexUnlock(&threadContext->stateMutex);
645
646	_changeVideoSync(&threadContext->sync, frameOn);
647}
648
649bool GBAThreadIsPaused(struct GBAThread* threadContext) {
650	bool isPaused;
651	MutexLock(&threadContext->stateMutex);
652	_waitOnInterrupt(threadContext);
653	isPaused = threadContext->state == THREAD_PAUSED;
654	MutexUnlock(&threadContext->stateMutex);
655	return isPaused;
656}
657
658void GBAThreadTogglePause(struct GBAThread* threadContext) {
659	bool frameOn = threadContext->sync.videoFrameOn;
660	MutexLock(&threadContext->stateMutex);
661	_waitOnInterrupt(threadContext);
662	if (threadContext->state == THREAD_PAUSED || threadContext->state == THREAD_PAUSING) {
663		threadContext->state = THREAD_RUNNING;
664		ConditionWake(&threadContext->stateCond);
665		frameOn = threadContext->frameWasOn;
666	} else if (threadContext->state == THREAD_RUNNING) {
667		_pauseThread(threadContext, false);
668		threadContext->frameWasOn = frameOn;
669		frameOn = false;
670	}
671	MutexUnlock(&threadContext->stateMutex);
672
673	_changeVideoSync(&threadContext->sync, frameOn);
674}
675
676void GBAThreadPauseFromThread(struct GBAThread* threadContext) {
677	bool frameOn = true;
678	MutexLock(&threadContext->stateMutex);
679	_waitOnInterrupt(threadContext);
680	if (threadContext->state == THREAD_RUNNING) {
681		_pauseThread(threadContext, true);
682		frameOn = false;
683	}
684	MutexUnlock(&threadContext->stateMutex);
685
686	_changeVideoSync(&threadContext->sync, frameOn);
687}
688
689#ifdef USE_PTHREADS
690struct GBAThread* GBAThreadGetContext(void) {
691	pthread_once(&_contextOnce, _createTLS);
692	return pthread_getspecific(_contextKey);
693}
694#elif _WIN32
695struct GBAThread* GBAThreadGetContext(void) {
696	InitOnceExecuteOnce(&_contextOnce, _createTLS, NULL, 0);
697	return TlsGetValue(_contextKey);
698}
699#endif
700
701#ifdef USE_PNG
702void GBAThreadTakeScreenshot(struct GBAThread* threadContext) {
703	unsigned stride;
704	void* pixels = 0;
705	struct VFile* vf = VDirOptionalOpenIncrementFile(threadContext->stateDir, threadContext->gba->activeFile, "screenshot", "-", ".png", O_CREAT | O_TRUNC | O_WRONLY);
706	threadContext->gba->video.renderer->getPixels(threadContext->gba->video.renderer, &stride, &pixels);
707	png_structp png = PNGWriteOpen(vf);
708	png_infop info = PNGWriteHeader(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
709	bool success = PNGWritePixels(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, stride, pixels);
710	PNGWriteClose(png, info);
711	vf->close(vf);
712	if (success) {
713		GBALog(threadContext->gba, GBA_LOG_STATUS, "Screenshot saved");
714	}
715}
716#endif
717
718#else
719struct GBAThread* GBAThreadGetContext(void) {
720	return 0;
721}
722#endif
723
724void GBASyncPostFrame(struct GBASync* sync) {
725	if (!sync) {
726		return;
727	}
728
729	MutexLock(&sync->videoFrameMutex);
730	++sync->videoFramePending;
731	--sync->videoFrameSkip;
732	if (sync->videoFrameSkip < 0) {
733		do {
734			ConditionWake(&sync->videoFrameAvailableCond);
735			if (sync->videoFrameWait) {
736				ConditionWait(&sync->videoFrameRequiredCond, &sync->videoFrameMutex);
737			}
738		} while (sync->videoFrameWait && sync->videoFramePending);
739	}
740	MutexUnlock(&sync->videoFrameMutex);
741}
742
743void GBASyncForceFrame(struct GBASync* sync) {
744	if (!sync) {
745		return;
746	}
747
748	MutexLock(&sync->videoFrameMutex);
749	ConditionWake(&sync->videoFrameAvailableCond);
750	MutexUnlock(&sync->videoFrameMutex);
751}
752
753bool GBASyncWaitFrameStart(struct GBASync* sync, int frameskip) {
754	if (!sync) {
755		return true;
756	}
757
758	MutexLock(&sync->videoFrameMutex);
759	ConditionWake(&sync->videoFrameRequiredCond);
760	if (!sync->videoFrameOn && !sync->videoFramePending) {
761		return false;
762	}
763	if (sync->videoFrameOn) {
764		if (ConditionWaitTimed(&sync->videoFrameAvailableCond, &sync->videoFrameMutex, 50)) {
765			return false;
766		}
767	}
768	sync->videoFramePending = 0;
769	sync->videoFrameSkip = frameskip;
770	return true;
771}
772
773void GBASyncWaitFrameEnd(struct GBASync* sync) {
774	if (!sync) {
775		return;
776	}
777
778	MutexUnlock(&sync->videoFrameMutex);
779}
780
781bool GBASyncDrawingFrame(struct GBASync* sync) {
782	if (!sync) {
783		return true;
784	}
785
786	return sync->videoFrameSkip <= 0;
787}
788
789void GBASyncSetVideoSync(struct GBASync* sync, bool wait) {
790	if (!sync) {
791		return;
792	}
793
794	_changeVideoSync(sync, wait);
795}
796
797void GBASyncProduceAudio(struct GBASync* sync, bool wait) {
798	if (!sync) {
799		return;
800	}
801
802	if (sync->audioWait && wait) {
803		// TODO loop properly in event of spurious wakeups
804		ConditionWait(&sync->audioRequiredCond, &sync->audioBufferMutex);
805	}
806	MutexUnlock(&sync->audioBufferMutex);
807}
808
809void GBASyncLockAudio(struct GBASync* sync) {
810	if (!sync) {
811		return;
812	}
813
814	MutexLock(&sync->audioBufferMutex);
815}
816
817void GBASyncUnlockAudio(struct GBASync* sync) {
818	if (!sync) {
819		return;
820	}
821
822	MutexUnlock(&sync->audioBufferMutex);
823}
824
825void GBASyncConsumeAudio(struct GBASync* sync) {
826	if (!sync) {
827		return;
828	}
829
830	ConditionWake(&sync->audioRequiredCond);
831	MutexUnlock(&sync->audioBufferMutex);
832}