1.35a psp bugfix release
[picodrive.git] / platform / psp / emu.c
1 // (c) Copyright 2007 notaz, All rights reserved.
2 // Free for non-commercial use.
3
4 // For commercial use, separate licencing terms must be obtained.
5
6 #include <sys/stat.h>
7 #include <sys/types.h>
8 #include <sys/syslimits.h> // PATH_MAX
9
10 #include <pspthreadman.h>
11 #include <pspdisplay.h>
12 #include <psputils.h>
13 #include <pspgu.h>
14 #include <pspaudio.h>
15
16 #include "psp.h"
17 #include "menu.h"
18 #include "emu.h"
19 #include "mp3.h"
20 #include "../common/emu.h"
21 #include "../common/lprintf.h"
22 #include "../../Pico/PicoInt.h"
23
24 #define OSD_FPS_X 424
25
26 // additional pspaudio imports, credits to crazyc
27 int sceAudio_38553111(unsigned short samples, unsigned short freq, char unknown);  // play with conversion?
28 int sceAudio_5C37C0AE(void);                            // end play?
29 int sceAudio_E0727056(int volume, void *buffer);        // blocking output
30 int sceAudioOutput2GetRestSample();
31
32
33 char romFileName[PATH_MAX];
34 unsigned char *PicoDraw2FB = (unsigned char *)VRAM_CACHED_STUFF + 8; // +8 to be able to skip border with 1 quadword..
35 int engineState;
36
37 static int combo_keys = 0, combo_acts = 0; // keys and actions which need button combos
38 static unsigned int noticeMsgTime = 0;
39 int reset_timing = 0; // do we need this?
40
41
42 static void sound_init(void);
43 static void sound_deinit(void);
44 static void blit2(const char *fps, const char *notice, int lagging_behind);
45 static void clearArea(int full);
46
47 void emu_noticeMsgUpdated(void)
48 {
49         noticeMsgTime = sceKernelGetSystemTimeLow();
50 }
51
52 void emu_getMainDir(char *dst, int len)
53 {
54         if (len > 0) *dst = 0;
55 }
56
57 static void osd_text(int x, const char *text, int is_active, int clear_all)
58 {
59         unsigned short *screen = is_active ? psp_video_get_active_fb() : psp_screen;
60         int len = clear_all ? (480 / 2) : (strlen(text) * 8 / 2);
61         int *p, h;
62         void *tmp;
63         for (h = 0; h < 8; h++) {
64                 p = (int *) (screen+x+512*(264+h));
65                 p = (int *) ((int)p & ~3); // align
66                 memset32_uncached(p, 0, len);
67         }
68         if (is_active) { tmp = psp_screen; psp_screen = screen; } // nasty pointer tricks
69         emu_textOut16(x, 264, text);
70         if (is_active) psp_screen = tmp;
71 }
72
73 void emu_msg_cb(const char *msg)
74 {
75         osd_text(4, msg, 1, 1);
76         noticeMsgTime = sceKernelGetSystemTimeLow() - 2000000;
77
78         /* assumption: emu_msg_cb gets called only when something slow is about to happen */
79         reset_timing = 1;
80 }
81
82 static void emu_msg_tray_open(void)
83 {
84         strcpy(noticeMsg, "CD tray opened");
85         noticeMsgTime = sceKernelGetSystemTimeLow();
86 }
87
88
89 void emu_Init(void)
90 {
91         // make dirs for saves, cfgs, etc.
92         mkdir("mds", 0777);
93         mkdir("srm", 0777);
94         mkdir("brm", 0777);
95         mkdir("cfg", 0777);
96
97         sound_init();
98
99         PicoInit();
100         PicoMessage = emu_msg_cb;
101         PicoMCDopenTray = emu_msg_tray_open;
102         PicoMCDcloseTray = menu_loop_tray;
103 }
104
105 void emu_Deinit(void)
106 {
107         // save SRAM
108         if ((currentConfig.EmuOpt & 1) && SRam.changed) {
109                 emu_SaveLoadGame(0, 1);
110                 SRam.changed = 0;
111         }
112
113         if (!(currentConfig.EmuOpt & 0x20)) {
114                 FILE *f = fopen(PicoConfigFile, "r+b");
115                 if (!f) emu_WriteConfig(0);
116                 else {
117                         // if we already have config, reload it, except last ROM
118                         fseek(f, sizeof(currentConfig.lastRomFile), SEEK_SET);
119                         fread(&currentConfig.EmuOpt, 1, sizeof(currentConfig) - sizeof(currentConfig.lastRomFile), f);
120                         fseek(f, 0, SEEK_SET);
121                         fwrite(&currentConfig, 1, sizeof(currentConfig), f);
122                         fflush(f);
123                         fclose(f);
124                 }
125         }
126
127         PicoExit();
128         sound_deinit();
129 }
130
131 void emu_setDefaultConfig(void)
132 {
133         memset(&currentConfig, 0, sizeof(currentConfig));
134         currentConfig.lastRomFile[0] = 0;
135         currentConfig.EmuOpt  = 0x1d | 0x680;  // | confirm_save, cd_leds, acc rend
136         currentConfig.PicoOpt = 0x0f | 0x1c00; // | gfx_cd, cd_pcm, cd_cdda
137         currentConfig.PsndRate = 22050;
138         currentConfig.PicoRegion = 0; // auto
139         currentConfig.PicoAutoRgnOrder = 0x184; // US, EU, JP
140         currentConfig.Frameskip = -1; // auto
141         currentConfig.volume = 50;
142         currentConfig.CPUclock = 333;
143         currentConfig.KeyBinds[ 4] = 1<<0; // SACB RLDU
144         currentConfig.KeyBinds[ 6] = 1<<1;
145         currentConfig.KeyBinds[ 7] = 1<<2;
146         currentConfig.KeyBinds[ 5] = 1<<3;
147         currentConfig.KeyBinds[14] = 1<<4;
148         currentConfig.KeyBinds[13] = 1<<5;
149         currentConfig.KeyBinds[15] = 1<<6;
150         currentConfig.KeyBinds[ 3] = 1<<7;
151         currentConfig.KeyBinds[12] = 1<<26; // switch rnd
152         currentConfig.KeyBinds[ 8] = 1<<27; // save state
153         currentConfig.KeyBinds[ 9] = 1<<28; // load state
154         currentConfig.KeyBinds[28] = 1<<0; // num "buttons"
155         currentConfig.KeyBinds[30] = 1<<1;
156         currentConfig.KeyBinds[31] = 1<<2;
157         currentConfig.KeyBinds[29] = 1<<3;
158         currentConfig.PicoCDBuffers = 64;
159         currentConfig.scaling = 1;     // bilinear filtering for psp
160         currentConfig.scale = 1.20;    // fullscreen
161         currentConfig.hscale40 = 1.25;
162         currentConfig.hscale32 = 1.56;
163 }
164
165
166 extern void amips_clut(unsigned short *dst, unsigned char *src, unsigned short *pal, int count);
167
168 struct Vertex
169 {
170         short u,v;
171         short x,y,z;
172 };
173
174 static struct Vertex __attribute__((aligned(4))) g_vertices[2];
175 static unsigned short __attribute__((aligned(16))) localPal[0x100];
176 static int dynamic_palette = 0, need_pal_upload = 0, blit_16bit_mode = 0;
177 static int fbimg_offs = 0;
178
179 static void set_scaling_params(void)
180 {
181         int src_width, fbimg_width, fbimg_height, fbimg_xoffs, fbimg_yoffs, border_hack = 0;
182         g_vertices[0].x = g_vertices[0].y =
183         g_vertices[0].z = g_vertices[1].z = 0;
184
185         fbimg_height = (int)(240.0 * currentConfig.scale + 0.5);
186         if (Pico.video.reg[12] & 1) {
187                 fbimg_width = (int)(320.0 * currentConfig.scale * currentConfig.hscale40 + 0.5);
188                 src_width = 320;
189         } else {
190                 fbimg_width = (int)(256.0 * currentConfig.scale * currentConfig.hscale32 + 0.5);
191                 src_width = 256;
192         }
193
194         if (fbimg_width  & 1) fbimg_width++;  // make even
195         if (fbimg_height & 1) fbimg_height++;
196
197         if (fbimg_width >= 480) {
198                 g_vertices[0].u = (fbimg_width-480)/2;
199                 g_vertices[1].u = src_width - (fbimg_width-480)/2 - 1;
200                 fbimg_width = 480;
201                 fbimg_xoffs = 0;
202         } else {
203                 g_vertices[0].u = 0;
204                 g_vertices[1].u = src_width;
205                 fbimg_xoffs = 240 - fbimg_width/2;
206         }
207         if (fbimg_width > 320 && fbimg_width <= 480) border_hack = 1;
208
209         if (fbimg_height >= 272) {
210                 g_vertices[0].v = (fbimg_height-272)/2;
211                 g_vertices[1].v = 240 - (fbimg_height-272)/2;
212                 fbimg_height = 272;
213                 fbimg_yoffs = 0;
214         } else {
215                 g_vertices[0].v = 0;
216                 g_vertices[1].v = 240;
217                 fbimg_yoffs = 136 - fbimg_height/2;
218         }
219
220         g_vertices[1].x = fbimg_width;
221         g_vertices[1].y = fbimg_height;
222         if (fbimg_xoffs < 0) fbimg_xoffs = 0;
223         if (fbimg_yoffs < 0) fbimg_yoffs = 0;
224         if (border_hack) {
225                 g_vertices[0].u++;
226                 g_vertices[0].x++;
227                 g_vertices[1].u--;
228                 g_vertices[1].x--;
229         }
230         fbimg_offs = (fbimg_yoffs*512 + fbimg_xoffs) * 2; // dst is always 16bit
231
232         /*
233         lprintf("set_scaling_params:\n");
234         lprintf("offs: %i, %i\n", fbimg_xoffs, fbimg_yoffs);
235         lprintf("xy0, xy1: %i, %i; %i, %i\n", g_vertices[0].x, g_vertices[0].y, g_vertices[1].x, g_vertices[1].y);
236         lprintf("uv0, uv1: %i, %i; %i, %i\n", g_vertices[0].u, g_vertices[0].v, g_vertices[1].u, g_vertices[1].v);
237         */
238 }
239
240 static void do_pal_update(int allow_sh)
241 {
242         unsigned int *spal=(void *)Pico.cram;
243         unsigned int *dpal=(void *)localPal;
244         int i;
245
246         for (i = 0x3f/2; i >= 0; i--)
247                 dpal[i] = ((spal[i]&0x000f000f)<< 1)|((spal[i]&0x00f000f0)<<3)|((spal[i]&0x0f000f00)<<4);
248
249         if (allow_sh && (Pico.video.reg[0xC]&8)) // shadow/hilight?
250         {
251                 // shadowed pixels
252                 for (i = 0x3f/2; i >= 0; i--)
253                         dpal[0x20|i] = dpal[0x60|i] = (dpal[i]>>1)&0x738e738e;
254                 // hilighted pixels
255                 for (i = 0x3f; i >= 0; i--) {
256                         int t=localPal[i]&0xe71c;t+=0x4208;
257                         if (t&0x20) t|=0x1c;
258                         if (t&0x800) t|=0x700;
259                         if (t&0x10000) t|=0xe000;
260                         t&=0xe71c;
261                         localPal[0x80|i]=(unsigned short)t;
262                 }
263                 localPal[0xe0] = 0;
264         }
265         Pico.m.dirtyPal = 0;
266         need_pal_upload = 1;
267 }
268
269 static void do_slowmode_lines(int line_to)
270 {
271         int line = 0, line_len = (Pico.video.reg[12]&1) ? 320 : 256;
272         unsigned short *dst = (unsigned short *)VRAM_STUFF + 512*240/2;
273         unsigned char  *src = (unsigned char  *)VRAM_CACHED_STUFF + 16;
274         if (!(Pico.video.reg[1]&8)) { line = 8; dst += 512*8; src += 512*8; }
275
276         for (; line < line_to; line++, dst+=512, src+=512)
277                 amips_clut(dst, src, localPal, line_len);
278 }
279
280 static void EmuScanPrepare(void)
281 {
282         HighCol = (unsigned char *)VRAM_CACHED_STUFF + 8;
283         if (!(Pico.video.reg[1]&8)) HighCol += 8*512;
284
285         dynamic_palette = 0;
286         if (Pico.m.dirtyPal)
287                 do_pal_update(1);
288 }
289
290 static int EmuScanSlow(unsigned int num, void *sdata)
291 {
292         if (!(Pico.video.reg[1]&8)) num += 8;
293
294         if (Pico.m.dirtyPal) {
295                 if (!dynamic_palette) {
296                         do_slowmode_lines(num);
297                         dynamic_palette = 1;
298                 }
299                 do_pal_update(1);
300         }
301
302         if (dynamic_palette) {
303                 int line_len = (Pico.video.reg[12]&1) ? 320 : 256;
304                 void *dst = (char *)VRAM_STUFF + 512*240 + 512*2*num;
305                 amips_clut(dst, HighCol + 8, localPal, line_len);
306         } else
307                 HighCol = (unsigned char *)VRAM_CACHED_STUFF + (num+1)*512 + 8;
308
309         return 0;
310 }
311
312 static void blitscreen_clut(void)
313 {
314         int offs = fbimg_offs;
315         offs += (psp_screen == VRAM_FB0) ? VRAMOFFS_FB0 : VRAMOFFS_FB1;
316
317         sceGuSync(0,0); // sync with prev
318         sceGuStart(GU_DIRECT, guCmdList);
319         sceGuDrawBuffer(GU_PSM_5650, (void *)offs, 512); // point to back buffer
320
321         if (dynamic_palette)
322         {
323                 if (!blit_16bit_mode) {
324                         sceGuTexMode(GU_PSM_5650, 0, 0, 0);
325                         sceGuTexImage(0,512,512,512,(char *)VRAM_STUFF + 512*240);
326
327                         blit_16bit_mode = 1;
328                 }
329         }
330         else
331         {
332                 if (blit_16bit_mode) {
333                         sceGuClutMode(GU_PSM_5650,0,0xff,0);
334                         sceGuTexMode(GU_PSM_T8,0,0,0); // 8-bit image
335                         sceGuTexImage(0,512,512,512,(char *)VRAM_STUFF + 16);
336                         blit_16bit_mode = 0;
337                 }
338
339                 if ((PicoOpt&0x10) && Pico.m.dirtyPal)
340                         do_pal_update(0);
341
342                 sceKernelDcacheWritebackAll();
343
344                 if (need_pal_upload) {
345                         need_pal_upload = 0;
346                         sceGuClutLoad((256/8), localPal); // upload 32*8 entries (256)
347                 }
348         }
349
350 #if 1
351         if (g_vertices[0].u == 0 && g_vertices[1].u == g_vertices[1].x)
352         {
353                 struct Vertex* vertices;
354                 int x;
355
356                 #define SLICE_WIDTH 32
357                 for (x = 0; x < g_vertices[1].x; x += SLICE_WIDTH)
358                 {
359                         // render sprite
360                         vertices = (struct Vertex*)sceGuGetMemory(2 * sizeof(struct Vertex));
361                         memcpy(vertices, g_vertices, 2 * sizeof(struct Vertex));
362                         vertices[0].u = vertices[0].x = x;
363                         vertices[1].u = vertices[1].x = x + SLICE_WIDTH;
364                         sceGuDrawArray(GU_SPRITES,GU_TEXTURE_16BIT|GU_VERTEX_16BIT|GU_TRANSFORM_2D,2,0,vertices);
365                 }
366                 // lprintf("listlen: %iB\n", sceGuCheckList()); // ~480 only
367         }
368         else
369 #endif
370                 sceGuDrawArray(GU_SPRITES,GU_TEXTURE_16BIT|GU_VERTEX_16BIT|GU_TRANSFORM_2D,2,0,g_vertices);
371
372         sceGuFinish();
373 }
374
375
376 static void cd_leds(void)
377 {
378         unsigned int reg, col_g, col_r, *p;
379
380         reg = Pico_mcd->s68k_regs[0];
381
382         p = (unsigned int *)((short *)psp_screen + 512*2+4+2);
383         col_g = (reg & 2) ? 0x06000600 : 0;
384         col_r = (reg & 1) ? 0x00180018 : 0;
385         *p++ = col_g; *p++ = col_g; p+=2; *p++ = col_r; *p++ = col_r; p += 512/2 - 12/2;
386         *p++ = col_g; *p++ = col_g; p+=2; *p++ = col_r; *p++ = col_r; p += 512/2 - 12/2;
387         *p++ = col_g; *p++ = col_g; p+=2; *p++ = col_r; *p++ = col_r;
388 }
389
390 #if 0
391 static void dbg_text(void)
392 {
393         int *p, h, len;
394         char text[128];
395
396         sprintf(text, "sl: %i, 16b: %i", g_vertices[0].u == 0 && g_vertices[1].u == g_vertices[1].x, blit_16bit_mode);
397         len = strlen(text) * 8 / 2;
398         for (h = 0; h < 8; h++) {
399                 p = (int *) ((unsigned short *) psp_screen+2+512*(256+h));
400                 p = (int *) ((int)p & ~3); // align
401                 memset32_uncached(p, 0, len);
402         }
403         emu_textOut16(2, 256, text);
404 }
405 #endif
406
407 /* called after rendering is done, but frame emulation is not finished */
408 void blit1(void)
409 {
410         if (PicoOpt&0x10)
411         {
412                 int i;
413                 unsigned char *pd;
414                 // clear top and bottom trash
415                 for (pd = PicoDraw2FB+8, i = 8; i > 0; i--, pd += 512)
416                         memset32((int *)pd, 0xe0e0e0e0, 320/4);
417                 for (pd = PicoDraw2FB+512*232+8, i = 8; i > 0; i--, pd += 512)
418                         memset32((int *)pd, 0xe0e0e0e0, 320/4);
419         }
420
421         blitscreen_clut();
422 }
423
424
425 static void blit2(const char *fps, const char *notice, int lagging_behind)
426 {
427         int vsync = 0, emu_opt = currentConfig.EmuOpt;
428
429         if (notice || (emu_opt & 2)) {
430                 if (notice)      osd_text(4, notice, 0, 0);
431                 if (emu_opt & 2) osd_text(OSD_FPS_X, fps, 0, 0);
432         }
433
434         //dbg_text();
435
436         if ((emu_opt & 0x400) && (PicoMCD & 1))
437                 cd_leds();
438
439         if (currentConfig.EmuOpt & 0x2000) { // want vsync
440                 if (!(currentConfig.EmuOpt & 0x10000) || !lagging_behind) vsync = 1;
441         }
442
443         psp_video_flip(vsync);
444 }
445
446 // clears whole screen or just the notice area (in all buffers)
447 static void clearArea(int full)
448 {
449         if (full) {
450                 memset32_uncached(psp_screen, 0, 512*272*2/4);
451                 psp_video_flip(0);
452                 memset32_uncached(psp_screen, 0, 512*272*2/4);
453                 memset32(VRAM_CACHED_STUFF, 0xe0e0e0e0, 512*240/4);
454                 memset32((int *)VRAM_CACHED_STUFF+512*240/4, 0, 512*240*2/4);
455         } else {
456                 void *fb = psp_video_get_active_fb();
457                 memset32_uncached((int *)((char *)psp_screen + 512*264*2), 0, 512*8*2/4);
458                 memset32_uncached((int *)((char *)fb         + 512*264*2), 0, 512*8*2/4);
459         }
460 }
461
462 static void vidResetMode(void)
463 {
464         // setup GU
465         sceGuSync(0,0); // sync with prev
466         sceGuStart(GU_DIRECT, guCmdList);
467
468         sceGuClutMode(GU_PSM_5650,0,0xff,0);
469         sceGuTexMode(GU_PSM_T8,0,0,0); // 8-bit image
470         sceGuTexFunc(GU_TFX_REPLACE,GU_TCC_RGB);
471         if (currentConfig.scaling)
472              sceGuTexFilter(GU_LINEAR, GU_LINEAR);
473         else sceGuTexFilter(GU_NEAREST, GU_NEAREST);
474         sceGuTexScale(1.0f,1.0f);
475         sceGuTexOffset(0.0f,0.0f);
476
477         sceGuTexImage(0,512,512,512,(char *)VRAM_STUFF + 16);
478
479         // slow rend.
480         PicoDrawSetColorFormat(-1);
481         PicoScan = EmuScanSlow;
482
483         localPal[0xe0] = 0;
484         Pico.m.dirtyPal = 1;
485         blit_16bit_mode = dynamic_palette = 0;
486
487         sceGuFinish();
488         set_scaling_params();
489         sceGuSync(0,0);
490 }
491
492
493 /* sound stuff */
494 #define SOUND_BLOCK_SIZE_NTSC (1470*2) // 1024 // 1152
495 #define SOUND_BLOCK_SIZE_PAL  (1764*2)
496 #define SOUND_BLOCK_COUNT    8
497
498 static short __attribute__((aligned(4))) sndBuffer[SOUND_BLOCK_SIZE_PAL*SOUND_BLOCK_COUNT + 44100/50*2];
499 static short *snd_playptr = NULL, *sndBuffer_endptr = NULL;
500 static int samples_made = 0, samples_done = 0, samples_block = 0;
501 static int sound_thread_exit = 0;
502 static SceUID sound_sem = -1;
503
504 static void writeSound(int len);
505
506 static int sound_thread(SceSize args, void *argp)
507 {
508         int ret = 0;
509
510         lprintf("sthr: started, priority %i\n", sceKernelGetThreadCurrentPriority());
511
512         while (!sound_thread_exit)
513         {
514                 if (samples_made - samples_done < samples_block) {
515                         // wait for data (use at least 2 blocks)
516                         //lprintf("sthr: wait... (%i)\n", samples_made - samples_done);
517                         while (samples_made - samples_done <= samples_block*2 && !sound_thread_exit)
518                                 ret = sceKernelWaitSema(sound_sem, 1, 0);
519                         if (ret < 0) lprintf("sthr: sceKernelWaitSema: %i\n", ret);
520                         continue;
521                 }
522
523                 // lprintf("sthr: got data: %i\n", samples_made - samples_done);
524
525                 ret = sceAudio_E0727056(PSP_AUDIO_VOLUME_MAX, snd_playptr);
526
527                 samples_done += samples_block;
528                 snd_playptr  += samples_block;
529                 if (snd_playptr >= sndBuffer_endptr)
530                         snd_playptr = sndBuffer;
531                 // 1.5 kernel returns 0, newer ones return # of samples queued
532                 if (ret < 0)
533                         lprintf("sthr: sceAudio_E0727056: %08x; pos %i/%i\n", ret, samples_done, samples_made);
534
535                 // shouln't happen, but just in case
536                 if (samples_made - samples_done >= samples_block*3) {
537                         lprintf("sthr: block skip (%i)\n", samples_made - samples_done);
538                         samples_done += samples_block; // skip
539                         snd_playptr  += samples_block;
540                 }
541
542         }
543
544         lprintf("sthr: exit\n");
545         sceKernelExitDeleteThread(0);
546         return 0;
547 }
548
549 static void sound_init(void)
550 {
551         SceUID thid;
552         int ret;
553
554         sound_sem = sceKernelCreateSema("sndsem", 0, 0, 1, NULL);
555         if (sound_sem < 0) lprintf("sceKernelCreateSema() failed: %i\n", sound_sem);
556
557         samples_made = samples_done = 0;
558         samples_block = SOUND_BLOCK_SIZE_NTSC; // make sure it goes to sema
559         sound_thread_exit = 0;
560         thid = sceKernelCreateThread("sndthread", sound_thread, 0x12, 0x10000, 0, NULL);
561         if (thid >= 0)
562         {
563                 ret = sceKernelStartThread(thid, 0, 0);
564                 if (ret < 0) lprintf("sound_init: sceKernelStartThread returned %08x\n", ret);
565         }
566         else
567                 lprintf("sceKernelCreateThread failed: %i\n", thid);
568 }
569
570 static void sound_prepare(void)
571 {
572         static int PsndRate_old = 0, PicoOpt_old = 0, pal_old = 0;
573         int ret, stereo;
574
575         samples_made = samples_done = 0;
576
577         if (PsndRate != PsndRate_old || (PicoOpt&0x0b) != (PicoOpt_old&0x0b) || Pico.m.pal != pal_old) {
578                 PsndRerate(Pico.m.frame_count ? 1 : 0);
579         }
580         stereo=(PicoOpt&8)>>3;
581
582         samples_block = Pico.m.pal ? SOUND_BLOCK_SIZE_PAL : SOUND_BLOCK_SIZE_NTSC;
583         if (PsndRate <= 22050) samples_block /= 2;
584         sndBuffer_endptr = &sndBuffer[samples_block*SOUND_BLOCK_COUNT];
585
586         lprintf("starting audio: %i, len: %i, stereo: %i, pal: %i, block samples: %i\n",
587                         PsndRate, PsndLen, stereo, Pico.m.pal, samples_block);
588
589         // while (sceAudioOutput2GetRestSample() > 0) psp_msleep(100);
590         // sceAudio_5C37C0AE();
591         ret = sceAudio_38553111(samples_block/2, PsndRate, 2); // seems to not need that stupid 64byte alignment
592         if (ret < 0) {
593                 lprintf("sceAudio_38553111() failed: %i\n", ret);
594                 sprintf(noticeMsg, "sound init failed (%i), snd disabled", ret);
595                 noticeMsgTime = sceKernelGetSystemTimeLow();
596                 currentConfig.EmuOpt &= ~4;
597         } else {
598                 PicoWriteSound = writeSound;
599                 memset32((int *)(void *)sndBuffer, 0, sizeof(sndBuffer)/4);
600                 snd_playptr = sndBuffer_endptr - samples_block;
601                 samples_made = samples_block; // send 1 empty block first..
602                 PsndOut = sndBuffer;
603                 PsndRate_old = PsndRate;
604                 PicoOpt_old  = PicoOpt;
605                 pal_old = Pico.m.pal;
606         }
607 }
608
609 static void sound_end(void)
610 {
611         int i;
612         if (samples_done == 0)
613         {
614                 // if no data is written between sceAudio_38553111 and sceAudio_5C37C0AE calls,
615                 // we get a deadlock on next sceAudio_38553111 call
616                 // so this is yet another workaround:
617                 memset32((int *)(void *)sndBuffer, 0, samples_block*4/4);
618                 samples_made = samples_block * 3;
619                 sceKernelSignalSema(sound_sem, 1);
620         }
621         sceKernelDelayThread(100*1000);
622         samples_made = samples_done = 0;
623         for (i = 0; sceAudioOutput2GetRestSample() > 0 && i < 16; i++)
624                 psp_msleep(100);
625         sceAudio_5C37C0AE();
626 }
627
628 static void sound_deinit(void)
629 {
630         sound_thread_exit = 1;
631         sceKernelSignalSema(sound_sem, 1);
632         sceKernelDeleteSema(sound_sem);
633         sound_sem = -1;
634 }
635
636 static void writeSound(int len)
637 {
638         int ret;
639         if (PicoOpt&8) len<<=1;
640
641         PsndOut += len;
642         /*if (PsndOut > sndBuffer_endptr) {
643                 memcpy32((int *)(void *)sndBuffer, (int *)endptr, (PsndOut - endptr + 1) / 2);
644                 PsndOut = &sndBuffer[PsndOut - endptr];
645                 lprintf("mov\n");
646         }
647         else*/
648         if (PsndOut > sndBuffer_endptr) lprintf("snd oflow %i!\n", PsndOut - sndBuffer_endptr);
649         if (PsndOut >= sndBuffer_endptr)
650                 PsndOut = sndBuffer;
651
652         // signal the snd thread
653         samples_made += len;
654         if (samples_made - samples_done > samples_block*2) {
655                 // lprintf("signal, %i/%i\n", samples_done, samples_made);
656                 ret = sceKernelSignalSema(sound_sem, 1);
657                 //if (ret < 0) lprintf("snd signal ret %08x\n", ret);
658         }
659 }
660
661
662 static void SkipFrame(void)
663 {
664         PicoSkipFrame=1;
665         PicoFrame();
666         PicoSkipFrame=0;
667 }
668
669 void emu_forcedFrame(void)
670 {
671         int po_old = PicoOpt;
672         int eo_old = currentConfig.EmuOpt;
673
674         PicoOpt &= ~0x0010;
675         PicoOpt |=  0x4080; // soft_scale | acc_sprites
676         currentConfig.EmuOpt |= 0x80;
677
678         vidResetMode();
679         memset32(VRAM_CACHED_STUFF, 0xe0e0e0e0, 512*8/4); // borders
680         memset32((int *)VRAM_CACHED_STUFF + 512*232/4, 0xe0e0e0e0, 512*8/4);
681         memset32_uncached((int *)psp_screen + 512*264*2/4, 0, 512*8*2/4);
682
683         PicoDrawSetColorFormat(-1);
684         PicoScan = EmuScanSlow;
685         EmuScanPrepare();
686         PicoFrameDrawOnly();
687         blit1();
688         sceGuSync(0,0);
689
690         PicoOpt = po_old;
691         currentConfig.EmuOpt = eo_old;
692 }
693
694
695 static void RunEvents(unsigned int which)
696 {
697         if (which & 0x1800) // save or load (but not both)
698         {
699                 int do_it = 1;
700
701                 if ( emu_checkSaveFile(state_slot) &&
702                                 (( (which & 0x1000) && (currentConfig.EmuOpt & 0x800)) || // load
703                                  (!(which & 0x1000) && (currentConfig.EmuOpt & 0x200))) ) // save
704                 {
705                         int keys;
706                         sceGuSync(0,0);
707                         blit2("", (which & 0x1000) ? "LOAD STATE? (X=yes, O=no)" : "OVERWRITE SAVE? (X=yes, O=no)", 0);
708                         while( !((keys = psp_pad_read(1)) & (BTN_X|BTN_CIRCLE)) )
709                                 psp_msleep(50);
710                         if (keys & BTN_CIRCLE) do_it = 0;
711                         while(  ((keys = psp_pad_read(1)) & (BTN_X|BTN_CIRCLE)) ) // wait for release
712                                 psp_msleep(50);
713                         clearArea(0);
714                 }
715
716                 if (do_it)
717                 {
718                         osd_text(4, (which & 0x1000) ? "LOADING GAME" : "SAVING GAME", 1, 0);
719                         PicoStateProgressCB = emu_msg_cb;
720                         emu_SaveLoadGame((which & 0x1000) >> 12, 0);
721                         PicoStateProgressCB = NULL;
722                         psp_msleep(0);
723                 }
724
725                 reset_timing = 1;
726         }
727         if (which & 0x0400) // switch renderer
728         {
729                 if (PicoOpt&0x10) { PicoOpt&=~0x10; currentConfig.EmuOpt |=  0x80; }
730                 else              { PicoOpt|= 0x10; currentConfig.EmuOpt &= ~0x80; }
731
732                 vidResetMode();
733
734                 if (PicoOpt&0x10)
735                         strcpy(noticeMsg, "fast renderer");
736                 else if (currentConfig.EmuOpt&0x80)
737                         strcpy(noticeMsg, "accurate renderer");
738
739                 noticeMsgTime = sceKernelGetSystemTimeLow();
740         }
741         if (which & 0x0300)
742         {
743                 if(which&0x0200) {
744                         state_slot -= 1;
745                         if(state_slot < 0) state_slot = 9;
746                 } else {
747                         state_slot += 1;
748                         if(state_slot > 9) state_slot = 0;
749                 }
750                 sprintf(noticeMsg, "SAVE SLOT %i [%s]", state_slot, emu_checkSaveFile(state_slot) ? "USED" : "FREE");
751                 noticeMsgTime = sceKernelGetSystemTimeLow();
752         }
753 }
754
755 static void updateKeys(void)
756 {
757         unsigned int keys, allActions[2] = { 0, 0 }, events;
758         static unsigned int prevEvents = 0;
759         int i;
760
761         keys = psp_pad_read(0);
762         if (keys & PSP_CTRL_HOME)
763                 sceDisplayWaitVblankStart();
764
765         if (keys & BTN_SELECT)
766                 engineState = PGS_Menu;
767
768         keys &= CONFIGURABLE_KEYS;
769
770         for (i = 0; i < 32; i++)
771         {
772                 if (keys & (1 << i))
773                 {
774                         int pl, acts = currentConfig.KeyBinds[i];
775                         if (!acts) continue;
776                         pl = (acts >> 16) & 1;
777                         if (combo_keys & (1 << i))
778                         {
779                                 int u = i+1, acts_c = acts & combo_acts;
780                                 // let's try to find the other one
781                                 if (acts_c)
782                                         for (; u < 32; u++)
783                                                 if ( (currentConfig.KeyBinds[u] & acts_c) && (keys & (1 << u)) ) {
784                                                         allActions[pl] |= acts_c;
785                                                         keys &= ~((1 << i) | (1 << u));
786                                                         break;
787                                                 }
788                                 // add non-combo actions if combo ones were not found
789                                 if (!acts_c || u == 32)
790                                         allActions[pl] |= acts & ~combo_acts;
791                         } else {
792                                 allActions[pl] |= acts;
793                         }
794                 }
795         }
796
797         PicoPad[0] = (unsigned short) allActions[0];
798         PicoPad[1] = (unsigned short) allActions[1];
799
800         events = (allActions[0] | allActions[1]) >> 16;
801
802         // volume is treated in special way and triggered every frame
803         if ((events & 0x6000) && PsndOut != NULL)
804         {
805                 int vol = currentConfig.volume;
806                 if (events & 0x2000) {
807                         if (vol < 100) vol++;
808                 } else {
809                         if (vol >   0) vol--;
810                 }
811                 // FrameworkAudio_SetVolume(vol, vol); // TODO
812                 sprintf(noticeMsg, "VOL: %02i ", vol);
813                 noticeMsgTime = sceKernelGetSystemTimeLow();
814                 currentConfig.volume = vol;
815         }
816
817         events &= ~prevEvents;
818         if (events) RunEvents(events);
819         if (movie_data) emu_updateMovie();
820
821         prevEvents = (allActions[0] | allActions[1]) >> 16;
822 }
823
824 static void find_combos(void)
825 {
826         int act, u;
827
828         // find out which keys and actions are combos
829         combo_keys = combo_acts = 0;
830         for (act = 0; act < 32; act++)
831         {
832                 int keyc = 0, keyc2 = 0;
833                 if (act == 16 || act == 17) continue; // player2 flag
834                 if (act > 17)
835                 {
836                         for (u = 0; u < 28; u++) // 28 because nub can't produce combos
837                                 if (currentConfig.KeyBinds[u] & (1 << act)) keyc++;
838                 }
839                 else
840                 {
841                         for (u = 0; u < 28; u++)
842                                 if ((currentConfig.KeyBinds[u] & 0x30000) == 0 && // pl. 1
843                                         (currentConfig.KeyBinds[u] & (1 << act))) keyc++;
844                         for (u = 0; u < 28; u++)
845                                 if ((currentConfig.KeyBinds[u] & 0x30000) == 1 && // pl. 2
846                                         (currentConfig.KeyBinds[u] & (1 << act))) keyc2++;
847                 }
848                 if (keyc > 1 || keyc2 > 1)
849                 {
850                         // loop again and mark those keys and actions as combo
851                         for (u = 0; u < 28; u++)
852                         {
853                                 if (currentConfig.KeyBinds[u] & (1 << act)) {
854                                         combo_keys |= 1 << u;
855                                         combo_acts |= 1 << act;
856                                 }
857                         }
858                 }
859         }
860 }
861
862
863 static void simpleWait(unsigned int until)
864 {
865         unsigned int tval;
866         int diff;
867
868         tval = sceKernelGetSystemTimeLow();
869         diff = (int)until - (int)tval;
870         if (diff >= 512 && diff < 100*1024)
871                 sceKernelDelayThread(diff);
872 }
873
874 void emu_Loop(void)
875 {
876         static int mp3_init_done = 0;
877         char fpsbuff[24]; // fps count c string
878         unsigned int tval, tval_prev = 0, tval_thissec = 0; // timing
879         int frames_done = 0, frames_shown = 0, oldmodes = 0;
880         int target_fps, target_frametime, lim_time, tval_diff, i;
881         char *notice = NULL;
882
883         lprintf("entered emu_Loop()\n");
884
885         fpsbuff[0] = 0;
886
887         if (currentConfig.CPUclock != psp_get_cpu_clock()) {
888                 lprintf("setting cpu clock to %iMHz... ", currentConfig.CPUclock);
889                 i = psp_set_cpu_clock(currentConfig.CPUclock);
890                 lprintf(i ? "failed\n" : "done\n");
891                 currentConfig.CPUclock = psp_get_cpu_clock();
892         }
893
894         // make sure we are in correct mode
895         vidResetMode();
896         clearArea(1);
897         Pico.m.dirtyPal = 1;
898         oldmodes = ((Pico.video.reg[12]&1)<<2) ^ 0xc;
899         find_combos();
900
901         // pal/ntsc might have changed, reset related stuff
902         target_fps = Pico.m.pal ? 50 : 60;
903         target_frametime = Pico.m.pal ? (1000000<<8)/50 : (1000000<<8)/60+1;
904         reset_timing = 1;
905
906         if (PicoMCD & 1) {
907                 // prepare CD buffer
908                 PicoCDBufferInit();
909                 // mp3...
910                 if (!mp3_init_done) {
911                         i = mp3_init();
912                         mp3_init_done = 1;
913                         if (i) { engineState = PGS_Menu; return; }
914                 }
915         }
916
917         // prepare sound stuff
918         PsndOut = NULL;
919         if (currentConfig.EmuOpt & 4)
920         {
921                 sound_prepare();
922         }
923
924         sceDisplayWaitVblankStart();
925
926         // loop?
927         while (engineState == PGS_Running)
928         {
929                 int modes;
930
931                 tval = sceKernelGetSystemTimeLow();
932                 if (reset_timing || tval < tval_prev) {
933                         //stdbg("timing reset");
934                         reset_timing = 0;
935                         tval_thissec = tval;
936                         frames_shown = frames_done = 0;
937                 }
938
939                 // show notice message?
940                 if (noticeMsgTime) {
941                         static int noticeMsgSum;
942                         if (tval - noticeMsgTime > 2000000) { // > 2.0 sec
943                                 noticeMsgTime = 0;
944                                 clearArea(0);
945                                 notice = 0;
946                         } else {
947                                 int sum = noticeMsg[0]+noticeMsg[1]+noticeMsg[2];
948                                 if (sum != noticeMsgSum) { clearArea(0); noticeMsgSum = sum; }
949                                 notice = noticeMsg;
950                         }
951                 }
952
953                 // check for mode changes
954                 modes = ((Pico.video.reg[12]&1)<<2)|(Pico.video.reg[1]&8);
955                 if (modes != oldmodes) {
956                         oldmodes = modes;
957                         clearArea(1);
958                         set_scaling_params();
959                 }
960
961                 // second passed?
962                 if (tval - tval_thissec >= 1000000)
963                 {
964                         // missing 1 frame?
965                         if (currentConfig.Frameskip < 0 && frames_done < target_fps) {
966                                 SkipFrame(); frames_done++;
967                         }
968
969                         if (currentConfig.EmuOpt & 2)
970                                 sprintf(fpsbuff, "%02i/%02i  ", frames_shown, frames_done);
971
972                         tval_thissec += 1000000;
973
974                         if (currentConfig.Frameskip < 0) {
975                                 frames_done  -= target_fps; if (frames_done  < 0) frames_done  = 0;
976                                 frames_shown -= target_fps; if (frames_shown < 0) frames_shown = 0;
977                                 if (frames_shown > frames_done) frames_shown = frames_done;
978                         } else {
979                                 frames_done = frames_shown = 0;
980                         }
981                 }
982 #ifdef PFRAMES
983                 sprintf(fpsbuff, "%i", Pico.m.frame_count);
984 #endif
985
986                 tval_prev = tval;
987                 lim_time = (frames_done+1) * target_frametime;
988                 if (currentConfig.Frameskip >= 0) // frameskip enabled
989                 {
990                         for (i = 0; i < currentConfig.Frameskip; i++) {
991                                 updateKeys();
992                                 SkipFrame(); frames_done++;
993                                 if (!(currentConfig.EmuOpt&0x40000)) { // do framelimitting if needed
994                                         int tval_diff;
995                                         tval = sceKernelGetSystemTimeLow();
996                                         tval_diff = (int)(tval - tval_thissec) << 8;
997                                         if (tval_diff < lim_time) // we are too fast
998                                                 simpleWait(tval + ((lim_time - tval_diff)>>8));
999                                 }
1000                                 lim_time += target_frametime;
1001                         }
1002                 }
1003                 else // auto frameskip
1004                 {
1005                         int tval_diff;
1006                         tval = sceKernelGetSystemTimeLow();
1007                         tval_diff = (int)(tval - tval_thissec) << 8;
1008                         if (tval_diff > lim_time && (frames_done/16 < frames_shown))
1009                         {
1010                                 // no time left for this frame - skip
1011                                 if (tval_diff - lim_time >= (300000<<8)) {
1012                                         reset_timing = 1;
1013                                         continue;
1014                                 }
1015                                 updateKeys();
1016                                 SkipFrame(); frames_done++;
1017                                 continue;
1018                         }
1019                 }
1020
1021                 updateKeys();
1022
1023                 if (!(PicoOpt&0x10))
1024                         EmuScanPrepare();
1025
1026                 PicoFrame();
1027
1028                 sceGuSync(0,0);
1029
1030                 // check time
1031                 tval = sceKernelGetSystemTimeLow();
1032                 tval_diff = (int)(tval - tval_thissec) << 8;
1033
1034                 blit2(fpsbuff, notice, tval_diff > lim_time);
1035
1036                 if (currentConfig.Frameskip < 0 && tval_diff - lim_time >= (300000<<8)) // slowdown detection
1037                         reset_timing = 1;
1038                 else if (!(currentConfig.EmuOpt&0x40000) || currentConfig.Frameskip < 0)
1039                 {
1040                         // sleep if we are still too fast
1041                         if (tval_diff < lim_time)
1042                         {
1043                                 // we are too fast
1044                                 simpleWait(tval + ((lim_time - tval_diff) >> 8));
1045                         }
1046                 }
1047
1048                 frames_done++; frames_shown++;
1049         }
1050
1051
1052         if (PicoMCD & 1) PicoCDBufferFree();
1053
1054         if (PsndOut != NULL) {
1055                 PsndOut = NULL;
1056                 sound_end();
1057         }
1058
1059         // save SRAM
1060         if ((currentConfig.EmuOpt & 1) && SRam.changed) {
1061                 emu_msg_cb("Writing SRAM/BRAM..");
1062                 emu_SaveLoadGame(0, 1);
1063                 SRam.changed = 0;
1064         }
1065
1066         // clear fps counters and stuff
1067         memset32_uncached((int *)psp_video_get_active_fb() + 512*264*2/4, 0, 512*8*2/4);
1068 }
1069
1070
1071 void emu_ResetGame(void)
1072 {
1073         PicoReset(0);
1074         reset_timing = 1;
1075 }
1076