all repos — mgba @ ea91c48d3e75f72577ef8cd00276819e4c3aa07e

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