all repos — mgba @ 03f96911bb66a989a45b9562b508580ef7f32fb3

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::clearKeys() {
 823	m_activeKeys = 0;
 824	m_inactiveKeys = 0;
 825	updateKeys();
 826}
 827
 828void GameController::setAutofire(int key, bool enable) {
 829	if (key >= GBA_KEY_MAX || key < 0) {
 830		return;
 831	}
 832
 833	if (!enable && m_autofireStatus[key]) {
 834		keyReleased(key);
 835	}
 836
 837	m_autofire[key] = enable;
 838	m_autofireStatus[key] = 0;
 839}
 840
 841void GameController::setAudioBufferSamples(int samples) {
 842	if (m_audioProcessor) {
 843		threadInterrupt();
 844		redoSamples(samples);
 845		threadContinue();
 846		m_audioProcessor->setBufferSamples(samples);
 847	}
 848}
 849
 850void GameController::setAudioSampleRate(unsigned rate) {
 851	if (!rate) {
 852		return;
 853	}
 854	if (m_audioProcessor) {
 855		threadInterrupt();
 856		redoSamples(m_audioProcessor->getBufferSamples());
 857		threadContinue();
 858		m_audioProcessor->requestSampleRate(rate);
 859	}
 860}
 861
 862void GameController::setAudioChannelEnabled(int channel, bool enable) {
 863	if (channel > 5 || channel < 0) {
 864		return;
 865	}
 866#ifdef M_CORE_GBA
 867	GBA* gba = static_cast<GBA*>(m_threadContext.core->board);
 868#endif
 869#ifdef M_CORE_GB
 870	GB* gb = static_cast<GB*>(m_threadContext.core->board);
 871#endif
 872	m_audioChannels[channel] = enable;
 873	if (isLoaded()) {
 874		switch (channel) {
 875		case 0:
 876		case 1:
 877		case 2:
 878		case 3:
 879			switch (m_threadContext.core->platform(m_threadContext.core)) {
 880#ifdef M_CORE_GBA
 881			case PLATFORM_GBA:
 882				gba->audio.psg.forceDisableCh[channel] = !enable;
 883				break;
 884#endif
 885#ifdef M_CORE_GB
 886			case PLATFORM_GB:
 887				gb->audio.forceDisableCh[channel] = !enable;
 888				break;
 889#endif
 890			default:
 891				break;
 892			}
 893			break;
 894#ifdef M_CORE_GBA
 895		case 4:
 896			if (m_threadContext.core->platform(m_threadContext.core) == PLATFORM_GBA) {
 897				gba->audio.forceDisableChA = !enable;
 898			}
 899			break;
 900		case 5:
 901			if (m_threadContext.core->platform(m_threadContext.core) == PLATFORM_GBA) {
 902				gba->audio.forceDisableChB = !enable;
 903			}
 904			break;
 905#endif
 906		}
 907	}
 908}
 909
 910void GameController::startAudio() {
 911	if (!m_audioProcessor->start()) {
 912		LOG(QT, ERROR) << tr("Failed to start audio processor");
 913		// Don't freeze!
 914		m_audioSync = false;
 915		m_videoSync = true;
 916		m_threadContext.sync.audioWait = false;
 917		m_threadContext.sync.videoFrameWait = true;
 918	}
 919}
 920
 921void GameController::setVideoLayerEnabled(int layer, bool enable) {
 922	if (layer > 4 || layer < 0) {
 923		return;
 924	}
 925	m_videoLayers[layer] = enable;
 926#ifdef M_CORE_GBA
 927	if (isLoaded() && m_threadContext.core->platform(m_threadContext.core) == PLATFORM_GBA) {
 928		GBA* gba = static_cast<GBA*>(m_threadContext.core->board);
 929		switch (layer) {
 930		case 0:
 931		case 1:
 932		case 2:
 933		case 3:
 934			gba->video.renderer->disableBG[layer] = !enable;
 935			break;
 936		case 4:
 937			gba->video.renderer->disableOBJ = !enable;
 938			break;
 939		}
 940	}
 941#endif
 942}
 943
 944void GameController::setFPSTarget(float fps) {
 945	Interrupter interrupter(this);
 946	m_fpsTarget = fps;
 947	m_threadContext.sync.fpsTarget = fps;
 948	if (m_turbo && m_turboSpeed > 0) {
 949		m_threadContext.sync.fpsTarget *= m_turboSpeed;
 950	}
 951	if (m_audioProcessor) {
 952		redoSamples(m_audioProcessor->getBufferSamples());
 953	}
 954}
 955
 956void GameController::setUseBIOS(bool use) {
 957	if (use == m_useBios) {
 958		return;
 959	}
 960	m_useBios = use;
 961	if (m_gameOpen) {
 962		closeGame();
 963		openGame();
 964	}
 965}
 966
 967void GameController::loadState(int slot) {
 968	if (m_fname.isEmpty()) {
 969		// We're in the BIOS
 970		return;
 971	}
 972	if (slot > 0 && slot != m_stateSlot) {
 973		m_stateSlot = slot;
 974		m_backupSaveState.clear();
 975	}
 976	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 977		GameController* controller = static_cast<GameController*>(context->userData);
 978		if (!controller->m_backupLoadState) {
 979			controller->m_backupLoadState = VFileMemChunk(nullptr, 0);
 980		}
 981		mCoreLoadStateNamed(context->core, controller->m_backupLoadState, controller->m_saveStateFlags);
 982		if (mCoreLoadState(context->core, controller->m_stateSlot, controller->m_loadStateFlags)) {
 983			controller->frameAvailable(controller->m_drawContext);
 984			controller->stateLoaded(context);
 985		}
 986	});
 987}
 988
 989void GameController::saveState(int slot) {
 990	if (m_fname.isEmpty()) {
 991		// We're in the BIOS
 992		return;
 993	}
 994	if (slot > 0) {
 995		m_stateSlot = slot;
 996	}
 997	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 998		GameController* controller = static_cast<GameController*>(context->userData);
 999		VFile* vf = mCoreGetState(context->core, controller->m_stateSlot, false);
1000		if (vf) {
1001			controller->m_backupSaveState.resize(vf->size(vf));
1002			vf->read(vf, controller->m_backupSaveState.data(), controller->m_backupSaveState.size());
1003			vf->close(vf);
1004		}
1005		mCoreSaveState(context->core, controller->m_stateSlot, controller->m_saveStateFlags);
1006	});
1007}
1008
1009void GameController::loadBackupState() {
1010	if (!m_backupLoadState) {
1011		return;
1012	}
1013
1014	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
1015		GameController* controller = static_cast<GameController*>(context->userData);
1016		controller->m_backupLoadState->seek(controller->m_backupLoadState, 0, SEEK_SET);
1017		if (mCoreLoadStateNamed(context->core, controller->m_backupLoadState, controller->m_loadStateFlags)) {
1018			mLOG(STATUS, INFO, "Undid state load");
1019			controller->frameAvailable(controller->m_drawContext);
1020			controller->stateLoaded(context);
1021		}
1022		controller->m_backupLoadState->close(controller->m_backupLoadState);
1023		controller->m_backupLoadState = nullptr;
1024	});
1025}
1026
1027void GameController::saveBackupState() {
1028	if (m_backupSaveState.isEmpty()) {
1029		return;
1030	}
1031
1032	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
1033		GameController* controller = static_cast<GameController*>(context->userData);
1034		VFile* vf = mCoreGetState(context->core, controller->m_stateSlot, true);
1035		if (vf) {
1036			vf->write(vf, controller->m_backupSaveState.constData(), controller->m_backupSaveState.size());
1037			vf->close(vf);
1038			mLOG(STATUS, INFO, "Undid state save");
1039		}
1040		controller->m_backupSaveState.clear();
1041	});
1042}
1043
1044void GameController::setTurbo(bool set, bool forced) {
1045	if (m_turboForced && !forced) {
1046		return;
1047	}
1048	if (m_turbo == set && m_turboForced == (set && forced)) {
1049		// Don't interrupt the thread if we don't need to
1050		return;
1051	}
1052	if (!m_sync) {
1053		return;
1054	}
1055	m_turbo = set;
1056	m_turboForced = set && forced;
1057	enableTurbo();
1058}
1059
1060void GameController::setTurboSpeed(float ratio) {
1061	m_turboSpeed = ratio;
1062	enableTurbo();
1063}
1064
1065void GameController::enableTurbo() {
1066	Interrupter interrupter(this);
1067	bool shouldRedoSamples = false;
1068	if (!m_turbo) {
1069		shouldRedoSamples = m_threadContext.sync.fpsTarget != m_fpsTarget;
1070		m_threadContext.sync.fpsTarget = m_fpsTarget;
1071		m_threadContext.sync.audioWait = m_audioSync;
1072		m_threadContext.sync.videoFrameWait = m_videoSync;
1073	} else if (m_turboSpeed <= 0) {
1074		shouldRedoSamples = m_threadContext.sync.fpsTarget != m_fpsTarget;
1075		m_threadContext.sync.fpsTarget = m_fpsTarget;
1076		m_threadContext.sync.audioWait = false;
1077		m_threadContext.sync.videoFrameWait = false;
1078	} else {
1079		shouldRedoSamples = m_threadContext.sync.fpsTarget != m_fpsTarget * m_turboSpeed;
1080		m_threadContext.sync.fpsTarget = m_fpsTarget * m_turboSpeed;
1081		m_threadContext.sync.audioWait = true;
1082		m_threadContext.sync.videoFrameWait = false;
1083	}
1084	if (m_audioProcessor && shouldRedoSamples) {
1085		redoSamples(m_audioProcessor->getBufferSamples());
1086	}
1087}
1088
1089void GameController::setSync(bool enable) {
1090	m_turbo = false;
1091	m_turboForced = false;
1092	if (!enable) {
1093		m_threadContext.sync.audioWait = false;
1094		m_threadContext.sync.videoFrameWait = false;
1095	} else {
1096		m_threadContext.sync.audioWait = m_audioSync;
1097		m_threadContext.sync.videoFrameWait = m_videoSync;
1098	}
1099	m_sync = enable;
1100}
1101void GameController::setAVStream(mAVStream* stream) {
1102	Interrupter interrupter(this);
1103	m_stream = stream;
1104	if (isLoaded()) {
1105		m_threadContext.core->setAVStream(m_threadContext.core, stream);
1106	}
1107}
1108
1109void GameController::clearAVStream() {
1110	Interrupter interrupter(this);
1111	m_stream = nullptr;
1112	if (isLoaded()) {
1113		m_threadContext.core->setAVStream(m_threadContext.core, nullptr);
1114	}
1115}
1116
1117#ifdef USE_PNG
1118void GameController::screenshot() {
1119	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
1120		mCoreTakeScreenshot(context->core);
1121	});
1122}
1123#endif
1124
1125void GameController::reloadAudioDriver() {
1126	int samples = 0;
1127	unsigned sampleRate = 0;
1128	if (m_audioProcessor) {
1129		m_audioProcessor->pause();
1130		samples = m_audioProcessor->getBufferSamples();
1131		sampleRate = m_audioProcessor->sampleRate();
1132		delete m_audioProcessor;
1133	}
1134	m_audioProcessor = AudioProcessor::create();
1135	if (samples) {
1136		m_audioProcessor->setBufferSamples(samples);
1137	}
1138	if (sampleRate) {
1139		m_audioProcessor->requestSampleRate(sampleRate);
1140	}
1141	connect(this, SIGNAL(gamePaused(mCoreThread*)), m_audioProcessor, SLOT(pause()));
1142	connect(this, SIGNAL(gameStarted(mCoreThread*, const QString&)), m_audioProcessor, SLOT(setInput(mCoreThread*)));
1143	if (isLoaded()) {
1144		m_audioProcessor->setInput(&m_threadContext);
1145		startAudio();
1146	}
1147}
1148
1149void GameController::setSaveStateExtdata(int flags) {
1150	m_saveStateFlags = flags;
1151}
1152
1153void GameController::setLoadStateExtdata(int flags) {
1154	m_loadStateFlags = flags;
1155}
1156
1157void GameController::setLuminanceValue(uint8_t value) {
1158	m_luxValue = value;
1159	value = std::max<int>(value - 0x16, 0);
1160	m_luxLevel = 10;
1161	for (int i = 0; i < 10; ++i) {
1162		if (value < GBA_LUX_LEVELS[i]) {
1163			m_luxLevel = i;
1164			break;
1165		}
1166	}
1167	emit luminanceValueChanged(m_luxValue);
1168}
1169
1170void GameController::setLuminanceLevel(int level) {
1171	int value = 0x16;
1172	level = std::max(0, std::min(10, level));
1173	if (level > 0) {
1174		value += GBA_LUX_LEVELS[level - 1];
1175	}
1176	setLuminanceValue(value);
1177}
1178
1179void GameController::setRealTime() {
1180	if (!isLoaded()) {
1181		return;
1182	}
1183	m_threadContext.core->rtc.override = RTC_NO_OVERRIDE;
1184}
1185
1186void GameController::setFixedTime(const QDateTime& time) {
1187	if (!isLoaded()) {
1188		return;
1189	}
1190	m_threadContext.core->rtc.override = RTC_FIXED;
1191	m_threadContext.core->rtc.value = time.toMSecsSinceEpoch();
1192}
1193
1194void GameController::setFakeEpoch(const QDateTime& time) {
1195	if (!isLoaded()) {
1196		return;
1197	}
1198	m_threadContext.core->rtc.override = RTC_FAKE_EPOCH;
1199	m_threadContext.core->rtc.value = time.toMSecsSinceEpoch();
1200}
1201
1202void GameController::updateKeys() {
1203	int activeKeys = m_activeKeys;
1204	activeKeys |= m_activeButtons;
1205	activeKeys &= ~m_inactiveKeys;
1206	if (isLoaded()) {
1207		m_threadContext.core->setKeys(m_threadContext.core, activeKeys);
1208	}
1209}
1210
1211void GameController::redoSamples(int samples) {
1212	if (m_threadContext.core) {
1213		m_threadContext.core->setAudioBufferSize(m_threadContext.core, samples);
1214	}
1215	m_audioProcessor->inputParametersChanged();
1216}
1217
1218void GameController::setLogLevel(int levels) {
1219	Interrupter interrupter(this);
1220	m_logLevels = levels;
1221}
1222
1223void GameController::enableLogLevel(int levels) {
1224	Interrupter interrupter(this);
1225	m_logLevels |= levels;
1226}
1227
1228void GameController::disableLogLevel(int levels) {
1229	Interrupter interrupter(this);
1230	m_logLevels &= ~levels;
1231}
1232
1233void GameController::pollEvents() {
1234	if (!m_inputController) {
1235		return;
1236	}
1237
1238	m_activeButtons = m_inputController->pollEvents();
1239	updateKeys();
1240}
1241
1242void GameController::updateAutofire() {
1243	// TODO: Move all key events onto the CPU thread...somehow
1244	for (int k = 0; k < GBA_KEY_MAX; ++k) {
1245		if (!m_autofire[k]) {
1246			continue;
1247		}
1248		m_autofireStatus[k] ^= 1;
1249		if (m_autofireStatus[k]) {
1250			keyPressed(k);
1251		} else {
1252			keyReleased(k);
1253		}
1254	}
1255}
1256
1257std::shared_ptr<mTileCache> GameController::tileCache() {
1258	if (m_tileCache) {
1259		return m_tileCache;
1260	}
1261	switch (platform()) {
1262#ifdef M_CORE_GBA
1263	case PLATFORM_GBA: {
1264		Interrupter interrupter(this);
1265		GBA* gba = static_cast<GBA*>(m_threadContext.core->board);
1266		m_tileCache = std::make_shared<mTileCache>();
1267		GBAVideoTileCacheInit(m_tileCache.get());
1268		GBAVideoTileCacheAssociate(m_tileCache.get(), &gba->video);
1269		mTileCacheSetPalette(m_tileCache.get(), 0);
1270		break;
1271	}
1272#endif
1273#ifdef M_CORE_GB
1274	case PLATFORM_GB: {
1275		Interrupter interrupter(this);
1276		GB* gb = static_cast<GB*>(m_threadContext.core->board);
1277		m_tileCache = std::make_shared<mTileCache>();
1278		GBVideoTileCacheInit(m_tileCache.get());
1279		GBVideoTileCacheAssociate(m_tileCache.get(), &gb->video);
1280		mTileCacheSetPalette(m_tileCache.get(), 0);
1281		break;
1282	}
1283#endif
1284	default:
1285		return nullptr;
1286	}
1287	return m_tileCache;
1288}
1289
1290GameController::Interrupter::Interrupter(GameController* parent, bool fromThread)
1291	: m_parent(parent)
1292	, m_fromThread(fromThread)
1293{
1294	if (!m_fromThread) {
1295		m_parent->threadInterrupt();
1296	} else {
1297		mCoreThreadInterruptFromThread(m_parent->thread());
1298	}
1299}
1300
1301GameController::Interrupter::~Interrupter() {
1302	if (!m_fromThread) {
1303		m_parent->threadContinue();
1304	} else {
1305		mCoreThreadContinue(m_parent->thread());
1306	}
1307}