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