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 /*****************************  MPEG-4 AAC Decoder  **************************
     85 
     86    Author(s):   Christian Griebel
     87    Description: Dynamic range control (DRC) decoder tool for AAC
     88 
     89 ******************************************************************************/
     90 
     91 #include "aacdec_drc.h"
     92 
     93 
     94 #include "channelinfo.h"
     95 #include "aac_rom.h"
     96 
     97  #include "sbrdecoder.h"
     98 
     99 /*
    100  * Dynamic Range Control
    101  */
    102 
    103 /* For parameter conversion */
    104 #define DRC_PARAMETER_BITS        ( 7 )
    105 #define DRC_MAX_QUANT_STEPS       ( 1<<DRC_PARAMETER_BITS )
    106 #define DRC_MAX_QUANT_FACTOR      ( DRC_MAX_QUANT_STEPS-1 )
    107 #define DRC_PARAM_QUANT_STEP      ( FL2FXCONST_DBL(1.0f/(float)DRC_MAX_QUANT_FACTOR) )
    108 #define DRC_PARAM_SCALE           ( 1 )
    109 
    110 #define MAX_REFERENCE_LEVEL       ( 127 )
    111 
    112  #define DVB_ANC_DATA_SYNC_BYTE   ( 0xBC )    /* DVB ancillary data sync byte. */
    113 
    114 /*!
    115   \brief Initialize DRC information
    116 
    117   \self Handle of DRC info
    118 
    119   \return none
    120 */
    121 void aacDecoder_drcInit (
    122     HANDLE_AAC_DRC self )
    123 {
    124   CDrcParams *pParams;
    125 
    126   if (self == NULL) {
    127     return;
    128   }
    129 
    130   /* init control fields */
    131   self->enable = 0;
    132   self->numThreads = 0;
    133   self->digitalNorm = 0;
    134 
    135   /* init params */
    136   pParams = &self->params;
    137   pParams->bsDelayEnable = 0;
    138   pParams->cut   = FL2FXCONST_DBL(0.0f);
    139   pParams->boost = FL2FXCONST_DBL(0.0f);
    140   pParams->targetRefLevel = AACDEC_DRC_DEFAULT_REF_LEVEL;
    141   pParams->expiryFrame = AACDEC_DRC_DFLT_EXPIRY_FRAMES;
    142 
    143   /* initial program ref level = target ref level */
    144   self->progRefLevel = pParams->targetRefLevel;
    145 }
    146 
    147 
    148 /*!
    149   \brief Initialize DRC control data for one channel
    150 
    151   \self Handle of DRC info
    152 
    153   \return none
    154 */
    155 void aacDecoder_drcInitChannelData (
    156     CDrcChannelData *pDrcChData )
    157 {
    158   if (pDrcChData != NULL) {
    159     pDrcChData->expiryCount = 0;
    160     pDrcChData->numBands    = 1;
    161     pDrcChData->bandTop[0]  = (1024 >> 2) - 1;
    162     pDrcChData->drcValue[0] = 0;
    163     pDrcChData->drcInterpolationScheme = 0;
    164     pDrcChData->drcDataType = UNKNOWN_PAYLOAD;
    165   }
    166 }
    167 
    168 
    169 /*!
    170   \brief  Set one single DRC parameter
    171 
    172   \self   Handle of DRC info.
    173   \param  Parameter to be set.
    174   \value  Value to be set.
    175 
    176   \return an error code.
    177 */
    178 AAC_DECODER_ERROR aacDecoder_drcSetParam (
    179     HANDLE_AAC_DRC    self,
    180     AACDEC_DRC_PARAM  param,
    181     INT               value )
    182 {
    183   AAC_DECODER_ERROR ErrorStatus = AAC_DEC_OK;
    184 
    185   switch (param)
    186   {
    187   case DRC_CUT_SCALE:
    188     /* set attenuation scale factor */
    189     if ( (value < 0)
    190       || (value > DRC_MAX_QUANT_FACTOR) ) {
    191       return AAC_DEC_SET_PARAM_FAIL;
    192     }
    193     if (self == NULL) {
    194       return AAC_DEC_INVALID_HANDLE;
    195     }
    196     self->params.cut = (FIXP_DBL)((INT)(DRC_PARAM_QUANT_STEP>>DRC_PARAM_SCALE) * (INT)value);
    197     break;
    198   case DRC_BOOST_SCALE:
    199     /* set boost factor */
    200     if ( (value < 0)
    201       || (value > DRC_MAX_QUANT_FACTOR) ) {
    202       return AAC_DEC_SET_PARAM_FAIL;
    203     }
    204     if (self == NULL) {
    205       return AAC_DEC_INVALID_HANDLE;
    206     }
    207     self->params.boost = (FIXP_DBL)((INT)(DRC_PARAM_QUANT_STEP>>DRC_PARAM_SCALE) * (INT)value);
    208     break;
    209   case TARGET_REF_LEVEL:
    210     if ( value >  MAX_REFERENCE_LEVEL
    211       || value < -MAX_REFERENCE_LEVEL ) {
    212       return AAC_DEC_SET_PARAM_FAIL;
    213     }
    214     if (self == NULL) {
    215       return AAC_DEC_INVALID_HANDLE;
    216     }
    217     if (value < 0) {
    218       self->digitalNorm = 0;
    219     }
    220     else {
    221       /* ref_level must be between 0 and MAX_REFERENCE_LEVEL, inclusive */
    222       self->digitalNorm    = 1;
    223       self->params.targetRefLevel = value;
    224       self->progRefLevel = (SCHAR)value;  /* Set the program reference level equal to the target
    225                                                level according to 4.5.2.7.3 of ISO/IEC 14496-3. */
    226     }
    227     break;
    228   case APPLY_HEAVY_COMPRESSION:
    229     if (value < 0 || value > 1) {
    230       return AAC_DEC_SET_PARAM_FAIL;
    231     }
    232     if (self == NULL) {
    233       return AAC_DEC_INVALID_HANDLE;
    234     }
    235     self->params.applyHeavyCompression = (UCHAR)value;
    236     break;
    237   case DRC_BS_DELAY:
    238     if (value < 0 || value > 1) {
    239       return AAC_DEC_SET_PARAM_FAIL;
    240     }
    241     if (self == NULL) {
    242       return AAC_DEC_INVALID_HANDLE;
    243     }
    244     self->params.bsDelayEnable = value;
    245     break;
    246   case DRC_DATA_EXPIRY_FRAME:
    247     if (self == NULL) {
    248       return AAC_DEC_INVALID_HANDLE;
    249     }
    250     self->params.expiryFrame = (UINT)value;
    251     break;
    252   default:
    253     return AAC_DEC_SET_PARAM_FAIL;
    254   }  /* switch(param) */
    255 
    256   /* switch on/off processing */
    257   self->enable = ( (self->params.boost > (FIXP_DBL)0)
    258                 || (self->params.cut   > (FIXP_DBL)0)
    259                 || (self->params.applyHeavyCompression != 0)
    260                 || (self->digitalNorm == 1) );
    261 
    262 
    263   return ErrorStatus;
    264 }
    265 
    266 
    267 static int parseExcludedChannels( UINT *excludedChnsMask,
    268                                   HANDLE_FDK_BITSTREAM bs )
    269 {
    270   UINT excludeMask = 0;
    271   UINT i, j;
    272   int  bitCnt = 9;
    273 
    274   for (i = 0, j = 1; i < 7; i++, j<<=1) {
    275     if (FDKreadBits(bs,1)) {
    276       excludeMask |= j;
    277     }
    278   }
    279 
    280   /* additional_excluded_chns */
    281   while (FDKreadBits(bs,1)) {
    282     for (i = 0; i < 7; i++, j<<=1) {
    283       if (FDKreadBits(bs,1)) {
    284         excludeMask |= j;
    285       }
    286     }
    287     bitCnt += 9;
    288     FDK_ASSERT(j < (UINT)-1);
    289   }
    290 
    291   *excludedChnsMask = excludeMask;
    292 
    293   return (bitCnt);
    294 }
    295 
    296 
    297 /*!
    298   \brief Save DRC payload bitstream position
    299 
    300   \self Handle of DRC info
    301   \bs Handle of FDK bitstream
    302 
    303   \return The number of DRC payload bits
    304 */
    305 int aacDecoder_drcMarkPayload (
    306     HANDLE_AAC_DRC self,
    307     HANDLE_FDK_BITSTREAM bs,
    308     AACDEC_DRC_PAYLOAD_TYPE type )
    309 {
    310   UINT bsStartPos;
    311   int  i, numBands = 1, bitCnt = 0;
    312 
    313   if (self == NULL) {
    314     return 0;
    315   }
    316 
    317   bsStartPos = FDKgetValidBits(bs);
    318 
    319   switch (type) {
    320     case MPEG_DRC_EXT_DATA:
    321     {
    322       bitCnt = 4;
    323 
    324       if (FDKreadBits(bs,1)) {          /* pce_tag_present */
    325         FDKreadBits(bs,8);              /* pce_instance_tag + drc_tag_reserved_bits */
    326         bitCnt+=8;
    327       }
    328 
    329       if (FDKreadBits(bs,1)) {          /* excluded_chns_present */
    330         FDKreadBits(bs,7);              /* exclude mask [0..7] */
    331         bitCnt+=8;
    332         while (FDKreadBits(bs,1)) {     /* additional_excluded_chns */
    333           FDKreadBits(bs,7);            /* exclude mask [x..y] */
    334           bitCnt+=8;
    335         }
    336       }
    337 
    338       if (FDKreadBits(bs,1)) {          /* drc_bands_present */
    339         numBands += FDKreadBits(bs, 4); /* drc_band_incr */
    340         FDKreadBits(bs,4);              /* reserved */
    341         bitCnt+=8;
    342         for (i = 0; i < numBands; i++) {
    343           FDKreadBits(bs,8);            /* drc_band_top[i] */
    344           bitCnt+=8;
    345         }
    346       }
    347 
    348       if (FDKreadBits(bs,1)) {          /* prog_ref_level_present */
    349         FDKreadBits(bs,8);              /* prog_ref_level + prog_ref_level_reserved_bits */
    350         bitCnt+=8;
    351       }
    352 
    353       for (i = 0; i < numBands; i++) {
    354         FDKreadBits(bs,8);              /* dyn_rng_sgn[i] + dyn_rng_ctl[i] */
    355         bitCnt+=8;
    356       }
    357 
    358       if ( (self->numPayloads < MAX_DRC_THREADS)
    359         && ((INT)FDKgetValidBits(bs) >= 0) )
    360       {
    361         self->drcPayloadPosition[self->numPayloads++] = bsStartPos;
    362       }
    363     }
    364     break;
    365 
    366     case DVB_DRC_ANC_DATA:
    367       bitCnt += 8;
    368       /* check sync word */
    369       if (FDKreadBits(bs, 8) == DVB_ANC_DATA_SYNC_BYTE)
    370       {
    371         int dmxLevelsPresent, compressionPresent;
    372         int coarseGrainTcPresent, fineGrainTcPresent;
    373 
    374         /* bs_info field */
    375         FDKreadBits(bs, 8);                          /* mpeg_audio_type, dolby_surround_mode, presentation_mode */
    376         bitCnt+=8;
    377 
    378         /* Evaluate ancillary_data_status */
    379         FDKreadBits(bs, 3);                          /* reserved, set to 0 */
    380         dmxLevelsPresent = FDKreadBits(bs, 1);       /* downmixing_levels_MPEG4_status */
    381         FDKreadBits(bs, 1);                          /* reserved, set to 0 */
    382         compressionPresent   = FDKreadBits(bs, 1);   /* audio_coding_mode_and_compression status */
    383         coarseGrainTcPresent = FDKreadBits(bs, 1);   /* coarse_grain_timecode_status */
    384         fineGrainTcPresent   = FDKreadBits(bs, 1);   /* fine_grain_timecode_status */
    385         bitCnt+=8;
    386 
    387         /* MPEG4 downmixing levels */
    388         if (dmxLevelsPresent) {
    389           FDKreadBits(bs, 8);                        /* downmixing_levels_MPEG4 */
    390           bitCnt+=8;
    391         }
    392         /* audio coding mode and compression status */
    393         if (compressionPresent) {
    394           FDKreadBits(bs, 16);                        /* audio_coding_mode, Compression_value */
    395           bitCnt+=16;
    396         }
    397         /* coarse grain timecode */
    398         if (coarseGrainTcPresent) {
    399           FDKreadBits(bs, 16);                       /* coarse_grain_timecode */
    400           bitCnt+=16;
    401         }
    402         /* fine grain timecode */
    403         if (fineGrainTcPresent) {
    404           FDKreadBits(bs, 16);                       /* fine_grain_timecode */
    405           bitCnt+=16;
    406         }
    407         if ( !self->dvbAncDataAvailable
    408           && ((INT)FDKgetValidBits(bs) >= 0) )
    409         {
    410           self->dvbAncDataPosition  = bsStartPos;
    411           self->dvbAncDataAvailable = 1;
    412         }
    413       }
    414       break;
    415 
    416     default:
    417       break;
    418   }
    419 
    420   return (bitCnt);
    421 }
    422 
    423 
    424 /*!
    425   \brief Parse DRC parameters from bitstream
    426 
    427   \bs Handle of FDK bitstream (in)
    428   \pDrcBs Pointer to DRC payload data container (out)
    429   \payloadPosition Bitstream position of MPEG DRC data junk (in)
    430 
    431   \return Number of bits read (0 in case of a parse error)
    432 */
    433 static int aacDecoder_drcParse (
    434     HANDLE_FDK_BITSTREAM  bs,
    435     CDrcPayload          *pDrcBs,
    436     UINT                  payloadPosition )
    437 {
    438   int i, numBands, bitCnt = 4;
    439 
    440   /* Move to the beginning of the DRC payload field */
    441   FDKpushBiDirectional(bs, FDKgetValidBits(bs)-payloadPosition);
    442 
    443   /* pce_tag_present */
    444   if (FDKreadBits(bs,1))
    445   {
    446     pDrcBs->pceInstanceTag = FDKreadBits(bs, 4);  /* pce_instance_tag */
    447     /* only one program supported */
    448     FDKreadBits(bs, 4);  /* drc_tag_reserved_bits */
    449     bitCnt += 8;
    450   } else {
    451     pDrcBs->pceInstanceTag = -1;  /* not present */
    452   }
    453 
    454   if (FDKreadBits(bs,1)) {        /* excluded_chns_present */
    455     /* get excluded_chn_mask */
    456     bitCnt += parseExcludedChannels(&pDrcBs->excludedChnsMask, bs);
    457   } else {
    458     pDrcBs->excludedChnsMask = 0;
    459   }
    460 
    461   numBands = 1;
    462   if (FDKreadBits(bs,1))  /* drc_bands_present */
    463   {
    464     /* get band_incr */
    465     numBands += FDKreadBits(bs, 4);  /* drc_band_incr */
    466     pDrcBs->channelData.drcInterpolationScheme = FDKreadBits(bs, 4);  /* drc_interpolation_scheme */
    467     bitCnt += 8;
    468     /* band_top */
    469     for (i = 0; i < numBands; i++)
    470     {
    471       pDrcBs->channelData.bandTop[i] = FDKreadBits(bs, 8);  /* drc_band_top[i] */
    472       bitCnt += 8;
    473     }
    474   }
    475   else {
    476     pDrcBs->channelData.bandTop[0] = 255;
    477   }
    478 
    479   pDrcBs->channelData.numBands = numBands;
    480 
    481   if (FDKreadBits(bs,1))                        /* prog_ref_level_present */
    482   {
    483     pDrcBs->progRefLevel = FDKreadBits(bs, 7);  /* prog_ref_level */
    484     FDKreadBits(bs, 1);                         /* prog_ref_level_reserved_bits */
    485     bitCnt += 8;
    486   } else {
    487     pDrcBs->progRefLevel = -1;
    488   }
    489 
    490   for (i = 0; i < numBands; i++)
    491   {
    492     pDrcBs->channelData.drcValue[i]  = FDKreadBits(bs, 1) << 7;   /* dyn_rng_sgn[i] */
    493     pDrcBs->channelData.drcValue[i] |= FDKreadBits(bs, 7) & 0x7F; /* dyn_rng_ctl[i] */
    494     bitCnt += 8;
    495   }
    496 
    497   /* Set DRC payload type */
    498   pDrcBs->channelData.drcDataType = MPEG_DRC_EXT_DATA;
    499 
    500   return (bitCnt);
    501 }
    502 
    503 
    504 /*!
    505   \brief Parse heavy compression value transported in DSEs of DVB streams with MPEG-4 content.
    506 
    507   \bs Handle of FDK bitstream (in)
    508   \pDrcBs Pointer to DRC payload data container (out)
    509   \payloadPosition Bitstream position of DVB ancillary data junk
    510 
    511   \return Number of bits read (0 in case of a parse error)
    512 */
    513 #define DVB_COMPRESSION_SCALE   ( 8 )       /* 48,164 dB */
    514 
    515 static int aacDecoder_drcReadCompression (
    516     HANDLE_FDK_BITSTREAM  bs,
    517     CDrcPayload          *pDrcBs,
    518     UINT                  payloadPosition )
    519 {
    520   int  bitCnt = 0;
    521   int  dmxLevelsPresent, compressionPresent;
    522   int  coarseGrainTcPresent, fineGrainTcPresent;
    523 
    524   /* Move to the beginning of the DRC payload field */
    525   FDKpushBiDirectional(bs, FDKgetValidBits(bs)-payloadPosition);
    526 
    527   /* Sanity checks */
    528   if ( FDKgetValidBits(bs) < 24 ) {
    529     return 0;
    530   }
    531 
    532   /* Check sync word */
    533   if (FDKreadBits(bs, 8) != DVB_ANC_DATA_SYNC_BYTE) {
    534     return 0;
    535   }
    536 
    537   /* Evaluate bs_info field */
    538   if (FDKreadBits(bs, 2) != 3) {               /* mpeg_audio_type */
    539     /* No MPEG-4 audio data */
    540     return 0;
    541   }
    542   FDKreadBits(bs, 2);                          /* dolby_surround_mode */
    543   FDKreadBits(bs, 2);                          /* presentation_mode */
    544   if (FDKreadBits(bs, 2) != 0) {               /* reserved, set to 0 */
    545     return 0;
    546   }
    547 
    548   /* Evaluate ancillary_data_status */
    549   if (FDKreadBits(bs, 3) != 0) {               /* reserved, set to 0 */
    550     return 0;
    551   }
    552   dmxLevelsPresent = FDKreadBits(bs, 1);       /* downmixing_levels_MPEG4_status */
    553   if (FDKreadBits(bs, 1) != 0) {               /* reserved, set to 0 */
    554     return 0;
    555   }
    556   compressionPresent   = FDKreadBits(bs, 1);   /* audio_coding_mode_and_compression status */
    557   coarseGrainTcPresent = FDKreadBits(bs, 1);   /* coarse_grain_timecode_status */
    558   fineGrainTcPresent   = FDKreadBits(bs, 1);   /* fine_grain_timecode_status */
    559   bitCnt += 24;
    560 
    561   if (dmxLevelsPresent) {
    562     FDKreadBits(bs, 8);                        /* downmixing_levels_MPEG4 */
    563     bitCnt += 8;
    564   }
    565 
    566   /* audio_coding_mode_and_compression_status */
    567   if (compressionPresent)
    568   {
    569     UCHAR compressionOn, compressionValue;
    570 
    571     /* audio_coding_mode */
    572     if ( FDKreadBits(bs, 7) != 0 ) {  /* The reserved bits shall be set to "0". */
    573       return 0;
    574     }
    575     compressionOn    = (UCHAR)FDKreadBits(bs, 1);  /* compression_on */
    576     compressionValue = (UCHAR)FDKreadBits(bs, 8);  /* Compression_value */
    577     bitCnt += 16;
    578 
    579     if ( compressionOn ) {
    580       /* A compression value is available so store the data just like MPEG DRC data */
    581       pDrcBs->channelData.numBands    =  1;                            /* One band ... */
    582       pDrcBs->channelData.drcValue[0] =  compressionValue;             /* ... with one value ... */
    583       pDrcBs->channelData.bandTop[0]  = (1024 >> 2) - 1;  /* ... comprising the whole spectrum. */
    584       pDrcBs->pceInstanceTag          = -1;                            /* Not present */
    585       pDrcBs->progRefLevel            = -1;                            /* Not present */
    586       pDrcBs->channelData.drcDataType =  DVB_DRC_ANC_DATA;             /* Set DRC payload type to DVB. */
    587     } else {
    588       /* No compression value available */
    589       /* CAUTION: It is not clearly defined by standard how to react in this situation. */
    590       /* Turn down the compression value to aprox. 0dB */
    591       pDrcBs->channelData.numBands    =  1;                            /* One band ... */
    592       pDrcBs->channelData.drcValue[0] =  0x80;                         /* ... with aprox. 0dB ... */
    593       pDrcBs->channelData.bandTop[0]  = (1024 >> 2) - 1;  /* ... comprising the whole spectrum. */
    594       pDrcBs->channelData.drcDataType =  DVB_DRC_ANC_DATA;             /* Set DRC payload type to DVB. */
    595 
    596       /* If compression_on field is set to "0" the compression_value field shall be "0000 0000". */
    597       if (compressionValue != 0) {
    598         return 0;
    599       }
    600     }
    601   }
    602 
    603   /* Read timecodes if available just to get the right amount of bits. */
    604   if (coarseGrainTcPresent) {
    605     FDKreadBits(bs, 16);      /* coarse_grain_timecode */
    606     bitCnt += 16;
    607   }
    608   if (fineGrainTcPresent) {
    609     FDKreadBits(bs, 16);      /* fine_grain_timecode */
    610     bitCnt += 16;
    611   }
    612 
    613   return (bitCnt);
    614 }
    615 
    616 
    617 /*
    618  * Prepare DRC processing
    619  */
    620 static int aacDecoder_drcExtractAndMap (
    621         HANDLE_AAC_DRC  self,
    622         HANDLE_FDK_BITSTREAM hBs,
    623         CAacDecoderStaticChannelInfo *pAacDecoderStaticChannelInfo[],
    624         UCHAR  pceInstanceTag,
    625         UCHAR  channelMapping[], /* Channel mapping translating drcChannel index to canonical channel index */
    626         int    validChannels )
    627 {
    628   CDrcPayload  threadBs[MAX_DRC_THREADS];
    629   CDrcPayload *validThreadBs[MAX_DRC_THREADS];
    630   UINT backupBsPosition;
    631   int  i, thread, validThreads = 0;
    632   int  numExcludedChns[MAX_DRC_THREADS];
    633 
    634   self->numThreads = 0;
    635   backupBsPosition = FDKgetValidBits(hBs);
    636 
    637   for (i = 0; i < self->numPayloads && self->numThreads < MAX_DRC_THREADS; i++) {
    638     int bitsParsed;
    639 
    640     /* Init payload data chunk. The memclear is very important because it initializes
    641        the most values. Without it the module wouldn't work properly or crash. */
    642     FDKmemclear(&threadBs[self->numThreads], sizeof(CDrcPayload));
    643     threadBs[self->numThreads].channelData.bandTop[0]  = (1024 >> 2) - 1;
    644 
    645     /* Extract payload */
    646     bitsParsed = aacDecoder_drcParse( hBs,
    647                                      &threadBs[self->numThreads],
    648                                       self->drcPayloadPosition[i] );
    649     if (bitsParsed > 0) {
    650       self->numThreads++;
    651     }
    652   }
    653   self->numPayloads = 0;
    654 
    655   if (self->dvbAncDataAvailable)
    656   { /* Append a DVB heavy compression payload thread if available. */
    657     int bitsParsed;
    658 
    659     /* Init payload data chunk. The memclear is very important because it initializes
    660        the most values. Without it the module wouldn't work properly or crash. */
    661     FDKmemclear(&threadBs[self->numThreads], sizeof(CDrcPayload));
    662     threadBs[self->numThreads].channelData.bandTop[0]  = (1024 >> 2) - 1;
    663 
    664     /* Extract payload */
    665     bitsParsed = aacDecoder_drcReadCompression( hBs,
    666                                                &threadBs[self->numThreads],
    667                                                 self->dvbAncDataPosition );
    668     if (bitsParsed > 0) {
    669       self->numThreads++;
    670     }
    671   }
    672   self->dvbAncDataAvailable = 0;
    673 
    674   /* Reset the bitbufffer */
    675   FDKpushBiDirectional(hBs, FDKgetValidBits(hBs) - backupBsPosition);
    676 
    677   /* calculate number of valid bits in excl_chn_mask */
    678 
    679   /* coupling channels not supported */
    680 
    681   /* check for valid threads */
    682   for (thread = 0; thread < self->numThreads; thread++) {
    683     CDrcPayload *pThreadBs = &threadBs[thread];
    684     int numExclChns = 0;
    685 
    686     switch ((AACDEC_DRC_PAYLOAD_TYPE)pThreadBs->channelData.drcDataType) {
    687       default:
    688         continue;
    689       case MPEG_DRC_EXT_DATA:
    690       case DVB_DRC_ANC_DATA:
    691         break;
    692     }
    693 
    694     if (pThreadBs->pceInstanceTag >= 0) {  /* if PCE tag present */
    695       if (pThreadBs->pceInstanceTag != pceInstanceTag) {
    696         continue;  /* don't accept */
    697       }
    698     }
    699 
    700     /* calculate number of excluded channels */
    701     if (pThreadBs->excludedChnsMask > 0) {
    702       INT exclMask = pThreadBs->excludedChnsMask;
    703       int ch;
    704       for (ch = 0; ch < validChannels; ch++) {
    705         numExclChns += exclMask & 0x1;
    706         exclMask >>= 1;
    707       }
    708     }
    709     if (numExclChns < validChannels) {
    710       validThreadBs[validThreads]   = pThreadBs;
    711       numExcludedChns[validThreads] = numExclChns;
    712       validThreads++;
    713     }
    714   }
    715 
    716   if (validThreads > 1) {
    717     int ch;
    718 
    719     /* check consistency of excl_chn_mask amongst valid DRC threads */
    720     for (ch = 0; ch < validChannels; ch++) {
    721       int present = 0;
    722 
    723       for (thread = 0; thread < validThreads; thread++) {
    724         CDrcPayload *pThreadBs = validThreadBs[thread];
    725 
    726 
    727         /* thread applies to this channel */
    728         if ( (pThreadBs->channelData.drcDataType == MPEG_DRC_EXT_DATA)
    729           && ( (numExcludedChns[thread] == 0)
    730             || (!(pThreadBs->excludedChnsMask & (1<<ch))) ) ) {
    731           present++;
    732         }
    733       }
    734 
    735 
    736       if (present > 1) {
    737         return -1;
    738       }
    739     }
    740   }
    741 
    742   /* map DRC bitstream information onto DRC channel information */
    743   for (thread = 0; thread < validThreads; thread++)
    744   {
    745     CDrcPayload *pThreadBs = validThreadBs[thread];
    746     INT exclMask = pThreadBs->excludedChnsMask;
    747     AACDEC_DRC_PAYLOAD_TYPE drcPayloadType = (AACDEC_DRC_PAYLOAD_TYPE)pThreadBs->channelData.drcDataType;
    748     int ch;
    749 
    750     /* last progRefLevel transmitted is the one that is used
    751      * (but it should really only be transmitted once per block!)
    752      */
    753     if (pThreadBs->progRefLevel >= 0) {
    754       self->progRefLevel = pThreadBs->progRefLevel;
    755     }
    756 
    757     /* SCE, CPE and LFE */
    758     for (ch = 0; ch < validChannels; ch++) {
    759       int mapedChannel = channelMapping[ch];
    760 
    761       if ( ((exclMask & (1<<mapedChannel)) == 0)
    762         && ( (drcPayloadType == MPEG_DRC_EXT_DATA)
    763           || ((drcPayloadType == DVB_DRC_ANC_DATA) && self->params.applyHeavyCompression)
    764          ) ) {
    765         /* copy thread to channel */
    766         pAacDecoderStaticChannelInfo[ch]->drcData = pThreadBs->channelData;
    767       }
    768     }
    769     /* CCEs not supported by now */
    770   }
    771 
    772   return 0;
    773 }
    774 
    775 
    776 void aacDecoder_drcApply (
    777         HANDLE_AAC_DRC          self,
    778         void                   *pSbrDec,
    779         CAacDecoderChannelInfo *pAacDecoderChannelInfo,
    780         CDrcChannelData        *pDrcChData,
    781         int  ch,   /* needed only for SBR */
    782         int  aacFrameSize,
    783         int  bSbrPresent )
    784 {
    785   int band, top, bin, numBands;
    786   int bottom = 0;
    787   int modifyBins = 0;
    788 
    789   FIXP_DBL max_mantissa;
    790   INT max_exponent;
    791 
    792   FIXP_DBL norm_mantissa = FL2FXCONST_DBL(0.0f);
    793   INT  norm_exponent = 0;
    794 
    795   FIXP_DBL fact_mantissa[MAX_DRC_BANDS];
    796   INT  fact_exponent[MAX_DRC_BANDS];
    797 
    798   CDrcParams  *pParams = &self->params;
    799 
    800   FIXP_DBL    *pSpectralCoefficient  =  SPEC_LONG(pAacDecoderChannelInfo->pSpectralCoefficient);
    801   CIcsInfo    *pIcsInfo              = &pAacDecoderChannelInfo->icsInfo;
    802   SHORT       *pSpecScale            =  pAacDecoderChannelInfo->specScale;
    803 
    804   int winSeq = pIcsInfo->WindowSequence;
    805 
    806   /* Increment and check expiry counter */
    807   if ( (pParams->expiryFrame > 0)
    808     && (++pDrcChData->expiryCount > pParams->expiryFrame) )
    809   { /* The DRC data is too old, so delete it. */
    810     aacDecoder_drcInitChannelData( pDrcChData );
    811   }
    812 
    813   if (!self->enable) {
    814     sbrDecoder_drcDisable( (HANDLE_SBRDECODER)pSbrDec, ch );
    815     return;
    816   }
    817 
    818   numBands = pDrcChData->numBands;
    819   top = FDKmax(0, numBands-1);
    820 
    821   pDrcChData->bandTop[0] = fixMin(pDrcChData->bandTop[0], (aacFrameSize >> 2) - 1);
    822 
    823   /* If program reference normalization is done in the digital domain,
    824   modify factor to perform normalization.  prog_ref_level can
    825   alternatively be passed to the system for modification of the level in
    826   the analog domain.  Analog level modification avoids problems with
    827   reduced DAC SNR (if signal is attenuated) or clipping (if signal is
    828   boosted) */
    829 
    830   if (self->digitalNorm == 1)
    831   {
    832     /* 0.5^((targetRefLevel - progRefLevel)/24) */
    833     norm_mantissa = fLdPow(
    834             FL2FXCONST_DBL(-1.0), /* log2(0.5) */
    835             0,
    836             (FIXP_DBL)((INT)(FL2FXCONST_DBL(1.0f/24.0)>>3) * (INT)(pParams->targetRefLevel-self->progRefLevel)),
    837             3,
    838            &norm_exponent );
    839   }
    840   else {
    841     norm_mantissa = FL2FXCONST_DBL(0.5f);
    842     norm_exponent = 1;
    843   }
    844 
    845 
    846   /* calc scale factors */
    847   for (band = 0; band < numBands; band++)
    848   {
    849     UCHAR drcVal = pDrcChData->drcValue[band];
    850     top = fixMin((int)( (pDrcChData->bandTop[band]+1)<<2 ), aacFrameSize);
    851 
    852     fact_mantissa[band] = FL2FXCONST_DBL(0.5f);
    853     fact_exponent[band] = 1;
    854 
    855     if (  pParams->applyHeavyCompression
    856       && ((AACDEC_DRC_PAYLOAD_TYPE)pDrcChData->drcDataType == DVB_DRC_ANC_DATA) )
    857     {
    858       INT compressionFactorVal_e;
    859       int valX, valY;
    860 
    861       valX = drcVal >> 4;
    862       valY = drcVal & 0x0F;
    863 
    864       /* calculate the unscaled heavy compression factor.
    865          compressionFactor = 48.164 - 6.0206*valX - 0.4014*valY dB
    866          range: -48.166 dB to 48.164 dB */
    867       if ( drcVal != 0x7F ) {
    868         fact_mantissa[band] =
    869           fPowInt( FL2FXCONST_DBL(0.95483867181), /* -0.4014dB = 0.95483867181 */
    870                    0,
    871                    valY,
    872                   &compressionFactorVal_e );
    873 
    874         /* -0.0008dB (48.164 - 6.0206*8 = -0.0008) */
    875         fact_mantissa[band] = fMult(FL2FXCONST_DBL(0.99990790084), fact_mantissa[band]);
    876 
    877         fact_exponent[band] = DVB_COMPRESSION_SCALE - valX + compressionFactorVal_e;
    878       }
    879     } else
    880     if ((AACDEC_DRC_PAYLOAD_TYPE)pDrcChData->drcDataType == MPEG_DRC_EXT_DATA)
    881     {
    882     /* apply the scaled dynamic range control words to factor.
    883      * if scaling drc_cut (or drc_boost), or control word drc_mantissa is 0
    884      * then there is no dynamic range compression
    885      *
    886      * if pDrcChData->drcSgn[band] is
    887      *  1 then gain is < 1 :  factor = 2^(-self->cut   * pDrcChData->drcMag[band] / 24)
    888      *  0 then gain is > 1 :  factor = 2^( self->boost * pDrcChData->drcMag[band] / 24)
    889      */
    890 
    891     if ((drcVal&0x7F) > 0) {
    892       FIXP_DBL tParamVal = (drcVal & 0x80) ? -pParams->cut : pParams->boost;
    893 
    894       fact_mantissa[band] =
    895         f2Pow( (FIXP_DBL)((INT)fMult(FL2FXCONST_DBL(1.0f/192.0f), tParamVal) * (drcVal&0x7F)),
    896                  3+DRC_PARAM_SCALE,
    897                 &fact_exponent[band] );
    898     }
    899     }
    900 
    901     fact_mantissa[band]  = fMult(fact_mantissa[band], norm_mantissa);
    902     fact_exponent[band] += norm_exponent;
    903 
    904 
    905     bottom = top;
    906 
    907   }  /* end loop over bands */
    908 
    909 
    910   /* normalizations */
    911   {
    912     int res;
    913 
    914     max_mantissa = FL2FXCONST_DBL(0.0f);
    915     max_exponent = 0;
    916     for (band = 0; band < numBands; band++) {
    917       max_mantissa = fixMax(max_mantissa, fact_mantissa[band]);
    918       max_exponent = fixMax(max_exponent, fact_exponent[band]);
    919     }
    920 
    921     /* left shift factors to gain accurancy */
    922     res = CntLeadingZeros(max_mantissa) - 1;
    923 
    924     /* above topmost DRC band gain factor is 1 */
    925     if (((pDrcChData->bandTop[numBands-1]+1)<<2) < aacFrameSize) res = 0;
    926 
    927     if (res > 0) {
    928       res = fixMin(res, max_exponent);
    929       max_exponent -= res;
    930 
    931       for (band = 0; band < numBands; band++) {
    932         fact_mantissa[band] <<= res;
    933         fact_exponent[band]  -= res;
    934       }
    935     }
    936 
    937     /* normalize magnitudes to one scale factor */
    938     for (band = 0; band < numBands; band++) {
    939       if (fact_exponent[band] < max_exponent) {
    940         fact_mantissa[band] >>= max_exponent - fact_exponent[band];
    941       }
    942       if (fact_mantissa[band] != FL2FXCONST_DBL(0.5f)) {
    943         modifyBins = 1;
    944       }
    945     }
    946     if (max_exponent != 1) {
    947       modifyBins = 1;
    948     }
    949   }
    950 
    951   /*  apply factor to spectral lines
    952    *  short blocks must take care that bands fall on
    953    *  block boundaries!
    954    */
    955   if (!bSbrPresent)
    956   {
    957     bottom = 0;
    958 
    959     if (!modifyBins) {
    960       /* We don't have to modify the spectral bins because the fractional part of all factors is 0.5.
    961          In order to keep accurancy we don't apply the factor but decrease the exponent instead. */
    962       max_exponent -= 1;
    963     } else
    964     {
    965       for (band = 0; band < numBands; band++)
    966       {
    967         top = fixMin((int)( (pDrcChData->bandTop[band]+1)<<2 ), aacFrameSize);   /* ... * DRC_BAND_MULT; */
    968 
    969         for (bin = bottom; bin < top; bin++) {
    970           pSpectralCoefficient[bin] = fMult(pSpectralCoefficient[bin], fact_mantissa[band]);
    971         }
    972 
    973         bottom = top;
    974       }
    975     }
    976 
    977     /* above topmost DRC band gain factor is 1 */
    978     if (max_exponent > 0) {
    979       for (bin = bottom; bin < aacFrameSize; bin+=1) {
    980         pSpectralCoefficient[bin] >>= max_exponent;
    981       }
    982     }
    983 
    984     /* adjust scaling */
    985     pSpecScale[0] += max_exponent;
    986 
    987     if (winSeq == EightShortSequence) {
    988       int win;
    989       for (win = 1; win < 8; win++) {
    990         pSpecScale[win] += max_exponent;
    991       }
    992     }
    993   }
    994   else {
    995     HANDLE_SBRDECODER hSbrDecoder = (HANDLE_SBRDECODER)pSbrDec;
    996     UINT numBands = pDrcChData->numBands;
    997 
    998     /* feed factors into SBR decoder for application in QMF domain. */
    999     sbrDecoder_drcFeedChannel (
   1000             hSbrDecoder,
   1001             ch,
   1002             numBands,
   1003             fact_mantissa,
   1004             max_exponent,
   1005             pDrcChData->drcInterpolationScheme,
   1006             winSeq,
   1007             pDrcChData->bandTop
   1008           );
   1009   }
   1010 
   1011   return;
   1012 }
   1013 
   1014 
   1015 /*
   1016  * Prepare DRC processing
   1017  */
   1018 int aacDecoder_drcProlog (
   1019         HANDLE_AAC_DRC  self,
   1020         HANDLE_FDK_BITSTREAM hBs,
   1021         CAacDecoderStaticChannelInfo *pAacDecoderStaticChannelInfo[],
   1022         UCHAR  pceInstanceTag,
   1023         UCHAR  channelMapping[], /* Channel mapping translating drcChannel index to canonical channel index */
   1024         int    validChannels )
   1025 {
   1026   int err = 0;
   1027 
   1028   if (self == NULL) {
   1029     return -1;
   1030   }
   1031 
   1032   if (!self->params.bsDelayEnable)
   1033   {
   1034     err = aacDecoder_drcExtractAndMap (
   1035             self,
   1036             hBs,
   1037             pAacDecoderStaticChannelInfo,
   1038             pceInstanceTag,
   1039             channelMapping,
   1040             validChannels );
   1041   }
   1042 
   1043   return err;
   1044 }
   1045 
   1046 
   1047 /*
   1048  * Finalize DRC processing
   1049  */
   1050 int aacDecoder_drcEpilog (
   1051         HANDLE_AAC_DRC  self,
   1052         HANDLE_FDK_BITSTREAM hBs,
   1053         CAacDecoderStaticChannelInfo *pAacDecoderStaticChannelInfo[],
   1054         UCHAR  pceInstanceTag,
   1055         UCHAR  channelMapping[], /* Channel mapping translating drcChannel index to canonical channel index */
   1056         int    validChannels )
   1057 {
   1058   int err = 0;
   1059 
   1060   if (self == NULL) {
   1061     return -1;
   1062   }
   1063 
   1064   if (self->params.bsDelayEnable)
   1065   {
   1066     err = aacDecoder_drcExtractAndMap (
   1067             self,
   1068             hBs,
   1069             pAacDecoderStaticChannelInfo,
   1070             pceInstanceTag,
   1071             channelMapping,
   1072             validChannels );
   1073   }
   1074 
   1075   return err;
   1076 }
   1077 
   1078