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