all repos — mgba @ 13d3e1dfecb6393c0f3f23e22b2e9e88afe4911a

mGBA Game Boy Advance Emulator

src/gb/core.c (view raw)

   1/* Copyright (c) 2013-2016 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 <mgba/gb/core.h>
   7
   8#include <mgba/core/core.h>
   9#include <mgba/internal/debugger/symbols.h>
  10#include <mgba/internal/gb/cheats.h>
  11#include <mgba/internal/gb/debugger/symbols.h>
  12#include <mgba/internal/gb/extra/cli.h>
  13#include <mgba/internal/gb/io.h>
  14#include <mgba/internal/gb/gb.h>
  15#include <mgba/internal/gb/mbc.h>
  16#include <mgba/internal/gb/overrides.h>
  17#include <mgba/internal/gb/renderers/software.h>
  18#include <mgba/internal/gb/renderers/proxy.h>
  19#include <mgba/internal/gb/serialize.h>
  20#include <mgba/internal/lr35902/lr35902.h>
  21#include <mgba/internal/lr35902/debugger/debugger.h>
  22#include <mgba-util/crc32.h>
  23#include <mgba-util/memory.h>
  24#include <mgba-util/patch.h>
  25#include <mgba-util/vfs.h>
  26
  27static const struct mCoreChannelInfo _GBVideoLayers[] = {
  28	{ 0, "bg", "Background", NULL },
  29	{ 1, "obj", "Objects", NULL },
  30	{ 2, "win", "Window", NULL },
  31};
  32
  33static const struct mCoreChannelInfo _GBAudioChannels[] = {
  34	{ 0, "ch1", "Channel 1", "Square/Sweep" },
  35	{ 1, "ch2", "Channel 2", "Square" },
  36	{ 2, "ch3", "Channel 3", "PCM" },
  37	{ 3, "ch4", "Channel 4", "Noise" },
  38};
  39
  40static const struct LR35902Segment _GBSegments[] = {
  41	{ .name = "ROM", .start = GB_BASE_CART_BANK1, .end = GB_BASE_VRAM },
  42	{ .name = "RAM", .start = GB_BASE_EXTERNAL_RAM, .end = GB_BASE_WORKING_RAM_BANK0 },
  43	{ 0 }
  44};
  45
  46static const struct LR35902Segment _GBCSegments[] = {
  47	{ .name = "ROM", .start = GB_BASE_CART_BANK1, .end = GB_BASE_VRAM },
  48	{ .name = "RAM", .start = GB_BASE_EXTERNAL_RAM, .end = GB_BASE_WORKING_RAM_BANK0 },
  49	{ .name = "WRAM", .start = GB_BASE_WORKING_RAM_BANK1, .end = 0xE000 },
  50	{ .name = "VRAM", .start = GB_BASE_VRAM, .end = GB_BASE_EXTERNAL_RAM },
  51	{ 0 }
  52};
  53
  54static const struct mCoreMemoryBlock _GBMemoryBlocks[] = {
  55	{ -1, "mem", "All", "All", 0, 0x10000, 0x10000, mCORE_MEMORY_VIRTUAL },
  56	{ GB_REGION_CART_BANK0, "cart0", "ROM Bank", "Game Pak (32kiB)", GB_BASE_CART_BANK0, GB_SIZE_CART_BANK0 * 2, 0x800000, mCORE_MEMORY_READ | mCORE_MEMORY_MAPPED, 511 },
  57	{ GB_REGION_VRAM, "vram", "VRAM", "Video RAM (8kiB)", GB_BASE_VRAM, GB_BASE_VRAM + GB_SIZE_VRAM, GB_SIZE_VRAM, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED },
  58	{ GB_REGION_EXTERNAL_RAM, "sram", "SRAM", "External RAM (8kiB)", GB_BASE_EXTERNAL_RAM, GB_BASE_EXTERNAL_RAM + GB_SIZE_EXTERNAL_RAM, GB_SIZE_EXTERNAL_RAM * 4, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED, 3 },
  59	{ GB_REGION_WORKING_RAM_BANK0, "wram", "WRAM", "Working RAM (8kiB)", GB_BASE_WORKING_RAM_BANK0, GB_BASE_WORKING_RAM_BANK0 + GB_SIZE_WORKING_RAM_BANK0 * 2 , GB_SIZE_WORKING_RAM_BANK0 * 2, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED },
  60	{ GB_BASE_OAM, "oam", "OAM", "OBJ Attribute Memory", GB_BASE_OAM, GB_BASE_OAM + GB_SIZE_OAM, GB_SIZE_OAM, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED },
  61	{ GB_BASE_IO, "io", "MMIO", "Memory-Mapped I/O", GB_BASE_IO, GB_BASE_IO + GB_SIZE_IO, GB_SIZE_IO, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED },
  62	{ GB_BASE_HRAM, "hram", "HRAM", "High RAM", GB_BASE_HRAM, GB_BASE_HRAM + GB_SIZE_HRAM, GB_SIZE_HRAM, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED },
  63};
  64
  65static const struct mCoreMemoryBlock _GBCMemoryBlocks[] = {
  66	{ -1, "mem", "All", "All", 0, 0x10000, 0x10000, mCORE_MEMORY_VIRTUAL },
  67	{ GB_REGION_CART_BANK0, "cart0", "ROM Bank", "Game Pak (32kiB)", GB_BASE_CART_BANK0, GB_SIZE_CART_BANK0 * 2, 0x800000, mCORE_MEMORY_READ | mCORE_MEMORY_MAPPED, 511 },
  68	{ GB_REGION_VRAM, "vram", "VRAM", "Video RAM (8kiB)", GB_BASE_VRAM, GB_BASE_VRAM + GB_SIZE_VRAM, GB_SIZE_VRAM * 2, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED, 1 },
  69	{ GB_REGION_EXTERNAL_RAM, "sram", "SRAM", "External RAM (8kiB)", GB_BASE_EXTERNAL_RAM, GB_BASE_EXTERNAL_RAM + GB_SIZE_EXTERNAL_RAM, GB_SIZE_EXTERNAL_RAM * 4, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED, 3 },
  70	{ GB_REGION_WORKING_RAM_BANK0, "wram", "WRAM", "Working RAM (8kiB)", GB_BASE_WORKING_RAM_BANK0, GB_BASE_WORKING_RAM_BANK0 + GB_SIZE_WORKING_RAM_BANK0 * 2, GB_SIZE_WORKING_RAM_BANK0 * 8, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED, 7 },
  71	{ GB_BASE_OAM, "oam", "OAM", "OBJ Attribute Memory", GB_BASE_OAM, GB_BASE_OAM + GB_SIZE_OAM, GB_SIZE_OAM, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED },
  72	{ GB_BASE_IO, "io", "MMIO", "Memory-Mapped I/O", GB_BASE_IO, GB_BASE_IO + GB_SIZE_IO, GB_SIZE_IO, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED },
  73	{ GB_BASE_HRAM, "hram", "HRAM", "High RAM", GB_BASE_HRAM, GB_BASE_HRAM + GB_SIZE_HRAM, GB_SIZE_HRAM, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED },
  74};
  75
  76struct mVideoLogContext;
  77struct GBCore {
  78	struct mCore d;
  79	struct GBVideoSoftwareRenderer renderer;
  80	struct GBVideoProxyRenderer proxyRenderer;
  81	struct mVideoLogContext* logContext;
  82	struct mCoreCallbacks logCallbacks;
  83	uint8_t keys;
  84	struct mCPUComponent* components[CPU_COMPONENT_MAX];
  85	const struct Configuration* overrides;
  86	struct mDebuggerPlatform* debuggerPlatform;
  87	struct mCheatDevice* cheatDevice;
  88};
  89
  90static bool _GBCoreInit(struct mCore* core) {
  91	struct GBCore* gbcore = (struct GBCore*) core;
  92
  93	struct LR35902Core* cpu = anonymousMemoryMap(sizeof(struct LR35902Core));
  94	struct GB* gb = anonymousMemoryMap(sizeof(struct GB));
  95	if (!cpu || !gb) {
  96		free(cpu);
  97		free(gb);
  98		return false;
  99	}
 100	core->cpu = cpu;
 101	core->board = gb;
 102	gbcore->overrides = NULL;
 103	gbcore->debuggerPlatform = NULL;
 104	gbcore->cheatDevice = NULL;
 105
 106	GBCreate(gb);
 107	memset(gbcore->components, 0, sizeof(gbcore->components));
 108	LR35902SetComponents(cpu, &gb->d, CPU_COMPONENT_MAX, gbcore->components);
 109	LR35902Init(cpu);
 110	mRTCGenericSourceInit(&core->rtc, core);
 111	gb->memory.rtc = &core->rtc.d;
 112
 113	GBVideoSoftwareRendererCreate(&gbcore->renderer);
 114	gbcore->renderer.outputBuffer = NULL;
 115
 116	gbcore->keys = 0;
 117	gb->keySource = &gbcore->keys;
 118
 119#if !defined(MINIMAL_CORE) || MINIMAL_CORE < 2
 120	mDirectorySetInit(&core->dirs);
 121#endif
 122	
 123	return true;
 124}
 125
 126static void _GBCoreDeinit(struct mCore* core) {
 127	LR35902Deinit(core->cpu);
 128	GBDestroy(core->board);
 129	mappedMemoryFree(core->cpu, sizeof(struct LR35902Core));
 130	mappedMemoryFree(core->board, sizeof(struct GB));
 131#if defined USE_DEBUGGERS && (!defined(MINIMAL_CORE) || MINIMAL_CORE < 2)
 132	mDirectorySetDeinit(&core->dirs);
 133	if (core->symbolTable) {
 134		mDebuggerSymbolTableDestroy(core->symbolTable);
 135	}
 136#endif
 137
 138	struct GBCore* gbcore = (struct GBCore*) core;
 139	free(gbcore->debuggerPlatform);
 140	if (gbcore->cheatDevice) {
 141		mCheatDeviceDestroy(gbcore->cheatDevice);
 142	}
 143	free(gbcore->cheatDevice);
 144	mCoreConfigFreeOpts(&core->opts);
 145	free(core);
 146}
 147
 148static enum mPlatform _GBCorePlatform(const struct mCore* core) {
 149	UNUSED(core);
 150	return PLATFORM_GB;
 151}
 152
 153static void _GBCoreSetSync(struct mCore* core, struct mCoreSync* sync) {
 154	struct GB* gb = core->board;
 155	gb->sync = sync;
 156}
 157
 158static void _GBCoreLoadConfig(struct mCore* core, const struct mCoreConfig* config) {
 159	UNUSED(config);
 160
 161	struct GB* gb = core->board;
 162	if (core->opts.mute) {
 163		gb->audio.masterVolume = 0;
 164	} else {
 165		gb->audio.masterVolume = core->opts.volume;
 166	}
 167	gb->video.frameskip = core->opts.frameskip;
 168
 169	int color;
 170	if (mCoreConfigGetIntValue(config, "gb.pal[0]", &color)) {
 171		GBVideoSetPalette(&gb->video, 0, color);
 172	}
 173	if (mCoreConfigGetIntValue(config, "gb.pal[1]", &color)) {
 174		GBVideoSetPalette(&gb->video, 1, color);
 175	}
 176	if (mCoreConfigGetIntValue(config, "gb.pal[2]", &color)) {
 177		GBVideoSetPalette(&gb->video, 2, color);
 178	}
 179	if (mCoreConfigGetIntValue(config, "gb.pal[3]", &color)) {
 180		GBVideoSetPalette(&gb->video, 3, color);
 181	}
 182
 183	mCoreConfigCopyValue(&core->config, config, "gb.bios");
 184	mCoreConfigCopyValue(&core->config, config, "sgb.bios");
 185	mCoreConfigCopyValue(&core->config, config, "gbc.bios");
 186	mCoreConfigCopyValue(&core->config, config, "gb.model");
 187	mCoreConfigCopyValue(&core->config, config, "sgb.model");
 188	mCoreConfigCopyValue(&core->config, config, "cgb.model");
 189
 190	int fakeBool;
 191	if (mCoreConfigGetIntValue(config, "sgb.borders", &fakeBool)) {
 192		gb->video.sgbBorders = fakeBool;
 193	}
 194
 195#if !defined(MINIMAL_CORE) || MINIMAL_CORE < 2
 196	struct GBCore* gbcore = (struct GBCore*) core;
 197	gbcore->overrides = mCoreConfigGetOverridesConst(config);
 198#endif
 199}
 200
 201static void _GBCoreDesiredVideoDimensions(struct mCore* core, unsigned* width, unsigned* height) {
 202	struct GB* gb = core->board;
 203	if (gb && (gb->model != GB_MODEL_SGB || !gb->video.sgbBorders)) {
 204		*width = GB_VIDEO_HORIZONTAL_PIXELS;
 205		*height = GB_VIDEO_VERTICAL_PIXELS;
 206	} else {
 207		*width = 256;
 208		*height = 224;
 209	}
 210}
 211
 212static void _GBCoreSetVideoBuffer(struct mCore* core, color_t* buffer, size_t stride) {
 213	struct GBCore* gbcore = (struct GBCore*) core;
 214	gbcore->renderer.outputBuffer = buffer;
 215	gbcore->renderer.outputBufferStride = stride;
 216}
 217
 218static void _GBCoreGetPixels(struct mCore* core, const void** buffer, size_t* stride) {
 219	struct GBCore* gbcore = (struct GBCore*) core;
 220	gbcore->renderer.d.getPixels(&gbcore->renderer.d, stride, buffer);
 221}
 222
 223static void _GBCorePutPixels(struct mCore* core, const void* buffer, size_t stride) {
 224	struct GBCore* gbcore = (struct GBCore*) core;
 225	gbcore->renderer.d.putPixels(&gbcore->renderer.d, stride, buffer);
 226}
 227
 228static struct blip_t* _GBCoreGetAudioChannel(struct mCore* core, int ch) {
 229	struct GB* gb = core->board;
 230	switch (ch) {
 231	case 0:
 232		return gb->audio.left;
 233	case 1:
 234		return gb->audio.right;
 235	default:
 236		return NULL;
 237	}
 238}
 239
 240static void _GBCoreSetAudioBufferSize(struct mCore* core, size_t samples) {
 241	struct GB* gb = core->board;
 242	GBAudioResizeBuffer(&gb->audio, samples);
 243}
 244
 245static size_t _GBCoreGetAudioBufferSize(struct mCore* core) {
 246	struct GB* gb = core->board;
 247	return gb->audio.samples;
 248}
 249
 250static void _GBCoreAddCoreCallbacks(struct mCore* core, struct mCoreCallbacks* coreCallbacks) {
 251	struct GB* gb = core->board;
 252	*mCoreCallbacksListAppend(&gb->coreCallbacks) = *coreCallbacks;
 253}
 254
 255static void _GBCoreClearCoreCallbacks(struct mCore* core) {
 256	struct GB* gb = core->board;
 257	mCoreCallbacksListClear(&gb->coreCallbacks);
 258}
 259
 260static void _GBCoreSetAVStream(struct mCore* core, struct mAVStream* stream) {
 261	struct GB* gb = core->board;
 262	gb->stream = stream;
 263	if (stream && stream->videoDimensionsChanged) {
 264		stream->videoDimensionsChanged(stream, GB_VIDEO_HORIZONTAL_PIXELS, GB_VIDEO_VERTICAL_PIXELS);
 265	}
 266}
 267
 268static bool _GBCoreLoadROM(struct mCore* core, struct VFile* vf) {
 269	return GBLoadROM(core->board, vf);
 270}
 271
 272static bool _GBCoreLoadBIOS(struct mCore* core, struct VFile* vf, int type) {
 273	UNUSED(type);
 274	GBLoadBIOS(core->board, vf);
 275	return true;
 276}
 277
 278static bool _GBCoreLoadSave(struct mCore* core, struct VFile* vf) {
 279	return GBLoadSave(core->board, vf);
 280}
 281
 282static bool _GBCoreLoadTemporarySave(struct mCore* core, struct VFile* vf) {
 283	struct GB* gb = core->board;
 284	GBSavedataMask(gb, vf, false);
 285	return true; // TODO: Return a real value
 286}
 287
 288static bool _GBCoreLoadPatch(struct mCore* core, struct VFile* vf) {
 289	if (!vf) {
 290		return false;
 291	}
 292	struct Patch patch;
 293	if (!loadPatch(vf, &patch)) {
 294		return false;
 295	}
 296	GBApplyPatch(core->board, &patch);
 297	return true;
 298}
 299
 300static void _GBCoreUnloadROM(struct mCore* core) {
 301	struct GBCore* gbcore = (struct GBCore*) core;
 302	struct LR35902Core* cpu = core->cpu;
 303	if (gbcore->cheatDevice) {
 304		LR35902HotplugDetach(cpu, CPU_COMPONENT_CHEAT_DEVICE);
 305		cpu->components[CPU_COMPONENT_CHEAT_DEVICE] = NULL;
 306		mCheatDeviceDestroy(gbcore->cheatDevice);
 307		gbcore->cheatDevice = NULL;
 308	}
 309	return GBUnloadROM(core->board);
 310}
 311
 312static void _GBCoreChecksum(const struct mCore* core, void* data, enum mCoreChecksumType type) {
 313	struct GB* gb = (struct GB*) core->board;
 314	switch (type) {
 315	case CHECKSUM_CRC32:
 316		memcpy(data, &gb->romCrc32, sizeof(gb->romCrc32));
 317		break;
 318	}
 319	return;
 320}
 321
 322static void _GBCoreReset(struct mCore* core) {
 323	struct GBCore* gbcore = (struct GBCore*) core;
 324	struct GB* gb = (struct GB*) core->board;
 325	if (gbcore->renderer.outputBuffer) {
 326		GBVideoAssociateRenderer(&gb->video, &gbcore->renderer.d);
 327	}
 328
 329	if (gb->memory.rom) {
 330		struct GBCartridgeOverride override;
 331		const struct GBCartridge* cart = (const struct GBCartridge*) &gb->memory.rom[0x100];
 332		override.headerCrc32 = doCrc32(cart, sizeof(*cart));
 333		if (GBOverrideFind(gbcore->overrides, &override)) {
 334			GBOverrideApply(gb, &override);
 335		}
 336	}
 337
 338	const char* modelGB = mCoreConfigGetValue(&core->config, "gb.model");
 339	const char* modelCGB = mCoreConfigGetValue(&core->config, "cgb.model");
 340	const char* modelSGB = mCoreConfigGetValue(&core->config, "sgb.model");
 341	if (modelGB || modelCGB || modelSGB) {
 342		GBDetectModel(gb);
 343		if (gb->model == GB_MODEL_DMG && modelGB) {
 344			gb->model = GBNameToModel(modelGB);
 345		} else if (gb->model == GB_MODEL_CGB && modelCGB) {
 346			gb->model = GBNameToModel(modelCGB);
 347		} else if (gb->model == GB_MODEL_SGB && modelSGB) {
 348			gb->model = GBNameToModel(modelSGB);
 349		}
 350	}
 351
 352#if !defined(MINIMAL_CORE) || MINIMAL_CORE < 2
 353	if (!gb->biosVf && core->opts.useBios) {
 354		struct VFile* bios = NULL;
 355		bool found = false;
 356		if (core->opts.bios) {
 357			bios = VFileOpen(core->opts.bios, O_RDONLY);
 358			if (bios && GBIsBIOS(bios)) {
 359				found = true;
 360			} else if (bios) {
 361				bios->close(bios);
 362				bios = NULL;
 363			}
 364		}
 365		if (!found) {
 366			GBDetectModel(gb);
 367			const char* configPath = NULL;
 368
 369			switch (gb->model) {
 370			case GB_MODEL_DMG:
 371			case GB_MODEL_MGB: // TODO
 372				configPath = mCoreConfigGetValue(&core->config, "gb.bios");
 373				break;
 374			case GB_MODEL_SGB:
 375			case GB_MODEL_SGB2: // TODO
 376				configPath = mCoreConfigGetValue(&core->config, "sgb.bios");
 377				break;
 378			case GB_MODEL_CGB:
 379			case GB_MODEL_AGB:
 380				configPath = mCoreConfigGetValue(&core->config, "gbc.bios");
 381				break;
 382			default:
 383				break;
 384			};
 385			if (configPath) {
 386				bios = VFileOpen(configPath, O_RDONLY);
 387			}
 388			if (bios && GBIsBIOS(bios)) {
 389				found = true;
 390			} else if (bios) {
 391				bios->close(bios);
 392				bios = NULL;
 393			}
 394		}
 395		if (!found) {
 396			char path[PATH_MAX];
 397			mCoreConfigDirectory(path, PATH_MAX);
 398			switch (gb->model) {
 399			case GB_MODEL_DMG:
 400			case GB_MODEL_MGB: // TODO
 401				strncat(path, PATH_SEP "gb_bios.bin", PATH_MAX - strlen(path));
 402				break;
 403			case GB_MODEL_SGB:
 404			case GB_MODEL_SGB2: // TODO
 405				strncat(path, PATH_SEP "sgb_bios.bin", PATH_MAX - strlen(path));
 406				break;
 407			case GB_MODEL_CGB:
 408			case GB_MODEL_AGB:
 409				strncat(path, PATH_SEP "gbc_bios.bin", PATH_MAX - strlen(path));
 410				break;
 411			default:
 412				break;
 413			};
 414			bios = VFileOpen(path, O_RDONLY);
 415			if (bios && GBIsBIOS(bios)) {
 416				found = true;
 417			} else if (bios) {
 418				bios->close(bios);
 419				bios = NULL;
 420			}
 421		}
 422		if (bios) {
 423			GBLoadBIOS(gb, bios);
 424		}
 425	}
 426#endif
 427
 428	LR35902Reset(core->cpu);
 429}
 430
 431static void _GBCoreRunFrame(struct mCore* core) {
 432	struct GB* gb = core->board;
 433	int32_t frameCounter = gb->video.frameCounter;
 434	while (gb->video.frameCounter == frameCounter) {
 435		LR35902Run(core->cpu);
 436	}
 437}
 438
 439static void _GBCoreRunLoop(struct mCore* core) {
 440	LR35902Run(core->cpu);
 441}
 442
 443static void _GBCoreStep(struct mCore* core) {
 444	struct LR35902Core* cpu = core->cpu;
 445	do {
 446		LR35902Tick(cpu);
 447	} while (cpu->executionState != LR35902_CORE_FETCH);
 448}
 449
 450static size_t _GBCoreStateSize(struct mCore* core) {
 451	UNUSED(core);
 452	return sizeof(struct GBSerializedState);
 453}
 454
 455static bool _GBCoreLoadState(struct mCore* core, const void* state) {
 456	return GBDeserialize(core->board, state);
 457}
 458
 459static bool _GBCoreSaveState(struct mCore* core, void* state) {
 460	struct LR35902Core* cpu = core->cpu;
 461	while (cpu->executionState != LR35902_CORE_FETCH) {
 462		LR35902Tick(cpu);
 463	}
 464	GBSerialize(core->board, state);
 465	return true;
 466}
 467
 468static void _GBCoreSetKeys(struct mCore* core, uint32_t keys) {
 469	struct GBCore* gbcore = (struct GBCore*) core;
 470	gbcore->keys = keys;
 471	GBTestKeypadIRQ(core->board);
 472}
 473
 474static void _GBCoreAddKeys(struct mCore* core, uint32_t keys) {
 475	struct GBCore* gbcore = (struct GBCore*) core;
 476	gbcore->keys |= keys;
 477	GBTestKeypadIRQ(core->board);
 478}
 479
 480static void _GBCoreClearKeys(struct mCore* core, uint32_t keys) {
 481	struct GBCore* gbcore = (struct GBCore*) core;
 482	gbcore->keys &= ~keys;
 483}
 484
 485static int32_t _GBCoreFrameCounter(const struct mCore* core) {
 486	const struct GB* gb = core->board;
 487	return gb->video.frameCounter;
 488}
 489
 490static int32_t _GBCoreFrameCycles(const  struct mCore* core) {
 491	UNUSED(core);
 492	return GB_VIDEO_TOTAL_LENGTH;
 493}
 494
 495static int32_t _GBCoreFrequency(const struct mCore* core) {
 496	UNUSED(core);
 497	// TODO: GB differences
 498	return DMG_LR35902_FREQUENCY;
 499}
 500
 501static void _GBCoreGetGameTitle(const struct mCore* core, char* title) {
 502	GBGetGameTitle(core->board, title);
 503}
 504
 505static void _GBCoreGetGameCode(const struct mCore* core, char* title) {
 506	GBGetGameCode(core->board, title);
 507}
 508
 509static void _GBCoreSetPeripheral(struct mCore* core, int type, void* periph) {
 510	struct GB* gb = core->board;
 511	switch (type) {
 512	case mPERIPH_ROTATION:
 513		gb->memory.rotation = periph;
 514		break;
 515	case mPERIPH_RUMBLE:
 516		gb->memory.rumble = periph;
 517		break;
 518	case mPERIPH_IMAGE_SOURCE:
 519		gb->memory.cam = periph;
 520		break;
 521	default:
 522		return;
 523	}
 524}
 525
 526static uint32_t _GBCoreBusRead8(struct mCore* core, uint32_t address) {
 527	struct LR35902Core* cpu = core->cpu;
 528	return cpu->memory.load8(cpu, address);
 529}
 530
 531static uint32_t _GBCoreBusRead16(struct mCore* core, uint32_t address) {
 532	struct LR35902Core* cpu = core->cpu;
 533	return cpu->memory.load8(cpu, address) | (cpu->memory.load8(cpu, address + 1) << 8);
 534}
 535
 536static uint32_t _GBCoreBusRead32(struct mCore* core, uint32_t address) {
 537	struct LR35902Core* cpu = core->cpu;
 538	return cpu->memory.load8(cpu, address) | (cpu->memory.load8(cpu, address + 1) << 8) |
 539	       (cpu->memory.load8(cpu, address + 2) << 16) | (cpu->memory.load8(cpu, address + 3) << 24);
 540}
 541
 542static void _GBCoreBusWrite8(struct mCore* core, uint32_t address, uint8_t value) {
 543	struct LR35902Core* cpu = core->cpu;
 544	cpu->memory.store8(cpu, address, value);
 545}
 546
 547static void _GBCoreBusWrite16(struct mCore* core, uint32_t address, uint16_t value) {
 548	struct LR35902Core* cpu = core->cpu;
 549	cpu->memory.store8(cpu, address, value);
 550	cpu->memory.store8(cpu, address + 1, value >> 8);
 551}
 552
 553static void _GBCoreBusWrite32(struct mCore* core, uint32_t address, uint32_t value) {
 554	struct LR35902Core* cpu = core->cpu;
 555	cpu->memory.store8(cpu, address, value);
 556	cpu->memory.store8(cpu, address + 1, value >> 8);
 557	cpu->memory.store8(cpu, address + 2, value >> 16);
 558	cpu->memory.store8(cpu, address + 3, value >> 24);
 559}
 560
 561static uint32_t _GBCoreRawRead8(struct mCore* core, uint32_t address, int segment) {
 562	struct LR35902Core* cpu = core->cpu;
 563	return GBView8(cpu, address, segment);
 564}
 565
 566static uint32_t _GBCoreRawRead16(struct mCore* core, uint32_t address, int segment) {
 567	struct LR35902Core* cpu = core->cpu;
 568	return GBView8(cpu, address, segment) | (GBView8(cpu, address + 1, segment) << 8);
 569}
 570
 571static uint32_t _GBCoreRawRead32(struct mCore* core, uint32_t address, int segment) {
 572	struct LR35902Core* cpu = core->cpu;
 573	return GBView8(cpu, address, segment) | (GBView8(cpu, address + 1, segment) << 8) |
 574	       (GBView8(cpu, address + 2, segment) << 16) | (GBView8(cpu, address + 3, segment) << 24);
 575}
 576
 577static void _GBCoreRawWrite8(struct mCore* core, uint32_t address, int segment, uint8_t value) {
 578	struct LR35902Core* cpu = core->cpu;
 579	GBPatch8(cpu, address, value, NULL, segment);
 580}
 581
 582static void _GBCoreRawWrite16(struct mCore* core, uint32_t address, int segment, uint16_t value) {
 583	struct LR35902Core* cpu = core->cpu;
 584	GBPatch8(cpu, address, value, NULL, segment);
 585	GBPatch8(cpu, address + 1, value >> 8, NULL, segment);
 586}
 587
 588static void _GBCoreRawWrite32(struct mCore* core, uint32_t address, int segment, uint32_t value) {
 589	struct LR35902Core* cpu = core->cpu;
 590	GBPatch8(cpu, address, value, NULL, segment);
 591	GBPatch8(cpu, address + 1, value >> 8, NULL, segment);
 592	GBPatch8(cpu, address + 2, value >> 16, NULL, segment);
 593	GBPatch8(cpu, address + 3, value >> 24, NULL, segment);
 594}
 595
 596size_t _GBListMemoryBlocks(const struct mCore* core, const struct mCoreMemoryBlock** blocks) {
 597	const struct GB* gb = core->board;
 598	switch (gb->model) {
 599	case GB_MODEL_DMG:
 600	case GB_MODEL_MGB:
 601	case GB_MODEL_SGB:
 602	case GB_MODEL_SGB2:
 603	default:
 604		*blocks = _GBMemoryBlocks;
 605		return sizeof(_GBMemoryBlocks) / sizeof(*_GBMemoryBlocks);
 606	case GB_MODEL_CGB:
 607	case GB_MODEL_AGB:
 608		*blocks = _GBCMemoryBlocks;
 609		return sizeof(_GBCMemoryBlocks) / sizeof(*_GBCMemoryBlocks);
 610	}
 611}
 612
 613void* _GBGetMemoryBlock(struct mCore* core, size_t id, size_t* sizeOut) {
 614	struct GB* gb = core->board;
 615	bool isCgb = gb->model >= GB_MODEL_CGB;
 616	switch (id) {
 617	default:
 618		return NULL;
 619	case GB_REGION_CART_BANK0:
 620		*sizeOut = gb->memory.romSize;
 621		return gb->memory.rom;
 622	case GB_REGION_VRAM:
 623		*sizeOut = GB_SIZE_WORKING_RAM_BANK0 * (isCgb ? 1 : 2);
 624		return gb->video.vram;
 625	case GB_REGION_EXTERNAL_RAM:
 626		*sizeOut = gb->sramSize;
 627		return gb->memory.sram;
 628	case GB_REGION_WORKING_RAM_BANK0:
 629		*sizeOut = GB_SIZE_VRAM * (isCgb ? 8 : 2);
 630		return gb->memory.wram;
 631	case GB_BASE_OAM:
 632		*sizeOut = GB_SIZE_OAM;
 633		return gb->video.oam.raw;
 634	case GB_BASE_HRAM:
 635		*sizeOut = GB_SIZE_HRAM;
 636		return gb->memory.hram;
 637	}
 638}
 639
 640#ifdef USE_DEBUGGERS
 641static bool _GBCoreSupportsDebuggerType(struct mCore* core, enum mDebuggerType type) {
 642	UNUSED(core);
 643	switch (type) {
 644	case DEBUGGER_CLI:
 645		return true;
 646	default:
 647		return false;
 648	}
 649}
 650
 651static struct mDebuggerPlatform* _GBCoreDebuggerPlatform(struct mCore* core) {
 652	struct GBCore* gbcore = (struct GBCore*) core;
 653	struct GB* gb = core->board;
 654	if (!gbcore->debuggerPlatform) {
 655		struct LR35902Debugger* platform = (struct LR35902Debugger*) LR35902DebuggerPlatformCreate();
 656		if (gb->model >= GB_MODEL_CGB) {
 657			platform->segments = _GBCSegments;
 658		} else {
 659			platform->segments = _GBSegments;
 660		}
 661		gbcore->debuggerPlatform = &platform->d;
 662	}
 663	return gbcore->debuggerPlatform;
 664}
 665
 666static struct CLIDebuggerSystem* _GBCoreCliDebuggerSystem(struct mCore* core) {
 667	return GBCLIDebuggerCreate(core);
 668}
 669
 670static void _GBCoreAttachDebugger(struct mCore* core, struct mDebugger* debugger) {
 671	struct LR35902Core* cpu = core->cpu;
 672	if (core->debugger) {
 673		LR35902HotplugDetach(cpu, CPU_COMPONENT_DEBUGGER);
 674	}
 675	cpu->components[CPU_COMPONENT_DEBUGGER] = &debugger->d;
 676	LR35902HotplugAttach(cpu, CPU_COMPONENT_DEBUGGER);
 677	core->debugger = debugger;
 678}
 679
 680static void _GBCoreDetachDebugger(struct mCore* core) {
 681	struct LR35902Core* cpu = core->cpu;
 682	if (core->debugger) {
 683		LR35902HotplugDetach(cpu, CPU_COMPONENT_DEBUGGER);
 684	}
 685	cpu->components[CPU_COMPONENT_DEBUGGER] = NULL;
 686	core->debugger = NULL;
 687}
 688
 689static void _GBCoreLoadSymbols(struct mCore* core, struct VFile* vf) {
 690	core->symbolTable = mDebuggerSymbolTableCreate();
 691#if !defined(MINIMAL_CORE) || MINIMAL_CORE < 2
 692	if (!vf) {
 693		vf = mDirectorySetOpenSuffix(&core->dirs, core->dirs.base, ".sym", O_RDONLY);
 694	}
 695#endif
 696	if (!vf) {
 697		return;
 698	}
 699	GBLoadSymbols(core->symbolTable, vf);
 700}
 701#endif
 702
 703static struct mCheatDevice* _GBCoreCheatDevice(struct mCore* core) {
 704	struct GBCore* gbcore = (struct GBCore*) core;
 705	if (!gbcore->cheatDevice) {
 706		gbcore->cheatDevice = GBCheatDeviceCreate();
 707		((struct LR35902Core*) core->cpu)->components[CPU_COMPONENT_CHEAT_DEVICE] = &gbcore->cheatDevice->d;
 708		LR35902HotplugAttach(core->cpu, CPU_COMPONENT_CHEAT_DEVICE);
 709		gbcore->cheatDevice->p = core;
 710	}
 711	return gbcore->cheatDevice;
 712}
 713
 714static size_t _GBCoreSavedataClone(struct mCore* core, void** sram) {
 715	struct GB* gb = core->board;
 716	struct VFile* vf = gb->sramVf;
 717	if (vf) {
 718		*sram = malloc(vf->size(vf));
 719		vf->seek(vf, 0, SEEK_SET);
 720		return vf->read(vf, *sram, vf->size(vf));
 721	}
 722	*sram = malloc(gb->sramSize);
 723	memcpy(*sram, gb->memory.sram, gb->sramSize);
 724	return gb->sramSize;
 725}
 726
 727static bool _GBCoreSavedataRestore(struct mCore* core, const void* sram, size_t size, bool writeback) {
 728	struct GB* gb = core->board;
 729	if (!writeback) {
 730		struct VFile* vf = VFileMemChunk(sram, size);
 731		GBSavedataMask(gb, vf, true);
 732		return true;
 733	}
 734	struct VFile* vf = gb->sramVf;
 735	if (vf) {
 736		vf->seek(vf, 0, SEEK_SET);
 737		return vf->write(vf, sram, size) > 0;
 738	}
 739	if (size > 0x20000) {
 740		size = 0x20000;
 741	}
 742	GBResizeSram(gb, size);
 743	memcpy(gb->memory.sram, sram, size);
 744	return true;
 745}
 746
 747static size_t _GBCoreListVideoLayers(const struct mCore* core, const struct mCoreChannelInfo** info) {
 748	UNUSED(core);
 749	*info = _GBVideoLayers;
 750	return sizeof(_GBVideoLayers) / sizeof(*_GBVideoLayers);
 751}
 752
 753static size_t _GBCoreListAudioChannels(const struct mCore* core, const struct mCoreChannelInfo** info) {
 754	UNUSED(core);
 755	*info = _GBAudioChannels;
 756	return sizeof(_GBAudioChannels) / sizeof(*_GBAudioChannels);
 757}
 758
 759static void _GBCoreEnableVideoLayer(struct mCore* core, size_t id, bool enable) {
 760	struct GB* gb = core->board;
 761	switch (id) {
 762	case 0:
 763		gb->video.renderer->disableBG = !enable;
 764		break;
 765	case 1:
 766		gb->video.renderer->disableOBJ = !enable;
 767		break;
 768	case 2:
 769		gb->video.renderer->disableWIN = !enable;
 770		break;
 771	default:
 772		break;
 773	}
 774}
 775
 776static void _GBCoreEnableAudioChannel(struct mCore* core, size_t id, bool enable) {
 777	struct GB* gb = core->board;
 778	switch (id) {
 779	case 0:
 780	case 1:
 781	case 2:
 782	case 3:
 783		gb->audio.forceDisableCh[id] = !enable;
 784		break;
 785	default:
 786		break;
 787	}
 788}
 789
 790static void _GBCoreStartVideoLog(struct mCore* core, struct mVideoLogContext* context) {
 791	struct GBCore* gbcore = (struct GBCore*) core;
 792	struct GB* gb = core->board;
 793	gbcore->logContext = context;
 794
 795	int channelId = mVideoLoggerAddChannel(context);
 796	gbcore->proxyRenderer.logger = malloc(sizeof(struct mVideoLogger));
 797	mVideoLoggerRendererCreate(gbcore->proxyRenderer.logger, false);
 798	mVideoLoggerAttachChannel(gbcore->proxyRenderer.logger, context, channelId);
 799	gbcore->proxyRenderer.logger->block = false;
 800
 801	GBVideoProxyRendererCreate(&gbcore->proxyRenderer, &gbcore->renderer.d);
 802	GBVideoProxyRendererShim(&gb->video, &gbcore->proxyRenderer);
 803}
 804
 805static void _GBCoreEndVideoLog(struct mCore* core) {
 806	struct GBCore* gbcore = (struct GBCore*) core;
 807	struct GB* gb = core->board;
 808	GBVideoProxyRendererUnshim(&gb->video, &gbcore->proxyRenderer);
 809	free(gbcore->proxyRenderer.logger);
 810	gbcore->proxyRenderer.logger = NULL;
 811}
 812
 813struct mCore* GBCoreCreate(void) {
 814	struct GBCore* gbcore = malloc(sizeof(*gbcore));
 815	struct mCore* core = &gbcore->d;
 816	memset(&core->opts, 0, sizeof(core->opts));
 817	core->cpu = NULL;
 818	core->board = NULL;
 819	core->debugger = NULL;
 820	core->symbolTable = NULL;
 821	core->init = _GBCoreInit;
 822	core->deinit = _GBCoreDeinit;
 823	core->platform = _GBCorePlatform;
 824	core->setSync = _GBCoreSetSync;
 825	core->loadConfig = _GBCoreLoadConfig;
 826	core->desiredVideoDimensions = _GBCoreDesiredVideoDimensions;
 827	core->setVideoBuffer = _GBCoreSetVideoBuffer;
 828	core->getPixels = _GBCoreGetPixels;
 829	core->putPixels = _GBCorePutPixels;
 830	core->getAudioChannel = _GBCoreGetAudioChannel;
 831	core->setAudioBufferSize = _GBCoreSetAudioBufferSize;
 832	core->getAudioBufferSize = _GBCoreGetAudioBufferSize;
 833	core->setAVStream = _GBCoreSetAVStream;
 834	core->addCoreCallbacks = _GBCoreAddCoreCallbacks;
 835	core->clearCoreCallbacks = _GBCoreClearCoreCallbacks;
 836	core->isROM = GBIsROM;
 837	core->loadROM = _GBCoreLoadROM;
 838	core->loadBIOS = _GBCoreLoadBIOS;
 839	core->loadSave = _GBCoreLoadSave;
 840	core->loadTemporarySave = _GBCoreLoadTemporarySave;
 841	core->loadPatch = _GBCoreLoadPatch;
 842	core->unloadROM = _GBCoreUnloadROM;
 843	core->checksum = _GBCoreChecksum;
 844	core->reset = _GBCoreReset;
 845	core->runFrame = _GBCoreRunFrame;
 846	core->runLoop = _GBCoreRunLoop;
 847	core->step = _GBCoreStep;
 848	core->stateSize = _GBCoreStateSize;
 849	core->loadState = _GBCoreLoadState;
 850	core->saveState = _GBCoreSaveState;
 851	core->setKeys = _GBCoreSetKeys;
 852	core->addKeys = _GBCoreAddKeys;
 853	core->clearKeys = _GBCoreClearKeys;
 854	core->frameCounter = _GBCoreFrameCounter;
 855	core->frameCycles = _GBCoreFrameCycles;
 856	core->frequency = _GBCoreFrequency;
 857	core->getGameTitle = _GBCoreGetGameTitle;
 858	core->getGameCode = _GBCoreGetGameCode;
 859	core->setPeripheral = _GBCoreSetPeripheral;
 860	core->busRead8 = _GBCoreBusRead8;
 861	core->busRead16 = _GBCoreBusRead16;
 862	core->busRead32 = _GBCoreBusRead32;
 863	core->busWrite8 = _GBCoreBusWrite8;
 864	core->busWrite16 = _GBCoreBusWrite16;
 865	core->busWrite32 = _GBCoreBusWrite32;
 866	core->rawRead8 = _GBCoreRawRead8;
 867	core->rawRead16 = _GBCoreRawRead16;
 868	core->rawRead32 = _GBCoreRawRead32;
 869	core->rawWrite8 = _GBCoreRawWrite8;
 870	core->rawWrite16 = _GBCoreRawWrite16;
 871	core->rawWrite32 = _GBCoreRawWrite32;
 872	core->listMemoryBlocks = _GBListMemoryBlocks;
 873	core->getMemoryBlock = _GBGetMemoryBlock;
 874#ifdef USE_DEBUGGERS
 875	core->supportsDebuggerType = _GBCoreSupportsDebuggerType;
 876	core->debuggerPlatform = _GBCoreDebuggerPlatform;
 877	core->cliDebuggerSystem = _GBCoreCliDebuggerSystem;
 878	core->attachDebugger = _GBCoreAttachDebugger;
 879	core->detachDebugger = _GBCoreDetachDebugger;
 880	core->loadSymbols = _GBCoreLoadSymbols;
 881#endif
 882	core->cheatDevice = _GBCoreCheatDevice;
 883	core->savedataClone = _GBCoreSavedataClone;
 884	core->savedataRestore = _GBCoreSavedataRestore;
 885	core->listVideoLayers = _GBCoreListVideoLayers;
 886	core->listAudioChannels = _GBCoreListAudioChannels;
 887	core->enableVideoLayer = _GBCoreEnableVideoLayer;
 888	core->enableAudioChannel = _GBCoreEnableAudioChannel;
 889#ifndef MINIMAL_CORE
 890	core->startVideoLog = _GBCoreStartVideoLog;
 891	core->endVideoLog = _GBCoreEndVideoLog;
 892#endif
 893	return core;
 894}
 895
 896#ifndef MINIMAL_CORE
 897static void _GBVLPStartFrameCallback(void *context) {
 898	struct mCore* core = context;
 899	struct GBCore* gbcore = (struct GBCore*) core;
 900	struct GB* gb = core->board;
 901
 902	if (!mVideoLoggerRendererRun(gbcore->proxyRenderer.logger, true)) {
 903		GBVideoProxyRendererUnshim(&gb->video, &gbcore->proxyRenderer);
 904		mVideoLogContextRewind(gbcore->logContext, core);
 905		GBVideoProxyRendererShim(&gb->video, &gbcore->proxyRenderer);
 906	}
 907}
 908
 909static bool _GBVLPInit(struct mCore* core) {
 910	struct GBCore* gbcore = (struct GBCore*) core;
 911	if (!_GBCoreInit(core)) {
 912		return false;
 913	}
 914	gbcore->proxyRenderer.logger = malloc(sizeof(struct mVideoLogger));
 915	mVideoLoggerRendererCreate(gbcore->proxyRenderer.logger, true);
 916	GBVideoProxyRendererCreate(&gbcore->proxyRenderer, NULL);
 917	memset(&gbcore->logCallbacks, 0, sizeof(gbcore->logCallbacks));
 918	gbcore->logCallbacks.videoFrameStarted = _GBVLPStartFrameCallback;
 919	gbcore->logCallbacks.context = core;
 920	core->addCoreCallbacks(core, &gbcore->logCallbacks);
 921	return true;
 922}
 923
 924static void _GBVLPDeinit(struct mCore* core) {
 925	struct GBCore* gbcore = (struct GBCore*) core;
 926	if (gbcore->logContext) {
 927		mVideoLogContextDestroy(core, gbcore->logContext);
 928	}
 929	_GBCoreDeinit(core);
 930}
 931
 932static void _GBVLPReset(struct mCore* core) {
 933	struct GBCore* gbcore = (struct GBCore*) core;
 934	struct GB* gb = (struct GB*) core->board;
 935	if (gb->video.renderer == &gbcore->proxyRenderer.d) {
 936		GBVideoProxyRendererUnshim(&gb->video, &gbcore->proxyRenderer);
 937	} else if (gbcore->renderer.outputBuffer) {
 938		struct GBVideoRenderer* renderer = &gbcore->renderer.d;
 939		GBVideoAssociateRenderer(&gb->video, renderer);
 940	}
 941
 942	LR35902Reset(core->cpu);
 943	mVideoLogContextRewind(gbcore->logContext, core);
 944	GBVideoProxyRendererShim(&gb->video, &gbcore->proxyRenderer);
 945
 946	// Make sure CPU loop never spins
 947	GBHalt(gb->cpu);
 948	gb->memory.ie = 0;
 949	gb->memory.ime = false;
 950}
 951
 952static bool _GBVLPLoadROM(struct mCore* core, struct VFile* vf) {
 953	struct GBCore* gbcore = (struct GBCore*) core;
 954	gbcore->logContext = mVideoLogContextCreate(NULL);
 955	if (!mVideoLogContextLoad(gbcore->logContext, vf)) {
 956		mVideoLogContextDestroy(core, gbcore->logContext);
 957		gbcore->logContext = NULL;
 958		return false;
 959	}
 960	mVideoLoggerAttachChannel(gbcore->proxyRenderer.logger, gbcore->logContext, 0);
 961	return true;
 962}
 963
 964static bool _GBVLPLoadState(struct mCore* core, const void* buffer) {
 965	struct GB* gb = (struct GB*) core->board;
 966	const struct GBSerializedState* state = buffer;
 967
 968	gb->timing.root = NULL;
 969	gb->model = state->model;
 970
 971	gb->cpu->pc = GB_BASE_HRAM;
 972	gb->cpu->memory.setActiveRegion(gb->cpu, gb->cpu->pc);
 973
 974	GBVideoDeserialize(&gb->video, state);
 975	GBIODeserialize(gb, state);
 976	GBAudioReset(&gb->audio);
 977
 978	// Make sure CPU loop never spins
 979	GBHalt(gb->cpu);
 980	gb->memory.ie = 0;
 981	gb->memory.ime = false;
 982
 983	return true;
 984}
 985
 986static bool _returnTrue(struct VFile* vf) {
 987	UNUSED(vf);
 988	return true;
 989}
 990
 991struct mCore* GBVideoLogPlayerCreate(void) {
 992	struct mCore* core = GBCoreCreate();
 993	core->init = _GBVLPInit;
 994	core->deinit = _GBVLPDeinit;
 995	core->reset = _GBVLPReset;
 996	core->loadROM = _GBVLPLoadROM;
 997	core->loadState = _GBVLPLoadState;
 998	core->isROM = _returnTrue;
 999	return core;
1000}
1001#else
1002struct mCore* GBVideoLogPlayerCreate(void) {
1003	return false;
1004}
1005#endif