1
2 /* -----------------------------------------------------------------------------------------------------------
3 Software License for The Fraunhofer FDK AAC Codec Library for Android
4
5 � Copyright 1995 - 2012 Fraunhofer-Gesellschaft zur F�rderung 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@iis.fraunhofer.de
82 ----------------------------------------------------------------------------------------------------------- */
83
84 /*************************** Fast MPEG AAC Audio Encoder **********************
85
86 Initial author: M. Schug / A. Groeschel
87 contents/description: fast aac coder functions
88
89 ******************************************************************************/
90
91 #include "aacenc.h"
92
93 #include "bitenc.h"
94 #include "interface.h"
95 #include "psy_configuration.h"
96 #include "psy_main.h"
97 #include "qc_main.h"
98 #include "bandwidth.h"
99 #include "channel_map.h"
100 #include "tns_func.h"
101 #include "aacEnc_ram.h"
102
103 #include "genericStds.h"
104
105
106
107
108 #define MIN_BUFSIZE_PER_EFF_CHAN 6144
109
110 static AAC_ENCODER_ERROR FDKaacEnc_InitCheckAncillary(INT bitRate,
111 INT framelength,
112 INT ancillaryRate,
113 INT *ancillaryBitsPerFrame,
114 INT sampleRate);
115
FDKaacEnc_LimitBitrate(HANDLE_TRANSPORTENC hTpEnc,INT coreSamplingRate,INT frameLength,INT nChannels,INT nChannelsEff,INT bitRate,INT averageBits,INT * pAverageBitsPerFrame,INT bitrateMode,INT nSubFrames)116 INT FDKaacEnc_LimitBitrate(
117 HANDLE_TRANSPORTENC hTpEnc,
118 INT coreSamplingRate,
119 INT frameLength,
120 INT nChannels,
121 INT nChannelsEff,
122 INT bitRate,
123 INT averageBits,
124 INT *pAverageBitsPerFrame,
125 INT bitrateMode,
126 INT nSubFrames
127 )
128 {
129 INT transportBits, prevBitRate, averageBitsPerFrame, shift = 0, iter=0;
130
131 while ( (frameLength & ~((1<<(shift+1))-1)) == frameLength
132 && (coreSamplingRate & ~((1<<(shift+1))-1)) == coreSamplingRate )
133 {
134 shift ++;
135 }
136
137 do {
138 prevBitRate = bitRate;
139 averageBitsPerFrame = (bitRate*(frameLength>>shift)) / (coreSamplingRate>>shift) / nSubFrames;
140
141 if (pAverageBitsPerFrame != NULL) {
142 *pAverageBitsPerFrame = averageBitsPerFrame;
143 }
144
145 if (hTpEnc != NULL) {
146 transportBits = transportEnc_GetStaticBits(hTpEnc, averageBitsPerFrame);
147 } else {
148 /* Assume some worst case */
149 transportBits = 208;
150 }
151
152 bitRate = FDKmax(bitRate, ((((40 * nChannels) + transportBits) * (coreSamplingRate)) / frameLength) );
153 FDK_ASSERT(bitRate >= 0);
154
155 bitRate = FDKmin(bitRate, ((nChannelsEff * MIN_BUFSIZE_PER_EFF_CHAN)*(coreSamplingRate>>shift)) / (frameLength>>shift)) ;
156 FDK_ASSERT(bitRate >= 0);
157
158 } while (prevBitRate != bitRate && iter++ < 3) ;
159
160 return bitRate;
161 }
162
163
164 typedef struct
165 {
166 AACENC_BITRATE_MODE bitrateMode;
167 int chanBitrate[2]; /* mono/stereo settings */
168 } CONFIG_TAB_ENTRY_VBR;
169
170 static const CONFIG_TAB_ENTRY_VBR configTabVBR[] = {
171 {AACENC_BR_MODE_CBR, { 0, 0}} ,
172 {AACENC_BR_MODE_VBR_1, { 32000, 20000}} ,
173 {AACENC_BR_MODE_VBR_2, { 40000, 32000}} ,
174 {AACENC_BR_MODE_VBR_3, { 56000, 48000}} ,
175 {AACENC_BR_MODE_VBR_4, { 72000, 64000}} ,
176 {AACENC_BR_MODE_VBR_5, {112000, 96000}}
177 };
178
179 /*-----------------------------------------------------------------------------
180
181 functionname: FDKaacEnc_GetVBRBitrate
182 description: Get VBR bitrate from vbr quality
183 input params: int vbrQuality (VBR0, VBR1, VBR2)
184 channelMode
185 returns: vbr bitrate
186
187 ------------------------------------------------------------------------------*/
FDKaacEnc_GetVBRBitrate(INT bitrateMode,CHANNEL_MODE channelMode)188 INT FDKaacEnc_GetVBRBitrate(INT bitrateMode, CHANNEL_MODE channelMode)
189 {
190 INT bitrate = 0;
191 INT monoStereoMode = 0; /* default mono */
192
193 if (FDKaacEnc_GetMonoStereoMode(channelMode)==EL_MODE_STEREO) {
194 monoStereoMode = 1;
195 }
196
197 switch((AACENC_BITRATE_MODE)bitrateMode){
198 case AACENC_BR_MODE_VBR_1:
199 case AACENC_BR_MODE_VBR_2:
200 case AACENC_BR_MODE_VBR_3:
201 case AACENC_BR_MODE_VBR_4:
202 case AACENC_BR_MODE_VBR_5:
203 bitrate = configTabVBR[bitrateMode].chanBitrate[monoStereoMode];
204 break;
205 case AACENC_BR_MODE_INVALID:
206 case AACENC_BR_MODE_CBR:
207 case AACENC_BR_MODE_SFR:
208 case AACENC_BR_MODE_FF:
209 default:
210 bitrate = 0;
211 break;
212 }
213
214 /* convert channel bitrate to overall bitrate*/
215 bitrate *= FDKaacEnc_GetChannelModeConfiguration(channelMode)->nChannelsEff;
216
217 return bitrate;
218 }
219
220 /**
221 * \brief Convert encoder bitreservoir value for transport library.
222 *
223 * \param bitrateMode Bitratemode used in current encoder instance. Se ::AACENC_BITRATE_MODE
224 * \param bitresTotal Encoder bitreservoir level in bits.
225 *
226 * \return Corrected bitreservoir level used in transport library.
227 */
FDKaacEnc_EncBitresToTpBitres(const AACENC_BITRATE_MODE bitrateMode,const INT bitresTotal)228 static INT FDKaacEnc_EncBitresToTpBitres(
229 const AACENC_BITRATE_MODE bitrateMode,
230 const INT bitresTotal
231 )
232 {
233 INT transporBitreservoir = 0;
234
235 switch (bitrateMode) {
236 case AACENC_BR_MODE_CBR:
237 transporBitreservoir = bitresTotal; /* encoder bitreservoir level */
238 break;
239 case AACENC_BR_MODE_VBR_1:
240 case AACENC_BR_MODE_VBR_2:
241 case AACENC_BR_MODE_VBR_3:
242 case AACENC_BR_MODE_VBR_4:
243 case AACENC_BR_MODE_VBR_5:
244 transporBitreservoir = FDK_INT_MAX; /* signal variable bitrate */
245 break;
246 case AACENC_BR_MODE_FF:
247 case AACENC_BR_MODE_SFR:
248 transporBitreservoir = 0; /* super framing and fixed framing */
249 break; /* without bitreservoir signaling */
250 default:
251 case AACENC_BR_MODE_INVALID:
252 transporBitreservoir = 0; /* invalid configuration*/
253 FDK_ASSERT(0);
254 }
255
256 return transporBitreservoir;
257 }
258
259 /*-----------------------------------------------------------------------------
260
261 functionname: FDKaacEnc_AacInitDefaultConfig
262 description: gives reasonable default configuration
263 returns: ---
264
265 ------------------------------------------------------------------------------*/
FDKaacEnc_AacInitDefaultConfig(AACENC_CONFIG * config)266 void FDKaacEnc_AacInitDefaultConfig(AACENC_CONFIG *config)
267 {
268 /* make thepre initialization of the structs flexible */
269 FDKmemclear(config, sizeof(AACENC_CONFIG));
270
271 /* default ancillary */
272 config->anc_Rate = 0; /* no ancillary data */
273 config->ancDataBitRate = 0; /* no additional consumed bitrate */
274
275 /* default configurations */
276 config->bitRate = -1; /* bitrate must be set*/
277 config->averageBits = -1; /* instead of bitrate/s we can configure bits/superframe */
278 config->bitrateMode = 0;
279 config->bandWidth = 0; /* get bandwidth from table */
280 config->useTns = TNS_ENABLE_MASK; /* tns enabled completly */
281 config->usePns = 1; /* depending on channelBitrate this might be set to 0 later */
282 config->useIS = 1; /* Intensity Stereo Configuration */
283 config->framelength = -1; /* Framesize not configured */
284 config->syntaxFlags = 0; /* default syntax with no specialities */
285 config->epConfig = -1; /* no ER syntax -> no additional error protection */
286 config->nSubFrames = 1; /* default, no sub frames */
287 config->channelOrder = CH_ORDER_MPEG; /* Use MPEG channel ordering. */
288 config->channelMode = MODE_UNKNOWN;
289 config->minBitsPerFrame = -1; /* minum number of bits in each AU */
290 config->maxBitsPerFrame = -1; /* minum number of bits in each AU */
291 config->bitreservoir = -1; /* default, uninitialized value */
292
293 /* init tabs in fixpoint_math */
294 InitLdInt();
295 InitInvSqrtTab();
296 }
297
298
299 /*---------------------------------------------------------------------------
300
301 functionname: FDKaacEnc_Open
302 description: allocate and initialize a new encoder instance
303 returns: error code
304
305 ---------------------------------------------------------------------------*/
FDKaacEnc_Open(HANDLE_AAC_ENC * phAacEnc,const INT nElements,const INT nChannels,const INT nSubFrames)306 AAC_ENCODER_ERROR FDKaacEnc_Open(HANDLE_AAC_ENC *phAacEnc,
307 const INT nElements,
308 const INT nChannels,
309 const INT nSubFrames)
310 {
311 AAC_ENCODER_ERROR ErrorStatus;
312 AAC_ENC *hAacEnc = NULL;
313 UCHAR *dynamicRAM = NULL;
314
315 if (phAacEnc==NULL) {
316 return AAC_ENC_INVALID_HANDLE;
317 }
318
319 /* allocate encoder structure */
320 hAacEnc = GetRam_aacEnc_AacEncoder();
321 if (hAacEnc == NULL) {
322 ErrorStatus = AAC_ENC_NO_MEMORY;
323 goto bail;
324 }
325 FDKmemclear(hAacEnc, sizeof(AAC_ENC));
326
327 hAacEnc->dynamic_RAM = GetAACdynamic_RAM();
328 dynamicRAM = (UCHAR*)hAacEnc->dynamic_RAM;
329
330 /* allocate the Psy aud Psy Out structure */
331 ErrorStatus = FDKaacEnc_PsyNew(&hAacEnc->psyKernel,
332 nElements,
333 nChannels
334 ,dynamicRAM
335 );
336 if (ErrorStatus != AAC_ENC_OK)
337 goto bail;
338
339 ErrorStatus = FDKaacEnc_PsyOutNew(hAacEnc->psyOut,
340 nElements,
341 nChannels,
342 nSubFrames
343 ,dynamicRAM
344 );
345 if (ErrorStatus != AAC_ENC_OK)
346 goto bail;
347
348 /* allocate the Q&C Out structure */
349 ErrorStatus = FDKaacEnc_QCOutNew(hAacEnc->qcOut,
350 nElements,
351 nChannels,
352 nSubFrames
353 ,dynamicRAM
354 );
355 if (ErrorStatus != AAC_ENC_OK)
356 goto bail;
357
358 /* allocate the Q&C kernel */
359 ErrorStatus = FDKaacEnc_QCNew(&hAacEnc->qcKernel,
360 nElements
361 ,dynamicRAM
362 );
363 if (ErrorStatus != AAC_ENC_OK)
364 goto bail;
365
366 hAacEnc->maxChannels = nChannels;
367 hAacEnc->maxElements = nElements;
368 hAacEnc->maxFrames = nSubFrames;
369
370 bail:
371 *phAacEnc = hAacEnc;
372 return ErrorStatus;
373 }
374
375
FDKaacEnc_Initialize(HANDLE_AAC_ENC hAacEnc,AACENC_CONFIG * config,HANDLE_TRANSPORTENC hTpEnc,ULONG initFlags)376 AAC_ENCODER_ERROR FDKaacEnc_Initialize(HANDLE_AAC_ENC hAacEnc,
377 AACENC_CONFIG *config, /* pre-initialized config struct */
378 HANDLE_TRANSPORTENC hTpEnc,
379 ULONG initFlags)
380 {
381 AAC_ENCODER_ERROR ErrorStatus;
382 INT psyBitrate, tnsMask; //INT profile = 1;
383 CHANNEL_MAPPING *cm = NULL;
384
385 INT qmbfac, qbw;
386 FIXP_DBL mbfac, bw_ratio;
387 QC_INIT qcInit;
388 INT averageBitsPerFrame = 0;
389
390 if (config==NULL)
391 return AAC_ENC_INVALID_HANDLE;
392
393 /******************* sanity checks *******************/
394
395 /* check config structure */
396 if (config->nChannels < 1 || config->nChannels > (6)) {
397 return AAC_ENC_UNSUPPORTED_CHANNELCONFIG;
398 }
399
400 /* check sample rate */
401 switch (config->sampleRate)
402 {
403 case 8000:
404 case 11025:
405 case 12000:
406 case 16000:
407 case 22050:
408 case 24000:
409 case 32000:
410 case 44100:
411 case 48000:
412 case 64000:
413 case 88200:
414 case 96000:
415 break;
416 default:
417 return AAC_ENC_UNSUPPORTED_SAMPLINGRATE;
418 }
419
420 /* bitrate has to be set */
421 if (config->bitRate==-1) {
422 return AAC_ENC_UNSUPPORTED_BITRATE;
423 }
424
425 /* check bit rate */
426
427 if (FDKaacEnc_LimitBitrate(
428 hTpEnc,
429 config->sampleRate,
430 config->framelength,
431 config->nChannels,
432 FDKaacEnc_GetChannelModeConfiguration(config->channelMode)->nChannelsEff,
433 config->bitRate,
434 config->averageBits,
435 &averageBitsPerFrame,
436 config->bitrateMode,
437 config->nSubFrames
438 ) != config->bitRate )
439 {
440 return AAC_ENC_UNSUPPORTED_BITRATE;
441 }
442
443 if (config->syntaxFlags & AC_ER_VCB11) {
444 return AAC_ENC_UNSUPPORTED_ER_FORMAT;
445 }
446 if (config->syntaxFlags & AC_ER_HCR) {
447 return AAC_ENC_UNSUPPORTED_ER_FORMAT;
448 }
449
450 /* check frame length */
451 switch (config->framelength)
452 {
453 case 1024:
454 if ( config->audioObjectType == AOT_ER_AAC_LD
455 || config->audioObjectType == AOT_ER_AAC_ELD )
456 {
457 return AAC_ENC_INVALID_FRAME_LENGTH;
458 }
459 break;
460 case 512:
461 case 480:
462 if ( config->audioObjectType != AOT_ER_AAC_LD
463 && config->audioObjectType != AOT_ER_AAC_ELD )
464 {
465 return AAC_ENC_INVALID_FRAME_LENGTH;
466 }
467 break;
468 default:
469 return AAC_ENC_INVALID_FRAME_LENGTH;
470 }
471
472 if (config->anc_Rate != 0) {
473
474 ErrorStatus = FDKaacEnc_InitCheckAncillary(config->bitRate,
475 config->framelength,
476 config->anc_Rate,
477 &hAacEnc->ancillaryBitsPerFrame,
478 config->sampleRate);
479 if (ErrorStatus != AAC_ENC_OK)
480 goto bail;
481
482
483 /* update estimated consumed bitrate */
484 config->ancDataBitRate += ( (hAacEnc->ancillaryBitsPerFrame * config->sampleRate) / config->framelength );
485
486 }
487
488 /* maximal allowed DSE bytes in frame */
489 {
490 /* fixpoint calculation*/
491 INT q_res, encBitrate, sc;
492 FIXP_DBL tmp = fDivNorm(config->framelength, config->sampleRate, &q_res);
493 encBitrate = (config->bitRate/*-config->ancDataBitRate*/)- (INT)(config->nChannels*8000);
494 sc = CountLeadingBits(encBitrate);
495 config->maxAncBytesPerAU = FDKmin( (256), FDKmax(0,(INT)(fMultDiv2(tmp, (FIXP_DBL)(encBitrate<<sc))>>(-q_res+sc-1+3))) );
496 }
497
498 /* bind config to hAacEnc->config */
499 hAacEnc->config = config;
500
501 /* set hAacEnc->bitrateMode */
502 hAacEnc->bitrateMode = (AACENC_BITRATE_MODE)config->bitrateMode;
503
504 hAacEnc->encoderMode = config->channelMode;
505
506 ErrorStatus = FDKaacEnc_InitChannelMapping(hAacEnc->encoderMode, config->channelOrder, &hAacEnc->channelMapping);
507 if (ErrorStatus != AAC_ENC_OK)
508 goto bail;
509
510 cm = &hAacEnc->channelMapping;
511
512 ErrorStatus = FDKaacEnc_DetermineBandWidth(&hAacEnc->config->bandWidth,
513 config->bandWidth,
514 config->bitRate - config->ancDataBitRate,
515 hAacEnc->bitrateMode,
516 config->sampleRate,
517 config->framelength,
518 cm,
519 hAacEnc->encoderMode);
520 if (ErrorStatus != AAC_ENC_OK)
521 goto bail;
522
523 hAacEnc->bandwidth90dB = (INT)hAacEnc->config->bandWidth;
524
525 tnsMask = config->useTns ? TNS_ENABLE_MASK : 0x0;
526 psyBitrate = config->bitRate - config->ancDataBitRate;
527
528 ErrorStatus = FDKaacEnc_psyInit(hAacEnc->psyKernel,
529 hAacEnc->psyOut,
530 hAacEnc->maxFrames,
531 hAacEnc->maxChannels,
532 config->audioObjectType,
533 cm);
534 if (ErrorStatus != AAC_ENC_OK)
535 goto bail;
536
537 ErrorStatus = FDKaacEnc_psyMainInit(hAacEnc->psyKernel,
538 config->audioObjectType,
539 cm,
540 config->sampleRate,
541 config->framelength,
542 psyBitrate,
543 tnsMask,
544 hAacEnc->bandwidth90dB,
545 config->usePns,
546 config->useIS,
547 config->syntaxFlags,
548 initFlags);
549 if (ErrorStatus != AAC_ENC_OK)
550 goto bail;
551
552 ErrorStatus = FDKaacEnc_QCOutInit(hAacEnc->qcOut, hAacEnc->maxFrames, cm);
553 if (ErrorStatus != AAC_ENC_OK)
554 goto bail;
555
556
557
558 qcInit.channelMapping = &hAacEnc->channelMapping;
559 qcInit.sceCpe = 0;
560
561 {
562 int maxBitres;
563 qcInit.averageBits = (averageBitsPerFrame+7)&~7;
564 maxBitres = (MIN_BUFSIZE_PER_EFF_CHAN*cm->nChannelsEff) - qcInit.averageBits;
565 qcInit.bitRes = (config->bitreservoir!=-1) ? FDKmin(config->bitreservoir, maxBitres) : maxBitres;
566
567 qcInit.maxBits = fixMin(MIN_BUFSIZE_PER_EFF_CHAN*cm->nChannelsEff, ((averageBitsPerFrame+7)&~7)+qcInit.bitRes);
568 qcInit.maxBits = (config->maxBitsPerFrame!=-1) ? fixMin(qcInit.maxBits, config->maxBitsPerFrame) : qcInit.maxBits;
569
570 qcInit.minBits = fixMax(0, ((averageBitsPerFrame-1)&~7)-qcInit.bitRes-transportEnc_GetStaticBits(hTpEnc, ((averageBitsPerFrame+7)&~7)+qcInit.bitRes));
571 qcInit.minBits = (config->minBitsPerFrame!=-1) ? fixMax(qcInit.minBits, config->minBitsPerFrame) : qcInit.minBits;
572 }
573
574 qcInit.nSubFrames = config->nSubFrames;
575 qcInit.padding.paddingRest = config->sampleRate;
576
577 /* Calc meanPe */
578 bw_ratio = fDivNorm((FIXP_DBL)hAacEnc->bandwidth90dB, (FIXP_DBL)(config->sampleRate>>1), &qbw);
579 qbw = DFRACT_BITS-1-qbw;
580 /* qcInit.meanPe = 10.0f * FRAME_LEN_LONG * hAacEnc->bandwidth90dB/(config->sampleRate/2.0f); */
581 qcInit.meanPe = fMult(bw_ratio, (FIXP_DBL)((10*config->framelength)<<16)) >> (qbw-15);
582
583 /* Calc maxBitFac */
584 mbfac = fDivNorm((MIN_BUFSIZE_PER_EFF_CHAN-744)*cm->nChannelsEff, qcInit.averageBits/qcInit.nSubFrames, &qmbfac);
585 qmbfac = DFRACT_BITS-1-qmbfac;
586 qcInit.maxBitFac = (qmbfac > 24) ? (mbfac >> (qmbfac - 24)):(mbfac << (24 - qmbfac));
587
588 switch(config->bitrateMode){
589 case AACENC_BR_MODE_CBR:
590 qcInit.bitrateMode = QCDATA_BR_MODE_CBR;
591 break;
592 case AACENC_BR_MODE_VBR_1:
593 qcInit.bitrateMode = QCDATA_BR_MODE_VBR_1;
594 break;
595 case AACENC_BR_MODE_VBR_2:
596 qcInit.bitrateMode = QCDATA_BR_MODE_VBR_2;
597 break;
598 case AACENC_BR_MODE_VBR_3:
599 qcInit.bitrateMode = QCDATA_BR_MODE_VBR_3;
600 break;
601 case AACENC_BR_MODE_VBR_4:
602 qcInit.bitrateMode = QCDATA_BR_MODE_VBR_4;
603 break;
604 case AACENC_BR_MODE_VBR_5:
605 qcInit.bitrateMode = QCDATA_BR_MODE_VBR_5;
606 break;
607 case AACENC_BR_MODE_SFR:
608 qcInit.bitrateMode = QCDATA_BR_MODE_SFR;
609 break;
610 case AACENC_BR_MODE_FF:
611 qcInit.bitrateMode = QCDATA_BR_MODE_FF;
612 break;
613 default:
614 ErrorStatus = AAC_ENC_UNSUPPORTED_BITRATE_MODE;
615 goto bail;
616 }
617
618 qcInit.invQuant = (config->useRequant)?2:0;
619
620 /* maxIterations should be set to the maximum number of requantization iterations that are
621 * allowed before the crash recovery functionality is activated. This setting should be adjusted
622 * to the processing power available, i.e. to the processing power headroom in one frame that is
623 * still left after normal encoding without requantization. Please note that if activated this
624 * functionality is used most likely only in cases where the encoder is operating beyond
625 * recommended settings, i.e. the audio quality is suboptimal anyway. Activating the crash
626 * recovery does not further reduce audio quality significantly in these cases. */
627 if ( (config->audioObjectType == AOT_ER_AAC_LD) || (config->audioObjectType == AOT_ER_AAC_ELD) ) {
628 qcInit.maxIterations = 2;
629 }
630 else
631 {
632 qcInit.maxIterations = 5;
633 }
634
635 qcInit.bitrate = config->bitRate - config->ancDataBitRate;
636
637 qcInit.staticBits = transportEnc_GetStaticBits(hTpEnc, qcInit.averageBits/qcInit.nSubFrames);
638
639 ErrorStatus = FDKaacEnc_QCInit(hAacEnc->qcKernel, &qcInit);
640 if (ErrorStatus != AAC_ENC_OK)
641 goto bail;
642
643 /* Map virtual aot's to intern aot used in bitstream writer. */
644 switch (hAacEnc->config->audioObjectType) {
645 case AOT_MP2_AAC_LC:
646 case AOT_DABPLUS_AAC_LC:
647 hAacEnc->aot = AOT_AAC_LC;
648 break;
649 case AOT_MP2_SBR:
650 case AOT_DABPLUS_SBR:
651 hAacEnc->aot = AOT_SBR;
652 break;
653 case AOT_MP2_PS:
654 case AOT_DABPLUS_PS:
655 hAacEnc->aot = AOT_PS;
656 break;
657 default:
658 hAacEnc->aot = hAacEnc->config->audioObjectType;
659 }
660
661 /* common things */
662
663 return AAC_ENC_OK;
664
665 bail:
666
667 return ErrorStatus;
668 }
669
670
671 /*---------------------------------------------------------------------------
672
673 functionname: FDKaacEnc_EncodeFrame
674 description: encodes one frame
675 returns: error code
676
677 ---------------------------------------------------------------------------*/
FDKaacEnc_EncodeFrame(HANDLE_AAC_ENC hAacEnc,HANDLE_TRANSPORTENC hTpEnc,INT_PCM * RESTRICT inputBuffer,INT * nOutBytes,AACENC_EXT_PAYLOAD extPayload[MAX_TOTAL_EXT_PAYLOADS])678 AAC_ENCODER_ERROR FDKaacEnc_EncodeFrame( HANDLE_AAC_ENC hAacEnc, /* encoder handle */
679 HANDLE_TRANSPORTENC hTpEnc,
680 INT_PCM* RESTRICT inputBuffer,
681 INT* nOutBytes,
682 AACENC_EXT_PAYLOAD extPayload[MAX_TOTAL_EXT_PAYLOADS]
683 )
684 {
685 AAC_ENCODER_ERROR ErrorStatus;
686 int el, n, c=0;
687 UCHAR extPayloadUsed[MAX_TOTAL_EXT_PAYLOADS];
688
689 CHANNEL_MAPPING *cm = &hAacEnc->channelMapping;
690
691
692
693 PSY_OUT *psyOut = hAacEnc->psyOut[c];
694 QC_OUT *qcOut = hAacEnc->qcOut[c];
695
696 FDKmemclear(extPayloadUsed, MAX_TOTAL_EXT_PAYLOADS * sizeof(UCHAR));
697
698 qcOut->elementExtBits = 0; /* sum up all extended bit of each element */
699 qcOut->staticBits = 0; /* sum up side info bits of each element */
700 qcOut->totalNoRedPe = 0; /* sum up PE */
701
702 /* advance psychoacoustics */
703 for (el=0; el<cm->nElements; el++) {
704 ELEMENT_INFO elInfo = cm->elInfo[el];
705
706 if ( (elInfo.elType == ID_SCE)
707 || (elInfo.elType == ID_CPE)
708 || (elInfo.elType == ID_LFE) )
709 {
710 int ch;
711
712 /* update pointer!*/
713 for(ch=0;ch<elInfo.nChannelsInEl;ch++) {
714 PSY_OUT_CHANNEL *psyOutChan = psyOut->psyOutElement[el]->psyOutChannel[ch];
715 QC_OUT_CHANNEL *qcOutChan = qcOut->qcElement[el]->qcOutChannel[ch];
716
717 psyOutChan->mdctSpectrum = qcOutChan->mdctSpectrum;
718 psyOutChan->sfbSpreadEnergy = qcOutChan->sfbSpreadEnergy;
719 psyOutChan->sfbEnergy = qcOutChan->sfbEnergy;
720 psyOutChan->sfbEnergyLdData = qcOutChan->sfbEnergyLdData;
721 psyOutChan->sfbMinSnrLdData = qcOutChan->sfbMinSnrLdData;
722 psyOutChan->sfbThresholdLdData = qcOutChan->sfbThresholdLdData;
723
724 }
725
726 FDKaacEnc_psyMain(elInfo.nChannelsInEl,
727 hAacEnc->psyKernel->psyElement[el],
728 hAacEnc->psyKernel->psyDynamic,
729 hAacEnc->psyKernel->psyConf,
730 psyOut->psyOutElement[el],
731 inputBuffer,
732 cm->elInfo[el].ChannelIndex,
733 cm->nChannels
734
735 );
736
737 /* FormFactor, Pe and staticBitDemand calculation */
738 ErrorStatus = FDKaacEnc_QCMainPrepare(&elInfo,
739 hAacEnc->qcKernel->hAdjThr->adjThrStateElem[el],
740 psyOut->psyOutElement[el],
741 qcOut->qcElement[el],
742 hAacEnc->aot,
743 hAacEnc->config->syntaxFlags,
744 hAacEnc->config->epConfig);
745
746 if (ErrorStatus != AAC_ENC_OK)
747 return ErrorStatus;
748
749 /*-------------------------------------------- */
750
751 qcOut->qcElement[el]->extBitsUsed = 0;
752 qcOut->qcElement[el]->nExtensions = 0;
753 /* reset extension payload */
754 FDKmemclear(&qcOut->qcElement[el]->extension, (1)*sizeof(QC_OUT_EXTENSION));
755
756 for ( n = 0; n < MAX_TOTAL_EXT_PAYLOADS; n++ ) {
757 if ( !extPayloadUsed[n]
758 && (extPayload[n].associatedChElement == el)
759 && (extPayload[n].dataSize > 0)
760 && (extPayload[n].pData != NULL) )
761 {
762 int idx = qcOut->qcElement[el]->nExtensions++;
763
764 qcOut->qcElement[el]->extension[idx].type = extPayload[n].dataType; /* Perform a sanity check on the type? */
765 qcOut->qcElement[el]->extension[idx].nPayloadBits = extPayload[n].dataSize;
766 qcOut->qcElement[el]->extension[idx].pPayload = extPayload[n].pData;
767 /* Now ask the bitstream encoder how many bits we need to encode the data with the current bitstream syntax: */
768 qcOut->qcElement[el]->extBitsUsed +=
769 FDKaacEnc_writeExtensionData( NULL,
770 &qcOut->qcElement[el]->extension[idx],
771 0, 0,
772 hAacEnc->config->syntaxFlags,
773 hAacEnc->aot,
774 hAacEnc->config->epConfig );
775 extPayloadUsed[n] = 1;
776 }
777 }
778
779 /* sum up extension and static bits for all channel elements */
780 qcOut->elementExtBits += qcOut->qcElement[el]->extBitsUsed;
781 qcOut->staticBits += qcOut->qcElement[el]->staticBitsUsed;
782
783 /* sum up pe */
784 qcOut->totalNoRedPe += qcOut->qcElement[el]->peData.pe;
785 }
786 }
787
788 qcOut->nExtensions = 0;
789 qcOut->globalExtBits = 0;
790
791 /* reset extension payload */
792 FDKmemclear(&qcOut->extension, (2+2)*sizeof(QC_OUT_EXTENSION));
793
794 /* Add extension payload not assigned to an channel element
795 (Ancillary data is the only supported type up to now) */
796 for ( n = 0; n < MAX_TOTAL_EXT_PAYLOADS; n++ ) {
797 if ( !extPayloadUsed[n]
798 && (extPayload[n].associatedChElement == -1)
799 && (extPayload[n].pData != NULL) )
800 {
801 UINT payloadBits = 0;
802
803 if (extPayload[n].dataType == EXT_DATA_ELEMENT) {
804 if (hAacEnc->ancillaryBitsPerFrame) {
805 /* granted frame dse bitrate */
806 payloadBits = hAacEnc->ancillaryBitsPerFrame;
807 }
808 else {
809 /* write anc data if bitrate constraint fulfilled */
810 if ((extPayload[n].dataSize>>3) <= hAacEnc->config->maxAncBytesPerAU) {
811 payloadBits = extPayload[n].dataSize;
812 }
813 }
814 payloadBits = fixMin( extPayload[n].dataSize, payloadBits );
815 } else {
816 payloadBits = extPayload[n].dataSize;
817 }
818
819 if (payloadBits > 0)
820 {
821 int idx = qcOut->nExtensions++;
822
823 qcOut->extension[idx].type = extPayload[n].dataType; /* Perform a sanity check on the type? */
824 qcOut->extension[idx].nPayloadBits = payloadBits;
825 qcOut->extension[idx].pPayload = extPayload[n].pData;
826 /* Now ask the bitstream encoder how many bits we need to encode the data with the current bitstream syntax: */
827 qcOut->globalExtBits += FDKaacEnc_writeExtensionData( NULL,
828 &qcOut->extension[idx],
829 0, 0,
830 hAacEnc->config->syntaxFlags,
831 hAacEnc->aot,
832 hAacEnc->config->epConfig );
833 if (extPayload[n].dataType == EXT_DATA_ELEMENT) {
834 /* substract the processed bits */
835 extPayload[n].dataSize -= payloadBits;
836 }
837 extPayloadUsed[n] = 1;
838 }
839 }
840 }
841
842 if (!(hAacEnc->config->syntaxFlags & (AC_SCALABLE|AC_ER))) {
843 qcOut->globalExtBits += EL_ID_BITS; /* add bits for ID_END */
844 }
845
846 /* build bitstream all nSubFrames */
847 {
848 INT totalBits = 0; /* Total AU bits */;
849 INT avgTotalBits = 0;
850
851 /*-------------------------------------------- */
852 /* Get average total bits */
853 /*-------------------------------------------- */
854 {
855 /* frame wise bitrate adaption */
856 FDKaacEnc_AdjustBitrate(hAacEnc->qcKernel,
857 cm,
858 &avgTotalBits,
859 hAacEnc->config->bitRate,
860 hAacEnc->config->sampleRate,
861 hAacEnc->config->framelength);
862
863 /* adjust super frame bitrate */
864 avgTotalBits *= hAacEnc->config->nSubFrames;
865 }
866
867 /* Make first estimate of transport header overhead.
868 Take maximum possible frame size into account to prevent bitreservoir underrun. */
869 hAacEnc->qcKernel->globHdrBits = transportEnc_GetStaticBits(hTpEnc, avgTotalBits + hAacEnc->qcKernel->bitResTot);
870
871
872 /*-------------------------------------------- */
873 /*-------------------------------------------- */
874 /*-------------------------------------------- */
875
876 ErrorStatus = FDKaacEnc_QCMain(hAacEnc->qcKernel,
877 hAacEnc->psyOut,
878 hAacEnc->qcOut,
879 avgTotalBits,
880 cm
881 ,hAacEnc->aot,
882 hAacEnc->config->syntaxFlags,
883 hAacEnc->config->epConfig);
884
885 if (ErrorStatus != AAC_ENC_OK)
886 return ErrorStatus;
887 /*-------------------------------------------- */
888
889 /*-------------------------------------------- */
890 ErrorStatus = FDKaacEnc_updateFillBits(cm,
891 hAacEnc->qcKernel,
892 hAacEnc->qcKernel->elementBits,
893 hAacEnc->qcOut);
894 if (ErrorStatus != AAC_ENC_OK)
895 return ErrorStatus;
896
897 /*-------------------------------------------- */
898 ErrorStatus = FDKaacEnc_FinalizeBitConsumption(cm,
899 hAacEnc->qcKernel,
900 qcOut,
901 qcOut->qcElement,
902 hTpEnc,
903 hAacEnc->aot,
904 hAacEnc->config->syntaxFlags,
905 hAacEnc->config->epConfig);
906 if (ErrorStatus != AAC_ENC_OK)
907 return ErrorStatus;
908 /*-------------------------------------------- */
909 totalBits += qcOut->totalBits;
910
911
912 /*-------------------------------------------- */
913 FDKaacEnc_updateBitres(cm,
914 hAacEnc->qcKernel,
915 hAacEnc->qcOut);
916
917 /*-------------------------------------------- */
918
919 /* for ( all sub frames ) ... */
920 /* write bitstream header */
921 transportEnc_WriteAccessUnit(
922 hTpEnc,
923 totalBits,
924 FDKaacEnc_EncBitresToTpBitres(hAacEnc->bitrateMode, hAacEnc->qcKernel->bitResTot),
925 cm->nChannelsEff);
926
927 /* write bitstream */
928 ErrorStatus = FDKaacEnc_WriteBitstream(
929 hTpEnc,
930 cm,
931 qcOut,
932 psyOut,
933 hAacEnc->qcKernel,
934 hAacEnc->aot,
935 hAacEnc->config->syntaxFlags,
936 hAacEnc->config->epConfig);
937
938 if (ErrorStatus != AAC_ENC_OK)
939 return ErrorStatus;
940
941 /* transportEnc_EndAccessUnit() is being called inside FDKaacEnc_WriteBitstream() */
942 transportEnc_GetFrame(hTpEnc, nOutBytes);
943
944 } /* -end- if (curFrame==hAacEnc->qcKernel->nSubFrames) */
945
946
947 /*-------------------------------------------- */
948 return AAC_ENC_OK;
949 }
950
951 /*---------------------------------------------------------------------------
952
953 functionname:FDKaacEnc_Close
954 description: delete encoder instance
955 returns:
956
957 ---------------------------------------------------------------------------*/
958
FDKaacEnc_Close(HANDLE_AAC_ENC * phAacEnc)959 void FDKaacEnc_Close( HANDLE_AAC_ENC* phAacEnc) /* encoder handle */
960 {
961 if (*phAacEnc == NULL) {
962 return;
963 }
964 AAC_ENC *hAacEnc = (AAC_ENC*)*phAacEnc;
965
966 if (hAacEnc->dynamic_RAM != NULL)
967 FreeAACdynamic_RAM(&hAacEnc->dynamic_RAM);
968
969 FDKaacEnc_PsyClose(&hAacEnc->psyKernel,hAacEnc->psyOut);
970
971 FDKaacEnc_QCClose(&hAacEnc->qcKernel, hAacEnc->qcOut);
972
973 FreeRam_aacEnc_AacEncoder(phAacEnc);
974 }
975
976
977 /* The following functions are in this source file only for convenience and */
978 /* need not be visible outside of a possible encoder library. */
979
980 /* basic defines for ancillary data */
981 #define MAX_ANCRATE 19200 /* ancillary rate >= 19200 isn't valid */
982
983 /*---------------------------------------------------------------------------
984
985 functionname: FDKaacEnc_InitCheckAncillary
986 description: initialize and check ancillary data struct
987 return: if success or NULL if error
988
989 ---------------------------------------------------------------------------*/
FDKaacEnc_InitCheckAncillary(INT bitRate,INT framelength,INT ancillaryRate,INT * ancillaryBitsPerFrame,INT sampleRate)990 static AAC_ENCODER_ERROR FDKaacEnc_InitCheckAncillary(INT bitRate,
991 INT framelength,
992 INT ancillaryRate,
993 INT *ancillaryBitsPerFrame,
994 INT sampleRate)
995 {
996 INT diffToByteAlign;
997
998 /* don't use negative ancillary rates */
999 if ( ancillaryRate < -1 )
1000 return AAC_ENC_UNSUPPORTED_ANC_BITRATE;
1001
1002 /* check if ancillary rate is ok */
1003 if ( (ancillaryRate != (-1)) && (ancillaryRate != 0) ) {
1004 /* ancRate <= 15% of bitrate && ancRate < 19200 */
1005 if ( ( ancillaryRate >= MAX_ANCRATE ) ||
1006 ( (ancillaryRate * 20) > (bitRate * 3) ) ) {
1007 return AAC_ENC_UNSUPPORTED_ANC_BITRATE;
1008 }
1009 }
1010 else if (ancillaryRate == -1) {
1011 /* if no special ancRate is requested but a ancillary file is
1012 stated, then generate a ancillary rate matching to the bitrate */
1013 if (bitRate >= (MAX_ANCRATE * 10)) {
1014 /* ancillary rate is 19199 */
1015 ancillaryRate = (MAX_ANCRATE - 1);
1016 }
1017 else { /* 10% of bitrate */
1018 ancillaryRate = bitRate / 10;
1019 }
1020 }
1021
1022 /* make ancillaryBitsPerFrame byte align */
1023 *ancillaryBitsPerFrame = (ancillaryRate * framelength ) / sampleRate;
1024 diffToByteAlign = *ancillaryBitsPerFrame % 8;
1025 *ancillaryBitsPerFrame = *ancillaryBitsPerFrame - diffToByteAlign;
1026
1027 return AAC_ENC_OK;
1028 }
1029