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