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#if RESAMPLE_LIBRARY == RESAMPLE_BLIP_BUF
226 blip_set_rates(context.gba->audio.left, GBA_ARM7TDMI_FREQUENCY, 32768);
227 blip_set_rates(context.gba->audio.right, GBA_ARM7TDMI_FREQUENCY, 32768);
228#endif
229
230 GBACheatDeviceCreate(&cheats);
231 GBACheatAttachDevice(context.gba, &cheats);
232 GBACheatSetInit(&cheatSet, "libretro");
233 GBACheatAddSet(&cheats, &cheatSet);
234}
235
236void retro_deinit(void) {
237 GBAContextDeinit(&context);
238 GBACheatRemoveSet(&cheats, &cheatSet);
239 GBACheatDeviceDestroy(&cheats);
240 GBACheatSetDeinit(&cheatSet);
241 free(renderer.outputBuffer);
242}
243
244void retro_run(void) {
245 uint16_t keys;
246 inputPollCallback();
247
248 struct retro_variable var = {
249 .key = "mgba_allow_opposing_directions",
250 .value = 0
251 };
252
253 bool updated = false;
254 if (environCallback(RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE, &updated) && updated) {
255 if (environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
256 context.gba->allowOpposingDirections = strcmp(var.value, "yes") == 0;
257 }
258 }
259
260 keys = 0;
261 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A)) << 0;
262 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B)) << 1;
263 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_SELECT)) << 2;
264 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START)) << 3;
265 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT)) << 4;
266 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT)) << 5;
267 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP)) << 6;
268 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN)) << 7;
269 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R)) << 8;
270 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L)) << 9;
271
272 static bool wasAdjustingLux = false;
273 if (wasAdjustingLux) {
274 wasAdjustingLux = inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R3) ||
275 inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L3);
276 } else {
277 if (inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R3)) {
278 ++luxLevel;
279 if (luxLevel > 10) {
280 luxLevel = 10;
281 }
282 wasAdjustingLux = true;
283 } else if (inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L3)) {
284 --luxLevel;
285 if (luxLevel < 0) {
286 luxLevel = 0;
287 }
288 wasAdjustingLux = true;
289 }
290 }
291
292 GBAContextFrame(&context, keys);
293 videoCallback(renderer.outputBuffer, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, BYTES_PER_PIXEL * renderer.outputBufferStride);
294}
295
296void retro_reset(void) {
297 ARMReset(context.cpu);
298
299 if (rumbleCallback) {
300 CircleBufferClear(&rumbleHistory);
301 }
302}
303
304bool retro_load_game(const struct retro_game_info* game) {
305 struct VFile* rom;
306 if (game->data) {
307 data = anonymousMemoryMap(game->size);
308 dataSize = game->size;
309 memcpy(data, game->data, game->size);
310 rom = VFileFromMemory(data, game->size);
311 } else {
312 data = 0;
313 rom = VFileOpen(game->path, O_RDONLY);
314 }
315 if (!rom) {
316 return false;
317 }
318 if (!GBAIsROM(rom)) {
319 rom->close(rom);
320 mappedMemoryFree(data, game->size);
321 return false;
322 }
323
324 savedata = anonymousMemoryMap(SIZE_CART_FLASH1M);
325 struct VFile* save = VFileFromMemory(savedata, SIZE_CART_FLASH1M);
326
327 _reloadSettings();
328 GBAContextLoadROMFromVFile(&context, rom, save);
329 GBAContextStart(&context);
330 return true;
331}
332
333void retro_unload_game(void) {
334 GBAContextStop(&context);
335 mappedMemoryFree(data, dataSize);
336 data = 0;
337 mappedMemoryFree(savedata, SIZE_CART_FLASH1M);
338 savedata = 0;
339 CircleBufferDeinit(&rumbleHistory);
340}
341
342size_t retro_serialize_size(void) {
343 return sizeof(struct GBASerializedState);
344}
345
346bool retro_serialize(void* data, size_t size) {
347 if (size != retro_serialize_size()) {
348 return false;
349 }
350 GBASerialize(context.gba, data);
351 return true;
352}
353
354bool retro_unserialize(const void* data, size_t size) {
355 if (size != retro_serialize_size()) {
356 return false;
357 }
358 GBADeserialize(context.gba, data);
359 return true;
360}
361
362void retro_cheat_reset(void) {
363 GBACheatSetDeinit(&cheatSet);
364 GBACheatSetInit(&cheatSet, "libretro");
365}
366
367void retro_cheat_set(unsigned index, bool enabled, const char* code) {
368 UNUSED(index);
369 UNUSED(enabled);
370 // Convert the super wonky unportable libretro format to something normal
371 char realCode[] = "XXXXXXXX XXXXXXXX";
372 size_t len = strlen(code) + 1; // Include null terminator
373 size_t i, pos;
374 for (i = 0, pos = 0; i < len; ++i) {
375 if (isspace((int) code[i]) || code[i] == '+') {
376 realCode[pos] = ' ';
377 } else {
378 realCode[pos] = code[i];
379 }
380 if ((pos == 13 && (realCode[pos] == ' ' || !realCode[pos])) || pos == 17) {
381 realCode[pos] = '\0';
382 GBACheatAddLine(&cheatSet, realCode);
383 pos = 0;
384 continue;
385 }
386 ++pos;
387 }
388}
389
390unsigned retro_get_region(void) {
391 return RETRO_REGION_NTSC; // TODO: This isn't strictly true
392}
393
394void retro_set_controller_port_device(unsigned port, unsigned device) {
395 UNUSED(port);
396 UNUSED(device);
397}
398
399bool retro_load_game_special(unsigned game_type, const struct retro_game_info* info, size_t num_info) {
400 UNUSED(game_type);
401 UNUSED(info);
402 UNUSED(num_info);
403 return false;
404}
405
406void* retro_get_memory_data(unsigned id) {
407 if (id != RETRO_MEMORY_SAVE_RAM) {
408 return 0;
409 }
410 return savedata;
411}
412
413size_t retro_get_memory_size(unsigned id) {
414 if (id != RETRO_MEMORY_SAVE_RAM) {
415 return 0;
416 }
417 switch (context.gba->memory.savedata.type) {
418 case SAVEDATA_AUTODETECT:
419 case SAVEDATA_FLASH1M:
420 return SIZE_CART_FLASH1M;
421 case SAVEDATA_FLASH512:
422 return SIZE_CART_FLASH512;
423 case SAVEDATA_EEPROM:
424 return SIZE_CART_EEPROM;
425 case SAVEDATA_SRAM:
426 return SIZE_CART_SRAM;
427 case SAVEDATA_FORCE_NONE:
428 return 0;
429 }
430 return 0;
431}
432
433void GBARetroLog(struct GBAThread* thread, enum GBALogLevel level, const char* format, va_list args) {
434 UNUSED(thread);
435 if (!logCallback) {
436 return;
437 }
438
439 char message[128];
440 vsnprintf(message, sizeof(message), format, args);
441
442 enum retro_log_level retroLevel = RETRO_LOG_INFO;
443 switch (level) {
444 case GBA_LOG_ALL:
445 case GBA_LOG_ERROR:
446 case GBA_LOG_FATAL:
447 retroLevel = RETRO_LOG_ERROR;
448 break;
449 case GBA_LOG_WARN:
450 retroLevel = RETRO_LOG_WARN;
451 break;
452 case GBA_LOG_INFO:
453 case GBA_LOG_GAME_ERROR:
454 case GBA_LOG_SWI:
455 case GBA_LOG_STATUS:
456 retroLevel = RETRO_LOG_INFO;
457 break;
458 case GBA_LOG_DEBUG:
459 case GBA_LOG_STUB:
460 case GBA_LOG_SIO:
461 retroLevel = RETRO_LOG_DEBUG;
462 break;
463 }
464 logCallback(retroLevel, "%s\n", message);
465}
466
467static void _postAudioBuffer(struct GBAAVStream* stream, struct GBAAudio* audio) {
468 UNUSED(stream);
469 int16_t samples[SAMPLES * 2];
470#if RESAMPLE_LIBRARY == RESAMPLE_BLIP_BUF
471 blip_read_samples(audio->left, samples, SAMPLES, true);
472 blip_read_samples(audio->right, samples + 1, SAMPLES, true);
473#else
474 int16_t samplesR[SAMPLES];
475 GBAAudioCopy(audio, &samples[SAMPLES], samplesR, SAMPLES);
476 size_t i;
477 for (i = 0; i < SAMPLES; ++i) {
478 samples[i * 2] = samples[SAMPLES + i];
479 samples[i * 2 + 1] = samplesR[i];
480 }
481#endif
482 audioCallback(samples, SAMPLES);
483}
484
485static void _setRumble(struct GBARumble* rumble, int enable) {
486 UNUSED(rumble);
487 if (!rumbleCallback) {
488 return;
489 }
490 rumbleLevel += enable;
491 if (CircleBufferSize(&rumbleHistory) == RUMBLE_PWM) {
492 int8_t oldLevel;
493 CircleBufferRead8(&rumbleHistory, &oldLevel);
494 rumbleLevel -= oldLevel;
495 }
496 CircleBufferWrite8(&rumbleHistory, enable);
497 rumbleCallback(0, RETRO_RUMBLE_STRONG, rumbleLevel * 0xFFFF / RUMBLE_PWM);
498 rumbleCallback(0, RETRO_RUMBLE_WEAK, rumbleLevel * 0xFFFF / RUMBLE_PWM);
499}
500
501static void _updateLux(struct GBALuminanceSource* lux) {
502 UNUSED(lux);
503 struct retro_variable var = {
504 .key = "mgba_solar_sensor_level",
505 .value = 0
506 };
507
508 bool updated = false;
509 if (!environCallback(RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE, &updated) || !updated) {
510 return;
511 }
512 if (!environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || !var.value) {
513 return;
514 }
515
516 char* end;
517 int newLuxLevel = strtol(var.value, &end, 10);
518 if (!*end) {
519 if (newLuxLevel > 10) {
520 luxLevel = 10;
521 } else if (newLuxLevel < 0) {
522 luxLevel = 0;
523 } else {
524 luxLevel = newLuxLevel;
525 }
526 }
527}
528
529static uint8_t _readLux(struct GBALuminanceSource* lux) {
530 UNUSED(lux);
531 int value = 0x16;
532 if (luxLevel > 0) {
533 value += GBA_LUX_LEVELS[luxLevel - 1];
534 }
535 return 0xFF - value;
536}