all repos — mgba @ 4360e73d1427312396135125efa45fe9aeb58175

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