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_saveStateFlags(SAVESTATE_SCREENSHOT | SAVESTATE_SAVEDATA | SAVESTATE_CHEATS | SAVESTATE_RTC)
38 , m_loadStateFlags(SAVESTATE_SCREENSHOT | 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 mCoreLoadForeignConfig(m_threadContext.core, config->config());
269 if (hasStarted()) {
270 updateFastForward();
271 mCoreThreadRewindParamsChanged(&m_threadContext);
272 }
273}
274
275#ifdef USE_DEBUGGERS
276void CoreController::setDebugger(mDebugger* debugger) {
277 Interrupter interrupter(this);
278 if (debugger) {
279 mDebuggerAttach(debugger, m_threadContext.core);
280 mDebuggerEnter(debugger, DEBUGGER_ENTER_ATTACHED, 0);
281 } else {
282 m_threadContext.core->detachDebugger(m_threadContext.core);
283 }
284}
285#endif
286
287void CoreController::setMultiplayerController(MultiplayerController* controller) {
288 if (controller == m_multiplayer) {
289 return;
290 }
291 clearMultiplayerController();
292 m_multiplayer = controller;
293 if (!mCoreThreadHasStarted(&m_threadContext)) {
294 return;
295 }
296 mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* thread) {
297 CoreController* controller = static_cast<CoreController*>(thread->userData);
298 controller->m_multiplayer->attachGame(controller);
299 });
300}
301
302void CoreController::clearMultiplayerController() {
303 if (!m_multiplayer) {
304 return;
305 }
306 m_multiplayer->detachGame(this);
307 m_multiplayer = nullptr;
308}
309
310mCacheSet* CoreController::graphicCaches() {
311 if (m_cacheSet) {
312 return m_cacheSet.get();
313 }
314 Interrupter interrupter(this);
315 switch (platform()) {
316#ifdef M_CORE_GBA
317 case PLATFORM_GBA: {
318 GBA* gba = static_cast<GBA*>(m_threadContext.core->board);
319 m_cacheSet = std::make_unique<mCacheSet>();
320 GBAVideoCacheInit(m_cacheSet.get());
321 GBAVideoCacheAssociate(m_cacheSet.get(), &gba->video);
322 break;
323 }
324#endif
325#ifdef M_CORE_GB
326 case PLATFORM_GB: {
327 GB* gb = static_cast<GB*>(m_threadContext.core->board);
328 m_cacheSet = std::make_unique<mCacheSet>();
329 GBVideoCacheInit(m_cacheSet.get());
330 GBVideoCacheAssociate(m_cacheSet.get(), &gb->video);
331 break;
332 }
333#endif
334 default:
335 return nullptr;
336 }
337 return m_cacheSet.get();
338}
339
340void CoreController::setOverride(std::unique_ptr<Override> override) {
341 Interrupter interrupter(this);
342 m_override = std::move(override);
343 m_override->identify(m_threadContext.core);
344}
345
346void CoreController::setInputController(InputController* inputController) {
347 m_inputController = inputController;
348 m_threadContext.core->setPeripheral(m_threadContext.core, mPERIPH_ROTATION, m_inputController->rotationSource());
349 m_threadContext.core->setPeripheral(m_threadContext.core, mPERIPH_RUMBLE, m_inputController->rumble());
350 m_threadContext.core->setPeripheral(m_threadContext.core, mPERIPH_IMAGE_SOURCE, m_inputController->imageSource());
351}
352
353void CoreController::setLogger(LogController* logger) {
354 disconnect(m_log);
355 m_log = logger;
356 m_threadContext.logger.d.filter = logger->filter();
357 connect(this, &CoreController::logPosted, m_log, &LogController::postLog);
358}
359
360void CoreController::start() {
361 if (!m_hwaccel) {
362 QSize size(256, 224);
363 m_activeBuffer.resize(size.width() * size.height() * sizeof(color_t));
364 m_activeBuffer.fill(0xFF);
365 m_completeBuffer = m_activeBuffer;
366
367 m_threadContext.core->setVideoBuffer(m_threadContext.core, reinterpret_cast<color_t*>(m_activeBuffer.data()), size.width());
368 }
369
370 if (!m_patched) {
371 mCoreAutoloadPatch(m_threadContext.core);
372 }
373 if (!mCoreThreadStart(&m_threadContext)) {
374 emit failed();
375 emit stopping();
376 }
377}
378
379void CoreController::stop() {
380 setSync(false);
381#ifdef USE_DEBUGGERS
382 setDebugger(nullptr);
383#endif
384 setPaused(false);
385 mCoreThreadEnd(&m_threadContext);
386}
387
388void CoreController::reset() {
389 bool wasPaused = isPaused();
390 setPaused(false);
391 Interrupter interrupter(this);
392 mCoreThreadReset(&m_threadContext);
393 if (wasPaused) {
394 setPaused(true);
395 }
396}
397
398void CoreController::setPaused(bool paused) {
399 if (paused == isPaused()) {
400 return;
401 }
402 if (paused) {
403 addFrameAction([this]() {
404 mCoreThreadPauseFromThread(&m_threadContext);
405 });
406 } else {
407 mCoreThreadUnpause(&m_threadContext);
408 }
409}
410
411void CoreController::frameAdvance() {
412 addFrameAction([this]() {
413 mCoreThreadPauseFromThread(&m_threadContext);
414 });
415 setPaused(false);
416}
417
418void CoreController::addFrameAction(std::function<void ()> action) {
419 QMutexLocker locker(&m_actionMutex);
420 m_frameActions.append(action);
421}
422
423void CoreController::setSync(bool sync) {
424 if (sync) {
425 m_threadContext.impl->sync.audioWait = m_audioSync;
426 m_threadContext.impl->sync.videoFrameWait = m_videoSync;
427 } else {
428 m_threadContext.impl->sync.audioWait = false;
429 m_threadContext.impl->sync.videoFrameWait = false;
430 }
431}
432
433void CoreController::setRewinding(bool rewind) {
434 if (!m_threadContext.core->opts.rewindEnable) {
435 return;
436 }
437 if (rewind && m_multiplayer && m_multiplayer->attached() > 1) {
438 return;
439 }
440
441 if (rewind && isPaused()) {
442 setPaused(false);
443 // TODO: restore autopausing
444 }
445 mCoreThreadSetRewinding(&m_threadContext, rewind);
446}
447
448void CoreController::rewind(int states) {
449 {
450 Interrupter interrupter(this);
451 if (!states) {
452 states = INT_MAX;
453 }
454 for (int i = 0; i < states; ++i) {
455 if (!mCoreRewindRestore(&m_threadContext.impl->rewind, m_threadContext.core)) {
456 break;
457 }
458 }
459 }
460 emit frameAvailable();
461 emit rewound();
462}
463
464void CoreController::setFastForward(bool enable) {
465 if (m_fastForward == enable) {
466 return;
467 }
468 m_fastForward = enable;
469 updateFastForward();
470 emit fastForwardChanged(enable);
471}
472
473void CoreController::forceFastForward(bool enable) {
474 if (m_fastForwardForced == enable) {
475 return;
476 }
477 m_fastForwardForced = enable;
478 updateFastForward();
479 emit fastForwardChanged(enable || m_fastForward);
480}
481
482void CoreController::loadState(int slot) {
483 if (slot > 0 && slot != m_stateSlot) {
484 m_stateSlot = slot;
485 m_backupSaveState.clear();
486 }
487 mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
488 CoreController* controller = static_cast<CoreController*>(context->userData);
489 if (!controller->m_backupLoadState.isOpen()) {
490 controller->m_backupLoadState = VFileMemChunk(nullptr, 0);
491 }
492 mCoreSaveStateNamed(context->core, controller->m_backupLoadState, controller->m_saveStateFlags);
493 if (mCoreLoadState(context->core, controller->m_stateSlot, controller->m_loadStateFlags)) {
494 emit controller->frameAvailable();
495 emit controller->stateLoaded();
496 }
497 });
498}
499
500void CoreController::loadState(const QString& path) {
501 m_statePath = path;
502 mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
503 CoreController* controller = static_cast<CoreController*>(context->userData);
504 VFile* vf = VFileDevice::open(controller->m_statePath, O_RDONLY);
505 if (!vf) {
506 return;
507 }
508 if (!controller->m_backupLoadState.isOpen()) {
509 controller->m_backupLoadState = VFileMemChunk(nullptr, 0);
510 }
511 mCoreSaveStateNamed(context->core, controller->m_backupLoadState, controller->m_saveStateFlags);
512 if (mCoreLoadStateNamed(context->core, vf, controller->m_loadStateFlags)) {
513 emit controller->frameAvailable();
514 emit controller->stateLoaded();
515 }
516 vf->close(vf);
517 });
518}
519
520void CoreController::saveState(int slot) {
521 if (slot > 0) {
522 m_stateSlot = slot;
523 }
524 mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
525 CoreController* controller = static_cast<CoreController*>(context->userData);
526 VFile* vf = mCoreGetState(context->core, controller->m_stateSlot, false);
527 if (vf) {
528 controller->m_backupSaveState.resize(vf->size(vf));
529 vf->read(vf, controller->m_backupSaveState.data(), controller->m_backupSaveState.size());
530 vf->close(vf);
531 }
532 mCoreSaveState(context->core, controller->m_stateSlot, controller->m_saveStateFlags);
533 });
534}
535
536void CoreController::saveState(const QString& path) {
537 m_statePath = path;
538 mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
539 CoreController* controller = static_cast<CoreController*>(context->userData);
540 VFile* vf = VFileDevice::open(controller->m_statePath, O_RDONLY);
541 if (vf) {
542 controller->m_backupSaveState.resize(vf->size(vf));
543 vf->read(vf, controller->m_backupSaveState.data(), controller->m_backupSaveState.size());
544 vf->close(vf);
545 }
546 vf = VFileDevice::open(controller->m_statePath, O_WRONLY | O_CREAT | O_TRUNC);
547 if (!vf) {
548 return;
549 }
550 mCoreSaveStateNamed(context->core, vf, controller->m_saveStateFlags);
551 vf->close(vf);
552 });
553}
554
555void CoreController::loadBackupState() {
556 if (!m_backupLoadState.isOpen()) {
557 return;
558 }
559
560 mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
561 CoreController* controller = static_cast<CoreController*>(context->userData);
562 controller->m_backupLoadState.seek(0);
563 if (mCoreLoadStateNamed(context->core, controller->m_backupLoadState, controller->m_loadStateFlags)) {
564 mLOG(STATUS, INFO, "Undid state load");
565 controller->frameAvailable();
566 controller->stateLoaded();
567 }
568 controller->m_backupLoadState.close();
569 });
570}
571
572void CoreController::saveBackupState() {
573 if (m_backupSaveState.isEmpty()) {
574 return;
575 }
576
577 mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
578 CoreController* controller = static_cast<CoreController*>(context->userData);
579 VFile* vf = mCoreGetState(context->core, controller->m_stateSlot, true);
580 if (vf) {
581 vf->write(vf, controller->m_backupSaveState.constData(), controller->m_backupSaveState.size());
582 vf->close(vf);
583 mLOG(STATUS, INFO, "Undid state save");
584 }
585 controller->m_backupSaveState.clear();
586 });
587}
588
589void CoreController::loadSave(const QString& path, bool temporary) {
590 m_resetActions.append([this, path, temporary]() {
591 VFile* vf = VFileDevice::open(path, temporary ? O_RDONLY : O_RDWR);
592 if (!vf) {
593 LOG(QT, ERROR) << tr("Failed to open save file: %1").arg(path);
594 return;
595 }
596
597 if (temporary) {
598 m_threadContext.core->loadTemporarySave(m_threadContext.core, vf);
599 } else {
600 m_threadContext.core->loadSave(m_threadContext.core, vf);
601 }
602 });
603 reset();
604}
605
606void CoreController::loadPatch(const QString& patchPath) {
607 Interrupter interrupter(this);
608 VFile* patch = VFileDevice::open(patchPath, O_RDONLY);
609 if (patch) {
610 m_threadContext.core->loadPatch(m_threadContext.core, patch);
611 m_patched = true;
612 patch->close(patch);
613 }
614 if (mCoreThreadHasStarted(&m_threadContext)) {
615 reset();
616 }
617}
618
619void CoreController::replaceGame(const QString& path) {
620 QFileInfo info(path);
621 if (!info.isReadable()) {
622 LOG(QT, ERROR) << tr("Failed to open game file: %1").arg(path);
623 return;
624 }
625 QString fname = info.canonicalFilePath();
626 Interrupter interrupter(this);
627 mDirectorySetDetachBase(&m_threadContext.core->dirs);
628 mCoreLoadFile(m_threadContext.core, fname.toUtf8().constData());
629}
630
631void CoreController::yankPak() {
632 Interrupter interrupter(this);
633
634 switch (platform()) {
635 case PLATFORM_GBA:
636 GBAYankROM(static_cast<GBA*>(m_threadContext.core->board));
637 break;
638 case PLATFORM_GB:
639 GBYankROM(static_cast<GB*>(m_threadContext.core->board));
640 break;
641 }
642}
643
644void CoreController::addKey(int key) {
645 m_activeKeys |= 1 << key;
646}
647
648void CoreController::clearKey(int key) {
649 m_activeKeys &= ~(1 << key);
650}
651
652void CoreController::setAutofire(int key, bool enable) {
653 if (key >= 32 || key < 0) {
654 return;
655 }
656
657 m_autofire[key] = enable;
658 m_autofireStatus[key] = 0;
659}
660
661#ifdef USE_PNG
662void CoreController::screenshot() {
663 mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
664 mCoreTakeScreenshot(context->core);
665 });
666}
667#endif
668
669void CoreController::setRealTime() {
670 m_threadContext.core->rtc.override = RTC_NO_OVERRIDE;
671}
672
673void CoreController::setFixedTime(const QDateTime& time) {
674 m_threadContext.core->rtc.override = RTC_FIXED;
675 m_threadContext.core->rtc.value = time.toMSecsSinceEpoch();
676}
677
678void CoreController::setFakeEpoch(const QDateTime& time) {
679 m_threadContext.core->rtc.override = RTC_FAKE_EPOCH;
680 m_threadContext.core->rtc.value = time.toMSecsSinceEpoch();
681}
682
683void CoreController::importSharkport(const QString& path) {
684#ifdef M_CORE_GBA
685 if (platform() != PLATFORM_GBA) {
686 return;
687 }
688 VFile* vf = VFileDevice::open(path, O_RDONLY);
689 if (!vf) {
690 LOG(QT, ERROR) << tr("Failed to open snapshot file for reading: %1").arg(path);
691 return;
692 }
693 Interrupter interrupter(this);
694 GBASavedataImportSharkPort(static_cast<GBA*>(m_threadContext.core->board), vf, false);
695 vf->close(vf);
696#endif
697}
698
699void CoreController::exportSharkport(const QString& path) {
700#ifdef M_CORE_GBA
701 if (platform() != PLATFORM_GBA) {
702 return;
703 }
704 VFile* vf = VFileDevice::open(path, O_WRONLY | O_CREAT | O_TRUNC);
705 if (!vf) {
706 LOG(QT, ERROR) << tr("Failed to open snapshot file for writing: %1").arg(path);
707 return;
708 }
709 Interrupter interrupter(this);
710 GBASavedataExportSharkPort(static_cast<GBA*>(m_threadContext.core->board), vf);
711 vf->close(vf);
712#endif
713}
714
715#ifdef M_CORE_GB
716void CoreController::attachPrinter() {
717 if (platform() != PLATFORM_GB) {
718 return;
719 }
720 GB* gb = static_cast<GB*>(m_threadContext.core->board);
721 clearMultiplayerController();
722 GBPrinterCreate(&m_printer.d);
723 m_printer.parent = this;
724 m_printer.d.print = [](GBPrinter* printer, int height, const uint8_t* data) {
725 QGBPrinter* qPrinter = reinterpret_cast<QGBPrinter*>(printer);
726 QImage image(GB_VIDEO_HORIZONTAL_PIXELS, height, QImage::Format_Indexed8);
727 QVector<QRgb> colors;
728 colors.append(qRgb(0xF8, 0xF8, 0xF8));
729 colors.append(qRgb(0xA8, 0xA8, 0xA8));
730 colors.append(qRgb(0x50, 0x50, 0x50));
731 colors.append(qRgb(0x00, 0x00, 0x00));
732 image.setColorTable(colors);
733 for (int y = 0; y < height; ++y) {
734 for (int x = 0; x < GB_VIDEO_HORIZONTAL_PIXELS; x += 4) {
735 uint8_t byte = data[(x + y * GB_VIDEO_HORIZONTAL_PIXELS) / 4];
736 image.setPixel(x + 0, y, (byte & 0xC0) >> 6);
737 image.setPixel(x + 1, y, (byte & 0x30) >> 4);
738 image.setPixel(x + 2, y, (byte & 0x0C) >> 2);
739 image.setPixel(x + 3, y, (byte & 0x03) >> 0);
740 }
741 }
742 QMetaObject::invokeMethod(qPrinter->parent, "imagePrinted", Q_ARG(const QImage&, image));
743 };
744 Interrupter interrupter(this);
745 GBSIOSetDriver(&gb->sio, &m_printer.d.d);
746}
747
748void CoreController::detachPrinter() {
749 if (platform() != PLATFORM_GB) {
750 return;
751 }
752 Interrupter interrupter(this);
753 GB* gb = static_cast<GB*>(m_threadContext.core->board);
754 GBPrinterDonePrinting(&m_printer.d);
755 GBSIOSetDriver(&gb->sio, nullptr);
756}
757
758void CoreController::endPrint() {
759 if (platform() != PLATFORM_GB) {
760 return;
761 }
762 Interrupter interrupter(this);
763 GBPrinterDonePrinting(&m_printer.d);
764}
765#endif
766
767#ifdef M_CORE_GBA
768void CoreController::attachBattleChipGate() {
769 if (platform() != PLATFORM_GBA) {
770 return;
771 }
772 Interrupter interrupter(this);
773 clearMultiplayerController();
774 GBASIOBattlechipGateCreate(&m_battlechip);
775 m_threadContext.core->setPeripheral(m_threadContext.core, mPERIPH_GBA_BATTLECHIP_GATE, &m_battlechip);
776}
777
778void CoreController::detachBattleChipGate() {
779 if (platform() != PLATFORM_GBA) {
780 return;
781 }
782 Interrupter interrupter(this);
783 m_threadContext.core->setPeripheral(m_threadContext.core, mPERIPH_GBA_BATTLECHIP_GATE, nullptr);
784}
785
786void CoreController::setBattleChipId(uint16_t id) {
787 if (platform() != PLATFORM_GBA) {
788 return;
789 }
790 Interrupter interrupter(this);
791 m_battlechip.chipId = id;
792}
793
794void CoreController::setBattleChipFlavor(int flavor) {
795 if (platform() != PLATFORM_GBA) {
796 return;
797 }
798 Interrupter interrupter(this);
799 m_battlechip.flavor = flavor;
800}
801#endif
802
803void CoreController::setAVStream(mAVStream* stream) {
804 Interrupter interrupter(this);
805 m_threadContext.core->setAVStream(m_threadContext.core, stream);
806}
807
808void CoreController::clearAVStream() {
809 Interrupter interrupter(this);
810 m_threadContext.core->setAVStream(m_threadContext.core, nullptr);
811}
812
813void CoreController::clearOverride() {
814 m_override.reset();
815}
816
817void CoreController::startVideoLog(const QString& path, bool compression) {
818 if (m_vl) {
819 return;
820 }
821
822 VFile* vf = VFileDevice::open(path, O_WRONLY | O_CREAT | O_TRUNC);
823 if (!vf) {
824 return;
825 }
826 startVideoLog(vf);
827}
828
829void CoreController::startVideoLog(VFile* vf, bool compression) {
830 if (m_vl || !vf) {
831 return;
832 }
833
834 Interrupter interrupter(this);
835 m_vl = mVideoLogContextCreate(m_threadContext.core);
836 m_vlVf = vf;
837 mVideoLogContextSetOutput(m_vl, m_vlVf);
838 mVideoLogContextSetCompression(m_vl, compression);
839 mVideoLogContextWriteHeader(m_vl, m_threadContext.core);
840}
841
842void CoreController::endVideoLog(bool closeVf) {
843 if (!m_vl) {
844 return;
845 }
846
847 Interrupter interrupter(this);
848 mVideoLogContextDestroy(m_threadContext.core, m_vl);
849 if (m_vlVf && closeVf) {
850 m_vlVf->close(m_vlVf);
851 m_vlVf = nullptr;
852 }
853 m_vl = nullptr;
854}
855
856void CoreController::setFramebufferHandle(int fb) {
857 Interrupter interrupter(this);
858 if (fb < 0) {
859 m_hwaccel = false;
860 } else {
861 m_threadContext.core->setVideoGLTex(m_threadContext.core, fb);
862 m_hwaccel = true;
863 }
864}
865
866void CoreController::updateKeys() {
867 int activeKeys = m_activeKeys | updateAutofire() | m_inputController->pollEvents();
868 m_threadContext.core->setKeys(m_threadContext.core, activeKeys);
869}
870
871int CoreController::updateAutofire() {
872 int active = 0;
873 for (int k = 0; k < 32; ++k) {
874 if (!m_autofire[k]) {
875 continue;
876 }
877 ++m_autofireStatus[k];
878 if (m_autofireStatus[k] >= 2 * m_autofireThreshold) {
879 m_autofireStatus[k] = 0;
880 } else if (m_autofireStatus[k] >= m_autofireThreshold) {
881 active |= 1 << k;
882 }
883 }
884 return active;
885}
886
887void CoreController::finishFrame() {
888 if (!m_hwaccel) {
889 unsigned width, height;
890 m_threadContext.core->desiredVideoDimensions(m_threadContext.core, &width, &height);
891
892 QMutexLocker locker(&m_bufferMutex);
893 memcpy(m_completeBuffer.data(), m_activeBuffer.constData(), 256 * height * BYTES_PER_PIXEL);
894 }
895
896 QMutexLocker locker(&m_actionMutex);
897 QList<std::function<void ()>> frameActions(m_frameActions);
898 m_frameActions.clear();
899 for (auto& action : frameActions) {
900 action();
901 }
902 updateKeys();
903
904 QMetaObject::invokeMethod(this, "frameAvailable");
905}
906
907void CoreController::updateFastForward() {
908 // If we have "Fast forward" checked in the menu (m_fastForwardForced)
909 // or are holding the fast forward button (m_fastForward):
910 if (m_fastForward || m_fastForwardForced) {
911 if (m_fastForwardVolume >= 0) {
912 m_threadContext.core->opts.volume = m_fastForwardVolume;
913 }
914 if (m_fastForwardMute >= 0) {
915 m_threadContext.core->opts.mute = m_fastForwardMute;
916 }
917
918 // If we aren't holding the fast forward button
919 // then use the non "(held)" ratio
920 if(!m_fastForward) {
921 if (m_fastForwardRatio > 0) {
922 m_threadContext.impl->sync.fpsTarget = m_fpsTarget * m_fastForwardRatio;
923 setSync(true);
924 } else {
925 setSync(false);
926 }
927 } else {
928 // If we are holding the fast forward button,
929 // then use the held ratio
930 if (m_fastForwardHeldRatio > 0) {
931 m_threadContext.impl->sync.fpsTarget = m_fpsTarget * m_fastForwardHeldRatio;
932 setSync(true);
933 } else {
934 setSync(false);
935 }
936 }
937 } else {
938 if (!mCoreConfigGetIntValue(&m_threadContext.core->config, "volume", &m_threadContext.core->opts.volume)) {
939 m_threadContext.core->opts.volume = 0x100;
940 }
941 int fakeBool = 0;
942 mCoreConfigGetIntValue(&m_threadContext.core->config, "mute", &fakeBool);
943 m_threadContext.core->opts.mute = fakeBool;
944 m_threadContext.impl->sync.fpsTarget = m_fpsTarget;
945 setSync(true);
946 }
947
948 m_threadContext.core->reloadConfigOption(m_threadContext.core, NULL, NULL);
949}
950
951CoreController::Interrupter::Interrupter(CoreController* parent, bool fromThread)
952 : m_parent(parent)
953{
954 if (!m_parent->thread()->impl) {
955 return;
956 }
957 if (!fromThread) {
958 mCoreThreadInterrupt(m_parent->thread());
959 } else {
960 mCoreThreadInterruptFromThread(m_parent->thread());
961 }
962}
963
964CoreController::Interrupter::Interrupter(std::shared_ptr<CoreController> parent, bool fromThread)
965 : m_parent(parent.get())
966{
967 if (!m_parent->thread()->impl) {
968 return;
969 }
970 if (!fromThread) {
971 mCoreThreadInterrupt(m_parent->thread());
972 } else {
973 mCoreThreadInterruptFromThread(m_parent->thread());
974 }
975}
976
977CoreController::Interrupter::Interrupter(const Interrupter& other)
978 : m_parent(other.m_parent)
979{
980 if (!m_parent->thread()->impl) {
981 return;
982 }
983 mCoreThreadInterrupt(m_parent->thread());
984}
985
986CoreController::Interrupter::~Interrupter() {
987 if (!m_parent->thread()->impl) {
988 return;
989 }
990 mCoreThreadContinue(m_parent->thread());
991}