all repos — mgba @ 205db2df90a06716acc2626095c6a53cb7cd38a9

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 mPLATFORM_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 mPLATFORM_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 mPLATFORM_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	QMutexLocker locker(&m_actionMutex);
 410	if (paused) {
 411		if (m_moreFrames < 0) {
 412			m_moreFrames = 1;
 413		}
 414	} else {
 415		m_moreFrames = -1;
 416		if (isPaused()) {
 417			mCoreThreadUnpause(&m_threadContext);
 418		}
 419	}
 420}
 421
 422void CoreController::frameAdvance() {
 423	QMutexLocker locker(&m_actionMutex);
 424	m_moreFrames = 1;
 425	if (isPaused()) {
 426		mCoreThreadUnpause(&m_threadContext);
 427	}
 428}
 429
 430void CoreController::addFrameAction(std::function<void ()> action) {
 431	QMutexLocker locker(&m_actionMutex);
 432	m_frameActions.append(action);
 433}
 434
 435void CoreController::setSync(bool sync) {
 436	if (sync) {
 437		m_threadContext.impl->sync.audioWait = m_audioSync;
 438		m_threadContext.impl->sync.videoFrameWait = m_videoSync;
 439	} else {
 440		m_threadContext.impl->sync.audioWait = false;
 441		m_threadContext.impl->sync.videoFrameWait = false;
 442	}
 443}
 444
 445void CoreController::setRewinding(bool rewind) {
 446	if (!m_threadContext.core->opts.rewindEnable) {
 447		return;
 448	}
 449	if (rewind && m_multiplayer && m_multiplayer->attached() > 1) {
 450		return;
 451	}
 452
 453	if (rewind && isPaused()) {
 454		setPaused(false);
 455		// TODO: restore autopausing
 456	}
 457	mCoreThreadSetRewinding(&m_threadContext, rewind);
 458}
 459
 460void CoreController::rewind(int states) {
 461	{
 462		Interrupter interrupter(this);
 463		if (!states) {
 464			states = INT_MAX;
 465		}
 466		for (int i = 0; i < states; ++i) {
 467			if (!mCoreRewindRestore(&m_threadContext.impl->rewind, m_threadContext.core)) {
 468				break;
 469			}
 470		}
 471	}
 472	emit frameAvailable();
 473	emit rewound();
 474}
 475
 476void CoreController::setFastForward(bool enable) {
 477	if (m_fastForward == enable) {
 478		return;
 479	}
 480	m_fastForward = enable;
 481	updateFastForward();
 482	emit fastForwardChanged(enable);
 483}
 484
 485void CoreController::forceFastForward(bool enable) {
 486	if (m_fastForwardForced == enable) {
 487		return;
 488	}
 489	m_fastForwardForced = enable;
 490	updateFastForward();
 491	emit fastForwardChanged(enable || m_fastForward);
 492}
 493
 494void CoreController::loadState(int slot) {
 495	if (slot > 0 && slot != m_stateSlot) {
 496		m_stateSlot = slot;
 497		m_backupSaveState.clear();
 498	}
 499	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 500		CoreController* controller = static_cast<CoreController*>(context->userData);
 501		if (!controller->m_backupLoadState.isOpen()) {
 502			controller->m_backupLoadState = VFileDevice::openMemory();
 503		}
 504		mCoreSaveStateNamed(context->core, controller->m_backupLoadState, controller->m_saveStateFlags);
 505		if (mCoreLoadState(context->core, controller->m_stateSlot, controller->m_loadStateFlags)) {
 506			emit controller->frameAvailable();
 507			emit controller->stateLoaded();
 508		}
 509	});
 510}
 511
 512void CoreController::loadState(const QString& path, int flags) {
 513	m_statePath = path;
 514	int savedFlags = m_loadStateFlags;
 515	if (flags != -1) {
 516		m_loadStateFlags = flags;
 517	}
 518	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 519		CoreController* controller = static_cast<CoreController*>(context->userData);
 520		VFile* vf = VFileDevice::open(controller->m_statePath, O_RDONLY);
 521		if (!vf) {
 522			return;
 523		}
 524		if (!controller->m_backupLoadState.isOpen()) {
 525			controller->m_backupLoadState = VFileDevice::openMemory();
 526		}
 527		mCoreSaveStateNamed(context->core, controller->m_backupLoadState, controller->m_saveStateFlags);
 528		if (mCoreLoadStateNamed(context->core, vf, controller->m_loadStateFlags)) {
 529			emit controller->frameAvailable();
 530			emit controller->stateLoaded();
 531		}
 532		vf->close(vf);
 533	});
 534	m_loadStateFlags = savedFlags;
 535}
 536
 537void CoreController::loadState(QIODevice* iodev, int flags) {
 538	m_stateVf = VFileDevice::wrap(iodev, QIODevice::ReadOnly);
 539	if (!m_stateVf) {
 540		return;
 541	}
 542	int savedFlags = m_loadStateFlags;
 543	if (flags != -1) {
 544		m_loadStateFlags = flags;
 545	}
 546	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 547		CoreController* controller = static_cast<CoreController*>(context->userData);
 548		VFile* vf = controller->m_stateVf;
 549		if (!vf) {
 550			return;
 551		}
 552		if (!controller->m_backupLoadState.isOpen()) {
 553			controller->m_backupLoadState = VFileDevice::openMemory();
 554		}
 555		mCoreSaveStateNamed(context->core, controller->m_backupLoadState, controller->m_saveStateFlags);
 556		if (mCoreLoadStateNamed(context->core, vf, controller->m_loadStateFlags)) {
 557			emit controller->frameAvailable();
 558			emit controller->stateLoaded();
 559		}
 560		vf->close(vf);
 561	});
 562	m_loadStateFlags = savedFlags;
 563}
 564
 565void CoreController::saveState(int slot) {
 566	if (slot > 0) {
 567		m_stateSlot = slot;
 568	}
 569	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 570		CoreController* controller = static_cast<CoreController*>(context->userData);
 571		VFile* vf = mCoreGetState(context->core, controller->m_stateSlot, false);
 572		if (vf) {
 573			controller->m_backupSaveState.resize(vf->size(vf));
 574			vf->read(vf, controller->m_backupSaveState.data(), controller->m_backupSaveState.size());
 575			vf->close(vf);
 576		}
 577		mCoreSaveState(context->core, controller->m_stateSlot, controller->m_saveStateFlags);
 578	});
 579}
 580
 581void CoreController::saveState(const QString& path, int flags) {
 582	m_statePath = path;
 583	int savedFlags = m_saveStateFlags;
 584	if (flags != -1) {
 585		m_saveStateFlags = flags;
 586	}
 587	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 588		CoreController* controller = static_cast<CoreController*>(context->userData);
 589		VFile* vf = VFileDevice::open(controller->m_statePath, O_RDONLY);
 590		if (vf) {
 591			controller->m_backupSaveState.resize(vf->size(vf));
 592			vf->read(vf, controller->m_backupSaveState.data(), controller->m_backupSaveState.size());
 593			vf->close(vf);
 594		}
 595		vf = VFileDevice::open(controller->m_statePath, O_WRONLY | O_CREAT | O_TRUNC);
 596		if (!vf) {
 597			return;
 598		}
 599		mCoreSaveStateNamed(context->core, vf, controller->m_saveStateFlags);
 600		vf->close(vf);
 601	});
 602	m_saveStateFlags = savedFlags;
 603}
 604
 605void CoreController::saveState(QIODevice* iodev, int flags) {
 606	m_stateVf = VFileDevice::wrap(iodev, QIODevice::WriteOnly | QIODevice::Truncate);
 607	if (!m_stateVf) {
 608		return;
 609	}
 610	int savedFlags = m_saveStateFlags;
 611	if (flags != -1) {
 612		m_saveStateFlags = flags;
 613	}
 614	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 615		CoreController* controller = static_cast<CoreController*>(context->userData);
 616		VFile* vf = controller->m_stateVf;
 617		if (!vf) {
 618			return;
 619		}
 620		mCoreSaveStateNamed(context->core, vf, controller->m_saveStateFlags);
 621		vf->close(vf);
 622	});
 623	m_saveStateFlags = savedFlags;
 624}
 625
 626void CoreController::loadBackupState() {
 627	if (!m_backupLoadState.isOpen()) {
 628		return;
 629	}
 630
 631	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 632		CoreController* controller = static_cast<CoreController*>(context->userData);
 633		controller->m_backupLoadState.seek(0);
 634		if (mCoreLoadStateNamed(context->core, controller->m_backupLoadState, controller->m_loadStateFlags)) {
 635			mLOG(STATUS, INFO, "Undid state load");
 636			controller->frameAvailable();
 637			controller->stateLoaded();
 638		}
 639		controller->m_backupLoadState.close();
 640	});
 641}
 642
 643void CoreController::saveBackupState() {
 644	if (m_backupSaveState.isEmpty()) {
 645		return;
 646	}
 647
 648	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 649		CoreController* controller = static_cast<CoreController*>(context->userData);
 650		VFile* vf = mCoreGetState(context->core, controller->m_stateSlot, true);
 651		if (vf) {
 652			vf->write(vf, controller->m_backupSaveState.constData(), controller->m_backupSaveState.size());
 653			vf->close(vf);
 654			mLOG(STATUS, INFO, "Undid state save");
 655		}
 656		controller->m_backupSaveState.clear();
 657	});
 658}
 659
 660void CoreController::loadSave(const QString& path, bool temporary) {
 661	m_resetActions.append([this, path, temporary]() {
 662		VFile* vf = VFileDevice::open(path, temporary ? O_RDONLY : O_RDWR);
 663		if (!vf) {
 664			LOG(QT, ERROR) << tr("Failed to open save file: %1").arg(path);
 665			return;
 666		}
 667
 668		if (temporary) {
 669			m_threadContext.core->loadTemporarySave(m_threadContext.core, vf);
 670		} else {
 671			m_threadContext.core->loadSave(m_threadContext.core, vf);
 672		}
 673	});
 674	reset();
 675}
 676
 677void CoreController::loadPatch(const QString& patchPath) {
 678	Interrupter interrupter(this);
 679	VFile* patch = VFileDevice::open(patchPath, O_RDONLY);
 680	if (patch) {
 681		m_threadContext.core->loadPatch(m_threadContext.core, patch);
 682		m_patched = true;
 683		patch->close(patch);
 684	}
 685	if (mCoreThreadHasStarted(&m_threadContext)) {
 686		reset();
 687	}
 688}
 689
 690void CoreController::replaceGame(const QString& path) {
 691	QFileInfo info(path);
 692	if (!info.isReadable()) {
 693		LOG(QT, ERROR) << tr("Failed to open game file: %1").arg(path);
 694		return;
 695	}
 696	QString fname = info.canonicalFilePath();
 697	Interrupter interrupter(this);
 698	mDirectorySetDetachBase(&m_threadContext.core->dirs);
 699	mCoreLoadFile(m_threadContext.core, fname.toUtf8().constData());
 700}
 701
 702void CoreController::yankPak() {
 703	Interrupter interrupter(this);
 704
 705	switch (platform()) {
 706#ifdef M_CORE_GBA
 707	case mPLATFORM_GBA:
 708		GBAYankROM(static_cast<GBA*>(m_threadContext.core->board));
 709		break;
 710#endif
 711#ifdef M_CORE_GB
 712	case mPLATFORM_GB:
 713		GBYankROM(static_cast<GB*>(m_threadContext.core->board));
 714		break;
 715#endif
 716	case mPLATFORM_NONE:
 717		LOG(QT, ERROR) << tr("Can't yank pack in unexpected platform!");
 718		break;
 719	}
 720}
 721
 722void CoreController::addKey(int key) {
 723	m_activeKeys |= 1 << key;
 724}
 725
 726void CoreController::clearKey(int key) {
 727	m_activeKeys &= ~(1 << key);
 728}
 729
 730void CoreController::setAutofire(int key, bool enable) {
 731	if (key >= 32 || key < 0) {
 732		return;
 733	}
 734
 735	m_autofire[key] = enable;
 736	m_autofireStatus[key] = 0;
 737}
 738
 739#ifdef USE_PNG
 740void CoreController::screenshot() {
 741	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 742		mCoreTakeScreenshot(context->core);
 743	});
 744}
 745#endif
 746
 747void CoreController::setRealTime() {
 748	m_threadContext.core->rtc.override = RTC_NO_OVERRIDE;
 749}
 750
 751void CoreController::setFixedTime(const QDateTime& time) {
 752	m_threadContext.core->rtc.override = RTC_FIXED;
 753	m_threadContext.core->rtc.value = time.toMSecsSinceEpoch();
 754}
 755
 756void CoreController::setFakeEpoch(const QDateTime& time) {
 757	m_threadContext.core->rtc.override = RTC_FAKE_EPOCH;
 758	m_threadContext.core->rtc.value = time.toMSecsSinceEpoch();
 759}
 760
 761void CoreController::scanCard(const QString& path) {
 762#ifdef M_CORE_GBA
 763	QImage image(path);
 764	if (image.isNull()) {
 765		QFile file(path);
 766		file.open(QIODevice::ReadOnly);
 767		m_eReaderData = file.read(2912);
 768	} else if (image.size() == QSize(989, 44)) {
 769		const uchar* bits = image.constBits();
 770		size_t size;
 771#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
 772		size = image.sizeInBytes();
 773#else
 774		size = image.byteCount();
 775#endif
 776		m_eReaderData.setRawData(reinterpret_cast<const char*>(bits), size);
 777	}
 778
 779	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* thread) {
 780		CoreController* controller = static_cast<CoreController*>(thread->userData);
 781		GBAEReaderQueueCard(static_cast<GBA*>(thread->core->board), controller->m_eReaderData.constData(), controller->m_eReaderData.size());
 782	});
 783#endif
 784}
 785
 786
 787void CoreController::importSharkport(const QString& path) {
 788#ifdef M_CORE_GBA
 789	if (platform() != mPLATFORM_GBA) {
 790		return;
 791	}
 792	VFile* vf = VFileDevice::open(path, O_RDONLY);
 793	if (!vf) {
 794		LOG(QT, ERROR) << tr("Failed to open snapshot file for reading: %1").arg(path);
 795		return;
 796	}
 797	Interrupter interrupter(this);
 798	GBASavedataImportSharkPort(static_cast<GBA*>(m_threadContext.core->board), vf, false);
 799	vf->close(vf);
 800#endif
 801}
 802
 803void CoreController::exportSharkport(const QString& path) {
 804#ifdef M_CORE_GBA
 805	if (platform() != mPLATFORM_GBA) {
 806		return;
 807	}
 808	VFile* vf = VFileDevice::open(path, O_WRONLY | O_CREAT | O_TRUNC);
 809	if (!vf) {
 810		LOG(QT, ERROR) << tr("Failed to open snapshot file for writing: %1").arg(path);
 811		return;
 812	}
 813	Interrupter interrupter(this);
 814	GBASavedataExportSharkPort(static_cast<GBA*>(m_threadContext.core->board), vf);
 815	vf->close(vf);
 816#endif
 817}
 818
 819#ifdef M_CORE_GB
 820void CoreController::attachPrinter() {
 821	if (platform() != mPLATFORM_GB) {
 822		return;
 823	}
 824	GB* gb = static_cast<GB*>(m_threadContext.core->board);
 825	clearMultiplayerController();
 826	GBPrinterCreate(&m_printer.d);
 827	m_printer.parent = this;
 828	m_printer.d.print = [](GBPrinter* printer, int height, const uint8_t* data) {
 829		QGBPrinter* qPrinter = reinterpret_cast<QGBPrinter*>(printer);
 830		QImage image(GB_VIDEO_HORIZONTAL_PIXELS, height, QImage::Format_Indexed8);
 831		QVector<QRgb> colors;
 832		colors.append(qRgb(0xF8, 0xF8, 0xF8));
 833		colors.append(qRgb(0xA8, 0xA8, 0xA8));
 834		colors.append(qRgb(0x50, 0x50, 0x50));
 835		colors.append(qRgb(0x00, 0x00, 0x00));
 836		image.setColorTable(colors);
 837		for (int y = 0; y < height; ++y) {
 838			for (int x = 0; x < GB_VIDEO_HORIZONTAL_PIXELS; x += 4) {
 839				uint8_t byte = data[(x + y * GB_VIDEO_HORIZONTAL_PIXELS) / 4];
 840				image.setPixel(x + 0, y, (byte & 0xC0) >> 6);
 841				image.setPixel(x + 1, y, (byte & 0x30) >> 4);
 842				image.setPixel(x + 2, y, (byte & 0x0C) >> 2);
 843				image.setPixel(x + 3, y, (byte & 0x03) >> 0);
 844			}
 845		}
 846		QMetaObject::invokeMethod(qPrinter->parent, "imagePrinted", Q_ARG(const QImage&, image));
 847	};
 848	Interrupter interrupter(this);
 849	GBSIOSetDriver(&gb->sio, &m_printer.d.d);
 850}
 851
 852void CoreController::detachPrinter() {
 853	if (platform() != mPLATFORM_GB) {
 854		return;
 855	}
 856	Interrupter interrupter(this);
 857	GB* gb = static_cast<GB*>(m_threadContext.core->board);
 858	GBPrinterDonePrinting(&m_printer.d);
 859	GBSIOSetDriver(&gb->sio, nullptr);
 860}
 861
 862void CoreController::endPrint() {
 863	if (platform() != mPLATFORM_GB) {
 864		return;
 865	}
 866	Interrupter interrupter(this);
 867	GBPrinterDonePrinting(&m_printer.d);
 868}
 869#endif
 870
 871#ifdef M_CORE_GBA
 872void CoreController::attachBattleChipGate() {
 873	if (platform() != mPLATFORM_GBA) {
 874		return;
 875	}
 876	Interrupter interrupter(this);
 877	clearMultiplayerController();
 878	GBASIOBattlechipGateCreate(&m_battlechip);
 879	m_threadContext.core->setPeripheral(m_threadContext.core, mPERIPH_GBA_BATTLECHIP_GATE, &m_battlechip);
 880}
 881
 882void CoreController::detachBattleChipGate() {
 883	if (platform() != mPLATFORM_GBA) {
 884		return;
 885	}
 886	Interrupter interrupter(this);
 887	m_threadContext.core->setPeripheral(m_threadContext.core, mPERIPH_GBA_BATTLECHIP_GATE, nullptr);
 888}
 889
 890void CoreController::setBattleChipId(uint16_t id) {
 891	if (platform() != mPLATFORM_GBA) {
 892		return;
 893	}
 894	Interrupter interrupter(this);
 895	m_battlechip.chipId = id;
 896}
 897
 898void CoreController::setBattleChipFlavor(int flavor) {
 899	if (platform() != mPLATFORM_GBA) {
 900		return;
 901	}
 902	Interrupter interrupter(this);
 903	m_battlechip.flavor = flavor;
 904}
 905#endif
 906
 907void CoreController::setAVStream(mAVStream* stream) {
 908	Interrupter interrupter(this);
 909	m_threadContext.core->setAVStream(m_threadContext.core, stream);
 910}
 911
 912void CoreController::clearAVStream() {
 913	Interrupter interrupter(this);
 914	m_threadContext.core->setAVStream(m_threadContext.core, nullptr);
 915}
 916
 917void CoreController::clearOverride() {
 918	m_override.reset();
 919}
 920
 921void CoreController::startVideoLog(const QString& path, bool compression) {
 922	if (m_vl) {
 923		return;
 924	}
 925
 926	VFile* vf = VFileDevice::open(path, O_WRONLY | O_CREAT | O_TRUNC);
 927	if (!vf) {
 928		return;
 929	}
 930	startVideoLog(vf, compression);
 931}
 932
 933void CoreController::startVideoLog(VFile* vf, bool compression) {
 934	if (m_vl || !vf) {
 935		return;
 936	}
 937
 938	Interrupter interrupter(this);
 939	m_vl = mVideoLogContextCreate(m_threadContext.core);
 940	m_vlVf = vf;
 941	mVideoLogContextSetOutput(m_vl, m_vlVf);
 942	mVideoLogContextSetCompression(m_vl, compression);
 943	mVideoLogContextWriteHeader(m_vl, m_threadContext.core);
 944}
 945
 946void CoreController::endVideoLog(bool closeVf) {
 947	if (!m_vl) {
 948		return;
 949	}
 950
 951	Interrupter interrupter(this);
 952	mVideoLogContextDestroy(m_threadContext.core, m_vl, closeVf);
 953	if (closeVf) {
 954		m_vlVf = nullptr;
 955	}
 956	m_vl = nullptr;
 957}
 958
 959void CoreController::setFramebufferHandle(int fb) {
 960	Interrupter interrupter(this);
 961	if (fb < 0) {
 962		if (!m_hwaccel) {
 963			return;
 964		}
 965		mCoreConfigSetIntValue(&m_threadContext.core->config, "hwaccelVideo", 0);
 966		m_threadContext.core->setVideoGLTex(m_threadContext.core, -1);
 967		m_hwaccel = false;
 968	} else {
 969		mCoreConfigSetIntValue(&m_threadContext.core->config, "hwaccelVideo", 1);
 970		m_threadContext.core->setVideoGLTex(m_threadContext.core, fb);
 971		if (m_hwaccel) {
 972			return;
 973		}
 974		m_hwaccel = true;
 975	}
 976	if (hasStarted()) {
 977		m_threadContext.core->reloadConfigOption(m_threadContext.core, "hwaccelVideo", NULL);
 978		if (!m_hwaccel) {
 979			m_threadContext.core->setVideoBuffer(m_threadContext.core, reinterpret_cast<color_t*>(m_activeBuffer.data()), screenDimensions().width());
 980		}
 981	}
 982}
 983
 984void CoreController::updateKeys() {
 985	int activeKeys = m_activeKeys | updateAutofire() | m_inputController->pollEvents();
 986	m_threadContext.core->setKeys(m_threadContext.core, activeKeys);
 987}
 988
 989int CoreController::updateAutofire() {
 990	int active = 0;
 991	for (int k = 0; k < 32; ++k) {
 992		if (!m_autofire[k]) {
 993			continue;
 994		}
 995		++m_autofireStatus[k];
 996		if (m_autofireStatus[k] >= 2 * m_autofireThreshold) {
 997			m_autofireStatus[k] = 0;
 998		} else if (m_autofireStatus[k] >= m_autofireThreshold) {
 999			active |= 1 << k;
1000		}
1001	}
1002	return active;
1003}
1004
1005void CoreController::finishFrame() {
1006	if (!m_hwaccel) {
1007		unsigned width, height;
1008		m_threadContext.core->desiredVideoDimensions(m_threadContext.core, &width, &height);
1009
1010		QMutexLocker locker(&m_bufferMutex);
1011		memcpy(m_completeBuffer.data(), m_activeBuffer.constData(), width * height * BYTES_PER_PIXEL);
1012	}
1013
1014	{
1015		QMutexLocker locker(&m_actionMutex);
1016		QList<std::function<void ()>> frameActions(m_frameActions);
1017		m_frameActions.clear();
1018		for (auto& action : frameActions) {
1019			action();
1020		}
1021		if (m_moreFrames > 0) {
1022			--m_moreFrames;
1023			if (!m_moreFrames) {
1024				mCoreThreadPauseFromThread(&m_threadContext);
1025			}
1026		}
1027	}
1028	updateKeys();
1029
1030	QMetaObject::invokeMethod(this, "frameAvailable");
1031}
1032
1033void CoreController::updateFastForward() {
1034	// If we have "Fast forward" checked in the menu (m_fastForwardForced)
1035	// or are holding the fast forward button (m_fastForward):
1036	if (m_fastForward || m_fastForwardForced) {
1037		if (m_fastForwardVolume >= 0) {
1038			m_threadContext.core->opts.volume = m_fastForwardVolume;
1039		}
1040		if (m_fastForwardMute >= 0) {
1041			m_threadContext.core->opts.mute = m_fastForwardMute;
1042		}
1043
1044		// If we aren't holding the fast forward button
1045		// then use the non "(held)" ratio
1046		if(!m_fastForward) {
1047			if (m_fastForwardRatio > 0) {
1048				m_threadContext.impl->sync.fpsTarget = m_fpsTarget * m_fastForwardRatio;
1049				setSync(true);
1050			}	else {
1051				setSync(false);
1052			}
1053		} else {
1054			// If we are holding the fast forward button,
1055			// then use the held ratio
1056			if (m_fastForwardHeldRatio > 0) {
1057				m_threadContext.impl->sync.fpsTarget = m_fpsTarget * m_fastForwardHeldRatio;
1058				setSync(true);
1059			} else {
1060				setSync(false);
1061			}
1062		}
1063	} else {
1064		if (!mCoreConfigGetIntValue(&m_threadContext.core->config, "volume", &m_threadContext.core->opts.volume)) {
1065			m_threadContext.core->opts.volume = 0x100;
1066		}
1067		int fakeBool = 0;
1068		mCoreConfigGetIntValue(&m_threadContext.core->config, "mute", &fakeBool);
1069		m_threadContext.core->opts.mute = fakeBool;
1070		m_threadContext.impl->sync.fpsTarget = m_fpsTarget;
1071		setSync(true);
1072	}
1073
1074	m_threadContext.core->reloadConfigOption(m_threadContext.core, NULL, NULL);
1075}
1076
1077CoreController::Interrupter::Interrupter(CoreController* parent)
1078	: m_parent(parent)
1079{
1080	if (!m_parent->thread()->impl) {
1081		return;
1082	}
1083	if (mCoreThreadGet() != m_parent->thread()) {
1084		mCoreThreadInterrupt(m_parent->thread());
1085	} else {
1086		mCoreThreadInterruptFromThread(m_parent->thread());
1087	}
1088}
1089
1090CoreController::Interrupter::Interrupter(std::shared_ptr<CoreController> parent)
1091	: m_parent(parent.get())
1092{
1093	if (!m_parent->thread()->impl) {
1094		return;
1095	}
1096	if (mCoreThreadGet() != m_parent->thread()) {
1097		mCoreThreadInterrupt(m_parent->thread());
1098	} else {
1099		mCoreThreadInterruptFromThread(m_parent->thread());
1100	}
1101}
1102
1103CoreController::Interrupter::Interrupter(const Interrupter& other)
1104	: m_parent(other.m_parent)
1105{
1106	if (!m_parent->thread()->impl) {
1107		return;
1108	}
1109	mCoreThreadInterrupt(m_parent->thread());
1110}
1111
1112CoreController::Interrupter::~Interrupter() {
1113	if (!m_parent->thread()->impl) {
1114		return;
1115	}
1116	mCoreThreadContinue(m_parent->thread());
1117}