src/platform/qt/CoreController.cpp (view raw)
1/* Copyright (c) 2013-2017 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 "CoreController.h"
7
8#include "ConfigController.h"
9#include "InputController.h"
10#include "LogController.h"
11#include "MultiplayerController.h"
12#include "Override.h"
13
14#include <QDateTime>
15#include <QMutexLocker>
16
17#include <mgba/core/serialize.h>
18#include <mgba/feature/video-logger.h>
19#ifdef M_CORE_GBA
20#include <mgba/internal/gba/gba.h>
21#include <mgba/internal/gba/renderers/cache-set.h>
22#include <mgba/internal/gba/sharkport.h>
23#endif
24#ifdef M_CORE_GB
25#include <mgba/internal/gb/gb.h>
26#include <mgba/internal/gb/renderers/cache-set.h>
27#endif
28#include "feature/sqlite3/no-intro.h"
29#include <mgba-util/math.h>
30#include <mgba-util/vfs.h>
31
32#define AUTOSAVE_GRANULARITY 600
33
34using namespace QGBA;
35
36CoreController::CoreController(mCore* core, QObject* parent)
37 : QObject(parent)
38 , m_loadStateFlags(SAVESTATE_SCREENSHOT | SAVESTATE_RTC)
39 , m_saveStateFlags(SAVESTATE_SCREENSHOT | SAVESTATE_SAVEDATA | SAVESTATE_CHEATS | SAVESTATE_RTC)
40{
41 m_threadContext.core = core;
42 m_threadContext.userData = this;
43 updateROMInfo();
44
45 m_resetActions.append([this]() {
46 if (m_autoload) {
47 mCoreLoadState(m_threadContext.core, 0, m_loadStateFlags);
48 }
49 });
50
51 m_threadContext.startCallback = [](mCoreThread* context) {
52 CoreController* controller = static_cast<CoreController*>(context->userData);
53
54 switch (context->core->platform(context->core)) {
55#ifdef M_CORE_GBA
56 case mPLATFORM_GBA:
57 context->core->setPeripheral(context->core, mPERIPH_GBA_LUMINANCE, controller->m_inputController->luminance());
58 break;
59#endif
60 default:
61 break;
62 }
63
64 controller->updateFastForward();
65
66 if (controller->m_multiplayer) {
67 controller->m_multiplayer->attachGame(controller);
68 }
69
70 QMetaObject::invokeMethod(controller, "started");
71 };
72
73 m_threadContext.resetCallback = [](mCoreThread* context) {
74 CoreController* controller = static_cast<CoreController*>(context->userData);
75 for (auto action : controller->m_resetActions) {
76 action();
77 }
78
79 if (controller->m_override) {
80 controller->m_override->identify(context->core);
81 controller->m_override->apply(context->core);
82 }
83
84 controller->m_resetActions.clear();
85
86 if (!controller->m_hwaccel) {
87 context->core->setVideoBuffer(context->core, reinterpret_cast<color_t*>(controller->m_activeBuffer.data()), controller->screenDimensions().width());
88 }
89
90 QMetaObject::invokeMethod(controller, "didReset");
91 controller->finishFrame();
92 };
93
94 m_threadContext.frameCallback = [](mCoreThread* context) {
95 CoreController* controller = static_cast<CoreController*>(context->userData);
96
97 if (controller->m_autosaveCounter == AUTOSAVE_GRANULARITY) {
98 if (controller->m_autosave) {
99 mCoreSaveState(context->core, 0, controller->m_saveStateFlags);
100 }
101 controller->m_autosaveCounter = 0;
102 }
103 ++controller->m_autosaveCounter;
104
105 controller->finishFrame();
106 };
107
108 m_threadContext.cleanCallback = [](mCoreThread* context) {
109 CoreController* controller = static_cast<CoreController*>(context->userData);
110
111 if (controller->m_autosave) {
112 mCoreSaveState(context->core, 0, controller->m_saveStateFlags);
113 }
114
115 controller->clearMultiplayerController();
116 QMetaObject::invokeMethod(controller, "stopping");
117 };
118
119 m_threadContext.pauseCallback = [](mCoreThread* context) {
120 CoreController* controller = static_cast<CoreController*>(context->userData);
121
122 QMetaObject::invokeMethod(controller, "paused");
123 };
124
125 m_threadContext.unpauseCallback = [](mCoreThread* context) {
126 CoreController* controller = static_cast<CoreController*>(context->userData);
127
128 QMetaObject::invokeMethod(controller, "unpaused");
129 };
130
131 m_threadContext.logger.d.log = [](mLogger* logger, int category, enum mLogLevel level, const char* format, va_list args) {
132 mThreadLogger* logContext = reinterpret_cast<mThreadLogger*>(logger);
133 mCoreThread* context = logContext->p;
134
135 static const char* savestateMessage = "State %i saved";
136 static const char* loadstateMessage = "State %i loaded";
137 static const char* savestateFailedMessage = "State %i failed to load";
138 static int biosCat = -1;
139 static int statusCat = -1;
140 if (!context) {
141 return;
142 }
143 CoreController* controller = static_cast<CoreController*>(context->userData);
144 QString message;
145 if (biosCat < 0) {
146 biosCat = mLogCategoryById("gba.bios");
147 }
148 if (statusCat < 0) {
149 statusCat = mLogCategoryById("core.status");
150 }
151#ifdef M_CORE_GBA
152 if (level == mLOG_STUB && category == biosCat) {
153 va_list argc;
154 va_copy(argc, args);
155 int immediate = va_arg(argc, int);
156 va_end(argc);
157 QMetaObject::invokeMethod(controller, "unimplementedBiosCall", Q_ARG(int, immediate));
158 } else
159#endif
160 if (category == statusCat) {
161 // Slot 0 is reserved for suspend points
162 if (strncmp(loadstateMessage, format, strlen(loadstateMessage)) == 0) {
163 va_list argc;
164 va_copy(argc, args);
165 int slot = va_arg(argc, int);
166 va_end(argc);
167 if (slot == 0) {
168 format = "Loaded suspend state";
169 }
170 } else if (strncmp(savestateFailedMessage, format, strlen(savestateFailedMessage)) == 0 || strncmp(savestateMessage, format, strlen(savestateMessage)) == 0) {
171 va_list argc;
172 va_copy(argc, args);
173 int slot = va_arg(argc, int);
174 va_end(argc);
175 if (slot == 0) {
176 return;
177 }
178 }
179 message = QString().vsprintf(format, args);
180 QMetaObject::invokeMethod(controller, "statusPosted", Q_ARG(const QString&, message));
181 }
182 message = QString().vsprintf(format, args);
183 QMetaObject::invokeMethod(controller, "logPosted", Q_ARG(int, level), Q_ARG(int, category), Q_ARG(const QString&, message));
184 if (level == mLOG_FATAL) {
185 QMetaObject::invokeMethod(controller, "crashed", Q_ARG(const QString&, QString().vsprintf(format, args)));
186 }
187 };
188}
189
190CoreController::~CoreController() {
191 endVideoLog();
192 stop();
193 disconnect();
194
195 mCoreThreadJoin(&m_threadContext);
196
197 if (m_cacheSet) {
198 mCacheSetDeinit(m_cacheSet.get());
199 m_cacheSet.reset();
200 }
201
202 mCoreConfigDeinit(&m_threadContext.core->config);
203 m_threadContext.core->deinit(m_threadContext.core);
204}
205
206const color_t* CoreController::drawContext() {
207 if (m_hwaccel) {
208 return nullptr;
209 }
210 QMutexLocker locker(&m_bufferMutex);
211 return reinterpret_cast<const color_t*>(m_completeBuffer.constData());
212}
213
214QImage CoreController::getPixels() {
215 QByteArray buffer;
216 QSize size = screenDimensions();
217 size_t stride = size.width() * BYTES_PER_PIXEL;
218
219 if (!m_hwaccel) {
220 buffer = m_completeBuffer;
221 } else {
222 Interrupter interrupter(this);
223 const void* pixels;
224 m_threadContext.core->getPixels(m_threadContext.core, &pixels, &stride);
225 stride *= BYTES_PER_PIXEL;
226 buffer = QByteArray::fromRawData(static_cast<const char*>(pixels), stride * size.height());
227 }
228
229 QImage image(reinterpret_cast<const uchar*>(buffer.constData()),
230 size.width(), size.height(), stride, QImage::Format_RGBX8888);
231 image.bits(); // Cause QImage to detach
232 return image;
233}
234
235bool CoreController::isPaused() {
236 return mCoreThreadIsPaused(&m_threadContext);
237}
238
239bool CoreController::hasStarted() {
240 return mCoreThreadHasStarted(&m_threadContext);
241}
242
243mPlatform CoreController::platform() const {
244 return m_threadContext.core->platform(m_threadContext.core);
245}
246
247QSize CoreController::screenDimensions() const {
248 unsigned width, height;
249 m_threadContext.core->desiredVideoDimensions(m_threadContext.core, &width, &height);
250
251 return QSize(width, height);
252}
253
254void CoreController::loadConfig(ConfigController* config) {
255 Interrupter interrupter(this);
256 m_loadStateFlags = config->getOption("loadStateExtdata", m_loadStateFlags).toInt();
257 m_saveStateFlags = config->getOption("saveStateExtdata", m_saveStateFlags).toInt();
258 m_fastForwardRatio = config->getOption("fastForwardRatio", m_fastForwardRatio).toFloat();
259 m_fastForwardHeldRatio = config->getOption("fastForwardHeldRatio", m_fastForwardRatio).toFloat();
260 m_videoSync = config->getOption("videoSync", m_videoSync).toInt();
261 m_audioSync = config->getOption("audioSync", m_audioSync).toInt();
262 m_fpsTarget = config->getOption("fpsTarget").toFloat();
263 m_autosave = config->getOption("autosave", false).toInt();
264 m_autoload = config->getOption("autoload", true).toInt();
265 m_autofireThreshold = config->getOption("autofireThreshold", m_autofireThreshold).toInt();
266 m_fastForwardVolume = config->getOption("fastForwardVolume", -1).toInt();
267 m_fastForwardMute = config->getOption("fastForwardMute", -1).toInt();
268 mCoreConfigCopyValue(&m_threadContext.core->config, config->config(), "volume");
269 mCoreConfigCopyValue(&m_threadContext.core->config, config->config(), "mute");
270
271 QSize sizeBefore = screenDimensions();
272 m_activeBuffer.resize(256 * 224 * sizeof(color_t));
273 m_threadContext.core->setVideoBuffer(m_threadContext.core, reinterpret_cast<color_t*>(m_activeBuffer.data()), sizeBefore.width());
274
275 mCoreLoadForeignConfig(m_threadContext.core, config->config());
276
277 QSize sizeAfter = screenDimensions();
278 m_activeBuffer.resize(sizeAfter.width() * sizeAfter.height() * sizeof(color_t));
279 m_threadContext.core->setVideoBuffer(m_threadContext.core, reinterpret_cast<color_t*>(m_activeBuffer.data()), sizeAfter.width());
280
281 if (hasStarted()) {
282 updateFastForward();
283 mCoreThreadRewindParamsChanged(&m_threadContext);
284 }
285 if (sizeBefore != sizeAfter) {
286#ifdef M_CORE_GB
287 mCoreConfigSetIntValue(&m_threadContext.core->config, "sgb.borders", 0);
288 m_threadContext.core->reloadConfigOption(m_threadContext.core, "sgb.borders", nullptr);
289 mCoreConfigCopyValue(&m_threadContext.core->config, config->config(), "sgb.borders");
290 m_threadContext.core->reloadConfigOption(m_threadContext.core, "sgb.borders", nullptr);
291#endif
292 }
293}
294
295#ifdef USE_DEBUGGERS
296void CoreController::setDebugger(mDebugger* debugger) {
297 Interrupter interrupter(this);
298 if (debugger) {
299 mDebuggerAttach(debugger, m_threadContext.core);
300 mDebuggerEnter(debugger, DEBUGGER_ENTER_ATTACHED, 0);
301 } else {
302 m_threadContext.core->detachDebugger(m_threadContext.core);
303 }
304}
305#endif
306
307void CoreController::setMultiplayerController(MultiplayerController* controller) {
308 if (controller == m_multiplayer) {
309 return;
310 }
311 clearMultiplayerController();
312 m_multiplayer = controller;
313 if (!mCoreThreadHasStarted(&m_threadContext)) {
314 return;
315 }
316 mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* thread) {
317 CoreController* controller = static_cast<CoreController*>(thread->userData);
318 controller->m_multiplayer->attachGame(controller);
319 });
320}
321
322void CoreController::clearMultiplayerController() {
323 if (!m_multiplayer) {
324 return;
325 }
326 m_multiplayer->detachGame(this);
327 m_multiplayer = nullptr;
328}
329
330mCacheSet* CoreController::graphicCaches() {
331 if (m_cacheSet) {
332 return m_cacheSet.get();
333 }
334 Interrupter interrupter(this);
335 switch (platform()) {
336#ifdef M_CORE_GBA
337 case mPLATFORM_GBA: {
338 GBA* gba = static_cast<GBA*>(m_threadContext.core->board);
339 m_cacheSet = std::make_unique<mCacheSet>();
340 GBAVideoCacheInit(m_cacheSet.get());
341 GBAVideoCacheAssociate(m_cacheSet.get(), &gba->video);
342 break;
343 }
344#endif
345#ifdef M_CORE_GB
346 case mPLATFORM_GB: {
347 GB* gb = static_cast<GB*>(m_threadContext.core->board);
348 m_cacheSet = std::make_unique<mCacheSet>();
349 GBVideoCacheInit(m_cacheSet.get());
350 GBVideoCacheAssociate(m_cacheSet.get(), &gb->video);
351 break;
352 }
353#endif
354 default:
355 return nullptr;
356 }
357 return m_cacheSet.get();
358}
359
360void CoreController::setOverride(std::unique_ptr<Override> override) {
361 Interrupter interrupter(this);
362 m_override = std::move(override);
363 m_override->identify(m_threadContext.core);
364}
365
366void CoreController::setInputController(InputController* inputController) {
367 m_inputController = inputController;
368 m_threadContext.core->setPeripheral(m_threadContext.core, mPERIPH_ROTATION, m_inputController->rotationSource());
369 m_threadContext.core->setPeripheral(m_threadContext.core, mPERIPH_RUMBLE, m_inputController->rumble());
370 m_threadContext.core->setPeripheral(m_threadContext.core, mPERIPH_IMAGE_SOURCE, m_inputController->imageSource());
371}
372
373void CoreController::setLogger(LogController* logger) {
374 disconnect(m_log);
375 m_log = logger;
376 m_threadContext.logger.d.filter = logger->filter();
377 connect(this, &CoreController::logPosted, m_log, &LogController::postLog);
378}
379
380void CoreController::start() {
381 QSize size(screenDimensions());
382 m_activeBuffer.resize(size.width() * size.height() * sizeof(color_t));
383 m_activeBuffer.fill(0xFF);
384 m_completeBuffer = m_activeBuffer;
385
386 m_threadContext.core->setVideoBuffer(m_threadContext.core, reinterpret_cast<color_t*>(m_activeBuffer.data()), size.width());
387
388 if (!m_patched) {
389 mCoreAutoloadPatch(m_threadContext.core);
390 }
391 if (!mCoreThreadStart(&m_threadContext)) {
392 emit failed();
393 emit stopping();
394 }
395}
396
397void CoreController::stop() {
398 setSync(false);
399#ifdef USE_DEBUGGERS
400 setDebugger(nullptr);
401#endif
402 setPaused(false);
403 mCoreThreadEnd(&m_threadContext);
404}
405
406void CoreController::reset() {
407 mCoreThreadReset(&m_threadContext);
408}
409
410void CoreController::setPaused(bool paused) {
411 QMutexLocker locker(&m_actionMutex);
412 if (paused) {
413 if (m_moreFrames < 0) {
414 m_moreFrames = 1;
415 }
416 } else {
417 m_moreFrames = -1;
418 if (isPaused()) {
419 mCoreThreadUnpause(&m_threadContext);
420 }
421 }
422}
423
424void CoreController::frameAdvance() {
425 QMutexLocker locker(&m_actionMutex);
426 m_moreFrames = 1;
427 if (isPaused()) {
428 mCoreThreadUnpause(&m_threadContext);
429 }
430}
431
432void CoreController::addFrameAction(std::function<void ()> action) {
433 QMutexLocker locker(&m_actionMutex);
434 m_frameActions.append(action);
435}
436
437void CoreController::setSync(bool sync) {
438 if (sync) {
439 m_threadContext.impl->sync.audioWait = m_audioSync;
440 m_threadContext.impl->sync.videoFrameWait = m_videoSync;
441 } else {
442 m_threadContext.impl->sync.audioWait = false;
443 m_threadContext.impl->sync.videoFrameWait = false;
444 }
445}
446
447void CoreController::setRewinding(bool rewind) {
448 if (!m_threadContext.core->opts.rewindEnable) {
449 return;
450 }
451 if (rewind && m_multiplayer && m_multiplayer->attached() > 1) {
452 return;
453 }
454
455 if (rewind && isPaused()) {
456 setPaused(false);
457 // TODO: restore autopausing
458 }
459 mCoreThreadSetRewinding(&m_threadContext, rewind);
460}
461
462void CoreController::rewind(int states) {
463 {
464 Interrupter interrupter(this);
465 if (!states) {
466 states = INT_MAX;
467 }
468 for (int i = 0; i < states; ++i) {
469 if (!mCoreRewindRestore(&m_threadContext.impl->rewind, m_threadContext.core)) {
470 break;
471 }
472 }
473 }
474 emit frameAvailable();
475 emit rewound();
476}
477
478void CoreController::setFastForward(bool enable) {
479 if (m_fastForward == enable) {
480 return;
481 }
482 m_fastForward = enable;
483 updateFastForward();
484 emit fastForwardChanged(enable);
485}
486
487void CoreController::forceFastForward(bool enable) {
488 if (m_fastForwardForced == enable) {
489 return;
490 }
491 m_fastForwardForced = enable;
492 updateFastForward();
493 emit fastForwardChanged(enable || m_fastForward);
494}
495
496void CoreController::loadState(int slot) {
497 if (slot > 0 && slot != m_stateSlot) {
498 m_stateSlot = slot;
499 m_backupSaveState.clear();
500 }
501 mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
502 CoreController* controller = static_cast<CoreController*>(context->userData);
503 if (!controller->m_backupLoadState.isOpen()) {
504 controller->m_backupLoadState = VFileDevice::openMemory();
505 }
506 mCoreSaveStateNamed(context->core, controller->m_backupLoadState, controller->m_saveStateFlags);
507 if (mCoreLoadState(context->core, controller->m_stateSlot, controller->m_loadStateFlags)) {
508 emit controller->frameAvailable();
509 emit controller->stateLoaded();
510 }
511 });
512}
513
514void CoreController::loadState(const QString& path, int flags) {
515 m_statePath = path;
516 int savedFlags = m_loadStateFlags;
517 if (flags != -1) {
518 m_loadStateFlags = flags;
519 }
520 mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
521 CoreController* controller = static_cast<CoreController*>(context->userData);
522 VFile* vf = VFileDevice::open(controller->m_statePath, O_RDONLY);
523 if (!vf) {
524 return;
525 }
526 if (!controller->m_backupLoadState.isOpen()) {
527 controller->m_backupLoadState = VFileDevice::openMemory();
528 }
529 mCoreSaveStateNamed(context->core, controller->m_backupLoadState, controller->m_saveStateFlags);
530 if (mCoreLoadStateNamed(context->core, vf, controller->m_loadStateFlags)) {
531 emit controller->frameAvailable();
532 emit controller->stateLoaded();
533 }
534 vf->close(vf);
535 });
536 m_loadStateFlags = savedFlags;
537}
538
539void CoreController::loadState(QIODevice* iodev, int flags) {
540 m_stateVf = VFileDevice::wrap(iodev, QIODevice::ReadOnly);
541 if (!m_stateVf) {
542 return;
543 }
544 int savedFlags = m_loadStateFlags;
545 if (flags != -1) {
546 m_loadStateFlags = flags;
547 }
548 mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
549 CoreController* controller = static_cast<CoreController*>(context->userData);
550 VFile* vf = controller->m_stateVf;
551 if (!vf) {
552 return;
553 }
554 if (!controller->m_backupLoadState.isOpen()) {
555 controller->m_backupLoadState = VFileDevice::openMemory();
556 }
557 mCoreSaveStateNamed(context->core, controller->m_backupLoadState, controller->m_saveStateFlags);
558 if (mCoreLoadStateNamed(context->core, vf, controller->m_loadStateFlags)) {
559 emit controller->frameAvailable();
560 emit controller->stateLoaded();
561 }
562 vf->close(vf);
563 });
564 m_loadStateFlags = savedFlags;
565}
566
567void CoreController::saveState(int slot) {
568 if (slot > 0) {
569 m_stateSlot = slot;
570 }
571 mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
572 CoreController* controller = static_cast<CoreController*>(context->userData);
573 VFile* vf = mCoreGetState(context->core, controller->m_stateSlot, false);
574 if (vf) {
575 controller->m_backupSaveState.resize(vf->size(vf));
576 vf->read(vf, controller->m_backupSaveState.data(), controller->m_backupSaveState.size());
577 vf->close(vf);
578 }
579 mCoreSaveState(context->core, controller->m_stateSlot, controller->m_saveStateFlags);
580 });
581}
582
583void CoreController::saveState(const QString& path, int flags) {
584 m_statePath = path;
585 int savedFlags = m_saveStateFlags;
586 if (flags != -1) {
587 m_saveStateFlags = flags;
588 }
589 mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
590 CoreController* controller = static_cast<CoreController*>(context->userData);
591 VFile* vf = VFileDevice::open(controller->m_statePath, O_RDONLY);
592 if (vf) {
593 controller->m_backupSaveState.resize(vf->size(vf));
594 vf->read(vf, controller->m_backupSaveState.data(), controller->m_backupSaveState.size());
595 vf->close(vf);
596 }
597 vf = VFileDevice::open(controller->m_statePath, O_WRONLY | O_CREAT | O_TRUNC);
598 if (!vf) {
599 return;
600 }
601 mCoreSaveStateNamed(context->core, vf, controller->m_saveStateFlags);
602 vf->close(vf);
603 });
604 m_saveStateFlags = savedFlags;
605}
606
607void CoreController::saveState(QIODevice* iodev, int flags) {
608 m_stateVf = VFileDevice::wrap(iodev, QIODevice::WriteOnly | QIODevice::Truncate);
609 if (!m_stateVf) {
610 return;
611 }
612 int savedFlags = m_saveStateFlags;
613 if (flags != -1) {
614 m_saveStateFlags = flags;
615 }
616 mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
617 CoreController* controller = static_cast<CoreController*>(context->userData);
618 VFile* vf = controller->m_stateVf;
619 if (!vf) {
620 return;
621 }
622 mCoreSaveStateNamed(context->core, vf, controller->m_saveStateFlags);
623 vf->close(vf);
624 });
625 m_saveStateFlags = savedFlags;
626}
627
628void CoreController::loadBackupState() {
629 if (!m_backupLoadState.isOpen()) {
630 return;
631 }
632
633 mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
634 CoreController* controller = static_cast<CoreController*>(context->userData);
635 controller->m_backupLoadState.seek(0);
636 if (mCoreLoadStateNamed(context->core, controller->m_backupLoadState, controller->m_loadStateFlags)) {
637 mLOG(STATUS, INFO, "Undid state load");
638 controller->frameAvailable();
639 controller->stateLoaded();
640 }
641 controller->m_backupLoadState.close();
642 });
643}
644
645void CoreController::saveBackupState() {
646 if (m_backupSaveState.isEmpty()) {
647 return;
648 }
649
650 mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
651 CoreController* controller = static_cast<CoreController*>(context->userData);
652 VFile* vf = mCoreGetState(context->core, controller->m_stateSlot, true);
653 if (vf) {
654 vf->write(vf, controller->m_backupSaveState.constData(), controller->m_backupSaveState.size());
655 vf->close(vf);
656 mLOG(STATUS, INFO, "Undid state save");
657 }
658 controller->m_backupSaveState.clear();
659 });
660}
661
662void CoreController::loadSave(const QString& path, bool temporary) {
663 m_resetActions.append([this, path, temporary]() {
664 VFile* vf = VFileDevice::open(path, temporary ? O_RDONLY : O_RDWR);
665 if (!vf) {
666 LOG(QT, ERROR) << tr("Failed to open save file: %1").arg(path);
667 return;
668 }
669
670 if (temporary) {
671 m_threadContext.core->loadTemporarySave(m_threadContext.core, vf);
672 } else {
673 m_threadContext.core->loadSave(m_threadContext.core, vf);
674 }
675 });
676 reset();
677}
678
679void CoreController::loadPatch(const QString& patchPath) {
680 Interrupter interrupter(this);
681 VFile* patch = VFileDevice::open(patchPath, O_RDONLY);
682 if (patch) {
683 m_threadContext.core->loadPatch(m_threadContext.core, patch);
684 m_patched = true;
685 patch->close(patch);
686 updateROMInfo();
687 }
688 if (mCoreThreadHasStarted(&m_threadContext)) {
689 interrupter.resume();
690 reset();
691 }
692}
693
694void CoreController::replaceGame(const QString& path) {
695 QFileInfo info(path);
696 if (!info.isReadable()) {
697 LOG(QT, ERROR) << tr("Failed to open game file: %1").arg(path);
698 return;
699 }
700 QString fname = info.canonicalFilePath();
701 Interrupter interrupter(this);
702 mDirectorySetDetachBase(&m_threadContext.core->dirs);
703 mCoreLoadFile(m_threadContext.core, fname.toUtf8().constData());
704 updateROMInfo();
705}
706
707void CoreController::yankPak() {
708 Interrupter interrupter(this);
709
710 switch (platform()) {
711#ifdef M_CORE_GBA
712 case mPLATFORM_GBA:
713 GBAYankROM(static_cast<GBA*>(m_threadContext.core->board));
714 break;
715#endif
716#ifdef M_CORE_GB
717 case mPLATFORM_GB:
718 GBYankROM(static_cast<GB*>(m_threadContext.core->board));
719 break;
720#endif
721 case mPLATFORM_NONE:
722 LOG(QT, ERROR) << tr("Can't yank pack in unexpected platform!");
723 break;
724 }
725}
726
727void CoreController::addKey(int key) {
728 m_activeKeys |= 1 << key;
729}
730
731void CoreController::clearKey(int key) {
732 m_activeKeys &= ~(1 << key);
733}
734
735void CoreController::setAutofire(int key, bool enable) {
736 if (key >= 32 || key < 0) {
737 return;
738 }
739
740 m_autofire[key] = enable;
741 m_autofireStatus[key] = 0;
742}
743
744#ifdef USE_PNG
745void CoreController::screenshot() {
746 mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
747 mCoreTakeScreenshot(context->core);
748 });
749}
750#endif
751
752void CoreController::setRealTime() {
753 m_threadContext.core->rtc.override = RTC_NO_OVERRIDE;
754}
755
756void CoreController::setFixedTime(const QDateTime& time) {
757 m_threadContext.core->rtc.override = RTC_FIXED;
758 m_threadContext.core->rtc.value = time.toMSecsSinceEpoch();
759}
760
761void CoreController::setFakeEpoch(const QDateTime& time) {
762 m_threadContext.core->rtc.override = RTC_FAKE_EPOCH;
763 m_threadContext.core->rtc.value = time.toMSecsSinceEpoch();
764}
765
766void CoreController::scanCard(const QString& path) {
767#ifdef M_CORE_GBA
768 QImage image(path);
769 if (image.isNull()) {
770 QFile file(path);
771 file.open(QIODevice::ReadOnly);
772 m_eReaderData = file.read(2912);
773 } else if (image.size() == QSize(989, 44)) {
774 const uchar* bits = image.constBits();
775 size_t size;
776#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
777 size = image.sizeInBytes();
778#else
779 size = image.byteCount();
780#endif
781 m_eReaderData.setRawData(reinterpret_cast<const char*>(bits), size);
782 }
783
784 mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* thread) {
785 CoreController* controller = static_cast<CoreController*>(thread->userData);
786 GBAEReaderQueueCard(static_cast<GBA*>(thread->core->board), controller->m_eReaderData.constData(), controller->m_eReaderData.size());
787 });
788#endif
789}
790
791
792void CoreController::importSharkport(const QString& path) {
793#ifdef M_CORE_GBA
794 if (platform() != mPLATFORM_GBA) {
795 return;
796 }
797 VFile* vf = VFileDevice::open(path, O_RDONLY);
798 if (!vf) {
799 LOG(QT, ERROR) << tr("Failed to open snapshot file for reading: %1").arg(path);
800 return;
801 }
802 Interrupter interrupter(this);
803 GBASavedataImportSharkPort(static_cast<GBA*>(m_threadContext.core->board), vf, false);
804 vf->close(vf);
805#endif
806}
807
808void CoreController::exportSharkport(const QString& path) {
809#ifdef M_CORE_GBA
810 if (platform() != mPLATFORM_GBA) {
811 return;
812 }
813 VFile* vf = VFileDevice::open(path, O_WRONLY | O_CREAT | O_TRUNC);
814 if (!vf) {
815 LOG(QT, ERROR) << tr("Failed to open snapshot file for writing: %1").arg(path);
816 return;
817 }
818 Interrupter interrupter(this);
819 GBASavedataExportSharkPort(static_cast<GBA*>(m_threadContext.core->board), vf);
820 vf->close(vf);
821#endif
822}
823
824#ifdef M_CORE_GB
825void CoreController::attachPrinter() {
826 if (platform() != mPLATFORM_GB) {
827 return;
828 }
829 GB* gb = static_cast<GB*>(m_threadContext.core->board);
830 clearMultiplayerController();
831 GBPrinterCreate(&m_printer.d);
832 m_printer.parent = this;
833 m_printer.d.print = [](GBPrinter* printer, int height, const uint8_t* data) {
834 QGBPrinter* qPrinter = reinterpret_cast<QGBPrinter*>(printer);
835 QImage image(GB_VIDEO_HORIZONTAL_PIXELS, height, QImage::Format_Indexed8);
836 QVector<QRgb> colors;
837 colors.append(qRgb(0xF8, 0xF8, 0xF8));
838 colors.append(qRgb(0xA8, 0xA8, 0xA8));
839 colors.append(qRgb(0x50, 0x50, 0x50));
840 colors.append(qRgb(0x00, 0x00, 0x00));
841 image.setColorTable(colors);
842 for (int y = 0; y < height; ++y) {
843 for (int x = 0; x < GB_VIDEO_HORIZONTAL_PIXELS; x += 4) {
844 uint8_t byte = data[(x + y * GB_VIDEO_HORIZONTAL_PIXELS) / 4];
845 image.setPixel(x + 0, y, (byte & 0xC0) >> 6);
846 image.setPixel(x + 1, y, (byte & 0x30) >> 4);
847 image.setPixel(x + 2, y, (byte & 0x0C) >> 2);
848 image.setPixel(x + 3, y, (byte & 0x03) >> 0);
849 }
850 }
851 QMetaObject::invokeMethod(qPrinter->parent, "imagePrinted", Q_ARG(const QImage&, image));
852 };
853 Interrupter interrupter(this);
854 GBSIOSetDriver(&gb->sio, &m_printer.d.d);
855}
856
857void CoreController::detachPrinter() {
858 if (platform() != mPLATFORM_GB) {
859 return;
860 }
861 Interrupter interrupter(this);
862 GB* gb = static_cast<GB*>(m_threadContext.core->board);
863 GBPrinterDonePrinting(&m_printer.d);
864 GBSIOSetDriver(&gb->sio, nullptr);
865}
866
867void CoreController::endPrint() {
868 if (platform() != mPLATFORM_GB) {
869 return;
870 }
871 Interrupter interrupter(this);
872 GBPrinterDonePrinting(&m_printer.d);
873}
874#endif
875
876#ifdef M_CORE_GBA
877void CoreController::attachBattleChipGate() {
878 if (platform() != mPLATFORM_GBA) {
879 return;
880 }
881 Interrupter interrupter(this);
882 clearMultiplayerController();
883 GBASIOBattlechipGateCreate(&m_battlechip);
884 m_threadContext.core->setPeripheral(m_threadContext.core, mPERIPH_GBA_BATTLECHIP_GATE, &m_battlechip);
885}
886
887void CoreController::detachBattleChipGate() {
888 if (platform() != mPLATFORM_GBA) {
889 return;
890 }
891 Interrupter interrupter(this);
892 m_threadContext.core->setPeripheral(m_threadContext.core, mPERIPH_GBA_BATTLECHIP_GATE, nullptr);
893}
894
895void CoreController::setBattleChipId(uint16_t id) {
896 if (platform() != mPLATFORM_GBA) {
897 return;
898 }
899 Interrupter interrupter(this);
900 m_battlechip.chipId = id;
901}
902
903void CoreController::setBattleChipFlavor(int flavor) {
904 if (platform() != mPLATFORM_GBA) {
905 return;
906 }
907 Interrupter interrupter(this);
908 m_battlechip.flavor = flavor;
909}
910#endif
911
912void CoreController::setAVStream(mAVStream* stream) {
913 Interrupter interrupter(this);
914 m_threadContext.core->setAVStream(m_threadContext.core, stream);
915}
916
917void CoreController::clearAVStream() {
918 Interrupter interrupter(this);
919 m_threadContext.core->setAVStream(m_threadContext.core, nullptr);
920}
921
922void CoreController::clearOverride() {
923 m_override.reset();
924}
925
926void CoreController::startVideoLog(const QString& path, bool compression) {
927 if (m_vl) {
928 return;
929 }
930
931 VFile* vf = VFileDevice::open(path, O_WRONLY | O_CREAT | O_TRUNC);
932 if (!vf) {
933 return;
934 }
935 startVideoLog(vf, compression);
936}
937
938void CoreController::startVideoLog(VFile* vf, bool compression) {
939 if (m_vl || !vf) {
940 return;
941 }
942
943 Interrupter interrupter(this);
944 m_vl = mVideoLogContextCreate(m_threadContext.core);
945 m_vlVf = vf;
946 mVideoLogContextSetOutput(m_vl, m_vlVf);
947 mVideoLogContextSetCompression(m_vl, compression);
948 mVideoLogContextWriteHeader(m_vl, m_threadContext.core);
949}
950
951void CoreController::endVideoLog(bool closeVf) {
952 if (!m_vl) {
953 return;
954 }
955
956 Interrupter interrupter(this);
957 mVideoLogContextDestroy(m_threadContext.core, m_vl, closeVf);
958 if (closeVf) {
959 m_vlVf = nullptr;
960 }
961 m_vl = nullptr;
962}
963
964void CoreController::setFramebufferHandle(int fb) {
965 Interrupter interrupter(this);
966 if (fb < 0) {
967 if (!m_hwaccel) {
968 return;
969 }
970 mCoreConfigSetIntValue(&m_threadContext.core->config, "hwaccelVideo", 0);
971 m_threadContext.core->setVideoGLTex(m_threadContext.core, -1);
972 m_hwaccel = false;
973 } else {
974 mCoreConfigSetIntValue(&m_threadContext.core->config, "hwaccelVideo", 1);
975 m_threadContext.core->setVideoGLTex(m_threadContext.core, fb);
976 if (m_hwaccel) {
977 return;
978 }
979 m_hwaccel = true;
980 }
981 if (hasStarted()) {
982 m_threadContext.core->reloadConfigOption(m_threadContext.core, "hwaccelVideo", NULL);
983 if (!m_hwaccel) {
984 m_threadContext.core->setVideoBuffer(m_threadContext.core, reinterpret_cast<color_t*>(m_activeBuffer.data()), screenDimensions().width());
985 }
986 }
987}
988
989void CoreController::updateKeys() {
990 int activeKeys = m_activeKeys | updateAutofire() | m_inputController->pollEvents();
991 m_threadContext.core->setKeys(m_threadContext.core, activeKeys);
992}
993
994int CoreController::updateAutofire() {
995 int active = 0;
996 for (int k = 0; k < 32; ++k) {
997 if (!m_autofire[k]) {
998 continue;
999 }
1000 ++m_autofireStatus[k];
1001 if (m_autofireStatus[k] >= 2 * m_autofireThreshold) {
1002 m_autofireStatus[k] = 0;
1003 } else if (m_autofireStatus[k] >= m_autofireThreshold) {
1004 active |= 1 << k;
1005 }
1006 }
1007 return active;
1008}
1009
1010void CoreController::finishFrame() {
1011 if (!m_hwaccel) {
1012 unsigned width, height;
1013 m_threadContext.core->desiredVideoDimensions(m_threadContext.core, &width, &height);
1014
1015 QMutexLocker locker(&m_bufferMutex);
1016 memcpy(m_completeBuffer.data(), m_activeBuffer.constData(), width * height * BYTES_PER_PIXEL);
1017 }
1018
1019 {
1020 QMutexLocker locker(&m_actionMutex);
1021 QList<std::function<void ()>> frameActions(m_frameActions);
1022 m_frameActions.clear();
1023 for (auto& action : frameActions) {
1024 action();
1025 }
1026 if (m_moreFrames > 0) {
1027 --m_moreFrames;
1028 if (!m_moreFrames) {
1029 mCoreThreadPauseFromThread(&m_threadContext);
1030 }
1031 }
1032 }
1033 updateKeys();
1034
1035 QMetaObject::invokeMethod(this, "frameAvailable");
1036}
1037
1038void CoreController::updateFastForward() {
1039 // If we have "Fast forward" checked in the menu (m_fastForwardForced)
1040 // or are holding the fast forward button (m_fastForward):
1041 if (m_fastForward || m_fastForwardForced) {
1042 if (m_fastForwardVolume >= 0) {
1043 m_threadContext.core->opts.volume = m_fastForwardVolume;
1044 }
1045 if (m_fastForwardMute >= 0) {
1046 m_threadContext.core->opts.mute = m_fastForwardMute;
1047 }
1048
1049 // If we aren't holding the fast forward button
1050 // then use the non "(held)" ratio
1051 if(!m_fastForward) {
1052 if (m_fastForwardRatio > 0) {
1053 m_threadContext.impl->sync.fpsTarget = m_fpsTarget * m_fastForwardRatio;
1054 setSync(true);
1055 } else {
1056 setSync(false);
1057 }
1058 } else {
1059 // If we are holding the fast forward button,
1060 // then use the held ratio
1061 if (m_fastForwardHeldRatio > 0) {
1062 m_threadContext.impl->sync.fpsTarget = m_fpsTarget * m_fastForwardHeldRatio;
1063 setSync(true);
1064 } else {
1065 setSync(false);
1066 }
1067 }
1068 } else {
1069 if (!mCoreConfigGetIntValue(&m_threadContext.core->config, "volume", &m_threadContext.core->opts.volume)) {
1070 m_threadContext.core->opts.volume = 0x100;
1071 }
1072 int fakeBool = 0;
1073 mCoreConfigGetIntValue(&m_threadContext.core->config, "mute", &fakeBool);
1074 m_threadContext.core->opts.mute = fakeBool;
1075 m_threadContext.impl->sync.fpsTarget = m_fpsTarget;
1076 setSync(true);
1077 }
1078
1079 m_threadContext.core->reloadConfigOption(m_threadContext.core, NULL, NULL);
1080}
1081
1082void CoreController::updateROMInfo() {
1083 const NoIntroDB* db = GBAApp::app()->gameDB();
1084 NoIntroGame game{};
1085 m_crc32 = 0;
1086 mCore* core = m_threadContext.core;
1087 core->checksum(core, &m_crc32, mCHECKSUM_CRC32);
1088
1089 char gameTitle[17] = { '\0' };
1090 core->getGameTitle(core, gameTitle);
1091 m_internalTitle = QLatin1String(gameTitle);
1092
1093#ifdef USE_SQLITE3
1094 if (db && m_crc32 && NoIntroDBLookupGameByCRC(db, m_crc32, &game)) {
1095 m_dbTitle = QString::fromUtf8(game.name);
1096 }
1097#endif
1098}
1099
1100CoreController::Interrupter::Interrupter()
1101 : m_parent(nullptr)
1102{
1103}
1104
1105CoreController::Interrupter::Interrupter(CoreController* parent)
1106 : m_parent(parent)
1107{
1108 interrupt();
1109}
1110
1111CoreController::Interrupter::Interrupter(std::shared_ptr<CoreController> parent)
1112 : m_parent(parent.get())
1113{
1114 interrupt();
1115}
1116
1117CoreController::Interrupter::Interrupter(const Interrupter& other)
1118 : m_parent(other.m_parent)
1119{
1120 interrupt();
1121}
1122
1123CoreController::Interrupter::~Interrupter() {
1124 resume();
1125}
1126
1127CoreController::Interrupter& CoreController::Interrupter::operator=(const Interrupter& other)
1128{
1129 interrupt(other.m_parent);
1130 return *this;
1131}
1132
1133void CoreController::Interrupter::interrupt(CoreController* controller) {
1134 if (m_parent != controller) {
1135 CoreController* old = m_parent;
1136 m_parent = controller;
1137 interrupt();
1138 resume(old);
1139 }
1140}
1141
1142void CoreController::Interrupter::interrupt(std::shared_ptr<CoreController> controller) {
1143 interrupt(controller.get());
1144}
1145
1146void CoreController::Interrupter::interrupt() {
1147 if (!m_parent || !m_parent->thread()->impl) {
1148 return;
1149 }
1150
1151 if (mCoreThreadGet() != m_parent->thread()) {
1152 mCoreThreadInterrupt(m_parent->thread());
1153 } else {
1154 mCoreThreadInterruptFromThread(m_parent->thread());
1155 }
1156}
1157
1158void CoreController::Interrupter::resume() {
1159 resume(m_parent);
1160 m_parent = nullptr;
1161}
1162
1163void CoreController::Interrupter::resume(CoreController* controller) {
1164 if (!controller || !controller->thread()->impl) {
1165 return;
1166 }
1167
1168 mCoreThreadContinue(controller->thread());
1169}