all repos — mgba @ 78b761cf017c6ee039810f29316b3736eee07fd4

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 "util/common.h"
  9
 10#include "gba/cheats.h"
 11#include "gba/renderers/video-software.h"
 12#include "gba/serialize.h"
 13#include "gba/context/context.h"
 14#include "util/circle-buffer.h"
 15#include "util/memory.h"
 16#include "util/vfs.h"
 17
 18#define SAMPLES 1024
 19#define RUMBLE_PWM 35
 20
 21#define SOLAR_SENSOR_LEVEL "mgba_solar_sensor_level"
 22#define ALLOW_OPPOSING_DIRECTIONS "mgba_allow_opposing_directions"
 23#define USE_BIOS "mgba_use_bios"
 24#define SKIP_BIOS "mgba_skip_bios"
 25#define IDLE_OPTIMIZATION "mgba_idle_optimization"
 26
 27static retro_environment_t environCallback;
 28static retro_video_refresh_t videoCallback;
 29static retro_audio_sample_batch_t audioCallback;
 30static retro_input_poll_t inputPollCallback;
 31static retro_input_state_t inputCallback;
 32static retro_log_printf_t logCallback;
 33static retro_set_rumble_state_t rumbleCallback;
 34
 35static void GBARetroLog(struct GBAThread* thread, enum GBALogLevel level, const char* format, va_list args);
 36
 37static void _postAudioBuffer(struct GBAAVStream*, struct GBAAudio* audio);
 38static void _setRumble(struct GBARumble* rumble, int enable);
 39static uint8_t _readLux(struct GBALuminanceSource* lux);
 40static void _updateLux(struct GBALuminanceSource* lux);
 41
 42static struct GBAContext context;
 43static struct GBAVideoSoftwareRenderer renderer;
 44static void* data;
 45static size_t dataSize;
 46static void* savedata;
 47static struct GBAAVStream stream;
 48static int rumbleLevel;
 49static struct CircleBuffer rumbleHistory;
 50static struct GBARumble rumble;
 51static struct GBALuminanceSource lux;
 52static int luxLevel;
 53static struct GBACheatDevice cheats;
 54static struct GBACheatSet cheatSet;
 55
 56static void _reloadSettings(void) {
 57	struct GBAOptions opts = {
 58		.useBios = true,
 59		.idleOptimization = IDLE_LOOP_REMOVE
 60	};
 61
 62	struct retro_variable var;
 63
 64	var.key = USE_BIOS;
 65	var.value = 0;
 66	if (environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
 67		opts.useBios = strcmp(var.value, "yes") == 0;
 68	}
 69
 70	var.key = SKIP_BIOS;
 71	var.value = 0;
 72	if (environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
 73		opts.skipBios = strcmp(var.value, "yes") == 0;
 74	}
 75
 76	var.key = IDLE_OPTIMIZATION;
 77	var.value = 0;
 78	if (environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
 79		if (strcmp(var.value, "don't remove") == 0) {
 80			opts.idleOptimization = IDLE_LOOP_IGNORE;
 81		} else if (strcmp(var.value, "remove known") == 0) {
 82			opts.idleOptimization = IDLE_LOOP_REMOVE;
 83		} else if (strcmp(var.value, "detect and remove") == 0) {
 84			opts.idleOptimization = IDLE_LOOP_DETECT;
 85		}
 86	}
 87
 88	GBAConfigLoadDefaults(&context.config, &opts);
 89}
 90
 91unsigned retro_api_version(void) {
 92   return RETRO_API_VERSION;
 93}
 94
 95void retro_set_environment(retro_environment_t env) {
 96	environCallback = env;
 97
 98	struct retro_variable vars[] = {
 99		{ SOLAR_SENSOR_LEVEL, "Solar sensor level; 0|1|2|3|4|5|6|7|8|9|10" },
100		{ ALLOW_OPPOSING_DIRECTIONS, "Allow opposing directional input; no|yes" },
101		{ USE_BIOS, "Use BIOS file if found; yes|no" },
102		{ SKIP_BIOS, "Skip BIOS intro; no|yes" },
103		{ IDLE_OPTIMIZATION, "Idle loop removal; remove known|detect and remove|don't remove" },
104		{ 0, 0 }
105	};
106
107	environCallback(RETRO_ENVIRONMENT_SET_VARIABLES, vars);
108}
109
110void retro_set_video_refresh(retro_video_refresh_t video) {
111	videoCallback = video;
112}
113
114void retro_set_audio_sample(retro_audio_sample_t audio) {
115	UNUSED(audio);
116}
117
118void retro_set_audio_sample_batch(retro_audio_sample_batch_t audioBatch) {
119	audioCallback = audioBatch;
120}
121
122void retro_set_input_poll(retro_input_poll_t inputPoll) {
123	inputPollCallback = inputPoll;
124}
125
126void retro_set_input_state(retro_input_state_t input) {
127	inputCallback = input;
128}
129
130void retro_get_system_info(struct retro_system_info* info) {
131   info->need_fullpath = false;
132   info->valid_extensions = "gba";
133   info->library_version = projectVersion;
134   info->library_name = projectName;
135   info->block_extract = false;
136}
137
138void retro_get_system_av_info(struct retro_system_av_info* info) {
139   info->geometry.base_width = VIDEO_HORIZONTAL_PIXELS;
140   info->geometry.base_height = VIDEO_VERTICAL_PIXELS;
141   info->geometry.max_width = VIDEO_HORIZONTAL_PIXELS;
142   info->geometry.max_height = VIDEO_VERTICAL_PIXELS;
143   info->geometry.aspect_ratio = 3.0 / 2.0;
144   info->timing.fps =  GBA_ARM7TDMI_FREQUENCY / (float) VIDEO_TOTAL_LENGTH;
145   info->timing.sample_rate = 32768;
146}
147
148void retro_init(void) {
149	enum retro_pixel_format fmt;
150#ifdef COLOR_16_BIT
151#ifdef COLOR_5_6_5
152	fmt = RETRO_PIXEL_FORMAT_RGB565;
153#else
154#warning This pixel format is unsupported. Please use -DCOLOR_16-BIT -DCOLOR_5_6_5
155	fmt = RETRO_PIXEL_FORMAT_0RGB1555;
156#endif
157#else
158#warning This pixel format is unsupported. Please use -DCOLOR_16-BIT -DCOLOR_5_6_5
159	fmt = RETRO_PIXEL_FORMAT_XRGB8888;
160#endif
161	environCallback(RETRO_ENVIRONMENT_SET_PIXEL_FORMAT, &fmt);
162
163	struct retro_input_descriptor inputDescriptors[] = {
164		{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A, "A" },
165		{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B, "B" },
166		{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_SELECT, "Select" },
167		{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START, "Start" },
168		{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT, "Right" },
169		{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT, "Left" },
170		{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP, "Up" },
171		{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN, "Down" },
172		{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R, "R" },
173		{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L, "L" },
174		{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R3, "Brighten Solar Sensor" },
175		{ 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L3, "Darken Solar Sensor" }
176	};
177	environCallback(RETRO_ENVIRONMENT_SET_INPUT_DESCRIPTORS, &inputDescriptors);
178
179	// TODO: RETRO_ENVIRONMENT_SET_SUPPORT_NO_GAME when BIOS booting is supported
180
181	struct retro_rumble_interface rumbleInterface;
182	if (environCallback(RETRO_ENVIRONMENT_GET_RUMBLE_INTERFACE, &rumbleInterface)) {
183		rumbleCallback = rumbleInterface.set_rumble_state;
184		CircleBufferInit(&rumbleHistory, RUMBLE_PWM);
185		rumble.setRumble = _setRumble;
186	} else {
187		rumbleCallback = 0;
188	}
189
190	luxLevel = 0;
191	lux.readLuminance = _readLux;
192	lux.sample = _updateLux;
193	_updateLux(&lux);
194
195	struct retro_log_callback log;
196	if (environCallback(RETRO_ENVIRONMENT_GET_LOG_INTERFACE, &log)) {
197		logCallback = log.log;
198	} else {
199		logCallback = 0;
200	}
201
202	stream.postAudioFrame = 0;
203	stream.postAudioBuffer = _postAudioBuffer;
204	stream.postVideoFrame = 0;
205
206	GBAContextInit(&context, 0);
207	context.gba->logHandler = GBARetroLog;
208	context.gba->stream = &stream;
209	if (rumbleCallback) {
210		context.gba->rumble = &rumble;
211	}
212	context.gba->luminanceSource = &lux;
213
214	const char* sysDir = 0;
215	if (environCallback(RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY, &sysDir)) {
216		char biosPath[PATH_MAX];
217		snprintf(biosPath, sizeof(biosPath), "%s%s%s", sysDir, PATH_SEP, "gba_bios.bin");
218		struct VFile* bios = VFileOpen(biosPath, O_RDONLY);
219		if (bios) {
220			GBAContextLoadBIOSFromVFile(&context, bios);
221		}
222	}
223
224	GBAVideoSoftwareRendererCreate(&renderer);
225	renderer.outputBuffer = malloc(256 * VIDEO_VERTICAL_PIXELS * BYTES_PER_PIXEL);
226	renderer.outputBufferStride = 256;
227	context.renderer = &renderer.d;
228
229	GBAAudioResizeBuffer(&context.gba->audio, SAMPLES);
230
231#if RESAMPLE_LIBRARY == RESAMPLE_BLIP_BUF
232	blip_set_rates(context.gba->audio.left,  GBA_ARM7TDMI_FREQUENCY, 32768);
233	blip_set_rates(context.gba->audio.right, GBA_ARM7TDMI_FREQUENCY, 32768);
234#endif
235
236	GBACheatDeviceCreate(&cheats);
237	GBACheatAttachDevice(context.gba, &cheats);
238	GBACheatSetInit(&cheatSet, "libretro");
239	GBACheatAddSet(&cheats, &cheatSet);
240}
241
242void retro_deinit(void) {
243	GBAContextDeinit(&context);
244	GBACheatRemoveSet(&cheats, &cheatSet);
245	GBACheatDeviceDestroy(&cheats);
246	GBACheatSetDeinit(&cheatSet);
247	free(renderer.outputBuffer);
248}
249
250void retro_run(void) {
251	uint16_t keys;
252	inputPollCallback();
253
254	struct retro_variable var = {
255		.key = ALLOW_OPPOSING_DIRECTIONS,
256		.value = 0
257	};
258
259	bool updated = false;
260	if (environCallback(RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE, &updated) && updated) {
261		if (environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
262			context.gba->allowOpposingDirections = strcmp(var.value, "yes") == 0;
263		}
264	}
265
266	keys = 0;
267	keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A)) << 0;
268	keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B)) << 1;
269	keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_SELECT)) << 2;
270	keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START)) << 3;
271	keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT)) << 4;
272	keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT)) << 5;
273	keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP)) << 6;
274	keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN)) << 7;
275	keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R)) << 8;
276	keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L)) << 9;
277
278	static bool wasAdjustingLux = false;
279	if (wasAdjustingLux) {
280		wasAdjustingLux = inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R3) ||
281		                  inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L3);
282	} else {
283		if (inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R3)) {
284			++luxLevel;
285			if (luxLevel > 10) {
286				luxLevel = 10;
287			}
288			wasAdjustingLux = true;
289		} else if (inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L3)) {
290			--luxLevel;
291			if (luxLevel < 0) {
292				luxLevel = 0;
293			}
294			wasAdjustingLux = true;
295		}
296	}
297
298	GBAContextFrame(&context, keys);
299	videoCallback(renderer.outputBuffer, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, BYTES_PER_PIXEL * renderer.outputBufferStride);
300}
301
302void retro_reset(void) {
303	ARMReset(context.cpu);
304
305	if (rumbleCallback) {
306		CircleBufferClear(&rumbleHistory);
307	}
308}
309
310bool retro_load_game(const struct retro_game_info* game) {
311	struct VFile* rom;
312	if (game->data) {
313		data = anonymousMemoryMap(game->size);
314		dataSize = game->size;
315		memcpy(data, game->data, game->size);
316		rom = VFileFromMemory(data, game->size);
317	} else {
318		data = 0;
319		rom = VFileOpen(game->path, O_RDONLY);
320	}
321	if (!rom) {
322		return false;
323	}
324	if (!GBAIsROM(rom)) {
325		rom->close(rom);
326		mappedMemoryFree(data, game->size);
327		return false;
328	}
329
330	savedata = anonymousMemoryMap(SIZE_CART_FLASH1M);
331	struct VFile* save = VFileFromMemory(savedata, SIZE_CART_FLASH1M);
332
333	_reloadSettings();
334	GBAContextLoadROMFromVFile(&context, rom, save);
335	GBAContextStart(&context);
336	return true;
337}
338
339void retro_unload_game(void) {
340	GBAContextStop(&context);
341	mappedMemoryFree(data, dataSize);
342	data = 0;
343	mappedMemoryFree(savedata, SIZE_CART_FLASH1M);
344	savedata = 0;
345	CircleBufferDeinit(&rumbleHistory);
346}
347
348size_t retro_serialize_size(void) {
349	return sizeof(struct GBASerializedState);
350}
351
352bool retro_serialize(void* data, size_t size) {
353	if (size != retro_serialize_size()) {
354		return false;
355	}
356	GBASerialize(context.gba, data);
357	return true;
358}
359
360bool retro_unserialize(const void* data, size_t size) {
361	if (size != retro_serialize_size()) {
362		return false;
363	}
364	GBADeserialize(context.gba, data);
365	return true;
366}
367
368void retro_cheat_reset(void) {
369	GBACheatSetDeinit(&cheatSet);
370	GBACheatSetInit(&cheatSet, "libretro");
371}
372
373void retro_cheat_set(unsigned index, bool enabled, const char* code) {
374	UNUSED(index);
375	UNUSED(enabled);
376	// Convert the super wonky unportable libretro format to something normal
377	char realCode[] = "XXXXXXXX XXXXXXXX";
378	size_t len = strlen(code) + 1; // Include null terminator
379	size_t i, pos;
380	for (i = 0, pos = 0; i < len; ++i) {
381		if (isspace((int) code[i]) || code[i] == '+') {
382			realCode[pos] = ' ';
383		} else {
384			realCode[pos] = code[i];
385		}
386		if ((pos == 13 && (realCode[pos] == ' ' || !realCode[pos])) || pos == 17) {
387			realCode[pos] = '\0';
388			GBACheatAddLine(&cheatSet, realCode);
389			pos = 0;
390			continue;
391		}
392		++pos;
393	}
394}
395
396unsigned retro_get_region(void) {
397	return RETRO_REGION_NTSC; // TODO: This isn't strictly true
398}
399
400void retro_set_controller_port_device(unsigned port, unsigned device) {
401	UNUSED(port);
402	UNUSED(device);
403}
404
405bool retro_load_game_special(unsigned game_type, const struct retro_game_info* info, size_t num_info) {
406	UNUSED(game_type);
407	UNUSED(info);
408	UNUSED(num_info);
409	return false;
410}
411
412void* retro_get_memory_data(unsigned id) {
413	if (id != RETRO_MEMORY_SAVE_RAM) {
414		return 0;
415	}
416	return savedata;
417}
418
419size_t retro_get_memory_size(unsigned id) {
420	if (id != RETRO_MEMORY_SAVE_RAM) {
421		return 0;
422	}
423	switch (context.gba->memory.savedata.type) {
424	case SAVEDATA_AUTODETECT:
425	case SAVEDATA_FLASH1M:
426		return SIZE_CART_FLASH1M;
427	case SAVEDATA_FLASH512:
428		return SIZE_CART_FLASH512;
429	case SAVEDATA_EEPROM:
430		return SIZE_CART_EEPROM;
431	case SAVEDATA_SRAM:
432		return SIZE_CART_SRAM;
433	case SAVEDATA_FORCE_NONE:
434		return 0;
435	}
436	return 0;
437}
438
439void GBARetroLog(struct GBAThread* thread, enum GBALogLevel level, const char* format, va_list args) {
440	UNUSED(thread);
441	if (!logCallback) {
442		return;
443	}
444
445	char message[128];
446	vsnprintf(message, sizeof(message), format, args);
447
448	enum retro_log_level retroLevel = RETRO_LOG_INFO;
449	switch (level) {
450	case GBA_LOG_ALL:
451	case GBA_LOG_ERROR:
452	case GBA_LOG_FATAL:
453		retroLevel = RETRO_LOG_ERROR;
454		break;
455	case GBA_LOG_WARN:
456		retroLevel = RETRO_LOG_WARN;
457		break;
458	case GBA_LOG_INFO:
459	case GBA_LOG_GAME_ERROR:
460	case GBA_LOG_SWI:
461	case GBA_LOG_STATUS:
462		retroLevel = RETRO_LOG_INFO;
463		break;
464	case GBA_LOG_DEBUG:
465	case GBA_LOG_STUB:
466	case GBA_LOG_SIO:
467		retroLevel = RETRO_LOG_DEBUG;
468		break;
469	}
470	logCallback(retroLevel, "%s\n", message);
471}
472
473static void _postAudioBuffer(struct GBAAVStream* stream, struct GBAAudio* audio) {
474	UNUSED(stream);
475	int16_t samples[SAMPLES * 2];
476#if RESAMPLE_LIBRARY == RESAMPLE_BLIP_BUF
477	blip_read_samples(audio->left, samples, SAMPLES, true);
478	blip_read_samples(audio->right, samples + 1, SAMPLES, true);
479#else
480	int16_t samplesR[SAMPLES];
481	GBAAudioCopy(audio, &samples[SAMPLES], samplesR, SAMPLES);
482	size_t i;
483	for (i = 0; i < SAMPLES; ++i) {
484		samples[i * 2] = samples[SAMPLES + i];
485		samples[i * 2 + 1] = samplesR[i];
486	}
487#endif
488	audioCallback(samples, SAMPLES);
489}
490
491static void _setRumble(struct GBARumble* rumble, int enable) {
492	UNUSED(rumble);
493	if (!rumbleCallback) {
494		return;
495	}
496	rumbleLevel += enable;
497	if (CircleBufferSize(&rumbleHistory) == RUMBLE_PWM) {
498		int8_t oldLevel;
499		CircleBufferRead8(&rumbleHistory, &oldLevel);
500		rumbleLevel -= oldLevel;
501	}
502	CircleBufferWrite8(&rumbleHistory, enable);
503	rumbleCallback(0, RETRO_RUMBLE_STRONG, rumbleLevel * 0xFFFF / RUMBLE_PWM);
504	rumbleCallback(0, RETRO_RUMBLE_WEAK, rumbleLevel * 0xFFFF / RUMBLE_PWM);
505}
506
507static void _updateLux(struct GBALuminanceSource* lux) {
508	UNUSED(lux);
509	struct retro_variable var = {
510		.key = SOLAR_SENSOR_LEVEL,
511		.value = 0
512	};
513
514	bool updated = false;
515	if (!environCallback(RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE, &updated) || !updated) {
516		return;
517	}
518	if (!environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || !var.value) {
519		return;
520	}
521
522	char* end;
523	int newLuxLevel = strtol(var.value, &end, 10);
524	if (!*end) {
525		if (newLuxLevel > 10) {
526			luxLevel = 10;
527		} else if (newLuxLevel < 0) {
528			luxLevel = 0;
529		} else {
530			luxLevel = newLuxLevel;
531		}
532	}
533}
534
535static uint8_t _readLux(struct GBALuminanceSource* lux) {
536	UNUSED(lux);
537	int value = 0x16;
538	if (luxLevel > 0) {
539		value += GBA_LUX_LEVELS[luxLevel - 1];
540	}
541	return 0xFF - value;
542}