all repos — mgba @ 7d009ec43c0ce59903643913609bc7766f3cb7fb

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, 0xFF, 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		Interrupter interrupter(this);
 324		m_override->identify(m_threadContext.core);
 325	}
 326}
 327
 328void GameController::clearOverride() {
 329	delete m_override;
 330	m_override = nullptr;
 331}
 332
 333void GameController::setConfig(const mCoreConfig* config) {
 334	m_config = config;
 335	if (isLoaded()) {
 336		Interrupter interrupter(this);
 337		mCoreLoadForeignConfig(m_threadContext.core, config);
 338		m_audioProcessor->setInput(&m_threadContext);
 339	}
 340}
 341
 342#ifdef USE_GDB_STUB
 343mDebugger* GameController::debugger() {
 344	if (!isLoaded()) {
 345		return nullptr;
 346	}
 347	return m_threadContext.core->debugger;
 348}
 349
 350void GameController::setDebugger(mDebugger* debugger) {
 351	Interrupter interrupter(this);
 352	if (debugger) {
 353		mDebuggerAttach(debugger, m_threadContext.core);
 354	} else {
 355		m_threadContext.core->detachDebugger(m_threadContext.core);
 356	}
 357}
 358#endif
 359
 360void GameController::loadGame(const QString& path) {
 361	closeGame();
 362	QFileInfo info(path);
 363	if (!info.isReadable()) {
 364		LOG(QT, ERROR) << tr("Failed to open game file: %1").arg(path);
 365		return;
 366	}
 367	m_fname = info.canonicalFilePath();
 368	m_vf = nullptr;
 369	openGame();
 370}
 371
 372void GameController::loadGame(VFile* vf, const QString& base) {
 373	closeGame();
 374	m_fname = base;
 375	m_vf = vf;
 376	openGame();
 377}
 378
 379void GameController::bootBIOS() {
 380	closeGame();
 381	m_fname = QString();
 382	openGame(true);
 383}
 384
 385void GameController::openGame(bool biosOnly) {
 386	if (m_fname.isEmpty()) {
 387		biosOnly = true;
 388	}
 389	if (biosOnly && (!m_useBios || m_bios.isNull())) {
 390		return;
 391	}
 392	if (isLoaded()) {
 393		// We need to delay if the game is still cleaning up
 394		QTimer::singleShot(10, this, SLOT(openGame()));
 395		return;
 396	} else if(m_gameOpen) {
 397		cleanGame();
 398	}
 399
 400	if (!biosOnly) {
 401		if (m_vf) {
 402			m_threadContext.core = mCoreFindVF(m_vf);
 403		} else {
 404			m_threadContext.core = mCoreFind(m_fname.toUtf8().constData());
 405		}
 406	} else {
 407		m_threadContext.core = GBACoreCreate();
 408	}
 409
 410	if (!m_threadContext.core) {
 411		return;
 412	}
 413
 414	m_pauseAfterFrame = false;
 415
 416	if (m_turbo) {
 417		m_threadContext.sync.videoFrameWait = false;
 418		m_threadContext.sync.audioWait = false;
 419	} else {
 420		m_threadContext.sync.videoFrameWait = m_videoSync;
 421		m_threadContext.sync.audioWait = m_audioSync;
 422	}
 423	m_threadContext.core->init(m_threadContext.core);
 424
 425	unsigned width, height;
 426	m_threadContext.core->desiredVideoDimensions(m_threadContext.core, &width, &height);
 427	m_drawContext = new uint32_t[width * height];
 428	m_frontBuffer = new uint32_t[width * height];
 429
 430	QByteArray bytes;
 431	if (!biosOnly) {
 432		bytes = m_fname.toUtf8();
 433		if (m_vf) {
 434			m_threadContext.core->loadROM(m_threadContext.core, m_vf);
 435		} else {
 436			mCoreLoadFile(m_threadContext.core, bytes.constData());
 437			mDirectorySetDetachBase(&m_threadContext.core->dirs);
 438		}
 439	} else {
 440		bytes = m_bios.toUtf8();
 441	}
 442	char dirname[PATH_MAX];
 443	separatePath(bytes.constData(), dirname, m_threadContext.core->dirs.baseName, 0);
 444	mDirectorySetAttachBase(&m_threadContext.core->dirs, VDirOpen(dirname));
 445
 446	m_threadContext.core->setVideoBuffer(m_threadContext.core, m_drawContext, width);
 447
 448	if (!m_bios.isNull() && m_useBios) {
 449		VFile* bios = VFileDevice::open(m_bios, O_RDONLY);
 450		if (bios && !m_threadContext.core->loadBIOS(m_threadContext.core, bios, 0)) {
 451			bios->close(bios);
 452		}
 453	}
 454
 455	m_inputController->recalibrateAxes();
 456	memset(m_drawContext, 0xF8, width * height * 4);
 457
 458	m_threadContext.core->setAVStream(m_threadContext.core, m_stream);
 459
 460	if (m_config) {
 461		mCoreLoadForeignConfig(m_threadContext.core, m_config);
 462	}
 463
 464	if (!biosOnly) {
 465		mCoreAutoloadSave(m_threadContext.core);
 466		if (!m_patch.isNull()) {
 467			VFile* patch = VFileDevice::open(m_patch, O_RDONLY);
 468			if (patch) {
 469				m_threadContext.core->loadPatch(m_threadContext.core, patch);
 470			}
 471			patch->close(patch);
 472		} else {
 473			mCoreAutoloadPatch(m_threadContext.core);
 474		}
 475	}
 476	m_vf = nullptr;
 477
 478	if (!mCoreThreadStart(&m_threadContext)) {
 479		emit gameFailed();
 480	}
 481}
 482
 483void GameController::loadBIOS(const QString& path) {
 484	if (m_bios == path) {
 485		return;
 486	}
 487	m_bios = path;
 488	if (m_gameOpen) {
 489		closeGame();
 490		openGame();
 491	}
 492}
 493
 494void GameController::loadSave(const QString& path, bool temporary) {
 495	if (!isLoaded()) {
 496		return;
 497	}
 498	m_resetActions.append([this, path, temporary]() {
 499		VFile* vf = VFileDevice::open(path, temporary ? O_RDONLY : O_RDWR);
 500		if (!vf) {
 501			LOG(QT, ERROR) << tr("Failed to open save file: %1").arg(path);
 502			return;
 503		}
 504
 505		if (temporary) {
 506			m_threadContext.core->loadTemporarySave(m_threadContext.core, vf);
 507		} else {
 508			m_threadContext.core->loadSave(m_threadContext.core, vf);
 509		}
 510	});
 511	reset();
 512}
 513
 514void GameController::yankPak() {
 515	if (!m_gameOpen) {
 516		return;
 517	}
 518	Interrupter interrupter(this);
 519	GBAYankROM(static_cast<GBA*>(m_threadContext.core->board));
 520}
 521
 522void GameController::replaceGame(const QString& path) {
 523	if (!m_gameOpen) {
 524		return;
 525	}
 526
 527	QFileInfo info(path);
 528	if (!info.isReadable()) {
 529		LOG(QT, ERROR) << tr("Failed to open game file: %1").arg(path);
 530		return;
 531	}
 532	m_fname = info.canonicalFilePath();
 533	Interrupter interrupter(this);
 534	mDirectorySetDetachBase(&m_threadContext.core->dirs);
 535	mCoreLoadFile(m_threadContext.core, m_fname.toLocal8Bit().constData());
 536}
 537
 538void GameController::loadPatch(const QString& path) {
 539	if (m_gameOpen) {
 540		closeGame();
 541		m_patch = path;
 542		openGame();
 543	} else {
 544		m_patch = path;
 545	}
 546}
 547
 548void GameController::importSharkport(const QString& path) {
 549	if (!isLoaded()) {
 550		return;
 551	}
 552#ifdef M_CORE_GBA
 553	if (platform() != PLATFORM_GBA) {
 554		return;
 555	}
 556	VFile* vf = VFileDevice::open(path, O_RDONLY);
 557	if (!vf) {
 558		LOG(QT, ERROR) << tr("Failed to open snapshot file for reading: %1").arg(path);
 559		return;
 560	}
 561	threadInterrupt();
 562	GBASavedataImportSharkPort(static_cast<GBA*>(m_threadContext.core->board), vf, false);
 563	threadContinue();
 564	vf->close(vf);
 565#endif
 566}
 567
 568void GameController::exportSharkport(const QString& path) {
 569	if (!isLoaded()) {
 570		return;
 571	}
 572#ifdef M_CORE_GBA
 573	if (platform() != PLATFORM_GBA) {
 574		return;
 575	}
 576	VFile* vf = VFileDevice::open(path, O_WRONLY | O_CREAT | O_TRUNC);
 577	if (!vf) {
 578		LOG(QT, ERROR) << tr("Failed to open snapshot file for writing: %1").arg(path);
 579		return;
 580	}
 581	threadInterrupt();
 582	GBASavedataExportSharkPort(static_cast<GBA*>(m_threadContext.core->board), vf);
 583	threadContinue();
 584	vf->close(vf);
 585#endif
 586}
 587
 588void GameController::closeGame() {
 589	if (!m_gameOpen) {
 590		return;
 591	}
 592	if (m_multiplayer) {
 593		m_multiplayer->detachGame(this);
 594	}
 595
 596	if (mCoreThreadIsPaused(&m_threadContext)) {
 597		mCoreThreadUnpause(&m_threadContext);
 598	}
 599	m_patch = QString();
 600	clearOverride();
 601
 602	QMetaObject::invokeMethod(m_audioProcessor, "pause", Qt::BlockingQueuedConnection);
 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}