aea17e81501041111eb667ea4082bd3b37536b88
[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 #define _GNU_SOURCE 1 // strcasestr
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <strings.h>
13
14 #include "../libpcsxcore/misc.h"
15 #include "../libpcsxcore/psxcounters.h"
16 #include "../libpcsxcore/psxmem_map.h"
17 #include "../libpcsxcore/new_dynarec/new_dynarec.h"
18 #include "../libpcsxcore/cdrom.h"
19 #include "../libpcsxcore/cdriso.h"
20 #include "../libpcsxcore/cheat.h"
21 #include "../plugins/dfsound/out.h"
22 #include "../plugins/dfinput/externals.h"
23 #include "cspace.h"
24 #include "main.h"
25 #include "plugin.h"
26 #include "plugin_lib.h"
27 #include "revision.h"
28 #include "libretro.h"
29
30 static retro_video_refresh_t video_cb;
31 static retro_input_poll_t input_poll_cb;
32 static retro_input_state_t input_state_cb;
33 static retro_environment_t environ_cb;
34 static retro_audio_sample_batch_t audio_batch_cb;
35
36 static void *vout_buf;
37 static int vout_width, vout_height;
38 static int vout_doffs_old, vout_fb_dirty;
39 static bool vout_can_dupe;
40 static bool duping_enable;
41
42 static int samples_sent, samples_to_send;
43 static int plugins_opened;
44 static int is_pal_mode;
45
46 /* memory card data */
47 extern char Mcd1Data[MCD_SIZE];
48 extern char McdDisable[2];
49
50 /* PCSX ReARMed core calls and stuff */
51 int in_type1, in_type2;
52 int in_a1[2] = { 127, 127 }, in_a2[2] = { 127, 127 };
53 int in_keystate;
54 int in_enable_vibration;
55
56 /* PSX max resolution is 640x512, but with enhancement it's 1024x512 */
57 #define VOUT_MAX_WIDTH 1024
58 #define VOUT_MAX_HEIGHT 512
59
60 static void init_memcard(char *mcd_data)
61 {
62         unsigned off = 0;
63         unsigned i;
64
65         memset(mcd_data, 0, MCD_SIZE);
66
67         mcd_data[off++] = 'M';
68         mcd_data[off++] = 'C';
69         off += 0x7d;
70         mcd_data[off++] = 0x0e;
71
72         for (i = 0; i < 15; i++) {
73                 mcd_data[off++] = 0xa0;
74                 off += 0x07;
75                 mcd_data[off++] = 0xff;
76                 mcd_data[off++] = 0xff;
77                 off += 0x75;
78                 mcd_data[off++] = 0xa0;
79         }
80
81         for (i = 0; i < 20; i++) {
82                 mcd_data[off++] = 0xff;
83                 mcd_data[off++] = 0xff;
84                 mcd_data[off++] = 0xff;
85                 mcd_data[off++] = 0xff;
86                 off += 0x04;
87                 mcd_data[off++] = 0xff;
88                 mcd_data[off++] = 0xff;
89                 off += 0x76;
90         }
91 }
92
93 static int vout_open(void)
94 {
95         return 0;
96 }
97
98 static void vout_set_mode(int w, int h, int raw_w, int raw_h, int bpp)
99 {
100         vout_width = w;
101         vout_height = h;
102 }
103
104 #ifndef FRONTEND_SUPPORTS_RGB565
105 static void convert(void *buf, size_t bytes)
106 {
107         unsigned int i, v, *p = buf;
108
109         for (i = 0; i < bytes / 4; i++) {
110                 v = p[i];
111                 p[i] = (v & 0x001f001f) | ((v >> 1) & 0x7fe07fe0);
112         }
113 }
114 #endif
115
116 static void vout_flip(const void *vram, int stride, int bgr24, int w, int h)
117 {
118         unsigned short *dest = vout_buf;
119         const unsigned short *src = vram;
120         int dstride = vout_width, h1 = h;
121         int doffs;
122
123         if (vram == NULL) {
124                 // blanking
125                 memset(vout_buf, 0, dstride * h * 2);
126                 goto out;
127         }
128
129         doffs = (vout_height - h) * dstride;
130         doffs += (dstride - w) / 2 & ~1;
131         if (doffs != vout_doffs_old) {
132                 // clear borders
133                 memset(vout_buf, 0, dstride * h * 2);
134                 vout_doffs_old = doffs;
135         }
136         dest += doffs;
137
138         if (bgr24)
139         {
140                 // XXX: could we switch to RETRO_PIXEL_FORMAT_XRGB8888 here?
141                 for (; h1-- > 0; dest += dstride, src += stride)
142                 {
143                         bgr888_to_rgb565(dest, src, w * 3);
144                 }
145         }
146         else
147         {
148                 for (; h1-- > 0; dest += dstride, src += stride)
149                 {
150                         bgr555_to_rgb565(dest, src, w * 2);
151                 }
152         }
153
154 out:
155 #ifndef FRONTEND_SUPPORTS_RGB565
156         convert(vout_buf, vout_width * vout_height * 2);
157 #endif
158         vout_fb_dirty = 1;
159         pl_rearmed_cbs.flip_cnt++;
160 }
161
162 static void vout_close(void)
163 {
164 }
165
166 static void *pl_mmap(unsigned int size)
167 {
168         return psxMap(0, size, 0, MAP_TAG_VRAM);
169 }
170
171 static void pl_munmap(void *ptr, unsigned int size)
172 {
173         psxUnmap(ptr, size, MAP_TAG_VRAM);
174 }
175
176 struct rearmed_cbs pl_rearmed_cbs = {
177         .pl_vout_open = vout_open,
178         .pl_vout_set_mode = vout_set_mode,
179         .pl_vout_flip = vout_flip,
180         .pl_vout_close = vout_close,
181         .mmap = pl_mmap,
182         .munmap = pl_munmap,
183         /* from psxcounters */
184         .gpu_hcnt = &hSyncCount,
185         .gpu_frame_count = &frame_counter,
186 };
187
188 void pl_frame_limit(void)
189 {
190         /* called once per frame, make psxCpu->Execute() above return */
191         stop = 1;
192 }
193
194 void pl_timing_prepare(int is_pal)
195 {
196         is_pal_mode = is_pal;
197 }
198
199 void plat_trigger_vibrate(int is_strong)
200 {
201 }
202
203 void pl_update_gun(int *xn, int *yn, int *xres, int *yres, int *in)
204 {
205 }
206
207 /* sound calls */
208 static int snd_init(void)
209 {
210         return 0;
211 }
212
213 static void snd_finish(void)
214 {
215 }
216
217 static int snd_busy(void)
218 {
219         if (samples_to_send > samples_sent)
220                 return 0; /* give more samples */
221         else
222                 return 1;
223 }
224
225 static void snd_feed(void *buf, int bytes)
226 {
227         audio_batch_cb(buf, bytes / 4);
228         samples_sent += bytes / 4;
229 }
230
231 void out_register_libretro(struct out_driver *drv)
232 {
233         drv->name = "libretro";
234         drv->init = snd_init;
235         drv->finish = snd_finish;
236         drv->busy = snd_busy;
237         drv->feed = snd_feed;
238 }
239
240 /* libretro */
241 void retro_set_environment(retro_environment_t cb)
242 {
243    static const struct retro_variable vars[] = {
244       { "frameskip", "Frameskip; 0|1|2|3" },
245       { "region", "Region; Auto|NTSC|PAL" },
246       { "pad1type", "Pad 1 Type; standard|analog" },
247 #ifndef DRC_DISABLE
248       { "rearmed_drc", "Dynamic recompiler; enabled|disabled" },
249 #endif
250 #ifdef __ARM_NEON__
251       { "neon_interlace_enable", "Enable interlacing mode(s); disabled|enabled" },
252       { "neon_enhancement_enable", "Enhanced resolution (slow); disabled|enabled" },
253       { "neon_enhancement_no_main", "Enhanced resolution speed hack; disabled|enabled" },
254 #endif
255       { "pcsx_rearmed_duping_enable", "Frame duping; on|off" },
256       { NULL, NULL },
257    };
258
259    environ_cb = cb;
260
261    cb(RETRO_ENVIRONMENT_SET_VARIABLES, (void*)vars);
262 }
263
264 void retro_set_video_refresh(retro_video_refresh_t cb) { video_cb = cb; }
265 void retro_set_audio_sample(retro_audio_sample_t cb) { (void)cb; }
266 void retro_set_audio_sample_batch(retro_audio_sample_batch_t cb) { audio_batch_cb = cb; }
267 void retro_set_input_poll(retro_input_poll_t cb) { input_poll_cb = cb; }
268 void retro_set_input_state(retro_input_state_t cb) { input_state_cb = cb; }
269
270 unsigned retro_api_version(void)
271 {
272         return RETRO_API_VERSION;
273 }
274
275 void retro_set_controller_port_device(unsigned port, unsigned device)
276 {
277 }
278
279 void retro_get_system_info(struct retro_system_info *info)
280 {
281         memset(info, 0, sizeof(*info));
282         info->library_name = "PCSX-ReARMed";
283         info->library_version = "r19";
284         info->valid_extensions = "bin|cue|img|mdf|pbp|toc|cbn|m3u";
285         info->need_fullpath = true;
286 }
287
288 void retro_get_system_av_info(struct retro_system_av_info *info)
289 {
290         memset(info, 0, sizeof(*info));
291         info->timing.fps            = is_pal_mode ? 50 : 60;
292         info->timing.sample_rate    = 44100;
293         info->geometry.base_width   = 320;
294         info->geometry.base_height  = 240;
295         info->geometry.max_width    = VOUT_MAX_WIDTH;
296         info->geometry.max_height   = VOUT_MAX_HEIGHT;
297         info->geometry.aspect_ratio = 4.0 / 3.0;
298 }
299
300 /* savestates */
301 size_t retro_serialize_size(void) 
302
303         // it's currently 4380651 bytes, but have some reserved for future
304         return 0x430000;
305 }
306
307 struct save_fp {
308         char *buf;
309         size_t pos;
310         int is_write;
311 };
312
313 static void *save_open(const char *name, const char *mode)
314 {
315         struct save_fp *fp;
316
317         if (name == NULL || mode == NULL)
318                 return NULL;
319
320         fp = malloc(sizeof(*fp));
321         if (fp == NULL)
322                 return NULL;
323
324         fp->buf = (char *)name;
325         fp->pos = 0;
326         fp->is_write = (mode[0] == 'w' || mode[1] == 'w');
327
328         return fp;
329 }
330
331 static int save_read(void *file, void *buf, u32 len)
332 {
333         struct save_fp *fp = file;
334         if (fp == NULL || buf == NULL)
335                 return -1;
336
337         memcpy(buf, fp->buf + fp->pos, len);
338         fp->pos += len;
339         return len;
340 }
341
342 static int save_write(void *file, const void *buf, u32 len)
343 {
344         struct save_fp *fp = file;
345         if (fp == NULL || buf == NULL)
346                 return -1;
347
348         memcpy(fp->buf + fp->pos, buf, len);
349         fp->pos += len;
350         return len;
351 }
352
353 static long save_seek(void *file, long offs, int whence)
354 {
355         struct save_fp *fp = file;
356         if (fp == NULL)
357                 return -1;
358
359         switch (whence) {
360         case SEEK_CUR:
361                 fp->pos += offs;
362                 return fp->pos;
363         case SEEK_SET:
364                 fp->pos = offs;
365                 return fp->pos;
366         default:
367                 return -1;
368         }
369 }
370
371 static void save_close(void *file)
372 {
373         struct save_fp *fp = file;
374         size_t r_size = retro_serialize_size();
375         if (fp == NULL)
376                 return;
377
378         if (fp->pos > r_size)
379                 SysPrintf("ERROR: save buffer overflow detected\n");
380         else if (fp->is_write && fp->pos < r_size)
381                 // make sure we don't save trash in leftover space
382                 memset(fp->buf + fp->pos, 0, r_size - fp->pos);
383         free(fp);
384 }
385
386 bool retro_serialize(void *data, size_t size)
387
388         int ret = SaveState(data);
389         return ret == 0 ? true : false;
390 }
391
392 bool retro_unserialize(const void *data, size_t size)
393 {
394         int ret = LoadState(data);
395         return ret == 0 ? true : false;
396 }
397
398 /* cheats */
399 void retro_cheat_reset(void)
400 {
401         ClearAllCheats();
402 }
403
404 void retro_cheat_set(unsigned index, bool enabled, const char *code)
405 {
406         char buf[256];
407         int ret;
408
409         // cheat funcs are destructive, need a copy..
410         strncpy(buf, code, sizeof(buf));
411         buf[sizeof(buf) - 1] = 0;
412
413         if (index < NumCheats)
414                 ret = EditCheat(index, "", buf);
415         else
416                 ret = AddCheat("", buf);
417
418         if (ret != 0)
419                 SysPrintf("Failed to set cheat %#u\n", index);
420         else if (index < NumCheats)
421                 Cheats[index].Enabled = enabled;
422 }
423
424 /* multidisk support */
425 static bool disk_ejected;
426 static unsigned int disk_current_index;
427 static unsigned int disk_count;
428 static struct disks_state {
429         char *fname;
430         int internal_index; // for multidisk eboots
431 } disks[8];
432
433 static bool disk_set_eject_state(bool ejected)
434 {
435         // weird PCSX API..
436         SetCdOpenCaseTime(ejected ? -1 : (time(NULL) + 2));
437         LidInterrupt();
438
439         disk_ejected = ejected;
440         return true;
441 }
442
443 static bool disk_get_eject_state(void)
444 {
445         /* can't be controlled by emulated software */
446         return disk_ejected;
447 }
448
449 static unsigned int disk_get_image_index(void)
450 {
451         return disk_current_index;
452 }
453
454 static bool disk_set_image_index(unsigned int index)
455 {
456         if (index >= sizeof(disks) / sizeof(disks[0]))
457                 return false;
458
459         CdromId[0] = '\0';
460         CdromLabel[0] = '\0';
461
462         if (disks[index].fname == NULL) {
463                 SysPrintf("missing disk #%u\n", index);
464                 CDR_shutdown();
465
466                 // RetroArch specifies "no disk" with index == count,
467                 // so don't fail here..
468                 disk_current_index = index;
469                 return true;
470         }
471
472         SysPrintf("switching to disk %u: \"%s\" #%d\n", index,
473                 disks[index].fname, disks[index].internal_index);
474
475         cdrIsoMultidiskSelect = disks[index].internal_index;
476         set_cd_image(disks[index].fname);
477         if (ReloadCdromPlugin() < 0) {
478                 SysPrintf("failed to load cdr plugin\n");
479                 return false;
480         }
481         if (CDR_open() < 0) {
482                 SysPrintf("failed to open cdr plugin\n");
483                 return false;
484         }
485
486         if (!disk_ejected) {
487                 SetCdOpenCaseTime(time(NULL) + 2);
488                 LidInterrupt();
489         }
490
491         disk_current_index = index;
492         return true;
493 }
494
495 static unsigned int disk_get_num_images(void)
496 {
497         return disk_count;
498 }
499
500 static bool disk_replace_image_index(unsigned index,
501         const struct retro_game_info *info)
502 {
503         char *old_fname;
504         bool ret = true;
505
506         if (index >= sizeof(disks) / sizeof(disks[0]))
507                 return false;
508
509         old_fname = disks[index].fname;
510         disks[index].fname = NULL;
511         disks[index].internal_index = 0;
512
513         if (info != NULL) {
514                 disks[index].fname = strdup(info->path);
515                 if (index == disk_current_index)
516                         ret = disk_set_image_index(index);
517         }
518
519         if (old_fname != NULL)
520                 free(old_fname);
521
522         return ret;
523 }
524
525 static bool disk_add_image_index(void)
526 {
527         if (disk_count >= 8)
528                 return false;
529
530         disk_count++;
531         return true;
532 }
533
534 static struct retro_disk_control_callback disk_control = {
535         .set_eject_state = disk_set_eject_state,
536         .get_eject_state = disk_get_eject_state,
537         .get_image_index = disk_get_image_index,
538         .set_image_index = disk_set_image_index,
539         .get_num_images = disk_get_num_images,
540         .replace_image_index = disk_replace_image_index,
541         .add_image_index = disk_add_image_index,
542 };
543
544 // just in case, maybe a win-rt port in the future?
545 #ifdef _WIN32
546 #define SLASH '\\'
547 #else
548 #define SLASH '/'
549 #endif
550
551 static char base_dir[PATH_MAX];
552
553 static bool read_m3u(const char *file)
554 {
555         char line[PATH_MAX];
556         char name[PATH_MAX];
557         FILE *f = fopen(file, "r");
558         if (!f)
559                 return false;
560
561         while (fgets(line, sizeof(line), f) && disk_count < sizeof(disks) / sizeof(disks[0])) {
562                 if (line[0] == '#')
563                         continue;
564                 char *carrige_return = strchr(line, '\r');
565                 if (carrige_return)
566                         *carrige_return = '\0';
567                 char *newline = strchr(line, '\n');
568                 if (newline)
569                         *newline = '\0';
570
571                 if (line[0] != '\0')
572                 {
573                         snprintf(name, sizeof(name), "%s%c%s", base_dir, SLASH, line);
574                         disks[disk_count++].fname = strdup(name);
575                 }
576         }
577
578         fclose(f);
579         return (disk_count != 0);
580 }
581
582 static void extract_directory(char *buf, const char *path, size_t size)
583 {
584    char *base;
585    strncpy(buf, path, size - 1);
586    buf[size - 1] = '\0';
587
588    base = strrchr(buf, '/');
589    if (!base)
590       base = strrchr(buf, '\\');
591
592    if (base)
593       *base = '\0';
594    else
595    {
596       buf[0] = '.';
597       buf[1] = '\0';
598    }
599 }
600
601 #ifdef __QNX__
602 /* Blackberry QNX doesn't have strcasestr */
603
604 /*
605  * Find the first occurrence of find in s, ignore case.
606  */
607 char *
608 strcasestr(const char *s, const char*find)
609 {
610         char c, sc;
611         size_t len;
612
613         if ((c = *find++) != 0) {
614                 c = tolower((unsigned char)c);
615                 len = strlen(find);
616                 do {
617                         do {
618                                 if ((sc = *s++) == 0)
619                                         return (NULL);
620                         } while ((char)tolower((unsigned char)sc) != c);
621                 } while (strncasecmp(s, find, len) != 0);
622                 s--;
623         }
624         return ((char *)s);
625 }
626 #endif
627
628 bool retro_load_game(const struct retro_game_info *info)
629 {
630         size_t i;
631         bool is_m3u = (strcasestr(info->path, ".m3u") != NULL);
632
633 #ifdef FRONTEND_SUPPORTS_RGB565
634         enum retro_pixel_format fmt = RETRO_PIXEL_FORMAT_RGB565;
635         if (environ_cb(RETRO_ENVIRONMENT_SET_PIXEL_FORMAT, &fmt)) {
636                 SysPrintf("RGB565 supported, using it\n");
637         }
638 #endif
639
640         if (info == NULL || info->path == NULL) {
641                 SysPrintf("info->path required\n");
642                 return false;
643         }
644
645         if (plugins_opened) {
646                 ClosePlugins();
647                 plugins_opened = 0;
648         }
649
650         for (i = 0; i < sizeof(disks) / sizeof(disks[0]); i++) {
651                 if (disks[i].fname != NULL) {
652                         free(disks[i].fname);
653                         disks[i].fname = NULL;
654                 }
655                 disks[i].internal_index = 0;
656         }
657
658         disk_current_index = 0;
659         extract_directory(base_dir, info->path, sizeof(base_dir));
660
661         if (is_m3u) {
662                 if (!read_m3u(info->path)) {
663                         SysPrintf("failed to read m3u file\n");
664                         return false;
665                 }
666         } else {
667                 disk_count = 1;
668                 disks[0].fname = strdup(info->path);
669         }
670
671         set_cd_image(disks[0].fname);
672
673         /* have to reload after set_cd_image for correct cdr plugin */
674         if (LoadPlugins() == -1) {
675                 SysPrintf("failed to load plugins\n");
676                 return false;
677         }
678
679         plugins_opened = 1;
680         NetOpened = 0;
681
682         if (OpenPlugins() == -1) {
683                 SysPrintf("failed to open plugins\n");
684                 return false;
685         }
686
687         plugin_call_rearmed_cbs();
688         dfinput_activate();
689
690         Config.PsxAuto = 1;
691         if (CheckCdrom() == -1) {
692                 SysPrintf("unsupported/invalid CD image: %s\n", info->path);
693                 return false;
694         }
695
696         SysReset();
697
698         if (LoadCdrom() == -1) {
699                 SysPrintf("could not load CD-ROM!\n");
700                 return false;
701         }
702         emu_on_new_cd(0);
703
704         // multidisk images
705         if (!is_m3u) {
706                 disk_count = cdrIsoMultidiskCount < 8 ? cdrIsoMultidiskCount : 8;
707                 for (i = 1; i < sizeof(disks) / sizeof(disks[0]) && i < cdrIsoMultidiskCount; i++) {
708                         disks[i].fname = strdup(info->path);
709                         disks[i].internal_index = i;
710                 }
711         }
712
713         return true;
714 }
715
716 bool retro_load_game_special(unsigned game_type, const struct retro_game_info *info, size_t num_info)
717 {
718         return false;
719 }
720
721 void retro_unload_game(void) 
722 {
723 }
724
725 unsigned retro_get_region(void)
726 {
727         return is_pal_mode ? RETRO_REGION_PAL : RETRO_REGION_NTSC;
728 }
729
730 void *retro_get_memory_data(unsigned id)
731 {
732         if (id == RETRO_MEMORY_SAVE_RAM)
733                 return Mcd1Data;
734         else
735                 return NULL;
736 }
737
738 size_t retro_get_memory_size(unsigned id)
739 {
740         if (id == RETRO_MEMORY_SAVE_RAM)
741                 return MCD_SIZE;
742         else
743                 return 0;
744 }
745
746 void retro_reset(void)
747 {
748         SysReset();
749 }
750
751 static const unsigned short retro_psx_map[] = {
752         [RETRO_DEVICE_ID_JOYPAD_B]      = 1 << DKEY_CROSS,
753         [RETRO_DEVICE_ID_JOYPAD_Y]      = 1 << DKEY_SQUARE,
754         [RETRO_DEVICE_ID_JOYPAD_SELECT] = 1 << DKEY_SELECT,
755         [RETRO_DEVICE_ID_JOYPAD_START]  = 1 << DKEY_START,
756         [RETRO_DEVICE_ID_JOYPAD_UP]     = 1 << DKEY_UP,
757         [RETRO_DEVICE_ID_JOYPAD_DOWN]   = 1 << DKEY_DOWN,
758         [RETRO_DEVICE_ID_JOYPAD_LEFT]   = 1 << DKEY_LEFT,
759         [RETRO_DEVICE_ID_JOYPAD_RIGHT]  = 1 << DKEY_RIGHT,
760         [RETRO_DEVICE_ID_JOYPAD_A]      = 1 << DKEY_CIRCLE,
761         [RETRO_DEVICE_ID_JOYPAD_X]      = 1 << DKEY_TRIANGLE,
762         [RETRO_DEVICE_ID_JOYPAD_L]      = 1 << DKEY_L1,
763         [RETRO_DEVICE_ID_JOYPAD_R]      = 1 << DKEY_R1,
764         [RETRO_DEVICE_ID_JOYPAD_L2]     = 1 << DKEY_L2,
765         [RETRO_DEVICE_ID_JOYPAD_R2]     = 1 << DKEY_R2,
766         [RETRO_DEVICE_ID_JOYPAD_L3]     = 1 << DKEY_L3,
767         [RETRO_DEVICE_ID_JOYPAD_R3]     = 1 << DKEY_R3,
768 };
769 #define RETRO_PSX_MAP_LEN (sizeof(retro_psx_map) / sizeof(retro_psx_map[0]))
770
771 static void update_variables(bool in_flight)
772 {
773    struct retro_variable var;
774    
775    var.value = NULL;
776    var.key = "frameskip";
777
778    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
779       pl_rearmed_cbs.frameskip = atoi(var.value);
780
781    var.value = NULL;
782    var.key = "region";
783
784    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
785    {
786       Config.PsxAuto = 0;
787       if (strcmp(var.value, "Automatic") == 0)
788          Config.PsxAuto = 1;
789       else if (strcmp(var.value, "NTSC") == 0)
790          Config.PsxType = 0;
791       else if (strcmp(var.value, "PAL") == 0)
792          Config.PsxType = 1;
793    }
794
795    var.value = NULL;
796    var.key = "pad1type";
797
798    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
799    {
800       in_type1 = PSE_PAD_TYPE_STANDARD;
801       if (strcmp(var.value, "analog") == 0)
802          in_type1 = PSE_PAD_TYPE_ANALOGPAD;
803    }
804
805 #ifdef __ARM_NEON__
806    var.value = "NULL";
807    var.key = "neon_interlace_enable";
808
809    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
810    {
811       if (strcmp(var.value, "disabled") == 0)
812          pl_rearmed_cbs.gpu_neon.allow_interlace = 0;
813       else if (strcmp(var.value, "enabled") == 0)
814          pl_rearmed_cbs.gpu_neon.allow_interlace = 1;
815    }
816
817    var.value = NULL;
818    var.key = "neon_enhancement_enable";
819
820    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
821    {
822       if (strcmp(var.value, "disabled") == 0)
823          pl_rearmed_cbs.gpu_neon.enhancement_enable = 0;
824       else if (strcmp(var.value, "enabled") == 0)
825          pl_rearmed_cbs.gpu_neon.enhancement_enable = 1;
826    }
827
828    var.value = NULL;
829    var.key = "neon_enhancement_no_main";
830
831    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
832    {
833       if (strcmp(var.value, "disabled") == 0)
834          pl_rearmed_cbs.gpu_neon.enhancement_no_main = 0;
835       else if (strcmp(var.value, "enabled") == 0)
836          pl_rearmed_cbs.gpu_neon.enhancement_no_main = 1;
837    }
838 #endif
839
840    var.value = "NULL";
841    var.key = "pcsx_rearmed_duping_enable";
842
843    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
844    {
845       if (strcmp(var.value, "off") == 0)
846          duping_enable = false;
847       else if (strcmp(var.value, "on") == 0)
848          duping_enable = true;
849    }
850
851 #ifndef DRC_DISABLE
852    var.value = NULL;
853    var.key = "rearmed_drc";
854
855    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
856    {
857       R3000Acpu *prev_cpu = psxCpu;
858
859       if (strcmp(var.value, "disabled") == 0)
860          Config.Cpu = CPU_INTERPRETER;
861       else if (strcmp(var.value, "enabled") == 0)
862          Config.Cpu = CPU_DYNAREC;
863
864       psxCpu = (Config.Cpu == CPU_INTERPRETER) ? &psxInt : &psxRec;
865       if (psxCpu != prev_cpu) {
866          prev_cpu->Shutdown();
867          psxCpu->Init();
868          psxCpu->Reset(); // not really a reset..
869       }
870    }
871 #endif
872
873         if (in_flight) {
874                 // inform core things about possible config changes
875                 plugin_call_rearmed_cbs();
876
877                 if (GPU_open != NULL && GPU_close != NULL) {
878                         GPU_close();
879                         GPU_open(&gpuDisp, "PCSX", NULL);
880                 }
881
882                 dfinput_activate();
883         }
884 }
885
886 void retro_run(void) 
887 {
888         int i;
889
890         input_poll_cb();
891
892         bool updated = false;
893         if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE, &updated) && updated)
894                 update_variables(true);
895
896         in_keystate = 0;
897         for (i = 0; i < RETRO_PSX_MAP_LEN; i++)
898                 if (input_state_cb(1, RETRO_DEVICE_JOYPAD, 0, i))
899                         in_keystate |= retro_psx_map[i];
900         in_keystate <<= 16;
901         for (i = 0; i < RETRO_PSX_MAP_LEN; i++)
902                 if (input_state_cb(0, RETRO_DEVICE_JOYPAD, 0, i))
903                         in_keystate |= retro_psx_map[i];
904
905    if (in_type1 == PSE_PAD_TYPE_ANALOGPAD)
906    {
907       in_a1[0] = (input_state_cb(0, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_LEFT, RETRO_DEVICE_ID_ANALOG_X) / 256) + 128;
908       in_a1[1] = (input_state_cb(0, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_LEFT, RETRO_DEVICE_ID_ANALOG_Y) / 256) + 128;
909       in_a2[0] = (input_state_cb(0, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_RIGHT, RETRO_DEVICE_ID_ANALOG_X) / 256) + 128;
910       in_a2[1] = (input_state_cb(0, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_RIGHT, RETRO_DEVICE_ID_ANALOG_Y) / 256) + 128;
911    }
912
913         stop = 0;
914         psxCpu->Execute();
915
916         samples_to_send += is_pal_mode ? 44100 / 50 : 44100 / 60;
917
918         video_cb((vout_fb_dirty || !vout_can_dupe || !duping_enable) ? vout_buf : NULL,
919                 vout_width, vout_height, vout_width * 2);
920         vout_fb_dirty = 0;
921 }
922
923 static bool try_use_bios(const char *path)
924 {
925         FILE *f;
926         long size;
927         const char *name;
928
929         f = fopen(path, "rb");
930         if (f == NULL)
931                 return false;
932
933         fseek(f, 0, SEEK_END);
934         size = ftell(f);
935         fclose(f);
936
937         if (size != 512 * 1024)
938                 return false;
939
940         name = strrchr(path, SLASH);
941         if (name++ == NULL)
942                 name = path;
943         snprintf(Config.Bios, sizeof(Config.Bios), "%s", name);
944         return true;
945 }
946
947 #if 1
948 #include <sys/types.h>
949 #include <dirent.h>
950
951 static bool find_any_bios(const char *dirpath, char *path, size_t path_size)
952 {
953         DIR *dir;
954         struct dirent *ent;
955         bool ret = false;
956
957         dir = opendir(dirpath);
958         if (dir == NULL)
959                 return false;
960
961         while ((ent = readdir(dir))) {
962                 if (strncasecmp(ent->d_name, "scph", 4) != 0)
963                         continue;
964
965                 snprintf(path, path_size, "%s/%s", dirpath, ent->d_name);
966                 ret = try_use_bios(path);
967                 if (ret)
968                         break;
969         }
970         closedir(dir);
971         return ret;
972 }
973 #else
974 #define find_any_bios(...) false
975 #endif
976
977 static void check_system_specs(void)
978 {
979    unsigned level = 6;
980    environ_cb(RETRO_ENVIRONMENT_SET_PERFORMANCE_LEVEL, &level);
981 }
982
983 void retro_init(void)
984 {
985         const char *bios[] = { "scph1001", "scph5501", "scph7001" };
986         const char *dir;
987         char path[256];
988         int i, ret, level;
989         bool found_bios = false;
990
991         ret = emu_core_preinit();
992         ret |= emu_core_init();
993         if (ret != 0) {
994                 SysPrintf("PCSX init failed.\n");
995                 exit(1);
996         }
997
998 #if defined(_POSIX_C_SOURCE) && (_POSIX_C_SOURCE >= 200112L)
999         posix_memalign(&vout_buf, 16, VOUT_MAX_WIDTH * VOUT_MAX_HEIGHT * 2);
1000 #else
1001         vout_buf = malloc(VOUT_MAX_WIDTH * VOUT_MAX_HEIGHT * 2);
1002 #endif
1003
1004         if (environ_cb(RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY, &dir) && dir)
1005         {
1006                 snprintf(Config.BiosDir, sizeof(Config.BiosDir), "%s/", dir);
1007
1008                 for (i = 0; i < sizeof(bios) / sizeof(bios[0]); i++) {
1009                         snprintf(path, sizeof(path), "%s/%s.bin", dir, bios[i]);
1010                         found_bios = try_use_bios(path);
1011                         if (found_bios)
1012                                 break;
1013                 }
1014
1015                 if (!found_bios)
1016                         found_bios = find_any_bios(dir, path, sizeof(path));
1017         }
1018         if (found_bios) {
1019                 SysPrintf("found BIOS file: %s\n", Config.Bios);
1020         }
1021         else
1022         {
1023                 SysPrintf("no BIOS files found.\n");
1024                 struct retro_message msg = 
1025                 {
1026                         "no BIOS found, expect bugs!",
1027                         180
1028                 };
1029                 environ_cb(RETRO_ENVIRONMENT_SET_MESSAGE, (void*)&msg);
1030         }
1031
1032         level = 1;
1033         environ_cb(RETRO_ENVIRONMENT_SET_PERFORMANCE_LEVEL, &level);
1034
1035         environ_cb(RETRO_ENVIRONMENT_GET_CAN_DUPE, &vout_can_dupe);
1036         environ_cb(RETRO_ENVIRONMENT_SET_DISK_CONTROL_INTERFACE, &disk_control);
1037
1038         /* Set how much slower PSX CPU runs * 100 (so that 200 is 2 times)
1039          * we have to do this because cache misses and some IO penalties
1040          * are not emulated. Warning: changing this may break compatibility. */
1041 #ifdef __ARM_ARCH_7A__
1042         cycle_multiplier = 175;
1043 #else
1044         cycle_multiplier = 200;
1045 #endif
1046
1047         McdDisable[0] = 0;
1048         McdDisable[1] = 1;
1049         init_memcard(Mcd1Data);
1050
1051         SaveFuncs.open = save_open;
1052         SaveFuncs.read = save_read;
1053         SaveFuncs.write = save_write;
1054         SaveFuncs.seek = save_seek;
1055         SaveFuncs.close = save_close;
1056
1057         update_variables(false);
1058    check_system_specs();
1059 }
1060
1061 void retro_deinit(void)
1062 {
1063         SysClose();
1064         free(vout_buf);
1065         vout_buf = NULL;
1066 }