xref: /aosp_15_r20/external/aac/libAACenc/src/qc_main.cpp (revision e54365361535b070c2db7374cec45c159c7d0e7a)
1 /* -----------------------------------------------------------------------------
2 Software License for The Fraunhofer FDK AAC Codec Library for Android
3 
4 © Copyright  1995 - 2020 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 [email protected]
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   /* 0: full bitreservoir, 1: reduced bitreservoir, 2: disabled bitreservoir */
377   hQC->bitResMode = init->bitResMode;
378 
379   hQC->padding.paddingRest = init->padding.paddingRest;
380 
381   hQC->globHdrBits = init->staticBits; /* Bit overhead due to transport */
382 
383   err = FDKaacEnc_InitElementBits(
384       hQC, init->channelMapping, init->bitrate,
385       (init->averageBits / init->nSubFrames) - hQC->globHdrBits,
386       hQC->maxBitsPerFrame / init->channelMapping->nChannelsEff);
387   if (err != AAC_ENC_OK) goto bail;
388 
389   hQC->vbrQualFactor = FL2FXCONST_DBL(0.f);
390   for (i = 0;
391        i < (int)(sizeof(tableVbrQualFactor) / sizeof(TAB_VBR_QUAL_FACTOR));
392        i++) {
393     if (hQC->bitrateMode == tableVbrQualFactor[i].bitrateMode) {
394       hQC->vbrQualFactor = (FIXP_DBL)tableVbrQualFactor[i].vbrQualFactor;
395       break;
396     }
397   }
398 
399   if (init->channelMapping->nChannelsEff == 1 &&
400       (init->bitrate / init->channelMapping->nChannelsEff) <
401           AACENC_DZQ_BR_THR &&
402       init->isLowDelay !=
403           0) /* watch out here: init->bitrate is the bitrate "minus" the
404                 standard SBR bitrate (=2500kbps) --> for the FDK the OFFSTE
405                 tuning should start somewhere below 32000kbps-2500kbps ... so
406                 everything is fine here */
407   {
408     hQC->dZoneQuantEnable = 1;
409   } else {
410     hQC->dZoneQuantEnable = 0;
411   }
412 
413   FDKaacEnc_AdjThrInit(
414       hQC->hAdjThr, init->meanPe, hQC->invQuant, init->channelMapping,
415       init->sampleRate, /* output sample rate */
416       init->bitrate,    /* total bitrate */
417       init->isLowDelay, /* if set, calc bits2PE factor
418                            depending on samplerate */
419       init->bitResMode  /* for a small bitreservoir, the pe
420                            correction is calc'd differently */
421       ,
422       hQC->dZoneQuantEnable, init->bitDistributionMode, hQC->vbrQualFactor);
423 
424 bail:
425   return err;
426 }
427 
428 /*********************************************************************************
429 
430          functionname: FDKaacEnc_QCMainPrepare
431          description:
432          return:
433 
434 **********************************************************************************/
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)435 AAC_ENCODER_ERROR FDKaacEnc_QCMainPrepare(
436     ELEMENT_INFO* elInfo, ATS_ELEMENT* RESTRICT adjThrStateElement,
437     PSY_OUT_ELEMENT* RESTRICT psyOutElement,
438     QC_OUT_ELEMENT* RESTRICT qcOutElement, AUDIO_OBJECT_TYPE aot,
439     UINT syntaxFlags, SCHAR epConfig) {
440   AAC_ENCODER_ERROR ErrorStatus = AAC_ENC_OK;
441   INT nChannels = elInfo->nChannelsInEl;
442 
443   PSY_OUT_CHANNEL** RESTRICT psyOutChannel =
444       psyOutElement->psyOutChannel; /* may be modified in-place */
445 
446   FDKaacEnc_CalcFormFactor(qcOutElement->qcOutChannel, psyOutChannel,
447                            nChannels);
448 
449   /* prepare and calculate PE without reduction */
450   FDKaacEnc_peCalculation(&qcOutElement->peData, psyOutChannel,
451                           qcOutElement->qcOutChannel, &psyOutElement->toolsInfo,
452                           adjThrStateElement, nChannels);
453 
454   ErrorStatus = FDKaacEnc_ChannelElementWrite(
455       NULL, elInfo, NULL, psyOutElement, psyOutElement->psyOutChannel,
456       syntaxFlags, aot, epConfig, &qcOutElement->staticBitsUsed, 0);
457 
458   return ErrorStatus;
459 }
460 
461 /*********************************************************************************
462 
463          functionname: FDKaacEnc_AdjustBitrate
464          description:  adjusts framelength via padding on a frame to frame
465 basis, to achieve a bitrate that demands a non byte aligned framelength return:
466 errorcode
467 
468 **********************************************************************************/
FDKaacEnc_AdjustBitrate(QC_STATE * RESTRICT hQC,CHANNEL_MAPPING * RESTRICT cm,INT * avgTotalBits,INT bitRate,INT sampleRate,INT granuleLength)469 AAC_ENCODER_ERROR FDKaacEnc_AdjustBitrate(
470     QC_STATE* RESTRICT hQC, CHANNEL_MAPPING* RESTRICT cm, INT* avgTotalBits,
471     INT bitRate,       /* total bitrate */
472     INT sampleRate,    /* output sampling rate */
473     INT granuleLength) /* frame length */
474 {
475   INT paddingOn;
476   INT frameLen;
477 
478   /* Do we need an extra padding byte? */
479   paddingOn = FDKaacEnc_framePadding(bitRate, sampleRate, granuleLength,
480                                      &hQC->padding.paddingRest);
481 
482   frameLen =
483       paddingOn + FDKaacEnc_calcFrameLen(bitRate, sampleRate, granuleLength,
484                                          FRAME_LEN_BYTES_INT);
485 
486   *avgTotalBits = frameLen << 3;
487 
488   return AAC_ENC_OK;
489 }
490 
491 #define isAudioElement(elType) \
492   ((elType == ID_SCE) || (elType == ID_CPE) || (elType == ID_LFE))
493 
494 /*********************************************************************************
495 
496          functionname: FDKaacEnc_distributeElementDynBits
497          description:  distributes all bits over all elements. The relative bit
498                        distibution is described in the ELEMENT_INFO of the
499                        appropriate element. The bit distribution table is
500                        initialized in FDKaacEnc_InitChannelMapping().
501          return:       errorcode
502 
503 **********************************************************************************/
FDKaacEnc_distributeElementDynBits(QC_STATE * hQC,QC_OUT_ELEMENT * qcElement[((8))],CHANNEL_MAPPING * cm,INT codeBits)504 static AAC_ENCODER_ERROR FDKaacEnc_distributeElementDynBits(
505     QC_STATE* hQC, QC_OUT_ELEMENT* qcElement[((8))], CHANNEL_MAPPING* cm,
506     INT codeBits) {
507   INT i;             /* counter variable */
508   INT totalBits = 0; /* sum of bits over all elements */
509 
510   for (i = (cm->nElements - 1); i >= 0; i--) {
511     if (isAudioElement(cm->elInfo[i].elType)) {
512       qcElement[i]->grantedDynBits =
513           fMax(0, fMultI(hQC->elementBits[i]->relativeBitsEl, codeBits));
514       totalBits += qcElement[i]->grantedDynBits;
515     }
516   }
517 
518   /* Due to inaccuracies with the multiplication, codeBits may differ from
519      totalBits. For that case, the difference must be added/substracted again
520      to/from one element, i.e:
521      Negative differences are substracted from the element with the most bits.
522      Positive differences are added to the element with the least bits.
523   */
524   if (codeBits != totalBits) {
525     INT elMaxBits = cm->nElements - 1; /* element with the most bits */
526     INT elMinBits = cm->nElements - 1; /* element with the least bits */
527 
528     /* Search for biggest and smallest audio element */
529     for (i = (cm->nElements - 1); i >= 0; i--) {
530       if (isAudioElement(cm->elInfo[i].elType)) {
531         if (qcElement[i]->grantedDynBits >
532             qcElement[elMaxBits]->grantedDynBits) {
533           elMaxBits = i;
534         }
535         if (qcElement[i]->grantedDynBits <
536             qcElement[elMinBits]->grantedDynBits) {
537           elMinBits = i;
538         }
539       }
540     }
541     /* Compensate for bit distibution difference */
542     if (codeBits - totalBits > 0) {
543       qcElement[elMinBits]->grantedDynBits += codeBits - totalBits;
544     } else {
545       qcElement[elMaxBits]->grantedDynBits += codeBits - totalBits;
546     }
547   }
548 
549   return AAC_ENC_OK;
550 }
551 
552 /**
553  * \brief  Verify whether minBitsPerFrame criterion can be satisfied.
554  *
555  * This function evaluates the bit consumption only if minBitsPerFrame parameter
556  * is not 0. In hyperframing mode the difference between grantedDynBits and
557  * usedDynBits of all sub frames results the number of fillbits to be written.
558  * This bits can be distrubitued in superframe to reach minBitsPerFrame bit
559  * consumption in single AU's. The return value denotes if enough desired fill
560  * bits are available to achieve minBitsPerFrame in all frames. This check can
561  * only be used within superframes.
562  *
563  * \param qcOut            Pointer to coding data struct.
564  * \param minBitsPerFrame  Minimal number of bits to be consumed in each frame.
565  * \param nSubFrames       Number of frames in superframe
566  *
567  * \return
568  *          - 1: all fine
569  *          - 0: criterion not fulfilled
570  */
checkMinFrameBitsDemand(QC_OUT ** qcOut,const INT minBitsPerFrame,const INT nSubFrames)571 static int checkMinFrameBitsDemand(QC_OUT** qcOut, const INT minBitsPerFrame,
572                                    const INT nSubFrames) {
573   int result = 1; /* all fine*/
574   return result;
575 }
576 
577 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
578 
579 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
580 /*********************************************************************************
581 
582          functionname: FDKaacEnc_getMinimalStaticBitdemand
583          description:  calculate minmal size of static bits by reduction ,
584                        to zero spectrum and deactivating tns and MS
585          return:       number of static bits
586 
587 **********************************************************************************/
FDKaacEnc_getMinimalStaticBitdemand(CHANNEL_MAPPING * cm,PSY_OUT ** psyOut)588 static int FDKaacEnc_getMinimalStaticBitdemand(CHANNEL_MAPPING* cm,
589                                                PSY_OUT** psyOut) {
590   AUDIO_OBJECT_TYPE aot = AOT_AAC_LC;
591   UINT syntaxFlags = 0;
592   SCHAR epConfig = -1;
593   int i, bitcount = 0;
594 
595   for (i = 0; i < cm->nElements; i++) {
596     ELEMENT_INFO elInfo = cm->elInfo[i];
597 
598     if ((elInfo.elType == ID_SCE) || (elInfo.elType == ID_CPE) ||
599         (elInfo.elType == ID_LFE)) {
600       INT minElBits = 0;
601 
602       FDKaacEnc_ChannelElementWrite(NULL, &elInfo, NULL,
603                                     psyOut[0]->psyOutElement[i],
604                                     psyOut[0]->psyOutElement[i]->psyOutChannel,
605                                     syntaxFlags, aot, epConfig, &minElBits, 1);
606       bitcount += minElBits;
607     }
608   }
609 
610   return bitcount;
611 }
612 
613 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
614 
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)615 static AAC_ENCODER_ERROR FDKaacEnc_prepareBitDistribution(
616     QC_STATE* hQC, PSY_OUT** psyOut, QC_OUT** qcOut, CHANNEL_MAPPING* cm,
617     QC_OUT_ELEMENT* qcElement[(1)][((8))], INT avgTotalBits,
618     INT* totalAvailableBits, INT* avgTotalDynBits) {
619   int i;
620   /* get maximal allowed dynamic bits */
621   qcOut[0]->grantedDynBits =
622       (fixMin(hQC->maxBitsPerFrame, avgTotalBits) - hQC->globHdrBits) & ~7;
623   qcOut[0]->grantedDynBits -= (qcOut[0]->globalExtBits + qcOut[0]->staticBits +
624                                qcOut[0]->elementExtBits);
625   qcOut[0]->maxDynBits = ((hQC->maxBitsPerFrame) & ~7) -
626                          (qcOut[0]->globalExtBits + qcOut[0]->staticBits +
627                           qcOut[0]->elementExtBits);
628   /* assure that enough bits are available */
629   if ((qcOut[0]->grantedDynBits + hQC->bitResTot) < 0) {
630     /* crash recovery allows to reduce static bits to a minimum */
631     if ((qcOut[0]->grantedDynBits + hQC->bitResTot) <
632         (FDKaacEnc_getMinimalStaticBitdemand(cm, psyOut) -
633          qcOut[0]->staticBits))
634       return AAC_ENC_BITRES_TOO_LOW;
635   }
636 
637   /* distribute dynamic bits to each element */
638   FDKaacEnc_distributeElementDynBits(hQC, qcElement[0], cm,
639                                      qcOut[0]->grantedDynBits);
640 
641   *avgTotalDynBits = 0; /*frameDynBits;*/
642 
643   *totalAvailableBits = avgTotalBits;
644 
645   /* sum up corrected granted PE */
646   qcOut[0]->totalGrantedPeCorr = 0;
647 
648   for (i = 0; i < cm->nElements; i++) {
649     ELEMENT_INFO elInfo = cm->elInfo[i];
650     int nChannels = elInfo.nChannelsInEl;
651 
652     if ((elInfo.elType == ID_SCE) || (elInfo.elType == ID_CPE) ||
653         (elInfo.elType == ID_LFE)) {
654       /* for ( all sub frames ) ... */
655       FDKaacEnc_DistributeBits(
656           hQC->hAdjThr, hQC->hAdjThr->adjThrStateElem[i],
657           psyOut[0]->psyOutElement[i]->psyOutChannel, &qcElement[0][i]->peData,
658           &qcElement[0][i]->grantedPe, &qcElement[0][i]->grantedPeCorr,
659           nChannels, psyOut[0]->psyOutElement[i]->commonWindow,
660           qcElement[0][i]->grantedDynBits, hQC->elementBits[i]->bitResLevelEl,
661           hQC->elementBits[i]->maxBitResBitsEl, hQC->maxBitFac,
662           hQC->bitResMode);
663 
664       *totalAvailableBits += hQC->elementBits[i]->bitResLevelEl;
665       /* get total corrected granted PE */
666       qcOut[0]->totalGrantedPeCorr += qcElement[0][i]->grantedPeCorr;
667     } /*  -end- if(ID_SCE || ID_CPE || ID_LFE) */
668 
669   } /* -end- element loop */
670 
671   *totalAvailableBits = fMin(hQC->maxBitsPerFrame, (*totalAvailableBits));
672 
673   return AAC_ENC_OK;
674 }
675 
676 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
FDKaacEnc_updateUsedDynBits(INT * sumDynBitsConsumed,QC_OUT_ELEMENT * qcElement[((8))],CHANNEL_MAPPING * cm)677 static AAC_ENCODER_ERROR FDKaacEnc_updateUsedDynBits(
678     INT* sumDynBitsConsumed, QC_OUT_ELEMENT* qcElement[((8))],
679     CHANNEL_MAPPING* cm) {
680   INT i;
681 
682   *sumDynBitsConsumed = 0;
683 
684   for (i = 0; i < cm->nElements; i++) {
685     ELEMENT_INFO elInfo = cm->elInfo[i];
686 
687     if ((elInfo.elType == ID_SCE) || (elInfo.elType == ID_CPE) ||
688         (elInfo.elType == ID_LFE)) {
689       /* sum up bits consumed */
690       *sumDynBitsConsumed += qcElement[i]->dynBitsUsed;
691     } /*  -end- if(ID_SCE || ID_CPE || ID_LFE) */
692 
693   } /* -end- element loop */
694 
695   return AAC_ENC_OK;
696 }
697 
FDKaacEnc_getTotalConsumedDynBits(QC_OUT ** qcOut,INT nSubFrames)698 static INT FDKaacEnc_getTotalConsumedDynBits(QC_OUT** qcOut, INT nSubFrames) {
699   INT c, totalBits = 0;
700 
701   /* sum up bit consumption for all sub frames */
702   for (c = 0; c < nSubFrames; c++) {
703     /* bit consumption not valid if dynamic bits
704        not available in one sub frame */
705     if (qcOut[c]->usedDynBits == -1) return -1;
706     totalBits += qcOut[c]->usedDynBits;
707   }
708 
709   return totalBits;
710 }
711 
FDKaacEnc_getTotalConsumedBits(QC_OUT ** qcOut,QC_OUT_ELEMENT * qcElement[(1)][((8))],CHANNEL_MAPPING * cm,INT globHdrBits,INT nSubFrames)712 static INT FDKaacEnc_getTotalConsumedBits(QC_OUT** qcOut,
713                                           QC_OUT_ELEMENT* qcElement[(1)][((8))],
714                                           CHANNEL_MAPPING* cm, INT globHdrBits,
715                                           INT nSubFrames) {
716   int c, i;
717   int totalUsedBits = 0;
718 
719   for (c = 0; c < nSubFrames; c++) {
720     int dataBits = 0;
721     for (i = 0; i < cm->nElements; i++) {
722       if ((cm->elInfo[i].elType == ID_SCE) ||
723           (cm->elInfo[i].elType == ID_CPE) ||
724           (cm->elInfo[i].elType == ID_LFE)) {
725         dataBits += qcElement[c][i]->dynBitsUsed +
726                     qcElement[c][i]->staticBitsUsed +
727                     qcElement[c][i]->extBitsUsed;
728       }
729     }
730     dataBits += qcOut[c]->globalExtBits;
731 
732     totalUsedBits += (8 - (dataBits) % 8) % 8;
733     totalUsedBits += dataBits + globHdrBits; /* header bits for every frame */
734   }
735   return totalUsedBits;
736 }
737 
FDKaacEnc_BitResRedistribution(QC_STATE * const hQC,const CHANNEL_MAPPING * const cm,const INT avgTotalBits)738 static AAC_ENCODER_ERROR FDKaacEnc_BitResRedistribution(
739     QC_STATE* const hQC, const CHANNEL_MAPPING* const cm,
740     const INT avgTotalBits) {
741   /* check bitreservoir fill level */
742   if (hQC->bitResTot < 0) {
743     return AAC_ENC_BITRES_TOO_LOW;
744   } else if (hQC->bitResTot > hQC->bitResTotMax) {
745     return AAC_ENC_BITRES_TOO_HIGH;
746   } else {
747     INT i;
748     INT totalBits = 0, totalBits_max = 0;
749 
750     const int totalBitreservoir =
751         fMin(hQC->bitResTot, (hQC->maxBitsPerFrame - avgTotalBits));
752     const int totalBitreservoirMax =
753         fMin(hQC->bitResTotMax, (hQC->maxBitsPerFrame - avgTotalBits));
754 
755     for (i = (cm->nElements - 1); i >= 0; i--) {
756       if ((cm->elInfo[i].elType == ID_SCE) ||
757           (cm->elInfo[i].elType == ID_CPE) ||
758           (cm->elInfo[i].elType == ID_LFE)) {
759         hQC->elementBits[i]->bitResLevelEl =
760             fMultI(hQC->elementBits[i]->relativeBitsEl, totalBitreservoir);
761         totalBits += hQC->elementBits[i]->bitResLevelEl;
762 
763         hQC->elementBits[i]->maxBitResBitsEl =
764             fMultI(hQC->elementBits[i]->relativeBitsEl, totalBitreservoirMax);
765         totalBits_max += hQC->elementBits[i]->maxBitResBitsEl;
766       }
767     }
768     for (i = 0; i < cm->nElements; i++) {
769       if ((cm->elInfo[i].elType == ID_SCE) ||
770           (cm->elInfo[i].elType == ID_CPE) ||
771           (cm->elInfo[i].elType == ID_LFE)) {
772         int deltaBits = fMax(totalBitreservoir - totalBits,
773                              -hQC->elementBits[i]->bitResLevelEl);
774         hQC->elementBits[i]->bitResLevelEl += deltaBits;
775         totalBits += deltaBits;
776 
777         deltaBits = fMax(totalBitreservoirMax - totalBits_max,
778                          -hQC->elementBits[i]->maxBitResBitsEl);
779         hQC->elementBits[i]->maxBitResBitsEl += deltaBits;
780         totalBits_max += deltaBits;
781       }
782     }
783   }
784 
785   return AAC_ENC_OK;
786 }
787 
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)788 AAC_ENCODER_ERROR FDKaacEnc_QCMain(QC_STATE* RESTRICT hQC, PSY_OUT** psyOut,
789                                    QC_OUT** qcOut, INT avgTotalBits,
790                                    CHANNEL_MAPPING* cm,
791                                    const AUDIO_OBJECT_TYPE aot,
792                                    UINT syntaxFlags, SCHAR epConfig) {
793   int i, c;
794   AAC_ENCODER_ERROR ErrorStatus = AAC_ENC_OK;
795   INT avgTotalDynBits = 0; /* maximal allowed dynamic bits for all frames */
796   INT totalAvailableBits = 0;
797   INT nSubFrames = 1;
798   const INT isCBRAdjustment = (isConstantBitrateMode(hQC->bitrateMode) ||
799                                (hQC->bitResMode != AACENC_BR_MODE_FULL))
800                                   ? 1
801                                   : 0;
802 
803   /*-------------------------------------------- */
804   /* redistribute total bitreservoir to elements */
805   ErrorStatus = FDKaacEnc_BitResRedistribution(
806       hQC, cm, (isCBRAdjustment == 0) ? hQC->maxBitsPerFrame : 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   /* calc granted dynamic bits for sub frame and
835      distribute it to each element */
836   ErrorStatus = FDKaacEnc_prepareBitDistribution(
837       hQC, psyOut, qcOut, cm, qcElement,
838       (isCBRAdjustment == 0) ? hQC->maxBitsPerFrame : avgTotalBits,
839       &totalAvailableBits, &avgTotalDynBits);
840 
841   if (ErrorStatus != AAC_ENC_OK) {
842     return ErrorStatus;
843   }
844 
845   /* for ( all sub frames ) ... */
846   for (c = 0; c < nSubFrames; c++) {
847     /* for CBR and VBR mode */
848     FDKaacEnc_AdjustThresholds(hQC->hAdjThr, qcElement[c], qcOut[c],
849                                psyOut[c]->psyOutElement, isCBRAdjustment, cm);
850 
851   } /* -end- sub frame counter */
852 
853   /*-------------------------------------------- */
854   INT iterations[(1)][((8))];
855   INT chConstraintsFulfilled[(1)][((8))][(2)];
856   INT calculateQuant[(1)][((8))][(2)];
857   INT constraintsFulfilled[(1)][((8))];
858   /*-------------------------------------------- */
859 
860   /* for ( all sub frames ) ... */
861   for (c = 0; c < nSubFrames; c++) {
862     for (i = 0; i < cm->nElements; i++) {
863       ELEMENT_INFO elInfo = cm->elInfo[i];
864       INT ch, nChannels = elInfo.nChannelsInEl;
865 
866       if ((elInfo.elType == ID_SCE) || (elInfo.elType == ID_CPE) ||
867           (elInfo.elType == ID_LFE)) {
868         /* Turn thresholds into scalefactors, optimize bit consumption and
869          * verify conformance */
870         FDKaacEnc_EstimateScaleFactors(
871             psyOut[c]->psyOutElement[i]->psyOutChannel,
872             qcElement[c][i]->qcOutChannel, hQC->invQuant, hQC->dZoneQuantEnable,
873             cm->elInfo[i].nChannelsInEl);
874 
875         /*-------------------------------------------- */
876         constraintsFulfilled[c][i] = 1;
877         iterations[c][i] = 0;
878 
879         for (ch = 0; ch < nChannels; ch++) {
880           chConstraintsFulfilled[c][i][ch] = 1;
881           calculateQuant[c][i][ch] = 1;
882         }
883 
884         /*-------------------------------------------- */
885 
886       } /*  -end- if(ID_SCE || ID_CPE || ID_LFE) */
887 
888     } /* -end- element loop */
889 
890     qcOut[c]->usedDynBits = -1;
891 
892   } /* -end- sub frame counter */
893 
894   INT quantizationDone = 0;
895   INT sumDynBitsConsumedTotal = 0;
896   INT decreaseBitConsumption = -1; /* no direction yet! */
897 
898   /*-------------------------------------------- */
899   /* -start- Quantization loop ...               */
900   /*-------------------------------------------- */
901   do /* until max allowed bits per frame and maxDynBits!=-1*/
902   {
903     quantizationDone = 0;
904 
905     c = 0; /* get frame to process */
906 
907     for (i = 0; i < cm->nElements; i++) {
908       ELEMENT_INFO elInfo = cm->elInfo[i];
909       INT ch, nChannels = elInfo.nChannelsInEl;
910 
911       if ((elInfo.elType == ID_SCE) || (elInfo.elType == ID_CPE) ||
912           (elInfo.elType == ID_LFE)) {
913         do /* until element bits < nChannels*MIN_BUFSIZE_PER_EFF_CHAN */
914         {
915           do /* until spectral values < MAX_QUANT */
916           {
917             /*-------------------------------------------- */
918             if (!constraintsFulfilled[c][i]) {
919               if ((ErrorStatus = FDKaacEnc_reduceBitConsumption(
920                        &iterations[c][i], hQC->maxIterations,
921                        (decreaseBitConsumption) ? 1 : -1,
922                        chConstraintsFulfilled[c][i], calculateQuant[c][i],
923                        nChannels, psyOut[c]->psyOutElement[i], qcOut[c],
924                        qcElement[c][i], hQC->elementBits[i], aot, syntaxFlags,
925                        epConfig)) != AAC_ENC_OK) {
926                 return ErrorStatus;
927               }
928             }
929 
930             /*-------------------------------------------- */
931             /*-------------------------------------------- */
932             constraintsFulfilled[c][i] = 1;
933 
934             /*-------------------------------------------- */
935             /* quantize spectrum (per each channel) */
936             for (ch = 0; ch < nChannels; ch++) {
937               /*-------------------------------------------- */
938               chConstraintsFulfilled[c][i][ch] = 1;
939 
940               /*-------------------------------------------- */
941 
942               if (calculateQuant[c][i][ch]) {
943                 QC_OUT_CHANNEL* qcOutCh = qcElement[c][i]->qcOutChannel[ch];
944                 PSY_OUT_CHANNEL* psyOutCh =
945                     psyOut[c]->psyOutElement[i]->psyOutChannel[ch];
946 
947                 calculateQuant[c][i][ch] =
948                     0; /* calculate quantization only if necessary */
949 
950                 /*-------------------------------------------- */
951                 FDKaacEnc_QuantizeSpectrum(
952                     psyOutCh->sfbCnt, psyOutCh->maxSfbPerGroup,
953                     psyOutCh->sfbPerGroup, psyOutCh->sfbOffsets,
954                     qcOutCh->mdctSpectrum, qcOutCh->globalGain, qcOutCh->scf,
955                     qcOutCh->quantSpec, hQC->dZoneQuantEnable);
956 
957                 /*-------------------------------------------- */
958                 if (FDKaacEnc_calcMaxValueInSfb(
959                         psyOutCh->sfbCnt, psyOutCh->maxSfbPerGroup,
960                         psyOutCh->sfbPerGroup, psyOutCh->sfbOffsets,
961                         qcOutCh->quantSpec,
962                         qcOutCh->maxValueInSfb) > MAX_QUANT) {
963                   chConstraintsFulfilled[c][i][ch] = 0;
964                   constraintsFulfilled[c][i] = 0;
965                   /* if quanizted value out of range; increase global gain! */
966                   decreaseBitConsumption = 1;
967                 }
968 
969                 /*-------------------------------------------- */
970 
971               } /* if calculateQuant[c][i][ch] */
972 
973             } /* channel loop */
974 
975             /*-------------------------------------------- */
976             /* quantize spectrum (per each channel) */
977 
978             /*-------------------------------------------- */
979 
980           } while (!constraintsFulfilled[c][i]); /* does not regard bit
981                                                     consumption */
982 
983           /*-------------------------------------------- */
984           /*-------------------------------------------- */
985           qcElement[c][i]->dynBitsUsed = 0; /* reset dynamic bits */
986 
987           /* quantization valid in current channel! */
988           for (ch = 0; ch < nChannels; ch++) {
989             QC_OUT_CHANNEL* qcOutCh = qcElement[c][i]->qcOutChannel[ch];
990             PSY_OUT_CHANNEL* psyOutCh =
991                 psyOut[c]->psyOutElement[i]->psyOutChannel[ch];
992 
993             /* count dynamic bits */
994             INT chDynBits = FDKaacEnc_dynBitCount(
995                 hQC->hBitCounter, qcOutCh->quantSpec, qcOutCh->maxValueInSfb,
996                 qcOutCh->scf, psyOutCh->lastWindowSequence, psyOutCh->sfbCnt,
997                 psyOutCh->maxSfbPerGroup, psyOutCh->sfbPerGroup,
998                 psyOutCh->sfbOffsets, &qcOutCh->sectionData, psyOutCh->noiseNrg,
999                 psyOutCh->isBook, psyOutCh->isScale, syntaxFlags);
1000 
1001             /* sum up dynamic channel bits */
1002             qcElement[c][i]->dynBitsUsed += chDynBits;
1003           }
1004 
1005           /* save dynBitsUsed for correction of bits2pe relation */
1006           if (hQC->hAdjThr->adjThrStateElem[i]->dynBitsLast == -1) {
1007             hQC->hAdjThr->adjThrStateElem[i]->dynBitsLast =
1008                 qcElement[c][i]->dynBitsUsed;
1009           }
1010 
1011           /* hold total bit consumption in present element below maximum allowed
1012            */
1013           if (qcElement[c][i]->dynBitsUsed >
1014               ((nChannels * MIN_BUFSIZE_PER_EFF_CHAN) -
1015                qcElement[c][i]->staticBitsUsed -
1016                qcElement[c][i]->extBitsUsed)) {
1017             constraintsFulfilled[c][i] = 0;
1018           }
1019 
1020         } while (!constraintsFulfilled[c][i]);
1021 
1022       } /*  -end- if(ID_SCE || ID_CPE || ID_LFE) */
1023 
1024     } /* -end- element loop */
1025 
1026     /* update dynBits of current subFrame */
1027     FDKaacEnc_updateUsedDynBits(&qcOut[c]->usedDynBits, qcElement[c], cm);
1028 
1029     /* get total consumed bits, dyn bits in all sub frames have to be valid */
1030     sumDynBitsConsumedTotal =
1031         FDKaacEnc_getTotalConsumedDynBits(qcOut, nSubFrames);
1032 
1033     if (sumDynBitsConsumedTotal == -1) {
1034       quantizationDone = 0; /* bit consumption not valid in all sub frames */
1035     } else {
1036       int sumBitsConsumedTotal = FDKaacEnc_getTotalConsumedBits(
1037           qcOut, qcElement, cm, hQC->globHdrBits, nSubFrames);
1038 
1039       /* in all frames are valid dynamic bits */
1040       if (((sumBitsConsumedTotal < totalAvailableBits) ||
1041            sumDynBitsConsumedTotal == 0) &&
1042           (decreaseBitConsumption == 1) &&
1043           checkMinFrameBitsDemand(qcOut, hQC->minBitsPerFrame, nSubFrames)
1044           /*()*/) {
1045         quantizationDone = 1; /* exit bit adjustment */
1046       }
1047       if (sumBitsConsumedTotal > totalAvailableBits &&
1048           (decreaseBitConsumption == 0)) {
1049         quantizationDone = 0; /* reset! */
1050       }
1051     }
1052 
1053     /*-------------------------------------------- */
1054 
1055     int emergencyIterations = 1;
1056     int dynBitsOvershoot = 0;
1057 
1058     for (c = 0; c < nSubFrames; c++) {
1059       for (i = 0; i < cm->nElements; i++) {
1060         ELEMENT_INFO elInfo = cm->elInfo[i];
1061 
1062         if ((elInfo.elType == ID_SCE) || (elInfo.elType == ID_CPE) ||
1063             (elInfo.elType == ID_LFE)) {
1064           /* iteration limitation */
1065           emergencyIterations &=
1066               ((iterations[c][i] < hQC->maxIterations) ? 0 : 1);
1067         }
1068       }
1069       /* detection if used dyn bits exceeds the maximal allowed criterion */
1070       dynBitsOvershoot |=
1071           ((qcOut[c]->usedDynBits > qcOut[c]->maxDynBits) ? 1 : 0);
1072     }
1073 
1074     if (quantizationDone == 0 || dynBitsOvershoot) {
1075       int sumBitsConsumedTotal = FDKaacEnc_getTotalConsumedBits(
1076           qcOut, qcElement, cm, hQC->globHdrBits, nSubFrames);
1077 
1078       if ((sumDynBitsConsumedTotal >= avgTotalDynBits) ||
1079           (sumDynBitsConsumedTotal == 0)) {
1080         quantizationDone = 1;
1081       }
1082       if (emergencyIterations && (sumBitsConsumedTotal < totalAvailableBits)) {
1083         quantizationDone = 1;
1084       }
1085       if ((sumBitsConsumedTotal > totalAvailableBits) ||
1086           !checkMinFrameBitsDemand(qcOut, hQC->minBitsPerFrame, nSubFrames)) {
1087         quantizationDone = 0;
1088       }
1089       if ((sumBitsConsumedTotal < totalAvailableBits) &&
1090           checkMinFrameBitsDemand(qcOut, hQC->minBitsPerFrame, nSubFrames)) {
1091         decreaseBitConsumption = 0;
1092       } else {
1093         decreaseBitConsumption = 1;
1094       }
1095 
1096       if (dynBitsOvershoot) {
1097         quantizationDone = 0;
1098         decreaseBitConsumption = 1;
1099       }
1100 
1101       /* reset constraints fullfilled flags */
1102       FDKmemclear(constraintsFulfilled, sizeof(constraintsFulfilled));
1103       FDKmemclear(chConstraintsFulfilled, sizeof(chConstraintsFulfilled));
1104 
1105     } /* quantizationDone */
1106 
1107   } while (!quantizationDone);
1108 
1109   /*-------------------------------------------- */
1110   /* ... -end- Quantization loop                 */
1111   /*-------------------------------------------- */
1112 
1113   /*-------------------------------------------- */
1114   /*-------------------------------------------- */
1115 
1116   return AAC_ENC_OK;
1117 }
1118 
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)1119 static AAC_ENCODER_ERROR FDKaacEnc_reduceBitConsumption(
1120     int* iterations, const int maxIterations, int gainAdjustment,
1121     int* chConstraintsFulfilled, int* calculateQuant, int nChannels,
1122     PSY_OUT_ELEMENT* psyOutElement, QC_OUT* qcOut, QC_OUT_ELEMENT* qcOutElement,
1123     ELEMENT_BITS* elBits, AUDIO_OBJECT_TYPE aot, UINT syntaxFlags,
1124     SCHAR epConfig) {
1125   int ch;
1126 
1127   /** SOLVING PROBLEM **/
1128   if ((*iterations) < maxIterations) {
1129     /* increase gain (+ next iteration) */
1130     for (ch = 0; ch < nChannels; ch++) {
1131       if (!chConstraintsFulfilled[ch]) {
1132         qcOutElement->qcOutChannel[ch]->globalGain += gainAdjustment;
1133         calculateQuant[ch] = 1; /* global gain has changed, recalculate
1134                                    quantization in next iteration! */
1135       }
1136     }
1137   } else if ((*iterations) == maxIterations) {
1138     if (qcOutElement->dynBitsUsed == 0) {
1139       return AAC_ENC_QUANT_ERROR;
1140     } else {
1141       /* crash recovery */
1142       INT bitsToSave = 0;
1143       if ((bitsToSave = fixMax(
1144                (qcOutElement->dynBitsUsed + 8) -
1145                    (elBits->bitResLevelEl + qcOutElement->grantedDynBits),
1146                (qcOutElement->dynBitsUsed + qcOutElement->staticBitsUsed + 8) -
1147                    (elBits->maxBitsEl))) > 0) {
1148         FDKaacEnc_crashRecovery(nChannels, psyOutElement, qcOut, qcOutElement,
1149                                 bitsToSave, aot, syntaxFlags, epConfig);
1150       } else {
1151         for (ch = 0; ch < nChannels; ch++) {
1152           qcOutElement->qcOutChannel[ch]->globalGain += 1;
1153         }
1154       }
1155       for (ch = 0; ch < nChannels; ch++) {
1156         calculateQuant[ch] = 1;
1157       }
1158     }
1159   } else {
1160     /* (*iterations) > maxIterations */
1161     return AAC_ENC_QUANT_ERROR;
1162   }
1163   (*iterations)++;
1164 
1165   return AAC_ENC_OK;
1166 }
1167 
FDKaacEnc_updateFillBits(CHANNEL_MAPPING * cm,QC_STATE * qcKernel,ELEMENT_BITS * RESTRICT elBits[((8))],QC_OUT ** qcOut)1168 AAC_ENCODER_ERROR FDKaacEnc_updateFillBits(CHANNEL_MAPPING* cm,
1169                                            QC_STATE* qcKernel,
1170                                            ELEMENT_BITS* RESTRICT elBits[((8))],
1171                                            QC_OUT** qcOut) {
1172   switch (qcKernel->bitrateMode) {
1173     case QCDATA_BR_MODE_SFR:
1174       break;
1175 
1176     case QCDATA_BR_MODE_FF:
1177       break;
1178     case QCDATA_BR_MODE_VBR_1:
1179     case QCDATA_BR_MODE_VBR_2:
1180     case QCDATA_BR_MODE_VBR_3:
1181     case QCDATA_BR_MODE_VBR_4:
1182     case QCDATA_BR_MODE_VBR_5:
1183       qcOut[0]->totFillBits =
1184           (qcOut[0]->grantedDynBits - qcOut[0]->usedDynBits) &
1185           7; /* precalculate alignment bits */
1186       qcOut[0]->totalBits = qcOut[0]->staticBits + qcOut[0]->usedDynBits +
1187                             qcOut[0]->totFillBits + qcOut[0]->elementExtBits +
1188                             qcOut[0]->globalExtBits;
1189       qcOut[0]->totFillBits +=
1190           (fixMax(0, qcKernel->minBitsPerFrame - qcOut[0]->totalBits) + 7) & ~7;
1191       break;
1192     case QCDATA_BR_MODE_CBR:
1193     case QCDATA_BR_MODE_INVALID:
1194     default:
1195       INT bitResSpace = qcKernel->bitResTotMax - qcKernel->bitResTot;
1196       /* processing fill-bits */
1197       INT deltaBitRes = qcOut[0]->grantedDynBits - qcOut[0]->usedDynBits;
1198       qcOut[0]->totFillBits = fixMax(
1199           (deltaBitRes & 7), (deltaBitRes - (fixMax(0, bitResSpace - 7) & ~7)));
1200       qcOut[0]->totalBits = qcOut[0]->staticBits + qcOut[0]->usedDynBits +
1201                             qcOut[0]->totFillBits + qcOut[0]->elementExtBits +
1202                             qcOut[0]->globalExtBits;
1203       qcOut[0]->totFillBits +=
1204           (fixMax(0, qcKernel->minBitsPerFrame - qcOut[0]->totalBits) + 7) & ~7;
1205       break;
1206   } /* switch (qcKernel->bitrateMode) */
1207 
1208   return AAC_ENC_OK;
1209 }
1210 
1211 /*********************************************************************************
1212 
1213          functionname: FDKaacEnc_calcMaxValueInSfb
1214          description:
1215          return:
1216 
1217 **********************************************************************************/
1218 
FDKaacEnc_calcMaxValueInSfb(INT sfbCnt,INT maxSfbPerGroup,INT sfbPerGroup,INT * RESTRICT sfbOffset,SHORT * RESTRICT quantSpectrum,UINT * RESTRICT maxValue)1219 static INT FDKaacEnc_calcMaxValueInSfb(INT sfbCnt, INT maxSfbPerGroup,
1220                                        INT sfbPerGroup, INT* RESTRICT sfbOffset,
1221                                        SHORT* RESTRICT quantSpectrum,
1222                                        UINT* RESTRICT maxValue) {
1223   INT sfbOffs, sfb;
1224   INT maxValueAll = 0;
1225 
1226   for (sfbOffs = 0; sfbOffs < sfbCnt; sfbOffs += sfbPerGroup)
1227     for (sfb = 0; sfb < maxSfbPerGroup; sfb++) {
1228       INT line;
1229       INT maxThisSfb = 0;
1230       for (line = sfbOffset[sfbOffs + sfb]; line < sfbOffset[sfbOffs + sfb + 1];
1231            line++) {
1232         INT tmp = fixp_abs(quantSpectrum[line]);
1233         maxThisSfb = fixMax(tmp, maxThisSfb);
1234       }
1235 
1236       maxValue[sfbOffs + sfb] = maxThisSfb;
1237       maxValueAll = fixMax(maxThisSfb, maxValueAll);
1238     }
1239   return maxValueAll;
1240 }
1241 
1242 /*********************************************************************************
1243 
1244          functionname: FDKaacEnc_updateBitres
1245          description:
1246          return:
1247 
1248 **********************************************************************************/
FDKaacEnc_updateBitres(CHANNEL_MAPPING * cm,QC_STATE * qcKernel,QC_OUT ** qcOut)1249 void FDKaacEnc_updateBitres(CHANNEL_MAPPING* cm, QC_STATE* qcKernel,
1250                             QC_OUT** qcOut) {
1251   switch (qcKernel->bitrateMode) {
1252     case QCDATA_BR_MODE_VBR_1:
1253     case QCDATA_BR_MODE_VBR_2:
1254     case QCDATA_BR_MODE_VBR_3:
1255     case QCDATA_BR_MODE_VBR_4:
1256     case QCDATA_BR_MODE_VBR_5:
1257       /* variable bitrate */
1258       qcKernel->bitResTot =
1259           fMin(qcKernel->maxBitsPerFrame, qcKernel->bitResTotMax);
1260       break;
1261     case QCDATA_BR_MODE_CBR:
1262     case QCDATA_BR_MODE_SFR:
1263     case QCDATA_BR_MODE_INVALID:
1264     default:
1265       int c = 0;
1266       /* constant bitrate */
1267       {
1268         qcKernel->bitResTot += qcOut[c]->grantedDynBits -
1269                                (qcOut[c]->usedDynBits + qcOut[c]->totFillBits +
1270                                 qcOut[c]->alignBits);
1271       }
1272       break;
1273   }
1274 }
1275 
1276 /*********************************************************************************
1277 
1278          functionname: FDKaacEnc_FinalizeBitConsumption
1279          description:
1280          return:
1281 
1282 **********************************************************************************/
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)1283 AAC_ENCODER_ERROR FDKaacEnc_FinalizeBitConsumption(
1284     CHANNEL_MAPPING* cm, QC_STATE* qcKernel, QC_OUT* qcOut,
1285     QC_OUT_ELEMENT** qcElement, HANDLE_TRANSPORTENC hTpEnc,
1286     AUDIO_OBJECT_TYPE aot, UINT syntaxFlags, SCHAR epConfig) {
1287   QC_OUT_EXTENSION fillExtPayload;
1288   INT totFillBits, alignBits;
1289 
1290   /* Get total consumed bits in AU */
1291   qcOut->totalBits = qcOut->staticBits + qcOut->usedDynBits +
1292                      qcOut->totFillBits + qcOut->elementExtBits +
1293                      qcOut->globalExtBits;
1294 
1295   if (qcKernel->bitrateMode == QCDATA_BR_MODE_CBR) {
1296     /* Now we can get the exact transport bit amount, and hopefully it is equal
1297      * to the estimated value */
1298     INT exactTpBits = transportEnc_GetStaticBits(hTpEnc, qcOut->totalBits);
1299 
1300     if (exactTpBits != qcKernel->globHdrBits) {
1301       INT diffFillBits = 0;
1302 
1303       /* How many bits can be take by bitreservoir */
1304       const INT bitresSpace =
1305           qcKernel->bitResTotMax -
1306           (qcKernel->bitResTot +
1307            (qcOut->grantedDynBits - (qcOut->usedDynBits + qcOut->totFillBits)));
1308 
1309       /* Number of bits which can be moved to bitreservoir. */
1310       const INT bitsToBitres = qcKernel->globHdrBits - exactTpBits;
1311       FDK_ASSERT(bitsToBitres >= 0); /* is always positive */
1312 
1313       /* If bitreservoir can not take all bits, move ramaining bits to fillbits
1314        */
1315       diffFillBits = fMax(0, bitsToBitres - bitresSpace);
1316 
1317       /* Assure previous alignment */
1318       diffFillBits = (diffFillBits + 7) & ~7;
1319 
1320       /* Move as many bits as possible to bitreservoir */
1321       qcKernel->bitResTot += (bitsToBitres - diffFillBits);
1322 
1323       /* Write remaing bits as fill bits */
1324       qcOut->totFillBits += diffFillBits;
1325       qcOut->totalBits += diffFillBits;
1326       qcOut->grantedDynBits += diffFillBits;
1327 
1328       /* Get new header bits */
1329       qcKernel->globHdrBits =
1330           transportEnc_GetStaticBits(hTpEnc, qcOut->totalBits);
1331 
1332       if (qcKernel->globHdrBits != exactTpBits) {
1333         /* In previous step, fill bits and corresponding total bits were changed
1334            when bitreservoir was completely filled. Now we can take the too much
1335            taken bits caused by header overhead from bitreservoir.
1336          */
1337         qcKernel->bitResTot -= (qcKernel->globHdrBits - exactTpBits);
1338       }
1339     }
1340 
1341   } /* MODE_CBR */
1342 
1343   /* Update exact number of consumed header bits. */
1344   qcKernel->globHdrBits = transportEnc_GetStaticBits(hTpEnc, qcOut->totalBits);
1345 
1346   /* Save total fill bits and distribut to alignment and fill bits */
1347   totFillBits = qcOut->totFillBits;
1348 
1349   /* fake a fill extension payload */
1350   FDKmemclear(&fillExtPayload, sizeof(QC_OUT_EXTENSION));
1351 
1352   fillExtPayload.type = EXT_FILL_DATA;
1353   fillExtPayload.nPayloadBits = totFillBits;
1354 
1355   /* ask bitstream encoder how many of that bits can be written in a fill
1356    * extension data entity */
1357   qcOut->totFillBits = FDKaacEnc_writeExtensionData(NULL, &fillExtPayload, 0, 0,
1358                                                     syntaxFlags, aot, epConfig);
1359 
1360   /* now distribute extra fillbits and alignbits */
1361   alignBits =
1362       7 - (qcOut->staticBits + qcOut->usedDynBits + qcOut->elementExtBits +
1363            qcOut->totFillBits + qcOut->globalExtBits - 1) %
1364               8;
1365 
1366   /* Maybe we could remove this */
1367   if (((alignBits + qcOut->totFillBits - totFillBits) == 8) &&
1368       (qcOut->totFillBits > 8))
1369     qcOut->totFillBits -= 8;
1370 
1371   qcOut->totalBits = qcOut->staticBits + qcOut->usedDynBits +
1372                      qcOut->totFillBits + alignBits + qcOut->elementExtBits +
1373                      qcOut->globalExtBits;
1374 
1375   if ((qcOut->totalBits > qcKernel->maxBitsPerFrame) ||
1376       (qcOut->totalBits < qcKernel->minBitsPerFrame)) {
1377     return AAC_ENC_QUANT_ERROR;
1378   }
1379 
1380   qcOut->alignBits = alignBits;
1381 
1382   return AAC_ENC_OK;
1383 }
1384 
1385 /*********************************************************************************
1386 
1387          functionname: FDKaacEnc_crashRecovery
1388          description:  fulfills constraints by means of brute force...
1389                        => bits are saved by cancelling out spectral lines!!
1390                           (beginning at the highest frequencies)
1391          return:       errorcode
1392 
1393 **********************************************************************************/
1394 
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)1395 static void FDKaacEnc_crashRecovery(INT nChannels,
1396                                     PSY_OUT_ELEMENT* psyOutElement,
1397                                     QC_OUT* qcOut, QC_OUT_ELEMENT* qcElement,
1398                                     INT bitsToSave, AUDIO_OBJECT_TYPE aot,
1399                                     UINT syntaxFlags, SCHAR epConfig) {
1400   INT ch;
1401   INT savedBits = 0;
1402   INT sfb, sfbGrp;
1403   INT bitsPerScf[(2)][MAX_GROUPED_SFB];
1404   INT sectionToScf[(2)][MAX_GROUPED_SFB];
1405   INT* sfbOffset;
1406   INT sect, statBitsNew;
1407   QC_OUT_CHANNEL** qcChannel = qcElement->qcOutChannel;
1408   PSY_OUT_CHANNEL** psyChannel = psyOutElement->psyOutChannel;
1409 
1410   /* create a table which converts frq-bins to bit-demand...    [bitsPerScf] */
1411   /* ...and another one which holds the corresponding sections [sectionToScf] */
1412   for (ch = 0; ch < nChannels; ch++) {
1413     sfbOffset = psyChannel[ch]->sfbOffsets;
1414 
1415     for (sect = 0; sect < qcChannel[ch]->sectionData.noOfSections; sect++) {
1416       INT codeBook = qcChannel[ch]->sectionData.huffsection[sect].codeBook;
1417 
1418       for (sfb = qcChannel[ch]->sectionData.huffsection[sect].sfbStart;
1419            sfb < qcChannel[ch]->sectionData.huffsection[sect].sfbStart +
1420                      qcChannel[ch]->sectionData.huffsection[sect].sfbCnt;
1421            sfb++) {
1422         bitsPerScf[ch][sfb] = 0;
1423         if ((codeBook != CODE_BOOK_PNS_NO) /*&&
1424              (sfb < (qcChannel[ch]->sectionData.noOfGroups*qcChannel[ch]->sectionData.maxSfbPerGroup))*/) {
1425           INT sfbStartLine = sfbOffset[sfb];
1426           INT noOfLines = sfbOffset[sfb + 1] - sfbStartLine;
1427           bitsPerScf[ch][sfb] = FDKaacEnc_countValues(
1428               &(qcChannel[ch]->quantSpec[sfbStartLine]), noOfLines, codeBook);
1429         }
1430         sectionToScf[ch][sfb] = sect;
1431       }
1432     }
1433   }
1434 
1435   /* LOWER [maxSfb] IN BOTH CHANNELS!! */
1436   /* Attention: in case of stereo: maxSfbL == maxSfbR, GroupingL == GroupingR ;
1437    */
1438 
1439   for (sfb = qcChannel[0]->sectionData.maxSfbPerGroup - 1; sfb >= 0; sfb--) {
1440     for (sfbGrp = 0; sfbGrp < psyChannel[0]->sfbCnt;
1441          sfbGrp += psyChannel[0]->sfbPerGroup) {
1442       for (ch = 0; ch < nChannels; ch++) {
1443         sect = sectionToScf[ch][sfbGrp + sfb];
1444         qcChannel[ch]->sectionData.huffsection[sect].sfbCnt--;
1445         savedBits += bitsPerScf[ch][sfbGrp + sfb];
1446 
1447         if (qcChannel[ch]->sectionData.huffsection[sect].sfbCnt == 0) {
1448           savedBits += (psyChannel[ch]->lastWindowSequence != SHORT_WINDOW)
1449                            ? FDKaacEnc_sideInfoTabLong[0]
1450                            : FDKaacEnc_sideInfoTabShort[0];
1451         }
1452       }
1453     }
1454 
1455     /* ...have enough bits been saved? */
1456     if (savedBits >= bitsToSave) break;
1457 
1458   } /* sfb loop */
1459 
1460   /* if not enough bits saved,
1461      clean whole spectrum and remove side info overhead */
1462   if (sfb == -1) {
1463     sfb = 0;
1464   }
1465 
1466   for (ch = 0; ch < nChannels; ch++) {
1467     qcChannel[ch]->sectionData.maxSfbPerGroup = sfb;
1468     psyChannel[ch]->maxSfbPerGroup = sfb;
1469     /* when no spectrum is coded save tools info in bitstream */
1470     if (sfb == 0) {
1471       FDKmemclear(&psyChannel[ch]->tnsInfo, sizeof(TNS_INFO));
1472       FDKmemclear(&psyOutElement->toolsInfo, sizeof(TOOLSINFO));
1473     }
1474   }
1475   /* dynamic bits will be updated in iteration loop */
1476 
1477   { /* if stop sfb has changed save bits in side info, e.g. MS or TNS coding */
1478     ELEMENT_INFO elInfo;
1479 
1480     FDKmemclear(&elInfo, sizeof(ELEMENT_INFO));
1481     elInfo.nChannelsInEl = nChannels;
1482     elInfo.elType = (nChannels == 2) ? ID_CPE : ID_SCE;
1483 
1484     FDKaacEnc_ChannelElementWrite(NULL, &elInfo, NULL, psyOutElement,
1485                                   psyChannel, syntaxFlags, aot, epConfig,
1486                                   &statBitsNew, 0);
1487   }
1488 
1489   savedBits = qcElement->staticBitsUsed - statBitsNew;
1490 
1491   /* update static and dynamic bits */
1492   qcElement->staticBitsUsed -= savedBits;
1493   qcElement->grantedDynBits += savedBits;
1494 
1495   qcOut->staticBits -= savedBits;
1496   qcOut->grantedDynBits += savedBits;
1497   qcOut->maxDynBits += savedBits;
1498 }
1499 
FDKaacEnc_QCClose(QC_STATE ** phQCstate,QC_OUT ** phQC)1500 void FDKaacEnc_QCClose(QC_STATE** phQCstate, QC_OUT** phQC) {
1501   int n, i;
1502 
1503   if (phQC != NULL) {
1504     for (n = 0; n < (1); n++) {
1505       if (phQC[n] != NULL) {
1506         QC_OUT* hQC = phQC[n];
1507         for (i = 0; i < (8); i++) {
1508         }
1509 
1510         for (i = 0; i < ((8)); i++) {
1511           if (hQC->qcElement[i]) FreeRam_aacEnc_QCelement(&hQC->qcElement[i]);
1512         }
1513 
1514         FreeRam_aacEnc_QCout(&phQC[n]);
1515       }
1516     }
1517   }
1518 
1519   if (phQCstate != NULL) {
1520     if (*phQCstate != NULL) {
1521       QC_STATE* hQCstate = *phQCstate;
1522 
1523       if (hQCstate->hAdjThr != NULL) FDKaacEnc_AdjThrClose(&hQCstate->hAdjThr);
1524 
1525       if (hQCstate->hBitCounter != NULL)
1526         FDKaacEnc_BCClose(&hQCstate->hBitCounter);
1527 
1528       for (i = 0; i < ((8)); i++) {
1529         if (hQCstate->elementBits[i] != NULL) {
1530           FreeRam_aacEnc_ElementBits(&hQCstate->elementBits[i]);
1531         }
1532       }
1533       FreeRam_aacEnc_QCstate(phQCstate);
1534     }
1535   }
1536 }
1537