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