all repos — mgba @ d5284f0f314cbe8dc6cc34df37769be2aba1fe44

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