1 /* -----------------------------------------------------------------------------
2 Software License for The Fraunhofer FDK AAC Codec Library for Android
3 
4 © Copyright  1995 - 2020 Fraunhofer-Gesellschaft zur Förderung der angewandten
5 Forschung e.V. All rights reserved.
6 
7  1.    INTRODUCTION
8 The Fraunhofer FDK AAC Codec Library for Android ("FDK AAC Codec") is software
9 that implements the MPEG Advanced Audio Coding ("AAC") encoding and decoding
10 scheme for digital audio. This FDK AAC Codec software is intended to be used on
11 a wide variety of Android devices.
12 
13 AAC's HE-AAC and HE-AAC v2 versions are regarded as today's most efficient
14 general perceptual audio codecs. AAC-ELD is considered the best-performing
15 full-bandwidth communications codec by independent studies and is widely
16 deployed. AAC has been standardized by ISO and IEC as part of the MPEG
17 specifications.
18 
19 Patent licenses for necessary patent claims for the FDK AAC Codec (including
20 those of Fraunhofer) may be obtained through Via Licensing
21 (www.vialicensing.com) or through the respective patent owners individually for
22 the purpose of encoding or decoding bit streams in products that are compliant
23 with the ISO/IEC MPEG audio standards. Please note that most manufacturers of
24 Android devices already license these patent claims through Via Licensing or
25 directly from the patent owners, and therefore FDK AAC Codec software may
26 already be covered under those patent licenses when it is used for those
27 licensed purposes only.
28 
29 Commercially-licensed AAC software libraries, including floating-point versions
30 with enhanced sound quality, are also available from Fraunhofer. Users are
31 encouraged to check the Fraunhofer website for additional applications
32 information and documentation.
33 
34 2.    COPYRIGHT LICENSE
35 
36 Redistribution and use in source and binary forms, with or without modification,
37 are permitted without payment of copyright license fees provided that you
38 satisfy the following conditions:
39 
40 You must retain the complete text of this software license in redistributions of
41 the FDK AAC Codec or your modifications thereto in source code form.
42 
43 You must retain the complete text of this software license in the documentation
44 and/or other materials provided with redistributions of the FDK AAC Codec or
45 your modifications thereto in binary form. You must make available free of
46 charge copies of the complete source code of the FDK AAC Codec and your
47 modifications thereto to recipients of copies in binary form.
48 
49 The name of Fraunhofer may not be used to endorse or promote products derived
50 from this library without prior written permission.
51 
52 You may not charge copyright license fees for anyone to use, copy or distribute
53 the FDK AAC Codec software or your modifications thereto.
54 
55 Your modified versions of the FDK AAC Codec must carry prominent notices stating
56 that you changed the software and the date of any change. For modified versions
57 of the FDK AAC Codec, the term "Fraunhofer FDK AAC Codec Library for Android"
58 must be replaced by the term "Third-Party Modified Version of the Fraunhofer FDK
59 AAC Codec Library for Android."
60 
61 3.    NO PATENT LICENSE
62 
63 NO EXPRESS OR IMPLIED LICENSES TO ANY PATENT CLAIMS, including without
64 limitation the patents of Fraunhofer, ARE GRANTED BY THIS SOFTWARE LICENSE.
65 Fraunhofer provides no warranty of patent non-infringement with respect to this
66 software.
67 
68 You may use this FDK AAC Codec software or modifications thereto only for
69 purposes that are authorized by appropriate patent licenses.
70 
71 4.    DISCLAIMER
72 
73 This FDK AAC Codec software is provided by Fraunhofer on behalf of the copyright
74 holders and contributors "AS IS" and WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES,
75 including but not limited to the implied warranties of merchantability and
76 fitness for a particular purpose. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
77 CONTRIBUTORS BE LIABLE for any direct, indirect, incidental, special, exemplary,
78 or consequential damages, including but not limited to procurement of substitute
79 goods or services; loss of use, data, or profits, or business interruption,
80 however caused and on any theory of liability, whether in contract, strict
81 liability, or tort (including negligence), arising in any way out of the use of
82 this software, even if advised of the possibility of such damage.
83 
84 5.    CONTACT INFORMATION
85 
86 Fraunhofer Institute for Integrated Circuits IIS
87 Attention: Audio and Multimedia Departments - FDK AAC LL
88 Am Wolfsmantel 33
89 91058 Erlangen, Germany
90 
91 www.iis.fraunhofer.de/amm
92 amm-info@iis.fraunhofer.de
93 ----------------------------------------------------------------------------- */
94 
95 /******************* MPEG transport format decoder library *********************
96 
97    Author(s):   Daniel Homm
98 
99    Description:
100 
101 *******************************************************************************/
102 
103 #include "tpdec_lib.h"
104 #include "tp_data.h"
105 
106 #include "FDK_crc.h"
107 
108 #include "common_fix.h"
109 
110 /**
111  * The following arrays provide the IDs of the consecutive elements for each
112  * channel configuration. Every channel_configuration has to be finalized with
113  * ID_NONE.
114  */
115 static const MP4_ELEMENT_ID channel_configuration_0[] = {ID_NONE};
116 static const MP4_ELEMENT_ID channel_configuration_1[] = {ID_SCE, ID_NONE};
117 static const MP4_ELEMENT_ID channel_configuration_2[] = {ID_CPE, ID_NONE};
118 static const MP4_ELEMENT_ID channel_configuration_3[] = {ID_SCE, ID_CPE,
119                                                          ID_NONE};
120 static const MP4_ELEMENT_ID channel_configuration_4[] = {ID_SCE, ID_CPE, ID_SCE,
121                                                          ID_NONE};
122 static const MP4_ELEMENT_ID channel_configuration_5[] = {ID_SCE, ID_CPE, ID_CPE,
123                                                          ID_NONE};
124 static const MP4_ELEMENT_ID channel_configuration_6[] = {ID_SCE, ID_CPE, ID_CPE,
125                                                          ID_LFE, ID_NONE};
126 static const MP4_ELEMENT_ID channel_configuration_7[] = {
127     ID_SCE, ID_CPE, ID_CPE, ID_CPE, ID_LFE, ID_NONE};
128 static const MP4_ELEMENT_ID channel_configuration_8[] = {
129     ID_NONE}; /* reserved */
130 static const MP4_ELEMENT_ID channel_configuration_9[] = {
131     ID_NONE}; /* reserved */
132 static const MP4_ELEMENT_ID channel_configuration_10[] = {
133     ID_NONE}; /* reserved */
134 static const MP4_ELEMENT_ID channel_configuration_11[] = {
135     ID_SCE, ID_CPE, ID_CPE, ID_SCE, ID_LFE, ID_NONE};
136 static const MP4_ELEMENT_ID channel_configuration_12[] = {
137     ID_SCE, ID_CPE, ID_CPE, ID_CPE, ID_LFE, ID_NONE};
138 static const MP4_ELEMENT_ID channel_configuration_13[] = {
139     ID_SCE, ID_CPE, ID_CPE, ID_CPE, ID_CPE, ID_SCE, ID_LFE, ID_LFE, ID_SCE,
140     ID_CPE, ID_CPE, ID_SCE, ID_CPE, ID_SCE, ID_SCE, ID_CPE, ID_NONE};
141 static const MP4_ELEMENT_ID channel_configuration_14[] = {
142     ID_SCE, ID_CPE, ID_CPE, ID_LFE, ID_CPE, ID_NONE};
143 
144 static const MP4_ELEMENT_ID *channel_configuration_array[] = {
145     channel_configuration_0,  channel_configuration_1,
146     channel_configuration_2,  channel_configuration_3,
147     channel_configuration_4,  channel_configuration_5,
148     channel_configuration_6,  channel_configuration_7,
149     channel_configuration_8,  channel_configuration_9,
150     channel_configuration_10, channel_configuration_11,
151     channel_configuration_12, channel_configuration_13,
152     channel_configuration_14};
153 
154 #define TP_USAC_MAX_CHANNEL_CONFIGURATION_INDEX (13)
155 #define SC_CHANNEL_CONFIG_TAB_SIZE (TP_USAC_MAX_CHANNEL_CONFIGURATION_INDEX + 1)
156 
157 /* channel config structure used for sanity check */
158 typedef struct {
159   SCHAR nCh;  /* number of channels */
160   SCHAR nSCE; /* number of SCE's */
161   SCHAR nCPE; /* number of CPE's */
162   SCHAR nLFE; /* number of LFE's */
163 } SC_CHANNEL_CONFIG;
164 
165 static const SC_CHANNEL_CONFIG sc_chan_config_tab[SC_CHANNEL_CONFIG_TAB_SIZE] =
166     {
167         /* nCh, nSCE, nCPE, nLFE,     cci */
168         {0, 0, 0, 0}, /*  0 */
169         {1, 1, 0, 0}, /*  1 */
170         {2, 0, 1, 0}, /*  2 */
171         {3, 1, 1, 0}, /*  3 */
172         {4, 2, 1, 0}, /*  4 */
173         {5, 1, 2, 0}, /*  5 */
174         {6, 1, 2, 1}, /*  6 */
175         {8, 1, 3, 1}, /*  7 */
176         {2, 2, 0, 0}, /*  8 */
177         {3, 1, 1, 0}, /*  9 */
178         {4, 0, 2, 0}, /* 10 */
179         {7, 2, 2, 1}, /* 11 */
180         {8, 1, 3, 1}, /* 12 */
181         {24, 6, 8, 2} /* 13 */
182 };
183 
CProgramConfig_Reset(CProgramConfig * pPce)184 void CProgramConfig_Reset(CProgramConfig *pPce) { pPce->elCounter = 0; }
185 
CProgramConfig_Init(CProgramConfig * pPce)186 void CProgramConfig_Init(CProgramConfig *pPce) {
187   FDKmemclear(pPce, sizeof(CProgramConfig));
188   pPce->SamplingFrequencyIndex = 0xf;
189 }
190 
CProgramConfig_IsValid(const CProgramConfig * pPce)191 int CProgramConfig_IsValid(const CProgramConfig *pPce) {
192   return ((pPce->isValid) ? 1 : 0);
193 }
194 
195 #define PCE_HEIGHT_EXT_SYNC (0xAC)
196 
197 /*
198  * Read the extension for height info.
199  * return 0 if successfull,
200  *       -1 if the CRC failed,
201  *       -2 if invalid HeightInfo.
202  */
CProgramConfig_ReadHeightExt(CProgramConfig * pPce,HANDLE_FDK_BITSTREAM bs,int * const bytesAvailable,const UINT alignmentAnchor)203 static int CProgramConfig_ReadHeightExt(CProgramConfig *pPce,
204                                         HANDLE_FDK_BITSTREAM bs,
205                                         int *const bytesAvailable,
206                                         const UINT alignmentAnchor) {
207   int err = 0;
208   FDK_CRCINFO crcInfo; /* CRC state info */
209   INT crcReg;
210   FDKcrcInit(&crcInfo, 0x07, 0xFF, 8);
211   crcReg = FDKcrcStartReg(&crcInfo, bs, 0);
212   UINT startAnchor = FDKgetValidBits(bs);
213 
214   FDK_ASSERT(pPce != NULL);
215   FDK_ASSERT(bs != NULL);
216   FDK_ASSERT(bytesAvailable != NULL);
217 
218   if ((startAnchor >= 24) && (*bytesAvailable >= 3) &&
219       (FDKreadBits(bs, 8) == PCE_HEIGHT_EXT_SYNC)) {
220     int i;
221 
222     for (i = 0; i < pPce->NumFrontChannelElements; i++) {
223       if ((pPce->FrontElementHeightInfo[i] = (UCHAR)FDKreadBits(bs, 2)) >=
224           PC_NUM_HEIGHT_LAYER) {
225         err = -2; /* height information is out of the valid range */
226       }
227     }
228     for (i = 0; i < pPce->NumSideChannelElements; i++) {
229       if ((pPce->SideElementHeightInfo[i] = (UCHAR)FDKreadBits(bs, 2)) >=
230           PC_NUM_HEIGHT_LAYER) {
231         err = -2; /* height information is out of the valid range */
232       }
233     }
234     for (i = 0; i < pPce->NumBackChannelElements; i++) {
235       if ((pPce->BackElementHeightInfo[i] = (UCHAR)FDKreadBits(bs, 2)) >=
236           PC_NUM_HEIGHT_LAYER) {
237         err = -2; /* height information is out of the valid range */
238       }
239     }
240     FDKbyteAlign(bs, alignmentAnchor);
241 
242     FDKcrcEndReg(&crcInfo, bs, crcReg);
243     if ((USHORT)FDKreadBits(bs, 8) != FDKcrcGetCRC(&crcInfo)) {
244       /* CRC failed */
245       err = -1;
246     }
247     if (err != 0) {
248       /* Reset whole height information in case an error occured during parsing.
249          The return value ensures that pPce->isValid is set to 0 and implicit
250          channel mapping is used. */
251       FDKmemclear(pPce->FrontElementHeightInfo,
252                   sizeof(pPce->FrontElementHeightInfo));
253       FDKmemclear(pPce->SideElementHeightInfo,
254                   sizeof(pPce->SideElementHeightInfo));
255       FDKmemclear(pPce->BackElementHeightInfo,
256                   sizeof(pPce->BackElementHeightInfo));
257     }
258   } else {
259     /* No valid extension data found -> restore the initial bitbuffer state */
260     FDKpushBack(bs, (INT)startAnchor - (INT)FDKgetValidBits(bs));
261   }
262 
263   /* Always report the bytes read. */
264   *bytesAvailable -= ((INT)startAnchor - (INT)FDKgetValidBits(bs)) >> 3;
265 
266   return (err);
267 }
268 
269 /**
270  * \brief Sanity checks for program config element.
271  *        Check order of elements according to ISO/IEC 13818-7:2003(E),
272  * chapter 8.5.1
273  *
274  * \param pPce  pointer to program config element.
275  *
276  * \return  0 if successful, otherwise 1.
277  */
CProgramConfig_Check(CProgramConfig * pPce)278 static int CProgramConfig_Check(CProgramConfig *pPce) {
279   INT i;
280   INT err = 0;
281   INT numBackChannels[3] = {0};
282   INT numSideChannels[3] = {0};
283   INT numFrontChannels[3] = {0};
284   UCHAR *pCpeFront = pPce->FrontElementIsCpe;
285   UCHAR *pCpeSide = pPce->SideElementIsCpe;
286   UCHAR *pCpeBack = pPce->BackElementIsCpe;
287   UCHAR *pHeight;
288 
289   pHeight = pPce->BackElementHeightInfo;
290   for (i = 0; i < pPce->NumBackChannelElements; i++) {
291     numBackChannels[*pHeight] += pPce->BackElementIsCpe[i] ? 2 : 1;
292     pHeight++;
293   }
294   pHeight = pPce->SideElementHeightInfo;
295   for (i = 0; i < pPce->NumSideChannelElements; i++) {
296     numSideChannels[*pHeight] += pPce->SideElementIsCpe[i] ? 2 : 1;
297     pHeight++;
298   }
299   pHeight = pPce->FrontElementHeightInfo;
300   for (i = 0; i < pPce->NumFrontChannelElements; i++) {
301     numFrontChannels[*pHeight] += pPce->FrontElementIsCpe[i] ? 2 : 1;
302     pHeight++;
303   }
304 
305   /* 0 = normal height channels, 1 = top height channels, 2 = bottom height
306    * channels */
307   for (i = 0; i < 3; i++) {
308     /* if number of channels is odd => first element must be a SCE (front center
309      * channel) */
310     if (numFrontChannels[i] & 1) {
311       if (*pCpeFront++ == ID_CPE) {
312         err = 1;
313         goto bail;
314       }
315       numFrontChannels[i]--;
316     }
317     while (numFrontChannels[i] > 0) {
318       /* must be CPE or paired SCE */
319       if (*pCpeFront++ == ID_SCE) {
320         if (*pCpeFront++ == ID_CPE) {
321           err = 1;
322           goto bail;
323         }
324       }
325       numFrontChannels[i] -= 2;
326     };
327 
328     /* in case that a top center surround channel (Ts) is transmitted the number
329      * of channels can be odd */
330     if (i != 1) {
331       /* number of channels must be even */
332       if (numSideChannels[i] & 1) {
333         err = 1;
334         goto bail;
335       }
336       while (numSideChannels[i] > 0) {
337         /* must be CPE or paired SCE */
338         if (*pCpeSide++ == ID_SCE) {
339           if (*pCpeSide++ == ID_CPE) {
340             err = 1;
341             goto bail;
342           }
343         }
344         numSideChannels[i] -= 2;
345       };
346     }
347 
348     while (numBackChannels[i] > 1) {
349       /* must be CPE or paired SCE */
350       if (*pCpeBack++ == ID_SCE) {
351         if (*pCpeBack++ == ID_CPE) {
352           err = 1;
353           goto bail;
354         }
355       }
356       numBackChannels[i] -= 2;
357     };
358     /* if number of channels is odd => last element must be a SCE (back center
359      * channel) */
360     if (numBackChannels[i]) {
361       if (*pCpeBack++ == ID_CPE) {
362         err = 1;
363         goto bail;
364       }
365     }
366   }
367 
368 bail:
369 
370   return err;
371 }
372 
CProgramConfig_Read(CProgramConfig * pPce,HANDLE_FDK_BITSTREAM bs,UINT alignmentAnchor)373 void CProgramConfig_Read(CProgramConfig *pPce, HANDLE_FDK_BITSTREAM bs,
374                          UINT alignmentAnchor) {
375   int i;
376   int commentBytes;
377   UCHAR tag, isCpe;
378   UCHAR checkElementTagSelect[3][PC_FSB_CHANNELS_MAX] = {{0}};
379 
380   pPce->isValid = 1;
381   pPce->NumEffectiveChannels = 0;
382   pPce->NumChannels = 0;
383   pPce->ElementInstanceTag = (UCHAR)FDKreadBits(bs, 4);
384   pPce->Profile = (UCHAR)FDKreadBits(bs, 2);
385   pPce->SamplingFrequencyIndex = (UCHAR)FDKreadBits(bs, 4);
386   pPce->NumFrontChannelElements = (UCHAR)FDKreadBits(bs, 4);
387   pPce->NumSideChannelElements = (UCHAR)FDKreadBits(bs, 4);
388   pPce->NumBackChannelElements = (UCHAR)FDKreadBits(bs, 4);
389   pPce->NumLfeChannelElements = (UCHAR)FDKreadBits(bs, 2);
390   pPce->NumAssocDataElements = (UCHAR)FDKreadBits(bs, 3);
391   pPce->NumValidCcElements = (UCHAR)FDKreadBits(bs, 4);
392 
393   if ((pPce->MonoMixdownPresent = (UCHAR)FDKreadBits(bs, 1)) != 0) {
394     pPce->MonoMixdownElementNumber = (UCHAR)FDKreadBits(bs, 4);
395   }
396 
397   if ((pPce->StereoMixdownPresent = (UCHAR)FDKreadBits(bs, 1)) != 0) {
398     pPce->StereoMixdownElementNumber = (UCHAR)FDKreadBits(bs, 4);
399   }
400 
401   if ((pPce->MatrixMixdownIndexPresent = (UCHAR)FDKreadBits(bs, 1)) != 0) {
402     pPce->MatrixMixdownIndex = (UCHAR)FDKreadBits(bs, 2);
403     pPce->PseudoSurroundEnable = (UCHAR)FDKreadBits(bs, 1);
404   }
405 
406   for (i = 0; i < pPce->NumFrontChannelElements; i++) {
407     pPce->FrontElementIsCpe[i] = isCpe = (UCHAR)FDKreadBits(bs, 1);
408     pPce->FrontElementTagSelect[i] = tag = (UCHAR)FDKreadBits(bs, 4);
409     pPce->NumChannels += pPce->FrontElementIsCpe[i] ? 2 : 1;
410 
411     /* Check element instance tag according to ISO/IEC 13818-7:2003(E),
412      * chapter 8.2.1.1 */
413     if (checkElementTagSelect[isCpe][tag] == 0) {
414       checkElementTagSelect[isCpe][tag] = 1;
415     } else {
416       pPce->isValid = 0;
417     }
418   }
419 
420   for (i = 0; i < pPce->NumSideChannelElements; i++) {
421     pPce->SideElementIsCpe[i] = isCpe = (UCHAR)FDKreadBits(bs, 1);
422     pPce->SideElementTagSelect[i] = tag = (UCHAR)FDKreadBits(bs, 4);
423     pPce->NumChannels += pPce->SideElementIsCpe[i] ? 2 : 1;
424 
425     /* Check element instance tag according to ISO/IEC 13818-7:2003(E),
426      * chapter 8.2.1.1 */
427     if (checkElementTagSelect[isCpe][tag] == 0) {
428       checkElementTagSelect[isCpe][tag] = 1;
429     } else {
430       pPce->isValid = 0;
431     }
432   }
433 
434   for (i = 0; i < pPce->NumBackChannelElements; i++) {
435     pPce->BackElementIsCpe[i] = isCpe = (UCHAR)FDKreadBits(bs, 1);
436     pPce->BackElementTagSelect[i] = tag = (UCHAR)FDKreadBits(bs, 4);
437     pPce->NumChannels += pPce->BackElementIsCpe[i] ? 2 : 1;
438 
439     /* Check element instance tag according to ISO/IEC 13818-7:2003(E),
440      * chapter 8.2.1.1 */
441     if (checkElementTagSelect[isCpe][tag] == 0) {
442       checkElementTagSelect[isCpe][tag] = 1;
443     } else {
444       pPce->isValid = 0;
445     }
446   }
447 
448   pPce->NumEffectiveChannels = pPce->NumChannels;
449 
450   for (i = 0; i < pPce->NumLfeChannelElements; i++) {
451     pPce->LfeElementTagSelect[i] = tag = (UCHAR)FDKreadBits(bs, 4);
452     pPce->NumChannels += 1;
453 
454     /* Check element instance tag according to ISO/IEC 13818-7:2003(E),
455      * chapter 8.2.1.1 */
456     if (checkElementTagSelect[2][tag] == 0) {
457       checkElementTagSelect[2][tag] = 1;
458     } else {
459       pPce->isValid = 0;
460     }
461   }
462 
463   for (i = 0; i < pPce->NumAssocDataElements; i++) {
464     pPce->AssocDataElementTagSelect[i] = (UCHAR)FDKreadBits(bs, 4);
465   }
466 
467   for (i = 0; i < pPce->NumValidCcElements; i++) {
468     pPce->CcElementIsIndSw[i] = (UCHAR)FDKreadBits(bs, 1);
469     pPce->ValidCcElementTagSelect[i] = (UCHAR)FDKreadBits(bs, 4);
470   }
471 
472   FDKbyteAlign(bs, alignmentAnchor);
473 
474   pPce->CommentFieldBytes = (UCHAR)FDKreadBits(bs, 8);
475   commentBytes = pPce->CommentFieldBytes;
476 
477   /* Search for height info extension and read it if available */
478   if (CProgramConfig_ReadHeightExt(pPce, bs, &commentBytes, alignmentAnchor)) {
479     pPce->isValid = 0;
480   }
481 
482   /* Check order of elements according to ISO / IEC 13818 - 7:2003(E),
483    * chapter 8.5.1 */
484   if (CProgramConfig_Check(pPce)) {
485     pPce->isValid = 0;
486   }
487 
488   for (i = 0; i < commentBytes; i++) {
489     UCHAR text;
490 
491     text = (UCHAR)FDKreadBits(bs, 8);
492 
493     if (i < PC_COMMENTLENGTH) {
494       pPce->Comment[i] = text;
495     }
496   }
497 }
498 
499 /*
500  * Compare two program configurations.
501  * Returns the result of the comparison:
502  *  -1 - completely different
503  *   0 - completely equal
504  *   1 - different but same channel configuration
505  *   2 - different channel configuration but same number of channels
506  */
CProgramConfig_Compare(const CProgramConfig * const pPce1,const CProgramConfig * const pPce2)507 int CProgramConfig_Compare(const CProgramConfig *const pPce1,
508                            const CProgramConfig *const pPce2) {
509   int result = 0; /* Innocent until proven false. */
510 
511   if (FDKmemcmp(pPce1, pPce2, sizeof(CProgramConfig)) !=
512       0) { /* Configurations are not completely equal.
513               So look into details and analyse the channel configurations: */
514     result = -1;
515 
516     if (pPce1->NumChannels ==
517         pPce2->NumChannels) { /* Now the logic changes. We first assume to have
518                                  the same channel configuration and then prove
519                                  if this assumption is true. */
520       result = 1;
521 
522       /* Front channels */
523       if (pPce1->NumFrontChannelElements != pPce2->NumFrontChannelElements) {
524         result = 2; /* different number of front channel elements */
525       } else {
526         int el, numCh1 = 0, numCh2 = 0;
527         for (el = 0; el < pPce1->NumFrontChannelElements; el += 1) {
528           if (pPce1->FrontElementHeightInfo[el] !=
529               pPce2->FrontElementHeightInfo[el]) {
530             result = 2; /* different height info */
531             break;
532           }
533           numCh1 += pPce1->FrontElementIsCpe[el] ? 2 : 1;
534           numCh2 += pPce2->FrontElementIsCpe[el] ? 2 : 1;
535         }
536         if (numCh1 != numCh2) {
537           result = 2; /* different number of front channels */
538         }
539       }
540       /* Side channels */
541       if (pPce1->NumSideChannelElements != pPce2->NumSideChannelElements) {
542         result = 2; /* different number of side channel elements */
543       } else {
544         int el, numCh1 = 0, numCh2 = 0;
545         for (el = 0; el < pPce1->NumSideChannelElements; el += 1) {
546           if (pPce1->SideElementHeightInfo[el] !=
547               pPce2->SideElementHeightInfo[el]) {
548             result = 2; /* different height info */
549             break;
550           }
551           numCh1 += pPce1->SideElementIsCpe[el] ? 2 : 1;
552           numCh2 += pPce2->SideElementIsCpe[el] ? 2 : 1;
553         }
554         if (numCh1 != numCh2) {
555           result = 2; /* different number of side channels */
556         }
557       }
558       /* Back channels */
559       if (pPce1->NumBackChannelElements != pPce2->NumBackChannelElements) {
560         result = 2; /* different number of back channel elements */
561       } else {
562         int el, numCh1 = 0, numCh2 = 0;
563         for (el = 0; el < pPce1->NumBackChannelElements; el += 1) {
564           if (pPce1->BackElementHeightInfo[el] !=
565               pPce2->BackElementHeightInfo[el]) {
566             result = 2; /* different height info */
567             break;
568           }
569           numCh1 += pPce1->BackElementIsCpe[el] ? 2 : 1;
570           numCh2 += pPce2->BackElementIsCpe[el] ? 2 : 1;
571         }
572         if (numCh1 != numCh2) {
573           result = 2; /* different number of back channels */
574         }
575       }
576       /* LFE channels */
577       if (pPce1->NumLfeChannelElements != pPce2->NumLfeChannelElements) {
578         result = 2; /* different number of lfe channels */
579       }
580       /* LFEs are always SCEs so we don't need to count the channels. */
581     }
582   }
583 
584   return result;
585 }
586 
CProgramConfig_GetDefault(CProgramConfig * pPce,const UINT channelConfig)587 void CProgramConfig_GetDefault(CProgramConfig *pPce, const UINT channelConfig) {
588   FDK_ASSERT(pPce != NULL);
589 
590   /* Init PCE */
591   CProgramConfig_Init(pPce);
592   pPce->Profile =
593       1; /* Set AAC LC because it is the only supported object type. */
594 
595   switch (channelConfig) {
596     /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
597     case 32: /* 7.1 side channel configuration as defined in FDK_audio.h */
598       pPce->NumFrontChannelElements = 2;
599       pPce->FrontElementIsCpe[0] = 0;
600       pPce->FrontElementIsCpe[1] = 1;
601       pPce->NumSideChannelElements = 1;
602       pPce->SideElementIsCpe[0] = 1;
603       pPce->NumBackChannelElements = 1;
604       pPce->BackElementIsCpe[0] = 1;
605       pPce->NumLfeChannelElements = 1;
606       pPce->NumChannels = 8;
607       pPce->NumEffectiveChannels = 7;
608       pPce->isValid = 1;
609       break;
610     /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
611     case 12: /* 3/0/4.1ch surround back */
612       pPce->BackElementIsCpe[1] = 1;
613       pPce->NumChannels += 1;
614       pPce->NumEffectiveChannels += 1;
615       FDK_FALLTHROUGH;
616     case 11: /* 3/0/3.1ch */
617       pPce->NumFrontChannelElements += 2;
618       pPce->FrontElementIsCpe[0] = 0;
619       pPce->FrontElementIsCpe[1] = 1;
620       pPce->NumBackChannelElements += 2;
621       pPce->BackElementIsCpe[0] = 1;
622       pPce->BackElementIsCpe[1] += 0;
623       pPce->NumLfeChannelElements += 1;
624       pPce->NumChannels += 7;
625       pPce->NumEffectiveChannels += 6;
626       pPce->isValid = 1;
627       break;
628     /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
629     case 14:                               /* 2/0/0-3/0/2-0.1ch front height */
630       pPce->FrontElementHeightInfo[2] = 1; /* Top speaker */
631       FDK_FALLTHROUGH;
632     case 7: /* 5/0/2.1ch front */
633       pPce->NumFrontChannelElements += 1;
634       pPce->FrontElementIsCpe[2] = 1;
635       pPce->NumChannels += 2;
636       pPce->NumEffectiveChannels += 2;
637       FDK_FALLTHROUGH;
638     case 6: /* 3/0/2.1ch */
639       pPce->NumLfeChannelElements += 1;
640       pPce->NumChannels += 1;
641       FDK_FALLTHROUGH;
642     case 5: /* 3/0/2.0ch */
643     case 4: /* 3/0/1.0ch */
644       pPce->NumBackChannelElements += 1;
645       pPce->BackElementIsCpe[0] = (channelConfig > 4) ? 1 : 0;
646       pPce->NumChannels += (channelConfig > 4) ? 2 : 1;
647       pPce->NumEffectiveChannels += (channelConfig > 4) ? 2 : 1;
648       FDK_FALLTHROUGH;
649     case 3: /* 3/0/0.0ch */
650       pPce->NumFrontChannelElements += 1;
651       pPce->FrontElementIsCpe[1] = 1;
652       pPce->NumChannels += 2;
653       pPce->NumEffectiveChannels += 2;
654       FDK_FALLTHROUGH;
655     case 1: /* 1/0/0.0ch */
656       pPce->NumFrontChannelElements += 1;
657       pPce->FrontElementIsCpe[0] = 0;
658       pPce->NumChannels += 1;
659       pPce->NumEffectiveChannels += 1;
660       pPce->isValid = 1;
661       break;
662     /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
663     case 2: /* 2/0/0.ch */
664       pPce->NumFrontChannelElements = 1;
665       pPce->FrontElementIsCpe[0] = 1;
666       pPce->NumChannels += 2;
667       pPce->NumEffectiveChannels += 2;
668       pPce->isValid = 1;
669       break;
670     /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
671     default:
672       pPce->isValid = 0; /* To be explicit! */
673       break;
674   }
675 
676   if (pPce->isValid) {
677     /* Create valid element instance tags */
678     int el, elTagSce = 0, elTagCpe = 0;
679 
680     for (el = 0; el < pPce->NumFrontChannelElements; el += 1) {
681       pPce->FrontElementTagSelect[el] =
682           (pPce->FrontElementIsCpe[el]) ? elTagCpe++ : elTagSce++;
683     }
684     for (el = 0; el < pPce->NumSideChannelElements; el += 1) {
685       pPce->SideElementTagSelect[el] =
686           (pPce->SideElementIsCpe[el]) ? elTagCpe++ : elTagSce++;
687     }
688     for (el = 0; el < pPce->NumBackChannelElements; el += 1) {
689       pPce->BackElementTagSelect[el] =
690           (pPce->BackElementIsCpe[el]) ? elTagCpe++ : elTagSce++;
691     }
692     elTagSce = 0;
693     for (el = 0; el < pPce->NumLfeChannelElements; el += 1) {
694       pPce->LfeElementTagSelect[el] = elTagSce++;
695     }
696   }
697 }
698 
699 /**
700  * \brief get implicit audio channel type for given channelConfig and MPEG
701  * ordered channel index
702  * \param channelConfig MPEG channelConfiguration from 1 upto 14
703  * \param index MPEG channel order index
704  * \return audio channel type.
705  */
getImplicitAudioChannelTypeAndIndex(AUDIO_CHANNEL_TYPE * chType,UCHAR * chIndex,UINT channelConfig,UINT index)706 static void getImplicitAudioChannelTypeAndIndex(AUDIO_CHANNEL_TYPE *chType,
707                                                 UCHAR *chIndex,
708                                                 UINT channelConfig,
709                                                 UINT index) {
710   if (index < 3) {
711     *chType = ACT_FRONT;
712     *chIndex = index;
713   } else {
714     switch (channelConfig) {
715       case 4: /* SCE, CPE, SCE */
716       case 5: /* SCE, CPE, CPE */
717       case 6: /* SCE, CPE, CPE, LFE */
718         switch (index) {
719           case 3:
720           case 4:
721             *chType = ACT_BACK;
722             *chIndex = index - 3;
723             break;
724           case 5:
725             *chType = ACT_LFE;
726             *chIndex = 0;
727             break;
728         }
729         break;
730       case 7: /* SCE,CPE,CPE,CPE,LFE */
731         switch (index) {
732           case 3:
733           case 4:
734             *chType = ACT_FRONT;
735             *chIndex = index;
736             break;
737           case 5:
738           case 6:
739             *chType = ACT_BACK;
740             *chIndex = index - 5;
741             break;
742           case 7:
743             *chType = ACT_LFE;
744             *chIndex = 0;
745             break;
746         }
747         break;
748       case 11: /* SCE,CPE,CPE,SCE,LFE */
749         if (index < 6) {
750           *chType = ACT_BACK;
751           *chIndex = index - 3;
752         } else {
753           *chType = ACT_LFE;
754           *chIndex = 0;
755         }
756         break;
757       case 12: /* SCE,CPE,CPE,CPE,LFE */
758         if (index < 7) {
759           *chType = ACT_BACK;
760           *chIndex = index - 3;
761         } else {
762           *chType = ACT_LFE;
763           *chIndex = 0;
764         }
765         break;
766       case 14: /* SCE,CPE,CPE,LFE,CPE */
767         switch (index) {
768           case 3:
769           case 4:
770             *chType = ACT_BACK;
771             *chIndex = index - 3;
772             break;
773           case 5:
774             *chType = ACT_LFE;
775             *chIndex = 0;
776             break;
777           case 6:
778           case 7:
779             *chType = ACT_FRONT_TOP;
780             *chIndex = index - 6; /* handle the top layer independently */
781             break;
782         }
783         break;
784       default:
785         *chType = ACT_NONE;
786         break;
787     }
788   }
789 }
790 
CProgramConfig_LookupElement(CProgramConfig * pPce,UINT channelConfig,const UINT tag,const UINT channelIdx,UCHAR chMapping[],AUDIO_CHANNEL_TYPE chType[],UCHAR chIndex[],const UINT chDescrLen,UCHAR * elMapping,MP4_ELEMENT_ID elList[],MP4_ELEMENT_ID elType)791 int CProgramConfig_LookupElement(CProgramConfig *pPce, UINT channelConfig,
792                                  const UINT tag, const UINT channelIdx,
793                                  UCHAR chMapping[], AUDIO_CHANNEL_TYPE chType[],
794                                  UCHAR chIndex[], const UINT chDescrLen,
795                                  UCHAR *elMapping, MP4_ELEMENT_ID elList[],
796                                  MP4_ELEMENT_ID elType) {
797   if (channelConfig > 0) {
798     /* Constant channel mapping must have
799        been set during initialization. */
800     if (IS_CHANNEL_ELEMENT(elType)) {
801       *elMapping = pPce->elCounter;
802       if (elList[pPce->elCounter] != elType &&
803           !IS_USAC_CHANNEL_ELEMENT(elType)) {
804         /* Not in the list */
805         if ((channelConfig == 2) &&
806             (elType == ID_SCE)) { /* This scenario occurs with HE-AAC v2 streams
807                                      of buggy encoders. In other decoder
808                                      implementations decoding of this kind of
809                                      streams is desired. */
810           channelConfig = 1;
811         } else if ((elList[pPce->elCounter] == ID_LFE) &&
812                    (elType ==
813                     ID_SCE)) { /* Decode bitstreams which wrongly use ID_SCE
814                                   instead of ID_LFE element type. */
815           ;
816         } else {
817           return 0;
818         }
819       }
820       /* Assume all front channels */
821       getImplicitAudioChannelTypeAndIndex(
822           &chType[channelIdx], &chIndex[channelIdx], channelConfig, channelIdx);
823       if (elType == ID_CPE || elType == ID_USAC_CPE) {
824         chType[channelIdx + 1] = chType[channelIdx];
825         chIndex[channelIdx + 1] = chIndex[channelIdx] + 1;
826       }
827       pPce->elCounter++;
828     }
829     /* Accept all non-channel elements, too. */
830     return 1;
831   } else {
832     if ((!pPce->isValid) || (pPce->NumChannels > chDescrLen)) {
833       /* Implicit channel mapping. */
834       if (IS_USAC_CHANNEL_ELEMENT(elType)) {
835         *elMapping = pPce->elCounter++;
836       } else if (IS_MP4_CHANNEL_ELEMENT(elType)) {
837         /* Store all channel element IDs */
838         elList[pPce->elCounter] = elType;
839         *elMapping = pPce->elCounter++;
840       }
841     } else {
842       /* Accept the additional channel(s), only if the tag is in the lists */
843       int isCpe = 0, i;
844       /* Element counter */
845       int ec[PC_NUM_HEIGHT_LAYER] = {0};
846       /* Channel counters */
847       int cc[PC_NUM_HEIGHT_LAYER] = {0};
848       int fc[PC_NUM_HEIGHT_LAYER] = {0}; /* front channel counter */
849       int sc[PC_NUM_HEIGHT_LAYER] = {0}; /* side channel counter */
850       int bc[PC_NUM_HEIGHT_LAYER] = {0}; /* back channel counter */
851       int lc = 0;                        /* lfe channel counter */
852 
853       /* General MPEG (PCE) composition rules:
854          - Over all:
855              <normal height channels><top height channels><bottom height
856          channels>
857          - Within each height layer:
858              <front channels><side channels><back channels>
859          - Exception:
860              The LFE channels have no height info and thus they are arranged at
861          the very end of the normal height layer channels.
862        */
863 
864       switch (elType) {
865         case ID_CPE:
866           isCpe = 1;
867           FDK_FALLTHROUGH;
868         case ID_SCE:
869           /* search in front channels */
870           for (i = 0; i < pPce->NumFrontChannelElements; i++) {
871             int heightLayer = pPce->FrontElementHeightInfo[i];
872             if (isCpe == pPce->FrontElementIsCpe[i] &&
873                 pPce->FrontElementTagSelect[i] == tag) {
874               int h, elIdx = ec[heightLayer], chIdx = cc[heightLayer];
875               AUDIO_CHANNEL_TYPE aChType =
876                   (AUDIO_CHANNEL_TYPE)((heightLayer << 4) | ACT_FRONT);
877               for (h = heightLayer - 1; h >= 0; h -= 1) {
878                 int el;
879                 /* Count front channels/elements */
880                 for (el = 0; el < pPce->NumFrontChannelElements; el += 1) {
881                   if (pPce->FrontElementHeightInfo[el] == h) {
882                     elIdx += 1;
883                     chIdx += (pPce->FrontElementIsCpe[el]) ? 2 : 1;
884                   }
885                 }
886                 /* Count side channels/elements */
887                 for (el = 0; el < pPce->NumSideChannelElements; el += 1) {
888                   if (pPce->SideElementHeightInfo[el] == h) {
889                     elIdx += 1;
890                     chIdx += (pPce->SideElementIsCpe[el]) ? 2 : 1;
891                   }
892                 }
893                 /* Count back channels/elements */
894                 for (el = 0; el < pPce->NumBackChannelElements; el += 1) {
895                   if (pPce->BackElementHeightInfo[el] == h) {
896                     elIdx += 1;
897                     chIdx += (pPce->BackElementIsCpe[el]) ? 2 : 1;
898                   }
899                 }
900                 if (h == 0) { /* normal height */
901                   elIdx += pPce->NumLfeChannelElements;
902                   chIdx += pPce->NumLfeChannelElements;
903                 }
904               }
905               chMapping[chIdx] = channelIdx;
906               chType[chIdx] = aChType;
907               chIndex[chIdx] = fc[heightLayer];
908               if (isCpe) {
909                 chMapping[chIdx + 1] = channelIdx + 1;
910                 chType[chIdx + 1] = aChType;
911                 chIndex[chIdx + 1] = fc[heightLayer] + 1;
912               }
913               *elMapping = elIdx;
914               return 1;
915             }
916             ec[heightLayer] += 1;
917             if (pPce->FrontElementIsCpe[i]) {
918               cc[heightLayer] += 2;
919               fc[heightLayer] += 2;
920             } else {
921               cc[heightLayer] += 1;
922               fc[heightLayer] += 1;
923             }
924           }
925           /* search in side channels */
926           for (i = 0; i < pPce->NumSideChannelElements; i++) {
927             int heightLayer = pPce->SideElementHeightInfo[i];
928             if (isCpe == pPce->SideElementIsCpe[i] &&
929                 pPce->SideElementTagSelect[i] == tag) {
930               int h, elIdx = ec[heightLayer], chIdx = cc[heightLayer];
931               AUDIO_CHANNEL_TYPE aChType =
932                   (AUDIO_CHANNEL_TYPE)((heightLayer << 4) | ACT_SIDE);
933               for (h = heightLayer - 1; h >= 0; h -= 1) {
934                 int el;
935                 /* Count front channels/elements */
936                 for (el = 0; el < pPce->NumFrontChannelElements; el += 1) {
937                   if (pPce->FrontElementHeightInfo[el] == h) {
938                     elIdx += 1;
939                     chIdx += (pPce->FrontElementIsCpe[el]) ? 2 : 1;
940                   }
941                 }
942                 /* Count side channels/elements */
943                 for (el = 0; el < pPce->NumSideChannelElements; el += 1) {
944                   if (pPce->SideElementHeightInfo[el] == h) {
945                     elIdx += 1;
946                     chIdx += (pPce->SideElementIsCpe[el]) ? 2 : 1;
947                   }
948                 }
949                 /* Count back channels/elements */
950                 for (el = 0; el < pPce->NumBackChannelElements; el += 1) {
951                   if (pPce->BackElementHeightInfo[el] == h) {
952                     elIdx += 1;
953                     chIdx += (pPce->BackElementIsCpe[el]) ? 2 : 1;
954                   }
955                 }
956                 if (h ==
957                     0) { /* LFE channels belong to the normal height layer */
958                   elIdx += pPce->NumLfeChannelElements;
959                   chIdx += pPce->NumLfeChannelElements;
960                 }
961               }
962               chMapping[chIdx] = channelIdx;
963               chType[chIdx] = aChType;
964               chIndex[chIdx] = sc[heightLayer];
965               if (isCpe) {
966                 chMapping[chIdx + 1] = channelIdx + 1;
967                 chType[chIdx + 1] = aChType;
968                 chIndex[chIdx + 1] = sc[heightLayer] + 1;
969               }
970               *elMapping = elIdx;
971               return 1;
972             }
973             ec[heightLayer] += 1;
974             if (pPce->SideElementIsCpe[i]) {
975               cc[heightLayer] += 2;
976               sc[heightLayer] += 2;
977             } else {
978               cc[heightLayer] += 1;
979               sc[heightLayer] += 1;
980             }
981           }
982           /* search in back channels */
983           for (i = 0; i < pPce->NumBackChannelElements; i++) {
984             int heightLayer = pPce->BackElementHeightInfo[i];
985             if (isCpe == pPce->BackElementIsCpe[i] &&
986                 pPce->BackElementTagSelect[i] == tag) {
987               int h, elIdx = ec[heightLayer], chIdx = cc[heightLayer];
988               AUDIO_CHANNEL_TYPE aChType =
989                   (AUDIO_CHANNEL_TYPE)((heightLayer << 4) | ACT_BACK);
990               for (h = heightLayer - 1; h >= 0; h -= 1) {
991                 int el;
992                 /* Count front channels/elements */
993                 for (el = 0; el < pPce->NumFrontChannelElements; el += 1) {
994                   if (pPce->FrontElementHeightInfo[el] == h) {
995                     elIdx += 1;
996                     chIdx += (pPce->FrontElementIsCpe[el]) ? 2 : 1;
997                   }
998                 }
999                 /* Count side channels/elements */
1000                 for (el = 0; el < pPce->NumSideChannelElements; el += 1) {
1001                   if (pPce->SideElementHeightInfo[el] == h) {
1002                     elIdx += 1;
1003                     chIdx += (pPce->SideElementIsCpe[el]) ? 2 : 1;
1004                   }
1005                 }
1006                 /* Count back channels/elements */
1007                 for (el = 0; el < pPce->NumBackChannelElements; el += 1) {
1008                   if (pPce->BackElementHeightInfo[el] == h) {
1009                     elIdx += 1;
1010                     chIdx += (pPce->BackElementIsCpe[el]) ? 2 : 1;
1011                   }
1012                 }
1013                 if (h == 0) { /* normal height */
1014                   elIdx += pPce->NumLfeChannelElements;
1015                   chIdx += pPce->NumLfeChannelElements;
1016                 }
1017               }
1018               chMapping[chIdx] = channelIdx;
1019               chType[chIdx] = aChType;
1020               chIndex[chIdx] = bc[heightLayer];
1021               if (isCpe) {
1022                 chMapping[chIdx + 1] = channelIdx + 1;
1023                 chType[chIdx + 1] = aChType;
1024                 chIndex[chIdx + 1] = bc[heightLayer] + 1;
1025               }
1026               *elMapping = elIdx;
1027               return 1;
1028             }
1029             ec[heightLayer] += 1;
1030             if (pPce->BackElementIsCpe[i]) {
1031               cc[heightLayer] += 2;
1032               bc[heightLayer] += 2;
1033             } else {
1034               cc[heightLayer] += 1;
1035               bc[heightLayer] += 1;
1036             }
1037           }
1038           break;
1039 
1040         case ID_LFE: { /* Unfortunately we have to go through all normal height
1041                           layer elements to get the position of the LFE
1042                           channels. Start with counting the front
1043                           channels/elements at normal height */
1044           for (i = 0; i < pPce->NumFrontChannelElements; i += 1) {
1045             int heightLayer = pPce->FrontElementHeightInfo[i];
1046             ec[heightLayer] += 1;
1047             cc[heightLayer] += (pPce->FrontElementIsCpe[i]) ? 2 : 1;
1048           }
1049           /* Count side channels/elements at normal height */
1050           for (i = 0; i < pPce->NumSideChannelElements; i += 1) {
1051             int heightLayer = pPce->SideElementHeightInfo[i];
1052             ec[heightLayer] += 1;
1053             cc[heightLayer] += (pPce->SideElementIsCpe[i]) ? 2 : 1;
1054           }
1055           /* Count back channels/elements at normal height */
1056           for (i = 0; i < pPce->NumBackChannelElements; i += 1) {
1057             int heightLayer = pPce->BackElementHeightInfo[i];
1058             ec[heightLayer] += 1;
1059             cc[heightLayer] += (pPce->BackElementIsCpe[i]) ? 2 : 1;
1060           }
1061 
1062           /* search in lfe channels */
1063           for (i = 0; i < pPce->NumLfeChannelElements; i++) {
1064             int elIdx =
1065                 ec[0]; /* LFE channels belong to the normal height layer */
1066             int chIdx = cc[0];
1067             if (pPce->LfeElementTagSelect[i] == tag) {
1068               chMapping[chIdx] = channelIdx;
1069               *elMapping = elIdx;
1070               chType[chIdx] = ACT_LFE;
1071               chIndex[chIdx] = lc;
1072               return 1;
1073             }
1074             ec[0] += 1;
1075             cc[0] += 1;
1076             lc += 1;
1077           }
1078         } break;
1079 
1080         /* Non audio elements */
1081         case ID_CCE:
1082           /* search in cce channels */
1083           for (i = 0; i < pPce->NumValidCcElements; i++) {
1084             if (pPce->ValidCcElementTagSelect[i] == tag) {
1085               return 1;
1086             }
1087           }
1088           break;
1089         case ID_DSE:
1090           /* search associated data elements */
1091           for (i = 0; i < pPce->NumAssocDataElements; i++) {
1092             if (pPce->AssocDataElementTagSelect[i] == tag) {
1093               return 1;
1094             }
1095           }
1096           break;
1097         default:
1098           return 0;
1099       }
1100       return 0; /* not found in any list */
1101     }
1102   }
1103 
1104   return 1;
1105 }
1106 
1107 #define SPEAKER_PLANE_NORMAL 0
1108 #define SPEAKER_PLANE_TOP 1
1109 #define SPEAKER_PLANE_BOTTOM 2
1110 
CProgramConfig_GetChannelDescription(const UINT chConfig,const CProgramConfig * pPce,AUDIO_CHANNEL_TYPE chType[],UCHAR chIndex[])1111 void CProgramConfig_GetChannelDescription(const UINT chConfig,
1112                                           const CProgramConfig *pPce,
1113                                           AUDIO_CHANNEL_TYPE chType[],
1114                                           UCHAR chIndex[]) {
1115   FDK_ASSERT(chType != NULL);
1116   FDK_ASSERT(chIndex != NULL);
1117 
1118   if ((chConfig == 0) && (pPce != NULL)) {
1119     if (pPce->isValid) {
1120       int spkPlane, chIdx = 0;
1121       for (spkPlane = SPEAKER_PLANE_NORMAL; spkPlane <= SPEAKER_PLANE_BOTTOM;
1122            spkPlane += 1) {
1123         int elIdx, grpChIdx = 0;
1124         for (elIdx = 0; elIdx < pPce->NumFrontChannelElements; elIdx += 1) {
1125           if (pPce->FrontElementHeightInfo[elIdx] == spkPlane) {
1126             chType[chIdx] = (AUDIO_CHANNEL_TYPE)((spkPlane << 4) | ACT_FRONT);
1127             chIndex[chIdx++] = grpChIdx++;
1128             if (pPce->FrontElementIsCpe[elIdx]) {
1129               chType[chIdx] = (AUDIO_CHANNEL_TYPE)((spkPlane << 4) | ACT_FRONT);
1130               chIndex[chIdx++] = grpChIdx++;
1131             }
1132           }
1133         }
1134         grpChIdx = 0;
1135         for (elIdx = 0; elIdx < pPce->NumSideChannelElements; elIdx += 1) {
1136           if (pPce->SideElementHeightInfo[elIdx] == spkPlane) {
1137             chType[chIdx] = (AUDIO_CHANNEL_TYPE)((spkPlane << 4) | ACT_SIDE);
1138             chIndex[chIdx++] = grpChIdx++;
1139             if (pPce->SideElementIsCpe[elIdx]) {
1140               chType[chIdx] = (AUDIO_CHANNEL_TYPE)((spkPlane << 4) | ACT_SIDE);
1141               chIndex[chIdx++] = grpChIdx++;
1142             }
1143           }
1144         }
1145         grpChIdx = 0;
1146         for (elIdx = 0; elIdx < pPce->NumBackChannelElements; elIdx += 1) {
1147           if (pPce->BackElementHeightInfo[elIdx] == spkPlane) {
1148             chType[chIdx] = (AUDIO_CHANNEL_TYPE)((spkPlane << 4) | ACT_BACK);
1149             chIndex[chIdx++] = grpChIdx++;
1150             if (pPce->BackElementIsCpe[elIdx]) {
1151               chType[chIdx] = (AUDIO_CHANNEL_TYPE)((spkPlane << 4) | ACT_BACK);
1152               chIndex[chIdx++] = grpChIdx++;
1153             }
1154           }
1155         }
1156         grpChIdx = 0;
1157         if (spkPlane == SPEAKER_PLANE_NORMAL) {
1158           for (elIdx = 0; elIdx < pPce->NumLfeChannelElements; elIdx += 1) {
1159             chType[chIdx] = ACT_LFE;
1160             chIndex[chIdx++] = grpChIdx++;
1161           }
1162         }
1163       }
1164     }
1165   } else {
1166     int chIdx;
1167     for (chIdx = 0; chIdx < getNumberOfTotalChannels(chConfig); chIdx += 1) {
1168       getImplicitAudioChannelTypeAndIndex(&chType[chIdx], &chIndex[chIdx],
1169                                           chConfig, chIdx);
1170     }
1171   }
1172 }
1173 
CProgramConfig_GetPceChMap(const CProgramConfig * pPce,UCHAR pceChMap[],const UINT pceChMapLen)1174 int CProgramConfig_GetPceChMap(const CProgramConfig *pPce, UCHAR pceChMap[],
1175                                const UINT pceChMapLen) {
1176   const UCHAR *nElements = &pPce->NumFrontChannelElements;
1177   const UCHAR *elHeight[3], *elIsCpe[3];
1178   unsigned chIdx, plane, grp, offset, totCh[3], numCh[3][4];
1179 
1180   FDK_ASSERT(pPce != NULL);
1181   FDK_ASSERT(pceChMap != NULL);
1182 
1183   /* Init counter: */
1184   FDKmemclear(totCh, 3 * sizeof(unsigned));
1185   FDKmemclear(numCh, 3 * 4 * sizeof(unsigned));
1186 
1187   /* Analyse PCE: */
1188   elHeight[0] = pPce->FrontElementHeightInfo;
1189   elIsCpe[0] = pPce->FrontElementIsCpe;
1190   elHeight[1] = pPce->SideElementHeightInfo;
1191   elIsCpe[1] = pPce->SideElementIsCpe;
1192   elHeight[2] = pPce->BackElementHeightInfo;
1193   elIsCpe[2] = pPce->BackElementIsCpe;
1194 
1195   for (plane = 0; plane <= SPEAKER_PLANE_BOTTOM; plane += 1) {
1196     for (grp = 0; grp < 3; grp += 1) { /* front, side, back */
1197       unsigned el;
1198       for (el = 0; el < nElements[grp]; el += 1) {
1199         if (elHeight[grp][el] == plane) {
1200           unsigned elCh = elIsCpe[grp][el] ? 2 : 1;
1201           numCh[plane][grp] += elCh;
1202           totCh[plane] += elCh;
1203         }
1204       }
1205     }
1206     if (plane == SPEAKER_PLANE_NORMAL) {
1207       unsigned elCh = pPce->NumLfeChannelElements;
1208       numCh[plane][grp] += elCh;
1209       totCh[plane] += elCh;
1210     }
1211   }
1212   /* Sanity checks: */
1213   chIdx = totCh[SPEAKER_PLANE_NORMAL] + totCh[SPEAKER_PLANE_TOP] +
1214           totCh[SPEAKER_PLANE_BOTTOM];
1215   if (chIdx > pceChMapLen) {
1216     return -1;
1217   }
1218 
1219   /* Create map: */
1220   offset = grp = 0;
1221   unsigned grpThresh = numCh[SPEAKER_PLANE_NORMAL][grp];
1222   for (chIdx = 0; chIdx < totCh[SPEAKER_PLANE_NORMAL]; chIdx += 1) {
1223     while ((chIdx >= grpThresh) && (grp < 3)) {
1224       offset += numCh[1][grp] + numCh[2][grp];
1225       grp += 1;
1226       grpThresh += numCh[SPEAKER_PLANE_NORMAL][grp];
1227     }
1228     pceChMap[chIdx] = chIdx + offset;
1229   }
1230   offset = 0;
1231   for (grp = 0; grp < 4; grp += 1) { /* front, side, back and lfe */
1232     offset += numCh[SPEAKER_PLANE_NORMAL][grp];
1233     for (plane = SPEAKER_PLANE_TOP; plane <= SPEAKER_PLANE_BOTTOM; plane += 1) {
1234       unsigned mapCh;
1235       for (mapCh = 0; mapCh < numCh[plane][grp]; mapCh += 1) {
1236         pceChMap[chIdx++] = offset;
1237         offset += 1;
1238       }
1239     }
1240   }
1241   return 0;
1242 }
1243 
CProgramConfig_GetElementTable(const CProgramConfig * pPce,MP4_ELEMENT_ID elList[],const INT elListSize,UCHAR * pChMapIdx)1244 int CProgramConfig_GetElementTable(const CProgramConfig *pPce,
1245                                    MP4_ELEMENT_ID elList[],
1246                                    const INT elListSize, UCHAR *pChMapIdx) {
1247   int i, el = 0;
1248 
1249   FDK_ASSERT(elList != NULL);
1250   FDK_ASSERT(pChMapIdx != NULL);
1251   FDK_ASSERT(pPce != NULL);
1252 
1253   *pChMapIdx = 0;
1254 
1255   if ((elListSize <
1256        pPce->NumFrontChannelElements + pPce->NumSideChannelElements +
1257            pPce->NumBackChannelElements + pPce->NumLfeChannelElements) ||
1258       (pPce->NumChannels == 0)) {
1259     return 0;
1260   }
1261 
1262   for (i = 0; i < pPce->NumFrontChannelElements; i += 1) {
1263     elList[el++] = (pPce->FrontElementIsCpe[i]) ? ID_CPE : ID_SCE;
1264   }
1265 
1266   for (i = 0; i < pPce->NumSideChannelElements; i += 1) {
1267     elList[el++] = (pPce->SideElementIsCpe[i]) ? ID_CPE : ID_SCE;
1268   }
1269 
1270   for (i = 0; i < pPce->NumBackChannelElements; i += 1) {
1271     elList[el++] = (pPce->BackElementIsCpe[i]) ? ID_CPE : ID_SCE;
1272   }
1273 
1274   for (i = 0; i < pPce->NumLfeChannelElements; i += 1) {
1275     elList[el++] = ID_LFE;
1276   }
1277 
1278   /* Find an corresponding channel configuration if possible */
1279   switch (pPce->NumChannels) {
1280     case 1:
1281     case 2:
1282       /* One and two channels have no alternatives. */
1283       *pChMapIdx = pPce->NumChannels;
1284       break;
1285     case 3:
1286     case 4:
1287     case 5:
1288     case 6: { /* Test if the number of channels can be used as channel config:
1289                */
1290       C_ALLOC_SCRATCH_START(tmpPce, CProgramConfig, 1);
1291       /* Create a PCE for the config to test ... */
1292       CProgramConfig_GetDefault(tmpPce, pPce->NumChannels);
1293       /* ... and compare it with the given one. */
1294       *pChMapIdx = (!(CProgramConfig_Compare(pPce, tmpPce) & 0xE))
1295                        ? pPce->NumChannels
1296                        : 0;
1297       /* If compare result is 0 or 1 we can be sure that it is channel
1298        * config 11. */
1299       C_ALLOC_SCRATCH_END(tmpPce, CProgramConfig, 1);
1300     } break;
1301     case 7: {
1302       C_ALLOC_SCRATCH_START(tmpPce, CProgramConfig, 1);
1303       /* Create a PCE for the config to test ... */
1304       CProgramConfig_GetDefault(tmpPce, 11);
1305       /* ... and compare it with the given one. */
1306       *pChMapIdx = (!(CProgramConfig_Compare(pPce, tmpPce) & 0xE)) ? 11 : 0;
1307       /* If compare result is 0 or 1 we can be sure that it is channel
1308        * config 11. */
1309       C_ALLOC_SCRATCH_END(tmpPce, CProgramConfig, 1);
1310     } break;
1311     case 8: { /* Try the four possible 7.1ch configurations. One after the
1312                  other. */
1313       UCHAR testCfg[4] = {32, 14, 12, 7};
1314       C_ALLOC_SCRATCH_START(tmpPce, CProgramConfig, 1);
1315       for (i = 0; i < 4; i += 1) {
1316         /* Create a PCE for the config to test ... */
1317         CProgramConfig_GetDefault(tmpPce, testCfg[i]);
1318         /* ... and compare it with the given one. */
1319         if (!(CProgramConfig_Compare(pPce, tmpPce) & 0xE)) {
1320           /* If the compare result is 0 or 1 than the two channel configurations
1321            * match. */
1322           /* Explicit mapping of 7.1 side channel configuration to 7.1 rear
1323            * channel mapping. */
1324           *pChMapIdx = (testCfg[i] == 32) ? 12 : testCfg[i];
1325         }
1326       }
1327       C_ALLOC_SCRATCH_END(tmpPce, CProgramConfig, 1);
1328     } break;
1329     default:
1330       /* The PCE does not match any predefined channel configuration. */
1331       *pChMapIdx = 0;
1332       break;
1333   }
1334 
1335   return el;
1336 }
1337 
getAOT(HANDLE_FDK_BITSTREAM bs)1338 static AUDIO_OBJECT_TYPE getAOT(HANDLE_FDK_BITSTREAM bs) {
1339   int tmp = 0;
1340 
1341   tmp = FDKreadBits(bs, 5);
1342   if (tmp == AOT_ESCAPE) {
1343     int tmp2 = FDKreadBits(bs, 6);
1344     tmp = 32 + tmp2;
1345   }
1346 
1347   return (AUDIO_OBJECT_TYPE)tmp;
1348 }
1349 
getSampleRate(HANDLE_FDK_BITSTREAM bs,UCHAR * index,int nBits)1350 static INT getSampleRate(HANDLE_FDK_BITSTREAM bs, UCHAR *index, int nBits) {
1351   INT sampleRate;
1352   int idx;
1353 
1354   idx = FDKreadBits(bs, nBits);
1355   if (idx == (1 << nBits) - 1) {
1356     if (FDKgetValidBits(bs) < 24) {
1357       return 0;
1358     }
1359     sampleRate = FDKreadBits(bs, 24);
1360   } else {
1361     sampleRate = SamplingRateTable[idx];
1362   }
1363 
1364   *index = idx;
1365 
1366   return sampleRate;
1367 }
1368 
GaSpecificConfig_Parse(CSGaSpecificConfig * self,CSAudioSpecificConfig * asc,HANDLE_FDK_BITSTREAM bs,UINT ascStartAnchor)1369 static TRANSPORTDEC_ERROR GaSpecificConfig_Parse(CSGaSpecificConfig *self,
1370                                                  CSAudioSpecificConfig *asc,
1371                                                  HANDLE_FDK_BITSTREAM bs,
1372                                                  UINT ascStartAnchor) {
1373   TRANSPORTDEC_ERROR ErrorStatus = TRANSPORTDEC_OK;
1374 
1375   self->m_frameLengthFlag = FDKreadBits(bs, 1);
1376 
1377   self->m_dependsOnCoreCoder = FDKreadBits(bs, 1);
1378 
1379   if (self->m_dependsOnCoreCoder) self->m_coreCoderDelay = FDKreadBits(bs, 14);
1380 
1381   self->m_extensionFlag = FDKreadBits(bs, 1);
1382 
1383   if (asc->m_channelConfiguration == 0) {
1384     CProgramConfig_Read(&asc->m_progrConfigElement, bs, ascStartAnchor);
1385   }
1386 
1387   if ((asc->m_aot == AOT_AAC_SCAL) || (asc->m_aot == AOT_ER_AAC_SCAL)) {
1388     self->m_layer = FDKreadBits(bs, 3);
1389   }
1390 
1391   if (self->m_extensionFlag) {
1392     if (asc->m_aot == AOT_ER_BSAC) {
1393       self->m_numOfSubFrame = FDKreadBits(bs, 5);
1394       self->m_layerLength = FDKreadBits(bs, 11);
1395     }
1396 
1397     if ((asc->m_aot == AOT_ER_AAC_LC) || (asc->m_aot == AOT_ER_AAC_LTP) ||
1398         (asc->m_aot == AOT_ER_AAC_SCAL) || (asc->m_aot == AOT_ER_AAC_LD)) {
1399       asc->m_vcb11Flag = FDKreadBits(bs, 1); /* aacSectionDataResilienceFlag */
1400       asc->m_rvlcFlag =
1401           FDKreadBits(bs, 1); /* aacScalefactorDataResilienceFlag */
1402       asc->m_hcrFlag = FDKreadBits(bs, 1); /* aacSpectralDataResilienceFlag */
1403     }
1404 
1405     self->m_extensionFlag3 = FDKreadBits(bs, 1);
1406   }
1407   return (ErrorStatus);
1408 }
1409 
skipSbrHeader(HANDLE_FDK_BITSTREAM hBs,int isUsac)1410 static INT skipSbrHeader(HANDLE_FDK_BITSTREAM hBs, int isUsac) {
1411   /* Dummy parse SbrDfltHeader() */
1412   INT dflt_header_extra1, dflt_header_extra2, bitsToSkip = 0;
1413 
1414   if (!isUsac) {
1415     bitsToSkip = 6;
1416     FDKpushFor(hBs, 6); /* amp res 1, xover freq 3, reserved 2 */
1417   }
1418   bitsToSkip += 8;
1419   FDKpushFor(hBs, 8); /* start / stop freq */
1420   bitsToSkip += 2;
1421   dflt_header_extra1 = FDKreadBit(hBs);
1422   dflt_header_extra2 = FDKreadBit(hBs);
1423   bitsToSkip += 5 * dflt_header_extra1 + 6 * dflt_header_extra2;
1424   FDKpushFor(hBs, 5 * dflt_header_extra1 + 6 * dflt_header_extra2);
1425 
1426   return bitsToSkip;
1427 }
1428 
ld_sbr_header(CSAudioSpecificConfig * asc,const INT dsFactor,HANDLE_FDK_BITSTREAM hBs,CSTpCallBacks * cb)1429 static INT ld_sbr_header(CSAudioSpecificConfig *asc, const INT dsFactor,
1430                          HANDLE_FDK_BITSTREAM hBs, CSTpCallBacks *cb) {
1431   const int channelConfiguration = asc->m_channelConfiguration;
1432   int i = 0, j = 0;
1433   INT error = 0;
1434   MP4_ELEMENT_ID element = ID_NONE;
1435 
1436   /* check whether the channelConfiguration is defined in
1437    * channel_configuration_array */
1438   if (channelConfiguration < 0 ||
1439       channelConfiguration > (INT)(sizeof(channel_configuration_array) /
1440                                        sizeof(MP4_ELEMENT_ID **) -
1441                                    1)) {
1442     return TRANSPORTDEC_PARSE_ERROR;
1443   }
1444 
1445   /* read elements of the passed channel_configuration until there is ID_NONE */
1446   while ((element = channel_configuration_array[channelConfiguration][j]) !=
1447          ID_NONE) {
1448     /* Setup LFE element for upsampling too. This is essential especially for
1449      * channel configs where the LFE element is not at the last position for
1450      * example in channel config 13 or 14. It leads to memory leaks if the setup
1451      * of the LFE element would be done later in the core. */
1452     if (element == ID_SCE || element == ID_CPE || element == ID_LFE) {
1453       error |= cb->cbSbr(
1454           cb->cbSbrData, hBs, asc->m_samplingFrequency / dsFactor,
1455           asc->m_extensionSamplingFrequency / dsFactor,
1456           asc->m_samplesPerFrame / dsFactor, AOT_ER_AAC_ELD, element, i++, 0, 0,
1457           asc->configMode, &asc->SbrConfigChanged, dsFactor);
1458       if (error != TRANSPORTDEC_OK) {
1459         goto bail;
1460       }
1461     }
1462     j++;
1463   }
1464 bail:
1465   return error;
1466 }
1467 
EldSpecificConfig_Parse(CSAudioSpecificConfig * asc,HANDLE_FDK_BITSTREAM hBs,CSTpCallBacks * cb)1468 static TRANSPORTDEC_ERROR EldSpecificConfig_Parse(CSAudioSpecificConfig *asc,
1469                                                   HANDLE_FDK_BITSTREAM hBs,
1470                                                   CSTpCallBacks *cb) {
1471   TRANSPORTDEC_ERROR ErrorStatus = TRANSPORTDEC_OK;
1472   CSEldSpecificConfig *esc = &asc->m_sc.m_eldSpecificConfig;
1473   UINT eldExtType;
1474   int eldExtLen, len, cnt, ldSbrLen = 0, eldExtLenSum, numSbrHeader = 0,
1475                            sbrIndex, eldExtCnt = 0;
1476 
1477   unsigned char downscale_fill_nibble;
1478 
1479   FDKmemclear(esc, sizeof(CSEldSpecificConfig));
1480 
1481   esc->m_frameLengthFlag = FDKreadBits(hBs, 1);
1482   if (esc->m_frameLengthFlag) {
1483     asc->m_samplesPerFrame = 480;
1484   } else {
1485     asc->m_samplesPerFrame = 512;
1486   }
1487 
1488   asc->m_vcb11Flag = FDKreadBits(hBs, 1);
1489   asc->m_rvlcFlag = FDKreadBits(hBs, 1);
1490   asc->m_hcrFlag = FDKreadBits(hBs, 1);
1491 
1492   esc->m_sbrPresentFlag = FDKreadBits(hBs, 1);
1493 
1494   if (esc->m_sbrPresentFlag == 1) {
1495     esc->m_sbrSamplingRate =
1496         FDKreadBits(hBs, 1); /* 0: single rate, 1: dual rate */
1497     esc->m_sbrCrcFlag = FDKreadBits(hBs, 1);
1498 
1499     asc->m_extensionSamplingFrequency = asc->m_samplingFrequency
1500                                         << esc->m_sbrSamplingRate;
1501 
1502     if (cb->cbSbr != NULL) {
1503       /* ELD reduced delay mode: LD-SBR initialization has to know the downscale
1504          information. Postpone LD-SBR initialization and read ELD extension
1505          information first. */
1506       switch (asc->m_channelConfiguration) {
1507         case 1:
1508         case 2:
1509           numSbrHeader = 1;
1510           break;
1511         case 3:
1512           numSbrHeader = 2;
1513           break;
1514         case 4:
1515         case 5:
1516         case 6:
1517           numSbrHeader = 3;
1518           break;
1519         case 7:
1520         case 11:
1521         case 12:
1522         case 14:
1523           numSbrHeader = 4;
1524           break;
1525         default:
1526           numSbrHeader = 0;
1527           break;
1528       }
1529       for (sbrIndex = 0; sbrIndex < numSbrHeader; sbrIndex++) {
1530         ldSbrLen += skipSbrHeader(hBs, 0);
1531       }
1532     } else {
1533       return TRANSPORTDEC_UNSUPPORTED_FORMAT;
1534     }
1535   }
1536   esc->m_useLdQmfTimeAlign = 0;
1537 
1538   /* new ELD syntax */
1539   eldExtLenSum = FDKgetValidBits(hBs);
1540   esc->m_downscaledSamplingFrequency = asc->m_samplingFrequency;
1541   /* parse ExtTypeConfigData */
1542   while (((eldExtType = FDKreadBits(hBs, 4)) != ELDEXT_TERM) &&
1543          ((INT)FDKgetValidBits(hBs) >= 0) && (eldExtCnt++ < 15)) {
1544     eldExtLen = len = FDKreadBits(hBs, 4);
1545     if (len == 0xf) {
1546       len = FDKreadBits(hBs, 8);
1547       eldExtLen += len;
1548 
1549       if (len == 0xff) {
1550         len = FDKreadBits(hBs, 16);
1551         eldExtLen += len;
1552       }
1553     }
1554 
1555     switch (eldExtType) {
1556       case ELDEXT_LDSAC:
1557         esc->m_useLdQmfTimeAlign = 1;
1558         if (cb->cbSsc != NULL) {
1559           ErrorStatus = (TRANSPORTDEC_ERROR)cb->cbSsc(
1560               cb->cbSscData, hBs, asc->m_aot,
1561               asc->m_samplingFrequency << esc->m_sbrSamplingRate,
1562               asc->m_samplesPerFrame << esc->m_sbrSamplingRate,
1563               asc->m_channelConfiguration, 1, /* stereoConfigIndex */
1564               -1, /* nTimeSlots: read from bitstream */
1565               eldExtLen, asc->configMode, &asc->SacConfigChanged);
1566           if (ErrorStatus != TRANSPORTDEC_OK) {
1567             return TRANSPORTDEC_PARSE_ERROR;
1568           }
1569           if (esc->m_downscaledSamplingFrequency != asc->m_samplingFrequency) {
1570             return TRANSPORTDEC_UNSUPPORTED_FORMAT; /* ELDv2 w/ ELD downscaled
1571                                                        mode not allowed */
1572           }
1573           break;
1574         }
1575 
1576         FDK_FALLTHROUGH;
1577       default:
1578         for (cnt = 0; cnt < eldExtLen; cnt++) {
1579           FDKreadBits(hBs, 8);
1580         }
1581         break;
1582 
1583       case ELDEXT_DOWNSCALEINFO:
1584         UCHAR tmpDownscaleFreqIdx;
1585         esc->m_downscaledSamplingFrequency =
1586             getSampleRate(hBs, &tmpDownscaleFreqIdx, 4);
1587         if (esc->m_downscaledSamplingFrequency == 0 ||
1588             esc->m_downscaledSamplingFrequency > 96000) {
1589           return TRANSPORTDEC_PARSE_ERROR;
1590         }
1591         downscale_fill_nibble = FDKreadBits(hBs, 4);
1592         if (downscale_fill_nibble != 0x0) {
1593           return TRANSPORTDEC_PARSE_ERROR;
1594         }
1595         if (esc->m_useLdQmfTimeAlign == 1) {
1596           return TRANSPORTDEC_UNSUPPORTED_FORMAT; /* ELDv2 w/ ELD downscaled
1597                                                      mode not allowed */
1598         }
1599         break;
1600     }
1601   }
1602   if (eldExtType != ELDEXT_TERM) {
1603     return TRANSPORTDEC_PARSE_ERROR;
1604   }
1605 
1606   if ((INT)FDKgetValidBits(hBs) < 0) {
1607     return TRANSPORTDEC_PARSE_ERROR;
1608   }
1609 
1610   if (esc->m_sbrPresentFlag == 1 && numSbrHeader != 0) {
1611     INT dsFactor = 1; /* Downscale factor must be 1 or even for SBR */
1612     if (esc->m_downscaledSamplingFrequency != 0) {
1613       if (asc->m_samplingFrequency % esc->m_downscaledSamplingFrequency != 0) {
1614         return TRANSPORTDEC_UNSUPPORTED_FORMAT;
1615       }
1616       dsFactor = asc->m_samplingFrequency / esc->m_downscaledSamplingFrequency;
1617       if (dsFactor != 1 && (dsFactor)&1) {
1618         return TRANSPORTDEC_UNSUPPORTED_FORMAT; /* SBR needs an even downscale
1619                                                    factor */
1620       }
1621       if (dsFactor != 1 && dsFactor != 2 && dsFactor != 4) {
1622         dsFactor = 1; /* don't apply dsf for not yet supported even dsfs */
1623       }
1624       if ((INT)asc->m_samplesPerFrame % dsFactor != 0) {
1625         return TRANSPORTDEC_UNSUPPORTED_FORMAT; /* frameSize/dsf must be an
1626                                                    integer number */
1627       }
1628     }
1629     eldExtLenSum = eldExtLenSum - FDKgetValidBits(hBs);
1630     FDKpushBack(hBs, eldExtLenSum + ldSbrLen);
1631     if (0 != ld_sbr_header(asc, dsFactor, hBs, cb)) {
1632       return TRANSPORTDEC_PARSE_ERROR;
1633     }
1634     FDKpushFor(hBs, eldExtLenSum);
1635   }
1636   return (ErrorStatus);
1637 }
1638 
1639 /*
1640 Subroutine to store config in UCHAR buffer. Bit stream position does not change.
1641 */
StoreConfigAsBitstream(HANDLE_FDK_BITSTREAM hBs,const INT configSize_bits,UCHAR * configTargetBuffer,const USHORT configTargetBufferSize_bytes)1642 static UINT StoreConfigAsBitstream(
1643     HANDLE_FDK_BITSTREAM hBs, const INT configSize_bits, /* If < 0 (> 0) config
1644                                                             to read is before
1645                                                             (after) current bit
1646                                                             stream position. */
1647     UCHAR *configTargetBuffer, const USHORT configTargetBufferSize_bytes) {
1648   FDK_BITSTREAM usacConf;
1649   UINT const nBits = fAbs(configSize_bits);
1650   UINT j, tmp;
1651 
1652   if (nBits > 8 * (UINT)configTargetBufferSize_bytes) {
1653     return 1;
1654   }
1655   FDKmemclear(configTargetBuffer, configTargetBufferSize_bytes);
1656 
1657   FDKinitBitStream(&usacConf, configTargetBuffer, configTargetBufferSize_bytes,
1658                    nBits, BS_WRITER);
1659   if (configSize_bits < 0) {
1660     FDKpushBack(hBs, nBits);
1661   }
1662   for (j = nBits; j > 31; j -= 32) {
1663     tmp = FDKreadBits(hBs, 32);
1664     FDKwriteBits(&usacConf, tmp, 32);
1665   }
1666   if (j > 0) {
1667     tmp = FDKreadBits(hBs, j);
1668     FDKwriteBits(&usacConf, tmp, j);
1669   }
1670   FDKsyncCache(&usacConf);
1671   if (configSize_bits > 0) {
1672     FDKpushBack(hBs, nBits);
1673   }
1674 
1675   return 0;
1676 }
1677 
1678 /* maps coreSbrFrameLengthIndex to coreCoderFrameLength */
1679 static const USHORT usacFrameLength[8] = {768, 1024, 2048, 2048, 4096, 0, 0, 0};
1680 /* maps coreSbrFrameLengthIndex to sbrRatioIndex */
1681 static const UCHAR sbrRatioIndex[8] = {0, 0, 2, 3, 1, 0, 0, 0};
1682 
1683 /*
1684   subroutine for parsing extension element configuration:
1685   UsacExtElementConfig() q.v. ISO/IEC FDIS 23003-3:2011(E) Table 14
1686   rsv603daExtElementConfig() q.v. ISO/IEC DIS 23008-3 Table 13
1687 */
extElementConfig(CSUsacExtElementConfig * extElement,HANDLE_FDK_BITSTREAM hBs,const CSTpCallBacks * cb,const UCHAR numSignalsInGroup,const UINT coreFrameLength,const int subStreamIndex,const AUDIO_OBJECT_TYPE aot)1688 static TRANSPORTDEC_ERROR extElementConfig(CSUsacExtElementConfig *extElement,
1689                                            HANDLE_FDK_BITSTREAM hBs,
1690                                            const CSTpCallBacks *cb,
1691                                            const UCHAR numSignalsInGroup,
1692                                            const UINT coreFrameLength,
1693                                            const int subStreamIndex,
1694                                            const AUDIO_OBJECT_TYPE aot) {
1695   TRANSPORTDEC_ERROR ErrorStatus = TRANSPORTDEC_OK;
1696 
1697   UINT usacExtElementType = escapedValue(hBs, 4, 8, 16);
1698 
1699   /* recurve extension elements which are invalid for USAC */
1700   if (aot == AOT_USAC) {
1701     switch (usacExtElementType) {
1702       case ID_EXT_ELE_FILL:
1703       case ID_EXT_ELE_MPEGS:
1704       case ID_EXT_ELE_SAOC:
1705       case ID_EXT_ELE_AUDIOPREROLL:
1706       case ID_EXT_ELE_UNI_DRC:
1707         break;
1708       default:
1709         usacExtElementType = ID_EXT_ELE_UNKNOWN;
1710         break;
1711     }
1712   }
1713 
1714   int usacExtElementConfigLength = escapedValue(hBs, 4, 8, 16);
1715   extElement->usacExtElementConfigLength = (USHORT)usacExtElementConfigLength;
1716   INT bsAnchor;
1717 
1718   if (FDKreadBit(hBs)) /* usacExtElementDefaultLengthPresent */
1719     extElement->usacExtElementDefaultLength = escapedValue(hBs, 8, 16, 0) + 1;
1720   else
1721     extElement->usacExtElementDefaultLength = 0;
1722 
1723   extElement->usacExtElementPayloadFrag = FDKreadBit(hBs);
1724 
1725   bsAnchor = (INT)FDKgetValidBits(hBs);
1726 
1727   switch (usacExtElementType) {
1728     case ID_EXT_ELE_UNKNOWN:
1729     case ID_EXT_ELE_FILL:
1730       break;
1731     case ID_EXT_ELE_AUDIOPREROLL:
1732       /* No configuration element */
1733       extElement->usacExtElementHasAudioPreRoll = 1;
1734       break;
1735     case ID_EXT_ELE_UNI_DRC: {
1736       if (cb->cbUniDrc != NULL) {
1737         ErrorStatus = (TRANSPORTDEC_ERROR)cb->cbUniDrc(
1738             cb->cbUniDrcData, hBs, usacExtElementConfigLength,
1739             0, /* uniDrcConfig */
1740             subStreamIndex, 0, aot);
1741         if (ErrorStatus != TRANSPORTDEC_OK) {
1742           return ErrorStatus;
1743         }
1744       }
1745     } break;
1746     default:
1747       usacExtElementType = ID_EXT_ELE_UNKNOWN;
1748       break;
1749   }
1750   extElement->usacExtElementType = (USAC_EXT_ELEMENT_TYPE)usacExtElementType;
1751 
1752   /* Adjust bit stream position. This is required because of byte alignment and
1753    * unhandled extensions. */
1754   {
1755     INT left_bits = (usacExtElementConfigLength << 3) -
1756                     (bsAnchor - (INT)FDKgetValidBits(hBs));
1757     if (left_bits >= 0) {
1758       FDKpushFor(hBs, left_bits);
1759     } else {
1760       /* parsed too many bits */
1761       ErrorStatus = TRANSPORTDEC_PARSE_ERROR;
1762     }
1763   }
1764 
1765   return ErrorStatus;
1766 }
1767 
1768 /*
1769   subroutine for parsing the USAC / RSVD60 configuration extension:
1770   UsacConfigExtension() q.v. ISO/IEC FDIS 23003-3:2011(E) Table 15
1771   rsv603daConfigExtension() q.v. ISO/IEC DIS 23008-3 Table 14
1772 */
configExtension(CSUsacConfig * usc,HANDLE_FDK_BITSTREAM hBs,const CSTpCallBacks * cb)1773 static TRANSPORTDEC_ERROR configExtension(CSUsacConfig *usc,
1774                                           HANDLE_FDK_BITSTREAM hBs,
1775                                           const CSTpCallBacks *cb) {
1776   TRANSPORTDEC_ERROR ErrorStatus = TRANSPORTDEC_OK;
1777 
1778   int numConfigExtensions;
1779   UINT usacConfigExtType;
1780   int usacConfigExtLength;
1781   int loudnessInfoSetIndex =
1782       -1; /* index of loudnessInfoSet config extension. -1 if not contained. */
1783   int tmp_subStreamIndex = 0;
1784   AUDIO_OBJECT_TYPE tmp_aot = AOT_USAC;
1785 
1786   numConfigExtensions = (int)escapedValue(hBs, 2, 4, 8) + 1;
1787   for (int confExtIdx = 0; confExtIdx < numConfigExtensions; confExtIdx++) {
1788     INT nbits;
1789     int loudnessInfoSetConfigExtensionPosition = FDKgetValidBits(hBs);
1790     usacConfigExtType = escapedValue(hBs, 4, 8, 16);
1791     usacConfigExtLength = (int)escapedValue(hBs, 4, 8, 16);
1792 
1793     /* Start bit position of config extension */
1794     nbits = (INT)FDKgetValidBits(hBs);
1795 
1796     /* Return an error in case the bitbuffer fill level is too low. */
1797     if (nbits < usacConfigExtLength * 8) {
1798       return TRANSPORTDEC_PARSE_ERROR;
1799     }
1800 
1801     switch (usacConfigExtType) {
1802       case ID_CONFIG_EXT_FILL:
1803         for (int i = 0; i < usacConfigExtLength; i++) {
1804           if (FDKreadBits(hBs, 8) != 0xa5) {
1805             return TRANSPORTDEC_PARSE_ERROR;
1806           }
1807         }
1808         break;
1809       case ID_CONFIG_EXT_LOUDNESS_INFO: {
1810         if (cb->cbUniDrc != NULL) {
1811           ErrorStatus = (TRANSPORTDEC_ERROR)cb->cbUniDrc(
1812               cb->cbUniDrcData, hBs, usacConfigExtLength,
1813               1, /* loudnessInfoSet */
1814               tmp_subStreamIndex, loudnessInfoSetConfigExtensionPosition,
1815               tmp_aot);
1816           if (ErrorStatus != TRANSPORTDEC_OK) {
1817             return ErrorStatus;
1818           }
1819           loudnessInfoSetIndex = confExtIdx;
1820         }
1821       } break;
1822       default:
1823         break;
1824     }
1825 
1826     /* Skip remaining bits. If too many bits were parsed, assume error. */
1827     usacConfigExtLength =
1828         8 * usacConfigExtLength - (nbits - (INT)FDKgetValidBits(hBs));
1829     if (usacConfigExtLength < 0) {
1830       return TRANSPORTDEC_PARSE_ERROR;
1831     }
1832     FDKpushFor(hBs, usacConfigExtLength);
1833   }
1834 
1835   if (loudnessInfoSetIndex == -1 && cb->cbUniDrc != NULL) {
1836     /* no loudnessInfoSet contained. Clear the loudnessInfoSet struct by feeding
1837      * an empty config extension */
1838     ErrorStatus = (TRANSPORTDEC_ERROR)cb->cbUniDrc(
1839         cb->cbUniDrcData, NULL, 0, 1 /* loudnessInfoSet */, tmp_subStreamIndex,
1840         0, tmp_aot);
1841     if (ErrorStatus != TRANSPORTDEC_OK) {
1842       return ErrorStatus;
1843     }
1844   }
1845 
1846   return ErrorStatus;
1847 }
1848 
1849 /* This function unifies decoder config parsing of USAC and RSV60:
1850    rsv603daDecoderConfig() ISO/IEC DIS 23008-3   Table 8
1851    UsacDecoderConfig()     ISO/IEC FDIS 23003-3  Table 6
1852   */
UsacRsv60DecoderConfig_Parse(CSAudioSpecificConfig * asc,HANDLE_FDK_BITSTREAM hBs,const CSTpCallBacks * cb)1853 static TRANSPORTDEC_ERROR UsacRsv60DecoderConfig_Parse(
1854     CSAudioSpecificConfig *asc, HANDLE_FDK_BITSTREAM hBs,
1855     const CSTpCallBacks *cb) {
1856   TRANSPORTDEC_ERROR ErrorStatus = TRANSPORTDEC_OK;
1857   CSUsacConfig *usc = &asc->m_sc.m_usacConfig;
1858   int i, numberOfElements;
1859   int channelElementIdx =
1860       0; /* index for elements which contain audio channels (sce, cpe, lfe) */
1861   SC_CHANNEL_CONFIG sc_chan_config = {0, 0, 0, 0};
1862   int uniDrcElement =
1863       -1; /* index of uniDrc extension element. -1 if not contained. */
1864 
1865   numberOfElements = (int)escapedValue(hBs, 4, 8, 16) + 1;
1866   usc->m_usacNumElements = numberOfElements;
1867   if (numberOfElements > TP_USAC_MAX_ELEMENTS) {
1868     return TRANSPORTDEC_UNSUPPORTED_FORMAT;
1869   }
1870   usc->m_nUsacChannels = 0;
1871   usc->m_channelConfigurationIndex = asc->m_channelConfiguration;
1872 
1873   if (asc->m_aot == AOT_USAC) {
1874     sc_chan_config = sc_chan_config_tab[usc->m_channelConfigurationIndex];
1875 
1876     if (sc_chan_config.nCh > (SCHAR)TP_USAC_MAX_SPEAKERS) {
1877       return TRANSPORTDEC_PARSE_ERROR;
1878     }
1879   }
1880 
1881   for (i = 0; i < numberOfElements; i++) {
1882     MP4_ELEMENT_ID usacElementType = (MP4_ELEMENT_ID)(
1883         FDKreadBits(hBs, 2) | USAC_ID_BIT); /* set USAC_ID_BIT to map
1884                                                usacElementType to
1885                                                MP4_ELEMENT_ID enum */
1886     usc->element[i].usacElementType = usacElementType;
1887 
1888     /* sanity check: update element counter */
1889     if (asc->m_aot == AOT_USAC) {
1890       switch (usacElementType) {
1891         case ID_USAC_SCE:
1892           sc_chan_config.nSCE--;
1893           break;
1894         case ID_USAC_CPE:
1895           sc_chan_config.nCPE--;
1896           break;
1897         case ID_USAC_LFE:
1898           sc_chan_config.nLFE--;
1899           break;
1900         default:
1901           break;
1902       }
1903       if (usc->m_channelConfigurationIndex) {
1904         /* sanity check: no element counter may be smaller zero */
1905         if (sc_chan_config.nCPE < 0 || sc_chan_config.nSCE < 0 ||
1906             sc_chan_config.nLFE < 0) {
1907           return TRANSPORTDEC_PARSE_ERROR;
1908         }
1909       }
1910     }
1911 
1912     switch (usacElementType) {
1913       case ID_USAC_SCE:
1914         /* UsacCoreConfig() ISO/IEC FDIS 23003-3  Table 10 */
1915         if (FDKreadBit(hBs)) { /* tw_mdct */
1916           return TRANSPORTDEC_UNSUPPORTED_FORMAT;
1917         }
1918         usc->element[i].m_noiseFilling = FDKreadBits(hBs, 1);
1919         /* end of UsacCoreConfig() */
1920         if (usc->m_sbrRatioIndex > 0) {
1921           if (cb->cbSbr == NULL) {
1922             return TRANSPORTDEC_UNKOWN_ERROR;
1923           }
1924           /* SbrConfig() ISO/IEC FDIS 23003-3  Table 11 */
1925           usc->element[i].m_harmonicSBR = FDKreadBit(hBs);
1926           usc->element[i].m_interTes = FDKreadBit(hBs);
1927           usc->element[i].m_pvc = FDKreadBit(hBs);
1928           if (cb->cbSbr(cb->cbSbrData, hBs, asc->m_samplingFrequency,
1929                         asc->m_extensionSamplingFrequency,
1930                         asc->m_samplesPerFrame, asc->m_aot, ID_SCE,
1931                         channelElementIdx, usc->element[i].m_harmonicSBR,
1932                         usc->element[i].m_stereoConfigIndex, asc->configMode,
1933                         &asc->SbrConfigChanged, 1)) {
1934             return TRANSPORTDEC_PARSE_ERROR;
1935           }
1936           /* end of SbrConfig() */
1937         }
1938         usc->m_nUsacChannels += 1;
1939         channelElementIdx++;
1940         break;
1941 
1942       case ID_USAC_CPE:
1943         /* UsacCoreConfig() ISO/IEC FDIS 23003-3  Table 10 */
1944         if (FDKreadBit(hBs)) { /* tw_mdct */
1945           return TRANSPORTDEC_UNSUPPORTED_FORMAT;
1946         }
1947         usc->element[i].m_noiseFilling = FDKreadBits(hBs, 1);
1948         /* end of UsacCoreConfig() */
1949         if (usc->m_sbrRatioIndex > 0) {
1950           if (cb->cbSbr == NULL) return TRANSPORTDEC_UNKOWN_ERROR;
1951           /* SbrConfig() ISO/IEC FDIS 23003-3 */
1952           usc->element[i].m_harmonicSBR = FDKreadBit(hBs);
1953           usc->element[i].m_interTes = FDKreadBit(hBs);
1954           usc->element[i].m_pvc = FDKreadBit(hBs);
1955           {
1956             INT bitsToSkip = skipSbrHeader(hBs, 1);
1957             /* read stereoConfigIndex */
1958             usc->element[i].m_stereoConfigIndex = FDKreadBits(hBs, 2);
1959             /* rewind */
1960             FDKpushBack(hBs, bitsToSkip + 2);
1961           }
1962           {
1963             MP4_ELEMENT_ID el_type =
1964                 (usc->element[i].m_stereoConfigIndex == 1 ||
1965                  usc->element[i].m_stereoConfigIndex == 2)
1966                     ? ID_SCE
1967                     : ID_CPE;
1968             if (cb->cbSbr(cb->cbSbrData, hBs, asc->m_samplingFrequency,
1969                           asc->m_extensionSamplingFrequency,
1970                           asc->m_samplesPerFrame, asc->m_aot, el_type,
1971                           channelElementIdx, usc->element[i].m_harmonicSBR,
1972                           usc->element[i].m_stereoConfigIndex, asc->configMode,
1973                           &asc->SbrConfigChanged, 1)) {
1974               return TRANSPORTDEC_PARSE_ERROR;
1975             }
1976           }
1977           /* end of SbrConfig() */
1978 
1979           usc->element[i].m_stereoConfigIndex =
1980               FDKreadBits(hBs, 2); /* Needed in RM5 syntax */
1981 
1982           if (usc->element[i].m_stereoConfigIndex > 0) {
1983             if (cb->cbSsc != NULL) {
1984               int samplesPerFrame = asc->m_samplesPerFrame;
1985 
1986               if (usc->m_sbrRatioIndex == 1) samplesPerFrame <<= 2;
1987               if (usc->m_sbrRatioIndex == 2)
1988                 samplesPerFrame = (samplesPerFrame * 8) / 3;
1989               if (usc->m_sbrRatioIndex == 3) samplesPerFrame <<= 1;
1990 
1991               /* Mps212Config() ISO/IEC FDIS 23003-3 */
1992               if (cb->cbSsc(cb->cbSscData, hBs, asc->m_aot,
1993                             asc->m_extensionSamplingFrequency, samplesPerFrame,
1994                             1, /* only downmix channels (residual channels are
1995                                   not counted) */
1996                             usc->element[i].m_stereoConfigIndex,
1997                             usc->m_coreSbrFrameLengthIndex,
1998                             0, /* don't know the length */
1999                             asc->configMode, &asc->SacConfigChanged)) {
2000                 return TRANSPORTDEC_PARSE_ERROR;
2001               }
2002               /* end of Mps212Config() */
2003             } else {
2004               return TRANSPORTDEC_UNKOWN_ERROR;
2005             }
2006           }
2007         } else {
2008           usc->element[i].m_stereoConfigIndex = 0;
2009         }
2010         usc->m_nUsacChannels += 2;
2011 
2012         channelElementIdx++;
2013         break;
2014 
2015       case ID_USAC_LFE:
2016         usc->element[i].m_noiseFilling = 0;
2017         usc->m_nUsacChannels += 1;
2018         if (usc->m_sbrRatioIndex > 0) {
2019           /* Use SBR for upsampling */
2020           if (cb->cbSbr == NULL) return ErrorStatus = TRANSPORTDEC_UNKOWN_ERROR;
2021           usc->element[i].m_harmonicSBR = (UCHAR)0;
2022           usc->element[i].m_interTes = (UCHAR)0;
2023           usc->element[i].m_pvc = (UCHAR)0;
2024           if (cb->cbSbr(cb->cbSbrData, hBs, asc->m_samplingFrequency,
2025                         asc->m_extensionSamplingFrequency,
2026                         asc->m_samplesPerFrame, asc->m_aot, ID_LFE,
2027                         channelElementIdx, usc->element[i].m_harmonicSBR,
2028                         usc->element[i].m_stereoConfigIndex, asc->configMode,
2029                         &asc->SbrConfigChanged, 1)) {
2030             return ErrorStatus = TRANSPORTDEC_PARSE_ERROR;
2031           }
2032         }
2033         channelElementIdx++;
2034         break;
2035 
2036       case ID_USAC_EXT:
2037         ErrorStatus = extElementConfig(&usc->element[i].extElement, hBs, cb, 0,
2038                                        asc->m_samplesPerFrame, 0, asc->m_aot);
2039         if (usc->element[i].extElement.usacExtElementType ==
2040             ID_EXT_ELE_UNI_DRC) {
2041           uniDrcElement = i;
2042         }
2043 
2044         if (ErrorStatus) {
2045           return ErrorStatus;
2046         }
2047         break;
2048 
2049       default:
2050         /* non USAC-element encountered */
2051         return TRANSPORTDEC_PARSE_ERROR;
2052     }
2053   }
2054 
2055   if (asc->m_aot == AOT_USAC) {
2056     if (usc->m_channelConfigurationIndex) {
2057       /* sanity check: all element counter must be zero */
2058       if (sc_chan_config.nCPE | sc_chan_config.nSCE | sc_chan_config.nLFE) {
2059         return TRANSPORTDEC_PARSE_ERROR;
2060       }
2061     } else {
2062       /* sanity check: number of audio channels shall be equal to or smaller
2063        * than the accumulated sum of all channels */
2064       if ((INT)(-2 * sc_chan_config.nCPE - sc_chan_config.nSCE -
2065                 sc_chan_config.nLFE) < (INT)usc->numAudioChannels) {
2066         return TRANSPORTDEC_PARSE_ERROR;
2067       }
2068     }
2069   }
2070 
2071   if (uniDrcElement == -1 && cb->cbUniDrc != NULL) {
2072     /* no uniDrcConfig contained. Clear the uniDrcConfig struct by feeding an
2073      * empty extension element */
2074     int subStreamIndex = 0;
2075     ErrorStatus = (TRANSPORTDEC_ERROR)cb->cbUniDrc(
2076         cb->cbUniDrcData, NULL, 0, 0 /* uniDrcConfig */, subStreamIndex, 0,
2077         asc->m_aot);
2078     if (ErrorStatus != TRANSPORTDEC_OK) {
2079       return ErrorStatus;
2080     }
2081   }
2082 
2083   return ErrorStatus;
2084 }
2085 
2086 /* Mapping of coreSbrFrameLengthIndex defined by Table 70 in ISO/IEC 23003-3 */
UsacConfig_SetCoreSbrFrameLengthIndex(CSAudioSpecificConfig * asc,int coreSbrFrameLengthIndex)2087 static TRANSPORTDEC_ERROR UsacConfig_SetCoreSbrFrameLengthIndex(
2088     CSAudioSpecificConfig *asc, int coreSbrFrameLengthIndex) {
2089   int sbrRatioIndex_val;
2090 
2091   if (coreSbrFrameLengthIndex > 4) {
2092     return TRANSPORTDEC_PARSE_ERROR; /* reserved values */
2093   }
2094   asc->m_sc.m_usacConfig.m_coreSbrFrameLengthIndex = coreSbrFrameLengthIndex;
2095   asc->m_samplesPerFrame = usacFrameLength[coreSbrFrameLengthIndex];
2096   sbrRatioIndex_val = sbrRatioIndex[coreSbrFrameLengthIndex];
2097   asc->m_sc.m_usacConfig.m_sbrRatioIndex = sbrRatioIndex_val;
2098 
2099   if (sbrRatioIndex_val > 0) {
2100     asc->m_sbrPresentFlag = 1;
2101     asc->m_extensionSamplingFrequency = asc->m_samplingFrequency;
2102     asc->m_extensionSamplingFrequencyIndex = asc->m_samplingFrequencyIndex;
2103     switch (sbrRatioIndex_val) {
2104       case 1: /* sbrRatio = 4:1 */
2105         asc->m_samplingFrequency >>= 2;
2106         asc->m_samplesPerFrame >>= 2;
2107         break;
2108       case 2: /* sbrRatio = 8:3 */
2109         asc->m_samplingFrequency = (asc->m_samplingFrequency * 3) / 8;
2110         asc->m_samplesPerFrame = (asc->m_samplesPerFrame * 3) / 8;
2111         break;
2112       case 3: /* sbrRatio = 2:1 */
2113         asc->m_samplingFrequency >>= 1;
2114         asc->m_samplesPerFrame >>= 1;
2115         break;
2116       default:
2117         return TRANSPORTDEC_PARSE_ERROR;
2118     }
2119     asc->m_samplingFrequencyIndex =
2120         getSamplingRateIndex(asc->m_samplingFrequency, 4);
2121   }
2122 
2123   return TRANSPORTDEC_OK;
2124 }
2125 
UsacConfig_Parse(CSAudioSpecificConfig * asc,HANDLE_FDK_BITSTREAM hBs,CSTpCallBacks * cb)2126 static TRANSPORTDEC_ERROR UsacConfig_Parse(CSAudioSpecificConfig *asc,
2127                                            HANDLE_FDK_BITSTREAM hBs,
2128                                            CSTpCallBacks *cb) {
2129   int usacSamplingFrequency, channelConfigurationIndex, coreSbrFrameLengthIndex;
2130   TRANSPORTDEC_ERROR err = TRANSPORTDEC_OK;
2131 
2132   /* Start bit position of usacConfig */
2133   INT nbits = (INT)FDKgetValidBits(hBs);
2134 
2135   usacSamplingFrequency = getSampleRate(hBs, &asc->m_samplingFrequencyIndex, 5);
2136   if (usacSamplingFrequency == 0 || usacSamplingFrequency > 96000) {
2137     return TRANSPORTDEC_PARSE_ERROR;
2138   }
2139   asc->m_samplingFrequency = (UINT)usacSamplingFrequency;
2140 
2141   coreSbrFrameLengthIndex = FDKreadBits(hBs, 3);
2142   if (UsacConfig_SetCoreSbrFrameLengthIndex(asc, coreSbrFrameLengthIndex) !=
2143       TRANSPORTDEC_OK) {
2144     return TRANSPORTDEC_PARSE_ERROR;
2145   }
2146 
2147   channelConfigurationIndex = FDKreadBits(hBs, 5);
2148   if (channelConfigurationIndex > 2) {
2149     return TRANSPORTDEC_PARSE_ERROR; /* only channelConfigurationIndex = [1,2]
2150                                         are supported */
2151   }
2152 
2153   if (channelConfigurationIndex == 0) {
2154     return TRANSPORTDEC_PARSE_ERROR; /* only channelConfigurationIndex = [1,2]
2155                                         are supported */
2156   }
2157   asc->m_channelConfiguration = channelConfigurationIndex;
2158 
2159   err = UsacRsv60DecoderConfig_Parse(asc, hBs, cb);
2160   if (err != TRANSPORTDEC_OK) {
2161     return err;
2162   }
2163 
2164   if (FDKreadBits(hBs, 1)) { /* usacConfigExtensionPresent */
2165     err = configExtension(&asc->m_sc.m_usacConfig, hBs, cb);
2166     if (err != TRANSPORTDEC_OK) {
2167       return err;
2168     }
2169   } else if (cb->cbUniDrc != NULL) {
2170     /* no loudnessInfoSet contained. Clear the loudnessInfoSet struct by feeding
2171      * an empty config extension */
2172     err = (TRANSPORTDEC_ERROR)cb->cbUniDrc(
2173         cb->cbUniDrcData, NULL, 0, 1 /* loudnessInfoSet */, 0, 0, asc->m_aot);
2174     if (err != TRANSPORTDEC_OK) {
2175       return err;
2176     }
2177   }
2178 
2179   /* sanity check whether number of channels signaled in UsacDecoderConfig()
2180      matches the number of channels required by channelConfigurationIndex */
2181   if ((channelConfigurationIndex > 0) &&
2182       (sc_chan_config_tab[channelConfigurationIndex].nCh !=
2183        asc->m_sc.m_usacConfig.m_nUsacChannels)) {
2184     return TRANSPORTDEC_PARSE_ERROR;
2185   }
2186 
2187   /* Copy UsacConfig() to asc->m_sc.m_usacConfig.UsacConfig[] buffer. */
2188   INT configSize_bits = (INT)FDKgetValidBits(hBs) - nbits;
2189   if (StoreConfigAsBitstream(hBs, configSize_bits,
2190                              asc->m_sc.m_usacConfig.UsacConfig,
2191                              TP_USAC_MAX_CONFIG_LEN)) {
2192     return TRANSPORTDEC_PARSE_ERROR;
2193   }
2194   asc->m_sc.m_usacConfig.UsacConfigBits = fAbs(configSize_bits);
2195 
2196   return err;
2197 }
2198 
AudioSpecificConfig_ExtensionParse(CSAudioSpecificConfig * self,HANDLE_FDK_BITSTREAM bs,CSTpCallBacks * cb)2199 static TRANSPORTDEC_ERROR AudioSpecificConfig_ExtensionParse(
2200     CSAudioSpecificConfig *self, HANDLE_FDK_BITSTREAM bs, CSTpCallBacks *cb) {
2201   TP_ASC_EXTENSION_ID lastAscExt, ascExtId = ASCEXT_UNKOWN;
2202   INT bitsAvailable = (INT)FDKgetValidBits(bs);
2203 
2204   while (bitsAvailable >= 11) {
2205     lastAscExt = ascExtId;
2206     ascExtId = (TP_ASC_EXTENSION_ID)FDKreadBits(bs, 11);
2207     bitsAvailable -= 11;
2208 
2209     switch (ascExtId) {
2210       case ASCEXT_SBR: /* 0x2b7 */
2211         if ((self->m_extensionAudioObjectType != AOT_SBR) &&
2212             (bitsAvailable >= 5)) {
2213           self->m_extensionAudioObjectType = getAOT(bs);
2214 
2215           if ((self->m_extensionAudioObjectType == AOT_SBR) ||
2216               (self->m_extensionAudioObjectType ==
2217                AOT_ER_BSAC)) { /* Get SBR extension configuration */
2218             self->m_sbrPresentFlag = FDKreadBits(bs, 1);
2219             if (self->m_aot == AOT_USAC && self->m_sbrPresentFlag > 0 &&
2220                 self->m_sc.m_usacConfig.m_sbrRatioIndex == 0) {
2221               return TRANSPORTDEC_PARSE_ERROR;
2222             }
2223 
2224             if (self->m_sbrPresentFlag == 1) {
2225               self->m_extensionSamplingFrequency = getSampleRate(
2226                   bs, &self->m_extensionSamplingFrequencyIndex, 4);
2227 
2228               if (self->m_extensionSamplingFrequency == 0 ||
2229                   self->m_extensionSamplingFrequency > 96000) {
2230                 return TRANSPORTDEC_PARSE_ERROR;
2231               }
2232             }
2233             if (self->m_extensionAudioObjectType == AOT_ER_BSAC) {
2234               self->m_extensionChannelConfiguration = FDKreadBits(bs, 4);
2235             }
2236           }
2237           /* Update counter because of variable length fields (AOT and sampling
2238            * rate) */
2239           bitsAvailable = (INT)FDKgetValidBits(bs);
2240         }
2241         break;
2242       case ASCEXT_PS: /* 0x548 */
2243         if ((lastAscExt == ASCEXT_SBR) &&
2244             (self->m_extensionAudioObjectType == AOT_SBR) &&
2245             (bitsAvailable > 0)) { /* Get PS extension configuration */
2246           self->m_psPresentFlag = FDKreadBits(bs, 1);
2247           bitsAvailable -= 1;
2248         }
2249         break;
2250       case ASCEXT_MPS: /* 0x76a */
2251         if (self->m_extensionAudioObjectType == AOT_MPEGS) break;
2252         FDK_FALLTHROUGH;
2253       case ASCEXT_LDMPS: /* 0x7cc */
2254         if ((ascExtId == ASCEXT_LDMPS) &&
2255             (self->m_extensionAudioObjectType == AOT_LD_MPEGS))
2256           break;
2257         if (bitsAvailable >= 1) {
2258           bitsAvailable -= 1;
2259           if (FDKreadBits(bs, 1)) { /* self->m_mpsPresentFlag */
2260             int sscLen = FDKreadBits(bs, 8);
2261             bitsAvailable -= 8;
2262             if (sscLen == 0xFF) {
2263               sscLen += FDKreadBits(bs, 16);
2264               bitsAvailable -= 16;
2265             }
2266             FDKpushFor(bs, sscLen); /* Skip SSC to be able to read the next
2267                                        extension if there is one. */
2268 
2269             bitsAvailable -= sscLen * 8;
2270           }
2271         }
2272         break;
2273       case ASCEXT_SAOC:
2274         if ((ascExtId == ASCEXT_SAOC) &&
2275             (self->m_extensionAudioObjectType == AOT_SAOC))
2276           break;
2277         if (FDKreadBits(bs, 1)) { /* saocPresent */
2278           int saocscLen = FDKreadBits(bs, 8);
2279           bitsAvailable -= 8;
2280           if (saocscLen == 0xFF) {
2281             saocscLen += FDKreadBits(bs, 16);
2282             bitsAvailable -= 16;
2283           }
2284           FDKpushFor(bs, saocscLen);
2285           bitsAvailable -= saocscLen * 8;
2286         }
2287         break;
2288       default:
2289         /* Just ignore anything. */
2290         return TRANSPORTDEC_OK;
2291     }
2292   }
2293 
2294   return TRANSPORTDEC_OK;
2295 }
2296 
2297 /*
2298  * API Functions
2299  */
2300 
AudioSpecificConfig_Init(CSAudioSpecificConfig * asc)2301 void AudioSpecificConfig_Init(CSAudioSpecificConfig *asc) {
2302   FDKmemclear(asc, sizeof(CSAudioSpecificConfig));
2303 
2304   /* Init all values that should not be zero. */
2305   asc->m_aot = AOT_NONE;
2306   asc->m_samplingFrequencyIndex = 0xf;
2307   asc->m_epConfig = -1;
2308   asc->m_extensionAudioObjectType = AOT_NULL_OBJECT;
2309   CProgramConfig_Init(&asc->m_progrConfigElement);
2310 }
2311 
AudioSpecificConfig_Parse(CSAudioSpecificConfig * self,HANDLE_FDK_BITSTREAM bs,int fExplicitBackwardCompatible,CSTpCallBacks * cb,UCHAR configMode,UCHAR configChanged,AUDIO_OBJECT_TYPE m_aot)2312 TRANSPORTDEC_ERROR AudioSpecificConfig_Parse(
2313     CSAudioSpecificConfig *self, HANDLE_FDK_BITSTREAM bs,
2314     int fExplicitBackwardCompatible, CSTpCallBacks *cb, UCHAR configMode,
2315     UCHAR configChanged, AUDIO_OBJECT_TYPE m_aot) {
2316   TRANSPORTDEC_ERROR ErrorStatus = TRANSPORTDEC_OK;
2317   UINT ascStartAnchor = FDKgetValidBits(bs);
2318   int frameLengthFlag = -1;
2319 
2320   AudioSpecificConfig_Init(self);
2321 
2322   self->configMode = configMode;
2323   self->AacConfigChanged = configChanged;
2324   self->SbrConfigChanged = configChanged;
2325   self->SacConfigChanged = configChanged;
2326 
2327   if (m_aot != AOT_NULL_OBJECT) {
2328     self->m_aot = m_aot;
2329   } else {
2330     self->m_aot = getAOT(bs);
2331     self->m_samplingFrequency =
2332         getSampleRate(bs, &self->m_samplingFrequencyIndex, 4);
2333     if (self->m_samplingFrequency <= 0 ||
2334         (self->m_samplingFrequency > 96000 && self->m_aot != 39) ||
2335         self->m_samplingFrequency > 4 * 96000) {
2336       return TRANSPORTDEC_PARSE_ERROR;
2337     }
2338 
2339     self->m_channelConfiguration = FDKreadBits(bs, 4);
2340 
2341     /* MPEG-04 standard ISO/IEC 14496-3: channelConfiguration == 0 is reserved
2342        in er_raw_data_block (table 4.19) and er_raw_data_block_eld (table 4.75)
2343        MPEG-04 conformance ISO/IEC 14496-4: channelConfiguration == 0 is not
2344        permitted for AOT_ER_AAC_LC, AOT_ER_AAC_LTP, AOT_ER_AAC_LD,
2345        AOT_ER_AAC_SCAL (chapter 6.6.4.1.2.1.1) */
2346     if ((self->m_channelConfiguration == 0) &&
2347         ((self->m_aot == AOT_ER_AAC_LC) || (self->m_aot == AOT_ER_AAC_LTP) ||
2348          (self->m_aot == AOT_ER_AAC_LD) || (self->m_aot == AOT_ER_AAC_SCAL) ||
2349          (self->m_aot == AOT_ER_AAC_ELD))) {
2350       return TRANSPORTDEC_UNSUPPORTED_FORMAT;
2351     }
2352     /* MPEG-04 conformance ISO/IEC 14496-4: channelConfiguration > 2 is not
2353      * permitted for AOT_AAC_SCAL and AOT_ER_AAC_SCAL (chapter 6.6.4.1.2.1.1) */
2354     if ((self->m_channelConfiguration > 2) &&
2355         ((self->m_aot == AOT_AAC_SCAL) || (self->m_aot == AOT_ER_AAC_SCAL))) {
2356       return TRANSPORTDEC_UNSUPPORTED_FORMAT;
2357     }
2358 
2359     /* SBR extension ( explicit non-backwards compatible mode ) */
2360     self->m_sbrPresentFlag = 0;
2361     self->m_psPresentFlag = 0;
2362 
2363     if (self->m_aot == AOT_SBR || self->m_aot == AOT_PS) {
2364       self->m_extensionAudioObjectType = AOT_SBR;
2365 
2366       self->m_sbrPresentFlag = 1;
2367       if (self->m_aot == AOT_PS) {
2368         self->m_psPresentFlag = 1;
2369       }
2370 
2371       self->m_extensionSamplingFrequency =
2372           getSampleRate(bs, &self->m_extensionSamplingFrequencyIndex, 4);
2373       if (self->m_extensionSamplingFrequency == 0 ||
2374           self->m_extensionSamplingFrequency > 96000) {
2375         return TRANSPORTDEC_PARSE_ERROR;
2376       }
2377       self->m_aot = getAOT(bs);
2378 
2379       switch (self->m_aot) {
2380         case AOT_AAC_LC:
2381           break;
2382         case AOT_ER_BSAC:
2383           break;
2384         default:
2385           return TRANSPORTDEC_UNSUPPORTED_FORMAT;
2386       }
2387 
2388       if (self->m_aot == AOT_ER_BSAC) {
2389         self->m_extensionChannelConfiguration = FDKreadBits(bs, 4);
2390       }
2391     } else {
2392       self->m_extensionAudioObjectType = AOT_NULL_OBJECT;
2393     }
2394   }
2395 
2396   /* Parse whatever specific configs */
2397   switch (self->m_aot) {
2398     case AOT_AAC_LC:
2399     case AOT_AAC_SCAL:
2400     case AOT_ER_AAC_LC:
2401     case AOT_ER_AAC_LD:
2402     case AOT_ER_AAC_SCAL:
2403     case AOT_ER_BSAC:
2404       if ((ErrorStatus = GaSpecificConfig_Parse(&self->m_sc.m_gaSpecificConfig,
2405                                                 self, bs, ascStartAnchor)) !=
2406           TRANSPORTDEC_OK) {
2407         return (ErrorStatus);
2408       }
2409       frameLengthFlag = self->m_sc.m_gaSpecificConfig.m_frameLengthFlag;
2410       break;
2411     case AOT_MPEGS:
2412       if (cb->cbSsc != NULL) {
2413         if (cb->cbSsc(cb->cbSscData, bs, self->m_aot, self->m_samplingFrequency,
2414                       self->m_samplesPerFrame, self->m_channelConfiguration, 1,
2415                       -1, /* nTimeSlots: read from bitstream */
2416                       0,  /* don't know the length */
2417                       self->configMode, &self->SacConfigChanged)) {
2418           return TRANSPORTDEC_UNSUPPORTED_FORMAT;
2419         }
2420       } else {
2421         return TRANSPORTDEC_UNSUPPORTED_FORMAT;
2422       }
2423       break;
2424     case AOT_ER_AAC_ELD:
2425       if ((ErrorStatus = EldSpecificConfig_Parse(self, bs, cb)) !=
2426           TRANSPORTDEC_OK) {
2427         return (ErrorStatus);
2428       }
2429       frameLengthFlag = self->m_sc.m_eldSpecificConfig.m_frameLengthFlag;
2430       self->m_sbrPresentFlag = self->m_sc.m_eldSpecificConfig.m_sbrPresentFlag;
2431       self->m_extensionSamplingFrequency =
2432           (self->m_sc.m_eldSpecificConfig.m_sbrSamplingRate + 1) *
2433           self->m_samplingFrequency;
2434       break;
2435     case AOT_USAC:
2436       if ((ErrorStatus = UsacConfig_Parse(self, bs, cb)) != TRANSPORTDEC_OK) {
2437         return (ErrorStatus);
2438       }
2439       break;
2440 
2441     default:
2442       return TRANSPORTDEC_UNSUPPORTED_FORMAT;
2443   }
2444 
2445   /* Frame length */
2446   switch (self->m_aot) {
2447     case AOT_AAC_LC:
2448     case AOT_AAC_SCAL:
2449     case AOT_ER_AAC_LC:
2450     case AOT_ER_AAC_SCAL:
2451     case AOT_ER_BSAC:
2452       /*case AOT_USAC:*/
2453       if (!frameLengthFlag)
2454         self->m_samplesPerFrame = 1024;
2455       else
2456         self->m_samplesPerFrame = 960;
2457       break;
2458     case AOT_ER_AAC_LD:
2459       if (!frameLengthFlag)
2460         self->m_samplesPerFrame = 512;
2461       else
2462         self->m_samplesPerFrame = 480;
2463       break;
2464     default:
2465       break;
2466   }
2467 
2468   switch (self->m_aot) {
2469     case AOT_ER_AAC_LC:
2470     case AOT_ER_AAC_LD:
2471     case AOT_ER_AAC_ELD:
2472     case AOT_ER_AAC_SCAL:
2473     case AOT_ER_CELP:
2474     case AOT_ER_HVXC:
2475     case AOT_ER_BSAC:
2476       self->m_epConfig = FDKreadBits(bs, 2);
2477 
2478       if (self->m_epConfig > 1) {
2479         return TRANSPORTDEC_UNSUPPORTED_FORMAT;  // EPCONFIG;
2480       }
2481       break;
2482     default:
2483       break;
2484   }
2485 
2486   if (fExplicitBackwardCompatible &&
2487       (self->m_aot == AOT_AAC_LC || self->m_aot == AOT_ER_AAC_LD ||
2488        self->m_aot == AOT_ER_BSAC)) {
2489     ErrorStatus = AudioSpecificConfig_ExtensionParse(self, bs, cb);
2490   }
2491 
2492   /* Copy config() to asc->config[] buffer. */
2493   if ((ErrorStatus == TRANSPORTDEC_OK) && (self->m_aot == AOT_USAC)) {
2494     INT configSize_bits = (INT)FDKgetValidBits(bs) - (INT)ascStartAnchor;
2495     if (StoreConfigAsBitstream(bs, configSize_bits, self->config,
2496                                TP_USAC_MAX_CONFIG_LEN)) {
2497       return TRANSPORTDEC_PARSE_ERROR;
2498     }
2499     self->configBits = fAbs(configSize_bits);
2500   }
2501 
2502   return (ErrorStatus);
2503 }
2504 
Drm_xHEAACDecoderConfig(CSAudioSpecificConfig * asc,HANDLE_FDK_BITSTREAM hBs,int audioMode,CSTpCallBacks * cb)2505 static TRANSPORTDEC_ERROR Drm_xHEAACDecoderConfig(
2506     CSAudioSpecificConfig *asc, HANDLE_FDK_BITSTREAM hBs, int audioMode,
2507     CSTpCallBacks *cb /* use cb == NULL to signal config check only mode */
2508 ) {
2509   TRANSPORTDEC_ERROR ErrorStatus = TRANSPORTDEC_OK;
2510   CSUsacConfig *usc = &asc->m_sc.m_usacConfig;
2511   int elemIdx = 0;
2512 
2513   usc->element[elemIdx].m_stereoConfigIndex = 0;
2514 
2515   usc->m_usacNumElements = 1; /* Currently all extension elements are skipped
2516                                  -> only one SCE or CPE. */
2517 
2518   switch (audioMode) {
2519     case 0: /* mono: ID_USAC_SCE */
2520       usc->element[elemIdx].usacElementType = ID_USAC_SCE;
2521       usc->m_nUsacChannels = 1;
2522       usc->element[elemIdx].m_noiseFilling = FDKreadBits(hBs, 1);
2523       if (usc->m_sbrRatioIndex > 0) {
2524         if (cb == NULL) {
2525           return ErrorStatus;
2526         }
2527         if (cb->cbSbr != NULL) {
2528           usc->element[elemIdx].m_harmonicSBR = FDKreadBit(hBs);
2529           usc->element[elemIdx].m_interTes = FDKreadBit(hBs);
2530           usc->element[elemIdx].m_pvc = FDKreadBit(hBs);
2531           if (cb->cbSbr(cb->cbSbrData, hBs, asc->m_samplingFrequency,
2532                         asc->m_extensionSamplingFrequency,
2533                         asc->m_samplesPerFrame, asc->m_aot, ID_SCE, elemIdx,
2534                         usc->element[elemIdx].m_harmonicSBR,
2535                         usc->element[elemIdx].m_stereoConfigIndex,
2536                         asc->configMode, &asc->SbrConfigChanged, 1)) {
2537             return ErrorStatus = TRANSPORTDEC_PARSE_ERROR;
2538           }
2539         }
2540       }
2541       break;
2542     case 2: /* stereo: ID_USAC_CPE */
2543       usc->element[elemIdx].usacElementType = ID_USAC_CPE;
2544       usc->m_nUsacChannels = 2;
2545       usc->element[elemIdx].m_noiseFilling = FDKreadBits(hBs, 1);
2546       if (usc->m_sbrRatioIndex > 0) {
2547         usc->element[elemIdx].m_harmonicSBR = FDKreadBit(hBs);
2548         usc->element[elemIdx].m_interTes = FDKreadBit(hBs);
2549         usc->element[elemIdx].m_pvc = FDKreadBit(hBs);
2550         {
2551           INT bitsToSkip = skipSbrHeader(hBs, 1);
2552           /* read stereoConfigIndex */
2553           usc->element[elemIdx].m_stereoConfigIndex = FDKreadBits(hBs, 2);
2554           /* rewind */
2555           FDKpushBack(hBs, bitsToSkip + 2);
2556         }
2557         /*
2558         The application of the following tools is mutually exclusive per audio
2559         stream configuration (see clause 5.3.2, xHE-AAC codec configuration):
2560         - MPS212 parametric stereo tool with residual coding
2561         (stereoConfigIndex>1); and
2562         - QMF based Harmonic Transposer (harmonicSBR==1).
2563         */
2564         if ((usc->element[elemIdx].m_stereoConfigIndex > 1) &&
2565             usc->element[elemIdx].m_harmonicSBR) {
2566           return ErrorStatus = TRANSPORTDEC_PARSE_ERROR;
2567         }
2568         /*
2569         The 4:1 sbrRatio (sbrRatioIndex==1 in [11]) may only be employed:
2570         - in mono operation; or
2571         - in stereo operation if parametric stereo (MPS212) without residual
2572         coding is applied, i.e. if stereoConfigIndex==1 (see clause 5.3.2,
2573         xHE-AAC codec configuration).
2574         */
2575         if ((usc->m_sbrRatioIndex == 1) &&
2576             (usc->element[elemIdx].m_stereoConfigIndex != 1)) {
2577           return ErrorStatus = TRANSPORTDEC_PARSE_ERROR;
2578         }
2579         if (cb == NULL) {
2580           return ErrorStatus;
2581         }
2582         {
2583           MP4_ELEMENT_ID el_type =
2584               (usc->element[elemIdx].m_stereoConfigIndex == 1 ||
2585                usc->element[elemIdx].m_stereoConfigIndex == 2)
2586                   ? ID_SCE
2587                   : ID_CPE;
2588           if (cb->cbSbr == NULL) return ErrorStatus = TRANSPORTDEC_UNKOWN_ERROR;
2589           if (cb->cbSbr(cb->cbSbrData, hBs, asc->m_samplingFrequency,
2590                         asc->m_extensionSamplingFrequency,
2591                         asc->m_samplesPerFrame, asc->m_aot, el_type, elemIdx,
2592                         usc->element[elemIdx].m_harmonicSBR,
2593                         usc->element[elemIdx].m_stereoConfigIndex,
2594                         asc->configMode, &asc->SbrConfigChanged, 1)) {
2595             return ErrorStatus = TRANSPORTDEC_PARSE_ERROR;
2596           }
2597         }
2598         /*usc->element[elemIdx].m_stereoConfigIndex =*/FDKreadBits(hBs, 2);
2599         if (usc->element[elemIdx].m_stereoConfigIndex > 0) {
2600           if (cb->cbSsc != NULL) {
2601             int samplesPerFrame = asc->m_samplesPerFrame;
2602 
2603             if (usc->m_sbrRatioIndex == 1) samplesPerFrame <<= 2;
2604             if (usc->m_sbrRatioIndex == 2)
2605               samplesPerFrame = (samplesPerFrame * 8) / 3;
2606             if (usc->m_sbrRatioIndex == 3) samplesPerFrame <<= 1;
2607 
2608             ErrorStatus = (TRANSPORTDEC_ERROR)cb->cbSsc(
2609                 cb->cbSscData, hBs,
2610                 AOT_DRM_USAC, /* syntax differs from MPEG Mps212Config() */
2611                 asc->m_extensionSamplingFrequency, samplesPerFrame,
2612                 1, /* only downmix channels (residual channels are not
2613                       counted) */
2614                 usc->element[elemIdx].m_stereoConfigIndex,
2615                 usc->m_coreSbrFrameLengthIndex, 0, /* don't know the length */
2616                 asc->configMode, &asc->SacConfigChanged);
2617           } else {
2618             /* ErrorStatus = TRANSPORTDEC_UNSUPPORTED_FORMAT; */
2619           }
2620         }
2621       }
2622       break;
2623     default:
2624       return TRANSPORTDEC_PARSE_ERROR;
2625   }
2626 
2627   return ErrorStatus;
2628 }
2629 
Drm_xHEAACStaticConfig(CSAudioSpecificConfig * asc,HANDLE_FDK_BITSTREAM bs,int audioMode,CSTpCallBacks * cb)2630 TRANSPORTDEC_ERROR Drm_xHEAACStaticConfig(
2631     CSAudioSpecificConfig *asc, HANDLE_FDK_BITSTREAM bs, int audioMode,
2632     CSTpCallBacks *cb /* use cb == NULL to signal config check only mode */
2633 ) {
2634   int coreSbrFrameLengthIndexDrm = FDKreadBits(bs, 2);
2635   if (UsacConfig_SetCoreSbrFrameLengthIndex(
2636           asc, coreSbrFrameLengthIndexDrm + 1) != TRANSPORTDEC_OK) {
2637     return TRANSPORTDEC_PARSE_ERROR;
2638   }
2639 
2640   asc->m_channelConfiguration = (audioMode) ? 2 : 1;
2641 
2642   if (Drm_xHEAACDecoderConfig(asc, bs, audioMode, cb) != TRANSPORTDEC_OK) {
2643     return TRANSPORTDEC_PARSE_ERROR;
2644   }
2645 
2646   return TRANSPORTDEC_OK;
2647 }
2648 
2649 /* Mapping of DRM audio sampling rate field to MPEG usacSamplingFrequencyIndex
2650  */
2651 const UCHAR mapSr2MPEGIdx[8] = {
2652     0x1b, /*  9.6 kHz */
2653     0x09, /* 12.0 kHz */
2654     0x08, /* 16.0 kHz */
2655     0x17, /* 19.2 kHz */
2656     0x06, /* 24.0 kHz */
2657     0x05, /* 32.0 kHz */
2658     0x12, /* 38.4 kHz */
2659     0x03  /* 48.0 kHz */
2660 };
2661 
DrmRawSdcAudioConfig_Parse(CSAudioSpecificConfig * self,HANDLE_FDK_BITSTREAM bs,CSTpCallBacks * cb,UCHAR configMode,UCHAR configChanged)2662 TRANSPORTDEC_ERROR DrmRawSdcAudioConfig_Parse(
2663     CSAudioSpecificConfig *self, HANDLE_FDK_BITSTREAM bs,
2664     CSTpCallBacks *cb, /* use cb == NULL to signal config check only mode */
2665     UCHAR configMode, UCHAR configChanged) {
2666   TRANSPORTDEC_ERROR ErrorStatus = TRANSPORTDEC_OK;
2667 
2668   AudioSpecificConfig_Init(self);
2669 
2670   if ((INT)FDKgetValidBits(bs) < 16) {
2671     ErrorStatus = TRANSPORTDEC_PARSE_ERROR;
2672     goto bail;
2673   } else {
2674     /* DRM - Audio information data entity - type 9
2675        - Short Id            2 bits (not part of the config buffer)
2676        - Stream Id           2 bits (not part of the config buffer)
2677        - audio coding        2 bits
2678        - SBR flag            1 bit
2679        - audio mode          2 bits
2680        - audio sampling rate 3 bits
2681        - text flag           1 bit
2682        - enhancement flag    1 bit
2683        - coder field         5 bits
2684        - rfa                 1 bit  */
2685 
2686     int audioCoding, audioMode, cSamplingFreq, coderField, sfIdx, sbrFlag;
2687 
2688     self->configMode = configMode;
2689     self->AacConfigChanged = configChanged;
2690     self->SbrConfigChanged = configChanged;
2691     self->SacConfigChanged = configChanged;
2692 
2693     /* Read the SDC field */
2694     audioCoding = FDKreadBits(bs, 2);
2695     sbrFlag = FDKreadBits(bs, 1);
2696     audioMode = FDKreadBits(bs, 2);
2697     cSamplingFreq = FDKreadBits(bs, 3); /* audio sampling rate */
2698 
2699     FDKreadBits(bs, 2); /* Text and enhancement flag */
2700     coderField = FDKreadBits(bs, 5);
2701     FDKreadBits(bs, 1); /* rfa */
2702 
2703     /* Evaluate configuration and fill the ASC */
2704     if (audioCoding == 3) {
2705       sfIdx = (int)mapSr2MPEGIdx[cSamplingFreq];
2706       sbrFlag = 0; /* rfa */
2707     } else {
2708       switch (cSamplingFreq) {
2709         case 0: /*  8 kHz */
2710           sfIdx = 11;
2711           break;
2712         case 1: /* 12 kHz */
2713           sfIdx = 9;
2714           break;
2715         case 2: /* 16 kHz */
2716           sfIdx = 8;
2717           break;
2718         case 3: /* 24 kHz */
2719           sfIdx = 6;
2720           break;
2721         case 5: /* 48 kHz */
2722           sfIdx = 3;
2723           break;
2724         case 4: /* reserved */
2725         case 6: /* reserved */
2726         case 7: /* reserved */
2727         default:
2728           ErrorStatus = TRANSPORTDEC_PARSE_ERROR;
2729           goto bail;
2730       }
2731     }
2732 
2733     self->m_samplingFrequencyIndex = sfIdx;
2734     self->m_samplingFrequency = SamplingRateTable[sfIdx];
2735 
2736     if (sbrFlag) {
2737       UINT i;
2738       int tmp = -1;
2739       self->m_sbrPresentFlag = 1;
2740       self->m_extensionAudioObjectType = AOT_SBR;
2741       self->m_extensionSamplingFrequency = self->m_samplingFrequency << 1;
2742       for (i = 0;
2743            i < (sizeof(SamplingRateTable) / sizeof(SamplingRateTable[0]));
2744            i++) {
2745         if (SamplingRateTable[i] == self->m_extensionSamplingFrequency) {
2746           tmp = i;
2747           break;
2748         }
2749       }
2750       self->m_extensionSamplingFrequencyIndex = tmp;
2751     }
2752 
2753     switch (audioCoding) {
2754       case 0: /* AAC */
2755         if ((coderField >> 2) && (audioMode != 1)) {
2756           self->m_aot = AOT_DRM_SURROUND; /* Set pseudo AOT for Drm Surround */
2757         } else {
2758           self->m_aot = AOT_DRM_AAC; /* Set pseudo AOT for Drm AAC */
2759         }
2760         switch (audioMode) {
2761           case 1: /* parametric stereo */
2762             self->m_psPresentFlag = 1;
2763             FDK_FALLTHROUGH;
2764           case 0: /* mono */
2765             self->m_channelConfiguration = 1;
2766             break;
2767           case 2: /* stereo */
2768             self->m_channelConfiguration = 2;
2769             break;
2770           default:
2771             ErrorStatus = TRANSPORTDEC_PARSE_ERROR;
2772             goto bail;
2773         }
2774         self->m_vcb11Flag = 1;
2775         self->m_hcrFlag = 1;
2776         self->m_samplesPerFrame = 960;
2777         self->m_epConfig = 1;
2778         break;
2779       case 1: /* CELP */
2780         self->m_aot = AOT_ER_CELP;
2781         self->m_channelConfiguration = 1;
2782         break;
2783       case 2: /* HVXC */
2784         self->m_aot = AOT_ER_HVXC;
2785         self->m_channelConfiguration = 1;
2786         break;
2787       case 3: /* xHE-AAC */
2788       {
2789         /* payload is MPEG conform -> no pseudo DRM AOT needed */
2790         self->m_aot = AOT_USAC;
2791       }
2792         switch (audioMode) {
2793           case 0: /* mono */
2794           case 2: /* stereo */
2795             /* codec specific config 8n bits */
2796             ErrorStatus = Drm_xHEAACStaticConfig(self, bs, audioMode, cb);
2797             break;
2798           default:
2799             ErrorStatus = TRANSPORTDEC_PARSE_ERROR;
2800             goto bail;
2801         }
2802         break;
2803       default:
2804         ErrorStatus = TRANSPORTDEC_PARSE_ERROR;
2805         self->m_aot = AOT_NONE;
2806         break;
2807     }
2808 
2809     if (self->m_psPresentFlag && !self->m_sbrPresentFlag) {
2810       ErrorStatus = TRANSPORTDEC_PARSE_ERROR;
2811       goto bail;
2812     }
2813   }
2814 
2815 bail:
2816   return (ErrorStatus);
2817 }
2818