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