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