• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 
2 /* -----------------------------------------------------------------------------------------------------------
3 Software License for The Fraunhofer FDK AAC Codec Library for Android
4 
5 � Copyright  1995 - 2012 Fraunhofer-Gesellschaft zur F�rderung der angewandten Forschung e.V.
6   All rights reserved.
7 
8  1.    INTRODUCTION
9 The Fraunhofer FDK AAC Codec Library for Android ("FDK AAC Codec") is software that implements
10 the MPEG Advanced Audio Coding ("AAC") encoding and decoding scheme for digital audio.
11 This FDK AAC Codec software is intended to be used on a wide variety of Android devices.
12 
13 AAC's HE-AAC and HE-AAC v2 versions are regarded as today's most efficient general perceptual
14 audio codecs. AAC-ELD is considered the best-performing full-bandwidth communications codec by
15 independent studies and is widely deployed. AAC has been standardized by ISO and IEC as part
16 of the MPEG specifications.
17 
18 Patent licenses for necessary patent claims for the FDK AAC Codec (including those of Fraunhofer)
19 may be obtained through Via Licensing (www.vialicensing.com) or through the respective patent owners
20 individually for the purpose of encoding or decoding bit streams in products that are compliant with
21 the ISO/IEC MPEG audio standards. Please note that most manufacturers of Android devices already license
22 these patent claims through Via Licensing or directly from the patent owners, and therefore FDK AAC Codec
23 software may already be covered under those patent licenses when it is used for those licensed purposes only.
24 
25 Commercially-licensed AAC software libraries, including floating-point versions with enhanced sound quality,
26 are also available from Fraunhofer. Users are encouraged to check the Fraunhofer website for additional
27 applications information and documentation.
28 
29 2.    COPYRIGHT LICENSE
30 
31 Redistribution and use in source and binary forms, with or without modification, are permitted without
32 payment of copyright license fees provided that you satisfy the following conditions:
33 
34 You must retain the complete text of this software license in redistributions of the FDK AAC Codec or
35 your modifications thereto in source code form.
36 
37 You must retain the complete text of this software license in the documentation and/or other materials
38 provided with redistributions of the FDK AAC Codec or your modifications thereto in binary form.
39 You must make available free of charge copies of the complete source code of the FDK AAC Codec and your
40 modifications thereto to recipients of copies in binary form.
41 
42 The name of Fraunhofer may not be used to endorse or promote products derived from this library without
43 prior written permission.
44 
45 You may not charge copyright license fees for anyone to use, copy or distribute the FDK AAC Codec
46 software or your modifications thereto.
47 
48 Your modified versions of the FDK AAC Codec must carry prominent notices stating that you changed the software
49 and the date of any change. For modified versions of the FDK AAC Codec, the term
50 "Fraunhofer FDK AAC Codec Library for Android" must be replaced by the term
51 "Third-Party Modified Version of the Fraunhofer FDK AAC Codec Library for Android."
52 
53 3.    NO PATENT LICENSE
54 
55 NO EXPRESS OR IMPLIED LICENSES TO ANY PATENT CLAIMS, including without limitation the patents of Fraunhofer,
56 ARE GRANTED BY THIS SOFTWARE LICENSE. Fraunhofer provides no warranty of patent non-infringement with
57 respect to this software.
58 
59 You may use this FDK AAC Codec software or modifications thereto only for purposes that are authorized
60 by appropriate patent licenses.
61 
62 4.    DISCLAIMER
63 
64 This FDK AAC Codec software is provided by Fraunhofer on behalf of the copyright holders and contributors
65 "AS IS" and WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, including but not limited to the implied warranties
66 of merchantability and fitness for a particular purpose. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
67 CONTRIBUTORS BE LIABLE for any direct, indirect, incidental, special, exemplary, or consequential damages,
68 including but not limited to procurement of substitute goods or services; loss of use, data, or profits,
69 or business interruption, however caused and on any theory of liability, whether in contract, strict
70 liability, or tort (including negligence), arising in any way out of the use of this software, even if
71 advised of the possibility of such damage.
72 
73 5.    CONTACT INFORMATION
74 
75 Fraunhofer Institute for Integrated Circuits IIS
76 Attention: Audio and Multimedia Departments - FDK AAC LL
77 Am Wolfsmantel 33
78 91058 Erlangen, Germany
79 
80 www.iis.fraunhofer.de/amm
81 amm-info@iis.fraunhofer.de
82 ----------------------------------------------------------------------------------------------------------- */
83 
84 /*!
85   \file
86   \brief  Sbr decoder
87   This module provides the actual decoder implementation. The SBR data (side information) is already
88   decoded. Only three functions are provided:
89 
90   \li 1.) createSbrDec(): One time initialization
91   \li 2.) resetSbrDec(): Called by sbr_Apply() when the information contained in an SBR_HEADER_ELEMENT requires a reset
92   and recalculation of important SBR structures.
93   \li 3.) sbr_dec(): The actual decoder. Calls the different tools such as filterbanks, lppTransposer(), and calculateSbrEnvelope()
94   [the envelope adjuster].
95 
96   \sa sbr_dec(), \ref documentationOverview
97 */
98 
99 #include "sbr_dec.h"
100 
101 #include "sbr_ram.h"
102 #include "env_extr.h"
103 #include "env_calc.h"
104 #include "scale.h"
105 
106 #include "genericStds.h"
107 
108 #include "sbrdec_drc.h"
109 
110 
111 
assignLcTimeSlots(HANDLE_SBR_DEC hSbrDec,FIXP_DBL ** QmfBufferReal,int noCols)112 static void assignLcTimeSlots( HANDLE_SBR_DEC hSbrDec,                     /*!< handle to Decoder channel */
113                                FIXP_DBL  **QmfBufferReal,
114                                int noCols )
115 {
116   int slot, i;
117   FIXP_DBL  *ptr;
118 
119   /* Number of QMF timeslots in the overlap buffer: */
120   ptr = hSbrDec->pSbrOverlapBuffer;
121   for(slot=0; slot<hSbrDec->LppTrans.pSettings->overlap; slot++) {
122     QmfBufferReal[slot] = ptr; ptr += (64);
123   }
124 
125   /* Assign timeslots to Workbuffer1 */
126   ptr = hSbrDec->WorkBuffer1;
127   for(i=0; i<noCols; i++) {
128     QmfBufferReal[slot] = ptr; ptr += (64);
129     slot++;
130   }
131 }
132 
133 
assignHqTimeSlots(HANDLE_SBR_DEC hSbrDec,FIXP_DBL ** QmfBufferReal,FIXP_DBL ** QmfBufferImag,int noCols)134 static void assignHqTimeSlots( HANDLE_SBR_DEC hSbrDec,                     /*!< handle to Decoder channel */
135                                FIXP_DBL  **QmfBufferReal,
136                                FIXP_DBL  **QmfBufferImag,
137                                int noCols )
138 {
139   FIXP_DBL  *ptr;
140   int slot;
141 
142   /* Number of QMF timeslots in one half of a frame (size of Workbuffer1 or 2): */
143   int halflen = (noCols >> 1) + hSbrDec->LppTrans.pSettings->overlap;
144   int totCols = noCols + hSbrDec->LppTrans.pSettings->overlap;
145 
146   /* Number of QMF timeslots in the overlap buffer: */
147   ptr = hSbrDec->pSbrOverlapBuffer;
148   for(slot=0; slot<hSbrDec->LppTrans.pSettings->overlap; slot++) {
149     QmfBufferReal[slot] = ptr; ptr += (64);
150     QmfBufferImag[slot] = ptr; ptr += (64);
151   }
152 
153   /* Assign first half of timeslots to Workbuffer1 */
154   ptr = hSbrDec->WorkBuffer1;
155   for(; slot<halflen; slot++) {
156     QmfBufferReal[slot] = ptr; ptr += (64);
157     QmfBufferImag[slot] = ptr; ptr += (64);
158   }
159 
160   /* Assign second half of timeslots to Workbuffer2 */
161   ptr = hSbrDec->WorkBuffer2;
162   for(; slot<totCols; slot++) {
163     QmfBufferReal[slot] = ptr; ptr += (64);
164     QmfBufferImag[slot] = ptr; ptr += (64);
165   }
166 }
167 
168 
assignTimeSlots(HANDLE_SBR_DEC hSbrDec,int noCols,int useLP)169 static void assignTimeSlots( HANDLE_SBR_DEC hSbrDec,                     /*!< handle to Decoder channel */
170                              int noCols,
171                              int useLP )
172 {
173  /* assign qmf time slots */
174   hSbrDec->useLP = useLP;
175   if (useLP) {
176     hSbrDec->SynthesisQMF.flags |= QMF_FLAG_LP;
177     hSbrDec->AnalysiscQMF.flags |= QMF_FLAG_LP;
178   } else {
179     hSbrDec->SynthesisQMF.flags &= ~QMF_FLAG_LP;
180     hSbrDec->AnalysiscQMF.flags &= ~QMF_FLAG_LP;
181   }
182   if (!useLP)
183     assignHqTimeSlots( hSbrDec, hSbrDec->QmfBufferReal, hSbrDec->QmfBufferImag, noCols );
184   else
185   {
186     assignLcTimeSlots( hSbrDec, hSbrDec->QmfBufferReal, noCols );
187   }
188 }
189 
changeQmfType(HANDLE_SBR_DEC hSbrDec,int useLdTimeAlign)190 static void changeQmfType( HANDLE_SBR_DEC hSbrDec,                     /*!< handle to Decoder channel */
191                            int useLdTimeAlign )
192 {
193   UINT synQmfFlags = hSbrDec->SynthesisQMF.flags;
194   UINT anaQmfFlags = hSbrDec->AnalysiscQMF.flags;
195   int  resetSynQmf = 0;
196   int  resetAnaQmf = 0;
197 
198   /* assign qmf type */
199   if (useLdTimeAlign) {
200     if (synQmfFlags & QMF_FLAG_CLDFB) {
201       /* change the type to MPSLD */
202       synQmfFlags &= ~QMF_FLAG_CLDFB;
203       synQmfFlags |=  QMF_FLAG_MPSLDFB;
204       resetSynQmf = 1;
205     }
206     if (anaQmfFlags & QMF_FLAG_CLDFB) {
207       /* change the type to MPSLD */
208       anaQmfFlags &= ~QMF_FLAG_CLDFB;
209       anaQmfFlags |=  QMF_FLAG_MPSLDFB;
210       resetAnaQmf = 1;
211     }
212   } else {
213     if (synQmfFlags & QMF_FLAG_MPSLDFB) {
214       /* change the type to CLDFB */
215       synQmfFlags &= ~QMF_FLAG_MPSLDFB;
216       synQmfFlags |=  QMF_FLAG_CLDFB;
217       resetSynQmf = 1;
218     }
219     if (anaQmfFlags & QMF_FLAG_MPSLDFB) {
220       /* change the type to CLDFB */
221       anaQmfFlags &= ~QMF_FLAG_MPSLDFB;
222       anaQmfFlags |=  QMF_FLAG_CLDFB;
223       resetAnaQmf = 1;
224     }
225   }
226 
227   if (resetAnaQmf) {
228     int qmfErr = qmfInitAnalysisFilterBank (
229            &hSbrDec->AnalysiscQMF,
230             hSbrDec->anaQmfStates,
231             hSbrDec->AnalysiscQMF.no_col,
232             hSbrDec->AnalysiscQMF.lsb,
233             hSbrDec->AnalysiscQMF.usb,
234             hSbrDec->AnalysiscQMF.no_channels,
235             anaQmfFlags | QMF_FLAG_KEEP_STATES
236             );
237     if (qmfErr != 0) {
238       FDK_ASSERT(0);
239     }
240   }
241 
242   if (resetSynQmf) {
243     int qmfErr = qmfInitSynthesisFilterBank (
244            &hSbrDec->SynthesisQMF,
245             hSbrDec->pSynQmfStates,
246             hSbrDec->SynthesisQMF.no_col,
247             hSbrDec->SynthesisQMF.lsb,
248             hSbrDec->SynthesisQMF.usb,
249             hSbrDec->SynthesisQMF.no_channels,
250             synQmfFlags | QMF_FLAG_KEEP_STATES
251             );
252 
253     if (qmfErr != 0) {
254       FDK_ASSERT(0);
255     }
256   }
257 }
258 
259 
260 /*!
261   \brief      SBR decoder core function for one channel
262 
263   \image html  BufferMgmtDetailed-1632.png
264 
265   Besides the filter states of the QMF filter bank and the LPC-states of
266   the LPP-Transposer, processing is mainly based on four buffers:
267   #timeIn, #timeOut, #WorkBuffer2 and #OverlapBuffer. The #WorkBuffer2
268   is reused for all channels and might be used by the core decoder, a
269   static overlap buffer is required for each channel. Du to in-place
270   processing, #timeIn and #timeOut point to identical locations.
271 
272   The spectral data is organized in so-called slots, each slot
273   containing 64 bands of complex data. The number of slots per frame is
274   dependend on the frame size. For mp3PRO, there are 18 slots per frame
275   and 6 slots per #OverlapBuffer. It is not necessary to have the slots
276   in located consecutive address ranges.
277 
278   To optimize memory usage and to minimize the number of memory
279   accesses, the memory management is organized as follows (Slot numbers
280   based on mp3PRO):
281 
282   1.) Input time domain signal is located in #timeIn, the last slots
283   (0..5) of the spectral data of the previous frame are located in the
284   #OverlapBuffer. In addition, #frameData of the current frame resides
285   in the upper part of #timeIn.
286 
287   2.) During the cplxAnalysisQmfFiltering(), 32 samples from #timeIn are transformed
288   into a slot of up to 32 complex spectral low band values at a
289   time. The first spectral slot -- nr. 6 -- is written at slot number
290   zero of #WorkBuffer2. #WorkBuffer2 will be completely filled with
291   spectral data.
292 
293   3.) LPP-Transposition in lppTransposer() is processed on 24 slots. During the
294   transposition, the high band part of the spectral data is replicated
295   based on the low band data.
296 
297   Envelope Adjustment is processed on the high band part of the spectral
298   data only by calculateSbrEnvelope().
299 
300   4.) The cplxSynthesisQmfFiltering() creates 64 time domain samples out
301   of a slot of 64 complex spectral values at a time. The first 6 slots
302   in #timeOut are filled from the results of spectral slots 0..5 in the
303   #OverlapBuffer. The consecutive slots in timeOut are now filled with
304   the results of spectral slots 6..17.
305 
306   5.) The preprocessed slots 18..23 have to be stored in the
307   #OverlapBuffer.
308 
309 */
310 
311 void
sbr_dec(HANDLE_SBR_DEC hSbrDec,INT_PCM * timeIn,INT_PCM * timeOut,HANDLE_SBR_DEC hSbrDecRight,INT_PCM * timeOutRight,const int strideIn,const int strideOut,HANDLE_SBR_HEADER_DATA hHeaderData,HANDLE_SBR_FRAME_DATA hFrameData,HANDLE_SBR_PREV_FRAME_DATA hPrevFrameData,const int applyProcessing,HANDLE_PS_DEC h_ps_d,const UINT flags)312 sbr_dec ( HANDLE_SBR_DEC hSbrDec,            /*!< handle to Decoder channel */
313           INT_PCM *timeIn,                   /*!< pointer to input time signal */
314           INT_PCM *timeOut,                  /*!< pointer to output time signal */
315           HANDLE_SBR_DEC hSbrDecRight,       /*!< handle to Decoder channel right */
316           INT_PCM *timeOutRight,             /*!< pointer to output time signal */
317           const int strideIn,                /*!< Time data traversal strideIn */
318           const int strideOut,               /*!< Time data traversal strideOut */
319           HANDLE_SBR_HEADER_DATA hHeaderData,/*!< Static control data */
320           HANDLE_SBR_FRAME_DATA hFrameData,  /*!< Control data of current frame */
321           HANDLE_SBR_PREV_FRAME_DATA hPrevFrameData,  /*!< Some control data of last frame */
322           const int applyProcessing,         /*!< Flag for SBR operation */
323           HANDLE_PS_DEC h_ps_d,
324           const UINT flags
325          )
326 {
327   int i, slot, reserve;
328   int saveLbScale;
329   int ov_len;
330   int lastSlotOffs;
331   FIXP_DBL maxVal;
332 
333   /* 1+1/3 frames of spectral data: */
334   FIXP_DBL **QmfBufferReal = hSbrDec->QmfBufferReal;
335   FIXP_DBL **QmfBufferImag = hSbrDec->QmfBufferImag;
336 
337  /* Number of QMF timeslots in the overlap buffer: */
338  ov_len = hSbrDec->LppTrans.pSettings->overlap;
339 
340  /* Number of QMF slots per frame */
341   int noCols = hHeaderData->numberTimeSlots * hHeaderData->timeStep;
342 
343  /* assign qmf time slots */
344   if ( ((flags & SBRDEC_LOW_POWER ) ? 1 : 0) != ((hSbrDec->SynthesisQMF.flags & QMF_FLAG_LP) ? 1 : 0) ) {
345     assignTimeSlots( hSbrDec, hHeaderData->numberTimeSlots * hHeaderData->timeStep, flags & SBRDEC_LOW_POWER);
346   }
347 
348   if (flags & SBRDEC_ELD_GRID) {
349     /* Choose the right low delay filter bank */
350     changeQmfType( hSbrDec, (flags & SBRDEC_LD_MPS_QMF) ? 1 : 0 );
351   }
352 
353   /*
354     low band codec signal subband filtering
355    */
356 
357   {
358     C_AALLOC_SCRATCH_START(qmfTemp, FIXP_DBL, 2*(64));
359 
360     qmfAnalysisFiltering( &hSbrDec->AnalysiscQMF,
361                            QmfBufferReal + ov_len,
362                            QmfBufferImag + ov_len,
363                           &hSbrDec->sbrScaleFactor,
364                            timeIn,
365                            strideIn,
366                            qmfTemp
367                          );
368 
369     C_AALLOC_SCRATCH_END(qmfTemp, FIXP_DBL, 2*(64));
370   }
371 
372   /*
373     Clear upper half of spectrum
374   */
375   {
376     int nAnalysisBands = hHeaderData->numberOfAnalysisBands;
377 
378     if (! (flags & SBRDEC_LOW_POWER)) {
379       for (slot = ov_len; slot < noCols+ov_len; slot++) {
380         FDKmemclear(&QmfBufferReal[slot][nAnalysisBands],((64)-nAnalysisBands)*sizeof(FIXP_DBL));
381         FDKmemclear(&QmfBufferImag[slot][nAnalysisBands],((64)-nAnalysisBands)*sizeof(FIXP_DBL));
382       }
383     } else
384     for (slot = ov_len; slot < noCols+ov_len; slot++) {
385       FDKmemclear(&QmfBufferReal[slot][nAnalysisBands],((64)-nAnalysisBands)*sizeof(FIXP_DBL));
386     }
387   }
388 
389 
390 
391   /*
392     Shift spectral data left to gain accuracy in transposer and adjustor
393   */
394   maxVal = maxSubbandSample( QmfBufferReal,
395                             (flags & SBRDEC_LOW_POWER) ? NULL : QmfBufferImag,
396                              0,
397                              hSbrDec->AnalysiscQMF.lsb,
398                              ov_len,
399                              noCols+ov_len );
400 
401   reserve = fixMax(0,CntLeadingZeros(maxVal)-1) ;
402   reserve = fixMin(reserve,DFRACT_BITS-1-hSbrDec->sbrScaleFactor.lb_scale);
403 
404   /* If all data is zero, lb_scale could become too large */
405   rescaleSubbandSamples( QmfBufferReal,
406                          (flags & SBRDEC_LOW_POWER) ? NULL : QmfBufferImag,
407                          0,
408                          hSbrDec->AnalysiscQMF.lsb,
409                          ov_len,
410                          noCols+ov_len,
411                          reserve);
412 
413   hSbrDec->sbrScaleFactor.lb_scale += reserve;
414 
415   /*
416     save low band scale, wavecoding or parametric stereo may modify it
417   */
418   saveLbScale = hSbrDec->sbrScaleFactor.lb_scale;
419 
420 
421   if (applyProcessing)
422   {
423     UCHAR * borders = hFrameData->frameInfo.borders;
424     lastSlotOffs =  borders[hFrameData->frameInfo.nEnvelopes] - hHeaderData->numberTimeSlots;
425 
426     FIXP_DBL degreeAlias[(64)];
427 
428     /* The transposer will override most values in degreeAlias[].
429        The array needs to be cleared at least from lowSubband to highSubband before. */
430     if (flags & SBRDEC_LOW_POWER)
431       FDKmemclear(&degreeAlias[hHeaderData->freqBandData.lowSubband], (hHeaderData->freqBandData.highSubband-hHeaderData->freqBandData.lowSubband)*sizeof(FIXP_DBL));
432 
433     /*
434       Inverse filtering of lowband and transposition into the SBR-frequency range
435     */
436 
437     lppTransposer ( &hSbrDec->LppTrans,
438                     &hSbrDec->sbrScaleFactor,
439                     QmfBufferReal,
440                     degreeAlias,                  // only used if useLP = 1
441                     QmfBufferImag,
442                     flags & SBRDEC_LOW_POWER,
443                     hHeaderData->timeStep,
444                     borders[0],
445                     lastSlotOffs,
446                     hHeaderData->freqBandData.nInvfBands,
447                     hFrameData->sbr_invf_mode,
448                     hPrevFrameData->sbr_invf_mode );
449 
450 
451 
452 
453 
454     /*
455       Adjust envelope of current frame.
456     */
457 
458     calculateSbrEnvelope (&hSbrDec->sbrScaleFactor,
459                           &hSbrDec->SbrCalculateEnvelope,
460                           hHeaderData,
461                           hFrameData,
462                           QmfBufferReal,
463                           QmfBufferImag,
464                           flags & SBRDEC_LOW_POWER,
465 
466                           degreeAlias,
467                           flags,
468                           (hHeaderData->frameErrorFlag || hPrevFrameData->frameErrorFlag));
469 
470 
471     /*
472       Update hPrevFrameData (to be used in the next frame)
473     */
474     for (i=0; i<hHeaderData->freqBandData.nInvfBands; i++) {
475       hPrevFrameData->sbr_invf_mode[i] = hFrameData->sbr_invf_mode[i];
476     }
477     hPrevFrameData->coupling = hFrameData->coupling;
478     hPrevFrameData->stopPos = borders[hFrameData->frameInfo.nEnvelopes];
479     hPrevFrameData->ampRes = hFrameData->ampResolutionCurrentFrame;
480   }
481   else {
482     /* Reset hb_scale if no highband is present, because hb_scale is considered in the QMF-synthesis */
483     hSbrDec->sbrScaleFactor.hb_scale = saveLbScale;
484   }
485 
486 
487   for (i=0; i<LPC_ORDER; i++){
488     /*
489       Store the unmodified qmf Slots values (required for LPC filtering)
490     */
491     if (! (flags & SBRDEC_LOW_POWER)) {
492       FDKmemcpy(hSbrDec->LppTrans.lpcFilterStatesReal[i], QmfBufferReal[noCols-LPC_ORDER+i], hSbrDec->AnalysiscQMF.lsb*sizeof(FIXP_DBL));
493       FDKmemcpy(hSbrDec->LppTrans.lpcFilterStatesImag[i], QmfBufferImag[noCols-LPC_ORDER+i], hSbrDec->AnalysiscQMF.lsb*sizeof(FIXP_DBL));
494     } else
495     FDKmemcpy(hSbrDec->LppTrans.lpcFilterStatesReal[i], QmfBufferReal[noCols-LPC_ORDER+i], hSbrDec->AnalysiscQMF.lsb*sizeof(FIXP_DBL));
496   }
497 
498   /*
499     Synthesis subband filtering.
500   */
501 
502   if ( ! (flags & SBRDEC_PS_DECODED) ) {
503 
504     {
505       int outScalefactor = 0;
506 
507       if (h_ps_d != NULL) {
508         h_ps_d->procFrameBased = 1;  /* we here do frame based processing */
509       }
510 
511 
512       sbrDecoder_drcApply(&hSbrDec->sbrDrcChannel,
513                            QmfBufferReal,
514                            (flags & SBRDEC_LOW_POWER) ? NULL : QmfBufferImag,
515                            hSbrDec->SynthesisQMF.no_col,
516                           &outScalefactor
517                           );
518 
519 
520 
521       qmfChangeOutScalefactor(&hSbrDec->SynthesisQMF, outScalefactor );
522 
523       {
524         C_AALLOC_SCRATCH_START(qmfTemp, FIXP_DBL, 2*(64));
525 
526         qmfSynthesisFiltering( &hSbrDec->SynthesisQMF,
527                                 QmfBufferReal,
528                                 (flags & SBRDEC_LOW_POWER) ? NULL : QmfBufferImag,
529                                &hSbrDec->sbrScaleFactor,
530                                 hSbrDec->LppTrans.pSettings->overlap,
531                                 timeOut,
532                                 strideOut,
533                                 qmfTemp);
534 
535         C_AALLOC_SCRATCH_END(qmfTemp, FIXP_DBL, 2*(64));
536       }
537 
538     }
539 
540   } else { /* (flags & SBRDEC_PS_DECODED) */
541     INT i, sdiff, outScalefactor, scaleFactorLowBand, scaleFactorHighBand;
542     SCHAR scaleFactorLowBand_ov, scaleFactorLowBand_no_ov;
543 
544     HANDLE_QMF_FILTER_BANK synQmf      = &hSbrDec->SynthesisQMF;
545     HANDLE_QMF_FILTER_BANK synQmfRight = &hSbrDecRight->SynthesisQMF;
546 
547     /* adapt scaling */
548     sdiff = hSbrDec->sbrScaleFactor.lb_scale - reserve;                  /* Scaling difference         */
549     scaleFactorHighBand   = sdiff - hSbrDec->sbrScaleFactor.hb_scale;    /* Scale of current high band */
550     scaleFactorLowBand_ov = sdiff - hSbrDec->sbrScaleFactor.ov_lb_scale; /* Scale of low band overlapping QMF data */
551     scaleFactorLowBand_no_ov = sdiff - hSbrDec->sbrScaleFactor.lb_scale; /* Scale of low band current QMF data     */
552     outScalefactor  = 0;                                                 /* Initial output scale */
553 
554     if (h_ps_d->procFrameBased == 1)    /* If we have switched from frame to slot based processing copy filter states */
555     { /* procFrameBased will be unset later */
556       /* copy filter states from left to right */
557       FDKmemcpy(synQmfRight->FilterStates, synQmf->FilterStates, ((640)-(64))*sizeof(FIXP_QSS));
558     }
559 
560     /* scale ALL qmf vales ( real and imag ) of mono / left channel to the
561        same scale factor ( ov_lb_sf, lb_sf and hq_sf )                      */
562     scalFilterBankValues( h_ps_d,                             /* parametric stereo decoder handle     */
563                           QmfBufferReal,                      /* qmf filterbank values                */
564                           QmfBufferImag,                      /* qmf filterbank values                */
565                           synQmf->lsb,                        /* sbr start subband                    */
566                           hSbrDec->sbrScaleFactor.ov_lb_scale,
567                           hSbrDec->sbrScaleFactor.lb_scale,
568                          &scaleFactorLowBand_ov,              /* adapt scaling values */
569                          &scaleFactorLowBand_no_ov,           /* adapt scaling values */
570                           hSbrDec->sbrScaleFactor.hb_scale,   /* current frame ( highband ) */
571                          &scaleFactorHighBand,
572                           synQmf->no_col);
573 
574     /* use the same synthese qmf values for left and right channel */
575     synQmfRight->no_col = synQmf->no_col;
576     synQmfRight->lsb    = synQmf->lsb;
577     synQmfRight->usb    = synQmf->usb;
578 
579     int env=0;
580 
581       outScalefactor += (SCAL_HEADROOM+1); /* psDiffScale! */
582 
583     {
584       C_AALLOC_SCRATCH_START(pWorkBuffer, FIXP_DBL, 2*(64));
585 
586       int maxShift = 0;
587 
588       if (hSbrDec->sbrDrcChannel.enable != 0) {
589         if (hSbrDec->sbrDrcChannel.prevFact_exp > maxShift) {
590           maxShift = hSbrDec->sbrDrcChannel.prevFact_exp;
591         }
592         if (hSbrDec->sbrDrcChannel.currFact_exp > maxShift) {
593           maxShift = hSbrDec->sbrDrcChannel.currFact_exp;
594         }
595         if (hSbrDec->sbrDrcChannel.nextFact_exp > maxShift) {
596           maxShift = hSbrDec->sbrDrcChannel.nextFact_exp;
597         }
598       }
599 
600       /* copy DRC data to right channel (with PS both channels use the same DRC gains) */
601       FDKmemcpy(&hSbrDecRight->sbrDrcChannel, &hSbrDec->sbrDrcChannel, sizeof(SBRDEC_DRC_CHANNEL));
602 
603       for (i = 0; i < synQmf->no_col; i++) {  /* ----- no_col loop ----- */
604 
605         INT outScalefactorR, outScalefactorL;
606         outScalefactorR = outScalefactorL = outScalefactor;
607 
608         /* qmf timeslot of right channel */
609         FIXP_DBL* rQmfReal = pWorkBuffer;
610         FIXP_DBL* rQmfImag = pWorkBuffer + 64;
611 
612 
613         {
614           if ( i == h_ps_d->bsData[h_ps_d->processSlot].mpeg.aEnvStartStop[env] ) {
615             initSlotBasedRotation( h_ps_d, env, hHeaderData->freqBandData.highSubband );
616             env++;
617           }
618 
619           ApplyPsSlot( h_ps_d,                   /* parametric stereo decoder handle  */
620                       (QmfBufferReal + i),       /* one timeslot of left/mono channel */
621                       (QmfBufferImag + i),       /* one timeslot of left/mono channel */
622                        rQmfReal,                 /* one timeslot or right channel     */
623                        rQmfImag);                /* one timeslot or right channel     */
624         }
625 
626 
627         scaleFactorLowBand = (i<(6)) ? scaleFactorLowBand_ov : scaleFactorLowBand_no_ov;
628 
629 
630         sbrDecoder_drcApplySlot ( /* right channel */
631                                  &hSbrDecRight->sbrDrcChannel,
632                                   rQmfReal,
633                                   rQmfImag,
634                                   i,
635                                   synQmfRight->no_col,
636                                   maxShift
637                                 );
638 
639         outScalefactorR += maxShift;
640 
641         sbrDecoder_drcApplySlot ( /* left channel */
642                                  &hSbrDec->sbrDrcChannel,
643                                  *(QmfBufferReal + i),
644                                  *(QmfBufferImag + i),
645                                   i,
646                                   synQmf->no_col,
647                                   maxShift
648                                 );
649 
650         outScalefactorL += maxShift;
651 
652 
653         /* scale filter states for left and right channel */
654         qmfChangeOutScalefactor( synQmf, outScalefactorL );
655         qmfChangeOutScalefactor( synQmfRight, outScalefactorR );
656 
657         {
658 
659           qmfSynthesisFilteringSlot( synQmfRight,
660                                      rQmfReal,                /* QMF real buffer */
661                                      rQmfImag,                /* QMF imag buffer */
662                                      scaleFactorLowBand,
663                                      scaleFactorHighBand,
664                                      timeOutRight+(i*synQmf->no_channels*strideOut),
665                                      strideOut,
666                                      pWorkBuffer);
667 
668           qmfSynthesisFilteringSlot( synQmf,
669                                    *(QmfBufferReal + i),      /* QMF real buffer */
670                                    *(QmfBufferImag + i),      /* QMF imag buffer */
671                                      scaleFactorLowBand,
672                                      scaleFactorHighBand,
673                                      timeOut+(i*synQmf->no_channels*strideOut),
674                                      strideOut,
675                                      pWorkBuffer);
676 
677         }
678       } /* no_col loop  i  */
679 
680       /* scale back (6) timeslots look ahead for hybrid filterbank to original value */
681       rescalFilterBankValues( h_ps_d,
682                               QmfBufferReal,
683                               QmfBufferImag,
684                               synQmf->lsb,
685                               synQmf->no_col );
686 
687       C_AALLOC_SCRATCH_END(pWorkBuffer, FIXP_DBL, 2*(64));
688     }
689   }
690 
691   sbrDecoder_drcUpdateChannel( &hSbrDec->sbrDrcChannel );
692 
693 
694   /*
695     Update overlap buffer
696     Even bands above usb are copied to avoid outdated spectral data in case
697     the stop frequency raises.
698   */
699 
700   if (hSbrDec->LppTrans.pSettings->overlap > 0)
701   {
702     if (! (flags & SBRDEC_LOW_POWER)) {
703       for ( i=0; i<hSbrDec->LppTrans.pSettings->overlap; i++ ) {
704         FDKmemcpy(QmfBufferReal[i], QmfBufferReal[i+noCols], (64)*sizeof(FIXP_DBL));
705         FDKmemcpy(QmfBufferImag[i], QmfBufferImag[i+noCols], (64)*sizeof(FIXP_DBL));
706       }
707     } else
708       for ( i=0; i<hSbrDec->LppTrans.pSettings->overlap; i++ ) {
709         FDKmemcpy(QmfBufferReal[i], QmfBufferReal[i+noCols], (64)*sizeof(FIXP_DBL));
710       }
711   }
712 
713   hSbrDec->sbrScaleFactor.ov_lb_scale = saveLbScale;
714 
715   /* Save current frame status */
716   hPrevFrameData->frameErrorFlag = hHeaderData->frameErrorFlag;
717 
718 } // sbr_dec()
719 
720 
721 /*!
722   \brief     Creates sbr decoder structure
723   \return    errorCode, 0 if successful
724 */
725 SBR_ERROR
createSbrDec(SBR_CHANNEL * hSbrChannel,HANDLE_SBR_HEADER_DATA hHeaderData,TRANSPOSER_SETTINGS * pSettings,const int downsampleFac,const UINT qmfFlags,const UINT flags,const int overlap,int chan)726 createSbrDec (SBR_CHANNEL * hSbrChannel,
727               HANDLE_SBR_HEADER_DATA hHeaderData, /*!< Static control data */
728               TRANSPOSER_SETTINGS *pSettings,
729               const int     downsampleFac,        /*!< Downsampling factor */
730               const UINT    qmfFlags,             /*!< flags -> 1: HQ/LP selector, 2: CLDFB */
731               const UINT    flags,
732               const int     overlap,
733               int           chan)                 /*!< Channel for which to assign buffers etc. */
734 
735 {
736   SBR_ERROR err = SBRDEC_OK;
737   int timeSlots = hHeaderData->numberTimeSlots;   /* Number of SBR slots per frame */
738   int noCols = timeSlots * hHeaderData->timeStep; /* Number of QMF slots per frame */
739   HANDLE_SBR_DEC hs = &(hSbrChannel->SbrDec);
740 
741   /* Initialize scale factors */
742   hs->sbrScaleFactor.ov_lb_scale  = 0;
743   hs->sbrScaleFactor.ov_hb_scale  = 0;
744   hs->sbrScaleFactor.hb_scale     = 0;
745 
746 
747   /*
748     create envelope calculator
749   */
750   err = createSbrEnvelopeCalc (&hs->SbrCalculateEnvelope,
751                                hHeaderData,
752                                chan,
753                                flags);
754   if (err != SBRDEC_OK) {
755     return err;
756   }
757 
758   /*
759     create QMF filter banks
760   */
761   {
762     int qmfErr;
763 
764     qmfErr = qmfInitAnalysisFilterBank (
765                     &hs->AnalysiscQMF,
766                      hs->anaQmfStates,
767                      noCols,
768                      hHeaderData->freqBandData.lowSubband,
769                      hHeaderData->freqBandData.highSubband,
770                      hHeaderData->numberOfAnalysisBands,
771                      qmfFlags & (~QMF_FLAG_KEEP_STATES)
772                      );
773     if (qmfErr != 0) {
774       return SBRDEC_UNSUPPORTED_CONFIG;
775     }
776   }
777   if (hs->pSynQmfStates == NULL) {
778     hs->pSynQmfStates = GetRam_sbr_QmfStatesSynthesis(chan);
779     if (hs->pSynQmfStates == NULL)
780       return SBRDEC_MEM_ALLOC_FAILED;
781   }
782 
783   {
784     int qmfErr;
785 
786     qmfErr = qmfInitSynthesisFilterBank (
787            &hs->SynthesisQMF,
788             hs->pSynQmfStates,
789             noCols,
790             hHeaderData->freqBandData.lowSubband,
791             hHeaderData->freqBandData.highSubband,
792             (64) / downsampleFac,
793             qmfFlags & (~QMF_FLAG_KEEP_STATES)
794             );
795 
796     if (qmfErr != 0) {
797       return SBRDEC_UNSUPPORTED_CONFIG;
798     }
799   }
800   initSbrPrevFrameData (&hSbrChannel->prevFrameData, timeSlots);
801 
802   /*
803     create transposer
804   */
805   err = createLppTransposer (&hs->LppTrans,
806                              pSettings,
807                              hHeaderData->freqBandData.lowSubband,
808                              hHeaderData->freqBandData.v_k_master,
809                              hHeaderData->freqBandData.numMaster,
810                              hs->SynthesisQMF.usb,
811                              timeSlots,
812                              hs->AnalysiscQMF.no_col,
813                              hHeaderData->freqBandData.freqBandTableNoise,
814                              hHeaderData->freqBandData.nNfb,
815                              hHeaderData->sbrProcSmplRate,
816                              chan,
817                              overlap );
818   if (err != SBRDEC_OK) {
819     return err;
820   }
821 
822   /* The CLDFB does not have overlap */
823   if ((qmfFlags & QMF_FLAG_CLDFB) == 0) {
824     if (hs->pSbrOverlapBuffer == NULL) {
825       hs->pSbrOverlapBuffer = GetRam_sbr_OverlapBuffer(chan);
826       if (hs->pSbrOverlapBuffer == NULL)  {
827         return SBRDEC_MEM_ALLOC_FAILED;
828       }
829     } else {
830       /* Clear overlap buffer */
831       FDKmemclear( hs->pSbrOverlapBuffer,
832                    sizeof(FIXP_DBL) * 2 * (6) * (64)
833                  );
834     }
835   }
836 
837   /* assign qmf time slots */
838   assignTimeSlots( &hSbrChannel->SbrDec, hHeaderData->numberTimeSlots * hHeaderData->timeStep, qmfFlags & QMF_FLAG_LP);
839 
840   return err;
841 }
842 
843 /*!
844   \brief     Delete sbr decoder structure
845   \return    errorCode, 0 if successful
846 */
847 int
deleteSbrDec(SBR_CHANNEL * hSbrChannel)848 deleteSbrDec (SBR_CHANNEL * hSbrChannel)
849 {
850   HANDLE_SBR_DEC hs = &hSbrChannel->SbrDec;
851 
852   deleteSbrEnvelopeCalc (&hs->SbrCalculateEnvelope);
853 
854   /* delete QMF filter states */
855   if (hs->pSynQmfStates != NULL) {
856     FreeRam_sbr_QmfStatesSynthesis(&hs->pSynQmfStates);
857   }
858 
859 
860   if (hs->pSbrOverlapBuffer != NULL) {
861     FreeRam_sbr_OverlapBuffer(&hs->pSbrOverlapBuffer);
862   }
863 
864   return 0;
865 }
866 
867 
868 /*!
869   \brief     resets sbr decoder structure
870   \return    errorCode, 0 if successful
871 */
872 SBR_ERROR
resetSbrDec(HANDLE_SBR_DEC hSbrDec,HANDLE_SBR_HEADER_DATA hHeaderData,HANDLE_SBR_PREV_FRAME_DATA hPrevFrameData,const int useLP,const int downsampleFac)873 resetSbrDec (HANDLE_SBR_DEC hSbrDec,
874              HANDLE_SBR_HEADER_DATA hHeaderData,
875              HANDLE_SBR_PREV_FRAME_DATA hPrevFrameData,
876              const int useLP,
877              const int downsampleFac
878              )
879 {
880   SBR_ERROR sbrError = SBRDEC_OK;
881 
882   int old_lsb = hSbrDec->SynthesisQMF.lsb;
883   int new_lsb = hHeaderData->freqBandData.lowSubband;
884   int l, startBand, stopBand, startSlot, size;
885 
886   int source_scale, target_scale, delta_scale, target_lsb, target_usb, reserve;
887   FIXP_DBL maxVal;
888 
889   /* overlapBuffer point to first (6) slots */
890   FIXP_DBL  **OverlapBufferReal = hSbrDec->QmfBufferReal;
891   FIXP_DBL  **OverlapBufferImag = hSbrDec->QmfBufferImag;
892 
893   /* assign qmf time slots */
894   assignTimeSlots( hSbrDec, hHeaderData->numberTimeSlots * hHeaderData->timeStep, useLP);
895 
896 
897 
898   resetSbrEnvelopeCalc (&hSbrDec->SbrCalculateEnvelope);
899 
900   hSbrDec->SynthesisQMF.lsb = hHeaderData->freqBandData.lowSubband;
901   hSbrDec->SynthesisQMF.usb = fixMin((INT)hSbrDec->SynthesisQMF.no_channels, (INT)hHeaderData->freqBandData.highSubband);
902 
903   hSbrDec->AnalysiscQMF.lsb = hSbrDec->SynthesisQMF.lsb;
904   hSbrDec->AnalysiscQMF.usb = hSbrDec->SynthesisQMF.usb;
905 
906 
907   /*
908     The following initialization of spectral data in the overlap buffer
909     is required for dynamic x-over or a change of the start-freq for 2 reasons:
910 
911     1. If the lowband gets _wider_, unadjusted data would remain
912 
913     2. If the lowband becomes _smaller_, the highest bands of the old lowband
914        must be cleared because the whitening would be affected
915   */
916   startBand = old_lsb;
917   stopBand  = new_lsb;
918   startSlot = hHeaderData->timeStep * (hPrevFrameData->stopPos - hHeaderData->numberTimeSlots);
919   size      = fixMax(0,stopBand-startBand);
920 
921   /* keep already adjusted data in the x-over-area */
922   if (!useLP) {
923     for (l=startSlot; l<hSbrDec->LppTrans.pSettings->overlap; l++) {
924       FDKmemclear(&OverlapBufferReal[l][startBand], size*sizeof(FIXP_DBL));
925       FDKmemclear(&OverlapBufferImag[l][startBand], size*sizeof(FIXP_DBL));
926     }
927   } else
928   for (l=startSlot; l<hSbrDec->LppTrans.pSettings->overlap ; l++) {
929     FDKmemclear(&OverlapBufferReal[l][startBand], size*sizeof(FIXP_DBL));
930   }
931 
932 
933   /*
934     reset LPC filter states
935   */
936   startBand = fixMin(old_lsb,new_lsb);
937   stopBand  = fixMax(old_lsb,new_lsb);
938   size      = fixMax(0,stopBand-startBand);
939 
940   FDKmemclear(&hSbrDec->LppTrans.lpcFilterStatesReal[0][startBand], size*sizeof(FIXP_DBL));
941   FDKmemclear(&hSbrDec->LppTrans.lpcFilterStatesReal[1][startBand], size*sizeof(FIXP_DBL));
942   if (!useLP) {
943     FDKmemclear(&hSbrDec->LppTrans.lpcFilterStatesImag[0][startBand], size*sizeof(FIXP_DBL));
944     FDKmemclear(&hSbrDec->LppTrans.lpcFilterStatesImag[1][startBand], size*sizeof(FIXP_DBL));
945   }
946 
947 
948   /*
949     Rescale already processed spectral data between old and new x-over frequency.
950     This must be done because of the separate scalefactors for lowband and highband.
951   */
952   startBand = fixMin(old_lsb,new_lsb);
953   stopBand =  fixMax(old_lsb,new_lsb);
954 
955   if (new_lsb > old_lsb) {
956     /* The x-over-area was part of the highband before and will now belong to the lowband */
957     source_scale = hSbrDec->sbrScaleFactor.ov_hb_scale;
958     target_scale = hSbrDec->sbrScaleFactor.ov_lb_scale;
959     target_lsb   = 0;
960     target_usb   = old_lsb;
961   }
962   else {
963     /* The x-over-area was part of the lowband before and will now belong to the highband */
964     source_scale = hSbrDec->sbrScaleFactor.ov_lb_scale;
965     target_scale = hSbrDec->sbrScaleFactor.ov_hb_scale;
966     /* jdr: The values old_lsb and old_usb might be wrong because the previous frame might have been "upsamling". */
967     target_lsb   = hSbrDec->SynthesisQMF.lsb;
968     target_usb   = hSbrDec->SynthesisQMF.usb;
969   }
970 
971   /* Shift left all samples of the x-over-area as much as possible
972      An unnecessary coarse scale could cause ov_lb_scale or ov_hb_scale to be
973      adapted and the accuracy in the next frame would seriously suffer! */
974 
975   maxVal = maxSubbandSample( OverlapBufferReal,
976                              (useLP) ? NULL : OverlapBufferImag,
977                              startBand,
978                              stopBand,
979                              0,
980                              startSlot);
981 
982   reserve = CntLeadingZeros(maxVal)-1;
983   reserve = fixMin(reserve,DFRACT_BITS-1-source_scale);
984 
985   rescaleSubbandSamples( OverlapBufferReal,
986                          (useLP) ? NULL : OverlapBufferImag,
987                          startBand,
988                          stopBand,
989                          0,
990                          startSlot,
991                          reserve);
992   source_scale += reserve;
993 
994   delta_scale = target_scale - source_scale;
995 
996   if (delta_scale > 0) { /* x-over-area is dominant */
997     delta_scale = -delta_scale;
998     startBand = target_lsb;
999     stopBand = target_usb;
1000 
1001     if (new_lsb > old_lsb) {
1002       /* The lowband has to be rescaled */
1003       hSbrDec->sbrScaleFactor.ov_lb_scale = source_scale;
1004     }
1005     else {
1006       /* The highband has be be rescaled */
1007       hSbrDec->sbrScaleFactor.ov_hb_scale = source_scale;
1008     }
1009   }
1010 
1011   FDK_ASSERT(startBand <= stopBand);
1012 
1013   if (!useLP) {
1014     for (l=0; l<startSlot; l++) {
1015       scaleValues( OverlapBufferReal[l] + startBand, stopBand-startBand, delta_scale );
1016       scaleValues( OverlapBufferImag[l] + startBand, stopBand-startBand, delta_scale );
1017     }
1018   } else
1019   for (l=0; l<startSlot; l++) {
1020     scaleValues( OverlapBufferReal[l] + startBand, stopBand-startBand, delta_scale );
1021   }
1022 
1023 
1024   /*
1025     Initialize transposer and limiter
1026   */
1027   sbrError = resetLppTransposer (&hSbrDec->LppTrans,
1028                                  hHeaderData->freqBandData.lowSubband,
1029                                  hHeaderData->freqBandData.v_k_master,
1030                                  hHeaderData->freqBandData.numMaster,
1031                                  hHeaderData->freqBandData.freqBandTableNoise,
1032                                  hHeaderData->freqBandData.nNfb,
1033                                  hHeaderData->freqBandData.highSubband,
1034                                  hHeaderData->sbrProcSmplRate);
1035   if (sbrError != SBRDEC_OK)
1036     return sbrError;
1037 
1038   sbrError = ResetLimiterBands ( hHeaderData->freqBandData.limiterBandTable,
1039                                  &hHeaderData->freqBandData.noLimiterBands,
1040                                  hHeaderData->freqBandData.freqBandTable[0],
1041                                  hHeaderData->freqBandData.nSfb[0],
1042                                  hSbrDec->LppTrans.pSettings->patchParam,
1043                                  hSbrDec->LppTrans.pSettings->noOfPatches,
1044                                  hHeaderData->bs_data.limiterBands);
1045 
1046 
1047   return sbrError;
1048 }
1049