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 <mgba-util/common.h>
9
10#include <mgba/core/blip_buf.h>
11#include <mgba/core/cheats.h>
12#include <mgba/core/core.h>
13#include <mgba/core/log.h>
14#include <mgba/core/serialize.h>
15#include <mgba/core/version.h>
16#ifdef M_CORE_GB
17#include <mgba/gb/core.h>
18#include <mgba/internal/gb/gb.h>
19#include <mgba/internal/gb/mbc.h>
20#endif
21#ifdef M_CORE_GBA
22#include <mgba/gba/core.h>
23#include <mgba/gba/interface.h>
24#include <mgba/internal/gba/gba.h>
25#endif
26#include <mgba-util/circle-buffer.h>
27#include <mgba-util/memory.h>
28#include <mgba-util/vfs.h>
29
30#define SAMPLES 1024
31#define RUMBLE_PWM 35
32
33static retro_environment_t environCallback;
34static retro_video_refresh_t videoCallback;
35static retro_audio_sample_batch_t audioCallback;
36static retro_input_poll_t inputPollCallback;
37static retro_input_state_t inputCallback;
38static retro_log_printf_t logCallback;
39static retro_set_rumble_state_t rumbleCallback;
40
41static void GBARetroLog(struct mLogger* logger, int category, enum mLogLevel level, const char* format, va_list args);
42
43static void _postAudioBuffer(struct mAVStream*, blip_t* left, blip_t* right);
44static void _setRumble(struct mRumble* rumble, int enable);
45static uint8_t _readLux(struct GBALuminanceSource* lux);
46static void _updateLux(struct GBALuminanceSource* lux);
47static void _updateCamera(const uint32_t* buffer, unsigned width, unsigned height, size_t pitch);
48static void _startImage(struct mImageSource*, unsigned w, unsigned h, int colorFormats);
49static void _stopImage(struct mImageSource*);
50static void _requestImage(struct mImageSource*, const void** buffer, size_t* stride, enum mColorFormat* colorFormat);
51
52static struct mCore* core;
53static void* outputBuffer;
54static void* data;
55static size_t dataSize;
56static void* savedata;
57static struct mAVStream stream;
58static int rumbleLevel;
59static struct CircleBuffer rumbleHistory;
60static struct mRumble rumble;
61static struct GBALuminanceSource lux;
62static int luxLevel;
63static struct mLogger logger;
64static struct retro_camera_callback cam;
65static struct mImageSource imageSource;
66static uint32_t* camData = NULL;
67static unsigned camWidth;
68static unsigned camHeight;
69static size_t camStride;
70
71static void _reloadSettings(void) {
72 struct mCoreOptions opts = {
73 .useBios = true,
74 .volume = 0x100,
75 };
76
77 struct retro_variable var;
78 enum GBModel model;
79 const char* modelName;
80
81 var.key = "mgba_gb_model";
82 var.value = 0;
83 if (environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
84 if (strcmp(var.value, "Game Boy") == 0) {
85 model = GB_MODEL_DMG;
86 } else if (strcmp(var.value, "Super Game Boy") == 0) {
87 model = GB_MODEL_SGB;
88 } else if (strcmp(var.value, "Game Boy Color") == 0) {
89 model = GB_MODEL_CGB;
90 } else if (strcmp(var.value, "Game Boy Advance") == 0) {
91 model = GB_MODEL_AGB;
92 } else {
93 model = GB_MODEL_AUTODETECT;
94 }
95
96 modelName = GBModelToName(model);
97 mCoreConfigSetDefaultValue(&core->config, "gb.model", modelName);
98 mCoreConfigSetDefaultValue(&core->config, "sgb.model", modelName);
99 mCoreConfigSetDefaultValue(&core->config, "cgb.model", modelName);
100 }
101
102 var.key = "mgba_use_bios";
103 var.value = 0;
104 if (environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
105 opts.useBios = strcmp(var.value, "ON") == 0;
106 }
107
108 var.key = "mgba_skip_bios";
109 var.value = 0;
110 if (environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
111 opts.skipBios = strcmp(var.value, "ON") == 0;
112 }
113
114 var.key = "mgba_sgb_borders";
115 var.value = 0;
116 if (environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
117 if (strcmp(var.value, "ON") == 0) {
118 mCoreConfigSetDefaultIntValue(&core->config, "sgb.borders", true);
119 } else {
120 mCoreConfigSetDefaultIntValue(&core->config, "sgb.borders", false);
121 }
122 }
123
124 var.key = "mgba_idle_optimization";
125 var.value = 0;
126 if (environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
127 if (strcmp(var.value, "Don't Remove") == 0) {
128 mCoreConfigSetDefaultValue(&core->config, "idleOptimization", "ignore");
129 } else if (strcmp(var.value, "Remove Known") == 0) {
130 mCoreConfigSetDefaultValue(&core->config, "idleOptimization", "remove");
131 } else if (strcmp(var.value, "Detect and Remove") == 0) {
132 mCoreConfigSetDefaultValue(&core->config, "idleOptimization", "detect");
133 }
134 }
135
136 var.key = "mgba_frameskip";
137 var.value = 0;
138 if (environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
139 opts.frameskip = strtol(var.value, NULL, 10);
140
141 }
142
143 mCoreConfigLoadDefaults(&core->config, &opts);
144 mCoreLoadConfig(core);
145}
146
147unsigned retro_api_version(void) {
148 return RETRO_API_VERSION;
149}
150
151void retro_set_environment(retro_environment_t env) {
152 environCallback = env;
153
154 struct retro_variable vars[] = {
155 { "mgba_solar_sensor_level", "Solar sensor level; 0|1|2|3|4|5|6|7|8|9|10" },
156 { "mgba_allow_opposing_directions", "Allow opposing directional input; OFF|ON" },
157 { "mgba_gb_model", "Game Boy model (requires restart); Autodetect|Game Boy|Super Game Boy|Game Boy Color|Game Boy Advance" },
158 { "mgba_use_bios", "Use BIOS file if found (requires restart); ON|OFF" },
159 { "mgba_skip_bios", "Skip BIOS intro (requires restart); OFF|ON" },
160 { "mgba_sgb_borders", "Use Super Game Boy borders (requires restart); ON|OFF" },
161 { "mgba_idle_optimization", "Idle loop removal; Remove Known|Detect and Remove|Don't Remove" },
162 { "mgba_frameskip", "Frameskip; 0|1|2|3|4|5|6|7|8|9|10" },
163 { 0, 0 }
164 };
165
166 environCallback(RETRO_ENVIRONMENT_SET_VARIABLES, vars);
167}
168
169void retro_set_video_refresh(retro_video_refresh_t video) {
170 videoCallback = video;
171}
172
173void retro_set_audio_sample(retro_audio_sample_t audio) {
174 UNUSED(audio);
175}
176
177void retro_set_audio_sample_batch(retro_audio_sample_batch_t audioBatch) {
178 audioCallback = audioBatch;
179}
180
181void retro_set_input_poll(retro_input_poll_t inputPoll) {
182 inputPollCallback = inputPoll;
183}
184
185void retro_set_input_state(retro_input_state_t input) {
186 inputCallback = input;
187}
188
189void retro_get_system_info(struct retro_system_info* info) {
190 info->need_fullpath = false;
191 info->valid_extensions = "gba|gb|gbc";
192 info->library_version = projectVersion;
193 info->library_name = projectName;
194 info->block_extract = false;
195}
196
197void retro_get_system_av_info(struct retro_system_av_info* info) {
198 unsigned width, height;
199 core->desiredVideoDimensions(core, &width, &height);
200 info->geometry.base_width = width;
201 info->geometry.base_height = height;
202#ifdef M_CORE_GB
203 if (core->platform(core) == PLATFORM_GB) {
204 info->geometry.max_width = 256;
205 info->geometry.max_height = 224;
206 } else
207#endif
208 {
209 info->geometry.max_width = width;
210 info->geometry.max_height = height;
211 }
212
213 info->geometry.aspect_ratio = width / (double) height;
214 info->timing.fps = core->frequency(core) / (float) core->frameCycles(core);
215 info->timing.sample_rate = 32768;
216}
217
218void retro_init(void) {
219 enum retro_pixel_format fmt;
220#ifdef COLOR_16_BIT
221#ifdef COLOR_5_6_5
222 fmt = RETRO_PIXEL_FORMAT_RGB565;
223#else
224#warning This pixel format is unsupported. Please use -DCOLOR_16-BIT -DCOLOR_5_6_5
225 fmt = RETRO_PIXEL_FORMAT_0RGB1555;
226#endif
227#else
228#warning This pixel format is unsupported. Please use -DCOLOR_16-BIT -DCOLOR_5_6_5
229 fmt = RETRO_PIXEL_FORMAT_XRGB8888;
230#endif
231 environCallback(RETRO_ENVIRONMENT_SET_PIXEL_FORMAT, &fmt);
232
233 struct retro_input_descriptor inputDescriptors[] = {
234 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A, "A" },
235 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B, "B" },
236 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_SELECT, "Select" },
237 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START, "Start" },
238 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT, "Right" },
239 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT, "Left" },
240 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP, "Up" },
241 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN, "Down" },
242 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R, "R" },
243 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L, "L" },
244 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R3, "Brighten Solar Sensor" },
245 { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L3, "Darken Solar Sensor" },
246 { 0 }
247 };
248 environCallback(RETRO_ENVIRONMENT_SET_INPUT_DESCRIPTORS, &inputDescriptors);
249
250 // TODO: RETRO_ENVIRONMENT_SET_SUPPORT_NO_GAME when BIOS booting is supported
251
252 struct retro_rumble_interface rumbleInterface;
253 if (environCallback(RETRO_ENVIRONMENT_GET_RUMBLE_INTERFACE, &rumbleInterface)) {
254 rumbleCallback = rumbleInterface.set_rumble_state;
255 CircleBufferInit(&rumbleHistory, RUMBLE_PWM);
256 rumble.setRumble = _setRumble;
257 } else {
258 rumbleCallback = 0;
259 }
260
261 luxLevel = 0;
262 lux.readLuminance = _readLux;
263 lux.sample = _updateLux;
264 _updateLux(&lux);
265
266 struct retro_log_callback log;
267 if (environCallback(RETRO_ENVIRONMENT_GET_LOG_INTERFACE, &log)) {
268 logCallback = log.log;
269 } else {
270 logCallback = 0;
271 }
272 logger.log = GBARetroLog;
273 mLogSetDefaultLogger(&logger);
274
275 stream.videoDimensionsChanged = 0;
276 stream.postAudioFrame = 0;
277 stream.postAudioBuffer = _postAudioBuffer;
278 stream.postVideoFrame = 0;
279
280 imageSource.startRequestImage = _startImage;
281 imageSource.stopRequestImage = _stopImage;
282 imageSource.requestImage = _requestImage;
283}
284
285void retro_deinit(void) {
286 free(outputBuffer);
287}
288
289void retro_run(void) {
290 uint16_t keys;
291 inputPollCallback();
292
293 bool updated = false;
294 if (environCallback(RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE, &updated) && updated) {
295 struct retro_variable var = {
296 .key = "mgba_allow_opposing_directions",
297 .value = 0
298 };
299 if (environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
300 ((struct GBA*) core->board)->allowOpposingDirections = strcmp(var.value, "yes") == 0;
301 }
302
303 var.key = "mgba_frameskip";
304 var.value = 0;
305 if (environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
306 mCoreConfigSetUIntValue(&core->config, "frameskip", strtol(var.value, NULL, 10));
307 mCoreLoadConfig(core);
308 }
309 }
310
311 keys = 0;
312 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A)) << 0;
313 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B)) << 1;
314 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_SELECT)) << 2;
315 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START)) << 3;
316 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT)) << 4;
317 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT)) << 5;
318 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP)) << 6;
319 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN)) << 7;
320 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R)) << 8;
321 keys |= (!!inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L)) << 9;
322 core->setKeys(core, keys);
323
324 static bool wasAdjustingLux = false;
325 if (wasAdjustingLux) {
326 wasAdjustingLux = inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R3) ||
327 inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L3);
328 } else {
329 if (inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R3)) {
330 ++luxLevel;
331 if (luxLevel > 10) {
332 luxLevel = 10;
333 }
334 wasAdjustingLux = true;
335 } else if (inputCallback(0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L3)) {
336 --luxLevel;
337 if (luxLevel < 0) {
338 luxLevel = 0;
339 }
340 wasAdjustingLux = true;
341 }
342 }
343
344 core->runFrame(core);
345 unsigned width, height;
346 core->desiredVideoDimensions(core, &width, &height);
347 videoCallback(outputBuffer, width, height, BYTES_PER_PIXEL * 256);
348}
349
350static void _setupMaps(struct mCore* core) {
351#ifdef M_CORE_GBA
352 if (core->platform(core) == PLATFORM_GBA) {
353 struct GBA* gba = core->board;
354 struct retro_memory_descriptor descs[11];
355 struct retro_memory_map mmaps;
356 size_t romSize = gba->memory.romSize + (gba->memory.romSize & 1);
357
358 memset(descs, 0, sizeof(descs));
359 size_t savedataSize = retro_get_memory_size(RETRO_MEMORY_SAVE_RAM);
360
361 /* Map internal working RAM */
362 descs[0].ptr = gba->memory.iwram;
363 descs[0].start = BASE_WORKING_IRAM;
364 descs[0].len = SIZE_WORKING_IRAM;
365 descs[0].select = 0xFF000000;
366
367 /* Map working RAM */
368 descs[1].ptr = gba->memory.wram;
369 descs[1].start = BASE_WORKING_RAM;
370 descs[1].len = SIZE_WORKING_RAM;
371 descs[1].select = 0xFF000000;
372
373 /* Map save RAM */
374 /* TODO: if SRAM is flash, use start=0 addrspace="S" instead */
375 descs[2].ptr = savedataSize ? savedata : NULL;
376 descs[2].start = BASE_CART_SRAM;
377 descs[2].len = savedataSize;
378
379 /* Map ROM */
380 descs[3].ptr = gba->memory.rom;
381 descs[3].start = BASE_CART0;
382 descs[3].len = romSize;
383 descs[3].flags = RETRO_MEMDESC_CONST;
384
385 descs[4].ptr = gba->memory.rom;
386 descs[4].start = BASE_CART1;
387 descs[4].len = romSize;
388 descs[4].flags = RETRO_MEMDESC_CONST;
389
390 descs[5].ptr = gba->memory.rom;
391 descs[5].start = BASE_CART2;
392 descs[5].len = romSize;
393 descs[5].flags = RETRO_MEMDESC_CONST;
394
395 /* Map BIOS */
396 descs[6].ptr = gba->memory.bios;
397 descs[6].start = BASE_BIOS;
398 descs[6].len = SIZE_BIOS;
399 descs[6].flags = RETRO_MEMDESC_CONST;
400
401 /* Map VRAM */
402 descs[7].ptr = gba->video.vram;
403 descs[7].start = BASE_VRAM;
404 descs[7].len = SIZE_VRAM;
405 descs[7].select = 0xFF000000;
406
407 /* Map palette RAM */
408 descs[8].ptr = gba->video.palette;
409 descs[8].start = BASE_PALETTE_RAM;
410 descs[8].len = SIZE_PALETTE_RAM;
411 descs[8].select = 0xFF000000;
412
413 /* Map OAM */
414 descs[9].ptr = &gba->video.oam; /* video.oam is a structure */
415 descs[9].start = BASE_OAM;
416 descs[9].len = SIZE_OAM;
417 descs[9].select = 0xFF000000;
418
419 /* Map mmapped I/O */
420 descs[10].ptr = gba->memory.io;
421 descs[10].start = BASE_IO;
422 descs[10].len = SIZE_IO;
423
424 mmaps.descriptors = descs;
425 mmaps.num_descriptors = sizeof(descs) / sizeof(descs[0]);
426
427 bool yes = true;
428 environCallback(RETRO_ENVIRONMENT_SET_MEMORY_MAPS, &mmaps);
429 environCallback(RETRO_ENVIRONMENT_SET_SUPPORT_ACHIEVEMENTS, &yes);
430 }
431#endif
432}
433
434void retro_reset(void) {
435 core->reset(core);
436 _setupMaps(core);
437
438 if (rumbleCallback) {
439 CircleBufferClear(&rumbleHistory);
440 }
441}
442
443bool retro_load_game(const struct retro_game_info* game) {
444 struct VFile* rom;
445 if (game->data) {
446 data = anonymousMemoryMap(game->size);
447 dataSize = game->size;
448 memcpy(data, game->data, game->size);
449 rom = VFileFromMemory(data, game->size);
450 } else {
451 data = 0;
452 rom = VFileOpen(game->path, O_RDONLY);
453 }
454 if (!rom) {
455 return false;
456 }
457
458 core = mCoreFindVF(rom);
459 if (!core) {
460 rom->close(rom);
461 mappedMemoryFree(data, game->size);
462 return false;
463 }
464 mCoreInitConfig(core, NULL);
465 core->init(core);
466 core->setAVStream(core, &stream);
467
468 size_t size = 256 * 224 * BYTES_PER_PIXEL;
469 outputBuffer = malloc(size);
470 memset(outputBuffer, 0xFF, size);
471 core->setVideoBuffer(core, outputBuffer, 256);
472
473 core->setAudioBufferSize(core, SAMPLES);
474
475 blip_set_rates(core->getAudioChannel(core, 0), core->frequency(core), 32768);
476 blip_set_rates(core->getAudioChannel(core, 1), core->frequency(core), 32768);
477
478 core->setPeripheral(core, mPERIPH_RUMBLE, &rumble);
479
480 savedata = anonymousMemoryMap(SIZE_CART_FLASH1M);
481 struct VFile* save = VFileFromMemory(savedata, SIZE_CART_FLASH1M);
482
483 _reloadSettings();
484 core->loadROM(core, rom);
485 core->loadSave(core, save);
486
487 const char* sysDir = 0;
488 const char* biosName = 0;
489 char biosPath[PATH_MAX];
490 environCallback(RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY, &sysDir);
491
492#ifdef M_CORE_GBA
493 if (core->platform(core) == PLATFORM_GBA) {
494 core->setPeripheral(core, mPERIPH_GBA_LUMINANCE, &lux);
495 biosName = "gba_bios.bin";
496
497 }
498#endif
499
500#ifdef M_CORE_GB
501 if (core->platform(core) == PLATFORM_GB) {
502 memset(&cam, 0, sizeof(cam));
503 cam.height = GBCAM_HEIGHT;
504 cam.width = GBCAM_WIDTH;
505 cam.caps = 1 << RETRO_CAMERA_BUFFER_RAW_FRAMEBUFFER;
506 cam.frame_raw_framebuffer = _updateCamera;
507 core->setPeripheral(core, mPERIPH_IMAGE_SOURCE, &imageSource);
508
509 environCallback(RETRO_ENVIRONMENT_GET_CAMERA_INTERFACE, &cam);
510 const char* modelName = mCoreConfigGetValue(&core->config, "gb.model");
511 struct GB* gb = core->board;
512
513 if (modelName) {
514 gb->model = GBNameToModel(modelName);
515 } else {
516 GBDetectModel(gb);
517 }
518
519 switch (gb->model) {
520 case GB_MODEL_AGB:
521 case GB_MODEL_CGB:
522 biosName = "gbc_bios.bin";
523 break;
524 case GB_MODEL_SGB:
525 biosName = "sgb_bios.bin";
526 break;
527 case GB_MODEL_DMG:
528 default:
529 biosName = "gb_bios.bin";
530 break;
531 }
532 }
533#endif
534
535 if (core->opts.useBios && sysDir && biosName) {
536 snprintf(biosPath, sizeof(biosPath), "%s%s%s", sysDir, PATH_SEP, biosName);
537 struct VFile* bios = VFileOpen(biosPath, O_RDONLY);
538 if (bios) {
539 core->loadBIOS(core, bios, 0);
540 }
541 }
542
543 core->reset(core);
544 _setupMaps(core);
545
546 return true;
547}
548
549void retro_unload_game(void) {
550 if (!core) {
551 return;
552 }
553 core->deinit(core);
554 mappedMemoryFree(data, dataSize);
555 data = 0;
556 mappedMemoryFree(savedata, SIZE_CART_FLASH1M);
557 savedata = 0;
558 CircleBufferDeinit(&rumbleHistory);
559}
560
561size_t retro_serialize_size(void) {
562 struct VFile* vfm = VFileMemChunk(NULL, 0);
563 mCoreSaveStateNamed(core, vfm, SAVESTATE_SAVEDATA | SAVESTATE_RTC);
564 size_t size = vfm->size(vfm);
565 vfm->close(vfm);
566 return size;
567}
568
569bool retro_serialize(void* data, size_t size) {
570 struct VFile* vfm = VFileMemChunk(NULL, 0);
571 mCoreSaveStateNamed(core, vfm, SAVESTATE_SAVEDATA | SAVESTATE_RTC);
572 if ((ssize_t) size > vfm->size(vfm)) {
573 size = vfm->size(vfm);
574 } else if ((ssize_t) size < vfm->size(vfm)) {
575 vfm->close(vfm);
576 return false;
577 }
578 vfm->seek(vfm, 0, SEEK_SET);
579 vfm->read(vfm, data, size);
580 vfm->close(vfm);
581 return true;
582}
583
584bool retro_unserialize(const void* data, size_t size) {
585 struct VFile* vfm = VFileFromConstMemory(data, size);
586 bool success = mCoreLoadStateNamed(core, vfm, SAVESTATE_RTC);
587 vfm->close(vfm);
588 return success;
589}
590
591void retro_cheat_reset(void) {
592 mCheatDeviceClear(core->cheatDevice(core));
593}
594
595void retro_cheat_set(unsigned index, bool enabled, const char* code) {
596 UNUSED(index);
597 UNUSED(enabled);
598 struct mCheatDevice* device = core->cheatDevice(core);
599 struct mCheatSet* cheatSet = NULL;
600 if (mCheatSetsSize(&device->cheats)) {
601 cheatSet = *mCheatSetsGetPointer(&device->cheats, 0);
602 } else {
603 cheatSet = device->createSet(device, NULL);
604 mCheatAddSet(device, cheatSet);
605 }
606 // Convert the super wonky unportable libretro format to something normal
607 char realCode[] = "XXXXXXXX XXXXXXXX";
608 size_t len = strlen(code) + 1; // Include null terminator
609 size_t i, pos;
610 for (i = 0, pos = 0; i < len; ++i) {
611 if (isspace((int) code[i]) || code[i] == '+') {
612 realCode[pos] = ' ';
613 } else {
614 realCode[pos] = code[i];
615 }
616 if ((pos == 13 && (realCode[pos] == ' ' || !realCode[pos])) || pos == 17) {
617 realCode[pos] = '\0';
618 mCheatAddLine(cheatSet, realCode, 0);
619 pos = 0;
620 continue;
621 }
622 ++pos;
623 }
624}
625
626unsigned retro_get_region(void) {
627 return RETRO_REGION_NTSC; // TODO: This isn't strictly true
628}
629
630void retro_set_controller_port_device(unsigned port, unsigned device) {
631 UNUSED(port);
632 UNUSED(device);
633}
634
635bool retro_load_game_special(unsigned game_type, const struct retro_game_info* info, size_t num_info) {
636 UNUSED(game_type);
637 UNUSED(info);
638 UNUSED(num_info);
639 return false;
640}
641
642void* retro_get_memory_data(unsigned id) {
643 if (id != RETRO_MEMORY_SAVE_RAM) {
644 return 0;
645 }
646 return savedata;
647}
648
649size_t retro_get_memory_size(unsigned id) {
650 if (id != RETRO_MEMORY_SAVE_RAM) {
651 return 0;
652 }
653#ifdef M_CORE_GBA
654 if (core->platform(core) == PLATFORM_GBA) {
655 switch (((struct GBA*) core->board)->memory.savedata.type) {
656 case SAVEDATA_AUTODETECT:
657 return SIZE_CART_FLASH1M;
658 default:
659 return GBASavedataSize(&((struct GBA*) core->board)->memory.savedata);
660 }
661 }
662#endif
663#ifdef M_CORE_GB
664 if (core->platform(core) == PLATFORM_GB) {
665 return ((struct GB*) core->board)->sramSize;
666 }
667#endif
668 return 0;
669}
670
671void GBARetroLog(struct mLogger* logger, int category, enum mLogLevel level, const char* format, va_list args) {
672 UNUSED(logger);
673 if (!logCallback) {
674 return;
675 }
676
677 char message[128];
678 vsnprintf(message, sizeof(message), format, args);
679
680 enum retro_log_level retroLevel = RETRO_LOG_INFO;
681 switch (level) {
682 case mLOG_ERROR:
683 case mLOG_FATAL:
684 retroLevel = RETRO_LOG_ERROR;
685 break;
686 case mLOG_WARN:
687 retroLevel = RETRO_LOG_WARN;
688 break;
689 case mLOG_INFO:
690 retroLevel = RETRO_LOG_INFO;
691 break;
692 case mLOG_GAME_ERROR:
693 case mLOG_STUB:
694#ifdef NDEBUG
695 return;
696#else
697 retroLevel = RETRO_LOG_DEBUG;
698 break;
699#endif
700 case mLOG_DEBUG:
701 retroLevel = RETRO_LOG_DEBUG;
702 break;
703 }
704#ifdef NDEBUG
705 static int biosCat = -1;
706 if (biosCat < 0) {
707 biosCat = mLogCategoryById("gba.bios");
708 }
709
710 if (category == biosCat) {
711 return;
712 }
713#endif
714 logCallback(retroLevel, "%s: %s\n", mLogCategoryName(category), message);
715}
716
717static void _postAudioBuffer(struct mAVStream* stream, blip_t* left, blip_t* right) {
718 UNUSED(stream);
719 int16_t samples[SAMPLES * 2];
720 blip_read_samples(left, samples, SAMPLES, true);
721 blip_read_samples(right, samples + 1, SAMPLES, true);
722 audioCallback(samples, SAMPLES);
723}
724
725static void _setRumble(struct mRumble* rumble, int enable) {
726 UNUSED(rumble);
727 if (!rumbleCallback) {
728 return;
729 }
730 rumbleLevel += enable;
731 if (CircleBufferSize(&rumbleHistory) == RUMBLE_PWM) {
732 int8_t oldLevel;
733 CircleBufferRead8(&rumbleHistory, &oldLevel);
734 rumbleLevel -= oldLevel;
735 }
736 CircleBufferWrite8(&rumbleHistory, enable);
737 rumbleCallback(0, RETRO_RUMBLE_STRONG, rumbleLevel * 0xFFFF / RUMBLE_PWM);
738 rumbleCallback(0, RETRO_RUMBLE_WEAK, rumbleLevel * 0xFFFF / RUMBLE_PWM);
739}
740
741static void _updateLux(struct GBALuminanceSource* lux) {
742 UNUSED(lux);
743 struct retro_variable var = {
744 .key = "mgba_solar_sensor_level",
745 .value = 0
746 };
747
748 bool updated = false;
749 if (!environCallback(RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE, &updated) || !updated) {
750 return;
751 }
752 if (!environCallback(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || !var.value) {
753 return;
754 }
755
756 char* end;
757 int newLuxLevel = strtol(var.value, &end, 10);
758 if (!*end) {
759 if (newLuxLevel > 10) {
760 luxLevel = 10;
761 } else if (newLuxLevel < 0) {
762 luxLevel = 0;
763 } else {
764 luxLevel = newLuxLevel;
765 }
766 }
767}
768
769static uint8_t _readLux(struct GBALuminanceSource* lux) {
770 UNUSED(lux);
771 int value = 0x16;
772 if (luxLevel > 0) {
773 value += GBA_LUX_LEVELS[luxLevel - 1];
774 }
775 return 0xFF - value;
776}
777
778static void _updateCamera(const uint32_t* buffer, unsigned width, unsigned height, size_t pitch) {
779 if (!camData || width != camWidth || height != camHeight) {
780 camData = malloc(sizeof(*buffer) * height * pitch);
781 camWidth = width;
782 camHeight = height;
783 camStride = pitch / sizeof(*buffer);
784 }
785 memcpy(camData, buffer, sizeof(*buffer) * height * pitch);
786}
787
788static void _startImage(struct mImageSource* image, unsigned w, unsigned h, int colorFormats) {
789 UNUSED(image);
790 UNUSED(colorFormats);
791
792 camData = NULL;
793 cam.start();
794}
795
796static void _stopImage(struct mImageSource* image) {
797 UNUSED(image);
798 cam.stop();
799}
800
801static void _requestImage(struct mImageSource* image, const void** buffer, size_t* stride, enum mColorFormat* colorFormat) {
802 UNUSED(image);
803 if (!camData) {
804 cam.start();
805 }
806 *buffer = camData;
807 *stride = camStride;
808 *colorFormat = mCOLOR_XRGB8;
809}