frontend: make -psxout cmd arg override config
[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 "../libpcsxcore/misc.h"
24 #include "../libpcsxcore/new_dynarec/new_dynarec.h"
25 #include "../plugins/cdrcimg/cdrcimg.h"
26 #include "common/plat.h"
27 #include "common/input.h"
28 #include "common/readpng.h"
29
30 int ready_to_go;
31 unsigned long gpuDisp;
32 char cfgfile_basename[MAXPATHLEN];
33 static char *(*real_getenv)(const char *name);
34 int state_slot;
35 enum sched_action emu_action, emu_action_old;
36 char hud_msg[64];
37 int hud_new_msg;
38
39 // from softgpu plugin
40 extern int UseFrameSkip;
41
42 static void make_path(char *buf, size_t size, const char *dir, const char *fname)
43 {
44         if (fname)
45                 snprintf(buf, size, ".%s%s", dir, fname);
46         else
47                 snprintf(buf, size, ".%s", dir);
48 }
49 #define MAKE_PATH(buf, dir, fname) \
50         make_path(buf, sizeof(buf), dir, fname)
51
52 static void create_profile_dir(const char *directory) {
53         char path[MAXPATHLEN];
54
55         MAKE_PATH(path, directory, NULL);
56         mkdir(path, S_IRWXU | S_IRWXG);
57 }
58
59 static void CheckSubDir() {
60         // make sure that ~/.pcsx exists
61         create_profile_dir(PCSX_DOT_DIR);
62
63         create_profile_dir(BIOS_DIR);
64         create_profile_dir(MEMCARD_DIR);
65         create_profile_dir(STATES_DIR);
66         create_profile_dir(PLUGINS_DIR);
67         create_profile_dir(PLUGINS_CFG_DIR);
68         create_profile_dir(CHEATS_DIR);
69         create_profile_dir(PATCHES_DIR);
70         create_profile_dir(PCSX_DOT_DIR "cfg");
71         create_profile_dir("/screenshots/");
72 }
73
74 static int get_gameid_filename(char *buf, int size, const char *fmt, int i) {
75         char trimlabel[33];
76         int j;
77
78         strncpy(trimlabel, CdromLabel, 32);
79         trimlabel[32] = 0;
80         for (j = 31; j >= 0; j--)
81                 if (trimlabel[j] == ' ')
82                         trimlabel[j] = 0;
83                 else
84                         continue;
85
86         snprintf(buf, size, fmt, trimlabel, CdromId, i);
87
88         return 0;
89 }
90
91 void set_cd_image(const char *fname)
92 {
93         const char *ext = NULL;
94         
95         if (fname != NULL)
96                 ext = strrchr(fname, '.');
97
98         if (ext && (
99             strcasecmp(ext, ".z") == 0 || strcasecmp(ext, ".bz") == 0 ||
100             strcasecmp(ext, ".znx") == 0 || strcasecmp(ext, ".pbp") == 0)) {
101                 SetIsoFile(NULL);
102                 cdrcimg_set_fname(fname);
103                 strcpy(Config.Cdr, "builtin_cdrcimg");
104         } else {
105                 SetIsoFile(fname);
106                 strcpy(Config.Cdr, "builtin_cdr");
107         }
108 }
109
110 static void set_default_paths(void)
111 {
112         MAKE_PATH(Config.Mcd1, MEMCARD_DIR, "card1.mcd");
113         MAKE_PATH(Config.Mcd2, MEMCARD_DIR, "card2.mcd");
114         strcpy(Config.BiosDir, "bios");
115
116         strcpy(Config.PluginsDir, "plugins");
117         strcpy(Config.Gpu, "builtin_gpu");
118         strcpy(Config.Spu, "builtin_spu");
119         strcpy(Config.Cdr, "builtin_cdr");
120         strcpy(Config.Pad1, "builtin_pad");
121         strcpy(Config.Pad2, "builtin_pad");
122         strcpy(Config.Net, "Disabled");
123         Config.PsxAuto = 1;
124
125         snprintf(Config.PatchesDir, sizeof(Config.PatchesDir), "." PATCHES_DIR);
126 }
127
128 void do_emu_action(void)
129 {
130         char buf[MAXPATHLEN];
131         int ret;
132
133         emu_action_old = emu_action;
134
135         switch (emu_action) {
136         case SACTION_NONE:
137                 return;
138         case SACTION_ENTER_MENU:
139                 menu_loop();
140                 return;
141         case SACTION_LOAD_STATE:
142                 ret = emu_load_state(state_slot);
143                 snprintf(hud_msg, sizeof(hud_msg), ret == 0 ? "LOADED" : "FAIL!");
144                 break;
145         case SACTION_SAVE_STATE:
146                 ret = emu_save_state(state_slot);
147                 snprintf(hud_msg, sizeof(hud_msg), ret == 0 ? "SAVED" : "FAIL!");
148                 break;
149         case SACTION_NEXT_SSLOT:
150                 state_slot++;
151                 if (state_slot > 9)
152                         state_slot = 0;
153                 goto do_state_slot;
154         case SACTION_PREV_SSLOT:
155                 state_slot--;
156                 if (state_slot < 0)
157                         state_slot = 9;
158                 goto do_state_slot;
159         case SACTION_TOGGLE_FSKIP:
160                 UseFrameSkip ^= 1;
161                 snprintf(hud_msg, sizeof(hud_msg), "FRAMESKIP %s",
162                         UseFrameSkip ? "ON" : "OFF");
163                 break;
164         case SACTION_SCREENSHOT:
165                 {
166                         void *scrbuf;
167                         int w, h, bpp;
168                         time_t t = time(NULL);
169                         struct tm *tb = localtime(&t);
170                         int ti = tb->tm_yday * 1000000 + tb->tm_hour * 10000 +
171                                 tb->tm_min * 100 + tb->tm_sec;
172
173                         scrbuf = pl_prepare_screenshot(&w, &h, &bpp);
174                         get_gameid_filename(buf, sizeof(buf),
175                                 "screenshots/%.32s-%.9s.%d.png", ti);
176                         ret = -1;
177                         if (scrbuf != 0 && bpp == 16)
178                                 ret = writepng(buf, scrbuf, w, h);
179                         if (ret == 0)
180                                 snprintf(hud_msg, sizeof(hud_msg), "SCREENSHOT TAKEN");
181                         break;
182                 }
183         }
184         hud_new_msg = 3;
185         return;
186
187 do_state_slot:
188         snprintf(hud_msg, sizeof(hud_msg), "STATE SLOT %d [%s]", state_slot,
189                 emu_check_state(state_slot) == 0 ? "USED" : "FREE");
190         hud_new_msg = 3;
191 }
192
193 int main(int argc, char *argv[])
194 {
195         void *tmp;
196
197         tmp = dlopen("/lib/libdl.so.2", RTLD_LAZY);
198         if (tmp == NULL)
199                 tmp = dlopen("/lib32/libdl.so.2", RTLD_LAZY);
200         if (tmp != NULL)
201                 real_getenv = dlsym(tmp, "getenv");
202         if (real_getenv == NULL) {
203                 fprintf(stderr, "%s\n", dlerror());
204                 return 1;
205         }
206         dlclose(tmp);
207
208         // what is the name of the config file?
209         // it may be redefined by -cfg on the command line
210         strcpy(cfgfile_basename, "pcsx.cfg");
211
212         emuLog = stdout;
213         SetIsoFile(NULL);
214
215         memset(&Config, 0, sizeof(Config));
216
217         CheckSubDir();
218         set_default_paths();
219         strcpy(Config.Bios, "HLE");
220
221 #ifdef MAEMO
222         extern int maemo_main(int argc, char **argv);
223         return maemo_main(argc, argv);
224 #else
225         char file[MAXPATHLEN] = "";
226         char path[MAXPATHLEN];
227         const char *cdfile = NULL;
228         int psxout = 0;
229         int loadst = 0;
230         int i;
231
232         // read command line options
233         for (i = 1; i < argc; i++) {
234                      if (!strcmp(argv[i], "-psxout")) psxout = 1;
235                 else if (!strcmp(argv[i], "-load")) loadst = atol(argv[++i]);
236                 else if (!strcmp(argv[i], "-cfg")) {
237                         if (i+1 >= argc) break;
238                         strncpy(cfgfile_basename, argv[++i], MAXPATHLEN-100);   /* TODO buffer overruns */
239                         printf("Using config file %s.\n", cfgfile_basename);
240                 }
241                 else if (!strcmp(argv[i], "-cdfile")) {
242                         char isofilename[MAXPATHLEN];
243
244                         if (i+1 >= argc) break;
245                         strncpy(isofilename, argv[++i], MAXPATHLEN);
246                         if (isofilename[0] != '/') {
247                                 getcwd(path, MAXPATHLEN);
248                                 if (strlen(path) + strlen(isofilename) + 1 < MAXPATHLEN) {
249                                         strcat(path, "/");
250                                         strcat(path, isofilename);
251                                         strcpy(isofilename, path);
252                                 } else
253                                         isofilename[0] = 0;
254                         }
255
256                         cdfile = isofilename;
257                 }
258                 else if (!strcmp(argv[i], "-h") ||
259                          !strcmp(argv[i], "-help") ||
260                          !strcmp(argv[i], "--help")) {
261                          printf(PACKAGE_NAME " " PACKAGE_VERSION "\n");
262                          printf("%s\n", _(
263                                                         " pcsx [options] [file]\n"
264                                                         "\toptions:\n"
265                                                         "\t-cdfile FILE\tRuns a CD image file\n"
266                                                         "\t-nogui\t\tDon't open the GTK GUI\n"
267                                                         "\t-cfg FILE\tLoads desired configuration file (default: ~/.pcsx/pcsx.cfg)\n"
268                                                         "\t-psxout\t\tEnable PSX output\n"
269                                                         "\t-load STATENUM\tLoads savestate STATENUM (1-5)\n"
270                                                         "\t-h -help\tDisplay this message\n"
271                                                         "\tfile\t\tLoads file\n"));
272                          return 0;
273                 } else {
274                         strncpy(file, argv[i], MAXPATHLEN);
275                         if (file[0] != '/') {
276                                 getcwd(path, MAXPATHLEN);
277                                 if (strlen(path) + strlen(file) + 1 < MAXPATHLEN) {
278                                         strcat(path, "/");
279                                         strcat(path, file);
280                                         strcpy(file, path);
281                                 } else
282                                         file[0] = 0;
283                         }
284                 }
285         }
286
287         if (cdfile)
288                 set_cd_image(cdfile);
289
290         if (SysInit() == -1)
291                 return 1;
292
293         // frontend stuff
294         in_init();
295         //in_probe();
296         plat_init();
297         menu_init(); // loads config
298
299         if (psxout)
300                 Config.PsxOut = 1;
301
302         if (LoadPlugins() == -1) {
303                 // FIXME: this recovery doesn't work, just delete bad config and bail out
304                 // SysMessage("could not load plugins, retrying with defaults\n");
305                 set_default_paths();
306                 snprintf(path, sizeof(path), "." PCSX_DOT_DIR "%s", cfgfile_basename);
307                 remove(path);
308                 SysMessage("Failed loading plugins!");
309                 return 1;
310         }
311         pcnt_hook_plugins();
312
313         if (OpenPlugins() == -1) {
314                 return 1;
315         }
316         plugin_call_rearmed_cbs();
317
318         CheckCdrom();
319         SysReset();
320
321         if (file[0] != '\0') {
322                 if (Load(file) != -1)
323                         ready_to_go = 1;
324         } else {
325                 if (cdfile) {
326                         if (LoadCdrom() == -1) {
327                                 ClosePlugins();
328                                 printf(_("Could not load CD-ROM!\n"));
329                                 return -1;
330                         }
331                         ready_to_go = 1;
332                 }
333         }
334
335         if (ready_to_go) {
336                 menu_prepare_emu();
337
338                 // If a state has been specified, then load that
339                 if (loadst) {
340                         int ret = emu_load_state(loadst - 1);
341                         printf("%s state %d\n", ret ? "failed to load" : "loaded", loadst);
342                 }
343         }
344         else
345                 menu_loop();
346
347         pl_start_watchdog();
348
349         while (1)
350         {
351                 stop = 0;
352                 emu_action = SACTION_NONE;
353
354                 psxCpu->Execute();
355                 if (emu_action != SACTION_NONE)
356                         do_emu_action();
357         }
358
359         return 0;
360 #endif
361 }
362
363 int SysInit() {
364         if (EmuInit() == -1) {
365                 printf("PSX emulator couldn't be initialized.\n");
366                 return -1;
367         }
368
369         LoadMcds(Config.Mcd1, Config.Mcd2);     /* TODO Do we need to have this here, or in the calling main() function?? */
370
371         if (Config.Debug) {
372                 StartDebugger();
373         }
374
375         return 0;
376 }
377
378 void SysRunGui() {
379         printf("SysRunGui\n");
380 }
381
382 void StartGui() {
383         printf("StartGui\n");
384 }
385
386 static void dummy_lace()
387 {
388 }
389
390 void SysReset() {
391         // rearmed hack: EmuReset() runs some code when real BIOS is used,
392         // but we usually do reset from menu while GPU is not open yet,
393         // so we need to prevent updateLace() call..
394         void *real_lace = GPU_updateLace;
395         GPU_updateLace = dummy_lace;
396
397         EmuReset();
398
399         // hmh core forgets this
400         CDR_stop();
401
402         GPU_updateLace = real_lace;
403 }
404
405 void SysClose() {
406         EmuShutdown();
407         ReleasePlugins();
408
409         StopDebugger();
410
411         if (emuLog != NULL) fclose(emuLog);
412 }
413
414 void SysUpdate() {
415 }
416
417 void OnFile_Exit() {
418         printf("OnFile_Exit\n");
419 #ifndef MAEMO
420         menu_finish();
421 #endif
422         SysClose();
423         plat_finish();
424         exit(0);
425 }
426
427 int get_state_filename(char *buf, int size, int i) {
428         return get_gameid_filename(buf, size,
429                 "." STATES_DIR "%.32s-%.9s.%3.3d", i);
430 }
431
432 int emu_check_state(int slot)
433 {
434         char fname[MAXPATHLEN];
435         int ret;
436
437         ret = get_state_filename(fname, sizeof(fname), slot);
438         if (ret != 0)
439                 return ret;
440
441         return CheckState(fname);
442 }
443
444 int emu_save_state(int slot)
445 {
446         char fname[MAXPATHLEN];
447         int ret;
448
449         ret = get_state_filename(fname, sizeof(fname), slot);
450         if (ret != 0)
451                 return ret;
452
453         return SaveState(fname);
454 }
455
456 int emu_load_state(int slot)
457 {
458         char fname[MAXPATHLEN];
459         int ret;
460
461         ret = get_state_filename(fname, sizeof(fname), slot);
462         if (ret != 0)
463                 return ret;
464
465         return LoadState(fname);
466 }
467
468 void SysPrintf(const char *fmt, ...) {
469         va_list list;
470         char msg[512];
471
472         va_start(list, fmt);
473         vsprintf(msg, fmt, list);
474         va_end(list);
475
476         fprintf(emuLog, "%s", msg);
477 }
478
479 void SysMessage(const char *fmt, ...) {
480         va_list list;
481         char msg[512];
482
483         va_start(list, fmt);
484         vsprintf(msg, fmt, list);
485         va_end(list);
486
487         if (msg[strlen(msg) - 1] == '\n')
488                 msg[strlen(msg) - 1] = 0;
489
490         fprintf(stderr, "%s\n", msg);
491 }
492
493 static void SignalExit(int sig) {
494         ClosePlugins();
495         OnFile_Exit();
496 }
497
498 #define PARSEPATH(dst, src) \
499         ptr = src + strlen(src); \
500         while (*ptr != '\\' && ptr != src) ptr--; \
501         if (ptr != src) { \
502                 strcpy(dst, ptr+1); \
503         }
504
505 static int _OpenPlugins(void) {
506         int ret;
507
508         signal(SIGINT, SignalExit);
509         signal(SIGPIPE, SignalExit);
510
511         GPU_clearDynarec(clearDynarec);
512
513         ret = CDR_open();
514         if (ret < 0) { SysMessage(_("Error opening CD-ROM plugin!")); return -1; }
515         ret = SPU_open();
516         if (ret < 0) { SysMessage(_("Error opening SPU plugin!")); return -1; }
517         SPU_registerCallback(SPUirq);
518         // pcsx-rearmed: we handle gpu elsewhere
519         //ret = GPU_open(&gpuDisp, "PCSX", NULL);
520         //if (ret < 0) { SysMessage(_("Error opening GPU plugin!")); return -1; }
521         ret = PAD1_open(&gpuDisp);
522         if (ret < 0) { SysMessage(_("Error opening Controller 1 plugin!")); return -1; }
523         ret = PAD2_open(&gpuDisp);
524         if (ret < 0) { SysMessage(_("Error opening Controller 2 plugin!")); return -1; }
525
526         if (Config.UseNet && !NetOpened) {
527                 netInfo info;
528                 char path[MAXPATHLEN];
529                 char dotdir[MAXPATHLEN];
530
531                 MAKE_PATH(dotdir, "/.pcsx/plugins/", NULL);
532
533                 strcpy(info.EmuName, "PCSX " PACKAGE_VERSION);
534                 strncpy(info.CdromID, CdromId, 9);
535                 strncpy(info.CdromLabel, CdromLabel, 9);
536                 info.psxMem = psxM;
537                 info.GPU_showScreenPic = GPU_showScreenPic;
538                 info.GPU_displayText = GPU_displayText;
539                 info.GPU_showScreenPic = GPU_showScreenPic;
540                 info.PAD_setSensitive = PAD1_setSensitive;
541                 sprintf(path, "%s%s", Config.BiosDir, Config.Bios);
542                 strcpy(info.BIOSpath, path);
543                 strcpy(info.MCD1path, Config.Mcd1);
544                 strcpy(info.MCD2path, Config.Mcd2);
545                 sprintf(path, "%s%s", dotdir, Config.Gpu);
546                 strcpy(info.GPUpath, path);
547                 sprintf(path, "%s%s", dotdir, Config.Spu);
548                 strcpy(info.SPUpath, path);
549                 sprintf(path, "%s%s", dotdir, Config.Cdr);
550                 strcpy(info.CDRpath, path);
551                 NET_setInfo(&info);
552
553                 ret = NET_open(&gpuDisp);
554                 if (ret < 0) {
555                         if (ret == -2) {
556                                 // -2 is returned when something in the info
557                                 // changed and needs to be synced
558                                 char *ptr;
559
560                                 PARSEPATH(Config.Bios, info.BIOSpath);
561                                 PARSEPATH(Config.Gpu,  info.GPUpath);
562                                 PARSEPATH(Config.Spu,  info.SPUpath);
563                                 PARSEPATH(Config.Cdr,  info.CDRpath);
564
565                                 strcpy(Config.Mcd1, info.MCD1path);
566                                 strcpy(Config.Mcd2, info.MCD2path);
567                                 return -2;
568                         } else {
569                                 Config.UseNet = FALSE;
570                         }
571                 } else {
572                         if (NET_queryPlayer() == 1) {
573                                 if (SendPcsxInfo() == -1) Config.UseNet = FALSE;
574                         } else {
575                                 if (RecvPcsxInfo() == -1) Config.UseNet = FALSE;
576                         }
577                 }
578                 NetOpened = TRUE;
579         } else if (Config.UseNet) {
580                 NET_resume();
581         }
582
583         return 0;
584 }
585
586 int OpenPlugins() {
587         int ret;
588
589         while ((ret = _OpenPlugins()) == -2) {
590                 ReleasePlugins();
591                 LoadMcds(Config.Mcd1, Config.Mcd2);
592                 if (LoadPlugins() == -1) return -1;
593         }
594         return ret;
595 }
596
597 void ClosePlugins() {
598         int ret;
599
600         signal(SIGINT, SIG_DFL);
601         signal(SIGPIPE, SIG_DFL);
602         ret = CDR_close();
603         if (ret < 0) { SysMessage(_("Error closing CD-ROM plugin!")); return; }
604         ret = SPU_close();
605         if (ret < 0) { SysMessage(_("Error closing SPU plugin!")); return; }
606         ret = PAD1_close();
607         if (ret < 0) { SysMessage(_("Error closing Controller 1 Plugin!")); return; }
608         ret = PAD2_close();
609         if (ret < 0) { SysMessage(_("Error closing Controller 2 plugin!")); return; }
610         // pcsx-rearmed: we handle gpu elsewhere
611         //ret = GPU_close();
612         //if (ret < 0) { SysMessage(_("Error closing GPU plugin!")); return; }
613
614         if (Config.UseNet) {
615                 NET_pause();
616         }
617 }
618
619 #if 1
620 /* this is to avoid having to hack every plugin to stop using $HOME */
621 char *getenv(const char *name)
622 {
623         static char ret[8] = ".";
624
625         if (name && strcmp(name, "HOME") == 0 &&
626                         ((int)name >> 28) == 0) // HACK: let libs find home
627                 return ret;
628
629         return real_getenv(name);
630 }
631 #endif
632
633 /* we hook statically linked plugins here */
634 static const char *builtin_plugins[] = {
635         "builtin_gpu", "builtin_spu", "builtin_cdr", "builtin_pad",
636         "builtin_cdrcimg",
637 };
638
639 static const int builtin_plugin_ids[] = {
640         PLUGIN_GPU, PLUGIN_SPU, PLUGIN_CDR, PLUGIN_PAD,
641         PLUGIN_CDRCIMG,
642 };
643
644 void *SysLoadLibrary(const char *lib) {
645         const char *tmp = strrchr(lib, '/');
646         void *ret;
647         int i;
648
649         printf("plugin: %s\n", lib);
650
651         if (tmp != NULL) {
652                 tmp++;
653                 for (i = 0; i < ARRAY_SIZE(builtin_plugins); i++)
654                         if (strcmp(tmp, builtin_plugins[i]) == 0)
655                                 return (void *)(long)(PLUGIN_DL_BASE + builtin_plugin_ids[i]);
656         }
657
658 #if defined(__x86_64__) || defined(__i386__)
659         // convenience hack
660         char name[MAXPATHLEN];
661         snprintf(name, sizeof(name), "%s.x86", lib);
662         lib = name;
663 #endif
664
665         ret = dlopen(lib, RTLD_NOW);
666         if (ret == NULL)
667                 fprintf(stderr, "dlopen: %s\n", dlerror());
668         return ret;
669 }
670
671 void *SysLoadSym(void *lib, const char *sym) {
672         unsigned int plugid = (unsigned int)(long)lib;
673
674         if (PLUGIN_DL_BASE <= plugid && plugid < PLUGIN_DL_BASE + ARRAY_SIZE(builtin_plugins))
675                 return plugin_link(plugid - PLUGIN_DL_BASE, sym);
676
677         return dlsym(lib, sym);
678 }
679
680 const char *SysLibError() {
681         return dlerror();
682 }
683
684 void SysCloseLibrary(void *lib) {
685         unsigned int plugid = (unsigned int)(long)lib;
686
687         if (PLUGIN_DL_BASE <= plugid && plugid < PLUGIN_DL_BASE + ARRAY_SIZE(builtin_plugins))
688                 return;
689
690         dlclose(lib);
691 }
692