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