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