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