all repos — mgba @ 8452e880c2d976b4054ce0e2cb5df0a2c230ee15

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