all repos — mgba @ 63ed7421ce05174608dd1799f8e7b0a5f01d5c3d

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