all repos — mgba @ c8db38f93b391b53d4b323122720b01b371823b2

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
 578	QMetaObject::invokeMethod(m_audioProcessor, "pause", Qt::BlockingQueuedConnection);
 579	mCoreThreadEnd(&m_threadContext);
 580}
 581
 582void GameController::cleanGame() {
 583	if (!m_gameOpen || mCoreThreadIsActive(&m_threadContext)) {
 584		return;
 585	}
 586	mCoreThreadJoin(&m_threadContext);
 587
 588	delete[] m_drawContext;
 589	delete[] m_frontBuffer;
 590
 591	m_threadContext.core->deinit(m_threadContext.core);
 592	m_gameOpen = false;
 593}
 594
 595void GameController::crashGame(const QString& crashMessage) {
 596	closeGame();
 597	emit gameCrashed(crashMessage);
 598}
 599
 600bool GameController::isPaused() {
 601	if (!m_gameOpen) {
 602		return false;
 603	}
 604	return mCoreThreadIsPaused(&m_threadContext);
 605}
 606
 607mPlatform GameController::platform() const {
 608	if (!m_gameOpen) {
 609		return PLATFORM_NONE;
 610	}
 611	return m_threadContext.core->platform(m_threadContext.core);
 612}
 613
 614QSize GameController::screenDimensions() const {
 615	if (!m_gameOpen) {
 616		return QSize();
 617	}
 618	unsigned width, height;
 619	m_threadContext.core->desiredVideoDimensions(m_threadContext.core, &width, &height);
 620
 621	return QSize(width, height);
 622}
 623
 624void GameController::setPaused(bool paused) {
 625	if (!isLoaded() || paused == mCoreThreadIsPaused(&m_threadContext)) {
 626		return;
 627	}
 628	m_wasPaused = paused;
 629	if (paused) {
 630		m_pauseAfterFrame.testAndSetRelaxed(false, true);
 631	} else {
 632		mCoreThreadUnpause(&m_threadContext);
 633		startAudio();
 634		emit gameUnpaused(&m_threadContext);
 635	}
 636}
 637
 638void GameController::reset() {
 639	if (!m_gameOpen) {
 640		return;
 641	}
 642	bool wasPaused = isPaused();
 643	setPaused(false);
 644	threadInterrupt();
 645	mCoreThreadReset(&m_threadContext);
 646	if (wasPaused) {
 647		setPaused(true);
 648	}
 649	threadContinue();
 650}
 651
 652void GameController::threadInterrupt() {
 653	if (m_gameOpen) {
 654		mCoreThreadInterrupt(&m_threadContext);
 655	}
 656}
 657
 658void GameController::threadContinue() {
 659	if (m_gameOpen) {
 660		mCoreThreadContinue(&m_threadContext);
 661	}
 662}
 663
 664void GameController::frameAdvance() {
 665	if (m_pauseAfterFrame.testAndSetRelaxed(false, true)) {
 666		setPaused(false);
 667	}
 668}
 669
 670void GameController::setRewind(bool enable, int capacity) {
 671	if (m_gameOpen) {
 672		threadInterrupt();
 673		if (m_threadContext.core->opts.rewindEnable && m_threadContext.core->opts.rewindBufferCapacity > 0) {
 674			mCoreRewindContextDeinit(&m_threadContext.rewind);
 675		}
 676		m_threadContext.core->opts.rewindEnable = enable;
 677		m_threadContext.core->opts.rewindBufferCapacity = capacity;
 678		if (enable && capacity > 0) {
 679			mCoreRewindContextInit(&m_threadContext.rewind, capacity);
 680		}
 681		threadContinue();
 682	}
 683}
 684
 685void GameController::rewind(int states) {
 686	threadInterrupt();
 687	if (!states) {
 688		states = INT_MAX;
 689	}
 690	for (int i = 0; i < states; ++i) {
 691		if (!mCoreRewindRestore(&m_threadContext.rewind, m_threadContext.core)) {
 692			break;
 693		}
 694	}
 695	threadContinue();
 696	emit frameAvailable(m_drawContext);
 697	emit rewound(&m_threadContext);
 698}
 699
 700void GameController::startRewinding() {
 701	if (!isLoaded()) {
 702		return;
 703	}
 704	if (!m_threadContext.core->opts.rewindEnable) {
 705		return;
 706	}
 707	if (m_multiplayer && m_multiplayer->attached() > 1) {
 708		return;
 709	}
 710	if (m_wasPaused) {
 711		setPaused(false);
 712		m_wasPaused = true;
 713	}
 714	mCoreThreadSetRewinding(&m_threadContext, true);
 715}
 716
 717void GameController::stopRewinding() {
 718	if (!isLoaded()) {
 719		return;
 720	}
 721	mCoreThreadSetRewinding(&m_threadContext, false);
 722	bool signalsBlocked = blockSignals(true);
 723	setPaused(m_wasPaused);
 724	blockSignals(signalsBlocked);
 725}
 726
 727void GameController::keyPressed(int key) {
 728	int mappedKey = 1 << key;
 729	m_activeKeys |= mappedKey;
 730	if (!m_inputController->allowOpposing()) {
 731		if ((m_activeKeys & 0x30) == 0x30) {
 732			m_inactiveKeys |= mappedKey ^ 0x30;
 733			m_activeKeys ^= mappedKey ^ 0x30;
 734		}
 735		if ((m_activeKeys & 0xC0) == 0xC0) {
 736			m_inactiveKeys |= mappedKey ^ 0xC0;
 737			m_activeKeys ^= mappedKey ^ 0xC0;
 738		}
 739	}
 740	updateKeys();
 741}
 742
 743void GameController::keyReleased(int key) {
 744	int mappedKey = 1 << key;
 745	m_activeKeys &= ~mappedKey;
 746	if (!m_inputController->allowOpposing()) {
 747		if (mappedKey & 0x30) {
 748			m_activeKeys |= m_inactiveKeys & (0x30 ^ mappedKey);
 749			m_inactiveKeys &= ~0x30;
 750		}
 751		if (mappedKey & 0xC0) {
 752			m_activeKeys |= m_inactiveKeys & (0xC0 ^ mappedKey);
 753			m_inactiveKeys &= ~0xC0;
 754		}
 755	}
 756	updateKeys();
 757}
 758
 759void GameController::clearKeys() {
 760	m_activeKeys = 0;
 761	m_inactiveKeys = 0;
 762	updateKeys();
 763}
 764
 765void GameController::setAutofire(int key, bool enable) {
 766	if (key >= GBA_KEY_MAX || key < 0) {
 767		return;
 768	}
 769
 770	if (!enable && m_autofireStatus[key]) {
 771		keyReleased(key);
 772	}
 773
 774	m_autofire[key] = enable;
 775	m_autofireStatus[key] = 0;
 776}
 777
 778void GameController::setAudioBufferSamples(int samples) {
 779	if (m_audioProcessor) {
 780		threadInterrupt();
 781		redoSamples(samples);
 782		threadContinue();
 783		QMetaObject::invokeMethod(m_audioProcessor, "setBufferSamples", Qt::BlockingQueuedConnection, Q_ARG(int, samples));
 784	}
 785}
 786
 787void GameController::setAudioSampleRate(unsigned rate) {
 788	if (!rate) {
 789		return;
 790	}
 791	if (m_audioProcessor) {
 792		threadInterrupt();
 793		redoSamples(m_audioProcessor->getBufferSamples());
 794		threadContinue();
 795		QMetaObject::invokeMethod(m_audioProcessor, "requestSampleRate", Q_ARG(unsigned, rate));
 796	}
 797}
 798
 799void GameController::setAudioChannelEnabled(int channel, bool enable) {
 800	if (channel > 5 || channel < 0) {
 801		return;
 802	}
 803#ifdef M_CORE_GBA
 804	GBA* gba = static_cast<GBA*>(m_threadContext.core->board);
 805#endif
 806#ifdef M_CORE_GB
 807	GB* gb = static_cast<GB*>(m_threadContext.core->board);
 808#endif
 809	m_audioChannels[channel] = enable;
 810	if (isLoaded()) {
 811		switch (channel) {
 812		case 0:
 813		case 1:
 814		case 2:
 815		case 3:
 816			switch (m_threadContext.core->platform(m_threadContext.core)) {
 817#ifdef M_CORE_GBA
 818			case PLATFORM_GBA:
 819				gba->audio.psg.forceDisableCh[channel] = !enable;
 820				break;
 821#endif
 822#ifdef M_CORE_GB
 823			case PLATFORM_GB:
 824				gb->audio.forceDisableCh[channel] = !enable;
 825				break;
 826#endif
 827			default:
 828				break;
 829			}
 830			break;
 831#ifdef M_CORE_GBA
 832		case 4:
 833			if (m_threadContext.core->platform(m_threadContext.core) == PLATFORM_GBA) {
 834				gba->audio.forceDisableChA = !enable;
 835			}
 836			break;
 837		case 5:
 838			if (m_threadContext.core->platform(m_threadContext.core) == PLATFORM_GBA) {
 839				gba->audio.forceDisableChB = !enable;
 840			}
 841			break;
 842#endif
 843		}
 844	}
 845}
 846
 847void GameController::startAudio() {
 848	bool started = false;
 849	QMetaObject::invokeMethod(m_audioProcessor, "start", Qt::BlockingQueuedConnection, Q_RETURN_ARG(bool, started));
 850	if (!started) {
 851		LOG(QT, ERROR) << tr("Failed to start audio processor");
 852		// Don't freeze!
 853		m_audioSync = false;
 854		m_videoSync = true;
 855		m_threadContext.sync.audioWait = false;
 856		m_threadContext.sync.videoFrameWait = true;
 857	}
 858}
 859
 860void GameController::setVideoLayerEnabled(int layer, bool enable) {
 861	if (layer > 4 || layer < 0) {
 862		return;
 863	}
 864	m_videoLayers[layer] = enable;
 865#ifdef M_CORE_GBA
 866	if (isLoaded() && m_threadContext.core->platform(m_threadContext.core) == PLATFORM_GBA) {
 867		GBA* gba = static_cast<GBA*>(m_threadContext.core->board);
 868		switch (layer) {
 869		case 0:
 870		case 1:
 871		case 2:
 872		case 3:
 873			gba->video.renderer->disableBG[layer] = !enable;
 874			break;
 875		case 4:
 876			gba->video.renderer->disableOBJ = !enable;
 877			break;
 878		}
 879	}
 880#endif
 881}
 882
 883void GameController::setFPSTarget(float fps) {
 884	threadInterrupt();
 885	m_fpsTarget = fps;
 886	m_threadContext.sync.fpsTarget = fps;
 887	if (m_turbo && m_turboSpeed > 0) {
 888		m_threadContext.sync.fpsTarget *= m_turboSpeed;
 889	}
 890	if (m_audioProcessor) {
 891		redoSamples(m_audioProcessor->getBufferSamples());
 892	}
 893	threadContinue();
 894}
 895
 896void GameController::setUseBIOS(bool use) {
 897	if (use == m_useBios) {
 898		return;
 899	}
 900	m_useBios = use;
 901	if (m_gameOpen) {
 902		closeGame();
 903		openGame();
 904	}
 905}
 906
 907void GameController::loadState(int slot) {
 908	if (m_fname.isEmpty()) {
 909		// We're in the BIOS
 910		return;
 911	}
 912	if (slot > 0 && slot != m_stateSlot) {
 913		m_stateSlot = slot;
 914		m_backupSaveState.clear();
 915	}
 916	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 917		GameController* controller = static_cast<GameController*>(context->userData);
 918		if (!controller->m_backupLoadState) {
 919			controller->m_backupLoadState = VFileMemChunk(nullptr, 0);
 920		}
 921		mCoreLoadStateNamed(context->core, controller->m_backupLoadState, controller->m_saveStateFlags);
 922		if (mCoreLoadState(context->core, controller->m_stateSlot, controller->m_loadStateFlags)) {
 923			controller->frameAvailable(controller->m_drawContext);
 924			controller->stateLoaded(context);
 925		}
 926	});
 927}
 928
 929void GameController::saveState(int slot) {
 930	if (m_fname.isEmpty()) {
 931		// We're in the BIOS
 932		return;
 933	}
 934	if (slot > 0) {
 935		m_stateSlot = slot;
 936	}
 937	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 938		GameController* controller = static_cast<GameController*>(context->userData);
 939		VFile* vf = mCoreGetState(context->core, controller->m_stateSlot, false);
 940		if (vf) {
 941			controller->m_backupSaveState.resize(vf->size(vf));
 942			vf->read(vf, controller->m_backupSaveState.data(), controller->m_backupSaveState.size());
 943			vf->close(vf);
 944		}
 945		mCoreSaveState(context->core, controller->m_stateSlot, controller->m_saveStateFlags);
 946	});
 947}
 948
 949void GameController::loadBackupState() {
 950	if (!m_backupLoadState) {
 951		return;
 952	}
 953
 954	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 955		GameController* controller = static_cast<GameController*>(context->userData);
 956		controller->m_backupLoadState->seek(controller->m_backupLoadState, 0, SEEK_SET);
 957		if (mCoreLoadStateNamed(context->core, controller->m_backupLoadState, controller->m_loadStateFlags)) {
 958			mLOG(STATUS, INFO, "Undid state load");
 959			controller->frameAvailable(controller->m_drawContext);
 960			controller->stateLoaded(context);
 961		}
 962		controller->m_backupLoadState->close(controller->m_backupLoadState);
 963		controller->m_backupLoadState = nullptr;
 964	});
 965}
 966
 967void GameController::saveBackupState() {
 968	if (m_backupSaveState.isEmpty()) {
 969		return;
 970	}
 971
 972	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 973		GameController* controller = static_cast<GameController*>(context->userData);
 974		VFile* vf = mCoreGetState(context->core, controller->m_stateSlot, true);
 975		if (vf) {
 976			vf->write(vf, controller->m_backupSaveState.constData(), controller->m_backupSaveState.size());
 977			vf->close(vf);
 978			mLOG(STATUS, INFO, "Undid state save");
 979		}
 980		controller->m_backupSaveState.clear();
 981	});
 982}
 983
 984void GameController::setTurbo(bool set, bool forced) {
 985	if (m_turboForced && !forced) {
 986		return;
 987	}
 988	if (m_turbo == set && m_turboForced == (set && forced)) {
 989		// Don't interrupt the thread if we don't need to
 990		return;
 991	}
 992	if (!m_sync) {
 993		return;
 994	}
 995	m_turbo = set;
 996	m_turboForced = set && forced;
 997	enableTurbo();
 998}
 999
1000void GameController::setTurboSpeed(float ratio) {
1001	m_turboSpeed = ratio;
1002	enableTurbo();
1003}
1004
1005void GameController::enableTurbo() {
1006	threadInterrupt();
1007	bool shouldRedoSamples = false;
1008	if (!m_turbo) {
1009		shouldRedoSamples = m_threadContext.sync.fpsTarget != m_fpsTarget;
1010		m_threadContext.sync.fpsTarget = m_fpsTarget;
1011		m_threadContext.sync.audioWait = m_audioSync;
1012		m_threadContext.sync.videoFrameWait = m_videoSync;
1013	} else if (m_turboSpeed <= 0) {
1014		shouldRedoSamples = m_threadContext.sync.fpsTarget != m_fpsTarget;
1015		m_threadContext.sync.fpsTarget = m_fpsTarget;
1016		m_threadContext.sync.audioWait = false;
1017		m_threadContext.sync.videoFrameWait = false;
1018	} else {
1019		shouldRedoSamples = m_threadContext.sync.fpsTarget != m_fpsTarget * m_turboSpeed;
1020		m_threadContext.sync.fpsTarget = m_fpsTarget * m_turboSpeed;
1021		m_threadContext.sync.audioWait = true;
1022		m_threadContext.sync.videoFrameWait = false;
1023	}
1024	if (m_audioProcessor && shouldRedoSamples) {
1025		redoSamples(m_audioProcessor->getBufferSamples());
1026	}
1027	threadContinue();
1028}
1029
1030void GameController::setSync(bool enable) {
1031	m_turbo = false;
1032	m_turboForced = false;
1033	if (!enable) {
1034		m_threadContext.sync.audioWait = false;
1035		m_threadContext.sync.videoFrameWait = false;
1036	} else {
1037		m_threadContext.sync.audioWait = m_audioSync;
1038		m_threadContext.sync.videoFrameWait = m_videoSync;
1039	}
1040	m_sync = enable;
1041}
1042void GameController::setAVStream(mAVStream* stream) {
1043	threadInterrupt();
1044	m_stream = stream;
1045	if (isLoaded()) {
1046		m_threadContext.core->setAVStream(m_threadContext.core, stream);
1047	}
1048	threadContinue();
1049}
1050
1051void GameController::clearAVStream() {
1052	threadInterrupt();
1053	m_stream = nullptr;
1054	if (isLoaded()) {
1055		m_threadContext.core->setAVStream(m_threadContext.core, nullptr);
1056	}
1057	threadContinue();
1058}
1059
1060#ifdef USE_PNG
1061void GameController::screenshot() {
1062	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
1063		mCoreTakeScreenshot(context->core);
1064	});
1065}
1066#endif
1067
1068void GameController::reloadAudioDriver() {
1069	int samples = 0;
1070	unsigned sampleRate = 0;
1071	if (m_audioProcessor) {
1072		QMetaObject::invokeMethod(m_audioProcessor, "pause", Qt::BlockingQueuedConnection);
1073		samples = m_audioProcessor->getBufferSamples();
1074		sampleRate = m_audioProcessor->sampleRate();
1075		delete m_audioProcessor;
1076	}
1077	m_audioProcessor = AudioProcessor::create();
1078	if (samples) {
1079		m_audioProcessor->setBufferSamples(samples);
1080	}
1081	if (sampleRate) {
1082		m_audioProcessor->requestSampleRate(sampleRate);
1083	}
1084	m_audioProcessor->moveToThread(m_audioThread);
1085	connect(this, SIGNAL(gamePaused(mCoreThread*)), m_audioProcessor, SLOT(pause()));
1086	connect(this, SIGNAL(gameStarted(mCoreThread*, const QString&)), m_audioProcessor, SLOT(setInput(mCoreThread*)));
1087	if (isLoaded()) {
1088		m_audioProcessor->setInput(&m_threadContext);
1089		startAudio();
1090	}
1091}
1092
1093void GameController::setSaveStateExtdata(int flags) {
1094	m_saveStateFlags = flags;
1095}
1096
1097void GameController::setLoadStateExtdata(int flags) {
1098	m_loadStateFlags = flags;
1099}
1100
1101void GameController::setLuminanceValue(uint8_t value) {
1102	m_luxValue = value;
1103	value = std::max<int>(value - 0x16, 0);
1104	m_luxLevel = 10;
1105	for (int i = 0; i < 10; ++i) {
1106		if (value < GBA_LUX_LEVELS[i]) {
1107			m_luxLevel = i;
1108			break;
1109		}
1110	}
1111	emit luminanceValueChanged(m_luxValue);
1112}
1113
1114void GameController::setLuminanceLevel(int level) {
1115	int value = 0x16;
1116	level = std::max(0, std::min(10, level));
1117	if (level > 0) {
1118		value += GBA_LUX_LEVELS[level - 1];
1119	}
1120	setLuminanceValue(value);
1121}
1122
1123void GameController::setRealTime() {
1124	m_rtc.override = RTC_NO_OVERRIDE;
1125}
1126
1127void GameController::setFixedTime(const QDateTime& time) {
1128	m_rtc.override = RTC_FIXED;
1129	m_rtc.value = time.toMSecsSinceEpoch() / 1000;
1130}
1131
1132void GameController::setFakeEpoch(const QDateTime& time) {
1133	m_rtc.override = RTC_FAKE_EPOCH;
1134	m_rtc.value = time.toMSecsSinceEpoch() / 1000;
1135}
1136
1137void GameController::updateKeys() {
1138	int activeKeys = m_activeKeys;
1139	activeKeys |= m_activeButtons;
1140	activeKeys &= ~m_inactiveKeys;
1141	if (isLoaded()) {
1142		m_threadContext.core->setKeys(m_threadContext.core, activeKeys);
1143	}
1144}
1145
1146void GameController::redoSamples(int samples) {
1147	if (m_threadContext.core) {
1148		m_threadContext.core->setAudioBufferSize(m_threadContext.core, samples);
1149	}
1150	QMetaObject::invokeMethod(m_audioProcessor, "inputParametersChanged");
1151}
1152
1153void GameController::setLogLevel(int levels) {
1154	threadInterrupt();
1155	m_logLevels = levels;
1156	threadContinue();
1157}
1158
1159void GameController::enableLogLevel(int levels) {
1160	threadInterrupt();
1161	m_logLevels |= levels;
1162	threadContinue();
1163}
1164
1165void GameController::disableLogLevel(int levels) {
1166	threadInterrupt();
1167	m_logLevels &= ~levels;
1168	threadContinue();
1169}
1170
1171void GameController::pollEvents() {
1172	if (!m_inputController) {
1173		return;
1174	}
1175
1176	m_activeButtons = m_inputController->pollEvents();
1177	updateKeys();
1178}
1179
1180void GameController::updateAutofire() {
1181	// TODO: Move all key events onto the CPU thread...somehow
1182	for (int k = 0; k < GBA_KEY_MAX; ++k) {
1183		if (!m_autofire[k]) {
1184			continue;
1185		}
1186		m_autofireStatus[k] ^= 1;
1187		if (m_autofireStatus[k]) {
1188			keyPressed(k);
1189		} else {
1190			keyReleased(k);
1191		}
1192	}
1193}