Coverage Report

Created: 2026-01-16 07:48

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