all repos — mgba @ 742538dc432a3d85b66318eded435a73dfce0f5c

mGBA Game Boy Advance Emulator

src/platform/qt/GameController.cpp (view raw)

   1/* Copyright (c) 2013-2014 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 "GameController.h"
   7
   8#include "AudioProcessor.h"
   9#include "InputController.h"
  10#include "LogController.h"
  11#include "MultiplayerController.h"
  12#include "VFileDevice.h"
  13
  14#include <QCoreApplication>
  15#include <QDateTime>
  16#include <QThread>
  17
  18#include <ctime>
  19
  20extern "C" {
  21#include "core/config.h"
  22#include "core/directories.h"
  23#include "core/serialize.h"
  24#ifdef M_CORE_GBA
  25#include "gba/bios.h"
  26#include "gba/core.h"
  27#include "gba/gba.h"
  28#include "gba/extra/sharkport.h"
  29#endif
  30#ifdef M_CORE_GB
  31#include "gb/gb.h"
  32#endif
  33#include "util/vfs.h"
  34}
  35
  36using namespace QGBA;
  37using namespace std;
  38
  39GameController::GameController(QObject* parent)
  40	: QObject(parent)
  41	, m_drawContext(nullptr)
  42	, m_frontBuffer(nullptr)
  43	, m_threadContext()
  44	, m_activeKeys(0)
  45	, m_inactiveKeys(0)
  46	, m_logLevels(0)
  47	, m_gameOpen(false)
  48	, m_vf(nullptr)
  49	, m_useBios(false)
  50	, m_audioThread(new QThread(this))
  51	, m_audioProcessor(AudioProcessor::create())
  52	, m_pauseAfterFrame(false)
  53	, m_sync(true)
  54	, m_videoSync(VIDEO_SYNC)
  55	, m_audioSync(AUDIO_SYNC)
  56	, m_fpsTarget(-1)
  57	, m_turbo(false)
  58	, m_turboForced(false)
  59	, m_turboSpeed(-1)
  60	, m_wasPaused(false)
  61	, m_audioChannels{ true, true, true, true, true, true }
  62	, m_videoLayers{ true, true, true, true, true }
  63	, m_autofire{}
  64	, m_autofireStatus{}
  65	, m_inputController(nullptr)
  66	, m_multiplayer(nullptr)
  67	, m_stream(nullptr)
  68	, m_stateSlot(1)
  69	, m_backupLoadState(nullptr)
  70	, m_backupSaveState(nullptr)
  71	, m_saveStateFlags(SAVESTATE_SCREENSHOT | SAVESTATE_SAVEDATA | SAVESTATE_CHEATS)
  72	, m_loadStateFlags(SAVESTATE_SCREENSHOT)
  73	, m_override(nullptr)
  74{
  75#ifdef M_CORE_GBA
  76	m_lux.p = this;
  77	m_lux.sample = [](GBALuminanceSource* context) {
  78		GameControllerLux* lux = static_cast<GameControllerLux*>(context);
  79		lux->value = 0xFF - lux->p->m_luxValue;
  80	};
  81
  82	m_lux.readLuminance = [](GBALuminanceSource* context) {
  83		GameControllerLux* lux = static_cast<GameControllerLux*>(context);
  84		return lux->value;
  85	};
  86	setLuminanceLevel(0);
  87#endif
  88
  89	m_threadContext.startCallback = [](mCoreThread* context) {
  90		GameController* controller = static_cast<GameController*>(context->userData);
  91		mRTCGenericSourceInit(&controller->m_rtc, context->core);
  92		context->core->setRTC(context->core, &controller->m_rtc.d);
  93		context->core->setRotation(context->core, controller->m_inputController->rotationSource());
  94		context->core->setRumble(context->core, controller->m_inputController->rumble());
  95
  96#ifdef M_CORE_GBA
  97		GBA* gba = static_cast<GBA*>(context->core->board);
  98#endif
  99#ifdef M_CORE_GB
 100		GB* gb = static_cast<GB*>(context->core->board);
 101#endif
 102		switch (context->core->platform(context->core)) {
 103#ifdef M_CORE_GBA
 104		case PLATFORM_GBA:
 105			gba->luminanceSource = &controller->m_lux;
 106			gba->audio.psg.forceDisableCh[0] = !controller->m_audioChannels[0];
 107			gba->audio.psg.forceDisableCh[1] = !controller->m_audioChannels[1];
 108			gba->audio.psg.forceDisableCh[2] = !controller->m_audioChannels[2];
 109			gba->audio.psg.forceDisableCh[3] = !controller->m_audioChannels[3];
 110			gba->audio.forceDisableChA = !controller->m_audioChannels[4];
 111			gba->audio.forceDisableChB = !controller->m_audioChannels[5];
 112			gba->video.renderer->disableBG[0] = !controller->m_videoLayers[0];
 113			gba->video.renderer->disableBG[1] = !controller->m_videoLayers[1];
 114			gba->video.renderer->disableBG[2] = !controller->m_videoLayers[2];
 115			gba->video.renderer->disableBG[3] = !controller->m_videoLayers[3];
 116			gba->video.renderer->disableOBJ = !controller->m_videoLayers[4];
 117			break;
 118#endif
 119#ifdef M_CORE_GB
 120		case PLATFORM_GB:
 121			gb->audio.forceDisableCh[0] = !controller->m_audioChannels[0];
 122			gb->audio.forceDisableCh[1] = !controller->m_audioChannels[1];
 123			gb->audio.forceDisableCh[2] = !controller->m_audioChannels[2];
 124			gb->audio.forceDisableCh[3] = !controller->m_audioChannels[3];
 125			break;
 126#endif
 127		default:
 128			break;
 129		}
 130		controller->m_fpsTarget = context->sync.fpsTarget;
 131
 132		if (mCoreLoadState(context->core, 0, controller->m_loadStateFlags)) {
 133			mCoreDeleteState(context->core, 0);
 134		}
 135
 136		controller->m_gameOpen = true;
 137		if (controller->m_multiplayer) {
 138			controller->m_multiplayer->attachGame(controller);
 139		}
 140
 141		QMetaObject::invokeMethod(controller, "gameStarted", Q_ARG(mCoreThread*, context), Q_ARG(const QString&, controller->m_fname));
 142		QMetaObject::invokeMethod(controller, "startAudio");
 143	};
 144
 145	m_threadContext.resetCallback = [](mCoreThread* context) {
 146		GameController* controller = static_cast<GameController*>(context->userData);
 147		for (auto action : controller->m_resetActions) {
 148			action();
 149		}
 150		controller->m_resetActions.clear();
 151
 152		unsigned width, height;
 153		controller->m_threadContext.core->desiredVideoDimensions(controller->m_threadContext.core, &width, &height);
 154		memset(controller->m_frontBuffer, 0xF8, width * height * BYTES_PER_PIXEL);
 155		QMetaObject::invokeMethod(controller, "frameAvailable", Q_ARG(const uint32_t*, controller->m_frontBuffer));
 156		if (controller->m_pauseAfterFrame.testAndSetAcquire(true, false)) {
 157			mCoreThreadPauseFromThread(context);
 158			QMetaObject::invokeMethod(controller, "gamePaused", Q_ARG(mCoreThread*, context));
 159		}
 160	};
 161
 162	m_threadContext.cleanCallback = [](mCoreThread* context) {
 163		GameController* controller = static_cast<GameController*>(context->userData);
 164		QMetaObject::invokeMethod(controller, "gameStopped", Q_ARG(mCoreThread*, context));
 165		QMetaObject::invokeMethod(controller, "cleanGame");
 166	};
 167
 168	m_threadContext.frameCallback = [](mCoreThread* context) {
 169		GameController* controller = static_cast<GameController*>(context->userData);
 170		unsigned width, height;
 171		controller->m_threadContext.core->desiredVideoDimensions(controller->m_threadContext.core, &width, &height);
 172		memcpy(controller->m_frontBuffer, controller->m_drawContext, width * height * BYTES_PER_PIXEL);
 173		QMetaObject::invokeMethod(controller, "frameAvailable", Q_ARG(const uint32_t*, controller->m_frontBuffer));
 174		if (controller->m_pauseAfterFrame.testAndSetAcquire(true, false)) {
 175			mCoreThreadPauseFromThread(context);
 176			QMetaObject::invokeMethod(controller, "gamePaused", Q_ARG(mCoreThread*, context));
 177		}
 178	};
 179
 180	// TODO: Put back
 181	/*m_threadContext.stopCallback = [](mCoreThread* context) {
 182		if (!context) {
 183			return false;
 184		}
 185		GameController* controller = static_cast<GameController*>(context->userData);
 186		if (!mCoreSaveState(context->core, 0, controller->m_saveStateFlags)) {
 187			return false;
 188		}
 189		QMetaObject::invokeMethod(controller, "closeGame");
 190		return true;
 191	};*/
 192
 193	m_threadContext.logger.d.log = [](mLogger* logger, int category, enum mLogLevel level, const char* format, va_list args) {
 194		mThreadLogger* logContext = reinterpret_cast<mThreadLogger*>(logger);
 195		mCoreThread* context = logContext->p;
 196
 197		static const char* savestateMessage = "State %i loaded";
 198		static const char* savestateFailedMessage = "State %i failed to load";
 199		if (!context) {
 200			return;
 201		}
 202		GameController* controller = static_cast<GameController*>(context->userData);
 203		QString message;
 204#ifdef M_CORE_GBA
 205		if (level == mLOG_STUB && category == _mLOG_CAT_GBA_BIOS()) {
 206			va_list argc;
 207			va_copy(argc, args);
 208			int immediate = va_arg(argc, int);
 209			va_end(argc);
 210			QMetaObject::invokeMethod(controller, "unimplementedBiosCall", Q_ARG(int, immediate));
 211		} else
 212#endif
 213		if (category == _mLOG_CAT_STATUS()) {
 214			// Slot 0 is reserved for suspend points
 215			if (strncmp(savestateMessage, format, strlen(savestateMessage)) == 0) {
 216				va_list argc;
 217				va_copy(argc, args);
 218				int slot = va_arg(argc, int);
 219				va_end(argc);
 220				if (slot == 0) {
 221					format = "Loaded suspend state";
 222				}
 223			} else if (strncmp(savestateFailedMessage, format, strlen(savestateFailedMessage)) == 0) {
 224				va_list argc;
 225				va_copy(argc, args);
 226				int slot = va_arg(argc, int);
 227				va_end(argc);
 228				if (slot == 0) {
 229					return;
 230				}
 231			}
 232			message = QString().vsprintf(format, args);
 233			QMetaObject::invokeMethod(controller, "statusPosted", Q_ARG(const QString&, message));
 234		}
 235		if (level == mLOG_FATAL) {
 236			mCoreThreadMarkCrashed(controller->thread());
 237			QMetaObject::invokeMethod(controller, "crashGame", Q_ARG(const QString&, QString().vsprintf(format, args)));
 238		} else if (!(controller->m_logLevels & level)) {
 239			return;
 240		}
 241		message = QString().vsprintf(format, args);
 242		QMetaObject::invokeMethod(controller, "postLog", Q_ARG(int, level), Q_ARG(int, category), Q_ARG(const QString&, message));
 243	};
 244
 245	m_threadContext.userData = this;
 246
 247	m_audioThread->setObjectName("Audio Thread");
 248	m_audioThread->start(QThread::TimeCriticalPriority);
 249	m_audioProcessor->moveToThread(m_audioThread);
 250	connect(this, SIGNAL(gamePaused(mCoreThread*)), m_audioProcessor, SLOT(pause()));
 251	connect(this, SIGNAL(gameStarted(mCoreThread*, const QString&)), m_audioProcessor, SLOT(setInput(mCoreThread*)));
 252	connect(this, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(pollEvents()));
 253	connect(this, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(updateAutofire()));
 254}
 255
 256GameController::~GameController() {
 257	disconnect();
 258	closeGame();
 259	m_audioThread->quit();
 260	m_audioThread->wait();
 261	clearMultiplayerController();
 262	delete m_backupLoadState;
 263}
 264
 265void GameController::setMultiplayerController(MultiplayerController* controller) {
 266	if (controller == m_multiplayer) {
 267		return;
 268	}
 269	clearMultiplayerController();
 270	m_multiplayer = controller;
 271	if (isLoaded()) {
 272		mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* thread) {
 273			GameController* controller = static_cast<GameController*>(thread->userData);
 274			controller->m_multiplayer->attachGame(controller);
 275		});
 276	}
 277}
 278
 279void GameController::clearMultiplayerController() {
 280	if (!m_multiplayer) {
 281		return;
 282	}
 283	m_multiplayer->detachGame(this);
 284	m_multiplayer = nullptr;
 285}
 286
 287void GameController::setOverride(Override* override) {
 288	m_override = override;
 289	if (isLoaded()) {
 290		threadInterrupt();
 291		m_override->identify(m_threadContext.core);
 292		threadContinue();
 293	}
 294}
 295
 296void GameController::clearOverride() {
 297	delete m_override;
 298	m_override = nullptr;
 299}
 300
 301void GameController::setConfig(const mCoreConfig* config) {
 302	m_config = config;
 303	if (isLoaded()) {
 304		threadInterrupt();
 305		mCoreLoadForeignConfig(m_threadContext.core, config);
 306		m_audioProcessor->setInput(&m_threadContext);
 307		threadContinue();
 308	}
 309}
 310
 311#ifdef USE_GDB_STUB
 312mDebugger* GameController::debugger() {
 313	if (!isLoaded()) {
 314		return nullptr;
 315	}
 316	return m_threadContext.core->debugger;
 317}
 318
 319void GameController::setDebugger(mDebugger* debugger) {
 320	threadInterrupt();
 321	if (debugger) {
 322		mDebuggerAttach(debugger, m_threadContext.core);
 323	} else {
 324		m_threadContext.core->detachDebugger(m_threadContext.core);
 325	}
 326	threadContinue();
 327}
 328#endif
 329
 330void GameController::loadGame(const QString& path) {
 331	closeGame();
 332	QFileInfo info(path);
 333	if (!info.isReadable()) {
 334		LOG(QT, ERROR) << tr("Failed to open game file: %1").arg(path);
 335		return;
 336	}
 337	m_fname = info.canonicalFilePath();
 338	m_vf = nullptr;
 339	openGame();
 340}
 341
 342void GameController::loadGame(VFile* vf, const QString& base) {
 343	closeGame();
 344	m_fname = base;
 345	m_vf = vf;
 346	openGame();
 347}
 348
 349void GameController::bootBIOS() {
 350	closeGame();
 351	m_fname = QString();
 352	openGame(true);
 353}
 354
 355void GameController::openGame(bool biosOnly) {
 356	if (m_fname.isEmpty()) {
 357		biosOnly = true;
 358	}
 359	if (biosOnly && (!m_useBios || m_bios.isNull())) {
 360		return;
 361	}
 362	if (isLoaded()) {
 363		// We need to delay if the game is still cleaning up
 364		QTimer::singleShot(10, this, SLOT(openGame()));
 365		return;
 366	} else if(m_gameOpen) {
 367		cleanGame();
 368	}
 369
 370	if (!biosOnly) {
 371		if (m_vf) {
 372			m_threadContext.core = mCoreFindVF(m_vf);
 373		} else {
 374			m_threadContext.core = mCoreFind(m_fname.toUtf8().constData());
 375		}
 376	} else {
 377		m_threadContext.core = GBACoreCreate();
 378	}
 379
 380	if (!m_threadContext.core) {
 381		return;
 382	}
 383
 384	m_pauseAfterFrame = false;
 385
 386	if (m_turbo) {
 387		m_threadContext.sync.videoFrameWait = false;
 388		m_threadContext.sync.audioWait = false;
 389	} else {
 390		m_threadContext.sync.videoFrameWait = m_videoSync;
 391		m_threadContext.sync.audioWait = m_audioSync;
 392	}
 393	m_threadContext.core->init(m_threadContext.core);
 394
 395	unsigned width, height;
 396	m_threadContext.core->desiredVideoDimensions(m_threadContext.core, &width, &height);
 397	m_drawContext = new uint32_t[width * height];
 398	m_frontBuffer = new uint32_t[width * height];
 399
 400	QByteArray bytes;
 401	if (!biosOnly) {
 402		bytes = m_fname.toUtf8();
 403		if (m_vf) {
 404			m_threadContext.core->loadROM(m_threadContext.core, m_vf);
 405		} else {
 406			mCoreLoadFile(m_threadContext.core, bytes.constData());
 407			mDirectorySetDetachBase(&m_threadContext.core->dirs);
 408		}
 409	} else {
 410		bytes = m_bios.toUtf8();
 411	}
 412	char dirname[PATH_MAX];
 413	separatePath(bytes.constData(), dirname, m_threadContext.core->dirs.baseName, 0);
 414	mDirectorySetAttachBase(&m_threadContext.core->dirs, VDirOpen(dirname));
 415
 416	m_threadContext.core->setVideoBuffer(m_threadContext.core, m_drawContext, width);
 417
 418	if (!m_bios.isNull() && m_useBios) {
 419		VFile* bios = VFileDevice::open(m_bios, O_RDONLY);
 420		if (bios && !m_threadContext.core->loadBIOS(m_threadContext.core, bios, 0)) {
 421			bios->close(bios);
 422		}
 423	}
 424
 425	m_inputController->recalibrateAxes();
 426	memset(m_drawContext, 0xF8, width * height * 4);
 427
 428	m_threadContext.core->setAVStream(m_threadContext.core, m_stream);
 429
 430	if (m_config) {
 431		mCoreLoadForeignConfig(m_threadContext.core, m_config);
 432	}
 433
 434	if (!biosOnly) {
 435		mCoreAutoloadSave(m_threadContext.core);
 436		if (!m_patch.isNull()) {
 437			VFile* patch = VFileDevice::open(m_patch, O_RDONLY);
 438			if (patch) {
 439				m_threadContext.core->loadPatch(m_threadContext.core, patch);
 440			}
 441			patch->close(patch);
 442		} else {
 443			mCoreAutoloadPatch(m_threadContext.core);
 444		}
 445	}
 446	m_vf = nullptr;
 447
 448	if (m_override) {
 449		m_override->identify(m_threadContext.core);
 450		m_override->apply(m_threadContext.core);
 451	}
 452
 453	if (!mCoreThreadStart(&m_threadContext)) {
 454		emit gameFailed();
 455	}
 456}
 457
 458void GameController::loadBIOS(const QString& path) {
 459	if (m_bios == path) {
 460		return;
 461	}
 462	m_bios = path;
 463	if (m_gameOpen) {
 464		closeGame();
 465		openGame();
 466	}
 467}
 468
 469void GameController::loadSave(const QString& path, bool temporary) {
 470	if (!isLoaded()) {
 471		return;
 472	}
 473	m_resetActions.append([this, path, temporary]() {
 474		VFile* vf = VFileDevice::open(path, temporary ? O_RDONLY : O_RDWR);
 475		if (!vf) {
 476			LOG(QT, ERROR) << tr("Failed to open save file: %1").arg(path);
 477			return;
 478		}
 479
 480		if (temporary) {
 481			m_threadContext.core->loadTemporarySave(m_threadContext.core, vf);
 482		} else {
 483			m_threadContext.core->loadSave(m_threadContext.core, vf);
 484		}
 485	});
 486	reset();
 487}
 488
 489void GameController::yankPak() {
 490	if (!m_gameOpen) {
 491		return;
 492	}
 493	threadInterrupt();
 494	GBAYankROM(static_cast<GBA*>(m_threadContext.core->board));
 495	threadContinue();
 496}
 497
 498void GameController::replaceGame(const QString& path) {
 499	if (!m_gameOpen) {
 500		return;
 501	}
 502
 503	QFileInfo info(path);
 504	if (!info.isReadable()) {
 505		LOG(QT, ERROR) << tr("Failed to open game file: %1").arg(path);
 506		return;
 507	}
 508	m_fname = info.canonicalFilePath();
 509	threadInterrupt();
 510	mDirectorySetDetachBase(&m_threadContext.core->dirs);
 511	mCoreLoadFile(m_threadContext.core, m_fname.toLocal8Bit().constData());
 512	threadContinue();
 513}
 514
 515void GameController::loadPatch(const QString& path) {
 516	if (m_gameOpen) {
 517		closeGame();
 518		m_patch = path;
 519		openGame();
 520	} else {
 521		m_patch = path;
 522	}
 523}
 524
 525void GameController::importSharkport(const QString& path) {
 526	if (!isLoaded()) {
 527		return;
 528	}
 529#ifdef M_CORE_GBA
 530	if (platform() != PLATFORM_GBA) {
 531		return;
 532	}
 533	VFile* vf = VFileDevice::open(path, O_RDONLY);
 534	if (!vf) {
 535		LOG(QT, ERROR) << tr("Failed to open snapshot file for reading: %1").arg(path);
 536		return;
 537	}
 538	threadInterrupt();
 539	GBASavedataImportSharkPort(static_cast<GBA*>(m_threadContext.core->board), vf, false);
 540	threadContinue();
 541	vf->close(vf);
 542#endif
 543}
 544
 545void GameController::exportSharkport(const QString& path) {
 546	if (!isLoaded()) {
 547		return;
 548	}
 549#ifdef M_CORE_GBA
 550	if (platform() != PLATFORM_GBA) {
 551		return;
 552	}
 553	VFile* vf = VFileDevice::open(path, O_WRONLY | O_CREAT | O_TRUNC);
 554	if (!vf) {
 555		LOG(QT, ERROR) << tr("Failed to open snapshot file for writing: %1").arg(path);
 556		return;
 557	}
 558	threadInterrupt();
 559	GBASavedataExportSharkPort(static_cast<GBA*>(m_threadContext.core->board), vf);
 560	threadContinue();
 561	vf->close(vf);
 562#endif
 563}
 564
 565void GameController::closeGame() {
 566	if (!m_gameOpen) {
 567		return;
 568	}
 569	if (m_multiplayer) {
 570		m_multiplayer->detachGame(this);
 571	}
 572
 573	if (mCoreThreadIsPaused(&m_threadContext)) {
 574		mCoreThreadUnpause(&m_threadContext);
 575	}
 576	m_patch = QString();
 577	clearOverride();
 578
 579	QMetaObject::invokeMethod(m_audioProcessor, "pause", Qt::BlockingQueuedConnection);
 580	mCoreThreadEnd(&m_threadContext);
 581}
 582
 583void GameController::cleanGame() {
 584	if (!m_gameOpen || mCoreThreadIsActive(&m_threadContext)) {
 585		return;
 586	}
 587	mCoreThreadJoin(&m_threadContext);
 588
 589	delete[] m_drawContext;
 590	delete[] m_frontBuffer;
 591
 592	m_threadContext.core->deinit(m_threadContext.core);
 593	m_gameOpen = false;
 594}
 595
 596void GameController::crashGame(const QString& crashMessage) {
 597	closeGame();
 598	emit gameCrashed(crashMessage);
 599}
 600
 601bool GameController::isPaused() {
 602	if (!m_gameOpen) {
 603		return false;
 604	}
 605	return mCoreThreadIsPaused(&m_threadContext);
 606}
 607
 608mPlatform GameController::platform() const {
 609	if (!m_gameOpen) {
 610		return PLATFORM_NONE;
 611	}
 612	return m_threadContext.core->platform(m_threadContext.core);
 613}
 614
 615QSize GameController::screenDimensions() const {
 616	if (!m_gameOpen) {
 617		return QSize();
 618	}
 619	unsigned width, height;
 620	m_threadContext.core->desiredVideoDimensions(m_threadContext.core, &width, &height);
 621
 622	return QSize(width, height);
 623}
 624
 625void GameController::setPaused(bool paused) {
 626	if (!isLoaded() || paused == mCoreThreadIsPaused(&m_threadContext)) {
 627		return;
 628	}
 629	m_wasPaused = paused;
 630	if (paused) {
 631		m_pauseAfterFrame.testAndSetRelaxed(false, true);
 632	} else {
 633		mCoreThreadUnpause(&m_threadContext);
 634		startAudio();
 635		emit gameUnpaused(&m_threadContext);
 636	}
 637}
 638
 639void GameController::reset() {
 640	if (!m_gameOpen) {
 641		return;
 642	}
 643	bool wasPaused = isPaused();
 644	setPaused(false);
 645	threadInterrupt();
 646	mCoreThreadReset(&m_threadContext);
 647	if (wasPaused) {
 648		setPaused(true);
 649	}
 650	threadContinue();
 651}
 652
 653void GameController::threadInterrupt() {
 654	if (m_gameOpen) {
 655		mCoreThreadInterrupt(&m_threadContext);
 656	}
 657}
 658
 659void GameController::threadContinue() {
 660	if (m_gameOpen) {
 661		mCoreThreadContinue(&m_threadContext);
 662	}
 663}
 664
 665void GameController::frameAdvance() {
 666	if (m_pauseAfterFrame.testAndSetRelaxed(false, true)) {
 667		setPaused(false);
 668	}
 669}
 670
 671void GameController::setRewind(bool enable, int capacity) {
 672	if (m_gameOpen) {
 673		threadInterrupt();
 674		if (m_threadContext.core->opts.rewindEnable && m_threadContext.core->opts.rewindBufferCapacity > 0) {
 675			mCoreRewindContextDeinit(&m_threadContext.rewind);
 676		}
 677		m_threadContext.core->opts.rewindEnable = enable;
 678		m_threadContext.core->opts.rewindBufferCapacity = capacity;
 679		if (enable && capacity > 0) {
 680			mCoreRewindContextInit(&m_threadContext.rewind, capacity);
 681		}
 682		threadContinue();
 683	}
 684}
 685
 686void GameController::rewind(int states) {
 687	threadInterrupt();
 688	if (!states) {
 689		states = INT_MAX;
 690	}
 691	for (int i = 0; i < states; ++i) {
 692		if (!mCoreRewindRestore(&m_threadContext.rewind, m_threadContext.core)) {
 693			break;
 694		}
 695	}
 696	threadContinue();
 697	emit frameAvailable(m_drawContext);
 698	emit rewound(&m_threadContext);
 699}
 700
 701void GameController::startRewinding() {
 702	if (!isLoaded()) {
 703		return;
 704	}
 705	if (!m_threadContext.core->opts.rewindEnable) {
 706		return;
 707	}
 708	if (m_multiplayer && m_multiplayer->attached() > 1) {
 709		return;
 710	}
 711	if (m_wasPaused) {
 712		setPaused(false);
 713		m_wasPaused = true;
 714	}
 715	mCoreThreadSetRewinding(&m_threadContext, true);
 716}
 717
 718void GameController::stopRewinding() {
 719	if (!isLoaded()) {
 720		return;
 721	}
 722	mCoreThreadSetRewinding(&m_threadContext, false);
 723	bool signalsBlocked = blockSignals(true);
 724	setPaused(m_wasPaused);
 725	blockSignals(signalsBlocked);
 726}
 727
 728void GameController::keyPressed(int key) {
 729	int mappedKey = 1 << key;
 730	m_activeKeys |= mappedKey;
 731	if (!m_inputController->allowOpposing()) {
 732		if ((m_activeKeys & 0x30) == 0x30) {
 733			m_inactiveKeys |= mappedKey ^ 0x30;
 734			m_activeKeys ^= mappedKey ^ 0x30;
 735		}
 736		if ((m_activeKeys & 0xC0) == 0xC0) {
 737			m_inactiveKeys |= mappedKey ^ 0xC0;
 738			m_activeKeys ^= mappedKey ^ 0xC0;
 739		}
 740	}
 741	updateKeys();
 742}
 743
 744void GameController::keyReleased(int key) {
 745	int mappedKey = 1 << key;
 746	m_activeKeys &= ~mappedKey;
 747	if (!m_inputController->allowOpposing()) {
 748		if (mappedKey & 0x30) {
 749			m_activeKeys |= m_inactiveKeys & (0x30 ^ mappedKey);
 750			m_inactiveKeys &= ~0x30;
 751		}
 752		if (mappedKey & 0xC0) {
 753			m_activeKeys |= m_inactiveKeys & (0xC0 ^ mappedKey);
 754			m_inactiveKeys &= ~0xC0;
 755		}
 756	}
 757	updateKeys();
 758}
 759
 760void GameController::clearKeys() {
 761	m_activeKeys = 0;
 762	m_inactiveKeys = 0;
 763	updateKeys();
 764}
 765
 766void GameController::setAutofire(int key, bool enable) {
 767	if (key >= GBA_KEY_MAX || key < 0) {
 768		return;
 769	}
 770
 771	if (!enable && m_autofireStatus[key]) {
 772		keyReleased(key);
 773	}
 774
 775	m_autofire[key] = enable;
 776	m_autofireStatus[key] = 0;
 777}
 778
 779void GameController::setAudioBufferSamples(int samples) {
 780	if (m_audioProcessor) {
 781		threadInterrupt();
 782		redoSamples(samples);
 783		threadContinue();
 784		QMetaObject::invokeMethod(m_audioProcessor, "setBufferSamples", Qt::BlockingQueuedConnection, Q_ARG(int, samples));
 785	}
 786}
 787
 788void GameController::setAudioSampleRate(unsigned rate) {
 789	if (!rate) {
 790		return;
 791	}
 792	if (m_audioProcessor) {
 793		threadInterrupt();
 794		redoSamples(m_audioProcessor->getBufferSamples());
 795		threadContinue();
 796		QMetaObject::invokeMethod(m_audioProcessor, "requestSampleRate", Q_ARG(unsigned, rate));
 797	}
 798}
 799
 800void GameController::setAudioChannelEnabled(int channel, bool enable) {
 801	if (channel > 5 || channel < 0) {
 802		return;
 803	}
 804#ifdef M_CORE_GBA
 805	GBA* gba = static_cast<GBA*>(m_threadContext.core->board);
 806#endif
 807#ifdef M_CORE_GB
 808	GB* gb = static_cast<GB*>(m_threadContext.core->board);
 809#endif
 810	m_audioChannels[channel] = enable;
 811	if (isLoaded()) {
 812		switch (channel) {
 813		case 0:
 814		case 1:
 815		case 2:
 816		case 3:
 817			switch (m_threadContext.core->platform(m_threadContext.core)) {
 818#ifdef M_CORE_GBA
 819			case PLATFORM_GBA:
 820				gba->audio.psg.forceDisableCh[channel] = !enable;
 821				break;
 822#endif
 823#ifdef M_CORE_GB
 824			case PLATFORM_GB:
 825				gb->audio.forceDisableCh[channel] = !enable;
 826				break;
 827#endif
 828			default:
 829				break;
 830			}
 831			break;
 832#ifdef M_CORE_GBA
 833		case 4:
 834			if (m_threadContext.core->platform(m_threadContext.core) == PLATFORM_GBA) {
 835				gba->audio.forceDisableChA = !enable;
 836			}
 837			break;
 838		case 5:
 839			if (m_threadContext.core->platform(m_threadContext.core) == PLATFORM_GBA) {
 840				gba->audio.forceDisableChB = !enable;
 841			}
 842			break;
 843#endif
 844		}
 845	}
 846}
 847
 848void GameController::startAudio() {
 849	bool started = false;
 850	QMetaObject::invokeMethod(m_audioProcessor, "start", Qt::BlockingQueuedConnection, Q_RETURN_ARG(bool, started));
 851	if (!started) {
 852		LOG(QT, ERROR) << tr("Failed to start audio processor");
 853		// Don't freeze!
 854		m_audioSync = false;
 855		m_videoSync = true;
 856		m_threadContext.sync.audioWait = false;
 857		m_threadContext.sync.videoFrameWait = true;
 858	}
 859}
 860
 861void GameController::setVideoLayerEnabled(int layer, bool enable) {
 862	if (layer > 4 || layer < 0) {
 863		return;
 864	}
 865	m_videoLayers[layer] = enable;
 866#ifdef M_CORE_GBA
 867	if (isLoaded() && m_threadContext.core->platform(m_threadContext.core) == PLATFORM_GBA) {
 868		GBA* gba = static_cast<GBA*>(m_threadContext.core->board);
 869		switch (layer) {
 870		case 0:
 871		case 1:
 872		case 2:
 873		case 3:
 874			gba->video.renderer->disableBG[layer] = !enable;
 875			break;
 876		case 4:
 877			gba->video.renderer->disableOBJ = !enable;
 878			break;
 879		}
 880	}
 881#endif
 882}
 883
 884void GameController::setFPSTarget(float fps) {
 885	threadInterrupt();
 886	m_fpsTarget = fps;
 887	m_threadContext.sync.fpsTarget = fps;
 888	if (m_turbo && m_turboSpeed > 0) {
 889		m_threadContext.sync.fpsTarget *= m_turboSpeed;
 890	}
 891	if (m_audioProcessor) {
 892		redoSamples(m_audioProcessor->getBufferSamples());
 893	}
 894	threadContinue();
 895}
 896
 897void GameController::setUseBIOS(bool use) {
 898	if (use == m_useBios) {
 899		return;
 900	}
 901	m_useBios = use;
 902	if (m_gameOpen) {
 903		closeGame();
 904		openGame();
 905	}
 906}
 907
 908void GameController::loadState(int slot) {
 909	if (m_fname.isEmpty()) {
 910		// We're in the BIOS
 911		return;
 912	}
 913	if (slot > 0 && slot != m_stateSlot) {
 914		m_stateSlot = slot;
 915		m_backupSaveState.clear();
 916	}
 917	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 918		GameController* controller = static_cast<GameController*>(context->userData);
 919		if (!controller->m_backupLoadState) {
 920			controller->m_backupLoadState = VFileMemChunk(nullptr, 0);
 921		}
 922		mCoreLoadStateNamed(context->core, controller->m_backupLoadState, controller->m_saveStateFlags);
 923		if (mCoreLoadState(context->core, controller->m_stateSlot, controller->m_loadStateFlags)) {
 924			controller->frameAvailable(controller->m_drawContext);
 925			controller->stateLoaded(context);
 926		}
 927	});
 928}
 929
 930void GameController::saveState(int slot) {
 931	if (m_fname.isEmpty()) {
 932		// We're in the BIOS
 933		return;
 934	}
 935	if (slot > 0) {
 936		m_stateSlot = slot;
 937	}
 938	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 939		GameController* controller = static_cast<GameController*>(context->userData);
 940		VFile* vf = mCoreGetState(context->core, controller->m_stateSlot, false);
 941		if (vf) {
 942			controller->m_backupSaveState.resize(vf->size(vf));
 943			vf->read(vf, controller->m_backupSaveState.data(), controller->m_backupSaveState.size());
 944			vf->close(vf);
 945		}
 946		mCoreSaveState(context->core, controller->m_stateSlot, controller->m_saveStateFlags);
 947	});
 948}
 949
 950void GameController::loadBackupState() {
 951	if (!m_backupLoadState) {
 952		return;
 953	}
 954
 955	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 956		GameController* controller = static_cast<GameController*>(context->userData);
 957		controller->m_backupLoadState->seek(controller->m_backupLoadState, 0, SEEK_SET);
 958		if (mCoreLoadStateNamed(context->core, controller->m_backupLoadState, controller->m_loadStateFlags)) {
 959			mLOG(STATUS, INFO, "Undid state load");
 960			controller->frameAvailable(controller->m_drawContext);
 961			controller->stateLoaded(context);
 962		}
 963		controller->m_backupLoadState->close(controller->m_backupLoadState);
 964		controller->m_backupLoadState = nullptr;
 965	});
 966}
 967
 968void GameController::saveBackupState() {
 969	if (m_backupSaveState.isEmpty()) {
 970		return;
 971	}
 972
 973	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 974		GameController* controller = static_cast<GameController*>(context->userData);
 975		VFile* vf = mCoreGetState(context->core, controller->m_stateSlot, true);
 976		if (vf) {
 977			vf->write(vf, controller->m_backupSaveState.constData(), controller->m_backupSaveState.size());
 978			vf->close(vf);
 979			mLOG(STATUS, INFO, "Undid state save");
 980		}
 981		controller->m_backupSaveState.clear();
 982	});
 983}
 984
 985void GameController::setTurbo(bool set, bool forced) {
 986	if (m_turboForced && !forced) {
 987		return;
 988	}
 989	if (m_turbo == set && m_turboForced == (set && forced)) {
 990		// Don't interrupt the thread if we don't need to
 991		return;
 992	}
 993	if (!m_sync) {
 994		return;
 995	}
 996	m_turbo = set;
 997	m_turboForced = set && forced;
 998	enableTurbo();
 999}
1000
1001void GameController::setTurboSpeed(float ratio) {
1002	m_turboSpeed = ratio;
1003	enableTurbo();
1004}
1005
1006void GameController::enableTurbo() {
1007	threadInterrupt();
1008	bool shouldRedoSamples = false;
1009	if (!m_turbo) {
1010		shouldRedoSamples = m_threadContext.sync.fpsTarget != m_fpsTarget;
1011		m_threadContext.sync.fpsTarget = m_fpsTarget;
1012		m_threadContext.sync.audioWait = m_audioSync;
1013		m_threadContext.sync.videoFrameWait = m_videoSync;
1014	} else if (m_turboSpeed <= 0) {
1015		shouldRedoSamples = m_threadContext.sync.fpsTarget != m_fpsTarget;
1016		m_threadContext.sync.fpsTarget = m_fpsTarget;
1017		m_threadContext.sync.audioWait = false;
1018		m_threadContext.sync.videoFrameWait = false;
1019	} else {
1020		shouldRedoSamples = m_threadContext.sync.fpsTarget != m_fpsTarget * m_turboSpeed;
1021		m_threadContext.sync.fpsTarget = m_fpsTarget * m_turboSpeed;
1022		m_threadContext.sync.audioWait = true;
1023		m_threadContext.sync.videoFrameWait = false;
1024	}
1025	if (m_audioProcessor && shouldRedoSamples) {
1026		redoSamples(m_audioProcessor->getBufferSamples());
1027	}
1028	threadContinue();
1029}
1030
1031void GameController::setSync(bool enable) {
1032	m_turbo = false;
1033	m_turboForced = false;
1034	if (!enable) {
1035		m_threadContext.sync.audioWait = false;
1036		m_threadContext.sync.videoFrameWait = false;
1037	} else {
1038		m_threadContext.sync.audioWait = m_audioSync;
1039		m_threadContext.sync.videoFrameWait = m_videoSync;
1040	}
1041	m_sync = enable;
1042}
1043void GameController::setAVStream(mAVStream* stream) {
1044	threadInterrupt();
1045	m_stream = stream;
1046	if (isLoaded()) {
1047		m_threadContext.core->setAVStream(m_threadContext.core, stream);
1048	}
1049	threadContinue();
1050}
1051
1052void GameController::clearAVStream() {
1053	threadInterrupt();
1054	m_stream = nullptr;
1055	if (isLoaded()) {
1056		m_threadContext.core->setAVStream(m_threadContext.core, nullptr);
1057	}
1058	threadContinue();
1059}
1060
1061#ifdef USE_PNG
1062void GameController::screenshot() {
1063	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
1064		mCoreTakeScreenshot(context->core);
1065	});
1066}
1067#endif
1068
1069void GameController::reloadAudioDriver() {
1070	int samples = 0;
1071	unsigned sampleRate = 0;
1072	if (m_audioProcessor) {
1073		QMetaObject::invokeMethod(m_audioProcessor, "pause", Qt::BlockingQueuedConnection);
1074		samples = m_audioProcessor->getBufferSamples();
1075		sampleRate = m_audioProcessor->sampleRate();
1076		delete m_audioProcessor;
1077	}
1078	m_audioProcessor = AudioProcessor::create();
1079	if (samples) {
1080		m_audioProcessor->setBufferSamples(samples);
1081	}
1082	if (sampleRate) {
1083		m_audioProcessor->requestSampleRate(sampleRate);
1084	}
1085	m_audioProcessor->moveToThread(m_audioThread);
1086	connect(this, SIGNAL(gamePaused(mCoreThread*)), m_audioProcessor, SLOT(pause()));
1087	connect(this, SIGNAL(gameStarted(mCoreThread*, const QString&)), m_audioProcessor, SLOT(setInput(mCoreThread*)));
1088	if (isLoaded()) {
1089		m_audioProcessor->setInput(&m_threadContext);
1090		startAudio();
1091	}
1092}
1093
1094void GameController::setSaveStateExtdata(int flags) {
1095	m_saveStateFlags = flags;
1096}
1097
1098void GameController::setLoadStateExtdata(int flags) {
1099	m_loadStateFlags = flags;
1100}
1101
1102void GameController::setLuminanceValue(uint8_t value) {
1103	m_luxValue = value;
1104	value = std::max<int>(value - 0x16, 0);
1105	m_luxLevel = 10;
1106	for (int i = 0; i < 10; ++i) {
1107		if (value < GBA_LUX_LEVELS[i]) {
1108			m_luxLevel = i;
1109			break;
1110		}
1111	}
1112	emit luminanceValueChanged(m_luxValue);
1113}
1114
1115void GameController::setLuminanceLevel(int level) {
1116	int value = 0x16;
1117	level = std::max(0, std::min(10, level));
1118	if (level > 0) {
1119		value += GBA_LUX_LEVELS[level - 1];
1120	}
1121	setLuminanceValue(value);
1122}
1123
1124void GameController::setRealTime() {
1125	m_rtc.override = RTC_NO_OVERRIDE;
1126}
1127
1128void GameController::setFixedTime(const QDateTime& time) {
1129	m_rtc.override = RTC_FIXED;
1130	m_rtc.value = time.toMSecsSinceEpoch() / 1000;
1131}
1132
1133void GameController::setFakeEpoch(const QDateTime& time) {
1134	m_rtc.override = RTC_FAKE_EPOCH;
1135	m_rtc.value = time.toMSecsSinceEpoch() / 1000;
1136}
1137
1138void GameController::updateKeys() {
1139	int activeKeys = m_activeKeys;
1140	activeKeys |= m_activeButtons;
1141	activeKeys &= ~m_inactiveKeys;
1142	if (isLoaded()) {
1143		m_threadContext.core->setKeys(m_threadContext.core, activeKeys);
1144	}
1145}
1146
1147void GameController::redoSamples(int samples) {
1148	if (m_threadContext.core) {
1149		m_threadContext.core->setAudioBufferSize(m_threadContext.core, samples);
1150	}
1151	QMetaObject::invokeMethod(m_audioProcessor, "inputParametersChanged");
1152}
1153
1154void GameController::setLogLevel(int levels) {
1155	threadInterrupt();
1156	m_logLevels = levels;
1157	threadContinue();
1158}
1159
1160void GameController::enableLogLevel(int levels) {
1161	threadInterrupt();
1162	m_logLevels |= levels;
1163	threadContinue();
1164}
1165
1166void GameController::disableLogLevel(int levels) {
1167	threadInterrupt();
1168	m_logLevels &= ~levels;
1169	threadContinue();
1170}
1171
1172void GameController::pollEvents() {
1173	if (!m_inputController) {
1174		return;
1175	}
1176
1177	m_activeButtons = m_inputController->pollEvents();
1178	updateKeys();
1179}
1180
1181void GameController::updateAutofire() {
1182	// TODO: Move all key events onto the CPU thread...somehow
1183	for (int k = 0; k < GBA_KEY_MAX; ++k) {
1184		if (!m_autofire[k]) {
1185			continue;
1186		}
1187		m_autofireStatus[k] ^= 1;
1188		if (m_autofireStatus[k]) {
1189			keyPressed(k);
1190		} else {
1191			keyReleased(k);
1192		}
1193	}
1194}