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