all repos — mgba @ 92c6b90b03f8c04b53312bf2273d86a9783ee073

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