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