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