Coverage Report

Created: 2025-08-29 06:06

/src/aac/libSBRdec/src/env_extr.cpp
Line
Count
Source (jump to first uncovered line)
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
0
#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
217
UINT sbrdec_mapToStdSampleRate(UINT fs,
218
                               UINT isUsac) /*!< Output sampling frequency */
219
0
{
220
0
  UINT fsMapped = fs, tableSize = 0;
221
0
  const SR_MAPPING *mappingTable;
222
0
  int i;
223
224
0
  if (!isUsac) {
225
0
    mappingTable = stdSampleRatesMapping;
226
0
    tableSize = sizeof(stdSampleRatesMapping) / sizeof(SR_MAPPING);
227
0
  } else {
228
0
    mappingTable = stdSampleRatesMappingUsac;
229
0
    tableSize = sizeof(stdSampleRatesMappingUsac) / sizeof(SR_MAPPING);
230
0
  }
231
232
0
  for (i = tableSize - 1; i >= 0; i--) {
233
0
    if (fs >= mappingTable[i].fsRangeLo) {
234
0
      fsMapped = mappingTable[i].fsMapped;
235
0
      break;
236
0
    }
237
0
  }
238
239
0
  return (fsMapped);
240
0
}
241
242
SBR_ERROR
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
0
               const int setDefaultHdr) {
247
0
  HANDLE_FREQ_BAND_DATA hFreq = &hHeaderData->freqBandData;
248
0
  SBR_ERROR sbrError = SBRDEC_OK;
249
0
  int numAnalysisBands;
250
0
  int sampleRateProc;
251
252
0
  if (!(flags & (SBRDEC_SYNTAX_USAC | SBRDEC_SYNTAX_RSVD50))) {
253
0
    sampleRateProc =
254
0
        sbrdec_mapToStdSampleRate(sampleRateOut * downscaleFactor, 0);
255
0
  } else {
256
0
    sampleRateProc = sampleRateOut * downscaleFactor;
257
0
  }
258
259
0
  if (sampleRateIn == sampleRateOut) {
260
0
    hHeaderData->sbrProcSmplRate = sampleRateProc << 1;
261
0
    numAnalysisBands = 32;
262
0
  } else {
263
0
    hHeaderData->sbrProcSmplRate = sampleRateProc;
264
0
    if ((sampleRateOut >> 1) == sampleRateIn) {
265
      /* 1:2 */
266
0
      numAnalysisBands = 32;
267
0
    } else if ((sampleRateOut >> 2) == sampleRateIn) {
268
      /* 1:4 */
269
0
      numAnalysisBands = 16;
270
0
    } else if ((sampleRateOut * 3) >> 3 == (sampleRateIn * 8) >> 3) {
271
      /* 3:8, 3/4 core frame length */
272
0
      numAnalysisBands = 24;
273
0
    } else {
274
0
      sbrError = SBRDEC_UNSUPPORTED_CONFIG;
275
0
      goto bail;
276
0
    }
277
0
  }
278
0
  numAnalysisBands /= downscaleFactor;
279
280
0
  if (setDefaultHdr) {
281
    /* Fill in default values first */
282
0
    hHeaderData->syncState = SBR_NOT_INITIALIZED;
283
0
    hHeaderData->status = 0;
284
0
    hHeaderData->frameErrorFlag = 0;
285
286
0
    hHeaderData->bs_info.ampResolution = 1;
287
0
    hHeaderData->bs_info.xover_band = 0;
288
0
    hHeaderData->bs_info.sbr_preprocessing = 0;
289
0
    hHeaderData->bs_info.pvc_mode = 0;
290
291
0
    hHeaderData->bs_data.startFreq = 5;
292
0
    hHeaderData->bs_data.stopFreq = 0;
293
0
    hHeaderData->bs_data.freqScale =
294
0
        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
0
    hHeaderData->bs_data.alterScale = 1;
300
0
    hHeaderData->bs_data.noise_bands = 2;
301
0
    hHeaderData->bs_data.limiterBands = 2;
302
0
    hHeaderData->bs_data.limiterGains = 2;
303
0
    hHeaderData->bs_data.interpolFreq = 1;
304
0
    hHeaderData->bs_data.smoothingLength = 1;
305
306
    /* Patch some entries */
307
0
    if (sampleRateOut * downscaleFactor >= 96000) {
308
0
      hHeaderData->bs_data.startFreq =
309
0
          4; /*   having read these frequency values from bit stream before. */
310
0
      hHeaderData->bs_data.stopFreq = 3;
311
0
    } else if (sampleRateOut * downscaleFactor >
312
0
               24000) { /* Trigger an error if SBR is going to be processed
313
                           without     */
314
0
      hHeaderData->bs_data.startFreq =
315
0
          7; /*   having read these frequency values from bit stream before. */
316
0
      hHeaderData->bs_data.stopFreq = 3;
317
0
    }
318
0
  }
319
320
0
  if ((sampleRateOut >> 2) == sampleRateIn) {
321
0
    hHeaderData->timeStep = 4;
322
0
  } else {
323
0
    hHeaderData->timeStep = (flags & SBRDEC_ELD_GRID) ? 1 : 2;
324
0
  }
325
326
  /* Setup pointers to frequency band tables */
327
0
  hFreq->freqBandTable[0] = hFreq->freqBandTableLo;
328
0
  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
0
  hHeaderData->numberTimeSlots =
333
0
      (samplesPerFrame / numAnalysisBands) >> (hHeaderData->timeStep - 1);
334
0
  if (hHeaderData->numberTimeSlots > (16)) {
335
0
    sbrError = SBRDEC_UNSUPPORTED_CONFIG;
336
0
  }
337
338
0
  hHeaderData->numberOfAnalysisBands = numAnalysisBands;
339
0
  if ((sampleRateOut >> 2) == sampleRateIn) {
340
0
    hHeaderData->numberTimeSlots <<= 1;
341
0
  }
342
343
0
bail:
344
0
  return sbrError;
345
0
}
346
347
/*!
348
  \brief   Initialize the SBR_PREV_FRAME_DATA struct
349
*/
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
0
{
355
0
  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
0
  for (i = 0; i < MAX_FREQ_COEFFS; i++)
360
0
    h_prev_data->sfb_nrg_prev[i] = (FIXP_DBL)0;
361
0
  for (i = 0; i < MAX_NOISE_COEFFS; i++)
362
0
    h_prev_data->prevNoiseLevel[i] = (FIXP_DBL)0;
363
0
  for (i = 0; i < MAX_INVF_BANDS; i++) h_prev_data->sbr_invf_mode[i] = INVF_OFF;
364
365
0
  h_prev_data->stopPos = timeSlots;
366
0
  h_prev_data->coupling = COUPLING_OFF;
367
0
  h_prev_data->ampRes = 0;
368
369
0
  FDKmemclear(&h_prev_data->prevFrameInfo, sizeof(h_prev_data->prevFrameInfo));
370
0
}
371
372
/*!
373
  \brief   Read header data from bitstream
374
375
  \return  error status - 0 if ok
376
*/
377
SBR_HEADER_STATUS
378
sbrGetHeaderData(HANDLE_SBR_HEADER_DATA hHeaderData, HANDLE_FDK_BITSTREAM hBs,
379
                 const UINT flags, const int fIsSbrData,
380
0
                 const UCHAR configMode) {
381
0
  SBR_HEADER_DATA_BS *pBsData;
382
0
  SBR_HEADER_DATA_BS lastHeader;
383
0
  SBR_HEADER_DATA_BS_INFO lastInfo;
384
0
  int headerExtra1 = 0, headerExtra2 = 0;
385
386
  /* Read and discard new header in config change detection mode */
387
0
  if (configMode & AC_CM_DET_CFG_CHANGE) {
388
0
    if (!(flags & (SBRDEC_SYNTAX_RSVD50 | SBRDEC_SYNTAX_USAC))) {
389
      /* ampResolution */
390
0
      FDKreadBits(hBs, 1);
391
0
    }
392
    /* startFreq, stopFreq */
393
0
    FDKpushFor(hBs, 8);
394
0
    if (!(flags & (SBRDEC_SYNTAX_RSVD50 | SBRDEC_SYNTAX_USAC))) {
395
      /* xover_band */
396
0
      FDKreadBits(hBs, 3);
397
      /* reserved bits */
398
0
      FDKreadBits(hBs, 2);
399
0
    }
400
0
    headerExtra1 = FDKreadBit(hBs);
401
0
    headerExtra2 = FDKreadBit(hBs);
402
0
    FDKpushFor(hBs, 5 * headerExtra1 + 6 * headerExtra2);
403
404
0
    return HEADER_OK;
405
0
  }
406
407
  /* Copy SBR bit stream header to temporary header */
408
0
  lastHeader = hHeaderData->bs_data;
409
0
  lastInfo = hHeaderData->bs_info;
410
411
  /* Read new header from bitstream */
412
0
  if ((flags & (SBRDEC_SYNTAX_RSVD50 | SBRDEC_SYNTAX_USAC)) && !fIsSbrData) {
413
0
    pBsData = &hHeaderData->bs_dflt;
414
0
  } else {
415
0
    pBsData = &hHeaderData->bs_data;
416
0
  }
417
418
0
  if (!(flags & (SBRDEC_SYNTAX_RSVD50 | SBRDEC_SYNTAX_USAC))) {
419
0
    hHeaderData->bs_info.ampResolution = FDKreadBits(hBs, 1);
420
0
  }
421
422
0
  pBsData->startFreq = FDKreadBits(hBs, 4);
423
0
  pBsData->stopFreq = FDKreadBits(hBs, 4);
424
425
0
  if (!(flags & (SBRDEC_SYNTAX_RSVD50 | SBRDEC_SYNTAX_USAC))) {
426
0
    hHeaderData->bs_info.xover_band = FDKreadBits(hBs, 3);
427
0
    FDKreadBits(hBs, 2);
428
0
  }
429
430
0
  headerExtra1 = FDKreadBits(hBs, 1);
431
0
  headerExtra2 = FDKreadBits(hBs, 1);
432
433
  /* Handle extra header information */
434
0
  if (headerExtra1) {
435
0
    pBsData->freqScale = FDKreadBits(hBs, 2);
436
0
    pBsData->alterScale = FDKreadBits(hBs, 1);
437
0
    pBsData->noise_bands = FDKreadBits(hBs, 2);
438
0
  } else {
439
0
    pBsData->freqScale = 2;
440
0
    pBsData->alterScale = 1;
441
0
    pBsData->noise_bands = 2;
442
0
  }
443
444
0
  if (headerExtra2) {
445
0
    pBsData->limiterBands = FDKreadBits(hBs, 2);
446
0
    pBsData->limiterGains = FDKreadBits(hBs, 2);
447
0
    pBsData->interpolFreq = FDKreadBits(hBs, 1);
448
0
    pBsData->smoothingLength = FDKreadBits(hBs, 1);
449
0
  } else {
450
0
    pBsData->limiterBands = 2;
451
0
    pBsData->limiterGains = 2;
452
0
    pBsData->interpolFreq = 1;
453
0
    pBsData->smoothingLength = 1;
454
0
  }
455
456
  /* Look for new settings. IEC 14496-3, 4.6.18.3.1 */
457
0
  if (hHeaderData->syncState < SBR_HEADER ||
458
0
      lastHeader.startFreq != pBsData->startFreq ||
459
0
      lastHeader.stopFreq != pBsData->stopFreq ||
460
0
      lastHeader.freqScale != pBsData->freqScale ||
461
0
      lastHeader.alterScale != pBsData->alterScale ||
462
0
      lastHeader.noise_bands != pBsData->noise_bands ||
463
0
      lastInfo.xover_band != hHeaderData->bs_info.xover_band) {
464
0
    return HEADER_RESET; /* New settings */
465
0
  }
466
467
0
  return HEADER_OK;
468
0
}
469
470
/*!
471
  \brief   Get missing harmonics parameters (only used for AAC+SBR)
472
473
  \return  error status - 0 if ok
474
*/
475
int sbrGetSyntheticCodedData(HANDLE_SBR_HEADER_DATA hHeaderData,
476
                             HANDLE_SBR_FRAME_DATA hFrameData,
477
0
                             HANDLE_FDK_BITSTREAM hBs, const UINT flags) {
478
0
  int i, bitsRead = 0;
479
480
0
  int add_harmonic_flag = FDKreadBits(hBs, 1);
481
0
  bitsRead++;
482
483
0
  if (add_harmonic_flag) {
484
0
    int nSfb = hHeaderData->freqBandData.nSfb[1];
485
0
    for (i = 0; i < ADD_HARMONICS_FLAGS_SIZE; i++) {
486
      /* read maximum 32 bits and align them to the MSB */
487
0
      int readBits = fMin(32, nSfb);
488
0
      nSfb -= readBits;
489
0
      if (readBits > 0) {
490
0
        hFrameData->addHarmonics[i] = FDKreadBits(hBs, readBits)
491
0
                                      << (32 - readBits);
492
0
      } else {
493
0
        hFrameData->addHarmonics[i] = 0;
494
0
      }
495
496
0
      bitsRead += readBits;
497
0
    }
498
    /* bs_pvc_mode = 0 for Rsvd50 */
499
0
    if (flags & SBRDEC_SYNTAX_USAC) {
500
0
      if (hHeaderData->bs_info.pvc_mode) {
501
0
        int bs_sinusoidal_position = 31;
502
0
        if (FDKreadBit(hBs) /* bs_sinusoidal_position_flag */) {
503
0
          bs_sinusoidal_position = FDKreadBits(hBs, 5);
504
0
        }
505
0
        hFrameData->sinusoidal_position = bs_sinusoidal_position;
506
0
      }
507
0
    }
508
0
  } else {
509
0
    for (i = 0; i < ADD_HARMONICS_FLAGS_SIZE; i++)
510
0
      hFrameData->addHarmonics[i] = 0;
511
0
  }
512
513
0
  return (bitsRead);
514
0
}
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
*/
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
0
) {
531
0
  INT nBitsLeft;
532
0
  int extended_data;
533
0
  int i, frameOk = 1;
534
535
0
  extended_data = FDKreadBits(hBs, 1);
536
537
0
  if (extended_data) {
538
0
    int cnt;
539
0
    int bPsRead = 0;
540
541
0
    cnt = FDKreadBits(hBs, 4);
542
0
    if (cnt == (1 << 4) - 1) cnt += FDKreadBits(hBs, 8);
543
544
0
    nBitsLeft = 8 * cnt;
545
546
    /* sanity check for cnt */
547
0
    if (nBitsLeft > (INT)FDKgetValidBits(hBs)) {
548
      /* limit nBitsLeft */
549
0
      nBitsLeft = (INT)FDKgetValidBits(hBs);
550
      /* set frame error */
551
0
      frameOk = 0;
552
0
    }
553
554
0
    while (nBitsLeft > 7) {
555
0
      int extension_id = FDKreadBits(hBs, 2);
556
0
      nBitsLeft -= 2;
557
558
0
      switch (extension_id) {
559
0
        case EXTENSION_ID_PS_CODING:
560
561
          /* Read PS data from bitstream */
562
563
0
          if (hParametricStereoDec != NULL) {
564
0
            if (bPsRead &&
565
0
                !hParametricStereoDec->bsData[hParametricStereoDec->bsReadSlot]
566
0
                     .mpeg.bPsHeaderValid) {
567
0
              cnt = nBitsLeft >> 3; /* number of remaining bytes */
568
0
              for (i = 0; i < cnt; i++) FDKreadBits(hBs, 8);
569
0
              nBitsLeft -= cnt * 8;
570
0
            } else {
571
0
              nBitsLeft -=
572
0
                  (INT)ReadPsData(hParametricStereoDec, hBs, nBitsLeft);
573
0
              bPsRead = 1;
574
0
            }
575
0
          }
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
0
          break;
591
592
0
        default:
593
0
          cnt = nBitsLeft >> 3; /* number of remaining bytes */
594
0
          for (i = 0; i < cnt; i++) FDKreadBits(hBs, 8);
595
0
          nBitsLeft -= cnt * 8;
596
0
          break;
597
0
      }
598
0
    }
599
600
0
    if (nBitsLeft < 0) {
601
0
      frameOk = 0;
602
0
      goto bail;
603
0
    } else {
604
      /* Read fill bits for byte alignment */
605
0
      FDKreadBits(hBs, nBitsLeft);
606
0
    }
607
0
  }
608
609
0
bail:
610
0
  return (frameOk);
611
0
}
612
613
/*!
614
  \brief      Read bitstream elements of a SBR channel element
615
  \return     SbrFrameOK
616
*/
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
0
                         const int overlap) {
624
0
  int i, bs_coupling = COUPLING_OFF;
625
0
  const int nCh = (hFrameDataRight == NULL) ? 1 : 2;
626
627
0
  if (!(flags & (SBRDEC_SYNTAX_USAC | SBRDEC_SYNTAX_RSVD50))) {
628
    /* Reserved bits */
629
0
    if (FDKreadBits(hBs, 1)) { /* bs_data_extra */
630
0
      FDKreadBits(hBs, 4);
631
0
      if ((flags & SBRDEC_SYNTAX_SCAL) || (nCh == 2)) {
632
0
        FDKreadBits(hBs, 4);
633
0
      }
634
0
    }
635
0
  }
636
637
0
  if (nCh == 2) {
638
    /* Read coupling flag */
639
0
    bs_coupling = FDKreadBits(hBs, 1);
640
0
    if (bs_coupling) {
641
0
      hFrameDataLeft->coupling = COUPLING_LEVEL;
642
0
      hFrameDataRight->coupling = COUPLING_BAL;
643
0
    } else {
644
0
      hFrameDataLeft->coupling = COUPLING_OFF;
645
0
      hFrameDataRight->coupling = COUPLING_OFF;
646
0
    }
647
0
  } else {
648
0
    if (flags & SBRDEC_SYNTAX_SCAL) {
649
0
      FDKreadBits(hBs, 1); /* bs_coupling */
650
0
    }
651
0
    hFrameDataLeft->coupling = COUPLING_OFF;
652
0
  }
653
654
0
  if (flags & (SBRDEC_SYNTAX_USAC | SBRDEC_SYNTAX_RSVD50)) {
655
0
    if (flags & SBRDEC_USAC_HARMONICSBR) {
656
0
      hFrameDataLeft->sbrPatchingMode = FDKreadBit(hBs);
657
0
      if (hFrameDataLeft->sbrPatchingMode == 0) {
658
0
        hFrameDataLeft->sbrOversamplingFlag = FDKreadBit(hBs);
659
0
        if (FDKreadBit(hBs)) { /* sbrPitchInBinsFlag */
660
0
          hFrameDataLeft->sbrPitchInBins = FDKreadBits(hBs, 7);
661
0
        } else {
662
0
          hFrameDataLeft->sbrPitchInBins = 0;
663
0
        }
664
0
      } else {
665
0
        hFrameDataLeft->sbrOversamplingFlag = 0;
666
0
        hFrameDataLeft->sbrPitchInBins = 0;
667
0
      }
668
669
0
      if (nCh == 2) {
670
0
        if (bs_coupling) {
671
0
          hFrameDataRight->sbrPatchingMode = hFrameDataLeft->sbrPatchingMode;
672
0
          hFrameDataRight->sbrOversamplingFlag =
673
0
              hFrameDataLeft->sbrOversamplingFlag;
674
0
          hFrameDataRight->sbrPitchInBins = hFrameDataLeft->sbrPitchInBins;
675
0
        } else {
676
0
          hFrameDataRight->sbrPatchingMode = FDKreadBit(hBs);
677
0
          if (hFrameDataRight->sbrPatchingMode == 0) {
678
0
            hFrameDataRight->sbrOversamplingFlag = FDKreadBit(hBs);
679
0
            if (FDKreadBit(hBs)) { /* sbrPitchInBinsFlag */
680
0
              hFrameDataRight->sbrPitchInBins = FDKreadBits(hBs, 7);
681
0
            } else {
682
0
              hFrameDataRight->sbrPitchInBins = 0;
683
0
            }
684
0
          } else {
685
0
            hFrameDataRight->sbrOversamplingFlag = 0;
686
0
            hFrameDataRight->sbrPitchInBins = 0;
687
0
          }
688
0
        }
689
0
      }
690
0
    } else {
691
0
      if (nCh == 2) {
692
0
        hFrameDataRight->sbrPatchingMode = 1;
693
0
        hFrameDataRight->sbrOversamplingFlag = 0;
694
0
        hFrameDataRight->sbrPitchInBins = 0;
695
0
      }
696
697
0
      hFrameDataLeft->sbrPatchingMode = 1;
698
0
      hFrameDataLeft->sbrOversamplingFlag = 0;
699
0
      hFrameDataLeft->sbrPitchInBins = 0;
700
0
    }
701
0
  } else {
702
0
    if (nCh == 2) {
703
0
      hFrameDataRight->sbrPatchingMode = 1;
704
0
      hFrameDataRight->sbrOversamplingFlag = 0;
705
0
      hFrameDataRight->sbrPitchInBins = 0;
706
0
    }
707
708
0
    hFrameDataLeft->sbrPatchingMode = 1;
709
0
    hFrameDataLeft->sbrOversamplingFlag = 0;
710
0
    hFrameDataLeft->sbrPitchInBins = 0;
711
0
  }
712
713
  /*
714
    sbr_grid(): Grid control
715
  */
716
0
  if (hHeaderData->bs_info.pvc_mode) {
717
0
    FDK_ASSERT(nCh == 1); /* PVC not possible for CPE */
718
0
    if (!extractPvcFrameInfo(hBs, hHeaderData, hFrameDataLeft,
719
0
                             hFrameDataLeftPrev, pvc_mode_last, flags))
720
0
      return 0;
721
722
0
    if (!checkFrameInfo(&hFrameDataLeft->frameInfo,
723
0
                        hHeaderData->numberTimeSlots, overlap,
724
0
                        hHeaderData->timeStep))
725
0
      return 0;
726
0
  } else {
727
0
    if (!extractFrameInfo(hBs, hHeaderData, hFrameDataLeft, 1, flags)) return 0;
728
729
0
    if (!checkFrameInfo(&hFrameDataLeft->frameInfo,
730
0
                        hHeaderData->numberTimeSlots, overlap,
731
0
                        hHeaderData->timeStep))
732
0
      return 0;
733
0
  }
734
0
  if (nCh == 2) {
735
0
    if (hFrameDataLeft->coupling) {
736
0
      FDKmemcpy(&hFrameDataRight->frameInfo, &hFrameDataLeft->frameInfo,
737
0
                sizeof(FRAME_INFO));
738
0
      hFrameDataRight->ampResolutionCurrentFrame =
739
0
          hFrameDataLeft->ampResolutionCurrentFrame;
740
0
    } else {
741
0
      if (!extractFrameInfo(hBs, hHeaderData, hFrameDataRight, 2, flags))
742
0
        return 0;
743
744
0
      if (!checkFrameInfo(&hFrameDataRight->frameInfo,
745
0
                          hHeaderData->numberTimeSlots, overlap,
746
0
                          hHeaderData->timeStep))
747
0
        return 0;
748
0
    }
749
0
  }
750
751
  /*
752
    sbr_dtdf(): Fetch domain vectors (time or frequency direction for
753
    delta-coding)
754
  */
755
0
  sbrGetDirectionControlData(hFrameDataLeft, hBs, flags,
756
0
                             hHeaderData->bs_info.pvc_mode);
757
0
  if (nCh == 2) {
758
0
    sbrGetDirectionControlData(hFrameDataRight, hBs, flags, 0);
759
0
  }
760
761
  /* sbr_invf() */
762
0
  for (i = 0; i < hHeaderData->freqBandData.nInvfBands; i++) {
763
0
    hFrameDataLeft->sbr_invf_mode[i] = (INVF_MODE)FDKreadBits(hBs, 2);
764
0
  }
765
0
  if (nCh == 2) {
766
0
    if (hFrameDataLeft->coupling) {
767
0
      for (i = 0; i < hHeaderData->freqBandData.nInvfBands; i++) {
768
0
        hFrameDataRight->sbr_invf_mode[i] = hFrameDataLeft->sbr_invf_mode[i];
769
0
      }
770
0
    } else {
771
0
      for (i = 0; i < hHeaderData->freqBandData.nInvfBands; i++) {
772
0
        hFrameDataRight->sbr_invf_mode[i] = (INVF_MODE)FDKreadBits(hBs, 2);
773
0
      }
774
0
    }
775
0
  }
776
777
0
  if (nCh == 1) {
778
0
    if (hHeaderData->bs_info.pvc_mode) {
779
0
      if (!sbrGetPvcEnvelope(hHeaderData, hFrameDataLeft, hBs, flags,
780
0
                             hHeaderData->bs_info.pvc_mode))
781
0
        return 0;
782
0
    } else if (!sbrGetEnvelope(hHeaderData, hFrameDataLeft, hBs, flags))
783
0
      return 0;
784
785
0
    sbrGetNoiseFloorData(hHeaderData, hFrameDataLeft, hBs);
786
0
  } else if (hFrameDataLeft->coupling) {
787
0
    if (!sbrGetEnvelope(hHeaderData, hFrameDataLeft, hBs, flags)) {
788
0
      return 0;
789
0
    }
790
791
0
    sbrGetNoiseFloorData(hHeaderData, hFrameDataLeft, hBs);
792
793
0
    if (!sbrGetEnvelope(hHeaderData, hFrameDataRight, hBs, flags)) {
794
0
      return 0;
795
0
    }
796
0
    sbrGetNoiseFloorData(hHeaderData, hFrameDataRight, hBs);
797
0
  } else { /* nCh == 2 && no coupling */
798
799
0
    if (!sbrGetEnvelope(hHeaderData, hFrameDataLeft, hBs, flags)) return 0;
800
801
0
    if (!sbrGetEnvelope(hHeaderData, hFrameDataRight, hBs, flags)) return 0;
802
803
0
    sbrGetNoiseFloorData(hHeaderData, hFrameDataLeft, hBs);
804
805
0
    sbrGetNoiseFloorData(hHeaderData, hFrameDataRight, hBs);
806
0
  }
807
808
0
  sbrGetSyntheticCodedData(hHeaderData, hFrameDataLeft, hBs, flags);
809
0
  if (nCh == 2) {
810
0
    sbrGetSyntheticCodedData(hHeaderData, hFrameDataRight, hBs, flags);
811
0
  }
812
813
0
  if (!(flags & (SBRDEC_SYNTAX_USAC | SBRDEC_SYNTAX_RSVD50))) {
814
0
    if (!extractExtendedData(hHeaderData, hBs, hParametricStereoDec)) {
815
0
      return 0;
816
0
    }
817
0
  }
818
819
0
  return 1;
820
0
}
821
822
/*!
823
  \brief   Read direction control data from bitstream
824
*/
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
0
{
831
0
  int i;
832
0
  int indepFlag = 0;
833
834
0
  if (flags & (SBRDEC_SYNTAX_USAC | SBRDEC_SYNTAX_RSVD50)) {
835
0
    indepFlag = flags & SBRDEC_USAC_INDEP;
836
0
  }
837
838
0
  if (bs_pvc_mode == 0) {
839
0
    i = 0;
840
0
    if (indepFlag) {
841
0
      h_frame_data->domain_vec[i++] = 0;
842
0
    }
843
0
    for (; i < h_frame_data->frameInfo.nEnvelopes; i++) {
844
0
      h_frame_data->domain_vec[i] = FDKreadBits(hBs, 1);
845
0
    }
846
0
  }
847
848
0
  i = 0;
849
0
  if (indepFlag) {
850
0
    h_frame_data->domain_vec_noise[i++] = 0;
851
0
  }
852
0
  for (; i < h_frame_data->frameInfo.nNoiseEnvelopes; i++) {
853
0
    h_frame_data->domain_vec_noise[i] = FDKreadBits(hBs, 1);
854
0
  }
855
0
}
856
857
/*!
858
  \brief   Read noise-floor-level data from bitstream
859
*/
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
0
{
865
0
  int i, j;
866
0
  int delta;
867
0
  COUPLING_MODE coupling;
868
0
  int noNoiseBands = hHeaderData->freqBandData.nNfb;
869
870
0
  Huffman hcb_noiseF;
871
0
  Huffman hcb_noise;
872
0
  int envDataTableCompFactor;
873
874
0
  coupling = h_frame_data->coupling;
875
876
  /*
877
    Select huffman codebook depending on coupling mode
878
  */
879
0
  if (coupling == COUPLING_BAL) {
880
0
    hcb_noise = (Huffman)&FDK_sbrDecoder_sbr_huffBook_NoiseBalance11T;
881
0
    hcb_noiseF =
882
0
        (Huffman)&FDK_sbrDecoder_sbr_huffBook_EnvBalance11F; /* "sbr_huffBook_NoiseBalance11F"
883
                                                              */
884
0
    envDataTableCompFactor = 1;
885
0
  } else {
886
0
    hcb_noise = (Huffman)&FDK_sbrDecoder_sbr_huffBook_NoiseLevel11T;
887
0
    hcb_noiseF =
888
0
        (Huffman)&FDK_sbrDecoder_sbr_huffBook_EnvLevel11F; /* "sbr_huffBook_NoiseLevel11F"
889
                                                            */
890
0
    envDataTableCompFactor = 0;
891
0
  }
892
893
  /*
894
    Read raw noise-envelope data
895
  */
896
0
  for (i = 0; i < h_frame_data->frameInfo.nNoiseEnvelopes; i++) {
897
0
    if (h_frame_data->domain_vec_noise[i] == 0) {
898
0
      if (coupling == COUPLING_BAL) {
899
0
        h_frame_data->sbrNoiseFloorLevel[i * noNoiseBands] =
900
0
            (FIXP_SGL)(((int)FDKreadBits(hBs, 5)) << envDataTableCompFactor);
901
0
      } else {
902
0
        h_frame_data->sbrNoiseFloorLevel[i * noNoiseBands] =
903
0
            (FIXP_SGL)(int)FDKreadBits(hBs, 5);
904
0
      }
905
906
0
      for (j = 1; j < noNoiseBands; j++) {
907
0
        delta = DecodeHuffmanCW(hcb_noiseF, hBs);
908
0
        h_frame_data->sbrNoiseFloorLevel[i * noNoiseBands + j] =
909
0
            (FIXP_SGL)(delta << envDataTableCompFactor);
910
0
      }
911
0
    } else {
912
0
      for (j = 0; j < noNoiseBands; j++) {
913
0
        delta = DecodeHuffmanCW(hcb_noise, hBs);
914
0
        h_frame_data->sbrNoiseFloorLevel[i * noNoiseBands + j] =
915
0
            (FIXP_SGL)(delta << envDataTableCompFactor);
916
0
      }
917
0
    }
918
0
  }
919
0
}
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
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
0
    const UINT flags, const UINT pvcMode) {
932
0
  int divMode, nsMode;
933
0
  int indepFlag = flags & SBRDEC_USAC_INDEP;
934
0
  UCHAR *pvcID = h_frame_data->pvcID;
935
936
0
  divMode = FDKreadBits(hBs, PVC_DIVMODE_BITS);
937
0
  nsMode = FDKreadBit(hBs);
938
0
  FDK_ASSERT((pvcMode == 1) || (pvcMode == 2));
939
0
  h_frame_data->ns = mapNsMode2ns[pvcMode - 1][nsMode];
940
941
0
  if (divMode <= 3) {
942
0
    int i, k = 1, sum_length = 0, reuse_pcvID;
943
944
    /* special treatment for first time slot k=0 */
945
0
    indepFlag ? (reuse_pcvID = 0) : (reuse_pcvID = FDKreadBit(hBs));
946
0
    if (reuse_pcvID) {
947
0
      pvcID[0] = hHeaderData->pvcIDprev;
948
0
    } else {
949
0
      pvcID[0] = FDKreadBits(hBs, PVC_PVCID_BITS);
950
0
    }
951
952
    /* other time slots k>0 */
953
0
    for (i = 0; i < divMode; i++) {
954
0
      int length, numBits = 4;
955
956
0
      if (sum_length >= 13) {
957
0
        numBits = 1;
958
0
      } else if (sum_length >= 11) {
959
0
        numBits = 2;
960
0
      } else if (sum_length >= 7) {
961
0
        numBits = 3;
962
0
      }
963
964
0
      length = FDKreadBits(hBs, numBits);
965
0
      sum_length += length + 1;
966
0
      if (sum_length >= PVC_NTIMESLOT) {
967
0
        return 0; /* parse error */
968
0
      }
969
0
      for (; length--; k++) {
970
0
        pvcID[k] = pvcID[k - 1];
971
0
      }
972
0
      pvcID[k++] = FDKreadBits(hBs, PVC_PVCID_BITS);
973
0
    }
974
0
    for (; k < 16; k++) {
975
0
      pvcID[k] = pvcID[k - 1];
976
0
    }
977
0
  } else { /* divMode >= 4 */
978
0
    int num_grid_info, fixed_length, grid_info, j, k = 0;
979
980
0
    divMode -= 4;
981
0
    num_grid_info = 2 << divMode;
982
0
    fixed_length = 8 >> divMode;
983
0
    FDK_ASSERT(num_grid_info * fixed_length == PVC_NTIMESLOT);
984
985
    /* special treatment for first time slot k=0 */
986
0
    indepFlag ? (grid_info = 1) : (grid_info = FDKreadBit(hBs));
987
0
    if (grid_info) {
988
0
      pvcID[k++] = FDKreadBits(hBs, PVC_PVCID_BITS);
989
0
    } else {
990
0
      pvcID[k++] = hHeaderData->pvcIDprev;
991
0
    }
992
0
    j = fixed_length - 1;
993
0
    for (; j--; k++) {
994
0
      pvcID[k] = pvcID[k - 1];
995
0
    }
996
0
    num_grid_info--;
997
998
    /* other time slots k>0 */
999
0
    for (; num_grid_info--;) {
1000
0
      j = fixed_length;
1001
0
      grid_info = FDKreadBit(hBs);
1002
0
      if (grid_info) {
1003
0
        pvcID[k++] = FDKreadBits(hBs, PVC_PVCID_BITS);
1004
0
        j--;
1005
0
      }
1006
0
      for (; j--; k++) {
1007
0
        pvcID[k] = pvcID[k - 1];
1008
0
      }
1009
0
    }
1010
0
  }
1011
1012
0
  hHeaderData->pvcIDprev = pvcID[PVC_NTIMESLOT - 1];
1013
1014
  /* usage of PVC excludes inter-TES tool */
1015
0
  h_frame_data->iTESactive = (UCHAR)0;
1016
1017
0
  return 1;
1018
0
}
1019
/*!
1020
  \brief   Read envelope data from bitstream
1021
*/
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
0
    const UINT flags) {
1027
0
  int i, j;
1028
0
  UCHAR no_band[MAX_ENVELOPES];
1029
0
  int delta = 0;
1030
0
  int offset = 0;
1031
0
  COUPLING_MODE coupling = h_frame_data->coupling;
1032
0
  int ampRes = hHeaderData->bs_info.ampResolution;
1033
0
  int nEnvelopes = h_frame_data->frameInfo.nEnvelopes;
1034
0
  int envDataTableCompFactor;
1035
0
  int start_bits, start_bits_balance;
1036
0
  Huffman hcb_t, hcb_f;
1037
1038
0
  h_frame_data->nScaleFactors = 0;
1039
1040
0
  if ((h_frame_data->frameInfo.frameClass == 0) && (nEnvelopes == 1)) {
1041
0
    if (flags & SBRDEC_ELD_GRID)
1042
0
      ampRes = h_frame_data->ampResolutionCurrentFrame;
1043
0
    else
1044
0
      ampRes = 0;
1045
0
  }
1046
0
  h_frame_data->ampResolutionCurrentFrame = ampRes;
1047
1048
  /*
1049
    Set number of bits for first value depending on amplitude resolution
1050
  */
1051
0
  if (ampRes == 1) {
1052
0
    start_bits = 6;
1053
0
    start_bits_balance = 5;
1054
0
  } else {
1055
0
    start_bits = 7;
1056
0
    start_bits_balance = 6;
1057
0
  }
1058
1059
  /*
1060
    Calculate number of values for each envelope and alltogether
1061
  */
1062
0
  for (i = 0; i < nEnvelopes; i++) {
1063
0
    no_band[i] =
1064
0
        hHeaderData->freqBandData.nSfb[h_frame_data->frameInfo.freqRes[i]];
1065
0
    h_frame_data->nScaleFactors += no_band[i];
1066
0
  }
1067
0
  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
0
  if (coupling == COUPLING_BAL) {
1073
0
    envDataTableCompFactor = 1;
1074
0
    if (ampRes == 0) {
1075
0
      hcb_t = (Huffman)&FDK_sbrDecoder_sbr_huffBook_EnvBalance10T;
1076
0
      hcb_f = (Huffman)&FDK_sbrDecoder_sbr_huffBook_EnvBalance10F;
1077
0
    } else {
1078
0
      hcb_t = (Huffman)&FDK_sbrDecoder_sbr_huffBook_EnvBalance11T;
1079
0
      hcb_f = (Huffman)&FDK_sbrDecoder_sbr_huffBook_EnvBalance11F;
1080
0
    }
1081
0
  } else {
1082
0
    envDataTableCompFactor = 0;
1083
0
    if (ampRes == 0) {
1084
0
      hcb_t = (Huffman)&FDK_sbrDecoder_sbr_huffBook_EnvLevel10T;
1085
0
      hcb_f = (Huffman)&FDK_sbrDecoder_sbr_huffBook_EnvLevel10F;
1086
0
    } else {
1087
0
      hcb_t = (Huffman)&FDK_sbrDecoder_sbr_huffBook_EnvLevel11T;
1088
0
      hcb_f = (Huffman)&FDK_sbrDecoder_sbr_huffBook_EnvLevel11F;
1089
0
    }
1090
0
  }
1091
1092
0
  h_frame_data->iTESactive = (UCHAR)0; /* disable inter-TES by default */
1093
  /*
1094
    Now read raw envelope data
1095
  */
1096
0
  for (j = 0, offset = 0; j < nEnvelopes; j++) {
1097
0
    if (h_frame_data->domain_vec[j] == 0) {
1098
0
      if (coupling == COUPLING_BAL) {
1099
0
        h_frame_data->iEnvelope[offset] =
1100
0
            (FIXP_SGL)(((int)FDKreadBits(hBs, start_bits_balance))
1101
0
                       << envDataTableCompFactor);
1102
0
      } else {
1103
0
        h_frame_data->iEnvelope[offset] =
1104
0
            (FIXP_SGL)(int)FDKreadBits(hBs, start_bits);
1105
0
      }
1106
0
    }
1107
1108
0
    for (i = (1 - h_frame_data->domain_vec[j]); i < no_band[j]; i++) {
1109
0
      if (h_frame_data->domain_vec[j] == 0) {
1110
0
        delta = DecodeHuffmanCW(hcb_f, hBs);
1111
0
      } else {
1112
0
        delta = DecodeHuffmanCW(hcb_t, hBs);
1113
0
      }
1114
1115
0
      h_frame_data->iEnvelope[offset + i] =
1116
0
          (FIXP_SGL)(delta << envDataTableCompFactor);
1117
0
    }
1118
0
    if ((flags & SBRDEC_SYNTAX_USAC) && (flags & SBRDEC_USAC_ITES)) {
1119
0
      int bs_temp_shape = FDKreadBit(hBs);
1120
0
      FDK_ASSERT(j < 8);
1121
0
      h_frame_data->iTESactive |= (UCHAR)(bs_temp_shape << j);
1122
0
      if (bs_temp_shape) {
1123
0
        h_frame_data->interTempShapeMode[j] =
1124
0
            FDKread2Bits(hBs); /* bs_inter_temp_shape_mode */
1125
0
      } else {
1126
0
        h_frame_data->interTempShapeMode[j] = 0;
1127
0
      }
1128
0
    }
1129
0
    offset += no_band[j];
1130
0
  }
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
0
  return 1;
1141
0
}
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
 ****************************************************************************/
1150
static int generateFixFixOnly(FRAME_INFO *hSbrFrameInfo, int tranPosInternal,
1151
0
                              int numberTimeSlots, const UINT flags) {
1152
0
  int nEnv, i, tranIdx;
1153
0
  const int *pTable;
1154
1155
0
  if (tranPosInternal >= numberTimeSlots) {
1156
0
    return 0;
1157
0
  }
1158
1159
0
  switch (numberTimeSlots) {
1160
0
    case 8:
1161
0
      pTable = FDK_sbrDecoder_envelopeTable_8[tranPosInternal];
1162
0
      break;
1163
0
    case 15:
1164
0
      pTable = FDK_sbrDecoder_envelopeTable_15[tranPosInternal];
1165
0
      break;
1166
0
    case 16:
1167
0
      pTable = FDK_sbrDecoder_envelopeTable_16[tranPosInternal];
1168
0
      break;
1169
0
    default:
1170
0
      return 0;
1171
0
  }
1172
1173
  /* look number of envelopes in table */
1174
0
  nEnv = pTable[0];
1175
  /* look up envelope distribution in table */
1176
0
  for (i = 1; i < nEnv; i++) hSbrFrameInfo->borders[i] = pTable[i + 2];
1177
  /* open and close frame border */
1178
0
  hSbrFrameInfo->borders[0] = 0;
1179
0
  hSbrFrameInfo->borders[nEnv] = numberTimeSlots;
1180
0
  hSbrFrameInfo->nEnvelopes = nEnv;
1181
1182
  /* transient idx */
1183
0
  tranIdx = hSbrFrameInfo->tranEnv = pTable[1];
1184
1185
  /* add noise floors */
1186
0
  hSbrFrameInfo->bordersNoise[0] = 0;
1187
0
  hSbrFrameInfo->bordersNoise[1] =
1188
0
      hSbrFrameInfo->borders[tranIdx ? tranIdx : 1];
1189
0
  hSbrFrameInfo->bordersNoise[2] = numberTimeSlots;
1190
  /* nEnv is always > 1, so nNoiseEnvelopes is always 2 (IEC 14496-3 4.6.19.3.2)
1191
   */
1192
0
  hSbrFrameInfo->nNoiseEnvelopes = 2;
1193
1194
0
  return 1;
1195
0
}
1196
1197
/*!
1198
  \brief  Extracts LowDelaySBR control data from the bitstream.
1199
1200
  \return zero for bitstream error, one for correct.
1201
*/
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
0
    int timeSlots, const UINT flags) {
1208
0
  FRAME_INFO *pFrameInfo = &h_frame_data->frameInfo;
1209
0
  INT numberTimeSlots = hHeaderData->numberTimeSlots;
1210
0
  INT temp = 0, k;
1211
1212
  /* FIXFIXonly framing case */
1213
0
  h_frame_data->frameInfo.frameClass = 0;
1214
1215
  /* get the transient position from the bitstream */
1216
0
  switch (timeSlots) {
1217
0
    case 8:
1218
      /* 3bit transient position (temp={0;..;7}) */
1219
0
      temp = FDKreadBits(hBitBuf, 3);
1220
0
      break;
1221
1222
0
    case 16:
1223
0
    case 15:
1224
      /* 4bit transient position (temp={0;..;15}) */
1225
0
      temp = FDKreadBits(hBitBuf, 4);
1226
0
      break;
1227
1228
0
    default:
1229
0
      return 0;
1230
0
  }
1231
1232
  /* For "case 15" only*/
1233
0
  if (temp >= timeSlots) {
1234
0
    return 0;
1235
0
  }
1236
1237
  /* calculate borders according to the transient position */
1238
0
  if (!generateFixFixOnly(pFrameInfo, temp, numberTimeSlots, flags)) {
1239
0
    return 0;
1240
0
  }
1241
1242
  /* decode freq res: */
1243
0
  for (k = 0; k < pFrameInfo->nEnvelopes; k++) {
1244
0
    pFrameInfo->freqRes[k] =
1245
0
        (UCHAR)FDKreadBits(hBitBuf, 1); /* f = F [1 bits] */
1246
0
  }
1247
1248
0
  return 1;
1249
0
}
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
*/
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
0
    const UINT flags) {
1265
0
  FRAME_INFO *pFrameInfo = &h_frame_data->frameInfo;
1266
0
  FRAME_INFO *pPrevFrameInfo = &h_prev_frame_data->prevFrameInfo;
1267
0
  int bs_var_len_hf, bs_noise_position;
1268
0
  bs_noise_position = FDKreadBits(hBs, 4); /* SBR_PVC_NOISEPOSITION_BITS 4 */
1269
0
  bs_var_len_hf = FDKreadBit(hBs);
1270
0
  pFrameInfo->noisePosition = bs_noise_position;
1271
0
  pFrameInfo->tranEnv = -1;
1272
1273
  /* Init for bs_noise_position == 0 in case a parse error is found below. */
1274
0
  pFrameInfo->nEnvelopes = 1;
1275
0
  pFrameInfo->nNoiseEnvelopes = 1;
1276
0
  pFrameInfo->freqRes[0] = 0;
1277
1278
0
  if (bs_var_len_hf) { /* 1 or 3 Bits */
1279
0
    pFrameInfo->varLength = FDKreadBits(hBs, 2) + 1;
1280
0
    if (pFrameInfo->varLength > 3) {
1281
0
      pFrameInfo->varLength =
1282
0
          0;    /* assume bs_var_len_hf == 0 in case of error */
1283
0
      return 0; /* reserved value -> parse error */
1284
0
    }
1285
0
  } else {
1286
0
    pFrameInfo->varLength = 0;
1287
0
  }
1288
1289
0
  if (bs_noise_position) {
1290
0
    pFrameInfo->nEnvelopes = 2;
1291
0
    pFrameInfo->nNoiseEnvelopes = 2;
1292
0
    FDKmemclear(pFrameInfo->freqRes, sizeof(pFrameInfo->freqRes));
1293
0
  }
1294
1295
  /* frame border calculation */
1296
0
  if (hHeaderData->bs_info.pvc_mode > 0) {
1297
    /* See "7.5.1.4 HF adjustment of SBR envelope scalefactors" for reference.
1298
     */
1299
1300
0
    FDK_ASSERT((pFrameInfo->nEnvelopes == 1) || (pFrameInfo->nEnvelopes == 2));
1301
1302
    /* left timeborder-offset: use the timeborder of prev SBR frame */
1303
0
    if (pPrevFrameInfo->nEnvelopes > 0) {
1304
0
      pFrameInfo->borders[0] =
1305
0
          pPrevFrameInfo->borders[pPrevFrameInfo->nEnvelopes] - PVC_NTIMESLOT;
1306
0
      FDK_ASSERT(pFrameInfo->borders[0] <= 3);
1307
0
    } else {
1308
0
      pFrameInfo->borders[0] = 0;
1309
0
    }
1310
1311
    /* right timeborder-offset: */
1312
0
    pFrameInfo->borders[pFrameInfo->nEnvelopes] = 16 + pFrameInfo->varLength;
1313
1314
0
    if (pFrameInfo->nEnvelopes == 2) {
1315
0
      pFrameInfo->borders[1] = pFrameInfo->noisePosition;
1316
0
    }
1317
1318
    /* Calculation of PVC time borders t_EPVC */
1319
0
    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
0
      pFrameInfo->pvcBorders[0] = pFrameInfo->borders[0];
1323
0
    } else {
1324
0
      pFrameInfo->pvcBorders[0] = 0;
1325
0
    }
1326
0
    if (pFrameInfo->nEnvelopes == 2) {
1327
0
      pFrameInfo->pvcBorders[1] = pFrameInfo->borders[1];
1328
0
    }
1329
0
    pFrameInfo->pvcBorders[pFrameInfo->nEnvelopes] = 16;
1330
1331
    /* calculation of SBR noise-floor time-border vector: */
1332
0
    for (INT i = 0; i <= pFrameInfo->nNoiseEnvelopes; i++) {
1333
0
      pFrameInfo->bordersNoise[i] = pFrameInfo->borders[i];
1334
0
    }
1335
1336
0
    pFrameInfo->tranEnv = -1; /* tranEnv not used */
1337
0
  }
1338
0
  return 1;
1339
0
}
1340
1341
/*!
1342
  \brief   Extract the frame information (structure FRAME_INFO) from the
1343
  bitstream \return  Zero for bitstream error, one for correct.
1344
*/
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
0
    const UINT nrOfChannels, const UINT flags) {
1351
0
  FRAME_INFO *pFrameInfo = &h_frame_data->frameInfo;
1352
0
  int numberTimeSlots = hHeaderData->numberTimeSlots;
1353
0
  int pointer_bits = 0, nEnv = 0, b = 0, border, i, n = 0, k, p, aL, aR, nL, nR,
1354
0
      temp = 0, staticFreqRes;
1355
0
  UCHAR frameClass;
1356
1357
0
  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
0
    frameClass = FDKreadBits(hBs, 1); /* frameClass = [1 bit] */
1361
0
    if (frameClass == 1) {
1362
      /* if frameClass == 1, extract LowDelaySbrGrid, otherwise extract normal
1363
       * SBR-Grid for FIXIFX */
1364
      /* extract the AACLD-Sbr-Grid */
1365
0
      pFrameInfo->frameClass = frameClass;
1366
0
      int err = 1;
1367
0
      err = extractLowDelayGrid(hBs, hHeaderData, h_frame_data, numberTimeSlots,
1368
0
                                flags);
1369
0
      return err;
1370
0
    }
1371
0
  } else {
1372
0
    frameClass = FDKreadBits(hBs, 2); /* frameClass = C [2 bits] */
1373
0
  }
1374
1375
0
  switch (frameClass) {
1376
0
    case 0:
1377
0
      temp = FDKreadBits(hBs, 2); /* E [2 bits ] */
1378
0
      nEnv = (int)(1 << temp);    /* E -> e */
1379
1380
0
      if ((flags & SBRDEC_ELD_GRID) && (nEnv == 1))
1381
0
        h_frame_data->ampResolutionCurrentFrame =
1382
0
            FDKreadBits(hBs, 1); /* new ELD Syntax 07-11-09 */
1383
1384
0
      staticFreqRes = FDKreadBits(hBs, 1);
1385
1386
0
      if (flags & (SBRDEC_SYNTAX_USAC | SBRDEC_SYNTAX_RSVD50)) {
1387
0
        if (nEnv > MAX_ENVELOPES_USAC) return 0;
1388
0
      } else
1389
1390
0
        b = nEnv + 1;
1391
0
      switch (nEnv) {
1392
0
        case 1:
1393
0
          switch (numberTimeSlots) {
1394
0
            case 15:
1395
0
              FDKmemcpy(pFrameInfo, &FDK_sbrDecoder_sbr_frame_info1_15,
1396
0
                        sizeof(FRAME_INFO));
1397
0
              break;
1398
0
            case 16:
1399
0
              FDKmemcpy(pFrameInfo, &FDK_sbrDecoder_sbr_frame_info1_16,
1400
0
                        sizeof(FRAME_INFO));
1401
0
              break;
1402
0
            default:
1403
0
              FDK_ASSERT(0);
1404
0
          }
1405
0
          break;
1406
0
        case 2:
1407
0
          switch (numberTimeSlots) {
1408
0
            case 15:
1409
0
              FDKmemcpy(pFrameInfo, &FDK_sbrDecoder_sbr_frame_info2_15,
1410
0
                        sizeof(FRAME_INFO));
1411
0
              break;
1412
0
            case 16:
1413
0
              FDKmemcpy(pFrameInfo, &FDK_sbrDecoder_sbr_frame_info2_16,
1414
0
                        sizeof(FRAME_INFO));
1415
0
              break;
1416
0
            default:
1417
0
              FDK_ASSERT(0);
1418
0
          }
1419
0
          break;
1420
0
        case 4:
1421
0
          switch (numberTimeSlots) {
1422
0
            case 15:
1423
0
              FDKmemcpy(pFrameInfo, &FDK_sbrDecoder_sbr_frame_info4_15,
1424
0
                        sizeof(FRAME_INFO));
1425
0
              break;
1426
0
            case 16:
1427
0
              FDKmemcpy(pFrameInfo, &FDK_sbrDecoder_sbr_frame_info4_16,
1428
0
                        sizeof(FRAME_INFO));
1429
0
              break;
1430
0
            default:
1431
0
              FDK_ASSERT(0);
1432
0
          }
1433
0
          break;
1434
0
        case 8:
1435
0
#if (MAX_ENVELOPES >= 8)
1436
0
          switch (numberTimeSlots) {
1437
0
            case 15:
1438
0
              FDKmemcpy(pFrameInfo, &FDK_sbrDecoder_sbr_frame_info8_15,
1439
0
                        sizeof(FRAME_INFO));
1440
0
              break;
1441
0
            case 16:
1442
0
              FDKmemcpy(pFrameInfo, &FDK_sbrDecoder_sbr_frame_info8_16,
1443
0
                        sizeof(FRAME_INFO));
1444
0
              break;
1445
0
            default:
1446
0
              FDK_ASSERT(0);
1447
0
          }
1448
0
          break;
1449
#else
1450
          return 0;
1451
#endif
1452
0
      }
1453
      /* Apply correct freqRes (High is default) */
1454
0
      if (!staticFreqRes) {
1455
0
        for (i = 0; i < nEnv; i++) pFrameInfo->freqRes[i] = 0;
1456
0
      }
1457
1458
0
      break;
1459
0
    case 1:
1460
0
    case 2:
1461
0
      temp = FDKreadBits(hBs, 2); /* A [2 bits] */
1462
1463
0
      n = FDKreadBits(hBs, 2); /* n = N [2 bits] */
1464
1465
0
      nEnv = n + 1; /* # envelopes */
1466
0
      b = nEnv + 1; /* # borders   */
1467
1468
0
      break;
1469
0
  }
1470
1471
0
  switch (frameClass) {
1472
0
    case 1:
1473
      /* Decode borders: */
1474
0
      pFrameInfo->borders[0] = 0;      /* first border          */
1475
0
      border = temp + numberTimeSlots; /* A -> aR               */
1476
0
      i = b - 1;                       /* frame info index for last border */
1477
0
      pFrameInfo->borders[i] = border; /* last border                      */
1478
1479
0
      for (k = 0; k < n; k++) {
1480
0
        temp = FDKreadBits(hBs, 2); /* R [2 bits] */
1481
0
        border -= (2 * temp + 2);   /* R -> r                */
1482
0
        pFrameInfo->borders[--i] = border;
1483
0
      }
1484
1485
      /* Decode pointer: */
1486
0
      pointer_bits = DFRACT_BITS - 1 - CountLeadingBits((FIXP_DBL)(n + 1));
1487
0
      p = FDKreadBits(hBs, pointer_bits); /* p = P [pointer_bits bits] */
1488
1489
0
      if (p > n + 1) return 0;
1490
1491
0
      pFrameInfo->tranEnv = p ? n + 2 - p : -1;
1492
1493
      /* Decode freq res: */
1494
0
      for (k = n; k >= 0; k--) {
1495
0
        pFrameInfo->freqRes[k] = FDKreadBits(hBs, 1); /* f = F [1 bits] */
1496
0
      }
1497
1498
      /* Calculate noise floor middle border: */
1499
0
      if (p == 0 || p == 1)
1500
0
        pFrameInfo->bordersNoise[1] = pFrameInfo->borders[n];
1501
0
      else
1502
0
        pFrameInfo->bordersNoise[1] = pFrameInfo->borders[pFrameInfo->tranEnv];
1503
1504
0
      break;
1505
1506
0
    case 2:
1507
      /* Decode borders: */
1508
0
      border = temp;                   /* A -> aL */
1509
0
      pFrameInfo->borders[0] = border; /* first border */
1510
1511
0
      for (k = 1; k <= n; k++) {
1512
0
        temp = FDKreadBits(hBs, 2); /* R [2 bits] */
1513
0
        border += (2 * temp + 2);   /* R -> r                */
1514
0
        pFrameInfo->borders[k] = border;
1515
0
      }
1516
0
      pFrameInfo->borders[k] = numberTimeSlots; /* last border */
1517
1518
      /* Decode pointer: */
1519
0
      pointer_bits = DFRACT_BITS - 1 - CountLeadingBits((FIXP_DBL)(n + 1));
1520
0
      p = FDKreadBits(hBs, pointer_bits); /* p = P [pointer_bits bits] */
1521
0
      if (p > n + 1) return 0;
1522
1523
0
      if (p == 0 || p == 1)
1524
0
        pFrameInfo->tranEnv = -1;
1525
0
      else
1526
0
        pFrameInfo->tranEnv = p - 1;
1527
1528
      /* Decode freq res: */
1529
0
      for (k = 0; k <= n; k++) {
1530
0
        pFrameInfo->freqRes[k] = FDKreadBits(hBs, 1); /* f = F [1 bits] */
1531
0
      }
1532
1533
      /* Calculate noise floor middle border: */
1534
0
      switch (p) {
1535
0
        case 0:
1536
0
          pFrameInfo->bordersNoise[1] = pFrameInfo->borders[1];
1537
0
          break;
1538
0
        case 1:
1539
0
          pFrameInfo->bordersNoise[1] = pFrameInfo->borders[n];
1540
0
          break;
1541
0
        default:
1542
0
          pFrameInfo->bordersNoise[1] =
1543
0
              pFrameInfo->borders[pFrameInfo->tranEnv];
1544
0
          break;
1545
0
      }
1546
1547
0
      break;
1548
1549
0
    case 3:
1550
      /* v_ctrlSignal = [frameClass,aL,aR,nL,nR,v_rL,v_rR,p,v_fLR]; */
1551
1552
0
      aL = FDKreadBits(hBs, 2); /* AL [2 bits], AL -> aL */
1553
1554
0
      aR = FDKreadBits(hBs, 2) + numberTimeSlots; /* AR [2 bits], AR -> aR */
1555
1556
0
      nL = FDKreadBits(hBs, 2); /* nL = NL [2 bits] */
1557
1558
0
      nR = FDKreadBits(hBs, 2); /* nR = NR [2 bits] */
1559
1560
      /*-------------------------------------------------------------------------
1561
        Calculate help variables
1562
        --------------------------------------------------------------------------*/
1563
1564
      /* general: */
1565
0
      nEnv = nL + nR + 1; /* # envelopes */
1566
0
      if (nEnv > MAX_ENVELOPES) return 0;
1567
0
      b = nEnv + 1; /* # borders   */
1568
1569
      /*-------------------------------------------------------------------------
1570
        Decode envelopes
1571
        --------------------------------------------------------------------------*/
1572
1573
      /* L-borders:   */
1574
0
      border = aL; /* first border */
1575
0
      pFrameInfo->borders[0] = border;
1576
1577
0
      for (k = 1; k <= nL; k++) {
1578
0
        temp = FDKreadBits(hBs, 2); /* R [2 bits] */
1579
0
        border += (2 * temp + 2);   /* R -> r                */
1580
0
        pFrameInfo->borders[k] = border;
1581
0
      }
1582
1583
      /* R-borders:  */
1584
0
      border = aR; /* last border */
1585
0
      i = nEnv;
1586
1587
0
      pFrameInfo->borders[i] = border;
1588
1589
0
      for (k = 0; k < nR; k++) {
1590
0
        temp = FDKreadBits(hBs, 2); /* R [2 bits] */
1591
0
        border -= (2 * temp + 2);   /* R -> r                */
1592
0
        pFrameInfo->borders[--i] = border;
1593
0
      }
1594
1595
      /* decode pointer: */
1596
0
      pointer_bits =
1597
0
          DFRACT_BITS - 1 - CountLeadingBits((FIXP_DBL)(nL + nR + 1));
1598
0
      p = FDKreadBits(hBs, pointer_bits); /* p = P [pointer_bits bits] */
1599
1600
0
      if (p > nL + nR + 1) return 0;
1601
1602
0
      pFrameInfo->tranEnv = p ? b - p : -1;
1603
1604
      /* decode freq res: */
1605
0
      for (k = 0; k < nEnv; k++) {
1606
0
        pFrameInfo->freqRes[k] = FDKreadBits(hBs, 1); /* f = F [1 bits] */
1607
0
      }
1608
1609
      /*-------------------------------------------------------------------------
1610
        Decode noise floors
1611
        --------------------------------------------------------------------------*/
1612
0
      pFrameInfo->bordersNoise[0] = aL;
1613
1614
0
      if (nEnv == 1) {
1615
        /* 1 noise floor envelope: */
1616
0
        pFrameInfo->bordersNoise[1] = aR;
1617
0
      } else {
1618
        /* 2 noise floor envelopes */
1619
0
        if (p == 0 || p == 1)
1620
0
          pFrameInfo->bordersNoise[1] = pFrameInfo->borders[nEnv - 1];
1621
0
        else
1622
0
          pFrameInfo->bordersNoise[1] =
1623
0
              pFrameInfo->borders[pFrameInfo->tranEnv];
1624
0
        pFrameInfo->bordersNoise[2] = aR;
1625
0
      }
1626
0
      break;
1627
0
  }
1628
1629
  /*
1630
    Store number of envelopes, noise floor envelopes and frame class
1631
  */
1632
0
  pFrameInfo->nEnvelopes = nEnv;
1633
1634
0
  if (nEnv == 1)
1635
0
    pFrameInfo->nNoiseEnvelopes = 1;
1636
0
  else
1637
0
    pFrameInfo->nNoiseEnvelopes = 2;
1638
1639
0
  pFrameInfo->frameClass = frameClass;
1640
1641
0
  if (pFrameInfo->frameClass == 2 || pFrameInfo->frameClass == 1) {
1642
    /* calculate noise floor first and last borders: */
1643
0
    pFrameInfo->bordersNoise[0] = pFrameInfo->borders[0];
1644
0
    pFrameInfo->bordersNoise[pFrameInfo->nNoiseEnvelopes] =
1645
0
        pFrameInfo->borders[nEnv];
1646
0
  }
1647
1648
0
  return 1;
1649
0
}
1650
1651
/*!
1652
  \brief   Check if the frameInfo vector has reasonable values.
1653
  \return  Zero for error, one for correct
1654
*/
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
0
{
1661
0
  int maxPos, i, j;
1662
0
  int startPos;
1663
0
  int stopPos;
1664
0
  int tranEnv;
1665
0
  int startPosNoise;
1666
0
  int stopPosNoise;
1667
0
  int nEnvelopes = pFrameInfo->nEnvelopes;
1668
0
  int nNoiseEnvelopes = pFrameInfo->nNoiseEnvelopes;
1669
1670
0
  if (nEnvelopes < 1 || nEnvelopes > MAX_ENVELOPES) return 0;
1671
1672
0
  if (nNoiseEnvelopes > MAX_NOISE_ENVELOPES) return 0;
1673
1674
0
  startPos = pFrameInfo->borders[0];
1675
0
  stopPos = pFrameInfo->borders[nEnvelopes];
1676
0
  tranEnv = pFrameInfo->tranEnv;
1677
0
  startPosNoise = pFrameInfo->bordersNoise[0];
1678
0
  stopPosNoise = pFrameInfo->bordersNoise[nNoiseEnvelopes];
1679
1680
0
  if (overlap < 0 || overlap > (3 * (4))) {
1681
0
    return 0;
1682
0
  }
1683
0
  if (timeStep < 1 || timeStep > (4)) {
1684
0
    return 0;
1685
0
  }
1686
0
  maxPos = numberOfTimeSlots + (overlap / timeStep);
1687
1688
  /* Check that the start and stop positions of the frame are reasonable values.
1689
   */
1690
0
  if ((startPos < 0) || (startPos >= stopPos)) return 0;
1691
0
  if (startPos > maxPos - numberOfTimeSlots) /* First env. must start in or
1692
                                                directly after the overlap
1693
                                                buffer */
1694
0
    return 0;
1695
0
  if (stopPos < numberOfTimeSlots) /* One complete frame must be ready for
1696
                                      output after processing */
1697
0
    return 0;
1698
0
  if (stopPos > maxPos) return 0;
1699
1700
  /* Check that the  start border for every envelope is strictly later in time
1701
   */
1702
0
  for (i = 0; i < nEnvelopes; i++) {
1703
0
    if (pFrameInfo->borders[i] >= pFrameInfo->borders[i + 1]) return 0;
1704
0
  }
1705
1706
  /* Check that the envelope to be shortened is actually among the envelopes */
1707
0
  if (tranEnv > nEnvelopes) return 0;
1708
1709
  /* Check the noise borders */
1710
0
  if (nEnvelopes == 1 && nNoiseEnvelopes > 1) return 0;
1711
1712
0
  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
0
  for (i = 0; i < nNoiseEnvelopes; i++) {
1717
0
    if (pFrameInfo->bordersNoise[i] >= pFrameInfo->bordersNoise[i + 1])
1718
0
      return 0;
1719
0
  }
1720
1721
  /* Check that every noise border is the same as an envelope border*/
1722
0
  for (i = 0; i < nNoiseEnvelopes; i++) {
1723
0
    startPosNoise = pFrameInfo->bordersNoise[i];
1724
1725
0
    for (j = 0; j < nEnvelopes; j++) {
1726
0
      if (pFrameInfo->borders[j] == startPosNoise) break;
1727
0
    }
1728
0
    if (j == nEnvelopes) return 0;
1729
0
  }
1730
1731
0
  return 1;
1732
0
}