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