all repos — mgba @ 709149458319ec6bdf1a95c615a3ce5a6bbe1cb0

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	QFile file(path);
 686	file.open(QIODevice::ReadOnly);
 687	m_eReaderData = file.read(2912);
 688
 689	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* thread) {
 690		CoreController* controller = static_cast<CoreController*>(thread->userData);
 691		GBAEReaderQueueCard(static_cast<GBA*>(thread->core->board), controller->m_eReaderData.constData(), controller->m_eReaderData.size());
 692	});
 693#endif
 694}
 695
 696
 697void CoreController::importSharkport(const QString& path) {
 698#ifdef M_CORE_GBA
 699	if (platform() != PLATFORM_GBA) {
 700		return;
 701	}
 702	VFile* vf = VFileDevice::open(path, O_RDONLY);
 703	if (!vf) {
 704		LOG(QT, ERROR) << tr("Failed to open snapshot file for reading: %1").arg(path);
 705		return;
 706	}
 707	Interrupter interrupter(this);
 708	GBASavedataImportSharkPort(static_cast<GBA*>(m_threadContext.core->board), vf, false);
 709	vf->close(vf);
 710#endif
 711}
 712
 713void CoreController::exportSharkport(const QString& path) {
 714#ifdef M_CORE_GBA
 715	if (platform() != PLATFORM_GBA) {
 716		return;
 717	}
 718	VFile* vf = VFileDevice::open(path, O_WRONLY | O_CREAT | O_TRUNC);
 719	if (!vf) {
 720		LOG(QT, ERROR) << tr("Failed to open snapshot file for writing: %1").arg(path);
 721		return;
 722	}
 723	Interrupter interrupter(this);
 724	GBASavedataExportSharkPort(static_cast<GBA*>(m_threadContext.core->board), vf);
 725	vf->close(vf);
 726#endif
 727}
 728
 729#ifdef M_CORE_GB
 730void CoreController::attachPrinter() {
 731	if (platform() != PLATFORM_GB) {
 732		return;
 733	}
 734	GB* gb = static_cast<GB*>(m_threadContext.core->board);
 735	clearMultiplayerController();
 736	GBPrinterCreate(&m_printer.d);
 737	m_printer.parent = this;
 738	m_printer.d.print = [](GBPrinter* printer, int height, const uint8_t* data) {
 739		QGBPrinter* qPrinter = reinterpret_cast<QGBPrinter*>(printer);
 740		QImage image(GB_VIDEO_HORIZONTAL_PIXELS, height, QImage::Format_Indexed8);
 741		QVector<QRgb> colors;
 742		colors.append(qRgb(0xF8, 0xF8, 0xF8));
 743		colors.append(qRgb(0xA8, 0xA8, 0xA8));
 744		colors.append(qRgb(0x50, 0x50, 0x50));
 745		colors.append(qRgb(0x00, 0x00, 0x00));
 746		image.setColorTable(colors);
 747		for (int y = 0; y < height; ++y) {
 748			for (int x = 0; x < GB_VIDEO_HORIZONTAL_PIXELS; x += 4) {
 749				uint8_t byte = data[(x + y * GB_VIDEO_HORIZONTAL_PIXELS) / 4];
 750				image.setPixel(x + 0, y, (byte & 0xC0) >> 6);
 751				image.setPixel(x + 1, y, (byte & 0x30) >> 4);
 752				image.setPixel(x + 2, y, (byte & 0x0C) >> 2);
 753				image.setPixel(x + 3, y, (byte & 0x03) >> 0);
 754			}
 755		}
 756		QMetaObject::invokeMethod(qPrinter->parent, "imagePrinted", Q_ARG(const QImage&, image));
 757	};
 758	Interrupter interrupter(this);
 759	GBSIOSetDriver(&gb->sio, &m_printer.d.d);
 760}
 761
 762void CoreController::detachPrinter() {
 763	if (platform() != PLATFORM_GB) {
 764		return;
 765	}
 766	Interrupter interrupter(this);
 767	GB* gb = static_cast<GB*>(m_threadContext.core->board);
 768	GBPrinterDonePrinting(&m_printer.d);
 769	GBSIOSetDriver(&gb->sio, nullptr);
 770}
 771
 772void CoreController::endPrint() {
 773	if (platform() != PLATFORM_GB) {
 774		return;
 775	}
 776	Interrupter interrupter(this);
 777	GBPrinterDonePrinting(&m_printer.d);
 778}
 779#endif
 780
 781#ifdef M_CORE_GBA
 782void CoreController::attachBattleChipGate() {
 783	if (platform() != PLATFORM_GBA) {
 784		return;
 785	}
 786	Interrupter interrupter(this);
 787	clearMultiplayerController();
 788	GBASIOBattlechipGateCreate(&m_battlechip);
 789	m_threadContext.core->setPeripheral(m_threadContext.core, mPERIPH_GBA_BATTLECHIP_GATE, &m_battlechip);
 790}
 791
 792void CoreController::detachBattleChipGate() {
 793	if (platform() != PLATFORM_GBA) {
 794		return;
 795	}
 796	Interrupter interrupter(this);
 797	m_threadContext.core->setPeripheral(m_threadContext.core, mPERIPH_GBA_BATTLECHIP_GATE, nullptr);
 798}
 799
 800void CoreController::setBattleChipId(uint16_t id) {
 801	if (platform() != PLATFORM_GBA) {
 802		return;
 803	}
 804	Interrupter interrupter(this);
 805	m_battlechip.chipId = id;
 806}
 807
 808void CoreController::setBattleChipFlavor(int flavor) {
 809	if (platform() != PLATFORM_GBA) {
 810		return;
 811	}
 812	Interrupter interrupter(this);
 813	m_battlechip.flavor = flavor;
 814}
 815#endif
 816
 817void CoreController::setAVStream(mAVStream* stream) {
 818	Interrupter interrupter(this);
 819	m_threadContext.core->setAVStream(m_threadContext.core, stream);
 820}
 821
 822void CoreController::clearAVStream() {
 823	Interrupter interrupter(this);
 824	m_threadContext.core->setAVStream(m_threadContext.core, nullptr);
 825}
 826
 827void CoreController::clearOverride() {
 828	m_override.reset();
 829}
 830
 831void CoreController::startVideoLog(const QString& path, bool compression) {
 832	if (m_vl) {
 833		return;
 834	}
 835
 836	VFile* vf = VFileDevice::open(path, O_WRONLY | O_CREAT | O_TRUNC);
 837	if (!vf) {
 838		return;
 839	}
 840	startVideoLog(vf);
 841}
 842
 843void CoreController::startVideoLog(VFile* vf, bool compression) {
 844	if (m_vl || !vf) {
 845		return;
 846	}
 847
 848	Interrupter interrupter(this);
 849	m_vl = mVideoLogContextCreate(m_threadContext.core);
 850	m_vlVf = vf;
 851	mVideoLogContextSetOutput(m_vl, m_vlVf);
 852	mVideoLogContextSetCompression(m_vl, compression);
 853	mVideoLogContextWriteHeader(m_vl, m_threadContext.core);
 854}
 855
 856void CoreController::endVideoLog(bool closeVf) {
 857	if (!m_vl) {
 858		return;
 859	}
 860
 861	Interrupter interrupter(this);
 862	mVideoLogContextDestroy(m_threadContext.core, m_vl);
 863	if (m_vlVf && closeVf) {
 864		m_vlVf->close(m_vlVf);
 865		m_vlVf = nullptr;
 866	}
 867	m_vl = nullptr;
 868}
 869
 870void CoreController::setFramebufferHandle(int fb) {
 871	Interrupter interrupter(this);
 872	if (fb < 0) {
 873		if (!m_hwaccel) {
 874			return;
 875		}
 876		mCoreConfigSetIntValue(&m_threadContext.core->config, "hwaccelVideo", 0);
 877		m_threadContext.core->setVideoGLTex(m_threadContext.core, -1);
 878		m_hwaccel = false;
 879	} else {
 880		mCoreConfigSetIntValue(&m_threadContext.core->config, "hwaccelVideo", 1);
 881		m_threadContext.core->setVideoGLTex(m_threadContext.core, fb);
 882		if (m_hwaccel) {
 883			return;
 884		}
 885		m_hwaccel = true;
 886	}
 887	if (hasStarted()) {
 888		m_threadContext.core->reloadConfigOption(m_threadContext.core, "hwaccelVideo", NULL);
 889	}
 890}
 891
 892void CoreController::updateKeys() {
 893	int activeKeys = m_activeKeys | updateAutofire() | m_inputController->pollEvents();
 894	m_threadContext.core->setKeys(m_threadContext.core, activeKeys);
 895}
 896
 897int CoreController::updateAutofire() {
 898	int active = 0;
 899	for (int k = 0; k < 32; ++k) {
 900		if (!m_autofire[k]) {
 901			continue;
 902		}
 903		++m_autofireStatus[k];
 904		if (m_autofireStatus[k] >= 2 * m_autofireThreshold) {
 905			m_autofireStatus[k] = 0;
 906		} else if (m_autofireStatus[k] >= m_autofireThreshold) {
 907			active |= 1 << k;
 908		}
 909	}
 910	return active;
 911}
 912
 913void CoreController::finishFrame() {
 914	if (!m_hwaccel) {
 915		unsigned width, height;
 916		m_threadContext.core->desiredVideoDimensions(m_threadContext.core, &width, &height);
 917
 918		QMutexLocker locker(&m_bufferMutex);
 919		memcpy(m_completeBuffer.data(), m_activeBuffer.constData(), 256 * height * BYTES_PER_PIXEL);
 920	}
 921
 922	QMutexLocker locker(&m_actionMutex);
 923	QList<std::function<void ()>> frameActions(m_frameActions);
 924	m_frameActions.clear();
 925	for (auto& action : frameActions) {
 926		action();
 927	}
 928	updateKeys();
 929
 930	QMetaObject::invokeMethod(this, "frameAvailable");
 931}
 932
 933void CoreController::updateFastForward() {
 934	// If we have "Fast forward" checked in the menu (m_fastForwardForced)
 935	// or are holding the fast forward button (m_fastForward):
 936	if (m_fastForward || m_fastForwardForced) {
 937		if (m_fastForwardVolume >= 0) {
 938			m_threadContext.core->opts.volume = m_fastForwardVolume;
 939		}
 940		if (m_fastForwardMute >= 0) {
 941			m_threadContext.core->opts.mute = m_fastForwardMute;
 942		}
 943
 944		// If we aren't holding the fast forward button
 945		// then use the non "(held)" ratio
 946		if(!m_fastForward) {
 947			if (m_fastForwardRatio > 0) {
 948				m_threadContext.impl->sync.fpsTarget = m_fpsTarget * m_fastForwardRatio;
 949				setSync(true);
 950			}	else {
 951				setSync(false);
 952			}
 953		} else {
 954			// If we are holding the fast forward button,
 955			// then use the held ratio
 956			if (m_fastForwardHeldRatio > 0) {
 957				m_threadContext.impl->sync.fpsTarget = m_fpsTarget * m_fastForwardHeldRatio;
 958				setSync(true);
 959			} else {
 960				setSync(false);
 961			}
 962		}
 963	} else {
 964		if (!mCoreConfigGetIntValue(&m_threadContext.core->config, "volume", &m_threadContext.core->opts.volume)) {
 965			m_threadContext.core->opts.volume = 0x100;
 966		}
 967		int fakeBool = 0;
 968		mCoreConfigGetIntValue(&m_threadContext.core->config, "mute", &fakeBool);
 969		m_threadContext.core->opts.mute = fakeBool;
 970		m_threadContext.impl->sync.fpsTarget = m_fpsTarget;
 971		setSync(true);
 972	}
 973
 974	m_threadContext.core->reloadConfigOption(m_threadContext.core, NULL, NULL);
 975}
 976
 977CoreController::Interrupter::Interrupter(CoreController* parent, bool fromThread)
 978	: m_parent(parent)
 979{
 980	if (!m_parent->thread()->impl) {
 981		return;
 982	}
 983	if (!fromThread) {
 984		mCoreThreadInterrupt(m_parent->thread());
 985	} else {
 986		mCoreThreadInterruptFromThread(m_parent->thread());
 987	}
 988}
 989
 990CoreController::Interrupter::Interrupter(std::shared_ptr<CoreController> parent, bool fromThread)
 991	: m_parent(parent.get())
 992{
 993	if (!m_parent->thread()->impl) {
 994		return;
 995	}
 996	if (!fromThread) {
 997		mCoreThreadInterrupt(m_parent->thread());
 998	} else {
 999		mCoreThreadInterruptFromThread(m_parent->thread());
1000	}
1001}
1002
1003CoreController::Interrupter::Interrupter(const Interrupter& other)
1004	: m_parent(other.m_parent)
1005{
1006	if (!m_parent->thread()->impl) {
1007		return;
1008	}
1009	mCoreThreadInterrupt(m_parent->thread());
1010}
1011
1012CoreController::Interrupter::~Interrupter() {
1013	if (!m_parent->thread()->impl) {
1014		return;
1015	}
1016	mCoreThreadContinue(m_parent->thread());
1017}