all repos — mgba @ d401db77f0a89d9b2a62ce9aa376032a889de5a3

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