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 core->setRumble(core, &rumble);
328
329#ifdef M_CORE_GBA
330 if (core->platform(core) == PLATFORM_GBA) {
331 struct GBA* gba = core->board;
332 gba->luminanceSource = &lux;
333
334 const char* sysDir = 0;
335 if (environCallback(RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY, &sysDir)) {
336 char biosPath[PATH_MAX];
337 snprintf(biosPath, sizeof(biosPath), "%s%s%s", sysDir, PATH_SEP, "gba_bios.bin");
338 struct VFile* bios = VFileOpen(biosPath, O_RDONLY);
339 if (bios) {
340 core->loadBIOS(core, bios, 0);
341 }
342 }
343
344 GBACheatDeviceCreate(&cheats);
345 GBACheatAttachDevice(gba, &cheats);
346 GBACheatSetInit(&cheatSet, "libretro");
347 GBACheatAddSet(&cheats, &cheatSet);
348 }
349#endif
350
351 savedata = anonymousMemoryMap(SIZE_CART_FLASH1M);
352 struct VFile* save = VFileFromMemory(savedata, SIZE_CART_FLASH1M);
353
354 _reloadSettings();
355 core->loadROM(core, rom);
356 core->loadSave(core, save);
357 core->reset(core);
358 return true;
359}
360
361void retro_unload_game(void) {
362 core->deinit(core);
363 mappedMemoryFree(data, dataSize);
364 data = 0;
365 mappedMemoryFree(savedata, SIZE_CART_FLASH1M);
366 savedata = 0;
367 CircleBufferDeinit(&rumbleHistory);
368}
369
370size_t retro_serialize_size(void) {
371 return sizeof(struct GBASerializedState);
372}
373
374bool retro_serialize(void* data, size_t size) {
375 if (size != retro_serialize_size()) {
376 return false;
377 }
378 GBASerialize(core->board, data);
379 return true;
380}
381
382bool retro_unserialize(const void* data, size_t size) {
383 if (size != retro_serialize_size()) {
384 return false;
385 }
386 GBADeserialize(core->board, data);
387 return true;
388}
389
390void retro_cheat_reset(void) {
391 GBACheatSetDeinit(&cheatSet);
392 GBACheatSetInit(&cheatSet, "libretro");
393}
394
395void retro_cheat_set(unsigned index, bool enabled, const char* code) {
396 UNUSED(index);
397 UNUSED(enabled);
398 // Convert the super wonky unportable libretro format to something normal
399 char realCode[] = "XXXXXXXX XXXXXXXX";
400 size_t len = strlen(code) + 1; // Include null terminator
401 size_t i, pos;
402 for (i = 0, pos = 0; i < len; ++i) {
403 if (isspace((int) code[i]) || code[i] == '+') {
404 realCode[pos] = ' ';
405 } else {
406 realCode[pos] = code[i];
407 }
408 if ((pos == 13 && (realCode[pos] == ' ' || !realCode[pos])) || pos == 17) {
409 realCode[pos] = '\0';
410 GBACheatAddLine(&cheatSet, realCode);
411 pos = 0;
412 continue;
413 }
414 ++pos;
415 }
416}
417
418unsigned retro_get_region(void) {
419 return RETRO_REGION_NTSC; // TODO: This isn't strictly true
420}
421
422void retro_set_controller_port_device(unsigned port, unsigned device) {
423 UNUSED(port);
424 UNUSED(device);
425}
426
427bool retro_load_game_special(unsigned game_type, const struct retro_game_info* info, size_t num_info) {
428 UNUSED(game_type);
429 UNUSED(info);
430 UNUSED(num_info);
431 return false;
432}
433
434void* retro_get_memory_data(unsigned id) {
435 if (id != RETRO_MEMORY_SAVE_RAM) {
436 return 0;
437 }
438 return savedata;
439}
440
441size_t retro_get_memory_size(unsigned id) {
442 if (id != RETRO_MEMORY_SAVE_RAM) {
443 return 0;
444 }
445 switch (((struct GBA*) core->board)->memory.savedata.type) {
446 case SAVEDATA_AUTODETECT:
447 case SAVEDATA_FLASH1M:
448 return SIZE_CART_FLASH1M;
449 case SAVEDATA_FLASH512:
450 return SIZE_CART_FLASH512;
451 case SAVEDATA_EEPROM:
452 return SIZE_CART_EEPROM;
453 case SAVEDATA_SRAM:
454 return SIZE_CART_SRAM;
455 case SAVEDATA_FORCE_NONE:
456 return 0;
457 }
458 return 0;
459}
460
461void GBARetroLog(struct mLogger* logger, int category, enum mLogLevel level, const char* format, va_list args) {
462 UNUSED(logger);
463 if (!logCallback) {
464 return;
465 }
466
467 char message[128];
468 vsnprintf(message, sizeof(message), format, args);
469
470 enum retro_log_level retroLevel = RETRO_LOG_INFO;
471 switch (level) {
472 case mLOG_ERROR:
473 case mLOG_FATAL:
474 retroLevel = RETRO_LOG_ERROR;
475 break;
476 case mLOG_WARN:
477 retroLevel = RETRO_LOG_WARN;
478 break;
479 case mLOG_INFO:
480 case mLOG_GAME_ERROR:
481 retroLevel = RETRO_LOG_INFO;
482 break;
483 case mLOG_DEBUG:
484 case mLOG_STUB:
485 retroLevel = RETRO_LOG_DEBUG;
486 break;
487 }
488 logCallback(retroLevel, "%s: %s\n", mLogCategoryName(category), message);
489}
490
491static void _postAudioBuffer(struct mAVStream* stream, blip_t* left, blip_t* right) {
492 UNUSED(stream);
493 int16_t samples[SAMPLES * 2];
494 blip_read_samples(left, samples, SAMPLES, true);
495 blip_read_samples(right, samples + 1, SAMPLES, true);
496 audioCallback(samples, SAMPLES);
497}
498
499static void _setRumble(struct mRumble* rumble, int enable) {
500 UNUSED(rumble);
501 if (!rumbleCallback) {
502 return;
503 }
504 rumbleLevel += enable;
505 if (CircleBufferSize(&rumbleHistory) == RUMBLE_PWM) {
506 int8_t oldLevel;
507 CircleBufferRead8(&rumbleHistory, &oldLevel);
508 rumbleLevel -= oldLevel;
509 }
510 CircleBufferWrite8(&rumbleHistory, enable);
511 rumbleCallback(0, RETRO_RUMBLE_STRONG, rumbleLevel * 0xFFFF / RUMBLE_PWM);
512 rumbleCallback(0, RETRO_RUMBLE_WEAK, rumbleLevel * 0xFFFF / RUMBLE_PWM);
513}
514
515static void _updateLux(struct GBALuminanceSource* lux) {
516 UNUSED(lux);
517 struct retro_variable var = {
518 .key = "mgba_solar_sensor_level",
519 .value = 0
520 };
521
522 bool updated = false;
523 if (!environCallback(RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE, &updated) || !updated) {
524 return;
525 }
526 if (!environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || !var.value) {
527 return;
528 }
529
530 char* end;
531 int newLuxLevel = strtol(var.value, &end, 10);
532 if (!*end) {
533 if (newLuxLevel > 10) {
534 luxLevel = 10;
535 } else if (newLuxLevel < 0) {
536 luxLevel = 0;
537 } else {
538 luxLevel = newLuxLevel;
539 }
540 }
541}
542
543static uint8_t _readLux(struct GBALuminanceSource* lux) {
544 UNUSED(lux);
545 int value = 0x16;
546 if (luxLevel > 0) {
547 value += GBA_LUX_LEVELS[luxLevel - 1];
548 }
549 return 0xFF - value;
550}