all repos — mgba @ dc60c28bf10aee056e61e5111cee4a857d2cc33b

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->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.sync.audioWait;
 303		m_videoSync = m_threadContext.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	if (m_turbo) {
 414		m_threadContext.sync.videoFrameWait = false;
 415		m_threadContext.sync.audioWait = false;
 416	} else {
 417		m_threadContext.sync.videoFrameWait = m_videoSync;
 418		m_threadContext.sync.audioWait = m_audioSync;
 419	}
 420	m_threadContext.core->init(m_threadContext.core);
 421	mCoreInitConfig(m_threadContext.core, nullptr);
 422
 423	unsigned width, height;
 424	m_threadContext.core->desiredVideoDimensions(m_threadContext.core, &width, &height);
 425	m_drawContext = new uint32_t[width * height];
 426	m_frontBuffer = new uint32_t[width * height];
 427
 428	if (m_config) {
 429		mCoreLoadForeignConfig(m_threadContext.core, m_config);
 430	}
 431
 432	QByteArray bytes;
 433	if (!biosOnly) {
 434		bytes = m_fname.toUtf8();
 435		if (m_preload) {
 436			if (m_vf) {
 437				mCorePreloadVF(m_threadContext.core, m_vf);
 438			} else {
 439				mCorePreloadFile(m_threadContext.core, bytes.constData());
 440				mDirectorySetDetachBase(&m_threadContext.core->dirs);
 441			}
 442		} else {
 443			if (m_vf) {
 444				m_threadContext.core->loadROM(m_threadContext.core, m_vf);
 445			} else {
 446				mCoreLoadFile(m_threadContext.core, bytes.constData());
 447				mDirectorySetDetachBase(&m_threadContext.core->dirs);
 448			}
 449		}
 450	} else {
 451		bytes = m_bios.toUtf8();
 452	}
 453	if (bytes.isNull()) {
 454		return;
 455	}
 456
 457	char dirname[PATH_MAX];
 458	separatePath(bytes.constData(), dirname, m_threadContext.core->dirs.baseName, 0);
 459	mDirectorySetAttachBase(&m_threadContext.core->dirs, VDirOpen(dirname));
 460
 461	m_threadContext.core->setVideoBuffer(m_threadContext.core, m_drawContext, width);
 462
 463	m_inputController->recalibrateAxes();
 464	memset(m_drawContext, 0xF8, width * height * 4);
 465
 466	m_threadContext.core->setAVStream(m_threadContext.core, m_stream);
 467
 468	if (!biosOnly) {
 469		mCoreAutoloadSave(m_threadContext.core);
 470		if (!m_patch.isNull()) {
 471			VFile* patch = VFileDevice::open(m_patch, O_RDONLY);
 472			if (patch) {
 473				m_threadContext.core->loadPatch(m_threadContext.core, patch);
 474			}
 475			patch->close(patch);
 476			m_patch = QString();
 477		} else {
 478			mCoreAutoloadPatch(m_threadContext.core);
 479		}
 480	}
 481	m_vf = nullptr;
 482
 483	if (!mCoreThreadStart(&m_threadContext)) {
 484		emit gameFailed();
 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.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.rewind, capacity, true);
 714			m_threadContext.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.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		m_threadContext.sync.audioWait = false;
 854		m_threadContext.sync.videoFrameWait = true;
 855	}
 856}
 857
 858void GameController::setVideoLayerEnabled(int layer, bool enable) {
 859	if (layer > 4 || layer < 0) {
 860		return;
 861	}
 862	m_videoLayers.reserve(layer + 1);
 863	while (m_videoLayers.size() <= layer) {
 864		m_videoLayers.append(true);
 865	}
 866	m_videoLayers[layer] = enable;
 867	if (isLoaded()) {
 868		m_threadContext.core->enableVideoLayer(m_threadContext.core, layer, enable);
 869	}
 870}
 871
 872void GameController::setFPSTarget(float fps) {
 873	Interrupter interrupter(this);
 874	m_fpsTarget = fps;
 875	m_threadContext.sync.fpsTarget = fps;
 876	if (m_turbo && m_turboSpeed > 0) {
 877		m_threadContext.sync.fpsTarget *= m_turboSpeed;
 878	}
 879	if (m_audioProcessor) {
 880		redoSamples(m_audioProcessor->getBufferSamples());
 881	}
 882}
 883
 884void GameController::setUseBIOS(bool use) {
 885	if (use == m_useBios) {
 886		return;
 887	}
 888	m_useBios = use;
 889	if (m_gameOpen) {
 890		closeGame();
 891		openGame();
 892	}
 893}
 894
 895void GameController::loadState(int slot) {
 896	if (m_fname.isEmpty()) {
 897		// We're in the BIOS
 898		return;
 899	}
 900	if (slot > 0 && slot != m_stateSlot) {
 901		m_stateSlot = slot;
 902		m_backupSaveState.clear();
 903	}
 904	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 905		GameController* controller = static_cast<GameController*>(context->userData);
 906		if (!controller->m_backupLoadState) {
 907			controller->m_backupLoadState = VFileMemChunk(nullptr, 0);
 908		}
 909		mCoreLoadStateNamed(context->core, controller->m_backupLoadState, controller->m_saveStateFlags);
 910		if (mCoreLoadState(context->core, controller->m_stateSlot, controller->m_loadStateFlags)) {
 911			emit controller->frameAvailable(controller->m_drawContext);
 912			emit controller->stateLoaded(context);
 913		}
 914	});
 915}
 916
 917void GameController::saveState(int slot) {
 918	if (m_fname.isEmpty()) {
 919		// We're in the BIOS
 920		return;
 921	}
 922	if (slot > 0) {
 923		m_stateSlot = slot;
 924	}
 925	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 926		GameController* controller = static_cast<GameController*>(context->userData);
 927		VFile* vf = mCoreGetState(context->core, controller->m_stateSlot, false);
 928		if (vf) {
 929			controller->m_backupSaveState.resize(vf->size(vf));
 930			vf->read(vf, controller->m_backupSaveState.data(), controller->m_backupSaveState.size());
 931			vf->close(vf);
 932		}
 933		mCoreSaveState(context->core, controller->m_stateSlot, controller->m_saveStateFlags);
 934	});
 935}
 936
 937void GameController::loadBackupState() {
 938	if (!m_backupLoadState) {
 939		return;
 940	}
 941
 942	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 943		GameController* controller = static_cast<GameController*>(context->userData);
 944		controller->m_backupLoadState->seek(controller->m_backupLoadState, 0, SEEK_SET);
 945		if (mCoreLoadStateNamed(context->core, controller->m_backupLoadState, controller->m_loadStateFlags)) {
 946			mLOG(STATUS, INFO, "Undid state load");
 947			controller->frameAvailable(controller->m_drawContext);
 948			controller->stateLoaded(context);
 949		}
 950		controller->m_backupLoadState->close(controller->m_backupLoadState);
 951		controller->m_backupLoadState = nullptr;
 952	});
 953}
 954
 955void GameController::saveBackupState() {
 956	if (m_backupSaveState.isEmpty()) {
 957		return;
 958	}
 959
 960	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 961		GameController* controller = static_cast<GameController*>(context->userData);
 962		VFile* vf = mCoreGetState(context->core, controller->m_stateSlot, true);
 963		if (vf) {
 964			vf->write(vf, controller->m_backupSaveState.constData(), controller->m_backupSaveState.size());
 965			vf->close(vf);
 966			mLOG(STATUS, INFO, "Undid state save");
 967		}
 968		controller->m_backupSaveState.clear();
 969	});
 970}
 971
 972void GameController::setTurbo(bool set, bool forced) {
 973	if (m_turboForced && !forced) {
 974		return;
 975	}
 976	if (m_turbo == set && m_turboForced == (set && forced)) {
 977		// Don't interrupt the thread if we don't need to
 978		return;
 979	}
 980	if (!m_sync) {
 981		return;
 982	}
 983	m_turbo = set;
 984	m_turboForced = set && forced;
 985	enableTurbo();
 986}
 987
 988void GameController::setTurboSpeed(float ratio) {
 989	m_turboSpeed = ratio;
 990	enableTurbo();
 991}
 992
 993void GameController::enableTurbo() {
 994	Interrupter interrupter(this);
 995	bool shouldRedoSamples = false;
 996	if (!m_turbo) {
 997		shouldRedoSamples = m_threadContext.sync.fpsTarget != m_fpsTarget;
 998		m_threadContext.sync.fpsTarget = m_fpsTarget;
 999		m_threadContext.sync.audioWait = m_audioSync;
1000		m_threadContext.sync.videoFrameWait = m_videoSync;
1001	} else if (m_turboSpeed <= 0) {
1002		shouldRedoSamples = m_threadContext.sync.fpsTarget != m_fpsTarget;
1003		m_threadContext.sync.fpsTarget = m_fpsTarget;
1004		m_threadContext.sync.audioWait = false;
1005		m_threadContext.sync.videoFrameWait = false;
1006	} else {
1007		shouldRedoSamples = m_threadContext.sync.fpsTarget != m_fpsTarget * m_turboSpeed;
1008		m_threadContext.sync.fpsTarget = m_fpsTarget * m_turboSpeed;
1009		m_threadContext.sync.audioWait = true;
1010		m_threadContext.sync.videoFrameWait = false;
1011	}
1012	if (m_audioProcessor && shouldRedoSamples) {
1013		redoSamples(m_audioProcessor->getBufferSamples());
1014	}
1015}
1016
1017void GameController::setSync(bool enable) {
1018	m_turbo = false;
1019	m_turboForced = false;
1020	if (!enable) {
1021		m_threadContext.sync.audioWait = false;
1022		m_threadContext.sync.videoFrameWait = false;
1023	} else {
1024		m_threadContext.sync.audioWait = m_audioSync;
1025		m_threadContext.sync.videoFrameWait = m_videoSync;
1026	}
1027	m_sync = enable;
1028}
1029
1030void GameController::setAudioSync(bool enable) {
1031	m_audioSync = enable;
1032	m_threadContext.sync.audioWait = enable;
1033}
1034
1035void GameController::setVideoSync(bool enable) {
1036	m_videoSync = enable;
1037	m_threadContext.sync.videoFrameWait = enable;
1038}
1039
1040void GameController::setAVStream(mAVStream* stream) {
1041	Interrupter interrupter(this);
1042	m_stream = stream;
1043	if (isLoaded()) {
1044		m_threadContext.core->setAVStream(m_threadContext.core, stream);
1045	}
1046}
1047
1048void GameController::clearAVStream() {
1049	Interrupter interrupter(this);
1050	m_stream = nullptr;
1051	if (isLoaded()) {
1052		m_threadContext.core->setAVStream(m_threadContext.core, nullptr);
1053	}
1054}
1055
1056#ifdef USE_PNG
1057void GameController::screenshot() {
1058	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
1059		mCoreTakeScreenshot(context->core);
1060	});
1061}
1062#endif
1063
1064void GameController::reloadAudioDriver() {
1065	int samples = 0;
1066	unsigned sampleRate = 0;
1067	if (m_audioProcessor) {
1068		m_audioProcessor->pause();
1069		samples = m_audioProcessor->getBufferSamples();
1070		sampleRate = m_audioProcessor->sampleRate();
1071		delete m_audioProcessor;
1072	}
1073	m_audioProcessor = AudioProcessor::create();
1074	if (samples) {
1075		m_audioProcessor->setBufferSamples(samples);
1076	}
1077	if (sampleRate) {
1078		m_audioProcessor->requestSampleRate(sampleRate);
1079	}
1080	connect(this, &GameController::gamePaused, m_audioProcessor, &AudioProcessor::pause);
1081	connect(this, &GameController::gameStarted, m_audioProcessor, &AudioProcessor::setInput);
1082	if (isLoaded()) {
1083		m_audioProcessor->setInput(&m_threadContext);
1084		startAudio();
1085	}
1086}
1087
1088void GameController::setSaveStateExtdata(int flags) {
1089	m_saveStateFlags = flags;
1090}
1091
1092void GameController::setLoadStateExtdata(int flags) {
1093	m_loadStateFlags = flags;
1094}
1095
1096void GameController::setPreload(bool preload) {
1097	m_preload = preload;
1098}
1099
1100void GameController::setLuminanceValue(uint8_t value) {
1101	m_luxValue = value;
1102	value = std::max<int>(value - 0x16, 0);
1103	m_luxLevel = 10;
1104	for (int i = 0; i < 10; ++i) {
1105		if (value < GBA_LUX_LEVELS[i]) {
1106			m_luxLevel = i;
1107			break;
1108		}
1109	}
1110	emit luminanceValueChanged(m_luxValue);
1111}
1112
1113void GameController::setLuminanceLevel(int level) {
1114	int value = 0x16;
1115	level = std::max(0, std::min(10, level));
1116	if (level > 0) {
1117		value += GBA_LUX_LEVELS[level - 1];
1118	}
1119	setLuminanceValue(value);
1120}
1121
1122void GameController::setRealTime() {
1123	if (!isLoaded()) {
1124		return;
1125	}
1126	m_threadContext.core->rtc.override = RTC_NO_OVERRIDE;
1127}
1128
1129void GameController::setFixedTime(const QDateTime& time) {
1130	if (!isLoaded()) {
1131		return;
1132	}
1133	m_threadContext.core->rtc.override = RTC_FIXED;
1134	m_threadContext.core->rtc.value = time.toMSecsSinceEpoch();
1135}
1136
1137void GameController::setFakeEpoch(const QDateTime& time) {
1138	if (!isLoaded()) {
1139		return;
1140	}
1141	m_threadContext.core->rtc.override = RTC_FAKE_EPOCH;
1142	m_threadContext.core->rtc.value = time.toMSecsSinceEpoch();
1143}
1144
1145void GameController::updateKeys() {
1146	int activeKeys = m_activeKeys;
1147	activeKeys |= m_activeButtons;
1148	activeKeys &= ~m_inactiveKeys;
1149	if (isLoaded()) {
1150		m_threadContext.core->setKeys(m_threadContext.core, activeKeys);
1151	}
1152}
1153
1154void GameController::redoSamples(int samples) {
1155	if (m_gameOpen && m_threadContext.core) {
1156		m_threadContext.core->setAudioBufferSize(m_threadContext.core, samples);
1157	}
1158	m_audioProcessor->inputParametersChanged();
1159}
1160
1161void GameController::setLogLevel(int levels) {
1162	Interrupter interrupter(this);
1163	m_logLevels = levels;
1164}
1165
1166void GameController::enableLogLevel(int levels) {
1167	Interrupter interrupter(this);
1168	m_logLevels |= levels;
1169}
1170
1171void GameController::disableLogLevel(int levels) {
1172	Interrupter interrupter(this);
1173	m_logLevels &= ~levels;
1174}
1175
1176void GameController::startVideoLog(const QString& path) {
1177	if (!isLoaded() || m_vl) {
1178		return;
1179	}
1180
1181	Interrupter interrupter(this);
1182	m_vl = mVideoLogContextCreate(m_threadContext.core);
1183	m_vlVf = VFileDevice::open(path, O_WRONLY | O_CREAT | O_TRUNC);
1184	mVideoLogContextSetOutput(m_vl, m_vlVf);
1185	mVideoLogContextWriteHeader(m_vl, m_threadContext.core);
1186}
1187
1188void GameController::endVideoLog() {
1189	if (!m_vl) {
1190		return;
1191	}
1192
1193	Interrupter interrupter(this);
1194	mVideoLogContextDestroy(m_threadContext.core, m_vl);
1195	if (m_vlVf) {
1196		m_vlVf->close(m_vlVf);
1197		m_vlVf = nullptr;
1198	}
1199	m_vl = nullptr;
1200}
1201
1202void GameController::pollEvents() {
1203	if (!m_inputController) {
1204		return;
1205	}
1206
1207	m_activeButtons = m_inputController->pollEvents();
1208	updateKeys();
1209}
1210
1211void GameController::updateAutofire() {
1212	// TODO: Move all key events onto the CPU thread...somehow
1213	for (int k = 0; k < GBA_KEY_MAX; ++k) {
1214		if (!m_autofire[k]) {
1215			continue;
1216		}
1217		m_autofireStatus[k] ^= 1;
1218		if (m_autofireStatus[k]) {
1219			keyPressed(k);
1220		} else {
1221			keyReleased(k);
1222		}
1223	}
1224}
1225
1226std::shared_ptr<mTileCache> GameController::tileCache() {
1227	if (m_tileCache) {
1228		return m_tileCache;
1229	}
1230	Interrupter interrupter(this);
1231	switch (platform()) {
1232#ifdef M_CORE_GBA
1233	case PLATFORM_GBA: {
1234		GBA* gba = static_cast<GBA*>(m_threadContext.core->board);
1235		m_tileCache = std::make_shared<mTileCache>();
1236		GBAVideoTileCacheInit(m_tileCache.get());
1237		GBAVideoTileCacheAssociate(m_tileCache.get(), &gba->video);
1238		mTileCacheSetPalette(m_tileCache.get(), 0);
1239		break;
1240	}
1241#endif
1242#ifdef M_CORE_GB
1243	case PLATFORM_GB: {
1244		GB* gb = static_cast<GB*>(m_threadContext.core->board);
1245		m_tileCache = std::make_shared<mTileCache>();
1246		GBVideoTileCacheInit(m_tileCache.get());
1247		GBVideoTileCacheAssociate(m_tileCache.get(), &gb->video);
1248		mTileCacheSetPalette(m_tileCache.get(), 0);
1249		break;
1250	}
1251#endif
1252	default:
1253		return nullptr;
1254	}
1255	return m_tileCache;
1256}
1257
1258GameController::Interrupter::Interrupter(GameController* parent, bool fromThread)
1259	: m_parent(parent)
1260	, m_fromThread(fromThread)
1261{
1262	if (!m_fromThread) {
1263		m_parent->threadInterrupt();
1264	} else {
1265		mCoreThreadInterruptFromThread(m_parent->thread());
1266	}
1267}
1268
1269GameController::Interrupter::~Interrupter() {
1270	if (!m_fromThread) {
1271		m_parent->threadContinue();
1272	} else {
1273		mCoreThreadContinue(m_parent->thread());
1274	}
1275}