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