all repos — mgba @ 2af1bf68e0a0833d368859d1c1bf4a04f8833552

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