all repos — mgba @ 870c8ebb8c529daeb5326c836322a72114a76c5d

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