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