Coverage Report

Created: 2026-04-01 07:00

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
379k
  (((aot) == AOT_DRM_AAC) && !(flags & AC_PS_PRESENT))
182
183
#define IS_STEREO_SBR(el_id, stereoConfigIndex)            \
184
193k
  (((el_id) == ID_USAC_CPE && (stereoConfigIndex) == 0) || \
185
193k
   ((el_id) == ID_USAC_CPE && (stereoConfigIndex) == 3))
186
187
366k
void CAacDecoder_SyncQmfMode(HANDLE_AACDECODER self) {
188
366k
  FDK_ASSERT(
189
366k
      !((self->flags[0] & AC_MPS_PRESENT) && (self->flags[0] & AC_PS_PRESENT)));
190
191
  /* Assign user requested mode */
192
366k
  self->qmfModeCurr = self->qmfModeUser;
193
194
366k
  if (IS_USAC(self->streamInfo.aot)) {
195
217k
    self->qmfModeCurr = MODE_HQ;
196
217k
  }
197
198
366k
  if (self->qmfModeCurr == NOT_DEFINED) {
199
148k
    if ((IS_LOWDELAY(self->streamInfo.aot) &&
200
73.3k
         (self->flags[0] & AC_MPS_PRESENT)) ||
201
107k
        ((self->streamInfo.aacNumChannels == 1) &&
202
35.8k
         ((CAN_DO_PS(self->streamInfo.aot) &&
203
9.96k
           !(self->flags[0] & AC_MPS_PRESENT)) ||
204
50.8k
          (IS_USAC(self->streamInfo.aot))))) {
205
50.8k
      self->qmfModeCurr = MODE_HQ;
206
97.5k
    } else {
207
97.5k
      self->qmfModeCurr = MODE_LP;
208
97.5k
    }
209
148k
  }
210
211
366k
  if (self->mpsEnableCurr) {
212
149k
    if (IS_LOWDELAY(self->streamInfo.aot) &&
213
38.1k
        (self->qmfModeCurr == MODE_LP)) { /* Overrule user requested QMF mode */
214
164
      self->qmfModeCurr = MODE_HQ;
215
164
    }
216
    /* Set and check if MPS decoder allows the current mode */
217
149k
    switch (mpegSurroundDecoder_SetParam(
218
149k
        (CMpegSurroundDecoder *)self->pMpegSurroundDecoder,
219
149k
        SACDEC_PARTIALLY_COMPLEX, self->qmfModeCurr == MODE_LP)) {
220
0
      case MPS_OK:
221
0
        break;
222
149k
      case MPS_INVALID_PARAMETER: { /* Only one mode supported. Find out which
223
                                       one: */
224
149k
        LIB_INFO libInfo[FDK_MODULE_LAST];
225
149k
        UINT mpsCaps;
226
227
149k
        FDKinitLibInfo(libInfo);
228
149k
        mpegSurroundDecoder_GetLibInfo(libInfo);
229
149k
        mpsCaps = FDKlibInfo_getCapabilities(libInfo, FDK_MPSDEC);
230
231
149k
        if (((mpsCaps & CAPF_MPS_LP) && (self->qmfModeCurr == MODE_LP)) ||
232
149k
            ((mpsCaps & CAPF_MPS_HQ) &&
233
149k
             (self->qmfModeCurr ==
234
149k
              MODE_HQ))) { /* MPS decoder does support the requested mode. */
235
148k
          break;
236
148k
        }
237
149k
      }
238
605
        FDK_FALLTHROUGH;
239
605
      default:
240
605
        if (self->qmfModeUser == NOT_DEFINED) {
241
          /* Revert in case mpegSurroundDecoder_SetParam() fails. */
242
605
          self->qmfModeCurr =
243
605
              (self->qmfModeCurr == MODE_LP) ? MODE_HQ : MODE_LP;
244
605
        } else {
245
          /* in case specific mode was requested we disable MPS and playout the
246
           * downmix */
247
0
          self->mpsEnableCurr = 0;
248
0
        }
249
149k
    }
250
149k
  }
251
252
  /* Set SBR to current QMF mode. Error does not matter. */
253
366k
  sbrDecoder_SetParam(self->hSbrDecoder, SBR_QMF_MODE,
254
366k
                      (self->qmfModeCurr == MODE_LP));
255
366k
  self->psPossible =
256
366k
      ((CAN_DO_PS(self->streamInfo.aot) &&
257
13.8k
        !PS_IS_EXPLICITLY_DISABLED(self->streamInfo.aot, self->flags[0]) &&
258
13.8k
        self->streamInfo.aacNumChannels == 1 &&
259
9.96k
        !(self->flags[0] & AC_MPS_PRESENT))) &&
260
9.96k
      self->qmfModeCurr == MODE_HQ;
261
366k
  FDK_ASSERT(!((self->flags[0] & AC_MPS_PRESENT) && self->psPossible));
262
366k
}
263
264
6.44k
void CAacDecoder_SignalInterruption(HANDLE_AACDECODER self) {
265
6.44k
  if (self->flags[0] & (AC_USAC | AC_RSVD50 | AC_RSV603DA)) {
266
4.38k
    int i;
267
268
9.94k
    for (i = 0; i < fMin(self->aacChannels, (8)); i++) {
269
5.56k
      if (self->pAacDecoderStaticChannelInfo
270
5.56k
              [i]) { /* number of active channels can be smaller */
271
5.56k
        self->pAacDecoderStaticChannelInfo[i]->hArCo->m_numberLinesPrev = 0;
272
5.56k
      }
273
5.56k
    }
274
4.38k
  }
275
6.44k
}
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
1.96M
                                     UCHAR usacStereoConfigIndex) {
287
1.96M
  int el_channels = 0;
288
289
1.96M
  switch (type) {
290
536k
    case ID_USAC_CPE:
291
536k
      if (usacStereoConfigIndex == 1) {
292
286k
        el_channels = 1;
293
286k
      } else {
294
250k
        el_channels = 2;
295
250k
      }
296
536k
      break;
297
461k
    case ID_CPE:
298
461k
      el_channels = 2;
299
461k
      break;
300
159k
    case ID_USAC_SCE:
301
159k
    case ID_USAC_LFE:
302
500k
    case ID_SCE:
303
618k
    case ID_LFE:
304
618k
      el_channels = 1;
305
618k
      break;
306
349k
    default:
307
349k
      el_channels = 0;
308
349k
      break;
309
1.96M
  }
310
311
1.96M
  return el_channels;
312
1.96M
}
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
355k
static AAC_DECODER_ERROR CAacDecoder_AncDataReset(CAncData *ancData) {
322
355k
  int i;
323
3.19M
  for (i = 0; i < 8; i++) {
324
2.84M
    ancData->offset[i] = 0;
325
2.84M
  }
326
355k
  ancData->nrElements = 0;
327
328
355k
  return AAC_DEC_OK;
329
355k
}
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
22.2k
                                          unsigned char *buffer, int size) {
342
22.2k
  if (size >= 0) {
343
22.2k
    ancData->buffer = buffer;
344
22.2k
    ancData->bufferSize = size;
345
346
22.2k
    CAacDecoder_AncDataReset(ancData);
347
348
22.2k
    return AAC_DEC_OK;
349
22.2k
  }
350
351
0
  return AAC_DEC_ANC_DATA_ERROR;
352
22.2k
}
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
9.67k
                                                  const int ancBytes) {
392
9.67k
  AAC_DECODER_ERROR error = AAC_DEC_OK;
393
9.67k
  int readBytes = 0;
394
395
9.67k
  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
9.67k
  readBytes = ancBytes - readBytes;
420
421
9.67k
  if (readBytes > 0) {
422
    /* skip data */
423
5.80k
    FDKpushFor(hBs, readBytes << 3);
424
5.80k
  }
425
426
9.67k
  return error;
427
9.67k
}
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.25k
                                                 UINT alignmentAnchor) {
440
9.25k
  AAC_DECODER_ERROR error = AAC_DEC_OK;
441
9.25k
  UINT dseBits;
442
9.25k
  INT dataStart;
443
9.25k
  int dataByteAlignFlag, count;
444
445
9.25k
  FDK_ASSERT(self != NULL);
446
447
9.25k
  int crcReg = transportDec_CrcStartReg(self->hInput, 0);
448
449
  /* Element Instance Tag */
450
9.25k
  *elementInstanceTag = FDKreadBits(bs, 4);
451
  /* Data Byte Align Flag */
452
9.25k
  dataByteAlignFlag = FDKreadBits(bs, 1);
453
454
9.25k
  count = FDKreadBits(bs, 8);
455
456
9.25k
  if (count == 255) {
457
13
    count += FDKreadBits(bs, 8); /* EscCount */
458
13
  }
459
9.25k
  dseBits = count * 8;
460
461
9.25k
  if (dataByteAlignFlag) {
462
4.92k
    FDKbyteAlign(bs, alignmentAnchor);
463
4.92k
  }
464
465
9.25k
  dataStart = (INT)FDKgetValidBits(bs);
466
467
9.25k
  error = CAacDecoder_AncDataParse(&self->ancData, bs, count);
468
9.25k
  transportDec_CrcEndReg(self->hInput, crcReg);
469
470
9.25k
  {
471
    /* Move to the beginning of the data chunk */
472
9.25k
    FDKpushBack(bs, dataStart - (INT)FDKgetValidBits(bs));
473
474
    /* Read Anc data if available */
475
9.25k
    aacDecoder_drcMarkPayload(self->hDrcInfo, bs, DVB_DRC_ANC_DATA);
476
9.25k
  }
477
478
9.25k
  {
479
9.25k
    PCMDMX_ERROR dmxErr = PCMDMX_OK;
480
481
    /* Move to the beginning of the data chunk */
482
9.25k
    FDKpushBack(bs, dataStart - (INT)FDKgetValidBits(bs));
483
484
    /* Read DMX meta-data */
485
9.25k
    dmxErr = pcmDmx_Parse(self->hPcmUtils, bs, dseBits, 0 /* not mpeg2 */);
486
9.25k
    if (error == AAC_DEC_OK && dmxErr != PCMDMX_OK) {
487
6.36k
      error = AAC_DEC_UNKNOWN;
488
6.36k
    }
489
9.25k
  }
490
491
  /* Move to the very end of the element. */
492
9.25k
  FDKpushBiDirectional(bs, (INT)FDKgetValidBits(bs) - dataStart + (INT)dseBits);
493
494
9.25k
  return error;
495
9.25k
}
496
497
static INT findElementInstanceTag(
498
    INT elementTag, MP4_ELEMENT_ID elementId,
499
    CAacDecoderChannelInfo **pAacDecoderChannelInfo, INT nChannels,
500
4.61k
    MP4_ELEMENT_ID *pElementIdTab, INT nElements) {
501
4.61k
  int el, chCnt = 0;
502
503
11.7k
  for (el = 0; el < nElements; el++) {
504
11.7k
    switch (pElementIdTab[el]) {
505
3.32k
      case ID_CPE:
506
10.4k
      case ID_SCE:
507
11.7k
      case ID_LFE:
508
11.7k
        if ((elementTag == pAacDecoderChannelInfo[chCnt]->ElementInstanceTag) &&
509
5.15k
            (elementId == pElementIdTab[el])) {
510
4.59k
          return 1; /* element instance tag found */
511
4.59k
        }
512
7.19k
        chCnt += (pElementIdTab[el] == ID_CPE) ? 2 : 1;
513
7.19k
        break;
514
0
      default:
515
0
        break;
516
11.7k
    }
517
7.19k
    if (chCnt >= nChannels) break;
518
7.17k
    if (pElementIdTab[el] == ID_END) break;
519
7.17k
  }
520
521
18
  return 0; /* element instance tag not found */
522
4.61k
}
523
524
static INT validateElementInstanceTags(
525
    CProgramConfig *pce, CAacDecoderChannelInfo **pAacDecoderChannelInfo,
526
1.30k
    INT nChannels, MP4_ELEMENT_ID *pElementIdTab, INT nElements) {
527
1.30k
  if (nChannels >= pce->NumChannels) {
528
2.67k
    for (int el = 0; el < pce->NumFrontChannelElements; el++) {
529
1.37k
      if (!findElementInstanceTag(pce->FrontElementTagSelect[el],
530
1.37k
                                  pce->FrontElementIsCpe[el] ? ID_CPE : ID_SCE,
531
1.37k
                                  pAacDecoderChannelInfo, nChannels,
532
1.37k
                                  pElementIdTab, nElements)) {
533
4
        return 0; /* element instance tag not in raw_data_block() */
534
4
      }
535
1.37k
    }
536
2.51k
    for (int el = 0; el < pce->NumSideChannelElements; el++) {
537
1.23k
      if (!findElementInstanceTag(pce->SideElementTagSelect[el],
538
1.23k
                                  pce->SideElementIsCpe[el] ? ID_CPE : ID_SCE,
539
1.23k
                                  pAacDecoderChannelInfo, nChannels,
540
1.23k
                                  pElementIdTab, nElements)) {
541
6
        return 0; /* element instance tag not in raw_data_block() */
542
6
      }
543
1.23k
    }
544
2.67k
    for (int el = 0; el < pce->NumBackChannelElements; el++) {
545
1.38k
      if (!findElementInstanceTag(pce->BackElementTagSelect[el],
546
1.38k
                                  pce->BackElementIsCpe[el] ? ID_CPE : ID_SCE,
547
1.38k
                                  pAacDecoderChannelInfo, nChannels,
548
1.38k
                                  pElementIdTab, nElements)) {
549
4
        return 0; /* element instance tag not in raw_data_block() */
550
4
      }
551
1.38k
    }
552
1.90k
    for (int el = 0; el < pce->NumLfeChannelElements; el++) {
553
619
      if (!findElementInstanceTag(pce->LfeElementTagSelect[el], ID_LFE,
554
619
                                  pAacDecoderChannelInfo, nChannels,
555
619
                                  pElementIdTab, nElements)) {
556
4
        return 0; /* element instance tag not in raw_data_block() */
557
4
      }
558
619
    }
559
1.28k
  } else {
560
3
    return 0; /* too less decoded audio channels */
561
3
  }
562
563
1.28k
  return 1; /* all element instance tags found in raw_data_block() */
564
1.30k
}
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
2.37k
                                      const UINT alignAnchor) {
583
2.37k
  int pceStatus = 0;
584
2.37k
  int crcReg;
585
586
  /* read PCE to temporal buffer first */
587
2.37k
  C_ALLOC_SCRATCH_START(tmpPce, CProgramConfig, 1);
588
589
2.37k
  CProgramConfig_Init(tmpPce);
590
591
2.37k
  crcReg = transportDec_CrcStartReg(pTp, 0);
592
593
2.37k
  CProgramConfig_Read(tmpPce, bs, alignAnchor);
594
595
2.37k
  transportDec_CrcEndReg(pTp, crcReg);
596
597
2.37k
  if (CProgramConfig_IsValid(tmpPce) && (tmpPce->Profile == 1)) {
598
1.54k
    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
1.54k
    if (CProgramConfig_IsValid(pce)) {
604
      /* Compare the new and the old PCE (tags ignored) */
605
1.54k
      switch (CProgramConfig_Compare(pce, tmpPce)) {
606
526
        case 1: /* Channel configuration not changed. Just new metadata. */
607
526
          FDKmemcpy(pce, tmpPce,
608
526
                    sizeof(CProgramConfig)); /* Store the complete PCE */
609
526
          pceStatus = 1; /* New PCE but no change of config */
610
526
          break;
611
2
        case 2:  /* The number of channels are identical but not the config */
612
11
        case -1: /* The channel configuration is completely different */
613
11
          pceStatus = -1; /* Not supported! */
614
11
          break;
615
1.00k
        case 0: /* Nothing to do because PCE matches the old one exactly. */
616
1.00k
        default:
617
          /* pceStatus = 0; */
618
1.00k
          break;
619
1.54k
      }
620
1.54k
    }
621
1.54k
  }
622
623
2.37k
  C_ALLOC_SCRATCH_END(tmpPce, CProgramConfig, 1);
624
625
2.37k
  return pceStatus;
626
2.37k
}
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
22
    const INT frameSize, const INT interleaved) {
642
22
  int i, ch, s1, s2;
643
22
  AAC_DECODER_ERROR ErrorStatus;
644
645
22
  ErrorStatus = AAC_DEC_OK;
646
647
22
  if (interleaved) {
648
22
    s1 = 1;
649
22
    s2 = numChannels;
650
22
  } else {
651
0
    s1 = frameSize;
652
0
    s2 = 1;
653
0
  }
654
655
44
  for (ch = 0; ch < numChannels; ch++) {
656
22
    const PCM_DEC *pIn = &pTimeData[ch * s1];
657
2.83k
    for (i = 0; i < TIME_DATA_FLUSH_SIZE; i++) {
658
2.81k
      pTimeDataFlush[ch][i] = *pIn;
659
2.81k
      pIn += s2;
660
2.81k
    }
661
22
  }
662
663
22
  return ErrorStatus;
664
22
}
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
174
    const INT frameSize, const INT interleaved) {
680
174
  int i, ch, s1, s2;
681
174
  AAC_DECODER_ERROR ErrorStatus;
682
683
174
  ErrorStatus = AAC_DEC_OK;
684
685
174
  if (interleaved) {
686
169
    s1 = 1;
687
169
    s2 = numChannels;
688
169
  } else {
689
5
    s1 = frameSize;
690
5
    s2 = 1;
691
5
  }
692
693
373
  for (ch = 0; ch < numChannels; ch++) {
694
199
    PCM_DEC *pIn = &pTimeData[ch * s1];
695
25.6k
    for (i = 0; i < TIME_DATA_FLUSH_SIZE; i++) {
696
25.4k
      FIXP_SGL alpha = (FIXP_SGL)i
697
25.4k
                       << (FRACT_BITS - 1 - TIME_DATA_FLUSH_SIZE_SF);
698
25.4k
      FIXP_DBL time = PCM_DEC2FIXP_DBL(*pIn);
699
25.4k
      FIXP_DBL timeFlush = PCM_DEC2FIXP_DBL(pTimeDataFlush[ch][i]);
700
701
25.4k
      *pIn = FIXP_DBL2PCM_DEC(timeFlush - fMult(timeFlush, alpha) +
702
25.4k
                              fMult(time, alpha));
703
25.4k
      pIn += s2;
704
25.4k
    }
705
199
  }
706
707
174
  return ErrorStatus;
708
174
}
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
3.08k
    UINT *prerollAULength) {
723
3.08k
  FDK_BITSTREAM bs;
724
3.08k
  HANDLE_FDK_BITSTREAM hBs;
725
3.08k
  AAC_DECODER_ERROR ErrorStatus;
726
727
3.08k
  INT auStartAnchor;
728
3.08k
  UINT independencyFlag;
729
3.08k
  UINT extPayloadPresentFlag;
730
3.08k
  UINT useDefaultLengthFlag;
731
3.08k
  UINT configLength = 0;
732
3.08k
  UINT preRollPossible = 1;
733
3.08k
  UINT i;
734
3.08k
  UCHAR configChanged = 0;
735
3.08k
  UCHAR config[TP_USAC_MAX_CONFIG_LEN] = {0};
736
3.08k
  UCHAR
737
3.08k
  implicitExplicitCfgDiff = 0; /* in case implicit and explicit config is
738
                                  equal preroll AU's should be processed
739
                                  after decoder reset */
740
741
3.08k
  ErrorStatus = AAC_DEC_OK;
742
743
3.08k
  hBs = transportDec_GetBitstream(self->hInput, 0);
744
3.08k
  bs = *hBs;
745
746
3.08k
  auStartAnchor = (INT)FDKgetValidBits(hBs);
747
3.08k
  if (auStartAnchor <= 0) {
748
6
    ErrorStatus = AAC_DEC_NOT_ENOUGH_BITS;
749
6
    goto bail;
750
6
  }
751
752
  /* Independency flag */
753
3.08k
  FDKreadBit(hBs);
754
755
  /* Payload present flag of extension ID_EXT_ELE_AUDIOPREROLL must be one */
756
3.08k
  extPayloadPresentFlag = FDKreadBits(hBs, 1);
757
3.08k
  if (!extPayloadPresentFlag) {
758
927
    preRollPossible = 0;
759
927
  }
760
761
  /* Default length flag of extension ID_EXT_ELE_AUDIOPREROLL must be zero */
762
3.08k
  useDefaultLengthFlag = FDKreadBits(hBs, 1);
763
3.08k
  if (useDefaultLengthFlag) {
764
363
    preRollPossible = 0;
765
363
  }
766
767
3.08k
  if (preRollPossible) { /* extPayloadPresentFlag && !useDefaultLengthFlag */
768
    /* Read overall ext payload length, useDefaultLengthFlag must be zero.  */
769
2.05k
    escapedValue(hBs, 8, 16, 0);
770
771
    /* Read RSVD60 Config size */
772
2.05k
    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.05k
  }
777
778
  /* If pre roll not possible then exit. */
779
3.08k
  if (preRollPossible == 0) {
780
    /* Sanity check: if flushing is switched on, preRollPossible must be 1 */
781
1.02k
    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.02k
    goto bail;
787
1.02k
  }
788
789
2.05k
  if (self->flags[0] & AC_USAC) {
790
1.22k
    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.56k
      for (i = 0; i < configLength; i++) {
794
1.47k
        config[i] = FDKreadBits(hBs, 8);
795
1.47k
      }
796
96
      TRANSPORTDEC_ERROR terr;
797
96
      terr = transportDec_InBandConfig(self->hInput, config, configLength,
798
96
                                       self->buildUpStatus, &configChanged, 0,
799
96
                                       &implicitExplicitCfgDiff);
800
96
      if (terr != TRANSPORTDEC_OK) {
801
40
        ErrorStatus = AAC_DEC_PARSE_ERROR;
802
40
        goto bail;
803
40
      }
804
96
    }
805
1.22k
  }
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.01k
  if ((self->streamInfo.numChannels == 0) && !implicitExplicitCfgDiff &&
811
1.03k
      (self->flags[0] & AC_USAC)) {
812
1.01k
    self->buildUpStatus = AACDEC_USAC_BUILD_UP_ON;
813
    /* sanity check: if buildUp status on -> flushing must be off */
814
1.01k
    if (self->flushStatus != AACDEC_FLUSH_OFF) {
815
0
      self->flushStatus = AACDEC_FLUSH_OFF;
816
0
      ErrorStatus = AAC_DEC_PARSE_ERROR;
817
0
      goto bail;
818
0
    }
819
1.01k
  }
820
821
2.01k
  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.18k
    if (self->buildUpStatus == AACDEC_USAC_BUILD_UP_ON) {
825
1.04k
      UCHAR applyCrossfade = FDKreadBit(hBs);
826
1.04k
      if (applyCrossfade) {
827
176
        self->applyCrossfade |= AACDEC_CROSSFADE_BITMASK_PREROLL;
828
864
      } else {
829
864
        self->applyCrossfade &= ~AACDEC_CROSSFADE_BITMASK_PREROLL;
830
864
      }
831
1.04k
      FDKreadBit(hBs); /* reserved */
832
      /* Read num preroll AU's */
833
1.04k
      *numPrerollAU = escapedValue(hBs, 2, 4, 0);
834
      /* check limits for USAC */
835
1.04k
      if (*numPrerollAU > AACDEC_MAX_NUM_PREROLL_AU_USAC) {
836
1
        *numPrerollAU = 0;
837
1
        ErrorStatus = AAC_DEC_PARSE_ERROR;
838
1
        goto bail;
839
1
      }
840
1.04k
    }
841
1.18k
  }
842
843
4.16k
  for (i = 0; i < *numPrerollAU; i++) {
844
    /* For every AU get length and offset in the bitstream */
845
2.15k
    prerollAULength[i] = escapedValue(hBs, 16, 16, 0);
846
2.15k
    if (prerollAULength[i] > 0) {
847
2.15k
      prerollAUOffset[i] = auStartAnchor - (INT)FDKgetValidBits(hBs);
848
2.15k
      independencyFlag = FDKreadBit(hBs);
849
2.15k
      if (i == 0 && !independencyFlag) {
850
1
        *numPrerollAU = 0;
851
1
        ErrorStatus = AAC_DEC_PARSE_ERROR;
852
1
        goto bail;
853
1
      }
854
2.15k
      FDKpushFor(hBs, prerollAULength[i] * 8 - 1);
855
2.15k
      self->prerollAULength[i] = (prerollAULength[i] * 8) + prerollAUOffset[i];
856
2.15k
    } else {
857
5
      *numPrerollAU = 0;
858
5
      ErrorStatus = AAC_DEC_PARSE_ERROR; /* Something is wrong */
859
5
      goto bail;
860
5
    }
861
2.15k
  }
862
863
3.08k
bail:
864
865
3.08k
  *hBs = bs;
866
867
3.08k
  return ErrorStatus;
868
2.01k
}
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
288k
    MP4_ELEMENT_ID previous_element, int elIndex, int fIsFillElement) {
882
288k
  AAC_DECODER_ERROR error = AAC_DEC_OK;
883
288k
  EXT_PAYLOAD_TYPE extension_type;
884
288k
  int bytes = (*count) >> 3;
885
288k
  int crcFlag = 0;
886
887
288k
  if (*count < 4) {
888
16
    return AAC_DEC_PARSE_ERROR;
889
288k
  } else if ((INT)FDKgetValidBits(hBs) < *count) {
890
233
    return AAC_DEC_DECODE_FRAME_ERROR;
891
233
  }
892
893
288k
  extension_type =
894
288k
      (EXT_PAYLOAD_TYPE)FDKreadBits(hBs, 4); /* bs_extension_type */
895
288k
  *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
288k
  if ((self->flags[0] & AC_ELD) && ((extension_type == EXT_SBR_DATA_CRC) ||
901
86.1k
                                    (extension_type == EXT_SBR_DATA))) {
902
976
    extension_type = EXT_FIL; /* skip sbr data */
903
976
  }
904
905
288k
  switch (extension_type) {
906
100k
    case EXT_DYNAMIC_RANGE: {
907
100k
      INT readBits =
908
100k
          aacDecoder_drcMarkPayload(self->hDrcInfo, hBs, MPEG_DRC_EXT_DATA);
909
910
100k
      if (readBits > *count) { /* Read too much. Something went wrong! */
911
6.31k
        error = AAC_DEC_PARSE_ERROR;
912
6.31k
      }
913
100k
      *count -= readBits;
914
100k
    } break;
915
10.6k
    case EXT_LDSAC_DATA:
916
39.2k
    case EXT_SAC_DATA:
917
      /* Read MPEG Surround Extension payload */
918
39.2k
      {
919
39.2k
        int err, mpsSampleRate, mpsFrameSize;
920
921
39.2k
        if (self->flags[0] & AC_PS_PRESENT) {
922
217
          error = AAC_DEC_PARSE_ERROR;
923
217
          goto bail;
924
217
        }
925
926
        /* Handle SBR dual rate case */
927
39.0k
        if (self->streamInfo.extSamplingRate != 0) {
928
33.1k
          mpsSampleRate = self->streamInfo.extSamplingRate;
929
33.1k
          mpsFrameSize = self->streamInfo.aacSamplesPerFrame *
930
33.1k
                         (self->streamInfo.extSamplingRate /
931
33.1k
                          self->streamInfo.aacSampleRate);
932
33.1k
        } else {
933
5.84k
          mpsSampleRate = self->streamInfo.aacSampleRate;
934
5.84k
          mpsFrameSize = self->streamInfo.aacSamplesPerFrame;
935
5.84k
        }
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
39.0k
        if (!(self->flags[0] & (AC_USAC | AC_RSVD50 | AC_ELD))) {
940
5.84k
          self->mpsEnableCurr = self->mpsEnableUser;
941
5.84k
        }
942
39.0k
        if (self->mpsEnableCurr) {
943
32.3k
          if (!self->qmfDomain.globalConf.qmfDomainExplicitConfig) {
944
            /* if not done yet, allocate full MPEG Surround decoder instance */
945
907
            if (mpegSurroundDecoder_IsFullMpegSurroundDecoderInstanceAvailable(
946
907
                    (CMpegSurroundDecoder *)self->pMpegSurroundDecoder) ==
947
907
                SAC_INSTANCE_NOT_FULL_AVAILABLE) {
948
360
              if (mpegSurroundDecoder_Open(
949
360
                      (CMpegSurroundDecoder **)&self->pMpegSurroundDecoder, -1,
950
360
                      &self->qmfDomain)) {
951
0
                return AAC_DEC_OUT_OF_MEMORY;
952
0
              }
953
360
            }
954
907
          }
955
32.3k
          err = mpegSurroundDecoder_Parse(
956
32.3k
              (CMpegSurroundDecoder *)self->pMpegSurroundDecoder, hBs, count,
957
32.3k
              self->streamInfo.aot, mpsSampleRate, mpsFrameSize,
958
32.3k
              self->flags[0] & AC_INDEP);
959
32.3k
          if (err == MPS_OK) {
960
19.6k
            self->flags[0] |= AC_MPS_PRESENT;
961
19.6k
          } else {
962
12.6k
            error = AAC_DEC_PARSE_ERROR;
963
12.6k
          }
964
32.3k
        }
965
        /* Skip any trailing bytes */
966
39.0k
        FDKpushFor(hBs, *count);
967
39.0k
        *count = 0;
968
39.0k
      }
969
0
      break;
970
971
11.8k
    case EXT_SBR_DATA_CRC:
972
11.8k
      crcFlag = 1;
973
11.8k
      FDK_FALLTHROUGH;
974
36.9k
    case EXT_SBR_DATA:
975
36.9k
      if (IS_CHANNEL_ELEMENT(previous_element)) {
976
36.7k
        SBR_ERROR sbrError;
977
36.7k
        UCHAR configMode = 0;
978
36.7k
        UCHAR configChanged = 0;
979
980
36.7k
        CAacDecoder_SyncQmfMode(self);
981
982
36.7k
        configMode |= AC_CM_ALLOC_MEM;
983
984
36.7k
        sbrError = sbrDecoder_InitElement(
985
36.7k
            self->hSbrDecoder, self->streamInfo.aacSampleRate,
986
36.7k
            self->streamInfo.extSamplingRate,
987
36.7k
            self->streamInfo.aacSamplesPerFrame, self->streamInfo.aot,
988
36.7k
            previous_element, elIndex,
989
36.7k
            2, /* Signalize that harmonicSBR shall be ignored in the config
990
                  change detection */
991
36.7k
            0, configMode, &configChanged, self->downscaleFactor);
992
993
36.7k
        if (sbrError == SBRDEC_OK) {
994
36.3k
          sbrError = sbrDecoder_Parse(self->hSbrDecoder, hBs,
995
36.3k
                                      self->pDrmBsBuffer, self->drmBsBufferSize,
996
36.3k
                                      count, *count, crcFlag, previous_element,
997
36.3k
                                      elIndex, self->flags[0], self->elFlags);
998
          /* Enable SBR for implicit SBR signalling but only if no severe error
999
           * happend. */
1000
36.3k
          if ((sbrError == SBRDEC_OK) || (sbrError == SBRDEC_PARSE_ERROR)) {
1001
36.3k
            self->sbrEnabled = 1;
1002
36.3k
          }
1003
36.3k
        } else {
1004
          /* Do not try to apply SBR because initializing the element failed. */
1005
444
          self->sbrEnabled = 0;
1006
444
        }
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
36.7k
        if (fIsFillElement) {
1013
30.1k
          FDKpushBiDirectional(hBs, *count);
1014
30.1k
          *count = 0;
1015
30.1k
        } else {
1016
          /* If this is not a fill element with a known length, we are screwed
1017
           * and further parsing makes no sense. */
1018
6.65k
          if (sbrError != SBRDEC_OK) {
1019
1.42k
            self->frameOK = 0;
1020
1.42k
          }
1021
6.65k
        }
1022
36.7k
      } else {
1023
184
        error = AAC_DEC_PARSE_ERROR;
1024
184
      }
1025
36.9k
      break;
1026
1027
1.22k
    case EXT_FILL_DATA: {
1028
1.22k
      int temp;
1029
1030
1.22k
      temp = FDKreadBits(hBs, 4);
1031
1.22k
      bytes--;
1032
1.22k
      if (temp != 0) {
1033
273
        error = AAC_DEC_PARSE_ERROR;
1034
273
        break;
1035
273
      }
1036
1.78k
      while (bytes > 0) {
1037
1.00k
        temp = FDKreadBits(hBs, 8);
1038
1.00k
        bytes--;
1039
1.00k
        if (temp != 0xa5) {
1040
170
          error = AAC_DEC_PARSE_ERROR;
1041
170
          break;
1042
170
        }
1043
1.00k
      }
1044
948
      *count = bytes << 3;
1045
948
    } break;
1046
1047
570
    case EXT_DATA_ELEMENT: {
1048
570
      int dataElementVersion;
1049
1050
570
      dataElementVersion = FDKreadBits(hBs, 4);
1051
570
      *count -= 4;
1052
570
      if (dataElementVersion == 0) /* ANC_DATA */
1053
420
      {
1054
420
        int temp, dataElementLength = 0;
1055
37.6k
        do {
1056
37.6k
          temp = FDKreadBits(hBs, 8);
1057
37.6k
          *count -= 8;
1058
37.6k
          dataElementLength += temp;
1059
37.6k
        } while (temp == 255);
1060
1061
420
        CAacDecoder_AncDataParse(&self->ancData, hBs, dataElementLength);
1062
420
        *count -= (dataElementLength << 3);
1063
420
      } else {
1064
        /* align = 0 */
1065
150
        error = AAC_DEC_PARSE_ERROR;
1066
150
        goto bail;
1067
150
      }
1068
570
    } break;
1069
1070
56.9k
    case EXT_DATA_LENGTH:
1071
56.9k
      if (!fIsFillElement /* Makes no sens to have an additional length in a
1072
                             fill ...   */
1073
56.8k
          &&
1074
56.8k
          (self->flags[0] &
1075
56.8k
           AC_ER)) /* ... element because this extension payload type was ... */
1076
56.8k
      { /* ... created to circumvent the missing length in ER-Syntax. */
1077
56.8k
        int bitCnt, len = FDKreadBits(hBs, 4);
1078
56.8k
        *count -= 4;
1079
1080
56.8k
        if (len == 15) {
1081
1.27k
          int add_len = FDKreadBits(hBs, 8);
1082
1.27k
          *count -= 8;
1083
1.27k
          len += add_len;
1084
1085
1.27k
          if (add_len == 255) {
1086
67
            len += FDKreadBits(hBs, 16);
1087
67
            *count -= 16;
1088
67
          }
1089
1.27k
        }
1090
56.8k
        len <<= 3;
1091
56.8k
        bitCnt = len;
1092
1093
56.8k
        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
23
          error = AAC_DEC_PARSE_ERROR;
1097
23
          goto bail;
1098
56.8k
        } else {
1099
          /* rewind and call myself again. */
1100
56.8k
          FDKpushBack(hBs, 4);
1101
1102
56.8k
          error = CAacDecoder_ExtPayloadParse(
1103
56.8k
              self, hBs, &bitCnt, previous_element, elIndex,
1104
56.8k
              1); /* Treat same as fill element */
1105
1106
56.8k
          *count -= len - bitCnt;
1107
56.8k
        }
1108
        /* Note: the fall through in case the if statement above is not taken is
1109
         * intentional. */
1110
56.8k
        break;
1111
56.8k
      }
1112
53
      FDK_FALLTHROUGH;
1113
1114
28.6k
    case EXT_FIL:
1115
1116
53.5k
    default:
1117
      /* align = 4 */
1118
53.5k
      FDKpushFor(hBs, *count);
1119
53.5k
      *count = 0;
1120
53.5k
      break;
1121
288k
  }
1122
1123
288k
bail:
1124
288k
  if ((error != AAC_DEC_OK) &&
1125
20.1k
      fIsFillElement) { /* Skip the remaining extension bytes */
1126
19.7k
    FDKpushBiDirectional(hBs, *count);
1127
19.7k
    *count = 0;
1128
    /* Patch error code because decoding can go on. */
1129
19.7k
    error = AAC_DEC_OK;
1130
    /* Be sure that parsing errors have been stored. */
1131
19.7k
  }
1132
288k
  return error;
1133
288k
}
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
317k
    const int element_index, const int el_cnt[]) {
1139
317k
  AAC_DECODER_ERROR ErrorStatus = AAC_DEC_OK;
1140
317k
  INT bitCnt = 0;
1141
1142
  /* get the remaining bits of this frame */
1143
317k
  bitCnt = transportDec_GetAuBitsRemaining(self->hInput, 0);
1144
1145
317k
  if ((self->flags[0] & AC_SBR_PRESENT) &&
1146
231k
      (self->flags[0] & (AC_USAC | AC_RSVD50 | AC_ELD | AC_DRM))) {
1147
220k
    SBR_ERROR err = SBRDEC_OK;
1148
220k
    int chElIdx, numChElements = el_cnt[ID_SCE] + el_cnt[ID_CPE] +
1149
220k
                                 el_cnt[ID_LFE] + el_cnt[ID_USAC_SCE] +
1150
220k
                                 el_cnt[ID_USAC_CPE] + el_cnt[ID_USAC_LFE];
1151
220k
    INT bitCntTmp = bitCnt;
1152
1153
220k
    if (self->flags[0] & AC_USAC) {
1154
193k
      chElIdx = numChElements - 1;
1155
193k
    } else {
1156
26.7k
      chElIdx = 0; /* ELD case */
1157
26.7k
    }
1158
1159
478k
    for (; chElIdx < numChElements; chElIdx += 1) {
1160
258k
      MP4_ELEMENT_ID sbrType;
1161
258k
      SBR_ERROR errTmp;
1162
258k
      if (self->flags[0] & (AC_USAC)) {
1163
193k
        FDK_ASSERT((self->elements[element_index] == ID_USAC_SCE) ||
1164
193k
                   (self->elements[element_index] == ID_USAC_CPE));
1165
193k
        sbrType = IS_STEREO_SBR(self->elements[element_index],
1166
193k
                                self->usacStereoConfigIndex[element_index])
1167
193k
                      ? ID_CPE
1168
193k
                      : ID_SCE;
1169
193k
      } else
1170
64.5k
        sbrType = self->elements[chElIdx];
1171
258k
      errTmp = sbrDecoder_Parse(self->hSbrDecoder, bs, self->pDrmBsBuffer,
1172
258k
                                self->drmBsBufferSize, &bitCnt, -1,
1173
258k
                                self->flags[0] & AC_SBRCRC, sbrType, chElIdx,
1174
258k
                                self->flags[0], self->elFlags);
1175
258k
      if (errTmp != SBRDEC_OK) {
1176
64.8k
        err = errTmp;
1177
64.8k
        bitCntTmp = bitCnt;
1178
64.8k
        bitCnt = 0;
1179
64.8k
      }
1180
258k
    }
1181
220k
    switch (err) {
1182
64.8k
      case SBRDEC_PARSE_ERROR:
1183
        /* Can not go on parsing because we do not
1184
            know the length of the SBR extension data. */
1185
64.8k
        FDKpushFor(bs, bitCntTmp);
1186
64.8k
        bitCnt = 0;
1187
64.8k
        break;
1188
155k
      case SBRDEC_OK:
1189
155k
        self->sbrEnabled = 1;
1190
155k
        break;
1191
0
      default:
1192
0
        self->frameOK = 0;
1193
0
        break;
1194
220k
    }
1195
220k
  }
1196
1197
317k
  if ((bitCnt > 0) && (self->flags[0] & (AC_USAC | AC_RSVD50))) {
1198
163k
    if ((self->flags[0] & AC_MPS_PRESENT) ||
1199
85.0k
        (self->elFlags[element_index] & AC_EL_USAC_MPS212)) {
1200
85.0k
      int err;
1201
1202
85.0k
      err = mpegSurroundDecoder_ParseNoHeader(
1203
85.0k
          (CMpegSurroundDecoder *)self->pMpegSurroundDecoder, bs, &bitCnt,
1204
85.0k
          self->flags[0] & AC_INDEP);
1205
85.0k
      if (err != MPS_OK) {
1206
314
        self->frameOK = 0;
1207
314
        ErrorStatus = AAC_DEC_PARSE_ERROR;
1208
314
      }
1209
85.0k
    }
1210
163k
  }
1211
1212
317k
  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
317k
  if (!(self->flags[0] & (AC_USAC | AC_RSVD50 | AC_DRM))) {
1219
327k
    while (bitCnt > 7) {
1220
226k
      ErrorStatus = CAacDecoder_ExtPayloadParse(
1221
226k
          self, bs, &bitCnt, previous_element, previous_element_index, 0);
1222
226k
      if (ErrorStatus != AAC_DEC_OK) {
1223
473
        self->frameOK = 0;
1224
473
        ErrorStatus = AAC_DEC_PARSE_ERROR;
1225
473
        break;
1226
473
      }
1227
226k
    }
1228
102k
  }
1229
317k
  return ErrorStatus;
1230
317k
}
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
22.2k
static void CStreamInfoInit(CStreamInfo *pStreamInfo) {
1240
22.2k
  pStreamInfo->aacSampleRate = 0;
1241
22.2k
  pStreamInfo->profile = -1;
1242
22.2k
  pStreamInfo->aot = AOT_NONE;
1243
1244
22.2k
  pStreamInfo->channelConfig = -1;
1245
22.2k
  pStreamInfo->bitRate = 0;
1246
22.2k
  pStreamInfo->aacSamplesPerFrame = 0;
1247
1248
22.2k
  pStreamInfo->extAot = AOT_NONE;
1249
22.2k
  pStreamInfo->extSamplingRate = 0;
1250
1251
22.2k
  pStreamInfo->flags = 0;
1252
1253
22.2k
  pStreamInfo->epConfig = -1; /* default: no ER */
1254
1255
22.2k
  pStreamInfo->numChannels = 0;
1256
22.2k
  pStreamInfo->sampleRate = 0;
1257
22.2k
  pStreamInfo->frameSize = 0;
1258
1259
22.2k
  pStreamInfo->outputDelay = 0;
1260
1261
  /* DRC */
1262
22.2k
  pStreamInfo->drcProgRefLev =
1263
22.2k
      -1; /* set program reference level to not indicated */
1264
22.2k
  pStreamInfo->drcPresMode = -1; /* default: presentation mode not indicated */
1265
1266
22.2k
  pStreamInfo->outputLoudness = -1; /* default: no loudness metadata present */
1267
22.2k
}
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
22.2k
{
1283
22.2k
  HANDLE_AACDECODER self;
1284
1285
22.2k
  self = GetAacDecoder();
1286
22.2k
  if (self == NULL) {
1287
0
    goto bail;
1288
0
  }
1289
1290
22.2k
  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
22.2k
  self->streamInfo.pChannelIndices = self->channelIndices;
1295
22.2k
  self->streamInfo.pChannelType = self->channelType;
1296
22.2k
  self->downscaleFactor = 1;
1297
22.2k
  self->downscaleFactorInBS = 1;
1298
1299
  /* initialize anc data */
1300
22.2k
  CAacDecoder_AncDataInit(&self->ancData, NULL, 0);
1301
1302
  /* initialize stream info */
1303
22.2k
  CStreamInfoInit(&self->streamInfo);
1304
1305
  /* initialize progam config */
1306
22.2k
  CProgramConfig_Init(&self->pce);
1307
1308
  /* initialize error concealment common data */
1309
22.2k
  CConcealment_InitCommonData(&self->concealCommonData);
1310
22.2k
  self->concealMethodUser = ConcealMethodNone; /* undefined -> auto mode */
1311
1312
22.2k
  self->hDrcInfo = GetDrcInfo();
1313
22.2k
  if (self->hDrcInfo == NULL) {
1314
0
    goto bail;
1315
0
  }
1316
  /* Init common DRC structure */
1317
22.2k
  aacDecoder_drcInit(self->hDrcInfo);
1318
  /* Set default frame delay */
1319
22.2k
  aacDecoder_drcSetParam(self->hDrcInfo, DRC_BS_DELAY,
1320
22.2k
                         CConcealment_GetDelay(&self->concealCommonData));
1321
22.2k
  self->workBufferCore1 = (FIXP_DBL *)GetWorkBufferCore1();
1322
1323
22.2k
  self->workBufferCore2 = GetWorkBufferCore2();
1324
22.2k
  if (self->workBufferCore2 == NULL) goto bail;
1325
1326
  /* When RSVD60 is active use dedicated memory for core decoding */
1327
22.2k
  self->pTimeData2 = GetWorkBufferCore5();
1328
22.2k
  self->timeData2Size = GetRequiredMemWorkBufferCore5();
1329
22.2k
  if (self->pTimeData2 == NULL) {
1330
0
    goto bail;
1331
0
  }
1332
1333
22.2k
  return self;
1334
1335
0
bail:
1336
0
  CAacDecoder_Close(self);
1337
1338
0
  return NULL;
1339
22.2k
}
1340
1341
/* Revert CAacDecoder_Init() */
1342
static void CAacDecoder_DeInit(HANDLE_AACDECODER self,
1343
175k
                               const int subStreamIndex) {
1344
175k
  int ch;
1345
175k
  int aacChannelOffset = 0, aacChannels = (8);
1346
175k
  int numElements = (3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) + 1),
1347
175k
      elementOffset = 0;
1348
1349
175k
  if (self == NULL) return;
1350
1351
175k
  {
1352
175k
    self->ascChannels[0] = 0;
1353
175k
    self->elements[0] = ID_END;
1354
175k
  }
1355
1356
1.57M
  for (ch = aacChannelOffset; ch < aacChannelOffset + aacChannels; ch++) {
1357
1.40M
    if (self->pAacDecoderChannelInfo[ch] != NULL) {
1358
700k
      if (self->pAacDecoderChannelInfo[ch]->pComStaticData != NULL) {
1359
447k
        if (self->pAacDecoderChannelInfo[ch]
1360
447k
                ->pComStaticData->pWorkBufferCore1 != NULL) {
1361
447k
          if (ch == aacChannelOffset) {
1362
144k
            FreeWorkBufferCore1(&self->pAacDecoderChannelInfo[ch]
1363
144k
                                     ->pComStaticData->pWorkBufferCore1);
1364
144k
          }
1365
447k
        }
1366
447k
        if (self->pAacDecoderChannelInfo[ch]
1367
447k
                ->pComStaticData->cplxPredictionData != NULL) {
1368
9.14k
          FreeCplxPredictionData(&self->pAacDecoderChannelInfo[ch]
1369
9.14k
                                      ->pComStaticData->cplxPredictionData);
1370
9.14k
        }
1371
        /* Avoid double free of linked pComStaticData in case of CPE by settings
1372
         * pointer to NULL. */
1373
447k
        if (ch < (8) - 1) {
1374
380k
          if ((self->pAacDecoderChannelInfo[ch + 1] != NULL) &&
1375
339k
              (self->pAacDecoderChannelInfo[ch + 1]->pComStaticData ==
1376
339k
               self->pAacDecoderChannelInfo[ch]->pComStaticData)) {
1377
252k
            self->pAacDecoderChannelInfo[ch + 1]->pComStaticData = NULL;
1378
252k
          }
1379
380k
        }
1380
447k
        FDKfree(self->pAacDecoderChannelInfo[ch]->pComStaticData);
1381
447k
        self->pAacDecoderChannelInfo[ch]->pComStaticData = NULL;
1382
447k
      }
1383
700k
      if (self->pAacDecoderChannelInfo[ch]->pComData != NULL) {
1384
        /* Avoid double free of linked pComData in case of CPE by settings
1385
         * pointer to NULL. */
1386
447k
        if (ch < (8) - 1) {
1387
380k
          if ((self->pAacDecoderChannelInfo[ch + 1] != NULL) &&
1388
339k
              (self->pAacDecoderChannelInfo[ch + 1]->pComData ==
1389
339k
               self->pAacDecoderChannelInfo[ch]->pComData)) {
1390
252k
            self->pAacDecoderChannelInfo[ch + 1]->pComData = NULL;
1391
252k
          }
1392
380k
        }
1393
447k
        if (ch == aacChannelOffset) {
1394
144k
          FreeWorkBufferCore6(
1395
144k
              (SCHAR **)&self->pAacDecoderChannelInfo[ch]->pComData);
1396
303k
        } else {
1397
303k
          FDKafree(self->pAacDecoderChannelInfo[ch]->pComData);
1398
303k
        }
1399
447k
        self->pAacDecoderChannelInfo[ch]->pComData = NULL;
1400
447k
      }
1401
700k
    }
1402
1.40M
    if (self->pAacDecoderStaticChannelInfo[ch] != NULL) {
1403
700k
      if (self->pAacDecoderStaticChannelInfo[ch]->pOverlapBuffer != NULL) {
1404
700k
        FreeOverlapBuffer(
1405
700k
            &self->pAacDecoderStaticChannelInfo[ch]->pOverlapBuffer);
1406
700k
      }
1407
700k
      if (self->pAacDecoderStaticChannelInfo[ch]->hArCo != NULL) {
1408
72.6k
        CArco_Destroy(self->pAacDecoderStaticChannelInfo[ch]->hArCo);
1409
72.6k
      }
1410
700k
      FreeAacDecoderStaticChannelInfo(&self->pAacDecoderStaticChannelInfo[ch]);
1411
700k
    }
1412
1.40M
    if (self->pAacDecoderChannelInfo[ch] != NULL) {
1413
700k
      FreeAacDecoderChannelInfo(&self->pAacDecoderChannelInfo[ch]);
1414
700k
    }
1415
1.40M
  }
1416
1417
175k
  {
1418
175k
    int el;
1419
10.8M
    for (el = elementOffset; el < elementOffset + numElements; el++) {
1420
10.6M
      if (self->cpeStaticData[el] != NULL) {
1421
9.14k
        FreeCpePersistentData(&self->cpeStaticData[el]);
1422
9.14k
      }
1423
10.6M
    }
1424
175k
  }
1425
1426
175k
  FDK_Delay_Destroy(&self->usacResidualDelay);
1427
1428
175k
  self->aacChannels = 0;
1429
175k
  self->streamInfo.aacSampleRate = 0;
1430
175k
  self->streamInfo.sampleRate = 0;
1431
  /* This samplerate value is checked for configuration change, not the others
1432
   * above. */
1433
175k
  self->samplingRateInfo[subStreamIndex].samplingRate = 0;
1434
175k
}
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
442k
                                    int elementOffset) {
1452
442k
  FDKmemcpy(self->elFlags, elFlags, sizeof(self->elFlags));
1453
1454
442k
  self->flags[streamIndex] = flags;
1455
442k
}
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
84
                                                         SCHAR buildUpCnt) {
1473
84
  AAC_DECODER_ERROR err = AAC_DEC_OK;
1474
1475
84
  self->flushStatus = flushStatus;
1476
84
  self->flushCnt = flushCnt;
1477
84
  self->buildUpStatus = buildUpStatus;
1478
84
  self->buildUpCnt = buildUpCnt;
1479
1480
84
  return (err);
1481
84
}
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
153k
                                                   const int subStreamIndex) {
1492
153k
  AAC_DECODER_ERROR err = AAC_DEC_OK;
1493
1494
153k
  CAacDecoder_DeInit(self, subStreamIndex);
1495
1496
153k
  return (err);
1497
153k
}
1498
1499
/* Destroy aac decoder */
1500
22.2k
LINKSPEC_CPP void CAacDecoder_Close(HANDLE_AACDECODER self) {
1501
22.2k
  if (self == NULL) return;
1502
1503
22.2k
  CAacDecoder_DeInit(self, 0);
1504
1505
22.2k
  {
1506
22.2k
    int ch;
1507
200k
    for (ch = 0; ch < (8); ch++) {
1508
178k
      if (self->pTimeDataFlush[ch] != NULL) {
1509
15.8k
        FreeTimeDataFlush(&self->pTimeDataFlush[ch]);
1510
15.8k
      }
1511
178k
    }
1512
22.2k
  }
1513
1514
22.2k
  if (self->hDrcInfo) {
1515
22.2k
    FreeDrcInfo(&self->hDrcInfo);
1516
22.2k
  }
1517
1518
22.2k
  if (self->workBufferCore1 != NULL) {
1519
22.2k
    FreeWorkBufferCore1((CWorkBufferCore1 **)&self->workBufferCore1);
1520
22.2k
  }
1521
1522
  /* Free WorkBufferCore2 */
1523
22.2k
  if (self->workBufferCore2 != NULL) {
1524
22.2k
    FreeWorkBufferCore2(&self->workBufferCore2);
1525
22.2k
  }
1526
22.2k
  if (self->pTimeData2 != NULL) {
1527
22.2k
    FreeWorkBufferCore5(&self->pTimeData2);
1528
22.2k
  }
1529
1530
22.2k
  FDK_QmfDomain_Close(&self->qmfDomain);
1531
1532
22.2k
  FreeAacDecoder(&self);
1533
22.2k
}
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
457k
                 UCHAR configMode, UCHAR *configChanged) {
1545
457k
  AAC_DECODER_ERROR err = AAC_DEC_OK;
1546
457k
  INT ascChannels, ascChanged = 0;
1547
457k
  AACDEC_RENDER_MODE initRenderMode = AACDEC_RENDER_INVALID;
1548
457k
  SCHAR usacStereoConfigIndex = -1;
1549
457k
  int usacResidualDelayCompSamples = 0;
1550
457k
  int elementOffset, aacChannelsOffset, aacChannelsOffsetIdx;
1551
457k
  const int streamIndex = 0;
1552
457k
  INT flushChannels = 0;
1553
1554
457k
  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
457k
  UINT elFlags[(3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) + 1)];
1558
1559
457k
  UCHAR sbrEnabled = self->sbrEnabled;
1560
457k
  UCHAR sbrEnabledPrev = self->sbrEnabledPrev;
1561
457k
  UCHAR mpsEnableCurr = self->mpsEnableCurr;
1562
1563
457k
  if (!self) return AAC_DEC_INVALID_HANDLE;
1564
1565
457k
  UCHAR downscaleFactor = self->downscaleFactor;
1566
457k
  UCHAR downscaleFactorInBS = self->downscaleFactorInBS;
1567
1568
457k
  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
457k
  switch (asc->m_aot) {
1574
165k
    case AOT_AAC_LC:
1575
165k
      self->streamInfo.profile = 1;
1576
165k
      FDK_FALLTHROUGH;
1577
195k
    case AOT_ER_AAC_SCAL:
1578
195k
      if (asc->m_sc.m_gaSpecificConfig.m_layer > 0) {
1579
        /* aac_scalable_extension_element() currently not supported. */
1580
199
        return AAC_DEC_UNSUPPORTED_FORMAT;
1581
199
      }
1582
194k
      FDK_FALLTHROUGH;
1583
194k
    case AOT_SBR:
1584
194k
    case AOT_PS:
1585
196k
    case AOT_ER_AAC_LC:
1586
210k
    case AOT_ER_AAC_LD:
1587
210k
    case AOT_DRM_AAC:
1588
210k
    case AOT_DRM_SURROUND:
1589
210k
      initRenderMode = AACDEC_RENDER_IMDCT;
1590
210k
      break;
1591
86.0k
    case AOT_ER_AAC_ELD:
1592
86.0k
      initRenderMode = AACDEC_RENDER_ELDFB;
1593
86.0k
      break;
1594
159k
    case AOT_USAC:
1595
159k
      initRenderMode = AACDEC_RENDER_IMDCT;
1596
159k
      break;
1597
1.21k
    default:
1598
1.21k
      return AAC_DEC_UNSUPPORTED_AOT;
1599
457k
  }
1600
1601
455k
  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
31.9k
    int pceCmpResult;
1606
31.9k
    C_ALLOC_SCRATCH_START(tmpPce, CProgramConfig, 1);
1607
1608
31.9k
    CProgramConfig_GetDefault(tmpPce, asc->m_channelConfiguration);
1609
31.9k
    pceCmpResult = CProgramConfig_Compare(&self->pce, tmpPce);
1610
31.9k
    if ((pceCmpResult < 0) /* Reset if PCEs are completely different ... */
1611
30.9k
        ||
1612
30.9k
        (pceCmpResult > 1)) { /*            ... or have a different layout. */
1613
30.8k
      CProgramConfig_Init(&self->pce);
1614
30.8k
    } /* Otherwise keep the PCE (and its metadata). */
1615
31.9k
    C_ALLOC_SCRATCH_END(tmpPce, CProgramConfig, 1);
1616
424k
  } else {
1617
424k
    CProgramConfig_Init(&self->pce);
1618
424k
  }
1619
1620
  /* set channels */
1621
455k
  switch (asc->m_channelConfiguration) {
1622
85.5k
    case 0:
1623
85.5k
      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
85.5k
        default:
1629
          /* get channels from program config (ASC) */
1630
85.5k
          if (CProgramConfig_IsValid(&asc->m_progrConfigElement)) {
1631
75.0k
            ascChannels = asc->m_progrConfigElement.NumChannels;
1632
75.0k
            if (ascChannels > 0) {
1633
74.6k
              int el_tmp;
1634
              /* valid number of channels -> copy program config element (PCE)
1635
               * from ASC */
1636
74.6k
              FDKmemcpy(&self->pce, &asc->m_progrConfigElement,
1637
74.6k
                        sizeof(CProgramConfig));
1638
              /* Built element table */
1639
74.6k
              el_tmp = CProgramConfig_GetElementTable(
1640
74.6k
                  &asc->m_progrConfigElement, self->elements, (((8)) + (8)),
1641
74.6k
                  &self->chMapIndex);
1642
4.26M
              for (; el_tmp < (3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) + 1);
1643
4.18M
                   el_tmp++) {
1644
4.18M
                self->elements[el_tmp] = ID_NONE;
1645
4.18M
              }
1646
74.6k
            } else {
1647
368
              return AAC_DEC_UNSUPPORTED_CHANNELCONFIG;
1648
368
            }
1649
75.0k
          } else {
1650
10.5k
            self->chMapIndex = 0;
1651
10.5k
            return AAC_DEC_UNSUPPORTED_CHANNELCONFIG;
1652
10.5k
          }
1653
74.6k
          break;
1654
85.5k
      }
1655
74.6k
      break;
1656
84.3k
    case 1:
1657
234k
    case 2:
1658
235k
    case 3:
1659
240k
    case 4:
1660
241k
    case 5:
1661
243k
    case 6:
1662
243k
      ascChannels = asc->m_channelConfiguration;
1663
243k
      break;
1664
10.0k
    case 11:
1665
10.0k
      ascChannels = 7;
1666
10.0k
      break;
1667
87.5k
    case 7:
1668
95.4k
    case 12:
1669
115k
    case 14:
1670
115k
      ascChannels = 8;
1671
115k
      break;
1672
1.28k
    default:
1673
1.28k
      return AAC_DEC_UNSUPPORTED_CHANNELCONFIG;
1674
455k
  }
1675
1676
443k
  if (asc->m_aot == AOT_USAC) {
1677
159k
    flushChannels = fMin(ascChannels, (8));
1678
159k
    INT numChannel;
1679
159k
    pcmDmx_GetParam(self->hPcmUtils, MIN_NUMBER_OF_OUTPUT_CHANNELS,
1680
159k
                    &numChannel);
1681
159k
    flushChannels = fMin(fMax(numChannel, flushChannels), (8));
1682
159k
  }
1683
1684
443k
  if (IS_USAC(asc->m_aot)) {
1685
342k
    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
182k
      if (asc->m_sc.m_usacConfig.element[el].m_stereoConfigIndex == 1) {
1689
28.2k
        ascChannels--; /* stereoConfigIndex == 1 stereo cases do actually
1690
                          contain only a mono core channel. */
1691
154k
      } 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
10.6k
        if (asc->m_sc.m_usacConfig.element[el].m_harmonicSBR) {
1698
771
          usacResidualDelayCompSamples += asc->m_samplesPerFrame;
1699
771
        }
1700
10.6k
        if (asc->m_sc.m_usacConfig.m_coreSbrFrameLengthIndex == 4) {
1701
8.25k
          usacResidualDelayCompSamples +=
1702
8.25k
              6 * 16; /* difference between 12 SBR
1703
                         overlap slots from SBR and 6
1704
                         slots delayed in MPS212 */
1705
8.25k
        }
1706
10.6k
      }
1707
182k
    }
1708
159k
  }
1709
1710
443k
  aacChannelsOffset = 0;
1711
443k
  aacChannelsOffsetIdx = 0;
1712
443k
  elementOffset = 0;
1713
443k
  if ((ascChannels <= 0) || (ascChannels > (8)) ||
1714
443k
      (asc->m_channelConfiguration > AACDEC_MAX_CH_CONF)) {
1715
315
    return AAC_DEC_UNSUPPORTED_CHANNELCONFIG;
1716
315
  }
1717
1718
  /* Set syntax flags */
1719
443k
  flags = 0;
1720
443k
  { FDKmemclear(elFlags, sizeof(elFlags)); }
1721
1722
443k
  if ((asc->m_channelConfiguration > 0) || IS_USAC(asc->m_aot)) {
1723
369k
    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
159k
      self->pUsacConfig[streamIndex] = &asc->m_sc.m_usacConfig;
1729
1730
      /* copy list of elements */
1731
159k
      if (self->pUsacConfig[streamIndex]->m_usacNumElements >
1732
159k
          (3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) + 1)) {
1733
0
        goto bail;
1734
0
      }
1735
1736
159k
      if (self->numUsacElements[streamIndex] !=
1737
159k
          asc->m_sc.m_usacConfig.m_usacNumElements) {
1738
26.4k
        ascChanged = 1;
1739
26.4k
      }
1740
1741
159k
      if (configMode & AC_CM_ALLOC_MEM) {
1742
78.6k
        self->numUsacElements[streamIndex] =
1743
78.6k
            asc->m_sc.m_usacConfig.m_usacNumElements;
1744
78.6k
      }
1745
1746
159k
      mpsEnableCurr = 0;
1747
159k
      for (int _el = 0;
1748
342k
           _el < (int)self->pUsacConfig[streamIndex]->m_usacNumElements;
1749
182k
           _el++) {
1750
182k
        int el = _el + elementOffset;
1751
182k
        if (self->elements[el] !=
1752
182k
            self->pUsacConfig[streamIndex]->element[_el].usacElementType) {
1753
69.5k
          ascChanged = 1;
1754
69.5k
        }
1755
182k
        if (self->usacStereoConfigIndex[el] !=
1756
182k
            asc->m_sc.m_usacConfig.element[_el].m_stereoConfigIndex) {
1757
13.6k
          ascChanged = 1;
1758
13.6k
        }
1759
182k
        if (configMode & AC_CM_ALLOC_MEM) {
1760
89.7k
          self->elements[el] =
1761
89.7k
              self->pUsacConfig[streamIndex]->element[_el].usacElementType;
1762
          /* for Unified Stereo Coding */
1763
89.7k
          self->usacStereoConfigIndex[el] =
1764
89.7k
              asc->m_sc.m_usacConfig.element[_el].m_stereoConfigIndex;
1765
89.7k
          if (self->elements[el] == ID_USAC_CPE) {
1766
56.3k
            mpsEnableCurr |= self->usacStereoConfigIndex[el] ? 1 : 0;
1767
56.3k
          }
1768
89.7k
        }
1769
1770
182k
        elFlags[el] |= (asc->m_sc.m_usacConfig.element[_el].m_noiseFilling)
1771
182k
                           ? AC_EL_USAC_NOISE
1772
182k
                           : 0;
1773
182k
        elFlags[el] |=
1774
182k
            (asc->m_sc.m_usacConfig.element[_el].m_stereoConfigIndex > 0)
1775
182k
                ? AC_EL_USAC_MPS212
1776
182k
                : 0;
1777
182k
        elFlags[el] |= (asc->m_sc.m_usacConfig.element[_el].m_interTes)
1778
182k
                           ? AC_EL_USAC_ITES
1779
182k
                           : 0;
1780
182k
        elFlags[el] |=
1781
182k
            (asc->m_sc.m_usacConfig.element[_el].m_pvc) ? AC_EL_USAC_PVC : 0;
1782
182k
        elFlags[el] |=
1783
182k
            (asc->m_sc.m_usacConfig.element[_el].usacElementType == ID_USAC_LFE)
1784
182k
                ? AC_EL_USAC_LFE
1785
182k
                : 0;
1786
182k
        elFlags[el] |=
1787
182k
            (asc->m_sc.m_usacConfig.element[_el].usacElementType == ID_USAC_LFE)
1788
182k
                ? AC_EL_LFE
1789
182k
                : 0;
1790
182k
        if ((asc->m_sc.m_usacConfig.element[_el].usacElementType ==
1791
182k
             ID_USAC_CPE) &&
1792
114k
            ((self->usacStereoConfigIndex[el] == 0))) {
1793
50.0k
          elFlags[el] |= AC_EL_USAC_CP_POSSIBLE;
1794
50.0k
        }
1795
182k
      }
1796
1797
159k
      self->hasAudioPreRoll = 0;
1798
159k
      if (self->pUsacConfig[streamIndex]->m_usacNumElements) {
1799
159k
        self->hasAudioPreRoll = asc->m_sc.m_usacConfig.element[0]
1800
159k
                                    .extElement.usacExtElementHasAudioPreRoll;
1801
159k
      }
1802
159k
      if (configMode & AC_CM_ALLOC_MEM) {
1803
78.6k
        self->elements[elementOffset +
1804
78.6k
                       self->pUsacConfig[streamIndex]->m_usacNumElements] =
1805
78.6k
            ID_END;
1806
78.6k
      }
1807
209k
    } else {
1808
      /* Initialize constant mappings for channel config 1-7 */
1809
209k
      int i;
1810
1.67M
      for (i = 0; i < AACDEC_CH_ELEMENTS_TAB_SIZE; i++) {
1811
1.46M
        self->elements[i] = elementsTab[asc->m_channelConfiguration - 1][i];
1812
1.46M
      }
1813
11.5M
      for (; i < (3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) + 1); i++) {
1814
11.3M
        self->elements[i] = ID_NONE;
1815
11.3M
      }
1816
209k
    }
1817
1818
369k
    {
1819
369k
      int ch;
1820
1821
1.76M
      for (ch = 0; ch < ascChannels; ch++) {
1822
1.39M
        self->chMapping[ch] = ch;
1823
1.39M
      }
1824
1.93M
      for (; ch < (8); ch++) {
1825
1.56M
        self->chMapping[ch] = 255;
1826
1.56M
      }
1827
369k
    }
1828
1829
369k
    self->chMapIndex = asc->m_channelConfiguration;
1830
369k
  } else {
1831
74.3k
    if (CProgramConfig_IsValid(&asc->m_progrConfigElement)) {
1832
      /* Set matrix mixdown infos if available from PCE. */
1833
74.3k
      pcmDmx_SetMatrixMixdownFromPce(
1834
74.3k
          self->hPcmUtils, asc->m_progrConfigElement.MatrixMixdownIndexPresent,
1835
74.3k
          asc->m_progrConfigElement.MatrixMixdownIndex,
1836
74.3k
          asc->m_progrConfigElement.PseudoSurroundEnable);
1837
74.3k
    }
1838
74.3k
  }
1839
1840
443k
  self->streamInfo.channelConfig = asc->m_channelConfiguration;
1841
1842
443k
  if (self->streamInfo.aot != asc->m_aot) {
1843
54.5k
    if (configMode & AC_CM_ALLOC_MEM) {
1844
24.4k
      self->streamInfo.aot = asc->m_aot;
1845
24.4k
    }
1846
54.5k
    ascChanged = 1;
1847
54.5k
  }
1848
1849
443k
  if (asc->m_aot == AOT_ER_AAC_ELD &&
1850
85.7k
      asc->m_sc.m_eldSpecificConfig.m_downscaledSamplingFrequency != 0) {
1851
85.7k
    if (self->samplingRateInfo[0].samplingRate !=
1852
85.7k
            asc->m_sc.m_eldSpecificConfig.m_downscaledSamplingFrequency ||
1853
45.7k
        self->samplingRateInfo[0].samplingRate * self->downscaleFactor !=
1854
45.7k
            asc->m_samplingFrequency) {
1855
      /* get downscaledSamplingFrequency from ESC and compute the downscale
1856
       * factor */
1857
40.4k
      downscaleFactorInBS =
1858
40.4k
          asc->m_samplingFrequency /
1859
40.4k
          asc->m_sc.m_eldSpecificConfig.m_downscaledSamplingFrequency;
1860
40.4k
      if ((downscaleFactorInBS == 1 || downscaleFactorInBS == 2 ||
1861
6.24k
           (downscaleFactorInBS == 3 &&
1862
1.13k
            asc->m_sc.m_eldSpecificConfig.m_frameLengthFlag) ||
1863
5.31k
           downscaleFactorInBS == 4) &&
1864
37.1k
          ((asc->m_samplingFrequency %
1865
37.1k
            asc->m_sc.m_eldSpecificConfig.m_downscaledSamplingFrequency) ==
1866
37.1k
           0)) {
1867
37.0k
        downscaleFactor = downscaleFactorInBS;
1868
37.0k
      } else {
1869
3.35k
        downscaleFactorInBS = 1;
1870
3.35k
        downscaleFactor = 1;
1871
3.35k
      }
1872
40.4k
    }
1873
357k
  } else {
1874
357k
    downscaleFactorInBS = 1;
1875
357k
    downscaleFactor = 1;
1876
357k
  }
1877
1878
443k
  if (self->downscaleFactorInBS != downscaleFactorInBS) {
1879
2.02k
    if (configMode & AC_CM_ALLOC_MEM) {
1880
1.00k
      self->downscaleFactorInBS = downscaleFactorInBS;
1881
1.00k
      self->downscaleFactor = downscaleFactor;
1882
1.00k
    }
1883
2.02k
    ascChanged = 1;
1884
2.02k
  }
1885
1886
443k
  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
443k
  self->streamInfo.bitRate = 0;
1892
1893
443k
  if (asc->m_aot == AOT_ER_AAC_ELD) {
1894
85.7k
    if (self->useLdQmfTimeAlign !=
1895
85.7k
        asc->m_sc.m_eldSpecificConfig.m_useLdQmfTimeAlign) {
1896
8.67k
      ascChanged = 1;
1897
8.67k
    }
1898
85.7k
    if (configMode & AC_CM_ALLOC_MEM) {
1899
39.3k
      self->useLdQmfTimeAlign =
1900
39.3k
          asc->m_sc.m_eldSpecificConfig.m_useLdQmfTimeAlign;
1901
39.3k
    }
1902
85.7k
    if (sbrEnabled != asc->m_sbrPresentFlag) {
1903
12.5k
      ascChanged = 1;
1904
12.5k
    }
1905
85.7k
  }
1906
1907
443k
  self->streamInfo.extAot = asc->m_extensionAudioObjectType;
1908
443k
  if (self->streamInfo.extSamplingRate !=
1909
443k
      (INT)asc->m_extensionSamplingFrequency) {
1910
108k
    ascChanged = 1;
1911
108k
  }
1912
443k
  if (configMode & AC_CM_ALLOC_MEM) {
1913
216k
    self->streamInfo.extSamplingRate = asc->m_extensionSamplingFrequency;
1914
216k
  }
1915
443k
  flags |= (asc->m_sbrPresentFlag) ? AC_SBR_PRESENT : 0;
1916
443k
  flags |= (asc->m_psPresentFlag) ? AC_PS_PRESENT : 0;
1917
443k
  if (asc->m_sbrPresentFlag) {
1918
197k
    sbrEnabled = 1;
1919
197k
    sbrEnabledPrev = 1;
1920
245k
  } else {
1921
245k
    sbrEnabled = 0;
1922
245k
    sbrEnabledPrev = 0;
1923
245k
  }
1924
443k
  if (sbrEnabled && asc->m_extensionSamplingFrequency) {
1925
197k
    if (downscaleFactor != 1 && (downscaleFactor)&1) {
1926
0
      return AAC_DEC_UNSUPPORTED_SAMPLINGRATE; /* SBR needs an even downscale
1927
                                                  factor */
1928
0
    }
1929
197k
    if (configMode & AC_CM_ALLOC_MEM) {
1930
94.0k
      self->streamInfo.extSamplingRate =
1931
94.0k
          self->streamInfo.extSamplingRate / self->downscaleFactor;
1932
94.0k
    }
1933
197k
  }
1934
443k
  if ((asc->m_aot == AOT_AAC_LC) && (asc->m_sbrPresentFlag == 1) &&
1935
3.48k
      (asc->m_extensionSamplingFrequency > (2 * asc->m_samplingFrequency))) {
1936
505
    return AAC_DEC_UNSUPPORTED_SAMPLINGRATE; /* Core decoder supports at most a
1937
                                                1:2 upsampling for HE-AAC and
1938
                                                HE-AACv2 */
1939
505
  }
1940
1941
  /* --------- vcb11 ------------ */
1942
442k
  flags |= (asc->m_vcb11Flag) ? AC_ER_VCB11 : 0;
1943
1944
  /* ---------- rvlc ------------ */
1945
442k
  flags |= (asc->m_rvlcFlag) ? AC_ER_RVLC : 0;
1946
1947
  /* ----------- hcr ------------ */
1948
442k
  flags |= (asc->m_hcrFlag) ? AC_ER_HCR : 0;
1949
1950
442k
  if (asc->m_aot == AOT_ER_AAC_ELD) {
1951
85.7k
    mpsEnableCurr = 0;
1952
85.7k
    flags |= AC_ELD;
1953
85.7k
    flags |= (asc->m_sbrPresentFlag)
1954
85.7k
                 ? AC_SBR_PRESENT
1955
85.7k
                 : 0; /* Need to set the SBR flag for backward-compatibility
1956
                               reasons. Even if SBR is not supported. */
1957
85.7k
    flags |= (asc->m_sc.m_eldSpecificConfig.m_sbrCrcFlag) ? AC_SBRCRC : 0;
1958
85.7k
    flags |= (asc->m_sc.m_eldSpecificConfig.m_useLdQmfTimeAlign)
1959
85.7k
                 ? AC_MPS_PRESENT
1960
85.7k
                 : 0;
1961
85.7k
    if (self->mpsApplicable) {
1962
17.9k
      mpsEnableCurr = asc->m_sc.m_eldSpecificConfig.m_useLdQmfTimeAlign;
1963
17.9k
    }
1964
85.7k
  }
1965
442k
  flags |= (asc->m_aot == AOT_ER_AAC_LD) ? AC_LD : 0;
1966
442k
  flags |= (asc->m_epConfig >= 0) ? AC_ER : 0;
1967
1968
442k
  if (asc->m_aot == AOT_USAC) {
1969
159k
    flags |= AC_USAC;
1970
159k
    flags |= (asc->m_sc.m_usacConfig.element[0].m_stereoConfigIndex > 0)
1971
159k
                 ? AC_MPS_PRESENT
1972
159k
                 : 0;
1973
159k
  }
1974
442k
  if (asc->m_aot == AOT_DRM_AAC) {
1975
0
    flags |= AC_DRM | AC_SBRCRC | AC_SCALABLE;
1976
0
  }
1977
442k
  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
442k
  if ((asc->m_aot == AOT_AAC_SCAL) || (asc->m_aot == AOT_ER_AAC_SCAL)) {
1982
29.3k
    flags |= AC_SCALABLE;
1983
29.3k
  }
1984
1985
442k
  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
442k
  self->streamInfo.epConfig = asc->m_epConfig;
1992
  /* self->hInput->asc.m_epConfig = asc->m_epConfig; */
1993
1994
442k
  if (asc->m_epConfig > 1) return AAC_DEC_UNSUPPORTED_ER_FORMAT;
1995
1996
  /* Check if samplerate changed. */
1997
442k
  if ((self->samplingRateInfo[streamIndex].samplingRate !=
1998
442k
       asc->m_samplingFrequency) ||
1999
223k
      (self->streamInfo.aacSamplesPerFrame !=
2000
286k
       (INT)asc->m_samplesPerFrame / downscaleFactor)) {
2001
286k
    AAC_DECODER_ERROR error;
2002
2003
286k
    ascChanged = 1;
2004
2005
286k
    if (configMode & AC_CM_ALLOC_MEM) {
2006
      /* Update samplerate info. */
2007
144k
      error = getSamplingRateInfo(
2008
144k
          &self->samplingRateInfo[streamIndex], asc->m_samplesPerFrame,
2009
144k
          asc->m_samplingFrequencyIndex, asc->m_samplingFrequency);
2010
144k
      if (error != AAC_DEC_OK) {
2011
0
        return error;
2012
0
      }
2013
144k
      self->streamInfo.aacSampleRate =
2014
144k
          self->samplingRateInfo[0].samplingRate / self->downscaleFactor;
2015
144k
      self->streamInfo.aacSamplesPerFrame =
2016
144k
          asc->m_samplesPerFrame / self->downscaleFactor;
2017
144k
      if (self->streamInfo.aacSampleRate <= 0) {
2018
0
        return AAC_DEC_UNSUPPORTED_SAMPLINGRATE;
2019
0
      }
2020
144k
    }
2021
286k
  }
2022
2023
  /* Check if amount of channels has changed. */
2024
442k
  if (self->ascChannels[streamIndex] != ascChannels) {
2025
181k
    ascChanged = 1;
2026
181k
  }
2027
2028
  /* detect config change */
2029
442k
  if (configMode & AC_CM_DET_CFG_CHANGE) {
2030
226k
    if (ascChanged != 0) {
2031
149k
      *configChanged = 1;
2032
149k
    }
2033
2034
226k
    CAacDecoder_AcceptFlags(self, asc, flags, elFlags, streamIndex,
2035
226k
                            elementOffset);
2036
2037
226k
    return err;
2038
226k
  }
2039
2040
  /* set AC_USAC_SCFGI3 globally if any usac element uses */
2041
216k
  switch (asc->m_aot) {
2042
78.6k
    case AOT_USAC:
2043
78.6k
      if (sbrEnabled) {
2044
70.6k
        for (int _el = 0;
2045
151k
             _el < (int)self->pUsacConfig[streamIndex]->m_usacNumElements;
2046
80.5k
             _el++) {
2047
80.5k
          int el = elementOffset + _el;
2048
80.5k
          if (IS_USAC_CHANNEL_ELEMENT(self->elements[el])) {
2049
70.6k
            if (usacStereoConfigIndex < 0) {
2050
70.6k
              usacStereoConfigIndex = self->usacStereoConfigIndex[el];
2051
70.6k
            } else {
2052
0
              if ((usacStereoConfigIndex != self->usacStereoConfigIndex[el]) ||
2053
0
                  (self->usacStereoConfigIndex[el] > 0)) {
2054
0
                goto bail;
2055
0
              }
2056
0
            }
2057
70.6k
          }
2058
80.5k
        }
2059
2060
70.6k
        if (usacStereoConfigIndex < 0) {
2061
0
          goto bail;
2062
0
        }
2063
2064
70.6k
        if (usacStereoConfigIndex == 3) {
2065
14.0k
          flags |= AC_USAC_SCFGI3;
2066
14.0k
        }
2067
70.6k
      }
2068
78.6k
      break;
2069
138k
    default:
2070
138k
      break;
2071
216k
  }
2072
2073
216k
  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
144k
    switch (asc->m_aot) {
2079
47.2k
      case AOT_USAC:
2080
47.2k
        if (sbrEnabled) {
2081
42.5k
          const UCHAR map_sbrRatio_2_nAnaBands[] = {16, 24, 32};
2082
2083
42.5k
          FDK_ASSERT(asc->m_sc.m_usacConfig.m_sbrRatioIndex > 0);
2084
42.5k
          FDK_ASSERT(streamIndex == 0);
2085
2086
42.5k
          self->qmfDomain.globalConf.nInputChannels_requested = ascChannels;
2087
42.5k
          self->qmfDomain.globalConf.nOutputChannels_requested =
2088
42.5k
              (usacStereoConfigIndex == 1) ? 2 : ascChannels;
2089
42.5k
          self->qmfDomain.globalConf.flags_requested = 0;
2090
42.5k
          self->qmfDomain.globalConf.nBandsAnalysis_requested =
2091
42.5k
              map_sbrRatio_2_nAnaBands[asc->m_sc.m_usacConfig.m_sbrRatioIndex -
2092
42.5k
                                       1];
2093
42.5k
          self->qmfDomain.globalConf.nBandsSynthesis_requested = 64;
2094
42.5k
          self->qmfDomain.globalConf.nQmfTimeSlots_requested =
2095
42.5k
              (asc->m_sc.m_usacConfig.m_sbrRatioIndex == 1) ? 64 : 32;
2096
42.5k
          self->qmfDomain.globalConf.nQmfOvTimeSlots_requested =
2097
42.5k
              (asc->m_sc.m_usacConfig.m_sbrRatioIndex == 1) ? 12 : 6;
2098
42.5k
          self->qmfDomain.globalConf.nQmfProcBands_requested = 64;
2099
42.5k
          self->qmfDomain.globalConf.nQmfProcChannels_requested = 1;
2100
42.5k
          self->qmfDomain.globalConf.parkChannel =
2101
42.5k
              (usacStereoConfigIndex == 3) ? 1 : 0;
2102
42.5k
          self->qmfDomain.globalConf.parkChannel_requested =
2103
42.5k
              (usacStereoConfigIndex == 3) ? 1 : 0;
2104
42.5k
          self->qmfDomain.globalConf.qmfDomainExplicitConfig = 1;
2105
42.5k
        }
2106
47.2k
        break;
2107
47.2k
      case AOT_ER_AAC_ELD:
2108
21.3k
        if (mpsEnableCurr &&
2109
3.51k
            asc->m_sc.m_eldSpecificConfig.m_useLdQmfTimeAlign) {
2110
3.51k
          SAC_INPUT_CONFIG sac_interface = (sbrEnabled && self->hSbrDecoder)
2111
3.51k
                                               ? SAC_INTERFACE_QMF
2112
3.51k
                                               : SAC_INTERFACE_TIME;
2113
3.51k
          mpegSurroundDecoder_ConfigureQmfDomain(
2114
3.51k
              (CMpegSurroundDecoder *)self->pMpegSurroundDecoder, sac_interface,
2115
3.51k
              (UINT)self->streamInfo.aacSampleRate, asc->m_aot);
2116
3.51k
          self->qmfDomain.globalConf.qmfDomainExplicitConfig = 1;
2117
3.51k
        }
2118
21.3k
        break;
2119
75.5k
      default:
2120
75.5k
        self->qmfDomain.globalConf.qmfDomainExplicitConfig =
2121
75.5k
            0; /* qmfDomain is initialized by SBR and MPS init functions if
2122
                  required */
2123
75.5k
        break;
2124
144k
    }
2125
2126
    /* Allocate all memory structures for each channel */
2127
144k
    {
2128
144k
      int ch = aacChannelsOffset;
2129
844k
      for (int _ch = 0; _ch < ascChannels; _ch++) {
2130
700k
        if (ch >= (8)) {
2131
0
          goto bail;
2132
0
        }
2133
700k
        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
700k
        if (self->pAacDecoderChannelInfo[ch] == NULL) {
2137
0
          goto bail;
2138
0
        }
2139
700k
        ch++;
2140
700k
      }
2141
2142
144k
      int chIdx = aacChannelsOffsetIdx;
2143
144k
      ch = aacChannelsOffset;
2144
144k
      int _numElements;
2145
144k
      _numElements = (((8)) + (8));
2146
144k
      if (flags & (AC_RSV603DA | AC_USAC)) {
2147
47.2k
        _numElements = (int)asc->m_sc.m_usacConfig.m_usacNumElements;
2148
47.2k
      }
2149
982k
      for (int _el = 0; _el < _numElements; _el++) {
2150
909k
        int el_channels = 0;
2151
909k
        int el = elementOffset + _el;
2152
2153
909k
        if (flags &
2154
909k
            (AC_ER | AC_LD | AC_ELD | AC_RSV603DA | AC_USAC | AC_RSVD50)) {
2155
168k
          if (ch >= ascChannels) {
2156
38.0k
            break;
2157
38.0k
          }
2158
168k
        }
2159
2160
871k
        switch (self->elements[el]) {
2161
98.1k
          case ID_SCE:
2162
325k
          case ID_CPE:
2163
400k
          case ID_LFE:
2164
417k
          case ID_USAC_SCE:
2165
447k
          case ID_USAC_CPE:
2166
447k
          case ID_USAC_LFE:
2167
2168
447k
            el_channels = CAacDecoder_GetELChannels(
2169
447k
                self->elements[el], self->usacStereoConfigIndex[el]);
2170
2171
447k
            {
2172
447k
              self->pAacDecoderChannelInfo[ch]->pComStaticData =
2173
447k
                  (CAacDecoderCommonStaticData *)FDKcalloc(
2174
447k
                      1, sizeof(CAacDecoderCommonStaticData));
2175
447k
              if (self->pAacDecoderChannelInfo[ch]->pComStaticData == NULL) {
2176
0
                goto bail;
2177
0
              }
2178
447k
              if (ch == aacChannelsOffset) {
2179
144k
                self->pAacDecoderChannelInfo[ch]->pComData =
2180
144k
                    (CAacDecoderCommonData *)GetWorkBufferCore6();
2181
144k
                self->pAacDecoderChannelInfo[ch]
2182
144k
                    ->pComStaticData->pWorkBufferCore1 = GetWorkBufferCore1();
2183
303k
              } else {
2184
303k
                self->pAacDecoderChannelInfo[ch]->pComData =
2185
303k
                    (CAacDecoderCommonData *)FDKaalloc(
2186
303k
                        sizeof(CAacDecoderCommonData), ALIGNMENT_DEFAULT);
2187
303k
                self->pAacDecoderChannelInfo[ch]
2188
303k
                    ->pComStaticData->pWorkBufferCore1 =
2189
303k
                    self->pAacDecoderChannelInfo[aacChannelsOffset]
2190
303k
                        ->pComStaticData->pWorkBufferCore1;
2191
303k
              }
2192
447k
              if ((self->pAacDecoderChannelInfo[ch]->pComData == NULL) ||
2193
447k
                  (self->pAacDecoderChannelInfo[ch]
2194
447k
                       ->pComStaticData->pWorkBufferCore1 == NULL)) {
2195
0
                goto bail;
2196
0
              }
2197
447k
              self->pAacDecoderChannelInfo[ch]->pDynData =
2198
447k
                  &(self->pAacDecoderChannelInfo[ch]
2199
447k
                        ->pComData->pAacDecoderDynamicData[0]);
2200
447k
              self->pAacDecoderChannelInfo[ch]->pSpectralCoefficient =
2201
447k
                  (SPECTRAL_PTR)&self->workBufferCore2[ch * 1024];
2202
2203
447k
              if (el_channels == 2) {
2204
252k
                if (ch >= (8) - 1) {
2205
0
                  return AAC_DEC_UNSUPPORTED_CHANNELCONFIG;
2206
0
                }
2207
252k
                self->pAacDecoderChannelInfo[ch + 1]->pComData =
2208
252k
                    self->pAacDecoderChannelInfo[ch]->pComData;
2209
252k
                self->pAacDecoderChannelInfo[ch + 1]->pComStaticData =
2210
252k
                    self->pAacDecoderChannelInfo[ch]->pComStaticData;
2211
252k
                self->pAacDecoderChannelInfo[ch + 1]
2212
252k
                    ->pComStaticData->pWorkBufferCore1 =
2213
252k
                    self->pAacDecoderChannelInfo[ch]
2214
252k
                        ->pComStaticData->pWorkBufferCore1;
2215
252k
                self->pAacDecoderChannelInfo[ch + 1]->pDynData =
2216
252k
                    &(self->pAacDecoderChannelInfo[ch]
2217
252k
                          ->pComData->pAacDecoderDynamicData[1]);
2218
252k
                self->pAacDecoderChannelInfo[ch + 1]->pSpectralCoefficient =
2219
252k
                    (SPECTRAL_PTR)&self->workBufferCore2[(ch + 1) * 1024];
2220
252k
              }
2221
2222
447k
              ch += el_channels;
2223
447k
            }
2224
0
            chIdx += el_channels;
2225
447k
            break;
2226
2227
423k
          default:
2228
423k
            break;
2229
871k
        }
2230
2231
871k
        if (self->elements[el] == ID_END) {
2232
33.4k
          break;
2233
33.4k
        }
2234
2235
838k
        el++;
2236
838k
      }
2237
2238
144k
      chIdx = aacChannelsOffsetIdx;
2239
144k
      ch = aacChannelsOffset;
2240
844k
      for (int _ch = 0; _ch < ascChannels; _ch++) {
2241
        /* Allocate persistent channel memory */
2242
700k
        {
2243
700k
          self->pAacDecoderStaticChannelInfo[ch] =
2244
700k
              GetAacDecoderStaticChannelInfo(ch);
2245
700k
          if (self->pAacDecoderStaticChannelInfo[ch] == NULL) {
2246
0
            goto bail;
2247
0
          }
2248
700k
          self->pAacDecoderStaticChannelInfo[ch]->pOverlapBuffer =
2249
700k
              GetOverlapBuffer(ch); /* This area size depends on the AOT */
2250
700k
          if (self->pAacDecoderStaticChannelInfo[ch]->pOverlapBuffer == NULL) {
2251
0
            goto bail;
2252
0
          }
2253
700k
          if (flags & (AC_USAC | AC_RSVD50 | AC_RSV603DA /*|AC_BSAC*/)) {
2254
72.6k
            self->pAacDecoderStaticChannelInfo[ch]->hArCo = CArco_Create();
2255
72.6k
            if (self->pAacDecoderStaticChannelInfo[ch]->hArCo == NULL) {
2256
0
              goto bail;
2257
0
            }
2258
72.6k
          }
2259
2260
700k
          if (!(flags & (AC_USAC | AC_RSV603DA))) {
2261
627k
            CPns_UpdateNoiseState(
2262
627k
                &self->pAacDecoderChannelInfo[ch]->data.aac.PnsData,
2263
627k
                &self->pAacDecoderStaticChannelInfo[ch]->pnsCurrentSeed,
2264
627k
                self->pAacDecoderChannelInfo[ch]->pComData->pnsRandomSeed);
2265
627k
          }
2266
700k
          ch++;
2267
700k
        }
2268
0
        chIdx++;
2269
700k
      }
2270
2271
144k
      if (flags & AC_USAC) {
2272
124k
        for (int _ch = 0; _ch < flushChannels; _ch++) {
2273
77.0k
          ch = aacChannelsOffset + _ch;
2274
77.0k
          if (self->pTimeDataFlush[ch] == NULL) {
2275
15.8k
            self->pTimeDataFlush[ch] = GetTimeDataFlush(ch);
2276
15.8k
            if (self->pTimeDataFlush[ch] == NULL) {
2277
0
              goto bail;
2278
0
            }
2279
15.8k
          }
2280
77.0k
        }
2281
47.2k
      }
2282
2283
144k
      if (flags & (AC_USAC | AC_RSV603DA)) {
2284
47.2k
        int complexStereoPredPossible = 0;
2285
47.2k
        ch = aacChannelsOffset;
2286
47.2k
        chIdx = aacChannelsOffsetIdx;
2287
103k
        for (int _el2 = 0; _el2 < (int)asc->m_sc.m_usacConfig.m_usacNumElements;
2288
56.6k
             _el2++) {
2289
56.6k
          int el2 = elementOffset + _el2;
2290
56.6k
          int elCh = 0, ch2;
2291
2292
56.6k
          if ((self->elements[el2] == ID_USAC_CPE) &&
2293
29.7k
              !(self->usacStereoConfigIndex[el2] == 1)) {
2294
25.3k
            elCh = 2;
2295
31.3k
          } else if (IS_CHANNEL_ELEMENT(self->elements[el2])) {
2296
21.9k
            elCh = 1;
2297
21.9k
          }
2298
2299
56.6k
          if (elFlags[el2] & AC_EL_USAC_CP_POSSIBLE) {
2300
9.14k
            complexStereoPredPossible = 1;
2301
9.14k
            if (self->cpeStaticData[el2] == NULL) {
2302
9.14k
              self->cpeStaticData[el2] = GetCpePersistentData();
2303
9.14k
              if (self->cpeStaticData[el2] == NULL) {
2304
0
                goto bail;
2305
0
              }
2306
9.14k
            }
2307
9.14k
          }
2308
2309
129k
          for (ch2 = 0; ch2 < elCh; ch2++) {
2310
            /* Hook element specific cpeStaticData into channel specific
2311
             * aacDecoderStaticChannelInfo */
2312
72.6k
            self->pAacDecoderStaticChannelInfo[ch]->pCpeStaticData =
2313
72.6k
                self->cpeStaticData[el2];
2314
72.6k
            if (self->pAacDecoderStaticChannelInfo[ch]->pCpeStaticData !=
2315
72.6k
                NULL) {
2316
18.2k
              self->pAacDecoderStaticChannelInfo[ch]
2317
18.2k
                  ->pCpeStaticData->jointStereoPersistentData
2318
18.2k
                  .spectralCoeffs[ch2] =
2319
18.2k
                  self->pAacDecoderStaticChannelInfo[ch]
2320
18.2k
                      ->concealmentInfo.spectralCoefficient;
2321
18.2k
              self->pAacDecoderStaticChannelInfo[ch]
2322
18.2k
                  ->pCpeStaticData->jointStereoPersistentData.specScale[ch2] =
2323
18.2k
                  self->pAacDecoderStaticChannelInfo[ch]
2324
18.2k
                      ->concealmentInfo.specScale;
2325
18.2k
              self->pAacDecoderStaticChannelInfo[ch]
2326
18.2k
                  ->pCpeStaticData->jointStereoPersistentData.scratchBuffer =
2327
18.2k
                  (FIXP_DBL *)self->pTimeData2;
2328
18.2k
            }
2329
72.6k
            chIdx++;
2330
72.6k
            ch++;
2331
72.6k
          } /* for each channel in current element */
2332
56.6k
          if (complexStereoPredPossible && (elCh == 2)) {
2333
            /* needed once for all channels */
2334
9.14k
            if (self->pAacDecoderChannelInfo[ch - 1]
2335
9.14k
                    ->pComStaticData->cplxPredictionData == NULL) {
2336
9.14k
              self->pAacDecoderChannelInfo[ch - 1]
2337
9.14k
                  ->pComStaticData->cplxPredictionData =
2338
9.14k
                  GetCplxPredictionData();
2339
9.14k
            }
2340
9.14k
            if (self->pAacDecoderChannelInfo[ch - 1]
2341
9.14k
                    ->pComStaticData->cplxPredictionData == NULL) {
2342
0
              goto bail;
2343
0
            }
2344
9.14k
          }
2345
56.6k
          if (elCh > 0) {
2346
47.2k
            self->pAacDecoderStaticChannelInfo[ch - elCh]->nfRandomSeed =
2347
47.2k
                (ULONG)0x3039;
2348
47.2k
            if (self->elements[el2] == ID_USAC_CPE) {
2349
29.7k
              if (asc->m_sc.m_usacConfig.element[el2].m_stereoConfigIndex !=
2350
29.7k
                  1) {
2351
25.3k
                self->pAacDecoderStaticChannelInfo[ch - elCh + 1]
2352
25.3k
                    ->nfRandomSeed = (ULONG)0x10932;
2353
25.3k
              }
2354
29.7k
            }
2355
47.2k
          }
2356
56.6k
        } /* for each element */
2357
47.2k
      }
2358
2359
144k
      if (ascChannels != self->aacChannels) {
2360
        /* Make allocated channel count persistent in decoder context. */
2361
144k
        self->aacChannels = aacChannelsOffset + ch;
2362
144k
      }
2363
144k
    }
2364
2365
144k
    if (usacResidualDelayCompSamples) {
2366
4.26k
      INT delayErr = FDK_Delay_Create(&self->usacResidualDelay,
2367
4.26k
                                      (USHORT)usacResidualDelayCompSamples, 1);
2368
4.26k
      if (delayErr) {
2369
0
        goto bail;
2370
0
      }
2371
4.26k
    }
2372
2373
    /* Make amount of signalled channels persistent in decoder context. */
2374
144k
    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
144k
    self->aacChannelsPrev = 0;
2379
144k
  }
2380
2381
216k
  if (self->pAacDecoderChannelInfo[0] != NULL) {
2382
216k
    self->pDrmBsBuffer = self->pAacDecoderChannelInfo[0]
2383
216k
                             ->pComStaticData->pWorkBufferCore1->DrmBsBuffer;
2384
216k
    self->drmBsBufferSize = DRM_BS_BUFFER_SIZE;
2385
216k
  }
2386
2387
  /* Update structures */
2388
216k
  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
144k
    int ch = 0;
2394
144k
    int chIdx = 0;
2395
844k
    for (int _ch = 0; _ch < self->ascChannels[streamIndex]; _ch++) {
2396
700k
      switch (self->streamInfo.aot) {
2397
80.8k
        case AOT_ER_AAC_ELD:
2398
114k
        case AOT_ER_AAC_LD:
2399
114k
          self->pAacDecoderChannelInfo[ch]->granuleLength =
2400
114k
              self->streamInfo.aacSamplesPerFrame;
2401
114k
          break;
2402
585k
        default:
2403
585k
          self->pAacDecoderChannelInfo[ch]->granuleLength =
2404
585k
              self->streamInfo.aacSamplesPerFrame / 8;
2405
585k
          break;
2406
700k
      }
2407
700k
      self->pAacDecoderChannelInfo[ch]->renderMode = initRenderMode;
2408
2409
700k
      mdct_init(&self->pAacDecoderStaticChannelInfo[ch]->IMdct,
2410
700k
                self->pAacDecoderStaticChannelInfo[ch]->pOverlapBuffer,
2411
700k
                OverlapBufferSize);
2412
2413
700k
      self->pAacDecoderStaticChannelInfo[ch]->last_core_mode = FD_LONG;
2414
700k
      self->pAacDecoderStaticChannelInfo[ch]->last_lpd_mode = 255;
2415
2416
700k
      self->pAacDecoderStaticChannelInfo[ch]->last_tcx_pitch = L_DIV;
2417
2418
      /* Reset DRC control data for this channel */
2419
700k
      aacDecoder_drcInitChannelData(
2420
700k
          &self->pAacDecoderStaticChannelInfo[ch]->drcData);
2421
2422
      /* Delete mixdown metadata from the past */
2423
700k
      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
700k
      CConcealment_InitChannelData(
2428
700k
          &self->pAacDecoderStaticChannelInfo[ch]->concealmentInfo,
2429
700k
          &self->concealCommonData, initRenderMode,
2430
700k
          self->streamInfo.aacSamplesPerFrame);
2431
700k
      ch++;
2432
700k
      chIdx++;
2433
700k
    }
2434
144k
  }
2435
2436
216k
  if (*configChanged) {
2437
144k
    int drcDecSampleRate, drcDecFrameSize;
2438
2439
144k
    if (self->streamInfo.extSamplingRate != 0) {
2440
64.7k
      drcDecSampleRate = self->streamInfo.extSamplingRate;
2441
64.7k
      drcDecFrameSize = (self->streamInfo.aacSamplesPerFrame *
2442
64.7k
                         self->streamInfo.extSamplingRate) /
2443
64.7k
                        self->streamInfo.aacSampleRate;
2444
79.4k
    } else {
2445
79.4k
      drcDecSampleRate = self->streamInfo.aacSampleRate;
2446
79.4k
      drcDecFrameSize = self->streamInfo.aacSamplesPerFrame;
2447
79.4k
    }
2448
2449
144k
    if (FDK_drcDec_Init(self->hUniDrcDecoder, drcDecFrameSize, drcDecSampleRate,
2450
144k
                        self->aacChannels) != 0)
2451
0
      goto bail;
2452
144k
  }
2453
2454
216k
  if (*configChanged) {
2455
144k
    if (asc->m_aot == AOT_USAC) {
2456
47.2k
      aacDecoder_drcDisable(self->hDrcInfo);
2457
47.2k
    }
2458
144k
  }
2459
2460
216k
  if (asc->m_aot == AOT_USAC) {
2461
78.6k
    pcmLimiter_SetAttack(self->hLimiter, (5));
2462
78.6k
    pcmLimiter_SetThreshold(self->hLimiter, FL2FXCONST_DBL(0.89125094f));
2463
78.6k
  }
2464
2465
216k
  CAacDecoder_AcceptFlags(self, asc, flags, elFlags, streamIndex,
2466
216k
                          elementOffset);
2467
216k
  self->sbrEnabled = sbrEnabled;
2468
216k
  self->sbrEnabledPrev = sbrEnabledPrev;
2469
216k
  self->mpsEnableCurr = mpsEnableCurr;
2470
2471
  /* Update externally visible copy of flags */
2472
216k
  self->streamInfo.flags = self->flags[0];
2473
2474
216k
  return err;
2475
2476
0
bail:
2477
0
  CAacDecoder_DeInit(self, 0);
2478
0
  return AAC_DEC_OUT_OF_MEMORY;
2479
216k
}
2480
2481
LINKSPEC_CPP AAC_DECODER_ERROR CAacDecoder_DecodeFrame(
2482
    HANDLE_AACDECODER self, const UINT flags, PCM_DEC *pTimeData,
2483
332k
    const INT timeDataSize, const int timeDataChannelOffset) {
2484
332k
  AAC_DECODER_ERROR ErrorStatus = AAC_DEC_OK;
2485
2486
332k
  CProgramConfig *pce;
2487
332k
  HANDLE_FDK_BITSTREAM bs = transportDec_GetBitstream(self->hInput, 0);
2488
2489
332k
  MP4_ELEMENT_ID type = ID_NONE; /* Current element type */
2490
332k
  INT aacChannels = 0; /* Channel counter for channels found in the bitstream */
2491
332k
  const int streamIndex = 0; /* index of the current substream */
2492
2493
332k
  INT auStartAnchor = (INT)FDKgetValidBits(
2494
332k
      bs); /* AU start bit buffer position for AU byte alignment */
2495
2496
332k
  INT checkSampleRate = self->streamInfo.aacSampleRate;
2497
2498
332k
  INT CConceal_TDFading_Applied[(8)] = {
2499
332k
      0}; /* Initialize status of Time Domain fading */
2500
2501
332k
  if (self->aacChannels <= 0) {
2502
40
    return AAC_DEC_UNSUPPORTED_CHANNELCONFIG;
2503
40
  }
2504
2505
  /* Any supported base layer valid AU will require more than 16 bits. */
2506
332k
  if ((transportDec_GetAuBitsRemaining(self->hInput, 0) < 15) &&
2507
1.50k
      (flags & (AACDEC_CONCEAL | AACDEC_FLUSH)) == 0) {
2508
1.50k
    self->frameOK = 0;
2509
1.50k
    ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
2510
1.50k
  }
2511
2512
  /* Reset Program Config structure */
2513
332k
  pce = &self->pce;
2514
332k
  CProgramConfig_Reset(pce);
2515
2516
332k
  CAacDecoder_AncDataReset(&self->ancData);
2517
332k
  if (!(flags & (AACDEC_CONCEAL | AACDEC_FLUSH)) &&
2518
332k
      !(self->flags[0] & (AC_USAC | AC_RSV603DA))) {
2519
114k
    int ch;
2520
114k
    if (self->streamInfo.channelConfig == 0) {
2521
      /* Init Channel/Element mapping table */
2522
14.5k
      for (ch = 0; ch < (8); ch++) {
2523
12.9k
        self->chMapping[ch] = 255;
2524
12.9k
      }
2525
1.62k
      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.62k
    }
2533
114k
  }
2534
2535
332k
  if (self->downscaleFactor > 1 && (self->flags[0] & AC_ELD)) {
2536
3.76k
    self->flags[0] |= AC_ELD_DOWNSCALE;
2537
329k
  } else {
2538
329k
    self->flags[0] &= ~AC_ELD_DOWNSCALE;
2539
329k
  }
2540
  /* unsupported dsf (aacSampleRate has not yet been divided by dsf) -> divide
2541
   */
2542
332k
  if (self->downscaleFactorInBS > 1 &&
2543
3.76k
      (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
332k
  if (self->streamInfo.aacSampleRate <= 0) {
2550
    /* Instance maybe uninitialized! */
2551
0
    return AAC_DEC_UNSUPPORTED_SAMPLINGRATE;
2552
0
  }
2553
332k
  switch (checkSampleRate) {
2554
4.81k
    case 96000:
2555
13.9k
    case 88200:
2556
15.4k
    case 64000:
2557
20.1k
    case 16000:
2558
32.8k
    case 12000:
2559
37.2k
    case 11025:
2560
56.3k
    case 8000:
2561
78.9k
    case 7350:
2562
79.2k
    case 48000:
2563
91.3k
    case 44100:
2564
96.3k
    case 32000:
2565
149k
    case 24000:
2566
239k
    case 22050:
2567
239k
      break;
2568
93.6k
    default:
2569
93.6k
      if (!(self->flags[0] & (AC_USAC | AC_RSVD50 | AC_RSV603DA))) {
2570
22
        return AAC_DEC_UNSUPPORTED_SAMPLINGRATE;
2571
22
      }
2572
93.6k
      break;
2573
332k
  }
2574
2575
332k
  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
332k
  int pceRead = 0; /* Flag indicating a PCE in the current raw_data_block() */
2599
2600
332k
  INT hdaacDecoded = 0;
2601
332k
  MP4_ELEMENT_ID previous_element =
2602
332k
      ID_END; /* Last element ID (required for extension payload mapping */
2603
332k
  UCHAR previous_element_index = 0; /* Canonical index of last element */
2604
332k
  int element_count =
2605
332k
      0; /* Element counter for elements found in the bitstream */
2606
332k
  int channel_element_count = 0; /* Channel element counter */
2607
332k
  MP4_ELEMENT_ID
2608
332k
  channel_elements[(3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) +
2609
332k
                    1)];     /* Channel elements in bit stream order. */
2610
332k
  int el_cnt[ID_LAST] = {0}; /* element counter ( robustness ) */
2611
332k
  int element_count_prev_streams =
2612
332k
      0; /* Element count of all previous sub streams. */
2613
2614
1.19M
  while ((type != ID_END) && (!(flags & (AACDEC_CONCEAL | AACDEC_FLUSH))) &&
2615
867k
         self->frameOK) {
2616
858k
    int el_channels;
2617
2618
858k
    if (!(self->flags[0] &
2619
858k
          (AC_USAC | AC_RSVD50 | AC_RSV603DA | AC_ELD | AC_SCALABLE | AC_ER)))
2620
48.0k
      type = (MP4_ELEMENT_ID)FDKreadBits(bs, 3);
2621
810k
    else {
2622
810k
      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
810k
      type = self->elements[element_count];
2628
810k
    }
2629
2630
858k
    if ((self->flags[streamIndex] & (AC_USAC | AC_RSVD50) &&
2631
449k
         element_count == 0) ||
2632
641k
        (self->flags[streamIndex] & AC_RSV603DA)) {
2633
217k
      self->flags[streamIndex] &= ~AC_INDEP;
2634
2635
217k
      if (FDKreadBit(bs)) {
2636
155k
        self->flags[streamIndex] |= AC_INDEP;
2637
155k
      }
2638
2639
217k
      int ch = aacChannels;
2640
509k
      for (int chIdx = aacChannels; chIdx < self->ascChannels[streamIndex];
2641
292k
           chIdx++) {
2642
292k
        {
2643
          /* Robustness check */
2644
292k
          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
292k
          if ((CConcealment_GetLastFrameOk(
2651
292k
                   &self->pAacDecoderStaticChannelInfo[ch]->concealmentInfo,
2652
292k
                   1) == 0) &&
2653
0
              !(self->flags[streamIndex] & AC_INDEP)) {
2654
0
            self->frameOK = 0;
2655
0
          }
2656
292k
          ch++;
2657
292k
        }
2658
292k
      }
2659
217k
    }
2660
2661
858k
    if ((INT)FDKgetValidBits(bs) < 0) {
2662
3.11k
      self->frameOK = 0;
2663
3.11k
    }
2664
2665
858k
    switch (type) {
2666
82.7k
      case ID_SCE:
2667
162k
      case ID_CPE:
2668
176k
      case ID_LFE:
2669
224k
      case ID_USAC_SCE:
2670
393k
      case ID_USAC_CPE:
2671
393k
      case ID_USAC_LFE:
2672
393k
        if (element_count >= (3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) + 1)) {
2673
19
          self->frameOK = 0;
2674
19
          ErrorStatus = AAC_DEC_PARSE_ERROR;
2675
19
          break;
2676
19
        }
2677
2678
393k
        el_channels = CAacDecoder_GetELChannels(
2679
393k
            type, self->usacStereoConfigIndex[element_count]);
2680
2681
        /*
2682
          Consistency check
2683
         */
2684
393k
        {
2685
393k
          int totalAscChannels = 0;
2686
2687
787k
          for (int i = 0; i < (1 * 1); i++) {
2688
393k
            totalAscChannels += self->ascChannels[i];
2689
393k
          }
2690
393k
          if ((el_cnt[type] >= (totalAscChannels >> (el_channels - 1))) ||
2691
393k
              (aacChannels > (totalAscChannels - el_channels))) {
2692
155
            ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
2693
155
            self->frameOK = 0;
2694
155
            break;
2695
155
          }
2696
393k
        }
2697
2698
393k
        if (!(self->flags[streamIndex] & (AC_USAC | AC_RSVD50 | AC_RSV603DA))) {
2699
176k
          int ch;
2700
431k
          for (ch = 0; ch < el_channels; ch += 1) {
2701
255k
            CPns_ResetData(&self->pAacDecoderChannelInfo[aacChannels + ch]
2702
255k
                                ->data.aac.PnsData,
2703
255k
                           &self->pAacDecoderChannelInfo[aacChannels + ch]
2704
255k
                                ->pComData->pnsInterChannelData);
2705
255k
          }
2706
176k
        }
2707
2708
393k
        if (self->frameOK) {
2709
392k
          ErrorStatus = CChannelElement_Read(
2710
392k
              bs, &self->pAacDecoderChannelInfo[aacChannels],
2711
392k
              &self->pAacDecoderStaticChannelInfo[aacChannels],
2712
392k
              self->streamInfo.aot, &self->samplingRateInfo[streamIndex],
2713
392k
              self->flags[streamIndex], self->elFlags[element_count],
2714
392k
              self->streamInfo.aacSamplesPerFrame, el_channels,
2715
392k
              self->streamInfo.epConfig, self->hInput);
2716
392k
          if (ErrorStatus != AAC_DEC_OK) {
2717
2.73k
            self->frameOK = 0;
2718
2.73k
          }
2719
392k
        }
2720
2721
393k
        if (self->frameOK) {
2722
          /* Lookup the element and decode it only if it belongs to the current
2723
           * program */
2724
389k
          if (CProgramConfig_LookupElement(
2725
389k
                  pce, self->streamInfo.channelConfig,
2726
389k
                  self->pAacDecoderChannelInfo[aacChannels]->ElementInstanceTag,
2727
389k
                  aacChannels, self->chMapping, self->channelType,
2728
389k
                  self->channelIndices, (8), &previous_element_index,
2729
389k
                  self->elements, type)) {
2730
389k
            channel_elements[channel_element_count++] = type;
2731
389k
            aacChannels += el_channels;
2732
389k
          } else {
2733
106
            self->frameOK = 0;
2734
106
          }
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
389k
          if (self->frameOK &&
2739
389k
              ((self->flags[streamIndex] & AC_SBR_PRESENT) ||
2740
113k
               (self->sbrEnabled == 1)) &&
2741
276k
              !(self->flags[streamIndex] &
2742
276k
                AC_USAC) /* Is done during explicit config set up */
2743
389k
          ) {
2744
83.0k
            SBR_ERROR sbrError;
2745
83.0k
            UCHAR configMode = 0;
2746
83.0k
            UCHAR configChanged = 0;
2747
83.0k
            configMode |= AC_CM_ALLOC_MEM;
2748
2749
83.0k
            sbrError = sbrDecoder_InitElement(
2750
83.0k
                self->hSbrDecoder, self->streamInfo.aacSampleRate,
2751
83.0k
                self->streamInfo.extSamplingRate,
2752
83.0k
                self->streamInfo.aacSamplesPerFrame, self->streamInfo.aot, type,
2753
83.0k
                previous_element_index, 2, /* Signalize that harmonicSBR shall
2754
                                              be ignored in the config change
2755
                                              detection */
2756
83.0k
                0, configMode, &configChanged, self->downscaleFactor);
2757
83.0k
            if (sbrError != SBRDEC_OK) {
2758
              /* Do not try to apply SBR because initializing the element
2759
               * failed. */
2760
45
              self->sbrEnabled = 0;
2761
45
            }
2762
83.0k
          }
2763
389k
        }
2764
2765
393k
        el_cnt[type]++;
2766
393k
        if (self->frameOK && (self->flags[streamIndex] & AC_USAC) &&
2767
215k
            (type == ID_USAC_CPE || type == ID_USAC_SCE)) {
2768
215k
          ErrorStatus = aacDecoder_ParseExplicitMpsAndSbr(
2769
215k
              self, bs, previous_element, previous_element_index, element_count,
2770
215k
              el_cnt);
2771
215k
          if (ErrorStatus != AAC_DEC_OK) {
2772
314
            self->frameOK = 0;
2773
314
          }
2774
215k
        }
2775
393k
        break;
2776
2777
1.02k
      case ID_CCE:
2778
        /*
2779
          Consistency check
2780
        */
2781
1.02k
        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
1.02k
        if (self->frameOK) {
2788
1.02k
          CAacDecoderCommonData commonData;
2789
1.02k
          CAacDecoderCommonStaticData commonStaticData;
2790
1.02k
          CWorkBufferCore1 workBufferCore1;
2791
1.02k
          commonStaticData.pWorkBufferCore1 = &workBufferCore1;
2792
          /* memory for spectral lines temporal on scratch */
2793
1.02k
          C_AALLOC_SCRATCH_START(mdctSpec, FIXP_DBL, 1024);
2794
2795
          /* create dummy channel for CCE parsing on stack */
2796
1.02k
          CAacDecoderChannelInfo tmpAacDecoderChannelInfo,
2797
1.02k
              *pTmpAacDecoderChannelInfo;
2798
2799
1.02k
          FDKmemclear(mdctSpec, 1024 * sizeof(FIXP_DBL));
2800
2801
1.02k
          tmpAacDecoderChannelInfo.pDynData = commonData.pAacDecoderDynamicData;
2802
1.02k
          tmpAacDecoderChannelInfo.pComData = &commonData;
2803
1.02k
          tmpAacDecoderChannelInfo.pComStaticData = &commonStaticData;
2804
1.02k
          tmpAacDecoderChannelInfo.pSpectralCoefficient =
2805
1.02k
              (SPECTRAL_PTR)mdctSpec;
2806
          /* Assume AAC-LC */
2807
1.02k
          tmpAacDecoderChannelInfo.granuleLength =
2808
1.02k
              self->streamInfo.aacSamplesPerFrame / 8;
2809
          /* Reset PNS data. */
2810
1.02k
          CPns_ResetData(
2811
1.02k
              &tmpAacDecoderChannelInfo.data.aac.PnsData,
2812
1.02k
              &tmpAacDecoderChannelInfo.pComData->pnsInterChannelData);
2813
1.02k
          pTmpAacDecoderChannelInfo = &tmpAacDecoderChannelInfo;
2814
          /* do CCE parsing */
2815
1.02k
          ErrorStatus = CChannelElement_Read(
2816
1.02k
              bs, &pTmpAacDecoderChannelInfo, NULL, self->streamInfo.aot,
2817
1.02k
              &self->samplingRateInfo[streamIndex], self->flags[streamIndex],
2818
1.02k
              AC_EL_GA_CCE, self->streamInfo.aacSamplesPerFrame, 1,
2819
1.02k
              self->streamInfo.epConfig, self->hInput);
2820
2821
1.02k
          C_AALLOC_SCRATCH_END(mdctSpec, FIXP_DBL, 1024);
2822
2823
1.02k
          if (ErrorStatus) {
2824
25
            self->frameOK = 0;
2825
25
          }
2826
2827
1.02k
          if (self->frameOK) {
2828
            /* Lookup the element and decode it only if it belongs to the
2829
             * current program */
2830
997
            if (CProgramConfig_LookupElement(
2831
997
                    pce, self->streamInfo.channelConfig,
2832
997
                    pTmpAacDecoderChannelInfo->ElementInstanceTag, 0,
2833
997
                    self->chMapping, self->channelType, self->channelIndices,
2834
997
                    (8), &previous_element_index, self->elements, type)) {
2835
              /* decoding of CCE not supported */
2836
990
            } else {
2837
7
              self->frameOK = 0;
2838
7
            }
2839
997
          }
2840
1.02k
        }
2841
1.02k
        el_cnt[type]++;
2842
1.02k
        break;
2843
2844
9.25k
      case ID_DSE: {
2845
9.25k
        UCHAR element_instance_tag;
2846
2847
9.25k
        CDataStreamElement_Read(self, bs, &element_instance_tag, auStartAnchor);
2848
2849
9.25k
        if (!CProgramConfig_LookupElement(
2850
9.25k
                pce, self->streamInfo.channelConfig, element_instance_tag, 0,
2851
9.25k
                self->chMapping, self->channelType, self->channelIndices, (8),
2852
9.25k
                &previous_element_index, self->elements, type)) {
2853
          /* most likely an error in bitstream occured */
2854
          // self->frameOK = 0;
2855
1.82k
        }
2856
9.25k
      } break;
2857
2858
2.37k
      case ID_PCE: {
2859
2.37k
        int result = CProgramConfigElement_Read(bs, self->hInput, pce,
2860
2.37k
                                                self->streamInfo.channelConfig,
2861
2.37k
                                                auStartAnchor);
2862
2.37k
        if (result < 0) {
2863
          /* Something went wrong */
2864
11
          ErrorStatus = AAC_DEC_PARSE_ERROR;
2865
11
          self->frameOK = 0;
2866
2.36k
        } 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
2.37k
        pceRead = (result >= 0) ? 1 : 0;
2884
2.37k
      } break;
2885
2886
8.62k
      case ID_FIL: {
2887
8.62k
        int bitCnt = FDKreadBits(bs, 4); /* bs_count */
2888
2889
8.62k
        if (bitCnt == 15) {
2890
22
          int esc_count = FDKreadBits(bs, 8); /* bs_esc_count */
2891
22
          bitCnt = esc_count + 14;
2892
22
        }
2893
2894
        /* Convert to bits */
2895
8.62k
        bitCnt <<= 3;
2896
2897
14.7k
        while (bitCnt > 0) {
2898
6.14k
          ErrorStatus = CAacDecoder_ExtPayloadParse(
2899
6.14k
              self, bs, &bitCnt, previous_element, previous_element_index, 1);
2900
6.14k
          if (ErrorStatus != AAC_DEC_OK) {
2901
53
            self->frameOK = 0;
2902
53
            break;
2903
53
          }
2904
6.14k
        }
2905
8.62k
      } break;
2906
2907
102k
      case ID_EXT:
2908
102k
        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
102k
        ErrorStatus = aacDecoder_ParseExplicitMpsAndSbr(
2915
102k
            self, bs, previous_element, previous_element_index, element_count,
2916
102k
            el_cnt);
2917
102k
        break;
2918
2919
17.2k
      case ID_USAC_EXT: {
2920
17.2k
        if ((element_count - element_count_prev_streams) >=
2921
17.2k
            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
17.2k
        int usacExtElementPayloadLength;
2931
        /* int usacExtElementStart, usacExtElementStop; */
2932
2933
17.2k
        if (FDKreadBit(bs)) {   /* usacExtElementPresent */
2934
6.69k
          if (FDKreadBit(bs)) { /* usacExtElementUseDefaultLength */
2935
4.48k
            usacExtElementPayloadLength =
2936
4.48k
                self->pUsacConfig[streamIndex]
2937
4.48k
                    ->element[element_count - element_count_prev_streams]
2938
4.48k
                    .extElement.usacExtElementDefaultLength;
2939
4.48k
          } else {
2940
2.20k
            usacExtElementPayloadLength = FDKreadBits(bs, 8);
2941
2.20k
            if (usacExtElementPayloadLength == (UINT)(1 << 8) - 1) {
2942
14
              UINT valueAdd = FDKreadBits(bs, 16);
2943
14
              usacExtElementPayloadLength += (INT)valueAdd - 2;
2944
14
            }
2945
2.20k
          }
2946
6.69k
          if (usacExtElementPayloadLength > 0) {
2947
5.53k
            int usacExtBitPos;
2948
2949
5.53k
            if (self->pUsacConfig[streamIndex]
2950
5.53k
                    ->element[element_count - element_count_prev_streams]
2951
5.53k
                    .extElement.usacExtElementPayloadFrag) {
2952
755
              /* usacExtElementStart = */ FDKreadBit(bs);
2953
755
              /* usacExtElementStop = */ FDKreadBit(bs);
2954
4.78k
            } else {
2955
              /* usacExtElementStart = 1; */
2956
              /* usacExtElementStop = 1; */
2957
4.78k
            }
2958
2959
5.53k
            usacExtBitPos = (INT)FDKgetValidBits(bs);
2960
2961
5.53k
            USAC_EXT_ELEMENT_TYPE usacExtElementType =
2962
5.53k
                self->pUsacConfig[streamIndex]
2963
5.53k
                    ->element[element_count - element_count_prev_streams]
2964
5.53k
                    .extElement.usacExtElementType;
2965
2966
5.53k
            switch (usacExtElementType) {
2967
4.46k
              case ID_EXT_ELE_UNI_DRC: /* uniDrcGain() */
2968
4.46k
                if (streamIndex == 0) {
2969
4.46k
                  int drcErr;
2970
2971
4.46k
                  drcErr = FDK_drcDec_ReadUniDrcGain(self->hUniDrcDecoder, bs);
2972
4.46k
                  if (drcErr != 0) {
2973
283
                    ErrorStatus = AAC_DEC_PARSE_ERROR;
2974
283
                  }
2975
4.46k
                }
2976
4.46k
                break;
2977
2978
1.07k
              default:
2979
1.07k
                break;
2980
5.53k
            }
2981
2982
            /* Skip any remaining bits of extension payload */
2983
5.53k
            usacExtBitPos = (usacExtElementPayloadLength * 8) -
2984
5.53k
                            (usacExtBitPos - (INT)FDKgetValidBits(bs));
2985
5.53k
            if (usacExtBitPos < 0) {
2986
66
              self->frameOK = 0;
2987
66
              ErrorStatus = AAC_DEC_PARSE_ERROR;
2988
66
            }
2989
5.53k
            FDKpushBiDirectional(bs, usacExtBitPos);
2990
5.53k
          }
2991
6.69k
        }
2992
17.2k
      } break;
2993
324k
      case ID_END:
2994
324k
      case ID_USAC_END:
2995
324k
        break;
2996
2997
0
      default:
2998
0
        ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
2999
0
        self->frameOK = 0;
3000
0
        break;
3001
858k
    }
3002
3003
858k
    previous_element = type;
3004
858k
    element_count++;
3005
3006
858k
  } /* while ( (type != ID_END) ... ) */
3007
3008
332k
  if (!(self->flags[streamIndex] &
3009
332k
        (AC_USAC | AC_RSVD50 | AC_RSV603DA | AC_BSAC | AC_LD | AC_ELD | AC_ER |
3010
332k
         AC_SCALABLE)) &&
3011
10.6k
      (self->streamInfo.channelConfig == 0) && pce->isValid &&
3012
1.62k
      (ErrorStatus == AAC_DEC_OK) && self->frameOK &&
3013
1.30k
      !(flags & (AACDEC_CONCEAL | AACDEC_FLUSH))) {
3014
    /* Check whether all PCE listed element instance tags are present in
3015
     * raw_data_block() */
3016
1.30k
    if (!validateElementInstanceTags(
3017
1.30k
            &self->pce, self->pAacDecoderChannelInfo, aacChannels,
3018
1.30k
            channel_elements,
3019
1.30k
            fMin(channel_element_count, (int)(sizeof(channel_elements) /
3020
1.30k
                                              sizeof(*channel_elements))))) {
3021
21
      ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
3022
21
      self->frameOK = 0;
3023
21
    }
3024
1.30k
  }
3025
3026
332k
  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
332k
    if (!(self->flags[streamIndex] & (AC_RSVD50 | AC_USAC)) ||
3031
218k
        (self->prerollAULength[self->accessUnit]) /* indicates preroll */
3032
332k
    ) {
3033
116k
      FDKbyteAlign(bs, auStartAnchor);
3034
116k
    }
3035
3036
    /* Check if all bits of the raw_data_block() have been read. */
3037
332k
    if (transportDec_GetAuBitsTotal(self->hInput, 0) > 0) {
3038
79.9k
      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
79.9k
      if (self->prerollAULength[self->accessUnit]) {
3043
62
        unreadBits = unreadBits - transportDec_GetAuBitsTotal(self->hInput, 0) +
3044
62
                     (INT)self->prerollAULength[self->accessUnit];
3045
62
      }
3046
79.9k
      if (((self->flags[streamIndex] & (AC_RSVD50 | AC_USAC)) &&
3047
10.3k
           ((unreadBits < 0) || (unreadBits > 7)) &&
3048
1.37k
           !(self->prerollAULength[self->accessUnit])) ||
3049
78.6k
          ((!(self->flags[streamIndex] & (AC_RSVD50 | AC_USAC)) ||
3050
9.08k
            (self->prerollAULength[self->accessUnit])) &&
3051
69.6k
           (unreadBits != 0))) {
3052
3.59k
        if ((((unreadBits < 0) || (unreadBits > 7)) && self->frameOK) &&
3053
242
            ((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
3.59k
        } else {
3058
3.59k
          self->frameOK = 0;
3059
3.59k
        }
3060
3061
        /* Do not overwrite current error */
3062
3.59k
        if (ErrorStatus == AAC_DEC_OK && self->frameOK == 0) {
3063
2.00k
          ErrorStatus = AAC_DEC_PARSE_ERROR;
3064
2.00k
        }
3065
        /* Always put the bitbuffer at the right position after the current
3066
         * Access Unit. */
3067
3.59k
        FDKpushBiDirectional(bs, unreadBits);
3068
3.59k
      }
3069
79.9k
    }
3070
3071
    /* Check the last element. The terminator (ID_END) has to be the last one
3072
     * (even if ER syntax is used). */
3073
332k
    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
332k
  }
3081
3082
332k
  if (!(flags & (AACDEC_CONCEAL | AACDEC_FLUSH)) && self->frameOK) {
3083
323k
    channel_elements[channel_element_count++] = ID_END;
3084
323k
  }
3085
332k
  element_count = 0;
3086
332k
  aacChannels = 0;
3087
332k
  type = ID_NONE;
3088
332k
  previous_element_index = 0;
3089
3090
1.08M
  while (type != ID_END &&
3091
753k
         element_count < (3 * ((8) * 2) + (((8) * 2)) / 2 + 4 * (1) + 1)) {
3092
753k
    int el_channels;
3093
3094
753k
    if ((flags & (AACDEC_CONCEAL | AACDEC_FLUSH)) || !self->frameOK) {
3095
29.1k
      channel_elements[element_count] = self->elements[element_count];
3096
29.1k
      if (channel_elements[element_count] == ID_NONE) {
3097
341
        channel_elements[element_count] = ID_END;
3098
341
      }
3099
29.1k
    }
3100
3101
753k
    if (self->flags[streamIndex] & (AC_USAC | AC_RSV603DA | AC_BSAC)) {
3102
455k
      type = self->elements[element_count];
3103
455k
    } else {
3104
297k
      type = channel_elements[element_count];
3105
297k
    }
3106
3107
753k
    if (!(flags & (AACDEC_CONCEAL | AACDEC_FLUSH)) && self->frameOK) {
3108
723k
      switch (type) {
3109
79.0k
        case ID_SCE:
3110
155k
        case ID_CPE:
3111
169k
        case ID_LFE:
3112
215k
        case ID_USAC_SCE:
3113
384k
        case ID_USAC_CPE:
3114
384k
        case ID_USAC_LFE:
3115
3116
384k
          el_channels = CAacDecoder_GetELChannels(
3117
384k
              type, self->usacStereoConfigIndex[element_count]);
3118
3119
384k
          if (!hdaacDecoded) {
3120
384k
            if (self->pAacDecoderStaticChannelInfo[aacChannels]
3121
384k
                    ->pCpeStaticData != NULL) {
3122
58.7k
              self->pAacDecoderStaticChannelInfo[aacChannels]
3123
58.7k
                  ->pCpeStaticData->jointStereoPersistentData.scratchBuffer =
3124
58.7k
                  (FIXP_DBL *)pTimeData;
3125
58.7k
            }
3126
384k
            CChannelElement_Decode(
3127
384k
                &self->pAacDecoderChannelInfo[aacChannels],
3128
384k
                &self->pAacDecoderStaticChannelInfo[aacChannels],
3129
384k
                &self->samplingRateInfo[streamIndex], self->flags[streamIndex],
3130
384k
                self->elFlags[element_count], el_channels);
3131
384k
          }
3132
384k
          aacChannels += el_channels;
3133
384k
          break;
3134
0
        case ID_NONE:
3135
0
          type = ID_END;
3136
0
          break;
3137
339k
        default:
3138
339k
          break;
3139
723k
      }
3140
723k
    }
3141
753k
    element_count++;
3142
753k
  }
3143
3144
  /* More AAC channels than specified by the ASC not allowed. */
3145
332k
  if ((aacChannels == 0 || aacChannels > self->aacChannels) &&
3146
9.36k
      !(flags & (AACDEC_CONCEAL | AACDEC_FLUSH))) {
3147
    /* Do not overwrite current error */
3148
9.34k
    if (ErrorStatus == AAC_DEC_OK) {
3149
1.95k
      ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
3150
1.95k
    }
3151
9.34k
    self->frameOK = 0;
3152
9.34k
    aacChannels = 0;
3153
9.34k
  }
3154
3155
332k
  if (!(flags & (AACDEC_CONCEAL | AACDEC_FLUSH))) {
3156
332k
    if (TRANSPORTDEC_OK != transportDec_CrcCheck(self->hInput)) {
3157
0
      ErrorStatus = AAC_DEC_CRC_ERROR;
3158
0
      self->frameOK = 0;
3159
0
    }
3160
332k
  }
3161
3162
  /* Ensure that in case of concealment a proper error status is set. */
3163
332k
  if ((self->frameOK == 0) && (ErrorStatus == AAC_DEC_OK)) {
3164
0
    ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
3165
0
  }
3166
3167
332k
  if (self->frameOK && (flags & AACDEC_FLUSH)) {
3168
22
    aacChannels = self->aacChannelsPrev;
3169
    /* Because the downmix could be active, its necessary to restore the channel
3170
     * type and indices. */
3171
22
    FDKmemcpy(self->channelType, self->channelTypePrev,
3172
22
              (8) * sizeof(AUDIO_CHANNEL_TYPE)); /* restore */
3173
22
    FDKmemcpy(self->channelIndices, self->channelIndicesPrev,
3174
22
              (8) * sizeof(UCHAR)); /* restore */
3175
22
    self->sbrEnabled = self->sbrEnabledPrev;
3176
332k
  } else {
3177
    /* store or restore the number of channels and the corresponding info */
3178
332k
    if (self->frameOK && !(flags & AACDEC_CONCEAL)) {
3179
323k
      self->aacChannelsPrev = aacChannels; /* store */
3180
323k
      FDKmemcpy(self->channelTypePrev, self->channelType,
3181
323k
                (8) * sizeof(AUDIO_CHANNEL_TYPE)); /* store */
3182
323k
      FDKmemcpy(self->channelIndicesPrev, self->channelIndices,
3183
323k
                (8) * sizeof(UCHAR)); /* store */
3184
323k
      self->sbrEnabledPrev = self->sbrEnabled;
3185
323k
    } else {
3186
9.34k
      if (self->aacChannels > 0) {
3187
9.34k
        if ((self->buildUpStatus == AACDEC_RSV60_BUILD_UP_ON) ||
3188
9.34k
            (self->buildUpStatus == AACDEC_RSV60_BUILD_UP_ON_IN_BAND) ||
3189
9.34k
            (self->buildUpStatus == AACDEC_USAC_BUILD_UP_ON)) {
3190
815
          aacChannels = self->aacChannels;
3191
815
          self->aacChannelsPrev = aacChannels; /* store */
3192
8.52k
        } else {
3193
8.52k
          aacChannels = self->aacChannelsPrev; /* restore */
3194
8.52k
        }
3195
9.34k
        FDKmemcpy(self->channelType, self->channelTypePrev,
3196
9.34k
                  (8) * sizeof(AUDIO_CHANNEL_TYPE)); /* restore */
3197
9.34k
        FDKmemcpy(self->channelIndices, self->channelIndicesPrev,
3198
9.34k
                  (8) * sizeof(UCHAR)); /* restore */
3199
9.34k
        self->sbrEnabled = self->sbrEnabledPrev;
3200
9.34k
      }
3201
9.34k
    }
3202
332k
  }
3203
3204
  /* Update number of output channels */
3205
332k
  self->streamInfo.aacNumChannels = aacChannels;
3206
3207
  /* Ensure consistency of IS_OUTPUT_VALID() macro. */
3208
332k
  if (aacChannels == 0) {
3209
3.38k
    ErrorStatus = AAC_DEC_UNKNOWN;
3210
3.38k
  }
3211
3212
332k
  if (pceRead == 1 && CProgramConfig_IsValid(pce)) {
3213
    /* Set matrix mixdown infos if available from PCE. */
3214
185
    pcmDmx_SetMatrixMixdownFromPce(
3215
185
        self->hPcmUtils, pce->MatrixMixdownIndexPresent,
3216
185
        pce->MatrixMixdownIndex, pce->PseudoSurroundEnable);
3217
185
    ;
3218
185
  }
3219
3220
  /* If there is no valid data to transfrom into time domain, return. */
3221
332k
  if (!IS_OUTPUT_VALID(ErrorStatus)) {
3222
3.38k
    return ErrorStatus;
3223
3.38k
  }
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
329k
  if ((self->streamInfo.channelConfig == 0) && !pce->isValid) {
3241
0
    self->chMapIndex = (aacChannels < 7) ? aacChannels : 0;
3242
0
  }
3243
3244
  /*
3245
    Inverse transform
3246
  */
3247
329k
  {
3248
329k
    int c, cIdx;
3249
329k
    int mapped, fCopyChMap = 1;
3250
329k
    UCHAR drcChMap[(8)];
3251
3252
329k
    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.38k
      UCHAR tmpChMap[(8)];
3264
1.38k
      if (CProgramConfig_GetPceChMap(pce, tmpChMap, (8)) == 0) {
3265
8.06k
        for (c = 0; c < aacChannels; c += 1) {
3266
6.68k
          drcChMap[c] =
3267
6.68k
              (self->chMapping[c] == 255) ? 255 : tmpChMap[self->chMapping[c]];
3268
6.68k
        }
3269
1.38k
        fCopyChMap = 0;
3270
1.38k
      }
3271
1.38k
    }
3272
329k
    if (fCopyChMap != 0) {
3273
328k
      FDKmemcpy(drcChMap, self->chMapping, (8) * sizeof(UCHAR));
3274
328k
    }
3275
3276
    /* Extract DRC control data and map it to channels (without bitstream delay)
3277
     */
3278
329k
    mapped = aacDecoder_drcProlog(
3279
329k
        self->hDrcInfo, bs, self->pAacDecoderStaticChannelInfo,
3280
329k
        pce->ElementInstanceTag, drcChMap, aacChannels);
3281
329k
    if (mapped > 0) {
3282
3.38k
      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.38k
        self->flags[streamIndex] |= AC_DRC_PRESENT;
3286
3.38k
      } else {
3287
0
        ErrorStatus = AAC_DEC_UNSUPPORTED_FORMAT;
3288
0
      }
3289
3.38k
    }
3290
329k
    if (self->flags[streamIndex] & (AC_USAC | AC_RSV603DA)) {
3291
217k
      aacDecoder_drcDisable(self->hDrcInfo);
3292
217k
    }
3293
3294
    /* Create a reverse mapping table */
3295
329k
    UCHAR Reverse_chMapping[((8) * 2)];
3296
874k
    for (c = 0; c < aacChannels; c++) {
3297
545k
      int d;
3298
1.05M
      for (d = 0; d < aacChannels - 1; d++) {
3299
728k
        if (self->chMapping[d] == c) {
3300
215k
          break;
3301
215k
        }
3302
728k
      }
3303
545k
      Reverse_chMapping[c] = d;
3304
545k
    }
3305
3306
329k
    int el;
3307
329k
    int el_channels;
3308
329k
    c = 0;
3309
329k
    cIdx = 0;
3310
329k
    el_channels = 0;
3311
1.07M
    for (el = 0; el < element_count; el++) {
3312
740k
      int frameOk_butConceal =
3313
740k
          0; /* Force frame concealment during mute release active state. */
3314
740k
      int concealApplyReturnCode;
3315
3316
740k
      if (self->flags[streamIndex] & (AC_USAC | AC_RSV603DA | AC_BSAC)) {
3317
453k
        type = self->elements[el];
3318
453k
      } else {
3319
287k
        type = channel_elements[el];
3320
287k
      }
3321
3322
740k
      {
3323
740k
        int nElementChannels;
3324
3325
740k
        nElementChannels =
3326
740k
            CAacDecoder_GetELChannels(type, self->usacStereoConfigIndex[el]);
3327
3328
740k
        el_channels += nElementChannels;
3329
3330
740k
        if (nElementChannels == 0) {
3331
349k
          continue;
3332
349k
        }
3333
740k
      }
3334
3335
391k
      int offset;
3336
391k
      int elCh = 0;
3337
      /* "c" iterates in canonical MPEG channel order */
3338
937k
      for (; cIdx < el_channels; c++, cIdx++, elCh++) {
3339
        /* Robustness check */
3340
545k
        if (c >= aacChannels) {
3341
210
          return AAC_DEC_UNKNOWN;
3342
210
        }
3343
3344
545k
        CAacDecoderChannelInfo *pAacDecoderChannelInfo =
3345
545k
            self->pAacDecoderChannelInfo[c];
3346
545k
        CAacDecoderStaticChannelInfo *pAacDecoderStaticChannelInfo =
3347
545k
            self->pAacDecoderStaticChannelInfo[c];
3348
3349
        /* Setup offset for time buffer traversal. */
3350
545k
        {
3351
545k
          pAacDecoderStaticChannelInfo =
3352
545k
              self->pAacDecoderStaticChannelInfo[Reverse_chMapping[c]];
3353
545k
          offset =
3354
545k
              FDK_chMapDescr_getMapValue(
3355
545k
                  &self->mapDescr, Reverse_chMapping[cIdx], self->chMapIndex) *
3356
545k
              timeDataChannelOffset;
3357
545k
        }
3358
3359
545k
        if (flags & AACDEC_FLUSH) {
3360
          /* Clear pAacDecoderChannelInfo->pSpectralCoefficient because with
3361
           * AACDEC_FLUSH set it contains undefined data. */
3362
22
          FDKmemclear(pAacDecoderChannelInfo->pSpectralCoefficient,
3363
22
                      sizeof(FIXP_DBL) * self->streamInfo.aacSamplesPerFrame);
3364
22
        }
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
545k
        {
3369
545k
          CIcsInfo *pIcsInfo = &pAacDecoderChannelInfo->icsInfo;
3370
545k
          CConcealmentInfo *hConcealmentInfo =
3371
545k
              &pAacDecoderStaticChannelInfo->concealmentInfo;
3372
545k
          const int mute_release_active =
3373
545k
              (self->frameOK && !(flags & AACDEC_CONCEAL)) &&
3374
535k
              ((hConcealmentInfo->concealState >= ConcealState_Mute) &&
3375
0
               (hConcealmentInfo->cntValidFrames + 1 <=
3376
0
                hConcealmentInfo->pConcealParams->numMuteReleaseFrames));
3377
545k
          const int icsIsInvalid = (GetScaleFactorBandsTransmitted(pIcsInfo) >
3378
545k
                                    GetScaleFactorBandsTotal(pIcsInfo));
3379
545k
          const int icsInfoUsedinFadeOut =
3380
545k
              !(pAacDecoderChannelInfo->renderMode == AACDEC_RENDER_LPD &&
3381
47.5k
                pAacDecoderStaticChannelInfo->last_lpd_mode == 0);
3382
545k
          if (icsInfoUsedinFadeOut && icsIsInvalid && !mute_release_active) {
3383
427
            self->frameOK = 0;
3384
427
          }
3385
545k
        }
3386
3387
        /*
3388
          Conceal defective spectral data
3389
        */
3390
545k
        {
3391
545k
          CAacDecoderChannelInfo **ppAacDecoderChannelInfo =
3392
545k
              &pAacDecoderChannelInfo;
3393
545k
          CAacDecoderStaticChannelInfo **ppAacDecoderStaticChannelInfo =
3394
545k
              &pAacDecoderStaticChannelInfo;
3395
545k
          {
3396
545k
            concealApplyReturnCode = CConcealment_Apply(
3397
545k
                &(*ppAacDecoderStaticChannelInfo)->concealmentInfo,
3398
545k
                *ppAacDecoderChannelInfo, *ppAacDecoderStaticChannelInfo,
3399
545k
                &self->samplingRateInfo[streamIndex],
3400
545k
                self->streamInfo.aacSamplesPerFrame,
3401
545k
                pAacDecoderStaticChannelInfo->last_lpd_mode,
3402
545k
                (self->frameOK && !(flags & AACDEC_CONCEAL)),
3403
545k
                self->flags[streamIndex]);
3404
545k
          }
3405
545k
        }
3406
545k
        if (concealApplyReturnCode == -1) {
3407
0
          frameOk_butConceal = 1;
3408
0
        }
3409
3410
545k
        if (flags & (AACDEC_INTR)) {
3411
          /* Reset DRC control data for this channel */
3412
0
          aacDecoder_drcInitChannelData(&pAacDecoderStaticChannelInfo->drcData);
3413
0
        }
3414
545k
        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
545k
        self->extGain[0] = (FIXP_DBL)AACDEC_DRC_GAIN_SCALING;
3425
3426
        /* DRC processing */
3427
545k
        aacDecoder_drcApply(
3428
545k
            self->hDrcInfo, self->hSbrDecoder, pAacDecoderChannelInfo,
3429
545k
            &pAacDecoderStaticChannelInfo->drcData, self->extGain, c,
3430
545k
            self->streamInfo.aacSamplesPerFrame, self->sbrEnabled
3431
3432
545k
        );
3433
3434
545k
        if (timeDataSize < timeDataChannelOffset * self->aacChannels) {
3435
0
          ErrorStatus = AAC_DEC_OUTPUT_BUFFER_TOO_SMALL;
3436
0
          break;
3437
0
        }
3438
545k
        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
545k
          switch (pAacDecoderChannelInfo->renderMode) {
3444
319k
            case AACDEC_RENDER_IMDCT:
3445
3446
319k
              CBlock_FrequencyToTime(
3447
319k
                  pAacDecoderStaticChannelInfo, pAacDecoderChannelInfo,
3448
319k
                  pTimeData + offset, self->streamInfo.aacSamplesPerFrame,
3449
319k
                  (self->frameOK && !(flags & AACDEC_CONCEAL) &&
3450
313k
                   !frameOk_butConceal),
3451
319k
                  pAacDecoderChannelInfo->pComStaticData->pWorkBufferCore1
3452
319k
                      ->mdctOutTemp,
3453
319k
                  self->aacOutDataHeadroom, self->elFlags[el], elCh);
3454
3455
319k
              self->extGainDelay = self->streamInfo.aacSamplesPerFrame;
3456
319k
              break;
3457
178k
            case AACDEC_RENDER_ELDFB: {
3458
178k
              CBlock_FrequencyToTimeLowDelay(
3459
178k
                  pAacDecoderStaticChannelInfo, pAacDecoderChannelInfo,
3460
178k
                  pTimeData + offset, self->streamInfo.aacSamplesPerFrame);
3461
178k
              self->extGainDelay =
3462
178k
                  (self->streamInfo.aacSamplesPerFrame * 2 -
3463
178k
                   self->streamInfo.aacSamplesPerFrame / 2 - 1) /
3464
178k
                  2;
3465
178k
            } break;
3466
47.2k
            case AACDEC_RENDER_LPD:
3467
3468
47.2k
              CLpd_RenderTimeSignal(
3469
47.2k
                  pAacDecoderStaticChannelInfo, pAacDecoderChannelInfo,
3470
47.2k
                  pTimeData + offset, self->streamInfo.aacSamplesPerFrame,
3471
47.2k
                  &self->samplingRateInfo[streamIndex],
3472
47.2k
                  (self->frameOK && !(flags & AACDEC_CONCEAL) &&
3473
46.2k
                   !frameOk_butConceal),
3474
47.2k
                  self->aacOutDataHeadroom, flags, self->flags[streamIndex]);
3475
3476
47.2k
              self->extGainDelay = self->streamInfo.aacSamplesPerFrame;
3477
47.2k
              break;
3478
0
            default:
3479
0
              ErrorStatus = AAC_DEC_UNKNOWN;
3480
0
              break;
3481
545k
          }
3482
        /* TimeDomainFading */
3483
545k
        if (!CConceal_TDFading_Applied[c]) {
3484
545k
          CConceal_TDFading_Applied[c] = CConcealment_TDFading(
3485
545k
              self->streamInfo.aacSamplesPerFrame,
3486
545k
              &self->pAacDecoderStaticChannelInfo[c], self->aacOutDataHeadroom,
3487
545k
              pTimeData + offset, 0);
3488
545k
          if (c + 1 < (8) && c < aacChannels - 1) {
3489
            /* update next TDNoise Seed to avoid muting in case of Parametric
3490
             * Stereo */
3491
215k
            self->pAacDecoderStaticChannelInfo[c + 1]
3492
215k
                ->concealmentInfo.TDNoiseSeed =
3493
215k
                self->pAacDecoderStaticChannelInfo[c]
3494
215k
                    ->concealmentInfo.TDNoiseSeed;
3495
215k
          }
3496
545k
        }
3497
545k
      }
3498
391k
    }
3499
3500
329k
    if (self->flags[streamIndex] & AC_USAC) {
3501
217k
      int bsPseudoLr = 0;
3502
217k
      mpegSurroundDecoder_IsPseudoLR(
3503
217k
          (CMpegSurroundDecoder *)self->pMpegSurroundDecoder, &bsPseudoLr);
3504
      /* ISO/IEC 23003-3, 7.11.2.6 Modification of core decoder output (pseudo
3505
       * LR) */
3506
217k
      if ((aacChannels == 2) && bsPseudoLr) {
3507
12.3k
        int i, offset2;
3508
12.3k
        const FIXP_SGL invSqrt2 = FL2FXCONST_SGL(0.707106781186547f);
3509
12.3k
        PCM_DEC *pTD = pTimeData;
3510
3511
12.3k
        offset2 = timeDataChannelOffset;
3512
3513
11.5M
        for (i = 0; i < self->streamInfo.aacSamplesPerFrame; i++) {
3514
11.5M
          FIXP_DBL L = PCM_DEC2FIXP_DBL(pTD[0]);
3515
11.5M
          FIXP_DBL R = PCM_DEC2FIXP_DBL(pTD[offset2]);
3516
11.5M
          L = fMult(L, invSqrt2);
3517
11.5M
          R = fMult(R, invSqrt2);
3518
11.5M
          pTD[0] = L + R;
3519
11.5M
          pTD[offset2] = L - R;
3520
11.5M
          pTD++;
3521
11.5M
        }
3522
12.3k
      }
3523
217k
    }
3524
3525
    /* Extract DRC control data and map it to channels (with bitstream delay) */
3526
329k
    mapped = aacDecoder_drcEpilog(
3527
329k
        self->hDrcInfo, bs, self->pAacDecoderStaticChannelInfo,
3528
329k
        pce->ElementInstanceTag, drcChMap, aacChannels);
3529
329k
    if (mapped > 0) {
3530
3.19k
      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
3.19k
        self->flags[streamIndex] |= AC_DRC_PRESENT;
3534
3.19k
      } else {
3535
0
        ErrorStatus = AAC_DEC_UNSUPPORTED_FORMAT;
3536
0
      }
3537
3.19k
    }
3538
329k
    if (self->flags[streamIndex] & (AC_USAC | AC_RSV603DA)) {
3539
217k
      aacDecoder_drcDisable(self->hDrcInfo);
3540
217k
    }
3541
329k
  }
3542
3543
  /* Add additional concealment delay */
3544
0
  self->streamInfo.outputDelay +=
3545
329k
      CConcealment_GetDelay(&self->concealCommonData) *
3546
329k
      self->streamInfo.aacSamplesPerFrame;
3547
3548
  /* Map DRC data to StreamInfo structure */
3549
329k
  aacDecoder_drcGetInfo(self->hDrcInfo, &self->streamInfo.drcPresMode,
3550
329k
                        &self->streamInfo.drcProgRefLev);
3551
3552
  /* Reorder channel type information tables.  */
3553
329k
  if (!(self->flags[0] & AC_RSV603DA)) {
3554
329k
    AUDIO_CHANNEL_TYPE types[(8)];
3555
329k
    UCHAR idx[(8)];
3556
329k
    int c;
3557
329k
    int mapValue;
3558
3559
329k
    FDK_ASSERT(sizeof(self->channelType) == sizeof(types));
3560
329k
    FDK_ASSERT(sizeof(self->channelIndices) == sizeof(idx));
3561
3562
329k
    FDKmemcpy(types, self->channelType, sizeof(types));
3563
329k
    FDKmemcpy(idx, self->channelIndices, sizeof(idx));
3564
3565
874k
    for (c = 0; c < aacChannels; c++) {
3566
545k
      mapValue =
3567
545k
          FDK_chMapDescr_getMapValue(&self->mapDescr, c, self->chMapIndex);
3568
545k
      self->channelType[mapValue] = types[c];
3569
545k
      self->channelIndices[mapValue] = idx[c];
3570
545k
    }
3571
329k
  }
3572
3573
329k
  self->blockNumber++;
3574
3575
329k
  return ErrorStatus;
3576
329k
}
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
}