Merge pull request #321 from fpscan/master
[pcsx_rearmed.git] / frontend / libretro.c
1 /*
2  * (C) notaz, 2012,2014,2015
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 #ifdef __MACH__
14 #include <unistd.h>
15 #include <sys/syscall.h>
16 #endif
17
18 #include "../libpcsxcore/misc.h"
19 #include "../libpcsxcore/psxcounters.h"
20 #include "../libpcsxcore/psxmem_map.h"
21 #include "../libpcsxcore/new_dynarec/new_dynarec.h"
22 #include "../libpcsxcore/cdrom.h"
23 #include "../libpcsxcore/cdriso.h"
24 #include "../libpcsxcore/cheat.h"
25 #include "../libpcsxcore/r3000a.h"
26 #include "../plugins/dfsound/out.h"
27 #include "../plugins/dfsound/spu_config.h"
28 #include "../plugins/dfinput/externals.h"
29 #include "cspace.h"
30 #include "main.h"
31 #include "menu.h"
32 #include "plugin.h"
33 #include "plugin_lib.h"
34 #include "arm_features.h"
35 #include "revision.h"
36
37 #include <libretro.h>
38 #include "libretro_core_options.h"
39
40 #ifdef _3DS
41 #include "3ds/3ds_utils.h"
42 #endif
43
44 #define PORTS_NUMBER 8
45
46 #ifndef MIN
47 #define MIN(a, b) ((a) < (b) ? (a) : (b))
48 #endif
49
50 #ifndef MAX
51 #define MAX(a, b) ((a) > (b) ? (a) : (b))
52 #endif
53
54 #define ISHEXDEC ((buf[cursor]>='0') && (buf[cursor]<='9')) || ((buf[cursor]>='a') && (buf[cursor]<='f')) || ((buf[cursor]>='A') && (buf[cursor]<='F'))
55
56 #define INTERNAL_FPS_SAMPLE_PERIOD 64
57
58 //hack to prevent retroarch freezing when reseting in the menu but not while running with the hot key
59 static int rebootemu = 0;
60
61 static retro_video_refresh_t video_cb;
62 static retro_input_poll_t input_poll_cb;
63 static retro_input_state_t input_state_cb;
64 static retro_environment_t environ_cb;
65 static retro_audio_sample_batch_t audio_batch_cb;
66 static retro_set_rumble_state_t rumble_cb;
67 static struct retro_log_callback logging;
68 static retro_log_printf_t log_cb;
69
70 static void *vout_buf;
71 static void * vout_buf_ptr;
72 static int vout_width, vout_height;
73 static int vout_doffs_old, vout_fb_dirty;
74 static bool vout_can_dupe;
75 static bool duping_enable;
76 static bool found_bios;
77 static bool display_internal_fps = false;
78 static unsigned frame_count = 0;
79 static bool libretro_supports_bitmasks = false;
80 static int show_advanced_gpu_peops_settings = -1;
81
82 static unsigned previous_width = 0;
83 static unsigned previous_height = 0;
84
85 static int plugins_opened;
86 static int is_pal_mode;
87
88 /* memory card data */
89 extern char Mcd1Data[MCD_SIZE];
90 extern char Mcd2Data[MCD_SIZE];
91 extern char McdDisable[2];
92
93 /* PCSX ReARMed core calls and stuff */
94 int in_type[8] =  { PSE_PAD_TYPE_NONE, PSE_PAD_TYPE_NONE,
95                   PSE_PAD_TYPE_NONE, PSE_PAD_TYPE_NONE,
96                   PSE_PAD_TYPE_NONE, PSE_PAD_TYPE_NONE,
97                   PSE_PAD_TYPE_NONE, PSE_PAD_TYPE_NONE };
98 int in_analog_left[8][2] = {{ 127, 127 },{ 127, 127 },{ 127, 127 },{ 127, 127 },{ 127, 127 },{ 127, 127 },{ 127, 127 },{ 127, 127 }};
99 int in_analog_right[8][2] = {{ 127, 127 },{ 127, 127 },{ 127, 127 },{ 127, 127 },{ 127, 127 },{ 127, 127 },{ 127, 127 },{ 127, 127 }};
100 unsigned short in_keystate[PORTS_NUMBER];
101 int multitap1 = 0;
102 int multitap2 = 0;
103 int in_enable_vibration = 1;
104
105 // NegCon adjustment parameters
106 // > The NegCon 'twist' action is somewhat awkward when mapped
107 //   to a standard analog stick -> user should be able to tweak
108 //   response/deadzone for comfort
109 // > When response is linear, 'additional' deadzone (set here)
110 //   may be left at zero, since this is normally handled via in-game
111 //   options menus
112 // > When response is non-linear, deadzone should be set to match the
113 //   controller being used (otherwise precision may be lost)
114 // > negcon_linearity:
115 //   - 1: Response is linear - recommended when using racing wheel
116 //        peripherals, not recommended for standard gamepads
117 //   - 2: Response is quadratic - optimal setting for gamepads
118 //   - 3: Response is cubic - enables precise fine control, but
119 //        difficult to use...
120 #define NEGCON_RANGE 0x7FFF
121 static int negcon_deadzone = 0;
122 static int negcon_linearity = 1;
123
124 /* PSX max resolution is 640x512, but with enhancement it's 1024x512 */
125 #define VOUT_MAX_WIDTH 1024
126 #define VOUT_MAX_HEIGHT 512
127
128 //Dummy functions
129 bool retro_load_game_special(unsigned game_type, const struct retro_game_info *info, size_t num_info){return false;}
130 void retro_unload_game(void){}
131 static int vout_open(void){return 0;}
132 static void vout_close(void){}
133 static int snd_init(void){return 0;}
134 static void snd_finish(void){}
135 static int snd_busy(void){return 0;}
136
137 static void init_memcard(char *mcd_data)
138 {
139         unsigned off = 0;
140         unsigned i;
141
142         memset(mcd_data, 0, MCD_SIZE);
143
144         mcd_data[off++] = 'M';
145         mcd_data[off++] = 'C';
146         off += 0x7d;
147         mcd_data[off++] = 0x0e;
148
149         for (i = 0; i < 15; i++) {
150                 mcd_data[off++] = 0xa0;
151                 off += 0x07;
152                 mcd_data[off++] = 0xff;
153                 mcd_data[off++] = 0xff;
154                 off += 0x75;
155                 mcd_data[off++] = 0xa0;
156         }
157
158         for (i = 0; i < 20; i++) {
159                 mcd_data[off++] = 0xff;
160                 mcd_data[off++] = 0xff;
161                 mcd_data[off++] = 0xff;
162                 mcd_data[off++] = 0xff;
163                 off += 0x04;
164                 mcd_data[off++] = 0xff;
165                 mcd_data[off++] = 0xff;
166                 off += 0x76;
167         }
168 }
169
170 static void set_vout_fb()
171 {
172   struct retro_framebuffer fb = {0};
173
174   fb.width           = vout_width;
175   fb.height          = vout_height;
176   fb.access_flags    = RETRO_MEMORY_ACCESS_WRITE;
177
178   if (environ_cb(RETRO_ENVIRONMENT_GET_CURRENT_SOFTWARE_FRAMEBUFFER, &fb) && fb.format == RETRO_PIXEL_FORMAT_RGB565)
179      vout_buf_ptr = (uint16_t*)fb.data;
180   else
181      vout_buf_ptr = vout_buf;
182 }
183
184 static void vout_set_mode(int w, int h, int raw_w, int raw_h, int bpp)
185 {
186   vout_width = w;
187   vout_height = h;
188
189         if (previous_width != vout_width || previous_height != vout_height)
190         {
191                 previous_width = vout_width;
192                 previous_height = vout_height;
193
194         struct retro_system_av_info info;
195         retro_get_system_av_info(&info);
196         environ_cb(RETRO_ENVIRONMENT_SET_GEOMETRY, &info.geometry);
197         }
198
199   set_vout_fb();
200 }
201
202 #ifndef FRONTEND_SUPPORTS_RGB565
203 static void convert(void *buf, size_t bytes)
204 {
205         unsigned int i, v, *p = buf;
206
207         for (i = 0; i < bytes / 4; i++) {
208                 v = p[i];
209                 p[i] = (v & 0x001f001f) | ((v >> 1) & 0x7fe07fe0);
210         }
211 }
212 #endif
213
214 static void vout_flip(const void *vram, int stride, int bgr24, int w, int h)
215 {
216         unsigned short *dest = vout_buf_ptr;
217         const unsigned short *src = vram;
218         int dstride = vout_width, h1 = h;
219         int doffs;
220
221         if (vram == NULL) {
222                 // blanking
223                 memset(vout_buf_ptr, 0, dstride * h * 2);
224                 goto out;
225         }
226
227         doffs = (vout_height - h) * dstride;
228         doffs += (dstride - w) / 2 & ~1;
229         if (doffs != vout_doffs_old) {
230                 // clear borders
231                 memset(vout_buf_ptr, 0, dstride * h * 2);
232                 vout_doffs_old = doffs;
233         }
234         dest += doffs;
235
236         if (bgr24)
237         {
238                 // XXX: could we switch to RETRO_PIXEL_FORMAT_XRGB8888 here?
239                 for (; h1-- > 0; dest += dstride, src += stride)
240                 {
241                         bgr888_to_rgb565(dest, src, w * 3);
242                 }
243         }
244         else
245         {
246                 for (; h1-- > 0; dest += dstride, src += stride)
247                 {
248                         bgr555_to_rgb565(dest, src, w * 2);
249                 }
250         }
251
252 out:
253 #ifndef FRONTEND_SUPPORTS_RGB565
254         convert(vout_buf_ptr, vout_width * vout_height * 2);
255 #endif
256         vout_fb_dirty = 1;
257         pl_rearmed_cbs.flip_cnt++;
258 }
259
260 #ifdef _3DS
261 typedef struct
262 {
263    void* buffer;
264    uint32_t target_map;
265    size_t size;
266    enum psxMapTag tag;
267 }psx_map_t;
268
269 psx_map_t custom_psx_maps[] = {
270    {NULL, 0x13000000, 0x210000, MAP_TAG_RAM},   // 0x80000000
271    {NULL, 0x12800000, 0x010000, MAP_TAG_OTHER}, // 0x1f800000
272    {NULL, 0x12c00000, 0x080000, MAP_TAG_OTHER}, // 0x1fc00000
273    {NULL, 0x11000000, 0x800000, MAP_TAG_LUTS},  // 0x08000000
274    {NULL, 0x12000000, 0x200000, MAP_TAG_VRAM},  // 0x00000000
275 };
276
277 void* pl_3ds_mmap(unsigned long addr, size_t size, int is_fixed,
278         enum psxMapTag tag)
279 {
280    (void)is_fixed;
281    (void)addr;
282
283    if (__ctr_svchax)
284    {
285       psx_map_t* custom_map = custom_psx_maps;
286
287       for (; custom_map->size; custom_map++)
288       {
289          if ((custom_map->size == size) && (custom_map->tag == tag))
290          {
291             uint32_t ptr_aligned, tmp;
292
293             custom_map->buffer = malloc(size + 0x1000);
294             ptr_aligned = (((u32)custom_map->buffer) + 0xFFF) & ~0xFFF;
295
296             if(svcControlMemory(&tmp, (void*)custom_map->target_map, (void*)ptr_aligned, size, MEMOP_MAP, 0x3) < 0)
297             {
298                SysPrintf("could not map memory @0x%08X\n", custom_map->target_map);
299                exit(1);
300             }
301
302             return (void*)custom_map->target_map;
303          }
304       }
305    }
306
307    return malloc(size);
308 }
309
310 void pl_3ds_munmap(void *ptr, size_t size, enum psxMapTag tag)
311 {
312    (void)tag;
313
314    if (__ctr_svchax)
315    {
316       psx_map_t* custom_map = custom_psx_maps;
317
318       for (; custom_map->size; custom_map++)
319       {
320          if ((custom_map->target_map == (uint32_t)ptr))
321          {
322             uint32_t ptr_aligned, tmp;
323
324             ptr_aligned = (((u32)custom_map->buffer) + 0xFFF) & ~0xFFF;
325
326             svcControlMemory(&tmp, (void*)custom_map->target_map, (void*)ptr_aligned, size, MEMOP_UNMAP, 0x3);
327
328             free(custom_map->buffer);
329             custom_map->buffer = NULL;
330             return;
331          }
332       }
333    }
334
335    free(ptr);
336 }
337 #endif
338
339 #ifdef VITA
340 typedef struct
341 {
342    void* buffer;
343    uint32_t target_map;
344    size_t size;
345    enum psxMapTag tag;
346 }psx_map_t;
347
348 void* addr = NULL;
349
350 psx_map_t custom_psx_maps[] = {
351    {NULL, NULL, 0x210000, MAP_TAG_RAM},   // 0x80000000
352    {NULL, NULL, 0x010000, MAP_TAG_OTHER}, // 0x1f800000
353    {NULL, NULL, 0x080000, MAP_TAG_OTHER}, // 0x1fc00000
354    {NULL, NULL, 0x800000, MAP_TAG_LUTS},  // 0x08000000
355    {NULL, NULL, 0x200000, MAP_TAG_VRAM},  // 0x00000000
356 };
357
358 int init_vita_mmap(){
359   int n;
360   void * tmpaddr;
361   addr = malloc(64*1024*1024);
362   if(addr==NULL)
363     return -1;
364   tmpaddr = ((u32)(addr+0xFFFFFF))&~0xFFFFFF;
365   custom_psx_maps[0].buffer=tmpaddr+0x2000000;
366   custom_psx_maps[1].buffer=tmpaddr+0x1800000;
367   custom_psx_maps[2].buffer=tmpaddr+0x1c00000;
368   custom_psx_maps[3].buffer=tmpaddr+0x0000000;
369   custom_psx_maps[4].buffer=tmpaddr+0x1000000;
370 #if 0
371   for(n = 0; n < 5; n++){
372     sceClibPrintf("addr reserved %x\n",custom_psx_maps[n].buffer);
373   }
374 #endif
375   return 0;
376 }
377
378 void deinit_vita_mmap(){
379   free(addr);
380 }
381
382 void* pl_vita_mmap(unsigned long addr, size_t size, int is_fixed,
383         enum psxMapTag tag)
384 {
385    (void)is_fixed;
386    (void)addr;
387
388
389     psx_map_t* custom_map = custom_psx_maps;
390
391     for (; custom_map->size; custom_map++)
392     {
393        if ((custom_map->size == size) && (custom_map->tag == tag))
394        {
395           return custom_map->buffer;
396        }
397     }
398
399
400    return malloc(size);
401 }
402
403 void pl_vita_munmap(void *ptr, size_t size, enum psxMapTag tag)
404 {
405    (void)tag;
406
407    psx_map_t* custom_map = custom_psx_maps;
408
409   for (; custom_map->size; custom_map++)
410   {
411      if ((custom_map->buffer == ptr))
412      {
413         return;
414      }
415   }
416
417    free(ptr);
418 }
419 #endif
420
421 static void *pl_mmap(unsigned int size)
422 {
423         return psxMap(0, size, 0, MAP_TAG_VRAM);
424 }
425
426 static void pl_munmap(void *ptr, unsigned int size)
427 {
428         psxUnmap(ptr, size, MAP_TAG_VRAM);
429 }
430
431 struct rearmed_cbs pl_rearmed_cbs = {
432         .pl_vout_open = vout_open,
433         .pl_vout_set_mode = vout_set_mode,
434         .pl_vout_flip = vout_flip,
435         .pl_vout_close = vout_close,
436         .mmap = pl_mmap,
437         .munmap = pl_munmap,
438         /* from psxcounters */
439         .gpu_hcnt = &hSyncCount,
440         .gpu_frame_count = &frame_counter,
441 };
442
443 void pl_frame_limit(void)
444 {
445         /* called once per frame, make psxCpu->Execute() above return */
446         stop = 1;
447 }
448
449 void pl_timing_prepare(int is_pal)
450 {
451         is_pal_mode = is_pal;
452 }
453
454 void plat_trigger_vibrate(int pad, int low, int high)
455 {
456         if (!rumble_cb)
457                 return;
458
459         if (in_enable_vibration)
460         {
461                 rumble_cb(pad, RETRO_RUMBLE_STRONG, high << 8);
462                 rumble_cb(pad, RETRO_RUMBLE_WEAK, low ? 0xffff : 0x0);
463     }
464 }
465
466 void pl_update_gun(int *xn, int *yn, int *xres, int *yres, int *in)
467 {
468 }
469
470 /* sound calls */
471 static void snd_feed(void *buf, int bytes)
472 {
473         if (audio_batch_cb != NULL)
474                 audio_batch_cb(buf, bytes / 4);
475 }
476
477 void out_register_libretro(struct out_driver *drv)
478 {
479         drv->name = "libretro";
480         drv->init = snd_init;
481         drv->finish = snd_finish;
482         drv->busy = snd_busy;
483         drv->feed = snd_feed;
484 }
485
486 /* libretro */
487 void retro_set_environment(retro_environment_t cb)
488 {
489    environ_cb = cb;
490
491    if (cb(RETRO_ENVIRONMENT_GET_LOG_INTERFACE, &logging))
492       log_cb = logging.log;
493
494    libretro_set_core_options(environ_cb);
495 }
496
497 void retro_set_video_refresh(retro_video_refresh_t cb) { video_cb = cb; }
498 void retro_set_audio_sample(retro_audio_sample_t cb) { (void)cb; }
499 void retro_set_audio_sample_batch(retro_audio_sample_batch_t cb) { audio_batch_cb = cb; }
500 void retro_set_input_poll(retro_input_poll_t cb) { input_poll_cb = cb; }
501 void retro_set_input_state(retro_input_state_t cb) { input_state_cb = cb; }
502
503 unsigned retro_api_version(void)
504 {
505         return RETRO_API_VERSION;
506 }
507
508 static int controller_port_variable(unsigned port, struct retro_variable *var)
509 {
510         if (port >= PORTS_NUMBER)
511                 return 0;
512
513         if (!environ_cb)
514                 return 0;
515
516         var->value = NULL;
517         switch (port) {
518         case 0:
519                 var->key = "pcsx_rearmed_pad1type";
520                 break;
521         case 1:
522                 var->key = "pcsx_rearmed_pad2type";
523                 break;
524         case 2:
525                 var->key = "pcsx_rearmed_pad3type";
526                 break;
527         case 3:
528                 var->key = "pcsx_rearmed_pad4type";
529                 break;
530         case 4:
531                 var->key = "pcsx_rearmed_pad5type";
532                 break;
533         case 5:
534                 var->key = "pcsx_rearmed_pad6type";
535                 break;
536         case 6:
537                 var->key = "pcsx_rearmed_pad7type";
538                 break;
539         case 7:
540                 var->key = "pcsx_rearmed_pad8type";
541                 break;
542         }
543
544         return environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, var) || var->value;
545 }
546
547 static void update_controller_port_variable(unsigned port)
548 {
549         if (port >= PORTS_NUMBER)
550                 return;
551
552         struct retro_variable var;
553
554         if (controller_port_variable(port, &var))
555         {
556                 if (strcmp(var.value, "standard") == 0)
557                         in_type[port] = PSE_PAD_TYPE_STANDARD;
558                 else if (strcmp(var.value, "analog") == 0)
559                         in_type[port] = PSE_PAD_TYPE_ANALOGJOY;
560                 else if (strcmp(var.value, "dualshock") == 0)
561                         in_type[port] = PSE_PAD_TYPE_ANALOGPAD;
562                 else if (strcmp(var.value, "negcon") == 0)
563                         in_type[port] = PSE_PAD_TYPE_NEGCON;
564                 else if (strcmp(var.value, "none") == 0)
565                         in_type[port] = PSE_PAD_TYPE_NONE;
566                 // else 'default' case, do nothing
567         }
568 }
569
570 static void update_controller_port_device(unsigned port, unsigned device)
571 {
572         if (port >= PORTS_NUMBER)
573                 return;
574
575         struct retro_variable var;
576
577         if (!controller_port_variable(port, &var))
578                 return;
579
580         if (strcmp(var.value, "default") != 0)
581                 return;
582
583         switch (device)
584         {
585         case RETRO_DEVICE_JOYPAD:
586                 in_type[port] = PSE_PAD_TYPE_STANDARD;
587                 break;
588         case RETRO_DEVICE_ANALOG:
589                 in_type[port] = PSE_PAD_TYPE_ANALOGPAD;
590                 break;
591         case RETRO_DEVICE_MOUSE:
592                 in_type[port] = PSE_PAD_TYPE_MOUSE;
593                 break;
594         case RETRO_DEVICE_LIGHTGUN:
595                 in_type[port] = PSE_PAD_TYPE_GUN;
596                 break;
597         case RETRO_DEVICE_NONE:
598         default:
599                 in_type[port] = PSE_PAD_TYPE_NONE;
600         }
601 }
602
603 static void update_multitap()
604 {
605         struct retro_variable var;
606         int auto_case, port;
607
608         var.value = NULL;
609         var.key = "pcsx_rearmed_multitap1";
610         auto_case = 0;
611         if (environ_cb && (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value))
612         {
613                 if (strcmp(var.value, "enabled") == 0)
614                         multitap1 = 1;
615                 else if (strcmp(var.value, "disabled") == 0)
616                         multitap1 = 0;
617                 else // 'auto' case
618                         auto_case = 1;
619         }
620         else
621                 auto_case = 1;
622
623         if (auto_case)
624         {
625                 // If a gamepad is plugged after port 2, we need a first multitap.
626                 multitap1 = 0;
627                 for (port = 2; port < PORTS_NUMBER; port++)
628                         multitap1 |= in_type[port] != PSE_PAD_TYPE_NONE;
629         }
630
631         var.value = NULL;
632         var.key = "pcsx_rearmed_multitap2";
633         auto_case = 0;
634         if (environ_cb && (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value))
635         {
636                 if (strcmp(var.value, "enabled") == 0)
637                         multitap2 = 1;
638                 else if (strcmp(var.value, "disabled") == 0)
639                         multitap2 = 0;
640                 else // 'auto' case
641                         auto_case = 1;
642         }
643         else
644                 auto_case = 1;
645
646         if (auto_case)
647         {
648                 // If a gamepad is plugged after port 4, we need a second multitap.
649                 multitap2 = 0;
650                 for (port = 4; port < PORTS_NUMBER; port++)
651                         multitap2 |= in_type[port] != PSE_PAD_TYPE_NONE;
652         }
653 }
654
655 void retro_set_controller_port_device(unsigned port, unsigned device)
656 {
657         SysPrintf("port %u  device %u",port,device);
658
659         if (port >= PORTS_NUMBER)
660                 return;
661
662         update_controller_port_device(port, device);
663         update_multitap();
664 }
665
666 void retro_get_system_info(struct retro_system_info *info)
667 {
668         memset(info, 0, sizeof(*info));
669         info->library_name = "PCSX-ReARMed";
670 #ifndef GIT_VERSION
671 #define GIT_VERSION ""
672 #endif
673         info->library_version = "r22" GIT_VERSION;
674         info->valid_extensions = "bin|cue|img|mdf|pbp|toc|cbn|m3u|chd";
675         info->need_fullpath = true;
676 }
677
678 void retro_get_system_av_info(struct retro_system_av_info *info)
679 {
680
681         unsigned geom_height = vout_height > 0 ? vout_height : 240;
682         unsigned geom_width = vout_width > 0 ? vout_width : 320;
683
684         memset(info, 0, sizeof(*info));
685         info->timing.fps            = is_pal_mode ? 50 : 60;
686         info->timing.sample_rate    = 44100;
687         info->geometry.base_width   = geom_width;
688         info->geometry.base_height  = geom_height;
689         info->geometry.max_width    = VOUT_MAX_WIDTH;
690         info->geometry.max_height   = VOUT_MAX_HEIGHT;
691         info->geometry.aspect_ratio = 4.0 / 3.0;
692 }
693
694 /* savestates */
695 size_t retro_serialize_size(void)
696 {
697         // it's currently 4380651-4397047 bytes,
698         // but have some reserved for future
699         return 0x440000;
700 }
701
702 struct save_fp {
703         char *buf;
704         size_t pos;
705         int is_write;
706 };
707
708 static void *save_open(const char *name, const char *mode)
709 {
710         struct save_fp *fp;
711
712         if (name == NULL || mode == NULL)
713                 return NULL;
714
715         fp = malloc(sizeof(*fp));
716         if (fp == NULL)
717                 return NULL;
718
719         fp->buf = (char *)name;
720         fp->pos = 0;
721         fp->is_write = (mode[0] == 'w' || mode[1] == 'w');
722
723         return fp;
724 }
725
726 static int save_read(void *file, void *buf, u32 len)
727 {
728         struct save_fp *fp = file;
729         if (fp == NULL || buf == NULL)
730                 return -1;
731
732         memcpy(buf, fp->buf + fp->pos, len);
733         fp->pos += len;
734         return len;
735 }
736
737 static int save_write(void *file, const void *buf, u32 len)
738 {
739         struct save_fp *fp = file;
740         if (fp == NULL || buf == NULL)
741                 return -1;
742
743         memcpy(fp->buf + fp->pos, buf, len);
744         fp->pos += len;
745         return len;
746 }
747
748 static long save_seek(void *file, long offs, int whence)
749 {
750         struct save_fp *fp = file;
751         if (fp == NULL)
752                 return -1;
753
754         switch (whence) {
755         case SEEK_CUR:
756                 fp->pos += offs;
757                 return fp->pos;
758         case SEEK_SET:
759                 fp->pos = offs;
760                 return fp->pos;
761         default:
762                 return -1;
763         }
764 }
765
766 static void save_close(void *file)
767 {
768         struct save_fp *fp = file;
769         size_t r_size = retro_serialize_size();
770         if (fp == NULL)
771                 return;
772
773         if (fp->pos > r_size)
774                 SysPrintf("ERROR: save buffer overflow detected\n");
775         else if (fp->is_write && fp->pos < r_size)
776                 // make sure we don't save trash in leftover space
777                 memset(fp->buf + fp->pos, 0, r_size - fp->pos);
778         free(fp);
779 }
780
781 bool retro_serialize(void *data, size_t size)
782 {
783         int ret = SaveState(data);
784         return ret == 0 ? true : false;
785 }
786
787 bool retro_unserialize(const void *data, size_t size)
788 {
789         int ret = LoadState(data);
790         return ret == 0 ? true : false;
791 }
792
793 /* cheats */
794 void retro_cheat_reset(void)
795 {
796         ClearAllCheats();
797 }
798
799 void retro_cheat_set(unsigned index, bool enabled, const char *code)
800 {
801         char buf[256];
802         int ret;
803
804         // cheat funcs are destructive, need a copy..
805         strncpy(buf, code, sizeof(buf));
806         buf[sizeof(buf) - 1] = 0;
807
808         //Prepare buffered cheat for PCSX's AddCheat fucntion.
809         int cursor=0;
810         int nonhexdec=0;
811         while (buf[cursor]){
812                 if (!(ISHEXDEC)){
813                         if (++nonhexdec%2){
814                                 buf[cursor]=' ';
815                         } else {
816                                 buf[cursor]='\n';
817                         }
818                 }
819                 cursor++;
820         }
821
822
823         if (index < NumCheats)
824                 ret = EditCheat(index, "", buf);
825         else
826                 ret = AddCheat("", buf);
827
828         if (ret != 0)
829                 SysPrintf("Failed to set cheat %#u\n", index);
830         else if (index < NumCheats)
831                 Cheats[index].Enabled = enabled;
832 }
833
834 /* multidisk support */
835 static bool disk_ejected;
836 static unsigned int disk_current_index;
837 static unsigned int disk_count;
838 static struct disks_state {
839         char *fname;
840         int internal_index; // for multidisk eboots
841 } disks[8];
842
843 static bool disk_set_eject_state(bool ejected)
844 {
845         // weird PCSX API..
846         SetCdOpenCaseTime(ejected ? -1 : (time(NULL) + 2));
847         LidInterrupt();
848
849         disk_ejected = ejected;
850         return true;
851 }
852
853 static bool disk_get_eject_state(void)
854 {
855         /* can't be controlled by emulated software */
856         return disk_ejected;
857 }
858
859 static unsigned int disk_get_image_index(void)
860 {
861         return disk_current_index;
862 }
863
864 static bool disk_set_image_index(unsigned int index)
865 {
866         if (index >= sizeof(disks) / sizeof(disks[0]))
867                 return false;
868
869         CdromId[0] = '\0';
870         CdromLabel[0] = '\0';
871
872         if (disks[index].fname == NULL) {
873                 SysPrintf("missing disk #%u\n", index);
874                 CDR_shutdown();
875
876                 // RetroArch specifies "no disk" with index == count,
877                 // so don't fail here..
878                 disk_current_index = index;
879                 return true;
880         }
881
882         SysPrintf("switching to disk %u: \"%s\" #%d\n", index,
883                 disks[index].fname, disks[index].internal_index);
884
885         cdrIsoMultidiskSelect = disks[index].internal_index;
886         set_cd_image(disks[index].fname);
887         if (ReloadCdromPlugin() < 0) {
888                 SysPrintf("failed to load cdr plugin\n");
889                 return false;
890         }
891         if (CDR_open() < 0) {
892                 SysPrintf("failed to open cdr plugin\n");
893                 return false;
894         }
895
896         if (!disk_ejected) {
897                 SetCdOpenCaseTime(time(NULL) + 2);
898                 LidInterrupt();
899         }
900
901         disk_current_index = index;
902         return true;
903 }
904
905 static unsigned int disk_get_num_images(void)
906 {
907         return disk_count;
908 }
909
910 static bool disk_replace_image_index(unsigned index,
911         const struct retro_game_info *info)
912 {
913         char *old_fname;
914         bool ret = true;
915
916         if (index >= sizeof(disks) / sizeof(disks[0]))
917                 return false;
918
919         old_fname = disks[index].fname;
920         disks[index].fname = NULL;
921         disks[index].internal_index = 0;
922
923         if (info != NULL) {
924                 disks[index].fname = strdup(info->path);
925                 if (index == disk_current_index)
926                         ret = disk_set_image_index(index);
927         }
928
929         if (old_fname != NULL)
930                 free(old_fname);
931
932         return ret;
933 }
934
935 static bool disk_add_image_index(void)
936 {
937         if (disk_count >= 8)
938                 return false;
939
940         disk_count++;
941         return true;
942 }
943
944 static struct retro_disk_control_callback disk_control = {
945         .set_eject_state = disk_set_eject_state,
946         .get_eject_state = disk_get_eject_state,
947         .get_image_index = disk_get_image_index,
948         .set_image_index = disk_set_image_index,
949         .get_num_images = disk_get_num_images,
950         .replace_image_index = disk_replace_image_index,
951         .add_image_index = disk_add_image_index,
952 };
953
954 // just in case, maybe a win-rt port in the future?
955 #ifdef _WIN32
956 #define SLASH '\\'
957 #else
958 #define SLASH '/'
959 #endif
960
961 #ifndef PATH_MAX
962 #define PATH_MAX  4096
963 #endif
964
965 static char base_dir[PATH_MAX];
966
967 static bool read_m3u(const char *file)
968 {
969         char line[PATH_MAX];
970         char name[PATH_MAX];
971         FILE *f = fopen(file, "r");
972         if (!f)
973                 return false;
974
975         while (fgets(line, sizeof(line), f) && disk_count < sizeof(disks) / sizeof(disks[0])) {
976                 if (line[0] == '#')
977                         continue;
978                 char *carrige_return = strchr(line, '\r');
979                 if (carrige_return)
980                         *carrige_return = '\0';
981                 char *newline = strchr(line, '\n');
982                 if (newline)
983                         *newline = '\0';
984
985                 if (line[0] != '\0')
986                 {
987                         snprintf(name, sizeof(name), "%s%c%s", base_dir, SLASH, line);
988                         disks[disk_count++].fname = strdup(name);
989                 }
990         }
991
992         fclose(f);
993         return (disk_count != 0);
994 }
995
996 static void extract_directory(char *buf, const char *path, size_t size)
997 {
998    char *base;
999    strncpy(buf, path, size - 1);
1000    buf[size - 1] = '\0';
1001
1002    base = strrchr(buf, '/');
1003    if (!base)
1004       base = strrchr(buf, '\\');
1005
1006    if (base)
1007       *base = '\0';
1008    else
1009    {
1010       buf[0] = '.';
1011       buf[1] = '\0';
1012    }
1013 }
1014
1015 #if defined(__QNX__) || defined(_WIN32)
1016 /* Blackberry QNX doesn't have strcasestr */
1017
1018 /*
1019  * Find the first occurrence of find in s, ignore case.
1020  */
1021 char *
1022 strcasestr(const char *s, const char*find)
1023 {
1024         char c, sc;
1025         size_t len;
1026
1027         if ((c = *find++) != 0) {
1028                 c = tolower((unsigned char)c);
1029                 len = strlen(find);
1030                 do {
1031                         do {
1032                                 if ((sc = *s++) == 0)
1033                                         return (NULL);
1034                         } while ((char)tolower((unsigned char)sc) != c);
1035                 } while (strncasecmp(s, find, len) != 0);
1036                 s--;
1037         }
1038         return ((char *)s);
1039 }
1040 #endif
1041
1042 bool retro_load_game(const struct retro_game_info *info)
1043 {
1044         size_t i;
1045         bool is_m3u = (strcasestr(info->path, ".m3u") != NULL);
1046
1047    struct retro_input_descriptor desc[] = {
1048       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT,  "D-Pad Left" },
1049       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP,    "D-Pad Up" },
1050       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN,  "D-Pad Down" },
1051       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT, "D-Pad Right" },
1052       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B,     "Cross" },
1053       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A,     "Circle" },
1054       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_X,     "Triangle" },
1055       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_Y,     "Square" },
1056       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L,     "L1" },
1057       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L2,    "L2" },
1058       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L3,    "L3" },
1059       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R,     "R1" },
1060       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R2,    "R2" },
1061       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R3,    "R3" },
1062       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_SELECT,    "Select" },
1063       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START,    "Start" },
1064       { 0, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_LEFT, RETRO_DEVICE_ID_ANALOG_X, "Left Analog X" },
1065       { 0, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_LEFT, RETRO_DEVICE_ID_ANALOG_Y, "Left Analog Y" },
1066       { 0, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_RIGHT, RETRO_DEVICE_ID_ANALOG_X, "Right Analog X" },
1067       { 0, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_RIGHT, RETRO_DEVICE_ID_ANALOG_Y, "Right Analog Y" },
1068
1069
1070       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT,  "D-Pad Left" },
1071       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP,    "D-Pad Up" },
1072       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN,  "D-Pad Down" },
1073       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT, "D-Pad Right" },
1074       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B,     "Cross" },
1075       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A,     "Circle" },
1076       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_X,     "Triangle" },
1077       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_Y,     "Square" },
1078       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L,     "L1" },
1079       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L2,    "L2" },
1080       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L3,    "L3" },
1081       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R,     "R1" },
1082       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R2,    "R2" },
1083       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R3,    "R3" },
1084       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_SELECT,    "Select" },
1085       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START,    "Start" },
1086       { 1, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_LEFT, RETRO_DEVICE_ID_ANALOG_X, "Left Analog X" },
1087       { 1, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_LEFT, RETRO_DEVICE_ID_ANALOG_Y, "Left Analog Y" },
1088       { 1, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_RIGHT, RETRO_DEVICE_ID_ANALOG_X, "Right Analog X" },
1089       { 1, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_RIGHT, RETRO_DEVICE_ID_ANALOG_Y, "Right Analog Y" },
1090
1091       { 2, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT,  "D-Pad Left" },
1092       { 2, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP,    "D-Pad Up" },
1093       { 2, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN,  "D-Pad Down" },
1094       { 2, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT, "D-Pad Right" },
1095       { 2, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B,     "Cross" },
1096       { 2, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A,     "Circle" },
1097       { 2, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_X,     "Triangle" },
1098       { 2, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_Y,     "Square" },
1099       { 2, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L,     "L1" },
1100       { 2, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L2,    "L2" },
1101       { 2, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L3,    "L3" },
1102       { 2, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R,     "R1" },
1103       { 2, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R2,    "R2" },
1104       { 2, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R3,    "R3" },
1105       { 2, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_SELECT,    "Select" },
1106       { 2, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START,    "Start" },
1107       { 2, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_LEFT, RETRO_DEVICE_ID_ANALOG_X, "Left Analog X" },
1108       { 2, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_LEFT, RETRO_DEVICE_ID_ANALOG_Y, "Left Analog Y" },
1109       { 2, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_RIGHT, RETRO_DEVICE_ID_ANALOG_X, "Right Analog X" },
1110       { 2, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_RIGHT, RETRO_DEVICE_ID_ANALOG_Y, "Right Analog Y" },
1111
1112       { 3, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT,  "D-Pad Left" },
1113       { 3, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP,    "D-Pad Up" },
1114       { 3, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN,  "D-Pad Down" },
1115       { 3, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT, "D-Pad Right" },
1116       { 3, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B,     "Cross" },
1117       { 3, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A,     "Circle" },
1118       { 3, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_X,     "Triangle" },
1119       { 3, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_Y,     "Square" },
1120       { 3, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L,     "L1" },
1121       { 3, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L2,    "L2" },
1122       { 3, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L3,    "L3" },
1123       { 3, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R,     "R1" },
1124       { 3, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R2,    "R2" },
1125       { 3, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R3,    "R3" },
1126       { 3, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_SELECT,    "Select" },
1127       { 3, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START,    "Start" },
1128       { 3, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_LEFT, RETRO_DEVICE_ID_ANALOG_X, "Left Analog X" },
1129       { 3, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_LEFT, RETRO_DEVICE_ID_ANALOG_Y, "Left Analog Y" },
1130       { 3, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_RIGHT, RETRO_DEVICE_ID_ANALOG_X, "Right Analog X" },
1131       { 3, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_RIGHT, RETRO_DEVICE_ID_ANALOG_Y, "Right Analog Y" },
1132
1133       { 4, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT,  "D-Pad Left" },
1134       { 4, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP,    "D-Pad Up" },
1135       { 4, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN,  "D-Pad Down" },
1136       { 4, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT, "D-Pad Right" },
1137       { 4, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B,     "Cross" },
1138       { 4, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A,     "Circle" },
1139       { 4, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_X,     "Triangle" },
1140       { 4, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_Y,     "Square" },
1141       { 4, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L,     "L1" },
1142       { 4, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L2,    "L2" },
1143       { 4, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L3,    "L3" },
1144       { 4, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R,     "R1" },
1145       { 4, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R2,    "R2" },
1146       { 4, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R3,    "R3" },
1147       { 4, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_SELECT,    "Select" },
1148       { 4, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START,    "Start" },
1149       { 4, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_LEFT, RETRO_DEVICE_ID_ANALOG_X, "Left Analog X" },
1150       { 4, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_LEFT, RETRO_DEVICE_ID_ANALOG_Y, "Left Analog Y" },
1151       { 4, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_RIGHT, RETRO_DEVICE_ID_ANALOG_X, "Right Analog X" },
1152       { 4, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_RIGHT, RETRO_DEVICE_ID_ANALOG_Y, "Right Analog Y" },
1153
1154       { 5, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT,  "D-Pad Left" },
1155       { 5, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP,    "D-Pad Up" },
1156       { 5, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN,  "D-Pad Down" },
1157       { 5, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT, "D-Pad Right" },
1158       { 5, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B,     "Cross" },
1159       { 5, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A,     "Circle" },
1160       { 5, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_X,     "Triangle" },
1161       { 5, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_Y,     "Square" },
1162       { 5, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L,     "L1" },
1163       { 5, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L2,    "L2" },
1164       { 5, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L3,    "L3" },
1165       { 5, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R,     "R1" },
1166       { 5, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R2,    "R2" },
1167       { 5, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R3,    "R3" },
1168       { 5, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_SELECT,    "Select" },
1169       { 5, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START,    "Start" },
1170       { 5, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_LEFT, RETRO_DEVICE_ID_ANALOG_X, "Left Analog X" },
1171       { 5, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_LEFT, RETRO_DEVICE_ID_ANALOG_Y, "Left Analog Y" },
1172       { 5, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_RIGHT, RETRO_DEVICE_ID_ANALOG_X, "Right Analog X" },
1173       { 5, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_RIGHT, RETRO_DEVICE_ID_ANALOG_Y, "Right Analog Y" },
1174
1175       { 6, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT,  "D-Pad Left" },
1176       { 6, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP,    "D-Pad Up" },
1177       { 6, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN,  "D-Pad Down" },
1178       { 6, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT, "D-Pad Right" },
1179       { 6, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B,     "Cross" },
1180       { 6, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A,     "Circle" },
1181       { 6, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_X,     "Triangle" },
1182       { 6, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_Y,     "Square" },
1183       { 6, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L,     "L1" },
1184       { 6, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L2,    "L2" },
1185       { 6, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L3,    "L3" },
1186       { 6, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R,     "R1" },
1187       { 6, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R2,    "R2" },
1188       { 6, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R3,    "R3" },
1189       { 6, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_SELECT,    "Select" },
1190       { 6, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START,    "Start" },
1191       { 6, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_LEFT, RETRO_DEVICE_ID_ANALOG_X, "Left Analog X" },
1192       { 6, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_LEFT, RETRO_DEVICE_ID_ANALOG_Y, "Left Analog Y" },
1193       { 6, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_RIGHT, RETRO_DEVICE_ID_ANALOG_X, "Right Analog X" },
1194       { 6, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_RIGHT, RETRO_DEVICE_ID_ANALOG_Y, "Right Analog Y" },
1195
1196       { 7, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT,  "D-Pad Left" },
1197       { 7, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP,    "D-Pad Up" },
1198       { 7, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN,  "D-Pad Down" },
1199       { 7, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT, "D-Pad Right" },
1200       { 7, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_B,     "Cross" },
1201       { 7, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A,     "Circle" },
1202       { 7, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_X,     "Triangle" },
1203       { 7, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_Y,     "Square" },
1204       { 7, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L,     "L1" },
1205       { 7, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L2,    "L2" },
1206       { 7, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_L3,    "L3" },
1207       { 7, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R,     "R1" },
1208       { 7, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R2,    "R2" },
1209       { 7, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_R3,    "R3" },
1210       { 7, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_SELECT,    "Select" },
1211       { 7, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_START,    "Start" },
1212       { 7, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_LEFT, RETRO_DEVICE_ID_ANALOG_X, "Left Analog X" },
1213       { 7, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_LEFT, RETRO_DEVICE_ID_ANALOG_Y, "Left Analog Y" },
1214       { 7, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_RIGHT, RETRO_DEVICE_ID_ANALOG_X, "Right Analog X" },
1215       { 7, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_RIGHT, RETRO_DEVICE_ID_ANALOG_Y, "Right Analog Y" },
1216
1217       { 0 },
1218    };
1219
1220          frame_count = 0;
1221
1222    environ_cb(RETRO_ENVIRONMENT_SET_INPUT_DESCRIPTORS, desc);
1223
1224 #ifdef FRONTEND_SUPPORTS_RGB565
1225         enum retro_pixel_format fmt = RETRO_PIXEL_FORMAT_RGB565;
1226         if (environ_cb(RETRO_ENVIRONMENT_SET_PIXEL_FORMAT, &fmt)) {
1227                 SysPrintf("RGB565 supported, using it\n");
1228         }
1229 #endif
1230
1231         if (info == NULL || info->path == NULL) {
1232                 SysPrintf("info->path required\n");
1233                 return false;
1234         }
1235
1236         if (plugins_opened) {
1237                 ClosePlugins();
1238                 plugins_opened = 0;
1239         }
1240
1241         for (i = 0; i < sizeof(disks) / sizeof(disks[0]); i++) {
1242                 if (disks[i].fname != NULL) {
1243                         free(disks[i].fname);
1244                         disks[i].fname = NULL;
1245                 }
1246                 disks[i].internal_index = 0;
1247         }
1248
1249         disk_current_index = 0;
1250         extract_directory(base_dir, info->path, sizeof(base_dir));
1251
1252         if (is_m3u) {
1253                 if (!read_m3u(info->path)) {
1254                         log_cb(RETRO_LOG_INFO, "failed to read m3u file\n");
1255                         return false;
1256                 }
1257         } else {
1258                 disk_count = 1;
1259                 disks[0].fname = strdup(info->path);
1260         }
1261
1262         set_cd_image(disks[0].fname);
1263
1264         /* have to reload after set_cd_image for correct cdr plugin */
1265         if (LoadPlugins() == -1) {
1266                 log_cb(RETRO_LOG_INFO, "failed to load plugins\n");
1267                 return false;
1268         }
1269
1270         plugins_opened = 1;
1271         NetOpened = 0;
1272
1273         if (OpenPlugins() == -1) {
1274                 log_cb(RETRO_LOG_INFO, "failed to open plugins\n");
1275                 return false;
1276         }
1277
1278         plugin_call_rearmed_cbs();
1279         dfinput_activate();
1280
1281         if (CheckCdrom() == -1) {
1282         log_cb(RETRO_LOG_INFO, "unsupported/invalid CD image: %s\n", info->path);
1283                 return false;
1284         }
1285
1286         SysReset();
1287
1288         if (LoadCdrom() == -1) {
1289                 log_cb(RETRO_LOG_INFO, "could not load CD\n");
1290                 return false;
1291         }
1292         emu_on_new_cd(0);
1293
1294         // multidisk images
1295         if (!is_m3u) {
1296                 disk_count = cdrIsoMultidiskCount < 8 ? cdrIsoMultidiskCount : 8;
1297                 for (i = 1; i < sizeof(disks) / sizeof(disks[0]) && i < cdrIsoMultidiskCount; i++) {
1298                         disks[i].fname = strdup(info->path);
1299                         disks[i].internal_index = i;
1300                 }
1301         }
1302
1303         return true;
1304 }
1305
1306 unsigned retro_get_region(void)
1307 {
1308         return is_pal_mode ? RETRO_REGION_PAL : RETRO_REGION_NTSC;
1309 }
1310
1311 void *retro_get_memory_data(unsigned id)
1312 {
1313         if (id == RETRO_MEMORY_SAVE_RAM)
1314                 return Mcd1Data;
1315         else if (id == RETRO_MEMORY_SYSTEM_RAM)
1316                 return psxM;
1317         else
1318                 return NULL;
1319 }
1320
1321 size_t retro_get_memory_size(unsigned id)
1322 {
1323         if (id == RETRO_MEMORY_SAVE_RAM)
1324                 return MCD_SIZE;
1325         else if (id == RETRO_MEMORY_SYSTEM_RAM)
1326                 return 0x210000;
1327         else
1328                 return 0;
1329 }
1330
1331 void retro_reset(void)
1332 {
1333    //hack to prevent retroarch freezing when reseting in the menu but not while running with the hot key
1334    rebootemu = 1;
1335         //SysReset();
1336 }
1337
1338 static const unsigned short retro_psx_map[] = {
1339         [RETRO_DEVICE_ID_JOYPAD_B]      = 1 << DKEY_CROSS,
1340         [RETRO_DEVICE_ID_JOYPAD_Y]      = 1 << DKEY_SQUARE,
1341         [RETRO_DEVICE_ID_JOYPAD_SELECT] = 1 << DKEY_SELECT,
1342         [RETRO_DEVICE_ID_JOYPAD_START]  = 1 << DKEY_START,
1343         [RETRO_DEVICE_ID_JOYPAD_UP]     = 1 << DKEY_UP,
1344         [RETRO_DEVICE_ID_JOYPAD_DOWN]   = 1 << DKEY_DOWN,
1345         [RETRO_DEVICE_ID_JOYPAD_LEFT]   = 1 << DKEY_LEFT,
1346         [RETRO_DEVICE_ID_JOYPAD_RIGHT]  = 1 << DKEY_RIGHT,
1347         [RETRO_DEVICE_ID_JOYPAD_A]      = 1 << DKEY_CIRCLE,
1348         [RETRO_DEVICE_ID_JOYPAD_X]      = 1 << DKEY_TRIANGLE,
1349         [RETRO_DEVICE_ID_JOYPAD_L]      = 1 << DKEY_L1,
1350         [RETRO_DEVICE_ID_JOYPAD_R]      = 1 << DKEY_R1,
1351         [RETRO_DEVICE_ID_JOYPAD_L2]     = 1 << DKEY_L2,
1352         [RETRO_DEVICE_ID_JOYPAD_R2]     = 1 << DKEY_R2,
1353         [RETRO_DEVICE_ID_JOYPAD_L3]     = 1 << DKEY_L3,
1354         [RETRO_DEVICE_ID_JOYPAD_R3]     = 1 << DKEY_R3,
1355 };
1356 #define RETRO_PSX_MAP_LEN (sizeof(retro_psx_map) / sizeof(retro_psx_map[0]))
1357
1358 static void update_variables(bool in_flight)
1359 {
1360    struct retro_variable var;
1361    int i;
1362    int gpu_peops_fix = 0;
1363
1364    var.value = NULL;
1365    var.key = "pcsx_rearmed_frameskip";
1366    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
1367       pl_rearmed_cbs.frameskip = atoi(var.value);
1368
1369    var.value = NULL;
1370    var.key = "pcsx_rearmed_region";
1371    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
1372    {
1373       Config.PsxAuto = 0;
1374       if (strcmp(var.value, "auto") == 0)
1375          Config.PsxAuto = 1;
1376       else if (strcmp(var.value, "NTSC") == 0)
1377          Config.PsxType = 0;
1378       else if (strcmp(var.value, "PAL") == 0)
1379          Config.PsxType = 1;
1380    }
1381
1382    for (i = 0; i < PORTS_NUMBER; i++)
1383       update_controller_port_variable(i);
1384
1385    update_multitap();
1386
1387    var.value = NULL;
1388    var.key = "pcsx_rearmed_negcon_deadzone";
1389    negcon_deadzone = 0;
1390    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
1391    {
1392       negcon_deadzone = (int)(atoi(var.value) * 0.01f * NEGCON_RANGE);
1393    }
1394
1395    var.value = NULL;
1396    var.key = "pcsx_rearmed_negcon_response";
1397    negcon_linearity = 1;
1398    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
1399    {
1400       if (strcmp(var.value, "quadratic") == 0){
1401          negcon_linearity = 2;
1402       } else if (strcmp(var.value, "cubic") == 0){
1403          negcon_linearity = 3;
1404       }
1405    }
1406
1407    var.value = NULL;
1408    var.key = "pcsx_rearmed_vibration";
1409
1410    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
1411    {
1412       if (strcmp(var.value, "disabled") == 0)
1413          in_enable_vibration = 0;
1414       else if (strcmp(var.value, "enabled") == 0)
1415          in_enable_vibration = 1;
1416    }
1417
1418    var.value = NULL;
1419    var.key = "pcsx_rearmed_dithering";
1420
1421    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
1422    {
1423       if (strcmp(var.value, "disabled") == 0) {
1424          pl_rearmed_cbs.gpu_peops.iUseDither = 0;
1425          pl_rearmed_cbs.gpu_peopsgl.bDrawDither = 0;
1426 #ifdef __ARM_NEON__
1427          pl_rearmed_cbs.gpu_neon.allow_dithering = 0;
1428 #endif
1429       }
1430       else if (strcmp(var.value, "enabled") == 0) {
1431          pl_rearmed_cbs.gpu_peops.iUseDither = 1;
1432          pl_rearmed_cbs.gpu_peopsgl.bDrawDither = 1;
1433 #ifdef __ARM_NEON__
1434          pl_rearmed_cbs.gpu_neon.allow_dithering = 1;
1435 #endif
1436       }
1437    }
1438
1439 #ifdef __ARM_NEON__
1440    var.value = "NULL";
1441    var.key = "pcsx_rearmed_neon_interlace_enable";
1442
1443    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
1444    {
1445       if (strcmp(var.value, "disabled") == 0)
1446          pl_rearmed_cbs.gpu_neon.allow_interlace = 0;
1447       else if (strcmp(var.value, "enabled") == 0)
1448          pl_rearmed_cbs.gpu_neon.allow_interlace = 1;
1449    }
1450
1451    var.value = NULL;
1452    var.key = "pcsx_rearmed_neon_enhancement_enable";
1453
1454    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
1455    {
1456       if (strcmp(var.value, "disabled") == 0)
1457          pl_rearmed_cbs.gpu_neon.enhancement_enable = 0;
1458       else if (strcmp(var.value, "enabled") == 0)
1459          pl_rearmed_cbs.gpu_neon.enhancement_enable = 1;
1460    }
1461
1462    var.value = NULL;
1463    var.key = "pcsx_rearmed_neon_enhancement_no_main";
1464
1465    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
1466    {
1467       if (strcmp(var.value, "disabled") == 0)
1468          pl_rearmed_cbs.gpu_neon.enhancement_no_main = 0;
1469       else if (strcmp(var.value, "enabled") == 0)
1470          pl_rearmed_cbs.gpu_neon.enhancement_no_main = 1;
1471    }
1472 #endif
1473
1474    var.value = "NULL";
1475    var.key = "pcsx_rearmed_duping_enable";
1476
1477    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
1478    {
1479       if (strcmp(var.value, "disabled") == 0)
1480          duping_enable = false;
1481       else if (strcmp(var.value, "enabled") == 0)
1482          duping_enable = true;
1483    }
1484
1485    var.value = "NULL";
1486    var.key = "pcsx_rearmed_display_internal_fps";
1487
1488    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
1489    {
1490       if (strcmp(var.value, "disabled") == 0)
1491          display_internal_fps = false;
1492       else if (strcmp(var.value, "enabled") == 0)
1493          display_internal_fps = true;
1494    }
1495
1496 #ifndef DRC_DISABLE
1497    var.value = NULL;
1498    var.key = "pcsx_rearmed_drc";
1499
1500    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
1501    {
1502       R3000Acpu *prev_cpu = psxCpu;
1503
1504 #ifdef _3DS
1505       if(!__ctr_svchax)
1506          Config.Cpu = CPU_INTERPRETER;
1507       else
1508 #endif
1509       if (strcmp(var.value, "disabled") == 0)
1510          Config.Cpu = CPU_INTERPRETER;
1511       else if (strcmp(var.value, "enabled") == 0)
1512          Config.Cpu = CPU_DYNAREC;
1513
1514       psxCpu = (Config.Cpu == CPU_INTERPRETER) ? &psxInt : &psxRec;
1515       if (psxCpu != prev_cpu) {
1516          prev_cpu->Shutdown();
1517          psxCpu->Init();
1518          psxCpu->Reset(); // not really a reset..
1519       }
1520    }
1521 #endif
1522
1523    var.value = "NULL";
1524    var.key = "pcsx_rearmed_spu_reverb";
1525
1526    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
1527    {
1528       if (strcmp(var.value, "disabled") == 0)
1529          spu_config.iUseReverb = false;
1530       else if (strcmp(var.value, "enabled") == 0)
1531          spu_config.iUseReverb = true;
1532    }
1533
1534    var.value = "NULL";
1535    var.key = "pcsx_rearmed_spu_interpolation";
1536
1537    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
1538    {
1539       if (strcmp(var.value, "simple") == 0)
1540          spu_config.iUseInterpolation = 1;
1541       else if (strcmp(var.value, "gaussian") == 0)
1542          spu_config.iUseInterpolation = 2;
1543       else if (strcmp(var.value, "cubic") == 0)
1544          spu_config.iUseInterpolation = 3;
1545       else if (strcmp(var.value, "off") == 0)
1546          spu_config.iUseInterpolation = 0;
1547    }
1548
1549    var.value = "NULL";
1550    var.key = "pcsx_rearmed_pe2_fix";
1551
1552    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
1553    {
1554       if (strcmp(var.value, "disabled") == 0)
1555          Config.RCntFix = 0;
1556       else if (strcmp(var.value, "enabled") == 0)
1557          Config.RCntFix = 1;
1558    }
1559
1560    var.value = "NULL";
1561    var.key = "pcsx_rearmed_idiablofix";
1562
1563    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
1564    {
1565       if (strcmp(var.value, "disabled") == 0)
1566          spu_config.idiablofix = 0;
1567       else if (strcmp(var.value, "enabled") == 0)
1568          spu_config.idiablofix = 1;
1569    }
1570
1571    var.value = "NULL";
1572    var.key = "pcsx_rearmed_inuyasha_fix";
1573
1574    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
1575    {
1576       if (strcmp(var.value, "disabled") == 0)
1577          Config.VSyncWA = 0;
1578       else if (strcmp(var.value, "enabled") == 0)
1579          Config.VSyncWA = 1;
1580    }
1581
1582    var.value = NULL;
1583    var.key = "pcsx_rearmed_noxadecoding";
1584    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
1585    {
1586       if (strcmp(var.value, "disabled") == 0)
1587          Config.Xa = 1;
1588       else
1589          Config.Xa = 0;
1590    }
1591
1592    var.value = NULL;
1593    var.key = "pcsx_rearmed_nocdaudio";
1594    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
1595    {
1596       if (strcmp(var.value, "disabled") == 0)
1597          Config.Cdda = 1;
1598       else
1599          Config.Cdda = 0;
1600    }
1601
1602 #ifndef DRC_DISABLE
1603    var.value = NULL;
1604    var.key = "pcsx_rearmed_nosmccheck";
1605    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
1606    {
1607       if (strcmp(var.value, "enabled") == 0)
1608          new_dynarec_hacks |= NDHACK_NO_SMC_CHECK;
1609       else
1610          new_dynarec_hacks &= ~NDHACK_NO_SMC_CHECK;
1611    }
1612
1613    var.value = NULL;
1614    var.key = "pcsx_rearmed_gteregsunneeded";
1615    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
1616    {
1617       if (strcmp(var.value, "enabled") == 0)
1618          new_dynarec_hacks |= NDHACK_GTE_UNNEEDED;
1619       else
1620          new_dynarec_hacks &= ~NDHACK_GTE_UNNEEDED;
1621    }
1622
1623    var.value = NULL;
1624    var.key = "pcsx_rearmed_nogteflags";
1625    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
1626    {
1627       if (strcmp(var.value, "enabled") == 0)
1628          new_dynarec_hacks |= NDHACK_GTE_NO_FLAGS;
1629       else
1630          new_dynarec_hacks &= ~NDHACK_GTE_NO_FLAGS;
1631    }
1632 #endif
1633
1634 #ifdef GPU_PEOPS
1635    var.value = "NULL";
1636    var.key = "pcsx_rearmed_gpu_peops_fix_0";
1637
1638    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
1639    {
1640       if (strcmp(var.value, "enabled") == 0)
1641          gpu_peops_fix |= (1 << 0);
1642    }
1643
1644    var.value = "NULL";
1645    var.key = "pcsx_rearmed_gpu_peops_fix_1";
1646
1647    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
1648    {
1649       if (strcmp(var.value, "enabled") == 0)
1650          gpu_peops_fix |= (1 << 1);
1651    }
1652
1653    var.value = "NULL";
1654    var.key = "pcsx_rearmed_gpu_peops_fix_2";
1655
1656    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
1657    {
1658       if (strcmp(var.value, "enabled") == 0)
1659          gpu_peops_fix |= (1 << 2);
1660    }
1661
1662    var.value = "NULL";
1663    var.key = "pcsx_rearmed_gpu_peops_fix_3";
1664
1665    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
1666    {
1667       if (strcmp(var.value, "enabled") == 0)
1668          gpu_peops_fix |= (1 << 3);
1669    }
1670
1671    var.value = "NULL";
1672    var.key = "pcsx_rearmed_gpu_peops_fix_6";
1673
1674    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
1675    {
1676       if (strcmp(var.value, "enabled") == 0)
1677          gpu_peops_fix |= (1 << 6);
1678    }
1679
1680    var.value = "NULL";
1681    var.key = "pcsx_rearmed_gpu_peops_fix_7";
1682
1683    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
1684    {
1685       if (strcmp(var.value, "enabled") == 0)
1686          gpu_peops_fix |= (1 << 7);
1687    }
1688
1689    var.value = "NULL";
1690    var.key = "pcsx_rearmed_gpu_peops_fix_8";
1691
1692    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
1693    {
1694       if (strcmp(var.value, "enabled") == 0)
1695          gpu_peops_fix |= (1 << 8);
1696    }
1697
1698    var.value = "NULL";
1699    var.key = "pcsx_rearmed_gpu_peops_fix_9";
1700
1701    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
1702    {
1703       if (strcmp(var.value, "enabled") == 0)
1704          gpu_peops_fix |= (1 << 9);
1705    }
1706
1707    var.value = "NULL";
1708    var.key = "pcsx_rearmed_gpu_peops_fix_10";
1709
1710    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
1711    {
1712       if (strcmp(var.value, "enabled") == 0)
1713          gpu_peops_fix |= (1 << 10);
1714    }
1715
1716    if (pl_rearmed_cbs.gpu_peops.dwActFixes != gpu_peops_fix)
1717       pl_rearmed_cbs.gpu_peops.dwActFixes = gpu_peops_fix;
1718
1719
1720     /* Show/hide core options */
1721
1722    var.key = "pcsx_rearmed_show_gpu_peops_settings";
1723    var.value = NULL;
1724
1725    if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value)
1726    {
1727       int show_advanced_gpu_peops_settings_prev = show_advanced_gpu_peops_settings;
1728
1729       show_advanced_gpu_peops_settings = 1;
1730       if (strcmp(var.value, "disabled") == 0)
1731          show_advanced_gpu_peops_settings = 0;
1732
1733       if (show_advanced_gpu_peops_settings != show_advanced_gpu_peops_settings_prev)
1734       {
1735          unsigned i;
1736          struct retro_core_option_display option_display;
1737          char gpu_peops_option[9][32] = {
1738             "pcsx_rearmed_gpu_peops_fix_0",
1739             "pcsx_rearmed_gpu_peops_fix_1",
1740             "pcsx_rearmed_gpu_peops_fix_2",
1741             "pcsx_rearmed_gpu_peops_fix_3",
1742             "pcsx_rearmed_gpu_peops_fix_6",
1743             "pcsx_rearmed_gpu_peops_fix_7",
1744             "pcsx_rearmed_gpu_peops_fix_8",
1745             "pcsx_rearmed_gpu_peops_fix_9",
1746             "pcsx_rearmed_gpu_peops_fix_10",
1747          };
1748
1749          option_display.visible = show_advanced_gpu_peops_settings;
1750
1751          for (i = 0; i < 9; i++)
1752          {
1753             option_display.key = gpu_peops_option[i];
1754             environ_cb(RETRO_ENVIRONMENT_SET_CORE_OPTIONS_DISPLAY, &option_display);
1755          }
1756       }
1757    }
1758 #endif
1759
1760    if (in_flight) {
1761       // inform core things about possible config changes
1762       plugin_call_rearmed_cbs();
1763
1764       if (GPU_open != NULL && GPU_close != NULL) {
1765          GPU_close();
1766          GPU_open(&gpuDisp, "PCSX", NULL);
1767       }
1768
1769       dfinput_activate();
1770    }
1771    else
1772    {
1773       //not yet running
1774
1775       //bootlogo display hack
1776       if (found_bios) {
1777          var.value = "NULL";
1778          var.key = "pcsx_rearmed_show_bios_bootlogo";
1779          if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
1780          {
1781             Config.SlowBoot = 0;
1782             rebootemu = 0;
1783             if (strcmp(var.value, "enabled") == 0)
1784             {
1785                Config.SlowBoot = 1;
1786                rebootemu = 1;
1787             }
1788          }
1789       }
1790 #ifndef DRC_DISABLE
1791       var.value = "NULL";
1792       var.key = "pcsx_rearmed_psxclock";
1793       if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
1794       {
1795          int psxclock = atoi(var.value);
1796          cycle_multiplier = 10000 / psxclock;
1797       }
1798 #endif
1799    }
1800 }
1801
1802 // Taken from beetle-psx-libretro
1803 static uint16_t get_analog_button(int16_t ret, retro_input_state_t input_state_cb, int player_index, int id)
1804 {
1805         // NOTE: Analog buttons were added Nov 2017. Not all front-ends support this
1806         // feature (or pre-date it) so we need to handle this in a graceful way.
1807
1808         // First, try and get an analog value using the new libretro API constant
1809         uint16_t button = input_state_cb(player_index,
1810                                                                         RETRO_DEVICE_ANALOG,
1811                                                                         RETRO_DEVICE_INDEX_ANALOG_BUTTON,
1812                                                                         id);
1813         button = MIN(button / 128, 255);
1814
1815         if (button == 0)
1816         {
1817                 // If we got exactly zero, we're either not pressing the button, or the front-end
1818                 // is not reporting analog values. We need to do a second check using the classic
1819                 // digital API method, to at least get some response - better than nothing.
1820
1821                 // NOTE: If we're really just not holding the button, we're still going to get zero.
1822
1823                 button = (ret & (1 << id)) ? 255 : 0;
1824         }
1825
1826         return button;
1827 }
1828
1829 void retro_run(void)
1830 {
1831         int i;
1832         //SysReset must be run while core is running,Not in menu (Locks up Retroarch)
1833         if (rebootemu != 0) {
1834                 rebootemu = 0;
1835                 SysReset();
1836                 if (!Config.HLE && !Config.SlowBoot) {
1837                         // skip BIOS logos
1838                         psxRegs.pc = psxRegs.GPR.n.ra;
1839                 }
1840         }
1841
1842         if (display_internal_fps) {
1843                 frame_count++;
1844
1845                 if (frame_count % INTERNAL_FPS_SAMPLE_PERIOD == 0) {
1846                         unsigned internal_fps = pl_rearmed_cbs.flip_cnt * (is_pal_mode ? 50 : 60) / INTERNAL_FPS_SAMPLE_PERIOD;
1847                         char str[64];
1848                         const char *strc = (const char*)str;
1849                         struct retro_message msg =
1850                         {
1851                                 strc,
1852                                 180
1853                         };
1854
1855                         str[0] = '\0';
1856
1857                         snprintf(str, sizeof(str), "Internal FPS: %2d", internal_fps);
1858
1859                         pl_rearmed_cbs.flip_cnt = 0;
1860
1861                         environ_cb(RETRO_ENVIRONMENT_SET_MESSAGE, &msg);
1862                 }
1863         }
1864    else
1865                 frame_count = 0;
1866
1867         input_poll_cb();
1868
1869         bool updated = false;
1870         if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE, &updated) && updated)
1871                 update_variables(true);
1872
1873         // reset all keystate, query libretro for keystate
1874         int j;
1875         int lsx;
1876         int rsy;
1877         float negcon_twist_amplitude;
1878         int negcon_i_rs;
1879         int negcon_ii_rs;
1880         for(i = 0; i < PORTS_NUMBER; i++)
1881    {
1882       int16_t ret    = 0;
1883                 in_keystate[i] = 0;
1884
1885                 if (in_type[i] == PSE_PAD_TYPE_NONE)
1886                         continue;
1887
1888       if (libretro_supports_bitmasks)
1889          ret = input_state_cb(i, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_MASK);
1890       else
1891       {
1892          unsigned j;
1893          for (j = 0; j < (RETRO_DEVICE_ID_JOYPAD_R3+1); j++)
1894          {
1895             if (input_state_cb(i, RETRO_DEVICE_JOYPAD, 0, j))
1896                ret |= (1 << j);
1897          }
1898       }
1899
1900                 if (in_type[i] == PSE_PAD_TYPE_NEGCON)
1901                 {
1902                         // Query digital inputs
1903                         //
1904                         // > Pad-Up
1905                         if (ret & (1 << RETRO_DEVICE_ID_JOYPAD_UP))
1906                                 in_keystate[i] |= (1 << DKEY_UP);
1907                         // > Pad-Right
1908                         if (ret & (1 << RETRO_DEVICE_ID_JOYPAD_RIGHT))
1909                                 in_keystate[i] |= (1 << DKEY_RIGHT);
1910                         // > Pad-Down
1911                         if (ret & (1 << RETRO_DEVICE_ID_JOYPAD_DOWN))
1912                                 in_keystate[i] |= (1 << DKEY_DOWN);
1913                         // > Pad-Left
1914                         if (ret & (1 << RETRO_DEVICE_ID_JOYPAD_LEFT))
1915                                 in_keystate[i] |= (1 << DKEY_LEFT);
1916                         // > Start
1917                         if (ret & (1 << RETRO_DEVICE_ID_JOYPAD_START))
1918                                 in_keystate[i] |= (1 << DKEY_START);
1919                         // > neGcon A
1920                         if (ret & (1 << RETRO_DEVICE_ID_JOYPAD_A))
1921                                 in_keystate[i] |= (1 << DKEY_CIRCLE);
1922                         // > neGcon B
1923                         if (ret & (1 << RETRO_DEVICE_ID_JOYPAD_X))
1924                                 in_keystate[i] |= (1 << DKEY_TRIANGLE);
1925                         // > neGcon R shoulder (digital)
1926                         if (ret & (1 << RETRO_DEVICE_ID_JOYPAD_R))
1927                                 in_keystate[i] |= (1 << DKEY_R1);
1928                         // Query analog inputs
1929                         //
1930                         // From studying 'libpcsxcore/plugins.c' and 'frontend/plugin.c':
1931                         // >> pad->leftJoyX  == in_analog_left[i][0]  == NeGcon II
1932                         // >> pad->leftJoyY  == in_analog_left[i][1]  == NeGcon L
1933                         // >> pad->rightJoyX == in_analog_right[i][0] == NeGcon twist
1934                         // >> pad->rightJoyY == in_analog_right[i][1] == NeGcon I
1935                         // So we just have to map in_analog_left/right to more
1936                         // appropriate inputs...
1937                         //
1938                         // > NeGcon twist
1939                         // >> Get raw analog stick value and account for deadzone
1940                         lsx = input_state_cb(i, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_LEFT, RETRO_DEVICE_ID_ANALOG_X);
1941                         if (lsx > negcon_deadzone)
1942                                 lsx = lsx - negcon_deadzone;
1943                         else if (lsx < -negcon_deadzone)
1944                                 lsx = lsx + negcon_deadzone;
1945                         else
1946                                 lsx = 0;
1947                         // >> Convert to an 'amplitude' [-1.0,1.0] and adjust response
1948                         negcon_twist_amplitude = (float)lsx / (float)(NEGCON_RANGE - negcon_deadzone);
1949                         if (negcon_linearity == 2)
1950          {
1951                                 if (negcon_twist_amplitude < 0.0)
1952                                         negcon_twist_amplitude = -(negcon_twist_amplitude * negcon_twist_amplitude);
1953             else
1954                                         negcon_twist_amplitude = negcon_twist_amplitude * negcon_twist_amplitude;
1955                         }
1956          else if (negcon_linearity == 3)
1957                                 negcon_twist_amplitude = negcon_twist_amplitude * negcon_twist_amplitude * negcon_twist_amplitude;
1958                         // >> Convert to final 'in_analog' integer value [0,255]
1959                         in_analog_right[i][0] = MAX(MIN((int)(negcon_twist_amplitude * 128.0f) + 128, 255), 0);
1960                         // > NeGcon I + II
1961                         // >> Handle right analog stick vertical axis mapping...
1962                         //    - Up (-Y) == accelerate == neGcon I
1963                         //    - Down (+Y) == brake == neGcon II
1964                         negcon_i_rs = 0;
1965                         negcon_ii_rs = 0;
1966                         rsy = input_state_cb(i, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_RIGHT, RETRO_DEVICE_ID_ANALOG_Y);
1967                         if (rsy >= 0){
1968                                 // Account for deadzone
1969                                 // (Note: have never encountered a gamepad with significant differences
1970                                 // in deadzone between left/right analog sticks, so use the regular 'twist'
1971                                 // deadzone here)
1972                                 if (rsy > negcon_deadzone)
1973                                         rsy = rsy - negcon_deadzone;
1974             else
1975                                         rsy = 0;
1976                                 // Convert to 'in_analog' integer value [0,255]
1977                                 negcon_ii_rs = MIN((int)(((float)rsy / (float)(NEGCON_RANGE - negcon_deadzone)) * 255.0f), 255);
1978                         } else {
1979                                 if (rsy < -negcon_deadzone)
1980                                         rsy = -1 * (rsy + negcon_deadzone);
1981             else
1982                                         rsy = 0;
1983                                 negcon_i_rs = MIN((int)(((float)rsy / (float)(NEGCON_RANGE - negcon_deadzone)) * 255.0f), 255);
1984                         }
1985                         // >> NeGcon I
1986                         in_analog_right[i][1] = MAX(
1987                                 MAX(
1988                                         get_analog_button(ret, input_state_cb, i, RETRO_DEVICE_ID_JOYPAD_R2),
1989                                         get_analog_button(ret, input_state_cb, i, RETRO_DEVICE_ID_JOYPAD_B)
1990                                 ),
1991                                 negcon_i_rs
1992                         );
1993                         // >> NeGcon II
1994                         in_analog_left[i][0] = MAX(
1995                                 MAX(
1996                                         get_analog_button(ret, input_state_cb, i, RETRO_DEVICE_ID_JOYPAD_L2),
1997                                         get_analog_button(ret, input_state_cb, i, RETRO_DEVICE_ID_JOYPAD_Y)
1998                                 ),
1999                                 negcon_ii_rs
2000                         );
2001                         // > NeGcon L
2002                         in_analog_left[i][1] = get_analog_button(ret, input_state_cb, i, RETRO_DEVICE_ID_JOYPAD_L);
2003                 }
2004                 else
2005                 {
2006                         // Query digital inputs
2007                         for (j = 0; j < RETRO_PSX_MAP_LEN; j++)
2008                                 if (ret & (1 << j))
2009                                         in_keystate[i] |= retro_psx_map[j];
2010
2011                         // Query analog inputs
2012                         if (in_type[i] == PSE_PAD_TYPE_ANALOGJOY || in_type[i] == PSE_PAD_TYPE_ANALOGPAD)
2013                         {
2014                                 in_analog_left[i][0] = MIN((input_state_cb(i, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_LEFT, RETRO_DEVICE_ID_ANALOG_X) / 255) + 128, 255);
2015                                 in_analog_left[i][1] = MIN((input_state_cb(i, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_LEFT, RETRO_DEVICE_ID_ANALOG_Y) / 255) + 128, 255);
2016                                 in_analog_right[i][0] = MIN((input_state_cb(i, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_RIGHT, RETRO_DEVICE_ID_ANALOG_X) / 255) + 128, 255);
2017                                 in_analog_right[i][1] = MIN((input_state_cb(i, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_RIGHT, RETRO_DEVICE_ID_ANALOG_Y) / 255) + 128, 255);
2018                         }
2019                 }
2020         }
2021
2022         stop = 0;
2023         psxCpu->Execute();
2024
2025         video_cb((vout_fb_dirty || !vout_can_dupe || !duping_enable) ? vout_buf_ptr : NULL,
2026                 vout_width, vout_height, vout_width * 2);
2027         vout_fb_dirty = 0;
2028
2029     set_vout_fb();
2030 }
2031
2032 static bool try_use_bios(const char *path)
2033 {
2034         FILE *f;
2035         long size;
2036         const char *name;
2037
2038         f = fopen(path, "rb");
2039         if (f == NULL)
2040                 return false;
2041
2042         fseek(f, 0, SEEK_END);
2043         size = ftell(f);
2044         fclose(f);
2045
2046         if (size != 512 * 1024)
2047                 return false;
2048
2049         name = strrchr(path, SLASH);
2050         if (name++ == NULL)
2051                 name = path;
2052         snprintf(Config.Bios, sizeof(Config.Bios), "%s", name);
2053         return true;
2054 }
2055
2056 #ifndef VITA
2057 #include <sys/types.h>
2058 #include <dirent.h>
2059
2060 static bool find_any_bios(const char *dirpath, char *path, size_t path_size)
2061 {
2062         DIR *dir;
2063         struct dirent *ent;
2064         bool ret = false;
2065
2066         dir = opendir(dirpath);
2067         if (dir == NULL)
2068                 return false;
2069
2070         while ((ent = readdir(dir))) {
2071                 if (strncasecmp(ent->d_name, "scph", 4) != 0)
2072                         continue;
2073
2074                 snprintf(path, path_size, "%s%c%s", dirpath, SLASH, ent->d_name);
2075                 ret = try_use_bios(path);
2076                 if (ret)
2077                         break;
2078         }
2079         closedir(dir);
2080         return ret;
2081 }
2082 #else
2083 #define find_any_bios(...) false
2084 #endif
2085
2086 static void check_system_specs(void)
2087 {
2088    unsigned level = 6;
2089    environ_cb(RETRO_ENVIRONMENT_SET_PERFORMANCE_LEVEL, &level);
2090 }
2091
2092 static int init_memcards(void)
2093 {
2094         int ret = 0;
2095         const char *dir;
2096         struct retro_variable var = { .key="pcsx_rearmed_memcard2", .value=NULL };
2097         static const char CARD2_FILE[] = "pcsx-card2.mcd";
2098
2099         // Memcard2 will be handled and is re-enabled if needed using core
2100         // operations.
2101         // Memcard1 is handled by libretro, doing this will set core to
2102         // skip file io operations for memcard1 like SaveMcd
2103         snprintf(Config.Mcd1, sizeof(Config.Mcd1), "none");
2104         snprintf(Config.Mcd2, sizeof(Config.Mcd2), "none");
2105         init_memcard(Mcd1Data);
2106         // Memcard 2 is managed by the emulator on the filesystem,
2107         // There is no need to initialize Mcd2Data like Mcd1Data.
2108
2109         if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
2110                 SysPrintf("Memcard 2: %s\n", var.value);
2111                 if (memcmp(var.value, "enabled", 7) == 0) {
2112                         if (environ_cb(RETRO_ENVIRONMENT_GET_SAVE_DIRECTORY, &dir) && dir) {
2113                                 if (strlen(dir) + strlen(CARD2_FILE) + 2 > sizeof(Config.Mcd2)) {
2114                                         SysPrintf("Path '%s' is too long. Cannot use memcard 2. Use a shorter path.\n", dir);
2115                                         ret = -1;
2116                                 } else {
2117                                         McdDisable[1] = 0;
2118                                         snprintf(Config.Mcd2, sizeof(Config.Mcd2), "%s/%s", dir, CARD2_FILE);
2119                                         SysPrintf("Use memcard 2: %s\n", Config.Mcd2);
2120                                 }
2121                         } else {
2122                                 SysPrintf("Could not get save directory! Could not create memcard 2.");
2123                                 ret = -1;
2124                         }
2125                 }
2126         }
2127         return ret;
2128 }
2129
2130 static void loadPSXBios(void)
2131 {
2132         const char *dir;
2133         char path[256];
2134         unsigned useHLE = 0;
2135
2136         const char *bios[] = {
2137                 "SCPH101", "scph101",
2138                 "SCPH5501", "scph5501",
2139                 "SCPH7001", "scph7001",
2140                 "SCPH1001", "scph1001"
2141         };
2142
2143         struct retro_variable var = {
2144                 .key = "pcsx_rearmed_bios",
2145                 .value = NULL
2146         };
2147
2148         found_bios = 0;
2149
2150         if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && var.value) {
2151                 if (!strcmp(var.value, "HLE"))
2152                         useHLE = 1;
2153         }
2154
2155         if (!useHLE)
2156         {
2157                 if (environ_cb(RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY, &dir) && dir)
2158                 {
2159                         unsigned i;
2160                         snprintf(Config.BiosDir, sizeof(Config.BiosDir), "%s", dir);
2161
2162                         for (i = 0; i < sizeof(bios) / sizeof(bios[0]); i++) {
2163                                 snprintf(path, sizeof(path), "%s%c%s.bin", dir, SLASH, bios[i]);
2164                                 found_bios = try_use_bios(path);
2165                                 if (found_bios)
2166                                         break;
2167                         }
2168
2169                         if (!found_bios)
2170                                 found_bios = find_any_bios(dir, path, sizeof(path));
2171                 }
2172                 if (found_bios) {
2173                         SysPrintf("found BIOS file: %s\n", Config.Bios);
2174                 }
2175         }
2176
2177         if (useHLE || !found_bios)
2178         {
2179                 SysPrintf("no BIOS files found.\n");
2180                 struct retro_message msg =
2181                 {
2182                         "No PlayStation BIOS file found - add for better compatibility",
2183                         180
2184                 };
2185                 environ_cb(RETRO_ENVIRONMENT_SET_MESSAGE, (void*)&msg);
2186         }
2187 }
2188
2189 void retro_init(void)
2190 {
2191         struct retro_rumble_interface rumble;
2192         int ret;
2193
2194 #ifdef __MACH__
2195         // magic sauce to make the dynarec work on iOS
2196         syscall(SYS_ptrace, 0 /*PTRACE_TRACEME*/, 0, 0, 0);
2197 #endif
2198
2199 #ifdef _3DS
2200    psxMapHook = pl_3ds_mmap;
2201    psxUnmapHook = pl_3ds_munmap;
2202 #endif
2203 #ifdef VITA
2204    if(init_vita_mmap()<0)
2205       abort();
2206    psxMapHook = pl_vita_mmap;
2207    psxUnmapHook = pl_vita_munmap;
2208 #endif
2209         ret = emu_core_preinit();
2210 #ifdef _3DS
2211    /* emu_core_preinit sets the cpu to dynarec */
2212    if(!__ctr_svchax)
2213       Config.Cpu = CPU_INTERPRETER;
2214 #endif
2215         ret |= init_memcards();
2216
2217         ret |= emu_core_init();
2218         if (ret != 0) {
2219                 SysPrintf("PCSX init failed.\n");
2220                 exit(1);
2221         }
2222
2223 #ifdef _3DS
2224    vout_buf = linearMemAlign(VOUT_MAX_WIDTH * VOUT_MAX_HEIGHT * 2, 0x80);
2225 #elif defined(_POSIX_C_SOURCE) && (_POSIX_C_SOURCE >= 200112L) && !defined(VITA)
2226         posix_memalign(&vout_buf, 16, VOUT_MAX_WIDTH * VOUT_MAX_HEIGHT * 2);
2227 #else
2228         vout_buf = malloc(VOUT_MAX_WIDTH * VOUT_MAX_HEIGHT * 2);
2229 #endif
2230
2231         vout_buf_ptr = vout_buf;
2232
2233         loadPSXBios();
2234
2235         environ_cb(RETRO_ENVIRONMENT_GET_CAN_DUPE, &vout_can_dupe);
2236         environ_cb(RETRO_ENVIRONMENT_SET_DISK_CONTROL_INTERFACE, &disk_control);
2237
2238         rumble_cb = NULL;
2239         if (environ_cb(RETRO_ENVIRONMENT_GET_RUMBLE_INTERFACE, &rumble))
2240                 rumble_cb = rumble.set_rumble_state;
2241
2242         /* Set how much slower PSX CPU runs * 100 (so that 200 is 2 times)
2243          * we have to do this because cache misses and some IO penalties
2244          * are not emulated. Warning: changing this may break compatibility. */
2245         cycle_multiplier = 175;
2246 #ifdef HAVE_PRE_ARMV7
2247         cycle_multiplier = 200;
2248 #endif
2249         pl_rearmed_cbs.gpu_peops.iUseDither = 1;
2250    pl_rearmed_cbs.gpu_peops.dwActFixes = 1 << 7;
2251         spu_config.iUseFixedUpdates = 1;
2252
2253         SaveFuncs.open = save_open;
2254         SaveFuncs.read = save_read;
2255         SaveFuncs.write = save_write;
2256         SaveFuncs.seek = save_seek;
2257         SaveFuncs.close = save_close;
2258
2259    if (environ_cb(RETRO_ENVIRONMENT_GET_INPUT_BITMASKS, NULL))
2260       libretro_supports_bitmasks = true;
2261
2262         update_variables(false);
2263         check_system_specs();
2264 }
2265
2266 void retro_deinit(void)
2267 {
2268         SysClose();
2269 #ifdef _3DS
2270    linearFree(vout_buf);
2271 #else
2272         free(vout_buf);
2273 #endif
2274         vout_buf = NULL;
2275
2276 #ifdef VITA
2277   deinit_vita_mmap();
2278 #endif
2279    libretro_supports_bitmasks = false;
2280 }
2281
2282 #ifdef VITA
2283 #include <psp2/kernel/threadmgr.h>
2284 int usleep (unsigned long us)
2285 {
2286    sceKernelDelayThread(us);
2287 }
2288 #endif