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