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 - 2012 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
     87   This module provides the actual decoder implementation. The SBR data (side information) is already
     88   decoded. Only three functions are provided:
     89 
     90   \li 1.) createSbrDec(): One time initialization
     91   \li 2.) resetSbrDec(): Called by sbr_Apply() when the information contained in an SBR_HEADER_ELEMENT requires a reset
     92   and recalculation of important SBR structures.
     93   \li 3.) sbr_dec(): The actual decoder. Calls the different tools such as filterbanks, lppTransposer(), and calculateSbrEnvelope()
     94   [the envelope adjuster].
     95 
     96   \sa sbr_dec(), \ref documentationOverview
     97 */
     98 
     99 #include "sbr_dec.h"
    100 
    101 #include "sbr_ram.h"
    102 #include "env_extr.h"
    103 #include "env_calc.h"
    104 #include "scale.h"
    105 
    106 #include "genericStds.h"
    107 
    108 #include "sbrdec_drc.h"
    109 
    110 
    111 
    112 static void assignLcTimeSlots( HANDLE_SBR_DEC hSbrDec,                     /*!< handle to Decoder channel */
    113                                FIXP_DBL  **QmfBufferReal,
    114                                int noCols )
    115 {
    116   int slot, i;
    117   FIXP_DBL  *ptr;
    118 
    119   /* Number of QMF timeslots in the overlap buffer: */
    120   ptr = hSbrDec->pSbrOverlapBuffer;
    121   for(slot=0; slot<hSbrDec->LppTrans.pSettings->overlap; slot++) {
    122     QmfBufferReal[slot] = ptr; ptr += (64);
    123   }
    124 
    125   /* Assign timeslots to Workbuffer1 */
    126   ptr = hSbrDec->WorkBuffer1;
    127   for(i=0; i<noCols; i++) {
    128     QmfBufferReal[slot] = ptr; ptr += (64);
    129     slot++;
    130   }
    131 }
    132 
    133 
    134 static void assignHqTimeSlots( HANDLE_SBR_DEC hSbrDec,                     /*!< handle to Decoder channel */
    135                                FIXP_DBL  **QmfBufferReal,
    136                                FIXP_DBL  **QmfBufferImag,
    137                                int noCols )
    138 {
    139   FIXP_DBL  *ptr;
    140   int slot;
    141 
    142   /* Number of QMF timeslots in one half of a frame (size of Workbuffer1 or 2): */
    143   int halflen = (noCols >> 1) + hSbrDec->LppTrans.pSettings->overlap;
    144   int totCols = noCols + hSbrDec->LppTrans.pSettings->overlap;
    145 
    146   /* Number of QMF timeslots in the overlap buffer: */
    147   ptr = hSbrDec->pSbrOverlapBuffer;
    148   for(slot=0; slot<hSbrDec->LppTrans.pSettings->overlap; slot++) {
    149     QmfBufferReal[slot] = ptr; ptr += (64);
    150     QmfBufferImag[slot] = ptr; ptr += (64);
    151   }
    152 
    153   /* Assign first half of timeslots to Workbuffer1 */
    154   ptr = hSbrDec->WorkBuffer1;
    155   for(; slot<halflen; slot++) {
    156     QmfBufferReal[slot] = ptr; ptr += (64);
    157     QmfBufferImag[slot] = ptr; ptr += (64);
    158   }
    159 
    160   /* Assign second half of timeslots to Workbuffer2 */
    161   ptr = hSbrDec->WorkBuffer2;
    162   for(; slot<totCols; slot++) {
    163     QmfBufferReal[slot] = ptr; ptr += (64);
    164     QmfBufferImag[slot] = ptr; ptr += (64);
    165   }
    166 }
    167 
    168 
    169 static void assignTimeSlots( HANDLE_SBR_DEC hSbrDec,                     /*!< handle to Decoder channel */
    170                              int noCols,
    171                              int useLP )
    172 {
    173  /* assign qmf time slots */
    174   hSbrDec->useLP = useLP;
    175   if (useLP) {
    176     hSbrDec->SynthesisQMF.flags |= QMF_FLAG_LP;
    177     hSbrDec->AnalysiscQMF.flags |= QMF_FLAG_LP;
    178   } else {
    179     hSbrDec->SynthesisQMF.flags &= ~QMF_FLAG_LP;
    180     hSbrDec->AnalysiscQMF.flags &= ~QMF_FLAG_LP;
    181   }
    182   if (!useLP)
    183     assignHqTimeSlots( hSbrDec, hSbrDec->QmfBufferReal, hSbrDec->QmfBufferImag, noCols );
    184   else
    185   {
    186     assignLcTimeSlots( hSbrDec, hSbrDec->QmfBufferReal, noCols );
    187   }
    188 }
    189 
    190 static void changeQmfType( HANDLE_SBR_DEC hSbrDec,                     /*!< handle to Decoder channel */
    191                            int useLdTimeAlign )
    192 {
    193   UINT synQmfFlags = hSbrDec->SynthesisQMF.flags;
    194   UINT anaQmfFlags = hSbrDec->AnalysiscQMF.flags;
    195   int  resetSynQmf = 0;
    196   int  resetAnaQmf = 0;
    197 
    198   /* assign qmf type */
    199   if (useLdTimeAlign) {
    200     if (synQmfFlags & QMF_FLAG_CLDFB) {
    201       /* change the type to MPSLD */
    202       synQmfFlags &= ~QMF_FLAG_CLDFB;
    203       synQmfFlags |=  QMF_FLAG_MPSLDFB;
    204       resetSynQmf = 1;
    205     }
    206     if (anaQmfFlags & QMF_FLAG_CLDFB) {
    207       /* change the type to MPSLD */
    208       anaQmfFlags &= ~QMF_FLAG_CLDFB;
    209       anaQmfFlags |=  QMF_FLAG_MPSLDFB;
    210       resetAnaQmf = 1;
    211     }
    212   } else {
    213     if (synQmfFlags & QMF_FLAG_MPSLDFB) {
    214       /* change the type to CLDFB */
    215       synQmfFlags &= ~QMF_FLAG_MPSLDFB;
    216       synQmfFlags |=  QMF_FLAG_CLDFB;
    217       resetSynQmf = 1;
    218     }
    219     if (anaQmfFlags & QMF_FLAG_MPSLDFB) {
    220       /* change the type to CLDFB */
    221       anaQmfFlags &= ~QMF_FLAG_MPSLDFB;
    222       anaQmfFlags |=  QMF_FLAG_CLDFB;
    223       resetAnaQmf = 1;
    224     }
    225   }
    226 
    227   if (resetAnaQmf) {
    228     int qmfErr = qmfInitAnalysisFilterBank (
    229            &hSbrDec->AnalysiscQMF,
    230             hSbrDec->anaQmfStates,
    231             hSbrDec->AnalysiscQMF.no_col,
    232             hSbrDec->AnalysiscQMF.lsb,
    233             hSbrDec->AnalysiscQMF.usb,
    234             hSbrDec->AnalysiscQMF.no_channels,
    235             anaQmfFlags | QMF_FLAG_KEEP_STATES
    236             );
    237     if (qmfErr != 0) {
    238       FDK_ASSERT(0);
    239     }
    240   }
    241 
    242   if (resetSynQmf) {
    243     int qmfErr = qmfInitSynthesisFilterBank (
    244            &hSbrDec->SynthesisQMF,
    245             hSbrDec->pSynQmfStates,
    246             hSbrDec->SynthesisQMF.no_col,
    247             hSbrDec->SynthesisQMF.lsb,
    248             hSbrDec->SynthesisQMF.usb,
    249             hSbrDec->SynthesisQMF.no_channels,
    250             synQmfFlags | QMF_FLAG_KEEP_STATES
    251             );
    252 
    253     if (qmfErr != 0) {
    254       FDK_ASSERT(0);
    255     }
    256   }
    257 }
    258 
    259 
    260 /*!
    261   \brief      SBR decoder core function for one channel
    262 
    263   \image html  BufferMgmtDetailed-1632.png
    264 
    265   Besides the filter states of the QMF filter bank and the LPC-states of
    266   the LPP-Transposer, processing is mainly based on four buffers:
    267   #timeIn, #timeOut, #WorkBuffer2 and #OverlapBuffer. The #WorkBuffer2
    268   is reused for all channels and might be used by the core decoder, a
    269   static overlap buffer is required for each channel. Du to in-place
    270   processing, #timeIn and #timeOut point to identical locations.
    271 
    272   The spectral data is organized in so-called slots, each slot
    273   containing 64 bands of complex data. The number of slots per frame is
    274   dependend on the frame size. For mp3PRO, there are 18 slots per frame
    275   and 6 slots per #OverlapBuffer. It is not necessary to have the slots
    276   in located consecutive address ranges.
    277 
    278   To optimize memory usage and to minimize the number of memory
    279   accesses, the memory management is organized as follows (Slot numbers
    280   based on mp3PRO):
    281 
    282   1.) Input time domain signal is located in #timeIn, the last slots
    283   (0..5) of the spectral data of the previous frame are located in the
    284   #OverlapBuffer. In addition, #frameData of the current frame resides
    285   in the upper part of #timeIn.
    286 
    287   2.) During the cplxAnalysisQmfFiltering(), 32 samples from #timeIn are transformed
    288   into a slot of up to 32 complex spectral low band values at a
    289   time. The first spectral slot -- nr. 6 -- is written at slot number
    290   zero of #WorkBuffer2. #WorkBuffer2 will be completely filled with
    291   spectral data.
    292 
    293   3.) LPP-Transposition in lppTransposer() is processed on 24 slots. During the
    294   transposition, the high band part of the spectral data is replicated
    295   based on the low band data.
    296 
    297   Envelope Adjustment is processed on the high band part of the spectral
    298   data only by calculateSbrEnvelope().
    299 
    300   4.) The cplxSynthesisQmfFiltering() creates 64 time domain samples out
    301   of a slot of 64 complex spectral values at a time. The first 6 slots
    302   in #timeOut are filled from the results of spectral slots 0..5 in the
    303   #OverlapBuffer. The consecutive slots in timeOut are now filled with
    304   the results of spectral slots 6..17.
    305 
    306   5.) The preprocessed slots 18..23 have to be stored in the
    307   #OverlapBuffer.
    308 
    309 */
    310 
    311 void
    312 sbr_dec ( HANDLE_SBR_DEC hSbrDec,            /*!< handle to Decoder channel */
    313           INT_PCM *timeIn,                   /*!< pointer to input time signal */
    314           INT_PCM *timeOut,                  /*!< pointer to output time signal */
    315           HANDLE_SBR_DEC hSbrDecRight,       /*!< handle to Decoder channel right */
    316           INT_PCM *timeOutRight,             /*!< pointer to output time signal */
    317           const int strideIn,                /*!< Time data traversal strideIn */
    318           const int strideOut,               /*!< Time data traversal strideOut */
    319           HANDLE_SBR_HEADER_DATA hHeaderData,/*!< Static control data */
    320           HANDLE_SBR_FRAME_DATA hFrameData,  /*!< Control data of current frame */
    321           HANDLE_SBR_PREV_FRAME_DATA hPrevFrameData,  /*!< Some control data of last frame */
    322           const int applyProcessing,         /*!< Flag for SBR operation */
    323           HANDLE_PS_DEC h_ps_d,
    324           const UINT flags
    325          )
    326 {
    327   int i, slot, reserve;
    328   int saveLbScale;
    329   int ov_len;
    330   int lastSlotOffs;
    331   FIXP_DBL maxVal;
    332 
    333   /* 1+1/3 frames of spectral data: */
    334   FIXP_DBL **QmfBufferReal = hSbrDec->QmfBufferReal;
    335   FIXP_DBL **QmfBufferImag = hSbrDec->QmfBufferImag;
    336 
    337  /* Number of QMF timeslots in the overlap buffer: */
    338  ov_len = hSbrDec->LppTrans.pSettings->overlap;
    339 
    340  /* Number of QMF slots per frame */
    341   int noCols = hHeaderData->numberTimeSlots * hHeaderData->timeStep;
    342 
    343  /* assign qmf time slots */
    344   if ( ((flags & SBRDEC_LOW_POWER ) ? 1 : 0) != ((hSbrDec->SynthesisQMF.flags & QMF_FLAG_LP) ? 1 : 0) ) {
    345     assignTimeSlots( hSbrDec, hHeaderData->numberTimeSlots * hHeaderData->timeStep, flags & SBRDEC_LOW_POWER);
    346   }
    347 
    348   if (flags & SBRDEC_ELD_GRID) {
    349     /* Choose the right low delay filter bank */
    350     changeQmfType( hSbrDec, (flags & SBRDEC_LD_MPS_QMF) ? 1 : 0 );
    351   }
    352 
    353   /*
    354     low band codec signal subband filtering
    355    */
    356 
    357   {
    358     C_AALLOC_SCRATCH_START(qmfTemp, FIXP_DBL, 2*(64));
    359 
    360     qmfAnalysisFiltering( &hSbrDec->AnalysiscQMF,
    361                            QmfBufferReal + ov_len,
    362                            QmfBufferImag + ov_len,
    363                           &hSbrDec->sbrScaleFactor,
    364                            timeIn,
    365                            strideIn,
    366                            qmfTemp
    367                          );
    368 
    369     C_AALLOC_SCRATCH_END(qmfTemp, FIXP_DBL, 2*(64));
    370   }
    371 
    372   /*
    373     Clear upper half of spectrum
    374   */
    375   {
    376     int nAnalysisBands = hHeaderData->numberOfAnalysisBands;
    377 
    378     if (! (flags & SBRDEC_LOW_POWER)) {
    379       for (slot = ov_len; slot < noCols+ov_len; slot++) {
    380         FDKmemclear(&QmfBufferReal[slot][nAnalysisBands],((64)-nAnalysisBands)*sizeof(FIXP_DBL));
    381         FDKmemclear(&QmfBufferImag[slot][nAnalysisBands],((64)-nAnalysisBands)*sizeof(FIXP_DBL));
    382       }
    383     } else
    384     for (slot = ov_len; slot < noCols+ov_len; slot++) {
    385       FDKmemclear(&QmfBufferReal[slot][nAnalysisBands],((64)-nAnalysisBands)*sizeof(FIXP_DBL));
    386     }
    387   }
    388 
    389 
    390 
    391   /*
    392     Shift spectral data left to gain accuracy in transposer and adjustor
    393   */
    394   maxVal = maxSubbandSample( QmfBufferReal,
    395                             (flags & SBRDEC_LOW_POWER) ? NULL : QmfBufferImag,
    396                              0,
    397                              hSbrDec->AnalysiscQMF.lsb,
    398                              ov_len,
    399                              noCols+ov_len );
    400 
    401   reserve = fixMax(0,CntLeadingZeros(maxVal)-1) ;
    402   reserve = fixMin(reserve,DFRACT_BITS-1-hSbrDec->sbrScaleFactor.lb_scale);
    403 
    404   /* If all data is zero, lb_scale could become too large */
    405   rescaleSubbandSamples( QmfBufferReal,
    406                          (flags & SBRDEC_LOW_POWER) ? NULL : QmfBufferImag,
    407                          0,
    408                          hSbrDec->AnalysiscQMF.lsb,
    409                          ov_len,
    410                          noCols+ov_len,
    411                          reserve);
    412 
    413   hSbrDec->sbrScaleFactor.lb_scale += reserve;
    414 
    415   /*
    416     save low band scale, wavecoding or parametric stereo may modify it
    417   */
    418   saveLbScale = hSbrDec->sbrScaleFactor.lb_scale;
    419 
    420 
    421   if (applyProcessing)
    422   {
    423     UCHAR * borders = hFrameData->frameInfo.borders;
    424     lastSlotOffs =  borders[hFrameData->frameInfo.nEnvelopes] - hHeaderData->numberTimeSlots;
    425 
    426     FIXP_DBL degreeAlias[(64)];
    427 
    428     /* The transposer will override most values in degreeAlias[].
    429        The array needs to be cleared at least from lowSubband to highSubband before. */
    430     if (flags & SBRDEC_LOW_POWER)
    431       FDKmemclear(&degreeAlias[hHeaderData->freqBandData.lowSubband], (hHeaderData->freqBandData.highSubband-hHeaderData->freqBandData.lowSubband)*sizeof(FIXP_DBL));
    432 
    433     /*
    434       Inverse filtering of lowband and transposition into the SBR-frequency range
    435     */
    436 
    437     lppTransposer ( &hSbrDec->LppTrans,
    438                     &hSbrDec->sbrScaleFactor,
    439                     QmfBufferReal,
    440                     degreeAlias,                  // only used if useLP = 1
    441                     QmfBufferImag,
    442                     flags & SBRDEC_LOW_POWER,
    443                     hHeaderData->timeStep,
    444                     borders[0],
    445                     lastSlotOffs,
    446                     hHeaderData->freqBandData.nInvfBands,
    447                     hFrameData->sbr_invf_mode,
    448                     hPrevFrameData->sbr_invf_mode );
    449 
    450 
    451 
    452 
    453 
    454     /*
    455       Adjust envelope of current frame.
    456     */
    457 
    458     calculateSbrEnvelope (&hSbrDec->sbrScaleFactor,
    459                           &hSbrDec->SbrCalculateEnvelope,
    460                           hHeaderData,
    461                           hFrameData,
    462                           QmfBufferReal,
    463                           QmfBufferImag,
    464                           flags & SBRDEC_LOW_POWER,
    465 
    466                           degreeAlias,
    467                           flags,
    468                           (hHeaderData->frameErrorFlag || hPrevFrameData->frameErrorFlag));
    469 
    470 
    471     /*
    472       Update hPrevFrameData (to be used in the next frame)
    473     */
    474     for (i=0; i<hHeaderData->freqBandData.nInvfBands; i++) {
    475       hPrevFrameData->sbr_invf_mode[i] = hFrameData->sbr_invf_mode[i];
    476     }
    477     hPrevFrameData->coupling = hFrameData->coupling;
    478     hPrevFrameData->stopPos = borders[hFrameData->frameInfo.nEnvelopes];
    479     hPrevFrameData->ampRes = hFrameData->ampResolutionCurrentFrame;
    480   }
    481   else {
    482     /* Reset hb_scale if no highband is present, because hb_scale is considered in the QMF-synthesis */
    483     hSbrDec->sbrScaleFactor.hb_scale = saveLbScale;
    484   }
    485 
    486 
    487   for (i=0; i<LPC_ORDER; i++){
    488     /*
    489       Store the unmodified qmf Slots values (required for LPC filtering)
    490     */
    491     if (! (flags & SBRDEC_LOW_POWER)) {
    492       FDKmemcpy(hSbrDec->LppTrans.lpcFilterStatesReal[i], QmfBufferReal[noCols-LPC_ORDER+i], hSbrDec->AnalysiscQMF.lsb*sizeof(FIXP_DBL));
    493       FDKmemcpy(hSbrDec->LppTrans.lpcFilterStatesImag[i], QmfBufferImag[noCols-LPC_ORDER+i], hSbrDec->AnalysiscQMF.lsb*sizeof(FIXP_DBL));
    494     } else
    495     FDKmemcpy(hSbrDec->LppTrans.lpcFilterStatesReal[i], QmfBufferReal[noCols-LPC_ORDER+i], hSbrDec->AnalysiscQMF.lsb*sizeof(FIXP_DBL));
    496   }
    497 
    498   /*
    499     Synthesis subband filtering.
    500   */
    501 
    502   if ( ! (flags & SBRDEC_PS_DECODED) ) {
    503 
    504     {
    505       int outScalefactor = 0;
    506 
    507       if (h_ps_d != NULL) {
    508         h_ps_d->procFrameBased = 1;  /* we here do frame based processing */
    509       }
    510 
    511 
    512       sbrDecoder_drcApply(&hSbrDec->sbrDrcChannel,
    513                            QmfBufferReal,
    514                            (flags & SBRDEC_LOW_POWER) ? NULL : QmfBufferImag,
    515                            hSbrDec->SynthesisQMF.no_col,
    516                           &outScalefactor
    517                           );
    518 
    519 
    520 
    521       qmfChangeOutScalefactor(&hSbrDec->SynthesisQMF, outScalefactor );
    522 
    523       {
    524         C_AALLOC_SCRATCH_START(qmfTemp, FIXP_DBL, 2*(64));
    525 
    526         qmfSynthesisFiltering( &hSbrDec->SynthesisQMF,
    527                                 QmfBufferReal,
    528                                 (flags & SBRDEC_LOW_POWER) ? NULL : QmfBufferImag,
    529                                &hSbrDec->sbrScaleFactor,
    530                                 hSbrDec->LppTrans.pSettings->overlap,
    531                                 timeOut,
    532                                 strideOut,
    533                                 qmfTemp);
    534 
    535         C_AALLOC_SCRATCH_END(qmfTemp, FIXP_DBL, 2*(64));
    536       }
    537 
    538     }
    539 
    540   } else { /* (flags & SBRDEC_PS_DECODED) */
    541     INT i, sdiff, outScalefactor, scaleFactorLowBand, scaleFactorHighBand;
    542     SCHAR scaleFactorLowBand_ov, scaleFactorLowBand_no_ov;
    543 
    544     HANDLE_QMF_FILTER_BANK synQmf      = &hSbrDec->SynthesisQMF;
    545     HANDLE_QMF_FILTER_BANK synQmfRight = &hSbrDecRight->SynthesisQMF;
    546 
    547     /* adapt scaling */
    548     sdiff = hSbrDec->sbrScaleFactor.lb_scale - reserve;                  /* Scaling difference         */
    549     scaleFactorHighBand   = sdiff - hSbrDec->sbrScaleFactor.hb_scale;    /* Scale of current high band */
    550     scaleFactorLowBand_ov = sdiff - hSbrDec->sbrScaleFactor.ov_lb_scale; /* Scale of low band overlapping QMF data */
    551     scaleFactorLowBand_no_ov = sdiff - hSbrDec->sbrScaleFactor.lb_scale; /* Scale of low band current QMF data     */
    552     outScalefactor  = 0;                                                 /* Initial output scale */
    553 
    554     if (h_ps_d->procFrameBased == 1)    /* If we have switched from frame to slot based processing copy filter states */
    555     { /* procFrameBased will be unset later */
    556       /* copy filter states from left to right */
    557       FDKmemcpy(synQmfRight->FilterStates, synQmf->FilterStates, ((640)-(64))*sizeof(FIXP_QSS));
    558     }
    559 
    560     /* scale ALL qmf vales ( real and imag ) of mono / left channel to the
    561        same scale factor ( ov_lb_sf, lb_sf and hq_sf )                      */
    562     scalFilterBankValues( h_ps_d,                             /* parametric stereo decoder handle     */
    563                           QmfBufferReal,                      /* qmf filterbank values                */
    564                           QmfBufferImag,                      /* qmf filterbank values                */
    565                           synQmf->lsb,                        /* sbr start subband                    */
    566                           hSbrDec->sbrScaleFactor.ov_lb_scale,
    567                           hSbrDec->sbrScaleFactor.lb_scale,
    568                          &scaleFactorLowBand_ov,              /* adapt scaling values */
    569                          &scaleFactorLowBand_no_ov,           /* adapt scaling values */
    570                           hSbrDec->sbrScaleFactor.hb_scale,   /* current frame ( highband ) */
    571                          &scaleFactorHighBand,
    572                           synQmf->no_col);
    573 
    574     /* use the same synthese qmf values for left and right channel */
    575     synQmfRight->no_col = synQmf->no_col;
    576     synQmfRight->lsb    = synQmf->lsb;
    577     synQmfRight->usb    = synQmf->usb;
    578 
    579     int env=0;
    580 
    581       outScalefactor += (SCAL_HEADROOM+1); /* psDiffScale! */
    582 
    583     {
    584       C_ALLOC_SCRATCH_START(pWorkBuffer, FIXP_DBL, 2*(64));
    585 
    586       int maxShift = 0;
    587 
    588       if (hSbrDec->sbrDrcChannel.prevFact_exp > maxShift) {
    589         maxShift = hSbrDec->sbrDrcChannel.prevFact_exp;
    590       }
    591       if (hSbrDec->sbrDrcChannel.currFact_exp > maxShift) {
    592         maxShift = hSbrDec->sbrDrcChannel.currFact_exp;
    593       }
    594       if (hSbrDec->sbrDrcChannel.nextFact_exp > maxShift) {
    595         maxShift = hSbrDec->sbrDrcChannel.nextFact_exp;
    596       }
    597 
    598       /* copy DRC data to right channel (with PS both channels use the same DRC gains) */
    599       FDKmemcpy(&hSbrDecRight->sbrDrcChannel, &hSbrDec->sbrDrcChannel, sizeof(SBRDEC_DRC_CHANNEL));
    600 
    601       for (i = 0; i < synQmf->no_col; i++) {  /* ----- no_col loop ----- */
    602 
    603         INT outScalefactorR, outScalefactorL;
    604         outScalefactorR = outScalefactorL = outScalefactor;
    605 
    606         /* qmf timeslot of right channel */
    607         FIXP_DBL* rQmfReal = pWorkBuffer;
    608         FIXP_DBL* rQmfImag = pWorkBuffer + 64;
    609 
    610 
    611         {
    612           if ( i == h_ps_d->bsData[h_ps_d->processSlot].mpeg.aEnvStartStop[env] ) {
    613             initSlotBasedRotation( h_ps_d, env, hHeaderData->freqBandData.highSubband );
    614             env++;
    615           }
    616 
    617           ApplyPsSlot( h_ps_d,                   /* parametric stereo decoder handle  */
    618                       (QmfBufferReal + i),       /* one timeslot of left/mono channel */
    619                       (QmfBufferImag + i),       /* one timeslot of left/mono channel */
    620                        rQmfReal,                 /* one timeslot or right channel     */
    621                        rQmfImag);                /* one timeslot or right channel     */
    622         }
    623 
    624 
    625         scaleFactorLowBand = (i<(6)) ? scaleFactorLowBand_ov : scaleFactorLowBand_no_ov;
    626 
    627 
    628         sbrDecoder_drcApplySlot ( /* right channel */
    629                                  &hSbrDecRight->sbrDrcChannel,
    630                                   rQmfReal,
    631                                   rQmfImag,
    632                                   i,
    633                                   synQmfRight->no_col,
    634                                   maxShift
    635                                 );
    636 
    637         outScalefactorR += maxShift;
    638 
    639         sbrDecoder_drcApplySlot ( /* left channel */
    640                                  &hSbrDec->sbrDrcChannel,
    641                                  *(QmfBufferReal + i),
    642                                  *(QmfBufferImag + i),
    643                                   i,
    644                                   synQmf->no_col,
    645                                   maxShift
    646                                 );
    647 
    648         outScalefactorL += maxShift;
    649 
    650 
    651         /* scale filter states for left and right channel */
    652         qmfChangeOutScalefactor( synQmf, outScalefactorL );
    653         qmfChangeOutScalefactor( synQmfRight, outScalefactorR );
    654 
    655         {
    656 
    657           qmfSynthesisFilteringSlot( synQmfRight,
    658                                      rQmfReal,                /* QMF real buffer */
    659                                      rQmfImag,                /* QMF imag buffer */
    660                                      scaleFactorLowBand,
    661                                      scaleFactorHighBand,
    662                                      timeOutRight+(i*synQmf->no_channels*strideOut),
    663                                      strideOut,
    664                                      pWorkBuffer);
    665 
    666           qmfSynthesisFilteringSlot( synQmf,
    667                                    *(QmfBufferReal + i),      /* QMF real buffer */
    668                                    *(QmfBufferImag + i),      /* QMF imag buffer */
    669                                      scaleFactorLowBand,
    670                                      scaleFactorHighBand,
    671                                      timeOut+(i*synQmf->no_channels*strideOut),
    672                                      strideOut,
    673                                      pWorkBuffer);
    674 
    675         }
    676       } /* no_col loop  i  */
    677 
    678       /* scale back (6) timeslots look ahead for hybrid filterbank to original value */
    679       rescalFilterBankValues( h_ps_d,
    680                               QmfBufferReal,
    681                               QmfBufferImag,
    682                               synQmf->lsb,
    683                               synQmf->no_col );
    684 
    685       C_ALLOC_SCRATCH_END(pWorkBuffer, FIXP_DBL, 2*(64));
    686     }
    687   }
    688 
    689   sbrDecoder_drcUpdateChannel( &hSbrDec->sbrDrcChannel );
    690 
    691 
    692   /*
    693     Update overlap buffer
    694     Even bands above usb are copied to avoid outdated spectral data in case
    695     the stop frequency raises.
    696   */
    697 
    698   if (hSbrDec->LppTrans.pSettings->overlap > 0)
    699   {
    700     if (! (flags & SBRDEC_LOW_POWER)) {
    701       for ( i=0; i<hSbrDec->LppTrans.pSettings->overlap; i++ ) {
    702         FDKmemcpy(QmfBufferReal[i], QmfBufferReal[i+noCols], (64)*sizeof(FIXP_DBL));
    703         FDKmemcpy(QmfBufferImag[i], QmfBufferImag[i+noCols], (64)*sizeof(FIXP_DBL));
    704       }
    705     } else
    706       for ( i=0; i<hSbrDec->LppTrans.pSettings->overlap; i++ ) {
    707         FDKmemcpy(QmfBufferReal[i], QmfBufferReal[i+noCols], (64)*sizeof(FIXP_DBL));
    708       }
    709   }
    710 
    711   hSbrDec->sbrScaleFactor.ov_lb_scale = saveLbScale;
    712 
    713   /* Save current frame status */
    714   hPrevFrameData->frameErrorFlag = hHeaderData->frameErrorFlag;
    715 
    716 } // sbr_dec()
    717 
    718 
    719 /*!
    720   \brief     Creates sbr decoder structure
    721   \return    errorCode, 0 if successful
    722 */
    723 SBR_ERROR
    724 createSbrDec (SBR_CHANNEL * hSbrChannel,
    725               HANDLE_SBR_HEADER_DATA hHeaderData, /*!< Static control data */
    726               TRANSPOSER_SETTINGS *pSettings,
    727               const int     downsampleFac,        /*!< Downsampling factor */
    728               const UINT    qmfFlags,             /*!< flags -> 1: HQ/LP selector, 2: CLDFB */
    729               const UINT    flags,
    730               const int     overlap,
    731               int           chan)                 /*!< Channel for which to assign buffers etc. */
    732 
    733 {
    734   SBR_ERROR err = SBRDEC_OK;
    735   int timeSlots = hHeaderData->numberTimeSlots;   /* Number of SBR slots per frame */
    736   int noCols = timeSlots * hHeaderData->timeStep; /* Number of QMF slots per frame */
    737   HANDLE_SBR_DEC hs = &(hSbrChannel->SbrDec);
    738 
    739   /* Initialize scale factors */
    740   hs->sbrScaleFactor.ov_lb_scale  = 0;
    741   hs->sbrScaleFactor.ov_hb_scale  = 0;
    742   hs->sbrScaleFactor.hb_scale     = 0;
    743 
    744 
    745   /*
    746     create envelope calculator
    747   */
    748   err = createSbrEnvelopeCalc (&hs->SbrCalculateEnvelope,
    749                                hHeaderData,
    750                                chan,
    751                                flags);
    752   if (err != SBRDEC_OK) {
    753     return err;
    754   }
    755 
    756   /*
    757     create QMF filter banks
    758   */
    759   {
    760     int qmfErr;
    761 
    762     qmfErr = qmfInitAnalysisFilterBank (
    763                     &hs->AnalysiscQMF,
    764                      hs->anaQmfStates,
    765                      noCols,
    766                      hHeaderData->freqBandData.lowSubband,
    767                      hHeaderData->freqBandData.highSubband,
    768                      hHeaderData->numberOfAnalysisBands,
    769                      qmfFlags & (~QMF_FLAG_KEEP_STATES)
    770                      );
    771     if (qmfErr != 0) {
    772       return SBRDEC_UNSUPPORTED_CONFIG;
    773     }
    774   }
    775   if (hs->pSynQmfStates == NULL) {
    776     hs->pSynQmfStates = GetRam_sbr_QmfStatesSynthesis(chan);
    777     if (hs->pSynQmfStates == NULL)
    778       return SBRDEC_MEM_ALLOC_FAILED;
    779   }
    780 
    781   {
    782     int qmfErr;
    783 
    784     qmfErr = qmfInitSynthesisFilterBank (
    785            &hs->SynthesisQMF,
    786             hs->pSynQmfStates,
    787             noCols,
    788             hHeaderData->freqBandData.lowSubband,
    789             hHeaderData->freqBandData.highSubband,
    790             (64) / downsampleFac,
    791             qmfFlags & (~QMF_FLAG_KEEP_STATES)
    792             );
    793 
    794     if (qmfErr != 0) {
    795       return SBRDEC_UNSUPPORTED_CONFIG;
    796     }
    797   }
    798   initSbrPrevFrameData (&hSbrChannel->prevFrameData, timeSlots);
    799 
    800   /*
    801     create transposer
    802   */
    803   err = createLppTransposer (&hs->LppTrans,
    804                              pSettings,
    805                              hHeaderData->freqBandData.lowSubband,
    806                              hHeaderData->freqBandData.v_k_master,
    807                              hHeaderData->freqBandData.numMaster,
    808                              hs->SynthesisQMF.usb,
    809                              timeSlots,
    810                              hs->AnalysiscQMF.no_col,
    811                              hHeaderData->freqBandData.freqBandTableNoise,
    812                              hHeaderData->freqBandData.nNfb,
    813                              hHeaderData->sbrProcSmplRate,
    814                              chan,
    815                              overlap );
    816   if (err != SBRDEC_OK) {
    817     return err;
    818   }
    819 
    820   /* The CLDFB does not have overlap */
    821   if ((qmfFlags & QMF_FLAG_CLDFB) == 0) {
    822     if (hs->pSbrOverlapBuffer == NULL) {
    823       hs->pSbrOverlapBuffer = GetRam_sbr_OverlapBuffer(chan);
    824       if (hs->pSbrOverlapBuffer == NULL)  {
    825         return SBRDEC_MEM_ALLOC_FAILED;
    826       }
    827     } else {
    828       /* Clear overlap buffer */
    829       FDKmemclear( hs->pSbrOverlapBuffer,
    830                    sizeof(FIXP_DBL) * 2 * (6) * (64)
    831                  );
    832     }
    833   }
    834 
    835   /* assign qmf time slots */
    836   assignTimeSlots( &hSbrChannel->SbrDec, hHeaderData->numberTimeSlots * hHeaderData->timeStep, qmfFlags & QMF_FLAG_LP);
    837 
    838   return err;
    839 }
    840 
    841 /*!
    842   \brief     Delete sbr decoder structure
    843   \return    errorCode, 0 if successful
    844 */
    845 int
    846 deleteSbrDec (SBR_CHANNEL * hSbrChannel)
    847 {
    848   HANDLE_SBR_DEC hs = &hSbrChannel->SbrDec;
    849 
    850   deleteSbrEnvelopeCalc (&hs->SbrCalculateEnvelope);
    851 
    852   /* delete QMF filter states */
    853   if (hs->pSynQmfStates != NULL) {
    854     FreeRam_sbr_QmfStatesSynthesis(&hs->pSynQmfStates);
    855   }
    856 
    857 
    858   if (hs->pSbrOverlapBuffer != NULL) {
    859     FreeRam_sbr_OverlapBuffer(&hs->pSbrOverlapBuffer);
    860   }
    861 
    862   return 0;
    863 }
    864 
    865 
    866 /*!
    867   \brief     resets sbr decoder structure
    868   \return    errorCode, 0 if successful
    869 */
    870 SBR_ERROR
    871 resetSbrDec (HANDLE_SBR_DEC hSbrDec,
    872              HANDLE_SBR_HEADER_DATA hHeaderData,
    873              HANDLE_SBR_PREV_FRAME_DATA hPrevFrameData,
    874              const int useLP,
    875              const int downsampleFac
    876              )
    877 {
    878   SBR_ERROR sbrError = SBRDEC_OK;
    879 
    880   int old_lsb = hSbrDec->SynthesisQMF.lsb;
    881   int new_lsb = hHeaderData->freqBandData.lowSubband;
    882   int l, startBand, stopBand, startSlot, size;
    883 
    884   int source_scale, target_scale, delta_scale, target_lsb, target_usb, reserve;
    885   FIXP_DBL maxVal;
    886 
    887   /* overlapBuffer point to first (6) slots */
    888   FIXP_DBL  **OverlapBufferReal = hSbrDec->QmfBufferReal;
    889   FIXP_DBL  **OverlapBufferImag = hSbrDec->QmfBufferImag;
    890 
    891   /* assign qmf time slots */
    892   assignTimeSlots( hSbrDec, hHeaderData->numberTimeSlots * hHeaderData->timeStep, useLP);
    893 
    894 
    895 
    896   resetSbrEnvelopeCalc (&hSbrDec->SbrCalculateEnvelope);
    897 
    898   hSbrDec->SynthesisQMF.lsb = hHeaderData->freqBandData.lowSubband;
    899   hSbrDec->SynthesisQMF.usb = fixMin((INT)hSbrDec->SynthesisQMF.no_channels, (INT)hHeaderData->freqBandData.highSubband);
    900 
    901   hSbrDec->AnalysiscQMF.lsb = hSbrDec->SynthesisQMF.lsb;
    902   hSbrDec->AnalysiscQMF.usb = hSbrDec->SynthesisQMF.usb;
    903 
    904 
    905   /*
    906     The following initialization of spectral data in the overlap buffer
    907     is required for dynamic x-over or a change of the start-freq for 2 reasons:
    908 
    909     1. If the lowband gets _wider_, unadjusted data would remain
    910 
    911     2. If the lowband becomes _smaller_, the highest bands of the old lowband
    912        must be cleared because the whitening would be affected
    913   */
    914   startBand = old_lsb;
    915   stopBand  = new_lsb;
    916   startSlot = hHeaderData->timeStep * (hPrevFrameData->stopPos - hHeaderData->numberTimeSlots);
    917   size      = fixMax(0,stopBand-startBand);
    918 
    919   /* keep already adjusted data in the x-over-area */
    920   if (!useLP) {
    921     for (l=startSlot; l<hSbrDec->LppTrans.pSettings->overlap; l++) {
    922       FDKmemclear(&OverlapBufferReal[l][startBand], size*sizeof(FIXP_DBL));
    923       FDKmemclear(&OverlapBufferImag[l][startBand], size*sizeof(FIXP_DBL));
    924     }
    925   } else
    926   for (l=startSlot; l<hSbrDec->LppTrans.pSettings->overlap ; l++) {
    927     FDKmemclear(&OverlapBufferReal[l][startBand], size*sizeof(FIXP_DBL));
    928   }
    929 
    930 
    931   /*
    932     reset LPC filter states
    933   */
    934   startBand = fixMin(old_lsb,new_lsb);
    935   stopBand  = fixMax(old_lsb,new_lsb);
    936   size      = fixMax(0,stopBand-startBand);
    937 
    938   FDKmemclear(&hSbrDec->LppTrans.lpcFilterStatesReal[0][startBand], size*sizeof(FIXP_DBL));
    939   FDKmemclear(&hSbrDec->LppTrans.lpcFilterStatesReal[1][startBand], size*sizeof(FIXP_DBL));
    940   if (!useLP) {
    941     FDKmemclear(&hSbrDec->LppTrans.lpcFilterStatesImag[0][startBand], size*sizeof(FIXP_DBL));
    942     FDKmemclear(&hSbrDec->LppTrans.lpcFilterStatesImag[1][startBand], size*sizeof(FIXP_DBL));
    943   }
    944 
    945 
    946   /*
    947     Rescale already processed spectral data between old and new x-over frequency.
    948     This must be done because of the separate scalefactors for lowband and highband.
    949   */
    950   startBand = fixMin(old_lsb,new_lsb);
    951   stopBand =  fixMax(old_lsb,new_lsb);
    952 
    953   if (new_lsb > old_lsb) {
    954     /* The x-over-area was part of the highband before and will now belong to the lowband */
    955     source_scale = hSbrDec->sbrScaleFactor.ov_hb_scale;
    956     target_scale = hSbrDec->sbrScaleFactor.ov_lb_scale;
    957     target_lsb   = 0;
    958     target_usb   = old_lsb;
    959   }
    960   else {
    961     /* The x-over-area was part of the lowband before and will now belong to the highband */
    962     source_scale = hSbrDec->sbrScaleFactor.ov_lb_scale;
    963     target_scale = hSbrDec->sbrScaleFactor.ov_hb_scale;
    964     /* jdr: The values old_lsb and old_usb might be wrong because the previous frame might have been "upsamling". */
    965     target_lsb   = hSbrDec->SynthesisQMF.lsb;
    966     target_usb   = hSbrDec->SynthesisQMF.usb;
    967   }
    968 
    969   /* Shift left all samples of the x-over-area as much as possible
    970      An unnecessary coarse scale could cause ov_lb_scale or ov_hb_scale to be
    971      adapted and the accuracy in the next frame would seriously suffer! */
    972 
    973   maxVal = maxSubbandSample( OverlapBufferReal,
    974                              (useLP) ? NULL : OverlapBufferImag,
    975                              startBand,
    976                              stopBand,
    977                              0,
    978                              startSlot);
    979 
    980   reserve = CntLeadingZeros(maxVal)-1;
    981   reserve = fixMin(reserve,DFRACT_BITS-1-source_scale);
    982 
    983   rescaleSubbandSamples( OverlapBufferReal,
    984                          (useLP) ? NULL : OverlapBufferImag,
    985                          startBand,
    986                          stopBand,
    987                          0,
    988                          startSlot,
    989                          reserve);
    990   source_scale += reserve;
    991 
    992   delta_scale = target_scale - source_scale;
    993 
    994   if (delta_scale > 0) { /* x-over-area is dominant */
    995     delta_scale = -delta_scale;
    996     startBand = target_lsb;
    997     stopBand = target_usb;
    998 
    999     if (new_lsb > old_lsb) {
   1000       /* The lowband has to be rescaled */
   1001       hSbrDec->sbrScaleFactor.ov_lb_scale = source_scale;
   1002     }
   1003     else {
   1004       /* The highband has be be rescaled */
   1005       hSbrDec->sbrScaleFactor.ov_hb_scale = source_scale;
   1006     }
   1007   }
   1008 
   1009   FDK_ASSERT(startBand <= stopBand);
   1010 
   1011   if (!useLP) {
   1012     for (l=0; l<startSlot; l++) {
   1013       scaleValues( OverlapBufferReal[l] + startBand, stopBand-startBand, delta_scale );
   1014       scaleValues( OverlapBufferImag[l] + startBand, stopBand-startBand, delta_scale );
   1015     }
   1016   } else
   1017   for (l=0; l<startSlot; l++) {
   1018     scaleValues( OverlapBufferReal[l] + startBand, stopBand-startBand, delta_scale );
   1019   }
   1020 
   1021 
   1022   /*
   1023     Initialize transposer and limiter
   1024   */
   1025   sbrError = resetLppTransposer (&hSbrDec->LppTrans,
   1026                                  hHeaderData->freqBandData.lowSubband,
   1027                                  hHeaderData->freqBandData.v_k_master,
   1028                                  hHeaderData->freqBandData.numMaster,
   1029                                  hHeaderData->freqBandData.freqBandTableNoise,
   1030                                  hHeaderData->freqBandData.nNfb,
   1031                                  hHeaderData->freqBandData.highSubband,
   1032                                  hHeaderData->sbrProcSmplRate);
   1033   if (sbrError != SBRDEC_OK)
   1034     return sbrError;
   1035 
   1036   sbrError = ResetLimiterBands ( hHeaderData->freqBandData.limiterBandTable,
   1037                                  &hHeaderData->freqBandData.noLimiterBands,
   1038                                  hHeaderData->freqBandData.freqBandTable[0],
   1039                                  hHeaderData->freqBandData.nSfb[0],
   1040                                  hSbrDec->LppTrans.pSettings->patchParam,
   1041                                  hSbrDec->LppTrans.pSettings->noOfPatches,
   1042                                  hHeaderData->bs_data.limiterBands);
   1043 
   1044 
   1045   return sbrError;
   1046 }
   1047