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