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