all repos — mgba @ 890b063ea5e3f7e4a6e742a57619c7ef959d8a0e

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