all repos — mgba @ 59b4d22833281f2758be30b8cedea35338daff25

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