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