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 reset();
690 }
691}
692
693void CoreController::replaceGame(const QString& path) {
694 QFileInfo info(path);
695 if (!info.isReadable()) {
696 LOG(QT, ERROR) << tr("Failed to open game file: %1").arg(path);
697 return;
698 }
699 QString fname = info.canonicalFilePath();
700 Interrupter interrupter(this);
701 mDirectorySetDetachBase(&m_threadContext.core->dirs);
702 mCoreLoadFile(m_threadContext.core, fname.toUtf8().constData());
703 updateROMInfo();
704}
705
706void CoreController::yankPak() {
707 Interrupter interrupter(this);
708
709 switch (platform()) {
710#ifdef M_CORE_GBA
711 case mPLATFORM_GBA:
712 GBAYankROM(static_cast<GBA*>(m_threadContext.core->board));
713 break;
714#endif
715#ifdef M_CORE_GB
716 case mPLATFORM_GB:
717 GBYankROM(static_cast<GB*>(m_threadContext.core->board));
718 break;
719#endif
720 case mPLATFORM_NONE:
721 LOG(QT, ERROR) << tr("Can't yank pack in unexpected platform!");
722 break;
723 }
724}
725
726void CoreController::addKey(int key) {
727 m_activeKeys |= 1 << key;
728}
729
730void CoreController::clearKey(int key) {
731 m_activeKeys &= ~(1 << key);
732}
733
734void CoreController::setAutofire(int key, bool enable) {
735 if (key >= 32 || key < 0) {
736 return;
737 }
738
739 m_autofire[key] = enable;
740 m_autofireStatus[key] = 0;
741}
742
743#ifdef USE_PNG
744void CoreController::screenshot() {
745 mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
746 mCoreTakeScreenshot(context->core);
747 });
748}
749#endif
750
751void CoreController::setRealTime() {
752 m_threadContext.core->rtc.override = RTC_NO_OVERRIDE;
753}
754
755void CoreController::setFixedTime(const QDateTime& time) {
756 m_threadContext.core->rtc.override = RTC_FIXED;
757 m_threadContext.core->rtc.value = time.toMSecsSinceEpoch();
758}
759
760void CoreController::setFakeEpoch(const QDateTime& time) {
761 m_threadContext.core->rtc.override = RTC_FAKE_EPOCH;
762 m_threadContext.core->rtc.value = time.toMSecsSinceEpoch();
763}
764
765void CoreController::scanCard(const QString& path) {
766#ifdef M_CORE_GBA
767 QImage image(path);
768 if (image.isNull()) {
769 QFile file(path);
770 file.open(QIODevice::ReadOnly);
771 m_eReaderData = file.read(2912);
772 } else if (image.size() == QSize(989, 44)) {
773 const uchar* bits = image.constBits();
774 size_t size;
775#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
776 size = image.sizeInBytes();
777#else
778 size = image.byteCount();
779#endif
780 m_eReaderData.setRawData(reinterpret_cast<const char*>(bits), size);
781 }
782
783 mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* thread) {
784 CoreController* controller = static_cast<CoreController*>(thread->userData);
785 GBAEReaderQueueCard(static_cast<GBA*>(thread->core->board), controller->m_eReaderData.constData(), controller->m_eReaderData.size());
786 });
787#endif
788}
789
790
791void CoreController::importSharkport(const QString& path) {
792#ifdef M_CORE_GBA
793 if (platform() != mPLATFORM_GBA) {
794 return;
795 }
796 VFile* vf = VFileDevice::open(path, O_RDONLY);
797 if (!vf) {
798 LOG(QT, ERROR) << tr("Failed to open snapshot file for reading: %1").arg(path);
799 return;
800 }
801 Interrupter interrupter(this);
802 GBASavedataImportSharkPort(static_cast<GBA*>(m_threadContext.core->board), vf, false);
803 vf->close(vf);
804#endif
805}
806
807void CoreController::exportSharkport(const QString& path) {
808#ifdef M_CORE_GBA
809 if (platform() != mPLATFORM_GBA) {
810 return;
811 }
812 VFile* vf = VFileDevice::open(path, O_WRONLY | O_CREAT | O_TRUNC);
813 if (!vf) {
814 LOG(QT, ERROR) << tr("Failed to open snapshot file for writing: %1").arg(path);
815 return;
816 }
817 Interrupter interrupter(this);
818 GBASavedataExportSharkPort(static_cast<GBA*>(m_threadContext.core->board), vf);
819 vf->close(vf);
820#endif
821}
822
823#ifdef M_CORE_GB
824void CoreController::attachPrinter() {
825 if (platform() != mPLATFORM_GB) {
826 return;
827 }
828 GB* gb = static_cast<GB*>(m_threadContext.core->board);
829 clearMultiplayerController();
830 GBPrinterCreate(&m_printer.d);
831 m_printer.parent = this;
832 m_printer.d.print = [](GBPrinter* printer, int height, const uint8_t* data) {
833 QGBPrinter* qPrinter = reinterpret_cast<QGBPrinter*>(printer);
834 QImage image(GB_VIDEO_HORIZONTAL_PIXELS, height, QImage::Format_Indexed8);
835 QVector<QRgb> colors;
836 colors.append(qRgb(0xF8, 0xF8, 0xF8));
837 colors.append(qRgb(0xA8, 0xA8, 0xA8));
838 colors.append(qRgb(0x50, 0x50, 0x50));
839 colors.append(qRgb(0x00, 0x00, 0x00));
840 image.setColorTable(colors);
841 for (int y = 0; y < height; ++y) {
842 for (int x = 0; x < GB_VIDEO_HORIZONTAL_PIXELS; x += 4) {
843 uint8_t byte = data[(x + y * GB_VIDEO_HORIZONTAL_PIXELS) / 4];
844 image.setPixel(x + 0, y, (byte & 0xC0) >> 6);
845 image.setPixel(x + 1, y, (byte & 0x30) >> 4);
846 image.setPixel(x + 2, y, (byte & 0x0C) >> 2);
847 image.setPixel(x + 3, y, (byte & 0x03) >> 0);
848 }
849 }
850 QMetaObject::invokeMethod(qPrinter->parent, "imagePrinted", Q_ARG(const QImage&, image));
851 };
852 Interrupter interrupter(this);
853 GBSIOSetDriver(&gb->sio, &m_printer.d.d);
854}
855
856void CoreController::detachPrinter() {
857 if (platform() != mPLATFORM_GB) {
858 return;
859 }
860 Interrupter interrupter(this);
861 GB* gb = static_cast<GB*>(m_threadContext.core->board);
862 GBPrinterDonePrinting(&m_printer.d);
863 GBSIOSetDriver(&gb->sio, nullptr);
864}
865
866void CoreController::endPrint() {
867 if (platform() != mPLATFORM_GB) {
868 return;
869 }
870 Interrupter interrupter(this);
871 GBPrinterDonePrinting(&m_printer.d);
872}
873#endif
874
875#ifdef M_CORE_GBA
876void CoreController::attachBattleChipGate() {
877 if (platform() != mPLATFORM_GBA) {
878 return;
879 }
880 Interrupter interrupter(this);
881 clearMultiplayerController();
882 GBASIOBattlechipGateCreate(&m_battlechip);
883 m_threadContext.core->setPeripheral(m_threadContext.core, mPERIPH_GBA_BATTLECHIP_GATE, &m_battlechip);
884}
885
886void CoreController::detachBattleChipGate() {
887 if (platform() != mPLATFORM_GBA) {
888 return;
889 }
890 Interrupter interrupter(this);
891 m_threadContext.core->setPeripheral(m_threadContext.core, mPERIPH_GBA_BATTLECHIP_GATE, nullptr);
892}
893
894void CoreController::setBattleChipId(uint16_t id) {
895 if (platform() != mPLATFORM_GBA) {
896 return;
897 }
898 Interrupter interrupter(this);
899 m_battlechip.chipId = id;
900}
901
902void CoreController::setBattleChipFlavor(int flavor) {
903 if (platform() != mPLATFORM_GBA) {
904 return;
905 }
906 Interrupter interrupter(this);
907 m_battlechip.flavor = flavor;
908}
909#endif
910
911void CoreController::setAVStream(mAVStream* stream) {
912 Interrupter interrupter(this);
913 m_threadContext.core->setAVStream(m_threadContext.core, stream);
914}
915
916void CoreController::clearAVStream() {
917 Interrupter interrupter(this);
918 m_threadContext.core->setAVStream(m_threadContext.core, nullptr);
919}
920
921void CoreController::clearOverride() {
922 m_override.reset();
923}
924
925void CoreController::startVideoLog(const QString& path, bool compression) {
926 if (m_vl) {
927 return;
928 }
929
930 VFile* vf = VFileDevice::open(path, O_WRONLY | O_CREAT | O_TRUNC);
931 if (!vf) {
932 return;
933 }
934 startVideoLog(vf, compression);
935}
936
937void CoreController::startVideoLog(VFile* vf, bool compression) {
938 if (m_vl || !vf) {
939 return;
940 }
941
942 Interrupter interrupter(this);
943 m_vl = mVideoLogContextCreate(m_threadContext.core);
944 m_vlVf = vf;
945 mVideoLogContextSetOutput(m_vl, m_vlVf);
946 mVideoLogContextSetCompression(m_vl, compression);
947 mVideoLogContextWriteHeader(m_vl, m_threadContext.core);
948}
949
950void CoreController::endVideoLog(bool closeVf) {
951 if (!m_vl) {
952 return;
953 }
954
955 Interrupter interrupter(this);
956 mVideoLogContextDestroy(m_threadContext.core, m_vl, closeVf);
957 if (closeVf) {
958 m_vlVf = nullptr;
959 }
960 m_vl = nullptr;
961}
962
963void CoreController::setFramebufferHandle(int fb) {
964 Interrupter interrupter(this);
965 if (fb < 0) {
966 if (!m_hwaccel) {
967 return;
968 }
969 mCoreConfigSetIntValue(&m_threadContext.core->config, "hwaccelVideo", 0);
970 m_threadContext.core->setVideoGLTex(m_threadContext.core, -1);
971 m_hwaccel = false;
972 } else {
973 mCoreConfigSetIntValue(&m_threadContext.core->config, "hwaccelVideo", 1);
974 m_threadContext.core->setVideoGLTex(m_threadContext.core, fb);
975 if (m_hwaccel) {
976 return;
977 }
978 m_hwaccel = true;
979 }
980 if (hasStarted()) {
981 m_threadContext.core->reloadConfigOption(m_threadContext.core, "hwaccelVideo", NULL);
982 if (!m_hwaccel) {
983 m_threadContext.core->setVideoBuffer(m_threadContext.core, reinterpret_cast<color_t*>(m_activeBuffer.data()), screenDimensions().width());
984 }
985 }
986}
987
988void CoreController::updateKeys() {
989 int activeKeys = m_activeKeys | updateAutofire() | m_inputController->pollEvents();
990 m_threadContext.core->setKeys(m_threadContext.core, activeKeys);
991}
992
993int CoreController::updateAutofire() {
994 int active = 0;
995 for (int k = 0; k < 32; ++k) {
996 if (!m_autofire[k]) {
997 continue;
998 }
999 ++m_autofireStatus[k];
1000 if (m_autofireStatus[k] >= 2 * m_autofireThreshold) {
1001 m_autofireStatus[k] = 0;
1002 } else if (m_autofireStatus[k] >= m_autofireThreshold) {
1003 active |= 1 << k;
1004 }
1005 }
1006 return active;
1007}
1008
1009void CoreController::finishFrame() {
1010 if (!m_hwaccel) {
1011 unsigned width, height;
1012 m_threadContext.core->desiredVideoDimensions(m_threadContext.core, &width, &height);
1013
1014 QMutexLocker locker(&m_bufferMutex);
1015 memcpy(m_completeBuffer.data(), m_activeBuffer.constData(), width * height * BYTES_PER_PIXEL);
1016 }
1017
1018 {
1019 QMutexLocker locker(&m_actionMutex);
1020 QList<std::function<void ()>> frameActions(m_frameActions);
1021 m_frameActions.clear();
1022 for (auto& action : frameActions) {
1023 action();
1024 }
1025 if (m_moreFrames > 0) {
1026 --m_moreFrames;
1027 if (!m_moreFrames) {
1028 mCoreThreadPauseFromThread(&m_threadContext);
1029 }
1030 }
1031 }
1032 updateKeys();
1033
1034 QMetaObject::invokeMethod(this, "frameAvailable");
1035}
1036
1037void CoreController::updateFastForward() {
1038 // If we have "Fast forward" checked in the menu (m_fastForwardForced)
1039 // or are holding the fast forward button (m_fastForward):
1040 if (m_fastForward || m_fastForwardForced) {
1041 if (m_fastForwardVolume >= 0) {
1042 m_threadContext.core->opts.volume = m_fastForwardVolume;
1043 }
1044 if (m_fastForwardMute >= 0) {
1045 m_threadContext.core->opts.mute = m_fastForwardMute;
1046 }
1047
1048 // If we aren't holding the fast forward button
1049 // then use the non "(held)" ratio
1050 if(!m_fastForward) {
1051 if (m_fastForwardRatio > 0) {
1052 m_threadContext.impl->sync.fpsTarget = m_fpsTarget * m_fastForwardRatio;
1053 setSync(true);
1054 } else {
1055 setSync(false);
1056 }
1057 } else {
1058 // If we are holding the fast forward button,
1059 // then use the held ratio
1060 if (m_fastForwardHeldRatio > 0) {
1061 m_threadContext.impl->sync.fpsTarget = m_fpsTarget * m_fastForwardHeldRatio;
1062 setSync(true);
1063 } else {
1064 setSync(false);
1065 }
1066 }
1067 } else {
1068 if (!mCoreConfigGetIntValue(&m_threadContext.core->config, "volume", &m_threadContext.core->opts.volume)) {
1069 m_threadContext.core->opts.volume = 0x100;
1070 }
1071 int fakeBool = 0;
1072 mCoreConfigGetIntValue(&m_threadContext.core->config, "mute", &fakeBool);
1073 m_threadContext.core->opts.mute = fakeBool;
1074 m_threadContext.impl->sync.fpsTarget = m_fpsTarget;
1075 setSync(true);
1076 }
1077
1078 m_threadContext.core->reloadConfigOption(m_threadContext.core, NULL, NULL);
1079}
1080
1081void CoreController::updateROMInfo() {
1082 const NoIntroDB* db = GBAApp::app()->gameDB();
1083 NoIntroGame game{};
1084 m_crc32 = 0;
1085 mCore* core = m_threadContext.core;
1086 core->checksum(core, &m_crc32, mCHECKSUM_CRC32);
1087
1088 char gameTitle[17] = { '\0' };
1089 core->getGameTitle(core, gameTitle);
1090 m_internalTitle = QLatin1String(gameTitle);
1091
1092#ifdef USE_SQLITE3
1093 if (db && m_crc32 && NoIntroDBLookupGameByCRC(db, m_crc32, &game)) {
1094 m_dbTitle = QString::fromUtf8(game.name);
1095 }
1096#endif
1097}
1098
1099CoreController::Interrupter::Interrupter(CoreController* parent)
1100 : m_parent(parent)
1101{
1102 if (!m_parent->thread()->impl) {
1103 return;
1104 }
1105 if (mCoreThreadGet() != m_parent->thread()) {
1106 mCoreThreadInterrupt(m_parent->thread());
1107 } else {
1108 mCoreThreadInterruptFromThread(m_parent->thread());
1109 }
1110}
1111
1112CoreController::Interrupter::Interrupter(std::shared_ptr<CoreController> parent)
1113 : m_parent(parent.get())
1114{
1115 if (!m_parent->thread()->impl) {
1116 return;
1117 }
1118 if (mCoreThreadGet() != m_parent->thread()) {
1119 mCoreThreadInterrupt(m_parent->thread());
1120 } else {
1121 mCoreThreadInterruptFromThread(m_parent->thread());
1122 }
1123}
1124
1125CoreController::Interrupter::Interrupter(const Interrupter& other)
1126 : m_parent(other.m_parent)
1127{
1128 if (!m_parent->thread()->impl) {
1129 return;
1130 }
1131 mCoreThreadInterrupt(m_parent->thread());
1132}
1133
1134CoreController::Interrupter::~Interrupter() {
1135 if (!m_parent->thread()->impl) {
1136 return;
1137 }
1138 mCoreThreadContinue(m_parent->thread());
1139}