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