all repos — mgba @ 7e9f43a9c91f96e9af0c815b7cccd422c0bb4fbf

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