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