psp mp3 implementation
[picodrive.git] / platform / psp / mp3.c
1 #include <stdio.h>
2 #include <string.h>
3
4 #include <pspkernel.h>
5 #include <pspsdk.h>
6 #include <pspaudiocodec.h>
7
8 #include "../../Pico/PicoInt.h"
9 #include "../../Pico/sound/mix.h"
10 #include "../common/lprintf.h"
11
12 int mp3_last_error = 0;
13
14 static SceUID thread_job_sem = -1;
15 static SceUID thread_busy_sem = -1;
16 static int thread_exit = 0;
17
18 // MPEG-1, layer 3
19 static int bitrates[] = { 0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0 };
20 //static int samplerates[] = { 44100, 48000, 32000, 0 };
21
22 #define MIN_INFRAME_SIZE 96
23 #define IN_BUFFER_SIZE (2*1024)
24
25 static unsigned long mp3_codec_struct[65] __attribute__((aligned(64)));
26
27 static unsigned char mp3_src_buffer[2][IN_BUFFER_SIZE] __attribute__((aligned(64)));
28 static short mp3_mix_buffer[2][1152*2] __attribute__((aligned(64)));
29 static int working_buf = 0;
30
31 static const char *mp3_fname = NULL;
32 static SceUID mp3_handle = -1;
33 static int mp3_src_pos = 0, mp3_src_size = 0;
34
35 static int decode_thread(SceSize args, void *argp);
36
37
38 static void psp_sem_lock(SceUID sem)
39 {
40         int ret = sceKernelWaitSema(sem, 1, 0);
41         if (ret < 0) lprintf("sceKernelWaitSema(%08x) failed with %08x\n", sem, ret);
42 }
43
44 static void psp_sem_unlock(SceUID sem)
45 {
46         int ret = sceKernelSignalSema(sem, 1);
47         if (ret < 0) lprintf("sceKernelSignalSema(%08x) failed with %08x\n", sem, ret);
48 }
49
50 // only accepts MPEG-1, layer3
51 static int find_sync_word(unsigned char *data, int len)
52 {
53         int i;
54         for (i = 0; i < len-1; i++)
55         {
56                 if ( data[i+0] != 0xff) continue;
57                 if ((data[i+1] & 0xfe) == 0xfa) return i;
58                 i++;
59         }
60         return -1;
61 }
62
63 static int read_next_frame(int which_buffer)
64 {
65         int i, bytes_read, frame_offset;
66         int bitrate, padding, frame_size = 0;
67
68         for (i = 0; i < 32; i++)
69         {
70                 bytes_read = sceIoRead(mp3_handle, mp3_src_buffer[which_buffer], sizeof(mp3_src_buffer[which_buffer]));
71                 mp3_src_pos += bytes_read;
72                 if (bytes_read < MIN_INFRAME_SIZE) {
73                         mp3_src_pos = mp3_src_size;
74                         return 0; // EOF/IO failure
75                 }
76                 frame_offset = find_sync_word(mp3_src_buffer[which_buffer], bytes_read);
77                 if (frame_offset < 0) {
78                         lprintf("missing syncword, foffs=%i\n", mp3_src_pos - bytes_read);
79                         mp3_src_pos--;
80                         sceIoLseek32(mp3_handle, mp3_src_pos, PSP_SEEK_SET);
81                         continue;
82                 }
83                 if (bytes_read - frame_offset < 4) {
84                         lprintf("syncword @ EOB, foffs=%i\n", mp3_src_pos - bytes_read);
85                         mp3_src_pos--;
86                         sceIoLseek32(mp3_handle, mp3_src_pos, PSP_SEEK_SET);
87                         continue;
88                 }
89
90                 bitrate =  mp3_src_buffer[which_buffer][frame_offset+2] >> 4;
91                 padding = (mp3_src_buffer[which_buffer][frame_offset+2] & 2) >> 1;
92
93                 frame_size = 144000*bitrates[bitrate]/44100 + padding;
94                 if (frame_size <= 0) {
95                         lprintf("bad frame, foffs=%i\n", mp3_src_pos - bytes_read);
96                         continue; // bad frame
97                 }
98
99                 if (bytes_read - frame_offset < frame_size) {
100                         lprintf("unfit, foffs=%i\n", mp3_src_pos - bytes_read);
101                         mp3_src_pos -= bytes_read - frame_offset;
102                         sceIoLseek32(mp3_handle, mp3_src_pos, PSP_SEEK_SET);
103                         continue; // didn't fit, re-read..
104                 }
105
106                 if (frame_offset) {
107                         lprintf("unaligned, foffs=%i, offs=%i\n", mp3_src_pos - bytes_read, frame_offset);
108                         memmove(mp3_src_buffer[which_buffer], mp3_src_buffer[which_buffer] + frame_offset, frame_size);
109                 }
110
111                 // align for next frame read
112                 mp3_src_pos -= bytes_read - (frame_offset + frame_size);
113                 sceIoLseek32(mp3_handle, mp3_src_pos, PSP_SEEK_SET);
114
115                 break;
116         }
117
118         return frame_size > 0 ? frame_size : -1;
119 }
120
121
122 static SceUID load_start_module(const char *prxname)
123 {
124         SceUID mod = pspSdkLoadStartModule(prxname, PSP_MEMORY_PARTITION_KERNEL);
125         if (mod < 0)
126                 lprintf("failed to load %s: %08x\n", prxname, mod);
127         return mod;
128 }
129
130
131 int mp3_init(void)
132 {
133         SceUID thid, mod;
134         int ret;
135
136         /* load modules */
137         /* <= 1.5 (and probably some other, not sure which) fw need this to for audiocodec to work,
138          * so if it fails, assume we are just on new enough firmware and continue.. */
139         load_start_module("flash0:/kd/me_for_vsh.prx");
140
141         if (sceKernelDevkitVersion() < 0x02070010)
142              mod = load_start_module("flash0:/kd/audiocodec.prx");
143         else mod = load_start_module("flash0:/kd/avcodec.prx");
144         if (mod < 0) {
145                 ret = mod = load_start_module("flash0:/kd/audiocodec_260.prx"); // last chance..
146                 if (mod < 0) goto fail;
147         }
148
149         /* audiocodec init */
150         memset(mp3_codec_struct, 0, sizeof(mp3_codec_struct));
151         ret = sceAudiocodecCheckNeedMem(mp3_codec_struct, 0x1002);
152         if (ret < 0) {
153                 lprintf("sceAudiocodecCheckNeedMem failed with %08x\n", ret);
154                 goto fail;
155         }
156
157         ret = sceAudiocodecGetEDRAM(mp3_codec_struct, 0x1002);
158         if (ret < 0) {
159                 lprintf("sceAudiocodecGetEDRAM failed with %08x\n", ret);
160                 goto fail;
161         }
162
163         ret = sceAudiocodecInit(mp3_codec_struct, 0x1002);
164         if (ret < 0) {
165                 lprintf("sceAudiocodecInit failed with %08x\n", ret);
166                 goto fail1;
167         }
168
169         /* thread and stuff */
170         thread_job_sem = sceKernelCreateSema("p_mp3job_sem", 0, 0, 1, NULL);
171         if (thread_job_sem < 0) {
172                 lprintf("sceKernelCreateSema() failed: %08x\n", thread_job_sem);
173                 ret = thread_job_sem;
174                 goto fail1;
175         }
176
177         thread_busy_sem = sceKernelCreateSema("p_mp3busy_sem", 0, 1, 1, NULL);
178         if (thread_busy_sem < 0) {
179                 lprintf("sceKernelCreateSema() failed: %08x\n", thread_busy_sem);
180                 ret = thread_busy_sem;
181                 goto fail2;
182         }
183
184         lprintf("thread_busy_sem: %08x, thread_job_sem: %08x\n", thread_busy_sem, thread_job_sem);
185
186         thread_exit = 0;
187         thid = sceKernelCreateThread("mp3decode_thread", decode_thread, 30, 0x2000, 0, 0); /* use slightly higher prio then main */
188         if (thid < 0) {
189                 lprintf("failed to create decode thread: %08x\n", thid);
190                 ret = thid;
191                 goto fail3;
192         }
193         ret = sceKernelStartThread(thid, 0, 0);
194         if (ret < 0) {
195                 lprintf("failed to start decode thread: %08x\n", ret);
196                 goto fail3;
197         }
198
199         mp3_last_error = 0;
200         return 0;
201
202 fail3:
203         sceKernelDeleteSema(thread_busy_sem);
204         thread_busy_sem = -1;
205 fail2:
206         sceKernelDeleteSema(thread_job_sem);
207         thread_job_sem = -1;
208 fail1:
209         sceAudiocodecReleaseEDRAM(mp3_codec_struct);
210 fail:
211         mp3_last_error = ret;
212         return 1;
213 }
214
215 void mp3_deinit(void)
216 {
217         lprintf("deinit\n");
218         thread_exit = 1;
219         psp_sem_lock(thread_busy_sem);
220         psp_sem_unlock(thread_busy_sem);
221
222         sceKernelSignalSema(thread_job_sem, 1);
223         sceKernelDelayThread(100*1000);
224
225         if (mp3_handle >= 0) sceIoClose(mp3_handle);
226         mp3_handle = -1;
227         mp3_fname = NULL;
228
229         sceKernelDeleteSema(thread_busy_sem);
230         thread_busy_sem = -1;
231         sceKernelDeleteSema(thread_job_sem);
232         thread_job_sem = -1;
233         sceAudiocodecReleaseEDRAM(mp3_codec_struct);
234 }
235
236 // may overflow stack?
237 static int decode_thread(SceSize args, void *argp)
238 {
239         int ret, frame_size;
240
241         lprintf("decode_thread started with id %08x, priority %i\n",
242                 sceKernelGetThreadId(), sceKernelGetThreadCurrentPriority());
243
244         while (!thread_exit)
245         {
246                 psp_sem_lock(thread_job_sem);
247                 if (thread_exit) break;
248
249                 psp_sem_lock(thread_busy_sem);
250                 //lprintf("{ job\n");
251
252                 frame_size = read_next_frame(working_buf);
253                 if (frame_size > 0)
254                 {
255                         mp3_codec_struct[6] = (unsigned long)mp3_src_buffer[working_buf];
256                         mp3_codec_struct[8] = (unsigned long)mp3_mix_buffer[working_buf];
257                         mp3_codec_struct[7] = mp3_codec_struct[10] = frame_size;
258                         mp3_codec_struct[9] = 1152 * 4;
259
260                         ret = sceAudiocodecDecode(mp3_codec_struct, 0x1002);
261                         if (ret < 0) lprintf("sceAudiocodecDecode failed with %08x\n", ret);
262                 }
263
264                 //lprintf("} job\n");
265                 psp_sem_unlock(thread_busy_sem);
266         }
267
268         lprintf("leaving decode thread\n");
269         sceKernelExitDeleteThread(0);
270         return 0;
271 }
272
273
274 int mp3_get_bitrate(FILE *f, int size)
275 {
276         int ret = -1, sample_rate, bitrate;
277         // filenames are stored instead handles in PSP, due to stupid max open file limit
278         char *fname = (char *)f;
279
280         /* make sure thread is not busy.. */
281         psp_sem_lock(thread_busy_sem);
282
283         if (mp3_handle >= 0) sceIoClose(mp3_handle);
284         mp3_handle = sceIoOpen(fname, PSP_O_RDONLY, 0777);
285         if (mp3_handle < 0) {
286                 lprintf("sceIoOpen(%s) failed\n", fname);
287                 goto end;
288         }
289
290         mp3_src_pos = 0;
291         ret = read_next_frame(0);
292         if (ret <= 0) {
293                 lprintf("read_next_frame() failed\n");
294                 goto end;
295         }
296         sample_rate = (mp3_src_buffer[0][2] & 0x0c) >> 2;
297         bitrate = mp3_src_buffer[0][2] >> 4;
298
299         if (sample_rate != 0) {
300                 lprintf("unsupported samplerate\n");
301                 goto end; // only 44kHz supported..
302         }
303         bitrate = bitrates[bitrate];
304         if (bitrate == 0) {
305                 lprintf("unsupported bitrate\n");
306                 goto end;
307         }
308
309         /* looking good.. */
310         ret = bitrate;
311 end:
312         if (mp3_handle >= 0) sceIoClose(mp3_handle);
313         mp3_handle = -1;
314         mp3_fname = NULL;
315         psp_sem_unlock(thread_busy_sem);
316         if (ret < 0) mp3_last_error = -1; // remember we had a problem..
317         return ret;
318 }
319
320
321 static int mp3_job_started = 0, mp3_samples_ready = 0, mp3_buffer_offs = 0, mp3_play_bufsel = 0;
322
323 void mp3_start_play(FILE *f, int pos)
324 {
325         char *fname = (char *)f;
326
327         lprintf("mp3_start_play(%s) @ %i\n", fname, pos);
328         psp_sem_lock(thread_busy_sem);
329
330         if (mp3_fname != fname)
331         {
332                 if (mp3_handle >= 0) sceIoClose(mp3_handle);
333                 mp3_handle = sceIoOpen(fname, PSP_O_RDONLY, 0777);
334                 if (mp3_handle < 0) {
335                         lprintf("sceIoOpen(%s) failed\n", fname);
336                         psp_sem_unlock(thread_busy_sem);
337                         return;
338                 }
339                 mp3_src_size = sceIoLseek32(mp3_handle, 0, PSP_SEEK_END);
340                 mp3_fname = fname;
341         }
342
343         // seek..
344         mp3_src_pos = (int) (((float)pos / 1023.0f) * (float)mp3_src_size);
345         sceIoLseek32(mp3_handle, mp3_src_pos, PSP_SEEK_SET);
346         lprintf("seek %i: %i/%i\n", pos, mp3_src_pos, mp3_src_size);
347
348         mp3_job_started = 1;
349         mp3_samples_ready = mp3_buffer_offs = mp3_play_bufsel = 0;
350         working_buf = 0;
351
352         /* send a request to decode first frame */
353         psp_sem_unlock(thread_busy_sem);
354         psp_sem_unlock(thread_job_sem);
355         sceKernelDelayThread(1); // reschedule
356 }
357
358
359 void mp3_update(int *buffer, int length, int stereo)
360 {
361         int length_mp3;
362
363         // playback was started, track not ended
364         if (mp3_handle < 0 || mp3_src_pos >= mp3_src_size) return;
365
366         length_mp3 = length;
367         if (PsndRate == 22050) length_mp3 <<= 1;        // mp3s are locked to 44100Hz stereo
368         else if (PsndRate == 11025) length_mp3 <<= 2;   // so make length 44100ish
369
370         /* do we have to wait? */
371         if (mp3_job_started && mp3_samples_ready < length_mp3)
372         {
373                 psp_sem_lock(thread_busy_sem);
374                 psp_sem_unlock(thread_busy_sem);
375                 mp3_job_started = 0;
376                 mp3_samples_ready += 1152;
377         }
378
379         /* mix mp3 data, only stereo */
380         if (mp3_samples_ready >= length_mp3)
381         {
382                 int shr = 0;
383                 void (*mix_samples)(int *dest_buf, short *mp3_buf, int count) = mix_16h_to_32;
384                 if (PsndRate == 22050) { mix_samples = mix_16h_to_32_s1; shr = 1; }
385                 else if (PsndRate == 11025) { mix_samples = mix_16h_to_32_s2; shr = 2; }
386
387                 if (1152 - mp3_buffer_offs >= length_mp3) {
388                         mix_samples(buffer, mp3_mix_buffer[mp3_play_bufsel] + mp3_buffer_offs*2, length<<1);
389
390                         mp3_buffer_offs += length_mp3;
391                 } else {
392                         // collect samples from both buffers..
393                         int left = 1152 - mp3_buffer_offs;
394                         if (mp3_play_bufsel == 0)
395                         {
396                                 mix_samples(buffer, mp3_mix_buffer[0] + mp3_buffer_offs*2, length<<1);
397                                 mp3_buffer_offs = length_mp3 - left;
398                                 mp3_play_bufsel = 1;
399                         } else {
400                                 mix_samples(buffer, mp3_mix_buffer[1] + mp3_buffer_offs*2, (left>>shr)<<1);
401                                 mp3_buffer_offs = length_mp3 - left;
402                                 mix_samples(buffer + ((left>>shr)<<1),
403                                         mp3_mix_buffer[0], (mp3_buffer_offs>>shr)<<1);
404                                 mp3_play_bufsel = 0;
405                         }
406                 }
407                 mp3_samples_ready -= length_mp3;
408         }
409
410         // ask to decode more if we already can
411         if (!mp3_job_started)
412         {
413                 mp3_job_started = 1;
414                 working_buf ^= 1;
415
416                 /* next job.. */
417                 psp_sem_lock(thread_busy_sem);   // just in case
418                 psp_sem_unlock(thread_busy_sem);
419                 psp_sem_unlock(thread_job_sem);
420                 sceKernelDelayThread(1);
421         }
422 }
423
424
425 int mp3_get_offset(void) // 0-1023
426 {
427         unsigned int offs1024 = 0;
428         int cdda_on;
429
430         cdda_on = (PicoMCD & 1) && (PicoOpt&0x800) && !(Pico_mcd->s68k_regs[0x36] & 1) &&
431                         (Pico_mcd->scd.Status_CDC & 1) && mp3_handle >= 0;
432
433         if (cdda_on) {
434                 offs1024  = mp3_src_pos << 7;
435                 offs1024 /= mp3_src_size >> 3;
436         }
437         lprintf("offs1024=%u (%i/%i)\n", offs1024, mp3_src_pos, mp3_src_size);
438
439         return offs1024;
440 }
441
442