all repos — mgba @ e9c82df5187212025d930d862beb523f373c74ed

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