• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* -----------------------------------------------------------------------------
2 Software License for The Fraunhofer FDK AAC Codec Library for Android
3 
4 © Copyright  1995 - 2019 Fraunhofer-Gesellschaft zur Förderung der angewandten
5 Forschung e.V. All rights reserved.
6 
7  1.    INTRODUCTION
8 The Fraunhofer FDK AAC Codec Library for Android ("FDK AAC Codec") is software
9 that implements the MPEG Advanced Audio Coding ("AAC") encoding and decoding
10 scheme for digital audio. This FDK AAC Codec software is intended to be used on
11 a wide variety of Android devices.
12 
13 AAC's HE-AAC and HE-AAC v2 versions are regarded as today's most efficient
14 general perceptual audio codecs. AAC-ELD is considered the best-performing
15 full-bandwidth communications codec by independent studies and is widely
16 deployed. AAC has been standardized by ISO and IEC as part of the MPEG
17 specifications.
18 
19 Patent licenses for necessary patent claims for the FDK AAC Codec (including
20 those of Fraunhofer) may be obtained through Via Licensing
21 (www.vialicensing.com) or through the respective patent owners individually for
22 the purpose of encoding or decoding bit streams in products that are compliant
23 with the ISO/IEC MPEG audio standards. Please note that most manufacturers of
24 Android devices already license these patent claims through Via Licensing or
25 directly from the patent owners, and therefore FDK AAC Codec software may
26 already be covered under those patent licenses when it is used for those
27 licensed purposes only.
28 
29 Commercially-licensed AAC software libraries, including floating-point versions
30 with enhanced sound quality, are also available from Fraunhofer. Users are
31 encouraged to check the Fraunhofer website for additional applications
32 information and documentation.
33 
34 2.    COPYRIGHT LICENSE
35 
36 Redistribution and use in source and binary forms, with or without modification,
37 are permitted without payment of copyright license fees provided that you
38 satisfy the following conditions:
39 
40 You must retain the complete text of this software license in redistributions of
41 the FDK AAC Codec or your modifications thereto in source code form.
42 
43 You must retain the complete text of this software license in the documentation
44 and/or other materials provided with redistributions of the FDK AAC Codec or
45 your modifications thereto in binary form. You must make available free of
46 charge copies of the complete source code of the FDK AAC Codec and your
47 modifications thereto to recipients of copies in binary form.
48 
49 The name of Fraunhofer may not be used to endorse or promote products derived
50 from this library without prior written permission.
51 
52 You may not charge copyright license fees for anyone to use, copy or distribute
53 the FDK AAC Codec software or your modifications thereto.
54 
55 Your modified versions of the FDK AAC Codec must carry prominent notices stating
56 that you changed the software and the date of any change. For modified versions
57 of the FDK AAC Codec, the term "Fraunhofer FDK AAC Codec Library for Android"
58 must be replaced by the term "Third-Party Modified Version of the Fraunhofer FDK
59 AAC Codec Library for Android."
60 
61 3.    NO PATENT LICENSE
62 
63 NO EXPRESS OR IMPLIED LICENSES TO ANY PATENT CLAIMS, including without
64 limitation the patents of Fraunhofer, ARE GRANTED BY THIS SOFTWARE LICENSE.
65 Fraunhofer provides no warranty of patent non-infringement with respect to this
66 software.
67 
68 You may use this FDK AAC Codec software or modifications thereto only for
69 purposes that are authorized by appropriate patent licenses.
70 
71 4.    DISCLAIMER
72 
73 This FDK AAC Codec software is provided by Fraunhofer on behalf of the copyright
74 holders and contributors "AS IS" and WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES,
75 including but not limited to the implied warranties of merchantability and
76 fitness for a particular purpose. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
77 CONTRIBUTORS BE LIABLE for any direct, indirect, incidental, special, exemplary,
78 or consequential damages, including but not limited to procurement of substitute
79 goods or services; loss of use, data, or profits, or business interruption,
80 however caused and on any theory of liability, whether in contract, strict
81 liability, or tort (including negligence), arising in any way out of the use of
82 this software, even if advised of the possibility of such damage.
83 
84 5.    CONTACT INFORMATION
85 
86 Fraunhofer Institute for Integrated Circuits IIS
87 Attention: Audio and Multimedia Departments - FDK AAC LL
88 Am Wolfsmantel 33
89 91058 Erlangen, Germany
90 
91 www.iis.fraunhofer.de/amm
92 amm-info@iis.fraunhofer.de
93 ----------------------------------------------------------------------------- */
94 
95 /**************************** AAC encoder library ******************************
96 
97    Author(s):   M. Werner
98 
99    Description: Quantizing & coding
100 
101 *******************************************************************************/
102 
103 #include "qc_main.h"
104 #include "quantize.h"
105 #include "interface.h"
106 #include "adj_thr.h"
107 #include "sf_estim.h"
108 #include "bit_cnt.h"
109 #include "dyn_bits.h"
110 #include "channel_map.h"
111 #include "aacEnc_ram.h"
112 
113 #include "genericStds.h"
114 
115 #define AACENC_DZQ_BR_THR 32000 /* Dead zone quantizer bitrate threshold */
116 
117 typedef struct {
118   QCDATA_BR_MODE bitrateMode;
119   LONG vbrQualFactor;
120 } TAB_VBR_QUAL_FACTOR;
121 
122 static const TAB_VBR_QUAL_FACTOR tableVbrQualFactor[] = {
123     {QCDATA_BR_MODE_VBR_1,
124      FL2FXCONST_DBL(0.150f)}, /* Approx.  32 kbps mono   AAC-LC + SBR + PS */
125     {QCDATA_BR_MODE_VBR_2,
126      FL2FXCONST_DBL(0.162f)}, /* Approx.  64 kbps stereo AAC-LC + SBR      */
127     {QCDATA_BR_MODE_VBR_3,
128      FL2FXCONST_DBL(0.176f)}, /* Approx.  96 kbps stereo AAC-LC            */
129     {QCDATA_BR_MODE_VBR_4,
130      FL2FXCONST_DBL(0.120f)}, /* Approx. 128 kbps stereo AAC-LC            */
131     {QCDATA_BR_MODE_VBR_5,
132      FL2FXCONST_DBL(0.070f)} /* Approx. 192 kbps stereo AAC-LC            */
133 };
134 
isConstantBitrateMode(const QCDATA_BR_MODE bitrateMode)135 static INT isConstantBitrateMode(const QCDATA_BR_MODE bitrateMode) {
136   return (((bitrateMode == QCDATA_BR_MODE_CBR) ||
137            (bitrateMode == QCDATA_BR_MODE_SFR) ||
138            (bitrateMode == QCDATA_BR_MODE_FF))
139               ? 1
140               : 0);
141 }
142 
143 typedef enum {
144   FRAME_LEN_BYTES_MODULO = 1,
145   FRAME_LEN_BYTES_INT = 2
146 } FRAME_LEN_RESULT_MODE;
147 
148 /* forward declarations */
149 
150 static INT FDKaacEnc_calcMaxValueInSfb(INT sfbCnt, INT maxSfbPerGroup,
151                                        INT sfbPerGroup, INT* RESTRICT sfbOffset,
152                                        SHORT* RESTRICT quantSpectrum,
153                                        UINT* RESTRICT maxValue);
154 
155 static void FDKaacEnc_crashRecovery(INT nChannels,
156                                     PSY_OUT_ELEMENT* psyOutElement,
157                                     QC_OUT* qcOut, QC_OUT_ELEMENT* qcElement,
158                                     INT bitsToSave, AUDIO_OBJECT_TYPE aot,
159                                     UINT syntaxFlags, SCHAR epConfig);
160 
161 static AAC_ENCODER_ERROR FDKaacEnc_reduceBitConsumption(
162     int* iterations, const int maxIterations, int gainAdjustment,
163     int* chConstraintsFulfilled, int* calculateQuant, int nChannels,
164     PSY_OUT_ELEMENT* psyOutElement, QC_OUT* qcOut, QC_OUT_ELEMENT* qcOutElement,
165     ELEMENT_BITS* elBits, AUDIO_OBJECT_TYPE aot, UINT syntaxFlags,
166     SCHAR epConfig);
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, INT sampleRate,
180                                   INT granuleLength,
181                                   FRAME_LEN_RESULT_MODE mode) {
182   INT result;
183 
184   result = ((granuleLength) >> 3) * (bitRate);
185 
186   switch (mode) {
187     case FRAME_LEN_BYTES_MODULO:
188       result %= sampleRate;
189       break;
190     case FRAME_LEN_BYTES_INT:
191       result /= sampleRate;
192       break;
193   }
194   return (result);
195 }
196 
197 /*****************************************************************************
198 
199     functionname:FDKaacEnc_framePadding
200     description: Calculates if padding is needed for actual frame
201     returns:
202     input:
203     output:
204 
205 *****************************************************************************/
FDKaacEnc_framePadding(INT bitRate,INT sampleRate,INT granuleLength,INT * paddingRest)206 static INT FDKaacEnc_framePadding(INT bitRate, INT sampleRate,
207                                   INT granuleLength, INT* paddingRest) {
208   INT paddingOn;
209   INT difference;
210 
211   paddingOn = 0;
212 
213   difference = FDKaacEnc_calcFrameLen(bitRate, sampleRate, granuleLength,
214                                       FRAME_LEN_BYTES_MODULO);
215   *paddingRest -= difference;
216 
217   if (*paddingRest <= 0) {
218     paddingOn = 1;
219     *paddingRest += sampleRate;
220   }
221 
222   return (paddingOn);
223 }
224 
225 /*********************************************************************************
226 
227          functionname: FDKaacEnc_QCOutNew
228          description:
229          return:
230 
231 **********************************************************************************/
FDKaacEnc_QCOutNew(QC_OUT ** phQC,const INT nElements,const INT nChannels,const INT nSubFrames,UCHAR * dynamic_RAM)232 AAC_ENCODER_ERROR FDKaacEnc_QCOutNew(QC_OUT** phQC, const INT nElements,
233                                      const INT nChannels, const INT nSubFrames,
234                                      UCHAR* dynamic_RAM) {
235   AAC_ENCODER_ERROR ErrorStatus;
236   int n, i;
237   int elInc = 0, chInc = 0;
238 
239   for (n = 0; n < nSubFrames; n++) {
240     phQC[n] = GetRam_aacEnc_QCout(n);
241     if (phQC[n] == NULL) {
242       ErrorStatus = AAC_ENC_NO_MEMORY;
243       goto QCOutNew_bail;
244     }
245 
246     for (i = 0; i < nChannels; i++) {
247       phQC[n]->pQcOutChannels[i] = GetRam_aacEnc_QCchannel(chInc, dynamic_RAM);
248       if (phQC[n]->pQcOutChannels[i] == NULL) {
249         ErrorStatus = AAC_ENC_NO_MEMORY;
250         goto QCOutNew_bail;
251       }
252 
253       chInc++;
254     } /* nChannels */
255 
256     for (i = 0; i < nElements; i++) {
257       phQC[n]->qcElement[i] = GetRam_aacEnc_QCelement(elInc);
258       if (phQC[n]->qcElement[i] == NULL) {
259         ErrorStatus = AAC_ENC_NO_MEMORY;
260         goto QCOutNew_bail;
261       }
262       elInc++;
263 
264       /* initialize pointer to dynamic buffer which are used in adjust
265        * thresholds */
266       phQC[n]->qcElement[i]->dynMem_Ah_Flag = dynamic_RAM + (P_BUF_1);
267       phQC[n]->qcElement[i]->dynMem_Thr_Exp =
268           dynamic_RAM + (P_BUF_1) + ADJ_THR_AH_FLAG_SIZE;
269       phQC[n]->qcElement[i]->dynMem_SfbNActiveLinesLdData =
270           dynamic_RAM + (P_BUF_1) + ADJ_THR_AH_FLAG_SIZE + ADJ_THR_THR_EXP_SIZE;
271 
272     } /* nElements */
273 
274   } /* nSubFrames */
275 
276   return AAC_ENC_OK;
277 
278 QCOutNew_bail:
279   return ErrorStatus;
280 }
281 
282 /*********************************************************************************
283 
284          functionname: FDKaacEnc_QCOutInit
285          description:
286          return:
287 
288 **********************************************************************************/
FDKaacEnc_QCOutInit(QC_OUT * phQC[(1)],const INT nSubFrames,const CHANNEL_MAPPING * cm)289 AAC_ENCODER_ERROR FDKaacEnc_QCOutInit(QC_OUT* phQC[(1)], const INT nSubFrames,
290                                       const CHANNEL_MAPPING* cm) {
291   INT n, i, ch;
292 
293   for (n = 0; n < nSubFrames; n++) {
294     INT chInc = 0;
295     for (i = 0; i < cm->nElements; i++) {
296       for (ch = 0; ch < cm->elInfo[i].nChannelsInEl; ch++) {
297         phQC[n]->qcElement[i]->qcOutChannel[ch] =
298             phQC[n]->pQcOutChannels[chInc];
299         chInc++;
300       } /* chInEl */
301     }   /* nElements */
302   }     /* nSubFrames */
303 
304   return AAC_ENC_OK;
305 }
306 
307 /*********************************************************************************
308 
309          functionname: FDKaacEnc_QCNew
310          description:
311          return:
312 
313 **********************************************************************************/
FDKaacEnc_QCNew(QC_STATE ** phQC,INT nElements,UCHAR * dynamic_RAM)314 AAC_ENCODER_ERROR FDKaacEnc_QCNew(QC_STATE** phQC, INT nElements,
315                                   UCHAR* dynamic_RAM) {
316   AAC_ENCODER_ERROR ErrorStatus;
317   int i;
318 
319   QC_STATE* hQC = GetRam_aacEnc_QCstate();
320   *phQC = hQC;
321   if (hQC == NULL) {
322     ErrorStatus = AAC_ENC_NO_MEMORY;
323     goto QCNew_bail;
324   }
325 
326   if (FDKaacEnc_AdjThrNew(&hQC->hAdjThr, nElements)) {
327     ErrorStatus = AAC_ENC_NO_MEMORY;
328     goto QCNew_bail;
329   }
330 
331   if (FDKaacEnc_BCNew(&(hQC->hBitCounter), dynamic_RAM)) {
332     ErrorStatus = AAC_ENC_NO_MEMORY;
333     goto QCNew_bail;
334   }
335 
336   for (i = 0; i < nElements; i++) {
337     hQC->elementBits[i] = GetRam_aacEnc_ElementBits(i);
338     if (hQC->elementBits[i] == NULL) {
339       ErrorStatus = AAC_ENC_NO_MEMORY;
340       goto QCNew_bail;
341     }
342   }
343 
344   return AAC_ENC_OK;
345 
346 QCNew_bail:
347   FDKaacEnc_QCClose(phQC, NULL);
348   return ErrorStatus;
349 }
350 
351 /*********************************************************************************
352 
353          functionname: FDKaacEnc_QCInit
354          description:
355          return:
356 
357 **********************************************************************************/
FDKaacEnc_QCInit(QC_STATE * hQC,struct QC_INIT * init,const ULONG initFlags)358 AAC_ENCODER_ERROR FDKaacEnc_QCInit(QC_STATE* hQC, struct QC_INIT* init,
359                                    const ULONG initFlags) {
360   AAC_ENCODER_ERROR err = AAC_ENC_OK;
361 
362   int i;
363   hQC->maxBitsPerFrame = init->maxBits;
364   hQC->minBitsPerFrame = init->minBits;
365   hQC->nElements = init->channelMapping->nElements;
366   if ((initFlags != 0) || ((init->bitrateMode != QCDATA_BR_MODE_FF) &&
367                            (hQC->bitResTotMax != init->bitRes))) {
368     hQC->bitResTot = init->bitRes;
369   }
370   hQC->bitResTotMax = init->bitRes;
371   hQC->maxBitFac = init->maxBitFac;
372   hQC->bitrateMode = init->bitrateMode;
373   hQC->invQuant = init->invQuant;
374   hQC->maxIterations = init->maxIterations;
375 
376   if (isConstantBitrateMode(hQC->bitrateMode)) {
377     /* 0: full bitreservoir, 1: reduced bitreservoir, 2: disabled bitreservoir
378      */
379     hQC->bitResMode = init->bitResMode;
380   } else {
381     hQC->bitResMode = AACENC_BR_MODE_FULL; /* full bitreservoir */
382   }
383 
384   hQC->padding.paddingRest = init->padding.paddingRest;
385 
386   hQC->globHdrBits = init->staticBits; /* Bit overhead due to transport */
387 
388   err = FDKaacEnc_InitElementBits(
389       hQC, init->channelMapping, init->bitrate,
390       (init->averageBits / init->nSubFrames) - hQC->globHdrBits,
391       hQC->maxBitsPerFrame / init->channelMapping->nChannelsEff);
392   if (err != AAC_ENC_OK) goto bail;
393 
394   hQC->vbrQualFactor = FL2FXCONST_DBL(0.f);
395   for (i = 0;
396        i < (int)(sizeof(tableVbrQualFactor) / sizeof(TAB_VBR_QUAL_FACTOR));
397        i++) {
398     if (hQC->bitrateMode == tableVbrQualFactor[i].bitrateMode) {
399       hQC->vbrQualFactor = (FIXP_DBL)tableVbrQualFactor[i].vbrQualFactor;
400       break;
401     }
402   }
403 
404   if (init->channelMapping->nChannelsEff == 1 &&
405       (init->bitrate / init->channelMapping->nChannelsEff) <
406           AACENC_DZQ_BR_THR &&
407       init->isLowDelay !=
408           0) /* watch out here: init->bitrate is the bitrate "minus" the
409                 standard SBR bitrate (=2500kbps) --> for the FDK the OFFSTE
410                 tuning should start somewhere below 32000kbps-2500kbps ... so
411                 everything is fine here */
412   {
413     hQC->dZoneQuantEnable = 1;
414   } else {
415     hQC->dZoneQuantEnable = 0;
416   }
417 
418   FDKaacEnc_AdjThrInit(
419       hQC->hAdjThr, init->meanPe, hQC->invQuant, init->channelMapping,
420       init->sampleRate, /* output sample rate */
421       init->bitrate,    /* total bitrate */
422       init->isLowDelay, /* if set, calc bits2PE factor
423                            depending on samplerate */
424       init->bitResMode  /* for a small bitreservoir, the pe
425                            correction is calc'd differently */
426       ,
427       hQC->dZoneQuantEnable, init->bitDistributionMode, hQC->vbrQualFactor);
428 
429 bail:
430   return err;
431 }
432 
433 /*********************************************************************************
434 
435          functionname: FDKaacEnc_QCMainPrepare
436          description:
437          return:
438 
439 **********************************************************************************/
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)440 AAC_ENCODER_ERROR FDKaacEnc_QCMainPrepare(
441     ELEMENT_INFO* elInfo, ATS_ELEMENT* RESTRICT adjThrStateElement,
442     PSY_OUT_ELEMENT* RESTRICT psyOutElement,
443     QC_OUT_ELEMENT* RESTRICT qcOutElement, AUDIO_OBJECT_TYPE aot,
444     UINT syntaxFlags, SCHAR epConfig) {
445   AAC_ENCODER_ERROR ErrorStatus = AAC_ENC_OK;
446   INT nChannels = elInfo->nChannelsInEl;
447 
448   PSY_OUT_CHANNEL** RESTRICT psyOutChannel =
449       psyOutElement->psyOutChannel; /* may be modified in-place */
450 
451   FDKaacEnc_CalcFormFactor(qcOutElement->qcOutChannel, psyOutChannel,
452                            nChannels);
453 
454   /* prepare and calculate PE without reduction */
455   FDKaacEnc_peCalculation(&qcOutElement->peData, psyOutChannel,
456                           qcOutElement->qcOutChannel, &psyOutElement->toolsInfo,
457                           adjThrStateElement, nChannels);
458 
459   ErrorStatus = FDKaacEnc_ChannelElementWrite(
460       NULL, elInfo, NULL, psyOutElement, psyOutElement->psyOutChannel,
461       syntaxFlags, aot, epConfig, &qcOutElement->staticBitsUsed, 0);
462 
463   return ErrorStatus;
464 }
465 
466 /*********************************************************************************
467 
468          functionname: FDKaacEnc_AdjustBitrate
469          description:  adjusts framelength via padding on a frame to frame
470 basis, to achieve a bitrate that demands a non byte aligned framelength return:
471 errorcode
472 
473 **********************************************************************************/
FDKaacEnc_AdjustBitrate(QC_STATE * RESTRICT hQC,CHANNEL_MAPPING * RESTRICT cm,INT * avgTotalBits,INT bitRate,INT sampleRate,INT granuleLength)474 AAC_ENCODER_ERROR FDKaacEnc_AdjustBitrate(
475     QC_STATE* RESTRICT hQC, CHANNEL_MAPPING* RESTRICT cm, INT* avgTotalBits,
476     INT bitRate,       /* total bitrate */
477     INT sampleRate,    /* output sampling rate */
478     INT granuleLength) /* frame length */
479 {
480   INT paddingOn;
481   INT frameLen;
482 
483   /* Do we need an extra padding byte? */
484   paddingOn = FDKaacEnc_framePadding(bitRate, sampleRate, granuleLength,
485                                      &hQC->padding.paddingRest);
486 
487   frameLen =
488       paddingOn + FDKaacEnc_calcFrameLen(bitRate, sampleRate, granuleLength,
489                                          FRAME_LEN_BYTES_INT);
490 
491   *avgTotalBits = frameLen << 3;
492 
493   return AAC_ENC_OK;
494 }
495 
496 #define isAudioElement(elType) \
497   ((elType == ID_SCE) || (elType == ID_CPE) || (elType == ID_LFE))
498 
499 /*********************************************************************************
500 
501          functionname: FDKaacEnc_distributeElementDynBits
502          description:  distributes all bits over all elements. The relative bit
503                        distibution is described in the ELEMENT_INFO of the
504                        appropriate element. The bit distribution table is
505                        initialized in FDKaacEnc_InitChannelMapping().
506          return:       errorcode
507 
508 **********************************************************************************/
FDKaacEnc_distributeElementDynBits(QC_STATE * hQC,QC_OUT_ELEMENT * qcElement[((8))],CHANNEL_MAPPING * cm,INT codeBits)509 static AAC_ENCODER_ERROR FDKaacEnc_distributeElementDynBits(
510     QC_STATE* hQC, QC_OUT_ELEMENT* qcElement[((8))], CHANNEL_MAPPING* cm,
511     INT codeBits) {
512   INT i;             /* counter variable */
513   INT totalBits = 0; /* sum of bits over all elements */
514 
515   for (i = (cm->nElements - 1); i >= 0; i--) {
516     if (isAudioElement(cm->elInfo[i].elType)) {
517       qcElement[i]->grantedDynBits =
518           fMax(0, fMultI(hQC->elementBits[i]->relativeBitsEl, codeBits));
519       totalBits += qcElement[i]->grantedDynBits;
520     }
521   }
522 
523   /* Due to inaccuracies with the multiplication, codeBits may differ from
524      totalBits. For that case, the difference must be added/substracted again
525      to/from one element, i.e:
526      Negative differences are substracted from the element with the most bits.
527      Positive differences are added to the element with the least bits.
528   */
529   if (codeBits != totalBits) {
530     INT elMaxBits = cm->nElements - 1; /* element with the most bits */
531     INT elMinBits = cm->nElements - 1; /* element with the least bits */
532 
533     /* Search for biggest and smallest audio element */
534     for (i = (cm->nElements - 1); i >= 0; i--) {
535       if (isAudioElement(cm->elInfo[i].elType)) {
536         if (qcElement[i]->grantedDynBits >
537             qcElement[elMaxBits]->grantedDynBits) {
538           elMaxBits = i;
539         }
540         if (qcElement[i]->grantedDynBits <
541             qcElement[elMinBits]->grantedDynBits) {
542           elMinBits = i;
543         }
544       }
545     }
546     /* Compensate for bit distibution difference */
547     if (codeBits - totalBits > 0) {
548       qcElement[elMinBits]->grantedDynBits += codeBits - totalBits;
549     } else {
550       qcElement[elMaxBits]->grantedDynBits += codeBits - totalBits;
551     }
552   }
553 
554   return AAC_ENC_OK;
555 }
556 
557 /**
558  * \brief  Verify whether minBitsPerFrame criterion can be satisfied.
559  *
560  * This function evaluates the bit consumption only if minBitsPerFrame parameter
561  * is not 0. In hyperframing mode the difference between grantedDynBits and
562  * usedDynBits of all sub frames results the number of fillbits to be written.
563  * This bits can be distrubitued in superframe to reach minBitsPerFrame bit
564  * consumption in single AU's. The return value denotes if enough desired fill
565  * bits are available to achieve minBitsPerFrame in all frames. This check can
566  * only be used within superframes.
567  *
568  * \param qcOut            Pointer to coding data struct.
569  * \param minBitsPerFrame  Minimal number of bits to be consumed in each frame.
570  * \param nSubFrames       Number of frames in superframe
571  *
572  * \return
573  *          - 1: all fine
574  *          - 0: criterion not fulfilled
575  */
checkMinFrameBitsDemand(QC_OUT ** qcOut,const INT minBitsPerFrame,const INT nSubFrames)576 static int checkMinFrameBitsDemand(QC_OUT** qcOut, const INT minBitsPerFrame,
577                                    const INT nSubFrames) {
578   int result = 1; /* all fine*/
579   return result;
580 }
581 
582 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
583 
584 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
585 /*********************************************************************************
586 
587          functionname: FDKaacEnc_getMinimalStaticBitdemand
588          description:  calculate minmal size of static bits by reduction ,
589                        to zero spectrum and deactivating tns and MS
590          return:       number of static bits
591 
592 **********************************************************************************/
FDKaacEnc_getMinimalStaticBitdemand(CHANNEL_MAPPING * cm,PSY_OUT ** psyOut)593 static int FDKaacEnc_getMinimalStaticBitdemand(CHANNEL_MAPPING* cm,
594                                                PSY_OUT** psyOut) {
595   AUDIO_OBJECT_TYPE aot = AOT_AAC_LC;
596   UINT syntaxFlags = 0;
597   SCHAR epConfig = -1;
598   int i, bitcount = 0;
599 
600   for (i = 0; i < cm->nElements; i++) {
601     ELEMENT_INFO elInfo = cm->elInfo[i];
602 
603     if ((elInfo.elType == ID_SCE) || (elInfo.elType == ID_CPE) ||
604         (elInfo.elType == ID_LFE)) {
605       INT minElBits = 0;
606 
607       FDKaacEnc_ChannelElementWrite(NULL, &elInfo, NULL,
608                                     psyOut[0]->psyOutElement[i],
609                                     psyOut[0]->psyOutElement[i]->psyOutChannel,
610                                     syntaxFlags, aot, epConfig, &minElBits, 1);
611       bitcount += minElBits;
612     }
613   }
614 
615   return bitcount;
616 }
617 
618 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
619 
FDKaacEnc_prepareBitDistribution(QC_STATE * hQC,PSY_OUT ** psyOut,QC_OUT ** qcOut,CHANNEL_MAPPING * cm,QC_OUT_ELEMENT * qcElement[(1)][((8))],INT avgTotalBits,INT * totalAvailableBits,INT * avgTotalDynBits)620 static AAC_ENCODER_ERROR FDKaacEnc_prepareBitDistribution(
621     QC_STATE* hQC, PSY_OUT** psyOut, QC_OUT** qcOut, CHANNEL_MAPPING* cm,
622     QC_OUT_ELEMENT* qcElement[(1)][((8))], INT avgTotalBits,
623     INT* totalAvailableBits, INT* avgTotalDynBits) {
624   int i;
625   /* get maximal allowed dynamic bits */
626   qcOut[0]->grantedDynBits =
627       (fixMin(hQC->maxBitsPerFrame, avgTotalBits) - hQC->globHdrBits) & ~7;
628   qcOut[0]->grantedDynBits -= (qcOut[0]->globalExtBits + qcOut[0]->staticBits +
629                                qcOut[0]->elementExtBits);
630   qcOut[0]->maxDynBits = ((hQC->maxBitsPerFrame) & ~7) -
631                          (qcOut[0]->globalExtBits + qcOut[0]->staticBits +
632                           qcOut[0]->elementExtBits);
633   /* assure that enough bits are available */
634   if ((qcOut[0]->grantedDynBits + hQC->bitResTot) < 0) {
635     /* crash recovery allows to reduce static bits to a minimum */
636     if ((qcOut[0]->grantedDynBits + hQC->bitResTot) <
637         (FDKaacEnc_getMinimalStaticBitdemand(cm, psyOut) -
638          qcOut[0]->staticBits))
639       return AAC_ENC_BITRES_TOO_LOW;
640   }
641 
642   /* distribute dynamic bits to each element */
643   FDKaacEnc_distributeElementDynBits(hQC, qcElement[0], cm,
644                                      qcOut[0]->grantedDynBits);
645 
646   *avgTotalDynBits = 0; /*frameDynBits;*/
647 
648   *totalAvailableBits = avgTotalBits;
649 
650   /* sum up corrected granted PE */
651   qcOut[0]->totalGrantedPeCorr = 0;
652 
653   for (i = 0; i < cm->nElements; i++) {
654     ELEMENT_INFO elInfo = cm->elInfo[i];
655     int nChannels = elInfo.nChannelsInEl;
656 
657     if ((elInfo.elType == ID_SCE) || (elInfo.elType == ID_CPE) ||
658         (elInfo.elType == ID_LFE)) {
659       /* for ( all sub frames ) ... */
660       FDKaacEnc_DistributeBits(
661           hQC->hAdjThr, hQC->hAdjThr->adjThrStateElem[i],
662           psyOut[0]->psyOutElement[i]->psyOutChannel, &qcElement[0][i]->peData,
663           &qcElement[0][i]->grantedPe, &qcElement[0][i]->grantedPeCorr,
664           nChannels, psyOut[0]->psyOutElement[i]->commonWindow,
665           qcElement[0][i]->grantedDynBits, hQC->elementBits[i]->bitResLevelEl,
666           hQC->elementBits[i]->maxBitResBitsEl, hQC->maxBitFac,
667           hQC->bitResMode);
668 
669       *totalAvailableBits += hQC->elementBits[i]->bitResLevelEl;
670       /* get total corrected granted PE */
671       qcOut[0]->totalGrantedPeCorr += qcElement[0][i]->grantedPeCorr;
672     } /*  -end- if(ID_SCE || ID_CPE || ID_LFE) */
673 
674   } /* -end- element loop */
675 
676   *totalAvailableBits = fMin(hQC->maxBitsPerFrame, (*totalAvailableBits));
677 
678   return AAC_ENC_OK;
679 }
680 
681 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
FDKaacEnc_updateUsedDynBits(INT * sumDynBitsConsumed,QC_OUT_ELEMENT * qcElement[((8))],CHANNEL_MAPPING * cm)682 static AAC_ENCODER_ERROR FDKaacEnc_updateUsedDynBits(
683     INT* sumDynBitsConsumed, QC_OUT_ELEMENT* qcElement[((8))],
684     CHANNEL_MAPPING* cm) {
685   INT i;
686 
687   *sumDynBitsConsumed = 0;
688 
689   for (i = 0; i < cm->nElements; i++) {
690     ELEMENT_INFO elInfo = cm->elInfo[i];
691 
692     if ((elInfo.elType == ID_SCE) || (elInfo.elType == ID_CPE) ||
693         (elInfo.elType == ID_LFE)) {
694       /* sum up bits consumed */
695       *sumDynBitsConsumed += qcElement[i]->dynBitsUsed;
696     } /*  -end- if(ID_SCE || ID_CPE || ID_LFE) */
697 
698   } /* -end- element loop */
699 
700   return AAC_ENC_OK;
701 }
702 
FDKaacEnc_getTotalConsumedDynBits(QC_OUT ** qcOut,INT nSubFrames)703 static INT FDKaacEnc_getTotalConsumedDynBits(QC_OUT** qcOut, INT nSubFrames) {
704   INT c, totalBits = 0;
705 
706   /* sum up bit consumption for all sub frames */
707   for (c = 0; c < nSubFrames; c++) {
708     /* bit consumption not valid if dynamic bits
709        not available in one sub frame */
710     if (qcOut[c]->usedDynBits == -1) return -1;
711     totalBits += qcOut[c]->usedDynBits;
712   }
713 
714   return totalBits;
715 }
716 
FDKaacEnc_getTotalConsumedBits(QC_OUT ** qcOut,QC_OUT_ELEMENT * qcElement[(1)][((8))],CHANNEL_MAPPING * cm,INT globHdrBits,INT nSubFrames)717 static INT FDKaacEnc_getTotalConsumedBits(QC_OUT** qcOut,
718                                           QC_OUT_ELEMENT* qcElement[(1)][((8))],
719                                           CHANNEL_MAPPING* cm, INT globHdrBits,
720                                           INT nSubFrames) {
721   int c, i;
722   int totalUsedBits = 0;
723 
724   for (c = 0; c < nSubFrames; c++) {
725     int dataBits = 0;
726     for (i = 0; i < cm->nElements; i++) {
727       if ((cm->elInfo[i].elType == ID_SCE) ||
728           (cm->elInfo[i].elType == ID_CPE) ||
729           (cm->elInfo[i].elType == ID_LFE)) {
730         dataBits += qcElement[c][i]->dynBitsUsed +
731                     qcElement[c][i]->staticBitsUsed +
732                     qcElement[c][i]->extBitsUsed;
733       }
734     }
735     dataBits += qcOut[c]->globalExtBits;
736 
737     totalUsedBits += (8 - (dataBits) % 8) % 8;
738     totalUsedBits += dataBits + globHdrBits; /* header bits for every frame */
739   }
740   return totalUsedBits;
741 }
742 
FDKaacEnc_BitResRedistribution(QC_STATE * const hQC,const CHANNEL_MAPPING * const cm,const INT avgTotalBits)743 static AAC_ENCODER_ERROR FDKaacEnc_BitResRedistribution(
744     QC_STATE* const hQC, const CHANNEL_MAPPING* const cm,
745     const INT avgTotalBits) {
746   /* check bitreservoir fill level */
747   if (hQC->bitResTot < 0) {
748     return AAC_ENC_BITRES_TOO_LOW;
749   } else if (hQC->bitResTot > hQC->bitResTotMax) {
750     return AAC_ENC_BITRES_TOO_HIGH;
751   } else {
752     INT i;
753     INT totalBits = 0, totalBits_max = 0;
754 
755     const int totalBitreservoir =
756         fMin(hQC->bitResTot, (hQC->maxBitsPerFrame - avgTotalBits));
757     const int totalBitreservoirMax =
758         fMin(hQC->bitResTotMax, (hQC->maxBitsPerFrame - avgTotalBits));
759 
760     for (i = (cm->nElements - 1); i >= 0; i--) {
761       if ((cm->elInfo[i].elType == ID_SCE) ||
762           (cm->elInfo[i].elType == ID_CPE) ||
763           (cm->elInfo[i].elType == ID_LFE)) {
764         hQC->elementBits[i]->bitResLevelEl =
765             fMultI(hQC->elementBits[i]->relativeBitsEl, totalBitreservoir);
766         totalBits += hQC->elementBits[i]->bitResLevelEl;
767 
768         hQC->elementBits[i]->maxBitResBitsEl =
769             fMultI(hQC->elementBits[i]->relativeBitsEl, totalBitreservoirMax);
770         totalBits_max += hQC->elementBits[i]->maxBitResBitsEl;
771       }
772     }
773     for (i = 0; i < cm->nElements; i++) {
774       if ((cm->elInfo[i].elType == ID_SCE) ||
775           (cm->elInfo[i].elType == ID_CPE) ||
776           (cm->elInfo[i].elType == ID_LFE)) {
777         int deltaBits = fMax(totalBitreservoir - totalBits,
778                              -hQC->elementBits[i]->bitResLevelEl);
779         hQC->elementBits[i]->bitResLevelEl += deltaBits;
780         totalBits += deltaBits;
781 
782         deltaBits = fMax(totalBitreservoirMax - totalBits_max,
783                          -hQC->elementBits[i]->maxBitResBitsEl);
784         hQC->elementBits[i]->maxBitResBitsEl += deltaBits;
785         totalBits_max += deltaBits;
786       }
787     }
788   }
789 
790   return AAC_ENC_OK;
791 }
792 
FDKaacEnc_QCMain(QC_STATE * RESTRICT hQC,PSY_OUT ** psyOut,QC_OUT ** qcOut,INT avgTotalBits,CHANNEL_MAPPING * cm,const AUDIO_OBJECT_TYPE aot,UINT syntaxFlags,SCHAR epConfig)793 AAC_ENCODER_ERROR FDKaacEnc_QCMain(QC_STATE* RESTRICT hQC, PSY_OUT** psyOut,
794                                    QC_OUT** qcOut, INT avgTotalBits,
795                                    CHANNEL_MAPPING* cm,
796                                    const AUDIO_OBJECT_TYPE aot,
797                                    UINT syntaxFlags, SCHAR epConfig) {
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)][((8))];
818 
819   /* work on a copy of qcChannel and qcElement */
820   for (i = 0; i < cm->nElements; i++) {
821     ELEMENT_INFO elInfo = cm->elInfo[i];
822 
823     if ((elInfo.elType == ID_SCE) || (elInfo.elType == ID_CPE) ||
824         (elInfo.elType == ID_LFE)) {
825       /* for ( all sub frames ) ... */
826       for (c = 0; c < nSubFrames; c++) {
827         { qcElement[c][i] = qcOut[c]->qcElement[i]; }
828       }
829     }
830   }
831 
832   /*-------------------------------------------- */
833   /*-------------------------------------------- */
834   if (isConstantBitrateMode(hQC->bitrateMode)) {
835     /* calc granted dynamic bits for sub frame and
836        distribute it to each element */
837     ErrorStatus = FDKaacEnc_prepareBitDistribution(
838         hQC, psyOut, qcOut, cm, qcElement, avgTotalBits, &totalAvailableBits,
839         &avgTotalDynBits);
840 
841     if (ErrorStatus != AAC_ENC_OK) {
842       return ErrorStatus;
843     }
844   } else {
845     qcOut[0]->grantedDynBits =
846         ((hQC->maxBitsPerFrame - (hQC->globHdrBits)) & ~7) -
847         (qcOut[0]->globalExtBits + qcOut[0]->staticBits +
848          qcOut[0]->elementExtBits);
849     qcOut[0]->maxDynBits = qcOut[0]->grantedDynBits;
850 
851     totalAvailableBits = hQC->maxBitsPerFrame;
852     avgTotalDynBits = 0;
853   }
854 
855   /* for ( all sub frames ) ... */
856   for (c = 0; c < nSubFrames; c++) {
857     /* for CBR and VBR mode */
858     FDKaacEnc_AdjustThresholds(hQC->hAdjThr, qcElement[c], qcOut[c],
859                                psyOut[c]->psyOutElement,
860                                isConstantBitrateMode(hQC->bitrateMode), cm);
861 
862   } /* -end- sub frame counter */
863 
864   /*-------------------------------------------- */
865   INT iterations[(1)][((8))];
866   INT chConstraintsFulfilled[(1)][((8))][(2)];
867   INT calculateQuant[(1)][((8))][(2)];
868   INT constraintsFulfilled[(1)][((8))];
869   /*-------------------------------------------- */
870 
871   /* for ( all sub frames ) ... */
872   for (c = 0; c < nSubFrames; c++) {
873     for (i = 0; i < cm->nElements; i++) {
874       ELEMENT_INFO elInfo = cm->elInfo[i];
875       INT ch, nChannels = elInfo.nChannelsInEl;
876 
877       if ((elInfo.elType == ID_SCE) || (elInfo.elType == ID_CPE) ||
878           (elInfo.elType == ID_LFE)) {
879         /* Turn thresholds into scalefactors, optimize bit consumption and
880          * verify conformance */
881         FDKaacEnc_EstimateScaleFactors(
882             psyOut[c]->psyOutElement[i]->psyOutChannel,
883             qcElement[c][i]->qcOutChannel, hQC->invQuant, hQC->dZoneQuantEnable,
884             cm->elInfo[i].nChannelsInEl);
885 
886         /*-------------------------------------------- */
887         constraintsFulfilled[c][i] = 1;
888         iterations[c][i] = 0;
889 
890         for (ch = 0; ch < nChannels; ch++) {
891           chConstraintsFulfilled[c][i][ch] = 1;
892           calculateQuant[c][i][ch] = 1;
893         }
894 
895         /*-------------------------------------------- */
896 
897       } /*  -end- if(ID_SCE || ID_CPE || ID_LFE) */
898 
899     } /* -end- element loop */
900 
901     qcOut[c]->usedDynBits = -1;
902 
903   } /* -end- sub frame counter */
904 
905   INT quantizationDone = 0;
906   INT sumDynBitsConsumedTotal = 0;
907   INT decreaseBitConsumption = -1; /* no direction yet! */
908 
909   /*-------------------------------------------- */
910   /* -start- Quantization loop ...               */
911   /*-------------------------------------------- */
912   do /* until max allowed bits per frame and maxDynBits!=-1*/
913   {
914     quantizationDone = 0;
915 
916     c = 0; /* get frame to process */
917 
918     for (i = 0; i < cm->nElements; i++) {
919       ELEMENT_INFO elInfo = cm->elInfo[i];
920       INT ch, nChannels = elInfo.nChannelsInEl;
921 
922       if ((elInfo.elType == ID_SCE) || (elInfo.elType == ID_CPE) ||
923           (elInfo.elType == ID_LFE)) {
924         do /* until element bits < nChannels*MIN_BUFSIZE_PER_EFF_CHAN */
925         {
926           do /* until spectral values < MAX_QUANT */
927           {
928             /*-------------------------------------------- */
929             if (!constraintsFulfilled[c][i]) {
930               if ((ErrorStatus = FDKaacEnc_reduceBitConsumption(
931                        &iterations[c][i], hQC->maxIterations,
932                        (decreaseBitConsumption) ? 1 : -1,
933                        chConstraintsFulfilled[c][i], calculateQuant[c][i],
934                        nChannels, psyOut[c]->psyOutElement[i], qcOut[c],
935                        qcElement[c][i], hQC->elementBits[i], aot, syntaxFlags,
936                        epConfig)) != AAC_ENC_OK) {
937                 return ErrorStatus;
938               }
939             }
940 
941             /*-------------------------------------------- */
942             /*-------------------------------------------- */
943             constraintsFulfilled[c][i] = 1;
944 
945             /*-------------------------------------------- */
946             /* quantize spectrum (per each channel) */
947             for (ch = 0; ch < nChannels; ch++) {
948               /*-------------------------------------------- */
949               chConstraintsFulfilled[c][i][ch] = 1;
950 
951               /*-------------------------------------------- */
952 
953               if (calculateQuant[c][i][ch]) {
954                 QC_OUT_CHANNEL* qcOutCh = qcElement[c][i]->qcOutChannel[ch];
955                 PSY_OUT_CHANNEL* psyOutCh =
956                     psyOut[c]->psyOutElement[i]->psyOutChannel[ch];
957 
958                 calculateQuant[c][i][ch] =
959                     0; /* calculate quantization only if necessary */
960 
961                 /*-------------------------------------------- */
962                 FDKaacEnc_QuantizeSpectrum(
963                     psyOutCh->sfbCnt, psyOutCh->maxSfbPerGroup,
964                     psyOutCh->sfbPerGroup, psyOutCh->sfbOffsets,
965                     qcOutCh->mdctSpectrum, qcOutCh->globalGain, qcOutCh->scf,
966                     qcOutCh->quantSpec, hQC->dZoneQuantEnable);
967 
968                 /*-------------------------------------------- */
969                 if (FDKaacEnc_calcMaxValueInSfb(
970                         psyOutCh->sfbCnt, psyOutCh->maxSfbPerGroup,
971                         psyOutCh->sfbPerGroup, psyOutCh->sfbOffsets,
972                         qcOutCh->quantSpec,
973                         qcOutCh->maxValueInSfb) > MAX_QUANT) {
974                   chConstraintsFulfilled[c][i][ch] = 0;
975                   constraintsFulfilled[c][i] = 0;
976                   /* if quanizted value out of range; increase global gain! */
977                   decreaseBitConsumption = 1;
978                 }
979 
980                 /*-------------------------------------------- */
981 
982               } /* if calculateQuant[c][i][ch] */
983 
984             } /* channel loop */
985 
986             /*-------------------------------------------- */
987             /* quantize spectrum (per each channel) */
988 
989             /*-------------------------------------------- */
990 
991           } while (!constraintsFulfilled[c][i]); /* does not regard bit
992                                                     consumption */
993 
994           /*-------------------------------------------- */
995           /*-------------------------------------------- */
996           qcElement[c][i]->dynBitsUsed = 0; /* reset dynamic bits */
997 
998           /* quantization valid in current channel! */
999           for (ch = 0; ch < nChannels; ch++) {
1000             QC_OUT_CHANNEL* qcOutCh = qcElement[c][i]->qcOutChannel[ch];
1001             PSY_OUT_CHANNEL* psyOutCh =
1002                 psyOut[c]->psyOutElement[i]->psyOutChannel[ch];
1003 
1004             /* count dynamic bits */
1005             INT chDynBits = FDKaacEnc_dynBitCount(
1006                 hQC->hBitCounter, qcOutCh->quantSpec, qcOutCh->maxValueInSfb,
1007                 qcOutCh->scf, psyOutCh->lastWindowSequence, psyOutCh->sfbCnt,
1008                 psyOutCh->maxSfbPerGroup, psyOutCh->sfbPerGroup,
1009                 psyOutCh->sfbOffsets, &qcOutCh->sectionData, psyOutCh->noiseNrg,
1010                 psyOutCh->isBook, psyOutCh->isScale, syntaxFlags);
1011 
1012             /* sum up dynamic channel bits */
1013             qcElement[c][i]->dynBitsUsed += chDynBits;
1014           }
1015 
1016           /* save dynBitsUsed for correction of bits2pe relation */
1017           if (hQC->hAdjThr->adjThrStateElem[i]->dynBitsLast == -1) {
1018             hQC->hAdjThr->adjThrStateElem[i]->dynBitsLast =
1019                 qcElement[c][i]->dynBitsUsed;
1020           }
1021 
1022           /* hold total bit consumption in present element below maximum allowed
1023            */
1024           if (qcElement[c][i]->dynBitsUsed >
1025               ((nChannels * MIN_BUFSIZE_PER_EFF_CHAN) -
1026                qcElement[c][i]->staticBitsUsed -
1027                qcElement[c][i]->extBitsUsed)) {
1028             constraintsFulfilled[c][i] = 0;
1029           }
1030 
1031         } while (!constraintsFulfilled[c][i]);
1032 
1033       } /*  -end- if(ID_SCE || ID_CPE || ID_LFE) */
1034 
1035     } /* -end- element loop */
1036 
1037     /* update dynBits of current subFrame */
1038     FDKaacEnc_updateUsedDynBits(&qcOut[c]->usedDynBits, qcElement[c], cm);
1039 
1040     /* get total consumed bits, dyn bits in all sub frames have to be valid */
1041     sumDynBitsConsumedTotal =
1042         FDKaacEnc_getTotalConsumedDynBits(qcOut, nSubFrames);
1043 
1044     if (sumDynBitsConsumedTotal == -1) {
1045       quantizationDone = 0; /* bit consumption not valid in all sub frames */
1046     } else {
1047       int sumBitsConsumedTotal = FDKaacEnc_getTotalConsumedBits(
1048           qcOut, qcElement, cm, hQC->globHdrBits, nSubFrames);
1049 
1050       /* in all frames are valid dynamic bits */
1051       if (((sumBitsConsumedTotal < totalAvailableBits) ||
1052            sumDynBitsConsumedTotal == 0) &&
1053           (decreaseBitConsumption == 1) &&
1054           checkMinFrameBitsDemand(qcOut, hQC->minBitsPerFrame, nSubFrames)
1055           /*()*/) {
1056         quantizationDone = 1; /* exit bit adjustment */
1057       }
1058       if (sumBitsConsumedTotal > totalAvailableBits &&
1059           (decreaseBitConsumption == 0)) {
1060         quantizationDone = 0; /* reset! */
1061       }
1062     }
1063 
1064     /*-------------------------------------------- */
1065 
1066     int emergencyIterations = 1;
1067     int dynBitsOvershoot = 0;
1068 
1069     for (c = 0; c < nSubFrames; c++) {
1070       for (i = 0; i < cm->nElements; i++) {
1071         ELEMENT_INFO elInfo = cm->elInfo[i];
1072 
1073         if ((elInfo.elType == ID_SCE) || (elInfo.elType == ID_CPE) ||
1074             (elInfo.elType == ID_LFE)) {
1075           /* iteration limitation */
1076           emergencyIterations &=
1077               ((iterations[c][i] < hQC->maxIterations) ? 0 : 1);
1078         }
1079       }
1080       /* detection if used dyn bits exceeds the maximal allowed criterion */
1081       dynBitsOvershoot |=
1082           ((qcOut[c]->usedDynBits > qcOut[c]->maxDynBits) ? 1 : 0);
1083     }
1084 
1085     if (quantizationDone == 0 || dynBitsOvershoot) {
1086       int sumBitsConsumedTotal = FDKaacEnc_getTotalConsumedBits(
1087           qcOut, qcElement, cm, hQC->globHdrBits, nSubFrames);
1088 
1089       if ((sumDynBitsConsumedTotal >= avgTotalDynBits) ||
1090           (sumDynBitsConsumedTotal == 0)) {
1091         quantizationDone = 1;
1092       }
1093       if (emergencyIterations && (sumBitsConsumedTotal < totalAvailableBits)) {
1094         quantizationDone = 1;
1095       }
1096       if ((sumBitsConsumedTotal > totalAvailableBits) ||
1097           !checkMinFrameBitsDemand(qcOut, hQC->minBitsPerFrame, nSubFrames)) {
1098         quantizationDone = 0;
1099       }
1100       if ((sumBitsConsumedTotal < totalAvailableBits) &&
1101           checkMinFrameBitsDemand(qcOut, hQC->minBitsPerFrame, nSubFrames)) {
1102         decreaseBitConsumption = 0;
1103       } else {
1104         decreaseBitConsumption = 1;
1105       }
1106 
1107       if (dynBitsOvershoot) {
1108         quantizationDone = 0;
1109         decreaseBitConsumption = 1;
1110       }
1111 
1112       /* reset constraints fullfilled flags */
1113       FDKmemclear(constraintsFulfilled, sizeof(constraintsFulfilled));
1114       FDKmemclear(chConstraintsFulfilled, sizeof(chConstraintsFulfilled));
1115 
1116     } /* quantizationDone */
1117 
1118   } while (!quantizationDone);
1119 
1120   /*-------------------------------------------- */
1121   /* ... -end- Quantization loop                 */
1122   /*-------------------------------------------- */
1123 
1124   /*-------------------------------------------- */
1125   /*-------------------------------------------- */
1126 
1127   return AAC_ENC_OK;
1128 }
1129 
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)1130 static AAC_ENCODER_ERROR FDKaacEnc_reduceBitConsumption(
1131     int* iterations, const int maxIterations, int gainAdjustment,
1132     int* chConstraintsFulfilled, int* calculateQuant, int nChannels,
1133     PSY_OUT_ELEMENT* psyOutElement, QC_OUT* qcOut, QC_OUT_ELEMENT* qcOutElement,
1134     ELEMENT_BITS* elBits, AUDIO_OBJECT_TYPE aot, UINT syntaxFlags,
1135     SCHAR epConfig) {
1136   int ch;
1137 
1138   /** SOLVING PROBLEM **/
1139   if ((*iterations) < maxIterations) {
1140     /* increase gain (+ next iteration) */
1141     for (ch = 0; ch < nChannels; ch++) {
1142       if (!chConstraintsFulfilled[ch]) {
1143         qcOutElement->qcOutChannel[ch]->globalGain += gainAdjustment;
1144         calculateQuant[ch] = 1; /* global gain has changed, recalculate
1145                                    quantization in next iteration! */
1146       }
1147     }
1148   } else if ((*iterations) == maxIterations) {
1149     if (qcOutElement->dynBitsUsed == 0) {
1150       return AAC_ENC_QUANT_ERROR;
1151     } else {
1152       /* crash recovery */
1153       INT bitsToSave = 0;
1154       if ((bitsToSave = fixMax(
1155                (qcOutElement->dynBitsUsed + 8) -
1156                    (elBits->bitResLevelEl + qcOutElement->grantedDynBits),
1157                (qcOutElement->dynBitsUsed + qcOutElement->staticBitsUsed + 8) -
1158                    (elBits->maxBitsEl))) > 0) {
1159         FDKaacEnc_crashRecovery(nChannels, psyOutElement, qcOut, qcOutElement,
1160                                 bitsToSave, aot, syntaxFlags, epConfig);
1161       } else {
1162         for (ch = 0; ch < nChannels; ch++) {
1163           qcOutElement->qcOutChannel[ch]->globalGain += 1;
1164         }
1165       }
1166       for (ch = 0; ch < nChannels; ch++) {
1167         calculateQuant[ch] = 1;
1168       }
1169     }
1170   } else {
1171     /* (*iterations) > maxIterations */
1172     return AAC_ENC_QUANT_ERROR;
1173   }
1174   (*iterations)++;
1175 
1176   return AAC_ENC_OK;
1177 }
1178 
FDKaacEnc_updateFillBits(CHANNEL_MAPPING * cm,QC_STATE * qcKernel,ELEMENT_BITS * RESTRICT elBits[((8))],QC_OUT ** qcOut)1179 AAC_ENCODER_ERROR FDKaacEnc_updateFillBits(CHANNEL_MAPPING* cm,
1180                                            QC_STATE* qcKernel,
1181                                            ELEMENT_BITS* RESTRICT elBits[((8))],
1182                                            QC_OUT** qcOut) {
1183   switch (qcKernel->bitrateMode) {
1184     case QCDATA_BR_MODE_SFR:
1185       break;
1186 
1187     case QCDATA_BR_MODE_FF:
1188       break;
1189     case QCDATA_BR_MODE_VBR_1:
1190     case QCDATA_BR_MODE_VBR_2:
1191     case QCDATA_BR_MODE_VBR_3:
1192     case QCDATA_BR_MODE_VBR_4:
1193     case QCDATA_BR_MODE_VBR_5:
1194       qcOut[0]->totFillBits =
1195           (qcOut[0]->grantedDynBits - qcOut[0]->usedDynBits) &
1196           7; /* precalculate alignment bits */
1197       qcOut[0]->totalBits = qcOut[0]->staticBits + qcOut[0]->usedDynBits +
1198                             qcOut[0]->totFillBits + qcOut[0]->elementExtBits +
1199                             qcOut[0]->globalExtBits;
1200       qcOut[0]->totFillBits +=
1201           (fixMax(0, qcKernel->minBitsPerFrame - qcOut[0]->totalBits) + 7) & ~7;
1202       break;
1203     case QCDATA_BR_MODE_CBR:
1204     case QCDATA_BR_MODE_INVALID:
1205     default:
1206       INT bitResSpace = qcKernel->bitResTotMax - qcKernel->bitResTot;
1207       /* processing fill-bits */
1208       INT deltaBitRes = qcOut[0]->grantedDynBits - qcOut[0]->usedDynBits;
1209       qcOut[0]->totFillBits = fixMax(
1210           (deltaBitRes & 7), (deltaBitRes - (fixMax(0, bitResSpace - 7) & ~7)));
1211       qcOut[0]->totalBits = qcOut[0]->staticBits + qcOut[0]->usedDynBits +
1212                             qcOut[0]->totFillBits + qcOut[0]->elementExtBits +
1213                             qcOut[0]->globalExtBits;
1214       qcOut[0]->totFillBits +=
1215           (fixMax(0, qcKernel->minBitsPerFrame - qcOut[0]->totalBits) + 7) & ~7;
1216       break;
1217   } /* switch (qcKernel->bitrateMode) */
1218 
1219   return AAC_ENC_OK;
1220 }
1221 
1222 /*********************************************************************************
1223 
1224          functionname: FDKaacEnc_calcMaxValueInSfb
1225          description:
1226          return:
1227 
1228 **********************************************************************************/
1229 
FDKaacEnc_calcMaxValueInSfb(INT sfbCnt,INT maxSfbPerGroup,INT sfbPerGroup,INT * RESTRICT sfbOffset,SHORT * RESTRICT quantSpectrum,UINT * RESTRICT maxValue)1230 static INT FDKaacEnc_calcMaxValueInSfb(INT sfbCnt, INT maxSfbPerGroup,
1231                                        INT sfbPerGroup, INT* RESTRICT sfbOffset,
1232                                        SHORT* RESTRICT quantSpectrum,
1233                                        UINT* RESTRICT maxValue) {
1234   INT sfbOffs, sfb;
1235   INT maxValueAll = 0;
1236 
1237   for (sfbOffs = 0; sfbOffs < sfbCnt; sfbOffs += sfbPerGroup)
1238     for (sfb = 0; sfb < maxSfbPerGroup; sfb++) {
1239       INT line;
1240       INT maxThisSfb = 0;
1241       for (line = sfbOffset[sfbOffs + sfb]; line < sfbOffset[sfbOffs + sfb + 1];
1242            line++) {
1243         INT tmp = fixp_abs(quantSpectrum[line]);
1244         maxThisSfb = fixMax(tmp, maxThisSfb);
1245       }
1246 
1247       maxValue[sfbOffs + sfb] = maxThisSfb;
1248       maxValueAll = fixMax(maxThisSfb, maxValueAll);
1249     }
1250   return maxValueAll;
1251 }
1252 
1253 /*********************************************************************************
1254 
1255          functionname: FDKaacEnc_updateBitres
1256          description:
1257          return:
1258 
1259 **********************************************************************************/
FDKaacEnc_updateBitres(CHANNEL_MAPPING * cm,QC_STATE * qcKernel,QC_OUT ** qcOut)1260 void FDKaacEnc_updateBitres(CHANNEL_MAPPING* cm, QC_STATE* qcKernel,
1261                             QC_OUT** qcOut) {
1262   switch (qcKernel->bitrateMode) {
1263     case QCDATA_BR_MODE_VBR_1:
1264     case QCDATA_BR_MODE_VBR_2:
1265     case QCDATA_BR_MODE_VBR_3:
1266     case QCDATA_BR_MODE_VBR_4:
1267     case QCDATA_BR_MODE_VBR_5:
1268       /* variable bitrate */
1269       qcKernel->bitResTot =
1270           fMin(qcKernel->maxBitsPerFrame, qcKernel->bitResTotMax);
1271       break;
1272     case QCDATA_BR_MODE_CBR:
1273     case QCDATA_BR_MODE_SFR:
1274     case QCDATA_BR_MODE_INVALID:
1275     default:
1276       int c = 0;
1277       /* constant bitrate */
1278       {
1279         qcKernel->bitResTot += qcOut[c]->grantedDynBits -
1280                                (qcOut[c]->usedDynBits + qcOut[c]->totFillBits +
1281                                 qcOut[c]->alignBits);
1282       }
1283       break;
1284   }
1285 }
1286 
1287 /*********************************************************************************
1288 
1289          functionname: FDKaacEnc_FinalizeBitConsumption
1290          description:
1291          return:
1292 
1293 **********************************************************************************/
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)1294 AAC_ENCODER_ERROR FDKaacEnc_FinalizeBitConsumption(
1295     CHANNEL_MAPPING* cm, QC_STATE* qcKernel, QC_OUT* qcOut,
1296     QC_OUT_ELEMENT** qcElement, HANDLE_TRANSPORTENC hTpEnc,
1297     AUDIO_OBJECT_TYPE aot, UINT syntaxFlags, SCHAR epConfig) {
1298   QC_OUT_EXTENSION fillExtPayload;
1299   INT totFillBits, alignBits;
1300 
1301   /* Get total consumed bits in AU */
1302   qcOut->totalBits = qcOut->staticBits + qcOut->usedDynBits +
1303                      qcOut->totFillBits + qcOut->elementExtBits +
1304                      qcOut->globalExtBits;
1305 
1306   if (qcKernel->bitrateMode == QCDATA_BR_MODE_CBR) {
1307     /* Now we can get the exact transport bit amount, and hopefully it is equal
1308      * to the estimated value */
1309     INT exactTpBits = transportEnc_GetStaticBits(hTpEnc, qcOut->totalBits);
1310 
1311     if (exactTpBits != qcKernel->globHdrBits) {
1312       INT diffFillBits = 0;
1313 
1314       /* How many bits can be take by bitreservoir */
1315       const INT bitresSpace =
1316           qcKernel->bitResTotMax -
1317           (qcKernel->bitResTot +
1318            (qcOut->grantedDynBits - (qcOut->usedDynBits + qcOut->totFillBits)));
1319 
1320       /* Number of bits which can be moved to bitreservoir. */
1321       const INT bitsToBitres = qcKernel->globHdrBits - exactTpBits;
1322       FDK_ASSERT(bitsToBitres >= 0); /* is always positive */
1323 
1324       /* If bitreservoir can not take all bits, move ramaining bits to fillbits
1325        */
1326       diffFillBits = fMax(0, bitsToBitres - bitresSpace);
1327 
1328       /* Assure previous alignment */
1329       diffFillBits = (diffFillBits + 7) & ~7;
1330 
1331       /* Move as many bits as possible to bitreservoir */
1332       qcKernel->bitResTot += (bitsToBitres - diffFillBits);
1333 
1334       /* Write remaing bits as fill bits */
1335       qcOut->totFillBits += diffFillBits;
1336       qcOut->totalBits += diffFillBits;
1337       qcOut->grantedDynBits += diffFillBits;
1338 
1339       /* Get new header bits */
1340       qcKernel->globHdrBits =
1341           transportEnc_GetStaticBits(hTpEnc, qcOut->totalBits);
1342 
1343       if (qcKernel->globHdrBits != exactTpBits) {
1344         /* In previous step, fill bits and corresponding total bits were changed
1345            when bitreservoir was completely filled. Now we can take the too much
1346            taken bits caused by header overhead from bitreservoir.
1347          */
1348         qcKernel->bitResTot -= (qcKernel->globHdrBits - exactTpBits);
1349       }
1350     }
1351 
1352   } /* MODE_CBR */
1353 
1354   /* Update exact number of consumed header bits. */
1355   qcKernel->globHdrBits = transportEnc_GetStaticBits(hTpEnc, qcOut->totalBits);
1356 
1357   /* Save total fill bits and distribut to alignment and fill bits */
1358   totFillBits = qcOut->totFillBits;
1359 
1360   /* fake a fill extension payload */
1361   FDKmemclear(&fillExtPayload, sizeof(QC_OUT_EXTENSION));
1362 
1363   fillExtPayload.type = EXT_FILL_DATA;
1364   fillExtPayload.nPayloadBits = totFillBits;
1365 
1366   /* ask bitstream encoder how many of that bits can be written in a fill
1367    * extension data entity */
1368   qcOut->totFillBits = FDKaacEnc_writeExtensionData(NULL, &fillExtPayload, 0, 0,
1369                                                     syntaxFlags, aot, epConfig);
1370 
1371   /* now distribute extra fillbits and alignbits */
1372   alignBits =
1373       7 - (qcOut->staticBits + qcOut->usedDynBits + qcOut->elementExtBits +
1374            qcOut->totFillBits + qcOut->globalExtBits - 1) %
1375               8;
1376 
1377   /* Maybe we could remove this */
1378   if (((alignBits + qcOut->totFillBits - totFillBits) == 8) &&
1379       (qcOut->totFillBits > 8))
1380     qcOut->totFillBits -= 8;
1381 
1382   qcOut->totalBits = qcOut->staticBits + qcOut->usedDynBits +
1383                      qcOut->totFillBits + alignBits + qcOut->elementExtBits +
1384                      qcOut->globalExtBits;
1385 
1386   if ((qcOut->totalBits > qcKernel->maxBitsPerFrame) ||
1387       (qcOut->totalBits < qcKernel->minBitsPerFrame)) {
1388     return AAC_ENC_QUANT_ERROR;
1389   }
1390 
1391   qcOut->alignBits = alignBits;
1392 
1393   return AAC_ENC_OK;
1394 }
1395 
1396 /*********************************************************************************
1397 
1398          functionname: FDKaacEnc_crashRecovery
1399          description:  fulfills constraints by means of brute force...
1400                        => bits are saved by cancelling out spectral lines!!
1401                           (beginning at the highest frequencies)
1402          return:       errorcode
1403 
1404 **********************************************************************************/
1405 
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)1406 static void FDKaacEnc_crashRecovery(INT nChannels,
1407                                     PSY_OUT_ELEMENT* psyOutElement,
1408                                     QC_OUT* qcOut, QC_OUT_ELEMENT* qcElement,
1409                                     INT bitsToSave, AUDIO_OBJECT_TYPE aot,
1410                                     UINT syntaxFlags, SCHAR epConfig) {
1411   INT ch;
1412   INT savedBits = 0;
1413   INT sfb, sfbGrp;
1414   INT bitsPerScf[(2)][MAX_GROUPED_SFB];
1415   INT sectionToScf[(2)][MAX_GROUPED_SFB];
1416   INT* sfbOffset;
1417   INT sect, statBitsNew;
1418   QC_OUT_CHANNEL** qcChannel = qcElement->qcOutChannel;
1419   PSY_OUT_CHANNEL** psyChannel = psyOutElement->psyOutChannel;
1420 
1421   /* create a table which converts frq-bins to bit-demand...    [bitsPerScf] */
1422   /* ...and another one which holds the corresponding sections [sectionToScf] */
1423   for (ch = 0; ch < nChannels; ch++) {
1424     sfbOffset = psyChannel[ch]->sfbOffsets;
1425 
1426     for (sect = 0; sect < qcChannel[ch]->sectionData.noOfSections; sect++) {
1427       INT codeBook = qcChannel[ch]->sectionData.huffsection[sect].codeBook;
1428 
1429       for (sfb = qcChannel[ch]->sectionData.huffsection[sect].sfbStart;
1430            sfb < qcChannel[ch]->sectionData.huffsection[sect].sfbStart +
1431                      qcChannel[ch]->sectionData.huffsection[sect].sfbCnt;
1432            sfb++) {
1433         bitsPerScf[ch][sfb] = 0;
1434         if ((codeBook != CODE_BOOK_PNS_NO) /*&&
1435              (sfb < (qcChannel[ch]->sectionData.noOfGroups*qcChannel[ch]->sectionData.maxSfbPerGroup))*/) {
1436           INT sfbStartLine = sfbOffset[sfb];
1437           INT noOfLines = sfbOffset[sfb + 1] - sfbStartLine;
1438           bitsPerScf[ch][sfb] = FDKaacEnc_countValues(
1439               &(qcChannel[ch]->quantSpec[sfbStartLine]), noOfLines, codeBook);
1440         }
1441         sectionToScf[ch][sfb] = sect;
1442       }
1443     }
1444   }
1445 
1446   /* LOWER [maxSfb] IN BOTH CHANNELS!! */
1447   /* Attention: in case of stereo: maxSfbL == maxSfbR, GroupingL == GroupingR ;
1448    */
1449 
1450   for (sfb = qcChannel[0]->sectionData.maxSfbPerGroup - 1; sfb >= 0; sfb--) {
1451     for (sfbGrp = 0; sfbGrp < psyChannel[0]->sfbCnt;
1452          sfbGrp += psyChannel[0]->sfbPerGroup) {
1453       for (ch = 0; ch < nChannels; ch++) {
1454         sect = sectionToScf[ch][sfbGrp + sfb];
1455         qcChannel[ch]->sectionData.huffsection[sect].sfbCnt--;
1456         savedBits += bitsPerScf[ch][sfbGrp + sfb];
1457 
1458         if (qcChannel[ch]->sectionData.huffsection[sect].sfbCnt == 0) {
1459           savedBits += (psyChannel[ch]->lastWindowSequence != SHORT_WINDOW)
1460                            ? FDKaacEnc_sideInfoTabLong[0]
1461                            : FDKaacEnc_sideInfoTabShort[0];
1462         }
1463       }
1464     }
1465 
1466     /* ...have enough bits been saved? */
1467     if (savedBits >= bitsToSave) break;
1468 
1469   } /* sfb loop */
1470 
1471   /* if not enough bits saved,
1472      clean whole spectrum and remove side info overhead */
1473   if (sfb == -1) {
1474     sfb = 0;
1475   }
1476 
1477   for (ch = 0; ch < nChannels; ch++) {
1478     qcChannel[ch]->sectionData.maxSfbPerGroup = sfb;
1479     psyChannel[ch]->maxSfbPerGroup = sfb;
1480     /* when no spectrum is coded save tools info in bitstream */
1481     if (sfb == 0) {
1482       FDKmemclear(&psyChannel[ch]->tnsInfo, sizeof(TNS_INFO));
1483       FDKmemclear(&psyOutElement->toolsInfo, sizeof(TOOLSINFO));
1484     }
1485   }
1486   /* dynamic bits will be updated in iteration loop */
1487 
1488   { /* if stop sfb has changed save bits in side info, e.g. MS or TNS coding */
1489     ELEMENT_INFO elInfo;
1490 
1491     FDKmemclear(&elInfo, sizeof(ELEMENT_INFO));
1492     elInfo.nChannelsInEl = nChannels;
1493     elInfo.elType = (nChannels == 2) ? ID_CPE : ID_SCE;
1494 
1495     FDKaacEnc_ChannelElementWrite(NULL, &elInfo, NULL, psyOutElement,
1496                                   psyChannel, syntaxFlags, aot, epConfig,
1497                                   &statBitsNew, 0);
1498   }
1499 
1500   savedBits = qcElement->staticBitsUsed - statBitsNew;
1501 
1502   /* update static and dynamic bits */
1503   qcElement->staticBitsUsed -= savedBits;
1504   qcElement->grantedDynBits += savedBits;
1505 
1506   qcOut->staticBits -= savedBits;
1507   qcOut->grantedDynBits += savedBits;
1508   qcOut->maxDynBits += savedBits;
1509 }
1510 
FDKaacEnc_QCClose(QC_STATE ** phQCstate,QC_OUT ** phQC)1511 void FDKaacEnc_QCClose(QC_STATE** phQCstate, QC_OUT** phQC) {
1512   int n, i;
1513 
1514   if (phQC != NULL) {
1515     for (n = 0; n < (1); n++) {
1516       if (phQC[n] != NULL) {
1517         QC_OUT* hQC = phQC[n];
1518         for (i = 0; i < (8); i++) {
1519         }
1520 
1521         for (i = 0; i < ((8)); i++) {
1522           if (hQC->qcElement[i]) FreeRam_aacEnc_QCelement(&hQC->qcElement[i]);
1523         }
1524 
1525         FreeRam_aacEnc_QCout(&phQC[n]);
1526       }
1527     }
1528   }
1529 
1530   if (phQCstate != NULL) {
1531     if (*phQCstate != NULL) {
1532       QC_STATE* hQCstate = *phQCstate;
1533 
1534       if (hQCstate->hAdjThr != NULL) FDKaacEnc_AdjThrClose(&hQCstate->hAdjThr);
1535 
1536       if (hQCstate->hBitCounter != NULL)
1537         FDKaacEnc_BCClose(&hQCstate->hBitCounter);
1538 
1539       for (i = 0; i < ((8)); i++) {
1540         if (hQCstate->elementBits[i] != NULL) {
1541           FreeRam_aacEnc_ElementBits(&hQCstate->elementBits[i]);
1542         }
1543       }
1544       FreeRam_aacEnc_QCstate(phQCstate);
1545     }
1546   }
1547 }
1548