all repos — mgba @ 1a749240239d58eab801825eb5d43be19290b90d

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