]> git.sesse.net Git - vlc/blob - modules/packetizer/mpeg4audio.c
Make Zorglub less unhappy
[vlc] / modules / packetizer / mpeg4audio.c
1 /*****************************************************************************
2  * mpeg4audio.c: parse and packetize an MPEG 4 audio stream
3  *****************************************************************************
4  * Copyright (C) 2001, 2002 the VideoLAN team
5  * $Id$
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
63     block_bytestream_t bytestream;
64
65     /*
66      * Common properties
67      */
68     audio_date_t end_date;
69     mtime_t i_pts;
70
71     int i_frame_size, i_raw_blocks;
72     unsigned int i_channels;
73     unsigned int i_rate, i_frame_length, i_header_size;
74 };
75
76 enum {
77
78     STATE_NOSYNC,
79     STATE_SYNC,
80     STATE_HEADER,
81     STATE_NEXT_SYNC,
82     STATE_GET_DATA,
83     STATE_SEND_DATA
84 };
85
86 static int i_sample_rates[] =
87 {
88     96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
89     16000, 12000, 11025, 8000,  7350,  0,     0,     0
90 };
91
92 #define ADTS_HEADER_SIZE 9
93
94 /****************************************************************************
95  * Local prototypes
96  ****************************************************************************/
97 static int  OpenPacketizer( vlc_object_t * );
98 static void ClosePacketizer( vlc_object_t * );
99
100 static block_t *PacketizeBlock    ( decoder_t *, block_t ** );
101 static block_t *ADTSPacketizeBlock( decoder_t *, block_t ** );
102
103 static uint8_t *GetOutBuffer ( decoder_t *, void ** );
104
105 static int ADTSSyncInfo( decoder_t *, const byte_t * p_buf,
106                          unsigned int * pi_channels,
107                          unsigned int * pi_sample_rate,
108                          unsigned int * pi_frame_length,
109                          unsigned int * pi_header_size,
110                          unsigned int * pi_raw_blocks );
111
112 /*****************************************************************************
113  * Module descriptor
114  *****************************************************************************/
115 vlc_module_begin();
116     set_category( CAT_SOUT );
117     set_subcategory( SUBCAT_SOUT_PACKETIZER );
118     set_description( _("MPEG4 audio packetizer") );
119     set_capability( "packetizer", 50 );
120     set_callbacks( OpenPacketizer, ClosePacketizer );
121 vlc_module_end();
122
123 /*****************************************************************************
124  * OpenPacketizer: probe the packetizer and return score
125  *****************************************************************************/
126 static int OpenPacketizer( vlc_object_t *p_this )
127 {
128     decoder_t *p_dec = (decoder_t*)p_this;
129     decoder_sys_t *p_sys;
130
131     if( p_dec->fmt_in.i_codec != VLC_FOURCC( 'm', 'p', '4', 'a' ) )
132     {
133         return VLC_EGENERIC;
134     }
135
136     /* Allocate the memory needed to store the decoder's structure */
137     if( ( p_dec->p_sys = p_sys =
138           (decoder_sys_t *)malloc(sizeof(decoder_sys_t)) ) == NULL )
139     {
140         msg_Err( p_dec, "out of memory" );
141         return VLC_EGENERIC;
142     }
143
144     /* Misc init */
145     p_sys->i_state = STATE_NOSYNC;
146     aout_DateSet( &p_sys->end_date, 0 );
147     p_sys->bytestream = block_BytestreamInit( p_dec );
148
149     /* Set output properties */
150     p_dec->fmt_out.i_cat = AUDIO_ES;
151     p_dec->fmt_out.i_codec = VLC_FOURCC('m','p','4','a');
152
153     /* Set callback */
154     p_dec->pf_packetize = PacketizeBlock;
155
156     msg_Info( p_dec, "running MPEG4 audio packetizer" );
157
158     if( p_dec->fmt_in.i_extra > 0 )
159     {
160         uint8_t *p_config = (uint8_t*)p_dec->fmt_in.p_extra;
161         int     i_index;
162
163         i_index = ( ( p_config[0] << 1 ) | ( p_config[1] >> 7 ) ) & 0x0f;
164         if( i_index != 0x0f )
165         {
166             p_dec->fmt_out.audio.i_rate = i_sample_rates[i_index];
167             p_dec->fmt_out.audio.i_frame_length =
168                 (( p_config[1] >> 2 ) & 0x01) ? 960 : 1024;
169         }
170         else
171         {
172             p_dec->fmt_out.audio.i_rate = ( ( p_config[1] & 0x7f ) << 17 ) |
173                 ( p_config[2] << 9 ) | ( p_config[3] << 1 ) |
174                 ( p_config[4] >> 7 );
175             p_dec->fmt_out.audio.i_frame_length =
176                 (( p_config[4] >> 2 ) & 0x01) ? 960 : 1024;
177         }
178
179         msg_Dbg( p_dec, "AAC %dHz %d samples/frame",
180                  p_dec->fmt_out.audio.i_rate,
181                  p_dec->fmt_out.audio.i_frame_length );
182
183         aout_DateInit( &p_sys->end_date, p_dec->fmt_out.audio.i_rate );
184
185         p_dec->fmt_out.audio.i_channels = p_dec->fmt_in.audio.i_channels;
186         p_dec->fmt_out.i_extra = p_dec->fmt_in.i_extra;
187         p_dec->fmt_out.p_extra = malloc( p_dec->fmt_in.i_extra );
188         memcpy( p_dec->fmt_out.p_extra, p_dec->fmt_in.p_extra,
189                 p_dec->fmt_in.i_extra );
190     }
191     else
192     {
193         msg_Dbg( p_dec, "no decoder specific info, must be an ADTS stream" );
194
195         /* We will try to create a AAC Config from adts */
196         p_dec->fmt_out.i_extra = 0;
197         p_dec->fmt_out.p_extra = NULL;
198         p_dec->pf_packetize = ADTSPacketizeBlock;
199     }
200
201     return VLC_SUCCESS;
202 }
203
204 /****************************************************************************
205  * PacketizeBlock: the whole thing
206  ****************************************************************************
207  * This function must be fed with complete frames.
208  ****************************************************************************/
209 static block_t *PacketizeBlock( decoder_t *p_dec, block_t **pp_block )
210 {
211     decoder_sys_t *p_sys = p_dec->p_sys;
212     block_t *p_block;
213
214     if( !pp_block || !*pp_block ) return NULL;
215
216     p_block = *pp_block;
217     *pp_block = NULL; /* Don't reuse this block */
218
219     if( !aout_DateGet( &p_sys->end_date ) && !p_block->i_pts )
220     {
221         /* We've just started the stream, wait for the first PTS. */
222         block_Release( p_block );
223         return NULL;
224     }
225     else if( p_block->i_pts != 0 &&
226              p_block->i_pts != aout_DateGet( &p_sys->end_date ) )
227     {
228         aout_DateSet( &p_sys->end_date, p_block->i_pts );
229     }
230
231     p_block->i_pts = p_block->i_dts = aout_DateGet( &p_sys->end_date );
232
233     p_block->i_length = aout_DateIncrement( &p_sys->end_date,
234         p_dec->fmt_out.audio.i_frame_length ) - p_block->i_pts;
235
236     return p_block;
237 }
238
239 /****************************************************************************
240  * DTSPacketizeBlock: the whole thing
241  ****************************************************************************/
242 static block_t *ADTSPacketizeBlock( decoder_t *p_dec, block_t **pp_block )
243 {
244     decoder_sys_t *p_sys = p_dec->p_sys;
245     uint8_t p_header[ADTS_HEADER_SIZE];
246     void *p_out_buffer;
247     uint8_t *p_buf;
248
249     if( !pp_block || !*pp_block ) return NULL;
250
251     if( !aout_DateGet( &p_sys->end_date ) && !(*pp_block)->i_pts )
252     {
253         /* We've just started the stream, wait for the first PTS. */
254         block_Release( *pp_block );
255         return NULL;
256     }
257
258     if( (*pp_block)->i_flags&BLOCK_FLAG_DISCONTINUITY )
259     {
260         p_sys->i_state = STATE_NOSYNC;
261     }
262
263     block_BytestreamPush( &p_sys->bytestream, *pp_block );
264
265     while( 1 )
266     {
267         switch( p_sys->i_state )
268         {
269
270         case STATE_NOSYNC:
271             while( block_PeekBytes( &p_sys->bytestream, p_header, 2 )
272                    == VLC_SUCCESS )
273             {
274                 /* Look for sync word - should be 0xfff + 2 layer bits */
275                 if( p_header[0] == 0xff && (p_header[1] & 0xf6) == 0xf0 )
276                 {
277                     p_sys->i_state = STATE_SYNC;
278                     break;
279                 }
280                 block_SkipByte( &p_sys->bytestream );
281             }
282             if( p_sys->i_state != STATE_SYNC )
283             {
284                 block_BytestreamFlush( &p_sys->bytestream );
285
286                 /* Need more data */
287                 return NULL;
288             }
289
290         case STATE_SYNC:
291             /* New frame, set the Presentation Time Stamp */
292             p_sys->i_pts = p_sys->bytestream.p_block->i_pts;
293             if( p_sys->i_pts != 0 &&
294                 p_sys->i_pts != aout_DateGet( &p_sys->end_date ) )
295             {
296                 aout_DateSet( &p_sys->end_date, p_sys->i_pts );
297             }
298             p_sys->i_state = STATE_HEADER;
299             break;
300
301         case STATE_HEADER:
302             /* Get ADTS frame header (ADTS_HEADER_SIZE bytes) */
303             if( block_PeekBytes( &p_sys->bytestream, p_header,
304                                  ADTS_HEADER_SIZE ) != VLC_SUCCESS )
305             {
306                 /* Need more data */
307                 return NULL;
308             }
309
310             /* Check if frame is valid and get frame info */
311             p_sys->i_frame_size = ADTSSyncInfo( p_dec, p_header,
312                                                 &p_sys->i_channels,
313                                                 &p_sys->i_rate,
314                                                 &p_sys->i_frame_length,
315                                                 &p_sys->i_header_size,
316                                                 &p_sys->i_raw_blocks );
317             if( p_sys->i_frame_size <= 0 )
318             {
319                 msg_Dbg( p_dec, "emulated sync word" );
320                 block_SkipByte( &p_sys->bytestream );
321                 p_sys->i_state = STATE_NOSYNC;
322                 break;
323             }
324
325             p_sys->i_state = STATE_NEXT_SYNC;
326
327         case STATE_NEXT_SYNC:
328             /* TODO: If p_block == NULL, flush the buffer without checking the
329              * next sync word */
330
331             /* Check if next expected frame contains the sync word */
332             if( block_PeekOffsetBytes( &p_sys->bytestream, p_sys->i_frame_size
333                                        + p_sys->i_header_size, p_header, 2 )
334                 != VLC_SUCCESS )
335             {
336                 /* Need more data */
337                 return NULL;
338             }
339
340             if( p_header[0] != 0xff || (p_header[1] & 0xf6) != 0xf0 )
341             {
342                 msg_Dbg( p_dec, "emulated sync word "
343                          "(no sync on following frame)" );
344                 p_sys->i_state = STATE_NOSYNC;
345                 block_SkipByte( &p_sys->bytestream );
346                 break;
347             }
348
349             p_sys->i_state = STATE_SEND_DATA;
350             break;
351
352         case STATE_GET_DATA:
353             /* Make sure we have enough data.
354              * (Not useful if we went through NEXT_SYNC) */
355             if( block_WaitBytes( &p_sys->bytestream, p_sys->i_frame_size +
356                                  p_sys->i_header_size) != VLC_SUCCESS )
357             {
358                 /* Need more data */
359                 return NULL;
360             }
361             p_sys->i_state = STATE_SEND_DATA;
362
363         case STATE_SEND_DATA:
364             if( !(p_buf = GetOutBuffer( p_dec, &p_out_buffer )) )
365             {
366                 //p_dec->b_error = VLC_TRUE;
367                 return NULL;
368             }
369
370             /* When we reach this point we already know we have enough
371              * data available. */
372
373             /* Skip the ADTS header */
374             block_SkipBytes( &p_sys->bytestream, p_sys->i_header_size );
375
376             /* Copy the whole frame into the buffer */
377             block_GetBytes( &p_sys->bytestream, p_buf, p_sys->i_frame_size );
378
379             /* Make sure we don't reuse the same pts twice */
380             if( p_sys->i_pts == p_sys->bytestream.p_block->i_pts )
381                 p_sys->i_pts = p_sys->bytestream.p_block->i_pts = 0;
382
383             /* So p_block doesn't get re-added several times */
384             *pp_block = block_BytestreamPop( &p_sys->bytestream );
385
386             p_sys->i_state = STATE_NOSYNC;
387
388             return p_out_buffer;
389         }
390     }
391
392     return NULL;
393 }
394
395 /*****************************************************************************
396  * GetOutBuffer:
397  *****************************************************************************/
398 static uint8_t *GetOutBuffer( decoder_t *p_dec, void **pp_out_buffer )
399 {
400     decoder_sys_t *p_sys = p_dec->p_sys;
401     block_t *p_block;
402
403     if( p_dec->fmt_out.audio.i_rate != p_sys->i_rate )
404     {
405         msg_Info( p_dec, "AAC channels: %d samplerate: %d",
406                   p_sys->i_channels, p_sys->i_rate );
407
408         aout_DateInit( &p_sys->end_date, p_sys->i_rate );
409         aout_DateSet( &p_sys->end_date, p_sys->i_pts );
410     }
411
412     p_dec->fmt_out.audio.i_rate     = p_sys->i_rate;
413     p_dec->fmt_out.audio.i_channels = p_sys->i_channels;
414     p_dec->fmt_out.audio.i_bytes_per_frame = p_sys->i_frame_size;
415     p_dec->fmt_out.audio.i_frame_length = p_sys->i_frame_length;
416
417 #if 0
418     p_dec->fmt_out.audio.i_original_channels = p_sys->i_channels_conf;
419     p_dec->fmt_out.audio.i_physical_channels =
420         p_sys->i_channels_conf & AOUT_CHAN_PHYSMASK;
421 #endif
422
423     p_block = block_New( p_dec, p_sys->i_frame_size );
424     if( p_block == NULL ) return NULL;
425
426     p_block->i_pts = p_block->i_dts = aout_DateGet( &p_sys->end_date );
427
428     p_block->i_length = aout_DateIncrement( &p_sys->end_date,
429                             p_sys->i_frame_length ) - p_block->i_pts;
430
431     *pp_out_buffer = p_block;
432     return p_block->p_buffer;
433 }
434
435 /*****************************************************************************
436  * ClosePacketizer: clean up the packetizer
437  *****************************************************************************/
438 static void ClosePacketizer( vlc_object_t *p_this )
439 {
440     decoder_t *p_dec = (decoder_t *)p_this;
441     decoder_sys_t *p_sys = p_dec->p_sys;
442
443     block_BytestreamRelease( &p_sys->bytestream );
444
445     free( p_dec->p_sys );
446 }
447
448 /*****************************************************************************
449  * ADTSSyncInfo: parse MPEG 4 audio ADTS sync info
450  *****************************************************************************/
451 static int ADTSSyncInfo( decoder_t * p_dec, const byte_t * p_buf,
452                          unsigned int * pi_channels,
453                          unsigned int * pi_sample_rate,
454                          unsigned int * pi_frame_length,
455                          unsigned int * pi_header_size,
456                          unsigned int * pi_raw_blocks_in_frame )
457 {
458     int i_id, i_profile, i_sample_rate_idx, i_frame_size;
459     vlc_bool_t b_crc;
460
461     /* Fixed header between frames */
462     i_id = ( (p_buf[1] >> 3) & 0x01 ) ? 2 : 4;
463     b_crc = !(p_buf[1] & 0x01);
464     i_profile = p_buf[2] >> 6;
465     i_sample_rate_idx = (p_buf[2] >> 2) & 0x0f;
466     *pi_sample_rate = i_sample_rates[i_sample_rate_idx];
467     *pi_channels = ((p_buf[2] & 0x01) << 2) | ((p_buf[3] >> 6) & 0x03);
468
469     /* Variable header */
470     i_frame_size = ((p_buf[3] & 0x03) << 11) | (p_buf[4] << 3) |
471                    ((p_buf[5] >> 5) & 0x7);
472     *pi_raw_blocks_in_frame = (p_buf[6] & 0x02) + 1;
473
474     if( !*pi_sample_rate || !*pi_channels || !i_frame_size )
475     {
476         return 0;
477     }
478
479     /* Fixme */
480     *pi_frame_length = 1024;
481
482     /* Build the decoder specific info header */
483     if( !p_dec->fmt_out.i_extra )
484     {
485         p_dec->fmt_out.i_extra = 2;
486         p_dec->fmt_out.p_extra = malloc( 2 );
487         ((uint8_t *)p_dec->fmt_out.p_extra)[0] =
488             (i_profile + 1) << 3 | (i_sample_rate_idx >> 1);
489         ((uint8_t *)p_dec->fmt_out.p_extra)[1] =
490             ((i_sample_rate_idx & 0x01) << 7) | (*pi_channels <<3);
491     }
492
493     /* ADTS header length */
494     *pi_header_size = b_crc ? 9 : 7;
495
496     return i_frame_size - *pi_header_size;
497 }