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