all repos — mgba @ 558cb2015e9cc71700332eb7d2ea005ffd827140

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