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