all repos — mgba @ 210ef6db506e26cd3bc2f0eb67d46563285fdfdb

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#include <QThread>
  17
  18#include <ctime>
  19
  20extern "C" {
  21#include "core/config.h"
  22#include "core/directories.h"
  23#ifdef M_CORE_GBA
  24#include "gba/bios.h"
  25#include "gba/core.h"
  26#include "gba/gba.h"
  27#include "gba/serialize.h"
  28#include "gba/extra/sharkport.h"
  29#endif
  30#ifdef M_CORE_GB
  31#include "gb/gb.h"
  32#endif
  33#include "util/vfs.h"
  34}
  35
  36using namespace QGBA;
  37using namespace std;
  38
  39GameController::GameController(QObject* parent)
  40	: QObject(parent)
  41	, m_drawContext(nullptr)
  42	, m_frontBuffer(nullptr)
  43	, m_threadContext()
  44	, m_activeKeys(0)
  45	, m_inactiveKeys(0)
  46	, m_logLevels(0)
  47	, m_gameOpen(false)
  48	, m_useBios(false)
  49	, m_audioThread(new QThread(this))
  50	, m_audioProcessor(AudioProcessor::create())
  51	, m_pauseAfterFrame(false)
  52	, m_videoSync(VIDEO_SYNC)
  53	, m_audioSync(AUDIO_SYNC)
  54	, m_fpsTarget(-1)
  55	, m_turbo(false)
  56	, m_turboForced(false)
  57	, m_turboSpeed(-1)
  58	, m_wasPaused(false)
  59	, m_audioChannels{ true, true, true, true, true, true }
  60	, m_videoLayers{ true, true, true, true, true }
  61	, m_autofire{}
  62	, m_autofireStatus{}
  63	, m_inputController(nullptr)
  64	, m_multiplayer(nullptr)
  65	, m_stream(nullptr)
  66	, m_stateSlot(1)
  67	, m_backupLoadState(nullptr)
  68	, m_backupSaveState(nullptr)
  69	, m_saveStateFlags(SAVESTATE_SCREENSHOT | SAVESTATE_SAVEDATA | SAVESTATE_CHEATS)
  70	, m_loadStateFlags(SAVESTATE_SCREENSHOT)
  71{
  72	m_lux.p = this;
  73	m_lux.sample = [](GBALuminanceSource* context) {
  74		GameControllerLux* lux = static_cast<GameControllerLux*>(context);
  75		lux->value = 0xFF - lux->p->m_luxValue;
  76	};
  77
  78	m_lux.readLuminance = [](GBALuminanceSource* context) {
  79		GameControllerLux* lux = static_cast<GameControllerLux*>(context);
  80		return lux->value;
  81	};
  82	setLuminanceLevel(0);
  83
  84	m_threadContext.startCallback = [](mCoreThread* context) {
  85		GameController* controller = static_cast<GameController*>(context->userData);
  86		if (controller->m_audioProcessor) {
  87			controller->m_audioProcessor->setInput(context);
  88		}
  89		mRTCGenericSourceInit(&controller->m_rtc, context->core);
  90		context->core->setRTC(context->core, &controller->m_rtc.d);
  91		context->core->setRotation(context->core, controller->m_inputController->rotationSource());
  92		context->core->setRumble(context->core, controller->m_inputController->rumble());
  93
  94#ifdef M_CORE_GBA
  95		GBA* gba = static_cast<GBA*>(context->core->board);
  96#endif
  97#ifdef M_CORE_GB
  98		GB* gb = static_cast<GB*>(context->core->board);
  99#endif
 100		switch (context->core->platform(context->core)) {
 101#ifdef M_CORE_GBA
 102		case PLATFORM_GBA:
 103			gba->luminanceSource = &controller->m_lux;
 104			gba->audio.psg.forceDisableCh[0] = !controller->m_audioChannels[0];
 105			gba->audio.psg.forceDisableCh[1] = !controller->m_audioChannels[1];
 106			gba->audio.psg.forceDisableCh[2] = !controller->m_audioChannels[2];
 107			gba->audio.psg.forceDisableCh[3] = !controller->m_audioChannels[3];
 108			gba->audio.forceDisableChA = !controller->m_audioChannels[4];
 109			gba->audio.forceDisableChB = !controller->m_audioChannels[5];
 110			gba->video.renderer->disableBG[0] = !controller->m_videoLayers[0];
 111			gba->video.renderer->disableBG[1] = !controller->m_videoLayers[1];
 112			gba->video.renderer->disableBG[2] = !controller->m_videoLayers[2];
 113			gba->video.renderer->disableBG[3] = !controller->m_videoLayers[3];
 114			gba->video.renderer->disableOBJ = !controller->m_videoLayers[4];
 115			break;
 116#endif
 117#ifdef M_CORE_GB
 118		case PLATFORM_GB:
 119			gb->audio.forceDisableCh[0] = !controller->m_audioChannels[0];
 120			gb->audio.forceDisableCh[1] = !controller->m_audioChannels[1];
 121			gb->audio.forceDisableCh[2] = !controller->m_audioChannels[2];
 122			gb->audio.forceDisableCh[3] = !controller->m_audioChannels[3];
 123			break;
 124#endif
 125		default:
 126			break;
 127		}
 128		controller->m_fpsTarget = context->sync.fpsTarget;
 129
 130		if (mCoreLoadState(context->core, 0, controller->m_loadStateFlags)) {
 131			mCoreDeleteState(context->core, 0);
 132		}
 133		QMetaObject::invokeMethod(controller, "gameStarted", Q_ARG(mCoreThread*, context), Q_ARG(const QString&, controller->m_fname));
 134	};
 135
 136	m_threadContext.cleanCallback = [](mCoreThread* context) {
 137		GameController* controller = static_cast<GameController*>(context->userData);
 138		QMetaObject::invokeMethod(controller, "gameStopped", Q_ARG(mCoreThread*, context));
 139	};
 140
 141	m_threadContext.frameCallback = [](mCoreThread* context) {
 142		GameController* controller = static_cast<GameController*>(context->userData);
 143		unsigned width, height;
 144		controller->m_threadContext.core->desiredVideoDimensions(controller->m_threadContext.core, &width, &height);
 145		memcpy(controller->m_frontBuffer, controller->m_drawContext, width * height * BYTES_PER_PIXEL);
 146		QMetaObject::invokeMethod(controller, "frameAvailable", Q_ARG(const uint32_t*, controller->m_frontBuffer));
 147		if (controller->m_pauseAfterFrame.testAndSetAcquire(true, false)) {
 148			mCoreThreadPauseFromThread(context);
 149			QMetaObject::invokeMethod(controller, "gamePaused", Q_ARG(mCoreThread*, context));
 150		}
 151	};
 152
 153	/*m_threadContext.stopCallback = [](mCoreThread* context) {
 154		if (!context) {
 155			return false;
 156		}
 157		GameController* controller = static_cast<GameController*>(context->userData);
 158		if (!mCoreSaveState(context->core, 0, controller->m_saveStateFlags)) {
 159			return false;
 160		}
 161		QMetaObject::invokeMethod(controller, "closeGame");
 162		return true;
 163	};*/
 164
 165	m_threadContext.logger.d.log = [](mLogger* logger, int category, enum mLogLevel level, const char* format, va_list args) {
 166		mThreadLogger* logContext = reinterpret_cast<mThreadLogger*>(logger);
 167		mCoreThread* context = logContext->p;
 168
 169		static const char* savestateMessage = "State %i loaded";
 170		static const char* savestateFailedMessage = "State %i failed to load";
 171		if (!context) {
 172			return;
 173		}
 174		GameController* controller = static_cast<GameController*>(context->userData);
 175		if (level == mLOG_STUB && category == _mLOG_CAT_GBA_BIOS()) {
 176			va_list argc;
 177			va_copy(argc, args);
 178			int immediate = va_arg(argc, int);
 179			va_end(argc);
 180			QMetaObject::invokeMethod(controller, "unimplementedBiosCall", Q_ARG(int, immediate));
 181		} else if (category == _mLOG_CAT_STATUS()) {
 182			// Slot 0 is reserved for suspend points
 183			if (strncmp(savestateMessage, format, strlen(savestateMessage)) == 0) {
 184				va_list argc;
 185				va_copy(argc, args);
 186				int slot = va_arg(argc, int);
 187				va_end(argc);
 188				if (slot == 0) {
 189					format = "Loaded suspend state";
 190				}
 191			} else if (strncmp(savestateFailedMessage, format, strlen(savestateFailedMessage)) == 0) {
 192				va_list argc;
 193				va_copy(argc, args);
 194				int slot = va_arg(argc, int);
 195				va_end(argc);
 196				if (slot == 0) {
 197					return;
 198				}
 199			}
 200		}
 201		if (level == mLOG_FATAL) {
 202			QMetaObject::invokeMethod(controller, "crashGame", Q_ARG(const QString&, QString().vsprintf(format, args)));
 203		} else if (!(controller->m_logLevels & level)) {
 204			return;
 205		}
 206		QString message(QString().vsprintf(format, args));
 207		if (category == _mLOG_CAT_STATUS()) {
 208			QMetaObject::invokeMethod(controller, "statusPosted", Q_ARG(const QString&, message));
 209		}
 210		QMetaObject::invokeMethod(controller, "postLog", Q_ARG(int, level), Q_ARG(int, category), Q_ARG(const QString&, message));
 211	};
 212
 213	m_threadContext.userData = this;
 214
 215	connect(&m_rewindTimer, &QTimer::timeout, [this]() {
 216		// TODO: Put rewind back
 217		emit frameAvailable(m_drawContext);
 218		emit rewound(&m_threadContext);
 219	});
 220	m_rewindTimer.setInterval(100);
 221
 222	m_audioThread->setObjectName("Audio Thread");
 223	m_audioThread->start(QThread::TimeCriticalPriority);
 224	m_audioProcessor->moveToThread(m_audioThread);
 225	connect(this, SIGNAL(gamePaused(mCoreThread*)), m_audioProcessor, SLOT(pause()));
 226	connect(this, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(pollEvents()));
 227	connect(this, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(updateAutofire()));
 228}
 229
 230GameController::~GameController() {
 231	m_audioThread->quit();
 232	m_audioThread->wait();
 233	disconnect();
 234	clearMultiplayerController();
 235	closeGame();
 236	delete m_backupLoadState;
 237}
 238
 239void GameController::setMultiplayerController(MultiplayerController* controller) {
 240	if (controller == m_multiplayer) {
 241		return;
 242	}
 243	clearMultiplayerController();
 244	m_multiplayer = controller;
 245	controller->attachGame(this);
 246}
 247
 248void GameController::clearMultiplayerController() {
 249	if (!m_multiplayer) {
 250		return;
 251	}
 252	m_multiplayer->detachGame(this);
 253	m_multiplayer = nullptr;
 254}
 255
 256void GameController::setOverride(const GBACartridgeOverride& override) {
 257	// TODO: Put back overrides
 258}
 259
 260void GameController::setConfig(const mCoreConfig* config) {
 261	m_config = config;
 262	if (isLoaded()) {
 263		threadInterrupt();
 264		mCoreLoadForeignConfig(m_threadContext.core, config);
 265		m_audioProcessor->setInput(&m_threadContext);
 266		threadContinue();
 267	}
 268}
 269
 270#ifdef USE_GDB_STUB
 271mDebugger* GameController::debugger() {
 272	if (!isLoaded()) {
 273		return nullptr;
 274	}
 275	return m_threadContext.core->debugger;
 276}
 277
 278void GameController::setDebugger(mDebugger* debugger) {
 279	threadInterrupt();
 280	if (debugger) {
 281		mDebuggerAttach(debugger, m_threadContext.core);
 282	} else {
 283		m_threadContext.core->detachDebugger(m_threadContext.core);
 284	}
 285	threadContinue();
 286}
 287#endif
 288
 289void GameController::loadGame(const QString& path) {
 290	closeGame();
 291	QFileInfo info(path);
 292	if (!info.isReadable()) {
 293		LOG(QT, ERROR) << tr("Failed to open game file: %1").arg(path);
 294		return;
 295	}
 296	m_fname = info.canonicalFilePath();
 297	openGame();
 298}
 299
 300void GameController::bootBIOS() {
 301	closeGame();
 302	m_fname = QString();
 303	openGame(true);
 304}
 305
 306void GameController::openGame(bool biosOnly) {
 307	if (biosOnly && (!m_useBios || m_bios.isNull())) {
 308		return;
 309	}
 310
 311	if (!biosOnly) {
 312		m_threadContext.core = mCoreFind(m_fname.toUtf8().constData());
 313	} else {
 314		m_threadContext.core = GBACoreCreate();
 315	}
 316
 317	if (!m_threadContext.core) {
 318		return;
 319	}
 320
 321	m_gameOpen = true;
 322
 323	m_pauseAfterFrame = false;
 324
 325	if (m_turbo) {
 326		m_threadContext.sync.videoFrameWait = false;
 327		m_threadContext.sync.audioWait = false;
 328	} else {
 329		m_threadContext.sync.videoFrameWait = m_videoSync;
 330		m_threadContext.sync.audioWait = m_audioSync;
 331	}
 332	m_threadContext.core->init(m_threadContext.core);
 333
 334	unsigned width, height;
 335	m_threadContext.core->desiredVideoDimensions(m_threadContext.core, &width, &height);
 336	m_drawContext = new uint32_t[width * height];
 337	m_frontBuffer = new uint32_t[width * height];
 338
 339	if (!biosOnly) {
 340		mCoreLoadFile(m_threadContext.core, m_fname.toUtf8().constData());
 341	}
 342
 343	m_threadContext.core->setVideoBuffer(m_threadContext.core, m_drawContext, width);
 344
 345	if (!m_bios.isNull() && m_useBios) {
 346		VFile* bios = VFileDevice::open(m_bios, O_RDONLY);
 347		if (bios) {
 348			// TODO: Lifetime issues?
 349			m_threadContext.core->loadBIOS(m_threadContext.core, bios, 0);
 350		}
 351	}
 352
 353	if (!m_patch.isNull()) {
 354		VFile* patch = VFileDevice::open(m_patch, O_RDONLY);
 355		if (patch) {
 356			m_threadContext.core->loadPatch(m_threadContext.core, patch);
 357		}
 358		patch->close(patch);
 359	}
 360
 361	m_inputController->recalibrateAxes();
 362	memset(m_drawContext, 0xF8, width * height * 4);
 363
 364	m_threadContext.core->setAVStream(m_threadContext.core, m_stream);
 365
 366	if (m_config) {
 367		mCoreLoadForeignConfig(m_threadContext.core, m_config);
 368	}
 369
 370	if (!biosOnly) {
 371		mCoreAutoloadSave(m_threadContext.core);
 372	}
 373
 374	if (!mCoreThreadStart(&m_threadContext)) {
 375		m_gameOpen = false;
 376		emit gameFailed();
 377	} else if (m_audioProcessor) {
 378		startAudio();
 379	}
 380}
 381
 382void GameController::loadBIOS(const QString& path) {
 383	if (m_bios == path) {
 384		return;
 385	}
 386	m_bios = path;
 387	if (m_gameOpen) {
 388		closeGame();
 389		openGame();
 390	}
 391}
 392
 393void GameController::yankPak() {
 394	if (!m_gameOpen) {
 395		return;
 396	}
 397	threadInterrupt();
 398	GBAYankROM(static_cast<GBA*>(m_threadContext.core->board));
 399	threadContinue();
 400}
 401
 402void GameController::replaceGame(const QString& path) {
 403	if (!m_gameOpen) {
 404		return;
 405	}
 406
 407	QFileInfo info(path);
 408	if (!info.isReadable()) {
 409		LOG(QT, ERROR) << tr("Failed to open game file: %1").arg(path);
 410		return;
 411	}
 412	m_fname = info.canonicalFilePath();
 413	threadInterrupt();
 414	mCoreLoadFile(m_threadContext.core, m_fname.toLocal8Bit().constData());
 415	threadContinue();
 416}
 417
 418void GameController::loadPatch(const QString& path) {
 419	if (m_gameOpen) {
 420		closeGame();
 421		m_patch = path;
 422		openGame();
 423	} else {
 424		m_patch = path;
 425	}
 426}
 427
 428void GameController::importSharkport(const QString& path) {
 429	if (!isLoaded()) {
 430		return;
 431	}
 432	VFile* vf = VFileDevice::open(path, O_RDONLY);
 433	if (!vf) {
 434		LOG(QT, ERROR) << tr("Failed to open snapshot file for reading: %1").arg(path);
 435		return;
 436	}
 437	threadInterrupt();
 438	GBASavedataImportSharkPort(static_cast<GBA*>(m_threadContext.core->board), vf, false);
 439	threadContinue();
 440	vf->close(vf);
 441}
 442
 443void GameController::exportSharkport(const QString& path) {
 444	if (!isLoaded()) {
 445		return;
 446	}
 447	VFile* vf = VFileDevice::open(path, O_WRONLY | O_CREAT | O_TRUNC);
 448	if (!vf) {
 449		LOG(QT, ERROR) << tr("Failed to open snapshot file for writing: %1").arg(path);
 450		return;
 451	}
 452	threadInterrupt();
 453	GBASavedataExportSharkPort(static_cast<GBA*>(m_threadContext.core->board), vf);
 454	threadContinue();
 455	vf->close(vf);
 456}
 457
 458void GameController::closeGame() {
 459	if (!m_gameOpen) {
 460		return;
 461	}
 462	m_gameOpen = false;
 463
 464	m_rewindTimer.stop();
 465	if (mCoreThreadIsPaused(&m_threadContext)) {
 466		mCoreThreadUnpause(&m_threadContext);
 467	}
 468	m_audioProcessor->pause();
 469	mCoreThreadEnd(&m_threadContext);
 470	mCoreThreadJoin(&m_threadContext);
 471	// Make sure the event queue clears out before the thread is reused
 472	QCoreApplication::processEvents();
 473
 474	delete[] m_drawContext;
 475	delete[] m_frontBuffer;
 476
 477	m_patch = QString();
 478
 479	m_threadContext.core->deinit(m_threadContext.core);
 480}
 481
 482void GameController::crashGame(const QString& crashMessage) {
 483	closeGame();
 484	emit gameCrashed(crashMessage);
 485	emit gameStopped(&m_threadContext);
 486}
 487
 488bool GameController::isPaused() {
 489	if (!m_gameOpen) {
 490		return false;
 491	}
 492	return mCoreThreadIsPaused(&m_threadContext);
 493}
 494
 495mPlatform GameController::platform() const {
 496	if (!m_gameOpen) {
 497		return PLATFORM_NONE;
 498	}
 499	return m_threadContext.core->platform(m_threadContext.core);
 500}
 501
 502QSize GameController::screenDimensions() const {
 503	if (!m_gameOpen) {
 504		return QSize();
 505	}
 506	unsigned width, height;
 507	m_threadContext.core->desiredVideoDimensions(m_threadContext.core, &width, &height);
 508
 509	return QSize(width, height);
 510}
 511
 512void GameController::setPaused(bool paused) {
 513	if (!isLoaded() || m_rewindTimer.isActive() || paused == mCoreThreadIsPaused(&m_threadContext)) {
 514		return;
 515	}
 516	if (paused) {
 517		m_pauseAfterFrame.testAndSetRelaxed(false, true);
 518	} else {
 519		mCoreThreadUnpause(&m_threadContext);
 520		startAudio();
 521		emit gameUnpaused(&m_threadContext);
 522	}
 523}
 524
 525void GameController::reset() {
 526	if (!m_gameOpen) {
 527		return;
 528	}
 529	bool wasPaused = isPaused();
 530	setPaused(false);
 531	mCoreThreadReset(&m_threadContext);
 532	if (wasPaused) {
 533		setPaused(true);
 534	}
 535}
 536
 537void GameController::threadInterrupt() {
 538	if (m_gameOpen) {
 539		mCoreThreadInterrupt(&m_threadContext);
 540	}
 541}
 542
 543void GameController::threadContinue() {
 544	if (m_gameOpen) {
 545		mCoreThreadContinue(&m_threadContext);
 546	}
 547}
 548
 549void GameController::frameAdvance() {
 550	if (m_rewindTimer.isActive()) {
 551		return;
 552	}
 553	if (m_pauseAfterFrame.testAndSetRelaxed(false, true)) {
 554		setPaused(false);
 555	}
 556}
 557
 558void GameController::setRewind(bool enable, int capacity, int interval) {
 559	if (m_gameOpen) {
 560		threadInterrupt();
 561		// TODO: Put back rewind
 562		threadContinue();
 563	} else {
 564		// TODO: Put back rewind
 565	}
 566}
 567
 568void GameController::rewind(int states) {
 569	threadInterrupt();
 570	if (!states) {
 571		// TODO: Put back rewind
 572	} else {
 573		// TODO: Put back rewind
 574	}
 575	threadContinue();
 576	emit frameAvailable(m_drawContext);
 577	emit rewound(&m_threadContext);
 578}
 579
 580void GameController::startRewinding() {
 581	if (!m_gameOpen || m_rewindTimer.isActive()) {
 582		return;
 583	}
 584	if (m_multiplayer && m_multiplayer->attached() > 1) {
 585		return;
 586	}
 587	m_wasPaused = isPaused();
 588	if (!mCoreThreadIsPaused(&m_threadContext)) {
 589		mCoreThreadPause(&m_threadContext);
 590	}
 591	m_rewindTimer.start();
 592}
 593
 594void GameController::stopRewinding() {
 595	if (!m_rewindTimer.isActive()) {
 596		return;
 597	}
 598	m_rewindTimer.stop();
 599	bool signalsBlocked = blockSignals(true);
 600	setPaused(m_wasPaused);
 601	blockSignals(signalsBlocked);
 602}
 603
 604void GameController::keyPressed(int key) {
 605	int mappedKey = 1 << key;
 606	m_activeKeys |= mappedKey;
 607	if (!m_inputController->allowOpposing()) {
 608		if ((m_activeKeys & 0x30) == 0x30) {
 609			m_inactiveKeys |= mappedKey ^ 0x30;
 610			m_activeKeys ^= mappedKey ^ 0x30;
 611		}
 612		if ((m_activeKeys & 0xC0) == 0xC0) {
 613			m_inactiveKeys |= mappedKey ^ 0xC0;
 614			m_activeKeys ^= mappedKey ^ 0xC0;
 615		}
 616	}
 617	updateKeys();
 618}
 619
 620void GameController::keyReleased(int key) {
 621	int mappedKey = 1 << key;
 622	m_activeKeys &= ~mappedKey;
 623	if (!m_inputController->allowOpposing()) {
 624		if (mappedKey & 0x30) {
 625			m_activeKeys |= m_inactiveKeys & (0x30 ^ mappedKey);
 626			m_inactiveKeys &= ~0x30;
 627		}
 628		if (mappedKey & 0xC0) {
 629			m_activeKeys |= m_inactiveKeys & (0xC0 ^ mappedKey);
 630			m_inactiveKeys &= ~0xC0;
 631		}
 632	}
 633	updateKeys();
 634}
 635
 636void GameController::clearKeys() {
 637	m_activeKeys = 0;
 638	m_inactiveKeys = 0;
 639	updateKeys();
 640}
 641
 642void GameController::setAutofire(int key, bool enable) {
 643	if (key >= GBA_KEY_MAX || key < 0) {
 644		return;
 645	}
 646	m_autofire[key] = enable;
 647	m_autofireStatus[key] = 0;
 648}
 649
 650void GameController::setAudioBufferSamples(int samples) {
 651	if (m_audioProcessor) {
 652		threadInterrupt();
 653		redoSamples(samples);
 654		threadContinue();
 655		QMetaObject::invokeMethod(m_audioProcessor, "setBufferSamples", Qt::BlockingQueuedConnection, Q_ARG(int, samples));
 656	}
 657}
 658
 659void GameController::setAudioSampleRate(unsigned rate) {
 660	if (!rate) {
 661		return;
 662	}
 663	if (m_audioProcessor) {
 664		threadInterrupt();
 665		redoSamples(m_audioProcessor->getBufferSamples());
 666		threadContinue();
 667		QMetaObject::invokeMethod(m_audioProcessor, "requestSampleRate", Q_ARG(unsigned, rate));
 668	}
 669}
 670
 671void GameController::setAudioChannelEnabled(int channel, bool enable) {
 672	if (channel > 5 || channel < 0) {
 673		return;
 674	}
 675#ifdef M_CORE_GBA
 676	GBA* gba = static_cast<GBA*>(m_threadContext.core->board);
 677#endif
 678#ifdef M_CORE_GB
 679	GB* gb = static_cast<GB*>(m_threadContext.core->board);
 680#endif
 681	m_audioChannels[channel] = enable;
 682	if (isLoaded()) {
 683		switch (channel) {
 684		case 0:
 685		case 1:
 686		case 2:
 687		case 3:
 688			switch (m_threadContext.core->platform(m_threadContext.core)) {
 689#ifdef M_CORE_GBA
 690			case PLATFORM_GBA:
 691				gba->audio.psg.forceDisableCh[channel] = !enable;
 692				break;
 693#endif
 694#ifdef M_CORE_GB
 695			case PLATFORM_GB:
 696				gb->audio.forceDisableCh[channel] = !enable;
 697				break;
 698#endif
 699			default:
 700				break;
 701			}
 702			break;
 703#ifdef M_CORE_GBA
 704		case 4:
 705			if (m_threadContext.core->platform(m_threadContext.core) == PLATFORM_GBA) {
 706				gba->audio.forceDisableChA = !enable;
 707			}
 708			break;
 709		case 5:
 710			if (m_threadContext.core->platform(m_threadContext.core) == PLATFORM_GBA) {
 711				gba->audio.forceDisableChB = !enable;
 712			}
 713			break;
 714#endif
 715		}
 716	}
 717}
 718
 719void GameController::startAudio() {
 720	bool started = false;
 721	QMetaObject::invokeMethod(m_audioProcessor, "start", Qt::BlockingQueuedConnection, Q_RETURN_ARG(bool, started));
 722	if (!started) {
 723		LOG(QT, ERROR) << tr("Failed to start audio processor");
 724		// Don't freeze!
 725		m_audioSync = false;
 726		m_videoSync = true;
 727		m_threadContext.sync.audioWait = false;
 728		m_threadContext.sync.videoFrameWait = true;
 729	}
 730}
 731
 732void GameController::setVideoLayerEnabled(int layer, bool enable) {
 733	if (layer > 4 || layer < 0) {
 734		return;
 735	}
 736	m_videoLayers[layer] = enable;
 737	if (isLoaded() && m_threadContext.core->platform(m_threadContext.core) == PLATFORM_GBA) {
 738		GBA* gba = static_cast<GBA*>(m_threadContext.core->board);
 739		switch (layer) {
 740		case 0:
 741		case 1:
 742		case 2:
 743		case 3:
 744			gba->video.renderer->disableBG[layer] = !enable;
 745			break;
 746		case 4:
 747			gba->video.renderer->disableOBJ = !enable;
 748			break;
 749		}
 750	}
 751}
 752
 753void GameController::setFPSTarget(float fps) {
 754	threadInterrupt();
 755	m_fpsTarget = fps;
 756	m_threadContext.sync.fpsTarget = fps;
 757	if (m_turbo && m_turboSpeed > 0) {
 758		m_threadContext.sync.fpsTarget *= m_turboSpeed;
 759	}
 760	if (m_audioProcessor) {
 761		redoSamples(m_audioProcessor->getBufferSamples());
 762	}
 763	threadContinue();
 764}
 765
 766void GameController::setUseBIOS(bool use) {
 767	if (use == m_useBios) {
 768		return;
 769	}
 770	m_useBios = use;
 771	if (m_gameOpen) {
 772		closeGame();
 773		openGame();
 774	}
 775}
 776
 777void GameController::loadState(int slot) {
 778	if (m_fname.isEmpty()) {
 779		// We're in the BIOS
 780		return;
 781	}
 782	if (slot > 0 && slot != m_stateSlot) {
 783		m_stateSlot = slot;
 784		m_backupSaveState.clear();
 785	}
 786	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 787		GameController* controller = static_cast<GameController*>(context->userData);
 788		if (!controller->m_backupLoadState) {
 789			controller->m_backupLoadState = VFileMemChunk(nullptr, 0);
 790		}
 791		context->core->saveState(context->core, controller->m_backupLoadState, controller->m_saveStateFlags);
 792		if (mCoreLoadState(context->core, controller->m_stateSlot, controller->m_loadStateFlags)) {
 793			controller->frameAvailable(controller->m_drawContext);
 794			controller->stateLoaded(context);
 795		}
 796	});
 797}
 798
 799void GameController::saveState(int slot) {
 800	if (m_fname.isEmpty()) {
 801		// We're in the BIOS
 802		return;
 803	}
 804	if (slot > 0) {
 805		m_stateSlot = slot;
 806	}
 807	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 808		GameController* controller = static_cast<GameController*>(context->userData);
 809		VFile* vf = mCoreGetState(context->core, controller->m_stateSlot, false);
 810		if (vf) {
 811			controller->m_backupSaveState.resize(vf->size(vf));
 812			vf->read(vf, controller->m_backupSaveState.data(), controller->m_backupSaveState.size());
 813			vf->close(vf);
 814		}
 815		mCoreSaveState(context->core, controller->m_stateSlot, controller->m_saveStateFlags);
 816	});
 817}
 818
 819void GameController::loadBackupState() {
 820	if (!m_backupLoadState) {
 821		return;
 822	}
 823
 824	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 825		GameController* controller = static_cast<GameController*>(context->userData);
 826		controller->m_backupLoadState->seek(controller->m_backupLoadState, 0, SEEK_SET);
 827		if (context->core->loadState(context->core, controller->m_backupLoadState, controller->m_loadStateFlags)) {
 828			mLOG(STATUS, INFO, "Undid state load");
 829			controller->frameAvailable(controller->m_drawContext);
 830			controller->stateLoaded(context);
 831		}
 832		controller->m_backupLoadState->close(controller->m_backupLoadState);
 833		controller->m_backupLoadState = nullptr;
 834	});
 835}
 836
 837void GameController::saveBackupState() {
 838	if (m_backupSaveState.isEmpty()) {
 839		return;
 840	}
 841
 842	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 843		GameController* controller = static_cast<GameController*>(context->userData);
 844		VFile* vf = mCoreGetState(context->core, controller->m_stateSlot, true);
 845		if (vf) {
 846			vf->write(vf, controller->m_backupSaveState.constData(), controller->m_backupSaveState.size());
 847			vf->close(vf);
 848			mLOG(STATUS, INFO, "Undid state save");
 849		}
 850		controller->m_backupSaveState.clear();
 851	});
 852}
 853
 854void GameController::setTurbo(bool set, bool forced) {
 855	if (m_turboForced && !forced) {
 856		return;
 857	}
 858	if (m_turbo == set && m_turboForced == forced) {
 859		// Don't interrupt the thread if we don't need to
 860		return;
 861	}
 862	m_turbo = set;
 863	m_turboForced = set && forced;
 864	enableTurbo();
 865}
 866
 867void GameController::setTurboSpeed(float ratio) {
 868	m_turboSpeed = ratio;
 869	enableTurbo();
 870}
 871
 872void GameController::enableTurbo() {
 873	threadInterrupt();
 874	if (!m_turbo) {
 875		m_threadContext.sync.fpsTarget = m_fpsTarget;
 876		m_threadContext.sync.audioWait = m_audioSync;
 877		m_threadContext.sync.videoFrameWait = m_videoSync;
 878	} else if (m_turboSpeed <= 0) {
 879		m_threadContext.sync.fpsTarget = m_fpsTarget;
 880		m_threadContext.sync.audioWait = false;
 881		m_threadContext.sync.videoFrameWait = false;
 882	} else {
 883		m_threadContext.sync.fpsTarget = m_fpsTarget * m_turboSpeed;
 884		m_threadContext.sync.audioWait = true;
 885		m_threadContext.sync.videoFrameWait = false;
 886	}
 887	if (m_audioProcessor) {
 888		redoSamples(m_audioProcessor->getBufferSamples());
 889	}
 890	threadContinue();
 891}
 892
 893void GameController::setAVStream(mAVStream* stream) {
 894	threadInterrupt();
 895	m_stream = stream;
 896	if (isLoaded()) {
 897		m_threadContext.core->setAVStream(m_threadContext.core, stream);
 898	}
 899	threadContinue();
 900}
 901
 902void GameController::clearAVStream() {
 903	threadInterrupt();
 904	m_stream = nullptr;
 905	if (isLoaded()) {
 906		m_threadContext.core->setAVStream(m_threadContext.core, nullptr);
 907	}
 908	threadContinue();
 909}
 910
 911#ifdef USE_PNG
 912void GameController::screenshot() {
 913	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 914		mCoreTakeScreenshot(context->core);
 915	});
 916}
 917#endif
 918
 919void GameController::reloadAudioDriver() {
 920	int samples = 0;
 921	unsigned sampleRate = 0;
 922	if (m_audioProcessor) {
 923		QMetaObject::invokeMethod(m_audioProcessor, "pause", Qt::BlockingQueuedConnection);
 924		samples = m_audioProcessor->getBufferSamples();
 925		sampleRate = m_audioProcessor->sampleRate();
 926		delete m_audioProcessor;
 927	}
 928	m_audioProcessor = AudioProcessor::create();
 929	if (samples) {
 930		m_audioProcessor->setBufferSamples(samples);
 931	}
 932	if (sampleRate) {
 933		m_audioProcessor->requestSampleRate(sampleRate);
 934	}
 935	m_audioProcessor->moveToThread(m_audioThread);
 936	connect(this, SIGNAL(gamePaused(mCoreThread*)), m_audioProcessor, SLOT(pause()));
 937	if (isLoaded()) {
 938		m_audioProcessor->setInput(&m_threadContext);
 939		startAudio();
 940	}
 941}
 942
 943void GameController::setSaveStateExtdata(int flags) {
 944	m_saveStateFlags = flags;
 945}
 946
 947void GameController::setLoadStateExtdata(int flags) {
 948	m_loadStateFlags = flags;
 949}
 950
 951void GameController::setLuminanceValue(uint8_t value) {
 952	m_luxValue = value;
 953	value = std::max<int>(value - 0x16, 0);
 954	m_luxLevel = 10;
 955	for (int i = 0; i < 10; ++i) {
 956		if (value < GBA_LUX_LEVELS[i]) {
 957			m_luxLevel = i;
 958			break;
 959		}
 960	}
 961	emit luminanceValueChanged(m_luxValue);
 962}
 963
 964void GameController::setLuminanceLevel(int level) {
 965	int value = 0x16;
 966	level = std::max(0, std::min(10, level));
 967	if (level > 0) {
 968		value += GBA_LUX_LEVELS[level - 1];
 969	}
 970	setLuminanceValue(value);
 971}
 972
 973void GameController::setRealTime() {
 974	m_rtc.override = RTC_NO_OVERRIDE;
 975}
 976
 977void GameController::setFixedTime(const QDateTime& time) {
 978	m_rtc.override = RTC_FIXED;
 979	m_rtc.value = time.toMSecsSinceEpoch() / 1000;
 980}
 981
 982void GameController::setFakeEpoch(const QDateTime& time) {
 983	m_rtc.override = RTC_FAKE_EPOCH;
 984	m_rtc.value = time.toMSecsSinceEpoch() / 1000;
 985}
 986
 987void GameController::updateKeys() {
 988	int activeKeys = m_activeKeys;
 989	activeKeys |= m_activeButtons;
 990	activeKeys &= ~m_inactiveKeys;
 991	if (isLoaded()) {
 992		m_threadContext.core->setKeys(m_threadContext.core, activeKeys);
 993	}
 994}
 995
 996void GameController::redoSamples(int samples) {
 997	if (m_threadContext.core) {
 998		m_threadContext.core->setAudioBufferSize(m_threadContext.core, samples);
 999	}
1000	QMetaObject::invokeMethod(m_audioProcessor, "inputParametersChanged");
1001}
1002
1003void GameController::setLogLevel(int levels) {
1004	threadInterrupt();
1005	m_logLevels = levels;
1006	threadContinue();
1007}
1008
1009void GameController::enableLogLevel(int levels) {
1010	threadInterrupt();
1011	m_logLevels |= levels;
1012	threadContinue();
1013}
1014
1015void GameController::disableLogLevel(int levels) {
1016	threadInterrupt();
1017	m_logLevels &= ~levels;
1018	threadContinue();
1019}
1020
1021void GameController::pollEvents() {
1022	if (!m_inputController) {
1023		return;
1024	}
1025
1026	m_activeButtons = m_inputController->pollEvents();
1027	updateKeys();
1028}
1029
1030void GameController::updateAutofire() {
1031	// TODO: Move all key events onto the CPU thread...somehow
1032	for (int k = 0; k < GBA_KEY_MAX; ++k) {
1033		if (!m_autofire[k]) {
1034			continue;
1035		}
1036		m_autofireStatus[k] ^= 1;
1037		if (m_autofireStatus[k]) {
1038			keyPressed(k);
1039		} else {
1040			keyReleased(k);
1041		}
1042	}
1043}