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