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