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