all repos — mgba @ df11c9d7f31dbb261747281b793a70a723b21b47

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