all repos — mgba @ 6af9a742bda66c3785cd13f76895558eeac77725

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 <QDateTime>
  15#include <QThread>
  16
  17#include <ctime>
  18
  19extern "C" {
  20#include "gba/audio.h"
  21#include "gba/context/config.h"
  22#include "gba/context/directories.h"
  23#include "gba/gba.h"
  24#include "gba/serialize.h"
  25#include "gba/sharkport.h"
  26#include "gba/renderers/video-software.h"
  27#include "util/vfs.h"
  28}
  29
  30using namespace QGBA;
  31using namespace std;
  32
  33GameController::GameController(QObject* parent)
  34	: QObject(parent)
  35	, m_drawContext(new uint32_t[VIDEO_VERTICAL_PIXELS * VIDEO_HORIZONTAL_PIXELS])
  36	, m_frontBuffer(new uint32_t[VIDEO_VERTICAL_PIXELS * VIDEO_HORIZONTAL_PIXELS])
  37	, m_threadContext()
  38	, m_activeKeys(0)
  39	, m_inactiveKeys(0)
  40	, m_logLevels(0)
  41	, m_gameOpen(false)
  42	, m_audioThread(new QThread(this))
  43	, m_audioProcessor(AudioProcessor::create())
  44	, m_pauseAfterFrame(false)
  45	, m_videoSync(VIDEO_SYNC)
  46	, m_audioSync(AUDIO_SYNC)
  47	, m_fpsTarget(-1)
  48	, m_turbo(false)
  49	, m_turboForced(false)
  50	, m_turboSpeed(-1)
  51	, m_wasPaused(false)
  52	, m_audioChannels{ true, true, true, true, true, true }
  53	, m_videoLayers{ true, true, true, true, true }
  54	, m_autofire{}
  55	, m_autofireStatus{}
  56	, m_inputController(nullptr)
  57	, m_multiplayer(nullptr)
  58	, m_stateSlot(1)
  59	, m_backupLoadState(nullptr)
  60	, m_backupSaveState(nullptr)
  61	, m_saveStateFlags(SAVESTATE_SCREENSHOT | SAVESTATE_SAVEDATA | SAVESTATE_CHEATS)
  62	, m_loadStateFlags(SAVESTATE_SCREENSHOT)
  63{
  64	m_renderer = new GBAVideoSoftwareRenderer;
  65	GBAVideoSoftwareRendererCreate(m_renderer);
  66	m_renderer->outputBuffer = (color_t*) m_drawContext;
  67	m_renderer->outputBufferStride = VIDEO_HORIZONTAL_PIXELS;
  68
  69	GBACheatDeviceCreate(&m_cheatDevice);
  70
  71	m_threadContext.state = THREAD_INITIALIZED;
  72	m_threadContext.debugger = 0;
  73	m_threadContext.frameskip = 0;
  74	m_threadContext.bios = 0;
  75	m_threadContext.renderer = &m_renderer->d;
  76	m_threadContext.userData = this;
  77	m_threadContext.rewindBufferCapacity = 0;
  78	m_threadContext.cheats = &m_cheatDevice;
  79	m_threadContext.logLevel = GBA_LOG_ALL;
  80	GBADirectorySetInit(&m_threadContext.dirs);
  81
  82	m_lux.p = this;
  83	m_lux.sample = [](GBALuminanceSource* context) {
  84		GameControllerLux* lux = static_cast<GameControllerLux*>(context);
  85		lux->value = 0xFF - lux->p->m_luxValue;
  86	};
  87
  88	m_lux.readLuminance = [](GBALuminanceSource* context) {
  89		GameControllerLux* lux = static_cast<GameControllerLux*>(context);
  90		return lux->value;
  91	};
  92	setLuminanceLevel(0);
  93
  94	m_threadContext.startCallback = [](GBAThread* context) {
  95		GameController* controller = static_cast<GameController*>(context->userData);
  96		if (controller->m_audioProcessor) {
  97			controller->m_audioProcessor->setInput(context);
  98		}
  99		context->gba->luminanceSource = &controller->m_lux;
 100		GBARTCGenericSourceInit(&controller->m_rtc, context->gba);
 101		context->gba->rtcSource = &controller->m_rtc.d;
 102		context->gba->rumble = controller->m_inputController->rumble();
 103		context->gba->rotationSource = controller->m_inputController->rotationSource();
 104		context->gba->audio.forceDisableCh[0] = !controller->m_audioChannels[0];
 105		context->gba->audio.forceDisableCh[1] = !controller->m_audioChannels[1];
 106		context->gba->audio.forceDisableCh[2] = !controller->m_audioChannels[2];
 107		context->gba->audio.forceDisableCh[3] = !controller->m_audioChannels[3];
 108		context->gba->audio.forceDisableChA = !controller->m_audioChannels[4];
 109		context->gba->audio.forceDisableChB = !controller->m_audioChannels[5];
 110		context->gba->video.renderer->disableBG[0] = !controller->m_videoLayers[0];
 111		context->gba->video.renderer->disableBG[1] = !controller->m_videoLayers[1];
 112		context->gba->video.renderer->disableBG[2] = !controller->m_videoLayers[2];
 113		context->gba->video.renderer->disableBG[3] = !controller->m_videoLayers[3];
 114		context->gba->video.renderer->disableOBJ = !controller->m_videoLayers[4];
 115		controller->m_fpsTarget = context->fpsTarget;
 116
 117		if (context->dirs.state && GBALoadState(context, context->dirs.state, 0, controller->m_loadStateFlags)) {
 118			VFile* vf = GBAGetState(context->gba, context->dirs.state, 0, true);
 119			if (vf) {
 120				vf->truncate(vf, 0);
 121			}
 122		}
 123		QMetaObject::invokeMethod(controller, "gameStarted", Q_ARG(GBAThread*, context));
 124	};
 125
 126	m_threadContext.cleanCallback = [](GBAThread* context) {
 127		GameController* controller = static_cast<GameController*>(context->userData);
 128		QMetaObject::invokeMethod(controller, "gameStopped", Q_ARG(GBAThread*, context));
 129	};
 130
 131	m_threadContext.frameCallback = [](GBAThread* context) {
 132		GameController* controller = static_cast<GameController*>(context->userData);
 133		memcpy(controller->m_frontBuffer, controller->m_drawContext, VIDEO_VERTICAL_PIXELS * VIDEO_HORIZONTAL_PIXELS * BYTES_PER_PIXEL);
 134		QMetaObject::invokeMethod(controller, "frameAvailable", Q_ARG(const uint32_t*, controller->m_frontBuffer));
 135		if (controller->m_pauseAfterFrame.testAndSetAcquire(true, false)) {
 136			GBAThreadPauseFromThread(context);
 137			QMetaObject::invokeMethod(controller, "gamePaused", Q_ARG(GBAThread*, context));
 138		}
 139	};
 140
 141	m_threadContext.stopCallback = [](GBAThread* context) {
 142		if (!context) {
 143			return false;
 144		}
 145		GameController* controller = static_cast<GameController*>(context->userData);
 146		if (!GBASaveState(context, context->dirs.state, 0, controller->m_saveStateFlags)) {
 147			return false;
 148		}
 149		QMetaObject::invokeMethod(controller, "closeGame");
 150		return true;
 151	};
 152
 153	m_threadContext.logHandler = [](GBAThread* context, enum GBALogLevel level, const char* format, va_list args) {
 154		static const char* stubMessage = "Stub software interrupt: %02X";
 155		static const char* savestateMessage = "State %i loaded";
 156		static const char* savestateFailedMessage = "State %i failed to load";
 157		if (!context) {
 158			return;
 159		}
 160		GameController* controller = static_cast<GameController*>(context->userData);
 161		if (level == GBA_LOG_STUB && strncmp(stubMessage, format, strlen(stubMessage)) == 0) {
 162			va_list argc;
 163			va_copy(argc, args);
 164			int immediate = va_arg(argc, int);
 165			va_end(argc);
 166			QMetaObject::invokeMethod(controller, "unimplementedBiosCall", Q_ARG(int, immediate));
 167		} else if (level == GBA_LOG_STATUS) {
 168			// Slot 0 is reserved for suspend points
 169			if (strncmp(savestateMessage, format, strlen(savestateMessage)) == 0) {
 170				va_list argc;
 171				va_copy(argc, args);
 172				int slot = va_arg(argc, int);
 173				va_end(argc);
 174				if (slot == 0) {
 175					format = "Loaded suspend state";
 176				}
 177			} else if (strncmp(savestateFailedMessage, format, strlen(savestateFailedMessage)) == 0) {
 178				va_list argc;
 179				va_copy(argc, args);
 180				int slot = va_arg(argc, int);
 181				va_end(argc);
 182				if (slot == 0) {
 183					return;
 184				}
 185			}
 186		}
 187		if (level == GBA_LOG_FATAL) {
 188			QMetaObject::invokeMethod(controller, "crashGame", Q_ARG(const QString&, QString().vsprintf(format, args)));
 189		} else if (!(controller->m_logLevels & level)) {
 190			return;
 191		}
 192		QString message(QString().vsprintf(format, args));
 193		if (level == GBA_LOG_STATUS) {
 194			QMetaObject::invokeMethod(controller, "statusPosted", Q_ARG(const QString&, message));
 195		}
 196		QMetaObject::invokeMethod(controller, "postLog", Q_ARG(int, level), Q_ARG(const QString&, message));
 197	};
 198
 199	connect(&m_rewindTimer, &QTimer::timeout, [this]() {
 200		GBARewind(&m_threadContext, 1);
 201		emit frameAvailable(m_drawContext);
 202		emit rewound(&m_threadContext);
 203	});
 204	m_rewindTimer.setInterval(100);
 205
 206	m_audioThread->setObjectName("Audio Thread");
 207	m_audioThread->start(QThread::TimeCriticalPriority);
 208	m_audioProcessor->moveToThread(m_audioThread);
 209	connect(this, SIGNAL(gameStarted(GBAThread*)), m_audioProcessor, SLOT(start()));
 210	connect(this, SIGNAL(gamePaused(GBAThread*)), m_audioProcessor, SLOT(pause()));
 211	connect(this, SIGNAL(gameUnpaused(GBAThread*)), m_audioProcessor, SLOT(start()));
 212	connect(this, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(pollEvents()));
 213	connect(this, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(updateAutofire()));
 214}
 215
 216GameController::~GameController() {
 217	m_audioThread->quit();
 218	m_audioThread->wait();
 219	disconnect();
 220	clearMultiplayerController();
 221	closeGame();
 222	GBACheatDeviceDestroy(&m_cheatDevice);
 223	GBADirectorySetDeinit(&m_threadContext.dirs);
 224	delete m_renderer;
 225	delete[] m_drawContext;
 226	delete[] m_frontBuffer;
 227	delete m_backupLoadState;
 228}
 229
 230void GameController::setMultiplayerController(MultiplayerController* controller) {
 231	if (controller == m_multiplayer) {
 232		return;
 233	}
 234	clearMultiplayerController();
 235	m_multiplayer = controller;
 236	controller->attachGame(this);
 237}
 238
 239void GameController::clearMultiplayerController() {
 240	if (!m_multiplayer) {
 241		return;
 242	}
 243	m_multiplayer->detachGame(this);
 244	m_multiplayer = nullptr;
 245}
 246
 247void GameController::setOverride(const GBACartridgeOverride& override) {
 248	m_threadContext.override = override;
 249	m_threadContext.hasOverride = true;
 250}
 251
 252void GameController::setOptions(const GBAOptions* opts) {
 253	setFrameskip(opts->frameskip);
 254	setAudioSync(opts->audioSync);
 255	setVideoSync(opts->videoSync);
 256	setSkipBIOS(opts->skipBios);
 257	setUseBIOS(opts->useBios);
 258	setRewind(opts->rewindEnable, opts->rewindBufferCapacity, opts->rewindBufferInterval);
 259	setVolume(opts->volume);
 260	setMute(opts->mute);
 261
 262	threadInterrupt();
 263	GBADirectorySetMapOptions(&m_threadContext.dirs, opts);
 264	m_threadContext.idleOptimization = opts->idleOptimization;
 265	threadContinue();
 266}
 267
 268#ifdef USE_GDB_STUB
 269ARMDebugger* GameController::debugger() {
 270	return m_threadContext.debugger;
 271}
 272
 273void GameController::setDebugger(ARMDebugger* debugger) {
 274	threadInterrupt();
 275	if (m_threadContext.debugger && GBAThreadIsActive(&m_threadContext)) {
 276		GBADetachDebugger(m_threadContext.gba);
 277	}
 278	m_threadContext.debugger = debugger;
 279	if (m_threadContext.debugger && GBAThreadIsActive(&m_threadContext)) {
 280		GBAAttachDebugger(m_threadContext.gba, m_threadContext.debugger);
 281	}
 282	threadContinue();
 283}
 284#endif
 285
 286void GameController::loadGame(const QString& path) {
 287	closeGame();
 288	QFile file(path);
 289	if (!file.open(QIODevice::ReadOnly)) {
 290		postLog(GBA_LOG_ERROR, tr("Failed to open game file: %1").arg(path));
 291		return;
 292	}
 293	file.close();
 294
 295	m_fname = path;
 296	openGame();
 297}
 298
 299void GameController::bootBIOS() {
 300	closeGame();
 301	m_fname = QString();
 302	openGame(true);
 303}
 304
 305void GameController::openGame(bool biosOnly) {
 306	if (biosOnly && (!m_useBios || m_bios.isNull())) {
 307		return;
 308	}
 309
 310	m_gameOpen = true;
 311
 312	m_pauseAfterFrame = false;
 313
 314	if (m_turbo) {
 315		m_threadContext.sync.videoFrameWait = false;
 316		m_threadContext.sync.audioWait = false;
 317	} else {
 318		m_threadContext.sync.videoFrameWait = m_videoSync;
 319		m_threadContext.sync.audioWait = m_audioSync;
 320	}
 321
 322	m_threadContext.bootBios = biosOnly;
 323	if (biosOnly) {
 324		m_threadContext.fname = nullptr;
 325	} else {
 326		m_threadContext.fname = strdup(m_fname.toUtf8().constData());
 327		GBAThreadLoadROM(&m_threadContext, m_threadContext.fname);
 328	}
 329
 330	if (!m_bios.isNull() && m_useBios) {
 331		m_threadContext.bios = VFileDevice::open(m_bios, O_RDONLY);
 332	} else {
 333		m_threadContext.bios = nullptr;
 334	}
 335
 336	if (!m_patch.isNull()) {
 337		m_threadContext.patch = VFileDevice::open(m_patch, O_RDONLY);
 338	}
 339
 340	m_inputController->recalibrateAxes();
 341	memset(m_drawContext, 0xF8, VIDEO_VERTICAL_PIXELS * VIDEO_HORIZONTAL_PIXELS * 4);
 342
 343	if (!GBAThreadStart(&m_threadContext)) {
 344		m_gameOpen = false;
 345		emit gameFailed();
 346	}
 347}
 348
 349void GameController::loadBIOS(const QString& path) {
 350	if (m_bios == path) {
 351		return;
 352	}
 353	m_bios = path;
 354	if (m_gameOpen) {
 355		closeGame();
 356		openGame();
 357	}
 358}
 359
 360void GameController::yankPak() {
 361	if (!m_gameOpen) {
 362		return;
 363	}
 364	threadInterrupt();
 365	GBAYankROM(m_threadContext.gba);
 366	threadContinue();
 367}
 368
 369void GameController::replaceGame(const QString& path) {
 370	if (!m_gameOpen) {
 371		return;
 372	}
 373
 374	m_fname = path;
 375	threadInterrupt();
 376	m_threadContext.fname = strdup(m_fname.toLocal8Bit().constData());
 377	GBAThreadReplaceROM(&m_threadContext, m_threadContext.fname);
 378	threadContinue();
 379}
 380
 381void GameController::loadPatch(const QString& path) {
 382	if (m_gameOpen) {
 383		closeGame();
 384		m_patch = path;
 385		openGame();
 386	} else {
 387		m_patch = path;
 388	}
 389}
 390
 391void GameController::importSharkport(const QString& path) {
 392	if (!isLoaded()) {
 393		return;
 394	}
 395	VFile* vf = VFileDevice::open(path, O_RDONLY);
 396	if (!vf) {
 397		postLog(GBA_LOG_ERROR, tr("Failed to open snapshot file for reading: %1").arg(path));
 398		return;
 399	}
 400	threadInterrupt();
 401	GBASavedataImportSharkPort(m_threadContext.gba, vf, false);
 402	threadContinue();
 403	vf->close(vf);
 404}
 405
 406void GameController::exportSharkport(const QString& path) {
 407	if (!isLoaded()) {
 408		return;
 409	}
 410	VFile* vf = VFileDevice::open(path, O_WRONLY | O_CREAT | O_TRUNC);
 411	if (!vf) {
 412		postLog(GBA_LOG_ERROR, tr("Failed to open snapshot file for writing: %1").arg(path));
 413		return;
 414	}
 415	threadInterrupt();
 416	GBASavedataExportSharkPort(m_threadContext.gba, vf);
 417	threadContinue();
 418	vf->close(vf);
 419}
 420
 421void GameController::closeGame() {
 422	if (!m_gameOpen) {
 423		return;
 424	}
 425	m_rewindTimer.stop();
 426	if (GBAThreadIsPaused(&m_threadContext)) {
 427		GBAThreadUnpause(&m_threadContext);
 428	}
 429	m_audioProcessor->pause();
 430	GBAThreadEnd(&m_threadContext);
 431	GBAThreadJoin(&m_threadContext);
 432	if (m_threadContext.fname) {
 433		free(const_cast<char*>(m_threadContext.fname));
 434		m_threadContext.fname = nullptr;
 435	}
 436
 437	m_patch = QString();
 438
 439	for (size_t i = 0; i < GBACheatSetsSize(&m_cheatDevice.cheats); ++i) {
 440		GBACheatSet* set = *GBACheatSetsGetPointer(&m_cheatDevice.cheats, i);
 441		GBACheatSetDeinit(set);
 442		delete set;
 443	}
 444	GBACheatSetsClear(&m_cheatDevice.cheats);
 445
 446	m_gameOpen = false;
 447	emit gameStopped(&m_threadContext);
 448}
 449
 450void GameController::crashGame(const QString& crashMessage) {
 451	closeGame();
 452	emit gameCrashed(crashMessage);
 453	emit gameStopped(&m_threadContext);
 454}
 455
 456bool GameController::isPaused() {
 457	if (!m_gameOpen) {
 458		return false;
 459	}
 460	return GBAThreadIsPaused(&m_threadContext);
 461}
 462
 463void GameController::setPaused(bool paused) {
 464	if (!isLoaded() || m_rewindTimer.isActive() || paused == GBAThreadIsPaused(&m_threadContext)) {
 465		return;
 466	}
 467	if (paused) {
 468		m_pauseAfterFrame.testAndSetRelaxed(false, true);
 469	} else {
 470		GBAThreadUnpause(&m_threadContext);
 471		emit gameUnpaused(&m_threadContext);
 472	}
 473}
 474
 475void GameController::reset() {
 476	if (!m_gameOpen) {
 477		return;
 478	}
 479	bool wasPaused = isPaused();
 480	setPaused(false);
 481	GBAThreadReset(&m_threadContext);
 482	if (wasPaused) {
 483		setPaused(true);
 484	}
 485}
 486
 487void GameController::threadInterrupt() {
 488	if (m_gameOpen) {
 489		GBAThreadInterrupt(&m_threadContext);
 490	}
 491}
 492
 493void GameController::threadContinue() {
 494	if (m_gameOpen) {
 495		GBAThreadContinue(&m_threadContext);
 496	}
 497}
 498
 499void GameController::frameAdvance() {
 500	if (m_rewindTimer.isActive()) {
 501		return;
 502	}
 503	if (m_pauseAfterFrame.testAndSetRelaxed(false, true)) {
 504		setPaused(false);
 505	}
 506}
 507
 508void GameController::setRewind(bool enable, int capacity, int interval) {
 509	if (m_gameOpen) {
 510		threadInterrupt();
 511		GBARewindSettingsChanged(&m_threadContext, enable ? capacity : 0, enable ? interval : 0);
 512		threadContinue();
 513	} else {
 514		if (enable) {
 515			m_threadContext.rewindBufferInterval = interval;
 516			m_threadContext.rewindBufferCapacity = capacity;
 517		} else {
 518			m_threadContext.rewindBufferInterval = 0;
 519			m_threadContext.rewindBufferCapacity = 0;
 520		}
 521	}
 522}
 523
 524void GameController::rewind(int states) {
 525	threadInterrupt();
 526	if (!states) {
 527		GBARewindAll(&m_threadContext);
 528	} else {
 529		GBARewind(&m_threadContext, states);
 530	}
 531	threadContinue();
 532	emit frameAvailable(m_drawContext);
 533	emit rewound(&m_threadContext);
 534}
 535
 536void GameController::startRewinding() {
 537	if (!m_gameOpen || m_rewindTimer.isActive()) {
 538		return;
 539	}
 540	if (m_multiplayer && m_multiplayer->attached() > 1) {
 541		return;
 542	}
 543	m_wasPaused = isPaused();
 544	if (!GBAThreadIsPaused(&m_threadContext)) {
 545		GBAThreadPause(&m_threadContext);
 546	}
 547	m_rewindTimer.start();
 548}
 549
 550void GameController::stopRewinding() {
 551	if (!m_rewindTimer.isActive()) {
 552		return;
 553	}
 554	m_rewindTimer.stop();
 555	bool signalsBlocked = blockSignals(true);
 556	setPaused(m_wasPaused);
 557	blockSignals(signalsBlocked);
 558}
 559
 560void GameController::keyPressed(int key) {
 561	int mappedKey = 1 << key;
 562	m_activeKeys |= mappedKey;
 563	if (!m_inputController->allowOpposing()) {
 564		if ((m_activeKeys & 0x30) == 0x30) {
 565			m_inactiveKeys |= mappedKey ^ 0x30;
 566			m_activeKeys ^= mappedKey ^ 0x30;
 567		}
 568		if ((m_activeKeys & 0xC0) == 0xC0) {
 569			m_inactiveKeys |= mappedKey ^ 0xC0;
 570			m_activeKeys ^= mappedKey ^ 0xC0;
 571		}
 572	}
 573	updateKeys();
 574}
 575
 576void GameController::keyReleased(int key) {
 577	int mappedKey = 1 << key;
 578	m_activeKeys &= ~mappedKey;
 579	if (!m_inputController->allowOpposing()) {
 580		if (mappedKey & 0x30) {
 581			m_activeKeys |= m_inactiveKeys & (0x30 ^ mappedKey);
 582			m_inactiveKeys &= ~0x30;
 583		}
 584		if (mappedKey & 0xC0) {
 585			m_activeKeys |= m_inactiveKeys & (0xC0 ^ mappedKey);
 586			m_inactiveKeys &= ~0xC0;
 587		}
 588	}
 589	updateKeys();
 590}
 591
 592void GameController::clearKeys() {
 593	m_activeKeys = 0;
 594	m_inactiveKeys = 0;
 595	updateKeys();
 596}
 597
 598void GameController::setAutofire(int key, bool enable) {
 599	if (key >= GBA_KEY_MAX || key < 0) {
 600		return;
 601	}
 602	m_autofire[key] = enable;
 603	m_autofireStatus[key] = 0;
 604}
 605
 606void GameController::setAudioBufferSamples(int samples) {
 607	if (m_audioProcessor) {
 608		threadInterrupt();
 609		redoSamples(samples);
 610		threadContinue();
 611		QMetaObject::invokeMethod(m_audioProcessor, "setBufferSamples", Qt::BlockingQueuedConnection, Q_ARG(int, samples));
 612	}
 613}
 614
 615void GameController::setAudioSampleRate(unsigned rate) {
 616	if (!rate) {
 617		return;
 618	}
 619	if (m_audioProcessor) {
 620		threadInterrupt();
 621		redoSamples(m_audioProcessor->getBufferSamples());
 622		threadContinue();
 623		QMetaObject::invokeMethod(m_audioProcessor, "requestSampleRate", Q_ARG(unsigned, rate));
 624	}
 625}
 626
 627void GameController::setAudioChannelEnabled(int channel, bool enable) {
 628	if (channel > 5 || channel < 0) {
 629		return;
 630	}
 631	m_audioChannels[channel] = enable;
 632	if (isLoaded()) {
 633		switch (channel) {
 634		case 0:
 635		case 1:
 636		case 2:
 637		case 3:
 638			m_threadContext.gba->audio.forceDisableCh[channel] = !enable;
 639			break;
 640		case 4:
 641			m_threadContext.gba->audio.forceDisableChA = !enable;
 642			break;
 643		case 5:
 644			m_threadContext.gba->audio.forceDisableChB = !enable;
 645			break;
 646		}
 647	}
 648}
 649
 650void GameController::setVideoLayerEnabled(int layer, bool enable) {
 651	if (layer > 4 || layer < 0) {
 652		return;
 653	}
 654	m_videoLayers[layer] = enable;
 655	if (isLoaded()) {
 656		switch (layer) {
 657		case 0:
 658		case 1:
 659		case 2:
 660		case 3:
 661			m_threadContext.gba->video.renderer->disableBG[layer] = !enable;
 662			break;
 663		case 4:
 664			m_threadContext.gba->video.renderer->disableOBJ = !enable;
 665			break;
 666		}
 667	}
 668}
 669
 670void GameController::setFPSTarget(float fps) {
 671	threadInterrupt();
 672	m_fpsTarget = fps;
 673	m_threadContext.fpsTarget = fps;
 674	if (m_turbo && m_turboSpeed > 0) {
 675		m_threadContext.fpsTarget *= m_turboSpeed;
 676	}
 677	if (m_audioProcessor) {
 678		redoSamples(m_audioProcessor->getBufferSamples());
 679	}
 680	threadContinue();
 681}
 682
 683void GameController::setSkipBIOS(bool set) {
 684	threadInterrupt();
 685	m_threadContext.skipBios = set;
 686	threadContinue();
 687}
 688
 689void GameController::setUseBIOS(bool use) {
 690	if (use == m_useBios) {
 691		return;
 692	}
 693	m_useBios = use;
 694	if (m_gameOpen) {
 695		closeGame();
 696		openGame();
 697	}
 698}
 699
 700void GameController::loadState(int slot) {
 701	if (!m_threadContext.fname) {
 702		// We're in the BIOS
 703		return;
 704	}
 705	if (slot > 0 && slot != m_stateSlot) {
 706		m_stateSlot = slot;
 707		m_backupSaveState.clear();
 708	}
 709	GBARunOnThread(&m_threadContext, [](GBAThread* context) {
 710		GameController* controller = static_cast<GameController*>(context->userData);
 711		if (!controller->m_backupLoadState) {
 712			controller->m_backupLoadState = new GBASerializedState;
 713		}
 714		GBASerialize(context->gba, controller->m_backupLoadState);
 715		if (GBALoadState(context, context->dirs.state, controller->m_stateSlot, controller->m_loadStateFlags)) {
 716			controller->frameAvailable(controller->m_drawContext);
 717			controller->stateLoaded(context);
 718		}
 719	});
 720}
 721
 722void GameController::saveState(int slot) {
 723	if (!m_threadContext.fname) {
 724		// We're in the BIOS
 725		return;
 726	}
 727	if (slot > 0) {
 728		m_stateSlot = slot;
 729	}
 730	GBARunOnThread(&m_threadContext, [](GBAThread* context) {
 731		GameController* controller = static_cast<GameController*>(context->userData);
 732		VFile* vf = GBAGetState(context->gba, context->dirs.state, controller->m_stateSlot, false);
 733		if (vf) {
 734			controller->m_backupSaveState.resize(vf->size(vf));
 735			vf->read(vf, controller->m_backupSaveState.data(), controller->m_backupSaveState.size());
 736			vf->close(vf);
 737		}
 738		GBASaveState(context, context->dirs.state, controller->m_stateSlot, controller->m_saveStateFlags);
 739	});
 740}
 741
 742void GameController::loadBackupState() {
 743	if (!m_backupLoadState) {
 744		return;
 745	}
 746
 747	GBARunOnThread(&m_threadContext, [](GBAThread* context) {
 748		GameController* controller = static_cast<GameController*>(context->userData);
 749		if (GBADeserialize(context->gba, controller->m_backupLoadState)) {
 750			GBALog(context->gba, GBA_LOG_STATUS, "Undid state load");
 751			controller->frameAvailable(controller->m_drawContext);
 752			controller->stateLoaded(context);
 753		}
 754		delete controller->m_backupLoadState;
 755		controller->m_backupLoadState = nullptr;
 756	});
 757}
 758
 759void GameController::saveBackupState() {
 760	if (m_backupSaveState.isEmpty()) {
 761		return;
 762	}
 763
 764	GBARunOnThread(&m_threadContext, [](GBAThread* context) {
 765		GameController* controller = static_cast<GameController*>(context->userData);
 766		VFile* vf = GBAGetState(context->gba, context->dirs.state, controller->m_stateSlot, true);
 767		if (vf) {
 768			vf->write(vf, controller->m_backupSaveState.constData(), controller->m_backupSaveState.size());
 769			vf->close(vf);
 770			GBALog(context->gba, GBA_LOG_STATUS, "Undid state save");
 771		}
 772		controller->m_backupSaveState.clear();
 773	});
 774}
 775
 776void GameController::setVideoSync(bool set) {
 777	m_videoSync = set;
 778	if (!m_turbo) {
 779		threadInterrupt();
 780		m_threadContext.sync.videoFrameWait = set;
 781		threadContinue();
 782	}
 783}
 784
 785void GameController::setAudioSync(bool set) {
 786	m_audioSync = set;
 787	if (!m_turbo) {
 788		threadInterrupt();
 789		m_threadContext.sync.audioWait = set;
 790		threadContinue();
 791	}
 792}
 793
 794void GameController::setFrameskip(int skip) {
 795	threadInterrupt();
 796	m_threadContext.frameskip = skip;
 797	if (isLoaded()) {
 798		m_threadContext.gba->video.frameskip = skip;
 799	}
 800	threadContinue();
 801}
 802
 803void GameController::setVolume(int volume) {
 804	threadInterrupt();
 805	m_threadContext.volume = volume;
 806	if (isLoaded()) {
 807		m_threadContext.gba->audio.masterVolume = volume;
 808	}
 809	threadContinue();
 810}
 811
 812void GameController::setMute(bool mute) {
 813	threadInterrupt();
 814	m_threadContext.mute = mute;
 815	if (isLoaded()) {
 816		m_threadContext.gba->audio.masterVolume = mute ? 0 : m_threadContext.volume;
 817	}
 818	threadContinue();
 819}
 820
 821void GameController::setTurbo(bool set, bool forced) {
 822	if (m_turboForced && !forced) {
 823		return;
 824	}
 825	if (m_turbo == set && m_turboForced == forced) {
 826		// Don't interrupt the thread if we don't need to
 827		return;
 828	}
 829	m_turbo = set;
 830	m_turboForced = set && forced;
 831	enableTurbo();
 832}
 833
 834void GameController::setTurboSpeed(float ratio) {
 835	m_turboSpeed = ratio;
 836	enableTurbo();
 837}
 838
 839void GameController::enableTurbo() {
 840	threadInterrupt();
 841	if (!m_turbo) {
 842		m_threadContext.fpsTarget = m_fpsTarget;
 843		m_threadContext.sync.audioWait = m_audioSync;
 844		m_threadContext.sync.videoFrameWait = m_videoSync;
 845	} else if (m_turboSpeed <= 0) {
 846		m_threadContext.fpsTarget = m_fpsTarget;
 847		m_threadContext.sync.audioWait = false;
 848		m_threadContext.sync.videoFrameWait = false;
 849	} else {
 850		m_threadContext.fpsTarget = m_fpsTarget * m_turboSpeed;
 851		m_threadContext.sync.audioWait = true;
 852		m_threadContext.sync.videoFrameWait = false;
 853	}
 854	if (m_audioProcessor) {
 855		redoSamples(m_audioProcessor->getBufferSamples());
 856	}
 857	threadContinue();
 858}
 859
 860void GameController::setAVStream(GBAAVStream* stream) {
 861	threadInterrupt();
 862	m_threadContext.stream = stream;
 863	if (isLoaded()) {
 864		m_threadContext.gba->stream = stream;
 865	}
 866	threadContinue();
 867}
 868
 869void GameController::clearAVStream() {
 870	threadInterrupt();
 871	m_threadContext.stream = nullptr;
 872	if (isLoaded()) {
 873		m_threadContext.gba->stream = nullptr;
 874	}
 875	threadContinue();
 876}
 877
 878#ifdef USE_PNG
 879void GameController::screenshot() {
 880	GBARunOnThread(&m_threadContext, GBAThreadTakeScreenshot);
 881}
 882#endif
 883
 884void GameController::reloadAudioDriver() {
 885	int samples = 0;
 886	unsigned sampleRate = 0;
 887	if (m_audioProcessor) {
 888		QMetaObject::invokeMethod(m_audioProcessor, "pause", Qt::BlockingQueuedConnection);
 889		samples = m_audioProcessor->getBufferSamples();
 890		sampleRate = m_audioProcessor->sampleRate();
 891		delete m_audioProcessor;
 892	}
 893	m_audioProcessor = AudioProcessor::create();
 894	if (samples) {
 895		m_audioProcessor->setBufferSamples(samples);
 896	}
 897	if (sampleRate) {
 898		m_audioProcessor->requestSampleRate(sampleRate);
 899	}
 900	m_audioProcessor->moveToThread(m_audioThread);
 901	connect(this, SIGNAL(gameStarted(GBAThread*)), m_audioProcessor, SLOT(start()));
 902	connect(this, SIGNAL(gamePaused(GBAThread*)), m_audioProcessor, SLOT(pause()));
 903	connect(this, SIGNAL(gameUnpaused(GBAThread*)), m_audioProcessor, SLOT(start()));
 904	if (isLoaded()) {
 905		m_audioProcessor->setInput(&m_threadContext);
 906		QMetaObject::invokeMethod(m_audioProcessor, "start");
 907	}
 908}
 909
 910void GameController::setSaveStateExtdata(int flags) {
 911	m_saveStateFlags = flags;
 912}
 913
 914void GameController::setLoadStateExtdata(int flags) {
 915	m_loadStateFlags = flags;
 916}
 917
 918void GameController::setLuminanceValue(uint8_t value) {
 919	m_luxValue = value;
 920	value = std::max<int>(value - 0x16, 0);
 921	m_luxLevel = 10;
 922	for (int i = 0; i < 10; ++i) {
 923		if (value < GBA_LUX_LEVELS[i]) {
 924			m_luxLevel = i;
 925			break;
 926		}
 927	}
 928	emit luminanceValueChanged(m_luxValue);
 929}
 930
 931void GameController::setLuminanceLevel(int level) {
 932	int value = 0x16;
 933	level = std::max(0, std::min(10, level));
 934	if (level > 0) {
 935		value += GBA_LUX_LEVELS[level - 1];
 936	}
 937	setLuminanceValue(value);
 938}
 939
 940void GameController::setRealTime() {
 941	m_rtc.override = GBARTCGenericSource::RTC_NO_OVERRIDE;
 942}
 943
 944void GameController::setFixedTime(const QDateTime& time) {
 945	m_rtc.override = GBARTCGenericSource::RTC_FIXED;
 946	m_rtc.value = time.toMSecsSinceEpoch() / 1000;
 947}
 948
 949void GameController::setFakeEpoch(const QDateTime& time) {
 950	m_rtc.override = GBARTCGenericSource::RTC_FAKE_EPOCH;
 951	m_rtc.value = time.toMSecsSinceEpoch() / 1000;
 952}
 953
 954void GameController::updateKeys() {
 955	int activeKeys = m_activeKeys;
 956	activeKeys |= m_activeButtons;
 957	activeKeys &= ~m_inactiveKeys;
 958	m_threadContext.activeKeys = activeKeys;
 959}
 960
 961void GameController::redoSamples(int samples) {
 962#if RESAMPLE_LIBRARY != RESAMPLE_BLIP_BUF
 963	float sampleRate = 0x8000;
 964	float ratio;
 965	if (m_threadContext.gba) {
 966		sampleRate = m_threadContext.gba->audio.sampleRate;
 967	}
 968	ratio = GBAAudioCalculateRatio(sampleRate, m_threadContext.fpsTarget, m_audioProcess->sampleRate());
 969	m_threadContext.audioBuffers = ceil(samples / ratio);
 970#else
 971	m_threadContext.audioBuffers = samples;
 972#endif
 973	if (m_threadContext.gba) {
 974		GBAAudioResizeBuffer(&m_threadContext.gba->audio, m_threadContext.audioBuffers);
 975	}
 976	QMetaObject::invokeMethod(m_audioProcessor, "inputParametersChanged");
 977}
 978
 979void GameController::setLogLevel(int levels) {
 980	threadInterrupt();
 981	m_logLevels = levels;
 982	threadContinue();
 983}
 984
 985void GameController::enableLogLevel(int levels) {
 986	threadInterrupt();
 987	m_logLevels |= levels;
 988	threadContinue();
 989}
 990
 991void GameController::disableLogLevel(int levels) {
 992	threadInterrupt();
 993	m_logLevels &= ~levels;
 994	threadContinue();
 995}
 996
 997void GameController::pollEvents() {
 998	if (!m_inputController) {
 999		return;
1000	}
1001
1002	m_activeButtons = m_inputController->pollEvents();
1003	updateKeys();
1004}
1005
1006void GameController::updateAutofire() {
1007	// TODO: Move all key events onto the CPU thread...somehow
1008	for (int k = 0; k < GBA_KEY_MAX; ++k) {
1009		if (!m_autofire[k]) {
1010			continue;
1011		}
1012		m_autofireStatus[k] ^= 1;
1013		if (m_autofireStatus[k]) {
1014			keyPressed(k);
1015		} else {
1016			keyReleased(k);
1017		}
1018	}
1019}