1 /* -----------------------------------------------------------------------------
2 Software License for The Fraunhofer FDK AAC Codec Library for Android
3
4 © Copyright 1995 - 2019 Fraunhofer-Gesellschaft zur Förderung der angewandten
5 Forschung e.V. All rights reserved.
6
7 1. INTRODUCTION
8 The Fraunhofer FDK AAC Codec Library for Android ("FDK AAC Codec") is software
9 that implements the MPEG Advanced Audio Coding ("AAC") encoding and decoding
10 scheme for digital audio. This FDK AAC Codec software is intended to be used on
11 a wide variety of Android devices.
12
13 AAC's HE-AAC and HE-AAC v2 versions are regarded as today's most efficient
14 general perceptual audio codecs. AAC-ELD is considered the best-performing
15 full-bandwidth communications codec by independent studies and is widely
16 deployed. AAC has been standardized by ISO and IEC as part of the MPEG
17 specifications.
18
19 Patent licenses for necessary patent claims for the FDK AAC Codec (including
20 those of Fraunhofer) may be obtained through Via Licensing
21 (www.vialicensing.com) or through the respective patent owners individually for
22 the purpose of encoding or decoding bit streams in products that are compliant
23 with the ISO/IEC MPEG audio standards. Please note that most manufacturers of
24 Android devices already license these patent claims through Via Licensing or
25 directly from the patent owners, and therefore FDK AAC Codec software may
26 already be covered under those patent licenses when it is used for those
27 licensed purposes only.
28
29 Commercially-licensed AAC software libraries, including floating-point versions
30 with enhanced sound quality, are also available from Fraunhofer. Users are
31 encouraged to check the Fraunhofer website for additional applications
32 information and documentation.
33
34 2. COPYRIGHT LICENSE
35
36 Redistribution and use in source and binary forms, with or without modification,
37 are permitted without payment of copyright license fees provided that you
38 satisfy the following conditions:
39
40 You must retain the complete text of this software license in redistributions of
41 the FDK AAC Codec or your modifications thereto in source code form.
42
43 You must retain the complete text of this software license in the documentation
44 and/or other materials provided with redistributions of the FDK AAC Codec or
45 your modifications thereto in binary form. You must make available free of
46 charge copies of the complete source code of the FDK AAC Codec and your
47 modifications thereto to recipients of copies in binary form.
48
49 The name of Fraunhofer may not be used to endorse or promote products derived
50 from this library without prior written permission.
51
52 You may not charge copyright license fees for anyone to use, copy or distribute
53 the FDK AAC Codec software or your modifications thereto.
54
55 Your modified versions of the FDK AAC Codec must carry prominent notices stating
56 that you changed the software and the date of any change. For modified versions
57 of the FDK AAC Codec, the term "Fraunhofer FDK AAC Codec Library for Android"
58 must be replaced by the term "Third-Party Modified Version of the Fraunhofer FDK
59 AAC Codec Library for Android."
60
61 3. NO PATENT LICENSE
62
63 NO EXPRESS OR IMPLIED LICENSES TO ANY PATENT CLAIMS, including without
64 limitation the patents of Fraunhofer, ARE GRANTED BY THIS SOFTWARE LICENSE.
65 Fraunhofer provides no warranty of patent non-infringement with respect to this
66 software.
67
68 You may use this FDK AAC Codec software or modifications thereto only for
69 purposes that are authorized by appropriate patent licenses.
70
71 4. DISCLAIMER
72
73 This FDK AAC Codec software is provided by Fraunhofer on behalf of the copyright
74 holders and contributors "AS IS" and WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES,
75 including but not limited to the implied warranties of merchantability and
76 fitness for a particular purpose. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
77 CONTRIBUTORS BE LIABLE for any direct, indirect, incidental, special, exemplary,
78 or consequential damages, including but not limited to procurement of substitute
79 goods or services; loss of use, data, or profits, or business interruption,
80 however caused and on any theory of liability, whether in contract, strict
81 liability, or tort (including negligence), arising in any way out of the use of
82 this software, even if advised of the possibility of such damage.
83
84 5. CONTACT INFORMATION
85
86 Fraunhofer Institute for Integrated Circuits IIS
87 Attention: Audio and Multimedia Departments - FDK AAC LL
88 Am Wolfsmantel 33
89 91058 Erlangen, Germany
90
91 www.iis.fraunhofer.de/amm
92 amm-info@iis.fraunhofer.de
93 ----------------------------------------------------------------------------- */
94
95 /**************************** AAC decoder library ******************************
96
97 Author(s): Christian Griebel
98
99 Description: Dynamic range control (DRC) decoder tool for AAC
100
101 *******************************************************************************/
102
103 #include "aacdec_drc.h"
104
105 #include "channelinfo.h"
106 #include "aac_rom.h"
107
108 #include "sbrdecoder.h"
109
110 /*
111 * Dynamic Range Control
112 */
113
114 /* For parameter conversion */
115 #define DRC_PARAMETER_BITS (7)
116 #define DRC_MAX_QUANT_STEPS (1 << DRC_PARAMETER_BITS)
117 #define DRC_MAX_QUANT_FACTOR (DRC_MAX_QUANT_STEPS - 1)
118 #define DRC_PARAM_QUANT_STEP \
119 (FL2FXCONST_DBL(1.0f / (float)DRC_MAX_QUANT_FACTOR))
120 #define DRC_PARAM_SCALE (1)
121 #define DRC_SCALING_MAX \
122 ((FIXP_DBL)((INT)(DRC_PARAM_QUANT_STEP >> DRC_PARAM_SCALE) * (INT)127))
123
124 #define DRC_BLOCK_LEN (1024)
125 #define DRC_BAND_MULT (4)
126 #define DRC_BLOCK_LEN_DIV_BAND_MULT (DRC_BLOCK_LEN / DRC_BAND_MULT)
127
128 #define MAX_REFERENCE_LEVEL (127)
129
130 #define DRC_HEAVY_THRESHOLD_DB (10)
131
132 #define DVB_ANC_DATA_SYNC_BYTE (0xBC) /* DVB ancillary data sync byte. */
133
134 #define OFF 0
135 #define ON 1
136
convert_drcParam(FIXP_DBL param_dbl)137 static INT convert_drcParam(FIXP_DBL param_dbl) {
138 /* converts an internal DRC boost/cut scaling factor in FIXP_DBL
139 (which is downscaled by DRC_PARAM_SCALE)
140 back to an integer value between 0 and 127. */
141 LONG param_long;
142
143 param_long = (LONG)param_dbl >> 7;
144 param_long = param_long * (INT)DRC_MAX_QUANT_FACTOR;
145 param_long >>= 31 - 7 - DRC_PARAM_SCALE - 1;
146 param_long += 1; /* for rounding */
147 param_long >>= 1;
148
149 return (INT)param_long;
150 }
151
152 /*!
153 \brief Reset DRC information
154
155 \self Handle of DRC info
156
157 \return none
158 */
aacDecoder_drcReset(HANDLE_AAC_DRC self)159 void aacDecoder_drcReset(HANDLE_AAC_DRC self) {
160 self->applyExtGain = 0;
161 self->additionalGainPrev = AACDEC_DRC_GAIN_INIT_VALUE;
162 self->additionalGainFilterState = AACDEC_DRC_GAIN_INIT_VALUE;
163 self->additionalGainFilterState1 = AACDEC_DRC_GAIN_INIT_VALUE;
164 }
165
166 /*!
167 \brief Initialize DRC information
168
169 \self Handle of DRC info
170
171 \return none
172 */
aacDecoder_drcInit(HANDLE_AAC_DRC self)173 void aacDecoder_drcInit(HANDLE_AAC_DRC self) {
174 CDrcParams *pParams;
175
176 if (self == NULL) {
177 return;
178 }
179
180 /* init control fields */
181 self->enable = OFF;
182 self->numThreads = 0;
183
184 /* init params */
185 pParams = &self->params;
186 pParams->bsDelayEnable = 0;
187 pParams->cut = FL2FXCONST_DBL(0.0f);
188 pParams->usrCut = FL2FXCONST_DBL(0.0f);
189 pParams->boost = FL2FXCONST_DBL(0.0f);
190 pParams->usrBoost = FL2FXCONST_DBL(0.0f);
191 pParams->targetRefLevel = 96;
192 pParams->expiryFrame = AACDEC_DRC_DFLT_EXPIRY_FRAMES;
193 pParams->applyHeavyCompression = OFF;
194 pParams->usrApplyHeavyCompression = OFF;
195
196 pParams->defaultPresentationMode = DISABLED_PARAMETER_HANDLING;
197 pParams->encoderTargetLevel = MAX_REFERENCE_LEVEL; /* worst case assumption */
198
199 self->update = 1;
200 self->numOutChannels = 0;
201 self->prevAacNumChannels = 0;
202
203 /* initial program ref level = target ref level */
204 self->progRefLevel = pParams->targetRefLevel;
205 self->progRefLevelPresent = 0;
206 self->presMode = -1;
207 self->uniDrcPrecedence = 0;
208
209 aacDecoder_drcReset(self);
210 }
211
212 /*!
213 \brief Initialize DRC control data for one channel
214
215 \self Handle of DRC info
216
217 \return none
218 */
aacDecoder_drcInitChannelData(CDrcChannelData * pDrcChData)219 void aacDecoder_drcInitChannelData(CDrcChannelData *pDrcChData) {
220 if (pDrcChData != NULL) {
221 pDrcChData->expiryCount = 0;
222 pDrcChData->numBands = 1;
223 pDrcChData->bandTop[0] = DRC_BLOCK_LEN_DIV_BAND_MULT - 1;
224 pDrcChData->drcValue[0] = 0;
225 pDrcChData->drcInterpolationScheme = 0;
226 pDrcChData->drcDataType = UNKNOWN_PAYLOAD;
227 }
228 }
229
230 /*!
231 \brief Set one single DRC parameter
232
233 \self Handle of DRC info.
234 \param Parameter to be set.
235 \value Value to be set.
236
237 \return an error code.
238 */
aacDecoder_drcSetParam(HANDLE_AAC_DRC self,AACDEC_DRC_PARAM param,INT value)239 AAC_DECODER_ERROR aacDecoder_drcSetParam(HANDLE_AAC_DRC self,
240 AACDEC_DRC_PARAM param, INT value) {
241 AAC_DECODER_ERROR ErrorStatus = AAC_DEC_OK;
242
243 switch (param) {
244 case DRC_CUT_SCALE:
245 /* set attenuation scale factor */
246 if ((value < 0) || (value > DRC_MAX_QUANT_FACTOR)) {
247 return AAC_DEC_SET_PARAM_FAIL;
248 }
249 if (self == NULL) {
250 return AAC_DEC_INVALID_HANDLE;
251 }
252 self->params.usrCut = (FIXP_DBL)(
253 (INT)(DRC_PARAM_QUANT_STEP >> DRC_PARAM_SCALE) * (INT)value);
254 self->update = 1;
255 break;
256 case DRC_BOOST_SCALE:
257 /* set boost factor */
258 if ((value < 0) || (value > DRC_MAX_QUANT_FACTOR)) {
259 return AAC_DEC_SET_PARAM_FAIL;
260 }
261 if (self == NULL) {
262 return AAC_DEC_INVALID_HANDLE;
263 }
264 self->params.usrBoost = (FIXP_DBL)(
265 (INT)(DRC_PARAM_QUANT_STEP >> DRC_PARAM_SCALE) * (INT)value);
266 self->update = 1;
267 break;
268 case TARGET_REF_LEVEL:
269 if (value > MAX_REFERENCE_LEVEL || value < -MAX_REFERENCE_LEVEL) {
270 return AAC_DEC_SET_PARAM_FAIL;
271 }
272 if (self == NULL) {
273 return AAC_DEC_INVALID_HANDLE;
274 }
275 if (value < 0) {
276 self->params.targetRefLevel = -1;
277 } else {
278 if (self->params.targetRefLevel != (SCHAR)value) {
279 self->params.targetRefLevel = (SCHAR)value;
280 self->progRefLevel = (SCHAR)value; /* Always set the program reference
281 level equal to the target level
282 according to 4.5.2.7.3 of
283 ISO/IEC 14496-3. */
284 }
285 self->update = 1;
286 }
287 break;
288 case APPLY_HEAVY_COMPRESSION:
289 if ((value != OFF) && (value != ON)) {
290 return AAC_DEC_SET_PARAM_FAIL;
291 }
292 if (self == NULL) {
293 return AAC_DEC_INVALID_HANDLE;
294 }
295 /* Store new parameter value */
296 self->params.usrApplyHeavyCompression = (UCHAR)value;
297 self->update = 1;
298 break;
299 case DEFAULT_PRESENTATION_MODE:
300 if (value < AAC_DRC_PARAMETER_HANDLING_DISABLED ||
301 value > AAC_DRC_PRESENTATION_MODE_2_DEFAULT) {
302 return AAC_DEC_SET_PARAM_FAIL;
303 }
304 if (self == NULL) {
305 return AAC_DEC_INVALID_HANDLE;
306 }
307 self->params.defaultPresentationMode =
308 (AACDEC_DRC_PARAMETER_HANDLING)value;
309 self->update = 1;
310 break;
311 case ENCODER_TARGET_LEVEL:
312 if (value > MAX_REFERENCE_LEVEL || value < 0) {
313 return AAC_DEC_SET_PARAM_FAIL;
314 }
315 if (self == NULL) {
316 return AAC_DEC_INVALID_HANDLE;
317 }
318 self->params.encoderTargetLevel = (UCHAR)value;
319 self->update = 1;
320 break;
321 case DRC_BS_DELAY:
322 if (value < 0 || value > 1) {
323 return AAC_DEC_SET_PARAM_FAIL;
324 }
325 if (self == NULL) {
326 return AAC_DEC_INVALID_HANDLE;
327 }
328 self->params.bsDelayEnable = value;
329 break;
330 case DRC_DATA_EXPIRY_FRAME:
331 if (self == NULL) {
332 return AAC_DEC_INVALID_HANDLE;
333 }
334 self->params.expiryFrame = (value > 0) ? (UINT)value : 0;
335 break;
336 case MAX_OUTPUT_CHANNELS:
337 if (self == NULL) {
338 return AAC_DEC_INVALID_HANDLE;
339 }
340 self->numOutChannels = (INT)value;
341 self->update = 1;
342 break;
343 case UNIDRC_PRECEDENCE:
344 if (self == NULL) {
345 return AAC_DEC_INVALID_HANDLE;
346 }
347 self->uniDrcPrecedence = (UCHAR)value;
348 break;
349 default:
350 return AAC_DEC_SET_PARAM_FAIL;
351 } /* switch(param) */
352
353 return ErrorStatus;
354 }
355
parseExcludedChannels(UINT * excludedChnsMask,HANDLE_FDK_BITSTREAM bs)356 static int parseExcludedChannels(UINT *excludedChnsMask,
357 HANDLE_FDK_BITSTREAM bs) {
358 UINT excludeMask = 0;
359 UINT i, j;
360 int bitCnt = 9;
361
362 for (i = 0, j = 1; i < 7; i++, j <<= 1) {
363 if (FDKreadBits(bs, 1)) {
364 excludeMask |= j;
365 }
366 }
367
368 /* additional_excluded_chns */
369 while (FDKreadBits(bs, 1)) {
370 for (i = 0; i < 7; i++, j <<= 1) {
371 if (FDKreadBits(bs, 1)) {
372 excludeMask |= j;
373 }
374 }
375 bitCnt += 9;
376 FDK_ASSERT(j < (UINT)-1);
377 }
378
379 *excludedChnsMask = excludeMask;
380
381 return (bitCnt);
382 }
383
384 /*!
385 \brief Save DRC payload bitstream position
386
387 \self Handle of DRC info
388 \bs Handle of FDK bitstream
389
390 \return The number of DRC payload bits
391 */
aacDecoder_drcMarkPayload(HANDLE_AAC_DRC self,HANDLE_FDK_BITSTREAM bs,AACDEC_DRC_PAYLOAD_TYPE type)392 int aacDecoder_drcMarkPayload(HANDLE_AAC_DRC self, HANDLE_FDK_BITSTREAM bs,
393 AACDEC_DRC_PAYLOAD_TYPE type) {
394 UINT bsStartPos;
395 int i, numBands = 1, bitCnt = 0;
396
397 if (self == NULL) {
398 return 0;
399 }
400
401 bsStartPos = FDKgetValidBits(bs);
402
403 switch (type) {
404 case MPEG_DRC_EXT_DATA: {
405 bitCnt = 4;
406
407 if (FDKreadBits(bs, 1)) { /* pce_tag_present */
408 FDKreadBits(bs, 8); /* pce_instance_tag + drc_tag_reserved_bits */
409 bitCnt += 8;
410 }
411
412 if (FDKreadBits(bs, 1)) { /* excluded_chns_present */
413 FDKreadBits(bs, 7); /* exclude mask [0..7] */
414 bitCnt += 8;
415 while (FDKreadBits(bs, 1)) { /* additional_excluded_chns */
416 FDKreadBits(bs, 7); /* exclude mask [x..y] */
417 bitCnt += 8;
418 }
419 }
420
421 if (FDKreadBits(bs, 1)) { /* drc_bands_present */
422 numBands += FDKreadBits(bs, 4); /* drc_band_incr */
423 FDKreadBits(bs, 4); /* reserved */
424 bitCnt += 8;
425 for (i = 0; i < numBands; i++) {
426 FDKreadBits(bs, 8); /* drc_band_top[i] */
427 bitCnt += 8;
428 }
429 }
430
431 if (FDKreadBits(bs, 1)) { /* prog_ref_level_present */
432 FDKreadBits(bs, 8); /* prog_ref_level + prog_ref_level_reserved_bits */
433 bitCnt += 8;
434 }
435
436 for (i = 0; i < numBands; i++) {
437 FDKreadBits(bs, 8); /* dyn_rng_sgn[i] + dyn_rng_ctl[i] */
438 bitCnt += 8;
439 }
440
441 if ((self->numPayloads < MAX_DRC_THREADS) &&
442 ((INT)FDKgetValidBits(bs) >= 0)) {
443 self->drcPayloadPosition[self->numPayloads++] = bsStartPos;
444 }
445 } break;
446
447 case DVB_DRC_ANC_DATA:
448 bitCnt += 8;
449 /* check sync word */
450 if (FDKreadBits(bs, 8) == DVB_ANC_DATA_SYNC_BYTE) {
451 int dmxLevelsPresent, compressionPresent;
452 int coarseGrainTcPresent, fineGrainTcPresent;
453
454 /* bs_info field */
455 FDKreadBits(
456 bs,
457 8); /* mpeg_audio_type, dolby_surround_mode, presentation_mode */
458 bitCnt += 8;
459
460 /* Evaluate ancillary_data_status */
461 FDKreadBits(bs, 3); /* reserved, set to 0 */
462 dmxLevelsPresent =
463 FDKreadBits(bs, 1); /* downmixing_levels_MPEG4_status */
464 FDKreadBits(bs, 1); /* reserved, set to 0 */
465 compressionPresent =
466 FDKreadBits(bs, 1); /* audio_coding_mode_and_compression status */
467 coarseGrainTcPresent =
468 FDKreadBits(bs, 1); /* coarse_grain_timecode_status */
469 fineGrainTcPresent =
470 FDKreadBits(bs, 1); /* fine_grain_timecode_status */
471 bitCnt += 8;
472
473 /* MPEG4 downmixing levels */
474 if (dmxLevelsPresent) {
475 FDKreadBits(bs, 8); /* downmixing_levels_MPEG4 */
476 bitCnt += 8;
477 }
478 /* audio coding mode and compression status */
479 if (compressionPresent) {
480 FDKreadBits(bs, 16); /* audio_coding_mode, Compression_value */
481 bitCnt += 16;
482 }
483 /* coarse grain timecode */
484 if (coarseGrainTcPresent) {
485 FDKreadBits(bs, 16); /* coarse_grain_timecode */
486 bitCnt += 16;
487 }
488 /* fine grain timecode */
489 if (fineGrainTcPresent) {
490 FDKreadBits(bs, 16); /* fine_grain_timecode */
491 bitCnt += 16;
492 }
493 if (!self->dvbAncDataAvailable && ((INT)FDKgetValidBits(bs) >= 0)) {
494 self->dvbAncDataPosition = bsStartPos;
495 self->dvbAncDataAvailable = 1;
496 }
497 }
498 break;
499
500 default:
501 break;
502 }
503
504 return (bitCnt);
505 }
506
507 /*!
508 \brief Parse DRC parameters from bitstream
509
510 \bs Handle of FDK bitstream (in)
511 \pDrcBs Pointer to DRC payload data container (out)
512 \payloadPosition Bitstream position of MPEG DRC data chunk (in)
513
514 \return Flag telling whether new DRC data has been found or not.
515 */
aacDecoder_drcParse(HANDLE_FDK_BITSTREAM bs,CDrcPayload * pDrcBs,UINT payloadPosition)516 static int aacDecoder_drcParse(HANDLE_FDK_BITSTREAM bs, CDrcPayload *pDrcBs,
517 UINT payloadPosition) {
518 int i, numBands;
519
520 /* Move to the beginning of the DRC payload field */
521 FDKpushBiDirectional(bs, (INT)FDKgetValidBits(bs) - (INT)payloadPosition);
522
523 /* pce_tag_present */
524 if (FDKreadBits(bs, 1)) {
525 pDrcBs->pceInstanceTag = FDKreadBits(bs, 4); /* pce_instance_tag */
526 /* only one program supported */
527 FDKreadBits(bs, 4); /* drc_tag_reserved_bits */
528 } else {
529 pDrcBs->pceInstanceTag = -1; /* not present */
530 }
531
532 if (FDKreadBits(bs, 1)) { /* excluded_chns_present */
533 /* get excluded_chn_mask */
534 parseExcludedChannels(&pDrcBs->excludedChnsMask, bs);
535 } else {
536 pDrcBs->excludedChnsMask = 0;
537 }
538
539 numBands = 1;
540 if (FDKreadBits(bs, 1)) /* drc_bands_present */
541 {
542 /* get band_incr */
543 numBands += FDKreadBits(bs, 4); /* drc_band_incr */
544 pDrcBs->channelData.drcInterpolationScheme =
545 FDKreadBits(bs, 4); /* drc_interpolation_scheme */
546 /* band_top */
547 for (i = 0; i < numBands; i++) {
548 pDrcBs->channelData.bandTop[i] = FDKreadBits(bs, 8); /* drc_band_top[i] */
549 }
550 } else {
551 pDrcBs->channelData.bandTop[0] = DRC_BLOCK_LEN_DIV_BAND_MULT -
552 1; /* ... comprising the whole spectrum. */
553 ;
554 }
555
556 pDrcBs->channelData.numBands = numBands;
557
558 if (FDKreadBits(bs, 1)) /* prog_ref_level_present */
559 {
560 pDrcBs->progRefLevel = FDKreadBits(bs, 7); /* prog_ref_level */
561 FDKreadBits(bs, 1); /* prog_ref_level_reserved_bits */
562 } else {
563 pDrcBs->progRefLevel = -1;
564 }
565
566 for (i = 0; i < numBands; i++) {
567 pDrcBs->channelData.drcValue[i] = FDKreadBits(bs, 1)
568 << 7; /* dyn_rng_sgn[i] */
569 pDrcBs->channelData.drcValue[i] |=
570 FDKreadBits(bs, 7) & 0x7F; /* dyn_rng_ctl[i] */
571 }
572
573 /* Set DRC payload type */
574 pDrcBs->channelData.drcDataType = MPEG_DRC_EXT_DATA;
575
576 return (1);
577 }
578
579 /*!
580 \brief Parse heavy compression value transported in DSEs of DVB streams with
581 MPEG-4 content.
582
583 \bs Handle of FDK bitstream (in)
584 \pDrcBs Pointer to DRC payload data container (out)
585 \payloadPosition Bitstream position of DVB ancillary data chunk
586
587 \return Flag telling whether new DRC data has been found or not.
588 */
589 #define DVB_COMPRESSION_SCALE (8) /* 48,164 dB */
590
aacDecoder_drcReadCompression(HANDLE_FDK_BITSTREAM bs,CDrcPayload * pDrcBs,UINT payloadPosition)591 static int aacDecoder_drcReadCompression(HANDLE_FDK_BITSTREAM bs,
592 CDrcPayload *pDrcBs,
593 UINT payloadPosition) {
594 int foundDrcData = 0;
595 int dmxLevelsPresent, compressionPresent;
596
597 /* Move to the beginning of the DRC payload field */
598 FDKpushBiDirectional(bs, (INT)FDKgetValidBits(bs) - (INT)payloadPosition);
599
600 /* Sanity checks */
601 if (FDKgetValidBits(bs) < 24) {
602 return 0;
603 }
604
605 /* Check sync word */
606 if (FDKreadBits(bs, 8) != DVB_ANC_DATA_SYNC_BYTE) {
607 return 0;
608 }
609
610 /* Evaluate bs_info field */
611 if (FDKreadBits(bs, 2) != 3) { /* mpeg_audio_type */
612 /* No MPEG-4 audio data */
613 return 0;
614 }
615 FDKreadBits(bs, 2); /* dolby_surround_mode */
616 pDrcBs->presMode = FDKreadBits(bs, 2); /* presentation_mode */
617 FDKreadBits(bs, 1); /* stereo_downmix_mode */
618 if (FDKreadBits(bs, 1) != 0) { /* reserved, set to 0 */
619 return 0;
620 }
621
622 /* Evaluate ancillary_data_status */
623 if (FDKreadBits(bs, 3) != 0) { /* reserved, set to 0 */
624 return 0;
625 }
626 dmxLevelsPresent = FDKreadBits(bs, 1); /* downmixing_levels_MPEG4_status */
627 /*extensionPresent =*/FDKreadBits(bs,
628 1); /* ancillary_data_extension_status; */
629 compressionPresent =
630 FDKreadBits(bs, 1); /* audio_coding_mode_and_compression status */
631 /*coarseGrainTcPresent =*/FDKreadBits(bs,
632 1); /* coarse_grain_timecode_status */
633 /*fineGrainTcPresent =*/FDKreadBits(bs, 1); /* fine_grain_timecode_status */
634
635 if (dmxLevelsPresent) {
636 FDKreadBits(bs, 8); /* downmixing_levels_MPEG4 */
637 }
638
639 /* audio_coding_mode_and_compression_status */
640 if (compressionPresent) {
641 UCHAR compressionOn, compressionValue;
642
643 /* audio_coding_mode */
644 if (FDKreadBits(bs, 7) != 0) { /* The reserved bits shall be set to "0". */
645 return 0;
646 }
647 compressionOn = (UCHAR)FDKreadBits(bs, 1); /* compression_on */
648 compressionValue = (UCHAR)FDKreadBits(bs, 8); /* Compression_value */
649
650 if (compressionOn) {
651 /* A compression value is available so store the data just like MPEG DRC
652 * data */
653 pDrcBs->channelData.numBands = 1; /* One band ... */
654 pDrcBs->channelData.drcValue[0] =
655 compressionValue; /* ... with one value ... */
656 pDrcBs->channelData.bandTop[0] =
657 DRC_BLOCK_LEN_DIV_BAND_MULT -
658 1; /* ... comprising the whole spectrum. */
659 ;
660 pDrcBs->pceInstanceTag = -1; /* Not present */
661 pDrcBs->progRefLevel = -1; /* Not present */
662 pDrcBs->channelData.drcDataType =
663 DVB_DRC_ANC_DATA; /* Set DRC payload type to DVB. */
664 foundDrcData = 1;
665 }
666 }
667
668 return (foundDrcData);
669 }
670
671 /*
672 * Extract DRC payload from bitstream and map it to channels.
673 * Valid return values are:
674 * -1 : An unexpected error occured.
675 * 0 : No error and no valid DRC data available.
676 * 1 : No error and valid DRC data has been mapped.
677 */
aacDecoder_drcExtractAndMap(HANDLE_AAC_DRC self,HANDLE_FDK_BITSTREAM hBs,CAacDecoderStaticChannelInfo * pAacDecoderStaticChannelInfo[],UCHAR pceInstanceTag,UCHAR channelMapping[],int validChannels)678 static int aacDecoder_drcExtractAndMap(
679 HANDLE_AAC_DRC self, HANDLE_FDK_BITSTREAM hBs,
680 CAacDecoderStaticChannelInfo *pAacDecoderStaticChannelInfo[],
681 UCHAR pceInstanceTag,
682 UCHAR channelMapping[], /* Channel mapping translating drcChannel index to
683 canonical channel index */
684 int validChannels) {
685 CDrcPayload threadBs[MAX_DRC_THREADS];
686 CDrcPayload *validThreadBs[MAX_DRC_THREADS];
687 CDrcParams *pParams;
688 UINT backupBsPosition;
689 int result = 0;
690 int i, thread, validThreads = 0;
691
692 FDK_ASSERT(self != NULL);
693 FDK_ASSERT(hBs != NULL);
694 FDK_ASSERT(pAacDecoderStaticChannelInfo != NULL);
695
696 pParams = &self->params;
697
698 self->numThreads = 0;
699 backupBsPosition = FDKgetValidBits(hBs);
700
701 for (i = 0; i < self->numPayloads && self->numThreads < MAX_DRC_THREADS;
702 i++) {
703 /* Init payload data chunk. The memclear is very important because it
704 initializes the most values. Without it the module wouldn't work properly
705 or crash. */
706 FDKmemclear(&threadBs[self->numThreads], sizeof(CDrcPayload));
707 threadBs[self->numThreads].channelData.bandTop[0] =
708 DRC_BLOCK_LEN_DIV_BAND_MULT - 1;
709
710 /* Extract payload */
711 self->numThreads += aacDecoder_drcParse(hBs, &threadBs[self->numThreads],
712 self->drcPayloadPosition[i]);
713 }
714 self->numPayloads = 0;
715
716 if (self->dvbAncDataAvailable &&
717 self->numThreads < MAX_DRC_THREADS) { /* Append a DVB heavy compression
718 payload thread if available. */
719
720 /* Init payload data chunk. The memclear is very important because it
721 initializes the most values. Without it the module wouldn't work properly
722 or crash. */
723 FDKmemclear(&threadBs[self->numThreads], sizeof(CDrcPayload));
724 threadBs[self->numThreads].channelData.bandTop[0] =
725 DRC_BLOCK_LEN_DIV_BAND_MULT - 1;
726
727 /* Extract payload */
728 self->numThreads += aacDecoder_drcReadCompression(
729 hBs, &threadBs[self->numThreads], self->dvbAncDataPosition);
730 }
731 self->dvbAncDataAvailable = 0;
732
733 /* Reset the bitbufffer */
734 FDKpushBiDirectional(hBs, (INT)FDKgetValidBits(hBs) - (INT)backupBsPosition);
735
736 /* calculate number of valid bits in excl_chn_mask */
737
738 /* coupling channels not supported */
739
740 /* check for valid threads */
741 for (thread = 0; thread < self->numThreads; thread++) {
742 CDrcPayload *pThreadBs = &threadBs[thread];
743 int numExclChns = 0;
744
745 switch ((AACDEC_DRC_PAYLOAD_TYPE)pThreadBs->channelData.drcDataType) {
746 default:
747 continue;
748 case MPEG_DRC_EXT_DATA:
749 case DVB_DRC_ANC_DATA:
750 break;
751 }
752
753 if (pThreadBs->pceInstanceTag >= 0) { /* if PCE tag present */
754 if (pThreadBs->pceInstanceTag != pceInstanceTag) {
755 continue; /* don't accept */
756 }
757 }
758
759 /* calculate number of excluded channels */
760 if (pThreadBs->excludedChnsMask > 0) {
761 INT exclMask = pThreadBs->excludedChnsMask;
762 int ch;
763 for (ch = 0; ch < validChannels; ch++) {
764 numExclChns += exclMask & 0x1;
765 exclMask >>= 1;
766 }
767 }
768 if (numExclChns < validChannels) {
769 validThreadBs[validThreads] = pThreadBs;
770 validThreads++;
771 }
772 }
773
774 /* map DRC bitstream information onto DRC channel information */
775 for (thread = 0; thread < validThreads; thread++) {
776 CDrcPayload *pThreadBs = validThreadBs[thread];
777 INT exclMask = pThreadBs->excludedChnsMask;
778 AACDEC_DRC_PAYLOAD_TYPE drcPayloadType =
779 (AACDEC_DRC_PAYLOAD_TYPE)pThreadBs->channelData.drcDataType;
780 int ch;
781
782 /* last progRefLevel transmitted is the one that is used
783 * (but it should really only be transmitted once per block!)
784 */
785 if (pThreadBs->progRefLevel >= 0) {
786 self->progRefLevel = pThreadBs->progRefLevel;
787 self->progRefLevelPresent = 1;
788 self->prlExpiryCount = 0; /* Got a new value -> Reset counter */
789 }
790
791 if (drcPayloadType == DVB_DRC_ANC_DATA) {
792 /* Announce the presentation mode of this valid thread. */
793 self->presMode = pThreadBs->presMode;
794 }
795
796 /* SCE, CPE and LFE */
797 for (ch = 0; ch < validChannels; ch++) {
798 AACDEC_DRC_PAYLOAD_TYPE prvPayloadType = UNKNOWN_PAYLOAD;
799 int mapedChannel = channelMapping[ch];
800
801 if ((mapedChannel >= validChannels) ||
802 ((exclMask & (1 << mapedChannel)) != 0))
803 continue;
804
805 if ((pParams->expiryFrame <= 0) ||
806 (pAacDecoderStaticChannelInfo[ch]->drcData.expiryCount <
807 pParams->expiryFrame)) {
808 prvPayloadType =
809 (AACDEC_DRC_PAYLOAD_TYPE)pAacDecoderStaticChannelInfo[ch]
810 ->drcData.drcDataType;
811 }
812 if (((drcPayloadType == MPEG_DRC_EXT_DATA) &&
813 (prvPayloadType != DVB_DRC_ANC_DATA)) ||
814 ((drcPayloadType == DVB_DRC_ANC_DATA) &&
815 (pParams->applyHeavyCompression ==
816 ON))) { /* copy thread to channel */
817 pAacDecoderStaticChannelInfo[ch]->drcData = pThreadBs->channelData;
818 result = 1;
819 }
820 }
821 /* CCEs not supported by now */
822 }
823
824 /* Increment and check expiry counter for the program reference level: */
825 if ((pParams->expiryFrame > 0) &&
826 (self->prlExpiryCount++ >
827 pParams->expiryFrame)) { /* The program reference level is too old, so
828 set it back to the target level. */
829 self->progRefLevelPresent = 0;
830 self->progRefLevel = pParams->targetRefLevel;
831 self->prlExpiryCount = 0;
832 }
833
834 return result;
835 }
836
aacDecoder_drcApply(HANDLE_AAC_DRC self,void * pSbrDec,CAacDecoderChannelInfo * pAacDecoderChannelInfo,CDrcChannelData * pDrcChData,FIXP_DBL * extGain,int ch,int aacFrameSize,int bSbrPresent)837 void aacDecoder_drcApply(HANDLE_AAC_DRC self, void *pSbrDec,
838 CAacDecoderChannelInfo *pAacDecoderChannelInfo,
839 CDrcChannelData *pDrcChData, FIXP_DBL *extGain,
840 int ch, /* needed only for SBR */
841 int aacFrameSize, int bSbrPresent) {
842 int band, bin, numBands;
843 int bottom = 0;
844 int modifyBins = 0;
845
846 FIXP_DBL max_mantissa;
847 INT max_exponent;
848
849 FIXP_DBL norm_mantissa = FL2FXCONST_DBL(0.5f);
850 INT norm_exponent = 1;
851
852 FIXP_DBL fact_mantissa[MAX_DRC_BANDS];
853 INT fact_exponent[MAX_DRC_BANDS];
854
855 CDrcParams *pParams = &self->params;
856
857 FIXP_DBL *pSpectralCoefficient =
858 SPEC_LONG(pAacDecoderChannelInfo->pSpectralCoefficient);
859 CIcsInfo *pIcsInfo = &pAacDecoderChannelInfo->icsInfo;
860 SHORT *pSpecScale = pAacDecoderChannelInfo->specScale;
861
862 int winSeq = pIcsInfo->WindowSequence;
863
864 /* Increment and check expiry counter */
865 if ((pParams->expiryFrame > 0) &&
866 (++pDrcChData->expiryCount >
867 pParams->expiryFrame)) { /* The DRC data is too old, so delete it. */
868 aacDecoder_drcInitChannelData(pDrcChData);
869 }
870
871 if (self->enable != ON) {
872 sbrDecoder_drcDisable((HANDLE_SBRDECODER)pSbrDec, ch);
873 if (extGain != NULL) {
874 INT gainScale = (INT)*extGain;
875 /* The gain scaling must be passed to the function in the buffer pointed
876 * on by extGain. */
877 if (gainScale >= 0 && gainScale <= DFRACT_BITS) {
878 *extGain = scaleValue(norm_mantissa, norm_exponent - gainScale);
879 } else {
880 FDK_ASSERT(0);
881 }
882 }
883 return;
884 }
885
886 numBands = pDrcChData->numBands;
887
888 /* If program reference normalization is done in the digital domain,
889 modify factor to perform normalization. prog_ref_level can
890 alternatively be passed to the system for modification of the level in
891 the analog domain. Analog level modification avoids problems with
892 reduced DAC SNR (if signal is attenuated) or clipping (if signal is
893 boosted) */
894
895 if (pParams->targetRefLevel >= 0) {
896 /* 0.5^((targetRefLevel - progRefLevel)/24) */
897 norm_mantissa =
898 fLdPow(FL2FXCONST_DBL(-1.0), /* log2(0.5) */
899 0,
900 (FIXP_DBL)((INT)(FL2FXCONST_DBL(1.0f / 24.0) >> 3) *
901 (INT)(pParams->targetRefLevel - self->progRefLevel)),
902 3, &norm_exponent);
903 }
904 /* Always export the normalization gain (if possible). */
905 if (extGain != NULL) {
906 INT gainScale = (INT)*extGain;
907 /* The gain scaling must be passed to the function in the buffer pointed on
908 * by extGain. */
909 if (gainScale >= 0 && gainScale <= DFRACT_BITS) {
910 *extGain = scaleValue(norm_mantissa, norm_exponent - gainScale);
911 } else {
912 FDK_ASSERT(0);
913 }
914 }
915 /* Reset normalization gain since this module must not apply it */
916 norm_mantissa = FL2FXCONST_DBL(0.5f);
917 norm_exponent = 1;
918
919 /* calc scale factors */
920 for (band = 0; band < numBands; band++) {
921 UCHAR drcVal = pDrcChData->drcValue[band];
922
923 fact_mantissa[band] = FL2FXCONST_DBL(0.5f);
924 fact_exponent[band] = 1;
925
926 if ((pParams->applyHeavyCompression == ON) &&
927 ((AACDEC_DRC_PAYLOAD_TYPE)pDrcChData->drcDataType ==
928 DVB_DRC_ANC_DATA)) {
929 INT compressionFactorVal_e;
930 int valX, valY;
931
932 valX = drcVal >> 4;
933 valY = drcVal & 0x0F;
934
935 /* calculate the unscaled heavy compression factor.
936 compressionFactor = 48.164 - 6.0206*valX - 0.4014*valY dB
937 range: -48.166 dB to 48.164 dB */
938 if (drcVal != 0x7F) {
939 fact_mantissa[band] = fPowInt(
940 FL2FXCONST_DBL(0.95483867181), /* -0.4014dB = 0.95483867181 */
941 0, valY, &compressionFactorVal_e);
942
943 /* -0.0008dB (48.164 - 6.0206*8 = -0.0008) */
944 fact_mantissa[band] =
945 fMult(FL2FXCONST_DBL(0.99990790084), fact_mantissa[band]);
946
947 fact_exponent[band] =
948 DVB_COMPRESSION_SCALE - valX + compressionFactorVal_e;
949 }
950 } else if ((AACDEC_DRC_PAYLOAD_TYPE)pDrcChData->drcDataType ==
951 MPEG_DRC_EXT_DATA) {
952 /* apply the scaled dynamic range control words to factor.
953 * if scaling drc_cut (or drc_boost), or control word drc_mantissa is 0
954 * then there is no dynamic range compression
955 *
956 * if pDrcChData->drcSgn[band] is
957 * 1 then gain is < 1 : factor = 2^(-self->cut *
958 * pDrcChData->drcMag[band] / 24) 0 then gain is > 1 : factor = 2^(
959 * self->boost * pDrcChData->drcMag[band] / 24)
960 */
961
962 if ((drcVal & 0x7F) > 0) {
963 FIXP_DBL tParamVal = (drcVal & 0x80) ? -pParams->cut : pParams->boost;
964
965 fact_mantissa[band] = f2Pow(
966 (FIXP_DBL)((INT)fMult(FL2FXCONST_DBL(1.0f / 192.0f), tParamVal) *
967 (drcVal & 0x7F)),
968 3 + DRC_PARAM_SCALE, &fact_exponent[band]);
969 }
970 }
971
972 fact_mantissa[band] = fMult(fact_mantissa[band], norm_mantissa);
973 fact_exponent[band] += norm_exponent;
974
975 } /* end loop over bands */
976
977 /* normalizations */
978 {
979 int res;
980
981 max_mantissa = FL2FXCONST_DBL(0.0f);
982 max_exponent = 0;
983 for (band = 0; band < numBands; band++) {
984 max_mantissa = fixMax(max_mantissa, fact_mantissa[band]);
985 max_exponent = fixMax(max_exponent, fact_exponent[band]);
986 }
987
988 /* left shift factors to gain accurancy */
989 res = CntLeadingZeros(max_mantissa) - 1;
990
991 /* above topmost DRC band gain factor is 1 */
992 if (((pDrcChData->bandTop[fMax(0, numBands - 1)] + 1) << 2) < aacFrameSize)
993 res = 0;
994
995 if (res > 0) {
996 res = fixMin(res, max_exponent);
997 max_exponent -= res;
998
999 for (band = 0; band < numBands; band++) {
1000 fact_mantissa[band] <<= res;
1001 fact_exponent[band] -= res;
1002 }
1003 }
1004
1005 /* normalize magnitudes to one scale factor */
1006 for (band = 0; band < numBands; band++) {
1007 if (fact_exponent[band] < max_exponent) {
1008 fact_mantissa[band] >>= max_exponent - fact_exponent[band];
1009 }
1010 if (fact_mantissa[band] != FL2FXCONST_DBL(0.5f)) {
1011 modifyBins = 1;
1012 }
1013 }
1014 if (max_exponent != 1) {
1015 modifyBins = 1;
1016 }
1017 }
1018
1019 /* apply factor to spectral lines
1020 * short blocks must take care that bands fall on
1021 * block boundaries!
1022 */
1023 if (!bSbrPresent) {
1024 bottom = 0;
1025
1026 if (!modifyBins) {
1027 /* We don't have to modify the spectral bins because the fractional part
1028 of all factors is 0.5. In order to keep accurancy we don't apply the
1029 factor but decrease the exponent instead. */
1030 max_exponent -= 1;
1031 } else {
1032 for (band = 0; band < numBands; band++) {
1033 int top = fixMin((int)((pDrcChData->bandTop[band] + 1) << 2),
1034 aacFrameSize); /* ... * DRC_BAND_MULT; */
1035
1036 for (bin = bottom; bin < top; bin++) {
1037 pSpectralCoefficient[bin] =
1038 fMult(pSpectralCoefficient[bin], fact_mantissa[band]);
1039 }
1040
1041 bottom = top;
1042 }
1043 }
1044
1045 /* above topmost DRC band gain factor is 1 */
1046 if (max_exponent > 0) {
1047 for (bin = bottom; bin < aacFrameSize; bin += 1) {
1048 pSpectralCoefficient[bin] >>= max_exponent;
1049 }
1050 }
1051
1052 /* adjust scaling */
1053 pSpecScale[0] += max_exponent;
1054
1055 if (winSeq == BLOCK_SHORT) {
1056 int win;
1057 for (win = 1; win < 8; win++) {
1058 pSpecScale[win] += max_exponent;
1059 }
1060 }
1061 } else {
1062 HANDLE_SBRDECODER hSbrDecoder = (HANDLE_SBRDECODER)pSbrDec;
1063 numBands = pDrcChData->numBands;
1064
1065 /* feed factors into SBR decoder for application in QMF domain. */
1066 sbrDecoder_drcFeedChannel(hSbrDecoder, ch, numBands, fact_mantissa,
1067 max_exponent, pDrcChData->drcInterpolationScheme,
1068 winSeq, pDrcChData->bandTop);
1069 }
1070
1071 return;
1072 }
1073
1074 /*
1075 * DRC parameter and presentation mode handling
1076 */
aacDecoder_drcParameterHandling(HANDLE_AAC_DRC self,INT aacNumChannels,SCHAR prevDrcProgRefLevel,SCHAR prevDrcPresMode)1077 static void aacDecoder_drcParameterHandling(HANDLE_AAC_DRC self,
1078 INT aacNumChannels,
1079 SCHAR prevDrcProgRefLevel,
1080 SCHAR prevDrcPresMode) {
1081 int isDownmix, isMonoDownmix, isStereoDownmix;
1082 int dDmx, dHr;
1083 AACDEC_DRC_PARAMETER_HANDLING drcParameterHandling;
1084 CDrcParams *p;
1085
1086 FDK_ASSERT(self != NULL);
1087
1088 p = &self->params;
1089
1090 if (self->progRefLevel != prevDrcProgRefLevel) self->update = 1;
1091
1092 if (self->presMode != prevDrcPresMode) self->update = 1;
1093
1094 if (self->prevAacNumChannels != aacNumChannels) self->update = 1;
1095
1096 /* return if no relevant parameter has changed */
1097 if (!self->update) {
1098 return;
1099 }
1100
1101 /* derive downmix property. aacNumChannels: number of channels in aac stream,
1102 * numOutChannels: number of output channels */
1103 isDownmix = (aacNumChannels > self->numOutChannels);
1104 isDownmix = (isDownmix && (self->numOutChannels > 0));
1105 isMonoDownmix = (isDownmix && (self->numOutChannels == 1));
1106 isStereoDownmix = (isDownmix && (self->numOutChannels == 2));
1107
1108 if ((self->presMode == 1) || (self->presMode == 2)) {
1109 drcParameterHandling = (AACDEC_DRC_PARAMETER_HANDLING)self->presMode;
1110 } else { /* no presentation mode -> use parameter handling specified by
1111 AAC_DRC_DEFAULT_PRESENTATION_MODE */
1112 drcParameterHandling = p->defaultPresentationMode;
1113 }
1114
1115 /* by default, do as desired */
1116 p->cut = p->usrCut;
1117 p->boost = p->usrBoost;
1118 p->applyHeavyCompression = p->usrApplyHeavyCompression;
1119
1120 switch (drcParameterHandling) {
1121 case DISABLED_PARAMETER_HANDLING:
1122 default:
1123 /* use drc parameters as requested */
1124 break;
1125
1126 case ENABLED_PARAMETER_HANDLING:
1127 /* dDmx: estimated headroom reduction due to downmix, format: -1/4*dB
1128 dDmx = floor(-4*20*log10(aacNumChannels/numOutChannels)) */
1129 if (isDownmix) {
1130 FIXP_DBL dmxTmp;
1131 int e_log, e_mult;
1132 dmxTmp = fDivNorm(self->numOutChannels,
1133 aacNumChannels); /* inverse division ->
1134 negative sign after
1135 logarithm */
1136 dmxTmp = fLog2(dmxTmp, 0, &e_log);
1137 dmxTmp = fMultNorm(
1138 dmxTmp, FL2FXCONST_DBL(4.0f * 20.0f * 0.30103f / (float)(1 << 5)),
1139 &e_mult); /* e = e_log + e_mult + 5 */
1140 dDmx = (int)scaleValue(dmxTmp, e_log + e_mult + 5 - (DFRACT_BITS - 1));
1141 } else {
1142 dDmx = 0;
1143 }
1144
1145 /* dHr: Full estimated (decoder) headroom reduction due to loudness
1146 * normalisation (DTL - PRL) and downmix. Format: -1/4*dB */
1147 if (p->targetRefLevel >= 0) { /* if target level is provided */
1148 dHr = p->targetRefLevel + dDmx - self->progRefLevel;
1149 } else {
1150 dHr = dDmx;
1151 }
1152
1153 if (dHr < 0) { /* if headroom is reduced */
1154 /* Use compression, but as little as possible. */
1155 /* eHr: Headroom provided by encoder, format: -1/4 dB */
1156 int eHr = fixMin(p->encoderTargetLevel - self->progRefLevel, 0);
1157 if (eHr <
1158 dHr) { /* if encoder provides more headroom than decoder needs */
1159 /* derive scaling of light DRC */
1160 FIXP_DBL calcFactor_norm;
1161 INT calcFactor; /* fraction of DRC gains that is minimally needed for
1162 clipping prevention */
1163 calcFactor_norm =
1164 fDivNorm(-dHr, -eHr); /* 0.0 < calcFactor_norm < 1.0 */
1165 calcFactor_norm = calcFactor_norm >> DRC_PARAM_SCALE;
1166 /* quantize to 128 steps */
1167 calcFactor = convert_drcParam(
1168 calcFactor_norm); /* convert to integer value between 0 and 127 */
1169 calcFactor_norm = (FIXP_DBL)(
1170 (INT)(DRC_PARAM_QUANT_STEP >> DRC_PARAM_SCALE) * calcFactor);
1171 p->cut = (calcFactor_norm > p->cut)
1172 ? calcFactor_norm
1173 : p->cut; /* use calcFactor_norm as lower limit */
1174 } else {
1175 /* encoder provides equal or less headroom than decoder needs */
1176 /* the time domain limiter must always be active in this case. It is
1177 * assumed that the framework activates it by default */
1178 p->cut = DRC_SCALING_MAX;
1179 if ((dHr - eHr) <=
1180 -4 * DRC_HEAVY_THRESHOLD_DB) { /* use heavy compression if
1181 headroom deficit is equal or
1182 higher than
1183 DRC_HEAVY_THRESHOLD_DB */
1184 p->applyHeavyCompression = ON;
1185 }
1186 }
1187 } else { /* dHr >= 0 */
1188 /* no restrictions required, as headroom is not reduced. */
1189 /* p->cut = p->usrCut; */
1190 }
1191 break;
1192
1193 /* presentation mode 1 and 2 according to ETSI TS 101 154:
1194 Digital Video Broadcasting (DVB); Specification for the use of Video
1195 and Audio Coding in Broadcasting Applications based on the MPEG-2
1196 Transport Stream, section C.5.4., "Decoding", and Table C.33. Also
1197 according to amendment 4 to ISO/IEC 14496-3, section 4.5.2.14.2.4, and
1198 Table AMD4.11. ISO DRC -> applyHeavyCompression = OFF (Use
1199 light compression, MPEG-style) Compression_value ->
1200 applyHeavyCompression = ON (Use heavy compression, DVB-style) scaling
1201 restricted -> p->cut = DRC_SCALING_MAX */
1202
1203 case DRC_PRESENTATION_MODE_1: /* presentation mode 1, Light:-31/Heavy:-23 */
1204 if ((p->targetRefLevel >= 0) &&
1205 (p->targetRefLevel <
1206 124)) { /* if target level is provided and > -31 dB */
1207 /* playback up to -23 dB */
1208 p->applyHeavyCompression = ON;
1209 } else { /* target level <= -31 dB or not provided */
1210 /* playback -31 dB */
1211 if (isMonoDownmix || isStereoDownmix) { /* stereo or mono downmixing */
1212 p->cut = DRC_SCALING_MAX;
1213 }
1214 }
1215 break;
1216
1217 case DRC_PRESENTATION_MODE_2: /* presentation mode 2, Light:-23/Heavy:-23 */
1218 if ((p->targetRefLevel >= 0) &&
1219 (p->targetRefLevel <
1220 124)) { /* if target level is provided and > -31 dB */
1221 /* playback up to -23 dB */
1222 if (isMonoDownmix) { /* if mono downmix */
1223 p->applyHeavyCompression = ON;
1224 } else {
1225 p->applyHeavyCompression = OFF;
1226 p->cut = DRC_SCALING_MAX;
1227 }
1228 } else { /* target level <= -31 dB or not provided */
1229 /* playback -31 dB */
1230 p->applyHeavyCompression = OFF;
1231 if (isMonoDownmix || isStereoDownmix) { /* stereo or mono downmixing */
1232 p->cut = DRC_SCALING_MAX;
1233 }
1234 }
1235 break;
1236 } /* switch (drcParameterHandling) */
1237
1238 /* With heavy compression, there is no scaling.
1239 Scaling factors are set for notification only. */
1240 if (p->applyHeavyCompression == ON) {
1241 p->boost = DRC_SCALING_MAX;
1242 p->cut = DRC_SCALING_MAX;
1243 }
1244
1245 /* switch on/off processing */
1246 self->enable = ((p->boost > (FIXP_DBL)0) || (p->cut > (FIXP_DBL)0) ||
1247 (p->applyHeavyCompression == ON) || (p->targetRefLevel >= 0));
1248 self->enable = (self->enable && !self->uniDrcPrecedence);
1249
1250 self->prevAacNumChannels = aacNumChannels;
1251 self->update = 0;
1252 }
1253
1254 /*
1255 * Prepare DRC processing
1256 * Valid return values are:
1257 * -1 : An unexpected error occured.
1258 * 0 : No error and no valid DRC data available.
1259 * 1 : No error and valid DRC data has been mapped.
1260 */
aacDecoder_drcProlog(HANDLE_AAC_DRC self,HANDLE_FDK_BITSTREAM hBs,CAacDecoderStaticChannelInfo * pAacDecoderStaticChannelInfo[],UCHAR pceInstanceTag,UCHAR channelMapping[],int validChannels)1261 int aacDecoder_drcProlog(
1262 HANDLE_AAC_DRC self, HANDLE_FDK_BITSTREAM hBs,
1263 CAacDecoderStaticChannelInfo *pAacDecoderStaticChannelInfo[],
1264 UCHAR pceInstanceTag,
1265 UCHAR channelMapping[], /* Channel mapping translating drcChannel index to
1266 canonical channel index */
1267 int validChannels) {
1268 int result = 0;
1269
1270 if (self == NULL) {
1271 return -1;
1272 }
1273
1274 if (!self->params.bsDelayEnable) {
1275 /* keep previous progRefLevel and presMode for update flag in
1276 * drcParameterHandling */
1277 INT prevPRL, prevPM = 0;
1278 prevPRL = self->progRefLevel;
1279 prevPM = self->presMode;
1280
1281 result = aacDecoder_drcExtractAndMap(
1282 self, hBs, pAacDecoderStaticChannelInfo, pceInstanceTag, channelMapping,
1283 validChannels);
1284
1285 if (result < 0) {
1286 return result;
1287 }
1288
1289 /* Drc parameter handling */
1290 aacDecoder_drcParameterHandling(self, validChannels, prevPRL, prevPM);
1291 }
1292
1293 return result;
1294 }
1295
1296 /*
1297 * Finalize DRC processing
1298 * Valid return values are:
1299 * -1 : An unexpected error occured.
1300 * 0 : No error and no valid DRC data available.
1301 * 1 : No error and valid DRC data has been mapped.
1302 */
aacDecoder_drcEpilog(HANDLE_AAC_DRC self,HANDLE_FDK_BITSTREAM hBs,CAacDecoderStaticChannelInfo * pAacDecoderStaticChannelInfo[],UCHAR pceInstanceTag,UCHAR channelMapping[],int validChannels)1303 int aacDecoder_drcEpilog(
1304 HANDLE_AAC_DRC self, HANDLE_FDK_BITSTREAM hBs,
1305 CAacDecoderStaticChannelInfo *pAacDecoderStaticChannelInfo[],
1306 UCHAR pceInstanceTag,
1307 UCHAR channelMapping[], /* Channel mapping translating drcChannel index to
1308 canonical channel index */
1309 int validChannels) {
1310 int result = 0;
1311
1312 if (self == NULL) {
1313 return -1;
1314 }
1315
1316 if (self->params.bsDelayEnable) {
1317 /* keep previous progRefLevel and presMode for update flag in
1318 * drcParameterHandling */
1319 INT prevPRL, prevPM = 0;
1320 prevPRL = self->progRefLevel;
1321 prevPM = self->presMode;
1322
1323 result = aacDecoder_drcExtractAndMap(
1324 self, hBs, pAacDecoderStaticChannelInfo, pceInstanceTag, channelMapping,
1325 validChannels);
1326
1327 if (result < 0) {
1328 return result;
1329 }
1330
1331 /* Drc parameter handling */
1332 aacDecoder_drcParameterHandling(self, validChannels, prevPRL, prevPM);
1333 }
1334
1335 return result;
1336 }
1337
1338 /*
1339 * Export relevant metadata info from bitstream payload.
1340 */
aacDecoder_drcGetInfo(HANDLE_AAC_DRC self,SCHAR * pPresMode,SCHAR * pProgRefLevel)1341 void aacDecoder_drcGetInfo(HANDLE_AAC_DRC self, SCHAR *pPresMode,
1342 SCHAR *pProgRefLevel) {
1343 if (self != NULL) {
1344 if (pPresMode != NULL) {
1345 *pPresMode = self->presMode;
1346 }
1347 if (pProgRefLevel != NULL) {
1348 if (self->progRefLevelPresent) {
1349 *pProgRefLevel = self->progRefLevel;
1350 } else {
1351 *pProgRefLevel = -1;
1352 }
1353 }
1354 }
1355 }
1356
1357 /**
1358 * \brief Apply DRC Level Normalization.
1359 *
1360 * This function prepares/applies the gain values for the DRC Level
1361 * Normalization and returns the exponent of the time data. The following two
1362 * cases are handled:
1363 *
1364 * - Limiter enabled:
1365 * The input data must be interleaved.
1366 * One gain per sample is written to the buffer pGainPerSample.
1367 * If necessary the time data is rescaled.
1368 *
1369 * - Limiter disabled:
1370 * The input data can be interleaved or deinterleaved.
1371 * The gain values are applied to the time data.
1372 * If necessary the time data is rescaled.
1373 *
1374 * \param hDrcInfo [i/o] handle to drc data structure.
1375 * \param samplesIn [i/o] pointer to time data.
1376 * \param pGain [i ] pointer to gain to be applied to
1377 * the time data.
1378 * \param pGainPerSample [o ] pointer to the gain per sample to
1379 * be applied to the time data in the limiter.
1380 * \param gain_scale [i ] exponent to be applied to the time
1381 * data.
1382 * \param gain_delay [i ] delay[samples] with which the gains
1383 * in pGain shall be applied (gain_delay <= nSamples).
1384 * \param nSamples [i ] number of samples per frame.
1385 * \param channels [i ] number of channels.
1386 * \param stride [i ] channel stride of time data.
1387 * \param limiterEnabled [i ] 1 if limiter is enabled, otherwise
1388 * 0.
1389 *
1390 * \return exponent of time data
1391 */
applyDrcLevelNormalization(HANDLE_AAC_DRC hDrcInfo,PCM_DEC * samplesIn,FIXP_DBL * pGain,FIXP_DBL * pGainPerSample,const INT gain_scale,const UINT gain_delay,const UINT nSamples,const UINT channels,const UINT stride,const UINT limiterEnabled)1392 INT applyDrcLevelNormalization(HANDLE_AAC_DRC hDrcInfo, PCM_DEC *samplesIn,
1393 FIXP_DBL *pGain, FIXP_DBL *pGainPerSample,
1394 const INT gain_scale, const UINT gain_delay,
1395 const UINT nSamples, const UINT channels,
1396 const UINT stride, const UINT limiterEnabled) {
1397 UINT i;
1398 INT additionalGain_scaling;
1399 FIXP_DBL additionalGain;
1400
1401 FDK_ASSERT(gain_delay <= nSamples);
1402
1403 FIXP_DBL additionalGainSmoothState = hDrcInfo->additionalGainFilterState;
1404 FIXP_DBL additionalGainSmoothState1 = hDrcInfo->additionalGainFilterState1;
1405
1406 if (!gain_delay) {
1407 additionalGain = pGain[0];
1408
1409 /* Apply the additional scaling gain_scale[0] that has no delay and no
1410 * smoothing */
1411 additionalGain_scaling =
1412 fMin(gain_scale, CntLeadingZeros(additionalGain) - 1);
1413 additionalGain = scaleValue(additionalGain, additionalGain_scaling);
1414
1415 /* if it's not possible to fully apply gain_scale to additionalGain, apply
1416 * it to the input signal */
1417 additionalGain_scaling -= gain_scale;
1418
1419 if (additionalGain_scaling) {
1420 scaleValuesSaturate(samplesIn, channels * nSamples,
1421 -additionalGain_scaling);
1422 }
1423
1424 if (limiterEnabled) {
1425 FDK_ASSERT(pGainPerSample != NULL);
1426
1427 for (i = 0; i < nSamples; i++) {
1428 pGainPerSample[i] = additionalGain;
1429 }
1430 } else {
1431 for (i = 0; i < channels * nSamples; i++) {
1432 samplesIn[i] = FIXP_DBL2PCM_DEC(fMult(samplesIn[i], additionalGain));
1433 }
1434 }
1435 } else {
1436 UINT inc;
1437 FIXP_DBL additionalGainUnfiltered;
1438
1439 inc = (stride == 1) ? channels : 1;
1440
1441 for (i = 0; i < nSamples; i++) {
1442 if (i < gain_delay) {
1443 additionalGainUnfiltered = hDrcInfo->additionalGainPrev;
1444 } else {
1445 additionalGainUnfiltered = pGain[0];
1446 }
1447
1448 /* Smooth additionalGain */
1449
1450 /* [b,a] = butter(1, 0.01) */
1451 static const FIXP_SGL b[] = {FL2FXCONST_SGL(0.015466 * 2.0),
1452 FL2FXCONST_SGL(0.015466 * 2.0)};
1453 static const FIXP_SGL a[] = {(FIXP_SGL)MAXVAL_SGL,
1454 FL2FXCONST_SGL(-0.96907)};
1455
1456 additionalGain = -fMult(additionalGainSmoothState, a[1]) +
1457 fMultDiv2(additionalGainUnfiltered, b[0]) +
1458 fMultDiv2(additionalGainSmoothState1, b[1]);
1459 additionalGainSmoothState1 = additionalGainUnfiltered;
1460 additionalGainSmoothState = additionalGain;
1461
1462 /* Apply the additional scaling gain_scale[0] that has no delay and no
1463 * smoothing */
1464 additionalGain_scaling =
1465 fMin(gain_scale, CntLeadingZeros(additionalGain) - 1);
1466 additionalGain = scaleValue(additionalGain, additionalGain_scaling);
1467
1468 /* if it's not possible to fully apply gain_scale[0] to additionalGain,
1469 * apply it to the input signal */
1470 additionalGain_scaling -= gain_scale;
1471
1472 if (limiterEnabled) {
1473 FDK_ASSERT(stride == 1);
1474 FDK_ASSERT(pGainPerSample != NULL);
1475
1476 if (additionalGain_scaling) {
1477 scaleValuesSaturate(samplesIn, channels, -additionalGain_scaling);
1478 }
1479
1480 pGainPerSample[i] = additionalGain;
1481 } else {
1482 if (additionalGain_scaling) {
1483 for (UINT k = 0; k < channels; k++) {
1484 scaleValuesSaturate(&samplesIn[k * stride], 1,
1485 -additionalGain_scaling);
1486 }
1487 }
1488
1489 for (UINT k = 0; k < channels; k++) {
1490 samplesIn[k * stride] =
1491 FIXP_DBL2PCM_DEC(fMult(samplesIn[k * stride], additionalGain));
1492 }
1493 }
1494
1495 samplesIn += inc;
1496 }
1497 }
1498
1499 hDrcInfo->additionalGainPrev = pGain[0];
1500 hDrcInfo->additionalGainFilterState = additionalGainSmoothState;
1501 hDrcInfo->additionalGainFilterState1 = additionalGainSmoothState1;
1502
1503 return (AACDEC_DRC_GAIN_SCALING);
1504 }
1505