all repos — mgba @ a86184df43bb8e0ab6ae3661d297cb12c5e91156

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