Home | History | Annotate | Download | only in src
      1 /* -----------------------------------------------------------------------------
      2 Software License for The Fraunhofer FDK AAC Codec Library for Android
      3 
      4  Copyright  1995 - 2018 Fraunhofer-Gesellschaft zur Frderung der angewandten
      5 Forschung e.V. All rights reserved.
      6 
      7  1.    INTRODUCTION
      8 The Fraunhofer FDK AAC Codec Library for Android ("FDK AAC Codec") is software
      9 that implements the MPEG Advanced Audio Coding ("AAC") encoding and decoding
     10 scheme for digital audio. This FDK AAC Codec software is intended to be used on
     11 a wide variety of Android devices.
     12 
     13 AAC's HE-AAC and HE-AAC v2 versions are regarded as today's most efficient
     14 general perceptual audio codecs. AAC-ELD is considered the best-performing
     15 full-bandwidth communications codec by independent studies and is widely
     16 deployed. AAC has been standardized by ISO and IEC as part of the MPEG
     17 specifications.
     18 
     19 Patent licenses for necessary patent claims for the FDK AAC Codec (including
     20 those of Fraunhofer) may be obtained through Via Licensing
     21 (www.vialicensing.com) or through the respective patent owners individually for
     22 the purpose of encoding or decoding bit streams in products that are compliant
     23 with the ISO/IEC MPEG audio standards. Please note that most manufacturers of
     24 Android devices already license these patent claims through Via Licensing or
     25 directly from the patent owners, and therefore FDK AAC Codec software may
     26 already be covered under those patent licenses when it is used for those
     27 licensed purposes only.
     28 
     29 Commercially-licensed AAC software libraries, including floating-point versions
     30 with enhanced sound quality, are also available from Fraunhofer. Users are
     31 encouraged to check the Fraunhofer website for additional applications
     32 information and documentation.
     33 
     34 2.    COPYRIGHT LICENSE
     35 
     36 Redistribution and use in source and binary forms, with or without modification,
     37 are permitted without payment of copyright license fees provided that you
     38 satisfy the following conditions:
     39 
     40 You must retain the complete text of this software license in redistributions of
     41 the FDK AAC Codec or your modifications thereto in source code form.
     42 
     43 You must retain the complete text of this software license in the documentation
     44 and/or other materials provided with redistributions of the FDK AAC Codec or
     45 your modifications thereto in binary form. You must make available free of
     46 charge copies of the complete source code of the FDK AAC Codec and your
     47 modifications thereto to recipients of copies in binary form.
     48 
     49 The name of Fraunhofer may not be used to endorse or promote products derived
     50 from this library without prior written permission.
     51 
     52 You may not charge copyright license fees for anyone to use, copy or distribute
     53 the FDK AAC Codec software or your modifications thereto.
     54 
     55 Your modified versions of the FDK AAC Codec must carry prominent notices stating
     56 that you changed the software and the date of any change. For modified versions
     57 of the FDK AAC Codec, the term "Fraunhofer FDK AAC Codec Library for Android"
     58 must be replaced by the term "Third-Party Modified Version of the Fraunhofer FDK
     59 AAC Codec Library for Android."
     60 
     61 3.    NO PATENT LICENSE
     62 
     63 NO EXPRESS OR IMPLIED LICENSES TO ANY PATENT CLAIMS, including without
     64 limitation the patents of Fraunhofer, ARE GRANTED BY THIS SOFTWARE LICENSE.
     65 Fraunhofer provides no warranty of patent non-infringement with respect to this
     66 software.
     67 
     68 You may use this FDK AAC Codec software or modifications thereto only for
     69 purposes that are authorized by appropriate patent licenses.
     70 
     71 4.    DISCLAIMER
     72 
     73 This FDK AAC Codec software is provided by Fraunhofer on behalf of the copyright
     74 holders and contributors "AS IS" and WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES,
     75 including but not limited to the implied warranties of merchantability and
     76 fitness for a particular purpose. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
     77 CONTRIBUTORS BE LIABLE for any direct, indirect, incidental, special, exemplary,
     78 or consequential damages, including but not limited to procurement of substitute
     79 goods or services; loss of use, data, or profits, or business interruption,
     80 however caused and on any theory of liability, whether in contract, strict
     81 liability, or tort (including negligence), arising in any way out of the use of
     82 this software, even if advised of the possibility of such damage.
     83 
     84 5.    CONTACT INFORMATION
     85 
     86 Fraunhofer Institute for Integrated Circuits IIS
     87 Attention: Audio and Multimedia Departments - FDK AAC LL
     88 Am Wolfsmantel 33
     89 91058 Erlangen, Germany
     90 
     91 www.iis.fraunhofer.de/amm
     92 amm-info (at) iis.fraunhofer.de
     93 ----------------------------------------------------------------------------- */
     94 
     95 /*********************** MPEG surround decoder library *************************
     96 
     97    Author(s):
     98 
     99    Description: SAC Dec bitstream decoder
    100 
    101 *******************************************************************************/
    102 
    103 #include "sac_bitdec.h"
    104 
    105 #include "sac_dec_errorcodes.h"
    106 #include "nlc_dec.h"
    107 #include "sac_rom.h"
    108 #include "FDK_matrixCalloc.h"
    109 #include "sac_tsd.h"
    110 
    111 enum {
    112   ottVsTotInactiv = 0,
    113   ottVsTotDb1Activ = 1,
    114   ottVsTotDb2Activ = 2,
    115   ottVsTotDb1Db2Activ = 3
    116 };
    117 
    118 static SACDEC_ERROR SpatialDecDecodeHelperInfo(
    119     SPATIAL_SPECIFIC_CONFIG *pSpatialSpecificConfig, UPMIXTYPE upmixType) {
    120   int i;
    121   UINT syntaxFlags;
    122 
    123   /* Determine bit stream syntax */
    124   syntaxFlags = 0;
    125   switch (pSpatialSpecificConfig->coreCodec) {
    126     case AOT_ER_AAC_ELD:
    127     case AOT_ER_AAC_LD:
    128       syntaxFlags |= SACDEC_SYNTAX_LD;
    129       break;
    130     case AOT_USAC:
    131       syntaxFlags |= SACDEC_SYNTAX_USAC;
    132       break;
    133     case AOT_NONE:
    134     default:
    135       return MPS_UNSUPPORTED_FORMAT;
    136   }
    137 
    138   pSpatialSpecificConfig->syntaxFlags = syntaxFlags;
    139 
    140   switch (pSpatialSpecificConfig->treeConfig) {
    141     case TREE_212: {
    142       pSpatialSpecificConfig->ottCLDdefault[0] = 0;
    143     } break;
    144     default:
    145       return MPS_INVALID_TREECONFIG;
    146   }
    147 
    148   if (syntaxFlags & SACDEC_SYNTAX_USAC) {
    149     if (pSpatialSpecificConfig->bsOttBandsPhasePresent) {
    150       pSpatialSpecificConfig->numOttBandsIPD =
    151           pSpatialSpecificConfig->bsOttBandsPhase;
    152     } else {
    153       int numParameterBands;
    154 
    155       numParameterBands = pSpatialSpecificConfig->freqRes;
    156       switch (numParameterBands) {
    157         case 4:
    158         case 5:
    159           pSpatialSpecificConfig->numOttBandsIPD = 2;
    160           break;
    161         case 7:
    162           pSpatialSpecificConfig->numOttBandsIPD = 3;
    163           break;
    164         case 10:
    165           pSpatialSpecificConfig->numOttBandsIPD = 5;
    166           break;
    167         case 14:
    168           pSpatialSpecificConfig->numOttBandsIPD = 7;
    169           break;
    170         case 20:
    171         case 28:
    172           pSpatialSpecificConfig->numOttBandsIPD = 10;
    173           break;
    174         default:
    175           return MPS_INVALID_PARAMETERBANDS;
    176       }
    177     }
    178   } else {
    179     pSpatialSpecificConfig->numOttBandsIPD = 0;
    180   }
    181   for (i = 0; i < pSpatialSpecificConfig->nOttBoxes; i++) {
    182     {
    183       pSpatialSpecificConfig->bitstreamOttBands[i] =
    184           pSpatialSpecificConfig->freqRes;
    185     }
    186     {
    187       pSpatialSpecificConfig->numOttBands[i] =
    188           pSpatialSpecificConfig->bitstreamOttBands[i];
    189       if (syntaxFlags & SACDEC_SYNTAX_USAC &&
    190           !pSpatialSpecificConfig->bsOttBandsPhasePresent) {
    191         if (pSpatialSpecificConfig->bResidualCoding &&
    192             pSpatialSpecificConfig->ResidualConfig[i].bResidualPresent &&
    193             (pSpatialSpecificConfig->numOttBandsIPD <
    194              pSpatialSpecificConfig->ResidualConfig[i].nResidualBands)) {
    195           pSpatialSpecificConfig->numOttBandsIPD =
    196               pSpatialSpecificConfig->ResidualConfig[i].nResidualBands;
    197         }
    198       }
    199     }
    200   } /* i */
    201 
    202   return MPS_OK;
    203 }
    204 
    205 /*******************************************************************************
    206  Functionname: SpatialDecParseExtensionConfig
    207  *******************************************************************************
    208 
    209  Description:
    210 
    211  Arguments:
    212 
    213  Return:
    214 
    215 *******************************************************************************/
    216 
    217 static SACDEC_ERROR SpatialDecParseExtensionConfig(
    218     HANDLE_FDK_BITSTREAM bitstream, SPATIAL_SPECIFIC_CONFIG *config,
    219     int numOttBoxes, int numTttBoxes, int numOutChan, int bitsAvailable) {
    220   SACDEC_ERROR err = MPS_OK;
    221   INT ba = bitsAvailable;
    222 
    223   config->sacExtCnt = 0;
    224   config->bResidualCoding = 0;
    225 
    226   ba = fMin((int)FDKgetValidBits(bitstream), ba);
    227 
    228   while ((ba >= 8) && (config->sacExtCnt < MAX_NUM_EXT_TYPES)) {
    229     int bitsRead, nFillBits;
    230     INT tmp;
    231     UINT sacExtLen;
    232 
    233     config->sacExtType[config->sacExtCnt] = FDKreadBits(bitstream, 4);
    234     ba -= 4;
    235 
    236     sacExtLen = FDKreadBits(bitstream, 4);
    237     ba -= 4;
    238 
    239     if (sacExtLen == 15) {
    240       sacExtLen += FDKreadBits(bitstream, 8);
    241       ba -= 8;
    242       if (sacExtLen == 15 + 255) {
    243         sacExtLen += FDKreadBits(bitstream, 16);
    244         ba -= 16;
    245       }
    246     }
    247 
    248     tmp = (INT)FDKgetValidBits(
    249         bitstream); /* Extension config payload start anchor. */
    250     if ((tmp <= 0) || (tmp < (INT)sacExtLen * 8) || (ba < (INT)sacExtLen * 8)) {
    251       err = MPS_PARSE_ERROR;
    252       goto bail;
    253     }
    254 
    255     switch (config->sacExtType[config->sacExtCnt]) {
    256       default:; /* unknown extension data => do nothing */
    257     }
    258 
    259     /* skip remaining extension data */
    260     bitsRead = tmp - FDKgetValidBits(bitstream);
    261     nFillBits = 8 * sacExtLen - bitsRead;
    262 
    263     if (nFillBits < 0) {
    264       err = MPS_PARSE_ERROR;
    265       goto bail;
    266     } else {
    267       /* Skip fill bits or an unkown extension. */
    268       FDKpushFor(bitstream, nFillBits);
    269     }
    270 
    271     ba -= 8 * sacExtLen;
    272     config->sacExtCnt++;
    273   }
    274 
    275 bail:
    276   return err;
    277 }
    278 
    279 SACDEC_ERROR SpatialDecParseSpecificConfigHeader(
    280     HANDLE_FDK_BITSTREAM bitstream,
    281     SPATIAL_SPECIFIC_CONFIG *pSpatialSpecificConfig,
    282     AUDIO_OBJECT_TYPE coreCodec, SPATIAL_DEC_UPMIX_TYPE upmixType) {
    283   SACDEC_ERROR err = MPS_OK;
    284   INT numFillBits;
    285   int sacHeaderLen = 0;
    286   int sacTimeAlignFlag = 0;
    287 
    288   sacTimeAlignFlag = FDKreadBits(bitstream, 1);
    289   sacHeaderLen = FDKreadBits(bitstream, 7);
    290 
    291   if (sacHeaderLen == 127) {
    292     sacHeaderLen += FDKreadBits(bitstream, 16);
    293   }
    294   numFillBits = FDKgetValidBits(bitstream);
    295 
    296   err = SpatialDecParseSpecificConfig(bitstream, pSpatialSpecificConfig,
    297                                       sacHeaderLen, coreCodec);
    298 
    299   numFillBits -=
    300       FDKgetValidBits(bitstream); /* the number of read bits (tmpBits) */
    301   numFillBits = (8 * sacHeaderLen) - numFillBits;
    302   if (numFillBits < 0) {
    303     /* Parsing went wrong */
    304     err = MPS_PARSE_ERROR;
    305   }
    306   /* Move to the very end of the SSC */
    307   FDKpushBiDirectional(bitstream, numFillBits);
    308 
    309   if ((err == MPS_OK) && sacTimeAlignFlag) {
    310     /* not supported */
    311     FDKreadBits(bitstream, 16);
    312     err = MPS_UNSUPPORTED_CONFIG;
    313   }
    314 
    315   /* Derive additional helper variables */
    316   SpatialDecDecodeHelperInfo(pSpatialSpecificConfig, (UPMIXTYPE)upmixType);
    317 
    318   return err;
    319 }
    320 
    321 SACDEC_ERROR SpatialDecParseMps212Config(
    322     HANDLE_FDK_BITSTREAM bitstream,
    323     SPATIAL_SPECIFIC_CONFIG *pSpatialSpecificConfig, int samplingRate,
    324     AUDIO_OBJECT_TYPE coreCodec, INT stereoConfigIndex,
    325     INT coreSbrFrameLengthIndex) {
    326   int i;
    327 
    328   pSpatialSpecificConfig->stereoConfigIndex = stereoConfigIndex;
    329   pSpatialSpecificConfig->coreSbrFrameLengthIndex = coreSbrFrameLengthIndex;
    330   pSpatialSpecificConfig->freqRes =
    331       (SPATIALDEC_FREQ_RES)freqResTable[FDKreadBits(bitstream, 3)];
    332   if (pSpatialSpecificConfig->freqRes == 0) {
    333     return MPS_PARSE_ERROR; /* reserved value */
    334   }
    335 
    336   switch (coreCodec) {
    337     case AOT_DRM_USAC:
    338       pSpatialSpecificConfig->bsFixedGainDMX =
    339           (SPATIALDEC_FIXED_GAINS)FDKreadBits(bitstream, 3);
    340       /* tempShapeConfig = (bsTempShapeConfigDrm == 1) ? 3 : 0 */
    341       pSpatialSpecificConfig->tempShapeConfig =
    342           (SPATIALDEC_TS_CONF)(FDKreadBits(bitstream, 1) * 3);
    343       pSpatialSpecificConfig->decorrConfig = (SPATIALDEC_DECORR_CONF)0;
    344       pSpatialSpecificConfig->bsDecorrType = 0;
    345       break;
    346     case AOT_USAC:
    347       pSpatialSpecificConfig->bsFixedGainDMX =
    348           (SPATIALDEC_FIXED_GAINS)FDKreadBits(bitstream, 3);
    349       pSpatialSpecificConfig->tempShapeConfig =
    350           (SPATIALDEC_TS_CONF)FDKreadBits(bitstream, 2);
    351       pSpatialSpecificConfig->decorrConfig =
    352           (SPATIALDEC_DECORR_CONF)FDKreadBits(bitstream, 2);
    353       if (pSpatialSpecificConfig->decorrConfig > 2) {
    354         return MPS_PARSE_ERROR; /* reserved value */
    355       }
    356       pSpatialSpecificConfig->bsDecorrType = 0;
    357       break;
    358     default:
    359       return MPS_UNSUPPORTED_FORMAT;
    360   }
    361   pSpatialSpecificConfig->nTimeSlots = (coreSbrFrameLengthIndex == 4) ? 64 : 32;
    362   pSpatialSpecificConfig->bsHighRateMode = (UCHAR)FDKreadBits(bitstream, 1);
    363 
    364   {
    365     pSpatialSpecificConfig->bsPhaseCoding = (UCHAR)FDKreadBits(bitstream, 1);
    366     pSpatialSpecificConfig->bsOttBandsPhasePresent =
    367         (UCHAR)FDKreadBits(bitstream, 1);
    368     if (pSpatialSpecificConfig->bsOttBandsPhasePresent) {
    369       if (MAX_PARAMETER_BANDS < (pSpatialSpecificConfig->bsOttBandsPhase =
    370                                      FDKreadBits(bitstream, 5))) {
    371         return MPS_PARSE_ERROR;
    372       }
    373     } else {
    374       pSpatialSpecificConfig->bsOttBandsPhase = 0;
    375     }
    376   }
    377 
    378   if (stereoConfigIndex > 1) { /* do residual coding */
    379     pSpatialSpecificConfig->bResidualCoding = 1;
    380     pSpatialSpecificConfig->ResidualConfig->bResidualPresent = 1;
    381     if (pSpatialSpecificConfig->freqRes <
    382         (pSpatialSpecificConfig->ResidualConfig->nResidualBands =
    383              FDKreadBits(bitstream, 5))) {
    384       return MPS_PARSE_ERROR;
    385     }
    386     pSpatialSpecificConfig->bsOttBandsPhase =
    387         fMax(pSpatialSpecificConfig->bsOttBandsPhase,
    388              pSpatialSpecificConfig->ResidualConfig->nResidualBands);
    389     pSpatialSpecificConfig->bsPseudoLr = (UCHAR)FDKreadBits(bitstream, 1);
    390 
    391     if (pSpatialSpecificConfig->bsPhaseCoding) {
    392       pSpatialSpecificConfig->bsPhaseCoding = 3;
    393     }
    394   } else {
    395     pSpatialSpecificConfig->bResidualCoding = 0;
    396     pSpatialSpecificConfig->ResidualConfig->bResidualPresent = 0;
    397   }
    398 
    399   if (pSpatialSpecificConfig->tempShapeConfig == 2) {
    400     switch (coreCodec) {
    401       case AOT_USAC:
    402         pSpatialSpecificConfig->envQuantMode = FDKreadBits(bitstream, 1);
    403         break;
    404       default: /* added to avoid compiler warning */
    405         break; /* added to avoid compiler warning */
    406     }
    407   }
    408 
    409   /* Static parameters */
    410 
    411   pSpatialSpecificConfig->samplingFreq =
    412       samplingRate; /* wrong for stereoConfigIndex == 3 but value is unused */
    413   pSpatialSpecificConfig->treeConfig = SPATIALDEC_MODE_RSVD7;
    414   pSpatialSpecificConfig->nOttBoxes =
    415       treePropertyTable[pSpatialSpecificConfig->treeConfig].numOttBoxes;
    416   pSpatialSpecificConfig->nInputChannels =
    417       treePropertyTable[pSpatialSpecificConfig->treeConfig].numInputChannels;
    418   pSpatialSpecificConfig->nOutputChannels =
    419       treePropertyTable[pSpatialSpecificConfig->treeConfig].numOutputChannels;
    420 
    421   pSpatialSpecificConfig->bArbitraryDownmix = 0;
    422 
    423   for (i = 0; i < pSpatialSpecificConfig->nOttBoxes; i++) {
    424     pSpatialSpecificConfig->OttConfig[i].nOttBands = 0;
    425   }
    426 
    427   if (coreCodec == AOT_DRM_USAC) {
    428     /* MPS payload is MPEG conform -> no need for pseudo DRM AOT */
    429     coreCodec = AOT_USAC;
    430   }
    431   pSpatialSpecificConfig->coreCodec = coreCodec;
    432 
    433   /* Derive additional helper variables */
    434   SpatialDecDecodeHelperInfo(pSpatialSpecificConfig, UPMIXTYPE_NORMAL);
    435 
    436   return MPS_OK;
    437 }
    438 
    439 SACDEC_ERROR SpatialDecParseSpecificConfig(
    440     HANDLE_FDK_BITSTREAM bitstream,
    441     SPATIAL_SPECIFIC_CONFIG *pSpatialSpecificConfig, int sacHeaderLen,
    442     AUDIO_OBJECT_TYPE coreCodec) {
    443   SACDEC_ERROR err = MPS_OK;
    444   int i;
    445   int bsSamplingFreqIndex;
    446   int bsFreqRes, b3DaudioMode = 0;
    447   int numHeaderBits;
    448   int cfgStartPos, bitsAvailable;
    449 
    450   cfgStartPos = FDKgetValidBits(bitstream);
    451   /* It might be that we do not know the SSC length beforehand. */
    452   if (sacHeaderLen == 0) {
    453     bitsAvailable = cfgStartPos;
    454   } else {
    455     bitsAvailable = 8 * sacHeaderLen;
    456     if (bitsAvailable > cfgStartPos) {
    457       err = MPS_PARSE_ERROR;
    458       goto bail;
    459     }
    460   }
    461 
    462   bsSamplingFreqIndex = FDKreadBits(bitstream, 4);
    463 
    464   if (bsSamplingFreqIndex == 15) {
    465     pSpatialSpecificConfig->samplingFreq = FDKreadBits(bitstream, 24);
    466   } else {
    467     pSpatialSpecificConfig->samplingFreq =
    468         samplingFreqTable[bsSamplingFreqIndex];
    469     if (pSpatialSpecificConfig->samplingFreq == 0) {
    470       err = MPS_PARSE_ERROR;
    471       goto bail;
    472     }
    473   }
    474 
    475   pSpatialSpecificConfig->nTimeSlots = FDKreadBits(bitstream, 5) + 1;
    476   if ((pSpatialSpecificConfig->nTimeSlots < 1) ||
    477       (pSpatialSpecificConfig->nTimeSlots > MAX_TIME_SLOTS)) {
    478     err = MPS_PARSE_ERROR;
    479     goto bail;
    480   }
    481 
    482   bsFreqRes = FDKreadBits(bitstream, 3);
    483 
    484   pSpatialSpecificConfig->freqRes =
    485       (SPATIALDEC_FREQ_RES)freqResTable_LD[bsFreqRes];
    486 
    487   pSpatialSpecificConfig->treeConfig =
    488       (SPATIALDEC_TREE_CONFIG)FDKreadBits(bitstream, 4);
    489 
    490   if (pSpatialSpecificConfig->treeConfig != SPATIALDEC_MODE_RSVD7) {
    491     err = MPS_UNSUPPORTED_CONFIG;
    492     goto bail;
    493   }
    494 
    495   {
    496     pSpatialSpecificConfig->nOttBoxes =
    497         treePropertyTable[pSpatialSpecificConfig->treeConfig].numOttBoxes;
    498     pSpatialSpecificConfig->nTttBoxes =
    499         treePropertyTable[pSpatialSpecificConfig->treeConfig].numTttBoxes;
    500     pSpatialSpecificConfig->nInputChannels =
    501         treePropertyTable[pSpatialSpecificConfig->treeConfig].numInputChannels;
    502     pSpatialSpecificConfig->nOutputChannels =
    503         treePropertyTable[pSpatialSpecificConfig->treeConfig].numOutputChannels;
    504   }
    505 
    506   pSpatialSpecificConfig->quantMode =
    507       (SPATIALDEC_QUANT_MODE)FDKreadBits(bitstream, 2);
    508 
    509   pSpatialSpecificConfig->bArbitraryDownmix = FDKreadBits(bitstream, 1);
    510 
    511   pSpatialSpecificConfig->bsFixedGainDMX =
    512       (SPATIALDEC_FIXED_GAINS)FDKreadBits(bitstream, 3);
    513 
    514   pSpatialSpecificConfig->tempShapeConfig =
    515       (SPATIALDEC_TS_CONF)FDKreadBits(bitstream, 2);
    516   pSpatialSpecificConfig->decorrConfig =
    517       (SPATIALDEC_DECORR_CONF)FDKreadBits(bitstream, 2);
    518   if (pSpatialSpecificConfig->decorrConfig > 2) {
    519     return MPS_PARSE_ERROR; /* reserved value */
    520   }
    521 
    522   for (i = 0; i < pSpatialSpecificConfig->nOttBoxes; i++) {
    523     pSpatialSpecificConfig->OttConfig[i].nOttBands = 0;
    524   }
    525 
    526   for (i = 0; i < pSpatialSpecificConfig->nTttBoxes; i++) {
    527     int bTttDualMode = FDKreadBits(bitstream, 1);
    528     FDKreadBits(bitstream, 3); /* not supported */
    529 
    530     if (bTttDualMode) {
    531       FDKreadBits(bitstream, 8); /* not supported */
    532     }
    533   }
    534 
    535   if (pSpatialSpecificConfig->tempShapeConfig == 2) {
    536     pSpatialSpecificConfig->envQuantMode = FDKreadBits(bitstream, 1);
    537   }
    538 
    539   if (b3DaudioMode) {
    540     if (FDKreadBits(bitstream, 2) == 0) { /* b3DaudioHRTFset ? */
    541       int hc;
    542       int HRTFnumBand;
    543       int HRTFfreqRes = FDKreadBits(bitstream, 3);
    544       int HRTFnumChan = FDKreadBits(bitstream, 4);
    545       int HRTFasymmetric = FDKreadBits(bitstream, 1);
    546 
    547       HRTFnumBand = freqResTable_LD[HRTFfreqRes];
    548 
    549       for (hc = 0; hc < HRTFnumChan; hc++) {
    550         FDKpushFor(bitstream, HRTFnumBand * 6); /* HRTFlevelLeft[hc][hb] */
    551         if (HRTFasymmetric) {
    552           FDKpushFor(bitstream, HRTFnumBand * 6); /* HRTFlevelRight[hc][hb] */
    553         }
    554         if (FDKreadBits(bitstream, 1)) {          /* HRTFphase[hc] ? */
    555           FDKpushFor(bitstream, HRTFnumBand * 6); /* HRTFphaseLR[hc][hb] */
    556         }
    557         if (FDKreadBits(bitstream, 1)) {          /* HRTFicc[hc] ? */
    558           FDKpushFor(bitstream, HRTFnumBand * 6); /* HRTFiccLR[hc][hb] */
    559         }
    560       }
    561     }
    562   }
    563 
    564   FDKbyteAlign(bitstream,
    565                cfgStartPos); /* ISO/IEC FDIS 23003-1: 5.2. ... byte alignment
    566                                 with respect to the beginning of the syntactic
    567                                 element in which ByteAlign() occurs. */
    568 
    569   numHeaderBits = cfgStartPos - (INT)FDKgetValidBits(bitstream);
    570   bitsAvailable -= numHeaderBits;
    571 
    572   pSpatialSpecificConfig->sacExtCnt = 0;
    573   pSpatialSpecificConfig->bResidualCoding = 0;
    574 
    575   if ((err == MPS_OK) && (bitsAvailable > 0)) {
    576     err = SpatialDecParseExtensionConfig(
    577         bitstream, pSpatialSpecificConfig, pSpatialSpecificConfig->nOttBoxes,
    578         pSpatialSpecificConfig->nTttBoxes,
    579         pSpatialSpecificConfig->nOutputChannels, bitsAvailable);
    580   }
    581 
    582   FDKbyteAlign(
    583       bitstream,
    584       cfgStartPos); /* Same alignment anchor as above because
    585                        SpatialExtensionConfig() always reads full bytes */
    586 
    587   pSpatialSpecificConfig->coreCodec = coreCodec;
    588 
    589   SpatialDecDecodeHelperInfo(pSpatialSpecificConfig, UPMIXTYPE_NORMAL);
    590 
    591 bail:
    592   if (sacHeaderLen > 0) {
    593     /* If the config is of known length then assure that the
    594        bitbuffer is exactly at its end when leaving the function. */
    595     FDKpushBiDirectional(
    596         bitstream,
    597         (sacHeaderLen * 8) - (cfgStartPos - (INT)FDKgetValidBits(bitstream)));
    598   }
    599 
    600   return err;
    601 }
    602 
    603 int SpatialDecDefaultSpecificConfig(
    604     SPATIAL_SPECIFIC_CONFIG *pSpatialSpecificConfig,
    605     AUDIO_OBJECT_TYPE coreCodec, int samplingFreq, int nTimeSlots,
    606     int sacDecoderLevel, int isBlind, int numCoreChannels)
    607 
    608 {
    609   int err = MPS_OK;
    610   int i;
    611 
    612   FDK_ASSERT(coreCodec != AOT_NONE);
    613   FDK_ASSERT(nTimeSlots > 0);
    614   FDK_ASSERT(samplingFreq > 0);
    615 
    616   pSpatialSpecificConfig->coreCodec = coreCodec;
    617   pSpatialSpecificConfig->samplingFreq = samplingFreq;
    618   pSpatialSpecificConfig->nTimeSlots = nTimeSlots;
    619   if ((pSpatialSpecificConfig->coreCodec == AOT_ER_AAC_ELD) ||
    620       (pSpatialSpecificConfig->coreCodec == AOT_ER_AAC_LD))
    621     pSpatialSpecificConfig->freqRes = SPATIALDEC_FREQ_RES_23;
    622   else
    623     pSpatialSpecificConfig->freqRes = SPATIALDEC_FREQ_RES_28;
    624 
    625   {
    626     pSpatialSpecificConfig->treeConfig =
    627         SPATIALDEC_MODE_RSVD7; /* 212  configuration */
    628   }
    629 
    630   {
    631     pSpatialSpecificConfig->nOttBoxes =
    632         treePropertyTable[pSpatialSpecificConfig->treeConfig].numOttBoxes;
    633     pSpatialSpecificConfig->nInputChannels =
    634         treePropertyTable[pSpatialSpecificConfig->treeConfig].numInputChannels;
    635     pSpatialSpecificConfig->nOutputChannels =
    636         treePropertyTable[pSpatialSpecificConfig->treeConfig].numOutputChannels;
    637   }
    638 
    639   pSpatialSpecificConfig->quantMode = SPATIALDEC_QUANT_FINE_DEF;
    640   pSpatialSpecificConfig->bArbitraryDownmix = 0;
    641   pSpatialSpecificConfig->bResidualCoding = 0;
    642   if ((pSpatialSpecificConfig->coreCodec == AOT_ER_AAC_ELD) ||
    643       (pSpatialSpecificConfig->coreCodec == AOT_ER_AAC_LD))
    644     pSpatialSpecificConfig->bsFixedGainDMX = SPATIALDEC_GAIN_RSVD2;
    645   else
    646     pSpatialSpecificConfig->bsFixedGainDMX = SPATIALDEC_GAIN_MODE0;
    647 
    648   pSpatialSpecificConfig->tempShapeConfig = SPATIALDEC_TS_TPNOWHITE;
    649   pSpatialSpecificConfig->decorrConfig = SPATIALDEC_DECORR_MODE0;
    650 
    651   for (i = 0; i < pSpatialSpecificConfig->nOttBoxes; i++) {
    652     pSpatialSpecificConfig->OttConfig[i].nOttBands = 0;
    653   }
    654 
    655   return err;
    656 }
    657 
    658 /*******************************************************************************
    659  Functionname: coarse2fine
    660  *******************************************************************************
    661 
    662  Description:
    663    Parameter index mapping from coarse to fine quantization
    664 
    665  Arguments:
    666 
    667 Input:
    668 
    669 Output:
    670 
    671 *******************************************************************************/
    672 static void coarse2fine(SCHAR *data, DATA_TYPE dataType, int startBand,
    673                         int numBands) {
    674   int i;
    675 
    676   for (i = startBand; i < startBand + numBands; i++) {
    677     data[i] <<= 1;
    678   }
    679 
    680   if (dataType == t_CLD) {
    681     for (i = startBand; i < startBand + numBands; i++) {
    682       if (data[i] == -14)
    683         data[i] = -15;
    684       else if (data[i] == 14)
    685         data[i] = 15;
    686     }
    687   }
    688 }
    689 
    690 /*******************************************************************************
    691  Functionname: fine2coarse
    692  *******************************************************************************
    693 
    694  Description:
    695    Parameter index mapping from fine to coarse quantization
    696 
    697  Arguments:
    698 
    699 Input:
    700 
    701 Output:
    702 
    703 *******************************************************************************/
    704 static void fine2coarse(SCHAR *data, DATA_TYPE dataType, int startBand,
    705                         int numBands) {
    706   int i;
    707 
    708   for (i = startBand; i < startBand + numBands; i++) {
    709     /* Note: the if cases below actually make a difference (negative values) */
    710     if (dataType == t_CLD)
    711       data[i] /= 2;
    712     else
    713       data[i] >>= 1;
    714   }
    715 }
    716 
    717 /*******************************************************************************
    718  Functionname: getStrideMap
    719  *******************************************************************************
    720 
    721  Description:
    722    Index Mapping accroding to pbStrides
    723 
    724  Arguments:
    725 
    726 Input:
    727 
    728 Output:
    729 
    730 *******************************************************************************/
    731 static int getStrideMap(int freqResStride, int startBand, int stopBand,
    732                         int *aStrides) {
    733   int i, pb, pbStride, dataBands, strOffset;
    734 
    735   pbStride = pbStrideTable[freqResStride];
    736   dataBands = (stopBand - startBand - 1) / pbStride + 1;
    737 
    738   aStrides[0] = startBand;
    739   for (pb = 1; pb <= dataBands; pb++) {
    740     aStrides[pb] = aStrides[pb - 1] + pbStride;
    741   }
    742   strOffset = 0;
    743   while (aStrides[dataBands] > stopBand) {
    744     if (strOffset < dataBands) strOffset++;
    745     for (i = strOffset; i <= dataBands; i++) {
    746       aStrides[i]--;
    747     }
    748   }
    749 
    750   return dataBands;
    751 }
    752 
    753 /*******************************************************************************
    754  Functionname: ecDataDec
    755  *******************************************************************************
    756 
    757  Description:
    758    Do delta decoding and dequantization
    759 
    760  Arguments:
    761 
    762 Input:
    763 
    764 Output:
    765 
    766 
    767 *******************************************************************************/
    768 
    769 static SACDEC_ERROR ecDataDec(
    770     const SPATIAL_BS_FRAME *frame, UINT syntaxFlags,
    771     HANDLE_FDK_BITSTREAM bitstream, LOSSLESSDATA *const llData,
    772     SCHAR (*data)[MAX_PARAMETER_SETS][MAX_PARAMETER_BANDS], SCHAR **lastdata,
    773     int datatype, int boxIdx, int startBand, int stopBand, SCHAR defaultValue) {
    774   SACDEC_ERROR err = MPS_OK;
    775   int i, j, pb, dataSets, setIdx, bsDataPair, dataBands, oldQuantCoarseXXX;
    776   INT aStrides[MAX_PARAMETER_BANDS + 1] = {0};
    777 
    778   dataSets = 0;
    779   for (i = 0; i < frame->numParameterSets; i++) {
    780     llData->bsXXXDataMode[i] = (SCHAR)FDKreadBits(bitstream, 2);
    781 
    782     if ((frame->bsIndependencyFlag == 1) && (i == 0) &&
    783         (llData->bsXXXDataMode[i] == 1 ||
    784          llData->bsXXXDataMode[i] == 2)) { /* This check catches bitstreams
    785                                               generated by older encoder that
    786                                               cause trouble */
    787       return MPS_PARSE_ERROR;
    788     }
    789     if ((i >= frame->numParameterSets - 1) &&
    790         (llData->bsXXXDataMode[i] ==
    791          2)) { /* The interpolation mode must not be active for the last
    792                   parameter set */
    793       return MPS_PARSE_ERROR;
    794     }
    795 
    796     if (llData->bsXXXDataMode[i] == 3) {
    797       dataSets++;
    798     }
    799   }
    800 
    801   setIdx = 0;
    802   bsDataPair = 0;
    803   oldQuantCoarseXXX = llData->state->bsQuantCoarseXXXprevParse;
    804 
    805   for (i = 0; i < frame->numParameterSets; i++) {
    806     if (llData->bsXXXDataMode[i] == 0) {
    807       for (pb = startBand; pb < stopBand; pb++) {
    808         lastdata[boxIdx][pb] = defaultValue;
    809       }
    810 
    811       oldQuantCoarseXXX = 0;
    812     }
    813 
    814     if (llData->bsXXXDataMode[i] == 3) {
    815       if (bsDataPair) {
    816         bsDataPair = 0;
    817       } else {
    818         bsDataPair = FDKreadBits(bitstream, 1);
    819         llData->bsQuantCoarseXXX[setIdx] = (UCHAR)FDKreadBits(bitstream, 1);
    820         llData->bsFreqResStrideXXX[setIdx] = (UCHAR)FDKreadBits(bitstream, 2);
    821 
    822         if (llData->bsQuantCoarseXXX[setIdx] != oldQuantCoarseXXX) {
    823           if (oldQuantCoarseXXX) {
    824             coarse2fine(lastdata[boxIdx], (DATA_TYPE)datatype, startBand,
    825                         stopBand - startBand);
    826           } else {
    827             fine2coarse(lastdata[boxIdx], (DATA_TYPE)datatype, startBand,
    828                         stopBand - startBand);
    829           }
    830         }
    831 
    832         dataBands = getStrideMap(llData->bsFreqResStrideXXX[setIdx], startBand,
    833                                  stopBand, aStrides);
    834 
    835         for (pb = 0; pb < dataBands; pb++) {
    836           lastdata[boxIdx][startBand + pb] = lastdata[boxIdx][aStrides[pb]];
    837         }
    838 
    839         if (boxIdx > MAX_NUM_OTT) return MPS_INVALID_BOXIDX;
    840         if ((setIdx + bsDataPair) > MAX_PARAMETER_SETS)
    841           return MPS_INVALID_SETIDX;
    842 
    843         /* DECODER_TYPE defined in FDK_tools */
    844         DECODER_TYPE this_decoder_type = SAC_DECODER;
    845         if (syntaxFlags & (SACDEC_SYNTAX_USAC | SACDEC_SYNTAX_RSVD50)) {
    846           this_decoder_type = USAC_DECODER;
    847         } else if (syntaxFlags & SACDEC_SYNTAX_LD) {
    848           this_decoder_type = SAOC_DECODER;
    849         }
    850 
    851         err = (SACDEC_ERROR)EcDataPairDec(
    852             this_decoder_type, bitstream, data[boxIdx][setIdx + 0],
    853             data[boxIdx][setIdx + 1], lastdata[boxIdx], (DATA_TYPE)datatype,
    854             startBand, dataBands, bsDataPair, llData->bsQuantCoarseXXX[setIdx],
    855             !(frame->bsIndependencyFlag && (i == 0)) || (setIdx > 0));
    856         if (err != MPS_OK) goto bail;
    857 
    858         if (datatype == t_IPD) {
    859           const SCHAR mask = (llData->bsQuantCoarseXXX[setIdx]) ? 7 : 15;
    860           for (pb = 0; pb < dataBands; pb++) {
    861             for (j = aStrides[pb]; j < aStrides[pb + 1]; j++) {
    862               lastdata[boxIdx][j] =
    863                   data[boxIdx][setIdx + bsDataPair][startBand + pb] & mask;
    864             }
    865           }
    866         } else {
    867           for (pb = 0; pb < dataBands; pb++) {
    868             for (j = aStrides[pb]; j < aStrides[pb + 1]; j++) {
    869               lastdata[boxIdx][j] =
    870                   data[boxIdx][setIdx + bsDataPair][startBand + pb];
    871             }
    872           }
    873         }
    874 
    875         oldQuantCoarseXXX = llData->bsQuantCoarseXXX[setIdx];
    876 
    877         if (bsDataPair) {
    878           llData->bsQuantCoarseXXX[setIdx + 1] =
    879               llData->bsQuantCoarseXXX[setIdx];
    880           llData->bsFreqResStrideXXX[setIdx + 1] =
    881               llData->bsFreqResStrideXXX[setIdx];
    882         }
    883         setIdx += bsDataPair + 1;
    884       } /* !bsDataPair */
    885     }   /* llData->bsXXXDataMode[i] == 3 */
    886   }
    887 
    888   llData->state->bsQuantCoarseXXXprevParse = oldQuantCoarseXXX;
    889 
    890 bail:
    891   return err;
    892 }
    893 
    894 /*******************************************************************************
    895  Functionname: parseArbitraryDownmixData
    896  *******************************************************************************
    897 
    898  Description:
    899 
    900  Arguments:
    901 
    902  Return:
    903 
    904 *******************************************************************************/
    905 static SACDEC_ERROR parseArbitraryDownmixData(
    906     spatialDec *self, const SPATIAL_SPECIFIC_CONFIG *pSSC,
    907     const UINT syntaxFlags, const SPATIAL_BS_FRAME *frame,
    908     HANDLE_FDK_BITSTREAM bitstream) {
    909   SACDEC_ERROR err = MPS_OK;
    910   int ch;
    911   int offset = pSSC->nOttBoxes;
    912 
    913   /* CLD (arbitrary down-mix gains) */
    914   for (ch = 0; ch < pSSC->nInputChannels; ch++) {
    915     err = ecDataDec(frame, syntaxFlags, bitstream,
    916                     &frame->CLDLosslessData[offset + ch],
    917                     frame->cmpArbdmxGainIdx, self->cmpArbdmxGainIdxPrev, t_CLD,
    918                     ch, 0, pSSC->freqRes, arbdmxGainDefault);
    919     if (err != MPS_OK) return err;
    920   }
    921 
    922   return err;
    923 
    924 } /* parseArbitraryDownmixData */
    925 
    926 /*******************************************************************************
    927  Functionname: SpatialDecParseFrame
    928  *******************************************************************************
    929 
    930  Description:
    931 
    932  Arguments:
    933 
    934  Input:
    935 
    936  Output:
    937 
    938 *******************************************************************************/
    939 
    940 static int nBitsParamSlot(int i) {
    941   int bitsParamSlot;
    942 
    943   bitsParamSlot = fMax(0, DFRACT_BITS - 1 - fNormz((FIXP_DBL)i));
    944   if ((1 << bitsParamSlot) < i) {
    945     bitsParamSlot++;
    946   }
    947   FDK_ASSERT((bitsParamSlot >= 0) && (bitsParamSlot <= 32));
    948 
    949   return bitsParamSlot;
    950 }
    951 
    952 SACDEC_ERROR SpatialDecParseFrameData(
    953     spatialDec_struct *self, SPATIAL_BS_FRAME *frame,
    954     HANDLE_FDK_BITSTREAM bitstream,
    955     const SPATIAL_SPECIFIC_CONFIG *pSpatialSpecificConfig, UPMIXTYPE upmixType,
    956     int fGlobalIndependencyFlag) {
    957   SACDEC_ERROR err = MPS_OK;
    958   int bsFramingType, dataBands, ps, pg, i;
    959   int pb;
    960   int numTempShapeChan = 0;
    961   int bsNumOutputChannels =
    962       treePropertyTable[pSpatialSpecificConfig->treeConfig]
    963           .numOutputChannels; /* CAUTION: Maybe different to
    964                                  pSpatialSpecificConfig->treeConfig in some
    965                                  modes! */
    966   int paramSetErr = 0;
    967   UINT alignAnchor = FDKgetValidBits(
    968       bitstream); /* Anchor for ByteAlign() function. See comment below. */
    969   UINT syntaxFlags;
    970 
    971   syntaxFlags = pSpatialSpecificConfig->syntaxFlags;
    972 
    973   if ((syntaxFlags & (SACDEC_SYNTAX_USAC | SACDEC_SYNTAX_RSVD50)) &&
    974       pSpatialSpecificConfig->bsHighRateMode == 0) {
    975     bsFramingType = 0; /* fixed framing */
    976     frame->numParameterSets = 1;
    977   } else {
    978     bsFramingType = FDKreadBits(bitstream, 1);
    979     if (syntaxFlags & SACDEC_SYNTAX_LD)
    980       frame->numParameterSets = FDKreadBits(bitstream, 1) + 1;
    981     else
    982       frame->numParameterSets = FDKreadBits(bitstream, 3) + 1;
    983   }
    984 
    985   /* Any error after this line shall trigger parameter invalidation at bail
    986    * label. */
    987   paramSetErr = 1;
    988 
    989   if (frame->numParameterSets >= MAX_PARAMETER_SETS) {
    990     goto bail;
    991   }
    992 
    993   /* Basic config check. */
    994   if (pSpatialSpecificConfig->nInputChannels <= 0 ||
    995       pSpatialSpecificConfig->nOutputChannels <= 0) {
    996     err = MPS_UNSUPPORTED_CONFIG;
    997     goto bail;
    998   }
    999 
   1000   if (bsFramingType) {
   1001     int prevParamSlot = -1;
   1002     int bitsParamSlot;
   1003 
   1004     {
   1005       bitsParamSlot = nBitsParamSlot(pSpatialSpecificConfig->nTimeSlots);
   1006 
   1007       for (i = 0; i < frame->numParameterSets; i++) {
   1008         frame->paramSlot[i] = FDKreadBits(bitstream, bitsParamSlot);
   1009         /* Sanity check */
   1010         if ((frame->paramSlot[i] <= prevParamSlot) ||
   1011             (frame->paramSlot[i] >= pSpatialSpecificConfig->nTimeSlots)) {
   1012           err = MPS_PARSE_ERROR;
   1013           goto bail;
   1014         }
   1015         prevParamSlot = frame->paramSlot[i];
   1016       }
   1017     }
   1018   } else {
   1019     for (i = 0; i < frame->numParameterSets; i++) {
   1020       frame->paramSlot[i] = ((pSpatialSpecificConfig->nTimeSlots * (i + 1)) /
   1021                              frame->numParameterSets) -
   1022                             1;
   1023     }
   1024   }
   1025 
   1026   if ((syntaxFlags & (SACDEC_SYNTAX_USAC | SACDEC_SYNTAX_RSVD50)) &&
   1027       fGlobalIndependencyFlag) {
   1028     frame->bsIndependencyFlag = 1;
   1029   } else {
   1030     frame->bsIndependencyFlag = (UCHAR)FDKreadBits(bitstream, 1);
   1031   }
   1032 
   1033   /*
   1034    * OttData()
   1035    */
   1036   for (i = 0; i < pSpatialSpecificConfig->nOttBoxes; i++) {
   1037     err = ecDataDec(frame, syntaxFlags, bitstream, &frame->CLDLosslessData[i],
   1038                     frame->cmpOttCLDidx, self->cmpOttCLDidxPrev, t_CLD, i, 0,
   1039                     pSpatialSpecificConfig->bitstreamOttBands[i],
   1040                     pSpatialSpecificConfig->ottCLDdefault[i]);
   1041     if (err != MPS_OK) {
   1042       goto bail;
   1043     }
   1044   } /* i < numOttBoxes */
   1045 
   1046   {
   1047     for (i = 0; i < pSpatialSpecificConfig->nOttBoxes; i++) {
   1048       err = ecDataDec(frame, syntaxFlags, bitstream, &frame->ICCLosslessData[i],
   1049                       frame->cmpOttICCidx, self->cmpOttICCidxPrev, t_ICC, i, 0,
   1050                       pSpatialSpecificConfig->bitstreamOttBands[i], ICCdefault);
   1051       if (err != MPS_OK) {
   1052         goto bail;
   1053       }
   1054     } /* i < numOttBoxes */
   1055   }   /* !oneICC */
   1056 
   1057   if ((pSpatialSpecificConfig->treeConfig == SPATIALDEC_MODE_RSVD7) &&
   1058       (pSpatialSpecificConfig->bsPhaseCoding)) {
   1059     frame->phaseMode = FDKreadBits(bitstream, 1);
   1060 
   1061     if (frame->phaseMode == 0) {
   1062       for (pb = 0; pb < pSpatialSpecificConfig->numOttBandsIPD; pb++) {
   1063         self->cmpOttIPDidxPrev[0][pb] = 0;
   1064         for (i = 0; i < frame->numParameterSets; i++) {
   1065           frame->cmpOttIPDidx[0][i][pb] = 0;
   1066           // frame->ottIPDidx[0][i][pb] = 0;
   1067         }
   1068         /* self->ottIPDidxPrev[0][pb] = 0; */
   1069       }
   1070       frame->OpdSmoothingMode = 0;
   1071     } else {
   1072       frame->OpdSmoothingMode = FDKreadBits(bitstream, 1);
   1073       err = ecDataDec(frame, syntaxFlags, bitstream, &frame->IPDLosslessData[0],
   1074                       frame->cmpOttIPDidx, self->cmpOttIPDidxPrev, t_IPD, 0, 0,
   1075                       pSpatialSpecificConfig->numOttBandsIPD, IPDdefault);
   1076       if (err != MPS_OK) {
   1077         goto bail;
   1078       }
   1079     }
   1080   }
   1081 
   1082   /*
   1083    * SmgData()
   1084    */
   1085 
   1086   {
   1087     if (!pSpatialSpecificConfig->bsHighRateMode &&
   1088         (syntaxFlags & SACDEC_SYNTAX_USAC)) {
   1089       for (ps = 0; ps < frame->numParameterSets; ps++) {
   1090         frame->bsSmoothMode[ps] = 0;
   1091       }
   1092     } else {
   1093       for (ps = 0; ps < frame->numParameterSets; ps++) {
   1094         frame->bsSmoothMode[ps] = (UCHAR)FDKreadBits(bitstream, 2);
   1095         if (frame->bsSmoothMode[ps] >= 2) {
   1096           frame->bsSmoothTime[ps] = (UCHAR)FDKreadBits(bitstream, 2);
   1097         }
   1098         if (frame->bsSmoothMode[ps] == 3) {
   1099           frame->bsFreqResStrideSmg[ps] = (UCHAR)FDKreadBits(bitstream, 2);
   1100           dataBands = (pSpatialSpecificConfig->freqRes - 1) /
   1101                           pbStrideTable[frame->bsFreqResStrideSmg[ps]] +
   1102                       1;
   1103           for (pg = 0; pg < dataBands; pg++) {
   1104             frame->bsSmgData[ps][pg] = (UCHAR)FDKreadBits(bitstream, 1);
   1105           }
   1106         }
   1107       } /* ps < numParameterSets */
   1108     }
   1109   }
   1110 
   1111   /*
   1112    * TempShapeData()
   1113    */
   1114   if ((pSpatialSpecificConfig->tempShapeConfig == 3) &&
   1115       (syntaxFlags & SACDEC_SYNTAX_USAC)) {
   1116     int TsdErr;
   1117     TsdErr = TsdRead(bitstream, pSpatialSpecificConfig->nTimeSlots,
   1118                      &frame->TsdData[0]);
   1119     if (TsdErr) {
   1120       err = MPS_PARSE_ERROR;
   1121       goto bail;
   1122     }
   1123   } else {
   1124     frame->TsdData[0].bsTsdEnable = 0;
   1125   }
   1126 
   1127   for (i = 0; i < bsNumOutputChannels; i++) {
   1128     frame->tempShapeEnableChannelSTP[i] = 0;
   1129     frame->tempShapeEnableChannelGES[i] = 0;
   1130   }
   1131 
   1132   if ((pSpatialSpecificConfig->tempShapeConfig == 1) ||
   1133       (pSpatialSpecificConfig->tempShapeConfig == 2)) {
   1134     int bsTempShapeEnable = FDKreadBits(bitstream, 1);
   1135     if (bsTempShapeEnable) {
   1136       numTempShapeChan =
   1137           tempShapeChanTable[pSpatialSpecificConfig->tempShapeConfig - 1]
   1138                             [pSpatialSpecificConfig->treeConfig];
   1139       switch (pSpatialSpecificConfig->tempShapeConfig) {
   1140         case 1: /* STP */
   1141           for (i = 0; i < numTempShapeChan; i++) {
   1142             int stpEnable = FDKreadBits(bitstream, 1);
   1143             frame->tempShapeEnableChannelSTP[i] = stpEnable;
   1144           }
   1145           break;
   1146         case 2: /* GES */
   1147         {
   1148           UCHAR gesChannelEnable[MAX_OUTPUT_CHANNELS];
   1149 
   1150           for (i = 0; i < numTempShapeChan; i++) {
   1151             gesChannelEnable[i] = (UCHAR)FDKreadBits(bitstream, 1);
   1152             frame->tempShapeEnableChannelGES[i] = gesChannelEnable[i];
   1153           }
   1154           for (i = 0; i < numTempShapeChan; i++) {
   1155             if (gesChannelEnable[i]) {
   1156               int envShapeData_tmp[MAX_TIME_SLOTS];
   1157               if (huff_dec_reshape(bitstream, envShapeData_tmp,
   1158                                    pSpatialSpecificConfig->nTimeSlots) != 0) {
   1159                 err = MPS_PARSE_ERROR;
   1160                 goto bail;
   1161               }
   1162               for (int ts = 0; ts < pSpatialSpecificConfig->nTimeSlots; ts++) {
   1163                 if (!(envShapeData_tmp[ts] >= 0) &&
   1164                     (envShapeData_tmp[ts] <= 4)) {
   1165                   err = MPS_PARSE_ERROR;
   1166                   goto bail;
   1167                 }
   1168                 frame->bsEnvShapeData[i][ts] = (UCHAR)envShapeData_tmp[ts];
   1169               }
   1170             }
   1171           }
   1172         } break;
   1173         default:
   1174           err = MPS_INVALID_TEMPSHAPE;
   1175           goto bail;
   1176       }
   1177     } /* bsTempShapeEnable */
   1178   }   /* pSpatialSpecificConfig->tempShapeConfig != 0 */
   1179 
   1180   if (pSpatialSpecificConfig->bArbitraryDownmix != 0) {
   1181     err = parseArbitraryDownmixData(self, pSpatialSpecificConfig, syntaxFlags,
   1182                                     frame, bitstream);
   1183     if (err != MPS_OK) goto bail;
   1184   }
   1185 
   1186   if (1 && (!(syntaxFlags & (SACDEC_SYNTAX_USAC)))) {
   1187     FDKbyteAlign(bitstream,
   1188                  alignAnchor); /* ISO/IEC FDIS 23003-1: 5.2. ... byte alignment
   1189                                   with respect to the beginning of the syntactic
   1190                                   element in which ByteAlign() occurs. */
   1191   }
   1192 
   1193 bail:
   1194   if (err != MPS_OK && paramSetErr != 0) {
   1195     /* Since the parameter set data has already been written to the instance we
   1196      * need to ... */
   1197     frame->numParameterSets = 0; /* ... signal that it is corrupt ... */
   1198   }
   1199 
   1200   return err;
   1201 
   1202 } /* SpatialDecParseFrame */
   1203 
   1204 /*******************************************************************************
   1205  Functionname: createMapping
   1206  *******************************************************************************
   1207 
   1208  Description:
   1209 
   1210  Arguments:
   1211 
   1212  Return:
   1213 
   1214 *******************************************************************************/
   1215 static void createMapping(int aMap[MAX_PARAMETER_BANDS + 1], int startBand,
   1216                           int stopBand, int stride) {
   1217   int inBands, outBands, bandsAchived, bandsDiff, incr, k, i;
   1218   int vDk[MAX_PARAMETER_BANDS + 1];
   1219   inBands = stopBand - startBand;
   1220   outBands = (inBands - 1) / stride + 1;
   1221 
   1222   if (outBands < 1) {
   1223     outBands = 1;
   1224   }
   1225 
   1226   bandsAchived = outBands * stride;
   1227   bandsDiff = inBands - bandsAchived;
   1228   for (i = 0; i < outBands; i++) {
   1229     vDk[i] = stride;
   1230   }
   1231 
   1232   if (bandsDiff > 0) {
   1233     incr = -1;
   1234     k = outBands - 1;
   1235   } else {
   1236     incr = 1;
   1237     k = 0;
   1238   }
   1239 
   1240   while (bandsDiff != 0) {
   1241     vDk[k] = vDk[k] - incr;
   1242     k = k + incr;
   1243     bandsDiff = bandsDiff + incr;
   1244     if (k >= outBands) {
   1245       if (bandsDiff > 0) {
   1246         k = outBands - 1;
   1247       } else if (bandsDiff < 0) {
   1248         k = 0;
   1249       }
   1250     }
   1251   }
   1252   aMap[0] = startBand;
   1253   for (i = 0; i < outBands; i++) {
   1254     aMap[i + 1] = aMap[i] + vDk[i];
   1255   }
   1256 } /* createMapping */
   1257 
   1258 /*******************************************************************************
   1259  Functionname: mapFrequency
   1260  *******************************************************************************
   1261 
   1262  Description:
   1263 
   1264  Arguments:
   1265 
   1266  Return:
   1267 
   1268 *******************************************************************************/
   1269 static void mapFrequency(const SCHAR *pInput, /* Input */
   1270                          SCHAR *pOutput,      /* Output */
   1271                          int *pMap,           /* Mapping function */
   1272                          int dataBands)       /* Number of data Bands */
   1273 {
   1274   int i, j;
   1275   int startBand0 = pMap[0];
   1276 
   1277   for (i = 0; i < dataBands; i++) {
   1278     int startBand, stopBand, value;
   1279 
   1280     value = pInput[i + startBand0];
   1281 
   1282     startBand = pMap[i];
   1283     stopBand = pMap[i + 1];
   1284     for (j = startBand; j < stopBand; j++) {
   1285       pOutput[j] = value;
   1286     }
   1287   }
   1288 }
   1289 
   1290 /*******************************************************************************
   1291  Functionname: deq
   1292  *******************************************************************************
   1293 
   1294  Description:
   1295 
   1296  Arguments:
   1297 
   1298  Return:
   1299 
   1300 *******************************************************************************/
   1301 static int deqIdx(int value, int paramType) {
   1302   int idx = -1;
   1303 
   1304   switch (paramType) {
   1305     case t_CLD:
   1306       if (((value + 15) >= 0) && ((value + 15) < 31)) {
   1307         idx = (value + 15);
   1308       }
   1309       break;
   1310 
   1311     case t_ICC:
   1312       if ((value >= 0) && (value < 8)) {
   1313         idx = value;
   1314       }
   1315       break;
   1316 
   1317     case t_IPD:
   1318       /* (+/-)15 * MAX_PARAMETER_BANDS for differential coding in frequency
   1319        * domain (according to rbl) */
   1320       if ((value >= -420) && (value <= 420)) {
   1321         idx = (value & 0xf);
   1322       }
   1323       break;
   1324 
   1325     default:
   1326       FDK_ASSERT(0);
   1327   }
   1328 
   1329   return idx;
   1330 }
   1331 
   1332   /*******************************************************************************
   1333    Functionname: factorFunct
   1334    *******************************************************************************
   1335 
   1336    Description:
   1337 
   1338    Arguments:
   1339 
   1340    Return:
   1341 
   1342   *******************************************************************************/
   1343 
   1344 #define SF_IDX (7)
   1345 #define SF_FACTOR (3)
   1346 #define SCALE_FACTOR (1 << SF_FACTOR)
   1347 #define SCALE_CLD_C1C2 (1 << SF_CLD_C1C2)
   1348 
   1349 static FIXP_DBL factorFunct(FIXP_DBL ottVsTotDb, INT quantMode) {
   1350   FIXP_DBL factor;
   1351 
   1352   if (ottVsTotDb > FL2FXCONST_DBL(0.0)) {
   1353     ottVsTotDb = FL2FXCONST_DBL(0.0);
   1354   }
   1355 
   1356   ottVsTotDb = -ottVsTotDb;
   1357 
   1358   switch (quantMode) {
   1359     case 0:
   1360       factor = FL2FXCONST_DBL(1.0f / SCALE_FACTOR);
   1361       break;
   1362     case 1:
   1363       if (ottVsTotDb >= FL2FXCONST_DBL(21.0f / SCALE_CLD_C1C2))
   1364         factor = FL2FXCONST_DBL(5.0f / SCALE_FACTOR);
   1365       else if (ottVsTotDb <= FL2FXCONST_DBL(1.0f / SCALE_CLD_C1C2))
   1366         factor = FL2FXCONST_DBL(1.0f / SCALE_FACTOR);
   1367       else
   1368         factor = (fMult(FL2FXCONST_DBL(0.2f), ottVsTotDb) +
   1369                   FL2FXCONST_DBL(0.8f / SCALE_CLD_C1C2))
   1370                  << (SF_CLD_C1C2 - SF_FACTOR);
   1371       break;
   1372     case 2:
   1373       if (ottVsTotDb >= FL2FXCONST_DBL(25.0f / SCALE_CLD_C1C2)) {
   1374         FDK_ASSERT(SF_FACTOR == 3);
   1375         factor = (FIXP_DBL)
   1376             MAXVAL_DBL; /* avoid warning: FL2FXCONST_DBL(8.0f/SCALE_FACTOR) */
   1377       } else if (ottVsTotDb <= FL2FXCONST_DBL(1.0f / SCALE_CLD_C1C2))
   1378         factor = FL2FXCONST_DBL(1.0f / SCALE_FACTOR);
   1379       else
   1380         factor = (fMult(FL2FXCONST_DBL(7.0f / 24.0f), ottVsTotDb) +
   1381                   FL2FXCONST_DBL((17.0f / 24.0f) / SCALE_CLD_C1C2))
   1382                  << (SF_CLD_C1C2 - SF_FACTOR);
   1383       break;
   1384     default:
   1385       factor = FL2FXCONST_DBL(0.0f);
   1386   }
   1387 
   1388   return (factor);
   1389 }
   1390 
   1391 /*******************************************************************************
   1392  Functionname: factorCLD
   1393  *******************************************************************************
   1394 
   1395  Description:
   1396 
   1397  Arguments:
   1398 
   1399  Return:
   1400 
   1401 *******************************************************************************/
   1402 static void factorCLD(SCHAR *idx, FIXP_DBL ottVsTotDb, FIXP_DBL *ottVsTotDb1,
   1403                       FIXP_DBL *ottVsTotDb2, SCHAR ottVsTotDbMode,
   1404                       INT quantMode) {
   1405   FIXP_DBL factor;
   1406   FIXP_DBL cldIdxFract;
   1407   INT cldIdx;
   1408 
   1409   factor = factorFunct(ottVsTotDb, quantMode);
   1410 
   1411   cldIdxFract =
   1412       fMult((FIXP_DBL)((*idx) << ((DFRACT_BITS - 1) - SF_IDX)), factor);
   1413   cldIdxFract += FL2FXCONST_DBL(15.5f / (1 << (SF_FACTOR + SF_IDX)));
   1414   cldIdx = fixp_truncateToInt(cldIdxFract, SF_FACTOR + SF_IDX);
   1415 
   1416   cldIdx = fMin(cldIdx, 30);
   1417   cldIdx = fMax(cldIdx, 0);
   1418 
   1419   *idx = cldIdx - 15;
   1420 
   1421   if (ottVsTotDbMode & ottVsTotDb1Activ)
   1422     (*ottVsTotDb1) = ottVsTotDb + dequantCLD_c1[cldIdx];
   1423 
   1424   if (ottVsTotDbMode & ottVsTotDb2Activ)
   1425     (*ottVsTotDb2) = ottVsTotDb + dequantCLD_c1[30 - cldIdx];
   1426 }
   1427 
   1428 /*******************************************************************************
   1429  Functionname: mapIndexData
   1430  *******************************************************************************
   1431 
   1432  Description:
   1433 
   1434  Arguments:
   1435 
   1436  Return:
   1437 
   1438 *******************************************************************************/
   1439 static SACDEC_ERROR mapIndexData(
   1440     LOSSLESSDATA *llData, SCHAR ***outputDataIdx, SCHAR ***outputIdxData,
   1441     const SCHAR (*cmpIdxData)[MAX_PARAMETER_SETS][MAX_PARAMETER_BANDS],
   1442     SCHAR ***diffIdxData, SCHAR xttIdx, SCHAR **idxPrev, int paramIdx,
   1443     int paramType, int startBand, int stopBand, SCHAR defaultValue,
   1444     int numParameterSets, const int *paramSlot, int extendFrame, int quantMode,
   1445     SpatialDecConcealmentInfo *concealmentInfo, SCHAR ottVsTotDbMode,
   1446     FIXP_DBL (*pOttVsTotDbIn)[MAX_PARAMETER_SETS][MAX_PARAMETER_BANDS],
   1447     FIXP_DBL (*pOttVsTotDb1)[MAX_PARAMETER_SETS][MAX_PARAMETER_BANDS],
   1448     FIXP_DBL (*pOttVsTotDb2)[MAX_PARAMETER_SETS][MAX_PARAMETER_BANDS]) {
   1449   int aParamSlots[MAX_PARAMETER_SETS];
   1450   int aInterpolate[MAX_PARAMETER_SETS];
   1451 
   1452   int dataSets;
   1453   int aMap[MAX_PARAMETER_BANDS + 1];
   1454 
   1455   int setIdx, i, band, parmSlot;
   1456   int dataBands;
   1457   int ps, pb;
   1458   int i1;
   1459 
   1460   if (numParameterSets > MAX_PARAMETER_SETS) return MPS_WRONG_PARAMETERSETS;
   1461 
   1462   dataSets = 0;
   1463   for (i = 0; i < numParameterSets; i++) {
   1464     if (llData->bsXXXDataMode[i] == 3) {
   1465       aParamSlots[dataSets] = i;
   1466       dataSets++;
   1467     }
   1468   }
   1469 
   1470   setIdx = 0;
   1471 
   1472   /* Main concealment stage is here: */
   1473   SpatialDecConcealment_Apply(
   1474       concealmentInfo, cmpIdxData[xttIdx],
   1475       (diffIdxData != NULL) ? diffIdxData[xttIdx] : NULL, idxPrev[xttIdx],
   1476       llData->bsXXXDataMode, startBand, stopBand, defaultValue, paramType,
   1477       numParameterSets);
   1478 
   1479   /* Prepare data */
   1480   for (i = 0; i < numParameterSets; i++) {
   1481     if (llData->bsXXXDataMode[i] == 0) {
   1482       llData->nocmpQuantCoarseXXX[i] = 0;
   1483       for (band = startBand; band < stopBand; band++) {
   1484         outputIdxData[xttIdx][i][band] = defaultValue;
   1485       }
   1486       for (band = startBand; band < stopBand; band++) {
   1487         idxPrev[xttIdx][band] = outputIdxData[xttIdx][i][band];
   1488       }
   1489       /* Because the idxPrev are also set to the defaultValue -> signalize fine
   1490        */
   1491       llData->state->bsQuantCoarseXXXprev = 0;
   1492     }
   1493 
   1494     if (llData->bsXXXDataMode[i] == 1) {
   1495       for (band = startBand; band < stopBand; band++) {
   1496         outputIdxData[xttIdx][i][band] = idxPrev[xttIdx][band];
   1497       }
   1498       llData->nocmpQuantCoarseXXX[i] = llData->state->bsQuantCoarseXXXprev;
   1499     }
   1500 
   1501     if (llData->bsXXXDataMode[i] == 2) {
   1502       for (band = startBand; band < stopBand; band++) {
   1503         outputIdxData[xttIdx][i][band] = idxPrev[xttIdx][band];
   1504       }
   1505       llData->nocmpQuantCoarseXXX[i] = llData->state->bsQuantCoarseXXXprev;
   1506       aInterpolate[i] = 1;
   1507     } else {
   1508       aInterpolate[i] = 0;
   1509     }
   1510 
   1511     if (llData->bsXXXDataMode[i] == 3) {
   1512       int stride;
   1513 
   1514       parmSlot = aParamSlots[setIdx];
   1515       stride = pbStrideTable[llData->bsFreqResStrideXXX[setIdx]];
   1516       dataBands = (stopBand - startBand - 1) / stride + 1;
   1517       createMapping(aMap, startBand, stopBand, stride);
   1518       mapFrequency(&cmpIdxData[xttIdx][setIdx][0],
   1519                    &outputIdxData[xttIdx][parmSlot][0], aMap, dataBands);
   1520       for (band = startBand; band < stopBand; band++) {
   1521         idxPrev[xttIdx][band] = outputIdxData[xttIdx][parmSlot][band];
   1522       }
   1523       llData->state->bsQuantCoarseXXXprev = llData->bsQuantCoarseXXX[setIdx];
   1524       llData->nocmpQuantCoarseXXX[i] = llData->bsQuantCoarseXXX[setIdx];
   1525 
   1526       setIdx++;
   1527     }
   1528     if (diffIdxData != NULL) {
   1529       for (band = startBand; band < stopBand; band++) {
   1530         outputIdxData[xttIdx][i][band] += diffIdxData[xttIdx][i][band];
   1531       }
   1532     }
   1533   } /* for( i = 0 ; i < numParameterSets; i++ ) */
   1534 
   1535   /* Map all coarse data to fine */
   1536   for (i = 0; i < numParameterSets; i++) {
   1537     if (llData->nocmpQuantCoarseXXX[i] == 1) {
   1538       coarse2fine(outputIdxData[xttIdx][i], (DATA_TYPE)paramType, startBand,
   1539                   stopBand - startBand);
   1540       llData->nocmpQuantCoarseXXX[i] = 0;
   1541     }
   1542   }
   1543 
   1544   /* Interpolate */
   1545   i1 = 0;
   1546   for (i = 0; i < numParameterSets; i++) {
   1547     int xi, i2, x1, x2;
   1548 
   1549     if (aInterpolate[i] != 1) {
   1550       i1 = i;
   1551     }
   1552     i2 = i;
   1553     while (aInterpolate[i2] == 1) {
   1554       i2++;
   1555     }
   1556     x1 = paramSlot[i1];
   1557     xi = paramSlot[i];
   1558     x2 = paramSlot[i2];
   1559 
   1560     if (aInterpolate[i] == 1) {
   1561       if (i2 >= numParameterSets) return MPS_WRONG_PARAMETERSETS;
   1562       for (band = startBand; band < stopBand; band++) {
   1563         int yi, y1, y2;
   1564         y1 = outputIdxData[xttIdx][i1][band];
   1565         y2 = outputIdxData[xttIdx][i2][band];
   1566         if (x1 != x2) {
   1567           yi = y1 + (xi - x1) * (y2 - y1) / (x2 - x1);
   1568         } else {
   1569           yi = y1 /*+ (xi-x1)*(y2-y1)/1e-12*/;
   1570         }
   1571         outputIdxData[xttIdx][i][band] = yi;
   1572       }
   1573     }
   1574   } /* for( i = 0 ; i < numParameterSets; i++ ) */
   1575 
   1576   /* Dequantize data and apply factorCLD if necessary */
   1577   for (ps = 0; ps < numParameterSets; ps++) {
   1578     if (quantMode && (paramType == t_CLD)) {
   1579       if (pOttVsTotDbIn == 0) return MPS_WRONG_OTT;
   1580       if ((pOttVsTotDb1 == 0) && (ottVsTotDbMode == ottVsTotDb1Activ))
   1581         return MPS_WRONG_OTT;
   1582       if ((pOttVsTotDb2 == 0) && (ottVsTotDbMode == ottVsTotDb2Activ))
   1583         return MPS_WRONG_OTT;
   1584 
   1585       for (pb = startBand; pb < stopBand; pb++) {
   1586         factorCLD(&(outputIdxData[xttIdx][ps][pb]), (*pOttVsTotDbIn)[ps][pb],
   1587                   (pOttVsTotDb1 != NULL) ? &((*pOttVsTotDb1)[ps][pb]) : NULL,
   1588                   (pOttVsTotDb2 != NULL) ? &((*pOttVsTotDb2)[ps][pb]) : NULL,
   1589                   ottVsTotDbMode, quantMode);
   1590       }
   1591     }
   1592 
   1593     /* Dequantize data */
   1594     for (band = startBand; band < stopBand; band++) {
   1595       outputDataIdx[xttIdx][ps][band] =
   1596           deqIdx(outputIdxData[xttIdx][ps][band], paramType);
   1597       if (outputDataIdx[xttIdx][ps][band] == -1) {
   1598         outputDataIdx[xttIdx][ps][band] = defaultValue;
   1599       }
   1600     }
   1601   } /* for( i = 0 ; i < numParameterSets; i++ ) */
   1602 
   1603   if (extendFrame) {
   1604     for (band = startBand; band < stopBand; band++) {
   1605       outputDataIdx[xttIdx][numParameterSets][band] =
   1606           outputDataIdx[xttIdx][numParameterSets - 1][band];
   1607     }
   1608   }
   1609 
   1610   return MPS_OK;
   1611 }
   1612 
   1613 /*******************************************************************************
   1614  Functionname: decodeAndMapFrameOtt
   1615  *******************************************************************************
   1616 
   1617  Description:
   1618    Do delta decoding and dequantization
   1619 
   1620  Arguments:
   1621 
   1622 Input:
   1623 
   1624 Output:
   1625 
   1626 *******************************************************************************/
   1627 static SACDEC_ERROR decodeAndMapFrameOtt(HANDLE_SPATIAL_DEC self,
   1628                                          SPATIAL_BS_FRAME *pCurBs) {
   1629   int i, ottIdx;
   1630   int numOttBoxes;
   1631 
   1632   SACDEC_ERROR err = MPS_OK;
   1633 
   1634   numOttBoxes = self->numOttBoxes;
   1635 
   1636   switch (self->treeConfig) {
   1637     default: {
   1638       if (self->quantMode != 0) {
   1639         goto bail;
   1640       }
   1641     }
   1642       for (i = 0; i < numOttBoxes; i++) {
   1643         err = mapIndexData(
   1644             &pCurBs->CLDLosslessData[i], /* LOSSLESSDATA *llData,*/
   1645             self->ottCLD__FDK, self->outIdxData,
   1646             pCurBs
   1647                 ->cmpOttCLDidx, /* int
   1648                                    cmpIdxData[MAX_NUM_OTT][MAX_PARAMETER_SETS][MAX_PARAMETER_BANDS],
   1649                                  */
   1650             NULL,               /* no differential data */
   1651             i, /*  int   xttIdx,  Which ott/ttt index to use for input and
   1652                   output buffers */
   1653             self->ottCLDidxPrev,                        /* int
   1654                                                            idxPrev[MAX_NUM_OTT][MAX_PARAMETER_BANDS],
   1655                                                          */
   1656             i, t_CLD, 0,                                /* int   startBand, */
   1657             self->pConfigCurrent->bitstreamOttBands[i], /*  int   stopBand, */
   1658             self->pConfigCurrent->ottCLDdefault[i], /* int   defaultValue, */
   1659             pCurBs->numParameterSets, /* int   numParameterSets) */
   1660             pCurBs->paramSlot, self->extendFrame, self->quantMode,
   1661             &(self->concealInfo), ottVsTotInactiv, NULL, NULL, NULL);
   1662         if (err != MPS_OK) goto bail;
   1663 
   1664       } /* for(i = 0; i < numOttBoxes ; i++ ) */
   1665       break;
   1666   } /* case */
   1667 
   1668   for (ottIdx = 0; ottIdx < numOttBoxes; ottIdx++) {
   1669     /* Read ICC */
   1670     err = mapIndexData(
   1671         &pCurBs->ICCLosslessData[ottIdx], /* LOSSLESSDATA *llData,*/
   1672         self->ottICC__FDK, self->outIdxData,
   1673         pCurBs
   1674             ->cmpOttICCidx,  /* int
   1675                                 cmpIdxData[MAX_NUM_OTT][MAX_PARAMETER_SETS][MAX_PARAMETER_BANDS],
   1676                               */
   1677         self->ottICCdiffidx, /* differential data */
   1678         ottIdx, /* int   xttIdx,  Which ott/ttt index to use for input and
   1679                    output buffers */
   1680         self->ottICCidxPrev, /* int   idxPrev[MAX_NUM_OTT][MAX_PARAMETER_BANDS],
   1681                               */
   1682         ottIdx, t_ICC, 0,    /* int   startBand, */
   1683         self->pConfigCurrent->bitstreamOttBands[ottIdx], /* int   stopBand, */
   1684         ICCdefault,               /* int   defaultValue, */
   1685         pCurBs->numParameterSets, /* int   numParameterSets) */
   1686         pCurBs->paramSlot, self->extendFrame, self->quantMode,
   1687         &(self->concealInfo), ottVsTotInactiv, NULL, NULL, NULL);
   1688     if (err != MPS_OK) goto bail;
   1689   } /* ottIdx */
   1690 
   1691   if ((self->treeConfig == TREE_212) && (self->phaseCoding)) {
   1692     if (pCurBs->phaseMode == 0) {
   1693       for (int pb = 0; pb < self->pConfigCurrent->numOttBandsIPD; pb++) {
   1694         self->ottIPDidxPrev[0][pb] = 0;
   1695       }
   1696     }
   1697     for (ottIdx = 0; ottIdx < numOttBoxes; ottIdx++) {
   1698       err = mapIndexData(
   1699           &pCurBs->IPDLosslessData[ottIdx], self->ottIPD__FDK, self->outIdxData,
   1700           pCurBs->cmpOttIPDidx, NULL, ottIdx, self->ottIPDidxPrev, ottIdx,
   1701           t_IPD, 0, self->numOttBandsIPD, IPDdefault, pCurBs->numParameterSets,
   1702           pCurBs->paramSlot, self->extendFrame, self->quantMode,
   1703           &(self->concealInfo), ottVsTotInactiv, NULL, NULL, NULL);
   1704     }
   1705   }
   1706 
   1707 bail:
   1708 
   1709   return MPS_OK;
   1710 
   1711 } /* decodeAndMapFrameOtt */
   1712 
   1713 /*******************************************************************************
   1714  Functionname: decodeAndMapFrameSmg
   1715  *******************************************************************************
   1716 
   1717  Description:
   1718    Decode smoothing flags
   1719 
   1720  Arguments:
   1721 
   1722 Input:
   1723 
   1724 Output:
   1725 
   1726 
   1727 *******************************************************************************/
   1728 static SACDEC_ERROR decodeAndMapFrameSmg(HANDLE_SPATIAL_DEC self,
   1729                                          const SPATIAL_BS_FRAME *frame) {
   1730   int ps, pb, pg, pbStride, dataBands, pbStart, pbStop,
   1731       aGroupToBand[MAX_PARAMETER_BANDS + 1];
   1732 
   1733   if (frame->numParameterSets > MAX_PARAMETER_SETS)
   1734     return MPS_WRONG_PARAMETERSETS;
   1735   if (self->bitstreamParameterBands > MAX_PARAMETER_BANDS)
   1736     return MPS_WRONG_PARAMETERBANDS;
   1737 
   1738   for (ps = 0; ps < frame->numParameterSets; ps++) {
   1739     switch (frame->bsSmoothMode[ps]) {
   1740       case 0:
   1741         self->smgTime[ps] = 256;
   1742         FDKmemclear(self->smgData[ps],
   1743                     self->bitstreamParameterBands * sizeof(UCHAR));
   1744         break;
   1745 
   1746       case 1:
   1747         if (ps > 0) {
   1748           self->smgTime[ps] = self->smgTime[ps - 1];
   1749           FDKmemcpy(self->smgData[ps], self->smgData[ps - 1],
   1750                     self->bitstreamParameterBands * sizeof(UCHAR));
   1751         } else {
   1752           self->smgTime[ps] = self->smoothState->prevSmgTime;
   1753           FDKmemcpy(self->smgData[ps], self->smoothState->prevSmgData,
   1754                     self->bitstreamParameterBands * sizeof(UCHAR));
   1755         }
   1756         break;
   1757 
   1758       case 2:
   1759         self->smgTime[ps] = smgTimeTable[frame->bsSmoothTime[ps]];
   1760         for (pb = 0; pb < self->bitstreamParameterBands; pb++) {
   1761           self->smgData[ps][pb] = 1;
   1762         }
   1763         break;
   1764 
   1765       case 3:
   1766         self->smgTime[ps] = smgTimeTable[frame->bsSmoothTime[ps]];
   1767         pbStride = pbStrideTable[frame->bsFreqResStrideSmg[ps]];
   1768         dataBands = (self->bitstreamParameterBands - 1) / pbStride + 1;
   1769         createMapping(aGroupToBand, 0, self->bitstreamParameterBands, pbStride);
   1770         for (pg = 0; pg < dataBands; pg++) {
   1771           pbStart = aGroupToBand[pg];
   1772           pbStop = aGroupToBand[pg + 1];
   1773           for (pb = pbStart; pb < pbStop; pb++) {
   1774             self->smgData[ps][pb] = frame->bsSmgData[ps][pg];
   1775           }
   1776         }
   1777         break;
   1778     }
   1779   }
   1780 
   1781   self->smoothState->prevSmgTime = self->smgTime[frame->numParameterSets - 1];
   1782   FDKmemcpy(self->smoothState->prevSmgData,
   1783             self->smgData[frame->numParameterSets - 1],
   1784             self->bitstreamParameterBands * sizeof(UCHAR));
   1785 
   1786   if (self->extendFrame) {
   1787     self->smgTime[frame->numParameterSets] =
   1788         self->smgTime[frame->numParameterSets - 1];
   1789     FDKmemcpy(self->smgData[frame->numParameterSets],
   1790               self->smgData[frame->numParameterSets - 1],
   1791               self->bitstreamParameterBands * sizeof(UCHAR));
   1792   }
   1793 
   1794   return MPS_OK;
   1795 }
   1796 
   1797 /*******************************************************************************
   1798  Functionname: decodeAndMapFrameArbdmx
   1799  *******************************************************************************
   1800 
   1801  Description:
   1802    Do delta decoding and dequantization
   1803 
   1804  Arguments:
   1805 
   1806 Input:
   1807 
   1808 Output:
   1809 
   1810 *******************************************************************************/
   1811 static SACDEC_ERROR decodeAndMapFrameArbdmx(HANDLE_SPATIAL_DEC self,
   1812                                             const SPATIAL_BS_FRAME *frame) {
   1813   SACDEC_ERROR err = MPS_OK;
   1814   int ch;
   1815   int offset = self->numOttBoxes;
   1816 
   1817   for (ch = 0; ch < self->numInputChannels; ch++) {
   1818     err = mapIndexData(&frame->CLDLosslessData[offset + ch],
   1819                        self->arbdmxGain__FDK, self->outIdxData,
   1820                        frame->cmpArbdmxGainIdx, NULL, /* no differential data */
   1821                        ch, self->arbdmxGainIdxPrev, offset + ch, t_CLD, 0,
   1822                        self->bitstreamParameterBands,
   1823                        0 /*self->arbdmxGainDefault*/, frame->numParameterSets,
   1824                        frame->paramSlot, self->extendFrame, 0,
   1825                        &(self->concealInfo), ottVsTotInactiv, NULL, NULL, NULL);
   1826     if (err != MPS_OK) goto bail;
   1827   }
   1828 
   1829 bail:
   1830   return err;
   1831 } /* decodeAndMapFrameArbdmx */
   1832 
   1833 /*******************************************************************************
   1834  Functionname: SpatialDecDecodeFrame
   1835  *******************************************************************************
   1836 
   1837  Description:
   1838 
   1839  Arguments:
   1840 
   1841  Return:
   1842 
   1843 *******************************************************************************/
   1844 SACDEC_ERROR SpatialDecDecodeFrame(spatialDec *self, SPATIAL_BS_FRAME *frame) {
   1845   SACDEC_ERROR err = MPS_OK;
   1846 
   1847   self->extendFrame = 0;
   1848   if (frame->paramSlot[frame->numParameterSets - 1] != self->timeSlots - 1) {
   1849     self->extendFrame = 1;
   1850   }
   1851 
   1852   self->TsdTs = 0;
   1853 
   1854   /****** DTDF and MAP DATA ********/
   1855   if ((err = decodeAndMapFrameOtt(self, frame)) != MPS_OK) goto bail;
   1856 
   1857   if ((err = decodeAndMapFrameSmg(self, frame)) != MPS_OK) goto bail;
   1858 
   1859   if (self->arbitraryDownmix != 0) {
   1860     if ((err = decodeAndMapFrameArbdmx(self, frame)) != MPS_OK) goto bail;
   1861   }
   1862 
   1863   if (self->extendFrame) {
   1864     frame->numParameterSets =
   1865         fixMin(MAX_PARAMETER_SETS, frame->numParameterSets + 1);
   1866     frame->paramSlot[frame->numParameterSets - 1] = self->timeSlots - 1;
   1867   }
   1868 
   1869 bail:
   1870   return err;
   1871 } /* SpatialDecDecodeFrame() */
   1872 
   1873 /*******************************************************************************
   1874  Functionname: SpatialDecodeHeader
   1875  *******************************************************************************
   1876 
   1877  Description:
   1878 
   1879  Arguments:
   1880 
   1881  Return:
   1882 
   1883 *******************************************************************************/
   1884 
   1885 SACDEC_ERROR SpatialDecDecodeHeader(
   1886     spatialDec *self, SPATIAL_SPECIFIC_CONFIG *pSpatialSpecificConfig) {
   1887   SACDEC_ERROR err = MPS_OK;
   1888   int i;
   1889 
   1890   self->samplingFreq = pSpatialSpecificConfig->samplingFreq;
   1891   self->timeSlots = pSpatialSpecificConfig->nTimeSlots;
   1892   self->frameLength = self->timeSlots * self->qmfBands;
   1893   self->bitstreamParameterBands = pSpatialSpecificConfig->freqRes;
   1894 
   1895   if (self->pConfigCurrent->syntaxFlags & SACDEC_SYNTAX_LD)
   1896     self->hybridBands = self->qmfBands;
   1897   else
   1898     self->hybridBands = SacGetHybridSubbands(self->qmfBands);
   1899   self->tp_hybBandBorder = 12;
   1900 
   1901   self->numParameterBands = self->bitstreamParameterBands;
   1902 
   1903   if (self->pConfigCurrent->syntaxFlags & SACDEC_SYNTAX_LD) {
   1904     switch (self->numParameterBands) {
   1905       case 4:
   1906         self->kernels = kernels_4_to_64;
   1907         break;
   1908       case 5:
   1909         self->kernels = kernels_5_to_64;
   1910         break;
   1911       case 7:
   1912         self->kernels = kernels_7_to_64;
   1913         break;
   1914       case 9:
   1915         self->kernels = kernels_9_to_64;
   1916         break;
   1917       case 12:
   1918         self->kernels = kernels_12_to_64;
   1919         break;
   1920       case 15:
   1921         self->kernels = kernels_15_to_64;
   1922         break;
   1923       case 23:
   1924         self->kernels = kernels_23_to_64;
   1925         break;
   1926       default:
   1927         return MPS_INVALID_PARAMETERBANDS; /* unsupported numParameterBands */
   1928     }
   1929   } else {
   1930     switch (self->numParameterBands) {
   1931       case 4:
   1932         self->kernels = kernels_4_to_71;
   1933         break;
   1934       case 5:
   1935         self->kernels = kernels_5_to_71;
   1936         break;
   1937       case 7:
   1938         self->kernels = kernels_7_to_71;
   1939         break;
   1940       case 10:
   1941         self->kernels = kernels_10_to_71;
   1942         break;
   1943       case 14:
   1944         self->kernels = kernels_14_to_71;
   1945         break;
   1946       case 20:
   1947         self->kernels = kernels_20_to_71;
   1948         break;
   1949       case 28:
   1950         self->kernels = kernels_28_to_71;
   1951         break;
   1952       default:
   1953         return MPS_INVALID_PARAMETERBANDS; /* unsupported numParameterBands */
   1954     }
   1955   }
   1956 
   1957   /* create param to hyb band table */
   1958   FDKmemclear(self->param2hyb, (MAX_PARAMETER_BANDS + 1) * sizeof(int));
   1959   for (i = 0; i < self->hybridBands; i++) {
   1960     self->param2hyb[self->kernels[i] + 1] = i + 1;
   1961   }
   1962   {
   1963     int pb = self->kernels[i - 1] + 2;
   1964     for (; pb < (MAX_PARAMETER_BANDS + 1); pb++) {
   1965       self->param2hyb[pb] = i;
   1966     }
   1967     for (pb = 0; pb < MAX_PARAMETER_BANDS; pb += 1) {
   1968       self->kernels_width[pb] = self->param2hyb[pb + 1] - self->param2hyb[pb];
   1969     }
   1970   }
   1971 
   1972   self->treeConfig = pSpatialSpecificConfig->treeConfig;
   1973 
   1974   self->numOttBoxes = pSpatialSpecificConfig->nOttBoxes;
   1975 
   1976   self->numInputChannels = pSpatialSpecificConfig->nInputChannels;
   1977 
   1978   self->numOutputChannels = pSpatialSpecificConfig->nOutputChannels;
   1979 
   1980   self->quantMode = pSpatialSpecificConfig->quantMode;
   1981 
   1982   self->arbitraryDownmix = pSpatialSpecificConfig->bArbitraryDownmix;
   1983 
   1984   self->numM2rows = self->numOutputChannels;
   1985 
   1986   {
   1987     self->residualCoding = 0;
   1988     if (self->arbitraryDownmix == 2)
   1989       self->arbitraryDownmix = 1; /* no arbitrary downmix residuals */
   1990   }
   1991   if ((self->pConfigCurrent->syntaxFlags & SACDEC_SYNTAX_USAC)) {
   1992     self->residualCoding = pSpatialSpecificConfig->bResidualCoding;
   1993   }
   1994 
   1995   self->clipProtectGain__FDK =
   1996       FX_CFG2FX_DBL(clipGainTable__FDK[pSpatialSpecificConfig->bsFixedGainDMX]);
   1997   self->clipProtectGainSF__FDK =
   1998       clipGainSFTable__FDK[pSpatialSpecificConfig->bsFixedGainDMX];
   1999 
   2000   self->tempShapeConfig = pSpatialSpecificConfig->tempShapeConfig;
   2001 
   2002   self->decorrConfig = pSpatialSpecificConfig->decorrConfig;
   2003 
   2004   if (self->upmixType == UPMIXTYPE_BYPASS) {
   2005     self->numOutputChannels = self->numInputChannels;
   2006   }
   2007 
   2008   self->numOutputChannelsAT = self->numOutputChannels;
   2009 
   2010   self->numOttBandsIPD = pSpatialSpecificConfig->numOttBandsIPD;
   2011   self->phaseCoding = pSpatialSpecificConfig->bsPhaseCoding;
   2012   for (i = 0; i < self->numOttBoxes; i++) {
   2013     {
   2014       self->pConfigCurrent->bitstreamOttBands[i] =
   2015           self->bitstreamParameterBands;
   2016     }
   2017     self->numOttBands[i] = self->pConfigCurrent->bitstreamOttBands[i];
   2018   } /* i */
   2019 
   2020   if (self->residualCoding) {
   2021     int numBoxes = self->numOttBoxes;
   2022     for (i = 0; i < numBoxes; i++) {
   2023       self->residualPresent[i] =
   2024           pSpatialSpecificConfig->ResidualConfig[i].bResidualPresent;
   2025 
   2026       if (self->residualPresent[i]) {
   2027         self->residualBands[i] =
   2028             pSpatialSpecificConfig->ResidualConfig[i].nResidualBands;
   2029         /* conversion from hybrid bands to qmf bands */
   2030         self->residualQMFBands[i] =
   2031             fMax(self->param2hyb[self->residualBands[i]] + 3 - 10,
   2032                  3); /* simplification for the lowest 10 hybrid bands */
   2033       } else {
   2034         self->residualBands[i] = 0;
   2035         self->residualQMFBands[i] = 0;
   2036       }
   2037     }
   2038   } /* self->residualCoding */
   2039   else {
   2040     int boxes = self->numOttBoxes;
   2041     for (i = 0; i < boxes; i += 1) {
   2042       self->residualPresent[i] = 0;
   2043       self->residualBands[i] = 0;
   2044     }
   2045   }
   2046 
   2047   switch (self->treeConfig) {
   2048     case TREE_212:
   2049       self->numDirektSignals = 1;
   2050       self->numDecorSignals = 1;
   2051       self->numXChannels = 1;
   2052       if (self->arbitraryDownmix == 2) {
   2053         self->numXChannels += 1;
   2054       }
   2055       self->numVChannels = self->numDirektSignals + self->numDecorSignals;
   2056       break;
   2057     default:
   2058       return MPS_INVALID_TREECONFIG;
   2059   }
   2060 
   2061   self->highRateMode = pSpatialSpecificConfig->bsHighRateMode;
   2062   self->decorrType = pSpatialSpecificConfig->bsDecorrType;
   2063 
   2064   SpatialDecDecodeHelperInfo(pSpatialSpecificConfig, UPMIXTYPE_NORMAL);
   2065 
   2066   return err;
   2067 }
   2068 
   2069 /*******************************************************************************
   2070  Functionname: SpatialDecCreateBsFrame
   2071  *******************************************************************************
   2072 
   2073  Description: Create spatial bitstream structure
   2074 
   2075  Arguments:   spatialDec* self
   2076               const SPATIAL_BS_FRAME **bsFrame
   2077 
   2078  Return:      -
   2079 
   2080 *******************************************************************************/
   2081 SACDEC_ERROR SpatialDecCreateBsFrame(SPATIAL_BS_FRAME *bsFrame,
   2082                                      BS_LL_STATE *llState) {
   2083   SPATIAL_BS_FRAME *pBs = bsFrame;
   2084 
   2085   const int maxNumOtt = MAX_NUM_OTT;
   2086   const int maxNumInputChannels = MAX_INPUT_CHANNELS;
   2087 
   2088   FDK_ALLOCATE_MEMORY_1D_P(
   2089       pBs->cmpOttIPDidx, maxNumOtt * MAX_PARAMETER_SETS * MAX_PARAMETER_BANDS,
   2090       SCHAR, SCHAR(*)[MAX_PARAMETER_SETS][MAX_PARAMETER_BANDS])
   2091 
   2092   /* Arbitrary Downmix */
   2093   FDK_ALLOCATE_MEMORY_1D_P(
   2094       pBs->cmpArbdmxGainIdx,
   2095       maxNumInputChannels * MAX_PARAMETER_SETS * MAX_PARAMETER_BANDS, SCHAR,
   2096       SCHAR(*)[MAX_PARAMETER_SETS][MAX_PARAMETER_BANDS])
   2097 
   2098   /* Lossless control */
   2099   FDK_ALLOCATE_MEMORY_1D(pBs->CLDLosslessData, MAX_NUM_PARAMETERS, LOSSLESSDATA)
   2100   FDK_ALLOCATE_MEMORY_1D(pBs->ICCLosslessData, MAX_NUM_PARAMETERS, LOSSLESSDATA)
   2101 
   2102   FDK_ALLOCATE_MEMORY_1D(pBs->IPDLosslessData, MAX_NUM_PARAMETERS, LOSSLESSDATA)
   2103 
   2104   pBs->newBsData = 0;
   2105   pBs->numParameterSets = 1;
   2106 
   2107   /* Link lossless states */
   2108   for (int x = 0; x < MAX_NUM_PARAMETERS; x++) {
   2109     pBs->CLDLosslessData[x].state = &llState->CLDLosslessState[x];
   2110     pBs->ICCLosslessData[x].state = &llState->ICCLosslessState[x];
   2111 
   2112     pBs->IPDLosslessData[x].state = &llState->IPDLosslessState[x];
   2113   }
   2114 
   2115   return MPS_OK;
   2116 
   2117 bail:
   2118   return MPS_OUTOFMEMORY;
   2119 }
   2120 
   2121 /*******************************************************************************
   2122  Functionname: SpatialDecCloseBsFrame
   2123  *******************************************************************************
   2124 
   2125  Description: Close spatial bitstream structure
   2126 
   2127  Arguments:   spatialDec* self
   2128 
   2129  Return:      -
   2130 
   2131 *******************************************************************************/
   2132 void SpatialDecCloseBsFrame(SPATIAL_BS_FRAME *pBs) {
   2133   if (pBs != NULL) {
   2134     /* These arrays contain the compact indices, only one value per pbstride,
   2135      * only paramsets actually containing data. */
   2136 
   2137     FDK_FREE_MEMORY_1D(pBs->cmpOttIPDidx);
   2138 
   2139     /* Arbitrary Downmix */
   2140     FDK_FREE_MEMORY_1D(pBs->cmpArbdmxGainIdx);
   2141 
   2142     /* Lossless control */
   2143     FDK_FREE_MEMORY_1D(pBs->IPDLosslessData);
   2144     FDK_FREE_MEMORY_1D(pBs->CLDLosslessData);
   2145     FDK_FREE_MEMORY_1D(pBs->ICCLosslessData);
   2146   }
   2147 }
   2148