all repos — mgba @ a260b4cf91649498b32e3d10a06117175c9cb75f

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