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 QSize size(256, 512);
44 m_buffers[0].resize(size.width() * size.height() * sizeof(color_t));
45 m_buffers[1].resize(size.width() * size.height() * sizeof(color_t));
46 m_buffers[0].fill(0xFF);
47 m_buffers[1].fill(0xFF);
48 m_activeBuffer = &m_buffers[0];
49 m_completeBuffer = m_buffers[0];
50
51 m_threadContext.core->setVideoBuffer(m_threadContext.core, reinterpret_cast<color_t*>(m_activeBuffer->data()), size.width());
52
53 m_resetActions.append([this]() {
54 if (m_autoload) {
55 mCoreLoadState(m_threadContext.core, 0, m_loadStateFlags);
56 }
57 });
58
59 m_threadContext.startCallback = [](mCoreThread* context) {
60 CoreController* controller = static_cast<CoreController*>(context->userData);
61
62 switch (context->core->platform(context->core)) {
63#ifdef M_CORE_GBA
64 case PLATFORM_GBA:
65 context->core->setPeripheral(context->core, mPERIPH_GBA_LUMINANCE, controller->m_inputController->luminance());
66 break;
67#endif
68 default:
69 break;
70 }
71
72 controller->updateFastForward();
73
74 if (controller->m_multiplayer) {
75 controller->m_multiplayer->attachGame(controller);
76 }
77
78 QMetaObject::invokeMethod(controller, "started");
79 };
80
81 m_threadContext.resetCallback = [](mCoreThread* context) {
82 CoreController* controller = static_cast<CoreController*>(context->userData);
83 for (auto action : controller->m_resetActions) {
84 action();
85 }
86
87 if (controller->m_override) {
88 controller->m_override->identify(context->core);
89 controller->m_override->apply(context->core);
90 }
91
92 controller->m_resetActions.clear();
93
94 controller->m_activeBuffer = &controller->m_buffers[0];
95 context->core->setVideoBuffer(context->core, reinterpret_cast<color_t*>(controller->m_activeBuffer->data()), controller->screenDimensions().width());
96
97 controller->finishFrame();
98 };
99
100 m_threadContext.frameCallback = [](mCoreThread* context) {
101 CoreController* controller = static_cast<CoreController*>(context->userData);
102
103 if (controller->m_autosaveCounter == AUTOSAVE_GRANULARITY) {
104 if (controller->m_autosave) {
105 mCoreSaveState(context->core, 0, controller->m_saveStateFlags);
106 }
107 controller->m_autosaveCounter = 0;
108 }
109 ++controller->m_autosaveCounter;
110
111 controller->finishFrame();
112 };
113
114 m_threadContext.cleanCallback = [](mCoreThread* context) {
115 CoreController* controller = static_cast<CoreController*>(context->userData);
116
117 if (controller->m_autosave) {
118 mCoreSaveState(context->core, 0, controller->m_saveStateFlags);
119 }
120
121 controller->clearMultiplayerController();
122 QMetaObject::invokeMethod(controller, "stopping");
123 };
124
125 m_threadContext.pauseCallback = [](mCoreThread* context) {
126 CoreController* controller = static_cast<CoreController*>(context->userData);
127
128 QMetaObject::invokeMethod(controller, "paused");
129 };
130
131 m_threadContext.unpauseCallback = [](mCoreThread* context) {
132 CoreController* controller = static_cast<CoreController*>(context->userData);
133
134 QMetaObject::invokeMethod(controller, "unpaused");
135 };
136
137 m_threadContext.logger.d.log = [](mLogger* logger, int category, enum mLogLevel level, const char* format, va_list args) {
138 mThreadLogger* logContext = reinterpret_cast<mThreadLogger*>(logger);
139 mCoreThread* context = logContext->p;
140
141 static const char* savestateMessage = "State %i saved";
142 static const char* loadstateMessage = "State %i loaded";
143 static const char* savestateFailedMessage = "State %i failed to load";
144 static int biosCat = -1;
145 static int statusCat = -1;
146 if (!context) {
147 return;
148 }
149 CoreController* controller = static_cast<CoreController*>(context->userData);
150 QString message;
151 if (biosCat < 0) {
152 biosCat = mLogCategoryById("gba.bios");
153 }
154 if (statusCat < 0) {
155 statusCat = mLogCategoryById("core.status");
156 }
157#ifdef M_CORE_GBA
158 if (level == mLOG_STUB && category == biosCat) {
159 va_list argc;
160 va_copy(argc, args);
161 int immediate = va_arg(argc, int);
162 va_end(argc);
163 QMetaObject::invokeMethod(controller, "unimplementedBiosCall", Q_ARG(int, immediate));
164 } else
165#endif
166 if (category == statusCat) {
167 // Slot 0 is reserved for suspend points
168 if (strncmp(loadstateMessage, format, strlen(loadstateMessage)) == 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 format = "Loaded suspend state";
175 }
176 } else if (strncmp(savestateFailedMessage, format, strlen(savestateFailedMessage)) == 0 || strncmp(savestateMessage, format, strlen(savestateMessage)) == 0) {
177 va_list argc;
178 va_copy(argc, args);
179 int slot = va_arg(argc, int);
180 va_end(argc);
181 if (slot == 0) {
182 return;
183 }
184 }
185 message = QString().vsprintf(format, args);
186 QMetaObject::invokeMethod(controller, "statusPosted", Q_ARG(const QString&, message));
187 }
188 message = QString().vsprintf(format, args);
189 QMetaObject::invokeMethod(controller, "logPosted", Q_ARG(int, level), Q_ARG(int, category), Q_ARG(const QString&, message));
190 if (level == mLOG_FATAL) {
191 QMetaObject::invokeMethod(controller, "crashed", Q_ARG(const QString&, QString().vsprintf(format, args)));
192 }
193 };
194}
195
196CoreController::~CoreController() {
197 endVideoLog();
198 stop();
199 disconnect();
200
201 mCoreThreadJoin(&m_threadContext);
202
203 if (m_cacheSet) {
204 mCacheSetDeinit(m_cacheSet.get());
205 m_cacheSet.reset();
206 }
207
208 mCoreConfigDeinit(&m_threadContext.core->config);
209 m_threadContext.core->deinit(m_threadContext.core);
210}
211
212const color_t* CoreController::drawContext() {
213 QMutexLocker locker(&m_mutex);
214 return reinterpret_cast<const color_t*>(m_completeBuffer.constData());
215}
216
217bool CoreController::isPaused() {
218 return mCoreThreadIsPaused(&m_threadContext);
219}
220
221bool CoreController::hasStarted() {
222 return mCoreThreadHasStarted(&m_threadContext);
223}
224
225mPlatform CoreController::platform() const {
226 return m_threadContext.core->platform(m_threadContext.core);
227}
228
229QSize CoreController::screenDimensions() const {
230 unsigned width, height;
231 m_threadContext.core->desiredVideoDimensions(m_threadContext.core, &width, &height);
232
233 return QSize(width, height);
234}
235
236void CoreController::loadConfig(ConfigController* config) {
237 Interrupter interrupter(this);
238 m_loadStateFlags = config->getOption("loadStateExtdata", m_loadStateFlags).toInt();
239 m_saveStateFlags = config->getOption("saveStateExtdata", m_saveStateFlags).toInt();
240 m_fastForwardRatio = config->getOption("fastForwardRatio", m_fastForwardRatio).toFloat();
241 m_videoSync = config->getOption("videoSync", m_videoSync).toInt();
242 m_audioSync = config->getOption("audioSync", m_audioSync).toInt();
243 m_fpsTarget = config->getOption("fpsTarget").toFloat();
244 m_autosave = config->getOption("autosave", false).toInt();
245 m_autoload = config->getOption("autoload", true).toInt();
246 m_autofireThreshold = config->getOption("autofireThreshold", m_autofireThreshold).toInt();
247 m_fastForwardVolume = config->getOption("fastForwardVolume", -1).toInt();
248 m_fastForwardMute = config->getOption("fastForwardMute", -1).toInt();
249 mCoreConfigCopyValue(&m_threadContext.core->config, config->config(), "volume");
250 mCoreConfigCopyValue(&m_threadContext.core->config, config->config(), "mute");
251 mCoreLoadForeignConfig(m_threadContext.core, config->config());
252 if (hasStarted()) {
253 updateFastForward();
254 mCoreThreadRewindParamsChanged(&m_threadContext);
255 }
256}
257
258#ifdef USE_DEBUGGERS
259void CoreController::setDebugger(mDebugger* debugger) {
260 Interrupter interrupter(this);
261 if (debugger) {
262 mDebuggerAttach(debugger, m_threadContext.core);
263 } else {
264 m_threadContext.core->detachDebugger(m_threadContext.core);
265 }
266}
267#endif
268
269void CoreController::setMultiplayerController(MultiplayerController* controller) {
270 if (controller == m_multiplayer) {
271 return;
272 }
273 clearMultiplayerController();
274 m_multiplayer = controller;
275 if (!mCoreThreadHasStarted(&m_threadContext)) {
276 return;
277 }
278 mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* thread) {
279 CoreController* controller = static_cast<CoreController*>(thread->userData);
280 controller->m_multiplayer->attachGame(controller);
281 });
282}
283
284void CoreController::clearMultiplayerController() {
285 if (!m_multiplayer) {
286 return;
287 }
288 m_multiplayer->detachGame(this);
289 m_multiplayer = nullptr;
290}
291
292mCacheSet* CoreController::graphicCaches() {
293 if (m_cacheSet) {
294 return m_cacheSet.get();
295 }
296 Interrupter interrupter(this);
297 switch (platform()) {
298#ifdef M_CORE_GBA
299 case PLATFORM_GBA: {
300 GBA* gba = static_cast<GBA*>(m_threadContext.core->board);
301 m_cacheSet = std::make_unique<mCacheSet>();
302 GBAVideoCacheInit(m_cacheSet.get());
303 GBAVideoCacheAssociate(m_cacheSet.get(), &gba->video);
304 break;
305 }
306#endif
307#ifdef M_CORE_GB
308 case PLATFORM_GB: {
309 GB* gb = static_cast<GB*>(m_threadContext.core->board);
310 m_cacheSet = std::make_unique<mCacheSet>();
311 GBVideoCacheInit(m_cacheSet.get());
312 GBVideoCacheAssociate(m_cacheSet.get(), &gb->video);
313 break;
314 }
315#endif
316 default:
317 return nullptr;
318 }
319 return m_cacheSet.get();
320}
321
322void CoreController::setOverride(std::unique_ptr<Override> override) {
323 Interrupter interrupter(this);
324 m_override = std::move(override);
325 m_override->identify(m_threadContext.core);
326}
327
328void CoreController::setInputController(InputController* inputController) {
329 m_inputController = inputController;
330 m_threadContext.core->setPeripheral(m_threadContext.core, mPERIPH_ROTATION, m_inputController->rotationSource());
331 m_threadContext.core->setPeripheral(m_threadContext.core, mPERIPH_RUMBLE, m_inputController->rumble());
332 m_threadContext.core->setPeripheral(m_threadContext.core, mPERIPH_IMAGE_SOURCE, m_inputController->imageSource());
333}
334
335void CoreController::setLogger(LogController* logger) {
336 disconnect(m_log);
337 m_log = logger;
338 m_threadContext.logger.d.filter = logger->filter();
339 connect(this, &CoreController::logPosted, m_log, &LogController::postLog);
340}
341
342void CoreController::start() {
343 if (!m_patched) {
344 mCoreAutoloadPatch(m_threadContext.core);
345 }
346 if (!mCoreThreadStart(&m_threadContext)) {
347 emit failed();
348 emit stopping();
349 }
350}
351
352void CoreController::stop() {
353 setSync(false);
354#ifdef USE_DEBUGGERS
355 setDebugger(nullptr);
356#endif
357 setPaused(false);
358 mCoreThreadEnd(&m_threadContext);
359 emit stopping();
360}
361
362void CoreController::reset() {
363 bool wasPaused = isPaused();
364 setPaused(false);
365 Interrupter interrupter(this);
366 mCoreThreadReset(&m_threadContext);
367 if (wasPaused) {
368 setPaused(true);
369 }
370}
371
372void CoreController::setPaused(bool paused) {
373 if (paused == isPaused()) {
374 return;
375 }
376 if (paused) {
377 QMutexLocker locker(&m_mutex);
378 m_frameActions.append([this]() {
379 mCoreThreadPauseFromThread(&m_threadContext);
380 });
381 } else {
382 mCoreThreadUnpause(&m_threadContext);
383 }
384}
385
386void CoreController::frameAdvance() {
387 QMutexLocker locker(&m_mutex);
388 m_frameActions.append([this]() {
389 mCoreThreadPauseFromThread(&m_threadContext);
390 });
391 setPaused(false);
392}
393
394void CoreController::setSync(bool sync) {
395 if (sync) {
396 m_threadContext.impl->sync.audioWait = m_audioSync;
397 m_threadContext.impl->sync.videoFrameWait = m_videoSync;
398 } else {
399 m_threadContext.impl->sync.audioWait = false;
400 m_threadContext.impl->sync.videoFrameWait = false;
401 }
402}
403
404void CoreController::setRewinding(bool rewind) {
405 if (!m_threadContext.core->opts.rewindEnable) {
406 return;
407 }
408 if (rewind && m_multiplayer && m_multiplayer->attached() > 1) {
409 return;
410 }
411
412 if (rewind && isPaused()) {
413 setPaused(false);
414 // TODO: restore autopausing
415 }
416 mCoreThreadSetRewinding(&m_threadContext, rewind);
417}
418
419void CoreController::rewind(int states) {
420 {
421 Interrupter interrupter(this);
422 if (!states) {
423 states = INT_MAX;
424 }
425 for (int i = 0; i < states; ++i) {
426 if (!mCoreRewindRestore(&m_threadContext.impl->rewind, m_threadContext.core)) {
427 break;
428 }
429 }
430 }
431 emit frameAvailable();
432 emit rewound();
433}
434
435void CoreController::setFastForward(bool enable) {
436 m_fastForward = enable;
437 updateFastForward();
438}
439
440void CoreController::forceFastForward(bool enable) {
441 m_fastForwardForced = enable;
442 updateFastForward();
443}
444
445void CoreController::loadState(int slot) {
446 if (slot > 0 && slot != m_stateSlot) {
447 m_stateSlot = slot;
448 m_backupSaveState.clear();
449 }
450 mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
451 CoreController* controller = static_cast<CoreController*>(context->userData);
452 if (!controller->m_backupLoadState.isOpen()) {
453 controller->m_backupLoadState = VFileMemChunk(nullptr, 0);
454 }
455 mCoreSaveStateNamed(context->core, controller->m_backupLoadState, controller->m_saveStateFlags);
456 if (mCoreLoadState(context->core, controller->m_stateSlot, controller->m_loadStateFlags)) {
457 emit controller->frameAvailable();
458 emit controller->stateLoaded();
459 }
460 });
461}
462
463void CoreController::loadState(const QString& path) {
464 m_statePath = path;
465 mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
466 CoreController* controller = static_cast<CoreController*>(context->userData);
467 VFile* vf = VFileDevice::open(controller->m_statePath, O_RDONLY);
468 if (!vf) {
469 return;
470 }
471 if (!controller->m_backupLoadState.isOpen()) {
472 controller->m_backupLoadState = VFileMemChunk(nullptr, 0);
473 }
474 mCoreSaveStateNamed(context->core, controller->m_backupLoadState, controller->m_saveStateFlags);
475 if (mCoreLoadStateNamed(context->core, vf, controller->m_loadStateFlags)) {
476 emit controller->frameAvailable();
477 emit controller->stateLoaded();
478 }
479 vf->close(vf);
480 });
481}
482
483void CoreController::saveState(int slot) {
484 if (slot > 0) {
485 m_stateSlot = slot;
486 }
487 mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
488 CoreController* controller = static_cast<CoreController*>(context->userData);
489 VFile* vf = mCoreGetState(context->core, controller->m_stateSlot, false);
490 if (vf) {
491 controller->m_backupSaveState.resize(vf->size(vf));
492 vf->read(vf, controller->m_backupSaveState.data(), controller->m_backupSaveState.size());
493 vf->close(vf);
494 }
495 mCoreSaveState(context->core, controller->m_stateSlot, controller->m_saveStateFlags);
496 });
497}
498
499void CoreController::saveState(const QString& path) {
500 m_statePath = path;
501 mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
502 CoreController* controller = static_cast<CoreController*>(context->userData);
503 VFile* vf = VFileDevice::open(controller->m_statePath, O_RDONLY);
504 if (vf) {
505 controller->m_backupSaveState.resize(vf->size(vf));
506 vf->read(vf, controller->m_backupSaveState.data(), controller->m_backupSaveState.size());
507 vf->close(vf);
508 }
509 vf = VFileDevice::open(controller->m_statePath, O_WRONLY | O_CREAT | O_TRUNC);
510 if (!vf) {
511 return;
512 }
513 mCoreSaveStateNamed(context->core, vf, controller->m_saveStateFlags);
514 vf->close(vf);
515 });
516}
517
518void CoreController::loadBackupState() {
519 if (!m_backupLoadState.isOpen()) {
520 return;
521 }
522
523 mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
524 CoreController* controller = static_cast<CoreController*>(context->userData);
525 controller->m_backupLoadState.seek(0);
526 if (mCoreLoadStateNamed(context->core, controller->m_backupLoadState, controller->m_loadStateFlags)) {
527 mLOG(STATUS, INFO, "Undid state load");
528 controller->frameAvailable();
529 controller->stateLoaded();
530 }
531 controller->m_backupLoadState.close();
532 });
533}
534
535void CoreController::saveBackupState() {
536 if (m_backupSaveState.isEmpty()) {
537 return;
538 }
539
540 mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
541 CoreController* controller = static_cast<CoreController*>(context->userData);
542 VFile* vf = mCoreGetState(context->core, controller->m_stateSlot, true);
543 if (vf) {
544 vf->write(vf, controller->m_backupSaveState.constData(), controller->m_backupSaveState.size());
545 vf->close(vf);
546 mLOG(STATUS, INFO, "Undid state save");
547 }
548 controller->m_backupSaveState.clear();
549 });
550}
551
552void CoreController::loadSave(const QString& path, bool temporary) {
553 m_resetActions.append([this, path, temporary]() {
554 VFile* vf = VFileDevice::open(path, temporary ? O_RDONLY : O_RDWR);
555 if (!vf) {
556 LOG(QT, ERROR) << tr("Failed to open save file: %1").arg(path);
557 return;
558 }
559
560 if (temporary) {
561 m_threadContext.core->loadTemporarySave(m_threadContext.core, vf);
562 } else {
563 m_threadContext.core->loadSave(m_threadContext.core, vf);
564 }
565 });
566 reset();
567}
568
569void CoreController::loadPatch(const QString& patchPath) {
570 Interrupter interrupter(this);
571 VFile* patch = VFileDevice::open(patchPath, O_RDONLY);
572 if (patch) {
573 m_threadContext.core->loadPatch(m_threadContext.core, patch);
574 m_patched = true;
575 patch->close(patch);
576 }
577 if (mCoreThreadHasStarted(&m_threadContext)) {
578 reset();
579 }
580}
581
582void CoreController::replaceGame(const QString& path) {
583 QFileInfo info(path);
584 if (!info.isReadable()) {
585 LOG(QT, ERROR) << tr("Failed to open game file: %1").arg(path);
586 return;
587 }
588 QString fname = info.canonicalFilePath();
589 Interrupter interrupter(this);
590 mDirectorySetDetachBase(&m_threadContext.core->dirs);
591 mCoreLoadFile(m_threadContext.core, fname.toUtf8().constData());
592}
593
594void CoreController::yankPak() {
595#ifdef M_CORE_GBA
596 if (platform() != PLATFORM_GBA) {
597 return;
598 }
599 Interrupter interrupter(this);
600 GBAYankROM(static_cast<GBA*>(m_threadContext.core->board));
601#endif
602}
603
604void CoreController::addKey(int key) {
605 m_activeKeys |= 1 << key;
606}
607
608void CoreController::clearKey(int key) {
609 m_activeKeys &= ~(1 << key);
610}
611
612void CoreController::setAutofire(int key, bool enable) {
613 if (key >= 32 || key < 0) {
614 return;
615 }
616
617 m_autofire[key] = enable;
618 m_autofireStatus[key] = 0;
619}
620
621#ifdef USE_PNG
622void CoreController::screenshot() {
623 mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
624 mCoreTakeScreenshot(context->core);
625 });
626}
627#endif
628
629void CoreController::setRealTime() {
630 m_threadContext.core->rtc.override = RTC_NO_OVERRIDE;
631}
632
633void CoreController::setFixedTime(const QDateTime& time) {
634 m_threadContext.core->rtc.override = RTC_FIXED;
635 m_threadContext.core->rtc.value = time.toMSecsSinceEpoch();
636}
637
638void CoreController::setFakeEpoch(const QDateTime& time) {
639 m_threadContext.core->rtc.override = RTC_FAKE_EPOCH;
640 m_threadContext.core->rtc.value = time.toMSecsSinceEpoch();
641}
642
643void CoreController::importSharkport(const QString& path) {
644#ifdef M_CORE_GBA
645 if (platform() != PLATFORM_GBA) {
646 return;
647 }
648 VFile* vf = VFileDevice::open(path, O_RDONLY);
649 if (!vf) {
650 LOG(QT, ERROR) << tr("Failed to open snapshot file for reading: %1").arg(path);
651 return;
652 }
653 Interrupter interrupter(this);
654 GBASavedataImportSharkPort(static_cast<GBA*>(m_threadContext.core->board), vf, false);
655 vf->close(vf);
656#endif
657}
658
659void CoreController::exportSharkport(const QString& path) {
660#ifdef M_CORE_GBA
661 if (platform() != PLATFORM_GBA) {
662 return;
663 }
664 VFile* vf = VFileDevice::open(path, O_WRONLY | O_CREAT | O_TRUNC);
665 if (!vf) {
666 LOG(QT, ERROR) << tr("Failed to open snapshot file for writing: %1").arg(path);
667 return;
668 }
669 Interrupter interrupter(this);
670 GBASavedataExportSharkPort(static_cast<GBA*>(m_threadContext.core->board), vf);
671 vf->close(vf);
672#endif
673}
674
675void CoreController::attachPrinter() {
676#ifdef M_CORE_GB
677 if (platform() != PLATFORM_GB) {
678 return;
679 }
680 GB* gb = static_cast<GB*>(m_threadContext.core->board);
681 clearMultiplayerController();
682 GBPrinterCreate(&m_printer.d);
683 m_printer.parent = this;
684 m_printer.d.print = [](GBPrinter* printer, int height, const uint8_t* data) {
685 QGBPrinter* qPrinter = reinterpret_cast<QGBPrinter*>(printer);
686 QImage image(GB_VIDEO_HORIZONTAL_PIXELS, height, QImage::Format_Indexed8);
687 QVector<QRgb> colors;
688 colors.append(qRgb(0xF8, 0xF8, 0xF8));
689 colors.append(qRgb(0xA8, 0xA8, 0xA8));
690 colors.append(qRgb(0x50, 0x50, 0x50));
691 colors.append(qRgb(0x00, 0x00, 0x00));
692 image.setColorTable(colors);
693 for (int y = 0; y < height; ++y) {
694 for (int x = 0; x < GB_VIDEO_HORIZONTAL_PIXELS; x += 4) {
695 uint8_t byte = data[(x + y * GB_VIDEO_HORIZONTAL_PIXELS) / 4];
696 image.setPixel(x + 0, y, (byte & 0xC0) >> 6);
697 image.setPixel(x + 1, y, (byte & 0x30) >> 4);
698 image.setPixel(x + 2, y, (byte & 0x0C) >> 2);
699 image.setPixel(x + 3, y, (byte & 0x03) >> 0);
700 }
701 }
702 QMetaObject::invokeMethod(qPrinter->parent, "imagePrinted", Q_ARG(const QImage&, image));
703 };
704 Interrupter interrupter(this);
705 GBSIOSetDriver(&gb->sio, &m_printer.d.d);
706#endif
707}
708
709void CoreController::detachPrinter() {
710#ifdef M_CORE_GB
711 if (platform() != PLATFORM_GB) {
712 return;
713 }
714 Interrupter interrupter(this);
715 GB* gb = static_cast<GB*>(m_threadContext.core->board);
716 GBPrinterDonePrinting(&m_printer.d);
717 GBSIOSetDriver(&gb->sio, nullptr);
718#endif
719}
720
721void CoreController::endPrint() {
722#ifdef M_CORE_GB
723 if (platform() != PLATFORM_GB) {
724 return;
725 }
726 Interrupter interrupter(this);
727 GBPrinterDonePrinting(&m_printer.d);
728#endif
729}
730
731void CoreController::setAVStream(mAVStream* stream) {
732 Interrupter interrupter(this);
733 m_threadContext.core->setAVStream(m_threadContext.core, stream);
734}
735
736void CoreController::clearAVStream() {
737 Interrupter interrupter(this);
738 m_threadContext.core->setAVStream(m_threadContext.core, nullptr);
739}
740
741void CoreController::clearOverride() {
742 m_override.reset();
743}
744
745void CoreController::startVideoLog(const QString& path) {
746 if (m_vl) {
747 return;
748 }
749
750 Interrupter interrupter(this);
751 m_vl = mVideoLogContextCreate(m_threadContext.core);
752 m_vlVf = VFileDevice::open(path, O_WRONLY | O_CREAT | O_TRUNC);
753 mVideoLogContextSetOutput(m_vl, m_vlVf);
754 mVideoLogContextWriteHeader(m_vl, m_threadContext.core);
755}
756
757void CoreController::endVideoLog() {
758 if (!m_vl) {
759 return;
760 }
761
762 Interrupter interrupter(this);
763 mVideoLogContextDestroy(m_threadContext.core, m_vl);
764 if (m_vlVf) {
765 m_vlVf->close(m_vlVf);
766 m_vlVf = nullptr;
767 }
768 m_vl = nullptr;
769}
770
771void CoreController::updateKeys() {
772 int activeKeys = m_activeKeys | updateAutofire() | m_inputController->pollEvents();
773 m_threadContext.core->setKeys(m_threadContext.core, activeKeys);
774}
775
776int CoreController::updateAutofire() {
777 int active = 0;
778 for (int k = 0; k < 32; ++k) {
779 if (!m_autofire[k]) {
780 continue;
781 }
782 ++m_autofireStatus[k];
783 if (m_autofireStatus[k] >= 2 * m_autofireThreshold) {
784 m_autofireStatus[k] = 0;
785 } else if (m_autofireStatus[k] >= m_autofireThreshold) {
786 active |= 1 << k;
787 }
788 }
789 return active;
790}
791
792void CoreController::finishFrame() {
793 QMutexLocker locker(&m_mutex);
794 memcpy(m_completeBuffer.data(), m_activeBuffer->constData(), m_activeBuffer->size());
795
796 // TODO: Generalize this to triple buffering?
797 m_activeBuffer = &m_buffers[0];
798 if (m_activeBuffer == m_completeBuffer) {
799 m_activeBuffer = &m_buffers[1];
800 }
801 // Copy contents to avoid issues when doing frameskip
802 memcpy(m_activeBuffer->data(), m_completeBuffer.constData(), m_activeBuffer->size());
803 m_threadContext.core->setVideoBuffer(m_threadContext.core, reinterpret_cast<color_t*>(m_activeBuffer->data()), screenDimensions().width());
804
805 for (auto& action : m_frameActions) {
806 action();
807 }
808 m_frameActions.clear();
809 updateKeys();
810
811 QMetaObject::invokeMethod(this, "frameAvailable");
812}
813
814void CoreController::updateFastForward() {
815 if (m_fastForward || m_fastForwardForced) {
816 if (m_fastForwardVolume >= 0) {
817 m_threadContext.core->opts.volume = m_fastForwardVolume;
818 }
819 if (m_fastForwardMute >= 0) {
820 m_threadContext.core->opts.mute = m_fastForwardMute;
821 }
822 if (m_fastForwardRatio > 0) {
823 m_threadContext.impl->sync.fpsTarget = m_fpsTarget * m_fastForwardRatio;
824 } else {
825 setSync(false);
826 }
827 } else {
828 if (!mCoreConfigGetIntValue(&m_threadContext.core->config, "volume", &m_threadContext.core->opts.volume)) {
829 m_threadContext.core->opts.volume = 0x100;
830 }
831 int fakeBool = 0;
832 mCoreConfigGetIntValue(&m_threadContext.core->config, "mute", &fakeBool);
833 m_threadContext.core->opts.mute = fakeBool;
834 m_threadContext.impl->sync.fpsTarget = m_fpsTarget;
835 setSync(true);
836 }
837 // XXX: Have a way of just updating opts
838 m_threadContext.core->loadConfig(m_threadContext.core, &m_threadContext.core->config);
839}
840
841CoreController::Interrupter::Interrupter(CoreController* parent, bool fromThread)
842 : m_parent(parent)
843{
844 if (!m_parent->thread()->impl) {
845 return;
846 }
847 if (!fromThread) {
848 mCoreThreadInterrupt(m_parent->thread());
849 } else {
850 mCoreThreadInterruptFromThread(m_parent->thread());
851 }
852}
853
854CoreController::Interrupter::Interrupter(std::shared_ptr<CoreController> parent, bool fromThread)
855 : m_parent(parent.get())
856{
857 if (!m_parent->thread()->impl) {
858 return;
859 }
860 if (!fromThread) {
861 mCoreThreadInterrupt(m_parent->thread());
862 } else {
863 mCoreThreadInterruptFromThread(m_parent->thread());
864 }
865}
866
867CoreController::Interrupter::Interrupter(const Interrupter& other)
868 : m_parent(other.m_parent)
869{
870 if (!m_parent->thread()->impl) {
871 return;
872 }
873 mCoreThreadInterrupt(m_parent->thread());
874}
875
876CoreController::Interrupter::~Interrupter() {
877 if (!m_parent->thread()->impl) {
878 return;
879 }
880 mCoreThreadContinue(m_parent->thread());
881}