perfect vsync
[libpicofe.git] / gp2x / emu.c
index c8c4f8a..36d956a 100644 (file)
@@ -1,4 +1,4 @@
-// (c) Copyright 2006 notaz, All rights reserved.\r
+// (c) Copyright 2006-2007 notaz, All rights reserved.\r
 // Free for non-commercial use.\r
 \r
 // For commercial use, separate licencing terms must be obtained.\r
@@ -54,29 +54,16 @@ extern int crashed_940;
 static short sndBuffer[2*44100/50];\r
 static char noticeMsg[64];                                     // notice msg to draw\r
 static struct timeval noticeMsgTime = { 0, 0 };        // when started showing\r
-static int reset_timing, osd_fps_x;\r
+static int osd_fps_x;\r
 static int combo_keys = 0, combo_acts = 0;     // keys and actions which need button combos\r
 static int gp2x_old_gamma = 100;\r
 static unsigned char *movie_data = NULL;\r
 static int movie_size = 0;\r
 unsigned char *framebuff = 0;  // temporary buffer for alt renderer\r
 int state_slot = 0;\r
+int reset_timing = 0;\r
 \r
-/*\r
-// tmp\r
-static FILE *logf = NULL;\r
 \r
-void pprintf(char *texto, ...)\r
-{\r
-       va_list args;\r
-\r
-       va_start(args,texto);\r
-       vfprintf(logf,texto,args);\r
-       va_end(args);\r
-       fflush(logf);\r
-       sync();\r
-}\r
-*/\r
 // utilities\r
 static void strlwr(char* string)\r
 {\r
@@ -169,31 +156,31 @@ int find_bios(int region, char **bios_file)
 \r
 /* checks if romFileName points to valid MegaCD image\r
  * if so, checks for suitable BIOS */\r
-static int cd_check(char *ext, char **bios_file)\r
+int emu_cd_check(char **bios_file)\r
 {\r
        unsigned char buf[32];\r
-       FILE *cd_f;\r
+       pm_file *cd_f;\r
        int type = 0, region = 4; // 1: Japan, 4: US, 8: Europe\r
 \r
-       cd_f = fopen(romFileName, "rb");\r
+       cd_f = pm_open(romFileName);\r
        if (!cd_f) return 0; // let the upper level handle this\r
 \r
-       if (fread(buf, 1, 32, cd_f) != 32) {\r
-               fclose(cd_f);\r
+       if (pm_read(buf, 32, cd_f) != 32) {\r
+               pm_close(cd_f);\r
                return 0;\r
        }\r
 \r
        if (!strncasecmp("SEGADISCSYSTEM", (char *)buf+0x00, 14)) type = 1;       // Sega CD (ISO)\r
        if (!strncasecmp("SEGADISCSYSTEM", (char *)buf+0x10, 14)) type = 2;       // Sega CD (BIN)\r
        if (type == 0) {\r
-               fclose(cd_f);\r
+               pm_close(cd_f);\r
                return 0;\r
        }\r
 \r
-       /* it seems we have a CD image here. Try to detect region and load a suitable BIOS now.. */\r
-       fseek(cd_f, (type == 1) ? 0x100+0x10B : 0x110+0x10B, SEEK_SET);\r
-       fread(buf, 1, 1, cd_f);\r
-       fclose(cd_f);\r
+       /* it seems we have a CD image here. Try to detect region now.. */\r
+       pm_seek(cd_f, (type == 1) ? 0x100+0x10B : 0x110+0x10B, SEEK_SET);\r
+       pm_read(buf, 1, cd_f);\r
+       pm_close(cd_f);\r
 \r
        if (buf[0] == 0x64) region = 8; // EU\r
        if (buf[0] == 0xa1) region = 1; // JAP\r
@@ -206,7 +193,9 @@ static int cd_check(char *ext, char **bios_file)
                printf("overrided region to %s\n", region != 4 ? (region == 8 ? "EU" : "JAP") : "USA");\r
        }\r
 \r
-       if(find_bios(region, bios_file))\r
+       if (bios_file == NULL) return type;\r
+\r
+       if (find_bios(region, bios_file))\r
                 return type;   // CD and BIOS detected\r
 \r
        return -1;              // CD detected but load failed\r
@@ -217,7 +206,7 @@ int emu_ReloadRom(void)
        unsigned int rom_size = 0;\r
        char *used_rom_name = romFileName;\r
        char ext[5];\r
-       FILE *rom;\r
+       pm_file *rom;\r
        int ret, cd_state;\r
 \r
        printf("emu_ReloadRom(%s)\n", romFileName);\r
@@ -283,8 +272,11 @@ int emu_ReloadRom(void)
                get_ext(romFileName, ext);\r
        }\r
 \r
+       if ((PicoMCD & 1) && Pico_mcd != NULL)\r
+               Stop_CD();\r
+\r
        // check for MegaCD image\r
-       cd_state = cd_check(ext, &used_rom_name);\r
+       cd_state = emu_cd_check(&used_rom_name);\r
        if (cd_state > 0) {\r
                PicoMCD |= 1;\r
                get_ext(used_rom_name, ext);\r
@@ -296,7 +288,7 @@ int emu_ReloadRom(void)
                PicoMCD &= ~1;\r
        }\r
 \r
-       rom = fopen(used_rom_name, "rb");\r
+       rom = pm_open(used_rom_name);\r
        if(!rom) {\r
                sprintf(menuErrorMsg, "Failed to open rom.");\r
                return 0;\r
@@ -308,29 +300,17 @@ int emu_ReloadRom(void)
                rom_size = 0;\r
        }\r
 \r
-       // zipfile support\r
-       if(!strcasecmp(ext, ".zip")) {\r
-               fclose(rom);\r
-               ret = CartLoadZip(used_rom_name, &rom_data, &rom_size);\r
-               if(ret) {\r
-                       if (ret == 4) strcpy(menuErrorMsg, "No ROMs found in zip.");\r
-                       else sprintf(menuErrorMsg, "Unzip failed with code %i", ret);\r
-                       printf("%s\n", menuErrorMsg);\r
-                       return 0;\r
-               }\r
-       } else {\r
-               if( (ret = PicoCartLoad(rom, &rom_data, &rom_size)) ) {\r
-                       sprintf(menuErrorMsg, "PicoCartLoad() failed.");\r
-                       printf("%s\n", menuErrorMsg);\r
-                       fclose(rom);\r
-                       return 0;\r
-               }\r
-               fclose(rom);\r
+       if( (ret = PicoCartLoad(rom, &rom_data, &rom_size)) ) {\r
+               sprintf(menuErrorMsg, "PicoCartLoad() failed.");\r
+               printf("%s\n", menuErrorMsg);\r
+               pm_close(rom);\r
+               return 0;\r
        }\r
+       pm_close(rom);\r
 \r
        // detect wrong files (Pico crashes on very small files), also see if ROM EP is good\r
        if(rom_size <= 0x200 || strncmp((char *)rom_data, "Pico", 4) == 0 ||\r
-         ((*(unsigned short *)(rom_data+4)<<16)|(*(unsigned short *)(rom_data+6))) >= (int)rom_size) {\r
+         ((*(unsigned char *)(rom_data+4)<<16)|(*(unsigned short *)(rom_data+6))) >= (int)rom_size) {\r
                if (rom_data) free(rom_data);\r
                rom_data = 0;\r
                sprintf(menuErrorMsg, "Not a ROM selected.");\r
@@ -405,6 +385,9 @@ int emu_ReloadRom(void)
 }\r
 \r
 \r
+static void emu_msg_cb(const char *msg);\r
+static void emu_msg_tray_open(void);\r
+\r
 void emu_Init(void)\r
 {\r
        // make temp buffer for alt renderer\r
@@ -421,8 +404,9 @@ void emu_Init(void)
        mkdir("cfg", 0777);\r
 \r
        PicoInit();\r
-\r
-//     logf = fopen("log.txt", "w");\r
+       PicoMessage = emu_msg_cb;\r
+       PicoMCDopenTray = emu_msg_tray_open;\r
+       PicoMCDcloseTray = menu_loop_tray;\r
 }\r
 \r
 \r
@@ -475,6 +459,18 @@ static void find_combos(void)
 }\r
 \r
 \r
+void scaling_update(void)\r
+{\r
+       PicoOpt &= ~0x4100;\r
+       switch (currentConfig.scaling) {\r
+               default: break; // off\r
+               case 1:  // hw hor\r
+               case 2:  PicoOpt |=  0x0100; break; // hw hor+vert\r
+               case 3:  PicoOpt |=  0x4000; break; // sw hor\r
+       }\r
+}\r
+\r
+\r
 int emu_ReadConfig(int game)\r
 {\r
        FILE *f;\r
@@ -486,8 +482,8 @@ int emu_ReadConfig(int game)
                // set default config\r
                memset(&currentConfig, 0, sizeof(currentConfig));\r
                currentConfig.lastRomFile[0] = 0;\r
-               currentConfig.EmuOpt  = 0x1f | 0x400; // | cd_leds\r
-               currentConfig.PicoOpt = 0x0f | 0xe00; // | use_940 | cd_pcm | cd_cdda\r
+               currentConfig.EmuOpt  = 0x1f | 0x600; // | confirm_save, cd_leds\r
+               currentConfig.PicoOpt = 0x0f | 0xe00; // | use_940, cd_pcm, cd_cdda\r
                currentConfig.PsndRate = 22050; // 44100;\r
                currentConfig.PicoRegion = 0; // auto\r
                currentConfig.PicoAutoRgnOrder = 0x184; // US, EU, JP\r
@@ -508,6 +504,8 @@ int emu_ReadConfig(int game)
                currentConfig.KeyBinds[23] = 1<<29; // vol up\r
                currentConfig.KeyBinds[22] = 1<<30; // vol down\r
                currentConfig.gamma = 100;\r
+               currentConfig.PicoCDBuffers = 64;\r
+               currentConfig.scaling = 0;\r
                strncpy(cfg, PicoConfigFile, 511);\r
                cfg[511] = 0;\r
        } else {\r
@@ -523,26 +521,29 @@ int emu_ReadConfig(int game)
                bread = fread(&currentConfig, 1, sizeof(currentConfig), f);\r
                fclose(f);\r
        }\r
-       printf((bread == sizeof(currentConfig)) ? "(ok)\n" : "(failed)\n");\r
+       printf(bread > 0 ? "(ok)\n" : "(failed)\n");\r
 \r
        PicoOpt = currentConfig.PicoOpt;\r
        PsndRate = currentConfig.PsndRate;\r
        PicoRegionOverride = currentConfig.PicoRegion;\r
        PicoAutoRgnOrder = currentConfig.PicoAutoRgnOrder;\r
+       PicoCDBuffers = currentConfig.PicoCDBuffers;\r
        if (PicoOpt & 0x20) {\r
                actionNames[ 8] = "Z"; actionNames[ 9] = "Y";\r
                actionNames[10] = "X"; actionNames[11] = "MODE";\r
        }\r
+       scaling_update();\r
        // some sanity checks\r
-       if (currentConfig.CPUclock < 1 || currentConfig.CPUclock > 4096) currentConfig.CPUclock = 200;\r
+       if (currentConfig.CPUclock < 10 || currentConfig.CPUclock > 4096) currentConfig.CPUclock = 200;\r
        if (currentConfig.gamma < 10 || currentConfig.gamma > 300) currentConfig.gamma = 100;\r
+       if (currentConfig.volume < 0 || currentConfig.volume > 99) currentConfig.volume = 50;\r
        // if volume keys are unbound, bind them to volume control\r
        if (!currentConfig.KeyBinds[23] && !currentConfig.KeyBinds[22]) {\r
                currentConfig.KeyBinds[23] = 1<<29; // vol up\r
                currentConfig.KeyBinds[22] = 1<<30; // vol down\r
        }\r
 \r
-       return (bread == sizeof(currentConfig));\r
+       return (bread > 0); // == sizeof(currentConfig));\r
 }\r
 \r
 \r
@@ -557,7 +558,7 @@ int emu_WriteConfig(int game)
                strncpy(cfg, PicoConfigFile, 511);\r
                cfg[511] = 0;\r
        } else {\r
-               romfname_ext(cfg, "cfg", ".pbcfg");\r
+               romfname_ext(cfg, "cfg/", ".pbcfg");\r
        }\r
 \r
        printf("emu_WriteConfig: %s ", cfg);\r
@@ -567,10 +568,13 @@ int emu_WriteConfig(int game)
                currentConfig.PsndRate = PsndRate;\r
                currentConfig.PicoRegion = PicoRegionOverride;\r
                currentConfig.PicoAutoRgnOrder = PicoAutoRgnOrder;\r
+               currentConfig.PicoCDBuffers = PicoCDBuffers;\r
                bwrite = fwrite(&currentConfig, 1, sizeof(currentConfig), f);\r
                fflush(f);\r
                fclose(f);\r
+#ifndef NO_SYNC\r
                sync();\r
+#endif\r
        }\r
        printf((bwrite == sizeof(currentConfig)) ? "(ok)\n" : "(failed)\n");\r
 \r
@@ -586,12 +590,26 @@ void emu_Deinit(void)
                SRam.changed = 0;\r
        }\r
 \r
-       if (!(currentConfig.EmuOpt & 0x20))\r
-               emu_WriteConfig(0);\r
+       if (!(currentConfig.EmuOpt & 0x20)) {\r
+               FILE *f = fopen(PicoConfigFile, "r+b");\r
+               if (!f) emu_WriteConfig(0);\r
+               else {\r
+                       // if we already have config, reload it, except last ROM\r
+                       fseek(f, sizeof(currentConfig.lastRomFile), SEEK_SET);\r
+                       fread(&currentConfig.EmuOpt, 1, sizeof(currentConfig) - sizeof(currentConfig.lastRomFile), f);\r
+                       fseek(f, 0, SEEK_SET);\r
+                       fwrite(&currentConfig, 1, sizeof(currentConfig), f);\r
+                       fflush(f);\r
+                       fclose(f);\r
+#ifndef NO_SYNC\r
+                       sync();\r
+#endif\r
+               }\r
+       }\r
+\r
        free(framebuff);\r
 \r
        PicoExit();\r
-//     fclose(logf);\r
 \r
        // restore gamma\r
        if (gp2x_old_gamma != 100)\r
@@ -711,9 +729,13 @@ static void blit(const char *fps, const char *notice)
                }\r
        }\r
 \r
-       if (notice) osd_text(4, 232, notice);\r
-       if (emu_opt & 2)\r
-               osd_text(osd_fps_x, 232, fps);\r
+       if (notice || (emu_opt & 2)) {\r
+               int h = 232;\r
+               if (currentConfig.scaling == 2 && !(Pico.video.reg[1]&8)) h -= 8;\r
+               if (notice) osd_text(4, h, notice);\r
+               if (emu_opt & 2)\r
+                       osd_text(osd_fps_x, h, fps);\r
+       }\r
        if ((emu_opt & 0x400) && (PicoMCD & 1))\r
                cd_leds();\r
 \r
@@ -776,23 +798,53 @@ static void vidResetMode(void)
        }\r
        Pico.m.dirtyPal = 1;\r
        // reset scaling\r
-       gp2x_video_RGB_setscaling((PicoOpt&0x100)&&!(Pico.video.reg[12]&1) ? 256 : 320, 240);\r
+       if (currentConfig.scaling == 2 && !(Pico.video.reg[1]&8))\r
+            gp2x_video_RGB_setscaling(8, (PicoOpt&0x100)&&!(Pico.video.reg[12]&1) ? 256 : 320, 224);\r
+       else gp2x_video_RGB_setscaling(0, (PicoOpt&0x100)&&!(Pico.video.reg[12]&1) ? 256 : 320, 240);\r
 }\r
 \r
 \r
+static void emu_msg_cb(const char *msg)\r
+{\r
+       if ((PicoOpt&0x10)||!(currentConfig.EmuOpt&0x80)) {\r
+               // 8-bit renderers\r
+               gp2x_memset_all_buffers(320*232, 0xe0, 320*8);\r
+               osd_text(4, 232, msg);\r
+               gp2x_memcpy_all_buffers((char *)gp2x_screen+320*232, 320*232, 320*8);\r
+       } else {\r
+               // 16bit accurate renderer\r
+               gp2x_memset_all_buffers(320*232*2, 0, 320*8*2);\r
+               osd_text(4, 232, msg);\r
+               gp2x_memcpy_all_buffers((char *)gp2x_screen+320*232*2, 320*232*2, 320*8*2);\r
+       }\r
+       gettimeofday(&noticeMsgTime, 0);\r
+       noticeMsgTime.tv_sec -= 2;\r
+\r
+       /* assumption: emu_msg_cb gets called only when something slow is about to happen */\r
+       reset_timing = 1;\r
+}\r
+\r
 static void emu_state_cb(const char *str)\r
 {\r
        clearArea(0);\r
        blit("", str);\r
 }\r
 \r
+static void emu_msg_tray_open(void)\r
+{\r
+       strcpy(noticeMsg, "CD tray opened");\r
+       gettimeofday(&noticeMsgTime, 0);\r
+}\r
+\r
 static void RunEvents(unsigned int which)\r
 {\r
        if(which & 0x1800) { // save or load (but not both)\r
                int do_it = 1;\r
-               if (!(which & 0x1000) && (currentConfig.EmuOpt & 0x200) && emu_check_save_file(state_slot)) {\r
+               if ( emu_check_save_file(state_slot) &&\r
+                               (( (which & 0x1000) && (currentConfig.EmuOpt & 0x800)) ||   // load\r
+                                (!(which & 0x1000) && (currentConfig.EmuOpt & 0x200))) ) { // save\r
                        unsigned long keys;\r
-                       blit("", "OVERWRITE SAVE? (Y=yes, X=no)");\r
+                       blit("", (which & 0x1000) ? "LOAD STATE? (Y=yes, X=no)" : "OVERWRITE SAVE? (Y=yes, X=no)");\r
                        while( !((keys = gp2x_joystick_read(1)) & (GP2X_X|GP2X_Y)) )\r
                                usleep(50*1024);\r
                        if (keys & GP2X_X) do_it = 0;\r
@@ -936,7 +988,7 @@ static void updateKeys(void)
        if(events & 0x6000) {\r
                int vol = currentConfig.volume;\r
                if (events & 0x2000) {\r
-                       if (vol < 90) vol++;\r
+                       if (vol < 99) vol++;\r
                } else {\r
                        if (vol >  0) vol--;\r
                }\r
@@ -958,25 +1010,17 @@ static void updateSound(int len)
 {\r
        if (PicoOpt&8) len<<=1;\r
 \r
-       gp2x_sound_write(PsndOut, len<<1);\r
+       /* avoid writing audio when lagging behind to prevent audio lag */\r
+       if (PicoSkipFrame != 2)\r
+               gp2x_sound_write(PsndOut, len<<1);\r
 }\r
 \r
 \r
-static void SkipFrame(int do_sound)\r
+static void SkipFrame(int do_audio)\r
 {\r
-       void *sndbuff_tmp = 0;\r
-       if (PsndOut && !do_sound) {\r
-               sndbuff_tmp = PsndOut;\r
-               PsndOut = 0;\r
-       }\r
-\r
-       PicoSkipFrame=1;\r
+       PicoSkipFrame=do_audio ? 1 : 2;\r
        PicoFrame();\r
        PicoSkipFrame=0;\r
-\r
-       if (sndbuff_tmp && !do_sound) {\r
-               PsndOut = sndbuff_tmp;\r
-       }\r
 }\r
 \r
 \r
@@ -986,7 +1030,6 @@ void emu_forced_frame(void)
 \r
        PicoOpt |= 0x10;\r
        PicoFrameFull();\r
-       PicoOpt = po_old;\r
 \r
        if (!(Pico.video.reg[12]&1)) {\r
                vidCpyM2 = vidCpyM2_32col;\r
@@ -996,6 +1039,8 @@ void emu_forced_frame(void)
        vidCpyM2((unsigned char *)gp2x_screen+320*8, framebuff+328*8);\r
        vidConvCpyRGB32(localPal, Pico.cram, 0x40);\r
        gp2x_video_setpalette(localPal, 0x40);\r
+\r
+       PicoOpt = po_old;\r
 }\r
 \r
 static void simpleWait(int thissec, int lim_time)\r
@@ -1018,11 +1063,11 @@ static void simpleWait(int thissec, int lim_time)
 void emu_Loop(void)\r
 {\r
        static int gp2x_old_clock = 200;\r
-       static int PsndRate_old = 0, PicoOpt_old = 0, PsndLen_real = 0, pal_old = 0;\r
+       static int PsndRate_old = 0, PicoOpt_old = 0, EmuOpt_old = 0, PsndLen_real = 0, pal_old = 0;\r
        char fpsbuff[24]; // fps count c string\r
        struct timeval tval; // timing\r
        int thissec = 0, frames_done = 0, frames_shown = 0, oldmodes = 0;\r
-       int target_fps, target_frametime, lim_time, i;\r
+       int target_fps, target_frametime, lim_time, vsync_offset, i;\r
        char *notice = 0;\r
 \r
        printf("entered emu_Loop()\n");\r
@@ -1040,6 +1085,13 @@ void emu_Loop(void)
                printf("updated gamma to %i\n", currentConfig.gamma);\r
        }\r
 \r
+       if ((EmuOpt_old&0x2000) != (currentConfig.EmuOpt&0x2000)) {\r
+               if (currentConfig.EmuOpt&0x2000)\r
+                    set_LCD_custom_rate(Pico.m.pal ? LCDR_100 : LCDR_120);\r
+               else unset_LCD_custom_rate();\r
+       }\r
+\r
+       EmuOpt_old = currentConfig.EmuOpt;\r
        fpsbuff[0] = 0;\r
 \r
        // make sure we are in correct mode\r
@@ -1080,6 +1132,22 @@ void emu_Loop(void)
                PsndOut = 0;\r
        }\r
 \r
+       // prepare CD buffer\r
+       if (PicoMCD & 1) PicoCDBufferInit();\r
+\r
+       // calc vsync offset to sync timing code with vsync\r
+       if (currentConfig.EmuOpt&0x2000) {\r
+               gettimeofday(&tval, 0);\r
+               gp2x_video_wait_vsync();\r
+               gettimeofday(&tval, 0);\r
+               vsync_offset = tval.tv_usec;\r
+               while (vsync_offset >= target_frametime)\r
+                       vsync_offset -= target_frametime;\r
+               if (!vsync_offset) vsync_offset++;\r
+               printf("vsync_offset: %i\n", vsync_offset);\r
+       } else\r
+               vsync_offset = 0;\r
+\r
        // loop?\r
        while (engineState == PGS_Running)\r
        {\r
@@ -1122,7 +1190,9 @@ void emu_Loop(void)
                                        vidCpyM2 = vidCpyM2_32col;\r
                                }\r
                        }\r
-                       gp2x_video_RGB_setscaling(scalex, 240);\r
+                       if (currentConfig.scaling == 2 && !(modes&8)) // want vertical scaling and game is not in 240 line mode\r
+                            gp2x_video_RGB_setscaling(8, scalex, 224);\r
+                       else gp2x_video_RGB_setscaling(0, scalex, 240);\r
                        oldmodes = modes;\r
                        clearArea(1);\r
                }\r
@@ -1161,7 +1231,7 @@ void emu_Loop(void)
                        }\r
                }\r
 \r
-               lim_time = (frames_done+1) * target_frametime;\r
+               lim_time = (frames_done+1) * target_frametime + vsync_offset;\r
                if(currentConfig.Frameskip >= 0) { // frameskip enabled\r
                        for(i = 0; i < currentConfig.Frameskip; i++) {\r
                                updateKeys();\r
@@ -1177,8 +1247,14 @@ void emu_Loop(void)
                        }\r
                } else if(tval.tv_usec > lim_time) { // auto frameskip\r
                        // no time left for this frame - skip\r
+                       if (tval.tv_usec - lim_time >= 0x300000) {\r
+                               /* something caused a slowdown for us (disk access? cache flush?)\r
+                                * try to recover by resetting timing... */\r
+                               reset_timing = 1;\r
+                               continue;\r
+                       }\r
                        updateKeys();\r
-                       SkipFrame(tval.tv_usec < lim_time+target_frametime); frames_done++;\r
+                       SkipFrame(tval.tv_usec < lim_time+target_frametime*2); frames_done++;\r
                        continue;\r
                }\r
 \r
@@ -1245,18 +1321,24 @@ if (Pico.m.frame_count == 31563) {
 \r
                // check time\r
                gettimeofday(&tval, 0);\r
-               if(thissec != tval.tv_sec) tval.tv_usec+=1000000;\r
+               if (thissec != tval.tv_sec) tval.tv_usec+=1000000;\r
 \r
-               // sleep if we are still too fast\r
-               if(PsndOut != 0 || currentConfig.Frameskip < 0)\r
+               if (currentConfig.Frameskip < 0 && tval.tv_usec - lim_time >= 0x300000) // slowdown detection\r
+                       reset_timing = 1;\r
+               else if (PsndOut != NULL || currentConfig.Frameskip < 0)\r
                {\r
+                       // sleep or vsync if we are still too fast\r
                        // usleep sleeps for ~20ms minimum, so it is not a solution here\r
-                       gettimeofday(&tval, 0);\r
-                       if(thissec != tval.tv_sec) tval.tv_usec+=1000000;\r
                        if(tval.tv_usec < lim_time)\r
                        {\r
                                // we are too fast\r
-                               simpleWait(thissec, lim_time);\r
+                               if (vsync_offset) {\r
+                                       if (lim_time - tval.tv_usec > target_frametime/2)\r
+                                               simpleWait(thissec, lim_time - target_frametime/4);\r
+                                       gp2x_video_wait_vsync();\r
+                               } else {\r
+                                       simpleWait(thissec, lim_time);\r
+                               }\r
                        }\r
                }\r
 \r
@@ -1265,9 +1347,12 @@ if (Pico.m.frame_count == 31563) {
                frames_done++; frames_shown++;\r
        }\r
 \r
+\r
+       if (PicoMCD & 1) PicoCDBufferFree();\r
+\r
        // save SRAM\r
        if((currentConfig.EmuOpt & 1) && SRam.changed) {\r
-               osd_text(4, 232, "Writing SRAM/BRAM..");\r
+               emu_state_cb("Writing SRAM/BRAM..");\r
                emu_SaveLoadGame(0, 1);\r
                SRam.changed = 0;\r
        }\r
@@ -1398,33 +1483,48 @@ int emu_SaveLoadGame(int load, int sram)
                FILE *sramFile;\r
                int sram_size;\r
                unsigned char *sram_data;\r
+               int truncate = 1;\r
                if (PicoMCD&1) {\r
-                       sram_size = 0x2000;\r
-                       sram_data = Pico_mcd->bram;\r
+                       if (PicoOpt&0x8000) { // MCD RAM cart?\r
+                               sram_size = 0x12000;\r
+                               sram_data = SRam.data;\r
+                               if (sram_data)\r
+                                       memcpy32((int *)sram_data, (int *)Pico_mcd->bram, 0x2000/4);\r
+                       } else {\r
+                               sram_size = 0x2000;\r
+                               sram_data = Pico_mcd->bram;\r
+                               truncate  = 0; // the .brm may contain RAM cart data after normal brm\r
+                       }\r
                } else {\r
                        sram_size = SRam.end-SRam.start+1;\r
                        if(SRam.reg_back & 4) sram_size=0x2000;\r
                        sram_data = SRam.data;\r
                }\r
-               if(!sram_data) return 0; // SRam forcefully disabled for this game\r
+               if (!sram_data) return 0; // SRam forcefully disabled for this game\r
 \r
-               if(load) {\r
+               if (load) {\r
                        sramFile = fopen(saveFname, "rb");\r
                        if(!sramFile) return -1;\r
                        fread(sram_data, 1, sram_size, sramFile);\r
                        fclose(sramFile);\r
+                       if ((PicoMCD&1) && (PicoOpt&0x8000))\r
+                               memcpy32((int *)Pico_mcd->bram, (int *)sram_data, 0x2000/4);\r
                } else {\r
                        // sram save needs some special processing\r
                        // see if we have anything to save\r
-                       for(; sram_size > 0; sram_size--)\r
-                               if(sram_data[sram_size-1]) break;\r
+                       for (; sram_size > 0; sram_size--)\r
+                               if (sram_data[sram_size-1]) break;\r
 \r
-                       if(sram_size) {\r
-                               sramFile = fopen(saveFname, "wb");\r
+                       if (sram_size) {\r
+                               sramFile = fopen(saveFname, truncate ? "wb" : "r+b");\r
+                               if (!sramFile) sramFile = fopen(saveFname, "wb"); // retry\r
+                               if (!sramFile) return -1;\r
                                ret = fwrite(sram_data, 1, sram_size, sramFile);\r
                                ret = (ret != sram_size) ? -1 : 0;\r
                                fclose(sramFile);\r
+#ifndef NO_SYNC\r
                                sync();\r
+#endif\r
                        }\r
                }\r
                return ret;\r
@@ -1448,8 +1548,10 @@ int emu_SaveLoadGame(int load, int sram)
                        ret = PmovState(load ? 6 : 5, PmovFile);\r
                        areaClose(PmovFile);\r
                        PmovFile = 0;\r
-                       if (!load) sync();\r
-                       else Pico.m.dirtyPal=1;\r
+                       if (load) Pico.m.dirtyPal=1;\r
+#ifndef NO_SYNC\r
+                       else sync();\r
+#endif\r
                }\r
                else    ret = -1;\r
                if (!ret)\r