all repos — mgba @ ba3b068df4a8fcb34c66b1bc5725a205a36d5807

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