Forráskód Böngészése

psp mp3 implementation

git-svn-id: file:///home/notaz/opt/svn/PicoDrive@293 be3aeb3a-fb24-0410-a615-afba39da0efa
notaz 16 éve
szülő
commit
4b167c12c7

+ 1 - 0
Pico/Cart.c

@@ -16,6 +16,7 @@
 static char *rom_exts[] = { "bin", "gen", "smd", "iso" };
 
 void (*PicoCartLoadProgressCB)(int percent) = NULL;
+void (*PicoCDLoadProgressCB)(int percent) = NULL; // handled in Pico/cd/cd_file.c
 
 
 pm_file *pm_open(const char *path)

+ 1 - 1
Pico/Pico.h

@@ -99,9 +99,9 @@ int      pm_close(pm_file *fp);
 int PicoCartLoad(pm_file *f,unsigned char **prom,unsigned int *psize);
 int PicoCartInsert(unsigned char *rom,unsigned int romsize);
 void Byteswap(unsigned char *data,int len);
-// anotherguest
 int PicoUnloadCart(unsigned char* romdata);
 extern void (*PicoCartLoadProgressCB)(int percent);
+extern void (*PicoCDLoadProgressCB)(int percent);
 
 // Draw.c
 void PicoDrawSetColorFormat(int which); // 0=BGR444, 1=RGB555, 2=8bit(HighPal pal)

+ 32 - 11
Pico/cd/cd_file.c

@@ -7,16 +7,14 @@
  *                                                         *
  ***********************************************************/
 
-#include <sys/stat.h>
-
 #include "../PicoInt.h"
 #include "cd_file.h"
 
 #define cdprintf dprintf
 //#define cdprintf(x...)
+//#define cdprintf(f,...) printf(f "\n",##__VA_ARGS__) // tmp
 #define DEBUG_CD
 
-
 PICO_INTERNAL int Load_ISO(const char *iso_name, int is_bin)
 {
 	int i, j, num_track, Cur_LBA, index, ret, iso_name_len;
@@ -26,11 +24,13 @@ PICO_INTERNAL int Load_ISO(const char *iso_name, int is_bin)
 	static char *exts[] = {
 		"%02d.mp3", " %02d.mp3", "-%02d.mp3", "_%02d.mp3", " - %02d.mp3",
 		"%d.mp3", " %d.mp3", "-%d.mp3", "_%d.mp3", " - %d.mp3",
+#if CASE_SENSITIVE_FS
 		"%02d.MP3", " %02d.MP3", "-%02d.MP3", "_%02d.MP3", " - %02d.MP3",
-		/* "%02d.wav", " %02d.wav", "-%02d.wav", "_%02d.wav", " - %02d.wav",
-		"%d.wav", " %d.wav", "-%d.wav", "_%d.wav", " - %2d.wav" */
+#endif
 	};
 
+	if (PicoCDLoadProgressCB != NULL) PicoCDLoadProgressCB(1);
+
 	Unload_ISO();
 
 	Tracks[0].ftype = is_bin ? TYPE_BIN : TYPE_ISO;
@@ -56,10 +56,14 @@ PICO_INTERNAL int Load_ISO(const char *iso_name, int is_bin)
 	Cur_LBA = Tracks[0].Length;				// Size in sectors
 
 	iso_name_len = strlen(iso_name);
+	if (iso_name_len >= sizeof(tmp_name))
+		iso_name_len = sizeof(tmp_name) - 1;
 
 	for (num_track = 2, i = 0; i < 100; i++)
 	{
-		for(j = 0; j < sizeof(exts)/sizeof(char *); j++)
+		if (PicoCDLoadProgressCB != NULL && i > 1) PicoCDLoadProgressCB(i);
+
+		for (j = 0; j < sizeof(exts)/sizeof(char *); j++)
 		{
 			int ext_len;
 			FILE *tmp_file;
@@ -80,18 +84,28 @@ PICO_INTERNAL int Load_ISO(const char *iso_name, int is_bin)
 			if (tmp_file)
 			{
 				int fs;
-				struct stat file_stat;
 				index = num_track - 1;
 
-				ret = stat(tmp_name, &file_stat);
-				fs = file_stat.st_size;				// used to calculate lenght
+				ret = fseek(tmp_file, 0, SEEK_END);
+				fs = ftell(tmp_file);				// used to calculate lenght
+				fseek(tmp_file, 0, SEEK_SET);
 
+#if DONT_OPEN_MANY_FILES
+				// some systems (like PSP) can't have many open files at a time,
+				// so we work with their names instead.
+				fclose(tmp_file);
+				tmp_file = (void *) strdup(tmp_name);
+#endif
 				Tracks[index].KBtps = (short) mp3_get_bitrate(tmp_file, fs);
 				Tracks[index].KBtps >>= 3;
 				if (ret != 0 || Tracks[index].KBtps <= 0)
 				{
-					cdprintf("Error track %i: stat %i, rate %i", index, ret, Tracks[index].KBtps);
+					cdprintf("Error track %i: rate %i", index, Tracks[index].KBtps);
+#if !DONT_OPEN_MANY_FILES
 					fclose(tmp_file);
+#else
+					free(tmp_file);
+#endif
 					continue;
 				}
 
@@ -124,6 +138,8 @@ PICO_INTERNAL int Load_ISO(const char *iso_name, int is_bin)
 	cdprintf("End CD - %02d:%02d:%02d\n\n", Tracks[index].MSF.M,
 		Tracks[index].MSF.S, Tracks[index].MSF.F);
 
+	if (PicoCDLoadProgressCB != NULL) PicoCDLoadProgressCB(100);
+
 	return 0;
 }
 
@@ -138,7 +154,12 @@ PICO_INTERNAL void Unload_ISO(void)
 
 	for(i = 1; i < 100; i++)
 	{
-		if (Pico_mcd->TOC.Tracks[i].F) fclose(Pico_mcd->TOC.Tracks[i].F);
+		if (Pico_mcd->TOC.Tracks[i].F != NULL)
+#if !DONT_OPEN_MANY_FILES
+			fclose(Pico_mcd->TOC.Tracks[i].F);
+#else
+			free(Pico_mcd->TOC.Tracks[i].F);
+#endif
 	}
 	memset(Pico_mcd->TOC.Tracks, 0, sizeof(Pico_mcd->TOC.Tracks));
 }

+ 18 - 1
Pico/sound/mix.c

@@ -39,16 +39,33 @@ void mix_32_to_16_mono(short *dest, int *src, int count)
 }
 
 
-/* unimplemented... */
 void mix_16h_to_32(int *dest_buf, short *mp3_buf, int count)
 {
+	while (count--)
+	{
+		*dest_buf++ += *mp3_buf++ >> 1;
+	}
 }
 
 void mix_16h_to_32_s1(int *dest_buf, short *mp3_buf, int count)
 {
+	count >>= 1;
+	while (count--)
+	{
+		*dest_buf++ += *mp3_buf++ >> 1;
+		*dest_buf++ += *mp3_buf++ >> 1;
+		mp3_buf += 1*2;
+	}
 }
 
 void mix_16h_to_32_s2(int *dest_buf, short *mp3_buf, int count)
 {
+	count >>= 1;
+	while (count--)
+	{
+		*dest_buf++ += *mp3_buf++ >> 1;
+		*dest_buf++ += *mp3_buf++ >> 1;
+		mp3_buf += 3*2;
+	}
 }
 

+ 6 - 2
platform/common/emu.c

@@ -285,7 +285,7 @@ int emu_ReloadRom(void)
 		return 0;
 	}
 
-	menu_romload_prepare(used_rom_name);
+	menu_romload_prepare(used_rom_name); // also CD load
 
 	if(rom_data) {
 		free(rom_data);
@@ -301,7 +301,6 @@ int emu_ReloadRom(void)
 		return 0;
 	}
 	pm_close(rom);
-	menu_romload_end();
 
 	// detect wrong files (Pico crashes on very small files), also see if ROM EP is good
 	if(rom_size <= 0x200 || strncmp((char *)rom_data, "Pico", 4) == 0 ||
@@ -309,6 +308,7 @@ int emu_ReloadRom(void)
 		if (rom_data) free(rom_data);
 		rom_data = 0;
 		sprintf(menuErrorMsg, "Not a ROM selected.");
+		menu_romload_end();
 		return 0;
 	}
 
@@ -321,6 +321,7 @@ int emu_ReloadRom(void)
 	lprintf("PicoCartInsert(%p, %d);\n", rom_data, rom_size);
 	if(PicoCartInsert(rom_data, rom_size)) {
 		sprintf(menuErrorMsg, "Failed to load ROM.");
+		menu_romload_end();
 		return 0;
 	}
 
@@ -332,10 +333,13 @@ int emu_ReloadRom(void)
 		if (ret != 0) {
 			sprintf(menuErrorMsg, "Insert_CD() failed, invalid CD image?");
 			lprintf("%s\n", menuErrorMsg);
+			menu_romload_end();
 			return 0;
 		}
 	}
 
+	menu_romload_end();
+
 	// emu_ReadConfig() might have messed currentConfig.lastRomFile
 	strncpy(currentConfig.lastRomFile, romFileName, sizeof(currentConfig.lastRomFile)-1);
 	currentConfig.lastRomFile[sizeof(currentConfig.lastRomFile)-1] = 0;

+ 3 - 0
platform/gizmondo/port_config.h

@@ -3,6 +3,9 @@
 #ifndef PORT_CONFIG_H
 #define PORT_CONFIG_H
 
+#define CASE_SENSITIVE_FS 0
+#define DONT_OPEN_MANY_FILES 0
+
 // draw.c
 #define OVERRIDE_HIGHCOL 1
 

+ 3 - 0
platform/gp2x/port_config.h

@@ -3,6 +3,9 @@
 #ifndef PORT_CONFIG_H
 #define PORT_CONFIG_H
 
+#define CASE_SENSITIVE_FS 1 // CS filesystem
+#define DONT_OPEN_MANY_FILES 0
+
 // draw.c
 #define OVERRIDE_HIGHCOL 0
 

+ 2 - 1
platform/psp/Makefile

@@ -76,7 +76,8 @@ endif
 OBJS += data/bg32.o data/bg40.o
 
 
-LIBS += -lpng -lm -lpspgu -lpsppower -lpspaudio -lpsprtc -Wl,-Map=PicoDrive.map
+LIBS += -lpng -lm -lpspgu -lpsppower -lpspaudio -lpsprtc -lpspaudiocodec
+LDFLAGS += -Wl,-Map=PicoDrive.map
 
 # target
 TARGET = PicoDrive

+ 8 - 7
platform/psp/emu.c

@@ -477,7 +477,7 @@ static void vidResetMode(void)
 /* sound stuff */
 #define SOUND_BLOCK_SIZE_NTSC (1470*2) // 1024 // 1152
 #define SOUND_BLOCK_SIZE_PAL  (1764*2)
-#define SOUND_BLOCK_COUNT    4
+#define SOUND_BLOCK_COUNT    8
 
 static short __attribute__((aligned(4))) sndBuffer[SOUND_BLOCK_SIZE_PAL*SOUND_BLOCK_COUNT + 44100/50*2];
 static short *snd_playptr = NULL, *sndBuffer_endptr = NULL;
@@ -489,7 +489,7 @@ static void writeSound(int len);
 
 static int sound_thread(SceSize args, void *argp)
 {
-	int ret;
+	int ret = 0;
 
 	lprintf("sthr: started, priority %i\n", sceKernelGetThreadCurrentPriority());
 
@@ -497,14 +497,14 @@ static int sound_thread(SceSize args, void *argp)
 	{
 		if (samples_made - samples_done < samples_block) {
 			// wait for data (use at least 2 blocks)
-			//lprintf("sthr: wait... (%i)\n", samples_made - samples_done);
+			lprintf("sthr: wait... (%i)\n", samples_made - samples_done);
 			while (samples_made - samples_done <= samples_block*2 && !sound_thread_exit)
 				ret = sceKernelWaitSema(sound_sem, 1, 0);
-			//lprintf("sthr: sceKernelWaitSema: %i\n", ret);
+			if (ret < 0) lprintf("sthr: sceKernelWaitSema: %i\n", ret);
 			continue;
 		}
 
-		//lprintf("sthr: got data: %i\n", samples_made - samples_done);
+		// lprintf("sthr: got data: %i\n", samples_made - samples_done);
 
 		ret = sceAudio_E0727056(PSP_AUDIO_VOLUME_MAX, snd_playptr);
 
@@ -517,7 +517,7 @@ static int sound_thread(SceSize args, void *argp)
 
 		// shouln't happen, but just in case
 		if (samples_made - samples_done >= samples_block*3) {
-			//lprintf("block skip (%i)\n", samples_made - samples_done);
+			lprintf("sthr: block skip (%i)\n", samples_made - samples_done);
 			samples_done += samples_block; // skip
 			snd_playptr  += samples_block;
 		}
@@ -615,6 +615,7 @@ static void writeSound(int len)
 		lprintf("mov\n");
 	}
 	else*/
+	if (PsndOut > sndBuffer_endptr) lprintf("snd oflow %i!\n", PsndOut - sndBuffer_endptr);
 	if (PsndOut >= sndBuffer_endptr)
 		PsndOut = sndBuffer;
 
@@ -623,7 +624,7 @@ static void writeSound(int len)
 	if (samples_made - samples_done > samples_block*2) {
 		// lprintf("signal, %i/%i\n", samples_done, samples_made);
 		ret = sceKernelSignalSema(sound_sem, 1);
-		// lprintf("signal ret %i\n", ret);
+		//if (ret < 0) lprintf("snd signal ret %08x\n", ret);
 	}
 }
 

+ 9 - 2
platform/psp/main.c

@@ -1,6 +1,7 @@
 #include "psp.h"
 #include "emu.h"
 #include "menu.h"
+#include "mp3.h"
 #include "../common/menu.h"
 #include "../common/emu.h"
 #include "../common/lprintf.h"
@@ -8,12 +9,15 @@
 
 int main()
 {
+	int mp3_ret;
+
 	lprintf("\nPicoDrive v" VERSION " " __DATE__ " " __TIME__ "\n");
 	psp_init();
 
 	emu_ReadConfig(0, 0);
 	emu_Init();
 	menu_init();
+	mp3_ret = mp3_init();
 
 	engineState = PGS_Menu;
 
@@ -26,9 +30,11 @@ int main()
 				break;
 
 			case PGS_ReloadRom:
-				if (emu_ReloadRom())
+				if (emu_ReloadRom()) {
 					engineState = PGS_Running;
-				else {
+					if (mp3_last_error != 0)
+						engineState = PGS_Menu; // send to menu to display mp3 error
+				} else {
 					lprintf("PGS_ReloadRom == 0\n");
 					engineState = PGS_Menu;
 				}
@@ -52,6 +58,7 @@ int main()
 
 	endloop:
 
+	if (mp3_ret == 0) mp3_deinit();
 	emu_Deinit();
 	psp_finish();
 

+ 42 - 8
platform/psp/menu.c

@@ -20,6 +20,7 @@
 #include "psp.h"
 #include "emu.h"
 #include "menu.h"
+#include "mp3.h"
 #include "../common/menu.h"
 #include "../common/emu.h"
 #include "../common/readpng.h"
@@ -112,17 +113,37 @@ static void menu_draw_end(void)
 
 // --------- loading ROM screen ----------
 
+static int lcdr_line = 0;
+
 static void load_progress_cb(int percent)
 {
 	int ln, len = percent * 480 / 100;
 	unsigned short *dst;
 
-	sceDisplayWaitVblankStart();
+	//sceDisplayWaitVblankStart();
+
+	dst = (unsigned short *)menu_screen + 512*10*lcdr_line;
+
+	if (len > 480) len = 480;
+	for (ln = 8; ln > 0; ln--, dst += 512)
+		memset(dst, 0xff, len*2);
+}
+
+static void cdload_progress_cb(int percent)
+{
+	int ln, len = percent * 480 / 100;
+	unsigned short *dst;
+
+	if (lcdr_line <= 2) {
+		lcdr_line++;
+		smalltext_out16(1, lcdr_line++ * 10, "Processing CD image / MP3s", 0xffff);
+		smalltext_out16_lim(1, lcdr_line++ * 10, romFileName, 0xffff, 80);
+	}
 
-	dst = (unsigned short *)menu_screen + 512*20;
+	dst = (unsigned short *)menu_screen + 512*10*lcdr_line;
 
 	if (len > 480) len = 480;
-	for (ln = 10; ln > 0; ln--, dst += 512)
+	for (ln = 8; ln > 0; ln--, dst += 512)
 		memset(dst, 0xff, len*2);
 }
 
@@ -132,17 +153,20 @@ void menu_romload_prepare(const char *rom_name)
 	while (p > rom_name && *p != '/') p--;
 
 	psp_video_switch_to_single();
-	menu_draw_begin();
+	if (rom_data) menu_draw_begin();
+	else memset32(psp_screen, 0, 512*272*2/4);
 
 	smalltext_out16(1, 1, "Loading", 0xffff);
 	smalltext_out16_lim(1, 10, p, 0xffff, 80);
 	PicoCartLoadProgressCB = load_progress_cb;
+	PicoCDLoadProgressCB = cdload_progress_cb;
+	lcdr_line = 2;
 }
 
 void menu_romload_end(void)
 {
-	PicoCartLoadProgressCB = NULL;
-	smalltext_out16(1, 30, "Starting emulation...", 0xffff);
+	PicoCartLoadProgressCB = PicoCDLoadProgressCB = NULL;
+	smalltext_out16(1, ++lcdr_line*10, "Starting emulation...", 0xffff);
 }
 
 // -------------- ROM selector --------------
@@ -907,7 +931,9 @@ static void cd_menu_loop_options(void)
 		strncpy(bios_names.jp, p, sizeof(bios_names.jp)); bios_names.jp[sizeof(bios_names.jp)-1] = 0;
 	} else	strcpy(bios_names.jp, "NOT FOUND");
 
-	for(;;)
+	menuErrorMsg[0] = 0;
+
+	for (;;)
 	{
 		draw_cd_menu_options(menu_sel, &bios_names);
 		inp = wait_for_input(BTN_UP|BTN_DOWN|BTN_LEFT|BTN_RIGHT|BTN_X|BTN_CIRCLE, 0);
@@ -1557,6 +1583,14 @@ static void menu_loop_root(void)
 	menu_sel_max = me_count_enabled(main_entries, MAIN_ENTRY_COUNT) - 1;
 	if (menu_sel > menu_sel_max) menu_sel = menu_sel_max;
 
+	// mp3 errors?
+	if (mp3_last_error != 0) {
+		if (mp3_last_error == -1)
+		     sprintf(menuErrorMsg, "Unsupported mp3 format, use 44kHz stereo");
+		else sprintf(menuErrorMsg, "mp3 init failed, code %08x", mp3_last_error);
+		mp3_last_error = 0;
+	}
+
 	/* make sure action buttons are not pressed on entering menu */
 	draw_menu_root(menu_sel);
 
@@ -1577,6 +1611,7 @@ static void menu_loop_root(void)
 			}
 		}
 		if(inp & BTN_CIRCLE)  {
+			menuErrorMsg[0] = 0; // clear error msg
 			switch (me_index2id(main_entries, MAIN_ENTRY_COUNT, menu_sel))
 			{
 				case MA_MAIN_RESUME_GAME:
@@ -1660,7 +1695,6 @@ static void menu_loop_root(void)
 					break;
 			}
 		}
-		menuErrorMsg[0] = 0; // clear error msg
 	}
 }
 

+ 425 - 3
platform/psp/mp3.c

@@ -1,20 +1,442 @@
 #include <stdio.h>
+#include <string.h>
 
-int mp3_get_bitrate(FILE *f, int size)
+#include <pspkernel.h>
+#include <pspsdk.h>
+#include <pspaudiocodec.h>
+
+#include "../../Pico/PicoInt.h"
+#include "../../Pico/sound/mix.h"
+#include "../common/lprintf.h"
+
+int mp3_last_error = 0;
+
+static SceUID thread_job_sem = -1;
+static SceUID thread_busy_sem = -1;
+static int thread_exit = 0;
+
+// MPEG-1, layer 3
+static int bitrates[] = { 0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0 };
+//static int samplerates[] = { 44100, 48000, 32000, 0 };
+
+#define MIN_INFRAME_SIZE 96
+#define IN_BUFFER_SIZE (2*1024)
+
+static unsigned long mp3_codec_struct[65] __attribute__((aligned(64)));
+
+static unsigned char mp3_src_buffer[2][IN_BUFFER_SIZE] __attribute__((aligned(64)));
+static short mp3_mix_buffer[2][1152*2] __attribute__((aligned(64)));
+static int working_buf = 0;
+
+static const char *mp3_fname = NULL;
+static SceUID mp3_handle = -1;
+static int mp3_src_pos = 0, mp3_src_size = 0;
+
+static int decode_thread(SceSize args, void *argp);
+
+
+static void psp_sem_lock(SceUID sem)
 {
+	int ret = sceKernelWaitSema(sem, 1, 0);
+	if (ret < 0) lprintf("sceKernelWaitSema(%08x) failed with %08x\n", sem, ret);
+}
+
+static void psp_sem_unlock(SceUID sem)
+{
+	int ret = sceKernelSignalSema(sem, 1);
+	if (ret < 0) lprintf("sceKernelSignalSema(%08x) failed with %08x\n", sem, ret);
+}
+
+// only accepts MPEG-1, layer3
+static int find_sync_word(unsigned char *data, int len)
+{
+	int i;
+	for (i = 0; i < len-1; i++)
+	{
+		if ( data[i+0] != 0xff) continue;
+		if ((data[i+1] & 0xfe) == 0xfa) return i;
+		i++;
+	}
+	return -1;
+}
+
+static int read_next_frame(int which_buffer)
+{
+	int i, bytes_read, frame_offset;
+	int bitrate, padding, frame_size = 0;
+
+	for (i = 0; i < 32; i++)
+	{
+		bytes_read = sceIoRead(mp3_handle, mp3_src_buffer[which_buffer], sizeof(mp3_src_buffer[which_buffer]));
+		mp3_src_pos += bytes_read;
+		if (bytes_read < MIN_INFRAME_SIZE) {
+			mp3_src_pos = mp3_src_size;
+			return 0; // EOF/IO failure
+		}
+		frame_offset = find_sync_word(mp3_src_buffer[which_buffer], bytes_read);
+		if (frame_offset < 0) {
+			lprintf("missing syncword, foffs=%i\n", mp3_src_pos - bytes_read);
+			mp3_src_pos--;
+			sceIoLseek32(mp3_handle, mp3_src_pos, PSP_SEEK_SET);
+			continue;
+		}
+		if (bytes_read - frame_offset < 4) {
+			lprintf("syncword @ EOB, foffs=%i\n", mp3_src_pos - bytes_read);
+			mp3_src_pos--;
+			sceIoLseek32(mp3_handle, mp3_src_pos, PSP_SEEK_SET);
+			continue;
+		}
+
+		bitrate =  mp3_src_buffer[which_buffer][frame_offset+2] >> 4;
+		padding = (mp3_src_buffer[which_buffer][frame_offset+2] & 2) >> 1;
+
+		frame_size = 144000*bitrates[bitrate]/44100 + padding;
+		if (frame_size <= 0) {
+			lprintf("bad frame, foffs=%i\n", mp3_src_pos - bytes_read);
+			continue; // bad frame
+		}
+
+		if (bytes_read - frame_offset < frame_size) {
+			lprintf("unfit, foffs=%i\n", mp3_src_pos - bytes_read);
+			mp3_src_pos -= bytes_read - frame_offset;
+			sceIoLseek32(mp3_handle, mp3_src_pos, PSP_SEEK_SET);
+			continue; // didn't fit, re-read..
+		}
+
+		if (frame_offset) {
+			lprintf("unaligned, foffs=%i, offs=%i\n", mp3_src_pos - bytes_read, frame_offset);
+			memmove(mp3_src_buffer[which_buffer], mp3_src_buffer[which_buffer] + frame_offset, frame_size);
+		}
+
+		// align for next frame read
+		mp3_src_pos -= bytes_read - (frame_offset + frame_size);
+		sceIoLseek32(mp3_handle, mp3_src_pos, PSP_SEEK_SET);
+
+		break;
+	}
+
+	return frame_size > 0 ? frame_size : -1;
+}
+
+
+static SceUID load_start_module(const char *prxname)
+{
+	SceUID mod = pspSdkLoadStartModule(prxname, PSP_MEMORY_PARTITION_KERNEL);
+	if (mod < 0)
+		lprintf("failed to load %s: %08x\n", prxname, mod);
+	return mod;
+}
+
+
+int mp3_init(void)
+{
+	SceUID thid, mod;
+	int ret;
+
+	/* load modules */
+	/* <= 1.5 (and probably some other, not sure which) fw need this to for audiocodec to work,
+	 * so if it fails, assume we are just on new enough firmware and continue.. */
+	load_start_module("flash0:/kd/me_for_vsh.prx");
+
+	if (sceKernelDevkitVersion() < 0x02070010)
+	     mod = load_start_module("flash0:/kd/audiocodec.prx");
+	else mod = load_start_module("flash0:/kd/avcodec.prx");
+	if (mod < 0) {
+		ret = mod = load_start_module("flash0:/kd/audiocodec_260.prx"); // last chance..
+		if (mod < 0) goto fail;
+	}
+
+	/* audiocodec init */
+	memset(mp3_codec_struct, 0, sizeof(mp3_codec_struct));
+	ret = sceAudiocodecCheckNeedMem(mp3_codec_struct, 0x1002);
+	if (ret < 0) {
+		lprintf("sceAudiocodecCheckNeedMem failed with %08x\n", ret);
+		goto fail;
+	}
+
+	ret = sceAudiocodecGetEDRAM(mp3_codec_struct, 0x1002);
+	if (ret < 0) {
+		lprintf("sceAudiocodecGetEDRAM failed with %08x\n", ret);
+		goto fail;
+	}
+
+	ret = sceAudiocodecInit(mp3_codec_struct, 0x1002);
+	if (ret < 0) {
+		lprintf("sceAudiocodecInit failed with %08x\n", ret);
+		goto fail1;
+	}
+
+	/* thread and stuff */
+	thread_job_sem = sceKernelCreateSema("p_mp3job_sem", 0, 0, 1, NULL);
+	if (thread_job_sem < 0) {
+		lprintf("sceKernelCreateSema() failed: %08x\n", thread_job_sem);
+		ret = thread_job_sem;
+		goto fail1;
+	}
+
+	thread_busy_sem = sceKernelCreateSema("p_mp3busy_sem", 0, 1, 1, NULL);
+	if (thread_busy_sem < 0) {
+		lprintf("sceKernelCreateSema() failed: %08x\n", thread_busy_sem);
+		ret = thread_busy_sem;
+		goto fail2;
+	}
+
+	lprintf("thread_busy_sem: %08x, thread_job_sem: %08x\n", thread_busy_sem, thread_job_sem);
+
+	thread_exit = 0;
+	thid = sceKernelCreateThread("mp3decode_thread", decode_thread, 30, 0x2000, 0, 0); /* use slightly higher prio then main */
+	if (thid < 0) {
+		lprintf("failed to create decode thread: %08x\n", thid);
+		ret = thid;
+		goto fail3;
+	}
+	ret = sceKernelStartThread(thid, 0, 0);
+	if (ret < 0) {
+		lprintf("failed to start decode thread: %08x\n", ret);
+		goto fail3;
+	}
+
+	mp3_last_error = 0;
 	return 0;
+
+fail3:
+	sceKernelDeleteSema(thread_busy_sem);
+	thread_busy_sem = -1;
+fail2:
+	sceKernelDeleteSema(thread_job_sem);
+	thread_job_sem = -1;
+fail1:
+	sceAudiocodecReleaseEDRAM(mp3_codec_struct);
+fail:
+	mp3_last_error = ret;
+	return 1;
 }
 
-void mp3_start_play(FILE *f, int pos)
+void mp3_deinit(void)
 {
+	lprintf("deinit\n");
+	thread_exit = 1;
+	psp_sem_lock(thread_busy_sem);
+	psp_sem_unlock(thread_busy_sem);
+
+	sceKernelSignalSema(thread_job_sem, 1);
+	sceKernelDelayThread(100*1000);
+
+	if (mp3_handle >= 0) sceIoClose(mp3_handle);
+	mp3_handle = -1;
+	mp3_fname = NULL;
+
+	sceKernelDeleteSema(thread_busy_sem);
+	thread_busy_sem = -1;
+	sceKernelDeleteSema(thread_job_sem);
+	thread_job_sem = -1;
+	sceAudiocodecReleaseEDRAM(mp3_codec_struct);
 }
 
-int  mp3_get_offset(void) // 0-1023
+// may overflow stack?
+static int decode_thread(SceSize args, void *argp)
 {
+	int ret, frame_size;
+
+	lprintf("decode_thread started with id %08x, priority %i\n",
+                sceKernelGetThreadId(), sceKernelGetThreadCurrentPriority());
+
+	while (!thread_exit)
+	{
+		psp_sem_lock(thread_job_sem);
+		if (thread_exit) break;
+
+		psp_sem_lock(thread_busy_sem);
+		//lprintf("{ job\n");
+
+		frame_size = read_next_frame(working_buf);
+		if (frame_size > 0)
+		{
+			mp3_codec_struct[6] = (unsigned long)mp3_src_buffer[working_buf];
+			mp3_codec_struct[8] = (unsigned long)mp3_mix_buffer[working_buf];
+			mp3_codec_struct[7] = mp3_codec_struct[10] = frame_size;
+			mp3_codec_struct[9] = 1152 * 4;
+
+			ret = sceAudiocodecDecode(mp3_codec_struct, 0x1002);
+			if (ret < 0) lprintf("sceAudiocodecDecode failed with %08x\n", ret);
+		}
+
+		//lprintf("} job\n");
+		psp_sem_unlock(thread_busy_sem);
+	}
+
+	lprintf("leaving decode thread\n");
+	sceKernelExitDeleteThread(0);
 	return 0;
 }
 
+
+int mp3_get_bitrate(FILE *f, int size)
+{
+	int ret = -1, sample_rate, bitrate;
+	// filenames are stored instead handles in PSP, due to stupid max open file limit
+	char *fname = (char *)f;
+
+	/* make sure thread is not busy.. */
+	psp_sem_lock(thread_busy_sem);
+
+	if (mp3_handle >= 0) sceIoClose(mp3_handle);
+	mp3_handle = sceIoOpen(fname, PSP_O_RDONLY, 0777);
+	if (mp3_handle < 0) {
+		lprintf("sceIoOpen(%s) failed\n", fname);
+		goto end;
+	}
+
+	mp3_src_pos = 0;
+	ret = read_next_frame(0);
+	if (ret <= 0) {
+		lprintf("read_next_frame() failed\n");
+		goto end;
+	}
+	sample_rate = (mp3_src_buffer[0][2] & 0x0c) >> 2;
+	bitrate = mp3_src_buffer[0][2] >> 4;
+
+	if (sample_rate != 0) {
+		lprintf("unsupported samplerate\n");
+		goto end; // only 44kHz supported..
+	}
+	bitrate = bitrates[bitrate];
+	if (bitrate == 0) {
+		lprintf("unsupported bitrate\n");
+		goto end;
+	}
+
+	/* looking good.. */
+	ret = bitrate;
+end:
+	if (mp3_handle >= 0) sceIoClose(mp3_handle);
+	mp3_handle = -1;
+	mp3_fname = NULL;
+	psp_sem_unlock(thread_busy_sem);
+	if (ret < 0) mp3_last_error = -1; // remember we had a problem..
+	return ret;
+}
+
+
+static int mp3_job_started = 0, mp3_samples_ready = 0, mp3_buffer_offs = 0, mp3_play_bufsel = 0;
+
+void mp3_start_play(FILE *f, int pos)
+{
+	char *fname = (char *)f;
+
+	lprintf("mp3_start_play(%s) @ %i\n", fname, pos);
+	psp_sem_lock(thread_busy_sem);
+
+	if (mp3_fname != fname)
+	{
+		if (mp3_handle >= 0) sceIoClose(mp3_handle);
+		mp3_handle = sceIoOpen(fname, PSP_O_RDONLY, 0777);
+		if (mp3_handle < 0) {
+			lprintf("sceIoOpen(%s) failed\n", fname);
+			psp_sem_unlock(thread_busy_sem);
+			return;
+		}
+		mp3_src_size = sceIoLseek32(mp3_handle, 0, PSP_SEEK_END);
+		mp3_fname = fname;
+	}
+
+	// seek..
+	mp3_src_pos = (int) (((float)pos / 1023.0f) * (float)mp3_src_size);
+	sceIoLseek32(mp3_handle, mp3_src_pos, PSP_SEEK_SET);
+	lprintf("seek %i: %i/%i\n", pos, mp3_src_pos, mp3_src_size);
+
+	mp3_job_started = 1;
+	mp3_samples_ready = mp3_buffer_offs = mp3_play_bufsel = 0;
+	working_buf = 0;
+
+	/* send a request to decode first frame */
+	psp_sem_unlock(thread_busy_sem);
+	psp_sem_unlock(thread_job_sem);
+	sceKernelDelayThread(1); // reschedule
+}
+
+
 void mp3_update(int *buffer, int length, int stereo)
 {
+	int length_mp3;
+
+	// playback was started, track not ended
+	if (mp3_handle < 0 || mp3_src_pos >= mp3_src_size) return;
+
+	length_mp3 = length;
+	if (PsndRate == 22050) length_mp3 <<= 1;	// mp3s are locked to 44100Hz stereo
+	else if (PsndRate == 11025) length_mp3 <<= 2;	// so make length 44100ish
+
+	/* do we have to wait? */
+	if (mp3_job_started && mp3_samples_ready < length_mp3)
+	{
+		psp_sem_lock(thread_busy_sem);
+		psp_sem_unlock(thread_busy_sem);
+		mp3_job_started = 0;
+		mp3_samples_ready += 1152;
+	}
+
+	/* mix mp3 data, only stereo */
+	if (mp3_samples_ready >= length_mp3)
+	{
+		int shr = 0;
+		void (*mix_samples)(int *dest_buf, short *mp3_buf, int count) = mix_16h_to_32;
+		if (PsndRate == 22050) { mix_samples = mix_16h_to_32_s1; shr = 1; }
+		else if (PsndRate == 11025) { mix_samples = mix_16h_to_32_s2; shr = 2; }
+
+		if (1152 - mp3_buffer_offs >= length_mp3) {
+			mix_samples(buffer, mp3_mix_buffer[mp3_play_bufsel] + mp3_buffer_offs*2, length<<1);
+
+			mp3_buffer_offs += length_mp3;
+		} else {
+			// collect samples from both buffers..
+			int left = 1152 - mp3_buffer_offs;
+			if (mp3_play_bufsel == 0)
+			{
+				mix_samples(buffer, mp3_mix_buffer[0] + mp3_buffer_offs*2, length<<1);
+				mp3_buffer_offs = length_mp3 - left;
+				mp3_play_bufsel = 1;
+			} else {
+				mix_samples(buffer, mp3_mix_buffer[1] + mp3_buffer_offs*2, (left>>shr)<<1);
+				mp3_buffer_offs = length_mp3 - left;
+				mix_samples(buffer + ((left>>shr)<<1),
+					mp3_mix_buffer[0], (mp3_buffer_offs>>shr)<<1);
+				mp3_play_bufsel = 0;
+			}
+		}
+		mp3_samples_ready -= length_mp3;
+	}
+
+	// ask to decode more if we already can
+	if (!mp3_job_started)
+	{
+		mp3_job_started = 1;
+		working_buf ^= 1;
+
+		/* next job.. */
+		psp_sem_lock(thread_busy_sem);   // just in case
+		psp_sem_unlock(thread_busy_sem);
+		psp_sem_unlock(thread_job_sem);
+		sceKernelDelayThread(1);
+	}
+}
+
+
+int mp3_get_offset(void) // 0-1023
+{
+	unsigned int offs1024 = 0;
+	int cdda_on;
+
+	cdda_on = (PicoMCD & 1) && (PicoOpt&0x800) && !(Pico_mcd->s68k_regs[0x36] & 1) &&
+			(Pico_mcd->scd.Status_CDC & 1) && mp3_handle >= 0;
+
+	if (cdda_on) {
+		offs1024  = mp3_src_pos << 7;
+		offs1024 /= mp3_src_size >> 3;
+	}
+	lprintf("offs1024=%u (%i/%i)\n", offs1024, mp3_src_pos, mp3_src_size);
+
+	return offs1024;
 }
 
+

+ 3 - 0
platform/psp/port_config.h

@@ -3,6 +3,9 @@
 #ifndef PORT_CONFIG_H
 #define PORT_CONFIG_H
 
+#define CASE_SENSITIVE_FS 0
+#define DONT_OPEN_MANY_FILES 1 // work around the stupid PSP 10 open file limit
+
 // draw.c
 #define USE_BGR555 1
 #define OVERRIDE_HIGHCOL 1

+ 2 - 2
platform/psp/psp.c

@@ -33,7 +33,7 @@ static int callback_thread(SceSize args, void *argp)
 {
 	int cbid;
 
-	lprintf("callback_thread started with id %i, priority %i\n",
+	lprintf("callback_thread started with id %08x, priority %i\n",
 		sceKernelGetThreadId(), sceKernelGetThreadCurrentPriority());
 
 	cbid = sceKernelCreateCallback("Exit Callback", exit_callback, NULL);
@@ -49,7 +49,7 @@ void psp_init(void)
 	SceUID thid;
 
 	lprintf("running in %08x kernel\n", sceKernelDevkitVersion()),
-	lprintf("entered psp_init, threadId %i, priority %i\n", sceKernelGetThreadId(),
+	lprintf("entered psp_init, threadId %08x, priority %i\n", sceKernelGetThreadId(),
 		sceKernelGetThreadCurrentPriority());
 
 	thid = sceKernelCreateThread("update_thread", callback_thread, 0x11, 0xFA0, 0, 0);