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 .logLevel = 0,
162 .idleOptimization = IDLE_LOOP_REMOVE
163 };
164 GBAConfigLoadDefaults(&context.config, &opts);
165 context.gba->logHandler = GBARetroLog;
166 context.gba->stream = &stream;
167 if (rumbleCallback) {
168 context.gba->rumble = &rumble;
169 }
170 context.gba->luminanceSource = &lux;
171
172 const char* sysDir = 0;
173 if (environCallback(RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY, &sysDir)) {
174 char biosPath[PATH_MAX];
175 snprintf(biosPath, sizeof(biosPath), "%s%s%s", sysDir, PATH_SEP, "gba_bios.bin");
176 struct VFile* bios = VFileOpen(biosPath, O_RDONLY);
177 if (bios) {
178 GBAContextLoadBIOSFromVFile(&context, bios);
179 }
180 }
181
182 GBAVideoSoftwareRendererCreate(&renderer);
183 renderer.outputBuffer = malloc(256 * VIDEO_VERTICAL_PIXELS * BYTES_PER_PIXEL);
184 renderer.outputBufferStride = 256;
185 context->renderer = &renderer.d;
186
187 GBAAudioResizeBuffer(&context.gba->audio, SAMPLES);
188
189#if RESAMPLE_LIBRARY == RESAMPLE_BLIP_BUF
190 blip_set_rates(context.gba->audio.left, GBA_ARM7TDMI_FREQUENCY, 32768);
191 blip_set_rates(context.gba->audio.right, GBA_ARM7TDMI_FREQUENCY, 32768);
192#endif
193}
194
195void retro_deinit(void) {
196 GBAContextDeinit(&context);
197}
198
199void retro_run(void) {
200 uint16_t keys;
201 inputPollCallback();
202
203 keys = 0;
204 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A)) << 0;
205 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B)) << 1;
206 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_SELECT)) << 2;
207 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START)) << 3;
208 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT)) << 4;
209 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT)) << 5;
210 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP)) << 6;
211 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN)) << 7;
212 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R)) << 8;
213 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L)) << 9;
214
215 static bool wasAdjustingLux = false;
216 if (wasAdjustingLux) {
217 wasAdjustingLux = inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R3) ||
218 inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L3);
219 } else {
220 if (inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R3)) {
221 ++luxLevel;
222 if (luxLevel > 10) {
223 luxLevel = 10;
224 }
225 wasAdjustingLux = true;
226 } else if (inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L3)) {
227 --luxLevel;
228 if (luxLevel < 0) {
229 luxLevel = 0;
230 }
231 wasAdjustingLux = true;
232 }
233 }
234
235 GBAContextFrame(&context, keys);
236}
237
238void retro_reset(void) {
239 ARMReset(context.cpu);
240
241 if (rumbleCallback) {
242 CircleBufferClear(&rumbleHistory);
243 }
244}
245
246bool retro_load_game(const struct retro_game_info* game) {
247 struct VFile* rom;
248 if (game->data) {
249 data = malloc(game->size);
250 memcpy(data, game->data, game->size);
251 rom = VFileFromMemory(data, game->size);
252 } else {
253 data = 0;
254 rom = VFileOpen(game->path, O_RDONLY);
255 }
256 if (!rom) {
257 return false;
258 }
259 if (!GBAIsROM(rom)) {
260 rom->close(rom);
261 free(data);
262 return false;
263 }
264
265 savedata = malloc(SIZE_CART_FLASH1M);
266 struct VFile* save = VFileFromMemory(savedata, SIZE_CART_FLASH1M);
267
268 GBAContextLoadROMFromVFile(&context, rom, save);
269 GBAContextStart(&context);
270 return true;
271}
272
273void retro_unload_game(void) {
274 GBAContextStop(&context);
275 free(data);
276 data = 0;
277 free(savedata);
278 savedata = 0;
279 CircleBufferDeinit(&rumbleHistory);
280}
281
282size_t retro_serialize_size(void) {
283 return sizeof(struct GBASerializedState);
284}
285
286bool retro_serialize(void* data, size_t size) {
287 if (size != retro_serialize_size()) {
288 return false;
289 }
290 GBASerialize(context.gba, data);
291 return true;
292}
293
294bool retro_unserialize(const void* data, size_t size) {
295 if (size != retro_serialize_size()) {
296 return false;
297 }
298 GBADeserialize(context.gba, data);
299 return true;
300}
301
302void retro_cheat_reset(void) {
303 // TODO: Cheats
304}
305
306void retro_cheat_set(unsigned index, bool enabled, const char* code) {
307 // TODO: Cheats
308 UNUSED(index);
309 UNUSED(enabled);
310 UNUSED(code);
311}
312
313unsigned retro_get_region(void) {
314 return RETRO_REGION_NTSC; // TODO: This isn't strictly true
315}
316
317void retro_set_controller_port_device(unsigned port, unsigned device) {
318 UNUSED(port);
319 UNUSED(device);
320}
321
322bool retro_load_game_special(unsigned game_type, const struct retro_game_info* info, size_t num_info) {
323 UNUSED(game_type);
324 UNUSED(info);
325 UNUSED(num_info);
326 return false;
327}
328
329void* retro_get_memory_data(unsigned id) {
330 if (id != RETRO_MEMORY_SAVE_RAM) {
331 return 0;
332 }
333 return savedata;
334}
335
336size_t retro_get_memory_size(unsigned id) {
337 if (id != RETRO_MEMORY_SAVE_RAM) {
338 return 0;
339 }
340 switch (context.gba->memory.savedata.type) {
341 case SAVEDATA_AUTODETECT:
342 case SAVEDATA_FLASH1M:
343 return SIZE_CART_FLASH1M;
344 case SAVEDATA_FLASH512:
345 return SIZE_CART_FLASH512;
346 case SAVEDATA_EEPROM:
347 return SIZE_CART_EEPROM;
348 case SAVEDATA_SRAM:
349 return SIZE_CART_SRAM;
350 case SAVEDATA_FORCE_NONE:
351 return 0;
352 }
353 return 0;
354}
355
356void GBARetroLog(struct GBAThread* thread, enum GBALogLevel level, const char* format, va_list args) {
357 UNUSED(thread);
358 if (!logCallback) {
359 return;
360 }
361
362 char message[128];
363 vsnprintf(message, sizeof(message), format, args);
364
365 enum retro_log_level retroLevel = RETRO_LOG_INFO;
366 switch (level) {
367 case GBA_LOG_ALL:
368 case GBA_LOG_ERROR:
369 case GBA_LOG_FATAL:
370 retroLevel = RETRO_LOG_ERROR;
371 break;
372 case GBA_LOG_WARN:
373 retroLevel = RETRO_LOG_WARN;
374 break;
375 case GBA_LOG_INFO:
376 case GBA_LOG_GAME_ERROR:
377 case GBA_LOG_SWI:
378 case GBA_LOG_STATUS:
379 retroLevel = RETRO_LOG_INFO;
380 break;
381 case GBA_LOG_DEBUG:
382 case GBA_LOG_STUB:
383 case GBA_LOG_SIO:
384 retroLevel = RETRO_LOG_DEBUG;
385 break;
386 }
387 logCallback(retroLevel, "%s\n", message);
388}
389
390static void _postAudioBuffer(struct GBAAVStream* stream, struct GBAAudio* audio) {
391 UNUSED(stream);
392 int16_t samples[SAMPLES * 2];
393#if RESAMPLE_LIBRARY == RESAMPLE_BLIP_BUF
394 blip_read_samples(audio->left, samples, SAMPLES, true);
395 blip_read_samples(audio->right, samples + 1, SAMPLES, true);
396#else
397 int16_t samplesR[SAMPLES];
398 GBAAudioCopy(audio, &samples[SAMPLES], samplesR, SAMPLES);
399 size_t i;
400 for (i = 0; i < SAMPLES; ++i) {
401 samples[i * 2] = samples[SAMPLES + i];
402 samples[i * 2 + 1] = samplesR[i];
403 }
404#endif
405 audioCallback(samples, SAMPLES);
406}
407
408static void _postVideoFrame(struct GBAAVStream* stream, struct GBAVideoRenderer* renderer) {
409 UNUSED(stream);
410 const void* pixels;
411 unsigned stride;
412 renderer->getPixels(renderer, &stride, &pixels);
413 videoCallback(pixels, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, BYTES_PER_PIXEL * stride);
414}
415
416static void _setRumble(struct GBARumble* rumble, int enable) {
417 UNUSED(rumble);
418 if (!rumbleCallback) {
419 return;
420 }
421 rumbleLevel += enable;
422 if (CircleBufferSize(&rumbleHistory) == RUMBLE_PWM) {
423 int8_t oldLevel;
424 CircleBufferRead8(&rumbleHistory, &oldLevel);
425 rumbleLevel -= oldLevel;
426 }
427 CircleBufferWrite8(&rumbleHistory, enable);
428 rumbleCallback(0, RETRO_RUMBLE_STRONG, rumbleLevel * 0xFFFF / RUMBLE_PWM);
429}
430
431static void _updateLux(struct GBALuminanceSource* lux) {
432 UNUSED(lux);
433 struct retro_variable var = {
434 .key = SOLAR_SENSOR_LEVEL,
435 .value = 0
436 };
437
438 bool updated = false;
439 if (!environCallback(RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE, &updated) || !updated) {
440 return;
441 }
442 if (!environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || !var.value) {
443 return;
444 }
445
446 char* end;
447 int newLuxLevel = strtol(var.value, &end, 10);
448 if (!*end) {
449 if (newLuxLevel > 10) {
450 luxLevel = 10;
451 } else if (newLuxLevel < 0) {
452 luxLevel = 0;
453 } else {
454 luxLevel = newLuxLevel;
455 }
456 }
457}
458
459static uint8_t _readLux(struct GBALuminanceSource* lux) {
460 UNUSED(lux);
461 int value = 0x16;
462 if (luxLevel > 0) {
463 value += GBA_LUX_LEVELS[luxLevel - 1];
464 }
465 return 0xFF - value;
466}