Coverage Report

Created: 2026-10-28 06:57

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