all repos — mgba @ a219c328d10461704314ee833869c5e052b40db8

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
  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->rumble = controller->m_inputController->rumble();
 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	m_gameOpen = true;
 310
 311	m_pauseAfterFrame = false;
 312
 313	if (m_turbo) {
 314		m_threadContext.sync.videoFrameWait = false;
 315		m_threadContext.sync.audioWait = false;
 316	} else {
 317		m_threadContext.sync.videoFrameWait = m_videoSync;
 318		m_threadContext.sync.audioWait = m_audioSync;
 319	}
 320
 321
 322	if (!biosOnly) {
 323		m_threadContext.core = mCoreFind(m_fname.toUtf8().constData());
 324	} else {
 325		m_threadContext.core = GBACoreCreate();
 326	}
 327	m_threadContext.core->init(m_threadContext.core);
 328
 329	unsigned width, height;
 330	m_threadContext.core->desiredVideoDimensions(m_threadContext.core, &width, &height);
 331	m_drawContext = new uint32_t[width * height];
 332	m_frontBuffer = new uint32_t[width * height];
 333
 334	if (!biosOnly) {
 335		mCoreLoadFile(m_threadContext.core, m_fname.toUtf8().constData());
 336	}
 337
 338	m_threadContext.core->setVideoBuffer(m_threadContext.core, m_drawContext, width);
 339
 340	if (!m_bios.isNull() && m_useBios) {
 341		VFile* bios = VFileDevice::open(m_bios, O_RDONLY);
 342		if (bios) {
 343			// TODO: Lifetime issues?
 344			m_threadContext.core->loadBIOS(m_threadContext.core, bios, 0);
 345		}
 346	}
 347
 348	if (!m_patch.isNull()) {
 349		VFile* patch = VFileDevice::open(m_patch, O_RDONLY);
 350		if (patch) {
 351			m_threadContext.core->loadPatch(m_threadContext.core, patch);
 352		}
 353		patch->close(patch);
 354	}
 355
 356	m_inputController->recalibrateAxes();
 357	memset(m_drawContext, 0xF8, width * height * 4);
 358
 359	m_threadContext.core->setAVStream(m_threadContext.core, m_stream);
 360
 361	if (m_config) {
 362		mCoreLoadForeignConfig(m_threadContext.core, m_config);
 363	}
 364
 365	if (!biosOnly) {
 366		mCoreAutoloadSave(m_threadContext.core);
 367	}
 368
 369	if (!mCoreThreadStart(&m_threadContext)) {
 370		m_gameOpen = false;
 371		emit gameFailed();
 372	} else if (m_audioProcessor) {
 373		startAudio();
 374	}
 375}
 376
 377void GameController::loadBIOS(const QString& path) {
 378	if (m_bios == path) {
 379		return;
 380	}
 381	m_bios = path;
 382	if (m_gameOpen) {
 383		closeGame();
 384		openGame();
 385	}
 386}
 387
 388void GameController::yankPak() {
 389	if (!m_gameOpen) {
 390		return;
 391	}
 392	threadInterrupt();
 393	GBAYankROM(static_cast<GBA*>(m_threadContext.core->board));
 394	threadContinue();
 395}
 396
 397void GameController::replaceGame(const QString& path) {
 398	if (!m_gameOpen) {
 399		return;
 400	}
 401
 402	m_fname = path;
 403	threadInterrupt();
 404	mCoreLoadFile(m_threadContext.core, m_fname.toLocal8Bit().constData());
 405	threadContinue();
 406}
 407
 408void GameController::loadPatch(const QString& path) {
 409	if (m_gameOpen) {
 410		closeGame();
 411		m_patch = path;
 412		openGame();
 413	} else {
 414		m_patch = path;
 415	}
 416}
 417
 418void GameController::importSharkport(const QString& path) {
 419	if (!isLoaded()) {
 420		return;
 421	}
 422	VFile* vf = VFileDevice::open(path, O_RDONLY);
 423	if (!vf) {
 424		LOG(QT, ERROR) << tr("Failed to open snapshot file for reading: %1").arg(path);
 425		return;
 426	}
 427	threadInterrupt();
 428	GBASavedataImportSharkPort(static_cast<GBA*>(m_threadContext.core->board), vf, false);
 429	threadContinue();
 430	vf->close(vf);
 431}
 432
 433void GameController::exportSharkport(const QString& path) {
 434	if (!isLoaded()) {
 435		return;
 436	}
 437	VFile* vf = VFileDevice::open(path, O_WRONLY | O_CREAT | O_TRUNC);
 438	if (!vf) {
 439		LOG(QT, ERROR) << tr("Failed to open snapshot file for writing: %1").arg(path);
 440		return;
 441	}
 442	threadInterrupt();
 443	GBASavedataExportSharkPort(static_cast<GBA*>(m_threadContext.core->board), vf);
 444	threadContinue();
 445	vf->close(vf);
 446}
 447
 448void GameController::closeGame() {
 449	if (!m_gameOpen) {
 450		return;
 451	}
 452	m_gameOpen = false;
 453
 454	m_rewindTimer.stop();
 455	if (mCoreThreadIsPaused(&m_threadContext)) {
 456		mCoreThreadUnpause(&m_threadContext);
 457	}
 458	m_audioProcessor->pause();
 459	mCoreThreadEnd(&m_threadContext);
 460	mCoreThreadJoin(&m_threadContext);
 461	// Make sure the event queue clears out before the thread is reused
 462	QCoreApplication::processEvents();
 463
 464	delete[] m_drawContext;
 465	delete[] m_frontBuffer;
 466
 467	m_patch = QString();
 468
 469	for (size_t i = 0; i < GBACheatSetsSize(&m_cheatDevice.cheats); ++i) {
 470		GBACheatSet* set = *GBACheatSetsGetPointer(&m_cheatDevice.cheats, i);
 471		GBACheatSetDeinit(set);
 472		delete set;
 473	}
 474	GBACheatSetsClear(&m_cheatDevice.cheats);
 475
 476	m_threadContext.core->deinit(m_threadContext.core);
 477}
 478
 479void GameController::crashGame(const QString& crashMessage) {
 480	closeGame();
 481	emit gameCrashed(crashMessage);
 482	emit gameStopped(&m_threadContext);
 483}
 484
 485bool GameController::isPaused() {
 486	if (!m_gameOpen) {
 487		return false;
 488	}
 489	return mCoreThreadIsPaused(&m_threadContext);
 490}
 491
 492mPlatform GameController::platform() const {
 493	if (!m_gameOpen) {
 494		return PLATFORM_NONE;
 495	}
 496	return m_threadContext.core->platform(m_threadContext.core);
 497}
 498
 499QSize GameController::screenDimensions() const {
 500	if (!m_gameOpen) {
 501		return QSize();
 502	}
 503	unsigned width, height;
 504	m_threadContext.core->desiredVideoDimensions(m_threadContext.core, &width, &height);
 505
 506	return QSize(width, height);
 507}
 508
 509void GameController::setPaused(bool paused) {
 510	if (!isLoaded() || m_rewindTimer.isActive() || paused == mCoreThreadIsPaused(&m_threadContext)) {
 511		return;
 512	}
 513	if (paused) {
 514		m_pauseAfterFrame.testAndSetRelaxed(false, true);
 515	} else {
 516		mCoreThreadUnpause(&m_threadContext);
 517		startAudio();
 518		emit gameUnpaused(&m_threadContext);
 519	}
 520}
 521
 522void GameController::reset() {
 523	if (!m_gameOpen) {
 524		return;
 525	}
 526	bool wasPaused = isPaused();
 527	setPaused(false);
 528	mCoreThreadReset(&m_threadContext);
 529	if (wasPaused) {
 530		setPaused(true);
 531	}
 532}
 533
 534void GameController::threadInterrupt() {
 535	if (m_gameOpen) {
 536		mCoreThreadInterrupt(&m_threadContext);
 537	}
 538}
 539
 540void GameController::threadContinue() {
 541	if (m_gameOpen) {
 542		mCoreThreadContinue(&m_threadContext);
 543	}
 544}
 545
 546void GameController::frameAdvance() {
 547	if (m_rewindTimer.isActive()) {
 548		return;
 549	}
 550	if (m_pauseAfterFrame.testAndSetRelaxed(false, true)) {
 551		setPaused(false);
 552	}
 553}
 554
 555void GameController::setRewind(bool enable, int capacity, int interval) {
 556	if (m_gameOpen) {
 557		threadInterrupt();
 558		// TODO: Put back rewind
 559		threadContinue();
 560	} else {
 561		// TODO: Put back rewind
 562	}
 563}
 564
 565void GameController::rewind(int states) {
 566	threadInterrupt();
 567	if (!states) {
 568		// TODO: Put back rewind
 569	} else {
 570		// TODO: Put back rewind
 571	}
 572	threadContinue();
 573	emit frameAvailable(m_drawContext);
 574	emit rewound(&m_threadContext);
 575}
 576
 577void GameController::startRewinding() {
 578	if (!m_gameOpen || m_rewindTimer.isActive()) {
 579		return;
 580	}
 581	if (m_multiplayer && m_multiplayer->attached() > 1) {
 582		return;
 583	}
 584	m_wasPaused = isPaused();
 585	if (!mCoreThreadIsPaused(&m_threadContext)) {
 586		mCoreThreadPause(&m_threadContext);
 587	}
 588	m_rewindTimer.start();
 589}
 590
 591void GameController::stopRewinding() {
 592	if (!m_rewindTimer.isActive()) {
 593		return;
 594	}
 595	m_rewindTimer.stop();
 596	bool signalsBlocked = blockSignals(true);
 597	setPaused(m_wasPaused);
 598	blockSignals(signalsBlocked);
 599}
 600
 601void GameController::keyPressed(int key) {
 602	int mappedKey = 1 << key;
 603	m_activeKeys |= mappedKey;
 604	if (!m_inputController->allowOpposing()) {
 605		if ((m_activeKeys & 0x30) == 0x30) {
 606			m_inactiveKeys |= mappedKey ^ 0x30;
 607			m_activeKeys ^= mappedKey ^ 0x30;
 608		}
 609		if ((m_activeKeys & 0xC0) == 0xC0) {
 610			m_inactiveKeys |= mappedKey ^ 0xC0;
 611			m_activeKeys ^= mappedKey ^ 0xC0;
 612		}
 613	}
 614	updateKeys();
 615}
 616
 617void GameController::keyReleased(int key) {
 618	int mappedKey = 1 << key;
 619	m_activeKeys &= ~mappedKey;
 620	if (!m_inputController->allowOpposing()) {
 621		if (mappedKey & 0x30) {
 622			m_activeKeys |= m_inactiveKeys & (0x30 ^ mappedKey);
 623			m_inactiveKeys &= ~0x30;
 624		}
 625		if (mappedKey & 0xC0) {
 626			m_activeKeys |= m_inactiveKeys & (0xC0 ^ mappedKey);
 627			m_inactiveKeys &= ~0xC0;
 628		}
 629	}
 630	updateKeys();
 631}
 632
 633void GameController::clearKeys() {
 634	m_activeKeys = 0;
 635	m_inactiveKeys = 0;
 636	updateKeys();
 637}
 638
 639void GameController::setAutofire(int key, bool enable) {
 640	if (key >= GBA_KEY_MAX || key < 0) {
 641		return;
 642	}
 643	m_autofire[key] = enable;
 644	m_autofireStatus[key] = 0;
 645}
 646
 647void GameController::setAudioBufferSamples(int samples) {
 648	if (m_audioProcessor) {
 649		threadInterrupt();
 650		redoSamples(samples);
 651		threadContinue();
 652		QMetaObject::invokeMethod(m_audioProcessor, "setBufferSamples", Qt::BlockingQueuedConnection, Q_ARG(int, samples));
 653	}
 654}
 655
 656void GameController::setAudioSampleRate(unsigned rate) {
 657	if (!rate) {
 658		return;
 659	}
 660	if (m_audioProcessor) {
 661		threadInterrupt();
 662		redoSamples(m_audioProcessor->getBufferSamples());
 663		threadContinue();
 664		QMetaObject::invokeMethod(m_audioProcessor, "requestSampleRate", Q_ARG(unsigned, rate));
 665	}
 666}
 667
 668void GameController::setAudioChannelEnabled(int channel, bool enable) {
 669	if (channel > 5 || channel < 0) {
 670		return;
 671	}
 672#ifdef M_CORE_GBA
 673	GBA* gba = static_cast<GBA*>(m_threadContext.core->board);
 674#endif
 675#ifdef M_CORE_GB
 676	GB* gb = static_cast<GB*>(m_threadContext.core->board);
 677#endif
 678	m_audioChannels[channel] = enable;
 679	if (isLoaded()) {
 680		switch (channel) {
 681		case 0:
 682		case 1:
 683		case 2:
 684		case 3:
 685			switch (m_threadContext.core->platform(m_threadContext.core)) {
 686#ifdef M_CORE_GBA
 687			case PLATFORM_GBA:
 688				gba->audio.psg.forceDisableCh[channel] = !enable;
 689				break;
 690#endif
 691#ifdef M_CORE_GB
 692			case PLATFORM_GB:
 693				gb->audio.forceDisableCh[channel] = !enable;
 694				break;
 695#endif
 696			default:
 697				break;
 698			}
 699			break;
 700#ifdef M_CORE_GBA
 701		case 4:
 702			if (m_threadContext.core->platform(m_threadContext.core) == PLATFORM_GBA) {
 703				gba->audio.forceDisableChA = !enable;
 704			}
 705			break;
 706		case 5:
 707			if (m_threadContext.core->platform(m_threadContext.core) == PLATFORM_GBA) {
 708				gba->audio.forceDisableChB = !enable;
 709			}
 710			break;
 711#endif
 712		}
 713	}
 714}
 715
 716void GameController::startAudio() {
 717	bool started = false;
 718	QMetaObject::invokeMethod(m_audioProcessor, "start", Qt::BlockingQueuedConnection, Q_RETURN_ARG(bool, started));
 719	if (!started) {
 720		LOG(QT, ERROR) << tr("Failed to start audio processor");
 721		// Don't freeze!
 722		m_audioSync = false;
 723		m_videoSync = true;
 724		m_threadContext.sync.audioWait = false;
 725		m_threadContext.sync.videoFrameWait = true;
 726	}
 727}
 728
 729void GameController::setVideoLayerEnabled(int layer, bool enable) {
 730	if (layer > 4 || layer < 0) {
 731		return;
 732	}
 733	m_videoLayers[layer] = enable;
 734	if (isLoaded() && m_threadContext.core->platform(m_threadContext.core) == PLATFORM_GBA) {
 735		GBA* gba = static_cast<GBA*>(m_threadContext.core->board);
 736		switch (layer) {
 737		case 0:
 738		case 1:
 739		case 2:
 740		case 3:
 741			gba->video.renderer->disableBG[layer] = !enable;
 742			break;
 743		case 4:
 744			gba->video.renderer->disableOBJ = !enable;
 745			break;
 746		}
 747	}
 748}
 749
 750void GameController::setFPSTarget(float fps) {
 751	threadInterrupt();
 752	m_fpsTarget = fps;
 753	m_threadContext.sync.fpsTarget = fps;
 754	if (m_turbo && m_turboSpeed > 0) {
 755		m_threadContext.sync.fpsTarget *= m_turboSpeed;
 756	}
 757	if (m_audioProcessor) {
 758		redoSamples(m_audioProcessor->getBufferSamples());
 759	}
 760	threadContinue();
 761}
 762
 763void GameController::setUseBIOS(bool use) {
 764	if (use == m_useBios) {
 765		return;
 766	}
 767	m_useBios = use;
 768	if (m_gameOpen) {
 769		closeGame();
 770		openGame();
 771	}
 772}
 773
 774void GameController::loadState(int slot) {
 775	if (m_fname.isEmpty()) {
 776		// We're in the BIOS
 777		return;
 778	}
 779	if (slot > 0 && slot != m_stateSlot) {
 780		m_stateSlot = slot;
 781		m_backupSaveState.clear();
 782	}
 783	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 784		GameController* controller = static_cast<GameController*>(context->userData);
 785		if (!controller->m_backupLoadState) {
 786			controller->m_backupLoadState = VFileMemChunk(nullptr, 0);
 787		}
 788		context->core->saveState(context->core, controller->m_backupLoadState, controller->m_saveStateFlags);
 789		if (mCoreLoadState(context->core, controller->m_stateSlot, controller->m_loadStateFlags)) {
 790			controller->frameAvailable(controller->m_drawContext);
 791			controller->stateLoaded(context);
 792		}
 793	});
 794}
 795
 796void GameController::saveState(int slot) {
 797	if (m_fname.isEmpty()) {
 798		// We're in the BIOS
 799		return;
 800	}
 801	if (slot > 0) {
 802		m_stateSlot = slot;
 803	}
 804	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 805		GameController* controller = static_cast<GameController*>(context->userData);
 806		VFile* vf = mCoreGetState(context->core, controller->m_stateSlot, false);
 807		if (vf) {
 808			controller->m_backupSaveState.resize(vf->size(vf));
 809			vf->read(vf, controller->m_backupSaveState.data(), controller->m_backupSaveState.size());
 810			vf->close(vf);
 811		}
 812		mCoreSaveState(context->core, controller->m_stateSlot, controller->m_saveStateFlags);
 813	});
 814}
 815
 816void GameController::loadBackupState() {
 817	if (!m_backupLoadState) {
 818		return;
 819	}
 820
 821	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 822		GameController* controller = static_cast<GameController*>(context->userData);
 823		controller->m_backupLoadState->seek(controller->m_backupLoadState, 0, SEEK_SET);
 824		if (context->core->loadState(context->core, controller->m_backupLoadState, controller->m_loadStateFlags)) {
 825			mLOG(STATUS, INFO, "Undid state load");
 826			controller->frameAvailable(controller->m_drawContext);
 827			controller->stateLoaded(context);
 828		}
 829		controller->m_backupLoadState->close(controller->m_backupLoadState);
 830		controller->m_backupLoadState = nullptr;
 831	});
 832}
 833
 834void GameController::saveBackupState() {
 835	if (m_backupSaveState.isEmpty()) {
 836		return;
 837	}
 838
 839	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 840		GameController* controller = static_cast<GameController*>(context->userData);
 841		VFile* vf = mCoreGetState(context->core, controller->m_stateSlot, true);
 842		if (vf) {
 843			vf->write(vf, controller->m_backupSaveState.constData(), controller->m_backupSaveState.size());
 844			vf->close(vf);
 845			mLOG(STATUS, INFO, "Undid state save");
 846		}
 847		controller->m_backupSaveState.clear();
 848	});
 849}
 850
 851void GameController::setMute(bool mute) {
 852	threadInterrupt();
 853	// TODO: Put back mute
 854	threadContinue();
 855}
 856
 857void GameController::setTurbo(bool set, bool forced) {
 858	if (m_turboForced && !forced) {
 859		return;
 860	}
 861	if (m_turbo == set && m_turboForced == forced) {
 862		// Don't interrupt the thread if we don't need to
 863		return;
 864	}
 865	m_turbo = set;
 866	m_turboForced = set && forced;
 867	enableTurbo();
 868}
 869
 870void GameController::setTurboSpeed(float ratio) {
 871	m_turboSpeed = ratio;
 872	enableTurbo();
 873}
 874
 875void GameController::enableTurbo() {
 876	threadInterrupt();
 877	if (!m_turbo) {
 878		m_threadContext.sync.fpsTarget = m_fpsTarget;
 879		m_threadContext.sync.audioWait = m_audioSync;
 880		m_threadContext.sync.videoFrameWait = m_videoSync;
 881	} else if (m_turboSpeed <= 0) {
 882		m_threadContext.sync.fpsTarget = m_fpsTarget;
 883		m_threadContext.sync.audioWait = false;
 884		m_threadContext.sync.videoFrameWait = false;
 885	} else {
 886		m_threadContext.sync.fpsTarget = m_fpsTarget * m_turboSpeed;
 887		m_threadContext.sync.audioWait = true;
 888		m_threadContext.sync.videoFrameWait = false;
 889	}
 890	if (m_audioProcessor) {
 891		redoSamples(m_audioProcessor->getBufferSamples());
 892	}
 893	threadContinue();
 894}
 895
 896void GameController::setAVStream(mAVStream* stream) {
 897	threadInterrupt();
 898	m_stream = stream;
 899	if (isLoaded()) {
 900		m_threadContext.core->setAVStream(m_threadContext.core, stream);
 901	}
 902	threadContinue();
 903}
 904
 905void GameController::clearAVStream() {
 906	threadInterrupt();
 907	m_stream = nullptr;
 908	if (isLoaded()) {
 909		m_threadContext.core->setAVStream(m_threadContext.core, nullptr);
 910	}
 911	threadContinue();
 912}
 913
 914#ifdef USE_PNG
 915void GameController::screenshot() {
 916	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 917		mCoreTakeScreenshot(context->core);
 918	});
 919}
 920#endif
 921
 922void GameController::reloadAudioDriver() {
 923	int samples = 0;
 924	unsigned sampleRate = 0;
 925	if (m_audioProcessor) {
 926		QMetaObject::invokeMethod(m_audioProcessor, "pause", Qt::BlockingQueuedConnection);
 927		samples = m_audioProcessor->getBufferSamples();
 928		sampleRate = m_audioProcessor->sampleRate();
 929		delete m_audioProcessor;
 930	}
 931	m_audioProcessor = AudioProcessor::create();
 932	if (samples) {
 933		m_audioProcessor->setBufferSamples(samples);
 934	}
 935	if (sampleRate) {
 936		m_audioProcessor->requestSampleRate(sampleRate);
 937	}
 938	m_audioProcessor->moveToThread(m_audioThread);
 939	connect(this, SIGNAL(gamePaused(mCoreThread*)), m_audioProcessor, SLOT(pause()));
 940	if (isLoaded()) {
 941		m_audioProcessor->setInput(&m_threadContext);
 942		startAudio();
 943	}
 944}
 945
 946void GameController::setSaveStateExtdata(int flags) {
 947	m_saveStateFlags = flags;
 948}
 949
 950void GameController::setLoadStateExtdata(int flags) {
 951	m_loadStateFlags = flags;
 952}
 953
 954void GameController::setLuminanceValue(uint8_t value) {
 955	m_luxValue = value;
 956	value = std::max<int>(value - 0x16, 0);
 957	m_luxLevel = 10;
 958	for (int i = 0; i < 10; ++i) {
 959		if (value < GBA_LUX_LEVELS[i]) {
 960			m_luxLevel = i;
 961			break;
 962		}
 963	}
 964	emit luminanceValueChanged(m_luxValue);
 965}
 966
 967void GameController::setLuminanceLevel(int level) {
 968	int value = 0x16;
 969	level = std::max(0, std::min(10, level));
 970	if (level > 0) {
 971		value += GBA_LUX_LEVELS[level - 1];
 972	}
 973	setLuminanceValue(value);
 974}
 975
 976void GameController::setRealTime() {
 977	m_rtc.override = RTC_NO_OVERRIDE;
 978}
 979
 980void GameController::setFixedTime(const QDateTime& time) {
 981	m_rtc.override = RTC_FIXED;
 982	m_rtc.value = time.toMSecsSinceEpoch() / 1000;
 983}
 984
 985void GameController::setFakeEpoch(const QDateTime& time) {
 986	m_rtc.override = RTC_FAKE_EPOCH;
 987	m_rtc.value = time.toMSecsSinceEpoch() / 1000;
 988}
 989
 990void GameController::updateKeys() {
 991	int activeKeys = m_activeKeys;
 992	activeKeys |= m_activeButtons;
 993	activeKeys &= ~m_inactiveKeys;
 994	if (isLoaded()) {
 995		m_threadContext.core->setKeys(m_threadContext.core, activeKeys);
 996	}
 997}
 998
 999void GameController::redoSamples(int samples) {
1000	if (m_threadContext.core) {
1001		m_threadContext.core->setAudioBufferSize(m_threadContext.core, samples);
1002	}
1003	QMetaObject::invokeMethod(m_audioProcessor, "inputParametersChanged");
1004}
1005
1006void GameController::setLogLevel(int levels) {
1007	threadInterrupt();
1008	m_logLevels = levels;
1009	threadContinue();
1010}
1011
1012void GameController::enableLogLevel(int levels) {
1013	threadInterrupt();
1014	m_logLevels |= levels;
1015	threadContinue();
1016}
1017
1018void GameController::disableLogLevel(int levels) {
1019	threadInterrupt();
1020	m_logLevels &= ~levels;
1021	threadContinue();
1022}
1023
1024void GameController::pollEvents() {
1025	if (!m_inputController) {
1026		return;
1027	}
1028
1029	m_activeButtons = m_inputController->pollEvents();
1030	updateKeys();
1031}
1032
1033void GameController::updateAutofire() {
1034	// TODO: Move all key events onto the CPU thread...somehow
1035	for (int k = 0; k < GBA_KEY_MAX; ++k) {
1036		if (!m_autofire[k]) {
1037			continue;
1038		}
1039		m_autofireStatus[k] ^= 1;
1040		if (m_autofireStatus[k]) {
1041			keyPressed(k);
1042		} else {
1043			keyReleased(k);
1044		}
1045	}
1046}