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