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