all repos — mgba @ 50402c830729f2ba5a6fc3e6facfd8b258f7f97d

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