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