]> git.sesse.net Git - vlc/blob - modules/codec/mad/libmad.c
PTS calculation fix for the mad plug-in, courtesy of KKI_ on IRC.
[vlc] / modules / codec / mad / libmad.c
1 /***************************************************************************
2              libmad.c  -  description
3                -------------------
4     Functions that are called by libmad to communicate with vlc decoder
5     infrastructure.
6
7     begin                : Mon Nov 5 2001
8     copyright            : (C) 2001 by Jean-Paul Saman
9     email                : jpsaman@wxs.nl
10  ***************************************************************************/
11
12 /***************************************************************************
13  *                                                                         *
14  *   This program is free software; you can redistribute it and/or modify  *
15  *   it under the terms of the GNU General Public License as published by  *
16  *   the Free Software Foundation; either version 2 of the License, or     *
17  *   (at your option) any later version.                                   *
18  *                                                                         *
19  ***************************************************************************/
20
21 /*****************************************************************************
22  * Preamble
23  *****************************************************************************/
24 #include <stdlib.h>                                      /* malloc(), free() */
25 #include <string.h>                                              /* strdup() */
26
27 #include <vlc/vlc.h>
28 #include <vlc/aout.h>
29 #include <vlc/decoder.h>
30
31 /*****************************************************************************
32  * Libmad includes files
33  *****************************************************************************/
34 #include <mad.h>
35 #include "decoder.h"
36 #include "libmad.h"
37
38 static void PrintFrameInfo(struct mad_header *Header);
39
40 /*****************************************************************************
41  * libmad_input: this function is called by libmad when the input buffer needs
42  * to be filled.
43  *****************************************************************************/
44 enum mad_flow libmad_input( void *p_data, struct mad_stream *p_stream )
45 {
46     mad_adec_thread_t * p_dec = (mad_adec_thread_t *) p_data;
47     size_t   i_wanted, i_left, i_current;
48
49     if ( p_dec->p_fifo->b_die )
50     {
51         msg_Dbg( p_dec->p_fifo, "stopping libmad decoder" );
52         return MAD_FLOW_STOP;
53     }
54
55     if ( p_dec->p_fifo->b_error )
56     {
57         msg_Warn( p_dec->p_fifo, "ignoring current audio frame" );
58         return MAD_FLOW_IGNORE;
59     }
60
61     /* libmad_stream_buffer does not consume the total buffer, it consumes
62      * only data for one frame only. So all data left in the buffer should
63      * be put back in front. */
64     if ( !p_stream->buffer || p_stream->error == MAD_ERROR_BUFLEN )
65     {
66        /* libmad does not consume all the buffer it's given. Some data,
67         * part of a truncated frame, is left unused at the end of the
68         * buffer. Those datas must be put back at the beginning of the
69         * buffer and taken in account for refilling the buffer. This
70         * means that the input buffer must be large enough to hold a
71         * complete frame at the highest observable bit-rate (currently
72         * 448 kb/s). XXX=XXX Is 2016 bytes the size of the largest frame?
73         * (448000*(1152/32000))/8 */
74         if( p_stream->next_frame )
75         {
76             i_left    = p_stream->bufend - p_stream->next_frame;
77             i_current = p_stream->next_frame - p_dec->buffer;
78             if( p_dec->buffer != p_stream->next_frame )
79             {
80                 memcpy( p_dec->buffer, p_stream->next_frame, i_left );
81             }
82             i_wanted = MAD_BUFFER_MDLEN - i_left;
83
84             /* Store timestamp for next frame */
85             if ( ( p_stream->next_frame == p_dec->buffer ) ||
86                  ( i_current >= i_left * ( ( i_current / ( MAD_BUFFER_MDLEN - i_current ) ) + 1 ) )
87                )
88             {
89                 p_dec->i_next_pts = p_dec->bit_stream.p_pes->i_pts;
90             }
91             else
92             {
93                 /* p_dec->bit_stream.p_pes->i_pts != p_dec->i_next_pts */
94                 p_dec->i_next_pts = 0;
95             }
96         }
97         else
98         {
99             i_wanted = MAD_BUFFER_MDLEN;
100             i_left = 0;
101
102             /* Store timestamp for this frame */
103             p_dec->i_current_pts = p_dec->bit_stream.p_pes->i_pts;
104         }
105
106         /* Fill-in the buffer. If an error occurs print a message and leave
107          * the decoding loop. If the end of stream is reached we also leave
108          * the loop but the return status is left untouched. */
109         if( i_wanted > (size_t)(p_dec->bit_stream.p_data->p_payload_end
110                                  - p_dec->bit_stream.p_data->p_payload_start) )
111         {
112             i_wanted = p_dec->bit_stream.p_data->p_payload_end
113                         - p_dec->bit_stream.p_data->p_payload_start;
114             memcpy( p_dec->buffer + i_left,
115                     p_dec->bit_stream.p_data->p_payload_start, i_wanted );
116             NextDataPacket( p_dec->p_fifo, &p_dec->bit_stream );
117             /* No need to check that p_dec->bit_stream->p_data is valid
118              * since we check later on for b_die and b_error */
119         }
120         else
121         {
122             memcpy( p_dec->buffer + i_left,
123                     p_dec->bit_stream.p_data->p_payload_start, i_wanted );
124             p_dec->bit_stream.p_data->p_payload_start += i_wanted;
125         }
126
127         if ( p_dec->p_fifo->b_die )
128         {
129             msg_Dbg( p_dec->p_fifo, "stopping libmad decoder" );
130             return MAD_FLOW_STOP;
131         }
132
133         if ( p_dec->p_fifo->b_error )
134         {
135             msg_Warn( p_dec->p_fifo, "ignoring current audio frame" );    
136             return MAD_FLOW_IGNORE;
137         }
138
139         /* Pipe the new buffer content to libmad's stream decoder facility.
140          * Libmad never copies the buffer, but just references it. So keep
141          * it in mad_adec_thread_t structure. */
142         mad_stream_buffer( p_stream, (unsigned char*) &p_dec->buffer,
143                            i_left + i_wanted );
144         p_stream->error = 0;
145     }
146
147     return MAD_FLOW_CONTINUE;
148 }
149
150 /*****************************************************************************
151  * libmad_output: this function is called just after the frame is decoded
152  *****************************************************************************/
153 enum mad_flow libmad_output( void *p_data, struct mad_header const *p_header,
154                              struct mad_pcm *p_pcm )
155 {
156     mad_adec_thread_t * p_dec = (mad_adec_thread_t *) p_data;
157     aout_buffer_t *     p_buffer;
158     mad_fixed_t const * p_left = p_pcm->samples[0];
159     mad_fixed_t const * p_right = p_pcm->samples[1];
160     unsigned int        i_samples = p_pcm->length;
161     mad_fixed_t *       p_samples;
162     unsigned int        i_channels = (p_pcm->channels == 2) ?
163                                      AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT :
164                                      AOUT_CHAN_CENTER;
165
166     /* Creating the audio output fifo. Assume the samplerate and nr of channels
167      * from the first decoded frame is right for the entire audio track. */
168     if( (p_dec->p_aout_input != NULL) &&
169         (p_dec->output_format.i_rate != p_pcm->samplerate
170            || p_dec->output_format.i_physical_channels != i_channels) )
171     {
172         /* Parameters changed - this should not happen. */
173         aout_DecDelete( p_dec->p_aout, p_dec->p_aout_input );
174         p_dec->p_aout_input = NULL;
175     }
176
177     /* Creating the audio input if not created yet. */
178     if( p_dec->p_aout_input == NULL )
179     {
180         p_dec->output_format.i_rate = p_pcm->samplerate;
181         p_dec->output_format.i_physical_channels = i_channels;
182         p_dec->output_format.i_original_channels = i_channels;
183         aout_DateInit( &p_dec->end_date, p_pcm->samplerate );
184         p_dec->p_aout_input = aout_DecNew( p_dec->p_fifo,
185                                            &p_dec->p_aout,
186                                            &p_dec->output_format );
187
188         if ( p_dec->p_aout_input == NULL )
189         {
190             p_dec->p_fifo->b_error = VLC_TRUE;
191             return MAD_FLOW_BREAK;
192         }
193     }
194
195     if( p_dec->i_current_pts )
196     {
197         /* Set the Presentation Time Stamp */
198         if( p_dec->i_current_pts != aout_DateGet( &p_dec->end_date ) )
199         {
200             aout_DateSet( &p_dec->end_date, p_dec->i_current_pts );
201         }
202
203         p_dec->i_current_pts = 0;
204     }
205     else if( p_dec->i_next_pts )
206     {
207         /* No PTS this time, but it'll be for next frame */
208         p_dec->i_current_pts = p_dec->i_next_pts;
209         p_dec->i_next_pts = 0;
210     }
211
212     if( !aout_DateGet( &p_dec->end_date ) )
213     {
214         /* No date available yet, wait for the first PTS. */
215         return MAD_FLOW_CONTINUE;
216     }
217
218     p_buffer = aout_DecNewBuffer( p_dec->p_aout, p_dec->p_aout_input, i_samples );
219
220     if ( p_buffer == NULL )
221     {
222         msg_Err( p_dec->p_fifo, "allocating new buffer failed" );
223         return MAD_FLOW_BREAK;
224     }
225
226     p_buffer->start_date = aout_DateGet( &p_dec->end_date );
227     p_buffer->end_date = aout_DateIncrement( &p_dec->end_date, i_samples );
228
229     /* Interleave and keep buffers in mad_fixed_t format */
230     p_samples = (mad_fixed_t *)p_buffer->p_buffer;
231
232     switch( p_pcm->channels )
233     {
234     case 2:
235         while( i_samples-- )
236         {
237             *p_samples++ = *p_left++;
238             *p_samples++ = *p_right++;
239         }
240         break;
241
242     case 1:
243         p_dec->p_fifo->p_vlc->pf_memcpy( p_samples, p_left,
244                                          i_samples * sizeof(mad_fixed_t) );
245         break;
246
247     default:
248         msg_Err( p_dec->p_fifo, "cannot interleave %i channels",
249                                 p_pcm->channels );
250     }
251
252     aout_DecPlay( p_dec->p_aout, p_dec->p_aout_input, p_buffer );
253
254     return MAD_FLOW_CONTINUE;
255 }
256
257 /*****************************************************************************
258  * libmad_error: this function is called when an error occurs during decoding
259  *****************************************************************************/
260 enum mad_flow libmad_error( void *p_data, struct mad_stream *p_libmad_stream,
261                             struct mad_frame *p_libmad_frame )
262 {
263     mad_adec_thread_t *p_dec = (mad_adec_thread_t *) p_data;
264     enum mad_flow result;
265     struct mad_pcm *p_pcm;
266
267     switch (p_libmad_stream->error)
268     {             
269
270     case MAD_ERROR_BADDATAPTR:        /* bad main_data_begin pointer */
271         msg_Warn( p_dec->p_fifo, "lost synchronization" );
272
273         if( p_dec->output_format.i_rate &&
274             p_dec->output_format.i_physical_channels )
275         {
276             p_pcm = malloc( sizeof(struct mad_pcm) );
277             memset( p_pcm, 0, sizeof(struct mad_pcm) );
278             p_pcm->length = 32 * MAD_NSBSAMPLES( &p_libmad_frame->header );
279             p_pcm->channels = ( p_dec->output_format.i_physical_channels ==
280                                 AOUT_CHAN_CENTER ) ? 1 : 2;
281             p_pcm->samplerate = p_dec->output_format.i_rate;
282             libmad_output( p_data, NULL, p_pcm );
283             free( p_pcm );
284         }
285         result = MAD_FLOW_CONTINUE;
286         break;
287
288     default:
289         result = MAD_FLOW_CONTINUE;
290         break;
291
292 #if 0
293     case MAD_ERROR_BUFLEN:                /* input buffer too small (or EOF) */
294         msg_Err( p_dec->p_fifo, "input buffer too small (or EOF)" );
295         result = MAD_FLOW_CONTINUE;
296         break;
297     case MAD_ERROR_BUFPTR:                /* invalid (null) buffer pointer */
298         msg_Err( p_dec->p_fifo, "invalid (null) buffer pointer" );
299         result = MAD_FLOW_STOP;
300         break;
301     case MAD_ERROR_NOMEM:                 /* not enough memory */
302         msg_Err( p_dec->p_fifo, "invalid (null) buffer pointer" );
303         result = MAD_FLOW_STOP;
304         break;
305     case MAD_ERROR_LOSTSYNC:            /* lost synchronization */
306         msg_Err( p_dec->p_fifo, "lost synchronization" );
307         result = MAD_FLOW_CONTINUE;
308         break;
309     case MAD_ERROR_BADLAYER:            /* reserved header layer value */
310         msg_Err( p_dec->p_fifo, "reserved header layer value" );
311         result = MAD_FLOW_CONTINUE;
312         break;
313     case MAD_ERROR_BADBITRATE:        /* forbidden bitrate value */
314         msg_Err( p_dec->p_fifo, "forbidden bitrate value" );
315         result = MAD_FLOW_CONTINUE;
316         break;
317     case MAD_ERROR_BADSAMPLERATE: /* reserved sample frequency value */
318         msg_Err( p_dec->p_fifo, "reserved sample frequency value" );
319         result = MAD_FLOW_CONTINUE;
320         break;
321     case MAD_ERROR_BADEMPHASIS:     /* reserved emphasis value */
322         msg_Err( p_dec->p_fifo, "reserverd emphasis value" );
323         result = MAD_FLOW_CONTINUE;
324         break;
325     case MAD_ERROR_BADCRC:                /* CRC check failed */
326         msg_Err( p_dec->p_fifo, "CRC check failed" );
327         result = MAD_FLOW_CONTINUE;
328         break;
329     case MAD_ERROR_BADBITALLOC:     /* forbidden bit allocation value */
330         msg_Err( p_dec->p_fifo, "forbidden bit allocation value" );
331         result = MAD_FLOW_IGNORE;
332         break;
333     case MAD_ERROR_BADSCALEFACTOR:/* bad scalefactor index */
334         msg_Err( p_dec->p_fifo, "bad scalefactor index" );
335         result = MAD_FLOW_CONTINUE;
336         break;
337     case MAD_ERROR_BADFRAMELEN:     /* bad frame length */
338         msg_Err( p_dec->p_fifo, "bad frame length" );
339         result = MAD_FLOW_CONTINUE;
340         break;
341     case MAD_ERROR_BADBIGVALUES:    /* bad big_values count */
342         msg_Err( p_dec->p_fifo, "bad big values count" );
343         result = MAD_FLOW_IGNORE;
344         break;
345     case MAD_ERROR_BADBLOCKTYPE:    /* reserved block_type */
346         msg_Err( p_dec->p_fifo, "reserverd block_type" );
347         result = MAD_FLOW_IGNORE;
348         break;
349     case MAD_ERROR_BADSCFSI:            /* bad scalefactor selection info */
350         msg_Err( p_dec->p_fifo, "bad scalefactor selection info" );
351         result = MAD_FLOW_CONTINUE;
352         break;
353     case MAD_ERROR_BADDATAPTR:        /* bad main_data_begin pointer */
354         msg_Err( p_dec->p_fifo, "bad main_data_begin pointer" );
355         result = MAD_FLOW_CONTINUE;
356         break;
357     case MAD_ERROR_BADPART3LEN:     /* bad audio data length */
358         msg_Err( p_dec->p_fifo, "bad audio data length" );
359         result = MAD_FLOW_IGNORE;
360         break;
361     case MAD_ERROR_BADHUFFTABLE:    /* bad Huffman table select */
362         msg_Err( p_dec->p_fifo, "bad Huffman table select" );
363         result = MAD_FLOW_IGNORE;
364         break;
365     case MAD_ERROR_BADHUFFDATA:     /* Huffman data overrun */
366         msg_Err( p_dec->p_fifo, "Huffman data overrun" );
367         result = MAD_FLOW_IGNORE;
368         break;
369     case MAD_ERROR_BADSTEREO:         /* incompatible block_type for JS */
370         msg_Err( p_dec->p_fifo, "incompatible block_type for JS" );
371         result = MAD_FLOW_IGNORE;
372         break;
373     default:
374         msg_Err( p_dec->p_fifo, "unknown error occured stopping decoder" );
375         result = MAD_FLOW_STOP;
376         break;
377 #endif
378     }
379     
380     return (MAD_RECOVERABLE(p_libmad_stream->error)? result: MAD_FLOW_STOP);
381 }
382
383 /*****************************************************************************
384  * libmad_message: this function is called to send a message
385  *****************************************************************************/
386 /* enum mad_flow libmad_message(void *, void*, unsigned int*)
387  * {
388  *     return MAD_FLOW_CONTINUE;
389  * }
390  */
391
392
393
394 /****************************************************************************
395  * Print human readable informations about an audio MPEG frame.
396  ****************************************************************************/
397 static void PrintFrameInfo(struct mad_header *Header)
398 {
399         const char      *Layer,
400                         *Mode,
401                         *Emphasis;
402
403         /* Convert the layer number to its printed representation. */
404         switch(Header->layer)
405         {
406                 case MAD_LAYER_I:
407                         Layer="I";
408                         break;
409                 case MAD_LAYER_II:
410                         Layer="II";
411                         break;
412                 case MAD_LAYER_III:
413                         Layer="III";
414                         break;
415                 default:
416                         Layer="(unexpected layer value)";
417                         break;
418         }
419
420         /* Convert the audio mode to its printed representation. */
421         switch(Header->mode)
422         {
423                 case MAD_MODE_SINGLE_CHANNEL:
424                         Mode="single channel";
425                         break;
426                 case MAD_MODE_DUAL_CHANNEL:
427                         Mode="dual channel";
428                         break;
429                 case MAD_MODE_JOINT_STEREO:
430                         Mode="joint (MS/intensity) stereo";
431                         break;
432                 case MAD_MODE_STEREO:
433                         Mode="normal LR stereo";
434                         break;
435                 default:
436                         Mode="(unexpected mode value)";
437                         break;
438         }
439
440         /* Convert the emphasis to its printed representation. */
441         switch(Header->emphasis)
442         {
443                 case MAD_EMPHASIS_NONE:
444                         Emphasis="no";
445                         break;
446                 case MAD_EMPHASIS_50_15_US:
447                         Emphasis="50/15 us";
448                         break;
449                 case MAD_EMPHASIS_CCITT_J_17:
450                         Emphasis="CCITT J.17";
451                         break;
452                 default:
453                         Emphasis="(unexpected emphasis value)";
454                         break;
455         }
456
457 //X     msg_Err("statistics: %lu kb/s audio mpeg layer %s stream %s crc, "
458 //X                     "%s with %s emphasis at %d Hz sample rate\n",
459 //X                     Header->bitrate,Layer,
460 //X                     Header->flags&MAD_FLAG_PROTECTION?"with":"without",
461 //X                     Mode,Emphasis,Header->samplerate);
462 }