]> git.sesse.net Git - vlc/blob - modules/packetizer/mpeg4audio.c
LGPL
[vlc] / modules / packetizer / mpeg4audio.c
1 /*****************************************************************************
2  * mpeg4audio.c: parse and packetize an MPEG 4 audio stream
3  *****************************************************************************
4  * Copyright (C) 2001, 2002, 2006 VLC authors and VideoLAN
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 it
11  * under the terms of the GNU Lesser General Public License as published by
12  * the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public License
21  * along with this program; if not, write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28
29 #ifdef HAVE_CONFIG_H
30 # include "config.h"
31 #endif
32
33 #include <vlc_common.h>
34 #include <vlc_plugin.h>
35 #include <vlc_codec.h>
36 #include <vlc_block.h>
37 #include <vlc_bits.h>
38
39 #include <vlc_block_helper.h>
40 #include "packetizer_helper.h"
41
42 #include <assert.h>
43
44 /* AAC Config in ES:
45  *
46  * AudioObjectType          5 bits
47  * samplingFrequencyIndex   4 bits
48  * if (samplingFrequencyIndex == 0xF)
49  *  samplingFrequency   24 bits
50  * channelConfiguration     4 bits
51  * GA_SpecificConfig
52  *  FrameLengthFlag         1 bit 1024 or 960
53  *  DependsOnCoreCoder      1 bit (always 0)
54  *  ExtensionFlag           1 bit (always 0)
55  */
56
57 /*****************************************************************************
58  * decoder_sys_t : decoder descriptor
59  *****************************************************************************/
60 typedef struct
61 {
62     int i_object_type;
63     int i_samplerate;
64     int i_channel;
65     int i_sbr;          // 0: no sbr, 1: sbr, -1: unknown
66     int i_ps;           // 0: no ps,  1: ps,  -1: unknown
67
68     struct
69     {
70         int i_object_type;
71         int i_samplerate;
72     } extension;
73
74     /* GASpecific */
75     int i_frame_length;   // 1024 or 960
76
77 } mpeg4_cfg_t;
78
79 #define LATM_MAX_EXTRA_SIZE 64
80 typedef struct
81 {
82     int i_program;
83     int i_layer;
84
85     int i_frame_length_type;
86     int i_frame_length;         // type 1
87     int i_frame_length_index;   // type 3 4 5 6 7
88
89     mpeg4_cfg_t cfg;
90
91     /* Raw configuration */
92     int     i_extra;
93     uint8_t extra[LATM_MAX_EXTRA_SIZE];
94
95 } latm_stream_t;
96
97 #define LATM_MAX_LAYER (8)
98 #define LATM_MAX_PROGRAM (16)
99 typedef struct
100 {
101     int b_same_time_framing;
102     int i_sub_frames;
103     int i_programs;
104
105     int pi_layers[LATM_MAX_PROGRAM];
106
107     int pi_stream[LATM_MAX_PROGRAM][LATM_MAX_LAYER];
108
109     int i_streams;
110     latm_stream_t stream[LATM_MAX_PROGRAM*LATM_MAX_LAYER];
111
112     int i_other_data;
113     int i_crc;  /* -1 if not set */
114 } latm_mux_t;
115
116 struct decoder_sys_t
117 {
118     /*
119      * Input properties
120      */
121     int i_state;
122     int i_type;
123
124     block_bytestream_t bytestream;
125
126     /*
127      * Common properties
128      */
129     date_t  end_date;
130     mtime_t i_pts;
131
132     int i_frame_size;
133     unsigned int i_channels;
134     unsigned int i_rate, i_frame_length, i_header_size;
135
136     int i_input_rate;
137
138     /* LOAS */
139     bool b_latm_cfg;
140     latm_mux_t latm;
141 };
142
143 enum {
144     TYPE_NONE,
145     TYPE_RAW,
146     TYPE_ADTS,
147     TYPE_LOAS
148 };
149
150 static const int pi_sample_rates[16] =
151 {
152     96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
153     16000, 12000, 11025, 8000,  7350,  0,     0,     0
154 };
155
156 #define ADTS_HEADER_SIZE 9
157 #define LOAS_HEADER_SIZE 3
158
159 /****************************************************************************
160  * Local prototypes
161  ****************************************************************************/
162 static int  OpenPacketizer( vlc_object_t * );
163 static void ClosePacketizer( vlc_object_t * );
164
165 static block_t *PacketizeRawBlock    ( decoder_t *, block_t ** );
166 static block_t *PacketizeStreamBlock( decoder_t *, block_t ** );
167
168 /*****************************************************************************
169  * Module descriptor
170  *****************************************************************************/
171 vlc_module_begin ()
172     set_category( CAT_SOUT )
173     set_subcategory( SUBCAT_SOUT_PACKETIZER )
174     set_description( N_("MPEG4 audio packetizer") )
175     set_capability( "packetizer", 50 )
176     set_callbacks( OpenPacketizer, ClosePacketizer )
177 vlc_module_end ()
178
179 /*****************************************************************************
180  * OpenPacketizer: probe the packetizer and return score
181  *****************************************************************************/
182 static int OpenPacketizer( vlc_object_t *p_this )
183 {
184     decoder_t *p_dec = (decoder_t*)p_this;
185     decoder_sys_t *p_sys;
186
187     if( p_dec->fmt_in.i_codec != VLC_CODEC_MP4A )
188     {
189         return VLC_EGENERIC;
190     }
191
192     /* Allocate the memory needed to store the decoder's structure */
193     if( ( p_dec->p_sys = p_sys =
194           (decoder_sys_t *)malloc(sizeof(decoder_sys_t)) ) == NULL )
195         return VLC_ENOMEM;
196
197     /* Misc init */
198     p_sys->i_state = STATE_NOSYNC;
199     date_Set( &p_sys->end_date, 0 );
200     block_BytestreamInit( &p_sys->bytestream );
201     p_sys->b_latm_cfg = false;
202
203     /* Set output properties */
204     p_dec->fmt_out.i_cat = AUDIO_ES;
205     p_dec->fmt_out.i_codec = VLC_CODEC_MP4A;
206
207     msg_Dbg( p_dec, "running MPEG4 audio packetizer" );
208
209     if( p_dec->fmt_in.i_extra > 0 )
210     {
211         uint8_t *p_config = (uint8_t*)p_dec->fmt_in.p_extra;
212         int     i_index;
213
214         i_index = ( ( p_config[0] << 1 ) | ( p_config[1] >> 7 ) ) & 0x0f;
215         if( i_index != 0x0f )
216         {
217             p_dec->fmt_out.audio.i_rate = pi_sample_rates[i_index];
218             p_dec->fmt_out.audio.i_frame_length =
219                 (( p_config[1] >> 2 ) & 0x01) ? 960 : 1024;
220         }
221         else
222         {
223             p_dec->fmt_out.audio.i_rate = ( ( p_config[1] & 0x7f ) << 17 ) |
224                 ( p_config[2] << 9 ) | ( p_config[3] << 1 ) |
225                 ( p_config[4] >> 7 );
226             p_dec->fmt_out.audio.i_frame_length =
227                 (( p_config[4] >> 2 ) & 0x01) ? 960 : 1024;
228         }
229
230         p_dec->fmt_out.audio.i_channels =
231             (p_config[i_index == 0x0f ? 4 : 1] >> 3) & 0x0f;
232
233         msg_Dbg( p_dec, "AAC %dHz %d samples/frame",
234                  p_dec->fmt_out.audio.i_rate,
235                  p_dec->fmt_out.audio.i_frame_length );
236
237         date_Init( &p_sys->end_date, p_dec->fmt_out.audio.i_rate, 1 );
238
239         p_dec->fmt_out.i_extra = p_dec->fmt_in.i_extra;
240         p_dec->fmt_out.p_extra = malloc( p_dec->fmt_in.i_extra );
241         if( !p_dec->fmt_out.p_extra )
242         {
243             p_dec->fmt_out.i_extra = 0;
244             return VLC_ENOMEM;
245         }
246         memcpy( p_dec->fmt_out.p_extra, p_dec->fmt_in.p_extra,
247                 p_dec->fmt_in.i_extra );
248
249         /* Set callback */
250         p_dec->pf_packetize = PacketizeRawBlock;
251         p_sys->i_type = TYPE_RAW;
252     }
253     else
254     {
255         msg_Dbg( p_dec, "no decoder specific info, must be an ADTS or LOAS stream" );
256
257         date_Init( &p_sys->end_date, p_dec->fmt_in.audio.i_rate, 1 );
258
259         /* We will try to create a AAC Config from adts/loas */
260         p_dec->fmt_out.i_extra = 0;
261         p_dec->fmt_out.p_extra = NULL;
262
263         /* Set callback */
264         p_dec->pf_packetize = PacketizeStreamBlock;
265         p_sys->i_type = TYPE_NONE;
266     }
267
268     return VLC_SUCCESS;
269 }
270
271 /****************************************************************************
272  * PacketizeRawBlock: the whole thing
273  ****************************************************************************
274  * This function must be fed with complete frames.
275  ****************************************************************************/
276 static block_t *PacketizeRawBlock( decoder_t *p_dec, block_t **pp_block )
277 {
278     decoder_sys_t *p_sys = p_dec->p_sys;
279     block_t *p_block;
280
281     if( !pp_block || !*pp_block ) return NULL;
282
283     if( (*pp_block)->i_flags&(BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED) )
284     {
285         date_Set( &p_sys->end_date, 0 );
286         block_Release( *pp_block );
287         return NULL;
288     }
289
290     p_block = *pp_block;
291     *pp_block = NULL; /* Don't reuse this block */
292
293     if( !date_Get( &p_sys->end_date ) && p_block->i_pts <= VLC_TS_INVALID )
294     {
295         /* We've just started the stream, wait for the first PTS. */
296         block_Release( p_block );
297         return NULL;
298     }
299     else if( p_block->i_pts > VLC_TS_INVALID &&
300              p_block->i_pts != date_Get( &p_sys->end_date ) )
301     {
302         date_Set( &p_sys->end_date, p_block->i_pts );
303     }
304
305     p_block->i_pts = p_block->i_dts = date_Get( &p_sys->end_date );
306
307     p_block->i_length = date_Increment( &p_sys->end_date,
308         p_dec->fmt_out.audio.i_frame_length ) - p_block->i_pts;
309
310     return p_block;
311 }
312
313 /****************************************************************************
314  * ADTS helpers
315  ****************************************************************************/
316 static int ADTSSyncInfo( decoder_t * p_dec, const uint8_t * p_buf,
317                          unsigned int * pi_channels,
318                          unsigned int * pi_sample_rate,
319                          unsigned int * pi_frame_length,
320                          unsigned int * pi_header_size )
321 {
322     int i_profile, i_sample_rate_idx, i_frame_size;
323     bool b_crc;
324
325     /* Fixed header between frames */
326     //int i_id = ( (p_buf[1] >> 3) & 0x01) ? 2 : 4; /* MPEG-2 or 4 */
327     b_crc = !(p_buf[1] & 0x01);
328     i_profile = p_buf[2] >> 6;
329     i_sample_rate_idx = (p_buf[2] >> 2) & 0x0f;
330     *pi_sample_rate = pi_sample_rates[i_sample_rate_idx];
331     //private_bit = (p_buf[2] >> 1) & 0x01;
332     *pi_channels = ((p_buf[2] & 0x01) << 2) | ((p_buf[3] >> 6) & 0x03);
333     //original_copy = (p_buf[3] >> 5) & 0x01;
334     //home = (p_buf[3] >> 4) & 0x01;
335
336     /* Variable header */
337     //copyright_id_bit = (p_buf[3] >> 3) & 0x01;
338     //copyright_id_start = (p_buf[3] >> 2) & 0x01;
339     i_frame_size = ((p_buf[3] & 0x03) << 11) | (p_buf[4] << 3) |
340                    ((p_buf[5] >> 5) /*& 0x7*/);
341     //uint16_t buffer_fullness = ((p_buf[5] & 0x1f) << 6) | (p_buf[6] >> 2);
342     unsigned short i_raw_blocks_in_frame = p_buf[6] & 0x03;
343
344     if( !*pi_sample_rate || !*pi_channels || !i_frame_size )
345     {
346         msg_Warn( p_dec, "Invalid ADTS header" );
347         return 0;
348     }
349
350     *pi_frame_length = 1024;
351
352     if( i_raw_blocks_in_frame == 0 )
353     {
354         if( b_crc )
355         {
356             msg_Warn( p_dec, "ADTS CRC not supported" );
357             //uint16_t crc = (p_buf[7] << 8) | p_buf[8];
358         }
359     }
360     else
361     {
362         msg_Err( p_dec, "Multiple blocks per frame in ADTS not supported" );
363         return 0;
364 #if 0
365         int i;
366         const uint8_t *p_pos = p_buf + 7;
367         uint16_t crc_block;
368         uint16_t i_block_pos[3];
369         if( b_crc )
370         {
371             for( i = 0 ; i < i_raw_blocks_in_frame ; i++ )
372             {   /* the 1st block's position is known ... */
373                 i_block_pos[i] = (*p_pos << 8) | *(p_pos+1);
374                 p_pos += 2;
375             }
376             crc_block = (*p_pos << 8) | *(p_pos+1);
377             p_pos += 2;
378         }
379         for( i = 0 ; i <= i_raw_blocks_in_frame ; i++ )
380         {
381             //read 1 block
382             if( b_crc )
383             {
384                 msg_Err( p_dec, "ADTS CRC not supported" );
385                 //uint16_t crc = (*p_pos << 8) | *(p_pos+1);
386                 //p_pos += 2;
387             }
388         }
389 #endif
390     }
391
392
393     /* Build the decoder specific info header */
394     if( !p_dec->fmt_out.i_extra )
395     {
396         p_dec->fmt_out.p_extra = malloc( 2 );
397         if( !p_dec->fmt_out.p_extra )
398         {
399             p_dec->fmt_out.i_extra = 0;
400             return 0;
401         }
402         p_dec->fmt_out.i_extra = 2;
403         ((uint8_t *)p_dec->fmt_out.p_extra)[0] =
404             (i_profile + 1) << 3 | (i_sample_rate_idx >> 1);
405         ((uint8_t *)p_dec->fmt_out.p_extra)[1] =
406             ((i_sample_rate_idx & 0x01) << 7) | (*pi_channels <<3);
407     }
408
409     /* ADTS header length */
410     *pi_header_size = b_crc ? 9 : 7;
411
412     return i_frame_size - *pi_header_size;
413 }
414
415 /****************************************************************************
416  * LOAS helpers
417  ****************************************************************************/
418 static int LOASSyncInfo( uint8_t p_header[LOAS_HEADER_SIZE], unsigned int *pi_header_size )
419 {
420     *pi_header_size = 3;
421     return ( ( p_header[1] & 0x1f ) << 8 ) + p_header[2];
422 }
423
424 static int Mpeg4GAProgramConfigElement( bs_t *s )
425 {
426     /* TODO compute channels count ? */
427     int i_tag = bs_read( s, 4 );
428     if( i_tag != 0x05 )
429         return -1;
430     bs_skip( s, 2 + 4 ); // object type + sampling index
431     int i_num_front = bs_read( s, 4 );
432     int i_num_side = bs_read( s, 4 );
433     int i_num_back = bs_read( s, 4 );
434     int i_num_lfe = bs_read( s, 2 );
435     int i_num_assoc_data = bs_read( s, 3 );
436     int i_num_valid_cc = bs_read( s, 4 );
437
438     if( bs_read1(s) )
439         bs_skip( s, 4 ); // mono downmix
440     if( bs_read1(s) )
441         bs_skip( s, 4 ); // stereo downmix
442     if( bs_read1(s) )
443         bs_skip( s, 2+1 ); // matrix downmix + pseudo_surround
444
445     bs_skip( s, i_num_front * (1+4) );
446     bs_skip( s, i_num_side * (1+4) );
447     bs_skip( s, i_num_back * (1+4) );
448     bs_skip( s, i_num_lfe * (4) );
449     bs_skip( s, i_num_assoc_data * (4) );
450     bs_skip( s, i_num_valid_cc * (5) );
451     bs_align( s );
452     int i_comment = bs_read( s, 8 );
453     bs_skip( s, i_comment * 8 );
454     return 0;
455 }
456
457 static int Mpeg4GASpecificConfig( mpeg4_cfg_t *p_cfg, bs_t *s )
458 {
459     p_cfg->i_frame_length = bs_read1(s) ? 960 : 1024;
460
461     if( bs_read1( s ) )     // depend on core coder
462         bs_skip( s, 14 );   // core coder delay
463
464     int i_extension_flag = bs_read1( s );
465     if( p_cfg->i_channel == 0 )
466     {
467         Mpeg4GAProgramConfigElement( s );
468     }
469     if( p_cfg->i_object_type == 6 || p_cfg->i_object_type == 20 )
470         bs_skip( s, 3 );    // layer
471
472     if( i_extension_flag )
473     {
474         if( p_cfg->i_object_type == 22 )
475         {
476             bs_skip( s, 5 + 11 );   // numOfSubFrame + layer length
477         }
478         if( p_cfg->i_object_type == 17 || p_cfg->i_object_type == 19 ||
479             p_cfg->i_object_type == 20 || p_cfg->i_object_type == 23 )
480         {
481             bs_skip( s, 1+1+1 );    // ER data : section scale spectral */
482         }
483         if( bs_read1( s ) )     // extension 3
484             fprintf( stderr, "Mpeg4GASpecificConfig: error 1\n" );
485     }
486     return 0;
487 }
488
489 static int Mpeg4ReadAudioObjectType( bs_t *s )
490 {
491     int i_type = bs_read( s, 5 );
492     if( i_type == 31 )
493         i_type = 32 + bs_read( s, 6 );
494     return i_type;
495 }
496
497 static int Mpeg4ReadAudioSamplerate( bs_t *s )
498 {
499     int i_index = bs_read( s, 4 );
500     if( i_index != 0x0f )
501         return pi_sample_rates[i_index];
502     return bs_read( s, 24 );
503 }
504
505 static int Mpeg4ReadAudioSpecificInfo( mpeg4_cfg_t *p_cfg, int *pi_extra, uint8_t *p_extra, bs_t *s, int i_max_size )
506 {
507 #if 0
508     static const char *ppsz_otype[] = {
509         "NULL",
510         "AAC Main", "AAC LC", "AAC SSR", "AAC LTP", "SBR", "AAC Scalable",
511         "TwinVQ",
512         "CELP", "HVXC",
513         "Reserved", "Reserved",
514         "TTSI",
515         "Main Synthetic", "Wavetables Synthesis", "General MIDI",
516         "Algorithmic Synthesis and Audio FX",
517         "ER AAC LC",
518         "Reserved",
519         "ER AAC LTP", "ER AAC Scalable", "ER TwinVQ", "ER BSAC", "ER AAC LD",
520         "ER CELP", "ER HVXC", "ER HILN", "ER Parametric",
521         "SSC",
522         "PS", "Reserved", "Escape",
523         "Layer 1", "Layer 2", "Layer 3",
524         "DST",
525     };
526 #endif
527     const int i_pos_start = bs_pos( s );
528     bs_t s_sav = *s;
529     int i_bits;
530     int i;
531
532     memset( p_cfg, 0, sizeof(*p_cfg) );
533     *pi_extra = 0;
534
535     p_cfg->i_object_type = Mpeg4ReadAudioObjectType( s );
536     p_cfg->i_samplerate = Mpeg4ReadAudioSamplerate( s );
537
538     p_cfg->i_channel = bs_read( s, 4 );
539     if( p_cfg->i_channel == 7 )
540         p_cfg->i_channel = 8; // 7.1
541     else if( p_cfg->i_channel >= 8 )
542         p_cfg->i_channel = -1;
543
544     p_cfg->i_sbr = -1;
545     p_cfg->i_ps  = -1;
546     p_cfg->extension.i_object_type = 0;
547     p_cfg->extension.i_samplerate = 0;
548     if( p_cfg->i_object_type == 5 || p_cfg->i_object_type == 29 )
549     {
550         p_cfg->i_sbr = 1;
551         if( p_cfg->i_object_type == 29 )
552            p_cfg->i_ps = 1;
553         p_cfg->extension.i_object_type = 5;
554         p_cfg->extension.i_samplerate = Mpeg4ReadAudioSamplerate( s );
555
556         p_cfg->i_object_type = Mpeg4ReadAudioObjectType( s );
557     }
558
559     switch( p_cfg->i_object_type )
560     {
561     case 1: case 2: case 3: case 4:
562     case 6: case 7:
563     case 17: case 19: case 20: case 21: case 22: case 23:
564         Mpeg4GASpecificConfig( p_cfg, s );
565         break;
566     case 8:
567         // CelpSpecificConfig();
568         break;
569     case 9:
570         // HvxcSpecificConfig();
571         break;
572     case 12:
573         // TTSSSpecificConfig();
574         break;
575     case 13: case 14: case 15: case 16:
576         // StructuredAudioSpecificConfig();
577         break;
578     case 24:
579         // ERCelpSpecificConfig();
580         break;
581     case 25:
582         // ERHvxcSpecificConfig();
583         break;
584     case 26: case 27:
585         // ParametricSpecificConfig();
586         break;
587     case 28:
588         // SSCSpecificConfig();
589         break;
590     case 32: case 33: case 34:
591         // MPEG_1_2_SpecificConfig();
592         break;
593     case 35:
594         // DSTSpecificConfig();
595         break;
596     case 36:
597         // ALSSpecificConfig();
598         break;
599     default:
600         // error
601         break;
602     }
603     switch( p_cfg->i_object_type )
604     {
605     case 17: case 19: case 20: case 21: case 22: case 23:
606     case 24: case 25: case 26: case 27:
607     {
608         int epConfig = bs_read( s, 2 );
609         if( epConfig == 2 || epConfig == 3 )
610         {
611             //ErrorProtectionSpecificConfig();
612         }
613         if( epConfig == 3 )
614         {
615             int directMapping = bs_read1( s );
616             if( directMapping )
617             {
618                 // tbd ...
619             }
620         }
621         break;
622     }
623     default:
624         break;
625     }
626
627     if( p_cfg->extension.i_object_type != 5 && i_max_size > 0 && i_max_size - (bs_pos(s) - i_pos_start) >= 16 &&
628         bs_read( s, 11 ) == 0x2b7 )
629     {
630         p_cfg->extension.i_object_type = Mpeg4ReadAudioObjectType( s );
631         if( p_cfg->extension.i_object_type == 5 )
632         {
633             p_cfg->i_sbr  = bs_read1( s );
634             if( p_cfg->i_sbr == 1 )
635             {
636                 p_cfg->extension.i_samplerate = Mpeg4ReadAudioSamplerate( s );
637                 if( i_max_size > 0 && i_max_size - (bs_pos(s) - i_pos_start) >= 12 && bs_read( s, 11 ) == 0x548 )
638                 {
639                    p_cfg->i_ps = bs_read1( s );
640                 }
641             }
642         }
643     }
644
645     //fprintf( stderr, "Mpeg4ReadAudioSpecificInfo: t=%s(%d)f=%d c=%d sbr=%d\n",
646     //         ppsz_otype[p_cfg->i_object_type], p_cfg->i_object_type, p_cfg->i_samplerate, p_cfg->i_channel, p_cfg->i_sbr );
647
648     i_bits = bs_pos(s) - i_pos_start;
649
650     *pi_extra = __MIN( ( i_bits + 7 ) / 8, LATM_MAX_EXTRA_SIZE );
651     for( i = 0; i < *pi_extra; i++ )
652     {
653         const int i_read = __MIN( 8, i_bits - 8*i );
654         p_extra[i] = bs_read( &s_sav, i_read ) << (8-i_read);
655     }
656     return i_bits;
657 }
658
659 static int LatmGetValue( bs_t *s )
660 {
661     int i_bytes = bs_read( s, 2 );
662     int v = 0;
663     int i;
664     for( i = 0; i < i_bytes; i++ )
665         v = (v << 8) + bs_read( s, 8 );
666
667     return v;
668 }
669
670 static int LatmReadStreamMuxConfiguration( latm_mux_t *m, bs_t *s )
671 {
672     int i_mux_version;
673     int i_mux_versionA;
674     int i_program;
675
676     i_mux_version = bs_read( s, 1 );
677     i_mux_versionA = 0;
678     if( i_mux_version )
679         i_mux_versionA = bs_read( s, 1 );
680
681     if( i_mux_versionA != 0 ) /* support only A=0 */
682         return -1;
683
684     memset( m, 0, sizeof(*m) );
685
686     if( i_mux_versionA == 0 )
687     {
688         if( i_mux_version == 1 )
689         {
690             LatmGetValue(s); /* taraBufferFullness */
691         }
692     }
693
694     m->b_same_time_framing = bs_read1( s );
695     m->i_sub_frames = 1 + bs_read( s, 6 );
696     m->i_programs = 1 + bs_read( s, 4 );
697
698     for( i_program = 0; i_program < m->i_programs; i_program++ )
699     {
700         int i_layer;
701
702         m->pi_layers[i_program] = 1+bs_read( s, 3 );
703
704         for( i_layer = 0; i_layer < m->pi_layers[i_program]; i_layer++ )
705         {
706             latm_stream_t *st = &m->stream[m->i_streams];
707             bool b_previous_cfg;
708
709             m->pi_stream[i_program][i_layer] = m->i_streams;
710             st->i_program = i_program;
711             st->i_layer = i_layer;
712
713             b_previous_cfg = false;
714             if( i_program != 0 || i_layer != 0 )
715                 b_previous_cfg = bs_read1( s );
716
717             if( b_previous_cfg )
718             {
719                 assert( m->i_streams > 0 );
720                 st->cfg = m->stream[m->i_streams-1].cfg;
721             }
722             else
723             {
724                 int i_cfg_size = 0;
725                 if( i_mux_version == 1 )
726                     i_cfg_size = LatmGetValue(s);
727                 i_cfg_size -= Mpeg4ReadAudioSpecificInfo( &st->cfg, &st->i_extra, st->extra, s, i_cfg_size );
728                 if( i_cfg_size > 0 )
729                     bs_skip( s, i_cfg_size );
730             }
731
732             st->i_frame_length_type = bs_read( s, 3 );
733             switch( st->i_frame_length_type )
734             {
735             case 0:
736             {
737                 bs_skip( s, 8 ); /* latmBufferFullnes */
738                 if( !m->b_same_time_framing )
739                 {
740                     if( st->cfg.i_object_type == 6 || st->cfg.i_object_type == 20 ||
741                         st->cfg.i_object_type == 8 || st->cfg.i_object_type == 24 )
742                     {
743                         bs_skip( s, 6 ); /* eFrameOffset */
744                     }
745                 }
746                 break;
747             }
748             case 1:
749                 st->i_frame_length = bs_read( s, 9 );
750                 break;
751             case 3: case 4: case 5:
752                 st->i_frame_length_index = bs_read( s, 6 ); // celp
753                 break;
754             case 6: case 7:
755                 st->i_frame_length_index = bs_read( s, 1 ); // hvxc
756             default:
757                 break;
758             }
759             /* Next stream */
760             m->i_streams++;
761         }
762     }
763
764     /* other data */
765     if( bs_read1( s ) )
766     {
767         if( i_mux_version == 1 )
768         {
769             m->i_other_data = LatmGetValue( s );
770         }
771         else
772         {
773             int b_continue;
774             do {
775                 b_continue = bs_read1(s);
776                 m->i_other_data = (m->i_other_data << 8) + bs_read( s, 8 );
777             } while( b_continue );
778         }
779     }
780
781     /* crc */
782     m->i_crc = -1;
783     if( bs_read1( s ) )
784         m->i_crc = bs_read( s, 8 );
785
786     return 0;
787 }
788
789 static int LOASParse( decoder_t *p_dec, uint8_t *p_buffer, int i_buffer )
790 {
791     decoder_sys_t *p_sys = p_dec->p_sys;
792     bs_t s;
793     int i_sub;
794     int i_accumulated = 0;
795
796     bs_init( &s, p_buffer, i_buffer );
797
798     /* Read the stream mux configuration if present */
799     if( !bs_read1( &s ) )
800     {
801         if( !LatmReadStreamMuxConfiguration( &p_sys->latm, &s ) &&
802             p_sys->latm.i_streams > 0 )
803         {
804             const latm_stream_t *st = &p_sys->latm.stream[0];
805
806             p_sys->i_channels = st->cfg.i_channel;
807             p_sys->i_rate = st->cfg.i_samplerate;
808             p_sys->i_frame_length = st->cfg.i_frame_length;
809
810             if ( p_sys->i_channels > 0 && p_sys->i_rate > 0 &&
811                  p_sys->i_frame_length > 0 )
812             {
813                 /* FIXME And if it changes ? */
814                 if( !p_dec->fmt_out.i_extra && st->i_extra > 0 )
815                 {
816                     p_dec->fmt_out.i_extra = st->i_extra;
817                     p_dec->fmt_out.p_extra = malloc( st->i_extra );
818                     if( !p_dec->fmt_out.p_extra )
819                     {
820                         p_dec->fmt_out.i_extra = 0;
821                         return 0;
822                     }
823                     memcpy( p_dec->fmt_out.p_extra, st->extra, st->i_extra );
824                 }
825                 p_sys->b_latm_cfg = true;
826             }
827         }
828     }
829     /* Wait for the configuration */
830     if( !p_sys->b_latm_cfg )
831         return 0;
832
833     /* FIXME do we need to split the subframe into independent packet ? */
834     if( p_sys->latm.i_sub_frames > 1 )
835         msg_Err( p_dec, "latm sub frames not yet supported, please send a sample" );
836
837     for( i_sub = 0; i_sub < p_sys->latm.i_sub_frames; i_sub++ )
838     {
839         int pi_payload[LATM_MAX_PROGRAM][LATM_MAX_LAYER];
840         if( p_sys->latm.b_same_time_framing )
841         {
842             int i_program;
843             /* Payload length */
844             for( i_program = 0; i_program < p_sys->latm.i_programs; i_program++ )
845             {
846                 int i_layer;
847                 for( i_layer = 0; i_layer < p_sys->latm.pi_layers[i_program]; i_layer++ )
848                 {
849                     latm_stream_t *st = &p_sys->latm.stream[p_sys->latm.pi_stream[i_program][i_layer]];
850                     if( st->i_frame_length_type == 0 )
851                     {
852                         int i_payload = 0;
853                         for( ;; )
854                         {
855                             int i_tmp = bs_read( &s, 8 );
856                             i_payload += i_tmp;
857                             if( i_tmp != 255 )
858                                 break;
859                         }
860                         pi_payload[i_program][i_layer] = i_payload;
861                     }
862                     else if( st->i_frame_length_type == 1 )
863                     {
864                         pi_payload[i_program][i_layer] = st->i_frame_length / 8; /* XXX not correct */
865                     }
866                     else if( ( st->i_frame_length_type == 3 ) ||
867                              ( st->i_frame_length_type == 5 ) ||
868                              ( st->i_frame_length_type == 7 ) )
869                     {
870                         bs_skip( &s, 2 ); // muxSlotLengthCoded
871                         pi_payload[i_program][i_layer] = 0; /* TODO */
872                     }
873                     else
874                     {
875                         pi_payload[i_program][i_layer] = 0; /* TODO */
876                     }
877                 }
878             }
879             /* Payload Data */
880             for( i_program = 0; i_program < p_sys->latm.i_programs; i_program++ )
881             {
882                 int i_layer;
883                 int i;
884                 for( i_layer = 0; i_layer < p_sys->latm.pi_layers[i_program]; i_layer++ )
885                 {
886                     /* XXX we only extract 1 stream */
887                     if( i_program != 0 || i_layer != 0 )
888                         break;
889
890                     if( pi_payload[i_program][i_layer] <= 0 )
891                         continue;
892
893                     /* FIXME that's slow (and a bit ugly to write in place) */
894                     for( i = 0; i < pi_payload[i_program][i_layer]; i++ )
895                         p_buffer[i_accumulated++] = bs_read( &s, 8 );
896                 }
897             }
898         }
899         else
900         {
901             const int i_chunks = bs_read( &s, 4 );
902             int pi_program[16];
903             int pi_layer[16];
904             int i_chunk;
905
906             msg_Err( p_dec, "latm without same time frameing not yet supported, please send a sample" );
907
908             for( i_chunk = 0; i_chunk < i_chunks; i_chunk++ )
909             {
910                 const int streamIndex = bs_read( &s, 4 );
911                 latm_stream_t *st = &p_sys->latm.stream[streamIndex];
912                 const int i_program = st->i_program;
913                 const int i_layer = st->i_layer;
914
915                 pi_program[i_chunk] = i_program;
916                 pi_layer[i_chunk] = i_layer;
917
918                 if( st->i_frame_length_type == 0 )
919                 {
920                     int i_payload = 0;
921                     for( ;; )
922                     {
923                         int i_tmp = bs_read( &s, 8 );
924                         i_payload += i_tmp;
925                         if( i_tmp != 255 )
926                             break;
927                     }
928                     pi_payload[i_program][i_layer] = i_payload;
929                     bs_skip( &s, 1 ); // auEndFlag
930                 }
931                 else if( st->i_frame_length_type == 1 )
932                 {
933                     pi_payload[i_program][i_layer] = st->i_frame_length / 8; /* XXX not correct */
934                 }
935                 else if( ( st->i_frame_length_type == 3 ) ||
936                          ( st->i_frame_length_type == 5 ) ||
937                          ( st->i_frame_length_type == 7 ) )
938                 {
939                     bs_read( &s, 2 ); // muxSlotLengthCoded
940                 }
941                 else
942                 {
943                 }
944             }
945             for( i_chunk = 0; i_chunk < i_chunks; i_chunk++ )
946             {
947                 //const int i_program = pi_program[i_chunk];
948                 //const int i_layer = pi_layer[i_chunk];
949
950                 /* TODO ? Payload */
951             }
952         }
953     }
954
955     if( p_sys->latm.i_other_data > 0 )
956     {
957         /* Other data XXX we just ignore them */
958     }
959     bs_align( &s );
960
961     return i_accumulated;
962 }
963
964 /****************************************************************************
965  * PacketizeStreamBlock: ADTS/LOAS packetizer
966  ****************************************************************************/
967 static void SetupOutput( decoder_t *p_dec, block_t *p_block );
968 static block_t *PacketizeStreamBlock( decoder_t *p_dec, block_t **pp_block )
969 {
970     decoder_sys_t *p_sys = p_dec->p_sys;
971     uint8_t p_header[ADTS_HEADER_SIZE + LOAS_HEADER_SIZE];
972     block_t *p_out_buffer;
973     uint8_t *p_buf;
974
975     if( !pp_block || !*pp_block ) return NULL;
976
977     if( (*pp_block)->i_flags&(BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED) )
978     {
979         if( (*pp_block)->i_flags&BLOCK_FLAG_CORRUPTED )
980         {
981             p_sys->i_state = STATE_NOSYNC;
982             block_BytestreamEmpty( &p_sys->bytestream );
983         }
984         date_Set( &p_sys->end_date, 0 );
985         block_Release( *pp_block );
986         return NULL;
987     }
988
989     if( !date_Get( &p_sys->end_date ) && (*pp_block)->i_pts <= VLC_TS_INVALID )
990     {
991         /* We've just started the stream, wait for the first PTS. */
992         block_Release( *pp_block );
993         return NULL;
994     }
995
996     block_BytestreamPush( &p_sys->bytestream, *pp_block );
997
998     for( ;; )
999     {
1000         switch( p_sys->i_state )
1001         {
1002
1003         case STATE_NOSYNC:
1004             while( block_PeekBytes( &p_sys->bytestream, p_header, 2 )
1005                    == VLC_SUCCESS )
1006             {
1007                 /* Look for sync word - should be 0xfff(adts) or 0x2b7(loas) */
1008                 if( p_header[0] == 0xff && (p_header[1] & 0xf6) == 0xf0 )
1009                 {
1010                     if( p_sys->i_type != TYPE_ADTS )
1011                         msg_Dbg( p_dec, "detected ADTS format" );
1012
1013                     p_sys->i_state = STATE_SYNC;
1014                     p_sys->i_type = TYPE_ADTS;
1015                     break;
1016                 }
1017                 else if( p_header[0] == 0x56 && (p_header[1] & 0xe0) == 0xe0 )
1018                 {
1019                     if( p_sys->i_type != TYPE_LOAS )
1020                         msg_Dbg( p_dec, "detected LOAS format" );
1021
1022                     p_sys->i_state = STATE_SYNC;
1023                     p_sys->i_type = TYPE_LOAS;
1024                     break;
1025                 }
1026                 block_SkipByte( &p_sys->bytestream );
1027             }
1028             if( p_sys->i_state != STATE_SYNC )
1029             {
1030                 block_BytestreamFlush( &p_sys->bytestream );
1031
1032                 /* Need more data */
1033                 return NULL;
1034             }
1035
1036         case STATE_SYNC:
1037             /* New frame, set the Presentation Time Stamp */
1038             p_sys->i_pts = p_sys->bytestream.p_block->i_pts;
1039             if( p_sys->i_pts > VLC_TS_INVALID &&
1040                 p_sys->i_pts != date_Get( &p_sys->end_date ) )
1041             {
1042                 date_Set( &p_sys->end_date, p_sys->i_pts );
1043             }
1044             p_sys->i_state = STATE_HEADER;
1045             break;
1046
1047         case STATE_HEADER:
1048             if( p_sys->i_type == TYPE_ADTS )
1049             {
1050                 /* Get ADTS frame header (ADTS_HEADER_SIZE bytes) */
1051                 if( block_PeekBytes( &p_sys->bytestream, p_header,
1052                                      ADTS_HEADER_SIZE ) != VLC_SUCCESS )
1053                 {
1054                     /* Need more data */
1055                     return NULL;
1056                 }
1057
1058                 /* Check if frame is valid and get frame info */
1059                 p_sys->i_frame_size = ADTSSyncInfo( p_dec, p_header,
1060                                                     &p_sys->i_channels,
1061                                                     &p_sys->i_rate,
1062                                                     &p_sys->i_frame_length,
1063                                                     &p_sys->i_header_size );
1064             }
1065             else
1066             {
1067                 assert( p_sys->i_type == TYPE_LOAS );
1068                 /* Get LOAS frame header (LOAS_HEADER_SIZE bytes) */
1069                 if( block_PeekBytes( &p_sys->bytestream, p_header,
1070                                      LOAS_HEADER_SIZE ) != VLC_SUCCESS )
1071                 {
1072                     /* Need more data */
1073                     return NULL;
1074                 }
1075
1076                 /* Check if frame is valid and get frame info */
1077                 p_sys->i_frame_size = LOASSyncInfo( p_header, &p_sys->i_header_size );
1078             }
1079
1080             if( p_sys->i_frame_size <= 0 )
1081             {
1082                 msg_Dbg( p_dec, "emulated sync word" );
1083                 block_SkipByte( &p_sys->bytestream );
1084                 p_sys->i_state = STATE_NOSYNC;
1085                 break;
1086             }
1087
1088             p_sys->i_state = STATE_NEXT_SYNC;
1089
1090         case STATE_NEXT_SYNC:
1091             /* TODO: If p_block == NULL, flush the buffer without checking the
1092              * next sync word */
1093             if( p_sys->bytestream.p_block == NULL )
1094             {
1095                 p_sys->i_state = STATE_NOSYNC;
1096                 block_BytestreamFlush( &p_sys->bytestream );
1097                 return NULL;
1098             }
1099
1100             /* Check if next expected frame contains the sync word */
1101             if( block_PeekOffsetBytes( &p_sys->bytestream, p_sys->i_frame_size
1102                                        + p_sys->i_header_size, p_header, 2 )
1103                 != VLC_SUCCESS )
1104             {
1105                 /* Need more data */
1106                 return NULL;
1107             }
1108
1109             assert( (p_sys->i_type == TYPE_ADTS) || (p_sys->i_type == TYPE_LOAS) );
1110             if( ( ( p_sys->i_type == TYPE_ADTS ) &&
1111                   ( p_header[0] != 0xff || (p_header[1] & 0xf6) != 0xf0 ) ) ||
1112                 ( ( p_sys->i_type == TYPE_LOAS ) &&
1113                   ( p_header[0] != 0x56 || (p_header[1] & 0xe0) != 0xe0 ) ) )
1114             {
1115                 msg_Dbg( p_dec, "emulated sync word "
1116                          "(no sync on following frame)" );
1117                 p_sys->i_state = STATE_NOSYNC;
1118                 block_SkipByte( &p_sys->bytestream );
1119                 break;
1120             }
1121
1122             p_sys->i_state = STATE_SEND_DATA;
1123             break;
1124
1125         case STATE_GET_DATA:
1126             /* Make sure we have enough data.
1127              * (Not useful if we went through NEXT_SYNC) */
1128             if( block_WaitBytes( &p_sys->bytestream, p_sys->i_frame_size +
1129                                  p_sys->i_header_size) != VLC_SUCCESS )
1130             {
1131                 /* Need more data */
1132                 return NULL;
1133             }
1134             p_sys->i_state = STATE_SEND_DATA;
1135
1136         case STATE_SEND_DATA:
1137             /* When we reach this point we already know we have enough
1138              * data available. */
1139
1140             p_out_buffer = block_New( p_dec, p_sys->i_frame_size );
1141             if( !p_out_buffer )
1142             {
1143                 //p_dec->b_error = true;
1144                 return NULL;
1145             }
1146             p_buf = p_out_buffer->p_buffer;
1147
1148             /* Skip the ADTS/LOAS header */
1149             block_SkipBytes( &p_sys->bytestream, p_sys->i_header_size );
1150
1151             if( p_sys->i_type == TYPE_ADTS )
1152             {
1153                 /* Copy the whole frame into the buffer */
1154                 block_GetBytes( &p_sys->bytestream, p_buf, p_sys->i_frame_size );
1155             }
1156             else
1157             {
1158                 assert( p_sys->i_type == TYPE_LOAS );
1159                 /* Copy the whole frame into the buffer and parse/extract it */
1160                 block_GetBytes( &p_sys->bytestream, p_buf, p_sys->i_frame_size );
1161                 p_out_buffer->i_buffer = LOASParse( p_dec, p_buf, p_sys->i_frame_size );
1162                 if( p_out_buffer->i_buffer <= 0 )
1163                 {
1164                     if( !p_sys->b_latm_cfg )
1165                         msg_Warn( p_dec, "waiting for header" );
1166
1167                     block_Release( p_out_buffer );
1168                     p_out_buffer = NULL;
1169                     p_sys->i_state = STATE_NOSYNC;
1170                     break;
1171                 }
1172             }
1173             SetupOutput( p_dec, p_out_buffer );
1174             /* Make sure we don't reuse the same pts twice */
1175             if( p_sys->i_pts == p_sys->bytestream.p_block->i_pts )
1176                 p_sys->i_pts = p_sys->bytestream.p_block->i_pts = VLC_TS_INVALID;
1177
1178             /* So p_block doesn't get re-added several times */
1179             *pp_block = block_BytestreamPop( &p_sys->bytestream );
1180
1181             p_sys->i_state = STATE_NOSYNC;
1182
1183             return p_out_buffer;
1184         }
1185     }
1186
1187     return NULL;
1188 }
1189
1190 /*****************************************************************************
1191  * SetupBuffer:
1192  *****************************************************************************/
1193 static void SetupOutput( decoder_t *p_dec, block_t *p_block )
1194 {
1195     decoder_sys_t *p_sys = p_dec->p_sys;
1196
1197     if( p_dec->fmt_out.audio.i_rate != p_sys->i_rate )
1198     {
1199         msg_Info( p_dec, "AAC channels: %d samplerate: %d",
1200                   p_sys->i_channels, p_sys->i_rate );
1201
1202         const mtime_t i_end_date = date_Get( &p_sys->end_date );
1203         date_Init( &p_sys->end_date, p_sys->i_rate, 1 );
1204         date_Set( &p_sys->end_date, i_end_date );
1205     }
1206
1207     p_dec->fmt_out.audio.i_rate     = p_sys->i_rate;
1208     p_dec->fmt_out.audio.i_channels = p_sys->i_channels;
1209     p_dec->fmt_out.audio.i_bytes_per_frame = p_sys->i_frame_size;
1210     p_dec->fmt_out.audio.i_frame_length = p_sys->i_frame_length;
1211
1212 #if 0
1213     p_dec->fmt_out.audio.i_original_channels = p_sys->i_channels_conf;
1214     p_dec->fmt_out.audio.i_physical_channels = p_sys->i_channels_conf;
1215 #endif
1216
1217     p_block->i_pts = p_block->i_dts = date_Get( &p_sys->end_date );
1218
1219     p_block->i_length =
1220         date_Increment( &p_sys->end_date, p_sys->i_frame_length ) - p_block->i_pts;
1221 }
1222
1223 /*****************************************************************************
1224  * ClosePacketizer: clean up the packetizer
1225  *****************************************************************************/
1226 static void ClosePacketizer( vlc_object_t *p_this )
1227 {
1228     decoder_t *p_dec = (decoder_t *)p_this;
1229     decoder_sys_t *p_sys = p_dec->p_sys;
1230
1231     block_BytestreamRelease( &p_sys->bytestream );
1232
1233     free( p_dec->p_sys );
1234 }