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