all repos — mgba @ 3f9abf2b05396e7219a7e9a6034c95b74cb0c055

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