all repos — mgba @ 8c0c03fb6a8c2ade5dc3d411166096708c4219e5

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