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