all repos — mgba @ 4731bae9e00a39c0ba2090846f16296704442514

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