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