all repos — mgba @ 2420fd81e71c3db111fa44cfc075b1c921948b24

mGBA Game Boy Advance Emulator

src/platform/qt/CoreController.cpp (view raw)

  1/* Copyright (c) 2013-2017 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 "CoreController.h"
  7
  8#include "ConfigController.h"
  9#include "InputController.h"
 10#include "LogController.h"
 11#include "MultiplayerController.h"
 12#include "Override.h"
 13
 14#include <QDateTime>
 15#include <QMutexLocker>
 16
 17#include <mgba/core/serialize.h>
 18#include <mgba/feature/video-logger.h>
 19#ifdef M_CORE_GBA
 20#include <mgba/internal/gba/gba.h>
 21#include <mgba/internal/gba/renderers/cache-set.h>
 22#include <mgba/internal/gba/sharkport.h>
 23#endif
 24#ifdef M_CORE_GB
 25#include <mgba/internal/gb/gb.h>
 26#include <mgba/internal/gb/renderers/cache-set.h>
 27#endif
 28#include <mgba-util/math.h>
 29#include <mgba-util/vfs.h>
 30
 31#define AUTOSAVE_GRANULARITY 600
 32
 33using namespace QGBA;
 34
 35CoreController::CoreController(mCore* core, QObject* parent)
 36	: QObject(parent)
 37	, m_saveStateFlags(SAVESTATE_SCREENSHOT | SAVESTATE_SAVEDATA | SAVESTATE_CHEATS | SAVESTATE_RTC)
 38	, m_loadStateFlags(SAVESTATE_SCREENSHOT | SAVESTATE_RTC)
 39{
 40	m_threadContext.core = core;
 41	m_threadContext.userData = this;
 42
 43	m_resetActions.append([this]() {
 44		if (m_autoload) {
 45			mCoreLoadState(m_threadContext.core, 0, m_loadStateFlags);
 46		}
 47	});
 48
 49	m_threadContext.startCallback = [](mCoreThread* context) {
 50		CoreController* controller = static_cast<CoreController*>(context->userData);
 51
 52		switch (context->core->platform(context->core)) {
 53#ifdef M_CORE_GBA
 54		case PLATFORM_GBA:
 55			context->core->setPeripheral(context->core, mPERIPH_GBA_LUMINANCE, controller->m_inputController->luminance());
 56			break;
 57#endif
 58		default:
 59			break;
 60		}
 61
 62		controller->updateFastForward();
 63
 64		if (controller->m_multiplayer) {
 65			controller->m_multiplayer->attachGame(controller);
 66		}
 67
 68		QMetaObject::invokeMethod(controller, "started");
 69	};
 70
 71	m_threadContext.resetCallback = [](mCoreThread* context) {
 72		CoreController* controller = static_cast<CoreController*>(context->userData);
 73		for (auto action : controller->m_resetActions) {
 74			action();
 75		}
 76
 77		if (controller->m_override) {
 78			controller->m_override->identify(context->core);
 79			controller->m_override->apply(context->core);
 80		}
 81
 82		controller->m_resetActions.clear();
 83
 84		if (!controller->m_hwaccel) {
 85			context->core->setVideoBuffer(context->core, reinterpret_cast<color_t*>(controller->m_activeBuffer.data()), controller->screenDimensions().width());
 86		}
 87
 88		QMetaObject::invokeMethod(controller, "didReset");
 89		controller->finishFrame();
 90	};
 91
 92	m_threadContext.frameCallback = [](mCoreThread* context) {
 93		CoreController* controller = static_cast<CoreController*>(context->userData);
 94
 95		if (controller->m_autosaveCounter == AUTOSAVE_GRANULARITY) {
 96			if (controller->m_autosave) {
 97				mCoreSaveState(context->core, 0, controller->m_saveStateFlags);
 98			}
 99			controller->m_autosaveCounter = 0;
100		}
101		++controller->m_autosaveCounter;
102
103		controller->finishFrame();
104	};
105
106	m_threadContext.cleanCallback = [](mCoreThread* context) {
107		CoreController* controller = static_cast<CoreController*>(context->userData);
108
109		if (controller->m_autosave) {
110			mCoreSaveState(context->core, 0, controller->m_saveStateFlags);
111		}
112
113		controller->clearMultiplayerController();
114		QMetaObject::invokeMethod(controller, "stopping");
115	};
116
117	m_threadContext.pauseCallback = [](mCoreThread* context) {
118		CoreController* controller = static_cast<CoreController*>(context->userData);
119
120		QMetaObject::invokeMethod(controller, "paused");
121	};
122
123	m_threadContext.unpauseCallback = [](mCoreThread* context) {
124		CoreController* controller = static_cast<CoreController*>(context->userData);
125
126		QMetaObject::invokeMethod(controller, "unpaused");
127	};
128
129	m_threadContext.logger.d.log = [](mLogger* logger, int category, enum mLogLevel level, const char* format, va_list args) {
130		mThreadLogger* logContext = reinterpret_cast<mThreadLogger*>(logger);
131		mCoreThread* context = logContext->p;
132
133		static const char* savestateMessage = "State %i saved";
134		static const char* loadstateMessage = "State %i loaded";
135		static const char* savestateFailedMessage = "State %i failed to load";
136		static int biosCat = -1;
137		static int statusCat = -1;
138		if (!context) {
139			return;
140		}
141		CoreController* controller = static_cast<CoreController*>(context->userData);
142		QString message;
143		if (biosCat < 0) {
144			biosCat = mLogCategoryById("gba.bios");
145		}
146		if (statusCat < 0) {
147			statusCat = mLogCategoryById("core.status");
148		}
149#ifdef M_CORE_GBA
150		if (level == mLOG_STUB && category == biosCat) {
151			va_list argc;
152			va_copy(argc, args);
153			int immediate = va_arg(argc, int);
154			va_end(argc);
155			QMetaObject::invokeMethod(controller, "unimplementedBiosCall", Q_ARG(int, immediate));
156		} else
157#endif
158		if (category == statusCat) {
159			// Slot 0 is reserved for suspend points
160			if (strncmp(loadstateMessage, format, strlen(loadstateMessage)) == 0) {
161				va_list argc;
162				va_copy(argc, args);
163				int slot = va_arg(argc, int);
164				va_end(argc);
165				if (slot == 0) {
166					format = "Loaded suspend state";
167				}
168			} else if (strncmp(savestateFailedMessage, format, strlen(savestateFailedMessage)) == 0 || strncmp(savestateMessage, format, strlen(savestateMessage)) == 0) {
169				va_list argc;
170				va_copy(argc, args);
171				int slot = va_arg(argc, int);
172				va_end(argc);
173				if (slot == 0) {
174					return;
175				}
176			}
177			message = QString().vsprintf(format, args);
178			QMetaObject::invokeMethod(controller, "statusPosted", Q_ARG(const QString&, message));
179		}
180		message = QString().vsprintf(format, args);
181		QMetaObject::invokeMethod(controller, "logPosted", Q_ARG(int, level), Q_ARG(int, category), Q_ARG(const QString&, message));
182		if (level == mLOG_FATAL) {
183			QMetaObject::invokeMethod(controller, "crashed", Q_ARG(const QString&, QString().vsprintf(format, args)));
184		}
185	};
186}
187
188CoreController::~CoreController() {
189	endVideoLog();
190	stop();
191	disconnect();
192
193	mCoreThreadJoin(&m_threadContext);
194
195	if (m_cacheSet) {
196		mCacheSetDeinit(m_cacheSet.get());
197		m_cacheSet.reset();
198	}
199
200	mCoreConfigDeinit(&m_threadContext.core->config);
201	m_threadContext.core->deinit(m_threadContext.core);
202}
203
204const color_t* CoreController::drawContext() {
205	if (m_hwaccel) {
206		return nullptr;
207	}
208	QMutexLocker locker(&m_bufferMutex);
209	return reinterpret_cast<const color_t*>(m_completeBuffer.constData());
210}
211
212QImage CoreController::getPixels() {
213	QByteArray buffer;
214	QSize size = screenDimensions();
215	size_t stride = size.width() * BYTES_PER_PIXEL;
216
217	if (!m_hwaccel) {
218		buffer = m_completeBuffer;
219	} else {
220		Interrupter interrupter(this);
221		const void* pixels;
222		m_threadContext.core->getPixels(m_threadContext.core, &pixels, &stride);
223		stride *= BYTES_PER_PIXEL;
224		buffer.resize(stride * size.height());
225		memcpy(buffer.data(), pixels, buffer.size());
226	}
227
228	return QImage(reinterpret_cast<const uchar*>(buffer.constData()),
229	              size.width(), size.height(), stride, QImage::Format_RGBX8888);
230}
231
232bool CoreController::isPaused() {
233	return mCoreThreadIsPaused(&m_threadContext);
234}
235
236bool CoreController::hasStarted() {
237	return mCoreThreadHasStarted(&m_threadContext);
238}
239
240mPlatform CoreController::platform() const {
241	return m_threadContext.core->platform(m_threadContext.core);
242}
243
244QSize CoreController::screenDimensions() const {
245	unsigned width, height;
246	m_threadContext.core->desiredVideoDimensions(m_threadContext.core, &width, &height);
247
248	return QSize(width, height);
249}
250
251void CoreController::loadConfig(ConfigController* config) {
252	Interrupter interrupter(this);
253	m_loadStateFlags = config->getOption("loadStateExtdata", m_loadStateFlags).toInt();
254	m_saveStateFlags = config->getOption("saveStateExtdata", m_saveStateFlags).toInt();
255	m_fastForwardRatio = config->getOption("fastForwardRatio", m_fastForwardRatio).toFloat();
256	m_videoSync = config->getOption("videoSync", m_videoSync).toInt();
257	m_audioSync = config->getOption("audioSync", m_audioSync).toInt();
258	m_fpsTarget = config->getOption("fpsTarget").toFloat();
259	m_autosave = config->getOption("autosave", false).toInt();
260	m_autoload = config->getOption("autoload", true).toInt();
261	m_autofireThreshold = config->getOption("autofireThreshold", m_autofireThreshold).toInt();
262	m_fastForwardVolume = config->getOption("fastForwardVolume", -1).toInt();
263	m_fastForwardMute = config->getOption("fastForwardMute", -1).toInt();
264	mCoreConfigCopyValue(&m_threadContext.core->config, config->config(), "volume");
265	mCoreConfigCopyValue(&m_threadContext.core->config, config->config(), "mute");
266	mCoreLoadForeignConfig(m_threadContext.core, config->config());
267	if (hasStarted()) {
268		updateFastForward();
269		mCoreThreadRewindParamsChanged(&m_threadContext);
270	}
271}
272
273#ifdef USE_DEBUGGERS
274void CoreController::setDebugger(mDebugger* debugger) {
275	Interrupter interrupter(this);
276	if (debugger) {
277		mDebuggerAttach(debugger, m_threadContext.core);
278		mDebuggerEnter(debugger, DEBUGGER_ENTER_ATTACHED, 0);
279	} else {
280		m_threadContext.core->detachDebugger(m_threadContext.core);
281	}
282}
283#endif
284
285void CoreController::setMultiplayerController(MultiplayerController* controller) {
286	if (controller == m_multiplayer) {
287		return;
288	}
289	clearMultiplayerController();
290	m_multiplayer = controller;
291	if (!mCoreThreadHasStarted(&m_threadContext)) {
292		return;
293	}
294	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* thread) {
295		CoreController* controller = static_cast<CoreController*>(thread->userData);
296		controller->m_multiplayer->attachGame(controller);
297	});
298}
299
300void CoreController::clearMultiplayerController() {
301	if (!m_multiplayer) {
302		return;
303	}
304	m_multiplayer->detachGame(this);
305	m_multiplayer = nullptr;
306}
307
308mCacheSet* CoreController::graphicCaches() {
309	if (m_cacheSet) {
310		return m_cacheSet.get();
311	}
312	Interrupter interrupter(this);
313	switch (platform()) {
314#ifdef M_CORE_GBA
315	case PLATFORM_GBA: {
316		GBA* gba = static_cast<GBA*>(m_threadContext.core->board);
317		m_cacheSet = std::make_unique<mCacheSet>();
318		GBAVideoCacheInit(m_cacheSet.get());
319		GBAVideoCacheAssociate(m_cacheSet.get(), &gba->video);
320		break;
321	}
322#endif
323#ifdef M_CORE_GB
324	case PLATFORM_GB: {
325		GB* gb = static_cast<GB*>(m_threadContext.core->board);
326		m_cacheSet = std::make_unique<mCacheSet>();
327		GBVideoCacheInit(m_cacheSet.get());
328		GBVideoCacheAssociate(m_cacheSet.get(), &gb->video);
329		break;
330	}
331#endif
332	default:
333		return nullptr;
334	}
335	return m_cacheSet.get();
336}
337
338void CoreController::setOverride(std::unique_ptr<Override> override) {
339	Interrupter interrupter(this);
340	m_override = std::move(override);
341	m_override->identify(m_threadContext.core);
342}
343
344void CoreController::setInputController(InputController* inputController) {
345	m_inputController = inputController;
346	m_threadContext.core->setPeripheral(m_threadContext.core, mPERIPH_ROTATION, m_inputController->rotationSource());
347	m_threadContext.core->setPeripheral(m_threadContext.core, mPERIPH_RUMBLE, m_inputController->rumble());
348	m_threadContext.core->setPeripheral(m_threadContext.core, mPERIPH_IMAGE_SOURCE, m_inputController->imageSource());
349}
350
351void CoreController::setLogger(LogController* logger) {
352	disconnect(m_log);
353	m_log = logger;
354	m_threadContext.logger.d.filter = logger->filter();
355	connect(this, &CoreController::logPosted, m_log, &LogController::postLog);
356}
357
358void CoreController::start() {
359	if (!m_hwaccel) {
360		QSize size(256, 224);
361		m_activeBuffer.resize(size.width() * size.height() * sizeof(color_t));
362		m_activeBuffer.fill(0xFF);
363		m_completeBuffer = m_activeBuffer;
364
365		m_threadContext.core->setVideoBuffer(m_threadContext.core, reinterpret_cast<color_t*>(m_activeBuffer.data()), size.width());
366	}
367
368	if (!m_patched) {
369		mCoreAutoloadPatch(m_threadContext.core);
370	}
371	if (!mCoreThreadStart(&m_threadContext)) {
372		emit failed();
373		emit stopping();
374	}
375}
376
377void CoreController::stop() {
378	setSync(false);
379#ifdef USE_DEBUGGERS
380	setDebugger(nullptr);
381#endif
382	setPaused(false);
383	mCoreThreadEnd(&m_threadContext);
384}
385
386void CoreController::reset() {
387	bool wasPaused = isPaused();
388	setPaused(false);
389	Interrupter interrupter(this);
390	mCoreThreadReset(&m_threadContext);
391	if (wasPaused) {
392		setPaused(true);
393	}
394}
395
396void CoreController::setPaused(bool paused) {
397	if (paused == isPaused()) {
398		return;
399	}
400	if (paused) {
401		addFrameAction([this]() {
402			mCoreThreadPauseFromThread(&m_threadContext);
403		});
404	} else {
405		mCoreThreadUnpause(&m_threadContext);
406	}
407}
408
409void CoreController::frameAdvance() {
410	addFrameAction([this]() {
411		mCoreThreadPauseFromThread(&m_threadContext);
412	});
413	setPaused(false);
414}
415
416void CoreController::addFrameAction(std::function<void ()> action) {
417	QMutexLocker locker(&m_actionMutex);
418	m_frameActions.append(action);
419}
420
421void CoreController::setSync(bool sync) {
422	if (sync) {
423		m_threadContext.impl->sync.audioWait = m_audioSync;
424		m_threadContext.impl->sync.videoFrameWait = m_videoSync;
425	} else {
426		m_threadContext.impl->sync.audioWait = false;
427		m_threadContext.impl->sync.videoFrameWait = false;
428	}
429}
430
431void CoreController::setRewinding(bool rewind) {
432	if (!m_threadContext.core->opts.rewindEnable) {
433		return;
434	}
435	if (rewind && m_multiplayer && m_multiplayer->attached() > 1) {
436		return;
437	}
438
439	if (rewind && isPaused()) {
440		setPaused(false);
441		// TODO: restore autopausing
442	}
443	mCoreThreadSetRewinding(&m_threadContext, rewind);
444}
445
446void CoreController::rewind(int states) {
447	{
448		Interrupter interrupter(this);
449		if (!states) {
450			states = INT_MAX;
451		}
452		for (int i = 0; i < states; ++i) {
453			if (!mCoreRewindRestore(&m_threadContext.impl->rewind, m_threadContext.core)) {
454				break;
455			}
456		}
457	}
458	emit frameAvailable();
459	emit rewound();
460}
461
462void CoreController::setFastForward(bool enable) {
463	if (m_fastForward == enable) {
464		return;
465	}
466	m_fastForward = enable;
467	updateFastForward();
468	emit fastForwardChanged(enable);
469}
470
471void CoreController::forceFastForward(bool enable) {
472	if (m_fastForwardForced == enable) {
473		return;
474	}
475	m_fastForwardForced = enable;
476	updateFastForward();
477	emit fastForwardChanged(enable || m_fastForward);
478}
479
480void CoreController::loadState(int slot) {
481	if (slot > 0 && slot != m_stateSlot) {
482		m_stateSlot = slot;
483		m_backupSaveState.clear();
484	}
485	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
486		CoreController* controller = static_cast<CoreController*>(context->userData);
487		if (!controller->m_backupLoadState.isOpen()) {
488			controller->m_backupLoadState = VFileMemChunk(nullptr, 0);
489		}
490		mCoreSaveStateNamed(context->core, controller->m_backupLoadState, controller->m_saveStateFlags);
491		if (mCoreLoadState(context->core, controller->m_stateSlot, controller->m_loadStateFlags)) {
492			emit controller->frameAvailable();
493			emit controller->stateLoaded();
494		}
495	});
496}
497
498void CoreController::loadState(const QString& path) {
499	m_statePath = path;
500	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
501		CoreController* controller = static_cast<CoreController*>(context->userData);
502		VFile* vf = VFileDevice::open(controller->m_statePath, O_RDONLY);
503		if (!vf) {
504			return;
505		}
506		if (!controller->m_backupLoadState.isOpen()) {
507			controller->m_backupLoadState = VFileMemChunk(nullptr, 0);
508		}
509		mCoreSaveStateNamed(context->core, controller->m_backupLoadState, controller->m_saveStateFlags);
510		if (mCoreLoadStateNamed(context->core, vf, controller->m_loadStateFlags)) {
511			emit controller->frameAvailable();
512			emit controller->stateLoaded();
513		}
514		vf->close(vf);
515	});
516}
517
518void CoreController::saveState(int slot) {
519	if (slot > 0) {
520		m_stateSlot = slot;
521	}
522	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
523		CoreController* controller = static_cast<CoreController*>(context->userData);
524		VFile* vf = mCoreGetState(context->core, controller->m_stateSlot, false);
525		if (vf) {
526			controller->m_backupSaveState.resize(vf->size(vf));
527			vf->read(vf, controller->m_backupSaveState.data(), controller->m_backupSaveState.size());
528			vf->close(vf);
529		}
530		mCoreSaveState(context->core, controller->m_stateSlot, controller->m_saveStateFlags);
531	});
532}
533
534void CoreController::saveState(const QString& path) {
535	m_statePath = path;
536	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
537		CoreController* controller = static_cast<CoreController*>(context->userData);
538		VFile* vf = VFileDevice::open(controller->m_statePath, O_RDONLY);
539		if (vf) {
540			controller->m_backupSaveState.resize(vf->size(vf));
541			vf->read(vf, controller->m_backupSaveState.data(), controller->m_backupSaveState.size());
542			vf->close(vf);
543		}
544		vf = VFileDevice::open(controller->m_statePath, O_WRONLY | O_CREAT | O_TRUNC);
545		if (!vf) {
546			return;
547		}
548		mCoreSaveStateNamed(context->core, vf, controller->m_saveStateFlags);
549		vf->close(vf);
550	});
551}
552
553void CoreController::loadBackupState() {
554	if (!m_backupLoadState.isOpen()) {
555		return;
556	}
557
558	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
559		CoreController* controller = static_cast<CoreController*>(context->userData);
560		controller->m_backupLoadState.seek(0);
561		if (mCoreLoadStateNamed(context->core, controller->m_backupLoadState, controller->m_loadStateFlags)) {
562			mLOG(STATUS, INFO, "Undid state load");
563			controller->frameAvailable();
564			controller->stateLoaded();
565		}
566		controller->m_backupLoadState.close();
567	});
568}
569
570void CoreController::saveBackupState() {
571	if (m_backupSaveState.isEmpty()) {
572		return;
573	}
574
575	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
576		CoreController* controller = static_cast<CoreController*>(context->userData);
577		VFile* vf = mCoreGetState(context->core, controller->m_stateSlot, true);
578		if (vf) {
579			vf->write(vf, controller->m_backupSaveState.constData(), controller->m_backupSaveState.size());
580			vf->close(vf);
581			mLOG(STATUS, INFO, "Undid state save");
582		}
583		controller->m_backupSaveState.clear();
584	});
585}
586
587void CoreController::loadSave(const QString& path, bool temporary) {
588	m_resetActions.append([this, path, temporary]() {
589		VFile* vf = VFileDevice::open(path, temporary ? O_RDONLY : O_RDWR);
590		if (!vf) {
591			LOG(QT, ERROR) << tr("Failed to open save file: %1").arg(path);
592			return;
593		}
594
595		if (temporary) {
596			m_threadContext.core->loadTemporarySave(m_threadContext.core, vf);
597		} else {
598			m_threadContext.core->loadSave(m_threadContext.core, vf);
599		}
600	});
601	reset();
602}
603
604void CoreController::loadPatch(const QString& patchPath) {
605	Interrupter interrupter(this);
606	VFile* patch = VFileDevice::open(patchPath, O_RDONLY);
607	if (patch) {
608		m_threadContext.core->loadPatch(m_threadContext.core, patch);
609		m_patched = true;
610		patch->close(patch);
611	}
612	if (mCoreThreadHasStarted(&m_threadContext)) {
613		reset();
614	}
615}
616
617void CoreController::replaceGame(const QString& path) {
618	QFileInfo info(path);
619	if (!info.isReadable()) {
620		LOG(QT, ERROR) << tr("Failed to open game file: %1").arg(path);
621		return;
622	}
623	QString fname = info.canonicalFilePath();
624	Interrupter interrupter(this);
625	mDirectorySetDetachBase(&m_threadContext.core->dirs);
626	mCoreLoadFile(m_threadContext.core, fname.toUtf8().constData());
627}
628
629void CoreController::yankPak() {
630#ifdef M_CORE_GBA
631	if (platform() != PLATFORM_GBA) {
632		return;
633	}
634	Interrupter interrupter(this);
635	GBAYankROM(static_cast<GBA*>(m_threadContext.core->board));
636#endif
637}
638
639void CoreController::addKey(int key) {
640	m_activeKeys |= 1 << key;
641}
642
643void CoreController::clearKey(int key) {
644	m_activeKeys &= ~(1 << key);
645}
646
647void CoreController::setAutofire(int key, bool enable) {
648	if (key >= 32 || key < 0) {
649		return;
650	}
651
652	m_autofire[key] = enable;
653	m_autofireStatus[key] = 0;
654}
655
656#ifdef USE_PNG
657void CoreController::screenshot() {
658	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
659		mCoreTakeScreenshot(context->core);
660	});
661}
662#endif
663
664void CoreController::setRealTime() {
665	m_threadContext.core->rtc.override = RTC_NO_OVERRIDE;
666}
667
668void CoreController::setFixedTime(const QDateTime& time) {
669	m_threadContext.core->rtc.override = RTC_FIXED;
670	m_threadContext.core->rtc.value = time.toMSecsSinceEpoch();
671}
672
673void CoreController::setFakeEpoch(const QDateTime& time) {
674	m_threadContext.core->rtc.override = RTC_FAKE_EPOCH;
675	m_threadContext.core->rtc.value = time.toMSecsSinceEpoch();
676}
677
678void CoreController::importSharkport(const QString& path) {
679#ifdef M_CORE_GBA
680	if (platform() != PLATFORM_GBA) {
681		return;
682	}
683	VFile* vf = VFileDevice::open(path, O_RDONLY);
684	if (!vf) {
685		LOG(QT, ERROR) << tr("Failed to open snapshot file for reading: %1").arg(path);
686		return;
687	}
688	Interrupter interrupter(this);
689	GBASavedataImportSharkPort(static_cast<GBA*>(m_threadContext.core->board), vf, false);
690	vf->close(vf);
691#endif
692}
693
694void CoreController::exportSharkport(const QString& path) {
695#ifdef M_CORE_GBA
696	if (platform() != PLATFORM_GBA) {
697		return;
698	}
699	VFile* vf = VFileDevice::open(path, O_WRONLY | O_CREAT | O_TRUNC);
700	if (!vf) {
701		LOG(QT, ERROR) << tr("Failed to open snapshot file for writing: %1").arg(path);
702		return;
703	}
704	Interrupter interrupter(this);
705	GBASavedataExportSharkPort(static_cast<GBA*>(m_threadContext.core->board), vf);
706	vf->close(vf);
707#endif
708}
709
710#ifdef M_CORE_GB
711void CoreController::attachPrinter() {
712	if (platform() != PLATFORM_GB) {
713		return;
714	}
715	GB* gb = static_cast<GB*>(m_threadContext.core->board);
716	clearMultiplayerController();
717	GBPrinterCreate(&m_printer.d);
718	m_printer.parent = this;
719	m_printer.d.print = [](GBPrinter* printer, int height, const uint8_t* data) {
720		QGBPrinter* qPrinter = reinterpret_cast<QGBPrinter*>(printer);
721		QImage image(GB_VIDEO_HORIZONTAL_PIXELS, height, QImage::Format_Indexed8);
722		QVector<QRgb> colors;
723		colors.append(qRgb(0xF8, 0xF8, 0xF8));
724		colors.append(qRgb(0xA8, 0xA8, 0xA8));
725		colors.append(qRgb(0x50, 0x50, 0x50));
726		colors.append(qRgb(0x00, 0x00, 0x00));
727		image.setColorTable(colors);
728		for (int y = 0; y < height; ++y) {
729			for (int x = 0; x < GB_VIDEO_HORIZONTAL_PIXELS; x += 4) {
730				uint8_t byte = data[(x + y * GB_VIDEO_HORIZONTAL_PIXELS) / 4];
731				image.setPixel(x + 0, y, (byte & 0xC0) >> 6);
732				image.setPixel(x + 1, y, (byte & 0x30) >> 4);
733				image.setPixel(x + 2, y, (byte & 0x0C) >> 2);
734				image.setPixel(x + 3, y, (byte & 0x03) >> 0);
735			}
736		}
737		QMetaObject::invokeMethod(qPrinter->parent, "imagePrinted", Q_ARG(const QImage&, image));
738	};
739	Interrupter interrupter(this);
740	GBSIOSetDriver(&gb->sio, &m_printer.d.d);
741}
742
743void CoreController::detachPrinter() {
744	if (platform() != PLATFORM_GB) {
745		return;
746	}
747	Interrupter interrupter(this);
748	GB* gb = static_cast<GB*>(m_threadContext.core->board);
749	GBPrinterDonePrinting(&m_printer.d);
750	GBSIOSetDriver(&gb->sio, nullptr);
751}
752
753void CoreController::endPrint() {
754	if (platform() != PLATFORM_GB) {
755		return;
756	}
757	Interrupter interrupter(this);
758	GBPrinterDonePrinting(&m_printer.d);
759}
760#endif
761
762#ifdef M_CORE_GBA
763void CoreController::attachBattleChipGate() {
764	if (platform() != PLATFORM_GBA) {
765		return;
766	}
767	Interrupter interrupter(this);
768	clearMultiplayerController();
769	GBASIOBattlechipGateCreate(&m_battlechip);
770	m_threadContext.core->setPeripheral(m_threadContext.core, mPERIPH_GBA_BATTLECHIP_GATE, &m_battlechip);
771}
772
773void CoreController::detachBattleChipGate() {
774	if (platform() != PLATFORM_GBA) {
775		return;
776	}
777	Interrupter interrupter(this);
778	m_threadContext.core->setPeripheral(m_threadContext.core, mPERIPH_GBA_BATTLECHIP_GATE, nullptr);
779}
780
781void CoreController::setBattleChipId(uint16_t id) {
782	if (platform() != PLATFORM_GBA) {
783		return;
784	}
785	Interrupter interrupter(this);
786	m_battlechip.chipId = id;
787}
788
789void CoreController::setBattleChipFlavor(int flavor) {
790	if (platform() != PLATFORM_GBA) {
791		return;
792	}
793	Interrupter interrupter(this);
794	m_battlechip.flavor = flavor;
795}
796#endif
797
798void CoreController::setAVStream(mAVStream* stream) {
799	Interrupter interrupter(this);
800	m_threadContext.core->setAVStream(m_threadContext.core, stream);
801}
802
803void CoreController::clearAVStream() {
804	Interrupter interrupter(this);
805	m_threadContext.core->setAVStream(m_threadContext.core, nullptr);
806}
807
808void CoreController::clearOverride() {
809	m_override.reset();
810}
811
812void CoreController::startVideoLog(const QString& path, bool compression) {
813	if (m_vl) {
814		return;
815	}
816
817	VFile* vf = VFileDevice::open(path, O_WRONLY | O_CREAT | O_TRUNC);
818	if (!vf) {
819		return;
820	}
821	startVideoLog(vf);
822}
823
824void CoreController::startVideoLog(VFile* vf, bool compression) {
825	if (m_vl || !vf) {
826		return;
827	}
828
829	Interrupter interrupter(this);
830	m_vl = mVideoLogContextCreate(m_threadContext.core);
831	m_vlVf = vf;
832	mVideoLogContextSetOutput(m_vl, m_vlVf);
833	mVideoLogContextSetCompression(m_vl, compression);
834	mVideoLogContextWriteHeader(m_vl, m_threadContext.core);
835}
836
837void CoreController::endVideoLog(bool closeVf) {
838	if (!m_vl) {
839		return;
840	}
841
842	Interrupter interrupter(this);
843	mVideoLogContextDestroy(m_threadContext.core, m_vl);
844	if (m_vlVf && closeVf) {
845		m_vlVf->close(m_vlVf);
846		m_vlVf = nullptr;
847	}
848	m_vl = nullptr;
849}
850
851void CoreController::setFramebufferHandle(int fb) {
852	Interrupter interrupter(this);
853	if (fb < 0) {
854		m_hwaccel = false;
855	} else {
856		m_threadContext.core->setVideoGLTex(m_threadContext.core, fb);
857		m_hwaccel = true;
858	}
859}
860
861void CoreController::updateKeys() {
862	int activeKeys = m_activeKeys | updateAutofire() | m_inputController->pollEvents();
863	m_threadContext.core->setKeys(m_threadContext.core, activeKeys);
864}
865
866int CoreController::updateAutofire() {
867	int active = 0;
868	for (int k = 0; k < 32; ++k) {
869		if (!m_autofire[k]) {
870			continue;
871		}
872		++m_autofireStatus[k];
873		if (m_autofireStatus[k] >= 2 * m_autofireThreshold) {
874			m_autofireStatus[k] = 0;
875		} else if (m_autofireStatus[k] >= m_autofireThreshold) {
876			active |= 1 << k;
877		}
878	}
879	return active;
880}
881
882void CoreController::finishFrame() {
883	if (!m_hwaccel) {
884		unsigned width, height;
885		m_threadContext.core->desiredVideoDimensions(m_threadContext.core, &width, &height);
886
887		QMutexLocker locker(&m_bufferMutex);
888		memcpy(m_completeBuffer.data(), m_activeBuffer.constData(), 256 * height * BYTES_PER_PIXEL);
889	}
890
891	QMutexLocker locker(&m_actionMutex);
892	QList<std::function<void ()>> frameActions(m_frameActions);
893	m_frameActions.clear();
894	for (auto& action : frameActions) {
895		action();
896	}
897	updateKeys();
898
899	QMetaObject::invokeMethod(this, "frameAvailable");
900}
901
902void CoreController::updateFastForward() {
903	if (m_fastForward || m_fastForwardForced) {
904		if (m_fastForwardVolume >= 0) {
905			m_threadContext.core->opts.volume = m_fastForwardVolume;
906		}
907		if (m_fastForwardMute >= 0) {
908			m_threadContext.core->opts.mute = m_fastForwardMute;
909		}
910		if (m_fastForwardRatio > 0) {
911			m_threadContext.impl->sync.fpsTarget = m_fpsTarget * m_fastForwardRatio;
912		} else {
913			setSync(false);
914		}
915	} else {
916		if (!mCoreConfigGetIntValue(&m_threadContext.core->config, "volume", &m_threadContext.core->opts.volume)) {
917			m_threadContext.core->opts.volume = 0x100;
918		}
919		int fakeBool = 0;
920		mCoreConfigGetIntValue(&m_threadContext.core->config, "mute", &fakeBool);
921		m_threadContext.core->opts.mute = fakeBool;
922		m_threadContext.impl->sync.fpsTarget = m_fpsTarget;
923		setSync(true);
924	}
925	// XXX: Have a way of just updating volume
926	switch (platform()) {
927#ifdef M_CORE_GBA
928	case PLATFORM_GBA: {
929		GBA* gba = static_cast<GBA*>(m_threadContext.core->board);
930		if (m_threadContext.core->opts.mute) {
931			gba->audio.masterVolume = 0;
932		} else {
933			gba->audio.masterVolume = m_threadContext.core->opts.volume;
934		}
935		break;
936	}
937#endif
938#ifdef M_CORE_GB
939	case PLATFORM_GB: {
940		GB* gb = static_cast<GB*>(m_threadContext.core->board);
941		if (m_threadContext.core->opts.mute) {
942			gb->audio.masterVolume = 0;
943		} else {
944			gb->audio.masterVolume = m_threadContext.core->opts.volume;
945		}
946		break;
947	}
948#endif
949	default:
950		break;
951	}
952}
953
954CoreController::Interrupter::Interrupter(CoreController* parent, bool fromThread)
955	: m_parent(parent)
956{
957	if (!m_parent->thread()->impl) {
958		return;
959	}
960	if (!fromThread) {
961		mCoreThreadInterrupt(m_parent->thread());
962	} else {
963		mCoreThreadInterruptFromThread(m_parent->thread());
964	}
965}
966
967CoreController::Interrupter::Interrupter(std::shared_ptr<CoreController> parent, bool fromThread)
968	: m_parent(parent.get())
969{
970	if (!m_parent->thread()->impl) {
971		return;
972	}
973	if (!fromThread) {
974		mCoreThreadInterrupt(m_parent->thread());
975	} else {
976		mCoreThreadInterruptFromThread(m_parent->thread());
977	}
978}
979
980CoreController::Interrupter::Interrupter(const Interrupter& other)
981	: m_parent(other.m_parent)
982{
983	if (!m_parent->thread()->impl) {
984		return;
985	}
986	mCoreThreadInterrupt(m_parent->thread());
987}
988
989CoreController::Interrupter::~Interrupter() {
990	if (!m_parent->thread()->impl) {
991		return;
992	}
993	mCoreThreadContinue(m_parent->thread());
994}