all repos — mgba @ a5bcfc7c80db49fadd652677ed4a3b87c6f235e5

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->setRotation(context->core, controller->m_inputController->rotationSource());
  91		context->core->setRumble(context->core, controller->m_inputController->rumble());
  92
  93#ifdef M_CORE_GBA
  94		GBA* gba = static_cast<GBA*>(context->core->board);
  95#endif
  96#ifdef M_CORE_GB
  97		GB* gb = static_cast<GB*>(context->core->board);
  98#endif
  99		switch (context->core->platform(context->core)) {
 100#ifdef M_CORE_GBA
 101		case PLATFORM_GBA:
 102			gba->luminanceSource = &controller->m_lux;
 103			gba->audio.psg.forceDisableCh[0] = !controller->m_audioChannels[0];
 104			gba->audio.psg.forceDisableCh[1] = !controller->m_audioChannels[1];
 105			gba->audio.psg.forceDisableCh[2] = !controller->m_audioChannels[2];
 106			gba->audio.psg.forceDisableCh[3] = !controller->m_audioChannels[3];
 107			gba->audio.forceDisableChA = !controller->m_audioChannels[4];
 108			gba->audio.forceDisableChB = !controller->m_audioChannels[5];
 109			gba->video.renderer->disableBG[0] = !controller->m_videoLayers[0];
 110			gba->video.renderer->disableBG[1] = !controller->m_videoLayers[1];
 111			gba->video.renderer->disableBG[2] = !controller->m_videoLayers[2];
 112			gba->video.renderer->disableBG[3] = !controller->m_videoLayers[3];
 113			gba->video.renderer->disableOBJ = !controller->m_videoLayers[4];
 114			break;
 115#endif
 116#ifdef M_CORE_GB
 117		case PLATFORM_GB:
 118			gb->audio.forceDisableCh[0] = !controller->m_audioChannels[0];
 119			gb->audio.forceDisableCh[1] = !controller->m_audioChannels[1];
 120			gb->audio.forceDisableCh[2] = !controller->m_audioChannels[2];
 121			gb->audio.forceDisableCh[3] = !controller->m_audioChannels[3];
 122			break;
 123#endif
 124		default:
 125			break;
 126		}
 127		controller->m_fpsTarget = context->sync.fpsTarget;
 128
 129		if (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		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	// TODO: Put back
 221	/*m_threadContext.stopCallback = [](mCoreThread* context) {
 222		if (!context) {
 223			return false;
 224		}
 225		GameController* controller = static_cast<GameController*>(context->userData);
 226		if (!mCoreSaveState(context->core, 0, controller->m_saveStateFlags)) {
 227			return false;
 228		}
 229		QMetaObject::invokeMethod(controller, "closeGame");
 230		return true;
 231	};*/
 232
 233	m_threadContext.logger.d.log = [](mLogger* logger, int category, enum mLogLevel level, const char* format, va_list args) {
 234		mThreadLogger* logContext = reinterpret_cast<mThreadLogger*>(logger);
 235		mCoreThread* context = logContext->p;
 236
 237		static const char* savestateMessage = "State %i loaded";
 238		static const char* savestateFailedMessage = "State %i failed to load";
 239		static int biosCat = -1;
 240		static int statusCat = -1;
 241		if (!context) {
 242			return;
 243		}
 244		GameController* controller = static_cast<GameController*>(context->userData);
 245		QString message;
 246		if (biosCat < 0) {
 247			biosCat = mLogCategoryById("gba.bios");
 248		}
 249		if (statusCat < 0) {
 250			statusCat = mLogCategoryById("core.status");
 251		}
 252#ifdef M_CORE_GBA
 253		if (level == mLOG_STUB && category == biosCat) {
 254			va_list argc;
 255			va_copy(argc, args);
 256			int immediate = va_arg(argc, int);
 257			va_end(argc);
 258			QMetaObject::invokeMethod(controller, "unimplementedBiosCall", Q_ARG(int, immediate));
 259		} else
 260#endif
 261		if (category == statusCat) {
 262			// Slot 0 is reserved for suspend points
 263			if (strncmp(savestateMessage, format, strlen(savestateMessage)) == 0) {
 264				va_list argc;
 265				va_copy(argc, args);
 266				int slot = va_arg(argc, int);
 267				va_end(argc);
 268				if (slot == 0) {
 269					format = "Loaded suspend state";
 270				}
 271			} else if (strncmp(savestateFailedMessage, format, strlen(savestateFailedMessage)) == 0) {
 272				va_list argc;
 273				va_copy(argc, args);
 274				int slot = va_arg(argc, int);
 275				va_end(argc);
 276				if (slot == 0) {
 277					return;
 278				}
 279			}
 280			message = QString().vsprintf(format, args);
 281			QMetaObject::invokeMethod(controller, "statusPosted", Q_ARG(const QString&, message));
 282		}
 283		if (level == mLOG_FATAL) {
 284			mCoreThreadMarkCrashed(controller->thread());
 285			QMetaObject::invokeMethod(controller, "crashGame", Q_ARG(const QString&, QString().vsprintf(format, args)));
 286		} else if (!(controller->m_logLevels & level)) {
 287			return;
 288		}
 289		message = QString().vsprintf(format, args);
 290		QMetaObject::invokeMethod(controller, "postLog", Q_ARG(int, level), Q_ARG(int, category), Q_ARG(const QString&, message));
 291	};
 292
 293	m_threadContext.userData = this;
 294
 295	connect(this, SIGNAL(gamePaused(mCoreThread*)), m_audioProcessor, SLOT(pause()));
 296	connect(this, SIGNAL(gameStarted(mCoreThread*, const QString&)), m_audioProcessor, SLOT(setInput(mCoreThread*)));
 297	connect(this, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(pollEvents()));
 298	connect(this, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(updateAutofire()));
 299}
 300
 301GameController::~GameController() {
 302	disconnect();
 303	closeGame();
 304	clearMultiplayerController();
 305	delete m_backupLoadState;
 306}
 307
 308void GameController::setMultiplayerController(MultiplayerController* controller) {
 309	if (controller == m_multiplayer) {
 310		return;
 311	}
 312	clearMultiplayerController();
 313	m_multiplayer = controller;
 314	if (isLoaded()) {
 315		mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* thread) {
 316			GameController* controller = static_cast<GameController*>(thread->userData);
 317			controller->m_multiplayer->attachGame(controller);
 318		});
 319	}
 320}
 321
 322void GameController::clearMultiplayerController() {
 323	if (!m_multiplayer) {
 324		return;
 325	}
 326	m_multiplayer->detachGame(this);
 327	m_multiplayer = nullptr;
 328}
 329
 330void GameController::setOverride(Override* override) {
 331	m_override = override;
 332	if (isLoaded()) {
 333		Interrupter interrupter(this);
 334		m_override->identify(m_threadContext.core);
 335	}
 336}
 337
 338void GameController::clearOverride() {
 339	delete m_override;
 340	m_override = nullptr;
 341}
 342
 343void GameController::setConfig(const mCoreConfig* config) {
 344	m_config = config;
 345	if (isLoaded()) {
 346		Interrupter interrupter(this);
 347		mCoreLoadForeignConfig(m_threadContext.core, config);
 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 = base + QDir::separator() + path;
 411		m_fsub = QString();
 412	} else {
 413		m_fname = base;
 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	mCoreThreadJoin(&m_threadContext);
 645
 646	if (m_tileCache) {
 647		mTileCacheDeinit(m_tileCache.get());
 648		m_tileCache.reset();
 649	}
 650
 651	delete[] m_drawContext;
 652	delete[] m_frontBuffer;
 653
 654	m_threadContext.core->deinit(m_threadContext.core);
 655	m_gameOpen = false;
 656}
 657
 658void GameController::crashGame(const QString& crashMessage) {
 659	closeGame();
 660	emit gameCrashed(crashMessage);
 661}
 662
 663bool GameController::isPaused() {
 664	if (!m_gameOpen) {
 665		return false;
 666	}
 667	return mCoreThreadIsPaused(&m_threadContext);
 668}
 669
 670mPlatform GameController::platform() const {
 671	if (!m_gameOpen) {
 672		return PLATFORM_NONE;
 673	}
 674	return m_threadContext.core->platform(m_threadContext.core);
 675}
 676
 677QSize GameController::screenDimensions() const {
 678	if (!m_gameOpen) {
 679		return QSize();
 680	}
 681	unsigned width, height;
 682	m_threadContext.core->desiredVideoDimensions(m_threadContext.core, &width, &height);
 683
 684	return QSize(width, height);
 685}
 686
 687void GameController::setPaused(bool paused) {
 688	if (!isLoaded() || paused == mCoreThreadIsPaused(&m_threadContext)) {
 689		return;
 690	}
 691	m_wasPaused = paused;
 692	if (paused) {
 693		m_pauseAfterFrame.testAndSetRelaxed(false, true);
 694	} else {
 695		mCoreThreadUnpause(&m_threadContext);
 696		startAudio();
 697		emit gameUnpaused(&m_threadContext);
 698	}
 699}
 700
 701void GameController::reset() {
 702	if (!m_gameOpen) {
 703		return;
 704	}
 705	bool wasPaused = isPaused();
 706	setPaused(false);
 707	Interrupter interrupter(this);
 708	mCoreThreadReset(&m_threadContext);
 709	if (wasPaused) {
 710		setPaused(true);
 711	}
 712}
 713
 714void GameController::threadInterrupt() {
 715	if (m_gameOpen) {
 716		mCoreThreadInterrupt(&m_threadContext);
 717	}
 718}
 719
 720void GameController::threadContinue() {
 721	if (m_gameOpen) {
 722		mCoreThreadContinue(&m_threadContext);
 723	}
 724}
 725
 726void GameController::frameAdvance() {
 727	if (m_pauseAfterFrame.testAndSetRelaxed(false, true)) {
 728		setPaused(false);
 729	}
 730}
 731
 732void GameController::setRewind(bool enable, int capacity, bool rewindSave) {
 733	if (m_gameOpen) {
 734		Interrupter interrupter(this);
 735		if (m_threadContext.core->opts.rewindEnable && m_threadContext.core->opts.rewindBufferCapacity > 0) {
 736			mCoreRewindContextDeinit(&m_threadContext.rewind);
 737		}
 738		m_threadContext.core->opts.rewindEnable = enable;
 739		m_threadContext.core->opts.rewindBufferCapacity = capacity;
 740		m_threadContext.core->opts.rewindSave = rewindSave;
 741		if (enable && capacity > 0) {
 742			mCoreRewindContextInit(&m_threadContext.rewind, capacity);
 743			 m_threadContext.rewind.stateFlags = rewindSave ? SAVESTATE_SAVEDATA : 0;
 744		}
 745	}
 746}
 747
 748void GameController::rewind(int states) {
 749	threadInterrupt();
 750	if (!states) {
 751		states = INT_MAX;
 752	}
 753	for (int i = 0; i < states; ++i) {
 754		if (!mCoreRewindRestore(&m_threadContext.rewind, m_threadContext.core)) {
 755			break;
 756		}
 757	}
 758	threadContinue();
 759	emit frameAvailable(m_drawContext);
 760	emit rewound(&m_threadContext);
 761}
 762
 763void GameController::startRewinding() {
 764	if (!isLoaded()) {
 765		return;
 766	}
 767	if (!m_threadContext.core->opts.rewindEnable) {
 768		return;
 769	}
 770	if (m_multiplayer && m_multiplayer->attached() > 1) {
 771		return;
 772	}
 773	if (m_wasPaused) {
 774		setPaused(false);
 775		m_wasPaused = true;
 776	}
 777	mCoreThreadSetRewinding(&m_threadContext, true);
 778}
 779
 780void GameController::stopRewinding() {
 781	if (!isLoaded()) {
 782		return;
 783	}
 784	mCoreThreadSetRewinding(&m_threadContext, false);
 785	bool signalsBlocked = blockSignals(true);
 786	setPaused(m_wasPaused);
 787	blockSignals(signalsBlocked);
 788}
 789
 790void GameController::keyPressed(int key) {
 791	int mappedKey = 1 << key;
 792	m_activeKeys |= mappedKey;
 793	if (!m_inputController->allowOpposing()) {
 794		if ((m_activeKeys & 0x30) == 0x30) {
 795			m_inactiveKeys |= mappedKey ^ 0x30;
 796			m_activeKeys ^= mappedKey ^ 0x30;
 797		}
 798		if ((m_activeKeys & 0xC0) == 0xC0) {
 799			m_inactiveKeys |= mappedKey ^ 0xC0;
 800			m_activeKeys ^= mappedKey ^ 0xC0;
 801		}
 802	}
 803	updateKeys();
 804}
 805
 806void GameController::keyReleased(int key) {
 807	int mappedKey = 1 << key;
 808	m_activeKeys &= ~mappedKey;
 809	if (!m_inputController->allowOpposing()) {
 810		if (mappedKey & 0x30) {
 811			m_activeKeys |= m_inactiveKeys & (0x30 ^ mappedKey);
 812			m_inactiveKeys &= ~0x30;
 813		}
 814		if (mappedKey & 0xC0) {
 815			m_activeKeys |= m_inactiveKeys & (0xC0 ^ mappedKey);
 816			m_inactiveKeys &= ~0xC0;
 817		}
 818	}
 819	updateKeys();
 820}
 821
 822void GameController::cursorLocation(int x, int y) {
 823	if (!isLoaded()) {
 824		return;
 825	}
 826	m_threadContext.core->setCursorLocation(m_threadContext.core, x, y);
 827}
 828
 829void GameController::cursorDown(bool down) {
 830	if (!isLoaded()) {
 831		return;
 832	}
 833	m_threadContext.core->setCursorDown(m_threadContext.core, down);
 834}
 835
 836void GameController::clearKeys() {
 837	m_activeKeys = 0;
 838	m_inactiveKeys = 0;
 839	updateKeys();
 840}
 841
 842void GameController::setAutofire(int key, bool enable) {
 843	if (key >= GBA_KEY_MAX || key < 0) {
 844		return;
 845	}
 846
 847	if (!enable && m_autofireStatus[key]) {
 848		keyReleased(key);
 849	}
 850
 851	m_autofire[key] = enable;
 852	m_autofireStatus[key] = 0;
 853}
 854
 855void GameController::setAudioBufferSamples(int samples) {
 856	if (m_audioProcessor) {
 857		threadInterrupt();
 858		redoSamples(samples);
 859		threadContinue();
 860		m_audioProcessor->setBufferSamples(samples);
 861	}
 862}
 863
 864void GameController::setAudioSampleRate(unsigned rate) {
 865	if (!rate) {
 866		return;
 867	}
 868	if (m_audioProcessor) {
 869		threadInterrupt();
 870		redoSamples(m_audioProcessor->getBufferSamples());
 871		threadContinue();
 872		m_audioProcessor->requestSampleRate(rate);
 873	}
 874}
 875
 876void GameController::setAudioChannelEnabled(int channel, bool enable) {
 877	if (channel > 5 || channel < 0) {
 878		return;
 879	}
 880#ifdef M_CORE_GBA
 881	GBA* gba = static_cast<GBA*>(m_threadContext.core->board);
 882#endif
 883#ifdef M_CORE_GB
 884	GB* gb = static_cast<GB*>(m_threadContext.core->board);
 885#endif
 886	m_audioChannels[channel] = enable;
 887	if (isLoaded()) {
 888		switch (channel) {
 889		case 0:
 890		case 1:
 891		case 2:
 892		case 3:
 893			switch (m_threadContext.core->platform(m_threadContext.core)) {
 894#ifdef M_CORE_GBA
 895			case PLATFORM_GBA:
 896				gba->audio.psg.forceDisableCh[channel] = !enable;
 897				break;
 898#endif
 899#ifdef M_CORE_GB
 900			case PLATFORM_GB:
 901				gb->audio.forceDisableCh[channel] = !enable;
 902				break;
 903#endif
 904			default:
 905				break;
 906			}
 907			break;
 908#ifdef M_CORE_GBA
 909		case 4:
 910			if (m_threadContext.core->platform(m_threadContext.core) == PLATFORM_GBA) {
 911				gba->audio.forceDisableChA = !enable;
 912			}
 913			break;
 914		case 5:
 915			if (m_threadContext.core->platform(m_threadContext.core) == PLATFORM_GBA) {
 916				gba->audio.forceDisableChB = !enable;
 917			}
 918			break;
 919#endif
 920		}
 921	}
 922}
 923
 924void GameController::startAudio() {
 925	if (!m_audioProcessor->start()) {
 926		LOG(QT, ERROR) << tr("Failed to start audio processor");
 927		// Don't freeze!
 928		m_audioSync = false;
 929		m_videoSync = true;
 930		m_threadContext.sync.audioWait = false;
 931		m_threadContext.sync.videoFrameWait = true;
 932	}
 933}
 934
 935void GameController::setVideoLayerEnabled(int layer, bool enable) {
 936	if (layer > 4 || layer < 0) {
 937		return;
 938	}
 939	m_videoLayers[layer] = enable;
 940#ifdef M_CORE_GBA
 941	if (isLoaded() && m_threadContext.core->platform(m_threadContext.core) == PLATFORM_GBA) {
 942		GBA* gba = static_cast<GBA*>(m_threadContext.core->board);
 943		switch (layer) {
 944		case 0:
 945		case 1:
 946		case 2:
 947		case 3:
 948			gba->video.renderer->disableBG[layer] = !enable;
 949			break;
 950		case 4:
 951			gba->video.renderer->disableOBJ = !enable;
 952			break;
 953		}
 954	}
 955#endif
 956}
 957
 958void GameController::setFPSTarget(float fps) {
 959	Interrupter interrupter(this);
 960	m_fpsTarget = fps;
 961	m_threadContext.sync.fpsTarget = fps;
 962	if (m_turbo && m_turboSpeed > 0) {
 963		m_threadContext.sync.fpsTarget *= m_turboSpeed;
 964	}
 965	if (m_audioProcessor) {
 966		redoSamples(m_audioProcessor->getBufferSamples());
 967	}
 968}
 969
 970void GameController::setUseBIOS(bool use) {
 971	if (use == m_useBios) {
 972		return;
 973	}
 974	m_useBios = use;
 975	if (m_gameOpen) {
 976		closeGame();
 977		openGame();
 978	}
 979}
 980
 981void GameController::loadState(int slot) {
 982	if (m_fname.isEmpty()) {
 983		// We're in the BIOS
 984		return;
 985	}
 986	if (slot > 0 && slot != m_stateSlot) {
 987		m_stateSlot = slot;
 988		m_backupSaveState.clear();
 989	}
 990	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 991		GameController* controller = static_cast<GameController*>(context->userData);
 992		if (!controller->m_backupLoadState) {
 993			controller->m_backupLoadState = VFileMemChunk(nullptr, 0);
 994		}
 995		mCoreLoadStateNamed(context->core, controller->m_backupLoadState, controller->m_saveStateFlags);
 996		if (mCoreLoadState(context->core, controller->m_stateSlot, controller->m_loadStateFlags)) {
 997			controller->frameAvailable(controller->m_drawContext);
 998			controller->stateLoaded(context);
 999		}
1000	});
1001}
1002
1003void GameController::saveState(int slot) {
1004	if (m_fname.isEmpty()) {
1005		// We're in the BIOS
1006		return;
1007	}
1008	if (slot > 0) {
1009		m_stateSlot = slot;
1010	}
1011	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
1012		GameController* controller = static_cast<GameController*>(context->userData);
1013		VFile* vf = mCoreGetState(context->core, controller->m_stateSlot, false);
1014		if (vf) {
1015			controller->m_backupSaveState.resize(vf->size(vf));
1016			vf->read(vf, controller->m_backupSaveState.data(), controller->m_backupSaveState.size());
1017			vf->close(vf);
1018		}
1019		mCoreSaveState(context->core, controller->m_stateSlot, controller->m_saveStateFlags);
1020	});
1021}
1022
1023void GameController::loadBackupState() {
1024	if (!m_backupLoadState) {
1025		return;
1026	}
1027
1028	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
1029		GameController* controller = static_cast<GameController*>(context->userData);
1030		controller->m_backupLoadState->seek(controller->m_backupLoadState, 0, SEEK_SET);
1031		if (mCoreLoadStateNamed(context->core, controller->m_backupLoadState, controller->m_loadStateFlags)) {
1032			mLOG(STATUS, INFO, "Undid state load");
1033			controller->frameAvailable(controller->m_drawContext);
1034			controller->stateLoaded(context);
1035		}
1036		controller->m_backupLoadState->close(controller->m_backupLoadState);
1037		controller->m_backupLoadState = nullptr;
1038	});
1039}
1040
1041void GameController::saveBackupState() {
1042	if (m_backupSaveState.isEmpty()) {
1043		return;
1044	}
1045
1046	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
1047		GameController* controller = static_cast<GameController*>(context->userData);
1048		VFile* vf = mCoreGetState(context->core, controller->m_stateSlot, true);
1049		if (vf) {
1050			vf->write(vf, controller->m_backupSaveState.constData(), controller->m_backupSaveState.size());
1051			vf->close(vf);
1052			mLOG(STATUS, INFO, "Undid state save");
1053		}
1054		controller->m_backupSaveState.clear();
1055	});
1056}
1057
1058void GameController::setTurbo(bool set, bool forced) {
1059	if (m_turboForced && !forced) {
1060		return;
1061	}
1062	if (m_turbo == set && m_turboForced == (set && forced)) {
1063		// Don't interrupt the thread if we don't need to
1064		return;
1065	}
1066	if (!m_sync) {
1067		return;
1068	}
1069	m_turbo = set;
1070	m_turboForced = set && forced;
1071	enableTurbo();
1072}
1073
1074void GameController::setTurboSpeed(float ratio) {
1075	m_turboSpeed = ratio;
1076	enableTurbo();
1077}
1078
1079void GameController::enableTurbo() {
1080	Interrupter interrupter(this);
1081	bool shouldRedoSamples = false;
1082	if (!m_turbo) {
1083		shouldRedoSamples = m_threadContext.sync.fpsTarget != m_fpsTarget;
1084		m_threadContext.sync.fpsTarget = m_fpsTarget;
1085		m_threadContext.sync.audioWait = m_audioSync;
1086		m_threadContext.sync.videoFrameWait = m_videoSync;
1087	} else if (m_turboSpeed <= 0) {
1088		shouldRedoSamples = m_threadContext.sync.fpsTarget != m_fpsTarget;
1089		m_threadContext.sync.fpsTarget = m_fpsTarget;
1090		m_threadContext.sync.audioWait = false;
1091		m_threadContext.sync.videoFrameWait = false;
1092	} else {
1093		shouldRedoSamples = m_threadContext.sync.fpsTarget != m_fpsTarget * m_turboSpeed;
1094		m_threadContext.sync.fpsTarget = m_fpsTarget * m_turboSpeed;
1095		m_threadContext.sync.audioWait = true;
1096		m_threadContext.sync.videoFrameWait = false;
1097	}
1098	if (m_audioProcessor && shouldRedoSamples) {
1099		redoSamples(m_audioProcessor->getBufferSamples());
1100	}
1101}
1102
1103void GameController::setSync(bool enable) {
1104	m_turbo = false;
1105	m_turboForced = false;
1106	if (!enable) {
1107		m_threadContext.sync.audioWait = false;
1108		m_threadContext.sync.videoFrameWait = false;
1109	} else {
1110		m_threadContext.sync.audioWait = m_audioSync;
1111		m_threadContext.sync.videoFrameWait = m_videoSync;
1112	}
1113	m_sync = enable;
1114}
1115void GameController::setAVStream(mAVStream* stream) {
1116	Interrupter interrupter(this);
1117	m_stream = stream;
1118	if (isLoaded()) {
1119		m_threadContext.core->setAVStream(m_threadContext.core, stream);
1120	}
1121}
1122
1123void GameController::clearAVStream() {
1124	Interrupter interrupter(this);
1125	m_stream = nullptr;
1126	if (isLoaded()) {
1127		m_threadContext.core->setAVStream(m_threadContext.core, nullptr);
1128	}
1129}
1130
1131#ifdef USE_PNG
1132void GameController::screenshot() {
1133	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
1134		mCoreTakeScreenshot(context->core);
1135	});
1136}
1137#endif
1138
1139void GameController::reloadAudioDriver() {
1140	int samples = 0;
1141	unsigned sampleRate = 0;
1142	if (m_audioProcessor) {
1143		m_audioProcessor->pause();
1144		samples = m_audioProcessor->getBufferSamples();
1145		sampleRate = m_audioProcessor->sampleRate();
1146		delete m_audioProcessor;
1147	}
1148	m_audioProcessor = AudioProcessor::create();
1149	if (samples) {
1150		m_audioProcessor->setBufferSamples(samples);
1151	}
1152	if (sampleRate) {
1153		m_audioProcessor->requestSampleRate(sampleRate);
1154	}
1155	connect(this, SIGNAL(gamePaused(mCoreThread*)), m_audioProcessor, SLOT(pause()));
1156	connect(this, SIGNAL(gameStarted(mCoreThread*, const QString&)), m_audioProcessor, SLOT(setInput(mCoreThread*)));
1157	if (isLoaded()) {
1158		m_audioProcessor->setInput(&m_threadContext);
1159		startAudio();
1160	}
1161}
1162
1163void GameController::setSaveStateExtdata(int flags) {
1164	m_saveStateFlags = flags;
1165}
1166
1167void GameController::setLoadStateExtdata(int flags) {
1168	m_loadStateFlags = flags;
1169}
1170
1171void GameController::setLuminanceValue(uint8_t value) {
1172	m_luxValue = value;
1173	value = std::max<int>(value - 0x16, 0);
1174	m_luxLevel = 10;
1175	for (int i = 0; i < 10; ++i) {
1176		if (value < GBA_LUX_LEVELS[i]) {
1177			m_luxLevel = i;
1178			break;
1179		}
1180	}
1181	emit luminanceValueChanged(m_luxValue);
1182}
1183
1184void GameController::setLuminanceLevel(int level) {
1185	int value = 0x16;
1186	level = std::max(0, std::min(10, level));
1187	if (level > 0) {
1188		value += GBA_LUX_LEVELS[level - 1];
1189	}
1190	setLuminanceValue(value);
1191}
1192
1193void GameController::setRealTime() {
1194	if (!isLoaded()) {
1195		return;
1196	}
1197	m_threadContext.core->rtc.override = RTC_NO_OVERRIDE;
1198}
1199
1200void GameController::setFixedTime(const QDateTime& time) {
1201	if (!isLoaded()) {
1202		return;
1203	}
1204	m_threadContext.core->rtc.override = RTC_FIXED;
1205	m_threadContext.core->rtc.value = time.toMSecsSinceEpoch();
1206}
1207
1208void GameController::setFakeEpoch(const QDateTime& time) {
1209	if (!isLoaded()) {
1210		return;
1211	}
1212	m_threadContext.core->rtc.override = RTC_FAKE_EPOCH;
1213	m_threadContext.core->rtc.value = time.toMSecsSinceEpoch();
1214}
1215
1216void GameController::updateKeys() {
1217	int activeKeys = m_activeKeys;
1218	activeKeys |= m_activeButtons;
1219	activeKeys &= ~m_inactiveKeys;
1220	if (isLoaded()) {
1221		m_threadContext.core->setKeys(m_threadContext.core, activeKeys);
1222	}
1223}
1224
1225void GameController::redoSamples(int samples) {
1226	if (m_threadContext.core) {
1227		m_threadContext.core->setAudioBufferSize(m_threadContext.core, samples);
1228	}
1229	m_audioProcessor->inputParametersChanged();
1230}
1231
1232void GameController::setLogLevel(int levels) {
1233	Interrupter interrupter(this);
1234	m_logLevels = levels;
1235}
1236
1237void GameController::enableLogLevel(int levels) {
1238	Interrupter interrupter(this);
1239	m_logLevels |= levels;
1240}
1241
1242void GameController::disableLogLevel(int levels) {
1243	Interrupter interrupter(this);
1244	m_logLevels &= ~levels;
1245}
1246
1247void GameController::pollEvents() {
1248	if (!m_inputController) {
1249		return;
1250	}
1251
1252	m_activeButtons = m_inputController->pollEvents();
1253	updateKeys();
1254}
1255
1256void GameController::updateAutofire() {
1257	// TODO: Move all key events onto the CPU thread...somehow
1258	for (int k = 0; k < GBA_KEY_MAX; ++k) {
1259		if (!m_autofire[k]) {
1260			continue;
1261		}
1262		m_autofireStatus[k] ^= 1;
1263		if (m_autofireStatus[k]) {
1264			keyPressed(k);
1265		} else {
1266			keyReleased(k);
1267		}
1268	}
1269}
1270
1271std::shared_ptr<mTileCache> GameController::tileCache() {
1272	if (m_tileCache) {
1273		return m_tileCache;
1274	}
1275	switch (platform()) {
1276#ifdef M_CORE_GBA
1277	case PLATFORM_GBA: {
1278		Interrupter interrupter(this);
1279		GBA* gba = static_cast<GBA*>(m_threadContext.core->board);
1280		m_tileCache = std::make_shared<mTileCache>();
1281		GBAVideoTileCacheInit(m_tileCache.get());
1282		GBAVideoTileCacheAssociate(m_tileCache.get(), &gba->video);
1283		mTileCacheSetPalette(m_tileCache.get(), 0);
1284		break;
1285	}
1286#endif
1287#ifdef M_CORE_GB
1288	case PLATFORM_GB: {
1289		Interrupter interrupter(this);
1290		GB* gb = static_cast<GB*>(m_threadContext.core->board);
1291		m_tileCache = std::make_shared<mTileCache>();
1292		GBVideoTileCacheInit(m_tileCache.get());
1293		GBVideoTileCacheAssociate(m_tileCache.get(), &gb->video);
1294		mTileCacheSetPalette(m_tileCache.get(), 0);
1295		break;
1296	}
1297#endif
1298	default:
1299		return nullptr;
1300	}
1301	return m_tileCache;
1302}
1303
1304GameController::Interrupter::Interrupter(GameController* parent, bool fromThread)
1305	: m_parent(parent)
1306	, m_fromThread(fromThread)
1307{
1308	if (!m_fromThread) {
1309		m_parent->threadInterrupt();
1310	} else {
1311		mCoreThreadInterruptFromThread(m_parent->thread());
1312	}
1313}
1314
1315GameController::Interrupter::~Interrupter() {
1316	if (!m_fromThread) {
1317		m_parent->threadContinue();
1318	} else {
1319		mCoreThreadContinue(m_parent->thread());
1320	}
1321}