uncommited code for 151 release (PSP suspend, file browser, etc)
[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/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 *)(void *)(localPal+0x80), (void *)localPal, 0x40/2);
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         if (Pico.m.dirtyPal)
300                 do_pal_update(1, 1);
301         if ((rendstatus & PDRAW_ACC_SPRITES) && !(Pico.video.reg[0xC]&8))
302              amips_clut_f = amips_clut_6bit;
303         else amips_clut_f = amips_clut;
304 }
305
306 static int EmuScanSlowBegin(unsigned int num)
307 {
308         if (!(Pico.video.reg[1]&8)) num += 8;
309
310         if (!dynamic_palette)
311                 HighCol = (unsigned char *)VRAM_CACHED_STUFF + num * 512 + 8;
312
313         return 0;
314 }
315
316 static int EmuScanSlowEnd(unsigned int num)
317 {
318         if (!(Pico.video.reg[1]&8)) num += 8;
319
320         if (Pico.m.dirtyPal) {
321                 if (!dynamic_palette) {
322                         do_slowmode_lines(num);
323                         dynamic_palette = 3; // last for 2 more frames
324                 }
325                 do_pal_update(1, 0);
326         }
327
328         if (dynamic_palette) {
329                 int line_len = (Pico.video.reg[12]&1) ? 320 : 256;
330                 void *dst = (char *)VRAM_STUFF + 512*240 + 512*2*num;
331                 amips_clut_f(dst, HighCol + 8, localPal, line_len);
332         }
333
334         return 0;
335 }
336
337 static void blitscreen_clut(void)
338 {
339         int offs = fbimg_offs;
340         offs += (psp_screen == VRAM_FB0) ? VRAMOFFS_FB0 : VRAMOFFS_FB1;
341
342         sceGuSync(0,0); // sync with prev
343         sceGuStart(GU_DIRECT, guCmdList);
344         sceGuDrawBuffer(GU_PSM_5650, (void *)offs, 512); // point to back buffer
345
346         if (dynamic_palette)
347         {
348                 if (!blit_16bit_mode) { // the current mode is not 16bit
349                         sceGuTexMode(GU_PSM_5650, 0, 0, 0);
350                         sceGuTexImage(0,512,512,512,(char *)VRAM_STUFF + 512*240);
351
352                         blit_16bit_mode = 1;
353                 }
354         }
355         else
356         {
357                 if (blit_16bit_mode) {
358                         sceGuClutMode(GU_PSM_5650,0,0xff,0);
359                         sceGuTexMode(GU_PSM_T8,0,0,0); // 8-bit image
360                         sceGuTexImage(0,512,512,512,(char *)VRAM_STUFF + 16);
361                         blit_16bit_mode = 0;
362                 }
363
364                 if ((PicoOpt&0x10) && Pico.m.dirtyPal)
365                         do_pal_update(0, 0);
366
367                 sceKernelDcacheWritebackAll();
368
369                 if (need_pal_upload) {
370                         need_pal_upload = 0;
371                         sceGuClutLoad((256/8), localPal); // upload 32*8 entries (256)
372                 }
373         }
374
375 #if 1
376         if (g_vertices[0].u == 0 && g_vertices[1].u == g_vertices[1].x)
377         {
378                 struct Vertex* vertices;
379                 int x;
380
381                 #define SLICE_WIDTH 32
382                 for (x = 0; x < g_vertices[1].x; x += SLICE_WIDTH)
383                 {
384                         // render sprite
385                         vertices = (struct Vertex*)sceGuGetMemory(2 * sizeof(struct Vertex));
386                         memcpy(vertices, g_vertices, 2 * sizeof(struct Vertex));
387                         vertices[0].u = vertices[0].x = x;
388                         vertices[1].u = vertices[1].x = x + SLICE_WIDTH;
389                         sceGuDrawArray(GU_SPRITES,GU_TEXTURE_16BIT|GU_VERTEX_16BIT|GU_TRANSFORM_2D,2,0,vertices);
390                 }
391                 // lprintf("listlen: %iB\n", sceGuCheckList()); // ~480 only
392         }
393         else
394 #endif
395                 sceGuDrawArray(GU_SPRITES,GU_TEXTURE_16BIT|GU_VERTEX_16BIT|GU_TRANSFORM_2D,2,0,g_vertices);
396
397         sceGuFinish();
398 }
399
400
401 static void cd_leds(void)
402 {
403         unsigned int reg, col_g, col_r, *p;
404
405         reg = Pico_mcd->s68k_regs[0];
406
407         p = (unsigned int *)((short *)psp_screen + 512*2+4+2);
408         col_g = (reg & 2) ? 0x06000600 : 0;
409         col_r = (reg & 1) ? 0x00180018 : 0;
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; p += 512/2 - 12/2;
412         *p++ = col_g; *p++ = col_g; p+=2; *p++ = col_r; *p++ = col_r;
413 }
414
415 static void draw_pico_ptr(void)
416 {
417         unsigned char *p = (unsigned char *)VRAM_STUFF + 16;
418
419         // only if pen enabled and for 8bit mode
420         if (pico_inp_mode == 0 || blit_16bit_mode) return;
421
422         p += 512 * (pico_pen_y + PICO_PEN_ADJUST_Y);
423         p += pico_pen_x + PICO_PEN_ADJUST_X;
424         p[  -1] = 0xe0; p[   0] = 0xf0; p[   1] = 0xe0;
425         p[ 511] = 0xf0; p[ 512] = 0xf0; p[ 513] = 0xf0;
426         p[1023] = 0xe0; p[1024] = 0xf0; p[1025] = 0xe0;
427 }
428
429
430 #if 0
431 static void dbg_text(void)
432 {
433         int *p, h, len;
434         char text[128];
435
436         sprintf(text, "sl: %i, 16b: %i", g_vertices[0].u == 0 && g_vertices[1].u == g_vertices[1].x, blit_16bit_mode);
437         len = strlen(text) * 8 / 2;
438         for (h = 0; h < 8; h++) {
439                 p = (int *) ((unsigned short *) psp_screen+2+512*(256+h));
440                 p = (int *) ((int)p & ~3); // align
441                 memset32_uncached(p, 0, len);
442         }
443         emu_textOut16(2, 256, text);
444 }
445 #endif
446
447 /* called after rendering is done, but frame emulation is not finished */
448 void blit1(void)
449 {
450         if (PicoOpt&0x10)
451         {
452                 int i;
453                 unsigned char *pd;
454                 // clear top and bottom trash
455                 for (pd = PicoDraw2FB+8, i = 8; i > 0; i--, pd += 512)
456                         memset32((int *)pd, 0xe0e0e0e0, 320/4);
457                 for (pd = PicoDraw2FB+512*232+8, i = 8; i > 0; i--, pd += 512)
458                         memset32((int *)pd, 0xe0e0e0e0, 320/4);
459         }
460
461         if (PicoAHW & PAHW_PICO)
462                 draw_pico_ptr();
463
464         blitscreen_clut();
465 }
466
467
468 static void blit2(const char *fps, const char *notice, int lagging_behind)
469 {
470         int vsync = 0, emu_opt = currentConfig.EmuOpt;
471
472         if (notice || (emu_opt & 2)) {
473                 if (notice)      osd_text(4, notice, 0, 0);
474                 if (emu_opt & 2) osd_text(OSD_FPS_X, fps, 0, 0);
475         }
476
477         //dbg_text();
478
479         if ((emu_opt & 0x400) && (PicoAHW & PAHW_MCD))
480                 cd_leds();
481
482         if (currentConfig.EmuOpt & 0x2000) { // want vsync
483                 if (!(currentConfig.EmuOpt & 0x10000) || !lagging_behind) vsync = 1;
484         }
485
486         psp_video_flip(vsync);
487 }
488
489 // clears whole screen or just the notice area (in all buffers)
490 static void clearArea(int full)
491 {
492         if (full) {
493                 memset32_uncached(psp_screen, 0, 512*272*2/4);
494                 psp_video_flip(0);
495                 memset32_uncached(psp_screen, 0, 512*272*2/4);
496                 memset32(VRAM_CACHED_STUFF, 0xe0e0e0e0, 512*240/4);
497                 memset32((int *)VRAM_CACHED_STUFF+512*240/4, 0, 512*240*2/4);
498         } else {
499                 void *fb = psp_video_get_active_fb();
500                 memset32_uncached((int *)((char *)psp_screen + 512*264*2), 0, 512*8*2/4);
501                 memset32_uncached((int *)((char *)fb         + 512*264*2), 0, 512*8*2/4);
502         }
503 }
504
505 static void vidResetMode(void)
506 {
507         // setup GU
508         sceGuSync(0,0); // sync with prev
509         sceGuStart(GU_DIRECT, guCmdList);
510
511         sceGuClutMode(GU_PSM_5650,0,0xff,0);
512         sceGuTexMode(GU_PSM_T8,0,0,0); // 8-bit image
513         sceGuTexFunc(GU_TFX_REPLACE,GU_TCC_RGB);
514         if (currentConfig.scaling)
515              sceGuTexFilter(GU_LINEAR, GU_LINEAR);
516         else sceGuTexFilter(GU_NEAREST, GU_NEAREST);
517         sceGuTexScale(1.0f,1.0f);
518         sceGuTexOffset(0.0f,0.0f);
519
520         sceGuTexImage(0,512,512,512,(char *)VRAM_STUFF + 16);
521
522         // slow rend.
523         PicoDrawSetColorFormat(-1);
524         PicoScanBegin = EmuScanSlowBegin;
525         PicoScanEnd = EmuScanSlowEnd;
526
527         localPal[0xe0] = 0;
528         localPal[0xf0] = 0x001f;
529         Pico.m.dirtyPal = 1;
530         blit_16bit_mode = dynamic_palette = 0;
531
532         sceGuFinish();
533         set_scaling_params();
534         sceGuSync(0,0);
535 }
536
537
538 /* sound stuff */
539 #define SOUND_BLOCK_SIZE_NTSC (1470*2) // 1024 // 1152
540 #define SOUND_BLOCK_SIZE_PAL  (1764*2)
541 #define SOUND_BLOCK_COUNT    8
542
543 static short __attribute__((aligned(4))) sndBuffer[SOUND_BLOCK_SIZE_PAL*SOUND_BLOCK_COUNT + 44100/50*2];
544 static short *snd_playptr = NULL, *sndBuffer_endptr = NULL;
545 static int samples_made = 0, samples_done = 0, samples_block = 0;
546 static int sound_thread_exit = 0;
547 static SceUID sound_sem = -1;
548
549 static void writeSound(int len);
550
551 static int sound_thread(SceSize args, void *argp)
552 {
553         int ret = 0;
554
555         lprintf("sthr: started, priority %i\n", sceKernelGetThreadCurrentPriority());
556
557         while (!sound_thread_exit)
558         {
559                 if (samples_made - samples_done < samples_block) {
560                         // wait for data (use at least 2 blocks)
561                         //lprintf("sthr: wait... (%i)\n", samples_made - samples_done);
562                         while (samples_made - samples_done <= samples_block*2 && !sound_thread_exit)
563                                 ret = sceKernelWaitSema(sound_sem, 1, 0);
564                         if (ret < 0) lprintf("sthr: sceKernelWaitSema: %i\n", ret);
565                         continue;
566                 }
567
568                 // lprintf("sthr: got data: %i\n", samples_made - samples_done);
569
570                 ret = sceAudio_E0727056(PSP_AUDIO_VOLUME_MAX, snd_playptr);
571
572                 samples_done += samples_block;
573                 snd_playptr  += samples_block;
574                 if (snd_playptr >= sndBuffer_endptr)
575                         snd_playptr = sndBuffer;
576                 // 1.5 kernel returns 0, newer ones return # of samples queued
577                 if (ret < 0)
578                         lprintf("sthr: sceAudio_E0727056: %08x; pos %i/%i\n", ret, samples_done, samples_made);
579
580                 // shouln't happen, but just in case
581                 if (samples_made - samples_done >= samples_block*3) {
582                         //lprintf("sthr: block skip (%i)\n", samples_made - samples_done);
583                         samples_done += samples_block; // skip
584                         snd_playptr  += samples_block;
585                 }
586
587         }
588
589         lprintf("sthr: exit\n");
590         sceKernelExitDeleteThread(0);
591         return 0;
592 }
593
594 static void sound_init(void)
595 {
596         SceUID thid;
597         int ret;
598
599         sound_sem = sceKernelCreateSema("sndsem", 0, 0, 1, NULL);
600         if (sound_sem < 0) lprintf("sceKernelCreateSema() failed: %i\n", sound_sem);
601
602         samples_made = samples_done = 0;
603         samples_block = SOUND_BLOCK_SIZE_NTSC; // make sure it goes to sema
604         sound_thread_exit = 0;
605         thid = sceKernelCreateThread("sndthread", sound_thread, 0x12, 0x10000, 0, NULL);
606         if (thid >= 0)
607         {
608                 ret = sceKernelStartThread(thid, 0, 0);
609                 if (ret < 0) lprintf("sound_init: sceKernelStartThread returned %08x\n", ret);
610         }
611         else
612                 lprintf("sceKernelCreateThread failed: %i\n", thid);
613 }
614
615 static void sound_prepare(void)
616 {
617         static int PsndRate_old = 0, PicoOpt_old = 0, pal_old = 0;
618         int ret, stereo;
619
620         samples_made = samples_done = 0;
621
622         if (PsndRate != PsndRate_old || (PicoOpt&0x0b) != (PicoOpt_old&0x0b) || Pico.m.pal != pal_old) {
623                 PsndRerate(Pico.m.frame_count ? 1 : 0);
624         }
625         stereo=(PicoOpt&8)>>3;
626
627         samples_block = Pico.m.pal ? SOUND_BLOCK_SIZE_PAL : SOUND_BLOCK_SIZE_NTSC;
628         if (PsndRate <= 22050) samples_block /= 2;
629         sndBuffer_endptr = &sndBuffer[samples_block*SOUND_BLOCK_COUNT];
630
631         lprintf("starting audio: %i, len: %i, stereo: %i, pal: %i, block samples: %i\n",
632                         PsndRate, PsndLen, stereo, Pico.m.pal, samples_block);
633
634         // while (sceAudioOutput2GetRestSample() > 0) psp_msleep(100);
635         // sceAudio_5C37C0AE();
636         ret = sceAudio_38553111(samples_block/2, PsndRate, 2); // seems to not need that stupid 64byte alignment
637         if (ret < 0) {
638                 lprintf("sceAudio_38553111() failed: %i\n", ret);
639                 sprintf(noticeMsg, "sound init failed (%i), snd disabled", ret);
640                 noticeMsgTime = sceKernelGetSystemTimeLow();
641                 currentConfig.EmuOpt &= ~4;
642         } else {
643                 PicoWriteSound = writeSound;
644                 memset32((int *)(void *)sndBuffer, 0, sizeof(sndBuffer)/4);
645                 snd_playptr = sndBuffer_endptr - samples_block;
646                 samples_made = samples_block; // send 1 empty block first..
647                 PsndOut = sndBuffer;
648                 PsndRate_old = PsndRate;
649                 PicoOpt_old  = PicoOpt;
650                 pal_old = Pico.m.pal;
651         }
652 }
653
654 static void sound_end(void)
655 {
656         int i;
657         if (samples_done == 0)
658         {
659                 // if no data is written between sceAudio_38553111 and sceAudio_5C37C0AE calls,
660                 // we get a deadlock on next sceAudio_38553111 call
661                 // so this is yet another workaround:
662                 memset32((int *)(void *)sndBuffer, 0, samples_block*4/4);
663                 samples_made = samples_block * 3;
664                 sceKernelSignalSema(sound_sem, 1);
665         }
666         sceKernelDelayThread(100*1000);
667         samples_made = samples_done = 0;
668         for (i = 0; sceAudioOutput2GetRestSample() > 0 && i < 16; i++)
669                 psp_msleep(100);
670         sceAudio_5C37C0AE();
671 }
672
673 static void sound_deinit(void)
674 {
675         sound_thread_exit = 1;
676         sceKernelSignalSema(sound_sem, 1);
677         sceKernelDeleteSema(sound_sem);
678         sound_sem = -1;
679 }
680
681 static void writeSound(int len)
682 {
683         int ret;
684         if (PicoOpt&8) len<<=1;
685
686         PsndOut += len;
687         /*if (PsndOut > sndBuffer_endptr) {
688                 memcpy32((int *)(void *)sndBuffer, (int *)endptr, (PsndOut - endptr + 1) / 2);
689                 PsndOut = &sndBuffer[PsndOut - endptr];
690                 lprintf("mov\n");
691         }
692         else*/
693         if (PsndOut > sndBuffer_endptr) lprintf("snd oflow %i!\n", PsndOut - sndBuffer_endptr);
694         if (PsndOut >= sndBuffer_endptr)
695                 PsndOut = sndBuffer;
696
697         // signal the snd thread
698         samples_made += len;
699         if (samples_made - samples_done > samples_block*2) {
700                 // lprintf("signal, %i/%i\n", samples_done, samples_made);
701                 ret = sceKernelSignalSema(sound_sem, 1);
702                 //if (ret < 0) lprintf("snd signal ret %08x\n", ret);
703         }
704 }
705
706
707 static void SkipFrame(void)
708 {
709         PicoSkipFrame=1;
710         PicoFrame();
711         PicoSkipFrame=0;
712 }
713
714 void emu_forcedFrame(int opts)
715 {
716         int po_old = PicoOpt;
717         int eo_old = currentConfig.EmuOpt;
718
719         PicoOpt &= ~0x10;
720         PicoOpt |= opts|POPT_ACC_SPRITES;
721         currentConfig.EmuOpt |= 0x80;
722
723         vidResetMode();
724         memset32(VRAM_CACHED_STUFF, 0xe0e0e0e0, 512*8/4); // borders
725         memset32((int *)VRAM_CACHED_STUFF + 512*232/4, 0xe0e0e0e0, 512*8/4);
726         memset32_uncached((int *)psp_screen + 512*264*2/4, 0, 512*8*2/4);
727
728         PicoDrawSetColorFormat(-1);
729         PicoScanBegin = EmuScanSlowBegin;
730         PicoScanEnd = EmuScanSlowEnd;
731         EmuScanPrepare();
732         PicoFrameDrawOnly();
733         blit1();
734         sceGuSync(0,0);
735
736         PicoOpt = po_old;
737         currentConfig.EmuOpt = eo_old;
738 }
739
740
741 static void RunEventsPico(unsigned int events, unsigned int keys)
742 {
743         emu_RunEventsPico(events);
744
745         if (pico_inp_mode != 0)
746         {
747                 PicoPad[0] &= ~0x0f; // release UDLR
748                 if (keys & BTN_UP)   { pico_pen_y--; if (pico_pen_y < 8) pico_pen_y = 8; }
749                 if (keys & BTN_DOWN) { pico_pen_y++; if (pico_pen_y > 224-PICO_PEN_ADJUST_Y) pico_pen_y = 224-PICO_PEN_ADJUST_Y; }
750                 if (keys & BTN_LEFT) { pico_pen_x--; if (pico_pen_x < 0) pico_pen_x = 0; }
751                 if (keys & BTN_RIGHT) {
752                         int lim = (Pico.video.reg[12]&1) ? 319 : 255;
753                         pico_pen_x++;
754                         if (pico_pen_x > lim-PICO_PEN_ADJUST_X)
755                                 pico_pen_x = lim-PICO_PEN_ADJUST_X;
756                 }
757                 PicoPicohw.pen_pos[0] = pico_pen_x;
758                 if (!(Pico.video.reg[12]&1)) PicoPicohw.pen_pos[0] += pico_pen_x/4;
759                 PicoPicohw.pen_pos[0] += 0x3c;
760                 PicoPicohw.pen_pos[1] = pico_inp_mode == 1 ? (0x2f8 + pico_pen_y) : (0x1fc + pico_pen_y);
761         }
762 }
763
764 static void RunEvents(unsigned int which)
765 {
766         if (which & 0x1800) // save or load (but not both)
767         {
768                 int do_it = 1;
769
770                 if ( emu_checkSaveFile(state_slot) &&
771                                 (( (which & 0x1000) && (currentConfig.EmuOpt & 0x800)) || // load
772                                  (!(which & 0x1000) && (currentConfig.EmuOpt & 0x200))) ) // save
773                 {
774                         int keys;
775                         sceGuSync(0,0);
776                         blit2("", (which & 0x1000) ? "LOAD STATE? (X=yes, O=no)" : "OVERWRITE SAVE? (X=yes, O=no)", 0);
777                         while( !((keys = psp_pad_read(1)) & (BTN_X|BTN_CIRCLE)) )
778                                 psp_msleep(50);
779                         if (keys & BTN_CIRCLE) do_it = 0;
780                         while(  ((keys = psp_pad_read(1)) & (BTN_X|BTN_CIRCLE)) ) // wait for release
781                                 psp_msleep(50);
782                         clearArea(0);
783                 }
784
785                 if (do_it)
786                 {
787                         osd_text(4, (which & 0x1000) ? "LOADING GAME" : "SAVING GAME", 1, 0);
788                         PicoStateProgressCB = emu_msg_cb;
789                         emu_SaveLoadGame((which & 0x1000) >> 12, 0);
790                         PicoStateProgressCB = NULL;
791                         psp_msleep(0);
792                 }
793
794                 reset_timing = 1;
795         }
796         if (which & 0x0400) // switch renderer
797         {
798                 if (PicoOpt&0x10) { PicoOpt&=~0x10; currentConfig.EmuOpt |=  0x80; }
799                 else              { PicoOpt|= 0x10; currentConfig.EmuOpt &= ~0x80; }
800
801                 vidResetMode();
802
803                 if (PicoOpt&0x10)
804                         strcpy(noticeMsg, "fast renderer");
805                 else if (currentConfig.EmuOpt&0x80)
806                         strcpy(noticeMsg, "accurate renderer");
807
808                 noticeMsgTime = sceKernelGetSystemTimeLow();
809         }
810         if (which & 0x0300)
811         {
812                 if(which&0x0200) {
813                         state_slot -= 1;
814                         if(state_slot < 0) state_slot = 9;
815                 } else {
816                         state_slot += 1;
817                         if(state_slot > 9) state_slot = 0;
818                 }
819                 sprintf(noticeMsg, "SAVE SLOT %i [%s]", state_slot, emu_checkSaveFile(state_slot) ? "USED" : "FREE");
820                 noticeMsgTime = sceKernelGetSystemTimeLow();
821         }
822 }
823
824 static void updateKeys(void)
825 {
826         unsigned int keys, allActions[2] = { 0, 0 }, events;
827         static unsigned int prevEvents = 0;
828         int i;
829
830         keys = psp_pad_read(0);
831         if (keys & PSP_CTRL_HOME)
832                 sceDisplayWaitVblankStart();
833
834         if (keys & BTN_SELECT)
835                 engineState = PGS_Menu;
836
837         keys &= CONFIGURABLE_KEYS;
838
839         for (i = 0; i < 32; i++)
840         {
841                 if (keys & (1 << i))
842                 {
843                         int pl, acts = currentConfig.KeyBinds[i];
844                         if (!acts) continue;
845                         pl = (acts >> 16) & 1;
846                         if (kb_combo_keys & (1 << i))
847                         {
848                                 int u = i+1, acts_c = acts & kb_combo_acts;
849                                 // let's try to find the other one
850                                 if (acts_c) {
851                                         for (; u < 32; u++)
852                                                 if ( (keys & (1 << u)) && (currentConfig.KeyBinds[u] & acts_c) ) {
853                                                         allActions[pl] |= acts_c & currentConfig.KeyBinds[u];
854                                                         keys &= ~((1 << i) | (1 << u));
855                                                         break;
856                                                 }
857                                 }
858                                 // add non-combo actions if combo ones were not found
859                                 if (!acts_c || u == 32)
860                                         allActions[pl] |= acts & ~kb_combo_acts;
861                         } else {
862                                 allActions[pl] |= acts;
863                         }
864                 }
865         }
866
867         PicoPad[0] = allActions[0] & 0xfff;
868         PicoPad[1] = allActions[1] & 0xfff;
869
870         if (allActions[0] & 0x7000) emu_DoTurbo(&PicoPad[0], allActions[0]);
871         if (allActions[1] & 0x7000) emu_DoTurbo(&PicoPad[1], allActions[1]);
872
873         events = (allActions[0] | allActions[1]) >> 16;
874
875         if ((events ^ prevEvents) & 0x40) {
876                 emu_changeFastForward(events & 0x40);
877                 reset_timing = 1;
878         }
879
880         events &= ~prevEvents;
881
882         if (PicoAHW == PAHW_PICO)
883                 RunEventsPico(events, keys);
884         if (events) RunEvents(events);
885         if (movie_data) emu_updateMovie();
886
887         prevEvents = (allActions[0] | allActions[1]) >> 16;
888 }
889
890
891 static void simpleWait(unsigned int until)
892 {
893         unsigned int tval;
894         int diff;
895
896         tval = sceKernelGetSystemTimeLow();
897         diff = (int)until - (int)tval;
898         if (diff >= 512 && diff < 100*1024)
899                 sceKernelDelayThread(diff);
900 }
901
902 void emu_Loop(void)
903 {
904         static int mp3_init_done = 0;
905         char fpsbuff[24]; // fps count c string
906         unsigned int tval, tval_thissec = 0; // timing
907         int target_fps, target_frametime, lim_time, tval_diff, i, oldmodes = 0;
908         int pframes_done, pframes_shown; // "period" frames, used for sync
909         int  frames_done,  frames_shown, tval_fpsc = 0; // actual frames
910         char *notice = NULL;
911
912         lprintf("entered emu_Loop()\n");
913
914         fpsbuff[0] = 0;
915
916         if (currentConfig.CPUclock != psp_get_cpu_clock()) {
917                 lprintf("setting cpu clock to %iMHz... ", currentConfig.CPUclock);
918                 i = psp_set_cpu_clock(currentConfig.CPUclock);
919                 lprintf(i ? "failed\n" : "done\n");
920                 currentConfig.CPUclock = psp_get_cpu_clock();
921         }
922
923         // make sure we are in correct mode
924         vidResetMode();
925         clearArea(1);
926         Pico.m.dirtyPal = 1;
927         oldmodes = ((Pico.video.reg[12]&1)<<2) ^ 0xc;
928         emu_findKeyBindCombos();
929
930         // pal/ntsc might have changed, reset related stuff
931         target_fps = Pico.m.pal ? 50 : 60;
932         target_frametime = Pico.m.pal ? (1000000<<8)/50 : (1000000<<8)/60+1;
933         reset_timing = 1;
934
935         if (PicoAHW & PAHW_MCD) {
936                 // prepare CD buffer
937                 PicoCDBufferInit();
938                 // mp3...
939                 if (!mp3_init_done) {
940                         i = mp3_init();
941                         mp3_init_done = 1;
942                         if (i) { engineState = PGS_Menu; return; }
943                 }
944         }
945
946         // prepare sound stuff
947         PsndOut = NULL;
948         if (currentConfig.EmuOpt & 4)
949         {
950                 sound_prepare();
951         }
952
953         sceDisplayWaitVblankStart();
954         pframes_shown = pframes_done =
955          frames_shown =  frames_done = 0;
956
957         tval_fpsc = sceKernelGetSystemTimeLow();
958
959         // loop?
960         while (engineState == PGS_Running)
961         {
962                 int modes;
963
964                 tval = sceKernelGetSystemTimeLow();
965                 if (reset_timing || tval < tval_fpsc) {
966                         //stdbg("timing reset");
967                         reset_timing = 0;
968                         tval_thissec = tval;
969                         pframes_shown = pframes_done = 0;
970                 }
971
972                 // show notice message?
973                 if (noticeMsgTime) {
974                         static int noticeMsgSum;
975                         if (tval - noticeMsgTime > 2000000) { // > 2.0 sec
976                                 noticeMsgTime = 0;
977                                 clearArea(0);
978                                 notice = 0;
979                         } else {
980                                 int sum = noticeMsg[0]+noticeMsg[1]+noticeMsg[2];
981                                 if (sum != noticeMsgSum) { clearArea(0); noticeMsgSum = sum; }
982                                 notice = noticeMsg;
983                         }
984                 }
985
986                 // check for mode changes
987                 modes = ((Pico.video.reg[12]&1)<<2)|(Pico.video.reg[1]&8);
988                 if (modes != oldmodes) {
989                         oldmodes = modes;
990                         clearArea(1);
991                         set_scaling_params();
992                 }
993
994                 // second passed?
995                 if (tval - tval_fpsc >= 1000000)
996                 {
997                         if (currentConfig.EmuOpt & 2)
998                                 sprintf(fpsbuff, "%02i/%02i  ", frames_shown, frames_done);
999                         frames_done = frames_shown = 0;
1000                         tval_fpsc += 1000000;
1001                 }
1002
1003                 if (tval - tval_thissec >= 1000000)
1004                 {
1005                         // missing 1 frame?
1006                         if (currentConfig.Frameskip < 0 && pframes_done < target_fps) {
1007                                 SkipFrame(); pframes_done++; frames_done++;
1008                         }
1009
1010                         tval_thissec += 1000000;
1011
1012                         if (currentConfig.Frameskip < 0) {
1013                                 pframes_done  -= target_fps; if (pframes_done  < 0) pframes_done  = 0;
1014                                 pframes_shown -= target_fps; if (pframes_shown < 0) pframes_shown = 0;
1015                                 if (pframes_shown > pframes_done) pframes_shown = pframes_done;
1016                         } else {
1017                                 pframes_done = pframes_shown = 0;
1018                         }
1019                 }
1020 #ifdef PFRAMES
1021                 sprintf(fpsbuff, "%i", Pico.m.frame_count);
1022 #endif
1023
1024                 lim_time = (pframes_done+1) * target_frametime;
1025                 if (currentConfig.Frameskip >= 0) // frameskip enabled
1026                 {
1027                         for (i = 0; i < currentConfig.Frameskip; i++) {
1028                                 updateKeys();
1029                                 SkipFrame(); pframes_done++; frames_done++;
1030                                 if (!(currentConfig.EmuOpt&0x40000)) { // do framelimitting if needed
1031                                         int tval_diff;
1032                                         tval = sceKernelGetSystemTimeLow();
1033                                         tval_diff = (int)(tval - tval_thissec) << 8;
1034                                         if (tval_diff < lim_time) // we are too fast
1035                                                 simpleWait(tval + ((lim_time - tval_diff)>>8));
1036                                 }
1037                                 lim_time += target_frametime;
1038                         }
1039                 }
1040                 else // auto frameskip
1041                 {
1042                         int tval_diff;
1043                         tval = sceKernelGetSystemTimeLow();
1044                         tval_diff = (int)(tval - tval_thissec) << 8;
1045                         if (tval_diff > lim_time && (pframes_done/16 < pframes_shown))
1046                         {
1047                                 // no time left for this frame - skip
1048                                 if (tval_diff - lim_time >= (300000<<8)) {
1049                                         reset_timing = 1;
1050                                         continue;
1051                                 }
1052                                 updateKeys();
1053                                 SkipFrame(); pframes_done++; frames_done++;
1054                                 continue;
1055                         }
1056                 }
1057
1058                 updateKeys();
1059
1060                 if (!(PicoOpt&0x10))
1061                         EmuScanPrepare();
1062
1063                 PicoFrame();
1064
1065                 sceGuSync(0,0);
1066
1067                 // check time
1068                 tval = sceKernelGetSystemTimeLow();
1069                 tval_diff = (int)(tval - tval_thissec) << 8;
1070
1071                 blit2(fpsbuff, notice, tval_diff > lim_time);
1072
1073                 if (currentConfig.Frameskip < 0 && tval_diff - lim_time >= (300000<<8)) { // slowdown detection
1074                         reset_timing = 1;
1075                 }
1076                 else if (!(currentConfig.EmuOpt&0x40000) || currentConfig.Frameskip < 0)
1077                 {
1078                         // sleep if we are still too fast
1079                         if (tval_diff < lim_time)
1080                         {
1081                                 // we are too fast
1082                                 simpleWait(tval + ((lim_time - tval_diff) >> 8));
1083                         }
1084                 }
1085
1086                 pframes_done++; pframes_shown++;
1087                  frames_done++;  frames_shown++;
1088         }
1089
1090
1091         emu_changeFastForward(0);
1092
1093         if (PicoAHW & PAHW_MCD) PicoCDBufferFree();
1094
1095         if (PsndOut != NULL) {
1096                 PsndOut = NULL;
1097                 sound_end();
1098         }
1099
1100         // save SRAM
1101         if ((currentConfig.EmuOpt & 1) && SRam.changed) {
1102                 emu_msg_cb("Writing SRAM/BRAM..");
1103                 emu_SaveLoadGame(0, 1);
1104                 SRam.changed = 0;
1105         }
1106
1107         // clear fps counters and stuff
1108         memset32_uncached((int *)psp_video_get_active_fb() + 512*264*2/4, 0, 512*8*2/4);
1109 }
1110
1111
1112 void emu_ResetGame(void)
1113 {
1114         PicoReset();
1115         reset_timing = 1;
1116 }
1117
1118 void emu_HandleResume(void)
1119 {
1120         if (!(PicoAHW & PAHW_MCD)) return;
1121
1122         // reopen first CD track
1123         if (Pico_mcd->TOC.Tracks[0].F != NULL)
1124         {
1125                 char *fname = romFileName;
1126                 int len = strlen(romFileName);
1127                 cue_data_t *cue_data = NULL;
1128
1129                 if (len > 4 && strcasecmp(fname + len - 4,  ".cue") == 0)
1130                 {
1131                         cue_data = cue_parse(romFileName);
1132                         if (cue_data != NULL)
1133                                 fname = cue_data->tracks[1].fname;
1134                 }
1135
1136                 lprintf("emu_HandleResume: reopen %s\n", fname);
1137                 pm_close(Pico_mcd->TOC.Tracks[0].F);
1138                 Pico_mcd->TOC.Tracks[0].F = pm_open(fname);
1139                 lprintf("reopen %s\n", Pico_mcd->TOC.Tracks[0].F != NULL ? "ok" : "failed");
1140
1141                 if (cue_data != NULL) cue_destroy(cue_data);
1142         }
1143
1144         mp3_reopen_file();
1145
1146         if (!(Pico_mcd->s68k_regs[0x36] & 1) && (Pico_mcd->scd.Status_CDC & 1))
1147                 cdda_start_play();
1148 }
1149