all repos — mgba @ 051198395dc108415035ac37f779e9f063b6d2eb

mGBA Game Boy Advance Emulator

src/platform/qt/GameController.cpp (view raw)

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