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