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 "core/version.h"
12#ifdef M_CORE_GB
13#include "gb/core.h"
14#include "gb/gb.h"
15#endif
16#ifdef M_CORE_GBA
17#include "gba/bios.h"
18#include "gba/core.h"
19#include "gba/cheats.h"
20#include "gba/core.h"
21#include "gba/serialize.h"
22#endif
23#include "util/circle-buffer.h"
24#include "util/memory.h"
25#include "util/vfs.h"
26
27#define SAMPLES 1024
28#define RUMBLE_PWM 35
29
30static retro_environment_t environCallback;
31static retro_video_refresh_t videoCallback;
32static retro_audio_sample_batch_t audioCallback;
33static retro_input_poll_t inputPollCallback;
34static retro_input_state_t inputCallback;
35static retro_log_printf_t logCallback;
36static retro_set_rumble_state_t rumbleCallback;
37
38static void GBARetroLog(struct mLogger* logger, int category, enum mLogLevel level, const char* format, va_list args);
39
40static void _postAudioBuffer(struct mAVStream*, blip_t* left, blip_t* right);
41static void _setRumble(struct mRumble* rumble, int enable);
42static uint8_t _readLux(struct GBALuminanceSource* lux);
43static void _updateLux(struct GBALuminanceSource* lux);
44
45static struct mCore* core;
46static void* outputBuffer;
47static void* data;
48static size_t dataSize;
49static void* savedata;
50static struct mAVStream stream;
51static int rumbleLevel;
52static struct CircleBuffer rumbleHistory;
53static struct mRumble rumble;
54static struct GBALuminanceSource lux;
55static int luxLevel;
56static struct mLogger logger;
57
58static void _reloadSettings(void) {
59 struct mCoreOptions opts = {
60 .useBios = true,
61 .volume = 0x100,
62 };
63
64 struct retro_variable var;
65
66 var.key = "mgba_use_bios";
67 var.value = 0;
68 if (environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
69 opts.useBios = strcmp(var.value, "ON") == 0;
70 }
71
72 var.key = "mgba_skip_bios";
73 var.value = 0;
74 if (environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
75 opts.skipBios = strcmp(var.value, "ON") == 0;
76 }
77
78 var.key = "mgba_idle_optimization";
79 var.value = 0;
80 if (environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
81 if (strcmp(var.value, "Don't Remove") == 0) {
82 mCoreConfigSetDefaultValue(&core->config, "idleOptimization", "ignore");
83 } else if (strcmp(var.value, "Remove Known") == 0) {
84 mCoreConfigSetDefaultValue(&core->config, "idleOptimization", "remove");
85 } else if (strcmp(var.value, "Detect and Remove") == 0) {
86 mCoreConfigSetDefaultValue(&core->config, "idleOptimization", "detect");
87 }
88 }
89
90 mCoreConfigLoadDefaults(&core->config, &opts);
91 mCoreLoadConfig(core);
92}
93
94unsigned retro_api_version(void) {
95 return RETRO_API_VERSION;
96}
97
98void retro_set_environment(retro_environment_t env) {
99 environCallback = env;
100
101 struct retro_variable vars[] = {
102 { "mgba_solar_sensor_level", "Solar sensor level; 0|1|2|3|4|5|6|7|8|9|10" },
103 { "mgba_allow_opposing_directions", "Allow opposing directional input; OFF|ON" },
104 { "mgba_use_bios", "Use BIOS file if found; ON|OFF" },
105 { "mgba_skip_bios", "Skip BIOS intro; OFF|ON" },
106 { "mgba_idle_optimization", "Idle loop removal; Remove Known|Detect and Remove|Don't Remove" },
107 { 0, 0 }
108 };
109
110 environCallback(RETRO_ENVIRONMENT_SET_VARIABLES, vars);
111}
112
113void retro_set_video_refresh(retro_video_refresh_t video) {
114 videoCallback = video;
115}
116
117void retro_set_audio_sample(retro_audio_sample_t audio) {
118 UNUSED(audio);
119}
120
121void retro_set_audio_sample_batch(retro_audio_sample_batch_t audioBatch) {
122 audioCallback = audioBatch;
123}
124
125void retro_set_input_poll(retro_input_poll_t inputPoll) {
126 inputPollCallback = inputPoll;
127}
128
129void retro_set_input_state(retro_input_state_t input) {
130 inputCallback = input;
131}
132
133void retro_get_system_info(struct retro_system_info* info) {
134 info->need_fullpath = false;
135 info->valid_extensions = "gba|gb|gbc";
136 info->library_version = projectVersion;
137 info->library_name = projectName;
138 info->block_extract = false;
139}
140
141void retro_get_system_av_info(struct retro_system_av_info* info) {
142 unsigned width, height;
143 core->desiredVideoDimensions(core, &width, &height);
144 info->geometry.base_width = width;
145 info->geometry.base_height = height;
146 info->geometry.max_width = width;
147 info->geometry.max_height = height;
148 info->geometry.aspect_ratio = width / (double) height;
149 info->timing.fps = GBA_ARM7TDMI_FREQUENCY / (float) VIDEO_TOTAL_LENGTH;
150 info->timing.sample_rate = 32768;
151}
152
153void retro_init(void) {
154 enum retro_pixel_format fmt;
155#ifdef COLOR_16_BIT
156#ifdef COLOR_5_6_5
157 fmt = RETRO_PIXEL_FORMAT_RGB565;
158#else
159#warning This pixel format is unsupported. Please use -DCOLOR_16-BIT -DCOLOR_5_6_5
160 fmt = RETRO_PIXEL_FORMAT_0RGB1555;
161#endif
162#else
163#warning This pixel format is unsupported. Please use -DCOLOR_16-BIT -DCOLOR_5_6_5
164 fmt = RETRO_PIXEL_FORMAT_XRGB8888;
165#endif
166 environCallback(RETRO_ENVIRONMENT_SET_PIXEL_FORMAT, &fmt);
167
168 struct retro_input_descriptor inputDescriptors[] = {
169 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A, "A" },
170 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B, "B" },
171 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_SELECT, "Select" },
172 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START, "Start" },
173 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT, "Right" },
174 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT, "Left" },
175 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP, "Up" },
176 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN, "Down" },
177 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R, "R" },
178 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L, "L" },
179 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R3, "Brighten Solar Sensor" },
180 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L3, "Darken Solar Sensor" }
181 };
182 environCallback(RETRO_ENVIRONMENT_SET_INPUT_DESCRIPTORS, &inputDescriptors);
183
184 // TODO: RETRO_ENVIRONMENT_SET_SUPPORT_NO_GAME when BIOS booting is supported
185
186 struct retro_rumble_interface rumbleInterface;
187 if (environCallback(RETRO_ENVIRONMENT_GET_RUMBLE_INTERFACE, &rumbleInterface)) {
188 rumbleCallback = rumbleInterface.set_rumble_state;
189 CircleBufferInit(&rumbleHistory, RUMBLE_PWM);
190 rumble.setRumble = _setRumble;
191 } else {
192 rumbleCallback = 0;
193 }
194
195 luxLevel = 0;
196 lux.readLuminance = _readLux;
197 lux.sample = _updateLux;
198 _updateLux(&lux);
199
200 struct retro_log_callback log;
201 if (environCallback(RETRO_ENVIRONMENT_GET_LOG_INTERFACE, &log)) {
202 logCallback = log.log;
203 } else {
204 logCallback = 0;
205 }
206 logger.log = GBARetroLog;
207 mLogSetDefaultLogger(&logger);
208
209 stream.videoDimensionsChanged = 0;
210 stream.postAudioFrame = 0;
211 stream.postAudioBuffer = _postAudioBuffer;
212 stream.postVideoFrame = 0;
213}
214
215void retro_deinit(void) {
216 free(outputBuffer);
217}
218
219void retro_run(void) {
220 uint16_t keys;
221 inputPollCallback();
222
223 struct retro_variable var = {
224 .key = "mgba_allow_opposing_directions",
225 .value = 0
226 };
227
228 bool updated = false;
229 if (environCallback(RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE, &updated) && updated) {
230 if (environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
231 ((struct GBA*) core->board)->allowOpposingDirections = strcmp(var.value, "yes") == 0;
232 }
233 }
234
235 keys = 0;
236 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A)) << 0;
237 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B)) << 1;
238 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_SELECT)) << 2;
239 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START)) << 3;
240 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT)) << 4;
241 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT)) << 5;
242 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP)) << 6;
243 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN)) << 7;
244 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R)) << 8;
245 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L)) << 9;
246 core->setKeys(core, keys);
247
248 static bool wasAdjustingLux = false;
249 if (wasAdjustingLux) {
250 wasAdjustingLux = inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R3) ||
251 inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L3);
252 } else {
253 if (inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R3)) {
254 ++luxLevel;
255 if (luxLevel > 10) {
256 luxLevel = 10;
257 }
258 wasAdjustingLux = true;
259 } else if (inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L3)) {
260 --luxLevel;
261 if (luxLevel < 0) {
262 luxLevel = 0;
263 }
264 wasAdjustingLux = true;
265 }
266 }
267
268 core->runFrame(core);
269 unsigned width, height;
270 core->desiredVideoDimensions(core, &width, &height);
271 videoCallback(outputBuffer, width, height, BYTES_PER_PIXEL * 256);
272}
273
274void retro_reset(void) {
275 core->reset(core);
276
277 if (rumbleCallback) {
278 CircleBufferClear(&rumbleHistory);
279 }
280}
281
282bool retro_load_game(const struct retro_game_info* game) {
283 struct VFile* rom;
284 if (game->data) {
285 data = anonymousMemoryMap(game->size);
286 dataSize = game->size;
287 memcpy(data, game->data, game->size);
288 rom = VFileFromMemory(data, game->size);
289 } else {
290 data = 0;
291 rom = VFileOpen(game->path, O_RDONLY);
292 }
293 if (!rom) {
294 return false;
295 }
296
297 core = NULL;
298#ifdef M_CORE_GBA
299 if (!core && GBAIsROM(rom)) {
300 core = GBACoreCreate();
301 }
302#endif
303#ifdef M_CORE_GB
304 if (!core && GBIsROM(rom)) {
305 core = GBCoreCreate();
306 }
307#endif
308 if (!core) {
309 rom->close(rom);
310 mappedMemoryFree(data, game->size);
311 return false;
312 }
313 mCoreInitConfig(core, NULL);
314 core->init(core);
315 core->setAVStream(core, &stream);
316
317 outputBuffer = malloc(256 * VIDEO_VERTICAL_PIXELS * BYTES_PER_PIXEL);
318 core->setVideoBuffer(core, outputBuffer, 256);
319
320 core->setAudioBufferSize(core, SAMPLES);
321
322 blip_set_rates(core->getAudioChannel(core, 0), core->frequency(core), 32768);
323 blip_set_rates(core->getAudioChannel(core, 1), core->frequency(core), 32768);
324
325 core->setRumble(core, &rumble);
326
327#ifdef M_CORE_GBA
328 if (core->platform(core) == PLATFORM_GBA) {
329 struct GBA* gba = core->board;
330 gba->luminanceSource = &lux;
331
332 const char* sysDir = 0;
333 if (environCallback(RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY, &sysDir)) {
334 char biosPath[PATH_MAX];
335 snprintf(biosPath, sizeof(biosPath), "%s%s%s", sysDir, PATH_SEP, "gba_bios.bin");
336 struct VFile* bios = VFileOpen(biosPath, O_RDONLY);
337 if (bios) {
338 core->loadBIOS(core, bios, 0);
339 }
340 }
341 }
342#endif
343
344 savedata = anonymousMemoryMap(SIZE_CART_FLASH1M);
345 struct VFile* save = VFileFromMemory(savedata, SIZE_CART_FLASH1M);
346
347 _reloadSettings();
348 core->loadROM(core, rom);
349 core->loadSave(core, save);
350 core->reset(core);
351 return true;
352}
353
354void retro_unload_game(void) {
355 if (!core) {
356 return;
357 }
358 core->deinit(core);
359 mappedMemoryFree(data, dataSize);
360 data = 0;
361 mappedMemoryFree(savedata, SIZE_CART_FLASH1M);
362 savedata = 0;
363 CircleBufferDeinit(&rumbleHistory);
364}
365
366size_t retro_serialize_size(void) {
367 return sizeof(struct GBASerializedState);
368}
369
370bool retro_serialize(void* data, size_t size) {
371 if (size != retro_serialize_size()) {
372 return false;
373 }
374 GBASerialize(core->board, data);
375 return true;
376}
377
378bool retro_unserialize(const void* data, size_t size) {
379 if (size != retro_serialize_size()) {
380 return false;
381 }
382 GBADeserialize(core->board, data);
383 return true;
384}
385
386void retro_cheat_reset(void) {
387 mCheatDeviceClear(core->cheatDevice(core));
388}
389
390void retro_cheat_set(unsigned index, bool enabled, const char* code) {
391 UNUSED(index);
392 UNUSED(enabled);
393 struct mCheatDevice* device = core->cheatDevice(core);
394 struct mCheatSet* cheatSet = NULL;
395 if (mCheatSetsSize(&device->cheats)) {
396 cheatSet = *mCheatSetsGetPointer(&device->cheats, 0);
397 } else {
398 cheatSet = device->createSet(device, NULL);
399 mCheatAddSet(device, cheatSet);
400 }
401 // Convert the super wonky unportable libretro format to something normal
402 char realCode[] = "XXXXXXXX XXXXXXXX";
403 size_t len = strlen(code) + 1; // Include null terminator
404 size_t i, pos;
405 for (i = 0, pos = 0; i < len; ++i) {
406 if (isspace((int) code[i]) || code[i] == '+') {
407 realCode[pos] = ' ';
408 } else {
409 realCode[pos] = code[i];
410 }
411 if ((pos == 13 && (realCode[pos] == ' ' || !realCode[pos])) || pos == 17) {
412 realCode[pos] = '\0';
413 mCheatAddLine(cheatSet, realCode, 0);
414 pos = 0;
415 continue;
416 }
417 ++pos;
418 }
419}
420
421unsigned retro_get_region(void) {
422 return RETRO_REGION_NTSC; // TODO: This isn't strictly true
423}
424
425void retro_set_controller_port_device(unsigned port, unsigned device) {
426 UNUSED(port);
427 UNUSED(device);
428}
429
430bool retro_load_game_special(unsigned game_type, const struct retro_game_info* info, size_t num_info) {
431 UNUSED(game_type);
432 UNUSED(info);
433 UNUSED(num_info);
434 return false;
435}
436
437void* retro_get_memory_data(unsigned id) {
438 if (id != RETRO_MEMORY_SAVE_RAM) {
439 return 0;
440 }
441 return savedata;
442}
443
444size_t retro_get_memory_size(unsigned id) {
445 if (id != RETRO_MEMORY_SAVE_RAM) {
446 return 0;
447 }
448 switch (((struct GBA*) core->board)->memory.savedata.type) {
449 case SAVEDATA_AUTODETECT:
450 case SAVEDATA_FLASH1M:
451 return SIZE_CART_FLASH1M;
452 case SAVEDATA_FLASH512:
453 return SIZE_CART_FLASH512;
454 case SAVEDATA_EEPROM:
455 return SIZE_CART_EEPROM;
456 case SAVEDATA_SRAM:
457 return SIZE_CART_SRAM;
458 case SAVEDATA_FORCE_NONE:
459 return 0;
460 }
461 return 0;
462}
463
464void GBARetroLog(struct mLogger* logger, int category, enum mLogLevel level, const char* format, va_list args) {
465 UNUSED(logger);
466 if (!logCallback) {
467 return;
468 }
469
470 char message[128];
471 vsnprintf(message, sizeof(message), format, args);
472
473 enum retro_log_level retroLevel = RETRO_LOG_INFO;
474 switch (level) {
475 case mLOG_ERROR:
476 case mLOG_FATAL:
477 retroLevel = RETRO_LOG_ERROR;
478 break;
479 case mLOG_WARN:
480 retroLevel = RETRO_LOG_WARN;
481 break;
482 case mLOG_INFO:
483 retroLevel = RETRO_LOG_INFO;
484 break;
485 case mLOG_GAME_ERROR:
486 case mLOG_STUB:
487#ifdef NDEBUG
488 return;
489#else
490 retroLevel = RETRO_LOG_DEBUG;
491 break;
492#endif
493 case mLOG_DEBUG:
494 retroLevel = RETRO_LOG_DEBUG;
495 break;
496 }
497#ifdef NDEBUG
498 if (category == _mLOG_CAT_GBA_BIOS()) {
499 return;
500 }
501#endif
502 logCallback(retroLevel, "%s: %s\n", mLogCategoryName(category), message);
503}
504
505static void _postAudioBuffer(struct mAVStream* stream, blip_t* left, blip_t* right) {
506 UNUSED(stream);
507 int16_t samples[SAMPLES * 2];
508 blip_read_samples(left, samples, SAMPLES, true);
509 blip_read_samples(right, samples + 1, SAMPLES, true);
510 audioCallback(samples, SAMPLES);
511}
512
513static void _setRumble(struct mRumble* rumble, int enable) {
514 UNUSED(rumble);
515 if (!rumbleCallback) {
516 return;
517 }
518 rumbleLevel += enable;
519 if (CircleBufferSize(&rumbleHistory) == RUMBLE_PWM) {
520 int8_t oldLevel;
521 CircleBufferRead8(&rumbleHistory, &oldLevel);
522 rumbleLevel -= oldLevel;
523 }
524 CircleBufferWrite8(&rumbleHistory, enable);
525 rumbleCallback(0, RETRO_RUMBLE_STRONG, rumbleLevel * 0xFFFF / RUMBLE_PWM);
526 rumbleCallback(0, RETRO_RUMBLE_WEAK, rumbleLevel * 0xFFFF / RUMBLE_PWM);
527}
528
529static void _updateLux(struct GBALuminanceSource* lux) {
530 UNUSED(lux);
531 struct retro_variable var = {
532 .key = "mgba_solar_sensor_level",
533 .value = 0
534 };
535
536 bool updated = false;
537 if (!environCallback(RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE, &updated) || !updated) {
538 return;
539 }
540 if (!environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || !var.value) {
541 return;
542 }
543
544 char* end;
545 int newLuxLevel = strtol(var.value, &end, 10);
546 if (!*end) {
547 if (newLuxLevel > 10) {
548 luxLevel = 10;
549 } else if (newLuxLevel < 0) {
550 luxLevel = 0;
551 } else {
552 luxLevel = newLuxLevel;
553 }
554 }
555}
556
557static uint8_t _readLux(struct GBALuminanceSource* lux) {
558 UNUSED(lux);
559 int value = 0x16;
560 if (luxLevel > 0) {
561 value += GBA_LUX_LEVELS[luxLevel - 1];
562 }
563 return 0xFF - value;
564}