Coverage Report

Created: 2025-12-31 07:57

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