Coverage Report

Created: 2026-10-17 06:51

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