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