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