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