• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* -----------------------------------------------------------------------------
2 Software License for The Fraunhofer FDK AAC Codec Library for Android
3 
4 © Copyright  1995 - 2021 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 /**************************** AAC decoder library ******************************
96 
97    Author(s):   Josef Hoepfl
98 
99    Description:
100 
101 *******************************************************************************/
102 
103 /*!
104   \page default General Overview of the AAC Decoder Implementation
105 
106   The main entry point to decode a AAC frame is CAacDecoder_DecodeFrame(). It
107   handles the different transport multiplexes and bitstream formats supported by
108   this implementation. It extracts the AAC_raw_data_blocks from these bitstreams
109   to further process then in the actual decoding stages.
110 
111   Note: Click on a function of file in the above image to see details about the
112   function. Also note, that this is just an overview of the most important
113   functions and not a complete call graph.
114 
115   <h2>1 Bitstream deformatter</h2>
116   The basic bit stream parser function CChannelElement_Read() is called. It uses
117   other subcalls in order to parse and unpack the bitstreams. Note, that this
118   includes huffmann decoding of the coded spectral data. This operation can be
119   computational significant specifically at higher bitrates. Optimization is
120   likely in CBlock_ReadSpectralData().
121 
122   The bitstream deformatter also includes many bitfield operations. Profiling on
123   the target will determine required optimizations.
124 
125   <h2>2 Actual decoding to retain the time domain output</h2>
126   The basic bitstream deformatter function CChannelElement_Decode() for CPE
127   elements and SCE elements are called. Except for the stereo processing (2.1)
128   which is only used for CPE elements, the function calls for CPE or SCE are
129   similar, except that CPE always processes to independent channels while SCE
130   only processes one channel.
131 
132   Often there is the distinction between long blocks and short blocks. However,
133   computational expensive functions that ususally require optimization are being
134   shared by these two groups,
135 
136   <h3>2.1 Stereo processing for CPE elements</h3>
137   CChannelPairElement_Decode() first calles the joint stereo  tools in
138   stereo.cpp when required.
139 
140   <h3>2.2 Scaling of spectral data</h3>
141   CBlock_ScaleSpectralData().
142 
143   <h3>2.3 Apply additional coding tools</h3>
144   ApplyTools() calles the PNS tools in case of MPEG-4 bitstreams, and TNS
145   filtering CTns_Apply() for MPEG-2 and MPEG-4 bitstreams. The function
146   TnsFilterIIR() which is called by CTns_Apply() (2.3.1) might require some
147   optimization.
148 
149   <h2>3 Frequency-To-Time conversion</h3>
150   The filterbank is called using CBlock_FrequencyToTime() using the MDCT module
151   from the FDK Tools
152 
153 */
154 
155 #include "aacdecoder.h"
156 
157 #include "aac_rom.h"
158 #include "aac_ram.h"
159 #include "channel.h"
160 #include "FDK_audio.h"
161 
162 #include "aacdec_pns.h"
163 
164 #include "sbrdecoder.h"
165 
166 #include "sac_dec_lib.h"
167 
168 #include "aacdec_hcr.h"
169 #include "rvlc.h"
170 
171 #include "usacdec_lpd.h"
172 
173 #include "ac_arith_coder.h"
174 
175 #include "tpdec_lib.h"
176 
177 #include "conceal.h"
178 
179 #include "FDK_crc.h"
180 #define PS_IS_EXPLICITLY_DISABLED(aot, flags) \
181   (((aot) == AOT_DRM_AAC) && !(flags & AC_PS_PRESENT))
182 
183 #define IS_STEREO_SBR(el_id, stereoConfigIndex)            \
184   (((el_id) == ID_USAC_CPE && (stereoConfigIndex) == 0) || \
185    ((el_id) == ID_USAC_CPE && (stereoConfigIndex) == 3))
186 
CAacDecoder_SyncQmfMode(HANDLE_AACDECODER self)187 void CAacDecoder_SyncQmfMode(HANDLE_AACDECODER self) {
188   FDK_ASSERT(
189       !((self->flags[0] & AC_MPS_PRESENT) && (self->flags[0] & AC_PS_PRESENT)));
190 
191   /* Assign user requested mode */
192   self->qmfModeCurr = self->qmfModeUser;
193 
194   if (IS_USAC(self->streamInfo.aot)) {
195     self->qmfModeCurr = MODE_HQ;
196   }
197 
198   if (self->qmfModeCurr == NOT_DEFINED) {
199     if ((IS_LOWDELAY(self->streamInfo.aot) &&
200          (self->flags[0] & AC_MPS_PRESENT)) ||
201         ((self->streamInfo.aacNumChannels == 1) &&
202          ((CAN_DO_PS(self->streamInfo.aot) &&
203            !(self->flags[0] & AC_MPS_PRESENT)) ||
204           (IS_USAC(self->streamInfo.aot))))) {
205       self->qmfModeCurr = MODE_HQ;
206     } else {
207       self->qmfModeCurr = MODE_LP;
208     }
209   }
210 
211   if (self->mpsEnableCurr) {
212     if (IS_LOWDELAY(self->streamInfo.aot) &&
213         (self->qmfModeCurr == MODE_LP)) { /* Overrule user requested QMF mode */
214       self->qmfModeCurr = MODE_HQ;
215     }
216     /* Set and check if MPS decoder allows the current mode */
217     switch (mpegSurroundDecoder_SetParam(
218         (CMpegSurroundDecoder *)self->pMpegSurroundDecoder,
219         SACDEC_PARTIALLY_COMPLEX, self->qmfModeCurr == MODE_LP)) {
220       case MPS_OK:
221         break;
222       case MPS_INVALID_PARAMETER: { /* Only one mode supported. Find out which
223                                        one: */
224         LIB_INFO libInfo[FDK_MODULE_LAST];
225         UINT mpsCaps;
226 
227         FDKinitLibInfo(libInfo);
228         mpegSurroundDecoder_GetLibInfo(libInfo);
229         mpsCaps = FDKlibInfo_getCapabilities(libInfo, FDK_MPSDEC);
230 
231         if (((mpsCaps & CAPF_MPS_LP) && (self->qmfModeCurr == MODE_LP)) ||
232             ((mpsCaps & CAPF_MPS_HQ) &&
233              (self->qmfModeCurr ==
234               MODE_HQ))) { /* MPS decoder does support the requested mode. */
235           break;
236         }
237       }
238         FDK_FALLTHROUGH;
239       default:
240         if (self->qmfModeUser == NOT_DEFINED) {
241           /* Revert in case mpegSurroundDecoder_SetParam() fails. */
242           self->qmfModeCurr =
243               (self->qmfModeCurr == MODE_LP) ? MODE_HQ : MODE_LP;
244         } else {
245           /* in case specific mode was requested we disable MPS and playout the
246            * downmix */
247           self->mpsEnableCurr = 0;
248         }
249     }
250   }
251 
252   /* Set SBR to current QMF mode. Error does not matter. */
253   sbrDecoder_SetParam(self->hSbrDecoder, SBR_QMF_MODE,
254                       (self->qmfModeCurr == MODE_LP));
255   self->psPossible =
256       ((CAN_DO_PS(self->streamInfo.aot) &&
257         !PS_IS_EXPLICITLY_DISABLED(self->streamInfo.aot, self->flags[0]) &&
258         self->streamInfo.aacNumChannels == 1 &&
259         !(self->flags[0] & AC_MPS_PRESENT))) &&
260       self->qmfModeCurr == MODE_HQ;
261   FDK_ASSERT(!((self->flags[0] & AC_MPS_PRESENT) && self->psPossible));
262 }
263 
CAacDecoder_SignalInterruption(HANDLE_AACDECODER self)264 void CAacDecoder_SignalInterruption(HANDLE_AACDECODER self) {
265   if (self->flags[0] & (AC_USAC | AC_RSVD50 | AC_RSV603DA)) {
266     int i;
267 
268     for (i = 0; i < fMin(self->aacChannels, (8)); i++) {
269       if (self->pAacDecoderStaticChannelInfo
270               [i]) { /* number of active channels can be smaller */
271         self->pAacDecoderStaticChannelInfo[i]->hArCo->m_numberLinesPrev = 0;
272       }
273     }
274   }
275 }
276 
277 /*!
278   \brief Calculates the number of element channels
279 
280   \type  channel type
281   \usacStereoConfigIndex  usac stereo config index
282 
283   \return  element channels
284 */
CAacDecoder_GetELChannels(MP4_ELEMENT_ID type,UCHAR usacStereoConfigIndex)285 static int CAacDecoder_GetELChannels(MP4_ELEMENT_ID type,
286                                      UCHAR usacStereoConfigIndex) {
287   int el_channels = 0;
288 
289   switch (type) {
290     case ID_USAC_CPE:
291       if (usacStereoConfigIndex == 1) {
292         el_channels = 1;
293       } else {
294         el_channels = 2;
295       }
296       break;
297     case ID_CPE:
298       el_channels = 2;
299       break;
300     case ID_USAC_SCE:
301     case ID_USAC_LFE:
302     case ID_SCE:
303     case ID_LFE:
304       el_channels = 1;
305       break;
306     default:
307       el_channels = 0;
308       break;
309   }
310 
311   return el_channels;
312 }
313 
314 /*!
315   \brief Reset ancillary data struct. Call before parsing a new frame.
316 
317   \ancData Pointer to ancillary data structure
318 
319   \return  Error code
320 */
CAacDecoder_AncDataReset(CAncData * ancData)321 static AAC_DECODER_ERROR CAacDecoder_AncDataReset(CAncData *ancData) {
322   int i;
323   for (i = 0; i < 8; i++) {
324     ancData->offset[i] = 0;
325   }
326   ancData->nrElements = 0;
327 
328   return AAC_DEC_OK;
329 }
330 
331 /*!
332   \brief Initialize ancillary buffer
333 
334   \ancData Pointer to ancillary data structure
335   \buffer Pointer to (external) anc data buffer
336   \size Size of the buffer pointed on by buffer in bytes
337 
338   \return  Error code
339 */
CAacDecoder_AncDataInit(CAncData * ancData,unsigned char * buffer,int size)340 AAC_DECODER_ERROR CAacDecoder_AncDataInit(CAncData *ancData,
341                                           unsigned char *buffer, int size) {
342   if (size >= 0) {
343     ancData->buffer = buffer;
344     ancData->bufferSize = size;
345 
346     CAacDecoder_AncDataReset(ancData);
347 
348     return AAC_DEC_OK;
349   }
350 
351   return AAC_DEC_ANC_DATA_ERROR;
352 }
353 
354 /*!
355   \brief Get one ancillary data element
356 
357   \ancData Pointer to ancillary data structure
358   \index Index of the anc data element to get
359   \ptr Pointer to a buffer receiving a pointer to the requested anc data element
360   \size Pointer to a buffer receiving the length of the requested anc data
361   element in bytes
362 
363   \return  Error code
364 */
CAacDecoder_AncDataGet(CAncData * ancData,int index,unsigned char ** ptr,int * size)365 AAC_DECODER_ERROR CAacDecoder_AncDataGet(CAncData *ancData, int index,
366                                          unsigned char **ptr, int *size) {
367   AAC_DECODER_ERROR error = AAC_DEC_OK;
368 
369   *ptr = NULL;
370   *size = 0;
371 
372   if (index >= 0 && index < 8 - 1 && index < ancData->nrElements) {
373     *ptr = &ancData->buffer[ancData->offset[index]];
374     *size = ancData->offset[index + 1] - ancData->offset[index];
375   }
376 
377   return error;
378 }
379 
380 /*!
381   \brief Parse ancillary data
382 
383   \ancData Pointer to ancillary data structure
384   \hBs Handle to FDK bitstream
385   \ancBytes Length of ancillary data to read from the bitstream
386 
387   \return  Error code
388 */
CAacDecoder_AncDataParse(CAncData * ancData,HANDLE_FDK_BITSTREAM hBs,const int ancBytes)389 static AAC_DECODER_ERROR CAacDecoder_AncDataParse(CAncData *ancData,
390                                                   HANDLE_FDK_BITSTREAM hBs,
391                                                   const int ancBytes) {
392   AAC_DECODER_ERROR error = AAC_DEC_OK;
393   int readBytes = 0;
394 
395   if (ancData->buffer != NULL) {
396     if (ancBytes > 0) {
397       /* write ancillary data to external buffer */
398       int offset = ancData->offset[ancData->nrElements];
399 
400       if ((offset + ancBytes) > ancData->bufferSize) {
401         error = AAC_DEC_TOO_SMALL_ANC_BUFFER;
402       } else if (ancData->nrElements >= 8 - 1) {
403         error = AAC_DEC_TOO_MANY_ANC_ELEMENTS;
404       } else {
405         int i;
406 
407         for (i = 0; i < ancBytes; i++) {
408           ancData->buffer[i + offset] = FDKreadBits(hBs, 8);
409           readBytes++;
410         }
411 
412         ancData->nrElements++;
413         ancData->offset[ancData->nrElements] =
414             ancBytes + ancData->offset[ancData->nrElements - 1];
415       }
416     }
417   }
418 
419   readBytes = ancBytes - readBytes;
420 
421   if (readBytes > 0) {
422     /* skip data */
423     FDKpushFor(hBs, readBytes << 3);
424   }
425 
426   return error;
427 }
428 
429 /*!
430   \brief Read Stream Data Element
431 
432   \bs Bitstream Handle
433 
434   \return  Error code
435 */
CDataStreamElement_Read(HANDLE_AACDECODER self,HANDLE_FDK_BITSTREAM bs,UCHAR * elementInstanceTag,UINT alignmentAnchor)436 static AAC_DECODER_ERROR CDataStreamElement_Read(HANDLE_AACDECODER self,
437                                                  HANDLE_FDK_BITSTREAM bs,
438                                                  UCHAR *elementInstanceTag,
439                                                  UINT alignmentAnchor) {
440   AAC_DECODER_ERROR error = AAC_DEC_OK;
441   UINT dseBits;
442   INT dataStart;
443   int dataByteAlignFlag, count;
444 
445   FDK_ASSERT(self != NULL);
446 
447   int crcReg = transportDec_CrcStartReg(self->hInput, 0);
448 
449   /* Element Instance Tag */
450   *elementInstanceTag = FDKreadBits(bs, 4);
451   /* Data Byte Align Flag */
452   dataByteAlignFlag = FDKreadBits(bs, 1);
453 
454   count = FDKreadBits(bs, 8);
455 
456   if (count == 255) {
457     count += FDKreadBits(bs, 8); /* EscCount */
458   }
459   dseBits = count * 8;
460 
461   if (dataByteAlignFlag) {
462     FDKbyteAlign(bs, alignmentAnchor);
463   }
464 
465   dataStart = (INT)FDKgetValidBits(bs);
466 
467   error = CAacDecoder_AncDataParse(&self->ancData, bs, count);
468   transportDec_CrcEndReg(self->hInput, crcReg);
469 
470   {
471     /* Move to the beginning of the data chunk */
472     FDKpushBack(bs, dataStart - (INT)FDKgetValidBits(bs));
473 
474     /* Read Anc data if available */
475     aacDecoder_drcMarkPayload(self->hDrcInfo, bs, DVB_DRC_ANC_DATA);
476   }
477 
478   {
479     PCMDMX_ERROR dmxErr = PCMDMX_OK;
480 
481     /* Move to the beginning of the data chunk */
482     FDKpushBack(bs, dataStart - (INT)FDKgetValidBits(bs));
483 
484     /* Read DMX meta-data */
485     dmxErr = pcmDmx_Parse(self->hPcmUtils, bs, dseBits, 0 /* not mpeg2 */);
486     if (error == AAC_DEC_OK && dmxErr != PCMDMX_OK) {
487       error = AAC_DEC_UNKNOWN;
488     }
489   }
490 
491   /* Move to the very end of the element. */
492   FDKpushBiDirectional(bs, (INT)FDKgetValidBits(bs) - dataStart + (INT)dseBits);
493 
494   return error;
495 }
496 
findElementInstanceTag(INT elementTag,MP4_ELEMENT_ID elementId,CAacDecoderChannelInfo ** pAacDecoderChannelInfo,INT nChannels,MP4_ELEMENT_ID * pElementIdTab,INT nElements)497 static INT findElementInstanceTag(
498     INT elementTag, MP4_ELEMENT_ID elementId,
499     CAacDecoderChannelInfo **pAacDecoderChannelInfo, INT nChannels,
500     MP4_ELEMENT_ID *pElementIdTab, INT nElements) {
501   int el, chCnt = 0;
502 
503   for (el = 0; el < nElements; el++) {
504     switch (pElementIdTab[el]) {
505       case ID_CPE:
506       case ID_SCE:
507       case ID_LFE:
508         if ((elementTag == pAacDecoderChannelInfo[chCnt]->ElementInstanceTag) &&
509             (elementId == pElementIdTab[el])) {
510           return 1; /* element instance tag found */
511         }
512         chCnt += (pElementIdTab[el] == ID_CPE) ? 2 : 1;
513         break;
514       default:
515         break;
516     }
517     if (chCnt >= nChannels) break;
518     if (pElementIdTab[el] == ID_END) break;
519   }
520 
521   return 0; /* element instance tag not found */
522 }
523 
validateElementInstanceTags(CProgramConfig * pce,CAacDecoderChannelInfo ** pAacDecoderChannelInfo,INT nChannels,MP4_ELEMENT_ID * pElementIdTab,INT nElements)524 static INT validateElementInstanceTags(
525     CProgramConfig *pce, CAacDecoderChannelInfo **pAacDecoderChannelInfo,
526     INT nChannels, MP4_ELEMENT_ID *pElementIdTab, INT nElements) {
527   if (nChannels >= pce->NumChannels) {
528     for (int el = 0; el < pce->NumFrontChannelElements; el++) {
529       if (!findElementInstanceTag(pce->FrontElementTagSelect[el],
530                                   pce->FrontElementIsCpe[el] ? ID_CPE : ID_SCE,
531                                   pAacDecoderChannelInfo, nChannels,
532                                   pElementIdTab, nElements)) {
533         return 0; /* element instance tag not in raw_data_block() */
534       }
535     }
536     for (int el = 0; el < pce->NumSideChannelElements; el++) {
537       if (!findElementInstanceTag(pce->SideElementTagSelect[el],
538                                   pce->SideElementIsCpe[el] ? ID_CPE : ID_SCE,
539                                   pAacDecoderChannelInfo, nChannels,
540                                   pElementIdTab, nElements)) {
541         return 0; /* element instance tag not in raw_data_block() */
542       }
543     }
544     for (int el = 0; el < pce->NumBackChannelElements; el++) {
545       if (!findElementInstanceTag(pce->BackElementTagSelect[el],
546                                   pce->BackElementIsCpe[el] ? ID_CPE : ID_SCE,
547                                   pAacDecoderChannelInfo, nChannels,
548                                   pElementIdTab, nElements)) {
549         return 0; /* element instance tag not in raw_data_block() */
550       }
551     }
552     for (int el = 0; el < pce->NumLfeChannelElements; el++) {
553       if (!findElementInstanceTag(pce->LfeElementTagSelect[el], ID_LFE,
554                                   pAacDecoderChannelInfo, nChannels,
555                                   pElementIdTab, nElements)) {
556         return 0; /* element instance tag not in raw_data_block() */
557       }
558     }
559   } else {
560     return 0; /* too less decoded audio channels */
561   }
562 
563   return 1; /* all element instance tags found in raw_data_block() */
564 }
565 
566 /*!
567   \brief Read Program Config Element
568 
569   \bs Bitstream Handle
570   \pTp Transport decoder handle for CRC handling
571   \pce Pointer to PCE buffer
572   \channelConfig Current channel configuration
573   \alignAnchor Anchor for byte alignment
574 
575   \return  PCE status (-1: fail, 0: no new PCE, 1: PCE updated, 2: PCE updated
576   need re-config).
577 */
CProgramConfigElement_Read(HANDLE_FDK_BITSTREAM bs,HANDLE_TRANSPORTDEC pTp,CProgramConfig * pce,const UINT channelConfig,const UINT alignAnchor)578 static int CProgramConfigElement_Read(HANDLE_FDK_BITSTREAM bs,
579                                       HANDLE_TRANSPORTDEC pTp,
580                                       CProgramConfig *pce,
581                                       const UINT channelConfig,
582                                       const UINT alignAnchor) {
583   int pceStatus = 0;
584   int crcReg;
585 
586   /* read PCE to temporal buffer first */
587   C_ALLOC_SCRATCH_START(tmpPce, CProgramConfig, 1);
588 
589   CProgramConfig_Init(tmpPce);
590 
591   crcReg = transportDec_CrcStartReg(pTp, 0);
592 
593   CProgramConfig_Read(tmpPce, bs, alignAnchor);
594 
595   transportDec_CrcEndReg(pTp, crcReg);
596 
597   if (CProgramConfig_IsValid(tmpPce) && (tmpPce->Profile == 1)) {
598     if (!CProgramConfig_IsValid(pce) && (channelConfig > 0)) {
599       /* Create a standard channel config PCE to compare with */
600       CProgramConfig_GetDefault(pce, channelConfig);
601     }
602 
603     if (CProgramConfig_IsValid(pce)) {
604       /* Compare the new and the old PCE (tags ignored) */
605       switch (CProgramConfig_Compare(pce, tmpPce)) {
606         case 1: /* Channel configuration not changed. Just new metadata. */
607           FDKmemcpy(pce, tmpPce,
608                     sizeof(CProgramConfig)); /* Store the complete PCE */
609           pceStatus = 1; /* New PCE but no change of config */
610           break;
611         case 2:  /* The number of channels are identical but not the config */
612         case -1: /* The channel configuration is completely different */
613           pceStatus = -1; /* Not supported! */
614           break;
615         case 0: /* Nothing to do because PCE matches the old one exactly. */
616         default:
617           /* pceStatus = 0; */
618           break;
619       }
620     }
621   }
622 
623   C_ALLOC_SCRATCH_END(tmpPce, CProgramConfig, 1);
624 
625   return pceStatus;
626 }
627 
628 /*!
629   \brief Prepares crossfade for USAC DASH IPF config change
630 
631   \pTimeData             Pointer to time data
632   \pTimeDataFlush        Pointer to flushed time data
633   \numChannels           Number of channels
634   \frameSize             Size of frame
635   \interleaved           Indicates if time data is interleaved
636 
637   \return  Error code
638 */
CAacDecoder_PrepareCrossFade(const PCM_DEC * pTimeData,PCM_DEC ** pTimeDataFlush,const INT numChannels,const INT frameSize,const INT interleaved)639 LINKSPEC_CPP AAC_DECODER_ERROR CAacDecoder_PrepareCrossFade(
640     const PCM_DEC *pTimeData, PCM_DEC **pTimeDataFlush, const INT numChannels,
641     const INT frameSize, const INT interleaved) {
642   int i, ch, s1, s2;
643   AAC_DECODER_ERROR ErrorStatus;
644 
645   ErrorStatus = AAC_DEC_OK;
646 
647   if (interleaved) {
648     s1 = 1;
649     s2 = numChannels;
650   } else {
651     s1 = frameSize;
652     s2 = 1;
653   }
654 
655   for (ch = 0; ch < numChannels; ch++) {
656     const PCM_DEC *pIn = &pTimeData[ch * s1];
657     for (i = 0; i < TIME_DATA_FLUSH_SIZE; i++) {
658       pTimeDataFlush[ch][i] = *pIn;
659       pIn += s2;
660     }
661   }
662 
663   return ErrorStatus;
664 }
665 
666 /*!
667   \brief Applies crossfade for USAC DASH IPF config change
668 
669   \pTimeData             Pointer to time data
670   \pTimeDataFlush        Pointer to flushed time data
671   \numChannels           Number of channels
672   \frameSize             Size of frame
673   \interleaved           Indicates if time data is interleaved
674 
675   \return  Error code
676 */
CAacDecoder_ApplyCrossFade(PCM_DEC * pTimeData,PCM_DEC ** pTimeDataFlush,const INT numChannels,const INT frameSize,const INT interleaved)677 LINKSPEC_CPP AAC_DECODER_ERROR CAacDecoder_ApplyCrossFade(
678     PCM_DEC *pTimeData, PCM_DEC **pTimeDataFlush, const INT numChannels,
679     const INT frameSize, const INT interleaved) {
680   int i, ch, s1, s2;
681   AAC_DECODER_ERROR ErrorStatus;
682 
683   ErrorStatus = AAC_DEC_OK;
684 
685   if (interleaved) {
686     s1 = 1;
687     s2 = numChannels;
688   } else {
689     s1 = frameSize;
690     s2 = 1;
691   }
692 
693   for (ch = 0; ch < numChannels; ch++) {
694     PCM_DEC *pIn = &pTimeData[ch * s1];
695     for (i = 0; i < TIME_DATA_FLUSH_SIZE; i++) {
696       FIXP_SGL alpha = (FIXP_SGL)i
697                        << (FRACT_BITS - 1 - TIME_DATA_FLUSH_SIZE_SF);
698       FIXP_DBL time = PCM_DEC2FIXP_DBL(*pIn);
699       FIXP_DBL timeFlush = PCM_DEC2FIXP_DBL(pTimeDataFlush[ch][i]);
700 
701       *pIn = FIXP_DBL2PCM_DEC(timeFlush - fMult(timeFlush, alpha) +
702                               fMult(time, alpha));
703       pIn += s2;
704     }
705   }
706 
707   return ErrorStatus;
708 }
709 
710 /*!
711   \brief Parse PreRoll Extension Payload
712 
713   \self             Handle of AAC decoder
714   \numPrerollAU     Number of preRoll AUs
715   \prerollAUOffset  Offset to each preRoll AU
716   \prerollAULength  Length of each preRoll AU
717 
718   \return  Error code
719 */
CAacDecoder_PreRollExtensionPayloadParse(HANDLE_AACDECODER self,UINT * numPrerollAU,UINT * prerollAUOffset,UINT * prerollAULength)720 LINKSPEC_CPP AAC_DECODER_ERROR CAacDecoder_PreRollExtensionPayloadParse(
721     HANDLE_AACDECODER self, UINT *numPrerollAU, UINT *prerollAUOffset,
722     UINT *prerollAULength) {
723   FDK_BITSTREAM bs;
724   HANDLE_FDK_BITSTREAM hBs;
725   AAC_DECODER_ERROR ErrorStatus;
726 
727   INT auStartAnchor;
728   UINT independencyFlag;
729   UINT extPayloadPresentFlag;
730   UINT useDefaultLengthFlag;
731   UINT configLength = 0;
732   UINT preRollPossible = 1;
733   UINT i;
734   UCHAR configChanged = 0;
735   UCHAR config[TP_USAC_MAX_CONFIG_LEN] = {0};
736   UCHAR
737   implicitExplicitCfgDiff = 0; /* in case implicit and explicit config is
738                                   equal preroll AU's should be processed
739                                   after decoder reset */
740 
741   ErrorStatus = AAC_DEC_OK;
742 
743   hBs = transportDec_GetBitstream(self->hInput, 0);
744   bs = *hBs;
745 
746   auStartAnchor = (INT)FDKgetValidBits(hBs);
747   if (auStartAnchor <= 0) {
748     ErrorStatus = AAC_DEC_NOT_ENOUGH_BITS;
749     goto bail;
750   }
751 
752   /* Independency flag */
753   FDKreadBit(hBs);
754 
755   /* Payload present flag of extension ID_EXT_ELE_AUDIOPREROLL must be one */
756   extPayloadPresentFlag = FDKreadBits(hBs, 1);
757   if (!extPayloadPresentFlag) {
758     preRollPossible = 0;
759   }
760 
761   /* Default length flag of extension ID_EXT_ELE_AUDIOPREROLL must be zero */
762   useDefaultLengthFlag = FDKreadBits(hBs, 1);
763   if (useDefaultLengthFlag) {
764     preRollPossible = 0;
765   }
766 
767   if (preRollPossible) { /* extPayloadPresentFlag && !useDefaultLengthFlag */
768     /* Read overall ext payload length, useDefaultLengthFlag must be zero.  */
769     escapedValue(hBs, 8, 16, 0);
770 
771     /* Read RSVD60 Config size */
772     configLength = escapedValue(hBs, 4, 4, 8);
773 
774     /* Avoid decoding pre roll frames if there was no config change and no
775      * config is included in the pre roll ext payload. */
776   }
777 
778   /* If pre roll not possible then exit. */
779   if (preRollPossible == 0) {
780     /* Sanity check: if flushing is switched on, preRollPossible must be 1 */
781     if (self->flushStatus != AACDEC_FLUSH_OFF) {
782       /* Mismatch of current payload and flushing status */
783       self->flushStatus = AACDEC_FLUSH_OFF;
784       ErrorStatus = AAC_DEC_PARSE_ERROR;
785     }
786     goto bail;
787   }
788 
789   if (self->flags[0] & AC_USAC) {
790     if (configLength > 0) {
791       /* DASH IPF USAC Config Change: Read new config and compare with current
792        * config. Apply reconfiguration if config's are different. */
793       for (i = 0; i < configLength; i++) {
794         config[i] = FDKreadBits(hBs, 8);
795       }
796       TRANSPORTDEC_ERROR terr;
797       terr = transportDec_InBandConfig(self->hInput, config, configLength,
798                                        self->buildUpStatus, &configChanged, 0,
799                                        &implicitExplicitCfgDiff);
800       if (terr != TRANSPORTDEC_OK) {
801         ErrorStatus = AAC_DEC_PARSE_ERROR;
802         goto bail;
803       }
804     }
805   }
806 
807   /* For the first frame buildUpStatus is not set and no flushing is performed
808    * but preroll AU's should processed. */
809   /* For USAC there is no idle state. */
810   if ((self->streamInfo.numChannels == 0) && !implicitExplicitCfgDiff &&
811       (self->flags[0] & AC_USAC)) {
812     self->buildUpStatus = AACDEC_USAC_BUILD_UP_ON;
813     /* sanity check: if buildUp status on -> flushing must be off */
814     if (self->flushStatus != AACDEC_FLUSH_OFF) {
815       self->flushStatus = AACDEC_FLUSH_OFF;
816       ErrorStatus = AAC_DEC_PARSE_ERROR;
817       goto bail;
818     }
819   }
820 
821   if (self->flags[0] & AC_USAC) {
822     /* We are interested in preroll AUs if an explicit or an implicit config
823      * change is signalized in other words if the build up status is set. */
824     if (self->buildUpStatus == AACDEC_USAC_BUILD_UP_ON) {
825       UCHAR applyCrossfade = FDKreadBit(hBs);
826       if (applyCrossfade) {
827         self->applyCrossfade |= AACDEC_CROSSFADE_BITMASK_PREROLL;
828       } else {
829         self->applyCrossfade &= ~AACDEC_CROSSFADE_BITMASK_PREROLL;
830       }
831       FDKreadBit(hBs); /* reserved */
832       /* Read num preroll AU's */
833       *numPrerollAU = escapedValue(hBs, 2, 4, 0);
834       /* check limits for USAC */
835       if (*numPrerollAU > AACDEC_MAX_NUM_PREROLL_AU_USAC) {
836         *numPrerollAU = 0;
837         ErrorStatus = AAC_DEC_PARSE_ERROR;
838         goto bail;
839       }
840     }
841   }
842 
843   for (i = 0; i < *numPrerollAU; i++) {
844     /* For every AU get length and offset in the bitstream */
845     prerollAULength[i] = escapedValue(hBs, 16, 16, 0);
846     if (prerollAULength[i] > 0) {
847       prerollAUOffset[i] = auStartAnchor - (INT)FDKgetValidBits(hBs);
848       independencyFlag = FDKreadBit(hBs);
849       if (i == 0 && !independencyFlag) {
850         *numPrerollAU = 0;
851         ErrorStatus = AAC_DEC_PARSE_ERROR;
852         goto bail;
853       }
854       FDKpushFor(hBs, prerollAULength[i] * 8 - 1);
855       self->prerollAULength[i] = (prerollAULength[i] * 8) + prerollAUOffset[i];
856     } else {
857       *numPrerollAU = 0;
858       ErrorStatus = AAC_DEC_PARSE_ERROR; /* Something is wrong */
859       goto bail;
860     }
861   }
862 
863 bail:
864 
865   *hBs = bs;
866 
867   return ErrorStatus;
868 }
869 
870 /*!
871   \brief Parse Extension Payload
872 
873   \self Handle of AAC decoder
874   \count Pointer to bit counter.
875   \previous_element ID of previous element (required by some extension payloads)
876 
877   \return  Error code
878 */
CAacDecoder_ExtPayloadParse(HANDLE_AACDECODER self,HANDLE_FDK_BITSTREAM hBs,int * count,MP4_ELEMENT_ID previous_element,int elIndex,int fIsFillElement)879 static AAC_DECODER_ERROR CAacDecoder_ExtPayloadParse(
880     HANDLE_AACDECODER self, HANDLE_FDK_BITSTREAM hBs, int *count,
881     MP4_ELEMENT_ID previous_element, int elIndex, int fIsFillElement) {
882   AAC_DECODER_ERROR error = AAC_DEC_OK;
883   EXT_PAYLOAD_TYPE extension_type;
884   int bytes = (*count) >> 3;
885   int crcFlag = 0;
886 
887   if (*count < 4) {
888     return AAC_DEC_PARSE_ERROR;
889   } else if ((INT)FDKgetValidBits(hBs) < *count) {
890     return AAC_DEC_DECODE_FRAME_ERROR;
891   }
892 
893   extension_type =
894       (EXT_PAYLOAD_TYPE)FDKreadBits(hBs, 4); /* bs_extension_type */
895   *count -= 4;
896 
897   /* For ELD, the SBR signaling is explicit and parsed in
898      aacDecoder_ParseExplicitMpsAndSbr(), therefore skip SBR if implicit
899      present. */
900   if ((self->flags[0] & AC_ELD) && ((extension_type == EXT_SBR_DATA_CRC) ||
901                                     (extension_type == EXT_SBR_DATA))) {
902     extension_type = EXT_FIL; /* skip sbr data */
903   }
904 
905   switch (extension_type) {
906     case EXT_DYNAMIC_RANGE: {
907       INT readBits =
908           aacDecoder_drcMarkPayload(self->hDrcInfo, hBs, MPEG_DRC_EXT_DATA);
909 
910       if (readBits > *count) { /* Read too much. Something went wrong! */
911         error = AAC_DEC_PARSE_ERROR;
912       }
913       *count -= readBits;
914     } break;
915     case EXT_UNI_DRC: {
916       DRC_DEC_ERROR drcErr = DRC_DEC_OK;
917       DRC_DEC_CODEC_MODE drcDecCodecMode = DRC_DEC_CODEC_MODE_UNDEFINED;
918       INT nBitsRemaining = FDKgetValidBits(hBs);
919       INT readBits;
920 
921       switch (self->streamInfo.aot) {
922         case AOT_AAC_LC:
923         case AOT_SBR:
924         case AOT_PS:
925           drcDecCodecMode = DRC_DEC_MPEG_4_AAC;
926           break;
927         default:
928           error = AAC_DEC_PARSE_ERROR;
929           goto bail;
930       }
931 
932       drcErr = FDK_drcDec_SetCodecMode(self->hUniDrcDecoder, drcDecCodecMode);
933       if (drcErr) {
934         error = AAC_DEC_PARSE_ERROR;
935         goto bail;
936       }
937 
938       drcErr = FDK_drcDec_ReadUniDrc(self->hUniDrcDecoder, hBs);
939       if (drcErr) {
940         error = AAC_DEC_PARSE_ERROR;
941         goto bail;
942       }
943       readBits = (INT)nBitsRemaining - (INT)FDKgetValidBits(hBs);
944       if (readBits > *count) { /* Read too much. Something went wrong! */
945         error = AAC_DEC_PARSE_ERROR;
946       }
947       *count -= readBits;
948       /* Skip any trailing bits */
949       FDKpushFor(hBs, *count);
950       *count = 0;
951     } break;
952     case EXT_LDSAC_DATA:
953     case EXT_SAC_DATA:
954       /* Read MPEG Surround Extension payload */
955       {
956         int err, mpsSampleRate, mpsFrameSize;
957 
958         if (self->flags[0] & AC_PS_PRESENT) {
959           error = AAC_DEC_PARSE_ERROR;
960           goto bail;
961         }
962 
963         /* Handle SBR dual rate case */
964         if (self->streamInfo.extSamplingRate != 0) {
965           mpsSampleRate = self->streamInfo.extSamplingRate;
966           mpsFrameSize = self->streamInfo.aacSamplesPerFrame *
967                          (self->streamInfo.extSamplingRate /
968                           self->streamInfo.aacSampleRate);
969         } else {
970           mpsSampleRate = self->streamInfo.aacSampleRate;
971           mpsFrameSize = self->streamInfo.aacSamplesPerFrame;
972         }
973         /* Setting of internal MPS state; may be reset in
974            CAacDecoder_SyncQmfMode if decoder is unable to decode with user
975            defined qmfMode */
976         if (!(self->flags[0] & (AC_USAC | AC_RSVD50 | AC_ELD))) {
977           self->mpsEnableCurr = self->mpsEnableUser;
978         }
979         if (self->mpsEnableCurr) {
980           if (!self->qmfDomain.globalConf.qmfDomainExplicitConfig) {
981             /* if not done yet, allocate full MPEG Surround decoder instance */
982             if (mpegSurroundDecoder_IsFullMpegSurroundDecoderInstanceAvailable(
983                     (CMpegSurroundDecoder *)self->pMpegSurroundDecoder) ==
984                 SAC_INSTANCE_NOT_FULL_AVAILABLE) {
985               if (mpegSurroundDecoder_Open(
986                       (CMpegSurroundDecoder **)&self->pMpegSurroundDecoder, -1,
987                       &self->qmfDomain)) {
988                 return AAC_DEC_OUT_OF_MEMORY;
989               }
990             }
991           }
992           err = mpegSurroundDecoder_Parse(
993               (CMpegSurroundDecoder *)self->pMpegSurroundDecoder, hBs, count,
994               self->streamInfo.aot, mpsSampleRate, mpsFrameSize,
995               self->flags[0] & AC_INDEP);
996           if (err == MPS_OK) {
997             self->flags[0] |= AC_MPS_PRESENT;
998           } else {
999             error = AAC_DEC_PARSE_ERROR;
1000           }
1001         }
1002         /* Skip any trailing bytes */
1003         FDKpushFor(hBs, *count);
1004         *count = 0;
1005       }
1006       break;
1007 
1008     case EXT_SBR_DATA_CRC:
1009       crcFlag = 1;
1010       FDK_FALLTHROUGH;
1011     case EXT_SBR_DATA:
1012       if (IS_CHANNEL_ELEMENT(previous_element)) {
1013         SBR_ERROR sbrError;
1014         UCHAR configMode = 0;
1015         UCHAR configChanged = 0;
1016 
1017         CAacDecoder_SyncQmfMode(self);
1018 
1019         configMode |= AC_CM_ALLOC_MEM;
1020 
1021         sbrError = sbrDecoder_InitElement(
1022             self->hSbrDecoder, self->streamInfo.aacSampleRate,
1023             self->streamInfo.extSamplingRate,
1024             self->streamInfo.aacSamplesPerFrame, self->streamInfo.aot,
1025             previous_element, elIndex,
1026             2, /* Signalize that harmonicSBR shall be ignored in the config
1027                   change detection */
1028             0, configMode, &configChanged, self->downscaleFactor);
1029 
1030         if (sbrError == SBRDEC_OK) {
1031           sbrError = sbrDecoder_Parse(self->hSbrDecoder, hBs,
1032                                       self->pDrmBsBuffer, self->drmBsBufferSize,
1033                                       count, *count, crcFlag, previous_element,
1034                                       elIndex, self->flags[0], self->elFlags);
1035           /* Enable SBR for implicit SBR signalling but only if no severe error
1036            * happend. */
1037           if ((sbrError == SBRDEC_OK) || (sbrError == SBRDEC_PARSE_ERROR)) {
1038             self->sbrEnabled = 1;
1039           }
1040         } else {
1041           /* Do not try to apply SBR because initializing the element failed. */
1042           self->sbrEnabled = 0;
1043         }
1044         /* Citation from ISO/IEC 14496-3 chapter 4.5.2.1.5.2
1045         Fill elements containing an extension_payload() with an extension_type
1046         of EXT_SBR_DATA or EXT_SBR_DATA_CRC shall not contain any other
1047         extension_payload of any other extension_type.
1048         */
1049         if (fIsFillElement) {
1050           FDKpushBiDirectional(hBs, *count);
1051           *count = 0;
1052         } else {
1053           /* If this is not a fill element with a known length, we are screwed
1054            * and further parsing makes no sense. */
1055           if (sbrError != SBRDEC_OK) {
1056             self->frameOK = 0;
1057           }
1058         }
1059       } else {
1060         error = AAC_DEC_PARSE_ERROR;
1061       }
1062       break;
1063 
1064     case EXT_FILL_DATA: {
1065       int temp;
1066 
1067       temp = FDKreadBits(hBs, 4);
1068       bytes--;
1069       if (temp != 0) {
1070         error = AAC_DEC_PARSE_ERROR;
1071         break;
1072       }
1073       while (bytes > 0) {
1074         temp = FDKreadBits(hBs, 8);
1075         bytes--;
1076         if (temp != 0xa5) {
1077           error = AAC_DEC_PARSE_ERROR;
1078           break;
1079         }
1080       }
1081       *count = bytes << 3;
1082     } break;
1083 
1084     case EXT_DATA_ELEMENT: {
1085       int dataElementVersion;
1086 
1087       dataElementVersion = FDKreadBits(hBs, 4);
1088       *count -= 4;
1089       if (dataElementVersion == 0) /* ANC_DATA */
1090       {
1091         int temp, dataElementLength = 0;
1092         do {
1093           temp = FDKreadBits(hBs, 8);
1094           *count -= 8;
1095           dataElementLength += temp;
1096         } while (temp == 255);
1097 
1098         CAacDecoder_AncDataParse(&self->ancData, hBs, dataElementLength);
1099         *count -= (dataElementLength << 3);
1100       } else {
1101         /* align = 0 */
1102         error = AAC_DEC_PARSE_ERROR;
1103         goto bail;
1104       }
1105     } break;
1106 
1107     case EXT_DATA_LENGTH:
1108       if (!fIsFillElement /* Makes no sens to have an additional length in a
1109                              fill ...   */
1110           &&
1111           (self->flags[0] &
1112            AC_ER)) /* ... element because this extension payload type was ... */
1113       { /* ... created to circumvent the missing length in ER-Syntax. */
1114         int bitCnt, len = FDKreadBits(hBs, 4);
1115         *count -= 4;
1116 
1117         if (len == 15) {
1118           int add_len = FDKreadBits(hBs, 8);
1119           *count -= 8;
1120           len += add_len;
1121 
1122           if (add_len == 255) {
1123             len += FDKreadBits(hBs, 16);
1124             *count -= 16;
1125           }
1126         }
1127         len <<= 3;
1128         bitCnt = len;
1129 
1130         if ((EXT_PAYLOAD_TYPE)FDKreadBits(hBs, 4) == EXT_DATA_LENGTH) {
1131           /* Check NOTE 2: The extension_payload() included here must
1132                            not have extension_type == EXT_DATA_LENGTH. */
1133           error = AAC_DEC_PARSE_ERROR;
1134           goto bail;
1135         } else {
1136           /* rewind and call myself again. */
1137           FDKpushBack(hBs, 4);
1138 
1139           error = CAacDecoder_ExtPayloadParse(
1140               self, hBs, &bitCnt, previous_element, elIndex,
1141               1); /* Treat same as fill element */
1142 
1143           *count -= len - bitCnt;
1144         }
1145         /* Note: the fall through in case the if statement above is not taken is
1146          * intentional. */
1147         break;
1148       }
1149       FDK_FALLTHROUGH;
1150 
1151     case EXT_FIL:
1152 
1153     default:
1154       /* align = 4 */
1155       FDKpushFor(hBs, *count);
1156       *count = 0;
1157       break;
1158   }
1159 
1160 bail:
1161   if ((error != AAC_DEC_OK) &&
1162       fIsFillElement) { /* Skip the remaining extension bytes */
1163     FDKpushBiDirectional(hBs, *count);
1164     *count = 0;
1165     /* Patch error code because decoding can go on. */
1166     error = AAC_DEC_OK;
1167     /* Be sure that parsing errors have been stored. */
1168   }
1169   return error;
1170 }
1171 
aacDecoder_ParseExplicitMpsAndSbr(HANDLE_AACDECODER self,HANDLE_FDK_BITSTREAM bs,const MP4_ELEMENT_ID previous_element,const int previous_element_index,const int element_index,const int el_cnt[])1172 static AAC_DECODER_ERROR aacDecoder_ParseExplicitMpsAndSbr(
1173     HANDLE_AACDECODER self, HANDLE_FDK_BITSTREAM bs,
1174     const MP4_ELEMENT_ID previous_element, const int previous_element_index,
1175     const int element_index, const int el_cnt[]) {
1176   AAC_DECODER_ERROR ErrorStatus = AAC_DEC_OK;
1177   INT bitCnt = 0;
1178 
1179   /* get the remaining bits of this frame */
1180   bitCnt = transportDec_GetAuBitsRemaining(self->hInput, 0);
1181 
1182   if ((self->flags[0] & AC_SBR_PRESENT) &&
1183       (self->flags[0] & (AC_USAC | AC_RSVD50 | AC_ELD | AC_DRM))) {
1184     SBR_ERROR err = SBRDEC_OK;
1185     int chElIdx, numChElements = el_cnt[ID_SCE] + el_cnt[ID_CPE] +
1186                                  el_cnt[ID_LFE] + el_cnt[ID_USAC_SCE] +
1187                                  el_cnt[ID_USAC_CPE] + el_cnt[ID_USAC_LFE];
1188     INT bitCntTmp = bitCnt;
1189 
1190     if (self->flags[0] & AC_USAC) {
1191       chElIdx = numChElements - 1;
1192     } else {
1193       chElIdx = 0; /* ELD case */
1194     }
1195 
1196     for (; chElIdx < numChElements; chElIdx += 1) {
1197       MP4_ELEMENT_ID sbrType;
1198       SBR_ERROR errTmp;
1199       if (self->flags[0] & (AC_USAC)) {
1200         FDK_ASSERT((self->elements[element_index] == ID_USAC_SCE) ||
1201                    (self->elements[element_index] == ID_USAC_CPE));
1202         sbrType = IS_STEREO_SBR(self->elements[element_index],
1203                                 self->usacStereoConfigIndex[element_index])
1204                       ? ID_CPE
1205                       : ID_SCE;
1206       } else
1207         sbrType = self->elements[chElIdx];
1208       errTmp = sbrDecoder_Parse(self->hSbrDecoder, bs, self->pDrmBsBuffer,
1209                                 self->drmBsBufferSize, &bitCnt, -1,
1210                                 self->flags[0] & AC_SBRCRC, sbrType, chElIdx,
1211                                 self->flags[0], self->elFlags);
1212       if (errTmp != SBRDEC_OK) {
1213         err = errTmp;
1214         bitCntTmp = bitCnt;
1215         bitCnt = 0;
1216       }
1217     }
1218     switch (err) {
1219       case SBRDEC_PARSE_ERROR:
1220         /* Can not go on parsing because we do not
1221             know the length of the SBR extension data. */
1222         FDKpushFor(bs, bitCntTmp);
1223         bitCnt = 0;
1224         break;
1225       case SBRDEC_OK:
1226         self->sbrEnabled = 1;
1227         break;
1228       default:
1229         self->frameOK = 0;
1230         break;
1231     }
1232   }
1233 
1234   if ((bitCnt > 0) && (self->flags[0] & (AC_USAC | AC_RSVD50))) {
1235     if ((self->flags[0] & AC_MPS_PRESENT) ||
1236         (self->elFlags[element_index] & AC_EL_USAC_MPS212)) {
1237       int err;
1238 
1239       err = mpegSurroundDecoder_ParseNoHeader(
1240           (CMpegSurroundDecoder *)self->pMpegSurroundDecoder, bs, &bitCnt,
1241           self->flags[0] & AC_INDEP);
1242       if (err != MPS_OK) {
1243         self->frameOK = 0;
1244         ErrorStatus = AAC_DEC_PARSE_ERROR;
1245       }
1246     }
1247   }
1248 
1249   if (self->flags[0] & AC_DRM) {
1250     if ((bitCnt = (INT)FDKgetValidBits(bs)) != 0) {
1251       FDKpushBiDirectional(bs, bitCnt);
1252     }
1253   }
1254 
1255   if (!(self->flags[0] & (AC_USAC | AC_RSVD50 | AC_DRM))) {
1256     while (bitCnt > 7) {
1257       ErrorStatus = CAacDecoder_ExtPayloadParse(
1258           self, bs, &bitCnt, previous_element, previous_element_index, 0);
1259       if (ErrorStatus != AAC_DEC_OK) {
1260         self->frameOK = 0;
1261         ErrorStatus = AAC_DEC_PARSE_ERROR;
1262         break;
1263       }
1264     }
1265   }
1266   return ErrorStatus;
1267 }
1268 
1269 /*  Stream Configuration and Information.
1270 
1271     This class holds configuration and information data for a stream to be
1272    decoded. It provides the calling application as well as the decoder with
1273    substantial information, e.g. profile, sampling rate, number of channels
1274    found in the bitstream etc.
1275 */
CStreamInfoInit(CStreamInfo * pStreamInfo)1276 static void CStreamInfoInit(CStreamInfo *pStreamInfo) {
1277   pStreamInfo->aacSampleRate = 0;
1278   pStreamInfo->profile = -1;
1279   pStreamInfo->aot = AOT_NONE;
1280 
1281   pStreamInfo->channelConfig = -1;
1282   pStreamInfo->bitRate = 0;
1283   pStreamInfo->aacSamplesPerFrame = 0;
1284 
1285   pStreamInfo->extAot = AOT_NONE;
1286   pStreamInfo->extSamplingRate = 0;
1287 
1288   pStreamInfo->flags = 0;
1289 
1290   pStreamInfo->epConfig = -1; /* default: no ER */
1291 
1292   pStreamInfo->numChannels = 0;
1293   pStreamInfo->sampleRate = 0;
1294   pStreamInfo->frameSize = 0;
1295 
1296   pStreamInfo->outputDelay = 0;
1297 
1298   /* DRC */
1299   pStreamInfo->drcProgRefLev =
1300       -1; /* set program reference level to not indicated */
1301   pStreamInfo->drcPresMode = -1; /* default: presentation mode not indicated */
1302 
1303   pStreamInfo->outputLoudness = -1; /* default: no loudness metadata present */
1304 }
1305 
1306 /*!
1307   \brief Initialization of AacDecoderChannelInfo
1308 
1309   The function initializes the pointers to AacDecoderChannelInfo for each
1310   channel, set the start values for window shape and window sequence of
1311   overlap&add to zero, set the overlap buffer to zero and initializes the
1312   pointers to the window coefficients. \param bsFormat is the format of the AAC
1313   bitstream
1314 
1315   \return  AACDECODER instance
1316 */
CAacDecoder_Open(TRANSPORT_TYPE bsFormat)1317 LINKSPEC_CPP HANDLE_AACDECODER CAacDecoder_Open(
1318     TRANSPORT_TYPE bsFormat) /*!< bitstream format (adif,adts,loas,...). */
1319 {
1320   HANDLE_AACDECODER self;
1321 
1322   self = GetAacDecoder();
1323   if (self == NULL) {
1324     goto bail;
1325   }
1326 
1327   FDK_QmfDomain_ClearRequested(&self->qmfDomain.globalConf);
1328 
1329   /* Assign channel mapping info arrays (doing so removes dependency of settings
1330    * header in API header). */
1331   self->streamInfo.pChannelIndices = self->channelIndices;
1332   self->streamInfo.pChannelType = self->channelType;
1333   self->downscaleFactor = 1;
1334   self->downscaleFactorInBS = 1;
1335 
1336   /* initialize anc data */
1337   CAacDecoder_AncDataInit(&self->ancData, NULL, 0);
1338 
1339   /* initialize stream info */
1340   CStreamInfoInit(&self->streamInfo);
1341 
1342   /* initialize progam config */
1343   CProgramConfig_Init(&self->pce);
1344 
1345   /* initialize error concealment common data */
1346   CConcealment_InitCommonData(&self->concealCommonData);
1347   self->concealMethodUser = ConcealMethodNone; /* undefined -> auto mode */
1348 
1349   self->hDrcInfo = GetDrcInfo();
1350   if (self->hDrcInfo == NULL) {
1351     goto bail;
1352   }
1353   /* Init common DRC structure */
1354   aacDecoder_drcInit(self->hDrcInfo);
1355   /* Set default frame delay */
1356   aacDecoder_drcSetParam(self->hDrcInfo, DRC_BS_DELAY,
1357                          CConcealment_GetDelay(&self->concealCommonData));
1358   self->workBufferCore1 = (FIXP_DBL *)GetWorkBufferCore1();
1359 
1360   self->workBufferCore2 = GetWorkBufferCore2();
1361   if (self->workBufferCore2 == NULL) goto bail;
1362 
1363   /* When RSVD60 is active use dedicated memory for core decoding */
1364   self->pTimeData2 = GetWorkBufferCore5();
1365   self->timeData2Size = GetRequiredMemWorkBufferCore5();
1366   if (self->pTimeData2 == NULL) {
1367     goto bail;
1368   }
1369 
1370   return self;
1371 
1372 bail:
1373   CAacDecoder_Close(self);
1374 
1375   return NULL;
1376 }
1377 
1378 /* Revert CAacDecoder_Init() */
CAacDecoder_DeInit(HANDLE_AACDECODER self,const int subStreamIndex)1379 static void CAacDecoder_DeInit(HANDLE_AACDECODER self,
1380                                const int subStreamIndex) {
1381   int ch;
1382   int aacChannelOffset = 0, aacChannels = (8);
1383   int numElements = (3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) + 1),
1384       elementOffset = 0;
1385 
1386   if (self == NULL) return;
1387 
1388   {
1389     self->ascChannels[0] = 0;
1390     self->elements[0] = ID_END;
1391   }
1392 
1393   for (ch = aacChannelOffset; ch < aacChannelOffset + aacChannels; ch++) {
1394     if (self->pAacDecoderChannelInfo[ch] != NULL) {
1395       if (self->pAacDecoderChannelInfo[ch]->pComStaticData != NULL) {
1396         if (self->pAacDecoderChannelInfo[ch]
1397                 ->pComStaticData->pWorkBufferCore1 != NULL) {
1398           if (ch == aacChannelOffset) {
1399             FreeWorkBufferCore1(&self->pAacDecoderChannelInfo[ch]
1400                                      ->pComStaticData->pWorkBufferCore1);
1401           }
1402         }
1403         if (self->pAacDecoderChannelInfo[ch]
1404                 ->pComStaticData->cplxPredictionData != NULL) {
1405           FreeCplxPredictionData(&self->pAacDecoderChannelInfo[ch]
1406                                       ->pComStaticData->cplxPredictionData);
1407         }
1408         /* Avoid double free of linked pComStaticData in case of CPE by settings
1409          * pointer to NULL. */
1410         if (ch < (8) - 1) {
1411           if ((self->pAacDecoderChannelInfo[ch + 1] != NULL) &&
1412               (self->pAacDecoderChannelInfo[ch + 1]->pComStaticData ==
1413                self->pAacDecoderChannelInfo[ch]->pComStaticData)) {
1414             self->pAacDecoderChannelInfo[ch + 1]->pComStaticData = NULL;
1415           }
1416         }
1417         FDKfree(self->pAacDecoderChannelInfo[ch]->pComStaticData);
1418         self->pAacDecoderChannelInfo[ch]->pComStaticData = NULL;
1419       }
1420       if (self->pAacDecoderChannelInfo[ch]->pComData != NULL) {
1421         /* Avoid double free of linked pComData in case of CPE by settings
1422          * pointer to NULL. */
1423         if (ch < (8) - 1) {
1424           if ((self->pAacDecoderChannelInfo[ch + 1] != NULL) &&
1425               (self->pAacDecoderChannelInfo[ch + 1]->pComData ==
1426                self->pAacDecoderChannelInfo[ch]->pComData)) {
1427             self->pAacDecoderChannelInfo[ch + 1]->pComData = NULL;
1428           }
1429         }
1430         if (ch == aacChannelOffset) {
1431           FreeWorkBufferCore6(
1432               (SCHAR **)&self->pAacDecoderChannelInfo[ch]->pComData);
1433         } else {
1434           FDKafree(self->pAacDecoderChannelInfo[ch]->pComData);
1435         }
1436         self->pAacDecoderChannelInfo[ch]->pComData = NULL;
1437       }
1438     }
1439     if (self->pAacDecoderStaticChannelInfo[ch] != NULL) {
1440       if (self->pAacDecoderStaticChannelInfo[ch]->pOverlapBuffer != NULL) {
1441         FreeOverlapBuffer(
1442             &self->pAacDecoderStaticChannelInfo[ch]->pOverlapBuffer);
1443       }
1444       if (self->pAacDecoderStaticChannelInfo[ch]->hArCo != NULL) {
1445         CArco_Destroy(self->pAacDecoderStaticChannelInfo[ch]->hArCo);
1446       }
1447       FreeAacDecoderStaticChannelInfo(&self->pAacDecoderStaticChannelInfo[ch]);
1448     }
1449     if (self->pAacDecoderChannelInfo[ch] != NULL) {
1450       FreeAacDecoderChannelInfo(&self->pAacDecoderChannelInfo[ch]);
1451     }
1452   }
1453 
1454   {
1455     int el;
1456     for (el = elementOffset; el < elementOffset + numElements; el++) {
1457       if (self->cpeStaticData[el] != NULL) {
1458         FreeCpePersistentData(&self->cpeStaticData[el]);
1459       }
1460     }
1461   }
1462 
1463   FDK_Delay_Destroy(&self->usacResidualDelay);
1464 
1465   self->aacChannels = 0;
1466   self->streamInfo.aacSampleRate = 0;
1467   self->streamInfo.sampleRate = 0;
1468   /* This samplerate value is checked for configuration change, not the others
1469    * above. */
1470   self->samplingRateInfo[subStreamIndex].samplingRate = 0;
1471 }
1472 
1473 /*!
1474  * \brief CAacDecoder_AcceptFlags Accept flags and element flags
1475  *
1476  * \param self          [o]   handle to AACDECODER structure
1477  * \param asc           [i]   handle to ASC structure
1478  * \param flags         [i]   flags
1479  * \param elFlags       [i]   pointer to element flags
1480  * \param streamIndex   [i]   stream index
1481  * \param elementOffset [i]   element offset
1482  *
1483  * \return void
1484  */
CAacDecoder_AcceptFlags(HANDLE_AACDECODER self,const CSAudioSpecificConfig * asc,UINT flags,UINT * elFlags,int streamIndex,int elementOffset)1485 static void CAacDecoder_AcceptFlags(HANDLE_AACDECODER self,
1486                                     const CSAudioSpecificConfig *asc,
1487                                     UINT flags, UINT *elFlags, int streamIndex,
1488                                     int elementOffset) {
1489   FDKmemcpy(self->elFlags, elFlags, sizeof(self->elFlags));
1490 
1491   self->flags[streamIndex] = flags;
1492 }
1493 
1494 /*!
1495  * \brief CAacDecoder_CtrlCFGChange Set config change parameters.
1496  *
1497  * \param self           [i]   handle to AACDECODER structure
1498  * \param flushStatus    [i]   flush status: on|off
1499  * \param flushCnt       [i]   flush frame counter
1500  * \param buildUpStatus  [i]   build up status: on|off
1501  * \param buildUpCnt     [i]   build up frame counter
1502  *
1503  * \return error
1504  */
CAacDecoder_CtrlCFGChange(HANDLE_AACDECODER self,UCHAR flushStatus,SCHAR flushCnt,UCHAR buildUpStatus,SCHAR buildUpCnt)1505 LINKSPEC_CPP AAC_DECODER_ERROR CAacDecoder_CtrlCFGChange(HANDLE_AACDECODER self,
1506                                                          UCHAR flushStatus,
1507                                                          SCHAR flushCnt,
1508                                                          UCHAR buildUpStatus,
1509                                                          SCHAR buildUpCnt) {
1510   AAC_DECODER_ERROR err = AAC_DEC_OK;
1511 
1512   self->flushStatus = flushStatus;
1513   self->flushCnt = flushCnt;
1514   self->buildUpStatus = buildUpStatus;
1515   self->buildUpCnt = buildUpCnt;
1516 
1517   return (err);
1518 }
1519 
1520 /*!
1521  * \brief CAacDecoder_FreeMem Free config dependent AAC memory.
1522  *
1523  * \param self       [i]   handle to AACDECODER structure
1524  *
1525  * \return error
1526  */
CAacDecoder_FreeMem(HANDLE_AACDECODER self,const int subStreamIndex)1527 LINKSPEC_CPP AAC_DECODER_ERROR CAacDecoder_FreeMem(HANDLE_AACDECODER self,
1528                                                    const int subStreamIndex) {
1529   AAC_DECODER_ERROR err = AAC_DEC_OK;
1530 
1531   CAacDecoder_DeInit(self, subStreamIndex);
1532 
1533   return (err);
1534 }
1535 
1536 /* Destroy aac decoder */
CAacDecoder_Close(HANDLE_AACDECODER self)1537 LINKSPEC_CPP void CAacDecoder_Close(HANDLE_AACDECODER self) {
1538   if (self == NULL) return;
1539 
1540   CAacDecoder_DeInit(self, 0);
1541 
1542   {
1543     int ch;
1544     for (ch = 0; ch < (8); ch++) {
1545       if (self->pTimeDataFlush[ch] != NULL) {
1546         FreeTimeDataFlush(&self->pTimeDataFlush[ch]);
1547       }
1548     }
1549   }
1550 
1551   if (self->hDrcInfo) {
1552     FreeDrcInfo(&self->hDrcInfo);
1553   }
1554 
1555   if (self->workBufferCore1 != NULL) {
1556     FreeWorkBufferCore1((CWorkBufferCore1 **)&self->workBufferCore1);
1557   }
1558 
1559   /* Free WorkBufferCore2 */
1560   if (self->workBufferCore2 != NULL) {
1561     FreeWorkBufferCore2(&self->workBufferCore2);
1562   }
1563   if (self->pTimeData2 != NULL) {
1564     FreeWorkBufferCore5(&self->pTimeData2);
1565   }
1566 
1567   FDK_QmfDomain_Close(&self->qmfDomain);
1568 
1569   FreeAacDecoder(&self);
1570 }
1571 
1572 /*!
1573   \brief Initialization of decoder instance
1574 
1575   The function initializes the decoder.
1576 
1577   \return  error status: 0 for success, <>0 for unsupported configurations
1578 */
1579 LINKSPEC_CPP AAC_DECODER_ERROR
CAacDecoder_Init(HANDLE_AACDECODER self,const CSAudioSpecificConfig * asc,UCHAR configMode,UCHAR * configChanged)1580 CAacDecoder_Init(HANDLE_AACDECODER self, const CSAudioSpecificConfig *asc,
1581                  UCHAR configMode, UCHAR *configChanged) {
1582   AAC_DECODER_ERROR err = AAC_DEC_OK;
1583   INT ascChannels, ascChanged = 0;
1584   AACDEC_RENDER_MODE initRenderMode = AACDEC_RENDER_INVALID;
1585   SCHAR usacStereoConfigIndex = -1;
1586   int usacResidualDelayCompSamples = 0;
1587   int elementOffset, aacChannelsOffset, aacChannelsOffsetIdx;
1588   const int streamIndex = 0;
1589   INT flushChannels = 0;
1590 
1591   UINT flags;
1592   /* elFlags[(3*MAX_CHANNELS + (MAX_CHANNELS)/2 + 4 * (MAX_TRACKS) + 1]
1593      where MAX_CHANNELS is (8*2) and MAX_TRACKS is 1 */
1594   UINT elFlags[(3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) + 1)];
1595 
1596   UCHAR sbrEnabled = self->sbrEnabled;
1597   UCHAR sbrEnabledPrev = self->sbrEnabledPrev;
1598   UCHAR mpsEnableCurr = self->mpsEnableCurr;
1599 
1600   if (!self) return AAC_DEC_INVALID_HANDLE;
1601 
1602   UCHAR downscaleFactor = self->downscaleFactor;
1603   UCHAR downscaleFactorInBS = self->downscaleFactorInBS;
1604 
1605   self->aacOutDataHeadroom = (3);
1606 
1607   // set profile and check for supported aot
1608   // leave profile on default (=-1) for all other supported MPEG-4 aot's except
1609   // aot=2 (=AAC-LC)
1610   switch (asc->m_aot) {
1611     case AOT_AAC_LC:
1612       self->streamInfo.profile = 1;
1613       FDK_FALLTHROUGH;
1614     case AOT_ER_AAC_SCAL:
1615       if (asc->m_sc.m_gaSpecificConfig.m_layer > 0) {
1616         /* aac_scalable_extension_element() currently not supported. */
1617         return AAC_DEC_UNSUPPORTED_FORMAT;
1618       }
1619       FDK_FALLTHROUGH;
1620     case AOT_SBR:
1621     case AOT_PS:
1622     case AOT_ER_AAC_LC:
1623     case AOT_ER_AAC_LD:
1624     case AOT_DRM_AAC:
1625     case AOT_DRM_SURROUND:
1626       initRenderMode = AACDEC_RENDER_IMDCT;
1627       break;
1628     case AOT_ER_AAC_ELD:
1629       initRenderMode = AACDEC_RENDER_ELDFB;
1630       break;
1631     case AOT_USAC:
1632       initRenderMode = AACDEC_RENDER_IMDCT;
1633       break;
1634     default:
1635       return AAC_DEC_UNSUPPORTED_AOT;
1636   }
1637 
1638   if (CProgramConfig_IsValid(&self->pce) && (asc->m_channelConfiguration > 0)) {
1639     /* Compare the stored (old) PCE with a default PCE created from the (new)
1640        channel_config (on a temporal buffer) to find out wheter we can keep it
1641        (and its metadata) or not. */
1642     int pceCmpResult;
1643     C_ALLOC_SCRATCH_START(tmpPce, CProgramConfig, 1);
1644 
1645     CProgramConfig_GetDefault(tmpPce, asc->m_channelConfiguration);
1646     pceCmpResult = CProgramConfig_Compare(&self->pce, tmpPce);
1647     if ((pceCmpResult < 0) /* Reset if PCEs are completely different ... */
1648         ||
1649         (pceCmpResult > 1)) { /*            ... or have a different layout. */
1650       CProgramConfig_Init(&self->pce);
1651     } /* Otherwise keep the PCE (and its metadata). */
1652     C_ALLOC_SCRATCH_END(tmpPce, CProgramConfig, 1);
1653   } else {
1654     CProgramConfig_Init(&self->pce);
1655   }
1656 
1657   /* set channels */
1658   switch (asc->m_channelConfiguration) {
1659     case 0:
1660       switch (asc->m_aot) {
1661         case AOT_USAC:
1662           self->chMapIndex = 0;
1663           ascChannels = asc->m_sc.m_usacConfig.m_nUsacChannels;
1664           break;
1665         default:
1666           /* get channels from program config (ASC) */
1667           if (CProgramConfig_IsValid(&asc->m_progrConfigElement)) {
1668             ascChannels = asc->m_progrConfigElement.NumChannels;
1669             if (ascChannels > 0) {
1670               int el_tmp;
1671               /* valid number of channels -> copy program config element (PCE)
1672                * from ASC */
1673               FDKmemcpy(&self->pce, &asc->m_progrConfigElement,
1674                         sizeof(CProgramConfig));
1675               /* Built element table */
1676               el_tmp = CProgramConfig_GetElementTable(
1677                   &asc->m_progrConfigElement, self->elements, (((8)) + (8)),
1678                   &self->chMapIndex);
1679               for (; el_tmp < (3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) + 1);
1680                    el_tmp++) {
1681                 self->elements[el_tmp] = ID_NONE;
1682               }
1683             } else {
1684               return AAC_DEC_UNSUPPORTED_CHANNELCONFIG;
1685             }
1686           } else {
1687             self->chMapIndex = 0;
1688             return AAC_DEC_UNSUPPORTED_CHANNELCONFIG;
1689           }
1690           break;
1691       }
1692       break;
1693     case 1:
1694     case 2:
1695     case 3:
1696     case 4:
1697     case 5:
1698     case 6:
1699       ascChannels = asc->m_channelConfiguration;
1700       break;
1701     case 11:
1702       ascChannels = 7;
1703       break;
1704     case 7:
1705     case 12:
1706     case 14:
1707       ascChannels = 8;
1708       break;
1709     default:
1710       return AAC_DEC_UNSUPPORTED_CHANNELCONFIG;
1711   }
1712 
1713   if (asc->m_aot == AOT_USAC) {
1714     flushChannels = fMin(ascChannels, (8));
1715     INT numChannel;
1716     pcmDmx_GetParam(self->hPcmUtils, MIN_NUMBER_OF_OUTPUT_CHANNELS,
1717                     &numChannel);
1718     flushChannels = fMin(fMax(numChannel, flushChannels), (8));
1719   }
1720 
1721   if (IS_USAC(asc->m_aot)) {
1722     for (int el = 0; el < (INT)asc->m_sc.m_usacConfig.m_usacNumElements; el++) {
1723       /* fix number of core channels aka ascChannels for stereoConfigIndex = 1
1724        * cases */
1725       if (asc->m_sc.m_usacConfig.element[el].m_stereoConfigIndex == 1) {
1726         ascChannels--; /* stereoConfigIndex == 1 stereo cases do actually
1727                           contain only a mono core channel. */
1728       } else if (asc->m_sc.m_usacConfig.element[el].m_stereoConfigIndex == 2) {
1729         /* In this case it is necessary to follow up the DMX signal delay caused
1730            by HBE also with the residual signal (2nd core channel). The SBR
1731            overlap delay is not regarded here, this is handled by the MPS212
1732            implementation.
1733         */
1734         if (asc->m_sc.m_usacConfig.element[el].m_harmonicSBR) {
1735           usacResidualDelayCompSamples += asc->m_samplesPerFrame;
1736         }
1737         if (asc->m_sc.m_usacConfig.m_coreSbrFrameLengthIndex == 4) {
1738           usacResidualDelayCompSamples +=
1739               6 * 16; /* difference between 12 SBR
1740                          overlap slots from SBR and 6
1741                          slots delayed in MPS212 */
1742         }
1743       }
1744     }
1745   }
1746 
1747   aacChannelsOffset = 0;
1748   aacChannelsOffsetIdx = 0;
1749   elementOffset = 0;
1750   if ((ascChannels <= 0) || (ascChannels > (8)) ||
1751       (asc->m_channelConfiguration > AACDEC_MAX_CH_CONF)) {
1752     return AAC_DEC_UNSUPPORTED_CHANNELCONFIG;
1753   }
1754 
1755   /* Set syntax flags */
1756   flags = 0;
1757   { FDKmemclear(elFlags, sizeof(elFlags)); }
1758 
1759   if ((asc->m_channelConfiguration > 0) || IS_USAC(asc->m_aot)) {
1760     if (IS_USAC(asc->m_aot)) {
1761       /* copy pointer to usac config
1762         (this is preliminary since there's an ongoing discussion about storing
1763         the config-part of the bitstream rather than the complete decoded
1764         configuration) */
1765       self->pUsacConfig[streamIndex] = &asc->m_sc.m_usacConfig;
1766 
1767       /* copy list of elements */
1768       if (self->pUsacConfig[streamIndex]->m_usacNumElements >
1769           (3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) + 1)) {
1770         goto bail;
1771       }
1772 
1773       if (self->numUsacElements[streamIndex] !=
1774           asc->m_sc.m_usacConfig.m_usacNumElements) {
1775         ascChanged = 1;
1776       }
1777 
1778       if (configMode & AC_CM_ALLOC_MEM) {
1779         self->numUsacElements[streamIndex] =
1780             asc->m_sc.m_usacConfig.m_usacNumElements;
1781       }
1782 
1783       mpsEnableCurr = 0;
1784       for (int _el = 0;
1785            _el < (int)self->pUsacConfig[streamIndex]->m_usacNumElements;
1786            _el++) {
1787         int el = _el + elementOffset;
1788         if (self->elements[el] !=
1789             self->pUsacConfig[streamIndex]->element[_el].usacElementType) {
1790           ascChanged = 1;
1791         }
1792         if (self->usacStereoConfigIndex[el] !=
1793             asc->m_sc.m_usacConfig.element[_el].m_stereoConfigIndex) {
1794           ascChanged = 1;
1795         }
1796         if (configMode & AC_CM_ALLOC_MEM) {
1797           self->elements[el] =
1798               self->pUsacConfig[streamIndex]->element[_el].usacElementType;
1799           /* for Unified Stereo Coding */
1800           self->usacStereoConfigIndex[el] =
1801               asc->m_sc.m_usacConfig.element[_el].m_stereoConfigIndex;
1802           if (self->elements[el] == ID_USAC_CPE) {
1803             mpsEnableCurr |= self->usacStereoConfigIndex[el] ? 1 : 0;
1804           }
1805         }
1806 
1807         elFlags[el] |= (asc->m_sc.m_usacConfig.element[_el].m_noiseFilling)
1808                            ? AC_EL_USAC_NOISE
1809                            : 0;
1810         elFlags[el] |=
1811             (asc->m_sc.m_usacConfig.element[_el].m_stereoConfigIndex > 0)
1812                 ? AC_EL_USAC_MPS212
1813                 : 0;
1814         elFlags[el] |= (asc->m_sc.m_usacConfig.element[_el].m_interTes)
1815                            ? AC_EL_USAC_ITES
1816                            : 0;
1817         elFlags[el] |=
1818             (asc->m_sc.m_usacConfig.element[_el].m_pvc) ? AC_EL_USAC_PVC : 0;
1819         elFlags[el] |=
1820             (asc->m_sc.m_usacConfig.element[_el].usacElementType == ID_USAC_LFE)
1821                 ? AC_EL_USAC_LFE
1822                 : 0;
1823         elFlags[el] |=
1824             (asc->m_sc.m_usacConfig.element[_el].usacElementType == ID_USAC_LFE)
1825                 ? AC_EL_LFE
1826                 : 0;
1827         if ((asc->m_sc.m_usacConfig.element[_el].usacElementType ==
1828              ID_USAC_CPE) &&
1829             ((self->usacStereoConfigIndex[el] == 0))) {
1830           elFlags[el] |= AC_EL_USAC_CP_POSSIBLE;
1831         }
1832       }
1833 
1834       self->hasAudioPreRoll = 0;
1835       if (self->pUsacConfig[streamIndex]->m_usacNumElements) {
1836         self->hasAudioPreRoll = asc->m_sc.m_usacConfig.element[0]
1837                                     .extElement.usacExtElementHasAudioPreRoll;
1838       }
1839       if (configMode & AC_CM_ALLOC_MEM) {
1840         self->elements[elementOffset +
1841                        self->pUsacConfig[streamIndex]->m_usacNumElements] =
1842             ID_END;
1843       }
1844     } else {
1845       /* Initialize constant mappings for channel config 1-7 */
1846       int i;
1847       for (i = 0; i < AACDEC_CH_ELEMENTS_TAB_SIZE; i++) {
1848         self->elements[i] = elementsTab[asc->m_channelConfiguration - 1][i];
1849       }
1850       for (; i < (3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) + 1); i++) {
1851         self->elements[i] = ID_NONE;
1852       }
1853     }
1854 
1855     {
1856       int ch;
1857 
1858       for (ch = 0; ch < ascChannels; ch++) {
1859         self->chMapping[ch] = ch;
1860       }
1861       for (; ch < (8); ch++) {
1862         self->chMapping[ch] = 255;
1863       }
1864     }
1865 
1866     self->chMapIndex = asc->m_channelConfiguration;
1867   } else {
1868     if (CProgramConfig_IsValid(&asc->m_progrConfigElement)) {
1869       /* Set matrix mixdown infos if available from PCE. */
1870       pcmDmx_SetMatrixMixdownFromPce(
1871           self->hPcmUtils, asc->m_progrConfigElement.MatrixMixdownIndexPresent,
1872           asc->m_progrConfigElement.MatrixMixdownIndex,
1873           asc->m_progrConfigElement.PseudoSurroundEnable);
1874     }
1875   }
1876 
1877   self->streamInfo.channelConfig = asc->m_channelConfiguration;
1878 
1879   if (self->streamInfo.aot != asc->m_aot) {
1880     if (configMode & AC_CM_ALLOC_MEM) {
1881       self->streamInfo.aot = asc->m_aot;
1882     }
1883     ascChanged = 1;
1884   }
1885 
1886   if (asc->m_aot == AOT_ER_AAC_ELD &&
1887       asc->m_sc.m_eldSpecificConfig.m_downscaledSamplingFrequency != 0) {
1888     if (self->samplingRateInfo[0].samplingRate !=
1889             asc->m_sc.m_eldSpecificConfig.m_downscaledSamplingFrequency ||
1890         self->samplingRateInfo[0].samplingRate * self->downscaleFactor !=
1891             asc->m_samplingFrequency) {
1892       /* get downscaledSamplingFrequency from ESC and compute the downscale
1893        * factor */
1894       downscaleFactorInBS =
1895           asc->m_samplingFrequency /
1896           asc->m_sc.m_eldSpecificConfig.m_downscaledSamplingFrequency;
1897       if ((downscaleFactorInBS == 1 || downscaleFactorInBS == 2 ||
1898            (downscaleFactorInBS == 3 &&
1899             asc->m_sc.m_eldSpecificConfig.m_frameLengthFlag) ||
1900            downscaleFactorInBS == 4) &&
1901           ((asc->m_samplingFrequency %
1902             asc->m_sc.m_eldSpecificConfig.m_downscaledSamplingFrequency) ==
1903            0)) {
1904         downscaleFactor = downscaleFactorInBS;
1905       } else {
1906         downscaleFactorInBS = 1;
1907         downscaleFactor = 1;
1908       }
1909     }
1910   } else {
1911     downscaleFactorInBS = 1;
1912     downscaleFactor = 1;
1913   }
1914 
1915   if (self->downscaleFactorInBS != downscaleFactorInBS) {
1916     if (configMode & AC_CM_ALLOC_MEM) {
1917       self->downscaleFactorInBS = downscaleFactorInBS;
1918       self->downscaleFactor = downscaleFactor;
1919     }
1920     ascChanged = 1;
1921   }
1922 
1923   if ((INT)asc->m_samplesPerFrame % downscaleFactor != 0) {
1924     return AAC_DEC_UNSUPPORTED_SAMPLINGRATE; /* frameSize/dsf must be an integer
1925                                                 number */
1926   }
1927 
1928   self->streamInfo.bitRate = 0;
1929 
1930   if (asc->m_aot == AOT_ER_AAC_ELD) {
1931     if (self->useLdQmfTimeAlign !=
1932         asc->m_sc.m_eldSpecificConfig.m_useLdQmfTimeAlign) {
1933       ascChanged = 1;
1934     }
1935     if (configMode & AC_CM_ALLOC_MEM) {
1936       self->useLdQmfTimeAlign =
1937           asc->m_sc.m_eldSpecificConfig.m_useLdQmfTimeAlign;
1938     }
1939     if (sbrEnabled != asc->m_sbrPresentFlag) {
1940       ascChanged = 1;
1941     }
1942   }
1943 
1944   self->streamInfo.extAot = asc->m_extensionAudioObjectType;
1945   if (self->streamInfo.extSamplingRate !=
1946       (INT)asc->m_extensionSamplingFrequency) {
1947     ascChanged = 1;
1948   }
1949   if (configMode & AC_CM_ALLOC_MEM) {
1950     self->streamInfo.extSamplingRate = asc->m_extensionSamplingFrequency;
1951   }
1952   flags |= (asc->m_sbrPresentFlag) ? AC_SBR_PRESENT : 0;
1953   flags |= (asc->m_psPresentFlag) ? AC_PS_PRESENT : 0;
1954   if (asc->m_sbrPresentFlag) {
1955     sbrEnabled = 1;
1956     sbrEnabledPrev = 1;
1957   } else {
1958     sbrEnabled = 0;
1959     sbrEnabledPrev = 0;
1960   }
1961   if (sbrEnabled && asc->m_extensionSamplingFrequency) {
1962     if (downscaleFactor != 1 && (downscaleFactor)&1) {
1963       return AAC_DEC_UNSUPPORTED_SAMPLINGRATE; /* SBR needs an even downscale
1964                                                   factor */
1965     }
1966     if (configMode & AC_CM_ALLOC_MEM) {
1967       self->streamInfo.extSamplingRate =
1968           self->streamInfo.extSamplingRate / self->downscaleFactor;
1969     }
1970   }
1971   if ((asc->m_aot == AOT_AAC_LC) && (asc->m_sbrPresentFlag == 1) &&
1972       (asc->m_extensionSamplingFrequency > (2 * asc->m_samplingFrequency))) {
1973     return AAC_DEC_UNSUPPORTED_SAMPLINGRATE; /* Core decoder supports at most a
1974                                                 1:2 upsampling for HE-AAC and
1975                                                 HE-AACv2 */
1976   }
1977 
1978   /* --------- vcb11 ------------ */
1979   flags |= (asc->m_vcb11Flag) ? AC_ER_VCB11 : 0;
1980 
1981   /* ---------- rvlc ------------ */
1982   flags |= (asc->m_rvlcFlag) ? AC_ER_RVLC : 0;
1983 
1984   /* ----------- hcr ------------ */
1985   flags |= (asc->m_hcrFlag) ? AC_ER_HCR : 0;
1986 
1987   if (asc->m_aot == AOT_ER_AAC_ELD) {
1988     mpsEnableCurr = 0;
1989     flags |= AC_ELD;
1990     flags |= (asc->m_sbrPresentFlag)
1991                  ? AC_SBR_PRESENT
1992                  : 0; /* Need to set the SBR flag for backward-compatibility
1993                                reasons. Even if SBR is not supported. */
1994     flags |= (asc->m_sc.m_eldSpecificConfig.m_sbrCrcFlag) ? AC_SBRCRC : 0;
1995     flags |= (asc->m_sc.m_eldSpecificConfig.m_useLdQmfTimeAlign)
1996                  ? AC_MPS_PRESENT
1997                  : 0;
1998     if (self->mpsApplicable) {
1999       mpsEnableCurr = asc->m_sc.m_eldSpecificConfig.m_useLdQmfTimeAlign;
2000     }
2001   }
2002   flags |= (asc->m_aot == AOT_ER_AAC_LD) ? AC_LD : 0;
2003   flags |= (asc->m_epConfig >= 0) ? AC_ER : 0;
2004 
2005   if (asc->m_aot == AOT_USAC) {
2006     flags |= AC_USAC;
2007     flags |= (asc->m_sc.m_usacConfig.element[0].m_stereoConfigIndex > 0)
2008                  ? AC_MPS_PRESENT
2009                  : 0;
2010   }
2011   if (asc->m_aot == AOT_DRM_AAC) {
2012     flags |= AC_DRM | AC_SBRCRC | AC_SCALABLE;
2013   }
2014   if (asc->m_aot == AOT_DRM_SURROUND) {
2015     flags |= AC_DRM | AC_SBRCRC | AC_SCALABLE | AC_MPS_PRESENT;
2016     FDK_ASSERT(!asc->m_psPresentFlag);
2017   }
2018   if ((asc->m_aot == AOT_AAC_SCAL) || (asc->m_aot == AOT_ER_AAC_SCAL)) {
2019     flags |= AC_SCALABLE;
2020   }
2021 
2022   if ((asc->m_epConfig >= 0) && (asc->m_channelConfiguration <= 0)) {
2023     /* we have to know the number of channels otherwise no decoding is possible
2024      */
2025     return AAC_DEC_UNSUPPORTED_ER_FORMAT;
2026   }
2027 
2028   self->streamInfo.epConfig = asc->m_epConfig;
2029   /* self->hInput->asc.m_epConfig = asc->m_epConfig; */
2030 
2031   if (asc->m_epConfig > 1) return AAC_DEC_UNSUPPORTED_ER_FORMAT;
2032 
2033   /* Check if samplerate changed. */
2034   if ((self->samplingRateInfo[streamIndex].samplingRate !=
2035        asc->m_samplingFrequency) ||
2036       (self->streamInfo.aacSamplesPerFrame !=
2037        (INT)asc->m_samplesPerFrame / downscaleFactor)) {
2038     AAC_DECODER_ERROR error;
2039 
2040     ascChanged = 1;
2041 
2042     if (configMode & AC_CM_ALLOC_MEM) {
2043       /* Update samplerate info. */
2044       error = getSamplingRateInfo(
2045           &self->samplingRateInfo[streamIndex], asc->m_samplesPerFrame,
2046           asc->m_samplingFrequencyIndex, asc->m_samplingFrequency);
2047       if (error != AAC_DEC_OK) {
2048         return error;
2049       }
2050       self->streamInfo.aacSampleRate =
2051           self->samplingRateInfo[0].samplingRate / self->downscaleFactor;
2052       self->streamInfo.aacSamplesPerFrame =
2053           asc->m_samplesPerFrame / self->downscaleFactor;
2054       if (self->streamInfo.aacSampleRate <= 0) {
2055         return AAC_DEC_UNSUPPORTED_SAMPLINGRATE;
2056       }
2057     }
2058   }
2059 
2060   /* Check if amount of channels has changed. */
2061   if (self->ascChannels[streamIndex] != ascChannels) {
2062     ascChanged = 1;
2063   }
2064 
2065   /* detect config change */
2066   if (configMode & AC_CM_DET_CFG_CHANGE) {
2067     if (ascChanged != 0) {
2068       *configChanged = 1;
2069     }
2070 
2071     CAacDecoder_AcceptFlags(self, asc, flags, elFlags, streamIndex,
2072                             elementOffset);
2073 
2074     return err;
2075   }
2076 
2077   /* set AC_USAC_SCFGI3 globally if any usac element uses */
2078   switch (asc->m_aot) {
2079     case AOT_USAC:
2080       if (sbrEnabled) {
2081         for (int _el = 0;
2082              _el < (int)self->pUsacConfig[streamIndex]->m_usacNumElements;
2083              _el++) {
2084           int el = elementOffset + _el;
2085           if (IS_USAC_CHANNEL_ELEMENT(self->elements[el])) {
2086             if (usacStereoConfigIndex < 0) {
2087               usacStereoConfigIndex = self->usacStereoConfigIndex[el];
2088             } else {
2089               if ((usacStereoConfigIndex != self->usacStereoConfigIndex[el]) ||
2090                   (self->usacStereoConfigIndex[el] > 0)) {
2091                 goto bail;
2092               }
2093             }
2094           }
2095         }
2096 
2097         if (usacStereoConfigIndex < 0) {
2098           goto bail;
2099         }
2100 
2101         if (usacStereoConfigIndex == 3) {
2102           flags |= AC_USAC_SCFGI3;
2103         }
2104       }
2105       break;
2106     default:
2107       break;
2108   }
2109 
2110   if (*configChanged) {
2111     /* Set up QMF domain for AOTs with explicit signalling of SBR and or MPS.
2112        This is to be able to play out the first frame alway with the correct
2113        frame size and sampling rate even in case of concealment.
2114     */
2115     switch (asc->m_aot) {
2116       case AOT_USAC:
2117         if (sbrEnabled) {
2118           const UCHAR map_sbrRatio_2_nAnaBands[] = {16, 24, 32};
2119 
2120           FDK_ASSERT(asc->m_sc.m_usacConfig.m_sbrRatioIndex > 0);
2121           FDK_ASSERT(streamIndex == 0);
2122 
2123           self->qmfDomain.globalConf.nInputChannels_requested = ascChannels;
2124           self->qmfDomain.globalConf.nOutputChannels_requested =
2125               (usacStereoConfigIndex == 1) ? 2 : ascChannels;
2126           self->qmfDomain.globalConf.flags_requested = 0;
2127           self->qmfDomain.globalConf.nBandsAnalysis_requested =
2128               map_sbrRatio_2_nAnaBands[asc->m_sc.m_usacConfig.m_sbrRatioIndex -
2129                                        1];
2130           self->qmfDomain.globalConf.nBandsSynthesis_requested = 64;
2131           self->qmfDomain.globalConf.nQmfTimeSlots_requested =
2132               (asc->m_sc.m_usacConfig.m_sbrRatioIndex == 1) ? 64 : 32;
2133           self->qmfDomain.globalConf.nQmfOvTimeSlots_requested =
2134               (asc->m_sc.m_usacConfig.m_sbrRatioIndex == 1) ? 12 : 6;
2135           self->qmfDomain.globalConf.nQmfProcBands_requested = 64;
2136           self->qmfDomain.globalConf.nQmfProcChannels_requested = 1;
2137           self->qmfDomain.globalConf.parkChannel =
2138               (usacStereoConfigIndex == 3) ? 1 : 0;
2139           self->qmfDomain.globalConf.parkChannel_requested =
2140               (usacStereoConfigIndex == 3) ? 1 : 0;
2141           self->qmfDomain.globalConf.qmfDomainExplicitConfig = 1;
2142         }
2143         break;
2144       case AOT_ER_AAC_ELD:
2145         if (mpsEnableCurr &&
2146             asc->m_sc.m_eldSpecificConfig.m_useLdQmfTimeAlign) {
2147           SAC_INPUT_CONFIG sac_interface = (sbrEnabled && self->hSbrDecoder)
2148                                                ? SAC_INTERFACE_QMF
2149                                                : SAC_INTERFACE_TIME;
2150           mpegSurroundDecoder_ConfigureQmfDomain(
2151               (CMpegSurroundDecoder *)self->pMpegSurroundDecoder, sac_interface,
2152               (UINT)self->streamInfo.aacSampleRate, asc->m_aot);
2153           self->qmfDomain.globalConf.qmfDomainExplicitConfig = 1;
2154         }
2155         break;
2156       default:
2157         self->qmfDomain.globalConf.qmfDomainExplicitConfig =
2158             0; /* qmfDomain is initialized by SBR and MPS init functions if
2159                   required */
2160         break;
2161     }
2162 
2163     /* Allocate all memory structures for each channel */
2164     {
2165       int ch = aacChannelsOffset;
2166       for (int _ch = 0; _ch < ascChannels; _ch++) {
2167         if (ch >= (8)) {
2168           goto bail;
2169         }
2170         self->pAacDecoderChannelInfo[ch] = GetAacDecoderChannelInfo(ch);
2171         /* This is temporary until the DynamicData is split into two or more
2172            regions! The memory could be reused after completed core decoding. */
2173         if (self->pAacDecoderChannelInfo[ch] == NULL) {
2174           goto bail;
2175         }
2176         ch++;
2177       }
2178 
2179       int chIdx = aacChannelsOffsetIdx;
2180       ch = aacChannelsOffset;
2181       int _numElements;
2182       _numElements = (((8)) + (8));
2183       if (flags & (AC_RSV603DA | AC_USAC)) {
2184         _numElements = (int)asc->m_sc.m_usacConfig.m_usacNumElements;
2185       }
2186       for (int _el = 0; _el < _numElements; _el++) {
2187         int el_channels = 0;
2188         int el = elementOffset + _el;
2189 
2190         if (flags &
2191             (AC_ER | AC_LD | AC_ELD | AC_RSV603DA | AC_USAC | AC_RSVD50)) {
2192           if (ch >= ascChannels) {
2193             break;
2194           }
2195         }
2196 
2197         switch (self->elements[el]) {
2198           case ID_SCE:
2199           case ID_CPE:
2200           case ID_LFE:
2201           case ID_USAC_SCE:
2202           case ID_USAC_CPE:
2203           case ID_USAC_LFE:
2204 
2205             el_channels = CAacDecoder_GetELChannels(
2206                 self->elements[el], self->usacStereoConfigIndex[el]);
2207 
2208             {
2209               self->pAacDecoderChannelInfo[ch]->pComStaticData =
2210                   (CAacDecoderCommonStaticData *)FDKcalloc(
2211                       1, sizeof(CAacDecoderCommonStaticData));
2212               if (self->pAacDecoderChannelInfo[ch]->pComStaticData == NULL) {
2213                 goto bail;
2214               }
2215               if (ch == aacChannelsOffset) {
2216                 self->pAacDecoderChannelInfo[ch]->pComData =
2217                     (CAacDecoderCommonData *)GetWorkBufferCore6();
2218                 self->pAacDecoderChannelInfo[ch]
2219                     ->pComStaticData->pWorkBufferCore1 = GetWorkBufferCore1();
2220               } else {
2221                 self->pAacDecoderChannelInfo[ch]->pComData =
2222                     (CAacDecoderCommonData *)FDKaalloc(
2223                         sizeof(CAacDecoderCommonData), ALIGNMENT_DEFAULT);
2224                 self->pAacDecoderChannelInfo[ch]
2225                     ->pComStaticData->pWorkBufferCore1 =
2226                     self->pAacDecoderChannelInfo[aacChannelsOffset]
2227                         ->pComStaticData->pWorkBufferCore1;
2228               }
2229               if ((self->pAacDecoderChannelInfo[ch]->pComData == NULL) ||
2230                   (self->pAacDecoderChannelInfo[ch]
2231                        ->pComStaticData->pWorkBufferCore1 == NULL)) {
2232                 goto bail;
2233               }
2234               self->pAacDecoderChannelInfo[ch]->pDynData =
2235                   &(self->pAacDecoderChannelInfo[ch]
2236                         ->pComData->pAacDecoderDynamicData[0]);
2237               self->pAacDecoderChannelInfo[ch]->pSpectralCoefficient =
2238                   (SPECTRAL_PTR)&self->workBufferCore2[ch * 1024];
2239 
2240               if (el_channels == 2) {
2241                 if (ch >= (8) - 1) {
2242                   return AAC_DEC_UNSUPPORTED_CHANNELCONFIG;
2243                 }
2244                 self->pAacDecoderChannelInfo[ch + 1]->pComData =
2245                     self->pAacDecoderChannelInfo[ch]->pComData;
2246                 self->pAacDecoderChannelInfo[ch + 1]->pComStaticData =
2247                     self->pAacDecoderChannelInfo[ch]->pComStaticData;
2248                 self->pAacDecoderChannelInfo[ch + 1]
2249                     ->pComStaticData->pWorkBufferCore1 =
2250                     self->pAacDecoderChannelInfo[ch]
2251                         ->pComStaticData->pWorkBufferCore1;
2252                 self->pAacDecoderChannelInfo[ch + 1]->pDynData =
2253                     &(self->pAacDecoderChannelInfo[ch]
2254                           ->pComData->pAacDecoderDynamicData[1]);
2255                 self->pAacDecoderChannelInfo[ch + 1]->pSpectralCoefficient =
2256                     (SPECTRAL_PTR)&self->workBufferCore2[(ch + 1) * 1024];
2257               }
2258 
2259               ch += el_channels;
2260             }
2261             chIdx += el_channels;
2262             break;
2263 
2264           default:
2265             break;
2266         }
2267 
2268         if (self->elements[el] == ID_END) {
2269           break;
2270         }
2271 
2272         el++;
2273       }
2274 
2275       chIdx = aacChannelsOffsetIdx;
2276       ch = aacChannelsOffset;
2277       for (int _ch = 0; _ch < ascChannels; _ch++) {
2278         /* Allocate persistent channel memory */
2279         {
2280           self->pAacDecoderStaticChannelInfo[ch] =
2281               GetAacDecoderStaticChannelInfo(ch);
2282           if (self->pAacDecoderStaticChannelInfo[ch] == NULL) {
2283             goto bail;
2284           }
2285           self->pAacDecoderStaticChannelInfo[ch]->pOverlapBuffer =
2286               GetOverlapBuffer(ch); /* This area size depends on the AOT */
2287           if (self->pAacDecoderStaticChannelInfo[ch]->pOverlapBuffer == NULL) {
2288             goto bail;
2289           }
2290           if (flags & (AC_USAC | AC_RSVD50 | AC_RSV603DA /*|AC_BSAC*/)) {
2291             self->pAacDecoderStaticChannelInfo[ch]->hArCo = CArco_Create();
2292             if (self->pAacDecoderStaticChannelInfo[ch]->hArCo == NULL) {
2293               goto bail;
2294             }
2295           }
2296 
2297           if (!(flags & (AC_USAC | AC_RSV603DA))) {
2298             CPns_UpdateNoiseState(
2299                 &self->pAacDecoderChannelInfo[ch]->data.aac.PnsData,
2300                 &self->pAacDecoderStaticChannelInfo[ch]->pnsCurrentSeed,
2301                 self->pAacDecoderChannelInfo[ch]->pComData->pnsRandomSeed);
2302           }
2303           ch++;
2304         }
2305         chIdx++;
2306       }
2307 
2308       if (flags & AC_USAC) {
2309         for (int _ch = 0; _ch < flushChannels; _ch++) {
2310           ch = aacChannelsOffset + _ch;
2311           if (self->pTimeDataFlush[ch] == NULL) {
2312             self->pTimeDataFlush[ch] = GetTimeDataFlush(ch);
2313             if (self->pTimeDataFlush[ch] == NULL) {
2314               goto bail;
2315             }
2316           }
2317         }
2318       }
2319 
2320       if (flags & (AC_USAC | AC_RSV603DA)) {
2321         int complexStereoPredPossible = 0;
2322         ch = aacChannelsOffset;
2323         chIdx = aacChannelsOffsetIdx;
2324         for (int _el2 = 0; _el2 < (int)asc->m_sc.m_usacConfig.m_usacNumElements;
2325              _el2++) {
2326           int el2 = elementOffset + _el2;
2327           int elCh = 0, ch2;
2328 
2329           if ((self->elements[el2] == ID_USAC_CPE) &&
2330               !(self->usacStereoConfigIndex[el2] == 1)) {
2331             elCh = 2;
2332           } else if (IS_CHANNEL_ELEMENT(self->elements[el2])) {
2333             elCh = 1;
2334           }
2335 
2336           if (elFlags[el2] & AC_EL_USAC_CP_POSSIBLE) {
2337             complexStereoPredPossible = 1;
2338             if (self->cpeStaticData[el2] == NULL) {
2339               self->cpeStaticData[el2] = GetCpePersistentData();
2340               if (self->cpeStaticData[el2] == NULL) {
2341                 goto bail;
2342               }
2343             }
2344           }
2345 
2346           for (ch2 = 0; ch2 < elCh; ch2++) {
2347             /* Hook element specific cpeStaticData into channel specific
2348              * aacDecoderStaticChannelInfo */
2349             self->pAacDecoderStaticChannelInfo[ch]->pCpeStaticData =
2350                 self->cpeStaticData[el2];
2351             if (self->pAacDecoderStaticChannelInfo[ch]->pCpeStaticData !=
2352                 NULL) {
2353               self->pAacDecoderStaticChannelInfo[ch]
2354                   ->pCpeStaticData->jointStereoPersistentData
2355                   .spectralCoeffs[ch2] =
2356                   self->pAacDecoderStaticChannelInfo[ch]
2357                       ->concealmentInfo.spectralCoefficient;
2358               self->pAacDecoderStaticChannelInfo[ch]
2359                   ->pCpeStaticData->jointStereoPersistentData.specScale[ch2] =
2360                   self->pAacDecoderStaticChannelInfo[ch]
2361                       ->concealmentInfo.specScale;
2362               self->pAacDecoderStaticChannelInfo[ch]
2363                   ->pCpeStaticData->jointStereoPersistentData.scratchBuffer =
2364                   (FIXP_DBL *)self->pTimeData2;
2365             }
2366             chIdx++;
2367             ch++;
2368           } /* for each channel in current element */
2369           if (complexStereoPredPossible && (elCh == 2)) {
2370             /* needed once for all channels */
2371             if (self->pAacDecoderChannelInfo[ch - 1]
2372                     ->pComStaticData->cplxPredictionData == NULL) {
2373               self->pAacDecoderChannelInfo[ch - 1]
2374                   ->pComStaticData->cplxPredictionData =
2375                   GetCplxPredictionData();
2376             }
2377             if (self->pAacDecoderChannelInfo[ch - 1]
2378                     ->pComStaticData->cplxPredictionData == NULL) {
2379               goto bail;
2380             }
2381           }
2382           if (elCh > 0) {
2383             self->pAacDecoderStaticChannelInfo[ch - elCh]->nfRandomSeed =
2384                 (ULONG)0x3039;
2385             if (self->elements[el2] == ID_USAC_CPE) {
2386               if (asc->m_sc.m_usacConfig.element[el2].m_stereoConfigIndex !=
2387                   1) {
2388                 self->pAacDecoderStaticChannelInfo[ch - elCh + 1]
2389                     ->nfRandomSeed = (ULONG)0x10932;
2390               }
2391             }
2392           }
2393         } /* for each element */
2394       }
2395 
2396       if (ascChannels != self->aacChannels) {
2397         /* Make allocated channel count persistent in decoder context. */
2398         self->aacChannels = aacChannelsOffset + ch;
2399       }
2400     }
2401 
2402     if (usacResidualDelayCompSamples) {
2403       INT delayErr = FDK_Delay_Create(&self->usacResidualDelay,
2404                                       (USHORT)usacResidualDelayCompSamples, 1);
2405       if (delayErr) {
2406         goto bail;
2407       }
2408     }
2409 
2410     /* Make amount of signalled channels persistent in decoder context. */
2411     self->ascChannels[streamIndex] = ascChannels;
2412     /* Init the previous channel count values. This is required to avoid a
2413        mismatch of memory accesses in the error concealment module and the
2414        allocated channel structures in this function. */
2415     self->aacChannelsPrev = 0;
2416   }
2417 
2418   if (self->pAacDecoderChannelInfo[0] != NULL) {
2419     self->pDrmBsBuffer = self->pAacDecoderChannelInfo[0]
2420                              ->pComStaticData->pWorkBufferCore1->DrmBsBuffer;
2421     self->drmBsBufferSize = DRM_BS_BUFFER_SIZE;
2422   }
2423 
2424   /* Update structures */
2425   if (*configChanged) {
2426     /* Things to be done for each channel, which do not involve allocating
2427        memory. Doing these things only on the channels needed for the current
2428        configuration (ascChannels) could lead to memory access violation later
2429        (error concealment). */
2430     int ch = 0;
2431     int chIdx = 0;
2432     for (int _ch = 0; _ch < self->ascChannels[streamIndex]; _ch++) {
2433       switch (self->streamInfo.aot) {
2434         case AOT_ER_AAC_ELD:
2435         case AOT_ER_AAC_LD:
2436           self->pAacDecoderChannelInfo[ch]->granuleLength =
2437               self->streamInfo.aacSamplesPerFrame;
2438           break;
2439         default:
2440           self->pAacDecoderChannelInfo[ch]->granuleLength =
2441               self->streamInfo.aacSamplesPerFrame / 8;
2442           break;
2443       }
2444       self->pAacDecoderChannelInfo[ch]->renderMode = initRenderMode;
2445 
2446       mdct_init(&self->pAacDecoderStaticChannelInfo[ch]->IMdct,
2447                 self->pAacDecoderStaticChannelInfo[ch]->pOverlapBuffer,
2448                 OverlapBufferSize);
2449 
2450       self->pAacDecoderStaticChannelInfo[ch]->last_core_mode = FD_LONG;
2451       self->pAacDecoderStaticChannelInfo[ch]->last_lpd_mode = 255;
2452 
2453       self->pAacDecoderStaticChannelInfo[ch]->last_tcx_pitch = L_DIV;
2454 
2455       /* Reset DRC control data for this channel */
2456       aacDecoder_drcInitChannelData(
2457           &self->pAacDecoderStaticChannelInfo[ch]->drcData);
2458 
2459       /* Delete mixdown metadata from the past */
2460       pcmDmx_Reset(self->hPcmUtils, PCMDMX_RESET_BS_DATA);
2461 
2462       /* Reset concealment only if ASC changed. Otherwise it will be done with
2463          any config callback. E.g. every time the LATM SMC is present. */
2464       CConcealment_InitChannelData(
2465           &self->pAacDecoderStaticChannelInfo[ch]->concealmentInfo,
2466           &self->concealCommonData, initRenderMode,
2467           self->streamInfo.aacSamplesPerFrame);
2468       ch++;
2469       chIdx++;
2470     }
2471   }
2472 
2473   if (*configChanged) {
2474     int drcDecSampleRate, drcDecFrameSize;
2475 
2476     if (self->streamInfo.extSamplingRate != 0) {
2477       drcDecSampleRate = self->streamInfo.extSamplingRate;
2478       drcDecFrameSize = (self->streamInfo.aacSamplesPerFrame *
2479                          self->streamInfo.extSamplingRate) /
2480                         self->streamInfo.aacSampleRate;
2481     } else {
2482       drcDecSampleRate = self->streamInfo.aacSampleRate;
2483       drcDecFrameSize = self->streamInfo.aacSamplesPerFrame;
2484     }
2485 
2486     if (FDK_drcDec_Init(self->hUniDrcDecoder, drcDecFrameSize, drcDecSampleRate,
2487                         self->aacChannels) != 0)
2488       goto bail;
2489   }
2490 
2491   if (*configChanged) {
2492     if (asc->m_aot == AOT_USAC) {
2493       aacDecoder_drcDisable(self->hDrcInfo);
2494     }
2495   }
2496 
2497   if (asc->m_aot == AOT_USAC) {
2498     pcmLimiter_SetAttack(self->hLimiter, (5));
2499     pcmLimiter_SetThreshold(self->hLimiter, FL2FXCONST_DBL(0.89125094f));
2500   }
2501 
2502   CAacDecoder_AcceptFlags(self, asc, flags, elFlags, streamIndex,
2503                           elementOffset);
2504   self->sbrEnabled = sbrEnabled;
2505   self->sbrEnabledPrev = sbrEnabledPrev;
2506   self->mpsEnableCurr = mpsEnableCurr;
2507 
2508   /* Update externally visible copy of flags */
2509   self->streamInfo.flags = self->flags[0];
2510 
2511   return err;
2512 
2513 bail:
2514   CAacDecoder_DeInit(self, 0);
2515   return AAC_DEC_OUT_OF_MEMORY;
2516 }
2517 
CAacDecoder_DecodeFrame(HANDLE_AACDECODER self,const UINT flags,PCM_DEC * pTimeData,const INT timeDataSize,const int timeDataChannelOffset)2518 LINKSPEC_CPP AAC_DECODER_ERROR CAacDecoder_DecodeFrame(
2519     HANDLE_AACDECODER self, const UINT flags, PCM_DEC *pTimeData,
2520     const INT timeDataSize, const int timeDataChannelOffset) {
2521   AAC_DECODER_ERROR ErrorStatus = AAC_DEC_OK;
2522 
2523   CProgramConfig *pce;
2524   HANDLE_FDK_BITSTREAM bs = transportDec_GetBitstream(self->hInput, 0);
2525 
2526   MP4_ELEMENT_ID type = ID_NONE; /* Current element type */
2527   INT aacChannels = 0; /* Channel counter for channels found in the bitstream */
2528   const int streamIndex = 0; /* index of the current substream */
2529 
2530   INT auStartAnchor = (INT)FDKgetValidBits(
2531       bs); /* AU start bit buffer position for AU byte alignment */
2532 
2533   INT checkSampleRate = self->streamInfo.aacSampleRate;
2534 
2535   INT CConceal_TDFading_Applied[(8)] = {
2536       0}; /* Initialize status of Time Domain fading */
2537 
2538   if (self->aacChannels <= 0) {
2539     return AAC_DEC_UNSUPPORTED_CHANNELCONFIG;
2540   }
2541 
2542   /* Any supported base layer valid AU will require more than 16 bits. */
2543   if ((transportDec_GetAuBitsRemaining(self->hInput, 0) < 15) &&
2544       (flags & (AACDEC_CONCEAL | AACDEC_FLUSH)) == 0) {
2545     self->frameOK = 0;
2546     ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
2547   }
2548 
2549   /* Reset Program Config structure */
2550   pce = &self->pce;
2551   CProgramConfig_Reset(pce);
2552 
2553   CAacDecoder_AncDataReset(&self->ancData);
2554   if (!(flags & (AACDEC_CONCEAL | AACDEC_FLUSH)) &&
2555       !(self->flags[0] & (AC_USAC | AC_RSV603DA))) {
2556     int ch;
2557     if (self->streamInfo.channelConfig == 0) {
2558       /* Init Channel/Element mapping table */
2559       for (ch = 0; ch < (8); ch++) {
2560         self->chMapping[ch] = 255;
2561       }
2562       if (!CProgramConfig_IsValid(pce)) {
2563         int el;
2564         for (el = 0; el < (3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) + 1);
2565              el++) {
2566           self->elements[el] = ID_NONE;
2567         }
2568       }
2569     }
2570   }
2571 
2572   if (self->downscaleFactor > 1 && (self->flags[0] & AC_ELD)) {
2573     self->flags[0] |= AC_ELD_DOWNSCALE;
2574   } else {
2575     self->flags[0] &= ~AC_ELD_DOWNSCALE;
2576   }
2577   /* unsupported dsf (aacSampleRate has not yet been divided by dsf) -> divide
2578    */
2579   if (self->downscaleFactorInBS > 1 &&
2580       (self->flags[0] & AC_ELD_DOWNSCALE) == 0) {
2581     checkSampleRate =
2582         self->streamInfo.aacSampleRate / self->downscaleFactorInBS;
2583   }
2584 
2585   /* Check sampling frequency  */
2586   if (self->streamInfo.aacSampleRate <= 0) {
2587     /* Instance maybe uninitialized! */
2588     return AAC_DEC_UNSUPPORTED_SAMPLINGRATE;
2589   }
2590   switch (checkSampleRate) {
2591     case 96000:
2592     case 88200:
2593     case 64000:
2594     case 16000:
2595     case 12000:
2596     case 11025:
2597     case 8000:
2598     case 7350:
2599     case 48000:
2600     case 44100:
2601     case 32000:
2602     case 24000:
2603     case 22050:
2604       break;
2605     default:
2606       if (!(self->flags[0] & (AC_USAC | AC_RSVD50 | AC_RSV603DA))) {
2607         return AAC_DEC_UNSUPPORTED_SAMPLINGRATE;
2608       }
2609       break;
2610   }
2611 
2612   if (flags & AACDEC_CLRHIST) {
2613     if (!(self->flags[0] & AC_USAC)) {
2614       int ch;
2615       /* Clear history */
2616       for (ch = 0; ch < self->aacChannels; ch++) {
2617         /* Reset concealment */
2618         CConcealment_InitChannelData(
2619             &self->pAacDecoderStaticChannelInfo[ch]->concealmentInfo,
2620             &self->concealCommonData,
2621             self->pAacDecoderChannelInfo[0]->renderMode,
2622             self->streamInfo.aacSamplesPerFrame);
2623         /* Clear overlap-add buffers to avoid clicks. */
2624         FDKmemclear(self->pAacDecoderStaticChannelInfo[ch]->pOverlapBuffer,
2625                     OverlapBufferSize * sizeof(FIXP_DBL));
2626       }
2627       if (self->streamInfo.channelConfig > 0) {
2628         /* Declare the possibly adopted old PCE (with outdated metadata)
2629          * invalid. */
2630         CProgramConfig_Init(pce);
2631       }
2632     }
2633   }
2634 
2635   int pceRead = 0; /* Flag indicating a PCE in the current raw_data_block() */
2636 
2637   INT hdaacDecoded = 0;
2638   MP4_ELEMENT_ID previous_element =
2639       ID_END; /* Last element ID (required for extension payload mapping */
2640   UCHAR previous_element_index = 0; /* Canonical index of last element */
2641   int element_count =
2642       0; /* Element counter for elements found in the bitstream */
2643   int channel_element_count = 0; /* Channel element counter */
2644   MP4_ELEMENT_ID
2645   channel_elements[(3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) +
2646                     1)];     /* Channel elements in bit stream order. */
2647   int el_cnt[ID_LAST] = {0}; /* element counter ( robustness ) */
2648   int element_count_prev_streams =
2649       0; /* Element count of all previous sub streams. */
2650 
2651   while ((type != ID_END) && (!(flags & (AACDEC_CONCEAL | AACDEC_FLUSH))) &&
2652          self->frameOK) {
2653     int el_channels;
2654 
2655     if (!(self->flags[0] &
2656           (AC_USAC | AC_RSVD50 | AC_RSV603DA | AC_ELD | AC_SCALABLE | AC_ER)))
2657       type = (MP4_ELEMENT_ID)FDKreadBits(bs, 3);
2658     else {
2659       if (element_count >= (3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) + 1)) {
2660         self->frameOK = 0;
2661         ErrorStatus = AAC_DEC_PARSE_ERROR;
2662         break;
2663       }
2664       type = self->elements[element_count];
2665     }
2666 
2667     if ((self->flags[streamIndex] & (AC_USAC | AC_RSVD50) &&
2668          element_count == 0) ||
2669         (self->flags[streamIndex] & AC_RSV603DA)) {
2670       self->flags[streamIndex] &= ~AC_INDEP;
2671 
2672       if (FDKreadBit(bs)) {
2673         self->flags[streamIndex] |= AC_INDEP;
2674       }
2675 
2676       int ch = aacChannels;
2677       for (int chIdx = aacChannels; chIdx < self->ascChannels[streamIndex];
2678            chIdx++) {
2679         {
2680           /* Robustness check */
2681           if (ch >= self->aacChannels) {
2682             return AAC_DEC_UNKNOWN;
2683           }
2684 
2685           /* if last frame was broken and this frame is no independent frame,
2686            * correct decoding is impossible we need to trigger concealment */
2687           if ((CConcealment_GetLastFrameOk(
2688                    &self->pAacDecoderStaticChannelInfo[ch]->concealmentInfo,
2689                    1) == 0) &&
2690               !(self->flags[streamIndex] & AC_INDEP)) {
2691             self->frameOK = 0;
2692           }
2693           ch++;
2694         }
2695       }
2696     }
2697 
2698     if ((INT)FDKgetValidBits(bs) < 0) {
2699       self->frameOK = 0;
2700     }
2701 
2702     switch (type) {
2703       case ID_SCE:
2704       case ID_CPE:
2705       case ID_LFE:
2706       case ID_USAC_SCE:
2707       case ID_USAC_CPE:
2708       case ID_USAC_LFE:
2709         if (element_count >= (3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) + 1)) {
2710           self->frameOK = 0;
2711           ErrorStatus = AAC_DEC_PARSE_ERROR;
2712           break;
2713         }
2714 
2715         el_channels = CAacDecoder_GetELChannels(
2716             type, self->usacStereoConfigIndex[element_count]);
2717 
2718         /*
2719           Consistency check
2720          */
2721         {
2722           int totalAscChannels = 0;
2723 
2724           for (int i = 0; i < (1 * 1); i++) {
2725             totalAscChannels += self->ascChannels[i];
2726           }
2727           if ((el_cnt[type] >= (totalAscChannels >> (el_channels - 1))) ||
2728               (aacChannels > (totalAscChannels - el_channels))) {
2729             ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
2730             self->frameOK = 0;
2731             break;
2732           }
2733         }
2734 
2735         if (!(self->flags[streamIndex] & (AC_USAC | AC_RSVD50 | AC_RSV603DA))) {
2736           int ch;
2737           for (ch = 0; ch < el_channels; ch += 1) {
2738             CPns_ResetData(&self->pAacDecoderChannelInfo[aacChannels + ch]
2739                                 ->data.aac.PnsData,
2740                            &self->pAacDecoderChannelInfo[aacChannels + ch]
2741                                 ->pComData->pnsInterChannelData);
2742           }
2743         }
2744 
2745         if (self->frameOK) {
2746           ErrorStatus = CChannelElement_Read(
2747               bs, &self->pAacDecoderChannelInfo[aacChannels],
2748               &self->pAacDecoderStaticChannelInfo[aacChannels],
2749               self->streamInfo.aot, &self->samplingRateInfo[streamIndex],
2750               self->flags[streamIndex], self->elFlags[element_count],
2751               self->streamInfo.aacSamplesPerFrame, el_channels,
2752               self->streamInfo.epConfig, self->hInput);
2753           if (ErrorStatus != AAC_DEC_OK) {
2754             self->frameOK = 0;
2755           }
2756         }
2757 
2758         if (self->frameOK) {
2759           /* Lookup the element and decode it only if it belongs to the current
2760            * program */
2761           if (CProgramConfig_LookupElement(
2762                   pce, self->streamInfo.channelConfig,
2763                   self->pAacDecoderChannelInfo[aacChannels]->ElementInstanceTag,
2764                   aacChannels, self->chMapping, self->channelType,
2765                   self->channelIndices, (8), &previous_element_index,
2766                   self->elements, type)) {
2767             channel_elements[channel_element_count++] = type;
2768             aacChannels += el_channels;
2769           } else {
2770             self->frameOK = 0;
2771           }
2772           /* Create SBR element for SBR for upsampling for LFE elements,
2773              and if SBR was implicitly signaled, because the first frame(s)
2774              may not contain SBR payload (broken encoder, bit errors). */
2775           if (self->frameOK &&
2776               ((self->flags[streamIndex] & AC_SBR_PRESENT) ||
2777                (self->sbrEnabled == 1)) &&
2778               !(self->flags[streamIndex] &
2779                 AC_USAC) /* Is done during explicit config set up */
2780           ) {
2781             SBR_ERROR sbrError;
2782             UCHAR configMode = 0;
2783             UCHAR configChanged = 0;
2784             configMode |= AC_CM_ALLOC_MEM;
2785 
2786             sbrError = sbrDecoder_InitElement(
2787                 self->hSbrDecoder, self->streamInfo.aacSampleRate,
2788                 self->streamInfo.extSamplingRate,
2789                 self->streamInfo.aacSamplesPerFrame, self->streamInfo.aot, type,
2790                 previous_element_index, 2, /* Signalize that harmonicSBR shall
2791                                               be ignored in the config change
2792                                               detection */
2793                 0, configMode, &configChanged, self->downscaleFactor);
2794             if (sbrError != SBRDEC_OK) {
2795               /* Do not try to apply SBR because initializing the element
2796                * failed. */
2797               self->sbrEnabled = 0;
2798             }
2799           }
2800         }
2801 
2802         el_cnt[type]++;
2803         if (self->frameOK && (self->flags[streamIndex] & AC_USAC) &&
2804             (type == ID_USAC_CPE || type == ID_USAC_SCE)) {
2805           ErrorStatus = aacDecoder_ParseExplicitMpsAndSbr(
2806               self, bs, previous_element, previous_element_index, element_count,
2807               el_cnt);
2808           if (ErrorStatus != AAC_DEC_OK) {
2809             self->frameOK = 0;
2810           }
2811         }
2812         break;
2813 
2814       case ID_CCE:
2815         /*
2816           Consistency check
2817         */
2818         if (el_cnt[type] > self->ascChannels[streamIndex]) {
2819           ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
2820           self->frameOK = 0;
2821           break;
2822         }
2823 
2824         if (self->frameOK) {
2825           CAacDecoderCommonData commonData;
2826           CAacDecoderCommonStaticData commonStaticData;
2827           CWorkBufferCore1 workBufferCore1;
2828           commonStaticData.pWorkBufferCore1 = &workBufferCore1;
2829           /* memory for spectral lines temporal on scratch */
2830           C_AALLOC_SCRATCH_START(mdctSpec, FIXP_DBL, 1024);
2831 
2832           /* create dummy channel for CCE parsing on stack */
2833           CAacDecoderChannelInfo tmpAacDecoderChannelInfo,
2834               *pTmpAacDecoderChannelInfo;
2835 
2836           FDKmemclear(mdctSpec, 1024 * sizeof(FIXP_DBL));
2837 
2838           tmpAacDecoderChannelInfo.pDynData = commonData.pAacDecoderDynamicData;
2839           tmpAacDecoderChannelInfo.pComData = &commonData;
2840           tmpAacDecoderChannelInfo.pComStaticData = &commonStaticData;
2841           tmpAacDecoderChannelInfo.pSpectralCoefficient =
2842               (SPECTRAL_PTR)mdctSpec;
2843           /* Assume AAC-LC */
2844           tmpAacDecoderChannelInfo.granuleLength =
2845               self->streamInfo.aacSamplesPerFrame / 8;
2846           /* Reset PNS data. */
2847           CPns_ResetData(
2848               &tmpAacDecoderChannelInfo.data.aac.PnsData,
2849               &tmpAacDecoderChannelInfo.pComData->pnsInterChannelData);
2850           pTmpAacDecoderChannelInfo = &tmpAacDecoderChannelInfo;
2851           /* do CCE parsing */
2852           ErrorStatus = CChannelElement_Read(
2853               bs, &pTmpAacDecoderChannelInfo, NULL, self->streamInfo.aot,
2854               &self->samplingRateInfo[streamIndex], self->flags[streamIndex],
2855               AC_EL_GA_CCE, self->streamInfo.aacSamplesPerFrame, 1,
2856               self->streamInfo.epConfig, self->hInput);
2857 
2858           C_AALLOC_SCRATCH_END(mdctSpec, FIXP_DBL, 1024);
2859 
2860           if (ErrorStatus) {
2861             self->frameOK = 0;
2862           }
2863 
2864           if (self->frameOK) {
2865             /* Lookup the element and decode it only if it belongs to the
2866              * current program */
2867             if (CProgramConfig_LookupElement(
2868                     pce, self->streamInfo.channelConfig,
2869                     pTmpAacDecoderChannelInfo->ElementInstanceTag, 0,
2870                     self->chMapping, self->channelType, self->channelIndices,
2871                     (8), &previous_element_index, self->elements, type)) {
2872               /* decoding of CCE not supported */
2873             } else {
2874               self->frameOK = 0;
2875             }
2876           }
2877         }
2878         el_cnt[type]++;
2879         break;
2880 
2881       case ID_DSE: {
2882         UCHAR element_instance_tag;
2883 
2884         CDataStreamElement_Read(self, bs, &element_instance_tag, auStartAnchor);
2885 
2886         if (!CProgramConfig_LookupElement(
2887                 pce, self->streamInfo.channelConfig, element_instance_tag, 0,
2888                 self->chMapping, self->channelType, self->channelIndices, (8),
2889                 &previous_element_index, self->elements, type)) {
2890           /* most likely an error in bitstream occured */
2891           // self->frameOK = 0;
2892         }
2893       } break;
2894 
2895       case ID_PCE: {
2896         int result = CProgramConfigElement_Read(bs, self->hInput, pce,
2897                                                 self->streamInfo.channelConfig,
2898                                                 auStartAnchor);
2899         if (result < 0) {
2900           /* Something went wrong */
2901           ErrorStatus = AAC_DEC_PARSE_ERROR;
2902           self->frameOK = 0;
2903         } else if (result > 1) {
2904           /* Built element table */
2905           int elIdx = CProgramConfig_GetElementTable(
2906               pce, self->elements, (((8)) + (8)), &self->chMapIndex);
2907           /* Reset the remaining tabs */
2908           for (; elIdx < (3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) + 1);
2909                elIdx++) {
2910             self->elements[elIdx] = ID_NONE;
2911           }
2912           /* Make new number of channel persistent */
2913           self->ascChannels[streamIndex] = pce->NumChannels;
2914           /* If PCE is not first element conceal this frame to avoid
2915            * inconsistencies */
2916           if (element_count != 0) {
2917             self->frameOK = 0;
2918           }
2919         }
2920         pceRead = (result >= 0) ? 1 : 0;
2921       } break;
2922 
2923       case ID_FIL: {
2924         int bitCnt = FDKreadBits(bs, 4); /* bs_count */
2925 
2926         if (bitCnt == 15) {
2927           int esc_count = FDKreadBits(bs, 8); /* bs_esc_count */
2928           bitCnt = esc_count + 14;
2929         }
2930 
2931         /* Convert to bits */
2932         bitCnt <<= 3;
2933 
2934         while (bitCnt > 0) {
2935           ErrorStatus = CAacDecoder_ExtPayloadParse(
2936               self, bs, &bitCnt, previous_element, previous_element_index, 1);
2937           if (ErrorStatus != AAC_DEC_OK) {
2938             self->frameOK = 0;
2939             break;
2940           }
2941         }
2942       } break;
2943 
2944       case ID_EXT:
2945         if (element_count >= (3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) + 1)) {
2946           self->frameOK = 0;
2947           ErrorStatus = AAC_DEC_PARSE_ERROR;
2948           break;
2949         }
2950 
2951         ErrorStatus = aacDecoder_ParseExplicitMpsAndSbr(
2952             self, bs, previous_element, previous_element_index, element_count,
2953             el_cnt);
2954         break;
2955 
2956       case ID_USAC_EXT: {
2957         if ((element_count - element_count_prev_streams) >=
2958             TP_USAC_MAX_ELEMENTS) {
2959           self->frameOK = 0;
2960           ErrorStatus = AAC_DEC_PARSE_ERROR;
2961           break;
2962         }
2963         /* parse extension element payload
2964            q.v. rsv603daExtElement() ISO/IEC DIS 23008-3  Table 30
2965            or   UsacExElement() ISO/IEC FDIS 23003-3:2011(E)  Table 21
2966          */
2967         int usacExtElementPayloadLength;
2968         /* int usacExtElementStart, usacExtElementStop; */
2969 
2970         if (FDKreadBit(bs)) {   /* usacExtElementPresent */
2971           if (FDKreadBit(bs)) { /* usacExtElementUseDefaultLength */
2972             usacExtElementPayloadLength =
2973                 self->pUsacConfig[streamIndex]
2974                     ->element[element_count - element_count_prev_streams]
2975                     .extElement.usacExtElementDefaultLength;
2976           } else {
2977             usacExtElementPayloadLength = FDKreadBits(bs, 8);
2978             if (usacExtElementPayloadLength == (UINT)(1 << 8) - 1) {
2979               UINT valueAdd = FDKreadBits(bs, 16);
2980               usacExtElementPayloadLength += (INT)valueAdd - 2;
2981             }
2982           }
2983           if (usacExtElementPayloadLength > 0) {
2984             int usacExtBitPos;
2985 
2986             if (self->pUsacConfig[streamIndex]
2987                     ->element[element_count - element_count_prev_streams]
2988                     .extElement.usacExtElementPayloadFrag) {
2989               /* usacExtElementStart = */ FDKreadBit(bs);
2990               /* usacExtElementStop = */ FDKreadBit(bs);
2991             } else {
2992               /* usacExtElementStart = 1; */
2993               /* usacExtElementStop = 1; */
2994             }
2995 
2996             usacExtBitPos = (INT)FDKgetValidBits(bs);
2997 
2998             USAC_EXT_ELEMENT_TYPE usacExtElementType =
2999                 self->pUsacConfig[streamIndex]
3000                     ->element[element_count - element_count_prev_streams]
3001                     .extElement.usacExtElementType;
3002 
3003             switch (usacExtElementType) {
3004               case ID_EXT_ELE_UNI_DRC: /* uniDrcGain() */
3005                 if (streamIndex == 0) {
3006                   int drcErr;
3007 
3008                   drcErr = FDK_drcDec_ReadUniDrcGain(self->hUniDrcDecoder, bs);
3009                   if (drcErr != 0) {
3010                     ErrorStatus = AAC_DEC_PARSE_ERROR;
3011                   }
3012                 }
3013                 break;
3014 
3015               default:
3016                 break;
3017             }
3018 
3019             /* Skip any remaining bits of extension payload */
3020             usacExtBitPos = (usacExtElementPayloadLength * 8) -
3021                             (usacExtBitPos - (INT)FDKgetValidBits(bs));
3022             if (usacExtBitPos < 0) {
3023               self->frameOK = 0;
3024               ErrorStatus = AAC_DEC_PARSE_ERROR;
3025             }
3026             FDKpushBiDirectional(bs, usacExtBitPos);
3027           }
3028         }
3029       } break;
3030       case ID_END:
3031       case ID_USAC_END:
3032         break;
3033 
3034       default:
3035         ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
3036         self->frameOK = 0;
3037         break;
3038     }
3039 
3040     previous_element = type;
3041     element_count++;
3042 
3043   } /* while ( (type != ID_END) ... ) */
3044 
3045   if (!(self->flags[streamIndex] &
3046         (AC_USAC | AC_RSVD50 | AC_RSV603DA | AC_BSAC | AC_LD | AC_ELD | AC_ER |
3047          AC_SCALABLE)) &&
3048       (self->streamInfo.channelConfig == 0) && pce->isValid &&
3049       (ErrorStatus == AAC_DEC_OK) && self->frameOK &&
3050       !(flags & (AACDEC_CONCEAL | AACDEC_FLUSH))) {
3051     /* Check whether all PCE listed element instance tags are present in
3052      * raw_data_block() */
3053     if (!validateElementInstanceTags(
3054             &self->pce, self->pAacDecoderChannelInfo, aacChannels,
3055             channel_elements,
3056             fMin(channel_element_count, (int)(sizeof(channel_elements) /
3057                                               sizeof(*channel_elements))))) {
3058       ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
3059       self->frameOK = 0;
3060     }
3061   }
3062 
3063   if (!(flags & (AACDEC_CONCEAL | AACDEC_FLUSH))) {
3064     /* float decoder checks if bitsLeft is in range 0-7; only prerollAUs are
3065      * byteAligned with respect to the first bit */
3066     /* Byte alignment with respect to the first bit of the raw_data_block(). */
3067     if (!(self->flags[streamIndex] & (AC_RSVD50 | AC_USAC)) ||
3068         (self->prerollAULength[self->accessUnit]) /* indicates preroll */
3069     ) {
3070       FDKbyteAlign(bs, auStartAnchor);
3071     }
3072 
3073     /* Check if all bits of the raw_data_block() have been read. */
3074     if (transportDec_GetAuBitsTotal(self->hInput, 0) > 0) {
3075       INT unreadBits = transportDec_GetAuBitsRemaining(self->hInput, 0);
3076       /* for pre-roll frames pre-roll length has to be used instead of total AU
3077        * lenght */
3078       /* unreadBits regarding preroll bounds */
3079       if (self->prerollAULength[self->accessUnit]) {
3080         unreadBits = unreadBits - transportDec_GetAuBitsTotal(self->hInput, 0) +
3081                      (INT)self->prerollAULength[self->accessUnit];
3082       }
3083       if (((self->flags[streamIndex] & (AC_RSVD50 | AC_USAC)) &&
3084            ((unreadBits < 0) || (unreadBits > 7)) &&
3085            !(self->prerollAULength[self->accessUnit])) ||
3086           ((!(self->flags[streamIndex] & (AC_RSVD50 | AC_USAC)) ||
3087             (self->prerollAULength[self->accessUnit])) &&
3088            (unreadBits != 0))) {
3089         if ((((unreadBits < 0) || (unreadBits > 7)) && self->frameOK) &&
3090             ((transportDec_GetFormat(self->hInput) == TT_DRM) &&
3091              (self->flags[streamIndex] & AC_USAC))) {
3092           /* Set frame OK because of fill bits. */
3093           self->frameOK = 1;
3094         } else {
3095           self->frameOK = 0;
3096         }
3097 
3098         /* Do not overwrite current error */
3099         if (ErrorStatus == AAC_DEC_OK && self->frameOK == 0) {
3100           ErrorStatus = AAC_DEC_PARSE_ERROR;
3101         }
3102         /* Always put the bitbuffer at the right position after the current
3103          * Access Unit. */
3104         FDKpushBiDirectional(bs, unreadBits);
3105       }
3106     }
3107 
3108     /* Check the last element. The terminator (ID_END) has to be the last one
3109      * (even if ER syntax is used). */
3110     if (self->frameOK && type != ID_END) {
3111       /* Do not overwrite current error */
3112       if (ErrorStatus == AAC_DEC_OK) {
3113         ErrorStatus = AAC_DEC_PARSE_ERROR;
3114       }
3115       self->frameOK = 0;
3116     }
3117   }
3118 
3119   if (!(flags & (AACDEC_CONCEAL | AACDEC_FLUSH)) && self->frameOK) {
3120     channel_elements[channel_element_count++] = ID_END;
3121   }
3122   element_count = 0;
3123   aacChannels = 0;
3124   type = ID_NONE;
3125   previous_element_index = 0;
3126 
3127   while (type != ID_END &&
3128          element_count < (3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) + 1)) {
3129     int el_channels;
3130 
3131     if ((flags & (AACDEC_CONCEAL | AACDEC_FLUSH)) || !self->frameOK) {
3132       channel_elements[element_count] = self->elements[element_count];
3133       if (channel_elements[element_count] == ID_NONE) {
3134         channel_elements[element_count] = ID_END;
3135       }
3136     }
3137 
3138     if (self->flags[streamIndex] & (AC_USAC | AC_RSV603DA | AC_BSAC)) {
3139       type = self->elements[element_count];
3140     } else {
3141       type = channel_elements[element_count];
3142     }
3143 
3144     if (!(flags & (AACDEC_CONCEAL | AACDEC_FLUSH)) && self->frameOK) {
3145       switch (type) {
3146         case ID_SCE:
3147         case ID_CPE:
3148         case ID_LFE:
3149         case ID_USAC_SCE:
3150         case ID_USAC_CPE:
3151         case ID_USAC_LFE:
3152 
3153           el_channels = CAacDecoder_GetELChannels(
3154               type, self->usacStereoConfigIndex[element_count]);
3155 
3156           if (!hdaacDecoded) {
3157             if (self->pAacDecoderStaticChannelInfo[aacChannels]
3158                     ->pCpeStaticData != NULL) {
3159               self->pAacDecoderStaticChannelInfo[aacChannels]
3160                   ->pCpeStaticData->jointStereoPersistentData.scratchBuffer =
3161                   (FIXP_DBL *)pTimeData;
3162             }
3163             CChannelElement_Decode(
3164                 &self->pAacDecoderChannelInfo[aacChannels],
3165                 &self->pAacDecoderStaticChannelInfo[aacChannels],
3166                 &self->samplingRateInfo[streamIndex], self->flags[streamIndex],
3167                 self->elFlags[element_count], el_channels);
3168           }
3169           aacChannels += el_channels;
3170           break;
3171         case ID_NONE:
3172           type = ID_END;
3173           break;
3174         default:
3175           break;
3176       }
3177     }
3178     element_count++;
3179   }
3180 
3181   /* More AAC channels than specified by the ASC not allowed. */
3182   if ((aacChannels == 0 || aacChannels > self->aacChannels) &&
3183       !(flags & (AACDEC_CONCEAL | AACDEC_FLUSH))) {
3184     /* Do not overwrite current error */
3185     if (ErrorStatus == AAC_DEC_OK) {
3186       ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
3187     }
3188     self->frameOK = 0;
3189     aacChannels = 0;
3190   }
3191 
3192   if (!(flags & (AACDEC_CONCEAL | AACDEC_FLUSH))) {
3193     if (TRANSPORTDEC_OK != transportDec_CrcCheck(self->hInput)) {
3194       ErrorStatus = AAC_DEC_CRC_ERROR;
3195       self->frameOK = 0;
3196     }
3197   }
3198 
3199   /* Ensure that in case of concealment a proper error status is set. */
3200   if ((self->frameOK == 0) && (ErrorStatus == AAC_DEC_OK)) {
3201     ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
3202   }
3203 
3204   if (self->frameOK && (flags & AACDEC_FLUSH)) {
3205     aacChannels = self->aacChannelsPrev;
3206     /* Because the downmix could be active, its necessary to restore the channel
3207      * type and indices. */
3208     FDKmemcpy(self->channelType, self->channelTypePrev,
3209               (8) * sizeof(AUDIO_CHANNEL_TYPE)); /* restore */
3210     FDKmemcpy(self->channelIndices, self->channelIndicesPrev,
3211               (8) * sizeof(UCHAR)); /* restore */
3212     self->sbrEnabled = self->sbrEnabledPrev;
3213   } else {
3214     /* store or restore the number of channels and the corresponding info */
3215     if (self->frameOK && !(flags & AACDEC_CONCEAL)) {
3216       self->aacChannelsPrev = aacChannels; /* store */
3217       FDKmemcpy(self->channelTypePrev, self->channelType,
3218                 (8) * sizeof(AUDIO_CHANNEL_TYPE)); /* store */
3219       FDKmemcpy(self->channelIndicesPrev, self->channelIndices,
3220                 (8) * sizeof(UCHAR)); /* store */
3221       self->sbrEnabledPrev = self->sbrEnabled;
3222     } else {
3223       if (self->aacChannels > 0) {
3224         if ((self->buildUpStatus == AACDEC_RSV60_BUILD_UP_ON) ||
3225             (self->buildUpStatus == AACDEC_RSV60_BUILD_UP_ON_IN_BAND) ||
3226             (self->buildUpStatus == AACDEC_USAC_BUILD_UP_ON)) {
3227           aacChannels = self->aacChannels;
3228           self->aacChannelsPrev = aacChannels; /* store */
3229         } else {
3230           aacChannels = self->aacChannelsPrev; /* restore */
3231         }
3232         FDKmemcpy(self->channelType, self->channelTypePrev,
3233                   (8) * sizeof(AUDIO_CHANNEL_TYPE)); /* restore */
3234         FDKmemcpy(self->channelIndices, self->channelIndicesPrev,
3235                   (8) * sizeof(UCHAR)); /* restore */
3236         self->sbrEnabled = self->sbrEnabledPrev;
3237       }
3238     }
3239   }
3240 
3241   /* Update number of output channels */
3242   self->streamInfo.aacNumChannels = aacChannels;
3243 
3244   /* Ensure consistency of IS_OUTPUT_VALID() macro. */
3245   if (aacChannels == 0) {
3246     ErrorStatus = AAC_DEC_UNKNOWN;
3247   }
3248 
3249   if (pceRead == 1 && CProgramConfig_IsValid(pce)) {
3250     /* Set matrix mixdown infos if available from PCE. */
3251     pcmDmx_SetMatrixMixdownFromPce(
3252         self->hPcmUtils, pce->MatrixMixdownIndexPresent,
3253         pce->MatrixMixdownIndex, pce->PseudoSurroundEnable);
3254     ;
3255   }
3256 
3257   /* If there is no valid data to transfrom into time domain, return. */
3258   if (!IS_OUTPUT_VALID(ErrorStatus)) {
3259     return ErrorStatus;
3260   }
3261 
3262   /* Setup the output channel mapping. The table below shows the three
3263    * possibilities: # | chCfg | PCE | chMapIndex
3264    *  ---+-------+-----+------------------
3265    *   1 |  > 0  |  no | chCfg
3266    *   2 |   0   | yes | cChCfg
3267    *   3 |   0   |  no | aacChannels || 0
3268    *  ---+-------+-----+--------+------------------
3269    *  Where chCfg is the channel configuration index from ASC and cChCfg is a
3270    * corresponding chCfg derived from a given PCE. The variable aacChannels
3271    * represents the number of channel found during bitstream decoding. Due to
3272    * the structure of the mapping table it can only be used for mapping if its
3273    * value is smaller than 7. Otherwise we use the fallback (0) which is a
3274    * simple pass-through. The possibility #3 should appear only with MPEG-2
3275    * (ADTS) streams. This is mode is called "implicit channel mapping".
3276    */
3277   if ((self->streamInfo.channelConfig == 0) && !pce->isValid) {
3278     self->chMapIndex = (aacChannels < 7) ? aacChannels : 0;
3279   }
3280 
3281   /*
3282     Inverse transform
3283   */
3284   {
3285     int c, cIdx;
3286     int mapped, fCopyChMap = 1;
3287     UCHAR drcChMap[(8)];
3288 
3289     if ((self->streamInfo.channelConfig == 0) && CProgramConfig_IsValid(pce)) {
3290       /* ISO/IEC 14496-3 says:
3291            If a PCE is present, the exclude_mask bits correspond to the audio
3292          channels in the SCE, CPE, CCE and LFE syntax elements in the order of
3293          their appearance in the PCE. In the case of a CPE, the first
3294          transmitted mask bit corresponds to the first channel in the CPE, the
3295          second transmitted mask bit to the second channel. In the case of a
3296          CCE, a mask bit is transmitted only if the coupling channel is
3297          specified to be an independently switched coupling channel. Thus we
3298          have to convert the internal channel mapping from "canonical" MPEG to
3299          PCE order: */
3300       UCHAR tmpChMap[(8)];
3301       if (CProgramConfig_GetPceChMap(pce, tmpChMap, (8)) == 0) {
3302         for (c = 0; c < aacChannels; c += 1) {
3303           drcChMap[c] =
3304               (self->chMapping[c] == 255) ? 255 : tmpChMap[self->chMapping[c]];
3305         }
3306         fCopyChMap = 0;
3307       }
3308     }
3309     if (fCopyChMap != 0) {
3310       FDKmemcpy(drcChMap, self->chMapping, (8) * sizeof(UCHAR));
3311     }
3312 
3313     /* deactivate legacy DRC in case uniDrc is active, i.e. uniDrc payload is
3314      * present and one of DRC or Loudness Normalization is switched on */
3315     aacDecoder_drcSetParam(
3316         self->hDrcInfo, UNIDRC_PRECEDENCE,
3317         FDK_drcDec_GetParam(self->hUniDrcDecoder, DRC_DEC_IS_ACTIVE));
3318 
3319     /* Extract DRC control data and map it to channels (without bitstream delay)
3320      */
3321     mapped = aacDecoder_drcProlog(
3322         self->hDrcInfo, bs, self->pAacDecoderStaticChannelInfo,
3323         pce->ElementInstanceTag, drcChMap, aacChannels);
3324     if (mapped > 0) {
3325       if (!(self->flags[streamIndex] & (AC_USAC | AC_RSV603DA))) {
3326         /* If at least one DRC thread has been mapped to a channel there was DRC
3327          * data in the bitstream. */
3328         self->flags[streamIndex] |= AC_DRC_PRESENT;
3329       } else {
3330         ErrorStatus = AAC_DEC_UNSUPPORTED_FORMAT;
3331       }
3332     }
3333     if (self->flags[streamIndex] & (AC_USAC | AC_RSV603DA)) {
3334       aacDecoder_drcDisable(self->hDrcInfo);
3335     }
3336 
3337     /* Create a reverse mapping table */
3338     UCHAR Reverse_chMapping[((8) * 2)];
3339     for (c = 0; c < aacChannels; c++) {
3340       int d;
3341       for (d = 0; d < aacChannels - 1; d++) {
3342         if (self->chMapping[d] == c) {
3343           break;
3344         }
3345       }
3346       Reverse_chMapping[c] = d;
3347     }
3348 
3349     int el;
3350     int el_channels;
3351     c = 0;
3352     cIdx = 0;
3353     el_channels = 0;
3354     for (el = 0; el < element_count; el++) {
3355       int frameOk_butConceal =
3356           0; /* Force frame concealment during mute release active state. */
3357       int concealApplyReturnCode;
3358 
3359       if (self->flags[streamIndex] & (AC_USAC | AC_RSV603DA | AC_BSAC)) {
3360         type = self->elements[el];
3361       } else {
3362         type = channel_elements[el];
3363       }
3364 
3365       {
3366         int nElementChannels;
3367 
3368         nElementChannels =
3369             CAacDecoder_GetELChannels(type, self->usacStereoConfigIndex[el]);
3370 
3371         el_channels += nElementChannels;
3372 
3373         if (nElementChannels == 0) {
3374           continue;
3375         }
3376       }
3377 
3378       int offset;
3379       int elCh = 0;
3380       /* "c" iterates in canonical MPEG channel order */
3381       for (; cIdx < el_channels; c++, cIdx++, elCh++) {
3382         /* Robustness check */
3383         if (c >= aacChannels) {
3384           return AAC_DEC_UNKNOWN;
3385         }
3386 
3387         CAacDecoderChannelInfo *pAacDecoderChannelInfo =
3388             self->pAacDecoderChannelInfo[c];
3389         CAacDecoderStaticChannelInfo *pAacDecoderStaticChannelInfo =
3390             self->pAacDecoderStaticChannelInfo[c];
3391 
3392         /* Setup offset for time buffer traversal. */
3393         {
3394           pAacDecoderStaticChannelInfo =
3395               self->pAacDecoderStaticChannelInfo[Reverse_chMapping[c]];
3396           offset =
3397               FDK_chMapDescr_getMapValue(
3398                   &self->mapDescr, Reverse_chMapping[cIdx], self->chMapIndex) *
3399               timeDataChannelOffset;
3400         }
3401 
3402         if (flags & AACDEC_FLUSH) {
3403           /* Clear pAacDecoderChannelInfo->pSpectralCoefficient because with
3404            * AACDEC_FLUSH set it contains undefined data. */
3405           FDKmemclear(pAacDecoderChannelInfo->pSpectralCoefficient,
3406                       sizeof(FIXP_DBL) * self->streamInfo.aacSamplesPerFrame);
3407         }
3408 
3409         /* if The ics info is not valid and it will be stored and used in the
3410          * following concealment method, mark the frame as erroneous */
3411         {
3412           CIcsInfo *pIcsInfo = &pAacDecoderChannelInfo->icsInfo;
3413           CConcealmentInfo *hConcealmentInfo =
3414               &pAacDecoderStaticChannelInfo->concealmentInfo;
3415           const int mute_release_active =
3416               (self->frameOK && !(flags & AACDEC_CONCEAL)) &&
3417               ((hConcealmentInfo->concealState >= ConcealState_Mute) &&
3418                (hConcealmentInfo->cntValidFrames + 1 <=
3419                 hConcealmentInfo->pConcealParams->numMuteReleaseFrames));
3420           const int icsIsInvalid = (GetScaleFactorBandsTransmitted(pIcsInfo) >
3421                                     GetScaleFactorBandsTotal(pIcsInfo));
3422           const int icsInfoUsedinFadeOut =
3423               !(pAacDecoderChannelInfo->renderMode == AACDEC_RENDER_LPD &&
3424                 pAacDecoderStaticChannelInfo->last_lpd_mode == 0);
3425           if (icsInfoUsedinFadeOut && icsIsInvalid && !mute_release_active) {
3426             self->frameOK = 0;
3427           }
3428         }
3429 
3430         /*
3431           Conceal defective spectral data
3432         */
3433         {
3434           CAacDecoderChannelInfo **ppAacDecoderChannelInfo =
3435               &pAacDecoderChannelInfo;
3436           CAacDecoderStaticChannelInfo **ppAacDecoderStaticChannelInfo =
3437               &pAacDecoderStaticChannelInfo;
3438           {
3439             concealApplyReturnCode = CConcealment_Apply(
3440                 &(*ppAacDecoderStaticChannelInfo)->concealmentInfo,
3441                 *ppAacDecoderChannelInfo, *ppAacDecoderStaticChannelInfo,
3442                 &self->samplingRateInfo[streamIndex],
3443                 self->streamInfo.aacSamplesPerFrame,
3444                 pAacDecoderStaticChannelInfo->last_lpd_mode,
3445                 (self->frameOK && !(flags & AACDEC_CONCEAL)),
3446                 self->flags[streamIndex]);
3447           }
3448         }
3449         if (concealApplyReturnCode == -1) {
3450           frameOk_butConceal = 1;
3451         }
3452 
3453         if (flags & (AACDEC_INTR)) {
3454           /* Reset DRC control data for this channel */
3455           aacDecoder_drcInitChannelData(&pAacDecoderStaticChannelInfo->drcData);
3456         }
3457         if (flags & (AACDEC_CLRHIST)) {
3458           if (!(self->flags[0] & AC_USAC)) {
3459             /* Reset DRC control data for this channel */
3460             aacDecoder_drcInitChannelData(
3461                 &pAacDecoderStaticChannelInfo->drcData);
3462           }
3463         }
3464 
3465         /* The DRC module demands to be called with the gain field holding the
3466          * gain scale. */
3467         self->extGain[0] = (FIXP_DBL)AACDEC_DRC_GAIN_SCALING;
3468 
3469         /* DRC processing */
3470         aacDecoder_drcApply(
3471             self->hDrcInfo, self->hSbrDecoder, pAacDecoderChannelInfo,
3472             &pAacDecoderStaticChannelInfo->drcData, self->extGain, c,
3473             self->streamInfo.aacSamplesPerFrame, self->sbrEnabled
3474 
3475         );
3476 
3477         if (timeDataSize < timeDataChannelOffset * self->aacChannels) {
3478           ErrorStatus = AAC_DEC_OUTPUT_BUFFER_TOO_SMALL;
3479           break;
3480         }
3481         if (self->flushStatus && (self->flushCnt > 0) &&
3482             !(flags & AACDEC_CONCEAL)) {
3483           FDKmemclear(pTimeData + offset,
3484                       sizeof(PCM_DEC) * self->streamInfo.aacSamplesPerFrame);
3485         } else
3486           switch (pAacDecoderChannelInfo->renderMode) {
3487             case AACDEC_RENDER_IMDCT:
3488 
3489               CBlock_FrequencyToTime(
3490                   pAacDecoderStaticChannelInfo, pAacDecoderChannelInfo,
3491                   pTimeData + offset, self->streamInfo.aacSamplesPerFrame,
3492                   (self->frameOK && !(flags & AACDEC_CONCEAL) &&
3493                    !frameOk_butConceal),
3494                   pAacDecoderChannelInfo->pComStaticData->pWorkBufferCore1
3495                       ->mdctOutTemp,
3496                   self->aacOutDataHeadroom, self->elFlags[el], elCh);
3497 
3498               self->extGainDelay = self->streamInfo.aacSamplesPerFrame;
3499               break;
3500             case AACDEC_RENDER_ELDFB: {
3501               CBlock_FrequencyToTimeLowDelay(
3502                   pAacDecoderStaticChannelInfo, pAacDecoderChannelInfo,
3503                   pTimeData + offset, self->streamInfo.aacSamplesPerFrame);
3504               self->extGainDelay =
3505                   (self->streamInfo.aacSamplesPerFrame * 2 -
3506                    self->streamInfo.aacSamplesPerFrame / 2 - 1) /
3507                   2;
3508             } break;
3509             case AACDEC_RENDER_LPD:
3510 
3511               CLpd_RenderTimeSignal(
3512                   pAacDecoderStaticChannelInfo, pAacDecoderChannelInfo,
3513                   pTimeData + offset, self->streamInfo.aacSamplesPerFrame,
3514                   &self->samplingRateInfo[streamIndex],
3515                   (self->frameOK && !(flags & AACDEC_CONCEAL) &&
3516                    !frameOk_butConceal),
3517                   self->aacOutDataHeadroom, flags, self->flags[streamIndex]);
3518 
3519               self->extGainDelay = self->streamInfo.aacSamplesPerFrame;
3520               break;
3521             default:
3522               ErrorStatus = AAC_DEC_UNKNOWN;
3523               break;
3524           }
3525         /* TimeDomainFading */
3526         if (!CConceal_TDFading_Applied[c]) {
3527           CConceal_TDFading_Applied[c] = CConcealment_TDFading(
3528               self->streamInfo.aacSamplesPerFrame,
3529               &self->pAacDecoderStaticChannelInfo[c], self->aacOutDataHeadroom,
3530               pTimeData + offset, 0);
3531           if (c + 1 < (8) && c < aacChannels - 1) {
3532             /* update next TDNoise Seed to avoid muting in case of Parametric
3533              * Stereo */
3534             self->pAacDecoderStaticChannelInfo[c + 1]
3535                 ->concealmentInfo.TDNoiseSeed =
3536                 self->pAacDecoderStaticChannelInfo[c]
3537                     ->concealmentInfo.TDNoiseSeed;
3538           }
3539         }
3540       }
3541     }
3542 
3543     if (self->flags[streamIndex] & AC_USAC) {
3544       int bsPseudoLr = 0;
3545       mpegSurroundDecoder_IsPseudoLR(
3546           (CMpegSurroundDecoder *)self->pMpegSurroundDecoder, &bsPseudoLr);
3547       /* ISO/IEC 23003-3, 7.11.2.6 Modification of core decoder output (pseudo
3548        * LR) */
3549       if ((aacChannels == 2) && bsPseudoLr) {
3550         int i, offset2;
3551         const FIXP_SGL invSqrt2 = FL2FXCONST_SGL(0.707106781186547f);
3552         PCM_DEC *pTD = pTimeData;
3553 
3554         offset2 = timeDataChannelOffset;
3555 
3556         for (i = 0; i < self->streamInfo.aacSamplesPerFrame; i++) {
3557           FIXP_DBL L = PCM_DEC2FIXP_DBL(pTD[0]);
3558           FIXP_DBL R = PCM_DEC2FIXP_DBL(pTD[offset2]);
3559           L = fMult(L, invSqrt2);
3560           R = fMult(R, invSqrt2);
3561           pTD[0] = L + R;
3562           pTD[offset2] = L - R;
3563           pTD++;
3564         }
3565       }
3566     }
3567 
3568     /* Extract DRC control data and map it to channels (with bitstream delay) */
3569     mapped = aacDecoder_drcEpilog(
3570         self->hDrcInfo, bs, self->pAacDecoderStaticChannelInfo,
3571         pce->ElementInstanceTag, drcChMap, aacChannels);
3572     if (mapped > 0) {
3573       if (!(self->flags[streamIndex] & (AC_USAC | AC_RSV603DA))) {
3574         /* If at least one DRC thread has been mapped to a channel there was DRC
3575          * data in the bitstream. */
3576         self->flags[streamIndex] |= AC_DRC_PRESENT;
3577       } else {
3578         ErrorStatus = AAC_DEC_UNSUPPORTED_FORMAT;
3579       }
3580     }
3581     if (self->flags[streamIndex] & (AC_USAC | AC_RSV603DA)) {
3582       aacDecoder_drcDisable(self->hDrcInfo);
3583     }
3584   }
3585 
3586   /* Add additional concealment delay */
3587   self->streamInfo.outputDelay +=
3588       CConcealment_GetDelay(&self->concealCommonData) *
3589       self->streamInfo.aacSamplesPerFrame;
3590 
3591   /* Map DRC data to StreamInfo structure */
3592   aacDecoder_drcGetInfo(self->hDrcInfo, &self->streamInfo.drcPresMode,
3593                         &self->streamInfo.drcProgRefLev);
3594 
3595   /* Reorder channel type information tables.  */
3596   if (!(self->flags[0] & AC_RSV603DA)) {
3597     AUDIO_CHANNEL_TYPE types[(8)];
3598     UCHAR idx[(8)];
3599     int c;
3600     int mapValue;
3601 
3602     FDK_ASSERT(sizeof(self->channelType) == sizeof(types));
3603     FDK_ASSERT(sizeof(self->channelIndices) == sizeof(idx));
3604 
3605     FDKmemcpy(types, self->channelType, sizeof(types));
3606     FDKmemcpy(idx, self->channelIndices, sizeof(idx));
3607 
3608     for (c = 0; c < aacChannels; c++) {
3609       mapValue =
3610           FDK_chMapDescr_getMapValue(&self->mapDescr, c, self->chMapIndex);
3611       self->channelType[mapValue] = types[c];
3612       self->channelIndices[mapValue] = idx[c];
3613     }
3614   }
3615 
3616   self->blockNumber++;
3617 
3618   return ErrorStatus;
3619 }
3620 
3621 /*!
3622   \brief returns the streaminfo pointer
3623 
3624   The function hands back a pointer to the streaminfo structure
3625 
3626   \return pointer to the struct
3627 */
CAacDecoder_GetStreamInfo(HANDLE_AACDECODER self)3628 LINKSPEC_CPP CStreamInfo *CAacDecoder_GetStreamInfo(HANDLE_AACDECODER self) {
3629   if (!self) {
3630     return NULL;
3631   }
3632   return &self->streamInfo;
3633 }
3634