libretro: improve retro_memory_map
[pcsx_rearmed.git] / frontend / main.c
1 /*
2  * (C) notaz, 2010-2012
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 #include <stdio.h>
9 #include <string.h>
10 #include <stdarg.h>
11 #include <unistd.h>
12 #include <signal.h>
13 #include <time.h>
14 #if !defined(_WIN32) && !defined(NO_DYLIB)
15 #include <dlfcn.h>
16 #endif
17
18 #include "main.h"
19 #include "plugin.h"
20 #include "plugin_lib.h"
21 #include "pcnt.h"
22 #include "menu.h"
23 #include "plat.h"
24 #include "../libpcsxcore/misc.h"
25 #include "../libpcsxcore/cheat.h"
26 #include "../libpcsxcore/sio.h"
27 #include "../libpcsxcore/database.h"
28 #include "../libpcsxcore/new_dynarec/new_dynarec.h"
29 #include "../plugins/cdrcimg/cdrcimg.h"
30 #include "../plugins/dfsound/spu_config.h"
31 #include "arm_features.h"
32 #include "revision.h"
33
34 #if defined(__has_builtin)
35 #define DO_CPU_CHECKS __has_builtin(__builtin_cpu_init)
36 #elif defined(__x86_64__) || defined(__i386__)
37 #define DO_CPU_CHECKS 1
38 #else
39 #define DO_CPU_CHECKS 0
40 #endif
41
42 #ifndef NO_FRONTEND
43 #include "libpicofe/input.h"
44 #include "libpicofe/plat.h"
45 #include "libpicofe/readpng.h"
46
47 static void toggle_fast_forward(int force_off);
48 static void check_profile(void);
49 static void check_memcards(void);
50 #endif
51 #ifndef BOOT_MSG
52 #define BOOT_MSG "Booting up..."
53 #endif
54
55 // don't include debug.h - it breaks ARM build (R1 redefined)
56 static void StartDebugger() {}
57 static void StopDebugger() {}
58
59 int ready_to_go, g_emu_want_quit, g_emu_resetting;
60 unsigned long gpuDisp;
61 char cfgfile_basename[MAXPATHLEN];
62 int state_slot;
63 enum sched_action emu_action, emu_action_old;
64 char hud_msg[64];
65 int hud_new_msg;
66
67 static void make_path(char *buf, size_t size, const char *dir, const char *fname)
68 {
69         if (fname)
70                 snprintf(buf, size, ".%s%s", dir, fname);
71         else
72                 snprintf(buf, size, ".%s", dir);
73 }
74 #define MAKE_PATH(buf, dir, fname) \
75         make_path(buf, sizeof(buf), dir, fname)
76
77 static int get_gameid_filename(char *buf, int size, const char *fmt, int i) {
78         char trimlabel[33];
79         int j;
80
81         strncpy(trimlabel, CdromLabel, 32);
82         trimlabel[32] = 0;
83         for (j = 31; j >= 0; j--)
84                 if (trimlabel[j] == ' ')
85                         trimlabel[j] = 0;
86                 else
87                         continue;
88
89         snprintf(buf, size, fmt, trimlabel, CdromId, i);
90
91         return 0;
92 }
93
94 void set_cd_image(const char *fname)
95 {
96         const char *ext = NULL;
97         
98         if (fname != NULL)
99                 ext = strrchr(fname, '.');
100
101         if (ext && (
102             strcasecmp(ext, ".z") == 0 || strcasecmp(ext, ".bz") == 0 ||
103             strcasecmp(ext, ".znx") == 0 /*|| strcasecmp(ext, ".pbp") == 0*/)) {
104                 SetIsoFile(NULL);
105                 cdrcimg_set_fname(fname);
106                 strcpy(Config.Cdr, "builtin_cdrcimg");
107         } else {
108                 SetIsoFile(fname);
109                 strcpy(Config.Cdr, "builtin_cdr");
110         }
111 }
112
113 static void set_default_paths(void)
114 {
115 #ifndef NO_FRONTEND
116         snprintf(Config.PatchesDir, sizeof(Config.PatchesDir), "." PATCHES_DIR);
117         MAKE_PATH(Config.Mcd1, MEMCARD_DIR, "card1.mcd");
118         MAKE_PATH(Config.Mcd2, MEMCARD_DIR, "card2.mcd");
119         strcpy(Config.BiosDir, "bios");
120 #endif
121
122         strcpy(Config.PluginsDir, "plugins");
123         strcpy(Config.Gpu, "builtin_gpu");
124         strcpy(Config.Spu, "builtin_spu");
125         strcpy(Config.Cdr, "builtin_cdr");
126         strcpy(Config.Pad1, "builtin_pad");
127         strcpy(Config.Pad2, "builtin_pad");
128         strcpy(Config.Net, "Disabled");
129 }
130
131 void emu_set_default_config(void)
132 {
133         // try to set sane config on which most games work
134         Config.Xa = Config.Cdda = 0;
135         Config.icache_emulation = 0;
136         Config.PsxAuto = 1;
137         Config.cycle_multiplier = CYCLE_MULT_DEFAULT;
138         Config.GpuListWalking = -1;
139         Config.FractionalFramerate = -1;
140
141         pl_rearmed_cbs.gpu_neon.allow_interlace = 2; // auto
142         pl_rearmed_cbs.gpu_neon.enhancement_enable =
143         pl_rearmed_cbs.gpu_neon.enhancement_no_main = 0;
144         pl_rearmed_cbs.gpu_neon.enhancement_tex_adj = 1;
145         pl_rearmed_cbs.gpu_peops.iUseDither = 0;
146         pl_rearmed_cbs.gpu_peops.dwActFixes = 1<<7;
147         pl_rearmed_cbs.gpu_unai.ilace_force = 0;
148         pl_rearmed_cbs.gpu_unai.pixel_skip = 0;
149         pl_rearmed_cbs.gpu_unai.lighting = 1;
150         pl_rearmed_cbs.gpu_unai.fast_lighting = 0;
151         pl_rearmed_cbs.gpu_unai.blending = 1;
152         pl_rearmed_cbs.gpu_unai.dithering = 0;
153         pl_rearmed_cbs.gpu_unai_old.abe_hack =
154         pl_rearmed_cbs.gpu_unai_old.no_light =
155         pl_rearmed_cbs.gpu_unai_old.no_blend = 0;
156         memset(&pl_rearmed_cbs.gpu_peopsgl, 0, sizeof(pl_rearmed_cbs.gpu_peopsgl));
157         pl_rearmed_cbs.gpu_peopsgl.iVRamSize = 64;
158         pl_rearmed_cbs.gpu_peopsgl.iTexGarbageCollection = 1;
159
160         spu_config.iUseReverb = 1;
161         spu_config.iUseInterpolation = 1;
162         spu_config.iXAPitch = 0;
163         spu_config.iVolume = 768;
164         spu_config.iTempo = 0;
165         // may cause issues, no effect if only 1 core is detected
166         spu_config.iUseThread = 0;
167 #if defined(HAVE_PRE_ARMV7) && !defined(_3DS) /* XXX GPH hack */
168         spu_config.iUseReverb = 0;
169         spu_config.iUseInterpolation = 0;
170 #ifndef HAVE_LIBRETRO
171         spu_config.iTempo = 1;
172 #endif
173 #endif
174         new_dynarec_hacks = 0;
175
176         in_type[0] = PSE_PAD_TYPE_STANDARD;
177         in_type[1] = PSE_PAD_TYPE_STANDARD;
178 }
179
180 void do_emu_action(void)
181 {
182         int ret;
183
184         emu_action_old = emu_action;
185
186         switch (emu_action) {
187         case SACTION_LOAD_STATE:
188                 ret = emu_load_state(state_slot);
189                 snprintf(hud_msg, sizeof(hud_msg), ret == 0 ? "LOADED" : "FAIL!");
190                 break;
191         case SACTION_SAVE_STATE:
192                 ret = emu_save_state(state_slot);
193                 snprintf(hud_msg, sizeof(hud_msg), ret == 0 ? "SAVED" : "FAIL!");
194                 break;
195 #ifndef NO_FRONTEND
196         case SACTION_ENTER_MENU:
197                 toggle_fast_forward(1);
198                 menu_loop();
199                 return;
200         case SACTION_NEXT_SSLOT:
201                 state_slot++;
202                 if (state_slot > 9)
203                         state_slot = 0;
204                 goto do_state_slot;
205         case SACTION_PREV_SSLOT:
206                 state_slot--;
207                 if (state_slot < 0)
208                         state_slot = 9;
209 do_state_slot:
210                 snprintf(hud_msg, sizeof(hud_msg), "STATE SLOT %d [%s]", state_slot,
211                         emu_check_state(state_slot) == 0 ? "USED" : "FREE");
212                 hud_new_msg = 3;
213                 SysPrintf("* %s\n", hud_msg);
214                 break;
215         case SACTION_TOGGLE_FSKIP:
216                 pl_rearmed_cbs.fskip_advice = 0;
217                 pl_rearmed_cbs.frameskip++;
218                 if (pl_rearmed_cbs.frameskip > 1)
219                         pl_rearmed_cbs.frameskip = -1;
220                 snprintf(hud_msg, sizeof(hud_msg), "FRAMESKIP: %s",
221                         pl_rearmed_cbs.frameskip == -1 ? "AUTO" :
222                         pl_rearmed_cbs.frameskip == 0 ? "OFF" : "1" );
223                 plugin_call_rearmed_cbs();
224                 break;
225         case SACTION_SWITCH_DISPMODE:
226                 pl_switch_dispmode();
227                 plugin_call_rearmed_cbs();
228                 if (GPU_open != NULL && GPU_close != NULL) {
229                         GPU_close();
230                         GPU_open(&gpuDisp, "PCSX", NULL);
231                 }
232                 break;
233         case SACTION_FAST_FORWARD:
234                 toggle_fast_forward(0);
235                 plugin_call_rearmed_cbs();
236                 break;
237         case SACTION_TOGGLE_FPS:
238                 if ((g_opts & (OPT_SHOWFPS|OPT_SHOWCPU))
239                     == (OPT_SHOWFPS|OPT_SHOWCPU))
240                         g_opts &= ~(OPT_SHOWFPS|OPT_SHOWCPU);
241                 else if (g_opts & OPT_SHOWFPS)
242                         g_opts |= OPT_SHOWCPU;
243                 else
244                         g_opts |= OPT_SHOWFPS;
245                 break;
246         case SACTION_TOGGLE_FULLSCREEN:
247                 plat_target.vout_fullscreen = !plat_target.vout_fullscreen;
248                 if (GPU_open != NULL && GPU_close != NULL) {
249                         GPU_close();
250                         GPU_open(&gpuDisp, "PCSX", NULL);
251                 }
252                 break;
253         case SACTION_SCREENSHOT:
254                 {
255                         char buf[MAXPATHLEN];
256                         void *scrbuf;
257                         int w, h, bpp;
258                         time_t t = time(NULL);
259                         struct tm *tb = localtime(&t);
260                         int ti = tb->tm_yday * 1000000 + tb->tm_hour * 10000 +
261                                 tb->tm_min * 100 + tb->tm_sec;
262
263                         scrbuf = pl_prepare_screenshot(&w, &h, &bpp);
264                         get_gameid_filename(buf, sizeof(buf),
265                                 "screenshots/%.32s-%.9s.%d.png", ti);
266                         ret = -1;
267                         if (scrbuf != 0 && bpp == 16)
268                                 ret = writepng(buf, scrbuf, w, h);
269                         if (ret == 0)
270                                 snprintf(hud_msg, sizeof(hud_msg), "SCREENSHOT TAKEN");
271                         break;
272                 }
273         case SACTION_VOLUME_UP:
274         case SACTION_VOLUME_DOWN:
275                 {
276                         static int volume;
277                         plat_target_step_volume(&volume,
278                                 emu_action == SACTION_VOLUME_UP ? 1 : -1);
279                 }
280                 return;
281         case SACTION_MINIMIZE:
282                 if (GPU_close != NULL)
283                         GPU_close();
284
285                 plat_minimize();
286
287                 if (GPU_open != NULL) {
288                         ret = GPU_open(&gpuDisp, "PCSX", NULL);
289                         if (ret)
290                                 SysMessage("GPU_open returned %d", ret);
291                 }
292                 return;
293         case SACTION_ANALOG_TOGGLE:
294                 ret = padToggleAnalog(0);
295                 snprintf(hud_msg, sizeof(hud_msg), "ANALOG %s", ret ? "ON" : "OFF");
296                 break;
297 #endif
298         default:
299                 return;
300         }
301
302         hud_new_msg = 3;
303 }
304
305 static char basic_lcase(char c)
306 {
307         if ('A' <= c && c <= 'Z')
308                 return c - 'A' + 'a';
309         return c;
310 }
311
312 static int cdidcmp(const char *id1, const char *id2)
313 {
314         while (*id1 != 0 && *id2 != 0) {
315                 if (*id1 == '_') { id1++; continue; }
316                 if (*id2 == '_') { id2++; continue; }
317                 if (basic_lcase(*id1) != basic_lcase(*id2))
318                         break;
319                 id1++;
320                 id2++;
321         }
322
323         return *id1 - *id2;
324 }
325
326 static void parse_cwcheat(void)
327 {
328         char line[256], buf[256], name[256], *p;
329         int newcheat = 1;
330         u32 a, v;
331         FILE *f;
332
333         f = fopen("cheatpops.db", "r");
334         if (f == NULL)
335                 return;
336
337         /* find the game */
338         while (fgets(line, sizeof(line), f)) {
339                 if (sscanf(line, "_S %63s", buf) != 1)
340                         continue;
341                 if (cdidcmp(buf, CdromId) == 0)
342                         break;
343         }
344
345         if (feof(f))
346                 goto out;
347
348         SysPrintf("cwcheat section found for %s\n", CdromId);
349         while (fgets(line, sizeof(line), f))
350         {
351                 p = line + strlen(line);
352                 for (p--; p >= line && (*p == '\r' || *p == '\n' || *p == ' '); p--)
353                         *p = 0;
354                 if (*p == 0 || *p == '#' || *p == ';')
355                         continue;
356
357                 if (strncmp(line, "_S", 2) == 0)
358                         break;
359                 if (strncmp(line, "_G", 2) == 0) {
360                         SysPrintf("  cwcheat game name: '%s'\n", line + 3);
361                         continue;
362                 }
363                 if (strncmp(line, "_C0", 3) == 0) {
364                         if (!newcheat && Cheats[NumCheats - 1].n == 0) {
365                                 SysPrintf("cheat '%s' failed to parse\n", name);
366                                 free(Cheats[NumCheats - 1].Descr);
367                                 NumCheats--;
368                         }
369                         snprintf(name, sizeof(name), "%s", line + 4);
370                         newcheat = 1;
371                         continue;
372                 }
373                 if (sscanf(line, "_L %x %x", &a, &v) != 2) {
374                         SysPrintf("line failed to parse: '%s'\n", line);
375                         continue;
376                 }
377
378                 if (newcheat) {
379                         if (NumCheats >= NumCheatsAllocated) {
380                                 NumCheatsAllocated += 16;
381                                 Cheats = realloc(Cheats, sizeof(Cheat) *
382                                                 NumCheatsAllocated);
383                                 if (Cheats == NULL)
384                                         break;
385                         }
386                         Cheats[NumCheats].Descr = strdup(name);
387                         Cheats[NumCheats].Enabled = 0;
388                         Cheats[NumCheats].WasEnabled = 0;
389                         Cheats[NumCheats].First = NumCodes;
390                         Cheats[NumCheats].n = 0;
391                         NumCheats++;
392                         newcheat = 0;
393                 }
394
395                 if (NumCodes >= NumCodesAllocated) {
396                         NumCodesAllocated += 16;
397                         CheatCodes = realloc(CheatCodes, sizeof(CheatCode) *
398                                 NumCodesAllocated);
399                         if (CheatCodes == NULL)
400                                 break;
401                 }
402                 CheatCodes[NumCodes].Addr = a;
403                 CheatCodes[NumCodes].Val = v;
404                 NumCodes++;
405                 Cheats[NumCheats - 1].n++;
406         }
407
408 out:
409         fclose(f);
410 }
411
412 void emu_on_new_cd(int show_hud_msg)
413 {
414         ClearAllCheats();
415         parse_cwcheat();
416
417         if (Config.HLE) {
418                 SysPrintf("note: running with HLE BIOS, expect compatibility problems\n");
419                 SysPrintf("----------------------------------------------------------\n");
420         }
421         if (Config.TurboCD)
422                 SysPrintf("note: TurboCD is enabled, this breaks games\n");
423
424         if (show_hud_msg) {
425                 if (check_unsatisfied_libcrypt())
426                         snprintf(hud_msg, sizeof(hud_msg),
427                                 "LibCrypt protected game with missing SBI detected");
428                 else
429                         snprintf(hud_msg, sizeof(hud_msg), BOOT_MSG);
430                 hud_new_msg = 3;
431         }
432 }
433
434 static void log_wrong_cpu(void)
435 {
436 #if DO_CPU_CHECKS
437         __builtin_cpu_init();
438         #define CHECK_CPU(name) if (!__builtin_cpu_supports(name)) \
439                 SysPrintf("ERROR: compiled for " name ", which is unsupported by the CPU\n")
440 #ifdef __SSE2__
441         CHECK_CPU("sse2");
442 #endif
443 #ifdef __SSSE3__
444         CHECK_CPU("ssse3");
445 #endif
446 #ifdef __SSE4_1__
447         CHECK_CPU("sse4.1");
448 #endif
449 #endif // DO_CPU_CHECKS
450 }
451
452 #define MKSTR2(x) #x
453 #define MKSTR(x) MKSTR2(x)
454 static const char *get_build_info(void)
455 {
456         return " ("
457 #ifdef __VERSION__
458                 "cc " __VERSION__ " "
459 #endif
460 #if defined(__SIZEOF_POINTER__) && __SIZEOF_POINTER__ == 8
461                 "64bit "
462 #elif defined(__SIZEOF_POINTER__) && __SIZEOF_POINTER__ == 4
463                 "32bit "
464 #endif
465 #if defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
466                 "be "
467 #endif
468 #if defined(__PIC__) || defined(__pic__)
469                 "pic "
470 #endif
471 #if defined(__aarch64__)
472                 "arm64"
473 #elif defined(__arm__)
474                 "arm"
475 #endif
476 #ifdef __ARM_ARCH
477                 "v" MKSTR(__ARM_ARCH) " "
478 #endif
479 #if defined(__AVX__)
480                 "avx "
481 #elif defined(__SSSE3__)
482                 "ssse3 "
483 #elif defined(__ARM_NEON) || defined(__ARM_NEON__)
484                 "neon "
485 #endif
486 #if defined(LIGHTREC)
487                 "lightrec "
488 #elif !defined(DRC_DISABLE)
489                 "ari64 "
490 #endif
491                 "gpu=" MKSTR(BUILTIN_GPU)
492                 ")";
493 }
494
495 int emu_core_preinit(void)
496 {
497         // what is the name of the config file?
498         // it may be redefined by -cfg on the command line
499         strcpy(cfgfile_basename, "pcsx.cfg");
500
501 #ifdef IOS
502         emuLog = fopen("/User/Documents/pcsxr.log", "w");
503         if (emuLog == NULL)
504                 emuLog = fopen("pcsxr.log", "w");
505         if (emuLog == NULL)
506 #endif
507         emuLog = stdout;
508
509         log_wrong_cpu();
510
511         SetIsoFile(NULL);
512
513         memset(&Config, 0, sizeof(Config));
514
515         set_default_paths();
516         emu_set_default_config();
517         strcpy(Config.Bios, "HLE");
518
519         return 0;
520 }
521
522 int emu_core_init(void)
523 {
524         SysPrintf("Starting PCSX-ReARMed " REV "%s\n", get_build_info());
525
526 #ifndef NO_FRONTEND
527         check_profile();
528         check_memcards();
529 #endif
530
531         if (EmuInit() == -1) {
532                 SysPrintf("PSX emulator couldn't be initialized.\n");
533                 return -1;
534         }
535
536         LoadMcds(Config.Mcd1, Config.Mcd2);
537
538         if (Config.Debug) {
539                 StartDebugger();
540         }
541
542         return 0;
543 }
544
545 void emu_core_ask_exit(void)
546 {
547         stop++;
548         g_emu_want_quit = 1;
549 }
550
551 #ifndef NO_FRONTEND
552
553 #include <sys/stat.h>
554 #include <sys/types.h>
555
556 static void create_profile_dir(const char *directory) {
557         char path[MAXPATHLEN];
558
559         MAKE_PATH(path, directory, NULL);
560         mkdir(path, S_IRWXU | S_IRWXG);
561 }
562
563 static void check_profile(void) {
564         // make sure that ~/.pcsx exists
565         create_profile_dir(PCSX_DOT_DIR);
566
567         create_profile_dir(BIOS_DIR);
568         create_profile_dir(MEMCARD_DIR);
569         create_profile_dir(STATES_DIR);
570         create_profile_dir(PLUGINS_DIR);
571         create_profile_dir(PLUGINS_CFG_DIR);
572         create_profile_dir(CHEATS_DIR);
573         create_profile_dir(PATCHES_DIR);
574         create_profile_dir(PCSX_DOT_DIR "cfg");
575         create_profile_dir("/screenshots/");
576 }
577
578 static void check_memcards(void)
579 {
580         char buf[MAXPATHLEN];
581         FILE *f;
582         int i;
583
584         for (i = 1; i <= 9; i++) {
585                 snprintf(buf, sizeof(buf), ".%scard%d.mcd", MEMCARD_DIR, i);
586
587                 f = fopen(buf, "rb");
588                 if (f == NULL) {
589                         SysPrintf("Creating memcard: %s\n", buf);
590                         CreateMcd(buf);
591                 }
592                 else
593                         fclose(f);
594         }
595 }
596
597 int main(int argc, char *argv[])
598 {
599         char file[MAXPATHLEN] = "";
600         char path[MAXPATHLEN];
601         char isofilename[MAXPATHLEN];
602         const char *cdfile = NULL;
603         const char *loadst_f = NULL;
604         int psxout = 0;
605         int loadst = 0;
606         int i;
607
608         emu_core_preinit();
609
610         // read command line options
611         for (i = 1; i < argc; i++) {
612                      if (!strcmp(argv[i], "-psxout")) psxout = 1;
613                 else if (!strcmp(argv[i], "-load")) loadst = atol(argv[++i]);
614                 else if (!strcmp(argv[i], "-cfg")) {
615                         if (i+1 >= argc) break;
616                         strncpy(cfgfile_basename, argv[++i], MAXPATHLEN-100);   /* TODO buffer overruns */
617                         SysPrintf("Using config file %s.\n", cfgfile_basename);
618                 }
619                 else if (!strcmp(argv[i], "-cdfile")) {
620                         if (i+1 >= argc) break;
621                         strncpy(isofilename, argv[++i], MAXPATHLEN);
622                         if (isofilename[0] != '/') {
623                                 getcwd(path, MAXPATHLEN);
624                                 if (strlen(path) + strlen(isofilename) + 1 < MAXPATHLEN) {
625                                         strcat(path, "/");
626                                         strcat(path, isofilename);
627                                         strcpy(isofilename, path);
628                                 } else
629                                         isofilename[0] = 0;
630                         }
631
632                         cdfile = isofilename;
633                 }
634                 else if (!strcmp(argv[i], "-loadf")) {
635                         if (i+1 >= argc) break;
636                         loadst_f = argv[++i];
637                 }
638                 else if (!strcmp(argv[i], "-h") ||
639                          !strcmp(argv[i], "-help") ||
640                          !strcmp(argv[i], "--help")) {
641                          printf("PCSX-ReARMed " REV "\n");
642                          printf("%s\n", _(
643                                                         " pcsx [options] [file]\n"
644                                                         "\toptions:\n"
645                                                         "\t-cdfile FILE\tRuns a CD image file\n"
646                                                         "\t-cfg FILE\tLoads desired configuration file (default: ~/.pcsx/pcsx.cfg)\n"
647                                                         "\t-psxout\t\tEnable PSX output\n"
648                                                         "\t-load STATENUM\tLoads savestate STATENUM (1-5)\n"
649                                                         "\t-h -help\tDisplay this message\n"
650                                                         "\tfile\t\tLoads a PSX EXE file\n"));
651                          return 0;
652                 } else {
653                         strncpy(file, argv[i], MAXPATHLEN);
654                         if (file[0] != '/') {
655                                 getcwd(path, MAXPATHLEN);
656                                 if (strlen(path) + strlen(file) + 1 < MAXPATHLEN) {
657                                         strcat(path, "/");
658                                         strcat(path, file);
659                                         strcpy(file, path);
660                                 } else
661                                         file[0] = 0;
662                         }
663                 }
664         }
665
666         if (cdfile)
667                 set_cd_image(cdfile);
668
669         // frontend stuff
670         // init input but leave probing to platform code,
671         // they add input drivers and may need to modify them after probe
672         in_init();
673         pl_init();
674         plat_init();
675         menu_init(); // loads config
676
677         if (emu_core_init() != 0)
678                 return 1;
679
680         if (psxout)
681                 Config.PsxOut = 1;
682
683         if (LoadPlugins() == -1) {
684                 // FIXME: this recovery doesn't work, just delete bad config and bail out
685                 // SysMessage("could not load plugins, retrying with defaults\n");
686                 set_default_paths();
687                 snprintf(path, sizeof(path), "." PCSX_DOT_DIR "%s", cfgfile_basename);
688                 remove(path);
689                 SysMessage("Failed loading plugins!");
690                 return 1;
691         }
692         pcnt_hook_plugins();
693
694         if (OpenPlugins() == -1) {
695                 return 1;
696         }
697         plugin_call_rearmed_cbs();
698
699         CheckCdrom();
700         SysReset();
701
702         if (file[0] != '\0') {
703                 if (Load(file) != -1)
704                         ready_to_go = 1;
705         } else {
706                 if (cdfile) {
707                         if (LoadCdrom() == -1) {
708                                 ClosePlugins();
709                                 SysPrintf(_("Could not load CD-ROM!\n"));
710                                 return -1;
711                         }
712                         emu_on_new_cd(!loadst);
713                         ready_to_go = 1;
714                 }
715         }
716
717         if (loadst_f) {
718                 int ret = LoadState(loadst_f);
719                 SysPrintf("%s state file: %s\n",
720                         ret ? "failed to load" : "loaded", loadst_f);
721                 ready_to_go |= ret == 0;
722         }
723
724         if (ready_to_go) {
725                 if (menu_load_config(1) != 0)
726                         menu_load_config(0);
727                 menu_prepare_emu();
728
729                 // If a state has been specified, then load that
730                 if (loadst) {
731                         int ret = emu_load_state(loadst - 1);
732                         SysPrintf("%s state %d\n",
733                                 ret ? "failed to load" : "loaded", loadst);
734                 }
735         }
736         else
737                 menu_loop();
738
739         pl_start_watchdog();
740
741         while (!g_emu_want_quit)
742         {
743                 stop = 0;
744                 emu_action = SACTION_NONE;
745
746                 psxCpu->Execute();
747                 if (emu_action != SACTION_NONE)
748                         do_emu_action();
749         }
750
751         printf("Exit..\n");
752         ClosePlugins();
753         SysClose();
754         menu_finish();
755         plat_finish();
756
757         return 0;
758 }
759
760 static void toggle_fast_forward(int force_off)
761 {
762         static int fast_forward;
763         static int normal_g_opts;
764         static int normal_enhancement_enable;
765         //static int normal_frameskip;
766
767         if (force_off && !fast_forward)
768                 return;
769
770         fast_forward = !fast_forward;
771         if (fast_forward) {
772                 normal_g_opts = g_opts;
773                 //normal_frameskip = pl_rearmed_cbs.frameskip;
774                 normal_enhancement_enable =
775                         pl_rearmed_cbs.gpu_neon.enhancement_enable;
776
777                 g_opts |= OPT_NO_FRAMELIM;
778                 // pl_rearmed_cbs.frameskip = 3; // too broken
779                 pl_rearmed_cbs.gpu_neon.enhancement_enable = 0;
780         } else {
781                 g_opts = normal_g_opts;
782                 //pl_rearmed_cbs.frameskip = normal_frameskip;
783                 pl_rearmed_cbs.gpu_neon.enhancement_enable =
784                         normal_enhancement_enable;
785
786                 pl_timing_prepare(Config.PsxType);
787         }
788
789         if (!force_off)
790                 snprintf(hud_msg, sizeof(hud_msg), "FAST FORWARD %s",
791                         fast_forward ? "ON" : "OFF");
792 }
793
794 static void SignalExit(int sig) {
795         // only to restore framebuffer/resolution on some devices
796         plat_finish();
797         _exit(1);
798 }
799 #endif
800
801 void SysRunGui() {
802         printf("SysRunGui\n");
803 }
804
805 static void CALLBACK dummy_lace()
806 {
807 }
808
809 void SysReset() {
810         // rearmed hack: EmuReset() runs some code when real BIOS is used,
811         // but we usually do reset from menu while GPU is not open yet,
812         // so we need to prevent updateLace() call..
813         void *real_lace = GPU_updateLace;
814         GPU_updateLace = dummy_lace;
815         g_emu_resetting = 1;
816
817         // reset can run code, timing must be set
818         pl_timing_prepare(Config.PsxType);
819
820         // hmh core forgets this
821         CDR_stop();
822    
823         EmuReset();
824
825         GPU_updateLace = real_lace;
826         g_emu_resetting = 0;
827 }
828
829 void SysClose() {
830         EmuShutdown();
831         ReleasePlugins();
832
833         StopDebugger();
834
835         if (emuLog != NULL && emuLog != stdout && emuLog != stderr) {
836                 fclose(emuLog);
837                 emuLog = NULL;
838         }
839 }
840
841 int get_state_filename(char *buf, int size, int i) {
842         return get_gameid_filename(buf, size,
843                 "." STATES_DIR "%.32s-%.9s.%3.3d", i);
844 }
845
846 int emu_check_state(int slot)
847 {
848         char fname[MAXPATHLEN];
849         int ret;
850
851         ret = get_state_filename(fname, sizeof(fname), slot);
852         if (ret != 0)
853                 return ret;
854
855         return CheckState(fname);
856 }
857
858 int emu_save_state(int slot)
859 {
860         char fname[MAXPATHLEN];
861         int ret;
862
863         ret = get_state_filename(fname, sizeof(fname), slot);
864         if (ret != 0)
865                 return ret;
866
867         ret = SaveState(fname);
868 #if defined(HAVE_PRE_ARMV7) && !defined(_3DS) && !defined(__SWITCH__) /* XXX GPH hack */
869         sync();
870 #endif
871         SysPrintf("* %s \"%s\" [%d]\n",
872                 ret == 0 ? "saved" : "failed to save", fname, slot);
873         return ret;
874 }
875
876 int emu_load_state(int slot)
877 {
878         char fname[MAXPATHLEN];
879         int ret;
880
881         hud_msg[0] = 0;
882
883         ret = get_state_filename(fname, sizeof(fname), slot);
884         if (ret != 0)
885                 return ret;
886
887         return LoadState(fname);
888 }
889
890 #ifndef HAVE_LIBRETRO
891 #ifndef ANDROID
892
893 void SysPrintf(const char *fmt, ...) {
894         va_list list;
895
896         va_start(list, fmt);
897         vfprintf(emuLog, fmt, list);
898         va_end(list);
899         fflush(emuLog);
900 }
901
902 #else
903
904 #include <android/log.h>
905
906 void SysPrintf(const char *fmt, ...) {
907         va_list list;
908
909         va_start(list, fmt);
910         __android_log_vprint(ANDROID_LOG_INFO, "PCSX", fmt, list);
911         va_end(list);
912 }
913
914 #endif
915 #endif /* HAVE_LIBRETRO */
916
917 void SysMessage(const char *fmt, ...) {
918         va_list list;
919         char msg[512];
920         int ret;
921
922         va_start(list, fmt);
923         ret = vsnprintf(msg, sizeof(msg), fmt, list);
924         va_end(list);
925
926         if (ret < sizeof(msg) && msg[ret - 1] == '\n')
927                 msg[ret - 1] = 0;
928
929         SysPrintf("%s\n", msg);
930 }
931
932 #define PARSEPATH(dst, src) \
933         ptr = src + strlen(src); \
934         while (*ptr != '\\' && ptr != src) ptr--; \
935         if (ptr != src) { \
936                 strcpy(dst, ptr+1); \
937         }
938
939 static int _OpenPlugins(void) {
940         int ret;
941
942 #ifndef NO_FRONTEND
943         signal(SIGINT, SignalExit);
944         signal(SIGPIPE, SignalExit);
945 #endif
946
947         ret = CDR_open();
948         if (ret < 0) { SysMessage(_("Error opening CD-ROM plugin!")); return -1; }
949         ret = SPU_open();
950         if (ret < 0) { SysMessage(_("Error opening SPU plugin!")); return -1; }
951         SPU_registerCallback(SPUirq);
952         SPU_registerScheduleCb(SPUschedule);
953         // pcsx-rearmed: we handle gpu elsewhere
954         //ret = GPU_open(&gpuDisp, "PCSX", NULL);
955         //if (ret < 0) { SysMessage(_("Error opening GPU plugin!")); return -1; }
956         ret = PAD1_open(&gpuDisp);
957         if (ret < 0) { SysMessage(_("Error opening Controller 1 plugin!")); return -1; }
958         ret = PAD2_open(&gpuDisp);
959         if (ret < 0) { SysMessage(_("Error opening Controller 2 plugin!")); return -1; }
960
961         if (Config.UseNet && !NetOpened) {
962                 netInfo info;
963                 char path[MAXPATHLEN * 2];
964                 char dotdir[MAXPATHLEN];
965
966                 MAKE_PATH(dotdir, "/.pcsx/plugins/", NULL);
967
968                 strcpy(info.EmuName, "PCSX");
969                 memcpy(info.CdromID, CdromId, 9); /* no \0 trailing character? */
970                 memcpy(info.CdromLabel, CdromLabel, 9);
971                 info.CdromLabel[9] = '\0';
972                 info.psxMem = psxM;
973                 info.GPU_showScreenPic = GPU_showScreenPic;
974                 info.GPU_displayText = GPU_displayText;
975                 info.GPU_showScreenPic = GPU_showScreenPic;
976                 info.PAD_setSensitive = PAD1_setSensitive;
977                 sprintf(path, "%s%s", Config.BiosDir, Config.Bios);
978                 strcpy(info.BIOSpath, path);
979                 strcpy(info.MCD1path, Config.Mcd1);
980                 strcpy(info.MCD2path, Config.Mcd2);
981                 sprintf(path, "%s%s", dotdir, Config.Gpu);
982                 strcpy(info.GPUpath, path);
983                 sprintf(path, "%s%s", dotdir, Config.Spu);
984                 strcpy(info.SPUpath, path);
985                 sprintf(path, "%s%s", dotdir, Config.Cdr);
986                 strcpy(info.CDRpath, path);
987                 NET_setInfo(&info);
988
989                 ret = NET_open(&gpuDisp);
990                 if (ret < 0) {
991                         if (ret == -2) {
992                                 // -2 is returned when something in the info
993                                 // changed and needs to be synced
994                                 char *ptr;
995
996                                 PARSEPATH(Config.Bios, info.BIOSpath);
997                                 PARSEPATH(Config.Gpu,  info.GPUpath);
998                                 PARSEPATH(Config.Spu,  info.SPUpath);
999                                 PARSEPATH(Config.Cdr,  info.CDRpath);
1000
1001                                 strcpy(Config.Mcd1, info.MCD1path);
1002                                 strcpy(Config.Mcd2, info.MCD2path);
1003                                 return -2;
1004                         } else {
1005                                 Config.UseNet = FALSE;
1006                         }
1007                 } else {
1008                         if (NET_queryPlayer() == 1) {
1009                                 if (SendPcsxInfo() == -1) Config.UseNet = FALSE;
1010                         } else {
1011                                 if (RecvPcsxInfo() == -1) Config.UseNet = FALSE;
1012                         }
1013                 }
1014                 NetOpened = TRUE;
1015         } else if (Config.UseNet) {
1016                 NET_resume();
1017         }
1018
1019         return 0;
1020 }
1021
1022 int OpenPlugins() {
1023         int ret;
1024
1025         while ((ret = _OpenPlugins()) == -2) {
1026                 ReleasePlugins();
1027                 LoadMcds(Config.Mcd1, Config.Mcd2);
1028                 if (LoadPlugins() == -1) return -1;
1029         }
1030         return ret;
1031 }
1032
1033 void ClosePlugins() {
1034         int ret;
1035
1036 #ifndef NO_FRONTEND
1037         signal(SIGINT, SIG_DFL);
1038         signal(SIGPIPE, SIG_DFL);
1039 #endif
1040
1041         ret = CDR_close();
1042         if (ret < 0) { SysMessage(_("Error closing CD-ROM plugin!")); return; }
1043         ret = SPU_close();
1044         if (ret < 0) { SysMessage(_("Error closing SPU plugin!")); return; }
1045         ret = PAD1_close();
1046         if (ret < 0) { SysMessage(_("Error closing Controller 1 Plugin!")); return; }
1047         ret = PAD2_close();
1048         if (ret < 0) { SysMessage(_("Error closing Controller 2 plugin!")); return; }
1049         // pcsx-rearmed: we handle gpu elsewhere
1050         //ret = GPU_close();
1051         //if (ret < 0) { SysMessage(_("Error closing GPU plugin!")); return; }
1052
1053         if (Config.UseNet) {
1054                 NET_pause();
1055         }
1056 }
1057
1058 /* we hook statically linked plugins here */
1059 static const char *builtin_plugins[] = {
1060         "builtin_gpu", "builtin_spu", "builtin_cdr", "builtin_pad",
1061         "builtin_cdrcimg",
1062 };
1063
1064 static const int builtin_plugin_ids[] = {
1065         PLUGIN_GPU, PLUGIN_SPU, PLUGIN_CDR, PLUGIN_PAD,
1066         PLUGIN_CDRCIMG,
1067 };
1068
1069 void *SysLoadLibrary(const char *lib) {
1070         const char *tmp = strrchr(lib, '/');
1071         void *ret = NULL;
1072         int i;
1073
1074         SysPrintf("plugin: %s\n", lib);
1075
1076         if (tmp != NULL) {
1077                 tmp++;
1078                 for (i = 0; i < ARRAY_SIZE(builtin_plugins); i++)
1079                         if (strcmp(tmp, builtin_plugins[i]) == 0)
1080                                 return (void *)(uintptr_t)(PLUGIN_DL_BASE + builtin_plugin_ids[i]);
1081         }
1082
1083 #if !defined(_WIN32) && !defined(NO_DYLIB)
1084         ret = dlopen(lib, RTLD_NOW);
1085         if (ret == NULL)
1086                 SysMessage("dlopen: %s", dlerror());
1087 #else
1088         /* no external plugin support, abi is no longer
1089          * compatible with psemu/pcsx anyway */
1090 #endif
1091         return ret;
1092 }
1093
1094 void *SysLoadSym(void *lib, const char *sym) {
1095         unsigned int plugid = (unsigned int)(uintptr_t)lib;
1096
1097         if (PLUGIN_DL_BASE <= plugid && plugid < PLUGIN_DL_BASE + ARRAY_SIZE(builtin_plugins))
1098                 return plugin_link(plugid - PLUGIN_DL_BASE, sym);
1099
1100 #if !defined(_WIN32) && !defined(NO_DYLIB)
1101         return dlsym(lib, sym);
1102 #else
1103         return NULL;
1104 #endif
1105 }
1106
1107 const char *SysLibError() {
1108 #if defined(NO_DYLIB)
1109         return NULL;
1110 #elif !defined(_WIN32)
1111         return dlerror();
1112 #else
1113         return "not supported";
1114 #endif
1115 }
1116
1117 void SysCloseLibrary(void *lib) {
1118         unsigned int plugid = (unsigned int)(uintptr_t)lib;
1119
1120         if (PLUGIN_DL_BASE <= plugid && plugid < PLUGIN_DL_BASE + ARRAY_SIZE(builtin_plugins))
1121                 return;
1122
1123 #if !defined(_WIN32) && !defined(NO_DYLIB)
1124         dlclose(lib);
1125 #endif
1126 }