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