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