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