d46cc4a2c180320ae324c128eb11728902d8e683
[picodrive.git] / platform / libretro.c
1 /*
2  * libretro core glue for PicoDrive
3  * (C) notaz, 2013
4  *
5  * This work is licensed under the terms of MAME license.
6  * See COPYING file in the top-level directory.
7  */
8
9 #define _GNU_SOURCE 1 // mremap
10 #include <stdio.h>
11 #include <stdarg.h>
12 #include <string.h>
13 #include <sys/mman.h>
14 #include <errno.h>
15 #ifdef __MACH__
16 #include <libkern/OSCacheControl.h>
17 #endif
18
19 #include <pico/pico_int.h>
20 #include <pico/state.h>
21 #include "common/input_pico.h"
22 #include "common/version.h"
23 #include "libretro.h"
24
25 #ifndef MAP_ANONYMOUS
26 #define MAP_ANONYMOUS MAP_ANON
27 #endif
28
29 static retro_video_refresh_t video_cb;
30 static retro_input_poll_t input_poll_cb;
31 static retro_input_state_t input_state_cb;
32 static retro_environment_t environ_cb;
33 static retro_audio_sample_batch_t audio_batch_cb;
34
35 static FILE *emu_log;
36
37 #define VOUT_MAX_WIDTH 320
38 #define VOUT_MAX_HEIGHT 240
39 static void *vout_buf;
40 static int vout_width, vout_height;
41
42 static short __attribute__((aligned(4))) sndBuffer[2*44100/50];
43
44 static void snd_write(int len);
45
46 #ifdef _WIN32
47 #define SLASH '\\'
48 #else
49 #define SLASH '/'
50 #endif
51
52 /* functions called by the core */
53
54 void cache_flush_d_inval_i(void *start, void *end)
55 {
56 #ifdef __arm__
57 #if defined(__BLACKBERRY_QNX__)
58         msync(start, end - start, MS_SYNC | MS_CACHE_ONLY | MS_INVALIDATE_ICACHE);
59 #elif defined(__MACH__)
60         size_t len = (char *)end - (char *)start;
61         sys_dcache_flush(start, len);
62         sys_icache_invalidate(start, len);
63 #else
64         __clear_cache(start, end);
65 #endif
66 #endif
67 }
68
69 void *plat_mmap(unsigned long addr, size_t size, int need_exec, int is_fixed)
70 {
71         int flags = MAP_PRIVATE | MAP_ANONYMOUS;
72         void *req, *ret;
73
74         req = (void *)addr;
75         ret = mmap(req, size, PROT_READ | PROT_WRITE, flags, -1, 0);
76         if (ret == MAP_FAILED) {
77                 lprintf("mmap(%08lx, %zd) failed: %d\n", addr, size, errno);
78                 return NULL;
79         }
80
81         if (addr != 0 && ret != (void *)addr) {
82                 lprintf("warning: wanted to map @%08lx, got %p\n",
83                         addr, ret);
84
85                 if (is_fixed) {
86                         munmap(ret, size);
87                         return NULL;
88                 }
89         }
90
91         return ret;
92 }
93
94 void *plat_mremap(void *ptr, size_t oldsize, size_t newsize)
95 {
96 #ifdef __linux__
97         void *ret = mremap(ptr, oldsize, newsize, 0);
98         if (ret == MAP_FAILED)
99                 return NULL;
100
101         return ret;
102 #else
103         void *tmp, *ret;
104         size_t preserve_size;
105         
106         preserve_size = oldsize;
107         if (preserve_size > newsize)
108                 preserve_size = newsize;
109         tmp = malloc(preserve_size);
110         if (tmp == NULL)
111                 return NULL;
112         memcpy(tmp, ptr, preserve_size);
113
114         munmap(ptr, oldsize);
115         ret = mmap(ptr, newsize, PROT_READ | PROT_WRITE,
116                    MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
117         if (ret == MAP_FAILED) {
118                 free(tmp);
119                 return NULL;
120         }
121         memcpy(ret, tmp, preserve_size);
122         free(tmp);
123         return ret;
124 #endif
125 }
126
127 void plat_munmap(void *ptr, size_t size)
128 {
129         if (ptr != NULL)
130                 munmap(ptr, size);
131 }
132
133 int plat_mem_set_exec(void *ptr, size_t size)
134 {
135         int ret = mprotect(ptr, size, PROT_READ | PROT_WRITE | PROT_EXEC);
136         if (ret != 0)
137                 lprintf("mprotect(%p, %zd) failed: %d\n", ptr, size, errno);
138
139         return ret;
140 }
141
142 void emu_video_mode_change(int start_line, int line_count, int is_32cols)
143 {
144         memset(vout_buf, 0, 320 * 240 * 2);
145         vout_width = is_32cols ? 256 : 320;
146         PicoDrawSetOutBuf(vout_buf, vout_width * 2);
147 }
148
149 void emu_32x_startup(void)
150 {
151 }
152
153 #ifndef ANDROID
154
155 void lprintf(const char *fmt, ...)
156 {
157         va_list list;
158
159         va_start(list, fmt);
160         fprintf(emu_log, "PicoDrive: ");
161         vfprintf(emu_log, fmt, list);
162         va_end(list);
163         fflush(emu_log);
164 }
165
166 #else
167
168 #include <android/log.h>
169
170 void lprintf(const char *fmt, ...)
171 {
172         va_list list;
173
174         va_start(list, fmt);
175         __android_log_vprint(ANDROID_LOG_INFO, "PicoDrive", fmt, list);
176         va_end(list);
177 }
178
179 #endif
180
181 /* libretro */
182 void retro_set_environment(retro_environment_t cb)
183 {
184         static const struct retro_variable vars[] = {
185                 //{ "region", "Region; Auto|NTSC|PAL" },
186                 { NULL, NULL },
187         };
188
189         environ_cb = cb;
190
191         cb(RETRO_ENVIRONMENT_SET_VARIABLES, (void *)vars);
192 }
193
194 void retro_set_video_refresh(retro_video_refresh_t cb) { video_cb = cb; }
195 void retro_set_audio_sample(retro_audio_sample_t cb) { (void)cb; }
196 void retro_set_audio_sample_batch(retro_audio_sample_batch_t cb) { audio_batch_cb = cb; }
197 void retro_set_input_poll(retro_input_poll_t cb) { input_poll_cb = cb; }
198 void retro_set_input_state(retro_input_state_t cb) { input_state_cb = cb; }
199
200 unsigned retro_api_version(void)
201 {
202         return RETRO_API_VERSION;
203 }
204
205 void retro_set_controller_port_device(unsigned port, unsigned device)
206 {
207 }
208
209 void retro_get_system_info(struct retro_system_info *info)
210 {
211         memset(info, 0, sizeof(*info));
212         info->library_name = "PicoDrive";
213         info->library_version = VERSION;
214         info->valid_extensions = "bin|gen|smd|md|32x|cue|iso|sms";
215         info->need_fullpath = true;
216 }
217
218 void retro_get_system_av_info(struct retro_system_av_info *info)
219 {
220         memset(info, 0, sizeof(*info));
221         info->timing.fps            = Pico.m.pal ? 50 : 60;
222         info->timing.sample_rate    = 44100;
223         info->geometry.base_width   = 320;
224         info->geometry.base_height  = 240;
225         info->geometry.max_width    = VOUT_MAX_WIDTH;
226         info->geometry.max_height   = VOUT_MAX_HEIGHT;
227         info->geometry.aspect_ratio = 4.0 / 3.0;
228 }
229
230 /* savestates */
231 struct savestate_state {
232         const char *load_buf;
233         char *save_buf;
234         size_t size;
235         size_t pos;
236 };
237
238 size_t state_read(void *p, size_t size, size_t nmemb, void *file)
239 {
240         struct savestate_state *state = file;
241         size_t bsize = size * nmemb;
242
243         if (state->pos + bsize > state->size) {
244                 lprintf("savestate error: %u/%u\n",
245                         state->pos + bsize, state->size);
246                 bsize = state->size - state->pos;
247                 if ((int)bsize <= 0)
248                         return 0;
249         }
250
251         memcpy(p, state->load_buf + state->pos, bsize);
252         state->pos += bsize;
253         return bsize;
254 }
255
256 size_t state_write(void *p, size_t size, size_t nmemb, void *file)
257 {
258         struct savestate_state *state = file;
259         size_t bsize = size * nmemb;
260
261         if (state->pos + bsize > state->size) {
262                 lprintf("savestate error: %u/%u\n",
263                         state->pos + bsize, state->size);
264                 bsize = state->size - state->pos;
265                 if ((int)bsize <= 0)
266                         return 0;
267         }
268
269         memcpy(state->save_buf + state->pos, p, bsize);
270         state->pos += bsize;
271         return bsize;
272 }
273
274 size_t state_skip(void *p, size_t size, size_t nmemb, void *file)
275 {
276         struct savestate_state *state = file;
277         size_t bsize = size * nmemb;
278
279         state->pos += bsize;
280         return bsize;
281 }
282
283 size_t state_eof(void *file)
284 {
285         struct savestate_state *state = file;
286
287         return state->pos >= state->size;
288 }
289
290 int state_fseek(void *file, long offset, int whence)
291 {
292         struct savestate_state *state = file;
293
294         switch (whence) {
295         case SEEK_SET:
296                 state->pos = offset;
297                 break;
298         case SEEK_CUR:
299                 state->pos += offset;
300                 break;
301         case SEEK_END:
302                 state->pos = state->size + offset;
303                 break;
304         }
305         return (int)state->pos;
306 }
307
308 /* savestate sizes vary wildly depending if cd/32x or
309  * carthw is active, so run the whole thing to get size */
310 size_t retro_serialize_size(void) 
311
312         struct savestate_state state = { 0, };
313         int ret;
314
315         ret = PicoStateFP(&state, 1, NULL, state_skip, NULL, state_fseek);
316         if (ret != 0)
317                 return 0;
318
319         return state.pos;
320 }
321
322 bool retro_serialize(void *data, size_t size)
323
324         struct savestate_state state = { 0, };
325         int ret;
326
327         state.save_buf = data;
328         state.size = size;
329         state.pos = 0;
330
331         ret = PicoStateFP(&state, 1, NULL, state_write,
332                 NULL, state_fseek);
333         return ret == 0;
334 }
335
336 bool retro_unserialize(const void *data, size_t size)
337 {
338         struct savestate_state state = { 0, };
339         int ret;
340
341         state.load_buf = data;
342         state.size = size;
343         state.pos = 0;
344
345         ret = PicoStateFP(&state, 0, state_read, NULL,
346                 state_eof, state_fseek);
347         return ret == 0;
348 }
349
350 /* cheats - TODO */
351 void retro_cheat_reset(void)
352 {
353 }
354
355 void retro_cheat_set(unsigned index, bool enabled, const char *code)
356 {
357 }
358
359 /* multidisk support */
360 static bool disk_ejected;
361 static unsigned int disk_current_index;
362 static unsigned int disk_count;
363 static struct disks_state {
364         char *fname;
365 } disks[8];
366
367 static bool disk_set_eject_state(bool ejected)
368 {
369         // TODO?
370         disk_ejected = ejected;
371         return true;
372 }
373
374 static bool disk_get_eject_state(void)
375 {
376         return disk_ejected;
377 }
378
379 static unsigned int disk_get_image_index(void)
380 {
381         return disk_current_index;
382 }
383
384 static bool disk_set_image_index(unsigned int index)
385 {
386         cd_img_type cd_type;
387         int ret;
388
389         if (index >= sizeof(disks) / sizeof(disks[0]))
390                 return false;
391
392         if (disks[index].fname == NULL) {
393                 lprintf("missing disk #%u\n", index);
394
395                 // RetroArch specifies "no disk" with index == count,
396                 // so don't fail here..
397                 disk_current_index = index;
398                 return true;
399         }
400
401         lprintf("switching to disk %u: \"%s\"\n", index,
402                 disks[index].fname);
403
404         ret = -1;
405         cd_type = PicoCdCheck(disks[index].fname, NULL);
406         if (cd_type != CIT_NOT_CD)
407                 ret = Insert_CD(disks[index].fname, cd_type);
408         if (ret != 0) {
409                 lprintf("Load failed, invalid CD image?\n");
410                 return 0;
411         }
412
413         disk_current_index = index;
414         return true;
415 }
416
417 static unsigned int disk_get_num_images(void)
418 {
419         return disk_count;
420 }
421
422 static bool disk_replace_image_index(unsigned index,
423         const struct retro_game_info *info)
424 {
425         bool ret = true;
426
427         if (index >= sizeof(disks) / sizeof(disks[0]))
428                 return false;
429
430         if (disks[index].fname != NULL)
431                 free(disks[index].fname);
432         disks[index].fname = NULL;
433
434         if (info != NULL) {
435                 disks[index].fname = strdup(info->path);
436                 if (index == disk_current_index)
437                         ret = disk_set_image_index(index);
438         }
439
440         return ret;
441 }
442
443 static bool disk_add_image_index(void)
444 {
445         if (disk_count >= sizeof(disks) / sizeof(disks[0]))
446                 return false;
447
448         disk_count++;
449         return true;
450 }
451
452 static struct retro_disk_control_callback disk_control = {
453         .set_eject_state = disk_set_eject_state,
454         .get_eject_state = disk_get_eject_state,
455         .get_image_index = disk_get_image_index,
456         .set_image_index = disk_set_image_index,
457         .get_num_images = disk_get_num_images,
458         .replace_image_index = disk_replace_image_index,
459         .add_image_index = disk_add_image_index,
460 };
461
462 static void disk_tray_open(void)
463 {
464         lprintf("cd tray open\n");
465         disk_ejected = 1;
466 }
467
468 static void disk_tray_close(void)
469 {
470         lprintf("cd tray close\n");
471         disk_ejected = 0;
472 }
473
474
475 static const char * const biosfiles_us[] = {
476         "us_scd1_9210", "us_scd2_9306", "SegaCDBIOS9303", "bios_CD_U"
477 };
478 static const char * const biosfiles_eu[] = {
479         "eu_mcd1_9210", "eu_mcd2_9306", "eu_mcd2_9303", "bios_CD_E"
480 };
481 static const char * const biosfiles_jp[] = {
482         "jp_mcd1_9112", "jp_mcd1_9111", "bios_CD_J"
483 };
484
485 static void make_system_path(char *buf, size_t buf_size,
486         const char *name, const char *ext)
487 {
488         const char *dir = NULL;
489
490         if (environ_cb(RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY, &dir) && dir) {
491                 snprintf(buf, buf_size, "%s%c%s%s", dir, SLASH, name, ext);
492         }
493         else {
494                 snprintf(buf, buf_size, "%s%s", name, ext);
495         }
496 }
497
498 static const char *find_bios(int *region, const char *cd_fname)
499 {
500         const char * const *files;
501         static char path[256];
502         int i, count;
503         FILE *f = NULL;
504
505         if (*region == 4) { // US
506                 files = biosfiles_us;
507                 count = sizeof(biosfiles_us) / sizeof(char *);
508         } else if (*region == 8) { // EU
509                 files = biosfiles_eu;
510                 count = sizeof(biosfiles_eu) / sizeof(char *);
511         } else if (*region == 1 || *region == 2) {
512                 files = biosfiles_jp;
513                 count = sizeof(biosfiles_jp) / sizeof(char *);
514         } else {
515                 return NULL;
516         }
517
518         for (i = 0; i < count; i++)
519         {
520                 make_system_path(path, sizeof(path), files[i], ".bin");
521                 f = fopen(path, "rb");
522                 if (f != NULL)
523                         break;
524
525                 make_system_path(path, sizeof(path), files[i], ".zip");
526                 f = fopen(path, "rb");
527                 if (f != NULL)
528                         break;
529         }
530
531         if (f != NULL) {
532                 lprintf("using bios: %s\n", path);
533                 fclose(f);
534                 return path;
535         }
536
537         return NULL;
538 }
539
540 bool retro_load_game(const struct retro_game_info *info)
541 {
542         enum media_type_e media_type;
543         static char carthw_path[256];
544         size_t i;
545
546         enum retro_pixel_format fmt = RETRO_PIXEL_FORMAT_RGB565;
547         if (!environ_cb(RETRO_ENVIRONMENT_SET_PIXEL_FORMAT, &fmt)) {
548                 lprintf("RGB565 suppot required, sorry\n");
549                 return false;
550         }
551
552         if (info == NULL || info->path == NULL) {
553                 lprintf("info->path required\n");
554                 return false;
555         }
556
557         for (i = 0; i < sizeof(disks) / sizeof(disks[0]); i++) {
558                 if (disks[i].fname != NULL) {
559                         free(disks[i].fname);
560                         disks[i].fname = NULL;
561                 }
562         }
563
564         disk_current_index = 0;
565         disk_count = 1;
566         disks[0].fname = strdup(info->path);
567
568         make_system_path(carthw_path, sizeof(carthw_path), "carthw", ".cfg");
569
570         media_type = PicoLoadMedia(info->path, carthw_path,
571                         find_bios, NULL);
572
573         switch (media_type) {
574         case PM_BAD_DETECT:
575                 lprintf("Failed to detect ROM/CD image type.\n");
576                 return false;
577         case PM_BAD_CD:
578                 lprintf("Invalid CD image\n");
579                 return false;
580         case PM_BAD_CD_NO_BIOS:
581                 lprintf("Missing BIOS\n");
582                 return false;
583         case PM_ERROR:
584                 lprintf("Load error\n");
585                 return false;
586         default:
587                 break;
588         }
589
590         PicoLoopPrepare();
591
592         PicoWriteSound = snd_write;
593         memset(sndBuffer, 0, sizeof(sndBuffer));
594         PsndOut = sndBuffer;
595         PsndRerate(1);
596
597         return true;
598 }
599
600 bool retro_load_game_special(unsigned game_type, const struct retro_game_info *info, size_t num_info)
601 {
602         return false;
603 }
604
605 void retro_unload_game(void) 
606 {
607 }
608
609 unsigned retro_get_region(void)
610 {
611         return Pico.m.pal ? RETRO_REGION_PAL : RETRO_REGION_NTSC;
612 }
613
614 void *retro_get_memory_data(unsigned id)
615 {
616         if (id != RETRO_MEMORY_SAVE_RAM)
617                 return NULL;
618
619         if (PicoAHW & PAHW_MCD)
620                 return Pico_mcd->bram;
621         else
622                 return SRam.data;
623 }
624
625 size_t retro_get_memory_size(unsigned id)
626 {
627         if (id != RETRO_MEMORY_SAVE_RAM)
628                 return 0;
629
630         if (PicoAHW & PAHW_MCD)
631                 // bram
632                 return 0x2000;
633         else
634                 return SRam.size;
635 }
636
637 void retro_reset(void)
638 {
639         PicoReset();
640 }
641
642 static const unsigned short retro_pico_map[] = {
643         [RETRO_DEVICE_ID_JOYPAD_B]      = 1 << GBTN_B,
644         [RETRO_DEVICE_ID_JOYPAD_Y]      = 1 << GBTN_A,
645         [RETRO_DEVICE_ID_JOYPAD_SELECT] = 1 << GBTN_MODE,
646         [RETRO_DEVICE_ID_JOYPAD_START]  = 1 << GBTN_START,
647         [RETRO_DEVICE_ID_JOYPAD_UP]     = 1 << GBTN_UP,
648         [RETRO_DEVICE_ID_JOYPAD_DOWN]   = 1 << GBTN_DOWN,
649         [RETRO_DEVICE_ID_JOYPAD_LEFT]   = 1 << GBTN_LEFT,
650         [RETRO_DEVICE_ID_JOYPAD_RIGHT]  = 1 << GBTN_RIGHT,
651         [RETRO_DEVICE_ID_JOYPAD_A]      = 1 << GBTN_C,
652         [RETRO_DEVICE_ID_JOYPAD_X]      = 1 << GBTN_Y,
653         [RETRO_DEVICE_ID_JOYPAD_L]      = 1 << GBTN_X,
654         [RETRO_DEVICE_ID_JOYPAD_R]      = 1 << GBTN_Z,
655 };
656 #define RETRO_PICO_MAP_LEN (sizeof(retro_pico_map) / sizeof(retro_pico_map[0]))
657
658 static void snd_write(int len)
659 {
660         audio_batch_cb(PsndOut, len / 4);
661 }
662
663 void retro_run(void) 
664 {
665         bool updated = false;
666         int pad, i;
667
668         if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE, &updated) && updated)
669                 ; //update_variables(true);
670
671         input_poll_cb();
672
673         PicoPad[0] = PicoPad[1] = 0;
674         for (pad = 0; pad < 2; pad++)
675                 for (i = 0; i < RETRO_PICO_MAP_LEN; i++)
676                         if (input_state_cb(pad, RETRO_DEVICE_JOYPAD, 0, i))
677                                 PicoPad[pad] |= retro_pico_map[i];
678
679         PicoFrame();
680
681         video_cb(vout_buf, vout_width, vout_height, vout_width * 2);
682 }
683
684 void retro_init(void)
685 {
686         int level;
687
688 #ifdef IOS
689         emu_log = fopen("/User/Documents/PicoDrive.log", "w");
690         if (emu_log == NULL)
691                 emu_log = fopen("PicoDrive.log", "w");
692         if (emu_log == NULL)
693 #endif
694         emu_log = stdout;
695
696         level = 0;
697         environ_cb(RETRO_ENVIRONMENT_SET_PERFORMANCE_LEVEL, &level);
698
699         environ_cb(RETRO_ENVIRONMENT_SET_DISK_CONTROL_INTERFACE, &disk_control);
700
701         PicoOpt = POPT_EN_STEREO|POPT_EN_FM|POPT_EN_PSG|POPT_EN_Z80
702                 | POPT_EN_MCD_PCM|POPT_EN_MCD_CDDA|POPT_EN_MCD_GFX
703                 | POPT_EN_32X|POPT_EN_PWM
704                 | POPT_ACC_SPRITES|POPT_DIS_32C_BORDER;
705 #ifdef __arm__
706         PicoOpt |= POPT_EN_SVP_DRC;
707 #endif
708         PsndRate = 44100;
709         PicoAutoRgnOrder = 0x184; // US, EU, JP
710         PicoCDBuffers = 0;
711
712         vout_width = 320;
713         vout_height = 240;
714         vout_buf = malloc(VOUT_MAX_WIDTH * VOUT_MAX_HEIGHT * 2);
715
716         PicoInit();
717         PicoDrawSetOutFormat(PDF_RGB555, 0);
718         PicoDrawSetOutBuf(vout_buf, vout_width * 2);
719
720         //PicoMessage = plat_status_msg_busy_next;
721         PicoMCDopenTray = disk_tray_open;
722         PicoMCDcloseTray = disk_tray_close;
723 }
724
725 void retro_deinit(void)
726 {
727         PicoExit();
728 }