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