Home | History | Annotate | Download | only in src
      1 
      2 /* -----------------------------------------------------------------------------------------------------------
      3 Software License for The Fraunhofer FDK AAC Codec Library for Android
      4 
      5  Copyright  1995 - 2015 Fraunhofer-Gesellschaft zur Frderung der angewandten Forschung e.V.
      6   All rights reserved.
      7 
      8  1.    INTRODUCTION
      9 The Fraunhofer FDK AAC Codec Library for Android ("FDK AAC Codec") is software that implements
     10 the MPEG Advanced Audio Coding ("AAC") encoding and decoding scheme for digital audio.
     11 This FDK AAC Codec software is intended to be used on a wide variety of Android devices.
     12 
     13 AAC's HE-AAC and HE-AAC v2 versions are regarded as today's most efficient general perceptual
     14 audio codecs. AAC-ELD is considered the best-performing full-bandwidth communications codec by
     15 independent studies and is widely deployed. AAC has been standardized by ISO and IEC as part
     16 of the MPEG specifications.
     17 
     18 Patent licenses for necessary patent claims for the FDK AAC Codec (including those of Fraunhofer)
     19 may be obtained through Via Licensing (www.vialicensing.com) or through the respective patent owners
     20 individually for the purpose of encoding or decoding bit streams in products that are compliant with
     21 the ISO/IEC MPEG audio standards. Please note that most manufacturers of Android devices already license
     22 these patent claims through Via Licensing or directly from the patent owners, and therefore FDK AAC Codec
     23 software may already be covered under those patent licenses when it is used for those licensed purposes only.
     24 
     25 Commercially-licensed AAC software libraries, including floating-point versions with enhanced sound quality,
     26 are also available from Fraunhofer. Users are encouraged to check the Fraunhofer website for additional
     27 applications information and documentation.
     28 
     29 2.    COPYRIGHT LICENSE
     30 
     31 Redistribution and use in source and binary forms, with or without modification, are permitted without
     32 payment of copyright license fees provided that you satisfy the following conditions:
     33 
     34 You must retain the complete text of this software license in redistributions of the FDK AAC Codec or
     35 your modifications thereto in source code form.
     36 
     37 You must retain the complete text of this software license in the documentation and/or other materials
     38 provided with redistributions of the FDK AAC Codec or your modifications thereto in binary form.
     39 You must make available free of charge copies of the complete source code of the FDK AAC Codec and your
     40 modifications thereto to recipients of copies in binary form.
     41 
     42 The name of Fraunhofer may not be used to endorse or promote products derived from this library without
     43 prior written permission.
     44 
     45 You may not charge copyright license fees for anyone to use, copy or distribute the FDK AAC Codec
     46 software or your modifications thereto.
     47 
     48 Your modified versions of the FDK AAC Codec must carry prominent notices stating that you changed the software
     49 and the date of any change. For modified versions of the FDK AAC Codec, the term
     50 "Fraunhofer FDK AAC Codec Library for Android" must be replaced by the term
     51 "Third-Party Modified Version of the Fraunhofer FDK AAC Codec Library for Android."
     52 
     53 3.    NO PATENT LICENSE
     54 
     55 NO EXPRESS OR IMPLIED LICENSES TO ANY PATENT CLAIMS, including without limitation the patents of Fraunhofer,
     56 ARE GRANTED BY THIS SOFTWARE LICENSE. Fraunhofer provides no warranty of patent non-infringement with
     57 respect to this software.
     58 
     59 You may use this FDK AAC Codec software or modifications thereto only for purposes that are authorized
     60 by appropriate patent licenses.
     61 
     62 4.    DISCLAIMER
     63 
     64 This FDK AAC Codec software is provided by Fraunhofer on behalf of the copyright holders and contributors
     65 "AS IS" and WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, including but not limited to the implied warranties
     66 of merchantability and fitness for a particular purpose. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
     67 CONTRIBUTORS BE LIABLE for any direct, indirect, incidental, special, exemplary, or consequential damages,
     68 including but not limited to procurement of substitute goods or services; loss of use, data, or profits,
     69 or business interruption, however caused and on any theory of liability, whether in contract, strict
     70 liability, or tort (including negligence), arising in any way out of the use of this software, even if
     71 advised of the possibility of such damage.
     72 
     73 5.    CONTACT INFORMATION
     74 
     75 Fraunhofer Institute for Integrated Circuits IIS
     76 Attention: Audio and Multimedia Departments - FDK AAC LL
     77 Am Wolfsmantel 33
     78 91058 Erlangen, Germany
     79 
     80 www.iis.fraunhofer.de/amm
     81 amm-info (at) iis.fraunhofer.de
     82 ----------------------------------------------------------------------------------------------------------- */
     83 
     84 /*!
     85   \file
     86   \brief  SBR decoder frontend
     87   This module provides a frontend to the SBR decoder. The function openSBR() is called for
     88   initialization. The function sbrDecoder_Apply() is called for each frame. sbr_Apply() will call the
     89   required functions to decode the raw SBR data (provided by env_extr.cpp), to decode the envelope data and noise floor levels [decodeSbrData()],
     90   and to finally apply SBR to the current frame [sbr_dec()].
     91 
     92   \sa sbrDecoder_Apply(), \ref documentationOverview
     93 */
     94 
     95 /*!
     96   \page documentationOverview Overview of important information resources and source code documentation
     97 
     98   The primary source code documentation is based on generated and cross-referenced HTML files using
     99   <a HREF="http://www.doxygen.org">doxygen</a>. As part of this documentation
    100   you can find more extensive descriptions about key concepts and algorithms at the following locations:
    101 
    102   <h2>Programming</h2>
    103 
    104   \li Buffer management: sbrDecoder_Apply() and sbr_dec()
    105   \li Internal scale factors to maximize SNR on fixed point processors: #QMF_SCALE_FACTOR
    106   \li Special mantissa-exponent format: Created in requantizeEnvelopeData() and used in calculateSbrEnvelope()
    107 
    108   <h2>Algorithmic details</h2>
    109   \li About the SBR data format: \ref SBR_HEADER_ELEMENT and \ref SBR_STANDARD_ELEMENT
    110   \li Details about the bitstream decoder: env_extr.cpp
    111   \li Details about the QMF filterbank and the provided polyphase implementation: qmf_dec.cpp
    112   \li Details about the transposer: lpp_tran.cpp
    113   \li Details about the envelope adjuster: env_calc.cpp
    114 
    115 */
    116 
    117 #include "sbrdecoder.h"
    118 
    119 #include "FDK_bitstream.h"
    120 
    121 #include "sbrdec_freq_sca.h"
    122 #include "env_extr.h"
    123 #include "sbr_dec.h"
    124 #include "env_dec.h"
    125 #include "sbr_crc.h"
    126 #include "sbr_ram.h"
    127 #include "sbr_rom.h"
    128 #include "lpp_tran.h"
    129 #include "transcendent.h"
    130 
    131 #include "FDK_crc.h"
    132 
    133 #include "sbrdec_drc.h"
    134 
    135 #include "psbitdec.h"
    136 
    137 
    138 /* Decoder library info */
    139 #define SBRDECODER_LIB_VL0 2
    140 #define SBRDECODER_LIB_VL1 2
    141 #define SBRDECODER_LIB_VL2 12
    142 #define SBRDECODER_LIB_TITLE "SBR Decoder"
    143 #ifdef __ANDROID__
    144 #define SBRDECODER_LIB_BUILD_DATE ""
    145 #define SBRDECODER_LIB_BUILD_TIME ""
    146 #else
    147 #define SBRDECODER_LIB_BUILD_DATE __DATE__
    148 #define SBRDECODER_LIB_BUILD_TIME __TIME__
    149 #endif
    150 
    151 
    152 
    153 
    154 static UCHAR getHeaderSlot( UCHAR currentSlot, UCHAR hdrSlotUsage[(1)+1] )
    155 {
    156   UINT  occupied = 0;
    157   int   s;
    158   UCHAR slot = hdrSlotUsage[currentSlot];
    159 
    160   FDK_ASSERT((1)+1 < 32);
    161 
    162   for (s = 0; s < (1)+1; s++) {
    163     if ( (hdrSlotUsage[s] == slot)
    164       && (s != slot) ) {
    165       occupied = 1;
    166       break;
    167     }
    168   }
    169 
    170   if (occupied) {
    171     occupied = 0;
    172 
    173     for (s = 0; s < (1)+1; s++) {
    174       occupied |= 1 << hdrSlotUsage[s];
    175     }
    176     for (s = 0; s < (1)+1; s++) {
    177       if ( !(occupied & 0x1) ) {
    178         slot = s;
    179         break;
    180       }
    181       occupied >>= 1;
    182     }
    183   }
    184 
    185   return slot;
    186 }
    187 
    188 static void copySbrHeader( HANDLE_SBR_HEADER_DATA hDst, const HANDLE_SBR_HEADER_DATA hSrc )
    189 {
    190   /* copy the whole header memory (including pointers) */
    191   FDKmemcpy( hDst, hSrc, sizeof(SBR_HEADER_DATA) );
    192 
    193   /* update pointers */
    194   hDst->freqBandData.freqBandTable[0]  = hDst->freqBandData.freqBandTableLo;
    195   hDst->freqBandData.freqBandTable[1] = hDst->freqBandData.freqBandTableHi;
    196 }
    197 
    198 static int compareSbrHeader( const HANDLE_SBR_HEADER_DATA hHdr1, const HANDLE_SBR_HEADER_DATA hHdr2 )
    199 {
    200   int result = 0;
    201 
    202   /* compare basic data */
    203   result |= (hHdr1->syncState != hHdr2->syncState) ? 1 : 0;
    204   result |= (hHdr1->status != hHdr2->status) ? 1 : 0;
    205   result |= (hHdr1->frameErrorFlag != hHdr2->frameErrorFlag) ? 1 : 0;
    206   result |= (hHdr1->numberTimeSlots != hHdr2->numberTimeSlots) ? 1 : 0;
    207   result |= (hHdr1->numberOfAnalysisBands != hHdr2->numberOfAnalysisBands) ? 1 : 0;
    208   result |= (hHdr1->timeStep != hHdr2->timeStep) ? 1 : 0;
    209   result |= (hHdr1->sbrProcSmplRate != hHdr2->sbrProcSmplRate) ? 1 : 0;
    210 
    211   /* compare bitstream data */
    212   result |= FDKmemcmp( &hHdr1->bs_data, &hHdr2->bs_data, sizeof(SBR_HEADER_DATA_BS) );
    213   result |= FDKmemcmp( &hHdr1->bs_info, &hHdr2->bs_info, sizeof(SBR_HEADER_DATA_BS_INFO) );
    214 
    215   /* compare frequency band data */
    216   result |= FDKmemcmp( &hHdr1->freqBandData, &hHdr2->freqBandData, (8+MAX_NUM_LIMITERS+1)*sizeof(UCHAR) );
    217   result |= FDKmemcmp( hHdr1->freqBandData.freqBandTableLo, hHdr2->freqBandData.freqBandTableLo, (MAX_FREQ_COEFFS/2+1)*sizeof(UCHAR) );
    218   result |= FDKmemcmp( hHdr1->freqBandData.freqBandTableHi, hHdr2->freqBandData.freqBandTableHi, (MAX_FREQ_COEFFS+1)*sizeof(UCHAR) );
    219   result |= FDKmemcmp( hHdr1->freqBandData.freqBandTableNoise, hHdr2->freqBandData.freqBandTableNoise, (MAX_NOISE_COEFFS+1)*sizeof(UCHAR) );
    220   result |= FDKmemcmp( hHdr1->freqBandData.v_k_master, hHdr2->freqBandData.v_k_master, (MAX_FREQ_COEFFS+1)*sizeof(UCHAR) );
    221 
    222   return result;
    223 }
    224 
    225 
    226 /*!
    227   \brief Reset SBR decoder.
    228 
    229   Reset should only be called if SBR has been sucessfully detected by
    230   an appropriate checkForPayload() function.
    231 
    232   \return Error code.
    233 */
    234 static
    235 SBR_ERROR sbrDecoder_ResetElement (
    236         HANDLE_SBRDECODER    self,
    237         int                  sampleRateIn,
    238         int                  sampleRateOut,
    239         int                  samplesPerFrame,
    240         const MP4_ELEMENT_ID elementID,
    241         const int            elementIndex,
    242         const int            overlap
    243         )
    244 {
    245   SBR_ERROR sbrError = SBRDEC_OK;
    246   HANDLE_SBR_HEADER_DATA hSbrHeader;
    247   UINT qmfFlags = 0;
    248 
    249   int i, synDownsampleFac;
    250 
    251   /* Check in/out samplerates */
    252   if ( sampleRateIn < 6400
    253     || sampleRateIn > 48000
    254      )
    255   {
    256     sbrError = SBRDEC_UNSUPPORTED_CONFIG;
    257     goto bail;
    258   }
    259 
    260   if ( sampleRateOut > 96000 )
    261   {
    262     sbrError = SBRDEC_UNSUPPORTED_CONFIG;
    263     goto bail;
    264   }
    265 
    266   /* Set QMF mode flags */
    267   if (self->flags & SBRDEC_LOW_POWER)
    268     qmfFlags |= QMF_FLAG_LP;
    269 
    270   if (self->coreCodec == AOT_ER_AAC_ELD) {
    271     if (self->flags & SBRDEC_LD_MPS_QMF) {
    272       qmfFlags |=  QMF_FLAG_MPSLDFB;
    273     } else {
    274       qmfFlags |=  QMF_FLAG_CLDFB;
    275     }
    276   }
    277 
    278   /* Set downsampling factor for synthesis filter bank */
    279   if (sampleRateOut == 0)
    280   {
    281     /* no single rate mode */
    282       sampleRateOut = sampleRateIn<<1; /* In case of implicit signalling, assume dual rate SBR */
    283   }
    284 
    285   if ( sampleRateIn == sampleRateOut ) {
    286     synDownsampleFac = 2;
    287     self->flags |=  SBRDEC_DOWNSAMPLE;
    288   } else {
    289     synDownsampleFac = 1;
    290     self->flags &= ~SBRDEC_DOWNSAMPLE;
    291   }
    292 
    293   self->synDownsampleFac = synDownsampleFac;
    294   self->sampleRateOut = sampleRateOut;
    295 
    296   {
    297     int i;
    298 
    299     for (i = 0; i < (1)+1; i++)
    300     {
    301       hSbrHeader = &(self->sbrHeader[elementIndex][i]);
    302 
    303       /* init a default header such that we can at least do upsampling later */
    304       sbrError = initHeaderData(
    305               hSbrHeader,
    306               sampleRateIn,
    307               sampleRateOut,
    308               samplesPerFrame,
    309               self->flags
    310               );
    311     }
    312   }
    313 
    314   if (sbrError != SBRDEC_OK) {
    315     goto bail;
    316   }
    317 
    318   /* Init SBR channels going to be assigned to a SBR element */
    319   {
    320     int ch;
    321 
    322     for (ch=0; ch<self->pSbrElement[elementIndex]->nChannels; ch++)
    323     {
    324       /* and create sbrDec */
    325       sbrError = createSbrDec (self->pSbrElement[elementIndex]->pSbrChannel[ch],
    326                           hSbrHeader,
    327                          &self->pSbrElement[elementIndex]->transposerSettings,
    328                           synDownsampleFac,
    329                           qmfFlags,
    330                           self->flags,
    331                           overlap,
    332                           ch );
    333 
    334       if (sbrError != SBRDEC_OK) {
    335         goto bail;
    336       }
    337     }
    338   }
    339 
    340   //FDKmemclear(sbr_OverlapBuffer, sizeof(sbr_OverlapBuffer));
    341 
    342   if (self->numSbrElements == 1) {
    343     switch ( self->coreCodec ) {
    344     case AOT_AAC_LC:
    345     case AOT_SBR:
    346     case AOT_PS:
    347     case AOT_ER_AAC_SCAL:
    348     case AOT_DRM_AAC:
    349       if (CreatePsDec ( &self->hParametricStereoDec, samplesPerFrame )) {
    350         sbrError = SBRDEC_CREATE_ERROR;
    351         goto bail;
    352       }
    353       break;
    354     default:
    355       break;
    356     }
    357   }
    358 
    359   /* Init frame delay slot handling */
    360   self->pSbrElement[elementIndex]->useFrameSlot = 0;
    361   for (i = 0; i < ((1)+1); i++) {
    362     self->pSbrElement[elementIndex]->useHeaderSlot[i] = i;
    363   }
    364 
    365 bail:
    366 
    367   return sbrError;
    368 }
    369 
    370 
    371 SBR_ERROR sbrDecoder_Open ( HANDLE_SBRDECODER  * pSelf )
    372 {
    373   HANDLE_SBRDECODER    self = NULL;
    374   SBR_ERROR sbrError = SBRDEC_OK;
    375 
    376   /* Get memory for this instance */
    377   self = GetRam_SbrDecoder();
    378   if (self == NULL) {
    379     sbrError = SBRDEC_MEM_ALLOC_FAILED;
    380     goto bail;
    381   }
    382 
    383   self->workBuffer1 = GetRam_SbrDecWorkBuffer1();
    384   self->workBuffer2 = GetRam_SbrDecWorkBuffer2();
    385 
    386   if (  self->workBuffer1 == NULL
    387      || self->workBuffer2 == NULL )
    388   {
    389     sbrError = SBRDEC_MEM_ALLOC_FAILED;
    390     goto bail;
    391   }
    392 
    393   /*
    394   Already zero because of calloc
    395   self->numSbrElements = 0;
    396   self->numSbrChannels = 0;
    397   self->codecFrameSize = 0;
    398   */
    399 
    400   self->numDelayFrames = (1);  /* set to the max value by default */
    401 
    402   *pSelf = self;
    403 
    404 bail:
    405   return sbrError;
    406 }
    407 
    408 /**
    409  * \brief determine if the given core codec AOT can be processed or not.
    410  * \param coreCodec core codec audio object type.
    411  * \return 1 if SBR can be processed, 0 if SBR cannot be processed/applied.
    412  */
    413 static
    414 int sbrDecoder_isCoreCodecValid(AUDIO_OBJECT_TYPE coreCodec)
    415 {
    416   switch (coreCodec) {
    417     case AOT_AAC_LC:
    418     case AOT_SBR:
    419     case AOT_PS:
    420     case AOT_ER_AAC_SCAL:
    421     case AOT_ER_AAC_ELD:
    422     case AOT_DRM_AAC:
    423       return 1;
    424     default:
    425       return 0;
    426   }
    427 }
    428 
    429 static
    430 void sbrDecoder_DestroyElement (
    431         HANDLE_SBRDECODER       self,
    432         const int               elementIndex
    433         )
    434 {
    435   if (self->pSbrElement[elementIndex] != NULL) {
    436     int ch;
    437 
    438     for (ch=0; ch<SBRDEC_MAX_CH_PER_ELEMENT; ch++) {
    439       if (self->pSbrElement[elementIndex]->pSbrChannel[ch] != NULL) {
    440         deleteSbrDec( self->pSbrElement[elementIndex]->pSbrChannel[ch] );
    441         FreeRam_SbrDecChannel( &self->pSbrElement[elementIndex]->pSbrChannel[ch] );
    442         self->numSbrChannels -= 1;
    443       }
    444     }
    445     FreeRam_SbrDecElement( &self->pSbrElement[elementIndex] );
    446     self->numSbrElements -= 1;
    447   }
    448 }
    449 
    450 
    451 SBR_ERROR sbrDecoder_InitElement (
    452         HANDLE_SBRDECODER       self,
    453         const int               sampleRateIn,
    454         const int               sampleRateOut,
    455         const int               samplesPerFrame,
    456         const AUDIO_OBJECT_TYPE coreCodec,
    457         const MP4_ELEMENT_ID    elementID,
    458         const int               elementIndex
    459         )
    460 {
    461   SBR_ERROR sbrError = SBRDEC_OK;
    462   int chCnt=0;
    463   int nSbrElementsStart = self->numSbrElements;
    464 
    465   /* Check core codec AOT */
    466   if (! sbrDecoder_isCoreCodecValid(coreCodec) || elementIndex >= (8)) {
    467     sbrError = SBRDEC_UNSUPPORTED_CONFIG;
    468     goto bail;
    469   }
    470 
    471   if ( elementID != ID_SCE && elementID != ID_CPE && elementID != ID_LFE )
    472   {
    473     sbrError = SBRDEC_UNSUPPORTED_CONFIG;
    474     goto bail;
    475   }
    476 
    477   if (  self->sampleRateIn == sampleRateIn
    478      && self->codecFrameSize == samplesPerFrame
    479      && self->coreCodec == coreCodec
    480      && self->pSbrElement[elementIndex] != NULL
    481      && self->pSbrElement[elementIndex]->elementID == elementID
    482      && !(self->flags & SBRDEC_FORCE_RESET)
    483      )
    484   {
    485      /* Nothing to do */
    486      return SBRDEC_OK;
    487   }
    488 
    489   self->sampleRateIn = sampleRateIn;
    490   self->codecFrameSize = samplesPerFrame;
    491   self->coreCodec = coreCodec;
    492 
    493   self->flags = 0;
    494   self->flags |= (coreCodec == AOT_ER_AAC_ELD) ? SBRDEC_ELD_GRID : 0;
    495   self->flags |= (coreCodec == AOT_ER_AAC_SCAL) ? SBRDEC_SYNTAX_SCAL : 0;
    496   self->flags |= (coreCodec == AOT_DRM_AAC)     ? SBRDEC_SYNTAX_SCAL|SBRDEC_SYNTAX_DRM : 0;
    497 
    498   /* Init SBR elements */
    499   {
    500     int elChannels, ch;
    501 
    502     if (self->pSbrElement[elementIndex] == NULL) {
    503       self->pSbrElement[elementIndex] = GetRam_SbrDecElement(elementIndex);
    504       if (self->pSbrElement[elementIndex] == NULL) {
    505         sbrError = SBRDEC_MEM_ALLOC_FAILED;
    506         goto bail;
    507       }
    508       self->numSbrElements ++;
    509     } else {
    510       self->numSbrChannels -= self->pSbrElement[elementIndex]->nChannels;
    511     }
    512 
    513     /* Save element ID for sanity checks and to have a fallback for concealment. */
    514     self->pSbrElement[elementIndex]->elementID = elementID;
    515 
    516     /* Determine amount of channels for this element */
    517     switch (elementID) {
    518       case ID_NONE:
    519       case ID_CPE: elChannels=2;
    520         break;
    521       case ID_LFE:
    522       case ID_SCE: elChannels=1;
    523         break;
    524       default: elChannels=0;
    525         break;
    526     }
    527 
    528     /* Handle case of Parametric Stereo */
    529     if ( elementIndex == 0 && elementID == ID_SCE ) {
    530       switch (coreCodec) {
    531         case AOT_AAC_LC:
    532         case AOT_SBR:
    533         case AOT_PS:
    534         case AOT_ER_AAC_SCAL:
    535         case AOT_DRM_AAC:
    536           elChannels = 2;
    537           break;
    538         default:
    539           break;
    540       }
    541     }
    542 
    543     self->pSbrElement[elementIndex]->nChannels = elChannels;
    544 
    545     for (ch=0; ch<elChannels; ch++)
    546     {
    547       if (self->pSbrElement[elementIndex]->pSbrChannel[ch] == NULL) {
    548         self->pSbrElement[elementIndex]->pSbrChannel[ch] = GetRam_SbrDecChannel(chCnt);
    549         if (self->pSbrElement[elementIndex]->pSbrChannel[ch] == NULL) {
    550           sbrError = SBRDEC_MEM_ALLOC_FAILED;
    551           goto bail;
    552         }
    553       }
    554       self->numSbrChannels ++;
    555 
    556       sbrDecoder_drcInitChannel( &self->pSbrElement[elementIndex]->pSbrChannel[ch]->SbrDec.sbrDrcChannel );
    557 
    558       /* Add reference pointer to workbuffers. */
    559       self->pSbrElement[elementIndex]->pSbrChannel[ch]->SbrDec.WorkBuffer1 = self->workBuffer1;
    560       self->pSbrElement[elementIndex]->pSbrChannel[ch]->SbrDec.WorkBuffer2 = self->workBuffer2;
    561       chCnt++;
    562     }
    563     if (elChannels == 1 && self->pSbrElement[elementIndex]->pSbrChannel[ch] != NULL) {
    564       deleteSbrDec( self->pSbrElement[elementIndex]->pSbrChannel[ch] );
    565       FreeRam_SbrDecChannel( &self->pSbrElement[elementIndex]->pSbrChannel[ch] );
    566     }
    567   }
    568 
    569   /* clear error flags for all delay slots */
    570   FDKmemclear(self->pSbrElement[elementIndex]->frameErrorFlag, ((1)+1)*sizeof(UCHAR));
    571 
    572   /* Initialize this instance */
    573   sbrError = sbrDecoder_ResetElement(
    574           self,
    575           sampleRateIn,
    576           sampleRateOut,
    577           samplesPerFrame,
    578           elementID,
    579           elementIndex,
    580           (coreCodec == AOT_ER_AAC_ELD) ? 0 : (6)
    581           );
    582 
    583 
    584 
    585 bail:
    586   if (sbrError != SBRDEC_OK) {
    587     if (nSbrElementsStart < self->numSbrElements) {
    588       /* Free the memory allocated for this element */
    589       sbrDecoder_DestroyElement( self, elementIndex );
    590     } else if ( (self->pSbrElement[elementIndex] != NULL)
    591              && (elementIndex < (8)))
    592     { /* Set error flag to trigger concealment */
    593       self->pSbrElement[elementIndex]->frameErrorFlag[self->pSbrElement[elementIndex]->useFrameSlot] = 1;
    594     }
    595   }
    596 
    597   return sbrError;
    598 }
    599 
    600 /**
    601  * \brief Apply decoded SBR header for one element.
    602  * \param self SBR decoder instance handle
    603  * \param hSbrHeader SBR header handle to be processed.
    604  * \param hSbrChannel pointer array to the SBR element channels corresponding to the SBR header.
    605  * \param headerStatus header status value returned from SBR header parser.
    606  * \param numElementChannels amount of channels for the SBR element whos header is to be processed.
    607  */
    608 static
    609 SBR_ERROR sbrDecoder_HeaderUpdate(
    610         HANDLE_SBRDECODER self,
    611         HANDLE_SBR_HEADER_DATA hSbrHeader,
    612         SBR_HEADER_STATUS headerStatus,
    613         HANDLE_SBR_CHANNEL hSbrChannel[],
    614         const int numElementChannels
    615         )
    616 {
    617   SBR_ERROR errorStatus = SBRDEC_OK;
    618 
    619   /*
    620     change of control data, reset decoder
    621   */
    622   errorStatus = resetFreqBandTables(hSbrHeader, self->flags);
    623 
    624   if (errorStatus == SBRDEC_OK) {
    625     if (hSbrHeader->syncState == UPSAMPLING && headerStatus != HEADER_RESET)
    626     {
    627       /* As the default header would limit the frequency range,
    628          lowSubband and highSubband must be patched. */
    629       hSbrHeader->freqBandData.lowSubband = hSbrHeader->numberOfAnalysisBands;
    630       hSbrHeader->freqBandData.highSubband = hSbrHeader->numberOfAnalysisBands;
    631     }
    632 
    633     /* Trigger a reset before processing this slot */
    634     hSbrHeader->status |= SBRDEC_HDR_STAT_RESET;
    635   }
    636 
    637   return errorStatus;
    638 }
    639 
    640 INT sbrDecoder_Header (
    641         HANDLE_SBRDECODER       self,
    642         HANDLE_FDK_BITSTREAM    hBs,
    643         const INT sampleRateIn,
    644         const INT sampleRateOut,
    645         const INT samplesPerFrame,
    646         const AUDIO_OBJECT_TYPE coreCodec,
    647         const MP4_ELEMENT_ID    elementID,
    648         const INT               elementIndex
    649         )
    650 {
    651   SBR_HEADER_STATUS headerStatus;
    652   HANDLE_SBR_HEADER_DATA hSbrHeader;
    653   SBR_ERROR sbrError = SBRDEC_OK;
    654   int headerIndex;
    655 
    656   if ( self == NULL || elementIndex > (8) )
    657   {
    658     return SBRDEC_UNSUPPORTED_CONFIG;
    659   }
    660 
    661   if (! sbrDecoder_isCoreCodecValid(coreCodec)) {
    662     return SBRDEC_UNSUPPORTED_CONFIG;
    663   }
    664 
    665   sbrError = sbrDecoder_InitElement(
    666           self,
    667           sampleRateIn,
    668           sampleRateOut,
    669           samplesPerFrame,
    670           coreCodec,
    671           elementID,
    672           elementIndex
    673           );
    674 
    675   if (sbrError != SBRDEC_OK) {
    676     goto bail;
    677   }
    678 
    679   headerIndex = getHeaderSlot(self->pSbrElement[elementIndex]->useFrameSlot,
    680                               self->pSbrElement[elementIndex]->useHeaderSlot);
    681   hSbrHeader = &(self->sbrHeader[elementIndex][headerIndex]);
    682 
    683   headerStatus = sbrGetHeaderData ( hSbrHeader,
    684                                     hBs,
    685                                     self->flags,
    686                                     0);
    687 
    688 
    689   {
    690     SBR_DECODER_ELEMENT *pSbrElement;
    691 
    692     pSbrElement = self->pSbrElement[elementIndex];
    693 
    694     /* Sanity check */
    695     if (pSbrElement != NULL) {
    696       if ( (elementID == ID_CPE && pSbrElement->nChannels != 2)
    697         || (elementID != ID_CPE && pSbrElement->nChannels != 1) )
    698       {
    699         return SBRDEC_UNSUPPORTED_CONFIG;
    700       }
    701       if ( headerStatus == HEADER_RESET ) {
    702 
    703         sbrError = sbrDecoder_HeaderUpdate(
    704               self,
    705               hSbrHeader,
    706               headerStatus,
    707               pSbrElement->pSbrChannel,
    708               pSbrElement->nChannels
    709               );
    710 
    711         if (sbrError == SBRDEC_OK) {
    712           hSbrHeader->syncState = SBR_HEADER;
    713           hSbrHeader->status   |= SBRDEC_HDR_STAT_UPDATE;
    714         }
    715         /* else {
    716           Since we already have overwritten the old SBR header the only way out is UPSAMPLING!
    717           This will be prepared in the next step.
    718         } */
    719       }
    720     }
    721   }
    722 bail:
    723   return sbrError;
    724 }
    725 
    726 
    727 SBR_ERROR sbrDecoder_SetParam (HANDLE_SBRDECODER   self,
    728                                const SBRDEC_PARAM  param,
    729                                const INT           value )
    730 {
    731   SBR_ERROR errorStatus = SBRDEC_OK;
    732 
    733   /* configure the subsystems */
    734   switch (param)
    735   {
    736   case SBR_SYSTEM_BITSTREAM_DELAY:
    737     if (value < 0 || value > (1)) {
    738       errorStatus = SBRDEC_SET_PARAM_FAIL;
    739       break;
    740     }
    741     if (self == NULL) {
    742       errorStatus = SBRDEC_NOT_INITIALIZED;
    743     } else {
    744       self->numDelayFrames = (UCHAR)value;
    745     }
    746     break;
    747   case SBR_QMF_MODE:
    748     if (self == NULL) {
    749       errorStatus = SBRDEC_NOT_INITIALIZED;
    750     } else {
    751       if (value == 1) {
    752         self->flags |= SBRDEC_LOW_POWER;
    753       } else {
    754         self->flags &= ~SBRDEC_LOW_POWER;
    755       }
    756     }
    757     break;
    758   case SBR_LD_QMF_TIME_ALIGN:
    759     if (self == NULL) {
    760       errorStatus = SBRDEC_NOT_INITIALIZED;
    761     } else {
    762       if (value == 1) {
    763         self->flags |= SBRDEC_LD_MPS_QMF;
    764       } else {
    765         self->flags &= ~SBRDEC_LD_MPS_QMF;
    766       }
    767     }
    768     break;
    769   case SBR_FLUSH_DATA:
    770     if (value != 0) {
    771       if (self == NULL) {
    772         errorStatus = SBRDEC_NOT_INITIALIZED;
    773       } else {
    774         self->flags |= SBRDEC_FLUSH;
    775       }
    776     }
    777     break;
    778   case SBR_CLEAR_HISTORY:
    779     if (value != 0) {
    780       if (self == NULL) {
    781         errorStatus = SBRDEC_NOT_INITIALIZED;
    782       } else {
    783         self->flags |= SBRDEC_FORCE_RESET;
    784       }
    785     }
    786     break;
    787   case SBR_BS_INTERRUPTION:
    788     {
    789       int elementIndex;
    790 
    791       if (self == NULL) {
    792         errorStatus = SBRDEC_NOT_INITIALIZED;
    793         break;
    794       }
    795 
    796       /* Loop over SBR elements */
    797       for (elementIndex = 0; elementIndex < self->numSbrElements; elementIndex++) {
    798       if (self->pSbrElement[elementIndex] != NULL)
    799       {
    800         HANDLE_SBR_HEADER_DATA hSbrHeader;
    801         int headerIndex = getHeaderSlot(self->pSbrElement[elementIndex]->useFrameSlot,
    802                                         self->pSbrElement[elementIndex]->useHeaderSlot);
    803 
    804         hSbrHeader = &(self->sbrHeader[elementIndex][headerIndex]);
    805 
    806         /* Set sync state UPSAMPLING for the corresponding slot.
    807            This switches off bitstream parsing until a new header arrives. */
    808         hSbrHeader->syncState = UPSAMPLING;
    809         hSbrHeader->status   |= SBRDEC_HDR_STAT_UPDATE;
    810       } }
    811     }
    812     break;
    813   default:
    814     errorStatus = SBRDEC_SET_PARAM_FAIL;
    815     break;
    816   }  /* switch(param) */
    817 
    818   return (errorStatus);
    819 }
    820 
    821 static
    822 SBRDEC_DRC_CHANNEL * sbrDecoder_drcGetChannel( const HANDLE_SBRDECODER self, const INT channel )
    823 {
    824   SBRDEC_DRC_CHANNEL *pSbrDrcChannelData = NULL;
    825   int elementIndex, elChanIdx=0, numCh=0;
    826 
    827   for (elementIndex = 0; (elementIndex < (8)) && (numCh <= channel); elementIndex++)
    828   {
    829     SBR_DECODER_ELEMENT *pSbrElement = self->pSbrElement[elementIndex];
    830     int c, elChannels;
    831 
    832     elChanIdx = 0;
    833     if (pSbrElement == NULL) break;
    834 
    835     /* Determine amount of channels for this element */
    836     switch (pSbrElement->elementID) {
    837       case ID_CPE: elChannels = 2;
    838         break;
    839       case ID_LFE:
    840       case ID_SCE: elChannels = 1;
    841         break;
    842       case ID_NONE:
    843       default: elChannels = 0;
    844         break;
    845     }
    846 
    847     /* Limit with actual allocated element channels */
    848     elChannels = FDKmin(elChannels, pSbrElement->nChannels);
    849 
    850     for (c = 0; (c < elChannels) && (numCh <= channel); c++) {
    851       if (pSbrElement->pSbrChannel[elChanIdx] != NULL) {
    852         numCh++;
    853         elChanIdx++;
    854       }
    855     }
    856   }
    857   elementIndex -= 1;
    858   elChanIdx -= 1;
    859 
    860   if (elChanIdx < 0 || elementIndex < 0) {
    861     return NULL;
    862   }
    863 
    864   if ( self->pSbrElement[elementIndex] != NULL ) {
    865     if ( self->pSbrElement[elementIndex]->pSbrChannel[elChanIdx] != NULL )
    866     {
    867       pSbrDrcChannelData = &self->pSbrElement[elementIndex]->pSbrChannel[elChanIdx]->SbrDec.sbrDrcChannel;
    868     }
    869   }
    870 
    871   return (pSbrDrcChannelData);
    872 }
    873 
    874 SBR_ERROR sbrDecoder_drcFeedChannel ( HANDLE_SBRDECODER  self,
    875                                       INT                ch,
    876                                       UINT               numBands,
    877                                       FIXP_DBL          *pNextFact_mag,
    878                                       INT                nextFact_exp,
    879                                       SHORT              drcInterpolationScheme,
    880                                       UCHAR              winSequence,
    881                                       USHORT            *pBandTop )
    882 {
    883   SBRDEC_DRC_CHANNEL *pSbrDrcChannelData = NULL;
    884   int band, isValidData = 0;
    885 
    886   if (self == NULL) {
    887     return SBRDEC_NOT_INITIALIZED;
    888   }
    889   if (ch > (8) || pNextFact_mag == NULL) {
    890     return SBRDEC_SET_PARAM_FAIL;
    891   }
    892 
    893   /* Search for gain values different to 1.0f */
    894   for (band = 0; band < numBands; band += 1) {
    895     if ( !((pNextFact_mag[band] == FL2FXCONST_DBL(0.5))  && (nextFact_exp == 1))
    896       && !((pNextFact_mag[band] == (FIXP_DBL)MAXVAL_DBL) && (nextFact_exp == 0)) ) {
    897       isValidData = 1;
    898       break;
    899     }
    900   }
    901 
    902   /* Find the right SBR channel */
    903   pSbrDrcChannelData = sbrDecoder_drcGetChannel( self, ch );
    904 
    905   if ( pSbrDrcChannelData != NULL ) {
    906     if ( pSbrDrcChannelData->enable || isValidData )
    907   { /* Activate processing only with real and valid data */
    908     int i;
    909 
    910     pSbrDrcChannelData->enable   = 1;
    911     pSbrDrcChannelData->numBandsNext = numBands;
    912 
    913     pSbrDrcChannelData->winSequenceNext            = winSequence;
    914     pSbrDrcChannelData->drcInterpolationSchemeNext = drcInterpolationScheme;
    915     pSbrDrcChannelData->nextFact_exp               = nextFact_exp;
    916 
    917     for (i = 0; i < (int)numBands; i++) {
    918       pSbrDrcChannelData->bandTopNext[i]  = pBandTop[i];
    919       pSbrDrcChannelData->nextFact_mag[i] = pNextFact_mag[i];
    920     }
    921   }
    922   }
    923 
    924   return SBRDEC_OK;
    925 }
    926 
    927 
    928 void sbrDecoder_drcDisable ( HANDLE_SBRDECODER  self,
    929                              INT                ch )
    930 {
    931   SBRDEC_DRC_CHANNEL *pSbrDrcChannelData = NULL;
    932 
    933   if ( (self == NULL)
    934     || (ch > (8))
    935     || (self->numSbrElements == 0)
    936     || (self->numSbrChannels == 0) ) {
    937     return;
    938   }
    939 
    940   /* Find the right SBR channel */
    941   pSbrDrcChannelData = sbrDecoder_drcGetChannel( self, ch );
    942 
    943   if ( pSbrDrcChannelData != NULL ) {
    944     sbrDecoder_drcInitChannel( pSbrDrcChannelData );
    945   }
    946 }
    947 
    948 
    949 
    950 SBR_ERROR sbrDecoder_Parse(
    951         HANDLE_SBRDECODER self,
    952         HANDLE_FDK_BITSTREAM  hBs,
    953         int *count,
    954         int  bsPayLen,
    955         int  crcFlag,
    956         MP4_ELEMENT_ID prevElement,
    957         int elementIndex,
    958         int fGlobalIndependencyFlag
    959         )
    960 {
    961   SBR_DECODER_ELEMENT   *hSbrElement;
    962   HANDLE_SBR_HEADER_DATA hSbrHeader = NULL;
    963   HANDLE_SBR_CHANNEL    *pSbrChannel;
    964 
    965   SBR_FRAME_DATA *hFrameDataLeft;
    966   SBR_FRAME_DATA *hFrameDataRight;
    967 
    968   SBR_ERROR errorStatus = SBRDEC_OK;
    969   SBR_HEADER_STATUS headerStatus = HEADER_NOT_PRESENT;
    970 
    971   INT  startPos;
    972   INT  CRCLen = 0;
    973   HANDLE_FDK_BITSTREAM hBsOriginal = hBs;
    974   FDK_CRCINFO  crcInfo;         /* shall be used for all other CRCs in the future (TBD) */
    975   INT          crcReg = 0;
    976   USHORT       drmSbrCrc = 0;
    977 
    978   int  stereo;
    979   int  fDoDecodeSbrData = 1;
    980 
    981   int lastSlot, lastHdrSlot = 0, thisHdrSlot;
    982 
    983   /* Reverse bits of DRM SBR payload */
    984   if ( (self->flags & SBRDEC_SYNTAX_DRM) && *count > 0 )
    985   {
    986     UCHAR *bsBufferDrm = (UCHAR*)self->workBuffer1;
    987     HANDLE_FDK_BITSTREAM hBsBwd = (HANDLE_FDK_BITSTREAM) (bsBufferDrm + (512));
    988     int dataBytes, dataBits;
    989 
    990     dataBits = *count;
    991 
    992     if (dataBits > ((512)*8)) {
    993       /* do not flip more data than needed */
    994       dataBits = (512)*8;
    995     }
    996 
    997     dataBytes = (dataBits+7)>>3;
    998 
    999     int j;
   1000 
   1001     if ((j = (int)FDKgetValidBits(hBs)) != 8) {
   1002       FDKpushBiDirectional(hBs, (j-8));
   1003     }
   1004 
   1005     j = 0;
   1006     for ( ; dataBytes > 0; dataBytes--)
   1007     {
   1008       int i;
   1009       UCHAR tmpByte;
   1010       UCHAR buffer = 0x00;
   1011 
   1012       tmpByte = (UCHAR) FDKreadBits(hBs, 8);
   1013       for (i = 0; i < 4; i++) {
   1014         int shift = 2 * i + 1;
   1015         buffer |= (tmpByte & (0x08>>i)) << shift;
   1016         buffer |= (tmpByte & (0x10<<i)) >> shift;
   1017       }
   1018       bsBufferDrm[j++] = buffer;
   1019       FDKpushBack(hBs, 16);
   1020     }
   1021 
   1022     FDKinitBitStream(hBsBwd, bsBufferDrm, (512), dataBits, BS_READER);
   1023 
   1024     /* Use reversed data */
   1025     hBs = hBsBwd;
   1026     bsPayLen = *count;
   1027   }
   1028 
   1029   /* Remember start position of  SBR element */
   1030   startPos = FDKgetValidBits(hBs);
   1031 
   1032   /* SBR sanity checks */
   1033   if ( self == NULL || self->pSbrElement[elementIndex] == NULL ) {
   1034     errorStatus = SBRDEC_NOT_INITIALIZED;
   1035     goto bail;
   1036   }
   1037 
   1038   hSbrElement = self->pSbrElement[elementIndex];
   1039 
   1040   lastSlot    = (hSbrElement->useFrameSlot > 0) ? hSbrElement->useFrameSlot-1 : self->numDelayFrames;
   1041   lastHdrSlot =  hSbrElement->useHeaderSlot[lastSlot];
   1042   thisHdrSlot =  getHeaderSlot( hSbrElement->useFrameSlot, hSbrElement->useHeaderSlot );  /* Get a free header slot not used by frames not processed yet. */
   1043 
   1044   /* Assign the free slot to store a new header if there is one. */
   1045   hSbrHeader = &self->sbrHeader[elementIndex][thisHdrSlot];
   1046 
   1047   pSbrChannel = hSbrElement->pSbrChannel;
   1048   stereo = (hSbrElement->elementID == ID_CPE) ? 1 : 0;
   1049 
   1050   hFrameDataLeft  = &self->pSbrElement[elementIndex]->pSbrChannel[0]->frameData[hSbrElement->useFrameSlot];
   1051   hFrameDataRight = &self->pSbrElement[elementIndex]->pSbrChannel[1]->frameData[hSbrElement->useFrameSlot];
   1052 
   1053 
   1054   /* reset PS flag; will be set after PS was found */
   1055   self->flags &= ~SBRDEC_PS_DECODED;
   1056 
   1057   if (hSbrHeader->status & SBRDEC_HDR_STAT_UPDATE) {
   1058     /* Got a new header from extern (e.g. from an ASC) */
   1059     headerStatus = HEADER_OK;
   1060     hSbrHeader->status &= ~SBRDEC_HDR_STAT_UPDATE;
   1061   }
   1062   else if (thisHdrSlot != lastHdrSlot) {
   1063     /* Copy the last header into this slot otherwise the
   1064        header compare will trigger more HEADER_RESETs than needed. */
   1065     copySbrHeader( hSbrHeader, &self->sbrHeader[elementIndex][lastHdrSlot] );
   1066   }
   1067 
   1068   /*
   1069      Check if bit stream data is valid and matches the element context
   1070   */
   1071   if ( ((prevElement != ID_SCE) && (prevElement != ID_CPE)) || prevElement != hSbrElement->elementID) {
   1072     /* In case of LFE we also land here, since there is no LFE SBR element (do upsampling only) */
   1073     fDoDecodeSbrData = 0;
   1074   }
   1075 
   1076   if (fDoDecodeSbrData)
   1077   {
   1078     if ((INT)FDKgetValidBits(hBs) <= 0) {
   1079       fDoDecodeSbrData = 0;
   1080     }
   1081   }
   1082 
   1083   /*
   1084      SBR CRC-check
   1085   */
   1086   if (fDoDecodeSbrData)
   1087   {
   1088     if (crcFlag) {
   1089       switch (self->coreCodec) {
   1090       case AOT_ER_AAC_ELD:
   1091         FDKpushFor (hBs, 10);
   1092         /* check sbrcrc later: we don't know the payload length now */
   1093         break;
   1094       case AOT_DRM_AAC:
   1095         drmSbrCrc = (USHORT)FDKreadBits(hBs, 8);
   1096         /* Setup CRC decoder */
   1097         FDKcrcInit(&crcInfo, 0x001d, 0xFFFF, 8);
   1098         /* Start CRC region */
   1099         crcReg = FDKcrcStartReg(&crcInfo, hBs, 0);
   1100         break;
   1101       default:
   1102         CRCLen = bsPayLen - 10;                     /* change: 0 => i */
   1103         if (CRCLen < 0) {
   1104           fDoDecodeSbrData = 0;
   1105         } else {
   1106           fDoDecodeSbrData = SbrCrcCheck (hBs, CRCLen);
   1107         }
   1108         break;
   1109       }
   1110     }
   1111   } /* if (fDoDecodeSbrData) */
   1112 
   1113   /*
   1114      Read in the header data and issue a reset if change occured
   1115   */
   1116   if (fDoDecodeSbrData)
   1117   {
   1118     int sbrHeaderPresent;
   1119 
   1120     {
   1121       sbrHeaderPresent = FDKreadBit(hBs);
   1122     }
   1123 
   1124     if ( sbrHeaderPresent ) {
   1125       headerStatus = sbrGetHeaderData (hSbrHeader,
   1126                                        hBs,
   1127                                        self->flags,
   1128                                        1);
   1129     }
   1130 
   1131     if (headerStatus == HEADER_RESET)
   1132     {
   1133       errorStatus = sbrDecoder_HeaderUpdate(
   1134             self,
   1135             hSbrHeader,
   1136             headerStatus,
   1137             pSbrChannel,
   1138             hSbrElement->nChannels
   1139             );
   1140 
   1141       if (errorStatus == SBRDEC_OK) {
   1142         hSbrHeader->syncState = SBR_HEADER;
   1143       } else {
   1144         hSbrHeader->syncState = SBR_NOT_INITIALIZED;
   1145         headerStatus = HEADER_ERROR;
   1146       }
   1147     }
   1148 
   1149     if (errorStatus != SBRDEC_OK) {
   1150       fDoDecodeSbrData = 0;
   1151     }
   1152   } /* if (fDoDecodeSbrData) */
   1153 
   1154   /*
   1155     Print debugging output only if state has changed
   1156   */
   1157 
   1158   /* read frame data */
   1159   if ((hSbrHeader->syncState >= SBR_HEADER) && fDoDecodeSbrData) {
   1160     int sbrFrameOk;
   1161     /* read the SBR element data */
   1162     if (stereo) {
   1163       sbrFrameOk = sbrGetChannelPairElement(hSbrHeader,
   1164                                             hFrameDataLeft,
   1165                                             hFrameDataRight,
   1166                                             hBs,
   1167                                             self->flags,
   1168                                             self->pSbrElement[elementIndex]->transposerSettings.overlap);
   1169     }
   1170     else {
   1171       if (self->hParametricStereoDec != NULL) {
   1172         /* update slot index for PS bitstream parsing */
   1173         self->hParametricStereoDec->bsLastSlot = self->hParametricStereoDec->bsReadSlot;
   1174         self->hParametricStereoDec->bsReadSlot = hSbrElement->useFrameSlot;
   1175       }
   1176       sbrFrameOk = sbrGetSingleChannelElement(hSbrHeader,
   1177                                               hFrameDataLeft,
   1178                                               hBs,
   1179                                               self->hParametricStereoDec,
   1180                                               self->flags,
   1181                                               self->pSbrElement[elementIndex]->transposerSettings.overlap);
   1182     }
   1183     if (!sbrFrameOk) {
   1184       fDoDecodeSbrData = 0;
   1185     }
   1186     else {
   1187       INT valBits;
   1188 
   1189       if (bsPayLen > 0) {
   1190         valBits = bsPayLen - ((INT)startPos - (INT)FDKgetValidBits(hBs));
   1191       } else {
   1192         valBits = (INT)FDKgetValidBits(hBs);
   1193       }
   1194 
   1195       if ( crcFlag ) {
   1196         switch (self->coreCodec) {
   1197         case AOT_ER_AAC_ELD:
   1198           {
   1199             /* late crc check for eld */
   1200             INT payloadbits = (INT)startPos - (INT)FDKgetValidBits(hBs) - startPos;
   1201             INT crcLen      = payloadbits - 10;
   1202             FDKpushBack(hBs, payloadbits);
   1203             fDoDecodeSbrData      = SbrCrcCheck (hBs, crcLen);
   1204             FDKpushFor(hBs, crcLen);
   1205           }
   1206           break;
   1207         case AOT_DRM_AAC:
   1208           /* End CRC region */
   1209           FDKcrcEndReg(&crcInfo, hBs, crcReg);
   1210           /* Check CRC */
   1211           if ((FDKcrcGetCRC(&crcInfo)^0xFF) != drmSbrCrc) {
   1212             fDoDecodeSbrData = 0;
   1213           }
   1214           break;
   1215         default:
   1216           break;
   1217         }
   1218       }
   1219 
   1220       /* sanity check of remaining bits */
   1221       if (valBits < 0) {
   1222         fDoDecodeSbrData = 0;
   1223       } else {
   1224         switch (self->coreCodec) {
   1225         case AOT_SBR:
   1226         case AOT_PS:
   1227         case AOT_AAC_LC:
   1228           {
   1229             /* This sanity check is only meaningful with General Audio bitstreams */
   1230             int alignBits = valBits & 0x7;
   1231 
   1232             if (valBits > alignBits) {
   1233               fDoDecodeSbrData = 0;
   1234             }
   1235           }
   1236           break;
   1237         default:
   1238           /* No sanity check available */
   1239           break;
   1240         }
   1241       }
   1242     }
   1243   } else {
   1244     /* The returned bit count will not be the actual payload size since we did not
   1245        parse the frame data. Return an error so that the caller can react respectively. */
   1246     errorStatus = SBRDEC_PARSE_ERROR;
   1247   }
   1248 
   1249   if (!fDoDecodeSbrData) {
   1250     /* Set error flag for this slot to trigger concealment */
   1251     self->pSbrElement[elementIndex]->frameErrorFlag[hSbrElement->useFrameSlot] = 1;
   1252     errorStatus = SBRDEC_PARSE_ERROR;
   1253   } else {
   1254     /* Everything seems to be ok so clear the error flag */
   1255     self->pSbrElement[elementIndex]->frameErrorFlag[hSbrElement->useFrameSlot] = 0;
   1256   }
   1257 
   1258   if (!stereo) {
   1259     /* Turn coupling off explicitely to avoid access to absent right frame data
   1260        that might occur with corrupt bitstreams. */
   1261     hFrameDataLeft->coupling = COUPLING_OFF;
   1262   }
   1263 
   1264 bail:
   1265 
   1266   if ( self->flags & SBRDEC_SYNTAX_DRM )
   1267   {
   1268     hBs = hBsOriginal;
   1269   }
   1270 
   1271   if ( (errorStatus == SBRDEC_OK)
   1272     || ( (errorStatus == SBRDEC_PARSE_ERROR)
   1273       && (headerStatus != HEADER_ERROR) ) )
   1274   {
   1275     int useOldHdr = ( (headerStatus == HEADER_NOT_PRESENT)
   1276                    || (headerStatus == HEADER_ERROR) ) ? 1 : 0;
   1277 
   1278     if (!useOldHdr && (thisHdrSlot != lastHdrSlot)) {
   1279       useOldHdr |= ( compareSbrHeader( hSbrHeader,
   1280                                       &self->sbrHeader[elementIndex][lastHdrSlot] ) == 0 ) ? 1 : 0;
   1281     }
   1282 
   1283     if (useOldHdr != 0) {
   1284       /* Use the old header for this frame */
   1285       hSbrElement->useHeaderSlot[hSbrElement->useFrameSlot] = lastHdrSlot;
   1286     } else {
   1287       /* Use the new header for this frame */
   1288       hSbrElement->useHeaderSlot[hSbrElement->useFrameSlot] = thisHdrSlot;
   1289     }
   1290 
   1291     /* Move frame pointer to the next slot which is up to be decoded/applied next */
   1292     hSbrElement->useFrameSlot = (hSbrElement->useFrameSlot+1) % (self->numDelayFrames+1);
   1293   }
   1294 
   1295   *count -= startPos - FDKgetValidBits(hBs);
   1296 
   1297   return errorStatus;
   1298 }
   1299 
   1300 
   1301 /**
   1302  * \brief Render one SBR element into time domain signal.
   1303  * \param self SBR decoder handle
   1304  * \param timeData pointer to output buffer
   1305  * \param interleaved flag indicating interleaved channel output
   1306  * \param channelMapping pointer to UCHAR array where next 2 channel offsets are stored.
   1307  * \param elementIndex enumerating index of the SBR element to render.
   1308  * \param numInChannels number of channels from core coder (reading stride).
   1309  * \param numOutChannels pointer to a location to return number of output channels.
   1310  * \param psPossible flag indicating if PS is possible or not.
   1311  * \return SBRDEC_OK if successfull, else error code
   1312  */
   1313 static SBR_ERROR
   1314 sbrDecoder_DecodeElement (
   1315         HANDLE_SBRDECODER    self,
   1316         INT_PCM             *timeData,
   1317         const int            interleaved,
   1318         const UCHAR         *channelMapping,
   1319         const int            elementIndex,
   1320         const int            numInChannels,
   1321         int                 *numOutChannels,
   1322         const int            psPossible
   1323         )
   1324 {
   1325   SBR_DECODER_ELEMENT *hSbrElement = self->pSbrElement[elementIndex];
   1326   HANDLE_SBR_CHANNEL    *pSbrChannel = self->pSbrElement[elementIndex]->pSbrChannel;
   1327   HANDLE_SBR_HEADER_DATA hSbrHeader = &self->sbrHeader[elementIndex][hSbrElement->useHeaderSlot[hSbrElement->useFrameSlot]];
   1328   HANDLE_PS_DEC h_ps_d = self->hParametricStereoDec;
   1329 
   1330   /* get memory for frame data from scratch */
   1331   SBR_FRAME_DATA *hFrameDataLeft  = &hSbrElement->pSbrChannel[0]->frameData[hSbrElement->useFrameSlot];
   1332   SBR_FRAME_DATA *hFrameDataRight = &hSbrElement->pSbrChannel[1]->frameData[hSbrElement->useFrameSlot];
   1333 
   1334   SBR_ERROR errorStatus = SBRDEC_OK;
   1335 
   1336 
   1337   INT  strideIn, strideOut, offset0, offset1;
   1338   INT  codecFrameSize = self->codecFrameSize;
   1339 
   1340   int  stereo = (hSbrElement->elementID == ID_CPE) ? 1 : 0;
   1341   int  numElementChannels = hSbrElement->nChannels; /* Number of channels of the current SBR element */
   1342 
   1343   if (self->flags & SBRDEC_FLUSH) {
   1344     if ( self->numFlushedFrames > self->numDelayFrames ) {
   1345       int hdrIdx;
   1346       /* No valid SBR payload available, hence switch to upsampling (in all headers) */
   1347       for (hdrIdx = 0; hdrIdx < ((1)+1); hdrIdx += 1) {
   1348         self->sbrHeader[elementIndex][hdrIdx].syncState = UPSAMPLING;
   1349       }
   1350     }
   1351     else {
   1352       /* Move frame pointer to the next slot which is up to be decoded/applied next */
   1353       hSbrElement->useFrameSlot = (hSbrElement->useFrameSlot+1) % (self->numDelayFrames+1);
   1354       /* Update header and frame data pointer because they have already been set */
   1355       hSbrHeader = &self->sbrHeader[elementIndex][hSbrElement->useHeaderSlot[hSbrElement->useFrameSlot]];
   1356       hFrameDataLeft  = &hSbrElement->pSbrChannel[0]->frameData[hSbrElement->useFrameSlot];
   1357       hFrameDataRight = &hSbrElement->pSbrChannel[1]->frameData[hSbrElement->useFrameSlot];
   1358     }
   1359   }
   1360 
   1361   /* Update the header error flag */
   1362   hSbrHeader->frameErrorFlag = hSbrElement->frameErrorFlag[hSbrElement->useFrameSlot];
   1363 
   1364   /*
   1365      Prepare filterbank for upsampling if no valid bit stream data is available.
   1366    */
   1367   if ( hSbrHeader->syncState == SBR_NOT_INITIALIZED )
   1368   {
   1369     errorStatus = initHeaderData(
   1370             hSbrHeader,
   1371             self->sampleRateIn,
   1372             self->sampleRateOut,
   1373             codecFrameSize,
   1374             self->flags
   1375             );
   1376 
   1377     if (errorStatus != SBRDEC_OK) {
   1378       return errorStatus;
   1379     }
   1380 
   1381     hSbrHeader->syncState = UPSAMPLING;
   1382 
   1383     errorStatus = sbrDecoder_HeaderUpdate(
   1384             self,
   1385             hSbrHeader,
   1386             HEADER_NOT_PRESENT,
   1387             pSbrChannel,
   1388             hSbrElement->nChannels
   1389             );
   1390 
   1391     if (errorStatus != SBRDEC_OK) {
   1392       hSbrHeader->syncState = SBR_NOT_INITIALIZED;
   1393       return errorStatus;
   1394     }
   1395   }
   1396 
   1397   /* reset */
   1398   if (hSbrHeader->status & SBRDEC_HDR_STAT_RESET) {
   1399     int ch;
   1400     for (ch = 0 ; ch < numElementChannels; ch++) {
   1401       SBR_ERROR errorStatusTmp = SBRDEC_OK;
   1402 
   1403       errorStatusTmp = resetSbrDec (
   1404              &pSbrChannel[ch]->SbrDec,
   1405               hSbrHeader,
   1406              &pSbrChannel[ch]->prevFrameData,
   1407               self->flags & SBRDEC_LOW_POWER,
   1408               self->synDownsampleFac
   1409               );
   1410 
   1411       if (errorStatusTmp != SBRDEC_OK) {
   1412         errorStatus = errorStatusTmp;
   1413       }
   1414     }
   1415     hSbrHeader->status &= ~SBRDEC_HDR_STAT_RESET;
   1416   }
   1417 
   1418   /* decoding */
   1419   if ( (hSbrHeader->syncState == SBR_ACTIVE)
   1420     || ((hSbrHeader->syncState == SBR_HEADER) && (hSbrHeader->frameErrorFlag == 0)) )
   1421   {
   1422     errorStatus = SBRDEC_OK;
   1423 
   1424     decodeSbrData (hSbrHeader,
   1425                    hFrameDataLeft,
   1426                   &pSbrChannel[0]->prevFrameData,
   1427                    (stereo) ? hFrameDataRight : NULL,
   1428                    (stereo) ? &pSbrChannel[1]->prevFrameData : NULL);
   1429 
   1430 
   1431     /* Now we have a full parameter set and can do parameter
   1432        based concealment instead of plain upsampling. */
   1433     hSbrHeader->syncState = SBR_ACTIVE;
   1434   }
   1435 
   1436   /* decode PS data if available */
   1437   if (h_ps_d != NULL && psPossible) {
   1438     int applyPs = 1;
   1439 
   1440     /* define which frame delay line slot to process */
   1441     h_ps_d->processSlot = hSbrElement->useFrameSlot;
   1442 
   1443     applyPs = DecodePs(h_ps_d, hSbrHeader->frameErrorFlag);
   1444     self->flags |= (applyPs) ? SBRDEC_PS_DECODED : 0;
   1445   }
   1446 
   1447   /* Set strides for reading and writing */
   1448   if (interleaved) {
   1449     strideIn = numInChannels;
   1450     if ( psPossible )
   1451       strideOut = (numInChannels < 2) ? 2 : numInChannels;
   1452     else
   1453       strideOut = numInChannels;
   1454     offset0 = channelMapping[0];
   1455     offset1 = channelMapping[1];
   1456   } else {
   1457     strideIn  = 1;
   1458     strideOut = 1;
   1459     offset0 = channelMapping[0]*2*codecFrameSize;
   1460     offset1 = channelMapping[1]*2*codecFrameSize;
   1461   }
   1462 
   1463   /* use same buffers for left and right channel and apply PS per timeslot */
   1464   /* Process left channel */
   1465 //FDKprintf("self->codecFrameSize %d\t%d\n",self->codecFrameSize,self->sampleRateIn);
   1466   sbr_dec (&pSbrChannel[0]->SbrDec,
   1467             timeData + offset0,
   1468             timeData + offset0,
   1469            &pSbrChannel[1]->SbrDec,
   1470             timeData + offset1,
   1471             strideIn,
   1472             strideOut,
   1473             hSbrHeader,
   1474             hFrameDataLeft,
   1475            &pSbrChannel[0]->prevFrameData,
   1476             (hSbrHeader->syncState == SBR_ACTIVE),
   1477             h_ps_d,
   1478             self->flags,
   1479             codecFrameSize
   1480           );
   1481 
   1482   if (stereo) {
   1483     /* Process right channel */
   1484     sbr_dec (&pSbrChannel[1]->SbrDec,
   1485               timeData + offset1,
   1486               timeData + offset1,
   1487               NULL,
   1488               NULL,
   1489               strideIn,
   1490               strideOut,
   1491               hSbrHeader,
   1492               hFrameDataRight,
   1493              &pSbrChannel[1]->prevFrameData,
   1494               (hSbrHeader->syncState == SBR_ACTIVE),
   1495               NULL,
   1496               self->flags,
   1497               codecFrameSize
   1498             );
   1499   }
   1500 
   1501   if (h_ps_d != NULL) {
   1502     /* save PS status for next run */
   1503     h_ps_d->psDecodedPrv = (self->flags & SBRDEC_PS_DECODED) ? 1 : 0 ;
   1504   }
   1505 
   1506   if ( psPossible
   1507     )
   1508   {
   1509     FDK_ASSERT(strideOut > 1);
   1510     if ( !(self->flags & SBRDEC_PS_DECODED) ) {
   1511       /* A decoder which is able to decode PS has to produce a stereo output even if no PS data is availble. */
   1512       /* So copy left channel to right channel.                                                              */
   1513       int copyFrameSize = codecFrameSize * 2 / self->synDownsampleFac;
   1514       if (interleaved) {
   1515         INT_PCM *ptr;
   1516         INT i;
   1517         FDK_ASSERT(strideOut == 2);
   1518 
   1519         ptr = timeData;
   1520         for (i = copyFrameSize>>1; i--; )
   1521         {
   1522           INT_PCM tmp; /* This temporal variable is required because some compilers can't do *ptr++ = *ptr++ correctly. */
   1523           tmp = *ptr++; *ptr++ = tmp;
   1524           tmp = *ptr++; *ptr++ = tmp;
   1525         }
   1526       } else {
   1527         FDKmemcpy( timeData+copyFrameSize, timeData, copyFrameSize*sizeof(INT_PCM) );
   1528       }
   1529     }
   1530     *numOutChannels = 2;  /* Output minimum two channels when PS is enabled. */
   1531   }
   1532 
   1533   return errorStatus;
   1534 }
   1535 
   1536 
   1537 SBR_ERROR sbrDecoder_Apply ( HANDLE_SBRDECODER   self,
   1538                              INT_PCM            *timeData,
   1539                              int                *numChannels,
   1540                              int                *sampleRate,
   1541                              const UCHAR         channelMapping[(8)],
   1542                              const int           interleaved,
   1543                              const int           coreDecodedOk,
   1544                              UCHAR              *psDecoded )
   1545 {
   1546   SBR_ERROR errorStatus = SBRDEC_OK;
   1547 
   1548   int   psPossible = 0;
   1549   int   sbrElementNum;
   1550   int   numCoreChannels = *numChannels;
   1551   int   numSbrChannels  = 0;
   1552 
   1553   psPossible = *psDecoded;
   1554 
   1555   if (self->numSbrElements < 1) {
   1556     /* exit immediately to avoid access violations */
   1557     return SBRDEC_CREATE_ERROR;
   1558   }
   1559 
   1560   /* Sanity check of allocated SBR elements. */
   1561   for (sbrElementNum=0; sbrElementNum<self->numSbrElements; sbrElementNum++) {
   1562     if (self->pSbrElement[sbrElementNum] == NULL) {
   1563       return SBRDEC_CREATE_ERROR;
   1564     }
   1565   }
   1566 
   1567   if (self->numSbrElements != 1 || self->pSbrElement[0]->elementID != ID_SCE) {
   1568     psPossible = 0;
   1569   }
   1570 
   1571 
   1572   /* In case of non-interleaved time domain data and upsampling, make room for bigger SBR output. */
   1573   if (self->synDownsampleFac == 1 && interleaved == 0) {
   1574     int c, outputFrameSize;
   1575 
   1576     outputFrameSize =
   1577             self->pSbrElement[0]->pSbrChannel[0]->SbrDec.SynthesisQMF.no_channels
   1578             * self->pSbrElement[0]->pSbrChannel[0]->SbrDec.SynthesisQMF.no_col;
   1579 
   1580     for (c=numCoreChannels-1; c>0; c--) {
   1581       FDKmemmove(timeData + c*outputFrameSize, timeData + c*self->codecFrameSize , self->codecFrameSize*sizeof(INT_PCM));
   1582     }
   1583   }
   1584 
   1585 
   1586   /* Make sure that even if no SBR data was found/parsed *psDecoded is returned 1 if psPossible was 0. */
   1587   if (psPossible == 0) {
   1588     self->flags &= ~SBRDEC_PS_DECODED;
   1589   }
   1590 
   1591   if ( self->flags & SBRDEC_FLUSH ) {
   1592     /* flushing is signalized, hence increment the flush frame counter */
   1593     self->numFlushedFrames++;
   1594   }
   1595   else {
   1596     /* no flushing is signalized, hence reset the flush frame counter */
   1597     self->numFlushedFrames = 0;
   1598   }
   1599 
   1600   /* Loop over SBR elements */
   1601   for (sbrElementNum = 0; sbrElementNum<self->numSbrElements; sbrElementNum++)
   1602   {
   1603     int numElementChan;
   1604 
   1605     if (psPossible && self->pSbrElement[sbrElementNum]->pSbrChannel[1] == NULL) {
   1606       /* Disable PS and try decoding SBR mono. */
   1607       psPossible = 0;
   1608     }
   1609 
   1610     numElementChan = (self->pSbrElement[sbrElementNum]->elementID == ID_CPE) ? 2 : 1;
   1611 
   1612     /* If core signal is bad then force upsampling */
   1613     if ( ! coreDecodedOk ) {
   1614       self->pSbrElement[sbrElementNum]->frameErrorFlag[self->pSbrElement[sbrElementNum]->useFrameSlot] = 1;
   1615     }
   1616 
   1617     errorStatus = sbrDecoder_DecodeElement (
   1618                                  self,
   1619                                  timeData,
   1620                                  interleaved,
   1621                                  channelMapping,
   1622                                  sbrElementNum,
   1623                                  numCoreChannels,
   1624                                 &numElementChan,
   1625                                  psPossible
   1626                                );
   1627 
   1628     if (errorStatus != SBRDEC_OK) {
   1629       goto bail;
   1630     }
   1631 
   1632     numSbrChannels += numElementChan;
   1633     channelMapping += numElementChan;
   1634 
   1635     if (numSbrChannels >= numCoreChannels) {
   1636       break;
   1637     }
   1638   }
   1639 
   1640   /* Update numChannels and samplerate */
   1641   *numChannels = numSbrChannels;
   1642   *sampleRate = self->sampleRateOut;
   1643   *psDecoded = (self->flags & SBRDEC_PS_DECODED) ? 1 : 0;
   1644 
   1645 
   1646 
   1647   /* Clear reset and flush flag because everything seems to be done successfully. */
   1648   self->flags &= ~SBRDEC_FORCE_RESET;
   1649   self->flags &= ~SBRDEC_FLUSH;
   1650 
   1651 bail:
   1652 
   1653   return errorStatus;
   1654 }
   1655 
   1656 
   1657 SBR_ERROR sbrDecoder_Close ( HANDLE_SBRDECODER *pSelf )
   1658 {
   1659   HANDLE_SBRDECODER self = *pSelf;
   1660   int i;
   1661 
   1662   if (self != NULL)
   1663   {
   1664     if (self->hParametricStereoDec != NULL) {
   1665       DeletePsDec ( &self->hParametricStereoDec );
   1666     }
   1667 
   1668     if (self->workBuffer1 != NULL) {
   1669       FreeRam_SbrDecWorkBuffer1(&self->workBuffer1);
   1670     }
   1671     if (self->workBuffer2 != NULL) {
   1672       FreeRam_SbrDecWorkBuffer2(&self->workBuffer2);
   1673     }
   1674 
   1675     for (i = 0; i < (8); i++) {
   1676       sbrDecoder_DestroyElement( self, i );
   1677     }
   1678 
   1679     FreeRam_SbrDecoder(pSelf);
   1680   }
   1681 
   1682   return SBRDEC_OK;
   1683 }
   1684 
   1685 
   1686 INT sbrDecoder_GetLibInfo( LIB_INFO *info )
   1687 {
   1688   int i;
   1689 
   1690   if (info == NULL) {
   1691     return -1;
   1692   }
   1693 
   1694   /* search for next free tab */
   1695   for (i = 0; i < FDK_MODULE_LAST; i++) {
   1696     if (info[i].module_id == FDK_NONE)
   1697       break;
   1698   }
   1699   if (i == FDK_MODULE_LAST)
   1700     return -1;
   1701   info += i;
   1702 
   1703   info->module_id = FDK_SBRDEC;
   1704   info->version = LIB_VERSION(SBRDECODER_LIB_VL0, SBRDECODER_LIB_VL1, SBRDECODER_LIB_VL2);
   1705   LIB_VERSION_STRING(info);
   1706   info->build_date = (char *)SBRDECODER_LIB_BUILD_DATE;
   1707   info->build_time = (char *)SBRDECODER_LIB_BUILD_TIME;
   1708   info->title      = (char *)SBRDECODER_LIB_TITLE;
   1709 
   1710   /* Set flags */
   1711   info->flags = 0
   1712     | CAPF_SBR_HQ
   1713     | CAPF_SBR_LP
   1714     | CAPF_SBR_PS_MPEG
   1715     | CAPF_SBR_DRM_BS
   1716     | CAPF_SBR_CONCEALMENT
   1717     | CAPF_SBR_DRC
   1718       ;
   1719   /* End of flags */
   1720 
   1721   return 0;
   1722 }
   1723 
   1724 
   1725 UINT sbrDecoder_GetDelay( const HANDLE_SBRDECODER self )
   1726 {
   1727   UINT outputDelay = 0;
   1728 
   1729   if ( self != NULL) {
   1730     UINT flags = self->flags;
   1731 
   1732     /* See chapter 1.6.7.2 of ISO/IEC 14496-3 for the GA-SBR figures below. */
   1733 
   1734     /* Are we initialized? */
   1735     if ( (self->numSbrChannels > 0)
   1736       && (self->numSbrElements > 0) )
   1737     {
   1738       /* Add QMF synthesis delay */
   1739       if ( (flags & SBRDEC_ELD_GRID)
   1740         && IS_LOWDELAY(self->coreCodec) ) {
   1741         /* Low delay SBR: */
   1742         {
   1743           outputDelay += (flags & SBRDEC_DOWNSAMPLE) ? 32 : 64;   /* QMF synthesis */
   1744           if (flags & SBRDEC_LD_MPS_QMF) {
   1745             outputDelay += 32;
   1746           }
   1747         }
   1748       }
   1749       else if (!IS_USAC(self->coreCodec)) {
   1750         /* By the method of elimination this is the GA (AAC-LC, HE-AAC, ...) branch: */
   1751         outputDelay += (flags & SBRDEC_DOWNSAMPLE) ? 481 : 962;
   1752       }
   1753     }
   1754   }
   1755 
   1756   return (outputDelay);
   1757 }
   1758