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