• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* -----------------------------------------------------------------------------
2 Software License for The Fraunhofer FDK AAC Codec Library for Android
3 
4 © Copyright  1995 - 2018 Fraunhofer-Gesellschaft zur Förderung der angewandten
5 Forschung e.V. All rights reserved.
6 
7  1.    INTRODUCTION
8 The Fraunhofer FDK AAC Codec Library for Android ("FDK AAC Codec") is software
9 that implements the MPEG Advanced Audio Coding ("AAC") encoding and decoding
10 scheme for digital audio. This FDK AAC Codec software is intended to be used on
11 a wide variety of Android devices.
12 
13 AAC's HE-AAC and HE-AAC v2 versions are regarded as today's most efficient
14 general perceptual audio codecs. AAC-ELD is considered the best-performing
15 full-bandwidth communications codec by independent studies and is widely
16 deployed. AAC has been standardized by ISO and IEC as part of the MPEG
17 specifications.
18 
19 Patent licenses for necessary patent claims for the FDK AAC Codec (including
20 those of Fraunhofer) may be obtained through Via Licensing
21 (www.vialicensing.com) or through the respective patent owners individually for
22 the purpose of encoding or decoding bit streams in products that are compliant
23 with the ISO/IEC MPEG audio standards. Please note that most manufacturers of
24 Android devices already license these patent claims through Via Licensing or
25 directly from the patent owners, and therefore FDK AAC Codec software may
26 already be covered under those patent licenses when it is used for those
27 licensed purposes only.
28 
29 Commercially-licensed AAC software libraries, including floating-point versions
30 with enhanced sound quality, are also available from Fraunhofer. Users are
31 encouraged to check the Fraunhofer website for additional applications
32 information and documentation.
33 
34 2.    COPYRIGHT LICENSE
35 
36 Redistribution and use in source and binary forms, with or without modification,
37 are permitted without payment of copyright license fees provided that you
38 satisfy the following conditions:
39 
40 You must retain the complete text of this software license in redistributions of
41 the FDK AAC Codec or your modifications thereto in source code form.
42 
43 You must retain the complete text of this software license in the documentation
44 and/or other materials provided with redistributions of the FDK AAC Codec or
45 your modifications thereto in binary form. You must make available free of
46 charge copies of the complete source code of the FDK AAC Codec and your
47 modifications thereto to recipients of copies in binary form.
48 
49 The name of Fraunhofer may not be used to endorse or promote products derived
50 from this library without prior written permission.
51 
52 You may not charge copyright license fees for anyone to use, copy or distribute
53 the FDK AAC Codec software or your modifications thereto.
54 
55 Your modified versions of the FDK AAC Codec must carry prominent notices stating
56 that you changed the software and the date of any change. For modified versions
57 of the FDK AAC Codec, the term "Fraunhofer FDK AAC Codec Library for Android"
58 must be replaced by the term "Third-Party Modified Version of the Fraunhofer FDK
59 AAC Codec Library for Android."
60 
61 3.    NO PATENT LICENSE
62 
63 NO EXPRESS OR IMPLIED LICENSES TO ANY PATENT CLAIMS, including without
64 limitation the patents of Fraunhofer, ARE GRANTED BY THIS SOFTWARE LICENSE.
65 Fraunhofer provides no warranty of patent non-infringement with respect to this
66 software.
67 
68 You may use this FDK AAC Codec software or modifications thereto only for
69 purposes that are authorized by appropriate patent licenses.
70 
71 4.    DISCLAIMER
72 
73 This FDK AAC Codec software is provided by Fraunhofer on behalf of the copyright
74 holders and contributors "AS IS" and WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES,
75 including but not limited to the implied warranties of merchantability and
76 fitness for a particular purpose. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
77 CONTRIBUTORS BE LIABLE for any direct, indirect, incidental, special, exemplary,
78 or consequential damages, including but not limited to procurement of substitute
79 goods or services; loss of use, data, or profits, or business interruption,
80 however caused and on any theory of liability, whether in contract, strict
81 liability, or tort (including negligence), arising in any way out of the use of
82 this software, even if advised of the possibility of such damage.
83 
84 5.    CONTACT INFORMATION
85 
86 Fraunhofer Institute for Integrated Circuits IIS
87 Attention: Audio and Multimedia Departments - FDK AAC LL
88 Am Wolfsmantel 33
89 91058 Erlangen, Germany
90 
91 www.iis.fraunhofer.de/amm
92 amm-info@iis.fraunhofer.de
93 ----------------------------------------------------------------------------- */
94 
95 /**************************** SBR decoder library ******************************
96 
97    Author(s):
98 
99    Description:
100 
101 *******************************************************************************/
102 
103 /*!
104   \file
105   \brief  Envelope extraction
106   The functions provided by this module are mostly called by applySBR(). After
107   it is determined that there is valid SBR data, sbrGetHeaderData() might be
108   called if the current SBR data contains an \ref SBR_HEADER_ELEMENT as opposed
109   to a \ref SBR_STANDARD_ELEMENT. This function may return various error codes
110   as defined in #SBR_HEADER_STATUS . Most importantly it returns HEADER_RESET
111   when decoder settings need to be recalculated according to the SBR
112   specifications. In that case applySBR() will initiatite the required
113   re-configuration.
114 
115   The header data is stored in a #SBR_HEADER_DATA structure.
116 
117   The actual SBR data for the current frame is decoded into SBR_FRAME_DATA
118   stuctures by sbrGetChannelPairElement() [for stereo streams] and
119   sbrGetSingleChannelElement() [for mono streams]. There is no fractional
120   arithmetic involved.
121 
122   Once the information is extracted, the data needs to be further prepared
123   before the actual decoding process. This is done in decodeSbrData().
124 
125   \sa Description of buffer management in applySBR(). \ref documentationOverview
126 
127   <h1>About the SBR data format:</h1>
128 
129   Each frame includes SBR data (side chain information), and can be either the
130   \ref SBR_HEADER_ELEMENT or the \ref SBR_STANDARD_ELEMENT. Parts of the data
131   can be protected by a CRC checksum.
132 
133   \anchor SBR_HEADER_ELEMENT <h2>The SBR_HEADER_ELEMENT</h2>
134 
135   The SBR_HEADER_ELEMENT can be transmitted with every frame, however, it
136   typically is send every second or so. It contains fundamental information such
137   as SBR sampling frequency and frequency range as well as control signals that
138   do not require frequent changes. It also includes the \ref
139   SBR_STANDARD_ELEMENT.
140 
141   Depending on the changes between the information in a current
142   SBR_HEADER_ELEMENT and the previous SBR_HEADER_ELEMENT, the SBR decoder might
143   need to be reset and reconfigured (e.g. new tables need to be calculated).
144 
145   \anchor SBR_STANDARD_ELEMENT <h2>The SBR_STANDARD_ELEMENT</h2>
146 
147   This data can be subdivided into "side info" and "raw data", where side info
148   is defined as signals needed to decode the raw data and some decoder tuning
149   signals. Raw data is referred to as PCM and Huffman coded envelope and noise
150   floor estimates. The side info also includes information about the
151   time-frequency grid for the current frame.
152 
153   \sa \ref documentationOverview
154 */
155 
156 #include "env_extr.h"
157 
158 #include "sbr_ram.h"
159 #include "sbr_rom.h"
160 #include "huff_dec.h"
161 
162 #include "psbitdec.h"
163 
164 #define DRM_PARAMETRIC_STEREO 0
165 #define EXTENSION_ID_PS_CODING 2
166 
167 static int extractPvcFrameInfo(
168     HANDLE_FDK_BITSTREAM hBs,           /*!< bitbuffer handle */
169     HANDLE_SBR_HEADER_DATA hHeaderData, /*!< Static control data */
170     HANDLE_SBR_FRAME_DATA h_frame_data, /*!< pointer to memory where the
171                                            frame-info will be stored */
172     HANDLE_SBR_PREV_FRAME_DATA h_prev_frame_data, /*!< pointer to memory where
173                                                      the previous frame-info
174                                                      will be stored */
175     UCHAR pvc_mode_last,                          /**< PVC mode of last frame */
176     const UINT flags);
177 static int extractFrameInfo(HANDLE_FDK_BITSTREAM hBs,
178                             HANDLE_SBR_HEADER_DATA hHeaderData,
179                             HANDLE_SBR_FRAME_DATA h_frame_data,
180                             const UINT nrOfChannels, const UINT flags);
181 
182 static int sbrGetPvcEnvelope(HANDLE_SBR_HEADER_DATA hHeaderData,
183                              HANDLE_SBR_FRAME_DATA h_frame_data,
184                              HANDLE_FDK_BITSTREAM hBs, const UINT flags,
185                              const UINT pvcMode);
186 static int sbrGetEnvelope(HANDLE_SBR_HEADER_DATA hHeaderData,
187                           HANDLE_SBR_FRAME_DATA h_frame_data,
188                           HANDLE_FDK_BITSTREAM hBs, const UINT flags);
189 
190 static void sbrGetDirectionControlData(HANDLE_SBR_FRAME_DATA hFrameData,
191                                        HANDLE_FDK_BITSTREAM hBs,
192                                        const UINT flags, const int bs_pvc_mode);
193 
194 static void sbrGetNoiseFloorData(HANDLE_SBR_HEADER_DATA hHeaderData,
195                                  HANDLE_SBR_FRAME_DATA h_frame_data,
196                                  HANDLE_FDK_BITSTREAM hBs);
197 
198 static int checkFrameInfo(FRAME_INFO *pFrameInfo, int numberOfTimeSlots,
199                           int overlap, int timeStep);
200 
201 /* Mapping to std samplerate table according to 14496-3 (4.6.18.2.6) */
202 typedef struct SR_MAPPING {
203   UINT fsRangeLo; /* If fsRangeLo(n+1)>fs>=fsRangeLo(n), it will be mapped to...
204                    */
205   UINT fsMapped;  /* fsMapped. */
206 } SR_MAPPING;
207 
208 static const SR_MAPPING stdSampleRatesMapping[] = {
209     {0, 8000},      {9391, 11025},  {11502, 12000}, {13856, 16000},
210     {18783, 22050}, {23004, 24000}, {27713, 32000}, {37566, 44100},
211     {46009, 48000}, {55426, 64000}, {75132, 88200}, {92017, 96000}};
212 static const SR_MAPPING stdSampleRatesMappingUsac[] = {
213     {0, 16000},     {18783, 22050}, {23004, 24000}, {27713, 32000},
214     {35777, 40000}, {42000, 44100}, {46009, 48000}, {55426, 64000},
215     {75132, 88200}, {92017, 96000}};
216 
sbrdec_mapToStdSampleRate(UINT fs,UINT isUsac)217 UINT sbrdec_mapToStdSampleRate(UINT fs,
218                                UINT isUsac) /*!< Output sampling frequency */
219 {
220   UINT fsMapped = fs, tableSize = 0;
221   const SR_MAPPING *mappingTable;
222   int i;
223 
224   if (!isUsac) {
225     mappingTable = stdSampleRatesMapping;
226     tableSize = sizeof(stdSampleRatesMapping) / sizeof(SR_MAPPING);
227   } else {
228     mappingTable = stdSampleRatesMappingUsac;
229     tableSize = sizeof(stdSampleRatesMappingUsac) / sizeof(SR_MAPPING);
230   }
231 
232   for (i = tableSize - 1; i >= 0; i--) {
233     if (fs >= mappingTable[i].fsRangeLo) {
234       fsMapped = mappingTable[i].fsMapped;
235       break;
236     }
237   }
238 
239   return (fsMapped);
240 }
241 
242 SBR_ERROR
initHeaderData(HANDLE_SBR_HEADER_DATA hHeaderData,const int sampleRateIn,const int sampleRateOut,const INT downscaleFactor,const int samplesPerFrame,const UINT flags,const int setDefaultHdr)243 initHeaderData(HANDLE_SBR_HEADER_DATA hHeaderData, const int sampleRateIn,
244                const int sampleRateOut, const INT downscaleFactor,
245                const int samplesPerFrame, const UINT flags,
246                const int setDefaultHdr) {
247   HANDLE_FREQ_BAND_DATA hFreq = &hHeaderData->freqBandData;
248   SBR_ERROR sbrError = SBRDEC_OK;
249   int numAnalysisBands;
250   int sampleRateProc;
251 
252   if (!(flags & (SBRDEC_SYNTAX_USAC | SBRDEC_SYNTAX_RSVD50))) {
253     sampleRateProc =
254         sbrdec_mapToStdSampleRate(sampleRateOut * downscaleFactor, 0);
255   } else {
256     sampleRateProc = sampleRateOut * downscaleFactor;
257   }
258 
259   if (sampleRateIn == sampleRateOut) {
260     hHeaderData->sbrProcSmplRate = sampleRateProc << 1;
261     numAnalysisBands = 32;
262   } else {
263     hHeaderData->sbrProcSmplRate = sampleRateProc;
264     if ((sampleRateOut >> 1) == sampleRateIn) {
265       /* 1:2 */
266       numAnalysisBands = 32;
267     } else if ((sampleRateOut >> 2) == sampleRateIn) {
268       /* 1:4 */
269       numAnalysisBands = 16;
270     } else if ((sampleRateOut * 3) >> 3 == (sampleRateIn * 8) >> 3) {
271       /* 3:8, 3/4 core frame length */
272       numAnalysisBands = 24;
273     } else {
274       sbrError = SBRDEC_UNSUPPORTED_CONFIG;
275       goto bail;
276     }
277   }
278   numAnalysisBands /= downscaleFactor;
279 
280   if (setDefaultHdr) {
281     /* Fill in default values first */
282     hHeaderData->syncState = SBR_NOT_INITIALIZED;
283     hHeaderData->status = 0;
284     hHeaderData->frameErrorFlag = 0;
285 
286     hHeaderData->bs_info.ampResolution = 1;
287     hHeaderData->bs_info.xover_band = 0;
288     hHeaderData->bs_info.sbr_preprocessing = 0;
289     hHeaderData->bs_info.pvc_mode = 0;
290 
291     hHeaderData->bs_data.startFreq = 5;
292     hHeaderData->bs_data.stopFreq = 0;
293     hHeaderData->bs_data.freqScale =
294         0; /* previously 2; for ELD reduced delay bitstreams
295            /samplerates initializing of the sbr decoder instance fails if
296            freqScale is set to 2 because no master table can be generated; in
297            ELD reduced delay bitstreams this value is always 0; gets overwritten
298            when header is read */
299     hHeaderData->bs_data.alterScale = 1;
300     hHeaderData->bs_data.noise_bands = 2;
301     hHeaderData->bs_data.limiterBands = 2;
302     hHeaderData->bs_data.limiterGains = 2;
303     hHeaderData->bs_data.interpolFreq = 1;
304     hHeaderData->bs_data.smoothingLength = 1;
305 
306     /* Patch some entries */
307     if (sampleRateOut * downscaleFactor >= 96000) {
308       hHeaderData->bs_data.startFreq =
309           4; /*   having read these frequency values from bit stream before. */
310       hHeaderData->bs_data.stopFreq = 3;
311     } else if (sampleRateOut * downscaleFactor >
312                24000) { /* Trigger an error if SBR is going to be processed
313                            without     */
314       hHeaderData->bs_data.startFreq =
315           7; /*   having read these frequency values from bit stream before. */
316       hHeaderData->bs_data.stopFreq = 3;
317     }
318   }
319 
320   if ((sampleRateOut >> 2) == sampleRateIn) {
321     hHeaderData->timeStep = 4;
322   } else {
323     hHeaderData->timeStep = (flags & SBRDEC_ELD_GRID) ? 1 : 2;
324   }
325 
326   /* Setup pointers to frequency band tables */
327   hFreq->freqBandTable[0] = hFreq->freqBandTableLo;
328   hFreq->freqBandTable[1] = hFreq->freqBandTableHi;
329 
330   /* One SBR timeslot corresponds to the amount of samples equal to the amount
331    * of analysis bands, divided by the timestep. */
332   hHeaderData->numberTimeSlots =
333       (samplesPerFrame / numAnalysisBands) >> (hHeaderData->timeStep - 1);
334   if (hHeaderData->numberTimeSlots > (16)) {
335     sbrError = SBRDEC_UNSUPPORTED_CONFIG;
336   }
337 
338   hHeaderData->numberOfAnalysisBands = numAnalysisBands;
339   if ((sampleRateOut >> 2) == sampleRateIn) {
340     hHeaderData->numberTimeSlots <<= 1;
341   }
342 
343 bail:
344   return sbrError;
345 }
346 
347 /*!
348   \brief   Initialize the SBR_PREV_FRAME_DATA struct
349 */
initSbrPrevFrameData(HANDLE_SBR_PREV_FRAME_DATA h_prev_data,int timeSlots)350 void initSbrPrevFrameData(
351     HANDLE_SBR_PREV_FRAME_DATA
352         h_prev_data, /*!< handle to struct SBR_PREV_FRAME_DATA */
353     int timeSlots)   /*!< Framelength in SBR-timeslots */
354 {
355   int i;
356 
357   /* Set previous energy and noise levels to 0 for the case
358      that decoding starts in the middle of a bitstream */
359   for (i = 0; i < MAX_FREQ_COEFFS; i++)
360     h_prev_data->sfb_nrg_prev[i] = (FIXP_DBL)0;
361   for (i = 0; i < MAX_NOISE_COEFFS; i++)
362     h_prev_data->prevNoiseLevel[i] = (FIXP_DBL)0;
363   for (i = 0; i < MAX_INVF_BANDS; i++) h_prev_data->sbr_invf_mode[i] = INVF_OFF;
364 
365   h_prev_data->stopPos = timeSlots;
366   h_prev_data->coupling = COUPLING_OFF;
367   h_prev_data->ampRes = 0;
368 
369   FDKmemclear(&h_prev_data->prevFrameInfo, sizeof(h_prev_data->prevFrameInfo));
370 }
371 
372 /*!
373   \brief   Read header data from bitstream
374 
375   \return  error status - 0 if ok
376 */
377 SBR_HEADER_STATUS
sbrGetHeaderData(HANDLE_SBR_HEADER_DATA hHeaderData,HANDLE_FDK_BITSTREAM hBs,const UINT flags,const int fIsSbrData,const UCHAR configMode)378 sbrGetHeaderData(HANDLE_SBR_HEADER_DATA hHeaderData, HANDLE_FDK_BITSTREAM hBs,
379                  const UINT flags, const int fIsSbrData,
380                  const UCHAR configMode) {
381   SBR_HEADER_DATA_BS *pBsData;
382   SBR_HEADER_DATA_BS lastHeader;
383   SBR_HEADER_DATA_BS_INFO lastInfo;
384   int headerExtra1 = 0, headerExtra2 = 0;
385 
386   /* Read and discard new header in config change detection mode */
387   if (configMode & AC_CM_DET_CFG_CHANGE) {
388     if (!(flags & (SBRDEC_SYNTAX_RSVD50 | SBRDEC_SYNTAX_USAC))) {
389       /* ampResolution */
390       FDKreadBits(hBs, 1);
391     }
392     /* startFreq, stopFreq */
393     FDKpushFor(hBs, 8);
394     if (!(flags & (SBRDEC_SYNTAX_RSVD50 | SBRDEC_SYNTAX_USAC))) {
395       /* xover_band */
396       FDKreadBits(hBs, 3);
397       /* reserved bits */
398       FDKreadBits(hBs, 2);
399     }
400     headerExtra1 = FDKreadBit(hBs);
401     headerExtra2 = FDKreadBit(hBs);
402     FDKpushFor(hBs, 5 * headerExtra1 + 6 * headerExtra2);
403 
404     return HEADER_OK;
405   }
406 
407   /* Copy SBR bit stream header to temporary header */
408   lastHeader = hHeaderData->bs_data;
409   lastInfo = hHeaderData->bs_info;
410 
411   /* Read new header from bitstream */
412   if ((flags & (SBRDEC_SYNTAX_RSVD50 | SBRDEC_SYNTAX_USAC)) && !fIsSbrData) {
413     pBsData = &hHeaderData->bs_dflt;
414   } else {
415     pBsData = &hHeaderData->bs_data;
416   }
417 
418   if (!(flags & (SBRDEC_SYNTAX_RSVD50 | SBRDEC_SYNTAX_USAC))) {
419     hHeaderData->bs_info.ampResolution = FDKreadBits(hBs, 1);
420   }
421 
422   pBsData->startFreq = FDKreadBits(hBs, 4);
423   pBsData->stopFreq = FDKreadBits(hBs, 4);
424 
425   if (!(flags & (SBRDEC_SYNTAX_RSVD50 | SBRDEC_SYNTAX_USAC))) {
426     hHeaderData->bs_info.xover_band = FDKreadBits(hBs, 3);
427     FDKreadBits(hBs, 2);
428   }
429 
430   headerExtra1 = FDKreadBits(hBs, 1);
431   headerExtra2 = FDKreadBits(hBs, 1);
432 
433   /* Handle extra header information */
434   if (headerExtra1) {
435     pBsData->freqScale = FDKreadBits(hBs, 2);
436     pBsData->alterScale = FDKreadBits(hBs, 1);
437     pBsData->noise_bands = FDKreadBits(hBs, 2);
438   } else {
439     pBsData->freqScale = 2;
440     pBsData->alterScale = 1;
441     pBsData->noise_bands = 2;
442   }
443 
444   if (headerExtra2) {
445     pBsData->limiterBands = FDKreadBits(hBs, 2);
446     pBsData->limiterGains = FDKreadBits(hBs, 2);
447     pBsData->interpolFreq = FDKreadBits(hBs, 1);
448     pBsData->smoothingLength = FDKreadBits(hBs, 1);
449   } else {
450     pBsData->limiterBands = 2;
451     pBsData->limiterGains = 2;
452     pBsData->interpolFreq = 1;
453     pBsData->smoothingLength = 1;
454   }
455 
456   /* Look for new settings. IEC 14496-3, 4.6.18.3.1 */
457   if (hHeaderData->syncState < SBR_HEADER ||
458       lastHeader.startFreq != pBsData->startFreq ||
459       lastHeader.stopFreq != pBsData->stopFreq ||
460       lastHeader.freqScale != pBsData->freqScale ||
461       lastHeader.alterScale != pBsData->alterScale ||
462       lastHeader.noise_bands != pBsData->noise_bands ||
463       lastInfo.xover_band != hHeaderData->bs_info.xover_band) {
464     return HEADER_RESET; /* New settings */
465   }
466 
467   return HEADER_OK;
468 }
469 
470 /*!
471   \brief   Get missing harmonics parameters (only used for AAC+SBR)
472 
473   \return  error status - 0 if ok
474 */
sbrGetSyntheticCodedData(HANDLE_SBR_HEADER_DATA hHeaderData,HANDLE_SBR_FRAME_DATA hFrameData,HANDLE_FDK_BITSTREAM hBs,const UINT flags)475 int sbrGetSyntheticCodedData(HANDLE_SBR_HEADER_DATA hHeaderData,
476                              HANDLE_SBR_FRAME_DATA hFrameData,
477                              HANDLE_FDK_BITSTREAM hBs, const UINT flags) {
478   int i, bitsRead = 0;
479 
480   int add_harmonic_flag = FDKreadBits(hBs, 1);
481   bitsRead++;
482 
483   if (add_harmonic_flag) {
484     int nSfb = hHeaderData->freqBandData.nSfb[1];
485     for (i = 0; i < ADD_HARMONICS_FLAGS_SIZE; i++) {
486       /* read maximum 32 bits and align them to the MSB */
487       int readBits = fMin(32, nSfb);
488       nSfb -= readBits;
489       if (readBits > 0) {
490         hFrameData->addHarmonics[i] = FDKreadBits(hBs, readBits)
491                                       << (32 - readBits);
492       } else {
493         hFrameData->addHarmonics[i] = 0;
494       }
495 
496       bitsRead += readBits;
497     }
498     /* bs_pvc_mode = 0 for Rsvd50 */
499     if (flags & SBRDEC_SYNTAX_USAC) {
500       if (hHeaderData->bs_info.pvc_mode) {
501         int bs_sinusoidal_position = 31;
502         if (FDKreadBit(hBs) /* bs_sinusoidal_position_flag */) {
503           bs_sinusoidal_position = FDKreadBits(hBs, 5);
504         }
505         hFrameData->sinusoidal_position = bs_sinusoidal_position;
506       }
507     }
508   } else {
509     for (i = 0; i < ADD_HARMONICS_FLAGS_SIZE; i++)
510       hFrameData->addHarmonics[i] = 0;
511   }
512 
513   return (bitsRead);
514 }
515 
516 /*!
517   \brief      Reads extension data from the bitstream
518 
519   The bitstream format allows up to 4 kinds of extended data element.
520   Extended data may contain several elements, each identified by a 2-bit-ID.
521   So far, no extended data elements are defined hence the first 2 parameters
522   are unused. The data should be skipped in order to update the number
523   of read bits for the consistency check in applySBR().
524 */
extractExtendedData(HANDLE_SBR_HEADER_DATA hHeaderData,HANDLE_FDK_BITSTREAM hBs,HANDLE_PS_DEC hParametricStereoDec)525 static int extractExtendedData(
526     HANDLE_SBR_HEADER_DATA hHeaderData, /*!< handle to SBR header */
527     HANDLE_FDK_BITSTREAM hBs            /*!< Handle to the bit buffer */
528     ,
529     HANDLE_PS_DEC hParametricStereoDec /*!< Parametric Stereo Decoder */
530 ) {
531   INT nBitsLeft;
532   int extended_data;
533   int i, frameOk = 1;
534 
535   extended_data = FDKreadBits(hBs, 1);
536 
537   if (extended_data) {
538     int cnt;
539     int bPsRead = 0;
540 
541     cnt = FDKreadBits(hBs, 4);
542     if (cnt == (1 << 4) - 1) cnt += FDKreadBits(hBs, 8);
543 
544     nBitsLeft = 8 * cnt;
545 
546     /* sanity check for cnt */
547     if (nBitsLeft > (INT)FDKgetValidBits(hBs)) {
548       /* limit nBitsLeft */
549       nBitsLeft = (INT)FDKgetValidBits(hBs);
550       /* set frame error */
551       frameOk = 0;
552     }
553 
554     while (nBitsLeft > 7) {
555       int extension_id = FDKreadBits(hBs, 2);
556       nBitsLeft -= 2;
557 
558       switch (extension_id) {
559         case EXTENSION_ID_PS_CODING:
560 
561           /* Read PS data from bitstream */
562 
563           if (hParametricStereoDec != NULL) {
564             if (bPsRead &&
565                 !hParametricStereoDec->bsData[hParametricStereoDec->bsReadSlot]
566                      .mpeg.bPsHeaderValid) {
567               cnt = nBitsLeft >> 3; /* number of remaining bytes */
568               for (i = 0; i < cnt; i++) FDKreadBits(hBs, 8);
569               nBitsLeft -= cnt * 8;
570             } else {
571               nBitsLeft -=
572                   (INT)ReadPsData(hParametricStereoDec, hBs, nBitsLeft);
573               bPsRead = 1;
574             }
575           }
576 
577           /* parametric stereo detected, could set channelMode accordingly here
578            */
579           /*                                                                     */
580           /* "The usage of this parametric stereo extension to HE-AAC is */
581           /* signalled implicitly in the bitstream. Hence, if an sbr_extension()
582            */
583           /* with bs_extension_id==EXTENSION_ID_PS is found in the SBR part of
584            */
585           /* the bitstream, a decoder supporting the combination of SBR and PS
586            */
587           /* shall operate the PS tool to generate a stereo output signal." */
588           /* source: ISO/IEC 14496-3:2001/FDAM 2:2004(E) */
589 
590           break;
591 
592         default:
593           cnt = nBitsLeft >> 3; /* number of remaining bytes */
594           for (i = 0; i < cnt; i++) FDKreadBits(hBs, 8);
595           nBitsLeft -= cnt * 8;
596           break;
597       }
598     }
599 
600     if (nBitsLeft < 0) {
601       frameOk = 0;
602       goto bail;
603     } else {
604       /* Read fill bits for byte alignment */
605       FDKreadBits(hBs, nBitsLeft);
606     }
607   }
608 
609 bail:
610   return (frameOk);
611 }
612 
613 /*!
614   \brief      Read bitstream elements of a SBR channel element
615   \return     SbrFrameOK
616 */
sbrGetChannelElement(HANDLE_SBR_HEADER_DATA hHeaderData,HANDLE_SBR_FRAME_DATA hFrameDataLeft,HANDLE_SBR_FRAME_DATA hFrameDataRight,HANDLE_SBR_PREV_FRAME_DATA hFrameDataLeftPrev,UCHAR pvc_mode_last,HANDLE_FDK_BITSTREAM hBs,HANDLE_PS_DEC hParametricStereoDec,const UINT flags,const int overlap)617 int sbrGetChannelElement(HANDLE_SBR_HEADER_DATA hHeaderData,
618                          HANDLE_SBR_FRAME_DATA hFrameDataLeft,
619                          HANDLE_SBR_FRAME_DATA hFrameDataRight,
620                          HANDLE_SBR_PREV_FRAME_DATA hFrameDataLeftPrev,
621                          UCHAR pvc_mode_last, HANDLE_FDK_BITSTREAM hBs,
622                          HANDLE_PS_DEC hParametricStereoDec, const UINT flags,
623                          const int overlap) {
624   int i, bs_coupling = COUPLING_OFF;
625   const int nCh = (hFrameDataRight == NULL) ? 1 : 2;
626 
627   if (!(flags & (SBRDEC_SYNTAX_USAC | SBRDEC_SYNTAX_RSVD50))) {
628     /* Reserved bits */
629     if (FDKreadBits(hBs, 1)) { /* bs_data_extra */
630       FDKreadBits(hBs, 4);
631       if ((flags & SBRDEC_SYNTAX_SCAL) || (nCh == 2)) {
632         FDKreadBits(hBs, 4);
633       }
634     }
635   }
636 
637   if (nCh == 2) {
638     /* Read coupling flag */
639     bs_coupling = FDKreadBits(hBs, 1);
640     if (bs_coupling) {
641       hFrameDataLeft->coupling = COUPLING_LEVEL;
642       hFrameDataRight->coupling = COUPLING_BAL;
643     } else {
644       hFrameDataLeft->coupling = COUPLING_OFF;
645       hFrameDataRight->coupling = COUPLING_OFF;
646     }
647   } else {
648     if (flags & SBRDEC_SYNTAX_SCAL) {
649       FDKreadBits(hBs, 1); /* bs_coupling */
650     }
651     hFrameDataLeft->coupling = COUPLING_OFF;
652   }
653 
654   if (flags & (SBRDEC_SYNTAX_USAC | SBRDEC_SYNTAX_RSVD50)) {
655     if (flags & SBRDEC_USAC_HARMONICSBR) {
656       hFrameDataLeft->sbrPatchingMode = FDKreadBit(hBs);
657       if (hFrameDataLeft->sbrPatchingMode == 0) {
658         hFrameDataLeft->sbrOversamplingFlag = FDKreadBit(hBs);
659         if (FDKreadBit(hBs)) { /* sbrPitchInBinsFlag */
660           hFrameDataLeft->sbrPitchInBins = FDKreadBits(hBs, 7);
661         } else {
662           hFrameDataLeft->sbrPitchInBins = 0;
663         }
664       } else {
665         hFrameDataLeft->sbrOversamplingFlag = 0;
666         hFrameDataLeft->sbrPitchInBins = 0;
667       }
668 
669       if (nCh == 2) {
670         if (bs_coupling) {
671           hFrameDataRight->sbrPatchingMode = hFrameDataLeft->sbrPatchingMode;
672           hFrameDataRight->sbrOversamplingFlag =
673               hFrameDataLeft->sbrOversamplingFlag;
674           hFrameDataRight->sbrPitchInBins = hFrameDataLeft->sbrPitchInBins;
675         } else {
676           hFrameDataRight->sbrPatchingMode = FDKreadBit(hBs);
677           if (hFrameDataRight->sbrPatchingMode == 0) {
678             hFrameDataRight->sbrOversamplingFlag = FDKreadBit(hBs);
679             if (FDKreadBit(hBs)) { /* sbrPitchInBinsFlag */
680               hFrameDataRight->sbrPitchInBins = FDKreadBits(hBs, 7);
681             } else {
682               hFrameDataRight->sbrPitchInBins = 0;
683             }
684           } else {
685             hFrameDataRight->sbrOversamplingFlag = 0;
686             hFrameDataRight->sbrPitchInBins = 0;
687           }
688         }
689       }
690     } else {
691       if (nCh == 2) {
692         hFrameDataRight->sbrPatchingMode = 1;
693         hFrameDataRight->sbrOversamplingFlag = 0;
694         hFrameDataRight->sbrPitchInBins = 0;
695       }
696 
697       hFrameDataLeft->sbrPatchingMode = 1;
698       hFrameDataLeft->sbrOversamplingFlag = 0;
699       hFrameDataLeft->sbrPitchInBins = 0;
700     }
701   } else {
702     if (nCh == 2) {
703       hFrameDataRight->sbrPatchingMode = 1;
704       hFrameDataRight->sbrOversamplingFlag = 0;
705       hFrameDataRight->sbrPitchInBins = 0;
706     }
707 
708     hFrameDataLeft->sbrPatchingMode = 1;
709     hFrameDataLeft->sbrOversamplingFlag = 0;
710     hFrameDataLeft->sbrPitchInBins = 0;
711   }
712 
713   /*
714     sbr_grid(): Grid control
715   */
716   if (hHeaderData->bs_info.pvc_mode) {
717     FDK_ASSERT(nCh == 1); /* PVC not possible for CPE */
718     if (!extractPvcFrameInfo(hBs, hHeaderData, hFrameDataLeft,
719                              hFrameDataLeftPrev, pvc_mode_last, flags))
720       return 0;
721 
722     if (!checkFrameInfo(&hFrameDataLeft->frameInfo,
723                         hHeaderData->numberTimeSlots, overlap,
724                         hHeaderData->timeStep))
725       return 0;
726   } else {
727     if (!extractFrameInfo(hBs, hHeaderData, hFrameDataLeft, 1, flags)) return 0;
728 
729     if (!checkFrameInfo(&hFrameDataLeft->frameInfo,
730                         hHeaderData->numberTimeSlots, overlap,
731                         hHeaderData->timeStep))
732       return 0;
733   }
734   if (nCh == 2) {
735     if (hFrameDataLeft->coupling) {
736       FDKmemcpy(&hFrameDataRight->frameInfo, &hFrameDataLeft->frameInfo,
737                 sizeof(FRAME_INFO));
738       hFrameDataRight->ampResolutionCurrentFrame =
739           hFrameDataLeft->ampResolutionCurrentFrame;
740     } else {
741       if (!extractFrameInfo(hBs, hHeaderData, hFrameDataRight, 2, flags))
742         return 0;
743 
744       if (!checkFrameInfo(&hFrameDataRight->frameInfo,
745                           hHeaderData->numberTimeSlots, overlap,
746                           hHeaderData->timeStep))
747         return 0;
748     }
749   }
750 
751   /*
752     sbr_dtdf(): Fetch domain vectors (time or frequency direction for
753     delta-coding)
754   */
755   sbrGetDirectionControlData(hFrameDataLeft, hBs, flags,
756                              hHeaderData->bs_info.pvc_mode);
757   if (nCh == 2) {
758     sbrGetDirectionControlData(hFrameDataRight, hBs, flags, 0);
759   }
760 
761   /* sbr_invf() */
762   for (i = 0; i < hHeaderData->freqBandData.nInvfBands; i++) {
763     hFrameDataLeft->sbr_invf_mode[i] = (INVF_MODE)FDKreadBits(hBs, 2);
764   }
765   if (nCh == 2) {
766     if (hFrameDataLeft->coupling) {
767       for (i = 0; i < hHeaderData->freqBandData.nInvfBands; i++) {
768         hFrameDataRight->sbr_invf_mode[i] = hFrameDataLeft->sbr_invf_mode[i];
769       }
770     } else {
771       for (i = 0; i < hHeaderData->freqBandData.nInvfBands; i++) {
772         hFrameDataRight->sbr_invf_mode[i] = (INVF_MODE)FDKreadBits(hBs, 2);
773       }
774     }
775   }
776 
777   if (nCh == 1) {
778     if (hHeaderData->bs_info.pvc_mode) {
779       if (!sbrGetPvcEnvelope(hHeaderData, hFrameDataLeft, hBs, flags,
780                              hHeaderData->bs_info.pvc_mode))
781         return 0;
782     } else if (!sbrGetEnvelope(hHeaderData, hFrameDataLeft, hBs, flags))
783       return 0;
784 
785     sbrGetNoiseFloorData(hHeaderData, hFrameDataLeft, hBs);
786   } else if (hFrameDataLeft->coupling) {
787     if (!sbrGetEnvelope(hHeaderData, hFrameDataLeft, hBs, flags)) {
788       return 0;
789     }
790 
791     sbrGetNoiseFloorData(hHeaderData, hFrameDataLeft, hBs);
792 
793     if (!sbrGetEnvelope(hHeaderData, hFrameDataRight, hBs, flags)) {
794       return 0;
795     }
796     sbrGetNoiseFloorData(hHeaderData, hFrameDataRight, hBs);
797   } else { /* nCh == 2 && no coupling */
798 
799     if (!sbrGetEnvelope(hHeaderData, hFrameDataLeft, hBs, flags)) return 0;
800 
801     if (!sbrGetEnvelope(hHeaderData, hFrameDataRight, hBs, flags)) return 0;
802 
803     sbrGetNoiseFloorData(hHeaderData, hFrameDataLeft, hBs);
804 
805     sbrGetNoiseFloorData(hHeaderData, hFrameDataRight, hBs);
806   }
807 
808   sbrGetSyntheticCodedData(hHeaderData, hFrameDataLeft, hBs, flags);
809   if (nCh == 2) {
810     sbrGetSyntheticCodedData(hHeaderData, hFrameDataRight, hBs, flags);
811   }
812 
813   if (!(flags & (SBRDEC_SYNTAX_USAC | SBRDEC_SYNTAX_RSVD50))) {
814     if (!extractExtendedData(hHeaderData, hBs, hParametricStereoDec)) {
815       return 0;
816     }
817   }
818 
819   return 1;
820 }
821 
822 /*!
823   \brief   Read direction control data from bitstream
824 */
sbrGetDirectionControlData(HANDLE_SBR_FRAME_DATA h_frame_data,HANDLE_FDK_BITSTREAM hBs,const UINT flags,const int bs_pvc_mode)825 void sbrGetDirectionControlData(
826     HANDLE_SBR_FRAME_DATA h_frame_data, /*!< handle to struct SBR_FRAME_DATA */
827     HANDLE_FDK_BITSTREAM hBs,           /*!< handle to struct BIT_BUF */
828     const UINT flags, const int bs_pvc_mode)
829 
830 {
831   int i;
832   int indepFlag = 0;
833 
834   if (flags & (SBRDEC_SYNTAX_USAC | SBRDEC_SYNTAX_RSVD50)) {
835     indepFlag = flags & SBRDEC_USAC_INDEP;
836   }
837 
838   if (bs_pvc_mode == 0) {
839     i = 0;
840     if (indepFlag) {
841       h_frame_data->domain_vec[i++] = 0;
842     }
843     for (; i < h_frame_data->frameInfo.nEnvelopes; i++) {
844       h_frame_data->domain_vec[i] = FDKreadBits(hBs, 1);
845     }
846   }
847 
848   i = 0;
849   if (indepFlag) {
850     h_frame_data->domain_vec_noise[i++] = 0;
851   }
852   for (; i < h_frame_data->frameInfo.nNoiseEnvelopes; i++) {
853     h_frame_data->domain_vec_noise[i] = FDKreadBits(hBs, 1);
854   }
855 }
856 
857 /*!
858   \brief   Read noise-floor-level data from bitstream
859 */
sbrGetNoiseFloorData(HANDLE_SBR_HEADER_DATA hHeaderData,HANDLE_SBR_FRAME_DATA h_frame_data,HANDLE_FDK_BITSTREAM hBs)860 void sbrGetNoiseFloorData(
861     HANDLE_SBR_HEADER_DATA hHeaderData, /*!< Static control data */
862     HANDLE_SBR_FRAME_DATA h_frame_data, /*!< handle to struct SBR_FRAME_DATA */
863     HANDLE_FDK_BITSTREAM hBs)           /*!< handle to struct BIT_BUF */
864 {
865   int i, j;
866   int delta;
867   COUPLING_MODE coupling;
868   int noNoiseBands = hHeaderData->freqBandData.nNfb;
869 
870   Huffman hcb_noiseF;
871   Huffman hcb_noise;
872   int envDataTableCompFactor;
873 
874   coupling = h_frame_data->coupling;
875 
876   /*
877     Select huffman codebook depending on coupling mode
878   */
879   if (coupling == COUPLING_BAL) {
880     hcb_noise = (Huffman)&FDK_sbrDecoder_sbr_huffBook_NoiseBalance11T;
881     hcb_noiseF =
882         (Huffman)&FDK_sbrDecoder_sbr_huffBook_EnvBalance11F; /* "sbr_huffBook_NoiseBalance11F"
883                                                               */
884     envDataTableCompFactor = 1;
885   } else {
886     hcb_noise = (Huffman)&FDK_sbrDecoder_sbr_huffBook_NoiseLevel11T;
887     hcb_noiseF =
888         (Huffman)&FDK_sbrDecoder_sbr_huffBook_EnvLevel11F; /* "sbr_huffBook_NoiseLevel11F"
889                                                             */
890     envDataTableCompFactor = 0;
891   }
892 
893   /*
894     Read raw noise-envelope data
895   */
896   for (i = 0; i < h_frame_data->frameInfo.nNoiseEnvelopes; i++) {
897     if (h_frame_data->domain_vec_noise[i] == 0) {
898       if (coupling == COUPLING_BAL) {
899         h_frame_data->sbrNoiseFloorLevel[i * noNoiseBands] =
900             (FIXP_SGL)(((int)FDKreadBits(hBs, 5)) << envDataTableCompFactor);
901       } else {
902         h_frame_data->sbrNoiseFloorLevel[i * noNoiseBands] =
903             (FIXP_SGL)(int)FDKreadBits(hBs, 5);
904       }
905 
906       for (j = 1; j < noNoiseBands; j++) {
907         delta = DecodeHuffmanCW(hcb_noiseF, hBs);
908         h_frame_data->sbrNoiseFloorLevel[i * noNoiseBands + j] =
909             (FIXP_SGL)(delta << envDataTableCompFactor);
910       }
911     } else {
912       for (j = 0; j < noNoiseBands; j++) {
913         delta = DecodeHuffmanCW(hcb_noise, hBs);
914         h_frame_data->sbrNoiseFloorLevel[i * noNoiseBands + j] =
915             (FIXP_SGL)(delta << envDataTableCompFactor);
916       }
917     }
918   }
919 }
920 
921 /* ns = mapNsMode2ns[pvcMode-1][nsMode] */
922 static const UCHAR mapNsMode2ns[2][2] = {
923     {16, 4}, /* pvcMode = 1 */
924     {12, 3}  /* pvcMode = 2 */
925 };
926 
sbrGetPvcEnvelope(HANDLE_SBR_HEADER_DATA hHeaderData,HANDLE_SBR_FRAME_DATA h_frame_data,HANDLE_FDK_BITSTREAM hBs,const UINT flags,const UINT pvcMode)927 static int sbrGetPvcEnvelope(
928     HANDLE_SBR_HEADER_DATA hHeaderData, /*!< Static control data */
929     HANDLE_SBR_FRAME_DATA h_frame_data, /*!< handle to struct SBR_FRAME_DATA */
930     HANDLE_FDK_BITSTREAM hBs,           /*!< handle to struct BIT_BUF */
931     const UINT flags, const UINT pvcMode) {
932   int divMode, nsMode;
933   int indepFlag = flags & SBRDEC_USAC_INDEP;
934   UCHAR *pvcID = h_frame_data->pvcID;
935 
936   divMode = FDKreadBits(hBs, PVC_DIVMODE_BITS);
937   nsMode = FDKreadBit(hBs);
938   FDK_ASSERT((pvcMode == 1) || (pvcMode == 2));
939   h_frame_data->ns = mapNsMode2ns[pvcMode - 1][nsMode];
940 
941   if (divMode <= 3) {
942     int i, k = 1, sum_length = 0, reuse_pcvID;
943 
944     /* special treatment for first time slot k=0 */
945     indepFlag ? (reuse_pcvID = 0) : (reuse_pcvID = FDKreadBit(hBs));
946     if (reuse_pcvID) {
947       pvcID[0] = hHeaderData->pvcIDprev;
948     } else {
949       pvcID[0] = FDKreadBits(hBs, PVC_PVCID_BITS);
950     }
951 
952     /* other time slots k>0 */
953     for (i = 0; i < divMode; i++) {
954       int length, numBits = 4;
955 
956       if (sum_length >= 13) {
957         numBits = 1;
958       } else if (sum_length >= 11) {
959         numBits = 2;
960       } else if (sum_length >= 7) {
961         numBits = 3;
962       }
963 
964       length = FDKreadBits(hBs, numBits);
965       sum_length += length + 1;
966       if (sum_length >= PVC_NTIMESLOT) {
967         return 0; /* parse error */
968       }
969       for (; length--; k++) {
970         pvcID[k] = pvcID[k - 1];
971       }
972       pvcID[k++] = FDKreadBits(hBs, PVC_PVCID_BITS);
973     }
974     for (; k < 16; k++) {
975       pvcID[k] = pvcID[k - 1];
976     }
977   } else { /* divMode >= 4 */
978     int num_grid_info, fixed_length, grid_info, j, k = 0;
979 
980     divMode -= 4;
981     num_grid_info = 2 << divMode;
982     fixed_length = 8 >> divMode;
983     FDK_ASSERT(num_grid_info * fixed_length == PVC_NTIMESLOT);
984 
985     /* special treatment for first time slot k=0 */
986     indepFlag ? (grid_info = 1) : (grid_info = FDKreadBit(hBs));
987     if (grid_info) {
988       pvcID[k++] = FDKreadBits(hBs, PVC_PVCID_BITS);
989     } else {
990       pvcID[k++] = hHeaderData->pvcIDprev;
991     }
992     j = fixed_length - 1;
993     for (; j--; k++) {
994       pvcID[k] = pvcID[k - 1];
995     }
996     num_grid_info--;
997 
998     /* other time slots k>0 */
999     for (; num_grid_info--;) {
1000       j = fixed_length;
1001       grid_info = FDKreadBit(hBs);
1002       if (grid_info) {
1003         pvcID[k++] = FDKreadBits(hBs, PVC_PVCID_BITS);
1004         j--;
1005       }
1006       for (; j--; k++) {
1007         pvcID[k] = pvcID[k - 1];
1008       }
1009     }
1010   }
1011 
1012   hHeaderData->pvcIDprev = pvcID[PVC_NTIMESLOT - 1];
1013 
1014   /* usage of PVC excludes inter-TES tool */
1015   h_frame_data->iTESactive = (UCHAR)0;
1016 
1017   return 1;
1018 }
1019 /*!
1020   \brief   Read envelope data from bitstream
1021 */
sbrGetEnvelope(HANDLE_SBR_HEADER_DATA hHeaderData,HANDLE_SBR_FRAME_DATA h_frame_data,HANDLE_FDK_BITSTREAM hBs,const UINT flags)1022 static int sbrGetEnvelope(
1023     HANDLE_SBR_HEADER_DATA hHeaderData, /*!< Static control data */
1024     HANDLE_SBR_FRAME_DATA h_frame_data, /*!< handle to struct SBR_FRAME_DATA */
1025     HANDLE_FDK_BITSTREAM hBs,           /*!< handle to struct BIT_BUF */
1026     const UINT flags) {
1027   int i, j;
1028   UCHAR no_band[MAX_ENVELOPES];
1029   int delta = 0;
1030   int offset = 0;
1031   COUPLING_MODE coupling = h_frame_data->coupling;
1032   int ampRes = hHeaderData->bs_info.ampResolution;
1033   int nEnvelopes = h_frame_data->frameInfo.nEnvelopes;
1034   int envDataTableCompFactor;
1035   int start_bits, start_bits_balance;
1036   Huffman hcb_t, hcb_f;
1037 
1038   h_frame_data->nScaleFactors = 0;
1039 
1040   if ((h_frame_data->frameInfo.frameClass == 0) && (nEnvelopes == 1)) {
1041     if (flags & SBRDEC_ELD_GRID)
1042       ampRes = h_frame_data->ampResolutionCurrentFrame;
1043     else
1044       ampRes = 0;
1045   }
1046   h_frame_data->ampResolutionCurrentFrame = ampRes;
1047 
1048   /*
1049     Set number of bits for first value depending on amplitude resolution
1050   */
1051   if (ampRes == 1) {
1052     start_bits = 6;
1053     start_bits_balance = 5;
1054   } else {
1055     start_bits = 7;
1056     start_bits_balance = 6;
1057   }
1058 
1059   /*
1060     Calculate number of values for each envelope and alltogether
1061   */
1062   for (i = 0; i < nEnvelopes; i++) {
1063     no_band[i] =
1064         hHeaderData->freqBandData.nSfb[h_frame_data->frameInfo.freqRes[i]];
1065     h_frame_data->nScaleFactors += no_band[i];
1066   }
1067   if (h_frame_data->nScaleFactors > MAX_NUM_ENVELOPE_VALUES) return 0;
1068 
1069   /*
1070     Select Huffman codebook depending on coupling mode and amplitude resolution
1071   */
1072   if (coupling == COUPLING_BAL) {
1073     envDataTableCompFactor = 1;
1074     if (ampRes == 0) {
1075       hcb_t = (Huffman)&FDK_sbrDecoder_sbr_huffBook_EnvBalance10T;
1076       hcb_f = (Huffman)&FDK_sbrDecoder_sbr_huffBook_EnvBalance10F;
1077     } else {
1078       hcb_t = (Huffman)&FDK_sbrDecoder_sbr_huffBook_EnvBalance11T;
1079       hcb_f = (Huffman)&FDK_sbrDecoder_sbr_huffBook_EnvBalance11F;
1080     }
1081   } else {
1082     envDataTableCompFactor = 0;
1083     if (ampRes == 0) {
1084       hcb_t = (Huffman)&FDK_sbrDecoder_sbr_huffBook_EnvLevel10T;
1085       hcb_f = (Huffman)&FDK_sbrDecoder_sbr_huffBook_EnvLevel10F;
1086     } else {
1087       hcb_t = (Huffman)&FDK_sbrDecoder_sbr_huffBook_EnvLevel11T;
1088       hcb_f = (Huffman)&FDK_sbrDecoder_sbr_huffBook_EnvLevel11F;
1089     }
1090   }
1091 
1092   h_frame_data->iTESactive = (UCHAR)0; /* disable inter-TES by default */
1093   /*
1094     Now read raw envelope data
1095   */
1096   for (j = 0, offset = 0; j < nEnvelopes; j++) {
1097     if (h_frame_data->domain_vec[j] == 0) {
1098       if (coupling == COUPLING_BAL) {
1099         h_frame_data->iEnvelope[offset] =
1100             (FIXP_SGL)(((int)FDKreadBits(hBs, start_bits_balance))
1101                        << envDataTableCompFactor);
1102       } else {
1103         h_frame_data->iEnvelope[offset] =
1104             (FIXP_SGL)(int)FDKreadBits(hBs, start_bits);
1105       }
1106     }
1107 
1108     for (i = (1 - h_frame_data->domain_vec[j]); i < no_band[j]; i++) {
1109       if (h_frame_data->domain_vec[j] == 0) {
1110         delta = DecodeHuffmanCW(hcb_f, hBs);
1111       } else {
1112         delta = DecodeHuffmanCW(hcb_t, hBs);
1113       }
1114 
1115       h_frame_data->iEnvelope[offset + i] =
1116           (FIXP_SGL)(delta << envDataTableCompFactor);
1117     }
1118     if ((flags & SBRDEC_SYNTAX_USAC) && (flags & SBRDEC_USAC_ITES)) {
1119       int bs_temp_shape = FDKreadBit(hBs);
1120       FDK_ASSERT(j < 8);
1121       h_frame_data->iTESactive |= (UCHAR)(bs_temp_shape << j);
1122       if (bs_temp_shape) {
1123         h_frame_data->interTempShapeMode[j] =
1124             FDKread2Bits(hBs); /* bs_inter_temp_shape_mode */
1125       } else {
1126         h_frame_data->interTempShapeMode[j] = 0;
1127       }
1128     }
1129     offset += no_band[j];
1130   }
1131 
1132 #if ENV_EXP_FRACT
1133   /* Convert from int to scaled fract (ENV_EXP_FRACT bits for the fractional
1134    * part) */
1135   for (i = 0; i < h_frame_data->nScaleFactors; i++) {
1136     h_frame_data->iEnvelope[i] <<= ENV_EXP_FRACT;
1137   }
1138 #endif
1139 
1140   return 1;
1141 }
1142 
1143 /***************************************************************************/
1144 /*!
1145   \brief    Generates frame info for FIXFIXonly frame class used for low delay
1146  version
1147 
1148   \return   zero for error, one for correct.
1149  ****************************************************************************/
generateFixFixOnly(FRAME_INFO * hSbrFrameInfo,int tranPosInternal,int numberTimeSlots,const UINT flags)1150 static int generateFixFixOnly(FRAME_INFO *hSbrFrameInfo, int tranPosInternal,
1151                               int numberTimeSlots, const UINT flags) {
1152   int nEnv, i, tranIdx;
1153   const int *pTable;
1154 
1155   if (tranPosInternal >= numberTimeSlots) {
1156     return 0;
1157   }
1158 
1159   switch (numberTimeSlots) {
1160     case 8:
1161       pTable = FDK_sbrDecoder_envelopeTable_8[tranPosInternal];
1162       break;
1163     case 15:
1164       pTable = FDK_sbrDecoder_envelopeTable_15[tranPosInternal];
1165       break;
1166     case 16:
1167       pTable = FDK_sbrDecoder_envelopeTable_16[tranPosInternal];
1168       break;
1169     default:
1170       return 0;
1171   }
1172 
1173   /* look number of envelopes in table */
1174   nEnv = pTable[0];
1175   /* look up envelope distribution in table */
1176   for (i = 1; i < nEnv; i++) hSbrFrameInfo->borders[i] = pTable[i + 2];
1177   /* open and close frame border */
1178   hSbrFrameInfo->borders[0] = 0;
1179   hSbrFrameInfo->borders[nEnv] = numberTimeSlots;
1180   hSbrFrameInfo->nEnvelopes = nEnv;
1181 
1182   /* transient idx */
1183   tranIdx = hSbrFrameInfo->tranEnv = pTable[1];
1184 
1185   /* add noise floors */
1186   hSbrFrameInfo->bordersNoise[0] = 0;
1187   hSbrFrameInfo->bordersNoise[1] =
1188       hSbrFrameInfo->borders[tranIdx ? tranIdx : 1];
1189   hSbrFrameInfo->bordersNoise[2] = numberTimeSlots;
1190   /* nEnv is always > 1, so nNoiseEnvelopes is always 2 (IEC 14496-3 4.6.19.3.2)
1191    */
1192   hSbrFrameInfo->nNoiseEnvelopes = 2;
1193 
1194   return 1;
1195 }
1196 
1197 /*!
1198   \brief  Extracts LowDelaySBR control data from the bitstream.
1199 
1200   \return zero for bitstream error, one for correct.
1201 */
extractLowDelayGrid(HANDLE_FDK_BITSTREAM hBitBuf,HANDLE_SBR_HEADER_DATA hHeaderData,HANDLE_SBR_FRAME_DATA h_frame_data,int timeSlots,const UINT flags)1202 static int extractLowDelayGrid(
1203     HANDLE_FDK_BITSTREAM hBitBuf, /*!< bitbuffer handle */
1204     HANDLE_SBR_HEADER_DATA hHeaderData,
1205     HANDLE_SBR_FRAME_DATA
1206         h_frame_data, /*!< contains the FRAME_INFO struct to be filled */
1207     int timeSlots, const UINT flags) {
1208   FRAME_INFO *pFrameInfo = &h_frame_data->frameInfo;
1209   INT numberTimeSlots = hHeaderData->numberTimeSlots;
1210   INT temp = 0, k;
1211 
1212   /* FIXFIXonly framing case */
1213   h_frame_data->frameInfo.frameClass = 0;
1214 
1215   /* get the transient position from the bitstream */
1216   switch (timeSlots) {
1217     case 8:
1218       /* 3bit transient position (temp={0;..;7}) */
1219       temp = FDKreadBits(hBitBuf, 3);
1220       break;
1221 
1222     case 16:
1223     case 15:
1224       /* 4bit transient position (temp={0;..;15}) */
1225       temp = FDKreadBits(hBitBuf, 4);
1226       break;
1227 
1228     default:
1229       return 0;
1230   }
1231 
1232   /* For "case 15" only*/
1233   if (temp >= timeSlots) {
1234     return 0;
1235   }
1236 
1237   /* calculate borders according to the transient position */
1238   if (!generateFixFixOnly(pFrameInfo, temp, numberTimeSlots, flags)) {
1239     return 0;
1240   }
1241 
1242   /* decode freq res: */
1243   for (k = 0; k < pFrameInfo->nEnvelopes; k++) {
1244     pFrameInfo->freqRes[k] =
1245         (UCHAR)FDKreadBits(hBitBuf, 1); /* f = F [1 bits] */
1246   }
1247 
1248   return 1;
1249 }
1250 
1251 /*!
1252   \brief   Extract the PVC frame information (structure FRAME_INFO) from the
1253   bitstream \return  Zero for bitstream error, one for correct.
1254 */
extractPvcFrameInfo(HANDLE_FDK_BITSTREAM hBs,HANDLE_SBR_HEADER_DATA hHeaderData,HANDLE_SBR_FRAME_DATA h_frame_data,HANDLE_SBR_PREV_FRAME_DATA h_prev_frame_data,UCHAR pvc_mode_last,const UINT flags)1255 int extractPvcFrameInfo(
1256     HANDLE_FDK_BITSTREAM hBs,           /*!< bitbuffer handle */
1257     HANDLE_SBR_HEADER_DATA hHeaderData, /*!< Static control data */
1258     HANDLE_SBR_FRAME_DATA h_frame_data, /*!< pointer to memory where the
1259                                            frame-info will be stored */
1260     HANDLE_SBR_PREV_FRAME_DATA h_prev_frame_data, /*!< pointer to memory where
1261                                                      the previous frame-info
1262                                                      will be stored */
1263     UCHAR pvc_mode_last,                          /**< PVC mode of last frame */
1264     const UINT flags) {
1265   FRAME_INFO *pFrameInfo = &h_frame_data->frameInfo;
1266   FRAME_INFO *pPrevFrameInfo = &h_prev_frame_data->prevFrameInfo;
1267   int bs_var_len_hf, bs_noise_position;
1268   bs_noise_position = FDKreadBits(hBs, 4); /* SBR_PVC_NOISEPOSITION_BITS 4 */
1269   bs_var_len_hf = FDKreadBit(hBs);
1270   pFrameInfo->noisePosition = bs_noise_position;
1271   pFrameInfo->tranEnv = -1;
1272 
1273   /* Init for bs_noise_position == 0 in case a parse error is found below. */
1274   pFrameInfo->nEnvelopes = 1;
1275   pFrameInfo->nNoiseEnvelopes = 1;
1276   pFrameInfo->freqRes[0] = 0;
1277 
1278   if (bs_var_len_hf) { /* 1 or 3 Bits */
1279     pFrameInfo->varLength = FDKreadBits(hBs, 2) + 1;
1280     if (pFrameInfo->varLength > 3) {
1281       pFrameInfo->varLength =
1282           0;    /* assume bs_var_len_hf == 0 in case of error */
1283       return 0; /* reserved value -> parse error */
1284     }
1285   } else {
1286     pFrameInfo->varLength = 0;
1287   }
1288 
1289   if (bs_noise_position) {
1290     pFrameInfo->nEnvelopes = 2;
1291     pFrameInfo->nNoiseEnvelopes = 2;
1292     FDKmemclear(pFrameInfo->freqRes, sizeof(pFrameInfo->freqRes));
1293   }
1294 
1295   /* frame border calculation */
1296   if (hHeaderData->bs_info.pvc_mode > 0) {
1297     /* See "7.5.1.4 HF adjustment of SBR envelope scalefactors" for reference.
1298      */
1299 
1300     FDK_ASSERT((pFrameInfo->nEnvelopes == 1) || (pFrameInfo->nEnvelopes == 2));
1301 
1302     /* left timeborder-offset: use the timeborder of prev SBR frame */
1303     if (pPrevFrameInfo->nEnvelopes > 0) {
1304       pFrameInfo->borders[0] =
1305           pPrevFrameInfo->borders[pPrevFrameInfo->nEnvelopes] - PVC_NTIMESLOT;
1306       FDK_ASSERT(pFrameInfo->borders[0] <= 3);
1307     } else {
1308       pFrameInfo->borders[0] = 0;
1309     }
1310 
1311     /* right timeborder-offset: */
1312     pFrameInfo->borders[pFrameInfo->nEnvelopes] = 16 + pFrameInfo->varLength;
1313 
1314     if (pFrameInfo->nEnvelopes == 2) {
1315       pFrameInfo->borders[1] = pFrameInfo->noisePosition;
1316     }
1317 
1318     /* Calculation of PVC time borders t_EPVC */
1319     if (pvc_mode_last == 0) {
1320       /* there was a legacy SBR frame before this frame => use bs_var_len' for
1321        * first PVC timeslot */
1322       pFrameInfo->pvcBorders[0] = pFrameInfo->borders[0];
1323     } else {
1324       pFrameInfo->pvcBorders[0] = 0;
1325     }
1326     if (pFrameInfo->nEnvelopes == 2) {
1327       pFrameInfo->pvcBorders[1] = pFrameInfo->borders[1];
1328     }
1329     pFrameInfo->pvcBorders[pFrameInfo->nEnvelopes] = 16;
1330 
1331     /* calculation of SBR noise-floor time-border vector: */
1332     for (INT i = 0; i <= pFrameInfo->nNoiseEnvelopes; i++) {
1333       pFrameInfo->bordersNoise[i] = pFrameInfo->borders[i];
1334     }
1335 
1336     pFrameInfo->tranEnv = -1; /* tranEnv not used */
1337   }
1338   return 1;
1339 }
1340 
1341 /*!
1342   \brief   Extract the frame information (structure FRAME_INFO) from the
1343   bitstream \return  Zero for bitstream error, one for correct.
1344 */
extractFrameInfo(HANDLE_FDK_BITSTREAM hBs,HANDLE_SBR_HEADER_DATA hHeaderData,HANDLE_SBR_FRAME_DATA h_frame_data,const UINT nrOfChannels,const UINT flags)1345 int extractFrameInfo(
1346     HANDLE_FDK_BITSTREAM hBs,           /*!< bitbuffer handle */
1347     HANDLE_SBR_HEADER_DATA hHeaderData, /*!< Static control data */
1348     HANDLE_SBR_FRAME_DATA h_frame_data, /*!< pointer to memory where the
1349                                            frame-info will be stored */
1350     const UINT nrOfChannels, const UINT flags) {
1351   FRAME_INFO *pFrameInfo = &h_frame_data->frameInfo;
1352   int numberTimeSlots = hHeaderData->numberTimeSlots;
1353   int pointer_bits = 0, nEnv = 0, b = 0, border, i, n = 0, k, p, aL, aR, nL, nR,
1354       temp = 0, staticFreqRes;
1355   UCHAR frameClass;
1356 
1357   if (flags & SBRDEC_ELD_GRID) {
1358     /* CODEC_AACLD (LD+SBR) only uses the normal 0 Grid for non-transient Frames
1359      * and the LowDelayGrid for transient Frames */
1360     frameClass = FDKreadBits(hBs, 1); /* frameClass = [1 bit] */
1361     if (frameClass == 1) {
1362       /* if frameClass == 1, extract LowDelaySbrGrid, otherwise extract normal
1363        * SBR-Grid for FIXIFX */
1364       /* extract the AACLD-Sbr-Grid */
1365       pFrameInfo->frameClass = frameClass;
1366       int err = 1;
1367       err = extractLowDelayGrid(hBs, hHeaderData, h_frame_data, numberTimeSlots,
1368                                 flags);
1369       return err;
1370     }
1371   } else {
1372     frameClass = FDKreadBits(hBs, 2); /* frameClass = C [2 bits] */
1373   }
1374 
1375   switch (frameClass) {
1376     case 0:
1377       temp = FDKreadBits(hBs, 2); /* E [2 bits ] */
1378       nEnv = (int)(1 << temp);    /* E -> e */
1379 
1380       if ((flags & SBRDEC_ELD_GRID) && (nEnv == 1))
1381         h_frame_data->ampResolutionCurrentFrame =
1382             FDKreadBits(hBs, 1); /* new ELD Syntax 07-11-09 */
1383 
1384       staticFreqRes = FDKreadBits(hBs, 1);
1385 
1386       if (flags & (SBRDEC_SYNTAX_USAC | SBRDEC_SYNTAX_RSVD50)) {
1387         if (nEnv > MAX_ENVELOPES_USAC) return 0;
1388       } else
1389 
1390         b = nEnv + 1;
1391       switch (nEnv) {
1392         case 1:
1393           switch (numberTimeSlots) {
1394             case 15:
1395               FDKmemcpy(pFrameInfo, &FDK_sbrDecoder_sbr_frame_info1_15,
1396                         sizeof(FRAME_INFO));
1397               break;
1398             case 16:
1399               FDKmemcpy(pFrameInfo, &FDK_sbrDecoder_sbr_frame_info1_16,
1400                         sizeof(FRAME_INFO));
1401               break;
1402             default:
1403               FDK_ASSERT(0);
1404           }
1405           break;
1406         case 2:
1407           switch (numberTimeSlots) {
1408             case 15:
1409               FDKmemcpy(pFrameInfo, &FDK_sbrDecoder_sbr_frame_info2_15,
1410                         sizeof(FRAME_INFO));
1411               break;
1412             case 16:
1413               FDKmemcpy(pFrameInfo, &FDK_sbrDecoder_sbr_frame_info2_16,
1414                         sizeof(FRAME_INFO));
1415               break;
1416             default:
1417               FDK_ASSERT(0);
1418           }
1419           break;
1420         case 4:
1421           switch (numberTimeSlots) {
1422             case 15:
1423               FDKmemcpy(pFrameInfo, &FDK_sbrDecoder_sbr_frame_info4_15,
1424                         sizeof(FRAME_INFO));
1425               break;
1426             case 16:
1427               FDKmemcpy(pFrameInfo, &FDK_sbrDecoder_sbr_frame_info4_16,
1428                         sizeof(FRAME_INFO));
1429               break;
1430             default:
1431               FDK_ASSERT(0);
1432           }
1433           break;
1434         case 8:
1435 #if (MAX_ENVELOPES >= 8)
1436           switch (numberTimeSlots) {
1437             case 15:
1438               FDKmemcpy(pFrameInfo, &FDK_sbrDecoder_sbr_frame_info8_15,
1439                         sizeof(FRAME_INFO));
1440               break;
1441             case 16:
1442               FDKmemcpy(pFrameInfo, &FDK_sbrDecoder_sbr_frame_info8_16,
1443                         sizeof(FRAME_INFO));
1444               break;
1445             default:
1446               FDK_ASSERT(0);
1447           }
1448           break;
1449 #else
1450           return 0;
1451 #endif
1452       }
1453       /* Apply correct freqRes (High is default) */
1454       if (!staticFreqRes) {
1455         for (i = 0; i < nEnv; i++) pFrameInfo->freqRes[i] = 0;
1456       }
1457 
1458       break;
1459     case 1:
1460     case 2:
1461       temp = FDKreadBits(hBs, 2); /* A [2 bits] */
1462 
1463       n = FDKreadBits(hBs, 2); /* n = N [2 bits] */
1464 
1465       nEnv = n + 1; /* # envelopes */
1466       b = nEnv + 1; /* # borders   */
1467 
1468       break;
1469   }
1470 
1471   switch (frameClass) {
1472     case 1:
1473       /* Decode borders: */
1474       pFrameInfo->borders[0] = 0;      /* first border          */
1475       border = temp + numberTimeSlots; /* A -> aR               */
1476       i = b - 1;                       /* frame info index for last border */
1477       pFrameInfo->borders[i] = border; /* last border                      */
1478 
1479       for (k = 0; k < n; k++) {
1480         temp = FDKreadBits(hBs, 2); /* R [2 bits] */
1481         border -= (2 * temp + 2);   /* R -> r                */
1482         pFrameInfo->borders[--i] = border;
1483       }
1484 
1485       /* Decode pointer: */
1486       pointer_bits = DFRACT_BITS - 1 - CountLeadingBits((FIXP_DBL)(n + 1));
1487       p = FDKreadBits(hBs, pointer_bits); /* p = P [pointer_bits bits] */
1488 
1489       if (p > n + 1) return 0;
1490 
1491       pFrameInfo->tranEnv = p ? n + 2 - p : -1;
1492 
1493       /* Decode freq res: */
1494       for (k = n; k >= 0; k--) {
1495         pFrameInfo->freqRes[k] = FDKreadBits(hBs, 1); /* f = F [1 bits] */
1496       }
1497 
1498       /* Calculate noise floor middle border: */
1499       if (p == 0 || p == 1)
1500         pFrameInfo->bordersNoise[1] = pFrameInfo->borders[n];
1501       else
1502         pFrameInfo->bordersNoise[1] = pFrameInfo->borders[pFrameInfo->tranEnv];
1503 
1504       break;
1505 
1506     case 2:
1507       /* Decode borders: */
1508       border = temp;                   /* A -> aL */
1509       pFrameInfo->borders[0] = border; /* first border */
1510 
1511       for (k = 1; k <= n; k++) {
1512         temp = FDKreadBits(hBs, 2); /* R [2 bits] */
1513         border += (2 * temp + 2);   /* R -> r                */
1514         pFrameInfo->borders[k] = border;
1515       }
1516       pFrameInfo->borders[k] = numberTimeSlots; /* last border */
1517 
1518       /* Decode pointer: */
1519       pointer_bits = DFRACT_BITS - 1 - CountLeadingBits((FIXP_DBL)(n + 1));
1520       p = FDKreadBits(hBs, pointer_bits); /* p = P [pointer_bits bits] */
1521       if (p > n + 1) return 0;
1522 
1523       if (p == 0 || p == 1)
1524         pFrameInfo->tranEnv = -1;
1525       else
1526         pFrameInfo->tranEnv = p - 1;
1527 
1528       /* Decode freq res: */
1529       for (k = 0; k <= n; k++) {
1530         pFrameInfo->freqRes[k] = FDKreadBits(hBs, 1); /* f = F [1 bits] */
1531       }
1532 
1533       /* Calculate noise floor middle border: */
1534       switch (p) {
1535         case 0:
1536           pFrameInfo->bordersNoise[1] = pFrameInfo->borders[1];
1537           break;
1538         case 1:
1539           pFrameInfo->bordersNoise[1] = pFrameInfo->borders[n];
1540           break;
1541         default:
1542           pFrameInfo->bordersNoise[1] =
1543               pFrameInfo->borders[pFrameInfo->tranEnv];
1544           break;
1545       }
1546 
1547       break;
1548 
1549     case 3:
1550       /* v_ctrlSignal = [frameClass,aL,aR,nL,nR,v_rL,v_rR,p,v_fLR]; */
1551 
1552       aL = FDKreadBits(hBs, 2); /* AL [2 bits], AL -> aL */
1553 
1554       aR = FDKreadBits(hBs, 2) + numberTimeSlots; /* AR [2 bits], AR -> aR */
1555 
1556       nL = FDKreadBits(hBs, 2); /* nL = NL [2 bits] */
1557 
1558       nR = FDKreadBits(hBs, 2); /* nR = NR [2 bits] */
1559 
1560       /*-------------------------------------------------------------------------
1561         Calculate help variables
1562         --------------------------------------------------------------------------*/
1563 
1564       /* general: */
1565       nEnv = nL + nR + 1; /* # envelopes */
1566       if (nEnv > MAX_ENVELOPES) return 0;
1567       b = nEnv + 1; /* # borders   */
1568 
1569       /*-------------------------------------------------------------------------
1570         Decode envelopes
1571         --------------------------------------------------------------------------*/
1572 
1573       /* L-borders:   */
1574       border = aL; /* first border */
1575       pFrameInfo->borders[0] = border;
1576 
1577       for (k = 1; k <= nL; k++) {
1578         temp = FDKreadBits(hBs, 2); /* R [2 bits] */
1579         border += (2 * temp + 2);   /* R -> r                */
1580         pFrameInfo->borders[k] = border;
1581       }
1582 
1583       /* R-borders:  */
1584       border = aR; /* last border */
1585       i = nEnv;
1586 
1587       pFrameInfo->borders[i] = border;
1588 
1589       for (k = 0; k < nR; k++) {
1590         temp = FDKreadBits(hBs, 2); /* R [2 bits] */
1591         border -= (2 * temp + 2);   /* R -> r                */
1592         pFrameInfo->borders[--i] = border;
1593       }
1594 
1595       /* decode pointer: */
1596       pointer_bits =
1597           DFRACT_BITS - 1 - CountLeadingBits((FIXP_DBL)(nL + nR + 1));
1598       p = FDKreadBits(hBs, pointer_bits); /* p = P [pointer_bits bits] */
1599 
1600       if (p > nL + nR + 1) return 0;
1601 
1602       pFrameInfo->tranEnv = p ? b - p : -1;
1603 
1604       /* decode freq res: */
1605       for (k = 0; k < nEnv; k++) {
1606         pFrameInfo->freqRes[k] = FDKreadBits(hBs, 1); /* f = F [1 bits] */
1607       }
1608 
1609       /*-------------------------------------------------------------------------
1610         Decode noise floors
1611         --------------------------------------------------------------------------*/
1612       pFrameInfo->bordersNoise[0] = aL;
1613 
1614       if (nEnv == 1) {
1615         /* 1 noise floor envelope: */
1616         pFrameInfo->bordersNoise[1] = aR;
1617       } else {
1618         /* 2 noise floor envelopes */
1619         if (p == 0 || p == 1)
1620           pFrameInfo->bordersNoise[1] = pFrameInfo->borders[nEnv - 1];
1621         else
1622           pFrameInfo->bordersNoise[1] =
1623               pFrameInfo->borders[pFrameInfo->tranEnv];
1624         pFrameInfo->bordersNoise[2] = aR;
1625       }
1626       break;
1627   }
1628 
1629   /*
1630     Store number of envelopes, noise floor envelopes and frame class
1631   */
1632   pFrameInfo->nEnvelopes = nEnv;
1633 
1634   if (nEnv == 1)
1635     pFrameInfo->nNoiseEnvelopes = 1;
1636   else
1637     pFrameInfo->nNoiseEnvelopes = 2;
1638 
1639   pFrameInfo->frameClass = frameClass;
1640 
1641   if (pFrameInfo->frameClass == 2 || pFrameInfo->frameClass == 1) {
1642     /* calculate noise floor first and last borders: */
1643     pFrameInfo->bordersNoise[0] = pFrameInfo->borders[0];
1644     pFrameInfo->bordersNoise[pFrameInfo->nNoiseEnvelopes] =
1645         pFrameInfo->borders[nEnv];
1646   }
1647 
1648   return 1;
1649 }
1650 
1651 /*!
1652   \brief   Check if the frameInfo vector has reasonable values.
1653   \return  Zero for error, one for correct
1654 */
checkFrameInfo(FRAME_INFO * pFrameInfo,int numberOfTimeSlots,int overlap,int timeStep)1655 static int checkFrameInfo(
1656     FRAME_INFO *pFrameInfo, /*!< pointer to frameInfo */
1657     int numberOfTimeSlots,  /*!< QMF time slots per frame */
1658     int overlap,            /*!< Amount of overlap QMF time slots */
1659     int timeStep)           /*!< QMF slots to SBR slots step factor */
1660 {
1661   int maxPos, i, j;
1662   int startPos;
1663   int stopPos;
1664   int tranEnv;
1665   int startPosNoise;
1666   int stopPosNoise;
1667   int nEnvelopes = pFrameInfo->nEnvelopes;
1668   int nNoiseEnvelopes = pFrameInfo->nNoiseEnvelopes;
1669 
1670   if (nEnvelopes < 1 || nEnvelopes > MAX_ENVELOPES) return 0;
1671 
1672   if (nNoiseEnvelopes > MAX_NOISE_ENVELOPES) return 0;
1673 
1674   startPos = pFrameInfo->borders[0];
1675   stopPos = pFrameInfo->borders[nEnvelopes];
1676   tranEnv = pFrameInfo->tranEnv;
1677   startPosNoise = pFrameInfo->bordersNoise[0];
1678   stopPosNoise = pFrameInfo->bordersNoise[nNoiseEnvelopes];
1679 
1680   if (overlap < 0 || overlap > (3 * (4))) {
1681     return 0;
1682   }
1683   if (timeStep < 1 || timeStep > (4)) {
1684     return 0;
1685   }
1686   maxPos = numberOfTimeSlots + (overlap / timeStep);
1687 
1688   /* Check that the start and stop positions of the frame are reasonable values.
1689    */
1690   if ((startPos < 0) || (startPos >= stopPos)) return 0;
1691   if (startPos > maxPos - numberOfTimeSlots) /* First env. must start in or
1692                                                 directly after the overlap
1693                                                 buffer */
1694     return 0;
1695   if (stopPos < numberOfTimeSlots) /* One complete frame must be ready for
1696                                       output after processing */
1697     return 0;
1698   if (stopPos > maxPos) return 0;
1699 
1700   /* Check that the  start border for every envelope is strictly later in time
1701    */
1702   for (i = 0; i < nEnvelopes; i++) {
1703     if (pFrameInfo->borders[i] >= pFrameInfo->borders[i + 1]) return 0;
1704   }
1705 
1706   /* Check that the envelope to be shortened is actually among the envelopes */
1707   if (tranEnv > nEnvelopes) return 0;
1708 
1709   /* Check the noise borders */
1710   if (nEnvelopes == 1 && nNoiseEnvelopes > 1) return 0;
1711 
1712   if (startPos != startPosNoise || stopPos != stopPosNoise) return 0;
1713 
1714   /* Check that the  start border for every noise-envelope is strictly later in
1715    * time*/
1716   for (i = 0; i < nNoiseEnvelopes; i++) {
1717     if (pFrameInfo->bordersNoise[i] >= pFrameInfo->bordersNoise[i + 1])
1718       return 0;
1719   }
1720 
1721   /* Check that every noise border is the same as an envelope border*/
1722   for (i = 0; i < nNoiseEnvelopes; i++) {
1723     startPosNoise = pFrameInfo->bordersNoise[i];
1724 
1725     for (j = 0; j < nEnvelopes; j++) {
1726       if (pFrameInfo->borders[j] == startPosNoise) break;
1727     }
1728     if (j == nEnvelopes) return 0;
1729   }
1730 
1731   return 1;
1732 }
1733