all repos — mgba @ a8d991e24f12aa1930498af61f16fa2b098cc618

mGBA Game Boy Advance Emulator

src/platform/libretro/libretro.c (view raw)

  1/* Copyright (c) 2013-2015 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 "libretro.h"
  7
  8#include <mgba-util/common.h>
  9
 10#include <mgba/core/blip_buf.h>
 11#include <mgba/core/cheats.h>
 12#include <mgba/core/core.h>
 13#include <mgba/core/log.h>
 14#include <mgba/core/serialize.h>
 15#include <mgba/core/version.h>
 16#ifdef M_CORE_GB
 17#include <mgba/gb/core.h>
 18#include <mgba/internal/gb/gb.h>
 19#include <mgba/internal/gb/mbc.h>
 20#endif
 21#ifdef M_CORE_GBA
 22#include <mgba/gba/core.h>
 23#include <mgba/gba/interface.h>
 24#include <mgba/internal/gba/gba.h>
 25#endif
 26#include <mgba-util/memory.h>
 27#include <mgba-util/vfs.h>
 28
 29#define SAMPLES 1024
 30#define RUMBLE_PWM 35
 31
 32static retro_environment_t environCallback;
 33static retro_video_refresh_t videoCallback;
 34static retro_audio_sample_batch_t audioCallback;
 35static retro_input_poll_t inputPollCallback;
 36static retro_input_state_t inputCallback;
 37static retro_log_printf_t logCallback;
 38static retro_set_rumble_state_t rumbleCallback;
 39
 40static void GBARetroLog(struct mLogger* logger, int category, enum mLogLevel level, const char* format, va_list args);
 41
 42static void _postAudioBuffer(struct mAVStream*, blip_t* left, blip_t* right);
 43static void _setRumble(struct mRumble* rumble, int enable);
 44static uint8_t _readLux(struct GBALuminanceSource* lux);
 45static void _updateLux(struct GBALuminanceSource* lux);
 46static void _updateCamera(const uint32_t* buffer, unsigned width, unsigned height, size_t pitch);
 47static void _startImage(struct mImageSource*, unsigned w, unsigned h, int colorFormats);
 48static void _stopImage(struct mImageSource*);
 49static void _requestImage(struct mImageSource*, const void** buffer, size_t* stride, enum mColorFormat* colorFormat);
 50
 51static struct mCore* core;
 52static void* outputBuffer;
 53static void* data;
 54static size_t dataSize;
 55static void* savedata;
 56static struct mAVStream stream;
 57static int rumbleUp;
 58static int rumbleDown;
 59static struct mRumble rumble;
 60static struct GBALuminanceSource lux;
 61static int luxLevel;
 62static struct mLogger logger;
 63static struct retro_camera_callback cam;
 64static struct mImageSource imageSource;
 65static uint32_t* camData = NULL;
 66static unsigned camWidth;
 67static unsigned camHeight;
 68static unsigned imcapWidth;
 69static unsigned imcapHeight;
 70static size_t camStride;
 71
 72static void _reloadSettings(void) {
 73	struct mCoreOptions opts = {
 74		.useBios = true,
 75		.volume = 0x100,
 76	};
 77
 78	struct retro_variable var;
 79	enum GBModel model;
 80	const char* modelName;
 81
 82	var.key = "mgba_gb_model";
 83	var.value = 0;
 84	if (environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
 85		if (strcmp(var.value, "Game Boy") == 0) {
 86			model = GB_MODEL_DMG;
 87		} else if (strcmp(var.value, "Super Game Boy") == 0) {
 88			model = GB_MODEL_SGB;
 89		} else if (strcmp(var.value, "Game Boy Color") == 0) {
 90			model = GB_MODEL_CGB;
 91		} else if (strcmp(var.value, "Game Boy Advance") == 0) {
 92			model = GB_MODEL_AGB;
 93		} else {
 94			model = GB_MODEL_AUTODETECT;
 95		}
 96
 97		modelName = GBModelToName(model);
 98		mCoreConfigSetDefaultValue(&core->config, "gb.model", modelName);
 99		mCoreConfigSetDefaultValue(&core->config, "sgb.model", modelName);
100		mCoreConfigSetDefaultValue(&core->config, "cgb.model", modelName);
101	}
102
103	var.key = "mgba_use_bios";
104	var.value = 0;
105	if (environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
106		opts.useBios = strcmp(var.value, "ON") == 0;
107	}
108
109	var.key = "mgba_skip_bios";
110	var.value = 0;
111	if (environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
112		opts.skipBios = strcmp(var.value, "ON") == 0;
113	}
114
115	var.key = "mgba_sgb_borders";
116	var.value = 0;
117	if (environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
118		if (strcmp(var.value, "ON") == 0) {
119			mCoreConfigSetDefaultIntValue(&core->config, "sgb.borders", true);
120		} else {
121			mCoreConfigSetDefaultIntValue(&core->config, "sgb.borders", false);
122		}
123	}
124
125	var.key = "mgba_idle_optimization";
126	var.value = 0;
127	if (environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
128		if (strcmp(var.value, "Don't Remove") == 0) {
129			mCoreConfigSetDefaultValue(&core->config, "idleOptimization", "ignore");
130		} else if (strcmp(var.value, "Remove Known") == 0) {
131			mCoreConfigSetDefaultValue(&core->config, "idleOptimization", "remove");
132		} else if (strcmp(var.value, "Detect and Remove") == 0) {
133			mCoreConfigSetDefaultValue(&core->config, "idleOptimization", "detect");
134		}
135	}
136
137	var.key = "mgba_frameskip";
138	var.value = 0;
139	if (environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
140		opts.frameskip = strtol(var.value, NULL, 10);
141
142	}
143
144	mCoreConfigLoadDefaults(&core->config, &opts);
145	mCoreLoadConfig(core);
146}
147
148unsigned retro_api_version(void) {
149	return RETRO_API_VERSION;
150}
151
152void retro_set_environment(retro_environment_t env) {
153	environCallback = env;
154
155	struct retro_variable vars[] = {
156		{ "mgba_solar_sensor_level", "Solar sensor level; 0|1|2|3|4|5|6|7|8|9|10" },
157		{ "mgba_allow_opposing_directions", "Allow opposing directional input; OFF|ON" },
158		{ "mgba_gb_model", "Game Boy model (requires restart); Autodetect|Game Boy|Super Game Boy|Game Boy Color|Game Boy Advance" },
159		{ "mgba_use_bios", "Use BIOS file if found (requires restart); ON|OFF" },
160		{ "mgba_skip_bios", "Skip BIOS intro (requires restart); OFF|ON" },
161		{ "mgba_sgb_borders", "Use Super Game Boy borders (requires restart); ON|OFF" },
162		{ "mgba_idle_optimization", "Idle loop removal; Remove Known|Detect and Remove|Don't Remove" },
163		{ "mgba_frameskip", "Frameskip; 0|1|2|3|4|5|6|7|8|9|10" },
164		{ 0, 0 }
165	};
166
167	environCallback(RETRO_ENVIRONMENT_SET_VARIABLES, vars);
168}
169
170void retro_set_video_refresh(retro_video_refresh_t video) {
171	videoCallback = video;
172}
173
174void retro_set_audio_sample(retro_audio_sample_t audio) {
175	UNUSED(audio);
176}
177
178void retro_set_audio_sample_batch(retro_audio_sample_batch_t audioBatch) {
179	audioCallback = audioBatch;
180}
181
182void retro_set_input_poll(retro_input_poll_t inputPoll) {
183	inputPollCallback = inputPoll;
184}
185
186void retro_set_input_state(retro_input_state_t input) {
187	inputCallback = input;
188}
189
190void retro_get_system_info(struct retro_system_info* info) {
191	info->need_fullpath = false;
192	info->valid_extensions = "gba|gb|gbc";
193	info->library_version = projectVersion;
194	info->library_name = projectName;
195	info->block_extract = false;
196}
197
198void retro_get_system_av_info(struct retro_system_av_info* info) {
199	unsigned width, height;
200	core->desiredVideoDimensions(core, &width, &height);
201	info->geometry.base_width = width;
202	info->geometry.base_height = height;
203#ifdef M_CORE_GB
204	if (core->platform(core) == PLATFORM_GB) {
205		info->geometry.max_width = 256;
206		info->geometry.max_height = 224;
207	} else
208#endif
209	{
210		info->geometry.max_width = width;
211		info->geometry.max_height = height;
212	}
213
214	info->geometry.aspect_ratio = width / (double) height;
215	info->timing.fps = core->frequency(core) / (float) core->frameCycles(core);
216	info->timing.sample_rate = 32768;
217}
218
219void retro_init(void) {
220	enum retro_pixel_format fmt;
221#ifdef COLOR_16_BIT
222#ifdef COLOR_5_6_5
223	fmt = RETRO_PIXEL_FORMAT_RGB565;
224#else
225#warning This pixel format is unsupported. Please use -DCOLOR_16-BIT -DCOLOR_5_6_5
226	fmt = RETRO_PIXEL_FORMAT_0RGB1555;
227#endif
228#else
229#warning This pixel format is unsupported. Please use -DCOLOR_16-BIT -DCOLOR_5_6_5
230	fmt = RETRO_PIXEL_FORMAT_XRGB8888;
231#endif
232	environCallback(RETRO_ENVIRONMENT_SET_PIXEL_FORMAT, &fmt);
233
234	struct retro_input_descriptor inputDescriptors[] = {
235		{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A, "A" },
236		{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B, "B" },
237		{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_SELECT, "Select" },
238		{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START, "Start" },
239		{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT, "Right" },
240		{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT, "Left" },
241		{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP, "Up" },
242		{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN, "Down" },
243		{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R, "R" },
244		{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L, "L" },
245		{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R3, "Brighten Solar Sensor" },
246		{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L3, "Darken Solar Sensor" },
247		{ 0 }
248	};
249	environCallback(RETRO_ENVIRONMENT_SET_INPUT_DESCRIPTORS, &inputDescriptors);
250
251	// TODO: RETRO_ENVIRONMENT_SET_SUPPORT_NO_GAME when BIOS booting is supported
252
253	struct retro_rumble_interface rumbleInterface;
254	if (environCallback(RETRO_ENVIRONMENT_GET_RUMBLE_INTERFACE, &rumbleInterface)) {
255		rumbleCallback = rumbleInterface.set_rumble_state;
256		rumble.setRumble = _setRumble;
257	} else {
258		rumbleCallback = 0;
259	}
260
261	luxLevel = 0;
262	lux.readLuminance = _readLux;
263	lux.sample = _updateLux;
264	_updateLux(&lux);
265
266	struct retro_log_callback log;
267	if (environCallback(RETRO_ENVIRONMENT_GET_LOG_INTERFACE, &log)) {
268		logCallback = log.log;
269	} else {
270		logCallback = 0;
271	}
272	logger.log = GBARetroLog;
273	mLogSetDefaultLogger(&logger);
274
275	stream.videoDimensionsChanged = 0;
276	stream.postAudioFrame = 0;
277	stream.postAudioBuffer = _postAudioBuffer;
278	stream.postVideoFrame = 0;
279
280	imageSource.startRequestImage = _startImage;
281	imageSource.stopRequestImage = _stopImage;
282	imageSource.requestImage = _requestImage;
283}
284
285void retro_deinit(void) {
286	free(outputBuffer);
287}
288
289void retro_run(void) {
290	uint16_t keys;
291	inputPollCallback();
292
293	bool updated = false;
294	if (environCallback(RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE, &updated) && updated) {
295		struct retro_variable var = {
296			.key = "mgba_allow_opposing_directions",
297			.value = 0
298		};
299		if (environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
300			((struct GBA*) core->board)->allowOpposingDirections = strcmp(var.value, "yes") == 0;
301		}
302
303		var.key = "mgba_frameskip";
304		var.value = 0;
305		if (environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
306			mCoreConfigSetUIntValue(&core->config, "frameskip", strtol(var.value, NULL, 10));
307			mCoreLoadConfig(core);
308		}
309	}
310
311	keys = 0;
312	keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A)) << 0;
313	keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B)) << 1;
314	keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_SELECT)) << 2;
315	keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START)) << 3;
316	keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT)) << 4;
317	keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT)) << 5;
318	keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP)) << 6;
319	keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN)) << 7;
320	keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R)) << 8;
321	keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L)) << 9;
322	core->setKeys(core, keys);
323
324	static bool wasAdjustingLux = false;
325	if (wasAdjustingLux) {
326		wasAdjustingLux = inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R3) ||
327		                  inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L3);
328	} else {
329		if (inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R3)) {
330			++luxLevel;
331			if (luxLevel > 10) {
332				luxLevel = 10;
333			}
334			wasAdjustingLux = true;
335		} else if (inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L3)) {
336			--luxLevel;
337			if (luxLevel < 0) {
338				luxLevel = 0;
339			}
340			wasAdjustingLux = true;
341		}
342	}
343
344	core->runFrame(core);
345	unsigned width, height;
346	core->desiredVideoDimensions(core, &width, &height);
347	videoCallback(outputBuffer, width, height, BYTES_PER_PIXEL * 256);
348
349	if (rumbleCallback) {
350		if (rumbleUp) {
351			rumbleCallback(0, RETRO_RUMBLE_STRONG, rumbleUp * 0xFFFF / (rumbleUp + rumbleDown));
352			rumbleCallback(0, RETRO_RUMBLE_WEAK, rumbleUp * 0xFFFF / (rumbleUp + rumbleDown));
353		} else {
354			rumbleCallback(0, RETRO_RUMBLE_STRONG, 0);
355			rumbleCallback(0, RETRO_RUMBLE_WEAK, 0);
356		}
357		rumbleUp = 0;
358		rumbleDown = 0;
359	}
360}
361
362static void _setupMaps(struct mCore* core) {
363#ifdef M_CORE_GBA
364	if (core->platform(core) == PLATFORM_GBA) {
365		struct GBA* gba = core->board;
366		struct retro_memory_descriptor descs[11];
367		struct retro_memory_map mmaps;
368		size_t romSize = gba->memory.romSize + (gba->memory.romSize & 1);
369
370		memset(descs, 0, sizeof(descs));
371		size_t savedataSize = retro_get_memory_size(RETRO_MEMORY_SAVE_RAM);
372
373		/* Map internal working RAM */
374		descs[0].ptr    = gba->memory.iwram;
375		descs[0].start  = BASE_WORKING_IRAM;
376		descs[0].len    = SIZE_WORKING_IRAM;
377		descs[0].select = 0xFF000000;
378
379		/* Map working RAM */
380		descs[1].ptr    = gba->memory.wram;
381		descs[1].start  = BASE_WORKING_RAM;
382		descs[1].len    = SIZE_WORKING_RAM;
383		descs[1].select = 0xFF000000;
384
385		/* Map save RAM */
386		/* TODO: if SRAM is flash, use start=0 addrspace="S" instead */
387		descs[2].ptr    = savedataSize ? savedata : NULL;
388		descs[2].start  = BASE_CART_SRAM;
389		descs[2].len    = savedataSize;
390
391		/* Map ROM */
392		descs[3].ptr    = gba->memory.rom;
393		descs[3].start  = BASE_CART0;
394		descs[3].len    = romSize;
395		descs[3].flags  = RETRO_MEMDESC_CONST;
396
397		descs[4].ptr    = gba->memory.rom;
398		descs[4].start  = BASE_CART1;
399		descs[4].len    = romSize;
400		descs[4].flags  = RETRO_MEMDESC_CONST;
401
402		descs[5].ptr    = gba->memory.rom;
403		descs[5].start  = BASE_CART2;
404		descs[5].len    = romSize;
405		descs[5].flags  = RETRO_MEMDESC_CONST;
406
407		/* Map BIOS */
408		descs[6].ptr    = gba->memory.bios;
409		descs[6].start  = BASE_BIOS;
410		descs[6].len    = SIZE_BIOS;
411		descs[6].flags  = RETRO_MEMDESC_CONST;
412
413		/* Map VRAM */
414		descs[7].ptr    = gba->video.vram;
415		descs[7].start  = BASE_VRAM;
416		descs[7].len    = SIZE_VRAM;
417		descs[7].select = 0xFF000000;
418
419		/* Map palette RAM */
420		descs[8].ptr    = gba->video.palette;
421		descs[8].start  = BASE_PALETTE_RAM;
422		descs[8].len    = SIZE_PALETTE_RAM;
423		descs[8].select = 0xFF000000;
424
425		/* Map OAM */
426		descs[9].ptr    = &gba->video.oam; /* video.oam is a structure */
427		descs[9].start  = BASE_OAM;
428		descs[9].len    = SIZE_OAM;
429		descs[9].select = 0xFF000000;
430
431		/* Map mmapped I/O */
432		descs[10].ptr    = gba->memory.io;
433		descs[10].start  = BASE_IO;
434		descs[10].len    = SIZE_IO;
435
436		mmaps.descriptors = descs;
437		mmaps.num_descriptors = sizeof(descs) / sizeof(descs[0]);
438
439		bool yes = true;
440		environCallback(RETRO_ENVIRONMENT_SET_MEMORY_MAPS, &mmaps);
441		environCallback(RETRO_ENVIRONMENT_SET_SUPPORT_ACHIEVEMENTS, &yes);
442	}
443#endif
444}
445
446void retro_reset(void) {
447	core->reset(core);
448	_setupMaps(core);
449
450	rumbleUp = 0;
451	rumbleDown = 0;
452}
453
454bool retro_load_game(const struct retro_game_info* game) {
455	struct VFile* rom;
456	if (game->data) {
457		data = anonymousMemoryMap(game->size);
458		dataSize = game->size;
459		memcpy(data, game->data, game->size);
460		rom = VFileFromMemory(data, game->size);
461	} else {
462		data = 0;
463		rom = VFileOpen(game->path, O_RDONLY);
464	}
465	if (!rom) {
466		return false;
467	}
468
469	core = mCoreFindVF(rom);
470	if (!core) {
471		rom->close(rom);
472		mappedMemoryFree(data, game->size);
473		return false;
474	}
475	mCoreInitConfig(core, NULL);
476	core->init(core);
477	core->setAVStream(core, &stream);
478
479	size_t size = 256 * 224 * BYTES_PER_PIXEL;
480	outputBuffer = malloc(size);
481	memset(outputBuffer, 0xFF, size);
482	core->setVideoBuffer(core, outputBuffer, 256);
483
484	core->setAudioBufferSize(core, SAMPLES);
485
486	blip_set_rates(core->getAudioChannel(core, 0), core->frequency(core), 32768);
487	blip_set_rates(core->getAudioChannel(core, 1), core->frequency(core), 32768);
488
489	core->setPeripheral(core, mPERIPH_RUMBLE, &rumble);
490
491	savedata = anonymousMemoryMap(SIZE_CART_FLASH1M);
492	struct VFile* save = VFileFromMemory(savedata, SIZE_CART_FLASH1M);
493
494	_reloadSettings();
495	core->loadROM(core, rom);
496	core->loadSave(core, save);
497
498	const char* sysDir = 0;
499	const char* biosName = 0;
500	char biosPath[PATH_MAX];
501	environCallback(RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY, &sysDir);
502
503#ifdef M_CORE_GBA
504	if (core->platform(core) == PLATFORM_GBA) {
505		core->setPeripheral(core, mPERIPH_GBA_LUMINANCE, &lux);
506		biosName = "gba_bios.bin";
507
508	}
509#endif
510
511#ifdef M_CORE_GB
512	if (core->platform(core) == PLATFORM_GB) {
513		memset(&cam, 0, sizeof(cam));
514		cam.height = GBCAM_HEIGHT;
515		cam.width = GBCAM_WIDTH;
516		cam.caps = 1 << RETRO_CAMERA_BUFFER_RAW_FRAMEBUFFER;
517		cam.frame_raw_framebuffer = _updateCamera;
518		core->setPeripheral(core, mPERIPH_IMAGE_SOURCE, &imageSource);
519
520		environCallback(RETRO_ENVIRONMENT_GET_CAMERA_INTERFACE, &cam);
521		const char* modelName = mCoreConfigGetValue(&core->config, "gb.model");
522		struct GB* gb = core->board;
523
524		if (modelName) {
525			gb->model = GBNameToModel(modelName);
526		} else {
527			GBDetectModel(gb);
528		}
529
530		switch (gb->model) {
531		case GB_MODEL_AGB:
532		case GB_MODEL_CGB:
533			biosName = "gbc_bios.bin";
534			break;
535		case GB_MODEL_SGB:
536			biosName = "sgb_bios.bin";
537			break;
538		case GB_MODEL_DMG:
539		default:
540			biosName = "gb_bios.bin";
541			break;
542		}
543	}
544#endif
545
546	if (core->opts.useBios && sysDir && biosName) {
547		snprintf(biosPath, sizeof(biosPath), "%s%s%s", sysDir, PATH_SEP, biosName);
548		struct VFile* bios = VFileOpen(biosPath, O_RDONLY);
549		if (bios) {
550			core->loadBIOS(core, bios, 0);
551		}
552	}
553
554	core->reset(core);
555	_setupMaps(core);
556
557	return true;
558}
559
560void retro_unload_game(void) {
561	if (!core) {
562		return;
563	}
564	core->deinit(core);
565	mappedMemoryFree(data, dataSize);
566	data = 0;
567	mappedMemoryFree(savedata, SIZE_CART_FLASH1M);
568	savedata = 0;
569}
570
571size_t retro_serialize_size(void) {
572	struct VFile* vfm = VFileMemChunk(NULL, 0);
573	mCoreSaveStateNamed(core, vfm, SAVESTATE_SAVEDATA | SAVESTATE_RTC);
574	size_t size = vfm->size(vfm);
575	vfm->close(vfm);
576	return size;
577}
578
579bool retro_serialize(void* data, size_t size) {
580	struct VFile* vfm = VFileMemChunk(NULL, 0);
581	mCoreSaveStateNamed(core, vfm, SAVESTATE_SAVEDATA | SAVESTATE_RTC);
582	if ((ssize_t) size > vfm->size(vfm)) {
583		size = vfm->size(vfm);
584	} else if ((ssize_t) size < vfm->size(vfm)) {
585		vfm->close(vfm);
586		return false;
587	}
588	vfm->seek(vfm, 0, SEEK_SET);
589	vfm->read(vfm, data, size);
590	vfm->close(vfm);
591	return true;
592}
593
594bool retro_unserialize(const void* data, size_t size) {
595	struct VFile* vfm = VFileFromConstMemory(data, size);
596	bool success = mCoreLoadStateNamed(core, vfm, SAVESTATE_RTC);
597	vfm->close(vfm);
598	return success;
599}
600
601void retro_cheat_reset(void) {
602	mCheatDeviceClear(core->cheatDevice(core));
603}
604
605void retro_cheat_set(unsigned index, bool enabled, const char* code) {
606	UNUSED(index);
607	UNUSED(enabled);
608	struct mCheatDevice* device = core->cheatDevice(core);
609	struct mCheatSet* cheatSet = NULL;
610	if (mCheatSetsSize(&device->cheats)) {
611		cheatSet = *mCheatSetsGetPointer(&device->cheats, 0);
612	} else {
613		cheatSet = device->createSet(device, NULL);
614		mCheatAddSet(device, cheatSet);
615	}
616// Convert the super wonky unportable libretro format to something normal
617#ifdef M_CORE_GBA
618	if (core->platform(core) == PLATFORM_GBA) {
619		char realCode[] = "XXXXXXXX XXXXXXXX";
620		size_t len = strlen(code) + 1; // Include null terminator
621		size_t i, pos;
622		for (i = 0, pos = 0; i < len; ++i) {
623			if (isspace((int) code[i]) || code[i] == '+') {
624				realCode[pos] = ' ';
625			} else {
626				realCode[pos] = code[i];
627			}
628			if ((pos == 13 && (realCode[pos] == ' ' || !realCode[pos])) || pos == 17) {
629				realCode[pos] = '\0';
630				mCheatAddLine(cheatSet, realCode, 0);
631				pos = 0;
632				continue;
633			}
634			++pos;
635		}
636	}
637#endif
638#ifdef M_CORE_GB
639	if (core->platform(core) == PLATFORM_GB) {
640		char realCode[] = "XXX-XXX-XXX";
641		size_t len = strlen(code) + 1; // Include null terminator
642		size_t i, pos;
643		for (i = 0, pos = 0; i < len; ++i) {
644			if (isspace((int) code[i]) || code[i] == '+') {
645				realCode[pos] = '\0';
646			} else {
647				realCode[pos] = code[i];
648			}
649			if (pos == 11 || !realCode[pos]) {
650				realCode[pos] = '\0';
651				mCheatAddLine(cheatSet, realCode, 0);
652				pos = 0;
653				continue;
654			}
655			++pos;
656		}
657	}
658#endif
659}
660
661unsigned retro_get_region(void) {
662	return RETRO_REGION_NTSC; // TODO: This isn't strictly true
663}
664
665void retro_set_controller_port_device(unsigned port, unsigned device) {
666	UNUSED(port);
667	UNUSED(device);
668}
669
670bool retro_load_game_special(unsigned game_type, const struct retro_game_info* info, size_t num_info) {
671	UNUSED(game_type);
672	UNUSED(info);
673	UNUSED(num_info);
674	return false;
675}
676
677void* retro_get_memory_data(unsigned id) {
678	if (id != RETRO_MEMORY_SAVE_RAM) {
679		return 0;
680	}
681	return savedata;
682}
683
684size_t retro_get_memory_size(unsigned id) {
685	if (id != RETRO_MEMORY_SAVE_RAM) {
686		return 0;
687	}
688#ifdef M_CORE_GBA
689	if (core->platform(core) == PLATFORM_GBA) {
690		switch (((struct GBA*) core->board)->memory.savedata.type) {
691		case SAVEDATA_AUTODETECT:
692			return SIZE_CART_FLASH1M;
693		default:
694			return GBASavedataSize(&((struct GBA*) core->board)->memory.savedata);
695		}
696	}
697#endif
698#ifdef M_CORE_GB
699	if (core->platform(core) == PLATFORM_GB) {
700		return ((struct GB*) core->board)->sramSize;
701	}
702#endif
703	return 0;
704}
705
706void GBARetroLog(struct mLogger* logger, int category, enum mLogLevel level, const char* format, va_list args) {
707	UNUSED(logger);
708	if (!logCallback) {
709		return;
710	}
711
712	char message[128];
713	vsnprintf(message, sizeof(message), format, args);
714
715	enum retro_log_level retroLevel = RETRO_LOG_INFO;
716	switch (level) {
717	case mLOG_ERROR:
718	case mLOG_FATAL:
719		retroLevel = RETRO_LOG_ERROR;
720		break;
721	case mLOG_WARN:
722		retroLevel = RETRO_LOG_WARN;
723		break;
724	case mLOG_INFO:
725		retroLevel = RETRO_LOG_INFO;
726		break;
727	case mLOG_GAME_ERROR:
728	case mLOG_STUB:
729#ifdef NDEBUG
730		return;
731#else
732		retroLevel = RETRO_LOG_DEBUG;
733		break;
734#endif
735	case mLOG_DEBUG:
736		retroLevel = RETRO_LOG_DEBUG;
737		break;
738	}
739#ifdef NDEBUG
740	static int biosCat = -1;
741	if (biosCat < 0) {
742		biosCat = mLogCategoryById("gba.bios");
743	}
744
745	if (category == biosCat) {
746		return;
747	}
748#endif
749	logCallback(retroLevel, "%s: %s\n", mLogCategoryName(category), message);
750}
751
752static void _postAudioBuffer(struct mAVStream* stream, blip_t* left, blip_t* right) {
753	UNUSED(stream);
754	int16_t samples[SAMPLES * 2];
755	blip_read_samples(left, samples, SAMPLES, true);
756	blip_read_samples(right, samples + 1, SAMPLES, true);
757	audioCallback(samples, SAMPLES);
758}
759
760static void _setRumble(struct mRumble* rumble, int enable) {
761	UNUSED(rumble);
762	if (!rumbleCallback) {
763		return;
764	}
765	if (enable) {
766		++rumbleUp;
767	} else {
768		++rumbleDown;
769	}
770}
771
772static void _updateLux(struct GBALuminanceSource* lux) {
773	UNUSED(lux);
774	struct retro_variable var = {
775		.key = "mgba_solar_sensor_level",
776		.value = 0
777	};
778
779	bool updated = false;
780	if (!environCallback(RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE, &updated) || !updated) {
781		return;
782	}
783	if (!environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || !var.value) {
784		return;
785	}
786
787	char* end;
788	int newLuxLevel = strtol(var.value, &end, 10);
789	if (!*end) {
790		if (newLuxLevel > 10) {
791			luxLevel = 10;
792		} else if (newLuxLevel < 0) {
793			luxLevel = 0;
794		} else {
795			luxLevel = newLuxLevel;
796		}
797	}
798}
799
800static uint8_t _readLux(struct GBALuminanceSource* lux) {
801	UNUSED(lux);
802	int value = 0x16;
803	if (luxLevel > 0) {
804		value += GBA_LUX_LEVELS[luxLevel - 1];
805	}
806	return 0xFF - value;
807}
808
809static void _updateCamera(const uint32_t* buffer, unsigned width, unsigned height, size_t pitch) {
810	if (!camData || width > camWidth || height > camHeight) {
811		if (camData) {
812			free(camData);
813		}
814		unsigned bufPitch = pitch / sizeof(*buffer);
815		unsigned bufHeight = height;
816		if (imcapWidth > bufPitch) {
817			bufPitch = imcapWidth;
818		}
819		if (imcapHeight > bufHeight) {
820			bufHeight = imcapHeight;
821		}
822		camData = malloc(sizeof(*buffer) * bufHeight * bufPitch);
823		memset(camData, 0xFF, sizeof(*buffer) * bufHeight * bufPitch);
824		camWidth = width;
825		camHeight = bufHeight;
826		camStride = bufPitch;
827	}
828	size_t i;
829	for (i = 0; i < height; ++i) {
830		memcpy(&camData[camStride * i], &buffer[pitch * i / sizeof(*buffer)], pitch);
831	}
832}
833
834static void _startImage(struct mImageSource* image, unsigned w, unsigned h, int colorFormats) {
835	UNUSED(image);
836	UNUSED(colorFormats);
837
838	if (camData) {
839		free(camData);
840	}
841	camData = NULL;
842	imcapWidth = w;
843	imcapHeight = h;
844	cam.start();
845}
846
847static void _stopImage(struct mImageSource* image) {
848	UNUSED(image);
849	cam.stop();	
850}
851
852static void _requestImage(struct mImageSource* image, const void** buffer, size_t* stride, enum mColorFormat* colorFormat) {
853	UNUSED(image);
854	if (!camData) {
855		cam.start();
856		*buffer = NULL;
857		return;
858	}
859	size_t offset = 0;
860	if (imcapWidth < camWidth) {
861		offset += (camWidth - imcapWidth) / 2;
862	}
863	if (imcapHeight < camHeight) {
864		offset += (camHeight - imcapHeight) / 2 * camStride;
865	}
866
867	*buffer = &camData[offset];
868	*stride = camStride;
869	*colorFormat = mCOLOR_XRGB8;
870}