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
13 #include "../libpcsxcore/misc.h"
14 #include "../libpcsxcore/psxcounters.h"
15 #include "../libpcsxcore/psxmem_map.h"
16 #include "../libpcsxcore/new_dynarec/new_dynarec.h"
17 #include "../libpcsxcore/cdrom.h"
18 #include "../libpcsxcore/cdriso.h"
19 #include "../libpcsxcore/cheat.h"
20 #include "../plugins/dfsound/out.h"
21 #include "../plugins/dfinput/externals.h"
25 #include "plugin_lib.h"
29 static retro_video_refresh_t video_cb;
30 static retro_input_poll_t input_poll_cb;
31 static retro_input_state_t input_state_cb;
32 static retro_environment_t environ_cb;
33 static retro_audio_sample_batch_t audio_batch_cb;
35 static void *vout_buf;
36 static int vout_width, vout_height;
37 static int vout_doffs_old, vout_fb_dirty;
38 static bool vout_can_dupe;
40 static int samples_sent, samples_to_send;
41 static int plugins_opened;
42 static int is_pal_mode;
44 /* memory card data */
45 extern char Mcd1Data[MCD_SIZE];
46 extern char McdDisable[2];
48 /* PCSX ReARMed core calls and stuff */
49 int in_type1, in_type2;
50 int in_a1[2] = { 127, 127 }, in_a2[2] = { 127, 127 };
52 int in_enable_vibration;
54 /* PSX max resolution is 640x512, but with enhancement it's 1024x512 */
55 #define VOUT_MAX_WIDTH 1024
56 #define VOUT_MAX_HEIGHT 512
58 static void init_memcard(char *mcd_data)
63 memset(mcd_data, 0, MCD_SIZE);
65 mcd_data[off++] = 'M';
66 mcd_data[off++] = 'C';
68 mcd_data[off++] = 0x0e;
70 for (i = 0; i < 15; i++) {
71 mcd_data[off++] = 0xa0;
73 mcd_data[off++] = 0xff;
74 mcd_data[off++] = 0xff;
76 mcd_data[off++] = 0xa0;
79 for (i = 0; i < 20; i++) {
80 mcd_data[off++] = 0xff;
81 mcd_data[off++] = 0xff;
82 mcd_data[off++] = 0xff;
83 mcd_data[off++] = 0xff;
85 mcd_data[off++] = 0xff;
86 mcd_data[off++] = 0xff;
91 static int vout_open(void)
96 static void vout_set_mode(int w, int h, int raw_w, int raw_h, int bpp)
102 #ifndef FRONTEND_SUPPORTS_RGB565
103 static void convert(void *buf, size_t bytes)
105 unsigned int i, v, *p = buf;
107 for (i = 0; i < bytes / 4; i++) {
109 p[i] = (v & 0x001f001f) | ((v >> 1) & 0x7fe07fe0);
114 static void vout_flip(const void *vram, int stride, int bgr24, int w, int h)
116 unsigned short *dest = vout_buf;
117 const unsigned short *src = vram;
118 int dstride = vout_width, h1 = h;
123 memset(vout_buf, 0, dstride * h * 2);
127 doffs = (vout_height - h) * dstride;
128 doffs += (dstride - w) / 2 & ~1;
129 if (doffs != vout_doffs_old) {
131 memset(vout_buf, 0, dstride * h * 2);
132 vout_doffs_old = doffs;
138 // XXX: could we switch to RETRO_PIXEL_FORMAT_XRGB8888 here?
139 for (; h1-- > 0; dest += dstride, src += stride)
141 bgr888_to_rgb565(dest, src, w * 3);
146 for (; h1-- > 0; dest += dstride, src += stride)
148 bgr555_to_rgb565(dest, src, w * 2);
153 #ifndef FRONTEND_SUPPORTS_RGB565
154 convert(vout_buf, vout_width * vout_height * 2);
157 pl_rearmed_cbs.flip_cnt++;
160 static void vout_close(void)
164 static void *pl_mmap(unsigned int size)
166 return psxMap(0, size, 0, MAP_TAG_VRAM);
169 static void pl_munmap(void *ptr, unsigned int size)
171 psxUnmap(ptr, size, MAP_TAG_VRAM);
174 struct rearmed_cbs pl_rearmed_cbs = {
175 .pl_vout_open = vout_open,
176 .pl_vout_set_mode = vout_set_mode,
177 .pl_vout_flip = vout_flip,
178 .pl_vout_close = vout_close,
181 /* from psxcounters */
182 .gpu_hcnt = &hSyncCount,
183 .gpu_frame_count = &frame_counter,
186 void pl_frame_limit(void)
188 /* called once per frame, make psxCpu->Execute() above return */
192 void pl_timing_prepare(int is_pal)
194 is_pal_mode = is_pal;
197 void plat_trigger_vibrate(int is_strong)
201 void pl_update_gun(int *xn, int *yn, int *xres, int *yres, int *in)
206 static int snd_init(void)
211 static void snd_finish(void)
215 static int snd_busy(void)
217 if (samples_to_send > samples_sent)
218 return 0; /* give more samples */
223 static void snd_feed(void *buf, int bytes)
225 audio_batch_cb(buf, bytes / 4);
226 samples_sent += bytes / 4;
229 void out_register_libretro(struct out_driver *drv)
231 drv->name = "libretro";
232 drv->init = snd_init;
233 drv->finish = snd_finish;
234 drv->busy = snd_busy;
235 drv->feed = snd_feed;
239 void retro_set_environment(retro_environment_t cb)
241 static const struct retro_variable vars[] = {
242 { "frameskip", "Frameskip; 0|1|2|3" },
243 { "region", "Region; Auto|NTSC|PAL" },
245 { "neon_interlace_enable", "Enable interlacing mode(s); disabled|enabled" },
246 { "neon_enhancement_enable", "Enhanced resolution (slow); disabled|enabled" },
247 { "neon_enhancement_no_main", "Enhanced resolution speed hack; disabled|enabled" },
254 cb(RETRO_ENVIRONMENT_SET_VARIABLES, (void*)vars);
257 void retro_set_video_refresh(retro_video_refresh_t cb) { video_cb = cb; }
258 void retro_set_audio_sample(retro_audio_sample_t cb) { (void)cb; }
259 void retro_set_audio_sample_batch(retro_audio_sample_batch_t cb) { audio_batch_cb = cb; }
260 void retro_set_input_poll(retro_input_poll_t cb) { input_poll_cb = cb; }
261 void retro_set_input_state(retro_input_state_t cb) { input_state_cb = cb; }
263 unsigned retro_api_version(void)
265 return RETRO_API_VERSION;
268 void retro_set_controller_port_device(unsigned port, unsigned device)
272 void retro_get_system_info(struct retro_system_info *info)
274 memset(info, 0, sizeof(*info));
275 info->library_name = "PCSX-ReARMed";
276 info->library_version = "r19";
277 info->valid_extensions = "bin|cue|img|mdf|pbp|toc|cbn|m3u";
278 info->need_fullpath = true;
281 void retro_get_system_av_info(struct retro_system_av_info *info)
283 memset(info, 0, sizeof(*info));
284 info->timing.fps = is_pal_mode ? 50 : 60;
285 info->timing.sample_rate = 44100;
286 info->geometry.base_width = 320;
287 info->geometry.base_height = 240;
288 info->geometry.max_width = VOUT_MAX_WIDTH;
289 info->geometry.max_height = VOUT_MAX_HEIGHT;
290 info->geometry.aspect_ratio = 4.0 / 3.0;
294 size_t retro_serialize_size(void)
296 // it's currently 4380651 bytes, but have some reserved for future
306 static void *save_open(const char *name, const char *mode)
310 if (name == NULL || mode == NULL)
313 fp = malloc(sizeof(*fp));
317 fp->buf = (char *)name;
319 fp->is_write = (mode[0] == 'w' || mode[1] == 'w');
324 static int save_read(void *file, void *buf, u32 len)
326 struct save_fp *fp = file;
327 if (fp == NULL || buf == NULL)
330 memcpy(buf, fp->buf + fp->pos, len);
335 static int save_write(void *file, const void *buf, u32 len)
337 struct save_fp *fp = file;
338 if (fp == NULL || buf == NULL)
341 memcpy(fp->buf + fp->pos, buf, len);
346 static long save_seek(void *file, long offs, int whence)
348 struct save_fp *fp = file;
364 static void save_close(void *file)
366 struct save_fp *fp = file;
367 size_t r_size = retro_serialize_size();
371 if (fp->pos > r_size)
372 SysPrintf("ERROR: save buffer overflow detected\n");
373 else if (fp->is_write && fp->pos < r_size)
374 // make sure we don't save trash in leftover space
375 memset(fp->buf + fp->pos, 0, r_size - fp->pos);
379 bool retro_serialize(void *data, size_t size)
381 int ret = SaveState(data);
382 return ret == 0 ? true : false;
385 bool retro_unserialize(const void *data, size_t size)
387 int ret = LoadState(data);
388 return ret == 0 ? true : false;
392 void retro_cheat_reset(void)
397 void retro_cheat_set(unsigned index, bool enabled, const char *code)
402 // cheat funcs are destructive, need a copy..
403 strncpy(buf, code, sizeof(buf));
404 buf[sizeof(buf) - 1] = 0;
406 if (index < NumCheats)
407 ret = EditCheat(index, "", buf);
409 ret = AddCheat("", buf);
412 SysPrintf("Failed to set cheat %#u\n", index);
413 else if (index < NumCheats)
414 Cheats[index].Enabled = enabled;
417 /* multidisk support */
418 static bool disk_ejected;
419 static unsigned int disk_current_index;
420 static unsigned int disk_count;
421 static struct disks_state {
423 int internal_index; // for multidisk eboots
426 static bool disk_set_eject_state(bool ejected)
429 SetCdOpenCaseTime(ejected ? -1 : (time(NULL) + 2));
432 disk_ejected = ejected;
436 static bool disk_get_eject_state(void)
438 /* can't be controlled by emulated software */
442 static unsigned int disk_get_image_index(void)
444 return disk_current_index;
447 static bool disk_set_image_index(unsigned int index)
449 if (index >= sizeof(disks) / sizeof(disks[0]))
453 CdromLabel[0] = '\0';
455 if (disks[index].fname == NULL) {
456 SysPrintf("missing disk #%u\n", index);
459 // RetroArch specifies "no disk" with index == count,
460 // so don't fail here..
461 disk_current_index = index;
465 SysPrintf("switching to disk %u: \"%s\" #%d\n", index,
466 disks[index].fname, disks[index].internal_index);
468 cdrIsoMultidiskSelect = disks[index].internal_index;
469 set_cd_image(disks[index].fname);
470 if (ReloadCdromPlugin() < 0) {
471 SysPrintf("failed to load cdr plugin\n");
474 if (CDR_open() < 0) {
475 SysPrintf("failed to open cdr plugin\n");
480 SetCdOpenCaseTime(time(NULL) + 2);
484 disk_current_index = index;
488 static unsigned int disk_get_num_images(void)
493 static bool disk_replace_image_index(unsigned index,
494 const struct retro_game_info *info)
499 if (index >= sizeof(disks) / sizeof(disks[0]))
502 old_fname = disks[index].fname;
503 disks[index].fname = NULL;
504 disks[index].internal_index = 0;
507 disks[index].fname = strdup(info->path);
508 if (index == disk_current_index)
509 ret = disk_set_image_index(index);
512 if (old_fname != NULL)
518 static bool disk_add_image_index(void)
527 static struct retro_disk_control_callback disk_control = {
528 .set_eject_state = disk_set_eject_state,
529 .get_eject_state = disk_get_eject_state,
530 .get_image_index = disk_get_image_index,
531 .set_image_index = disk_set_image_index,
532 .get_num_images = disk_get_num_images,
533 .replace_image_index = disk_replace_image_index,
534 .add_image_index = disk_add_image_index,
537 // just in case, maybe a win-rt port in the future?
544 static char base_dir[PATH_MAX];
546 static bool read_m3u(const char *file)
550 FILE *f = fopen(file, "r");
554 while (fgets(line, sizeof(line), f) && disk_count < sizeof(disks) / sizeof(disks[0])) {
557 char *carrige_return = strchr(line, '\r');
559 *carrige_return = '\0';
560 char *newline = strchr(line, '\n');
566 snprintf(name, sizeof(name), "%s%c%s", base_dir, SLASH, line);
567 disks[disk_count++].fname = strdup(name);
572 return (disk_count != 0);
575 static void extract_directory(char *buf, const char *path, size_t size)
578 strncpy(buf, path, size - 1);
579 buf[size - 1] = '\0';
581 base = strrchr(buf, '/');
583 base = strrchr(buf, '\\');
595 /* Blackberry QNX doesn't have strcasestr */
598 * Find the first occurrence of find in s, ignore case.
601 strcasestr(const char *s, const char*find)
606 if ((c = *find++) != 0) {
607 c = tolower((unsigned char)c);
611 if ((sc = *s++) == 0)
613 } while ((char)tolower((unsigned char)sc) != c);
614 } while (strncasecmp(s, find, len) != 0);
621 bool retro_load_game(const struct retro_game_info *info)
624 bool is_m3u = (strcasestr(info->path, ".m3u") != NULL);
626 #ifdef FRONTEND_SUPPORTS_RGB565
627 enum retro_pixel_format fmt = RETRO_PIXEL_FORMAT_RGB565;
628 if (environ_cb(RETRO_ENVIRONMENT_SET_PIXEL_FORMAT, &fmt)) {
629 SysPrintf("RGB565 supported, using it\n");
633 if (info == NULL || info->path == NULL) {
634 SysPrintf("info->path required\n");
638 if (plugins_opened) {
643 for (i = 0; i < sizeof(disks) / sizeof(disks[0]); i++) {
644 if (disks[i].fname != NULL) {
645 free(disks[i].fname);
646 disks[i].fname = NULL;
648 disks[i].internal_index = 0;
651 disk_current_index = 0;
652 extract_directory(base_dir, info->path, sizeof(base_dir));
655 if (!read_m3u(info->path)) {
656 SysPrintf("failed to read m3u file\n");
661 disks[0].fname = strdup(info->path);
664 set_cd_image(disks[0].fname);
666 /* have to reload after set_cd_image for correct cdr plugin */
667 if (LoadPlugins() == -1) {
668 SysPrintf("failed to load plugins\n");
675 if (OpenPlugins() == -1) {
676 SysPrintf("failed to open plugins\n");
680 plugin_call_rearmed_cbs();
684 if (CheckCdrom() == -1) {
685 SysPrintf("unsupported/invalid CD image: %s\n", info->path);
691 if (LoadCdrom() == -1) {
692 SysPrintf("could not load CD-ROM!\n");
699 disk_count = cdrIsoMultidiskCount < 8 ? cdrIsoMultidiskCount : 8;
700 for (i = 1; i < sizeof(disks) / sizeof(disks[0]) && i < cdrIsoMultidiskCount; i++) {
701 disks[i].fname = strdup(info->path);
702 disks[i].internal_index = i;
709 bool retro_load_game_special(unsigned game_type, const struct retro_game_info *info, size_t num_info)
714 void retro_unload_game(void)
718 unsigned retro_get_region(void)
720 return is_pal_mode ? RETRO_REGION_PAL : RETRO_REGION_NTSC;
723 void *retro_get_memory_data(unsigned id)
725 if (id == RETRO_MEMORY_SAVE_RAM)
731 size_t retro_get_memory_size(unsigned id)
733 if (id == RETRO_MEMORY_SAVE_RAM)
739 void retro_reset(void)
744 static const unsigned short retro_psx_map[] = {
745 [RETRO_DEVICE_ID_JOYPAD_B] = 1 << DKEY_CROSS,
746 [RETRO_DEVICE_ID_JOYPAD_Y] = 1 << DKEY_SQUARE,
747 [RETRO_DEVICE_ID_JOYPAD_SELECT] = 1 << DKEY_SELECT,
748 [RETRO_DEVICE_ID_JOYPAD_START] = 1 << DKEY_START,
749 [RETRO_DEVICE_ID_JOYPAD_UP] = 1 << DKEY_UP,
750 [RETRO_DEVICE_ID_JOYPAD_DOWN] = 1 << DKEY_DOWN,
751 [RETRO_DEVICE_ID_JOYPAD_LEFT] = 1 << DKEY_LEFT,
752 [RETRO_DEVICE_ID_JOYPAD_RIGHT] = 1 << DKEY_RIGHT,
753 [RETRO_DEVICE_ID_JOYPAD_A] = 1 << DKEY_CIRCLE,
754 [RETRO_DEVICE_ID_JOYPAD_X] = 1 << DKEY_TRIANGLE,
755 [RETRO_DEVICE_ID_JOYPAD_L] = 1 << DKEY_L1,
756 [RETRO_DEVICE_ID_JOYPAD_R] = 1 << DKEY_R1,
757 [RETRO_DEVICE_ID_JOYPAD_L2] = 1 << DKEY_L2,
758 [RETRO_DEVICE_ID_JOYPAD_R2] = 1 << DKEY_R2,
759 [RETRO_DEVICE_ID_JOYPAD_L3] = 1 << DKEY_L3,
760 [RETRO_DEVICE_ID_JOYPAD_R3] = 1 << DKEY_R3,
762 #define RETRO_PSX_MAP_LEN (sizeof(retro_psx_map) / sizeof(retro_psx_map[0]))
764 static void update_variables(bool in_flight)
766 struct retro_variable var;
769 var.key = "frameskip";
771 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
772 pl_rearmed_cbs.frameskip = atoi(var.value);
777 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
780 if (strcmp(var.value, "Automatic") == 0)
782 else if (strcmp(var.value, "NTSC") == 0)
784 else if (strcmp(var.value, "PAL") == 0)
789 var.key = "neon_interlace_enable";
791 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
793 if (strcmp(var.value, "disabled") == 0)
794 pl_rearmed_cbs.gpu_neon.allow_interlace = 0;
795 else if (strcmp(var.value, "enabled") == 0)
796 pl_rearmed_cbs.gpu_neon.allow_interlace = 1;
800 var.key = "neon_enhancement_enable";
802 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
804 if (strcmp(var.value, "disabled") == 0)
805 pl_rearmed_cbs.gpu_neon.enhancement_enable = 0;
806 else if (strcmp(var.value, "enabled") == 0)
807 pl_rearmed_cbs.gpu_neon.enhancement_enable = 1;
811 var.key = "neon_enhancement_no_main";
813 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) || var.value)
815 if (strcmp(var.value, "disabled") == 0)
816 pl_rearmed_cbs.gpu_neon.enhancement_no_main = 0;
817 else if (strcmp(var.value, "enabled") == 0)
818 pl_rearmed_cbs.gpu_neon.enhancement_no_main = 1;
823 // inform core things about possible config changes
824 plugin_call_rearmed_cbs();
826 if (GPU_open != NULL && GPU_close != NULL) {
828 GPU_open(&gpuDisp, "PCSX", NULL);
841 bool updated = false;
842 if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE, &updated) && updated)
843 update_variables(true);
846 for (i = 0; i < RETRO_PSX_MAP_LEN; i++)
847 if (input_state_cb(1, RETRO_DEVICE_JOYPAD, 0, i))
848 in_keystate |= retro_psx_map[i];
850 for (i = 0; i < RETRO_PSX_MAP_LEN; i++)
851 if (input_state_cb(0, RETRO_DEVICE_JOYPAD, 0, i))
852 in_keystate |= retro_psx_map[i];
857 samples_to_send += is_pal_mode ? 44100 / 50 : 44100 / 60;
859 video_cb((vout_fb_dirty || !vout_can_dupe) ? vout_buf : NULL,
860 vout_width, vout_height, vout_width * 2);
864 void retro_init(void)
866 const char *bios[] = { "scph1001", "scph5501", "scph7001" };
872 ret = emu_core_preinit();
873 ret |= emu_core_init();
875 SysPrintf("PCSX init failed.\n");
879 vout_buf = malloc(VOUT_MAX_WIDTH * VOUT_MAX_HEIGHT * 2);
881 if (environ_cb(RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY, &dir) && dir)
883 snprintf(Config.BiosDir, sizeof(Config.BiosDir), "%s/", dir);
885 for (i = 0; i < sizeof(bios) / sizeof(bios[0]); i++) {
886 snprintf(path, sizeof(path), "%s/%s.bin", dir, bios[i]);
887 f = fopen(path, "r");
889 snprintf(Config.Bios, sizeof(Config.Bios), "%s.bin", bios[i]);
895 SysPrintf("found BIOS file: %s\n", Config.Bios);
900 SysPrintf("no BIOS files found.\n");
901 struct retro_message msg =
903 "no BIOS found, expect bugs!",
906 environ_cb(RETRO_ENVIRONMENT_SET_MESSAGE, (void*)&msg);
910 environ_cb(RETRO_ENVIRONMENT_SET_PERFORMANCE_LEVEL, &level);
912 environ_cb(RETRO_ENVIRONMENT_GET_CAN_DUPE, &vout_can_dupe);
913 environ_cb(RETRO_ENVIRONMENT_SET_DISK_CONTROL_INTERFACE, &disk_control);
915 /* Set how much slower PSX CPU runs * 100 (so that 200 is 2 times)
916 * we have to do this because cache misses and some IO penalties
917 * are not emulated. Warning: changing this may break compatibility. */
918 #ifdef __ARM_ARCH_7A__
919 cycle_multiplier = 175;
921 cycle_multiplier = 200;
926 init_memcard(Mcd1Data);
928 SaveFuncs.open = save_open;
929 SaveFuncs.read = save_read;
930 SaveFuncs.write = save_write;
931 SaveFuncs.seek = save_seek;
932 SaveFuncs.close = save_close;
934 update_variables(false);
937 void retro_deinit(void)