xref: /aosp_15_r20/external/aac/libAACdec/src/aacdecoder.cpp (revision e54365361535b070c2db7374cec45c159c7d0e7a)
1 /* -----------------------------------------------------------------------------
2 Software License for The Fraunhofer FDK AAC Codec Library for Android
3 
4 © Copyright  1995 - 2023 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 [email protected]
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_LDSAC_DATA:
916     case EXT_SAC_DATA:
917       /* Read MPEG Surround Extension payload */
918       {
919         int err, mpsSampleRate, mpsFrameSize;
920 
921         if (self->flags[0] & AC_PS_PRESENT) {
922           error = AAC_DEC_PARSE_ERROR;
923           goto bail;
924         }
925 
926         /* Handle SBR dual rate case */
927         if (self->streamInfo.extSamplingRate != 0) {
928           mpsSampleRate = self->streamInfo.extSamplingRate;
929           mpsFrameSize = self->streamInfo.aacSamplesPerFrame *
930                          (self->streamInfo.extSamplingRate /
931                           self->streamInfo.aacSampleRate);
932         } else {
933           mpsSampleRate = self->streamInfo.aacSampleRate;
934           mpsFrameSize = self->streamInfo.aacSamplesPerFrame;
935         }
936         /* Setting of internal MPS state; may be reset in
937            CAacDecoder_SyncQmfMode if decoder is unable to decode with user
938            defined qmfMode */
939         if (!(self->flags[0] & (AC_USAC | AC_RSVD50 | AC_ELD))) {
940           self->mpsEnableCurr = self->mpsEnableUser;
941         }
942         if (self->mpsEnableCurr) {
943           if (!self->qmfDomain.globalConf.qmfDomainExplicitConfig) {
944             /* if not done yet, allocate full MPEG Surround decoder instance */
945             if (mpegSurroundDecoder_IsFullMpegSurroundDecoderInstanceAvailable(
946                     (CMpegSurroundDecoder *)self->pMpegSurroundDecoder) ==
947                 SAC_INSTANCE_NOT_FULL_AVAILABLE) {
948               if (mpegSurroundDecoder_Open(
949                       (CMpegSurroundDecoder **)&self->pMpegSurroundDecoder, -1,
950                       &self->qmfDomain)) {
951                 return AAC_DEC_OUT_OF_MEMORY;
952               }
953             }
954           }
955           err = mpegSurroundDecoder_Parse(
956               (CMpegSurroundDecoder *)self->pMpegSurroundDecoder, hBs, count,
957               self->streamInfo.aot, mpsSampleRate, mpsFrameSize,
958               self->flags[0] & AC_INDEP);
959           if (err == MPS_OK) {
960             self->flags[0] |= AC_MPS_PRESENT;
961           } else {
962             error = AAC_DEC_PARSE_ERROR;
963           }
964         }
965         /* Skip any trailing bytes */
966         FDKpushFor(hBs, *count);
967         *count = 0;
968       }
969       break;
970 
971     case EXT_SBR_DATA_CRC:
972       crcFlag = 1;
973       FDK_FALLTHROUGH;
974     case EXT_SBR_DATA:
975       if (IS_CHANNEL_ELEMENT(previous_element)) {
976         SBR_ERROR sbrError;
977         UCHAR configMode = 0;
978         UCHAR configChanged = 0;
979 
980         CAacDecoder_SyncQmfMode(self);
981 
982         configMode |= AC_CM_ALLOC_MEM;
983 
984         sbrError = sbrDecoder_InitElement(
985             self->hSbrDecoder, self->streamInfo.aacSampleRate,
986             self->streamInfo.extSamplingRate,
987             self->streamInfo.aacSamplesPerFrame, self->streamInfo.aot,
988             previous_element, elIndex,
989             2, /* Signalize that harmonicSBR shall be ignored in the config
990                   change detection */
991             0, configMode, &configChanged, self->downscaleFactor);
992 
993         if (sbrError == SBRDEC_OK) {
994           sbrError = sbrDecoder_Parse(self->hSbrDecoder, hBs,
995                                       self->pDrmBsBuffer, self->drmBsBufferSize,
996                                       count, *count, crcFlag, previous_element,
997                                       elIndex, self->flags[0], self->elFlags);
998           /* Enable SBR for implicit SBR signalling but only if no severe error
999            * happend. */
1000           if ((sbrError == SBRDEC_OK) || (sbrError == SBRDEC_PARSE_ERROR)) {
1001             self->sbrEnabled = 1;
1002           }
1003         } else {
1004           /* Do not try to apply SBR because initializing the element failed. */
1005           self->sbrEnabled = 0;
1006         }
1007         /* Citation from ISO/IEC 14496-3 chapter 4.5.2.1.5.2
1008         Fill elements containing an extension_payload() with an extension_type
1009         of EXT_SBR_DATA or EXT_SBR_DATA_CRC shall not contain any other
1010         extension_payload of any other extension_type.
1011         */
1012         if (fIsFillElement) {
1013           FDKpushBiDirectional(hBs, *count);
1014           *count = 0;
1015         } else {
1016           /* If this is not a fill element with a known length, we are screwed
1017            * and further parsing makes no sense. */
1018           if (sbrError != SBRDEC_OK) {
1019             self->frameOK = 0;
1020           }
1021         }
1022       } else {
1023         error = AAC_DEC_PARSE_ERROR;
1024       }
1025       break;
1026 
1027     case EXT_FILL_DATA: {
1028       int temp;
1029 
1030       temp = FDKreadBits(hBs, 4);
1031       bytes--;
1032       if (temp != 0) {
1033         error = AAC_DEC_PARSE_ERROR;
1034         break;
1035       }
1036       while (bytes > 0) {
1037         temp = FDKreadBits(hBs, 8);
1038         bytes--;
1039         if (temp != 0xa5) {
1040           error = AAC_DEC_PARSE_ERROR;
1041           break;
1042         }
1043       }
1044       *count = bytes << 3;
1045     } break;
1046 
1047     case EXT_DATA_ELEMENT: {
1048       int dataElementVersion;
1049 
1050       dataElementVersion = FDKreadBits(hBs, 4);
1051       *count -= 4;
1052       if (dataElementVersion == 0) /* ANC_DATA */
1053       {
1054         int temp, dataElementLength = 0;
1055         do {
1056           temp = FDKreadBits(hBs, 8);
1057           *count -= 8;
1058           dataElementLength += temp;
1059         } while (temp == 255);
1060 
1061         CAacDecoder_AncDataParse(&self->ancData, hBs, dataElementLength);
1062         *count -= (dataElementLength << 3);
1063       } else {
1064         /* align = 0 */
1065         error = AAC_DEC_PARSE_ERROR;
1066         goto bail;
1067       }
1068     } break;
1069 
1070     case EXT_DATA_LENGTH:
1071       if (!fIsFillElement /* Makes no sens to have an additional length in a
1072                              fill ...   */
1073           &&
1074           (self->flags[0] &
1075            AC_ER)) /* ... element because this extension payload type was ... */
1076       { /* ... created to circumvent the missing length in ER-Syntax. */
1077         int bitCnt, len = FDKreadBits(hBs, 4);
1078         *count -= 4;
1079 
1080         if (len == 15) {
1081           int add_len = FDKreadBits(hBs, 8);
1082           *count -= 8;
1083           len += add_len;
1084 
1085           if (add_len == 255) {
1086             len += FDKreadBits(hBs, 16);
1087             *count -= 16;
1088           }
1089         }
1090         len <<= 3;
1091         bitCnt = len;
1092 
1093         if ((EXT_PAYLOAD_TYPE)FDKreadBits(hBs, 4) == EXT_DATA_LENGTH) {
1094           /* Check NOTE 2: The extension_payload() included here must
1095                            not have extension_type == EXT_DATA_LENGTH. */
1096           error = AAC_DEC_PARSE_ERROR;
1097           goto bail;
1098         } else {
1099           /* rewind and call myself again. */
1100           FDKpushBack(hBs, 4);
1101 
1102           error = CAacDecoder_ExtPayloadParse(
1103               self, hBs, &bitCnt, previous_element, elIndex,
1104               1); /* Treat same as fill element */
1105 
1106           *count -= len - bitCnt;
1107         }
1108         /* Note: the fall through in case the if statement above is not taken is
1109          * intentional. */
1110         break;
1111       }
1112       FDK_FALLTHROUGH;
1113 
1114     case EXT_FIL:
1115 
1116     default:
1117       /* align = 4 */
1118       FDKpushFor(hBs, *count);
1119       *count = 0;
1120       break;
1121   }
1122 
1123 bail:
1124   if ((error != AAC_DEC_OK) &&
1125       fIsFillElement) { /* Skip the remaining extension bytes */
1126     FDKpushBiDirectional(hBs, *count);
1127     *count = 0;
1128     /* Patch error code because decoding can go on. */
1129     error = AAC_DEC_OK;
1130     /* Be sure that parsing errors have been stored. */
1131   }
1132   return error;
1133 }
1134 
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[])1135 static AAC_DECODER_ERROR aacDecoder_ParseExplicitMpsAndSbr(
1136     HANDLE_AACDECODER self, HANDLE_FDK_BITSTREAM bs,
1137     const MP4_ELEMENT_ID previous_element, const int previous_element_index,
1138     const int element_index, const int el_cnt[]) {
1139   AAC_DECODER_ERROR ErrorStatus = AAC_DEC_OK;
1140   INT bitCnt = 0;
1141 
1142   /* get the remaining bits of this frame */
1143   bitCnt = transportDec_GetAuBitsRemaining(self->hInput, 0);
1144 
1145   if ((self->flags[0] & AC_SBR_PRESENT) &&
1146       (self->flags[0] & (AC_USAC | AC_RSVD50 | AC_ELD | AC_DRM))) {
1147     SBR_ERROR err = SBRDEC_OK;
1148     int chElIdx, numChElements = el_cnt[ID_SCE] + el_cnt[ID_CPE] +
1149                                  el_cnt[ID_LFE] + el_cnt[ID_USAC_SCE] +
1150                                  el_cnt[ID_USAC_CPE] + el_cnt[ID_USAC_LFE];
1151     INT bitCntTmp = bitCnt;
1152 
1153     if (self->flags[0] & AC_USAC) {
1154       chElIdx = numChElements - 1;
1155     } else {
1156       chElIdx = 0; /* ELD case */
1157     }
1158 
1159     for (; chElIdx < numChElements; chElIdx += 1) {
1160       MP4_ELEMENT_ID sbrType;
1161       SBR_ERROR errTmp;
1162       if (self->flags[0] & (AC_USAC)) {
1163         FDK_ASSERT((self->elements[element_index] == ID_USAC_SCE) ||
1164                    (self->elements[element_index] == ID_USAC_CPE));
1165         sbrType = IS_STEREO_SBR(self->elements[element_index],
1166                                 self->usacStereoConfigIndex[element_index])
1167                       ? ID_CPE
1168                       : ID_SCE;
1169       } else
1170         sbrType = self->elements[chElIdx];
1171       errTmp = sbrDecoder_Parse(self->hSbrDecoder, bs, self->pDrmBsBuffer,
1172                                 self->drmBsBufferSize, &bitCnt, -1,
1173                                 self->flags[0] & AC_SBRCRC, sbrType, chElIdx,
1174                                 self->flags[0], self->elFlags);
1175       if (errTmp != SBRDEC_OK) {
1176         err = errTmp;
1177         bitCntTmp = bitCnt;
1178         bitCnt = 0;
1179       }
1180     }
1181     switch (err) {
1182       case SBRDEC_PARSE_ERROR:
1183         /* Can not go on parsing because we do not
1184             know the length of the SBR extension data. */
1185         FDKpushFor(bs, bitCntTmp);
1186         bitCnt = 0;
1187         break;
1188       case SBRDEC_OK:
1189         self->sbrEnabled = 1;
1190         break;
1191       default:
1192         self->frameOK = 0;
1193         break;
1194     }
1195   }
1196 
1197   if ((bitCnt > 0) && (self->flags[0] & (AC_USAC | AC_RSVD50))) {
1198     if ((self->flags[0] & AC_MPS_PRESENT) ||
1199         (self->elFlags[element_index] & AC_EL_USAC_MPS212)) {
1200       int err;
1201 
1202       err = mpegSurroundDecoder_ParseNoHeader(
1203           (CMpegSurroundDecoder *)self->pMpegSurroundDecoder, bs, &bitCnt,
1204           self->flags[0] & AC_INDEP);
1205       if (err != MPS_OK) {
1206         self->frameOK = 0;
1207         ErrorStatus = AAC_DEC_PARSE_ERROR;
1208       }
1209     }
1210   }
1211 
1212   if (self->flags[0] & AC_DRM) {
1213     if ((bitCnt = (INT)FDKgetValidBits(bs)) != 0) {
1214       FDKpushBiDirectional(bs, bitCnt);
1215     }
1216   }
1217 
1218   if (!(self->flags[0] & (AC_USAC | AC_RSVD50 | AC_DRM))) {
1219     while (bitCnt > 7) {
1220       ErrorStatus = CAacDecoder_ExtPayloadParse(
1221           self, bs, &bitCnt, previous_element, previous_element_index, 0);
1222       if (ErrorStatus != AAC_DEC_OK) {
1223         self->frameOK = 0;
1224         ErrorStatus = AAC_DEC_PARSE_ERROR;
1225         break;
1226       }
1227     }
1228   }
1229   return ErrorStatus;
1230 }
1231 
1232 /*  Stream Configuration and Information.
1233 
1234     This class holds configuration and information data for a stream to be
1235    decoded. It provides the calling application as well as the decoder with
1236    substantial information, e.g. profile, sampling rate, number of channels
1237    found in the bitstream etc.
1238 */
CStreamInfoInit(CStreamInfo * pStreamInfo)1239 static void CStreamInfoInit(CStreamInfo *pStreamInfo) {
1240   pStreamInfo->aacSampleRate = 0;
1241   pStreamInfo->profile = -1;
1242   pStreamInfo->aot = AOT_NONE;
1243 
1244   pStreamInfo->channelConfig = -1;
1245   pStreamInfo->bitRate = 0;
1246   pStreamInfo->aacSamplesPerFrame = 0;
1247 
1248   pStreamInfo->extAot = AOT_NONE;
1249   pStreamInfo->extSamplingRate = 0;
1250 
1251   pStreamInfo->flags = 0;
1252 
1253   pStreamInfo->epConfig = -1; /* default: no ER */
1254 
1255   pStreamInfo->numChannels = 0;
1256   pStreamInfo->sampleRate = 0;
1257   pStreamInfo->frameSize = 0;
1258 
1259   pStreamInfo->outputDelay = 0;
1260 
1261   /* DRC */
1262   pStreamInfo->drcProgRefLev =
1263       -1; /* set program reference level to not indicated */
1264   pStreamInfo->drcPresMode = -1; /* default: presentation mode not indicated */
1265 
1266   pStreamInfo->outputLoudness = -1; /* default: no loudness metadata present */
1267 }
1268 
1269 /*!
1270   \brief Initialization of AacDecoderChannelInfo
1271 
1272   The function initializes the pointers to AacDecoderChannelInfo for each
1273   channel, set the start values for window shape and window sequence of
1274   overlap&add to zero, set the overlap buffer to zero and initializes the
1275   pointers to the window coefficients. \param bsFormat is the format of the AAC
1276   bitstream
1277 
1278   \return  AACDECODER instance
1279 */
CAacDecoder_Open(TRANSPORT_TYPE bsFormat)1280 LINKSPEC_CPP HANDLE_AACDECODER CAacDecoder_Open(
1281     TRANSPORT_TYPE bsFormat) /*!< bitstream format (adif,adts,loas,...). */
1282 {
1283   HANDLE_AACDECODER self;
1284 
1285   self = GetAacDecoder();
1286   if (self == NULL) {
1287     goto bail;
1288   }
1289 
1290   FDK_QmfDomain_ClearRequested(&self->qmfDomain.globalConf);
1291 
1292   /* Assign channel mapping info arrays (doing so removes dependency of settings
1293    * header in API header). */
1294   self->streamInfo.pChannelIndices = self->channelIndices;
1295   self->streamInfo.pChannelType = self->channelType;
1296   self->downscaleFactor = 1;
1297   self->downscaleFactorInBS = 1;
1298 
1299   /* initialize anc data */
1300   CAacDecoder_AncDataInit(&self->ancData, NULL, 0);
1301 
1302   /* initialize stream info */
1303   CStreamInfoInit(&self->streamInfo);
1304 
1305   /* initialize progam config */
1306   CProgramConfig_Init(&self->pce);
1307 
1308   /* initialize error concealment common data */
1309   CConcealment_InitCommonData(&self->concealCommonData);
1310   self->concealMethodUser = ConcealMethodNone; /* undefined -> auto mode */
1311 
1312   self->hDrcInfo = GetDrcInfo();
1313   if (self->hDrcInfo == NULL) {
1314     goto bail;
1315   }
1316   /* Init common DRC structure */
1317   aacDecoder_drcInit(self->hDrcInfo);
1318   /* Set default frame delay */
1319   aacDecoder_drcSetParam(self->hDrcInfo, DRC_BS_DELAY,
1320                          CConcealment_GetDelay(&self->concealCommonData));
1321   self->workBufferCore1 = (FIXP_DBL *)GetWorkBufferCore1();
1322 
1323   self->workBufferCore2 = GetWorkBufferCore2();
1324   if (self->workBufferCore2 == NULL) goto bail;
1325 
1326   /* When RSVD60 is active use dedicated memory for core decoding */
1327   self->pTimeData2 = GetWorkBufferCore5();
1328   self->timeData2Size = GetRequiredMemWorkBufferCore5();
1329   if (self->pTimeData2 == NULL) {
1330     goto bail;
1331   }
1332 
1333   return self;
1334 
1335 bail:
1336   CAacDecoder_Close(self);
1337 
1338   return NULL;
1339 }
1340 
1341 /* Revert CAacDecoder_Init() */
CAacDecoder_DeInit(HANDLE_AACDECODER self,const int subStreamIndex)1342 static void CAacDecoder_DeInit(HANDLE_AACDECODER self,
1343                                const int subStreamIndex) {
1344   int ch;
1345   int aacChannelOffset = 0, aacChannels = (8);
1346   int numElements = (3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) + 1),
1347       elementOffset = 0;
1348 
1349   if (self == NULL) return;
1350 
1351   {
1352     self->ascChannels[0] = 0;
1353     self->elements[0] = ID_END;
1354   }
1355 
1356   for (ch = aacChannelOffset; ch < aacChannelOffset + aacChannels; ch++) {
1357     if (self->pAacDecoderChannelInfo[ch] != NULL) {
1358       if (self->pAacDecoderChannelInfo[ch]->pComStaticData != NULL) {
1359         if (self->pAacDecoderChannelInfo[ch]
1360                 ->pComStaticData->pWorkBufferCore1 != NULL) {
1361           if (ch == aacChannelOffset) {
1362             FreeWorkBufferCore1(&self->pAacDecoderChannelInfo[ch]
1363                                      ->pComStaticData->pWorkBufferCore1);
1364           }
1365         }
1366         if (self->pAacDecoderChannelInfo[ch]
1367                 ->pComStaticData->cplxPredictionData != NULL) {
1368           FreeCplxPredictionData(&self->pAacDecoderChannelInfo[ch]
1369                                       ->pComStaticData->cplxPredictionData);
1370         }
1371         /* Avoid double free of linked pComStaticData in case of CPE by settings
1372          * pointer to NULL. */
1373         if (ch < (8) - 1) {
1374           if ((self->pAacDecoderChannelInfo[ch + 1] != NULL) &&
1375               (self->pAacDecoderChannelInfo[ch + 1]->pComStaticData ==
1376                self->pAacDecoderChannelInfo[ch]->pComStaticData)) {
1377             self->pAacDecoderChannelInfo[ch + 1]->pComStaticData = NULL;
1378           }
1379         }
1380         FDKfree(self->pAacDecoderChannelInfo[ch]->pComStaticData);
1381         self->pAacDecoderChannelInfo[ch]->pComStaticData = NULL;
1382       }
1383       if (self->pAacDecoderChannelInfo[ch]->pComData != NULL) {
1384         /* Avoid double free of linked pComData in case of CPE by settings
1385          * pointer to NULL. */
1386         if (ch < (8) - 1) {
1387           if ((self->pAacDecoderChannelInfo[ch + 1] != NULL) &&
1388               (self->pAacDecoderChannelInfo[ch + 1]->pComData ==
1389                self->pAacDecoderChannelInfo[ch]->pComData)) {
1390             self->pAacDecoderChannelInfo[ch + 1]->pComData = NULL;
1391           }
1392         }
1393         if (ch == aacChannelOffset) {
1394           FreeWorkBufferCore6(
1395               (SCHAR **)&self->pAacDecoderChannelInfo[ch]->pComData);
1396         } else {
1397           FDKafree(self->pAacDecoderChannelInfo[ch]->pComData);
1398         }
1399         self->pAacDecoderChannelInfo[ch]->pComData = NULL;
1400       }
1401     }
1402     if (self->pAacDecoderStaticChannelInfo[ch] != NULL) {
1403       if (self->pAacDecoderStaticChannelInfo[ch]->pOverlapBuffer != NULL) {
1404         FreeOverlapBuffer(
1405             &self->pAacDecoderStaticChannelInfo[ch]->pOverlapBuffer);
1406       }
1407       if (self->pAacDecoderStaticChannelInfo[ch]->hArCo != NULL) {
1408         CArco_Destroy(self->pAacDecoderStaticChannelInfo[ch]->hArCo);
1409       }
1410       FreeAacDecoderStaticChannelInfo(&self->pAacDecoderStaticChannelInfo[ch]);
1411     }
1412     if (self->pAacDecoderChannelInfo[ch] != NULL) {
1413       FreeAacDecoderChannelInfo(&self->pAacDecoderChannelInfo[ch]);
1414     }
1415   }
1416 
1417   {
1418     int el;
1419     for (el = elementOffset; el < elementOffset + numElements; el++) {
1420       if (self->cpeStaticData[el] != NULL) {
1421         FreeCpePersistentData(&self->cpeStaticData[el]);
1422       }
1423     }
1424   }
1425 
1426   FDK_Delay_Destroy(&self->usacResidualDelay);
1427 
1428   self->aacChannels = 0;
1429   self->streamInfo.aacSampleRate = 0;
1430   self->streamInfo.sampleRate = 0;
1431   /* This samplerate value is checked for configuration change, not the others
1432    * above. */
1433   self->samplingRateInfo[subStreamIndex].samplingRate = 0;
1434 }
1435 
1436 /*!
1437  * \brief CAacDecoder_AcceptFlags Accept flags and element flags
1438  *
1439  * \param self          [o]   handle to AACDECODER structure
1440  * \param asc           [i]   handle to ASC structure
1441  * \param flags         [i]   flags
1442  * \param elFlags       [i]   pointer to element flags
1443  * \param streamIndex   [i]   stream index
1444  * \param elementOffset [i]   element offset
1445  *
1446  * \return void
1447  */
CAacDecoder_AcceptFlags(HANDLE_AACDECODER self,const CSAudioSpecificConfig * asc,UINT flags,UINT * elFlags,int streamIndex,int elementOffset)1448 static void CAacDecoder_AcceptFlags(HANDLE_AACDECODER self,
1449                                     const CSAudioSpecificConfig *asc,
1450                                     UINT flags, UINT *elFlags, int streamIndex,
1451                                     int elementOffset) {
1452   FDKmemcpy(self->elFlags, elFlags, sizeof(self->elFlags));
1453 
1454   self->flags[streamIndex] = flags;
1455 }
1456 
1457 /*!
1458  * \brief CAacDecoder_CtrlCFGChange Set config change parameters.
1459  *
1460  * \param self           [i]   handle to AACDECODER structure
1461  * \param flushStatus    [i]   flush status: on|off
1462  * \param flushCnt       [i]   flush frame counter
1463  * \param buildUpStatus  [i]   build up status: on|off
1464  * \param buildUpCnt     [i]   build up frame counter
1465  *
1466  * \return error
1467  */
CAacDecoder_CtrlCFGChange(HANDLE_AACDECODER self,UCHAR flushStatus,SCHAR flushCnt,UCHAR buildUpStatus,SCHAR buildUpCnt)1468 LINKSPEC_CPP AAC_DECODER_ERROR CAacDecoder_CtrlCFGChange(HANDLE_AACDECODER self,
1469                                                          UCHAR flushStatus,
1470                                                          SCHAR flushCnt,
1471                                                          UCHAR buildUpStatus,
1472                                                          SCHAR buildUpCnt) {
1473   AAC_DECODER_ERROR err = AAC_DEC_OK;
1474 
1475   self->flushStatus = flushStatus;
1476   self->flushCnt = flushCnt;
1477   self->buildUpStatus = buildUpStatus;
1478   self->buildUpCnt = buildUpCnt;
1479 
1480   return (err);
1481 }
1482 
1483 /*!
1484  * \brief CAacDecoder_FreeMem Free config dependent AAC memory.
1485  *
1486  * \param self       [i]   handle to AACDECODER structure
1487  *
1488  * \return error
1489  */
CAacDecoder_FreeMem(HANDLE_AACDECODER self,const int subStreamIndex)1490 LINKSPEC_CPP AAC_DECODER_ERROR CAacDecoder_FreeMem(HANDLE_AACDECODER self,
1491                                                    const int subStreamIndex) {
1492   AAC_DECODER_ERROR err = AAC_DEC_OK;
1493 
1494   CAacDecoder_DeInit(self, subStreamIndex);
1495 
1496   return (err);
1497 }
1498 
1499 /* Destroy aac decoder */
CAacDecoder_Close(HANDLE_AACDECODER self)1500 LINKSPEC_CPP void CAacDecoder_Close(HANDLE_AACDECODER self) {
1501   if (self == NULL) return;
1502 
1503   CAacDecoder_DeInit(self, 0);
1504 
1505   {
1506     int ch;
1507     for (ch = 0; ch < (8); ch++) {
1508       if (self->pTimeDataFlush[ch] != NULL) {
1509         FreeTimeDataFlush(&self->pTimeDataFlush[ch]);
1510       }
1511     }
1512   }
1513 
1514   if (self->hDrcInfo) {
1515     FreeDrcInfo(&self->hDrcInfo);
1516   }
1517 
1518   if (self->workBufferCore1 != NULL) {
1519     FreeWorkBufferCore1((CWorkBufferCore1 **)&self->workBufferCore1);
1520   }
1521 
1522   /* Free WorkBufferCore2 */
1523   if (self->workBufferCore2 != NULL) {
1524     FreeWorkBufferCore2(&self->workBufferCore2);
1525   }
1526   if (self->pTimeData2 != NULL) {
1527     FreeWorkBufferCore5(&self->pTimeData2);
1528   }
1529 
1530   FDK_QmfDomain_Close(&self->qmfDomain);
1531 
1532   FreeAacDecoder(&self);
1533 }
1534 
1535 /*!
1536   \brief Initialization of decoder instance
1537 
1538   The function initializes the decoder.
1539 
1540   \return  error status: 0 for success, <>0 for unsupported configurations
1541 */
1542 LINKSPEC_CPP AAC_DECODER_ERROR
CAacDecoder_Init(HANDLE_AACDECODER self,const CSAudioSpecificConfig * asc,UCHAR configMode,UCHAR * configChanged)1543 CAacDecoder_Init(HANDLE_AACDECODER self, const CSAudioSpecificConfig *asc,
1544                  UCHAR configMode, UCHAR *configChanged) {
1545   AAC_DECODER_ERROR err = AAC_DEC_OK;
1546   INT ascChannels, ascChanged = 0;
1547   AACDEC_RENDER_MODE initRenderMode = AACDEC_RENDER_INVALID;
1548   SCHAR usacStereoConfigIndex = -1;
1549   int usacResidualDelayCompSamples = 0;
1550   int elementOffset, aacChannelsOffset, aacChannelsOffsetIdx;
1551   const int streamIndex = 0;
1552   INT flushChannels = 0;
1553 
1554   UINT flags;
1555   /* elFlags[(3*MAX_CHANNELS + (MAX_CHANNELS)/2 + 4 * (MAX_TRACKS) + 1]
1556      where MAX_CHANNELS is (8*2) and MAX_TRACKS is 1 */
1557   UINT elFlags[(3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) + 1)];
1558 
1559   UCHAR sbrEnabled = self->sbrEnabled;
1560   UCHAR sbrEnabledPrev = self->sbrEnabledPrev;
1561   UCHAR mpsEnableCurr = self->mpsEnableCurr;
1562 
1563   if (!self) return AAC_DEC_INVALID_HANDLE;
1564 
1565   UCHAR downscaleFactor = self->downscaleFactor;
1566   UCHAR downscaleFactorInBS = self->downscaleFactorInBS;
1567 
1568   self->aacOutDataHeadroom = (3);
1569 
1570   // set profile and check for supported aot
1571   // leave profile on default (=-1) for all other supported MPEG-4 aot's except
1572   // aot=2 (=AAC-LC)
1573   switch (asc->m_aot) {
1574     case AOT_AAC_LC:
1575       self->streamInfo.profile = 1;
1576       FDK_FALLTHROUGH;
1577     case AOT_ER_AAC_SCAL:
1578       if (asc->m_sc.m_gaSpecificConfig.m_layer > 0) {
1579         /* aac_scalable_extension_element() currently not supported. */
1580         return AAC_DEC_UNSUPPORTED_FORMAT;
1581       }
1582       FDK_FALLTHROUGH;
1583     case AOT_SBR:
1584     case AOT_PS:
1585     case AOT_ER_AAC_LC:
1586     case AOT_ER_AAC_LD:
1587     case AOT_DRM_AAC:
1588     case AOT_DRM_SURROUND:
1589       initRenderMode = AACDEC_RENDER_IMDCT;
1590       break;
1591     case AOT_ER_AAC_ELD:
1592       initRenderMode = AACDEC_RENDER_ELDFB;
1593       break;
1594     case AOT_USAC:
1595       initRenderMode = AACDEC_RENDER_IMDCT;
1596       break;
1597     default:
1598       return AAC_DEC_UNSUPPORTED_AOT;
1599   }
1600 
1601   if (CProgramConfig_IsValid(&self->pce) && (asc->m_channelConfiguration > 0)) {
1602     /* Compare the stored (old) PCE with a default PCE created from the (new)
1603        channel_config (on a temporal buffer) to find out wheter we can keep it
1604        (and its metadata) or not. */
1605     int pceCmpResult;
1606     C_ALLOC_SCRATCH_START(tmpPce, CProgramConfig, 1);
1607 
1608     CProgramConfig_GetDefault(tmpPce, asc->m_channelConfiguration);
1609     pceCmpResult = CProgramConfig_Compare(&self->pce, tmpPce);
1610     if ((pceCmpResult < 0) /* Reset if PCEs are completely different ... */
1611         ||
1612         (pceCmpResult > 1)) { /*            ... or have a different layout. */
1613       CProgramConfig_Init(&self->pce);
1614     } /* Otherwise keep the PCE (and its metadata). */
1615     C_ALLOC_SCRATCH_END(tmpPce, CProgramConfig, 1);
1616   } else {
1617     CProgramConfig_Init(&self->pce);
1618   }
1619 
1620   /* set channels */
1621   switch (asc->m_channelConfiguration) {
1622     case 0:
1623       switch (asc->m_aot) {
1624         case AOT_USAC:
1625           self->chMapIndex = 0;
1626           ascChannels = asc->m_sc.m_usacConfig.m_nUsacChannels;
1627           break;
1628         default:
1629           /* get channels from program config (ASC) */
1630           if (CProgramConfig_IsValid(&asc->m_progrConfigElement)) {
1631             ascChannels = asc->m_progrConfigElement.NumChannels;
1632             if (ascChannels > 0) {
1633               int el_tmp;
1634               /* valid number of channels -> copy program config element (PCE)
1635                * from ASC */
1636               FDKmemcpy(&self->pce, &asc->m_progrConfigElement,
1637                         sizeof(CProgramConfig));
1638               /* Built element table */
1639               el_tmp = CProgramConfig_GetElementTable(
1640                   &asc->m_progrConfigElement, self->elements, (((8)) + (8)),
1641                   &self->chMapIndex);
1642               for (; el_tmp < (3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) + 1);
1643                    el_tmp++) {
1644                 self->elements[el_tmp] = ID_NONE;
1645               }
1646             } else {
1647               return AAC_DEC_UNSUPPORTED_CHANNELCONFIG;
1648             }
1649           } else {
1650             self->chMapIndex = 0;
1651             return AAC_DEC_UNSUPPORTED_CHANNELCONFIG;
1652           }
1653           break;
1654       }
1655       break;
1656     case 1:
1657     case 2:
1658     case 3:
1659     case 4:
1660     case 5:
1661     case 6:
1662       ascChannels = asc->m_channelConfiguration;
1663       break;
1664     case 11:
1665       ascChannels = 7;
1666       break;
1667     case 7:
1668     case 12:
1669     case 14:
1670       ascChannels = 8;
1671       break;
1672     default:
1673       return AAC_DEC_UNSUPPORTED_CHANNELCONFIG;
1674   }
1675 
1676   if (asc->m_aot == AOT_USAC) {
1677     flushChannels = fMin(ascChannels, (8));
1678     INT numChannel;
1679     pcmDmx_GetParam(self->hPcmUtils, MIN_NUMBER_OF_OUTPUT_CHANNELS,
1680                     &numChannel);
1681     flushChannels = fMin(fMax(numChannel, flushChannels), (8));
1682   }
1683 
1684   if (IS_USAC(asc->m_aot)) {
1685     for (int el = 0; el < (INT)asc->m_sc.m_usacConfig.m_usacNumElements; el++) {
1686       /* fix number of core channels aka ascChannels for stereoConfigIndex = 1
1687        * cases */
1688       if (asc->m_sc.m_usacConfig.element[el].m_stereoConfigIndex == 1) {
1689         ascChannels--; /* stereoConfigIndex == 1 stereo cases do actually
1690                           contain only a mono core channel. */
1691       } else if (asc->m_sc.m_usacConfig.element[el].m_stereoConfigIndex == 2) {
1692         /* In this case it is necessary to follow up the DMX signal delay caused
1693            by HBE also with the residual signal (2nd core channel). The SBR
1694            overlap delay is not regarded here, this is handled by the MPS212
1695            implementation.
1696         */
1697         if (asc->m_sc.m_usacConfig.element[el].m_harmonicSBR) {
1698           usacResidualDelayCompSamples += asc->m_samplesPerFrame;
1699         }
1700         if (asc->m_sc.m_usacConfig.m_coreSbrFrameLengthIndex == 4) {
1701           usacResidualDelayCompSamples +=
1702               6 * 16; /* difference between 12 SBR
1703                          overlap slots from SBR and 6
1704                          slots delayed in MPS212 */
1705         }
1706       }
1707     }
1708   }
1709 
1710   aacChannelsOffset = 0;
1711   aacChannelsOffsetIdx = 0;
1712   elementOffset = 0;
1713   if ((ascChannels <= 0) || (ascChannels > (8)) ||
1714       (asc->m_channelConfiguration > AACDEC_MAX_CH_CONF)) {
1715     return AAC_DEC_UNSUPPORTED_CHANNELCONFIG;
1716   }
1717 
1718   /* Set syntax flags */
1719   flags = 0;
1720   { FDKmemclear(elFlags, sizeof(elFlags)); }
1721 
1722   if ((asc->m_channelConfiguration > 0) || IS_USAC(asc->m_aot)) {
1723     if (IS_USAC(asc->m_aot)) {
1724       /* copy pointer to usac config
1725         (this is preliminary since there's an ongoing discussion about storing
1726         the config-part of the bitstream rather than the complete decoded
1727         configuration) */
1728       self->pUsacConfig[streamIndex] = &asc->m_sc.m_usacConfig;
1729 
1730       /* copy list of elements */
1731       if (self->pUsacConfig[streamIndex]->m_usacNumElements >
1732           (3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) + 1)) {
1733         goto bail;
1734       }
1735 
1736       if (self->numUsacElements[streamIndex] !=
1737           asc->m_sc.m_usacConfig.m_usacNumElements) {
1738         ascChanged = 1;
1739       }
1740 
1741       if (configMode & AC_CM_ALLOC_MEM) {
1742         self->numUsacElements[streamIndex] =
1743             asc->m_sc.m_usacConfig.m_usacNumElements;
1744       }
1745 
1746       mpsEnableCurr = 0;
1747       for (int _el = 0;
1748            _el < (int)self->pUsacConfig[streamIndex]->m_usacNumElements;
1749            _el++) {
1750         int el = _el + elementOffset;
1751         if (self->elements[el] !=
1752             self->pUsacConfig[streamIndex]->element[_el].usacElementType) {
1753           ascChanged = 1;
1754         }
1755         if (self->usacStereoConfigIndex[el] !=
1756             asc->m_sc.m_usacConfig.element[_el].m_stereoConfigIndex) {
1757           ascChanged = 1;
1758         }
1759         if (configMode & AC_CM_ALLOC_MEM) {
1760           self->elements[el] =
1761               self->pUsacConfig[streamIndex]->element[_el].usacElementType;
1762           /* for Unified Stereo Coding */
1763           self->usacStereoConfigIndex[el] =
1764               asc->m_sc.m_usacConfig.element[_el].m_stereoConfigIndex;
1765           if (self->elements[el] == ID_USAC_CPE) {
1766             mpsEnableCurr |= self->usacStereoConfigIndex[el] ? 1 : 0;
1767           }
1768         }
1769 
1770         elFlags[el] |= (asc->m_sc.m_usacConfig.element[_el].m_noiseFilling)
1771                            ? AC_EL_USAC_NOISE
1772                            : 0;
1773         elFlags[el] |=
1774             (asc->m_sc.m_usacConfig.element[_el].m_stereoConfigIndex > 0)
1775                 ? AC_EL_USAC_MPS212
1776                 : 0;
1777         elFlags[el] |= (asc->m_sc.m_usacConfig.element[_el].m_interTes)
1778                            ? AC_EL_USAC_ITES
1779                            : 0;
1780         elFlags[el] |=
1781             (asc->m_sc.m_usacConfig.element[_el].m_pvc) ? AC_EL_USAC_PVC : 0;
1782         elFlags[el] |=
1783             (asc->m_sc.m_usacConfig.element[_el].usacElementType == ID_USAC_LFE)
1784                 ? AC_EL_USAC_LFE
1785                 : 0;
1786         elFlags[el] |=
1787             (asc->m_sc.m_usacConfig.element[_el].usacElementType == ID_USAC_LFE)
1788                 ? AC_EL_LFE
1789                 : 0;
1790         if ((asc->m_sc.m_usacConfig.element[_el].usacElementType ==
1791              ID_USAC_CPE) &&
1792             ((self->usacStereoConfigIndex[el] == 0))) {
1793           elFlags[el] |= AC_EL_USAC_CP_POSSIBLE;
1794         }
1795       }
1796 
1797       self->hasAudioPreRoll = 0;
1798       if (self->pUsacConfig[streamIndex]->m_usacNumElements) {
1799         self->hasAudioPreRoll = asc->m_sc.m_usacConfig.element[0]
1800                                     .extElement.usacExtElementHasAudioPreRoll;
1801       }
1802       if (configMode & AC_CM_ALLOC_MEM) {
1803         self->elements[elementOffset +
1804                        self->pUsacConfig[streamIndex]->m_usacNumElements] =
1805             ID_END;
1806       }
1807     } else {
1808       /* Initialize constant mappings for channel config 1-7 */
1809       int i;
1810       for (i = 0; i < AACDEC_CH_ELEMENTS_TAB_SIZE; i++) {
1811         self->elements[i] = elementsTab[asc->m_channelConfiguration - 1][i];
1812       }
1813       for (; i < (3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) + 1); i++) {
1814         self->elements[i] = ID_NONE;
1815       }
1816     }
1817 
1818     {
1819       int ch;
1820 
1821       for (ch = 0; ch < ascChannels; ch++) {
1822         self->chMapping[ch] = ch;
1823       }
1824       for (; ch < (8); ch++) {
1825         self->chMapping[ch] = 255;
1826       }
1827     }
1828 
1829     self->chMapIndex = asc->m_channelConfiguration;
1830   } else {
1831     if (CProgramConfig_IsValid(&asc->m_progrConfigElement)) {
1832       /* Set matrix mixdown infos if available from PCE. */
1833       pcmDmx_SetMatrixMixdownFromPce(
1834           self->hPcmUtils, asc->m_progrConfigElement.MatrixMixdownIndexPresent,
1835           asc->m_progrConfigElement.MatrixMixdownIndex,
1836           asc->m_progrConfigElement.PseudoSurroundEnable);
1837     }
1838   }
1839 
1840   self->streamInfo.channelConfig = asc->m_channelConfiguration;
1841 
1842   if (self->streamInfo.aot != asc->m_aot) {
1843     if (configMode & AC_CM_ALLOC_MEM) {
1844       self->streamInfo.aot = asc->m_aot;
1845     }
1846     ascChanged = 1;
1847   }
1848 
1849   if (asc->m_aot == AOT_ER_AAC_ELD &&
1850       asc->m_sc.m_eldSpecificConfig.m_downscaledSamplingFrequency != 0) {
1851     if (self->samplingRateInfo[0].samplingRate !=
1852             asc->m_sc.m_eldSpecificConfig.m_downscaledSamplingFrequency ||
1853         self->samplingRateInfo[0].samplingRate * self->downscaleFactor !=
1854             asc->m_samplingFrequency) {
1855       /* get downscaledSamplingFrequency from ESC and compute the downscale
1856        * factor */
1857       downscaleFactorInBS =
1858           asc->m_samplingFrequency /
1859           asc->m_sc.m_eldSpecificConfig.m_downscaledSamplingFrequency;
1860       if ((downscaleFactorInBS == 1 || downscaleFactorInBS == 2 ||
1861            (downscaleFactorInBS == 3 &&
1862             asc->m_sc.m_eldSpecificConfig.m_frameLengthFlag) ||
1863            downscaleFactorInBS == 4) &&
1864           ((asc->m_samplingFrequency %
1865             asc->m_sc.m_eldSpecificConfig.m_downscaledSamplingFrequency) ==
1866            0)) {
1867         downscaleFactor = downscaleFactorInBS;
1868       } else {
1869         downscaleFactorInBS = 1;
1870         downscaleFactor = 1;
1871       }
1872     }
1873   } else {
1874     downscaleFactorInBS = 1;
1875     downscaleFactor = 1;
1876   }
1877 
1878   if (self->downscaleFactorInBS != downscaleFactorInBS) {
1879     if (configMode & AC_CM_ALLOC_MEM) {
1880       self->downscaleFactorInBS = downscaleFactorInBS;
1881       self->downscaleFactor = downscaleFactor;
1882     }
1883     ascChanged = 1;
1884   }
1885 
1886   if ((INT)asc->m_samplesPerFrame % downscaleFactor != 0) {
1887     return AAC_DEC_UNSUPPORTED_SAMPLINGRATE; /* frameSize/dsf must be an integer
1888                                                 number */
1889   }
1890 
1891   self->streamInfo.bitRate = 0;
1892 
1893   if (asc->m_aot == AOT_ER_AAC_ELD) {
1894     if (self->useLdQmfTimeAlign !=
1895         asc->m_sc.m_eldSpecificConfig.m_useLdQmfTimeAlign) {
1896       ascChanged = 1;
1897     }
1898     if (configMode & AC_CM_ALLOC_MEM) {
1899       self->useLdQmfTimeAlign =
1900           asc->m_sc.m_eldSpecificConfig.m_useLdQmfTimeAlign;
1901     }
1902     if (sbrEnabled != asc->m_sbrPresentFlag) {
1903       ascChanged = 1;
1904     }
1905   }
1906 
1907   self->streamInfo.extAot = asc->m_extensionAudioObjectType;
1908   if (self->streamInfo.extSamplingRate !=
1909       (INT)asc->m_extensionSamplingFrequency) {
1910     ascChanged = 1;
1911   }
1912   if (configMode & AC_CM_ALLOC_MEM) {
1913     self->streamInfo.extSamplingRate = asc->m_extensionSamplingFrequency;
1914   }
1915   flags |= (asc->m_sbrPresentFlag) ? AC_SBR_PRESENT : 0;
1916   flags |= (asc->m_psPresentFlag) ? AC_PS_PRESENT : 0;
1917   if (asc->m_sbrPresentFlag) {
1918     sbrEnabled = 1;
1919     sbrEnabledPrev = 1;
1920   } else {
1921     sbrEnabled = 0;
1922     sbrEnabledPrev = 0;
1923   }
1924   if (sbrEnabled && asc->m_extensionSamplingFrequency) {
1925     if (downscaleFactor != 1 && (downscaleFactor)&1) {
1926       return AAC_DEC_UNSUPPORTED_SAMPLINGRATE; /* SBR needs an even downscale
1927                                                   factor */
1928     }
1929     if (configMode & AC_CM_ALLOC_MEM) {
1930       self->streamInfo.extSamplingRate =
1931           self->streamInfo.extSamplingRate / self->downscaleFactor;
1932     }
1933   }
1934   if ((asc->m_aot == AOT_AAC_LC) && (asc->m_sbrPresentFlag == 1) &&
1935       (asc->m_extensionSamplingFrequency > (2 * asc->m_samplingFrequency))) {
1936     return AAC_DEC_UNSUPPORTED_SAMPLINGRATE; /* Core decoder supports at most a
1937                                                 1:2 upsampling for HE-AAC and
1938                                                 HE-AACv2 */
1939   }
1940 
1941   /* --------- vcb11 ------------ */
1942   flags |= (asc->m_vcb11Flag) ? AC_ER_VCB11 : 0;
1943 
1944   /* ---------- rvlc ------------ */
1945   flags |= (asc->m_rvlcFlag) ? AC_ER_RVLC : 0;
1946 
1947   /* ----------- hcr ------------ */
1948   flags |= (asc->m_hcrFlag) ? AC_ER_HCR : 0;
1949 
1950   if (asc->m_aot == AOT_ER_AAC_ELD) {
1951     mpsEnableCurr = 0;
1952     flags |= AC_ELD;
1953     flags |= (asc->m_sbrPresentFlag)
1954                  ? AC_SBR_PRESENT
1955                  : 0; /* Need to set the SBR flag for backward-compatibility
1956                                reasons. Even if SBR is not supported. */
1957     flags |= (asc->m_sc.m_eldSpecificConfig.m_sbrCrcFlag) ? AC_SBRCRC : 0;
1958     flags |= (asc->m_sc.m_eldSpecificConfig.m_useLdQmfTimeAlign)
1959                  ? AC_MPS_PRESENT
1960                  : 0;
1961     if (self->mpsApplicable) {
1962       mpsEnableCurr = asc->m_sc.m_eldSpecificConfig.m_useLdQmfTimeAlign;
1963     }
1964   }
1965   flags |= (asc->m_aot == AOT_ER_AAC_LD) ? AC_LD : 0;
1966   flags |= (asc->m_epConfig >= 0) ? AC_ER : 0;
1967 
1968   if (asc->m_aot == AOT_USAC) {
1969     flags |= AC_USAC;
1970     flags |= (asc->m_sc.m_usacConfig.element[0].m_stereoConfigIndex > 0)
1971                  ? AC_MPS_PRESENT
1972                  : 0;
1973   }
1974   if (asc->m_aot == AOT_DRM_AAC) {
1975     flags |= AC_DRM | AC_SBRCRC | AC_SCALABLE;
1976   }
1977   if (asc->m_aot == AOT_DRM_SURROUND) {
1978     flags |= AC_DRM | AC_SBRCRC | AC_SCALABLE | AC_MPS_PRESENT;
1979     FDK_ASSERT(!asc->m_psPresentFlag);
1980   }
1981   if ((asc->m_aot == AOT_AAC_SCAL) || (asc->m_aot == AOT_ER_AAC_SCAL)) {
1982     flags |= AC_SCALABLE;
1983   }
1984 
1985   if ((asc->m_epConfig >= 0) && (asc->m_channelConfiguration <= 0)) {
1986     /* we have to know the number of channels otherwise no decoding is possible
1987      */
1988     return AAC_DEC_UNSUPPORTED_ER_FORMAT;
1989   }
1990 
1991   self->streamInfo.epConfig = asc->m_epConfig;
1992   /* self->hInput->asc.m_epConfig = asc->m_epConfig; */
1993 
1994   if (asc->m_epConfig > 1) return AAC_DEC_UNSUPPORTED_ER_FORMAT;
1995 
1996   /* Check if samplerate changed. */
1997   if ((self->samplingRateInfo[streamIndex].samplingRate !=
1998        asc->m_samplingFrequency) ||
1999       (self->streamInfo.aacSamplesPerFrame !=
2000        (INT)asc->m_samplesPerFrame / downscaleFactor)) {
2001     AAC_DECODER_ERROR error;
2002 
2003     ascChanged = 1;
2004 
2005     if (configMode & AC_CM_ALLOC_MEM) {
2006       /* Update samplerate info. */
2007       error = getSamplingRateInfo(
2008           &self->samplingRateInfo[streamIndex], asc->m_samplesPerFrame,
2009           asc->m_samplingFrequencyIndex, asc->m_samplingFrequency);
2010       if (error != AAC_DEC_OK) {
2011         return error;
2012       }
2013       self->streamInfo.aacSampleRate =
2014           self->samplingRateInfo[0].samplingRate / self->downscaleFactor;
2015       self->streamInfo.aacSamplesPerFrame =
2016           asc->m_samplesPerFrame / self->downscaleFactor;
2017       if (self->streamInfo.aacSampleRate <= 0) {
2018         return AAC_DEC_UNSUPPORTED_SAMPLINGRATE;
2019       }
2020     }
2021   }
2022 
2023   /* Check if amount of channels has changed. */
2024   if (self->ascChannels[streamIndex] != ascChannels) {
2025     ascChanged = 1;
2026   }
2027 
2028   /* detect config change */
2029   if (configMode & AC_CM_DET_CFG_CHANGE) {
2030     if (ascChanged != 0) {
2031       *configChanged = 1;
2032     }
2033 
2034     CAacDecoder_AcceptFlags(self, asc, flags, elFlags, streamIndex,
2035                             elementOffset);
2036 
2037     return err;
2038   }
2039 
2040   /* set AC_USAC_SCFGI3 globally if any usac element uses */
2041   switch (asc->m_aot) {
2042     case AOT_USAC:
2043       if (sbrEnabled) {
2044         for (int _el = 0;
2045              _el < (int)self->pUsacConfig[streamIndex]->m_usacNumElements;
2046              _el++) {
2047           int el = elementOffset + _el;
2048           if (IS_USAC_CHANNEL_ELEMENT(self->elements[el])) {
2049             if (usacStereoConfigIndex < 0) {
2050               usacStereoConfigIndex = self->usacStereoConfigIndex[el];
2051             } else {
2052               if ((usacStereoConfigIndex != self->usacStereoConfigIndex[el]) ||
2053                   (self->usacStereoConfigIndex[el] > 0)) {
2054                 goto bail;
2055               }
2056             }
2057           }
2058         }
2059 
2060         if (usacStereoConfigIndex < 0) {
2061           goto bail;
2062         }
2063 
2064         if (usacStereoConfigIndex == 3) {
2065           flags |= AC_USAC_SCFGI3;
2066         }
2067       }
2068       break;
2069     default:
2070       break;
2071   }
2072 
2073   if (*configChanged) {
2074     /* Set up QMF domain for AOTs with explicit signalling of SBR and or MPS.
2075        This is to be able to play out the first frame alway with the correct
2076        frame size and sampling rate even in case of concealment.
2077     */
2078     switch (asc->m_aot) {
2079       case AOT_USAC:
2080         if (sbrEnabled) {
2081           const UCHAR map_sbrRatio_2_nAnaBands[] = {16, 24, 32};
2082 
2083           FDK_ASSERT(asc->m_sc.m_usacConfig.m_sbrRatioIndex > 0);
2084           FDK_ASSERT(streamIndex == 0);
2085 
2086           self->qmfDomain.globalConf.nInputChannels_requested = ascChannels;
2087           self->qmfDomain.globalConf.nOutputChannels_requested =
2088               (usacStereoConfigIndex == 1) ? 2 : ascChannels;
2089           self->qmfDomain.globalConf.flags_requested = 0;
2090           self->qmfDomain.globalConf.nBandsAnalysis_requested =
2091               map_sbrRatio_2_nAnaBands[asc->m_sc.m_usacConfig.m_sbrRatioIndex -
2092                                        1];
2093           self->qmfDomain.globalConf.nBandsSynthesis_requested = 64;
2094           self->qmfDomain.globalConf.nQmfTimeSlots_requested =
2095               (asc->m_sc.m_usacConfig.m_sbrRatioIndex == 1) ? 64 : 32;
2096           self->qmfDomain.globalConf.nQmfOvTimeSlots_requested =
2097               (asc->m_sc.m_usacConfig.m_sbrRatioIndex == 1) ? 12 : 6;
2098           self->qmfDomain.globalConf.nQmfProcBands_requested = 64;
2099           self->qmfDomain.globalConf.nQmfProcChannels_requested = 1;
2100           self->qmfDomain.globalConf.parkChannel =
2101               (usacStereoConfigIndex == 3) ? 1 : 0;
2102           self->qmfDomain.globalConf.parkChannel_requested =
2103               (usacStereoConfigIndex == 3) ? 1 : 0;
2104           self->qmfDomain.globalConf.qmfDomainExplicitConfig = 1;
2105         }
2106         break;
2107       case AOT_ER_AAC_ELD:
2108         if (mpsEnableCurr &&
2109             asc->m_sc.m_eldSpecificConfig.m_useLdQmfTimeAlign) {
2110           SAC_INPUT_CONFIG sac_interface = (sbrEnabled && self->hSbrDecoder)
2111                                                ? SAC_INTERFACE_QMF
2112                                                : SAC_INTERFACE_TIME;
2113           mpegSurroundDecoder_ConfigureQmfDomain(
2114               (CMpegSurroundDecoder *)self->pMpegSurroundDecoder, sac_interface,
2115               (UINT)self->streamInfo.aacSampleRate, asc->m_aot);
2116           self->qmfDomain.globalConf.qmfDomainExplicitConfig = 1;
2117         }
2118         break;
2119       default:
2120         self->qmfDomain.globalConf.qmfDomainExplicitConfig =
2121             0; /* qmfDomain is initialized by SBR and MPS init functions if
2122                   required */
2123         break;
2124     }
2125 
2126     /* Allocate all memory structures for each channel */
2127     {
2128       int ch = aacChannelsOffset;
2129       for (int _ch = 0; _ch < ascChannels; _ch++) {
2130         if (ch >= (8)) {
2131           goto bail;
2132         }
2133         self->pAacDecoderChannelInfo[ch] = GetAacDecoderChannelInfo(ch);
2134         /* This is temporary until the DynamicData is split into two or more
2135            regions! The memory could be reused after completed core decoding. */
2136         if (self->pAacDecoderChannelInfo[ch] == NULL) {
2137           goto bail;
2138         }
2139         ch++;
2140       }
2141 
2142       int chIdx = aacChannelsOffsetIdx;
2143       ch = aacChannelsOffset;
2144       int _numElements;
2145       _numElements = (((8)) + (8));
2146       if (flags & (AC_RSV603DA | AC_USAC)) {
2147         _numElements = (int)asc->m_sc.m_usacConfig.m_usacNumElements;
2148       }
2149       for (int _el = 0; _el < _numElements; _el++) {
2150         int el_channels = 0;
2151         int el = elementOffset + _el;
2152 
2153         if (flags &
2154             (AC_ER | AC_LD | AC_ELD | AC_RSV603DA | AC_USAC | AC_RSVD50)) {
2155           if (ch >= ascChannels) {
2156             break;
2157           }
2158         }
2159 
2160         switch (self->elements[el]) {
2161           case ID_SCE:
2162           case ID_CPE:
2163           case ID_LFE:
2164           case ID_USAC_SCE:
2165           case ID_USAC_CPE:
2166           case ID_USAC_LFE:
2167 
2168             el_channels = CAacDecoder_GetELChannels(
2169                 self->elements[el], self->usacStereoConfigIndex[el]);
2170 
2171             {
2172               self->pAacDecoderChannelInfo[ch]->pComStaticData =
2173                   (CAacDecoderCommonStaticData *)FDKcalloc(
2174                       1, sizeof(CAacDecoderCommonStaticData));
2175               if (self->pAacDecoderChannelInfo[ch]->pComStaticData == NULL) {
2176                 goto bail;
2177               }
2178               if (ch == aacChannelsOffset) {
2179                 self->pAacDecoderChannelInfo[ch]->pComData =
2180                     (CAacDecoderCommonData *)GetWorkBufferCore6();
2181                 self->pAacDecoderChannelInfo[ch]
2182                     ->pComStaticData->pWorkBufferCore1 = GetWorkBufferCore1();
2183               } else {
2184                 self->pAacDecoderChannelInfo[ch]->pComData =
2185                     (CAacDecoderCommonData *)FDKaalloc(
2186                         sizeof(CAacDecoderCommonData), ALIGNMENT_DEFAULT);
2187                 self->pAacDecoderChannelInfo[ch]
2188                     ->pComStaticData->pWorkBufferCore1 =
2189                     self->pAacDecoderChannelInfo[aacChannelsOffset]
2190                         ->pComStaticData->pWorkBufferCore1;
2191               }
2192               if ((self->pAacDecoderChannelInfo[ch]->pComData == NULL) ||
2193                   (self->pAacDecoderChannelInfo[ch]
2194                        ->pComStaticData->pWorkBufferCore1 == NULL)) {
2195                 goto bail;
2196               }
2197               self->pAacDecoderChannelInfo[ch]->pDynData =
2198                   &(self->pAacDecoderChannelInfo[ch]
2199                         ->pComData->pAacDecoderDynamicData[0]);
2200               self->pAacDecoderChannelInfo[ch]->pSpectralCoefficient =
2201                   (SPECTRAL_PTR)&self->workBufferCore2[ch * 1024];
2202 
2203               if (el_channels == 2) {
2204                 if (ch >= (8) - 1) {
2205                   return AAC_DEC_UNSUPPORTED_CHANNELCONFIG;
2206                 }
2207                 self->pAacDecoderChannelInfo[ch + 1]->pComData =
2208                     self->pAacDecoderChannelInfo[ch]->pComData;
2209                 self->pAacDecoderChannelInfo[ch + 1]->pComStaticData =
2210                     self->pAacDecoderChannelInfo[ch]->pComStaticData;
2211                 self->pAacDecoderChannelInfo[ch + 1]
2212                     ->pComStaticData->pWorkBufferCore1 =
2213                     self->pAacDecoderChannelInfo[ch]
2214                         ->pComStaticData->pWorkBufferCore1;
2215                 self->pAacDecoderChannelInfo[ch + 1]->pDynData =
2216                     &(self->pAacDecoderChannelInfo[ch]
2217                           ->pComData->pAacDecoderDynamicData[1]);
2218                 self->pAacDecoderChannelInfo[ch + 1]->pSpectralCoefficient =
2219                     (SPECTRAL_PTR)&self->workBufferCore2[(ch + 1) * 1024];
2220               }
2221 
2222               ch += el_channels;
2223             }
2224             chIdx += el_channels;
2225             break;
2226 
2227           default:
2228             break;
2229         }
2230 
2231         if (self->elements[el] == ID_END) {
2232           break;
2233         }
2234 
2235         el++;
2236       }
2237 
2238       chIdx = aacChannelsOffsetIdx;
2239       ch = aacChannelsOffset;
2240       for (int _ch = 0; _ch < ascChannels; _ch++) {
2241         /* Allocate persistent channel memory */
2242         {
2243           self->pAacDecoderStaticChannelInfo[ch] =
2244               GetAacDecoderStaticChannelInfo(ch);
2245           if (self->pAacDecoderStaticChannelInfo[ch] == NULL) {
2246             goto bail;
2247           }
2248           self->pAacDecoderStaticChannelInfo[ch]->pOverlapBuffer =
2249               GetOverlapBuffer(ch); /* This area size depends on the AOT */
2250           if (self->pAacDecoderStaticChannelInfo[ch]->pOverlapBuffer == NULL) {
2251             goto bail;
2252           }
2253           if (flags & (AC_USAC | AC_RSVD50 | AC_RSV603DA /*|AC_BSAC*/)) {
2254             self->pAacDecoderStaticChannelInfo[ch]->hArCo = CArco_Create();
2255             if (self->pAacDecoderStaticChannelInfo[ch]->hArCo == NULL) {
2256               goto bail;
2257             }
2258           }
2259 
2260           if (!(flags & (AC_USAC | AC_RSV603DA))) {
2261             CPns_UpdateNoiseState(
2262                 &self->pAacDecoderChannelInfo[ch]->data.aac.PnsData,
2263                 &self->pAacDecoderStaticChannelInfo[ch]->pnsCurrentSeed,
2264                 self->pAacDecoderChannelInfo[ch]->pComData->pnsRandomSeed);
2265           }
2266           ch++;
2267         }
2268         chIdx++;
2269       }
2270 
2271       if (flags & AC_USAC) {
2272         for (int _ch = 0; _ch < flushChannels; _ch++) {
2273           ch = aacChannelsOffset + _ch;
2274           if (self->pTimeDataFlush[ch] == NULL) {
2275             self->pTimeDataFlush[ch] = GetTimeDataFlush(ch);
2276             if (self->pTimeDataFlush[ch] == NULL) {
2277               goto bail;
2278             }
2279           }
2280         }
2281       }
2282 
2283       if (flags & (AC_USAC | AC_RSV603DA)) {
2284         int complexStereoPredPossible = 0;
2285         ch = aacChannelsOffset;
2286         chIdx = aacChannelsOffsetIdx;
2287         for (int _el2 = 0; _el2 < (int)asc->m_sc.m_usacConfig.m_usacNumElements;
2288              _el2++) {
2289           int el2 = elementOffset + _el2;
2290           int elCh = 0, ch2;
2291 
2292           if ((self->elements[el2] == ID_USAC_CPE) &&
2293               !(self->usacStereoConfigIndex[el2] == 1)) {
2294             elCh = 2;
2295           } else if (IS_CHANNEL_ELEMENT(self->elements[el2])) {
2296             elCh = 1;
2297           }
2298 
2299           if (elFlags[el2] & AC_EL_USAC_CP_POSSIBLE) {
2300             complexStereoPredPossible = 1;
2301             if (self->cpeStaticData[el2] == NULL) {
2302               self->cpeStaticData[el2] = GetCpePersistentData();
2303               if (self->cpeStaticData[el2] == NULL) {
2304                 goto bail;
2305               }
2306             }
2307           }
2308 
2309           for (ch2 = 0; ch2 < elCh; ch2++) {
2310             /* Hook element specific cpeStaticData into channel specific
2311              * aacDecoderStaticChannelInfo */
2312             self->pAacDecoderStaticChannelInfo[ch]->pCpeStaticData =
2313                 self->cpeStaticData[el2];
2314             if (self->pAacDecoderStaticChannelInfo[ch]->pCpeStaticData !=
2315                 NULL) {
2316               self->pAacDecoderStaticChannelInfo[ch]
2317                   ->pCpeStaticData->jointStereoPersistentData
2318                   .spectralCoeffs[ch2] =
2319                   self->pAacDecoderStaticChannelInfo[ch]
2320                       ->concealmentInfo.spectralCoefficient;
2321               self->pAacDecoderStaticChannelInfo[ch]
2322                   ->pCpeStaticData->jointStereoPersistentData.specScale[ch2] =
2323                   self->pAacDecoderStaticChannelInfo[ch]
2324                       ->concealmentInfo.specScale;
2325               self->pAacDecoderStaticChannelInfo[ch]
2326                   ->pCpeStaticData->jointStereoPersistentData.scratchBuffer =
2327                   (FIXP_DBL *)self->pTimeData2;
2328             }
2329             chIdx++;
2330             ch++;
2331           } /* for each channel in current element */
2332           if (complexStereoPredPossible && (elCh == 2)) {
2333             /* needed once for all channels */
2334             if (self->pAacDecoderChannelInfo[ch - 1]
2335                     ->pComStaticData->cplxPredictionData == NULL) {
2336               self->pAacDecoderChannelInfo[ch - 1]
2337                   ->pComStaticData->cplxPredictionData =
2338                   GetCplxPredictionData();
2339             }
2340             if (self->pAacDecoderChannelInfo[ch - 1]
2341                     ->pComStaticData->cplxPredictionData == NULL) {
2342               goto bail;
2343             }
2344           }
2345           if (elCh > 0) {
2346             self->pAacDecoderStaticChannelInfo[ch - elCh]->nfRandomSeed =
2347                 (ULONG)0x3039;
2348             if (self->elements[el2] == ID_USAC_CPE) {
2349               if (asc->m_sc.m_usacConfig.element[el2].m_stereoConfigIndex !=
2350                   1) {
2351                 self->pAacDecoderStaticChannelInfo[ch - elCh + 1]
2352                     ->nfRandomSeed = (ULONG)0x10932;
2353               }
2354             }
2355           }
2356         } /* for each element */
2357       }
2358 
2359       if (ascChannels != self->aacChannels) {
2360         /* Make allocated channel count persistent in decoder context. */
2361         self->aacChannels = aacChannelsOffset + ch;
2362       }
2363     }
2364 
2365     if (usacResidualDelayCompSamples) {
2366       INT delayErr = FDK_Delay_Create(&self->usacResidualDelay,
2367                                       (USHORT)usacResidualDelayCompSamples, 1);
2368       if (delayErr) {
2369         goto bail;
2370       }
2371     }
2372 
2373     /* Make amount of signalled channels persistent in decoder context. */
2374     self->ascChannels[streamIndex] = ascChannels;
2375     /* Init the previous channel count values. This is required to avoid a
2376        mismatch of memory accesses in the error concealment module and the
2377        allocated channel structures in this function. */
2378     self->aacChannelsPrev = 0;
2379   }
2380 
2381   if (self->pAacDecoderChannelInfo[0] != NULL) {
2382     self->pDrmBsBuffer = self->pAacDecoderChannelInfo[0]
2383                              ->pComStaticData->pWorkBufferCore1->DrmBsBuffer;
2384     self->drmBsBufferSize = DRM_BS_BUFFER_SIZE;
2385   }
2386 
2387   /* Update structures */
2388   if (*configChanged) {
2389     /* Things to be done for each channel, which do not involve allocating
2390        memory. Doing these things only on the channels needed for the current
2391        configuration (ascChannels) could lead to memory access violation later
2392        (error concealment). */
2393     int ch = 0;
2394     int chIdx = 0;
2395     for (int _ch = 0; _ch < self->ascChannels[streamIndex]; _ch++) {
2396       switch (self->streamInfo.aot) {
2397         case AOT_ER_AAC_ELD:
2398         case AOT_ER_AAC_LD:
2399           self->pAacDecoderChannelInfo[ch]->granuleLength =
2400               self->streamInfo.aacSamplesPerFrame;
2401           break;
2402         default:
2403           self->pAacDecoderChannelInfo[ch]->granuleLength =
2404               self->streamInfo.aacSamplesPerFrame / 8;
2405           break;
2406       }
2407       self->pAacDecoderChannelInfo[ch]->renderMode = initRenderMode;
2408 
2409       mdct_init(&self->pAacDecoderStaticChannelInfo[ch]->IMdct,
2410                 self->pAacDecoderStaticChannelInfo[ch]->pOverlapBuffer,
2411                 OverlapBufferSize);
2412 
2413       self->pAacDecoderStaticChannelInfo[ch]->last_core_mode = FD_LONG;
2414       self->pAacDecoderStaticChannelInfo[ch]->last_lpd_mode = 255;
2415 
2416       self->pAacDecoderStaticChannelInfo[ch]->last_tcx_pitch = L_DIV;
2417 
2418       /* Reset DRC control data for this channel */
2419       aacDecoder_drcInitChannelData(
2420           &self->pAacDecoderStaticChannelInfo[ch]->drcData);
2421 
2422       /* Delete mixdown metadata from the past */
2423       pcmDmx_Reset(self->hPcmUtils, PCMDMX_RESET_BS_DATA);
2424 
2425       /* Reset concealment only if ASC changed. Otherwise it will be done with
2426          any config callback. E.g. every time the LATM SMC is present. */
2427       CConcealment_InitChannelData(
2428           &self->pAacDecoderStaticChannelInfo[ch]->concealmentInfo,
2429           &self->concealCommonData, initRenderMode,
2430           self->streamInfo.aacSamplesPerFrame);
2431       ch++;
2432       chIdx++;
2433     }
2434   }
2435 
2436   if (*configChanged) {
2437     int drcDecSampleRate, drcDecFrameSize;
2438 
2439     if (self->streamInfo.extSamplingRate != 0) {
2440       drcDecSampleRate = self->streamInfo.extSamplingRate;
2441       drcDecFrameSize = (self->streamInfo.aacSamplesPerFrame *
2442                          self->streamInfo.extSamplingRate) /
2443                         self->streamInfo.aacSampleRate;
2444     } else {
2445       drcDecSampleRate = self->streamInfo.aacSampleRate;
2446       drcDecFrameSize = self->streamInfo.aacSamplesPerFrame;
2447     }
2448 
2449     if (FDK_drcDec_Init(self->hUniDrcDecoder, drcDecFrameSize, drcDecSampleRate,
2450                         self->aacChannels) != 0)
2451       goto bail;
2452   }
2453 
2454   if (*configChanged) {
2455     if (asc->m_aot == AOT_USAC) {
2456       aacDecoder_drcDisable(self->hDrcInfo);
2457     }
2458   }
2459 
2460   if (asc->m_aot == AOT_USAC) {
2461     pcmLimiter_SetAttack(self->hLimiter, (5));
2462     pcmLimiter_SetThreshold(self->hLimiter, FL2FXCONST_DBL(0.89125094f));
2463   }
2464 
2465   CAacDecoder_AcceptFlags(self, asc, flags, elFlags, streamIndex,
2466                           elementOffset);
2467   self->sbrEnabled = sbrEnabled;
2468   self->sbrEnabledPrev = sbrEnabledPrev;
2469   self->mpsEnableCurr = mpsEnableCurr;
2470 
2471   /* Update externally visible copy of flags */
2472   self->streamInfo.flags = self->flags[0];
2473 
2474   return err;
2475 
2476 bail:
2477   CAacDecoder_DeInit(self, 0);
2478   return AAC_DEC_OUT_OF_MEMORY;
2479 }
2480 
CAacDecoder_DecodeFrame(HANDLE_AACDECODER self,const UINT flags,PCM_DEC * pTimeData,const INT timeDataSize,const int timeDataChannelOffset)2481 LINKSPEC_CPP AAC_DECODER_ERROR CAacDecoder_DecodeFrame(
2482     HANDLE_AACDECODER self, const UINT flags, PCM_DEC *pTimeData,
2483     const INT timeDataSize, const int timeDataChannelOffset) {
2484   AAC_DECODER_ERROR ErrorStatus = AAC_DEC_OK;
2485 
2486   CProgramConfig *pce;
2487   HANDLE_FDK_BITSTREAM bs = transportDec_GetBitstream(self->hInput, 0);
2488 
2489   MP4_ELEMENT_ID type = ID_NONE; /* Current element type */
2490   INT aacChannels = 0; /* Channel counter for channels found in the bitstream */
2491   const int streamIndex = 0; /* index of the current substream */
2492 
2493   INT auStartAnchor = (INT)FDKgetValidBits(
2494       bs); /* AU start bit buffer position for AU byte alignment */
2495 
2496   INT checkSampleRate = self->streamInfo.aacSampleRate;
2497 
2498   INT CConceal_TDFading_Applied[(8)] = {
2499       0}; /* Initialize status of Time Domain fading */
2500 
2501   if (self->aacChannels <= 0) {
2502     return AAC_DEC_UNSUPPORTED_CHANNELCONFIG;
2503   }
2504 
2505   /* Any supported base layer valid AU will require more than 16 bits. */
2506   if ((transportDec_GetAuBitsRemaining(self->hInput, 0) < 15) &&
2507       (flags & (AACDEC_CONCEAL | AACDEC_FLUSH)) == 0) {
2508     self->frameOK = 0;
2509     ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
2510   }
2511 
2512   /* Reset Program Config structure */
2513   pce = &self->pce;
2514   CProgramConfig_Reset(pce);
2515 
2516   CAacDecoder_AncDataReset(&self->ancData);
2517   if (!(flags & (AACDEC_CONCEAL | AACDEC_FLUSH)) &&
2518       !(self->flags[0] & (AC_USAC | AC_RSV603DA))) {
2519     int ch;
2520     if (self->streamInfo.channelConfig == 0) {
2521       /* Init Channel/Element mapping table */
2522       for (ch = 0; ch < (8); ch++) {
2523         self->chMapping[ch] = 255;
2524       }
2525       if (!CProgramConfig_IsValid(pce)) {
2526         int el;
2527         for (el = 0; el < (3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) + 1);
2528              el++) {
2529           self->elements[el] = ID_NONE;
2530         }
2531       }
2532     }
2533   }
2534 
2535   if (self->downscaleFactor > 1 && (self->flags[0] & AC_ELD)) {
2536     self->flags[0] |= AC_ELD_DOWNSCALE;
2537   } else {
2538     self->flags[0] &= ~AC_ELD_DOWNSCALE;
2539   }
2540   /* unsupported dsf (aacSampleRate has not yet been divided by dsf) -> divide
2541    */
2542   if (self->downscaleFactorInBS > 1 &&
2543       (self->flags[0] & AC_ELD_DOWNSCALE) == 0) {
2544     checkSampleRate =
2545         self->streamInfo.aacSampleRate / self->downscaleFactorInBS;
2546   }
2547 
2548   /* Check sampling frequency  */
2549   if (self->streamInfo.aacSampleRate <= 0) {
2550     /* Instance maybe uninitialized! */
2551     return AAC_DEC_UNSUPPORTED_SAMPLINGRATE;
2552   }
2553   switch (checkSampleRate) {
2554     case 96000:
2555     case 88200:
2556     case 64000:
2557     case 16000:
2558     case 12000:
2559     case 11025:
2560     case 8000:
2561     case 7350:
2562     case 48000:
2563     case 44100:
2564     case 32000:
2565     case 24000:
2566     case 22050:
2567       break;
2568     default:
2569       if (!(self->flags[0] & (AC_USAC | AC_RSVD50 | AC_RSV603DA))) {
2570         return AAC_DEC_UNSUPPORTED_SAMPLINGRATE;
2571       }
2572       break;
2573   }
2574 
2575   if (flags & AACDEC_CLRHIST) {
2576     if (!(self->flags[0] & AC_USAC)) {
2577       int ch;
2578       /* Clear history */
2579       for (ch = 0; ch < self->aacChannels; ch++) {
2580         /* Reset concealment */
2581         CConcealment_InitChannelData(
2582             &self->pAacDecoderStaticChannelInfo[ch]->concealmentInfo,
2583             &self->concealCommonData,
2584             self->pAacDecoderChannelInfo[0]->renderMode,
2585             self->streamInfo.aacSamplesPerFrame);
2586         /* Clear overlap-add buffers to avoid clicks. */
2587         FDKmemclear(self->pAacDecoderStaticChannelInfo[ch]->pOverlapBuffer,
2588                     OverlapBufferSize * sizeof(FIXP_DBL));
2589       }
2590       if (self->streamInfo.channelConfig > 0) {
2591         /* Declare the possibly adopted old PCE (with outdated metadata)
2592          * invalid. */
2593         CProgramConfig_Init(pce);
2594       }
2595     }
2596   }
2597 
2598   int pceRead = 0; /* Flag indicating a PCE in the current raw_data_block() */
2599 
2600   INT hdaacDecoded = 0;
2601   MP4_ELEMENT_ID previous_element =
2602       ID_END; /* Last element ID (required for extension payload mapping */
2603   UCHAR previous_element_index = 0; /* Canonical index of last element */
2604   int element_count =
2605       0; /* Element counter for elements found in the bitstream */
2606   int channel_element_count = 0; /* Channel element counter */
2607   MP4_ELEMENT_ID
2608   channel_elements[(3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) +
2609                     1)];     /* Channel elements in bit stream order. */
2610   int el_cnt[ID_LAST] = {0}; /* element counter ( robustness ) */
2611   int element_count_prev_streams =
2612       0; /* Element count of all previous sub streams. */
2613 
2614   while ((type != ID_END) && (!(flags & (AACDEC_CONCEAL | AACDEC_FLUSH))) &&
2615          self->frameOK) {
2616     int el_channels;
2617 
2618     if (!(self->flags[0] &
2619           (AC_USAC | AC_RSVD50 | AC_RSV603DA | AC_ELD | AC_SCALABLE | AC_ER)))
2620       type = (MP4_ELEMENT_ID)FDKreadBits(bs, 3);
2621     else {
2622       if (element_count >= (3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) + 1)) {
2623         self->frameOK = 0;
2624         ErrorStatus = AAC_DEC_PARSE_ERROR;
2625         break;
2626       }
2627       type = self->elements[element_count];
2628     }
2629 
2630     if ((self->flags[streamIndex] & (AC_USAC | AC_RSVD50) &&
2631          element_count == 0) ||
2632         (self->flags[streamIndex] & AC_RSV603DA)) {
2633       self->flags[streamIndex] &= ~AC_INDEP;
2634 
2635       if (FDKreadBit(bs)) {
2636         self->flags[streamIndex] |= AC_INDEP;
2637       }
2638 
2639       int ch = aacChannels;
2640       for (int chIdx = aacChannels; chIdx < self->ascChannels[streamIndex];
2641            chIdx++) {
2642         {
2643           /* Robustness check */
2644           if (ch >= self->aacChannels) {
2645             return AAC_DEC_UNKNOWN;
2646           }
2647 
2648           /* if last frame was broken and this frame is no independent frame,
2649            * correct decoding is impossible we need to trigger concealment */
2650           if ((CConcealment_GetLastFrameOk(
2651                    &self->pAacDecoderStaticChannelInfo[ch]->concealmentInfo,
2652                    1) == 0) &&
2653               !(self->flags[streamIndex] & AC_INDEP)) {
2654             self->frameOK = 0;
2655           }
2656           ch++;
2657         }
2658       }
2659     }
2660 
2661     if ((INT)FDKgetValidBits(bs) < 0) {
2662       self->frameOK = 0;
2663     }
2664 
2665     switch (type) {
2666       case ID_SCE:
2667       case ID_CPE:
2668       case ID_LFE:
2669       case ID_USAC_SCE:
2670       case ID_USAC_CPE:
2671       case ID_USAC_LFE:
2672         if (element_count >= (3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) + 1)) {
2673           self->frameOK = 0;
2674           ErrorStatus = AAC_DEC_PARSE_ERROR;
2675           break;
2676         }
2677 
2678         el_channels = CAacDecoder_GetELChannels(
2679             type, self->usacStereoConfigIndex[element_count]);
2680 
2681         /*
2682           Consistency check
2683          */
2684         {
2685           int totalAscChannels = 0;
2686 
2687           for (int i = 0; i < (1 * 1); i++) {
2688             totalAscChannels += self->ascChannels[i];
2689           }
2690           if ((el_cnt[type] >= (totalAscChannels >> (el_channels - 1))) ||
2691               (aacChannels > (totalAscChannels - el_channels))) {
2692             ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
2693             self->frameOK = 0;
2694             break;
2695           }
2696         }
2697 
2698         if (!(self->flags[streamIndex] & (AC_USAC | AC_RSVD50 | AC_RSV603DA))) {
2699           int ch;
2700           for (ch = 0; ch < el_channels; ch += 1) {
2701             CPns_ResetData(&self->pAacDecoderChannelInfo[aacChannels + ch]
2702                                 ->data.aac.PnsData,
2703                            &self->pAacDecoderChannelInfo[aacChannels + ch]
2704                                 ->pComData->pnsInterChannelData);
2705           }
2706         }
2707 
2708         if (self->frameOK) {
2709           ErrorStatus = CChannelElement_Read(
2710               bs, &self->pAacDecoderChannelInfo[aacChannels],
2711               &self->pAacDecoderStaticChannelInfo[aacChannels],
2712               self->streamInfo.aot, &self->samplingRateInfo[streamIndex],
2713               self->flags[streamIndex], self->elFlags[element_count],
2714               self->streamInfo.aacSamplesPerFrame, el_channels,
2715               self->streamInfo.epConfig, self->hInput);
2716           if (ErrorStatus != AAC_DEC_OK) {
2717             self->frameOK = 0;
2718           }
2719         }
2720 
2721         if (self->frameOK) {
2722           /* Lookup the element and decode it only if it belongs to the current
2723            * program */
2724           if (CProgramConfig_LookupElement(
2725                   pce, self->streamInfo.channelConfig,
2726                   self->pAacDecoderChannelInfo[aacChannels]->ElementInstanceTag,
2727                   aacChannels, self->chMapping, self->channelType,
2728                   self->channelIndices, (8), &previous_element_index,
2729                   self->elements, type)) {
2730             channel_elements[channel_element_count++] = type;
2731             aacChannels += el_channels;
2732           } else {
2733             self->frameOK = 0;
2734           }
2735           /* Create SBR element for SBR for upsampling for LFE elements,
2736              and if SBR was implicitly signaled, because the first frame(s)
2737              may not contain SBR payload (broken encoder, bit errors). */
2738           if (self->frameOK &&
2739               ((self->flags[streamIndex] & AC_SBR_PRESENT) ||
2740                (self->sbrEnabled == 1)) &&
2741               !(self->flags[streamIndex] &
2742                 AC_USAC) /* Is done during explicit config set up */
2743           ) {
2744             SBR_ERROR sbrError;
2745             UCHAR configMode = 0;
2746             UCHAR configChanged = 0;
2747             configMode |= AC_CM_ALLOC_MEM;
2748 
2749             sbrError = sbrDecoder_InitElement(
2750                 self->hSbrDecoder, self->streamInfo.aacSampleRate,
2751                 self->streamInfo.extSamplingRate,
2752                 self->streamInfo.aacSamplesPerFrame, self->streamInfo.aot, type,
2753                 previous_element_index, 2, /* Signalize that harmonicSBR shall
2754                                               be ignored in the config change
2755                                               detection */
2756                 0, configMode, &configChanged, self->downscaleFactor);
2757             if (sbrError != SBRDEC_OK) {
2758               /* Do not try to apply SBR because initializing the element
2759                * failed. */
2760               self->sbrEnabled = 0;
2761             }
2762           }
2763         }
2764 
2765         el_cnt[type]++;
2766         if (self->frameOK && (self->flags[streamIndex] & AC_USAC) &&
2767             (type == ID_USAC_CPE || type == ID_USAC_SCE)) {
2768           ErrorStatus = aacDecoder_ParseExplicitMpsAndSbr(
2769               self, bs, previous_element, previous_element_index, element_count,
2770               el_cnt);
2771           if (ErrorStatus != AAC_DEC_OK) {
2772             self->frameOK = 0;
2773           }
2774         }
2775         break;
2776 
2777       case ID_CCE:
2778         /*
2779           Consistency check
2780         */
2781         if (el_cnt[type] > self->ascChannels[streamIndex]) {
2782           ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
2783           self->frameOK = 0;
2784           break;
2785         }
2786 
2787         if (self->frameOK) {
2788           CAacDecoderCommonData commonData;
2789           CAacDecoderCommonStaticData commonStaticData;
2790           CWorkBufferCore1 workBufferCore1;
2791           commonStaticData.pWorkBufferCore1 = &workBufferCore1;
2792           /* memory for spectral lines temporal on scratch */
2793           C_AALLOC_SCRATCH_START(mdctSpec, FIXP_DBL, 1024);
2794 
2795           /* create dummy channel for CCE parsing on stack */
2796           CAacDecoderChannelInfo tmpAacDecoderChannelInfo,
2797               *pTmpAacDecoderChannelInfo;
2798 
2799           FDKmemclear(mdctSpec, 1024 * sizeof(FIXP_DBL));
2800 
2801           tmpAacDecoderChannelInfo.pDynData = commonData.pAacDecoderDynamicData;
2802           tmpAacDecoderChannelInfo.pComData = &commonData;
2803           tmpAacDecoderChannelInfo.pComStaticData = &commonStaticData;
2804           tmpAacDecoderChannelInfo.pSpectralCoefficient =
2805               (SPECTRAL_PTR)mdctSpec;
2806           /* Assume AAC-LC */
2807           tmpAacDecoderChannelInfo.granuleLength =
2808               self->streamInfo.aacSamplesPerFrame / 8;
2809           /* Reset PNS data. */
2810           CPns_ResetData(
2811               &tmpAacDecoderChannelInfo.data.aac.PnsData,
2812               &tmpAacDecoderChannelInfo.pComData->pnsInterChannelData);
2813           pTmpAacDecoderChannelInfo = &tmpAacDecoderChannelInfo;
2814           /* do CCE parsing */
2815           ErrorStatus = CChannelElement_Read(
2816               bs, &pTmpAacDecoderChannelInfo, NULL, self->streamInfo.aot,
2817               &self->samplingRateInfo[streamIndex], self->flags[streamIndex],
2818               AC_EL_GA_CCE, self->streamInfo.aacSamplesPerFrame, 1,
2819               self->streamInfo.epConfig, self->hInput);
2820 
2821           C_AALLOC_SCRATCH_END(mdctSpec, FIXP_DBL, 1024);
2822 
2823           if (ErrorStatus) {
2824             self->frameOK = 0;
2825           }
2826 
2827           if (self->frameOK) {
2828             /* Lookup the element and decode it only if it belongs to the
2829              * current program */
2830             if (CProgramConfig_LookupElement(
2831                     pce, self->streamInfo.channelConfig,
2832                     pTmpAacDecoderChannelInfo->ElementInstanceTag, 0,
2833                     self->chMapping, self->channelType, self->channelIndices,
2834                     (8), &previous_element_index, self->elements, type)) {
2835               /* decoding of CCE not supported */
2836             } else {
2837               self->frameOK = 0;
2838             }
2839           }
2840         }
2841         el_cnt[type]++;
2842         break;
2843 
2844       case ID_DSE: {
2845         UCHAR element_instance_tag;
2846 
2847         CDataStreamElement_Read(self, bs, &element_instance_tag, auStartAnchor);
2848 
2849         if (!CProgramConfig_LookupElement(
2850                 pce, self->streamInfo.channelConfig, element_instance_tag, 0,
2851                 self->chMapping, self->channelType, self->channelIndices, (8),
2852                 &previous_element_index, self->elements, type)) {
2853           /* most likely an error in bitstream occured */
2854           // self->frameOK = 0;
2855         }
2856       } break;
2857 
2858       case ID_PCE: {
2859         int result = CProgramConfigElement_Read(bs, self->hInput, pce,
2860                                                 self->streamInfo.channelConfig,
2861                                                 auStartAnchor);
2862         if (result < 0) {
2863           /* Something went wrong */
2864           ErrorStatus = AAC_DEC_PARSE_ERROR;
2865           self->frameOK = 0;
2866         } else if (result > 1) {
2867           /* Built element table */
2868           int elIdx = CProgramConfig_GetElementTable(
2869               pce, self->elements, (((8)) + (8)), &self->chMapIndex);
2870           /* Reset the remaining tabs */
2871           for (; elIdx < (3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) + 1);
2872                elIdx++) {
2873             self->elements[elIdx] = ID_NONE;
2874           }
2875           /* Make new number of channel persistent */
2876           self->ascChannels[streamIndex] = pce->NumChannels;
2877           /* If PCE is not first element conceal this frame to avoid
2878            * inconsistencies */
2879           if (element_count != 0) {
2880             self->frameOK = 0;
2881           }
2882         }
2883         pceRead = (result >= 0) ? 1 : 0;
2884       } break;
2885 
2886       case ID_FIL: {
2887         int bitCnt = FDKreadBits(bs, 4); /* bs_count */
2888 
2889         if (bitCnt == 15) {
2890           int esc_count = FDKreadBits(bs, 8); /* bs_esc_count */
2891           bitCnt = esc_count + 14;
2892         }
2893 
2894         /* Convert to bits */
2895         bitCnt <<= 3;
2896 
2897         while (bitCnt > 0) {
2898           ErrorStatus = CAacDecoder_ExtPayloadParse(
2899               self, bs, &bitCnt, previous_element, previous_element_index, 1);
2900           if (ErrorStatus != AAC_DEC_OK) {
2901             self->frameOK = 0;
2902             break;
2903           }
2904         }
2905       } break;
2906 
2907       case ID_EXT:
2908         if (element_count >= (3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) + 1)) {
2909           self->frameOK = 0;
2910           ErrorStatus = AAC_DEC_PARSE_ERROR;
2911           break;
2912         }
2913 
2914         ErrorStatus = aacDecoder_ParseExplicitMpsAndSbr(
2915             self, bs, previous_element, previous_element_index, element_count,
2916             el_cnt);
2917         break;
2918 
2919       case ID_USAC_EXT: {
2920         if ((element_count - element_count_prev_streams) >=
2921             TP_USAC_MAX_ELEMENTS) {
2922           self->frameOK = 0;
2923           ErrorStatus = AAC_DEC_PARSE_ERROR;
2924           break;
2925         }
2926         /* parse extension element payload
2927            q.v. rsv603daExtElement() ISO/IEC DIS 23008-3  Table 30
2928            or   UsacExElement() ISO/IEC FDIS 23003-3:2011(E)  Table 21
2929          */
2930         int usacExtElementPayloadLength;
2931         /* int usacExtElementStart, usacExtElementStop; */
2932 
2933         if (FDKreadBit(bs)) {   /* usacExtElementPresent */
2934           if (FDKreadBit(bs)) { /* usacExtElementUseDefaultLength */
2935             usacExtElementPayloadLength =
2936                 self->pUsacConfig[streamIndex]
2937                     ->element[element_count - element_count_prev_streams]
2938                     .extElement.usacExtElementDefaultLength;
2939           } else {
2940             usacExtElementPayloadLength = FDKreadBits(bs, 8);
2941             if (usacExtElementPayloadLength == (UINT)(1 << 8) - 1) {
2942               UINT valueAdd = FDKreadBits(bs, 16);
2943               usacExtElementPayloadLength += (INT)valueAdd - 2;
2944             }
2945           }
2946           if (usacExtElementPayloadLength > 0) {
2947             int usacExtBitPos;
2948 
2949             if (self->pUsacConfig[streamIndex]
2950                     ->element[element_count - element_count_prev_streams]
2951                     .extElement.usacExtElementPayloadFrag) {
2952               /* usacExtElementStart = */ FDKreadBit(bs);
2953               /* usacExtElementStop = */ FDKreadBit(bs);
2954             } else {
2955               /* usacExtElementStart = 1; */
2956               /* usacExtElementStop = 1; */
2957             }
2958 
2959             usacExtBitPos = (INT)FDKgetValidBits(bs);
2960 
2961             USAC_EXT_ELEMENT_TYPE usacExtElementType =
2962                 self->pUsacConfig[streamIndex]
2963                     ->element[element_count - element_count_prev_streams]
2964                     .extElement.usacExtElementType;
2965 
2966             switch (usacExtElementType) {
2967               case ID_EXT_ELE_UNI_DRC: /* uniDrcGain() */
2968                 if (streamIndex == 0) {
2969                   int drcErr;
2970 
2971                   drcErr = FDK_drcDec_ReadUniDrcGain(self->hUniDrcDecoder, bs);
2972                   if (drcErr != 0) {
2973                     ErrorStatus = AAC_DEC_PARSE_ERROR;
2974                   }
2975                 }
2976                 break;
2977 
2978               default:
2979                 break;
2980             }
2981 
2982             /* Skip any remaining bits of extension payload */
2983             usacExtBitPos = (usacExtElementPayloadLength * 8) -
2984                             (usacExtBitPos - (INT)FDKgetValidBits(bs));
2985             if (usacExtBitPos < 0) {
2986               self->frameOK = 0;
2987               ErrorStatus = AAC_DEC_PARSE_ERROR;
2988             }
2989             FDKpushBiDirectional(bs, usacExtBitPos);
2990           }
2991         }
2992       } break;
2993       case ID_END:
2994       case ID_USAC_END:
2995         break;
2996 
2997       default:
2998         ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
2999         self->frameOK = 0;
3000         break;
3001     }
3002 
3003     previous_element = type;
3004     element_count++;
3005 
3006   } /* while ( (type != ID_END) ... ) */
3007 
3008   if (!(self->flags[streamIndex] &
3009         (AC_USAC | AC_RSVD50 | AC_RSV603DA | AC_BSAC | AC_LD | AC_ELD | AC_ER |
3010          AC_SCALABLE)) &&
3011       (self->streamInfo.channelConfig == 0) && pce->isValid &&
3012       (ErrorStatus == AAC_DEC_OK) && self->frameOK &&
3013       !(flags & (AACDEC_CONCEAL | AACDEC_FLUSH))) {
3014     /* Check whether all PCE listed element instance tags are present in
3015      * raw_data_block() */
3016     if (!validateElementInstanceTags(
3017             &self->pce, self->pAacDecoderChannelInfo, aacChannels,
3018             channel_elements,
3019             fMin(channel_element_count, (int)(sizeof(channel_elements) /
3020                                               sizeof(*channel_elements))))) {
3021       ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
3022       self->frameOK = 0;
3023     }
3024   }
3025 
3026   if (!(flags & (AACDEC_CONCEAL | AACDEC_FLUSH))) {
3027     /* float decoder checks if bitsLeft is in range 0-7; only prerollAUs are
3028      * byteAligned with respect to the first bit */
3029     /* Byte alignment with respect to the first bit of the raw_data_block(). */
3030     if (!(self->flags[streamIndex] & (AC_RSVD50 | AC_USAC)) ||
3031         (self->prerollAULength[self->accessUnit]) /* indicates preroll */
3032     ) {
3033       FDKbyteAlign(bs, auStartAnchor);
3034     }
3035 
3036     /* Check if all bits of the raw_data_block() have been read. */
3037     if (transportDec_GetAuBitsTotal(self->hInput, 0) > 0) {
3038       INT unreadBits = transportDec_GetAuBitsRemaining(self->hInput, 0);
3039       /* for pre-roll frames pre-roll length has to be used instead of total AU
3040        * lenght */
3041       /* unreadBits regarding preroll bounds */
3042       if (self->prerollAULength[self->accessUnit]) {
3043         unreadBits = unreadBits - transportDec_GetAuBitsTotal(self->hInput, 0) +
3044                      (INT)self->prerollAULength[self->accessUnit];
3045       }
3046       if (((self->flags[streamIndex] & (AC_RSVD50 | AC_USAC)) &&
3047            ((unreadBits < 0) || (unreadBits > 7)) &&
3048            !(self->prerollAULength[self->accessUnit])) ||
3049           ((!(self->flags[streamIndex] & (AC_RSVD50 | AC_USAC)) ||
3050             (self->prerollAULength[self->accessUnit])) &&
3051            (unreadBits != 0))) {
3052         if ((((unreadBits < 0) || (unreadBits > 7)) && self->frameOK) &&
3053             ((transportDec_GetFormat(self->hInput) == TT_DRM) &&
3054              (self->flags[streamIndex] & AC_USAC))) {
3055           /* Set frame OK because of fill bits. */
3056           self->frameOK = 1;
3057         } else {
3058           self->frameOK = 0;
3059         }
3060 
3061         /* Do not overwrite current error */
3062         if (ErrorStatus == AAC_DEC_OK && self->frameOK == 0) {
3063           ErrorStatus = AAC_DEC_PARSE_ERROR;
3064         }
3065         /* Always put the bitbuffer at the right position after the current
3066          * Access Unit. */
3067         FDKpushBiDirectional(bs, unreadBits);
3068       }
3069     }
3070 
3071     /* Check the last element. The terminator (ID_END) has to be the last one
3072      * (even if ER syntax is used). */
3073     if (self->frameOK && type != ID_END) {
3074       /* Do not overwrite current error */
3075       if (ErrorStatus == AAC_DEC_OK) {
3076         ErrorStatus = AAC_DEC_PARSE_ERROR;
3077       }
3078       self->frameOK = 0;
3079     }
3080   }
3081 
3082   if (!(flags & (AACDEC_CONCEAL | AACDEC_FLUSH)) && self->frameOK) {
3083     channel_elements[channel_element_count++] = ID_END;
3084   }
3085   element_count = 0;
3086   aacChannels = 0;
3087   type = ID_NONE;
3088   previous_element_index = 0;
3089 
3090   while (type != ID_END &&
3091          element_count < (3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) + 1)) {
3092     int el_channels;
3093 
3094     if ((flags & (AACDEC_CONCEAL | AACDEC_FLUSH)) || !self->frameOK) {
3095       channel_elements[element_count] = self->elements[element_count];
3096       if (channel_elements[element_count] == ID_NONE) {
3097         channel_elements[element_count] = ID_END;
3098       }
3099     }
3100 
3101     if (self->flags[streamIndex] & (AC_USAC | AC_RSV603DA | AC_BSAC)) {
3102       type = self->elements[element_count];
3103     } else {
3104       type = channel_elements[element_count];
3105     }
3106 
3107     if (!(flags & (AACDEC_CONCEAL | AACDEC_FLUSH)) && self->frameOK) {
3108       switch (type) {
3109         case ID_SCE:
3110         case ID_CPE:
3111         case ID_LFE:
3112         case ID_USAC_SCE:
3113         case ID_USAC_CPE:
3114         case ID_USAC_LFE:
3115 
3116           el_channels = CAacDecoder_GetELChannels(
3117               type, self->usacStereoConfigIndex[element_count]);
3118 
3119           if (!hdaacDecoded) {
3120             if (self->pAacDecoderStaticChannelInfo[aacChannels]
3121                     ->pCpeStaticData != NULL) {
3122               self->pAacDecoderStaticChannelInfo[aacChannels]
3123                   ->pCpeStaticData->jointStereoPersistentData.scratchBuffer =
3124                   (FIXP_DBL *)pTimeData;
3125             }
3126             CChannelElement_Decode(
3127                 &self->pAacDecoderChannelInfo[aacChannels],
3128                 &self->pAacDecoderStaticChannelInfo[aacChannels],
3129                 &self->samplingRateInfo[streamIndex], self->flags[streamIndex],
3130                 self->elFlags[element_count], el_channels);
3131           }
3132           aacChannels += el_channels;
3133           break;
3134         case ID_NONE:
3135           type = ID_END;
3136           break;
3137         default:
3138           break;
3139       }
3140     }
3141     element_count++;
3142   }
3143 
3144   /* More AAC channels than specified by the ASC not allowed. */
3145   if ((aacChannels == 0 || aacChannels > self->aacChannels) &&
3146       !(flags & (AACDEC_CONCEAL | AACDEC_FLUSH))) {
3147     /* Do not overwrite current error */
3148     if (ErrorStatus == AAC_DEC_OK) {
3149       ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
3150     }
3151     self->frameOK = 0;
3152     aacChannels = 0;
3153   }
3154 
3155   if (!(flags & (AACDEC_CONCEAL | AACDEC_FLUSH))) {
3156     if (TRANSPORTDEC_OK != transportDec_CrcCheck(self->hInput)) {
3157       ErrorStatus = AAC_DEC_CRC_ERROR;
3158       self->frameOK = 0;
3159     }
3160   }
3161 
3162   /* Ensure that in case of concealment a proper error status is set. */
3163   if ((self->frameOK == 0) && (ErrorStatus == AAC_DEC_OK)) {
3164     ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
3165   }
3166 
3167   if (self->frameOK && (flags & AACDEC_FLUSH)) {
3168     aacChannels = self->aacChannelsPrev;
3169     /* Because the downmix could be active, its necessary to restore the channel
3170      * type and indices. */
3171     FDKmemcpy(self->channelType, self->channelTypePrev,
3172               (8) * sizeof(AUDIO_CHANNEL_TYPE)); /* restore */
3173     FDKmemcpy(self->channelIndices, self->channelIndicesPrev,
3174               (8) * sizeof(UCHAR)); /* restore */
3175     self->sbrEnabled = self->sbrEnabledPrev;
3176   } else {
3177     /* store or restore the number of channels and the corresponding info */
3178     if (self->frameOK && !(flags & AACDEC_CONCEAL)) {
3179       self->aacChannelsPrev = aacChannels; /* store */
3180       FDKmemcpy(self->channelTypePrev, self->channelType,
3181                 (8) * sizeof(AUDIO_CHANNEL_TYPE)); /* store */
3182       FDKmemcpy(self->channelIndicesPrev, self->channelIndices,
3183                 (8) * sizeof(UCHAR)); /* store */
3184       self->sbrEnabledPrev = self->sbrEnabled;
3185     } else {
3186       if (self->aacChannels > 0) {
3187         if ((self->buildUpStatus == AACDEC_RSV60_BUILD_UP_ON) ||
3188             (self->buildUpStatus == AACDEC_RSV60_BUILD_UP_ON_IN_BAND) ||
3189             (self->buildUpStatus == AACDEC_USAC_BUILD_UP_ON)) {
3190           aacChannels = self->aacChannels;
3191           self->aacChannelsPrev = aacChannels; /* store */
3192         } else {
3193           aacChannels = self->aacChannelsPrev; /* restore */
3194         }
3195         FDKmemcpy(self->channelType, self->channelTypePrev,
3196                   (8) * sizeof(AUDIO_CHANNEL_TYPE)); /* restore */
3197         FDKmemcpy(self->channelIndices, self->channelIndicesPrev,
3198                   (8) * sizeof(UCHAR)); /* restore */
3199         self->sbrEnabled = self->sbrEnabledPrev;
3200       }
3201     }
3202   }
3203 
3204   /* Update number of output channels */
3205   self->streamInfo.aacNumChannels = aacChannels;
3206 
3207   /* Ensure consistency of IS_OUTPUT_VALID() macro. */
3208   if (aacChannels == 0) {
3209     ErrorStatus = AAC_DEC_UNKNOWN;
3210   }
3211 
3212   if (pceRead == 1 && CProgramConfig_IsValid(pce)) {
3213     /* Set matrix mixdown infos if available from PCE. */
3214     pcmDmx_SetMatrixMixdownFromPce(
3215         self->hPcmUtils, pce->MatrixMixdownIndexPresent,
3216         pce->MatrixMixdownIndex, pce->PseudoSurroundEnable);
3217     ;
3218   }
3219 
3220   /* If there is no valid data to transfrom into time domain, return. */
3221   if (!IS_OUTPUT_VALID(ErrorStatus)) {
3222     return ErrorStatus;
3223   }
3224 
3225   /* Setup the output channel mapping. The table below shows the three
3226    * possibilities: # | chCfg | PCE | chMapIndex
3227    *  ---+-------+-----+------------------
3228    *   1 |  > 0  |  no | chCfg
3229    *   2 |   0   | yes | cChCfg
3230    *   3 |   0   |  no | aacChannels || 0
3231    *  ---+-------+-----+--------+------------------
3232    *  Where chCfg is the channel configuration index from ASC and cChCfg is a
3233    * corresponding chCfg derived from a given PCE. The variable aacChannels
3234    * represents the number of channel found during bitstream decoding. Due to
3235    * the structure of the mapping table it can only be used for mapping if its
3236    * value is smaller than 7. Otherwise we use the fallback (0) which is a
3237    * simple pass-through. The possibility #3 should appear only with MPEG-2
3238    * (ADTS) streams. This is mode is called "implicit channel mapping".
3239    */
3240   if ((self->streamInfo.channelConfig == 0) && !pce->isValid) {
3241     self->chMapIndex = (aacChannels < 7) ? aacChannels : 0;
3242   }
3243 
3244   /*
3245     Inverse transform
3246   */
3247   {
3248     int c, cIdx;
3249     int mapped, fCopyChMap = 1;
3250     UCHAR drcChMap[(8)];
3251 
3252     if ((self->streamInfo.channelConfig == 0) && CProgramConfig_IsValid(pce)) {
3253       /* ISO/IEC 14496-3 says:
3254            If a PCE is present, the exclude_mask bits correspond to the audio
3255          channels in the SCE, CPE, CCE and LFE syntax elements in the order of
3256          their appearance in the PCE. In the case of a CPE, the first
3257          transmitted mask bit corresponds to the first channel in the CPE, the
3258          second transmitted mask bit to the second channel. In the case of a
3259          CCE, a mask bit is transmitted only if the coupling channel is
3260          specified to be an independently switched coupling channel. Thus we
3261          have to convert the internal channel mapping from "canonical" MPEG to
3262          PCE order: */
3263       UCHAR tmpChMap[(8)];
3264       if (CProgramConfig_GetPceChMap(pce, tmpChMap, (8)) == 0) {
3265         for (c = 0; c < aacChannels; c += 1) {
3266           drcChMap[c] =
3267               (self->chMapping[c] == 255) ? 255 : tmpChMap[self->chMapping[c]];
3268         }
3269         fCopyChMap = 0;
3270       }
3271     }
3272     if (fCopyChMap != 0) {
3273       FDKmemcpy(drcChMap, self->chMapping, (8) * sizeof(UCHAR));
3274     }
3275 
3276     /* Extract DRC control data and map it to channels (without bitstream delay)
3277      */
3278     mapped = aacDecoder_drcProlog(
3279         self->hDrcInfo, bs, self->pAacDecoderStaticChannelInfo,
3280         pce->ElementInstanceTag, drcChMap, aacChannels);
3281     if (mapped > 0) {
3282       if (!(self->flags[streamIndex] & (AC_USAC | AC_RSV603DA))) {
3283         /* If at least one DRC thread has been mapped to a channel there was DRC
3284          * data in the bitstream. */
3285         self->flags[streamIndex] |= AC_DRC_PRESENT;
3286       } else {
3287         ErrorStatus = AAC_DEC_UNSUPPORTED_FORMAT;
3288       }
3289     }
3290     if (self->flags[streamIndex] & (AC_USAC | AC_RSV603DA)) {
3291       aacDecoder_drcDisable(self->hDrcInfo);
3292     }
3293 
3294     /* Create a reverse mapping table */
3295     UCHAR Reverse_chMapping[((8) * 2)];
3296     for (c = 0; c < aacChannels; c++) {
3297       int d;
3298       for (d = 0; d < aacChannels - 1; d++) {
3299         if (self->chMapping[d] == c) {
3300           break;
3301         }
3302       }
3303       Reverse_chMapping[c] = d;
3304     }
3305 
3306     int el;
3307     int el_channels;
3308     c = 0;
3309     cIdx = 0;
3310     el_channels = 0;
3311     for (el = 0; el < element_count; el++) {
3312       int frameOk_butConceal =
3313           0; /* Force frame concealment during mute release active state. */
3314       int concealApplyReturnCode;
3315 
3316       if (self->flags[streamIndex] & (AC_USAC | AC_RSV603DA | AC_BSAC)) {
3317         type = self->elements[el];
3318       } else {
3319         type = channel_elements[el];
3320       }
3321 
3322       {
3323         int nElementChannels;
3324 
3325         nElementChannels =
3326             CAacDecoder_GetELChannels(type, self->usacStereoConfigIndex[el]);
3327 
3328         el_channels += nElementChannels;
3329 
3330         if (nElementChannels == 0) {
3331           continue;
3332         }
3333       }
3334 
3335       int offset;
3336       int elCh = 0;
3337       /* "c" iterates in canonical MPEG channel order */
3338       for (; cIdx < el_channels; c++, cIdx++, elCh++) {
3339         /* Robustness check */
3340         if (c >= aacChannels) {
3341           return AAC_DEC_UNKNOWN;
3342         }
3343 
3344         CAacDecoderChannelInfo *pAacDecoderChannelInfo =
3345             self->pAacDecoderChannelInfo[c];
3346         CAacDecoderStaticChannelInfo *pAacDecoderStaticChannelInfo =
3347             self->pAacDecoderStaticChannelInfo[c];
3348 
3349         /* Setup offset for time buffer traversal. */
3350         {
3351           pAacDecoderStaticChannelInfo =
3352               self->pAacDecoderStaticChannelInfo[Reverse_chMapping[c]];
3353           offset =
3354               FDK_chMapDescr_getMapValue(
3355                   &self->mapDescr, Reverse_chMapping[cIdx], self->chMapIndex) *
3356               timeDataChannelOffset;
3357         }
3358 
3359         if (flags & AACDEC_FLUSH) {
3360           /* Clear pAacDecoderChannelInfo->pSpectralCoefficient because with
3361            * AACDEC_FLUSH set it contains undefined data. */
3362           FDKmemclear(pAacDecoderChannelInfo->pSpectralCoefficient,
3363                       sizeof(FIXP_DBL) * self->streamInfo.aacSamplesPerFrame);
3364         }
3365 
3366         /* if The ics info is not valid and it will be stored and used in the
3367          * following concealment method, mark the frame as erroneous */
3368         {
3369           CIcsInfo *pIcsInfo = &pAacDecoderChannelInfo->icsInfo;
3370           CConcealmentInfo *hConcealmentInfo =
3371               &pAacDecoderStaticChannelInfo->concealmentInfo;
3372           const int mute_release_active =
3373               (self->frameOK && !(flags & AACDEC_CONCEAL)) &&
3374               ((hConcealmentInfo->concealState >= ConcealState_Mute) &&
3375                (hConcealmentInfo->cntValidFrames + 1 <=
3376                 hConcealmentInfo->pConcealParams->numMuteReleaseFrames));
3377           const int icsIsInvalid = (GetScaleFactorBandsTransmitted(pIcsInfo) >
3378                                     GetScaleFactorBandsTotal(pIcsInfo));
3379           const int icsInfoUsedinFadeOut =
3380               !(pAacDecoderChannelInfo->renderMode == AACDEC_RENDER_LPD &&
3381                 pAacDecoderStaticChannelInfo->last_lpd_mode == 0);
3382           if (icsInfoUsedinFadeOut && icsIsInvalid && !mute_release_active) {
3383             self->frameOK = 0;
3384           }
3385         }
3386 
3387         /*
3388           Conceal defective spectral data
3389         */
3390         {
3391           CAacDecoderChannelInfo **ppAacDecoderChannelInfo =
3392               &pAacDecoderChannelInfo;
3393           CAacDecoderStaticChannelInfo **ppAacDecoderStaticChannelInfo =
3394               &pAacDecoderStaticChannelInfo;
3395           {
3396             concealApplyReturnCode = CConcealment_Apply(
3397                 &(*ppAacDecoderStaticChannelInfo)->concealmentInfo,
3398                 *ppAacDecoderChannelInfo, *ppAacDecoderStaticChannelInfo,
3399                 &self->samplingRateInfo[streamIndex],
3400                 self->streamInfo.aacSamplesPerFrame,
3401                 pAacDecoderStaticChannelInfo->last_lpd_mode,
3402                 (self->frameOK && !(flags & AACDEC_CONCEAL)),
3403                 self->flags[streamIndex]);
3404           }
3405         }
3406         if (concealApplyReturnCode == -1) {
3407           frameOk_butConceal = 1;
3408         }
3409 
3410         if (flags & (AACDEC_INTR)) {
3411           /* Reset DRC control data for this channel */
3412           aacDecoder_drcInitChannelData(&pAacDecoderStaticChannelInfo->drcData);
3413         }
3414         if (flags & (AACDEC_CLRHIST)) {
3415           if (!(self->flags[0] & AC_USAC)) {
3416             /* Reset DRC control data for this channel */
3417             aacDecoder_drcInitChannelData(
3418                 &pAacDecoderStaticChannelInfo->drcData);
3419           }
3420         }
3421 
3422         /* The DRC module demands to be called with the gain field holding the
3423          * gain scale. */
3424         self->extGain[0] = (FIXP_DBL)AACDEC_DRC_GAIN_SCALING;
3425 
3426         /* DRC processing */
3427         aacDecoder_drcApply(
3428             self->hDrcInfo, self->hSbrDecoder, pAacDecoderChannelInfo,
3429             &pAacDecoderStaticChannelInfo->drcData, self->extGain, c,
3430             self->streamInfo.aacSamplesPerFrame, self->sbrEnabled
3431 
3432         );
3433 
3434         if (timeDataSize < timeDataChannelOffset * self->aacChannels) {
3435           ErrorStatus = AAC_DEC_OUTPUT_BUFFER_TOO_SMALL;
3436           break;
3437         }
3438         if (self->flushStatus && (self->flushCnt > 0) &&
3439             !(flags & AACDEC_CONCEAL)) {
3440           FDKmemclear(pTimeData + offset,
3441                       sizeof(PCM_DEC) * self->streamInfo.aacSamplesPerFrame);
3442         } else
3443           switch (pAacDecoderChannelInfo->renderMode) {
3444             case AACDEC_RENDER_IMDCT:
3445 
3446               CBlock_FrequencyToTime(
3447                   pAacDecoderStaticChannelInfo, pAacDecoderChannelInfo,
3448                   pTimeData + offset, self->streamInfo.aacSamplesPerFrame,
3449                   (self->frameOK && !(flags & AACDEC_CONCEAL) &&
3450                    !frameOk_butConceal),
3451                   pAacDecoderChannelInfo->pComStaticData->pWorkBufferCore1
3452                       ->mdctOutTemp,
3453                   self->aacOutDataHeadroom, self->elFlags[el], elCh);
3454 
3455               self->extGainDelay = self->streamInfo.aacSamplesPerFrame;
3456               break;
3457             case AACDEC_RENDER_ELDFB: {
3458               CBlock_FrequencyToTimeLowDelay(
3459                   pAacDecoderStaticChannelInfo, pAacDecoderChannelInfo,
3460                   pTimeData + offset, self->streamInfo.aacSamplesPerFrame);
3461               self->extGainDelay =
3462                   (self->streamInfo.aacSamplesPerFrame * 2 -
3463                    self->streamInfo.aacSamplesPerFrame / 2 - 1) /
3464                   2;
3465             } break;
3466             case AACDEC_RENDER_LPD:
3467 
3468               CLpd_RenderTimeSignal(
3469                   pAacDecoderStaticChannelInfo, pAacDecoderChannelInfo,
3470                   pTimeData + offset, self->streamInfo.aacSamplesPerFrame,
3471                   &self->samplingRateInfo[streamIndex],
3472                   (self->frameOK && !(flags & AACDEC_CONCEAL) &&
3473                    !frameOk_butConceal),
3474                   self->aacOutDataHeadroom, flags, self->flags[streamIndex]);
3475 
3476               self->extGainDelay = self->streamInfo.aacSamplesPerFrame;
3477               break;
3478             default:
3479               ErrorStatus = AAC_DEC_UNKNOWN;
3480               break;
3481           }
3482         /* TimeDomainFading */
3483         if (!CConceal_TDFading_Applied[c]) {
3484           CConceal_TDFading_Applied[c] = CConcealment_TDFading(
3485               self->streamInfo.aacSamplesPerFrame,
3486               &self->pAacDecoderStaticChannelInfo[c], self->aacOutDataHeadroom,
3487               pTimeData + offset, 0);
3488           if (c + 1 < (8) && c < aacChannels - 1) {
3489             /* update next TDNoise Seed to avoid muting in case of Parametric
3490              * Stereo */
3491             self->pAacDecoderStaticChannelInfo[c + 1]
3492                 ->concealmentInfo.TDNoiseSeed =
3493                 self->pAacDecoderStaticChannelInfo[c]
3494                     ->concealmentInfo.TDNoiseSeed;
3495           }
3496         }
3497       }
3498     }
3499 
3500     if (self->flags[streamIndex] & AC_USAC) {
3501       int bsPseudoLr = 0;
3502       mpegSurroundDecoder_IsPseudoLR(
3503           (CMpegSurroundDecoder *)self->pMpegSurroundDecoder, &bsPseudoLr);
3504       /* ISO/IEC 23003-3, 7.11.2.6 Modification of core decoder output (pseudo
3505        * LR) */
3506       if ((aacChannels == 2) && bsPseudoLr) {
3507         int i, offset2;
3508         const FIXP_SGL invSqrt2 = FL2FXCONST_SGL(0.707106781186547f);
3509         PCM_DEC *pTD = pTimeData;
3510 
3511         offset2 = timeDataChannelOffset;
3512 
3513         for (i = 0; i < self->streamInfo.aacSamplesPerFrame; i++) {
3514           FIXP_DBL L = PCM_DEC2FIXP_DBL(pTD[0]);
3515           FIXP_DBL R = PCM_DEC2FIXP_DBL(pTD[offset2]);
3516           L = fMult(L, invSqrt2);
3517           R = fMult(R, invSqrt2);
3518           pTD[0] = L + R;
3519           pTD[offset2] = L - R;
3520           pTD++;
3521         }
3522       }
3523     }
3524 
3525     /* Extract DRC control data and map it to channels (with bitstream delay) */
3526     mapped = aacDecoder_drcEpilog(
3527         self->hDrcInfo, bs, self->pAacDecoderStaticChannelInfo,
3528         pce->ElementInstanceTag, drcChMap, aacChannels);
3529     if (mapped > 0) {
3530       if (!(self->flags[streamIndex] & (AC_USAC | AC_RSV603DA))) {
3531         /* If at least one DRC thread has been mapped to a channel there was DRC
3532          * data in the bitstream. */
3533         self->flags[streamIndex] |= AC_DRC_PRESENT;
3534       } else {
3535         ErrorStatus = AAC_DEC_UNSUPPORTED_FORMAT;
3536       }
3537     }
3538     if (self->flags[streamIndex] & (AC_USAC | AC_RSV603DA)) {
3539       aacDecoder_drcDisable(self->hDrcInfo);
3540     }
3541   }
3542 
3543   /* Add additional concealment delay */
3544   self->streamInfo.outputDelay +=
3545       CConcealment_GetDelay(&self->concealCommonData) *
3546       self->streamInfo.aacSamplesPerFrame;
3547 
3548   /* Map DRC data to StreamInfo structure */
3549   aacDecoder_drcGetInfo(self->hDrcInfo, &self->streamInfo.drcPresMode,
3550                         &self->streamInfo.drcProgRefLev);
3551 
3552   /* Reorder channel type information tables.  */
3553   if (!(self->flags[0] & AC_RSV603DA)) {
3554     AUDIO_CHANNEL_TYPE types[(8)];
3555     UCHAR idx[(8)];
3556     int c;
3557     int mapValue;
3558 
3559     FDK_ASSERT(sizeof(self->channelType) == sizeof(types));
3560     FDK_ASSERT(sizeof(self->channelIndices) == sizeof(idx));
3561 
3562     FDKmemcpy(types, self->channelType, sizeof(types));
3563     FDKmemcpy(idx, self->channelIndices, sizeof(idx));
3564 
3565     for (c = 0; c < aacChannels; c++) {
3566       mapValue =
3567           FDK_chMapDescr_getMapValue(&self->mapDescr, c, self->chMapIndex);
3568       self->channelType[mapValue] = types[c];
3569       self->channelIndices[mapValue] = idx[c];
3570     }
3571   }
3572 
3573   self->blockNumber++;
3574 
3575   return ErrorStatus;
3576 }
3577 
3578 /*!
3579   \brief returns the streaminfo pointer
3580 
3581   The function hands back a pointer to the streaminfo structure
3582 
3583   \return pointer to the struct
3584 */
CAacDecoder_GetStreamInfo(HANDLE_AACDECODER self)3585 LINKSPEC_CPP CStreamInfo *CAacDecoder_GetStreamInfo(HANDLE_AACDECODER self) {
3586   if (!self) {
3587     return NULL;
3588   }
3589   return &self->streamInfo;
3590 }
3591