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