all repos — mgba @ 0f356a9582199674563ae3614ff8c6983a80e71d

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