• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 /**************************** SBR decoder library ******************************
96 
97    Author(s):
98 
99    Description:
100 
101 *******************************************************************************/
102 
103 /*!
104   \file
105   \brief  SBR decoder frontend
106   This module provides a frontend to the SBR decoder. The function openSBR() is
107   called for initialization. The function sbrDecoder_Apply() is called for each
108   frame. sbr_Apply() will call the required functions to decode the raw SBR data
109   (provided by env_extr.cpp), to decode the envelope data and noise floor levels
110   [decodeSbrData()], and to finally apply SBR to the current frame [sbr_dec()].
111 
112   \sa sbrDecoder_Apply(), \ref documentationOverview
113 */
114 
115 /*!
116   \page documentationOverview Overview of important information resources and
117   source code documentation
118 
119   As part of this documentation you can find more extensive descriptions about
120   key concepts and algorithms at the following locations:
121 
122   <h2>Programming</h2>
123 
124   \li Buffer management: sbrDecoder_Apply() and sbr_dec()
125   \li Internal scale factors to maximize SNR on fixed point processors:
126   #QMF_SCALE_FACTOR \li Special mantissa-exponent format: Created in
127   requantizeEnvelopeData() and used in calculateSbrEnvelope()
128 
129   <h2>Algorithmic details</h2>
130   \li About the SBR data format: \ref SBR_HEADER_ELEMENT and \ref
131   SBR_STANDARD_ELEMENT \li Details about the bitstream decoder: env_extr.cpp \li
132   Details about the QMF filterbank and the provided polyphase implementation:
133   qmf_dec.cpp \li Details about the transposer: lpp_tran.cpp \li Details about
134   the envelope adjuster: env_calc.cpp
135 
136 */
137 
138 #include "sbrdecoder.h"
139 
140 #include "FDK_bitstream.h"
141 
142 #include "sbrdec_freq_sca.h"
143 #include "env_extr.h"
144 #include "sbr_dec.h"
145 #include "env_dec.h"
146 #include "sbr_crc.h"
147 #include "sbr_ram.h"
148 #include "sbr_rom.h"
149 #include "lpp_tran.h"
150 #include "transcendent.h"
151 
152 #include "FDK_crc.h"
153 
154 #include "sbrdec_drc.h"
155 
156 #include "psbitdec.h"
157 
158 /* Decoder library info */
159 #define SBRDECODER_LIB_VL0 3
160 #define SBRDECODER_LIB_VL1 0
161 #define SBRDECODER_LIB_VL2 0
162 #define SBRDECODER_LIB_TITLE "SBR Decoder"
163 #ifdef __ANDROID__
164 #define SBRDECODER_LIB_BUILD_DATE ""
165 #define SBRDECODER_LIB_BUILD_TIME ""
166 #else
167 #define SBRDECODER_LIB_BUILD_DATE __DATE__
168 #define SBRDECODER_LIB_BUILD_TIME __TIME__
169 #endif
170 
setFrameErrorFlag(SBR_DECODER_ELEMENT * pSbrElement,UCHAR value)171 static void setFrameErrorFlag(SBR_DECODER_ELEMENT *pSbrElement, UCHAR value) {
172   if (pSbrElement != NULL) {
173     switch (value) {
174       case FRAME_ERROR_ALLSLOTS:
175         FDKmemset(pSbrElement->frameErrorFlag, FRAME_ERROR,
176                   sizeof(pSbrElement->frameErrorFlag));
177         break;
178       default:
179         pSbrElement->frameErrorFlag[pSbrElement->useFrameSlot] = value;
180     }
181   }
182 }
183 
getHeaderSlot(UCHAR currentSlot,UCHAR hdrSlotUsage[(1)+1])184 static UCHAR getHeaderSlot(UCHAR currentSlot, UCHAR hdrSlotUsage[(1) + 1]) {
185   UINT occupied = 0;
186   int s;
187   UCHAR slot = hdrSlotUsage[currentSlot];
188 
189   FDK_ASSERT((1) + 1 < 32);
190 
191   for (s = 0; s < (1) + 1; s++) {
192     if ((hdrSlotUsage[s] == slot) && (s != slot)) {
193       occupied = 1;
194       break;
195     }
196   }
197 
198   if (occupied) {
199     occupied = 0;
200 
201     for (s = 0; s < (1) + 1; s++) {
202       occupied |= 1 << hdrSlotUsage[s];
203     }
204     for (s = 0; s < (1) + 1; s++) {
205       if (!(occupied & 0x1)) {
206         slot = s;
207         break;
208       }
209       occupied >>= 1;
210     }
211   }
212 
213   return slot;
214 }
215 
copySbrHeader(HANDLE_SBR_HEADER_DATA hDst,const HANDLE_SBR_HEADER_DATA hSrc)216 static void copySbrHeader(HANDLE_SBR_HEADER_DATA hDst,
217                           const HANDLE_SBR_HEADER_DATA hSrc) {
218   /* copy the whole header memory (including pointers) */
219   FDKmemcpy(hDst, hSrc, sizeof(SBR_HEADER_DATA));
220 
221   /* update pointers */
222   hDst->freqBandData.freqBandTable[0] = hDst->freqBandData.freqBandTableLo;
223   hDst->freqBandData.freqBandTable[1] = hDst->freqBandData.freqBandTableHi;
224 }
225 
compareSbrHeader(const HANDLE_SBR_HEADER_DATA hHdr1,const HANDLE_SBR_HEADER_DATA hHdr2)226 static int compareSbrHeader(const HANDLE_SBR_HEADER_DATA hHdr1,
227                             const HANDLE_SBR_HEADER_DATA hHdr2) {
228   int result = 0;
229 
230   /* compare basic data */
231   result |= (hHdr1->syncState != hHdr2->syncState) ? 1 : 0;
232   result |= (hHdr1->status != hHdr2->status) ? 1 : 0;
233   result |= (hHdr1->frameErrorFlag != hHdr2->frameErrorFlag) ? 1 : 0;
234   result |= (hHdr1->numberTimeSlots != hHdr2->numberTimeSlots) ? 1 : 0;
235   result |=
236       (hHdr1->numberOfAnalysisBands != hHdr2->numberOfAnalysisBands) ? 1 : 0;
237   result |= (hHdr1->timeStep != hHdr2->timeStep) ? 1 : 0;
238   result |= (hHdr1->sbrProcSmplRate != hHdr2->sbrProcSmplRate) ? 1 : 0;
239 
240   /* compare bitstream data */
241   result |=
242       FDKmemcmp(&hHdr1->bs_data, &hHdr2->bs_data, sizeof(SBR_HEADER_DATA_BS));
243   result |=
244       FDKmemcmp(&hHdr1->bs_dflt, &hHdr2->bs_dflt, sizeof(SBR_HEADER_DATA_BS));
245   result |= FDKmemcmp(&hHdr1->bs_info, &hHdr2->bs_info,
246                       sizeof(SBR_HEADER_DATA_BS_INFO));
247 
248   /* compare frequency band data */
249   result |= FDKmemcmp(&hHdr1->freqBandData, &hHdr2->freqBandData,
250                       (8 + MAX_NUM_LIMITERS + 1) * sizeof(UCHAR));
251   result |= FDKmemcmp(hHdr1->freqBandData.freqBandTableLo,
252                       hHdr2->freqBandData.freqBandTableLo,
253                       (MAX_FREQ_COEFFS / 2 + 1) * sizeof(UCHAR));
254   result |= FDKmemcmp(hHdr1->freqBandData.freqBandTableHi,
255                       hHdr2->freqBandData.freqBandTableHi,
256                       (MAX_FREQ_COEFFS + 1) * sizeof(UCHAR));
257   result |= FDKmemcmp(hHdr1->freqBandData.freqBandTableNoise,
258                       hHdr2->freqBandData.freqBandTableNoise,
259                       (MAX_NOISE_COEFFS + 1) * sizeof(UCHAR));
260   result |=
261       FDKmemcmp(hHdr1->freqBandData.v_k_master, hHdr2->freqBandData.v_k_master,
262                 (MAX_FREQ_COEFFS + 1) * sizeof(UCHAR));
263 
264   return result;
265 }
266 
267 /*!
268   \brief Reset SBR decoder.
269 
270   Reset should only be called if SBR has been sucessfully detected by
271   an appropriate checkForPayload() function.
272 
273   \return Error code.
274 */
sbrDecoder_ResetElement(HANDLE_SBRDECODER self,int sampleRateIn,int sampleRateOut,int samplesPerFrame,const MP4_ELEMENT_ID elementID,const int elementIndex,const int overlap)275 static SBR_ERROR sbrDecoder_ResetElement(HANDLE_SBRDECODER self,
276                                          int sampleRateIn, int sampleRateOut,
277                                          int samplesPerFrame,
278                                          const MP4_ELEMENT_ID elementID,
279                                          const int elementIndex,
280                                          const int overlap) {
281   SBR_ERROR sbrError = SBRDEC_OK;
282   HANDLE_SBR_HEADER_DATA hSbrHeader;
283   UINT qmfFlags = 0;
284 
285   int i, synDownsampleFac;
286 
287   /* USAC: assuming theoretical case 8 kHz output sample rate with 4:1 SBR */
288   const int sbr_min_sample_rate_in = IS_USAC(self->coreCodec) ? 2000 : 6400;
289 
290   /* Check in/out samplerates */
291   if (sampleRateIn < sbr_min_sample_rate_in || sampleRateIn > (96000)) {
292     sbrError = SBRDEC_UNSUPPORTED_CONFIG;
293     goto bail;
294   }
295 
296   if (sampleRateOut > (96000)) {
297     sbrError = SBRDEC_UNSUPPORTED_CONFIG;
298     goto bail;
299   }
300 
301   /* Set QMF mode flags */
302   if (self->flags & SBRDEC_LOW_POWER) qmfFlags |= QMF_FLAG_LP;
303 
304   if (self->coreCodec == AOT_ER_AAC_ELD) {
305     if (self->flags & SBRDEC_LD_MPS_QMF) {
306       qmfFlags |= QMF_FLAG_MPSLDFB;
307     } else {
308       qmfFlags |= QMF_FLAG_CLDFB;
309     }
310   }
311 
312   /* Set downsampling factor for synthesis filter bank */
313   if (sampleRateOut == 0) {
314     /* no single rate mode */
315     sampleRateOut =
316         sampleRateIn
317         << 1; /* In case of implicit signalling, assume dual rate SBR */
318   }
319 
320   if (sampleRateIn == sampleRateOut) {
321     synDownsampleFac = 2;
322     self->flags |= SBRDEC_DOWNSAMPLE;
323   } else {
324     synDownsampleFac = 1;
325     self->flags &= ~SBRDEC_DOWNSAMPLE;
326   }
327 
328   self->synDownsampleFac = synDownsampleFac;
329   self->sampleRateOut = sampleRateOut;
330 
331   {
332     for (i = 0; i < (1) + 1; i++) {
333       int setDflt;
334       hSbrHeader = &(self->sbrHeader[elementIndex][i]);
335       setDflt = ((hSbrHeader->syncState == SBR_NOT_INITIALIZED) ||
336                  (self->flags & SBRDEC_FORCE_RESET))
337                     ? 1
338                     : 0;
339 
340       /* init a default header such that we can at least do upsampling later */
341       sbrError = initHeaderData(hSbrHeader, sampleRateIn, sampleRateOut,
342                                 self->downscaleFactor, samplesPerFrame,
343                                 self->flags, setDflt);
344 
345       /* Set synchState to UPSAMPLING in case it already is initialized */
346       hSbrHeader->syncState = hSbrHeader->syncState > UPSAMPLING
347                                   ? UPSAMPLING
348                                   : hSbrHeader->syncState;
349     }
350   }
351 
352   if (sbrError != SBRDEC_OK) {
353     goto bail;
354   }
355 
356   if (!self->pQmfDomain->globalConf.qmfDomainExplicitConfig) {
357     self->pQmfDomain->globalConf.flags_requested |= qmfFlags;
358     self->pQmfDomain->globalConf.nBandsAnalysis_requested =
359         self->sbrHeader[elementIndex][0].numberOfAnalysisBands;
360     self->pQmfDomain->globalConf.nBandsSynthesis_requested =
361         (synDownsampleFac == 1) ? 64 : 32; /* may be overwritten by MPS */
362     self->pQmfDomain->globalConf.nBandsSynthesis_requested /=
363         self->downscaleFactor;
364     self->pQmfDomain->globalConf.nQmfTimeSlots_requested =
365         self->sbrHeader[elementIndex][0].numberTimeSlots *
366         self->sbrHeader[elementIndex][0].timeStep;
367     self->pQmfDomain->globalConf.nQmfOvTimeSlots_requested = overlap;
368     self->pQmfDomain->globalConf.nQmfProcBands_requested = 64; /* always 64 */
369     self->pQmfDomain->globalConf.nQmfProcChannels_requested =
370         1; /* may be overwritten by MPS */
371   }
372 
373   /* Init SBR channels going to be assigned to a SBR element */
374   {
375     int ch;
376     for (ch = 0; ch < self->pSbrElement[elementIndex]->nChannels; ch++) {
377       int headerIndex =
378           getHeaderSlot(self->pSbrElement[elementIndex]->useFrameSlot,
379                         self->pSbrElement[elementIndex]->useHeaderSlot);
380 
381       /* and create sbrDec */
382       sbrError =
383           createSbrDec(self->pSbrElement[elementIndex]->pSbrChannel[ch],
384                        &self->sbrHeader[elementIndex][headerIndex],
385                        &self->pSbrElement[elementIndex]->transposerSettings,
386                        synDownsampleFac, qmfFlags, self->flags, overlap, ch,
387                        self->codecFrameSize);
388 
389       if (sbrError != SBRDEC_OK) {
390         goto bail;
391       }
392     }
393   }
394 
395   // FDKmemclear(sbr_OverlapBuffer, sizeof(sbr_OverlapBuffer));
396 
397   if (self->numSbrElements == 1) {
398     switch (self->coreCodec) {
399       case AOT_AAC_LC:
400       case AOT_SBR:
401       case AOT_PS:
402       case AOT_ER_AAC_SCAL:
403       case AOT_DRM_AAC:
404       case AOT_DRM_SURROUND:
405         if (CreatePsDec(&self->hParametricStereoDec, samplesPerFrame)) {
406           sbrError = SBRDEC_CREATE_ERROR;
407           goto bail;
408         }
409         break;
410       default:
411         break;
412     }
413   }
414 
415   /* Init frame delay slot handling */
416   self->pSbrElement[elementIndex]->useFrameSlot = 0;
417   for (i = 0; i < ((1) + 1); i++) {
418     self->pSbrElement[elementIndex]->useHeaderSlot[i] = i;
419   }
420 
421 bail:
422 
423   return sbrError;
424 }
425 
426 /*!
427   \brief Assign QMF domain provided QMF channels to SBR channels.
428 
429   \return void
430 */
sbrDecoder_AssignQmfChannels2SbrChannels(HANDLE_SBRDECODER self)431 static void sbrDecoder_AssignQmfChannels2SbrChannels(HANDLE_SBRDECODER self) {
432   int ch, el, absCh_offset = 0;
433   for (el = 0; el < self->numSbrElements; el++) {
434     if (self->pSbrElement[el] != NULL) {
435       for (ch = 0; ch < self->pSbrElement[el]->nChannels; ch++) {
436         FDK_ASSERT(((absCh_offset + ch) < ((8) + (1))) &&
437                    ((absCh_offset + ch) < ((8) + (1))));
438         self->pSbrElement[el]->pSbrChannel[ch]->SbrDec.qmfDomainInCh =
439             &self->pQmfDomain->QmfDomainIn[absCh_offset + ch];
440         self->pSbrElement[el]->pSbrChannel[ch]->SbrDec.qmfDomainOutCh =
441             &self->pQmfDomain->QmfDomainOut[absCh_offset + ch];
442       }
443       absCh_offset += self->pSbrElement[el]->nChannels;
444     }
445   }
446 }
447 
sbrDecoder_Open(HANDLE_SBRDECODER * pSelf,HANDLE_FDK_QMF_DOMAIN pQmfDomain)448 SBR_ERROR sbrDecoder_Open(HANDLE_SBRDECODER *pSelf,
449                           HANDLE_FDK_QMF_DOMAIN pQmfDomain) {
450   HANDLE_SBRDECODER self = NULL;
451   SBR_ERROR sbrError = SBRDEC_OK;
452   int elIdx;
453 
454   if ((pSelf == NULL) || (pQmfDomain == NULL)) {
455     return SBRDEC_INVALID_ARGUMENT;
456   }
457 
458   /* Get memory for this instance */
459   self = GetRam_SbrDecoder();
460   if (self == NULL) {
461     sbrError = SBRDEC_MEM_ALLOC_FAILED;
462     goto bail;
463   }
464 
465   self->pQmfDomain = pQmfDomain;
466 
467   /*
468   Already zero because of calloc
469   self->numSbrElements = 0;
470   self->numSbrChannels = 0;
471   self->codecFrameSize = 0;
472   */
473 
474   self->numDelayFrames = (1); /* set to the max value by default */
475 
476   /* Initialize header sync state */
477   for (elIdx = 0; elIdx < (8); elIdx += 1) {
478     int i;
479     for (i = 0; i < (1) + 1; i += 1) {
480       self->sbrHeader[elIdx][i].syncState = SBR_NOT_INITIALIZED;
481     }
482   }
483 
484   *pSelf = self;
485 
486 bail:
487   return sbrError;
488 }
489 
490 /**
491  * \brief determine if the given core codec AOT can be processed or not.
492  * \param coreCodec core codec audio object type.
493  * \return 1 if SBR can be processed, 0 if SBR cannot be processed/applied.
494  */
sbrDecoder_isCoreCodecValid(AUDIO_OBJECT_TYPE coreCodec)495 static int sbrDecoder_isCoreCodecValid(AUDIO_OBJECT_TYPE coreCodec) {
496   switch (coreCodec) {
497     case AOT_AAC_LC:
498     case AOT_SBR:
499     case AOT_PS:
500     case AOT_ER_AAC_SCAL:
501     case AOT_ER_AAC_ELD:
502     case AOT_DRM_AAC:
503     case AOT_DRM_SURROUND:
504     case AOT_USAC:
505       return 1;
506     default:
507       return 0;
508   }
509 }
510 
sbrDecoder_DestroyElement(HANDLE_SBRDECODER self,const int elementIndex)511 static void sbrDecoder_DestroyElement(HANDLE_SBRDECODER self,
512                                       const int elementIndex) {
513   if (self->pSbrElement[elementIndex] != NULL) {
514     int ch;
515 
516     for (ch = 0; ch < SBRDEC_MAX_CH_PER_ELEMENT; ch++) {
517       if (self->pSbrElement[elementIndex]->pSbrChannel[ch] != NULL) {
518         deleteSbrDec(self->pSbrElement[elementIndex]->pSbrChannel[ch]);
519         FreeRam_SbrDecChannel(
520             &self->pSbrElement[elementIndex]->pSbrChannel[ch]);
521         self->numSbrChannels -= 1;
522       }
523     }
524     FreeRam_SbrDecElement(&self->pSbrElement[elementIndex]);
525     self->numSbrElements -= 1;
526   }
527 }
528 
sbrDecoder_InitElement(HANDLE_SBRDECODER self,const int sampleRateIn,const int sampleRateOut,const int samplesPerFrame,const AUDIO_OBJECT_TYPE coreCodec,const MP4_ELEMENT_ID elementID,const int elementIndex,const UCHAR harmonicSBR,const UCHAR stereoConfigIndex,const UCHAR configMode,UCHAR * configChanged,const INT downscaleFactor)529 SBR_ERROR sbrDecoder_InitElement(
530     HANDLE_SBRDECODER self, const int sampleRateIn, const int sampleRateOut,
531     const int samplesPerFrame, const AUDIO_OBJECT_TYPE coreCodec,
532     const MP4_ELEMENT_ID elementID, const int elementIndex,
533     const UCHAR harmonicSBR, const UCHAR stereoConfigIndex,
534     const UCHAR configMode, UCHAR *configChanged, const INT downscaleFactor) {
535   SBR_ERROR sbrError = SBRDEC_OK;
536   int chCnt = 0;
537   int nSbrElementsStart;
538   int nSbrChannelsStart;
539   if (self == NULL) {
540     return SBRDEC_INVALID_ARGUMENT;
541   }
542 
543   nSbrElementsStart = self->numSbrElements;
544   nSbrChannelsStart = self->numSbrChannels;
545 
546   /* Check core codec AOT */
547   if (!sbrDecoder_isCoreCodecValid(coreCodec) || elementIndex >= (8)) {
548     sbrError = SBRDEC_UNSUPPORTED_CONFIG;
549     goto bail;
550   }
551 
552   if (elementID != ID_SCE && elementID != ID_CPE && elementID != ID_LFE) {
553     sbrError = SBRDEC_UNSUPPORTED_CONFIG;
554     goto bail;
555   }
556 
557   if (self->sampleRateIn == sampleRateIn &&
558       self->codecFrameSize == samplesPerFrame && self->coreCodec == coreCodec &&
559       self->pSbrElement[elementIndex] != NULL &&
560       self->pSbrElement[elementIndex]->elementID == elementID &&
561       !(self->flags & SBRDEC_FORCE_RESET) &&
562       ((sampleRateOut == 0) ? 1 : (self->sampleRateOut == sampleRateOut)) &&
563       ((harmonicSBR == 2) ? 1
564                           : (self->harmonicSBR ==
565                              harmonicSBR)) /* The value 2 signalizes that
566                                               harmonicSBR shall be ignored in
567                                               the config change detection */
568   ) {
569     /* Nothing to do */
570     return SBRDEC_OK;
571   } else {
572     if (configMode & AC_CM_DET_CFG_CHANGE) {
573       *configChanged = 1;
574     }
575   }
576 
577   /* reaching this point the SBR-decoder gets (re-)configured */
578 
579   /* The flags field is used for all elements! */
580   self->flags &=
581       (SBRDEC_FORCE_RESET | SBRDEC_FLUSH); /* Keep the global flags. They will
582                                               be reset after decoding. */
583   self->flags |= (downscaleFactor > 1) ? SBRDEC_ELD_DOWNSCALE : 0;
584   self->flags |= (coreCodec == AOT_ER_AAC_ELD) ? SBRDEC_ELD_GRID : 0;
585   self->flags |= (coreCodec == AOT_ER_AAC_SCAL) ? SBRDEC_SYNTAX_SCAL : 0;
586   self->flags |=
587       (coreCodec == AOT_DRM_AAC) ? SBRDEC_SYNTAX_SCAL | SBRDEC_SYNTAX_DRM : 0;
588   self->flags |= (coreCodec == AOT_DRM_SURROUND)
589                      ? SBRDEC_SYNTAX_SCAL | SBRDEC_SYNTAX_DRM
590                      : 0;
591   self->flags |= (coreCodec == AOT_USAC) ? SBRDEC_SYNTAX_USAC : 0;
592   /* Robustness: Take integer division rounding into consideration. E.g. 22050
593    * Hz with 4:1 SBR => 5512 Hz core sampling rate. */
594   self->flags |= (sampleRateIn == sampleRateOut / 4) ? SBRDEC_QUAD_RATE : 0;
595   self->flags |= (harmonicSBR == 1) ? SBRDEC_USAC_HARMONICSBR : 0;
596 
597   if (configMode & AC_CM_DET_CFG_CHANGE) {
598     return SBRDEC_OK;
599   }
600 
601   self->sampleRateIn = sampleRateIn;
602   self->codecFrameSize = samplesPerFrame;
603   self->coreCodec = coreCodec;
604   self->harmonicSBR = harmonicSBR;
605   self->downscaleFactor = downscaleFactor;
606 
607   /* Init SBR elements */
608   {
609     int elChannels, ch;
610 
611     if (self->pSbrElement[elementIndex] == NULL) {
612       self->pSbrElement[elementIndex] = GetRam_SbrDecElement(elementIndex);
613       if (self->pSbrElement[elementIndex] == NULL) {
614         sbrError = SBRDEC_MEM_ALLOC_FAILED;
615         goto bail;
616       }
617       self->numSbrElements++;
618     } else {
619       self->numSbrChannels -= self->pSbrElement[elementIndex]->nChannels;
620     }
621 
622     /* Save element ID for sanity checks and to have a fallback for concealment.
623      */
624     self->pSbrElement[elementIndex]->elementID = elementID;
625 
626     /* Determine amount of channels for this element */
627     switch (elementID) {
628       case ID_NONE:
629       case ID_CPE:
630         elChannels = 2;
631         break;
632       case ID_LFE:
633       case ID_SCE:
634         elChannels = 1;
635         break;
636       default:
637         elChannels = 0;
638         break;
639     }
640 
641     /* Handle case of Parametric Stereo */
642     if (elementIndex == 0 && elementID == ID_SCE) {
643       switch (coreCodec) {
644         case AOT_AAC_LC:
645         case AOT_SBR:
646         case AOT_PS:
647         case AOT_ER_AAC_SCAL:
648         case AOT_DRM_AAC:
649         case AOT_DRM_SURROUND:
650           elChannels = 2;
651           break;
652         default:
653           break;
654       }
655     }
656 
657     /* Sanity check to avoid memory leaks */
658     if (elChannels < self->pSbrElement[elementIndex]->nChannels) {
659       self->numSbrChannels += self->pSbrElement[elementIndex]->nChannels;
660       sbrError = SBRDEC_PARSE_ERROR;
661       goto bail;
662     }
663 
664     self->pSbrElement[elementIndex]->nChannels = elChannels;
665 
666     for (ch = 0; ch < elChannels; ch++) {
667       if (self->pSbrElement[elementIndex]->pSbrChannel[ch] == NULL) {
668         self->pSbrElement[elementIndex]->pSbrChannel[ch] =
669             GetRam_SbrDecChannel(chCnt);
670         if (self->pSbrElement[elementIndex]->pSbrChannel[ch] == NULL) {
671           sbrError = SBRDEC_MEM_ALLOC_FAILED;
672           goto bail;
673         }
674       }
675       self->numSbrChannels++;
676 
677       sbrDecoder_drcInitChannel(&self->pSbrElement[elementIndex]
678                                      ->pSbrChannel[ch]
679                                      ->SbrDec.sbrDrcChannel);
680 
681       chCnt++;
682     }
683   }
684 
685   if (!self->pQmfDomain->globalConf.qmfDomainExplicitConfig) {
686     self->pQmfDomain->globalConf.nInputChannels_requested =
687         self->numSbrChannels;
688     self->pQmfDomain->globalConf.nOutputChannels_requested =
689         fMax((INT)self->numSbrChannels,
690              (INT)self->pQmfDomain->globalConf.nOutputChannels_requested);
691   }
692 
693   /* Make sure each SBR channel has one QMF channel assigned even if
694    * numSbrChannels or element set-up has changed. */
695   sbrDecoder_AssignQmfChannels2SbrChannels(self);
696 
697   /* clear error flags for all delay slots */
698   FDKmemclear(self->pSbrElement[elementIndex]->frameErrorFlag,
699               ((1) + 1) * sizeof(UCHAR));
700 
701   {
702     int overlap;
703 
704     if (coreCodec == AOT_ER_AAC_ELD) {
705       overlap = 0;
706     } else if (self->flags & SBRDEC_QUAD_RATE) {
707       overlap = (3 * 4);
708     } else {
709       overlap = (3 * 2);
710     }
711     /* Initialize this instance */
712     sbrError = sbrDecoder_ResetElement(self, sampleRateIn, sampleRateOut,
713                                        samplesPerFrame, elementID, elementIndex,
714                                        overlap);
715   }
716 
717 bail:
718   if (sbrError != SBRDEC_OK) {
719     if ((nSbrElementsStart < self->numSbrElements) ||
720         (nSbrChannelsStart < self->numSbrChannels)) {
721       /* Free the memory allocated for this element */
722       sbrDecoder_DestroyElement(self, elementIndex);
723     } else if ((elementIndex < (8)) &&
724                (self->pSbrElement[elementIndex] !=
725                 NULL)) { /* Set error flag to trigger concealment */
726       setFrameErrorFlag(self->pSbrElement[elementIndex], FRAME_ERROR);
727     }
728   }
729 
730   return sbrError;
731 }
732 
733 /**
734  * \brief Free config dependent SBR memory.
735  * \param self SBR decoder instance handle
736  */
sbrDecoder_FreeMem(HANDLE_SBRDECODER * self)737 SBR_ERROR sbrDecoder_FreeMem(HANDLE_SBRDECODER *self) {
738   int i;
739   int elIdx;
740 
741   if (self != NULL && *self != NULL) {
742     for (i = 0; i < (8); i++) {
743       sbrDecoder_DestroyElement(*self, i);
744     }
745 
746     for (elIdx = 0; elIdx < (8); elIdx += 1) {
747       for (i = 0; i < (1) + 1; i += 1) {
748         (*self)->sbrHeader[elIdx][i].syncState = SBR_NOT_INITIALIZED;
749       }
750     }
751   }
752 
753   return SBRDEC_OK;
754 }
755 
756 /**
757  * \brief Apply decoded SBR header for one element.
758  * \param self SBR decoder instance handle
759  * \param hSbrHeader SBR header handle to be processed.
760  * \param hSbrChannel pointer array to the SBR element channels corresponding to
761  * the SBR header.
762  * \param headerStatus header status value returned from SBR header parser.
763  * \param numElementChannels amount of channels for the SBR element whos header
764  * is to be processed.
765  */
sbrDecoder_HeaderUpdate(HANDLE_SBRDECODER self,HANDLE_SBR_HEADER_DATA hSbrHeader,SBR_HEADER_STATUS headerStatus,HANDLE_SBR_CHANNEL hSbrChannel[],const int numElementChannels)766 static SBR_ERROR sbrDecoder_HeaderUpdate(HANDLE_SBRDECODER self,
767                                          HANDLE_SBR_HEADER_DATA hSbrHeader,
768                                          SBR_HEADER_STATUS headerStatus,
769                                          HANDLE_SBR_CHANNEL hSbrChannel[],
770                                          const int numElementChannels) {
771   SBR_ERROR errorStatus = SBRDEC_OK;
772 
773   /*
774     change of control data, reset decoder
775   */
776   errorStatus = resetFreqBandTables(hSbrHeader, self->flags);
777 
778   if (errorStatus == SBRDEC_OK) {
779     if (hSbrHeader->syncState == UPSAMPLING && headerStatus != HEADER_RESET) {
780 #if (SBRDEC_MAX_HB_FADE_FRAMES > 0)
781       int ch;
782       for (ch = 0; ch < numElementChannels; ch += 1) {
783         hSbrChannel[ch]->SbrDec.highBandFadeCnt = SBRDEC_MAX_HB_FADE_FRAMES;
784       }
785 
786 #endif
787       /* As the default header would limit the frequency range,
788          lowSubband and highSubband must be patched. */
789       hSbrHeader->freqBandData.lowSubband = hSbrHeader->numberOfAnalysisBands;
790       hSbrHeader->freqBandData.highSubband = hSbrHeader->numberOfAnalysisBands;
791     }
792 
793     /* Trigger a reset before processing this slot */
794     hSbrHeader->status |= SBRDEC_HDR_STAT_RESET;
795   }
796 
797   return errorStatus;
798 }
799 
sbrDecoder_Header(HANDLE_SBRDECODER self,HANDLE_FDK_BITSTREAM hBs,const INT sampleRateIn,const INT sampleRateOut,const INT samplesPerFrame,const AUDIO_OBJECT_TYPE coreCodec,const MP4_ELEMENT_ID elementID,const INT elementIndex,const UCHAR harmonicSBR,const UCHAR stereoConfigIndex,const UCHAR configMode,UCHAR * configChanged,const INT downscaleFactor)800 INT sbrDecoder_Header(HANDLE_SBRDECODER self, HANDLE_FDK_BITSTREAM hBs,
801                       const INT sampleRateIn, const INT sampleRateOut,
802                       const INT samplesPerFrame,
803                       const AUDIO_OBJECT_TYPE coreCodec,
804                       const MP4_ELEMENT_ID elementID, const INT elementIndex,
805                       const UCHAR harmonicSBR, const UCHAR stereoConfigIndex,
806                       const UCHAR configMode, UCHAR *configChanged,
807                       const INT downscaleFactor) {
808   SBR_HEADER_STATUS headerStatus;
809   HANDLE_SBR_HEADER_DATA hSbrHeader;
810   SBR_ERROR sbrError = SBRDEC_OK;
811   int headerIndex;
812   UINT flagsSaved =
813       0; /* flags should not be changed in AC_CM_DET_CFG_CHANGE - mode after
814             parsing */
815 
816   if (self == NULL || elementIndex >= (8)) {
817     return SBRDEC_UNSUPPORTED_CONFIG;
818   }
819 
820   if (!sbrDecoder_isCoreCodecValid(coreCodec)) {
821     return SBRDEC_UNSUPPORTED_CONFIG;
822   }
823 
824   if (configMode & AC_CM_DET_CFG_CHANGE) {
825     flagsSaved = self->flags; /* store */
826   }
827 
828   sbrError = sbrDecoder_InitElement(
829       self, sampleRateIn, sampleRateOut, samplesPerFrame, coreCodec, elementID,
830       elementIndex, harmonicSBR, stereoConfigIndex, configMode, configChanged,
831       downscaleFactor);
832 
833   if ((sbrError != SBRDEC_OK) || (elementID == ID_LFE)) {
834     goto bail;
835   }
836 
837   if (configMode & AC_CM_DET_CFG_CHANGE) {
838     hSbrHeader = NULL;
839   } else {
840     headerIndex = getHeaderSlot(self->pSbrElement[elementIndex]->useFrameSlot,
841                                 self->pSbrElement[elementIndex]->useHeaderSlot);
842 
843     hSbrHeader = &(self->sbrHeader[elementIndex][headerIndex]);
844   }
845 
846   headerStatus = sbrGetHeaderData(hSbrHeader, hBs, self->flags, 0, configMode);
847 
848   if (coreCodec == AOT_USAC) {
849     if (configMode & AC_CM_DET_CFG_CHANGE) {
850       self->flags = flagsSaved; /* restore */
851     }
852     return sbrError;
853   }
854 
855   if (configMode & AC_CM_ALLOC_MEM) {
856     SBR_DECODER_ELEMENT *pSbrElement;
857 
858     pSbrElement = self->pSbrElement[elementIndex];
859 
860     /* Sanity check */
861     if (pSbrElement != NULL) {
862       if ((elementID == ID_CPE && pSbrElement->nChannels != 2) ||
863           (elementID != ID_CPE && pSbrElement->nChannels != 1)) {
864         return SBRDEC_UNSUPPORTED_CONFIG;
865       }
866       if (headerStatus == HEADER_RESET) {
867         sbrError = sbrDecoder_HeaderUpdate(self, hSbrHeader, headerStatus,
868                                            pSbrElement->pSbrChannel,
869                                            pSbrElement->nChannels);
870 
871         if (sbrError == SBRDEC_OK) {
872           hSbrHeader->syncState = SBR_HEADER;
873           hSbrHeader->status |= SBRDEC_HDR_STAT_UPDATE;
874         } else {
875           hSbrHeader->syncState = SBR_NOT_INITIALIZED;
876           hSbrHeader->status = HEADER_ERROR;
877         }
878       }
879     }
880   }
881 bail:
882   if (configMode & AC_CM_DET_CFG_CHANGE) {
883     self->flags = flagsSaved; /* restore */
884   }
885   return sbrError;
886 }
887 
sbrDecoder_SetParam(HANDLE_SBRDECODER self,const SBRDEC_PARAM param,const INT value)888 SBR_ERROR sbrDecoder_SetParam(HANDLE_SBRDECODER self, const SBRDEC_PARAM param,
889                               const INT value) {
890   SBR_ERROR errorStatus = SBRDEC_OK;
891 
892   /* configure the subsystems */
893   switch (param) {
894     case SBR_SYSTEM_BITSTREAM_DELAY:
895       if (value < 0 || value > (1)) {
896         errorStatus = SBRDEC_SET_PARAM_FAIL;
897         break;
898       }
899       if (self == NULL) {
900         errorStatus = SBRDEC_NOT_INITIALIZED;
901       } else {
902         self->numDelayFrames = (UCHAR)value;
903       }
904       break;
905     case SBR_QMF_MODE:
906       if (self == NULL) {
907         errorStatus = SBRDEC_NOT_INITIALIZED;
908       } else {
909         if (value == 1) {
910           self->flags |= SBRDEC_LOW_POWER;
911         } else {
912           self->flags &= ~SBRDEC_LOW_POWER;
913         }
914       }
915       break;
916     case SBR_LD_QMF_TIME_ALIGN:
917       if (self == NULL) {
918         errorStatus = SBRDEC_NOT_INITIALIZED;
919       } else {
920         if (value == 1) {
921           self->flags |= SBRDEC_LD_MPS_QMF;
922         } else {
923           self->flags &= ~SBRDEC_LD_MPS_QMF;
924         }
925       }
926       break;
927     case SBR_FLUSH_DATA:
928       if (value != 0) {
929         if (self == NULL) {
930           errorStatus = SBRDEC_NOT_INITIALIZED;
931         } else {
932           self->flags |= SBRDEC_FLUSH;
933         }
934       }
935       break;
936     case SBR_CLEAR_HISTORY:
937       if (value != 0) {
938         if (self == NULL) {
939           errorStatus = SBRDEC_NOT_INITIALIZED;
940         } else {
941           self->flags |= SBRDEC_FORCE_RESET;
942         }
943       }
944       break;
945     case SBR_BS_INTERRUPTION: {
946       int elementIndex;
947 
948       if (self == NULL) {
949         errorStatus = SBRDEC_NOT_INITIALIZED;
950         break;
951       }
952 
953       /* Loop over SBR elements */
954       for (elementIndex = 0; elementIndex < self->numSbrElements;
955            elementIndex++) {
956         if (self->pSbrElement[elementIndex] != NULL) {
957           HANDLE_SBR_HEADER_DATA hSbrHeader;
958           int headerIndex =
959               getHeaderSlot(self->pSbrElement[elementIndex]->useFrameSlot,
960                             self->pSbrElement[elementIndex]->useHeaderSlot);
961 
962           hSbrHeader = &(self->sbrHeader[elementIndex][headerIndex]);
963 
964           /* Set sync state UPSAMPLING for the corresponding slot.
965              This switches off bitstream parsing until a new header arrives. */
966           hSbrHeader->syncState = UPSAMPLING;
967           hSbrHeader->status |= SBRDEC_HDR_STAT_UPDATE;
968         }
969       }
970     } break;
971 
972     case SBR_SKIP_QMF:
973       if (self == NULL) {
974         errorStatus = SBRDEC_NOT_INITIALIZED;
975       } else {
976         if (value == 1) {
977           self->flags |= SBRDEC_SKIP_QMF_ANA;
978         } else {
979           self->flags &= ~SBRDEC_SKIP_QMF_ANA;
980         }
981         if (value == 2) {
982           self->flags |= SBRDEC_SKIP_QMF_SYN;
983         } else {
984           self->flags &= ~SBRDEC_SKIP_QMF_SYN;
985         }
986       }
987       break;
988     default:
989       errorStatus = SBRDEC_SET_PARAM_FAIL;
990       break;
991   } /* switch(param) */
992 
993   return (errorStatus);
994 }
995 
sbrDecoder_drcGetChannel(const HANDLE_SBRDECODER self,const INT channel)996 static SBRDEC_DRC_CHANNEL *sbrDecoder_drcGetChannel(
997     const HANDLE_SBRDECODER self, const INT channel) {
998   SBRDEC_DRC_CHANNEL *pSbrDrcChannelData = NULL;
999   int elementIndex, elChanIdx = 0, numCh = 0;
1000 
1001   for (elementIndex = 0; (elementIndex < (8)) && (numCh <= channel);
1002        elementIndex++) {
1003     SBR_DECODER_ELEMENT *pSbrElement = self->pSbrElement[elementIndex];
1004     int c, elChannels;
1005 
1006     elChanIdx = 0;
1007     if (pSbrElement == NULL) break;
1008 
1009     /* Determine amount of channels for this element */
1010     switch (pSbrElement->elementID) {
1011       case ID_CPE:
1012         elChannels = 2;
1013         break;
1014       case ID_LFE:
1015       case ID_SCE:
1016         elChannels = 1;
1017         break;
1018       case ID_NONE:
1019       default:
1020         elChannels = 0;
1021         break;
1022     }
1023 
1024     /* Limit with actual allocated element channels */
1025     elChannels = fMin(elChannels, pSbrElement->nChannels);
1026 
1027     for (c = 0; (c < elChannels) && (numCh <= channel); c++) {
1028       if (pSbrElement->pSbrChannel[elChanIdx] != NULL) {
1029         numCh++;
1030         elChanIdx++;
1031       }
1032     }
1033   }
1034   elementIndex -= 1;
1035   elChanIdx -= 1;
1036 
1037   if (elChanIdx < 0 || elementIndex < 0) {
1038     return NULL;
1039   }
1040 
1041   if (self->pSbrElement[elementIndex] != NULL) {
1042     if (self->pSbrElement[elementIndex]->pSbrChannel[elChanIdx] != NULL) {
1043       pSbrDrcChannelData = &self->pSbrElement[elementIndex]
1044                                 ->pSbrChannel[elChanIdx]
1045                                 ->SbrDec.sbrDrcChannel;
1046     }
1047   }
1048 
1049   return (pSbrDrcChannelData);
1050 }
1051 
sbrDecoder_drcFeedChannel(HANDLE_SBRDECODER self,INT ch,UINT numBands,FIXP_DBL * pNextFact_mag,INT nextFact_exp,SHORT drcInterpolationScheme,UCHAR winSequence,USHORT * pBandTop)1052 SBR_ERROR sbrDecoder_drcFeedChannel(HANDLE_SBRDECODER self, INT ch,
1053                                     UINT numBands, FIXP_DBL *pNextFact_mag,
1054                                     INT nextFact_exp,
1055                                     SHORT drcInterpolationScheme,
1056                                     UCHAR winSequence, USHORT *pBandTop) {
1057   SBRDEC_DRC_CHANNEL *pSbrDrcChannelData = NULL;
1058   int band, isValidData = 0;
1059 
1060   if (self == NULL) {
1061     return SBRDEC_NOT_INITIALIZED;
1062   }
1063   if (ch > (8) || pNextFact_mag == NULL) {
1064     return SBRDEC_SET_PARAM_FAIL;
1065   }
1066 
1067   /* Search for gain values different to 1.0f */
1068   for (band = 0; band < (int)numBands; band += 1) {
1069     if (!((pNextFact_mag[band] == FL2FXCONST_DBL(0.5)) &&
1070           (nextFact_exp == 1)) &&
1071         !((pNextFact_mag[band] == (FIXP_DBL)MAXVAL_DBL) &&
1072           (nextFact_exp == 0))) {
1073       isValidData = 1;
1074       break;
1075     }
1076   }
1077 
1078   /* Find the right SBR channel */
1079   pSbrDrcChannelData = sbrDecoder_drcGetChannel(self, ch);
1080 
1081   if (pSbrDrcChannelData != NULL) {
1082     if (pSbrDrcChannelData->enable ||
1083         isValidData) { /* Activate processing only with real and valid data */
1084       int i;
1085 
1086       pSbrDrcChannelData->enable = 1;
1087       pSbrDrcChannelData->numBandsNext = numBands;
1088 
1089       pSbrDrcChannelData->winSequenceNext = winSequence;
1090       pSbrDrcChannelData->drcInterpolationSchemeNext = drcInterpolationScheme;
1091       pSbrDrcChannelData->nextFact_exp = nextFact_exp;
1092 
1093       for (i = 0; i < (int)numBands; i++) {
1094         pSbrDrcChannelData->bandTopNext[i] = pBandTop[i];
1095         pSbrDrcChannelData->nextFact_mag[i] = pNextFact_mag[i];
1096       }
1097     }
1098   }
1099 
1100   return SBRDEC_OK;
1101 }
1102 
sbrDecoder_drcDisable(HANDLE_SBRDECODER self,INT ch)1103 void sbrDecoder_drcDisable(HANDLE_SBRDECODER self, INT ch) {
1104   SBRDEC_DRC_CHANNEL *pSbrDrcChannelData = NULL;
1105 
1106   if ((self == NULL) || (ch > (8)) || (self->numSbrElements == 0) ||
1107       (self->numSbrChannels == 0)) {
1108     return;
1109   }
1110 
1111   /* Find the right SBR channel */
1112   pSbrDrcChannelData = sbrDecoder_drcGetChannel(self, ch);
1113 
1114   if (pSbrDrcChannelData != NULL) {
1115     sbrDecoder_drcInitChannel(pSbrDrcChannelData);
1116   }
1117 }
1118 
sbrDecoder_Parse(HANDLE_SBRDECODER self,HANDLE_FDK_BITSTREAM hBs,UCHAR * pDrmBsBuffer,USHORT drmBsBufferSize,int * count,int bsPayLen,int crcFlag,MP4_ELEMENT_ID prevElement,int elementIndex,UINT acFlags,UINT acElFlags[])1119 SBR_ERROR sbrDecoder_Parse(HANDLE_SBRDECODER self, HANDLE_FDK_BITSTREAM hBs,
1120                            UCHAR *pDrmBsBuffer, USHORT drmBsBufferSize,
1121                            int *count, int bsPayLen, int crcFlag,
1122                            MP4_ELEMENT_ID prevElement, int elementIndex,
1123                            UINT acFlags, UINT acElFlags[]) {
1124   SBR_DECODER_ELEMENT *hSbrElement = NULL;
1125   HANDLE_SBR_HEADER_DATA hSbrHeader = NULL;
1126   HANDLE_SBR_CHANNEL *pSbrChannel;
1127 
1128   SBR_FRAME_DATA *hFrameDataLeft = NULL;
1129   SBR_FRAME_DATA *hFrameDataRight = NULL;
1130   SBR_FRAME_DATA frameDataLeftCopy;
1131   SBR_FRAME_DATA frameDataRightCopy;
1132 
1133   SBR_ERROR errorStatus = SBRDEC_OK;
1134   SBR_HEADER_STATUS headerStatus = HEADER_NOT_PRESENT;
1135 
1136   INT startPos = FDKgetValidBits(hBs);
1137   INT CRCLen = 0;
1138   HANDLE_FDK_BITSTREAM hBsOriginal = hBs;
1139   FDK_BITSTREAM bsBwd;
1140 
1141   FDK_CRCINFO crcInfo;
1142   INT crcReg = 0;
1143   USHORT drmSbrCrc = 0;
1144   const int fGlobalIndependencyFlag = acFlags & AC_INDEP;
1145   const int bs_pvc = acElFlags[elementIndex] & AC_EL_USAC_PVC;
1146   const int bs_interTes = acElFlags[elementIndex] & AC_EL_USAC_ITES;
1147   int stereo;
1148   int fDoDecodeSbrData = 1;
1149 
1150   int lastSlot, lastHdrSlot = 0, thisHdrSlot = 0;
1151 
1152   if (*count <= 0) {
1153     setFrameErrorFlag(self->pSbrElement[elementIndex], FRAME_ERROR);
1154     return SBRDEC_OK;
1155   }
1156 
1157   /* SBR sanity checks */
1158   if (self == NULL) {
1159     errorStatus = SBRDEC_NOT_INITIALIZED;
1160     goto bail;
1161   }
1162 
1163   /* Reverse bits of DRM SBR payload */
1164   if ((self->flags & SBRDEC_SYNTAX_DRM) && *count > 0) {
1165     int dataBytes, dataBits;
1166 
1167     FDK_ASSERT(drmBsBufferSize >= (512));
1168     dataBits = *count;
1169 
1170     if (dataBits > ((512) * 8)) {
1171       /* do not flip more data than needed */
1172       dataBits = (512) * 8;
1173     }
1174 
1175     dataBytes = (dataBits + 7) >> 3;
1176 
1177     int j;
1178 
1179     if ((j = (int)FDKgetValidBits(hBs)) != 8) {
1180       FDKpushBiDirectional(hBs, (j - 8));
1181     }
1182 
1183     j = 0;
1184     for (; dataBytes > 0; dataBytes--) {
1185       int i;
1186       UCHAR tmpByte;
1187       UCHAR buffer = 0x00;
1188 
1189       tmpByte = (UCHAR)FDKreadBits(hBs, 8);
1190       for (i = 0; i < 4; i++) {
1191         int shift = 2 * i + 1;
1192         buffer |= (tmpByte & (0x08 >> i)) << shift;
1193         buffer |= (tmpByte & (0x10 << i)) >> shift;
1194       }
1195       pDrmBsBuffer[j++] = buffer;
1196       FDKpushBack(hBs, 16);
1197     }
1198 
1199     FDKinitBitStream(&bsBwd, pDrmBsBuffer, (512), dataBits, BS_READER);
1200 
1201     /* Use reversed data */
1202     hBs = &bsBwd;
1203     bsPayLen = *count;
1204   }
1205 
1206   /* Remember start position of  SBR element */
1207   startPos = FDKgetValidBits(hBs);
1208 
1209   /* SBR sanity checks */
1210   if (self->pSbrElement[elementIndex] == NULL) {
1211     errorStatus = SBRDEC_NOT_INITIALIZED;
1212     goto bail;
1213   }
1214   hSbrElement = self->pSbrElement[elementIndex];
1215 
1216   lastSlot = (hSbrElement->useFrameSlot > 0) ? hSbrElement->useFrameSlot - 1
1217                                              : self->numDelayFrames;
1218   lastHdrSlot = hSbrElement->useHeaderSlot[lastSlot];
1219   thisHdrSlot = getHeaderSlot(
1220       hSbrElement->useFrameSlot,
1221       hSbrElement->useHeaderSlot); /* Get a free header slot not used by
1222                                       frames not processed yet. */
1223 
1224   /* Assign the free slot to store a new header if there is one. */
1225   hSbrHeader = &self->sbrHeader[elementIndex][thisHdrSlot];
1226 
1227   pSbrChannel = hSbrElement->pSbrChannel;
1228   stereo = (hSbrElement->elementID == ID_CPE) ? 1 : 0;
1229 
1230   hFrameDataLeft = &self->pSbrElement[elementIndex]
1231                         ->pSbrChannel[0]
1232                         ->frameData[hSbrElement->useFrameSlot];
1233   if (stereo) {
1234     hFrameDataRight = &self->pSbrElement[elementIndex]
1235                            ->pSbrChannel[1]
1236                            ->frameData[hSbrElement->useFrameSlot];
1237   }
1238 
1239   /* store frameData; new parsed frameData possibly corrupted */
1240   FDKmemcpy(&frameDataLeftCopy, hFrameDataLeft, sizeof(SBR_FRAME_DATA));
1241   if (stereo) {
1242     FDKmemcpy(&frameDataRightCopy, hFrameDataRight, sizeof(SBR_FRAME_DATA));
1243   }
1244 
1245   /* reset PS flag; will be set after PS was found */
1246   self->flags &= ~SBRDEC_PS_DECODED;
1247 
1248   if (hSbrHeader->status & SBRDEC_HDR_STAT_UPDATE) {
1249     /* Got a new header from extern (e.g. from an ASC) */
1250     headerStatus = HEADER_OK;
1251     hSbrHeader->status &= ~SBRDEC_HDR_STAT_UPDATE;
1252   } else if (thisHdrSlot != lastHdrSlot) {
1253     /* Copy the last header into this slot otherwise the
1254        header compare will trigger more HEADER_RESETs than needed. */
1255     copySbrHeader(hSbrHeader, &self->sbrHeader[elementIndex][lastHdrSlot]);
1256   }
1257 
1258   /*
1259      Check if bit stream data is valid and matches the element context
1260   */
1261   if (((prevElement != ID_SCE) && (prevElement != ID_CPE)) ||
1262       prevElement != hSbrElement->elementID) {
1263     /* In case of LFE we also land here, since there is no LFE SBR element (do
1264      * upsampling only) */
1265     fDoDecodeSbrData = 0;
1266   }
1267 
1268   if (fDoDecodeSbrData) {
1269     if ((INT)FDKgetValidBits(hBs) <= 0) {
1270       fDoDecodeSbrData = 0;
1271     }
1272   }
1273 
1274   /*
1275      SBR CRC-check
1276   */
1277   if (fDoDecodeSbrData) {
1278     if (crcFlag) {
1279       switch (self->coreCodec) {
1280         case AOT_ER_AAC_ELD:
1281           FDKpushFor(hBs, 10);
1282           /* check sbrcrc later: we don't know the payload length now */
1283           break;
1284         case AOT_DRM_AAC:
1285         case AOT_DRM_SURROUND:
1286           drmSbrCrc = (USHORT)FDKreadBits(hBs, 8);
1287           /* Setup CRC decoder */
1288           FDKcrcInit(&crcInfo, 0x001d, 0xFFFF, 8);
1289           /* Start CRC region */
1290           crcReg = FDKcrcStartReg(&crcInfo, hBs, 0);
1291           break;
1292         default:
1293           CRCLen = bsPayLen - 10; /* change: 0 => i */
1294           if (CRCLen < 0) {
1295             fDoDecodeSbrData = 0;
1296           } else {
1297             fDoDecodeSbrData = SbrCrcCheck(hBs, CRCLen);
1298           }
1299           break;
1300       }
1301     }
1302   } /* if (fDoDecodeSbrData) */
1303 
1304   /*
1305      Read in the header data and issue a reset if change occured
1306   */
1307   if (fDoDecodeSbrData) {
1308     int sbrHeaderPresent;
1309 
1310     if (self->flags & (SBRDEC_SYNTAX_RSVD50 | SBRDEC_SYNTAX_USAC)) {
1311       SBR_HEADER_DATA_BS_INFO newSbrInfo;
1312       int sbrInfoPresent;
1313 
1314       if (bs_interTes) {
1315         self->flags |= SBRDEC_USAC_ITES;
1316       } else {
1317         self->flags &= ~SBRDEC_USAC_ITES;
1318       }
1319 
1320       if (fGlobalIndependencyFlag) {
1321         self->flags |= SBRDEC_USAC_INDEP;
1322         sbrInfoPresent = 1;
1323         sbrHeaderPresent = 1;
1324       } else {
1325         self->flags &= ~SBRDEC_USAC_INDEP;
1326         sbrInfoPresent = FDKreadBit(hBs);
1327         if (sbrInfoPresent) {
1328           sbrHeaderPresent = FDKreadBit(hBs);
1329         } else {
1330           sbrHeaderPresent = 0;
1331         }
1332       }
1333 
1334       if (sbrInfoPresent) {
1335         newSbrInfo.ampResolution = FDKreadBit(hBs);
1336         newSbrInfo.xover_band = FDKreadBits(hBs, 4);
1337         newSbrInfo.sbr_preprocessing = FDKreadBit(hBs);
1338         if (bs_pvc) {
1339           newSbrInfo.pvc_mode = FDKreadBits(hBs, 2);
1340           /* bs_pvc_mode: 0 -> no PVC, 1 -> PVC mode 1, 2 -> PVC mode 2, 3 ->
1341            * reserved */
1342           if (newSbrInfo.pvc_mode > 2) {
1343             headerStatus = HEADER_ERROR;
1344           }
1345           if (stereo && newSbrInfo.pvc_mode > 0) {
1346             /* bs_pvc is always transmitted but pvc_mode is set to zero in case
1347              * of stereo SBR. The config might be wrong but we cannot tell for
1348              * sure. */
1349             newSbrInfo.pvc_mode = 0;
1350           }
1351         } else {
1352           newSbrInfo.pvc_mode = 0;
1353         }
1354         if (headerStatus != HEADER_ERROR) {
1355           if (FDKmemcmp(&hSbrHeader->bs_info, &newSbrInfo,
1356                         sizeof(SBR_HEADER_DATA_BS_INFO))) {
1357             /* in case of ampResolution and preprocessing change no full reset
1358              * required    */
1359             /* HEADER reset would trigger HBE transposer reset which breaks
1360              * eSbr_3_Eaa.mp4 */
1361             if ((hSbrHeader->bs_info.pvc_mode != newSbrInfo.pvc_mode) ||
1362                 (hSbrHeader->bs_info.xover_band != newSbrInfo.xover_band)) {
1363               headerStatus = HEADER_RESET;
1364             } else {
1365               headerStatus = HEADER_OK;
1366             }
1367 
1368             hSbrHeader->bs_info = newSbrInfo;
1369           } else {
1370             headerStatus = HEADER_OK;
1371           }
1372         }
1373       }
1374       if (headerStatus == HEADER_ERROR) {
1375         /* Corrupt SBR info data, do not decode and switch to UPSAMPLING */
1376         hSbrHeader->syncState = UPSAMPLING;
1377         fDoDecodeSbrData = 0;
1378         sbrHeaderPresent = 0;
1379       }
1380 
1381       if (sbrHeaderPresent && fDoDecodeSbrData) {
1382         int useDfltHeader;
1383 
1384         useDfltHeader = FDKreadBit(hBs);
1385 
1386         if (useDfltHeader) {
1387           sbrHeaderPresent = 0;
1388           if (FDKmemcmp(&hSbrHeader->bs_data, &hSbrHeader->bs_dflt,
1389                         sizeof(SBR_HEADER_DATA_BS)) ||
1390               hSbrHeader->syncState != SBR_ACTIVE) {
1391             hSbrHeader->bs_data = hSbrHeader->bs_dflt;
1392             headerStatus = HEADER_RESET;
1393           }
1394         }
1395       }
1396     } else {
1397       sbrHeaderPresent = FDKreadBit(hBs);
1398     }
1399 
1400     if (sbrHeaderPresent) {
1401       headerStatus = sbrGetHeaderData(hSbrHeader, hBs, self->flags, 1, 0);
1402     }
1403 
1404     if (headerStatus == HEADER_RESET) {
1405       errorStatus = sbrDecoder_HeaderUpdate(
1406           self, hSbrHeader, headerStatus, pSbrChannel, hSbrElement->nChannels);
1407 
1408       if (errorStatus == SBRDEC_OK) {
1409         hSbrHeader->syncState = SBR_HEADER;
1410       } else {
1411         hSbrHeader->syncState = SBR_NOT_INITIALIZED;
1412         headerStatus = HEADER_ERROR;
1413       }
1414     }
1415 
1416     if (errorStatus != SBRDEC_OK) {
1417       fDoDecodeSbrData = 0;
1418     }
1419   } /* if (fDoDecodeSbrData) */
1420 
1421   /*
1422     Print debugging output only if state has changed
1423   */
1424 
1425   /* read frame data */
1426   if ((hSbrHeader->syncState >= SBR_HEADER) && fDoDecodeSbrData) {
1427     int sbrFrameOk;
1428     /* read the SBR element data */
1429     if (!stereo && (self->hParametricStereoDec != NULL)) {
1430       /* update slot index for PS bitstream parsing */
1431       self->hParametricStereoDec->bsLastSlot =
1432           self->hParametricStereoDec->bsReadSlot;
1433       self->hParametricStereoDec->bsReadSlot = hSbrElement->useFrameSlot;
1434     }
1435     sbrFrameOk = sbrGetChannelElement(
1436         hSbrHeader, hFrameDataLeft, (stereo) ? hFrameDataRight : NULL,
1437         &pSbrChannel[0]->prevFrameData,
1438         pSbrChannel[0]->SbrDec.PvcStaticData.pvc_mode_last, hBs,
1439         (stereo) ? NULL : self->hParametricStereoDec, self->flags,
1440         self->pSbrElement[elementIndex]->transposerSettings.overlap);
1441 
1442     if (!sbrFrameOk) {
1443       fDoDecodeSbrData = 0;
1444     } else {
1445       INT valBits;
1446 
1447       if (bsPayLen > 0) {
1448         valBits = bsPayLen - ((INT)startPos - (INT)FDKgetValidBits(hBs));
1449       } else {
1450         valBits = (INT)FDKgetValidBits(hBs);
1451       }
1452 
1453       if (crcFlag) {
1454         switch (self->coreCodec) {
1455           case AOT_ER_AAC_ELD: {
1456             /* late crc check for eld */
1457             INT payloadbits =
1458                 (INT)startPos - (INT)FDKgetValidBits(hBs) - startPos;
1459             INT crcLen = payloadbits - 10;
1460             FDKpushBack(hBs, payloadbits);
1461             fDoDecodeSbrData = SbrCrcCheck(hBs, crcLen);
1462             FDKpushFor(hBs, crcLen);
1463           } break;
1464           case AOT_DRM_AAC:
1465           case AOT_DRM_SURROUND:
1466             /* End CRC region */
1467             FDKcrcEndReg(&crcInfo, hBs, crcReg);
1468             /* Check CRC */
1469             if ((FDKcrcGetCRC(&crcInfo) ^ 0xFF) != drmSbrCrc) {
1470               fDoDecodeSbrData = 0;
1471               if (headerStatus != HEADER_NOT_PRESENT) {
1472                 headerStatus = HEADER_ERROR;
1473                 hSbrHeader->syncState = SBR_NOT_INITIALIZED;
1474               }
1475             }
1476             break;
1477           default:
1478             break;
1479         }
1480       }
1481 
1482       /* sanity check of remaining bits */
1483       if (valBits < 0) {
1484         fDoDecodeSbrData = 0;
1485       } else {
1486         switch (self->coreCodec) {
1487           case AOT_SBR:
1488           case AOT_PS:
1489           case AOT_AAC_LC: {
1490             /* This sanity check is only meaningful with General Audio
1491              * bitstreams */
1492             int alignBits = valBits & 0x7;
1493 
1494             if (valBits > alignBits) {
1495               fDoDecodeSbrData = 0;
1496             }
1497           } break;
1498           default:
1499             /* No sanity check available */
1500             break;
1501         }
1502       }
1503     }
1504   } else {
1505     /* The returned bit count will not be the actual payload size since we did
1506        not parse the frame data. Return an error so that the caller can react
1507        respectively. */
1508     errorStatus = SBRDEC_PARSE_ERROR;
1509   }
1510 
1511   if (!fDoDecodeSbrData) {
1512     /* Set error flag for this slot to trigger concealment */
1513     setFrameErrorFlag(self->pSbrElement[elementIndex], FRAME_ERROR);
1514     /* restore old frameData for concealment */
1515     FDKmemcpy(hFrameDataLeft, &frameDataLeftCopy, sizeof(SBR_FRAME_DATA));
1516     if (stereo) {
1517       FDKmemcpy(hFrameDataRight, &frameDataRightCopy, sizeof(SBR_FRAME_DATA));
1518     }
1519     errorStatus = SBRDEC_PARSE_ERROR;
1520   } else {
1521     /* Everything seems to be ok so clear the error flag */
1522     setFrameErrorFlag(self->pSbrElement[elementIndex], FRAME_OK);
1523   }
1524 
1525   if (!stereo) {
1526     /* Turn coupling off explicitely to avoid access to absent right frame data
1527        that might occur with corrupt bitstreams. */
1528     hFrameDataLeft->coupling = COUPLING_OFF;
1529   }
1530 
1531 bail:
1532 
1533   if (self != NULL) {
1534     if (self->flags & SBRDEC_SYNTAX_DRM) {
1535       hBs = hBsOriginal;
1536     }
1537 
1538     if (errorStatus != SBRDEC_NOT_INITIALIZED) {
1539       int useOldHdr =
1540           ((headerStatus == HEADER_NOT_PRESENT) ||
1541            (headerStatus == HEADER_ERROR) ||
1542            (headerStatus == HEADER_RESET && errorStatus == SBRDEC_PARSE_ERROR))
1543               ? 1
1544               : 0;
1545 
1546       if (!useOldHdr && (thisHdrSlot != lastHdrSlot) && (hSbrHeader != NULL)) {
1547         useOldHdr |=
1548             (compareSbrHeader(hSbrHeader,
1549                               &self->sbrHeader[elementIndex][lastHdrSlot]) == 0)
1550                 ? 1
1551                 : 0;
1552       }
1553 
1554       if (hSbrElement != NULL) {
1555         if (useOldHdr != 0) {
1556           /* Use the old header for this frame */
1557           hSbrElement->useHeaderSlot[hSbrElement->useFrameSlot] = lastHdrSlot;
1558         } else {
1559           /* Use the new header for this frame */
1560           hSbrElement->useHeaderSlot[hSbrElement->useFrameSlot] = thisHdrSlot;
1561         }
1562 
1563         /* Move frame pointer to the next slot which is up to be decoded/applied
1564          * next */
1565         hSbrElement->useFrameSlot =
1566             (hSbrElement->useFrameSlot + 1) % (self->numDelayFrames + 1);
1567       }
1568     }
1569   }
1570 
1571   *count -= startPos - (INT)FDKgetValidBits(hBs);
1572 
1573   return errorStatus;
1574 }
1575 
1576 /**
1577  * \brief Render one SBR element into time domain signal.
1578  * \param self SBR decoder handle
1579  * \param timeData pointer to output buffer
1580  * \param channelMapping pointer to UCHAR array where next 2 channel offsets are
1581  * stored.
1582  * \param elementIndex enumerating index of the SBR element to render.
1583  * \param numInChannels number of channels from core coder.
1584  * \param numOutChannels pointer to a location to return number of output
1585  * channels.
1586  * \param psPossible flag indicating if PS is possible or not.
1587  * \return SBRDEC_OK if successfull, else error code
1588  */
sbrDecoder_DecodeElement(HANDLE_SBRDECODER self,QDOM_PCM * input,INT_PCM * timeData,const int timeDataSize,const FDK_channelMapDescr * const mapDescr,const int mapIdx,int channelIndex,const int elementIndex,const int numInChannels,int * numOutChannels,const int psPossible)1589 static SBR_ERROR sbrDecoder_DecodeElement(
1590     HANDLE_SBRDECODER self, QDOM_PCM *input, INT_PCM *timeData,
1591     const int timeDataSize, const FDK_channelMapDescr *const mapDescr,
1592     const int mapIdx, int channelIndex, const int elementIndex,
1593     const int numInChannels, int *numOutChannels, const int psPossible) {
1594   SBR_DECODER_ELEMENT *hSbrElement = self->pSbrElement[elementIndex];
1595   HANDLE_SBR_CHANNEL *pSbrChannel =
1596       self->pSbrElement[elementIndex]->pSbrChannel;
1597   HANDLE_SBR_HEADER_DATA hSbrHeader =
1598       &self->sbrHeader[elementIndex]
1599                       [hSbrElement->useHeaderSlot[hSbrElement->useFrameSlot]];
1600   HANDLE_PS_DEC h_ps_d = self->hParametricStereoDec;
1601 
1602   /* get memory for frame data from scratch */
1603   SBR_FRAME_DATA *hFrameDataLeft = NULL;
1604   SBR_FRAME_DATA *hFrameDataRight = NULL;
1605 
1606   SBR_ERROR errorStatus = SBRDEC_OK;
1607 
1608   INT strideOut, offset0 = 255, offset0_block = 0, offset1 = 255,
1609                  offset1_block = 0;
1610   INT codecFrameSize = self->codecFrameSize;
1611 
1612   int stereo = (hSbrElement->elementID == ID_CPE) ? 1 : 0;
1613   int numElementChannels =
1614       hSbrElement
1615           ->nChannels; /* Number of channels of the current SBR element */
1616 
1617   hFrameDataLeft =
1618       &hSbrElement->pSbrChannel[0]->frameData[hSbrElement->useFrameSlot];
1619   if (stereo) {
1620     hFrameDataRight =
1621         &hSbrElement->pSbrChannel[1]->frameData[hSbrElement->useFrameSlot];
1622   }
1623 
1624   if (self->flags & SBRDEC_FLUSH) {
1625     if (self->numFlushedFrames > self->numDelayFrames) {
1626       int hdrIdx;
1627       /* No valid SBR payload available, hence switch to upsampling (in all
1628        * headers) */
1629       for (hdrIdx = 0; hdrIdx < ((1) + 1); hdrIdx += 1) {
1630         self->sbrHeader[elementIndex][hdrIdx].syncState = UPSAMPLING;
1631       }
1632     } else {
1633       /* Move frame pointer to the next slot which is up to be decoded/applied
1634        * next */
1635       hSbrElement->useFrameSlot =
1636           (hSbrElement->useFrameSlot + 1) % (self->numDelayFrames + 1);
1637       /* Update header and frame data pointer because they have already been set
1638        */
1639       hSbrHeader =
1640           &self->sbrHeader[elementIndex]
1641                           [hSbrElement
1642                                ->useHeaderSlot[hSbrElement->useFrameSlot]];
1643       hFrameDataLeft =
1644           &hSbrElement->pSbrChannel[0]->frameData[hSbrElement->useFrameSlot];
1645       if (stereo) {
1646         hFrameDataRight =
1647             &hSbrElement->pSbrChannel[1]->frameData[hSbrElement->useFrameSlot];
1648       }
1649     }
1650   }
1651 
1652   /* Update the header error flag */
1653   hSbrHeader->frameErrorFlag =
1654       hSbrElement->frameErrorFlag[hSbrElement->useFrameSlot];
1655 
1656   /*
1657      Prepare filterbank for upsampling if no valid bit stream data is available.
1658    */
1659   if (hSbrHeader->syncState == SBR_NOT_INITIALIZED) {
1660     errorStatus =
1661         initHeaderData(hSbrHeader, self->sampleRateIn, self->sampleRateOut,
1662                        self->downscaleFactor, codecFrameSize, self->flags,
1663                        1 /* SET_DEFAULT_HDR */
1664         );
1665 
1666     if (errorStatus != SBRDEC_OK) {
1667       return errorStatus;
1668     }
1669 
1670     hSbrHeader->syncState = UPSAMPLING;
1671 
1672     errorStatus = sbrDecoder_HeaderUpdate(self, hSbrHeader, HEADER_NOT_PRESENT,
1673                                           pSbrChannel, hSbrElement->nChannels);
1674 
1675     if (errorStatus != SBRDEC_OK) {
1676       hSbrHeader->syncState = SBR_NOT_INITIALIZED;
1677       return errorStatus;
1678     }
1679   }
1680 
1681   /* reset */
1682   if (hSbrHeader->status & SBRDEC_HDR_STAT_RESET) {
1683     int ch;
1684     int applySbrProc = (hSbrHeader->syncState == SBR_ACTIVE ||
1685                         (hSbrHeader->frameErrorFlag == 0 &&
1686                          hSbrHeader->syncState == SBR_HEADER));
1687     for (ch = 0; ch < numElementChannels; ch++) {
1688       SBR_ERROR errorStatusTmp = SBRDEC_OK;
1689 
1690       errorStatusTmp = resetSbrDec(
1691           &pSbrChannel[ch]->SbrDec, hSbrHeader, &pSbrChannel[ch]->prevFrameData,
1692           self->synDownsampleFac, self->flags, pSbrChannel[ch]->frameData);
1693 
1694       if (errorStatusTmp != SBRDEC_OK) {
1695         hSbrHeader->syncState = UPSAMPLING;
1696       }
1697     }
1698     if (applySbrProc) {
1699       hSbrHeader->status &= ~SBRDEC_HDR_STAT_RESET;
1700     }
1701   }
1702 
1703   /* decoding */
1704   if ((hSbrHeader->syncState == SBR_ACTIVE) ||
1705       ((hSbrHeader->syncState == SBR_HEADER) &&
1706        (hSbrHeader->frameErrorFlag == 0))) {
1707     errorStatus = SBRDEC_OK;
1708 
1709     decodeSbrData(hSbrHeader, hFrameDataLeft, &pSbrChannel[0]->prevFrameData,
1710                   (stereo) ? hFrameDataRight : NULL,
1711                   (stereo) ? &pSbrChannel[1]->prevFrameData : NULL);
1712 
1713     /* Now we have a full parameter set and can do parameter
1714        based concealment instead of plain upsampling. */
1715     hSbrHeader->syncState = SBR_ACTIVE;
1716   }
1717 
1718   if (timeDataSize <
1719       hSbrHeader->numberTimeSlots * hSbrHeader->timeStep *
1720           self->pQmfDomain->globalConf.nBandsSynthesis *
1721           (psPossible ? fMax(2, numInChannels) : numInChannels)) {
1722     return SBRDEC_OUTPUT_BUFFER_TOO_SMALL;
1723   }
1724 
1725   {
1726     self->flags &= ~SBRDEC_PS_DECODED;
1727     C_ALLOC_SCRATCH_START(pPsScratch, struct PS_DEC_COEFFICIENTS, 1)
1728 
1729     /* decode PS data if available */
1730     if (h_ps_d != NULL && psPossible && (hSbrHeader->syncState == SBR_ACTIVE)) {
1731       int applyPs = 1;
1732 
1733       /* define which frame delay line slot to process */
1734       h_ps_d->processSlot = hSbrElement->useFrameSlot;
1735 
1736       applyPs = DecodePs(h_ps_d, hSbrHeader->frameErrorFlag, pPsScratch);
1737       self->flags |= (applyPs) ? SBRDEC_PS_DECODED : 0;
1738     }
1739 
1740     offset0 = FDK_chMapDescr_getMapValue(mapDescr, channelIndex, mapIdx);
1741     offset0_block = offset0 * codecFrameSize;
1742     if (stereo || psPossible) {
1743       /* the value of offset1 only matters if the condition is true, however if
1744       it is not true channelIndex+1 may exceed the channel map resutling in an
1745       error, though the value of offset1 is actually meaningless. This is
1746       prevented here. */
1747       offset1 = FDK_chMapDescr_getMapValue(mapDescr, channelIndex + 1, mapIdx);
1748       offset1_block = offset1 * codecFrameSize;
1749     }
1750     /* Set strides for reading and writing */
1751     if (psPossible)
1752       strideOut = (numInChannels < 2) ? 2 : numInChannels;
1753     else
1754       strideOut = numInChannels;
1755 
1756     /* use same buffers for left and right channel and apply PS per timeslot */
1757     /* Process left channel */
1758     sbr_dec(&pSbrChannel[0]->SbrDec, input + offset0_block, timeData + offset0,
1759             (self->flags & SBRDEC_PS_DECODED) ? &pSbrChannel[1]->SbrDec : NULL,
1760             timeData + offset1, strideOut, hSbrHeader, hFrameDataLeft,
1761             &pSbrChannel[0]->prevFrameData,
1762             (hSbrHeader->syncState == SBR_ACTIVE), h_ps_d, self->flags,
1763             codecFrameSize);
1764 
1765     if (stereo) {
1766       /* Process right channel */
1767       sbr_dec(&pSbrChannel[1]->SbrDec, input + offset1_block,
1768               timeData + offset1, NULL, NULL, strideOut, hSbrHeader,
1769               hFrameDataRight, &pSbrChannel[1]->prevFrameData,
1770               (hSbrHeader->syncState == SBR_ACTIVE), NULL, self->flags,
1771               codecFrameSize);
1772     }
1773 
1774     C_ALLOC_SCRATCH_END(pPsScratch, struct PS_DEC_COEFFICIENTS, 1)
1775   }
1776 
1777   if (h_ps_d != NULL) {
1778     /* save PS status for next run */
1779     h_ps_d->psDecodedPrv = (self->flags & SBRDEC_PS_DECODED) ? 1 : 0;
1780   }
1781 
1782   if (psPossible && !(self->flags & SBRDEC_SKIP_QMF_SYN)) {
1783     FDK_ASSERT(strideOut > 1);
1784     if (!(self->flags & SBRDEC_PS_DECODED)) {
1785       /* A decoder which is able to decode PS has to produce a stereo output
1786        * even if no PS data is available. */
1787       /* So copy left channel to right channel. */
1788       int copyFrameSize =
1789           codecFrameSize * self->pQmfDomain->QmfDomainOut->fb.no_channels;
1790       copyFrameSize /= self->pQmfDomain->QmfDomainIn->fb.no_channels;
1791       INT_PCM *ptr;
1792       INT i;
1793       FDK_ASSERT(strideOut == 2);
1794 
1795       ptr = timeData;
1796       for (i = copyFrameSize >> 1; i--;) {
1797         INT_PCM tmp; /* This temporal variable is required because some
1798                         compilers can't do *ptr++ = *ptr++ correctly. */
1799         tmp = *ptr++;
1800         *ptr++ = tmp;
1801         tmp = *ptr++;
1802         *ptr++ = tmp;
1803       }
1804     }
1805     *numOutChannels = 2; /* Output minimum two channels when PS is enabled. */
1806   }
1807 
1808   return errorStatus;
1809 }
1810 
sbrDecoder_Apply(HANDLE_SBRDECODER self,INT_PCM * input,INT_PCM * timeData,const int timeDataSize,int * numChannels,int * sampleRate,const FDK_channelMapDescr * const mapDescr,const int mapIdx,const int coreDecodedOk,UCHAR * psDecoded)1811 SBR_ERROR sbrDecoder_Apply(HANDLE_SBRDECODER self, INT_PCM *input,
1812                            INT_PCM *timeData, const int timeDataSize,
1813                            int *numChannels, int *sampleRate,
1814                            const FDK_channelMapDescr *const mapDescr,
1815                            const int mapIdx, const int coreDecodedOk,
1816                            UCHAR *psDecoded) {
1817   SBR_ERROR errorStatus = SBRDEC_OK;
1818 
1819   int psPossible;
1820   int sbrElementNum;
1821   int numCoreChannels;
1822   int numSbrChannels = 0;
1823 
1824   if ((self == NULL) || (timeData == NULL) || (numChannels == NULL) ||
1825       (sampleRate == NULL) || (psDecoded == NULL) ||
1826       !FDK_chMapDescr_isValid(mapDescr)) {
1827     return SBRDEC_INVALID_ARGUMENT;
1828   }
1829 
1830   psPossible = *psDecoded;
1831   numCoreChannels = *numChannels;
1832   if (numCoreChannels <= 0) {
1833     return SBRDEC_INVALID_ARGUMENT;
1834   }
1835 
1836   if (self->numSbrElements < 1) {
1837     /* exit immediately to avoid access violations */
1838     return SBRDEC_NOT_INITIALIZED;
1839   }
1840 
1841   /* Sanity check of allocated SBR elements. */
1842   for (sbrElementNum = 0; sbrElementNum < self->numSbrElements;
1843        sbrElementNum++) {
1844     if (self->pSbrElement[sbrElementNum] == NULL) {
1845       return SBRDEC_NOT_INITIALIZED;
1846     }
1847   }
1848 
1849   if (self->numSbrElements != 1 || self->pSbrElement[0]->elementID != ID_SCE) {
1850     psPossible = 0;
1851   }
1852 
1853   /* Make sure that even if no SBR data was found/parsed *psDecoded is returned
1854    * 1 if psPossible was 0. */
1855   if (psPossible == 0) {
1856     self->flags &= ~SBRDEC_PS_DECODED;
1857   }
1858 
1859   /* replaces channel based reset inside sbr_dec() */
1860   if (((self->flags & SBRDEC_LOW_POWER) ? 1 : 0) !=
1861       ((self->pQmfDomain->globalConf.flags & QMF_FLAG_LP) ? 1 : 0)) {
1862     if (self->flags & SBRDEC_LOW_POWER) {
1863       self->pQmfDomain->globalConf.flags |= QMF_FLAG_LP;
1864       self->pQmfDomain->globalConf.flags_requested |= QMF_FLAG_LP;
1865     } else {
1866       self->pQmfDomain->globalConf.flags &= ~QMF_FLAG_LP;
1867       self->pQmfDomain->globalConf.flags_requested &= ~QMF_FLAG_LP;
1868     }
1869     if (FDK_QmfDomain_InitFilterBank(self->pQmfDomain, QMF_FLAG_KEEP_STATES)) {
1870       return SBRDEC_UNSUPPORTED_CONFIG;
1871     }
1872   }
1873   if (self->numSbrChannels > self->pQmfDomain->globalConf.nInputChannels) {
1874     return SBRDEC_UNSUPPORTED_CONFIG;
1875   }
1876 
1877   if (self->flags & SBRDEC_FLUSH) {
1878     /* flushing is signalized, hence increment the flush frame counter */
1879     self->numFlushedFrames++;
1880   } else {
1881     /* no flushing is signalized, hence reset the flush frame counter */
1882     self->numFlushedFrames = 0;
1883   }
1884 
1885   /* Loop over SBR elements */
1886   for (sbrElementNum = 0; sbrElementNum < self->numSbrElements;
1887        sbrElementNum++) {
1888     int numElementChan;
1889 
1890     if (psPossible &&
1891         self->pSbrElement[sbrElementNum]->pSbrChannel[1] == NULL) {
1892       /* Disable PS and try decoding SBR mono. */
1893       psPossible = 0;
1894     }
1895 
1896     numElementChan =
1897         (self->pSbrElement[sbrElementNum]->elementID == ID_CPE) ? 2 : 1;
1898 
1899     /* If core signal is bad then force upsampling */
1900     if (!coreDecodedOk) {
1901       setFrameErrorFlag(self->pSbrElement[sbrElementNum], FRAME_ERROR_ALLSLOTS);
1902     }
1903 
1904     errorStatus = sbrDecoder_DecodeElement(
1905         self, input, timeData, timeDataSize, mapDescr, mapIdx, numSbrChannels,
1906         sbrElementNum,
1907         numCoreChannels, /* is correct even for USC SCI==2 case */
1908         &numElementChan, psPossible);
1909 
1910     if (errorStatus != SBRDEC_OK) {
1911       goto bail;
1912     }
1913 
1914     numSbrChannels += numElementChan;
1915 
1916     if (numSbrChannels >= numCoreChannels) {
1917       break;
1918     }
1919   }
1920 
1921   /* Update numChannels and samplerate */
1922   /* Do not mess with output channels in case of USAC. numSbrChannels !=
1923    * numChannels for stereoConfigIndex == 2 */
1924   if (!(self->flags & SBRDEC_SYNTAX_USAC)) {
1925     *numChannels = numSbrChannels;
1926   }
1927   *sampleRate = self->sampleRateOut;
1928   *psDecoded = (self->flags & SBRDEC_PS_DECODED) ? 1 : 0;
1929 
1930   /* Clear reset and flush flag because everything seems to be done
1931    * successfully. */
1932   self->flags &= ~SBRDEC_FORCE_RESET;
1933   self->flags &= ~SBRDEC_FLUSH;
1934 
1935 bail:
1936 
1937   return errorStatus;
1938 }
1939 
sbrDecoder_Close(HANDLE_SBRDECODER * pSelf)1940 SBR_ERROR sbrDecoder_Close(HANDLE_SBRDECODER *pSelf) {
1941   HANDLE_SBRDECODER self = *pSelf;
1942   int i;
1943 
1944   if (self != NULL) {
1945     if (self->hParametricStereoDec != NULL) {
1946       DeletePsDec(&self->hParametricStereoDec);
1947     }
1948 
1949     for (i = 0; i < (8); i++) {
1950       sbrDecoder_DestroyElement(self, i);
1951     }
1952 
1953     FreeRam_SbrDecoder(pSelf);
1954   }
1955 
1956   return SBRDEC_OK;
1957 }
1958 
sbrDecoder_GetLibInfo(LIB_INFO * info)1959 INT sbrDecoder_GetLibInfo(LIB_INFO *info) {
1960   int i;
1961 
1962   if (info == NULL) {
1963     return -1;
1964   }
1965 
1966   /* search for next free tab */
1967   for (i = 0; i < FDK_MODULE_LAST; i++) {
1968     if (info[i].module_id == FDK_NONE) break;
1969   }
1970   if (i == FDK_MODULE_LAST) return -1;
1971   info += i;
1972 
1973   info->module_id = FDK_SBRDEC;
1974   info->version =
1975       LIB_VERSION(SBRDECODER_LIB_VL0, SBRDECODER_LIB_VL1, SBRDECODER_LIB_VL2);
1976   LIB_VERSION_STRING(info);
1977   info->build_date = SBRDECODER_LIB_BUILD_DATE;
1978   info->build_time = SBRDECODER_LIB_BUILD_TIME;
1979   info->title = SBRDECODER_LIB_TITLE;
1980 
1981   /* Set flags */
1982   info->flags = 0 | CAPF_SBR_HQ | CAPF_SBR_LP | CAPF_SBR_PS_MPEG |
1983                 CAPF_SBR_DRM_BS | CAPF_SBR_CONCEALMENT | CAPF_SBR_DRC |
1984                 CAPF_SBR_ELD_DOWNSCALE | CAPF_SBR_HBEHQ;
1985   /* End of flags */
1986 
1987   return 0;
1988 }
1989 
sbrDecoder_GetDelay(const HANDLE_SBRDECODER self)1990 UINT sbrDecoder_GetDelay(const HANDLE_SBRDECODER self) {
1991   UINT outputDelay = 0;
1992 
1993   if (self != NULL) {
1994     UINT flags = self->flags;
1995 
1996     /* See chapter 1.6.7.2 of ISO/IEC 14496-3 for the GA-SBR figures below. */
1997 
1998     /* Are we initialized? */
1999     if ((self->numSbrChannels > 0) && (self->numSbrElements > 0)) {
2000       /* Add QMF synthesis delay */
2001       if ((flags & SBRDEC_ELD_GRID) && IS_LOWDELAY(self->coreCodec)) {
2002         /* Low delay SBR: */
2003         if (!(flags & SBRDEC_SKIP_QMF_SYN)) {
2004           outputDelay +=
2005               (flags & SBRDEC_DOWNSAMPLE) ? 32 : 64; /* QMF synthesis */
2006           if (flags & SBRDEC_LD_MPS_QMF) {
2007             outputDelay += 32;
2008           }
2009         }
2010       } else if (!IS_USAC(self->coreCodec)) {
2011         /* By the method of elimination this is the GA (AAC-LC, HE-AAC, ...)
2012          * branch: */
2013         outputDelay += (flags & SBRDEC_DOWNSAMPLE) ? 481 : 962;
2014         if (flags & SBRDEC_SKIP_QMF_SYN) {
2015           outputDelay -= 257; /* QMF synthesis */
2016         }
2017       }
2018     }
2019   }
2020 
2021   return (outputDelay);
2022 }
2023