all repos — mgba @ 123dc183987e1fac9654b0d877b46cbc43bfe535

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/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_audioThread(new QThread(this))
  49	, m_audioProcessor(AudioProcessor::create())
  50	, m_pauseAfterFrame(false)
  51	, m_videoSync(VIDEO_SYNC)
  52	, m_audioSync(AUDIO_SYNC)
  53	, m_fpsTarget(-1)
  54	, m_turbo(false)
  55	, m_turboForced(false)
  56	, m_turboSpeed(-1)
  57	, m_wasPaused(false)
  58	, m_audioChannels{ true, true, true, true, true, true }
  59	, m_videoLayers{ true, true, true, true, true }
  60	, m_autofire{}
  61	, m_autofireStatus{}
  62	, m_inputController(nullptr)
  63	, m_multiplayer(nullptr)
  64	, m_stream(nullptr)
  65	, m_stateSlot(1)
  66	, m_backupLoadState(nullptr)
  67	, m_backupSaveState(nullptr)
  68	, m_saveStateFlags(SAVESTATE_SCREENSHOT | SAVESTATE_SAVEDATA | SAVESTATE_CHEATS)
  69	, m_loadStateFlags(SAVESTATE_SCREENSHOT)
  70{
  71	GBACheatDeviceCreate(&m_cheatDevice);
  72
  73	m_lux.p = this;
  74	m_lux.sample = [](GBALuminanceSource* context) {
  75		GameControllerLux* lux = static_cast<GameControllerLux*>(context);
  76		lux->value = 0xFF - lux->p->m_luxValue;
  77	};
  78
  79	m_lux.readLuminance = [](GBALuminanceSource* context) {
  80		GameControllerLux* lux = static_cast<GameControllerLux*>(context);
  81		return lux->value;
  82	};
  83	setLuminanceLevel(0);
  84
  85	m_threadContext.startCallback = [](mCoreThread* context) {
  86		GameController* controller = static_cast<GameController*>(context->userData);
  87		if (controller->m_audioProcessor) {
  88			controller->m_audioProcessor->setInput(context);
  89		}
  90		mRTCGenericSourceInit(&controller->m_rtc, context->core);
  91		context->core->setRTC(context->core, &controller->m_rtc.d);
  92		context->core->setRotation(context->core, controller->m_inputController->rotationSource());
  93		context->core->setRumble(context->core, controller->m_inputController->rumble());
  94
  95#ifdef M_CORE_GBA
  96		GBA* gba = static_cast<GBA*>(context->core->board);
  97#endif
  98#ifdef M_CORE_GB
  99		GB* gb = static_cast<GB*>(context->core->board);
 100#endif
 101		switch (context->core->platform(context->core)) {
 102#ifdef M_CORE_GBA
 103		case PLATFORM_GBA:
 104			gba->luminanceSource = &controller->m_lux;
 105			gba->audio.psg.forceDisableCh[0] = !controller->m_audioChannels[0];
 106			gba->audio.psg.forceDisableCh[1] = !controller->m_audioChannels[1];
 107			gba->audio.psg.forceDisableCh[2] = !controller->m_audioChannels[2];
 108			gba->audio.psg.forceDisableCh[3] = !controller->m_audioChannels[3];
 109			gba->audio.forceDisableChA = !controller->m_audioChannels[4];
 110			gba->audio.forceDisableChB = !controller->m_audioChannels[5];
 111			gba->video.renderer->disableBG[0] = !controller->m_videoLayers[0];
 112			gba->video.renderer->disableBG[1] = !controller->m_videoLayers[1];
 113			gba->video.renderer->disableBG[2] = !controller->m_videoLayers[2];
 114			gba->video.renderer->disableBG[3] = !controller->m_videoLayers[3];
 115			gba->video.renderer->disableOBJ = !controller->m_videoLayers[4];
 116			break;
 117#endif
 118#ifdef M_CORE_GB
 119		case PLATFORM_GB:
 120			gb->audio.forceDisableCh[0] = !controller->m_audioChannels[0];
 121			gb->audio.forceDisableCh[1] = !controller->m_audioChannels[1];
 122			gb->audio.forceDisableCh[2] = !controller->m_audioChannels[2];
 123			gb->audio.forceDisableCh[3] = !controller->m_audioChannels[3];
 124			break;
 125#endif
 126		default:
 127			break;
 128		}
 129		controller->m_fpsTarget = context->sync.fpsTarget;
 130
 131		if (mCoreLoadState(context->core, 0, controller->m_loadStateFlags)) {
 132			mCoreDeleteState(context->core, 0);
 133		}
 134		QMetaObject::invokeMethod(controller, "gameStarted", Q_ARG(mCoreThread*, context), Q_ARG(const QString&, controller->m_fname));
 135	};
 136
 137	m_threadContext.cleanCallback = [](mCoreThread* context) {
 138		GameController* controller = static_cast<GameController*>(context->userData);
 139		QMetaObject::invokeMethod(controller, "gameStopped", Q_ARG(mCoreThread*, context));
 140	};
 141
 142	m_threadContext.frameCallback = [](mCoreThread* context) {
 143		GameController* controller = static_cast<GameController*>(context->userData);
 144		unsigned width, height;
 145		controller->m_threadContext.core->desiredVideoDimensions(controller->m_threadContext.core, &width, &height);
 146		memcpy(controller->m_frontBuffer, controller->m_drawContext, width * height * BYTES_PER_PIXEL);
 147		QMetaObject::invokeMethod(controller, "frameAvailable", Q_ARG(const uint32_t*, controller->m_frontBuffer));
 148		if (controller->m_pauseAfterFrame.testAndSetAcquire(true, false)) {
 149			mCoreThreadPauseFromThread(context);
 150			QMetaObject::invokeMethod(controller, "gamePaused", Q_ARG(mCoreThread*, context));
 151		}
 152	};
 153
 154	/*m_threadContext.stopCallback = [](mCoreThread* context) {
 155		if (!context) {
 156			return false;
 157		}
 158		GameController* controller = static_cast<GameController*>(context->userData);
 159		if (!mCoreSaveState(context->core, 0, controller->m_saveStateFlags)) {
 160			return false;
 161		}
 162		QMetaObject::invokeMethod(controller, "closeGame");
 163		return true;
 164	};*/
 165
 166	m_threadContext.logger.d.log = [](mLogger* logger, int category, enum mLogLevel level, const char* format, va_list args) {
 167		mThreadLogger* logContext = reinterpret_cast<mThreadLogger*>(logger);
 168		mCoreThread* context = logContext->p;
 169
 170		static const char* savestateMessage = "State %i loaded";
 171		static const char* savestateFailedMessage = "State %i failed to load";
 172		if (!context) {
 173			return;
 174		}
 175		GameController* controller = static_cast<GameController*>(context->userData);
 176		if (level == mLOG_STUB && category == _mLOG_CAT_GBA_BIOS()) {
 177			va_list argc;
 178			va_copy(argc, args);
 179			int immediate = va_arg(argc, int);
 180			va_end(argc);
 181			QMetaObject::invokeMethod(controller, "unimplementedBiosCall", Q_ARG(int, immediate));
 182		} else if (category == _mLOG_CAT_STATUS()) {
 183			// Slot 0 is reserved for suspend points
 184			if (strncmp(savestateMessage, format, strlen(savestateMessage)) == 0) {
 185				va_list argc;
 186				va_copy(argc, args);
 187				int slot = va_arg(argc, int);
 188				va_end(argc);
 189				if (slot == 0) {
 190					format = "Loaded suspend state";
 191				}
 192			} else if (strncmp(savestateFailedMessage, format, strlen(savestateFailedMessage)) == 0) {
 193				va_list argc;
 194				va_copy(argc, args);
 195				int slot = va_arg(argc, int);
 196				va_end(argc);
 197				if (slot == 0) {
 198					return;
 199				}
 200			}
 201		}
 202		if (level == mLOG_FATAL) {
 203			QMetaObject::invokeMethod(controller, "crashGame", Q_ARG(const QString&, QString().vsprintf(format, args)));
 204		} else if (!(controller->m_logLevels & level)) {
 205			return;
 206		}
 207		QString message(QString().vsprintf(format, args));
 208		if (category == _mLOG_CAT_STATUS()) {
 209			QMetaObject::invokeMethod(controller, "statusPosted", Q_ARG(const QString&, message));
 210		}
 211		QMetaObject::invokeMethod(controller, "postLog", Q_ARG(int, level), Q_ARG(int, category), Q_ARG(const QString&, message));
 212	};
 213
 214	m_threadContext.userData = this;
 215
 216	connect(&m_rewindTimer, &QTimer::timeout, [this]() {
 217		// TODO: Put rewind back
 218		emit frameAvailable(m_drawContext);
 219		emit rewound(&m_threadContext);
 220	});
 221	m_rewindTimer.setInterval(100);
 222
 223	m_audioThread->setObjectName("Audio Thread");
 224	m_audioThread->start(QThread::TimeCriticalPriority);
 225	m_audioProcessor->moveToThread(m_audioThread);
 226	connect(this, SIGNAL(gamePaused(mCoreThread*)), m_audioProcessor, SLOT(pause()));
 227	connect(this, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(pollEvents()));
 228	connect(this, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(updateAutofire()));
 229}
 230
 231GameController::~GameController() {
 232	m_audioThread->quit();
 233	m_audioThread->wait();
 234	disconnect();
 235	clearMultiplayerController();
 236	closeGame();
 237	GBACheatDeviceDestroy(&m_cheatDevice);
 238	delete m_backupLoadState;
 239}
 240
 241void GameController::setMultiplayerController(MultiplayerController* controller) {
 242	if (controller == m_multiplayer) {
 243		return;
 244	}
 245	clearMultiplayerController();
 246	m_multiplayer = controller;
 247	controller->attachGame(this);
 248}
 249
 250void GameController::clearMultiplayerController() {
 251	if (!m_multiplayer) {
 252		return;
 253	}
 254	m_multiplayer->detachGame(this);
 255	m_multiplayer = nullptr;
 256}
 257
 258void GameController::setOverride(const GBACartridgeOverride& override) {
 259	// TODO: Put back overrides
 260}
 261
 262void GameController::setConfig(const mCoreConfig* config) {
 263	m_config = config;
 264	if (isLoaded()) {
 265		threadInterrupt();
 266		mCoreLoadForeignConfig(m_threadContext.core, config);
 267		m_audioProcessor->setInput(&m_threadContext);
 268		threadContinue();
 269	}
 270}
 271
 272#ifdef USE_GDB_STUB
 273Debugger* GameController::debugger() {
 274	// TODO: Put back debugger
 275	return nullptr;
 276}
 277
 278void GameController::setDebugger(Debugger* debugger) {
 279	threadInterrupt();
 280	// TODO: Put back debugger
 281	threadContinue();
 282}
 283#endif
 284
 285void GameController::loadGame(const QString& path) {
 286	closeGame();
 287	QFile file(path);
 288	if (!file.open(QIODevice::ReadOnly)) {
 289		LOG(QT, ERROR) << tr("Failed to open game file: %1").arg(path);
 290		return;
 291	}
 292	file.close();
 293
 294	m_fname = path;
 295	openGame();
 296}
 297
 298void GameController::bootBIOS() {
 299	closeGame();
 300	m_fname = QString();
 301	openGame(true);
 302}
 303
 304void GameController::openGame(bool biosOnly) {
 305	if (biosOnly && (!m_useBios || m_bios.isNull())) {
 306		return;
 307	}
 308
 309	if (!biosOnly) {
 310		m_threadContext.core = mCoreFind(m_fname.toUtf8().constData());
 311	} else {
 312		m_threadContext.core = GBACoreCreate();
 313	}
 314
 315	if (!m_threadContext.core) {
 316		return;
 317	}
 318
 319	m_gameOpen = true;
 320
 321	m_pauseAfterFrame = false;
 322
 323	if (m_turbo) {
 324		m_threadContext.sync.videoFrameWait = false;
 325		m_threadContext.sync.audioWait = false;
 326	} else {
 327		m_threadContext.sync.videoFrameWait = m_videoSync;
 328		m_threadContext.sync.audioWait = m_audioSync;
 329	}
 330	m_threadContext.core->init(m_threadContext.core);
 331
 332	unsigned width, height;
 333	m_threadContext.core->desiredVideoDimensions(m_threadContext.core, &width, &height);
 334	m_drawContext = new uint32_t[width * height];
 335	m_frontBuffer = new uint32_t[width * height];
 336
 337	if (!biosOnly) {
 338		mCoreLoadFile(m_threadContext.core, m_fname.toUtf8().constData());
 339	}
 340
 341	m_threadContext.core->setVideoBuffer(m_threadContext.core, m_drawContext, width);
 342
 343	if (!m_bios.isNull() && m_useBios) {
 344		VFile* bios = VFileDevice::open(m_bios, O_RDONLY);
 345		if (bios) {
 346			// TODO: Lifetime issues?
 347			m_threadContext.core->loadBIOS(m_threadContext.core, bios, 0);
 348		}
 349	}
 350
 351	if (!m_patch.isNull()) {
 352		VFile* patch = VFileDevice::open(m_patch, O_RDONLY);
 353		if (patch) {
 354			m_threadContext.core->loadPatch(m_threadContext.core, patch);
 355		}
 356		patch->close(patch);
 357	}
 358
 359	m_inputController->recalibrateAxes();
 360	memset(m_drawContext, 0xF8, width * height * 4);
 361
 362	m_threadContext.core->setAVStream(m_threadContext.core, m_stream);
 363
 364	if (m_config) {
 365		mCoreLoadForeignConfig(m_threadContext.core, m_config);
 366	}
 367
 368	if (!biosOnly) {
 369		mCoreAutoloadSave(m_threadContext.core);
 370	}
 371
 372	if (!mCoreThreadStart(&m_threadContext)) {
 373		m_gameOpen = false;
 374		emit gameFailed();
 375	} else if (m_audioProcessor) {
 376		startAudio();
 377	}
 378}
 379
 380void GameController::loadBIOS(const QString& path) {
 381	if (m_bios == path) {
 382		return;
 383	}
 384	m_bios = path;
 385	if (m_gameOpen) {
 386		closeGame();
 387		openGame();
 388	}
 389}
 390
 391void GameController::yankPak() {
 392	if (!m_gameOpen) {
 393		return;
 394	}
 395	threadInterrupt();
 396	GBAYankROM(static_cast<GBA*>(m_threadContext.core->board));
 397	threadContinue();
 398}
 399
 400void GameController::replaceGame(const QString& path) {
 401	if (!m_gameOpen) {
 402		return;
 403	}
 404
 405	m_fname = path;
 406	threadInterrupt();
 407	mCoreLoadFile(m_threadContext.core, m_fname.toLocal8Bit().constData());
 408	threadContinue();
 409}
 410
 411void GameController::loadPatch(const QString& path) {
 412	if (m_gameOpen) {
 413		closeGame();
 414		m_patch = path;
 415		openGame();
 416	} else {
 417		m_patch = path;
 418	}
 419}
 420
 421void GameController::importSharkport(const QString& path) {
 422	if (!isLoaded()) {
 423		return;
 424	}
 425	VFile* vf = VFileDevice::open(path, O_RDONLY);
 426	if (!vf) {
 427		LOG(QT, ERROR) << tr("Failed to open snapshot file for reading: %1").arg(path);
 428		return;
 429	}
 430	threadInterrupt();
 431	GBASavedataImportSharkPort(static_cast<GBA*>(m_threadContext.core->board), vf, false);
 432	threadContinue();
 433	vf->close(vf);
 434}
 435
 436void GameController::exportSharkport(const QString& path) {
 437	if (!isLoaded()) {
 438		return;
 439	}
 440	VFile* vf = VFileDevice::open(path, O_WRONLY | O_CREAT | O_TRUNC);
 441	if (!vf) {
 442		LOG(QT, ERROR) << tr("Failed to open snapshot file for writing: %1").arg(path);
 443		return;
 444	}
 445	threadInterrupt();
 446	GBASavedataExportSharkPort(static_cast<GBA*>(m_threadContext.core->board), vf);
 447	threadContinue();
 448	vf->close(vf);
 449}
 450
 451void GameController::closeGame() {
 452	if (!m_gameOpen) {
 453		return;
 454	}
 455	m_gameOpen = false;
 456
 457	m_rewindTimer.stop();
 458	if (mCoreThreadIsPaused(&m_threadContext)) {
 459		mCoreThreadUnpause(&m_threadContext);
 460	}
 461	m_audioProcessor->pause();
 462	mCoreThreadEnd(&m_threadContext);
 463	mCoreThreadJoin(&m_threadContext);
 464	// Make sure the event queue clears out before the thread is reused
 465	QCoreApplication::processEvents();
 466
 467	delete[] m_drawContext;
 468	delete[] m_frontBuffer;
 469
 470	m_patch = QString();
 471
 472	for (size_t i = 0; i < GBACheatSetsSize(&m_cheatDevice.cheats); ++i) {
 473		GBACheatSet* set = *GBACheatSetsGetPointer(&m_cheatDevice.cheats, i);
 474		GBACheatSetDeinit(set);
 475		delete set;
 476	}
 477	GBACheatSetsClear(&m_cheatDevice.cheats);
 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}