• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* -----------------------------------------------------------------------------
2 Software License for The Fraunhofer FDK AAC Codec Library for Android
3 
4 © Copyright  1995 - 2018 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):   Josef Hoepfl
98 
99    Description: long/short-block decoding
100 
101 *******************************************************************************/
102 
103 #include "block.h"
104 
105 #include "aac_rom.h"
106 #include "FDK_bitstream.h"
107 #include "scale.h"
108 #include "FDK_tools_rom.h"
109 
110 #include "usacdec_fac.h"
111 #include "usacdec_lpd.h"
112 #include "usacdec_lpc.h"
113 #include "FDK_trigFcts.h"
114 
115 #include "ac_arith_coder.h"
116 
117 #include "aacdec_hcr.h"
118 #include "rvlc.h"
119 
120 #if defined(__arm__)
121 #include "arm/block_arm.cpp"
122 #endif
123 
124 /*!
125   \brief Read escape sequence of codeword
126 
127   The function reads the escape sequence from the bitstream,
128   if the absolute value of the quantized coefficient has the
129   value 16.
130   A limitation is implemented to maximal 31 bits to prevent endless loops.
131   If it strikes, MAX_QUANTIZED_VALUE + 1 is returned, independent of the sign of
132   parameter q.
133 
134   \return  quantized coefficient
135 */
CBlock_GetEscape(HANDLE_FDK_BITSTREAM bs,const LONG q)136 LONG CBlock_GetEscape(HANDLE_FDK_BITSTREAM bs, /*!< pointer to bitstream */
137                       const LONG q)            /*!< quantized coefficient */
138 {
139   if (fAbs(q) != 16) return (q);
140 
141   LONG i, off;
142   for (i = 4; i < 32; i++) {
143     if (FDKreadBit(bs) == 0) break;
144   }
145 
146   if (i == 32) return (MAX_QUANTIZED_VALUE + 1);
147 
148   off = FDKreadBits(bs, i);
149   i = off + (1 << i);
150 
151   if (q < 0) i = -i;
152 
153   return i;
154 }
155 
CBlock_ReadScaleFactorData(CAacDecoderChannelInfo * pAacDecoderChannelInfo,HANDLE_FDK_BITSTREAM bs,UINT flags)156 AAC_DECODER_ERROR CBlock_ReadScaleFactorData(
157     CAacDecoderChannelInfo *pAacDecoderChannelInfo, HANDLE_FDK_BITSTREAM bs,
158     UINT flags) {
159   int temp;
160   int band;
161   int group;
162   int position = 0; /* accu for intensity delta coding */
163   int factor = pAacDecoderChannelInfo->pDynData->RawDataInfo
164                    .GlobalGain; /* accu for scale factor delta coding */
165   UCHAR *pCodeBook = pAacDecoderChannelInfo->pDynData->aCodeBook;
166   SHORT *pScaleFactor = pAacDecoderChannelInfo->pDynData->aScaleFactor;
167   const CodeBookDescription *hcb = &AACcodeBookDescriptionTable[BOOKSCL];
168 
169   const USHORT(*CodeBook)[HuffmanEntries] = hcb->CodeBook;
170 
171   int ScaleFactorBandsTransmitted =
172       GetScaleFactorBandsTransmitted(&pAacDecoderChannelInfo->icsInfo);
173   for (group = 0; group < GetWindowGroups(&pAacDecoderChannelInfo->icsInfo);
174        group++) {
175     for (band = 0; band < ScaleFactorBandsTransmitted; band++) {
176       switch (pCodeBook[band]) {
177         case ZERO_HCB: /* zero book */
178           pScaleFactor[band] = 0;
179           break;
180 
181         default: /* decode scale factor */
182           if (!((flags & (AC_USAC | AC_RSVD50 | AC_RSV603DA)) && band == 0 &&
183                 group == 0)) {
184             temp = CBlock_DecodeHuffmanWordCB(bs, CodeBook);
185             factor += temp - 60; /* MIDFAC 1.5 dB */
186           }
187           pScaleFactor[band] = factor - 100;
188           break;
189 
190         case INTENSITY_HCB: /* intensity steering */
191         case INTENSITY_HCB2:
192           temp = CBlock_DecodeHuffmanWordCB(bs, CodeBook);
193           position += temp - 60;
194           pScaleFactor[band] = position - 100;
195           break;
196 
197         case NOISE_HCB: /* PNS */
198           if (flags & (AC_MPEGD_RES | AC_USAC | AC_RSVD50 | AC_RSV603DA)) {
199             return AAC_DEC_PARSE_ERROR;
200           }
201           CPns_Read(&pAacDecoderChannelInfo->data.aac.PnsData, bs, hcb,
202                     pAacDecoderChannelInfo->pDynData->aScaleFactor,
203                     pAacDecoderChannelInfo->pDynData->RawDataInfo.GlobalGain,
204                     band, group);
205           break;
206       }
207     }
208     pCodeBook += 16;
209     pScaleFactor += 16;
210   }
211 
212   return AAC_DEC_OK;
213 }
214 
CBlock_ScaleSpectralData(CAacDecoderChannelInfo * pAacDecoderChannelInfo,UCHAR maxSfbs,SamplingRateInfo * pSamplingRateInfo)215 void CBlock_ScaleSpectralData(CAacDecoderChannelInfo *pAacDecoderChannelInfo,
216                               UCHAR maxSfbs,
217                               SamplingRateInfo *pSamplingRateInfo) {
218   int band;
219   int window;
220   const SHORT *RESTRICT pSfbScale = pAacDecoderChannelInfo->pDynData->aSfbScale;
221   SHORT *RESTRICT pSpecScale = pAacDecoderChannelInfo->specScale;
222   int groupwin, group;
223   const SHORT *RESTRICT BandOffsets = GetScaleFactorBandOffsets(
224       &pAacDecoderChannelInfo->icsInfo, pSamplingRateInfo);
225   SPECTRAL_PTR RESTRICT pSpectralCoefficient =
226       pAacDecoderChannelInfo->pSpectralCoefficient;
227 
228   FDKmemclear(pSpecScale, 8 * sizeof(SHORT));
229 
230   for (window = 0, group = 0;
231        group < GetWindowGroups(&pAacDecoderChannelInfo->icsInfo); group++) {
232     for (groupwin = 0; groupwin < GetWindowGroupLength(
233                                       &pAacDecoderChannelInfo->icsInfo, group);
234          groupwin++, window++) {
235       int SpecScale_window = pSpecScale[window];
236       FIXP_DBL *pSpectrum = SPEC(pSpectralCoefficient, window,
237                                  pAacDecoderChannelInfo->granuleLength);
238 
239       /* find scaling for current window */
240       for (band = 0; band < maxSfbs; band++) {
241         SpecScale_window =
242             fMax(SpecScale_window, (int)pSfbScale[window * 16 + band]);
243       }
244 
245       if (pAacDecoderChannelInfo->pDynData->TnsData.Active &&
246           pAacDecoderChannelInfo->pDynData->TnsData.NumberOfFilters[window] >
247               0) {
248         int filter_index, SpecScale_window_tns;
249         int tns_start, tns_stop;
250 
251         /* Find max scale of TNS bands */
252         SpecScale_window_tns = 0;
253         tns_start = GetMaximumTnsBands(&pAacDecoderChannelInfo->icsInfo,
254                                        pSamplingRateInfo->samplingRateIndex);
255         tns_stop = 0;
256         for (filter_index = 0;
257              filter_index < (int)pAacDecoderChannelInfo->pDynData->TnsData
258                                 .NumberOfFilters[window];
259              filter_index++) {
260           for (band = pAacDecoderChannelInfo->pDynData->TnsData
261                           .Filter[window][filter_index]
262                           .StartBand;
263                band < pAacDecoderChannelInfo->pDynData->TnsData
264                           .Filter[window][filter_index]
265                           .StopBand;
266                band++) {
267             SpecScale_window_tns =
268                 fMax(SpecScale_window_tns, (int)pSfbScale[window * 16 + band]);
269           }
270           /* Find TNS line boundaries for all TNS filters */
271           tns_start =
272               fMin(tns_start, (int)pAacDecoderChannelInfo->pDynData->TnsData
273                                   .Filter[window][filter_index]
274                                   .StartBand);
275           tns_stop =
276               fMax(tns_stop, (int)pAacDecoderChannelInfo->pDynData->TnsData
277                                  .Filter[window][filter_index]
278                                  .StopBand);
279         }
280         SpecScale_window_tns = SpecScale_window_tns +
281                                pAacDecoderChannelInfo->pDynData->TnsData.GainLd;
282         FDK_ASSERT(tns_stop >= tns_start);
283         /* Consider existing headroom of all MDCT lines inside the TNS bands. */
284         SpecScale_window_tns -=
285             getScalefactor(pSpectrum + BandOffsets[tns_start],
286                            BandOffsets[tns_stop] - BandOffsets[tns_start]);
287         if (SpecScale_window <= 17) {
288           SpecScale_window_tns++;
289         }
290         /* Add enough mantissa head room such that the spectrum is still
291            representable after applying TNS. */
292         SpecScale_window = fMax(SpecScale_window, SpecScale_window_tns);
293       }
294 
295       /* store scaling of current window */
296       pSpecScale[window] = SpecScale_window;
297 
298 #ifdef FUNCTION_CBlock_ScaleSpectralData_func1
299 
300       CBlock_ScaleSpectralData_func1(pSpectrum, maxSfbs, BandOffsets,
301                                      SpecScale_window, pSfbScale, window);
302 
303 #else  /* FUNCTION_CBlock_ScaleSpectralData_func1 */
304       for (band = 0; band < maxSfbs; band++) {
305         int scale = fMin(DFRACT_BITS - 1,
306                          SpecScale_window - pSfbScale[window * 16 + band]);
307         if (scale) {
308           FDK_ASSERT(scale > 0);
309 
310           /* following relation can be used for optimizations:
311            * (BandOffsets[i]%4) == 0 for all i */
312           int max_index = BandOffsets[band + 1];
313           DWORD_ALIGNED(pSpectrum);
314           for (int index = BandOffsets[band]; index < max_index; index++) {
315             pSpectrum[index] >>= scale;
316           }
317         }
318       }
319 #endif /* FUNCTION_CBlock_ScaleSpectralData_func1 */
320     }
321   }
322 }
323 
CBlock_ReadSectionData(HANDLE_FDK_BITSTREAM bs,CAacDecoderChannelInfo * pAacDecoderChannelInfo,const SamplingRateInfo * pSamplingRateInfo,const UINT flags)324 AAC_DECODER_ERROR CBlock_ReadSectionData(
325     HANDLE_FDK_BITSTREAM bs, CAacDecoderChannelInfo *pAacDecoderChannelInfo,
326     const SamplingRateInfo *pSamplingRateInfo, const UINT flags) {
327   int top, band;
328   int sect_len, sect_len_incr;
329   int group;
330   UCHAR sect_cb;
331   UCHAR *pCodeBook = pAacDecoderChannelInfo->pDynData->aCodeBook;
332   /* HCR input (long) */
333   SHORT *pNumLinesInSec =
334       pAacDecoderChannelInfo->pDynData->specificTo.aac.aNumLineInSec4Hcr;
335   int numLinesInSecIdx = 0;
336   UCHAR *pHcrCodeBook =
337       pAacDecoderChannelInfo->pDynData->specificTo.aac.aCodeBooks4Hcr;
338   const SHORT *BandOffsets = GetScaleFactorBandOffsets(
339       &pAacDecoderChannelInfo->icsInfo, pSamplingRateInfo);
340   pAacDecoderChannelInfo->pDynData->specificTo.aac.numberSection = 0;
341   AAC_DECODER_ERROR ErrorStatus = AAC_DEC_OK;
342 
343   FDKmemclear(pCodeBook, sizeof(UCHAR) * (8 * 16));
344 
345   const int nbits =
346       (IsLongBlock(&pAacDecoderChannelInfo->icsInfo) == 1) ? 5 : 3;
347 
348   int sect_esc_val = (1 << nbits) - 1;
349 
350   UCHAR ScaleFactorBandsTransmitted =
351       GetScaleFactorBandsTransmitted(&pAacDecoderChannelInfo->icsInfo);
352   for (group = 0; group < GetWindowGroups(&pAacDecoderChannelInfo->icsInfo);
353        group++) {
354     for (band = 0; band < ScaleFactorBandsTransmitted;) {
355       sect_len = 0;
356       if (flags & AC_ER_VCB11) {
357         sect_cb = (UCHAR)FDKreadBits(bs, 5);
358       } else
359         sect_cb = (UCHAR)FDKreadBits(bs, 4);
360 
361       if (((flags & AC_ER_VCB11) == 0) || (sect_cb < 11) ||
362           ((sect_cb > 11) && (sect_cb < 16))) {
363         sect_len_incr = FDKreadBits(bs, nbits);
364         while (sect_len_incr == sect_esc_val) {
365           sect_len += sect_esc_val;
366           sect_len_incr = FDKreadBits(bs, nbits);
367         }
368       } else {
369         sect_len_incr = 1;
370       }
371 
372       sect_len += sect_len_incr;
373 
374       top = band + sect_len;
375 
376       if (flags & AC_ER_HCR) {
377         /* HCR input (long) -- collecting sideinfo (for HCR-_long_ only) */
378         if (numLinesInSecIdx >= MAX_SFB_HCR) {
379           return AAC_DEC_PARSE_ERROR;
380         }
381         if (top > (int)GetNumberOfScaleFactorBands(
382                       &pAacDecoderChannelInfo->icsInfo, pSamplingRateInfo)) {
383           return AAC_DEC_PARSE_ERROR;
384         }
385         pNumLinesInSec[numLinesInSecIdx] = BandOffsets[top] - BandOffsets[band];
386         numLinesInSecIdx++;
387         if (sect_cb == BOOKSCL) {
388           return AAC_DEC_INVALID_CODE_BOOK;
389         } else {
390           *pHcrCodeBook++ = sect_cb;
391         }
392         pAacDecoderChannelInfo->pDynData->specificTo.aac.numberSection++;
393       }
394 
395       /* Check spectral line limits */
396       if (IsLongBlock(&(pAacDecoderChannelInfo->icsInfo))) {
397         if (top > 64) {
398           return AAC_DEC_DECODE_FRAME_ERROR;
399         }
400       } else { /* short block */
401         if (top + group * 16 > (8 * 16)) {
402           return AAC_DEC_DECODE_FRAME_ERROR;
403         }
404       }
405 
406       /* Check if decoded codebook index is feasible */
407       if ((sect_cb == BOOKSCL) ||
408           ((sect_cb == INTENSITY_HCB || sect_cb == INTENSITY_HCB2) &&
409            pAacDecoderChannelInfo->pDynData->RawDataInfo.CommonWindow == 0)) {
410         return AAC_DEC_INVALID_CODE_BOOK;
411       }
412 
413       /* Store codebook index */
414       for (; band < top; band++) {
415         pCodeBook[group * 16 + band] = sect_cb;
416       }
417     }
418   }
419 
420   return ErrorStatus;
421 }
422 
423 /* mso: provides a faster way to i-quantize a whole band in one go */
424 
425 /**
426  * \brief inverse quantize one sfb. Each value of the sfb is processed according
427  * to the formula: spectrum[i] = Sign(spectrum[i]) * Matissa(spectrum[i])^(4/3)
428  * * 2^(lsb/4).
429  * \param spectrum pointer to first line of the sfb to be inverse quantized.
430  * \param noLines number of lines belonging to the sfb.
431  * \param lsb last 2 bits of the scale factor of the sfb.
432  * \param scale max allowed shift scale for the sfb.
433  */
InverseQuantizeBand(FIXP_DBL * RESTRICT spectrum,const FIXP_DBL * RESTRICT InverseQuantTabler,const FIXP_DBL * RESTRICT MantissaTabler,const SCHAR * RESTRICT ExponentTabler,INT noLines,INT scale)434 static inline void InverseQuantizeBand(
435     FIXP_DBL *RESTRICT spectrum, const FIXP_DBL *RESTRICT InverseQuantTabler,
436     const FIXP_DBL *RESTRICT MantissaTabler,
437     const SCHAR *RESTRICT ExponentTabler, INT noLines, INT scale) {
438   scale = scale + 1; /* +1 to compensate fMultDiv2 shift-right in loop */
439 
440   FIXP_DBL *RESTRICT ptr = spectrum;
441   FIXP_DBL signedValue;
442 
443   for (INT i = noLines; i--;) {
444     if ((signedValue = *ptr++) != FL2FXCONST_DBL(0)) {
445       FIXP_DBL value = fAbs(signedValue);
446       UINT freeBits = CntLeadingZeros(value);
447       UINT exponent = 32 - freeBits;
448 
449       UINT x = (UINT)(LONG)value << (INT)freeBits;
450       x <<= 1; /* shift out sign bit to avoid masking later on */
451       UINT tableIndex = x >> 24;
452       x = (x >> 20) & 0x0F;
453 
454       UINT r0 = (UINT)(LONG)InverseQuantTabler[tableIndex + 0];
455       UINT r1 = (UINT)(LONG)InverseQuantTabler[tableIndex + 1];
456       UINT temp = (r1 - r0) * x + (r0 << 4);
457 
458       value = fMultDiv2((FIXP_DBL)temp, MantissaTabler[exponent]);
459 
460       /* + 1 compensates fMultDiv2() */
461       scaleValueInPlace(&value, scale + ExponentTabler[exponent]);
462 
463       signedValue = (signedValue < (FIXP_DBL)0) ? -value : value;
464       ptr[-1] = signedValue;
465     }
466   }
467 }
468 
maxabs_D(const FIXP_DBL * pSpectralCoefficient,const int noLines)469 static inline FIXP_DBL maxabs_D(const FIXP_DBL *pSpectralCoefficient,
470                                 const int noLines) {
471   /* Find max spectral line value of the current sfb */
472   FIXP_DBL locMax = (FIXP_DBL)0;
473   int i;
474 
475   DWORD_ALIGNED(pSpectralCoefficient);
476 
477   for (i = noLines; i-- > 0;) {
478     /* Expensive memory access */
479     locMax = fMax(fixp_abs(pSpectralCoefficient[i]), locMax);
480   }
481 
482   return locMax;
483 }
484 
CBlock_InverseQuantizeSpectralData(CAacDecoderChannelInfo * pAacDecoderChannelInfo,SamplingRateInfo * pSamplingRateInfo,UCHAR * band_is_noise,UCHAR active_band_search)485 AAC_DECODER_ERROR CBlock_InverseQuantizeSpectralData(
486     CAacDecoderChannelInfo *pAacDecoderChannelInfo,
487     SamplingRateInfo *pSamplingRateInfo, UCHAR *band_is_noise,
488     UCHAR active_band_search) {
489   int window, group, groupwin, band;
490   int ScaleFactorBandsTransmitted =
491       GetScaleFactorBandsTransmitted(&pAacDecoderChannelInfo->icsInfo);
492   UCHAR *RESTRICT pCodeBook = pAacDecoderChannelInfo->pDynData->aCodeBook;
493   SHORT *RESTRICT pSfbScale = pAacDecoderChannelInfo->pDynData->aSfbScale;
494   SHORT *RESTRICT pScaleFactor = pAacDecoderChannelInfo->pDynData->aScaleFactor;
495   const SHORT *RESTRICT BandOffsets = GetScaleFactorBandOffsets(
496       &pAacDecoderChannelInfo->icsInfo, pSamplingRateInfo);
497   const SHORT total_bands =
498       GetScaleFactorBandsTotal(&pAacDecoderChannelInfo->icsInfo);
499 
500   FDKmemclear(pAacDecoderChannelInfo->pDynData->aSfbScale,
501               (8 * 16) * sizeof(SHORT));
502 
503   for (window = 0, group = 0;
504        group < GetWindowGroups(&pAacDecoderChannelInfo->icsInfo); group++) {
505     for (groupwin = 0; groupwin < GetWindowGroupLength(
506                                       &pAacDecoderChannelInfo->icsInfo, group);
507          groupwin++, window++) {
508       /* inverse quantization */
509       for (band = 0; band < ScaleFactorBandsTransmitted; band++) {
510         FIXP_DBL *pSpectralCoefficient =
511             SPEC(pAacDecoderChannelInfo->pSpectralCoefficient, window,
512                  pAacDecoderChannelInfo->granuleLength) +
513             BandOffsets[band];
514         FIXP_DBL locMax;
515 
516         const int noLines = BandOffsets[band + 1] - BandOffsets[band];
517         const int bnds = group * 16 + band;
518 
519         if ((pCodeBook[bnds] == ZERO_HCB) ||
520             (pCodeBook[bnds] == INTENSITY_HCB) ||
521             (pCodeBook[bnds] == INTENSITY_HCB2))
522           continue;
523 
524         if (pCodeBook[bnds] == NOISE_HCB) {
525           /* Leave headroom for PNS values. + 1 because ceil(log2(2^(0.25*3))) =
526              1, worst case of additional headroom required because of the
527              scalefactor. */
528           pSfbScale[window * 16 + band] = (pScaleFactor[bnds] >> 2) + 1;
529           continue;
530         }
531 
532         locMax = maxabs_D(pSpectralCoefficient, noLines);
533 
534         if (active_band_search) {
535           if (locMax != FIXP_DBL(0)) {
536             band_is_noise[group * 16 + band] = 0;
537           }
538         }
539 
540         /* Cheap robustness improvement - Do not remove!!! */
541         if (fixp_abs(locMax) > (FIXP_DBL)MAX_QUANTIZED_VALUE) {
542           return AAC_DEC_PARSE_ERROR;
543         }
544 
545         /* Added by Youliy Ninov:
546         The inverse quantization operation is given by (ISO/IEC 14496-3:2009(E))
547         by:
548 
549         x_invquant=Sign(x_quant). abs(x_quant)^(4/3)
550 
551         We apply a gain, derived from the scale factor for the particular sfb,
552         according to the following function:
553 
554         gain=2^(0.25*ScaleFactor)
555 
556         So, after scaling we have:
557 
558         x_rescale=gain*x_invquant=Sign(x_quant)*2^(0.25*ScaleFactor)*abs(s_quant)^(4/3)
559 
560         We could represent the ScaleFactor as:
561 
562         ScaleFactor= (ScaleFactor >> 2)*4 + ScaleFactor %4
563 
564         When we substitute it we get:
565 
566         x_rescale=Sign(x_quant)*2^(ScaleFactor>>2)* (
567         2^(0.25*(ScaleFactor%4))*abs(s_quant)^(4/3))
568 
569         When we set: msb=(ScaleFactor>>2) and lsb=(ScaleFactor%4), we obtain:
570 
571         x_rescale=Sign(x_quant)*(2^msb)* ( 2^(lsb/4)*abs(s_quant)^(4/3))
572 
573         The rescaled output can be represented by:
574            mantissa : Sign(x_quant)*( 2^(lsb/4)*abs(s_quant)^(4/3))
575            exponent :(2^msb)
576 
577         */
578 
579         int msb = pScaleFactor[bnds] >> 2;
580 
581         /* Inverse quantize band only if it is not empty */
582         if (locMax != FIXP_DBL(0)) {
583           int lsb = pScaleFactor[bnds] & 0x03;
584 
585           int scale = EvaluatePower43(&locMax, lsb);
586 
587           scale = CntLeadingZeros(locMax) - scale - 2;
588 
589           pSfbScale[window * 16 + band] = msb - scale;
590           InverseQuantizeBand(pSpectralCoefficient, InverseQuantTable,
591                               MantissaTable[lsb], ExponentTable[lsb], noLines,
592                               scale);
593         } else {
594           pSfbScale[window * 16 + band] = msb;
595         }
596 
597       } /* for (band=0; band < ScaleFactorBandsTransmitted; band++) */
598 
599       /* Make sure the array is cleared to the end */
600       SHORT start_clear = BandOffsets[ScaleFactorBandsTransmitted];
601       SHORT end_clear = BandOffsets[total_bands];
602       int diff_clear = (int)(end_clear - start_clear);
603       FIXP_DBL *pSpectralCoefficient =
604           SPEC(pAacDecoderChannelInfo->pSpectralCoefficient, window,
605                pAacDecoderChannelInfo->granuleLength) +
606           start_clear;
607       FDKmemclear(pSpectralCoefficient, diff_clear * sizeof(FIXP_DBL));
608 
609     } /* for (groupwin=0; groupwin <
610          GetWindowGroupLength(&pAacDecoderChannelInfo->icsInfo,group);
611          groupwin++, window++) */
612   }   /* for (window=0, group=0; group <
613          GetWindowGroups(&pAacDecoderChannelInfo->icsInfo); group++)*/
614 
615   return AAC_DEC_OK;
616 }
617 
CBlock_ReadSpectralData(HANDLE_FDK_BITSTREAM bs,CAacDecoderChannelInfo * pAacDecoderChannelInfo,const SamplingRateInfo * pSamplingRateInfo,const UINT flags)618 AAC_DECODER_ERROR CBlock_ReadSpectralData(
619     HANDLE_FDK_BITSTREAM bs, CAacDecoderChannelInfo *pAacDecoderChannelInfo,
620     const SamplingRateInfo *pSamplingRateInfo, const UINT flags) {
621   int index, i;
622   const SHORT *RESTRICT BandOffsets = GetScaleFactorBandOffsets(
623       &pAacDecoderChannelInfo->icsInfo, pSamplingRateInfo);
624 
625   SPECTRAL_PTR pSpectralCoefficient =
626       pAacDecoderChannelInfo->pSpectralCoefficient;
627 
628   FDK_ASSERT(BandOffsets != NULL);
629 
630   FDKmemclear(pSpectralCoefficient, sizeof(SPECTRUM));
631 
632   if ((flags & AC_ER_HCR) == 0) {
633     int group;
634     int groupoffset;
635     UCHAR *pCodeBook = pAacDecoderChannelInfo->pDynData->aCodeBook;
636     int ScaleFactorBandsTransmitted =
637         GetScaleFactorBandsTransmitted(&pAacDecoderChannelInfo->icsInfo);
638     int granuleLength = pAacDecoderChannelInfo->granuleLength;
639 
640     groupoffset = 0;
641 
642     /* plain huffman decoder  short */
643     int max_group = GetWindowGroups(&pAacDecoderChannelInfo->icsInfo);
644 
645     for (group = 0; group < max_group; group++) {
646       int max_groupwin =
647           GetWindowGroupLength(&pAacDecoderChannelInfo->icsInfo, group);
648       int band;
649 
650       int bnds = group * 16;
651 
652       int bandOffset1 = BandOffsets[0];
653       for (band = 0; band < ScaleFactorBandsTransmitted; band++, bnds++) {
654         UCHAR currentCB = pCodeBook[bnds];
655         int bandOffset0 = bandOffset1;
656         bandOffset1 = BandOffsets[band + 1];
657 
658         /* patch to run plain-huffman-decoder with vcb11 input codebooks
659          * (LAV-checking might be possible below using the virtual cb and a
660          * LAV-table) */
661         if ((currentCB >= 16) && (currentCB <= 31)) {
662           pCodeBook[bnds] = currentCB = 11;
663         }
664         if (((currentCB != ZERO_HCB) && (currentCB != NOISE_HCB) &&
665              (currentCB != INTENSITY_HCB) && (currentCB != INTENSITY_HCB2))) {
666           const CodeBookDescription *hcb =
667               &AACcodeBookDescriptionTable[currentCB];
668           int step = hcb->Dimension;
669           int offset = hcb->Offset;
670           int bits = hcb->numBits;
671           int mask = (1 << bits) - 1;
672           const USHORT(*CodeBook)[HuffmanEntries] = hcb->CodeBook;
673           int groupwin;
674 
675           FIXP_DBL *mdctSpectrum =
676               &pSpectralCoefficient[groupoffset * granuleLength];
677 
678           if (offset == 0) {
679             for (groupwin = 0; groupwin < max_groupwin; groupwin++) {
680               for (index = bandOffset0; index < bandOffset1; index += step) {
681                 int idx = CBlock_DecodeHuffmanWordCB(bs, CodeBook);
682                 for (i = 0; i < step; i++, idx >>= bits) {
683                   FIXP_DBL tmp = (FIXP_DBL)((idx & mask) - offset);
684                   if (tmp != FIXP_DBL(0)) tmp = (FDKreadBit(bs)) ? -tmp : tmp;
685                   mdctSpectrum[index + i] = tmp;
686                 }
687 
688                 if (currentCB == ESCBOOK) {
689                   for (int j = 0; j < 2; j++)
690                     mdctSpectrum[index + j] = (FIXP_DBL)CBlock_GetEscape(
691                         bs, (LONG)mdctSpectrum[index + j]);
692                 }
693               }
694               mdctSpectrum += granuleLength;
695             }
696           } else {
697             for (groupwin = 0; groupwin < max_groupwin; groupwin++) {
698               for (index = bandOffset0; index < bandOffset1; index += step) {
699                 int idx = CBlock_DecodeHuffmanWordCB(bs, CodeBook);
700                 for (i = 0; i < step; i++, idx >>= bits) {
701                   mdctSpectrum[index + i] = (FIXP_DBL)((idx & mask) - offset);
702                 }
703                 if (currentCB == ESCBOOK) {
704                   for (int j = 0; j < 2; j++)
705                     mdctSpectrum[index + j] = (FIXP_DBL)CBlock_GetEscape(
706                         bs, (LONG)mdctSpectrum[index + j]);
707                 }
708               }
709               mdctSpectrum += granuleLength;
710             }
711           }
712         }
713       }
714       groupoffset += max_groupwin;
715     }
716     /* plain huffman decoding (short) finished */
717   }
718 
719   /* HCR - Huffman Codeword Reordering  short */
720   else /* if ( flags & AC_ER_HCR ) */
721 
722   {
723     H_HCR_INFO hHcr = &pAacDecoderChannelInfo->pComData->overlay.aac.erHcrInfo;
724 
725     int hcrStatus = 0;
726 
727     /* advanced Huffman decoding starts here (HCR decoding :) */
728     if (pAacDecoderChannelInfo->pDynData->specificTo.aac
729             .lenOfReorderedSpectralData != 0) {
730       /* HCR initialization short */
731       hcrStatus = HcrInit(hHcr, pAacDecoderChannelInfo, pSamplingRateInfo, bs);
732 
733       if (hcrStatus != 0) {
734         return AAC_DEC_DECODE_FRAME_ERROR;
735       }
736 
737       /* HCR decoding short */
738       hcrStatus =
739           HcrDecoder(hHcr, pAacDecoderChannelInfo, pSamplingRateInfo, bs);
740 
741       if (hcrStatus != 0) {
742 #if HCR_ERROR_CONCEALMENT
743         HcrMuteErroneousLines(hHcr);
744 #else
745         return AAC_DEC_DECODE_FRAME_ERROR;
746 #endif /* HCR_ERROR_CONCEALMENT */
747       }
748 
749       FDKpushFor(bs, pAacDecoderChannelInfo->pDynData->specificTo.aac
750                          .lenOfReorderedSpectralData);
751     }
752   }
753   /* HCR - Huffman Codeword Reordering short finished */
754 
755   if (IsLongBlock(&pAacDecoderChannelInfo->icsInfo) &&
756       !(flags & (AC_ELD | AC_SCALABLE))) {
757     /* apply pulse data */
758     CPulseData_Apply(
759         &pAacDecoderChannelInfo->pDynData->specificTo.aac.PulseData,
760         GetScaleFactorBandOffsets(&pAacDecoderChannelInfo->icsInfo,
761                                   pSamplingRateInfo),
762         SPEC_LONG(pSpectralCoefficient));
763   }
764 
765   return AAC_DEC_OK;
766 }
767 
768 static const FIXP_SGL noise_level_tab[8] = {
769     /* FDKpow(2, (float)(noise_level-14)/3.0f) * 2; (*2 to compensate for
770        fMultDiv2) noise_level_tab(noise_level==0) == 0 by definition
771     */
772     FX_DBL2FXCONST_SGL(0x00000000 /*0x0a145173*/),
773     FX_DBL2FXCONST_SGL(0x0cb2ff5e),
774     FX_DBL2FXCONST_SGL(0x10000000),
775     FX_DBL2FXCONST_SGL(0x1428a2e7),
776     FX_DBL2FXCONST_SGL(0x1965febd),
777     FX_DBL2FXCONST_SGL(0x20000000),
778     FX_DBL2FXCONST_SGL(0x28514606),
779     FX_DBL2FXCONST_SGL(0x32cbfd33)};
780 
CBlock_ApplyNoise(CAacDecoderChannelInfo * pAacDecoderChannelInfo,SamplingRateInfo * pSamplingRateInfo,ULONG * nfRandomSeed,UCHAR * band_is_noise)781 void CBlock_ApplyNoise(CAacDecoderChannelInfo *pAacDecoderChannelInfo,
782                        SamplingRateInfo *pSamplingRateInfo, ULONG *nfRandomSeed,
783                        UCHAR *band_is_noise) {
784   const SHORT *swb_offset = GetScaleFactorBandOffsets(
785       &pAacDecoderChannelInfo->icsInfo, pSamplingRateInfo);
786   int g, win, gwin, sfb, noiseFillingStartOffset, nfStartOffset_sfb;
787 
788   /* Obtain noise level and scale factor offset. */
789   int noise_level = pAacDecoderChannelInfo->pDynData->specificTo.usac
790                         .fd_noise_level_and_offset >>
791                     5;
792   const FIXP_SGL noiseVal_pos = noise_level_tab[noise_level];
793 
794   /* noise_offset can change even when noise_level=0. Neccesary for IGF stereo
795    * filling */
796   const int noise_offset = (pAacDecoderChannelInfo->pDynData->specificTo.usac
797                                 .fd_noise_level_and_offset &
798                             0x1f) -
799                            16;
800 
801   int max_sfb =
802       GetScaleFactorBandsTransmitted(&pAacDecoderChannelInfo->icsInfo);
803 
804   noiseFillingStartOffset =
805       (GetWindowSequence(&pAacDecoderChannelInfo->icsInfo) == BLOCK_SHORT)
806           ? 20
807           : 160;
808   if (pAacDecoderChannelInfo->granuleLength == 96) {
809     noiseFillingStartOffset =
810         (3 * noiseFillingStartOffset) /
811         4; /* scale offset with 3/4 for coreCoderFrameLength == 768 */
812   }
813 
814   /* determine sfb from where on noise filling is applied */
815   for (sfb = 0; swb_offset[sfb] < noiseFillingStartOffset; sfb++)
816     ;
817   nfStartOffset_sfb = sfb;
818 
819   /* if (noise_level!=0) */
820   {
821     for (g = 0, win = 0; g < GetWindowGroups(&pAacDecoderChannelInfo->icsInfo);
822          g++) {
823       int windowGroupLength =
824           GetWindowGroupLength(&pAacDecoderChannelInfo->icsInfo, g);
825       for (sfb = nfStartOffset_sfb; sfb < max_sfb; sfb++) {
826         int bin_start = swb_offset[sfb];
827         int bin_stop = swb_offset[sfb + 1];
828 
829         int flagN = band_is_noise[g * 16 + sfb];
830 
831         /* if all bins of one sfb in one window group are zero modify the scale
832          * factor by noise_offset */
833         if (flagN) {
834           /* Change scaling factors for empty signal bands */
835           pAacDecoderChannelInfo->pDynData->aScaleFactor[g * 16 + sfb] +=
836               noise_offset;
837           /* scale factor "sf" implied gain "g" is g = 2^(sf/4) */
838           for (gwin = 0; gwin < windowGroupLength; gwin++) {
839             pAacDecoderChannelInfo->pDynData
840                 ->aSfbScale[(win + gwin) * 16 + sfb] += (noise_offset >> 2);
841           }
842         }
843 
844         ULONG seed = *nfRandomSeed;
845         /* + 1 because exponent of MantissaTable[lsb][0] is always 1. */
846         int scale =
847             (pAacDecoderChannelInfo->pDynData->aScaleFactor[g * 16 + sfb] >>
848              2) +
849             1;
850         int lsb =
851             pAacDecoderChannelInfo->pDynData->aScaleFactor[g * 16 + sfb] & 3;
852         FIXP_DBL mantissa = MantissaTable[lsb][0];
853 
854         for (gwin = 0; gwin < windowGroupLength; gwin++) {
855           FIXP_DBL *pSpec =
856               SPEC(pAacDecoderChannelInfo->pSpectralCoefficient, win + gwin,
857                    pAacDecoderChannelInfo->granuleLength);
858 
859           int scale1 = scale - pAacDecoderChannelInfo->pDynData
860                                    ->aSfbScale[(win + gwin) * 16 + sfb];
861           FIXP_DBL scaled_noiseVal_pos =
862               scaleValue(fMultDiv2(noiseVal_pos, mantissa), scale1);
863           FIXP_DBL scaled_noiseVal_neg = -scaled_noiseVal_pos;
864 
865           /* If the whole band is zero, just fill without checking */
866           if (flagN) {
867             for (int bin = bin_start; bin < bin_stop; bin++) {
868               seed = (ULONG)(
869                   (UINT64)seed * 69069 +
870                   5); /* Inlined: UsacRandomSign - origin in usacdec_lpd.h */
871               pSpec[bin] =
872                   (seed & 0x10000) ? scaled_noiseVal_neg : scaled_noiseVal_pos;
873             } /* for (bin...) */
874           }
875           /*If band is sparsely filled, check for 0 and fill */
876           else {
877             for (int bin = bin_start; bin < bin_stop; bin++) {
878               if (pSpec[bin] == (FIXP_DBL)0) {
879                 seed = (ULONG)(
880                     (UINT64)seed * 69069 +
881                     5); /* Inlined: UsacRandomSign - origin in usacdec_lpd.h */
882                 pSpec[bin] = (seed & 0x10000) ? scaled_noiseVal_neg
883                                               : scaled_noiseVal_pos;
884               }
885             } /* for (bin...) */
886           }
887 
888         } /* for (gwin...) */
889         *nfRandomSeed = seed;
890       } /* for (sfb...) */
891       win += windowGroupLength;
892     } /* for (g...) */
893 
894   } /* ... */
895 }
896 
CBlock_ReadAcSpectralData(HANDLE_FDK_BITSTREAM hBs,CAacDecoderChannelInfo * pAacDecoderChannelInfo,CAacDecoderStaticChannelInfo * pAacDecoderStaticChannelInfo,const SamplingRateInfo * pSamplingRateInfo,const UINT frame_length,const UINT flags)897 AAC_DECODER_ERROR CBlock_ReadAcSpectralData(
898     HANDLE_FDK_BITSTREAM hBs, CAacDecoderChannelInfo *pAacDecoderChannelInfo,
899     CAacDecoderStaticChannelInfo *pAacDecoderStaticChannelInfo,
900     const SamplingRateInfo *pSamplingRateInfo, const UINT frame_length,
901     const UINT flags) {
902   AAC_DECODER_ERROR errorAAC = AAC_DEC_OK;
903   ARITH_CODING_ERROR error = ARITH_CODER_OK;
904   int arith_reset_flag, lg, numWin, win, winLen;
905   const SHORT *RESTRICT BandOffsets;
906 
907   /* number of transmitted spectral coefficients */
908   BandOffsets = GetScaleFactorBandOffsets(&pAacDecoderChannelInfo->icsInfo,
909                                           pSamplingRateInfo);
910   lg = BandOffsets[GetScaleFactorBandsTransmitted(
911       &pAacDecoderChannelInfo->icsInfo)];
912 
913   numWin = GetWindowsPerFrame(&pAacDecoderChannelInfo->icsInfo);
914   winLen = (IsLongBlock(&pAacDecoderChannelInfo->icsInfo))
915                ? (int)frame_length
916                : (int)frame_length / numWin;
917 
918   if (flags & AC_INDEP) {
919     arith_reset_flag = 1;
920   } else {
921     arith_reset_flag = (USHORT)FDKreadBits(hBs, 1);
922   }
923 
924   for (win = 0; win < numWin; win++) {
925     error =
926         CArco_DecodeArithData(pAacDecoderStaticChannelInfo->hArCo, hBs,
927                               SPEC(pAacDecoderChannelInfo->pSpectralCoefficient,
928                                    win, pAacDecoderChannelInfo->granuleLength),
929                               lg, winLen, arith_reset_flag && (win == 0));
930     if (error != ARITH_CODER_OK) {
931       goto bail;
932     }
933   }
934 
935 bail:
936   if (error == ARITH_CODER_ERROR) {
937     errorAAC = AAC_DEC_PARSE_ERROR;
938   }
939 
940   return errorAAC;
941 }
942 
ApplyTools(CAacDecoderChannelInfo * pAacDecoderChannelInfo[],const SamplingRateInfo * pSamplingRateInfo,const UINT flags,const UINT elFlags,const int channel,const int common_window)943 void ApplyTools(CAacDecoderChannelInfo *pAacDecoderChannelInfo[],
944                 const SamplingRateInfo *pSamplingRateInfo, const UINT flags,
945                 const UINT elFlags, const int channel,
946                 const int common_window) {
947   if (!(flags & (AC_USAC | AC_RSVD50 | AC_MPEGD_RES | AC_RSV603DA))) {
948     CPns_Apply(&pAacDecoderChannelInfo[channel]->data.aac.PnsData,
949                &pAacDecoderChannelInfo[channel]->icsInfo,
950                pAacDecoderChannelInfo[channel]->pSpectralCoefficient,
951                pAacDecoderChannelInfo[channel]->specScale,
952                pAacDecoderChannelInfo[channel]->pDynData->aScaleFactor,
953                pSamplingRateInfo,
954                pAacDecoderChannelInfo[channel]->granuleLength, channel);
955   }
956 
957   UCHAR nbands =
958       GetScaleFactorBandsTransmitted(&pAacDecoderChannelInfo[channel]->icsInfo);
959 
960   CTns_Apply(&pAacDecoderChannelInfo[channel]->pDynData->TnsData,
961              &pAacDecoderChannelInfo[channel]->icsInfo,
962              pAacDecoderChannelInfo[channel]->pSpectralCoefficient,
963              pSamplingRateInfo, pAacDecoderChannelInfo[channel]->granuleLength,
964              nbands, (elFlags & AC_EL_ENHANCED_NOISE) ? 1 : 0, flags);
965 }
966 
getWindow2Nr(int length,int shape)967 static int getWindow2Nr(int length, int shape) {
968   int nr = 0;
969 
970   if (shape == 2) {
971     /* Low Overlap, 3/4 zeroed */
972     nr = (length * 3) >> 2;
973   }
974 
975   return nr;
976 }
977 
get_gain(const FIXP_DBL * x,const FIXP_DBL * y,int n)978 FIXP_DBL get_gain(const FIXP_DBL *x, const FIXP_DBL *y, int n) {
979   FIXP_DBL corr = (FIXP_DBL)0;
980   FIXP_DBL ener = (FIXP_DBL)1;
981 
982   int headroom_x = getScalefactor(x, n);
983   int headroom_y = getScalefactor(y, n);
984 
985   /*Calculate the normalization necessary due to addition*/
986   /* Check for power of two /special case */
987   INT width_shift = (INT)(fNormz((FIXP_DBL)n));
988   /* Get the number of bits necessary minus one, because we need one sign bit
989    * only */
990   width_shift = 31 - width_shift;
991 
992   for (int i = 0; i < n; i++) {
993     corr +=
994         fMultDiv2((x[i] << headroom_x), (y[i] << headroom_y)) >> width_shift;
995     ener += fPow2Div2((y[i] << headroom_y)) >> width_shift;
996   }
997 
998   int exp_corr = (17 - headroom_x) + (17 - headroom_y) + width_shift + 1;
999   int exp_ener = ((17 - headroom_y) << 1) + width_shift + 1;
1000 
1001   int temp_exp = 0;
1002   FIXP_DBL output = fDivNormSigned(corr, ener, &temp_exp);
1003 
1004   int output_exp = (exp_corr - exp_ener) + temp_exp;
1005 
1006   INT output_shift = 17 - output_exp;
1007   output_shift = fMin(output_shift, 31);
1008 
1009   output = scaleValue(output, -output_shift);
1010 
1011   return output;
1012 }
1013 
CBlock_FrequencyToTime(CAacDecoderStaticChannelInfo * pAacDecoderStaticChannelInfo,CAacDecoderChannelInfo * pAacDecoderChannelInfo,FIXP_PCM outSamples[],const SHORT frameLen,const int frameOk,FIXP_DBL * pWorkBuffer1,UINT elFlags,INT elCh)1014 void CBlock_FrequencyToTime(
1015     CAacDecoderStaticChannelInfo *pAacDecoderStaticChannelInfo,
1016     CAacDecoderChannelInfo *pAacDecoderChannelInfo, FIXP_PCM outSamples[],
1017     const SHORT frameLen, const int frameOk, FIXP_DBL *pWorkBuffer1,
1018     UINT elFlags, INT elCh) {
1019   int fr, fl, tl, nSpec;
1020 
1021 #if defined(FDK_ASSERT_ENABLE)
1022   LONG nSamples;
1023 #endif
1024 
1025   /* Determine left slope length (fl), right slope length (fr) and transform
1026      length (tl). USAC: The slope length may mismatch with the previous frame in
1027      case of LPD / FD transitions. The adjustment is handled by the imdct
1028      implementation.
1029   */
1030   tl = frameLen;
1031   nSpec = 1;
1032 
1033   switch (pAacDecoderChannelInfo->icsInfo.WindowSequence) {
1034     default:
1035     case BLOCK_LONG:
1036       fl = frameLen;
1037       fr = frameLen -
1038            getWindow2Nr(frameLen,
1039                         GetWindowShape(&pAacDecoderChannelInfo->icsInfo));
1040       /* New startup needs differentiation between sine shape and low overlap
1041          shape. This is a special case for the LD-AAC transformation windows,
1042          because the slope length can be different while using the same window
1043          sequence. */
1044       if (pAacDecoderStaticChannelInfo->IMdct.prev_tl == 0) {
1045         fl = fr;
1046       }
1047       break;
1048     case BLOCK_STOP:
1049       fl = frameLen >> 3;
1050       fr = frameLen;
1051       break;
1052     case BLOCK_START: /* or StopStartSequence */
1053       fl = frameLen;
1054       fr = frameLen >> 3;
1055       break;
1056     case BLOCK_SHORT:
1057       fl = fr = frameLen >> 3;
1058       tl >>= 3;
1059       nSpec = 8;
1060       break;
1061   }
1062 
1063   {
1064     int last_frame_lost = pAacDecoderStaticChannelInfo->last_lpc_lost;
1065 
1066     if (pAacDecoderStaticChannelInfo->last_core_mode == LPD) {
1067       INT fac_FB = 1;
1068       if (elFlags & AC_EL_FULLBANDLPD) {
1069         fac_FB = 2;
1070       }
1071 
1072       FIXP_DBL *synth;
1073 
1074       /* Keep some free space at the beginning of the buffer. To be used for
1075        * past data */
1076       if (!(elFlags & AC_EL_LPDSTEREOIDX)) {
1077         synth = pWorkBuffer1 + ((PIT_MAX_MAX - (1 * L_SUBFR)) * fac_FB);
1078       } else {
1079         synth = pWorkBuffer1 + PIT_MAX_MAX * fac_FB;
1080       }
1081 
1082       int fac_length =
1083           (pAacDecoderChannelInfo->icsInfo.WindowSequence == BLOCK_SHORT)
1084               ? (frameLen >> 4)
1085               : (frameLen >> 3);
1086 
1087       INT pitch[NB_SUBFR_SUPERFR + SYN_SFD];
1088       FIXP_DBL pit_gain[NB_SUBFR_SUPERFR + SYN_SFD];
1089 
1090       int nbDiv = (elFlags & AC_EL_FULLBANDLPD) ? 2 : 4;
1091       int lFrame = (elFlags & AC_EL_FULLBANDLPD) ? frameLen / 2 : frameLen;
1092       int nbSubfr =
1093           lFrame / (nbDiv * L_SUBFR); /* number of subframes per division */
1094       int LpdSfd = (nbDiv * nbSubfr) >> 1;
1095       int SynSfd = LpdSfd - BPF_SFD;
1096 
1097       FDKmemclear(
1098           pitch,
1099           sizeof(
1100               pitch));  // added to prevent ferret errors in bass_pf_1sf_delay
1101       FDKmemclear(pit_gain, sizeof(pit_gain));
1102 
1103       /* FAC case */
1104       if (pAacDecoderStaticChannelInfo->last_lpd_mode == 0 ||
1105           pAacDecoderStaticChannelInfo->last_lpd_mode == 4) {
1106         FIXP_DBL fac_buf[LFAC];
1107         FIXP_LPC *A = pAacDecoderChannelInfo->data.usac.lp_coeff[0];
1108 
1109         if (!frameOk || last_frame_lost ||
1110             (pAacDecoderChannelInfo->data.usac.fac_data[0] == NULL)) {
1111           FDKmemclear(fac_buf,
1112                       pAacDecoderChannelInfo->granuleLength * sizeof(FIXP_DBL));
1113           pAacDecoderChannelInfo->data.usac.fac_data[0] = fac_buf;
1114           pAacDecoderChannelInfo->data.usac.fac_data_e[0] = 0;
1115         }
1116 
1117         INT A_exp; /* linear prediction coefficients exponent */
1118         {
1119           for (int i = 0; i < M_LP_FILTER_ORDER; i++) {
1120             A[i] = FX_DBL2FX_LPC(fixp_cos(
1121                 fMult(pAacDecoderStaticChannelInfo->lpc4_lsf[i],
1122                       FL2FXCONST_SGL((1 << LSPARG_SCALE) * M_PI / 6400.0)),
1123                 LSF_SCALE - LSPARG_SCALE));
1124           }
1125 
1126           E_LPC_f_lsp_a_conversion(A, A, &A_exp);
1127         }
1128 
1129 #if defined(FDK_ASSERT_ENABLE)
1130         nSamples =
1131 #endif
1132             CLpd_FAC_Acelp2Mdct(
1133                 &pAacDecoderStaticChannelInfo->IMdct, synth,
1134                 SPEC_LONG(pAacDecoderChannelInfo->pSpectralCoefficient),
1135                 pAacDecoderChannelInfo->specScale, nSpec,
1136                 pAacDecoderChannelInfo->data.usac.fac_data[0],
1137                 pAacDecoderChannelInfo->data.usac.fac_data_e[0], fac_length,
1138                 frameLen, tl,
1139                 FDKgetWindowSlope(
1140                     fr, GetWindowShape(&pAacDecoderChannelInfo->icsInfo)),
1141                 fr, A, A_exp, &pAacDecoderStaticChannelInfo->acelp,
1142                 (FIXP_DBL)0, /* FAC gain has already been applied. */
1143                 (last_frame_lost || !frameOk), 1,
1144                 pAacDecoderStaticChannelInfo->last_lpd_mode, 0,
1145                 pAacDecoderChannelInfo->currAliasingSymmetry);
1146 
1147       } else {
1148 #if defined(FDK_ASSERT_ENABLE)
1149         nSamples =
1150 #endif
1151             imlt_block(
1152                 &pAacDecoderStaticChannelInfo->IMdct, synth,
1153                 SPEC_LONG(pAacDecoderChannelInfo->pSpectralCoefficient),
1154                 pAacDecoderChannelInfo->specScale, nSpec, frameLen, tl,
1155                 FDKgetWindowSlope(
1156                     fl, GetWindowShape(&pAacDecoderChannelInfo->icsInfo)),
1157                 fl,
1158                 FDKgetWindowSlope(
1159                     fr, GetWindowShape(&pAacDecoderChannelInfo->icsInfo)),
1160                 fr, (FIXP_DBL)0,
1161                 pAacDecoderChannelInfo->currAliasingSymmetry
1162                     ? MLT_FLAG_CURR_ALIAS_SYMMETRY
1163                     : 0);
1164       }
1165       FDK_ASSERT(nSamples == frameLen);
1166 
1167       /* The "if" clause is entered both for fullbandLpd mono and
1168        * non-fullbandLpd*. The "else"-> just for fullbandLpd stereo*/
1169       if (!(elFlags & AC_EL_LPDSTEREOIDX)) {
1170         FDKmemcpy(pitch, pAacDecoderStaticChannelInfo->old_T_pf,
1171                   SynSfd * sizeof(INT));
1172         FDKmemcpy(pit_gain, pAacDecoderStaticChannelInfo->old_gain_pf,
1173                   SynSfd * sizeof(FIXP_DBL));
1174 
1175         for (int i = SynSfd; i < LpdSfd + 3; i++) {
1176           pitch[i] = L_SUBFR;
1177           pit_gain[i] = (FIXP_DBL)0;
1178         }
1179 
1180         if (pAacDecoderStaticChannelInfo->last_lpd_mode == 0) {
1181           pitch[SynSfd] = pitch[SynSfd - 1];
1182           pit_gain[SynSfd] = pit_gain[SynSfd - 1];
1183           if (IsLongBlock(&pAacDecoderChannelInfo->icsInfo)) {
1184             pitch[SynSfd + 1] = pitch[SynSfd];
1185             pit_gain[SynSfd + 1] = pit_gain[SynSfd];
1186           }
1187         }
1188 
1189         /* Copy old data to the beginning of the buffer */
1190         {
1191           FDKmemcpy(
1192               pWorkBuffer1, pAacDecoderStaticChannelInfo->old_synth,
1193               ((PIT_MAX_MAX - (1 * L_SUBFR)) * fac_FB) * sizeof(FIXP_DBL));
1194         }
1195 
1196         FIXP_DBL *p2_synth = pWorkBuffer1 + (PIT_MAX_MAX * fac_FB);
1197 
1198         /* recalculate pitch gain to allow postfilering on FAC area */
1199         for (int i = 0; i < SynSfd + 2; i++) {
1200           int T = pitch[i];
1201           FIXP_DBL gain = pit_gain[i];
1202 
1203           if (gain > (FIXP_DBL)0) {
1204             gain = get_gain(&p2_synth[i * L_SUBFR * fac_FB],
1205                             &p2_synth[(i * L_SUBFR * fac_FB) - fac_FB * T],
1206                             L_SUBFR * fac_FB);
1207             pit_gain[i] = gain;
1208           }
1209         }
1210 
1211         bass_pf_1sf_delay(p2_synth, pitch, pit_gain, frameLen,
1212                           (LpdSfd + 2) * L_SUBFR + BPF_SFD * L_SUBFR,
1213                           frameLen - (LpdSfd + 4) * L_SUBFR, outSamples,
1214                           pAacDecoderStaticChannelInfo->mem_bpf);
1215       }
1216 
1217     } else /* last_core_mode was not LPD */
1218     {
1219       FIXP_DBL *tmp =
1220           pAacDecoderChannelInfo->pComStaticData->pWorkBufferCore1->mdctOutTemp;
1221 #if defined(FDK_ASSERT_ENABLE)
1222       nSamples =
1223 #endif
1224           imlt_block(&pAacDecoderStaticChannelInfo->IMdct, tmp,
1225                      SPEC_LONG(pAacDecoderChannelInfo->pSpectralCoefficient),
1226                      pAacDecoderChannelInfo->specScale, nSpec, frameLen, tl,
1227                      FDKgetWindowSlope(
1228                          fl, GetWindowShape(&pAacDecoderChannelInfo->icsInfo)),
1229                      fl,
1230                      FDKgetWindowSlope(
1231                          fr, GetWindowShape(&pAacDecoderChannelInfo->icsInfo)),
1232                      fr, (FIXP_DBL)0,
1233                      pAacDecoderChannelInfo->currAliasingSymmetry
1234                          ? MLT_FLAG_CURR_ALIAS_SYMMETRY
1235                          : 0);
1236 
1237       scaleValuesSaturate(outSamples, tmp, frameLen, MDCT_OUT_HEADROOM);
1238     }
1239   }
1240 
1241   FDK_ASSERT(nSamples == frameLen);
1242 
1243   pAacDecoderStaticChannelInfo->last_core_mode =
1244       (pAacDecoderChannelInfo->icsInfo.WindowSequence == BLOCK_SHORT) ? FD_SHORT
1245                                                                       : FD_LONG;
1246   pAacDecoderStaticChannelInfo->last_lpd_mode = 255;
1247 }
1248 
1249 #include "ldfiltbank.h"
CBlock_FrequencyToTimeLowDelay(CAacDecoderStaticChannelInfo * pAacDecoderStaticChannelInfo,CAacDecoderChannelInfo * pAacDecoderChannelInfo,FIXP_PCM outSamples[],const short frameLen)1250 void CBlock_FrequencyToTimeLowDelay(
1251     CAacDecoderStaticChannelInfo *pAacDecoderStaticChannelInfo,
1252     CAacDecoderChannelInfo *pAacDecoderChannelInfo, FIXP_PCM outSamples[],
1253     const short frameLen) {
1254   InvMdctTransformLowDelay_fdk(
1255       SPEC_LONG(pAacDecoderChannelInfo->pSpectralCoefficient),
1256       pAacDecoderChannelInfo->specScale[0], outSamples,
1257       pAacDecoderStaticChannelInfo->pOverlapBuffer, frameLen);
1258 }
1259