all repos — mgba @ b7999071434ad01e8566562f58aec172ff165847

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