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