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