all repos — mgba @ 3ceadd4ccdb70574bc09d1a1270ab5d9341de776

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