all repos — mgba @ 0eb76806beb6af13d8aacf535795fc0f84b65233

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