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