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