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