all repos — mgba @ 4c38f769565e8ddd7d3a8eef1a41975206c129a0

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