all repos — mgba @ 80c61379a0a690871e0e69dbe8d1a943b2f9ed89

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/vfile.h"
 11
 12#include <signal.h>
 13
 14#ifdef USE_PTHREADS
 15static pthread_key_t _contextKey;
 16static pthread_once_t _contextOnce = PTHREAD_ONCE_INIT;
 17
 18static void _createTLS(void) {
 19	pthread_key_create(&_contextKey, 0);
 20}
 21#else
 22static DWORD _contextKey;
 23static INIT_ONCE _contextOnce = INIT_ONCE_STATIC_INIT;
 24
 25static BOOL CALLBACK _createTLS(PINIT_ONCE once, PVOID param, PVOID* context) {
 26	UNUSED(once);
 27	UNUSED(param);
 28	UNUSED(context);
 29	_contextKey = TlsAlloc();
 30	return TRUE;
 31}
 32#endif
 33
 34static void _changeState(struct GBAThread* threadContext, enum ThreadState newState, int broadcast) {
 35	MutexLock(&threadContext->stateMutex);
 36	threadContext->state = newState;
 37	if (broadcast) {
 38		ConditionWake(&threadContext->stateCond);
 39	}
 40	MutexUnlock(&threadContext->stateMutex);
 41}
 42
 43static void _waitOnInterrupt(struct GBAThread* threadContext) {
 44	while (threadContext->state == THREAD_INTERRUPTED) {
 45		ConditionWait(&threadContext->stateCond, &threadContext->stateMutex);
 46	}
 47}
 48
 49static THREAD_ENTRY _GBAThreadRun(void* context) {
 50#ifdef USE_PTHREADS
 51	pthread_once(&_contextOnce, _createTLS);
 52#else
 53	InitOnceExecuteOnce(&_contextOnce, _createTLS, NULL, 0);
 54#endif
 55
 56	struct GBA gba;
 57	struct ARMCore cpu;
 58	struct Patch patch;
 59	struct GBAThread* threadContext = context;
 60	struct ARMComponent* components[1] = {};
 61	int numComponents = 0;
 62
 63	if (threadContext->debugger) {
 64		components[numComponents] = &threadContext->debugger->d;
 65		++numComponents;
 66	}
 67
 68#if !defined(_WIN32) && defined(USE_PTHREADS)
 69	sigset_t signals;
 70	sigemptyset(&signals);
 71	pthread_sigmask(SIG_SETMASK, &signals, 0);
 72#endif
 73
 74	gba.logHandler = threadContext->logHandler;
 75	GBACreate(&gba);
 76	ARMSetComponents(&cpu, &gba.d, numComponents, components);
 77	ARMInit(&cpu);
 78	ARMReset(&cpu);
 79	threadContext->gba = &gba;
 80	gba.sync = &threadContext->sync;
 81	gba.logLevel = threadContext->logLevel;
 82#ifdef USE_PTHREADS
 83	pthread_setspecific(_contextKey, threadContext);
 84#else
 85	TlsSetValue(_contextKey, threadContext);
 86#endif
 87	if (threadContext->renderer) {
 88		GBAVideoAssociateRenderer(&gba.video, threadContext->renderer);
 89	}
 90
 91	if (threadContext->rom) {
 92		GBALoadROM(&gba, threadContext->rom, threadContext->save, threadContext->fname);
 93		if (threadContext->bios) {
 94			GBALoadBIOS(&gba, threadContext->bios);
 95		}
 96
 97		if (threadContext->patch && loadPatch(threadContext->patch, &patch)) {
 98			GBAApplyPatch(&gba, &patch);
 99		}
100	}
101
102	if (threadContext->debugger) {
103		GBAAttachDebugger(&gba, threadContext->debugger);
104		ARMDebuggerEnter(threadContext->debugger, DEBUGGER_ENTER_ATTACHED);
105	}
106
107	GBASIOSetDriverSet(&gba.sio, &threadContext->sioDrivers);
108
109	gba.keySource = &threadContext->activeKeys;
110
111	if (threadContext->startCallback) {
112		threadContext->startCallback(threadContext);
113	}
114
115	_changeState(threadContext, THREAD_RUNNING, 1);
116
117	while (threadContext->state < THREAD_EXITING) {
118		if (threadContext->debugger) {
119			struct ARMDebugger* debugger = threadContext->debugger;
120			ARMDebuggerRun(debugger);
121			if (debugger->state == DEBUGGER_SHUTDOWN) {
122				_changeState(threadContext, THREAD_EXITING, 0);
123			}
124		} else {
125			while (threadContext->state == THREAD_RUNNING) {
126				ARMRun(&cpu);
127			}
128		}
129
130		int resetScheduled = 0;
131		MutexLock(&threadContext->stateMutex);
132		if (threadContext->state == THREAD_PAUSING) {
133			threadContext->state = THREAD_PAUSED;
134			ConditionWake(&threadContext->stateCond);
135		}
136		if (threadContext->state == THREAD_INTERRUPTING) {
137			threadContext->state = THREAD_INTERRUPTED;
138			ConditionWake(&threadContext->stateCond);
139		}
140		if (threadContext->state == THREAD_RESETING) {
141			threadContext->state = THREAD_RUNNING;
142			resetScheduled = 1;
143		}
144		while (threadContext->state == THREAD_PAUSED) {
145			ConditionWait(&threadContext->stateCond, &threadContext->stateMutex);
146		}
147		MutexUnlock(&threadContext->stateMutex);
148		if (resetScheduled) {
149			ARMReset(&cpu);
150		}
151	}
152
153	while (threadContext->state != THREAD_SHUTDOWN) {
154		_changeState(threadContext, THREAD_SHUTDOWN, 0);
155	}
156
157	if (threadContext->cleanCallback) {
158		threadContext->cleanCallback(threadContext);
159	}
160
161	threadContext->gba = 0;
162	ARMDeinit(&cpu);
163	GBADestroy(&gba);
164
165	ConditionWake(&threadContext->sync.videoFrameAvailableCond);
166	ConditionWake(&threadContext->sync.audioRequiredCond);
167
168	return 0;
169}
170
171void GBAMapOptionsToContext(struct StartupOptions* opts, struct GBAThread* threadContext) {
172	threadContext->rom = VFileOpen(opts->fname, O_RDONLY);
173	threadContext->fname = opts->fname;
174	threadContext->bios = VFileOpen(opts->bios, O_RDONLY);
175	threadContext->patch = VFileOpen(opts->patch, O_RDONLY);
176	threadContext->frameskip = opts->frameskip;
177	threadContext->logLevel = opts->logLevel;
178	threadContext->rewindBufferCapacity = opts->rewindBufferCapacity;
179	threadContext->rewindBufferInterval = opts->rewindBufferInterval;
180}
181
182bool GBAThreadStart(struct GBAThread* threadContext) {
183	// TODO: error check
184	threadContext->activeKeys = 0;
185	threadContext->state = THREAD_INITIALIZED;
186	threadContext->sync.videoFrameOn = 1;
187	threadContext->sync.videoFrameSkip = 0;
188
189	threadContext->rewindBufferNext = threadContext->rewindBufferInterval;
190	threadContext->rewindBufferSize = 0;
191	if (threadContext->rewindBufferCapacity) {
192		threadContext->rewindBuffer = calloc(threadContext->rewindBufferCapacity, sizeof(void*));
193	} else {
194		threadContext->rewindBuffer = 0;
195	}
196
197	if (threadContext->fname && !threadContext->save) {
198		char* savedata = 0;
199		char* dotPoint = strrchr(threadContext->fname, '.');
200		if (dotPoint > strrchr(threadContext->fname, '/') && dotPoint[1] && dotPoint[2] && dotPoint[3]) {
201			savedata = strdup(threadContext->fname);
202			dotPoint = strrchr(savedata, '.');
203			dotPoint[1] = 's';
204			dotPoint[2] = 'a';
205			dotPoint[3] = 'v';
206			dotPoint[4] = '\0';
207		} else if (dotPoint) {
208			savedata = malloc((dotPoint - threadContext->fname + 5) * sizeof(char));
209			strncpy(savedata, threadContext->fname, dotPoint - threadContext->fname + 1);
210			strcat(savedata, "sav");
211		} else {
212			savedata = malloc(strlen(threadContext->fname + 5));
213			strcpy(savedata, threadContext->fname);
214			strcat(savedata, "sav");
215		}
216		threadContext->save = VFileOpen(savedata, O_RDWR | O_CREAT);
217		free(savedata);
218	}
219
220	MutexInit(&threadContext->stateMutex);
221	ConditionInit(&threadContext->stateCond);
222
223	MutexInit(&threadContext->sync.videoFrameMutex);
224	ConditionInit(&threadContext->sync.videoFrameAvailableCond);
225	ConditionInit(&threadContext->sync.videoFrameRequiredCond);
226	MutexInit(&threadContext->sync.audioBufferMutex);
227	ConditionInit(&threadContext->sync.audioRequiredCond);
228
229#ifndef _WIN32
230	sigset_t signals;
231	sigemptyset(&signals);
232	sigaddset(&signals, SIGINT);
233	sigaddset(&signals, SIGTRAP);
234	pthread_sigmask(SIG_BLOCK, &signals, 0);
235#endif
236
237	MutexLock(&threadContext->stateMutex);
238	ThreadCreate(&threadContext->thread, _GBAThreadRun, threadContext);
239	while (threadContext->state < THREAD_RUNNING) {
240		ConditionWait(&threadContext->stateCond, &threadContext->stateMutex);
241	}
242	MutexUnlock(&threadContext->stateMutex);
243
244	return true;
245}
246
247bool GBAThreadHasStarted(struct GBAThread* threadContext) {
248	bool hasStarted;
249	MutexLock(&threadContext->stateMutex);
250	hasStarted = threadContext->state > THREAD_INITIALIZED;
251	MutexUnlock(&threadContext->stateMutex);
252	return hasStarted;
253}
254
255void GBAThreadEnd(struct GBAThread* threadContext) {
256	MutexLock(&threadContext->stateMutex);
257	if (threadContext->debugger && threadContext->debugger->state == DEBUGGER_RUNNING) {
258		threadContext->debugger->state = DEBUGGER_EXITING;
259	}
260	threadContext->state = THREAD_EXITING;
261	MutexUnlock(&threadContext->stateMutex);
262	MutexLock(&threadContext->sync.audioBufferMutex);
263	threadContext->sync.audioWait = 0;
264	ConditionWake(&threadContext->sync.audioRequiredCond);
265	MutexUnlock(&threadContext->sync.audioBufferMutex);
266}
267
268void GBAThreadReset(struct GBAThread* threadContext) {
269	MutexLock(&threadContext->stateMutex);
270	_waitOnInterrupt(threadContext);
271	threadContext->state = THREAD_RESETING;
272	ConditionWake(&threadContext->stateCond);
273	MutexUnlock(&threadContext->stateMutex);
274}
275
276void GBAThreadJoin(struct GBAThread* threadContext) {
277	MutexLock(&threadContext->sync.videoFrameMutex);
278	threadContext->sync.videoFrameWait = 0;
279	ConditionWake(&threadContext->sync.videoFrameRequiredCond);
280	MutexUnlock(&threadContext->sync.videoFrameMutex);
281
282	ThreadJoin(threadContext->thread);
283
284	MutexDeinit(&threadContext->stateMutex);
285	ConditionDeinit(&threadContext->stateCond);
286
287	MutexDeinit(&threadContext->sync.videoFrameMutex);
288	ConditionWake(&threadContext->sync.videoFrameAvailableCond);
289	ConditionDeinit(&threadContext->sync.videoFrameAvailableCond);
290	ConditionWake(&threadContext->sync.videoFrameRequiredCond);
291	ConditionDeinit(&threadContext->sync.videoFrameRequiredCond);
292
293	ConditionWake(&threadContext->sync.audioRequiredCond);
294	ConditionDeinit(&threadContext->sync.audioRequiredCond);
295	MutexDeinit(&threadContext->sync.audioBufferMutex);
296
297	int i;
298	for (i = 0; i < threadContext->rewindBufferCapacity; ++i) {
299		if (threadContext->rewindBuffer[i]) {
300			GBADeallocateState(threadContext->rewindBuffer[i]);
301		}
302	}
303	free(threadContext->rewindBuffer);
304
305	if (threadContext->rom) {
306		threadContext->rom->close(threadContext->rom);
307		threadContext->rom = 0;
308	}
309
310	if (threadContext->save) {
311		threadContext->save->close(threadContext->save);
312		threadContext->save = 0;
313	}
314
315	if (threadContext->bios) {
316		threadContext->bios->close(threadContext->bios);
317		threadContext->bios = 0;
318	}
319
320	if (threadContext->patch) {
321		threadContext->patch->close(threadContext->patch);
322		threadContext->patch = 0;
323	}
324}
325
326void GBAThreadInterrupt(struct GBAThread* threadContext) {
327	MutexLock(&threadContext->stateMutex);
328	threadContext->savedState = threadContext->state;
329	_waitOnInterrupt(threadContext);
330	threadContext->state = THREAD_INTERRUPTING;
331	if (threadContext->debugger && threadContext->debugger->state == DEBUGGER_RUNNING) {
332		threadContext->debugger->state = DEBUGGER_EXITING;
333	}
334	ConditionWake(&threadContext->stateCond);
335	while (threadContext->state == THREAD_INTERRUPTING) {
336		ConditionWait(&threadContext->stateCond, &threadContext->stateMutex);
337	}
338	MutexUnlock(&threadContext->stateMutex);
339}
340
341void GBAThreadContinue(struct GBAThread* threadContext) {
342	_changeState(threadContext, threadContext->savedState, 1);
343}
344
345void GBAThreadPause(struct GBAThread* threadContext) {
346	int frameOn = 1;
347	MutexLock(&threadContext->stateMutex);
348	_waitOnInterrupt(threadContext);
349	if (threadContext->state == THREAD_RUNNING) {
350		if (threadContext->debugger && threadContext->debugger->state == DEBUGGER_RUNNING) {
351			threadContext->debugger->state = DEBUGGER_EXITING;
352		}
353		threadContext->state = THREAD_PAUSING;
354		frameOn = 0;
355	}
356	MutexUnlock(&threadContext->stateMutex);
357	MutexLock(&threadContext->sync.videoFrameMutex);
358	if (frameOn != threadContext->sync.videoFrameOn) {
359		threadContext->sync.videoFrameOn = frameOn;
360		ConditionWake(&threadContext->sync.videoFrameAvailableCond);
361	}
362	MutexUnlock(&threadContext->sync.videoFrameMutex);
363}
364
365void GBAThreadUnpause(struct GBAThread* threadContext) {
366	int frameOn = 1;
367	MutexLock(&threadContext->stateMutex);
368	_waitOnInterrupt(threadContext);
369	if (threadContext->state == THREAD_PAUSED || threadContext->state == THREAD_PAUSING) {
370		threadContext->state = THREAD_RUNNING;
371		ConditionWake(&threadContext->stateCond);
372	}
373	MutexUnlock(&threadContext->stateMutex);
374	MutexLock(&threadContext->sync.videoFrameMutex);
375	if (frameOn != threadContext->sync.videoFrameOn) {
376		threadContext->sync.videoFrameOn = frameOn;
377		ConditionWake(&threadContext->sync.videoFrameAvailableCond);
378	}
379	MutexUnlock(&threadContext->sync.videoFrameMutex);
380}
381
382bool GBAThreadIsPaused(struct GBAThread* threadContext) {
383	bool isPaused;
384	MutexLock(&threadContext->stateMutex);
385	_waitOnInterrupt(threadContext);
386	isPaused = threadContext->state == THREAD_PAUSED;
387	MutexUnlock(&threadContext->stateMutex);
388	return isPaused;
389}
390
391void GBAThreadTogglePause(struct GBAThread* threadContext) {
392	bool frameOn = true;
393	MutexLock(&threadContext->stateMutex);
394	_waitOnInterrupt(threadContext);
395	if (threadContext->state == THREAD_PAUSED) {
396		threadContext->state = THREAD_RUNNING;
397		ConditionWake(&threadContext->stateCond);
398	} else if (threadContext->state == THREAD_RUNNING) {
399		if (threadContext->debugger && threadContext->debugger->state == DEBUGGER_RUNNING) {
400			threadContext->debugger->state = DEBUGGER_EXITING;
401		}
402		threadContext->state = THREAD_PAUSED;
403		frameOn = false;
404	}
405	MutexUnlock(&threadContext->stateMutex);
406	MutexLock(&threadContext->sync.videoFrameMutex);
407	if (frameOn != threadContext->sync.videoFrameOn) {
408		threadContext->sync.videoFrameOn = frameOn;
409		ConditionWake(&threadContext->sync.videoFrameAvailableCond);
410	}
411	MutexUnlock(&threadContext->sync.videoFrameMutex);
412}
413
414#ifdef USE_PTHREADS
415struct GBAThread* GBAThreadGetContext(void) {
416	pthread_once(&_contextOnce, _createTLS);
417	return pthread_getspecific(_contextKey);
418}
419#else
420struct GBAThread* GBAThreadGetContext(void) {
421	InitOnceExecuteOnce(&_contextOnce, _createTLS, NULL, 0);
422	return TlsGetValue(_contextKey);
423}
424#endif
425
426void GBASyncPostFrame(struct GBASync* sync) {
427	if (!sync) {
428		return;
429	}
430
431	MutexLock(&sync->videoFrameMutex);
432	++sync->videoFramePending;
433	--sync->videoFrameSkip;
434	if (sync->videoFrameSkip < 0) {
435		ConditionWake(&sync->videoFrameAvailableCond);
436		while (sync->videoFrameWait && sync->videoFramePending) {
437			ConditionWait(&sync->videoFrameRequiredCond, &sync->videoFrameMutex);
438		}
439	}
440	MutexUnlock(&sync->videoFrameMutex);
441
442	struct GBAThread* thread = GBAThreadGetContext();
443	if (thread->rewindBuffer) {
444		--thread->rewindBufferNext;
445		if (thread->rewindBufferNext <= 0) {
446			thread->rewindBufferNext = thread->rewindBufferInterval;
447			GBARecordFrame(thread);
448		}
449	}
450	if (thread->frameCallback) {
451		thread->frameCallback(thread);
452	}
453}
454
455bool GBASyncWaitFrameStart(struct GBASync* sync, int frameskip) {
456	if (!sync) {
457		return true;
458	}
459
460	MutexLock(&sync->videoFrameMutex);
461	ConditionWake(&sync->videoFrameRequiredCond);
462	if (!sync->videoFrameOn) {
463		return false;
464	}
465	ConditionWait(&sync->videoFrameAvailableCond, &sync->videoFrameMutex);
466	sync->videoFramePending = 0;
467	sync->videoFrameSkip = frameskip;
468	return true;
469}
470
471void GBASyncWaitFrameEnd(struct GBASync* sync) {
472	if (!sync) {
473		return;
474	}
475
476	MutexUnlock(&sync->videoFrameMutex);
477}
478
479bool GBASyncDrawingFrame(struct GBASync* sync) {
480	return sync->videoFrameSkip <= 0;
481}
482
483void GBASyncProduceAudio(struct GBASync* sync, int wait) {
484	if (sync->audioWait && wait) {
485		// TODO loop properly in event of spurious wakeups
486		ConditionWait(&sync->audioRequiredCond, &sync->audioBufferMutex);
487	}
488	MutexUnlock(&sync->audioBufferMutex);
489}
490
491void GBASyncLockAudio(struct GBASync* sync) {
492	MutexLock(&sync->audioBufferMutex);
493}
494
495void GBASyncConsumeAudio(struct GBASync* sync) {
496	ConditionWake(&sync->audioRequiredCond);
497	MutexUnlock(&sync->audioBufferMutex);
498}