all repos — mgba @ ccfb9f24f53c4d5d0d78573d46fe7bcea60126bd

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