all repos — mgba @ 893fdd383f3f4f59de31ac617bc8a28d3f8059c6

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