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 - 2015 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):   Manuel Jander
     87    Description:
     88 
     89 ******************************************************************************/
     90 
     91 #include "aacdecoder_lib.h"
     92 
     93 #include "aac_ram.h"
     94 #include "aacdecoder.h"
     95 #include "tpdec_lib.h"
     96 #include "FDK_core.h" /* FDK_tools version info */
     97 
     98 
     99  #include "sbrdecoder.h"
    100 
    101 
    102 
    103 
    104 #include "conceal.h"
    105 
    106  #include "aacdec_drc.h"
    107 
    108 
    109 
    110 /* Decoder library info */
    111 #define AACDECODER_LIB_VL0 2
    112 #define AACDECODER_LIB_VL1 5
    113 #define AACDECODER_LIB_VL2 17
    114 #define AACDECODER_LIB_TITLE "AAC Decoder Lib"
    115 #ifdef __ANDROID__
    116 #define AACDECODER_LIB_BUILD_DATE ""
    117 #define AACDECODER_LIB_BUILD_TIME ""
    118 #else
    119 #define AACDECODER_LIB_BUILD_DATE __DATE__
    120 #define AACDECODER_LIB_BUILD_TIME __TIME__
    121 #endif
    122 
    123 static AAC_DECODER_ERROR
    124 setConcealMethod ( const HANDLE_AACDECODER  self,
    125                    const INT                method );
    126 
    127 
    128 LINKSPEC_CPP AAC_DECODER_ERROR aacDecoder_GetFreeBytes ( const HANDLE_AACDECODER  self, UINT *pFreeBytes){
    129 
    130   /* reset free bytes */
    131   *pFreeBytes = 0;
    132 
    133   /* check handle */
    134   if(!self)
    135     return AAC_DEC_INVALID_HANDLE;
    136 
    137   /* return nr of free bytes */
    138   HANDLE_FDK_BITSTREAM hBs = transportDec_GetBitstream(self->hInput, 0);
    139   *pFreeBytes = FDKgetFreeBits(hBs) >> 3;
    140 
    141   /* success */
    142   return AAC_DEC_OK;
    143 }
    144 
    145 /**
    146  * Config Decoder using a CSAudioSpecificConfig struct.
    147  */
    148 static
    149 LINKSPEC_CPP AAC_DECODER_ERROR aacDecoder_Config(HANDLE_AACDECODER self, const CSAudioSpecificConfig *pAscStruct)
    150 {
    151   AAC_DECODER_ERROR err;
    152 
    153   /* Initialize AAC core decoder, and update self->streaminfo */
    154   err = CAacDecoder_Init(self, pAscStruct);
    155 
    156   return err;
    157 }
    158 
    159 LINKSPEC_CPP AAC_DECODER_ERROR aacDecoder_ConfigRaw (
    160         HANDLE_AACDECODER self,
    161         UCHAR *conf[],
    162         const UINT length[] )
    163 {
    164   AAC_DECODER_ERROR err = AAC_DEC_OK;
    165   TRANSPORTDEC_ERROR   errTp;
    166   UINT layer, nrOfLayers = self->nrOfLayers;
    167 
    168   for(layer = 0; layer < nrOfLayers; layer++){
    169     if(length[layer] > 0){
    170       errTp = transportDec_OutOfBandConfig(self->hInput, conf[layer], length[layer], layer);
    171       if (errTp != TRANSPORTDEC_OK) {
    172         switch (errTp) {
    173         case TRANSPORTDEC_NEED_TO_RESTART:
    174           err = AAC_DEC_NEED_TO_RESTART;
    175           break;
    176         case TRANSPORTDEC_UNSUPPORTED_FORMAT:
    177           err = AAC_DEC_UNSUPPORTED_FORMAT;
    178           break;
    179         default:
    180           err = AAC_DEC_UNKNOWN;
    181           break;
    182         }
    183         /* if baselayer is OK we continue decoding */
    184         if(layer >= 1){
    185           self->nrOfLayers = layer;
    186           err = AAC_DEC_OK;
    187         }
    188         break;
    189       }
    190     }
    191   }
    192 
    193   return err;
    194 }
    195 
    196 
    197 
    198 static INT aacDecoder_ConfigCallback(void *handle, const CSAudioSpecificConfig *pAscStruct)
    199 {
    200   HANDLE_AACDECODER self = (HANDLE_AACDECODER)handle;
    201   AAC_DECODER_ERROR err = AAC_DEC_OK;
    202   TRANSPORTDEC_ERROR errTp;
    203 
    204   {
    205     {
    206       err = aacDecoder_Config(self, pAscStruct);
    207     }
    208   }
    209   if (err == AAC_DEC_OK) {
    210     if ( self->flags & (AC_USAC|AC_RSVD50|AC_LD|AC_ELD)
    211       && CConcealment_GetDelay(&self->concealCommonData) > 0 )
    212     {
    213       /* Revert to error concealment method Noise Substitution.
    214          Because interpolation is not implemented for USAC/RSVD50 or
    215          the additional delay is unwanted for low delay codecs. */
    216       setConcealMethod(self, 1);
    217 #ifdef DEBUG
    218       FDKprintf("  Concealment method was reverted to 1 !\n");
    219 #endif
    220     }
    221     errTp = TRANSPORTDEC_OK;
    222   } else {
    223     if (IS_INIT_ERROR(err)) {
    224       errTp = TRANSPORTDEC_UNSUPPORTED_FORMAT;
    225     } /* Fatal errors */
    226     else if (err == AAC_DEC_NEED_TO_RESTART) {
    227       errTp = TRANSPORTDEC_NEED_TO_RESTART;
    228     } else {
    229       errTp = TRANSPORTDEC_UNKOWN_ERROR;
    230     }
    231   }
    232 
    233   return errTp;
    234 }
    235 
    236 
    237 
    238 LINKSPEC_CPP AAC_DECODER_ERROR
    239 aacDecoder_AncDataInit ( HANDLE_AACDECODER self,
    240                          UCHAR *buffer,
    241                          int size )
    242 {
    243   CAncData *ancData = &self->ancData;
    244 
    245   return CAacDecoder_AncDataInit(ancData, buffer, size);
    246 }
    247 
    248 
    249 LINKSPEC_CPP AAC_DECODER_ERROR
    250 aacDecoder_AncDataGet ( HANDLE_AACDECODER self,
    251                         int     index,
    252                         UCHAR **ptr,
    253                         int    *size )
    254 {
    255   CAncData *ancData = &self->ancData;
    256 
    257   return CAacDecoder_AncDataGet(ancData, index, ptr, size);
    258 }
    259 
    260 
    261 static AAC_DECODER_ERROR
    262 setConcealMethod ( const HANDLE_AACDECODER  self,   /*!< Handle of the decoder instance */
    263                    const INT                method )
    264 {
    265   AAC_DECODER_ERROR errorStatus = AAC_DEC_OK;
    266   CConcealParams  *pConcealData = NULL;
    267   HANDLE_SBRDECODER hSbrDec = NULL;
    268   HANDLE_AAC_DRC hDrcInfo = NULL;
    269   HANDLE_PCM_DOWNMIX hPcmDmx = NULL;
    270   CConcealmentMethod backupMethod = ConcealMethodNone;
    271   int backupDelay = 0;
    272   int bsDelay = 0;
    273 
    274   /* check decoder handle */
    275   if (self != NULL) {
    276     pConcealData = &self->concealCommonData;
    277     hSbrDec = self->hSbrDecoder;
    278     hDrcInfo = self->hDrcInfo;
    279     hPcmDmx = self->hPcmUtils;
    280   }
    281 
    282 
    283   /* Get current method/delay */
    284   backupMethod = CConcealment_GetMethod(pConcealData);
    285   backupDelay  = CConcealment_GetDelay(pConcealData);
    286 
    287   /* Be sure to set AAC and SBR concealment method simultaneously! */
    288   errorStatus =
    289     CConcealment_SetParams(
    290       pConcealData,
    291       (int)method,                         // concealMethod
    292       AACDEC_CONCEAL_PARAM_NOT_SPECIFIED,  // concealFadeOutSlope
    293       AACDEC_CONCEAL_PARAM_NOT_SPECIFIED,  // concealFadeInSlope
    294       AACDEC_CONCEAL_PARAM_NOT_SPECIFIED,  // concealMuteRelease
    295       AACDEC_CONCEAL_PARAM_NOT_SPECIFIED   // concealComfNoiseLevel
    296     );
    297   if ( (errorStatus != AAC_DEC_OK)
    298     && (errorStatus != AAC_DEC_INVALID_HANDLE) ) {
    299     goto bail;
    300   }
    301 
    302   /* Get new delay */
    303   bsDelay = CConcealment_GetDelay(pConcealData);
    304 
    305   {
    306     SBR_ERROR sbrErr = SBRDEC_OK;
    307 
    308     /* set SBR bitstream delay */
    309     sbrErr = sbrDecoder_SetParam (
    310       hSbrDec,
    311       SBR_SYSTEM_BITSTREAM_DELAY,
    312       bsDelay
    313     );
    314 
    315     switch (sbrErr) {
    316     case SBRDEC_OK:
    317     case SBRDEC_NOT_INITIALIZED:
    318       if (self != NULL) {
    319         /* save the param value and set later
    320            (when SBR has been initialized) */
    321         self->sbrParams.bsDelay = bsDelay;
    322       }
    323       break;
    324     default:
    325       errorStatus = AAC_DEC_SET_PARAM_FAIL;
    326       goto bail;
    327     }
    328   }
    329 
    330   errorStatus =
    331     aacDecoder_drcSetParam (
    332       hDrcInfo,
    333       DRC_BS_DELAY,
    334       bsDelay
    335     );
    336   if ( (errorStatus != AAC_DEC_OK)
    337     && (errorStatus != AAC_DEC_INVALID_HANDLE) ) {
    338     goto bail;
    339   }
    340 
    341   if (errorStatus == AAC_DEC_OK) {
    342     PCMDMX_ERROR err =
    343       pcmDmx_SetParam (
    344         hPcmDmx,
    345         DMX_BS_DATA_DELAY,
    346         bsDelay
    347       );
    348     switch (err) {
    349     case PCMDMX_INVALID_HANDLE:
    350       errorStatus = AAC_DEC_INVALID_HANDLE;
    351     case PCMDMX_OK:
    352       break;
    353     default:
    354       errorStatus = AAC_DEC_SET_PARAM_FAIL;
    355       goto bail;
    356     }
    357   }
    358 
    359 
    360 bail:
    361   if ( (errorStatus != AAC_DEC_OK)
    362     && (errorStatus != AAC_DEC_INVALID_HANDLE) )
    363   {
    364     /* Revert to the initial state */
    365     CConcealment_SetParams (
    366         pConcealData,
    367         (int)backupMethod,
    368         AACDEC_CONCEAL_PARAM_NOT_SPECIFIED,
    369         AACDEC_CONCEAL_PARAM_NOT_SPECIFIED,
    370         AACDEC_CONCEAL_PARAM_NOT_SPECIFIED,
    371         AACDEC_CONCEAL_PARAM_NOT_SPECIFIED
    372       );
    373     /* Revert SBR bitstream delay */
    374     sbrDecoder_SetParam (
    375         hSbrDec,
    376         SBR_SYSTEM_BITSTREAM_DELAY,
    377         backupDelay
    378       );
    379     /* Revert DRC bitstream delay */
    380     aacDecoder_drcSetParam (
    381         hDrcInfo,
    382         DRC_BS_DELAY,
    383         backupDelay
    384       );
    385     /* Revert PCM mixdown bitstream delay */
    386     pcmDmx_SetParam (
    387         hPcmDmx,
    388         DMX_BS_DATA_DELAY,
    389         backupDelay
    390       );
    391   }
    392 
    393   return errorStatus;
    394 }
    395 
    396 
    397 LINKSPEC_CPP AAC_DECODER_ERROR
    398 aacDecoder_SetParam ( const HANDLE_AACDECODER  self,   /*!< Handle of the decoder instance */
    399                       const AACDEC_PARAM       param,  /*!< Parameter to set               */
    400                       const INT                value)  /*!< Parameter valued               */
    401 {
    402   AAC_DECODER_ERROR errorStatus = AAC_DEC_OK;
    403   CConcealParams  *pConcealData = NULL;
    404   HANDLE_AAC_DRC hDrcInfo = NULL;
    405   HANDLE_PCM_DOWNMIX hPcmDmx = NULL;
    406   TDLimiterPtr hPcmTdl = NULL;
    407 
    408   /* check decoder handle */
    409   if (self != NULL) {
    410     pConcealData = &self->concealCommonData;
    411     hDrcInfo = self->hDrcInfo;
    412     hPcmDmx = self->hPcmUtils;
    413     hPcmTdl = self->hLimiter;
    414   } else {
    415     errorStatus = AAC_DEC_INVALID_HANDLE;
    416   }
    417 
    418   /* configure the subsystems */
    419   switch (param)
    420   {
    421   case AAC_PCM_OUTPUT_INTERLEAVED:
    422     if (value < 0 || value > 1) {
    423       return AAC_DEC_SET_PARAM_FAIL;
    424     }
    425     if (self == NULL) {
    426       return AAC_DEC_INVALID_HANDLE;
    427     }
    428     self->outputInterleaved = value;
    429     break;
    430 
    431   case AAC_PCM_MIN_OUTPUT_CHANNELS:
    432     if (value < -1 || value > (8)) {
    433       return AAC_DEC_SET_PARAM_FAIL;
    434     }
    435     {
    436       PCMDMX_ERROR err;
    437 
    438       err = pcmDmx_SetParam (
    439               hPcmDmx,
    440               MIN_NUMBER_OF_OUTPUT_CHANNELS,
    441               value );
    442 
    443       switch (err) {
    444       case PCMDMX_OK:
    445         break;
    446       case PCMDMX_INVALID_HANDLE:
    447         return AAC_DEC_INVALID_HANDLE;
    448       default:
    449         return AAC_DEC_SET_PARAM_FAIL;
    450       }
    451     }
    452     break;
    453 
    454   case AAC_PCM_MAX_OUTPUT_CHANNELS:
    455     if (value < -1 || value > (8)) {
    456       return AAC_DEC_SET_PARAM_FAIL;
    457     }
    458     {
    459       PCMDMX_ERROR err;
    460 
    461       err = pcmDmx_SetParam (
    462               hPcmDmx,
    463               MAX_NUMBER_OF_OUTPUT_CHANNELS,
    464               value );
    465 
    466       switch (err) {
    467       case PCMDMX_OK:
    468         break;
    469       case PCMDMX_INVALID_HANDLE:
    470         return AAC_DEC_INVALID_HANDLE;
    471       default:
    472         return AAC_DEC_SET_PARAM_FAIL;
    473       }
    474     }
    475     break;
    476 
    477   case AAC_PCM_DUAL_CHANNEL_OUTPUT_MODE:
    478     {
    479       PCMDMX_ERROR err;
    480 
    481       err = pcmDmx_SetParam (
    482               hPcmDmx,
    483               DMX_DUAL_CHANNEL_MODE,
    484               value );
    485 
    486       switch (err) {
    487       case PCMDMX_OK:
    488         break;
    489       case PCMDMX_INVALID_HANDLE:
    490         return AAC_DEC_INVALID_HANDLE;
    491       default:
    492         return AAC_DEC_SET_PARAM_FAIL;
    493       }
    494     }
    495     break;
    496 
    497 
    498   case AAC_PCM_LIMITER_ENABLE:
    499     if (value < -1 || value > 1) {
    500       return AAC_DEC_SET_PARAM_FAIL;
    501     }
    502     if (self == NULL) {
    503       return AAC_DEC_INVALID_HANDLE;
    504     }
    505     self->limiterEnableUser = value;
    506     break;
    507 
    508   case AAC_PCM_LIMITER_ATTACK_TIME:
    509     if (value <= 0) {  /* module function converts value to unsigned */
    510       return AAC_DEC_SET_PARAM_FAIL;
    511     }
    512     switch (setLimiterAttack(hPcmTdl, value)) {
    513     case TDLIMIT_OK:
    514       break;
    515     case TDLIMIT_INVALID_HANDLE:
    516       return AAC_DEC_INVALID_HANDLE;
    517     case TDLIMIT_INVALID_PARAMETER:
    518     default:
    519       return AAC_DEC_SET_PARAM_FAIL;
    520     }
    521     break;
    522 
    523   case AAC_PCM_LIMITER_RELEAS_TIME:
    524     if (value <= 0) {  /* module function converts value to unsigned */
    525       return AAC_DEC_SET_PARAM_FAIL;
    526     }
    527     switch (setLimiterRelease(hPcmTdl, value)) {
    528     case TDLIMIT_OK:
    529       break;
    530     case TDLIMIT_INVALID_HANDLE:
    531       return AAC_DEC_INVALID_HANDLE;
    532     case TDLIMIT_INVALID_PARAMETER:
    533     default:
    534       return AAC_DEC_SET_PARAM_FAIL;
    535     }
    536     break;
    537 
    538   case AAC_PCM_OUTPUT_CHANNEL_MAPPING:
    539     switch (value) {
    540       case 0:
    541         if (self != NULL) {
    542           self->channelOutputMapping = channelMappingTablePassthrough;
    543         }
    544         break;
    545       case 1:
    546         if (self != NULL) {
    547           self->channelOutputMapping = channelMappingTableWAV;
    548         }
    549         break;
    550       default:
    551         errorStatus = AAC_DEC_SET_PARAM_FAIL;
    552         break;
    553     }
    554     break;
    555 
    556 
    557   case AAC_QMF_LOWPOWER:
    558     if (value < -1 || value > 1) {
    559       return AAC_DEC_SET_PARAM_FAIL;
    560     }
    561     if (self == NULL) {
    562       return AAC_DEC_INVALID_HANDLE;
    563     }
    564 
    565     /**
    566      * Set QMF mode (might be overriden)
    567      *  0:HQ (complex)
    568      *  1:LP (partially complex)
    569      */
    570     self->qmfModeUser = (QMF_MODE)value;
    571     break;
    572 
    573 
    574   case AAC_DRC_ATTENUATION_FACTOR:
    575     /* DRC compression factor (where 0 is no and 127 is max compression) */
    576     errorStatus =
    577       aacDecoder_drcSetParam (
    578         hDrcInfo,
    579         DRC_CUT_SCALE,
    580         value
    581       );
    582     break;
    583 
    584   case AAC_DRC_BOOST_FACTOR:
    585     /* DRC boost factor (where 0 is no and 127 is max boost) */
    586     errorStatus =
    587       aacDecoder_drcSetParam (
    588         hDrcInfo,
    589         DRC_BOOST_SCALE,
    590         value
    591       );
    592     break;
    593 
    594   case AAC_DRC_REFERENCE_LEVEL:
    595     /* DRC reference level quantized in 0.25dB steps using values [0..127] it is '-' for analog scaling */
    596     errorStatus =
    597       aacDecoder_drcSetParam (
    598         hDrcInfo,
    599         TARGET_REF_LEVEL,
    600         value
    601       );
    602     break;
    603 
    604   case AAC_DRC_HEAVY_COMPRESSION:
    605     /* Don't need to overwrite cut/boost values */
    606     errorStatus =
    607       aacDecoder_drcSetParam (
    608         hDrcInfo,
    609         APPLY_HEAVY_COMPRESSION,
    610         value
    611       );
    612     break;
    613 
    614 
    615   case AAC_TPDEC_CLEAR_BUFFER:
    616     transportDec_SetParam(self->hInput, TPDEC_PARAM_RESET, 1);
    617     self->streamInfo.numLostAccessUnits = 0;
    618     self->streamInfo.numBadBytes = 0;
    619     self->streamInfo.numTotalBytes = 0;
    620     /* aacDecoder_SignalInterruption(self); */
    621     break;
    622 
    623   case AAC_CONCEAL_METHOD:
    624     /* Changing the concealment method can introduce additional bitstream delay. And
    625        that in turn affects sub libraries and modules which makes the whole thing quite
    626        complex.  So the complete changing routine is packed into a helper function which
    627        keeps all modules and libs in a consistent state even in the case an error occures. */
    628     errorStatus = setConcealMethod ( self, value );
    629     break;
    630 
    631   default:
    632     return AAC_DEC_SET_PARAM_FAIL;
    633   }  /* switch(param) */
    634 
    635   return (errorStatus);
    636 }
    637 
    638 
    639 LINKSPEC_CPP HANDLE_AACDECODER aacDecoder_Open(TRANSPORT_TYPE transportFmt, UINT nrOfLayers)
    640 {
    641   AAC_DECODER_INSTANCE *aacDec = NULL;
    642   HANDLE_TRANSPORTDEC pIn;
    643   int err = 0;
    644 
    645   /* Allocate transport layer struct. */
    646   pIn = transportDec_Open(transportFmt, TP_FLAG_MPEG4);
    647   if (pIn == NULL) {
    648     return NULL;
    649   }
    650 
    651   transportDec_SetParam(pIn, TPDEC_PARAM_IGNORE_BUFFERFULLNESS, 1);
    652 
    653   /* Allocate AAC decoder core struct. */
    654   aacDec = CAacDecoder_Open(transportFmt);
    655 
    656   if (aacDec == NULL) {
    657     transportDec_Close(&pIn);
    658     goto bail;
    659   }
    660   aacDec->hInput = pIn;
    661 
    662   aacDec->nrOfLayers = nrOfLayers;
    663 
    664   aacDec->channelOutputMapping = channelMappingTableWAV;
    665 
    666   /* Register Config Update callback. */
    667   transportDec_RegisterAscCallback(pIn, aacDecoder_ConfigCallback, (void*)aacDec);
    668 
    669   /* open SBR decoder */
    670   if ( SBRDEC_OK != sbrDecoder_Open ( &aacDec->hSbrDecoder )) {
    671     err = -1;
    672     goto bail;
    673   }
    674   aacDec->qmfModeUser = NOT_DEFINED;
    675   transportDec_RegisterSbrCallback(aacDec->hInput, (cbSbr_t)sbrDecoder_Header, (void*)aacDec->hSbrDecoder);
    676 
    677 
    678   pcmDmx_Open( &aacDec->hPcmUtils );
    679   if (aacDec->hPcmUtils == NULL) {
    680     err = -1;
    681     goto bail;
    682   }
    683 
    684   aacDec->hLimiter = createLimiter(TDL_ATTACK_DEFAULT_MS, TDL_RELEASE_DEFAULT_MS, SAMPLE_MAX, (8), 96000);
    685   if (NULL == aacDec->hLimiter) {
    686     err = -1;
    687     goto bail;
    688   }
    689   aacDec->limiterEnableUser = (UCHAR)-1;
    690   aacDec->limiterEnableCurr = 0;
    691 
    692 
    693 
    694   /* Assure that all modules have same delay */
    695   if ( setConcealMethod(aacDec, CConcealment_GetMethod(&aacDec->concealCommonData)) ) {
    696     err = -1;
    697     goto bail;
    698   }
    699 
    700 bail:
    701   if (err == -1) {
    702     aacDecoder_Close(aacDec);
    703     aacDec = NULL;
    704   }
    705   return aacDec;
    706 }
    707 
    708 LINKSPEC_CPP AAC_DECODER_ERROR aacDecoder_Fill(
    709         HANDLE_AACDECODER   self,
    710         UCHAR              *pBuffer[],
    711         const UINT          bufferSize[],
    712         UINT               *pBytesValid
    713         )
    714 {
    715   TRANSPORTDEC_ERROR tpErr;
    716   /* loop counter for layers; if not TT_MP4_RAWPACKETS used as index for only
    717      available layer                                                           */
    718   INT layer      = 0;
    719   INT nrOfLayers = self->nrOfLayers;
    720 
    721   {
    722     for (layer = 0; layer < nrOfLayers; layer++){
    723       {
    724         tpErr = transportDec_FillData( self->hInput, pBuffer[layer], bufferSize[layer], &pBytesValid[layer], layer );
    725         if (tpErr != TRANSPORTDEC_OK) {
    726           return AAC_DEC_UNKNOWN;  /* Must be an internal error */
    727         }
    728       }
    729     }
    730   }
    731 
    732   return AAC_DEC_OK;
    733 }
    734 
    735 
    736 static void aacDecoder_SignalInterruption(HANDLE_AACDECODER self)
    737 {
    738   CAacDecoder_SignalInterruption(self);
    739 
    740   if ( self->hSbrDecoder != NULL ) {
    741     sbrDecoder_SetParam(self->hSbrDecoder, SBR_BS_INTERRUPTION, 0);
    742   }
    743 }
    744 
    745 static void aacDecoder_UpdateBitStreamCounters(CStreamInfo *pSi, HANDLE_FDK_BITSTREAM hBs, int nBits, AAC_DECODER_ERROR ErrorStatus)
    746 {
    747   /* calculate bit difference (amount of bits moved forward) */
    748   nBits = nBits - FDKgetValidBits(hBs);
    749 
    750   /* Note: The amount of bits consumed might become negative when parsing a
    751      bit stream with several sub frames, and we find out at the last sub frame
    752      that the total frame length does not match the sum of sub frame length.
    753      If this happens, the transport decoder might want to rewind to the supposed
    754      ending of the transport frame, and this position might be before the last
    755      access unit beginning. */
    756 
    757   /* Calc bitrate. */
    758   if (pSi->frameSize > 0) {
    759     pSi->bitRate = (nBits * pSi->sampleRate)/pSi->frameSize;
    760   }
    761 
    762   /* bit/byte counters */
    763   {
    764     int nBytes;
    765 
    766     nBytes = nBits>>3;
    767     pSi->numTotalBytes += nBytes;
    768     if (IS_OUTPUT_VALID(ErrorStatus)) {
    769       pSi->numTotalAccessUnits++;
    770     }
    771     if (IS_DECODE_ERROR(ErrorStatus)) {
    772       pSi->numBadBytes += nBytes;
    773       pSi->numBadAccessUnits++;
    774     }
    775   }
    776 }
    777 
    778 static INT aacDecoder_EstimateNumberOfLostFrames(HANDLE_AACDECODER self)
    779 {
    780   INT n;
    781 
    782   transportDec_GetMissingAccessUnitCount( &n, self->hInput);
    783 
    784   return n;
    785 }
    786 
    787 LINKSPEC_CPP AAC_DECODER_ERROR aacDecoder_DecodeFrame(
    788         HANDLE_AACDECODER  self,
    789         INT_PCM           *pTimeData_extern,
    790         const INT          timeDataSize_extern,
    791         const UINT         flags)
    792 {
    793     AAC_DECODER_ERROR ErrorStatus;
    794     INT layer;
    795     INT nBits;
    796     INT interleaved = self->outputInterleaved;
    797     HANDLE_FDK_BITSTREAM hBs;
    798     int fTpInterruption = 0;  /* Transport originated interruption detection. */
    799     int fTpConceal = 0;       /* Transport originated concealment. */
    800     INT_PCM *pTimeData = NULL;
    801     INT timeDataSize = 0;
    802 
    803 
    804     if (self == NULL) {
    805       return AAC_DEC_INVALID_HANDLE;
    806     }
    807 
    808     pTimeData = self->pcmOutputBuffer;
    809     timeDataSize = sizeof(self->pcmOutputBuffer)/sizeof(*self->pcmOutputBuffer);
    810 
    811     if (flags & AACDEC_INTR) {
    812       self->streamInfo.numLostAccessUnits = 0;
    813     }
    814 
    815     hBs = transportDec_GetBitstream(self->hInput, 0);
    816 
    817     /* Get current bits position for bitrate calculation. */
    818     nBits = FDKgetValidBits(hBs);
    819     if (! (flags & (AACDEC_CONCEAL | AACDEC_FLUSH) ) )
    820     {
    821       TRANSPORTDEC_ERROR err;
    822 
    823       for(layer = 0; layer < self->nrOfLayers; layer++)
    824       {
    825         err = transportDec_ReadAccessUnit(self->hInput, layer);
    826         if (err != TRANSPORTDEC_OK) {
    827           switch (err) {
    828           case TRANSPORTDEC_NOT_ENOUGH_BITS:
    829             ErrorStatus = AAC_DEC_NOT_ENOUGH_BITS;
    830             goto bail;
    831           case TRANSPORTDEC_SYNC_ERROR:
    832             self->streamInfo.numLostAccessUnits = aacDecoder_EstimateNumberOfLostFrames(self);
    833             fTpInterruption = 1;
    834             break;
    835           case TRANSPORTDEC_NEED_TO_RESTART:
    836             ErrorStatus = AAC_DEC_NEED_TO_RESTART;
    837             goto bail;
    838           case TRANSPORTDEC_CRC_ERROR:
    839             fTpConceal = 1;
    840             break;
    841           default:
    842             ErrorStatus = AAC_DEC_UNKNOWN;
    843             goto bail;
    844           }
    845         }
    846       }
    847     } else {
    848       if (self->streamInfo.numLostAccessUnits > 0) {
    849         self->streamInfo.numLostAccessUnits--;
    850       }
    851     }
    852 
    853     /* Signal bit stream interruption to other modules if required. */
    854     if ( fTpInterruption || (flags & (AACDEC_INTR|AACDEC_CLRHIST)) )
    855     {
    856       sbrDecoder_SetParam(self->hSbrDecoder, SBR_CLEAR_HISTORY, (flags&AACDEC_CLRHIST));
    857       aacDecoder_SignalInterruption(self);
    858       if ( ! (flags & AACDEC_INTR) ) {
    859         ErrorStatus = AAC_DEC_TRANSPORT_SYNC_ERROR;
    860         goto bail;
    861       }
    862     }
    863 
    864     /* Empty bit buffer in case of flush request. */
    865     if (flags & AACDEC_FLUSH)
    866     {
    867       transportDec_SetParam(self->hInput, TPDEC_PARAM_RESET, 1);
    868       self->streamInfo.numLostAccessUnits = 0;
    869       self->streamInfo.numBadBytes = 0;
    870       self->streamInfo.numTotalBytes = 0;
    871     }
    872     /* Reset the output delay field. The modules will add their figures one after another. */
    873     self->streamInfo.outputDelay = 0;
    874 
    875     if (self->limiterEnableUser==(UCHAR)-1) {
    876       /* Enbale limiter for all non-lowdelay AOT's. */
    877       self->limiterEnableCurr = ( self->flags & (AC_LD|AC_ELD) ) ? 0 : 1;
    878     }
    879     else {
    880       /* Use limiter configuration as requested. */
    881       self->limiterEnableCurr = self->limiterEnableUser;
    882     }
    883     /* reset limiter gain on a per frame basis */
    884     self->extGain[0] = FL2FXCONST_DBL(1.0f/(float)(1<<TDL_GAIN_SCALING));
    885 
    886 
    887     ErrorStatus = CAacDecoder_DecodeFrame(self,
    888                                           flags | (fTpConceal ? AACDEC_CONCEAL : 0),
    889                                           pTimeData,
    890                                           timeDataSize,
    891                                           interleaved);
    892 
    893     if (!(flags & (AACDEC_CONCEAL|AACDEC_FLUSH))) {
    894       TRANSPORTDEC_ERROR tpErr;
    895       tpErr = transportDec_EndAccessUnit(self->hInput);
    896       if (tpErr != TRANSPORTDEC_OK) {
    897         self->frameOK = 0;
    898       }
    899     }
    900 
    901     /* If the current pTimeData does not contain a valid signal, there nothing else we can do, so bail. */
    902     if ( ! IS_OUTPUT_VALID(ErrorStatus) ) {
    903       goto bail;
    904     }
    905 
    906     {
    907       /* Export data into streaminfo structure */
    908       self->streamInfo.sampleRate = self->streamInfo.aacSampleRate;
    909       self->streamInfo.frameSize  = self->streamInfo.aacSamplesPerFrame;
    910     }
    911     self->streamInfo.numChannels = self->streamInfo.aacNumChannels;
    912 
    913 
    914 
    915     CAacDecoder_SyncQmfMode(self);
    916 
    917 /* sbr decoder */
    918 
    919     if (ErrorStatus || (flags & AACDEC_CONCEAL) || self->pAacDecoderStaticChannelInfo[0]->concealmentInfo.concealState > ConcealState_FadeIn)
    920     {
    921       self->frameOK = 0;  /* if an error has occured do concealment in the SBR decoder too */
    922     }
    923 
    924     if (self->sbrEnabled)
    925     {
    926       SBR_ERROR sbrError = SBRDEC_OK;
    927       int chIdx, numCoreChannel = self->streamInfo.numChannels;
    928       int chOutMapIdx = ((self->chMapIndex==0) && (numCoreChannel<7)) ? numCoreChannel : self->chMapIndex;
    929 
    930       /* set params */
    931       sbrDecoder_SetParam ( self->hSbrDecoder,
    932                             SBR_SYSTEM_BITSTREAM_DELAY,
    933                             self->sbrParams.bsDelay);
    934       sbrDecoder_SetParam ( self->hSbrDecoder,
    935                             SBR_FLUSH_DATA,
    936                             (flags & AACDEC_FLUSH) );
    937 
    938       if ( self->streamInfo.aot == AOT_ER_AAC_ELD ) {
    939         /* Configure QMF */
    940         sbrDecoder_SetParam ( self->hSbrDecoder,
    941                               SBR_LD_QMF_TIME_ALIGN,
    942                               (self->flags & AC_LD_MPS) ? 1 : 0 );
    943       }
    944 
    945       {
    946         PCMDMX_ERROR dmxErr;
    947         INT  maxOutCh = 0;
    948 
    949         dmxErr = pcmDmx_GetParam(self->hPcmUtils, MAX_NUMBER_OF_OUTPUT_CHANNELS, &maxOutCh);
    950         if ( (dmxErr == PCMDMX_OK) && (maxOutCh == 1) ) {
    951           /* Disable PS processing if we have to create a mono output signal. */
    952           self->psPossible = 0;
    953         }
    954       }
    955 
    956 
    957       /* apply SBR processing */
    958       sbrError = sbrDecoder_Apply ( self->hSbrDecoder,
    959                                     pTimeData,
    960                                    &self->streamInfo.numChannels,
    961                                    &self->streamInfo.sampleRate,
    962                                     self->channelOutputMapping[chOutMapIdx],
    963                                     interleaved,
    964                                     self->frameOK,
    965                                    &self->psPossible);
    966 
    967 
    968      if (sbrError == SBRDEC_OK) {
    969        #define UPS_SCALE  2  /* Maximum upsampling factor is 4 (CELP+SBR) */
    970        FIXP_DBL  upsampleFactor = FL2FXCONST_DBL(1.0f/(1<<UPS_SCALE));
    971 
    972        /* Update data in streaminfo structure. Assume that the SBR upsampling factor is either 1 or 2 */
    973        self->flags |= AC_SBR_PRESENT;
    974        if (self->streamInfo.aacSampleRate != self->streamInfo.sampleRate) {
    975          if (self->streamInfo.frameSize == 768) {
    976            upsampleFactor = FL2FXCONST_DBL(8.0f/(3<<UPS_SCALE));
    977          } else {
    978            upsampleFactor = FL2FXCONST_DBL(2.0f/(1<<UPS_SCALE));
    979          }
    980        }
    981        /* Apply upsampling factor to both the core frame length and the core delay */
    982        self->streamInfo.frameSize    =       (INT)fMult((FIXP_DBL)self->streamInfo.aacSamplesPerFrame<<UPS_SCALE, upsampleFactor);
    983        self->streamInfo.outputDelay  = (UINT)(INT)fMult((FIXP_DBL)self->streamInfo.outputDelay<<UPS_SCALE, upsampleFactor);
    984        self->streamInfo.outputDelay += sbrDecoder_GetDelay( self->hSbrDecoder );
    985 
    986        if (self->psPossible) {
    987          self->flags |= AC_PS_PRESENT;
    988        }
    989        for (chIdx = numCoreChannel; chIdx < self->streamInfo.numChannels; chIdx+=1) {
    990          self->channelType[chIdx] = ACT_FRONT;
    991          self->channelIndices[chIdx] = chIdx;
    992        }
    993      }
    994    }
    995 
    996 
    997     {
    998     INT pcmLimiterScale = 0;
    999     PCMDMX_ERROR dmxErr = PCMDMX_OK;
   1000     if ( flags & (AACDEC_INTR | AACDEC_CLRHIST) ) {
   1001       /* delete data from the past (e.g. mixdown coeficients) */
   1002       pcmDmx_Reset( self->hPcmUtils, PCMDMX_RESET_BS_DATA );
   1003     }
   1004     /* do PCM post processing */
   1005     dmxErr = pcmDmx_ApplyFrame (
   1006             self->hPcmUtils,
   1007             pTimeData,
   1008             self->streamInfo.frameSize,
   1009            &self->streamInfo.numChannels,
   1010             interleaved,
   1011             self->channelType,
   1012             self->channelIndices,
   1013             self->channelOutputMapping,
   1014             (self->limiterEnableCurr) ? &pcmLimiterScale : NULL
   1015       );
   1016     if ( (ErrorStatus == AAC_DEC_OK)
   1017       && (dmxErr == PCMDMX_INVALID_MODE) ) {
   1018       /* Announce the framework that the current combination of channel configuration and downmix
   1019        * settings are not know to produce a predictable behavior and thus maybe produce strange output. */
   1020       ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
   1021     }
   1022 
   1023     if ( flags & AACDEC_CLRHIST ) {
   1024       /* Delete the delayed signal. */
   1025       resetLimiter(self->hLimiter);
   1026     }
   1027     if (self->limiterEnableCurr)
   1028     {
   1029       /* Set actual signal parameters */
   1030       setLimiterNChannels(self->hLimiter, self->streamInfo.numChannels);
   1031       setLimiterSampleRate(self->hLimiter, self->streamInfo.sampleRate);
   1032 
   1033       applyLimiter(
   1034               self->hLimiter,
   1035               pTimeData,
   1036               self->extGain,
   1037              &pcmLimiterScale,
   1038               1,
   1039               self->extGainDelay,
   1040               self->streamInfo.frameSize
   1041               );
   1042 
   1043       /* Announce the additional limiter output delay */
   1044       self->streamInfo.outputDelay += getLimiterDelay(self->hLimiter);
   1045     }
   1046     }
   1047 
   1048 
   1049     /* Signal interruption to take effect in next frame. */
   1050     if ( flags & AACDEC_FLUSH ) {
   1051       aacDecoder_SignalInterruption(self);
   1052     }
   1053 
   1054     /* Update externally visible copy of flags */
   1055     self->streamInfo.flags = self->flags;
   1056 
   1057 bail:
   1058 
   1059     /* Update Statistics */
   1060     aacDecoder_UpdateBitStreamCounters(&self->streamInfo, hBs, nBits, ErrorStatus);
   1061 
   1062     /* Check whether external output buffer is large enough. */
   1063     if (timeDataSize_extern < self->streamInfo.numChannels*self->streamInfo.frameSize) {
   1064       ErrorStatus = AAC_DEC_OUTPUT_BUFFER_TOO_SMALL;
   1065     }
   1066 
   1067     /* Update external output buffer. */
   1068     if ( IS_OUTPUT_VALID(ErrorStatus) ) {
   1069       FDKmemcpy(pTimeData_extern, pTimeData, self->streamInfo.numChannels*self->streamInfo.frameSize*sizeof(*pTimeData));
   1070     }
   1071     else {
   1072       FDKmemclear(pTimeData_extern, timeDataSize_extern*sizeof(*pTimeData_extern));
   1073     }
   1074 
   1075     return ErrorStatus;
   1076 }
   1077 
   1078 LINKSPEC_CPP void aacDecoder_Close ( HANDLE_AACDECODER self )
   1079 {
   1080   if (self == NULL)
   1081     return;
   1082 
   1083 
   1084   if (self->hLimiter != NULL) {
   1085     destroyLimiter(self->hLimiter);
   1086   }
   1087 
   1088   if (self->hPcmUtils != NULL) {
   1089     pcmDmx_Close( &self->hPcmUtils );
   1090   }
   1091 
   1092 
   1093 
   1094   if (self->hSbrDecoder != NULL) {
   1095     sbrDecoder_Close(&self->hSbrDecoder);
   1096   }
   1097 
   1098   if (self->hInput != NULL) {
   1099     transportDec_Close(&self->hInput);
   1100   }
   1101 
   1102   CAacDecoder_Close(self);
   1103 }
   1104 
   1105 
   1106 LINKSPEC_CPP CStreamInfo* aacDecoder_GetStreamInfo ( HANDLE_AACDECODER self )
   1107 {
   1108   return CAacDecoder_GetStreamInfo(self);
   1109 }
   1110 
   1111 LINKSPEC_CPP INT aacDecoder_GetLibInfo ( LIB_INFO *info )
   1112 {
   1113   int i;
   1114 
   1115   if (info == NULL) {
   1116     return -1;
   1117   }
   1118 
   1119   sbrDecoder_GetLibInfo( info );
   1120   transportDec_GetLibInfo( info );
   1121   FDK_toolsGetLibInfo( info );
   1122   pcmDmx_GetLibInfo( info );
   1123 
   1124   /* search for next free tab */
   1125   for (i = 0; i < FDK_MODULE_LAST; i++) {
   1126     if (info[i].module_id == FDK_NONE) break;
   1127   }
   1128   if (i == FDK_MODULE_LAST) {
   1129     return -1;
   1130   }
   1131   info += i;
   1132 
   1133   info->module_id = FDK_AACDEC;
   1134   /* build own library info */
   1135   info->version = LIB_VERSION(AACDECODER_LIB_VL0, AACDECODER_LIB_VL1, AACDECODER_LIB_VL2);
   1136   LIB_VERSION_STRING(info);
   1137   info->build_date = AACDECODER_LIB_BUILD_DATE;
   1138   info->build_time = AACDECODER_LIB_BUILD_TIME;
   1139   info->title = AACDECODER_LIB_TITLE;
   1140 
   1141   /* Set flags */
   1142   info->flags = 0
   1143       | CAPF_AAC_LC
   1144       | CAPF_ER_AAC_SCAL
   1145       | CAPF_AAC_VCB11
   1146       | CAPF_AAC_HCR
   1147       | CAPF_AAC_RVLC
   1148       | CAPF_ER_AAC_LD
   1149       | CAPF_ER_AAC_ELD
   1150       | CAPF_AAC_CONCEALMENT
   1151       | CAPF_AAC_DRC
   1152 
   1153       | CAPF_AAC_MPEG4
   1154 
   1155       | CAPF_AAC_DRM_BSFORMAT
   1156 
   1157       | CAPF_AAC_1024
   1158       | CAPF_AAC_960
   1159 
   1160       | CAPF_AAC_512
   1161 
   1162       | CAPF_AAC_480
   1163 
   1164       ;
   1165   /* End of flags */
   1166 
   1167   return 0;
   1168 }
   1169 
   1170 
   1171 
   1172 
   1173