all repos — mgba @ f8fb86ef7986d6935234589972a792349c3c1d71

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