Coverage Report

Created: 2025-07-18 06:04

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