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