all repos — mgba @ 1a0e44c014ad34bea30d237d27015d82d02cda4b

mGBA Game Boy Advance Emulator

src/platform/qt/GameController.cpp (view raw)

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