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