all repos — mgba @ 1fdf413ee9f31e797618d0968f709d8db0674b6b

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