Coverage Report

Created: 2026-01-17 06:32

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/aac/libAACdec/src/aacdecoder.cpp
Line
Count
Source
1
/* -----------------------------------------------------------------------------
2
Software License for The Fraunhofer FDK AAC Codec Library for Android
3
4
© Copyright  1995 - 2023 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
/**************************** AAC decoder library ******************************
96
97
   Author(s):   Josef Hoepfl
98
99
   Description:
100
101
*******************************************************************************/
102
103
/*!
104
  \page default General Overview of the AAC Decoder Implementation
105
106
  The main entry point to decode a AAC frame is CAacDecoder_DecodeFrame(). It
107
  handles the different transport multiplexes and bitstream formats supported by
108
  this implementation. It extracts the AAC_raw_data_blocks from these bitstreams
109
  to further process then in the actual decoding stages.
110
111
  Note: Click on a function of file in the above image to see details about the
112
  function. Also note, that this is just an overview of the most important
113
  functions and not a complete call graph.
114
115
  <h2>1 Bitstream deformatter</h2>
116
  The basic bit stream parser function CChannelElement_Read() is called. It uses
117
  other subcalls in order to parse and unpack the bitstreams. Note, that this
118
  includes huffmann decoding of the coded spectral data. This operation can be
119
  computational significant specifically at higher bitrates. Optimization is
120
  likely in CBlock_ReadSpectralData().
121
122
  The bitstream deformatter also includes many bitfield operations. Profiling on
123
  the target will determine required optimizations.
124
125
  <h2>2 Actual decoding to retain the time domain output</h2>
126
  The basic bitstream deformatter function CChannelElement_Decode() for CPE
127
  elements and SCE elements are called. Except for the stereo processing (2.1)
128
  which is only used for CPE elements, the function calls for CPE or SCE are
129
  similar, except that CPE always processes to independent channels while SCE
130
  only processes one channel.
131
132
  Often there is the distinction between long blocks and short blocks. However,
133
  computational expensive functions that ususally require optimization are being
134
  shared by these two groups,
135
136
  <h3>2.1 Stereo processing for CPE elements</h3>
137
  CChannelPairElement_Decode() first calles the joint stereo  tools in
138
  stereo.cpp when required.
139
140
  <h3>2.2 Scaling of spectral data</h3>
141
  CBlock_ScaleSpectralData().
142
143
  <h3>2.3 Apply additional coding tools</h3>
144
  ApplyTools() calles the PNS tools in case of MPEG-4 bitstreams, and TNS
145
  filtering CTns_Apply() for MPEG-2 and MPEG-4 bitstreams. The function
146
  TnsFilterIIR() which is called by CTns_Apply() (2.3.1) might require some
147
  optimization.
148
149
  <h2>3 Frequency-To-Time conversion</h3>
150
  The filterbank is called using CBlock_FrequencyToTime() using the MDCT module
151
  from the FDK Tools
152
153
*/
154
155
#include "aacdecoder.h"
156
157
#include "aac_rom.h"
158
#include "aac_ram.h"
159
#include "channel.h"
160
#include "FDK_audio.h"
161
162
#include "aacdec_pns.h"
163
164
#include "sbrdecoder.h"
165
166
#include "sac_dec_lib.h"
167
168
#include "aacdec_hcr.h"
169
#include "rvlc.h"
170
171
#include "usacdec_lpd.h"
172
173
#include "ac_arith_coder.h"
174
175
#include "tpdec_lib.h"
176
177
#include "conceal.h"
178
179
#include "FDK_crc.h"
180
#define PS_IS_EXPLICITLY_DISABLED(aot, flags) \
181
472k
  (((aot) == AOT_DRM_AAC) && !(flags & AC_PS_PRESENT))
182
183
#define IS_STEREO_SBR(el_id, stereoConfigIndex)            \
184
235k
  (((el_id) == ID_USAC_CPE && (stereoConfigIndex) == 0) || \
185
235k
   ((el_id) == ID_USAC_CPE && (stereoConfigIndex) == 3))
186
187
457k
void CAacDecoder_SyncQmfMode(HANDLE_AACDECODER self) {
188
457k
  FDK_ASSERT(
189
457k
      !((self->flags[0] & AC_MPS_PRESENT) && (self->flags[0] & AC_PS_PRESENT)));
190
191
  /* Assign user requested mode */
192
457k
  self->qmfModeCurr = self->qmfModeUser;
193
194
457k
  if (IS_USAC(self->streamInfo.aot)) {
195
271k
    self->qmfModeCurr = MODE_HQ;
196
271k
  }
197
198
457k
  if (self->qmfModeCurr == NOT_DEFINED) {
199
186k
    if ((IS_LOWDELAY(self->streamInfo.aot) &&
200
85.2k
         (self->flags[0] & AC_MPS_PRESENT)) ||
201
139k
        ((self->streamInfo.aacNumChannels == 1) &&
202
38.7k
         ((CAN_DO_PS(self->streamInfo.aot) &&
203
10.9k
           !(self->flags[0] & AC_MPS_PRESENT)) ||
204
57.6k
          (IS_USAC(self->streamInfo.aot))))) {
205
57.6k
      self->qmfModeCurr = MODE_HQ;
206
128k
    } else {
207
128k
      self->qmfModeCurr = MODE_LP;
208
128k
    }
209
186k
  }
210
211
457k
  if (self->mpsEnableCurr) {
212
197k
    if (IS_LOWDELAY(self->streamInfo.aot) &&
213
44.4k
        (self->qmfModeCurr == MODE_LP)) { /* Overrule user requested QMF mode */
214
224
      self->qmfModeCurr = MODE_HQ;
215
224
    }
216
    /* Set and check if MPS decoder allows the current mode */
217
197k
    switch (mpegSurroundDecoder_SetParam(
218
197k
        (CMpegSurroundDecoder *)self->pMpegSurroundDecoder,
219
197k
        SACDEC_PARTIALLY_COMPLEX, self->qmfModeCurr == MODE_LP)) {
220
0
      case MPS_OK:
221
0
        break;
222
197k
      case MPS_INVALID_PARAMETER: { /* Only one mode supported. Find out which
223
                                       one: */
224
197k
        LIB_INFO libInfo[FDK_MODULE_LAST];
225
197k
        UINT mpsCaps;
226
227
197k
        FDKinitLibInfo(libInfo);
228
197k
        mpegSurroundDecoder_GetLibInfo(libInfo);
229
197k
        mpsCaps = FDKlibInfo_getCapabilities(libInfo, FDK_MPSDEC);
230
231
197k
        if (((mpsCaps & CAPF_MPS_LP) && (self->qmfModeCurr == MODE_LP)) ||
232
197k
            ((mpsCaps & CAPF_MPS_HQ) &&
233
197k
             (self->qmfModeCurr ==
234
197k
              MODE_HQ))) { /* MPS decoder does support the requested mode. */
235
197k
          break;
236
197k
        }
237
197k
      }
238
361
        FDK_FALLTHROUGH;
239
361
      default:
240
361
        if (self->qmfModeUser == NOT_DEFINED) {
241
          /* Revert in case mpegSurroundDecoder_SetParam() fails. */
242
361
          self->qmfModeCurr =
243
361
              (self->qmfModeCurr == MODE_LP) ? MODE_HQ : MODE_LP;
244
361
        } else {
245
          /* in case specific mode was requested we disable MPS and playout the
246
           * downmix */
247
0
          self->mpsEnableCurr = 0;
248
0
        }
249
197k
    }
250
197k
  }
251
252
  /* Set SBR to current QMF mode. Error does not matter. */
253
457k
  sbrDecoder_SetParam(self->hSbrDecoder, SBR_QMF_MODE,
254
457k
                      (self->qmfModeCurr == MODE_LP));
255
457k
  self->psPossible =
256
457k
      ((CAN_DO_PS(self->streamInfo.aot) &&
257
15.4k
        !PS_IS_EXPLICITLY_DISABLED(self->streamInfo.aot, self->flags[0]) &&
258
15.4k
        self->streamInfo.aacNumChannels == 1 &&
259
10.9k
        !(self->flags[0] & AC_MPS_PRESENT))) &&
260
10.9k
      self->qmfModeCurr == MODE_HQ;
261
457k
  FDK_ASSERT(!((self->flags[0] & AC_MPS_PRESENT) && self->psPossible));
262
457k
}
263
264
7.89k
void CAacDecoder_SignalInterruption(HANDLE_AACDECODER self) {
265
7.89k
  if (self->flags[0] & (AC_USAC | AC_RSVD50 | AC_RSV603DA)) {
266
5.32k
    int i;
267
268
12.1k
    for (i = 0; i < fMin(self->aacChannels, (8)); i++) {
269
6.77k
      if (self->pAacDecoderStaticChannelInfo
270
6.77k
              [i]) { /* number of active channels can be smaller */
271
6.77k
        self->pAacDecoderStaticChannelInfo[i]->hArCo->m_numberLinesPrev = 0;
272
6.77k
      }
273
6.77k
    }
274
5.32k
  }
275
7.89k
}
276
277
/*!
278
  \brief Calculates the number of element channels
279
280
  \type  channel type
281
  \usacStereoConfigIndex  usac stereo config index
282
283
  \return  element channels
284
*/
285
static int CAacDecoder_GetELChannels(MP4_ELEMENT_ID type,
286
2.35M
                                     UCHAR usacStereoConfigIndex) {
287
2.35M
  int el_channels = 0;
288
289
2.35M
  switch (type) {
290
657k
    case ID_USAC_CPE:
291
657k
      if (usacStereoConfigIndex == 1) {
292
409k
        el_channels = 1;
293
409k
      } else {
294
248k
        el_channels = 2;
295
248k
      }
296
657k
      break;
297
548k
    case ID_CPE:
298
548k
      el_channels = 2;
299
548k
      break;
300
191k
    case ID_USAC_SCE:
301
191k
    case ID_USAC_LFE:
302
576k
    case ID_SCE:
303
708k
    case ID_LFE:
304
708k
      el_channels = 1;
305
708k
      break;
306
440k
    default:
307
440k
      el_channels = 0;
308
440k
      break;
309
2.35M
  }
310
311
2.35M
  return el_channels;
312
2.35M
}
313
314
/*!
315
  \brief Reset ancillary data struct. Call before parsing a new frame.
316
317
  \ancData Pointer to ancillary data structure
318
319
  \return  Error code
320
*/
321
443k
static AAC_DECODER_ERROR CAacDecoder_AncDataReset(CAncData *ancData) {
322
443k
  int i;
323
3.99M
  for (i = 0; i < 8; i++) {
324
3.54M
    ancData->offset[i] = 0;
325
3.54M
  }
326
443k
  ancData->nrElements = 0;
327
328
443k
  return AAC_DEC_OK;
329
443k
}
330
331
/*!
332
  \brief Initialize ancillary buffer
333
334
  \ancData Pointer to ancillary data structure
335
  \buffer Pointer to (external) anc data buffer
336
  \size Size of the buffer pointed on by buffer in bytes
337
338
  \return  Error code
339
*/
340
AAC_DECODER_ERROR CAacDecoder_AncDataInit(CAncData *ancData,
341
26.6k
                                          unsigned char *buffer, int size) {
342
26.6k
  if (size >= 0) {
343
26.6k
    ancData->buffer = buffer;
344
26.6k
    ancData->bufferSize = size;
345
346
26.6k
    CAacDecoder_AncDataReset(ancData);
347
348
26.6k
    return AAC_DEC_OK;
349
26.6k
  }
350
351
0
  return AAC_DEC_ANC_DATA_ERROR;
352
26.6k
}
353
354
/*!
355
  \brief Get one ancillary data element
356
357
  \ancData Pointer to ancillary data structure
358
  \index Index of the anc data element to get
359
  \ptr Pointer to a buffer receiving a pointer to the requested anc data element
360
  \size Pointer to a buffer receiving the length of the requested anc data
361
  element in bytes
362
363
  \return  Error code
364
*/
365
AAC_DECODER_ERROR CAacDecoder_AncDataGet(CAncData *ancData, int index,
366
0
                                         unsigned char **ptr, int *size) {
367
0
  AAC_DECODER_ERROR error = AAC_DEC_OK;
368
369
0
  *ptr = NULL;
370
0
  *size = 0;
371
372
0
  if (index >= 0 && index < 8 - 1 && index < ancData->nrElements) {
373
0
    *ptr = &ancData->buffer[ancData->offset[index]];
374
0
    *size = ancData->offset[index + 1] - ancData->offset[index];
375
0
  }
376
377
0
  return error;
378
0
}
379
380
/*!
381
  \brief Parse ancillary data
382
383
  \ancData Pointer to ancillary data structure
384
  \hBs Handle to FDK bitstream
385
  \ancBytes Length of ancillary data to read from the bitstream
386
387
  \return  Error code
388
*/
389
static AAC_DECODER_ERROR CAacDecoder_AncDataParse(CAncData *ancData,
390
                                                  HANDLE_FDK_BITSTREAM hBs,
391
10.1k
                                                  const int ancBytes) {
392
10.1k
  AAC_DECODER_ERROR error = AAC_DEC_OK;
393
10.1k
  int readBytes = 0;
394
395
10.1k
  if (ancData->buffer != NULL) {
396
0
    if (ancBytes > 0) {
397
      /* write ancillary data to external buffer */
398
0
      int offset = ancData->offset[ancData->nrElements];
399
400
0
      if ((offset + ancBytes) > ancData->bufferSize) {
401
0
        error = AAC_DEC_TOO_SMALL_ANC_BUFFER;
402
0
      } else if (ancData->nrElements >= 8 - 1) {
403
0
        error = AAC_DEC_TOO_MANY_ANC_ELEMENTS;
404
0
      } else {
405
0
        int i;
406
407
0
        for (i = 0; i < ancBytes; i++) {
408
0
          ancData->buffer[i + offset] = FDKreadBits(hBs, 8);
409
0
          readBytes++;
410
0
        }
411
412
0
        ancData->nrElements++;
413
0
        ancData->offset[ancData->nrElements] =
414
0
            ancBytes + ancData->offset[ancData->nrElements - 1];
415
0
      }
416
0
    }
417
0
  }
418
419
10.1k
  readBytes = ancBytes - readBytes;
420
421
10.1k
  if (readBytes > 0) {
422
    /* skip data */
423
6.35k
    FDKpushFor(hBs, readBytes << 3);
424
6.35k
  }
425
426
10.1k
  return error;
427
10.1k
}
428
429
/*!
430
  \brief Read Stream Data Element
431
432
  \bs Bitstream Handle
433
434
  \return  Error code
435
*/
436
static AAC_DECODER_ERROR CDataStreamElement_Read(HANDLE_AACDECODER self,
437
                                                 HANDLE_FDK_BITSTREAM bs,
438
                                                 UCHAR *elementInstanceTag,
439
9.41k
                                                 UINT alignmentAnchor) {
440
9.41k
  AAC_DECODER_ERROR error = AAC_DEC_OK;
441
9.41k
  UINT dseBits;
442
9.41k
  INT dataStart;
443
9.41k
  int dataByteAlignFlag, count;
444
445
9.41k
  FDK_ASSERT(self != NULL);
446
447
9.41k
  int crcReg = transportDec_CrcStartReg(self->hInput, 0);
448
449
  /* Element Instance Tag */
450
9.41k
  *elementInstanceTag = FDKreadBits(bs, 4);
451
  /* Data Byte Align Flag */
452
9.41k
  dataByteAlignFlag = FDKreadBits(bs, 1);
453
454
9.41k
  count = FDKreadBits(bs, 8);
455
456
9.41k
  if (count == 255) {
457
12
    count += FDKreadBits(bs, 8); /* EscCount */
458
12
  }
459
9.41k
  dseBits = count * 8;
460
461
9.41k
  if (dataByteAlignFlag) {
462
5.02k
    FDKbyteAlign(bs, alignmentAnchor);
463
5.02k
  }
464
465
9.41k
  dataStart = (INT)FDKgetValidBits(bs);
466
467
9.41k
  error = CAacDecoder_AncDataParse(&self->ancData, bs, count);
468
9.41k
  transportDec_CrcEndReg(self->hInput, crcReg);
469
470
9.41k
  {
471
    /* Move to the beginning of the data chunk */
472
9.41k
    FDKpushBack(bs, dataStart - (INT)FDKgetValidBits(bs));
473
474
    /* Read Anc data if available */
475
9.41k
    aacDecoder_drcMarkPayload(self->hDrcInfo, bs, DVB_DRC_ANC_DATA);
476
9.41k
  }
477
478
9.41k
  {
479
9.41k
    PCMDMX_ERROR dmxErr = PCMDMX_OK;
480
481
    /* Move to the beginning of the data chunk */
482
9.41k
    FDKpushBack(bs, dataStart - (INT)FDKgetValidBits(bs));
483
484
    /* Read DMX meta-data */
485
9.41k
    dmxErr = pcmDmx_Parse(self->hPcmUtils, bs, dseBits, 0 /* not mpeg2 */);
486
9.41k
    if (error == AAC_DEC_OK && dmxErr != PCMDMX_OK) {
487
6.71k
      error = AAC_DEC_UNKNOWN;
488
6.71k
    }
489
9.41k
  }
490
491
  /* Move to the very end of the element. */
492
9.41k
  FDKpushBiDirectional(bs, (INT)FDKgetValidBits(bs) - dataStart + (INT)dseBits);
493
494
9.41k
  return error;
495
9.41k
}
496
497
static INT findElementInstanceTag(
498
    INT elementTag, MP4_ELEMENT_ID elementId,
499
    CAacDecoderChannelInfo **pAacDecoderChannelInfo, INT nChannels,
500
5.68k
    MP4_ELEMENT_ID *pElementIdTab, INT nElements) {
501
5.68k
  int el, chCnt = 0;
502
503
14.9k
  for (el = 0; el < nElements; el++) {
504
14.9k
    switch (pElementIdTab[el]) {
505
3.45k
      case ID_CPE:
506
13.2k
      case ID_SCE:
507
14.9k
      case ID_LFE:
508
14.9k
        if ((elementTag == pAacDecoderChannelInfo[chCnt]->ElementInstanceTag) &&
509
6.43k
            (elementId == pElementIdTab[el])) {
510
5.66k
          return 1; /* element instance tag found */
511
5.66k
        }
512
9.31k
        chCnt += (pElementIdTab[el] == ID_CPE) ? 2 : 1;
513
9.31k
        break;
514
0
      default:
515
0
        break;
516
14.9k
    }
517
9.31k
    if (chCnt >= nChannels) break;
518
9.29k
    if (pElementIdTab[el] == ID_END) break;
519
9.29k
  }
520
521
20
  return 0; /* element instance tag not found */
522
5.68k
}
523
524
static INT validateElementInstanceTags(
525
    CProgramConfig *pce, CAacDecoderChannelInfo **pAacDecoderChannelInfo,
526
1.51k
    INT nChannels, MP4_ELEMENT_ID *pElementIdTab, INT nElements) {
527
1.51k
  if (nChannels >= pce->NumChannels) {
528
3.12k
    for (int el = 0; el < pce->NumFrontChannelElements; el++) {
529
1.61k
      if (!findElementInstanceTag(pce->FrontElementTagSelect[el],
530
1.61k
                                  pce->FrontElementIsCpe[el] ? ID_CPE : ID_SCE,
531
1.61k
                                  pAacDecoderChannelInfo, nChannels,
532
1.61k
                                  pElementIdTab, nElements)) {
533
6
        return 0; /* element instance tag not in raw_data_block() */
534
6
      }
535
1.61k
    }
536
2.91k
    for (int el = 0; el < pce->NumSideChannelElements; el++) {
537
1.41k
      if (!findElementInstanceTag(pce->SideElementTagSelect[el],
538
1.41k
                                  pce->SideElementIsCpe[el] ? ID_CPE : ID_SCE,
539
1.41k
                                  pAacDecoderChannelInfo, nChannels,
540
1.41k
                                  pElementIdTab, nElements)) {
541
6
        return 0; /* element instance tag not in raw_data_block() */
542
6
      }
543
1.41k
    }
544
3.33k
    for (int el = 0; el < pce->NumBackChannelElements; el++) {
545
1.84k
      if (!findElementInstanceTag(pce->BackElementTagSelect[el],
546
1.84k
                                  pce->BackElementIsCpe[el] ? ID_CPE : ID_SCE,
547
1.84k
                                  pAacDecoderChannelInfo, nChannels,
548
1.84k
                                  pElementIdTab, nElements)) {
549
5
        return 0; /* element instance tag not in raw_data_block() */
550
5
      }
551
1.84k
    }
552
2.30k
    for (int el = 0; el < pce->NumLfeChannelElements; el++) {
553
811
      if (!findElementInstanceTag(pce->LfeElementTagSelect[el], ID_LFE,
554
811
                                  pAacDecoderChannelInfo, nChannels,
555
811
                                  pElementIdTab, nElements)) {
556
3
        return 0; /* element instance tag not in raw_data_block() */
557
3
      }
558
811
    }
559
1.49k
  } else {
560
4
    return 0; /* too less decoded audio channels */
561
4
  }
562
563
1.49k
  return 1; /* all element instance tags found in raw_data_block() */
564
1.51k
}
565
566
/*!
567
  \brief Read Program Config Element
568
569
  \bs Bitstream Handle
570
  \pTp Transport decoder handle for CRC handling
571
  \pce Pointer to PCE buffer
572
  \channelConfig Current channel configuration
573
  \alignAnchor Anchor for byte alignment
574
575
  \return  PCE status (-1: fail, 0: no new PCE, 1: PCE updated, 2: PCE updated
576
  need re-config).
577
*/
578
static int CProgramConfigElement_Read(HANDLE_FDK_BITSTREAM bs,
579
                                      HANDLE_TRANSPORTDEC pTp,
580
                                      CProgramConfig *pce,
581
                                      const UINT channelConfig,
582
1.48k
                                      const UINT alignAnchor) {
583
1.48k
  int pceStatus = 0;
584
1.48k
  int crcReg;
585
586
  /* read PCE to temporal buffer first */
587
1.48k
  C_ALLOC_SCRATCH_START(tmpPce, CProgramConfig, 1);
588
589
1.48k
  CProgramConfig_Init(tmpPce);
590
591
1.48k
  crcReg = transportDec_CrcStartReg(pTp, 0);
592
593
1.48k
  CProgramConfig_Read(tmpPce, bs, alignAnchor);
594
595
1.48k
  transportDec_CrcEndReg(pTp, crcReg);
596
597
1.48k
  if (CProgramConfig_IsValid(tmpPce) && (tmpPce->Profile == 1)) {
598
662
    if (!CProgramConfig_IsValid(pce) && (channelConfig > 0)) {
599
      /* Create a standard channel config PCE to compare with */
600
2
      CProgramConfig_GetDefault(pce, channelConfig);
601
2
    }
602
603
662
    if (CProgramConfig_IsValid(pce)) {
604
      /* Compare the new and the old PCE (tags ignored) */
605
662
      switch (CProgramConfig_Compare(pce, tmpPce)) {
606
257
        case 1: /* Channel configuration not changed. Just new metadata. */
607
257
          FDKmemcpy(pce, tmpPce,
608
257
                    sizeof(CProgramConfig)); /* Store the complete PCE */
609
257
          pceStatus = 1; /* New PCE but no change of config */
610
257
          break;
611
2
        case 2:  /* The number of channels are identical but not the config */
612
14
        case -1: /* The channel configuration is completely different */
613
14
          pceStatus = -1; /* Not supported! */
614
14
          break;
615
391
        case 0: /* Nothing to do because PCE matches the old one exactly. */
616
391
        default:
617
          /* pceStatus = 0; */
618
391
          break;
619
662
      }
620
662
    }
621
662
  }
622
623
1.48k
  C_ALLOC_SCRATCH_END(tmpPce, CProgramConfig, 1);
624
625
1.48k
  return pceStatus;
626
1.48k
}
627
628
/*!
629
  \brief Prepares crossfade for USAC DASH IPF config change
630
631
  \pTimeData             Pointer to time data
632
  \pTimeDataFlush        Pointer to flushed time data
633
  \numChannels           Number of channels
634
  \frameSize             Size of frame
635
  \interleaved           Indicates if time data is interleaved
636
637
  \return  Error code
638
*/
639
LINKSPEC_CPP AAC_DECODER_ERROR CAacDecoder_PrepareCrossFade(
640
    const PCM_DEC *pTimeData, PCM_DEC **pTimeDataFlush, const INT numChannels,
641
26
    const INT frameSize, const INT interleaved) {
642
26
  int i, ch, s1, s2;
643
26
  AAC_DECODER_ERROR ErrorStatus;
644
645
26
  ErrorStatus = AAC_DEC_OK;
646
647
26
  if (interleaved) {
648
26
    s1 = 1;
649
26
    s2 = numChannels;
650
26
  } else {
651
0
    s1 = frameSize;
652
0
    s2 = 1;
653
0
  }
654
655
52
  for (ch = 0; ch < numChannels; ch++) {
656
26
    const PCM_DEC *pIn = &pTimeData[ch * s1];
657
3.35k
    for (i = 0; i < TIME_DATA_FLUSH_SIZE; i++) {
658
3.32k
      pTimeDataFlush[ch][i] = *pIn;
659
3.32k
      pIn += s2;
660
3.32k
    }
661
26
  }
662
663
26
  return ErrorStatus;
664
26
}
665
666
/*!
667
  \brief Applies crossfade for USAC DASH IPF config change
668
669
  \pTimeData             Pointer to time data
670
  \pTimeDataFlush        Pointer to flushed time data
671
  \numChannels           Number of channels
672
  \frameSize             Size of frame
673
  \interleaved           Indicates if time data is interleaved
674
675
  \return  Error code
676
*/
677
LINKSPEC_CPP AAC_DECODER_ERROR CAacDecoder_ApplyCrossFade(
678
    PCM_DEC *pTimeData, PCM_DEC **pTimeDataFlush, const INT numChannels,
679
211
    const INT frameSize, const INT interleaved) {
680
211
  int i, ch, s1, s2;
681
211
  AAC_DECODER_ERROR ErrorStatus;
682
683
211
  ErrorStatus = AAC_DEC_OK;
684
685
211
  if (interleaved) {
686
204
    s1 = 1;
687
204
    s2 = numChannels;
688
204
  } else {
689
7
    s1 = frameSize;
690
7
    s2 = 1;
691
7
  }
692
693
443
  for (ch = 0; ch < numChannels; ch++) {
694
232
    PCM_DEC *pIn = &pTimeData[ch * s1];
695
29.9k
    for (i = 0; i < TIME_DATA_FLUSH_SIZE; i++) {
696
29.6k
      FIXP_SGL alpha = (FIXP_SGL)i
697
29.6k
                       << (FRACT_BITS - 1 - TIME_DATA_FLUSH_SIZE_SF);
698
29.6k
      FIXP_DBL time = PCM_DEC2FIXP_DBL(*pIn);
699
29.6k
      FIXP_DBL timeFlush = PCM_DEC2FIXP_DBL(pTimeDataFlush[ch][i]);
700
701
29.6k
      *pIn = FIXP_DBL2PCM_DEC(timeFlush - fMult(timeFlush, alpha) +
702
29.6k
                              fMult(time, alpha));
703
29.6k
      pIn += s2;
704
29.6k
    }
705
232
  }
706
707
211
  return ErrorStatus;
708
211
}
709
710
/*!
711
  \brief Parse PreRoll Extension Payload
712
713
  \self             Handle of AAC decoder
714
  \numPrerollAU     Number of preRoll AUs
715
  \prerollAUOffset  Offset to each preRoll AU
716
  \prerollAULength  Length of each preRoll AU
717
718
  \return  Error code
719
*/
720
LINKSPEC_CPP AAC_DECODER_ERROR CAacDecoder_PreRollExtensionPayloadParse(
721
    HANDLE_AACDECODER self, UINT *numPrerollAU, UINT *prerollAUOffset,
722
4.00k
    UINT *prerollAULength) {
723
4.00k
  FDK_BITSTREAM bs;
724
4.00k
  HANDLE_FDK_BITSTREAM hBs;
725
4.00k
  AAC_DECODER_ERROR ErrorStatus;
726
727
4.00k
  INT auStartAnchor;
728
4.00k
  UINT independencyFlag;
729
4.00k
  UINT extPayloadPresentFlag;
730
4.00k
  UINT useDefaultLengthFlag;
731
4.00k
  UINT configLength = 0;
732
4.00k
  UINT preRollPossible = 1;
733
4.00k
  UINT i;
734
4.00k
  UCHAR configChanged = 0;
735
4.00k
  UCHAR config[TP_USAC_MAX_CONFIG_LEN] = {0};
736
4.00k
  UCHAR
737
4.00k
  implicitExplicitCfgDiff = 0; /* in case implicit and explicit config is
738
                                  equal preroll AU's should be processed
739
                                  after decoder reset */
740
741
4.00k
  ErrorStatus = AAC_DEC_OK;
742
743
4.00k
  hBs = transportDec_GetBitstream(self->hInput, 0);
744
4.00k
  bs = *hBs;
745
746
4.00k
  auStartAnchor = (INT)FDKgetValidBits(hBs);
747
4.00k
  if (auStartAnchor <= 0) {
748
5
    ErrorStatus = AAC_DEC_NOT_ENOUGH_BITS;
749
5
    goto bail;
750
5
  }
751
752
  /* Independency flag */
753
4.00k
  FDKreadBit(hBs);
754
755
  /* Payload present flag of extension ID_EXT_ELE_AUDIOPREROLL must be one */
756
4.00k
  extPayloadPresentFlag = FDKreadBits(hBs, 1);
757
4.00k
  if (!extPayloadPresentFlag) {
758
1.41k
    preRollPossible = 0;
759
1.41k
  }
760
761
  /* Default length flag of extension ID_EXT_ELE_AUDIOPREROLL must be zero */
762
4.00k
  useDefaultLengthFlag = FDKreadBits(hBs, 1);
763
4.00k
  if (useDefaultLengthFlag) {
764
566
    preRollPossible = 0;
765
566
  }
766
767
4.00k
  if (preRollPossible) { /* extPayloadPresentFlag && !useDefaultLengthFlag */
768
    /* Read overall ext payload length, useDefaultLengthFlag must be zero.  */
769
2.43k
    escapedValue(hBs, 8, 16, 0);
770
771
    /* Read RSVD60 Config size */
772
2.43k
    configLength = escapedValue(hBs, 4, 4, 8);
773
774
    /* Avoid decoding pre roll frames if there was no config change and no
775
     * config is included in the pre roll ext payload. */
776
2.43k
  }
777
778
  /* If pre roll not possible then exit. */
779
4.00k
  if (preRollPossible == 0) {
780
    /* Sanity check: if flushing is switched on, preRollPossible must be 1 */
781
1.57k
    if (self->flushStatus != AACDEC_FLUSH_OFF) {
782
      /* Mismatch of current payload and flushing status */
783
0
      self->flushStatus = AACDEC_FLUSH_OFF;
784
0
      ErrorStatus = AAC_DEC_PARSE_ERROR;
785
0
    }
786
1.57k
    goto bail;
787
1.57k
  }
788
789
2.43k
  if (self->flags[0] & AC_USAC) {
790
1.41k
    if (configLength > 0) {
791
      /* DASH IPF USAC Config Change: Read new config and compare with current
792
       * config. Apply reconfiguration if config's are different. */
793
1.57k
      for (i = 0; i < configLength; i++) {
794
1.45k
        config[i] = FDKreadBits(hBs, 8);
795
1.45k
      }
796
116
      TRANSPORTDEC_ERROR terr;
797
116
      terr = transportDec_InBandConfig(self->hInput, config, configLength,
798
116
                                       self->buildUpStatus, &configChanged, 0,
799
116
                                       &implicitExplicitCfgDiff);
800
116
      if (terr != TRANSPORTDEC_OK) {
801
45
        ErrorStatus = AAC_DEC_PARSE_ERROR;
802
45
        goto bail;
803
45
      }
804
116
    }
805
1.41k
  }
806
807
  /* For the first frame buildUpStatus is not set and no flushing is performed
808
   * but preroll AU's should processed. */
809
  /* For USAC there is no idle state. */
810
2.38k
  if ((self->streamInfo.numChannels == 0) && !implicitExplicitCfgDiff &&
811
1.17k
      (self->flags[0] & AC_USAC)) {
812
1.15k
    self->buildUpStatus = AACDEC_USAC_BUILD_UP_ON;
813
    /* sanity check: if buildUp status on -> flushing must be off */
814
1.15k
    if (self->flushStatus != AACDEC_FLUSH_OFF) {
815
1
      self->flushStatus = AACDEC_FLUSH_OFF;
816
1
      ErrorStatus = AAC_DEC_PARSE_ERROR;
817
1
      goto bail;
818
1
    }
819
1.15k
  }
820
821
2.38k
  if (self->flags[0] & AC_USAC) {
822
    /* We are interested in preroll AUs if an explicit or an implicit config
823
     * change is signalized in other words if the build up status is set. */
824
1.37k
    if (self->buildUpStatus == AACDEC_USAC_BUILD_UP_ON) {
825
1.18k
      UCHAR applyCrossfade = FDKreadBit(hBs);
826
1.18k
      if (applyCrossfade) {
827
212
        self->applyCrossfade |= AACDEC_CROSSFADE_BITMASK_PREROLL;
828
969
      } else {
829
969
        self->applyCrossfade &= ~AACDEC_CROSSFADE_BITMASK_PREROLL;
830
969
      }
831
1.18k
      FDKreadBit(hBs); /* reserved */
832
      /* Read num preroll AU's */
833
1.18k
      *numPrerollAU = escapedValue(hBs, 2, 4, 0);
834
      /* check limits for USAC */
835
1.18k
      if (*numPrerollAU > AACDEC_MAX_NUM_PREROLL_AU_USAC) {
836
2
        *numPrerollAU = 0;
837
2
        ErrorStatus = AAC_DEC_PARSE_ERROR;
838
2
        goto bail;
839
2
      }
840
1.18k
    }
841
1.37k
  }
842
843
4.78k
  for (i = 0; i < *numPrerollAU; i++) {
844
    /* For every AU get length and offset in the bitstream */
845
2.41k
    prerollAULength[i] = escapedValue(hBs, 16, 16, 0);
846
2.41k
    if (prerollAULength[i] > 0) {
847
2.40k
      prerollAUOffset[i] = auStartAnchor - (INT)FDKgetValidBits(hBs);
848
2.40k
      independencyFlag = FDKreadBit(hBs);
849
2.40k
      if (i == 0 && !independencyFlag) {
850
1
        *numPrerollAU = 0;
851
1
        ErrorStatus = AAC_DEC_PARSE_ERROR;
852
1
        goto bail;
853
1
      }
854
2.40k
      FDKpushFor(hBs, prerollAULength[i] * 8 - 1);
855
2.40k
      self->prerollAULength[i] = (prerollAULength[i] * 8) + prerollAUOffset[i];
856
2.40k
    } else {
857
8
      *numPrerollAU = 0;
858
8
      ErrorStatus = AAC_DEC_PARSE_ERROR; /* Something is wrong */
859
8
      goto bail;
860
8
    }
861
2.41k
  }
862
863
4.00k
bail:
864
865
4.00k
  *hBs = bs;
866
867
4.00k
  return ErrorStatus;
868
2.38k
}
869
870
/*!
871
  \brief Parse Extension Payload
872
873
  \self Handle of AAC decoder
874
  \count Pointer to bit counter.
875
  \previous_element ID of previous element (required by some extension payloads)
876
877
  \return  Error code
878
*/
879
static AAC_DECODER_ERROR CAacDecoder_ExtPayloadParse(
880
    HANDLE_AACDECODER self, HANDLE_FDK_BITSTREAM hBs, int *count,
881
356k
    MP4_ELEMENT_ID previous_element, int elIndex, int fIsFillElement) {
882
356k
  AAC_DECODER_ERROR error = AAC_DEC_OK;
883
356k
  EXT_PAYLOAD_TYPE extension_type;
884
356k
  int bytes = (*count) >> 3;
885
356k
  int crcFlag = 0;
886
887
356k
  if (*count < 4) {
888
27
    return AAC_DEC_PARSE_ERROR;
889
356k
  } else if ((INT)FDKgetValidBits(hBs) < *count) {
890
236
    return AAC_DEC_DECODE_FRAME_ERROR;
891
236
  }
892
893
355k
  extension_type =
894
355k
      (EXT_PAYLOAD_TYPE)FDKreadBits(hBs, 4); /* bs_extension_type */
895
355k
  *count -= 4;
896
897
  /* For ELD, the SBR signaling is explicit and parsed in
898
     aacDecoder_ParseExplicitMpsAndSbr(), therefore skip SBR if implicit
899
     present. */
900
355k
  if ((self->flags[0] & AC_ELD) && ((extension_type == EXT_SBR_DATA_CRC) ||
901
108k
                                    (extension_type == EXT_SBR_DATA))) {
902
1.38k
    extension_type = EXT_FIL; /* skip sbr data */
903
1.38k
  }
904
905
355k
  switch (extension_type) {
906
109k
    case EXT_DYNAMIC_RANGE: {
907
109k
      INT readBits =
908
109k
          aacDecoder_drcMarkPayload(self->hDrcInfo, hBs, MPEG_DRC_EXT_DATA);
909
910
109k
      if (readBits > *count) { /* Read too much. Something went wrong! */
911
7.13k
        error = AAC_DEC_PARSE_ERROR;
912
7.13k
      }
913
109k
      *count -= readBits;
914
109k
    } break;
915
13.8k
    case EXT_LDSAC_DATA:
916
48.3k
    case EXT_SAC_DATA:
917
      /* Read MPEG Surround Extension payload */
918
48.3k
      {
919
48.3k
        int err, mpsSampleRate, mpsFrameSize;
920
921
48.3k
        if (self->flags[0] & AC_PS_PRESENT) {
922
97
          error = AAC_DEC_PARSE_ERROR;
923
97
          goto bail;
924
97
        }
925
926
        /* Handle SBR dual rate case */
927
48.2k
        if (self->streamInfo.extSamplingRate != 0) {
928
40.9k
          mpsSampleRate = self->streamInfo.extSamplingRate;
929
40.9k
          mpsFrameSize = self->streamInfo.aacSamplesPerFrame *
930
40.9k
                         (self->streamInfo.extSamplingRate /
931
40.9k
                          self->streamInfo.aacSampleRate);
932
40.9k
        } else {
933
7.30k
          mpsSampleRate = self->streamInfo.aacSampleRate;
934
7.30k
          mpsFrameSize = self->streamInfo.aacSamplesPerFrame;
935
7.30k
        }
936
        /* Setting of internal MPS state; may be reset in
937
           CAacDecoder_SyncQmfMode if decoder is unable to decode with user
938
           defined qmfMode */
939
48.2k
        if (!(self->flags[0] & (AC_USAC | AC_RSVD50 | AC_ELD))) {
940
7.30k
          self->mpsEnableCurr = self->mpsEnableUser;
941
7.30k
        }
942
48.2k
        if (self->mpsEnableCurr) {
943
40.1k
          if (!self->qmfDomain.globalConf.qmfDomainExplicitConfig) {
944
            /* if not done yet, allocate full MPEG Surround decoder instance */
945
1.30k
            if (mpegSurroundDecoder_IsFullMpegSurroundDecoderInstanceAvailable(
946
1.30k
                    (CMpegSurroundDecoder *)self->pMpegSurroundDecoder) ==
947
1.30k
                SAC_INSTANCE_NOT_FULL_AVAILABLE) {
948
444
              if (mpegSurroundDecoder_Open(
949
444
                      (CMpegSurroundDecoder **)&self->pMpegSurroundDecoder, -1,
950
444
                      &self->qmfDomain)) {
951
0
                return AAC_DEC_OUT_OF_MEMORY;
952
0
              }
953
444
            }
954
1.30k
          }
955
40.1k
          err = mpegSurroundDecoder_Parse(
956
40.1k
              (CMpegSurroundDecoder *)self->pMpegSurroundDecoder, hBs, count,
957
40.1k
              self->streamInfo.aot, mpsSampleRate, mpsFrameSize,
958
40.1k
              self->flags[0] & AC_INDEP);
959
40.1k
          if (err == MPS_OK) {
960
24.3k
            self->flags[0] |= AC_MPS_PRESENT;
961
24.3k
          } else {
962
15.8k
            error = AAC_DEC_PARSE_ERROR;
963
15.8k
          }
964
40.1k
        }
965
        /* Skip any trailing bytes */
966
48.2k
        FDKpushFor(hBs, *count);
967
48.2k
        *count = 0;
968
48.2k
      }
969
0
      break;
970
971
15.7k
    case EXT_SBR_DATA_CRC:
972
15.7k
      crcFlag = 1;
973
15.7k
      FDK_FALLTHROUGH;
974
45.3k
    case EXT_SBR_DATA:
975
45.3k
      if (IS_CHANNEL_ELEMENT(previous_element)) {
976
45.0k
        SBR_ERROR sbrError;
977
45.0k
        UCHAR configMode = 0;
978
45.0k
        UCHAR configChanged = 0;
979
980
45.0k
        CAacDecoder_SyncQmfMode(self);
981
982
45.0k
        configMode |= AC_CM_ALLOC_MEM;
983
984
45.0k
        sbrError = sbrDecoder_InitElement(
985
45.0k
            self->hSbrDecoder, self->streamInfo.aacSampleRate,
986
45.0k
            self->streamInfo.extSamplingRate,
987
45.0k
            self->streamInfo.aacSamplesPerFrame, self->streamInfo.aot,
988
45.0k
            previous_element, elIndex,
989
45.0k
            2, /* Signalize that harmonicSBR shall be ignored in the config
990
                  change detection */
991
45.0k
            0, configMode, &configChanged, self->downscaleFactor);
992
993
45.0k
        if (sbrError == SBRDEC_OK) {
994
44.2k
          sbrError = sbrDecoder_Parse(self->hSbrDecoder, hBs,
995
44.2k
                                      self->pDrmBsBuffer, self->drmBsBufferSize,
996
44.2k
                                      count, *count, crcFlag, previous_element,
997
44.2k
                                      elIndex, self->flags[0], self->elFlags);
998
          /* Enable SBR for implicit SBR signalling but only if no severe error
999
           * happend. */
1000
44.2k
          if ((sbrError == SBRDEC_OK) || (sbrError == SBRDEC_PARSE_ERROR)) {
1001
44.2k
            self->sbrEnabled = 1;
1002
44.2k
          }
1003
44.2k
        } else {
1004
          /* Do not try to apply SBR because initializing the element failed. */
1005
762
          self->sbrEnabled = 0;
1006
762
        }
1007
        /* Citation from ISO/IEC 14496-3 chapter 4.5.2.1.5.2
1008
        Fill elements containing an extension_payload() with an extension_type
1009
        of EXT_SBR_DATA or EXT_SBR_DATA_CRC shall not contain any other
1010
        extension_payload of any other extension_type.
1011
        */
1012
45.0k
        if (fIsFillElement) {
1013
36.0k
          FDKpushBiDirectional(hBs, *count);
1014
36.0k
          *count = 0;
1015
36.0k
        } else {
1016
          /* If this is not a fill element with a known length, we are screwed
1017
           * and further parsing makes no sense. */
1018
9.02k
          if (sbrError != SBRDEC_OK) {
1019
1.84k
            self->frameOK = 0;
1020
1.84k
          }
1021
9.02k
        }
1022
45.0k
      } else {
1023
289
        error = AAC_DEC_PARSE_ERROR;
1024
289
      }
1025
45.3k
      break;
1026
1027
830
    case EXT_FILL_DATA: {
1028
830
      int temp;
1029
1030
830
      temp = FDKreadBits(hBs, 4);
1031
830
      bytes--;
1032
830
      if (temp != 0) {
1033
255
        error = AAC_DEC_PARSE_ERROR;
1034
255
        break;
1035
255
      }
1036
1.60k
      while (bytes > 0) {
1037
1.29k
        temp = FDKreadBits(hBs, 8);
1038
1.29k
        bytes--;
1039
1.29k
        if (temp != 0xa5) {
1040
270
          error = AAC_DEC_PARSE_ERROR;
1041
270
          break;
1042
270
        }
1043
1.29k
      }
1044
575
      *count = bytes << 3;
1045
575
    } break;
1046
1047
1.06k
    case EXT_DATA_ELEMENT: {
1048
1.06k
      int dataElementVersion;
1049
1050
1.06k
      dataElementVersion = FDKreadBits(hBs, 4);
1051
1.06k
      *count -= 4;
1052
1.06k
      if (dataElementVersion == 0) /* ANC_DATA */
1053
725
      {
1054
725
        int temp, dataElementLength = 0;
1055
51.0k
        do {
1056
51.0k
          temp = FDKreadBits(hBs, 8);
1057
51.0k
          *count -= 8;
1058
51.0k
          dataElementLength += temp;
1059
51.0k
        } while (temp == 255);
1060
1061
725
        CAacDecoder_AncDataParse(&self->ancData, hBs, dataElementLength);
1062
725
        *count -= (dataElementLength << 3);
1063
725
      } else {
1064
        /* align = 0 */
1065
340
        error = AAC_DEC_PARSE_ERROR;
1066
340
        goto bail;
1067
340
      }
1068
1.06k
    } break;
1069
1070
74.2k
    case EXT_DATA_LENGTH:
1071
74.2k
      if (!fIsFillElement /* Makes no sens to have an additional length in a
1072
                             fill ...   */
1073
74.2k
          &&
1074
74.2k
          (self->flags[0] &
1075
74.2k
           AC_ER)) /* ... element because this extension payload type was ... */
1076
74.2k
      { /* ... created to circumvent the missing length in ER-Syntax. */
1077
74.2k
        int bitCnt, len = FDKreadBits(hBs, 4);
1078
74.2k
        *count -= 4;
1079
1080
74.2k
        if (len == 15) {
1081
4.62k
          int add_len = FDKreadBits(hBs, 8);
1082
4.62k
          *count -= 8;
1083
4.62k
          len += add_len;
1084
1085
4.62k
          if (add_len == 255) {
1086
75
            len += FDKreadBits(hBs, 16);
1087
75
            *count -= 16;
1088
75
          }
1089
4.62k
        }
1090
74.2k
        len <<= 3;
1091
74.2k
        bitCnt = len;
1092
1093
74.2k
        if ((EXT_PAYLOAD_TYPE)FDKreadBits(hBs, 4) == EXT_DATA_LENGTH) {
1094
          /* Check NOTE 2: The extension_payload() included here must
1095
                           not have extension_type == EXT_DATA_LENGTH. */
1096
24
          error = AAC_DEC_PARSE_ERROR;
1097
24
          goto bail;
1098
74.2k
        } else {
1099
          /* rewind and call myself again. */
1100
74.2k
          FDKpushBack(hBs, 4);
1101
1102
74.2k
          error = CAacDecoder_ExtPayloadParse(
1103
74.2k
              self, hBs, &bitCnt, previous_element, elIndex,
1104
74.2k
              1); /* Treat same as fill element */
1105
1106
74.2k
          *count -= len - bitCnt;
1107
74.2k
        }
1108
        /* Note: the fall through in case the if statement above is not taken is
1109
         * intentional. */
1110
74.2k
        break;
1111
74.2k
      }
1112
40
      FDK_FALLTHROUGH;
1113
1114
37.9k
    case EXT_FIL:
1115
1116
76.9k
    default:
1117
      /* align = 4 */
1118
76.9k
      FDKpushFor(hBs, *count);
1119
76.9k
      *count = 0;
1120
76.9k
      break;
1121
355k
  }
1122
1123
355k
bail:
1124
355k
  if ((error != AAC_DEC_OK) &&
1125
24.4k
      fIsFillElement) { /* Skip the remaining extension bytes */
1126
23.9k
    FDKpushBiDirectional(hBs, *count);
1127
23.9k
    *count = 0;
1128
    /* Patch error code because decoding can go on. */
1129
23.9k
    error = AAC_DEC_OK;
1130
    /* Be sure that parsing errors have been stored. */
1131
23.9k
  }
1132
355k
  return error;
1133
355k
}
1134
1135
static AAC_DECODER_ERROR aacDecoder_ParseExplicitMpsAndSbr(
1136
    HANDLE_AACDECODER self, HANDLE_FDK_BITSTREAM bs,
1137
    const MP4_ELEMENT_ID previous_element, const int previous_element_index,
1138
398k
    const int element_index, const int el_cnt[]) {
1139
398k
  AAC_DECODER_ERROR ErrorStatus = AAC_DEC_OK;
1140
398k
  INT bitCnt = 0;
1141
1142
  /* get the remaining bits of this frame */
1143
398k
  bitCnt = transportDec_GetAuBitsRemaining(self->hInput, 0);
1144
1145
398k
  if ((self->flags[0] & AC_SBR_PRESENT) &&
1146
281k
      (self->flags[0] & (AC_USAC | AC_RSVD50 | AC_ELD | AC_DRM))) {
1147
266k
    SBR_ERROR err = SBRDEC_OK;
1148
266k
    int chElIdx, numChElements = el_cnt[ID_SCE] + el_cnt[ID_CPE] +
1149
266k
                                 el_cnt[ID_LFE] + el_cnt[ID_USAC_SCE] +
1150
266k
                                 el_cnt[ID_USAC_CPE] + el_cnt[ID_USAC_LFE];
1151
266k
    INT bitCntTmp = bitCnt;
1152
1153
266k
    if (self->flags[0] & AC_USAC) {
1154
235k
      chElIdx = numChElements - 1;
1155
235k
    } else {
1156
30.8k
      chElIdx = 0; /* ELD case */
1157
30.8k
    }
1158
1159
586k
    for (; chElIdx < numChElements; chElIdx += 1) {
1160
320k
      MP4_ELEMENT_ID sbrType;
1161
320k
      SBR_ERROR errTmp;
1162
320k
      if (self->flags[0] & (AC_USAC)) {
1163
235k
        FDK_ASSERT((self->elements[element_index] == ID_USAC_SCE) ||
1164
235k
                   (self->elements[element_index] == ID_USAC_CPE));
1165
235k
        sbrType = IS_STEREO_SBR(self->elements[element_index],
1166
235k
                                self->usacStereoConfigIndex[element_index])
1167
235k
                      ? ID_CPE
1168
235k
                      : ID_SCE;
1169
235k
      } else
1170
84.5k
        sbrType = self->elements[chElIdx];
1171
320k
      errTmp = sbrDecoder_Parse(self->hSbrDecoder, bs, self->pDrmBsBuffer,
1172
320k
                                self->drmBsBufferSize, &bitCnt, -1,
1173
320k
                                self->flags[0] & AC_SBRCRC, sbrType, chElIdx,
1174
320k
                                self->flags[0], self->elFlags);
1175
320k
      if (errTmp != SBRDEC_OK) {
1176
70.2k
        err = errTmp;
1177
70.2k
        bitCntTmp = bitCnt;
1178
70.2k
        bitCnt = 0;
1179
70.2k
      }
1180
320k
    }
1181
266k
    switch (err) {
1182
70.2k
      case SBRDEC_PARSE_ERROR:
1183
        /* Can not go on parsing because we do not
1184
            know the length of the SBR extension data. */
1185
70.2k
        FDKpushFor(bs, bitCntTmp);
1186
70.2k
        bitCnt = 0;
1187
70.2k
        break;
1188
196k
      case SBRDEC_OK:
1189
196k
        self->sbrEnabled = 1;
1190
196k
        break;
1191
0
      default:
1192
0
        self->frameOK = 0;
1193
0
        break;
1194
266k
    }
1195
266k
  }
1196
1197
398k
  if ((bitCnt > 0) && (self->flags[0] & (AC_USAC | AC_RSVD50))) {
1198
214k
    if ((self->flags[0] & AC_MPS_PRESENT) ||
1199
120k
        (self->elFlags[element_index] & AC_EL_USAC_MPS212)) {
1200
120k
      int err;
1201
1202
120k
      err = mpegSurroundDecoder_ParseNoHeader(
1203
120k
          (CMpegSurroundDecoder *)self->pMpegSurroundDecoder, bs, &bitCnt,
1204
120k
          self->flags[0] & AC_INDEP);
1205
120k
      if (err != MPS_OK) {
1206
386
        self->frameOK = 0;
1207
386
        ErrorStatus = AAC_DEC_PARSE_ERROR;
1208
386
      }
1209
120k
    }
1210
214k
  }
1211
1212
398k
  if (self->flags[0] & AC_DRM) {
1213
0
    if ((bitCnt = (INT)FDKgetValidBits(bs)) != 0) {
1214
0
      FDKpushBiDirectional(bs, bitCnt);
1215
0
    }
1216
0
  }
1217
1218
398k
  if (!(self->flags[0] & (AC_USAC | AC_RSVD50 | AC_DRM))) {
1219
405k
    while (bitCnt > 7) {
1220
274k
      ErrorStatus = CAacDecoder_ExtPayloadParse(
1221
274k
          self, bs, &bitCnt, previous_element, previous_element_index, 0);
1222
274k
      if (ErrorStatus != AAC_DEC_OK) {
1223
518
        self->frameOK = 0;
1224
518
        ErrorStatus = AAC_DEC_PARSE_ERROR;
1225
518
        break;
1226
518
      }
1227
274k
    }
1228
130k
  }
1229
398k
  return ErrorStatus;
1230
398k
}
1231
1232
/*  Stream Configuration and Information.
1233
1234
    This class holds configuration and information data for a stream to be
1235
   decoded. It provides the calling application as well as the decoder with
1236
   substantial information, e.g. profile, sampling rate, number of channels
1237
   found in the bitstream etc.
1238
*/
1239
26.6k
static void CStreamInfoInit(CStreamInfo *pStreamInfo) {
1240
26.6k
  pStreamInfo->aacSampleRate = 0;
1241
26.6k
  pStreamInfo->profile = -1;
1242
26.6k
  pStreamInfo->aot = AOT_NONE;
1243
1244
26.6k
  pStreamInfo->channelConfig = -1;
1245
26.6k
  pStreamInfo->bitRate = 0;
1246
26.6k
  pStreamInfo->aacSamplesPerFrame = 0;
1247
1248
26.6k
  pStreamInfo->extAot = AOT_NONE;
1249
26.6k
  pStreamInfo->extSamplingRate = 0;
1250
1251
26.6k
  pStreamInfo->flags = 0;
1252
1253
26.6k
  pStreamInfo->epConfig = -1; /* default: no ER */
1254
1255
26.6k
  pStreamInfo->numChannels = 0;
1256
26.6k
  pStreamInfo->sampleRate = 0;
1257
26.6k
  pStreamInfo->frameSize = 0;
1258
1259
26.6k
  pStreamInfo->outputDelay = 0;
1260
1261
  /* DRC */
1262
26.6k
  pStreamInfo->drcProgRefLev =
1263
26.6k
      -1; /* set program reference level to not indicated */
1264
26.6k
  pStreamInfo->drcPresMode = -1; /* default: presentation mode not indicated */
1265
1266
26.6k
  pStreamInfo->outputLoudness = -1; /* default: no loudness metadata present */
1267
26.6k
}
1268
1269
/*!
1270
  \brief Initialization of AacDecoderChannelInfo
1271
1272
  The function initializes the pointers to AacDecoderChannelInfo for each
1273
  channel, set the start values for window shape and window sequence of
1274
  overlap&add to zero, set the overlap buffer to zero and initializes the
1275
  pointers to the window coefficients. \param bsFormat is the format of the AAC
1276
  bitstream
1277
1278
  \return  AACDECODER instance
1279
*/
1280
LINKSPEC_CPP HANDLE_AACDECODER CAacDecoder_Open(
1281
    TRANSPORT_TYPE bsFormat) /*!< bitstream format (adif,adts,loas,...). */
1282
26.6k
{
1283
26.6k
  HANDLE_AACDECODER self;
1284
1285
26.6k
  self = GetAacDecoder();
1286
26.6k
  if (self == NULL) {
1287
0
    goto bail;
1288
0
  }
1289
1290
26.6k
  FDK_QmfDomain_ClearRequested(&self->qmfDomain.globalConf);
1291
1292
  /* Assign channel mapping info arrays (doing so removes dependency of settings
1293
   * header in API header). */
1294
26.6k
  self->streamInfo.pChannelIndices = self->channelIndices;
1295
26.6k
  self->streamInfo.pChannelType = self->channelType;
1296
26.6k
  self->downscaleFactor = 1;
1297
26.6k
  self->downscaleFactorInBS = 1;
1298
1299
  /* initialize anc data */
1300
26.6k
  CAacDecoder_AncDataInit(&self->ancData, NULL, 0);
1301
1302
  /* initialize stream info */
1303
26.6k
  CStreamInfoInit(&self->streamInfo);
1304
1305
  /* initialize progam config */
1306
26.6k
  CProgramConfig_Init(&self->pce);
1307
1308
  /* initialize error concealment common data */
1309
26.6k
  CConcealment_InitCommonData(&self->concealCommonData);
1310
26.6k
  self->concealMethodUser = ConcealMethodNone; /* undefined -> auto mode */
1311
1312
26.6k
  self->hDrcInfo = GetDrcInfo();
1313
26.6k
  if (self->hDrcInfo == NULL) {
1314
0
    goto bail;
1315
0
  }
1316
  /* Init common DRC structure */
1317
26.6k
  aacDecoder_drcInit(self->hDrcInfo);
1318
  /* Set default frame delay */
1319
26.6k
  aacDecoder_drcSetParam(self->hDrcInfo, DRC_BS_DELAY,
1320
26.6k
                         CConcealment_GetDelay(&self->concealCommonData));
1321
26.6k
  self->workBufferCore1 = (FIXP_DBL *)GetWorkBufferCore1();
1322
1323
26.6k
  self->workBufferCore2 = GetWorkBufferCore2();
1324
26.6k
  if (self->workBufferCore2 == NULL) goto bail;
1325
1326
  /* When RSVD60 is active use dedicated memory for core decoding */
1327
26.6k
  self->pTimeData2 = GetWorkBufferCore5();
1328
26.6k
  self->timeData2Size = GetRequiredMemWorkBufferCore5();
1329
26.6k
  if (self->pTimeData2 == NULL) {
1330
0
    goto bail;
1331
0
  }
1332
1333
26.6k
  return self;
1334
1335
0
bail:
1336
0
  CAacDecoder_Close(self);
1337
1338
0
  return NULL;
1339
26.6k
}
1340
1341
/* Revert CAacDecoder_Init() */
1342
static void CAacDecoder_DeInit(HANDLE_AACDECODER self,
1343
170k
                               const int subStreamIndex) {
1344
170k
  int ch;
1345
170k
  int aacChannelOffset = 0, aacChannels = (8);
1346
170k
  int numElements = (3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) + 1),
1347
170k
      elementOffset = 0;
1348
1349
170k
  if (self == NULL) return;
1350
1351
170k
  {
1352
170k
    self->ascChannels[0] = 0;
1353
170k
    self->elements[0] = ID_END;
1354
170k
  }
1355
1356
1.53M
  for (ch = aacChannelOffset; ch < aacChannelOffset + aacChannels; ch++) {
1357
1.36M
    if (self->pAacDecoderChannelInfo[ch] != NULL) {
1358
649k
      if (self->pAacDecoderChannelInfo[ch]->pComStaticData != NULL) {
1359
418k
        if (self->pAacDecoderChannelInfo[ch]
1360
418k
                ->pComStaticData->pWorkBufferCore1 != NULL) {
1361
418k
          if (ch == aacChannelOffset) {
1362
136k
            FreeWorkBufferCore1(&self->pAacDecoderChannelInfo[ch]
1363
136k
                                     ->pComStaticData->pWorkBufferCore1);
1364
136k
          }
1365
418k
        }
1366
418k
        if (self->pAacDecoderChannelInfo[ch]
1367
418k
                ->pComStaticData->cplxPredictionData != NULL) {
1368
8.30k
          FreeCplxPredictionData(&self->pAacDecoderChannelInfo[ch]
1369
8.30k
                                      ->pComStaticData->cplxPredictionData);
1370
8.30k
        }
1371
        /* Avoid double free of linked pComStaticData in case of CPE by settings
1372
         * pointer to NULL. */
1373
418k
        if (ch < (8) - 1) {
1374
355k
          if ((self->pAacDecoderChannelInfo[ch + 1] != NULL) &&
1375
311k
              (self->pAacDecoderChannelInfo[ch + 1]->pComStaticData ==
1376
311k
               self->pAacDecoderChannelInfo[ch]->pComStaticData)) {
1377
231k
            self->pAacDecoderChannelInfo[ch + 1]->pComStaticData = NULL;
1378
231k
          }
1379
355k
        }
1380
418k
        FDKfree(self->pAacDecoderChannelInfo[ch]->pComStaticData);
1381
418k
        self->pAacDecoderChannelInfo[ch]->pComStaticData = NULL;
1382
418k
      }
1383
649k
      if (self->pAacDecoderChannelInfo[ch]->pComData != NULL) {
1384
        /* Avoid double free of linked pComData in case of CPE by settings
1385
         * pointer to NULL. */
1386
418k
        if (ch < (8) - 1) {
1387
355k
          if ((self->pAacDecoderChannelInfo[ch + 1] != NULL) &&
1388
311k
              (self->pAacDecoderChannelInfo[ch + 1]->pComData ==
1389
311k
               self->pAacDecoderChannelInfo[ch]->pComData)) {
1390
231k
            self->pAacDecoderChannelInfo[ch + 1]->pComData = NULL;
1391
231k
          }
1392
355k
        }
1393
418k
        if (ch == aacChannelOffset) {
1394
136k
          FreeWorkBufferCore6(
1395
136k
              (SCHAR **)&self->pAacDecoderChannelInfo[ch]->pComData);
1396
282k
        } else {
1397
282k
          FDKafree(self->pAacDecoderChannelInfo[ch]->pComData);
1398
282k
        }
1399
418k
        self->pAacDecoderChannelInfo[ch]->pComData = NULL;
1400
418k
      }
1401
649k
    }
1402
1.36M
    if (self->pAacDecoderStaticChannelInfo[ch] != NULL) {
1403
649k
      if (self->pAacDecoderStaticChannelInfo[ch]->pOverlapBuffer != NULL) {
1404
649k
        FreeOverlapBuffer(
1405
649k
            &self->pAacDecoderStaticChannelInfo[ch]->pOverlapBuffer);
1406
649k
      }
1407
649k
      if (self->pAacDecoderStaticChannelInfo[ch]->hArCo != NULL) {
1408
59.0k
        CArco_Destroy(self->pAacDecoderStaticChannelInfo[ch]->hArCo);
1409
59.0k
      }
1410
649k
      FreeAacDecoderStaticChannelInfo(&self->pAacDecoderStaticChannelInfo[ch]);
1411
649k
    }
1412
1.36M
    if (self->pAacDecoderChannelInfo[ch] != NULL) {
1413
649k
      FreeAacDecoderChannelInfo(&self->pAacDecoderChannelInfo[ch]);
1414
649k
    }
1415
1.36M
  }
1416
1417
170k
  {
1418
170k
    int el;
1419
10.5M
    for (el = elementOffset; el < elementOffset + numElements; el++) {
1420
10.3M
      if (self->cpeStaticData[el] != NULL) {
1421
8.30k
        FreeCpePersistentData(&self->cpeStaticData[el]);
1422
8.30k
      }
1423
10.3M
    }
1424
170k
  }
1425
1426
170k
  FDK_Delay_Destroy(&self->usacResidualDelay);
1427
1428
170k
  self->aacChannels = 0;
1429
170k
  self->streamInfo.aacSampleRate = 0;
1430
170k
  self->streamInfo.sampleRate = 0;
1431
  /* This samplerate value is checked for configuration change, not the others
1432
   * above. */
1433
170k
  self->samplingRateInfo[subStreamIndex].samplingRate = 0;
1434
170k
}
1435
1436
/*!
1437
 * \brief CAacDecoder_AcceptFlags Accept flags and element flags
1438
 *
1439
 * \param self          [o]   handle to AACDECODER structure
1440
 * \param asc           [i]   handle to ASC structure
1441
 * \param flags         [i]   flags
1442
 * \param elFlags       [i]   pointer to element flags
1443
 * \param streamIndex   [i]   stream index
1444
 * \param elementOffset [i]   element offset
1445
 *
1446
 * \return void
1447
 */
1448
static void CAacDecoder_AcceptFlags(HANDLE_AACDECODER self,
1449
                                    const CSAudioSpecificConfig *asc,
1450
                                    UINT flags, UINT *elFlags, int streamIndex,
1451
465k
                                    int elementOffset) {
1452
465k
  FDKmemcpy(self->elFlags, elFlags, sizeof(self->elFlags));
1453
1454
465k
  self->flags[streamIndex] = flags;
1455
465k
}
1456
1457
/*!
1458
 * \brief CAacDecoder_CtrlCFGChange Set config change parameters.
1459
 *
1460
 * \param self           [i]   handle to AACDECODER structure
1461
 * \param flushStatus    [i]   flush status: on|off
1462
 * \param flushCnt       [i]   flush frame counter
1463
 * \param buildUpStatus  [i]   build up status: on|off
1464
 * \param buildUpCnt     [i]   build up frame counter
1465
 *
1466
 * \return error
1467
 */
1468
LINKSPEC_CPP AAC_DECODER_ERROR CAacDecoder_CtrlCFGChange(HANDLE_AACDECODER self,
1469
                                                         UCHAR flushStatus,
1470
                                                         SCHAR flushCnt,
1471
                                                         UCHAR buildUpStatus,
1472
98
                                                         SCHAR buildUpCnt) {
1473
98
  AAC_DECODER_ERROR err = AAC_DEC_OK;
1474
1475
98
  self->flushStatus = flushStatus;
1476
98
  self->flushCnt = flushCnt;
1477
98
  self->buildUpStatus = buildUpStatus;
1478
98
  self->buildUpCnt = buildUpCnt;
1479
1480
98
  return (err);
1481
98
}
1482
1483
/*!
1484
 * \brief CAacDecoder_FreeMem Free config dependent AAC memory.
1485
 *
1486
 * \param self       [i]   handle to AACDECODER structure
1487
 *
1488
 * \return error
1489
 */
1490
LINKSPEC_CPP AAC_DECODER_ERROR CAacDecoder_FreeMem(HANDLE_AACDECODER self,
1491
143k
                                                   const int subStreamIndex) {
1492
143k
  AAC_DECODER_ERROR err = AAC_DEC_OK;
1493
1494
143k
  CAacDecoder_DeInit(self, subStreamIndex);
1495
1496
143k
  return (err);
1497
143k
}
1498
1499
/* Destroy aac decoder */
1500
26.6k
LINKSPEC_CPP void CAacDecoder_Close(HANDLE_AACDECODER self) {
1501
26.6k
  if (self == NULL) return;
1502
1503
26.6k
  CAacDecoder_DeInit(self, 0);
1504
1505
26.6k
  {
1506
26.6k
    int ch;
1507
239k
    for (ch = 0; ch < (8); ch++) {
1508
213k
      if (self->pTimeDataFlush[ch] != NULL) {
1509
19.0k
        FreeTimeDataFlush(&self->pTimeDataFlush[ch]);
1510
19.0k
      }
1511
213k
    }
1512
26.6k
  }
1513
1514
26.6k
  if (self->hDrcInfo) {
1515
26.6k
    FreeDrcInfo(&self->hDrcInfo);
1516
26.6k
  }
1517
1518
26.6k
  if (self->workBufferCore1 != NULL) {
1519
26.6k
    FreeWorkBufferCore1((CWorkBufferCore1 **)&self->workBufferCore1);
1520
26.6k
  }
1521
1522
  /* Free WorkBufferCore2 */
1523
26.6k
  if (self->workBufferCore2 != NULL) {
1524
26.6k
    FreeWorkBufferCore2(&self->workBufferCore2);
1525
26.6k
  }
1526
26.6k
  if (self->pTimeData2 != NULL) {
1527
26.6k
    FreeWorkBufferCore5(&self->pTimeData2);
1528
26.6k
  }
1529
1530
26.6k
  FDK_QmfDomain_Close(&self->qmfDomain);
1531
1532
26.6k
  FreeAacDecoder(&self);
1533
26.6k
}
1534
1535
/*!
1536
  \brief Initialization of decoder instance
1537
1538
  The function initializes the decoder.
1539
1540
  \return  error status: 0 for success, <>0 for unsupported configurations
1541
*/
1542
LINKSPEC_CPP AAC_DECODER_ERROR
1543
CAacDecoder_Init(HANDLE_AACDECODER self, const CSAudioSpecificConfig *asc,
1544
475k
                 UCHAR configMode, UCHAR *configChanged) {
1545
475k
  AAC_DECODER_ERROR err = AAC_DEC_OK;
1546
475k
  INT ascChannels, ascChanged = 0;
1547
475k
  AACDEC_RENDER_MODE initRenderMode = AACDEC_RENDER_INVALID;
1548
475k
  SCHAR usacStereoConfigIndex = -1;
1549
475k
  int usacResidualDelayCompSamples = 0;
1550
475k
  int elementOffset, aacChannelsOffset, aacChannelsOffsetIdx;
1551
475k
  const int streamIndex = 0;
1552
475k
  INT flushChannels = 0;
1553
1554
475k
  UINT flags;
1555
  /* elFlags[(3*MAX_CHANNELS + (MAX_CHANNELS)/2 + 4 * (MAX_TRACKS) + 1]
1556
     where MAX_CHANNELS is (8*2) and MAX_TRACKS is 1 */
1557
475k
  UINT elFlags[(3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) + 1)];
1558
1559
475k
  UCHAR sbrEnabled = self->sbrEnabled;
1560
475k
  UCHAR sbrEnabledPrev = self->sbrEnabledPrev;
1561
475k
  UCHAR mpsEnableCurr = self->mpsEnableCurr;
1562
1563
475k
  if (!self) return AAC_DEC_INVALID_HANDLE;
1564
1565
475k
  UCHAR downscaleFactor = self->downscaleFactor;
1566
475k
  UCHAR downscaleFactorInBS = self->downscaleFactorInBS;
1567
1568
475k
  self->aacOutDataHeadroom = (3);
1569
1570
  // set profile and check for supported aot
1571
  // leave profile on default (=-1) for all other supported MPEG-4 aot's except
1572
  // aot=2 (=AAC-LC)
1573
475k
  switch (asc->m_aot) {
1574
150k
    case AOT_AAC_LC:
1575
150k
      self->streamInfo.profile = 1;
1576
150k
      FDK_FALLTHROUGH;
1577
202k
    case AOT_ER_AAC_SCAL:
1578
202k
      if (asc->m_sc.m_gaSpecificConfig.m_layer > 0) {
1579
        /* aac_scalable_extension_element() currently not supported. */
1580
211
        return AAC_DEC_UNSUPPORTED_FORMAT;
1581
211
      }
1582
202k
      FDK_FALLTHROUGH;
1583
202k
    case AOT_SBR:
1584
202k
    case AOT_PS:
1585
203k
    case AOT_ER_AAC_LC:
1586
212k
    case AOT_ER_AAC_LD:
1587
212k
    case AOT_DRM_AAC:
1588
212k
    case AOT_DRM_SURROUND:
1589
212k
      initRenderMode = AACDEC_RENDER_IMDCT;
1590
212k
      break;
1591
104k
    case AOT_ER_AAC_ELD:
1592
104k
      initRenderMode = AACDEC_RENDER_ELDFB;
1593
104k
      break;
1594
157k
    case AOT_USAC:
1595
157k
      initRenderMode = AACDEC_RENDER_IMDCT;
1596
157k
      break;
1597
976
    default:
1598
976
      return AAC_DEC_UNSUPPORTED_AOT;
1599
475k
  }
1600
1601
474k
  if (CProgramConfig_IsValid(&self->pce) && (asc->m_channelConfiguration > 0)) {
1602
    /* Compare the stored (old) PCE with a default PCE created from the (new)
1603
       channel_config (on a temporal buffer) to find out wheter we can keep it
1604
       (and its metadata) or not. */
1605
30.0k
    int pceCmpResult;
1606
30.0k
    C_ALLOC_SCRATCH_START(tmpPce, CProgramConfig, 1);
1607
1608
30.0k
    CProgramConfig_GetDefault(tmpPce, asc->m_channelConfiguration);
1609
30.0k
    pceCmpResult = CProgramConfig_Compare(&self->pce, tmpPce);
1610
30.0k
    if ((pceCmpResult < 0) /* Reset if PCEs are completely different ... */
1611
28.5k
        ||
1612
29.4k
        (pceCmpResult > 1)) { /*            ... or have a different layout. */
1613
29.4k
      CProgramConfig_Init(&self->pce);
1614
29.4k
    } /* Otherwise keep the PCE (and its metadata). */
1615
30.0k
    C_ALLOC_SCRATCH_END(tmpPce, CProgramConfig, 1);
1616
444k
  } else {
1617
444k
    CProgramConfig_Init(&self->pce);
1618
444k
  }
1619
1620
  /* set channels */
1621
474k
  switch (asc->m_channelConfiguration) {
1622
74.8k
    case 0:
1623
74.8k
      switch (asc->m_aot) {
1624
0
        case AOT_USAC:
1625
0
          self->chMapIndex = 0;
1626
0
          ascChannels = asc->m_sc.m_usacConfig.m_nUsacChannels;
1627
0
          break;
1628
74.8k
        default:
1629
          /* get channels from program config (ASC) */
1630
74.8k
          if (CProgramConfig_IsValid(&asc->m_progrConfigElement)) {
1631
68.5k
            ascChannels = asc->m_progrConfigElement.NumChannels;
1632
68.5k
            if (ascChannels > 0) {
1633
68.0k
              int el_tmp;
1634
              /* valid number of channels -> copy program config element (PCE)
1635
               * from ASC */
1636
68.0k
              FDKmemcpy(&self->pce, &asc->m_progrConfigElement,
1637
68.0k
                        sizeof(CProgramConfig));
1638
              /* Built element table */
1639
68.0k
              el_tmp = CProgramConfig_GetElementTable(
1640
68.0k
                  &asc->m_progrConfigElement, self->elements, (((8)) + (8)),
1641
68.0k
                  &self->chMapIndex);
1642
3.88M
              for (; el_tmp < (3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) + 1);
1643
3.82M
                   el_tmp++) {
1644
3.82M
                self->elements[el_tmp] = ID_NONE;
1645
3.82M
              }
1646
68.0k
            } else {
1647
527
              return AAC_DEC_UNSUPPORTED_CHANNELCONFIG;
1648
527
            }
1649
68.5k
          } else {
1650
6.30k
            self->chMapIndex = 0;
1651
6.30k
            return AAC_DEC_UNSUPPORTED_CHANNELCONFIG;
1652
6.30k
          }
1653
68.0k
          break;
1654
74.8k
      }
1655
68.0k
      break;
1656
90.7k
    case 1:
1657
261k
    case 2:
1658
262k
    case 3:
1659
265k
    case 4:
1660
267k
    case 5:
1661
268k
    case 6:
1662
268k
      ascChannels = asc->m_channelConfiguration;
1663
268k
      break;
1664
11.0k
    case 11:
1665
11.0k
      ascChannels = 7;
1666
11.0k
      break;
1667
85.4k
    case 7:
1668
93.2k
    case 12:
1669
118k
    case 14:
1670
118k
      ascChannels = 8;
1671
118k
      break;
1672
1.37k
    default:
1673
1.37k
      return AAC_DEC_UNSUPPORTED_CHANNELCONFIG;
1674
474k
  }
1675
1676
466k
  if (asc->m_aot == AOT_USAC) {
1677
157k
    flushChannels = fMin(ascChannels, (8));
1678
157k
    INT numChannel;
1679
157k
    pcmDmx_GetParam(self->hPcmUtils, MIN_NUMBER_OF_OUTPUT_CHANNELS,
1680
157k
                    &numChannel);
1681
157k
    flushChannels = fMin(fMax(numChannel, flushChannels), (8));
1682
157k
  }
1683
1684
466k
  if (IS_USAC(asc->m_aot)) {
1685
333k
    for (int el = 0; el < (INT)asc->m_sc.m_usacConfig.m_usacNumElements; el++) {
1686
      /* fix number of core channels aka ascChannels for stereoConfigIndex = 1
1687
       * cases */
1688
176k
      if (asc->m_sc.m_usacConfig.element[el].m_stereoConfigIndex == 1) {
1689
37.3k
        ascChannels--; /* stereoConfigIndex == 1 stereo cases do actually
1690
                          contain only a mono core channel. */
1691
138k
      } else if (asc->m_sc.m_usacConfig.element[el].m_stereoConfigIndex == 2) {
1692
        /* In this case it is necessary to follow up the DMX signal delay caused
1693
           by HBE also with the residual signal (2nd core channel). The SBR
1694
           overlap delay is not regarded here, this is handled by the MPS212
1695
           implementation.
1696
        */
1697
3.58k
        if (asc->m_sc.m_usacConfig.element[el].m_harmonicSBR) {
1698
661
          usacResidualDelayCompSamples += asc->m_samplesPerFrame;
1699
661
        }
1700
3.58k
        if (asc->m_sc.m_usacConfig.m_coreSbrFrameLengthIndex == 4) {
1701
925
          usacResidualDelayCompSamples +=
1702
925
              6 * 16; /* difference between 12 SBR
1703
                         overlap slots from SBR and 6
1704
                         slots delayed in MPS212 */
1705
925
        }
1706
3.58k
      }
1707
176k
    }
1708
157k
  }
1709
1710
466k
  aacChannelsOffset = 0;
1711
466k
  aacChannelsOffsetIdx = 0;
1712
466k
  elementOffset = 0;
1713
466k
  if ((ascChannels <= 0) || (ascChannels > (8)) ||
1714
465k
      (asc->m_channelConfiguration > AACDEC_MAX_CH_CONF)) {
1715
460
    return AAC_DEC_UNSUPPORTED_CHANNELCONFIG;
1716
460
  }
1717
1718
  /* Set syntax flags */
1719
465k
  flags = 0;
1720
465k
  { FDKmemclear(elFlags, sizeof(elFlags)); }
1721
1722
465k
  if ((asc->m_channelConfiguration > 0) || IS_USAC(asc->m_aot)) {
1723
398k
    if (IS_USAC(asc->m_aot)) {
1724
      /* copy pointer to usac config
1725
        (this is preliminary since there's an ongoing discussion about storing
1726
        the config-part of the bitstream rather than the complete decoded
1727
        configuration) */
1728
157k
      self->pUsacConfig[streamIndex] = &asc->m_sc.m_usacConfig;
1729
1730
      /* copy list of elements */
1731
157k
      if (self->pUsacConfig[streamIndex]->m_usacNumElements >
1732
157k
          (3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) + 1)) {
1733
0
        goto bail;
1734
0
      }
1735
1736
157k
      if (self->numUsacElements[streamIndex] !=
1737
157k
          asc->m_sc.m_usacConfig.m_usacNumElements) {
1738
28.8k
        ascChanged = 1;
1739
28.8k
      }
1740
1741
157k
      if (configMode & AC_CM_ALLOC_MEM) {
1742
77.7k
        self->numUsacElements[streamIndex] =
1743
77.7k
            asc->m_sc.m_usacConfig.m_usacNumElements;
1744
77.7k
      }
1745
1746
157k
      mpsEnableCurr = 0;
1747
157k
      for (int _el = 0;
1748
333k
           _el < (int)self->pUsacConfig[streamIndex]->m_usacNumElements;
1749
176k
           _el++) {
1750
176k
        int el = _el + elementOffset;
1751
176k
        if (self->elements[el] !=
1752
176k
            self->pUsacConfig[streamIndex]->element[_el].usacElementType) {
1753
63.3k
          ascChanged = 1;
1754
63.3k
        }
1755
176k
        if (self->usacStereoConfigIndex[el] !=
1756
176k
            asc->m_sc.m_usacConfig.element[_el].m_stereoConfigIndex) {
1757
12.6k
          ascChanged = 1;
1758
12.6k
        }
1759
176k
        if (configMode & AC_CM_ALLOC_MEM) {
1760
87.0k
          self->elements[el] =
1761
87.0k
              self->pUsacConfig[streamIndex]->element[_el].usacElementType;
1762
          /* for Unified Stereo Coding */
1763
87.0k
          self->usacStereoConfigIndex[el] =
1764
87.0k
              asc->m_sc.m_usacConfig.element[_el].m_stereoConfigIndex;
1765
87.0k
          if (self->elements[el] == ID_USAC_CPE) {
1766
57.1k
            mpsEnableCurr |= self->usacStereoConfigIndex[el] ? 1 : 0;
1767
57.1k
          }
1768
87.0k
        }
1769
1770
176k
        elFlags[el] |= (asc->m_sc.m_usacConfig.element[_el].m_noiseFilling)
1771
176k
                           ? AC_EL_USAC_NOISE
1772
176k
                           : 0;
1773
176k
        elFlags[el] |=
1774
176k
            (asc->m_sc.m_usacConfig.element[_el].m_stereoConfigIndex > 0)
1775
176k
                ? AC_EL_USAC_MPS212
1776
176k
                : 0;
1777
176k
        elFlags[el] |= (asc->m_sc.m_usacConfig.element[_el].m_interTes)
1778
176k
                           ? AC_EL_USAC_ITES
1779
176k
                           : 0;
1780
176k
        elFlags[el] |=
1781
176k
            (asc->m_sc.m_usacConfig.element[_el].m_pvc) ? AC_EL_USAC_PVC : 0;
1782
176k
        elFlags[el] |=
1783
176k
            (asc->m_sc.m_usacConfig.element[_el].usacElementType == ID_USAC_LFE)
1784
176k
                ? AC_EL_USAC_LFE
1785
176k
                : 0;
1786
176k
        elFlags[el] |=
1787
176k
            (asc->m_sc.m_usacConfig.element[_el].usacElementType == ID_USAC_LFE)
1788
176k
                ? AC_EL_LFE
1789
176k
                : 0;
1790
176k
        if ((asc->m_sc.m_usacConfig.element[_el].usacElementType ==
1791
176k
             ID_USAC_CPE) &&
1792
116k
            ((self->usacStereoConfigIndex[el] == 0))) {
1793
56.1k
          elFlags[el] |= AC_EL_USAC_CP_POSSIBLE;
1794
56.1k
        }
1795
176k
      }
1796
1797
157k
      self->hasAudioPreRoll = 0;
1798
157k
      if (self->pUsacConfig[streamIndex]->m_usacNumElements) {
1799
157k
        self->hasAudioPreRoll = asc->m_sc.m_usacConfig.element[0]
1800
157k
                                    .extElement.usacExtElementHasAudioPreRoll;
1801
157k
      }
1802
157k
      if (configMode & AC_CM_ALLOC_MEM) {
1803
77.7k
        self->elements[elementOffset +
1804
77.7k
                       self->pUsacConfig[streamIndex]->m_usacNumElements] =
1805
77.7k
            ID_END;
1806
77.7k
      }
1807
240k
    } else {
1808
      /* Initialize constant mappings for channel config 1-7 */
1809
240k
      int i;
1810
1.92M
      for (i = 0; i < AACDEC_CH_ELEMENTS_TAB_SIZE; i++) {
1811
1.68M
        self->elements[i] = elementsTab[asc->m_channelConfiguration - 1][i];
1812
1.68M
      }
1813
13.2M
      for (; i < (3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) + 1); i++) {
1814
13.0M
        self->elements[i] = ID_NONE;
1815
13.0M
      }
1816
240k
    }
1817
1818
398k
    {
1819
398k
      int ch;
1820
1821
1.85M
      for (ch = 0; ch < ascChannels; ch++) {
1822
1.45M
        self->chMapping[ch] = ch;
1823
1.45M
      }
1824
2.13M
      for (; ch < (8); ch++) {
1825
1.73M
        self->chMapping[ch] = 255;
1826
1.73M
      }
1827
398k
    }
1828
1829
398k
    self->chMapIndex = asc->m_channelConfiguration;
1830
398k
  } else {
1831
67.5k
    if (CProgramConfig_IsValid(&asc->m_progrConfigElement)) {
1832
      /* Set matrix mixdown infos if available from PCE. */
1833
67.5k
      pcmDmx_SetMatrixMixdownFromPce(
1834
67.5k
          self->hPcmUtils, asc->m_progrConfigElement.MatrixMixdownIndexPresent,
1835
67.5k
          asc->m_progrConfigElement.MatrixMixdownIndex,
1836
67.5k
          asc->m_progrConfigElement.PseudoSurroundEnable);
1837
67.5k
    }
1838
67.5k
  }
1839
1840
465k
  self->streamInfo.channelConfig = asc->m_channelConfiguration;
1841
1842
465k
  if (self->streamInfo.aot != asc->m_aot) {
1843
60.7k
    if (configMode & AC_CM_ALLOC_MEM) {
1844
27.7k
      self->streamInfo.aot = asc->m_aot;
1845
27.7k
    }
1846
60.7k
    ascChanged = 1;
1847
60.7k
  }
1848
1849
465k
  if (asc->m_aot == AOT_ER_AAC_ELD &&
1850
104k
      asc->m_sc.m_eldSpecificConfig.m_downscaledSamplingFrequency != 0) {
1851
104k
    if (self->samplingRateInfo[0].samplingRate !=
1852
104k
            asc->m_sc.m_eldSpecificConfig.m_downscaledSamplingFrequency ||
1853
61.8k
        self->samplingRateInfo[0].samplingRate * self->downscaleFactor !=
1854
61.8k
            asc->m_samplingFrequency) {
1855
      /* get downscaledSamplingFrequency from ESC and compute the downscale
1856
       * factor */
1857
43.0k
      downscaleFactorInBS =
1858
43.0k
          asc->m_samplingFrequency /
1859
43.0k
          asc->m_sc.m_eldSpecificConfig.m_downscaledSamplingFrequency;
1860
43.0k
      if ((downscaleFactorInBS == 1 || downscaleFactorInBS == 2 ||
1861
2.90k
           (downscaleFactorInBS == 3 &&
1862
1.07k
            asc->m_sc.m_eldSpecificConfig.m_frameLengthFlag) ||
1863
2.02k
           downscaleFactorInBS == 4) &&
1864
42.1k
          ((asc->m_samplingFrequency %
1865
42.1k
            asc->m_sc.m_eldSpecificConfig.m_downscaledSamplingFrequency) ==
1866
42.1k
           0)) {
1867
41.8k
        downscaleFactor = downscaleFactorInBS;
1868
41.8k
      } else {
1869
1.18k
        downscaleFactorInBS = 1;
1870
1.18k
        downscaleFactor = 1;
1871
1.18k
      }
1872
43.0k
    }
1873
361k
  } else {
1874
361k
    downscaleFactorInBS = 1;
1875
361k
    downscaleFactor = 1;
1876
361k
  }
1877
1878
465k
  if (self->downscaleFactorInBS != downscaleFactorInBS) {
1879
2.04k
    if (configMode & AC_CM_ALLOC_MEM) {
1880
884
      self->downscaleFactorInBS = downscaleFactorInBS;
1881
884
      self->downscaleFactor = downscaleFactor;
1882
884
    }
1883
2.04k
    ascChanged = 1;
1884
2.04k
  }
1885
1886
465k
  if ((INT)asc->m_samplesPerFrame % downscaleFactor != 0) {
1887
0
    return AAC_DEC_UNSUPPORTED_SAMPLINGRATE; /* frameSize/dsf must be an integer
1888
                                                number */
1889
0
  }
1890
1891
465k
  self->streamInfo.bitRate = 0;
1892
1893
465k
  if (asc->m_aot == AOT_ER_AAC_ELD) {
1894
104k
    if (self->useLdQmfTimeAlign !=
1895
104k
        asc->m_sc.m_eldSpecificConfig.m_useLdQmfTimeAlign) {
1896
11.3k
      ascChanged = 1;
1897
11.3k
    }
1898
104k
    if (configMode & AC_CM_ALLOC_MEM) {
1899
48.9k
      self->useLdQmfTimeAlign =
1900
48.9k
          asc->m_sc.m_eldSpecificConfig.m_useLdQmfTimeAlign;
1901
48.9k
    }
1902
104k
    if (sbrEnabled != asc->m_sbrPresentFlag) {
1903
15.5k
      ascChanged = 1;
1904
15.5k
    }
1905
104k
  }
1906
1907
465k
  self->streamInfo.extAot = asc->m_extensionAudioObjectType;
1908
465k
  if (self->streamInfo.extSamplingRate !=
1909
465k
      (INT)asc->m_extensionSamplingFrequency) {
1910
87.5k
    ascChanged = 1;
1911
87.5k
  }
1912
465k
  if (configMode & AC_CM_ALLOC_MEM) {
1913
228k
    self->streamInfo.extSamplingRate = asc->m_extensionSamplingFrequency;
1914
228k
  }
1915
465k
  flags |= (asc->m_sbrPresentFlag) ? AC_SBR_PRESENT : 0;
1916
465k
  flags |= (asc->m_psPresentFlag) ? AC_PS_PRESENT : 0;
1917
465k
  if (asc->m_sbrPresentFlag) {
1918
188k
    sbrEnabled = 1;
1919
188k
    sbrEnabledPrev = 1;
1920
277k
  } else {
1921
277k
    sbrEnabled = 0;
1922
277k
    sbrEnabledPrev = 0;
1923
277k
  }
1924
465k
  if (sbrEnabled && asc->m_extensionSamplingFrequency) {
1925
188k
    if (downscaleFactor != 1 && (downscaleFactor)&1) {
1926
0
      return AAC_DEC_UNSUPPORTED_SAMPLINGRATE; /* SBR needs an even downscale
1927
                                                  factor */
1928
0
    }
1929
188k
    if (configMode & AC_CM_ALLOC_MEM) {
1930
90.1k
      self->streamInfo.extSamplingRate =
1931
90.1k
          self->streamInfo.extSamplingRate / self->downscaleFactor;
1932
90.1k
    }
1933
188k
  }
1934
465k
  if ((asc->m_aot == AOT_AAC_LC) && (asc->m_sbrPresentFlag == 1) &&
1935
3.19k
      (asc->m_extensionSamplingFrequency > (2 * asc->m_samplingFrequency))) {
1936
269
    return AAC_DEC_UNSUPPORTED_SAMPLINGRATE; /* Core decoder supports at most a
1937
                                                1:2 upsampling for HE-AAC and
1938
                                                HE-AACv2 */
1939
269
  }
1940
1941
  /* --------- vcb11 ------------ */
1942
465k
  flags |= (asc->m_vcb11Flag) ? AC_ER_VCB11 : 0;
1943
1944
  /* ---------- rvlc ------------ */
1945
465k
  flags |= (asc->m_rvlcFlag) ? AC_ER_RVLC : 0;
1946
1947
  /* ----------- hcr ------------ */
1948
465k
  flags |= (asc->m_hcrFlag) ? AC_ER_HCR : 0;
1949
1950
465k
  if (asc->m_aot == AOT_ER_AAC_ELD) {
1951
104k
    mpsEnableCurr = 0;
1952
104k
    flags |= AC_ELD;
1953
104k
    flags |= (asc->m_sbrPresentFlag)
1954
104k
                 ? AC_SBR_PRESENT
1955
104k
                 : 0; /* Need to set the SBR flag for backward-compatibility
1956
                               reasons. Even if SBR is not supported. */
1957
104k
    flags |= (asc->m_sc.m_eldSpecificConfig.m_sbrCrcFlag) ? AC_SBRCRC : 0;
1958
104k
    flags |= (asc->m_sc.m_eldSpecificConfig.m_useLdQmfTimeAlign)
1959
104k
                 ? AC_MPS_PRESENT
1960
104k
                 : 0;
1961
104k
    if (self->mpsApplicable) {
1962
27.2k
      mpsEnableCurr = asc->m_sc.m_eldSpecificConfig.m_useLdQmfTimeAlign;
1963
27.2k
    }
1964
104k
  }
1965
465k
  flags |= (asc->m_aot == AOT_ER_AAC_LD) ? AC_LD : 0;
1966
465k
  flags |= (asc->m_epConfig >= 0) ? AC_ER : 0;
1967
1968
465k
  if (asc->m_aot == AOT_USAC) {
1969
157k
    flags |= AC_USAC;
1970
157k
    flags |= (asc->m_sc.m_usacConfig.element[0].m_stereoConfigIndex > 0)
1971
157k
                 ? AC_MPS_PRESENT
1972
157k
                 : 0;
1973
157k
  }
1974
465k
  if (asc->m_aot == AOT_DRM_AAC) {
1975
0
    flags |= AC_DRM | AC_SBRCRC | AC_SCALABLE;
1976
0
  }
1977
465k
  if (asc->m_aot == AOT_DRM_SURROUND) {
1978
0
    flags |= AC_DRM | AC_SBRCRC | AC_SCALABLE | AC_MPS_PRESENT;
1979
0
    FDK_ASSERT(!asc->m_psPresentFlag);
1980
0
  }
1981
465k
  if ((asc->m_aot == AOT_AAC_SCAL) || (asc->m_aot == AOT_ER_AAC_SCAL)) {
1982
52.4k
    flags |= AC_SCALABLE;
1983
52.4k
  }
1984
1985
465k
  if ((asc->m_epConfig >= 0) && (asc->m_channelConfiguration <= 0)) {
1986
    /* we have to know the number of channels otherwise no decoding is possible
1987
     */
1988
0
    return AAC_DEC_UNSUPPORTED_ER_FORMAT;
1989
0
  }
1990
1991
465k
  self->streamInfo.epConfig = asc->m_epConfig;
1992
  /* self->hInput->asc.m_epConfig = asc->m_epConfig; */
1993
1994
465k
  if (asc->m_epConfig > 1) return AAC_DEC_UNSUPPORTED_ER_FORMAT;
1995
1996
  /* Check if samplerate changed. */
1997
465k
  if ((self->samplingRateInfo[streamIndex].samplingRate !=
1998
465k
       asc->m_samplingFrequency) ||
1999
266k
      (self->streamInfo.aacSamplesPerFrame !=
2000
266k
       (INT)asc->m_samplesPerFrame / downscaleFactor)) {
2001
264k
    AAC_DECODER_ERROR error;
2002
2003
264k
    ascChanged = 1;
2004
2005
264k
    if (configMode & AC_CM_ALLOC_MEM) {
2006
      /* Update samplerate info. */
2007
136k
      error = getSamplingRateInfo(
2008
136k
          &self->samplingRateInfo[streamIndex], asc->m_samplesPerFrame,
2009
136k
          asc->m_samplingFrequencyIndex, asc->m_samplingFrequency);
2010
136k
      if (error != AAC_DEC_OK) {
2011
0
        return error;
2012
0
      }
2013
136k
      self->streamInfo.aacSampleRate =
2014
136k
          self->samplingRateInfo[0].samplingRate / self->downscaleFactor;
2015
136k
      self->streamInfo.aacSamplesPerFrame =
2016
136k
          asc->m_samplesPerFrame / self->downscaleFactor;
2017
136k
      if (self->streamInfo.aacSampleRate <= 0) {
2018
0
        return AAC_DEC_UNSUPPORTED_SAMPLINGRATE;
2019
0
      }
2020
136k
    }
2021
264k
  }
2022
2023
  /* Check if amount of channels has changed. */
2024
465k
  if (self->ascChannels[streamIndex] != ascChannels) {
2025
175k
    ascChanged = 1;
2026
175k
  }
2027
2028
  /* detect config change */
2029
465k
  if (configMode & AC_CM_DET_CFG_CHANGE) {
2030
237k
    if (ascChanged != 0) {
2031
138k
      *configChanged = 1;
2032
138k
    }
2033
2034
237k
    CAacDecoder_AcceptFlags(self, asc, flags, elFlags, streamIndex,
2035
237k
                            elementOffset);
2036
2037
237k
    return err;
2038
237k
  }
2039
2040
  /* set AC_USAC_SCFGI3 globally if any usac element uses */
2041
228k
  switch (asc->m_aot) {
2042
77.7k
    case AOT_USAC:
2043
77.7k
      if (sbrEnabled) {
2044
62.1k
        for (int _el = 0;
2045
131k
             _el < (int)self->pUsacConfig[streamIndex]->m_usacNumElements;
2046
69.5k
             _el++) {
2047
69.5k
          int el = elementOffset + _el;
2048
69.5k
          if (IS_USAC_CHANNEL_ELEMENT(self->elements[el])) {
2049
62.1k
            if (usacStereoConfigIndex < 0) {
2050
62.1k
              usacStereoConfigIndex = self->usacStereoConfigIndex[el];
2051
62.1k
            } else {
2052
0
              if ((usacStereoConfigIndex != self->usacStereoConfigIndex[el]) ||
2053
0
                  (self->usacStereoConfigIndex[el] > 0)) {
2054
0
                goto bail;
2055
0
              }
2056
0
            }
2057
62.1k
          }
2058
69.5k
        }
2059
2060
62.1k
        if (usacStereoConfigIndex < 0) {
2061
0
          goto bail;
2062
0
        }
2063
2064
62.1k
        if (usacStereoConfigIndex == 3) {
2065
11.2k
          flags |= AC_USAC_SCFGI3;
2066
11.2k
        }
2067
62.1k
      }
2068
77.7k
      break;
2069
150k
    default:
2070
150k
      break;
2071
228k
  }
2072
2073
228k
  if (*configChanged) {
2074
    /* Set up QMF domain for AOTs with explicit signalling of SBR and or MPS.
2075
       This is to be able to play out the first frame alway with the correct
2076
       frame size and sampling rate even in case of concealment.
2077
    */
2078
136k
    switch (asc->m_aot) {
2079
40.2k
      case AOT_USAC:
2080
40.2k
        if (sbrEnabled) {
2081
34.1k
          const UCHAR map_sbrRatio_2_nAnaBands[] = {16, 24, 32};
2082
2083
34.1k
          FDK_ASSERT(asc->m_sc.m_usacConfig.m_sbrRatioIndex > 0);
2084
34.1k
          FDK_ASSERT(streamIndex == 0);
2085
2086
34.1k
          self->qmfDomain.globalConf.nInputChannels_requested = ascChannels;
2087
34.1k
          self->qmfDomain.globalConf.nOutputChannels_requested =
2088
34.1k
              (usacStereoConfigIndex == 1) ? 2 : ascChannels;
2089
34.1k
          self->qmfDomain.globalConf.flags_requested = 0;
2090
34.1k
          self->qmfDomain.globalConf.nBandsAnalysis_requested =
2091
34.1k
              map_sbrRatio_2_nAnaBands[asc->m_sc.m_usacConfig.m_sbrRatioIndex -
2092
34.1k
                                       1];
2093
34.1k
          self->qmfDomain.globalConf.nBandsSynthesis_requested = 64;
2094
34.1k
          self->qmfDomain.globalConf.nQmfTimeSlots_requested =
2095
34.1k
              (asc->m_sc.m_usacConfig.m_sbrRatioIndex == 1) ? 64 : 32;
2096
34.1k
          self->qmfDomain.globalConf.nQmfOvTimeSlots_requested =
2097
34.1k
              (asc->m_sc.m_usacConfig.m_sbrRatioIndex == 1) ? 12 : 6;
2098
34.1k
          self->qmfDomain.globalConf.nQmfProcBands_requested = 64;
2099
34.1k
          self->qmfDomain.globalConf.nQmfProcChannels_requested = 1;
2100
34.1k
          self->qmfDomain.globalConf.parkChannel =
2101
34.1k
              (usacStereoConfigIndex == 3) ? 1 : 0;
2102
34.1k
          self->qmfDomain.globalConf.parkChannel_requested =
2103
34.1k
              (usacStereoConfigIndex == 3) ? 1 : 0;
2104
34.1k
          self->qmfDomain.globalConf.qmfDomainExplicitConfig = 1;
2105
34.1k
        }
2106
40.2k
        break;
2107
40.2k
      case AOT_ER_AAC_ELD:
2108
25.0k
        if (mpsEnableCurr &&
2109
6.82k
            asc->m_sc.m_eldSpecificConfig.m_useLdQmfTimeAlign) {
2110
6.82k
          SAC_INPUT_CONFIG sac_interface = (sbrEnabled && self->hSbrDecoder)
2111
6.82k
                                               ? SAC_INTERFACE_QMF
2112
6.82k
                                               : SAC_INTERFACE_TIME;
2113
6.82k
          mpegSurroundDecoder_ConfigureQmfDomain(
2114
6.82k
              (CMpegSurroundDecoder *)self->pMpegSurroundDecoder, sac_interface,
2115
6.82k
              (UINT)self->streamInfo.aacSampleRate, asc->m_aot);
2116
6.82k
          self->qmfDomain.globalConf.qmfDomainExplicitConfig = 1;
2117
6.82k
        }
2118
25.0k
        break;
2119
70.7k
      default:
2120
70.7k
        self->qmfDomain.globalConf.qmfDomainExplicitConfig =
2121
70.7k
            0; /* qmfDomain is initialized by SBR and MPS init functions if
2122
                  required */
2123
70.7k
        break;
2124
136k
    }
2125
2126
    /* Allocate all memory structures for each channel */
2127
136k
    {
2128
136k
      int ch = aacChannelsOffset;
2129
785k
      for (int _ch = 0; _ch < ascChannels; _ch++) {
2130
649k
        if (ch >= (8)) {
2131
0
          goto bail;
2132
0
        }
2133
649k
        self->pAacDecoderChannelInfo[ch] = GetAacDecoderChannelInfo(ch);
2134
        /* This is temporary until the DynamicData is split into two or more
2135
           regions! The memory could be reused after completed core decoding. */
2136
649k
        if (self->pAacDecoderChannelInfo[ch] == NULL) {
2137
0
          goto bail;
2138
0
        }
2139
649k
        ch++;
2140
649k
      }
2141
2142
136k
      int chIdx = aacChannelsOffsetIdx;
2143
136k
      ch = aacChannelsOffset;
2144
136k
      int _numElements;
2145
136k
      _numElements = (((8)) + (8));
2146
136k
      if (flags & (AC_RSV603DA | AC_USAC)) {
2147
40.2k
        _numElements = (int)asc->m_sc.m_usacConfig.m_usacNumElements;
2148
40.2k
      }
2149
927k
      for (int _el = 0; _el < _numElements; _el++) {
2150
861k
        int el_channels = 0;
2151
861k
        int el = elementOffset + _el;
2152
2153
861k
        if (flags &
2154
861k
            (AC_ER | AC_LD | AC_ELD | AC_RSV603DA | AC_USAC | AC_RSVD50)) {
2155
157k
          if (ch >= ascChannels) {
2156
38.8k
            break;
2157
38.8k
          }
2158
157k
        }
2159
2160
822k
        switch (self->elements[el]) {
2161
95.3k
          case ID_SCE:
2162
307k
          case ID_CPE:
2163
377k
          case ID_LFE:
2164
393k
          case ID_USAC_SCE:
2165
418k
          case ID_USAC_CPE:
2166
418k
          case ID_USAC_LFE:
2167
2168
418k
            el_channels = CAacDecoder_GetELChannels(
2169
418k
                self->elements[el], self->usacStereoConfigIndex[el]);
2170
2171
418k
            {
2172
418k
              self->pAacDecoderChannelInfo[ch]->pComStaticData =
2173
418k
                  (CAacDecoderCommonStaticData *)FDKcalloc(
2174
418k
                      1, sizeof(CAacDecoderCommonStaticData));
2175
418k
              if (self->pAacDecoderChannelInfo[ch]->pComStaticData == NULL) {
2176
0
                goto bail;
2177
0
              }
2178
418k
              if (ch == aacChannelsOffset) {
2179
136k
                self->pAacDecoderChannelInfo[ch]->pComData =
2180
136k
                    (CAacDecoderCommonData *)GetWorkBufferCore6();
2181
136k
                self->pAacDecoderChannelInfo[ch]
2182
136k
                    ->pComStaticData->pWorkBufferCore1 = GetWorkBufferCore1();
2183
282k
              } else {
2184
282k
                self->pAacDecoderChannelInfo[ch]->pComData =
2185
282k
                    (CAacDecoderCommonData *)FDKaalloc(
2186
282k
                        sizeof(CAacDecoderCommonData), ALIGNMENT_DEFAULT);
2187
282k
                self->pAacDecoderChannelInfo[ch]
2188
282k
                    ->pComStaticData->pWorkBufferCore1 =
2189
282k
                    self->pAacDecoderChannelInfo[aacChannelsOffset]
2190
282k
                        ->pComStaticData->pWorkBufferCore1;
2191
282k
              }
2192
418k
              if ((self->pAacDecoderChannelInfo[ch]->pComData == NULL) ||
2193
418k
                  (self->pAacDecoderChannelInfo[ch]
2194
418k
                       ->pComStaticData->pWorkBufferCore1 == NULL)) {
2195
0
                goto bail;
2196
0
              }
2197
418k
              self->pAacDecoderChannelInfo[ch]->pDynData =
2198
418k
                  &(self->pAacDecoderChannelInfo[ch]
2199
418k
                        ->pComData->pAacDecoderDynamicData[0]);
2200
418k
              self->pAacDecoderChannelInfo[ch]->pSpectralCoefficient =
2201
418k
                  (SPECTRAL_PTR)&self->workBufferCore2[ch * 1024];
2202
2203
418k
              if (el_channels == 2) {
2204
231k
                if (ch >= (8) - 1) {
2205
0
                  return AAC_DEC_UNSUPPORTED_CHANNELCONFIG;
2206
0
                }
2207
231k
                self->pAacDecoderChannelInfo[ch + 1]->pComData =
2208
231k
                    self->pAacDecoderChannelInfo[ch]->pComData;
2209
231k
                self->pAacDecoderChannelInfo[ch + 1]->pComStaticData =
2210
231k
                    self->pAacDecoderChannelInfo[ch]->pComStaticData;
2211
231k
                self->pAacDecoderChannelInfo[ch + 1]
2212
231k
                    ->pComStaticData->pWorkBufferCore1 =
2213
231k
                    self->pAacDecoderChannelInfo[ch]
2214
231k
                        ->pComStaticData->pWorkBufferCore1;
2215
231k
                self->pAacDecoderChannelInfo[ch + 1]->pDynData =
2216
231k
                    &(self->pAacDecoderChannelInfo[ch]
2217
231k
                          ->pComData->pAacDecoderDynamicData[1]);
2218
231k
                self->pAacDecoderChannelInfo[ch + 1]->pSpectralCoefficient =
2219
231k
                    (SPECTRAL_PTR)&self->workBufferCore2[(ch + 1) * 1024];
2220
231k
              }
2221
2222
418k
              ch += el_channels;
2223
418k
            }
2224
0
            chIdx += el_channels;
2225
418k
            break;
2226
2227
404k
          default:
2228
404k
            break;
2229
822k
        }
2230
2231
822k
        if (self->elements[el] == ID_END) {
2232
31.5k
          break;
2233
31.5k
        }
2234
2235
791k
        el++;
2236
791k
      }
2237
2238
136k
      chIdx = aacChannelsOffsetIdx;
2239
136k
      ch = aacChannelsOffset;
2240
785k
      for (int _ch = 0; _ch < ascChannels; _ch++) {
2241
        /* Allocate persistent channel memory */
2242
649k
        {
2243
649k
          self->pAacDecoderStaticChannelInfo[ch] =
2244
649k
              GetAacDecoderStaticChannelInfo(ch);
2245
649k
          if (self->pAacDecoderStaticChannelInfo[ch] == NULL) {
2246
0
            goto bail;
2247
0
          }
2248
649k
          self->pAacDecoderStaticChannelInfo[ch]->pOverlapBuffer =
2249
649k
              GetOverlapBuffer(ch); /* This area size depends on the AOT */
2250
649k
          if (self->pAacDecoderStaticChannelInfo[ch]->pOverlapBuffer == NULL) {
2251
0
            goto bail;
2252
0
          }
2253
649k
          if (flags & (AC_USAC | AC_RSVD50 | AC_RSV603DA /*|AC_BSAC*/)) {
2254
59.0k
            self->pAacDecoderStaticChannelInfo[ch]->hArCo = CArco_Create();
2255
59.0k
            if (self->pAacDecoderStaticChannelInfo[ch]->hArCo == NULL) {
2256
0
              goto bail;
2257
0
            }
2258
59.0k
          }
2259
2260
649k
          if (!(flags & (AC_USAC | AC_RSV603DA))) {
2261
590k
            CPns_UpdateNoiseState(
2262
590k
                &self->pAacDecoderChannelInfo[ch]->data.aac.PnsData,
2263
590k
                &self->pAacDecoderStaticChannelInfo[ch]->pnsCurrentSeed,
2264
590k
                self->pAacDecoderChannelInfo[ch]->pComData->pnsRandomSeed);
2265
590k
          }
2266
649k
          ch++;
2267
649k
        }
2268
0
        chIdx++;
2269
649k
      }
2270
2271
136k
      if (flags & AC_USAC) {
2272
104k
        for (int _ch = 0; _ch < flushChannels; _ch++) {
2273
64.5k
          ch = aacChannelsOffset + _ch;
2274
64.5k
          if (self->pTimeDataFlush[ch] == NULL) {
2275
19.0k
            self->pTimeDataFlush[ch] = GetTimeDataFlush(ch);
2276
19.0k
            if (self->pTimeDataFlush[ch] == NULL) {
2277
0
              goto bail;
2278
0
            }
2279
19.0k
          }
2280
64.5k
        }
2281
40.2k
      }
2282
2283
136k
      if (flags & (AC_USAC | AC_RSV603DA)) {
2284
40.2k
        int complexStereoPredPossible = 0;
2285
40.2k
        ch = aacChannelsOffset;
2286
40.2k
        chIdx = aacChannelsOffsetIdx;
2287
89.1k
        for (int _el2 = 0; _el2 < (int)asc->m_sc.m_usacConfig.m_usacNumElements;
2288
48.8k
             _el2++) {
2289
48.8k
          int el2 = elementOffset + _el2;
2290
48.8k
          int elCh = 0, ch2;
2291
2292
48.8k
          if ((self->elements[el2] == ID_USAC_CPE) &&
2293
24.2k
              !(self->usacStereoConfigIndex[el2] == 1)) {
2294
18.8k
            elCh = 2;
2295
30.0k
          } else if (IS_CHANNEL_ELEMENT(self->elements[el2])) {
2296
21.4k
            elCh = 1;
2297
21.4k
          }
2298
2299
48.8k
          if (elFlags[el2] & AC_EL_USAC_CP_POSSIBLE) {
2300
8.30k
            complexStereoPredPossible = 1;
2301
8.30k
            if (self->cpeStaticData[el2] == NULL) {
2302
8.30k
              self->cpeStaticData[el2] = GetCpePersistentData();
2303
8.30k
              if (self->cpeStaticData[el2] == NULL) {
2304
0
                goto bail;
2305
0
              }
2306
8.30k
            }
2307
8.30k
          }
2308
2309
107k
          for (ch2 = 0; ch2 < elCh; ch2++) {
2310
            /* Hook element specific cpeStaticData into channel specific
2311
             * aacDecoderStaticChannelInfo */
2312
59.0k
            self->pAacDecoderStaticChannelInfo[ch]->pCpeStaticData =
2313
59.0k
                self->cpeStaticData[el2];
2314
59.0k
            if (self->pAacDecoderStaticChannelInfo[ch]->pCpeStaticData !=
2315
59.0k
                NULL) {
2316
16.6k
              self->pAacDecoderStaticChannelInfo[ch]
2317
16.6k
                  ->pCpeStaticData->jointStereoPersistentData
2318
16.6k
                  .spectralCoeffs[ch2] =
2319
16.6k
                  self->pAacDecoderStaticChannelInfo[ch]
2320
16.6k
                      ->concealmentInfo.spectralCoefficient;
2321
16.6k
              self->pAacDecoderStaticChannelInfo[ch]
2322
16.6k
                  ->pCpeStaticData->jointStereoPersistentData.specScale[ch2] =
2323
16.6k
                  self->pAacDecoderStaticChannelInfo[ch]
2324
16.6k
                      ->concealmentInfo.specScale;
2325
16.6k
              self->pAacDecoderStaticChannelInfo[ch]
2326
16.6k
                  ->pCpeStaticData->jointStereoPersistentData.scratchBuffer =
2327
16.6k
                  (FIXP_DBL *)self->pTimeData2;
2328
16.6k
            }
2329
59.0k
            chIdx++;
2330
59.0k
            ch++;
2331
59.0k
          } /* for each channel in current element */
2332
48.8k
          if (complexStereoPredPossible && (elCh == 2)) {
2333
            /* needed once for all channels */
2334
8.30k
            if (self->pAacDecoderChannelInfo[ch - 1]
2335
8.30k
                    ->pComStaticData->cplxPredictionData == NULL) {
2336
8.30k
              self->pAacDecoderChannelInfo[ch - 1]
2337
8.30k
                  ->pComStaticData->cplxPredictionData =
2338
8.30k
                  GetCplxPredictionData();
2339
8.30k
            }
2340
8.30k
            if (self->pAacDecoderChannelInfo[ch - 1]
2341
8.30k
                    ->pComStaticData->cplxPredictionData == NULL) {
2342
0
              goto bail;
2343
0
            }
2344
8.30k
          }
2345
48.8k
          if (elCh > 0) {
2346
40.2k
            self->pAacDecoderStaticChannelInfo[ch - elCh]->nfRandomSeed =
2347
40.2k
                (ULONG)0x3039;
2348
40.2k
            if (self->elements[el2] == ID_USAC_CPE) {
2349
24.2k
              if (asc->m_sc.m_usacConfig.element[el2].m_stereoConfigIndex !=
2350
24.2k
                  1) {
2351
18.8k
                self->pAacDecoderStaticChannelInfo[ch - elCh + 1]
2352
18.8k
                    ->nfRandomSeed = (ULONG)0x10932;
2353
18.8k
              }
2354
24.2k
            }
2355
40.2k
          }
2356
48.8k
        } /* for each element */
2357
40.2k
      }
2358
2359
136k
      if (ascChannels != self->aacChannels) {
2360
        /* Make allocated channel count persistent in decoder context. */
2361
136k
        self->aacChannels = aacChannelsOffset + ch;
2362
136k
      }
2363
136k
    }
2364
2365
136k
    if (usacResidualDelayCompSamples) {
2366
583
      INT delayErr = FDK_Delay_Create(&self->usacResidualDelay,
2367
583
                                      (USHORT)usacResidualDelayCompSamples, 1);
2368
583
      if (delayErr) {
2369
0
        goto bail;
2370
0
      }
2371
583
    }
2372
2373
    /* Make amount of signalled channels persistent in decoder context. */
2374
136k
    self->ascChannels[streamIndex] = ascChannels;
2375
    /* Init the previous channel count values. This is required to avoid a
2376
       mismatch of memory accesses in the error concealment module and the
2377
       allocated channel structures in this function. */
2378
136k
    self->aacChannelsPrev = 0;
2379
136k
  }
2380
2381
228k
  if (self->pAacDecoderChannelInfo[0] != NULL) {
2382
228k
    self->pDrmBsBuffer = self->pAacDecoderChannelInfo[0]
2383
228k
                             ->pComStaticData->pWorkBufferCore1->DrmBsBuffer;
2384
228k
    self->drmBsBufferSize = DRM_BS_BUFFER_SIZE;
2385
228k
  }
2386
2387
  /* Update structures */
2388
228k
  if (*configChanged) {
2389
    /* Things to be done for each channel, which do not involve allocating
2390
       memory. Doing these things only on the channels needed for the current
2391
       configuration (ascChannels) could lead to memory access violation later
2392
       (error concealment). */
2393
136k
    int ch = 0;
2394
136k
    int chIdx = 0;
2395
785k
    for (int _ch = 0; _ch < self->ascChannels[streamIndex]; _ch++) {
2396
649k
      switch (self->streamInfo.aot) {
2397
85.2k
        case AOT_ER_AAC_ELD:
2398
102k
        case AOT_ER_AAC_LD:
2399
102k
          self->pAacDecoderChannelInfo[ch]->granuleLength =
2400
102k
              self->streamInfo.aacSamplesPerFrame;
2401
102k
          break;
2402
546k
        default:
2403
546k
          self->pAacDecoderChannelInfo[ch]->granuleLength =
2404
546k
              self->streamInfo.aacSamplesPerFrame / 8;
2405
546k
          break;
2406
649k
      }
2407
649k
      self->pAacDecoderChannelInfo[ch]->renderMode = initRenderMode;
2408
2409
649k
      mdct_init(&self->pAacDecoderStaticChannelInfo[ch]->IMdct,
2410
649k
                self->pAacDecoderStaticChannelInfo[ch]->pOverlapBuffer,
2411
649k
                OverlapBufferSize);
2412
2413
649k
      self->pAacDecoderStaticChannelInfo[ch]->last_core_mode = FD_LONG;
2414
649k
      self->pAacDecoderStaticChannelInfo[ch]->last_lpd_mode = 255;
2415
2416
649k
      self->pAacDecoderStaticChannelInfo[ch]->last_tcx_pitch = L_DIV;
2417
2418
      /* Reset DRC control data for this channel */
2419
649k
      aacDecoder_drcInitChannelData(
2420
649k
          &self->pAacDecoderStaticChannelInfo[ch]->drcData);
2421
2422
      /* Delete mixdown metadata from the past */
2423
649k
      pcmDmx_Reset(self->hPcmUtils, PCMDMX_RESET_BS_DATA);
2424
2425
      /* Reset concealment only if ASC changed. Otherwise it will be done with
2426
         any config callback. E.g. every time the LATM SMC is present. */
2427
649k
      CConcealment_InitChannelData(
2428
649k
          &self->pAacDecoderStaticChannelInfo[ch]->concealmentInfo,
2429
649k
          &self->concealCommonData, initRenderMode,
2430
649k
          self->streamInfo.aacSamplesPerFrame);
2431
649k
      ch++;
2432
649k
      chIdx++;
2433
649k
    }
2434
136k
  }
2435
2436
228k
  if (*configChanged) {
2437
136k
    int drcDecSampleRate, drcDecFrameSize;
2438
2439
136k
    if (self->streamInfo.extSamplingRate != 0) {
2440
60.0k
      drcDecSampleRate = self->streamInfo.extSamplingRate;
2441
60.0k
      drcDecFrameSize = (self->streamInfo.aacSamplesPerFrame *
2442
60.0k
                         self->streamInfo.extSamplingRate) /
2443
60.0k
                        self->streamInfo.aacSampleRate;
2444
76.0k
    } else {
2445
76.0k
      drcDecSampleRate = self->streamInfo.aacSampleRate;
2446
76.0k
      drcDecFrameSize = self->streamInfo.aacSamplesPerFrame;
2447
76.0k
    }
2448
2449
136k
    if (FDK_drcDec_Init(self->hUniDrcDecoder, drcDecFrameSize, drcDecSampleRate,
2450
136k
                        self->aacChannels) != 0)
2451
0
      goto bail;
2452
136k
  }
2453
2454
228k
  if (*configChanged) {
2455
136k
    if (asc->m_aot == AOT_USAC) {
2456
40.2k
      aacDecoder_drcDisable(self->hDrcInfo);
2457
40.2k
    }
2458
136k
  }
2459
2460
228k
  if (asc->m_aot == AOT_USAC) {
2461
77.7k
    pcmLimiter_SetAttack(self->hLimiter, (5));
2462
77.7k
    pcmLimiter_SetThreshold(self->hLimiter, FL2FXCONST_DBL(0.89125094f));
2463
77.7k
  }
2464
2465
228k
  CAacDecoder_AcceptFlags(self, asc, flags, elFlags, streamIndex,
2466
228k
                          elementOffset);
2467
228k
  self->sbrEnabled = sbrEnabled;
2468
228k
  self->sbrEnabledPrev = sbrEnabledPrev;
2469
228k
  self->mpsEnableCurr = mpsEnableCurr;
2470
2471
  /* Update externally visible copy of flags */
2472
228k
  self->streamInfo.flags = self->flags[0];
2473
2474
228k
  return err;
2475
2476
0
bail:
2477
0
  CAacDecoder_DeInit(self, 0);
2478
0
  return AAC_DEC_OUT_OF_MEMORY;
2479
228k
}
2480
2481
LINKSPEC_CPP AAC_DECODER_ERROR CAacDecoder_DecodeFrame(
2482
    HANDLE_AACDECODER self, const UINT flags, PCM_DEC *pTimeData,
2483
416k
    const INT timeDataSize, const int timeDataChannelOffset) {
2484
416k
  AAC_DECODER_ERROR ErrorStatus = AAC_DEC_OK;
2485
2486
416k
  CProgramConfig *pce;
2487
416k
  HANDLE_FDK_BITSTREAM bs = transportDec_GetBitstream(self->hInput, 0);
2488
2489
416k
  MP4_ELEMENT_ID type = ID_NONE; /* Current element type */
2490
416k
  INT aacChannels = 0; /* Channel counter for channels found in the bitstream */
2491
416k
  const int streamIndex = 0; /* index of the current substream */
2492
2493
416k
  INT auStartAnchor = (INT)FDKgetValidBits(
2494
416k
      bs); /* AU start bit buffer position for AU byte alignment */
2495
2496
416k
  INT checkSampleRate = self->streamInfo.aacSampleRate;
2497
2498
416k
  INT CConceal_TDFading_Applied[(8)] = {
2499
416k
      0}; /* Initialize status of Time Domain fading */
2500
2501
416k
  if (self->aacChannels <= 0) {
2502
45
    return AAC_DEC_UNSUPPORTED_CHANNELCONFIG;
2503
45
  }
2504
2505
  /* Any supported base layer valid AU will require more than 16 bits. */
2506
416k
  if ((transportDec_GetAuBitsRemaining(self->hInput, 0) < 15) &&
2507
1.75k
      (flags & (AACDEC_CONCEAL | AACDEC_FLUSH)) == 0) {
2508
1.75k
    self->frameOK = 0;
2509
1.75k
    ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
2510
1.75k
  }
2511
2512
  /* Reset Program Config structure */
2513
416k
  pce = &self->pce;
2514
416k
  CProgramConfig_Reset(pce);
2515
2516
416k
  CAacDecoder_AncDataReset(&self->ancData);
2517
416k
  if (!(flags & (AACDEC_CONCEAL | AACDEC_FLUSH)) &&
2518
416k
      !(self->flags[0] & (AC_USAC | AC_RSV603DA))) {
2519
144k
    int ch;
2520
144k
    if (self->streamInfo.channelConfig == 0) {
2521
      /* Init Channel/Element mapping table */
2522
17.0k
      for (ch = 0; ch < (8); ch++) {
2523
15.1k
        self->chMapping[ch] = 255;
2524
15.1k
      }
2525
1.89k
      if (!CProgramConfig_IsValid(pce)) {
2526
0
        int el;
2527
0
        for (el = 0; el < (3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) + 1);
2528
0
             el++) {
2529
0
          self->elements[el] = ID_NONE;
2530
0
        }
2531
0
      }
2532
1.89k
    }
2533
144k
  }
2534
2535
416k
  if (self->downscaleFactor > 1 && (self->flags[0] & AC_ELD)) {
2536
3.72k
    self->flags[0] |= AC_ELD_DOWNSCALE;
2537
413k
  } else {
2538
413k
    self->flags[0] &= ~AC_ELD_DOWNSCALE;
2539
413k
  }
2540
  /* unsupported dsf (aacSampleRate has not yet been divided by dsf) -> divide
2541
   */
2542
416k
  if (self->downscaleFactorInBS > 1 &&
2543
3.72k
      (self->flags[0] & AC_ELD_DOWNSCALE) == 0) {
2544
0
    checkSampleRate =
2545
0
        self->streamInfo.aacSampleRate / self->downscaleFactorInBS;
2546
0
  }
2547
2548
  /* Check sampling frequency  */
2549
416k
  if (self->streamInfo.aacSampleRate <= 0) {
2550
    /* Instance maybe uninitialized! */
2551
0
    return AAC_DEC_UNSUPPORTED_SAMPLINGRATE;
2552
0
  }
2553
416k
  switch (checkSampleRate) {
2554
4.99k
    case 96000:
2555
15.9k
    case 88200:
2556
18.1k
    case 64000:
2557
29.6k
    case 16000:
2558
43.9k
    case 12000:
2559
48.9k
    case 11025:
2560
73.8k
    case 8000:
2561
105k
    case 7350:
2562
106k
    case 48000:
2563
118k
    case 44100:
2564
124k
    case 32000:
2565
185k
    case 24000:
2566
309k
    case 22050:
2567
309k
      break;
2568
107k
    default:
2569
107k
      if (!(self->flags[0] & (AC_USAC | AC_RSVD50 | AC_RSV603DA))) {
2570
28
        return AAC_DEC_UNSUPPORTED_SAMPLINGRATE;
2571
28
      }
2572
106k
      break;
2573
416k
  }
2574
2575
416k
  if (flags & AACDEC_CLRHIST) {
2576
0
    if (!(self->flags[0] & AC_USAC)) {
2577
0
      int ch;
2578
      /* Clear history */
2579
0
      for (ch = 0; ch < self->aacChannels; ch++) {
2580
        /* Reset concealment */
2581
0
        CConcealment_InitChannelData(
2582
0
            &self->pAacDecoderStaticChannelInfo[ch]->concealmentInfo,
2583
0
            &self->concealCommonData,
2584
0
            self->pAacDecoderChannelInfo[0]->renderMode,
2585
0
            self->streamInfo.aacSamplesPerFrame);
2586
        /* Clear overlap-add buffers to avoid clicks. */
2587
0
        FDKmemclear(self->pAacDecoderStaticChannelInfo[ch]->pOverlapBuffer,
2588
0
                    OverlapBufferSize * sizeof(FIXP_DBL));
2589
0
      }
2590
0
      if (self->streamInfo.channelConfig > 0) {
2591
        /* Declare the possibly adopted old PCE (with outdated metadata)
2592
         * invalid. */
2593
0
        CProgramConfig_Init(pce);
2594
0
      }
2595
0
    }
2596
0
  }
2597
2598
416k
  int pceRead = 0; /* Flag indicating a PCE in the current raw_data_block() */
2599
2600
416k
  INT hdaacDecoded = 0;
2601
416k
  MP4_ELEMENT_ID previous_element =
2602
416k
      ID_END; /* Last element ID (required for extension payload mapping */
2603
416k
  UCHAR previous_element_index = 0; /* Canonical index of last element */
2604
416k
  int element_count =
2605
416k
      0; /* Element counter for elements found in the bitstream */
2606
416k
  int channel_element_count = 0; /* Channel element counter */
2607
416k
  MP4_ELEMENT_ID
2608
416k
  channel_elements[(3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) +
2609
416k
                    1)];     /* Channel elements in bit stream order. */
2610
416k
  int el_cnt[ID_LAST] = {0}; /* element counter ( robustness ) */
2611
416k
  int element_count_prev_streams =
2612
416k
      0; /* Element count of all previous sub streams. */
2613
2614
1.50M
  while ((type != ID_END) && (!(flags & (AACDEC_CONCEAL | AACDEC_FLUSH))) &&
2615
1.09M
         self->frameOK) {
2616
1.08M
    int el_channels;
2617
2618
1.08M
    if (!(self->flags[0] &
2619
1.08M
          (AC_USAC | AC_RSVD50 | AC_RSV603DA | AC_ELD | AC_SCALABLE | AC_ER)))
2620
53.0k
      type = (MP4_ELEMENT_ID)FDKreadBits(bs, 3);
2621
1.03M
    else {
2622
1.03M
      if (element_count >= (3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) + 1)) {
2623
0
        self->frameOK = 0;
2624
0
        ErrorStatus = AAC_DEC_PARSE_ERROR;
2625
0
        break;
2626
0
      }
2627
1.03M
      type = self->elements[element_count];
2628
1.03M
    }
2629
2630
1.08M
    if ((self->flags[streamIndex] & (AC_USAC | AC_RSVD50) &&
2631
563k
         element_count == 0) ||
2632
816k
        (self->flags[streamIndex] & AC_RSV603DA)) {
2633
270k
      self->flags[streamIndex] &= ~AC_INDEP;
2634
2635
270k
      if (FDKreadBit(bs)) {
2636
188k
        self->flags[streamIndex] |= AC_INDEP;
2637
188k
      }
2638
2639
270k
      int ch = aacChannels;
2640
618k
      for (int chIdx = aacChannels; chIdx < self->ascChannels[streamIndex];
2641
347k
           chIdx++) {
2642
347k
        {
2643
          /* Robustness check */
2644
347k
          if (ch >= self->aacChannels) {
2645
0
            return AAC_DEC_UNKNOWN;
2646
0
          }
2647
2648
          /* if last frame was broken and this frame is no independent frame,
2649
           * correct decoding is impossible we need to trigger concealment */
2650
347k
          if ((CConcealment_GetLastFrameOk(
2651
347k
                   &self->pAacDecoderStaticChannelInfo[ch]->concealmentInfo,
2652
347k
                   1) == 0) &&
2653
0
              !(self->flags[streamIndex] & AC_INDEP)) {
2654
0
            self->frameOK = 0;
2655
0
          }
2656
347k
          ch++;
2657
347k
        }
2658
347k
      }
2659
270k
    }
2660
2661
1.08M
    if ((INT)FDKgetValidBits(bs) < 0) {
2662
3.81k
      self->frameOK = 0;
2663
3.81k
    }
2664
2665
1.08M
    switch (type) {
2666
98.6k
      case ID_SCE:
2667
212k
      case ID_CPE:
2668
232k
      case ID_LFE:
2669
291k
      case ID_USAC_SCE:
2670
503k
      case ID_USAC_CPE:
2671
503k
      case ID_USAC_LFE:
2672
503k
        if (element_count >= (3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) + 1)) {
2673
18
          self->frameOK = 0;
2674
18
          ErrorStatus = AAC_DEC_PARSE_ERROR;
2675
18
          break;
2676
18
        }
2677
2678
503k
        el_channels = CAacDecoder_GetELChannels(
2679
503k
            type, self->usacStereoConfigIndex[element_count]);
2680
2681
        /*
2682
          Consistency check
2683
         */
2684
503k
        {
2685
503k
          int totalAscChannels = 0;
2686
2687
1.00M
          for (int i = 0; i < (1 * 1); i++) {
2688
503k
            totalAscChannels += self->ascChannels[i];
2689
503k
          }
2690
503k
          if ((el_cnt[type] >= (totalAscChannels >> (el_channels - 1))) ||
2691
503k
              (aacChannels > (totalAscChannels - el_channels))) {
2692
203
            ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
2693
203
            self->frameOK = 0;
2694
203
            break;
2695
203
          }
2696
503k
        }
2697
2698
503k
        if (!(self->flags[streamIndex] & (AC_USAC | AC_RSVD50 | AC_RSV603DA))) {
2699
232k
          int ch;
2700
578k
          for (ch = 0; ch < el_channels; ch += 1) {
2701
345k
            CPns_ResetData(&self->pAacDecoderChannelInfo[aacChannels + ch]
2702
345k
                                ->data.aac.PnsData,
2703
345k
                           &self->pAacDecoderChannelInfo[aacChannels + ch]
2704
345k
                                ->pComData->pnsInterChannelData);
2705
345k
          }
2706
232k
        }
2707
2708
503k
        if (self->frameOK) {
2709
501k
          ErrorStatus = CChannelElement_Read(
2710
501k
              bs, &self->pAacDecoderChannelInfo[aacChannels],
2711
501k
              &self->pAacDecoderStaticChannelInfo[aacChannels],
2712
501k
              self->streamInfo.aot, &self->samplingRateInfo[streamIndex],
2713
501k
              self->flags[streamIndex], self->elFlags[element_count],
2714
501k
              self->streamInfo.aacSamplesPerFrame, el_channels,
2715
501k
              self->streamInfo.epConfig, self->hInput);
2716
501k
          if (ErrorStatus != AAC_DEC_OK) {
2717
3.39k
            self->frameOK = 0;
2718
3.39k
          }
2719
501k
        }
2720
2721
503k
        if (self->frameOK) {
2722
          /* Lookup the element and decode it only if it belongs to the current
2723
           * program */
2724
498k
          if (CProgramConfig_LookupElement(
2725
498k
                  pce, self->streamInfo.channelConfig,
2726
498k
                  self->pAacDecoderChannelInfo[aacChannels]->ElementInstanceTag,
2727
498k
                  aacChannels, self->chMapping, self->channelType,
2728
498k
                  self->channelIndices, (8), &previous_element_index,
2729
498k
                  self->elements, type)) {
2730
498k
            channel_elements[channel_element_count++] = type;
2731
498k
            aacChannels += el_channels;
2732
498k
          } else {
2733
111
            self->frameOK = 0;
2734
111
          }
2735
          /* Create SBR element for SBR for upsampling for LFE elements,
2736
             and if SBR was implicitly signaled, because the first frame(s)
2737
             may not contain SBR payload (broken encoder, bit errors). */
2738
498k
          if (self->frameOK &&
2739
498k
              ((self->flags[streamIndex] & AC_SBR_PRESENT) ||
2740
154k
               (self->sbrEnabled == 1)) &&
2741
344k
              !(self->flags[streamIndex] &
2742
344k
                AC_USAC) /* Is done during explicit config set up */
2743
498k
          ) {
2744
109k
            SBR_ERROR sbrError;
2745
109k
            UCHAR configMode = 0;
2746
109k
            UCHAR configChanged = 0;
2747
109k
            configMode |= AC_CM_ALLOC_MEM;
2748
2749
109k
            sbrError = sbrDecoder_InitElement(
2750
109k
                self->hSbrDecoder, self->streamInfo.aacSampleRate,
2751
109k
                self->streamInfo.extSamplingRate,
2752
109k
                self->streamInfo.aacSamplesPerFrame, self->streamInfo.aot, type,
2753
109k
                previous_element_index, 2, /* Signalize that harmonicSBR shall
2754
                                              be ignored in the config change
2755
                                              detection */
2756
109k
                0, configMode, &configChanged, self->downscaleFactor);
2757
109k
            if (sbrError != SBRDEC_OK) {
2758
              /* Do not try to apply SBR because initializing the element
2759
               * failed. */
2760
43
              self->sbrEnabled = 0;
2761
43
            }
2762
109k
          }
2763
498k
        }
2764
2765
503k
        el_cnt[type]++;
2766
503k
        if (self->frameOK && (self->flags[streamIndex] & AC_USAC) &&
2767
268k
            (type == ID_USAC_CPE || type == ID_USAC_SCE)) {
2768
268k
          ErrorStatus = aacDecoder_ParseExplicitMpsAndSbr(
2769
268k
              self, bs, previous_element, previous_element_index, element_count,
2770
268k
              el_cnt);
2771
268k
          if (ErrorStatus != AAC_DEC_OK) {
2772
386
            self->frameOK = 0;
2773
386
          }
2774
268k
        }
2775
503k
        break;
2776
2777
725
      case ID_CCE:
2778
        /*
2779
          Consistency check
2780
        */
2781
725
        if (el_cnt[type] > self->ascChannels[streamIndex]) {
2782
2
          ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
2783
2
          self->frameOK = 0;
2784
2
          break;
2785
2
        }
2786
2787
723
        if (self->frameOK) {
2788
714
          CAacDecoderCommonData commonData;
2789
714
          CAacDecoderCommonStaticData commonStaticData;
2790
714
          CWorkBufferCore1 workBufferCore1;
2791
714
          commonStaticData.pWorkBufferCore1 = &workBufferCore1;
2792
          /* memory for spectral lines temporal on scratch */
2793
714
          C_AALLOC_SCRATCH_START(mdctSpec, FIXP_DBL, 1024);
2794
2795
          /* create dummy channel for CCE parsing on stack */
2796
714
          CAacDecoderChannelInfo tmpAacDecoderChannelInfo,
2797
714
              *pTmpAacDecoderChannelInfo;
2798
2799
714
          FDKmemclear(mdctSpec, 1024 * sizeof(FIXP_DBL));
2800
2801
714
          tmpAacDecoderChannelInfo.pDynData = commonData.pAacDecoderDynamicData;
2802
714
          tmpAacDecoderChannelInfo.pComData = &commonData;
2803
714
          tmpAacDecoderChannelInfo.pComStaticData = &commonStaticData;
2804
714
          tmpAacDecoderChannelInfo.pSpectralCoefficient =
2805
714
              (SPECTRAL_PTR)mdctSpec;
2806
          /* Assume AAC-LC */
2807
714
          tmpAacDecoderChannelInfo.granuleLength =
2808
714
              self->streamInfo.aacSamplesPerFrame / 8;
2809
          /* Reset PNS data. */
2810
714
          CPns_ResetData(
2811
714
              &tmpAacDecoderChannelInfo.data.aac.PnsData,
2812
714
              &tmpAacDecoderChannelInfo.pComData->pnsInterChannelData);
2813
714
          pTmpAacDecoderChannelInfo = &tmpAacDecoderChannelInfo;
2814
          /* do CCE parsing */
2815
714
          ErrorStatus = CChannelElement_Read(
2816
714
              bs, &pTmpAacDecoderChannelInfo, NULL, self->streamInfo.aot,
2817
714
              &self->samplingRateInfo[streamIndex], self->flags[streamIndex],
2818
714
              AC_EL_GA_CCE, self->streamInfo.aacSamplesPerFrame, 1,
2819
714
              self->streamInfo.epConfig, self->hInput);
2820
2821
714
          C_AALLOC_SCRATCH_END(mdctSpec, FIXP_DBL, 1024);
2822
2823
714
          if (ErrorStatus) {
2824
23
            self->frameOK = 0;
2825
23
          }
2826
2827
714
          if (self->frameOK) {
2828
            /* Lookup the element and decode it only if it belongs to the
2829
             * current program */
2830
691
            if (CProgramConfig_LookupElement(
2831
691
                    pce, self->streamInfo.channelConfig,
2832
691
                    pTmpAacDecoderChannelInfo->ElementInstanceTag, 0,
2833
691
                    self->chMapping, self->channelType, self->channelIndices,
2834
691
                    (8), &previous_element_index, self->elements, type)) {
2835
              /* decoding of CCE not supported */
2836
681
            } else {
2837
10
              self->frameOK = 0;
2838
10
            }
2839
691
          }
2840
714
        }
2841
723
        el_cnt[type]++;
2842
723
        break;
2843
2844
9.41k
      case ID_DSE: {
2845
9.41k
        UCHAR element_instance_tag;
2846
2847
9.41k
        CDataStreamElement_Read(self, bs, &element_instance_tag, auStartAnchor);
2848
2849
9.41k
        if (!CProgramConfig_LookupElement(
2850
9.41k
                pce, self->streamInfo.channelConfig, element_instance_tag, 0,
2851
9.41k
                self->chMapping, self->channelType, self->channelIndices, (8),
2852
9.41k
                &previous_element_index, self->elements, type)) {
2853
          /* most likely an error in bitstream occured */
2854
          // self->frameOK = 0;
2855
1.69k
        }
2856
9.41k
      } break;
2857
2858
1.48k
      case ID_PCE: {
2859
1.48k
        int result = CProgramConfigElement_Read(bs, self->hInput, pce,
2860
1.48k
                                                self->streamInfo.channelConfig,
2861
1.48k
                                                auStartAnchor);
2862
1.48k
        if (result < 0) {
2863
          /* Something went wrong */
2864
14
          ErrorStatus = AAC_DEC_PARSE_ERROR;
2865
14
          self->frameOK = 0;
2866
1.46k
        } else if (result > 1) {
2867
          /* Built element table */
2868
0
          int elIdx = CProgramConfig_GetElementTable(
2869
0
              pce, self->elements, (((8)) + (8)), &self->chMapIndex);
2870
          /* Reset the remaining tabs */
2871
0
          for (; elIdx < (3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) + 1);
2872
0
               elIdx++) {
2873
0
            self->elements[elIdx] = ID_NONE;
2874
0
          }
2875
          /* Make new number of channel persistent */
2876
0
          self->ascChannels[streamIndex] = pce->NumChannels;
2877
          /* If PCE is not first element conceal this frame to avoid
2878
           * inconsistencies */
2879
0
          if (element_count != 0) {
2880
0
            self->frameOK = 0;
2881
0
          }
2882
0
        }
2883
1.48k
        pceRead = (result >= 0) ? 1 : 0;
2884
1.48k
      } break;
2885
2886
10.2k
      case ID_FIL: {
2887
10.2k
        int bitCnt = FDKreadBits(bs, 4); /* bs_count */
2888
2889
10.2k
        if (bitCnt == 15) {
2890
28
          int esc_count = FDKreadBits(bs, 8); /* bs_esc_count */
2891
28
          bitCnt = esc_count + 14;
2892
28
        }
2893
2894
        /* Convert to bits */
2895
10.2k
        bitCnt <<= 3;
2896
2897
17.2k
        while (bitCnt > 0) {
2898
7.02k
          ErrorStatus = CAacDecoder_ExtPayloadParse(
2899
7.02k
              self, bs, &bitCnt, previous_element, previous_element_index, 1);
2900
7.02k
          if (ErrorStatus != AAC_DEC_OK) {
2901
70
            self->frameOK = 0;
2902
70
            break;
2903
70
          }
2904
7.02k
        }
2905
10.2k
      } break;
2906
2907
130k
      case ID_EXT:
2908
130k
        if (element_count >= (3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) + 1)) {
2909
0
          self->frameOK = 0;
2910
0
          ErrorStatus = AAC_DEC_PARSE_ERROR;
2911
0
          break;
2912
0
        }
2913
2914
130k
        ErrorStatus = aacDecoder_ParseExplicitMpsAndSbr(
2915
130k
            self, bs, previous_element, previous_element_index, element_count,
2916
130k
            el_cnt);
2917
130k
        break;
2918
2919
25.0k
      case ID_USAC_EXT: {
2920
25.0k
        if ((element_count - element_count_prev_streams) >=
2921
25.0k
            TP_USAC_MAX_ELEMENTS) {
2922
0
          self->frameOK = 0;
2923
0
          ErrorStatus = AAC_DEC_PARSE_ERROR;
2924
0
          break;
2925
0
        }
2926
        /* parse extension element payload
2927
           q.v. rsv603daExtElement() ISO/IEC DIS 23008-3  Table 30
2928
           or   UsacExElement() ISO/IEC FDIS 23003-3:2011(E)  Table 21
2929
         */
2930
25.0k
        int usacExtElementPayloadLength;
2931
        /* int usacExtElementStart, usacExtElementStop; */
2932
2933
25.0k
        if (FDKreadBit(bs)) {   /* usacExtElementPresent */
2934
11.0k
          if (FDKreadBit(bs)) { /* usacExtElementUseDefaultLength */
2935
8.35k
            usacExtElementPayloadLength =
2936
8.35k
                self->pUsacConfig[streamIndex]
2937
8.35k
                    ->element[element_count - element_count_prev_streams]
2938
8.35k
                    .extElement.usacExtElementDefaultLength;
2939
8.35k
          } else {
2940
2.72k
            usacExtElementPayloadLength = FDKreadBits(bs, 8);
2941
2.72k
            if (usacExtElementPayloadLength == (UINT)(1 << 8) - 1) {
2942
13
              UINT valueAdd = FDKreadBits(bs, 16);
2943
13
              usacExtElementPayloadLength += (INT)valueAdd - 2;
2944
13
            }
2945
2.72k
          }
2946
11.0k
          if (usacExtElementPayloadLength > 0) {
2947
9.78k
            int usacExtBitPos;
2948
2949
9.78k
            if (self->pUsacConfig[streamIndex]
2950
9.78k
                    ->element[element_count - element_count_prev_streams]
2951
9.78k
                    .extElement.usacExtElementPayloadFrag) {
2952
894
              /* usacExtElementStart = */ FDKreadBit(bs);
2953
894
              /* usacExtElementStop = */ FDKreadBit(bs);
2954
8.88k
            } else {
2955
              /* usacExtElementStart = 1; */
2956
              /* usacExtElementStop = 1; */
2957
8.88k
            }
2958
2959
9.78k
            usacExtBitPos = (INT)FDKgetValidBits(bs);
2960
2961
9.78k
            USAC_EXT_ELEMENT_TYPE usacExtElementType =
2962
9.78k
                self->pUsacConfig[streamIndex]
2963
9.78k
                    ->element[element_count - element_count_prev_streams]
2964
9.78k
                    .extElement.usacExtElementType;
2965
2966
9.78k
            switch (usacExtElementType) {
2967
8.58k
              case ID_EXT_ELE_UNI_DRC: /* uniDrcGain() */
2968
8.58k
                if (streamIndex == 0) {
2969
8.58k
                  int drcErr;
2970
2971
8.58k
                  drcErr = FDK_drcDec_ReadUniDrcGain(self->hUniDrcDecoder, bs);
2972
8.58k
                  if (drcErr != 0) {
2973
355
                    ErrorStatus = AAC_DEC_PARSE_ERROR;
2974
355
                  }
2975
8.58k
                }
2976
8.58k
                break;
2977
2978
1.19k
              default:
2979
1.19k
                break;
2980
9.78k
            }
2981
2982
            /* Skip any remaining bits of extension payload */
2983
9.78k
            usacExtBitPos = (usacExtElementPayloadLength * 8) -
2984
9.78k
                            (usacExtBitPos - (INT)FDKgetValidBits(bs));
2985
9.78k
            if (usacExtBitPos < 0) {
2986
93
              self->frameOK = 0;
2987
93
              ErrorStatus = AAC_DEC_PARSE_ERROR;
2988
93
            }
2989
9.78k
            FDKpushBiDirectional(bs, usacExtBitPos);
2990
9.78k
          }
2991
11.0k
        }
2992
25.0k
      } break;
2993
406k
      case ID_END:
2994
406k
      case ID_USAC_END:
2995
406k
        break;
2996
2997
0
      default:
2998
0
        ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
2999
0
        self->frameOK = 0;
3000
0
        break;
3001
1.08M
    }
3002
3003
1.08M
    previous_element = type;
3004
1.08M
    element_count++;
3005
3006
1.08M
  } /* while ( (type != ID_END) ... ) */
3007
3008
416k
  if (!(self->flags[streamIndex] &
3009
416k
        (AC_USAC | AC_RSVD50 | AC_RSV603DA | AC_BSAC | AC_LD | AC_ELD | AC_ER |
3010
416k
         AC_SCALABLE)) &&
3011
12.0k
      (self->streamInfo.channelConfig == 0) && pce->isValid &&
3012
1.89k
      (ErrorStatus == AAC_DEC_OK) && self->frameOK &&
3013
1.51k
      !(flags & (AACDEC_CONCEAL | AACDEC_FLUSH))) {
3014
    /* Check whether all PCE listed element instance tags are present in
3015
     * raw_data_block() */
3016
1.51k
    if (!validateElementInstanceTags(
3017
1.51k
            &self->pce, self->pAacDecoderChannelInfo, aacChannels,
3018
1.51k
            channel_elements,
3019
1.51k
            fMin(channel_element_count, (int)(sizeof(channel_elements) /
3020
1.51k
                                              sizeof(*channel_elements))))) {
3021
24
      ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
3022
24
      self->frameOK = 0;
3023
24
    }
3024
1.51k
  }
3025
3026
416k
  if (!(flags & (AACDEC_CONCEAL | AACDEC_FLUSH))) {
3027
    /* float decoder checks if bitsLeft is in range 0-7; only prerollAUs are
3028
     * byteAligned with respect to the first bit */
3029
    /* Byte alignment with respect to the first bit of the raw_data_block(). */
3030
416k
    if (!(self->flags[streamIndex] & (AC_RSVD50 | AC_USAC)) ||
3031
272k
        (self->prerollAULength[self->accessUnit]) /* indicates preroll */
3032
416k
    ) {
3033
146k
      FDKbyteAlign(bs, auStartAnchor);
3034
146k
    }
3035
3036
    /* Check if all bits of the raw_data_block() have been read. */
3037
416k
    if (transportDec_GetAuBitsTotal(self->hInput, 0) > 0) {
3038
95.7k
      INT unreadBits = transportDec_GetAuBitsRemaining(self->hInput, 0);
3039
      /* for pre-roll frames pre-roll length has to be used instead of total AU
3040
       * lenght */
3041
      /* unreadBits regarding preroll bounds */
3042
95.7k
      if (self->prerollAULength[self->accessUnit]) {
3043
73
        unreadBits = unreadBits - transportDec_GetAuBitsTotal(self->hInput, 0) +
3044
73
                     (INT)self->prerollAULength[self->accessUnit];
3045
73
      }
3046
95.7k
      if (((self->flags[streamIndex] & (AC_RSVD50 | AC_USAC)) &&
3047
13.8k
           ((unreadBits < 0) || (unreadBits > 7)) &&
3048
1.66k
           !(self->prerollAULength[self->accessUnit])) ||
3049
94.2k
          ((!(self->flags[streamIndex] & (AC_RSVD50 | AC_USAC)) ||
3050
12.2k
            (self->prerollAULength[self->accessUnit])) &&
3051
82.0k
           (unreadBits != 0))) {
3052
4.26k
        if ((((unreadBits < 0) || (unreadBits > 7)) && self->frameOK) &&
3053
233
            ((transportDec_GetFormat(self->hInput) == TT_DRM) &&
3054
0
             (self->flags[streamIndex] & AC_USAC))) {
3055
          /* Set frame OK because of fill bits. */
3056
0
          self->frameOK = 1;
3057
4.26k
        } else {
3058
4.26k
          self->frameOK = 0;
3059
4.26k
        }
3060
3061
        /* Do not overwrite current error */
3062
4.26k
        if (ErrorStatus == AAC_DEC_OK && self->frameOK == 0) {
3063
2.38k
          ErrorStatus = AAC_DEC_PARSE_ERROR;
3064
2.38k
        }
3065
        /* Always put the bitbuffer at the right position after the current
3066
         * Access Unit. */
3067
4.26k
        FDKpushBiDirectional(bs, unreadBits);
3068
4.26k
      }
3069
95.7k
    }
3070
3071
    /* Check the last element. The terminator (ID_END) has to be the last one
3072
     * (even if ER syntax is used). */
3073
416k
    if (self->frameOK && type != ID_END) {
3074
      /* Do not overwrite current error */
3075
0
      if (ErrorStatus == AAC_DEC_OK) {
3076
0
        ErrorStatus = AAC_DEC_PARSE_ERROR;
3077
0
      }
3078
0
      self->frameOK = 0;
3079
0
    }
3080
416k
  }
3081
3082
416k
  if (!(flags & (AACDEC_CONCEAL | AACDEC_FLUSH)) && self->frameOK) {
3083
405k
    channel_elements[channel_element_count++] = ID_END;
3084
405k
  }
3085
416k
  element_count = 0;
3086
416k
  aacChannels = 0;
3087
416k
  type = ID_NONE;
3088
416k
  previous_element_index = 0;
3089
3090
1.37M
  while (type != ID_END &&
3091
956k
         element_count < (3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) + 1)) {
3092
956k
    int el_channels;
3093
3094
956k
    if ((flags & (AACDEC_CONCEAL | AACDEC_FLUSH)) || !self->frameOK) {
3095
35.2k
      channel_elements[element_count] = self->elements[element_count];
3096
35.2k
      if (channel_elements[element_count] == ID_NONE) {
3097
405
        channel_elements[element_count] = ID_END;
3098
405
      }
3099
35.2k
    }
3100
3101
956k
    if (self->flags[streamIndex] & (AC_USAC | AC_RSV603DA | AC_BSAC)) {
3102
570k
      type = self->elements[element_count];
3103
570k
    } else {
3104
385k
      type = channel_elements[element_count];
3105
385k
    }
3106
3107
956k
    if (!(flags & (AACDEC_CONCEAL | AACDEC_FLUSH)) && self->frameOK) {
3108
921k
      switch (type) {
3109
94.2k
        case ID_SCE:
3110
204k
        case ID_CPE:
3111
224k
        case ID_LFE:
3112
281k
        case ID_USAC_SCE:
3113
491k
        case ID_USAC_CPE:
3114
491k
        case ID_USAC_LFE:
3115
3116
491k
          el_channels = CAacDecoder_GetELChannels(
3117
491k
              type, self->usacStereoConfigIndex[element_count]);
3118
3119
491k
          if (!hdaacDecoded) {
3120
491k
            if (self->pAacDecoderStaticChannelInfo[aacChannels]
3121
491k
                    ->pCpeStaticData != NULL) {
3122
58.5k
              self->pAacDecoderStaticChannelInfo[aacChannels]
3123
58.5k
                  ->pCpeStaticData->jointStereoPersistentData.scratchBuffer =
3124
58.5k
                  (FIXP_DBL *)pTimeData;
3125
58.5k
            }
3126
491k
            CChannelElement_Decode(
3127
491k
                &self->pAacDecoderChannelInfo[aacChannels],
3128
491k
                &self->pAacDecoderStaticChannelInfo[aacChannels],
3129
491k
                &self->samplingRateInfo[streamIndex], self->flags[streamIndex],
3130
491k
                self->elFlags[element_count], el_channels);
3131
491k
          }
3132
491k
          aacChannels += el_channels;
3133
491k
          break;
3134
0
        case ID_NONE:
3135
0
          type = ID_END;
3136
0
          break;
3137
429k
        default:
3138
429k
          break;
3139
921k
      }
3140
921k
    }
3141
956k
    element_count++;
3142
956k
  }
3143
3144
  /* More AAC channels than specified by the ASC not allowed. */
3145
416k
  if ((aacChannels == 0 || aacChannels > self->aacChannels) &&
3146
11.2k
      !(flags & (AACDEC_CONCEAL | AACDEC_FLUSH))) {
3147
    /* Do not overwrite current error */
3148
11.2k
    if (ErrorStatus == AAC_DEC_OK) {
3149
2.34k
      ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
3150
2.34k
    }
3151
11.2k
    self->frameOK = 0;
3152
11.2k
    aacChannels = 0;
3153
11.2k
  }
3154
3155
416k
  if (!(flags & (AACDEC_CONCEAL | AACDEC_FLUSH))) {
3156
416k
    if (TRANSPORTDEC_OK != transportDec_CrcCheck(self->hInput)) {
3157
0
      ErrorStatus = AAC_DEC_CRC_ERROR;
3158
0
      self->frameOK = 0;
3159
0
    }
3160
416k
  }
3161
3162
  /* Ensure that in case of concealment a proper error status is set. */
3163
416k
  if ((self->frameOK == 0) && (ErrorStatus == AAC_DEC_OK)) {
3164
0
    ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
3165
0
  }
3166
3167
416k
  if (self->frameOK && (flags & AACDEC_FLUSH)) {
3168
26
    aacChannels = self->aacChannelsPrev;
3169
    /* Because the downmix could be active, its necessary to restore the channel
3170
     * type and indices. */
3171
26
    FDKmemcpy(self->channelType, self->channelTypePrev,
3172
26
              (8) * sizeof(AUDIO_CHANNEL_TYPE)); /* restore */
3173
26
    FDKmemcpy(self->channelIndices, self->channelIndicesPrev,
3174
26
              (8) * sizeof(UCHAR)); /* restore */
3175
26
    self->sbrEnabled = self->sbrEnabledPrev;
3176
416k
  } else {
3177
    /* store or restore the number of channels and the corresponding info */
3178
416k
    if (self->frameOK && !(flags & AACDEC_CONCEAL)) {
3179
405k
      self->aacChannelsPrev = aacChannels; /* store */
3180
405k
      FDKmemcpy(self->channelTypePrev, self->channelType,
3181
405k
                (8) * sizeof(AUDIO_CHANNEL_TYPE)); /* store */
3182
405k
      FDKmemcpy(self->channelIndicesPrev, self->channelIndices,
3183
405k
                (8) * sizeof(UCHAR)); /* store */
3184
405k
      self->sbrEnabledPrev = self->sbrEnabled;
3185
405k
    } else {
3186
11.2k
      if (self->aacChannels > 0) {
3187
11.2k
        if ((self->buildUpStatus == AACDEC_RSV60_BUILD_UP_ON) ||
3188
11.2k
            (self->buildUpStatus == AACDEC_RSV60_BUILD_UP_ON_IN_BAND) ||
3189
11.2k
            (self->buildUpStatus == AACDEC_USAC_BUILD_UP_ON)) {
3190
843
          aacChannels = self->aacChannels;
3191
843
          self->aacChannelsPrev = aacChannels; /* store */
3192
10.3k
        } else {
3193
10.3k
          aacChannels = self->aacChannelsPrev; /* restore */
3194
10.3k
        }
3195
11.2k
        FDKmemcpy(self->channelType, self->channelTypePrev,
3196
11.2k
                  (8) * sizeof(AUDIO_CHANNEL_TYPE)); /* restore */
3197
11.2k
        FDKmemcpy(self->channelIndices, self->channelIndicesPrev,
3198
11.2k
                  (8) * sizeof(UCHAR)); /* restore */
3199
11.2k
        self->sbrEnabled = self->sbrEnabledPrev;
3200
11.2k
      }
3201
11.2k
    }
3202
416k
  }
3203
3204
  /* Update number of output channels */
3205
416k
  self->streamInfo.aacNumChannels = aacChannels;
3206
3207
  /* Ensure consistency of IS_OUTPUT_VALID() macro. */
3208
416k
  if (aacChannels == 0) {
3209
4.03k
    ErrorStatus = AAC_DEC_UNKNOWN;
3210
4.03k
  }
3211
3212
416k
  if (pceRead == 1 && CProgramConfig_IsValid(pce)) {
3213
    /* Set matrix mixdown infos if available from PCE. */
3214
133
    pcmDmx_SetMatrixMixdownFromPce(
3215
133
        self->hPcmUtils, pce->MatrixMixdownIndexPresent,
3216
133
        pce->MatrixMixdownIndex, pce->PseudoSurroundEnable);
3217
133
    ;
3218
133
  }
3219
3220
  /* If there is no valid data to transfrom into time domain, return. */
3221
416k
  if (!IS_OUTPUT_VALID(ErrorStatus)) {
3222
4.03k
    return ErrorStatus;
3223
4.03k
  }
3224
3225
  /* Setup the output channel mapping. The table below shows the three
3226
   * possibilities: # | chCfg | PCE | chMapIndex
3227
   *  ---+-------+-----+------------------
3228
   *   1 |  > 0  |  no | chCfg
3229
   *   2 |   0   | yes | cChCfg
3230
   *   3 |   0   |  no | aacChannels || 0
3231
   *  ---+-------+-----+--------+------------------
3232
   *  Where chCfg is the channel configuration index from ASC and cChCfg is a
3233
   * corresponding chCfg derived from a given PCE. The variable aacChannels
3234
   * represents the number of channel found during bitstream decoding. Due to
3235
   * the structure of the mapping table it can only be used for mapping if its
3236
   * value is smaller than 7. Otherwise we use the fallback (0) which is a
3237
   * simple pass-through. The possibility #3 should appear only with MPEG-2
3238
   * (ADTS) streams. This is mode is called "implicit channel mapping".
3239
   */
3240
412k
  if ((self->streamInfo.channelConfig == 0) && !pce->isValid) {
3241
0
    self->chMapIndex = (aacChannels < 7) ? aacChannels : 0;
3242
0
  }
3243
3244
  /*
3245
    Inverse transform
3246
  */
3247
412k
  {
3248
412k
    int c, cIdx;
3249
412k
    int mapped, fCopyChMap = 1;
3250
412k
    UCHAR drcChMap[(8)];
3251
3252
412k
    if ((self->streamInfo.channelConfig == 0) && CProgramConfig_IsValid(pce)) {
3253
      /* ISO/IEC 14496-3 says:
3254
           If a PCE is present, the exclude_mask bits correspond to the audio
3255
         channels in the SCE, CPE, CCE and LFE syntax elements in the order of
3256
         their appearance in the PCE. In the case of a CPE, the first
3257
         transmitted mask bit corresponds to the first channel in the CPE, the
3258
         second transmitted mask bit to the second channel. In the case of a
3259
         CCE, a mask bit is transmitted only if the coupling channel is
3260
         specified to be an independently switched coupling channel. Thus we
3261
         have to convert the internal channel mapping from "canonical" MPEG to
3262
         PCE order: */
3263
1.61k
      UCHAR tmpChMap[(8)];
3264
1.61k
      if (CProgramConfig_GetPceChMap(pce, tmpChMap, (8)) == 0) {
3265
9.56k
        for (c = 0; c < aacChannels; c += 1) {
3266
7.94k
          drcChMap[c] =
3267
7.94k
              (self->chMapping[c] == 255) ? 255 : tmpChMap[self->chMapping[c]];
3268
7.94k
        }
3269
1.61k
        fCopyChMap = 0;
3270
1.61k
      }
3271
1.61k
    }
3272
412k
    if (fCopyChMap != 0) {
3273
411k
      FDKmemcpy(drcChMap, self->chMapping, (8) * sizeof(UCHAR));
3274
411k
    }
3275
3276
    /* Extract DRC control data and map it to channels (without bitstream delay)
3277
     */
3278
412k
    mapped = aacDecoder_drcProlog(
3279
412k
        self->hDrcInfo, bs, self->pAacDecoderStaticChannelInfo,
3280
412k
        pce->ElementInstanceTag, drcChMap, aacChannels);
3281
412k
    if (mapped > 0) {
3282
3.61k
      if (!(self->flags[streamIndex] & (AC_USAC | AC_RSV603DA))) {
3283
        /* If at least one DRC thread has been mapped to a channel there was DRC
3284
         * data in the bitstream. */
3285
3.61k
        self->flags[streamIndex] |= AC_DRC_PRESENT;
3286
3.61k
      } else {
3287
0
        ErrorStatus = AAC_DEC_UNSUPPORTED_FORMAT;
3288
0
      }
3289
3.61k
    }
3290
412k
    if (self->flags[streamIndex] & (AC_USAC | AC_RSV603DA)) {
3291
271k
      aacDecoder_drcDisable(self->hDrcInfo);
3292
271k
    }
3293
3294
    /* Create a reverse mapping table */
3295
412k
    UCHAR Reverse_chMapping[((8) * 2)];
3296
1.10M
    for (c = 0; c < aacChannels; c++) {
3297
689k
      int d;
3298
1.39M
      for (d = 0; d < aacChannels - 1; d++) {
3299
977k
        if (self->chMapping[d] == c) {
3300
276k
          break;
3301
276k
        }
3302
977k
      }
3303
689k
      Reverse_chMapping[c] = d;
3304
689k
    }
3305
3306
412k
    int el;
3307
412k
    int el_channels;
3308
412k
    c = 0;
3309
412k
    cIdx = 0;
3310
412k
    el_channels = 0;
3311
1.35M
    for (el = 0; el < element_count; el++) {
3312
941k
      int frameOk_butConceal =
3313
941k
          0; /* Force frame concealment during mute release active state. */
3314
941k
      int concealApplyReturnCode;
3315
3316
941k
      if (self->flags[streamIndex] & (AC_USAC | AC_RSV603DA | AC_BSAC)) {
3317
568k
        type = self->elements[el];
3318
568k
      } else {
3319
373k
        type = channel_elements[el];
3320
373k
      }
3321
3322
941k
      {
3323
941k
        int nElementChannels;
3324
3325
941k
        nElementChannels =
3326
941k
            CAacDecoder_GetELChannels(type, self->usacStereoConfigIndex[el]);
3327
3328
941k
        el_channels += nElementChannels;
3329
3330
941k
        if (nElementChannels == 0) {
3331
440k
          continue;
3332
440k
        }
3333
941k
      }
3334
3335
501k
      int offset;
3336
501k
      int elCh = 0;
3337
      /* "c" iterates in canonical MPEG channel order */
3338
1.19M
      for (; cIdx < el_channels; c++, cIdx++, elCh++) {
3339
        /* Robustness check */
3340
690k
        if (c >= aacChannels) {
3341
284
          return AAC_DEC_UNKNOWN;
3342
284
        }
3343
3344
689k
        CAacDecoderChannelInfo *pAacDecoderChannelInfo =
3345
689k
            self->pAacDecoderChannelInfo[c];
3346
689k
        CAacDecoderStaticChannelInfo *pAacDecoderStaticChannelInfo =
3347
689k
            self->pAacDecoderStaticChannelInfo[c];
3348
3349
        /* Setup offset for time buffer traversal. */
3350
689k
        {
3351
689k
          pAacDecoderStaticChannelInfo =
3352
689k
              self->pAacDecoderStaticChannelInfo[Reverse_chMapping[c]];
3353
689k
          offset =
3354
689k
              FDK_chMapDescr_getMapValue(
3355
689k
                  &self->mapDescr, Reverse_chMapping[cIdx], self->chMapIndex) *
3356
689k
              timeDataChannelOffset;
3357
689k
        }
3358
3359
689k
        if (flags & AACDEC_FLUSH) {
3360
          /* Clear pAacDecoderChannelInfo->pSpectralCoefficient because with
3361
           * AACDEC_FLUSH set it contains undefined data. */
3362
26
          FDKmemclear(pAacDecoderChannelInfo->pSpectralCoefficient,
3363
26
                      sizeof(FIXP_DBL) * self->streamInfo.aacSamplesPerFrame);
3364
26
        }
3365
3366
        /* if The ics info is not valid and it will be stored and used in the
3367
         * following concealment method, mark the frame as erroneous */
3368
689k
        {
3369
689k
          CIcsInfo *pIcsInfo = &pAacDecoderChannelInfo->icsInfo;
3370
689k
          CConcealmentInfo *hConcealmentInfo =
3371
689k
              &pAacDecoderStaticChannelInfo->concealmentInfo;
3372
689k
          const int mute_release_active =
3373
689k
              (self->frameOK && !(flags & AACDEC_CONCEAL)) &&
3374
677k
              ((hConcealmentInfo->concealState >= ConcealState_Mute) &&
3375
0
               (hConcealmentInfo->cntValidFrames + 1 <=
3376
0
                hConcealmentInfo->pConcealParams->numMuteReleaseFrames));
3377
689k
          const int icsIsInvalid = (GetScaleFactorBandsTransmitted(pIcsInfo) >
3378
689k
                                    GetScaleFactorBandsTotal(pIcsInfo));
3379
689k
          const int icsInfoUsedinFadeOut =
3380
689k
              !(pAacDecoderChannelInfo->renderMode == AACDEC_RENDER_LPD &&
3381
48.8k
                pAacDecoderStaticChannelInfo->last_lpd_mode == 0);
3382
689k
          if (icsInfoUsedinFadeOut && icsIsInvalid && !mute_release_active) {
3383
475
            self->frameOK = 0;
3384
475
          }
3385
689k
        }
3386
3387
        /*
3388
          Conceal defective spectral data
3389
        */
3390
689k
        {
3391
689k
          CAacDecoderChannelInfo **ppAacDecoderChannelInfo =
3392
689k
              &pAacDecoderChannelInfo;
3393
689k
          CAacDecoderStaticChannelInfo **ppAacDecoderStaticChannelInfo =
3394
689k
              &pAacDecoderStaticChannelInfo;
3395
689k
          {
3396
689k
            concealApplyReturnCode = CConcealment_Apply(
3397
689k
                &(*ppAacDecoderStaticChannelInfo)->concealmentInfo,
3398
689k
                *ppAacDecoderChannelInfo, *ppAacDecoderStaticChannelInfo,
3399
689k
                &self->samplingRateInfo[streamIndex],
3400
689k
                self->streamInfo.aacSamplesPerFrame,
3401
689k
                pAacDecoderStaticChannelInfo->last_lpd_mode,
3402
689k
                (self->frameOK && !(flags & AACDEC_CONCEAL)),
3403
689k
                self->flags[streamIndex]);
3404
689k
          }
3405
689k
        }
3406
689k
        if (concealApplyReturnCode == -1) {
3407
0
          frameOk_butConceal = 1;
3408
0
        }
3409
3410
689k
        if (flags & (AACDEC_INTR)) {
3411
          /* Reset DRC control data for this channel */
3412
0
          aacDecoder_drcInitChannelData(&pAacDecoderStaticChannelInfo->drcData);
3413
0
        }
3414
689k
        if (flags & (AACDEC_CLRHIST)) {
3415
0
          if (!(self->flags[0] & AC_USAC)) {
3416
            /* Reset DRC control data for this channel */
3417
0
            aacDecoder_drcInitChannelData(
3418
0
                &pAacDecoderStaticChannelInfo->drcData);
3419
0
          }
3420
0
        }
3421
3422
        /* The DRC module demands to be called with the gain field holding the
3423
         * gain scale. */
3424
689k
        self->extGain[0] = (FIXP_DBL)AACDEC_DRC_GAIN_SCALING;
3425
3426
        /* DRC processing */
3427
689k
        aacDecoder_drcApply(
3428
689k
            self->hDrcInfo, self->hSbrDecoder, pAacDecoderChannelInfo,
3429
689k
            &pAacDecoderStaticChannelInfo->drcData, self->extGain, c,
3430
689k
            self->streamInfo.aacSamplesPerFrame, self->sbrEnabled
3431
3432
689k
        );
3433
3434
689k
        if (timeDataSize < timeDataChannelOffset * self->aacChannels) {
3435
0
          ErrorStatus = AAC_DEC_OUTPUT_BUFFER_TOO_SMALL;
3436
0
          break;
3437
0
        }
3438
689k
        if (self->flushStatus && (self->flushCnt > 0) &&
3439
0
            !(flags & AACDEC_CONCEAL)) {
3440
0
          FDKmemclear(pTimeData + offset,
3441
0
                      sizeof(PCM_DEC) * self->streamInfo.aacSamplesPerFrame);
3442
0
        } else
3443
689k
          switch (pAacDecoderChannelInfo->renderMode) {
3444
410k
            case AACDEC_RENDER_IMDCT:
3445
3446
410k
              CBlock_FrequencyToTime(
3447
410k
                  pAacDecoderStaticChannelInfo, pAacDecoderChannelInfo,
3448
410k
                  pTimeData + offset, self->streamInfo.aacSamplesPerFrame,
3449
410k
                  (self->frameOK && !(flags & AACDEC_CONCEAL) &&
3450
402k
                   !frameOk_butConceal),
3451
410k
                  pAacDecoderChannelInfo->pComStaticData->pWorkBufferCore1
3452
410k
                      ->mdctOutTemp,
3453
410k
                  self->aacOutDataHeadroom, self->elFlags[el], elCh);
3454
3455
410k
              self->extGainDelay = self->streamInfo.aacSamplesPerFrame;
3456
410k
              break;
3457
231k
            case AACDEC_RENDER_ELDFB: {
3458
231k
              CBlock_FrequencyToTimeLowDelay(
3459
231k
                  pAacDecoderStaticChannelInfo, pAacDecoderChannelInfo,
3460
231k
                  pTimeData + offset, self->streamInfo.aacSamplesPerFrame);
3461
231k
              self->extGainDelay =
3462
231k
                  (self->streamInfo.aacSamplesPerFrame * 2 -
3463
231k
                   self->streamInfo.aacSamplesPerFrame / 2 - 1) /
3464
231k
                  2;
3465
231k
            } break;
3466
48.5k
            case AACDEC_RENDER_LPD:
3467
3468
48.5k
              CLpd_RenderTimeSignal(
3469
48.5k
                  pAacDecoderStaticChannelInfo, pAacDecoderChannelInfo,
3470
48.5k
                  pTimeData + offset, self->streamInfo.aacSamplesPerFrame,
3471
48.5k
                  &self->samplingRateInfo[streamIndex],
3472
48.5k
                  (self->frameOK && !(flags & AACDEC_CONCEAL) &&
3473
47.4k
                   !frameOk_butConceal),
3474
48.5k
                  self->aacOutDataHeadroom, flags, self->flags[streamIndex]);
3475
3476
48.5k
              self->extGainDelay = self->streamInfo.aacSamplesPerFrame;
3477
48.5k
              break;
3478
0
            default:
3479
0
              ErrorStatus = AAC_DEC_UNKNOWN;
3480
0
              break;
3481
689k
          }
3482
        /* TimeDomainFading */
3483
689k
        if (!CConceal_TDFading_Applied[c]) {
3484
689k
          CConceal_TDFading_Applied[c] = CConcealment_TDFading(
3485
689k
              self->streamInfo.aacSamplesPerFrame,
3486
689k
              &self->pAacDecoderStaticChannelInfo[c], self->aacOutDataHeadroom,
3487
689k
              pTimeData + offset, 0);
3488
689k
          if (c + 1 < (8) && c < aacChannels - 1) {
3489
            /* update next TDNoise Seed to avoid muting in case of Parametric
3490
             * Stereo */
3491
277k
            self->pAacDecoderStaticChannelInfo[c + 1]
3492
277k
                ->concealmentInfo.TDNoiseSeed =
3493
277k
                self->pAacDecoderStaticChannelInfo[c]
3494
277k
                    ->concealmentInfo.TDNoiseSeed;
3495
277k
          }
3496
689k
        }
3497
689k
      }
3498
501k
    }
3499
3500
412k
    if (self->flags[streamIndex] & AC_USAC) {
3501
271k
      int bsPseudoLr = 0;
3502
271k
      mpegSurroundDecoder_IsPseudoLR(
3503
271k
          (CMpegSurroundDecoder *)self->pMpegSurroundDecoder, &bsPseudoLr);
3504
      /* ISO/IEC 23003-3, 7.11.2.6 Modification of core decoder output (pseudo
3505
       * LR) */
3506
271k
      if ((aacChannels == 2) && bsPseudoLr) {
3507
14.6k
        int i, offset2;
3508
14.6k
        const FIXP_SGL invSqrt2 = FL2FXCONST_SGL(0.707106781186547f);
3509
14.6k
        PCM_DEC *pTD = pTimeData;
3510
3511
14.6k
        offset2 = timeDataChannelOffset;
3512
3513
13.8M
        for (i = 0; i < self->streamInfo.aacSamplesPerFrame; i++) {
3514
13.8M
          FIXP_DBL L = PCM_DEC2FIXP_DBL(pTD[0]);
3515
13.8M
          FIXP_DBL R = PCM_DEC2FIXP_DBL(pTD[offset2]);
3516
13.8M
          L = fMult(L, invSqrt2);
3517
13.8M
          R = fMult(R, invSqrt2);
3518
13.8M
          pTD[0] = L + R;
3519
13.8M
          pTD[offset2] = L - R;
3520
13.8M
          pTD++;
3521
13.8M
        }
3522
14.6k
      }
3523
271k
    }
3524
3525
    /* Extract DRC control data and map it to channels (with bitstream delay) */
3526
412k
    mapped = aacDecoder_drcEpilog(
3527
412k
        self->hDrcInfo, bs, self->pAacDecoderStaticChannelInfo,
3528
412k
        pce->ElementInstanceTag, drcChMap, aacChannels);
3529
412k
    if (mapped > 0) {
3530
5.21k
      if (!(self->flags[streamIndex] & (AC_USAC | AC_RSV603DA))) {
3531
        /* If at least one DRC thread has been mapped to a channel there was DRC
3532
         * data in the bitstream. */
3533
5.21k
        self->flags[streamIndex] |= AC_DRC_PRESENT;
3534
5.21k
      } else {
3535
0
        ErrorStatus = AAC_DEC_UNSUPPORTED_FORMAT;
3536
0
      }
3537
5.21k
    }
3538
412k
    if (self->flags[streamIndex] & (AC_USAC | AC_RSV603DA)) {
3539
271k
      aacDecoder_drcDisable(self->hDrcInfo);
3540
271k
    }
3541
412k
  }
3542
3543
  /* Add additional concealment delay */
3544
0
  self->streamInfo.outputDelay +=
3545
412k
      CConcealment_GetDelay(&self->concealCommonData) *
3546
412k
      self->streamInfo.aacSamplesPerFrame;
3547
3548
  /* Map DRC data to StreamInfo structure */
3549
412k
  aacDecoder_drcGetInfo(self->hDrcInfo, &self->streamInfo.drcPresMode,
3550
412k
                        &self->streamInfo.drcProgRefLev);
3551
3552
  /* Reorder channel type information tables.  */
3553
412k
  if (!(self->flags[0] & AC_RSV603DA)) {
3554
412k
    AUDIO_CHANNEL_TYPE types[(8)];
3555
412k
    UCHAR idx[(8)];
3556
412k
    int c;
3557
412k
    int mapValue;
3558
3559
412k
    FDK_ASSERT(sizeof(self->channelType) == sizeof(types));
3560
412k
    FDK_ASSERT(sizeof(self->channelIndices) == sizeof(idx));
3561
3562
412k
    FDKmemcpy(types, self->channelType, sizeof(types));
3563
412k
    FDKmemcpy(idx, self->channelIndices, sizeof(idx));
3564
3565
1.10M
    for (c = 0; c < aacChannels; c++) {
3566
689k
      mapValue =
3567
689k
          FDK_chMapDescr_getMapValue(&self->mapDescr, c, self->chMapIndex);
3568
689k
      self->channelType[mapValue] = types[c];
3569
689k
      self->channelIndices[mapValue] = idx[c];
3570
689k
    }
3571
412k
  }
3572
3573
412k
  self->blockNumber++;
3574
3575
412k
  return ErrorStatus;
3576
412k
}
3577
3578
/*!
3579
  \brief returns the streaminfo pointer
3580
3581
  The function hands back a pointer to the streaminfo structure
3582
3583
  \return pointer to the struct
3584
*/
3585
0
LINKSPEC_CPP CStreamInfo *CAacDecoder_GetStreamInfo(HANDLE_AACDECODER self) {
3586
0
  if (!self) {
3587
0
    return NULL;
3588
0
  }
3589
0
  return &self->streamInfo;
3590
0
}