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