all repos — mgba @ f36a74759a291b63520eaabf853025ffbd221c80

mGBA Game Boy Advance Emulator

src/gba/gba-thread.c (view raw)

  1#include "gba-thread.h"
  2
  3#include "arm.h"
  4#include "gba.h"
  5#include "gba-serialize.h"
  6
  7#include "debugger/debugger.h"
  8
  9#include "util/patch.h"
 10#include "util/png-io.h"
 11#include "util/vfs.h"
 12
 13#include <signal.h>
 14
 15static const float _defaultFPSTarget = 60.f;
 16
 17#ifdef USE_PTHREADS
 18static pthread_key_t _contextKey;
 19static pthread_once_t _contextOnce = PTHREAD_ONCE_INIT;
 20
 21static void _createTLS(void) {
 22	pthread_key_create(&_contextKey, 0);
 23}
 24#else
 25static DWORD _contextKey;
 26static INIT_ONCE _contextOnce = INIT_ONCE_STATIC_INIT;
 27
 28static BOOL CALLBACK _createTLS(PINIT_ONCE once, PVOID param, PVOID* context) {
 29	UNUSED(once);
 30	UNUSED(param);
 31	UNUSED(context);
 32	_contextKey = TlsAlloc();
 33	return TRUE;
 34}
 35#endif
 36
 37static void _changeState(struct GBAThread* threadContext, enum ThreadState newState, bool broadcast) {
 38	MutexLock(&threadContext->stateMutex);
 39	threadContext->state = newState;
 40	if (broadcast) {
 41		ConditionWake(&threadContext->stateCond);
 42	}
 43	MutexUnlock(&threadContext->stateMutex);
 44}
 45
 46static void _waitOnInterrupt(struct GBAThread* threadContext) {
 47	while (threadContext->state == THREAD_INTERRUPTED) {
 48		ConditionWait(&threadContext->stateCond, &threadContext->stateMutex);
 49	}
 50}
 51
 52static void _waitUntilNotState(struct GBAThread* threadContext, enum ThreadState oldState) {
 53	while (threadContext->state == oldState) {
 54		MutexUnlock(&threadContext->stateMutex);
 55
 56		MutexLock(&threadContext->sync.videoFrameMutex);
 57		ConditionWake(&threadContext->sync.videoFrameRequiredCond);
 58		MutexUnlock(&threadContext->sync.videoFrameMutex);
 59
 60		MutexLock(&threadContext->sync.audioBufferMutex);
 61		ConditionWake(&threadContext->sync.audioRequiredCond);
 62		MutexUnlock(&threadContext->sync.audioBufferMutex);
 63
 64		MutexLock(&threadContext->stateMutex);
 65		ConditionWake(&threadContext->stateCond);
 66	}
 67}
 68
 69static void _pauseThread(struct GBAThread* threadContext, bool onThread) {
 70	if (threadContext->debugger && threadContext->debugger->state == DEBUGGER_RUNNING) {
 71		threadContext->debugger->state = DEBUGGER_EXITING;
 72	}
 73	threadContext->state = THREAD_PAUSING;
 74	if (!onThread) {
 75		_waitUntilNotState(threadContext, THREAD_PAUSING);
 76	}
 77}
 78
 79static void _changeVideoSync(struct GBASync* sync, bool frameOn) {
 80	// Make sure the video thread can process events while the GBA thread is paused
 81	MutexLock(&sync->videoFrameMutex);
 82	if (frameOn != sync->videoFrameOn) {
 83		sync->videoFrameOn = frameOn;
 84		ConditionWake(&sync->videoFrameAvailableCond);
 85	}
 86	MutexUnlock(&sync->videoFrameMutex);
 87}
 88
 89static THREAD_ENTRY _GBAThreadRun(void* context) {
 90#ifdef USE_PTHREADS
 91	pthread_once(&_contextOnce, _createTLS);
 92#else
 93	InitOnceExecuteOnce(&_contextOnce, _createTLS, NULL, 0);
 94#endif
 95
 96	struct GBA gba;
 97	struct ARMCore cpu;
 98	struct Patch patch;
 99	struct GBAThread* threadContext = context;
100	struct ARMComponent* components[1] = {};
101	int numComponents = 0;
102
103	if (threadContext->debugger) {
104		components[numComponents] = &threadContext->debugger->d;
105		++numComponents;
106	}
107
108#if !defined(_WIN32) && defined(USE_PTHREADS)
109	sigset_t signals;
110	sigemptyset(&signals);
111	pthread_sigmask(SIG_SETMASK, &signals, 0);
112#endif
113
114	GBACreate(&gba);
115	ARMSetComponents(&cpu, &gba.d, numComponents, components);
116	ARMInit(&cpu);
117	threadContext->gba = &gba;
118	gba.sync = &threadContext->sync;
119	gba.logLevel = threadContext->logLevel;
120#ifdef USE_PTHREADS
121	pthread_setspecific(_contextKey, threadContext);
122#else
123	TlsSetValue(_contextKey, threadContext);
124#endif
125
126	if (threadContext->audioBuffers) {
127		GBAAudioResizeBuffer(&gba.audio, threadContext->audioBuffers);
128	} else {
129		threadContext->audioBuffers = GBA_AUDIO_SAMPLES;
130	}
131
132	if (threadContext->renderer) {
133		GBAVideoAssociateRenderer(&gba.video, threadContext->renderer);
134	}
135
136	if (threadContext->rom) {
137		GBALoadROM(&gba, threadContext->rom, threadContext->save, threadContext->fname);
138		if (threadContext->bios) {
139			GBALoadBIOS(&gba, threadContext->bios);
140		}
141
142		if (threadContext->patch && loadPatch(threadContext->patch, &patch)) {
143			GBAApplyPatch(&gba, &patch);
144		}
145	}
146
147	ARMReset(&cpu);
148
149	if (threadContext->debugger) {
150		threadContext->debugger->log = GBADebuggerLogShim;
151		GBAAttachDebugger(&gba, threadContext->debugger);
152		ARMDebuggerEnter(threadContext->debugger, DEBUGGER_ENTER_ATTACHED);
153	}
154
155	GBASIOSetDriverSet(&gba.sio, &threadContext->sioDrivers);
156
157	gba.keySource = &threadContext->activeKeys;
158
159	if (threadContext->startCallback) {
160		threadContext->startCallback(threadContext);
161	}
162
163	_changeState(threadContext, THREAD_RUNNING, true);
164
165	while (threadContext->state < THREAD_EXITING) {
166		if (threadContext->debugger) {
167			struct ARMDebugger* debugger = threadContext->debugger;
168			ARMDebuggerRun(debugger);
169			if (debugger->state == DEBUGGER_SHUTDOWN) {
170				_changeState(threadContext, THREAD_EXITING, false);
171			}
172		} else {
173			while (threadContext->state == THREAD_RUNNING) {
174				ARMRunLoop(&cpu);
175			}
176		}
177
178		int resetScheduled = 0;
179		MutexLock(&threadContext->stateMutex);
180		if (threadContext->state == THREAD_PAUSING) {
181			threadContext->state = THREAD_PAUSED;
182			ConditionWake(&threadContext->stateCond);
183		}
184		if (threadContext->state == THREAD_INTERRUPTING) {
185			threadContext->state = THREAD_INTERRUPTED;
186			ConditionWake(&threadContext->stateCond);
187		}
188		if (threadContext->state == THREAD_RESETING) {
189			threadContext->state = THREAD_RUNNING;
190			resetScheduled = 1;
191		}
192		while (threadContext->state == THREAD_PAUSED) {
193			ConditionWait(&threadContext->stateCond, &threadContext->stateMutex);
194		}
195		MutexUnlock(&threadContext->stateMutex);
196		if (resetScheduled) {
197			ARMReset(&cpu);
198		}
199	}
200
201	while (threadContext->state != THREAD_SHUTDOWN) {
202		_changeState(threadContext, THREAD_SHUTDOWN, false);
203	}
204
205	if (threadContext->cleanCallback) {
206		threadContext->cleanCallback(threadContext);
207	}
208
209	threadContext->gba = 0;
210	ARMDeinit(&cpu);
211	GBADestroy(&gba);
212
213	threadContext->sync.videoFrameOn = false;
214	ConditionWake(&threadContext->sync.videoFrameAvailableCond);
215	ConditionWake(&threadContext->sync.audioRequiredCond);
216
217	return 0;
218}
219
220void GBAMapOptionsToContext(struct GBAOptions* opts, struct GBAThread* threadContext) {
221	threadContext->bios = VFileOpen(opts->bios, O_RDONLY);
222	threadContext->frameskip = opts->frameskip;
223	threadContext->logLevel = opts->logLevel;
224	threadContext->rewindBufferCapacity = opts->rewindBufferCapacity;
225	threadContext->rewindBufferInterval = opts->rewindBufferInterval;
226}
227
228void GBAMapStartupOptionsToContext(struct StartupOptions* opts, struct GBAThread* threadContext) {
229	if (opts->dirmode) {
230		threadContext->gameDir = VDirOpen(opts->fname);
231		threadContext->stateDir = threadContext->gameDir;
232	} else {
233		threadContext->rom = VFileOpen(opts->fname, O_RDONLY);
234#if ENABLE_LIBZIP
235		threadContext->gameDir = VDirOpenZip(opts->fname, 0);
236#endif
237	}
238	threadContext->fname = opts->fname;
239	threadContext->patch = VFileOpen(opts->patch, O_RDONLY);
240}
241
242bool GBAThreadStart(struct GBAThread* threadContext) {
243	// TODO: error check
244	threadContext->activeKeys = 0;
245	threadContext->state = THREAD_INITIALIZED;
246	threadContext->sync.videoFrameOn = true;
247	threadContext->sync.videoFrameSkip = 0;
248
249	threadContext->rewindBufferNext = threadContext->rewindBufferInterval;
250	threadContext->rewindBufferSize = 0;
251	if (threadContext->rewindBufferCapacity) {
252		threadContext->rewindBuffer = calloc(threadContext->rewindBufferCapacity, sizeof(void*));
253	} else {
254		threadContext->rewindBuffer = 0;
255	}
256
257	if (!threadContext->fpsTarget) {
258		threadContext->fpsTarget = _defaultFPSTarget;
259	}
260
261	if (threadContext->rom && !GBAIsROM(threadContext->rom)) {
262		threadContext->rom->close(threadContext->rom);
263		threadContext->rom = 0;
264	}
265
266	if (threadContext->gameDir) {
267		threadContext->gameDir->rewind(threadContext->gameDir);
268		struct VDirEntry* dirent = threadContext->gameDir->listNext(threadContext->gameDir);
269		while (dirent) {
270			struct Patch patchTemp;
271			struct VFile* vf = threadContext->gameDir->openFile(threadContext->gameDir, dirent->name(dirent), O_RDONLY);
272			if (!vf) {
273				continue;
274			}
275			if (!threadContext->rom && GBAIsROM(vf)) {
276				threadContext->rom = vf;
277			} else if (!threadContext->patch && loadPatch(vf, &patchTemp)) {
278				threadContext->patch = vf;
279			} else {
280				vf->close(vf);
281			}
282			dirent = threadContext->gameDir->listNext(threadContext->gameDir);
283		}
284
285	}
286
287	if (!threadContext->rom) {
288		threadContext->state = THREAD_SHUTDOWN;
289		return false;
290	}
291
292	threadContext->save = VDirOptionalOpenFile(threadContext->stateDir, threadContext->fname, "sram", ".sav", O_CREAT | O_RDWR);
293
294	MutexInit(&threadContext->stateMutex);
295	ConditionInit(&threadContext->stateCond);
296
297	MutexInit(&threadContext->sync.videoFrameMutex);
298	ConditionInit(&threadContext->sync.videoFrameAvailableCond);
299	ConditionInit(&threadContext->sync.videoFrameRequiredCond);
300	MutexInit(&threadContext->sync.audioBufferMutex);
301	ConditionInit(&threadContext->sync.audioRequiredCond);
302
303#ifndef _WIN32
304	sigset_t signals;
305	sigemptyset(&signals);
306	sigaddset(&signals, SIGINT);
307	sigaddset(&signals, SIGTRAP);
308	pthread_sigmask(SIG_BLOCK, &signals, 0);
309#endif
310
311	MutexLock(&threadContext->stateMutex);
312	ThreadCreate(&threadContext->thread, _GBAThreadRun, threadContext);
313	while (threadContext->state < THREAD_RUNNING) {
314		ConditionWait(&threadContext->stateCond, &threadContext->stateMutex);
315	}
316	MutexUnlock(&threadContext->stateMutex);
317
318	return true;
319}
320
321bool GBAThreadHasStarted(struct GBAThread* threadContext) {
322	bool hasStarted;
323	MutexLock(&threadContext->stateMutex);
324	hasStarted = threadContext->state > THREAD_INITIALIZED;
325	MutexUnlock(&threadContext->stateMutex);
326	return hasStarted;
327}
328
329void GBAThreadEnd(struct GBAThread* threadContext) {
330	MutexLock(&threadContext->stateMutex);
331	if (threadContext->debugger && threadContext->debugger->state == DEBUGGER_RUNNING) {
332		threadContext->debugger->state = DEBUGGER_EXITING;
333	}
334	threadContext->state = THREAD_EXITING;
335	ConditionWake(&threadContext->stateCond);
336	MutexUnlock(&threadContext->stateMutex);
337	MutexLock(&threadContext->sync.audioBufferMutex);
338	threadContext->sync.audioWait = 0;
339	ConditionWake(&threadContext->sync.audioRequiredCond);
340	MutexUnlock(&threadContext->sync.audioBufferMutex);
341}
342
343void GBAThreadReset(struct GBAThread* threadContext) {
344	MutexLock(&threadContext->stateMutex);
345	_waitOnInterrupt(threadContext);
346	threadContext->state = THREAD_RESETING;
347	ConditionWake(&threadContext->stateCond);
348	MutexUnlock(&threadContext->stateMutex);
349}
350
351void GBAThreadJoin(struct GBAThread* threadContext) {
352	MutexLock(&threadContext->sync.videoFrameMutex);
353	threadContext->sync.videoFrameWait = 0;
354	ConditionWake(&threadContext->sync.videoFrameRequiredCond);
355	MutexUnlock(&threadContext->sync.videoFrameMutex);
356
357	ThreadJoin(threadContext->thread);
358
359	MutexDeinit(&threadContext->stateMutex);
360	ConditionDeinit(&threadContext->stateCond);
361
362	MutexDeinit(&threadContext->sync.videoFrameMutex);
363	ConditionWake(&threadContext->sync.videoFrameAvailableCond);
364	ConditionDeinit(&threadContext->sync.videoFrameAvailableCond);
365	ConditionWake(&threadContext->sync.videoFrameRequiredCond);
366	ConditionDeinit(&threadContext->sync.videoFrameRequiredCond);
367
368	ConditionWake(&threadContext->sync.audioRequiredCond);
369	ConditionDeinit(&threadContext->sync.audioRequiredCond);
370	MutexDeinit(&threadContext->sync.audioBufferMutex);
371
372	int i;
373	for (i = 0; i < threadContext->rewindBufferCapacity; ++i) {
374		if (threadContext->rewindBuffer[i]) {
375			GBADeallocateState(threadContext->rewindBuffer[i]);
376		}
377	}
378	free(threadContext->rewindBuffer);
379
380	GBAInputMapDeinit(&threadContext->inputMap);
381
382	if (threadContext->rom) {
383		threadContext->rom->close(threadContext->rom);
384		threadContext->rom = 0;
385	}
386
387	if (threadContext->save) {
388		threadContext->save->close(threadContext->save);
389		threadContext->save = 0;
390	}
391
392	if (threadContext->bios) {
393		threadContext->bios->close(threadContext->bios);
394		threadContext->bios = 0;
395	}
396
397	if (threadContext->patch) {
398		threadContext->patch->close(threadContext->patch);
399		threadContext->patch = 0;
400	}
401
402	if (threadContext->gameDir) {
403		if (threadContext->stateDir == threadContext->gameDir) {
404			threadContext->stateDir = 0;
405		}
406		threadContext->gameDir->close(threadContext->gameDir);
407		threadContext->gameDir = 0;
408	}
409
410	if (threadContext->stateDir) {
411		threadContext->stateDir->close(threadContext->stateDir);
412		threadContext->stateDir = 0;
413	}
414}
415
416void GBAThreadInterrupt(struct GBAThread* threadContext) {
417	MutexLock(&threadContext->stateMutex);
418	threadContext->savedState = threadContext->state;
419	_waitOnInterrupt(threadContext);
420	threadContext->state = THREAD_INTERRUPTING;
421	if (threadContext->debugger && threadContext->debugger->state == DEBUGGER_RUNNING) {
422		threadContext->debugger->state = DEBUGGER_EXITING;
423	}
424	ConditionWake(&threadContext->stateCond);
425	_waitUntilNotState(threadContext, THREAD_INTERRUPTING);
426	MutexUnlock(&threadContext->stateMutex);
427}
428
429void GBAThreadContinue(struct GBAThread* threadContext) {
430	_changeState(threadContext, threadContext->savedState, 1);
431}
432
433void GBAThreadPause(struct GBAThread* threadContext) {
434	bool frameOn = true;
435	MutexLock(&threadContext->stateMutex);
436	_waitOnInterrupt(threadContext);
437	if (threadContext->state == THREAD_RUNNING) {
438		_pauseThread(threadContext, false);
439		frameOn = false;
440	}
441	MutexUnlock(&threadContext->stateMutex);
442
443	_changeVideoSync(&threadContext->sync, frameOn);
444}
445
446void GBAThreadUnpause(struct GBAThread* threadContext) {
447	MutexLock(&threadContext->stateMutex);
448	_waitOnInterrupt(threadContext);
449	if (threadContext->state == THREAD_PAUSED || threadContext->state == THREAD_PAUSING) {
450		threadContext->state = THREAD_RUNNING;
451		ConditionWake(&threadContext->stateCond);
452	}
453	MutexUnlock(&threadContext->stateMutex);
454
455	_changeVideoSync(&threadContext->sync, true);
456}
457
458bool GBAThreadIsPaused(struct GBAThread* threadContext) {
459	bool isPaused;
460	MutexLock(&threadContext->stateMutex);
461	_waitOnInterrupt(threadContext);
462	isPaused = threadContext->state == THREAD_PAUSED;
463	MutexUnlock(&threadContext->stateMutex);
464	return isPaused;
465}
466
467void GBAThreadTogglePause(struct GBAThread* threadContext) {
468	bool frameOn = true;
469	MutexLock(&threadContext->stateMutex);
470	_waitOnInterrupt(threadContext);
471	if (threadContext->state == THREAD_PAUSED || threadContext->state == THREAD_PAUSING) {
472		threadContext->state = THREAD_RUNNING;
473		ConditionWake(&threadContext->stateCond);
474	} else if (threadContext->state == THREAD_RUNNING) {
475		_pauseThread(threadContext, false);
476		frameOn = false;
477	}
478	MutexUnlock(&threadContext->stateMutex);
479
480	_changeVideoSync(&threadContext->sync, frameOn);
481}
482
483void GBAThreadPauseFromThread(struct GBAThread* threadContext) {
484	bool frameOn = true;
485	MutexLock(&threadContext->stateMutex);
486	_waitOnInterrupt(threadContext);
487	if (threadContext->state == THREAD_RUNNING) {
488		_pauseThread(threadContext, true);
489		frameOn = false;
490	}
491	MutexUnlock(&threadContext->stateMutex);
492
493	_changeVideoSync(&threadContext->sync, frameOn);
494}
495
496#ifdef USE_PTHREADS
497struct GBAThread* GBAThreadGetContext(void) {
498	pthread_once(&_contextOnce, _createTLS);
499	return pthread_getspecific(_contextKey);
500}
501#else
502struct GBAThread* GBAThreadGetContext(void) {
503	InitOnceExecuteOnce(&_contextOnce, _createTLS, NULL, 0);
504	return TlsGetValue(_contextKey);
505}
506#endif
507
508#ifdef USE_PNG
509void GBAThreadTakeScreenshot(struct GBAThread* threadContext) {
510	unsigned stride;
511	void* pixels = 0;
512	struct VFile* vf = VDirOptionalOpenIncrementFile(threadContext->stateDir, threadContext->gba->activeFile, "screenshot", "-", ".png", O_CREAT | O_TRUNC | O_WRONLY);
513	threadContext->gba->video.renderer->getPixels(threadContext->gba->video.renderer, &stride, &pixels);
514	png_structp png = PNGWriteOpen(vf);
515	png_infop info = PNGWriteHeader(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS);
516	PNGWritePixels(png, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, stride, pixels);
517	PNGWriteClose(png, info);
518	vf->close(vf);
519}
520#endif
521
522void GBASyncPostFrame(struct GBASync* sync) {
523	if (!sync) {
524		return;
525	}
526
527	MutexLock(&sync->videoFrameMutex);
528	++sync->videoFramePending;
529	--sync->videoFrameSkip;
530	if (sync->videoFrameSkip < 0) {
531		do {
532			ConditionWake(&sync->videoFrameAvailableCond);
533			if (sync->videoFrameWait) {
534				ConditionWait(&sync->videoFrameRequiredCond, &sync->videoFrameMutex);
535			}
536		} while (sync->videoFrameWait && sync->videoFramePending);
537	}
538	MutexUnlock(&sync->videoFrameMutex);
539
540	struct GBAThread* thread = GBAThreadGetContext();
541	if (!thread) {
542		return;
543	}
544
545	if (thread->rewindBuffer) {
546		--thread->rewindBufferNext;
547		if (thread->rewindBufferNext <= 0) {
548			thread->rewindBufferNext = thread->rewindBufferInterval;
549			GBARecordFrame(thread);
550		}
551	}
552	if (thread->stream) {
553		thread->stream->postVideoFrame(thread->stream, thread->renderer);
554	}
555	if (thread->frameCallback) {
556		thread->frameCallback(thread);
557	}
558}
559
560bool GBASyncWaitFrameStart(struct GBASync* sync, int frameskip) {
561	if (!sync) {
562		return true;
563	}
564
565	MutexLock(&sync->videoFrameMutex);
566	ConditionWake(&sync->videoFrameRequiredCond);
567	if (!sync->videoFrameOn && !sync->videoFramePending) {
568		return false;
569	}
570	if (sync->videoFrameOn && !sync->videoFramePending) {
571		ConditionWait(&sync->videoFrameAvailableCond, &sync->videoFrameMutex);
572	}
573	sync->videoFramePending = 0;
574	sync->videoFrameSkip = frameskip;
575	return true;
576}
577
578void GBASyncWaitFrameEnd(struct GBASync* sync) {
579	if (!sync) {
580		return;
581	}
582
583	MutexUnlock(&sync->videoFrameMutex);
584}
585
586bool GBASyncDrawingFrame(struct GBASync* sync) {
587	return sync->videoFrameSkip <= 0;
588}
589
590void GBASyncSuspendDrawing(struct GBASync* sync) {
591	_changeVideoSync(sync, false);
592}
593
594void GBASyncResumeDrawing(struct GBASync* sync) {
595	_changeVideoSync(sync, true);
596}
597
598void GBASyncProduceAudio(struct GBASync* sync, bool wait) {
599	if (sync->audioWait && wait) {
600		// TODO loop properly in event of spurious wakeups
601		ConditionWait(&sync->audioRequiredCond, &sync->audioBufferMutex);
602	}
603	MutexUnlock(&sync->audioBufferMutex);
604}
605
606void GBASyncLockAudio(struct GBASync* sync) {
607	MutexLock(&sync->audioBufferMutex);
608}
609
610void GBASyncUnlockAudio(struct GBASync* sync) {
611	MutexUnlock(&sync->audioBufferMutex);
612}
613
614void GBASyncConsumeAudio(struct GBASync* sync) {
615	ConditionWake(&sync->audioRequiredCond);
616	MutexUnlock(&sync->audioBufferMutex);
617}