all repos — mgba @ 6c87c1c69da9999c2c6fb1bf8932c06810750185

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