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