all repos — mgba @ db2b56f418359e03f0505bac5e894cf821989cc3

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