all repos — mgba @ f6755a6e1b7b0cf2b944cd8ca842746f11d6bf82

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* gba = core->board;
301			struct GB* gb = core->board;
302			switch (core->platform(core)) {
303			case PLATFORM_GBA:
304				gba->allowOpposingDirections = strcmp(var.value, "yes") == 0;
305				break;
306			case PLATFORM_GB:
307				gb->allowOpposingDirections = strcmp(var.value, "yes") == 0;
308				break;
309			default:
310				break;
311			}
312		}
313
314		var.key = "mgba_frameskip";
315		var.value = 0;
316		if (environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
317			mCoreConfigSetUIntValue(&core->config, "frameskip", strtol(var.value, NULL, 10));
318			mCoreLoadConfig(core);
319		}
320	}
321
322	keys = 0;
323	keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A)) << 0;
324	keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B)) << 1;
325	keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_SELECT)) << 2;
326	keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START)) << 3;
327	keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT)) << 4;
328	keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT)) << 5;
329	keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP)) << 6;
330	keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN)) << 7;
331	keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R)) << 8;
332	keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L)) << 9;
333	core->setKeys(core, keys);
334
335	static bool wasAdjustingLux = false;
336	if (wasAdjustingLux) {
337		wasAdjustingLux = inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R3) ||
338		                  inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L3);
339	} else {
340		if (inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R3)) {
341			++luxLevel;
342			if (luxLevel > 10) {
343				luxLevel = 10;
344			}
345			wasAdjustingLux = true;
346		} else if (inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L3)) {
347			--luxLevel;
348			if (luxLevel < 0) {
349				luxLevel = 0;
350			}
351			wasAdjustingLux = true;
352		}
353	}
354
355	core->runFrame(core);
356	unsigned width, height;
357	core->desiredVideoDimensions(core, &width, &height);
358	videoCallback(outputBuffer, width, height, BYTES_PER_PIXEL * 256);
359
360	if (rumbleCallback) {
361		if (rumbleUp) {
362			rumbleCallback(0, RETRO_RUMBLE_STRONG, rumbleUp * 0xFFFF / (rumbleUp + rumbleDown));
363			rumbleCallback(0, RETRO_RUMBLE_WEAK, rumbleUp * 0xFFFF / (rumbleUp + rumbleDown));
364		} else {
365			rumbleCallback(0, RETRO_RUMBLE_STRONG, 0);
366			rumbleCallback(0, RETRO_RUMBLE_WEAK, 0);
367		}
368		rumbleUp = 0;
369		rumbleDown = 0;
370	}
371}
372
373static void _setupMaps(struct mCore* core) {
374#ifdef M_CORE_GBA
375	if (core->platform(core) == PLATFORM_GBA) {
376		struct GBA* gba = core->board;
377		struct retro_memory_descriptor descs[11];
378		struct retro_memory_map mmaps;
379		size_t romSize = gba->memory.romSize + (gba->memory.romSize & 1);
380
381		memset(descs, 0, sizeof(descs));
382		size_t savedataSize = retro_get_memory_size(RETRO_MEMORY_SAVE_RAM);
383
384		/* Map internal working RAM */
385		descs[0].ptr    = gba->memory.iwram;
386		descs[0].start  = BASE_WORKING_IRAM;
387		descs[0].len    = SIZE_WORKING_IRAM;
388		descs[0].select = 0xFF000000;
389
390		/* Map working RAM */
391		descs[1].ptr    = gba->memory.wram;
392		descs[1].start  = BASE_WORKING_RAM;
393		descs[1].len    = SIZE_WORKING_RAM;
394		descs[1].select = 0xFF000000;
395
396		/* Map save RAM */
397		/* TODO: if SRAM is flash, use start=0 addrspace="S" instead */
398		descs[2].ptr    = savedataSize ? savedata : NULL;
399		descs[2].start  = BASE_CART_SRAM;
400		descs[2].len    = savedataSize;
401
402		/* Map ROM */
403		descs[3].ptr    = gba->memory.rom;
404		descs[3].start  = BASE_CART0;
405		descs[3].len    = romSize;
406		descs[3].flags  = RETRO_MEMDESC_CONST;
407
408		descs[4].ptr    = gba->memory.rom;
409		descs[4].start  = BASE_CART1;
410		descs[4].len    = romSize;
411		descs[4].flags  = RETRO_MEMDESC_CONST;
412
413		descs[5].ptr    = gba->memory.rom;
414		descs[5].start  = BASE_CART2;
415		descs[5].len    = romSize;
416		descs[5].flags  = RETRO_MEMDESC_CONST;
417
418		/* Map BIOS */
419		descs[6].ptr    = gba->memory.bios;
420		descs[6].start  = BASE_BIOS;
421		descs[6].len    = SIZE_BIOS;
422		descs[6].flags  = RETRO_MEMDESC_CONST;
423
424		/* Map VRAM */
425		descs[7].ptr    = gba->video.vram;
426		descs[7].start  = BASE_VRAM;
427		descs[7].len    = SIZE_VRAM;
428		descs[7].select = 0xFF000000;
429
430		/* Map palette RAM */
431		descs[8].ptr    = gba->video.palette;
432		descs[8].start  = BASE_PALETTE_RAM;
433		descs[8].len    = SIZE_PALETTE_RAM;
434		descs[8].select = 0xFF000000;
435
436		/* Map OAM */
437		descs[9].ptr    = &gba->video.oam; /* video.oam is a structure */
438		descs[9].start  = BASE_OAM;
439		descs[9].len    = SIZE_OAM;
440		descs[9].select = 0xFF000000;
441
442		/* Map mmapped I/O */
443		descs[10].ptr    = gba->memory.io;
444		descs[10].start  = BASE_IO;
445		descs[10].len    = SIZE_IO;
446
447		mmaps.descriptors = descs;
448		mmaps.num_descriptors = sizeof(descs) / sizeof(descs[0]);
449
450		bool yes = true;
451		environCallback(RETRO_ENVIRONMENT_SET_MEMORY_MAPS, &mmaps);
452		environCallback(RETRO_ENVIRONMENT_SET_SUPPORT_ACHIEVEMENTS, &yes);
453	}
454#endif
455}
456
457void retro_reset(void) {
458	core->reset(core);
459	_setupMaps(core);
460
461	rumbleUp = 0;
462	rumbleDown = 0;
463}
464
465bool retro_load_game(const struct retro_game_info* game) {
466	struct VFile* rom;
467	if (game->data) {
468		data = anonymousMemoryMap(game->size);
469		dataSize = game->size;
470		memcpy(data, game->data, game->size);
471		rom = VFileFromMemory(data, game->size);
472	} else {
473		data = 0;
474		rom = VFileOpen(game->path, O_RDONLY);
475	}
476	if (!rom) {
477		return false;
478	}
479
480	core = mCoreFindVF(rom);
481	if (!core) {
482		rom->close(rom);
483		mappedMemoryFree(data, game->size);
484		return false;
485	}
486	mCoreInitConfig(core, NULL);
487	core->init(core);
488	core->setAVStream(core, &stream);
489
490	size_t size = 256 * 224 * BYTES_PER_PIXEL;
491	outputBuffer = malloc(size);
492	memset(outputBuffer, 0xFF, size);
493	core->setVideoBuffer(core, outputBuffer, 256);
494
495	core->setAudioBufferSize(core, SAMPLES);
496
497	blip_set_rates(core->getAudioChannel(core, 0), core->frequency(core), 32768);
498	blip_set_rates(core->getAudioChannel(core, 1), core->frequency(core), 32768);
499
500	core->setPeripheral(core, mPERIPH_RUMBLE, &rumble);
501
502	savedata = anonymousMemoryMap(SIZE_CART_FLASH1M);
503	memset(savedata, 0xFF, SIZE_CART_FLASH1M);
504	struct VFile* save = VFileFromMemory(savedata, SIZE_CART_FLASH1M);
505
506	_reloadSettings();
507	core->loadROM(core, rom);
508	core->loadSave(core, save);
509
510	const char* sysDir = 0;
511	const char* biosName = 0;
512	char biosPath[PATH_MAX];
513	environCallback(RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY, &sysDir);
514
515#ifdef M_CORE_GBA
516	if (core->platform(core) == PLATFORM_GBA) {
517		core->setPeripheral(core, mPERIPH_GBA_LUMINANCE, &lux);
518		biosName = "gba_bios.bin";
519
520	}
521#endif
522
523#ifdef M_CORE_GB
524	if (core->platform(core) == PLATFORM_GB) {
525		memset(&cam, 0, sizeof(cam));
526		cam.height = GBCAM_HEIGHT;
527		cam.width = GBCAM_WIDTH;
528		cam.caps = 1 << RETRO_CAMERA_BUFFER_RAW_FRAMEBUFFER;
529		cam.frame_raw_framebuffer = _updateCamera;
530		core->setPeripheral(core, mPERIPH_IMAGE_SOURCE, &imageSource);
531
532		environCallback(RETRO_ENVIRONMENT_GET_CAMERA_INTERFACE, &cam);
533		const char* modelName = mCoreConfigGetValue(&core->config, "gb.model");
534		struct GB* gb = core->board;
535
536		if (modelName) {
537			gb->model = GBNameToModel(modelName);
538		} else {
539			GBDetectModel(gb);
540		}
541
542		switch (gb->model) {
543		case GB_MODEL_AGB:
544		case GB_MODEL_CGB:
545			biosName = "gbc_bios.bin";
546			break;
547		case GB_MODEL_SGB:
548			biosName = "sgb_bios.bin";
549			break;
550		case GB_MODEL_DMG:
551		default:
552			biosName = "gb_bios.bin";
553			break;
554		}
555	}
556#endif
557
558	if (core->opts.useBios && sysDir && biosName) {
559		snprintf(biosPath, sizeof(biosPath), "%s%s%s", sysDir, PATH_SEP, biosName);
560		struct VFile* bios = VFileOpen(biosPath, O_RDONLY);
561		if (bios) {
562			core->loadBIOS(core, bios, 0);
563		}
564	}
565
566	core->reset(core);
567	_setupMaps(core);
568
569	return true;
570}
571
572void retro_unload_game(void) {
573	if (!core) {
574		return;
575	}
576	mCoreConfigDeinit(&core->config);
577	core->deinit(core);
578	mappedMemoryFree(data, dataSize);
579	data = 0;
580	mappedMemoryFree(savedata, SIZE_CART_FLASH1M);
581	savedata = 0;
582}
583
584size_t retro_serialize_size(void) {
585	struct VFile* vfm = VFileMemChunk(NULL, 0);
586	mCoreSaveStateNamed(core, vfm, SAVESTATE_SAVEDATA | SAVESTATE_RTC);
587	size_t size = vfm->size(vfm);
588	vfm->close(vfm);
589	return size;
590}
591
592bool retro_serialize(void* data, size_t size) {
593	struct VFile* vfm = VFileMemChunk(NULL, 0);
594	mCoreSaveStateNamed(core, vfm, SAVESTATE_SAVEDATA | SAVESTATE_RTC);
595	if ((ssize_t) size > vfm->size(vfm)) {
596		size = vfm->size(vfm);
597	} else if ((ssize_t) size < vfm->size(vfm)) {
598		vfm->close(vfm);
599		return false;
600	}
601	vfm->seek(vfm, 0, SEEK_SET);
602	vfm->read(vfm, data, size);
603	vfm->close(vfm);
604	return true;
605}
606
607bool retro_unserialize(const void* data, size_t size) {
608	struct VFile* vfm = VFileFromConstMemory(data, size);
609	bool success = mCoreLoadStateNamed(core, vfm, SAVESTATE_RTC);
610	vfm->close(vfm);
611	return success;
612}
613
614void retro_cheat_reset(void) {
615	mCheatDeviceClear(core->cheatDevice(core));
616}
617
618void retro_cheat_set(unsigned index, bool enabled, const char* code) {
619	UNUSED(index);
620	UNUSED(enabled);
621	struct mCheatDevice* device = core->cheatDevice(core);
622	struct mCheatSet* cheatSet = NULL;
623	if (mCheatSetsSize(&device->cheats)) {
624		cheatSet = *mCheatSetsGetPointer(&device->cheats, 0);
625	} else {
626		cheatSet = device->createSet(device, NULL);
627		mCheatAddSet(device, cheatSet);
628	}
629// Convert the super wonky unportable libretro format to something normal
630#ifdef M_CORE_GBA
631	if (core->platform(core) == PLATFORM_GBA) {
632		char realCode[] = "XXXXXXXX XXXXXXXX";
633		size_t len = strlen(code) + 1; // Include null terminator
634		size_t i, pos;
635		for (i = 0, pos = 0; i < len; ++i) {
636			if (isspace((int) code[i]) || code[i] == '+') {
637				realCode[pos] = ' ';
638			} else {
639				realCode[pos] = code[i];
640			}
641			if ((pos == 13 && (realCode[pos] == ' ' || !realCode[pos])) || pos == 17) {
642				realCode[pos] = '\0';
643				mCheatAddLine(cheatSet, realCode, 0);
644				pos = 0;
645				continue;
646			}
647			++pos;
648		}
649	}
650#endif
651#ifdef M_CORE_GB
652	if (core->platform(core) == PLATFORM_GB) {
653		char realCode[] = "XXX-XXX-XXX";
654		size_t len = strlen(code) + 1; // Include null terminator
655		size_t i, pos;
656		for (i = 0, pos = 0; i < len; ++i) {
657			if (isspace((int) code[i]) || code[i] == '+') {
658				realCode[pos] = '\0';
659			} else {
660				realCode[pos] = code[i];
661			}
662			if (pos == 11 || !realCode[pos]) {
663				realCode[pos] = '\0';
664				mCheatAddLine(cheatSet, realCode, 0);
665				pos = 0;
666				continue;
667			}
668			++pos;
669		}
670	}
671#endif
672	cheatSet->refresh(cheatSet, device);
673}
674
675unsigned retro_get_region(void) {
676	return RETRO_REGION_NTSC; // TODO: This isn't strictly true
677}
678
679void retro_set_controller_port_device(unsigned port, unsigned device) {
680	UNUSED(port);
681	UNUSED(device);
682}
683
684bool retro_load_game_special(unsigned game_type, const struct retro_game_info* info, size_t num_info) {
685	UNUSED(game_type);
686	UNUSED(info);
687	UNUSED(num_info);
688	return false;
689}
690
691void* retro_get_memory_data(unsigned id) {
692	if (id != RETRO_MEMORY_SAVE_RAM) {
693		return 0;
694	}
695	return savedata;
696}
697
698size_t retro_get_memory_size(unsigned id) {
699	if (id != RETRO_MEMORY_SAVE_RAM) {
700		return 0;
701	}
702#ifdef M_CORE_GBA
703	if (core->platform(core) == PLATFORM_GBA) {
704		switch (((struct GBA*) core->board)->memory.savedata.type) {
705		case SAVEDATA_AUTODETECT:
706			return SIZE_CART_FLASH1M;
707		default:
708			return GBASavedataSize(&((struct GBA*) core->board)->memory.savedata);
709		}
710	}
711#endif
712#ifdef M_CORE_GB
713	if (core->platform(core) == PLATFORM_GB) {
714		return ((struct GB*) core->board)->sramSize;
715	}
716#endif
717	return 0;
718}
719
720void GBARetroLog(struct mLogger* logger, int category, enum mLogLevel level, const char* format, va_list args) {
721	UNUSED(logger);
722	if (!logCallback) {
723		return;
724	}
725
726	char message[128];
727	vsnprintf(message, sizeof(message), format, args);
728
729	enum retro_log_level retroLevel = RETRO_LOG_INFO;
730	switch (level) {
731	case mLOG_ERROR:
732	case mLOG_FATAL:
733		retroLevel = RETRO_LOG_ERROR;
734		break;
735	case mLOG_WARN:
736		retroLevel = RETRO_LOG_WARN;
737		break;
738	case mLOG_INFO:
739		retroLevel = RETRO_LOG_INFO;
740		break;
741	case mLOG_GAME_ERROR:
742	case mLOG_STUB:
743#ifdef NDEBUG
744		return;
745#else
746		retroLevel = RETRO_LOG_DEBUG;
747		break;
748#endif
749	case mLOG_DEBUG:
750		retroLevel = RETRO_LOG_DEBUG;
751		break;
752	}
753#ifdef NDEBUG
754	static int biosCat = -1;
755	if (biosCat < 0) {
756		biosCat = mLogCategoryById("gba.bios");
757	}
758
759	if (category == biosCat) {
760		return;
761	}
762#endif
763	logCallback(retroLevel, "%s: %s\n", mLogCategoryName(category), message);
764}
765
766static void _postAudioBuffer(struct mAVStream* stream, blip_t* left, blip_t* right) {
767	UNUSED(stream);
768	int16_t samples[SAMPLES * 2];
769	blip_read_samples(left, samples, SAMPLES, true);
770	blip_read_samples(right, samples + 1, SAMPLES, true);
771	audioCallback(samples, SAMPLES);
772}
773
774static void _setRumble(struct mRumble* rumble, int enable) {
775	UNUSED(rumble);
776	if (!rumbleCallback) {
777		return;
778	}
779	if (enable) {
780		++rumbleUp;
781	} else {
782		++rumbleDown;
783	}
784}
785
786static void _updateLux(struct GBALuminanceSource* lux) {
787	UNUSED(lux);
788	struct retro_variable var = {
789		.key = "mgba_solar_sensor_level",
790		.value = 0
791	};
792
793	bool updated = false;
794	if (!environCallback(RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE, &updated) || !updated) {
795		return;
796	}
797	if (!environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || !var.value) {
798		return;
799	}
800
801	char* end;
802	int newLuxLevel = strtol(var.value, &end, 10);
803	if (!*end) {
804		if (newLuxLevel > 10) {
805			luxLevel = 10;
806		} else if (newLuxLevel < 0) {
807			luxLevel = 0;
808		} else {
809			luxLevel = newLuxLevel;
810		}
811	}
812}
813
814static uint8_t _readLux(struct GBALuminanceSource* lux) {
815	UNUSED(lux);
816	int value = 0x16;
817	if (luxLevel > 0) {
818		value += GBA_LUX_LEVELS[luxLevel - 1];
819	}
820	return 0xFF - value;
821}
822
823static void _updateCamera(const uint32_t* buffer, unsigned width, unsigned height, size_t pitch) {
824	if (!camData || width > camWidth || height > camHeight) {
825		if (camData) {
826			free(camData);
827		}
828		unsigned bufPitch = pitch / sizeof(*buffer);
829		unsigned bufHeight = height;
830		if (imcapWidth > bufPitch) {
831			bufPitch = imcapWidth;
832		}
833		if (imcapHeight > bufHeight) {
834			bufHeight = imcapHeight;
835		}
836		camData = malloc(sizeof(*buffer) * bufHeight * bufPitch);
837		memset(camData, 0xFF, sizeof(*buffer) * bufHeight * bufPitch);
838		camWidth = width;
839		camHeight = bufHeight;
840		camStride = bufPitch;
841	}
842	size_t i;
843	for (i = 0; i < height; ++i) {
844		memcpy(&camData[camStride * i], &buffer[pitch * i / sizeof(*buffer)], pitch);
845	}
846}
847
848static void _startImage(struct mImageSource* image, unsigned w, unsigned h, int colorFormats) {
849	UNUSED(image);
850	UNUSED(colorFormats);
851
852	if (camData) {
853		free(camData);
854	}
855	camData = NULL;
856	imcapWidth = w;
857	imcapHeight = h;
858	cam.start();
859}
860
861static void _stopImage(struct mImageSource* image) {
862	UNUSED(image);
863	cam.stop();	
864}
865
866static void _requestImage(struct mImageSource* image, const void** buffer, size_t* stride, enum mColorFormat* colorFormat) {
867	UNUSED(image);
868	if (!camData) {
869		cam.start();
870		*buffer = NULL;
871		return;
872	}
873	size_t offset = 0;
874	if (imcapWidth < camWidth) {
875		offset += (camWidth - imcapWidth) / 2;
876	}
877	if (imcapHeight < camHeight) {
878		offset += (camHeight - imcapHeight) / 2 * camStride;
879	}
880
881	*buffer = &camData[offset];
882	*stride = camStride;
883	*colorFormat = mCOLOR_XRGB8;
884}