all repos — mgba @ 61f8f1469421b7460848d71b07466962cf681050

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