allow to disable SH2 dynarec on runtime
[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                 { "picodrive_input1", "Input device 1; 3 button pad|6 button pad|None" },
187                 { "picodrive_input2", "Input device 2; 3 button pad|6 button pad|None" },
188 #ifdef DRC_SH2
189                 { "picodrive_drc", "Dynamic recompilers; enabled|disabled" },
190 #endif
191                 { NULL, NULL },
192         };
193
194         environ_cb = cb;
195
196         cb(RETRO_ENVIRONMENT_SET_VARIABLES, (void *)vars);
197 }
198
199 void retro_set_video_refresh(retro_video_refresh_t cb) { video_cb = cb; }
200 void retro_set_audio_sample(retro_audio_sample_t cb) { (void)cb; }
201 void retro_set_audio_sample_batch(retro_audio_sample_batch_t cb) { audio_batch_cb = cb; }
202 void retro_set_input_poll(retro_input_poll_t cb) { input_poll_cb = cb; }
203 void retro_set_input_state(retro_input_state_t cb) { input_state_cb = cb; }
204
205 unsigned retro_api_version(void)
206 {
207         return RETRO_API_VERSION;
208 }
209
210 void retro_set_controller_port_device(unsigned port, unsigned device)
211 {
212 }
213
214 void retro_get_system_info(struct retro_system_info *info)
215 {
216         memset(info, 0, sizeof(*info));
217         info->library_name = "PicoDrive";
218         info->library_version = VERSION;
219         info->valid_extensions = "bin|gen|smd|md|32x|cue|iso|sms";
220         info->need_fullpath = true;
221 }
222
223 void retro_get_system_av_info(struct retro_system_av_info *info)
224 {
225         memset(info, 0, sizeof(*info));
226         info->timing.fps            = Pico.m.pal ? 50 : 60;
227         info->timing.sample_rate    = 44100;
228         info->geometry.base_width   = 320;
229         info->geometry.base_height  = 240;
230         info->geometry.max_width    = VOUT_MAX_WIDTH;
231         info->geometry.max_height   = VOUT_MAX_HEIGHT;
232         info->geometry.aspect_ratio = 4.0 / 3.0;
233 }
234
235 /* savestates */
236 struct savestate_state {
237         const char *load_buf;
238         char *save_buf;
239         size_t size;
240         size_t pos;
241 };
242
243 size_t state_read(void *p, size_t size, size_t nmemb, void *file)
244 {
245         struct savestate_state *state = file;
246         size_t bsize = size * nmemb;
247
248         if (state->pos + bsize > state->size) {
249                 lprintf("savestate error: %u/%u\n",
250                         state->pos + bsize, state->size);
251                 bsize = state->size - state->pos;
252                 if ((int)bsize <= 0)
253                         return 0;
254         }
255
256         memcpy(p, state->load_buf + state->pos, bsize);
257         state->pos += bsize;
258         return bsize;
259 }
260
261 size_t state_write(void *p, size_t size, size_t nmemb, void *file)
262 {
263         struct savestate_state *state = file;
264         size_t bsize = size * nmemb;
265
266         if (state->pos + bsize > state->size) {
267                 lprintf("savestate error: %u/%u\n",
268                         state->pos + bsize, state->size);
269                 bsize = state->size - state->pos;
270                 if ((int)bsize <= 0)
271                         return 0;
272         }
273
274         memcpy(state->save_buf + state->pos, p, bsize);
275         state->pos += bsize;
276         return bsize;
277 }
278
279 size_t state_skip(void *p, size_t size, size_t nmemb, void *file)
280 {
281         struct savestate_state *state = file;
282         size_t bsize = size * nmemb;
283
284         state->pos += bsize;
285         return bsize;
286 }
287
288 size_t state_eof(void *file)
289 {
290         struct savestate_state *state = file;
291
292         return state->pos >= state->size;
293 }
294
295 int state_fseek(void *file, long offset, int whence)
296 {
297         struct savestate_state *state = file;
298
299         switch (whence) {
300         case SEEK_SET:
301                 state->pos = offset;
302                 break;
303         case SEEK_CUR:
304                 state->pos += offset;
305                 break;
306         case SEEK_END:
307                 state->pos = state->size + offset;
308                 break;
309         }
310         return (int)state->pos;
311 }
312
313 /* savestate sizes vary wildly depending if cd/32x or
314  * carthw is active, so run the whole thing to get size */
315 size_t retro_serialize_size(void) 
316
317         struct savestate_state state = { 0, };
318         int ret;
319
320         ret = PicoStateFP(&state, 1, NULL, state_skip, NULL, state_fseek);
321         if (ret != 0)
322                 return 0;
323
324         return state.pos;
325 }
326
327 bool retro_serialize(void *data, size_t size)
328
329         struct savestate_state state = { 0, };
330         int ret;
331
332         state.save_buf = data;
333         state.size = size;
334         state.pos = 0;
335
336         ret = PicoStateFP(&state, 1, NULL, state_write,
337                 NULL, state_fseek);
338         return ret == 0;
339 }
340
341 bool retro_unserialize(const void *data, size_t size)
342 {
343         struct savestate_state state = { 0, };
344         int ret;
345
346         state.load_buf = data;
347         state.size = size;
348         state.pos = 0;
349
350         ret = PicoStateFP(&state, 0, state_read, NULL,
351                 state_eof, state_fseek);
352         return ret == 0;
353 }
354
355 /* cheats - TODO */
356 void retro_cheat_reset(void)
357 {
358 }
359
360 void retro_cheat_set(unsigned index, bool enabled, const char *code)
361 {
362 }
363
364 /* multidisk support */
365 static bool disk_ejected;
366 static unsigned int disk_current_index;
367 static unsigned int disk_count;
368 static struct disks_state {
369         char *fname;
370 } disks[8];
371
372 static bool disk_set_eject_state(bool ejected)
373 {
374         // TODO?
375         disk_ejected = ejected;
376         return true;
377 }
378
379 static bool disk_get_eject_state(void)
380 {
381         return disk_ejected;
382 }
383
384 static unsigned int disk_get_image_index(void)
385 {
386         return disk_current_index;
387 }
388
389 static bool disk_set_image_index(unsigned int index)
390 {
391         cd_img_type cd_type;
392         int ret;
393
394         if (index >= sizeof(disks) / sizeof(disks[0]))
395                 return false;
396
397         if (disks[index].fname == NULL) {
398                 lprintf("missing disk #%u\n", index);
399
400                 // RetroArch specifies "no disk" with index == count,
401                 // so don't fail here..
402                 disk_current_index = index;
403                 return true;
404         }
405
406         lprintf("switching to disk %u: \"%s\"\n", index,
407                 disks[index].fname);
408
409         ret = -1;
410         cd_type = PicoCdCheck(disks[index].fname, NULL);
411         if (cd_type != CIT_NOT_CD)
412                 ret = Insert_CD(disks[index].fname, cd_type);
413         if (ret != 0) {
414                 lprintf("Load failed, invalid CD image?\n");
415                 return 0;
416         }
417
418         disk_current_index = index;
419         return true;
420 }
421
422 static unsigned int disk_get_num_images(void)
423 {
424         return disk_count;
425 }
426
427 static bool disk_replace_image_index(unsigned index,
428         const struct retro_game_info *info)
429 {
430         bool ret = true;
431
432         if (index >= sizeof(disks) / sizeof(disks[0]))
433                 return false;
434
435         if (disks[index].fname != NULL)
436                 free(disks[index].fname);
437         disks[index].fname = NULL;
438
439         if (info != NULL) {
440                 disks[index].fname = strdup(info->path);
441                 if (index == disk_current_index)
442                         ret = disk_set_image_index(index);
443         }
444
445         return ret;
446 }
447
448 static bool disk_add_image_index(void)
449 {
450         if (disk_count >= sizeof(disks) / sizeof(disks[0]))
451                 return false;
452
453         disk_count++;
454         return true;
455 }
456
457 static struct retro_disk_control_callback disk_control = {
458         .set_eject_state = disk_set_eject_state,
459         .get_eject_state = disk_get_eject_state,
460         .get_image_index = disk_get_image_index,
461         .set_image_index = disk_set_image_index,
462         .get_num_images = disk_get_num_images,
463         .replace_image_index = disk_replace_image_index,
464         .add_image_index = disk_add_image_index,
465 };
466
467 static void disk_tray_open(void)
468 {
469         lprintf("cd tray open\n");
470         disk_ejected = 1;
471 }
472
473 static void disk_tray_close(void)
474 {
475         lprintf("cd tray close\n");
476         disk_ejected = 0;
477 }
478
479
480 static const char * const biosfiles_us[] = {
481         "us_scd1_9210", "us_scd2_9306", "SegaCDBIOS9303", "bios_CD_U"
482 };
483 static const char * const biosfiles_eu[] = {
484         "eu_mcd1_9210", "eu_mcd2_9306", "eu_mcd2_9303", "bios_CD_E"
485 };
486 static const char * const biosfiles_jp[] = {
487         "jp_mcd1_9112", "jp_mcd1_9111", "bios_CD_J"
488 };
489
490 static void make_system_path(char *buf, size_t buf_size,
491         const char *name, const char *ext)
492 {
493         const char *dir = NULL;
494
495         if (environ_cb(RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY, &dir) && dir) {
496                 snprintf(buf, buf_size, "%s%c%s%s", dir, SLASH, name, ext);
497         }
498         else {
499                 snprintf(buf, buf_size, "%s%s", name, ext);
500         }
501 }
502
503 static const char *find_bios(int *region, const char *cd_fname)
504 {
505         const char * const *files;
506         static char path[256];
507         int i, count;
508         FILE *f = NULL;
509
510         if (*region == 4) { // US
511                 files = biosfiles_us;
512                 count = sizeof(biosfiles_us) / sizeof(char *);
513         } else if (*region == 8) { // EU
514                 files = biosfiles_eu;
515                 count = sizeof(biosfiles_eu) / sizeof(char *);
516         } else if (*region == 1 || *region == 2) {
517                 files = biosfiles_jp;
518                 count = sizeof(biosfiles_jp) / sizeof(char *);
519         } else {
520                 return NULL;
521         }
522
523         for (i = 0; i < count; i++)
524         {
525                 make_system_path(path, sizeof(path), files[i], ".bin");
526                 f = fopen(path, "rb");
527                 if (f != NULL)
528                         break;
529
530                 make_system_path(path, sizeof(path), files[i], ".zip");
531                 f = fopen(path, "rb");
532                 if (f != NULL)
533                         break;
534         }
535
536         if (f != NULL) {
537                 lprintf("using bios: %s\n", path);
538                 fclose(f);
539                 return path;
540         }
541
542         return NULL;
543 }
544
545 bool retro_load_game(const struct retro_game_info *info)
546 {
547         enum media_type_e media_type;
548         static char carthw_path[256];
549         size_t i;
550
551         enum retro_pixel_format fmt = RETRO_PIXEL_FORMAT_RGB565;
552         if (!environ_cb(RETRO_ENVIRONMENT_SET_PIXEL_FORMAT, &fmt)) {
553                 lprintf("RGB565 support required, sorry\n");
554                 return false;
555         }
556
557         if (info == NULL || info->path == NULL) {
558                 lprintf("info->path required\n");
559                 return false;
560         }
561
562         for (i = 0; i < sizeof(disks) / sizeof(disks[0]); i++) {
563                 if (disks[i].fname != NULL) {
564                         free(disks[i].fname);
565                         disks[i].fname = NULL;
566                 }
567         }
568
569         disk_current_index = 0;
570         disk_count = 1;
571         disks[0].fname = strdup(info->path);
572
573         make_system_path(carthw_path, sizeof(carthw_path), "carthw", ".cfg");
574
575         media_type = PicoLoadMedia(info->path, carthw_path,
576                         find_bios, NULL);
577
578         switch (media_type) {
579         case PM_BAD_DETECT:
580                 lprintf("Failed to detect ROM/CD image type.\n");
581                 return false;
582         case PM_BAD_CD:
583                 lprintf("Invalid CD image\n");
584                 return false;
585         case PM_BAD_CD_NO_BIOS:
586                 lprintf("Missing BIOS\n");
587                 return false;
588         case PM_ERROR:
589                 lprintf("Load error\n");
590                 return false;
591         default:
592                 break;
593         }
594
595         PicoLoopPrepare();
596
597         PicoWriteSound = snd_write;
598         memset(sndBuffer, 0, sizeof(sndBuffer));
599         PsndOut = sndBuffer;
600         PsndRerate(1);
601
602         return true;
603 }
604
605 bool retro_load_game_special(unsigned game_type, const struct retro_game_info *info, size_t num_info)
606 {
607         return false;
608 }
609
610 void retro_unload_game(void) 
611 {
612 }
613
614 unsigned retro_get_region(void)
615 {
616         return Pico.m.pal ? RETRO_REGION_PAL : RETRO_REGION_NTSC;
617 }
618
619 void *retro_get_memory_data(unsigned id)
620 {
621         if (id != RETRO_MEMORY_SAVE_RAM)
622                 return NULL;
623
624         if (PicoAHW & PAHW_MCD)
625                 return Pico_mcd->bram;
626         else
627                 return SRam.data;
628 }
629
630 size_t retro_get_memory_size(unsigned id)
631 {
632         if (id != RETRO_MEMORY_SAVE_RAM)
633                 return 0;
634
635         if (PicoAHW & PAHW_MCD)
636                 // bram
637                 return 0x2000;
638         else
639                 return SRam.size;
640 }
641
642 void retro_reset(void)
643 {
644         PicoReset();
645 }
646
647 static const unsigned short retro_pico_map[] = {
648         [RETRO_DEVICE_ID_JOYPAD_B]      = 1 << GBTN_B,
649         [RETRO_DEVICE_ID_JOYPAD_Y]      = 1 << GBTN_A,
650         [RETRO_DEVICE_ID_JOYPAD_SELECT] = 1 << GBTN_MODE,
651         [RETRO_DEVICE_ID_JOYPAD_START]  = 1 << GBTN_START,
652         [RETRO_DEVICE_ID_JOYPAD_UP]     = 1 << GBTN_UP,
653         [RETRO_DEVICE_ID_JOYPAD_DOWN]   = 1 << GBTN_DOWN,
654         [RETRO_DEVICE_ID_JOYPAD_LEFT]   = 1 << GBTN_LEFT,
655         [RETRO_DEVICE_ID_JOYPAD_RIGHT]  = 1 << GBTN_RIGHT,
656         [RETRO_DEVICE_ID_JOYPAD_A]      = 1 << GBTN_C,
657         [RETRO_DEVICE_ID_JOYPAD_X]      = 1 << GBTN_Y,
658         [RETRO_DEVICE_ID_JOYPAD_L]      = 1 << GBTN_X,
659         [RETRO_DEVICE_ID_JOYPAD_R]      = 1 << GBTN_Z,
660 };
661 #define RETRO_PICO_MAP_LEN (sizeof(retro_pico_map) / sizeof(retro_pico_map[0]))
662
663 static void snd_write(int len)
664 {
665         audio_batch_cb(PsndOut, len / 4);
666 }
667
668 static enum input_device input_name_to_val(const char *name)
669 {
670         if (strcmp(name, "3 button pad") == 0)
671                 return PICO_INPUT_PAD_3BTN;
672         if (strcmp(name, "6 button pad") == 0)
673                 return PICO_INPUT_PAD_6BTN;
674         if (strcmp(name, "None") == 0)
675                 return PICO_INPUT_NOTHING;
676
677         lprintf("invalid picodrive_input: '%s'\n", name);
678         return PICO_INPUT_PAD_3BTN;
679 }
680
681 static void update_variables(void)
682 {
683         struct retro_variable var;
684
685         var.value = NULL;
686         var.key = "picodrive_input1";
687         if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
688                 PicoSetInputDevice(0, input_name_to_val(var.value));
689
690         var.value = NULL;
691         var.key = "picodrive_input2";
692         if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
693                 PicoSetInputDevice(1, input_name_to_val(var.value));
694
695 #ifdef DRC_SH2
696         var.value = NULL;
697         var.key = "picodrive_drc";
698         if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
699                 if (strcmp(var.value, "enabled") == 0)
700                         PicoOpt |= POPT_EN_DRC;
701                 else
702                         PicoOpt &= ~POPT_EN_DRC;
703         }
704 #endif
705 }
706
707 void retro_run(void) 
708 {
709         bool updated = false;
710         int pad, i;
711
712         if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE, &updated) && updated)
713                 update_variables();
714
715         input_poll_cb();
716
717         PicoPad[0] = PicoPad[1] = 0;
718         for (pad = 0; pad < 2; pad++)
719                 for (i = 0; i < RETRO_PICO_MAP_LEN; i++)
720                         if (input_state_cb(pad, RETRO_DEVICE_JOYPAD, 0, i))
721                                 PicoPad[pad] |= retro_pico_map[i];
722
723         PicoFrame();
724
725         video_cb(vout_buf, vout_width, vout_height, vout_width * 2);
726 }
727
728 void retro_init(void)
729 {
730         int level;
731
732 #ifdef IOS
733         emu_log = fopen("/User/Documents/PicoDrive.log", "w");
734         if (emu_log == NULL)
735                 emu_log = fopen("PicoDrive.log", "w");
736         if (emu_log == NULL)
737 #endif
738         emu_log = stdout;
739
740         level = 0;
741         environ_cb(RETRO_ENVIRONMENT_SET_PERFORMANCE_LEVEL, &level);
742
743         environ_cb(RETRO_ENVIRONMENT_SET_DISK_CONTROL_INTERFACE, &disk_control);
744
745         PicoOpt = POPT_EN_STEREO|POPT_EN_FM|POPT_EN_PSG|POPT_EN_Z80
746                 | POPT_EN_MCD_PCM|POPT_EN_MCD_CDDA|POPT_EN_MCD_GFX
747                 | POPT_EN_32X|POPT_EN_PWM
748                 | POPT_ACC_SPRITES|POPT_DIS_32C_BORDER;
749 #ifdef __arm__
750         PicoOpt |= POPT_EN_SVP_DRC;
751 #endif
752         PsndRate = 44100;
753         PicoAutoRgnOrder = 0x184; // US, EU, JP
754         PicoCDBuffers = 0;
755
756         vout_width = 320;
757         vout_height = 240;
758         vout_buf = malloc(VOUT_MAX_WIDTH * VOUT_MAX_HEIGHT * 2);
759
760         PicoInit();
761         PicoDrawSetOutFormat(PDF_RGB555, 0);
762         PicoDrawSetOutBuf(vout_buf, vout_width * 2);
763
764         //PicoMessage = plat_status_msg_busy_next;
765         PicoMCDopenTray = disk_tray_open;
766         PicoMCDcloseTray = disk_tray_close;
767
768         update_variables();
769 }
770
771 void retro_deinit(void)
772 {
773         PicoExit();
774 }