all repos — mgba @ 8d9d644dfefa94686a16dd09b3b931eeabc907d8

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
 31using namespace QGBA;
 32
 33
 34CoreController::CoreController(mCore* core, QObject* parent)
 35	: QObject(parent)
 36	, m_saveStateFlags(SAVESTATE_SCREENSHOT | SAVESTATE_SAVEDATA | SAVESTATE_CHEATS | SAVESTATE_RTC)
 37	, m_loadStateFlags(SAVESTATE_SCREENSHOT | SAVESTATE_RTC)
 38{
 39	m_threadContext.core = core;
 40	m_threadContext.userData = this;
 41
 42	QSize size(256, 512);
 43	m_buffers[0].resize(size.width() * size.height() * sizeof(color_t));
 44	m_buffers[1].resize(size.width() * size.height() * sizeof(color_t));
 45	m_buffers[0].fill(0xFF);
 46	m_buffers[1].fill(0xFF);
 47	m_activeBuffer = &m_buffers[0];
 48
 49	m_threadContext.core->setVideoBuffer(m_threadContext.core, reinterpret_cast<color_t*>(m_activeBuffer->data()), size.width());
 50
 51	m_threadContext.startCallback = [](mCoreThread* context) {
 52		CoreController* controller = static_cast<CoreController*>(context->userData);
 53
 54		switch (context->core->platform(context->core)) {
 55#ifdef M_CORE_GBA
 56		case PLATFORM_GBA:
 57			context->core->setPeripheral(context->core, mPERIPH_GBA_LUMINANCE, controller->m_inputController->luminance());
 58			break;
 59#endif
 60		default:
 61			break;
 62		}
 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		if (mCoreLoadState(context->core, 0, controller->m_loadStateFlags)) {
 83			mCoreDeleteState(context->core, 0);
 84		}
 85
 86		controller->m_resetActions.clear();
 87
 88		QSize size = controller->screenDimensions();
 89		controller->m_buffers[0].resize(size.width() * size.height() * sizeof(color_t));
 90		controller->m_buffers[1].resize(size.width() * size.height() * sizeof(color_t));
 91		controller->m_buffers[0].fill(0xFF);
 92		controller->m_buffers[1].fill(0xFF);
 93		controller->m_activeBuffer = &controller->m_buffers[0];
 94
 95		context->core->setVideoBuffer(context->core, reinterpret_cast<color_t*>(controller->m_activeBuffer->data()), size.width());
 96
 97		controller->finishFrame();
 98	};
 99
100	m_threadContext.frameCallback = [](mCoreThread* context) {
101		CoreController* controller = static_cast<CoreController*>(context->userData);
102
103		controller->finishFrame();
104	};
105
106	m_threadContext.cleanCallback = [](mCoreThread* context) {
107		CoreController* controller = static_cast<CoreController*>(context->userData);
108
109		controller->clearMultiplayerController();
110		QMetaObject::invokeMethod(controller, "stopping");
111	};
112
113	m_threadContext.pauseCallback = [](mCoreThread* context) {
114		CoreController* controller = static_cast<CoreController*>(context->userData);
115
116		QMetaObject::invokeMethod(controller, "paused");
117	};
118
119	m_threadContext.unpauseCallback = [](mCoreThread* context) {
120		CoreController* controller = static_cast<CoreController*>(context->userData);
121
122		QMetaObject::invokeMethod(controller, "unpaused");
123	};
124
125	m_threadContext.logger.d.log = [](mLogger* logger, int category, enum mLogLevel level, const char* format, va_list args) {
126		mThreadLogger* logContext = reinterpret_cast<mThreadLogger*>(logger);
127		mCoreThread* context = logContext->p;
128
129		static const char* savestateMessage = "State %i loaded";
130		static const char* savestateFailedMessage = "State %i failed to load";
131		static int biosCat = -1;
132		static int statusCat = -1;
133		if (!context) {
134			return;
135		}
136		CoreController* controller = static_cast<CoreController*>(context->userData);
137		QString message;
138		if (biosCat < 0) {
139			biosCat = mLogCategoryById("gba.bios");
140		}
141		if (statusCat < 0) {
142			statusCat = mLogCategoryById("core.status");
143		}
144#ifdef M_CORE_GBA
145		if (level == mLOG_STUB && category == biosCat) {
146			va_list argc;
147			va_copy(argc, args);
148			int immediate = va_arg(argc, int);
149			va_end(argc);
150			QMetaObject::invokeMethod(controller, "unimplementedBiosCall", Q_ARG(int, immediate));
151		} else
152#endif
153		if (category == statusCat) {
154			// Slot 0 is reserved for suspend points
155			if (strncmp(savestateMessage, format, strlen(savestateMessage)) == 0) {
156				va_list argc;
157				va_copy(argc, args);
158				int slot = va_arg(argc, int);
159				va_end(argc);
160				if (slot == 0) {
161					format = "Loaded suspend state";
162				}
163			} else if (strncmp(savestateFailedMessage, format, strlen(savestateFailedMessage)) == 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					return;
170				}
171			}
172			message = QString().vsprintf(format, args);
173			QMetaObject::invokeMethod(controller, "statusPosted", Q_ARG(const QString&, message));
174		}
175		if (level == mLOG_FATAL) {
176			mCoreThreadMarkCrashed(controller->thread());
177			QMetaObject::invokeMethod(controller, "crashed", Q_ARG(const QString&, QString().vsprintf(format, args)));
178		}
179		message = QString().vsprintf(format, args);
180		QMetaObject::invokeMethod(controller, "logPosted", Q_ARG(int, level), Q_ARG(int, category), Q_ARG(const QString&, message));
181	};
182}
183
184CoreController::~CoreController() {
185	endVideoLog();
186	stop();
187	disconnect();
188
189	if (m_cacheSet) {
190		mCacheSetDeinit(m_cacheSet.get());
191		m_cacheSet.reset();
192	}
193
194	mCoreThreadJoin(&m_threadContext);
195
196	mCoreConfigDeinit(&m_threadContext.core->config);
197	m_threadContext.core->deinit(m_threadContext.core);
198}
199
200color_t* CoreController::drawContext() {
201	QMutexLocker locker(&m_mutex);
202	if (!m_completeBuffer) {
203		return nullptr;
204	}
205	return reinterpret_cast<color_t*>(m_completeBuffer->data());
206}
207
208bool CoreController::isPaused() {
209	return mCoreThreadIsPaused(&m_threadContext);
210}
211
212mPlatform CoreController::platform() const {
213	return m_threadContext.core->platform(m_threadContext.core);
214}
215
216QSize CoreController::screenDimensions() const {
217	unsigned width, height;
218	m_threadContext.core->desiredVideoDimensions(m_threadContext.core, &width, &height);
219
220	return QSize(width, height);
221}
222
223void CoreController::loadConfig(ConfigController* config) {
224	Interrupter interrupter(this);
225	m_loadStateFlags = config->getOption("loadStateExtdata", m_loadStateFlags).toInt();
226	m_saveStateFlags = config->getOption("saveStateExtdata", m_saveStateFlags).toInt();
227	m_fastForwardRatio = config->getOption("fastForwardRatio", m_fastForwardRatio).toFloat();
228	m_videoSync = config->getOption("videoSync", m_videoSync).toInt();
229	m_audioSync = config->getOption("audioSync", m_audioSync).toInt();
230	m_fpsTarget = config->getOption("fpsTarget").toFloat();
231	m_autofireThreshold = config->getOption("autofireThreshold", m_autofireThreshold).toInt();
232	updateFastForward();
233	mCoreLoadForeignConfig(m_threadContext.core, config->config());
234	mCoreThreadRewindParamsChanged(&m_threadContext);
235}
236
237#ifdef USE_DEBUGGERS
238void CoreController::setDebugger(mDebugger* debugger) {
239	Interrupter interrupter(this);
240	if (debugger) {
241		mDebuggerAttach(debugger, m_threadContext.core);
242	} else {
243		m_threadContext.core->detachDebugger(m_threadContext.core);
244	}
245}
246#endif
247
248void CoreController::setMultiplayerController(MultiplayerController* controller) {
249	if (controller == m_multiplayer) {
250		return;
251	}
252	clearMultiplayerController();
253	m_multiplayer = controller;
254	if (!mCoreThreadHasStarted(&m_threadContext)) {
255		return;
256	}
257	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* thread) {
258		CoreController* controller = static_cast<CoreController*>(thread->userData);
259		controller->m_multiplayer->attachGame(controller);
260	});
261}
262
263void CoreController::clearMultiplayerController() {
264	if (!m_multiplayer) {
265		return;
266	}
267	m_multiplayer->detachGame(this);
268	m_multiplayer = nullptr;
269}
270
271mCacheSet* CoreController::graphicCaches() {
272	if (m_cacheSet) {
273		return m_cacheSet.get();
274	}
275	Interrupter interrupter(this);
276	switch (platform()) {
277#ifdef M_CORE_GBA
278	case PLATFORM_GBA: {
279		GBA* gba = static_cast<GBA*>(m_threadContext.core->board);
280		m_cacheSet = std::make_unique<mCacheSet>();
281		GBAVideoCacheInit(m_cacheSet.get());
282		GBAVideoCacheAssociate(m_cacheSet.get(), &gba->video);
283		break;
284	}
285#endif
286#ifdef M_CORE_GB
287	case PLATFORM_GB: {
288		GB* gb = static_cast<GB*>(m_threadContext.core->board);
289		m_cacheSet = std::make_unique<mCacheSet>();
290		GBVideoCacheInit(m_cacheSet.get());
291		GBVideoCacheAssociate(m_cacheSet.get(), &gb->video);
292		break;
293	}
294#endif
295	default:
296		return nullptr;
297	}
298	return m_cacheSet.get();
299}
300
301void CoreController::setOverride(std::unique_ptr<Override> override) {
302	Interrupter interrupter(this);
303	m_override = std::move(override);
304	m_override->identify(m_threadContext.core);
305}
306
307void CoreController::setInputController(InputController* inputController) {
308	m_inputController = inputController;
309	m_threadContext.core->setPeripheral(m_threadContext.core, mPERIPH_ROTATION, m_inputController->rotationSource());
310	m_threadContext.core->setPeripheral(m_threadContext.core, mPERIPH_RUMBLE, m_inputController->rumble());
311	m_threadContext.core->setPeripheral(m_threadContext.core, mPERIPH_IMAGE_SOURCE, m_inputController->imageSource());
312}
313
314void CoreController::setLogger(LogController* logger) {
315	disconnect(m_log);
316	m_log = logger;
317	m_threadContext.logger.d.filter = logger->filter();
318	connect(this, &CoreController::logPosted, m_log, &LogController::postLog);
319}
320
321void CoreController::start() {
322	if (!m_patched) {
323		mCoreAutoloadPatch(m_threadContext.core);
324	}
325	if (!mCoreThreadStart(&m_threadContext)) {
326		emit failed();
327		emit stopping();
328	}
329}
330
331void CoreController::stop() {
332#ifdef USE_DEBUGGERS
333	setDebugger(nullptr);
334#endif
335	setPaused(false);
336	mCoreThreadEnd(&m_threadContext);
337	emit stopping();
338}
339
340void CoreController::reset() {
341	bool wasPaused = isPaused();
342	setPaused(false);
343	Interrupter interrupter(this);
344	mCoreThreadReset(&m_threadContext);
345	if (wasPaused) {
346		setPaused(true);
347	}
348}
349
350void CoreController::setPaused(bool paused) {
351	if (paused == isPaused()) {
352		return;
353	}
354	if (paused) {
355		QMutexLocker locker(&m_mutex);
356		m_frameActions.append([this]() {
357			mCoreThreadPauseFromThread(&m_threadContext);
358		});
359	} else {
360		mCoreThreadUnpause(&m_threadContext);
361	}
362}
363
364void CoreController::frameAdvance() {
365	QMutexLocker locker(&m_mutex);
366	m_frameActions.append([this]() {
367		mCoreThreadPauseFromThread(&m_threadContext);
368	});
369	setPaused(false);
370}
371
372void CoreController::setSync(bool sync) {
373	if (sync) {
374		m_threadContext.impl->sync.audioWait = m_audioSync;
375		m_threadContext.impl->sync.videoFrameWait = m_videoSync;
376	} else {
377		m_threadContext.impl->sync.audioWait = false;
378		m_threadContext.impl->sync.videoFrameWait = false;
379	}
380}
381
382void CoreController::setRewinding(bool rewind) {
383	if (!m_threadContext.core->opts.rewindEnable) {
384		return;
385	}
386	if (rewind && m_multiplayer && m_multiplayer->attached() > 1) {
387		return;
388	}
389
390	if (rewind && isPaused()) {
391		setPaused(false);
392		// TODO: restore autopausing
393	}
394	mCoreThreadSetRewinding(&m_threadContext, rewind);
395}
396
397void CoreController::rewind(int states) {
398	{
399		Interrupter interrupter(this);
400		if (!states) {
401			states = INT_MAX;
402		}
403		for (int i = 0; i < states; ++i) {
404			if (!mCoreRewindRestore(&m_threadContext.impl->rewind, m_threadContext.core)) {
405				break;
406			}
407		}
408	}
409	emit frameAvailable();
410	emit rewound();
411}
412
413void CoreController::setFastForward(bool enable) {
414	m_fastForward = enable;
415	updateFastForward();
416}
417
418void CoreController::forceFastForward(bool enable) {
419	m_fastForwardForced = enable;
420	updateFastForward();
421}
422
423void CoreController::loadState(int slot) {
424	if (slot > 0 && slot != m_stateSlot) {
425		m_stateSlot = slot;
426		m_backupSaveState.clear();
427	}
428	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
429		CoreController* controller = static_cast<CoreController*>(context->userData);
430		if (!controller->m_backupLoadState.isOpen()) {
431			controller->m_backupLoadState = VFileMemChunk(nullptr, 0);
432		}
433		mCoreSaveStateNamed(context->core, controller->m_backupLoadState, controller->m_saveStateFlags);
434		if (mCoreLoadState(context->core, controller->m_stateSlot, controller->m_loadStateFlags)) {
435			emit controller->frameAvailable();
436			emit controller->stateLoaded();
437		}
438	});
439}
440
441void CoreController::saveState(int slot) {
442	if (slot > 0) {
443		m_stateSlot = slot;
444	}
445	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
446		CoreController* controller = static_cast<CoreController*>(context->userData);
447		VFile* vf = mCoreGetState(context->core, controller->m_stateSlot, false);
448		if (vf) {
449			controller->m_backupSaveState.resize(vf->size(vf));
450			vf->read(vf, controller->m_backupSaveState.data(), controller->m_backupSaveState.size());
451			vf->close(vf);
452		}
453		mCoreSaveState(context->core, controller->m_stateSlot, controller->m_saveStateFlags);
454	});
455}
456
457void CoreController::loadBackupState() {
458	if (!m_backupLoadState.isOpen()) {
459		return;
460	}
461
462	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
463		CoreController* controller = static_cast<CoreController*>(context->userData);
464		controller->m_backupLoadState.seek(0);
465		if (mCoreLoadStateNamed(context->core, controller->m_backupLoadState, controller->m_loadStateFlags)) {
466			mLOG(STATUS, INFO, "Undid state load");
467			controller->frameAvailable();
468			controller->stateLoaded();
469		}
470		controller->m_backupLoadState.close();
471	});
472}
473
474void CoreController::saveBackupState() {
475	if (m_backupSaveState.isEmpty()) {
476		return;
477	}
478
479	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
480		CoreController* controller = static_cast<CoreController*>(context->userData);
481		VFile* vf = mCoreGetState(context->core, controller->m_stateSlot, true);
482		if (vf) {
483			vf->write(vf, controller->m_backupSaveState.constData(), controller->m_backupSaveState.size());
484			vf->close(vf);
485			mLOG(STATUS, INFO, "Undid state save");
486		}
487		controller->m_backupSaveState.clear();
488	});
489}
490
491void CoreController::loadSave(const QString& path, bool temporary) {
492	m_resetActions.append([this, path, temporary]() {
493		VFile* vf = VFileDevice::open(path, temporary ? O_RDONLY : O_RDWR);
494		if (!vf) {
495			LOG(QT, ERROR) << tr("Failed to open save file: %1").arg(path);
496			return;
497		}
498
499		if (temporary) {
500			m_threadContext.core->loadTemporarySave(m_threadContext.core, vf);
501		} else {
502			m_threadContext.core->loadSave(m_threadContext.core, vf);
503		}
504	});
505	reset();
506}
507
508void CoreController::loadPatch(const QString& patchPath) {
509	Interrupter interrupter(this);
510	VFile* patch = VFileDevice::open(patchPath, O_RDONLY);
511	if (patch) {
512		m_threadContext.core->loadPatch(m_threadContext.core, patch);
513		m_patched = true;
514	}
515	patch->close(patch);
516	if (mCoreThreadHasStarted(&m_threadContext)) {
517		reset();
518	}
519}
520
521void CoreController::replaceGame(const QString& path) {
522	QFileInfo info(path);
523	if (!info.isReadable()) {
524		LOG(QT, ERROR) << tr("Failed to open game file: %1").arg(path);
525		return;
526	}
527	QString fname = info.canonicalFilePath();
528	Interrupter interrupter(this);
529	mDirectorySetDetachBase(&m_threadContext.core->dirs);
530	mCoreLoadFile(m_threadContext.core, fname.toLocal8Bit().constData());
531}
532
533void CoreController::yankPak() {
534#ifdef M_CORE_GBA
535	if (platform() != PLATFORM_GBA) {
536		return;
537	}
538	Interrupter interrupter(this);
539	GBAYankROM(static_cast<GBA*>(m_threadContext.core->board));
540#endif
541}
542
543void CoreController::addKey(int key) {
544	m_activeKeys |= 1 << key;
545}
546
547void CoreController::clearKey(int key) {
548	m_activeKeys &= ~(1 << key);
549}
550
551void CoreController::setAutofire(int key, bool enable) {
552	if (key >= 32 || key < 0) {
553		return;
554	}
555
556	m_autofire[key] = enable;
557	m_autofireStatus[key] = 0;
558}
559
560#ifdef USE_PNG
561void CoreController::screenshot() {
562	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
563		mCoreTakeScreenshot(context->core);
564	});
565}
566#endif
567
568void CoreController::setRealTime() {
569	m_threadContext.core->rtc.override = RTC_NO_OVERRIDE;
570}
571
572void CoreController::setFixedTime(const QDateTime& time) {
573	m_threadContext.core->rtc.override = RTC_FIXED;
574	m_threadContext.core->rtc.value = time.toMSecsSinceEpoch();
575}
576
577void CoreController::setFakeEpoch(const QDateTime& time) {
578	m_threadContext.core->rtc.override = RTC_FAKE_EPOCH;
579	m_threadContext.core->rtc.value = time.toMSecsSinceEpoch();
580}
581
582void CoreController::importSharkport(const QString& path) {
583#ifdef M_CORE_GBA
584	if (platform() != PLATFORM_GBA) {
585		return;
586	}
587	VFile* vf = VFileDevice::open(path, O_RDONLY);
588	if (!vf) {
589		LOG(QT, ERROR) << tr("Failed to open snapshot file for reading: %1").arg(path);
590		return;
591	}
592	Interrupter interrupter(this);
593	GBASavedataImportSharkPort(static_cast<GBA*>(m_threadContext.core->board), vf, false);
594	vf->close(vf);
595#endif
596}
597
598void CoreController::exportSharkport(const QString& path) {
599#ifdef M_CORE_GBA
600	if (platform() != PLATFORM_GBA) {
601		return;
602	}
603	VFile* vf = VFileDevice::open(path, O_WRONLY | O_CREAT | O_TRUNC);
604	if (!vf) {
605		LOG(QT, ERROR) << tr("Failed to open snapshot file for writing: %1").arg(path);
606		return;
607	}
608	Interrupter interrupter(this);
609	GBASavedataExportSharkPort(static_cast<GBA*>(m_threadContext.core->board), vf);
610	vf->close(vf);
611#endif
612}
613
614void CoreController::attachPrinter() {
615#ifdef M_CORE_GB
616	if (platform() != PLATFORM_GB) {
617		return;
618	}
619	GB* gb = static_cast<GB*>(m_threadContext.core->board);
620	clearMultiplayerController();
621	GBPrinterCreate(&m_printer.d);
622	m_printer.parent = this;
623	m_printer.d.print = [](GBPrinter* printer, int height, const uint8_t* data) {
624		QGBPrinter* qPrinter = reinterpret_cast<QGBPrinter*>(printer);
625		QImage image(GB_VIDEO_HORIZONTAL_PIXELS, height, QImage::Format_Indexed8);
626		QVector<QRgb> colors;
627		colors.append(qRgb(0xF8, 0xF8, 0xF8));
628		colors.append(qRgb(0xA8, 0xA8, 0xA8));
629		colors.append(qRgb(0x50, 0x50, 0x50));
630		colors.append(qRgb(0x00, 0x00, 0x00));
631		image.setColorTable(colors);
632		for (int y = 0; y < height; ++y) {
633			for (int x = 0; x < GB_VIDEO_HORIZONTAL_PIXELS; x += 4) {
634				uint8_t byte = data[(x + y * GB_VIDEO_HORIZONTAL_PIXELS) / 4];
635				image.setPixel(x + 0, y, (byte & 0xC0) >> 6);
636				image.setPixel(x + 1, y, (byte & 0x30) >> 4);
637				image.setPixel(x + 2, y, (byte & 0x0C) >> 2);
638				image.setPixel(x + 3, y, (byte & 0x03) >> 0);
639			}
640		}
641		QMetaObject::invokeMethod(qPrinter->parent, "imagePrinted", Q_ARG(const QImage&, image));
642	};
643	GBSIOSetDriver(&gb->sio, &m_printer.d.d);
644#endif
645}
646
647void CoreController::detachPrinter() {
648#ifdef M_CORE_GB
649	if (platform() != PLATFORM_GB) {
650		return;
651	}
652	GB* gb = static_cast<GB*>(m_threadContext.core->board);
653	GBPrinterDonePrinting(&m_printer.d);
654	GBSIOSetDriver(&gb->sio, nullptr);
655#endif
656}
657
658void CoreController::endPrint() {
659#ifdef M_CORE_GB
660	if (platform() != PLATFORM_GB) {
661		return;
662	}
663	GBPrinterDonePrinting(&m_printer.d);
664#endif
665}
666
667void CoreController::setAVStream(mAVStream* stream) {
668	Interrupter interrupter(this);
669	m_threadContext.core->setAVStream(m_threadContext.core, stream);
670}
671
672void CoreController::clearAVStream() {
673	Interrupter interrupter(this);
674	m_threadContext.core->setAVStream(m_threadContext.core, nullptr);
675}
676
677void CoreController::clearOverride() {
678	m_override.reset();
679}
680
681void CoreController::startVideoLog(const QString& path) {
682	if (m_vl) {
683		return;
684	}
685
686	Interrupter interrupter(this);
687	m_vl = mVideoLogContextCreate(m_threadContext.core);
688	m_vlVf = VFileDevice::open(path, O_WRONLY | O_CREAT | O_TRUNC);
689	mVideoLogContextSetOutput(m_vl, m_vlVf);
690	mVideoLogContextWriteHeader(m_vl, m_threadContext.core);
691}
692
693void CoreController::endVideoLog() {
694	if (!m_vl) {
695		return;
696	}
697
698	Interrupter interrupter(this);
699	mVideoLogContextDestroy(m_threadContext.core, m_vl);
700	if (m_vlVf) {
701		m_vlVf->close(m_vlVf);
702		m_vlVf = nullptr;
703	}
704	m_vl = nullptr;
705}
706
707void CoreController::updateKeys() {
708	int activeKeys = m_activeKeys | updateAutofire() | m_inputController->pollEvents();
709	m_threadContext.core->setKeys(m_threadContext.core, activeKeys);
710}
711
712int CoreController::updateAutofire() {
713	int active = 0;
714	for (int k = 0; k < 32; ++k) {
715		if (!m_autofire[k]) {
716			continue;
717		}
718		++m_autofireStatus[k];
719		if (m_autofireStatus[k] >= 2 * m_autofireThreshold) {
720			m_autofireStatus[k] = 0;
721		} else if (m_autofireStatus[k] >= m_autofireThreshold) {
722			active |= 1 << k;
723		}
724	}
725	return active;
726}
727
728void CoreController::finishFrame() {
729	QMutexLocker locker(&m_mutex);
730	m_completeBuffer = m_activeBuffer;
731
732	// TODO: Generalize this to triple buffering?
733	m_activeBuffer = &m_buffers[0];
734	if (m_activeBuffer == m_completeBuffer) {
735		m_activeBuffer = &m_buffers[1];
736	}
737	// Copy contents to avoid issues when doing frameskip
738	*m_activeBuffer = *m_completeBuffer;
739	m_threadContext.core->setVideoBuffer(m_threadContext.core, reinterpret_cast<color_t*>(m_activeBuffer->data()), screenDimensions().width());
740
741	for (auto& action : m_frameActions) {
742		action();
743	}
744	m_frameActions.clear();
745	updateKeys();
746
747	QMetaObject::invokeMethod(this, "frameAvailable");
748}
749
750void CoreController::updateFastForward() {
751	if (m_fastForward || m_fastForwardForced) {
752		if (m_fastForwardRatio > 0) {
753			m_threadContext.impl->sync.fpsTarget = m_fpsTarget * m_fastForwardRatio;
754		} else {
755			setSync(false);
756		}
757	} else {
758		m_threadContext.impl->sync.fpsTarget = m_fpsTarget;
759		setSync(true);
760	}
761}
762
763CoreController::Interrupter::Interrupter(CoreController* parent, bool fromThread)
764	: m_parent(parent)
765{
766	if (!m_parent->thread()->impl) {
767		return;
768	}
769	if (!fromThread) {
770		mCoreThreadInterrupt(m_parent->thread());
771	} else {
772		mCoreThreadInterruptFromThread(m_parent->thread());
773	}
774}
775
776CoreController::Interrupter::Interrupter(std::shared_ptr<CoreController> parent, bool fromThread)
777	: m_parent(parent.get())
778{
779	if (!m_parent->thread()->impl) {
780		return;
781	}
782	if (!fromThread) {
783		mCoreThreadInterrupt(m_parent->thread());
784	} else {
785		mCoreThreadInterruptFromThread(m_parent->thread());
786	}
787}
788
789CoreController::Interrupter::Interrupter(const Interrupter& other)
790	: m_parent(other.m_parent)
791{
792	if (!m_parent->thread()->impl) {
793		return;
794	}
795	mCoreThreadInterrupt(m_parent->thread());
796}
797
798CoreController::Interrupter::~Interrupter() {
799	if (!m_parent->thread()->impl) {
800		return;
801	}
802	mCoreThreadContinue(m_parent->thread());
803}