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