all repos — mgba @ 75fa9a80fa51e116f6104cf7f9dd1598f365e66c

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		context->core->setVideoBuffer(context->core, reinterpret_cast<color_t*>(controller->m_activeBuffer.data()), controller->screenDimensions().width());
  85
  86		QMetaObject::invokeMethod(controller, "didReset");
  87		controller->finishFrame();
  88	};
  89
  90	m_threadContext.frameCallback = [](mCoreThread* context) {
  91		CoreController* controller = static_cast<CoreController*>(context->userData);
  92
  93		if (controller->m_autosaveCounter == AUTOSAVE_GRANULARITY) {
  94			if (controller->m_autosave) {
  95				mCoreSaveState(context->core, 0, controller->m_saveStateFlags);
  96			}
  97			controller->m_autosaveCounter = 0;
  98		}
  99		++controller->m_autosaveCounter;
 100
 101		controller->finishFrame();
 102	};
 103
 104	m_threadContext.cleanCallback = [](mCoreThread* context) {
 105		CoreController* controller = static_cast<CoreController*>(context->userData);
 106
 107		if (controller->m_autosave) {
 108			mCoreSaveState(context->core, 0, controller->m_saveStateFlags);
 109		}
 110
 111		controller->clearMultiplayerController();
 112		QMetaObject::invokeMethod(controller, "stopping");
 113	};
 114
 115	m_threadContext.pauseCallback = [](mCoreThread* context) {
 116		CoreController* controller = static_cast<CoreController*>(context->userData);
 117
 118		QMetaObject::invokeMethod(controller, "paused");
 119	};
 120
 121	m_threadContext.unpauseCallback = [](mCoreThread* context) {
 122		CoreController* controller = static_cast<CoreController*>(context->userData);
 123
 124		QMetaObject::invokeMethod(controller, "unpaused");
 125	};
 126
 127	m_threadContext.logger.d.log = [](mLogger* logger, int category, enum mLogLevel level, const char* format, va_list args) {
 128		mThreadLogger* logContext = reinterpret_cast<mThreadLogger*>(logger);
 129		mCoreThread* context = logContext->p;
 130
 131		static const char* savestateMessage = "State %i saved";
 132		static const char* loadstateMessage = "State %i loaded";
 133		static const char* savestateFailedMessage = "State %i failed to load";
 134		static int biosCat = -1;
 135		static int statusCat = -1;
 136		if (!context) {
 137			return;
 138		}
 139		CoreController* controller = static_cast<CoreController*>(context->userData);
 140		QString message;
 141		if (biosCat < 0) {
 142			biosCat = mLogCategoryById("gba.bios");
 143		}
 144		if (statusCat < 0) {
 145			statusCat = mLogCategoryById("core.status");
 146		}
 147#ifdef M_CORE_GBA
 148		if (level == mLOG_STUB && category == biosCat) {
 149			va_list argc;
 150			va_copy(argc, args);
 151			int immediate = va_arg(argc, int);
 152			va_end(argc);
 153			QMetaObject::invokeMethod(controller, "unimplementedBiosCall", Q_ARG(int, immediate));
 154		} else
 155#endif
 156		if (category == statusCat) {
 157			// Slot 0 is reserved for suspend points
 158			if (strncmp(loadstateMessage, format, strlen(loadstateMessage)) == 0) {
 159				va_list argc;
 160				va_copy(argc, args);
 161				int slot = va_arg(argc, int);
 162				va_end(argc);
 163				if (slot == 0) {
 164					format = "Loaded suspend state";
 165				}
 166			} else if (strncmp(savestateFailedMessage, format, strlen(savestateFailedMessage)) == 0 || strncmp(savestateMessage, format, strlen(savestateMessage)) == 0) {
 167				va_list argc;
 168				va_copy(argc, args);
 169				int slot = va_arg(argc, int);
 170				va_end(argc);
 171				if (slot == 0) {
 172					return;
 173				}
 174			}
 175			message = QString().vsprintf(format, args);
 176			QMetaObject::invokeMethod(controller, "statusPosted", Q_ARG(const QString&, message));
 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		if (level == mLOG_FATAL) {
 181			QMetaObject::invokeMethod(controller, "crashed", Q_ARG(const QString&, QString().vsprintf(format, args)));
 182		}
 183	};
 184}
 185
 186CoreController::~CoreController() {
 187	endVideoLog();
 188	stop();
 189	disconnect();
 190
 191	mCoreThreadJoin(&m_threadContext);
 192
 193	if (m_cacheSet) {
 194		mCacheSetDeinit(m_cacheSet.get());
 195		m_cacheSet.reset();
 196	}
 197
 198	mCoreConfigDeinit(&m_threadContext.core->config);
 199	m_threadContext.core->deinit(m_threadContext.core);
 200}
 201
 202const color_t* CoreController::drawContext() {
 203	if (m_hwaccel) {
 204		return nullptr;
 205	}
 206	QMutexLocker locker(&m_bufferMutex);
 207	return reinterpret_cast<const color_t*>(m_completeBuffer.constData());
 208}
 209
 210QImage CoreController::getPixels() {
 211	QByteArray buffer;
 212	QSize size = screenDimensions();
 213	size_t stride = size.width() * BYTES_PER_PIXEL;
 214
 215	if (!m_hwaccel) {
 216		buffer = m_completeBuffer;
 217	} else {
 218		Interrupter interrupter(this);
 219		const void* pixels;
 220		m_threadContext.core->getPixels(m_threadContext.core, &pixels, &stride);
 221		stride *= BYTES_PER_PIXEL;
 222		buffer = QByteArray::fromRawData(static_cast<const char*>(pixels), stride * size.height());
 223	}
 224
 225	QImage image(reinterpret_cast<const uchar*>(buffer.constData()),
 226	             size.width(), size.height(), stride, QImage::Format_RGBX8888);
 227	image.bits(); // Cause QImage to detach
 228	return image;
 229}
 230
 231bool CoreController::isPaused() {
 232	return mCoreThreadIsPaused(&m_threadContext);
 233}
 234
 235bool CoreController::hasStarted() {
 236	return mCoreThreadHasStarted(&m_threadContext);
 237}
 238
 239mPlatform CoreController::platform() const {
 240	return m_threadContext.core->platform(m_threadContext.core);
 241}
 242
 243QSize CoreController::screenDimensions() const {
 244	unsigned width, height;
 245	m_threadContext.core->desiredVideoDimensions(m_threadContext.core, &width, &height);
 246
 247	return QSize(width, height);
 248}
 249
 250void CoreController::loadConfig(ConfigController* config) {
 251	Interrupter interrupter(this);
 252	m_loadStateFlags = config->getOption("loadStateExtdata", m_loadStateFlags).toInt();
 253	m_saveStateFlags = config->getOption("saveStateExtdata", m_saveStateFlags).toInt();
 254	m_fastForwardRatio = config->getOption("fastForwardRatio", m_fastForwardRatio).toFloat();
 255	m_fastForwardHeldRatio = config->getOption("fastForwardHeldRatio", 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	QSize size(256, 224);
 360	m_activeBuffer.resize(size.width() * size.height() * sizeof(color_t));
 361	m_activeBuffer.fill(0xFF);
 362	m_completeBuffer = m_activeBuffer;
 363
 364	m_threadContext.core->setVideoBuffer(m_threadContext.core, reinterpret_cast<color_t*>(m_activeBuffer.data()), size.width());
 365
 366	if (!m_patched) {
 367		mCoreAutoloadPatch(m_threadContext.core);
 368	}
 369	if (!mCoreThreadStart(&m_threadContext)) {
 370		emit failed();
 371		emit stopping();
 372	}
 373}
 374
 375void CoreController::stop() {
 376	setSync(false);
 377#ifdef USE_DEBUGGERS
 378	setDebugger(nullptr);
 379#endif
 380	setPaused(false);
 381	mCoreThreadEnd(&m_threadContext);
 382}
 383
 384void CoreController::reset() {
 385	bool wasPaused = isPaused();
 386	setPaused(false);
 387	Interrupter interrupter(this);
 388	mCoreThreadReset(&m_threadContext);
 389	if (wasPaused) {
 390		setPaused(true);
 391	}
 392}
 393
 394void CoreController::setPaused(bool paused) {
 395	if (paused == isPaused()) {
 396		return;
 397	}
 398	if (paused) {
 399		addFrameAction([this]() {
 400			mCoreThreadPauseFromThread(&m_threadContext);
 401		});
 402	} else {
 403		mCoreThreadUnpause(&m_threadContext);
 404	}
 405}
 406
 407void CoreController::frameAdvance() {
 408	addFrameAction([this]() {
 409		mCoreThreadPauseFromThread(&m_threadContext);
 410	});
 411	setPaused(false);
 412}
 413
 414void CoreController::addFrameAction(std::function<void ()> action) {
 415	QMutexLocker locker(&m_actionMutex);
 416	m_frameActions.append(action);
 417}
 418
 419void CoreController::setSync(bool sync) {
 420	if (sync) {
 421		m_threadContext.impl->sync.audioWait = m_audioSync;
 422		m_threadContext.impl->sync.videoFrameWait = m_videoSync;
 423	} else {
 424		m_threadContext.impl->sync.audioWait = false;
 425		m_threadContext.impl->sync.videoFrameWait = false;
 426	}
 427}
 428
 429void CoreController::setRewinding(bool rewind) {
 430	if (!m_threadContext.core->opts.rewindEnable) {
 431		return;
 432	}
 433	if (rewind && m_multiplayer && m_multiplayer->attached() > 1) {
 434		return;
 435	}
 436
 437	if (rewind && isPaused()) {
 438		setPaused(false);
 439		// TODO: restore autopausing
 440	}
 441	mCoreThreadSetRewinding(&m_threadContext, rewind);
 442}
 443
 444void CoreController::rewind(int states) {
 445	{
 446		Interrupter interrupter(this);
 447		if (!states) {
 448			states = INT_MAX;
 449		}
 450		for (int i = 0; i < states; ++i) {
 451			if (!mCoreRewindRestore(&m_threadContext.impl->rewind, m_threadContext.core)) {
 452				break;
 453			}
 454		}
 455	}
 456	emit frameAvailable();
 457	emit rewound();
 458}
 459
 460void CoreController::setFastForward(bool enable) {
 461	if (m_fastForward == enable) {
 462		return;
 463	}
 464	m_fastForward = enable;
 465	updateFastForward();
 466	emit fastForwardChanged(enable);
 467}
 468
 469void CoreController::forceFastForward(bool enable) {
 470	if (m_fastForwardForced == enable) {
 471		return;
 472	}
 473	m_fastForwardForced = enable;
 474	updateFastForward();
 475	emit fastForwardChanged(enable || m_fastForward);
 476}
 477
 478void CoreController::loadState(int slot) {
 479	if (slot > 0 && slot != m_stateSlot) {
 480		m_stateSlot = slot;
 481		m_backupSaveState.clear();
 482	}
 483	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 484		CoreController* controller = static_cast<CoreController*>(context->userData);
 485		if (!controller->m_backupLoadState.isOpen()) {
 486			controller->m_backupLoadState = VFileMemChunk(nullptr, 0);
 487		}
 488		mCoreSaveStateNamed(context->core, controller->m_backupLoadState, controller->m_saveStateFlags);
 489		if (mCoreLoadState(context->core, controller->m_stateSlot, controller->m_loadStateFlags)) {
 490			emit controller->frameAvailable();
 491			emit controller->stateLoaded();
 492		}
 493	});
 494}
 495
 496void CoreController::loadState(const QString& path) {
 497	m_statePath = path;
 498	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 499		CoreController* controller = static_cast<CoreController*>(context->userData);
 500		VFile* vf = VFileDevice::open(controller->m_statePath, O_RDONLY);
 501		if (!vf) {
 502			return;
 503		}
 504		if (!controller->m_backupLoadState.isOpen()) {
 505			controller->m_backupLoadState = VFileMemChunk(nullptr, 0);
 506		}
 507		mCoreSaveStateNamed(context->core, controller->m_backupLoadState, controller->m_saveStateFlags);
 508		if (mCoreLoadStateNamed(context->core, vf, controller->m_loadStateFlags)) {
 509			emit controller->frameAvailable();
 510			emit controller->stateLoaded();
 511		}
 512		vf->close(vf);
 513	});
 514}
 515
 516void CoreController::saveState(int slot) {
 517	if (slot > 0) {
 518		m_stateSlot = slot;
 519	}
 520	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 521		CoreController* controller = static_cast<CoreController*>(context->userData);
 522		VFile* vf = mCoreGetState(context->core, controller->m_stateSlot, false);
 523		if (vf) {
 524			controller->m_backupSaveState.resize(vf->size(vf));
 525			vf->read(vf, controller->m_backupSaveState.data(), controller->m_backupSaveState.size());
 526			vf->close(vf);
 527		}
 528		mCoreSaveState(context->core, controller->m_stateSlot, controller->m_saveStateFlags);
 529	});
 530}
 531
 532void CoreController::saveState(const QString& path) {
 533	m_statePath = path;
 534	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 535		CoreController* controller = static_cast<CoreController*>(context->userData);
 536		VFile* vf = VFileDevice::open(controller->m_statePath, O_RDONLY);
 537		if (vf) {
 538			controller->m_backupSaveState.resize(vf->size(vf));
 539			vf->read(vf, controller->m_backupSaveState.data(), controller->m_backupSaveState.size());
 540			vf->close(vf);
 541		}
 542		vf = VFileDevice::open(controller->m_statePath, O_WRONLY | O_CREAT | O_TRUNC);
 543		if (!vf) {
 544			return;
 545		}
 546		mCoreSaveStateNamed(context->core, vf, controller->m_saveStateFlags);
 547		vf->close(vf);
 548	});
 549}
 550
 551void CoreController::loadBackupState() {
 552	if (!m_backupLoadState.isOpen()) {
 553		return;
 554	}
 555
 556	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 557		CoreController* controller = static_cast<CoreController*>(context->userData);
 558		controller->m_backupLoadState.seek(0);
 559		if (mCoreLoadStateNamed(context->core, controller->m_backupLoadState, controller->m_loadStateFlags)) {
 560			mLOG(STATUS, INFO, "Undid state load");
 561			controller->frameAvailable();
 562			controller->stateLoaded();
 563		}
 564		controller->m_backupLoadState.close();
 565	});
 566}
 567
 568void CoreController::saveBackupState() {
 569	if (m_backupSaveState.isEmpty()) {
 570		return;
 571	}
 572
 573	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 574		CoreController* controller = static_cast<CoreController*>(context->userData);
 575		VFile* vf = mCoreGetState(context->core, controller->m_stateSlot, true);
 576		if (vf) {
 577			vf->write(vf, controller->m_backupSaveState.constData(), controller->m_backupSaveState.size());
 578			vf->close(vf);
 579			mLOG(STATUS, INFO, "Undid state save");
 580		}
 581		controller->m_backupSaveState.clear();
 582	});
 583}
 584
 585void CoreController::loadSave(const QString& path, bool temporary) {
 586	m_resetActions.append([this, path, temporary]() {
 587		VFile* vf = VFileDevice::open(path, temporary ? O_RDONLY : O_RDWR);
 588		if (!vf) {
 589			LOG(QT, ERROR) << tr("Failed to open save file: %1").arg(path);
 590			return;
 591		}
 592
 593		if (temporary) {
 594			m_threadContext.core->loadTemporarySave(m_threadContext.core, vf);
 595		} else {
 596			m_threadContext.core->loadSave(m_threadContext.core, vf);
 597		}
 598	});
 599	reset();
 600}
 601
 602void CoreController::loadPatch(const QString& patchPath) {
 603	Interrupter interrupter(this);
 604	VFile* patch = VFileDevice::open(patchPath, O_RDONLY);
 605	if (patch) {
 606		m_threadContext.core->loadPatch(m_threadContext.core, patch);
 607		m_patched = true;
 608		patch->close(patch);
 609	}
 610	if (mCoreThreadHasStarted(&m_threadContext)) {
 611		reset();
 612	}
 613}
 614
 615void CoreController::replaceGame(const QString& path) {
 616	QFileInfo info(path);
 617	if (!info.isReadable()) {
 618		LOG(QT, ERROR) << tr("Failed to open game file: %1").arg(path);
 619		return;
 620	}
 621	QString fname = info.canonicalFilePath();
 622	Interrupter interrupter(this);
 623	mDirectorySetDetachBase(&m_threadContext.core->dirs);
 624	mCoreLoadFile(m_threadContext.core, fname.toUtf8().constData());
 625}
 626
 627void CoreController::yankPak() {
 628	Interrupter interrupter(this);
 629
 630	switch (platform()) {
 631#ifdef M_CORE_GBA
 632	case PLATFORM_GBA:
 633		GBAYankROM(static_cast<GBA*>(m_threadContext.core->board));
 634		break;
 635#endif
 636#ifdef M_CORE_GB
 637	case PLATFORM_GB:
 638		GBYankROM(static_cast<GB*>(m_threadContext.core->board));
 639		break;
 640#endif
 641	}
 642}
 643
 644void CoreController::addKey(int key) {
 645	m_activeKeys |= 1 << key;
 646}
 647
 648void CoreController::clearKey(int key) {
 649	m_activeKeys &= ~(1 << key);
 650}
 651
 652void CoreController::setAutofire(int key, bool enable) {
 653	if (key >= 32 || key < 0) {
 654		return;
 655	}
 656
 657	m_autofire[key] = enable;
 658	m_autofireStatus[key] = 0;
 659}
 660
 661#ifdef USE_PNG
 662void CoreController::screenshot() {
 663	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 664		mCoreTakeScreenshot(context->core);
 665	});
 666}
 667#endif
 668
 669void CoreController::setRealTime() {
 670	m_threadContext.core->rtc.override = RTC_NO_OVERRIDE;
 671}
 672
 673void CoreController::setFixedTime(const QDateTime& time) {
 674	m_threadContext.core->rtc.override = RTC_FIXED;
 675	m_threadContext.core->rtc.value = time.toMSecsSinceEpoch();
 676}
 677
 678void CoreController::setFakeEpoch(const QDateTime& time) {
 679	m_threadContext.core->rtc.override = RTC_FAKE_EPOCH;
 680	m_threadContext.core->rtc.value = time.toMSecsSinceEpoch();
 681}
 682
 683void CoreController::scanCard(const QString& path) {
 684#ifdef M_CORE_GBA
 685	QImage image(path);
 686	if (image.isNull()) {
 687		QFile file(path);
 688		file.open(QIODevice::ReadOnly);
 689		m_eReaderData = file.read(2912);
 690	} else if (image.size() == QSize(989, 44)) {
 691		const uchar* bits = image.constBits();
 692		size_t size;
 693#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
 694		size = image.sizeInBytes();
 695#else
 696		size = image.byteCount();
 697#endif
 698		m_eReaderData.setRawData(reinterpret_cast<const char*>(bits), image.sizeInBytes());
 699	}
 700
 701	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* thread) {
 702		CoreController* controller = static_cast<CoreController*>(thread->userData);
 703		GBAEReaderQueueCard(static_cast<GBA*>(thread->core->board), controller->m_eReaderData.constData(), controller->m_eReaderData.size());
 704	});
 705#endif
 706}
 707
 708
 709void CoreController::importSharkport(const QString& path) {
 710#ifdef M_CORE_GBA
 711	if (platform() != PLATFORM_GBA) {
 712		return;
 713	}
 714	VFile* vf = VFileDevice::open(path, O_RDONLY);
 715	if (!vf) {
 716		LOG(QT, ERROR) << tr("Failed to open snapshot file for reading: %1").arg(path);
 717		return;
 718	}
 719	Interrupter interrupter(this);
 720	GBASavedataImportSharkPort(static_cast<GBA*>(m_threadContext.core->board), vf, false);
 721	vf->close(vf);
 722#endif
 723}
 724
 725void CoreController::exportSharkport(const QString& path) {
 726#ifdef M_CORE_GBA
 727	if (platform() != PLATFORM_GBA) {
 728		return;
 729	}
 730	VFile* vf = VFileDevice::open(path, O_WRONLY | O_CREAT | O_TRUNC);
 731	if (!vf) {
 732		LOG(QT, ERROR) << tr("Failed to open snapshot file for writing: %1").arg(path);
 733		return;
 734	}
 735	Interrupter interrupter(this);
 736	GBASavedataExportSharkPort(static_cast<GBA*>(m_threadContext.core->board), vf);
 737	vf->close(vf);
 738#endif
 739}
 740
 741#ifdef M_CORE_GB
 742void CoreController::attachPrinter() {
 743	if (platform() != PLATFORM_GB) {
 744		return;
 745	}
 746	GB* gb = static_cast<GB*>(m_threadContext.core->board);
 747	clearMultiplayerController();
 748	GBPrinterCreate(&m_printer.d);
 749	m_printer.parent = this;
 750	m_printer.d.print = [](GBPrinter* printer, int height, const uint8_t* data) {
 751		QGBPrinter* qPrinter = reinterpret_cast<QGBPrinter*>(printer);
 752		QImage image(GB_VIDEO_HORIZONTAL_PIXELS, height, QImage::Format_Indexed8);
 753		QVector<QRgb> colors;
 754		colors.append(qRgb(0xF8, 0xF8, 0xF8));
 755		colors.append(qRgb(0xA8, 0xA8, 0xA8));
 756		colors.append(qRgb(0x50, 0x50, 0x50));
 757		colors.append(qRgb(0x00, 0x00, 0x00));
 758		image.setColorTable(colors);
 759		for (int y = 0; y < height; ++y) {
 760			for (int x = 0; x < GB_VIDEO_HORIZONTAL_PIXELS; x += 4) {
 761				uint8_t byte = data[(x + y * GB_VIDEO_HORIZONTAL_PIXELS) / 4];
 762				image.setPixel(x + 0, y, (byte & 0xC0) >> 6);
 763				image.setPixel(x + 1, y, (byte & 0x30) >> 4);
 764				image.setPixel(x + 2, y, (byte & 0x0C) >> 2);
 765				image.setPixel(x + 3, y, (byte & 0x03) >> 0);
 766			}
 767		}
 768		QMetaObject::invokeMethod(qPrinter->parent, "imagePrinted", Q_ARG(const QImage&, image));
 769	};
 770	Interrupter interrupter(this);
 771	GBSIOSetDriver(&gb->sio, &m_printer.d.d);
 772}
 773
 774void CoreController::detachPrinter() {
 775	if (platform() != PLATFORM_GB) {
 776		return;
 777	}
 778	Interrupter interrupter(this);
 779	GB* gb = static_cast<GB*>(m_threadContext.core->board);
 780	GBPrinterDonePrinting(&m_printer.d);
 781	GBSIOSetDriver(&gb->sio, nullptr);
 782}
 783
 784void CoreController::endPrint() {
 785	if (platform() != PLATFORM_GB) {
 786		return;
 787	}
 788	Interrupter interrupter(this);
 789	GBPrinterDonePrinting(&m_printer.d);
 790}
 791#endif
 792
 793#ifdef M_CORE_GBA
 794void CoreController::attachBattleChipGate() {
 795	if (platform() != PLATFORM_GBA) {
 796		return;
 797	}
 798	Interrupter interrupter(this);
 799	clearMultiplayerController();
 800	GBASIOBattlechipGateCreate(&m_battlechip);
 801	m_threadContext.core->setPeripheral(m_threadContext.core, mPERIPH_GBA_BATTLECHIP_GATE, &m_battlechip);
 802}
 803
 804void CoreController::detachBattleChipGate() {
 805	if (platform() != PLATFORM_GBA) {
 806		return;
 807	}
 808	Interrupter interrupter(this);
 809	m_threadContext.core->setPeripheral(m_threadContext.core, mPERIPH_GBA_BATTLECHIP_GATE, nullptr);
 810}
 811
 812void CoreController::setBattleChipId(uint16_t id) {
 813	if (platform() != PLATFORM_GBA) {
 814		return;
 815	}
 816	Interrupter interrupter(this);
 817	m_battlechip.chipId = id;
 818}
 819
 820void CoreController::setBattleChipFlavor(int flavor) {
 821	if (platform() != PLATFORM_GBA) {
 822		return;
 823	}
 824	Interrupter interrupter(this);
 825	m_battlechip.flavor = flavor;
 826}
 827#endif
 828
 829void CoreController::setAVStream(mAVStream* stream) {
 830	Interrupter interrupter(this);
 831	m_threadContext.core->setAVStream(m_threadContext.core, stream);
 832}
 833
 834void CoreController::clearAVStream() {
 835	Interrupter interrupter(this);
 836	m_threadContext.core->setAVStream(m_threadContext.core, nullptr);
 837}
 838
 839void CoreController::clearOverride() {
 840	m_override.reset();
 841}
 842
 843void CoreController::startVideoLog(const QString& path, bool compression) {
 844	if (m_vl) {
 845		return;
 846	}
 847
 848	VFile* vf = VFileDevice::open(path, O_WRONLY | O_CREAT | O_TRUNC);
 849	if (!vf) {
 850		return;
 851	}
 852	startVideoLog(vf);
 853}
 854
 855void CoreController::startVideoLog(VFile* vf, bool compression) {
 856	if (m_vl || !vf) {
 857		return;
 858	}
 859
 860	Interrupter interrupter(this);
 861	m_vl = mVideoLogContextCreate(m_threadContext.core);
 862	m_vlVf = vf;
 863	mVideoLogContextSetOutput(m_vl, m_vlVf);
 864	mVideoLogContextSetCompression(m_vl, compression);
 865	mVideoLogContextWriteHeader(m_vl, m_threadContext.core);
 866}
 867
 868void CoreController::endVideoLog(bool closeVf) {
 869	if (!m_vl) {
 870		return;
 871	}
 872
 873	Interrupter interrupter(this);
 874	mVideoLogContextDestroy(m_threadContext.core, m_vl);
 875	if (m_vlVf && closeVf) {
 876		m_vlVf->close(m_vlVf);
 877		m_vlVf = nullptr;
 878	}
 879	m_vl = nullptr;
 880}
 881
 882void CoreController::setFramebufferHandle(int fb) {
 883	Interrupter interrupter(this);
 884	if (fb < 0) {
 885		if (!m_hwaccel) {
 886			return;
 887		}
 888		mCoreConfigSetIntValue(&m_threadContext.core->config, "hwaccelVideo", 0);
 889		m_threadContext.core->setVideoGLTex(m_threadContext.core, -1);
 890		m_hwaccel = false;
 891	} else {
 892		mCoreConfigSetIntValue(&m_threadContext.core->config, "hwaccelVideo", 1);
 893		m_threadContext.core->setVideoGLTex(m_threadContext.core, fb);
 894		if (m_hwaccel) {
 895			return;
 896		}
 897		m_hwaccel = true;
 898	}
 899	if (hasStarted()) {
 900		m_threadContext.core->reloadConfigOption(m_threadContext.core, "hwaccelVideo", NULL);
 901	}
 902}
 903
 904void CoreController::updateKeys() {
 905	int activeKeys = m_activeKeys | updateAutofire() | m_inputController->pollEvents();
 906	m_threadContext.core->setKeys(m_threadContext.core, activeKeys);
 907}
 908
 909int CoreController::updateAutofire() {
 910	int active = 0;
 911	for (int k = 0; k < 32; ++k) {
 912		if (!m_autofire[k]) {
 913			continue;
 914		}
 915		++m_autofireStatus[k];
 916		if (m_autofireStatus[k] >= 2 * m_autofireThreshold) {
 917			m_autofireStatus[k] = 0;
 918		} else if (m_autofireStatus[k] >= m_autofireThreshold) {
 919			active |= 1 << k;
 920		}
 921	}
 922	return active;
 923}
 924
 925void CoreController::finishFrame() {
 926	if (!m_hwaccel) {
 927		unsigned width, height;
 928		m_threadContext.core->desiredVideoDimensions(m_threadContext.core, &width, &height);
 929
 930		QMutexLocker locker(&m_bufferMutex);
 931		memcpy(m_completeBuffer.data(), m_activeBuffer.constData(), 256 * height * BYTES_PER_PIXEL);
 932	}
 933
 934	QMutexLocker locker(&m_actionMutex);
 935	QList<std::function<void ()>> frameActions(m_frameActions);
 936	m_frameActions.clear();
 937	for (auto& action : frameActions) {
 938		action();
 939	}
 940	updateKeys();
 941
 942	QMetaObject::invokeMethod(this, "frameAvailable");
 943}
 944
 945void CoreController::updateFastForward() {
 946	// If we have "Fast forward" checked in the menu (m_fastForwardForced)
 947	// or are holding the fast forward button (m_fastForward):
 948	if (m_fastForward || m_fastForwardForced) {
 949		if (m_fastForwardVolume >= 0) {
 950			m_threadContext.core->opts.volume = m_fastForwardVolume;
 951		}
 952		if (m_fastForwardMute >= 0) {
 953			m_threadContext.core->opts.mute = m_fastForwardMute;
 954		}
 955
 956		// If we aren't holding the fast forward button
 957		// then use the non "(held)" ratio
 958		if(!m_fastForward) {
 959			if (m_fastForwardRatio > 0) {
 960				m_threadContext.impl->sync.fpsTarget = m_fpsTarget * m_fastForwardRatio;
 961				setSync(true);
 962			}	else {
 963				setSync(false);
 964			}
 965		} else {
 966			// If we are holding the fast forward button,
 967			// then use the held ratio
 968			if (m_fastForwardHeldRatio > 0) {
 969				m_threadContext.impl->sync.fpsTarget = m_fpsTarget * m_fastForwardHeldRatio;
 970				setSync(true);
 971			} else {
 972				setSync(false);
 973			}
 974		}
 975	} else {
 976		if (!mCoreConfigGetIntValue(&m_threadContext.core->config, "volume", &m_threadContext.core->opts.volume)) {
 977			m_threadContext.core->opts.volume = 0x100;
 978		}
 979		int fakeBool = 0;
 980		mCoreConfigGetIntValue(&m_threadContext.core->config, "mute", &fakeBool);
 981		m_threadContext.core->opts.mute = fakeBool;
 982		m_threadContext.impl->sync.fpsTarget = m_fpsTarget;
 983		setSync(true);
 984	}
 985
 986	m_threadContext.core->reloadConfigOption(m_threadContext.core, NULL, NULL);
 987}
 988
 989CoreController::Interrupter::Interrupter(CoreController* parent, bool fromThread)
 990	: m_parent(parent)
 991{
 992	if (!m_parent->thread()->impl) {
 993		return;
 994	}
 995	if (!fromThread) {
 996		mCoreThreadInterrupt(m_parent->thread());
 997	} else {
 998		mCoreThreadInterruptFromThread(m_parent->thread());
 999	}
1000}
1001
1002CoreController::Interrupter::Interrupter(std::shared_ptr<CoreController> parent, bool fromThread)
1003	: m_parent(parent.get())
1004{
1005	if (!m_parent->thread()->impl) {
1006		return;
1007	}
1008	if (!fromThread) {
1009		mCoreThreadInterrupt(m_parent->thread());
1010	} else {
1011		mCoreThreadInterruptFromThread(m_parent->thread());
1012	}
1013}
1014
1015CoreController::Interrupter::Interrupter(const Interrupter& other)
1016	: m_parent(other.m_parent)
1017{
1018	if (!m_parent->thread()->impl) {
1019		return;
1020	}
1021	mCoreThreadInterrupt(m_parent->thread());
1022}
1023
1024CoreController::Interrupter::~Interrupter() {
1025	if (!m_parent->thread()->impl) {
1026		return;
1027	}
1028	mCoreThreadContinue(m_parent->thread());
1029}