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