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