spu: don't stop a channel by adsr if we have potential irq
[pcsx_rearmed.git] / frontend / menu.c
1 /*
2  * (C) GraÅžvydas "notaz" Ignotas, 2010-2011
3  *
4  * This work is licensed under the terms of any of these licenses
5  * (at your option):
6  *  - GNU GPL, version 2 or later.
7  *  - GNU LGPL, version 2.1 or later.
8  * See the COPYING file in the top-level directory.
9  */
10
11 #include <stdio.h>
12 #include <string.h>
13 #include <errno.h>
14 #include <dlfcn.h>
15 #include <zlib.h>
16
17 #include "main.h"
18 #include "menu.h"
19 #include "config.h"
20 #include "plugin.h"
21 #include "plugin_lib.h"
22 #include "omap.h"
23 #include "common/plat.h"
24 #include "../libpcsxcore/misc.h"
25 #include "../libpcsxcore/new_dynarec/new_dynarec.h"
26 #include "revision.h"
27
28 #define MENU_X2 1
29 #define array_size(x) (sizeof(x) / sizeof(x[0]))
30
31 typedef enum
32 {
33         MA_NONE = 1,
34         MA_MAIN_RESUME_GAME,
35         MA_MAIN_SAVE_STATE,
36         MA_MAIN_LOAD_STATE,
37         MA_MAIN_RESET_GAME,
38         MA_MAIN_LOAD_ROM,
39         MA_MAIN_RUN_BIOS,
40         MA_MAIN_CONTROLS,
41         MA_MAIN_CREDITS,
42         MA_MAIN_EXIT,
43         MA_CTRL_PLAYER1,
44         MA_CTRL_PLAYER2,
45         MA_CTRL_EMU,
46         MA_CTRL_DEV_FIRST,
47         MA_CTRL_DEV_NEXT,
48         MA_CTRL_DONE,
49         MA_OPT_SAVECFG,
50         MA_OPT_SAVECFG_GAME,
51         MA_OPT_CPU_CLOCKS,
52         MA_OPT_FILTERING,
53 } menu_id;
54
55 enum {
56         SCALE_1_1,
57         SCALE_4_3,
58         SCALE_FULLSCREEN,
59         SCALE_CUSTOM,
60 };
61
62 static int last_psx_w, last_psx_h, last_psx_bpp;
63 static int scaling, filter, state_slot, cpu_clock, cpu_clock_st;
64 static char rom_fname_reload[MAXPATHLEN];
65 static char last_selected_fname[MAXPATHLEN];
66 int g_opts;
67
68 // from softgpu plugin
69 extern int iUseDither;
70 extern int UseFrameSkip;
71 extern uint32_t dwActFixes;
72 extern float fFrameRateHz;
73 extern int dwFrameRateTicks;
74
75 // sound plugin
76 extern int iUseReverb;
77 extern int iUseInterpolation;
78 extern int iXAPitch;
79 extern int iSPUIRQWait;
80 extern int iUseTimer;
81
82 static const char *bioses[24];
83 static const char *gpu_plugins[16];
84 static const char *spu_plugins[16];
85 static int bios_sel, gpu_plugsel, spu_plugsel;
86
87
88 static int min(int x, int y) { return x < y ? x : y; }
89 static int max(int x, int y) { return x > y ? x : y; }
90
91 void emu_make_path(char *buff, const char *end, int size)
92 {
93         int pos, end_len;
94
95         end_len = strlen(end);
96         pos = plat_get_root_dir(buff, size);
97         strncpy(buff + pos, end, size - pos);
98         buff[size - 1] = 0;
99         if (pos + end_len > size - 1)
100                 printf("Warning: path truncated: %s\n", buff);
101 }
102
103 static int emu_check_save_file(int slot)
104 {
105         char fname[MAXPATHLEN];
106         int ret;
107
108         ret = get_state_filename(fname, sizeof(fname), slot);
109         if (ret != 0)
110                 return 0;
111
112         ret = CheckState(fname);
113         return ret == 0 ? 1 : 0;
114 }
115
116 static int emu_save_load_game(int load, int sram)
117 {
118         char fname[MAXPATHLEN];
119         int ret;
120
121         ret = get_state_filename(fname, sizeof(fname), state_slot);
122         if (ret != 0)
123                 return 0;
124
125         if (load) {
126                 ret = LoadState(fname);
127
128                 // reflect hle/bios mode from savestate
129                 if (Config.HLE)
130                         bios_sel = 0;
131                 else if (bios_sel == 0 && bioses[1] != NULL)
132                         // XXX: maybe find the right bios instead
133                         bios_sel = 1;
134         }
135         else
136                 ret = SaveState(fname);
137
138         return ret;
139 }
140
141 static void menu_set_defconfig(void)
142 {
143         g_opts = 0;
144         scaling = SCALE_4_3;
145
146         Config.Xa = Config.Cdda = Config.Sio =
147         Config.SpuIrq = Config.RCntFix = Config.VSyncWA = 0;
148
149         iUseDither = UseFrameSkip = 0;
150         dwActFixes = 1<<7;
151
152         iUseReverb = 2;
153         iUseInterpolation = 1;
154         iXAPitch = iSPUIRQWait = 0;
155         iUseTimer = 2;
156 }
157
158 #define CE_CONFIG_STR(val) \
159         { #val, 0, Config.val }
160
161 #define CE_CONFIG_VAL(val) \
162         { #val, sizeof(Config.val), &Config.val }
163
164 #define CE_STR(val) \
165         { #val, 0, val }
166
167 #define CE_INTVAL(val) \
168         { #val, sizeof(val), &val }
169
170 static const struct {
171         const char *name;
172         size_t len;
173         void *val;
174 } config_data[] = {
175         CE_CONFIG_STR(Bios),
176         CE_CONFIG_STR(Gpu),
177         CE_CONFIG_STR(Spu),
178         CE_CONFIG_STR(Cdr),
179         CE_CONFIG_VAL(Xa),
180         CE_CONFIG_VAL(Sio),
181         CE_CONFIG_VAL(Mdec),
182         CE_CONFIG_VAL(PsxAuto),
183         CE_CONFIG_VAL(Cdda),
184         CE_CONFIG_VAL(Debug),
185         CE_CONFIG_VAL(PsxOut),
186         CE_CONFIG_VAL(SpuIrq),
187         CE_CONFIG_VAL(RCntFix),
188         CE_CONFIG_VAL(VSyncWA),
189         CE_CONFIG_VAL(Cpu),
190         CE_CONFIG_VAL(PsxType),
191         CE_INTVAL(scaling),
192         CE_INTVAL(g_layer_x),
193         CE_INTVAL(g_layer_y),
194         CE_INTVAL(g_layer_w),
195         CE_INTVAL(g_layer_h),
196         CE_INTVAL(filter),
197         CE_INTVAL(state_slot),
198         CE_INTVAL(cpu_clock),
199         CE_INTVAL(g_opts),
200         CE_INTVAL(iUseDither),
201         CE_INTVAL(UseFrameSkip),
202         CE_INTVAL(dwActFixes),
203         CE_INTVAL(iUseReverb),
204         CE_INTVAL(iUseInterpolation),
205         CE_INTVAL(iXAPitch),
206         CE_INTVAL(iSPUIRQWait),
207         CE_INTVAL(iUseTimer),
208 };
209
210 static char *get_cd_label(void)
211 {
212         static char trimlabel[33];
213         int j;
214
215         strncpy(trimlabel, CdromLabel, 32);
216         trimlabel[32] = 0;
217         for (j = 31; j >= 0; j--)
218                 if (trimlabel[j] == ' ')
219                         trimlabel[j] = 0;
220
221         return trimlabel;
222 }
223
224 static void make_cfg_fname(char *buf, size_t size, int is_game)
225 {
226         if (is_game)
227                 snprintf(buf, size, "." PCSX_DOT_DIR "cfg/%.32s-%.9s.cfg", get_cd_label(), CdromId);
228         else
229                 snprintf(buf, size, "." PCSX_DOT_DIR "%s", cfgfile_basename);
230 }
231
232 static int menu_write_config(int is_game)
233 {
234         char cfgfile[MAXPATHLEN];
235         FILE *f;
236         int i;
237
238         make_cfg_fname(cfgfile, sizeof(cfgfile), is_game);
239         f = fopen(cfgfile, "w");
240         if (f == NULL) {
241                 printf("menu_write_config: failed to open: %s\n", cfgfile);
242                 return -1;
243         }
244
245         for (i = 0; i < ARRAY_SIZE(config_data); i++) {
246                 fprintf(f, "%s = ", config_data[i].name);
247                 switch (config_data[i].len) {
248                 case 0:
249                         fprintf(f, "%s\n", (char *)config_data[i].val);
250                         break;
251                 case 1:
252                         fprintf(f, "%x\n", *(u8 *)config_data[i].val);
253                         break;
254                 case 2:
255                         fprintf(f, "%x\n", *(u16 *)config_data[i].val);
256                         break;
257                 case 4:
258                         fprintf(f, "%x\n", *(u32 *)config_data[i].val);
259                         break;
260                 default:
261                         printf("menu_write_config: unhandled len %d for %s\n",
262                                  config_data[i].len, config_data[i].name);
263                         break;
264                 }
265         }
266
267         if (!is_game)
268                 fprintf(f, "lastcdimg = %s\n", last_selected_fname);
269
270         fclose(f);
271         return 0;
272 }
273
274 static void parse_str_val(char *cval, const char *src)
275 {
276         char *tmp;
277         strncpy(cval, src, MAXPATHLEN);
278         cval[MAXPATHLEN - 1] = 0;
279         tmp = strchr(cval, '\n');
280         if (tmp == NULL)
281                 tmp = strchr(cval, '\r');
282         if (tmp != NULL)
283                 *tmp = 0;
284 }
285
286 static int menu_load_config(int is_game)
287 {
288         char cfgfile[MAXPATHLEN];
289         int i, ret = -1;
290         long size;
291         char *cfg;
292         FILE *f;
293
294         make_cfg_fname(cfgfile, sizeof(cfgfile), is_game);
295         f = fopen(cfgfile, "r");
296         if (f == NULL) {
297                 printf("menu_load_config: failed to open: %s\n", cfgfile);
298                 return -1;
299         }
300
301         fseek(f, 0, SEEK_END);
302         size = ftell(f);
303         if (size <= 0) {
304                 printf("bad size %ld: %s\n", size, cfgfile);
305                 goto fail;
306         }
307
308         cfg = malloc(size + 1);
309         if (cfg == NULL)
310                 goto fail;
311
312         fseek(f, 0, SEEK_SET);
313         if (fread(cfg, 1, size, f) != size) {
314                 printf("failed to read: %s\n", cfgfile);
315                 goto fail_read;
316         }
317         cfg[size] = 0;
318
319         for (i = 0; i < ARRAY_SIZE(config_data); i++) {
320                 char *tmp, *tmp2;
321                 u32 val;
322
323                 tmp = strstr(cfg, config_data[i].name);
324                 if (tmp == NULL)
325                         continue;
326                 tmp += strlen(config_data[i].name);
327                 if (strncmp(tmp, " = ", 3) != 0)
328                         continue;
329                 tmp += 3;
330
331                 if (config_data[i].len == 0) {
332                         parse_str_val(config_data[i].val, tmp);
333                         continue;
334                 }
335
336                 tmp2 = NULL;
337                 val = strtoul(tmp, &tmp2, 16);
338                 if (tmp2 == NULL || tmp == tmp2)
339                         continue; // parse failed
340
341                 switch (config_data[i].len) {
342                 case 1:
343                         *(u8 *)config_data[i].val = val;
344                         break;
345                 case 2:
346                         *(u16 *)config_data[i].val = val;
347                         break;
348                 case 4:
349                         *(u32 *)config_data[i].val = val;
350                         break;
351                 default:
352                         printf("menu_load_config: unhandled len %d for %s\n",
353                                  config_data[i].len, config_data[i].name);
354                         break;
355                 }
356         }
357
358         if (!is_game) {
359                 char *tmp = strstr(cfg, "lastcdimg = ");
360                 if (tmp != NULL) {
361                         tmp += 12;
362                         parse_str_val(last_selected_fname, tmp);
363                 }
364         }
365
366         // sync plugins
367         for (i = bios_sel = 0; bioses[i] != NULL; i++)
368                 if (strcmp(Config.Bios, bioses[i]) == 0)
369                         { bios_sel = i; break; }
370
371         for (i = gpu_plugsel = 0; gpu_plugins[i] != NULL; i++)
372                 if (strcmp(Config.Gpu, gpu_plugins[i]) == 0)
373                         { gpu_plugsel = i; break; }
374
375         for (i = spu_plugsel = 0; spu_plugins[i] != NULL; i++)
376                 if (strcmp(Config.Spu, spu_plugins[i]) == 0)
377                         { spu_plugsel = i; break; }
378
379         ret = 0;
380 fail_read:
381         free(cfg);
382 fail:
383         fclose(f);
384         return ret;
385 }
386
387 // rrrr rggg gggb bbbb
388 static unsigned short fname2color(const char *fname)
389 {
390         static const char *cdimg_exts[] = { ".bin", ".img", ".iso", ".z", ".cue" };
391         static const char *other_exts[] = { ".ccd", ".toc", ".mds", ".sub", ".table" };
392         const char *ext = strrchr(fname, '.');
393         int i;
394
395         if (ext == NULL)
396                 return 0xffff;
397         for (i = 0; i < array_size(cdimg_exts); i++)
398                 if (strcasecmp(ext, cdimg_exts[i]) == 0)
399                         return 0x7bff;
400         for (i = 0; i < array_size(other_exts); i++)
401                 if (strcasecmp(ext, other_exts[i]) == 0)
402                         return 0xa514;
403         return 0xffff;
404 }
405
406 static void draw_savestate_bg(int slot);
407
408 #define MENU_ALIGN_LEFT
409 #define menu_init menu_init_common
410 #include "common/menu.c"
411 #undef menu_init
412
413 // a bit of black magic here
414 static void draw_savestate_bg(int slot)
415 {
416         extern void bgr555_to_rgb565(void *dst, void *src, int bytes);
417         static const int psx_widths[8]  = { 256, 368, 320, 384, 512, 512, 640, 640 };
418         int x, y, w, h;
419         char fname[MAXPATHLEN];
420         GPUFreeze_t *gpu;
421         u16 *s, *d;
422         gzFile f;
423         int ret;
424         u32 tmp;
425
426         ret = get_state_filename(fname, sizeof(fname), slot);
427         if (ret != 0)
428                 return;
429
430         f = gzopen(fname, "rb");
431         if (f == NULL)
432                 return;
433
434         if (gzseek(f, 0x29933d, SEEK_SET) != 0x29933d) {
435                 fprintf(stderr, "gzseek failed\n");
436                 gzclose(f);
437                 return;
438         }
439
440         gpu = malloc(sizeof(*gpu));
441         if (gpu == NULL) {
442                 gzclose(f);
443                 return;
444         }
445
446         ret = gzread(f, gpu, sizeof(*gpu));
447         gzclose(f);
448         if (ret != sizeof(*gpu)) {
449                 fprintf(stderr, "gzread failed\n");
450                 goto out;
451         }
452
453         memcpy(g_menubg_ptr, g_menubg_src_ptr, g_menuscreen_w * g_menuscreen_h * 2);
454
455         if ((gpu->ulStatus & 0x800000) || (gpu->ulStatus & 0x200000))
456                 goto out; // disabled || 24bpp (NYET)
457
458         x = gpu->ulControl[5] & 0x3ff;
459         y = (gpu->ulControl[5] >> 10) & 0x1ff;
460         s = (u16 *)gpu->psxVRam + y * 1024 + (x & ~3);
461         w = psx_widths[(gpu->ulStatus >> 16) & 7];
462         tmp = gpu->ulControl[7];
463         h = ((tmp >> 10) & 0x3ff) - (tmp & 0x3ff);
464         if (gpu->ulStatus & 0x80000) // doubleheight
465                 h *= 2;
466
467         x = max(0, g_menuscreen_w - w) & ~3;
468         y = max(0, g_menuscreen_h / 2 - h / 2);
469         w = min(g_menuscreen_w, w);
470         h = min(g_menuscreen_h, h);
471         d = (u16 *)g_menubg_ptr + g_menuscreen_w * y + x;
472
473         for (; h > 0; h--, d += g_menuscreen_w, s += 1024)
474                 bgr555_to_rgb565(d, s, w * 2);
475
476 out:
477         free(gpu);
478 }
479
480 // ---------- pandora specific -----------
481
482 static const char pnd_script_base[] = "sudo -n /usr/pandora/scripts";
483 static char **pnd_filter_list;
484
485 static int get_cpu_clock(void)
486 {
487         FILE *f;
488         int ret = 0;
489         f = fopen("/proc/pandora/cpu_mhz_max", "r");
490         if (f) {
491                 fscanf(f, "%d", &ret);
492                 fclose(f);
493         }
494         return ret;
495 }
496
497 static void apply_cpu_clock(void)
498 {
499         char buf[128];
500
501         if (cpu_clock != 0 && cpu_clock != get_cpu_clock()) {
502                 snprintf(buf, sizeof(buf), "unset DISPLAY; echo y | %s/op_cpuspeed.sh %d",
503                          pnd_script_base, cpu_clock);
504                 system(buf);
505         }
506 }
507
508 static void apply_filter(int which)
509 {
510         static int old = -1;
511         char buf[128];
512         int i;
513
514         if (pnd_filter_list == NULL || which == old)
515                 return;
516
517         for (i = 0; i < which; i++)
518                 if (pnd_filter_list[i] == NULL)
519                         return;
520
521         if (pnd_filter_list[i] == NULL)
522                 return;
523
524         snprintf(buf, sizeof(buf), "%s/op_videofir.sh %s", pnd_script_base, pnd_filter_list[i]);
525         system(buf);
526         old = which;
527 }
528
529 static menu_entry e_menu_gfx_options[];
530
531 static void pnd_menu_init(void)
532 {
533         struct dirent *ent;
534         int i, count = 0;
535         char **mfilters;
536         char buff[64];
537         DIR *dir;
538
539         cpu_clock_st = cpu_clock = get_cpu_clock();
540
541         dir = opendir("/etc/pandora/conf/dss_fir");
542         if (dir == NULL) {
543                 perror("filter opendir");
544                 return;
545         }
546
547         while (1) {
548                 errno = 0;
549                 ent = readdir(dir);
550                 if (ent == NULL) {
551                         if (errno != 0)
552                                 perror("readdir");
553                         break;
554                 }
555
556                 if (ent->d_type != DT_REG && ent->d_type != DT_LNK)
557                         continue;
558
559                 count++;
560         }
561
562         if (count == 0)
563                 return;
564
565         mfilters = calloc(count + 1, sizeof(mfilters[0]));
566         if (mfilters == NULL)
567                 return;
568
569         rewinddir(dir);
570         for (i = 0; (ent = readdir(dir)); ) {
571                 size_t len;
572
573                 if (ent->d_type != DT_REG && ent->d_type != DT_LNK)
574                         continue;
575
576                 len = strlen(ent->d_name);
577
578                 // skip pre-HF5 extra files
579                 if (len >= 3 && strcmp(ent->d_name + len - 3, "_v3") == 0)
580                         continue;
581                 if (len >= 3 && strcmp(ent->d_name + len - 3, "_v5") == 0)
582                         continue;
583
584                 // have to cut "_up_h" for pre-HF5
585                 if (len > 5 && strcmp(ent->d_name + len - 5, "_up_h") == 0)
586                         len -= 5;
587
588                 if (len > sizeof(buff) - 1)
589                         continue;
590
591                 strncpy(buff, ent->d_name, len);
592                 buff[len] = 0;
593                 mfilters[i] = strdup(buff);
594                 if (mfilters[i] != NULL)
595                         i++;
596         }
597         closedir(dir);
598
599         i = me_id2offset(e_menu_gfx_options, MA_OPT_FILTERING);
600         e_menu_gfx_options[i].data = (void *)mfilters;
601         pnd_filter_list = mfilters;
602 }
603
604 void menu_finish(void)
605 {
606         cpu_clock = cpu_clock_st;
607         apply_cpu_clock();
608 }
609
610 // -------------- key config --------------
611
612 me_bind_action me_ctrl_actions[] =
613 {
614         { "UP      ", 1 << DKEY_UP},
615         { "DOWN    ", 1 << DKEY_DOWN },
616         { "LEFT    ", 1 << DKEY_LEFT },
617         { "RIGHT   ", 1 << DKEY_RIGHT },
618         { "TRIANGLE", 1 << DKEY_TRIANGLE },
619         { "CIRCLE  ", 1 << DKEY_CIRCLE },
620         { "CROSS   ", 1 << DKEY_CROSS },
621         { "SQUARE  ", 1 << DKEY_SQUARE },
622         { "L1      ", 1 << DKEY_L1 },
623         { "R1      ", 1 << DKEY_R1 },
624         { "L2      ", 1 << DKEY_L2 },
625         { "R2      ", 1 << DKEY_R2 },
626         { "START   ", 1 << DKEY_START },
627         { "SELECT  ", 1 << DKEY_SELECT },
628         { NULL,       0 }
629 };
630
631 me_bind_action emuctrl_actions[] =
632 {
633 /*
634         { "Load State       ", PEV_STATE_LOAD },
635         { "Save State       ", PEV_STATE_SAVE },
636         { "Prev Save Slot   ", PEV_SSLOT_PREV },
637         { "Next Save Slot   ", PEV_SSLOT_NEXT },
638 */
639         { "Enter Menu       ", PEV_MENU },
640         { NULL,                0 }
641 };
642
643 static int key_config_loop_wrap(int id, int keys)
644 {
645         switch (id) {
646                 case MA_CTRL_PLAYER1:
647                         key_config_loop(me_ctrl_actions, array_size(me_ctrl_actions) - 1, 0);
648                         break;
649                 case MA_CTRL_PLAYER2:
650                         key_config_loop(me_ctrl_actions, array_size(me_ctrl_actions) - 1, 1);
651                         break;
652                 case MA_CTRL_EMU:
653                         key_config_loop(emuctrl_actions, array_size(emuctrl_actions) - 1, -1);
654                         break;
655                 default:
656                         break;
657         }
658         return 0;
659 }
660
661 static const char *mgn_dev_name(int id, int *offs)
662 {
663         const char *name = NULL;
664         static int it = 0;
665
666         if (id == MA_CTRL_DEV_FIRST)
667                 it = 0;
668
669         for (; it < IN_MAX_DEVS; it++) {
670                 name = in_get_dev_name(it, 1, 1);
671                 if (name != NULL)
672                         break;
673         }
674
675         it++;
676         return name;
677 }
678
679 static const char *mgn_saveloadcfg(int id, int *offs)
680 {
681         return "";
682 }
683
684 static int mh_savecfg(int id, int keys)
685 {
686         if (menu_write_config(id == MA_OPT_SAVECFG_GAME ? 1 : 0) == 0)
687                 me_update_msg("config saved");
688         else
689                 me_update_msg("failed to write config");
690
691         return 1;
692 }
693
694 static menu_entry e_menu_keyconfig[] =
695 {
696         mee_handler_id("Player 1",          MA_CTRL_PLAYER1,    key_config_loop_wrap),
697         mee_handler_id("Player 2",          MA_CTRL_PLAYER2,    key_config_loop_wrap),
698         mee_handler_id("Emulator controls", MA_CTRL_EMU,        key_config_loop_wrap),
699 //      mee_cust_nosave("Save global config",       MA_OPT_SAVECFG, mh_savecfg, mgn_saveloadcfg),
700 //      mee_cust_nosave("Save cfg for loaded game", MA_OPT_SAVECFG_GAME, mh_savecfg, mgn_saveloadcfg),
701         mee_label     (""),
702         mee_label     ("Input devices:"),
703         mee_label_mk  (MA_CTRL_DEV_FIRST, mgn_dev_name),
704         mee_label_mk  (MA_CTRL_DEV_NEXT,  mgn_dev_name),
705         mee_label_mk  (MA_CTRL_DEV_NEXT,  mgn_dev_name),
706         mee_label_mk  (MA_CTRL_DEV_NEXT,  mgn_dev_name),
707         mee_label_mk  (MA_CTRL_DEV_NEXT,  mgn_dev_name),
708         mee_label_mk  (MA_CTRL_DEV_NEXT,  mgn_dev_name),
709         mee_label_mk  (MA_CTRL_DEV_NEXT,  mgn_dev_name),
710         mee_end,
711 };
712
713 static int menu_loop_keyconfig(int id, int keys)
714 {
715         static int sel = 0;
716
717 //      me_enable(e_menu_keyconfig, MA_OPT_SAVECFG_GAME, ready_to_go && CdromId[0]);
718         me_loop(e_menu_keyconfig, &sel, NULL);
719         return 0;
720 }
721
722 // ------------ gfx options menu ------------
723
724 static const char *men_scaler[] = { "1x1", "scaled 4:3", "fullscreen", "custom", NULL };
725 static const char h_cscaler[]   = "Displays the scaler layer, you can resize it\n"
726                                   "using d-pad or move it using R+d-pad";
727 static const char *men_dummy[] = { NULL };
728
729 static int menu_loop_cscaler(int id, int keys)
730 {
731         unsigned int inp;
732
733         scaling = SCALE_CUSTOM;
734
735         omap_enable_layer(1);
736
737         for (;;)
738         {
739                 menu_draw_begin(0);
740                 memset(g_menuscreen_ptr, 4, g_menuscreen_w * g_menuscreen_h * 2);
741                 text_out16(2, 2, "%d,%d", g_layer_x, g_layer_y);
742                 text_out16(2, 480 - 18, "%dx%d | d-pad: resize, R+d-pad: move", g_layer_w, g_layer_h);
743                 menu_draw_end();
744
745                 inp = in_menu_wait(PBTN_UP|PBTN_DOWN|PBTN_LEFT|PBTN_RIGHT|PBTN_R|PBTN_MOK|PBTN_MBACK, 40);
746                 if (inp & PBTN_UP)    g_layer_y--;
747                 if (inp & PBTN_DOWN)  g_layer_y++;
748                 if (inp & PBTN_LEFT)  g_layer_x--;
749                 if (inp & PBTN_RIGHT) g_layer_x++;
750                 if (!(inp & PBTN_R)) {
751                         if (inp & PBTN_UP)    g_layer_h += 2;
752                         if (inp & PBTN_DOWN)  g_layer_h -= 2;
753                         if (inp & PBTN_LEFT)  g_layer_w += 2;
754                         if (inp & PBTN_RIGHT) g_layer_w -= 2;
755                 }
756                 if (inp & (PBTN_MOK|PBTN_MBACK))
757                         break;
758
759                 if (inp & (PBTN_UP|PBTN_DOWN|PBTN_LEFT|PBTN_RIGHT)) {
760                         if (g_layer_x < 0)   g_layer_x = 0;
761                         if (g_layer_x > 640) g_layer_x = 640;
762                         if (g_layer_y < 0)   g_layer_y = 0;
763                         if (g_layer_y > 420) g_layer_y = 420;
764                         if (g_layer_w < 160) g_layer_w = 160;
765                         if (g_layer_h < 60)  g_layer_h = 60;
766                         if (g_layer_x + g_layer_w > 800)
767                                 g_layer_w = 800 - g_layer_x;
768                         if (g_layer_y + g_layer_h > 480)
769                                 g_layer_h = 480 - g_layer_y;
770                         omap_enable_layer(1);
771                 }
772         }
773
774         omap_enable_layer(0);
775
776         return 0;
777 }
778
779 static menu_entry e_menu_gfx_options[] =
780 {
781         mee_enum      ("Scaler",                   0, scaling, men_scaler),
782         mee_enum      ("Filter",                   MA_OPT_FILTERING, filter, men_dummy),
783 //      mee_onoff     ("Vsync",                    0, vsync, 1),
784         mee_cust_h    ("Setup custom scaler",      0, menu_loop_cscaler, NULL, h_cscaler),
785         mee_end,
786 };
787
788 static int menu_loop_gfx_options(int id, int keys)
789 {
790         static int sel = 0;
791
792         me_loop(e_menu_gfx_options, &sel, NULL);
793
794         return 0;
795 }
796
797 // ------------ bios/plugins ------------
798
799 static const char *men_gpu_dithering[] = { "None", "Game dependant", "Always", NULL };
800 static const char h_gpu_0[]            = "Needed for Chrono Cross";
801 static const char h_gpu_1[]            = "Capcom fighting games";
802 static const char h_gpu_2[]            = "Black screens in Lunar";
803 static const char h_gpu_3[]            = "Compatibility mode";
804 static const char h_gpu_6[]            = "Pandemonium 2";
805 static const char h_gpu_7[]            = "Skip every second frame";
806 static const char h_gpu_8[]            = "Needed by Dark Forces";
807 static const char h_gpu_9[]            = "better g-colors, worse textures";
808 static const char h_gpu_10[]           = "Toggle busy flags after drawing";
809
810 static menu_entry e_menu_plugin_gpu[] =
811 {
812         mee_enum      ("Dithering",                  0, iUseDither, men_gpu_dithering),
813         mee_onoff_h   ("Odd/even bit hack",          0, dwActFixes, 1<<0, h_gpu_0),
814         mee_onoff_h   ("Expand screen width",        0, dwActFixes, 1<<1, h_gpu_1),
815         mee_onoff_h   ("Ignore brightness color",    0, dwActFixes, 1<<2, h_gpu_2),
816         mee_onoff_h   ("Disable coordinate check",   0, dwActFixes, 1<<3, h_gpu_3),
817         mee_onoff_h   ("Lazy screen update",         0, dwActFixes, 1<<6, h_gpu_6),
818         mee_onoff_h   ("Old frame skipping",         0, dwActFixes, 1<<7, h_gpu_7),
819         mee_onoff_h   ("Repeated flat tex triangles ",0,dwActFixes, 1<<8, h_gpu_8),
820         mee_onoff_h   ("Draw quads with triangles",  0, dwActFixes, 1<<9, h_gpu_9),
821         mee_onoff_h   ("Fake 'gpu busy' states",     0, dwActFixes, 1<<10, h_gpu_10),
822         mee_end,
823 };
824
825 static int menu_loop_plugin_gpu(int id, int keys)
826 {
827         static int sel = 0;
828         me_loop(e_menu_plugin_gpu, &sel, NULL);
829         return 0;
830 }
831
832 static const char *men_spu_reverb[] = { "Off", "Fake", "On", NULL };
833 static const char *men_spu_interp[] = { "None", "Simple", "Gaussian", "Cubic", NULL };
834 static const char h_spu_irq_wait[]  = "Wait for CPU; only useful for some games, may cause glitches";
835 static const char h_spu_thread[]    = "Run sound emulation in main thread (recommended)";
836
837 static menu_entry e_menu_plugin_spu[] =
838 {
839         mee_enum      ("Reverb",                    0, iUseReverb, men_spu_reverb),
840         mee_enum      ("Interpolation",             0, iUseInterpolation, men_spu_interp),
841         mee_onoff     ("Adjust XA pitch",           0, iXAPitch, 1),
842         mee_onoff_h   ("SPU IRQ Wait",              0, iSPUIRQWait, 1, h_spu_irq_wait),
843         mee_onoff_h   ("Sound in main thread",      0, iUseTimer, 2, h_spu_thread),
844         mee_end,
845 };
846
847 static int menu_loop_plugin_spu(int id, int keys)
848 {
849         static int sel = 0;
850         me_loop(e_menu_plugin_spu, &sel, NULL);
851         return 0;
852 }
853
854 static const char h_bios[]       = "HLE is simulated BIOS. BIOS is saved in savestates.\n"
855                                    "Must save config and reload the game\n"
856                                    "for change to take effect";
857 static const char h_plugin_xpu[] = "Must save config and reload the game\n"
858                                    "for plugin change to take effect";
859 static const char h_gpu[]        = "Configure built-in P.E.Op.S. SoftGL Driver V1.17";
860 static const char h_spu[]        = "Configure built-in P.E.Op.S. Sound Driver V1.7";
861
862 static menu_entry e_menu_plugin_options[] =
863 {
864         mee_enum_h    ("BIOS",                          0, bios_sel, bioses, h_bios),
865         mee_enum_h    ("GPU plugin",                    0, gpu_plugsel, gpu_plugins, h_plugin_xpu),
866         mee_enum_h    ("SPU plugin",                    0, spu_plugsel, spu_plugins, h_plugin_xpu),
867         mee_handler_h ("Configure built-in GPU plugin", menu_loop_plugin_gpu, h_gpu),
868         mee_handler_h ("Configure built-in SPU plugin", menu_loop_plugin_spu, h_spu),
869         mee_end,
870 };
871
872 static menu_entry e_menu_main[];
873
874 static int menu_loop_plugin_options(int id, int keys)
875 {
876         static int sel = 0;
877         me_loop(e_menu_plugin_options, &sel, NULL);
878
879         // sync BIOS/plugins
880         snprintf(Config.Bios, sizeof(Config.Bios), "%s", bioses[bios_sel]);
881         snprintf(Config.Gpu, sizeof(Config.Gpu), "%s", gpu_plugins[gpu_plugsel]);
882         snprintf(Config.Spu, sizeof(Config.Spu), "%s", spu_plugins[spu_plugsel]);
883         me_enable(e_menu_main, MA_MAIN_RUN_BIOS, bios_sel != 0);
884
885         return 0;
886 }
887
888 // ------------ adv options menu ------------
889
890 static const char h_cfg_cpul[]   = "Shows CPU usage in %%";
891 static const char h_cfg_fl[]     = "Frame Limiter keeps the game from running too fast";
892 static const char h_cfg_xa[]     = "Disables XA sound, which can sometimes improve performance";
893 static const char h_cfg_cdda[]   = "Disable CD Audio for a performance boost\n"
894                                    "(proper .cue/.bin dump is needed otherwise)";
895 static const char h_cfg_sio[]    = "This should be enabled for certain memcards/gamepads";
896 static const char h_cfg_spuirq[] = "Compatibility tweak; should probably be left off";
897 static const char h_cfg_rcnt1[]  = "Parasite Eve 2, Vandal Hearts 1/2 Fix";
898 static const char h_cfg_rcnt2[]  = "InuYasha Sengoku Battle Fix";
899 static const char h_cfg_nodrc[]  = "Disable dynamic recompiler and use interpreter\n"
900                                    "Might be useful to overcome some dynarec bugs";
901
902 static menu_entry e_menu_adv_options[] =
903 {
904         mee_onoff_h   ("Show CPU load",          0, g_opts, OPT_SHOWCPU, h_cfg_cpul),
905         mee_onoff_h   ("Disable Frame Limiter",  0, g_opts, OPT_NO_FRAMELIM, h_cfg_fl),
906         mee_onoff_h   ("Disable XA Decoding",    0, Config.Xa, 1, h_cfg_xa),
907         mee_onoff_h   ("Disable CD Audio",       0, Config.Cdda, 1, h_cfg_cdda),
908         mee_onoff_h   ("SIO IRQ Always Enabled", 0, Config.Sio, 1, h_cfg_sio),
909         mee_onoff_h   ("SPU IRQ Always Enabled", 0, Config.SpuIrq, 1, h_cfg_spuirq),
910         mee_onoff_h   ("Rootcounter hack",       0, Config.RCntFix, 1, h_cfg_rcnt1),
911         mee_onoff_h   ("Rootcounter hack 2",     0, Config.VSyncWA, 1, h_cfg_rcnt2),
912         mee_onoff_h   ("Disable dynarec (slow!)",0, Config.Cpu, 1, h_cfg_nodrc),
913         mee_end,
914 };
915
916 static int menu_loop_adv_options(int id, int keys)
917 {
918         static int sel = 0;
919         me_loop(e_menu_adv_options, &sel, NULL);
920         return 0;
921 }
922
923 // ------------ options menu ------------
924
925 static int mh_restore_defaults(int id, int keys)
926 {
927         menu_set_defconfig();
928         me_update_msg("defaults restored");
929         return 1;
930 }
931
932 static const char *men_region[]       = { "NTSC", "PAL", NULL };
933 /*
934 static const char *men_confirm_save[] = { "OFF", "writes", "loads", "both", NULL };
935 static const char h_confirm_save[]    = "Ask for confirmation when overwriting save,\n"
936                                         "loading state or both";
937 */
938 static const char h_restore_def[]     = "Switches back to default / recommended\n"
939                                         "configuration";
940
941 static menu_entry e_menu_options[] =
942 {
943 //      mee_range     ("Save slot",                0, state_slot, 0, 9),
944 //      mee_enum_h    ("Confirm savestate",        0, dummy, men_confirm_save, h_confirm_save),
945         mee_onoff     ("Frameskip",                0, UseFrameSkip, 1),
946         mee_onoff     ("Show FPS",                 0, g_opts, OPT_SHOWFPS),
947         mee_enum      ("Region",                   0, Config.PsxType, men_region),
948         mee_range     ("CPU clock",                MA_OPT_CPU_CLOCKS, cpu_clock, 20, 5000),
949         mee_handler   ("[Display]",                menu_loop_gfx_options),
950         mee_handler   ("[BIOS/Plugins]",           menu_loop_plugin_options),
951         mee_handler   ("[Advanced]",               menu_loop_adv_options),
952         mee_cust_nosave("Save global config",      MA_OPT_SAVECFG,      mh_savecfg, mgn_saveloadcfg),
953         mee_cust_nosave("Save cfg for loaded game",MA_OPT_SAVECFG_GAME, mh_savecfg, mgn_saveloadcfg),
954         mee_handler_h ("Restore default config",   mh_restore_defaults, h_restore_def),
955         mee_end,
956 };
957
958 static int menu_loop_options(int id, int keys)
959 {
960         static int sel = 0;
961         int i;
962
963         i = me_id2offset(e_menu_options, MA_OPT_CPU_CLOCKS);
964         e_menu_options[i].enabled = cpu_clock != 0 ? 1 : 0;
965         me_enable(e_menu_options, MA_OPT_SAVECFG_GAME, ready_to_go && CdromId[0]);
966
967         me_loop(e_menu_options, &sel, NULL);
968
969         return 0;
970 }
971
972 // ------------ debug menu ------------
973
974 static void draw_frame_debug(void)
975 {
976         smalltext_out16(4, 1, "build: "__DATE__ " " __TIME__ " " REV, 0xe7fc);
977 }
978
979 static void debug_menu_loop(void)
980 {
981         int inp;
982
983         while (1)
984         {
985                 menu_draw_begin(1);
986                 draw_frame_debug();
987                 menu_draw_end();
988
989                 inp = in_menu_wait(PBTN_MOK|PBTN_MBACK|PBTN_MA2|PBTN_MA3|PBTN_L|PBTN_R |
990                                         PBTN_UP|PBTN_DOWN|PBTN_LEFT|PBTN_RIGHT, 70);
991                 if (inp & PBTN_MBACK)
992                         return;
993         }
994 }
995
996 // ------------ main menu ------------
997
998 void OnFile_Exit();
999
1000 static void draw_frame_main(void)
1001 {
1002         if (CdromId[0] != 0) {
1003                 char buff[64];
1004                 snprintf(buff, sizeof(buff), "%.32s/%.9s", get_cd_label(), CdromId);
1005                 smalltext_out16(4, 1, buff, 0x105f);
1006         }
1007 }
1008
1009 static void draw_frame_credits(void)
1010 {
1011         smalltext_out16(4, 1, "build: "__DATE__ " " __TIME__ " " REV, 0xe7fc);
1012 }
1013
1014 const char *plat_get_credits(void)
1015 {
1016         return  "PCSX-ReARMed\n\n"
1017                 "(C) 1999-2003 PCSX Team\n"
1018                 "(C) 2005-2009 PCSX-df Team\n"
1019                 "(C) 2009-2010 PCSX-Reloaded Team\n\n"
1020                 "GPU and SPU code by Pete Bernert\n"
1021                 "  and the P.E.Op.S. team\n"
1022                 "ARM recompiler (C) 2009-2010 Ari64\n"
1023                 "PCSX4ALL plugins by PCSX4ALL team\n"
1024                 "  Chui, Franxis, Unai\n\n"
1025                 "integration, optimization and\n"
1026                 "  frontend (C) 2010-2011 notaz\n";
1027 }
1028
1029 static int reset_game(void)
1030 {
1031         // sanity check
1032         if (bios_sel == 0 && !Config.HLE)
1033                 return -1;
1034
1035         ClosePlugins();
1036         OpenPlugins();
1037         SysReset();
1038         if (CheckCdrom() != -1) {
1039                 LoadCdrom();
1040         }
1041         return 0;
1042 }
1043
1044 static int run_bios(void)
1045 {
1046         if (bios_sel == 0)
1047                 return -1;
1048
1049         ready_to_go = 0;
1050         pl_fbdev_buf = NULL;
1051
1052         ClosePlugins();
1053         set_cd_image(NULL);
1054         LoadPlugins();
1055         NetOpened = 0;
1056         if (OpenPlugins() == -1) {
1057                 me_update_msg("failed to open plugins");
1058                 return -1;
1059         }
1060         plugin_call_rearmed_cbs();
1061
1062         CdromId[0] = '\0';
1063         CdromLabel[0] = '\0';
1064
1065         SysReset();
1066
1067         ready_to_go = 1;
1068         return 0;
1069 }
1070
1071 static int run_cd_image(const char *fname)
1072 {
1073         ready_to_go = 0;
1074         pl_fbdev_buf = NULL;
1075
1076         ClosePlugins();
1077         set_cd_image(fname);
1078         LoadPlugins();
1079         NetOpened = 0;
1080         if (OpenPlugins() == -1) {
1081                 me_update_msg("failed to open plugins");
1082                 return -1;
1083         }
1084         plugin_call_rearmed_cbs();
1085
1086         if (CheckCdrom() == -1) {
1087                 // Only check the CD if we are starting the console with a CD
1088                 ClosePlugins();
1089                 me_update_msg("unsupported/invalid CD image");
1090                 return -1;
1091         }
1092
1093         SysReset();
1094
1095         // Read main executable directly from CDRom and start it
1096         if (LoadCdrom() == -1) {
1097                 ClosePlugins();
1098                 me_update_msg("failed to load CD image");
1099                 return -1;
1100         }
1101
1102         ready_to_go = 1;
1103         return 0;
1104 }
1105
1106 static int romsel_run(void)
1107 {
1108         int prev_gpu, prev_spu;
1109         char *fname;
1110
1111         fname = menu_loop_romsel(last_selected_fname, sizeof(last_selected_fname));
1112         if (fname == NULL)
1113                 return -1;
1114
1115         printf("selected file: %s\n", fname);
1116
1117         if (run_cd_image(fname) != 0)
1118                 return -1;
1119
1120         prev_gpu = gpu_plugsel;
1121         prev_spu = spu_plugsel;
1122         if (menu_load_config(1) != 0)
1123                 menu_load_config(0);
1124
1125         // check for plugin changes, have to repeat
1126         // loading if game config changed plugins to reload them
1127         if (prev_gpu != gpu_plugsel || prev_spu != spu_plugsel) {
1128                 printf("plugin change detected, reloading plugins..\n");
1129                 if (run_cd_image(fname) != 0)
1130                         return -1;
1131         }
1132
1133         strcpy(last_selected_fname, rom_fname_reload);
1134         return 0;
1135 }
1136
1137 static int main_menu_handler(int id, int keys)
1138 {
1139         switch (id)
1140         {
1141         case MA_MAIN_RESUME_GAME:
1142                 if (ready_to_go)
1143                         return 1;
1144                 break;
1145         case MA_MAIN_SAVE_STATE:
1146                 if (ready_to_go)
1147                         return menu_loop_savestate(0);
1148                 break;
1149         case MA_MAIN_LOAD_STATE:
1150                 if (ready_to_go)
1151                         return menu_loop_savestate(1);
1152                 break;
1153         case MA_MAIN_RESET_GAME:
1154                 if (ready_to_go && reset_game() == 0)
1155                         return 1;
1156                 break;
1157         case MA_MAIN_LOAD_ROM:
1158                 if (romsel_run() == 0)
1159                         return 1;
1160                 break;
1161         case MA_MAIN_RUN_BIOS:
1162                 if (run_bios() == 0)
1163                         return 1;
1164                 break;
1165         case MA_MAIN_CREDITS:
1166                 draw_menu_credits(draw_frame_credits);
1167                 in_menu_wait(PBTN_MOK|PBTN_MBACK, 70);
1168                 break;
1169         case MA_MAIN_EXIT:
1170                 OnFile_Exit();
1171                 break;
1172         default:
1173                 lprintf("%s: something unknown selected\n", __FUNCTION__);
1174                 break;
1175         }
1176
1177         return 0;
1178 }
1179
1180 static menu_entry e_menu_main[] =
1181 {
1182         mee_label     (""),
1183         mee_label     (""),
1184         mee_handler_id("Resume game",        MA_MAIN_RESUME_GAME, main_menu_handler),
1185         mee_handler_id("Save State",         MA_MAIN_SAVE_STATE,  main_menu_handler),
1186         mee_handler_id("Load State",         MA_MAIN_LOAD_STATE,  main_menu_handler),
1187         mee_handler_id("Reset game",         MA_MAIN_RESET_GAME,  main_menu_handler),
1188         mee_handler_id("Load CD image",      MA_MAIN_LOAD_ROM,    main_menu_handler),
1189         mee_handler_id("Run BIOS",           MA_MAIN_RUN_BIOS,    main_menu_handler),
1190         mee_handler   ("Options",            menu_loop_options),
1191         mee_handler   ("Controls",           menu_loop_keyconfig),
1192         mee_handler_id("Credits",            MA_MAIN_CREDITS,     main_menu_handler),
1193         mee_handler_id("Exit",               MA_MAIN_EXIT,        main_menu_handler),
1194         mee_end,
1195 };
1196
1197 // ----------------------------
1198
1199 static void menu_leave_emu(void);
1200
1201 void menu_loop(void)
1202 {
1203         static int sel = 0;
1204
1205         menu_leave_emu();
1206
1207         me_enable(e_menu_main, MA_MAIN_RESUME_GAME, ready_to_go);
1208         me_enable(e_menu_main, MA_MAIN_SAVE_STATE,  ready_to_go && CdromId[0]);
1209         me_enable(e_menu_main, MA_MAIN_LOAD_STATE,  ready_to_go && CdromId[0]);
1210         me_enable(e_menu_main, MA_MAIN_RESET_GAME,  ready_to_go);
1211         me_enable(e_menu_main, MA_MAIN_RUN_BIOS, bios_sel != 0);
1212
1213         in_set_config_int(0, IN_CFG_BLOCKING, 1);
1214
1215         do {
1216                 me_loop(e_menu_main, &sel, draw_frame_main);
1217         } while (!ready_to_go);
1218
1219         /* wait until menu, ok, back is released */
1220         while (in_menu_wait_any(50) & (PBTN_MENU|PBTN_MOK|PBTN_MBACK))
1221                 ;
1222
1223         in_set_config_int(0, IN_CFG_BLOCKING, 0);
1224
1225         menu_prepare_emu();
1226 }
1227
1228 static void scan_bios_plugins(void)
1229 {
1230         char fname[MAXPATHLEN];
1231         struct dirent *ent;
1232         int bios_i, gpu_i, spu_i;
1233         char *p;
1234         DIR *dir;
1235
1236         bioses[0] = "HLE";
1237         gpu_plugins[0] = "builtin_gpu";
1238         spu_plugins[0] = "builtin_spu";
1239         bios_i = gpu_i = spu_i = 1;
1240
1241         snprintf(fname, sizeof(fname), "%s/", Config.BiosDir);
1242         dir = opendir(fname);
1243         if (dir == NULL) {
1244                 perror("scan_bios_plugins bios opendir");
1245                 goto do_plugins;
1246         }
1247
1248         while (1) {
1249                 struct stat st;
1250
1251                 errno = 0;
1252                 ent = readdir(dir);
1253                 if (ent == NULL) {
1254                         if (errno != 0)
1255                                 perror("readdir");
1256                         break;
1257                 }
1258
1259                 if (ent->d_type != DT_REG && ent->d_type != DT_LNK)
1260                         continue;
1261
1262                 snprintf(fname, sizeof(fname), "%s/%s", Config.BiosDir, ent->d_name);
1263                 if (stat(fname, &st) != 0 || st.st_size != 512*1024) {
1264                         printf("bad BIOS file: %s\n", ent->d_name);
1265                         continue;
1266                 }
1267
1268                 if (bios_i < ARRAY_SIZE(bioses) - 1) {
1269                         bioses[bios_i++] = strdup(ent->d_name);
1270                         continue;
1271                 }
1272
1273                 printf("too many BIOSes, dropping \"%s\"\n", ent->d_name);
1274         }
1275
1276         closedir(dir);
1277
1278 do_plugins:
1279         snprintf(fname, sizeof(fname), "%s/", Config.PluginsDir);
1280         dir = opendir(fname);
1281         if (dir == NULL) {
1282                 perror("scan_bios_plugins opendir");
1283                 return;
1284         }
1285
1286         while (1) {
1287                 void *h, *tmp;
1288
1289                 errno = 0;
1290                 ent = readdir(dir);
1291                 if (ent == NULL) {
1292                         if (errno != 0)
1293                                 perror("readdir");
1294                         break;
1295                 }
1296                 p = strstr(ent->d_name, ".so");
1297                 if (p == NULL)
1298                         continue;
1299
1300                 snprintf(fname, sizeof(fname), "%s/%s", Config.PluginsDir, ent->d_name);
1301                 h = dlopen(fname, RTLD_LAZY | RTLD_LOCAL);
1302                 if (h == NULL) {
1303                         fprintf(stderr, "%s\n", dlerror());
1304                         continue;
1305                 }
1306
1307                 // now what do we have here?
1308                 tmp = dlsym(h, "GPUinit");
1309                 if (tmp) {
1310                         dlclose(h);
1311                         if (gpu_i < ARRAY_SIZE(gpu_plugins) - 1)
1312                                 gpu_plugins[gpu_i++] = strdup(ent->d_name);
1313                         continue;
1314                 }
1315
1316                 tmp = dlsym(h, "SPUinit");
1317                 if (tmp) {
1318                         dlclose(h);
1319                         if (spu_i < ARRAY_SIZE(spu_plugins) - 1)
1320                                 spu_plugins[spu_i++] = strdup(ent->d_name);
1321                         continue;
1322                 }
1323
1324                 fprintf(stderr, "ignoring unidentified plugin: %s\n", fname);
1325                 dlclose(h);
1326         }
1327
1328         closedir(dir);
1329 }
1330
1331 void menu_init(void)
1332 {
1333         char buff[MAXPATHLEN];
1334
1335         strcpy(last_selected_fname, "/media");
1336
1337         scan_bios_plugins();
1338         pnd_menu_init();
1339         menu_init_common();
1340
1341         menu_set_defconfig();
1342         menu_load_config(0);
1343         last_psx_w = 320;
1344         last_psx_h = 240;
1345         last_psx_bpp = 16;
1346
1347         g_menubg_src_ptr = calloc(g_menuscreen_w * g_menuscreen_h * 2, 1);
1348         if (g_menubg_src_ptr == NULL)
1349                 exit(1);
1350         emu_make_path(buff, "skin/background.png", sizeof(buff));
1351         readpng(g_menubg_src_ptr, buff, READPNG_BG, g_menuscreen_w, g_menuscreen_h);
1352 }
1353
1354 void menu_notify_mode_change(int w, int h, int bpp)
1355 {
1356         last_psx_w = w;
1357         last_psx_h = h;
1358         last_psx_bpp = bpp;
1359
1360         if (scaling == SCALE_1_1) {
1361                 g_layer_x = 800/2 - w/2;  g_layer_y = 480/2 - h/2;
1362                 g_layer_w = w; g_layer_h = h;
1363         }
1364 }
1365
1366 static void menu_leave_emu(void)
1367 {
1368         if (GPU_close != NULL) {
1369                 int ret = GPU_close();
1370                 if (ret)
1371                         fprintf(stderr, "Warning: GPU_close returned %d\n", ret);
1372         }
1373
1374         memcpy(g_menubg_ptr, g_menubg_src_ptr, g_menuscreen_w * g_menuscreen_h * 2);
1375         if (pl_fbdev_buf != NULL && ready_to_go && last_psx_bpp == 16) {
1376                 int x = max(0, g_menuscreen_w - last_psx_w);
1377                 int y = max(0, g_menuscreen_h / 2 - last_psx_h / 2);
1378                 int w = min(g_menuscreen_w, last_psx_w);
1379                 int h = min(g_menuscreen_h, last_psx_h);
1380                 u16 *d = (u16 *)g_menubg_ptr + g_menuscreen_w * y + x;
1381                 u16 *s = pl_fbdev_buf;
1382
1383                 for (; h > 0; h--, d += g_menuscreen_w, s += last_psx_w)
1384                         menu_darken_bg(d, s, w, 0);
1385         }
1386
1387         if (ready_to_go)
1388                 cpu_clock = get_cpu_clock();
1389
1390         plat_video_menu_enter(ready_to_go);
1391 }
1392
1393 void menu_prepare_emu(void)
1394 {
1395         R3000Acpu *prev_cpu = psxCpu;
1396
1397         plat_video_menu_leave();
1398
1399         switch (scaling) {
1400         case SCALE_1_1:
1401                 menu_notify_mode_change(last_psx_w, last_psx_h, last_psx_bpp);
1402                 break;
1403         case SCALE_4_3:
1404                 g_layer_x = 80;  g_layer_y = 0;
1405                 g_layer_w = 640; g_layer_h = 480;
1406                 break;
1407         case SCALE_FULLSCREEN:
1408                 g_layer_x = 0;   g_layer_y = 0;
1409                 g_layer_w = 800; g_layer_h = 480;
1410                 break;
1411         case SCALE_CUSTOM:
1412                 break;
1413         }
1414         apply_filter(filter);
1415         apply_cpu_clock();
1416         stop = 0;
1417
1418         psxCpu = (Config.Cpu == CPU_INTERPRETER) ? &psxInt : &psxRec;
1419         if (psxCpu != prev_cpu)
1420                 // note that this does not really reset, just clears drc caches
1421                 psxCpu->Reset();
1422
1423         // core doesn't care about Config.Cdda changes,
1424         // so handle them manually here
1425         if (Config.Cdda)
1426                 CDR_stop();
1427
1428         pl_frame_interval = Config.PsxType ? 20000 : 16667;
1429
1430         if (GPU_open != NULL) {
1431                 int ret = GPU_open(&gpuDisp, "PCSX", NULL);
1432                 if (ret)
1433                         fprintf(stderr, "Warning: GPU_open returned %d\n", ret);
1434         }
1435 }
1436
1437 void me_update_msg(const char *msg)
1438 {
1439         strncpy(menu_error_msg, msg, sizeof(menu_error_msg));
1440         menu_error_msg[sizeof(menu_error_msg) - 1] = 0;
1441
1442         menu_error_time = plat_get_ticks_ms();
1443         lprintf("msg: %s\n", menu_error_msg);
1444 }
1445