2 /* -----------------------------------------------------------------------------------------------------------
3 Software License for The Fraunhofer FDK AAC Codec Library for Android
5 © Copyright 1995 - 2013 Fraunhofer-Gesellschaft zur Förderung der angewandten Forschung e.V.
9 The Fraunhofer FDK AAC Codec Library for Android ("FDK AAC Codec") is software that implements
10 the MPEG Advanced Audio Coding ("AAC") encoding and decoding scheme for digital audio.
11 This FDK AAC Codec software is intended to be used on a wide variety of Android devices.
13 AAC's HE-AAC and HE-AAC v2 versions are regarded as today's most efficient general perceptual
14 audio codecs. AAC-ELD is considered the best-performing full-bandwidth communications codec by
15 independent studies and is widely deployed. AAC has been standardized by ISO and IEC as part
16 of the MPEG specifications.
18 Patent licenses for necessary patent claims for the FDK AAC Codec (including those of Fraunhofer)
19 may be obtained through Via Licensing (www.vialicensing.com) or through the respective patent owners
20 individually for the purpose of encoding or decoding bit streams in products that are compliant with
21 the ISO/IEC MPEG audio standards. Please note that most manufacturers of Android devices already license
22 these patent claims through Via Licensing or directly from the patent owners, and therefore FDK AAC Codec
23 software may already be covered under those patent licenses when it is used for those licensed purposes only.
25 Commercially-licensed AAC software libraries, including floating-point versions with enhanced sound quality,
26 are also available from Fraunhofer. Users are encouraged to check the Fraunhofer website for additional
27 applications information and documentation.
31 Redistribution and use in source and binary forms, with or without modification, are permitted without
32 payment of copyright license fees provided that you satisfy the following conditions:
34 You must retain the complete text of this software license in redistributions of the FDK AAC Codec or
35 your modifications thereto in source code form.
37 You must retain the complete text of this software license in the documentation and/or other materials
38 provided with redistributions of the FDK AAC Codec or your modifications thereto in binary form.
39 You must make available free of charge copies of the complete source code of the FDK AAC Codec and your
40 modifications thereto to recipients of copies in binary form.
42 The name of Fraunhofer may not be used to endorse or promote products derived from this library without
43 prior written permission.
45 You may not charge copyright license fees for anyone to use, copy or distribute the FDK AAC Codec
46 software or your modifications thereto.
48 Your modified versions of the FDK AAC Codec must carry prominent notices stating that you changed the software
49 and the date of any change. For modified versions of the FDK AAC Codec, the term
50 "Fraunhofer FDK AAC Codec Library for Android" must be replaced by the term
51 "Third-Party Modified Version of the Fraunhofer FDK AAC Codec Library for Android."
55 NO EXPRESS OR IMPLIED LICENSES TO ANY PATENT CLAIMS, including without limitation the patents of Fraunhofer,
56 ARE GRANTED BY THIS SOFTWARE LICENSE. Fraunhofer provides no warranty of patent non-infringement with
57 respect to this software.
59 You may use this FDK AAC Codec software or modifications thereto only for purposes that are authorized
60 by appropriate patent licenses.
64 This FDK AAC Codec software is provided by Fraunhofer on behalf of the copyright holders and contributors
65 "AS IS" and WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, including but not limited to the implied warranties
66 of merchantability and fitness for a particular purpose. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
67 CONTRIBUTORS BE LIABLE for any direct, indirect, incidental, special, exemplary, or consequential damages,
68 including but not limited to procurement of substitute goods or services; loss of use, data, or profits,
69 or business interruption, however caused and on any theory of liability, whether in contract, strict
70 liability, or tort (including negligence), arising in any way out of the use of this software, even if
71 advised of the possibility of such damage.
73 5. CONTACT INFORMATION
75 Fraunhofer Institute for Integrated Circuits IIS
76 Attention: Audio and Multimedia Departments - FDK AAC LL
78 91058 Erlangen, Germany
80 www.iis.fraunhofer.de/amm
81 amm-info@iis.fraunhofer.de
82 ----------------------------------------------------------------------------------------------------------- */
84 /******************************** MPEG Audio Encoder **************************
86 Initial author: M. Werner
87 contents/description: Quantizing & coding
89 ******************************************************************************/
93 #include "interface.h"
98 #include "channel_map.h"
99 #include "aacEnc_ram.h"
101 #include "genericStds.h"
105 QCDATA_BR_MODE bitrateMode
;
107 } TAB_VBR_QUAL_FACTOR
;
109 static const TAB_VBR_QUAL_FACTOR tableVbrQualFactor
[] = {
110 {QCDATA_BR_MODE_CBR
, FL2FXCONST_DBL(0.00f
)},
111 {QCDATA_BR_MODE_VBR_1
, FL2FXCONST_DBL(0.160f
)}, /* 32 kbps mono AAC-LC + SBR + PS */
112 {QCDATA_BR_MODE_VBR_2
, FL2FXCONST_DBL(0.148f
)}, /* 64 kbps stereo AAC-LC + SBR */
113 {QCDATA_BR_MODE_VBR_3
, FL2FXCONST_DBL(0.135f
)}, /* 80 - 96 kbps stereo AAC-LC */
114 {QCDATA_BR_MODE_VBR_4
, FL2FXCONST_DBL(0.111f
)}, /* 128 kbps stereo AAC-LC */
115 {QCDATA_BR_MODE_VBR_5
, FL2FXCONST_DBL(0.070f
)}, /* 192 kbps stereo AAC-LC */
116 {QCDATA_BR_MODE_SFR
, FL2FXCONST_DBL(0.00f
)},
117 {QCDATA_BR_MODE_FF
, FL2FXCONST_DBL(0.00f
)}
120 static INT
isConstantBitrateMode(
121 const QCDATA_BR_MODE bitrateMode
124 return ( ((bitrateMode
==QCDATA_BR_MODE_CBR
) || (bitrateMode
==QCDATA_BR_MODE_SFR
) || (bitrateMode
==QCDATA_BR_MODE_FF
)) ? 1 : 0 );
130 FRAME_LEN_BYTES_MODULO
= 1,
131 FRAME_LEN_BYTES_INT
= 2
132 }FRAME_LEN_RESULT_MODE
;
134 /* forward declarations */
136 static INT
FDKaacEnc_calcMaxValueInSfb(INT sfbCnt
,
139 INT
*RESTRICT sfbOffset
,
140 SHORT
*RESTRICT quantSpectrum
,
141 UINT
*RESTRICT maxValue
);
143 static void FDKaacEnc_crashRecovery(INT nChannels
,
144 PSY_OUT_ELEMENT
* psyOutElement
,
146 QC_OUT_ELEMENT
*qcElement
,
148 AUDIO_OBJECT_TYPE aot
,
153 AAC_ENCODER_ERROR
FDKaacEnc_reduceBitConsumption(int* iterations
,
154 const int maxIterations
,
156 int* chConstraintsFulfilled
,
159 PSY_OUT_ELEMENT
* psyOutElement
,
161 QC_OUT_ELEMENT
* qcOutElement
,
162 ELEMENT_BITS
* elBits
,
163 AUDIO_OBJECT_TYPE aot
,
168 void FDKaacEnc_QCClose (QC_STATE
**phQCstate
, QC_OUT
**phQC
);
170 /*****************************************************************************
172 functionname: FDKaacEnc_calcFrameLen
178 *****************************************************************************/
179 static INT
FDKaacEnc_calcFrameLen(INT bitRate
,
182 FRAME_LEN_RESULT_MODE mode
)
187 result
= ((granuleLength
)>>3)*(bitRate
);
190 case FRAME_LEN_BYTES_MODULO
:
191 result
%= sampleRate
;
193 case FRAME_LEN_BYTES_INT
:
194 result
/= sampleRate
;
200 /*****************************************************************************
202 functionname:FDKaacEnc_framePadding
203 description: Calculates if padding is needed for actual frame
208 *****************************************************************************/
209 static INT
FDKaacEnc_framePadding(INT bitRate
,
219 difference
= FDKaacEnc_calcFrameLen( bitRate
,
222 FRAME_LEN_BYTES_MODULO
);
223 *paddingRest
-=difference
;
225 if (*paddingRest
<= 0 ) {
227 *paddingRest
+= sampleRate
;
234 /*********************************************************************************
236 functionname: FDKaacEnc_QCOutNew
240 **********************************************************************************/
241 AAC_ENCODER_ERROR
FDKaacEnc_QCOutNew(QC_OUT
**phQC
,
248 AAC_ENCODER_ERROR ErrorStatus
;
250 int elInc
= 0, chInc
= 0;
252 for (n
=0; n
<nSubFrames
; n
++) {
253 phQC
[n
] = GetRam_aacEnc_QCout(n
);
254 if (phQC
[n
] == NULL
) {
255 ErrorStatus
= AAC_ENC_NO_MEMORY
;
259 for (i
=0; i
<nChannels
; i
++) {
260 phQC
[n
]->pQcOutChannels
[i
] = GetRam_aacEnc_QCchannel(chInc
, dynamic_RAM
);
261 if ( phQC
[n
]->pQcOutChannels
[i
] == NULL
264 ErrorStatus
= AAC_ENC_NO_MEMORY
;
270 for (i
=0; i
<nElements
; i
++) {
271 phQC
[n
]->qcElement
[i
] = GetRam_aacEnc_QCelement(elInc
);
272 if (phQC
[n
]->qcElement
[i
] == NULL
)
274 ErrorStatus
= AAC_ENC_NO_MEMORY
;
289 /*********************************************************************************
291 functionname: FDKaacEnc_QCOutInit
295 **********************************************************************************/
296 AAC_ENCODER_ERROR
FDKaacEnc_QCOutInit(QC_OUT
*phQC
[(1)],
297 const INT nSubFrames
,
298 const CHANNEL_MAPPING
*cm
)
302 for (n
=0; n
<nSubFrames
; n
++) {
304 for (i
=0; i
<cm
->nElements
; i
++) {
305 for (ch
=0; ch
<cm
->elInfo
[i
].nChannelsInEl
; ch
++) {
306 phQC
[n
]->qcElement
[i
]->qcOutChannel
[ch
] = phQC
[n
]->pQcOutChannels
[chInc
];
315 /*********************************************************************************
317 functionname: FDKaacEnc_QCNew
321 **********************************************************************************/
322 AAC_ENCODER_ERROR
FDKaacEnc_QCNew(QC_STATE
**phQC
,
327 AAC_ENCODER_ERROR ErrorStatus
;
330 QC_STATE
* hQC
= GetRam_aacEnc_QCstate();
333 ErrorStatus
= AAC_ENC_NO_MEMORY
;
337 if (FDKaacEnc_AdjThrNew(&hQC
->hAdjThr
, nElements
)) {
338 ErrorStatus
= AAC_ENC_NO_MEMORY
;
342 if (FDKaacEnc_BCNew(&(hQC
->hBitCounter
), dynamic_RAM
)) {
343 ErrorStatus
= AAC_ENC_NO_MEMORY
;
347 for (i
=0; i
<nElements
; i
++) {
348 hQC
->elementBits
[i
] = GetRam_aacEnc_ElementBits(i
);
349 if (hQC
->elementBits
[i
] == NULL
) {
350 ErrorStatus
= AAC_ENC_NO_MEMORY
;
358 FDKaacEnc_QCClose(phQC
, NULL
);
362 /*********************************************************************************
364 functionname: FDKaacEnc_QCInit
368 **********************************************************************************/
369 AAC_ENCODER_ERROR
FDKaacEnc_QCInit(QC_STATE
*hQC
,
370 struct QC_INIT
*init
)
372 hQC
->maxBitsPerFrame
= init
->maxBits
;
373 hQC
->minBitsPerFrame
= init
->minBits
;
374 hQC
->nElements
= init
->channelMapping
->nElements
;
375 hQC
->bitResTotMax
= init
->bitRes
;
376 hQC
->bitResTot
= init
->bitRes
;
377 hQC
->maxBitFac
= init
->maxBitFac
;
378 hQC
->bitrateMode
= init
->bitrateMode
;
379 hQC
->invQuant
= init
->invQuant
;
380 hQC
->maxIterations
= init
->maxIterations
;
382 if ( isConstantBitrateMode(hQC
->bitrateMode
) ) {
383 INT bitresPerChannel
= (hQC
->bitResTotMax
/ init
->channelMapping
->nChannelsEff
);
384 /* 0: full bitreservoir, 1: reduced bitreservoir, 2: disabled bitreservoir */
385 hQC
->bitDistributionMode
= (bitresPerChannel
>100) ? 0 : (bitresPerChannel
>0) ? 1 : 2;
388 hQC
->bitDistributionMode
= 0; /* full bitreservoir */
392 hQC
->padding
.paddingRest
= init
->padding
.paddingRest
;
394 hQC
->globHdrBits
= init
->staticBits
; /* Bit overhead due to transport */
396 FDKaacEnc_InitElementBits(hQC
,
397 init
->channelMapping
,
399 (init
->averageBits
/init
->nSubFrames
) - hQC
->globHdrBits
,
400 hQC
->maxBitsPerFrame
/init
->channelMapping
->nChannelsEff
);
402 switch(hQC
->bitrateMode
){
403 case QCDATA_BR_MODE_CBR
:
404 case QCDATA_BR_MODE_VBR_1
:
405 case QCDATA_BR_MODE_VBR_2
:
406 case QCDATA_BR_MODE_VBR_3
:
407 case QCDATA_BR_MODE_VBR_4
:
408 case QCDATA_BR_MODE_VBR_5
:
409 case QCDATA_BR_MODE_SFR
:
410 case QCDATA_BR_MODE_FF
:
411 if((int)hQC
->bitrateMode
< (int)(sizeof(tableVbrQualFactor
)/sizeof(TAB_VBR_QUAL_FACTOR
))){
412 hQC
->vbrQualFactor
= (FIXP_DBL
)tableVbrQualFactor
[hQC
->bitrateMode
].vbrQualFactor
;
414 hQC
->vbrQualFactor
= FL2FXCONST_DBL(0.f
); /* default setting */
417 case QCDATA_BR_MODE_INVALID
:
419 hQC
->vbrQualFactor
= FL2FXCONST_DBL(0.f
);
423 FDKaacEnc_AdjThrInit(
426 hQC
->elementBits
, /* or channelBitrates, was: channelBitrate */
428 init
->channelMapping
->nElements
,
429 init
->channelMapping
->nChannelsEff
,
430 init
->sampleRate
, /* output sample rate */
431 init
->advancedBitsToPe
, /* if set, calc bits2PE factor depending on samplerate */
440 /*********************************************************************************
442 functionname: FDKaacEnc_QCMainPrepare
446 **********************************************************************************/
447 AAC_ENCODER_ERROR
FDKaacEnc_QCMainPrepare(ELEMENT_INFO
*elInfo
,
448 ATS_ELEMENT
* RESTRICT adjThrStateElement
,
449 PSY_OUT_ELEMENT
* RESTRICT psyOutElement
,
450 QC_OUT_ELEMENT
* RESTRICT qcOutElement
,
451 AUDIO_OBJECT_TYPE aot
,
456 AAC_ENCODER_ERROR ErrorStatus
= AAC_ENC_OK
;
457 INT nChannels
= elInfo
->nChannelsInEl
;
459 PSY_OUT_CHANNEL
** RESTRICT psyOutChannel
= psyOutElement
->psyOutChannel
; /* may be modified in-place */
461 FDKaacEnc_CalcFormFactor(qcOutElement
->qcOutChannel
, psyOutChannel
, nChannels
);
463 /* prepare and calculate PE without reduction */
464 FDKaacEnc_peCalculation(&qcOutElement
->peData
, psyOutChannel
, qcOutElement
->qcOutChannel
, &psyOutElement
->toolsInfo
, adjThrStateElement
, nChannels
);
466 ErrorStatus
= FDKaacEnc_ChannelElementWrite( NULL
, elInfo
, NULL
,
468 psyOutElement
->psyOutChannel
,
472 &qcOutElement
->staticBitsUsed
,
478 /*********************************************************************************
480 functionname: FDKaacEnc_AdjustBitrate
481 description: adjusts framelength via padding on a frame to frame basis,
482 to achieve a bitrate that demands a non byte aligned
486 **********************************************************************************/
487 AAC_ENCODER_ERROR
FDKaacEnc_AdjustBitrate(QC_STATE
*RESTRICT hQC
,
488 CHANNEL_MAPPING
*RESTRICT cm
,
490 INT bitRate
, /* total bitrate */
491 INT sampleRate
, /* output sampling rate */
492 INT granuleLength
) /* frame length */
497 /* Do we need an extra padding byte? */
498 paddingOn
= FDKaacEnc_framePadding(bitRate
,
501 &hQC
->padding
.paddingRest
);
503 frameLen
= paddingOn
+ FDKaacEnc_calcFrameLen(bitRate
,
506 FRAME_LEN_BYTES_INT
);
508 *avgTotalBits
= frameLen
<<3;
513 static AAC_ENCODER_ERROR
FDKaacEnc_distributeElementDynBits(QC_STATE
* hQC
,
514 QC_OUT_ELEMENT
* qcElement
[(8)],
519 INT i
, firstEl
= cm
->nElements
-1;
522 for (i
=(cm
->nElements
-1); i
>=0; i
--) {
523 if ((cm
->elInfo
[i
].elType
== ID_SCE
) || (cm
->elInfo
[i
].elType
== ID_CPE
) ||
524 (cm
->elInfo
[i
].elType
== ID_LFE
))
526 qcElement
[i
]->grantedDynBits
= (INT
)fMult(hQC
->elementBits
[i
]->relativeBitsEl
, (FIXP_DBL
)codeBits
);
527 totalBits
+= qcElement
[i
]->grantedDynBits
;
531 qcElement
[firstEl
]->grantedDynBits
+= codeBits
- totalBits
;
537 * \brief Verify whether minBitsPerFrame criterion can be satisfied.
539 * This function evaluates the bit consumption only if minBitsPerFrame parameter is not 0.
540 * In hyperframing mode the difference between grantedDynBits and usedDynBits of all sub frames
541 * results the number of fillbits to be written.
542 * This bits can be distrubitued in superframe to reach minBitsPerFrame bit consumption in single AU's.
543 * The return value denotes if enough desired fill bits are available to achieve minBitsPerFrame in all frames.
544 * This check can only be used within superframes.
546 * \param qcOut Pointer to coding data struct.
547 * \param minBitsPerFrame Minimal number of bits to be consumed in each frame.
548 * \param nSubFrames Number of frames in superframe
552 * - 0: criterion not fulfilled
554 static int checkMinFrameBitsDemand(
556 const INT minBitsPerFrame
,
560 int result
= 1; /* all fine*/
564 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
566 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
567 /*********************************************************************************
569 functionname: FDKaacEnc_getMinimalStaticBitdemand
570 description: calculate minmal size of static bits by reduction ,
571 to zero spectrum and deactivating tns and MS
572 return: number of static bits
574 **********************************************************************************/
575 static int FDKaacEnc_getMinimalStaticBitdemand(CHANNEL_MAPPING
* cm
,
578 AUDIO_OBJECT_TYPE aot
= AOT_AAC_LC
;
579 UINT syntaxFlags
= 0;
583 for (i
=0; i
<cm
->nElements
; i
++) {
584 ELEMENT_INFO elInfo
= cm
->elInfo
[i
];
586 if ( (elInfo
.elType
== ID_SCE
)
587 || (elInfo
.elType
== ID_CPE
)
588 || (elInfo
.elType
== ID_LFE
) )
592 FDKaacEnc_ChannelElementWrite( NULL
, &elInfo
, NULL
,
593 psyOut
[0]->psyOutElement
[i
],
594 psyOut
[0]->psyOutElement
[i
]->psyOutChannel
,
600 bitcount
+= minElBits
;
607 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
609 static AAC_ENCODER_ERROR
FDKaacEnc_prepareBitDistribution(QC_STATE
* hQC
,
613 QC_OUT_ELEMENT
* qcElement
[(1)][(8)],
615 INT
*totalAvailableBits
,
616 INT
*avgTotalDynBits
)
619 /* get maximal allowed dynamic bits */
620 qcOut
[0]->grantedDynBits
= (fixMin(hQC
->maxBitsPerFrame
, avgTotalBits
) - hQC
->globHdrBits
)&~7;
621 qcOut
[0]->grantedDynBits
-= (qcOut
[0]->globalExtBits
+ qcOut
[0]->staticBits
+ qcOut
[0]->elementExtBits
);
622 qcOut
[0]->maxDynBits
= ((hQC
->maxBitsPerFrame
)&~7) - (qcOut
[0]->globalExtBits
+ qcOut
[0]->staticBits
+ qcOut
[0]->elementExtBits
);
623 /* assure that enough bits are available */
624 if ((qcOut
[0]->grantedDynBits
+hQC
->bitResTot
) < 0) {
625 /* crash recovery allows to reduce static bits to a minimum */
626 if ( (qcOut
[0]->grantedDynBits
+hQC
->bitResTot
) < (FDKaacEnc_getMinimalStaticBitdemand(cm
, psyOut
)-qcOut
[0]->staticBits
) )
627 return AAC_ENC_BITRES_TOO_LOW
;
630 /* distribute dynamic bits to each element */
631 FDKaacEnc_distributeElementDynBits(hQC
,
634 qcOut
[0]->grantedDynBits
);
636 *avgTotalDynBits
= 0; /*frameDynBits;*/
638 *totalAvailableBits
= avgTotalBits
;
640 /* sum up corrected granted PE */
641 qcOut
[0]->totalGrantedPeCorr
= 0;
643 for (i
=0; i
<cm
->nElements
; i
++)
645 ELEMENT_INFO elInfo
= cm
->elInfo
[i
];
646 int nChannels
= elInfo
.nChannelsInEl
;
648 if ((elInfo
.elType
== ID_SCE
) || (elInfo
.elType
== ID_CPE
) ||
649 (elInfo
.elType
== ID_LFE
))
651 /* for ( all sub frames ) ... */
652 FDKaacEnc_DistributeBits(hQC
->hAdjThr
,
653 hQC
->hAdjThr
->adjThrStateElem
[i
],
654 psyOut
[0]->psyOutElement
[i
]->psyOutChannel
,
655 &qcElement
[0][i
]->peData
,
656 &qcElement
[0][i
]->grantedPe
,
657 &qcElement
[0][i
]->grantedPeCorr
,
659 psyOut
[0]->psyOutElement
[i
]->commonWindow
,
660 qcElement
[0][i
]->grantedDynBits
,
661 hQC
->elementBits
[i
]->bitResLevelEl
,
662 hQC
->elementBits
[i
]->maxBitResBitsEl
,
664 hQC
->bitDistributionMode
);
666 *totalAvailableBits
+= hQC
->elementBits
[i
]->bitResLevelEl
;
667 /* get total corrected granted PE */
668 qcOut
[0]->totalGrantedPeCorr
+= qcElement
[0][i
]->grantedPeCorr
;
669 } /* -end- if(ID_SCE || ID_CPE || ID_LFE) */
671 } /* -end- element loop */
673 *totalAvailableBits
= FDKmin(hQC
->maxBitsPerFrame
, (*totalAvailableBits
));
678 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
679 static AAC_ENCODER_ERROR
FDKaacEnc_updateUsedDynBits(INT
* sumDynBitsConsumed
,
680 QC_OUT_ELEMENT
* qcElement
[(8)],
685 *sumDynBitsConsumed
= 0;
687 for (i
=0; i
<cm
->nElements
; i
++)
689 ELEMENT_INFO elInfo
= cm
->elInfo
[i
];
691 if ((elInfo
.elType
== ID_SCE
) || (elInfo
.elType
== ID_CPE
) ||
692 (elInfo
.elType
== ID_LFE
))
694 /* sum up bits consumed */
695 *sumDynBitsConsumed
+= qcElement
[i
]->dynBitsUsed
;
696 } /* -end- if(ID_SCE || ID_CPE || ID_LFE) */
698 } /* -end- element loop */
704 static INT
FDKaacEnc_getTotalConsumedDynBits(QC_OUT
** qcOut
,
709 /* sum up bit consumption for all sub frames */
710 for (c
=0; c
<nSubFrames
; c
++)
712 /* bit consumption not valid if dynamic bits
713 not available in one sub frame */
714 if (qcOut
[c
]->usedDynBits
==-1) return -1;
715 totalBits
+= qcOut
[c
]->usedDynBits
;
722 static INT
FDKaacEnc_getTotalConsumedBits(QC_OUT
** qcOut
,
723 QC_OUT_ELEMENT
* qcElement
[(1)][(8)],
729 int totalUsedBits
= 0;
731 for (c
= 0 ; c
< nSubFrames
; c
++ )
734 for (i
=0; i
<cm
->nElements
; i
++)
736 if ((cm
->elInfo
[i
].elType
== ID_SCE
) || (cm
->elInfo
[i
].elType
== ID_CPE
) ||
737 (cm
->elInfo
[i
].elType
== ID_LFE
))
739 dataBits
+= qcElement
[c
][i
]->dynBitsUsed
+ qcElement
[c
][i
]->staticBitsUsed
+ qcElement
[c
][i
]->extBitsUsed
;
742 dataBits
+= qcOut
[c
]->globalExtBits
;
744 totalUsedBits
+= (8 - (dataBits
) % 8) % 8;
745 totalUsedBits
+= dataBits
+ globHdrBits
; /* header bits for every frame */
747 return totalUsedBits
;
750 static AAC_ENCODER_ERROR
FDKaacEnc_BitResRedistribution(
752 const CHANNEL_MAPPING
*const cm
,
753 const INT avgTotalBits
756 /* check bitreservoir fill level */
757 if (hQC
->bitResTot
< 0) {
758 return AAC_ENC_BITRES_TOO_LOW
;
760 else if (hQC
->bitResTot
> hQC
->bitResTotMax
) {
761 return AAC_ENC_BITRES_TOO_HIGH
;
764 INT i
, firstEl
= cm
->nElements
-1;
765 INT totalBits
= 0, totalBits_max
= 0;
767 int totalBitreservoir
= FDKmin(hQC
->bitResTot
, (hQC
->maxBitsPerFrame
-avgTotalBits
));
768 int totalBitreservoirMax
= FDKmin(hQC
->bitResTotMax
, (hQC
->maxBitsPerFrame
-avgTotalBits
));
770 int sc_bitResTot
= CountLeadingBits(totalBitreservoir
);
771 int sc_bitResTotMax
= CountLeadingBits(totalBitreservoirMax
);
773 for (i
=(cm
->nElements
-1); i
>=0; i
--) {
774 if ((cm
->elInfo
[i
].elType
== ID_SCE
) || (cm
->elInfo
[i
].elType
== ID_CPE
) ||
775 (cm
->elInfo
[i
].elType
== ID_LFE
))
777 hQC
->elementBits
[i
]->bitResLevelEl
= (INT
)fMult(hQC
->elementBits
[i
]->relativeBitsEl
, (FIXP_DBL
)(totalBitreservoir
<<sc_bitResTot
))>>sc_bitResTot
;
778 totalBits
+= hQC
->elementBits
[i
]->bitResLevelEl
;
780 hQC
->elementBits
[i
]->maxBitResBitsEl
= (INT
)fMult(hQC
->elementBits
[i
]->relativeBitsEl
, (FIXP_DBL
)(totalBitreservoirMax
<<sc_bitResTotMax
))>>sc_bitResTotMax
;
781 totalBits_max
+= hQC
->elementBits
[i
]->maxBitResBitsEl
;
786 hQC
->elementBits
[firstEl
]->bitResLevelEl
+= totalBitreservoir
- totalBits
;
787 hQC
->elementBits
[firstEl
]->maxBitResBitsEl
+= totalBitreservoirMax
- totalBits_max
;
794 AAC_ENCODER_ERROR
FDKaacEnc_QCMain(QC_STATE
* RESTRICT hQC
,
799 ,AUDIO_OBJECT_TYPE aot
,
805 AAC_ENCODER_ERROR ErrorStatus
= AAC_ENC_OK
;
806 INT avgTotalDynBits
= 0; /* maximal allowed dynamic bits for all frames */
807 INT totalAvailableBits
= 0;
810 /*-------------------------------------------- */
811 /* redistribute total bitreservoir to elements */
812 ErrorStatus
= FDKaacEnc_BitResRedistribution(hQC
, cm
, avgTotalBits
);
813 if (ErrorStatus
!= AAC_ENC_OK
) {
817 /*-------------------------------------------- */
818 /* fastenc needs one time threshold simulation,
819 in case of multiple frames, one more guess has to be calculated */
821 /*-------------------------------------------- */
823 QC_OUT_ELEMENT
* qcElement
[(1)][(8)];
825 /* work on a copy of qcChannel and qcElement */
826 for (i
=0; i
<cm
->nElements
; i
++)
828 ELEMENT_INFO elInfo
= cm
->elInfo
[i
];
830 if ((elInfo
.elType
== ID_SCE
) || (elInfo
.elType
== ID_CPE
) ||
831 (elInfo
.elType
== ID_LFE
))
833 /* for ( all sub frames ) ... */
834 for (c
= 0 ; c
< nSubFrames
; c
++ )
837 qcElement
[c
][i
] = qcOut
[c
]->qcElement
[i
];
843 /*-------------------------------------------- */
844 /*-------------------------------------------- */
845 if ( isConstantBitrateMode(hQC
->bitrateMode
) )
847 /* calc granted dynamic bits for sub frame and
848 distribute it to each element */
849 ErrorStatus
= FDKaacEnc_prepareBitDistribution(
859 if (ErrorStatus
!= AAC_ENC_OK
) {
864 qcOut
[0]->grantedDynBits
= ((hQC
->maxBitsPerFrame
- (hQC
->globHdrBits
))&~7)
865 - (qcOut
[0]->globalExtBits
+ qcOut
[0]->staticBits
+ qcOut
[0]->elementExtBits
);
866 qcOut
[0]->maxDynBits
= qcOut
[0]->grantedDynBits
;
868 totalAvailableBits
= hQC
->maxBitsPerFrame
;
872 #ifdef PNS_PRECOUNT_ENABLE
873 /* Calculate estimated pns bits and substract them from grantedDynBits to get a more accurate number of available bits. */
874 if (syntaxFlags
& (AC_LD
|AC_ELD
))
876 int estimatedPnsBits
= 0, ch
;
878 for (ch
=0; ch
<cm
->nChannels
; ch
++) {
879 qcOut
[0]->pQcOutChannels
[ch
]->sectionData
.noiseNrgBits
= noisePreCount(psyOut
[0]->pPsyOutChannels
[ch
]->noiseNrg
, psyOut
[0]->pPsyOutChannels
[ch
]->maxSfbPerGroup
);
880 estimatedPnsBits
+= qcOut
[0]->pQcOutChannels
[ch
]->sectionData
.noiseNrgBits
;
882 qcOut
[0]->grantedDynBits
-= estimatedPnsBits
;
886 /* for ( all sub frames ) ... */
887 for (c
= 0 ; c
< nSubFrames
; c
++ )
889 /* for CBR and VBR mode */
890 FDKaacEnc_AdjustThresholds(hQC
->hAdjThr
->adjThrStateElem
,
893 psyOut
[c
]->psyOutElement
,
894 isConstantBitrateMode(hQC
->bitrateMode
),
897 } /* -end- sub frame counter */
899 /*-------------------------------------------- */
900 INT iterations
[(1)][(8)];
901 INT chConstraintsFulfilled
[(1)][(8)][(2)];
902 INT calculateQuant
[(1)][(8)][(2)];
903 INT constraintsFulfilled
[(1)][(8)];
904 /*-------------------------------------------- */
907 /* for ( all sub frames ) ... */
908 for (c
= 0 ; c
< nSubFrames
; c
++ )
910 for (i
=0; i
<cm
->nElements
; i
++)
912 ELEMENT_INFO elInfo
= cm
->elInfo
[i
];
913 INT ch
, nChannels
= elInfo
.nChannelsInEl
;
915 if ((elInfo
.elType
== ID_SCE
) || (elInfo
.elType
== ID_CPE
) ||
916 (elInfo
.elType
== ID_LFE
))
918 /* Turn thresholds into scalefactors, optimize bit consumption and verify conformance */
919 FDKaacEnc_EstimateScaleFactors(psyOut
[c
]->psyOutElement
[i
]->psyOutChannel
,
920 qcElement
[c
][i
]->qcOutChannel
,
922 cm
->elInfo
[i
].nChannelsInEl
);
925 /*-------------------------------------------- */
926 constraintsFulfilled
[c
][i
] = 1;
927 iterations
[c
][i
] = 0 ;
929 for (ch
= 0; ch
< nChannels
; ch
++)
931 chConstraintsFulfilled
[c
][i
][ch
] = 1;
932 calculateQuant
[c
][i
][ch
] = 1;
935 /*-------------------------------------------- */
937 } /* -end- if(ID_SCE || ID_CPE || ID_LFE) */
939 } /* -end- element loop */
941 qcOut
[c
]->usedDynBits
= -1;
943 } /* -end- sub frame counter */
947 INT quantizationDone
= 0;
948 INT sumDynBitsConsumedTotal
= 0;
949 INT decreaseBitConsumption
= -1; /* no direction yet! */
951 /*-------------------------------------------- */
952 /* -start- Quantization loop ... */
953 /*-------------------------------------------- */
954 do /* until max allowed bits per frame and maxDynBits!=-1*/
956 quantizationDone
= 0;
958 c
= 0; /* get frame to process */
960 for (i
=0; i
<cm
->nElements
; i
++)
962 ELEMENT_INFO elInfo
= cm
->elInfo
[i
];
963 INT ch
, nChannels
= elInfo
.nChannelsInEl
;
965 if ((elInfo
.elType
== ID_SCE
) || (elInfo
.elType
== ID_CPE
) ||
966 (elInfo
.elType
== ID_LFE
))
968 do /* until spectral values < MAX_QUANT */
970 /*-------------------------------------------- */
971 if (!constraintsFulfilled
[c
][i
])
973 FDKaacEnc_reduceBitConsumption(&iterations
[c
][i
],
975 (decreaseBitConsumption
) ? 1 : -1,
976 chConstraintsFulfilled
[c
][i
],
977 calculateQuant
[c
][i
],
979 psyOut
[c
]->psyOutElement
[i
],
988 /*-------------------------------------------- */
989 /*-------------------------------------------- */
990 constraintsFulfilled
[c
][i
] = 1 ;
992 /*-------------------------------------------- */
993 /* quantize spectrum (per each channel) */
994 for (ch
= 0; ch
< nChannels
; ch
++)
996 /*-------------------------------------------- */
997 chConstraintsFulfilled
[c
][i
][ch
] = 1;
999 /*-------------------------------------------- */
1001 if (calculateQuant
[c
][i
][ch
])
1003 QC_OUT_CHANNEL
* qcOutCh
= qcElement
[c
][i
]->qcOutChannel
[ch
];
1004 PSY_OUT_CHANNEL
* psyOutCh
= psyOut
[c
]->psyOutElement
[i
]->psyOutChannel
[ch
];
1006 calculateQuant
[c
][i
][ch
] = 0; /* calculate quantization only if necessary */
1008 /*-------------------------------------------- */
1009 FDKaacEnc_QuantizeSpectrum(psyOutCh
->sfbCnt
,
1010 psyOutCh
->maxSfbPerGroup
,
1011 psyOutCh
->sfbPerGroup
,
1012 psyOutCh
->sfbOffsets
,
1013 qcOutCh
->mdctSpectrum
,
1014 qcOutCh
->globalGain
,
1016 qcOutCh
->quantSpec
) ;
1018 /*-------------------------------------------- */
1019 if (FDKaacEnc_calcMaxValueInSfb(psyOutCh
->sfbCnt
,
1020 psyOutCh
->maxSfbPerGroup
,
1021 psyOutCh
->sfbPerGroup
,
1022 psyOutCh
->sfbOffsets
,
1024 qcOutCh
->maxValueInSfb
) > MAX_QUANT
)
1026 chConstraintsFulfilled
[c
][i
][ch
] = 0;
1027 constraintsFulfilled
[c
][i
] = 0 ;
1028 /* if quanizted value out of range; increase global gain! */
1029 decreaseBitConsumption
= 1;
1032 /*-------------------------------------------- */
1034 } /* if calculateQuant[c][i][ch] */
1036 } /* channel loop */
1038 /*-------------------------------------------- */
1039 /* quantize spectrum (per each channel) */
1041 /*-------------------------------------------- */
1043 } while (!constraintsFulfilled
[c
][i
]) ; /* does not regard bit consumption */
1046 /*-------------------------------------------- */
1047 /*-------------------------------------------- */
1048 qcElement
[c
][i
]->dynBitsUsed
= 0 ; /* reset dynamic bits */
1050 /* quantization valid in current channel! */
1051 for (ch
= 0; ch
< nChannels
; ch
++)
1053 QC_OUT_CHANNEL
* qcOutCh
= qcElement
[c
][i
]->qcOutChannel
[ch
];
1054 PSY_OUT_CHANNEL
*psyOutCh
= psyOut
[c
]->psyOutElement
[i
]->psyOutChannel
[ch
];
1056 /* count dynamic bits */
1057 INT chDynBits
= FDKaacEnc_dynBitCount(hQC
->hBitCounter
,
1059 qcOutCh
->maxValueInSfb
,
1061 psyOutCh
->lastWindowSequence
,
1063 psyOutCh
->maxSfbPerGroup
,
1064 psyOutCh
->sfbPerGroup
,
1065 psyOutCh
->sfbOffsets
,
1066 &qcOutCh
->sectionData
,
1072 /* sum up dynamic channel bits */
1073 qcElement
[c
][i
]->dynBitsUsed
+= chDynBits
;
1076 /* save dynBitsUsed for correction of bits2pe relation */
1077 if(hQC
->hAdjThr
->adjThrStateElem
[i
]->dynBitsLast
==-1) {
1078 hQC
->hAdjThr
->adjThrStateElem
[i
]->dynBitsLast
= qcElement
[c
][i
]->dynBitsUsed
;
1080 } /* -end- if(ID_SCE || ID_CPE || ID_LFE) */
1082 } /* -end- element loop */
1084 /* update dynBits of current subFrame */
1085 FDKaacEnc_updateUsedDynBits(&qcOut
[c
]->usedDynBits
,
1089 /* get total consumed bits, dyn bits in all sub frames have to be valid */
1090 sumDynBitsConsumedTotal
= FDKaacEnc_getTotalConsumedDynBits(qcOut
, nSubFrames
);
1092 if (sumDynBitsConsumedTotal
==-1)
1094 quantizationDone
= 0; /* bit consumption not valid in all sub frames */
1098 int sumBitsConsumedTotal
= FDKaacEnc_getTotalConsumedBits(qcOut
, qcElement
, cm
, hQC
->globHdrBits
, nSubFrames
);
1100 /* in all frames are valid dynamic bits */
1101 if ( ((sumBitsConsumedTotal
< totalAvailableBits
) || qcOut
[c
]->usedDynBits
==0) && (decreaseBitConsumption
==1) && checkMinFrameBitsDemand(qcOut
,hQC
->minBitsPerFrame
,nSubFrames
)
1104 quantizationDone
= 1; /* exit bit adjustment */
1106 if (sumBitsConsumedTotal
> totalAvailableBits
&& (decreaseBitConsumption
==0) )
1109 quantizationDone
= 0; /* reset! */
1115 /*-------------------------------------------- */
1117 int emergencyIterations
= 1;
1118 int dynBitsOvershoot
= 0;
1120 for (c
= 0 ; c
< nSubFrames
; c
++ )
1122 for (i
=0; i
<cm
->nElements
; i
++)
1124 ELEMENT_INFO elInfo
= cm
->elInfo
[i
];
1126 if ((elInfo
.elType
== ID_SCE
) || (elInfo
.elType
== ID_CPE
) ||
1127 (elInfo
.elType
== ID_LFE
))
1129 /* iteration limitation */
1130 emergencyIterations
&= ((iterations
[c
][i
] < hQC
->maxIterations
) ? 0 : 1);
1133 /* detection if used dyn bits exceeds the maximal allowed criterion */
1134 dynBitsOvershoot
|= ((qcOut
[c
]->usedDynBits
> qcOut
[c
]->maxDynBits
) ? 1 : 0);
1137 if (quantizationDone
==0 || dynBitsOvershoot
)
1140 int sumBitsConsumedTotal
= FDKaacEnc_getTotalConsumedBits(qcOut
, qcElement
, cm
, hQC
->globHdrBits
, nSubFrames
);
1142 if ( (sumDynBitsConsumedTotal
>= avgTotalDynBits
) || (sumDynBitsConsumedTotal
==0) ) {
1143 quantizationDone
= 1;
1145 if (emergencyIterations
&& (sumBitsConsumedTotal
< totalAvailableBits
)) {
1146 quantizationDone
= 1;
1148 if ((sumBitsConsumedTotal
> totalAvailableBits
) || !checkMinFrameBitsDemand(qcOut
,hQC
->minBitsPerFrame
,nSubFrames
)) {
1149 quantizationDone
= 0;
1151 if ((sumBitsConsumedTotal
< totalAvailableBits
) && checkMinFrameBitsDemand(qcOut
,hQC
->minBitsPerFrame
,nSubFrames
)) {
1152 decreaseBitConsumption
= 0;
1155 decreaseBitConsumption
= 1;
1158 if (dynBitsOvershoot
) {
1159 quantizationDone
= 0;
1160 decreaseBitConsumption
= 1;
1163 /* reset constraints fullfilled flags */
1164 FDKmemclear(constraintsFulfilled
, sizeof(constraintsFulfilled
));
1165 FDKmemclear(chConstraintsFulfilled
, sizeof(chConstraintsFulfilled
));
1168 }/* quantizationDone */
1170 } while (!quantizationDone
) ;
1172 /*-------------------------------------------- */
1173 /* ... -end- Quantization loop */
1174 /*-------------------------------------------- */
1176 /*-------------------------------------------- */
1177 /*-------------------------------------------- */
1183 static AAC_ENCODER_ERROR
FDKaacEnc_reduceBitConsumption(int* iterations
,
1184 const int maxIterations
,
1186 int* chConstraintsFulfilled
,
1187 int* calculateQuant
,
1189 PSY_OUT_ELEMENT
* psyOutElement
,
1191 QC_OUT_ELEMENT
* qcOutElement
,
1192 ELEMENT_BITS
* elBits
,
1193 AUDIO_OBJECT_TYPE aot
,
1199 /** SOLVING PROBLEM **/
1200 if ((*iterations
)++ >= maxIterations
)
1202 if (qcOutElement
->dynBitsUsed
==0) {
1204 /* crash recovery */
1207 if ( (bitsToSave
= fixMax((qcOutElement
->dynBitsUsed
+ 8) - (elBits
->bitResLevelEl
+ qcOutElement
->grantedDynBits
),
1208 (qcOutElement
->dynBitsUsed
+ qcOutElement
->staticBitsUsed
+ 8) - (elBits
->maxBitsEl
))) > 0 )
1210 FDKaacEnc_crashRecovery(nChannels
,
1221 for (ch
= 0; ch
< nChannels
; ch
++)
1223 qcOutElement
->qcOutChannel
[ch
]->globalGain
+= 1;
1226 for (ch
= 0; ch
< nChannels
; ch
++)
1228 calculateQuant
[ch
] = 1;
1232 else /* iterations >= maxIterations */
1234 /* increase gain (+ next iteration) */
1235 for (ch
= 0; ch
< nChannels
; ch
++)
1237 if(!chConstraintsFulfilled
[ch
])
1239 qcOutElement
->qcOutChannel
[ch
]->globalGain
+= gainAdjustment
;
1240 calculateQuant
[ch
] = 1; /* global gain has changed, recalculate quantization in next iteration! */
1248 AAC_ENCODER_ERROR
FDKaacEnc_updateFillBits(CHANNEL_MAPPING
* cm
,
1250 ELEMENT_BITS
* RESTRICT elBits
[(8)],
1253 switch (qcKernel
->bitrateMode
) {
1254 case QCDATA_BR_MODE_SFR
:
1257 case QCDATA_BR_MODE_FF
:
1260 case QCDATA_BR_MODE_VBR_1
:
1261 case QCDATA_BR_MODE_VBR_2
:
1262 case QCDATA_BR_MODE_VBR_3
:
1263 case QCDATA_BR_MODE_VBR_4
:
1264 case QCDATA_BR_MODE_VBR_5
:
1265 qcOut
[0]->totFillBits
= (qcOut
[0]->grantedDynBits
- qcOut
[0]->usedDynBits
)&7; /* precalculate alignment bits */
1268 case QCDATA_BR_MODE_CBR
:
1269 case QCDATA_BR_MODE_INVALID
:
1271 INT bitResSpace
= qcKernel
->bitResTotMax
- qcKernel
->bitResTot
;
1272 /* processing fill-bits */
1273 INT deltaBitRes
= qcOut
[0]->grantedDynBits
- qcOut
[0]->usedDynBits
;
1274 qcOut
[0]->totFillBits
= fixMax((deltaBitRes
&7), (deltaBitRes
- (fixMax(0,bitResSpace
-7)&~7)));
1276 } /* switch (qcKernel->bitrateMode) */
1284 /*********************************************************************************
1286 functionname: FDKaacEnc_calcMaxValueInSfb
1290 **********************************************************************************/
1292 static INT
FDKaacEnc_calcMaxValueInSfb(INT sfbCnt
,
1295 INT
*RESTRICT sfbOffset
,
1296 SHORT
*RESTRICT quantSpectrum
,
1297 UINT
*RESTRICT maxValue
)
1300 INT maxValueAll
= 0;
1302 for (sfbOffs
=0;sfbOffs
<sfbCnt
;sfbOffs
+=sfbPerGroup
)
1303 for (sfb
= 0; sfb
< maxSfbPerGroup
; sfb
++)
1307 for (line
= sfbOffset
[sfbOffs
+sfb
]; line
< sfbOffset
[sfbOffs
+sfb
+1]; line
++)
1309 INT tmp
= fixp_abs(quantSpectrum
[line
]);
1310 maxThisSfb
= fixMax(tmp
, maxThisSfb
);
1313 maxValue
[sfbOffs
+sfb
] = maxThisSfb
;
1314 maxValueAll
= fixMax(maxThisSfb
, maxValueAll
);
1320 /*********************************************************************************
1322 functionname: FDKaacEnc_updateBitres
1326 **********************************************************************************/
1327 void FDKaacEnc_updateBitres(CHANNEL_MAPPING
*cm
,
1331 switch (qcKernel
->bitrateMode
) {
1332 case QCDATA_BR_MODE_FF
:
1333 case QCDATA_BR_MODE_VBR_1
:
1334 case QCDATA_BR_MODE_VBR_2
:
1335 case QCDATA_BR_MODE_VBR_3
:
1336 case QCDATA_BR_MODE_VBR_4
:
1337 case QCDATA_BR_MODE_VBR_5
:
1338 /* variable bitrate */
1339 qcKernel
->bitResTot
= FDKmin(qcKernel
->maxBitsPerFrame
, qcKernel
->bitResTotMax
);
1342 case QCDATA_BR_MODE_CBR
:
1343 case QCDATA_BR_MODE_SFR
:
1344 case QCDATA_BR_MODE_INVALID
:
1347 /* constant bitrate */
1349 qcKernel
->bitResTot
+= qcOut
[c
]->grantedDynBits
- (qcOut
[c
]->usedDynBits
+ qcOut
[c
]->totFillBits
+ qcOut
[c
]->alignBits
);
1355 /*********************************************************************************
1357 functionname: FDKaacEnc_FinalizeBitConsumption
1361 **********************************************************************************/
1362 AAC_ENCODER_ERROR
FDKaacEnc_FinalizeBitConsumption(CHANNEL_MAPPING
*cm
,
1365 QC_OUT_ELEMENT
** qcElement
,
1366 HANDLE_TRANSPORTENC hTpEnc
,
1367 AUDIO_OBJECT_TYPE aot
,
1371 QC_OUT_EXTENSION fillExtPayload
;
1372 INT totFillBits
, alignBits
;
1374 /* Get total consumed bits in AU */
1375 qcOut
->totalBits
= qcOut
->staticBits
+ qcOut
->usedDynBits
+ qcOut
->totFillBits
+
1376 qcOut
->elementExtBits
+ qcOut
->globalExtBits
;
1378 if (qcKernel
->bitrateMode
==QCDATA_BR_MODE_CBR
) {
1380 /* Now we can get the exact transport bit amount, and hopefully it is equal to the estimated value */
1381 INT exactTpBits
= transportEnc_GetStaticBits(hTpEnc
, qcOut
->totalBits
);
1383 if (exactTpBits
!= qcKernel
->globHdrBits
) {
1384 INT diffFillBits
= 0;
1386 /* How many bits can be taken by bitreservoir */
1387 const INT bitresSpace
= qcKernel
->bitResTotMax
- (qcKernel
->bitResTot
+ (qcOut
->grantedDynBits
- (qcOut
->usedDynBits
+ qcOut
->totFillBits
) ) );
1389 /* Number of bits which can be moved to bitreservoir. */
1390 const INT bitsToBitres
= qcKernel
->globHdrBits
- exactTpBits
;
1391 FDK_ASSERT(bitsToBitres
>=0); /* is always positive */
1393 /* If bitreservoir can not take all bits, move ramaining bits to fillbits */
1394 diffFillBits
= FDKmax(0, bitsToBitres
- bitresSpace
);
1396 /* Assure previous alignment */
1397 diffFillBits
= (diffFillBits
+7)&~7;
1399 /* Move as many bits as possible to bitreservoir */
1400 qcKernel
->bitResTot
+= (bitsToBitres
-diffFillBits
);
1402 /* Write remaing bits as fill bits */
1403 qcOut
->totFillBits
+= diffFillBits
;
1404 qcOut
->totalBits
+= diffFillBits
;
1405 qcOut
->grantedDynBits
+= diffFillBits
;
1407 /* Get new header bits */
1408 qcKernel
->globHdrBits
= transportEnc_GetStaticBits(hTpEnc
, qcOut
->totalBits
);
1410 if (qcKernel
->globHdrBits
!= exactTpBits
) {
1411 /* In previous step, fill bits and corresponding total bits were changed when bitreservoir was completely filled.
1412 Now we can take the too much taken bits caused by header overhead from bitreservoir.
1414 qcKernel
->bitResTot
-= (qcKernel
->globHdrBits
- exactTpBits
);
1420 /* Update exact number of consumed header bits. */
1421 qcKernel
->globHdrBits
= transportEnc_GetStaticBits(hTpEnc
, qcOut
->totalBits
);
1423 /* Save total fill bits and distribut to alignment and fill bits */
1424 totFillBits
= qcOut
->totFillBits
;
1426 /* fake a fill extension payload */
1427 FDKmemclear(&fillExtPayload
, sizeof(QC_OUT_EXTENSION
));
1429 fillExtPayload
.type
= EXT_FILL_DATA
;
1430 fillExtPayload
.nPayloadBits
= totFillBits
;
1432 /* ask bitstream encoder how many of that bits can be written in a fill extension data entity */
1433 qcOut
->totFillBits
= FDKaacEnc_writeExtensionData( NULL
,
1440 /* now distribute extra fillbits and alignbits */
1441 alignBits
= 7 - (qcOut
->staticBits
+ qcOut
->usedDynBits
+ qcOut
->elementExtBits
1442 + qcOut
->totFillBits
+ qcOut
->globalExtBits
-1)%8;
1444 /* Maybe we could remove this */
1445 if( ((alignBits
+ qcOut
->totFillBits
- totFillBits
)==8) && (qcOut
->totFillBits
>8) )
1446 qcOut
->totFillBits
-= 8;
1448 qcOut
->totalBits
= qcOut
->staticBits
+ qcOut
->usedDynBits
+ qcOut
->totFillBits
+
1449 alignBits
+ qcOut
->elementExtBits
+ qcOut
->globalExtBits
;
1451 if ( (qcOut
->totalBits
>qcKernel
->maxBitsPerFrame
) || (qcOut
->totalBits
<qcKernel
->minBitsPerFrame
) ) {
1452 return AAC_ENC_QUANT_ERROR
;
1455 qcOut
->alignBits
= alignBits
;
1462 /*********************************************************************************
1464 functionname: FDKaacEnc_crashRecovery
1465 description: fulfills constraints by means of brute force...
1466 => bits are saved by cancelling out spectral lines!!
1467 (beginning at the highest frequencies)
1470 **********************************************************************************/
1472 static void FDKaacEnc_crashRecovery(INT nChannels
,
1473 PSY_OUT_ELEMENT
* psyOutElement
,
1475 QC_OUT_ELEMENT
*qcElement
,
1477 AUDIO_OBJECT_TYPE aot
,
1484 INT bitsPerScf
[(2)][MAX_GROUPED_SFB
] ;
1485 INT sectionToScf
[(2)][MAX_GROUPED_SFB
] ;
1487 INT sect
, statBitsNew
;
1488 QC_OUT_CHANNEL
**qcChannel
= qcElement
->qcOutChannel
;
1489 PSY_OUT_CHANNEL
**psyChannel
= psyOutElement
->psyOutChannel
;
1491 /* create a table which converts frq-bins to bit-demand... [bitsPerScf] */
1492 /* ...and another one which holds the corresponding sections [sectionToScf] */
1493 for (ch
= 0; ch
< nChannels
; ch
++)
1495 sfbOffset
= psyChannel
[ch
]->sfbOffsets
;
1497 for (sect
= 0; sect
< qcChannel
[ch
]->sectionData
.noOfSections
; sect
++)
1500 INT codeBook
= qcChannel
[ch
]->sectionData
.huffsection
[sect
].codeBook
;
1502 for (sfb
= qcChannel
[ch
]->sectionData
.huffsection
[sect
].sfbStart
;
1503 sfb
< qcChannel
[ch
]->sectionData
.huffsection
[sect
].sfbStart
+
1504 qcChannel
[ch
]->sectionData
.huffsection
[sect
].sfbCnt
;
1507 bitsPerScf
[ch
][sfb
] = 0;
1508 if ( (codeBook
!= CODE_BOOK_PNS_NO
) /*&&
1509 (sfb < (qcChannel[ch]->sectionData.noOfGroups*qcChannel[ch]->sectionData.maxSfbPerGroup))*/ )
1511 INT sfbStartLine
= sfbOffset
[sfb
] ;
1512 INT noOfLines
= sfbOffset
[sfb
+1] - sfbStartLine
;
1513 bitsPerScf
[ch
][sfb
] = FDKaacEnc_countValues(&(qcChannel
[ch
]->quantSpec
[sfbStartLine
]), noOfLines
, codeBook
) ;
1515 sectionToScf
[ch
][sfb
] = sect
;
1521 /* LOWER [maxSfb] IN BOTH CHANNELS!! */
1522 /* Attention: in case of stereo: maxSfbL == maxSfbR, GroupingL == GroupingR ; */
1524 for (sfb
= qcChannel
[0]->sectionData
.maxSfbPerGroup
-1; sfb
>= 0; sfb
--)
1526 for (sfbGrp
= 0; sfbGrp
< psyChannel
[0]->sfbCnt
; sfbGrp
+= psyChannel
[0]->sfbPerGroup
)
1528 for (ch
= 0; ch
< nChannels
; ch
++)
1530 int sect
= sectionToScf
[ch
][sfbGrp
+sfb
];
1531 qcChannel
[ch
]->sectionData
.huffsection
[sect
].sfbCnt
-- ;
1532 savedBits
+= bitsPerScf
[ch
][sfbGrp
+sfb
] ;
1534 if (qcChannel
[ch
]->sectionData
.huffsection
[sect
].sfbCnt
== 0) {
1535 savedBits
+= (psyChannel
[ch
]->lastWindowSequence
!=SHORT_WINDOW
) ? FDKaacEnc_sideInfoTabLong
[0]
1536 : FDKaacEnc_sideInfoTabShort
[0];
1541 /* ...have enough bits been saved? */
1542 if (savedBits
>= bitsToSave
)
1547 /* if not enough bits saved,
1548 clean whole spectrum and remove side info overhead */
1553 for (ch
= 0; ch
< nChannels
; ch
++)
1555 qcChannel
[ch
]->sectionData
.maxSfbPerGroup
= sfb
;
1556 psyChannel
[ch
]->maxSfbPerGroup
= sfb
;
1557 /* when no spectrum is coded save tools info in bitstream */
1559 FDKmemclear(&psyChannel
[ch
]->tnsInfo
, sizeof(TNS_INFO
));
1560 FDKmemclear(&psyOutElement
->toolsInfo
, sizeof(TOOLSINFO
));
1563 /* dynamic bits will be updated in iteration loop */
1565 { /* if stop sfb has changed save bits in side info, e.g. MS or TNS coding */
1566 ELEMENT_INFO elInfo
;
1568 FDKmemclear(&elInfo
, sizeof(ELEMENT_INFO
));
1569 elInfo
.nChannelsInEl
= nChannels
;
1570 elInfo
.elType
= (nChannels
== 2) ? ID_CPE
: ID_SCE
;
1572 FDKaacEnc_ChannelElementWrite( NULL
, &elInfo
, NULL
,
1582 savedBits
= qcElement
->staticBitsUsed
- statBitsNew
;
1584 /* update static and dynamic bits */
1585 qcElement
->staticBitsUsed
-= savedBits
;
1586 qcElement
->grantedDynBits
+= savedBits
;
1588 qcOut
->staticBits
-= savedBits
;
1589 qcOut
->grantedDynBits
+= savedBits
;
1590 qcOut
->maxDynBits
+= savedBits
;
1597 void FDKaacEnc_QCClose (QC_STATE
**phQCstate
, QC_OUT
**phQC
)
1603 for (n
=0;n
<(1);n
++) {
1604 if (phQC
[n
] != NULL
) {
1605 QC_OUT
*hQC
= phQC
[n
];
1606 for (i
=0; i
<(8); i
++) {
1609 for (i
=0; i
<(8); i
++) {
1610 if (hQC
->qcElement
[i
])
1611 FreeRam_aacEnc_QCelement(&hQC
->qcElement
[i
]);
1614 FreeRam_aacEnc_QCout(&phQC
[n
]);
1619 if (phQCstate
!=NULL
) {
1620 if (*phQCstate
!= NULL
) {
1621 QC_STATE
*hQCstate
= *phQCstate
;
1623 if (hQCstate
->hAdjThr
!= NULL
)
1624 FDKaacEnc_AdjThrClose(&hQCstate
->hAdjThr
);
1626 if (hQCstate
->hBitCounter
!= NULL
)
1627 FDKaacEnc_BCClose(&hQCstate
->hBitCounter
);
1629 for (i
=0; i
<(8); i
++) {
1630 if (hQCstate
->elementBits
[i
]!=NULL
) {
1631 FreeRam_aacEnc_ElementBits(&hQCstate
->elementBits
[i
]);
1634 FreeRam_aacEnc_QCstate(phQCstate
);