all repos — mgba @ 2d5bfe33211e897a78e28283797376f752764010

mGBA Game Boy Advance Emulator

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