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