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/gba.h"
11#include "gba/interface.h"
12#include "gba/renderers/video-software.h"
13#include "gba/serialize.h"
14#include "gba/supervisor/overrides.h"
15#include "gba/video.h"
16#include "util/circle-buffer.h"
17#include "util/vfs.h"
18
19#define SAMPLES 1024
20#define RUMBLE_PWM 35
21
22#define SOLAR_SENSOR_LEVEL "mgba_solar_sensor_level"
23
24static retro_environment_t environCallback;
25static retro_video_refresh_t videoCallback;
26static retro_audio_sample_batch_t audioCallback;
27static retro_input_poll_t inputPollCallback;
28static retro_input_state_t inputCallback;
29static retro_log_printf_t logCallback;
30static retro_set_rumble_state_t rumbleCallback;
31
32static void GBARetroLog(struct GBAThread* thread, enum GBALogLevel level, const char* format, va_list args);
33
34static void _postAudioBuffer(struct GBAAVStream*, struct GBAAudio* audio);
35static void _postVideoFrame(struct GBAAVStream*, struct GBAVideoRenderer* renderer);
36static void _setRumble(struct GBARumble* rumble, int enable);
37static uint8_t _readLux(struct GBALuminanceSource* lux);
38static void _updateLux(struct GBALuminanceSource* lux);
39
40static struct GBA gba;
41static struct ARMCore cpu;
42static struct GBAVideoSoftwareRenderer renderer;
43static struct VFile* rom;
44static void* data;
45static struct VFile* save;
46static void* savedata;
47static struct VFile* bios;
48static struct GBAAVStream stream;
49static int rumbleLevel;
50static struct CircleBuffer rumbleHistory;
51static struct GBARumble rumble;
52static struct GBALuminanceSource lux;
53static int luxLevel;
54
55unsigned retro_api_version(void) {
56 return RETRO_API_VERSION;
57}
58
59void retro_set_environment(retro_environment_t env) {
60 environCallback = env;
61
62 struct retro_variable vars[] = {
63 { SOLAR_SENSOR_LEVEL, "Solar sensor level; 0|1|2|3|4|5|6|7|8|9|10" },
64 { 0, 0 }
65 };
66
67 environCallback(RETRO_ENVIRONMENT_SET_VARIABLES, vars);
68}
69
70void retro_set_video_refresh(retro_video_refresh_t video) {
71 videoCallback = video;
72}
73
74void retro_set_audio_sample(retro_audio_sample_t audio) {
75 UNUSED(audio);
76}
77
78void retro_set_audio_sample_batch(retro_audio_sample_batch_t audioBatch) {
79 audioCallback = audioBatch;
80}
81
82void retro_set_input_poll(retro_input_poll_t inputPoll) {
83 inputPollCallback = inputPoll;
84}
85
86void retro_set_input_state(retro_input_state_t input) {
87 inputCallback = input;
88}
89
90void retro_get_system_info(struct retro_system_info* info) {
91 info->need_fullpath = false;
92 info->valid_extensions = "gba";
93 info->library_version = projectVersion;
94 info->library_name = projectName;
95 info->block_extract = false;
96}
97
98void retro_get_system_av_info(struct retro_system_av_info* info) {
99 info->geometry.base_width = VIDEO_HORIZONTAL_PIXELS;
100 info->geometry.base_height = VIDEO_VERTICAL_PIXELS;
101 info->geometry.max_width = VIDEO_HORIZONTAL_PIXELS;
102 info->geometry.max_height = VIDEO_VERTICAL_PIXELS;
103 info->timing.fps = GBA_ARM7TDMI_FREQUENCY / (float) VIDEO_TOTAL_LENGTH;
104 info->timing.sample_rate = 32768;
105}
106
107void retro_init(void) {
108 enum retro_pixel_format fmt;
109#ifdef COLOR_16_BIT
110#ifdef COLOR_5_6_5
111 fmt = RETRO_PIXEL_FORMAT_RGB565;
112#else
113#warning This pixel format is unsupported. Please use -DCOLOR_16-BIT -DCOLOR_5_6_5
114 fmt = RETRO_PIXEL_FORMAT_0RGB1555;
115#endif
116#else
117#warning This pixel format is unsupported. Please use -DCOLOR_16-BIT -DCOLOR_5_6_5
118 fmt = RETRO_PIXEL_FORMAT_XRGB8888;
119#endif
120 environCallback(RETRO_ENVIRONMENT_SET_PIXEL_FORMAT, &fmt);
121
122 struct retro_input_descriptor inputDescriptors[] = {
123 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A, "A" },
124 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B, "B" },
125 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_SELECT, "Select" },
126 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START, "Start" },
127 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT, "Right" },
128 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT, "Left" },
129 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP, "Up" },
130 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN, "Down" },
131 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R, "R" },
132 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L, "L" }
133 };
134 environCallback(RETRO_ENVIRONMENT_SET_INPUT_DESCRIPTORS, &inputDescriptors);
135
136 // TODO: RETRO_ENVIRONMENT_SET_SUPPORT_NO_GAME when BIOS booting is supported
137
138 struct retro_rumble_interface rumbleInterface;
139 if (environCallback(RETRO_ENVIRONMENT_GET_RUMBLE_INTERFACE, &rumbleInterface)) {
140 rumbleCallback = rumbleInterface.set_rumble_state;
141 CircleBufferInit(&rumbleHistory, RUMBLE_PWM);
142 rumble.setRumble = _setRumble;
143 } else {
144 rumbleCallback = 0;
145 }
146
147 luxLevel = 0;
148 lux.readLuminance = _readLux;
149 lux.sample = _updateLux;
150 _updateLux(&lux);
151
152 struct retro_log_callback log;
153 if (environCallback(RETRO_ENVIRONMENT_GET_LOG_INTERFACE, &log)) {
154 logCallback = log.log;
155 } else {
156 logCallback = 0;
157 }
158
159 stream.postAudioFrame = 0;
160 stream.postAudioBuffer = _postAudioBuffer;
161 stream.postVideoFrame = _postVideoFrame;
162
163 GBACreate(&gba);
164 ARMSetComponents(&cpu, &gba.d, 0, 0);
165 ARMInit(&cpu);
166 gba.logLevel = 0; // TODO: Settings
167 gba.logHandler = GBARetroLog;
168 gba.stream = &stream;
169 gba.idleOptimization = IDLE_LOOP_REMOVE; // TODO: Settings
170 if (rumbleCallback) {
171 gba.rumble = &rumble;
172 }
173 gba.luminanceSource = &lux;
174 rom = 0;
175
176 const char* sysDir = 0;
177 if (environCallback(RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY, &sysDir)) {
178 char biosPath[PATH_MAX];
179 snprintf(biosPath, sizeof(biosPath), "%s%s%s", sysDir, PATH_SEP, "gba_bios.bin");
180 bios = VFileOpen(biosPath, O_RDONLY);
181 if (bios) {
182 GBALoadBIOS(&gba, bios);
183 }
184 }
185
186 GBAVideoSoftwareRendererCreate(&renderer);
187 renderer.outputBuffer = malloc(256 * VIDEO_VERTICAL_PIXELS * BYTES_PER_PIXEL);
188 renderer.outputBufferStride = 256;
189 GBAVideoAssociateRenderer(&gba.video, &renderer.d);
190
191 GBAAudioResizeBuffer(&gba.audio, SAMPLES);
192
193#if RESAMPLE_LIBRARY == RESAMPLE_BLIP_BUF
194 blip_set_rates(gba.audio.left, GBA_ARM7TDMI_FREQUENCY, 32768);
195 blip_set_rates(gba.audio.right, GBA_ARM7TDMI_FREQUENCY, 32768);
196#endif
197}
198
199void retro_deinit(void) {
200 if (bios) {
201 bios->close(bios);
202 bios = 0;
203 }
204 GBADestroy(&gba);
205}
206
207void retro_run(void) {
208 int keys;
209 gba.keySource = &keys;
210 inputPollCallback();
211
212 keys = 0;
213 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A)) << 0;
214 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B)) << 1;
215 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_SELECT)) << 2;
216 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START)) << 3;
217 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT)) << 4;
218 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT)) << 5;
219 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP)) << 6;
220 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN)) << 7;
221 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R)) << 8;
222 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L)) << 9;
223
224 int frameCount = gba.video.frameCounter;
225 while (gba.video.frameCounter == frameCount) {
226 ARMRunLoop(&cpu);
227 }
228}
229
230void retro_reset(void) {
231 ARMReset(&cpu);
232
233 if (rumbleCallback) {
234 CircleBufferClear(&rumbleHistory);
235 }
236}
237
238bool retro_load_game(const struct retro_game_info* game) {
239 if (game->data) {
240 data = malloc(game->size);
241 memcpy(data, game->data, game->size);
242 rom = VFileFromMemory(data, game->size);
243 } else {
244 data = 0;
245 rom = VFileOpen(game->path, O_RDONLY);
246 }
247 if (!rom) {
248 return false;
249 }
250 if (!GBAIsROM(rom)) {
251 return false;
252 }
253
254 savedata = malloc(SIZE_CART_FLASH1M);
255 save = VFileFromMemory(savedata, SIZE_CART_FLASH1M);
256
257 GBALoadROM(&gba, rom, save, game->path);
258 GBAOverrideApplyDefaults(&gba);
259
260 ARMReset(&cpu);
261 return true;
262}
263
264void retro_unload_game(void) {
265 rom->close(rom);
266 rom = 0;
267 free(data);
268 data = 0;
269 save->close(save);
270 save = 0;
271 free(savedata);
272 savedata = 0;
273 CircleBufferDeinit(&rumbleHistory);
274}
275
276size_t retro_serialize_size(void) {
277 return sizeof(struct GBASerializedState);
278}
279
280bool retro_serialize(void* data, size_t size) {
281 if (size != retro_serialize_size()) {
282 return false;
283 }
284 GBASerialize(&gba, data);
285 return true;
286}
287
288bool retro_unserialize(const void* data, size_t size) {
289 if (size != retro_serialize_size()) {
290 return false;
291 }
292 GBADeserialize(&gba, data);
293 return true;
294}
295
296void retro_cheat_reset(void) {
297 // TODO: Cheats
298}
299
300void retro_cheat_set(unsigned index, bool enabled, const char* code) {
301 // TODO: Cheats
302 UNUSED(index);
303 UNUSED(enabled);
304 UNUSED(code);
305}
306
307unsigned retro_get_region(void) {
308 return RETRO_REGION_NTSC; // TODO: This isn't strictly true
309}
310
311void retro_set_controller_port_device(unsigned port, unsigned device) {
312 UNUSED(port);
313 UNUSED(device);
314}
315
316bool retro_load_game_special(unsigned game_type, const struct retro_game_info* info, size_t num_info) {
317 UNUSED(game_type);
318 UNUSED(info);
319 UNUSED(num_info);
320 return false;
321}
322
323void* retro_get_memory_data(unsigned id) {
324 if (id != RETRO_MEMORY_SAVE_RAM) {
325 return 0;
326 }
327 return savedata;
328}
329
330size_t retro_get_memory_size(unsigned id) {
331 if (id != RETRO_MEMORY_SAVE_RAM) {
332 return 0;
333 }
334 switch (gba.memory.savedata.type) {
335 case SAVEDATA_AUTODETECT:
336 case SAVEDATA_FLASH1M:
337 return SIZE_CART_FLASH1M;
338 case SAVEDATA_FLASH512:
339 return SIZE_CART_FLASH512;
340 case SAVEDATA_EEPROM:
341 return SIZE_CART_EEPROM;
342 case SAVEDATA_SRAM:
343 return SIZE_CART_SRAM;
344 case SAVEDATA_FORCE_NONE:
345 return 0;
346 }
347 return 0;
348}
349
350void GBARetroLog(struct GBAThread* thread, enum GBALogLevel level, const char* format, va_list args) {
351 UNUSED(thread);
352 if (!logCallback) {
353 return;
354 }
355
356 char message[128];
357 vsnprintf(message, sizeof(message), format, args);
358
359 enum retro_log_level retroLevel = RETRO_LOG_INFO;
360 switch (level) {
361 case GBA_LOG_ALL:
362 case GBA_LOG_ERROR:
363 case GBA_LOG_FATAL:
364 retroLevel = RETRO_LOG_ERROR;
365 break;
366 case GBA_LOG_WARN:
367 retroLevel = RETRO_LOG_WARN;
368 break;
369 case GBA_LOG_INFO:
370 case GBA_LOG_GAME_ERROR:
371 case GBA_LOG_SWI:
372 case GBA_LOG_STATUS:
373 retroLevel = RETRO_LOG_INFO;
374 break;
375 case GBA_LOG_DEBUG:
376 case GBA_LOG_STUB:
377 case GBA_LOG_SIO:
378 retroLevel = RETRO_LOG_DEBUG;
379 break;
380 }
381 logCallback(retroLevel, "%s\n", message);
382}
383
384static void _postAudioBuffer(struct GBAAVStream* stream, struct GBAAudio* audio) {
385 UNUSED(stream);
386 int16_t samples[SAMPLES * 2];
387#if RESAMPLE_LIBRARY == RESAMPLE_BLIP_BUF
388 blip_read_samples(audio->left, samples, SAMPLES, true);
389 blip_read_samples(audio->right, samples + 1, SAMPLES, true);
390#else
391 int16_t samplesR[SAMPLES];
392 GBAAudioCopy(audio, &samples[SAMPLES], samplesR, SAMPLES);
393 size_t i;
394 for (i = 0; i < SAMPLES; ++i) {
395 samples[i * 2] = samples[SAMPLES + i];
396 samples[i * 2 + 1] = samplesR[i];
397 }
398#endif
399 audioCallback(samples, SAMPLES);
400}
401
402static void _postVideoFrame(struct GBAAVStream* stream, struct GBAVideoRenderer* renderer) {
403 UNUSED(stream);
404 void* pixels;
405 unsigned stride;
406 renderer->getPixels(renderer, &stride, &pixels);
407 videoCallback(pixels, VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, BYTES_PER_PIXEL * stride);
408}
409
410static void _setRumble(struct GBARumble* rumble, int enable) {
411 UNUSED(rumble);
412 if (!rumbleCallback) {
413 return;
414 }
415 rumbleLevel += enable;
416 if (CircleBufferSize(&rumbleHistory) == RUMBLE_PWM) {
417 int8_t oldLevel;
418 CircleBufferRead8(&rumbleHistory, &oldLevel);
419 rumbleLevel -= oldLevel;
420 }
421 CircleBufferWrite8(&rumbleHistory, enable);
422 rumbleCallback(0, RETRO_RUMBLE_STRONG, rumbleLevel * 0xFFFF / RUMBLE_PWM);
423}
424
425static void _updateLux(struct GBALuminanceSource* lux) {
426 UNUSED(lux);
427 struct retro_variable var = {
428 .key = SOLAR_SENSOR_LEVEL,
429 .value = 0
430 };
431
432 bool updated = false;
433 if (!environCallback(RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE, &updated) || !updated) {
434 return;
435 }
436 if (!environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || !var.value) {
437 return;
438 }
439
440 char* end;
441 int newLuxLevel = strtol(var.value, &end, 10);
442 if (!*end) {
443 if (newLuxLevel > 10) {
444 luxLevel = 10;
445 } else if (newLuxLevel < 0) {
446 luxLevel = 0;
447 } else {
448 luxLevel = newLuxLevel;
449 }
450 }
451}
452
453static uint8_t _readLux(struct GBALuminanceSource* lux) {
454 UNUSED(lux);
455 int value = 0x16;
456 if (luxLevel > 0) {
457 value += GBA_LUX_LEVELS[luxLevel - 1];
458 }
459 return 0xFF - value;
460}