all repos — mgba @ b750c76d02af94646309a700c86c04faf6707b7d

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