src/platform/qt/GameController.cpp (view raw)
1/* Copyright (c) 2013-2014 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 "GameController.h"
7
8#include "AudioProcessor.h"
9#include "InputController.h"
10#include "LogController.h"
11#include "MultiplayerController.h"
12#include "VFileDevice.h"
13
14#include <QCoreApplication>
15#include <QDateTime>
16#include <QThread>
17
18#include <ctime>
19
20extern "C" {
21#include "gba/audio.h"
22#include "gba/context/config.h"
23#include "gba/context/directories.h"
24#include "gba/gba.h"
25#include "gba/serialize.h"
26#include "gba/sharkport.h"
27#include "gba/renderers/video-software.h"
28#include "util/vfs.h"
29}
30
31using namespace QGBA;
32using namespace std;
33
34GameController::GameController(QObject* parent)
35 : QObject(parent)
36 , m_drawContext(new uint32_t[VIDEO_VERTICAL_PIXELS * VIDEO_HORIZONTAL_PIXELS])
37 , m_frontBuffer(new uint32_t[VIDEO_VERTICAL_PIXELS * VIDEO_HORIZONTAL_PIXELS])
38 , m_threadContext()
39 , m_activeKeys(0)
40 , m_inactiveKeys(0)
41 , m_logLevels(0)
42 , m_gameOpen(false)
43 , m_audioThread(new QThread(this))
44 , m_audioProcessor(AudioProcessor::create())
45 , m_pauseAfterFrame(false)
46 , m_videoSync(VIDEO_SYNC)
47 , m_audioSync(AUDIO_SYNC)
48 , m_fpsTarget(-1)
49 , m_turbo(false)
50 , m_turboForced(false)
51 , m_turboSpeed(-1)
52 , m_wasPaused(false)
53 , m_audioChannels{ true, true, true, true, true, true }
54 , m_videoLayers{ true, true, true, true, true }
55 , m_autofire{}
56 , m_autofireStatus{}
57 , m_inputController(nullptr)
58 , m_multiplayer(nullptr)
59 , m_stateSlot(1)
60 , m_backupLoadState(nullptr)
61 , m_backupSaveState(nullptr)
62 , m_saveStateFlags(SAVESTATE_SCREENSHOT | SAVESTATE_SAVEDATA | SAVESTATE_CHEATS)
63 , m_loadStateFlags(SAVESTATE_SCREENSHOT)
64{
65 m_renderer = new GBAVideoSoftwareRenderer;
66 GBAVideoSoftwareRendererCreate(m_renderer);
67 m_renderer->outputBuffer = (color_t*) m_drawContext;
68 m_renderer->outputBufferStride = VIDEO_HORIZONTAL_PIXELS;
69
70 GBACheatDeviceCreate(&m_cheatDevice);
71
72 m_threadContext.state = THREAD_INITIALIZED;
73 m_threadContext.debugger = 0;
74 m_threadContext.frameskip = 0;
75 m_threadContext.bios = 0;
76 m_threadContext.renderer = &m_renderer->d;
77 m_threadContext.userData = this;
78 m_threadContext.rewindBufferCapacity = 0;
79 m_threadContext.cheats = &m_cheatDevice;
80 m_threadContext.logLevel = GBA_LOG_ALL;
81 GBADirectorySetInit(&m_threadContext.dirs);
82
83 m_lux.p = this;
84 m_lux.sample = [](GBALuminanceSource* context) {
85 GameControllerLux* lux = static_cast<GameControllerLux*>(context);
86 lux->value = 0xFF - lux->p->m_luxValue;
87 };
88
89 m_lux.readLuminance = [](GBALuminanceSource* context) {
90 GameControllerLux* lux = static_cast<GameControllerLux*>(context);
91 return lux->value;
92 };
93 setLuminanceLevel(0);
94
95 m_threadContext.startCallback = [](GBAThread* context) {
96 GameController* controller = static_cast<GameController*>(context->userData);
97 if (controller->m_audioProcessor) {
98 controller->m_audioProcessor->setInput(context);
99 }
100 context->gba->luminanceSource = &controller->m_lux;
101 GBARTCGenericSourceInit(&controller->m_rtc, context->gba);
102 context->gba->rtcSource = &controller->m_rtc.d;
103 context->gba->rumble = controller->m_inputController->rumble();
104 context->gba->rotationSource = controller->m_inputController->rotationSource();
105 context->gba->audio.forceDisableCh[0] = !controller->m_audioChannels[0];
106 context->gba->audio.forceDisableCh[1] = !controller->m_audioChannels[1];
107 context->gba->audio.forceDisableCh[2] = !controller->m_audioChannels[2];
108 context->gba->audio.forceDisableCh[3] = !controller->m_audioChannels[3];
109 context->gba->audio.forceDisableChA = !controller->m_audioChannels[4];
110 context->gba->audio.forceDisableChB = !controller->m_audioChannels[5];
111 context->gba->video.renderer->disableBG[0] = !controller->m_videoLayers[0];
112 context->gba->video.renderer->disableBG[1] = !controller->m_videoLayers[1];
113 context->gba->video.renderer->disableBG[2] = !controller->m_videoLayers[2];
114 context->gba->video.renderer->disableBG[3] = !controller->m_videoLayers[3];
115 context->gba->video.renderer->disableOBJ = !controller->m_videoLayers[4];
116 controller->m_fpsTarget = context->fpsTarget;
117
118 if (context->dirs.state && GBALoadState(context, context->dirs.state, 0, controller->m_loadStateFlags)) {
119 GBADeleteState(context->gba, context->dirs.state, 0);
120 }
121 QMetaObject::invokeMethod(controller, "gameStarted", Q_ARG(GBAThread*, context));
122 };
123
124 m_threadContext.cleanCallback = [](GBAThread* context) {
125 GameController* controller = static_cast<GameController*>(context->userData);
126 QMetaObject::invokeMethod(controller, "gameStopped", Q_ARG(GBAThread*, context));
127 };
128
129 m_threadContext.frameCallback = [](GBAThread* context) {
130 GameController* controller = static_cast<GameController*>(context->userData);
131 memcpy(controller->m_frontBuffer, controller->m_drawContext, VIDEO_VERTICAL_PIXELS * VIDEO_HORIZONTAL_PIXELS * BYTES_PER_PIXEL);
132 QMetaObject::invokeMethod(controller, "frameAvailable", Q_ARG(const uint32_t*, controller->m_frontBuffer));
133 if (controller->m_pauseAfterFrame.testAndSetAcquire(true, false)) {
134 GBAThreadPauseFromThread(context);
135 QMetaObject::invokeMethod(controller, "gamePaused", Q_ARG(GBAThread*, context));
136 }
137 };
138
139 m_threadContext.stopCallback = [](GBAThread* context) {
140 if (!context) {
141 return false;
142 }
143 GameController* controller = static_cast<GameController*>(context->userData);
144 if (!GBASaveState(context, context->dirs.state, 0, controller->m_saveStateFlags)) {
145 return false;
146 }
147 QMetaObject::invokeMethod(controller, "closeGame");
148 return true;
149 };
150
151 m_threadContext.logHandler = [](GBAThread* context, enum GBALogLevel level, const char* format, va_list args) {
152 static const char* stubMessage = "Stub software interrupt: %02X";
153 static const char* savestateMessage = "State %i loaded";
154 static const char* savestateFailedMessage = "State %i failed to load";
155 if (!context) {
156 return;
157 }
158 GameController* controller = static_cast<GameController*>(context->userData);
159 if (level == GBA_LOG_STUB && strncmp(stubMessage, format, strlen(stubMessage)) == 0) {
160 va_list argc;
161 va_copy(argc, args);
162 int immediate = va_arg(argc, int);
163 va_end(argc);
164 QMetaObject::invokeMethod(controller, "unimplementedBiosCall", Q_ARG(int, immediate));
165 } else if (level == GBA_LOG_STATUS) {
166 // Slot 0 is reserved for suspend points
167 if (strncmp(savestateMessage, format, strlen(savestateMessage)) == 0) {
168 va_list argc;
169 va_copy(argc, args);
170 int slot = va_arg(argc, int);
171 va_end(argc);
172 if (slot == 0) {
173 format = "Loaded suspend state";
174 }
175 } else if (strncmp(savestateFailedMessage, format, strlen(savestateFailedMessage)) == 0) {
176 va_list argc;
177 va_copy(argc, args);
178 int slot = va_arg(argc, int);
179 va_end(argc);
180 if (slot == 0) {
181 return;
182 }
183 }
184 }
185 if (level == GBA_LOG_FATAL) {
186 QMetaObject::invokeMethod(controller, "crashGame", Q_ARG(const QString&, QString().vsprintf(format, args)));
187 } else if (!(controller->m_logLevels & level)) {
188 return;
189 }
190 QString message(QString().vsprintf(format, args));
191 if (level == GBA_LOG_STATUS) {
192 QMetaObject::invokeMethod(controller, "statusPosted", Q_ARG(const QString&, message));
193 }
194 QMetaObject::invokeMethod(controller, "postLog", Q_ARG(int, level), Q_ARG(const QString&, message));
195 };
196
197 connect(&m_rewindTimer, &QTimer::timeout, [this]() {
198 GBARewind(&m_threadContext, 1);
199 emit frameAvailable(m_drawContext);
200 emit rewound(&m_threadContext);
201 });
202 m_rewindTimer.setInterval(100);
203
204 m_audioThread->setObjectName("Audio Thread");
205 m_audioThread->start(QThread::TimeCriticalPriority);
206 m_audioProcessor->moveToThread(m_audioThread);
207 connect(this, SIGNAL(gamePaused(GBAThread*)), m_audioProcessor, SLOT(pause()));
208 connect(this, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(pollEvents()));
209 connect(this, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(updateAutofire()));
210}
211
212GameController::~GameController() {
213 m_audioThread->quit();
214 m_audioThread->wait();
215 disconnect();
216 clearMultiplayerController();
217 closeGame();
218 GBACheatDeviceDestroy(&m_cheatDevice);
219 GBADirectorySetDeinit(&m_threadContext.dirs);
220 delete m_renderer;
221 delete[] m_drawContext;
222 delete[] m_frontBuffer;
223 delete m_backupLoadState;
224}
225
226void GameController::setMultiplayerController(MultiplayerController* controller) {
227 if (controller == m_multiplayer) {
228 return;
229 }
230 clearMultiplayerController();
231 m_multiplayer = controller;
232 controller->attachGame(this);
233}
234
235void GameController::clearMultiplayerController() {
236 if (!m_multiplayer) {
237 return;
238 }
239 m_multiplayer->detachGame(this);
240 m_multiplayer = nullptr;
241}
242
243void GameController::setOverride(const GBACartridgeOverride& override) {
244 m_threadContext.override = override;
245 m_threadContext.hasOverride = true;
246}
247
248void GameController::setOptions(const GBAOptions* opts) {
249 setFrameskip(opts->frameskip);
250 setAudioSync(opts->audioSync);
251 setVideoSync(opts->videoSync);
252 setSkipBIOS(opts->skipBios);
253 setUseBIOS(opts->useBios);
254 setRewind(opts->rewindEnable, opts->rewindBufferCapacity, opts->rewindBufferInterval);
255 setVolume(opts->volume);
256 setMute(opts->mute);
257
258 threadInterrupt();
259 GBADirectorySetMapOptions(&m_threadContext.dirs, opts);
260 m_threadContext.idleOptimization = opts->idleOptimization;
261 threadContinue();
262}
263
264#ifdef USE_GDB_STUB
265ARMDebugger* GameController::debugger() {
266 return m_threadContext.debugger;
267}
268
269void GameController::setDebugger(ARMDebugger* debugger) {
270 threadInterrupt();
271 if (m_threadContext.debugger && GBAThreadIsActive(&m_threadContext)) {
272 GBADetachDebugger(m_threadContext.gba);
273 }
274 m_threadContext.debugger = debugger;
275 if (m_threadContext.debugger && GBAThreadIsActive(&m_threadContext)) {
276 GBAAttachDebugger(m_threadContext.gba, m_threadContext.debugger);
277 }
278 threadContinue();
279}
280#endif
281
282void GameController::loadGame(const QString& path) {
283 closeGame();
284 QFile file(path);
285 if (!file.open(QIODevice::ReadOnly)) {
286 postLog(GBA_LOG_ERROR, tr("Failed to open game file: %1").arg(path));
287 return;
288 }
289 file.close();
290
291 m_fname = path;
292 openGame();
293}
294
295void GameController::bootBIOS() {
296 closeGame();
297 m_fname = QString();
298 openGame(true);
299}
300
301void GameController::openGame(bool biosOnly) {
302 if (biosOnly && (!m_useBios || m_bios.isNull())) {
303 return;
304 }
305
306 m_gameOpen = true;
307
308 m_pauseAfterFrame = false;
309
310 if (m_turbo) {
311 m_threadContext.sync.videoFrameWait = false;
312 m_threadContext.sync.audioWait = false;
313 } else {
314 m_threadContext.sync.videoFrameWait = m_videoSync;
315 m_threadContext.sync.audioWait = m_audioSync;
316 }
317
318 m_threadContext.bootBios = biosOnly;
319 if (biosOnly) {
320 m_threadContext.fname = nullptr;
321 } else {
322 m_threadContext.fname = strdup(m_fname.toUtf8().constData());
323 GBAThreadLoadROM(&m_threadContext, m_threadContext.fname);
324 }
325
326 if (!m_bios.isNull() && m_useBios) {
327 m_threadContext.bios = VFileDevice::open(m_bios, O_RDONLY);
328 } else {
329 m_threadContext.bios = nullptr;
330 }
331
332 if (!m_patch.isNull()) {
333 m_threadContext.patch = VFileDevice::open(m_patch, O_RDONLY);
334 }
335
336 m_inputController->recalibrateAxes();
337 memset(m_drawContext, 0xF8, VIDEO_VERTICAL_PIXELS * VIDEO_HORIZONTAL_PIXELS * 4);
338
339 if (!GBAThreadStart(&m_threadContext)) {
340 m_gameOpen = false;
341 emit gameFailed();
342 } else if (m_audioProcessor) {
343 bool started = false;
344 QMetaObject::invokeMethod(m_audioProcessor, "start", Qt::BlockingQueuedConnection, Q_RETURN_ARG(bool, started));
345 if (!started) {
346 LOG(ERROR) << tr("Failed to start audio processor");
347 // Don't freeze!
348 m_audioSync = false;
349 m_videoSync = true;
350 m_threadContext.sync.audioWait = false;
351 m_threadContext.sync.videoFrameWait = true;
352 }
353 }
354}
355
356void GameController::loadBIOS(const QString& path) {
357 if (m_bios == path) {
358 return;
359 }
360 m_bios = path;
361 if (m_gameOpen) {
362 closeGame();
363 openGame();
364 }
365}
366
367void GameController::yankPak() {
368 if (!m_gameOpen) {
369 return;
370 }
371 threadInterrupt();
372 GBAYankROM(m_threadContext.gba);
373 threadContinue();
374}
375
376void GameController::replaceGame(const QString& path) {
377 if (!m_gameOpen) {
378 return;
379 }
380
381 m_fname = path;
382 threadInterrupt();
383 m_threadContext.fname = strdup(m_fname.toLocal8Bit().constData());
384 GBAThreadReplaceROM(&m_threadContext, m_threadContext.fname);
385 threadContinue();
386}
387
388void GameController::loadPatch(const QString& path) {
389 if (m_gameOpen) {
390 closeGame();
391 m_patch = path;
392 openGame();
393 } else {
394 m_patch = path;
395 }
396}
397
398void GameController::importSharkport(const QString& path) {
399 if (!isLoaded()) {
400 return;
401 }
402 VFile* vf = VFileDevice::open(path, O_RDONLY);
403 if (!vf) {
404 postLog(GBA_LOG_ERROR, tr("Failed to open snapshot file for reading: %1").arg(path));
405 return;
406 }
407 threadInterrupt();
408 GBASavedataImportSharkPort(m_threadContext.gba, vf, false);
409 threadContinue();
410 vf->close(vf);
411}
412
413void GameController::exportSharkport(const QString& path) {
414 if (!isLoaded()) {
415 return;
416 }
417 VFile* vf = VFileDevice::open(path, O_WRONLY | O_CREAT | O_TRUNC);
418 if (!vf) {
419 postLog(GBA_LOG_ERROR, tr("Failed to open snapshot file for writing: %1").arg(path));
420 return;
421 }
422 threadInterrupt();
423 GBASavedataExportSharkPort(m_threadContext.gba, vf);
424 threadContinue();
425 vf->close(vf);
426}
427
428void GameController::closeGame() {
429 if (!m_gameOpen) {
430 return;
431 }
432 m_gameOpen = false;
433
434 m_rewindTimer.stop();
435 if (GBAThreadIsPaused(&m_threadContext)) {
436 GBAThreadUnpause(&m_threadContext);
437 }
438 m_audioProcessor->pause();
439 GBAThreadEnd(&m_threadContext);
440 GBAThreadJoin(&m_threadContext);
441 // Make sure the event queue clears out before the thread is reused
442 QCoreApplication::processEvents();
443 if (m_threadContext.fname) {
444 free(const_cast<char*>(m_threadContext.fname));
445 m_threadContext.fname = nullptr;
446 }
447
448 m_patch = QString();
449
450 for (size_t i = 0; i < GBACheatSetsSize(&m_cheatDevice.cheats); ++i) {
451 GBACheatSet* set = *GBACheatSetsGetPointer(&m_cheatDevice.cheats, i);
452 GBACheatSetDeinit(set);
453 delete set;
454 }
455 GBACheatSetsClear(&m_cheatDevice.cheats);
456
457 m_gameOpen = false;
458 emit gameStopped(&m_threadContext);
459}
460
461void GameController::crashGame(const QString& crashMessage) {
462 closeGame();
463 emit gameCrashed(crashMessage);
464 emit gameStopped(&m_threadContext);
465}
466
467bool GameController::isPaused() {
468 if (!m_gameOpen) {
469 return false;
470 }
471 return GBAThreadIsPaused(&m_threadContext);
472}
473
474void GameController::setPaused(bool paused) {
475 if (!isLoaded() || m_rewindTimer.isActive() || paused == GBAThreadIsPaused(&m_threadContext)) {
476 return;
477 }
478 if (paused) {
479 m_pauseAfterFrame.testAndSetRelaxed(false, true);
480 } else {
481 GBAThreadUnpause(&m_threadContext);
482 emit gameUnpaused(&m_threadContext);
483 }
484}
485
486void GameController::reset() {
487 if (!m_gameOpen) {
488 return;
489 }
490 bool wasPaused = isPaused();
491 setPaused(false);
492 GBAThreadReset(&m_threadContext);
493 if (wasPaused) {
494 setPaused(true);
495 }
496}
497
498void GameController::threadInterrupt() {
499 if (m_gameOpen) {
500 GBAThreadInterrupt(&m_threadContext);
501 }
502}
503
504void GameController::threadContinue() {
505 if (m_gameOpen) {
506 GBAThreadContinue(&m_threadContext);
507 }
508}
509
510void GameController::frameAdvance() {
511 if (m_rewindTimer.isActive()) {
512 return;
513 }
514 if (m_pauseAfterFrame.testAndSetRelaxed(false, true)) {
515 setPaused(false);
516 }
517}
518
519void GameController::setRewind(bool enable, int capacity, int interval) {
520 if (m_gameOpen) {
521 threadInterrupt();
522 GBARewindSettingsChanged(&m_threadContext, enable ? capacity : 0, enable ? interval : 0);
523 threadContinue();
524 } else {
525 if (enable) {
526 m_threadContext.rewindBufferInterval = interval;
527 m_threadContext.rewindBufferCapacity = capacity;
528 } else {
529 m_threadContext.rewindBufferInterval = 0;
530 m_threadContext.rewindBufferCapacity = 0;
531 }
532 }
533}
534
535void GameController::rewind(int states) {
536 threadInterrupt();
537 if (!states) {
538 GBARewindAll(&m_threadContext);
539 } else {
540 GBARewind(&m_threadContext, states);
541 }
542 threadContinue();
543 emit frameAvailable(m_drawContext);
544 emit rewound(&m_threadContext);
545}
546
547void GameController::startRewinding() {
548 if (!m_gameOpen || m_rewindTimer.isActive()) {
549 return;
550 }
551 if (m_multiplayer && m_multiplayer->attached() > 1) {
552 return;
553 }
554 m_wasPaused = isPaused();
555 if (!GBAThreadIsPaused(&m_threadContext)) {
556 GBAThreadPause(&m_threadContext);
557 }
558 m_rewindTimer.start();
559}
560
561void GameController::stopRewinding() {
562 if (!m_rewindTimer.isActive()) {
563 return;
564 }
565 m_rewindTimer.stop();
566 bool signalsBlocked = blockSignals(true);
567 setPaused(m_wasPaused);
568 blockSignals(signalsBlocked);
569}
570
571void GameController::keyPressed(int key) {
572 int mappedKey = 1 << key;
573 m_activeKeys |= mappedKey;
574 if (!m_inputController->allowOpposing()) {
575 if ((m_activeKeys & 0x30) == 0x30) {
576 m_inactiveKeys |= mappedKey ^ 0x30;
577 m_activeKeys ^= mappedKey ^ 0x30;
578 }
579 if ((m_activeKeys & 0xC0) == 0xC0) {
580 m_inactiveKeys |= mappedKey ^ 0xC0;
581 m_activeKeys ^= mappedKey ^ 0xC0;
582 }
583 }
584 updateKeys();
585}
586
587void GameController::keyReleased(int key) {
588 int mappedKey = 1 << key;
589 m_activeKeys &= ~mappedKey;
590 if (!m_inputController->allowOpposing()) {
591 if (mappedKey & 0x30) {
592 m_activeKeys |= m_inactiveKeys & (0x30 ^ mappedKey);
593 m_inactiveKeys &= ~0x30;
594 }
595 if (mappedKey & 0xC0) {
596 m_activeKeys |= m_inactiveKeys & (0xC0 ^ mappedKey);
597 m_inactiveKeys &= ~0xC0;
598 }
599 }
600 updateKeys();
601}
602
603void GameController::clearKeys() {
604 m_activeKeys = 0;
605 m_inactiveKeys = 0;
606 updateKeys();
607}
608
609void GameController::setAutofire(int key, bool enable) {
610 if (key >= GBA_KEY_MAX || key < 0) {
611 return;
612 }
613 m_autofire[key] = enable;
614 m_autofireStatus[key] = 0;
615}
616
617void GameController::setAudioBufferSamples(int samples) {
618 if (m_audioProcessor) {
619 threadInterrupt();
620 redoSamples(samples);
621 threadContinue();
622 QMetaObject::invokeMethod(m_audioProcessor, "setBufferSamples", Qt::BlockingQueuedConnection, Q_ARG(int, samples));
623 }
624}
625
626void GameController::setAudioSampleRate(unsigned rate) {
627 if (!rate) {
628 return;
629 }
630 if (m_audioProcessor) {
631 threadInterrupt();
632 redoSamples(m_audioProcessor->getBufferSamples());
633 threadContinue();
634 QMetaObject::invokeMethod(m_audioProcessor, "requestSampleRate", Q_ARG(unsigned, rate));
635 }
636}
637
638void GameController::setAudioChannelEnabled(int channel, bool enable) {
639 if (channel > 5 || channel < 0) {
640 return;
641 }
642 m_audioChannels[channel] = enable;
643 if (isLoaded()) {
644 switch (channel) {
645 case 0:
646 case 1:
647 case 2:
648 case 3:
649 m_threadContext.gba->audio.forceDisableCh[channel] = !enable;
650 break;
651 case 4:
652 m_threadContext.gba->audio.forceDisableChA = !enable;
653 break;
654 case 5:
655 m_threadContext.gba->audio.forceDisableChB = !enable;
656 break;
657 }
658 }
659}
660
661void GameController::setVideoLayerEnabled(int layer, bool enable) {
662 if (layer > 4 || layer < 0) {
663 return;
664 }
665 m_videoLayers[layer] = enable;
666 if (isLoaded()) {
667 switch (layer) {
668 case 0:
669 case 1:
670 case 2:
671 case 3:
672 m_threadContext.gba->video.renderer->disableBG[layer] = !enable;
673 break;
674 case 4:
675 m_threadContext.gba->video.renderer->disableOBJ = !enable;
676 break;
677 }
678 }
679}
680
681void GameController::setFPSTarget(float fps) {
682 threadInterrupt();
683 m_fpsTarget = fps;
684 m_threadContext.fpsTarget = fps;
685 if (m_turbo && m_turboSpeed > 0) {
686 m_threadContext.fpsTarget *= m_turboSpeed;
687 }
688 if (m_audioProcessor) {
689 redoSamples(m_audioProcessor->getBufferSamples());
690 }
691 threadContinue();
692}
693
694void GameController::setSkipBIOS(bool set) {
695 threadInterrupt();
696 m_threadContext.skipBios = set;
697 threadContinue();
698}
699
700void GameController::setUseBIOS(bool use) {
701 if (use == m_useBios) {
702 return;
703 }
704 m_useBios = use;
705 if (m_gameOpen) {
706 closeGame();
707 openGame();
708 }
709}
710
711void GameController::loadState(int slot) {
712 if (!m_threadContext.fname) {
713 // We're in the BIOS
714 return;
715 }
716 if (slot > 0 && slot != m_stateSlot) {
717 m_stateSlot = slot;
718 m_backupSaveState.clear();
719 }
720 GBARunOnThread(&m_threadContext, [](GBAThread* context) {
721 GameController* controller = static_cast<GameController*>(context->userData);
722 if (!controller->m_backupLoadState) {
723 controller->m_backupLoadState = new GBASerializedState;
724 }
725 GBASerialize(context->gba, controller->m_backupLoadState);
726 if (GBALoadState(context, context->dirs.state, controller->m_stateSlot, controller->m_loadStateFlags)) {
727 controller->frameAvailable(controller->m_drawContext);
728 controller->stateLoaded(context);
729 }
730 });
731}
732
733void GameController::saveState(int slot) {
734 if (!m_threadContext.fname) {
735 // We're in the BIOS
736 return;
737 }
738 if (slot > 0) {
739 m_stateSlot = slot;
740 }
741 GBARunOnThread(&m_threadContext, [](GBAThread* context) {
742 GameController* controller = static_cast<GameController*>(context->userData);
743 VFile* vf = GBAGetState(context->gba, context->dirs.state, controller->m_stateSlot, false);
744 if (vf) {
745 controller->m_backupSaveState.resize(vf->size(vf));
746 vf->read(vf, controller->m_backupSaveState.data(), controller->m_backupSaveState.size());
747 vf->close(vf);
748 }
749 GBASaveState(context, context->dirs.state, controller->m_stateSlot, controller->m_saveStateFlags);
750 });
751}
752
753void GameController::loadBackupState() {
754 if (!m_backupLoadState) {
755 return;
756 }
757
758 GBARunOnThread(&m_threadContext, [](GBAThread* context) {
759 GameController* controller = static_cast<GameController*>(context->userData);
760 if (GBADeserialize(context->gba, controller->m_backupLoadState)) {
761 GBALog(context->gba, GBA_LOG_STATUS, "Undid state load");
762 controller->frameAvailable(controller->m_drawContext);
763 controller->stateLoaded(context);
764 }
765 delete controller->m_backupLoadState;
766 controller->m_backupLoadState = nullptr;
767 });
768}
769
770void GameController::saveBackupState() {
771 if (m_backupSaveState.isEmpty()) {
772 return;
773 }
774
775 GBARunOnThread(&m_threadContext, [](GBAThread* context) {
776 GameController* controller = static_cast<GameController*>(context->userData);
777 VFile* vf = GBAGetState(context->gba, context->dirs.state, controller->m_stateSlot, true);
778 if (vf) {
779 vf->write(vf, controller->m_backupSaveState.constData(), controller->m_backupSaveState.size());
780 vf->close(vf);
781 GBALog(context->gba, GBA_LOG_STATUS, "Undid state save");
782 }
783 controller->m_backupSaveState.clear();
784 });
785}
786
787void GameController::setVideoSync(bool set) {
788 m_videoSync = set;
789 if (!m_turbo) {
790 threadInterrupt();
791 m_threadContext.sync.videoFrameWait = set;
792 threadContinue();
793 }
794}
795
796void GameController::setAudioSync(bool set) {
797 m_audioSync = set;
798 if (!m_turbo) {
799 threadInterrupt();
800 m_threadContext.sync.audioWait = set;
801 threadContinue();
802 }
803}
804
805void GameController::setFrameskip(int skip) {
806 threadInterrupt();
807 m_threadContext.frameskip = skip;
808 if (isLoaded()) {
809 m_threadContext.gba->video.frameskip = skip;
810 }
811 threadContinue();
812}
813
814void GameController::setVolume(int volume) {
815 threadInterrupt();
816 m_threadContext.volume = volume;
817 if (isLoaded()) {
818 m_threadContext.gba->audio.masterVolume = volume;
819 }
820 threadContinue();
821}
822
823void GameController::setMute(bool mute) {
824 threadInterrupt();
825 m_threadContext.mute = mute;
826 if (isLoaded()) {
827 m_threadContext.gba->audio.masterVolume = mute ? 0 : m_threadContext.volume;
828 }
829 threadContinue();
830}
831
832void GameController::setTurbo(bool set, bool forced) {
833 if (m_turboForced && !forced) {
834 return;
835 }
836 if (m_turbo == set && m_turboForced == forced) {
837 // Don't interrupt the thread if we don't need to
838 return;
839 }
840 m_turbo = set;
841 m_turboForced = set && forced;
842 enableTurbo();
843}
844
845void GameController::setTurboSpeed(float ratio) {
846 m_turboSpeed = ratio;
847 enableTurbo();
848}
849
850void GameController::enableTurbo() {
851 threadInterrupt();
852 if (!m_turbo) {
853 m_threadContext.fpsTarget = m_fpsTarget;
854 m_threadContext.sync.audioWait = m_audioSync;
855 m_threadContext.sync.videoFrameWait = m_videoSync;
856 } else if (m_turboSpeed <= 0) {
857 m_threadContext.fpsTarget = m_fpsTarget;
858 m_threadContext.sync.audioWait = false;
859 m_threadContext.sync.videoFrameWait = false;
860 } else {
861 m_threadContext.fpsTarget = m_fpsTarget * m_turboSpeed;
862 m_threadContext.sync.audioWait = true;
863 m_threadContext.sync.videoFrameWait = false;
864 }
865 if (m_audioProcessor) {
866 redoSamples(m_audioProcessor->getBufferSamples());
867 }
868 threadContinue();
869}
870
871void GameController::setAVStream(GBAAVStream* stream) {
872 threadInterrupt();
873 m_threadContext.stream = stream;
874 if (isLoaded()) {
875 m_threadContext.gba->stream = stream;
876 }
877 threadContinue();
878}
879
880void GameController::clearAVStream() {
881 threadInterrupt();
882 m_threadContext.stream = nullptr;
883 if (isLoaded()) {
884 m_threadContext.gba->stream = nullptr;
885 }
886 threadContinue();
887}
888
889#ifdef USE_PNG
890void GameController::screenshot() {
891 GBARunOnThread(&m_threadContext, GBAThreadTakeScreenshot);
892}
893#endif
894
895void GameController::reloadAudioDriver() {
896 int samples = 0;
897 unsigned sampleRate = 0;
898 if (m_audioProcessor) {
899 QMetaObject::invokeMethod(m_audioProcessor, "pause", Qt::BlockingQueuedConnection);
900 samples = m_audioProcessor->getBufferSamples();
901 sampleRate = m_audioProcessor->sampleRate();
902 delete m_audioProcessor;
903 }
904 m_audioProcessor = AudioProcessor::create();
905 if (samples) {
906 m_audioProcessor->setBufferSamples(samples);
907 }
908 if (sampleRate) {
909 m_audioProcessor->requestSampleRate(sampleRate);
910 }
911 m_audioProcessor->moveToThread(m_audioThread);
912 connect(this, SIGNAL(gamePaused(GBAThread*)), m_audioProcessor, SLOT(pause()));
913 if (isLoaded()) {
914 m_audioProcessor->setInput(&m_threadContext);
915 bool started = false;
916 QMetaObject::invokeMethod(m_audioProcessor, "start", Qt::BlockingQueuedConnection, Q_RETURN_ARG(bool, started));
917 if (!started) {
918 LOG(ERROR) << tr("Failed to start audio processor");
919 // Don't freeze!
920 m_audioSync = false;
921 m_videoSync = true;
922 m_threadContext.sync.audioWait = false;
923 m_threadContext.sync.videoFrameWait = true;
924 }
925 }
926}
927
928void GameController::setSaveStateExtdata(int flags) {
929 m_saveStateFlags = flags;
930}
931
932void GameController::setLoadStateExtdata(int flags) {
933 m_loadStateFlags = flags;
934}
935
936void GameController::setLuminanceValue(uint8_t value) {
937 m_luxValue = value;
938 value = std::max<int>(value - 0x16, 0);
939 m_luxLevel = 10;
940 for (int i = 0; i < 10; ++i) {
941 if (value < GBA_LUX_LEVELS[i]) {
942 m_luxLevel = i;
943 break;
944 }
945 }
946 emit luminanceValueChanged(m_luxValue);
947}
948
949void GameController::setLuminanceLevel(int level) {
950 int value = 0x16;
951 level = std::max(0, std::min(10, level));
952 if (level > 0) {
953 value += GBA_LUX_LEVELS[level - 1];
954 }
955 setLuminanceValue(value);
956}
957
958void GameController::setRealTime() {
959 m_rtc.override = GBARTCGenericSource::RTC_NO_OVERRIDE;
960}
961
962void GameController::setFixedTime(const QDateTime& time) {
963 m_rtc.override = GBARTCGenericSource::RTC_FIXED;
964 m_rtc.value = time.toMSecsSinceEpoch() / 1000;
965}
966
967void GameController::setFakeEpoch(const QDateTime& time) {
968 m_rtc.override = GBARTCGenericSource::RTC_FAKE_EPOCH;
969 m_rtc.value = time.toMSecsSinceEpoch() / 1000;
970}
971
972void GameController::updateKeys() {
973 int activeKeys = m_activeKeys;
974 activeKeys |= m_activeButtons;
975 activeKeys &= ~m_inactiveKeys;
976 m_threadContext.activeKeys = activeKeys;
977}
978
979void GameController::redoSamples(int samples) {
980#if RESAMPLE_LIBRARY != RESAMPLE_BLIP_BUF
981 float sampleRate = 0x8000;
982 float ratio;
983 if (m_threadContext.gba) {
984 sampleRate = m_threadContext.gba->audio.sampleRate;
985 }
986 ratio = GBAAudioCalculateRatio(sampleRate, m_threadContext.fpsTarget, m_audioProcess->sampleRate());
987 m_threadContext.audioBuffers = ceil(samples / ratio);
988#else
989 m_threadContext.audioBuffers = samples;
990#endif
991 if (m_threadContext.gba) {
992 GBAAudioResizeBuffer(&m_threadContext.gba->audio, m_threadContext.audioBuffers);
993 }
994 QMetaObject::invokeMethod(m_audioProcessor, "inputParametersChanged");
995}
996
997void GameController::setLogLevel(int levels) {
998 threadInterrupt();
999 m_logLevels = levels;
1000 threadContinue();
1001}
1002
1003void GameController::enableLogLevel(int levels) {
1004 threadInterrupt();
1005 m_logLevels |= levels;
1006 threadContinue();
1007}
1008
1009void GameController::disableLogLevel(int levels) {
1010 threadInterrupt();
1011 m_logLevels &= ~levels;
1012 threadContinue();
1013}
1014
1015void GameController::pollEvents() {
1016 if (!m_inputController) {
1017 return;
1018 }
1019
1020 m_activeButtons = m_inputController->pollEvents();
1021 updateKeys();
1022}
1023
1024void GameController::updateAutofire() {
1025 // TODO: Move all key events onto the CPU thread...somehow
1026 for (int k = 0; k < GBA_KEY_MAX; ++k) {
1027 if (!m_autofire[k]) {
1028 continue;
1029 }
1030 m_autofireStatus[k] ^= 1;
1031 if (m_autofireStatus[k]) {
1032 keyPressed(k);
1033 } else {
1034 keyReleased(k);
1035 }
1036 }
1037}