* mpeg_audio.c: fix segfault caused by free bitrate and padding set.
[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.16 2003/06/25 00:40:41 fenrir 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 10000
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     int i_free_frame_size = 0;
119
120     /* Allocate the memory needed to store the thread's structure */
121     p_dec = malloc( sizeof(dec_thread_t) );
122     if( p_dec == NULL )
123     {
124         msg_Err( p_fifo, "out of memory" );
125         DecoderError( p_fifo );
126         return -1;
127     }
128
129     /* Initialize the thread properties */
130     p_dec->p_aout = NULL;
131     p_dec->p_aout_input = NULL;
132     p_dec->p_fifo = p_fifo;
133
134     aout_DateSet( &end_date, 0 );
135
136     /* Init the bitstream */
137     if( InitBitstream( &p_dec->bit_stream, p_dec->p_fifo,
138                        NULL, NULL ) != VLC_SUCCESS )
139     {
140         msg_Err( p_fifo, "cannot initialize bitstream" );
141         DecoderError( p_fifo );
142         free( p_dec );
143         return -1;
144     }
145
146     /* Init sync buffer. */
147     NextPTS( &p_dec->bit_stream, &pts, NULL );
148     GetChunk( &p_dec->bit_stream, p_sync, MAD_BUFFER_GUARD );
149
150     /* Decoder thread's main loop */
151     while ( !p_dec->p_fifo->b_die && !p_dec->p_fifo->b_error )
152     {
153         int i_current_frame_size;
154         unsigned int i_rate, i_original_channels, i_frame_size, i_frame_length;
155         unsigned int i_new_layer, i_bit_rate;
156         uint32_t i_header;
157         aout_buffer_t * p_buffer;
158         int i;
159
160         /* Look for sync word - should be 0xffe */
161         if ( (p_sync[0] != 0xff) || ((p_sync[1] & 0xe0) != 0xe0) )
162         {
163             msg_Warn( p_dec->p_fifo, "no sync - skipping" );
164             /* Look inside the sync buffer. */
165             for ( i = 1; i < MAD_BUFFER_GUARD - 1; i++ )
166             {
167                 if ( (p_sync[i] == 0xff) && ((p_sync[i + 1] & 0xe0) == 0xe0) )
168                     break;
169             }
170             if ( i < MAD_BUFFER_GUARD - 1 )
171             {
172                 /* Found it ! */
173                 memmove( p_sync, &p_sync[i], MAD_BUFFER_GUARD - i );
174                 GetChunk( &p_dec->bit_stream, &p_sync[MAD_BUFFER_GUARD - i],
175                           i );
176             }
177             else
178             {
179                 if ( p_sync[MAD_BUFFER_GUARD - 1] == 0xff
180                       && ShowBits( &p_dec->bit_stream, 3 ) == 0x3 )
181                 {
182                     /* Found it ! */
183                     p_sync[0] = p_sync[MAD_BUFFER_GUARD - 1];
184                     GetChunk( &p_dec->bit_stream,
185                               &p_sync[1], MAD_BUFFER_GUARD - 1 );
186                 }
187                 else
188                 {
189                     /* Scan the stream. */
190                     while ( ShowBits( &p_dec->bit_stream, 11 ) != 0x07ff &&
191                             (!p_dec->p_fifo->b_die) &&
192                             (!p_dec->p_fifo->b_error) )
193                     {
194                         RemoveBits( &p_dec->bit_stream, 8 );
195                     }
196                     if ( p_dec->p_fifo->b_die || p_dec->p_fifo->b_error )
197                         break;
198                     NextPTS( &p_dec->bit_stream, &pts, NULL );
199                     GetChunk( &p_dec->bit_stream,p_sync, MAD_BUFFER_GUARD );
200                 }
201             }
202         }
203         if ( p_dec->p_fifo->b_die || p_dec->p_fifo->b_error ) break;
204
205         /* Set the Presentation Time Stamp */
206         if ( pts != 0 && pts != aout_DateGet( &end_date ) )
207         {
208             aout_DateSet( &end_date, pts );
209         }
210
211         /* Get frame header */
212         i_header = (p_sync[0] << 24) | (p_sync[1] << 16) | (p_sync[2] << 8)
213                      | p_sync[3];
214
215         /* Check if frame is valid and get frame info */
216         i_current_frame_size = SyncInfo( i_header,
217                                          &i_original_channels, &i_rate,
218                                          &i_bit_rate, &i_frame_length,
219                                          &i_frame_size, &i_new_layer );
220         if( i_current_frame_size == -1 )
221         {
222             msg_Warn( p_dec->p_fifo, "syncinfo failed" );
223             /* This is probably an emulated startcode, drop the first byte
224              * to force looking for the next startcode. */
225             memmove( p_sync, &p_sync[1], MAD_BUFFER_GUARD - 1 );
226             p_sync[MAD_BUFFER_GUARD - 1] = GetBits( &p_dec->bit_stream, 8 );
227             continue;
228         }
229
230         if( i_bit_rate == 0 )
231         {
232             /* free birate, but 99% emulated startcode :( */
233             i_current_frame_size = i_free_frame_size;
234         }
235
236         if ( (unsigned int)i_current_frame_size > i_frame_size )
237         {
238             msg_Warn( p_dec->p_fifo, "frame too big %d > %d",
239                       i_current_frame_size, i_frame_size );
240             memmove( p_sync, &p_sync[1], MAD_BUFFER_GUARD - 1 );
241             p_sync[MAD_BUFFER_GUARD - 1] = GetBits( &p_dec->bit_stream, 8 );
242             continue;
243         }
244
245         if( (p_dec->p_aout_input != NULL) &&
246             ( (p_dec->output_format.i_rate != i_rate)
247                 || (p_dec->output_format.i_original_channels
248                       != i_original_channels)
249                 || (p_dec->output_format.i_bytes_per_frame
250                       != i_frame_size + MAD_BUFFER_GUARD)
251                 || (p_dec->output_format.i_frame_length != i_frame_length)
252                 || (i_layer != i_new_layer) ) )
253         {
254             /* Parameters changed - this should not happen. */
255             aout_DecDelete( p_dec->p_aout, p_dec->p_aout_input );
256             p_dec->p_aout_input = NULL;
257         }
258
259         /* Creating the audio input if not created yet. */
260         if( p_dec->p_aout_input == NULL )
261         {
262             i_layer = i_new_layer;
263             if ( i_layer == 3 )
264             {
265                 p_dec->output_format.i_format = VLC_FOURCC('m','p','g','3');
266             }
267             else
268             {
269                 p_dec->output_format.i_format = VLC_FOURCC('m','p','g','a');
270             }
271             p_dec->output_format.i_rate = i_rate;
272             p_dec->output_format.i_original_channels = i_original_channels;
273             p_dec->output_format.i_physical_channels
274                        = i_original_channels & AOUT_CHAN_PHYSMASK;
275             p_dec->output_format.i_bytes_per_frame = i_frame_size
276                                                         + MAD_BUFFER_GUARD;
277             p_dec->output_format.i_frame_length = i_frame_length;
278             aout_DateInit( &end_date, i_rate );
279             aout_DateSet( &end_date, pts );
280             p_dec->p_aout_input = aout_DecNew( p_dec->p_fifo,
281                                                &p_dec->p_aout,
282                                                &p_dec->output_format );
283
284             if ( p_dec->p_aout_input == NULL )
285             {
286                 p_dec->p_fifo->b_error = 1;
287                 break;
288             }
289         }
290
291         if ( !aout_DateGet( &end_date ) )
292         {
293             byte_t p_junk[MAX_FRAME_SIZE];
294             int    i_skip = i_current_frame_size - MAD_BUFFER_GUARD;
295
296             /* We've just started the stream, wait for the first PTS. */
297             while( i_skip > 0 )
298             {
299                 int i_read;
300
301                 i_read = __MIN( i_current_frame_size  - MAD_BUFFER_GUARD, MAX_FRAME_SIZE );
302                 GetChunk( &p_dec->bit_stream, p_junk, i_read );
303
304                 i_skip -= i_read;
305             }
306             NextPTS( &p_dec->bit_stream, &pts, NULL );
307             GetChunk( &p_dec->bit_stream, p_sync, MAD_BUFFER_GUARD );
308             continue;
309         }
310
311         p_buffer = aout_DecNewBuffer( p_dec->p_aout, p_dec->p_aout_input,
312                                       i_frame_length );
313         if ( p_buffer == NULL )
314         {
315             p_dec->p_fifo->b_error = 1;
316             break;
317         }
318         p_buffer->start_date = aout_DateGet( &end_date );
319         p_buffer->end_date = aout_DateIncrement( &end_date,
320                                                  i_frame_length );
321
322         /* Get the whole frame. */
323         memcpy( p_buffer->p_buffer, p_sync, MAD_BUFFER_GUARD );
324         if ( i_current_frame_size )
325         {
326             GetChunk( &p_dec->bit_stream, p_buffer->p_buffer + MAD_BUFFER_GUARD,
327                       i_current_frame_size - MAD_BUFFER_GUARD );
328         }
329         else
330         {
331             /* Free bit-rate stream. Peek at next frame header. */
332             i = MAD_BUFFER_GUARD;
333             for ( ; ; )
334             {
335                 int i_next_real_frame_size;
336                 unsigned int i_next_channels, i_next_rate, i_next_bit_rate;
337                 unsigned int i_next_frame_length, i_next_frame_size;
338                 unsigned int i_next_layer;
339                 while ( ShowBits( &p_dec->bit_stream, 11 ) != 0x07ff &&
340                         (!p_dec->p_fifo->b_die) &&
341                         (!p_dec->p_fifo->b_error) &&
342                         i < (int)i_frame_size + MAD_BUFFER_GUARD )
343                 {
344                     ((uint8_t *)p_buffer->p_buffer)[i++] =
345                                 GetBits( &p_dec->bit_stream, 8 );
346                 }
347                 if ( p_dec->p_fifo->b_die || p_dec->p_fifo->b_error
348                       || i == (int)i_frame_size + MAD_BUFFER_GUARD )
349                     break;
350                 i_header = ShowBits( &p_dec->bit_stream, 8 );
351                 i_next_real_frame_size = SyncInfo( i_header,
352                                          &i_next_channels, &i_next_rate,
353                                          &i_next_bit_rate, &i_next_frame_length,
354                                          &i_next_frame_size, &i_next_layer );
355                 if ( i_next_real_frame_size != 0 ||
356                      i_next_channels != i_original_channels ||
357                      i_next_rate != i_rate ||
358                      i_next_bit_rate != i_bit_rate ||
359                      i_next_frame_length != i_frame_length ||
360                      i_next_frame_size != i_frame_size ||
361                      i_next_layer != i_new_layer )
362                 {
363                     /* This is an emulated start code, try again. */
364                     /* there is at least 1 byte free */
365                     ((uint8_t *)p_buffer->p_buffer)[i++] =
366                                 GetBits( &p_dec->bit_stream, 8 );
367                     continue;
368                 }
369                 i_free_frame_size = i;
370                 break;
371             }
372             if ( p_dec->p_fifo->b_die || p_dec->p_fifo->b_error )
373                 break;
374             if ( i == (int)i_frame_size + MAD_BUFFER_GUARD )
375             {
376                 /* Couldn't find the next start-code. This is sooo
377                  * embarassing. */
378                 aout_DecDeleteBuffer( p_dec->p_aout, p_dec->p_aout_input,
379                                       p_buffer );
380                 NextPTS( &p_dec->bit_stream, &pts, NULL );
381                 GetChunk( &p_dec->bit_stream, p_sync, MAD_BUFFER_GUARD );
382                 continue;
383             }
384         }
385         if( p_dec->p_fifo->b_die )
386         {
387             aout_DecDeleteBuffer( p_dec->p_aout, p_dec->p_aout_input,
388                                   p_buffer );
389             break;
390         }
391         /* Get beginning of next frame. */
392         NextPTS( &p_dec->bit_stream, &pts, NULL );
393         GetChunk( &p_dec->bit_stream, p_buffer->p_buffer + i_current_frame_size,
394                   MAD_BUFFER_GUARD );
395         memcpy( p_sync, p_buffer->p_buffer + i_current_frame_size,
396                 MAD_BUFFER_GUARD );
397
398         p_buffer->i_nb_bytes = i_current_frame_size + MAD_BUFFER_GUARD;
399
400         /* Send the buffer to the aout core. */
401         aout_DecPlay( p_dec->p_aout, p_dec->p_aout_input, p_buffer );
402     }
403
404     if( p_dec->p_fifo->b_error )
405     {
406         DecoderError( p_dec->p_fifo );
407     }
408
409     EndThread( p_dec );
410
411     return 0;
412 }
413
414 /*****************************************************************************
415  * EndThread : thread destruction
416  *****************************************************************************/
417 static void EndThread( dec_thread_t * p_dec )
418 {
419     if ( p_dec->p_aout_input != NULL )
420     {
421         aout_DecDelete( p_dec->p_aout, p_dec->p_aout_input );
422     }
423
424     CloseBitstream( &p_dec->bit_stream );
425     free( p_dec );
426 }
427
428 /*****************************************************************************
429  * SyncInfo: parse MPEG audio sync info
430  *****************************************************************************/
431 static int SyncInfo( uint32_t i_header, unsigned int * pi_channels,
432                      unsigned int * pi_sample_rate, unsigned int * pi_bit_rate,
433                      unsigned int * pi_frame_length,
434                      unsigned int * pi_frame_size, unsigned int * pi_layer )
435 {
436     static const int pppi_mpegaudio_bitrate[2][3][16] =
437     {
438         {
439             /* v1 l1 */
440             { 0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384,
441               416, 448, 0},
442             /* v1 l2 */
443             { 0, 32, 48, 56,  64,  80,  96, 112, 128, 160, 192, 224, 256,
444               320, 384, 0},
445             /* v1 l3 */
446             { 0, 32, 40, 48,  56,  64,  80,  96, 112, 128, 160, 192, 224,
447               256, 320, 0}
448         },
449
450         {
451             /* v2 l1 */
452             { 0, 32, 48, 56,  64,  80,  96, 112, 128, 144, 160, 176, 192,
453               224, 256, 0},
454             /* v2 l2 */
455             { 0,  8, 16, 24,  32,  40,  48,  56,  64,  80,  96, 112, 128,
456               144, 160, 0},
457             /* v2 l3 */
458             { 0,  8, 16, 24,  32,  40,  48,  56,  64,  80,  96, 112, 128,
459               144, 160, 0}
460         }
461     };
462
463     static const int ppi_mpegaudio_samplerate[2][4] = /* version 1 then 2 */
464     {
465         { 44100, 48000, 32000, 0 },
466         { 22050, 24000, 16000, 0 }
467     };
468
469     int i_version, i_mode, i_emphasis;
470     vlc_bool_t b_padding, b_mpeg_2_5;
471     int i_current_frame_size = 0;
472     int i_bitrate_index, i_samplerate_index;
473     int i_max_bit_rate;
474
475     b_mpeg_2_5  = 1 - ((i_header & 0x100000) >> 20);
476     i_version   = 1 - ((i_header & 0x80000) >> 19);
477     *pi_layer   = 4 - ((i_header & 0x60000) >> 17);
478     /* CRC */
479     i_bitrate_index = (i_header & 0xf000) >> 12;
480     i_samplerate_index = (i_header & 0xc00) >> 10;
481     b_padding   = (i_header & 0x200) >> 9;
482     /* Extension */
483     i_mode      = (i_header & 0xc0) >> 6;
484     /* Modeext, copyright & original */
485     i_emphasis  = i_header & 0x3;
486
487     if( *pi_layer != 4 &&
488         i_bitrate_index < 0x0f &&
489         i_samplerate_index != 0x03 &&
490         i_emphasis != 0x02 )
491     {
492         switch ( i_mode )
493         {
494         case 0: /* stereo */
495         case 1: /* joint stereo */
496             *pi_channels = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT;
497             break;
498         case 2: /* dual-mono */
499             *pi_channels = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT
500                             | AOUT_CHAN_DUALMONO;
501             break;
502         case 3: /* mono */
503             *pi_channels = AOUT_CHAN_CENTER;
504             break;
505         }
506         *pi_bit_rate = pppi_mpegaudio_bitrate[i_version][*pi_layer-1][i_bitrate_index];
507         i_max_bit_rate = pppi_mpegaudio_bitrate[i_version][*pi_layer-1][14];
508         *pi_sample_rate = ppi_mpegaudio_samplerate[i_version][i_samplerate_index];
509
510         if ( b_mpeg_2_5 )
511         {
512             *pi_sample_rate >>= 1;
513         }
514
515         switch( *pi_layer )
516         {
517         case 1:
518             i_current_frame_size = ( 12000 *
519                                         *pi_bit_rate / *pi_sample_rate
520                                         + b_padding ) * 4;
521             *pi_frame_size = ( 12000 *
522                                   i_max_bit_rate / *pi_sample_rate + 1 ) * 4;
523             *pi_frame_length = 384;
524             break;
525
526         case 2:
527             i_current_frame_size = 144000 *
528                                       *pi_bit_rate / *pi_sample_rate
529                                       + b_padding;
530             *pi_frame_size = 144000 * i_max_bit_rate / *pi_sample_rate + 1;
531             *pi_frame_length = 1152;
532             break;
533
534         case 3:
535             i_current_frame_size = ( i_version ? 72000 : 144000 ) *
536                                    *pi_bit_rate / *pi_sample_rate + b_padding;
537             *pi_frame_size = ( i_version ? 72000 : 144000 ) *
538                                  i_max_bit_rate / *pi_sample_rate + 1;
539             *pi_frame_length = i_version ? 576 : 1152;
540             break;
541
542         default:
543             break;
544         }
545     }
546     else
547     {
548         return -1;
549     }
550
551     return i_current_frame_size;
552 }
553