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