all repos — mgba @ 393252718fdabad0e8cb4902be3d2420c17c8005

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