all repos — mgba @ 5436d2576ffd0dac6254963e4a8d656e445ef078

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, bool compression) {
813	if (m_vl) {
814		return;
815	}
816
817	VFile* vf = VFileDevice::open(path, O_WRONLY | O_CREAT | O_TRUNC);
818	if (!vf) {
819		return;
820	}
821	startVideoLog(vf);
822}
823
824void CoreController::startVideoLog(VFile* vf, bool compression) {
825	if (m_vl || !vf) {
826		return;
827	}
828
829	Interrupter interrupter(this);
830	m_vl = mVideoLogContextCreate(m_threadContext.core);
831	m_vlVf = vf;
832	mVideoLogContextSetOutput(m_vl, m_vlVf);
833	mVideoLogContextSetCompression(m_vl, compression);
834	mVideoLogContextWriteHeader(m_vl, m_threadContext.core);
835}
836
837void CoreController::endVideoLog(bool closeVf) {
838	if (!m_vl) {
839		return;
840	}
841
842	Interrupter interrupter(this);
843	mVideoLogContextDestroy(m_threadContext.core, m_vl);
844	if (m_vlVf && closeVf) {
845		m_vlVf->close(m_vlVf);
846		m_vlVf = nullptr;
847	}
848	m_vl = nullptr;
849}
850
851void CoreController::setFramebufferHandle(int fb) {
852	Interrupter interrupter(this);
853	if (fb < 0) {
854		m_hwaccel = false;
855	} else {
856		m_threadContext.core->setVideoGLTex(m_threadContext.core, fb);
857		m_hwaccel = true;
858	}
859}
860
861void CoreController::updateKeys() {
862	int activeKeys = m_activeKeys | updateAutofire() | m_inputController->pollEvents();
863	m_threadContext.core->setKeys(m_threadContext.core, activeKeys);
864}
865
866int CoreController::updateAutofire() {
867	int active = 0;
868	for (int k = 0; k < 32; ++k) {
869		if (!m_autofire[k]) {
870			continue;
871		}
872		++m_autofireStatus[k];
873		if (m_autofireStatus[k] >= 2 * m_autofireThreshold) {
874			m_autofireStatus[k] = 0;
875		} else if (m_autofireStatus[k] >= m_autofireThreshold) {
876			active |= 1 << k;
877		}
878	}
879	return active;
880}
881
882void CoreController::finishFrame() {
883	QMutexLocker locker(&m_mutex);
884	if (!m_hwaccel) {
885			memcpy(m_completeBuffer.data(), m_activeBuffer->constData(), m_activeBuffer->size());
886
887		// TODO: Generalize this to triple buffering?
888		m_activeBuffer = &m_buffers[0];
889		if (m_activeBuffer == m_completeBuffer) {
890			m_activeBuffer = &m_buffers[1];
891		}
892		// Copy contents to avoid issues when doing frameskip
893		memcpy(m_activeBuffer->data(), m_completeBuffer.constData(), m_activeBuffer->size());
894		m_threadContext.core->setVideoBuffer(m_threadContext.core, reinterpret_cast<color_t*>(m_activeBuffer->data()), screenDimensions().width());
895	}
896	for (auto& action : m_frameActions) {
897		action();
898	}
899	m_frameActions.clear();
900	updateKeys();
901
902	QMetaObject::invokeMethod(this, "frameAvailable");
903}
904
905void CoreController::updateFastForward() {
906	if (m_fastForward || m_fastForwardForced) {
907		if (m_fastForwardVolume >= 0) {
908			m_threadContext.core->opts.volume = m_fastForwardVolume;
909		}
910		if (m_fastForwardMute >= 0) {
911			m_threadContext.core->opts.mute = m_fastForwardMute;
912		}
913		if (m_fastForwardRatio > 0) {
914			m_threadContext.impl->sync.fpsTarget = m_fpsTarget * m_fastForwardRatio;
915		} else {
916			setSync(false);
917		}
918	} else {
919		if (!mCoreConfigGetIntValue(&m_threadContext.core->config, "volume", &m_threadContext.core->opts.volume)) {
920			m_threadContext.core->opts.volume = 0x100;
921		}
922		int fakeBool = 0;
923		mCoreConfigGetIntValue(&m_threadContext.core->config, "mute", &fakeBool);
924		m_threadContext.core->opts.mute = fakeBool;
925		m_threadContext.impl->sync.fpsTarget = m_fpsTarget;
926		setSync(true);
927	}
928	// XXX: Have a way of just updating volume
929	switch (platform()) {
930#ifdef M_CORE_GBA
931	case PLATFORM_GBA: {
932		GBA* gba = static_cast<GBA*>(m_threadContext.core->board);
933		if (m_threadContext.core->opts.mute) {
934			gba->audio.masterVolume = 0;
935		} else {
936			gba->audio.masterVolume = m_threadContext.core->opts.volume;
937		}
938		break;
939	}
940#endif
941#ifdef M_CORE_GB
942	case PLATFORM_GB: {
943		GB* gb = static_cast<GB*>(m_threadContext.core->board);
944		if (m_threadContext.core->opts.mute) {
945			gb->audio.masterVolume = 0;
946		} else {
947			gb->audio.masterVolume = m_threadContext.core->opts.volume;
948		}
949		break;
950	}
951#endif
952	default:
953		break;
954	}
955}
956
957CoreController::Interrupter::Interrupter(CoreController* parent, bool fromThread)
958	: m_parent(parent)
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(std::shared_ptr<CoreController> parent, bool fromThread)
971	: m_parent(parent.get())
972{
973	if (!m_parent->thread()->impl) {
974		return;
975	}
976	if (!fromThread) {
977		mCoreThreadInterrupt(m_parent->thread());
978	} else {
979		mCoreThreadInterruptFromThread(m_parent->thread());
980	}
981}
982
983CoreController::Interrupter::Interrupter(const Interrupter& other)
984	: m_parent(other.m_parent)
985{
986	if (!m_parent->thread()->impl) {
987		return;
988	}
989	mCoreThreadInterrupt(m_parent->thread());
990}
991
992CoreController::Interrupter::~Interrupter() {
993	if (!m_parent->thread()->impl) {
994		return;
995	}
996	mCoreThreadContinue(m_parent->thread());
997}