all repos — mgba @ 5bcf56c5caccea4021abc92b461a0873978546f5

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
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	m_videoLayers[layer] = enable;
667	if (isLoaded() && m_threadContext.core->platform(m_threadContext.core) == PLATFORM_GBA) {
668		GBA* gba = static_cast<GBA*>(m_threadContext.core->board);
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	m_threadContext.sync.fpsTarget = fps;
687	if (m_turbo && m_turboSpeed > 0) {
688		m_threadContext.sync.fpsTarget *= m_turboSpeed;
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		m_threadContext.sync.fpsTarget = m_fpsTarget;
812		m_threadContext.sync.audioWait = m_audioSync;
813		m_threadContext.sync.videoFrameWait = m_videoSync;
814	} else if (m_turboSpeed <= 0) {
815		m_threadContext.sync.fpsTarget = m_fpsTarget;
816		m_threadContext.sync.audioWait = false;
817		m_threadContext.sync.videoFrameWait = false;
818	} else {
819		m_threadContext.sync.fpsTarget = m_fpsTarget * m_turboSpeed;
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	if (m_threadContext.core) {
934		m_threadContext.core->setAudioBufferSize(m_threadContext.core, samples);
935	}
936	QMetaObject::invokeMethod(m_audioProcessor, "inputParametersChanged");
937}
938
939void GameController::setLogLevel(int levels) {
940	threadInterrupt();
941	m_logLevels = levels;
942	threadContinue();
943}
944
945void GameController::enableLogLevel(int levels) {
946	threadInterrupt();
947	m_logLevels |= levels;
948	threadContinue();
949}
950
951void GameController::disableLogLevel(int levels) {
952	threadInterrupt();
953	m_logLevels &= ~levels;
954	threadContinue();
955}
956
957void GameController::pollEvents() {
958	if (!m_inputController) {
959		return;
960	}
961
962	m_activeButtons = m_inputController->pollEvents();
963	updateKeys();
964}
965
966void GameController::updateAutofire() {
967	// TODO: Move all key events onto the CPU thread...somehow
968	for (int k = 0; k < GBA_KEY_MAX; ++k) {
969		if (!m_autofire[k]) {
970			continue;
971		}
972		m_autofireStatus[k] ^= 1;
973		if (m_autofireStatus[k]) {
974			keyPressed(k);
975		} else {
976			keyReleased(k);
977		}
978	}
979}