all repos — mgba @ 0a6e2b49ab3cc40b7ba4752d47e04ed9a13b7192

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/context/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/vfs.h"
 20
 21#include "platform/commandline.h"
 22
 23#include <signal.h>
 24
 25static void _loadGameDir(struct GBAThread* threadContext);
 26
 27static const float _defaultFPSTarget = 60.f;
 28
 29#ifndef DISABLE_THREADING
 30#ifdef USE_PTHREADS
 31static pthread_key_t _contextKey;
 32static pthread_once_t _contextOnce = PTHREAD_ONCE_INIT;
 33
 34static void _createTLS(void) {
 35	pthread_key_create(&_contextKey, 0);
 36}
 37#elif _WIN32
 38static DWORD _contextKey;
 39static INIT_ONCE _contextOnce = INIT_ONCE_STATIC_INIT;
 40
 41static BOOL CALLBACK _createTLS(PINIT_ONCE once, PVOID param, PVOID* context) {
 42	UNUSED(once);
 43	UNUSED(param);
 44	UNUSED(context);
 45	_contextKey = TlsAlloc();
 46	return TRUE;
 47}
 48#endif
 49
 50static void _changeState(struct GBAThread* threadContext, enum ThreadState newState, bool broadcast) {
 51	MutexLock(&threadContext->stateMutex);
 52	threadContext->state = newState;
 53	if (broadcast) {
 54		ConditionWake(&threadContext->stateCond);
 55	}
 56	MutexUnlock(&threadContext->stateMutex);
 57}
 58
 59static void _waitOnInterrupt(struct GBAThread* threadContext) {
 60	while (threadContext->state == THREAD_INTERRUPTED) {
 61		ConditionWait(&threadContext->stateCond, &threadContext->stateMutex);
 62	}
 63}
 64
 65static void _waitUntilNotState(struct GBAThread* threadContext, enum ThreadState oldState) {
 66	MutexLock(&threadContext->sync.videoFrameMutex);
 67	bool videoFrameWait = threadContext->sync.videoFrameWait;
 68	threadContext->sync.videoFrameWait = false;
 69	MutexUnlock(&threadContext->sync.videoFrameMutex);
 70
 71	while (threadContext->state == oldState) {
 72		MutexUnlock(&threadContext->stateMutex);
 73
 74		if (!MutexTryLock(&threadContext->sync.videoFrameMutex)) {
 75			ConditionWake(&threadContext->sync.videoFrameRequiredCond);
 76			MutexUnlock(&threadContext->sync.videoFrameMutex);
 77		}
 78
 79		if (!MutexTryLock(&threadContext->sync.audioBufferMutex)) {
 80			ConditionWake(&threadContext->sync.audioRequiredCond);
 81			MutexUnlock(&threadContext->sync.audioBufferMutex);
 82		}
 83
 84		MutexLock(&threadContext->stateMutex);
 85		ConditionWake(&threadContext->stateCond);
 86	}
 87
 88	MutexLock(&threadContext->sync.videoFrameMutex);
 89	threadContext->sync.videoFrameWait = videoFrameWait;
 90	MutexUnlock(&threadContext->sync.videoFrameMutex);
 91}
 92
 93static void _pauseThread(struct GBAThread* threadContext, bool onThread) {
 94	threadContext->state = THREAD_PAUSING;
 95	if (!onThread) {
 96		_waitUntilNotState(threadContext, THREAD_PAUSING);
 97	}
 98}
 99
100struct GBAThreadStop {
101	struct GBAStopCallback d;
102	struct GBAThread* p;
103};
104
105static void _stopCallback(struct GBAStopCallback* stop) {
106	struct GBAThreadStop* callback = (struct GBAThreadStop*) stop;
107	if (callback->p->stopCallback(callback->p)) {
108		_changeState(callback->p, THREAD_EXITING, false);
109	}
110}
111
112static THREAD_ENTRY _GBAThreadRun(void* context) {
113#ifdef USE_PTHREADS
114	pthread_once(&_contextOnce, _createTLS);
115#elif _WIN32
116	InitOnceExecuteOnce(&_contextOnce, _createTLS, NULL, 0);
117#endif
118
119	struct GBA gba;
120	struct ARMCore cpu;
121	struct Patch patch;
122	struct GBACheatDevice cheatDevice;
123	struct GBAThread* threadContext = context;
124	struct ARMComponent* components[GBA_COMPONENT_MAX] = { 0 };
125	struct GBARRContext* movie = 0;
126	int numComponents = GBA_COMPONENT_MAX;
127
128	ThreadSetName("CPU Thread");
129
130#if !defined(_WIN32) && defined(USE_PTHREADS)
131	sigset_t signals;
132	sigemptyset(&signals);
133	pthread_sigmask(SIG_SETMASK, &signals, 0);
134#endif
135
136	GBACreate(&gba);
137	ARMSetComponents(&cpu, &gba.d, numComponents, components);
138	ARMInit(&cpu);
139	gba.sync = &threadContext->sync;
140	threadContext->gba = &gba;
141	threadContext->cpu = &cpu;
142	gba.logLevel = threadContext->logLevel;
143	gba.logHandler = threadContext->logHandler;
144	gba.stream = threadContext->stream;
145	gba.video.frameskip = threadContext->frameskip;
146
147	struct GBAThreadStop stop;
148	if (threadContext->stopCallback) {
149		stop.d.stop = _stopCallback;
150		stop.p = threadContext;
151		gba.stopCallback = &stop.d;
152	}
153
154	gba.idleOptimization = threadContext->idleOptimization;
155#ifdef USE_PTHREADS
156	pthread_setspecific(_contextKey, threadContext);
157#elif _WIN32
158	TlsSetValue(_contextKey, threadContext);
159#endif
160
161	if (threadContext->audioBuffers) {
162		GBAAudioResizeBuffer(&gba.audio, threadContext->audioBuffers);
163	} else {
164		threadContext->audioBuffers = GBA_AUDIO_SAMPLES;
165	}
166
167	if (threadContext->renderer) {
168		GBAVideoAssociateRenderer(&gba.video, threadContext->renderer);
169	}
170
171	if (threadContext->rom) {
172		if (GBAIsMB(threadContext->rom)) {
173			GBALoadMB(&gba, threadContext->rom, threadContext->fname);
174		} else {
175			GBALoadROM(&gba, threadContext->rom, threadContext->save, threadContext->fname);
176		}
177
178		struct GBACartridgeOverride override;
179		const struct GBACartridge* cart = (const struct GBACartridge*) gba.pristineRom;
180		memcpy(override.id, &cart->id, sizeof(override.id));
181		if (GBAOverrideFind(threadContext->overrides, &override)) {
182			GBAOverrideApply(&gba, &override);
183		}
184		if (threadContext->hasOverride) {
185			GBAOverrideApply(&gba, &threadContext->override);
186		}
187
188		if (threadContext->patch && loadPatch(threadContext->patch, &patch)) {
189			GBAApplyPatch(&gba, &patch);
190		}
191	}
192
193	if (threadContext->bios && GBAIsBIOS(threadContext->bios)) {
194		GBALoadBIOS(&gba, threadContext->bios);
195	}
196
197	if (threadContext->movie) {
198		struct VDir* movieDir = VDirOpen(threadContext->movie);
199#ifdef USE_LIBZIP
200		if (!movieDir) {
201			movieDir = VDirOpenZip(threadContext->movie, 0);
202		}
203#endif
204		if (movieDir) {
205			struct GBAMGMContext* mgm = malloc(sizeof(*mgm));
206			GBAMGMContextCreate(mgm);
207			if (!GBAMGMSetStream(mgm, movieDir)) {
208				mgm->d.destroy(&mgm->d);
209			} else {
210				movie = &mgm->d;
211			}
212		} else {
213			struct VFile* movieFile = VFileOpen(threadContext->movie, O_RDONLY);
214			if (movieFile) {
215				struct GBAVBMContext* vbm = malloc(sizeof(*vbm));
216				GBAVBMContextCreate(vbm);
217				if (!GBAVBMSetStream(vbm, movieFile)) {
218					vbm->d.destroy(&vbm->d);
219				} else {
220					movie = &vbm->d;
221				}
222			}
223		}
224	}
225
226	ARMReset(&cpu);
227
228	if (movie) {
229		gba.rr = movie;
230		movie->startPlaying(movie, false);
231		GBARRInitPlay(&gba);
232	}
233
234	if (threadContext->skipBios && gba.pristineRom) {
235		GBASkipBIOS(&gba);
236	}
237
238	if (!threadContext->cheats) {
239		GBACheatDeviceCreate(&cheatDevice);
240		threadContext->cheats = &cheatDevice;
241	}
242	if (threadContext->cheatsFile) {
243		GBACheatParseFile(threadContext->cheats, threadContext->cheatsFile);
244	}
245	GBACheatAttachDevice(&gba, threadContext->cheats);
246
247	if (threadContext->debugger) {
248		threadContext->debugger->log = GBADebuggerLogShim;
249		GBAAttachDebugger(&gba, threadContext->debugger);
250		ARMDebuggerEnter(threadContext->debugger, DEBUGGER_ENTER_ATTACHED, 0);
251	}
252
253	GBASIOSetDriverSet(&gba.sio, &threadContext->sioDrivers);
254
255	if (threadContext->volume == 0) {
256		threadContext->volume = GBA_AUDIO_VOLUME_MAX;
257	}
258	if (threadContext->mute) {
259		gba.audio.masterVolume = 0;
260	} else {
261		gba.audio.masterVolume = threadContext->volume;
262	}
263
264	gba.keySource = &threadContext->activeKeys;
265
266	if (threadContext->startCallback) {
267		threadContext->startCallback(threadContext);
268	}
269
270	_changeState(threadContext, THREAD_RUNNING, true);
271
272	while (threadContext->state < THREAD_EXITING) {
273		if (threadContext->debugger) {
274			struct ARMDebugger* debugger = threadContext->debugger;
275			ARMDebuggerRun(debugger);
276			if (debugger->state == DEBUGGER_SHUTDOWN) {
277				_changeState(threadContext, THREAD_EXITING, false);
278			}
279		} else {
280			while (threadContext->state == THREAD_RUNNING) {
281				ARMRunLoop(&cpu);
282			}
283		}
284
285		int resetScheduled = 0;
286		MutexLock(&threadContext->stateMutex);
287		while (threadContext->state > THREAD_RUNNING && threadContext->state < THREAD_EXITING) {
288			if (threadContext->state == THREAD_PAUSING) {
289				threadContext->state = THREAD_PAUSED;
290				ConditionWake(&threadContext->stateCond);
291			}
292			if (threadContext->state == THREAD_INTERRUPTING) {
293				threadContext->state = THREAD_INTERRUPTED;
294				ConditionWake(&threadContext->stateCond);
295			}
296			if (threadContext->state == THREAD_RUN_ON) {
297				if (threadContext->run) {
298					threadContext->run(threadContext);
299				}
300				threadContext->state = threadContext->savedState;
301				ConditionWake(&threadContext->stateCond);
302			}
303			if (threadContext->state == THREAD_RESETING) {
304				threadContext->state = THREAD_RUNNING;
305				resetScheduled = 1;
306			}
307			while (threadContext->state == THREAD_PAUSED || threadContext->state == THREAD_INTERRUPTED) {
308				ConditionWait(&threadContext->stateCond, &threadContext->stateMutex);
309			}
310		}
311		MutexUnlock(&threadContext->stateMutex);
312		if (resetScheduled) {
313			ARMReset(&cpu);
314			if (threadContext->skipBios && gba.pristineRom) {
315				GBASkipBIOS(&gba);
316			}
317		}
318	}
319
320	while (threadContext->state < THREAD_SHUTDOWN) {
321		_changeState(threadContext, THREAD_SHUTDOWN, false);
322	}
323
324	if (threadContext->cleanCallback) {
325		threadContext->cleanCallback(threadContext);
326	}
327
328	threadContext->gba = 0;
329	ARMDeinit(&cpu);
330	GBADestroy(&gba);
331	if (&cheatDevice == threadContext->cheats) {
332		GBACheatDeviceDestroy(&cheatDevice);
333	}
334
335	if (movie) {
336		movie->destroy(movie);
337		free(movie);
338	}
339
340	threadContext->sync.videoFrameOn = false;
341	ConditionWake(&threadContext->sync.videoFrameAvailableCond);
342	ConditionWake(&threadContext->sync.audioRequiredCond);
343
344	return 0;
345}
346
347void GBAMapOptionsToContext(const struct GBAOptions* opts, struct GBAThread* threadContext) {
348	if (opts->useBios) {
349		threadContext->bios = VFileOpen(opts->bios, O_RDONLY);
350	} else {
351		threadContext->bios = 0;
352	}
353	threadContext->frameskip = opts->frameskip;
354	threadContext->volume = opts->volume;
355	threadContext->mute = opts->mute;
356	threadContext->logLevel = opts->logLevel;
357	if (opts->rewindEnable) {
358		threadContext->rewindBufferCapacity = opts->rewindBufferCapacity;
359		threadContext->rewindBufferInterval = opts->rewindBufferInterval;
360	} else {
361		threadContext->rewindBufferCapacity = 0;
362	}
363	threadContext->skipBios = opts->skipBios;
364	threadContext->sync.audioWait = opts->audioSync;
365	threadContext->sync.videoFrameWait = opts->videoSync;
366
367	if (opts->fpsTarget) {
368		threadContext->fpsTarget = opts->fpsTarget;
369	}
370
371	if (opts->audioBuffers) {
372		threadContext->audioBuffers = opts->audioBuffers;
373	}
374
375	threadContext->idleOptimization = opts->idleOptimization;
376}
377
378void GBAMapArgumentsToContext(const struct GBAArguments* args, struct GBAThread* threadContext) {
379	if (args->dirmode) {
380		threadContext->gameDir = VDirOpen(args->fname);
381		threadContext->stateDir = threadContext->gameDir;
382	} else {
383		GBAThreadLoadROM(threadContext, args->fname);
384	}
385	threadContext->fname = args->fname;
386	threadContext->patch = VFileOpen(args->patch, O_RDONLY);
387	threadContext->cheatsFile = VFileOpen(args->cheatsFile, O_RDONLY);
388	threadContext->movie = args->movie;
389}
390
391bool GBAThreadStart(struct GBAThread* threadContext) {
392	// TODO: error check
393	threadContext->activeKeys = 0;
394	threadContext->state = THREAD_INITIALIZED;
395	threadContext->sync.videoFrameOn = true;
396
397	threadContext->rewindBuffer = 0;
398	threadContext->rewindScreenBuffer = 0;
399	int newCapacity = threadContext->rewindBufferCapacity;
400	int newInterval = threadContext->rewindBufferInterval;
401	threadContext->rewindBufferCapacity = 0;
402	threadContext->rewindBufferInterval = 0;
403	GBARewindSettingsChanged(threadContext, newCapacity, newInterval);
404
405	if (!threadContext->fpsTarget) {
406		threadContext->fpsTarget = _defaultFPSTarget;
407	}
408
409	bool bootBios = threadContext->bootBios && threadContext->bios;
410
411	if (threadContext->rom && (!GBAIsROM(threadContext->rom) || bootBios)) {
412		threadContext->rom->close(threadContext->rom);
413		threadContext->rom = 0;
414	}
415
416	if (threadContext->gameDir) {
417		_loadGameDir(threadContext);
418	}
419
420	if (!threadContext->rom && !bootBios) {
421		threadContext->state = THREAD_SHUTDOWN;
422		return false;
423	}
424
425	threadContext->save = VDirOptionalOpenFile(threadContext->stateDir, threadContext->fname, "sram", ".sav", O_CREAT | O_RDWR);
426
427	if (!threadContext->patch) {
428		threadContext->patch = VDirOptionalOpenFile(threadContext->stateDir, threadContext->fname, "patch", ".ups", O_RDONLY);
429	}
430	if (!threadContext->patch) {
431		threadContext->patch = VDirOptionalOpenFile(threadContext->stateDir, threadContext->fname, "patch", ".ips", O_RDONLY);
432	}
433	if (!threadContext->patch) {
434		threadContext->patch = VDirOptionalOpenFile(threadContext->stateDir, threadContext->fname, "patch", ".bps", O_RDONLY);
435	}
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#ifdef USE_PTHREADS
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	GBASyncSetVideoSync(&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	GBASyncSetVideoSync(&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	GBASyncSetVideoSync(&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	GBASyncSetVideoSync(&threadContext->sync, frameOn);
687}
688
689void GBAThreadLoadROM(struct GBAThread* threadContext, const char* fname) {
690	threadContext->rom = VFileOpen(fname, O_RDONLY);
691	threadContext->gameDir = 0;
692	if (!threadContext->gameDir) {
693		threadContext->gameDir = VDirOpenArchive(fname);
694	}
695}
696
697static void _loadGameDir(struct GBAThread* threadContext) {
698	threadContext->gameDir->rewind(threadContext->gameDir);
699	struct VDirEntry* dirent = threadContext->gameDir->listNext(threadContext->gameDir);
700	while (dirent) {
701		struct Patch patchTemp;
702		struct VFile* vf = threadContext->gameDir->openFile(threadContext->gameDir, dirent->name(dirent), O_RDONLY);
703		if (!vf) {
704			dirent = threadContext->gameDir->listNext(threadContext->gameDir);
705			continue;
706		}
707		if (!threadContext->rom && GBAIsROM(vf)) {
708			threadContext->rom = vf;
709		} else if (!threadContext->patch && loadPatch(vf, &patchTemp)) {
710			threadContext->patch = vf;
711		} else {
712			vf->close(vf);
713		}
714		dirent = threadContext->gameDir->listNext(threadContext->gameDir);
715	}
716}
717
718void GBAThreadReplaceROM(struct GBAThread* threadContext, const char* fname) {
719	GBAUnloadROM(threadContext->gba);
720
721	if (threadContext->rom) {
722		threadContext->rom->close(threadContext->rom);
723		threadContext->rom = 0;
724	}
725
726	if (threadContext->save) {
727		threadContext->save->close(threadContext->save);
728		threadContext->save = 0;
729	}
730
731	GBAThreadLoadROM(threadContext, fname);
732	if (threadContext->gameDir) {
733		_loadGameDir(threadContext);
734	}
735
736	threadContext->fname = fname;
737	threadContext->save = VDirOptionalOpenFile(threadContext->stateDir, threadContext->fname, "sram", ".sav", O_CREAT | O_RDWR);
738
739	GBARaiseIRQ(threadContext->gba, IRQ_GAMEPAK);
740	GBALoadROM(threadContext->gba, threadContext->rom, threadContext->save, threadContext->fname);
741}
742
743#ifdef USE_PTHREADS
744struct GBAThread* GBAThreadGetContext(void) {
745	pthread_once(&_contextOnce, _createTLS);
746	return pthread_getspecific(_contextKey);
747}
748#elif _WIN32
749struct GBAThread* GBAThreadGetContext(void) {
750	InitOnceExecuteOnce(&_contextOnce, _createTLS, NULL, 0);
751	return TlsGetValue(_contextKey);
752}
753#endif
754
755void GBAThreadTakeScreenshot(struct GBAThread* threadContext) {
756	GBATakeScreenshot(threadContext->gba, threadContext->stateDir);
757}
758
759#else
760struct GBAThread* GBAThreadGetContext(void) {
761	return 0;
762}
763#endif