all repos — mgba @ c45d91d311854c824faa1055038c676e1cfc7e7b

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