all repos — mgba @ a714774a2598c043c3c4183ed2825fe8cbc1b748

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 (controller->m_multiplayer) {
 70			controller->m_multiplayer->attachGame(controller);
 71		}
 72
 73		QMetaObject::invokeMethod(controller, "started");
 74	};
 75
 76	m_threadContext.resetCallback = [](mCoreThread* context) {
 77		CoreController* controller = static_cast<CoreController*>(context->userData);
 78		for (auto action : controller->m_resetActions) {
 79			action();
 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(toPow2(size.width()) * size.height() * sizeof(color_t));
 90		controller->m_buffers[1].resize(toPow2(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()), toPow2(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_tileCache) {
190		mTileCacheDeinit(m_tileCache.get());
191		m_tileCache.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
271mTileCache* CoreController::tileCache() {
272	if (m_tileCache) {
273		return m_tileCache.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_tileCache = std::make_unique<mTileCache>();
281		GBAVideoTileCacheInit(m_tileCache.get());
282		GBAVideoTileCacheAssociate(m_tileCache.get(), &gba->video);
283		mTileCacheSetPalette(m_tileCache.get(), 0);
284		break;
285	}
286#endif
287#ifdef M_CORE_GB
288	case PLATFORM_GB: {
289		GB* gb = static_cast<GB*>(m_threadContext.core->board);
290		m_tileCache = std::make_unique<mTileCache>();
291		GBVideoTileCacheInit(m_tileCache.get());
292		GBVideoTileCacheAssociate(m_tileCache.get(), &gb->video);
293		mTileCacheSetPalette(m_tileCache.get(), 0);
294		break;
295	}
296#endif
297	default:
298		return nullptr;
299	}
300	return m_tileCache.get();
301}
302
303void CoreController::setOverride(std::unique_ptr<Override> override) {
304	Interrupter interrupter(this);
305	m_override = std::move(override);
306	m_override->identify(m_threadContext.core);
307}
308
309void CoreController::setInputController(InputController* inputController) {
310	m_inputController = inputController;
311	m_threadContext.core->setPeripheral(m_threadContext.core, mPERIPH_ROTATION, m_inputController->rotationSource());
312	m_threadContext.core->setPeripheral(m_threadContext.core, mPERIPH_RUMBLE, m_inputController->rumble());
313	m_threadContext.core->setPeripheral(m_threadContext.core, mPERIPH_IMAGE_SOURCE, m_inputController->imageSource());
314}
315
316void CoreController::setLogger(LogController* logger) {
317	disconnect(m_log);
318	m_log = logger;
319	m_threadContext.logger.d.filter = logger->filter();
320	connect(this, &CoreController::logPosted, m_log, &LogController::postLog);
321}
322
323void CoreController::start() {
324	if (!m_patched) {
325		mCoreAutoloadPatch(m_threadContext.core);
326	}
327	if (!mCoreThreadStart(&m_threadContext)) {
328		emit failed();
329		emit stopping();
330	}
331}
332
333void CoreController::stop() {
334#ifdef USE_DEBUGGERS
335	setDebugger(nullptr);
336#endif
337	setPaused(false);
338	mCoreThreadEnd(&m_threadContext);
339	emit stopping();
340}
341
342void CoreController::reset() {
343	bool wasPaused = isPaused();
344	setPaused(false);
345	Interrupter interrupter(this);
346	mCoreThreadReset(&m_threadContext);
347	if (wasPaused) {
348		setPaused(true);
349	}
350}
351
352void CoreController::setPaused(bool paused) {
353	if (paused == isPaused()) {
354		return;
355	}
356	if (paused) {
357		QMutexLocker locker(&m_mutex);
358		m_frameActions.append([this]() {
359			mCoreThreadPauseFromThread(&m_threadContext);
360		});
361	} else {
362		mCoreThreadUnpause(&m_threadContext);
363	}
364}
365
366void CoreController::frameAdvance() {
367	QMutexLocker locker(&m_mutex);
368	m_frameActions.append([this]() {
369		mCoreThreadPauseFromThread(&m_threadContext);
370	});
371	setPaused(false);
372}
373
374void CoreController::setSync(bool sync) {
375	if (sync) {
376		m_threadContext.impl->sync.audioWait = m_audioSync;
377		m_threadContext.impl->sync.videoFrameWait = m_videoSync;
378	} else {
379		m_threadContext.impl->sync.audioWait = false;
380		m_threadContext.impl->sync.videoFrameWait = false;
381	}
382}
383
384void CoreController::setRewinding(bool rewind) {
385	if (!m_threadContext.core->opts.rewindEnable) {
386		return;
387	}
388	if (rewind && m_multiplayer && m_multiplayer->attached() > 1) {
389		return;
390	}
391
392	if (rewind && isPaused()) {
393		setPaused(false);
394		// TODO: restore autopausing
395	}
396	mCoreThreadSetRewinding(&m_threadContext, rewind);
397}
398
399void CoreController::rewind(int states) {
400	{
401		Interrupter interrupter(this);
402		if (!states) {
403			states = INT_MAX;
404		}
405		for (int i = 0; i < states; ++i) {
406			if (!mCoreRewindRestore(&m_threadContext.impl->rewind, m_threadContext.core)) {
407				break;
408			}
409		}
410	}
411	emit frameAvailable();
412	emit rewound();
413}
414
415void CoreController::setFastForward(bool enable) {
416	m_fastForward = enable;
417	updateFastForward();
418}
419
420void CoreController::forceFastForward(bool enable) {
421	m_fastForwardForced = enable;
422	updateFastForward();
423}
424
425void CoreController::loadState(int slot) {
426	if (slot > 0 && slot != m_stateSlot) {
427		m_stateSlot = slot;
428		m_backupSaveState.clear();
429	}
430	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
431		CoreController* controller = static_cast<CoreController*>(context->userData);
432		if (!controller->m_backupLoadState.isOpen()) {
433			controller->m_backupLoadState = VFileMemChunk(nullptr, 0);
434		}
435		mCoreSaveStateNamed(context->core, controller->m_backupLoadState, controller->m_saveStateFlags);
436		if (mCoreLoadState(context->core, controller->m_stateSlot, controller->m_loadStateFlags)) {
437			emit controller->frameAvailable();
438			emit controller->stateLoaded();
439		}
440	});
441}
442
443void CoreController::saveState(int slot) {
444	if (slot > 0) {
445		m_stateSlot = slot;
446	}
447	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
448		CoreController* controller = static_cast<CoreController*>(context->userData);
449		VFile* vf = mCoreGetState(context->core, controller->m_stateSlot, false);
450		if (vf) {
451			controller->m_backupSaveState.resize(vf->size(vf));
452			vf->read(vf, controller->m_backupSaveState.data(), controller->m_backupSaveState.size());
453			vf->close(vf);
454		}
455		mCoreSaveState(context->core, controller->m_stateSlot, controller->m_saveStateFlags);
456	});
457}
458
459void CoreController::loadBackupState() {
460	if (!m_backupLoadState.isOpen()) {
461		return;
462	}
463
464	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
465		CoreController* controller = static_cast<CoreController*>(context->userData);
466		controller->m_backupLoadState.seek(0);
467		if (mCoreLoadStateNamed(context->core, controller->m_backupLoadState, controller->m_loadStateFlags)) {
468			mLOG(STATUS, INFO, "Undid state load");
469			controller->frameAvailable();
470			controller->stateLoaded();
471		}
472		controller->m_backupLoadState.close();
473	});
474}
475
476void CoreController::saveBackupState() {
477	if (m_backupSaveState.isEmpty()) {
478		return;
479	}
480
481	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
482		CoreController* controller = static_cast<CoreController*>(context->userData);
483		VFile* vf = mCoreGetState(context->core, controller->m_stateSlot, true);
484		if (vf) {
485			vf->write(vf, controller->m_backupSaveState.constData(), controller->m_backupSaveState.size());
486			vf->close(vf);
487			mLOG(STATUS, INFO, "Undid state save");
488		}
489		controller->m_backupSaveState.clear();
490	});
491}
492
493void CoreController::loadSave(const QString& path, bool temporary) {
494	m_resetActions.append([this, path, temporary]() {
495		VFile* vf = VFileDevice::open(path, temporary ? O_RDONLY : O_RDWR);
496		if (!vf) {
497			LOG(QT, ERROR) << tr("Failed to open save file: %1").arg(path);
498			return;
499		}
500
501		if (temporary) {
502			m_threadContext.core->loadTemporarySave(m_threadContext.core, vf);
503		} else {
504			m_threadContext.core->loadSave(m_threadContext.core, vf);
505		}
506	});
507	reset();
508}
509
510void CoreController::loadPatch(const QString& patchPath) {
511	Interrupter interrupter(this);
512	VFile* patch = VFileDevice::open(patchPath, O_RDONLY);
513	if (patch) {
514		m_threadContext.core->loadPatch(m_threadContext.core, patch);
515		m_patched = true;
516	}
517	patch->close(patch);
518	if (mCoreThreadHasStarted(&m_threadContext)) {
519		reset();
520	}
521}
522
523void CoreController::replaceGame(const QString& path) {
524	QFileInfo info(path);
525	if (!info.isReadable()) {
526		LOG(QT, ERROR) << tr("Failed to open game file: %1").arg(path);
527		return;
528	}
529	QString fname = info.canonicalFilePath();
530	Interrupter interrupter(this);
531	mDirectorySetDetachBase(&m_threadContext.core->dirs);
532	mCoreLoadFile(m_threadContext.core, fname.toLocal8Bit().constData());
533}
534
535void CoreController::yankPak() {
536#ifdef M_CORE_GBA
537	if (platform() != PLATFORM_GBA) {
538		return;
539	}
540	Interrupter interrupter(this);
541	GBAYankROM(static_cast<GBA*>(m_threadContext.core->board));
542#endif
543}
544
545void CoreController::addKey(int key) {
546	m_activeKeys |= 1 << key;
547}
548
549void CoreController::clearKey(int key) {
550	m_activeKeys &= ~(1 << key);
551}
552
553void CoreController::setAutofire(int key, bool enable) {
554	if (key >= 32 || key < 0) {
555		return;
556	}
557
558	m_autofire[key] = enable;
559	m_autofireStatus[key] = 0;
560}
561
562#ifdef USE_PNG
563void CoreController::screenshot() {
564	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
565		mCoreTakeScreenshot(context->core);
566	});
567}
568#endif
569
570void CoreController::setRealTime() {
571	m_threadContext.core->rtc.override = RTC_NO_OVERRIDE;
572}
573
574void CoreController::setFixedTime(const QDateTime& time) {
575	m_threadContext.core->rtc.override = RTC_FIXED;
576	m_threadContext.core->rtc.value = time.toMSecsSinceEpoch();
577}
578
579void CoreController::setFakeEpoch(const QDateTime& time) {
580	m_threadContext.core->rtc.override = RTC_FAKE_EPOCH;
581	m_threadContext.core->rtc.value = time.toMSecsSinceEpoch();
582}
583
584void CoreController::importSharkport(const QString& path) {
585#ifdef M_CORE_GBA
586	if (platform() != PLATFORM_GBA) {
587		return;
588	}
589	VFile* vf = VFileDevice::open(path, O_RDONLY);
590	if (!vf) {
591		LOG(QT, ERROR) << tr("Failed to open snapshot file for reading: %1").arg(path);
592		return;
593	}
594	Interrupter interrupter(this);
595	GBASavedataImportSharkPort(static_cast<GBA*>(m_threadContext.core->board), vf, false);
596	vf->close(vf);
597#endif
598}
599
600void CoreController::exportSharkport(const QString& path) {
601#ifdef M_CORE_GBA
602	if (platform() != PLATFORM_GBA) {
603		return;
604	}
605	VFile* vf = VFileDevice::open(path, O_WRONLY | O_CREAT | O_TRUNC);
606	if (!vf) {
607		LOG(QT, ERROR) << tr("Failed to open snapshot file for writing: %1").arg(path);
608		return;
609	}
610	Interrupter interrupter(this);
611	GBASavedataExportSharkPort(static_cast<GBA*>(m_threadContext.core->board), vf);
612	vf->close(vf);
613#endif
614}
615
616void CoreController::attachPrinter() {
617#ifdef M_CORE_GB
618	if (platform() != PLATFORM_GB) {
619		return;
620	}
621	GB* gb = static_cast<GB*>(m_threadContext.core->board);
622	clearMultiplayerController();
623	GBPrinterCreate(&m_printer.d);
624	m_printer.parent = this;
625	m_printer.d.print = [](GBPrinter* printer, int height, const uint8_t* data) {
626		QGBPrinter* qPrinter = reinterpret_cast<QGBPrinter*>(printer);
627		QImage image(GB_VIDEO_HORIZONTAL_PIXELS, height, QImage::Format_Indexed8);
628		QVector<QRgb> colors;
629		colors.append(qRgb(0xF8, 0xF8, 0xF8));
630		colors.append(qRgb(0xA8, 0xA8, 0xA8));
631		colors.append(qRgb(0x50, 0x50, 0x50));
632		colors.append(qRgb(0x00, 0x00, 0x00));
633		image.setColorTable(colors);
634		for (int y = 0; y < height; ++y) {
635			for (int x = 0; x < GB_VIDEO_HORIZONTAL_PIXELS; x += 4) {
636				uint8_t byte = data[(x + y * GB_VIDEO_HORIZONTAL_PIXELS) / 4];
637				image.setPixel(x + 0, y, (byte & 0xC0) >> 6);
638				image.setPixel(x + 1, y, (byte & 0x30) >> 4);
639				image.setPixel(x + 2, y, (byte & 0x0C) >> 2);
640				image.setPixel(x + 3, y, (byte & 0x03) >> 0);
641			}
642		}
643		QMetaObject::invokeMethod(qPrinter->parent, "imagePrinted", Q_ARG(const QImage&, image));
644	};
645	GBSIOSetDriver(&gb->sio, &m_printer.d.d);
646#endif
647}
648
649void CoreController::detachPrinter() {
650#ifdef M_CORE_GB
651	if (platform() != PLATFORM_GB) {
652		return;
653	}
654	GB* gb = static_cast<GB*>(m_threadContext.core->board);
655	GBPrinterDonePrinting(&m_printer.d);
656	GBSIOSetDriver(&gb->sio, nullptr);
657#endif
658}
659
660void CoreController::endPrint() {
661#ifdef M_CORE_GB
662	if (platform() != PLATFORM_GB) {
663		return;
664	}
665	GBPrinterDonePrinting(&m_printer.d);
666#endif
667}
668
669void CoreController::setAVStream(mAVStream* stream) {
670	Interrupter interrupter(this);
671	m_threadContext.core->setAVStream(m_threadContext.core, stream);
672}
673
674void CoreController::clearAVStream() {
675	Interrupter interrupter(this);
676	m_threadContext.core->setAVStream(m_threadContext.core, nullptr);
677}
678
679void CoreController::clearOverride() {
680	m_override.reset();
681}
682
683void CoreController::startVideoLog(const QString& path) {
684	if (m_vl) {
685		return;
686	}
687
688	Interrupter interrupter(this);
689	m_vl = mVideoLogContextCreate(m_threadContext.core);
690	m_vlVf = VFileDevice::open(path, O_WRONLY | O_CREAT | O_TRUNC);
691	mVideoLogContextSetOutput(m_vl, m_vlVf);
692	mVideoLogContextWriteHeader(m_vl, m_threadContext.core);
693}
694
695void CoreController::endVideoLog() {
696	if (!m_vl) {
697		return;
698	}
699
700	Interrupter interrupter(this);
701	mVideoLogContextDestroy(m_threadContext.core, m_vl);
702	if (m_vlVf) {
703		m_vlVf->close(m_vlVf);
704		m_vlVf = nullptr;
705	}
706	m_vl = nullptr;
707}
708
709void CoreController::updateKeys() {
710	int activeKeys = m_activeKeys | updateAutofire() | m_inputController->pollEvents();
711	m_threadContext.core->setKeys(m_threadContext.core, activeKeys);
712}
713
714int CoreController::updateAutofire() {
715	int active = 0;
716	for (int k = 0; k < 32; ++k) {
717		if (!m_autofire[k]) {
718			continue;
719		}
720		++m_autofireStatus[k];
721		if (m_autofireStatus[k] >= 2 * m_autofireThreshold) {
722			m_autofireStatus[k] = 0;
723		} else if (m_autofireStatus[k] >= m_autofireThreshold) {
724			active |= 1 << k;
725		}
726	}
727	return active;
728}
729
730void CoreController::finishFrame() {
731	QMutexLocker locker(&m_mutex);
732	m_completeBuffer = m_activeBuffer;
733
734	// TODO: Generalize this to triple buffering?
735	m_activeBuffer = &m_buffers[0];
736	if (m_activeBuffer == m_completeBuffer) {
737		m_activeBuffer = &m_buffers[1];
738	}
739	m_threadContext.core->setVideoBuffer(m_threadContext.core, reinterpret_cast<color_t*>(m_activeBuffer->data()), toPow2(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}