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