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 /***************************  Fast MPEG AAC Audio Encoder  **********************
     85 
     86    Initial author:       M. Schug / A. Groeschel
     87    contents/description: fast aac coder functions
     88 
     89 ******************************************************************************/
     90 
     91 #include "aacenc.h"
     92 
     93 #include "bitenc.h"
     94 #include "interface.h"
     95 #include "psy_configuration.h"
     96 #include "psy_main.h"
     97 #include "qc_main.h"
     98 #include "bandwidth.h"
     99 #include "channel_map.h"
    100 #include "tns_func.h"
    101 #include "aacEnc_ram.h"
    102 
    103 #include "genericStds.h"
    104 
    105 
    106 
    107 
    108 #define MIN_BUFSIZE_PER_EFF_CHAN 6144
    109 
    110 static AAC_ENCODER_ERROR FDKaacEnc_InitCheckAncillary(INT bitRate,
    111                                                       INT framelength,
    112                                                       INT ancillaryRate,
    113                                                       INT *ancillaryBitsPerFrame,
    114                                                       INT sampleRate);
    115 
    116 INT FDKaacEnc_LimitBitrate(
    117         HANDLE_TRANSPORTENC hTpEnc,
    118         INT coreSamplingRate,
    119         INT frameLength,
    120         INT nChannels,
    121         INT nChannelsEff,
    122         INT bitRate,
    123         INT averageBits,
    124         INT *pAverageBitsPerFrame,
    125         INT bitrateMode,
    126         INT nSubFrames
    127         )
    128 {
    129   INT transportBits, prevBitRate, averageBitsPerFrame, shift = 0, iter=0;
    130 
    131   while ( (frameLength & ~((1<<(shift+1))-1)) == frameLength
    132     && (coreSamplingRate & ~((1<<(shift+1))-1)) == coreSamplingRate )
    133   {
    134     shift ++;
    135   }
    136 
    137   do {
    138     prevBitRate = bitRate;
    139      averageBitsPerFrame = (bitRate*(frameLength>>shift)) / (coreSamplingRate>>shift) / nSubFrames;
    140 
    141     if (pAverageBitsPerFrame != NULL) {
    142       *pAverageBitsPerFrame = averageBitsPerFrame;
    143     }
    144 
    145     if (hTpEnc != NULL) {
    146       transportBits = transportEnc_GetStaticBits(hTpEnc, averageBitsPerFrame);
    147     } else {
    148       /* Assume some worst case */
    149       transportBits = 208;
    150     }
    151 
    152     bitRate = FDKmax(bitRate, ((((40 * nChannels) + transportBits) * (coreSamplingRate)) / frameLength) );
    153     FDK_ASSERT(bitRate >= 0);
    154 
    155     bitRate = FDKmin(bitRate, ((nChannelsEff * MIN_BUFSIZE_PER_EFF_CHAN)*(coreSamplingRate>>shift)) / (frameLength>>shift)) ;
    156     FDK_ASSERT(bitRate >= 0);
    157 
    158   } while (prevBitRate != bitRate && iter++ < 3) ;
    159 
    160   return bitRate;
    161 }
    162 
    163 
    164 typedef struct
    165 {
    166   AACENC_BITRATE_MODE bitrateMode;
    167   int chanBitrate[2]; /* mono/stereo settings */
    168 } CONFIG_TAB_ENTRY_VBR;
    169 
    170 static const CONFIG_TAB_ENTRY_VBR configTabVBR[] = {
    171   {AACENC_BR_MODE_CBR,   {     0,     0}} ,
    172   {AACENC_BR_MODE_VBR_1, { 32000, 20000}} ,
    173   {AACENC_BR_MODE_VBR_2, { 40000, 32000}} ,
    174   {AACENC_BR_MODE_VBR_3, { 56000, 48000}} ,
    175   {AACENC_BR_MODE_VBR_4, { 72000, 64000}} ,
    176   {AACENC_BR_MODE_VBR_5, {112000, 96000}}
    177 };
    178 
    179 /*-----------------------------------------------------------------------------
    180 
    181      functionname: FDKaacEnc_GetVBRBitrate
    182      description:  Get VBR bitrate from vbr quality
    183      input params: int vbrQuality (VBR0, VBR1, VBR2)
    184                    channelMode
    185      returns:      vbr bitrate
    186 
    187  ------------------------------------------------------------------------------*/
    188 INT FDKaacEnc_GetVBRBitrate(INT bitrateMode, CHANNEL_MODE channelMode)
    189 {
    190   INT bitrate = 0;
    191   INT monoStereoMode = 0; /* default mono */
    192 
    193   if (FDKaacEnc_GetMonoStereoMode(channelMode)==EL_MODE_STEREO) {
    194       monoStereoMode = 1;
    195   }
    196 
    197   switch((AACENC_BITRATE_MODE)bitrateMode){
    198   case AACENC_BR_MODE_VBR_1:
    199   case AACENC_BR_MODE_VBR_2:
    200   case AACENC_BR_MODE_VBR_3:
    201   case AACENC_BR_MODE_VBR_4:
    202   case AACENC_BR_MODE_VBR_5:
    203     bitrate = configTabVBR[bitrateMode].chanBitrate[monoStereoMode];
    204     break;
    205   case AACENC_BR_MODE_INVALID:
    206   case AACENC_BR_MODE_CBR:
    207   case AACENC_BR_MODE_SFR:
    208   case AACENC_BR_MODE_FF:
    209   default:
    210     bitrate = 0;
    211     break;
    212   }
    213 
    214   /* convert channel bitrate to overall bitrate*/
    215   bitrate *= FDKaacEnc_GetChannelModeConfiguration(channelMode)->nChannelsEff;
    216 
    217   return bitrate;
    218 }
    219 
    220 /**
    221  * \brief  Convert encoder bitreservoir value for transport library.
    222  *
    223  * \param bitrateMode           Bitratemode used in current encoder instance. Se ::AACENC_BITRATE_MODE
    224  * \param bitresTotal           Encoder bitreservoir level in bits.
    225  *
    226  * \return  Corrected bitreservoir level used in transport library.
    227  */
    228 static INT FDKaacEnc_EncBitresToTpBitres(
    229         const AACENC_BITRATE_MODE bitrateMode,
    230         const INT                 bitresTotal
    231         )
    232 {
    233   INT transporBitreservoir = 0;
    234 
    235   switch (bitrateMode) {
    236     case AACENC_BR_MODE_CBR:
    237       transporBitreservoir = bitresTotal; /* encoder bitreservoir level */
    238       break;
    239     case AACENC_BR_MODE_VBR_1:
    240     case AACENC_BR_MODE_VBR_2:
    241     case AACENC_BR_MODE_VBR_3:
    242     case AACENC_BR_MODE_VBR_4:
    243     case AACENC_BR_MODE_VBR_5:
    244       transporBitreservoir = FDK_INT_MAX; /* signal variable bitrate */
    245       break;
    246     case AACENC_BR_MODE_FF:
    247     case AACENC_BR_MODE_SFR:
    248       transporBitreservoir = 0;           /* super framing and fixed framing */
    249       break;                              /* without bitreservoir signaling */
    250     default:
    251     case AACENC_BR_MODE_INVALID:
    252       transporBitreservoir = 0;           /* invalid configuration*/
    253       FDK_ASSERT(0);
    254   }
    255 
    256   return transporBitreservoir;
    257 }
    258 
    259 /*-----------------------------------------------------------------------------
    260 
    261      functionname: FDKaacEnc_AacInitDefaultConfig
    262      description:  gives reasonable default configuration
    263      returns:      ---
    264 
    265  ------------------------------------------------------------------------------*/
    266 void FDKaacEnc_AacInitDefaultConfig(AACENC_CONFIG *config)
    267 {
    268     /* make thepre initialization of the structs flexible */
    269     FDKmemclear(config, sizeof(AACENC_CONFIG));
    270 
    271     /* default ancillary */
    272     config->anc_Rate = 0;         /* no ancillary data */
    273     config->ancDataBitRate = 0;   /* no additional consumed bitrate */
    274 
    275     /* default configurations */
    276     config->bitRate         = -1;                   /* bitrate must be set*/
    277     config->averageBits     = -1;                   /* instead of bitrate/s we can configure bits/superframe */
    278     config->bitrateMode     = 0;
    279     config->bandWidth       = 0;                    /* get bandwidth from table */
    280     config->useTns          = TNS_ENABLE_MASK;      /* tns enabled completly */
    281     config->usePns          = 1;                    /* depending on channelBitrate this might be set to 0 later */
    282     config->useIS           = 1;                    /* Intensity Stereo Configuration */
    283     config->framelength     = -1;                   /* Framesize not configured */
    284     config->syntaxFlags     = 0;                    /* default syntax with no specialities */
    285     config->epConfig        = -1;                   /* no ER syntax -> no additional error protection */
    286     config->nSubFrames      = 1;                    /* default, no sub frames */
    287     config->channelOrder    = CH_ORDER_MPEG;        /* Use MPEG channel ordering. */
    288     config->channelMode     = MODE_UNKNOWN;
    289     config->minBitsPerFrame = -1;                   /* minum number of bits in each AU */
    290     config->maxBitsPerFrame = -1;                   /* minum number of bits in each AU */
    291     config->bitreservoir    = -1;                   /* default, uninitialized value */
    292 
    293     /* init tabs in fixpoint_math */
    294     InitLdInt();
    295     InitInvSqrtTab();
    296 }
    297 
    298 
    299 /*---------------------------------------------------------------------------
    300 
    301     functionname: FDKaacEnc_Open
    302     description:  allocate and initialize a new encoder instance
    303     returns:      error code
    304 
    305   ---------------------------------------------------------------------------*/
    306 AAC_ENCODER_ERROR FDKaacEnc_Open(HANDLE_AAC_ENC  *phAacEnc,
    307                                  const INT        nElements,
    308                                  const INT        nChannels,
    309                                  const INT        nSubFrames)
    310 {
    311   AAC_ENCODER_ERROR ErrorStatus;
    312   AAC_ENC           *hAacEnc = NULL;
    313   UCHAR             *dynamicRAM = NULL;
    314 
    315   if (phAacEnc==NULL) {
    316     return AAC_ENC_INVALID_HANDLE;
    317   }
    318 
    319   /* allocate encoder structure */
    320   hAacEnc = GetRam_aacEnc_AacEncoder();
    321   if (hAacEnc == NULL) {
    322     ErrorStatus = AAC_ENC_NO_MEMORY;
    323     goto bail;
    324   }
    325   FDKmemclear(hAacEnc, sizeof(AAC_ENC));
    326 
    327   hAacEnc->dynamic_RAM = GetAACdynamic_RAM();
    328   dynamicRAM = (UCHAR*)hAacEnc->dynamic_RAM;
    329 
    330   /* allocate the Psy aud Psy Out structure */
    331    ErrorStatus = FDKaacEnc_PsyNew(&hAacEnc->psyKernel,
    332                                   nElements,
    333                                   nChannels
    334                                  ,dynamicRAM
    335                                  );
    336    if (ErrorStatus != AAC_ENC_OK)
    337      goto bail;
    338 
    339    ErrorStatus = FDKaacEnc_PsyOutNew(hAacEnc->psyOut,
    340                                      nElements,
    341                                      nChannels,
    342                                      nSubFrames
    343                                     ,dynamicRAM
    344                                     );
    345    if (ErrorStatus != AAC_ENC_OK)
    346      goto bail;
    347 
    348   /* allocate the Q&C Out structure */
    349   ErrorStatus = FDKaacEnc_QCOutNew(hAacEnc->qcOut,
    350                                    nElements,
    351                                    nChannels,
    352                                    nSubFrames
    353                                   ,dynamicRAM
    354                                    );
    355   if (ErrorStatus != AAC_ENC_OK)
    356     goto bail;
    357 
    358   /* allocate the Q&C kernel */
    359   ErrorStatus = FDKaacEnc_QCNew(&hAacEnc->qcKernel,
    360                                  nElements
    361                                 ,dynamicRAM
    362                                 );
    363   if (ErrorStatus != AAC_ENC_OK)
    364     goto bail;
    365 
    366   hAacEnc->maxChannels = nChannels;
    367   hAacEnc->maxElements = nElements;
    368   hAacEnc->maxFrames   = nSubFrames;
    369 
    370 bail:
    371   *phAacEnc = hAacEnc;
    372   return ErrorStatus;
    373 }
    374 
    375 
    376 AAC_ENCODER_ERROR FDKaacEnc_Initialize(HANDLE_AAC_ENC      hAacEnc,
    377                                        AACENC_CONFIG      *config,     /* pre-initialized config struct */
    378                                        HANDLE_TRANSPORTENC hTpEnc,
    379                                        ULONG               initFlags)
    380 {
    381   AAC_ENCODER_ERROR ErrorStatus;
    382   INT psyBitrate, tnsMask; //INT profile = 1;
    383   CHANNEL_MAPPING   *cm = NULL;
    384 
    385   INT qmbfac, qbw;
    386   FIXP_DBL mbfac, bw_ratio;
    387   QC_INIT qcInit;
    388   INT averageBitsPerFrame = 0;
    389 
    390   if (config==NULL)
    391     return AAC_ENC_INVALID_HANDLE;
    392 
    393   /******************* sanity checks *******************/
    394 
    395   /* check config structure */
    396   if (config->nChannels  < 1 || config->nChannels > (8)) {
    397     return AAC_ENC_UNSUPPORTED_CHANNELCONFIG;
    398   }
    399 
    400   /* check sample rate */
    401   switch (config->sampleRate)
    402   {
    403     case 8000:
    404     case 11025:
    405     case 12000:
    406     case 16000:
    407     case 22050:
    408     case 24000:
    409     case 32000:
    410     case 44100:
    411     case 48000:
    412     case 64000:
    413     case 88200:
    414     case 96000:
    415       break;
    416     default:
    417       return AAC_ENC_UNSUPPORTED_SAMPLINGRATE;
    418   }
    419 
    420   /* bitrate has to be set */
    421   if (config->bitRate==-1) {
    422       return AAC_ENC_UNSUPPORTED_BITRATE;
    423   }
    424 
    425   /* check bit rate */
    426 
    427   if (FDKaacEnc_LimitBitrate(
    428           hTpEnc,
    429           config->sampleRate,
    430           config->framelength,
    431           config->nChannels,
    432           FDKaacEnc_GetChannelModeConfiguration(config->channelMode)->nChannelsEff,
    433           config->bitRate,
    434           config->averageBits,
    435          &averageBitsPerFrame,
    436           config->bitrateMode,
    437           config->nSubFrames
    438           ) != config->bitRate )
    439   {
    440     return AAC_ENC_UNSUPPORTED_BITRATE;
    441   }
    442 
    443   if (config->syntaxFlags & AC_ER_VCB11) {
    444       return AAC_ENC_UNSUPPORTED_ER_FORMAT;
    445   }
    446   if (config->syntaxFlags & AC_ER_HCR) {
    447       return AAC_ENC_UNSUPPORTED_ER_FORMAT;
    448   }
    449 
    450   /* check frame length */
    451   switch (config->framelength)
    452   {
    453     case 1024:
    454       if ( config->audioObjectType == AOT_ER_AAC_LD
    455         || config->audioObjectType == AOT_ER_AAC_ELD )
    456       {
    457         return AAC_ENC_INVALID_FRAME_LENGTH;
    458       }
    459       break;
    460     case 512:
    461     case 480:
    462       if ( config->audioObjectType != AOT_ER_AAC_LD
    463         && config->audioObjectType != AOT_ER_AAC_ELD )
    464       {
    465         return AAC_ENC_INVALID_FRAME_LENGTH;
    466       }
    467       break;
    468     default:
    469       return AAC_ENC_INVALID_FRAME_LENGTH;
    470   }
    471 
    472   if (config->anc_Rate != 0) {
    473 
    474      ErrorStatus = FDKaacEnc_InitCheckAncillary(config->bitRate,
    475                                                 config->framelength,
    476                                                 config->anc_Rate,
    477                                                &hAacEnc->ancillaryBitsPerFrame,
    478                                                 config->sampleRate);
    479      if (ErrorStatus != AAC_ENC_OK)
    480        goto bail;
    481 
    482 
    483      /* update estimated consumed bitrate */
    484      config->ancDataBitRate += ( (hAacEnc->ancillaryBitsPerFrame * config->sampleRate) / config->framelength );
    485 
    486   }
    487 
    488   /* maximal allowed DSE bytes in frame */
    489   {
    490   /* fixpoint calculation*/
    491   INT q_res, encBitrate, sc;
    492   FIXP_DBL tmp = fDivNorm(config->framelength, config->sampleRate, &q_res);
    493   encBitrate = (config->bitRate/*-config->ancDataBitRate*/)- (INT)(config->nChannels*8000);
    494   sc = CountLeadingBits(encBitrate);
    495   config->maxAncBytesPerAU = FDKmin( (256), FDKmax(0,(INT)(fMultDiv2(tmp, (FIXP_DBL)(encBitrate<<sc))>>(-q_res+sc-1+3))) );
    496   }
    497 
    498   /* bind config to hAacEnc->config */
    499   hAacEnc->config = config;
    500 
    501   /* set hAacEnc->bitrateMode */
    502   hAacEnc->bitrateMode = (AACENC_BITRATE_MODE)config->bitrateMode;
    503 
    504   hAacEnc->encoderMode = config->channelMode;
    505 
    506   ErrorStatus = FDKaacEnc_InitChannelMapping(hAacEnc->encoderMode, config->channelOrder, &hAacEnc->channelMapping);
    507   if (ErrorStatus != AAC_ENC_OK)
    508     goto bail;
    509 
    510   cm = &hAacEnc->channelMapping;
    511 
    512   ErrorStatus = FDKaacEnc_DetermineBandWidth(&hAacEnc->config->bandWidth,
    513                                              config->bandWidth,
    514                                              config->bitRate - config->ancDataBitRate,
    515                                              hAacEnc->bitrateMode,
    516                                              config->sampleRate,
    517                                              config->framelength,
    518                                              cm,
    519                                              hAacEnc->encoderMode);
    520   if (ErrorStatus != AAC_ENC_OK)
    521     goto bail;
    522 
    523   hAacEnc->bandwidth90dB = (INT)hAacEnc->config->bandWidth;
    524 
    525   tnsMask = config->useTns ? TNS_ENABLE_MASK : 0x0;
    526   psyBitrate = config->bitRate - config->ancDataBitRate;
    527 
    528   ErrorStatus = FDKaacEnc_psyInit(hAacEnc->psyKernel,
    529                                   hAacEnc->psyOut,
    530                                   hAacEnc->maxFrames,
    531                                   hAacEnc->maxChannels,
    532                                   config->audioObjectType,
    533                                   cm);
    534   if (ErrorStatus != AAC_ENC_OK)
    535     goto bail;
    536 
    537   ErrorStatus = FDKaacEnc_psyMainInit(hAacEnc->psyKernel,
    538                                       config->audioObjectType,
    539                                       cm,
    540                                       config->sampleRate,
    541                                       config->framelength,
    542                                       psyBitrate,
    543                                       tnsMask,
    544                                       hAacEnc->bandwidth90dB,
    545                                       config->usePns,
    546                                       config->useIS,
    547                                       config->syntaxFlags,
    548                                       initFlags);
    549   if (ErrorStatus != AAC_ENC_OK)
    550     goto bail;
    551 
    552   ErrorStatus = FDKaacEnc_QCOutInit(hAacEnc->qcOut, hAacEnc->maxFrames, cm);
    553   if (ErrorStatus != AAC_ENC_OK)
    554     goto bail;
    555 
    556 
    557 
    558   qcInit.channelMapping      = &hAacEnc->channelMapping;
    559   qcInit.sceCpe              = 0;
    560 
    561   if ((config->bitrateMode>=1) && (config->bitrateMode<=5)) {
    562       qcInit.averageBits     = (averageBitsPerFrame+7)&~7;
    563       qcInit.bitRes          = MIN_BUFSIZE_PER_EFF_CHAN*cm->nChannelsEff;
    564       qcInit.maxBits         = MIN_BUFSIZE_PER_EFF_CHAN*cm->nChannelsEff;
    565       qcInit.minBits         = 0;
    566   }
    567   else
    568   {
    569       int maxBitres;
    570       qcInit.averageBits     = (averageBitsPerFrame+7)&~7;
    571       maxBitres              = (MIN_BUFSIZE_PER_EFF_CHAN*cm->nChannelsEff) - qcInit.averageBits;
    572       qcInit.bitRes          = (config->bitreservoir!=-1) ? FDKmin(config->bitreservoir, maxBitres) : maxBitres;
    573 
    574       qcInit.maxBits         = fixMin(MIN_BUFSIZE_PER_EFF_CHAN*cm->nChannelsEff, ((averageBitsPerFrame+7)&~7)+qcInit.bitRes);
    575       qcInit.maxBits         = (config->maxBitsPerFrame!=-1) ? fixMin(qcInit.maxBits, config->maxBitsPerFrame) : qcInit.maxBits;
    576 
    577       qcInit.minBits         = fixMax(0, ((averageBitsPerFrame-1)&~7)-qcInit.bitRes-transportEnc_GetStaticBits(hTpEnc, ((averageBitsPerFrame+7)&~7)+qcInit.bitRes));
    578       qcInit.minBits         = (config->minBitsPerFrame!=-1) ? fixMax(qcInit.minBits, config->minBitsPerFrame) : qcInit.minBits;
    579   }
    580 
    581   qcInit.sampleRate          = config->sampleRate;
    582   qcInit.advancedBitsToPe    = isLowDelay(config->audioObjectType) ? 1 : 0 ;
    583   qcInit.nSubFrames          = config->nSubFrames;
    584   qcInit.padding.paddingRest = config->sampleRate;
    585 
    586   /* Calc meanPe */
    587   bw_ratio = fDivNorm((FIXP_DBL)hAacEnc->bandwidth90dB, (FIXP_DBL)(config->sampleRate>>1), &qbw);
    588   qbw = DFRACT_BITS-1-qbw;
    589   /* qcInit.meanPe = 10.0f * FRAME_LEN_LONG * hAacEnc->bandwidth90dB/(config->sampleRate/2.0f); */
    590   qcInit.meanPe = fMult(bw_ratio, (FIXP_DBL)((10*config->framelength)<<16)) >> (qbw-15);
    591 
    592   /* Calc maxBitFac */
    593   mbfac = fDivNorm((MIN_BUFSIZE_PER_EFF_CHAN-744)*cm->nChannelsEff, qcInit.averageBits/qcInit.nSubFrames, &qmbfac);
    594   qmbfac = DFRACT_BITS-1-qmbfac;
    595   qcInit.maxBitFac = (qmbfac > 24) ? (mbfac >> (qmbfac - 24)):(mbfac << (24 - qmbfac));
    596 
    597   switch(config->bitrateMode){
    598   case AACENC_BR_MODE_CBR:
    599     qcInit.bitrateMode = QCDATA_BR_MODE_CBR;
    600     break;
    601   case AACENC_BR_MODE_VBR_1:
    602     qcInit.bitrateMode = QCDATA_BR_MODE_VBR_1;
    603     break;
    604   case AACENC_BR_MODE_VBR_2:
    605     qcInit.bitrateMode = QCDATA_BR_MODE_VBR_2;
    606     break;
    607   case AACENC_BR_MODE_VBR_3:
    608     qcInit.bitrateMode = QCDATA_BR_MODE_VBR_3;
    609     break;
    610   case AACENC_BR_MODE_VBR_4:
    611     qcInit.bitrateMode = QCDATA_BR_MODE_VBR_4;
    612     break;
    613   case AACENC_BR_MODE_VBR_5:
    614     qcInit.bitrateMode = QCDATA_BR_MODE_VBR_5;
    615     break;
    616   case AACENC_BR_MODE_SFR:
    617     qcInit.bitrateMode = QCDATA_BR_MODE_SFR;
    618     break;
    619   case AACENC_BR_MODE_FF:
    620     qcInit.bitrateMode = QCDATA_BR_MODE_FF;
    621     break;
    622   default:
    623     ErrorStatus = AAC_ENC_UNSUPPORTED_BITRATE_MODE;
    624     goto bail;
    625   }
    626 
    627   qcInit.invQuant = (config->useRequant)?2:0;
    628 
    629   /* maxIterations should be set to the maximum number of requantization iterations that are
    630    * allowed before the crash recovery functionality is activated. This setting should be adjusted
    631    * to the processing power available, i.e. to the processing power headroom in one frame that is
    632    * still left after normal encoding without requantization. Please note that if activated this
    633    * functionality is used most likely only in cases where the encoder is operating beyond
    634    * recommended settings, i.e. the audio quality is suboptimal anyway. Activating the crash
    635    * recovery does not further reduce audio quality significantly in these cases. */
    636   if ( (config->audioObjectType == AOT_ER_AAC_LD) || (config->audioObjectType == AOT_ER_AAC_ELD) ) {
    637     qcInit.maxIterations = 2;
    638   }
    639   else
    640   {
    641     qcInit.maxIterations = 5;
    642   }
    643 
    644   qcInit.bitrate = config->bitRate - config->ancDataBitRate;
    645 
    646   qcInit.staticBits = transportEnc_GetStaticBits(hTpEnc, qcInit.averageBits/qcInit.nSubFrames);
    647 
    648   ErrorStatus = FDKaacEnc_QCInit(hAacEnc->qcKernel, &qcInit);
    649   if (ErrorStatus != AAC_ENC_OK)
    650     goto bail;
    651 
    652   /* Map virtual aot's to intern aot used in bitstream writer. */
    653   switch (hAacEnc->config->audioObjectType) {
    654     case AOT_MP2_AAC_LC:
    655     case AOT_DABPLUS_AAC_LC:
    656       hAacEnc->aot = AOT_AAC_LC;
    657       break;
    658     case AOT_MP2_SBR:
    659     case AOT_DABPLUS_SBR:
    660       hAacEnc->aot = AOT_SBR;
    661       break;
    662     case AOT_MP2_PS:
    663     case AOT_DABPLUS_PS:
    664       hAacEnc->aot = AOT_PS;
    665       break;
    666     default:
    667       hAacEnc->aot = hAacEnc->config->audioObjectType;
    668   }
    669 
    670   /* common things */
    671 
    672   return AAC_ENC_OK;
    673 
    674 bail:
    675 
    676   return ErrorStatus;
    677 }
    678 
    679 
    680 /*---------------------------------------------------------------------------
    681 
    682     functionname: FDKaacEnc_EncodeFrame
    683     description:  encodes one frame
    684     returns:      error code
    685 
    686   ---------------------------------------------------------------------------*/
    687 AAC_ENCODER_ERROR FDKaacEnc_EncodeFrame( HANDLE_AAC_ENC       hAacEnc,          /* encoder handle */
    688                                          HANDLE_TRANSPORTENC  hTpEnc,
    689                                          INT_PCM* RESTRICT    inputBuffer,
    690                                          INT*                 nOutBytes,
    691                                          AACENC_EXT_PAYLOAD   extPayload[MAX_TOTAL_EXT_PAYLOADS]
    692                                        )
    693 {
    694     AAC_ENCODER_ERROR ErrorStatus;
    695     int    el, n, c=0;
    696     UCHAR  extPayloadUsed[MAX_TOTAL_EXT_PAYLOADS];
    697 
    698     CHANNEL_MAPPING *cm      = &hAacEnc->channelMapping;
    699 
    700 
    701 
    702     PSY_OUT *psyOut = hAacEnc->psyOut[c];
    703     QC_OUT  *qcOut  = hAacEnc->qcOut[c];
    704 
    705     FDKmemclear(extPayloadUsed, MAX_TOTAL_EXT_PAYLOADS * sizeof(UCHAR));
    706 
    707     qcOut->elementExtBits = 0; /* sum up all extended bit of each element */
    708     qcOut->staticBits     = 0; /* sum up side info bits of each element */
    709     qcOut->totalNoRedPe   = 0; /* sum up PE */
    710 
    711     /* advance psychoacoustics */
    712     for (el=0; el<cm->nElements; el++) {
    713         ELEMENT_INFO elInfo = cm->elInfo[el];
    714 
    715         if ( (elInfo.elType == ID_SCE)
    716           || (elInfo.elType == ID_CPE)
    717           || (elInfo.elType == ID_LFE) )
    718         {
    719             int ch;
    720 
    721             /* update pointer!*/
    722             for(ch=0;ch<elInfo.nChannelsInEl;ch++) {
    723                 PSY_OUT_CHANNEL *psyOutChan = psyOut->psyOutElement[el]->psyOutChannel[ch];
    724                 QC_OUT_CHANNEL  *qcOutChan = qcOut->qcElement[el]->qcOutChannel[ch];
    725 
    726                 psyOutChan->mdctSpectrum       = qcOutChan->mdctSpectrum;
    727                 psyOutChan->sfbSpreadEnergy  = qcOutChan->sfbSpreadEnergy;
    728                 psyOutChan->sfbEnergy          = qcOutChan->sfbEnergy;
    729                 psyOutChan->sfbEnergyLdData    = qcOutChan->sfbEnergyLdData;
    730                 psyOutChan->sfbMinSnrLdData    = qcOutChan->sfbMinSnrLdData;
    731                 psyOutChan->sfbThresholdLdData = qcOutChan->sfbThresholdLdData;
    732 
    733             }
    734 
    735             FDKaacEnc_psyMain(elInfo.nChannelsInEl,
    736                               hAacEnc->psyKernel->psyElement[el],
    737                               hAacEnc->psyKernel->psyDynamic,
    738                               hAacEnc->psyKernel->psyConf,
    739                               psyOut->psyOutElement[el],
    740                               inputBuffer,
    741                               cm->elInfo[el].ChannelIndex,
    742                               cm->nChannels
    743 
    744                     );
    745 
    746             /* FormFactor, Pe and staticBitDemand calculation */
    747             ErrorStatus = FDKaacEnc_QCMainPrepare(&elInfo,
    748                                                    hAacEnc->qcKernel->hAdjThr->adjThrStateElem[el],
    749                                                    psyOut->psyOutElement[el],
    750                                                    qcOut->qcElement[el],
    751                                                    hAacEnc->aot,
    752                                                    hAacEnc->config->syntaxFlags,
    753                                                    hAacEnc->config->epConfig);
    754 
    755             if (ErrorStatus != AAC_ENC_OK)
    756               return ErrorStatus;
    757 
    758             /*-------------------------------------------- */
    759 
    760             qcOut->qcElement[el]->extBitsUsed = 0;
    761             qcOut->qcElement[el]->nExtensions = 0;
    762             /* reset extension payload */
    763             FDKmemclear(&qcOut->qcElement[el]->extension, (1)*sizeof(QC_OUT_EXTENSION));
    764 
    765             for ( n = 0; n < MAX_TOTAL_EXT_PAYLOADS; n++ ) {
    766                 if ( !extPayloadUsed[n]
    767                   && (extPayload[n].associatedChElement == el)
    768                   && (extPayload[n].dataSize > 0)
    769                   && (extPayload[n].pData != NULL) )
    770                 {
    771                     int idx = qcOut->qcElement[el]->nExtensions++;
    772 
    773                     qcOut->qcElement[el]->extension[idx].type         = extPayload[n].dataType;   /* Perform a sanity check on the type? */
    774                     qcOut->qcElement[el]->extension[idx].nPayloadBits = extPayload[n].dataSize;
    775                     qcOut->qcElement[el]->extension[idx].pPayload = extPayload[n].pData;
    776                     /* Now ask the bitstream encoder how many bits we need to encode the data with the current bitstream syntax: */
    777                     qcOut->qcElement[el]->extBitsUsed +=
    778                           FDKaacEnc_writeExtensionData( NULL,
    779                                                        &qcOut->qcElement[el]->extension[idx],
    780                                                         0, 0,
    781                                                         hAacEnc->config->syntaxFlags,
    782                                                         hAacEnc->aot,
    783                                                         hAacEnc->config->epConfig );
    784                     extPayloadUsed[n] = 1;
    785                 }
    786             }
    787 
    788             /* sum up extension and static bits for all channel elements */
    789             qcOut->elementExtBits += qcOut->qcElement[el]->extBitsUsed;
    790             qcOut->staticBits   += qcOut->qcElement[el]->staticBitsUsed;
    791 
    792             /* sum up pe */
    793             qcOut->totalNoRedPe += qcOut->qcElement[el]->peData.pe;
    794         }
    795     }
    796 
    797     qcOut->nExtensions   = 0;
    798     qcOut->globalExtBits = 0;
    799 
    800     /* reset extension payload */
    801     FDKmemclear(&qcOut->extension, (2+2)*sizeof(QC_OUT_EXTENSION));
    802 
    803     /* Add extension payload not assigned to an channel element
    804       (Ancillary data is the only supported type up to now) */
    805     for ( n = 0; n < MAX_TOTAL_EXT_PAYLOADS; n++ ) {
    806         if ( !extPayloadUsed[n]
    807           && (extPayload[n].associatedChElement == -1)
    808           && (extPayload[n].pData != NULL) )
    809         {
    810             UINT payloadBits = 0;
    811 
    812             if (extPayload[n].dataType == EXT_DATA_ELEMENT) {
    813                 if (hAacEnc->ancillaryBitsPerFrame) {
    814                     /* granted frame dse bitrate */
    815                     payloadBits = hAacEnc->ancillaryBitsPerFrame;
    816                 }
    817                 else {
    818                     /* write anc data if bitrate constraint fulfilled */
    819                     if ((extPayload[n].dataSize>>3) <= hAacEnc->config->maxAncBytesPerAU) {
    820                         payloadBits = extPayload[n].dataSize;
    821                     }
    822                 }
    823                 payloadBits = fixMin( extPayload[n].dataSize, payloadBits );
    824             } else {
    825                 payloadBits = extPayload[n].dataSize;
    826             }
    827 
    828             if (payloadBits > 0)
    829             {
    830                 int idx = qcOut->nExtensions++;
    831 
    832                 qcOut->extension[idx].type         = extPayload[n].dataType;   /* Perform a sanity check on the type? */
    833                 qcOut->extension[idx].nPayloadBits = payloadBits;
    834                 qcOut->extension[idx].pPayload = extPayload[n].pData;
    835                 /* Now ask the bitstream encoder how many bits we need to encode the data with the current bitstream syntax: */
    836                 qcOut->globalExtBits += FDKaacEnc_writeExtensionData( NULL,
    837                                                                      &qcOut->extension[idx],
    838                                                                       0, 0,
    839                                                                       hAacEnc->config->syntaxFlags,
    840                                                                       hAacEnc->aot,
    841                                                                       hAacEnc->config->epConfig );
    842                 if (extPayload[n].dataType == EXT_DATA_ELEMENT) {
    843                     /* substract the processed bits */
    844                     extPayload[n].dataSize -= payloadBits;
    845                 }
    846                 extPayloadUsed[n] = 1;
    847             }
    848         }
    849     }
    850 
    851     if (!(hAacEnc->config->syntaxFlags & (AC_SCALABLE|AC_ER))) {
    852       qcOut->globalExtBits += EL_ID_BITS;  /* add bits for ID_END */
    853     }
    854 
    855     /* build bitstream all nSubFrames */
    856     {
    857         INT totalBits    = 0;   /* Total AU bits */;
    858         INT avgTotalBits = 0;
    859 
    860         /*-------------------------------------------- */
    861         /* Get average total bits */
    862         /*-------------------------------------------- */
    863         {
    864             /* frame wise bitrate adaption */
    865             FDKaacEnc_AdjustBitrate(hAacEnc->qcKernel,
    866                                     cm,
    867                                    &avgTotalBits,
    868                                     hAacEnc->config->bitRate,
    869                                     hAacEnc->config->sampleRate,
    870                                     hAacEnc->config->framelength);
    871 
    872             /* adjust super frame bitrate */
    873             avgTotalBits *= hAacEnc->config->nSubFrames;
    874         }
    875 
    876         /* Make first estimate of transport header overhead.
    877            Take maximum possible frame size into account to prevent bitreservoir underrun. */
    878         hAacEnc->qcKernel->globHdrBits = transportEnc_GetStaticBits(hTpEnc, avgTotalBits + hAacEnc->qcKernel->bitResTot);
    879 
    880 
    881         /*-------------------------------------------- */
    882         /*-------------------------------------------- */
    883         /*-------------------------------------------- */
    884 
    885         ErrorStatus = FDKaacEnc_QCMain(hAacEnc->qcKernel,
    886                                        hAacEnc->psyOut,
    887                                        hAacEnc->qcOut,
    888                                        avgTotalBits,
    889                                        cm
    890                                       ,hAacEnc->aot,
    891                                        hAacEnc->config->syntaxFlags,
    892                                        hAacEnc->config->epConfig);
    893 
    894         if (ErrorStatus != AAC_ENC_OK)
    895             return ErrorStatus;
    896         /*-------------------------------------------- */
    897 
    898         /*-------------------------------------------- */
    899         ErrorStatus = FDKaacEnc_updateFillBits(cm,
    900                                                hAacEnc->qcKernel,
    901                                                hAacEnc->qcKernel->elementBits,
    902                                                hAacEnc->qcOut);
    903         if (ErrorStatus != AAC_ENC_OK)
    904             return ErrorStatus;
    905 
    906             /*-------------------------------------------- */
    907             ErrorStatus = FDKaacEnc_FinalizeBitConsumption(cm,
    908                                                            hAacEnc->qcKernel,
    909                                                            qcOut,
    910                                                            qcOut->qcElement,
    911                                                            hTpEnc,
    912                                                            hAacEnc->aot,
    913                                                            hAacEnc->config->syntaxFlags,
    914                                                            hAacEnc->config->epConfig);
    915             if (ErrorStatus != AAC_ENC_OK)
    916                 return ErrorStatus;
    917             /*-------------------------------------------- */
    918             totalBits += qcOut->totalBits;
    919 
    920 
    921         /*-------------------------------------------- */
    922         FDKaacEnc_updateBitres(cm,
    923                                hAacEnc->qcKernel,
    924                                hAacEnc->qcOut);
    925 
    926         /*-------------------------------------------- */
    927 
    928         /* for ( all sub frames ) ... */
    929               /* write bitstream header */
    930               transportEnc_WriteAccessUnit(
    931                     hTpEnc,
    932                     totalBits,
    933                     FDKaacEnc_EncBitresToTpBitres(hAacEnc->bitrateMode, hAacEnc->qcKernel->bitResTot),
    934                     cm->nChannelsEff);
    935 
    936               /* write bitstream */
    937               ErrorStatus = FDKaacEnc_WriteBitstream(
    938                     hTpEnc,
    939                     cm,
    940                     qcOut,
    941                     psyOut,
    942                     hAacEnc->qcKernel,
    943                     hAacEnc->aot,
    944                     hAacEnc->config->syntaxFlags,
    945                     hAacEnc->config->epConfig);
    946 
    947               if (ErrorStatus != AAC_ENC_OK)
    948                 return ErrorStatus;
    949 
    950               /* transportEnc_EndAccessUnit() is being called inside FDKaacEnc_WriteBitstream() */
    951               transportEnc_GetFrame(hTpEnc, nOutBytes);
    952 
    953     } /* -end- if (curFrame==hAacEnc->qcKernel->nSubFrames) */
    954 
    955 
    956     /*-------------------------------------------- */
    957     return AAC_ENC_OK;
    958 }
    959 
    960 /*---------------------------------------------------------------------------
    961 
    962     functionname:FDKaacEnc_Close
    963     description: delete encoder instance
    964     returns:
    965 
    966   ---------------------------------------------------------------------------*/
    967 
    968 void FDKaacEnc_Close( HANDLE_AAC_ENC*  phAacEnc)   /* encoder handle */
    969 {
    970     if (*phAacEnc == NULL) {
    971       return;
    972     }
    973     AAC_ENC *hAacEnc = (AAC_ENC*)*phAacEnc;
    974 
    975    if (hAacEnc->dynamic_RAM != NULL)
    976        FreeAACdynamic_RAM(&hAacEnc->dynamic_RAM);
    977 
    978     FDKaacEnc_PsyClose(&hAacEnc->psyKernel,hAacEnc->psyOut);
    979 
    980     FDKaacEnc_QCClose(&hAacEnc->qcKernel, hAacEnc->qcOut);
    981 
    982     FreeRam_aacEnc_AacEncoder(phAacEnc);
    983 }
    984 
    985 
    986 /* The following functions are in this source file only for convenience and */
    987 /* need not be visible outside of a possible encoder library. */
    988 
    989 /* basic defines for ancillary data */
    990 #define MAX_ANCRATE 19200            /* ancillary rate >= 19200 isn't valid */
    991 
    992 /*---------------------------------------------------------------------------
    993 
    994     functionname:  FDKaacEnc_InitCheckAncillary
    995     description:   initialize and check ancillary data struct
    996     return:        if success or NULL if error
    997 
    998   ---------------------------------------------------------------------------*/
    999 static AAC_ENCODER_ERROR FDKaacEnc_InitCheckAncillary(INT bitRate,
   1000                                                       INT framelength,
   1001                                                       INT ancillaryRate,
   1002                                                       INT *ancillaryBitsPerFrame,
   1003                                                       INT sampleRate)
   1004 {
   1005   INT diffToByteAlign;
   1006 
   1007   /* don't use negative ancillary rates */
   1008   if ( ancillaryRate < -1 )
   1009     return AAC_ENC_UNSUPPORTED_ANC_BITRATE;
   1010 
   1011   /* check if ancillary rate is ok */
   1012   if ( (ancillaryRate != (-1)) && (ancillaryRate != 0) ) {
   1013     /* ancRate <= 15% of bitrate && ancRate < 19200 */
   1014     if ( ( ancillaryRate >= MAX_ANCRATE ) ||
   1015          ( (ancillaryRate * 20) > (bitRate * 3) ) ) {
   1016       return AAC_ENC_UNSUPPORTED_ANC_BITRATE;
   1017     }
   1018   }
   1019   else if (ancillaryRate == -1) {
   1020     /* if no special ancRate is requested but a ancillary file is
   1021        stated, then generate a ancillary rate matching to the bitrate */
   1022     if (bitRate >= (MAX_ANCRATE * 10)) {
   1023       /* ancillary rate is 19199 */
   1024       ancillaryRate = (MAX_ANCRATE - 1);
   1025     }
   1026     else { /* 10% of bitrate */
   1027       ancillaryRate = bitRate / 10;
   1028     }
   1029   }
   1030 
   1031   /* make ancillaryBitsPerFrame byte align */
   1032   *ancillaryBitsPerFrame = (ancillaryRate * framelength ) / sampleRate;
   1033   diffToByteAlign = *ancillaryBitsPerFrame % 8;
   1034   *ancillaryBitsPerFrame = *ancillaryBitsPerFrame - diffToByteAlign;
   1035 
   1036   return AAC_ENC_OK;
   1037 }
   1038