* Fixed MPEG audio layer III VBR,
[vlc.git] / modules / codec / mpeg_audio.c
1 /*****************************************************************************
2  * mpeg_audio.c: parse MPEG audio sync info and packetize the stream
3  *****************************************************************************
4  * Copyright (C) 2001-2003 VideoLAN
5  * $Id: mpeg_audio.c,v 1.4 2003/01/15 23:55:22 massiot Exp $
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *          Eric Petit <titer@videolan.org>
9  *          Christophe Massiot <massiot@via.ecp.fr>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
24  *****************************************************************************/
25
26 /*****************************************************************************
27  * Preamble
28  *****************************************************************************/
29 #include <stdlib.h>                                      /* malloc(), free() */
30 #include <string.h>                                              /* strdup() */
31
32 #include <vlc/vlc.h>
33 #include <vlc/aout.h>
34 #include <vlc/decoder.h>
35
36 /*****************************************************************************
37  * dec_thread_t : decoder thread descriptor
38  *****************************************************************************/
39 typedef struct dec_thread_t
40 {
41     /*
42      * Thread properties
43      */
44     vlc_thread_t        thread_id;                /* id for thread functions */
45
46     /*
47      * Input properties
48      */
49     decoder_fifo_t *    p_fifo;                /* stores the PES stream data */
50     bit_stream_t        bit_stream;
51
52     /*
53      * Output properties
54      */
55     aout_instance_t *   p_aout; /* opaque */
56     aout_input_t *      p_aout_input; /* opaque */
57     audio_sample_format_t output_format;
58 } dec_thread_t;
59
60 #define MAX_FRAME_SIZE (511 + 2048)
61 /* This isn't the place to put mad-specific stuff. However, it makes the
62  * mad plug-in's life much easier if we put 8 extra bytes at the end of the
63  * buffer, because that way it doesn't have to copy the aout_buffer_t to a
64  * bigger buffer. This has no implication on other plug-ins, and we only
65  * lose 8 bytes per frame. --Meuuh */
66 #define MAD_BUFFER_GUARD 8
67
68
69 /****************************************************************************
70  * Local prototypes
71  ****************************************************************************/
72 static int  Open           ( vlc_object_t * );
73 static int  RunDecoder     ( decoder_fifo_t * );
74
75 static void EndThread      ( dec_thread_t * );
76
77 static int SyncInfo( uint32_t i_header, unsigned int * pi_channels,
78                      unsigned int * pi_sample_rate, unsigned int * pi_bit_rate,
79                      unsigned int * pi_frame_length,
80                      unsigned int * pi_current_frame_length,
81                      unsigned int * pi_layer );
82
83 /*****************************************************************************
84  * Module descriptor
85  *****************************************************************************/
86 vlc_module_begin();
87     set_description( _("MPEG audio layer I/II/III parser") );
88     set_capability( "decoder", 100 );
89     set_callbacks( Open, NULL );
90 vlc_module_end();
91
92 /*****************************************************************************
93  * OpenDecoder: probe the decoder and return score
94  *****************************************************************************/
95 static int Open( vlc_object_t *p_this )
96 {
97     decoder_fifo_t *p_fifo = (decoder_fifo_t*) p_this;
98
99     if( p_fifo->i_fourcc != VLC_FOURCC( 'm', 'p', 'g', 'a') )
100     {
101         return VLC_EGENERIC;
102     }
103
104     p_fifo->pf_run = RunDecoder;
105     return VLC_SUCCESS;
106 }
107
108 /*****************************************************************************
109  * RunDecoder: this function is called just after the thread is created
110  *****************************************************************************/
111 static int RunDecoder( decoder_fifo_t *p_fifo )
112 {
113     dec_thread_t * p_dec;
114     audio_date_t end_date;
115     unsigned int i_layer = 0;
116     byte_t p_sync[MAD_BUFFER_GUARD];
117     mtime_t pts;
118
119     /* Allocate the memory needed to store the thread's structure */
120     p_dec = malloc( sizeof(dec_thread_t) );
121     if( p_dec == NULL )
122     {
123         msg_Err( p_fifo, "out of memory" );
124         DecoderError( p_fifo );
125         return -1;
126     }
127
128     /* Initialize the thread properties */
129     p_dec->p_aout = NULL;
130     p_dec->p_aout_input = NULL;
131     p_dec->p_fifo = p_fifo;
132
133     aout_DateSet( &end_date, 0 );
134
135     /* Init the bitstream */
136     if( InitBitstream( &p_dec->bit_stream, p_dec->p_fifo,
137                        NULL, NULL ) != VLC_SUCCESS )
138     {
139         msg_Err( p_fifo, "cannot initialize bitstream" );
140         DecoderError( p_fifo );
141         free( p_dec );
142         return -1;
143     }
144
145     /* Init sync buffer. */
146     NextPTS( &p_dec->bit_stream, &pts, NULL );
147     GetChunk( &p_dec->bit_stream, p_sync, MAD_BUFFER_GUARD );
148
149     /* Decoder thread's main loop */
150     while ( !p_dec->p_fifo->b_die && !p_dec->p_fifo->b_error )
151     {
152         int i_bit_rate;
153         unsigned int i_rate, i_original_channels, i_frame_size, i_frame_length;
154         unsigned int i_new_layer, i_current_frame_size;
155         uint32_t i_header;
156         aout_buffer_t * p_buffer;
157         int i;
158
159         /* Look for sync word - should be 0xffe */
160         if ( (p_sync[0] != 0xff) || ((p_sync[1] & 0xe0) != 0xe0) )
161         {
162             msg_Warn( p_dec->p_fifo, "no sync - skipping" );
163             /* Look inside the sync buffer. */
164             for ( i = 1; i < MAD_BUFFER_GUARD - 1; i++ )
165             {
166                 if ( (p_sync[i] == 0xff) && ((p_sync[i + 1] & 0xe0) != 0xe0) )
167                     break;
168             }
169             if ( i < MAD_BUFFER_GUARD - 1 )
170             {
171                 /* Found it ! */
172                 memmove( p_sync, &p_sync[i], MAD_BUFFER_GUARD - i );
173                 GetChunk( &p_dec->bit_stream, &p_sync[MAD_BUFFER_GUARD - i],
174                           i );
175             }
176             else
177             {
178                 if ( p_sync[MAD_BUFFER_GUARD - 1] == 0xff
179                       && ShowBits( &p_dec->bit_stream, 3 ) == 0x3 )
180                 {
181                     /* Found it ! */
182                     p_sync[0] = p_sync[MAD_BUFFER_GUARD - 1];
183                     GetChunk( &p_dec->bit_stream,
184                               &p_sync[1], MAD_BUFFER_GUARD - 1 );
185                 }
186                 else
187                 {
188                     /* Scan the stream. */
189                     while ( ShowBits( &p_dec->bit_stream, 11 ) != 0x07ff &&
190                             (!p_dec->p_fifo->b_die) &&
191                             (!p_dec->p_fifo->b_error) )
192                     {
193                         RemoveBits( &p_dec->bit_stream, 8 );
194                     }
195                     if ( p_dec->p_fifo->b_die || p_dec->p_fifo->b_error )
196                         break;
197                     GetChunk( &p_dec->bit_stream,p_sync, MAD_BUFFER_GUARD );
198                 }
199             }
200         }
201         if ( p_dec->p_fifo->b_die || p_dec->p_fifo->b_error ) break;
202
203         /* Set the Presentation Time Stamp */
204         if ( pts != 0 && pts != aout_DateGet( &end_date ) )
205         {
206             aout_DateSet( &end_date, pts );
207         }
208
209         /* Get frame header */
210         i_header = (p_sync[0] << 24) | (p_sync[1] << 16) | (p_sync[2] << 8)
211                      | p_sync[3];
212
213         /* Check if frame is valid and get frame info */
214         i_current_frame_size = SyncInfo( i_header,
215                                          &i_original_channels, &i_rate,
216                                          &i_bit_rate, &i_frame_length,
217                                          &i_frame_size, &i_new_layer );
218
219         if ( !i_current_frame_size )
220         {
221             msg_Warn( p_dec->p_fifo, "syncinfo failed" );
222             /* This is probably an emulated startcode, drop the first byte
223              * to force looking for the next startcode. */
224             memmove( p_sync, &p_sync[1], MAD_BUFFER_GUARD - 1 );
225             p_sync[MAD_BUFFER_GUARD - 1] = GetBits( &p_dec->bit_stream, 8 );
226             continue;
227         }
228         if ( i_current_frame_size > i_frame_size )
229         {
230             msg_Warn( p_dec->p_fifo, "frame too big %d > %d",
231                       i_current_frame_size, i_frame_size );
232             memmove( p_sync, &p_sync[1], MAD_BUFFER_GUARD - 1 );
233             p_sync[MAD_BUFFER_GUARD - 1] = GetBits( &p_dec->bit_stream, 8 );
234             continue;
235         }
236
237         if( (p_dec->p_aout_input != NULL) &&
238             ( (p_dec->output_format.i_rate != i_rate)
239                 || (p_dec->output_format.i_original_channels
240                       != i_original_channels)
241                 || (p_dec->output_format.i_bytes_per_frame
242                       != i_frame_size + MAD_BUFFER_GUARD)
243                 || (p_dec->output_format.i_frame_length != i_frame_length)
244                 || (i_layer != i_new_layer) ) )
245         {
246             /* Parameters changed - this should not happen. */
247             aout_DecDelete( p_dec->p_aout, p_dec->p_aout_input );
248             p_dec->p_aout_input = NULL;
249         }
250
251         /* Creating the audio input if not created yet. */
252         if( p_dec->p_aout_input == NULL )
253         {
254             i_layer = i_new_layer;
255             if ( i_layer == 3 )
256             {
257                 p_dec->output_format.i_format = VLC_FOURCC('m','p','g','3');
258             }
259             else
260             {
261                 p_dec->output_format.i_format = VLC_FOURCC('m','p','g','a');
262             }
263             p_dec->output_format.i_rate = i_rate;
264             p_dec->output_format.i_original_channels = i_original_channels;
265             p_dec->output_format.i_physical_channels
266                        = i_original_channels & AOUT_CHAN_PHYSMASK;
267             p_dec->output_format.i_bytes_per_frame = i_frame_size
268                                                         + MAD_BUFFER_GUARD;
269             p_dec->output_format.i_frame_length = i_frame_length;
270             aout_DateInit( &end_date, i_rate );
271             p_dec->p_aout_input = aout_DecNew( p_dec->p_fifo,
272                                                &p_dec->p_aout,
273                                                &p_dec->output_format );
274
275             if ( p_dec->p_aout_input == NULL )
276             {
277                 p_dec->p_fifo->b_error = 1;
278                 break;
279             }
280         }
281
282         if ( !aout_DateGet( &end_date ) )
283         {
284             byte_t p_junk[MAX_FRAME_SIZE];
285
286             /* We've just started the stream, wait for the first PTS. */
287             GetChunk( &p_dec->bit_stream, p_junk, i_current_frame_size );
288             memcpy( p_sync, &p_junk[i_current_frame_size - MAD_BUFFER_GUARD],
289                     MAD_BUFFER_GUARD );
290             continue;
291         }
292
293         p_buffer = aout_DecNewBuffer( p_dec->p_aout, p_dec->p_aout_input,
294                                       i_frame_length );
295         if ( p_buffer == NULL )
296         {
297             p_dec->p_fifo->b_error = 1;
298             break;
299         }
300         p_buffer->start_date = aout_DateGet( &end_date );
301         p_buffer->end_date = aout_DateIncrement( &end_date,
302                                                  i_frame_length );
303
304         /* Get the whole frame. */
305         memcpy( p_buffer->p_buffer, p_sync, MAD_BUFFER_GUARD );
306         GetChunk( &p_dec->bit_stream, p_buffer->p_buffer + MAD_BUFFER_GUARD,
307                   i_current_frame_size - MAD_BUFFER_GUARD );
308         if( p_dec->p_fifo->b_die )
309         {
310             aout_DecDeleteBuffer( p_dec->p_aout, p_dec->p_aout_input,
311                                   p_buffer );
312             break;
313         }
314         /* Get beginning of next frame. */
315         NextPTS( &p_dec->bit_stream, &pts, NULL );
316         GetChunk( &p_dec->bit_stream, p_buffer->p_buffer + i_current_frame_size,
317                   MAD_BUFFER_GUARD );
318         memcpy( p_sync, p_buffer->p_buffer + i_current_frame_size,
319                 MAD_BUFFER_GUARD );
320
321         p_buffer->i_nb_bytes = i_current_frame_size + MAD_BUFFER_GUARD;
322
323         /* Send the buffer to the aout core. */
324         aout_DecPlay( p_dec->p_aout, p_dec->p_aout_input, p_buffer );
325     }
326
327     if( p_dec->p_fifo->b_error )
328     {
329         DecoderError( p_dec->p_fifo );
330     }
331
332     EndThread( p_dec );
333
334     return 0;
335 }
336
337 /*****************************************************************************
338  * EndThread : thread destruction
339  *****************************************************************************/
340 static void EndThread( dec_thread_t * p_dec )
341 {
342     if ( p_dec->p_aout_input != NULL )
343     {
344         aout_DecDelete( p_dec->p_aout, p_dec->p_aout_input );
345     }
346
347     CloseBitstream( &p_dec->bit_stream );
348     free( p_dec );
349 }
350
351 /*****************************************************************************
352  * SyncInfo: parse MPEG audio sync info
353  *****************************************************************************/
354 static int SyncInfo( uint32_t i_header, unsigned int * pi_channels,
355                      unsigned int * pi_sample_rate, unsigned int * pi_bit_rate,
356                      unsigned int * pi_frame_length,
357                      unsigned int * pi_frame_size, unsigned int * pi_layer )
358 {
359     static const int pppi_mpegaudio_bitrate[2][3][16] =
360     {
361         {
362             /* v1 l1 */
363             { 0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384,
364               416, 448, 0},
365             /* v1 l2 */
366             { 0, 32, 48, 56,  64,  80,  96, 112, 128, 160, 192, 224, 256,
367               320, 384, 0},
368             /* v1 l3 */
369             { 0, 32, 40, 48,  56,  64,  80,  96, 112, 128, 160, 192, 224,
370               256, 320, 0} 
371         },
372
373         {
374             /* v2 l1 */
375             { 0, 32, 48, 56,  64,  80,  96, 112, 128, 144, 160, 176, 192,
376               224, 256, 0},
377             /* v2 l2 */
378             { 0,  8, 16, 24,  32,  40,  48,  56,  64,  80,  96, 112, 128,
379               144, 160, 0},
380             /* v2 l3 */
381             { 0,  8, 16, 24,  32,  40,  48,  56,  64,  80,  96, 112, 128,
382               144, 160, 0} 
383         }
384     };
385
386     static const int ppi_mpegaudio_samplerate[2][4] = /* version 1 then 2 */
387     {
388         { 44100, 48000, 32000, 0 },
389         { 22050, 24000, 16000, 0 }
390     };
391
392     int i_version, i_mode, i_emphasis;
393     vlc_bool_t b_padding, b_mpeg_2_5;
394     int i_current_frame_size = 0;
395     int i_bitrate_index, i_samplerate_index;
396     int i_max_bit_rate;
397
398     b_mpeg_2_5  = 1 - ((i_header & 0x100000) >> 20);
399     i_version   = 1 - ((i_header & 0x80000) >> 19);
400     *pi_layer   = 4 - ((i_header & 0x60000) >> 17);
401     /* CRC */
402     i_bitrate_index = (i_header & 0xf000) >> 12;
403     i_samplerate_index = (i_header & 0xc00) >> 10;
404     b_padding   = (i_header & 0x200) >> 9;
405     /* Extension */
406     i_mode      = (i_header & 0xc0) >> 6;
407     /* Modeext, copyright & original */
408     i_emphasis  = i_header & 0x3;
409
410     if( *pi_layer != 4 &&
411         i_bitrate_index < 0x0f &&
412         i_samplerate_index != 0x03 &&
413         i_emphasis != 0x02 )
414     {
415         switch ( i_mode )
416         {
417         case 0: /* stereo */
418         case 1: /* joint stereo */
419             *pi_channels = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT;
420             break;
421         case 2: /* dual-mono */
422             *pi_channels = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT
423                             | AOUT_CHAN_DUALMONO;
424             break;
425         case 3: /* mono */
426             *pi_channels = AOUT_CHAN_CENTER;
427             break;
428         }
429         *pi_bit_rate = pppi_mpegaudio_bitrate[i_version][*pi_layer-1][i_bitrate_index];
430         i_max_bit_rate = pppi_mpegaudio_bitrate[i_version][*pi_layer-1][14];
431         *pi_sample_rate = ppi_mpegaudio_samplerate[i_version][i_samplerate_index];
432
433         if ( b_mpeg_2_5 )
434         {
435             *pi_sample_rate >>= 1;
436         }
437
438         switch( *pi_layer )
439         {
440         case 1:
441             i_current_frame_size = ( ( i_version ? 6000 : 12000 ) *
442                                         *pi_bit_rate / *pi_sample_rate
443                                         + b_padding ) * 4;
444             *pi_frame_size = ( ( i_version ? 6000 : 12000 ) *
445                                   i_max_bit_rate / *pi_sample_rate + 1 ) * 4;
446             *pi_frame_length = 384;
447             break;
448
449         case 2:
450             i_current_frame_size = ( i_version ? 72000 : 144000 ) *
451                                       *pi_bit_rate / *pi_sample_rate
452                                       + b_padding;
453             *pi_frame_size = ( i_version ? 72000 : 144000 ) *
454                                       i_max_bit_rate / *pi_sample_rate + 1;
455             *pi_frame_length = 1152;
456             break;
457
458         case 3:
459             i_current_frame_size = ( i_version ? 72000 : 144000 ) *
460                                       *pi_bit_rate / *pi_sample_rate
461                                       + b_padding;
462             *pi_frame_size = ( i_version ? 72000 : 144000 ) *
463                                       i_max_bit_rate / *pi_sample_rate + 1;
464             *pi_frame_length = i_version ? 576 : 1152;
465             break;
466
467         default:
468             i_current_frame_size = *pi_frame_size = 0;
469             *pi_frame_length = 0;
470         }
471     }
472     
473     return i_current_frame_size;
474 }