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