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