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