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