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