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