1 /*
2 ** FAAD2 - Freeware Advanced Audio (AAC) Decoder including SBR decoding
3 ** Copyright (C) 2003-2005 M. Bakker, Nero AG, http://www.nero.com
4 **
5 ** This program is free software; you can redistribute it and/or modify
6 ** it under the terms of the GNU General Public License as published by
7 ** the Free Software Foundation; either version 2 of the License, or
8 ** (at your option) any later version.
9 **
10 ** This program is distributed in the hope that it will be useful,
11 ** but WITHOUT ANY WARRANTY; without even the implied warranty of
12 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 ** GNU General Public License for more details.
14 **
15 ** You should have received a copy of the GNU General Public License
16 ** along with this program; if not, write to the Free Software
17 ** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18 **
19 ** Any non-GPL usage of this software or parts of this software is strictly
20 ** forbidden.
21 **
22 ** The "appropriate copyright message" mentioned in section 2c of the GPLv2
23 ** must read: "Code from FAAD2 is copyright (c) Nero AG, www.nero.com"
24 **
25 ** Commercial non-GPL licensing of this software is possible.
26 ** For more info contact Nero AG through Mpeg4AAClicense@nero.com.
27 **
28 ** $Id: syntax.c,v 1.93 2009/01/26 23:51:15 menno Exp $
29 **/
30 
31 /*
32    Reads the AAC bitstream as defined in 14496-3 (MPEG-4 Audio)
33 */
34 
35 #include "common.h"
36 #include "structs.h"
37 
38 #include <stdlib.h>
39 #include <stdio.h>
40 #include <string.h>
41 
42 #include "syntax.h"
43 #include "specrec.h"
44 #include "huffman.h"
45 #include "bits.h"
46 #include "pulse.h"
47 #include "analysis.h"
48 #include "drc.h"
49 #ifdef ERROR_RESILIENCE
50 #include "rvlc.h"
51 #endif
52 #ifdef SBR_DEC
53 #include "sbr_syntax.h"
54 #endif
55 #include "mp4.h"
56 
57 
58 /* static function declarations */
59 static void decode_sce_lfe(NeAACDecStruct *hDecoder, NeAACDecFrameInfo *hInfo, bitfile *ld,
60                            uint8_t id_syn_ele);
61 static void decode_cpe(NeAACDecStruct *hDecoder, NeAACDecFrameInfo *hInfo, bitfile *ld,
62                        uint8_t id_syn_ele);
63 static uint8_t single_lfe_channel_element(NeAACDecStruct *hDecoder, bitfile *ld,
64                                           uint8_t channel, uint8_t *tag);
65 static uint8_t channel_pair_element(NeAACDecStruct *hDecoder, bitfile *ld,
66                                     uint8_t channel, uint8_t *tag);
67 #ifdef COUPLING_DEC
68 static uint8_t coupling_channel_element(NeAACDecStruct *hDecoder, bitfile *ld);
69 #endif
70 static uint16_t data_stream_element(NeAACDecStruct *hDecoder, bitfile *ld);
71 static uint8_t program_config_element(program_config *pce, bitfile *ld);
72 static uint8_t fill_element(NeAACDecStruct *hDecoder, bitfile *ld, drc_info *drc
73 #ifdef SBR_DEC
74                             ,uint8_t sbr_ele
75 #endif
76                             );
77 static uint8_t individual_channel_stream(NeAACDecStruct *hDecoder, element *ele,
78                                          bitfile *ld, ic_stream *ics, uint8_t scal_flag,
79                                          int16_t *spec_data);
80 static uint8_t ics_info(NeAACDecStruct *hDecoder, ic_stream *ics, bitfile *ld,
81                         uint8_t common_window);
82 static uint8_t section_data(NeAACDecStruct *hDecoder, ic_stream *ics, bitfile *ld);
83 static uint8_t scale_factor_data(NeAACDecStruct *hDecoder, ic_stream *ics, bitfile *ld);
84 #ifdef SSR_DEC
85 static void gain_control_data(bitfile *ld, ic_stream *ics);
86 #endif
87 static uint8_t spectral_data(NeAACDecStruct *hDecoder, ic_stream *ics, bitfile *ld,
88                              int16_t *spectral_data);
89 static uint16_t extension_payload(bitfile *ld, drc_info *drc, uint16_t count);
90 static uint8_t pulse_data(ic_stream *ics, pulse_info *pul, bitfile *ld);
91 static void tns_data(ic_stream *ics, tns_info *tns, bitfile *ld);
92 #ifdef LTP_DEC
93 static uint8_t ltp_data(NeAACDecStruct *hDecoder, ic_stream *ics, ltp_info *ltp, bitfile *ld);
94 #endif
95 static uint8_t adts_fixed_header(adts_header *adts, bitfile *ld);
96 static void adts_variable_header(adts_header *adts, bitfile *ld);
97 static void adts_error_check(adts_header *adts, bitfile *ld);
98 static uint8_t dynamic_range_info(bitfile *ld, drc_info *drc);
99 static uint8_t excluded_channels(bitfile *ld, drc_info *drc);
100 static uint8_t side_info(NeAACDecStruct *hDecoder, element *ele,
101                          bitfile *ld, ic_stream *ics, uint8_t scal_flag);
102 #ifdef DRM
103 static int8_t DRM_aac_scalable_main_header(NeAACDecStruct *hDecoder, ic_stream *ics1, ic_stream *ics2,
104                                            bitfile *ld, uint8_t this_layer_stereo);
105 #endif
106 
107 
108 /* Table 4.4.1 */
109 int8_t GASpecificConfig(bitfile *ld, mp4AudioSpecificConfig *mp4ASC,
110                         program_config *pce_out)
111 {
112     program_config pce;
113 
114     /* 1024 or 960 */
115     mp4ASC->frameLengthFlag = faad_get1bit(ld
116         DEBUGVAR(1,138,"GASpecificConfig(): FrameLengthFlag"));
117 #ifndef ALLOW_SMALL_FRAMELENGTH
118     if (mp4ASC->frameLengthFlag == 1)
119         return -3;
120 #endif
121 
122     mp4ASC->dependsOnCoreCoder = faad_get1bit(ld
123         DEBUGVAR(1,139,"GASpecificConfig(): DependsOnCoreCoder"));
124     if (mp4ASC->dependsOnCoreCoder == 1)
125     {
126         mp4ASC->coreCoderDelay = (uint16_t)faad_getbits(ld, 14
127             DEBUGVAR(1,140,"GASpecificConfig(): CoreCoderDelay"));
128     }
129 
130     mp4ASC->extensionFlag = faad_get1bit(ld DEBUGVAR(1,141,"GASpecificConfig(): ExtensionFlag"));
131     if (mp4ASC->channelsConfiguration == 0)
132     {
133         if (program_config_element(&pce, ld))
134             return -3;
135         //mp4ASC->channelsConfiguration = pce.channels;
136 
137         if (pce_out != NULL)
138             memcpy(pce_out, &pce, sizeof(program_config));
139 
140         /*
141         if (pce.num_valid_cc_elements)
142             return -3;
143         */
144     }
145 
146 #ifdef ERROR_RESILIENCE
147     if (mp4ASC->extensionFlag == 1)
148     {
149         /* Error resilience not supported yet */
150         if (mp4ASC->objectTypeIndex >= ER_OBJECT_START)
151         {
152             mp4ASC->aacSectionDataResilienceFlag = faad_get1bit(ld
153                 DEBUGVAR(1,144,"GASpecificConfig(): aacSectionDataResilienceFlag"));
154             mp4ASC->aacScalefactorDataResilienceFlag = faad_get1bit(ld
155                 DEBUGVAR(1,145,"GASpecificConfig(): aacScalefactorDataResilienceFlag"));
156             mp4ASC->aacSpectralDataResilienceFlag = faad_get1bit(ld
157                 DEBUGVAR(1,146,"GASpecificConfig(): aacSpectralDataResilienceFlag"));
158         }
159         /* 1 bit: extensionFlag3 */
160         faad_getbits(ld, 1);
161 	}
162 #endif
163 
164     return 0;
165 }
166 
167 /* Table 4.4.2 */
168 /* An MPEG-4 Audio decoder is only required to follow the Program
169    Configuration Element in GASpecificConfig(). The decoder shall ignore
170    any Program Configuration Elements that may occur in raw data blocks.
171    PCEs transmitted in raw data blocks cannot be used to convey decoder
172    configuration information.
173 */
174 static uint8_t program_config_element(program_config *pce, bitfile *ld)
175 {
176     uint8_t i;
177 
178     memset(pce, 0, sizeof(program_config));
179 
180     pce->channels = 0;
181 
182     pce->element_instance_tag = (uint8_t)faad_getbits(ld, 4
183         DEBUGVAR(1,10,"program_config_element(): element_instance_tag"));
184 
185     pce->object_type = (uint8_t)faad_getbits(ld, 2
186         DEBUGVAR(1,11,"program_config_element(): object_type"));
187     pce->sf_index = (uint8_t)faad_getbits(ld, 4
188         DEBUGVAR(1,12,"program_config_element(): sf_index"));
189     pce->num_front_channel_elements = (uint8_t)faad_getbits(ld, 4
190         DEBUGVAR(1,13,"program_config_element(): num_front_channel_elements"));
191     pce->num_side_channel_elements = (uint8_t)faad_getbits(ld, 4
192         DEBUGVAR(1,14,"program_config_element(): num_side_channel_elements"));
193     pce->num_back_channel_elements = (uint8_t)faad_getbits(ld, 4
194         DEBUGVAR(1,15,"program_config_element(): num_back_channel_elements"));
195     pce->num_lfe_channel_elements = (uint8_t)faad_getbits(ld, 2
196         DEBUGVAR(1,16,"program_config_element(): num_lfe_channel_elements"));
197     pce->num_assoc_data_elements = (uint8_t)faad_getbits(ld, 3
198         DEBUGVAR(1,17,"program_config_element(): num_assoc_data_elements"));
199     pce->num_valid_cc_elements = (uint8_t)faad_getbits(ld, 4
200         DEBUGVAR(1,18,"program_config_element(): num_valid_cc_elements"));
201 
202     pce->mono_mixdown_present = faad_get1bit(ld
203         DEBUGVAR(1,19,"program_config_element(): mono_mixdown_present"));
204     if (pce->mono_mixdown_present == 1)
205     {
206         pce->mono_mixdown_element_number = (uint8_t)faad_getbits(ld, 4
207             DEBUGVAR(1,20,"program_config_element(): mono_mixdown_element_number"));
208     }
209 
210     pce->stereo_mixdown_present = faad_get1bit(ld
211         DEBUGVAR(1,21,"program_config_element(): stereo_mixdown_present"));
212     if (pce->stereo_mixdown_present == 1)
213     {
214         pce->stereo_mixdown_element_number = (uint8_t)faad_getbits(ld, 4
215             DEBUGVAR(1,22,"program_config_element(): stereo_mixdown_element_number"));
216     }
217 
218     pce->matrix_mixdown_idx_present = faad_get1bit(ld
219         DEBUGVAR(1,23,"program_config_element(): matrix_mixdown_idx_present"));
220     if (pce->matrix_mixdown_idx_present == 1)
221     {
222         pce->matrix_mixdown_idx = (uint8_t)faad_getbits(ld, 2
223             DEBUGVAR(1,24,"program_config_element(): matrix_mixdown_idx"));
224         pce->pseudo_surround_enable = faad_get1bit(ld
225             DEBUGVAR(1,25,"program_config_element(): pseudo_surround_enable"));
226     }
227 
228     for (i = 0; i < pce->num_front_channel_elements; i++)
229     {
230         pce->front_element_is_cpe[i] = faad_get1bit(ld
231             DEBUGVAR(1,26,"program_config_element(): front_element_is_cpe"));
232         pce->front_element_tag_select[i] = (uint8_t)faad_getbits(ld, 4
233             DEBUGVAR(1,27,"program_config_element(): front_element_tag_select"));
234 
235         if (pce->front_element_is_cpe[i] & 1)
236         {
237             pce->cpe_channel[pce->front_element_tag_select[i]] = pce->channels;
238             pce->num_front_channels += 2;
239             pce->channels += 2;
240         } else {
241             pce->sce_channel[pce->front_element_tag_select[i]] = pce->channels;
242             pce->num_front_channels++;
243             pce->channels++;
244         }
245     }
246 
247     for (i = 0; i < pce->num_side_channel_elements; i++)
248     {
249         pce->side_element_is_cpe[i] = faad_get1bit(ld
250             DEBUGVAR(1,28,"program_config_element(): side_element_is_cpe"));
251         pce->side_element_tag_select[i] = (uint8_t)faad_getbits(ld, 4
252             DEBUGVAR(1,29,"program_config_element(): side_element_tag_select"));
253 
254         if (pce->side_element_is_cpe[i] & 1)
255         {
256             pce->cpe_channel[pce->side_element_tag_select[i]] = pce->channels;
257             pce->num_side_channels += 2;
258             pce->channels += 2;
259         } else {
260             pce->sce_channel[pce->side_element_tag_select[i]] = pce->channels;
261             pce->num_side_channels++;
262             pce->channels++;
263         }
264     }
265 
266     for (i = 0; i < pce->num_back_channel_elements; i++)
267     {
268         pce->back_element_is_cpe[i] = faad_get1bit(ld
269             DEBUGVAR(1,30,"program_config_element(): back_element_is_cpe"));
270         pce->back_element_tag_select[i] = (uint8_t)faad_getbits(ld, 4
271             DEBUGVAR(1,31,"program_config_element(): back_element_tag_select"));
272 
273         if (pce->back_element_is_cpe[i] & 1)
274         {
275             pce->cpe_channel[pce->back_element_tag_select[i]] = pce->channels;
276             pce->channels += 2;
277             pce->num_back_channels += 2;
278         } else {
279             pce->sce_channel[pce->back_element_tag_select[i]] = pce->channels;
280             pce->num_back_channels++;
281             pce->channels++;
282         }
283     }
284 
285     for (i = 0; i < pce->num_lfe_channel_elements; i++)
286     {
287         pce->lfe_element_tag_select[i] = (uint8_t)faad_getbits(ld, 4
288             DEBUGVAR(1,32,"program_config_element(): lfe_element_tag_select"));
289 
290         pce->sce_channel[pce->lfe_element_tag_select[i]] = pce->channels;
291         pce->num_lfe_channels++;
292         pce->channels++;
293     }
294 
295     for (i = 0; i < pce->num_assoc_data_elements; i++)
296         pce->assoc_data_element_tag_select[i] = (uint8_t)faad_getbits(ld, 4
297         DEBUGVAR(1,33,"program_config_element(): assoc_data_element_tag_select"));
298 
299     for (i = 0; i < pce->num_valid_cc_elements; i++)
300     {
301         pce->cc_element_is_ind_sw[i] = faad_get1bit(ld
302             DEBUGVAR(1,34,"program_config_element(): cc_element_is_ind_sw"));
303         pce->valid_cc_element_tag_select[i] = (uint8_t)faad_getbits(ld, 4
304             DEBUGVAR(1,35,"program_config_element(): valid_cc_element_tag_select"));
305     }
306 
307     faad_byte_align(ld);
308 
309     pce->comment_field_bytes = (uint8_t)faad_getbits(ld, 8
310         DEBUGVAR(1,36,"program_config_element(): comment_field_bytes"));
311 
312     for (i = 0; i < pce->comment_field_bytes; i++)
313     {
314         pce->comment_field_data[i] = (uint8_t)faad_getbits(ld, 8
315             DEBUGVAR(1,37,"program_config_element(): comment_field_data"));
316     }
317     pce->comment_field_data[i] = 0;
318 
319     if (pce->channels > MAX_CHANNELS)
320         return 22;
321 
322     return 0;
323 }
324 
325 static void decode_sce_lfe(NeAACDecStruct *hDecoder,
326                            NeAACDecFrameInfo *hInfo, bitfile *ld,
327                            uint8_t id_syn_ele)
328 {
329     uint8_t channels = hDecoder->fr_channels;
330     uint8_t tag = 0;
331 
332     if (channels+1 > MAX_CHANNELS)
333     {
334         hInfo->error = 12;
335         return;
336     }
337     if (hDecoder->fr_ch_ele+1 > MAX_SYNTAX_ELEMENTS)
338     {
339         hInfo->error = 13;
340         return;
341     }
342 
343     /* for SCE hDecoder->element_output_channels[] is not set here because this
344        can become 2 when some form of Parametric Stereo coding is used
345     */
346 
347     /* save the syntax element id */
348     hDecoder->element_id[hDecoder->fr_ch_ele] = id_syn_ele;
349 
350     /* decode the element */
351     hInfo->error = single_lfe_channel_element(hDecoder, ld, channels, &tag);
352 
353     /* map output channels position to internal data channels */
354     if (hDecoder->element_output_channels[hDecoder->fr_ch_ele] == 2)
355     {
356         /* this might be faulty when pce_set is true */
357         hDecoder->internal_channel[channels] = channels;
358         hDecoder->internal_channel[channels+1] = channels+1;
359     } else {
360         if (hDecoder->pce_set)
361             hDecoder->internal_channel[hDecoder->pce.sce_channel[tag]] = channels;
362         else
363             hDecoder->internal_channel[channels] = channels;
364     }
365 
366     hDecoder->fr_channels += hDecoder->element_output_channels[hDecoder->fr_ch_ele];
367     hDecoder->fr_ch_ele++;
368 }
369 
370 static void decode_cpe(NeAACDecStruct *hDecoder, NeAACDecFrameInfo *hInfo, bitfile *ld,
371                        uint8_t id_syn_ele)
372 {
373     uint8_t channels = hDecoder->fr_channels;
374     uint8_t tag = 0;
375 
376     if (channels+2 > MAX_CHANNELS)
377     {
378         hInfo->error = 12;
379         return;
380     }
381     if (hDecoder->fr_ch_ele+1 > MAX_SYNTAX_ELEMENTS)
382     {
383         hInfo->error = 13;
384         return;
385     }
386 
387     /* for CPE the number of output channels is always 2 */
388     if (hDecoder->element_output_channels[hDecoder->fr_ch_ele] == 0)
389     {
390         /* element_output_channels not set yet */
391         hDecoder->element_output_channels[hDecoder->fr_ch_ele] = 2;
392     } else if (hDecoder->element_output_channels[hDecoder->fr_ch_ele] != 2) {
393         /* element inconsistency */
394         hInfo->error = 21;
395         return;
396     }
397 
398     /* save the syntax element id */
399     hDecoder->element_id[hDecoder->fr_ch_ele] = id_syn_ele;
400 
401     /* decode the element */
402     hInfo->error = channel_pair_element(hDecoder, ld, channels, &tag);
403 
404     /* map output channel position to internal data channels */
405     if (hDecoder->pce_set)
406     {
407         hDecoder->internal_channel[hDecoder->pce.cpe_channel[tag]] = channels;
408         hDecoder->internal_channel[hDecoder->pce.cpe_channel[tag]+1] = channels+1;
409     } else {
410         hDecoder->internal_channel[channels] = channels;
411         hDecoder->internal_channel[channels+1] = channels+1;
412     }
413 
414     hDecoder->fr_channels += 2;
415     hDecoder->fr_ch_ele++;
416 }
417 
418 void raw_data_block(NeAACDecStruct *hDecoder, NeAACDecFrameInfo *hInfo,
419                     bitfile *ld, program_config *pce, drc_info *drc)
420 {
421     uint8_t id_syn_ele;
422     uint8_t ele_this_frame = 0;
423 
424     hDecoder->fr_channels = 0;
425     hDecoder->fr_ch_ele = 0;
426     hDecoder->first_syn_ele = 25;
427     hDecoder->has_lfe = 0;
428 
429 #ifdef ERROR_RESILIENCE
430     if (hDecoder->object_type < ER_OBJECT_START)
431     {
432 #endif
433         /* Table 4.4.3: raw_data_block() */
434         while ((id_syn_ele = (uint8_t)faad_getbits(ld, LEN_SE_ID
435             DEBUGVAR(1,4,"NeAACDecDecode(): id_syn_ele"))) != ID_END)
436         {
437             switch (id_syn_ele) {
438             case ID_SCE:
439                 ele_this_frame++;
440                 if (hDecoder->first_syn_ele == 25) hDecoder->first_syn_ele = id_syn_ele;
441                 decode_sce_lfe(hDecoder, hInfo, ld, id_syn_ele);
442                 if (hInfo->error > 0)
443                     return;
444                 break;
445             case ID_CPE:
446                 ele_this_frame++;
447                 if (hDecoder->first_syn_ele == 25) hDecoder->first_syn_ele = id_syn_ele;
448                 decode_cpe(hDecoder, hInfo, ld, id_syn_ele);
449                 if (hInfo->error > 0)
450                     return;
451                 break;
452             case ID_LFE:
453 #ifdef DRM
454                 hInfo->error = 32;
455 #else
456                 ele_this_frame++;
457                 hDecoder->has_lfe++;
458                 decode_sce_lfe(hDecoder, hInfo, ld, id_syn_ele);
459 #endif
460                 if (hInfo->error > 0)
461                     return;
462                 break;
463             case ID_CCE: /* not implemented yet, but skip the bits */
464 #ifdef DRM
465                 hInfo->error = 32;
466 #else
467                 ele_this_frame++;
468 #ifdef COUPLING_DEC
469                 hInfo->error = coupling_channel_element(hDecoder, ld);
470 #else
471                 hInfo->error = 6;
472 #endif
473 #endif
474                 if (hInfo->error > 0)
475                     return;
476                 break;
477             case ID_DSE:
478                 ele_this_frame++;
479                 data_stream_element(hDecoder, ld);
480                 break;
481             case ID_PCE:
482                 if (ele_this_frame != 0)
483                 {
484                     hInfo->error = 31;
485                     return;
486                 }
487                 ele_this_frame++;
488                 /* 14496-4: 5.6.4.1.2.1.3: */
489                 /* program_configuration_element()'s in access units shall be ignored */
490                 program_config_element(pce, ld);
491                 //if ((hInfo->error = program_config_element(pce, ld)) > 0)
492                 //    return;
493                 //hDecoder->pce_set = 1;
494                 break;
495             case ID_FIL:
496                 ele_this_frame++;
497                 /* one sbr_info describes a channel_element not a channel! */
498                 /* if we encounter SBR data here: error */
499                 /* SBR data will be read directly in the SCE/LFE/CPE element */
500                 if ((hInfo->error = fill_element(hDecoder, ld, drc
501 #ifdef SBR_DEC
502                     , INVALID_SBR_ELEMENT
503 #endif
504                     )) > 0)
505                     return;
506                 break;
507             }
508         }
509 #ifdef ERROR_RESILIENCE
510     } else {
511         /* Table 262: er_raw_data_block() */
512         switch (hDecoder->channelConfiguration)
513         {
514         case 1:
515             decode_sce_lfe(hDecoder, hInfo, ld, ID_SCE);
516             if (hInfo->error > 0)
517                 return;
518             break;
519         case 2:
520             decode_cpe(hDecoder, hInfo, ld, ID_CPE);
521             if (hInfo->error > 0)
522                 return;
523             break;
524         case 3:
525             decode_sce_lfe(hDecoder, hInfo, ld, ID_SCE);
526             decode_cpe(hDecoder, hInfo, ld, ID_CPE);
527             if (hInfo->error > 0)
528                 return;
529             break;
530         case 4:
531             decode_sce_lfe(hDecoder, hInfo, ld, ID_SCE);
532             decode_cpe(hDecoder, hInfo, ld, ID_CPE);
533             decode_sce_lfe(hDecoder, hInfo, ld, ID_SCE);
534             if (hInfo->error > 0)
535                 return;
536             break;
537         case 5:
538             decode_sce_lfe(hDecoder, hInfo, ld, ID_SCE);
539             decode_cpe(hDecoder, hInfo, ld, ID_CPE);
540             decode_cpe(hDecoder, hInfo, ld, ID_CPE);
541             if (hInfo->error > 0)
542                 return;
543             break;
544         case 6:
545             decode_sce_lfe(hDecoder, hInfo, ld, ID_SCE);
546             decode_cpe(hDecoder, hInfo, ld, ID_CPE);
547             decode_cpe(hDecoder, hInfo, ld, ID_CPE);
548             decode_sce_lfe(hDecoder, hInfo, ld, ID_LFE);
549             if (hInfo->error > 0)
550                 return;
551             break;
552         case 7: /* 8 channels */
553             decode_sce_lfe(hDecoder, hInfo, ld, ID_SCE);
554             decode_cpe(hDecoder, hInfo, ld, ID_CPE);
555             decode_cpe(hDecoder, hInfo, ld, ID_CPE);
556             decode_cpe(hDecoder, hInfo, ld, ID_CPE);
557             decode_sce_lfe(hDecoder, hInfo, ld, ID_LFE);
558             if (hInfo->error > 0)
559                 return;
560             break;
561         default:
562             hInfo->error = 7;
563             return;
564         }
565 #if 0
566         cnt = bits_to_decode() / 8;
567         while (cnt >= 1)
568         {
569             cnt -= extension_payload(cnt);
570         }
571 #endif
572     }
573 #endif
574 
575     /* new in corrigendum 14496-3:2002 */
576 #ifdef DRM
577     if (hDecoder->object_type != DRM_ER_LC
578 #if 0
579         && !hDecoder->latm_header_present
580 #endif
581         )
582 #endif
583     {
584         faad_byte_align(ld);
585     }
586 
587     return;
588 }
589 
590 /* Table 4.4.4 and */
591 /* Table 4.4.9 */
592 static uint8_t single_lfe_channel_element(NeAACDecStruct *hDecoder, bitfile *ld,
593                                           uint8_t channel, uint8_t *tag)
594 {
595     uint8_t retval = 0;
596     element sce = {0};
597     ic_stream *ics = &(sce.ics1);
598     ALIGN int16_t spec_data[1024] = {0};
599 
600     sce.element_instance_tag = (uint8_t)faad_getbits(ld, LEN_TAG
601         DEBUGVAR(1,38,"single_lfe_channel_element(): element_instance_tag"));
602 
603     *tag = sce.element_instance_tag;
604     sce.channel = channel;
605     sce.paired_channel = -1;
606 
607     retval = individual_channel_stream(hDecoder, &sce, ld, ics, 0, spec_data);
608     if (retval > 0)
609         return retval;
610 
611     /* IS not allowed in single channel */
612     if (ics->is_used)
613         return 32;
614 
615 #ifdef SBR_DEC
616     /* check if next bitstream element is a fill element */
617     /* if so, read it now so SBR decoding can be done in case of a file with SBR */
618     if (faad_showbits(ld, LEN_SE_ID) == ID_FIL)
619     {
620         faad_flushbits(ld, LEN_SE_ID);
621 
622         /* one sbr_info describes a channel_element not a channel! */
623         if ((retval = fill_element(hDecoder, ld, hDecoder->drc, hDecoder->fr_ch_ele)) > 0)
624         {
625             return retval;
626         }
627     }
628 #endif
629 
630     /* noiseless coding is done, spectral reconstruction is done now */
631     retval = reconstruct_single_channel(hDecoder, ics, &sce, spec_data);
632     if (retval > 0)
633         return retval;
634 
635     return 0;
636 }
637 
638 /* Table 4.4.5 */
639 static uint8_t channel_pair_element(NeAACDecStruct *hDecoder, bitfile *ld,
640                                     uint8_t channels, uint8_t *tag)
641 {
642     ALIGN int16_t spec_data1[1024] = {0};
643     ALIGN int16_t spec_data2[1024] = {0};
644     element cpe = {0};
645     ic_stream *ics1 = &(cpe.ics1);
646     ic_stream *ics2 = &(cpe.ics2);
647     uint8_t result;
648 
649     cpe.channel        = channels;
650     cpe.paired_channel = channels+1;
651 
652     cpe.element_instance_tag = (uint8_t)faad_getbits(ld, LEN_TAG
653         DEBUGVAR(1,39,"channel_pair_element(): element_instance_tag"));
654     *tag = cpe.element_instance_tag;
655 
656     if ((cpe.common_window = faad_get1bit(ld
657         DEBUGVAR(1,40,"channel_pair_element(): common_window"))) & 1)
658     {
659         /* both channels have common ics information */
660         if ((result = ics_info(hDecoder, ics1, ld, cpe.common_window)) > 0)
661             return result;
662 
663         ics1->ms_mask_present = (uint8_t)faad_getbits(ld, 2
664             DEBUGVAR(1,41,"channel_pair_element(): ms_mask_present"));
665         if (ics1->ms_mask_present == 3)
666         {
667             /* bitstream error */
668             return 32;
669         }
670         if (ics1->ms_mask_present == 1)
671         {
672             uint8_t g, sfb;
673             for (g = 0; g < ics1->num_window_groups; g++)
674             {
675                 for (sfb = 0; sfb < ics1->max_sfb; sfb++)
676                 {
677                     ics1->ms_used[g][sfb] = faad_get1bit(ld
678                         DEBUGVAR(1,42,"channel_pair_element(): faad_get1bit"));
679                 }
680             }
681         }
682 
683 #ifdef ERROR_RESILIENCE
684         if ((hDecoder->object_type >= ER_OBJECT_START) && (ics1->predictor_data_present))
685         {
686             if ((
687 #ifdef LTP_DEC
688                 ics1->ltp.data_present =
689 #endif
690                 faad_get1bit(ld DEBUGVAR(1,50,"channel_pair_element(): ltp.data_present"))) & 1)
691             {
692 #ifdef LTP_DEC
693                 if ((result = ltp_data(hDecoder, ics1, &(ics1->ltp), ld)) > 0)
694                 {
695                     return result;
696                 }
697 #else
698                 return 26;
699 #endif
700             }
701         }
702 #endif
703 
704         memcpy(ics2, ics1, sizeof(ic_stream));
705     } else {
706         ics1->ms_mask_present = 0;
707     }
708 
709     if ((result = individual_channel_stream(hDecoder, &cpe, ld, ics1,
710         0, spec_data1)) > 0)
711     {
712         return result;
713     }
714 
715 #ifdef ERROR_RESILIENCE
716     if (cpe.common_window && (hDecoder->object_type >= ER_OBJECT_START) &&
717         (ics1->predictor_data_present))
718     {
719         if ((
720 #ifdef LTP_DEC
721             ics1->ltp2.data_present =
722 #endif
723             faad_get1bit(ld DEBUGVAR(1,50,"channel_pair_element(): ltp.data_present"))) & 1)
724         {
725 #ifdef LTP_DEC
726             if ((result = ltp_data(hDecoder, ics1, &(ics1->ltp2), ld)) > 0)
727             {
728                 return result;
729             }
730 #else
731             return 26;
732 #endif
733         }
734     }
735 #endif
736 
737     if ((result = individual_channel_stream(hDecoder, &cpe, ld, ics2,
738         0, spec_data2)) > 0)
739     {
740         return result;
741     }
742 
743 #ifdef SBR_DEC
744     /* check if next bitstream element is a fill element */
745     /* if so, read it now so SBR decoding can be done in case of a file with SBR */
746     if (faad_showbits(ld, LEN_SE_ID) == ID_FIL)
747     {
748         faad_flushbits(ld, LEN_SE_ID);
749 
750         /* one sbr_info describes a channel_element not a channel! */
751         if ((result = fill_element(hDecoder, ld, hDecoder->drc, hDecoder->fr_ch_ele)) > 0)
752         {
753             return result;
754         }
755     }
756 #endif
757 
758     /* noiseless coding is done, spectral reconstruction is done now */
759     if ((result = reconstruct_channel_pair(hDecoder, ics1, ics2, &cpe,
760         spec_data1, spec_data2)) > 0)
761     {
762         return result;
763     }
764 
765     return 0;
766 }
767 
768 /* Table 4.4.6 */
769 static uint8_t ics_info(NeAACDecStruct *hDecoder, ic_stream *ics, bitfile *ld,
770                         uint8_t common_window)
771 {
772     uint8_t retval = 0;
773     uint8_t ics_reserved_bit;
774 
775     ics_reserved_bit = faad_get1bit(ld
776         DEBUGVAR(1,43,"ics_info(): ics_reserved_bit"));
777     if (ics_reserved_bit != 0)
778         return 32;
779     ics->window_sequence = (uint8_t)faad_getbits(ld, 2
780         DEBUGVAR(1,44,"ics_info(): window_sequence"));
781     ics->window_shape = faad_get1bit(ld
782         DEBUGVAR(1,45,"ics_info(): window_shape"));
783 
784 #ifdef LD_DEC
785     /* No block switching in LD */
786     if ((hDecoder->object_type == LD) && (ics->window_sequence != ONLY_LONG_SEQUENCE))
787         return 32;
788 #endif
789 
790     if (ics->window_sequence == EIGHT_SHORT_SEQUENCE)
791     {
792         ics->max_sfb = (uint8_t)faad_getbits(ld, 4
793             DEBUGVAR(1,46,"ics_info(): max_sfb (short)"));
794         ics->scale_factor_grouping = (uint8_t)faad_getbits(ld, 7
795             DEBUGVAR(1,47,"ics_info(): scale_factor_grouping"));
796     } else {
797         ics->max_sfb = (uint8_t)faad_getbits(ld, 6
798             DEBUGVAR(1,48,"ics_info(): max_sfb (long)"));
799     }
800 
801     /* get the grouping information */
802     if ((retval = window_grouping_info(hDecoder, ics)) > 0)
803         return retval;
804 
805 
806     /* should be an error */
807     /* check the range of max_sfb */
808     if (ics->max_sfb > ics->num_swb)
809         return 16;
810 
811     if (ics->window_sequence != EIGHT_SHORT_SEQUENCE)
812     {
813         if ((ics->predictor_data_present = faad_get1bit(ld
814             DEBUGVAR(1,49,"ics_info(): predictor_data_present"))) & 1)
815         {
816             if (hDecoder->object_type == MAIN) /* MPEG2 style AAC predictor */
817             {
818                 uint8_t sfb;
819 
820                 uint8_t limit = min(ics->max_sfb, max_pred_sfb(hDecoder->sf_index));
821 #ifdef MAIN_DEC
822                 ics->pred.limit = limit;
823 #endif
824 
825                 if ((
826 #ifdef MAIN_DEC
827                     ics->pred.predictor_reset =
828 #endif
829                     faad_get1bit(ld DEBUGVAR(1,53,"ics_info(): pred.predictor_reset"))) & 1)
830                 {
831 #ifdef MAIN_DEC
832                     ics->pred.predictor_reset_group_number =
833 #endif
834                         (uint8_t)faad_getbits(ld, 5 DEBUGVAR(1,54,"ics_info(): pred.predictor_reset_group_number"));
835                 }
836 
837                 for (sfb = 0; sfb < limit; sfb++)
838                 {
839 #ifdef MAIN_DEC
840                     ics->pred.prediction_used[sfb] =
841 #endif
842                         faad_get1bit(ld DEBUGVAR(1,55,"ics_info(): pred.prediction_used"));
843                 }
844             }
845 #ifdef LTP_DEC
846             else { /* Long Term Prediction */
847                 if (hDecoder->object_type < ER_OBJECT_START)
848                 {
849                     if ((ics->ltp.data_present = faad_get1bit(ld
850                         DEBUGVAR(1,50,"ics_info(): ltp.data_present"))) & 1)
851                     {
852                         if ((retval = ltp_data(hDecoder, ics, &(ics->ltp), ld)) > 0)
853                         {
854                             return retval;
855                         }
856                     }
857                     if (common_window)
858                     {
859                         if ((ics->ltp2.data_present = faad_get1bit(ld
860                             DEBUGVAR(1,51,"ics_info(): ltp2.data_present"))) & 1)
861                         {
862                             if ((retval = ltp_data(hDecoder, ics, &(ics->ltp2), ld)) > 0)
863                             {
864                                 return retval;
865                             }
866                         }
867                     }
868                 }
869 #ifdef ERROR_RESILIENCE
870                 if (!common_window && (hDecoder->object_type >= ER_OBJECT_START))
871                 {
872                     if ((ics->ltp.data_present = faad_get1bit(ld
873                         DEBUGVAR(1,50,"ics_info(): ltp.data_present"))) & 1)
874                     {
875                         ltp_data(hDecoder, ics, &(ics->ltp), ld);
876                     }
877                 }
878 #endif
879             }
880 #endif
881         }
882     }
883 
884     return retval;
885 }
886 
887 /* Table 4.4.7 */
888 static uint8_t pulse_data(ic_stream *ics, pulse_info *pul, bitfile *ld)
889 {
890     uint8_t i;
891 
892     pul->number_pulse = (uint8_t)faad_getbits(ld, 2
893         DEBUGVAR(1,56,"pulse_data(): number_pulse"));
894     pul->pulse_start_sfb = (uint8_t)faad_getbits(ld, 6
895         DEBUGVAR(1,57,"pulse_data(): pulse_start_sfb"));
896 
897     /* check the range of pulse_start_sfb */
898     if (pul->pulse_start_sfb > ics->num_swb)
899         return 16;
900 
901     for (i = 0; i < pul->number_pulse+1; i++)
902     {
903         pul->pulse_offset[i] = (uint8_t)faad_getbits(ld, 5
904             DEBUGVAR(1,58,"pulse_data(): pulse_offset"));
905 #if 0
906         printf("%d\n", pul->pulse_offset[i]);
907 #endif
908         pul->pulse_amp[i] = (uint8_t)faad_getbits(ld, 4
909             DEBUGVAR(1,59,"pulse_data(): pulse_amp"));
910 #if 0
911         printf("%d\n", pul->pulse_amp[i]);
912 #endif
913     }
914 
915     return 0;
916 }
917 
918 #ifdef COUPLING_DEC
919 /* Table 4.4.8: Currently just for skipping the bits... */
920 static uint8_t coupling_channel_element(NeAACDecStruct *hDecoder, bitfile *ld)
921 {
922     uint8_t c, result = 0;
923     uint8_t ind_sw_cce_flag = 0;
924     uint8_t num_gain_element_lists = 0;
925     uint8_t num_coupled_elements = 0;
926 
927     element el_empty = {0};
928     ic_stream ics_empty = {0};
929     int16_t sh_data[1024];
930 
931     c = faad_getbits(ld, LEN_TAG
932         DEBUGVAR(1,900,"coupling_channel_element(): element_instance_tag"));
933 
934     ind_sw_cce_flag = faad_get1bit(ld
935         DEBUGVAR(1,901,"coupling_channel_element(): ind_sw_cce_flag"));
936     num_coupled_elements = faad_getbits(ld, 3
937         DEBUGVAR(1,902,"coupling_channel_element(): num_coupled_elements"));
938 
939     for (c = 0; c < num_coupled_elements + 1; c++)
940     {
941         uint8_t cc_target_is_cpe, cc_target_tag_select;
942 
943         num_gain_element_lists++;
944 
945         cc_target_is_cpe = faad_get1bit(ld
946             DEBUGVAR(1,903,"coupling_channel_element(): cc_target_is_cpe"));
947         cc_target_tag_select = faad_getbits(ld, 4
948             DEBUGVAR(1,904,"coupling_channel_element(): cc_target_tag_select"));
949 
950         if (cc_target_is_cpe)
951         {
952             uint8_t cc_l = faad_get1bit(ld
953                 DEBUGVAR(1,905,"coupling_channel_element(): cc_l"));
954             uint8_t cc_r = faad_get1bit(ld
955                 DEBUGVAR(1,906,"coupling_channel_element(): cc_r"));
956 
957             if (cc_l && cc_r)
958                 num_gain_element_lists++;
959         }
960     }
961 
962     faad_get1bit(ld
963         DEBUGVAR(1,907,"coupling_channel_element(): cc_domain"));
964     faad_get1bit(ld
965         DEBUGVAR(1,908,"coupling_channel_element(): gain_element_sign"));
966     faad_getbits(ld, 2
967         DEBUGVAR(1,909,"coupling_channel_element(): gain_element_scale"));
968 
969     if ((result = individual_channel_stream(hDecoder, &el_empty, ld, &ics_empty,
970         0, sh_data)) > 0)
971     {
972         return result;
973     }
974 
975     /* IS not allowed in single channel */
976     if (ics->is_used)
977         return 32;
978 
979     for (c = 1; c < num_gain_element_lists; c++)
980     {
981         uint8_t cge;
982 
983         if (ind_sw_cce_flag)
984         {
985             cge = 1;
986         } else {
987             cge = faad_get1bit(ld
988                 DEBUGVAR(1,910,"coupling_channel_element(): common_gain_element_present"));
989         }
990 
991         if (cge)
992         {
993             huffman_scale_factor(ld);
994         } else {
995             uint8_t g, sfb;
996 
997             for (g = 0; g < ics_empty.num_window_groups; g++)
998             {
999                 for (sfb = 0; sfb < ics_empty.max_sfb; sfb++)
1000                 {
1001                     if (ics_empty.sfb_cb[g][sfb] != ZERO_HCB)
1002                         huffman_scale_factor(ld);
1003                 }
1004             }
1005         }
1006     }
1007 
1008     return 0;
1009 }
1010 #endif
1011 
1012 /* Table 4.4.10 */
1013 static uint16_t data_stream_element(NeAACDecStruct *hDecoder, bitfile *ld)
1014 {
1015     uint8_t byte_aligned;
1016     uint16_t i, count;
1017 
1018     /* element_instance_tag = */ faad_getbits(ld, LEN_TAG
1019         DEBUGVAR(1,60,"data_stream_element(): element_instance_tag"));
1020     byte_aligned = faad_get1bit(ld
1021         DEBUGVAR(1,61,"data_stream_element(): byte_aligned"));
1022     count = (uint16_t)faad_getbits(ld, 8
1023         DEBUGVAR(1,62,"data_stream_element(): count"));
1024     if (count == 255)
1025     {
1026         count += (uint16_t)faad_getbits(ld, 8
1027             DEBUGVAR(1,63,"data_stream_element(): extra count"));
1028     }
1029     if (byte_aligned)
1030         faad_byte_align(ld);
1031 
1032     for (i = 0; i < count; i++)
1033     {
1034         faad_getbits(ld, LEN_BYTE
1035             DEBUGVAR(1,64,"data_stream_element(): data_stream_byte"));
1036     }
1037 
1038     return count;
1039 }
1040 
1041 /* Table 4.4.11 */
1042 static uint8_t fill_element(NeAACDecStruct *hDecoder, bitfile *ld, drc_info *drc
1043 #ifdef SBR_DEC
1044                             ,uint8_t sbr_ele
1045 #endif
1046                             )
1047 {
1048     uint16_t count;
1049 #ifdef SBR_DEC
1050     uint8_t bs_extension_type;
1051 #endif
1052 
1053     count = (uint16_t)faad_getbits(ld, 4
1054         DEBUGVAR(1,65,"fill_element(): count"));
1055     if (count == 15)
1056     {
1057         count += (uint16_t)faad_getbits(ld, 8
1058             DEBUGVAR(1,66,"fill_element(): extra count")) - 1;
1059     }
1060 
1061     if (count > 0)
1062     {
1063 #ifdef SBR_DEC
1064         bs_extension_type = (uint8_t)faad_showbits(ld, 4);
1065 
1066         if ((bs_extension_type == EXT_SBR_DATA) ||
1067             (bs_extension_type == EXT_SBR_DATA_CRC))
1068         {
1069             if (sbr_ele == INVALID_SBR_ELEMENT)
1070                 return 24;
1071 
1072             if (!hDecoder->sbr[sbr_ele])
1073             {
1074                 hDecoder->sbr[sbr_ele] = sbrDecodeInit(hDecoder->frameLength,
1075                     hDecoder->element_id[sbr_ele], 2*get_sample_rate(hDecoder->sf_index),
1076                     hDecoder->downSampledSBR
1077 #ifdef DRM
1078                     , 0
1079 #endif
1080                     );
1081             }
1082 
1083             hDecoder->sbr_present_flag = 1;
1084 
1085             /* parse the SBR data */
1086             hDecoder->sbr[sbr_ele]->ret = sbr_extension_data(ld, hDecoder->sbr[sbr_ele], count,
1087                 hDecoder->postSeekResetFlag);
1088 
1089 #if 0
1090             if (hDecoder->sbr[sbr_ele]->ret > 0)
1091             {
1092                 printf("%s\n", NeAACDecGetErrorMessage(hDecoder->sbr[sbr_ele]->ret));
1093             }
1094 #endif
1095 
1096 #if (defined(PS_DEC) || defined(DRM_PS))
1097             if (hDecoder->sbr[sbr_ele]->ps_used)
1098             {
1099                 hDecoder->ps_used[sbr_ele] = 1;
1100 
1101                 /* set element independent flag to 1 as well */
1102                 hDecoder->ps_used_global = 1;
1103             }
1104 #endif
1105         } else {
1106 #endif
1107 #ifndef DRM
1108             while (count > 0)
1109             {
1110                 count -= extension_payload(ld, drc, count);
1111             }
1112 #else
1113             return 30;
1114 #endif
1115 #ifdef SBR_DEC
1116         }
1117 #endif
1118     }
1119 
1120     return 0;
1121 }
1122 
1123 /* Table 4.4.12 */
1124 #ifdef SSR_DEC
1125 static void gain_control_data(bitfile *ld, ic_stream *ics)
1126 {
1127     uint8_t bd, wd, ad;
1128     ssr_info *ssr = &(ics->ssr);
1129 
1130     ssr->max_band = (uint8_t)faad_getbits(ld, 2
1131         DEBUGVAR(1,1000,"gain_control_data(): max_band"));
1132 
1133     if (ics->window_sequence == ONLY_LONG_SEQUENCE)
1134     {
1135         for (bd = 1; bd <= ssr->max_band; bd++)
1136         {
1137             for (wd = 0; wd < 1; wd++)
1138             {
1139                 ssr->adjust_num[bd][wd] = (uint8_t)faad_getbits(ld, 3
1140                     DEBUGVAR(1,1001,"gain_control_data(): adjust_num"));
1141 
1142                 for (ad = 0; ad < ssr->adjust_num[bd][wd]; ad++)
1143                 {
1144                     ssr->alevcode[bd][wd][ad] = (uint8_t)faad_getbits(ld, 4
1145                         DEBUGVAR(1,1002,"gain_control_data(): alevcode"));
1146                     ssr->aloccode[bd][wd][ad] = (uint8_t)faad_getbits(ld, 5
1147                         DEBUGVAR(1,1003,"gain_control_data(): aloccode"));
1148                 }
1149             }
1150         }
1151     } else if (ics->window_sequence == LONG_START_SEQUENCE) {
1152         for (bd = 1; bd <= ssr->max_band; bd++)
1153         {
1154             for (wd = 0; wd < 2; wd++)
1155             {
1156                 ssr->adjust_num[bd][wd] = (uint8_t)faad_getbits(ld, 3
1157                     DEBUGVAR(1,1001,"gain_control_data(): adjust_num"));
1158 
1159                 for (ad = 0; ad < ssr->adjust_num[bd][wd]; ad++)
1160                 {
1161                     ssr->alevcode[bd][wd][ad] = (uint8_t)faad_getbits(ld, 4
1162                         DEBUGVAR(1,1002,"gain_control_data(): alevcode"));
1163                     if (wd == 0)
1164                     {
1165                         ssr->aloccode[bd][wd][ad] = (uint8_t)faad_getbits(ld, 4
1166                             DEBUGVAR(1,1003,"gain_control_data(): aloccode"));
1167                     } else {
1168                         ssr->aloccode[bd][wd][ad] = (uint8_t)faad_getbits(ld, 2
1169                             DEBUGVAR(1,1003,"gain_control_data(): aloccode"));
1170                     }
1171                 }
1172             }
1173         }
1174     } else if (ics->window_sequence == EIGHT_SHORT_SEQUENCE) {
1175         for (bd = 1; bd <= ssr->max_band; bd++)
1176         {
1177             for (wd = 0; wd < 8; wd++)
1178             {
1179                 ssr->adjust_num[bd][wd] = (uint8_t)faad_getbits(ld, 3
1180                     DEBUGVAR(1,1001,"gain_control_data(): adjust_num"));
1181 
1182                 for (ad = 0; ad < ssr->adjust_num[bd][wd]; ad++)
1183                 {
1184                     ssr->alevcode[bd][wd][ad] = (uint8_t)faad_getbits(ld, 4
1185                         DEBUGVAR(1,1002,"gain_control_data(): alevcode"));
1186                     ssr->aloccode[bd][wd][ad] = (uint8_t)faad_getbits(ld, 2
1187                         DEBUGVAR(1,1003,"gain_control_data(): aloccode"));
1188                 }
1189             }
1190         }
1191     } else if (ics->window_sequence == LONG_STOP_SEQUENCE) {
1192         for (bd = 1; bd <= ssr->max_band; bd++)
1193         {
1194             for (wd = 0; wd < 2; wd++)
1195             {
1196                 ssr->adjust_num[bd][wd] = (uint8_t)faad_getbits(ld, 3
1197                     DEBUGVAR(1,1001,"gain_control_data(): adjust_num"));
1198 
1199                 for (ad = 0; ad < ssr->adjust_num[bd][wd]; ad++)
1200                 {
1201                     ssr->alevcode[bd][wd][ad] = (uint8_t)faad_getbits(ld, 4
1202                         DEBUGVAR(1,1002,"gain_control_data(): alevcode"));
1203 
1204                     if (wd == 0)
1205                     {
1206                         ssr->aloccode[bd][wd][ad] = (uint8_t)faad_getbits(ld, 4
1207                             DEBUGVAR(1,1003,"gain_control_data(): aloccode"));
1208                     } else {
1209                         ssr->aloccode[bd][wd][ad] = (uint8_t)faad_getbits(ld, 5
1210                             DEBUGVAR(1,1003,"gain_control_data(): aloccode"));
1211                     }
1212                 }
1213             }
1214         }
1215     }
1216 }
1217 #endif
1218 
1219 #ifdef DRM
1220 /* Table 4.4.13 ASME */
1221 void DRM_aac_scalable_main_element(NeAACDecStruct *hDecoder, NeAACDecFrameInfo *hInfo,
1222                                    bitfile *ld, program_config *pce, drc_info *drc)
1223 {
1224     uint8_t retval = 0;
1225     uint8_t channels = hDecoder->fr_channels = 0;
1226     uint8_t ch;
1227     uint8_t this_layer_stereo = (hDecoder->channelConfiguration > 1) ? 1 : 0;
1228     element cpe = {0};
1229     ic_stream *ics1 = &(cpe.ics1);
1230     ic_stream *ics2 = &(cpe.ics2);
1231     int16_t *spec_data;
1232     ALIGN int16_t spec_data1[1024] = {0};
1233     ALIGN int16_t spec_data2[1024] = {0};
1234 
1235     hDecoder->fr_ch_ele = 0;
1236 
1237     hInfo->error = DRM_aac_scalable_main_header(hDecoder, ics1, ics2, ld, this_layer_stereo);
1238     if (hInfo->error > 0)
1239         return;
1240 
1241     cpe.common_window = 1;
1242     if (this_layer_stereo)
1243     {
1244         hDecoder->element_id[0] = ID_CPE;
1245         if (hDecoder->element_output_channels[hDecoder->fr_ch_ele] == 0)
1246             hDecoder->element_output_channels[hDecoder->fr_ch_ele] = 2;
1247     } else {
1248         hDecoder->element_id[0] = ID_SCE;
1249     }
1250 
1251     if (this_layer_stereo)
1252     {
1253         cpe.channel        = 0;
1254         cpe.paired_channel = 1;
1255     }
1256 
1257 
1258     /* Stereo2 / Mono1 */
1259     ics1->tns_data_present = faad_get1bit(ld);
1260 
1261 #if defined(LTP_DEC)
1262     ics1->ltp.data_present = faad_get1bit(ld);
1263 #elif defined (DRM)
1264     if(faad_get1bit(ld)) {
1265          hInfo->error = 26;
1266          return;
1267     }
1268 #else
1269     faad_get1bit(ld);
1270 #endif
1271 
1272     hInfo->error = side_info(hDecoder, &cpe, ld, ics1, 1);
1273     if (hInfo->error > 0)
1274         return;
1275     if (this_layer_stereo)
1276     {
1277         /* Stereo3 */
1278         ics2->tns_data_present = faad_get1bit(ld);
1279 #ifdef LTP_DEC
1280         ics1->ltp.data_present =
1281 #endif
1282             faad_get1bit(ld);
1283         hInfo->error = side_info(hDecoder, &cpe, ld, ics2, 1);
1284         if (hInfo->error > 0)
1285             return;
1286     }
1287     /* Stereo4 / Mono2 */
1288     if (ics1->tns_data_present)
1289         tns_data(ics1, &(ics1->tns), ld);
1290     if (this_layer_stereo)
1291     {
1292         /* Stereo5 */
1293         if (ics2->tns_data_present)
1294             tns_data(ics2, &(ics2->tns), ld);
1295     }
1296 
1297 #ifdef DRM
1298     /* CRC check */
1299     if (hDecoder->object_type == DRM_ER_LC)
1300     {
1301         if ((hInfo->error = (uint8_t)faad_check_CRC(ld, (uint16_t)faad_get_processed_bits(ld) - 8)) > 0)
1302             return;
1303     }
1304 #endif
1305 
1306     /* Stereo6 / Mono3 */
1307     /* error resilient spectral data decoding */
1308     if ((hInfo->error = reordered_spectral_data(hDecoder, ics1, ld, spec_data1)) > 0)
1309     {
1310         return;
1311     }
1312     if (this_layer_stereo)
1313     {
1314         /* Stereo7 */
1315         /* error resilient spectral data decoding */
1316         if ((hInfo->error = reordered_spectral_data(hDecoder, ics2, ld, spec_data2)) > 0)
1317         {
1318             return;
1319         }
1320     }
1321 
1322 
1323 #ifdef DRM
1324 #ifdef SBR_DEC
1325     /* In case of DRM we need to read the SBR info before channel reconstruction */
1326     if ((hDecoder->sbr_present_flag == 1) && (hDecoder->object_type == DRM_ER_LC))
1327     {
1328         bitfile ld_sbr = {0};
1329         uint32_t i;
1330         uint16_t count = 0;
1331         uint8_t *revbuffer;
1332         uint8_t *prevbufstart;
1333         uint8_t *pbufend;
1334 
1335         /* all forward bitreading should be finished at this point */
1336         uint32_t bitsconsumed = faad_get_processed_bits(ld);
1337         uint32_t buffer_size = faad_origbitbuffer_size(ld);
1338         uint8_t *buffer = (uint8_t*)faad_origbitbuffer(ld);
1339 
1340         if (bitsconsumed + 8 > buffer_size*8)
1341         {
1342             hInfo->error = 14;
1343             return;
1344         }
1345 
1346         if (!hDecoder->sbr[0])
1347         {
1348             hDecoder->sbr[0] = sbrDecodeInit(hDecoder->frameLength, hDecoder->element_id[0],
1349                 2*get_sample_rate(hDecoder->sf_index), 0 /* ds SBR */, 1);
1350         }
1351 
1352         /* Reverse bit reading of SBR data in DRM audio frame */
1353         revbuffer = (uint8_t*)faad_malloc(buffer_size*sizeof(uint8_t));
1354         prevbufstart = revbuffer;
1355         pbufend = &buffer[buffer_size - 1];
1356         for (i = 0; i < buffer_size; i++)
1357             *prevbufstart++ = tabFlipbits[*pbufend--];
1358 
1359         /* Set SBR data */
1360         /* consider 8 bits from AAC-CRC */
1361         /* SBR buffer size is original buffer size minus AAC buffer size */
1362         count = (uint16_t)bit2byte(buffer_size*8 - bitsconsumed);
1363         faad_initbits(&ld_sbr, revbuffer, count);
1364 
1365         hDecoder->sbr[0]->sample_rate = get_sample_rate(hDecoder->sf_index);
1366         hDecoder->sbr[0]->sample_rate *= 2;
1367 
1368         faad_getbits(&ld_sbr, 8); /* Skip 8-bit CRC */
1369 
1370         hDecoder->sbr[0]->ret = sbr_extension_data(&ld_sbr, hDecoder->sbr[0], count, hDecoder->postSeekResetFlag);
1371 #if (defined(PS_DEC) || defined(DRM_PS))
1372         if (hDecoder->sbr[0]->ps_used)
1373         {
1374             hDecoder->ps_used[0] = 1;
1375             hDecoder->ps_used_global = 1;
1376         }
1377 #endif
1378 
1379         if (ld_sbr.error)
1380         {
1381             hDecoder->sbr[0]->ret = 1;
1382         }
1383 
1384         /* check CRC */
1385         /* no need to check it if there was already an error */
1386         if (hDecoder->sbr[0]->ret == 0)
1387             hDecoder->sbr[0]->ret = (uint8_t)faad_check_CRC(&ld_sbr, (uint16_t)faad_get_processed_bits(&ld_sbr) - 8);
1388 
1389         /* SBR data was corrupted, disable it until the next header */
1390         if (hDecoder->sbr[0]->ret != 0)
1391         {
1392             hDecoder->sbr[0]->header_count = 0;
1393         }
1394 
1395         faad_endbits(&ld_sbr);
1396 
1397         if (revbuffer)
1398             faad_free(revbuffer);
1399     }
1400 #endif
1401 #endif
1402 
1403     if (this_layer_stereo)
1404     {
1405         hInfo->error = reconstruct_channel_pair(hDecoder, ics1, ics2, &cpe, spec_data1, spec_data2);
1406         if (hInfo->error > 0)
1407             return;
1408     } else {
1409         hInfo->error = reconstruct_single_channel(hDecoder, ics1, &cpe, spec_data1);
1410         if (hInfo->error > 0)
1411             return;
1412     }
1413 
1414     /* map output channels position to internal data channels */
1415     if (hDecoder->element_output_channels[hDecoder->fr_ch_ele] == 2)
1416     {
1417         /* this might be faulty when pce_set is true */
1418         hDecoder->internal_channel[channels] = channels;
1419         hDecoder->internal_channel[channels+1] = channels+1;
1420     } else {
1421         hDecoder->internal_channel[channels] = channels;
1422     }
1423 
1424     hDecoder->fr_channels += hDecoder->element_output_channels[hDecoder->fr_ch_ele];
1425     hDecoder->fr_ch_ele++;
1426 
1427     return;
1428 }
1429 
1430 /* Table 4.4.15 */
1431 static int8_t DRM_aac_scalable_main_header(NeAACDecStruct *hDecoder, ic_stream *ics1, ic_stream *ics2,
1432                                            bitfile *ld, uint8_t this_layer_stereo)
1433 {
1434     uint8_t retval = 0;
1435     uint8_t ch;
1436     ic_stream *ics;
1437     uint8_t ics_reserved_bit;
1438 
1439     ics_reserved_bit = faad_get1bit(ld
1440         DEBUGVAR(1,300,"aac_scalable_main_header(): ics_reserved_bits"));
1441     if (ics_reserved_bit != 0)
1442         return 32;
1443     ics1->window_sequence = (uint8_t)faad_getbits(ld, 2
1444         DEBUGVAR(1,301,"aac_scalable_main_header(): window_sequence"));
1445     ics1->window_shape = faad_get1bit(ld
1446         DEBUGVAR(1,302,"aac_scalable_main_header(): window_shape"));
1447 
1448     if (ics1->window_sequence == EIGHT_SHORT_SEQUENCE)
1449     {
1450         ics1->max_sfb = (uint8_t)faad_getbits(ld, 4
1451             DEBUGVAR(1,303,"aac_scalable_main_header(): max_sfb (short)"));
1452         ics1->scale_factor_grouping = (uint8_t)faad_getbits(ld, 7
1453             DEBUGVAR(1,304,"aac_scalable_main_header(): scale_factor_grouping"));
1454     } else {
1455         ics1->max_sfb = (uint8_t)faad_getbits(ld, 6
1456             DEBUGVAR(1,305,"aac_scalable_main_header(): max_sfb (long)"));
1457     }
1458 
1459     /* get the grouping information */
1460     if ((retval = window_grouping_info(hDecoder, ics1)) > 0)
1461         return retval;
1462 
1463     /* should be an error */
1464     /* check the range of max_sfb */
1465     if (ics1->max_sfb > ics1->num_swb)
1466         return 16;
1467 
1468     if (this_layer_stereo)
1469     {
1470         ics1->ms_mask_present = (uint8_t)faad_getbits(ld, 2
1471             DEBUGVAR(1,306,"aac_scalable_main_header(): ms_mask_present"));
1472         if (ics1->ms_mask_present == 3)
1473         {
1474             /* bitstream error */
1475             return 32;
1476         }
1477         if (ics1->ms_mask_present == 1)
1478         {
1479             uint8_t g, sfb;
1480             for (g = 0; g < ics1->num_window_groups; g++)
1481             {
1482                 for (sfb = 0; sfb < ics1->max_sfb; sfb++)
1483                 {
1484                     ics1->ms_used[g][sfb] = faad_get1bit(ld
1485                         DEBUGVAR(1,307,"aac_scalable_main_header(): faad_get1bit"));
1486                 }
1487             }
1488         }
1489 
1490         memcpy(ics2, ics1, sizeof(ic_stream));
1491     } else {
1492         ics1->ms_mask_present = 0;
1493     }
1494 
1495     return 0;
1496 }
1497 #endif
1498 
1499 static uint8_t side_info(NeAACDecStruct *hDecoder, element *ele,
1500                          bitfile *ld, ic_stream *ics, uint8_t scal_flag)
1501 {
1502     uint8_t result;
1503 
1504     ics->global_gain = (uint8_t)faad_getbits(ld, 8
1505         DEBUGVAR(1,67,"individual_channel_stream(): global_gain"));
1506 
1507     if (!ele->common_window && !scal_flag)
1508     {
1509         if ((result = ics_info(hDecoder, ics, ld, ele->common_window)) > 0)
1510             return result;
1511     }
1512 
1513     if ((result = section_data(hDecoder, ics, ld)) > 0)
1514         return result;
1515 
1516     if ((result = scale_factor_data(hDecoder, ics, ld)) > 0)
1517         return result;
1518 
1519     if (!scal_flag)
1520     {
1521         /**
1522          **  NOTE: It could be that pulse data is available in scalable AAC too,
1523          **        as said in Amendment 1, this could be only the case for ER AAC,
1524          **        though. (have to check this out later)
1525          **/
1526         /* get pulse data */
1527         if ((ics->pulse_data_present = faad_get1bit(ld
1528             DEBUGVAR(1,68,"individual_channel_stream(): pulse_data_present"))) & 1)
1529         {
1530             if ((result = pulse_data(ics, &(ics->pul), ld)) > 0)
1531                 return result;
1532         }
1533 
1534         /* get tns data */
1535         if ((ics->tns_data_present = faad_get1bit(ld
1536             DEBUGVAR(1,69,"individual_channel_stream(): tns_data_present"))) & 1)
1537         {
1538 #ifdef ERROR_RESILIENCE
1539             if (hDecoder->object_type < ER_OBJECT_START)
1540 #endif
1541                 tns_data(ics, &(ics->tns), ld);
1542         }
1543 
1544         /* get gain control data */
1545         if ((ics->gain_control_data_present = faad_get1bit(ld
1546             DEBUGVAR(1,70,"individual_channel_stream(): gain_control_data_present"))) & 1)
1547         {
1548 #ifdef SSR_DEC
1549             if (hDecoder->object_type != SSR)
1550                 return 1;
1551             else
1552                 gain_control_data(ld, ics);
1553 #else
1554             return 1;
1555 #endif
1556         }
1557     }
1558 
1559 #ifdef ERROR_RESILIENCE
1560     if (hDecoder->aacSpectralDataResilienceFlag)
1561     {
1562         ics->length_of_reordered_spectral_data = (uint16_t)faad_getbits(ld, 14
1563             DEBUGVAR(1,147,"individual_channel_stream(): length_of_reordered_spectral_data"));
1564 
1565         if (hDecoder->channelConfiguration == 2)
1566         {
1567             if (ics->length_of_reordered_spectral_data > 6144)
1568                 ics->length_of_reordered_spectral_data = 6144;
1569         } else {
1570             if (ics->length_of_reordered_spectral_data > 12288)
1571                 ics->length_of_reordered_spectral_data = 12288;
1572         }
1573 
1574         ics->length_of_longest_codeword = (uint8_t)faad_getbits(ld, 6
1575             DEBUGVAR(1,148,"individual_channel_stream(): length_of_longest_codeword"));
1576         if (ics->length_of_longest_codeword >= 49)
1577             ics->length_of_longest_codeword = 49;
1578     }
1579 
1580     /* RVLC spectral data is put here */
1581     if (hDecoder->aacScalefactorDataResilienceFlag)
1582     {
1583         if ((result = rvlc_decode_scale_factors(ics, ld)) > 0)
1584             return result;
1585     }
1586 #endif
1587 
1588     return 0;
1589 }
1590 
1591 /* Table 4.4.24 */
1592 static uint8_t individual_channel_stream(NeAACDecStruct *hDecoder, element *ele,
1593                                          bitfile *ld, ic_stream *ics, uint8_t scal_flag,
1594                                          int16_t *spec_data)
1595 {
1596     uint8_t result;
1597 
1598     result = side_info(hDecoder, ele, ld, ics, scal_flag);
1599     if (result > 0)
1600         return result;
1601 
1602     if (hDecoder->object_type >= ER_OBJECT_START)
1603     {
1604         if (ics->tns_data_present)
1605             tns_data(ics, &(ics->tns), ld);
1606     }
1607 
1608 #ifdef DRM
1609     /* CRC check */
1610     if (hDecoder->object_type == DRM_ER_LC)
1611     {
1612         if ((result = (uint8_t)faad_check_CRC(ld, (uint16_t)faad_get_processed_bits(ld) - 8)) > 0)
1613             return result;
1614     }
1615 #endif
1616 
1617 #ifdef ERROR_RESILIENCE
1618     if (hDecoder->aacSpectralDataResilienceFlag)
1619     {
1620         /* error resilient spectral data decoding */
1621         if ((result = reordered_spectral_data(hDecoder, ics, ld, spec_data)) > 0)
1622         {
1623             return result;
1624         }
1625     } else {
1626 #endif
1627         /* decode the spectral data */
1628         if ((result = spectral_data(hDecoder, ics, ld, spec_data)) > 0)
1629         {
1630             return result;
1631         }
1632 #ifdef ERROR_RESILIENCE
1633     }
1634 #endif
1635 
1636     /* pulse coding reconstruction */
1637     if (ics->pulse_data_present)
1638     {
1639         if (ics->window_sequence != EIGHT_SHORT_SEQUENCE)
1640         {
1641             if ((result = pulse_decode(ics, spec_data, hDecoder->frameLength)) > 0)
1642                 return result;
1643         } else {
1644             return 2; /* pulse coding not allowed for short blocks */
1645         }
1646     }
1647 
1648     return 0;
1649 }
1650 
1651 /* Table 4.4.25 */
1652 static uint8_t section_data(NeAACDecStruct *hDecoder, ic_stream *ics, bitfile *ld)
1653 {
1654     uint8_t g;
1655     uint8_t sect_esc_val, sect_bits;
1656 
1657     if (ics->window_sequence == EIGHT_SHORT_SEQUENCE)
1658         sect_bits = 3;
1659     else
1660         sect_bits = 5;
1661     sect_esc_val = (1<<sect_bits) - 1;
1662 
1663 #if 0
1664     printf("\ntotal sfb %d\n", ics->max_sfb);
1665     printf("   sect    top     cb\n");
1666 #endif
1667 
1668     for (g = 0; g < ics->num_window_groups; g++)
1669     {
1670         uint8_t k = 0;
1671         uint8_t i = 0;
1672 
1673         while (k < ics->max_sfb)
1674         {
1675 #ifdef ERROR_RESILIENCE
1676             uint8_t vcb11 = 0;
1677 #endif
1678             uint8_t sfb;
1679             uint8_t sect_len_incr;
1680             uint16_t sect_len = 0;
1681             uint8_t sect_cb_bits = 4;
1682 
1683             /* if "faad_getbits" detects error and returns "0", "k" is never
1684                incremented and we cannot leave the while loop */
1685             if (ld->error != 0)
1686                 return 14;
1687 
1688 #ifdef ERROR_RESILIENCE
1689             if (hDecoder->aacSectionDataResilienceFlag)
1690                 sect_cb_bits = 5;
1691 #endif
1692 
1693             ics->sect_cb[g][i] = (uint8_t)faad_getbits(ld, sect_cb_bits
1694                 DEBUGVAR(1,71,"section_data(): sect_cb"));
1695 
1696             if (ics->sect_cb[g][i] == 12)
1697                 return 32;
1698 
1699 #if 0
1700             printf("%d\n", ics->sect_cb[g][i]);
1701 #endif
1702 
1703 #ifndef DRM
1704             if (ics->sect_cb[g][i] == NOISE_HCB)
1705                 ics->noise_used = 1;
1706 #else
1707             /* PNS not allowed in DRM */
1708             if (ics->sect_cb[g][i] == NOISE_HCB)
1709                 return 29;
1710 #endif
1711             if (ics->sect_cb[g][i] == INTENSITY_HCB2 || ics->sect_cb[g][i] == INTENSITY_HCB)
1712                 ics->is_used = 1;
1713 
1714 #ifdef ERROR_RESILIENCE
1715             if (hDecoder->aacSectionDataResilienceFlag)
1716             {
1717                 if ((ics->sect_cb[g][i] == 11) ||
1718                     ((ics->sect_cb[g][i] >= 16) && (ics->sect_cb[g][i] <= 32)))
1719                 {
1720                     vcb11 = 1;
1721                 }
1722             }
1723             if (vcb11)
1724             {
1725                 sect_len_incr = 1;
1726             } else {
1727 #endif
1728                 sect_len_incr = (uint8_t)faad_getbits(ld, sect_bits
1729                     DEBUGVAR(1,72,"section_data(): sect_len_incr"));
1730 #ifdef ERROR_RESILIENCE
1731             }
1732 #endif
1733             while ((sect_len_incr == sect_esc_val) /* &&
1734                 (k+sect_len < ics->max_sfb)*/)
1735             {
1736                 sect_len += sect_len_incr;
1737                 sect_len_incr = (uint8_t)faad_getbits(ld, sect_bits
1738                     DEBUGVAR(1,72,"section_data(): sect_len_incr"));
1739             }
1740 
1741             sect_len += sect_len_incr;
1742 
1743             ics->sect_start[g][i] = k;
1744             ics->sect_end[g][i] = k + sect_len;
1745 
1746 #if 0
1747             printf("%d\n", ics->sect_start[g][i]);
1748 #endif
1749 #if 0
1750             printf("%d\n", ics->sect_end[g][i]);
1751 #endif
1752 
1753             if (ics->window_sequence == EIGHT_SHORT_SEQUENCE)
1754             {
1755                 if (k + sect_len > 8*15)
1756                     return 15;
1757                 if (i >= 8*15)
1758                     return 15;
1759             } else {
1760                 if (k + sect_len > MAX_SFB)
1761                     return 15;
1762                 if (i >= MAX_SFB)
1763                     return 15;
1764             }
1765 
1766             for (sfb = k; sfb < k + sect_len; sfb++)
1767             {
1768                 ics->sfb_cb[g][sfb] = ics->sect_cb[g][i];
1769 #if 0
1770                 printf("%d\n", ics->sfb_cb[g][sfb]);
1771 #endif
1772             }
1773 
1774 #if 0
1775             printf(" %6d %6d %6d\n",
1776                 i,
1777                 ics->sect_end[g][i],
1778                 ics->sect_cb[g][i]);
1779 #endif
1780 
1781             k += sect_len;
1782             i++;
1783         }
1784         ics->num_sec[g] = i;
1785 
1786         /* the sum of all sect_len_incr elements for a given window
1787          * group shall equal max_sfb */
1788         if (k != ics->max_sfb)
1789         {
1790             return 32;
1791         }
1792 #if 0
1793         printf("%d\n", ics->num_sec[g]);
1794 #endif
1795     }
1796 
1797 #if 0
1798     printf("\n");
1799 #endif
1800 
1801     return 0;
1802 }
1803 
1804 /*
1805  *  decode_scale_factors()
1806  *   decodes the scalefactors from the bitstream
1807  */
1808 /*
1809  * All scalefactors (and also the stereo positions and pns energies) are
1810  * transmitted using Huffman coded DPCM relative to the previous active
1811  * scalefactor (respectively previous stereo position or previous pns energy,
1812  * see subclause 4.6.2 and 4.6.3). The first active scalefactor is
1813  * differentially coded relative to the global gain.
1814  */
1815 static uint8_t decode_scale_factors(ic_stream *ics, bitfile *ld)
1816 {
1817     uint8_t g, sfb;
1818     int16_t t;
1819     int8_t noise_pcm_flag = 1;
1820 
1821     int16_t scale_factor = ics->global_gain;
1822     int16_t is_position = 0;
1823     int16_t noise_energy = ics->global_gain - 90;
1824 
1825     for (g = 0; g < ics->num_window_groups; g++)
1826     {
1827         for (sfb = 0; sfb < ics->max_sfb; sfb++)
1828         {
1829             switch (ics->sfb_cb[g][sfb])
1830             {
1831             case ZERO_HCB: /* zero book */
1832                 ics->scale_factors[g][sfb] = 0;
1833 //#define SF_PRINT
1834 #ifdef SF_PRINT
1835                 printf("%d\n", ics->scale_factors[g][sfb]);
1836 #endif
1837                 break;
1838             case INTENSITY_HCB: /* intensity books */
1839             case INTENSITY_HCB2:
1840 
1841                 /* decode intensity position */
1842                 t = huffman_scale_factor(ld);
1843                 is_position += (t - 60);
1844                 ics->scale_factors[g][sfb] = is_position;
1845 #ifdef SF_PRINT
1846                 printf("%d\n", ics->scale_factors[g][sfb]);
1847 #endif
1848 
1849                 break;
1850             case NOISE_HCB: /* noise books */
1851 
1852 #ifndef DRM
1853                 /* decode noise energy */
1854                 if (noise_pcm_flag)
1855                 {
1856                     noise_pcm_flag = 0;
1857                     t = (int16_t)faad_getbits(ld, 9
1858                         DEBUGVAR(1,73,"scale_factor_data(): first noise")) - 256;
1859                 } else {
1860                     t = huffman_scale_factor(ld);
1861                     t -= 60;
1862                 }
1863                 noise_energy += t;
1864                 ics->scale_factors[g][sfb] = noise_energy;
1865 #ifdef SF_PRINT
1866                 printf("%d\n", ics->scale_factors[g][sfb]);
1867 #endif
1868 #else
1869                 /* PNS not allowed in DRM */
1870                 return 29;
1871 #endif
1872 
1873                 break;
1874             default: /* spectral books */
1875 
1876                 /* ics->scale_factors[g][sfb] must be between 0 and 255 */
1877 
1878                 ics->scale_factors[g][sfb] = 0;
1879 
1880                 /* decode scale factor */
1881                 t = huffman_scale_factor(ld);
1882                 scale_factor += (t - 60);
1883                 if (scale_factor < 0 || scale_factor > 255)
1884                     return 4;
1885                 ics->scale_factors[g][sfb] = scale_factor;
1886 #ifdef SF_PRINT
1887                 printf("%d\n", ics->scale_factors[g][sfb]);
1888 #endif
1889 
1890                 break;
1891             }
1892         }
1893     }
1894 
1895     return 0;
1896 }
1897 
1898 /* Table 4.4.26 */
1899 static uint8_t scale_factor_data(NeAACDecStruct *hDecoder, ic_stream *ics, bitfile *ld)
1900 {
1901     uint8_t ret = 0;
1902 #ifdef PROFILE
1903     int64_t count = faad_get_ts();
1904 #endif
1905 
1906 #ifdef ERROR_RESILIENCE
1907     if (!hDecoder->aacScalefactorDataResilienceFlag)
1908     {
1909 #endif
1910         ret = decode_scale_factors(ics, ld);
1911 #ifdef ERROR_RESILIENCE
1912     } else {
1913         /* In ER AAC the parameters for RVLC are seperated from the actual
1914            data that holds the scale_factors.
1915            Strangely enough, 2 parameters for HCR are put inbetween them.
1916         */
1917         ret = rvlc_scale_factor_data(ics, ld);
1918     }
1919 #endif
1920 
1921 #ifdef PROFILE
1922     count = faad_get_ts() - count;
1923     hDecoder->scalefac_cycles += count;
1924 #endif
1925 
1926     return ret;
1927 }
1928 
1929 /* Table 4.4.27 */
1930 static void tns_data(ic_stream *ics, tns_info *tns, bitfile *ld)
1931 {
1932     uint8_t w, filt, i, start_coef_bits, coef_bits;
1933     uint8_t n_filt_bits = 2;
1934     uint8_t length_bits = 6;
1935     uint8_t order_bits = 5;
1936 
1937     if (ics->window_sequence == EIGHT_SHORT_SEQUENCE)
1938     {
1939         n_filt_bits = 1;
1940         length_bits = 4;
1941         order_bits = 3;
1942     }
1943 
1944     for (w = 0; w < ics->num_windows; w++)
1945     {
1946         tns->n_filt[w] = (uint8_t)faad_getbits(ld, n_filt_bits
1947             DEBUGVAR(1,74,"tns_data(): n_filt"));
1948 #if 0
1949         printf("%d\n", tns->n_filt[w]);
1950 #endif
1951 
1952         if (tns->n_filt[w])
1953         {
1954             if ((tns->coef_res[w] = faad_get1bit(ld
1955                 DEBUGVAR(1,75,"tns_data(): coef_res"))) & 1)
1956             {
1957                 start_coef_bits = 4;
1958             } else {
1959                 start_coef_bits = 3;
1960             }
1961 #if 0
1962             printf("%d\n", tns->coef_res[w]);
1963 #endif
1964         }
1965 
1966         for (filt = 0; filt < tns->n_filt[w]; filt++)
1967         {
1968             tns->length[w][filt] = (uint8_t)faad_getbits(ld, length_bits
1969                 DEBUGVAR(1,76,"tns_data(): length"));
1970 #if 0
1971             printf("%d\n", tns->length[w][filt]);
1972 #endif
1973             tns->order[w][filt]  = (uint8_t)faad_getbits(ld, order_bits
1974                 DEBUGVAR(1,77,"tns_data(): order"));
1975 #if 0
1976             printf("%d\n", tns->order[w][filt]);
1977 #endif
1978             if (tns->order[w][filt])
1979             {
1980                 tns->direction[w][filt] = faad_get1bit(ld
1981                     DEBUGVAR(1,78,"tns_data(): direction"));
1982 #if 0
1983                 printf("%d\n", tns->direction[w][filt]);
1984 #endif
1985                 tns->coef_compress[w][filt] = faad_get1bit(ld
1986                     DEBUGVAR(1,79,"tns_data(): coef_compress"));
1987 #if 0
1988                 printf("%d\n", tns->coef_compress[w][filt]);
1989 #endif
1990 
1991                 coef_bits = start_coef_bits - tns->coef_compress[w][filt];
1992                 for (i = 0; i < tns->order[w][filt]; i++)
1993                 {
1994                     tns->coef[w][filt][i] = (uint8_t)faad_getbits(ld, coef_bits
1995                         DEBUGVAR(1,80,"tns_data(): coef"));
1996 #if 0
1997                     printf("%d\n", tns->coef[w][filt][i]);
1998 #endif
1999                 }
2000             }
2001         }
2002     }
2003 }
2004 
2005 #ifdef LTP_DEC
2006 /* Table 4.4.28 */
2007 static uint8_t ltp_data(NeAACDecStruct *hDecoder, ic_stream *ics, ltp_info *ltp, bitfile *ld)
2008 {
2009     uint8_t sfb, w;
2010 
2011     ltp->lag = 0;
2012 
2013 #ifdef LD_DEC
2014     if (hDecoder->object_type == LD)
2015     {
2016         ltp->lag_update = (uint8_t)faad_getbits(ld, 1
2017             DEBUGVAR(1,142,"ltp_data(): lag_update"));
2018 
2019         if (ltp->lag_update)
2020         {
2021             ltp->lag = (uint16_t)faad_getbits(ld, 10
2022                 DEBUGVAR(1,81,"ltp_data(): lag"));
2023         }
2024     } else {
2025 #endif
2026         ltp->lag = (uint16_t)faad_getbits(ld, 11
2027             DEBUGVAR(1,81,"ltp_data(): lag"));
2028 #ifdef LD_DEC
2029     }
2030 #endif
2031 
2032     /* Check length of lag */
2033     if (ltp->lag > (hDecoder->frameLength << 1))
2034         return 18;
2035 
2036     ltp->coef = (uint8_t)faad_getbits(ld, 3
2037         DEBUGVAR(1,82,"ltp_data(): coef"));
2038 
2039     if (ics->window_sequence == EIGHT_SHORT_SEQUENCE)
2040     {
2041         for (w = 0; w < ics->num_windows; w++)
2042         {
2043             if ((ltp->short_used[w] = faad_get1bit(ld
2044                 DEBUGVAR(1,83,"ltp_data(): short_used"))) & 1)
2045             {
2046                 ltp->short_lag_present[w] = faad_get1bit(ld
2047                     DEBUGVAR(1,84,"ltp_data(): short_lag_present"));
2048                 if (ltp->short_lag_present[w])
2049                 {
2050                     ltp->short_lag[w] = (uint8_t)faad_getbits(ld, 4
2051                         DEBUGVAR(1,85,"ltp_data(): short_lag"));
2052                 }
2053             }
2054         }
2055     } else {
2056         ltp->last_band = (ics->max_sfb < MAX_LTP_SFB ? ics->max_sfb : MAX_LTP_SFB);
2057 
2058         for (sfb = 0; sfb < ltp->last_band; sfb++)
2059         {
2060             ltp->long_used[sfb] = faad_get1bit(ld
2061                 DEBUGVAR(1,86,"ltp_data(): long_used"));
2062         }
2063     }
2064 
2065     return 0;
2066 }
2067 #endif
2068 
2069 /* Table 4.4.29 */
2070 static uint8_t spectral_data(NeAACDecStruct *hDecoder, ic_stream *ics, bitfile *ld,
2071                              int16_t *spectral_data)
2072 {
2073     int8_t i;
2074     uint8_t g;
2075     uint16_t inc, k, p = 0;
2076     uint8_t groups = 0;
2077     uint8_t sect_cb;
2078     uint8_t result;
2079     uint16_t nshort = hDecoder->frameLength/8;
2080 
2081 #ifdef PROFILE
2082     int64_t count = faad_get_ts();
2083 #endif
2084 
2085     for(g = 0; g < ics->num_window_groups; g++)
2086     {
2087         p = groups*nshort;
2088 
2089         for (i = 0; i < ics->num_sec[g]; i++)
2090         {
2091             sect_cb = ics->sect_cb[g][i];
2092 
2093             inc = (sect_cb >= FIRST_PAIR_HCB) ? 2 : 4;
2094 
2095             switch (sect_cb)
2096             {
2097             case ZERO_HCB:
2098             case NOISE_HCB:
2099             case INTENSITY_HCB:
2100             case INTENSITY_HCB2:
2101 //#define SD_PRINT
2102 #ifdef SD_PRINT
2103                 {
2104                     int j;
2105                     for (j = ics->sect_sfb_offset[g][ics->sect_start[g][i]]; j < ics->sect_sfb_offset[g][ics->sect_end[g][i]]; j++)
2106                     {
2107                         printf("%d\n", 0);
2108                     }
2109                 }
2110 #endif
2111 //#define SFBO_PRINT
2112 #ifdef SFBO_PRINT
2113                 printf("%d\n", ics->sect_sfb_offset[g][ics->sect_start[g][i]]);
2114 #endif
2115                 p += (ics->sect_sfb_offset[g][ics->sect_end[g][i]] -
2116                     ics->sect_sfb_offset[g][ics->sect_start[g][i]]);
2117                 break;
2118             default:
2119 #ifdef SFBO_PRINT
2120                 printf("%d\n", ics->sect_sfb_offset[g][ics->sect_start[g][i]]);
2121 #endif
2122                 for (k = ics->sect_sfb_offset[g][ics->sect_start[g][i]];
2123                      k < ics->sect_sfb_offset[g][ics->sect_end[g][i]]; k += inc)
2124                 {
2125                     if ((result = huffman_spectral_data(sect_cb, ld, &spectral_data[p])) > 0)
2126                         return result;
2127 #ifdef SD_PRINT
2128                     {
2129                         int j;
2130                         for (j = p; j < p+inc; j++)
2131                         {
2132                             printf("%d\n", spectral_data[j]);
2133                         }
2134                     }
2135 #endif
2136                     p += inc;
2137                 }
2138                 break;
2139             }
2140         }
2141         groups += ics->window_group_length[g];
2142     }
2143 
2144 #ifdef PROFILE
2145     count = faad_get_ts() - count;
2146     hDecoder->spectral_cycles += count;
2147 #endif
2148 
2149     return 0;
2150 }
2151 
2152 /* Table 4.4.30 */
2153 static uint16_t extension_payload(bitfile *ld, drc_info *drc, uint16_t count)
2154 {
2155     uint16_t i, n, dataElementLength;
2156     uint8_t dataElementLengthPart;
2157     uint8_t align = 4, data_element_version, loopCounter;
2158 
2159     uint8_t extension_type = (uint8_t)faad_getbits(ld, 4
2160         DEBUGVAR(1,87,"extension_payload(): extension_type"));
2161 
2162     switch (extension_type)
2163     {
2164     case EXT_DYNAMIC_RANGE:
2165         drc->present = 1;
2166         n = dynamic_range_info(ld, drc);
2167         return n;
2168     case EXT_FILL_DATA:
2169         /* fill_nibble = */ faad_getbits(ld, 4
2170             DEBUGVAR(1,136,"extension_payload(): fill_nibble")); /* must be �0000� */
2171         for (i = 0; i < count-1; i++)
2172         {
2173             /* fill_byte[i] = */ faad_getbits(ld, 8
2174                 DEBUGVAR(1,88,"extension_payload(): fill_byte")); /* must be �10100101� */
2175         }
2176         return count;
2177     case EXT_DATA_ELEMENT:
2178         data_element_version = (uint8_t)faad_getbits(ld, 4
2179             DEBUGVAR(1,400,"extension_payload(): data_element_version"));
2180         switch (data_element_version)
2181         {
2182         case ANC_DATA:
2183             loopCounter = 0;
2184             dataElementLength = 0;
2185             do {
2186                 dataElementLengthPart = (uint8_t)faad_getbits(ld, 8
2187                     DEBUGVAR(1,401,"extension_payload(): dataElementLengthPart"));
2188                 dataElementLength += dataElementLengthPart;
2189                 loopCounter++;
2190             } while (dataElementLengthPart == 255);
2191 
2192             for (i = 0; i < dataElementLength; i++)
2193             {
2194                 /* data_element_byte[i] = */ faad_getbits(ld, 8
2195                     DEBUGVAR(1,402,"extension_payload(): data_element_byte"));
2196                 return (dataElementLength+loopCounter+1);
2197             }
2198         default:
2199             align = 0;
2200         }
2201     case EXT_FIL:
2202     default:
2203         faad_getbits(ld, align
2204             DEBUGVAR(1,88,"extension_payload(): fill_nibble"));
2205         for (i = 0; i < count-1; i++)
2206         {
2207             /* other_bits[i] = */ faad_getbits(ld, 8
2208                DEBUGVAR(1,89,"extension_payload(): fill_bit"));
2209         }
2210         return count;
2211     }
2212 }
2213 
2214 /* Table 4.4.31 */
2215 static uint8_t dynamic_range_info(bitfile *ld, drc_info *drc)
2216 {
2217     uint8_t i, n = 1;
2218     uint8_t band_incr;
2219 
2220     drc->num_bands = 1;
2221 
2222     if (faad_get1bit(ld
2223         DEBUGVAR(1,90,"dynamic_range_info(): has instance_tag")) & 1)
2224     {
2225         drc->pce_instance_tag = (uint8_t)faad_getbits(ld, 4
2226             DEBUGVAR(1,91,"dynamic_range_info(): pce_instance_tag"));
2227         /* drc->drc_tag_reserved_bits = */ faad_getbits(ld, 4
2228             DEBUGVAR(1,92,"dynamic_range_info(): drc_tag_reserved_bits"));
2229         n++;
2230     }
2231 
2232     drc->excluded_chns_present = faad_get1bit(ld
2233         DEBUGVAR(1,93,"dynamic_range_info(): excluded_chns_present"));
2234     if (drc->excluded_chns_present == 1)
2235     {
2236         n += excluded_channels(ld, drc);
2237     }
2238 
2239     if (faad_get1bit(ld
2240         DEBUGVAR(1,94,"dynamic_range_info(): has bands data")) & 1)
2241     {
2242         band_incr = (uint8_t)faad_getbits(ld, 4
2243             DEBUGVAR(1,95,"dynamic_range_info(): band_incr"));
2244         /* drc->drc_bands_reserved_bits = */ faad_getbits(ld, 4
2245             DEBUGVAR(1,96,"dynamic_range_info(): drc_bands_reserved_bits"));
2246         n++;
2247         drc->num_bands += band_incr;
2248 
2249         for (i = 0; i < drc->num_bands; i++)
2250         {
2251             drc->band_top[i] = (uint8_t)faad_getbits(ld, 8
2252                 DEBUGVAR(1,97,"dynamic_range_info(): band_top"));
2253             n++;
2254         }
2255     }
2256 
2257     if (faad_get1bit(ld
2258         DEBUGVAR(1,98,"dynamic_range_info(): has prog_ref_level")) & 1)
2259     {
2260         drc->prog_ref_level = (uint8_t)faad_getbits(ld, 7
2261             DEBUGVAR(1,99,"dynamic_range_info(): prog_ref_level"));
2262         /* drc->prog_ref_level_reserved_bits = */ faad_get1bit(ld
2263             DEBUGVAR(1,100,"dynamic_range_info(): prog_ref_level_reserved_bits"));
2264         n++;
2265     }
2266 
2267     for (i = 0; i < drc->num_bands; i++)
2268     {
2269         drc->dyn_rng_sgn[i] = faad_get1bit(ld
2270             DEBUGVAR(1,101,"dynamic_range_info(): dyn_rng_sgn"));
2271         drc->dyn_rng_ctl[i] = (uint8_t)faad_getbits(ld, 7
2272             DEBUGVAR(1,102,"dynamic_range_info(): dyn_rng_ctl"));
2273         n++;
2274     }
2275 
2276     return n;
2277 }
2278 
2279 /* Table 4.4.32 */
2280 static uint8_t excluded_channels(bitfile *ld, drc_info *drc)
2281 {
2282     uint8_t i, n = 0;
2283     uint8_t num_excl_chan = 7;
2284 
2285     for (i = 0; i < 7; i++)
2286     {
2287         drc->exclude_mask[i] = faad_get1bit(ld
2288             DEBUGVAR(1,103,"excluded_channels(): exclude_mask"));
2289     }
2290     n++;
2291 
2292     while ((drc->additional_excluded_chns[n-1] = faad_get1bit(ld
2293         DEBUGVAR(1,104,"excluded_channels(): additional_excluded_chns"))) == 1)
2294     {
2295         for (i = num_excl_chan; i < num_excl_chan+7; i++)
2296         {
2297             drc->exclude_mask[i] = faad_get1bit(ld
2298                 DEBUGVAR(1,105,"excluded_channels(): exclude_mask"));
2299         }
2300         n++;
2301         num_excl_chan += 7;
2302     }
2303 
2304     return n;
2305 }
2306 
2307 /* Annex A: Audio Interchange Formats */
2308 
2309 /* Table 1.A.2 */
2310 void get_adif_header(adif_header *adif, bitfile *ld)
2311 {
2312     uint8_t i;
2313 
2314     /* adif_id[0] = */ faad_getbits(ld, 8
2315         DEBUGVAR(1,106,"get_adif_header(): adif_id[0]"));
2316     /* adif_id[1] = */ faad_getbits(ld, 8
2317         DEBUGVAR(1,107,"get_adif_header(): adif_id[1]"));
2318     /* adif_id[2] = */ faad_getbits(ld, 8
2319         DEBUGVAR(1,108,"get_adif_header(): adif_id[2]"));
2320     /* adif_id[3] = */ faad_getbits(ld, 8
2321         DEBUGVAR(1,109,"get_adif_header(): adif_id[3]"));
2322     adif->copyright_id_present = faad_get1bit(ld
2323         DEBUGVAR(1,110,"get_adif_header(): copyright_id_present"));
2324     if(adif->copyright_id_present)
2325     {
2326         for (i = 0; i < 72/8; i++)
2327         {
2328             adif->copyright_id[i] = (int8_t)faad_getbits(ld, 8
2329                 DEBUGVAR(1,111,"get_adif_header(): copyright_id"));
2330         }
2331         adif->copyright_id[i] = 0;
2332     }
2333     adif->original_copy  = faad_get1bit(ld
2334         DEBUGVAR(1,112,"get_adif_header(): original_copy"));
2335     adif->home = faad_get1bit(ld
2336         DEBUGVAR(1,113,"get_adif_header(): home"));
2337     adif->bitstream_type = faad_get1bit(ld
2338         DEBUGVAR(1,114,"get_adif_header(): bitstream_type"));
2339     adif->bitrate = faad_getbits(ld, 23
2340         DEBUGVAR(1,115,"get_adif_header(): bitrate"));
2341     adif->num_program_config_elements = (uint8_t)faad_getbits(ld, 4
2342         DEBUGVAR(1,116,"get_adif_header(): num_program_config_elements"));
2343 
2344     for (i = 0; i < adif->num_program_config_elements + 1; i++)
2345     {
2346         if(adif->bitstream_type == 0)
2347         {
2348             adif->adif_buffer_fullness = faad_getbits(ld, 20
2349                 DEBUGVAR(1,117,"get_adif_header(): adif_buffer_fullness"));
2350         } else {
2351             adif->adif_buffer_fullness = 0;
2352         }
2353 
2354         program_config_element(&adif->pce[i], ld);
2355     }
2356 }
2357 
2358 /* Table 1.A.5 */
2359 uint8_t adts_frame(adts_header *adts, bitfile *ld)
2360 {
2361     /* faad_byte_align(ld); */
2362     if (adts_fixed_header(adts, ld))
2363         return 5;
2364     adts_variable_header(adts, ld);
2365     adts_error_check(adts, ld);
2366 
2367     return 0;
2368 }
2369 
2370 /* Table 1.A.6 */
2371 static uint8_t adts_fixed_header(adts_header *adts, bitfile *ld)
2372 {
2373     uint16_t i;
2374     uint8_t sync_err = 1;
2375 
2376     /* try to recover from sync errors */
2377     for (i = 0; i < 768; i++)
2378     {
2379         adts->syncword = (uint16_t)faad_showbits(ld, 12);
2380         if (adts->syncword != 0xFFF)
2381         {
2382             faad_getbits(ld, 8
2383                 DEBUGVAR(0,0,""));
2384         } else {
2385             sync_err = 0;
2386             faad_getbits(ld, 12
2387                 DEBUGVAR(1,118,"adts_fixed_header(): syncword"));
2388             break;
2389         }
2390     }
2391     if (sync_err)
2392         return 5;
2393 
2394     adts->id = faad_get1bit(ld
2395         DEBUGVAR(1,119,"adts_fixed_header(): id"));
2396     adts->layer = (uint8_t)faad_getbits(ld, 2
2397         DEBUGVAR(1,120,"adts_fixed_header(): layer"));
2398     adts->protection_absent = faad_get1bit(ld
2399         DEBUGVAR(1,121,"adts_fixed_header(): protection_absent"));
2400     adts->profile = (uint8_t)faad_getbits(ld, 2
2401         DEBUGVAR(1,122,"adts_fixed_header(): profile"));
2402     adts->sf_index = (uint8_t)faad_getbits(ld, 4
2403         DEBUGVAR(1,123,"adts_fixed_header(): sf_index"));
2404     adts->private_bit = faad_get1bit(ld
2405         DEBUGVAR(1,124,"adts_fixed_header(): private_bit"));
2406     adts->channel_configuration = (uint8_t)faad_getbits(ld, 3
2407         DEBUGVAR(1,125,"adts_fixed_header(): channel_configuration"));
2408     adts->original = faad_get1bit(ld
2409         DEBUGVAR(1,126,"adts_fixed_header(): original"));
2410     adts->home = faad_get1bit(ld
2411         DEBUGVAR(1,127,"adts_fixed_header(): home"));
2412 
2413     if (adts->old_format == 1)
2414     {
2415         /* Removed in corrigendum 14496-3:2002 */
2416         if (adts->id == 0)
2417         {
2418             adts->emphasis = (uint8_t)faad_getbits(ld, 2
2419                 DEBUGVAR(1,128,"adts_fixed_header(): emphasis"));
2420         }
2421     }
2422 
2423     return 0;
2424 }
2425 
2426 /* Table 1.A.7 */
2427 static void adts_variable_header(adts_header *adts, bitfile *ld)
2428 {
2429     adts->copyright_identification_bit = faad_get1bit(ld
2430         DEBUGVAR(1,129,"adts_variable_header(): copyright_identification_bit"));
2431     adts->copyright_identification_start = faad_get1bit(ld
2432         DEBUGVAR(1,130,"adts_variable_header(): copyright_identification_start"));
2433     adts->aac_frame_length = (uint16_t)faad_getbits(ld, 13
2434         DEBUGVAR(1,131,"adts_variable_header(): aac_frame_length"));
2435     adts->adts_buffer_fullness = (uint16_t)faad_getbits(ld, 11
2436         DEBUGVAR(1,132,"adts_variable_header(): adts_buffer_fullness"));
2437     adts->no_raw_data_blocks_in_frame = (uint8_t)faad_getbits(ld, 2
2438         DEBUGVAR(1,133,"adts_variable_header(): no_raw_data_blocks_in_frame"));
2439 }
2440 
2441 /* Table 1.A.8 */
2442 static void adts_error_check(adts_header *adts, bitfile *ld)
2443 {
2444     if (adts->protection_absent == 0)
2445     {
2446         adts->crc_check = (uint16_t)faad_getbits(ld, 16
2447             DEBUGVAR(1,134,"adts_error_check(): crc_check"));
2448     }
2449 }
2450 
2451 /* LATM parsing functions */
2452 
2453 static uint32_t latm_get_value(bitfile *ld)
2454 {
2455     uint32_t l, value;
2456     uint8_t bytesForValue;
2457 
2458     bytesForValue = (uint8_t)faad_getbits(ld, 2);
2459     value = 0;
2460     for(l=0; l<bytesForValue; l++)
2461         value = (value << 8) | (uint8_t)faad_getbits(ld, 8);
2462 
2463     return value;
2464 }
2465 
2466 
2467 static uint32_t latmParsePayload(latm_header *latm, bitfile *ld)
2468 {
2469     //assuming there's only one program with a single layer and 1 subFrame,
2470     //allStreamsSametimeframing is set,
2471     uint32_t framelen;
2472     uint8_t tmp;
2473 
2474     //this should be the payload length field for the current configuration
2475     framelen = 0;
2476     if(latm->framelen_type==0)
2477     {
2478         do
2479         {
2480             tmp = (uint8_t)faad_getbits(ld, 8);
2481             framelen += tmp;
2482         } while(tmp==0xff);
2483     }
2484     else if(latm->framelen_type==1)
2485         framelen=latm->frameLength;
2486 
2487     return framelen;
2488 }
2489 
2490 
2491 static uint32_t latmAudioMuxElement(latm_header *latm, bitfile *ld)
2492 {
2493     uint32_t ascLen, asc_bits=0;
2494     uint32_t x1, y1, m, n, i;
2495     program_config pce;
2496     mp4AudioSpecificConfig mp4ASC;
2497 
2498     latm->useSameStreamMux = (uint8_t)faad_getbits(ld, 1);
2499     if(!latm->useSameStreamMux)
2500     {
2501         //parseSameStreamMuxConfig
2502         latm->version = (uint8_t) faad_getbits(ld, 1);
2503         if(latm->version)
2504             latm->versionA = (uint8_t) faad_getbits(ld, 1);
2505         if(latm->versionA)
2506         {
2507             //dunno the payload format for versionA
2508             fprintf(stderr, "versionA not supported\n");
2509             return 0;
2510         }
2511         if(latm->version) //read taraBufferFullness
2512             latm_get_value(ld);
2513         latm->allStreamsSameTimeFraming = (uint8_t)faad_getbits(ld, 1);
2514         latm->numSubFrames = (uint8_t)faad_getbits(ld, 6) + 1;
2515         latm->numPrograms = (uint8_t)faad_getbits(ld, 4) + 1;
2516         latm->numLayers = faad_getbits(ld, 3) + 1;
2517         if(latm->numPrograms>1 || !latm->allStreamsSameTimeFraming || latm->numSubFrames>1 || latm->numLayers>1)
2518         {
2519             fprintf(stderr, "\r\nUnsupported LATM configuration: %d programs/ %d subframes, %d layers, allstreams: %d\n",
2520                 latm->numPrograms, latm->numSubFrames, latm->numLayers, latm->allStreamsSameTimeFraming);
2521             return 0;
2522         }
2523         ascLen = 0;
2524         if(latm->version)
2525             ascLen = latm_get_value(ld);
2526 
2527         x1 = faad_get_processed_bits(ld);
2528         if(AudioSpecificConfigFromBitfile(ld, &mp4ASC, &pce, 0, 1) < 0)
2529             return 0;
2530 
2531         //horrid hack to unread the ASC bits and store them in latm->ASC
2532         //the correct code would rely on an ideal faad_ungetbits()
2533         y1 = faad_get_processed_bits(ld);
2534         if((y1-x1) <= MAX_ASC_BYTES*8)
2535         {
2536             faad_rewindbits(ld);
2537             m = x1;
2538             while(m>0)
2539             {
2540                 n = min(m, 32);
2541                 faad_getbits(ld, n);
2542                 m -= n;
2543             }
2544 
2545             i = 0;
2546             m = latm->ASCbits = y1 - x1;
2547             while(m > 0)
2548             {
2549                 n = min(m, 8);
2550                 latm->ASC[i++] = (uint8_t) faad_getbits(ld, n);
2551                 m -= n;
2552             }
2553         }
2554 
2555         asc_bits = y1-x1;
2556 
2557         if(ascLen>asc_bits)
2558             faad_getbits(ld, ascLen-asc_bits);
2559 
2560         latm->framelen_type = (uint8_t) faad_getbits(ld, 3);
2561         if(latm->framelen_type == 0)
2562         {
2563             latm->frameLength = 0;
2564             faad_getbits(ld, 8); //buffer fullness for frame_len_type==0, useless
2565         }
2566         else if(latm->framelen_type == 1)
2567         {
2568             latm->frameLength = faad_getbits(ld, 9);
2569             if(latm->frameLength==0)
2570             {
2571                 fprintf(stderr, "Invalid frameLength: 0\r\n");
2572                 return 0;
2573             }
2574             latm->frameLength = (latm->frameLength+20)*8;
2575         }
2576         else
2577         {   //hellish CELP or HCVX stuff, discard
2578             fprintf(stderr, "Unsupported CELP/HCVX framelentype: %d\n", latm->framelen_type);
2579             return 0;
2580         }
2581 
2582         latm->otherDataLenBits = 0;
2583         if(faad_getbits(ld, 1))
2584         {   //other data present
2585             int esc, tmp;
2586             if(latm->version)
2587                 latm->otherDataLenBits = latm_get_value(ld);
2588             else do
2589             {
2590                 esc = faad_getbits(ld, 1);
2591                 tmp = faad_getbits(ld, 8);
2592                 latm->otherDataLenBits = (latm->otherDataLenBits << 8) + tmp;
2593             } while(esc);
2594         }
2595         if(faad_getbits(ld, 1)) //crc
2596             faad_getbits(ld, 8);
2597         latm->inited = 1;
2598       }
2599 
2600       //read payload
2601       if(latm->inited)
2602           return latmParsePayload(latm, ld);
2603       else
2604           return 0;
2605 }
2606 
2607 
2608 uint32_t faad_latm_frame(latm_header *latm, bitfile *ld)
2609 {
2610     uint16_t len;
2611     uint32_t initpos, endpos, firstpos, ret;
2612 
2613     firstpos = faad_get_processed_bits(ld);
2614     while (ld->bytes_left)
2615     {
2616         faad_byte_align(ld);
2617         if(faad_showbits(ld, 11) != 0x2B7)
2618         {
2619             faad_getbits(ld, 8);
2620             continue;
2621         }
2622         faad_getbits(ld, 11);
2623         len = faad_getbits(ld, 13);
2624         if(!len)
2625             continue;
2626         initpos = faad_get_processed_bits(ld);
2627         ret = latmAudioMuxElement(latm, ld);
2628         endpos = faad_get_processed_bits(ld);
2629         if(ret>0)
2630             return (len*8)-(endpos-initpos);
2631         //faad_getbits(ld, initpos-endpos); //go back to initpos, but is valid a getbits(-N) ?
2632     }
2633     return -1U;
2634 }
2635