all repos — mgba @ eab5ed6e142e75656adbe918f2422d936f67c5c2

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_DEBUGGERS
 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#ifdef USE_DEBUGGERS
 626	setDebugger(nullptr);
 627#endif
 628	if (mCoreThreadIsPaused(&m_threadContext)) {
 629		mCoreThreadUnpause(&m_threadContext);
 630	}
 631	mCoreThreadEnd(&m_threadContext);
 632}
 633
 634void GameController::cleanGame() {
 635	if (!m_gameOpen || mCoreThreadIsActive(&m_threadContext)) {
 636		return;
 637	}
 638
 639	m_audioProcessor->pause();
 640	mCoreThreadJoin(&m_threadContext);
 641
 642	if (m_tileCache) {
 643		mTileCacheDeinit(m_tileCache.get());
 644		m_tileCache.reset();
 645	}
 646
 647	delete[] m_drawContext;
 648	delete[] m_frontBuffer;
 649
 650	m_threadContext.core->deinit(m_threadContext.core);
 651	m_threadContext.core = nullptr;
 652	m_gameOpen = false;
 653}
 654
 655void GameController::crashGame(const QString& crashMessage) {
 656	closeGame();
 657	emit gameCrashed(crashMessage);
 658}
 659
 660bool GameController::isPaused() {
 661	if (!m_gameOpen) {
 662		return false;
 663	}
 664	return mCoreThreadIsPaused(&m_threadContext);
 665}
 666
 667mPlatform GameController::platform() const {
 668	if (!m_gameOpen) {
 669		return PLATFORM_NONE;
 670	}
 671	return m_threadContext.core->platform(m_threadContext.core);
 672}
 673
 674QSize GameController::screenDimensions() const {
 675	if (!m_gameOpen) {
 676		return QSize();
 677	}
 678	unsigned width, height;
 679	m_threadContext.core->desiredVideoDimensions(m_threadContext.core, &width, &height);
 680
 681	return QSize(width, height);
 682}
 683
 684void GameController::setPaused(bool paused) {
 685	if (!isLoaded() || paused == mCoreThreadIsPaused(&m_threadContext)) {
 686		return;
 687	}
 688	m_wasPaused = paused;
 689	if (paused) {
 690		m_pauseAfterFrame.testAndSetRelaxed(false, true);
 691	} else {
 692		mCoreThreadUnpause(&m_threadContext);
 693		startAudio();
 694		emit gameUnpaused(&m_threadContext);
 695	}
 696}
 697
 698void GameController::reset() {
 699	if (!m_gameOpen) {
 700		return;
 701	}
 702	bool wasPaused = isPaused();
 703	setPaused(false);
 704	Interrupter interrupter(this);
 705	mCoreThreadReset(&m_threadContext);
 706	if (wasPaused) {
 707		setPaused(true);
 708	}
 709}
 710
 711void GameController::threadInterrupt() {
 712	if (m_gameOpen) {
 713		mCoreThreadInterrupt(&m_threadContext);
 714	}
 715}
 716
 717void GameController::threadContinue() {
 718	if (m_gameOpen) {
 719		mCoreThreadContinue(&m_threadContext);
 720	}
 721}
 722
 723void GameController::frameAdvance() {
 724	if (m_pauseAfterFrame.testAndSetRelaxed(false, true)) {
 725		setPaused(false);
 726	}
 727}
 728
 729void GameController::setRewind(bool enable, int capacity, bool rewindSave) {
 730	if (m_gameOpen) {
 731		Interrupter interrupter(this);
 732		if (m_threadContext.core->opts.rewindEnable && m_threadContext.core->opts.rewindBufferCapacity > 0) {
 733			mCoreRewindContextDeinit(&m_threadContext.rewind);
 734		}
 735		m_threadContext.core->opts.rewindEnable = enable;
 736		m_threadContext.core->opts.rewindBufferCapacity = capacity;
 737		m_threadContext.core->opts.rewindSave = rewindSave;
 738		if (enable && capacity > 0) {
 739			mCoreRewindContextInit(&m_threadContext.rewind, capacity);
 740			 m_threadContext.rewind.stateFlags = rewindSave ? SAVESTATE_SAVEDATA : 0;
 741		}
 742	}
 743}
 744
 745void GameController::rewind(int states) {
 746	threadInterrupt();
 747	if (!states) {
 748		states = INT_MAX;
 749	}
 750	for (int i = 0; i < states; ++i) {
 751		if (!mCoreRewindRestore(&m_threadContext.rewind, m_threadContext.core)) {
 752			break;
 753		}
 754	}
 755	threadContinue();
 756	emit frameAvailable(m_drawContext);
 757	emit rewound(&m_threadContext);
 758}
 759
 760void GameController::startRewinding() {
 761	if (!isLoaded()) {
 762		return;
 763	}
 764	if (!m_threadContext.core->opts.rewindEnable) {
 765		return;
 766	}
 767	if (m_multiplayer && m_multiplayer->attached() > 1) {
 768		return;
 769	}
 770	if (m_wasPaused) {
 771		setPaused(false);
 772		m_wasPaused = true;
 773	}
 774	mCoreThreadSetRewinding(&m_threadContext, true);
 775}
 776
 777void GameController::stopRewinding() {
 778	if (!isLoaded()) {
 779		return;
 780	}
 781	mCoreThreadSetRewinding(&m_threadContext, false);
 782	bool signalsBlocked = blockSignals(true);
 783	setPaused(m_wasPaused);
 784	blockSignals(signalsBlocked);
 785}
 786
 787void GameController::keyPressed(int key) {
 788	int mappedKey = 1 << key;
 789	m_activeKeys |= mappedKey;
 790	if (!m_inputController->allowOpposing()) {
 791		if ((m_activeKeys & 0x30) == 0x30) {
 792			m_inactiveKeys |= mappedKey ^ 0x30;
 793			m_activeKeys ^= mappedKey ^ 0x30;
 794		}
 795		if ((m_activeKeys & 0xC0) == 0xC0) {
 796			m_inactiveKeys |= mappedKey ^ 0xC0;
 797			m_activeKeys ^= mappedKey ^ 0xC0;
 798		}
 799	}
 800	updateKeys();
 801}
 802
 803void GameController::keyReleased(int key) {
 804	int mappedKey = 1 << key;
 805	m_activeKeys &= ~mappedKey;
 806	if (!m_inputController->allowOpposing()) {
 807		if (mappedKey & 0x30) {
 808			m_activeKeys |= m_inactiveKeys & (0x30 ^ mappedKey);
 809			m_inactiveKeys &= ~0x30;
 810		}
 811		if (mappedKey & 0xC0) {
 812			m_activeKeys |= m_inactiveKeys & (0xC0 ^ mappedKey);
 813			m_inactiveKeys &= ~0xC0;
 814		}
 815	}
 816	updateKeys();
 817}
 818
 819void GameController::clearKeys() {
 820	m_activeKeys = 0;
 821	m_inactiveKeys = 0;
 822	updateKeys();
 823}
 824
 825void GameController::setAutofire(int key, bool enable) {
 826	if (key >= GBA_KEY_MAX || key < 0) {
 827		return;
 828	}
 829
 830	if (!enable && m_autofireStatus[key]) {
 831		keyReleased(key);
 832	}
 833
 834	m_autofire[key] = enable;
 835	m_autofireStatus[key] = 0;
 836}
 837
 838void GameController::setAudioBufferSamples(int samples) {
 839	if (m_audioProcessor) {
 840		threadInterrupt();
 841		redoSamples(samples);
 842		threadContinue();
 843		m_audioProcessor->setBufferSamples(samples);
 844	}
 845}
 846
 847void GameController::setAudioSampleRate(unsigned rate) {
 848	if (!rate) {
 849		return;
 850	}
 851	if (m_audioProcessor) {
 852		threadInterrupt();
 853		redoSamples(m_audioProcessor->getBufferSamples());
 854		threadContinue();
 855		m_audioProcessor->requestSampleRate(rate);
 856	}
 857}
 858
 859void GameController::setAudioChannelEnabled(int channel, bool enable) {
 860	if (channel > 5 || channel < 0) {
 861		return;
 862	}
 863	m_audioChannels.reserve(channel + 1);
 864	while (m_audioChannels.size() <= channel) {
 865		m_audioChannels.append(true);
 866	}
 867	m_audioChannels[channel] = enable;
 868	if (isLoaded()) {
 869		m_threadContext.core->enableAudioChannel(m_threadContext.core, channel, enable);
 870	}
 871}
 872
 873void GameController::startAudio() {
 874	if (!m_audioProcessor->start()) {
 875		LOG(QT, ERROR) << tr("Failed to start audio processor");
 876		// Don't freeze!
 877		m_audioSync = false;
 878		m_videoSync = true;
 879		m_threadContext.sync.audioWait = false;
 880		m_threadContext.sync.videoFrameWait = true;
 881	}
 882}
 883
 884void GameController::setVideoLayerEnabled(int layer, bool enable) {
 885	if (layer > 4 || layer < 0) {
 886		return;
 887	}
 888	m_videoLayers.reserve(layer + 1);
 889	while (m_videoLayers.size() <= layer) {
 890		m_videoLayers.append(true);
 891	}
 892	m_videoLayers[layer] = enable;
 893	if (isLoaded()) {
 894		m_threadContext.core->enableVideoLayer(m_threadContext.core, layer, enable);
 895	}
 896}
 897
 898void GameController::setFPSTarget(float fps) {
 899	Interrupter interrupter(this);
 900	m_fpsTarget = fps;
 901	m_threadContext.sync.fpsTarget = fps;
 902	if (m_turbo && m_turboSpeed > 0) {
 903		m_threadContext.sync.fpsTarget *= m_turboSpeed;
 904	}
 905	if (m_audioProcessor) {
 906		redoSamples(m_audioProcessor->getBufferSamples());
 907	}
 908}
 909
 910void GameController::setUseBIOS(bool use) {
 911	if (use == m_useBios) {
 912		return;
 913	}
 914	m_useBios = use;
 915	if (m_gameOpen) {
 916		closeGame();
 917		openGame();
 918	}
 919}
 920
 921void GameController::loadState(int slot) {
 922	if (m_fname.isEmpty()) {
 923		// We're in the BIOS
 924		return;
 925	}
 926	if (slot > 0 && slot != m_stateSlot) {
 927		m_stateSlot = slot;
 928		m_backupSaveState.clear();
 929	}
 930	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 931		GameController* controller = static_cast<GameController*>(context->userData);
 932		if (!controller->m_backupLoadState) {
 933			controller->m_backupLoadState = VFileMemChunk(nullptr, 0);
 934		}
 935		mCoreLoadStateNamed(context->core, controller->m_backupLoadState, controller->m_saveStateFlags);
 936		if (mCoreLoadState(context->core, controller->m_stateSlot, controller->m_loadStateFlags)) {
 937			controller->frameAvailable(controller->m_drawContext);
 938			controller->stateLoaded(context);
 939		}
 940	});
 941}
 942
 943void GameController::saveState(int slot) {
 944	if (m_fname.isEmpty()) {
 945		// We're in the BIOS
 946		return;
 947	}
 948	if (slot > 0) {
 949		m_stateSlot = slot;
 950	}
 951	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 952		GameController* controller = static_cast<GameController*>(context->userData);
 953		VFile* vf = mCoreGetState(context->core, controller->m_stateSlot, false);
 954		if (vf) {
 955			controller->m_backupSaveState.resize(vf->size(vf));
 956			vf->read(vf, controller->m_backupSaveState.data(), controller->m_backupSaveState.size());
 957			vf->close(vf);
 958		}
 959		mCoreSaveState(context->core, controller->m_stateSlot, controller->m_saveStateFlags);
 960	});
 961}
 962
 963void GameController::loadBackupState() {
 964	if (!m_backupLoadState) {
 965		return;
 966	}
 967
 968	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 969		GameController* controller = static_cast<GameController*>(context->userData);
 970		controller->m_backupLoadState->seek(controller->m_backupLoadState, 0, SEEK_SET);
 971		if (mCoreLoadStateNamed(context->core, controller->m_backupLoadState, controller->m_loadStateFlags)) {
 972			mLOG(STATUS, INFO, "Undid state load");
 973			controller->frameAvailable(controller->m_drawContext);
 974			controller->stateLoaded(context);
 975		}
 976		controller->m_backupLoadState->close(controller->m_backupLoadState);
 977		controller->m_backupLoadState = nullptr;
 978	});
 979}
 980
 981void GameController::saveBackupState() {
 982	if (m_backupSaveState.isEmpty()) {
 983		return;
 984	}
 985
 986	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 987		GameController* controller = static_cast<GameController*>(context->userData);
 988		VFile* vf = mCoreGetState(context->core, controller->m_stateSlot, true);
 989		if (vf) {
 990			vf->write(vf, controller->m_backupSaveState.constData(), controller->m_backupSaveState.size());
 991			vf->close(vf);
 992			mLOG(STATUS, INFO, "Undid state save");
 993		}
 994		controller->m_backupSaveState.clear();
 995	});
 996}
 997
 998void GameController::setTurbo(bool set, bool forced) {
 999	if (m_turboForced && !forced) {
1000		return;
1001	}
1002	if (m_turbo == set && m_turboForced == (set && forced)) {
1003		// Don't interrupt the thread if we don't need to
1004		return;
1005	}
1006	if (!m_sync) {
1007		return;
1008	}
1009	m_turbo = set;
1010	m_turboForced = set && forced;
1011	enableTurbo();
1012}
1013
1014void GameController::setTurboSpeed(float ratio) {
1015	m_turboSpeed = ratio;
1016	enableTurbo();
1017}
1018
1019void GameController::enableTurbo() {
1020	Interrupter interrupter(this);
1021	bool shouldRedoSamples = false;
1022	if (!m_turbo) {
1023		shouldRedoSamples = m_threadContext.sync.fpsTarget != m_fpsTarget;
1024		m_threadContext.sync.fpsTarget = m_fpsTarget;
1025		m_threadContext.sync.audioWait = m_audioSync;
1026		m_threadContext.sync.videoFrameWait = m_videoSync;
1027	} else if (m_turboSpeed <= 0) {
1028		shouldRedoSamples = m_threadContext.sync.fpsTarget != m_fpsTarget;
1029		m_threadContext.sync.fpsTarget = m_fpsTarget;
1030		m_threadContext.sync.audioWait = false;
1031		m_threadContext.sync.videoFrameWait = false;
1032	} else {
1033		shouldRedoSamples = m_threadContext.sync.fpsTarget != m_fpsTarget * m_turboSpeed;
1034		m_threadContext.sync.fpsTarget = m_fpsTarget * m_turboSpeed;
1035		m_threadContext.sync.audioWait = true;
1036		m_threadContext.sync.videoFrameWait = false;
1037	}
1038	if (m_audioProcessor && shouldRedoSamples) {
1039		redoSamples(m_audioProcessor->getBufferSamples());
1040	}
1041}
1042
1043void GameController::setSync(bool enable) {
1044	m_turbo = false;
1045	m_turboForced = false;
1046	if (!enable) {
1047		m_threadContext.sync.audioWait = false;
1048		m_threadContext.sync.videoFrameWait = false;
1049	} else {
1050		m_threadContext.sync.audioWait = m_audioSync;
1051		m_threadContext.sync.videoFrameWait = m_videoSync;
1052	}
1053	m_sync = enable;
1054}
1055
1056void GameController::setAudioSync(bool enable) {
1057	m_audioSync = enable;
1058	m_threadContext.sync.audioWait = enable;
1059}
1060
1061void GameController::setVideoSync(bool enable) {
1062	m_videoSync = enable;
1063	m_threadContext.sync.videoFrameWait = enable;
1064}
1065
1066void GameController::setAVStream(mAVStream* stream) {
1067	Interrupter interrupter(this);
1068	m_stream = stream;
1069	if (isLoaded()) {
1070		m_threadContext.core->setAVStream(m_threadContext.core, stream);
1071	}
1072}
1073
1074void GameController::clearAVStream() {
1075	Interrupter interrupter(this);
1076	m_stream = nullptr;
1077	if (isLoaded()) {
1078		m_threadContext.core->setAVStream(m_threadContext.core, nullptr);
1079	}
1080}
1081
1082#ifdef USE_PNG
1083void GameController::screenshot() {
1084	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
1085		mCoreTakeScreenshot(context->core);
1086	});
1087}
1088#endif
1089
1090void GameController::reloadAudioDriver() {
1091	int samples = 0;
1092	unsigned sampleRate = 0;
1093	if (m_audioProcessor) {
1094		m_audioProcessor->pause();
1095		samples = m_audioProcessor->getBufferSamples();
1096		sampleRate = m_audioProcessor->sampleRate();
1097		delete m_audioProcessor;
1098	}
1099	m_audioProcessor = AudioProcessor::create();
1100	if (samples) {
1101		m_audioProcessor->setBufferSamples(samples);
1102	}
1103	if (sampleRate) {
1104		m_audioProcessor->requestSampleRate(sampleRate);
1105	}
1106	connect(this, SIGNAL(gamePaused(mCoreThread*)), m_audioProcessor, SLOT(pause()));
1107	connect(this, SIGNAL(gameStarted(mCoreThread*, const QString&)), m_audioProcessor, SLOT(setInput(mCoreThread*)));
1108	if (isLoaded()) {
1109		m_audioProcessor->setInput(&m_threadContext);
1110		startAudio();
1111	}
1112}
1113
1114void GameController::setSaveStateExtdata(int flags) {
1115	m_saveStateFlags = flags;
1116}
1117
1118void GameController::setLoadStateExtdata(int flags) {
1119	m_loadStateFlags = flags;
1120}
1121
1122void GameController::setPreload(bool preload) {
1123	m_preload = preload;
1124}
1125
1126void GameController::setLuminanceValue(uint8_t value) {
1127	m_luxValue = value;
1128	value = std::max<int>(value - 0x16, 0);
1129	m_luxLevel = 10;
1130	for (int i = 0; i < 10; ++i) {
1131		if (value < GBA_LUX_LEVELS[i]) {
1132			m_luxLevel = i;
1133			break;
1134		}
1135	}
1136	emit luminanceValueChanged(m_luxValue);
1137}
1138
1139void GameController::setLuminanceLevel(int level) {
1140	int value = 0x16;
1141	level = std::max(0, std::min(10, level));
1142	if (level > 0) {
1143		value += GBA_LUX_LEVELS[level - 1];
1144	}
1145	setLuminanceValue(value);
1146}
1147
1148void GameController::setRealTime() {
1149	if (!isLoaded()) {
1150		return;
1151	}
1152	m_threadContext.core->rtc.override = RTC_NO_OVERRIDE;
1153}
1154
1155void GameController::setFixedTime(const QDateTime& time) {
1156	if (!isLoaded()) {
1157		return;
1158	}
1159	m_threadContext.core->rtc.override = RTC_FIXED;
1160	m_threadContext.core->rtc.value = time.toMSecsSinceEpoch();
1161}
1162
1163void GameController::setFakeEpoch(const QDateTime& time) {
1164	if (!isLoaded()) {
1165		return;
1166	}
1167	m_threadContext.core->rtc.override = RTC_FAKE_EPOCH;
1168	m_threadContext.core->rtc.value = time.toMSecsSinceEpoch();
1169}
1170
1171void GameController::updateKeys() {
1172	int activeKeys = m_activeKeys;
1173	activeKeys |= m_activeButtons;
1174	activeKeys &= ~m_inactiveKeys;
1175	if (isLoaded()) {
1176		m_threadContext.core->setKeys(m_threadContext.core, activeKeys);
1177	}
1178}
1179
1180void GameController::redoSamples(int samples) {
1181	if (m_gameOpen && m_threadContext.core) {
1182		m_threadContext.core->setAudioBufferSize(m_threadContext.core, samples);
1183	}
1184	m_audioProcessor->inputParametersChanged();
1185}
1186
1187void GameController::setLogLevel(int levels) {
1188	Interrupter interrupter(this);
1189	m_logLevels = levels;
1190}
1191
1192void GameController::enableLogLevel(int levels) {
1193	Interrupter interrupter(this);
1194	m_logLevels |= levels;
1195}
1196
1197void GameController::disableLogLevel(int levels) {
1198	Interrupter interrupter(this);
1199	m_logLevels &= ~levels;
1200}
1201
1202void GameController::pollEvents() {
1203	if (!m_inputController) {
1204		return;
1205	}
1206
1207	m_activeButtons = m_inputController->pollEvents();
1208	updateKeys();
1209}
1210
1211void GameController::updateAutofire() {
1212	// TODO: Move all key events onto the CPU thread...somehow
1213	for (int k = 0; k < GBA_KEY_MAX; ++k) {
1214		if (!m_autofire[k]) {
1215			continue;
1216		}
1217		m_autofireStatus[k] ^= 1;
1218		if (m_autofireStatus[k]) {
1219			keyPressed(k);
1220		} else {
1221			keyReleased(k);
1222		}
1223	}
1224}
1225
1226std::shared_ptr<mTileCache> GameController::tileCache() {
1227	if (m_tileCache) {
1228		return m_tileCache;
1229	}
1230	switch (platform()) {
1231#ifdef M_CORE_GBA
1232	case PLATFORM_GBA: {
1233		Interrupter interrupter(this);
1234		GBA* gba = static_cast<GBA*>(m_threadContext.core->board);
1235		m_tileCache = std::make_shared<mTileCache>();
1236		GBAVideoTileCacheInit(m_tileCache.get());
1237		GBAVideoTileCacheAssociate(m_tileCache.get(), &gba->video);
1238		mTileCacheSetPalette(m_tileCache.get(), 0);
1239		break;
1240	}
1241#endif
1242#ifdef M_CORE_GB
1243	case PLATFORM_GB: {
1244		Interrupter interrupter(this);
1245		GB* gb = static_cast<GB*>(m_threadContext.core->board);
1246		m_tileCache = std::make_shared<mTileCache>();
1247		GBVideoTileCacheInit(m_tileCache.get());
1248		GBVideoTileCacheAssociate(m_tileCache.get(), &gb->video);
1249		mTileCacheSetPalette(m_tileCache.get(), 0);
1250		break;
1251	}
1252#endif
1253	default:
1254		return nullptr;
1255	}
1256	return m_tileCache;
1257}
1258
1259GameController::Interrupter::Interrupter(GameController* parent, bool fromThread)
1260	: m_parent(parent)
1261	, m_fromThread(fromThread)
1262{
1263	if (!m_fromThread) {
1264		m_parent->threadInterrupt();
1265	} else {
1266		mCoreThreadInterruptFromThread(m_parent->thread());
1267	}
1268}
1269
1270GameController::Interrupter::~Interrupter() {
1271	if (!m_fromThread) {
1272		m_parent->threadContinue();
1273	} else {
1274		mCoreThreadContinue(m_parent->thread());
1275	}
1276}