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