• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 
2 /* -----------------------------------------------------------------------------------------------------------
3 Software License for The Fraunhofer FDK AAC Codec Library for Android
4 
5 � Copyright  1995 - 2013 Fraunhofer-Gesellschaft zur F�rderung der angewandten Forschung e.V.
6   All rights reserved.
7 
8  1.    INTRODUCTION
9 The Fraunhofer FDK AAC Codec Library for Android ("FDK AAC Codec") is software that implements
10 the MPEG Advanced Audio Coding ("AAC") encoding and decoding scheme for digital audio.
11 This FDK AAC Codec software is intended to be used on a wide variety of Android devices.
12 
13 AAC's HE-AAC and HE-AAC v2 versions are regarded as today's most efficient general perceptual
14 audio codecs. AAC-ELD is considered the best-performing full-bandwidth communications codec by
15 independent studies and is widely deployed. AAC has been standardized by ISO and IEC as part
16 of the MPEG specifications.
17 
18 Patent licenses for necessary patent claims for the FDK AAC Codec (including those of Fraunhofer)
19 may be obtained through Via Licensing (www.vialicensing.com) or through the respective patent owners
20 individually for the purpose of encoding or decoding bit streams in products that are compliant with
21 the ISO/IEC MPEG audio standards. Please note that most manufacturers of Android devices already license
22 these patent claims through Via Licensing or directly from the patent owners, and therefore FDK AAC Codec
23 software may already be covered under those patent licenses when it is used for those licensed purposes only.
24 
25 Commercially-licensed AAC software libraries, including floating-point versions with enhanced sound quality,
26 are also available from Fraunhofer. Users are encouraged to check the Fraunhofer website for additional
27 applications information and documentation.
28 
29 2.    COPYRIGHT LICENSE
30 
31 Redistribution and use in source and binary forms, with or without modification, are permitted without
32 payment of copyright license fees provided that you satisfy the following conditions:
33 
34 You must retain the complete text of this software license in redistributions of the FDK AAC Codec or
35 your modifications thereto in source code form.
36 
37 You must retain the complete text of this software license in the documentation and/or other materials
38 provided with redistributions of the FDK AAC Codec or your modifications thereto in binary form.
39 You must make available free of charge copies of the complete source code of the FDK AAC Codec and your
40 modifications thereto to recipients of copies in binary form.
41 
42 The name of Fraunhofer may not be used to endorse or promote products derived from this library without
43 prior written permission.
44 
45 You may not charge copyright license fees for anyone to use, copy or distribute the FDK AAC Codec
46 software or your modifications thereto.
47 
48 Your modified versions of the FDK AAC Codec must carry prominent notices stating that you changed the software
49 and the date of any change. For modified versions of the FDK AAC Codec, the term
50 "Fraunhofer FDK AAC Codec Library for Android" must be replaced by the term
51 "Third-Party Modified Version of the Fraunhofer FDK AAC Codec Library for Android."
52 
53 3.    NO PATENT LICENSE
54 
55 NO EXPRESS OR IMPLIED LICENSES TO ANY PATENT CLAIMS, including without limitation the patents of Fraunhofer,
56 ARE GRANTED BY THIS SOFTWARE LICENSE. Fraunhofer provides no warranty of patent non-infringement with
57 respect to this software.
58 
59 You may use this FDK AAC Codec software or modifications thereto only for purposes that are authorized
60 by appropriate patent licenses.
61 
62 4.    DISCLAIMER
63 
64 This FDK AAC Codec software is provided by Fraunhofer on behalf of the copyright holders and contributors
65 "AS IS" and WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, including but not limited to the implied warranties
66 of merchantability and fitness for a particular purpose. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
67 CONTRIBUTORS BE LIABLE for any direct, indirect, incidental, special, exemplary, or consequential damages,
68 including but not limited to procurement of substitute goods or services; loss of use, data, or profits,
69 or business interruption, however caused and on any theory of liability, whether in contract, strict
70 liability, or tort (including negligence), arising in any way out of the use of this software, even if
71 advised of the possibility of such damage.
72 
73 5.    CONTACT INFORMATION
74 
75 Fraunhofer Institute for Integrated Circuits IIS
76 Attention: Audio and Multimedia Departments - FDK AAC LL
77 Am Wolfsmantel 33
78 91058 Erlangen, Germany
79 
80 www.iis.fraunhofer.de/amm
81 amm-info@iis.fraunhofer.de
82 ----------------------------------------------------------------------------------------------------------- */
83 
84 /*!
85   \file
86   \brief  SBR decoder frontend
87   This module provides a frontend to the SBR decoder. The function openSBR() is called for
88   initialization. The function sbrDecoder_Apply() is called for each frame. sbr_Apply() will call the
89   required functions to decode the raw SBR data (provided by env_extr.cpp), to decode the envelope data and noise floor levels [decodeSbrData()],
90   and to finally apply SBR to the current frame [sbr_dec()].
91 
92   \sa sbrDecoder_Apply(), \ref documentationOverview
93 */
94 
95 /*!
96   \page documentationOverview Overview of important information resources and source code documentation
97 
98   The primary source code documentation is based on generated and cross-referenced HTML files using
99   <a HREF="http://www.doxygen.org">doxygen</a>. As part of this documentation
100   you can find more extensive descriptions about key concepts and algorithms at the following locations:
101 
102   <h2>Programming</h2>
103 
104   \li Buffer management: sbrDecoder_Apply() and sbr_dec()
105   \li Internal scale factors to maximize SNR on fixed point processors: #QMF_SCALE_FACTOR
106   \li Special mantissa-exponent format: Created in requantizeEnvelopeData() and used in calculateSbrEnvelope()
107 
108   <h2>Algorithmic details</h2>
109   \li About the SBR data format: \ref SBR_HEADER_ELEMENT and \ref SBR_STANDARD_ELEMENT
110   \li Details about the bitstream decoder: env_extr.cpp
111   \li Details about the QMF filterbank and the provided polyphase implementation: qmf_dec.cpp
112   \li Details about the transposer: lpp_tran.cpp
113   \li Details about the envelope adjuster: env_calc.cpp
114 
115 */
116 
117 #include "sbrdecoder.h"
118 
119 #include "FDK_bitstream.h"
120 
121 #include "sbrdec_freq_sca.h"
122 #include "env_extr.h"
123 #include "sbr_dec.h"
124 #include "env_dec.h"
125 #include "sbr_crc.h"
126 #include "sbr_ram.h"
127 #include "sbr_rom.h"
128 #include "lpp_tran.h"
129 #include "transcendent.h"
130 
131 
132 #include "sbrdec_drc.h"
133 
134 #include "psbitdec.h"
135 
136 
137 /* Decoder library info */
138 #define SBRDECODER_LIB_VL0 2
139 #define SBRDECODER_LIB_VL1 2
140 #define SBRDECODER_LIB_VL2 6
141 #define SBRDECODER_LIB_TITLE "SBR Decoder"
142 #define SBRDECODER_LIB_BUILD_DATE __DATE__
143 #define SBRDECODER_LIB_BUILD_TIME __TIME__
144 
145 
146 
147 
getHeaderSlot(UCHAR currentSlot,UCHAR hdrSlotUsage[(1)+1])148 static UCHAR getHeaderSlot( UCHAR currentSlot, UCHAR hdrSlotUsage[(1)+1] )
149 {
150   UINT  occupied = 0;
151   int   s;
152   UCHAR slot = hdrSlotUsage[currentSlot];
153 
154   FDK_ASSERT((1)+1 < 32);
155 
156   for (s = 0; s < (1)+1; s++) {
157     if ( (hdrSlotUsage[s] == slot)
158       && (s != slot) ) {
159       occupied = 1;
160       break;
161     }
162   }
163 
164   if (occupied) {
165     occupied = 0;
166 
167     for (s = 0; s < (1)+1; s++) {
168       occupied |= 1 << hdrSlotUsage[s];
169     }
170     for (s = 0; s < (1)+1; s++) {
171       if ( !(occupied & 0x1) ) {
172         slot = s;
173         break;
174       }
175       occupied >>= 1;
176     }
177   }
178 
179   return slot;
180 }
181 
copySbrHeader(HANDLE_SBR_HEADER_DATA hDst,const HANDLE_SBR_HEADER_DATA hSrc)182 static void copySbrHeader( HANDLE_SBR_HEADER_DATA hDst, const HANDLE_SBR_HEADER_DATA hSrc )
183 {
184   /* copy the whole header memory (including pointers) */
185   FDKmemcpy( hDst, hSrc, sizeof(SBR_HEADER_DATA) );
186 
187   /* update pointers */
188   hDst->freqBandData.freqBandTable[0]  = hDst->freqBandData.freqBandTableLo;
189   hDst->freqBandData.freqBandTable[1] = hDst->freqBandData.freqBandTableHi;
190 }
191 
192 
193 /*!
194   \brief Reset SBR decoder.
195 
196   Reset should only be called if SBR has been sucessfully detected by
197   an appropriate checkForPayload() function.
198 
199   \return Error code.
200 */
201 static
sbrDecoder_ResetElement(HANDLE_SBRDECODER self,int sampleRateIn,int sampleRateOut,int samplesPerFrame,const MP4_ELEMENT_ID elementID,const int elementIndex,const int overlap)202 SBR_ERROR sbrDecoder_ResetElement (
203         HANDLE_SBRDECODER    self,
204         int                  sampleRateIn,
205         int                  sampleRateOut,
206         int                  samplesPerFrame,
207         const MP4_ELEMENT_ID elementID,
208         const int            elementIndex,
209         const int            overlap
210         )
211 {
212   SBR_ERROR sbrError = SBRDEC_OK;
213   HANDLE_SBR_HEADER_DATA hSbrHeader;
214   UINT qmfFlags = 0;
215 
216   int i, synDownsampleFac;
217 
218   /* Check in/out samplerates */
219   if ( sampleRateIn < 6400
220     || sampleRateIn > 48000
221      )
222   {
223     sbrError = SBRDEC_UNSUPPORTED_CONFIG;
224     goto bail;
225   }
226 
227   if ( sampleRateOut > 96000 )
228   {
229     sbrError = SBRDEC_UNSUPPORTED_CONFIG;
230     goto bail;
231   }
232 
233   /* Set QMF mode flags */
234   if (self->flags & SBRDEC_LOW_POWER)
235     qmfFlags |= QMF_FLAG_LP;
236 
237   if (self->coreCodec == AOT_ER_AAC_ELD) {
238     if (self->flags & SBRDEC_LD_MPS_QMF) {
239       qmfFlags |=  QMF_FLAG_MPSLDFB;
240     } else {
241       qmfFlags |=  QMF_FLAG_CLDFB;
242     }
243   }
244 
245   /* Set downsampling factor for synthesis filter bank */
246   if (sampleRateOut == 0)
247   {
248     /* no single rate mode */
249       sampleRateOut = sampleRateIn<<1; /* In case of implicit signalling, assume dual rate SBR */
250   }
251 
252   if ( sampleRateIn == sampleRateOut ) {
253     synDownsampleFac = 2;
254     self->flags |=  SBRDEC_DOWNSAMPLE;
255   } else {
256     synDownsampleFac = 1;
257     self->flags &= ~SBRDEC_DOWNSAMPLE;
258   }
259 
260   self->synDownsampleFac = synDownsampleFac;
261   self->sampleRateOut = sampleRateOut;
262 
263   {
264     int i;
265 
266     for (i = 0; i < (1)+1; i++)
267     {
268       hSbrHeader = &(self->sbrHeader[elementIndex][i]);
269 
270       /* init a default header such that we can at least do upsampling later */
271       sbrError = initHeaderData(
272               hSbrHeader,
273               sampleRateIn,
274               sampleRateOut,
275               samplesPerFrame,
276               self->flags
277               );
278     }
279   }
280 
281   if (sbrError != SBRDEC_OK) {
282     goto bail;
283   }
284 
285   /* Init SBR channels going to be assigned to a SBR element */
286   {
287     int ch;
288 
289     for (ch=0; ch<self->pSbrElement[elementIndex]->nChannels; ch++)
290     {
291       /* and create sbrDec */
292       sbrError = createSbrDec (self->pSbrElement[elementIndex]->pSbrChannel[ch],
293                           hSbrHeader,
294                          &self->pSbrElement[elementIndex]->transposerSettings,
295                           synDownsampleFac,
296                           qmfFlags,
297                           self->flags,
298                           overlap,
299                           ch );
300 
301       if (sbrError != SBRDEC_OK) {
302         goto bail;
303       }
304     }
305   }
306 
307   //FDKmemclear(sbr_OverlapBuffer, sizeof(sbr_OverlapBuffer));
308 
309   if (self->numSbrElements == 1) {
310     switch ( self->coreCodec ) {
311     case AOT_AAC_LC:
312     case AOT_SBR:
313     case AOT_PS:
314     case AOT_ER_AAC_SCAL:
315     case AOT_DRM_AAC:
316     case AOT_DRM_SURROUND:
317       if (CreatePsDec ( &self->hParametricStereoDec, samplesPerFrame )) {
318         sbrError = SBRDEC_CREATE_ERROR;
319         goto bail;
320       }
321       break;
322     default:
323       break;
324     }
325   }
326 
327   /* Init frame delay slot handling */
328   self->pSbrElement[elementIndex]->useFrameSlot = 0;
329   for (i = 0; i < ((1)+1); i++) {
330     self->pSbrElement[elementIndex]->useHeaderSlot[i] = i;
331   }
332 
333 bail:
334 
335   return sbrError;
336 }
337 
338 
sbrDecoder_Open(HANDLE_SBRDECODER * pSelf)339 SBR_ERROR sbrDecoder_Open ( HANDLE_SBRDECODER  * pSelf )
340 {
341   HANDLE_SBRDECODER    self = NULL;
342   SBR_ERROR sbrError = SBRDEC_OK;
343 
344   /* Get memory for this instance */
345   self = GetRam_SbrDecoder();
346   if (self == NULL) {
347     sbrError = SBRDEC_MEM_ALLOC_FAILED;
348     goto bail;
349   }
350 
351   self->workBuffer1 = GetRam_SbrDecWorkBuffer1();
352   self->workBuffer2 = GetRam_SbrDecWorkBuffer2();
353 
354   if (  self->workBuffer1 == NULL
355      || self->workBuffer2 == NULL )
356   {
357     sbrError = SBRDEC_MEM_ALLOC_FAILED;
358     goto bail;
359   }
360 
361   /*
362   Already zero because of calloc
363   self->numSbrElements = 0;
364   self->numSbrChannels = 0;
365   self->codecFrameSize = 0;
366   */
367 
368   self->numDelayFrames = (1);  /* set to the max value by default */
369 
370   *pSelf = self;
371 
372 bail:
373   return sbrError;
374 }
375 
376 /**
377  * \brief determine if the given core codec AOT can be processed or not.
378  * \param coreCodec core codec audio object type.
379  * \return 1 if SBR can be processed, 0 if SBR cannot be processed/applied.
380  */
381 static
sbrDecoder_isCoreCodecValid(AUDIO_OBJECT_TYPE coreCodec)382 int sbrDecoder_isCoreCodecValid(AUDIO_OBJECT_TYPE coreCodec)
383 {
384   switch (coreCodec) {
385     case AOT_AAC_LC:
386     case AOT_SBR:
387     case AOT_PS:
388     case AOT_ER_AAC_SCAL:
389     case AOT_ER_AAC_ELD:
390       return 1;
391     default:
392       return 0;
393   }
394 }
395 
396 static
sbrDecoder_DestroyElement(HANDLE_SBRDECODER self,const int elementIndex)397 void sbrDecoder_DestroyElement (
398         HANDLE_SBRDECODER       self,
399         const int               elementIndex
400         )
401 {
402   if (self->pSbrElement[elementIndex] != NULL) {
403     int ch;
404 
405     for (ch=0; ch<SBRDEC_MAX_CH_PER_ELEMENT; ch++) {
406       if (self->pSbrElement[elementIndex]->pSbrChannel[ch] != NULL) {
407         deleteSbrDec( self->pSbrElement[elementIndex]->pSbrChannel[ch] );
408         FreeRam_SbrDecChannel( &self->pSbrElement[elementIndex]->pSbrChannel[ch] );
409         self->numSbrChannels -= 1;
410       }
411     }
412     FreeRam_SbrDecElement( &self->pSbrElement[elementIndex] );
413     self->numSbrElements -= 1;
414   }
415 }
416 
417 
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)418 SBR_ERROR sbrDecoder_InitElement (
419         HANDLE_SBRDECODER       self,
420         const int               sampleRateIn,
421         const int               sampleRateOut,
422         const int               samplesPerFrame,
423         const AUDIO_OBJECT_TYPE coreCodec,
424         const MP4_ELEMENT_ID    elementID,
425         const int               elementIndex
426         )
427 {
428   SBR_ERROR sbrError = SBRDEC_OK;
429   int chCnt=0;
430   int nSbrElementsStart = self->numSbrElements;
431 
432   /* Check core codec AOT */
433   if (! sbrDecoder_isCoreCodecValid(coreCodec) || elementIndex >= (8)) {
434     sbrError = SBRDEC_UNSUPPORTED_CONFIG;
435     goto bail;
436   }
437 
438   if ( elementID != ID_SCE && elementID != ID_CPE && elementID != ID_LFE )
439   {
440     sbrError = SBRDEC_UNSUPPORTED_CONFIG;
441     goto bail;
442   }
443 
444   if (  self->sampleRateIn == sampleRateIn
445      && self->codecFrameSize == samplesPerFrame
446      && self->coreCodec == coreCodec
447      && self->pSbrElement[elementIndex] != NULL
448      && self->pSbrElement[elementIndex]->elementID == elementID
449      && !(self->flags & SBRDEC_FORCE_RESET)
450      )
451   {
452      /* Nothing to do */
453      return SBRDEC_OK;
454   }
455 
456   self->sampleRateIn = sampleRateIn;
457   self->codecFrameSize = samplesPerFrame;
458   self->coreCodec = coreCodec;
459 
460   self->flags = 0;
461   self->flags |= (coreCodec == AOT_ER_AAC_ELD) ? SBRDEC_ELD_GRID : 0;
462 
463   /* Init SBR elements */
464   {
465     int elChannels, ch;
466 
467     if (self->pSbrElement[elementIndex] == NULL) {
468       self->pSbrElement[elementIndex] = GetRam_SbrDecElement(elementIndex);
469       if (self->pSbrElement[elementIndex] == NULL) {
470         sbrError = SBRDEC_MEM_ALLOC_FAILED;
471         goto bail;
472       }
473       self->numSbrElements ++;
474     } else {
475       self->numSbrChannels -= self->pSbrElement[elementIndex]->nChannels;
476     }
477 
478     /* Save element ID for sanity checks and to have a fallback for concealment. */
479     self->pSbrElement[elementIndex]->elementID = elementID;
480 
481     /* Determine amount of channels for this element */
482     switch (elementID) {
483       case ID_NONE:
484       case ID_CPE: elChannels=2;
485         break;
486       case ID_LFE:
487       case ID_SCE: elChannels=1;
488         break;
489       default: elChannels=0;
490         break;
491     }
492 
493     /* Handle case of Parametric Stereo */
494     if ( elementIndex == 0 && elementID == ID_SCE ) {
495       switch (coreCodec) {
496         case AOT_AAC_LC:
497         case AOT_SBR:
498         case AOT_PS:
499         case AOT_ER_AAC_SCAL:
500         case AOT_DRM_AAC:
501         case AOT_DRM_SURROUND:
502           elChannels = 2;
503           break;
504         default:
505           break;
506       }
507     }
508 
509     self->pSbrElement[elementIndex]->nChannels = elChannels;
510 
511     for (ch=0; ch<elChannels; ch++)
512     {
513       if (self->pSbrElement[elementIndex]->pSbrChannel[ch] == NULL) {
514         self->pSbrElement[elementIndex]->pSbrChannel[ch] = GetRam_SbrDecChannel(chCnt);
515         if (self->pSbrElement[elementIndex]->pSbrChannel[ch] == NULL) {
516           sbrError = SBRDEC_MEM_ALLOC_FAILED;
517           goto bail;
518         }
519       }
520       self->numSbrChannels ++;
521 
522       sbrDecoder_drcInitChannel( &self->pSbrElement[elementIndex]->pSbrChannel[ch]->SbrDec.sbrDrcChannel );
523 
524       /* Add reference pointer to workbuffers. */
525       self->pSbrElement[elementIndex]->pSbrChannel[ch]->SbrDec.WorkBuffer1 = self->workBuffer1;
526       self->pSbrElement[elementIndex]->pSbrChannel[ch]->SbrDec.WorkBuffer2 = self->workBuffer2;
527       chCnt++;
528     }
529     if (elChannels == 1 && self->pSbrElement[elementIndex]->pSbrChannel[ch] != NULL) {
530       deleteSbrDec( self->pSbrElement[elementIndex]->pSbrChannel[ch] );
531       FreeRam_SbrDecChannel( &self->pSbrElement[elementIndex]->pSbrChannel[ch] );
532     }
533   }
534 
535   /* clear error flags for all delay slots */
536   FDKmemclear(self->pSbrElement[elementIndex]->frameErrorFlag, ((1)+1)*sizeof(UCHAR));
537 
538   /* Initialize this instance */
539   sbrError = sbrDecoder_ResetElement(
540           self,
541           sampleRateIn,
542           sampleRateOut,
543           samplesPerFrame,
544           elementID,
545           elementIndex,
546           (coreCodec == AOT_ER_AAC_ELD) ? 0 : (6)
547           );
548 
549 
550 
551 bail:
552   if (sbrError != SBRDEC_OK) {
553     if (nSbrElementsStart < self->numSbrElements) {
554       /* Free the memory allocated for this element */
555       sbrDecoder_DestroyElement( self, elementIndex );
556     } else if ( (self->pSbrElement[elementIndex] != NULL)
557              && (elementIndex < (8)))
558     { /* Set error flag to trigger concealment */
559       self->pSbrElement[elementIndex]->frameErrorFlag[self->pSbrElement[elementIndex]->useFrameSlot] = 1;
560     }
561   }
562 
563   return sbrError;
564 }
565 
566 /**
567  * \brief Apply decoded SBR header for one element.
568  * \param self SBR decoder instance handle
569  * \param hSbrHeader SBR header handle to be processed.
570  * \param hSbrChannel pointer array to the SBR element channels corresponding to the SBR header.
571  * \param headerStatus header status value returned from SBR header parser.
572  * \param numElementChannels amount of channels for the SBR element whos header is to be processed.
573  */
574 static
sbrDecoder_HeaderUpdate(HANDLE_SBRDECODER self,HANDLE_SBR_HEADER_DATA hSbrHeader,SBR_HEADER_STATUS headerStatus,HANDLE_SBR_CHANNEL hSbrChannel[],const int numElementChannels)575 SBR_ERROR sbrDecoder_HeaderUpdate(
576         HANDLE_SBRDECODER self,
577         HANDLE_SBR_HEADER_DATA hSbrHeader,
578         SBR_HEADER_STATUS headerStatus,
579         HANDLE_SBR_CHANNEL hSbrChannel[],
580         const int numElementChannels
581         )
582 {
583   SBR_ERROR errorStatus = SBRDEC_OK;
584 
585   /*
586     change of control data, reset decoder
587   */
588   errorStatus = resetFreqBandTables(hSbrHeader, self->flags);
589 
590   if (errorStatus == SBRDEC_OK) {
591     if (hSbrHeader->syncState == UPSAMPLING && headerStatus != HEADER_RESET)
592     {
593       /* As the default header would limit the frequency range,
594          lowSubband and highSubband must be patched. */
595       hSbrHeader->freqBandData.lowSubband = hSbrHeader->numberOfAnalysisBands;
596       hSbrHeader->freqBandData.highSubband = hSbrHeader->numberOfAnalysisBands;
597     }
598 
599     /* Trigger a reset before processing this slot */
600     hSbrHeader->status |= SBRDEC_HDR_STAT_RESET;
601   }
602 
603   return errorStatus;
604 }
605 
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)606 INT sbrDecoder_Header (
607         HANDLE_SBRDECODER       self,
608         HANDLE_FDK_BITSTREAM    hBs,
609         const INT sampleRateIn,
610         const INT sampleRateOut,
611         const INT samplesPerFrame,
612         const AUDIO_OBJECT_TYPE coreCodec,
613         const MP4_ELEMENT_ID    elementID,
614         const INT               elementIndex
615         )
616 {
617   SBR_HEADER_STATUS headerStatus;
618   HANDLE_SBR_HEADER_DATA hSbrHeader;
619   SBR_ERROR sbrError = SBRDEC_OK;
620   int headerIndex;
621 
622   if ( self == NULL || elementIndex > (8) )
623   {
624     return SBRDEC_UNSUPPORTED_CONFIG;
625   }
626 
627   if (! sbrDecoder_isCoreCodecValid(coreCodec)) {
628     return SBRDEC_UNSUPPORTED_CONFIG;
629   }
630 
631   sbrError = sbrDecoder_InitElement(
632           self,
633           sampleRateIn,
634           sampleRateOut,
635           samplesPerFrame,
636           coreCodec,
637           elementID,
638           elementIndex
639           );
640 
641   if (sbrError != SBRDEC_OK) {
642     goto bail;
643   }
644 
645   headerIndex = getHeaderSlot(self->pSbrElement[elementIndex]->useFrameSlot,
646                               self->pSbrElement[elementIndex]->useHeaderSlot);
647   hSbrHeader = &(self->sbrHeader[elementIndex][headerIndex]);
648 
649   headerStatus = sbrGetHeaderData ( hSbrHeader,
650                                     hBs,
651                                     self->flags,
652                                     0);
653 
654 
655   {
656     SBR_DECODER_ELEMENT *pSbrElement;
657 
658     pSbrElement = self->pSbrElement[elementIndex];
659 
660     /* Sanity check */
661     if (pSbrElement != NULL) {
662       if ( (elementID == ID_CPE && pSbrElement->nChannels != 2)
663         || (elementID != ID_CPE && pSbrElement->nChannels != 1) )
664       {
665         return SBRDEC_UNSUPPORTED_CONFIG;
666       }
667       if ( headerStatus == HEADER_RESET ) {
668 
669         sbrError = sbrDecoder_HeaderUpdate(
670               self,
671               hSbrHeader,
672               headerStatus,
673               pSbrElement->pSbrChannel,
674               pSbrElement->nChannels
675               );
676 
677         if (sbrError == SBRDEC_OK) {
678           hSbrHeader->syncState = SBR_HEADER;
679           hSbrHeader->status   |= SBRDEC_HDR_STAT_UPDATE;
680         }
681         /* else {
682           Since we already have overwritten the old SBR header the only way out is UPSAMPLING!
683           This will be prepared in the next step.
684         } */
685       }
686     }
687   }
688 bail:
689   return sbrError;
690 }
691 
692 
sbrDecoder_SetParam(HANDLE_SBRDECODER self,const SBRDEC_PARAM param,const INT value)693 SBR_ERROR sbrDecoder_SetParam (HANDLE_SBRDECODER   self,
694                                const SBRDEC_PARAM  param,
695                                const INT           value )
696 {
697   SBR_ERROR errorStatus = SBRDEC_OK;
698 
699   /* configure the subsystems */
700   switch (param)
701   {
702   case SBR_SYSTEM_BITSTREAM_DELAY:
703     if (value < 0 || value > (1)) {
704       errorStatus = SBRDEC_SET_PARAM_FAIL;
705       break;
706     }
707     if (self == NULL) {
708       errorStatus = SBRDEC_NOT_INITIALIZED;
709     } else {
710       self->numDelayFrames = (UCHAR)value;
711     }
712     break;
713   case SBR_QMF_MODE:
714     if (self == NULL) {
715       errorStatus = SBRDEC_NOT_INITIALIZED;
716     } else {
717       if (value == 1) {
718         self->flags |= SBRDEC_LOW_POWER;
719       } else {
720         self->flags &= ~SBRDEC_LOW_POWER;
721       }
722     }
723     break;
724   case SBR_LD_QMF_TIME_ALIGN:
725     if (self == NULL) {
726       errorStatus = SBRDEC_NOT_INITIALIZED;
727     } else {
728       if (value == 1) {
729         self->flags |= SBRDEC_LD_MPS_QMF;
730       } else {
731         self->flags &= ~SBRDEC_LD_MPS_QMF;
732       }
733     }
734     break;
735   case SBR_FLUSH_DATA:
736     if (value != 0) {
737       if (self == NULL) {
738         errorStatus = SBRDEC_NOT_INITIALIZED;
739       } else {
740         self->flags |= SBRDEC_FLUSH;
741       }
742     }
743     break;
744   case SBR_CLEAR_HISTORY:
745     if (value != 0) {
746       if (self == NULL) {
747         errorStatus = SBRDEC_NOT_INITIALIZED;
748       } else {
749         self->flags |= SBRDEC_FORCE_RESET;
750       }
751     }
752     break;
753   case SBR_BS_INTERRUPTION:
754     {
755       int elementIndex;
756 
757       if (self == NULL) {
758         errorStatus = SBRDEC_NOT_INITIALIZED;
759         break;
760       }
761 
762       /* Loop over SBR elements */
763       for (elementIndex = 0; elementIndex < self->numSbrElements; elementIndex++) {
764       if (self->pSbrElement[elementIndex] != NULL)
765       {
766         HANDLE_SBR_HEADER_DATA hSbrHeader;
767         int headerIndex = getHeaderSlot(self->pSbrElement[elementIndex]->useFrameSlot,
768                                         self->pSbrElement[elementIndex]->useHeaderSlot);
769 
770         hSbrHeader = &(self->sbrHeader[elementIndex][headerIndex]);
771 
772         /* Set sync state UPSAMPLING for the corresponding slot.
773            This switches off bitstream parsing until a new header arrives. */
774         hSbrHeader->syncState = UPSAMPLING;
775         hSbrHeader->status   |= SBRDEC_HDR_STAT_UPDATE;
776       } }
777     }
778     break;
779   default:
780     errorStatus = SBRDEC_SET_PARAM_FAIL;
781     break;
782   }  /* switch(param) */
783 
784   return (errorStatus);
785 }
786 
787 static
sbrDecoder_drcGetChannel(const HANDLE_SBRDECODER self,const INT channel)788 SBRDEC_DRC_CHANNEL * sbrDecoder_drcGetChannel( const HANDLE_SBRDECODER self, const INT channel )
789 {
790   SBRDEC_DRC_CHANNEL *pSbrDrcChannelData = NULL;
791   int elementIndex, elChanIdx=0, numCh=0;
792 
793   for (elementIndex = 0; (elementIndex < (8)) && (numCh <= channel); elementIndex++)
794   {
795     SBR_DECODER_ELEMENT *pSbrElement = self->pSbrElement[elementIndex];
796     int c, elChannels;
797 
798     elChanIdx = 0;
799     if (pSbrElement == NULL) break;
800 
801     /* Determine amount of channels for this element */
802     switch (pSbrElement->elementID) {
803       case ID_CPE: elChannels = 2;
804         break;
805       case ID_LFE:
806       case ID_SCE: elChannels = 1;
807         break;
808       case ID_NONE:
809       default: elChannels = 0;
810         break;
811     }
812 
813     /* Limit with actual allocated element channels */
814     elChannels = FDKmin(elChannels, pSbrElement->nChannels);
815 
816     for (c = 0; (c < elChannels) && (numCh <= channel); c++) {
817       if (pSbrElement->pSbrChannel[elChanIdx] != NULL) {
818         numCh++;
819         elChanIdx++;
820       }
821     }
822   }
823   elementIndex -= 1;
824   elChanIdx -= 1;
825 
826   if (elChanIdx < 0 || elementIndex < 0) {
827     return NULL;
828   }
829 
830   if ( self->pSbrElement[elementIndex] != NULL ) {
831     if ( self->pSbrElement[elementIndex]->pSbrChannel[elChanIdx] != NULL )
832     {
833       pSbrDrcChannelData = &self->pSbrElement[elementIndex]->pSbrChannel[elChanIdx]->SbrDec.sbrDrcChannel;
834     }
835   }
836 
837   return (pSbrDrcChannelData);
838 }
839 
sbrDecoder_drcFeedChannel(HANDLE_SBRDECODER self,INT ch,UINT numBands,FIXP_DBL * pNextFact_mag,INT nextFact_exp,SHORT drcInterpolationScheme,UCHAR winSequence,USHORT * pBandTop)840 SBR_ERROR sbrDecoder_drcFeedChannel ( HANDLE_SBRDECODER  self,
841                                       INT                ch,
842                                       UINT               numBands,
843                                       FIXP_DBL          *pNextFact_mag,
844                                       INT                nextFact_exp,
845                                       SHORT              drcInterpolationScheme,
846                                       UCHAR              winSequence,
847                                       USHORT            *pBandTop )
848 {
849   SBRDEC_DRC_CHANNEL *pSbrDrcChannelData = NULL;
850   int band, isValidData = 0;
851 
852   if (self == NULL) {
853     return SBRDEC_NOT_INITIALIZED;
854   }
855   if (ch > (8) || pNextFact_mag == NULL) {
856     return SBRDEC_SET_PARAM_FAIL;
857   }
858 
859   /* Search for gain values different to 1.0f */
860   for (band = 0; band < numBands; band += 1) {
861     if ( !((pNextFact_mag[band] == FL2FXCONST_DBL(0.5))  && (nextFact_exp == 1))
862       && !((pNextFact_mag[band] == (FIXP_DBL)MAXVAL_DBL) && (nextFact_exp == 0)) ) {
863       isValidData = 1;
864       break;
865     }
866   }
867 
868   /* Find the right SBR channel */
869   pSbrDrcChannelData = sbrDecoder_drcGetChannel( self, ch );
870 
871   if ( pSbrDrcChannelData != NULL ) {
872     if ( pSbrDrcChannelData->enable || isValidData )
873   { /* Activate processing only with real and valid data */
874     int i;
875 
876     pSbrDrcChannelData->enable   = 1;
877     pSbrDrcChannelData->numBandsNext = numBands;
878 
879     pSbrDrcChannelData->winSequenceNext            = winSequence;
880     pSbrDrcChannelData->drcInterpolationSchemeNext = drcInterpolationScheme;
881     pSbrDrcChannelData->nextFact_exp               = nextFact_exp;
882 
883     for (i = 0; i < (int)numBands; i++) {
884       pSbrDrcChannelData->bandTopNext[i]  = pBandTop[i];
885       pSbrDrcChannelData->nextFact_mag[i] = pNextFact_mag[i];
886     }
887   }
888   }
889 
890   return SBRDEC_OK;
891 }
892 
893 
sbrDecoder_drcDisable(HANDLE_SBRDECODER self,INT ch)894 void sbrDecoder_drcDisable ( HANDLE_SBRDECODER  self,
895                              INT                ch )
896 {
897   SBRDEC_DRC_CHANNEL *pSbrDrcChannelData = NULL;
898 
899   if ( (self == NULL)
900     || (ch > (8))
901     || (self->numSbrElements == 0)
902     || (self->numSbrChannels == 0) ) {
903     return;
904   }
905 
906   /* Find the right SBR channel */
907   pSbrDrcChannelData = sbrDecoder_drcGetChannel( self, ch );
908 
909   if ( pSbrDrcChannelData != NULL ) {
910     sbrDecoder_drcInitChannel( pSbrDrcChannelData );
911   }
912 }
913 
914 
915 
sbrDecoder_Parse(HANDLE_SBRDECODER self,HANDLE_FDK_BITSTREAM hBs,int * count,int bsPayLen,int crcFlag,MP4_ELEMENT_ID prevElement,int elementIndex,int fGlobalIndependencyFlag)916 SBR_ERROR sbrDecoder_Parse(
917         HANDLE_SBRDECODER self,
918         HANDLE_FDK_BITSTREAM  hBs,
919         int *count,
920         int  bsPayLen,
921         int  crcFlag,
922         MP4_ELEMENT_ID prevElement,
923         int elementIndex,
924         int fGlobalIndependencyFlag
925         )
926 {
927   SBR_DECODER_ELEMENT   *hSbrElement;
928   HANDLE_SBR_HEADER_DATA hSbrHeader;
929   HANDLE_SBR_CHANNEL    *pSbrChannel;
930 
931   SBR_FRAME_DATA *hFrameDataLeft;
932   SBR_FRAME_DATA *hFrameDataRight;
933 
934   SBR_ERROR errorStatus = SBRDEC_OK;
935   SBR_SYNC_STATE initialSyncState;
936   SBR_HEADER_STATUS headerStatus = HEADER_NOT_PRESENT;
937 
938   INT  startPos;
939   INT  CRCLen = 0;
940 
941   int  stereo;
942   int  fDoDecodeSbrData = 1;
943 
944   int lastSlot, lastHdrSlot = 0, thisHdrSlot;
945 
946   /* Remember start position of  SBR element */
947   startPos = FDKgetValidBits(hBs);
948 
949   /* SBR sanity checks */
950   if ( self == NULL || self->pSbrElement[elementIndex] == NULL ) {
951     errorStatus = SBRDEC_NOT_INITIALIZED;
952     goto bail;
953   }
954 
955   hSbrElement = self->pSbrElement[elementIndex];
956 
957   lastSlot    = (hSbrElement->useFrameSlot > 0) ? hSbrElement->useFrameSlot-1 : self->numDelayFrames;
958   lastHdrSlot =  hSbrElement->useHeaderSlot[lastSlot];
959   thisHdrSlot =  getHeaderSlot( hSbrElement->useFrameSlot, hSbrElement->useHeaderSlot );  /* Get a free header slot not used by frames not processed yet. */
960 
961   /* Assign the free slot to store a new header if there is one. */
962   hSbrHeader = &self->sbrHeader[elementIndex][thisHdrSlot];
963 
964   pSbrChannel = hSbrElement->pSbrChannel;
965   stereo = (hSbrElement->elementID == ID_CPE) ? 1 : 0;
966 
967   hFrameDataLeft  = &self->pSbrElement[elementIndex]->pSbrChannel[0]->frameData[hSbrElement->useFrameSlot];
968   hFrameDataRight = &self->pSbrElement[elementIndex]->pSbrChannel[1]->frameData[hSbrElement->useFrameSlot];
969 
970   initialSyncState = hSbrHeader->syncState;
971 
972   /* reset PS flag; will be set after PS was found */
973   self->flags &= ~SBRDEC_PS_DECODED;
974 
975   if (hSbrHeader->status & SBRDEC_HDR_STAT_UPDATE) {
976     /* Got a new header from extern (e.g. from an ASC) */
977     headerStatus = HEADER_OK;
978     hSbrHeader->status &= ~SBRDEC_HDR_STAT_UPDATE;
979   }
980   else if (thisHdrSlot != lastHdrSlot) {
981     /* Copy the last header into this slot otherwise the
982        header compare will trigger more HEADER_RESETs than needed. */
983     copySbrHeader( hSbrHeader, &self->sbrHeader[elementIndex][lastHdrSlot] );
984   }
985 
986   /*
987      Check if bit stream data is valid and matches the element context
988   */
989   if ( ((prevElement != ID_SCE) && (prevElement != ID_CPE)) || prevElement != hSbrElement->elementID) {
990     /* In case of LFE we also land here, since there is no LFE SBR element (do upsampling only) */
991     fDoDecodeSbrData = 0;
992   }
993 
994   if (fDoDecodeSbrData)
995   {
996     if ((INT)FDKgetValidBits(hBs) <= 0) {
997       fDoDecodeSbrData = 0;
998     }
999   }
1000 
1001   /*
1002      SBR CRC-check
1003   */
1004   if (fDoDecodeSbrData)
1005   {
1006     if (crcFlag == 1) {
1007       switch (self->coreCodec) {
1008       case AOT_ER_AAC_ELD:
1009         FDKpushFor (hBs, 10);
1010         /* check sbrcrc later: we don't know the payload length now */
1011         break;
1012       default:
1013         CRCLen = bsPayLen - 10;                     /* change: 0 => i */
1014         if (CRCLen < 0) {
1015           fDoDecodeSbrData = 0;
1016         } else {
1017           fDoDecodeSbrData = SbrCrcCheck (hBs, CRCLen);
1018         }
1019         break;
1020       }
1021     }
1022   } /* if (fDoDecodeSbrData) */
1023 
1024   /*
1025      Read in the header data and issue a reset if change occured
1026   */
1027   if (fDoDecodeSbrData)
1028   {
1029     int sbrHeaderPresent;
1030 
1031     {
1032       sbrHeaderPresent = FDKreadBit(hBs);
1033     }
1034 
1035     if ( sbrHeaderPresent ) {
1036       headerStatus = sbrGetHeaderData (hSbrHeader,
1037                                        hBs,
1038                                        self->flags,
1039                                        1);
1040     }
1041 
1042     if (headerStatus == HEADER_RESET)
1043     {
1044       errorStatus = sbrDecoder_HeaderUpdate(
1045             self,
1046             hSbrHeader,
1047             headerStatus,
1048             pSbrChannel,
1049             hSbrElement->nChannels
1050             );
1051 
1052       if (errorStatus == SBRDEC_OK) {
1053         hSbrHeader->syncState = SBR_HEADER;
1054       } else {
1055         hSbrHeader->syncState = SBR_NOT_INITIALIZED;
1056       }
1057     }
1058 
1059     if (errorStatus != SBRDEC_OK) {
1060       fDoDecodeSbrData = 0;
1061     }
1062   } /* if (fDoDecodeSbrData) */
1063 
1064   /*
1065     Print debugging output only if state has changed
1066   */
1067 
1068   /* read frame data */
1069   if ((hSbrHeader->syncState >= SBR_HEADER) && fDoDecodeSbrData) {
1070     int sbrFrameOk;
1071     /* read the SBR element data */
1072     if (stereo) {
1073       sbrFrameOk = sbrGetChannelPairElement(hSbrHeader,
1074                                             hFrameDataLeft,
1075                                             hFrameDataRight,
1076                                             hBs,
1077                                             self->flags,
1078                                             self->pSbrElement[elementIndex]->transposerSettings.overlap);
1079     }
1080     else {
1081       if (self->hParametricStereoDec != NULL) {
1082         /* update slot index for PS bitstream parsing */
1083         self->hParametricStereoDec->bsLastSlot = self->hParametricStereoDec->bsReadSlot;
1084         self->hParametricStereoDec->bsReadSlot = hSbrElement->useFrameSlot;
1085       }
1086       sbrFrameOk = sbrGetSingleChannelElement(hSbrHeader,
1087                                               hFrameDataLeft,
1088                                               hBs,
1089                                               self->hParametricStereoDec,
1090                                               self->flags,
1091                                               self->pSbrElement[elementIndex]->transposerSettings.overlap);
1092     }
1093     if (!sbrFrameOk) {
1094       fDoDecodeSbrData = 0;
1095     }
1096     else {
1097       INT valBits;
1098 
1099       if (bsPayLen > 0) {
1100         valBits = bsPayLen - ((INT)startPos - (INT)FDKgetValidBits(hBs));
1101       } else {
1102         valBits = (INT)FDKgetValidBits(hBs);
1103       }
1104 
1105       if ( crcFlag == 1 ) {
1106         switch (self->coreCodec) {
1107         case AOT_ER_AAC_ELD:
1108           {
1109             /* late crc check for eld */
1110             INT payloadbits = (INT)startPos - (INT)FDKgetValidBits(hBs) - startPos;
1111             INT crcLen      = payloadbits - 10;
1112             FDKpushBack(hBs, payloadbits);
1113             fDoDecodeSbrData      = SbrCrcCheck (hBs, crcLen);
1114             FDKpushFor(hBs, crcLen);
1115           }
1116           break;
1117         default:
1118           break;
1119         }
1120       }
1121 
1122       /* sanity check of remaining bits */
1123       if (valBits < 0) {
1124         fDoDecodeSbrData = 0;
1125       } else {
1126         switch (self->coreCodec) {
1127         case AOT_SBR:
1128         case AOT_PS:
1129         case AOT_AAC_LC:
1130           {
1131             /* This sanity check is only meaningful with General Audio bitstreams */
1132             int alignBits = valBits & 0x7;
1133 
1134             if (valBits > alignBits) {
1135               fDoDecodeSbrData = 0;
1136             }
1137           }
1138           break;
1139         default:
1140           /* No sanity check available */
1141           break;
1142         }
1143       }
1144     }
1145   } else {
1146     /* The returned bit count will not be the actual payload size since we did not
1147        parse the frame data. Return an error so that the caller can react respectively. */
1148     errorStatus = SBRDEC_PARSE_ERROR;
1149   }
1150 
1151   if (!fDoDecodeSbrData) {
1152     /* Set error flag for this slot to trigger concealment */
1153     self->pSbrElement[elementIndex]->frameErrorFlag[hSbrElement->useFrameSlot] = 1;
1154     errorStatus = SBRDEC_PARSE_ERROR;
1155   } else {
1156     /* Everything seems to be ok so clear the error flag */
1157     self->pSbrElement[elementIndex]->frameErrorFlag[hSbrElement->useFrameSlot] = 0;
1158   }
1159 
1160   if (!stereo) {
1161     /* Turn coupling off explicitely to avoid access to absent right frame data
1162        that might occur with corrupt bitstreams. */
1163     hFrameDataLeft->coupling = COUPLING_OFF;
1164   }
1165 
1166 bail:
1167   if (errorStatus == SBRDEC_OK) {
1168     if (headerStatus == HEADER_NOT_PRESENT) {
1169       /* Use the old header for this frame */
1170       hSbrElement->useHeaderSlot[hSbrElement->useFrameSlot] = lastHdrSlot;
1171     } else {
1172       /* Use the new header for this frame */
1173       hSbrElement->useHeaderSlot[hSbrElement->useFrameSlot] = thisHdrSlot;
1174     }
1175 
1176     /* Move frame pointer to the next slot which is up to be decoded/applied next */
1177     hSbrElement->useFrameSlot = (hSbrElement->useFrameSlot+1) % (self->numDelayFrames+1);
1178   }
1179 
1180   *count -= startPos - FDKgetValidBits(hBs);
1181 
1182   return errorStatus;
1183 }
1184 
1185 
1186 /**
1187  * \brief Render one SBR element into time domain signal.
1188  * \param self SBR decoder handle
1189  * \param timeData pointer to output buffer
1190  * \param interleaved flag indicating interleaved channel output
1191  * \param channelMapping pointer to UCHAR array where next 2 channel offsets are stored.
1192  * \param elementIndex enumerating index of the SBR element to render.
1193  * \param numInChannels number of channels from core coder (reading stride).
1194  * \param numOutChannels pointer to a location to return number of output channels.
1195  * \param psPossible flag indicating if PS is possible or not.
1196  * \return SBRDEC_OK if successfull, else error code
1197  */
1198 static SBR_ERROR
sbrDecoder_DecodeElement(HANDLE_SBRDECODER self,INT_PCM * timeData,const int interleaved,const UCHAR * channelMapping,const int elementIndex,const int numInChannels,int * numOutChannels,const int psPossible)1199 sbrDecoder_DecodeElement (
1200         HANDLE_SBRDECODER    self,
1201         INT_PCM             *timeData,
1202         const int            interleaved,
1203         const UCHAR         *channelMapping,
1204         const int            elementIndex,
1205         const int            numInChannels,
1206         int                 *numOutChannels,
1207         const int            psPossible
1208         )
1209 {
1210   SBR_DECODER_ELEMENT *hSbrElement = self->pSbrElement[elementIndex];
1211   HANDLE_SBR_CHANNEL    *pSbrChannel = self->pSbrElement[elementIndex]->pSbrChannel;
1212   HANDLE_SBR_HEADER_DATA hSbrHeader = &self->sbrHeader[elementIndex][hSbrElement->useHeaderSlot[hSbrElement->useFrameSlot]];
1213   HANDLE_PS_DEC h_ps_d = self->hParametricStereoDec;
1214 
1215   /* get memory for frame data from scratch */
1216   SBR_FRAME_DATA *hFrameDataLeft  = &hSbrElement->pSbrChannel[0]->frameData[hSbrElement->useFrameSlot];
1217   SBR_FRAME_DATA *hFrameDataRight = &hSbrElement->pSbrChannel[1]->frameData[hSbrElement->useFrameSlot];
1218 
1219   SBR_ERROR errorStatus = SBRDEC_OK;
1220 
1221 
1222   INT  strideIn, strideOut, offset0, offset1;
1223   INT  codecFrameSize = self->codecFrameSize;
1224 
1225   int  stereo = (hSbrElement->elementID == ID_CPE) ? 1 : 0;
1226   int  numElementChannels = hSbrElement->nChannels; /* Number of channels of the current SBR element */
1227 
1228   if (self->flags & SBRDEC_FLUSH) {
1229     /* Move frame pointer to the next slot which is up to be decoded/applied next */
1230     hSbrElement->useFrameSlot = (hSbrElement->useFrameSlot+1) % (self->numDelayFrames+1);
1231     /* Update header and frame data pointer because they have already been set */
1232     hSbrHeader = &self->sbrHeader[elementIndex][hSbrElement->useHeaderSlot[hSbrElement->useFrameSlot]];
1233     hFrameDataLeft  = &hSbrElement->pSbrChannel[0]->frameData[hSbrElement->useFrameSlot];
1234     hFrameDataRight = &hSbrElement->pSbrChannel[1]->frameData[hSbrElement->useFrameSlot];
1235   }
1236 
1237   /* Update the header error flag */
1238   hSbrHeader->frameErrorFlag = hSbrElement->frameErrorFlag[hSbrElement->useFrameSlot];
1239 
1240   /*
1241      Prepare filterbank for upsampling if no valid bit stream data is available.
1242    */
1243   if ( hSbrHeader->syncState == SBR_NOT_INITIALIZED )
1244   {
1245     errorStatus = initHeaderData(
1246             hSbrHeader,
1247             self->sampleRateIn,
1248             self->sampleRateOut,
1249             codecFrameSize,
1250             self->flags
1251             );
1252 
1253     if (errorStatus != SBRDEC_OK) {
1254       return errorStatus;
1255     }
1256 
1257     hSbrHeader->syncState = UPSAMPLING;
1258 
1259     errorStatus = sbrDecoder_HeaderUpdate(
1260             self,
1261             hSbrHeader,
1262             HEADER_NOT_PRESENT,
1263             pSbrChannel,
1264             hSbrElement->nChannels
1265             );
1266 
1267     if (errorStatus != SBRDEC_OK) {
1268       hSbrHeader->syncState = SBR_NOT_INITIALIZED;
1269       return errorStatus;
1270     }
1271   }
1272 
1273   /* reset */
1274   if (hSbrHeader->status & SBRDEC_HDR_STAT_RESET) {
1275     int ch;
1276     for (ch = 0 ; ch < numElementChannels; ch++) {
1277       SBR_ERROR errorStatusTmp = SBRDEC_OK;
1278 
1279       errorStatusTmp = resetSbrDec (
1280              &pSbrChannel[ch]->SbrDec,
1281               hSbrHeader,
1282              &pSbrChannel[ch]->prevFrameData,
1283               self->flags & SBRDEC_LOW_POWER,
1284               self->synDownsampleFac
1285               );
1286 
1287       if (errorStatusTmp != SBRDEC_OK) {
1288         errorStatus = errorStatusTmp;
1289       }
1290     }
1291     hSbrHeader->status &= ~SBRDEC_HDR_STAT_RESET;
1292   }
1293 
1294   /* decoding */
1295   if ( (hSbrHeader->syncState == SBR_ACTIVE)
1296     || ((hSbrHeader->syncState == SBR_HEADER) && (hSbrHeader->frameErrorFlag == 0)) )
1297   {
1298     errorStatus = SBRDEC_OK;
1299 
1300     decodeSbrData (hSbrHeader,
1301                    hFrameDataLeft,
1302                   &pSbrChannel[0]->prevFrameData,
1303                    (stereo) ? hFrameDataRight : NULL,
1304                    (stereo) ? &pSbrChannel[1]->prevFrameData : NULL);
1305 
1306 
1307     /* Now we have a full parameter set and can do parameter
1308        based concealment instead of plain upsampling. */
1309     hSbrHeader->syncState = SBR_ACTIVE;
1310   }
1311 
1312   /* decode PS data if available */
1313   if (h_ps_d != NULL && psPossible) {
1314     int applyPs = 1;
1315 
1316     /* define which frame delay line slot to process */
1317     h_ps_d->processSlot = hSbrElement->useFrameSlot;
1318 
1319     applyPs = DecodePs(h_ps_d, hSbrHeader->frameErrorFlag);
1320     self->flags |= (applyPs) ? SBRDEC_PS_DECODED : 0;
1321   }
1322 
1323   /* Set strides for reading and writing */
1324   if (interleaved) {
1325     strideIn = numInChannels;
1326     if ( psPossible )
1327       strideOut = (numInChannels < 2) ? 2 : numInChannels;
1328     else
1329       strideOut = numInChannels;
1330     offset0 = channelMapping[0];
1331     offset1 = channelMapping[1];
1332   } else {
1333     strideIn  = 1;
1334     strideOut = 1;
1335     offset0 = channelMapping[0]*2*codecFrameSize;
1336     offset1 = channelMapping[1]*2*codecFrameSize;
1337   }
1338 
1339   /* use same buffers for left and right channel and apply PS per timeslot */
1340   /* Process left channel */
1341 //FDKprintf("self->codecFrameSize %d\t%d\n",self->codecFrameSize,self->sampleRateIn);
1342   sbr_dec (&pSbrChannel[0]->SbrDec,
1343             timeData + offset0,
1344             timeData + offset0,
1345            &pSbrChannel[1]->SbrDec,
1346             timeData + offset1,
1347             strideIn,
1348             strideOut,
1349             hSbrHeader,
1350             hFrameDataLeft,
1351            &pSbrChannel[0]->prevFrameData,
1352             (hSbrHeader->syncState == SBR_ACTIVE),
1353             h_ps_d,
1354             self->flags
1355           );
1356 
1357   if (stereo) {
1358     /* Process right channel */
1359     sbr_dec (&pSbrChannel[1]->SbrDec,
1360               timeData + offset1,
1361               timeData + offset1,
1362               NULL,
1363               NULL,
1364               strideIn,
1365               strideOut,
1366               hSbrHeader,
1367               hFrameDataRight,
1368              &pSbrChannel[1]->prevFrameData,
1369               (hSbrHeader->syncState == SBR_ACTIVE),
1370               NULL,
1371               self->flags
1372             );
1373   }
1374 
1375   if (h_ps_d != NULL) {
1376     /* save PS status for next run */
1377     h_ps_d->psDecodedPrv = (self->flags & SBRDEC_PS_DECODED) ? 1 : 0 ;
1378   }
1379 
1380   if ( psPossible
1381     )
1382   {
1383     FDK_ASSERT(strideOut > 1);
1384     if ( !(self->flags & SBRDEC_PS_DECODED) ) {
1385       /* A decoder which is able to decode PS has to produce a stereo output even if no PS data is availble. */
1386       /* So copy left channel to right channel.                                                              */
1387       if (interleaved) {
1388         INT_PCM *ptr;
1389         INT i;
1390         FDK_ASSERT(strideOut == 2);
1391 
1392         ptr = timeData;
1393         for (i = codecFrameSize; i--; )
1394         {
1395           INT_PCM tmp; /* This temporal variable is required because some compilers can't do *ptr++ = *ptr++ correctly. */
1396           tmp = *ptr++; *ptr++ = tmp;
1397           tmp = *ptr++; *ptr++ = tmp;
1398         }
1399       } else {
1400         FDKmemcpy( timeData+2*codecFrameSize, timeData, 2*codecFrameSize*sizeof(INT_PCM) );
1401       }
1402     }
1403     *numOutChannels = 2;  /* Output minimum two channels when PS is enabled. */
1404   }
1405 
1406   return errorStatus;
1407 }
1408 
1409 
sbrDecoder_Apply(HANDLE_SBRDECODER self,INT_PCM * timeData,int * numChannels,int * sampleRate,const UCHAR channelMapping[(8)],const int interleaved,const int coreDecodedOk,UCHAR * psDecoded)1410 SBR_ERROR sbrDecoder_Apply ( HANDLE_SBRDECODER   self,
1411                              INT_PCM            *timeData,
1412                              int                *numChannels,
1413                              int                *sampleRate,
1414                              const UCHAR         channelMapping[(8)],
1415                              const int           interleaved,
1416                              const int           coreDecodedOk,
1417                              UCHAR              *psDecoded )
1418 {
1419   SBR_ERROR errorStatus = SBRDEC_OK;
1420 
1421   int   psPossible = 0;
1422   int   sbrElementNum;
1423   int   numCoreChannels = *numChannels;
1424   int   numSbrChannels  = 0;
1425 
1426   psPossible = *psDecoded;
1427 
1428   if (self->numSbrElements < 1) {
1429     /* exit immediately to avoid access violations */
1430     return SBRDEC_CREATE_ERROR;
1431   }
1432 
1433   /* Sanity check of allocated SBR elements. */
1434   for (sbrElementNum=0; sbrElementNum<self->numSbrElements; sbrElementNum++) {
1435     if (self->pSbrElement[sbrElementNum] == NULL) {
1436       return SBRDEC_CREATE_ERROR;
1437     }
1438   }
1439 
1440   if (self->numSbrElements != 1 || self->pSbrElement[0]->elementID != ID_SCE) {
1441     psPossible = 0;
1442   }
1443 
1444 
1445   /* In case of non-interleaved time domain data and upsampling, make room for bigger SBR output. */
1446   if (self->synDownsampleFac == 1 && interleaved == 0) {
1447     int c, outputFrameSize;
1448 
1449     outputFrameSize =
1450             self->pSbrElement[0]->pSbrChannel[0]->SbrDec.SynthesisQMF.no_channels
1451             * self->pSbrElement[0]->pSbrChannel[0]->SbrDec.SynthesisQMF.no_col;
1452 
1453     for (c=numCoreChannels-1; c>0; c--) {
1454       FDKmemmove(timeData + c*outputFrameSize, timeData + c*self->codecFrameSize , self->codecFrameSize*sizeof(INT_PCM));
1455     }
1456   }
1457 
1458 
1459   /* Make sure that even if no SBR data was found/parsed *psDecoded is returned 1 if psPossible was 0. */
1460   if (psPossible == 0) {
1461     self->flags &= ~SBRDEC_PS_DECODED;
1462   }
1463 
1464   /* Loop over SBR elements */
1465   for (sbrElementNum = 0; sbrElementNum<self->numSbrElements; sbrElementNum++)
1466   {
1467     int numElementChan;
1468 
1469     if (psPossible && self->pSbrElement[sbrElementNum]->pSbrChannel[1] == NULL) {
1470       errorStatus = SBRDEC_UNSUPPORTED_CONFIG;
1471       goto bail;
1472     }
1473 
1474     numElementChan = (self->pSbrElement[sbrElementNum]->elementID == ID_CPE) ? 2 : 1;
1475 
1476     /* If core signal is bad then force upsampling */
1477     if ( ! coreDecodedOk ) {
1478       self->pSbrElement[sbrElementNum]->frameErrorFlag[self->pSbrElement[sbrElementNum]->useFrameSlot] = 1;
1479     }
1480 
1481     errorStatus = sbrDecoder_DecodeElement (
1482                                  self,
1483                                  timeData,
1484                                  interleaved,
1485                                  channelMapping,
1486                                  sbrElementNum,
1487                                  numCoreChannels,
1488                                 &numElementChan,
1489                                  psPossible
1490                                );
1491 
1492     if (errorStatus != SBRDEC_OK) {
1493       goto bail;
1494     }
1495 
1496     numSbrChannels += numElementChan;
1497     channelMapping += numElementChan;
1498 
1499     if (numSbrChannels >= numCoreChannels) {
1500       break;
1501     }
1502   }
1503 
1504   /* Update numChannels and samplerate */
1505   *numChannels = numSbrChannels;
1506   *sampleRate = self->sampleRateOut;
1507   *psDecoded = (self->flags & SBRDEC_PS_DECODED) ? 1 : 0;
1508 
1509 
1510 
1511   /* Clear reset and flush flag because everything seems to be done successfully. */
1512   self->flags &= ~SBRDEC_FORCE_RESET;
1513   self->flags &= ~SBRDEC_FLUSH;
1514 
1515 bail:
1516 
1517   return errorStatus;
1518 }
1519 
1520 
sbrDecoder_Close(HANDLE_SBRDECODER * pSelf)1521 SBR_ERROR sbrDecoder_Close ( HANDLE_SBRDECODER *pSelf )
1522 {
1523   HANDLE_SBRDECODER self = *pSelf;
1524   int i;
1525 
1526   if (self != NULL)
1527   {
1528     if (self->hParametricStereoDec != NULL) {
1529       DeletePsDec ( &self->hParametricStereoDec );
1530     }
1531 
1532     if (self->workBuffer1 != NULL) {
1533       FreeRam_SbrDecWorkBuffer1(&self->workBuffer1);
1534     }
1535     if (self->workBuffer2 != NULL) {
1536       FreeRam_SbrDecWorkBuffer2(&self->workBuffer2);
1537     }
1538 
1539     for (i = 0; i < (8); i++) {
1540       sbrDecoder_DestroyElement( self, i );
1541     }
1542 
1543     FreeRam_SbrDecoder(pSelf);
1544   }
1545 
1546   return SBRDEC_OK;
1547 }
1548 
1549 
sbrDecoder_GetLibInfo(LIB_INFO * info)1550 INT sbrDecoder_GetLibInfo( LIB_INFO *info )
1551 {
1552   int i;
1553 
1554   if (info == NULL) {
1555     return -1;
1556   }
1557 
1558   /* search for next free tab */
1559   for (i = 0; i < FDK_MODULE_LAST; i++) {
1560     if (info[i].module_id == FDK_NONE)
1561       break;
1562   }
1563   if (i == FDK_MODULE_LAST)
1564     return -1;
1565   info += i;
1566 
1567   info->module_id = FDK_SBRDEC;
1568   info->version = LIB_VERSION(SBRDECODER_LIB_VL0, SBRDECODER_LIB_VL1, SBRDECODER_LIB_VL2);
1569   LIB_VERSION_STRING(info);
1570   info->build_date = (char *)SBRDECODER_LIB_BUILD_DATE;
1571   info->build_time = (char *)SBRDECODER_LIB_BUILD_TIME;
1572   info->title      = (char *)SBRDECODER_LIB_TITLE;
1573 
1574   /* Set flags */
1575   info->flags = 0
1576     | CAPF_SBR_HQ
1577     | CAPF_SBR_LP
1578     | CAPF_SBR_PS_MPEG
1579     | CAPF_SBR_CONCEALMENT
1580     | CAPF_SBR_DRC
1581       ;
1582   /* End of flags */
1583 
1584   return 0;
1585 }
1586 
1587 
sbrDecoder_GetDelay(const HANDLE_SBRDECODER self)1588 UINT sbrDecoder_GetDelay( const HANDLE_SBRDECODER self )
1589 {
1590   UINT outputDelay = 0;
1591 
1592   if ( self != NULL) {
1593     UINT flags = self->flags;
1594 
1595     /* See chapter 1.6.7.2 of ISO/IEC 14496-3 for the GA-SBR figures below. */
1596 
1597     /* Are we initialized? */
1598     if ( (self->numSbrChannels > 0)
1599       && (self->numSbrElements > 0) )
1600     {
1601       /* Add QMF synthesis delay */
1602       if ( (flags & SBRDEC_ELD_GRID)
1603         && IS_LOWDELAY(self->coreCodec) ) {
1604         /* Low delay SBR: */
1605         {
1606           outputDelay += (flags & SBRDEC_DOWNSAMPLE) ? 32 : 64;   /* QMF synthesis */
1607         }
1608       }
1609       else if (!IS_USAC(self->coreCodec)) {
1610         /* By the method of elimination this is the GA (AAC-LC, HE-AAC, ...) branch: */
1611         outputDelay += (flags & SBRDEC_DOWNSAMPLE) ? 481 : 962;
1612       }
1613     }
1614   }
1615 
1616   return (outputDelay);
1617 }
1618