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