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