Imported Debian version 0.1.3.1
[deb_fdk-aac.git] / libAACdec / src / aacdecoder.cpp
1
2 /* -----------------------------------------------------------------------------------------------------------
3 Software License for The Fraunhofer FDK AAC Codec Library for Android
4
5 © Copyright 1995 - 2013 Fraunhofer-Gesellschaft zur Förderung der angewandten Forschung e.V.
6 All rights reserved.
7
8 1. INTRODUCTION
9 The Fraunhofer FDK AAC Codec Library for Android ("FDK AAC Codec") is software that implements
10 the MPEG Advanced Audio Coding ("AAC") encoding and decoding scheme for digital audio.
11 This FDK AAC Codec software is intended to be used on a wide variety of Android devices.
12
13 AAC's HE-AAC and HE-AAC v2 versions are regarded as today's most efficient general perceptual
14 audio codecs. AAC-ELD is considered the best-performing full-bandwidth communications codec by
15 independent studies and is widely deployed. AAC has been standardized by ISO and IEC as part
16 of the MPEG specifications.
17
18 Patent licenses for necessary patent claims for the FDK AAC Codec (including those of Fraunhofer)
19 may be obtained through Via Licensing (www.vialicensing.com) or through the respective patent owners
20 individually for the purpose of encoding or decoding bit streams in products that are compliant with
21 the ISO/IEC MPEG audio standards. Please note that most manufacturers of Android devices already license
22 these patent claims through Via Licensing or directly from the patent owners, and therefore FDK AAC Codec
23 software may already be covered under those patent licenses when it is used for those licensed purposes only.
24
25 Commercially-licensed AAC software libraries, including floating-point versions with enhanced sound quality,
26 are also available from Fraunhofer. Users are encouraged to check the Fraunhofer website for additional
27 applications information and documentation.
28
29 2. COPYRIGHT LICENSE
30
31 Redistribution and use in source and binary forms, with or without modification, are permitted without
32 payment of copyright license fees provided that you satisfy the following conditions:
33
34 You must retain the complete text of this software license in redistributions of the FDK AAC Codec or
35 your modifications thereto in source code form.
36
37 You must retain the complete text of this software license in the documentation and/or other materials
38 provided with redistributions of the FDK AAC Codec or your modifications thereto in binary form.
39 You must make available free of charge copies of the complete source code of the FDK AAC Codec and your
40 modifications thereto to recipients of copies in binary form.
41
42 The name of Fraunhofer may not be used to endorse or promote products derived from this library without
43 prior written permission.
44
45 You may not charge copyright license fees for anyone to use, copy or distribute the FDK AAC Codec
46 software or your modifications thereto.
47
48 Your modified versions of the FDK AAC Codec must carry prominent notices stating that you changed the software
49 and the date of any change. For modified versions of the FDK AAC Codec, the term
50 "Fraunhofer FDK AAC Codec Library for Android" must be replaced by the term
51 "Third-Party Modified Version of the Fraunhofer FDK AAC Codec Library for Android."
52
53 3. NO PATENT LICENSE
54
55 NO EXPRESS OR IMPLIED LICENSES TO ANY PATENT CLAIMS, including without limitation the patents of Fraunhofer,
56 ARE GRANTED BY THIS SOFTWARE LICENSE. Fraunhofer provides no warranty of patent non-infringement with
57 respect to this software.
58
59 You may use this FDK AAC Codec software or modifications thereto only for purposes that are authorized
60 by appropriate patent licenses.
61
62 4. DISCLAIMER
63
64 This FDK AAC Codec software is provided by Fraunhofer on behalf of the copyright holders and contributors
65 "AS IS" and WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, including but not limited to the implied warranties
66 of merchantability and fitness for a particular purpose. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
67 CONTRIBUTORS BE LIABLE for any direct, indirect, incidental, special, exemplary, or consequential damages,
68 including but not limited to procurement of substitute goods or services; loss of use, data, or profits,
69 or business interruption, however caused and on any theory of liability, whether in contract, strict
70 liability, or tort (including negligence), arising in any way out of the use of this software, even if
71 advised of the possibility of such damage.
72
73 5. CONTACT INFORMATION
74
75 Fraunhofer Institute for Integrated Circuits IIS
76 Attention: Audio and Multimedia Departments - FDK AAC LL
77 Am Wolfsmantel 33
78 91058 Erlangen, Germany
79
80 www.iis.fraunhofer.de/amm
81 amm-info@iis.fraunhofer.de
82 ----------------------------------------------------------------------------------------------------------- */
83
84 /***************************** MPEG-4 AAC Decoder **************************
85
86 Author(s): Josef Hoepfl
87 Description:
88
89 ******************************************************************************/
90
91
92 /*!
93 \page default General Overview of the AAC Decoder Implementation
94
95 The main entry point to decode a AAC frame is CAacDecoder_DecodeFrame(). It handles the different
96 transport multiplexes and bitstream formats supported by this implementation. It extracts the
97 AAC_raw_data_blocks from these bitstreams to further process then in the actual decoding stages.
98
99 Note: Click on a function of file in the above image to see details about the function. Also note, that
100 this is just an overview of the most important functions and not a complete call graph.
101
102 <h2>1 Bitstream deformatter</h2>
103 The basic bit stream parser function CChannelElement_Read() is called. It uses other subcalls in order
104 to parse and unpack the bitstreams. Note, that this includes huffmann decoding of the coded spectral data.
105 This operation can be computational significant specifically at higher bitrates. Optimization is likely in
106 CBlock_ReadSpectralData().
107
108 The bitstream deformatter also includes many bitfield operations. Profiling on the target will determine
109 required optimizations.
110
111 <h2>2 Actual decoding to retain the time domain output</h2>
112 The basic bitstream deformatter function CChannelElement_Decode() for CPE elements and SCE elements are called.
113 Except for the stereo processing (2.1) which is only used for CPE elements, the function calls for CPE or SCE
114 are similar, except that CPE always processes to independent channels while SCE only processes one channel.
115
116 Often there is the distinction between long blocks and short blocks. However, computational expensive functions
117 that ususally require optimization are being shared by these two groups,
118
119 <h3>2.1 Stereo processing for CPE elements</h3>
120 CChannelPairElement_Decode() first calles the joint stereo tools in stereo.cpp when required.
121
122 <h3>2.2 Scaling of spectral data</h3>
123 CBlock_ScaleSpectralData().
124
125 <h3>2.3 Apply additional coding tools</h3>
126 ApplyTools() calles the PNS tools in case of MPEG-4 bitstreams, and TNS filtering CTns_Apply() for MPEG-2 and MPEG-4 bitstreams.
127 The function TnsFilterIIR() which is called by CTns_Apply() (2.3.1) might require some optimization.
128
129 <h2>3 Frequency-To-Time conversion</h3>
130 The filterbank is called using CBlock_FrequencyToTime() using the MDCT module from the FDK Tools
131
132 */
133
134
135
136 #include "aacdecoder.h"
137
138 #include "aac_rom.h"
139 #include "aac_ram.h"
140 #include "channel.h"
141 #include "FDK_audio.h"
142
143 #include "FDK_tools_rom.h"
144
145 #include "aacdec_pns.h"
146
147 #include "sbrdecoder.h"
148
149
150
151
152 #include "aacdec_hcr.h"
153 #include "rvlc.h"
154
155
156 #include "tpdec_lib.h"
157
158 #include "conceal.h"
159
160
161
162 #define CAN_DO_PS(aot) \
163 ((aot) == AOT_AAC_LC \
164 || (aot) == AOT_SBR \
165 || (aot) == AOT_PS \
166 || (aot) == AOT_ER_BSAC \
167 || (aot) == AOT_DRM_AAC)
168
169 #define IS_USAC(aot) \
170 ((aot) == AOT_USAC \
171 || (aot) == AOT_RSVD50)
172
173 #define IS_LOWDELAY(aot) \
174 ((aot) == AOT_ER_AAC_LD \
175 || (aot) == AOT_ER_AAC_ELD)
176
177 void CAacDecoder_SyncQmfMode(HANDLE_AACDECODER self)
178 {
179
180 /* Assign user requested mode */
181 self->qmfModeCurr = self->qmfModeUser;
182
183 if ( self->qmfModeCurr == NOT_DEFINED )
184 {
185 if ( (IS_LOWDELAY(self->streamInfo.aot) && (self->flags & AC_MPS_PRESENT))
186 || ( (self->streamInfo.aacNumChannels == 1)
187 && ( (CAN_DO_PS(self->streamInfo.aot) && !(self->flags & AC_MPS_PRESENT))
188 || ( IS_USAC(self->streamInfo.aot) && (self->flags & AC_MPS_PRESENT)) ) ) )
189 {
190 self->qmfModeCurr = MODE_HQ;
191 } else {
192 self->qmfModeCurr = MODE_LP;
193 }
194 }
195
196
197 /* Set SBR to current QMF mode. Error does not matter. */
198 sbrDecoder_SetParam(self->hSbrDecoder, SBR_QMF_MODE, (self->qmfModeCurr == MODE_LP));
199 self->psPossible = ((CAN_DO_PS(self->streamInfo.aot) && self->streamInfo.aacNumChannels == 1 && ! (self->flags & AC_MPS_PRESENT))) && self->qmfModeCurr == MODE_HQ ;
200 FDK_ASSERT( ! ( (self->flags & AC_MPS_PRESENT) && self->psPossible ) );
201 }
202
203 void CAacDecoder_SignalInterruption(HANDLE_AACDECODER self)
204 {
205 }
206
207 /*!
208 \brief Reset ancillary data struct. Call before parsing a new frame.
209
210 \ancData Pointer to ancillary data structure
211
212 \return Error code
213 */
214 static AAC_DECODER_ERROR CAacDecoder_AncDataReset(CAncData *ancData)
215 {
216 int i;
217 for (i=0; i<8; i++)
218 {
219 ancData->offset[i] = 0;
220 }
221 ancData->nrElements = 0;
222
223 return AAC_DEC_OK;
224 }
225
226 /*!
227 \brief Initialize ancillary buffer
228
229 \ancData Pointer to ancillary data structure
230 \buffer Pointer to (external) anc data buffer
231 \size Size of the buffer pointed on by buffer in bytes
232
233 \return Error code
234 */
235 AAC_DECODER_ERROR CAacDecoder_AncDataInit(CAncData *ancData, unsigned char *buffer, int size)
236 {
237 if (size >= 0) {
238 ancData->buffer = buffer;
239 ancData->bufferSize = size;
240
241 CAacDecoder_AncDataReset(ancData);
242
243 return AAC_DEC_OK;
244 }
245
246 return AAC_DEC_ANC_DATA_ERROR;
247 }
248
249 /*!
250 \brief Get one ancillary data element
251
252 \ancData Pointer to ancillary data structure
253 \index Index of the anc data element to get
254 \ptr Pointer to a buffer receiving a pointer to the requested anc data element
255 \size Pointer to a buffer receiving the length of the requested anc data element in bytes
256
257 \return Error code
258 */
259 AAC_DECODER_ERROR CAacDecoder_AncDataGet(CAncData *ancData, int index, unsigned char **ptr, int *size)
260 {
261 AAC_DECODER_ERROR error = AAC_DEC_OK;
262
263 *ptr = NULL;
264 *size = 0;
265
266 if (index >= 0 && index < 8 && index < ancData->nrElements)
267 {
268 *ptr = &ancData->buffer[ancData->offset[index]];
269 *size = ancData->offset[index+1] - ancData->offset[index];
270 }
271
272 return error;
273 }
274
275
276 /*!
277 \brief Parse ancillary data
278
279 \ancData Pointer to ancillary data structure
280 \hBs Handle to FDK bitstream
281 \ancBytes Length of ancillary data to read from the bitstream
282
283 \return Error code
284 */
285 static
286 AAC_DECODER_ERROR CAacDecoder_AncDataParse (
287 CAncData *ancData,
288 HANDLE_FDK_BITSTREAM hBs,
289 const int ancBytes )
290 {
291 AAC_DECODER_ERROR error = AAC_DEC_OK;
292 int readBytes = 0;
293
294 if (ancData->buffer != NULL)
295 {
296 if (ancBytes > 0) {
297 /* write ancillary data to external buffer */
298 int offset = ancData->offset[ancData->nrElements];
299
300 if ((offset + ancBytes) > ancData->bufferSize)
301 {
302 error = AAC_DEC_TOO_SMALL_ANC_BUFFER;
303 }
304 else if (ancData->nrElements >= 8-1)
305 {
306 error = AAC_DEC_TOO_MANY_ANC_ELEMENTS;
307 }
308 else
309 {
310 int i;
311
312 for (i = 0; i < ancBytes; i++) {
313 ancData->buffer[i+offset] = FDKreadBits(hBs, 8);
314 readBytes++;
315 }
316
317 ancData->nrElements++;
318 ancData->offset[ancData->nrElements] = ancBytes + ancData->offset[ancData->nrElements-1];
319 }
320 }
321 }
322
323 readBytes = ancBytes - readBytes;
324
325 if (readBytes > 0) {
326 /* skip data */
327 FDKpushFor(hBs, readBytes<<3);
328 }
329
330 return error;
331 }
332
333 /*!
334 \brief Read Stream Data Element
335
336 \bs Bitstream Handle
337
338 \return Error code
339 */
340 static AAC_DECODER_ERROR CDataStreamElement_Read (
341 HANDLE_FDK_BITSTREAM bs,
342 CAncData *ancData,
343 HANDLE_AAC_DRC hDrcInfo,
344 HANDLE_TRANSPORTDEC pTp,
345 UCHAR *elementInstanceTag,
346 UINT alignmentAnchor )
347 {
348 AAC_DECODER_ERROR error = AAC_DEC_OK;
349 UINT dataStart;
350 int dataByteAlignFlag, count;
351
352 int crcReg = transportDec_CrcStartReg(pTp, 0);
353
354 /* Element Instance Tag */
355 *elementInstanceTag = FDKreadBits(bs,4);
356 /* Data Byte Align Flag */
357 dataByteAlignFlag = FDKreadBits(bs,1);
358
359 count = FDKreadBits(bs,8);
360
361 if (count == 255) {
362 count += FDKreadBits(bs,8); /* EscCount */
363 }
364
365 if (dataByteAlignFlag) {
366 FDKbyteAlign(bs, alignmentAnchor);
367 }
368
369 dataStart = FDKgetValidBits(bs);
370
371 error = CAacDecoder_AncDataParse(ancData, bs, count);
372 transportDec_CrcEndReg(pTp, crcReg);
373
374 {
375 INT readBits, dataBits = count<<3;
376
377 /* Move to the beginning of the data junk */
378 FDKpushBack(bs, dataStart-FDKgetValidBits(bs));
379
380 /* Read Anc data if available */
381 readBits = aacDecoder_drcMarkPayload( hDrcInfo, bs, DVB_DRC_ANC_DATA );
382
383 if (readBits != dataBits) {
384 /* Move to the end again. */
385 FDKpushBiDirectional(bs, FDKgetValidBits(bs)-dataStart+dataBits);
386 }
387 }
388
389 return error;
390 }
391
392 #ifdef TP_PCE_ENABLE
393 /*!
394 \brief Read Program Config Element
395
396 \bs Bitstream Handle
397 \pTp Transport decoder handle for CRC handling
398 \pce Pointer to PCE buffer
399 \channelConfig Current channel configuration
400 \alignAnchor Anchor for byte alignment
401
402 \return PCE status (-1: fail, 0: no new PCE, 1: PCE updated, 2: PCE updated need re-config).
403 */
404 static int CProgramConfigElement_Read (
405 HANDLE_FDK_BITSTREAM bs,
406 HANDLE_TRANSPORTDEC pTp,
407 CProgramConfig *pce,
408 const UINT channelConfig,
409 const UINT alignAnchor )
410 {
411 int pceStatus = 0;
412 int crcReg;
413
414 /* read PCE to temporal buffer first */
415 C_ALLOC_SCRATCH_START(tmpPce, CProgramConfig, 1);
416
417 CProgramConfig_Init(tmpPce);
418 CProgramConfig_Reset(tmpPce);
419
420 crcReg = transportDec_CrcStartReg(pTp, 0);
421
422 CProgramConfig_Read(tmpPce, bs, alignAnchor);
423
424 transportDec_CrcEndReg(pTp, crcReg);
425
426 if ( CProgramConfig_IsValid(tmpPce)
427 && (tmpPce->Profile == 1) )
428 {
429 if ( !pce->isValid && (channelConfig > 0) ) {
430 /* Create a standard channel config PCE to compare with */
431 CProgramConfig_GetDefault( pce, channelConfig );
432 }
433
434 if (pce->isValid) {
435 /* Compare the new and the old PCE (tags ignored) */
436 switch ( CProgramConfig_Compare( pce, tmpPce ) )
437 {
438 case 1: /* Channel configuration not changed. Just new metadata. */
439 FDKmemcpy(pce, tmpPce, sizeof(CProgramConfig)); /* Store the complete PCE */
440 pceStatus = 1; /* New PCE but no change of config */
441 break;
442 case 2: /* The number of channels are identical but not the config */
443 if (channelConfig == 0) {
444 FDKmemcpy(pce, tmpPce, sizeof(CProgramConfig)); /* Store the complete PCE */
445 pceStatus = 2; /* Decoder needs re-configuration */
446 }
447 break;
448 case -1: /* The channel configuration is completely different */
449 pceStatus = -1; /* Not supported! */
450 break;
451 case 0: /* Nothing to do because PCE matches the old one exactly. */
452 default:
453 /* pceStatus = 0; */
454 break;
455 }
456 }
457 }
458
459 C_ALLOC_SCRATCH_END(tmpPce, CProgramConfig, 1);
460
461 return pceStatus;
462 }
463 #endif /* TP_PCE_ENABLE */
464
465 /*!
466 \brief Parse Extension Payload
467
468 \self Handle of AAC decoder
469 \count Pointer to bit counter.
470 \previous_element ID of previous element (required by some extension payloads)
471
472 \return Error code
473 */
474 static
475 AAC_DECODER_ERROR CAacDecoder_ExtPayloadParse (HANDLE_AACDECODER self,
476 HANDLE_FDK_BITSTREAM hBs,
477 int *count,
478 MP4_ELEMENT_ID previous_element,
479 int elIndex,
480 int fIsFillElement)
481 {
482 AAC_DECODER_ERROR error = AAC_DEC_OK;
483 EXT_PAYLOAD_TYPE extension_type;
484 int bytes = (*count) >> 3;
485 int crcFlag = 0;
486
487 if (*count < 4) {
488 return AAC_DEC_PARSE_ERROR;
489 } else if ((INT)FDKgetValidBits(hBs) < *count) {
490 return AAC_DEC_DECODE_FRAME_ERROR;
491 }
492
493 extension_type = (EXT_PAYLOAD_TYPE) FDKreadBits(hBs, 4); /* bs_extension_type */
494 *count -= 4;
495
496 switch (extension_type)
497 {
498 case EXT_DYNAMIC_RANGE:
499 {
500 INT readBits = aacDecoder_drcMarkPayload( self->hDrcInfo, hBs, MPEG_DRC_EXT_DATA );
501
502 if (readBits > *count)
503 { /* Read too much. Something went wrong! */
504 error = AAC_DEC_PARSE_ERROR;
505 }
506 *count -= readBits;
507 }
508 break;
509
510
511 case EXT_SBR_DATA_CRC:
512 crcFlag = 1;
513 case EXT_SBR_DATA:
514 if (IS_CHANNEL_ELEMENT(previous_element)) {
515 SBR_ERROR sbrError;
516
517 CAacDecoder_SyncQmfMode(self);
518
519 sbrError = sbrDecoder_InitElement(
520 self->hSbrDecoder,
521 self->streamInfo.aacSampleRate,
522 self->streamInfo.extSamplingRate,
523 self->streamInfo.aacSamplesPerFrame,
524 self->streamInfo.aot,
525 previous_element,
526 elIndex
527 );
528
529 if (sbrError == SBRDEC_OK) {
530 sbrError = sbrDecoder_Parse (
531 self->hSbrDecoder,
532 hBs,
533 count,
534 *count,
535 crcFlag,
536 previous_element,
537 elIndex,
538 self->flags & AC_INDEP );
539 /* Enable SBR for implicit SBR signalling. */
540 if (sbrError == SBRDEC_OK) {
541 self->sbrEnabled = 1;
542 }
543 } else {
544 /* Do not try to apply SBR because initializing the element failed. */
545 self->sbrEnabled = 0;
546 }
547 /* Citation from ISO/IEC 14496-3 chapter 4.5.2.1.5.2
548 Fill elements containing an extension_payload() with an extension_type of EXT_SBR_DATA
549 or EXT_SBR_DATA_CRC shall not contain any other extension_payload of any other extension_type.
550 */
551 if (fIsFillElement) {
552 FDKpushBiDirectional(hBs, *count);
553 *count = 0;
554 } else {
555 /* If this is not a fill element with a known length, we are screwed an no further parsing makes sense. */
556 if (sbrError != SBRDEC_OK) {
557 self->frameOK = 0;
558 }
559 }
560 } else {
561 error = AAC_DEC_PARSE_ERROR;
562 }
563 break;
564
565 case EXT_FILL_DATA:
566 {
567 int temp;
568
569 temp = FDKreadBits(hBs,4);
570 bytes--;
571 if (temp != 0) {
572 error = AAC_DEC_PARSE_ERROR;
573 break;
574 }
575 while (bytes > 0) {
576 temp = FDKreadBits(hBs,8);
577 bytes--;
578 if (temp != 0xa5) {
579 error = AAC_DEC_PARSE_ERROR;
580 break;
581 }
582 }
583 *count = bytes<<3;
584 }
585 break;
586
587 case EXT_DATA_ELEMENT:
588 {
589 int dataElementVersion;
590
591 dataElementVersion = FDKreadBits(hBs,4);
592 *count -= 4;
593 if (dataElementVersion == 0) /* ANC_DATA */
594 {
595 int temp, dataElementLength = 0;
596 do {
597 temp = FDKreadBits(hBs,8);
598 *count -= 8;
599 dataElementLength += temp;
600 } while (temp == 255 );
601
602 CAacDecoder_AncDataParse(&self->ancData, hBs, dataElementLength);
603 *count -= (dataElementLength<<3);
604 } else {
605 /* align = 0 */
606 error = AAC_DEC_PARSE_ERROR;
607 goto bail;
608 }
609 }
610 break;
611
612 case EXT_DATA_LENGTH:
613 if ( !fIsFillElement /* Makes no sens to have an additional length in a fill ... */
614 && (self->flags & AC_ER) ) /* ... element because this extension payload type was ... */
615 { /* ... created to circumvent the missing length in ER-Syntax. */
616 int bitCnt, len = FDKreadBits(hBs, 4);
617 *count -= 4;
618
619 if (len == 15) {
620 int add_len = FDKreadBits(hBs, 8);
621 *count -= 8;
622 len += add_len;
623
624 if (add_len == 255) {
625 len += FDKreadBits(hBs, 16);
626 *count -= 16;
627 }
628 }
629 len <<= 3;
630 bitCnt = len;
631
632 if ( (EXT_PAYLOAD_TYPE)FDKreadBits(hBs, 4) == EXT_DATA_LENGTH ) {
633 /* Check NOTE 2: The extension_payload() included here must
634 not have extension_type == EXT_DATA_LENGTH. */
635 error = AAC_DEC_PARSE_ERROR;
636 } else {
637 /* rewind and call myself again. */
638 FDKpushBack(hBs, 4);
639
640 error =
641 CAacDecoder_ExtPayloadParse (
642 self,
643 hBs,
644 &bitCnt,
645 previous_element,
646 elIndex,
647 0 );
648
649 *count -= len - bitCnt;
650 }
651 /* Note: the fall through in case the if statement above is not taken is intentional. */
652 break;
653 }
654
655 case EXT_FIL:
656
657 default:
658 /* align = 4 */
659 FDKpushFor(hBs, *count);
660 *count = 0;
661 break;
662 }
663
664 bail:
665 if ( (error != AAC_DEC_OK)
666 && fIsFillElement )
667 { /* Skip the remaining extension bytes */
668 FDKpushBiDirectional(hBs, *count);
669 *count = 0;
670 /* Patch error code because decoding can go on. */
671 error = AAC_DEC_OK;
672 /* Be sure that parsing errors have been stored. */
673 }
674 return error;
675 }
676
677 /* Stream Configuration and Information.
678
679 This class holds configuration and information data for a stream to be decoded. It
680 provides the calling application as well as the decoder with substantial information,
681 e.g. profile, sampling rate, number of channels found in the bitstream etc.
682 */
683 static
684 void CStreamInfoInit(CStreamInfo *pStreamInfo)
685 {
686 pStreamInfo->aacSampleRate = 0;
687 pStreamInfo->profile = -1;
688 pStreamInfo->aot = AOT_NONE;
689
690 pStreamInfo->channelConfig = -1;
691 pStreamInfo->bitRate = 0;
692 pStreamInfo->aacSamplesPerFrame = 0;
693
694 pStreamInfo->extAot = AOT_NONE;
695 pStreamInfo->extSamplingRate = 0;
696
697 pStreamInfo->flags = 0;
698
699 pStreamInfo->epConfig = -1; /* default is no ER */
700
701 pStreamInfo->numChannels = 0;
702 pStreamInfo->sampleRate = 0;
703 pStreamInfo->frameSize = 0;
704 }
705
706 /*!
707 \brief Initialization of AacDecoderChannelInfo
708
709 The function initializes the pointers to AacDecoderChannelInfo for each channel,
710 set the start values for window shape and window sequence of overlap&add to zero,
711 set the overlap buffer to zero and initializes the pointers to the window coefficients.
712 \param bsFormat is the format of the AAC bitstream
713
714 \return AACDECODER instance
715 */
716 LINKSPEC_CPP HANDLE_AACDECODER CAacDecoder_Open(TRANSPORT_TYPE bsFormat) /*!< bitstream format (adif,adts,loas,...). */
717 {
718 HANDLE_AACDECODER self;
719
720 self = GetAacDecoder();
721 if (self == NULL) {
722 goto bail;
723 }
724
725 /* Assign channel mapping info arrays (doing so removes dependency of settings header in API header). */
726 self->streamInfo.pChannelIndices = self->channelIndices;
727 self->streamInfo.pChannelType = self->channelType;
728
729 /* set default output mode */
730 self->outputInterleaved = 1; /* interleaved */
731
732 /* initialize anc data */
733 CAacDecoder_AncDataInit(&self->ancData, NULL, 0);
734
735 /* initialize stream info */
736 CStreamInfoInit(&self->streamInfo);
737
738 /* initialize error concealment common data */
739 CConcealment_InitCommonData(&self->concealCommonData);
740
741 self->hDrcInfo = GetDrcInfo();
742 if (self->hDrcInfo == NULL) {
743 goto bail;
744 }
745 /* Init common DRC structure */
746 aacDecoder_drcInit( self->hDrcInfo );
747 /* Set default frame delay */
748 aacDecoder_drcSetParam (
749 self->hDrcInfo,
750 DRC_BS_DELAY,
751 CConcealment_GetDelay(&self->concealCommonData)
752 );
753
754
755 self->aacCommonData.workBufferCore1 = GetWorkBufferCore1();
756 self->aacCommonData.workBufferCore2 = GetWorkBufferCore2();
757 if (self->aacCommonData.workBufferCore1 == NULL
758 ||self->aacCommonData.workBufferCore2 == NULL )
759 goto bail;
760
761 return self;
762
763 bail:
764 CAacDecoder_Close( self );
765
766 return NULL;
767 }
768
769 /* Destroy aac decoder */
770 LINKSPEC_CPP void CAacDecoder_Close(HANDLE_AACDECODER self)
771 {
772 int ch;
773
774 if (self == NULL)
775 return;
776
777 for (ch=0; ch<(6); ch++) {
778 if (self->pAacDecoderStaticChannelInfo[ch] != NULL) {
779 if (self->pAacDecoderStaticChannelInfo[ch]->pOverlapBuffer != NULL) {
780 FreeOverlapBuffer (&self->pAacDecoderStaticChannelInfo[ch]->pOverlapBuffer);
781 }
782 if (self->pAacDecoderStaticChannelInfo[ch] != NULL) {
783 FreeAacDecoderStaticChannelInfo (&self->pAacDecoderStaticChannelInfo[ch]);
784 }
785 }
786 if (self->pAacDecoderChannelInfo[ch] != NULL) {
787 FreeAacDecoderChannelInfo (&self->pAacDecoderChannelInfo[ch]);
788 }
789 }
790
791 self->aacChannels = 0;
792
793 if (self->hDrcInfo) {
794 FreeDrcInfo(&self->hDrcInfo);
795 }
796
797 if (self->aacCommonData.workBufferCore1 != NULL) {
798 FreeWorkBufferCore1 (&self->aacCommonData.workBufferCore1);
799 }
800 if (self->aacCommonData.workBufferCore2 != NULL) {
801 FreeWorkBufferCore2 (&self->aacCommonData.workBufferCore2);
802 }
803
804 FreeAacDecoder ( &self);
805 }
806
807
808 /*!
809 \brief Initialization of decoder instance
810
811 The function initializes the decoder.
812
813 \return error status: 0 for success, <>0 for unsupported configurations
814 */
815 LINKSPEC_CPP AAC_DECODER_ERROR CAacDecoder_Init(HANDLE_AACDECODER self, const CSAudioSpecificConfig *asc)
816 {
817 AAC_DECODER_ERROR err = AAC_DEC_OK;
818 INT ascChannels, ch, ascChanged = 0;
819
820 if (!self)
821 return AAC_DEC_INVALID_HANDLE;
822
823 // set profile and check for supported aot
824 // leave profile on default (=-1) for all other supported MPEG-4 aot's except aot=2 (=AAC-LC)
825 switch (asc->m_aot) {
826 case AOT_AAC_LC:
827 self->streamInfo.profile = 1;
828 break;
829
830 case AOT_SBR:
831 case AOT_PS:
832 case AOT_ER_AAC_LD:
833 case AOT_ER_AAC_ELD:
834 break;
835
836 default:
837 return AAC_DEC_UNSUPPORTED_AOT;
838 }
839
840 CProgramConfig_Init(&self->pce);
841
842 /* set channels */
843 switch (asc->m_channelConfiguration) {
844 case 0:
845 #ifdef TP_PCE_ENABLE
846 /* get channels from program config (ASC) */
847 if (CProgramConfig_IsValid(&asc->m_progrConfigElement)) {
848 ascChannels = asc->m_progrConfigElement.NumChannels;
849 if (ascChannels > 0) {
850 int el;
851 /* valid number of channels -> copy program config element (PCE) from ASC */
852 FDKmemcpy(&self->pce, &asc->m_progrConfigElement, sizeof(CProgramConfig));
853 /* Built element table */
854 el = CProgramConfig_GetElementTable(&asc->m_progrConfigElement, self->elements, 7);
855 for (; el<7; el++) {
856 self->elements[el] = ID_NONE;
857 }
858 } else {
859 return AAC_DEC_UNSUPPORTED_CHANNELCONFIG;
860 }
861 } else {
862 if (transportDec_GetFormat(self->hInput) == TT_MP4_ADTS) {
863 /* set default max_channels for memory allocation because in implicit channel mapping mode
864 we don't know the actual number of channels until we processed at least one raw_data_block(). */
865 ascChannels = (6);
866 } else {
867 return AAC_DEC_UNSUPPORTED_CHANNELCONFIG;
868 }
869 }
870 #else /* TP_PCE_ENABLE */
871 return AAC_DEC_UNSUPPORTED_CHANNELCONFIG;
872 #endif /* TP_PCE_ENABLE */
873 break;
874 case 1: case 2: case 3: case 4: case 5: case 6:
875 ascChannels = asc->m_channelConfiguration;
876 break;
877 case 7:
878 ascChannels = 8;
879 break;
880 default:
881 return AAC_DEC_UNSUPPORTED_CHANNELCONFIG;
882 }
883
884 /* Initialize constant mappings for channel config 1-7 */
885 if (asc->m_channelConfiguration > 0) {
886 int el;
887 FDKmemcpy(self->elements, elementsTab[asc->m_channelConfiguration-1], sizeof(MP4_ELEMENT_ID)*FDKmin(7,7));
888 for (el=7; el<7; el++) {
889 self->elements[el] = ID_NONE;
890 }
891 for (ch=0; ch<ascChannels; ch++) {
892 self->chMapping[ch] = ch;
893 }
894 for (; ch<(6); ch++) {
895 self->chMapping[ch] = 255;
896 }
897 }
898 #ifdef TP_PCE_ENABLE
899 else {
900 if (CProgramConfig_IsValid(&asc->m_progrConfigElement)) {
901 /* Set matrix mixdown infos if available from PCE. */
902 pcmDmx_SetMatrixMixdownFromPce ( self->hPcmUtils,
903 asc->m_progrConfigElement.MatrixMixdownIndexPresent,
904 asc->m_progrConfigElement.MatrixMixdownIndex,
905 asc->m_progrConfigElement.PseudoSurroundEnable );
906 }
907 }
908 #endif
909
910 self->streamInfo.channelConfig = asc->m_channelConfiguration;
911
912 if (ascChannels > (6)) {
913 return AAC_DEC_UNSUPPORTED_CHANNELCONFIG;
914 }
915 if (self->streamInfo.aot != asc->m_aot) {
916 self->streamInfo.aot = asc->m_aot;
917 ascChanged = 1;
918 }
919
920 if (self->streamInfo.aacSamplesPerFrame != (INT)asc->m_samplesPerFrame) {
921 self->streamInfo.aacSamplesPerFrame = asc->m_samplesPerFrame;
922 ascChanged = 1;
923 }
924
925 self->streamInfo.bitRate = 0;
926
927 /* Set syntax flags */
928 self->flags = 0;
929
930 self->streamInfo.extAot = asc->m_extensionAudioObjectType;
931 self->streamInfo.extSamplingRate = asc->m_extensionSamplingFrequency;
932 self->flags |= (asc->m_sbrPresentFlag) ? AC_SBR_PRESENT : 0;
933 self->flags |= (asc->m_psPresentFlag) ? AC_PS_PRESENT : 0;
934 self->sbrEnabled = 0;
935
936 /* --------- vcb11 ------------ */
937 self->flags |= (asc->m_vcb11Flag) ? AC_ER_VCB11 : 0;
938
939 /* ---------- rvlc ------------ */
940 self->flags |= (asc->m_rvlcFlag) ? AC_ER_RVLC : 0;
941
942 /* ----------- hcr ------------ */
943 self->flags |= (asc->m_hcrFlag) ? AC_ER_HCR : 0;
944
945 if (asc->m_aot == AOT_ER_AAC_ELD) {
946 self->flags |= AC_ELD;
947 self->flags |= (asc->m_sc.m_eldSpecificConfig.m_sbrCrcFlag) ? AC_SBRCRC : 0;
948 self->flags |= (asc->m_sc.m_eldSpecificConfig.m_useLdQmfTimeAlign) ? AC_LD_MPS : 0;
949 }
950 self->flags |= (asc->m_aot == AOT_ER_AAC_LD) ? AC_LD : 0;
951 self->flags |= (asc->m_epConfig >= 0) ? AC_ER : 0;
952
953
954 if (asc->m_sbrPresentFlag) {
955 self->sbrEnabled = 1;
956 self->sbrEnabledPrev = 1;
957 }
958 if (asc->m_psPresentFlag) {
959 self->flags |= AC_PS_PRESENT;
960 }
961
962 if ( (asc->m_epConfig >= 0)
963 && (asc->m_channelConfiguration <= 0) ) {
964 /* we have to know the number of channels otherwise no decoding is possible */
965 return AAC_DEC_UNSUPPORTED_ER_FORMAT;
966 }
967
968 self->streamInfo.epConfig = asc->m_epConfig;
969 /* self->hInput->asc.m_epConfig = asc->m_epConfig; */
970
971 if (asc->m_epConfig > 1)
972 return AAC_DEC_UNSUPPORTED_ER_FORMAT;
973
974 /* Check if samplerate changed. */
975 if (self->streamInfo.aacSampleRate != (INT)asc->m_samplingFrequency) {
976 AAC_DECODER_ERROR error;
977
978 ascChanged = 1;
979
980 /* Update samplerate info. */
981 error = getSamplingRateInfo(&self->samplingRateInfo, asc->m_samplesPerFrame, asc->m_samplingFrequencyIndex, asc->m_samplingFrequency);
982 if (error != AAC_DEC_OK) {
983 return error;
984 }
985 self->streamInfo.aacSampleRate = self->samplingRateInfo.samplingRate;
986 }
987
988 /* Check if amount of channels has changed. */
989 if (self->ascChannels != ascChannels)
990 {
991 ascChanged = 1;
992
993 /* Allocate all memory structures for each channel */
994 {
995 for (ch = 0; ch < ascChannels; ch++) {
996 CAacDecoderDynamicData *aacDecoderDynamicData = &self->aacCommonData.workBufferCore1->pAacDecoderDynamicData[ch%2];
997
998 /* initialize pointer to CAacDecoderChannelInfo */
999 if (self->pAacDecoderChannelInfo[ch] == NULL) {
1000 self->pAacDecoderChannelInfo[ch] = GetAacDecoderChannelInfo(ch);
1001 /* This is temporary until the DynamicData is split into two or more regions!
1002 The memory could be reused after completed core decoding. */
1003 if (self->pAacDecoderChannelInfo[ch] == NULL) {
1004 goto bail;
1005 }
1006 /* Hook shared work memory into channel data structure */
1007 self->pAacDecoderChannelInfo[ch]->pDynData = aacDecoderDynamicData;
1008 self->pAacDecoderChannelInfo[ch]->pComData = &self->aacCommonData;
1009 }
1010
1011 /* Allocate persistent channel memory */
1012 if (self->pAacDecoderStaticChannelInfo[ch] == NULL) {
1013 self->pAacDecoderStaticChannelInfo[ch] = GetAacDecoderStaticChannelInfo(ch);
1014 if (self->pAacDecoderStaticChannelInfo[ch] == NULL) {
1015 goto bail;
1016 }
1017 self->pAacDecoderStaticChannelInfo[ch]->pOverlapBuffer = GetOverlapBuffer(ch); /* This area size depends on the AOT */
1018 if (self->pAacDecoderStaticChannelInfo[ch]->pOverlapBuffer == NULL) {
1019 goto bail;
1020 }
1021 self->pAacDecoderChannelInfo[ch]->pSpectralCoefficient = (SPECTRAL_PTR) &self->aacCommonData.workBufferCore2[ch*1024];
1022
1023 }
1024 CPns_InitPns(&self->pAacDecoderChannelInfo[ch]->data.aac.PnsData, &self->aacCommonData.pnsInterChannelData, &self->aacCommonData.pnsCurrentSeed, self->aacCommonData.pnsRandomSeed);
1025 }
1026
1027 if (ascChannels > self->aacChannels)
1028 {
1029 /* Make allocated channel count persistent in decoder context. */
1030 self->aacChannels = ascChannels;
1031 }
1032
1033 HcrInitRom(&self->aacCommonData.overlay.aac.erHcrInfo);
1034 setHcrType(&self->aacCommonData.overlay.aac.erHcrInfo, ID_SCE);
1035 }
1036
1037 /* Make amount of signalled channels persistent in decoder context. */
1038 self->ascChannels = ascChannels;
1039 }
1040
1041 /* Update structures */
1042 if (ascChanged) {
1043
1044 /* Things to be done for each channel, which do not involve allocating memory.
1045 Doing these things only on the channels needed for the current configuration
1046 (ascChannels) could lead to memory access violation later (error concealment). */
1047 for (ch = 0; ch < self->aacChannels; ch++) {
1048 switch (self->streamInfo.aot) {
1049 case AOT_ER_AAC_ELD:
1050 case AOT_ER_AAC_LD:
1051 self->pAacDecoderChannelInfo[ch]->granuleLength = self->streamInfo.aacSamplesPerFrame;
1052 break;
1053 default:
1054 self->pAacDecoderChannelInfo[ch]->granuleLength = self->streamInfo.aacSamplesPerFrame / 8;
1055 break;
1056 }
1057 mdct_init( &self->pAacDecoderStaticChannelInfo[ch]->IMdct,
1058 self->pAacDecoderStaticChannelInfo[ch]->pOverlapBuffer,
1059 OverlapBufferSize );
1060
1061
1062 /* Reset DRC control data for this channel */
1063 aacDecoder_drcInitChannelData ( &self->pAacDecoderStaticChannelInfo[ch]->drcData );
1064
1065 /* Reset concealment only if ASC changed. Otherwise it will be done with any config callback.
1066 E.g. every time the LATM SMC is present. */
1067 CConcealment_InitChannelData(&self->pAacDecoderStaticChannelInfo[ch]->concealmentInfo,
1068 &self->concealCommonData,
1069 self->streamInfo.aacSamplesPerFrame );
1070 }
1071 }
1072
1073 /* Update externally visible copy of flags */
1074 self->streamInfo.flags = self->flags;
1075
1076 return err;
1077
1078 bail:
1079 aacDecoder_Close( self );
1080 return AAC_DEC_OUT_OF_MEMORY;
1081 }
1082
1083
1084 LINKSPEC_CPP AAC_DECODER_ERROR CAacDecoder_DecodeFrame(
1085 HANDLE_AACDECODER self,
1086 const UINT flags,
1087 INT_PCM *pTimeData,
1088 const INT timeDataSize,
1089 const INT interleaved
1090 )
1091 {
1092 AAC_DECODER_ERROR ErrorStatus = AAC_DEC_OK;
1093
1094 CProgramConfig *pce;
1095 HANDLE_FDK_BITSTREAM bs = transportDec_GetBitstream(self->hInput, 0);
1096
1097 MP4_ELEMENT_ID type = ID_NONE; /* Current element type */
1098 INT aacChannels=0; /* Channel counter for channels found in the bitstream */
1099
1100 INT auStartAnchor = (INT)FDKgetValidBits(bs); /* AU start bit buffer position for AU byte alignment */
1101
1102 self->frameOK = 1;
1103
1104 /* Any supported base layer valid AU will require more than 16 bits. */
1105 if ( (transportDec_GetAuBitsRemaining(self->hInput, 0) < 15) && (flags & (AACDEC_CONCEAL|AACDEC_FLUSH)) == 0) {
1106 self->frameOK = 0;
1107 ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
1108 }
1109
1110
1111 /* Reset Program Config structure */
1112 pce = &self->pce;
1113 CProgramConfig_Reset(pce);
1114
1115 CAacDecoder_AncDataReset(&self->ancData);
1116
1117 {
1118 int ch;
1119
1120 if (self->streamInfo.channelConfig == 0) {
1121 /* Init Channel/Element mapping table */
1122 for (ch=0; ch<(6); ch++) {
1123 self->chMapping[ch] = 255;
1124 }
1125 if (!CProgramConfig_IsValid(pce)) {
1126 int el;
1127 for (el=0; el<7; el++) {
1128 self->elements[el] = ID_NONE;
1129 }
1130 }
1131 }
1132 }
1133
1134 /* Check sampling frequency */
1135 switch ( self->streamInfo.aacSampleRate ) {
1136 case 16000:
1137 case 12000:
1138 case 11025:
1139 case 8000:
1140 case 7350:
1141 case 48000:
1142 case 44100:
1143 case 32000:
1144 case 24000:
1145 case 22050:
1146 break;
1147 default:
1148 if ( ! (self->flags & (AC_USAC|AC_RSVD50)) ) {
1149 return AAC_DEC_UNSUPPORTED_SAMPLINGRATE;
1150 }
1151 break;
1152 }
1153
1154
1155 if ( flags & AACDEC_CLRHIST )
1156 {
1157 int ch;
1158 /* Clear history */
1159 for (ch = 0; ch < self->aacChannels; ch++) {
1160 /* Reset concealment */
1161 CConcealment_InitChannelData(&self->pAacDecoderStaticChannelInfo[ch]->concealmentInfo,
1162 &self->concealCommonData,
1163 self->streamInfo.aacSamplesPerFrame );
1164 /* Clear concealment buffers to get rid of the complete history */
1165 FDKmemclear(self->pAacDecoderStaticChannelInfo[ch]->concealmentInfo.spectralCoefficient, 1024 * sizeof(FIXP_CNCL));
1166 FDKmemclear(self->pAacDecoderStaticChannelInfo[ch]->concealmentInfo.specScale, 8 * sizeof(SHORT));
1167 /* Clear overlap-add buffers to avoid clicks. */
1168 FDKmemclear(self->pAacDecoderStaticChannelInfo[ch]->IMdct.overlap.freq, OverlapBufferSize*sizeof(FIXP_DBL));
1169 }
1170 }
1171
1172
1173
1174 #ifdef TP_PCE_ENABLE
1175 int pceRead = 0; /* Flag indicating a PCE in the current raw_data_block() */
1176 #endif
1177
1178
1179 INT hdaacDecoded = 0;
1180 MP4_ELEMENT_ID previous_element = ID_END; /* Last element ID (required for extension payload mapping */
1181 UCHAR previous_element_index = 0; /* Canonical index of last element */
1182 int element_count = 0; /* Element counter for elements found in the bitstream */
1183 int el_cnt[ID_LAST] = { 0 }; /* element counter ( robustness ) */
1184
1185 while ( (type != ID_END) && (! (flags & (AACDEC_CONCEAL | AACDEC_FLUSH))) && self->frameOK )
1186 {
1187 int el_channels;
1188
1189 if (! (self->flags & (AC_USAC|AC_RSVD50|AC_ELD|AC_SCALABLE|AC_ER)))
1190 type = (MP4_ELEMENT_ID) FDKreadBits(bs,3);
1191 else
1192 type = self->elements[element_count];
1193
1194 setHcrType(&self->aacCommonData.overlay.aac.erHcrInfo, type);
1195
1196
1197 if ((INT)FDKgetValidBits(bs) < 0)
1198 self->frameOK = 0;
1199
1200 switch (type)
1201 {
1202 case ID_SCE:
1203 case ID_CPE:
1204 case ID_LFE:
1205 /*
1206 Consistency check
1207 */
1208
1209 if (type == ID_CPE) {
1210 el_channels = 2;
1211 } else {
1212 el_channels = 1;
1213 }
1214
1215 if ( (el_cnt[type] >= (self->ascChannels>>(el_channels-1))) || (aacChannels > (self->ascChannels-el_channels)) ) {
1216 ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
1217 self->frameOK = 0;
1218 break;
1219 }
1220
1221 if ( !(self->flags & (AC_USAC|AC_RSVD50)) ) {
1222 int ch;
1223 for (ch=0; ch < el_channels; ch+=1) {
1224 CPns_ResetData(&self->pAacDecoderChannelInfo[aacChannels+ch]->data.aac.PnsData,
1225 &self->pAacDecoderChannelInfo[aacChannels+ch]->pComData->pnsInterChannelData);
1226 }
1227 }
1228
1229 if(self->frameOK) {
1230 ErrorStatus = CChannelElement_Read( bs,
1231 &self->pAacDecoderChannelInfo[aacChannels],
1232 &self->pAacDecoderStaticChannelInfo[aacChannels],
1233 self->streamInfo.aot,
1234 &self->samplingRateInfo,
1235 self->flags,
1236 self->streamInfo.aacSamplesPerFrame,
1237 el_channels,
1238 self->streamInfo.epConfig,
1239 self->hInput
1240 );
1241 if (ErrorStatus) {
1242 self->frameOK = 0;
1243 }
1244 }
1245
1246
1247 if ( self->frameOK) {
1248 /* Lookup the element and decode it only if it belongs to the current program */
1249 if ( CProgramConfig_LookupElement(
1250 pce,
1251 self->streamInfo.channelConfig,
1252 self->pAacDecoderChannelInfo[aacChannels]->ElementInstanceTag,
1253 aacChannels,
1254 self->chMapping,
1255 self->channelType,
1256 self->channelIndices,
1257 &previous_element_index,
1258 self->elements,
1259 type) )
1260 {
1261 if ( !hdaacDecoded ) {
1262 CChannelElement_Decode(
1263 &self->pAacDecoderChannelInfo[aacChannels],
1264 &self->pAacDecoderStaticChannelInfo[aacChannels],
1265 &self->samplingRateInfo,
1266 self->flags,
1267 el_channels
1268 );
1269 }
1270 aacChannels += 1;
1271 if (type == ID_CPE) {
1272 aacChannels += 1;
1273 }
1274 }
1275 else {
1276 self->frameOK = 0;
1277 }
1278 /* Create SBR element for SBR for upsampling for LFE elements,
1279 and if SBR was explicitly signaled, because the first frame(s)
1280 may not contain SBR payload (broken encoder, bit errors). */
1281 if ( (self->flags & AC_SBR_PRESENT) || (self->sbrEnabled == 1) )
1282 {
1283 SBR_ERROR sbrError;
1284
1285 sbrError = sbrDecoder_InitElement(
1286 self->hSbrDecoder,
1287 self->streamInfo.aacSampleRate,
1288 self->streamInfo.extSamplingRate,
1289 self->streamInfo.aacSamplesPerFrame,
1290 self->streamInfo.aot,
1291 type,
1292 previous_element_index
1293 );
1294 if (sbrError != SBRDEC_OK) {
1295 /* Do not try to apply SBR because initializing the element failed. */
1296 self->sbrEnabled = 0;
1297 }
1298 }
1299 }
1300
1301 el_cnt[type]++;
1302 break;
1303
1304 case ID_CCE:
1305 /*
1306 Consistency check
1307 */
1308 if ( el_cnt[type] > self->ascChannels ) {
1309 ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
1310 self->frameOK = 0;
1311 break;
1312 }
1313
1314 if (self->frameOK)
1315 {
1316 /* memory for spectral lines temporal on scratch */
1317 C_ALLOC_SCRATCH_START(mdctSpec, FIXP_DBL, 1024);
1318
1319 /* create dummy channel for CCE parsing on stack */
1320 CAacDecoderChannelInfo tmpAacDecoderChannelInfo, *pTmpAacDecoderChannelInfo;
1321
1322 FDKmemclear(mdctSpec, 1024*sizeof(FIXP_DBL));
1323
1324 tmpAacDecoderChannelInfo.pDynData = self->aacCommonData.workBufferCore1->pAacDecoderDynamicData;
1325 tmpAacDecoderChannelInfo.pComData = &self->aacCommonData;
1326 tmpAacDecoderChannelInfo.pSpectralCoefficient = (SPECTRAL_PTR)mdctSpec;
1327 /* Assume AAC-LC */
1328 tmpAacDecoderChannelInfo.granuleLength = self->streamInfo.aacSamplesPerFrame / 8;
1329
1330 /* Reset PNS data. */
1331 CPns_ResetData(&tmpAacDecoderChannelInfo.data.aac.PnsData, &tmpAacDecoderChannelInfo.pComData->pnsInterChannelData);
1332
1333 pTmpAacDecoderChannelInfo = &tmpAacDecoderChannelInfo;
1334 /* do CCE parsing */
1335 ErrorStatus = CChannelElement_Read( bs,
1336 &pTmpAacDecoderChannelInfo,
1337 NULL,
1338 self->streamInfo.aot,
1339 &self->samplingRateInfo,
1340 self->flags,
1341 self->streamInfo.aacSamplesPerFrame,
1342 1,
1343 self->streamInfo.epConfig,
1344 self->hInput
1345 );
1346
1347 C_ALLOC_SCRATCH_END(mdctSpec, FIXP_DBL, 1024);
1348
1349 if (ErrorStatus) {
1350 self->frameOK = 0;
1351 }
1352
1353 if (self->frameOK) {
1354 /* Lookup the element and decode it only if it belongs to the current program */
1355 if (CProgramConfig_LookupElement(
1356 pce,
1357 self->streamInfo.channelConfig,
1358 pTmpAacDecoderChannelInfo->ElementInstanceTag,
1359 0,
1360 self->chMapping,
1361 self->channelType,
1362 self->channelIndices,
1363 &previous_element_index,
1364 self->elements,
1365 type) )
1366 {
1367 /* decoding of CCE not supported */
1368 }
1369 else {
1370 self->frameOK = 0;
1371 }
1372 }
1373 }
1374 el_cnt[type]++;
1375 break;
1376
1377 case ID_DSE:
1378 {
1379 UCHAR element_instance_tag;
1380
1381 CDataStreamElement_Read( bs,
1382 &self->ancData,
1383 self->hDrcInfo,
1384 self->hInput,
1385 &element_instance_tag,
1386 auStartAnchor );
1387
1388 if (!CProgramConfig_LookupElement(
1389 pce,
1390 self->streamInfo.channelConfig,
1391 element_instance_tag,
1392 0,
1393 self->chMapping,
1394 self->channelType,
1395 self->channelIndices,
1396 &previous_element_index,
1397 self->elements,
1398 type) )
1399 {
1400 /* most likely an error in bitstream occured */
1401 //self->frameOK = 0;
1402 }
1403 }
1404
1405 {
1406 UCHAR *pDvbAncData = NULL;
1407 AAC_DECODER_ERROR ancErr;
1408 int ancIndex;
1409 int dvbAncDataSize = 0;
1410
1411 /* Ask how many anc data elements are in buffer */
1412 ancIndex = self->ancData.nrElements - 1;
1413 /* Get the last one (if available) */
1414 ancErr = CAacDecoder_AncDataGet( &self->ancData,
1415 ancIndex,
1416 &pDvbAncData,
1417 &dvbAncDataSize );
1418
1419 if (ancErr == AAC_DEC_OK) {
1420 pcmDmx_ReadDvbAncData (
1421 self->hPcmUtils,
1422 pDvbAncData,
1423 dvbAncDataSize,
1424 0 /* not mpeg2 */ );
1425 }
1426 }
1427 break;
1428
1429 #ifdef TP_PCE_ENABLE
1430 case ID_PCE:
1431 {
1432 int result = CProgramConfigElement_Read(
1433 bs,
1434 self->hInput,
1435 pce,
1436 self->streamInfo.channelConfig,
1437 auStartAnchor );
1438 if ( result < 0 ) {
1439 /* Something went wrong */
1440 ErrorStatus = AAC_DEC_PARSE_ERROR;
1441 self->frameOK = 0;
1442 }
1443 else if ( result > 1 ) {
1444 /* Built element table */
1445 int elIdx = CProgramConfig_GetElementTable(pce, self->elements, 7);
1446 /* Reset the remaining tabs */
1447 for ( ; elIdx<7; elIdx++) {
1448 self->elements[elIdx] = ID_NONE;
1449 }
1450 /* Make new number of channel persistant */
1451 self->ascChannels = pce->NumChannels;
1452 /* If PCE is not first element conceal this frame to avoid inconsistencies */
1453 if ( element_count != 0 ) {
1454 self->frameOK = 0;
1455 }
1456 }
1457 pceRead = (result>=0) ? 1 : 0;
1458 }
1459 break;
1460 #endif /* TP_PCE_ENABLE */
1461
1462 case ID_FIL:
1463 {
1464 int bitCnt = FDKreadBits(bs,4); /* bs_count */
1465
1466 if (bitCnt == 15)
1467 {
1468 int esc_count = FDKreadBits(bs,8); /* bs_esc_count */
1469 bitCnt = esc_count + 14;
1470 }
1471
1472 /* Convert to bits */
1473 bitCnt <<= 3;
1474
1475 while (bitCnt > 0) {
1476 ErrorStatus = CAacDecoder_ExtPayloadParse(self, bs, &bitCnt, previous_element, previous_element_index, 1);
1477 if (ErrorStatus != AAC_DEC_OK) {
1478 self->frameOK = 0;
1479 break;
1480 }
1481 }
1482 }
1483 break;
1484
1485 case ID_EXT:
1486 {
1487 INT bitCnt = 0;
1488
1489 /* get the remaining bits of this frame */
1490 bitCnt = transportDec_GetAuBitsRemaining(self->hInput, 0);
1491
1492 if ( (bitCnt > 0) && (self->flags & AC_SBR_PRESENT) && (self->flags & (AC_USAC|AC_RSVD50|AC_ELD)) )
1493 {
1494 SBR_ERROR err = SBRDEC_OK;
1495 int elIdx, numChElements = el_cnt[ID_SCE] + el_cnt[ID_CPE];
1496
1497 for (elIdx = 0; elIdx < numChElements; elIdx += 1)
1498 {
1499 err = sbrDecoder_Parse (
1500 self->hSbrDecoder,
1501 bs,
1502 &bitCnt,
1503 -1,
1504 self->flags & AC_SBRCRC,
1505 self->elements[elIdx],
1506 elIdx,
1507 self->flags & AC_INDEP );
1508
1509 if (err != SBRDEC_OK) {
1510 break;
1511 }
1512 }
1513 if (err == SBRDEC_OK) {
1514 self->sbrEnabled = 1;
1515 } else {
1516 self->frameOK = 0;
1517 }
1518 }
1519
1520
1521 if ( ! (self->flags & (AC_USAC|AC_RSVD50|AC_DRM)) )
1522 {
1523 while ( bitCnt > 7 ) {
1524 ErrorStatus = CAacDecoder_ExtPayloadParse(self, bs, &bitCnt, previous_element, previous_element_index, 0);
1525 if (ErrorStatus != AAC_DEC_OK) {
1526 self->frameOK = 0;
1527 ErrorStatus = AAC_DEC_PARSE_ERROR;
1528 break;
1529 }
1530 }
1531 }
1532 }
1533 break;
1534
1535 case ID_END:
1536 break;
1537
1538 default:
1539 ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
1540 self->frameOK = 0;
1541 break;
1542 }
1543
1544 previous_element = type;
1545 element_count++;
1546
1547 } /* while ( (type != ID_END) ... ) */
1548
1549 if ( !(flags & (AACDEC_CONCEAL|AACDEC_FLUSH)) )
1550 {
1551 /* Byte alignment with respect to the first bit of the raw_data_block(). */
1552 {
1553 FDKbyteAlign(bs, auStartAnchor);
1554 }
1555
1556 /* Check if all bits of the raw_data_block() have been read. */
1557 if ( transportDec_GetAuBitsTotal(self->hInput, 0) > 0 ) {
1558 INT unreadBits = transportDec_GetAuBitsRemaining(self->hInput, 0);
1559 if ( unreadBits != 0 ) {
1560
1561 self->frameOK = 0;
1562 /* Do not overwrite current error */
1563 if (ErrorStatus == AAC_DEC_OK && self->frameOK == 0) {
1564 ErrorStatus = AAC_DEC_PARSE_ERROR;
1565 }
1566 /* Always put the bitbuffer at the right position after the current Access Unit. */
1567 FDKpushBiDirectional(bs, unreadBits);
1568 }
1569 }
1570
1571 /* Check the last element. The terminator (ID_END) has to be the last one (even if ER syntax is used). */
1572 if ( self->frameOK && type != ID_END ) {
1573 /* Do not overwrite current error */
1574 if (ErrorStatus == AAC_DEC_OK) {
1575 ErrorStatus = AAC_DEC_PARSE_ERROR;
1576 }
1577 self->frameOK = 0;
1578 }
1579 }
1580
1581 /* More AAC channels than specified by the ASC not allowed. */
1582 if ( (aacChannels == 0 || aacChannels > self->aacChannels) && !(flags & (AACDEC_CONCEAL|AACDEC_FLUSH)) ) {
1583 {
1584 /* Do not overwrite current error */
1585 if (ErrorStatus == AAC_DEC_OK) {
1586 ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
1587 }
1588 self->frameOK = 0;
1589 }
1590 aacChannels = 0;
1591 }
1592 else if ( aacChannels > self->ascChannels ) {
1593 /* Do not overwrite current error */
1594 if (ErrorStatus == AAC_DEC_OK) {
1595 ErrorStatus = AAC_DEC_UNSUPPORTED_FORMAT;
1596 }
1597 self->frameOK = 0;
1598 aacChannels = 0;
1599 }
1600
1601 if ( TRANSPORTDEC_OK != transportDec_CrcCheck(self->hInput) )
1602 {
1603 self->frameOK=0;
1604 }
1605
1606 /* store or restore the number of channels */
1607 if ( self->frameOK && !(flags &(AACDEC_CONCEAL|AACDEC_FLUSH)) ) {
1608 self->concealChannels = aacChannels; /* store */
1609 self->sbrEnabledPrev = self->sbrEnabled;
1610 } else {
1611 if (self->aacChannels > 0) {
1612 aacChannels = self->concealChannels; /* restore */
1613 self->sbrEnabled = self->sbrEnabledPrev;
1614 }
1615 }
1616
1617 /* Update number of output channels */
1618 self->streamInfo.aacNumChannels = aacChannels;
1619
1620 #ifdef TP_PCE_ENABLE
1621 if (pceRead == 1 && CProgramConfig_IsValid(pce)) {
1622 /* Set matrix mixdown infos if available from PCE. */
1623 pcmDmx_SetMatrixMixdownFromPce ( self->hPcmUtils,
1624 pce->MatrixMixdownIndexPresent,
1625 pce->MatrixMixdownIndex,
1626 pce->PseudoSurroundEnable );
1627 }
1628 #endif
1629
1630 /* If there is no valid data to transfrom into time domain, return. */
1631 if ( ! IS_OUTPUT_VALID(ErrorStatus) ) {
1632 return ErrorStatus;
1633 }
1634
1635 /*
1636 Inverse transform
1637 */
1638 {
1639 int stride, offset, c;
1640
1641 /* Extract DRC control data and map it to channels (without bitstream delay) */
1642 aacDecoder_drcProlog (
1643 self->hDrcInfo,
1644 bs,
1645 self->pAacDecoderStaticChannelInfo,
1646 self->pce.ElementInstanceTag,
1647 self->chMapping,
1648 aacChannels
1649 );
1650
1651 /* "c" iterates in canonical MPEG channel order */
1652 for (c=0; c < aacChannels; c++)
1653 {
1654 CAacDecoderChannelInfo *pAacDecoderChannelInfo;
1655
1656 /* Select correct pAacDecoderChannelInfo for current channel */
1657 if (self->chMapping[c] >= aacChannels) {
1658 pAacDecoderChannelInfo = self->pAacDecoderChannelInfo[c];
1659 } else {
1660 pAacDecoderChannelInfo = self->pAacDecoderChannelInfo[self->chMapping[c]];
1661 }
1662
1663 /* Setup offset and stride for time buffer traversal. */
1664 if (interleaved) {
1665 stride = aacChannels;
1666 offset = self->channelOutputMapping[aacChannels-1][c];
1667 } else {
1668 stride = 1;
1669 offset = self->channelOutputMapping[aacChannels-1][c] * self->streamInfo.aacSamplesPerFrame;
1670 }
1671
1672
1673 /*
1674 Conceal defective spectral data
1675 */
1676 CConcealment_Apply(&self->pAacDecoderStaticChannelInfo[c]->concealmentInfo,
1677 pAacDecoderChannelInfo,
1678 self->pAacDecoderStaticChannelInfo[c],
1679 &self->samplingRateInfo,
1680 self->streamInfo.aacSamplesPerFrame,
1681 0,
1682 (self->frameOK && !(flags&AACDEC_CONCEAL)),
1683 self->flags
1684 );
1685
1686
1687 if (flags & (AACDEC_INTR|AACDEC_CLRHIST)) {
1688 /* Reset DRC control data for this channel */
1689 aacDecoder_drcInitChannelData ( &self->pAacDecoderStaticChannelInfo[c]->drcData );
1690 }
1691 /* DRC processing */
1692 aacDecoder_drcApply (
1693 self->hDrcInfo,
1694 self->hSbrDecoder,
1695 pAacDecoderChannelInfo,
1696 &self->pAacDecoderStaticChannelInfo[c]->drcData,
1697 c,
1698 self->streamInfo.aacSamplesPerFrame,
1699 self->sbrEnabled
1700 );
1701
1702 switch (pAacDecoderChannelInfo->renderMode)
1703 {
1704 case AACDEC_RENDER_IMDCT:
1705 CBlock_FrequencyToTime(
1706 self->pAacDecoderStaticChannelInfo[c],
1707 pAacDecoderChannelInfo,
1708 pTimeData + offset,
1709 self->streamInfo.aacSamplesPerFrame,
1710 stride,
1711 (self->frameOK && !(flags&AACDEC_CONCEAL)),
1712 self->aacCommonData.workBufferCore1->mdctOutTemp
1713 );
1714 break;
1715 case AACDEC_RENDER_ELDFB:
1716 CBlock_FrequencyToTimeLowDelay(
1717 self->pAacDecoderStaticChannelInfo[c],
1718 pAacDecoderChannelInfo,
1719 pTimeData + offset,
1720 self->streamInfo.aacSamplesPerFrame,
1721 stride
1722 );
1723 break;
1724 default:
1725 ErrorStatus = AAC_DEC_UNKNOWN;
1726 break;
1727 }
1728 if ( flags&AACDEC_FLUSH ) {
1729 FDKmemclear(pAacDecoderChannelInfo->pSpectralCoefficient, sizeof(FIXP_DBL)*self->streamInfo.aacSamplesPerFrame);
1730 FDKmemclear(self->pAacDecoderStaticChannelInfo[c]->pOverlapBuffer, OverlapBufferSize*sizeof(FIXP_DBL));
1731 }
1732 }
1733
1734
1735 /* Extract DRC control data and map it to channels (with bitstream delay) */
1736 aacDecoder_drcEpilog (
1737 self->hDrcInfo,
1738 bs,
1739 self->pAacDecoderStaticChannelInfo,
1740 self->pce.ElementInstanceTag,
1741 self->chMapping,
1742 aacChannels
1743 );
1744 }
1745
1746
1747 /* Reorder channel type information tables. */
1748 {
1749 AUDIO_CHANNEL_TYPE types[(6)];
1750 UCHAR idx[(6)];
1751 int c;
1752
1753 FDK_ASSERT(sizeof(self->channelType) == sizeof(types));
1754 FDK_ASSERT(sizeof(self->channelIndices) == sizeof(idx));
1755
1756 FDKmemcpy(types, self->channelType, sizeof(types));
1757 FDKmemcpy(idx, self->channelIndices, sizeof(idx));
1758
1759 for (c=0; c<aacChannels; c++) {
1760 self->channelType[self->channelOutputMapping[aacChannels-1][c]] = types[c];
1761 self->channelIndices[self->channelOutputMapping[aacChannels-1][c]] = idx[c];
1762 }
1763 }
1764
1765 self->blockNumber++;
1766
1767 return ErrorStatus;
1768 }
1769
1770 /*!
1771 \brief returns the streaminfo pointer
1772
1773 The function hands back a pointer to the streaminfo structure
1774
1775 \return pointer to the struct
1776 */
1777 LINKSPEC_CPP CStreamInfo* CAacDecoder_GetStreamInfo ( HANDLE_AACDECODER self )
1778 {
1779 if (!self) {
1780 return NULL;
1781 }
1782 return &self->streamInfo;
1783 }
1784
1785
1786
1787