all repos — mgba @ a32cb5cc5e4fa0f1590725036ca58a490d0f1164

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	memset(savedata, 0xFF, SIZE_CART_FLASH1M);
493	struct VFile* save = VFileFromMemory(savedata, SIZE_CART_FLASH1M);
494
495	_reloadSettings();
496	core->loadROM(core, rom);
497	core->loadSave(core, save);
498
499	const char* sysDir = 0;
500	const char* biosName = 0;
501	char biosPath[PATH_MAX];
502	environCallback(RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY, &sysDir);
503
504#ifdef M_CORE_GBA
505	if (core->platform(core) == PLATFORM_GBA) {
506		core->setPeripheral(core, mPERIPH_GBA_LUMINANCE, &lux);
507		biosName = "gba_bios.bin";
508
509	}
510#endif
511
512#ifdef M_CORE_GB
513	if (core->platform(core) == PLATFORM_GB) {
514		memset(&cam, 0, sizeof(cam));
515		cam.height = GBCAM_HEIGHT;
516		cam.width = GBCAM_WIDTH;
517		cam.caps = 1 << RETRO_CAMERA_BUFFER_RAW_FRAMEBUFFER;
518		cam.frame_raw_framebuffer = _updateCamera;
519		core->setPeripheral(core, mPERIPH_IMAGE_SOURCE, &imageSource);
520
521		environCallback(RETRO_ENVIRONMENT_GET_CAMERA_INTERFACE, &cam);
522		const char* modelName = mCoreConfigGetValue(&core->config, "gb.model");
523		struct GB* gb = core->board;
524
525		if (modelName) {
526			gb->model = GBNameToModel(modelName);
527		} else {
528			GBDetectModel(gb);
529		}
530
531		switch (gb->model) {
532		case GB_MODEL_AGB:
533		case GB_MODEL_CGB:
534			biosName = "gbc_bios.bin";
535			break;
536		case GB_MODEL_SGB:
537			biosName = "sgb_bios.bin";
538			break;
539		case GB_MODEL_DMG:
540		default:
541			biosName = "gb_bios.bin";
542			break;
543		}
544	}
545#endif
546
547	if (core->opts.useBios && sysDir && biosName) {
548		snprintf(biosPath, sizeof(biosPath), "%s%s%s", sysDir, PATH_SEP, biosName);
549		struct VFile* bios = VFileOpen(biosPath, O_RDONLY);
550		if (bios) {
551			core->loadBIOS(core, bios, 0);
552		}
553	}
554
555	core->reset(core);
556	_setupMaps(core);
557
558	return true;
559}
560
561void retro_unload_game(void) {
562	if (!core) {
563		return;
564	}
565	mCoreConfigDeinit(&core->config);
566	core->deinit(core);
567	mappedMemoryFree(data, dataSize);
568	data = 0;
569	mappedMemoryFree(savedata, SIZE_CART_FLASH1M);
570	savedata = 0;
571}
572
573size_t retro_serialize_size(void) {
574	struct VFile* vfm = VFileMemChunk(NULL, 0);
575	mCoreSaveStateNamed(core, vfm, SAVESTATE_SAVEDATA | SAVESTATE_RTC);
576	size_t size = vfm->size(vfm);
577	vfm->close(vfm);
578	return size;
579}
580
581bool retro_serialize(void* data, size_t size) {
582	struct VFile* vfm = VFileMemChunk(NULL, 0);
583	mCoreSaveStateNamed(core, vfm, SAVESTATE_SAVEDATA | SAVESTATE_RTC);
584	if ((ssize_t) size > vfm->size(vfm)) {
585		size = vfm->size(vfm);
586	} else if ((ssize_t) size < vfm->size(vfm)) {
587		vfm->close(vfm);
588		return false;
589	}
590	vfm->seek(vfm, 0, SEEK_SET);
591	vfm->read(vfm, data, size);
592	vfm->close(vfm);
593	return true;
594}
595
596bool retro_unserialize(const void* data, size_t size) {
597	struct VFile* vfm = VFileFromConstMemory(data, size);
598	bool success = mCoreLoadStateNamed(core, vfm, SAVESTATE_RTC);
599	vfm->close(vfm);
600	return success;
601}
602
603void retro_cheat_reset(void) {
604	mCheatDeviceClear(core->cheatDevice(core));
605}
606
607void retro_cheat_set(unsigned index, bool enabled, const char* code) {
608	UNUSED(index);
609	UNUSED(enabled);
610	struct mCheatDevice* device = core->cheatDevice(core);
611	struct mCheatSet* cheatSet = NULL;
612	if (mCheatSetsSize(&device->cheats)) {
613		cheatSet = *mCheatSetsGetPointer(&device->cheats, 0);
614	} else {
615		cheatSet = device->createSet(device, NULL);
616		mCheatAddSet(device, cheatSet);
617	}
618// Convert the super wonky unportable libretro format to something normal
619#ifdef M_CORE_GBA
620	if (core->platform(core) == PLATFORM_GBA) {
621		char realCode[] = "XXXXXXXX XXXXXXXX";
622		size_t len = strlen(code) + 1; // Include null terminator
623		size_t i, pos;
624		for (i = 0, pos = 0; i < len; ++i) {
625			if (isspace((int) code[i]) || code[i] == '+') {
626				realCode[pos] = ' ';
627			} else {
628				realCode[pos] = code[i];
629			}
630			if ((pos == 13 && (realCode[pos] == ' ' || !realCode[pos])) || pos == 17) {
631				realCode[pos] = '\0';
632				mCheatAddLine(cheatSet, realCode, 0);
633				pos = 0;
634				continue;
635			}
636			++pos;
637		}
638	}
639#endif
640#ifdef M_CORE_GB
641	if (core->platform(core) == PLATFORM_GB) {
642		char realCode[] = "XXX-XXX-XXX";
643		size_t len = strlen(code) + 1; // Include null terminator
644		size_t i, pos;
645		for (i = 0, pos = 0; i < len; ++i) {
646			if (isspace((int) code[i]) || code[i] == '+') {
647				realCode[pos] = '\0';
648			} else {
649				realCode[pos] = code[i];
650			}
651			if (pos == 11 || !realCode[pos]) {
652				realCode[pos] = '\0';
653				mCheatAddLine(cheatSet, realCode, 0);
654				pos = 0;
655				continue;
656			}
657			++pos;
658		}
659	}
660#endif
661	cheatSet->refresh(cheatSet, device);
662}
663
664unsigned retro_get_region(void) {
665	return RETRO_REGION_NTSC; // TODO: This isn't strictly true
666}
667
668void retro_set_controller_port_device(unsigned port, unsigned device) {
669	UNUSED(port);
670	UNUSED(device);
671}
672
673bool retro_load_game_special(unsigned game_type, const struct retro_game_info* info, size_t num_info) {
674	UNUSED(game_type);
675	UNUSED(info);
676	UNUSED(num_info);
677	return false;
678}
679
680void* retro_get_memory_data(unsigned id) {
681	if (id != RETRO_MEMORY_SAVE_RAM) {
682		return 0;
683	}
684	return savedata;
685}
686
687size_t retro_get_memory_size(unsigned id) {
688	if (id != RETRO_MEMORY_SAVE_RAM) {
689		return 0;
690	}
691#ifdef M_CORE_GBA
692	if (core->platform(core) == PLATFORM_GBA) {
693		switch (((struct GBA*) core->board)->memory.savedata.type) {
694		case SAVEDATA_AUTODETECT:
695			return SIZE_CART_FLASH1M;
696		default:
697			return GBASavedataSize(&((struct GBA*) core->board)->memory.savedata);
698		}
699	}
700#endif
701#ifdef M_CORE_GB
702	if (core->platform(core) == PLATFORM_GB) {
703		return ((struct GB*) core->board)->sramSize;
704	}
705#endif
706	return 0;
707}
708
709void GBARetroLog(struct mLogger* logger, int category, enum mLogLevel level, const char* format, va_list args) {
710	UNUSED(logger);
711	if (!logCallback) {
712		return;
713	}
714
715	char message[128];
716	vsnprintf(message, sizeof(message), format, args);
717
718	enum retro_log_level retroLevel = RETRO_LOG_INFO;
719	switch (level) {
720	case mLOG_ERROR:
721	case mLOG_FATAL:
722		retroLevel = RETRO_LOG_ERROR;
723		break;
724	case mLOG_WARN:
725		retroLevel = RETRO_LOG_WARN;
726		break;
727	case mLOG_INFO:
728		retroLevel = RETRO_LOG_INFO;
729		break;
730	case mLOG_GAME_ERROR:
731	case mLOG_STUB:
732#ifdef NDEBUG
733		return;
734#else
735		retroLevel = RETRO_LOG_DEBUG;
736		break;
737#endif
738	case mLOG_DEBUG:
739		retroLevel = RETRO_LOG_DEBUG;
740		break;
741	}
742#ifdef NDEBUG
743	static int biosCat = -1;
744	if (biosCat < 0) {
745		biosCat = mLogCategoryById("gba.bios");
746	}
747
748	if (category == biosCat) {
749		return;
750	}
751#endif
752	logCallback(retroLevel, "%s: %s\n", mLogCategoryName(category), message);
753}
754
755static void _postAudioBuffer(struct mAVStream* stream, blip_t* left, blip_t* right) {
756	UNUSED(stream);
757	int16_t samples[SAMPLES * 2];
758	blip_read_samples(left, samples, SAMPLES, true);
759	blip_read_samples(right, samples + 1, SAMPLES, true);
760	audioCallback(samples, SAMPLES);
761}
762
763static void _setRumble(struct mRumble* rumble, int enable) {
764	UNUSED(rumble);
765	if (!rumbleCallback) {
766		return;
767	}
768	if (enable) {
769		++rumbleUp;
770	} else {
771		++rumbleDown;
772	}
773}
774
775static void _updateLux(struct GBALuminanceSource* lux) {
776	UNUSED(lux);
777	struct retro_variable var = {
778		.key = "mgba_solar_sensor_level",
779		.value = 0
780	};
781
782	bool updated = false;
783	if (!environCallback(RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE, &updated) || !updated) {
784		return;
785	}
786	if (!environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || !var.value) {
787		return;
788	}
789
790	char* end;
791	int newLuxLevel = strtol(var.value, &end, 10);
792	if (!*end) {
793		if (newLuxLevel > 10) {
794			luxLevel = 10;
795		} else if (newLuxLevel < 0) {
796			luxLevel = 0;
797		} else {
798			luxLevel = newLuxLevel;
799		}
800	}
801}
802
803static uint8_t _readLux(struct GBALuminanceSource* lux) {
804	UNUSED(lux);
805	int value = 0x16;
806	if (luxLevel > 0) {
807		value += GBA_LUX_LEVELS[luxLevel - 1];
808	}
809	return 0xFF - value;
810}
811
812static void _updateCamera(const uint32_t* buffer, unsigned width, unsigned height, size_t pitch) {
813	if (!camData || width > camWidth || height > camHeight) {
814		if (camData) {
815			free(camData);
816		}
817		unsigned bufPitch = pitch / sizeof(*buffer);
818		unsigned bufHeight = height;
819		if (imcapWidth > bufPitch) {
820			bufPitch = imcapWidth;
821		}
822		if (imcapHeight > bufHeight) {
823			bufHeight = imcapHeight;
824		}
825		camData = malloc(sizeof(*buffer) * bufHeight * bufPitch);
826		memset(camData, 0xFF, sizeof(*buffer) * bufHeight * bufPitch);
827		camWidth = width;
828		camHeight = bufHeight;
829		camStride = bufPitch;
830	}
831	size_t i;
832	for (i = 0; i < height; ++i) {
833		memcpy(&camData[camStride * i], &buffer[pitch * i / sizeof(*buffer)], pitch);
834	}
835}
836
837static void _startImage(struct mImageSource* image, unsigned w, unsigned h, int colorFormats) {
838	UNUSED(image);
839	UNUSED(colorFormats);
840
841	if (camData) {
842		free(camData);
843	}
844	camData = NULL;
845	imcapWidth = w;
846	imcapHeight = h;
847	cam.start();
848}
849
850static void _stopImage(struct mImageSource* image) {
851	UNUSED(image);
852	cam.stop();	
853}
854
855static void _requestImage(struct mImageSource* image, const void** buffer, size_t* stride, enum mColorFormat* colorFormat) {
856	UNUSED(image);
857	if (!camData) {
858		cam.start();
859		*buffer = NULL;
860		return;
861	}
862	size_t offset = 0;
863	if (imcapWidth < camWidth) {
864		offset += (camWidth - imcapWidth) / 2;
865	}
866	if (imcapHeight < camHeight) {
867		offset += (camHeight - imcapHeight) / 2 * camStride;
868	}
869
870	*buffer = &camData[offset];
871	*stride = camStride;
872	*colorFormat = mCOLOR_XRGB8;
873}