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