renderers (interlace and stuff)
[picodrive.git] / platform / gizmondo / emu.c
1 #include <windows.h>
2 #include <string.h>
3
4 #include <sys/stat.h>  // mkdir
5 #include <sys/types.h>
6
7 #include "kgsdk/Framework.h"
8 #include "kgsdk/Framework2D.h"
9 #include "kgsdk/FrameworkAudio.h"
10 #include "../common/emu.h"
11 #include "../common/lprintf.h"
12 #include "../common/arm_utils.h"
13 #include "emu.h"
14 #include "menu.h"
15 #include "giz.h"
16 #include "asm_utils.h"
17
18 #include <Pico/PicoInt.h>
19
20 #ifdef BENCHMARK
21 #define OSD_FPS_X 220
22 #else
23 #define OSD_FPS_X 260
24 #endif
25
26 // main 300K gfx-related buffer. Used by menu and renderers.
27 unsigned char gfx_buffer[321*240*2*2];
28 char romFileName[MAX_PATH];
29 int engineState;
30
31 unsigned char *PicoDraw2FB = gfx_buffer;  // temporary buffer for alt renderer ( (8+320)*(8+240+8) )
32 int reset_timing = 0;
33
34 static int combo_keys = 0, combo_acts = 0; // keys and actions which need button combos
35 static DWORD noticeMsgTime = 0;
36 static short *snd_cbuff = NULL;
37 static int snd_cbuf_samples = 0, snd_all_samples = 0;
38
39
40 static void blit(const char *fps, const char *notice);
41 static void clearArea(int full);
42
43 void emu_noticeMsgUpdated(void)
44 {
45         noticeMsgTime = GetTickCount();
46 }
47
48 void emu_getMainDir(char *dst, int len)
49 {
50         if (len > 0) *dst = 0;
51 }
52
53 static void emu_msg_cb(const char *msg)
54 {
55         if (giz_screen == NULL)
56                 giz_screen = Framework2D_LockBuffer();
57
58         memset32((int *)((char *)giz_screen + 321*232*2), 0, 321*8*2/4);
59         emu_textOut16(4, 232, msg);
60         noticeMsgTime = GetTickCount() - 2000;
61
62         /* assumption: emu_msg_cb gets called only when something slow is about to happen */
63         reset_timing = 1;
64 }
65
66 static void emu_state_cb(const char *str)
67 {
68         if (giz_screen == NULL)
69                 giz_screen = Framework2D_LockBuffer();
70
71         clearArea(0);
72         blit("", str);
73
74         Framework2D_UnlockBuffer();
75         giz_screen = NULL;
76 }
77
78 static void emu_msg_tray_open(void)
79 {
80         strcpy(noticeMsg, "CD tray opened");
81         noticeMsgTime = GetTickCount();
82 }
83
84
85 void emu_Init(void)
86 {
87         // make dirs for saves, cfgs, etc.
88         mkdir("mds", 0777);
89         mkdir("srm", 0777);
90         mkdir("brm", 0777);
91         mkdir("cfg", 0777);
92
93         PicoInit();
94         PicoMessage = emu_msg_cb;
95         PicoMCDopenTray = emu_msg_tray_open;
96         PicoMCDcloseTray = menu_loop_tray;
97 }
98
99 void emu_Deinit(void)
100 {
101         // save SRAM
102         if((currentConfig.EmuOpt & 1) && SRam.changed) {
103                 emu_SaveLoadGame(0, 1);
104                 SRam.changed = 0;
105         }
106
107         if (!(currentConfig.EmuOpt & 0x20)) {
108                 FILE *f = fopen(PicoConfigFile, "r+b");
109                 if (!f) emu_WriteConfig(0);
110                 else {
111                         // if we already have config, reload it, except last ROM
112                         fseek(f, sizeof(currentConfig.lastRomFile), SEEK_SET);
113                         fread(&currentConfig.EmuOpt, 1, sizeof(currentConfig) - sizeof(currentConfig.lastRomFile), f);
114                         fseek(f, 0, SEEK_SET);
115                         fwrite(&currentConfig, 1, sizeof(currentConfig), f);
116                         fflush(f);
117                         fclose(f);
118                 }
119         }
120
121         PicoExit();
122 }
123
124 void emu_setDefaultConfig(void)
125 {
126         memset(&currentConfig, 0, sizeof(currentConfig));
127         currentConfig.lastRomFile[0] = 0;
128         currentConfig.EmuOpt  = 0x1f | 0x680; // | confirm_save, cd_leds, 16bit rend
129         currentConfig.PicoOpt = 0x07 | 0xc00; // | cd_pcm, cd_cdda
130         currentConfig.PsndRate = 22050;
131         currentConfig.PicoRegion = 0; // auto
132         currentConfig.PicoAutoRgnOrder = 0x184; // US, EU, JP
133         currentConfig.Frameskip = -1; // auto
134         currentConfig.volume = 50;
135         currentConfig.KeyBinds[ 2] = 1<<0; // SACB RLDU
136         currentConfig.KeyBinds[ 3] = 1<<1;
137         currentConfig.KeyBinds[ 0] = 1<<2;
138         currentConfig.KeyBinds[ 1] = 1<<3;
139         currentConfig.KeyBinds[ 5] = 1<<4;
140         currentConfig.KeyBinds[ 6] = 1<<5;
141         currentConfig.KeyBinds[ 7] = 1<<6;
142         currentConfig.KeyBinds[ 4] = 1<<7;
143         currentConfig.KeyBinds[13] = 1<<26; // switch rend
144         currentConfig.KeyBinds[ 8] = 1<<27; // save state
145         currentConfig.KeyBinds[ 9] = 1<<28; // load state
146         currentConfig.KeyBinds[12] = 1<<29; // vol up
147         currentConfig.KeyBinds[11] = 1<<30; // vol down
148         currentConfig.PicoCDBuffers = 0;
149         currentConfig.scaling = 0;
150 }
151
152
153 static int EmuScan16(unsigned int num, void *sdata)
154 {
155         if (!(Pico.video.reg[1]&8)) num += 8;
156         DrawLineDest = (unsigned short *) giz_screen + 321*(num+1);
157
158         if ((currentConfig.EmuOpt&0x4000) && (num&1) == (Pico.m.frame_count&1))
159                 return 1; // skip next line
160
161         return 0;
162 }
163
164 static int EmuScan8(unsigned int num, void *sdata)
165 {
166         // draw like the fast renderer
167         if (!(Pico.video.reg[1]&8)) num += 8;
168         HighCol = gfx_buffer + 328*(num+1);
169
170         return 0;
171 }
172
173 static void osd_text(int x, int y, const char *text)
174 {
175         int len = strlen(text) * 8 / 2;
176         int *p, h;
177         for (h = 0; h < 8; h++) {
178                 p = (int *) ((unsigned short *) giz_screen+x+321*(y+h));
179                 p = (int *) ((int)p & ~3); // align
180                 memset32(p, 0, len);
181         }
182         emu_textOut16(x, y, text);
183 }
184
185 /*
186 void log1(void *p1, void *p2)
187 {
188         lprintf("%p %p %p\n", p1, p2, DrawLineDest);
189 }
190 */
191
192 static void cd_leds(void)
193 {
194         static int old_reg = 0;
195         unsigned int col_g, col_r, *p;
196
197         if (!((Pico_mcd->s68k_regs[0] ^ old_reg) & 3)) return; // no change
198         old_reg = Pico_mcd->s68k_regs[0];
199
200         p = (unsigned int *)((short *)giz_screen + 321*2+4+2);
201         col_g = (old_reg & 2) ? 0x06000600 : 0;
202         col_r = (old_reg & 1) ? 0xc000c000 : 0;
203         *p++ = col_g; *p++ = col_g; p+=2; *p++ = col_r; *p++ = col_r; p += 321/2 - 12/2 + 1;
204         *p++ = col_g; p+=3; *p++ = col_r; p += 321/2 - 10/2;
205         *p++ = col_g; *p++ = col_g; p+=2; *p++ = col_r; *p++ = col_r;
206 }
207
208
209 static short localPal[0x100];
210
211 static void blit(const char *fps, const char *notice)
212 {
213         int emu_opt = currentConfig.EmuOpt;
214
215         if (PicoOpt&0x10)
216         {
217                 int lines_flags = 224;
218                 // 8bit fast renderer
219                 if (Pico.m.dirtyPal) {
220                         Pico.m.dirtyPal = 0;
221                         vidConvCpyRGB565(localPal, Pico.cram, 0x40);
222                 }
223                 if (!(Pico.video.reg[12]&1)) lines_flags|=0x10000;
224                 if (currentConfig.EmuOpt&0x4000)
225                         lines_flags|=(Pico.m.frame_count&1)?0x20000:0x40000;
226                 vidCpy8to16((unsigned short *)giz_screen+321*8, PicoDraw2FB+328*8, localPal, lines_flags);
227         }
228         else if (!(emu_opt&0x80))
229         {
230                 int lines_flags;
231                 // 8bit accurate renderer
232                 if (Pico.m.dirtyPal) {
233                         Pico.m.dirtyPal = 0;
234                         vidConvCpyRGB565(localPal, Pico.cram, 0x40);
235                         if (Pico.video.reg[0xC]&8) { // shadow/hilight mode
236                                 //vidConvCpyRGB32sh(localPal+0x40, Pico.cram, 0x40);
237                                 //vidConvCpyRGB32hi(localPal+0x80, Pico.cram, 0x40); // TODO?
238                                 blockcpy(localPal+0xc0, localPal+0x40, 0x40*2);
239                                 localPal[0xc0] = 0x0600;
240                                 localPal[0xd0] = 0xc000;
241                                 localPal[0xe0] = 0x0000; // reserved pixels for OSD
242                                 localPal[0xf0] = 0xffff;
243                         }
244                         /* no support
245                         else if (rendstatus & 0x20) { // mid-frame palette changes
246                                 vidConvCpyRGB565(localPal+0x40, HighPal, 0x40);
247                                 vidConvCpyRGB565(localPal+0x80, HighPal+0x40, 0x40);
248                         } */
249                 }
250                 lines_flags = (Pico.video.reg[1]&8) ? 240 : 224;
251                 if (!(Pico.video.reg[12]&1)) lines_flags|=0x10000;
252                 if (currentConfig.EmuOpt&0x4000)
253                         lines_flags|=(Pico.m.frame_count&1)?0x20000:0x40000;
254                 vidCpy8to16((unsigned short *)giz_screen+321*8, PicoDraw2FB+328*8, localPal, lines_flags);
255         }
256
257         if (notice || (emu_opt & 2)) {
258                 int h = 232;
259                 if (notice)      osd_text(4, h, notice);
260                 if (emu_opt & 2) osd_text(OSD_FPS_X, h, fps);
261         }
262
263         if ((emu_opt & 0x400) && (PicoMCD & 1))
264                 cd_leds();
265 }
266
267 // clears whole screen or just the notice area (in all buffers)
268 static void clearArea(int full)
269 {
270         if (giz_screen == NULL)
271                 giz_screen = Framework2D_LockBuffer();
272         if (full) memset32(giz_screen, 0, 320*240*2/4);
273         else      memset32((int *)((char *)giz_screen + 321*232*2), 0, 321*8*2/4);
274 }
275
276 static void vidResetMode(void)
277 {
278         giz_screen = Framework2D_LockBuffer();
279
280         if (PicoOpt&0x10) {
281         } else if (currentConfig.EmuOpt&0x80) {
282                 PicoDrawSetColorFormat(1);
283                 PicoScan = EmuScan16;
284         } else {
285                 PicoDrawSetColorFormat(-1);
286                 PicoScan = EmuScan8;
287         }
288         if ((PicoOpt&0x10) || !(currentConfig.EmuOpt&0x80)) {
289                 // setup pal for 8-bit modes
290                 localPal[0xc0] = 0x0600;
291                 localPal[0xd0] = 0xc000;
292                 localPal[0xe0] = 0x0000; // reserved pixels for OSD
293                 localPal[0xf0] = 0xffff;
294         }
295         Pico.m.dirtyPal = 1;
296
297         memset32(giz_screen, 0, 321*240*2/4);
298         Framework2D_UnlockBuffer();
299         giz_screen = NULL;
300 }
301
302
303 #include <stdarg.h>
304 static void stdbg(const char *fmt, ...)
305 {
306         static int cnt = 0;
307         va_list vl;
308
309         sprintf(noticeMsg, "%x ", cnt++);
310         va_start(vl, fmt);
311         vsnprintf(noticeMsg+strlen(noticeMsg), sizeof(noticeMsg)-strlen(noticeMsg), fmt, vl);
312         va_end(vl);
313
314         noticeMsgTime = GetTickCount();
315 }
316
317
318 static void updateSound(int len)
319 {
320         if (PicoOpt&8) len<<=1;
321
322         snd_all_samples += len;
323         PsndOut += len;
324         if (PsndOut - snd_cbuff >= snd_cbuf_samples)
325         {
326                 if (PsndOut - snd_cbuff != snd_cbuf_samples)
327                         stdbg("snd diff is %i, not %i", PsndOut - snd_cbuff, snd_cbuf_samples);
328                 PsndOut = snd_cbuff;
329         }
330 }
331
332
333 static void SkipFrame(void)
334 {
335         PicoSkipFrame=1;
336         PicoFrame();
337         PicoSkipFrame=0;
338 }
339
340 void emu_forcedFrame(void)
341 {
342         int po_old = PicoOpt;
343         int eo_old = currentConfig.EmuOpt;
344
345         PicoOpt &= ~0x0010;
346         PicoOpt |=  0x4080; // soft_scale | acc_sprites
347         currentConfig.EmuOpt |= 0x80;
348
349         if (giz_screen == NULL)
350                 giz_screen = Framework2D_LockBuffer();
351
352         PicoDrawSetColorFormat(1);
353         PicoScan = EmuScan16;
354         PicoScan((unsigned) -1, NULL);
355         Pico.m.dirtyPal = 1;
356         PicoFrameDrawOnly();
357
358         Framework2D_UnlockBuffer();
359         giz_screen = NULL;
360
361         PicoOpt = po_old;
362         currentConfig.EmuOpt = eo_old;
363 }
364
365
366 static void RunEvents(unsigned int which)
367 {
368         if (which & 0x1800) { // save or load (but not both)
369                 int do_it = 1;
370                 if ( emu_checkSaveFile(state_slot) &&
371                                 (( (which & 0x1000) && (currentConfig.EmuOpt & 0x800)) || // load
372                                  (!(which & 0x1000) && (currentConfig.EmuOpt & 0x200))) ) // save
373                 {
374                         int keys;
375                         if (giz_screen == NULL)
376                                 giz_screen = Framework2D_LockBuffer();
377                         blit("", (which & 0x1000) ? "LOAD STATE? (PLAY=yes, STOP=no)" : "OVERWRITE SAVE? (PLAY=yes, STOP=no)");
378                         while( !((keys = Framework_PollGetButtons()) & (BTN_PLAY|BTN_STOP)) )
379                                 Sleep(50);
380                         if (keys & BTN_STOP) do_it = 0;
381                         clearArea(0);
382                 }
383                 if (do_it) {
384                         osd_text(4, 232, (which & 0x1000) ? "LOADING GAME" : "SAVING GAME");
385                         PicoStateProgressCB = emu_state_cb;
386                         emu_SaveLoadGame((which & 0x1000) >> 12, 0);
387                         PicoStateProgressCB = NULL;
388                 }
389
390                 reset_timing = 1;
391         }
392         if (which & 0x0400) { // switch renderer
393                 if (PicoOpt&0x10) { PicoOpt&=~0x10; currentConfig.EmuOpt |=  0x80; }
394                 else              { PicoOpt|= 0x10; currentConfig.EmuOpt &= ~0x80; }
395
396                 vidResetMode();
397
398                 if (PicoOpt&0x10) {
399                         strcpy(noticeMsg, " 8bit fast renderer");
400                 } else if (currentConfig.EmuOpt&0x80) {
401                         strcpy(noticeMsg, "16bit accurate renderer");
402                 } else {
403                         strcpy(noticeMsg, " 8bit accurate renderer");
404                 }
405
406                 noticeMsgTime = GetTickCount();
407         }
408         if (which & 0x0300) {
409                 if(which&0x0200) {
410                         state_slot -= 1;
411                         if(state_slot < 0) state_slot = 9;
412                 } else {
413                         state_slot += 1;
414                         if(state_slot > 9) state_slot = 0;
415                 }
416                 sprintf(noticeMsg, "SAVE SLOT %i [%s]", state_slot, emu_checkSaveFile(state_slot) ? "USED" : "FREE");
417                 noticeMsgTime = GetTickCount();
418         }
419 }
420
421 static void updateKeys(void)
422 {
423         unsigned int keys, allActions[2] = { 0, 0 }, events;
424         static unsigned int prevEvents = 0;
425         int i;
426
427         keys = Framework_PollGetButtons();
428         if (keys & BTN_HOME)
429                 engineState = PGS_Menu;
430
431         keys &= CONFIGURABLE_KEYS;
432
433         for (i = 0; i < 32; i++)
434         {
435                 if (keys & (1 << i))
436                 {
437                         int pl, acts = currentConfig.KeyBinds[i];
438                         if (!acts) continue;
439                         pl = (acts >> 16) & 1;
440                         if (combo_keys & (1 << i))
441                         {
442                                 int u = i+1, acts_c = acts & combo_acts;
443                                 // let's try to find the other one
444                                 if (acts_c)
445                                         for (; u < 32; u++)
446                                                 if ( (currentConfig.KeyBinds[u] & acts_c) && (keys & (1 << u)) ) {
447                                                         allActions[pl] |= acts_c;
448                                                         keys &= ~((1 << i) | (1 << u));
449                                                         break;
450                                                 }
451                                 // add non-combo actions if combo ones were not found
452                                 if (!acts_c || u == 32)
453                                         allActions[pl] |= acts & ~combo_acts;
454                         } else {
455                                 allActions[pl] |= acts;
456                         }
457                 }
458         }
459
460         PicoPad[0] = (unsigned short) allActions[0];
461         PicoPad[1] = (unsigned short) allActions[1];
462
463         events = (allActions[0] | allActions[1]) >> 16;
464
465         // volume is treated in special way and triggered every frame
466         if ((events & 0x6000) && PsndOut != NULL)
467         {
468                 int vol = currentConfig.volume;
469                 if (events & 0x2000) {
470                         if (vol < 100) vol++;
471                 } else {
472                         if (vol >   0) vol--;
473                 }
474                 FrameworkAudio_SetVolume(vol, vol);
475                 sprintf(noticeMsg, "VOL: %02i", vol);
476                 noticeMsgTime = GetTickCount();
477                 currentConfig.volume = vol;
478         }
479
480         events &= ~prevEvents;
481         if (events) RunEvents(events);
482         if (movie_data) emu_updateMovie();
483
484         prevEvents = (allActions[0] | allActions[1]) >> 16;
485 }
486
487 static void find_combos(void)
488 {
489         int act, u;
490
491         // find out which keys and actions are combos
492         combo_keys = combo_acts = 0;
493         for (act = 0; act < 32; act++)
494         {
495                 int keyc = 0;
496                 if (act == 16 || act == 17) continue; // player2 flag
497                 for (u = 0; u < 32; u++)
498                 {
499                         if (currentConfig.KeyBinds[u] & (1 << act)) keyc++;
500                 }
501                 if (keyc > 1)
502                 {
503                         // loop again and mark those keys and actions as combo
504                         for (u = 0; u < 32; u++)
505                         {
506                                 if (currentConfig.KeyBinds[u] & (1 << act)) {
507                                         combo_keys |= 1 << u;
508                                         combo_acts |= 1 << act;
509                                 }
510                         }
511                 }
512         }
513 }
514
515
516 static void simpleWait(DWORD until)
517 {
518         DWORD tval;
519         int diff;
520
521         tval = GetTickCount();
522         diff = (int)until - (int)tval;
523         if (diff >= 2)
524                 Sleep(diff - 1);
525
526         while ((tval = GetTickCount()) < until && until - tval < 512) // some simple overflow detection
527                 spend_cycles(1024*2);
528 }
529
530 void emu_Loop(void)
531 {
532         static int PsndRate_old = 0, PicoOpt_old = 0, pal_old = 0;
533         char fpsbuff[24]; // fps count c string
534         DWORD tval, tval_prev = 0, tval_thissec = 0; // timing
535         int frames_done = 0, frames_shown = 0, oldmodes = 0, sec_ms = 1000;
536         int target_fps, target_frametime, lim_time, tval_diff, i;
537         char *notice = NULL;
538
539         lprintf("entered emu_Loop()\n");
540
541         fpsbuff[0] = 0;
542
543         // make sure we are in correct mode
544         vidResetMode();
545         if (currentConfig.scaling) PicoOpt|=0x4000;
546         else PicoOpt&=~0x4000;
547         Pico.m.dirtyPal = 1;
548         oldmodes = ((Pico.video.reg[12]&1)<<2) ^ 0xc;
549         find_combos();
550
551         // pal/ntsc might have changed, reset related stuff
552         target_fps = Pico.m.pal ? 50 : 60;
553         target_frametime = Pico.m.pal ? (1000<<8)/50 : (1000<<8)/60+1;
554         reset_timing = 1;
555
556         // prepare CD buffer
557         if (PicoMCD & 1) PicoCDBufferInit();
558
559         // prepare sound stuff
560         PsndOut = NULL;
561         if (currentConfig.EmuOpt & 4)
562         {
563                 int ret, snd_excess_add, stereo=(PicoOpt&8)>>3;
564                 if (PsndRate != PsndRate_old || (PicoOpt&0x0b) != (PicoOpt_old&0x0b) || Pico.m.pal != pal_old) {
565                         sound_rerate(Pico.m.frame_count ? 1 : 0);
566                 }
567                 snd_excess_add = ((PsndRate - PsndLen*target_fps)<<16) / target_fps;
568                 snd_cbuf_samples = (PsndRate<<stereo) * 16 / target_fps;
569                 lprintf("starting audio: %i len: %i (ex: %04x) stereo: %i, pal: %i\n",
570                         PsndRate, PsndLen, snd_excess_add, stereo, Pico.m.pal);
571                 ret = FrameworkAudio_Init(PsndRate, snd_cbuf_samples, stereo);
572                 if (ret != 0) {
573                         lprintf("FrameworkAudio_Init() failed: %i\n", ret);
574                         sprintf(noticeMsg, "sound init failed (%i), snd disabled", ret);
575                         noticeMsgTime = GetTickCount();
576                         currentConfig.EmuOpt &= ~4;
577                 } else {
578                         FrameworkAudio_SetVolume(currentConfig.volume, currentConfig.volume);
579                         PicoWriteSound = updateSound;
580                         snd_cbuff = FrameworkAudio_56448Buffer();
581                         PsndOut = snd_cbuff + snd_cbuf_samples / 2; // start writing at the middle
582                         snd_all_samples = 0;
583                         PsndRate_old = PsndRate;
584                         PicoOpt_old  = PicoOpt;
585                         pal_old = Pico.m.pal;
586                 }
587         }
588
589         // loop?
590         while (engineState == PGS_Running)
591         {
592                 int modes;
593
594                 tval = GetTickCount();
595                 if (reset_timing || tval < tval_prev) {
596                         stdbg("timing reset");
597                         reset_timing = 0;
598                         tval_thissec = tval;
599                         frames_shown = frames_done = 0;
600                 }
601
602                 // show notice message?
603                 if (noticeMsgTime) {
604                         static int noticeMsgSum;
605                         if (tval - noticeMsgTime > 2000) { // > 2.0 sec
606                                 noticeMsgTime = 0;
607                                 clearArea(0);
608                                 notice = 0;
609                         } else {
610                                 int sum = noticeMsg[0]+noticeMsg[1]+noticeMsg[2];
611                                 if (sum != noticeMsgSum) { clearArea(0); noticeMsgSum = sum; }
612                                 notice = noticeMsg;
613                         }
614                 }
615
616                 // check for mode changes
617                 modes = ((Pico.video.reg[12]&1)<<2)|(Pico.video.reg[1]&8);
618                 if (modes != oldmodes) {
619                         oldmodes = modes;
620                         clearArea(1);
621                 }
622
623                 // second passed?
624                 if (tval - tval_thissec >= sec_ms)
625                 {
626 #ifdef BENCHMARK
627                         static int bench = 0, bench_fps = 0, bench_fps_s = 0, bfp = 0, bf[4];
628                         if(++bench == 10) {
629                                 bench = 0;
630                                 bench_fps_s = bench_fps;
631                                 bf[bfp++ & 3] = bench_fps;
632                                 bench_fps = 0;
633                         }
634                         bench_fps += frames_shown;
635                         sprintf(fpsbuff, "%02i/%02i/%02i", frames_shown, bench_fps_s, (bf[0]+bf[1]+bf[2]+bf[3])>>2);
636 #else
637                         if(currentConfig.EmuOpt & 2)
638                                 sprintf(fpsbuff, "%02i/%02i", frames_shown, frames_done);
639 #endif
640                         //tval_thissec += 1000;
641                         tval_thissec += sec_ms;
642
643                         if (PsndOut != NULL)
644                         {
645                                 /* some code which tries to sync things to audio clock, the dirty way */
646                                 static int audio_skew_prev = 0;
647                                 int audio_skew, adj, co = 9, shift = 7;
648                                 audio_skew = snd_all_samples*2 - FrameworkAudio_BufferPos();
649                                 if (PsndRate == 22050) co = 10;
650                                 if (PsndRate  > 22050) co = 11;
651                                 if (PicoOpt&8) shift++;
652                                 if (audio_skew < 0) {
653                                         adj = -((-audio_skew) >> shift);
654                                         if (audio_skew > -(6<<co)) adj>>=1;
655                                         if (audio_skew > -(4<<co)) adj>>=1;
656                                         if (audio_skew > -(2<<co)) adj>>=1;
657                                         if (audio_skew > audio_skew_prev) adj>>=2; // going up already
658                                 } else {
659                                         adj = audio_skew >> shift;
660                                         if (audio_skew < (6<<co)) adj>>=1;
661                                         if (audio_skew < (4<<co)) adj>>=1;
662                                         if (audio_skew < (2<<co)) adj>>=1;
663                                         if (audio_skew < audio_skew_prev) adj>>=2;
664                                 }
665                                 audio_skew_prev = audio_skew;
666                                 target_frametime += adj;
667                                 sec_ms = (target_frametime * target_fps) >> 8;
668                                 stdbg("%i %i %i", audio_skew, adj, sec_ms);
669                                 frames_done = frames_shown = 0;
670                         }
671                         else if (currentConfig.Frameskip < 0) {
672                                 frames_done  -= target_fps; if (frames_done  < 0) frames_done  = 0;
673                                 frames_shown -= target_fps; if (frames_shown < 0) frames_shown = 0;
674                                 if (frames_shown > frames_done) frames_shown = frames_done;
675                         } else {
676                                 frames_done = frames_shown = 0;
677                         }
678                 }
679 #ifdef PFRAMES
680                 sprintf(fpsbuff, "%i", Pico.m.frame_count);
681 #endif
682
683                 tval_prev = tval;
684                 lim_time = (frames_done+1) * target_frametime;
685                 if (currentConfig.Frameskip >= 0) // frameskip enabled
686                 {
687                         for (i = 0; i < currentConfig.Frameskip; i++) {
688                                 updateKeys();
689                                 SkipFrame(); frames_done++;
690                                 if (PsndOut) { // do framelimitting if sound is enabled
691                                         int tval_diff;
692                                         tval = GetTickCount();
693                                         tval_diff = (int)(tval - tval_thissec) << 8;
694                                         if (tval_diff < lim_time) // we are too fast
695                                                 simpleWait(tval + ((lim_time - tval_diff)>>8));
696                                 }
697                                 lim_time += target_frametime;
698                         }
699                 }
700                 else // auto frameskip
701                 {
702                         int tval_diff;
703                         tval = GetTickCount();
704                         tval_diff = (int)(tval - tval_thissec) << 8;
705                         if (tval_diff > lim_time)
706                         {
707                                 // no time left for this frame - skip
708                                 if (tval_diff - lim_time >= (300<<8)) {
709                                         /* something caused a slowdown for us (disk access? cache flush?)
710                                          * try to recover by resetting timing... */
711                                         reset_timing = 1;
712                                         continue;
713                                 }
714                                 updateKeys();
715                                 SkipFrame(); frames_done++;
716                                 continue;
717                         }
718                 }
719
720                 updateKeys();
721
722                 if (giz_screen == NULL && (currentConfig.EmuOpt&0x80))
723                         giz_screen = Framework2D_LockBuffer();
724                 if (!(PicoOpt&0x10))
725                         PicoScan((unsigned) -1, NULL);
726
727                 PicoFrame();
728
729                 if (currentConfig.EmuOpt&0x2000)
730                         Framework2D_WaitVSync();
731
732                 if (giz_screen == NULL)
733                         giz_screen = Framework2D_LockBuffer();
734
735                 blit(fpsbuff, notice);
736
737                 if (giz_screen != NULL) {
738                         Framework2D_UnlockBuffer();
739                         giz_screen = NULL;
740                 }
741
742                 // check time
743                 tval = GetTickCount();
744                 tval_diff = (int)(tval - tval_thissec) << 8;
745
746                 if (currentConfig.Frameskip < 0 && tval_diff - lim_time >= (300<<8)) // slowdown detection
747                         reset_timing = 1;
748                 else if (PsndOut != NULL || currentConfig.Frameskip < 0)
749                 {
750                         // sleep if we are still too fast
751                         if (tval_diff < lim_time)
752                         {
753                                 // we are too fast
754                                 simpleWait(tval + ((lim_time - tval_diff) >> 8));
755                         }
756                 }
757
758                 frames_done++; frames_shown++;
759         }
760
761
762         if (PicoMCD & 1) PicoCDBufferFree();
763
764         if (PsndOut != NULL) {
765                 PsndOut = snd_cbuff = NULL;
766                 FrameworkAudio_Close();
767         }
768
769         // save SRAM
770         if ((currentConfig.EmuOpt & 1) && SRam.changed) {
771                 emu_state_cb("Writing SRAM/BRAM..");
772                 emu_SaveLoadGame(0, 1);
773                 SRam.changed = 0;
774         }
775 }
776
777
778 void emu_ResetGame(void)
779 {
780         PicoReset(0);
781         reset_timing = 1;
782 }
783