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