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