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