all repos — mgba @ b9c942546475eb971a142fc9ec905beeb7a93815

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	setPaused(true);
523	m_rewindTimer.start();
524}
525
526void GameController::stopRewinding() {
527	if (!m_rewindTimer.isActive()) {
528		return;
529	}
530	m_rewindTimer.stop();
531	setPaused(m_wasPaused);
532}
533
534void GameController::keyPressed(int key) {
535	int mappedKey = 1 << key;
536	m_activeKeys |= mappedKey;
537	if (!m_inputController->allowOpposing()) {
538		if ((m_activeKeys & 0x30) == 0x30) {
539			m_inactiveKeys |= mappedKey ^ 0x30;
540			m_activeKeys ^= mappedKey ^ 0x30;
541		}
542		if ((m_activeKeys & 0xC0) == 0xC0) {
543			m_inactiveKeys |= mappedKey ^ 0xC0;
544			m_activeKeys ^= mappedKey ^ 0xC0;
545		}
546	}
547	updateKeys();
548}
549
550void GameController::keyReleased(int key) {
551	int mappedKey = 1 << key;
552	m_activeKeys &= ~mappedKey;
553	if (!m_inputController->allowOpposing()) {
554		if (mappedKey & 0x30) {
555			m_activeKeys |= m_inactiveKeys & (0x30 ^ mappedKey);
556			m_inactiveKeys &= ~0x30;
557		}
558		if (mappedKey & 0xC0) {
559			m_activeKeys |= m_inactiveKeys & (0xC0 ^ mappedKey);
560			m_inactiveKeys &= ~0xC0;
561		}
562	}
563	updateKeys();
564}
565
566void GameController::clearKeys() {
567	m_activeKeys = 0;
568	m_inactiveKeys = 0;
569	updateKeys();
570}
571
572void GameController::setAudioBufferSamples(int samples) {
573	threadInterrupt();
574	redoSamples(samples);
575	threadContinue();
576	QMetaObject::invokeMethod(m_audioProcessor, "setBufferSamples", Q_ARG(int, samples));
577}
578
579void GameController::setFPSTarget(float fps) {
580	threadInterrupt();
581	m_fpsTarget = fps;
582	m_threadContext.fpsTarget = fps;
583	if (m_turbo && m_turboSpeed > 0) {
584		m_threadContext.fpsTarget *= m_turboSpeed;
585	}
586	redoSamples(m_audioProcessor->getBufferSamples());
587	threadContinue();
588}
589
590void GameController::setSkipBIOS(bool set) {
591	threadInterrupt();
592	m_threadContext.skipBios = set;
593	threadContinue();
594}
595
596void GameController::setUseBIOS(bool use) {
597	threadInterrupt();
598	m_useBios = use;
599	threadContinue();
600}
601
602void GameController::loadState(int slot) {
603	if (slot > 0 && slot != m_stateSlot) {
604		m_stateSlot = slot;
605		m_backupSaveState.clear();
606	}
607	GBARunOnThread(&m_threadContext, [](GBAThread* context) {
608		GameController* controller = static_cast<GameController*>(context->userData);
609		if (!controller->m_backupLoadState) {
610			controller->m_backupLoadState = new GBASerializedState;
611		}
612		GBASerialize(context->gba, controller->m_backupLoadState);
613		if (GBALoadState(context, context->stateDir, controller->m_stateSlot)) {
614			controller->frameAvailable(controller->m_drawContext);
615			controller->stateLoaded(context);
616		}
617	});
618}
619
620void GameController::saveState(int slot) {
621	if (slot > 0) {
622		m_stateSlot = slot;
623	}
624	GBARunOnThread(&m_threadContext, [](GBAThread* context) {
625		GameController* controller = static_cast<GameController*>(context->userData);
626		VFile* vf = GBAGetState(context->gba, context->stateDir, controller->m_stateSlot, false);
627		if (vf) {
628			controller->m_backupSaveState.resize(vf->size(vf));
629			vf->read(vf, controller->m_backupSaveState.data(), controller->m_backupSaveState.size());
630			vf->close(vf);
631		}
632		GBASaveState(context, context->stateDir, controller->m_stateSlot, true);
633	});
634}
635
636void GameController::loadBackupState() {
637	if (!m_backupLoadState) {
638		return;
639	}
640
641	GBARunOnThread(&m_threadContext, [](GBAThread* context) {
642		GameController* controller = static_cast<GameController*>(context->userData);
643		if (GBADeserialize(context->gba, controller->m_backupLoadState)) {
644			GBALog(context->gba, GBA_LOG_STATUS, "Undid state load");
645			controller->frameAvailable(controller->m_drawContext);
646			controller->stateLoaded(context);
647		}
648		delete controller->m_backupLoadState;
649		controller->m_backupLoadState = nullptr;
650	});
651}
652
653void GameController::saveBackupState() {
654	if (m_backupSaveState.isEmpty()) {
655		return;
656	}
657
658	GBARunOnThread(&m_threadContext, [](GBAThread* context) {
659		GameController* controller = static_cast<GameController*>(context->userData);
660		VFile* vf = GBAGetState(context->gba, context->stateDir, controller->m_stateSlot, true);
661		if (vf) {
662			vf->write(vf, controller->m_backupSaveState.constData(), controller->m_backupSaveState.size());
663			vf->close(vf);
664			GBALog(context->gba, GBA_LOG_STATUS, "Undid state save");
665		}
666		controller->m_backupSaveState.clear();
667	});
668}
669
670void GameController::setVideoSync(bool set) {
671	m_videoSync = set;
672	if (!m_turbo) {
673		threadInterrupt();
674		m_threadContext.sync.videoFrameWait = set;
675		threadContinue();
676	}
677}
678
679void GameController::setAudioSync(bool set) {
680	m_audioSync = set;
681	if (!m_turbo) {
682		threadInterrupt();
683		m_threadContext.sync.audioWait = set;
684		threadContinue();
685	}
686}
687
688void GameController::setFrameskip(int skip) {
689	m_threadContext.frameskip = skip;
690}
691
692void GameController::setVolume(int volume) {
693	threadInterrupt();
694	m_threadContext.volume = volume;
695	if (m_gameOpen) {
696		m_threadContext.gba->audio.masterVolume = volume;
697	}
698	threadContinue();
699}
700
701void GameController::setMute(bool mute) {
702	threadInterrupt();
703	m_threadContext.mute = mute;
704	if (m_gameOpen) {
705		m_threadContext.gba->audio.masterVolume = mute ? 0 : m_threadContext.volume;
706	}
707	threadContinue();
708}
709
710void GameController::setTurbo(bool set, bool forced) {
711	if (m_turboForced && !forced) {
712		return;
713	}
714	if (m_turbo == set && m_turboForced == forced) {
715		// Don't interrupt the thread if we don't need to
716		return;
717	}
718	m_turbo = set;
719	m_turboForced = set && forced;
720	enableTurbo();
721}
722
723void GameController::setTurboSpeed(float ratio) {
724	m_turboSpeed = ratio;
725	enableTurbo();
726}
727
728void GameController::enableTurbo() {
729	threadInterrupt();
730	if (!m_turbo) {
731		m_threadContext.fpsTarget = m_fpsTarget;
732		m_threadContext.sync.audioWait = m_audioSync;
733		m_threadContext.sync.videoFrameWait = m_videoSync;
734	} else if (m_turboSpeed <= 0) {
735		m_threadContext.fpsTarget = m_fpsTarget;
736		m_threadContext.sync.audioWait = false;
737		m_threadContext.sync.videoFrameWait = false;
738	} else {
739		m_threadContext.fpsTarget = m_fpsTarget * m_turboSpeed;
740		m_threadContext.sync.audioWait = true;
741		m_threadContext.sync.videoFrameWait = false;
742	}
743	redoSamples(m_audioProcessor->getBufferSamples());
744	threadContinue();
745}
746
747void GameController::setAVStream(GBAAVStream* stream) {
748	threadInterrupt();
749	m_threadContext.stream = stream;
750	if (m_gameOpen) {
751		m_threadContext.gba->stream = stream;
752	}
753	threadContinue();
754}
755
756void GameController::clearAVStream() {
757	threadInterrupt();
758	m_threadContext.stream = nullptr;
759	if (m_gameOpen) {
760		m_threadContext.gba->stream = nullptr;
761	}
762	threadContinue();
763}
764
765#ifdef USE_PNG
766void GameController::screenshot() {
767	GBARunOnThread(&m_threadContext, GBAThreadTakeScreenshot);
768}
769#endif
770
771void GameController::reloadAudioDriver() {
772	QMetaObject::invokeMethod(m_audioProcessor, "pause", Qt::BlockingQueuedConnection);
773	int samples = m_audioProcessor->getBufferSamples();
774	delete m_audioProcessor;
775	m_audioProcessor = AudioProcessor::create();
776	m_audioProcessor->setBufferSamples(samples);
777	m_audioProcessor->moveToThread(m_audioThread);
778	connect(this, SIGNAL(gameStarted(GBAThread*)), m_audioProcessor, SLOT(start()));
779	connect(this, SIGNAL(gameStopped(GBAThread*)), m_audioProcessor, SLOT(pause()));
780	connect(this, SIGNAL(gamePaused(GBAThread*)), m_audioProcessor, SLOT(pause()));
781	connect(this, SIGNAL(gameUnpaused(GBAThread*)), m_audioProcessor, SLOT(start()));
782	if (isLoaded()) {
783		m_audioProcessor->setInput(&m_threadContext);
784		QMetaObject::invokeMethod(m_audioProcessor, "start");
785	}
786}
787
788void GameController::setLuminanceValue(uint8_t value) {
789	m_luxValue = value;
790	value = std::max<int>(value - 0x16, 0);
791	m_luxLevel = 10;
792	for (int i = 0; i < 10; ++i) {
793		if (value < LUX_LEVELS[i]) {
794			m_luxLevel = i;
795			break;
796		}
797	}
798	emit luminanceValueChanged(m_luxValue);
799}
800
801void GameController::setLuminanceLevel(int level) {
802	int value = 0x16;
803	level = std::max(0, std::min(10, level));
804	if (level > 0) {
805		value += LUX_LEVELS[level - 1];
806	}
807	setLuminanceValue(value);
808}
809
810void GameController::setRealTime() {
811	m_rtc.override = GBARTCGenericSource::RTC_NO_OVERRIDE;
812}
813
814void GameController::setFixedTime(const QDateTime& time) {
815	m_rtc.override = GBARTCGenericSource::RTC_FIXED;
816	m_rtc.value = time.toMSecsSinceEpoch() / 1000;
817}
818
819void GameController::setFakeEpoch(const QDateTime& time) {
820	m_rtc.override = GBARTCGenericSource::RTC_FAKE_EPOCH;
821	m_rtc.value = time.toMSecsSinceEpoch() / 1000;
822}
823
824void GameController::updateKeys() {
825	int activeKeys = m_activeKeys;
826	activeKeys |= m_activeButtons;
827	activeKeys &= ~m_inactiveKeys;
828	m_threadContext.activeKeys = activeKeys;
829}
830
831void GameController::redoSamples(int samples) {
832#if RESAMPLE_LIBRARY != RESAMPLE_BLIP_BUF
833	float sampleRate = 0x8000;
834	float ratio;
835	if (m_threadContext.gba) {
836		sampleRate = m_threadContext.gba->audio.sampleRate;
837	}
838	ratio = GBAAudioCalculateRatio(sampleRate, m_threadContext.fpsTarget, m_audioProcess->sampleRate());
839	m_threadContext.audioBuffers = ceil(samples / ratio);
840#else
841	m_threadContext.audioBuffers = samples;
842#endif
843	if (m_threadContext.gba) {
844		GBAAudioResizeBuffer(&m_threadContext.gba->audio, m_threadContext.audioBuffers);
845	}
846	QMetaObject::invokeMethod(m_audioProcessor, "inputParametersChanged");
847}
848
849void GameController::setLogLevel(int levels) {
850	threadInterrupt();
851	m_logLevels = levels;
852	threadContinue();
853}
854
855void GameController::enableLogLevel(int levels) {
856	threadInterrupt();
857	m_logLevels |= levels;
858	threadContinue();
859}
860
861void GameController::disableLogLevel(int levels) {
862	threadInterrupt();
863	m_logLevels &= ~levels;
864	threadContinue();
865}
866
867void GameController::pollEvents() {
868	if (!m_inputController) {
869		return;
870	}
871
872	m_activeButtons = m_inputController->pollEvents();
873	updateKeys();
874}