all repos — mgba @ 9ec62368bc9906ee8b9390bb609efe780ae11e21

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