]> git.sesse.net Git - vlc/blob - modules/packetizer/mpeg4audio.c
aa0eb2c78409b4ceea06163ca97d7f655e5290a4
[vlc] / modules / packetizer / mpeg4audio.c
1 /*****************************************************************************
2  * mpeg4audio.c: parse and packetize an MPEG 4 audio stream
3  *****************************************************************************
4  * Copyright (C) 2001, 2002 VideoLAN
5  * $Id: mpeg4audio.c,v 1.9 2003/10/05 18:09:36 gbazin Exp $
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *          Gildas Bazin <gbazin@netcourrier.com>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28 #include <stdlib.h>                                      /* malloc(), free() */
29 #include <string.h>                                              /* strdup() */
30
31 #include <vlc/vlc.h>
32 #include <vlc/aout.h>
33 #include <vlc/decoder.h>
34 #include <vlc/input.h>
35 #include <vlc/sout.h>
36 #include "codecs.h"
37
38 #include "vlc_block_helper.h"
39
40 /* AAC Config in ES:
41  *
42  * AudioObjectType          5 bits
43  * samplingFrequencyIndex   4 bits
44  * if (samplingFrequencyIndex == 0xF)
45  *  samplingFrequency   24 bits
46  * channelConfiguration     4 bits
47  * GA_SpecificConfig
48  *  FrameLengthFlag         1 bit 1024 or 960
49  *  DependsOnCoreCoder      1 bit (always 0)
50  *  ExtensionFlag           1 bit (always 0)
51  */
52
53 /*****************************************************************************
54  * decoder_sys_t : decoder descriptor
55  *****************************************************************************/
56 struct decoder_sys_t
57 {
58     /*
59      * Input properties
60      */
61     int        i_state;
62     vlc_bool_t b_synchro;
63
64     block_t *p_chain;
65     block_bytestream_t bytestream;
66
67     /*
68      * Packetizer output properties
69      */
70     sout_packetizer_input_t *p_sout_input;
71     sout_format_t           sout_format;
72     sout_buffer_t *         p_sout_buffer;            /* current sout buffer */
73
74     /*
75      * Common properties
76      */
77     audio_date_t          end_date;
78     mtime_t pts;
79
80     int i_frame_size, i_raw_blocks;
81     unsigned int i_channels;
82     unsigned int i_rate, i_frame_length;
83 };
84
85 enum {
86
87     STATE_NOSYNC,
88     STATE_SYNC,
89     STATE_HEADER,
90     STATE_NEXT_SYNC,
91     STATE_DATA
92 };
93
94 static int i_sample_rates[] = 
95 {
96     96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 
97     16000, 12000, 11025, 8000,  7350,  0,     0,     0
98 };
99
100 #define ADTS_HEADER_SIZE 6
101
102 /****************************************************************************
103  * Local prototypes
104  ****************************************************************************/
105 static int OpenPacketizer( vlc_object_t * );
106 static int InitPacketizer( decoder_t * );
107 static int RunFramePacketizer ( decoder_t *, block_t * );
108 static int RunADTSPacketizer ( decoder_t *, block_t * );
109 static int EndPacketizer ( decoder_t * );
110 static int GetSoutBuffer( decoder_t *, sout_buffer_t ** );
111
112 static int ADTSSyncInfo( decoder_t *, const byte_t * p_buf,
113                          unsigned int * pi_channels,
114                          unsigned int * pi_sample_rate,
115                          unsigned int * pi_frame_length,
116                          unsigned int * pi_raw_blocks );
117
118 /*****************************************************************************
119  * Module descriptor
120  *****************************************************************************/
121 vlc_module_begin();
122     set_description( _("MPEG4 Audio packetizer") );
123     set_capability( "packetizer", 50 );
124     set_callbacks( OpenPacketizer, NULL );
125 vlc_module_end();
126
127 /*****************************************************************************
128  * OpenPacketizer: probe the packetizer and return score
129  *****************************************************************************/
130 static int OpenPacketizer( vlc_object_t *p_this )
131 {
132     decoder_t *p_dec = (decoder_t*)p_this;
133
134     if( p_dec->p_fifo->i_fourcc != VLC_FOURCC( 'm', 'p', '4', 'a' ) )
135     {
136         return VLC_EGENERIC;
137     }
138
139     /* Allocate the memory needed to store the decoder's structure */
140     if( ( p_dec->p_sys =
141           (decoder_sys_t *)malloc(sizeof(decoder_sys_t)) ) == NULL )
142     {
143         msg_Err( p_dec, "out of memory" );
144         return VLC_EGENERIC;
145     }
146
147     p_dec->pf_init = InitPacketizer;
148     p_dec->pf_decode = RunFramePacketizer;
149     p_dec->pf_end = EndPacketizer;
150
151     return VLC_SUCCESS;
152 }
153
154 /*****************************************************************************
155  * InitPacketizer: Initalize the packetizer
156  *****************************************************************************/
157 static int InitPacketizer( decoder_t *p_dec )
158 {
159     decoder_sys_t *p_sys = p_dec->p_sys;
160     WAVEFORMATEX *p_wf;
161
162     p_sys->i_state = STATE_NOSYNC;
163     p_sys->b_synchro = VLC_FALSE;
164
165     aout_DateSet( &p_sys->end_date, 0 );
166
167     p_sys->p_sout_input = NULL;
168     p_sys->p_sout_buffer = NULL;
169     p_sys->p_chain = NULL;
170
171     msg_Info( p_dec, "Running MPEG4 audio packetizer" );
172
173     p_wf = (WAVEFORMATEX*)p_dec->p_fifo->p_waveformatex;
174
175     if( p_wf && p_wf->cbSize > 0)
176     {
177         uint8_t *p_config = (uint8_t*)&p_wf[1];
178         int     i_index;
179
180         i_index = ( ( p_config[0] << 1 ) | ( p_config[1] >> 7 ) ) & 0x0f;
181         if( i_index != 0x0f )
182         {
183             p_sys->i_rate = i_sample_rates[i_index];
184             p_sys->i_frame_length = (( p_config[1] >> 2 ) & 0x01) ? 960 : 1024;
185         }
186         else
187         {
188             p_sys->i_rate = ( ( p_config[1] & 0x7f ) << 17 ) |
189                 ( p_config[2] << 9 ) | ( p_config[3] << 1 ) |
190                 ( p_config[4] >> 7 );
191             p_sys->i_frame_length = (( p_config[4] >> 2 ) & 0x01) ? 960 : 1024;
192         }
193
194         msg_Dbg( p_dec, "AAC %dHz %d samples/frame",
195                  p_sys->i_rate, p_sys->i_frame_length );
196
197         p_sys->i_channels = p_wf->nChannels;
198         p_sys->sout_format.i_extra_data = p_wf->cbSize;
199         p_sys->sout_format.p_extra_data = malloc( p_wf->cbSize );
200         memcpy( p_sys->sout_format.p_extra_data, &p_wf[1], p_wf->cbSize );
201     }
202     else
203     {
204         msg_Dbg( p_dec, "No decoder specific info, must be an ADTS stream" );
205
206         /* We will try to create a AAC Config from adts */
207         p_sys->sout_format.i_extra_data = 0;
208         p_sys->sout_format.p_extra_data = NULL;
209         p_dec->pf_decode = RunADTSPacketizer;
210     }
211
212     return VLC_SUCCESS;
213 }
214
215 /****************************************************************************
216  * RunFramePacketizer: the whole thing
217  ****************************************************************************
218  * This function must be fed with complete frames.
219  ****************************************************************************/
220 static int RunFramePacketizer( decoder_t *p_dec, block_t *p_block )
221 {
222     decoder_sys_t *p_sys = p_dec->p_sys;
223
224     if( !aout_DateGet( &p_sys->end_date ) && !p_block->i_pts )
225     {
226         /* We've just started the stream, wait for the first PTS. */
227         block_Release( p_block );
228         return VLC_SUCCESS;
229     }
230
231     p_sys->pts = p_block->i_pts;
232     p_sys->i_frame_size = p_block->i_buffer;
233
234     if( GetSoutBuffer( p_dec, &p_sys->p_sout_buffer ) != VLC_SUCCESS )
235     {
236         return VLC_EGENERIC;
237     }
238
239     /* Copy the whole frame into the buffer */
240     p_dec->p_vlc->pf_memcpy( p_sys->p_sout_buffer->p_buffer,
241                              p_block->p_buffer, p_block->i_buffer );
242
243     sout_InputSendBuffer( p_sys->p_sout_input, p_sys->p_sout_buffer );
244     p_sys->p_sout_buffer = NULL;
245
246     block_Release( p_block );
247     return VLC_SUCCESS;
248 }
249
250 /****************************************************************************
251  * RunADTSPacketizer: the whole thing
252  ****************************************************************************/
253 static int RunADTSPacketizer( decoder_t *p_dec, block_t *p_block )
254 {
255     decoder_sys_t *p_sys = p_dec->p_sys;
256     uint8_t p_header[ADTS_HEADER_SIZE];
257
258     if( (!aout_DateGet( &p_sys->end_date ) && !p_block->i_pts)
259         || p_block->b_discontinuity )
260     {
261         /* We've just started the stream, wait for the first PTS. */
262         block_Release( p_block );
263         p_sys->b_synchro = VLC_FALSE;
264         return VLC_SUCCESS;
265     }
266
267     if( p_sys->p_chain )
268     {
269         block_ChainAppend( &p_sys->p_chain, p_block );
270     }
271     else
272     {
273         block_ChainAppend( &p_sys->p_chain, p_block );
274         p_sys->bytestream = block_BytestreamInit( p_dec, p_sys->p_chain, 0 );
275     }
276
277     while( 1 )
278     {
279         switch( p_sys->i_state )
280         {
281
282         case STATE_NOSYNC:
283             while( block_PeekBytes( &p_sys->bytestream, p_header, 2 )
284                    == VLC_SUCCESS )
285             {
286                 /* Look for sync word - should be 0xfff + 2 layer bits */
287                 if( p_header[0] == 0xff && (p_header[1] & 0xf6) == 0xf0 )
288                 {
289                     p_sys->i_state = STATE_SYNC;
290                     break;
291                 }
292                 block_SkipByte( &p_sys->bytestream );
293                 p_sys->b_synchro = VLC_FALSE;
294             }
295             if( p_sys->i_state != STATE_SYNC )
296             {
297                 block_ChainRelease( p_sys->p_chain );
298                 p_sys->p_chain = NULL;
299
300                 /* Need more data */
301                 return VLC_SUCCESS;
302             }
303
304         case STATE_SYNC:
305             /* New frame, set the Presentation Time Stamp */
306             p_sys->pts = p_sys->bytestream.p_block->i_pts;
307             if( p_sys->pts != 0 &&
308                 p_sys->pts != aout_DateGet( &p_sys->end_date ) )
309             {
310                 aout_DateSet( &p_sys->end_date, p_sys->pts );
311             }
312             p_sys->i_state = STATE_HEADER;
313             break;
314
315         case STATE_HEADER:
316             /* Get ADTS frame header (ADTS_HEADER_SIZE bytes) */
317             if( block_PeekBytes( &p_sys->bytestream, p_header,
318                                  ADTS_HEADER_SIZE ) != VLC_SUCCESS )
319             {
320                 /* Need more data */
321                 return VLC_SUCCESS;
322             }
323
324             /* Check if frame is valid and get frame info */
325             p_sys->i_frame_size = ADTSSyncInfo( p_dec, p_header,
326                                                 &p_sys->i_channels,
327                                                 &p_sys->i_rate,
328                                                 &p_sys->i_frame_length,
329                                                 &p_sys->i_raw_blocks );
330             if( !p_sys->i_frame_size )
331             {
332                 msg_Dbg( p_dec, "emulated sync word" );
333                 block_SkipByte( &p_sys->bytestream );
334                 p_sys->i_state = STATE_NOSYNC;
335                 p_sys->b_synchro = VLC_FALSE;
336                 break;
337             }
338
339             p_sys->i_state = STATE_DATA;
340
341         case STATE_DATA:
342             /* TODO: If p_block == NULL, flush the buffer without checking the
343              * next sync word */
344
345             if( !p_sys->b_synchro )
346             {
347                 /* Check if next expected frame contains the sync word */
348                 if( block_PeekOffsetBytes( &p_sys->bytestream,
349                                            p_sys->i_frame_size, p_header, 2 )
350                     != VLC_SUCCESS )
351                 {
352                     /* Need more data */
353                     return VLC_SUCCESS;
354                 }
355
356                 if( p_header[0] != 0xff || (p_header[1] & 0xf6) != 0xf0 )
357                 {
358                     msg_Dbg( p_dec, "emulated sync word "
359                              "(no sync on following frame)" );
360                     p_sys->i_state = STATE_NOSYNC;
361                     block_SkipByte( &p_sys->bytestream );
362                     p_sys->b_synchro = VLC_FALSE;
363                     break;
364                 }
365             }
366
367             if( !p_sys->p_sout_buffer )
368             if( GetSoutBuffer( p_dec, &p_sys->p_sout_buffer ) != VLC_SUCCESS )
369             {
370                 return VLC_EGENERIC;
371             }
372
373             /* Copy the whole frame into the buffer */
374             if( block_GetBytes( &p_sys->bytestream,
375                                 p_sys->p_sout_buffer->p_buffer,
376                                 p_sys->i_frame_size ) != VLC_SUCCESS )
377             {
378                 /* Need more data */
379                 return VLC_SUCCESS;
380             }
381
382             p_sys->p_chain = block_BytestreamFlush( &p_sys->bytestream );
383
384             sout_InputSendBuffer( p_sys->p_sout_input, p_sys->p_sout_buffer );
385
386             p_sys->i_state = STATE_NOSYNC;
387             p_sys->p_sout_buffer = NULL;
388             p_sys->b_synchro = VLC_TRUE;
389
390             /* Make sure we don't reuse the same pts twice */
391             if( p_sys->pts == p_sys->bytestream.p_block->i_pts )
392                 p_sys->pts = p_sys->bytestream.p_block->i_pts = 0;
393         }
394     }
395
396     return VLC_SUCCESS;
397 }
398
399 /*****************************************************************************
400  * GetSoutBuffer:
401  *****************************************************************************/
402 static int GetSoutBuffer( decoder_t *p_dec, sout_buffer_t **pp_buffer )
403 {
404     decoder_sys_t *p_sys = p_dec->p_sys;
405
406     if( p_sys->p_sout_input != NULL &&
407         ( p_sys->sout_format.i_sample_rate != (int)p_sys->i_rate
408           || p_sys->sout_format.i_channels != (int)p_sys->i_channels ) )
409     {
410         /* Parameters changed - this should not happen. */
411     }
412
413     /* Creating the sout input if not created yet. */
414     if( p_sys->p_sout_input == NULL )
415     {
416         p_sys->sout_format.i_cat = AUDIO_ES;
417         p_sys->sout_format.i_fourcc = VLC_FOURCC( 'm', 'p', '4', 'a' );
418         p_sys->sout_format.i_sample_rate = p_sys->i_rate;
419         p_sys->sout_format.i_channels    = p_sys->i_channels;
420         p_sys->sout_format.i_block_align = 0;
421         p_sys->sout_format.i_bitrate     = 0;
422
423         aout_DateInit( &p_sys->end_date, p_sys->i_rate );
424         aout_DateSet( &p_sys->end_date, p_sys->pts );
425
426         p_sys->p_sout_input = sout_InputNew( p_dec, &p_sys->sout_format );
427         if( p_sys->p_sout_input == NULL )
428         {
429             msg_Err( p_dec, "cannot add a new stream" );
430             *pp_buffer = NULL;
431             return VLC_EGENERIC;
432         }
433         msg_Info( p_dec, "AAC channels: %d samplerate: %d",
434                   p_sys->i_channels, p_sys->i_rate );
435     }
436
437     *pp_buffer = sout_BufferNew( p_sys->p_sout_input->p_sout,
438                                  p_sys->i_frame_size );
439     if( *pp_buffer == NULL )
440     {
441         return VLC_EGENERIC;
442     }
443
444     (*pp_buffer)->i_pts =
445         (*pp_buffer)->i_dts = aout_DateGet( &p_sys->end_date );
446
447     (*pp_buffer)->i_length =
448         aout_DateIncrement( &p_sys->end_date, p_sys->i_frame_length )
449         - (*pp_buffer)->i_pts;
450
451     return VLC_SUCCESS;
452 }
453
454 /*****************************************************************************
455  * EndPacketizer: clean up the packetizer
456  *****************************************************************************/
457 static int EndPacketizer( decoder_t *p_dec )
458 {
459     if( p_dec->p_sys->p_sout_input != NULL )
460     {
461         if( p_dec->p_sys->p_sout_buffer )
462         {
463             sout_BufferDelete( p_dec->p_sys->p_sout_input->p_sout,
464                                p_dec->p_sys->p_sout_buffer );
465         }
466
467         sout_InputDelete( p_dec->p_sys->p_sout_input );
468     }
469
470     if( p_dec->p_sys->p_chain ) block_ChainRelease( p_dec->p_sys->p_chain );
471
472     free( p_dec->p_sys );
473
474     return VLC_SUCCESS;
475 }
476
477 /*****************************************************************************
478  * ADTSSyncInfo: parse MPEG 4 audio ADTS sync info
479  *****************************************************************************/
480 static int ADTSSyncInfo( decoder_t * p_dec, const byte_t * p_buf,
481                          unsigned int * pi_channels,
482                          unsigned int * pi_sample_rate,
483                          unsigned int * pi_frame_length,
484                          unsigned int * pi_raw_blocks_in_frame )
485 {
486     decoder_sys_t *p_sys = p_dec->p_sys;
487     int i_id, i_profile, i_sample_rate_idx, i_frame_size;
488
489     /* Fixed header between frames */
490     i_id = ( (p_buf[1] >> 3) & 0x01 ) ? 2 : 4;
491     i_profile = p_buf[2] >> 6;
492     i_sample_rate_idx = (p_buf[2] >> 2) & 0x0f;
493     *pi_sample_rate = i_sample_rates[i_sample_rate_idx];
494     *pi_channels = ((p_buf[2] & 0x01) << 2) | ((p_buf[3] >> 6) & 0x03);
495
496     /* Variable header */
497     i_frame_size = ((p_buf[3] & 0x03) << 11) | (p_buf[4] << 3) |
498                    ((p_buf[5] >> 5) & 0x7);
499     *pi_raw_blocks_in_frame = (p_buf[6] & 0x02) + 1;
500
501     if( !*pi_sample_rate || !*pi_channels || !i_frame_size )
502     {
503         return 0;
504     }
505
506     /* Fixme */
507     *pi_frame_length = 1024;
508
509     /* Build the decoder specific info header */
510     if( !p_dec->p_sys->sout_format.i_extra_data )
511     {
512         p_sys->sout_format.i_extra_data = 2;
513         p_sys->sout_format.p_extra_data = malloc( 2 );
514         p_sys->sout_format.p_extra_data[0] =
515             (i_profile + 1) << 3 | (i_sample_rate_idx > 1);
516         p_sys->sout_format.p_extra_data[1] =
517             ((i_sample_rate_idx & 0x01) << 7) | (*pi_channels <<3);
518     }
519
520     return i_frame_size;
521 }