all repos — mgba @ cb0f95b07053e63e817bd05df0a36bf917667d09

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