• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 
2 /* -----------------------------------------------------------------------------------------------------------
3 Software License for The Fraunhofer FDK AAC Codec Library for Android
4 
5 � Copyright  1995 - 2012 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 /******************************** MPEG Audio Encoder **************************
85 
86    Initial author:       M. Werner
87    contents/description: Quantizing & coding
88 
89 ******************************************************************************/
90 
91 #include "qc_main.h"
92 #include "quantize.h"
93 #include "interface.h"
94 #include "adj_thr.h"
95 #include "sf_estim.h"
96 #include "bit_cnt.h"
97 #include "dyn_bits.h"
98 #include "channel_map.h"
99 #include "aacEnc_ram.h"
100 
101 #include "genericStds.h"
102 
103 
104 typedef struct {
105   QCDATA_BR_MODE bitrateMode;
106   LONG vbrQualFactor;
107 } TAB_VBR_QUAL_FACTOR;
108 
109 static const TAB_VBR_QUAL_FACTOR tableVbrQualFactor[] = {
110   {QCDATA_BR_MODE_CBR,   FL2FXCONST_DBL(0.00f)},
111   {QCDATA_BR_MODE_VBR_1, FL2FXCONST_DBL(0.160f)}, /* 32 kbps mono   AAC-LC + SBR + PS */
112   {QCDATA_BR_MODE_VBR_2, FL2FXCONST_DBL(0.148f)}, /* 64 kbps stereo AAC-LC + SBR      */
113   {QCDATA_BR_MODE_VBR_3, FL2FXCONST_DBL(0.135f)}, /* 80 - 96 kbps stereo AAC-LC       */
114   {QCDATA_BR_MODE_VBR_4, FL2FXCONST_DBL(0.111f)}, /* 128 kbps stereo AAC-LC           */
115   {QCDATA_BR_MODE_VBR_5, FL2FXCONST_DBL(0.070f)}, /* 192 kbps stereo AAC-LC           */
116   {QCDATA_BR_MODE_SFR,   FL2FXCONST_DBL(0.00f)},
117   {QCDATA_BR_MODE_FF,    FL2FXCONST_DBL(0.00f)}
118 };
119 
isConstantBitrateMode(const QCDATA_BR_MODE bitrateMode)120 static INT isConstantBitrateMode(
121         const QCDATA_BR_MODE bitrateMode
122         )
123 {
124   return ( ((bitrateMode==QCDATA_BR_MODE_CBR) || (bitrateMode==QCDATA_BR_MODE_SFR) || (bitrateMode==QCDATA_BR_MODE_FF)) ? 1 : 0 );
125 }
126 
127 
128 
129 typedef enum{
130     FRAME_LEN_BYTES_MODULO =  1,
131     FRAME_LEN_BYTES_INT    =  2
132 }FRAME_LEN_RESULT_MODE;
133 
134 /* forward declarations */
135 
136 static INT FDKaacEnc_calcMaxValueInSfb(INT   sfbCnt,
137                              INT   maxSfbPerGroup,
138                              INT   sfbPerGroup,
139                              INT  *RESTRICT sfbOffset,
140                              SHORT *RESTRICT quantSpectrum,
141                              UINT *RESTRICT maxValue);
142 
143 static void FDKaacEnc_crashRecovery(INT               nChannels,
144                           PSY_OUT_ELEMENT*  psyOutElement,
145                           QC_OUT*           qcOut,
146                           QC_OUT_ELEMENT   *qcElement,
147                           INT               bitsToSave,
148                           AUDIO_OBJECT_TYPE aot,
149                           UINT              syntaxFlags,
150                           SCHAR             epConfig);
151 
152 static
153 AAC_ENCODER_ERROR FDKaacEnc_reduceBitConsumption(int*             iterations,
154                                        const int        maxIterations,
155                                        int              gainAdjustment,
156                                        int*             chConstraintsFulfilled,
157                                        int*             calculateQuant,
158                                        int              nChannels,
159                                        PSY_OUT_ELEMENT* psyOutElement,
160                                        QC_OUT*          qcOut,
161                                        QC_OUT_ELEMENT*  qcOutElement,
162                                        ELEMENT_BITS*    elBits,
163                                        AUDIO_OBJECT_TYPE  aot,
164                                        UINT             syntaxFlags,
165                                        SCHAR            epConfig);
166 
167 
168 void  FDKaacEnc_QCClose (QC_STATE  **phQCstate, QC_OUT **phQC);
169 
170 /*****************************************************************************
171 
172     functionname: FDKaacEnc_calcFrameLen
173     description:
174     returns:
175     input:
176     output:
177 
178 *****************************************************************************/
FDKaacEnc_calcFrameLen(INT bitRate,INT sampleRate,INT granuleLength,FRAME_LEN_RESULT_MODE mode)179 static INT FDKaacEnc_calcFrameLen(INT bitRate,
180                         INT sampleRate,
181                         INT granuleLength,
182                         FRAME_LEN_RESULT_MODE mode)
183 {
184 
185    INT result;
186 
187    result = ((granuleLength)>>3)*(bitRate);
188 
189    switch(mode) {
190      case FRAME_LEN_BYTES_MODULO:
191          result %= sampleRate;
192      break;
193      case FRAME_LEN_BYTES_INT:
194          result /= sampleRate;
195      break;
196    }
197    return(result);
198 }
199 
200 /*****************************************************************************
201 
202     functionname:FDKaacEnc_framePadding
203     description: Calculates if padding is needed for actual frame
204     returns:
205     input:
206     output:
207 
208 *****************************************************************************/
FDKaacEnc_framePadding(INT bitRate,INT sampleRate,INT granuleLength,INT * paddingRest)209 static INT FDKaacEnc_framePadding(INT bitRate,
210                         INT sampleRate,
211                         INT granuleLength,
212                         INT *paddingRest)
213 {
214   INT paddingOn;
215   INT difference;
216 
217   paddingOn = 0;
218 
219   difference = FDKaacEnc_calcFrameLen( bitRate,
220                              sampleRate,
221                              granuleLength,
222                              FRAME_LEN_BYTES_MODULO );
223   *paddingRest-=difference;
224 
225   if (*paddingRest <= 0 ) {
226     paddingOn = 1;
227     *paddingRest += sampleRate;
228   }
229 
230   return( paddingOn );
231 }
232 
233 
234 /*********************************************************************************
235 
236          functionname: FDKaacEnc_QCOutNew
237          description:
238          return:
239 
240 **********************************************************************************/
FDKaacEnc_QCOutNew(QC_OUT ** phQC,const INT nElements,const INT nChannels,const INT nSubFrames,UCHAR * dynamic_RAM)241 AAC_ENCODER_ERROR FDKaacEnc_QCOutNew(QC_OUT    **phQC,
242                                      const INT   nElements,
243                                      const INT   nChannels,
244                                      const INT   nSubFrames
245                                     ,UCHAR      *dynamic_RAM
246                                     )
247 {
248   AAC_ENCODER_ERROR ErrorStatus;
249   int n, i;
250   int elInc = 0, chInc = 0;
251 
252   for (n=0; n<nSubFrames; n++) {
253     phQC[n] = GetRam_aacEnc_QCout(n);
254     if (phQC[n] == NULL) {
255       ErrorStatus = AAC_ENC_NO_MEMORY;
256       goto QCOutNew_bail;
257     }
258 
259     for (i=0; i<nChannels; i++) {
260       phQC[n]->pQcOutChannels[i] = GetRam_aacEnc_QCchannel(chInc, dynamic_RAM);
261       if ( phQC[n]->pQcOutChannels[i] == NULL
262          )
263       {
264          ErrorStatus = AAC_ENC_NO_MEMORY;
265          goto QCOutNew_bail;
266       }
267       chInc++;
268     } /* nChannels */
269 
270     for (i=0; i<nElements; i++) {
271       phQC[n]->qcElement[i]      = GetRam_aacEnc_QCelement(elInc);
272       if (phQC[n]->qcElement[i] == NULL)
273       {
274         ErrorStatus = AAC_ENC_NO_MEMORY;
275         goto QCOutNew_bail;
276       }
277       elInc++;
278     } /* nElements */
279 
280   } /* nSubFrames */
281 
282 
283   return AAC_ENC_OK;
284 
285 QCOutNew_bail:
286   return ErrorStatus;
287 }
288 
289 /*********************************************************************************
290 
291          functionname: FDKaacEnc_QCOutInit
292          description:
293          return:
294 
295 **********************************************************************************/
FDKaacEnc_QCOutInit(QC_OUT * phQC[(1)],const INT nSubFrames,const CHANNEL_MAPPING * cm)296 AAC_ENCODER_ERROR FDKaacEnc_QCOutInit(QC_OUT          *phQC[(1)],
297                                       const INT        nSubFrames,
298                                       const CHANNEL_MAPPING *cm)
299 {
300   INT n,i,ch;
301 
302   for (n=0; n<nSubFrames; n++) {
303     INT chInc = 0;
304     for (i=0; i<cm->nElements; i++) {
305       for (ch=0; ch<cm->elInfo[i].nChannelsInEl; ch++) {
306         phQC[n]->qcElement[i]->qcOutChannel[ch] = phQC[n]->pQcOutChannels[chInc];
307         chInc++;
308       } /* chInEl */
309     } /* nElements */
310   } /* nSubFrames */
311 
312   return AAC_ENC_OK;
313 }
314 
315 /*********************************************************************************
316 
317          functionname: FDKaacEnc_QCNew
318          description:
319          return:
320 
321 **********************************************************************************/
FDKaacEnc_QCNew(QC_STATE ** phQC,INT nElements,UCHAR * dynamic_RAM)322 AAC_ENCODER_ERROR FDKaacEnc_QCNew(QC_STATE  **phQC,
323                                   INT         nElements
324                                  ,UCHAR*      dynamic_RAM
325            )
326 {
327   AAC_ENCODER_ERROR ErrorStatus;
328   int i;
329 
330   QC_STATE* hQC = GetRam_aacEnc_QCstate();
331   *phQC = hQC;
332   if (hQC == NULL) {
333     ErrorStatus = AAC_ENC_NO_MEMORY;
334     goto QCNew_bail;
335   }
336 
337   if (FDKaacEnc_AdjThrNew(&hQC->hAdjThr, nElements)) {
338     ErrorStatus = AAC_ENC_NO_MEMORY;
339     goto QCNew_bail;
340   }
341 
342   if (FDKaacEnc_BCNew(&(hQC->hBitCounter), dynamic_RAM)) {
343     ErrorStatus = AAC_ENC_NO_MEMORY;
344     goto QCNew_bail;
345   }
346 
347   for (i=0; i<nElements; i++) {
348     hQC->elementBits[i] = GetRam_aacEnc_ElementBits(i);
349     if (hQC->elementBits[i] == NULL) {
350       ErrorStatus = AAC_ENC_NO_MEMORY;
351       goto QCNew_bail;
352     }
353   }
354 
355   return AAC_ENC_OK;
356 
357 QCNew_bail:
358   FDKaacEnc_QCClose(phQC, NULL);
359   return ErrorStatus;
360 }
361 
362 /*********************************************************************************
363 
364          functionname: FDKaacEnc_QCInit
365          description:
366          return:
367 
368 **********************************************************************************/
FDKaacEnc_QCInit(QC_STATE * hQC,struct QC_INIT * init)369 AAC_ENCODER_ERROR FDKaacEnc_QCInit(QC_STATE *hQC,
370                                    struct QC_INIT *init)
371 {
372   hQC->maxBitsPerFrame = init->maxBits;
373   hQC->minBitsPerFrame = init->minBits;
374   hQC->nElements       = init->channelMapping->nElements;
375   hQC->bitResTotMax    = init->bitRes;
376   hQC->bitResTot       = init->bitRes;
377   hQC->maxBitFac       = init->maxBitFac;
378   hQC->bitrateMode     = init->bitrateMode;
379   hQC->invQuant        = init->invQuant;
380   hQC->maxIterations   = init->maxIterations;
381 
382   if ( isConstantBitrateMode(hQC->bitrateMode) ) {
383     INT bitresPerChannel = (hQC->bitResTotMax / init->channelMapping->nChannelsEff);
384     /* 0: full bitreservoir, 1: reduced bitreservoir, 2: disabled bitreservoir */
385     hQC->bitDistributenMode = (bitresPerChannel>50) ? 0 : (bitresPerChannel>0) ? 1 : 2;
386   }
387   else {
388     hQC->bitDistributenMode = 0; /* full bitreservoir */
389   }
390 
391 
392   hQC->padding.paddingRest = init->padding.paddingRest;
393 
394   hQC->globHdrBits = init->staticBits; /* Bit overhead due to transport */
395 
396   FDKaacEnc_InitElementBits(hQC,
397                             init->channelMapping,
398                             init->bitrate,
399                             (init->averageBits/init->nSubFrames) - hQC->globHdrBits,
400                             hQC->maxBitsPerFrame/init->channelMapping->nChannelsEff);
401 
402   switch(hQC->bitrateMode){
403     case QCDATA_BR_MODE_CBR:
404     case QCDATA_BR_MODE_VBR_1:
405     case QCDATA_BR_MODE_VBR_2:
406     case QCDATA_BR_MODE_VBR_3:
407     case QCDATA_BR_MODE_VBR_4:
408     case QCDATA_BR_MODE_VBR_5:
409     case QCDATA_BR_MODE_SFR:
410     case QCDATA_BR_MODE_FF:
411       if((int)hQC->bitrateMode < (int)(sizeof(tableVbrQualFactor)/sizeof(TAB_VBR_QUAL_FACTOR))){
412         hQC->vbrQualFactor = (FIXP_DBL)tableVbrQualFactor[hQC->bitrateMode].vbrQualFactor;
413       } else {
414         hQC->vbrQualFactor = FL2FXCONST_DBL(0.f); /* default setting */
415       }
416       break;
417     case QCDATA_BR_MODE_INVALID:
418     default:
419       hQC->vbrQualFactor = FL2FXCONST_DBL(0.f);
420       break;
421   }
422 
423   FDKaacEnc_AdjThrInit(hQC->hAdjThr,
424              init->meanPe,
425              hQC->elementBits,                 /* or channelBitrates, was: channelBitrate */
426              init->channelMapping->nElements,
427              hQC->vbrQualFactor);
428 
429   return AAC_ENC_OK;
430 }
431 
432 
433 
434 /*********************************************************************************
435 
436          functionname: FDKaacEnc_QCMainPrepare
437          description:
438          return:
439 
440 **********************************************************************************/
FDKaacEnc_QCMainPrepare(ELEMENT_INFO * elInfo,ATS_ELEMENT * RESTRICT adjThrStateElement,PSY_OUT_ELEMENT * RESTRICT psyOutElement,QC_OUT_ELEMENT * RESTRICT qcOutElement,AUDIO_OBJECT_TYPE aot,UINT syntaxFlags,SCHAR epConfig)441 AAC_ENCODER_ERROR FDKaacEnc_QCMainPrepare(ELEMENT_INFO              *elInfo,
442                                           ATS_ELEMENT* RESTRICT      adjThrStateElement,
443                                           PSY_OUT_ELEMENT* RESTRICT  psyOutElement,
444                                           QC_OUT_ELEMENT* RESTRICT   qcOutElement,
445                                           AUDIO_OBJECT_TYPE          aot,
446                                           UINT                       syntaxFlags,
447                                           SCHAR                      epConfig
448                                          )
449 {
450   AAC_ENCODER_ERROR ErrorStatus = AAC_ENC_OK;
451   INT  nChannels = elInfo->nChannelsInEl;
452 
453   PSY_OUT_CHANNEL** RESTRICT psyOutChannel = psyOutElement->psyOutChannel;    /* may be modified in-place */
454 
455   FDKaacEnc_CalcFormFactor(qcOutElement->qcOutChannel, psyOutChannel, nChannels);
456 
457   /* prepare and calculate PE without reduction */
458   FDKaacEnc_peCalculation(&qcOutElement->peData, psyOutChannel, qcOutElement->qcOutChannel, &psyOutElement->toolsInfo, adjThrStateElement, nChannels);
459 
460   ErrorStatus = FDKaacEnc_ChannelElementWrite( NULL, elInfo, NULL,
461                                                psyOutElement,
462                                                psyOutElement->psyOutChannel,
463                                                syntaxFlags,
464                                                aot,
465                                                epConfig,
466                                               &qcOutElement->staticBitsUsed,
467                                                0 );
468 
469   return ErrorStatus;
470 }
471 
472 /*********************************************************************************
473 
474          functionname: FDKaacEnc_AdjustBitrate
475          description:  adjusts framelength via padding on a frame to frame basis,
476                        to achieve a bitrate that demands a non byte aligned
477                        framelength
478          return:       errorcode
479 
480 **********************************************************************************/
FDKaacEnc_AdjustBitrate(QC_STATE * RESTRICT hQC,CHANNEL_MAPPING * RESTRICT cm,INT * avgTotalBits,INT bitRate,INT sampleRate,INT granuleLength)481 AAC_ENCODER_ERROR FDKaacEnc_AdjustBitrate(QC_STATE        *RESTRICT hQC,
482                                           CHANNEL_MAPPING *RESTRICT cm,
483                                           INT             *avgTotalBits,
484                                           INT              bitRate,       /* total bitrate */
485                                           INT              sampleRate,    /* output sampling rate */
486                                           INT              granuleLength) /* frame length */
487 {
488   INT paddingOn;
489   INT frameLen;
490 
491   /* Do we need an extra padding byte? */
492   paddingOn = FDKaacEnc_framePadding(bitRate,
493                            sampleRate,
494                            granuleLength,
495                           &hQC->padding.paddingRest);
496 
497   frameLen = paddingOn + FDKaacEnc_calcFrameLen(bitRate,
498                                       sampleRate,
499                                       granuleLength,
500                                       FRAME_LEN_BYTES_INT);
501 
502   *avgTotalBits = frameLen<<3;
503 
504   return AAC_ENC_OK;
505 }
506 
FDKaacEnc_distributeElementDynBits(QC_STATE * hQC,QC_OUT_ELEMENT * qcElement[(6)],CHANNEL_MAPPING * cm,INT codeBits)507 static AAC_ENCODER_ERROR FDKaacEnc_distributeElementDynBits(QC_STATE*         hQC,
508                                                   QC_OUT_ELEMENT*   qcElement[(6)],
509                                                   CHANNEL_MAPPING*  cm,
510                                                   INT               codeBits)
511 {
512 
513   INT i, firstEl = cm->nElements-1;
514   INT totalBits = 0;
515 
516   for (i=(cm->nElements-1); i>=0; i--) {
517     if ((cm->elInfo[i].elType == ID_SCE) || (cm->elInfo[i].elType == ID_CPE) ||
518         (cm->elInfo[i].elType == ID_LFE))
519     {
520       qcElement[i]->grantedDynBits =  (INT)fMult(hQC->elementBits[i]->relativeBitsEl, (FIXP_DBL)codeBits);
521       totalBits += qcElement[i]->grantedDynBits;
522       firstEl = i;
523     }
524   }
525   qcElement[firstEl]->grantedDynBits += codeBits - totalBits;
526 
527   return AAC_ENC_OK;
528 }
529 
530 /**
531  * \brief  Verify whether minBitsPerFrame criterion can be satisfied.
532  *
533  * This function evaluates the bit consumption only if minBitsPerFrame parameter is not 0.
534  * In hyperframing mode the difference between grantedDynBits and usedDynBits of all sub frames
535  * results the number of fillbits to be written.
536  * This bits can be distrubitued in superframe to reach minBitsPerFrame bit consumption in single AU's.
537  * The return value denotes if enough desired fill bits are available to achieve minBitsPerFrame in all frames.
538  * This check can only be used within superframes.
539  *
540  * \param qcOut            Pointer to coding data struct.
541  * \param minBitsPerFrame  Minimal number of bits to be consumed in each frame.
542  * \param nSubFrames       Number of frames in superframe
543  *
544  * \return
545  *          - 1: all fine
546  *          - 0: criterion not fulfilled
547  */
checkMinFrameBitsDemand(QC_OUT ** qcOut,const INT minBitsPerFrame,const INT nSubFrames)548 static int checkMinFrameBitsDemand(
549         QC_OUT**                  qcOut,
550         const INT                 minBitsPerFrame,
551         const INT                 nSubFrames
552         )
553 {
554   int result = 1; /* all fine*/
555   return result;
556 }
557 
558 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
559 
560 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
561 /*********************************************************************************
562 
563          functionname: FDKaacEnc_getMinimalStaticBitdemand
564          description:  calculate minmal size of static bits by reduction ,
565                        to zero spectrum and deactivating tns and MS
566          return:       number of static bits
567 
568 **********************************************************************************/
FDKaacEnc_getMinimalStaticBitdemand(CHANNEL_MAPPING * cm,PSY_OUT ** psyOut)569 static int FDKaacEnc_getMinimalStaticBitdemand(CHANNEL_MAPPING*     cm,
570                                                PSY_OUT**            psyOut)
571 {
572   AUDIO_OBJECT_TYPE aot = AOT_AAC_LC;
573   UINT  syntaxFlags = 0;
574   SCHAR epConfig = -1;
575   int i, bitcount = 0;
576 
577   for (i=0; i<cm->nElements; i++) {
578       ELEMENT_INFO elInfo = cm->elInfo[i];
579 
580       if ( (elInfo.elType == ID_SCE)
581         || (elInfo.elType == ID_CPE)
582         || (elInfo.elType == ID_LFE) )
583       {
584         INT minElBits = 0;
585 
586         FDKaacEnc_ChannelElementWrite( NULL, &elInfo, NULL,
587                                        psyOut[0]->psyOutElement[i],
588                                        psyOut[0]->psyOutElement[i]->psyOutChannel,
589                                        syntaxFlags,
590                                        aot,
591                                        epConfig,
592                                       &minElBits,
593                                        1 );
594         bitcount += minElBits;
595       }
596   }
597 
598   return bitcount;
599 }
600 
601 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
602 
FDKaacEnc_prepareBitDistribution(QC_STATE * hQC,PSY_OUT ** psyOut,QC_OUT ** qcOut,CHANNEL_MAPPING * cm,QC_OUT_ELEMENT * qcElement[(1)][(6)],INT avgTotalBits,INT * totalAvailableBits,INT * avgTotalDynBits)603 static AAC_ENCODER_ERROR FDKaacEnc_prepareBitDistribution(QC_STATE*            hQC,
604                                                 PSY_OUT**            psyOut,
605                                                 QC_OUT**             qcOut,
606                                                 CHANNEL_MAPPING*     cm,
607                                                 QC_OUT_ELEMENT*      qcElement[(1)][(6)],
608                                                 INT                  avgTotalBits,
609                                                 INT                 *totalAvailableBits,
610                                                 INT                 *avgTotalDynBits)
611 {
612     int i;
613       /* get maximal allowed dynamic bits */
614       qcOut[0]->grantedDynBits =  (fixMin(hQC->maxBitsPerFrame, avgTotalBits) - hQC->globHdrBits)&~7;
615       qcOut[0]->grantedDynBits -= (qcOut[0]->globalExtBits + qcOut[0]->staticBits + qcOut[0]->elementExtBits);
616       qcOut[0]->maxDynBits = ((hQC->maxBitsPerFrame)&~7) - (qcOut[0]->globalExtBits + qcOut[0]->staticBits + qcOut[0]->elementExtBits);
617       /* assure that enough bits are available */
618       if ((qcOut[0]->grantedDynBits+hQC->bitResTot) < 0) {
619         /* crash recovery allows to reduce static bits to a minimum */
620         if ( (qcOut[0]->grantedDynBits+hQC->bitResTot) < (FDKaacEnc_getMinimalStaticBitdemand(cm, psyOut)-qcOut[0]->staticBits) )
621           return AAC_ENC_BITRES_TOO_LOW;
622       }
623 
624       /* distribute dynamic bits to each element */
625       FDKaacEnc_distributeElementDynBits(hQC,
626                                qcElement[0],
627                                cm,
628                                qcOut[0]->grantedDynBits);
629 
630       *avgTotalDynBits = 0; /*frameDynBits;*/
631 
632     *totalAvailableBits = avgTotalBits;
633 
634     /* sum up corrected granted PE */
635     qcOut[0]->totalGrantedPeCorr = 0;
636 
637     for (i=0; i<cm->nElements; i++)
638     {
639         ELEMENT_INFO elInfo = cm->elInfo[i];
640         int nChannels = elInfo.nChannelsInEl;
641 
642         if ((elInfo.elType == ID_SCE) || (elInfo.elType == ID_CPE) ||
643             (elInfo.elType == ID_LFE))
644         {
645                 /* for ( all sub frames ) ... */
646                 FDKaacEnc_DistributeBits(hQC->hAdjThr,
647                                          hQC->hAdjThr->adjThrStateElem[i],
648                                          psyOut[0]->psyOutElement[i]->psyOutChannel,
649                                         &qcElement[0][i]->peData,
650                                         &qcElement[0][i]->grantedPe,
651                                         &qcElement[0][i]->grantedPeCorr,
652                                          nChannels,
653                                          psyOut[0]->psyOutElement[i]->commonWindow,
654                                          qcElement[0][i]->grantedDynBits,
655                                          hQC->elementBits[i]->bitResLevelEl,
656                                          hQC->elementBits[i]->maxBitResBitsEl,
657                                          hQC->maxBitFac,
658                                          hQC->bitDistributenMode);
659 
660                 *totalAvailableBits += hQC->elementBits[i]->bitResLevelEl;
661         /* get total corrected granted PE */
662         qcOut[0]->totalGrantedPeCorr += qcElement[0][i]->grantedPeCorr;
663         }  /*  -end- if(ID_SCE || ID_CPE || ID_LFE) */
664 
665     }  /* -end- element loop */
666 
667     *totalAvailableBits = FDKmin(hQC->maxBitsPerFrame, (*totalAvailableBits));
668 
669     return AAC_ENC_OK;
670 }
671 
672 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
FDKaacEnc_updateUsedDynBits(INT * sumDynBitsConsumed,QC_OUT_ELEMENT * qcElement[(6)],CHANNEL_MAPPING * cm)673 static AAC_ENCODER_ERROR FDKaacEnc_updateUsedDynBits(INT*               sumDynBitsConsumed,
674                                             QC_OUT_ELEMENT*    qcElement[(6)],
675                                             CHANNEL_MAPPING*   cm)
676 {
677   INT i;
678 
679   *sumDynBitsConsumed = 0;
680 
681   for (i=0; i<cm->nElements; i++)
682   {
683       ELEMENT_INFO elInfo = cm->elInfo[i];
684 
685       if ((elInfo.elType == ID_SCE) || (elInfo.elType == ID_CPE) ||
686           (elInfo.elType == ID_LFE))
687       {
688           /* sum up bits consumed */
689           *sumDynBitsConsumed  += qcElement[i]->dynBitsUsed;
690       }  /*  -end- if(ID_SCE || ID_CPE || ID_LFE) */
691 
692   }  /* -end- element loop */
693 
694   return AAC_ENC_OK;
695 }
696 
697 
FDKaacEnc_getTotalConsumedDynBits(QC_OUT ** qcOut,INT nSubFrames)698 static INT FDKaacEnc_getTotalConsumedDynBits(QC_OUT** qcOut,
699                                    INT nSubFrames)
700 {
701     INT c, totalBits=0;
702 
703     /* sum up bit consumption for all sub frames */
704     for (c=0; c<nSubFrames; c++)
705     {
706         /* bit consumption not valid if dynamic bits
707            not available in one sub frame */
708         if (qcOut[c]->usedDynBits==-1) return -1;
709         totalBits += qcOut[c]->usedDynBits;
710     }
711 
712     return totalBits;
713 
714 }
715 
FDKaacEnc_getTotalConsumedBits(QC_OUT ** qcOut,QC_OUT_ELEMENT * qcElement[(1)][(6)],CHANNEL_MAPPING * cm,INT globHdrBits,INT nSubFrames)716 static INT FDKaacEnc_getTotalConsumedBits(QC_OUT**          qcOut,
717                                 QC_OUT_ELEMENT*   qcElement[(1)][(6)],
718                                 CHANNEL_MAPPING*  cm,
719                                 INT               globHdrBits,
720                                 INT               nSubFrames)
721 {
722     int c, i;
723     int totalUsedBits = 0;
724 
725     for (c = 0 ; c < nSubFrames ; c++ )
726     {
727         int dataBits = 0;
728         for (i=0; i<cm->nElements; i++)
729         {
730             if ((cm->elInfo[i].elType == ID_SCE) || (cm->elInfo[i].elType == ID_CPE) ||
731                 (cm->elInfo[i].elType == ID_LFE))
732             {
733                    dataBits += qcElement[c][i]->dynBitsUsed + qcElement[c][i]->staticBitsUsed + qcElement[c][i]->extBitsUsed;
734             }
735         }
736         dataBits += qcOut[c]->globalExtBits;
737 
738         totalUsedBits += (8 - (dataBits) % 8) % 8;
739         totalUsedBits += dataBits + globHdrBits;  /* header bits for every frame */
740     }
741     return totalUsedBits;
742 }
743 
FDKaacEnc_BitResRedistribution(QC_STATE * const hQC,const CHANNEL_MAPPING * const cm,const INT avgTotalBits)744 static AAC_ENCODER_ERROR FDKaacEnc_BitResRedistribution(
745         QC_STATE *const              hQC,
746         const CHANNEL_MAPPING *const cm,
747         const INT                    avgTotalBits
748         )
749 {
750     /* check bitreservoir fill level */
751     if (hQC->bitResTot < 0) {
752       return AAC_ENC_BITRES_TOO_LOW;
753     }
754     else if (hQC->bitResTot > hQC->bitResTotMax) {
755       return AAC_ENC_BITRES_TOO_HIGH;
756     }
757     else {
758       INT i, firstEl = cm->nElements-1;
759       INT totalBits = 0, totalBits_max = 0;
760 
761       int totalBitreservoir    = FDKmin(hQC->bitResTot, (hQC->maxBitsPerFrame-avgTotalBits));
762       int totalBitreservoirMax = FDKmin(hQC->bitResTotMax, (hQC->maxBitsPerFrame-avgTotalBits));
763 
764       int sc_bitResTot = CountLeadingBits(totalBitreservoir);
765       int sc_bitResTotMax = CountLeadingBits(totalBitreservoirMax);
766 
767       for (i=(cm->nElements-1); i>=0; i--) {
768         if ((cm->elInfo[i].elType == ID_SCE) || (cm->elInfo[i].elType == ID_CPE) ||
769             (cm->elInfo[i].elType == ID_LFE))
770         {
771           hQC->elementBits[i]->bitResLevelEl = (INT)fMult(hQC->elementBits[i]->relativeBitsEl, (FIXP_DBL)(totalBitreservoir<<sc_bitResTot))>>sc_bitResTot;
772           totalBits += hQC->elementBits[i]->bitResLevelEl;
773 
774           hQC->elementBits[i]->maxBitResBitsEl = (INT)fMult(hQC->elementBits[i]->relativeBitsEl, (FIXP_DBL)(totalBitreservoirMax<<sc_bitResTotMax))>>sc_bitResTotMax;
775           totalBits_max += hQC->elementBits[i]->maxBitResBitsEl;
776 
777           firstEl = i;
778         }
779       }
780       hQC->elementBits[firstEl]->bitResLevelEl   += totalBitreservoir - totalBits;
781       hQC->elementBits[firstEl]->maxBitResBitsEl += totalBitreservoirMax - totalBits_max;
782     }
783 
784     return AAC_ENC_OK;
785 }
786 
787 
FDKaacEnc_QCMain(QC_STATE * RESTRICT hQC,PSY_OUT ** psyOut,QC_OUT ** qcOut,INT avgTotalBits,CHANNEL_MAPPING * cm,AUDIO_OBJECT_TYPE aot,UINT syntaxFlags,SCHAR epConfig)788 AAC_ENCODER_ERROR FDKaacEnc_QCMain(QC_STATE* RESTRICT         hQC,
789                                    PSY_OUT**                  psyOut,
790                                    QC_OUT**                   qcOut,
791                                    INT                        avgTotalBits,
792                                    CHANNEL_MAPPING*           cm
793                                   ,AUDIO_OBJECT_TYPE          aot,
794                                    UINT                       syntaxFlags,
795                                    SCHAR                      epConfig
796                                   )
797 {
798   int i, c;
799   AAC_ENCODER_ERROR ErrorStatus = AAC_ENC_OK;
800   INT avgTotalDynBits = 0; /* maximal allowed dynamic bits for all frames */
801   INT totalAvailableBits = 0;
802   INT nSubFrames = 1;
803 
804   /*-------------------------------------------- */
805   /* redistribute total bitreservoir to elements */
806   ErrorStatus = FDKaacEnc_BitResRedistribution(hQC, cm, avgTotalBits);
807   if (ErrorStatus != AAC_ENC_OK) {
808     return ErrorStatus;
809   }
810 
811   /*-------------------------------------------- */
812   /* fastenc needs one time threshold simulation,
813      in case of multiple frames, one more guess has to be calculated */
814 
815       /*-------------------------------------------- */
816       /* helper pointer */
817       QC_OUT_ELEMENT*  qcElement[(1)][(6)];
818 
819       /* work on a copy of qcChannel and qcElement */
820       for (i=0; i<cm->nElements; i++)
821       {
822           ELEMENT_INFO elInfo = cm->elInfo[i];
823 
824           if ((elInfo.elType == ID_SCE) || (elInfo.elType == ID_CPE) ||
825               (elInfo.elType == ID_LFE))
826           {
827               /* for ( all sub frames ) ... */
828               for (c = 0 ; c < nSubFrames ; c++ )
829               {
830                   {
831                       qcElement[c][i] = qcOut[c]->qcElement[i];
832                   }
833               }
834           }
835       }
836 
837       /*-------------------------------------------- */
838       /*-------------------------------------------- */
839       if ( isConstantBitrateMode(hQC->bitrateMode) )
840       {
841           /* calc granted dynamic bits for sub frame and
842              distribute it to each element */
843           ErrorStatus = FDKaacEnc_prepareBitDistribution(
844                                  hQC,
845                                  psyOut,
846                                  qcOut,
847                                  cm,
848                                  qcElement,
849                                  avgTotalBits,
850                                 &totalAvailableBits,
851                                 &avgTotalDynBits);
852 
853           if (ErrorStatus != AAC_ENC_OK) {
854             return ErrorStatus;
855           }
856       }
857       else {
858           qcOut[0]->grantedDynBits = ((hQC->maxBitsPerFrame - (hQC->globHdrBits))&~7)
859                                    - (qcOut[0]->globalExtBits + qcOut[0]->staticBits + qcOut[0]->elementExtBits);
860           qcOut[0]->maxDynBits     = qcOut[0]->grantedDynBits;
861 
862           totalAvailableBits = hQC->maxBitsPerFrame;
863           avgTotalDynBits = 0;
864       }
865 
866 #ifdef PNS_PRECOUNT_ENABLE
867       /* Calculate estimated pns bits and substract them from grantedDynBits to get a more accurate number of available bits. */
868       if (syntaxFlags & (AC_LD|AC_ELD))
869       {
870         int estimatedPnsBits = 0, ch;
871 
872         for (ch=0; ch<cm->nChannels; ch++) {
873           qcOut[0]->pQcOutChannels[ch]->sectionData.noiseNrgBits = noisePreCount(psyOut[0]->pPsyOutChannels[ch]->noiseNrg, psyOut[0]->pPsyOutChannels[ch]->maxSfbPerGroup);
874           estimatedPnsBits += qcOut[0]->pQcOutChannels[ch]->sectionData.noiseNrgBits;
875         }
876         qcOut[0]->grantedDynBits -= estimatedPnsBits;
877       }
878 #endif
879 
880       /* for ( all sub frames ) ... */
881       for (c = 0 ; c < nSubFrames ; c++ )
882       {
883           /* for CBR and VBR mode */
884           FDKaacEnc_AdjustThresholds(hQC->hAdjThr->adjThrStateElem,
885                                      qcElement[c],
886                                      qcOut[c],
887                                      psyOut[c]->psyOutElement,
888                                      isConstantBitrateMode(hQC->bitrateMode),
889                                      cm);
890 
891       } /* -end- sub frame counter */
892 
893       /*-------------------------------------------- */
894       INT iterations[(1)][(6)];
895       INT chConstraintsFulfilled[(1)][(6)][(2)];
896       INT calculateQuant[(1)][(6)][(2)];
897       INT constraintsFulfilled[(1)][(6)];
898       /*-------------------------------------------- */
899 
900 
901       /* for ( all sub frames ) ... */
902       for (c = 0 ; c < nSubFrames ; c++ )
903       {
904           for (i=0; i<cm->nElements; i++)
905           {
906               ELEMENT_INFO elInfo = cm->elInfo[i];
907               INT ch, nChannels = elInfo.nChannelsInEl;
908 
909               if ((elInfo.elType == ID_SCE) || (elInfo.elType == ID_CPE) ||
910                   (elInfo.elType == ID_LFE))
911               {
912                       /* Turn thresholds into scalefactors, optimize bit consumption and verify conformance */
913                       FDKaacEnc_EstimateScaleFactors(psyOut[c]->psyOutElement[i]->psyOutChannel,
914                                             qcElement[c][i]->qcOutChannel,
915                                             hQC->invQuant,
916                                             cm->elInfo[i].nChannelsInEl);
917 
918 
919                       /*-------------------------------------------- */
920                       constraintsFulfilled[c][i] = 1;
921                       iterations[c][i] = 0 ;
922 
923                       for (ch = 0; ch < nChannels; ch++)
924                       {
925                           chConstraintsFulfilled[c][i][ch] = 1;
926                           calculateQuant[c][i][ch] = 1;
927                       }
928 
929                       /*-------------------------------------------- */
930 
931               }  /*  -end- if(ID_SCE || ID_CPE || ID_LFE) */
932 
933           }  /* -end- element loop */
934 
935           qcOut[c]->usedDynBits = -1;
936 
937       } /* -end- sub frame counter */
938 
939 
940 
941       INT quantizationDone = 0;
942       INT sumDynBitsConsumedTotal  = 0;
943       INT decreaseBitConsumption = -1; /* no direction yet! */
944 
945       /*-------------------------------------------- */
946       /* -start- Quantization loop ...               */
947       /*-------------------------------------------- */
948       do /* until max allowed bits per frame and maxDynBits!=-1*/
949       {
950           quantizationDone = 0;
951 
952               c = 0;              /* get frame to process */
953 
954               for (i=0; i<cm->nElements; i++)
955               {
956                   ELEMENT_INFO elInfo = cm->elInfo[i];
957                   INT ch, nChannels = elInfo.nChannelsInEl;
958 
959                   if ((elInfo.elType == ID_SCE) || (elInfo.elType == ID_CPE) ||
960                       (elInfo.elType == ID_LFE))
961                   {
962                       do /* until spectral values < MAX_QUANT */
963                       {
964                           /*-------------------------------------------- */
965                           if (!constraintsFulfilled[c][i])
966                           {
967                               FDKaacEnc_reduceBitConsumption(&iterations[c][i],
968                                                     hQC->maxIterations,
969                                                     (decreaseBitConsumption) ? 1 : -1,
970                                                     chConstraintsFulfilled[c][i],
971                                                     calculateQuant[c][i],
972                                                     nChannels,
973                                                     psyOut[c]->psyOutElement[i],
974                                                     qcOut[c],
975                                                     qcElement[c][i],
976                                                     hQC->elementBits[i],
977                                                     aot,
978                                                     syntaxFlags,
979                                                     epConfig);
980                           }
981 
982                           /*-------------------------------------------- */
983                           /*-------------------------------------------- */
984                           constraintsFulfilled[c][i] = 1 ;
985 
986                           /*-------------------------------------------- */
987                           /* quantize spectrum (per each channel) */
988                           for (ch = 0; ch < nChannels; ch++)
989                           {
990                               /*-------------------------------------------- */
991                               chConstraintsFulfilled[c][i][ch] = 1;
992 
993                               /*-------------------------------------------- */
994 
995                               if (calculateQuant[c][i][ch])
996                               {
997                                   QC_OUT_CHANNEL* qcOutCh = qcElement[c][i]->qcOutChannel[ch];
998                                   PSY_OUT_CHANNEL* psyOutCh = psyOut[c]->psyOutElement[i]->psyOutChannel[ch];
999 
1000                                   calculateQuant[c][i][ch] = 0; /* calculate quantization only if necessary */
1001 
1002                                   /*-------------------------------------------- */
1003                                   FDKaacEnc_QuantizeSpectrum(psyOutCh->sfbCnt,
1004                                                              psyOutCh->maxSfbPerGroup,
1005                                                              psyOutCh->sfbPerGroup,
1006                                                              psyOutCh->sfbOffsets,
1007                                                              qcOutCh->mdctSpectrum,
1008                                                              qcOutCh->globalGain,
1009                                                              qcOutCh->scf,
1010                                                              qcOutCh->quantSpec) ;
1011 
1012                                   /*-------------------------------------------- */
1013                                   if (FDKaacEnc_calcMaxValueInSfb(psyOutCh->sfbCnt,
1014                                                         psyOutCh->maxSfbPerGroup,
1015                                                         psyOutCh->sfbPerGroup,
1016                                                         psyOutCh->sfbOffsets,
1017                                                         qcOutCh->quantSpec,
1018                                                         qcOutCh->maxValueInSfb) > MAX_QUANT)
1019                                   {
1020                                     chConstraintsFulfilled[c][i][ch] = 0;
1021                                     constraintsFulfilled[c][i] = 0 ;
1022                                     /* if quanizted value out of range; increase global gain! */
1023                                     decreaseBitConsumption = 1;
1024                                   }
1025 
1026                                   /*-------------------------------------------- */
1027 
1028                               } /* if calculateQuant[c][i][ch] */
1029 
1030                           } /* channel loop */
1031 
1032                           /*-------------------------------------------- */
1033                           /* quantize spectrum (per each channel) */
1034 
1035                           /*-------------------------------------------- */
1036 
1037                       } while (!constraintsFulfilled[c][i]) ; /* does not regard bit consumption */
1038 
1039 
1040                       /*-------------------------------------------- */
1041                       /*-------------------------------------------- */
1042                       qcElement[c][i]->dynBitsUsed = 0 ; /* reset dynamic bits */
1043 
1044                       /* quantization valid in current channel! */
1045                       for (ch = 0; ch < nChannels; ch++)
1046                       {
1047                           QC_OUT_CHANNEL* qcOutCh = qcElement[c][i]->qcOutChannel[ch];
1048                           PSY_OUT_CHANNEL *psyOutCh = psyOut[c]->psyOutElement[i]->psyOutChannel[ch];
1049 
1050                           /* count dynamic bits */
1051                           INT chDynBits = FDKaacEnc_dynBitCount(hQC->hBitCounter,
1052                                                                 qcOutCh->quantSpec,
1053                                                                 qcOutCh->maxValueInSfb,
1054                                                                 qcOutCh->scf,
1055                                                                 psyOutCh->lastWindowSequence,
1056                                                                 psyOutCh->sfbCnt,
1057                                                                 psyOutCh->maxSfbPerGroup,
1058                                                                 psyOutCh->sfbPerGroup,
1059                                                                 psyOutCh->sfbOffsets,
1060                                                                 &qcOutCh->sectionData,
1061                                                                 psyOutCh->noiseNrg,
1062                                                                 psyOutCh->isBook,
1063                                                                 psyOutCh->isScale,
1064                                                                 syntaxFlags) ;
1065 
1066                           /* sum up dynamic channel bits */
1067                           qcElement[c][i]->dynBitsUsed += chDynBits;
1068                       }
1069 
1070                       /* save dynBitsUsed for correction of bits2pe relation */
1071                       if(hQC->hAdjThr->adjThrStateElem[i]->dynBitsLast==-1) {
1072                           hQC->hAdjThr->adjThrStateElem[i]->dynBitsLast = qcElement[c][i]->dynBitsUsed;
1073                       }
1074                   }  /*  -end- if(ID_SCE || ID_CPE || ID_LFE) */
1075 
1076               }  /* -end- element loop */
1077 
1078               /* update dynBits of current subFrame */
1079               FDKaacEnc_updateUsedDynBits(&qcOut[c]->usedDynBits,
1080                                  qcElement[c],
1081                                  cm);
1082 
1083               /* get total consumed bits, dyn bits in all sub frames have to be valid */
1084               sumDynBitsConsumedTotal = FDKaacEnc_getTotalConsumedDynBits(qcOut, nSubFrames);
1085 
1086               if (sumDynBitsConsumedTotal==-1)
1087               {
1088                   quantizationDone = 0; /* bit consumption not valid in all sub frames */
1089               }
1090               else
1091               {
1092                 int sumBitsConsumedTotal = FDKaacEnc_getTotalConsumedBits(qcOut, qcElement, cm, hQC->globHdrBits, nSubFrames);
1093 
1094                 /* in all frames are valid dynamic bits */
1095                 if ( ((sumBitsConsumedTotal < totalAvailableBits) || qcOut[c]->usedDynBits==0) && (decreaseBitConsumption==1) && checkMinFrameBitsDemand(qcOut,hQC->minBitsPerFrame,nSubFrames)
1096                       /*()*/  )
1097                 {
1098                     quantizationDone = 1; /* exit bit adjustment */
1099                 }
1100                 if (sumBitsConsumedTotal > totalAvailableBits && (decreaseBitConsumption==0) )
1101 //                      /*()*/  )
1102                 {
1103                     quantizationDone = 0; /* reset! */
1104                     break;
1105                 }
1106               }
1107 
1108 
1109           /*-------------------------------------------- */
1110 
1111               int emergencyIterations = 1;
1112               int dynBitsOvershoot    = 0;
1113 
1114               for (c = 0 ; c < nSubFrames ; c++ )
1115               {
1116                   for (i=0; i<cm->nElements; i++)
1117                   {
1118                       ELEMENT_INFO elInfo = cm->elInfo[i];
1119 
1120                       if ((elInfo.elType == ID_SCE) || (elInfo.elType == ID_CPE) ||
1121                           (elInfo.elType == ID_LFE))
1122                       {
1123                         /* iteration limitation */
1124                         emergencyIterations &= ((iterations[c][i] < hQC->maxIterations) ? 0 : 1);
1125                       }
1126                   }
1127                   /* detection if used dyn bits exceeds the maximal allowed criterion */
1128                   dynBitsOvershoot |= ((qcOut[c]->usedDynBits > qcOut[c]->maxDynBits) ? 1 : 0);
1129               }
1130 
1131               if (quantizationDone==0 || dynBitsOvershoot)
1132               {
1133 
1134                   int sumBitsConsumedTotal = FDKaacEnc_getTotalConsumedBits(qcOut, qcElement, cm, hQC->globHdrBits, nSubFrames);
1135 
1136                   if ( (sumDynBitsConsumedTotal >= avgTotalDynBits) || (sumDynBitsConsumedTotal==0) ) {
1137                       quantizationDone = 1;
1138                   }
1139                   if (emergencyIterations && (sumBitsConsumedTotal < totalAvailableBits)) {
1140                       quantizationDone = 1;
1141                   }
1142                   if ((sumBitsConsumedTotal > totalAvailableBits) || !checkMinFrameBitsDemand(qcOut,hQC->minBitsPerFrame,nSubFrames)) {
1143                       quantizationDone = 0;
1144                   }
1145                   if ((sumBitsConsumedTotal < totalAvailableBits) && checkMinFrameBitsDemand(qcOut,hQC->minBitsPerFrame,nSubFrames)) {
1146                       decreaseBitConsumption = 0;
1147                   }
1148                   else {
1149                       decreaseBitConsumption = 1;
1150                   }
1151 
1152                   if (dynBitsOvershoot) {
1153                      quantizationDone = 0;
1154                      decreaseBitConsumption = 1;
1155                   }
1156 
1157                   /* reset constraints fullfilled flags */
1158                   FDKmemclear(constraintsFulfilled, sizeof(constraintsFulfilled));
1159                   FDKmemclear(chConstraintsFulfilled, sizeof(chConstraintsFulfilled));
1160 
1161 
1162               }/* quantizationDone */
1163 
1164       } while (!quantizationDone) ;
1165 
1166       /*-------------------------------------------- */
1167       /* ... -end- Quantization loop                 */
1168       /*-------------------------------------------- */
1169 
1170   /*-------------------------------------------- */
1171   /*-------------------------------------------- */
1172 
1173   return AAC_ENC_OK;
1174 }
1175 
1176 
FDKaacEnc_reduceBitConsumption(int * iterations,const int maxIterations,int gainAdjustment,int * chConstraintsFulfilled,int * calculateQuant,int nChannels,PSY_OUT_ELEMENT * psyOutElement,QC_OUT * qcOut,QC_OUT_ELEMENT * qcOutElement,ELEMENT_BITS * elBits,AUDIO_OBJECT_TYPE aot,UINT syntaxFlags,SCHAR epConfig)1177 static AAC_ENCODER_ERROR FDKaacEnc_reduceBitConsumption(int*             iterations,
1178                                               const int        maxIterations,
1179                                               int              gainAdjustment,
1180                                               int*             chConstraintsFulfilled,
1181                                               int*             calculateQuant,
1182                                               int              nChannels,
1183                                               PSY_OUT_ELEMENT* psyOutElement,
1184                                               QC_OUT*          qcOut,
1185                                               QC_OUT_ELEMENT*  qcOutElement,
1186                                               ELEMENT_BITS*    elBits,
1187                                               AUDIO_OBJECT_TYPE aot,
1188                                               UINT             syntaxFlags,
1189                                               SCHAR            epConfig)
1190 {
1191   int ch;
1192 
1193   /** SOLVING PROBLEM **/
1194   if ((*iterations)++ >= maxIterations)
1195   {
1196     if (qcOutElement->dynBitsUsed==0) {
1197     }
1198     /* crash recovery */
1199     else {
1200       INT bitsToSave = 0;
1201       if ( (bitsToSave = fixMax((qcOutElement->dynBitsUsed + 8) - (elBits->bitResLevelEl + qcOutElement->grantedDynBits),
1202                                 (qcOutElement->dynBitsUsed + qcOutElement->staticBitsUsed + 8) - (elBits->maxBitsEl))) > 0 )
1203       {
1204         FDKaacEnc_crashRecovery(nChannels,
1205                       psyOutElement,
1206                       qcOut,
1207                       qcOutElement,
1208                       bitsToSave,
1209                       aot,
1210                       syntaxFlags,
1211                       epConfig) ;
1212     }
1213     else
1214     {
1215       for (ch = 0; ch < nChannels; ch++)
1216       {
1217           qcOutElement->qcOutChannel[ch]->globalGain += 1;
1218       }
1219     }
1220     for (ch = 0; ch < nChannels; ch++)
1221     {
1222       calculateQuant[ch] = 1;
1223     }
1224   }
1225   }
1226   else /* iterations >= maxIterations */
1227   {
1228     /* increase gain (+ next iteration) */
1229     for (ch = 0; ch < nChannels; ch++)
1230     {
1231       if(!chConstraintsFulfilled[ch])
1232       {
1233           qcOutElement->qcOutChannel[ch]->globalGain += gainAdjustment ;
1234           calculateQuant[ch] = 1; /* global gain has changed, recalculate quantization in next iteration! */
1235       }
1236     }
1237   }
1238 
1239   return AAC_ENC_OK;
1240 }
1241 
FDKaacEnc_updateFillBits(CHANNEL_MAPPING * cm,QC_STATE * qcKernel,ELEMENT_BITS * RESTRICT elBits[(6)],QC_OUT ** qcOut)1242 AAC_ENCODER_ERROR FDKaacEnc_updateFillBits(CHANNEL_MAPPING*          cm,
1243                                            QC_STATE*                 qcKernel,
1244                                            ELEMENT_BITS* RESTRICT    elBits[(6)],
1245                                            QC_OUT**                  qcOut)
1246 {
1247   switch (qcKernel->bitrateMode) {
1248     case QCDATA_BR_MODE_SFR:
1249       break;
1250 
1251     case QCDATA_BR_MODE_FF:
1252        break;
1253 
1254     case QCDATA_BR_MODE_VBR_1:
1255     case QCDATA_BR_MODE_VBR_2:
1256     case QCDATA_BR_MODE_VBR_3:
1257     case QCDATA_BR_MODE_VBR_4:
1258     case QCDATA_BR_MODE_VBR_5:
1259       qcOut[0]->totFillBits = (qcOut[0]->grantedDynBits - qcOut[0]->usedDynBits)&7; /* precalculate alignment bits */
1260       break;
1261 
1262     case QCDATA_BR_MODE_CBR:
1263     case QCDATA_BR_MODE_INVALID:
1264     default:
1265       INT bitResSpace = qcKernel->bitResTotMax - qcKernel->bitResTot ;
1266       /* processing fill-bits */
1267       INT deltaBitRes = qcOut[0]->grantedDynBits - qcOut[0]->usedDynBits ;
1268       qcOut[0]->totFillBits = fixMax((deltaBitRes&7), (deltaBitRes - (fixMax(0,bitResSpace-7)&~7)));
1269       break;
1270   } /* switch (qcKernel->bitrateMode) */
1271 
1272   return AAC_ENC_OK;
1273 }
1274 
1275 
1276 
1277 
1278 /*********************************************************************************
1279 
1280          functionname: FDKaacEnc_calcMaxValueInSfb
1281          description:
1282          return:
1283 
1284 **********************************************************************************/
1285 
FDKaacEnc_calcMaxValueInSfb(INT sfbCnt,INT maxSfbPerGroup,INT sfbPerGroup,INT * RESTRICT sfbOffset,SHORT * RESTRICT quantSpectrum,UINT * RESTRICT maxValue)1286 static INT FDKaacEnc_calcMaxValueInSfb(INT   sfbCnt,
1287                              INT   maxSfbPerGroup,
1288                              INT   sfbPerGroup,
1289                              INT  *RESTRICT sfbOffset,
1290                              SHORT *RESTRICT quantSpectrum,
1291                              UINT *RESTRICT maxValue)
1292 {
1293   INT sfbOffs,sfb;
1294   INT maxValueAll = 0;
1295 
1296   for (sfbOffs=0;sfbOffs<sfbCnt;sfbOffs+=sfbPerGroup)
1297     for (sfb = 0; sfb < maxSfbPerGroup; sfb++)
1298     {
1299       INT line;
1300       INT maxThisSfb = 0;
1301       for (line = sfbOffset[sfbOffs+sfb]; line < sfbOffset[sfbOffs+sfb+1]; line++)
1302       {
1303         INT tmp = fixp_abs(quantSpectrum[line]);
1304         maxThisSfb = fixMax(tmp, maxThisSfb);
1305       }
1306 
1307       maxValue[sfbOffs+sfb] = maxThisSfb;
1308       maxValueAll = fixMax(maxThisSfb, maxValueAll);
1309     }
1310   return maxValueAll;
1311 }
1312 
1313 
1314 /*********************************************************************************
1315 
1316          functionname: FDKaacEnc_updateBitres
1317          description:
1318          return:
1319 
1320 **********************************************************************************/
FDKaacEnc_updateBitres(CHANNEL_MAPPING * cm,QC_STATE * qcKernel,QC_OUT ** qcOut)1321 void FDKaacEnc_updateBitres(CHANNEL_MAPPING *cm,
1322                             QC_STATE* qcKernel,
1323                             QC_OUT** qcOut)
1324 {
1325   switch (qcKernel->bitrateMode) {
1326     case QCDATA_BR_MODE_FF:
1327     case QCDATA_BR_MODE_VBR_1:
1328     case QCDATA_BR_MODE_VBR_2:
1329     case QCDATA_BR_MODE_VBR_3:
1330     case QCDATA_BR_MODE_VBR_4:
1331     case QCDATA_BR_MODE_VBR_5:
1332       /* variable bitrate */
1333       qcKernel->bitResTot = FDKmin(qcKernel->maxBitsPerFrame, qcKernel->bitResTotMax);
1334       break;
1335 
1336     case QCDATA_BR_MODE_CBR:
1337     case QCDATA_BR_MODE_SFR:
1338     case QCDATA_BR_MODE_INVALID:
1339     default:
1340       int c = 0;
1341       /* constant bitrate */
1342       {
1343         qcKernel->bitResTot += qcOut[c]->grantedDynBits - (qcOut[c]->usedDynBits + qcOut[c]->totFillBits + qcOut[c]->alignBits);
1344       }
1345       break;
1346   }
1347 }
1348 
1349 /*********************************************************************************
1350 
1351          functionname: FDKaacEnc_FinalizeBitConsumption
1352          description:
1353          return:
1354 
1355 **********************************************************************************/
FDKaacEnc_FinalizeBitConsumption(CHANNEL_MAPPING * cm,QC_STATE * qcKernel,QC_OUT * qcOut,QC_OUT_ELEMENT ** qcElement,HANDLE_TRANSPORTENC hTpEnc,AUDIO_OBJECT_TYPE aot,UINT syntaxFlags,SCHAR epConfig)1356 AAC_ENCODER_ERROR FDKaacEnc_FinalizeBitConsumption(CHANNEL_MAPPING *cm,
1357                                                    QC_STATE *qcKernel,
1358                                                    QC_OUT *qcOut,
1359                                                    QC_OUT_ELEMENT** qcElement,
1360                                                    HANDLE_TRANSPORTENC hTpEnc,
1361                                                    AUDIO_OBJECT_TYPE   aot,
1362                                                    UINT                syntaxFlags,
1363                                                    SCHAR               epConfig)
1364 {
1365   QC_OUT_EXTENSION fillExtPayload;
1366   INT totFillBits, alignBits;
1367 
1368   /* Get total consumed bits in AU */
1369   qcOut->totalBits = qcOut->staticBits + qcOut->usedDynBits  + qcOut->totFillBits +
1370                      qcOut->elementExtBits + qcOut->globalExtBits;
1371 
1372   if (qcKernel->bitrateMode==QCDATA_BR_MODE_CBR) {
1373 
1374     /* Now we can get the exact transport bit amount, and hopefully it is equal to the estimated value */
1375     INT exactTpBits = transportEnc_GetStaticBits(hTpEnc, qcOut->totalBits);
1376 
1377     if (exactTpBits != qcKernel->globHdrBits) {
1378       INT diffFillBits = 0;
1379 
1380       /* How many bits can be taken by bitreservoir */
1381       const INT bitresSpace = qcKernel->bitResTotMax - (qcKernel->bitResTot + (qcOut->grantedDynBits - (qcOut->usedDynBits + qcOut->totFillBits) ) );
1382 
1383       /* Number of bits which can be moved to bitreservoir. */
1384       const INT bitsToBitres = qcKernel->globHdrBits - exactTpBits;
1385       FDK_ASSERT(bitsToBitres>=0); /* is always positive */
1386 
1387       /* If bitreservoir can not take all bits, move ramaining bits to fillbits */
1388       diffFillBits = FDKmax(0, bitsToBitres - bitresSpace);
1389 
1390       /* Assure previous alignment */
1391       diffFillBits = (diffFillBits+7)&~7;
1392 
1393       /* Move as many bits as possible to bitreservoir */
1394       qcKernel->bitResTot    += (bitsToBitres-diffFillBits);
1395 
1396       /* Write remaing bits as fill bits */
1397       qcOut->totFillBits     += diffFillBits;
1398       qcOut->totalBits       += diffFillBits;
1399       qcOut->grantedDynBits  += diffFillBits;
1400 
1401       /* Get new header bits */
1402       qcKernel->globHdrBits = transportEnc_GetStaticBits(hTpEnc, qcOut->totalBits);
1403 
1404       if (qcKernel->globHdrBits != exactTpBits) {
1405         /* In previous step, fill bits and corresponding total bits were changed when bitreservoir was completely filled.
1406            Now we can take the too much taken bits caused by header overhead from bitreservoir.
1407          */
1408         qcKernel->bitResTot -= (qcKernel->globHdrBits - exactTpBits);
1409       }
1410     }
1411 
1412   } /* MODE_CBR */
1413 
1414   /* Update exact number of consumed header bits. */
1415   qcKernel->globHdrBits = transportEnc_GetStaticBits(hTpEnc, qcOut->totalBits);
1416 
1417   /* Save total fill bits and distribut to alignment and fill bits */
1418   totFillBits = qcOut->totFillBits;
1419 
1420   /* fake a fill extension payload */
1421   FDKmemclear(&fillExtPayload, sizeof(QC_OUT_EXTENSION));
1422 
1423   fillExtPayload.type = EXT_FILL_DATA;
1424   fillExtPayload.nPayloadBits = totFillBits;
1425 
1426   /* ask bitstream encoder how many of that bits can be written in a fill extension data entity */
1427   qcOut->totFillBits = FDKaacEnc_writeExtensionData( NULL,
1428                                                     &fillExtPayload,
1429                                                      0, 0,
1430                                                      syntaxFlags,
1431                                                      aot,
1432                                                      epConfig );
1433 
1434   /* now distribute extra fillbits and alignbits */
1435   alignBits = 7 - (qcOut->staticBits + qcOut->usedDynBits + qcOut->elementExtBits
1436                    + qcOut->totFillBits + qcOut->globalExtBits -1)%8;
1437 
1438   /* Maybe we could remove this */
1439   if( ((alignBits + qcOut->totFillBits - totFillBits)==8) && (qcOut->totFillBits>8) )
1440         qcOut->totFillBits -= 8;
1441 
1442   qcOut->totalBits = qcOut->staticBits + qcOut->usedDynBits + qcOut->totFillBits +
1443                      alignBits + qcOut->elementExtBits + qcOut->globalExtBits;
1444 
1445   if ( (qcOut->totalBits>qcKernel->maxBitsPerFrame) || (qcOut->totalBits<qcKernel->minBitsPerFrame) ) {
1446     return AAC_ENC_QUANT_ERROR;
1447   }
1448 
1449   qcOut->alignBits = alignBits;
1450 
1451   return AAC_ENC_OK;
1452 }
1453 
1454 
1455 
1456 /*********************************************************************************
1457 
1458          functionname: FDKaacEnc_crashRecovery
1459          description:  fulfills constraints by means of brute force...
1460                        => bits are saved by cancelling out spectral lines!!
1461                           (beginning at the highest frequencies)
1462          return:       errorcode
1463 
1464 **********************************************************************************/
1465 
FDKaacEnc_crashRecovery(INT nChannels,PSY_OUT_ELEMENT * psyOutElement,QC_OUT * qcOut,QC_OUT_ELEMENT * qcElement,INT bitsToSave,AUDIO_OBJECT_TYPE aot,UINT syntaxFlags,SCHAR epConfig)1466 static void FDKaacEnc_crashRecovery(INT               nChannels,
1467                           PSY_OUT_ELEMENT*  psyOutElement,
1468                           QC_OUT*           qcOut,
1469                           QC_OUT_ELEMENT   *qcElement,
1470                           INT               bitsToSave,
1471                           AUDIO_OBJECT_TYPE aot,
1472                           UINT              syntaxFlags,
1473                           SCHAR             epConfig)
1474 {
1475   INT ch ;
1476   INT savedBits = 0 ;
1477   INT sfb, sfbGrp ;
1478   INT bitsPerScf[(2)][MAX_GROUPED_SFB] ;
1479   INT sectionToScf[(2)][MAX_GROUPED_SFB] ;
1480   INT *sfbOffset ;
1481   INT sect, statBitsNew ;
1482   QC_OUT_CHANNEL **qcChannel = qcElement->qcOutChannel;
1483   PSY_OUT_CHANNEL **psyChannel = psyOutElement->psyOutChannel;
1484 
1485   /* create a table which converts frq-bins to bit-demand...    [bitsPerScf] */
1486   /* ...and another one which holds the corresponding sections [sectionToScf] */
1487   for (ch = 0; ch < nChannels; ch++)
1488   {
1489     sfbOffset = psyChannel[ch]->sfbOffsets ;
1490 
1491     for (sect = 0; sect < qcChannel[ch]->sectionData.noOfSections; sect++)
1492     {
1493       INT sfb ;
1494       INT codeBook = qcChannel[ch]->sectionData.huffsection[sect].codeBook ;
1495 
1496       for (sfb = qcChannel[ch]->sectionData.huffsection[sect].sfbStart;
1497            sfb < qcChannel[ch]->sectionData.huffsection[sect].sfbStart +
1498                  qcChannel[ch]->sectionData.huffsection[sect].sfbCnt;
1499            sfb++)
1500       {
1501         bitsPerScf[ch][sfb] = 0;
1502         if ( (codeBook != CODE_BOOK_PNS_NO) /*&&
1503              (sfb < (qcChannel[ch]->sectionData.noOfGroups*qcChannel[ch]->sectionData.maxSfbPerGroup))*/ )
1504         {
1505             INT sfbStartLine = sfbOffset[sfb] ;
1506             INT noOfLines    = sfbOffset[sfb+1] - sfbStartLine ;
1507             bitsPerScf[ch][sfb] = FDKaacEnc_countValues(&(qcChannel[ch]->quantSpec[sfbStartLine]), noOfLines, codeBook) ;
1508         }
1509         sectionToScf[ch][sfb] = sect ;
1510       }
1511 
1512     }
1513   }
1514 
1515   /* LOWER [maxSfb] IN BOTH CHANNELS!! */
1516   /* Attention: in case of stereo: maxSfbL == maxSfbR, GroupingL == GroupingR ; */
1517 
1518   for (sfb = qcChannel[0]->sectionData.maxSfbPerGroup-1; sfb >= 0; sfb--)
1519   {
1520     for (sfbGrp = 0; sfbGrp < psyChannel[0]->sfbCnt; sfbGrp += psyChannel[0]->sfbPerGroup)
1521     {
1522       for (ch = 0; ch < nChannels; ch++)
1523       {
1524         int sect = sectionToScf[ch][sfbGrp+sfb];
1525         qcChannel[ch]->sectionData.huffsection[sect].sfbCnt-- ;
1526         savedBits += bitsPerScf[ch][sfbGrp+sfb] ;
1527 
1528         if (qcChannel[ch]->sectionData.huffsection[sect].sfbCnt == 0) {
1529           savedBits += (psyChannel[ch]->lastWindowSequence!=SHORT_WINDOW) ? FDKaacEnc_sideInfoTabLong[0]
1530                                                                       : FDKaacEnc_sideInfoTabShort[0];
1531         }
1532       }
1533     }
1534 
1535     /* ...have enough bits been saved? */
1536     if (savedBits >= bitsToSave)
1537       break ;
1538 
1539   } /* sfb loop */
1540 
1541   /* if not enough bits saved,
1542      clean whole spectrum and remove side info overhead */
1543   if (sfb == -1) {
1544     sfb = 0 ;
1545   }
1546 
1547   for (ch = 0; ch < nChannels; ch++)
1548   {
1549     qcChannel[ch]->sectionData.maxSfbPerGroup = sfb ;
1550     psyChannel[ch]->maxSfbPerGroup = sfb ;
1551     /* when no spectrum is coded save tools info in bitstream */
1552     if(sfb==0) {
1553       FDKmemclear(&psyChannel[ch]->tnsInfo, sizeof(TNS_INFO));
1554       FDKmemclear(&psyOutElement->toolsInfo, sizeof(TOOLSINFO));
1555     }
1556   }
1557   /* dynamic bits will be updated in iteration loop */
1558 
1559   { /* if stop sfb has changed save bits in side info, e.g. MS or TNS coding */
1560     ELEMENT_INFO elInfo;
1561 
1562     FDKmemclear(&elInfo, sizeof(ELEMENT_INFO));
1563     elInfo.nChannelsInEl = nChannels;
1564     elInfo.elType = (nChannels == 2) ? ID_CPE : ID_SCE;
1565 
1566     FDKaacEnc_ChannelElementWrite( NULL, &elInfo, NULL,
1567                                    psyOutElement,
1568                                    psyChannel,
1569                                    syntaxFlags,
1570                                    aot,
1571                                    epConfig,
1572                                   &statBitsNew,
1573                                    0 );
1574   }
1575 
1576   savedBits = qcElement->staticBitsUsed - statBitsNew;
1577 
1578   /* update static and dynamic bits */
1579   qcElement->staticBitsUsed -= savedBits;
1580   qcElement->grantedDynBits += savedBits;
1581 
1582   qcOut->staticBits     -= savedBits;
1583   qcOut->grantedDynBits += savedBits;
1584   qcOut->maxDynBits     += savedBits;
1585 
1586 
1587 }
1588 
1589 
1590 
FDKaacEnc_QCClose(QC_STATE ** phQCstate,QC_OUT ** phQC)1591 void  FDKaacEnc_QCClose (QC_STATE  **phQCstate, QC_OUT **phQC)
1592 {
1593   int n, i;
1594 
1595   if (phQC!=NULL) {
1596 
1597     for (n=0;n<(1);n++) {
1598       if (phQC[n] != NULL) {
1599         QC_OUT    *hQC      = phQC[n];
1600         for (i=0; i<(6); i++) {
1601         }
1602 
1603         for (i=0; i<(6); i++) {
1604           if (hQC->qcElement[i])
1605             FreeRam_aacEnc_QCelement(&hQC->qcElement[i]);
1606         }
1607 
1608         FreeRam_aacEnc_QCout(&phQC[n]);
1609       }
1610     }
1611   }
1612 
1613   if (phQCstate!=NULL) {
1614     if (*phQCstate != NULL) {
1615       QC_STATE  *hQCstate = *phQCstate;
1616 
1617       if (hQCstate->hAdjThr != NULL)
1618         FDKaacEnc_AdjThrClose(&hQCstate->hAdjThr);
1619 
1620       if (hQCstate->hBitCounter != NULL)
1621         FDKaacEnc_BCClose(&hQCstate->hBitCounter);
1622 
1623       for (i=0; i<(6); i++) {
1624         if (hQCstate->elementBits[i]!=NULL) {
1625           FreeRam_aacEnc_ElementBits(&hQCstate->elementBits[i]);
1626         }
1627       }
1628       FreeRam_aacEnc_QCstate(phQCstate);
1629     }
1630   }
1631 }
1632 
1633