all repos — mgba @ 4fd479897c6972377ac625f43306aa794bc4d5c0

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	threadInterrupt();
674	m_useBios = use;
675	threadContinue();
676}
677
678void GameController::loadState(int slot) {
679	if (slot > 0 && slot != m_stateSlot) {
680		m_stateSlot = slot;
681		m_backupSaveState.clear();
682	}
683	GBARunOnThread(&m_threadContext, [](GBAThread* context) {
684		GameController* controller = static_cast<GameController*>(context->userData);
685		if (!controller->m_backupLoadState) {
686			controller->m_backupLoadState = new GBASerializedState;
687		}
688		GBASerialize(context->gba, controller->m_backupLoadState);
689		if (GBALoadState(context, context->stateDir, controller->m_stateSlot)) {
690			controller->frameAvailable(controller->m_drawContext);
691			controller->stateLoaded(context);
692		}
693	});
694}
695
696void GameController::saveState(int slot) {
697	if (slot > 0) {
698		m_stateSlot = slot;
699	}
700	GBARunOnThread(&m_threadContext, [](GBAThread* context) {
701		GameController* controller = static_cast<GameController*>(context->userData);
702		VFile* vf = GBAGetState(context->gba, context->stateDir, controller->m_stateSlot, false);
703		if (vf) {
704			controller->m_backupSaveState.resize(vf->size(vf));
705			vf->read(vf, controller->m_backupSaveState.data(), controller->m_backupSaveState.size());
706			vf->close(vf);
707		}
708		GBASaveState(context, context->stateDir, controller->m_stateSlot, true);
709	});
710}
711
712void GameController::loadBackupState() {
713	if (!m_backupLoadState) {
714		return;
715	}
716
717	GBARunOnThread(&m_threadContext, [](GBAThread* context) {
718		GameController* controller = static_cast<GameController*>(context->userData);
719		if (GBADeserialize(context->gba, controller->m_backupLoadState)) {
720			GBALog(context->gba, GBA_LOG_STATUS, "Undid state load");
721			controller->frameAvailable(controller->m_drawContext);
722			controller->stateLoaded(context);
723		}
724		delete controller->m_backupLoadState;
725		controller->m_backupLoadState = nullptr;
726	});
727}
728
729void GameController::saveBackupState() {
730	if (m_backupSaveState.isEmpty()) {
731		return;
732	}
733
734	GBARunOnThread(&m_threadContext, [](GBAThread* context) {
735		GameController* controller = static_cast<GameController*>(context->userData);
736		VFile* vf = GBAGetState(context->gba, context->stateDir, controller->m_stateSlot, true);
737		if (vf) {
738			vf->write(vf, controller->m_backupSaveState.constData(), controller->m_backupSaveState.size());
739			vf->close(vf);
740			GBALog(context->gba, GBA_LOG_STATUS, "Undid state save");
741		}
742		controller->m_backupSaveState.clear();
743	});
744}
745
746void GameController::setVideoSync(bool set) {
747	m_videoSync = set;
748	if (!m_turbo) {
749		threadInterrupt();
750		m_threadContext.sync.videoFrameWait = set;
751		threadContinue();
752	}
753}
754
755void GameController::setAudioSync(bool set) {
756	m_audioSync = set;
757	if (!m_turbo) {
758		threadInterrupt();
759		m_threadContext.sync.audioWait = set;
760		threadContinue();
761	}
762}
763
764void GameController::setFrameskip(int skip) {
765	m_threadContext.frameskip = skip;
766}
767
768void GameController::setVolume(int volume) {
769	threadInterrupt();
770	m_threadContext.volume = volume;
771	if (m_gameOpen) {
772		m_threadContext.gba->audio.masterVolume = volume;
773	}
774	threadContinue();
775}
776
777void GameController::setMute(bool mute) {
778	threadInterrupt();
779	m_threadContext.mute = mute;
780	if (m_gameOpen) {
781		m_threadContext.gba->audio.masterVolume = mute ? 0 : m_threadContext.volume;
782	}
783	threadContinue();
784}
785
786void GameController::setTurbo(bool set, bool forced) {
787	if (m_turboForced && !forced) {
788		return;
789	}
790	if (m_turbo == set && m_turboForced == forced) {
791		// Don't interrupt the thread if we don't need to
792		return;
793	}
794	m_turbo = set;
795	m_turboForced = set && forced;
796	enableTurbo();
797}
798
799void GameController::setTurboSpeed(float ratio) {
800	m_turboSpeed = ratio;
801	enableTurbo();
802}
803
804void GameController::enableTurbo() {
805	threadInterrupt();
806	if (!m_turbo) {
807		m_threadContext.fpsTarget = m_fpsTarget;
808		m_threadContext.sync.audioWait = m_audioSync;
809		m_threadContext.sync.videoFrameWait = m_videoSync;
810	} else if (m_turboSpeed <= 0) {
811		m_threadContext.fpsTarget = m_fpsTarget;
812		m_threadContext.sync.audioWait = false;
813		m_threadContext.sync.videoFrameWait = false;
814	} else {
815		m_threadContext.fpsTarget = m_fpsTarget * m_turboSpeed;
816		m_threadContext.sync.audioWait = true;
817		m_threadContext.sync.videoFrameWait = false;
818	}
819	if (m_audioProcessor) {
820		redoSamples(m_audioProcessor->getBufferSamples());
821	}
822	threadContinue();
823}
824
825void GameController::setAVStream(GBAAVStream* stream) {
826	threadInterrupt();
827	m_threadContext.stream = stream;
828	if (m_gameOpen) {
829		m_threadContext.gba->stream = stream;
830	}
831	threadContinue();
832}
833
834void GameController::clearAVStream() {
835	threadInterrupt();
836	m_threadContext.stream = nullptr;
837	if (m_gameOpen) {
838		m_threadContext.gba->stream = nullptr;
839	}
840	threadContinue();
841}
842
843#ifdef USE_PNG
844void GameController::screenshot() {
845	GBARunOnThread(&m_threadContext, GBAThreadTakeScreenshot);
846}
847#endif
848
849void GameController::reloadAudioDriver() {
850	int samples = 0;
851	unsigned sampleRate = 0;
852	if (m_audioProcessor) {
853		QMetaObject::invokeMethod(m_audioProcessor, "pause", Qt::BlockingQueuedConnection);
854		samples = m_audioProcessor->getBufferSamples();
855		sampleRate = m_audioProcessor->sampleRate();
856		delete m_audioProcessor;
857	}
858	m_audioProcessor = AudioProcessor::create();
859	if (samples) {
860		m_audioProcessor->setBufferSamples(samples);
861	}
862	if (sampleRate) {
863		m_audioProcessor->requestSampleRate(sampleRate);
864	}
865	m_audioProcessor->moveToThread(m_audioThread);
866	connect(this, SIGNAL(gameStarted(GBAThread*)), m_audioProcessor, SLOT(start()));
867	connect(this, SIGNAL(gameStopped(GBAThread*)), m_audioProcessor, SLOT(pause()));
868	connect(this, SIGNAL(gamePaused(GBAThread*)), m_audioProcessor, SLOT(pause()));
869	connect(this, SIGNAL(gameUnpaused(GBAThread*)), m_audioProcessor, SLOT(start()));
870	if (isLoaded()) {
871		m_audioProcessor->setInput(&m_threadContext);
872		QMetaObject::invokeMethod(m_audioProcessor, "start");
873	}
874}
875
876void GameController::setLuminanceValue(uint8_t value) {
877	m_luxValue = value;
878	value = std::max<int>(value - 0x16, 0);
879	m_luxLevel = 10;
880	for (int i = 0; i < 10; ++i) {
881		if (value < GBA_LUX_LEVELS[i]) {
882			m_luxLevel = i;
883			break;
884		}
885	}
886	emit luminanceValueChanged(m_luxValue);
887}
888
889void GameController::setLuminanceLevel(int level) {
890	int value = 0x16;
891	level = std::max(0, std::min(10, level));
892	if (level > 0) {
893		value += GBA_LUX_LEVELS[level - 1];
894	}
895	setLuminanceValue(value);
896}
897
898void GameController::setRealTime() {
899	m_rtc.override = GBARTCGenericSource::RTC_NO_OVERRIDE;
900}
901
902void GameController::setFixedTime(const QDateTime& time) {
903	m_rtc.override = GBARTCGenericSource::RTC_FIXED;
904	m_rtc.value = time.toMSecsSinceEpoch() / 1000;
905}
906
907void GameController::setFakeEpoch(const QDateTime& time) {
908	m_rtc.override = GBARTCGenericSource::RTC_FAKE_EPOCH;
909	m_rtc.value = time.toMSecsSinceEpoch() / 1000;
910}
911
912void GameController::updateKeys() {
913	int activeKeys = m_activeKeys;
914	activeKeys |= m_activeButtons;
915	activeKeys &= ~m_inactiveKeys;
916	m_threadContext.activeKeys = activeKeys;
917}
918
919void GameController::redoSamples(int samples) {
920#if RESAMPLE_LIBRARY != RESAMPLE_BLIP_BUF
921	float sampleRate = 0x8000;
922	float ratio;
923	if (m_threadContext.gba) {
924		sampleRate = m_threadContext.gba->audio.sampleRate;
925	}
926	ratio = GBAAudioCalculateRatio(sampleRate, m_threadContext.fpsTarget, m_audioProcess->sampleRate());
927	m_threadContext.audioBuffers = ceil(samples / ratio);
928#else
929	m_threadContext.audioBuffers = samples;
930#endif
931	if (m_threadContext.gba) {
932		GBAAudioResizeBuffer(&m_threadContext.gba->audio, m_threadContext.audioBuffers);
933	}
934	QMetaObject::invokeMethod(m_audioProcessor, "inputParametersChanged");
935}
936
937void GameController::setLogLevel(int levels) {
938	threadInterrupt();
939	m_logLevels = levels;
940	threadContinue();
941}
942
943void GameController::enableLogLevel(int levels) {
944	threadInterrupt();
945	m_logLevels |= levels;
946	threadContinue();
947}
948
949void GameController::disableLogLevel(int levels) {
950	threadInterrupt();
951	m_logLevels &= ~levels;
952	threadContinue();
953}
954
955void GameController::pollEvents() {
956	if (!m_inputController) {
957		return;
958	}
959
960	m_activeButtons = m_inputController->pollEvents();
961	updateKeys();
962}