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