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