all repos — mgba @ a5f029c2faa14f9e65d6c8413498057348100ede

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