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