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