f916f57a7229be4e9f59ba6d4e18cd497942f650
[pcsx_rearmed.git] / frontend / libretro.c
1 /*
2  * (C) notaz, 2012
3  *
4  * This work is licensed under the terms of the GNU GPLv2 or later.
5  * See the COPYING file in the top-level directory.
6  */
7
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
11
12 #include "../libpcsxcore/misc.h"
13 #include "../libpcsxcore/psxcounters.h"
14 #include "../libpcsxcore/psxmem_map.h"
15 #include "../libpcsxcore/new_dynarec/new_dynarec.h"
16 #include "../libpcsxcore/cdrom.h"
17 #include "../libpcsxcore/cdriso.h"
18 #include "../libpcsxcore/cheat.h"
19 #include "../plugins/dfsound/out.h"
20 #include "cspace.h"
21 #include "main.h"
22 #include "plugin.h"
23 #include "plugin_lib.h"
24 #include "revision.h"
25 #include "libretro.h"
26
27 static retro_video_refresh_t video_cb;
28 static retro_input_poll_t input_poll_cb;
29 static retro_input_state_t input_state_cb;
30 static retro_environment_t environ_cb;
31 static retro_audio_sample_batch_t audio_batch_cb;
32
33 static void *vout_buf;
34 static int vout_width, vout_height;
35 static int vout_doffs_old, vout_fb_dirty;
36 static bool vout_can_dupe;
37
38 static int samples_sent, samples_to_send;
39 static int plugins_opened;
40 static int is_pal_mode;
41
42 /* memory card data */
43 extern char Mcd1Data[MCD_SIZE];
44 extern char McdDisable[2];
45
46 /* PCSX ReARMed core calls and stuff */
47 int in_type1, in_type2;
48 int in_a1[2] = { 127, 127 }, in_a2[2] = { 127, 127 };
49 int in_keystate;
50 int in_enable_vibration;
51
52 static void init_memcard(char *mcd_data)
53 {
54         unsigned off = 0;
55         unsigned i;
56
57         memset(mcd_data, 0, MCD_SIZE);
58
59         mcd_data[off++] = 'M';
60         mcd_data[off++] = 'C';
61         off += 0x7d;
62         mcd_data[off++] = 0x0e;
63
64         for (i = 0; i < 15; i++) {
65                 mcd_data[off++] = 0xa0;
66                 off += 0x07;
67                 mcd_data[off++] = 0xff;
68                 mcd_data[off++] = 0xff;
69                 off += 0x75;
70                 mcd_data[off++] = 0xa0;
71         }
72
73         for (i = 0; i < 20; i++) {
74                 mcd_data[off++] = 0xff;
75                 mcd_data[off++] = 0xff;
76                 mcd_data[off++] = 0xff;
77                 mcd_data[off++] = 0xff;
78                 off += 0x04;
79                 mcd_data[off++] = 0xff;
80                 mcd_data[off++] = 0xff;
81                 off += 0x76;
82         }
83 }
84
85 static int vout_open(void)
86 {
87         return 0;
88 }
89
90 static void vout_set_mode(int w, int h, int raw_w, int raw_h, int bpp)
91 {
92         vout_width = w;
93         vout_height = h;
94 }
95
96 #ifndef FRONTEND_SUPPORTS_RGB565
97 static void convert(void *buf, size_t bytes)
98 {
99         unsigned int i, v, *p = buf;
100
101         for (i = 0; i < bytes / 4; i++) {
102                 v = p[i];
103                 p[i] = (v & 0x001f001f) | ((v >> 1) & 0x7fe07fe0);
104         }
105 }
106 #endif
107
108 static void vout_flip(const void *vram, int stride, int bgr24, int w, int h)
109 {
110         unsigned short *dest = vout_buf;
111         const unsigned short *src = vram;
112         int dstride = vout_width, h1 = h;
113         int doffs;
114
115         if (vram == NULL) {
116                 // blanking
117                 memset(vout_buf, 0, dstride * h * 2);
118                 goto out;
119         }
120
121         doffs = (vout_height - h) * dstride;
122         doffs += (dstride - w) / 2 & ~1;
123         if (doffs != vout_doffs_old) {
124                 // clear borders
125                 memset(vout_buf, 0, dstride * h * 2);
126                 vout_doffs_old = doffs;
127         }
128         dest += doffs;
129
130         if (bgr24)
131         {
132                 // XXX: could we switch to RETRO_PIXEL_FORMAT_XRGB8888 here?
133                 for (; h1-- > 0; dest += dstride, src += stride)
134                 {
135                         bgr888_to_rgb565(dest, src, w * 3);
136                 }
137         }
138         else
139         {
140                 for (; h1-- > 0; dest += dstride, src += stride)
141                 {
142                         bgr555_to_rgb565(dest, src, w * 2);
143                 }
144         }
145
146 out:
147 #ifndef FRONTEND_SUPPORTS_RGB565
148         convert(vout_buf, vout_width * vout_height * 2);
149 #endif
150         vout_fb_dirty = 1;
151         pl_rearmed_cbs.flip_cnt++;
152 }
153
154 static void vout_close(void)
155 {
156 }
157
158 static void *pl_mmap(unsigned int size)
159 {
160         return psxMap(0, size, 0, MAP_TAG_VRAM);
161 }
162
163 static void pl_munmap(void *ptr, unsigned int size)
164 {
165         psxUnmap(ptr, size, MAP_TAG_VRAM);
166 }
167
168 struct rearmed_cbs pl_rearmed_cbs = {
169         .pl_vout_open = vout_open,
170         .pl_vout_set_mode = vout_set_mode,
171         .pl_vout_flip = vout_flip,
172         .pl_vout_close = vout_close,
173         .mmap = pl_mmap,
174         .munmap = pl_munmap,
175         /* from psxcounters */
176         .gpu_hcnt = &hSyncCount,
177         .gpu_frame_count = &frame_counter,
178 };
179
180 void pl_frame_limit(void)
181 {
182         /* called once per frame, make psxCpu->Execute() above return */
183         stop = 1;
184 }
185
186 void pl_timing_prepare(int is_pal)
187 {
188         is_pal_mode = is_pal;
189 }
190
191 void plat_trigger_vibrate(int is_strong)
192 {
193 }
194
195 void pl_update_gun(int *xn, int *yn, int *xres, int *yres, int *in)
196 {
197 }
198
199 /* sound calls */
200 static int snd_init(void)
201 {
202         return 0;
203 }
204
205 static void snd_finish(void)
206 {
207 }
208
209 static int snd_busy(void)
210 {
211         if (samples_to_send > samples_sent)
212                 return 0; /* give more samples */
213         else
214                 return 1;
215 }
216
217 static void snd_feed(void *buf, int bytes)
218 {
219         audio_batch_cb(buf, bytes / 4);
220         samples_sent += bytes / 4;
221 }
222
223 void out_register_libretro(struct out_driver *drv)
224 {
225         drv->name = "libretro";
226         drv->init = snd_init;
227         drv->finish = snd_finish;
228         drv->busy = snd_busy;
229         drv->feed = snd_feed;
230 }
231
232 /* libretro */
233 void retro_set_environment(retro_environment_t cb) { environ_cb = cb; }
234 void retro_set_video_refresh(retro_video_refresh_t cb) { video_cb = cb; }
235 void retro_set_audio_sample(retro_audio_sample_t cb) { (void)cb; }
236 void retro_set_audio_sample_batch(retro_audio_sample_batch_t cb) { audio_batch_cb = cb; }
237 void retro_set_input_poll(retro_input_poll_t cb) { input_poll_cb = cb; }
238 void retro_set_input_state(retro_input_state_t cb) { input_state_cb = cb; }
239
240 unsigned retro_api_version(void)
241 {
242         return RETRO_API_VERSION;
243 }
244
245 void retro_set_controller_port_device(unsigned port, unsigned device)
246 {
247 }
248
249 void retro_get_system_info(struct retro_system_info *info)
250 {
251         memset(info, 0, sizeof(*info));
252         info->library_name = "PCSX-ReARMed";
253         info->library_version = "r19";
254         info->valid_extensions = "bin|cue|img|mdf|pbp|cbn";
255         info->need_fullpath = true;
256 }
257
258 void retro_get_system_av_info(struct retro_system_av_info *info)
259 {
260         memset(info, 0, sizeof(*info));
261         info->timing.fps            = is_pal_mode ? 50 : 60;
262         info->timing.sample_rate    = 44100;
263         info->geometry.base_width   = 320;
264         info->geometry.base_height  = 240;
265         info->geometry.max_width    = 640;
266         info->geometry.max_height   = 512;
267         info->geometry.aspect_ratio = 4.0 / 3.0;
268 }
269
270 /* savestates */
271 size_t retro_serialize_size(void) 
272
273         // it's currently 4380651 bytes, but have some reserved for future
274         return 0x430000;
275 }
276
277 struct save_fp {
278         char *buf;
279         size_t pos;
280         int is_write;
281 };
282
283 static void *save_open(const char *name, const char *mode)
284 {
285         struct save_fp *fp;
286
287         if (name == NULL || mode == NULL)
288                 return NULL;
289
290         fp = malloc(sizeof(*fp));
291         if (fp == NULL)
292                 return NULL;
293
294         fp->buf = (char *)name;
295         fp->pos = 0;
296         fp->is_write = (mode[0] == 'w' || mode[1] == 'w');
297
298         return fp;
299 }
300
301 static int save_read(void *file, void *buf, u32 len)
302 {
303         struct save_fp *fp = file;
304         if (fp == NULL || buf == NULL)
305                 return -1;
306
307         memcpy(buf, fp->buf + fp->pos, len);
308         fp->pos += len;
309         return len;
310 }
311
312 static int save_write(void *file, const void *buf, u32 len)
313 {
314         struct save_fp *fp = file;
315         if (fp == NULL || buf == NULL)
316                 return -1;
317
318         memcpy(fp->buf + fp->pos, buf, len);
319         fp->pos += len;
320         return len;
321 }
322
323 static long save_seek(void *file, long offs, int whence)
324 {
325         struct save_fp *fp = file;
326         if (fp == NULL)
327                 return -1;
328
329         switch (whence) {
330         case SEEK_CUR:
331                 fp->pos += offs;
332                 return fp->pos;
333         case SEEK_SET:
334                 fp->pos = offs;
335                 return fp->pos;
336         default:
337                 return -1;
338         }
339 }
340
341 static void save_close(void *file)
342 {
343         struct save_fp *fp = file;
344         size_t r_size = retro_serialize_size();
345         if (fp == NULL)
346                 return;
347
348         if (fp->pos > r_size)
349                 SysPrintf("ERROR: save buffer overflow detected\n");
350         else if (fp->is_write && fp->pos < r_size)
351                 // make sure we don't save trash in leftover space
352                 memset(fp->buf + fp->pos, 0, r_size - fp->pos);
353         free(fp);
354 }
355
356 bool retro_serialize(void *data, size_t size)
357
358         int ret = SaveState(data);
359         return ret == 0 ? true : false;
360 }
361
362 bool retro_unserialize(const void *data, size_t size)
363 {
364         int ret = LoadState(data);
365         return ret == 0 ? true : false;
366 }
367
368 /* cheats */
369 void retro_cheat_reset(void)
370 {
371         ClearAllCheats();
372 }
373
374 void retro_cheat_set(unsigned index, bool enabled, const char *code)
375 {
376         char buf[256];
377         int ret;
378
379         // cheat funcs are destructive, need a copy..
380         strncpy(buf, code, sizeof(buf));
381         buf[sizeof(buf) - 1] = 0;
382
383         if (index < NumCheats)
384                 ret = EditCheat(index, "", buf);
385         else
386                 ret = AddCheat("", buf);
387
388         if (ret != 0)
389                 SysPrintf("Failed to set cheat %#u\n", index);
390         else if (index < NumCheats)
391                 Cheats[index].Enabled = enabled;
392 }
393
394 /* multidisk support */
395 static bool disk_ejected;
396 static unsigned int disk_current_index;
397 static struct disks_state {
398         char *fname;
399         int internal_index; // for multidisk eboots
400 } disks[8];
401
402 static bool disk_set_eject_state(bool ejected)
403 {
404         // weird PCSX API..
405         SetCdOpenCaseTime(ejected ? -1 : (time(NULL) + 2));
406         LidInterrupt();
407
408         disk_ejected = ejected;
409         return true;
410 }
411
412 static bool disk_get_eject_state(void)
413 {
414         /* can't be controlled by emulated software */
415         return disk_ejected;
416 }
417
418 static unsigned int disk_get_image_index(void)
419 {
420         return disk_current_index;
421 }
422
423 static bool disk_set_image_index(unsigned int index)
424 {
425         if (index >= sizeof(disks) / sizeof(disks[0]))
426                 return false;
427
428         CdromId[0] = '\0';
429         CdromLabel[0] = '\0';
430
431         if (disks[index].fname == NULL) {
432                 SysPrintf("missing disk #%u\n", index);
433                 CDR_shutdown();
434
435                 // RetroArch specifies "no disk" with index == count,
436                 // so don't fail here..
437                 disk_current_index = index;
438                 return true;
439         }
440
441         SysPrintf("switching to disk %u: \"%s\" #%d\n", index,
442                 disks[index].fname, disks[index].internal_index);
443
444         cdrIsoMultidiskSelect = disks[index].internal_index;
445         set_cd_image(disks[index].fname);
446         if (ReloadCdromPlugin() < 0) {
447                 SysPrintf("failed to load cdr plugin\n");
448                 return false;
449         }
450         if (CDR_open() < 0) {
451                 SysPrintf("failed to open cdr plugin\n");
452                 return false;
453         }
454
455         if (!disk_ejected) {
456                 SetCdOpenCaseTime(time(NULL) + 2);
457                 LidInterrupt();
458         }
459
460         disk_current_index = index;
461         return true;
462 }
463
464 static unsigned int disk_get_num_images(void)
465 {
466         unsigned int count = 0;
467         size_t i;
468
469         for (i = 0; i < sizeof(disks) / sizeof(disks[0]); i++)
470                 if (disks[i].fname != NULL)
471                         count++;
472
473         return count;
474 }
475
476 static bool disk_replace_image_index(unsigned index,
477         const struct retro_game_info *info)
478 {
479         char *old_fname;
480         bool ret = true;
481
482         if (index >= sizeof(disks) / sizeof(disks[0]))
483                 return false;
484
485         old_fname = disks[index].fname;
486         disks[index].fname = NULL;
487         disks[index].internal_index = 0;
488
489         if (info != NULL) {
490                 disks[index].fname = strdup(info->path);
491                 if (index == disk_current_index)
492                         ret = disk_set_image_index(index);
493         }
494
495         if (old_fname != NULL)
496                 free(old_fname);
497
498         return ret;
499 }
500
501 static bool disk_add_image_index(void)
502 {
503         // TODO??
504         return true;
505 }
506
507 static struct retro_disk_control_callback disk_control = {
508         .set_eject_state = disk_set_eject_state,
509         .get_eject_state = disk_get_eject_state,
510         .get_image_index = disk_get_image_index,
511         .set_image_index = disk_set_image_index,
512         .get_num_images = disk_get_num_images,
513         .replace_image_index = disk_replace_image_index,
514         .add_image_index = disk_add_image_index,
515 };
516
517 bool retro_load_game(const struct retro_game_info *info)
518 {
519         size_t i;
520 #ifdef FRONTEND_SUPPORTS_RGB565
521         enum retro_pixel_format fmt = RETRO_PIXEL_FORMAT_RGB565;
522         if (environ_cb(RETRO_ENVIRONMENT_SET_PIXEL_FORMAT, &fmt)) {
523                 SysPrintf("RGB565 supported, using it\n");
524         }
525 #endif
526
527         if (info == NULL || info->path == NULL) {
528                 SysPrintf("info->path required\n");
529                 return false;
530         }
531
532         if (plugins_opened) {
533                 ClosePlugins();
534                 plugins_opened = 0;
535         }
536
537         for (i = 0; i < sizeof(disks) / sizeof(disks[0]); i++) {
538                 if (disks[i].fname != NULL) {
539                         free(disks[i].fname);
540                         disks[i].fname = NULL;
541                 }
542                 disks[i].internal_index = 0;
543         }
544
545         disk_current_index = 0;
546         disks[0].fname = strdup(info->path);
547
548         set_cd_image(disks[0].fname);
549
550         /* have to reload after set_cd_image for correct cdr plugin */
551         if (LoadPlugins() == -1) {
552                 SysPrintf("failed to load plugins\n");
553                 return false;
554         }
555
556         plugins_opened = 1;
557         NetOpened = 0;
558
559         if (OpenPlugins() == -1) {
560                 SysPrintf("failed to open plugins\n");
561                 return false;
562         }
563
564         plugin_call_rearmed_cbs();
565
566         Config.PsxAuto = 1;
567         if (CheckCdrom() == -1) {
568                 SysPrintf("unsupported/invalid CD image: %s\n", info->path);
569                 return false;
570         }
571
572         SysReset();
573
574         if (LoadCdrom() == -1) {
575                 SysPrintf("could not load CD-ROM!\n");
576                 return false;
577         }
578         emu_on_new_cd(0);
579
580         // multidisk images
581         for (i = 1; i < sizeof(disks) / sizeof(disks[0]) && i < cdrIsoMultidiskCount; i++) {
582                 disks[i].fname = strdup(info->path);
583                 disks[i].internal_index = i;
584         }
585
586         return true;
587 }
588
589 bool retro_load_game_special(unsigned game_type, const struct retro_game_info *info, size_t num_info)
590 {
591         return false;
592 }
593
594 void retro_unload_game(void) 
595 {
596 }
597
598 unsigned retro_get_region(void)
599 {
600         return is_pal_mode ? RETRO_REGION_PAL : RETRO_REGION_NTSC;
601 }
602
603 void *retro_get_memory_data(unsigned id)
604 {
605         return Mcd1Data;
606 }
607
608 size_t retro_get_memory_size(unsigned id)
609 {
610         return MCD_SIZE;
611 }
612
613 void retro_reset(void)
614 {
615         SysReset();
616 }
617
618 static const unsigned short retro_psx_map[] = {
619         [RETRO_DEVICE_ID_JOYPAD_B]      = 1 << DKEY_CROSS,
620         [RETRO_DEVICE_ID_JOYPAD_Y]      = 1 << DKEY_SQUARE,
621         [RETRO_DEVICE_ID_JOYPAD_SELECT] = 1 << DKEY_SELECT,
622         [RETRO_DEVICE_ID_JOYPAD_START]  = 1 << DKEY_START,
623         [RETRO_DEVICE_ID_JOYPAD_UP]     = 1 << DKEY_UP,
624         [RETRO_DEVICE_ID_JOYPAD_DOWN]   = 1 << DKEY_DOWN,
625         [RETRO_DEVICE_ID_JOYPAD_LEFT]   = 1 << DKEY_LEFT,
626         [RETRO_DEVICE_ID_JOYPAD_RIGHT]  = 1 << DKEY_RIGHT,
627         [RETRO_DEVICE_ID_JOYPAD_A]      = 1 << DKEY_CIRCLE,
628         [RETRO_DEVICE_ID_JOYPAD_X]      = 1 << DKEY_TRIANGLE,
629         [RETRO_DEVICE_ID_JOYPAD_L]      = 1 << DKEY_L1,
630         [RETRO_DEVICE_ID_JOYPAD_R]      = 1 << DKEY_R1,
631         [RETRO_DEVICE_ID_JOYPAD_L2]     = 1 << DKEY_L2,
632         [RETRO_DEVICE_ID_JOYPAD_R2]     = 1 << DKEY_R2,
633         [RETRO_DEVICE_ID_JOYPAD_L3]     = 1 << DKEY_L3,
634         [RETRO_DEVICE_ID_JOYPAD_R3]     = 1 << DKEY_R3,
635 };
636 #define RETRO_PSX_MAP_LEN (sizeof(retro_psx_map) / sizeof(retro_psx_map[0]))
637
638 void retro_run(void) 
639 {
640         int i;
641
642         input_poll_cb();
643         in_keystate = 0;
644         for (i = 0; i < RETRO_PSX_MAP_LEN; i++)
645                 if (input_state_cb(1, RETRO_DEVICE_JOYPAD, 0, i))
646                         in_keystate |= retro_psx_map[i];
647         in_keystate <<= 16;
648         for (i = 0; i < RETRO_PSX_MAP_LEN; i++)
649                 if (input_state_cb(0, RETRO_DEVICE_JOYPAD, 0, i))
650                         in_keystate |= retro_psx_map[i];
651
652         stop = 0;
653         psxCpu->Execute();
654
655         samples_to_send += is_pal_mode ? 44100 / 50 : 44100 / 60;
656
657         video_cb((vout_fb_dirty || !vout_can_dupe) ? vout_buf : NULL,
658                 vout_width, vout_height, vout_width * 2);
659         vout_fb_dirty = 0;
660 }
661
662 void retro_init(void)
663 {
664         const char *bios[] = { "scph1001", "scph5501", "scph7001" };
665         const char *dir;
666         char path[256];
667         FILE *f = NULL;
668         int i, ret, level;
669
670         ret = emu_core_preinit();
671         ret |= emu_core_init();
672         if (ret != 0) {
673                 SysPrintf("PCSX init failed.\n");
674                 exit(1);
675         }
676
677         vout_buf = malloc(640 * 512 * 2);
678
679         if (environ_cb(RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY, &dir) && dir)
680         {
681                 snprintf(Config.BiosDir, sizeof(Config.BiosDir), "%s/", dir);
682
683                 for (i = 0; i < sizeof(bios) / sizeof(bios[0]); i++) {
684                         snprintf(path, sizeof(path), "%s/%s.bin", dir, bios[i]);
685                         f = fopen(path, "r");
686                         if (f != NULL) {
687                                 snprintf(Config.Bios, sizeof(Config.Bios), "%s.bin", bios[i]);
688                                 break;
689                         }
690                 }
691         }
692         if (f != NULL) {
693                 SysPrintf("found BIOS file: %s\n", Config.Bios);
694                 fclose(f);
695         }
696         else
697                 SysPrintf("no BIOS files found.\n");
698
699         level = 1;
700         environ_cb(RETRO_ENVIRONMENT_SET_PERFORMANCE_LEVEL, &level);
701
702         environ_cb(RETRO_ENVIRONMENT_GET_CAN_DUPE, &vout_can_dupe);
703         environ_cb(RETRO_ENVIRONMENT_SET_DISK_CONTROL_INTERFACE, &disk_control);
704
705         /* Set how much slower PSX CPU runs * 100 (so that 200 is 2 times)
706          * we have to do this because cache misses and some IO penalties
707          * are not emulated. Warning: changing this may break compatibility. */
708 #ifdef __ARM_ARCH_7A__
709         cycle_multiplier = 175;
710 #else
711         cycle_multiplier = 200;
712 #endif
713
714         McdDisable[0] = 0;
715         McdDisable[1] = 1;
716         init_memcard(Mcd1Data);
717
718         SaveFuncs.open = save_open;
719         SaveFuncs.read = save_read;
720         SaveFuncs.write = save_write;
721         SaveFuncs.seek = save_seek;
722         SaveFuncs.close = save_close;
723 }
724
725 void retro_deinit(void)
726 {
727         SysClose();
728         free(vout_buf);
729         vout_buf = NULL;
730 }