all repos — mgba @ 6d898542c765f4efc4a094c5ebd3f3465c36f417

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