all repos — mgba @ 51b8c862b969390582cb39b3ac98239cdea9a4b1

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	threadContext->bios = VFileOpen(opts->bios, O_RDONLY);
314	threadContext->frameskip = opts->frameskip;
315	threadContext->logLevel = opts->logLevel;
316	if (opts->rewindEnable) {
317		threadContext->rewindBufferCapacity = opts->rewindBufferCapacity;
318		threadContext->rewindBufferInterval = opts->rewindBufferInterval;
319	} else {
320		threadContext->rewindBufferCapacity = 0;
321	}
322	threadContext->skipBios = opts->skipBios;
323	threadContext->sync.audioWait = opts->audioSync;
324	threadContext->sync.videoFrameWait = opts->videoSync;
325
326	if (opts->fpsTarget) {
327		threadContext->fpsTarget = opts->fpsTarget;
328	}
329
330	if (opts->audioBuffers) {
331		threadContext->audioBuffers = opts->audioBuffers;
332	}
333
334	threadContext->idleOptimization = opts->idleOptimization;
335}
336
337void GBAMapArgumentsToContext(const struct GBAArguments* args, struct GBAThread* threadContext) {
338	if (args->dirmode) {
339		threadContext->gameDir = VDirOpen(args->fname);
340		threadContext->stateDir = threadContext->gameDir;
341	} else {
342		threadContext->rom = VFileOpen(args->fname, O_RDONLY);
343		threadContext->gameDir = 0;
344#if USE_LIBZIP
345		if (!threadContext->gameDir) {
346			threadContext->gameDir = VDirOpenZip(args->fname, 0);
347		}
348#endif
349#if USE_LZMA
350		if (!threadContext->gameDir) {
351			threadContext->gameDir = VDirOpen7z(args->fname, 0);
352		}
353#endif
354	}
355	threadContext->fname = args->fname;
356	threadContext->patch = VFileOpen(args->patch, O_RDONLY);
357	threadContext->cheatsFile = VFileOpen(args->cheatsFile, O_RDONLY);
358	threadContext->movie = args->movie;
359}
360
361bool GBAThreadStart(struct GBAThread* threadContext) {
362	// TODO: error check
363	threadContext->activeKeys = 0;
364	threadContext->state = THREAD_INITIALIZED;
365	threadContext->sync.videoFrameOn = true;
366	threadContext->sync.videoFrameSkip = 0;
367
368	threadContext->rewindBuffer = 0;
369	int newCapacity = threadContext->rewindBufferCapacity;
370	int newInterval = threadContext->rewindBufferInterval;
371	threadContext->rewindBufferCapacity = 0;
372	threadContext->rewindBufferInterval = 0;
373	GBARewindSettingsChanged(threadContext, newCapacity, newInterval);
374
375	if (!threadContext->fpsTarget) {
376		threadContext->fpsTarget = _defaultFPSTarget;
377	}
378
379	if (threadContext->rom && !GBAIsROM(threadContext->rom)) {
380		threadContext->rom->close(threadContext->rom);
381		threadContext->rom = 0;
382	}
383
384	if (threadContext->gameDir) {
385		threadContext->gameDir->rewind(threadContext->gameDir);
386		struct VDirEntry* dirent = threadContext->gameDir->listNext(threadContext->gameDir);
387		while (dirent) {
388			struct Patch patchTemp;
389			struct VFile* vf = threadContext->gameDir->openFile(threadContext->gameDir, dirent->name(dirent), O_RDONLY);
390			if (!vf) {
391				dirent = threadContext->gameDir->listNext(threadContext->gameDir);
392				continue;
393			}
394			if (!threadContext->rom && GBAIsROM(vf)) {
395				threadContext->rom = vf;
396			} else if (!threadContext->patch && loadPatch(vf, &patchTemp)) {
397				threadContext->patch = vf;
398			} else {
399				vf->close(vf);
400			}
401			dirent = threadContext->gameDir->listNext(threadContext->gameDir);
402		}
403
404	}
405
406	if (!threadContext->rom) {
407		threadContext->state = THREAD_SHUTDOWN;
408		return false;
409	}
410
411	threadContext->save = VDirOptionalOpenFile(threadContext->stateDir, threadContext->fname, "sram", ".sav", O_CREAT | O_RDWR);
412
413	MutexInit(&threadContext->stateMutex);
414	ConditionInit(&threadContext->stateCond);
415
416	MutexInit(&threadContext->sync.videoFrameMutex);
417	ConditionInit(&threadContext->sync.videoFrameAvailableCond);
418	ConditionInit(&threadContext->sync.videoFrameRequiredCond);
419	MutexInit(&threadContext->sync.audioBufferMutex);
420	ConditionInit(&threadContext->sync.audioRequiredCond);
421
422	threadContext->interruptDepth = 0;
423
424#ifndef _WIN32
425	sigset_t signals;
426	sigemptyset(&signals);
427	sigaddset(&signals, SIGINT);
428	sigaddset(&signals, SIGTRAP);
429	pthread_sigmask(SIG_BLOCK, &signals, 0);
430#endif
431
432	MutexLock(&threadContext->stateMutex);
433	ThreadCreate(&threadContext->thread, _GBAThreadRun, threadContext);
434	while (threadContext->state < THREAD_RUNNING) {
435		ConditionWait(&threadContext->stateCond, &threadContext->stateMutex);
436	}
437	MutexUnlock(&threadContext->stateMutex);
438
439	return true;
440}
441
442bool GBAThreadHasStarted(struct GBAThread* threadContext) {
443	bool hasStarted;
444	MutexLock(&threadContext->stateMutex);
445	hasStarted = threadContext->state > THREAD_INITIALIZED;
446	MutexUnlock(&threadContext->stateMutex);
447	return hasStarted;
448}
449
450bool GBAThreadHasExited(struct GBAThread* threadContext) {
451	bool hasExited;
452	MutexLock(&threadContext->stateMutex);
453	hasExited = threadContext->state > THREAD_EXITING;
454	MutexUnlock(&threadContext->stateMutex);
455	return hasExited;
456}
457
458bool GBAThreadHasCrashed(struct GBAThread* threadContext) {
459	bool hasExited;
460	MutexLock(&threadContext->stateMutex);
461	hasExited = threadContext->state == THREAD_CRASHED;
462	MutexUnlock(&threadContext->stateMutex);
463	return hasExited;
464}
465
466void GBAThreadEnd(struct GBAThread* threadContext) {
467	MutexLock(&threadContext->stateMutex);
468	_waitOnInterrupt(threadContext);
469	threadContext->state = THREAD_EXITING;
470	if (threadContext->gba) {
471		threadContext->gba->cpu->halted = false;
472	}
473	ConditionWake(&threadContext->stateCond);
474	MutexUnlock(&threadContext->stateMutex);
475	MutexLock(&threadContext->sync.audioBufferMutex);
476	threadContext->sync.audioWait = 0;
477	ConditionWake(&threadContext->sync.audioRequiredCond);
478	MutexUnlock(&threadContext->sync.audioBufferMutex);
479
480	MutexLock(&threadContext->sync.videoFrameMutex);
481	threadContext->sync.videoFrameWait = false;
482	threadContext->sync.videoFrameOn = false;
483	ConditionWake(&threadContext->sync.videoFrameRequiredCond);
484	ConditionWake(&threadContext->sync.videoFrameAvailableCond);
485	MutexUnlock(&threadContext->sync.videoFrameMutex);
486}
487
488void GBAThreadReset(struct GBAThread* threadContext) {
489	MutexLock(&threadContext->stateMutex);
490	_waitOnInterrupt(threadContext);
491	threadContext->state = THREAD_RESETING;
492	ConditionWake(&threadContext->stateCond);
493	MutexUnlock(&threadContext->stateMutex);
494}
495
496void GBAThreadJoin(struct GBAThread* threadContext) {
497	ThreadJoin(threadContext->thread);
498
499	MutexDeinit(&threadContext->stateMutex);
500	ConditionDeinit(&threadContext->stateCond);
501
502	MutexDeinit(&threadContext->sync.videoFrameMutex);
503	ConditionWake(&threadContext->sync.videoFrameAvailableCond);
504	ConditionDeinit(&threadContext->sync.videoFrameAvailableCond);
505	ConditionWake(&threadContext->sync.videoFrameRequiredCond);
506	ConditionDeinit(&threadContext->sync.videoFrameRequiredCond);
507
508	ConditionWake(&threadContext->sync.audioRequiredCond);
509	ConditionDeinit(&threadContext->sync.audioRequiredCond);
510	MutexDeinit(&threadContext->sync.audioBufferMutex);
511
512	int i;
513	for (i = 0; i < threadContext->rewindBufferCapacity; ++i) {
514		if (threadContext->rewindBuffer[i]) {
515			GBADeallocateState(threadContext->rewindBuffer[i]);
516		}
517	}
518	free(threadContext->rewindBuffer);
519
520	if (threadContext->rom) {
521		threadContext->rom->close(threadContext->rom);
522		threadContext->rom = 0;
523	}
524
525	if (threadContext->save) {
526		threadContext->save->close(threadContext->save);
527		threadContext->save = 0;
528	}
529
530	if (threadContext->bios) {
531		threadContext->bios->close(threadContext->bios);
532		threadContext->bios = 0;
533	}
534
535	if (threadContext->patch) {
536		threadContext->patch->close(threadContext->patch);
537		threadContext->patch = 0;
538	}
539
540	if (threadContext->gameDir) {
541		if (threadContext->stateDir == threadContext->gameDir) {
542			threadContext->stateDir = 0;
543		}
544		threadContext->gameDir->close(threadContext->gameDir);
545		threadContext->gameDir = 0;
546	}
547
548	if (threadContext->stateDir) {
549		threadContext->stateDir->close(threadContext->stateDir);
550		threadContext->stateDir = 0;
551	}
552}
553
554bool GBAThreadIsActive(struct GBAThread* threadContext) {
555	return threadContext->state >= THREAD_RUNNING && threadContext->state < THREAD_EXITING;
556}
557
558void GBAThreadInterrupt(struct GBAThread* threadContext) {
559	MutexLock(&threadContext->stateMutex);
560	++threadContext->interruptDepth;
561	if (threadContext->interruptDepth > 1 || !GBAThreadIsActive(threadContext)) {
562		MutexUnlock(&threadContext->stateMutex);
563		return;
564	}
565	threadContext->savedState = threadContext->state;
566	_waitOnInterrupt(threadContext);
567	threadContext->state = THREAD_INTERRUPTING;
568	threadContext->gba->cpu->nextEvent = 0;
569	ConditionWake(&threadContext->stateCond);
570	_waitUntilNotState(threadContext, THREAD_INTERRUPTING);
571	MutexUnlock(&threadContext->stateMutex);
572}
573
574void GBAThreadContinue(struct GBAThread* threadContext) {
575	MutexLock(&threadContext->stateMutex);
576	--threadContext->interruptDepth;
577	if (threadContext->interruptDepth < 1 && GBAThreadIsActive(threadContext)) {
578		threadContext->state = threadContext->savedState;
579		ConditionWake(&threadContext->stateCond);
580	}
581	MutexUnlock(&threadContext->stateMutex);
582}
583
584void GBAThreadPause(struct GBAThread* threadContext) {
585	bool frameOn = true;
586	MutexLock(&threadContext->stateMutex);
587	_waitOnInterrupt(threadContext);
588	if (threadContext->state == THREAD_RUNNING) {
589		_pauseThread(threadContext, false);
590		frameOn = false;
591	}
592	MutexUnlock(&threadContext->stateMutex);
593
594	_changeVideoSync(&threadContext->sync, frameOn);
595}
596
597void GBAThreadUnpause(struct GBAThread* threadContext) {
598	MutexLock(&threadContext->stateMutex);
599	_waitOnInterrupt(threadContext);
600	if (threadContext->state == THREAD_PAUSED || threadContext->state == THREAD_PAUSING) {
601		threadContext->state = THREAD_RUNNING;
602		ConditionWake(&threadContext->stateCond);
603	}
604	MutexUnlock(&threadContext->stateMutex);
605
606	_changeVideoSync(&threadContext->sync, true);
607}
608
609bool GBAThreadIsPaused(struct GBAThread* threadContext) {
610	bool isPaused;
611	MutexLock(&threadContext->stateMutex);
612	_waitOnInterrupt(threadContext);
613	isPaused = threadContext->state == THREAD_PAUSED;
614	MutexUnlock(&threadContext->stateMutex);
615	return isPaused;
616}
617
618void GBAThreadTogglePause(struct GBAThread* threadContext) {
619	bool frameOn = true;
620	MutexLock(&threadContext->stateMutex);
621	_waitOnInterrupt(threadContext);
622	if (threadContext->state == THREAD_PAUSED || threadContext->state == THREAD_PAUSING) {
623		threadContext->state = THREAD_RUNNING;
624		ConditionWake(&threadContext->stateCond);
625	} else 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 GBAThreadPauseFromThread(struct GBAThread* threadContext) {
635	bool frameOn = true;
636	MutexLock(&threadContext->stateMutex);
637	_waitOnInterrupt(threadContext);
638	if (threadContext->state == THREAD_RUNNING) {
639		_pauseThread(threadContext, true);
640		frameOn = false;
641	}
642	MutexUnlock(&threadContext->stateMutex);
643
644	_changeVideoSync(&threadContext->sync, frameOn);
645}
646
647#ifdef USE_PTHREADS
648struct GBAThread* GBAThreadGetContext(void) {
649	pthread_once(&_contextOnce, _createTLS);
650	return pthread_getspecific(_contextKey);
651}
652#elif _WIN32
653struct GBAThread* GBAThreadGetContext(void) {
654	InitOnceExecuteOnce(&_contextOnce, _createTLS, NULL, 0);
655	return TlsGetValue(_contextKey);
656}
657#endif
658
659#ifdef USE_PNG
660void GBAThreadTakeScreenshot(struct GBAThread* threadContext) {
661	unsigned stride;
662	void* pixels = 0;
663	struct VFile* vf = VDirOptionalOpenIncrementFile(threadContext->stateDir, threadContext->gba->activeFile, "screenshot", "-", ".png", O_CREAT | O_TRUNC | O_WRONLY);
664	threadContext->gba->video.renderer->getPixels(threadContext->gba->video.renderer, &stride, &pixels);
665	png_structp png = PNGWriteOpen(vf);
666	png_infop info = PNGWriteHeader(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
667	PNGWritePixels(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, stride, pixels);
668	PNGWriteClose(png, info);
669	vf->close(vf);
670}
671#endif
672
673#else
674struct GBAThread* GBAThreadGetContext(void) {
675	return 0;
676}
677#endif
678
679void GBASyncPostFrame(struct GBASync* sync) {
680	if (!sync) {
681		return;
682	}
683
684	MutexLock(&sync->videoFrameMutex);
685	++sync->videoFramePending;
686	--sync->videoFrameSkip;
687	if (sync->videoFrameSkip < 0) {
688		do {
689			ConditionWake(&sync->videoFrameAvailableCond);
690			if (sync->videoFrameWait) {
691				ConditionWait(&sync->videoFrameRequiredCond, &sync->videoFrameMutex);
692			}
693		} while (sync->videoFrameWait && sync->videoFramePending);
694	}
695	MutexUnlock(&sync->videoFrameMutex);
696}
697
698bool GBASyncWaitFrameStart(struct GBASync* sync, int frameskip) {
699	if (!sync) {
700		return true;
701	}
702
703	MutexLock(&sync->videoFrameMutex);
704	ConditionWake(&sync->videoFrameRequiredCond);
705	if (!sync->videoFrameOn && !sync->videoFramePending) {
706		return false;
707	}
708	if (sync->videoFrameOn) {
709		if (ConditionWaitTimed(&sync->videoFrameAvailableCond, &sync->videoFrameMutex, 50)) {
710			return false;
711		}
712	}
713	sync->videoFramePending = 0;
714	sync->videoFrameSkip = frameskip;
715	return true;
716}
717
718void GBASyncWaitFrameEnd(struct GBASync* sync) {
719	if (!sync) {
720		return;
721	}
722
723	MutexUnlock(&sync->videoFrameMutex);
724}
725
726bool GBASyncDrawingFrame(struct GBASync* sync) {
727	if (!sync) {
728		return true;
729	}
730
731	return sync->videoFrameSkip <= 0;
732}
733
734void GBASyncSuspendDrawing(struct GBASync* sync) {
735	if (!sync) {
736		return;
737	}
738
739	_changeVideoSync(sync, false);
740}
741
742void GBASyncResumeDrawing(struct GBASync* sync) {
743	if (!sync) {
744		return;
745	}
746
747	_changeVideoSync(sync, true);
748}
749
750void GBASyncProduceAudio(struct GBASync* sync, bool wait) {
751	if (!sync) {
752		return;
753	}
754
755	if (sync->audioWait && wait) {
756		// TODO loop properly in event of spurious wakeups
757		ConditionWait(&sync->audioRequiredCond, &sync->audioBufferMutex);
758	}
759	MutexUnlock(&sync->audioBufferMutex);
760}
761
762void GBASyncLockAudio(struct GBASync* sync) {
763	if (!sync) {
764		return;
765	}
766
767	MutexLock(&sync->audioBufferMutex);
768}
769
770void GBASyncUnlockAudio(struct GBASync* sync) {
771	if (!sync) {
772		return;
773	}
774
775	MutexUnlock(&sync->audioBufferMutex);
776}
777
778void GBASyncConsumeAudio(struct GBASync* sync) {
779	if (!sync) {
780		return;
781	}
782
783	ConditionWake(&sync->audioRequiredCond);
784	MutexUnlock(&sync->audioBufferMutex);
785}