]> git.sesse.net Git - vlc/blob - plugins/mad/mad_libmad.c
* ./plugins/mad/mad_libmad.c: prevent the MAD decoder from looping endlessly
[vlc] / plugins / mad / mad_libmad.c
1 /***************************************************************************
2            mad_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 "mad_adec.h"
36 #include "mad_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 *data, struct mad_stream *p_libmad_stream)
45 {
46     mad_adec_thread_t *p_mad_adec = (mad_adec_thread_t *) data;
47     size_t             ReadSize, Remaining;
48     unsigned char     *ReadStart;
49
50     if ( p_mad_adec->p_fifo->b_die == 1 ) {
51         msg_Dbg( p_mad_adec->p_fifo, "libmad_input stopping libmad decoder" );
52         return MAD_FLOW_STOP;
53     }
54
55     if ( p_mad_adec->p_fifo->b_error == 1 ) {
56         msg_Warn( p_mad_adec->p_fifo, "libmad_input ignoring current audio frame" );
57         return MAD_FLOW_IGNORE;
58     }
59
60     /* libmad_stream_buffer does not consume the total buffer, it consumes only data
61      * for one frame only. So all data left in the buffer should be put back in front.
62      */
63     if ((p_libmad_stream->buffer==NULL) || (p_libmad_stream->error==MAD_ERROR_BUFLEN))
64     {
65         /* libmad does not consume all the buffer it's given. Some
66          * datas, part of a truncated frame, is left unused at the
67          * end of the buffer. Those datas must be put back at the
68          * beginning of the buffer and taken in account for
69          * refilling the buffer. This means that the input buffer
70          * must be large enough to hold a complete frame at the
71          * highest observable bit-rate (currently 448 kb/s). XXX=XXX
72          * Is 2016 bytes the size of the largest frame?
73          * (448000*(1152/32000))/8
74          */
75         if(p_libmad_stream->next_frame!=NULL)
76         {
77             Remaining=p_libmad_stream->bufend-p_libmad_stream->next_frame;
78             if( p_mad_adec->buffer != p_libmad_stream->next_frame )
79             {
80                 p_mad_adec->p_fifo->p_vlc->pf_memcpy( p_mad_adec->buffer,
81                                     p_libmad_stream->next_frame, Remaining );
82             }
83             ReadStart=p_mad_adec->buffer+Remaining;
84             ReadSize=(MAD_BUFFER_MDLEN)-Remaining;
85
86             /* Store time stamp of next frame */
87             p_mad_adec->i_current_pts = p_mad_adec->i_next_pts;
88             p_mad_adec->i_next_pts = p_mad_adec->p_fifo->p_first->i_pts;
89         }
90         else
91         {
92             ReadSize=(MAD_BUFFER_MDLEN);
93             ReadStart=p_mad_adec->buffer;
94             Remaining=0;
95             p_mad_adec->i_next_pts = 0;
96             p_mad_adec->i_current_pts = p_mad_adec->p_fifo->p_first->i_pts;
97         }
98
99         /* Fill-in the buffer. If an error occurs print a message
100          * and leave the decoding loop. If the end of stream is
101          * reached we also leave the loop but the return status is
102          * left untouched.
103          */
104         if( ReadSize > p_mad_adec->p_data->p_payload_end
105                         - p_mad_adec->p_data->p_payload_start )
106         {
107             ReadSize = p_mad_adec->p_data->p_payload_end
108                         - p_mad_adec->p_data->p_payload_start;
109             p_mad_adec->p_fifo->p_vlc->pf_memcpy( ReadStart,
110                                 p_mad_adec->p_data->p_payload_start, ReadSize );
111             NextDataPacket( p_mad_adec->p_fifo, &p_mad_adec->p_data );
112         }
113         else
114         {
115             p_mad_adec->p_fifo->p_vlc->pf_memcpy( ReadStart,
116                          p_mad_adec->p_data->p_payload_start, ReadSize );
117             p_mad_adec->p_data->p_payload_start += ReadSize;
118         }
119
120         if ( p_mad_adec->p_fifo->b_die == 1 )
121         {
122             msg_Dbg( p_mad_adec->p_fifo, "libmad_input stopping libmad decoder" );
123             return MAD_FLOW_STOP;
124         }
125
126         if ( p_mad_adec->p_fifo->b_error == 1 )
127         {
128             msg_Warn( p_mad_adec->p_fifo, "libmad_input ignoring current audio frame" );    
129             return MAD_FLOW_IGNORE;
130         }
131
132         /* Pipe the new buffer content to libmad's stream decoder facility.
133          * Libmad never copies the buffer, but just references it. So keep it in
134          * mad_adec_thread_t structure.
135          */
136         mad_stream_buffer(p_libmad_stream,(unsigned char*) &p_mad_adec->buffer,
137                           Remaining + ReadSize);
138         p_libmad_stream->error=0;
139     }
140
141     return MAD_FLOW_CONTINUE;
142 }
143
144 /*****************************************************************************
145  * libmad_header: this function is called just after the header of a frame is
146  * decoded
147  *****************************************************************************/
148 /*
149  *enum mad_flow libmad_header(void *data, struct mad_header const *p_libmad_header)
150  *{
151  *   mad_adec_thread_t *p_mad_adec = (mad_adec_thread_t *) data;
152  *
153  *   msg_Err( p_mad_adec->p_fifo, "libmad_header samplerate %d", p_libmad_header->samplerate);
154  *
155  *   PrintFrameInfo(p_limad_mad_header)
156  *   return MAD_FLOW_CONTINUE;
157  *}
158  */
159
160 /*****************************************************************************
161  * lib_mad_filter: this function is called to filter data of a frame
162  *****************************************************************************/
163 /* enum mad_flow libmad_filter(void *data, struct mad_stream const *p_libmad_stream, struct mad_frame *p_libmad_frame)
164  * {
165  *      return MAD_FLOW_CONTINUE;
166  * }
167  */
168
169 /*****************************************************************************
170  * support routines borrowed from mpg321 (file: mad.c), which is distributed
171  * under GPL license
172  *
173  * mpg321 was written by Joe Drew <drew@debian.org>, and based upon 'plaympeg'
174  * from the smpeg sources, which was written by various people from Loki Software
175  * (http://www.lokigames.com).
176  *
177  * It also incorporates some source from mad, written by Robert Leslie
178  *****************************************************************************/
179
180 /* The following two routines and data structure are from the ever-brilliant
181      Rob Leslie.
182 */
183
184 struct audio_dither {
185     mad_fixed_t error[3];
186     mad_fixed_t random;
187 };
188
189 /*
190 * NAME:                prng()
191 * DESCRIPTION: 32-bit pseudo-random number generator
192 */
193 static inline unsigned long prng(unsigned long state)
194 {
195     return (state * 0x0019660dL + 0x3c6ef35fL) & 0xffffffffL;
196 }
197
198 /*
199 * NAME:        mpg321_s24_to_s16_pcm()
200 * DESCRIPTION: generic linear sample quantize and dither routine
201 */
202 static inline signed int mpg321_s24_to_s16_pcm(unsigned int bits, mad_fixed_t sample,
203                                     struct audio_dither *dither)
204 {
205     unsigned int scalebits;
206     mad_fixed_t output, mask, random;
207
208     enum {
209         MIN = -MAD_F_ONE,
210         MAX = MAD_F_ONE - 1
211     };
212
213     /* noise shape */
214     sample += dither->error[0] - dither->error[1] + dither->error[2];
215
216     dither->error[2] = dither->error[1];
217     dither->error[1] = dither->error[0] / 2;
218
219     /* bias */
220     output = sample + (1L << (MAD_F_FRACBITS + 1 - bits - 1));
221
222     scalebits = MAD_F_FRACBITS + 1 - bits;
223     mask = (1L << scalebits) - 1;
224
225     /* dither */
226     random    = prng(dither->random);
227     output += (random & mask) - (dither->random & mask);
228
229     dither->random = random;
230
231     /* clip */
232     if (output > MAX) {
233         output = MAX;
234
235         if (sample > MAX)
236             sample = MAX;
237     }
238     else if (output < MIN) {
239         output = MIN;
240
241         if (sample < MIN)
242             sample = MIN;
243     }
244
245     /* quantize */
246     output &= ~mask;
247
248     /* error feedback */
249     dither->error[0] = sample - output;
250
251     /* scale */
252     return output >> scalebits;
253 }
254
255 /*****************************************************************************
256  * s24_to_s16_pcm: Scale a 24 bit pcm sample to a 16 bit pcm sample.
257  *****************************************************************************/
258 static inline mad_fixed_t s24_to_s16_pcm(mad_fixed_t sample)
259 {
260   /* round */
261   sample += (1L << (MAD_F_FRACBITS - 16));
262
263   /* clip */
264   if (sample >= MAD_F_ONE)
265     sample = MAD_F_ONE - 1;
266   else if (sample < -MAD_F_ONE)
267     sample = -MAD_F_ONE;
268
269   /* quantize */
270   return sample >> (MAD_F_FRACBITS + 1 - 16);
271 }
272
273 /*****************************************************************************
274  * libmad_ouput: this function is called just after the frame is decoded
275  *****************************************************************************/
276 enum mad_flow libmad_output(void *data, struct mad_header const *p_libmad_header, struct mad_pcm *p_libmad_pcm)
277 {
278     mad_adec_thread_t *p_mad_adec= (mad_adec_thread_t *) data;
279     byte_t *buffer=NULL;
280     mad_fixed_t const *left_ch = p_libmad_pcm->samples[0], *right_ch = p_libmad_pcm->samples[1];
281     register int nsamples = p_libmad_pcm->length;
282     mad_fixed_t sample;
283     static struct audio_dither dither;
284
285     /* Creating the audio output fifo.
286      * Assume the samplerate and nr of channels from the first decoded frame is right for the entire audio track.
287      */
288     if (p_mad_adec->p_aout_fifo==NULL)
289     {
290         p_mad_adec->p_aout_fifo = aout_CreateFifo(
291                 p_mad_adec->p_fifo,
292                 AOUT_FIFO_PCM,              /* fifo type */
293                 2, /*p_libmad_pcm->channels,*/     /* nr. of channels */
294                 p_libmad_pcm->samplerate,   /* frame rate in Hz ?*/
295                 p_libmad_pcm->length*2,     /* length of output buffer *2 channels*/
296                 NULL  );                    /* buffer */
297
298         if ( p_mad_adec->p_aout_fifo == NULL )
299         {
300                 return MAD_FLOW_BREAK;
301         }
302
303         msg_Dbg( p_mad_adec->p_fifo, "aout fifo created");
304     }
305
306     if (p_mad_adec->p_aout_fifo->i_rate != p_libmad_pcm->samplerate)
307     {
308         msg_Warn( p_mad_adec->p_fifo, "samplerate is changing from [%d] Hz "
309                   "to [%d] Hz, sample size [%d], error_code [%0x]",
310                   p_mad_adec->p_aout_fifo->i_rate, p_libmad_pcm->samplerate,
311                   p_libmad_pcm->length,
312                   p_mad_adec->libmad_decoder->sync->stream.error );
313         p_mad_adec->p_aout_fifo->i_rate = p_libmad_pcm->samplerate;
314     }
315
316     if( p_mad_adec->i_current_pts )
317     {
318         p_mad_adec->p_aout_fifo->date[p_mad_adec->p_aout_fifo->i_end_frame]
319                 = p_mad_adec->i_current_pts;
320     }
321     else
322     {
323         p_mad_adec->p_aout_fifo->date[p_mad_adec->p_aout_fifo->i_end_frame]
324                 = LAST_MDATE;
325     }
326 //    mad_timer_add(&p_mad_adec->libmad_timer,p_libmad_header->duration);
327
328     buffer = ((byte_t *)p_mad_adec->p_aout_fifo->buffer) + (p_mad_adec->p_aout_fifo->i_end_frame * (p_libmad_pcm->length*4));
329
330     while (nsamples--)
331     {
332         switch (p_mad_adec->audio_scaling)
333         {
334           case MPG321_SCALING:
335                sample = mpg321_s24_to_s16_pcm(16, *left_ch++, &dither);
336           break;
337           case FAST_SCALING: /* intended fall through */
338           default:
339                sample = s24_to_s16_pcm(*left_ch++);
340           break;
341                           }
342
343         /* left audio channel */
344 #ifndef WORDS_BIGENDIAN
345         *buffer++ = (byte_t) (sample >> 0);
346         *buffer++ = (byte_t) (sample >> 8);
347 #else
348           *buffer++ = (byte_t) (sample >> 8);
349           *buffer++ = (byte_t) (sample >> 0);
350 #endif
351         if (p_libmad_pcm->channels == 2)
352         {
353             /* right audio channel */
354             switch (p_mad_adec->audio_scaling)
355             {
356               case MPG321_SCALING:
357                    sample = mpg321_s24_to_s16_pcm(16, *right_ch++, &dither);
358               break;
359               case FAST_SCALING: /* intended fall through */
360               default:
361                    sample = s24_to_s16_pcm(*right_ch++);
362               break;
363                           }
364         }
365         /* else reuse left_ch */
366 #ifndef WORDS_BIGENDIAN
367         *buffer++ = (byte_t) (sample >> 0);
368         *buffer++ = (byte_t) (sample >> 8);
369 #else
370         *buffer++ = (byte_t) (sample >> 8);
371         *buffer++ = (byte_t) (sample >> 0);
372 #endif                                          
373     }
374
375     /* DEBUG */
376     /*
377     if (p_libmad_pcm->channels == 1) {
378        msg_Dbg( p_mad_adec->p_fifo, "libmad_output channels [%d]", p_libmad_pcm->channels);
379     }
380     */
381
382     vlc_mutex_lock (&p_mad_adec->p_aout_fifo->data_lock);
383     p_mad_adec->p_aout_fifo->i_end_frame = (p_mad_adec->p_aout_fifo->i_end_frame + 1) & AOUT_FIFO_SIZE;
384     vlc_cond_signal (&p_mad_adec->p_aout_fifo->data_wait);
385     vlc_mutex_unlock (&p_mad_adec->p_aout_fifo->data_lock);
386
387     return MAD_FLOW_CONTINUE;
388 }
389
390 /*****************************************************************************
391  * libmad_error: this function is called when an error occurs during decoding
392  *****************************************************************************/
393 enum mad_flow libmad_error(void *data, struct mad_stream *p_libmad_stream, struct mad_frame *p_libmad_frame)
394 {
395     enum mad_flow result = MAD_FLOW_CONTINUE;
396
397     switch (p_libmad_stream->error)
398     {             
399     case MAD_ERROR_BUFLEN:                /* input buffer too small (or EOF) */
400 //X        intf_ErrMsg("libmad error: input buffer too small (or EOF)");
401         result = MAD_FLOW_CONTINUE;
402         break;
403     case MAD_ERROR_BUFPTR:                /* invalid (null) buffer pointer */
404 //X        intf_ErrMsg("libmad error: invalid (null) buffer pointer");
405         result = MAD_FLOW_STOP;
406         break;
407     case MAD_ERROR_NOMEM:                 /* not enough memory */
408 //X        intf_ErrMsg("libmad error: invalid (null) buffer pointer");
409         result = MAD_FLOW_STOP;
410         break;
411     case MAD_ERROR_LOSTSYNC:            /* lost synchronization */
412 //X        intf_ErrMsg("libmad error: lost synchronization");
413         mad_stream_sync(p_libmad_stream);
414         result = MAD_FLOW_CONTINUE;
415         break;
416     case MAD_ERROR_BADLAYER:            /* reserved header layer value */
417 //X        intf_ErrMsg("libmad error: reserved header layer value");
418         result = MAD_FLOW_CONTINUE;
419         break;
420     case MAD_ERROR_BADBITRATE:        /* forbidden bitrate value */
421 //X        intf_ErrMsg("libmad error: forbidden bitrate value");
422         result = MAD_FLOW_CONTINUE;
423         break;
424     case MAD_ERROR_BADSAMPLERATE: /* reserved sample frequency value */
425 //X        intf_ErrMsg("libmad error: reserved sample frequency value");
426         result = MAD_FLOW_CONTINUE;
427         break;
428     case MAD_ERROR_BADEMPHASIS:     /* reserved emphasis value */
429 //X        intf_ErrMsg("libmad error: reserverd emphasis value");
430         result = MAD_FLOW_CONTINUE;
431         break;
432     case MAD_ERROR_BADCRC:                /* CRC check failed */
433 //X        intf_ErrMsg("libmad error: CRC check failed");
434         result = MAD_FLOW_CONTINUE;
435         break;
436     case MAD_ERROR_BADBITALLOC:     /* forbidden bit allocation value */
437 //X        intf_ErrMsg("libmad error: forbidden bit allocation value");
438         result = MAD_FLOW_IGNORE;
439         break;
440     case MAD_ERROR_BADSCALEFACTOR:/* bad scalefactor index */
441 //X        intf_ErrMsg("libmad error: bad scalefactor index");
442         result = MAD_FLOW_CONTINUE;
443         break;
444     case MAD_ERROR_BADFRAMELEN:     /* bad frame length */
445 //X        intf_ErrMsg("libmad error: bad frame length");
446         result = MAD_FLOW_CONTINUE;
447         break;
448     case MAD_ERROR_BADBIGVALUES:    /* bad big_values count */
449 //X        intf_ErrMsg("libmad error: bad big values count");
450         result = MAD_FLOW_IGNORE;
451         break;
452     case MAD_ERROR_BADBLOCKTYPE:    /* reserved block_type */
453 //X        intf_ErrMsg("libmad error: reserverd block_type");
454         result = MAD_FLOW_IGNORE;
455         break;
456     case MAD_ERROR_BADSCFSI:            /* bad scalefactor selection info */
457 //X        intf_ErrMsg("libmad error: bad scalefactor selection info");
458         result = MAD_FLOW_CONTINUE;
459         break;
460     case MAD_ERROR_BADDATAPTR:        /* bad main_data_begin pointer */
461 //X        intf_ErrMsg("libmad error: bad main_data_begin pointer");
462         result = MAD_FLOW_STOP;
463         break;
464     case MAD_ERROR_BADPART3LEN:     /* bad audio data length */
465 //X        intf_ErrMsg("libmad error: bad audio data length");
466         result = MAD_FLOW_IGNORE;
467         break;
468     case MAD_ERROR_BADHUFFTABLE:    /* bad Huffman table select */
469 //X        intf_ErrMsg("libmad error: bad Huffman table select");
470         result = MAD_FLOW_IGNORE;
471         break;
472     case MAD_ERROR_BADHUFFDATA:     /* Huffman data overrun */
473 //X        intf_ErrMsg("libmad error: Huffman data overrun");
474         result = MAD_FLOW_IGNORE;
475         break;
476     case MAD_ERROR_BADSTEREO:         /* incompatible block_type for JS */
477 //X        intf_ErrMsg("libmad error: incompatible block_type for JS");
478         result = MAD_FLOW_IGNORE;
479         break;
480     default:
481 //X        intf_ErrMsg("libmad error: unknown error occured stopping decoder");
482         result = MAD_FLOW_STOP;
483         break;
484     }
485     
486     return (MAD_RECOVERABLE(p_libmad_stream->error)? result: MAD_FLOW_STOP);
487     //return (MAD_FLOW_CONTINUE);
488 }
489
490 /*****************************************************************************
491  * libmad_message: this function is called to send a message
492  *****************************************************************************/
493 /* enum mad_flow libmad_message(void *, void*, unsigned int*)
494  * {
495  *     return MAD_FLOW_CONTINUE;
496  * }
497  */
498
499
500
501 /****************************************************************************
502  * Print human readable informations about an audio MPEG frame.                         *
503  ****************************************************************************/
504 static void PrintFrameInfo(struct mad_header *Header)
505 {
506         const char      *Layer,
507                         *Mode,
508                         *Emphasis;
509
510         /* Convert the layer number to it's printed representation. */
511         switch(Header->layer)
512         {
513                 case MAD_LAYER_I:
514                         Layer="I";
515                         break;
516                 case MAD_LAYER_II:
517                         Layer="II";
518                         break;
519                 case MAD_LAYER_III:
520                         Layer="III";
521                         break;
522                 default:
523                         Layer="(unexpected layer value)";
524                         break;
525         }
526
527         /* Convert the audio mode to it's printed representation. */
528         switch(Header->mode)
529         {
530                 case MAD_MODE_SINGLE_CHANNEL:
531                         Mode="single channel";
532                         break;
533                 case MAD_MODE_DUAL_CHANNEL:
534                         Mode="dual channel";
535                         break;
536                 case MAD_MODE_JOINT_STEREO:
537                         Mode="joint (MS/intensity) stereo";
538                         break;
539                 case MAD_MODE_STEREO:
540                         Mode="normal LR stereo";
541                         break;
542                 default:
543                         Mode="(unexpected mode value)";
544                         break;
545         }
546
547         /* Convert the emphasis to it's printed representation. */
548         switch(Header->emphasis)
549         {
550                 case MAD_EMPHASIS_NONE:
551                         Emphasis="no";
552                         break;
553                 case MAD_EMPHASIS_50_15_US:
554                         Emphasis="50/15 us";
555                         break;
556                 case MAD_EMPHASIS_CCITT_J_17:
557                         Emphasis="CCITT J.17";
558                         break;
559                 default:
560                         Emphasis="(unexpected emphasis value)";
561                         break;
562         }
563
564 //X     intf_ErrMsg("statistics: %lu kb/s audio mpeg layer %s stream %s crc, "
565 //X                     "%s with %s emphasis at %d Hz sample rate\n",
566 //X                     Header->bitrate,Layer,
567 //X                     Header->flags&MAD_FLAG_PROTECTION?"with":"without",
568 //X                     Mode,Emphasis,Header->samplerate);
569 }