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