4 * This work is licensed under the terms of the GNU GPLv2 or later.
5 * See the COPYING file in the top-level directory.
8 #define _GNU_SOURCE 1 // strcasestr
14 #include "../libpcsxcore/misc.h"
15 #include "../libpcsxcore/psxcounters.h"
16 #include "../libpcsxcore/psxmem_map.h"
17 #include "../libpcsxcore/new_dynarec/new_dynarec.h"
18 #include "../libpcsxcore/cdrom.h"
19 #include "../libpcsxcore/cdriso.h"
20 #include "../libpcsxcore/cheat.h"
21 #include "../plugins/dfsound/out.h"
22 #include "../plugins/dfinput/externals.h"
26 #include "plugin_lib.h"
30 static retro_video_refresh_t video_cb;
31 static retro_input_poll_t input_poll_cb;
32 static retro_input_state_t input_state_cb;
33 static retro_environment_t environ_cb;
34 static retro_audio_sample_batch_t audio_batch_cb;
36 static void *vout_buf;
37 static int vout_width, vout_height;
38 static int vout_doffs_old, vout_fb_dirty;
39 static bool vout_can_dupe;
41 static int samples_sent, samples_to_send;
42 static int plugins_opened;
43 static int is_pal_mode;
45 /* memory card data */
46 extern char Mcd1Data[MCD_SIZE];
47 extern char McdDisable[2];
49 /* PCSX ReARMed core calls and stuff */
50 int in_type1, in_type2;
51 int in_a1[2] = { 127, 127 }, in_a2[2] = { 127, 127 };
53 int in_enable_vibration;
55 /* PSX max resolution is 640x512, but with enhancement it's 1024x512 */
56 #define VOUT_MAX_WIDTH 1024
57 #define VOUT_MAX_HEIGHT 512
59 static void init_memcard(char *mcd_data)
64 memset(mcd_data, 0, MCD_SIZE);
66 mcd_data[off++] = 'M';
67 mcd_data[off++] = 'C';
69 mcd_data[off++] = 0x0e;
71 for (i = 0; i < 15; i++) {
72 mcd_data[off++] = 0xa0;
74 mcd_data[off++] = 0xff;
75 mcd_data[off++] = 0xff;
77 mcd_data[off++] = 0xa0;
80 for (i = 0; i < 20; i++) {
81 mcd_data[off++] = 0xff;
82 mcd_data[off++] = 0xff;
83 mcd_data[off++] = 0xff;
84 mcd_data[off++] = 0xff;
86 mcd_data[off++] = 0xff;
87 mcd_data[off++] = 0xff;
92 static int vout_open(void)
97 static void vout_set_mode(int w, int h, int raw_w, int raw_h, int bpp)
103 #ifndef FRONTEND_SUPPORTS_RGB565
104 static void convert(void *buf, size_t bytes)
106 unsigned int i, v, *p = buf;
108 for (i = 0; i < bytes / 4; i++) {
110 p[i] = (v & 0x001f001f) | ((v >> 1) & 0x7fe07fe0);
115 static void vout_flip(const void *vram, int stride, int bgr24, int w, int h)
117 unsigned short *dest = vout_buf;
118 const unsigned short *src = vram;
119 int dstride = vout_width, h1 = h;
124 memset(vout_buf, 0, dstride * h * 2);
128 doffs = (vout_height - h) * dstride;
129 doffs += (dstride - w) / 2 & ~1;
130 if (doffs != vout_doffs_old) {
132 memset(vout_buf, 0, dstride * h * 2);
133 vout_doffs_old = doffs;
139 // XXX: could we switch to RETRO_PIXEL_FORMAT_XRGB8888 here?
140 for (; h1-- > 0; dest += dstride, src += stride)
142 bgr888_to_rgb565(dest, src, w * 3);
147 for (; h1-- > 0; dest += dstride, src += stride)
149 bgr555_to_rgb565(dest, src, w * 2);
154 #ifndef FRONTEND_SUPPORTS_RGB565
155 convert(vout_buf, vout_width * vout_height * 2);
158 pl_rearmed_cbs.flip_cnt++;
161 static void vout_close(void)
165 static void *pl_mmap(unsigned int size)
167 return psxMap(0, size, 0, MAP_TAG_VRAM);
170 static void pl_munmap(void *ptr, unsigned int size)
172 psxUnmap(ptr, size, MAP_TAG_VRAM);
175 struct rearmed_cbs pl_rearmed_cbs = {
176 .pl_vout_open = vout_open,
177 .pl_vout_set_mode = vout_set_mode,
178 .pl_vout_flip = vout_flip,
179 .pl_vout_close = vout_close,
182 /* from psxcounters */
183 .gpu_hcnt = &hSyncCount,
184 .gpu_frame_count = &frame_counter,
187 void pl_frame_limit(void)
189 /* called once per frame, make psxCpu->Execute() above return */
193 void pl_timing_prepare(int is_pal)
195 is_pal_mode = is_pal;
198 void plat_trigger_vibrate(int is_strong)
202 void pl_update_gun(int *xn, int *yn, int *xres, int *yres, int *in)
207 static int snd_init(void)
212 static void snd_finish(void)
216 static int snd_busy(void)
218 if (samples_to_send > samples_sent)
219 return 0; /* give more samples */
224 static void snd_feed(void *buf, int bytes)
226 audio_batch_cb(buf, bytes / 4);
227 samples_sent += bytes / 4;
230 void out_register_libretro(struct out_driver *drv)
232 drv->name = "libretro";
233 drv->init = snd_init;
234 drv->finish = snd_finish;
235 drv->busy = snd_busy;
236 drv->feed = snd_feed;
240 void retro_set_environment(retro_environment_t cb)
242 static const struct retro_variable vars[] = {
243 { "frameskip", "Frameskip; 0|1|2|3" },
244 { "region", "Region; Auto|NTSC|PAL" },
245 { "pad1type", "Pad 1 Type; standard|analog" },
247 { "neon_interlace_enable", "Enable interlacing mode(s); disabled|enabled" },
248 { "neon_enhancement_enable", "Enhanced resolution (slow); disabled|enabled" },
249 { "neon_enhancement_no_main", "Enhanced resolution speed hack; disabled|enabled" },
256 cb(RETRO_ENVIRONMENT_SET_VARIABLES, (void*)vars);
259 void retro_set_video_refresh(retro_video_refresh_t cb) { video_cb = cb; }
260 void retro_set_audio_sample(retro_audio_sample_t cb) { (void)cb; }
261 void retro_set_audio_sample_batch(retro_audio_sample_batch_t cb) { audio_batch_cb = cb; }
262 void retro_set_input_poll(retro_input_poll_t cb) { input_poll_cb = cb; }
263 void retro_set_input_state(retro_input_state_t cb) { input_state_cb = cb; }
265 unsigned retro_api_version(void)
267 return RETRO_API_VERSION;
270 void retro_set_controller_port_device(unsigned port, unsigned device)
274 void retro_get_system_info(struct retro_system_info *info)
276 memset(info, 0, sizeof(*info));
277 info->library_name = "PCSX-ReARMed";
278 info->library_version = "r19";
279 info->valid_extensions = "bin|cue|img|mdf|pbp|toc|cbn|m3u";
280 info->need_fullpath = true;
283 void retro_get_system_av_info(struct retro_system_av_info *info)
285 memset(info, 0, sizeof(*info));
286 info->timing.fps = is_pal_mode ? 50 : 60;
287 info->timing.sample_rate = 44100;
288 info->geometry.base_width = 320;
289 info->geometry.base_height = 240;
290 info->geometry.max_width = VOUT_MAX_WIDTH;
291 info->geometry.max_height = VOUT_MAX_HEIGHT;
292 info->geometry.aspect_ratio = 4.0 / 3.0;
296 size_t retro_serialize_size(void)
298 // it's currently 4380651 bytes, but have some reserved for future
308 static void *save_open(const char *name, const char *mode)
312 if (name == NULL || mode == NULL)
315 fp = malloc(sizeof(*fp));
319 fp->buf = (char *)name;
321 fp->is_write = (mode[0] == 'w' || mode[1] == 'w');
326 static int save_read(void *file, void *buf, u32 len)
328 struct save_fp *fp = file;
329 if (fp == NULL || buf == NULL)
332 memcpy(buf, fp->buf + fp->pos, len);
337 static int save_write(void *file, const void *buf, u32 len)
339 struct save_fp *fp = file;
340 if (fp == NULL || buf == NULL)
343 memcpy(fp->buf + fp->pos, buf, len);
348 static long save_seek(void *file, long offs, int whence)
350 struct save_fp *fp = file;
366 static void save_close(void *file)
368 struct save_fp *fp = file;
369 size_t r_size = retro_serialize_size();
373 if (fp->pos > r_size)
374 SysPrintf("ERROR: save buffer overflow detected\n");
375 else if (fp->is_write && fp->pos < r_size)
376 // make sure we don't save trash in leftover space
377 memset(fp->buf + fp->pos, 0, r_size - fp->pos);
381 bool retro_serialize(void *data, size_t size)
383 int ret = SaveState(data);
384 return ret == 0 ? true : false;
387 bool retro_unserialize(const void *data, size_t size)
389 int ret = LoadState(data);
390 return ret == 0 ? true : false;
394 void retro_cheat_reset(void)
399 void retro_cheat_set(unsigned index, bool enabled, const char *code)
404 // cheat funcs are destructive, need a copy..
405 strncpy(buf, code, sizeof(buf));
406 buf[sizeof(buf) - 1] = 0;
408 if (index < NumCheats)
409 ret = EditCheat(index, "", buf);
411 ret = AddCheat("", buf);
414 SysPrintf("Failed to set cheat %#u\n", index);
415 else if (index < NumCheats)
416 Cheats[index].Enabled = enabled;
419 /* multidisk support */
420 static bool disk_ejected;
421 static unsigned int disk_current_index;
422 static unsigned int disk_count;
423 static struct disks_state {
425 int internal_index; // for multidisk eboots
428 static bool disk_set_eject_state(bool ejected)
431 SetCdOpenCaseTime(ejected ? -1 : (time(NULL) + 2));
434 disk_ejected = ejected;
438 static bool disk_get_eject_state(void)
440 /* can't be controlled by emulated software */
444 static unsigned int disk_get_image_index(void)
446 return disk_current_index;
449 static bool disk_set_image_index(unsigned int index)
451 if (index >= sizeof(disks) / sizeof(disks[0]))
455 CdromLabel[0] = '\0';
457 if (disks[index].fname == NULL) {
458 SysPrintf("missing disk #%u\n", index);
461 // RetroArch specifies "no disk" with index == count,
462 // so don't fail here..
463 disk_current_index = index;
467 SysPrintf("switching to disk %u: \"%s\" #%d\n", index,
468 disks[index].fname, disks[index].internal_index);
470 cdrIsoMultidiskSelect = disks[index].internal_index;
471 set_cd_image(disks[index].fname);
472 if (ReloadCdromPlugin() < 0) {
473 SysPrintf("failed to load cdr plugin\n");
476 if (CDR_open() < 0) {
477 SysPrintf("failed to open cdr plugin\n");
482 SetCdOpenCaseTime(time(NULL) + 2);
486 disk_current_index = index;
490 static unsigned int disk_get_num_images(void)
495 static bool disk_replace_image_index(unsigned index,
496 const struct retro_game_info *info)
501 if (index >= sizeof(disks) / sizeof(disks[0]))
504 old_fname = disks[index].fname;
505 disks[index].fname = NULL;
506 disks[index].internal_index = 0;
509 disks[index].fname = strdup(info->path);
510 if (index == disk_current_index)
511 ret = disk_set_image_index(index);
514 if (old_fname != NULL)
520 static bool disk_add_image_index(void)
529 static struct retro_disk_control_callback disk_control = {
530 .set_eject_state = disk_set_eject_state,
531 .get_eject_state = disk_get_eject_state,
532 .get_image_index = disk_get_image_index,
533 .set_image_index = disk_set_image_index,
534 .get_num_images = disk_get_num_images,
535 .replace_image_index = disk_replace_image_index,
536 .add_image_index = disk_add_image_index,
539 // just in case, maybe a win-rt port in the future?
546 static char base_dir[PATH_MAX];
548 static bool read_m3u(const char *file)
552 FILE *f = fopen(file, "r");
556 while (fgets(line, sizeof(line), f) && disk_count < sizeof(disks) / sizeof(disks[0])) {
559 char *carrige_return = strchr(line, '\r');
561 *carrige_return = '\0';
562 char *newline = strchr(line, '\n');
568 snprintf(name, sizeof(name), "%s%c%s", base_dir, SLASH, line);
569 disks[disk_count++].fname = strdup(name);
574 return (disk_count != 0);
577 static void extract_directory(char *buf, const char *path, size_t size)
580 strncpy(buf, path, size - 1);
581 buf[size - 1] = '\0';
583 base = strrchr(buf, '/');
585 base = strrchr(buf, '\\');
597 /* Blackberry QNX doesn't have strcasestr */
600 * Find the first occurrence of find in s, ignore case.
603 strcasestr(const char *s, const char*find)
608 if ((c = *find++) != 0) {
609 c = tolower((unsigned char)c);
613 if ((sc = *s++) == 0)
615 } while ((char)tolower((unsigned char)sc) != c);
616 } while (strncasecmp(s, find, len) != 0);
623 bool retro_load_game(const struct retro_game_info *info)
626 bool is_m3u = (strcasestr(info->path, ".m3u") != NULL);
628 #ifdef FRONTEND_SUPPORTS_RGB565
629 enum retro_pixel_format fmt = RETRO_PIXEL_FORMAT_RGB565;
630 if (environ_cb(RETRO_ENVIRONMENT_SET_PIXEL_FORMAT, &fmt)) {
631 SysPrintf("RGB565 supported, using it\n");
635 if (info == NULL || info->path == NULL) {
636 SysPrintf("info->path required\n");
640 if (plugins_opened) {
645 for (i = 0; i < sizeof(disks) / sizeof(disks[0]); i++) {
646 if (disks[i].fname != NULL) {
647 free(disks[i].fname);
648 disks[i].fname = NULL;
650 disks[i].internal_index = 0;
653 disk_current_index = 0;
654 extract_directory(base_dir, info->path, sizeof(base_dir));
657 if (!read_m3u(info->path)) {
658 SysPrintf("failed to read m3u file\n");
663 disks[0].fname = strdup(info->path);
666 set_cd_image(disks[0].fname);
668 /* have to reload after set_cd_image for correct cdr plugin */
669 if (LoadPlugins() == -1) {
670 SysPrintf("failed to load plugins\n");
677 if (OpenPlugins() == -1) {
678 SysPrintf("failed to open plugins\n");
682 plugin_call_rearmed_cbs();
686 if (CheckCdrom() == -1) {
687 SysPrintf("unsupported/invalid CD image: %s\n", info->path);
693 if (LoadCdrom() == -1) {
694 SysPrintf("could not load CD-ROM!\n");
701 disk_count = cdrIsoMultidiskCount < 8 ? cdrIsoMultidiskCount : 8;
702 for (i = 1; i < sizeof(disks) / sizeof(disks[0]) && i < cdrIsoMultidiskCount; i++) {
703 disks[i].fname = strdup(info->path);
704 disks[i].internal_index = i;
711 bool retro_load_game_special(unsigned game_type, const struct retro_game_info *info, size_t num_info)
716 void retro_unload_game(void)
720 unsigned retro_get_region(void)
722 return is_pal_mode ? RETRO_REGION_PAL : RETRO_REGION_NTSC;
725 void *retro_get_memory_data(unsigned id)
727 if (id == RETRO_MEMORY_SAVE_RAM)
733 size_t retro_get_memory_size(unsigned id)
735 if (id == RETRO_MEMORY_SAVE_RAM)
741 void retro_reset(void)
746 static const unsigned short retro_psx_map[] = {
747 [RETRO_DEVICE_ID_JOYPAD_B] = 1 << DKEY_CROSS,
748 [RETRO_DEVICE_ID_JOYPAD_Y] = 1 << DKEY_SQUARE,
749 [RETRO_DEVICE_ID_JOYPAD_SELECT] = 1 << DKEY_SELECT,
750 [RETRO_DEVICE_ID_JOYPAD_START] = 1 << DKEY_START,
751 [RETRO_DEVICE_ID_JOYPAD_UP] = 1 << DKEY_UP,
752 [RETRO_DEVICE_ID_JOYPAD_DOWN] = 1 << DKEY_DOWN,
753 [RETRO_DEVICE_ID_JOYPAD_LEFT] = 1 << DKEY_LEFT,
754 [RETRO_DEVICE_ID_JOYPAD_RIGHT] = 1 << DKEY_RIGHT,
755 [RETRO_DEVICE_ID_JOYPAD_A] = 1 << DKEY_CIRCLE,
756 [RETRO_DEVICE_ID_JOYPAD_X] = 1 << DKEY_TRIANGLE,
757 [RETRO_DEVICE_ID_JOYPAD_L] = 1 << DKEY_L1,
758 [RETRO_DEVICE_ID_JOYPAD_R] = 1 << DKEY_R1,
759 [RETRO_DEVICE_ID_JOYPAD_L2] = 1 << DKEY_L2,
760 [RETRO_DEVICE_ID_JOYPAD_R2] = 1 << DKEY_R2,
761 [RETRO_DEVICE_ID_JOYPAD_L3] = 1 << DKEY_L3,
762 [RETRO_DEVICE_ID_JOYPAD_R3] = 1 << DKEY_R3,
764 #define RETRO_PSX_MAP_LEN (sizeof(retro_psx_map) / sizeof(retro_psx_map[0]))
766 static void update_variables(bool in_flight)
768 struct retro_variable var;
771 var.key = "frameskip";
773 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
774 pl_rearmed_cbs.frameskip = atoi(var.value);
779 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
782 if (strcmp(var.value, "Automatic") == 0)
784 else if (strcmp(var.value, "NTSC") == 0)
786 else if (strcmp(var.value, "PAL") == 0)
791 var.key = "pad1type";
793 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
795 in_type1 = PSE_PAD_TYPE_STANDARD;
796 if (strcmp(var.value, "analog") == 0)
797 in_type1 = PSE_PAD_TYPE_ANALOGPAD;
802 var.key = "neon_interlace_enable";
804 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
806 if (strcmp(var.value, "disabled") == 0)
807 pl_rearmed_cbs.gpu_neon.allow_interlace = 0;
808 else if (strcmp(var.value, "enabled") == 0)
809 pl_rearmed_cbs.gpu_neon.allow_interlace = 1;
813 var.key = "neon_enhancement_enable";
815 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
817 if (strcmp(var.value, "disabled") == 0)
818 pl_rearmed_cbs.gpu_neon.enhancement_enable = 0;
819 else if (strcmp(var.value, "enabled") == 0)
820 pl_rearmed_cbs.gpu_neon.enhancement_enable = 1;
824 var.key = "neon_enhancement_no_main";
826 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
828 if (strcmp(var.value, "disabled") == 0)
829 pl_rearmed_cbs.gpu_neon.enhancement_no_main = 0;
830 else if (strcmp(var.value, "enabled") == 0)
831 pl_rearmed_cbs.gpu_neon.enhancement_no_main = 1;
836 // inform core things about possible config changes
837 plugin_call_rearmed_cbs();
839 if (GPU_open != NULL && GPU_close != NULL) {
841 GPU_open(&gpuDisp, "PCSX", NULL);
854 bool updated = false;
855 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE, &updated) && updated)
856 update_variables(true);
859 for (i = 0; i < RETRO_PSX_MAP_LEN; i++)
860 if (input_state_cb(1, RETRO_DEVICE_JOYPAD, 0, i))
861 in_keystate |= retro_psx_map[i];
863 for (i = 0; i < RETRO_PSX_MAP_LEN; i++)
864 if (input_state_cb(0, RETRO_DEVICE_JOYPAD, 0, i))
865 in_keystate |= retro_psx_map[i];
867 if (in_type1 == PSE_PAD_TYPE_ANALOGPAD)
869 in_a1[0] = (input_state_cb(0, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_LEFT, RETRO_DEVICE_ID_ANALOG_X) / 256) + 128;
870 in_a1[1] = (input_state_cb(0, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_LEFT, RETRO_DEVICE_ID_ANALOG_Y) / 256) + 128;
871 in_a2[0] = (input_state_cb(0, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_RIGHT, RETRO_DEVICE_ID_ANALOG_X) / 256) + 128;
872 in_a2[1] = (input_state_cb(0, RETRO_DEVICE_ANALOG, RETRO_DEVICE_INDEX_ANALOG_RIGHT, RETRO_DEVICE_ID_ANALOG_Y) / 256) + 128;
878 samples_to_send += is_pal_mode ? 44100 / 50 : 44100 / 60;
880 video_cb((vout_fb_dirty || !vout_can_dupe) ? vout_buf : NULL,
881 vout_width, vout_height, vout_width * 2);
885 static bool try_use_bios(const char *path)
891 f = fopen(path, "rb");
895 fseek(f, 0, SEEK_END);
899 if (size != 512 * 1024)
902 name = strrchr(path, SLASH);
905 snprintf(Config.Bios, sizeof(Config.Bios), "%s", name);
910 #include <sys/types.h>
913 static bool find_any_bios(const char *dirpath, char *path, size_t path_size)
919 dir = opendir(dirpath);
923 while ((ent = readdir(dir))) {
924 if (strncasecmp(ent->d_name, "scph", 4) != 0)
927 snprintf(path, path_size, "%s/%s", dirpath, ent->d_name);
928 ret = try_use_bios(path);
936 #define find_any_bios(...) false
939 void retro_init(void)
941 const char *bios[] = { "scph1001", "scph5501", "scph7001" };
945 bool found_bios = false;
947 ret = emu_core_preinit();
948 ret |= emu_core_init();
950 SysPrintf("PCSX init failed.\n");
954 vout_buf = malloc(VOUT_MAX_WIDTH * VOUT_MAX_HEIGHT * 2);
956 if (environ_cb(RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY, &dir) && dir)
958 snprintf(Config.BiosDir, sizeof(Config.BiosDir), "%s/", dir);
960 for (i = 0; i < sizeof(bios) / sizeof(bios[0]); i++) {
961 snprintf(path, sizeof(path), "%s/%s.bin", dir, bios[i]);
962 found_bios = try_use_bios(path);
968 found_bios = find_any_bios(dir, path, sizeof(path));
971 SysPrintf("found BIOS file: %s\n", Config.Bios);
975 SysPrintf("no BIOS files found.\n");
976 struct retro_message msg =
978 "no BIOS found, expect bugs!",
981 environ_cb(RETRO_ENVIRONMENT_SET_MESSAGE, (void*)&msg);
985 environ_cb(RETRO_ENVIRONMENT_SET_PERFORMANCE_LEVEL, &level);
987 environ_cb(RETRO_ENVIRONMENT_GET_CAN_DUPE, &vout_can_dupe);
988 environ_cb(RETRO_ENVIRONMENT_SET_DISK_CONTROL_INTERFACE, &disk_control);
990 /* Set how much slower PSX CPU runs * 100 (so that 200 is 2 times)
991 * we have to do this because cache misses and some IO penalties
992 * are not emulated. Warning: changing this may break compatibility. */
993 #ifdef __ARM_ARCH_7A__
994 cycle_multiplier = 175;
996 cycle_multiplier = 200;
1001 init_memcard(Mcd1Data);
1003 SaveFuncs.open = save_open;
1004 SaveFuncs.read = save_read;
1005 SaveFuncs.write = save_write;
1006 SaveFuncs.seek = save_seek;
1007 SaveFuncs.close = save_close;
1009 update_variables(false);
1012 void retro_deinit(void)