1
2 /* -----------------------------------------------------------------------------------------------------------
3 Software License for The Fraunhofer FDK AAC Codec Library for Android
4
5 � Copyright 1995 - 2012 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
CAacDecoder_SyncQmfMode(HANDLE_AACDECODER self)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->ascChannels == 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->aacChannels == 1 && ! (self->flags & AC_MPS_PRESENT))) && self->qmfModeCurr == MODE_HQ ;
200 FDK_ASSERT( ! ( (self->flags & AC_MPS_PRESENT) && self->psPossible ) );
201 }
202
CAacDecoder_SignalInterruption(HANDLE_AACDECODER self)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 */
CAacDecoder_AncDataReset(CAncData * ancData)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 */
CAacDecoder_AncDataInit(CAncData * ancData,unsigned char * buffer,int size)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 */
CAacDecoder_AncDataGet(CAncData * ancData,int index,unsigned char ** ptr,int * size)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
CAacDecoder_AncDataParse(CAncData * ancData,HANDLE_FDK_BITSTREAM hBs,const int ancBytes)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 */
CDataStreamElement_Read(HANDLE_FDK_BITSTREAM bs,CAncData * ancData,HANDLE_AAC_DRC hDrcInfo,HANDLE_TRANSPORTDEC pTp,UCHAR * elementInstanceTag,UINT alignmentAnchor)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 \count Pointer to program config element.
398
399 \return Error code
400 */
CProgramConfigElement_Read(HANDLE_FDK_BITSTREAM bs,HANDLE_TRANSPORTDEC pTp,CProgramConfig * pce,UINT channelConfig,UINT alignAnchor)401 static AAC_DECODER_ERROR CProgramConfigElement_Read (
402 HANDLE_FDK_BITSTREAM bs,
403 HANDLE_TRANSPORTDEC pTp,
404 CProgramConfig *pce,
405 UINT channelConfig,
406 UINT alignAnchor )
407 {
408 AAC_DECODER_ERROR error = AAC_DEC_OK;
409 int crcReg;
410
411 /* read PCE to temporal buffer first */
412 C_ALLOC_SCRATCH_START(tmpPce, CProgramConfig, 1);
413
414 CProgramConfig_Init(tmpPce);
415 CProgramConfig_Reset(tmpPce);
416
417 crcReg = transportDec_CrcStartReg(pTp, 0);
418
419 CProgramConfig_Read(tmpPce, bs, alignAnchor);
420
421 transportDec_CrcEndReg(pTp, crcReg);
422
423 if ( CProgramConfig_IsValid(tmpPce)
424 && ( (channelConfig == 6 && (tmpPce->NumChannels == 6))
425 || (channelConfig == 5 && (tmpPce->NumChannels == 5))
426 || (channelConfig == 0 && (tmpPce->NumChannels == pce->NumChannels)) )
427 && (tmpPce->NumFrontChannelElements == 2)
428 && (tmpPce->NumSideChannelElements == 0)
429 && (tmpPce->NumBackChannelElements == 1)
430 && (tmpPce->Profile == 1) )
431 { /* Copy the complete PCE including metadata. */
432 FDKmemcpy(pce, tmpPce, sizeof(CProgramConfig));
433 }
434
435 C_ALLOC_SCRATCH_END(tmpPce, CProgramConfig, 1);
436
437 return error;
438 }
439 #endif
440
441 /*!
442 \brief Parse Extension Payload
443
444 \self Handle of AAC decoder
445 \count Pointer to bit counter.
446 \previous_element ID of previous element (required by some extension payloads)
447
448 \return Error code
449 */
450 static
CAacDecoder_ExtPayloadParse(HANDLE_AACDECODER self,HANDLE_FDK_BITSTREAM hBs,int * count,MP4_ELEMENT_ID previous_element,int elIndex,int fIsFillElement)451 AAC_DECODER_ERROR CAacDecoder_ExtPayloadParse (HANDLE_AACDECODER self,
452 HANDLE_FDK_BITSTREAM hBs,
453 int *count,
454 MP4_ELEMENT_ID previous_element,
455 int elIndex,
456 int fIsFillElement)
457 {
458 AAC_DECODER_ERROR error = AAC_DEC_OK;
459 EXT_PAYLOAD_TYPE extension_type;
460 int bytes = (*count) >> 3;
461 int crcFlag = 0;
462
463 if (*count < 4) {
464 return AAC_DEC_PARSE_ERROR;
465 } else if ((INT)FDKgetValidBits(hBs) < *count) {
466 return AAC_DEC_DECODE_FRAME_ERROR;
467 }
468
469 extension_type = (EXT_PAYLOAD_TYPE) FDKreadBits(hBs, 4); /* bs_extension_type */
470 *count -= 4;
471
472 switch (extension_type)
473 {
474 case EXT_DYNAMIC_RANGE:
475 {
476 INT readBits = aacDecoder_drcMarkPayload( self->hDrcInfo, hBs, MPEG_DRC_EXT_DATA );
477
478 if (readBits > *count)
479 { /* Read too much. Something went wrong! */
480 error = AAC_DEC_PARSE_ERROR;
481 }
482 *count -= readBits;
483 }
484 break;
485
486
487 case EXT_SBR_DATA_CRC:
488 crcFlag = 1;
489 case EXT_SBR_DATA:
490 if (IS_CHANNEL_ELEMENT(previous_element)) {
491 SBR_ERROR sbrError;
492
493 CAacDecoder_SyncQmfMode(self);
494
495 sbrError = sbrDecoder_InitElement(
496 self->hSbrDecoder,
497 self->streamInfo.aacSampleRate,
498 self->streamInfo.extSamplingRate,
499 self->streamInfo.aacSamplesPerFrame,
500 self->streamInfo.aot,
501 previous_element,
502 elIndex
503 );
504
505 if (sbrError == SBRDEC_OK) {
506 sbrError = sbrDecoder_Parse (
507 self->hSbrDecoder,
508 hBs,
509 count,
510 *count,
511 crcFlag,
512 previous_element,
513 elIndex,
514 self->flags & AC_INDEP );
515 /* Enable SBR for implicit SBR signalling. */
516 if (sbrError == SBRDEC_OK) {
517 self->sbrEnabled = 1;
518 }
519 } else {
520 /* Do not try to apply SBR because initializing the element failed. */
521 self->sbrEnabled = 0;
522 }
523 /* Citation from ISO/IEC 14496-3 chapter 4.5.2.1.5.2
524 Fill elements containing an extension_payload() with an extension_type of EXT_SBR_DATA
525 or EXT_SBR_DATA_CRC shall not contain any other extension_payload of any other extension_type.
526 */
527 if (fIsFillElement) {
528 FDKpushBiDirectional(hBs, *count);
529 *count = 0;
530 } else {
531 /* If this is not a fill element with a known length, we are screwed an no further parsing makes sense. */
532 if (sbrError != SBRDEC_OK) {
533 self->frameOK = 0;
534 }
535 }
536 } else {
537 error = AAC_DEC_PARSE_ERROR;
538 }
539 break;
540
541 case EXT_FILL_DATA:
542 {
543 int temp;
544
545 temp = FDKreadBits(hBs,4);
546 bytes--;
547 if (temp != 0) {
548 error = AAC_DEC_PARSE_ERROR;
549 break;
550 }
551 while (bytes > 0) {
552 temp = FDKreadBits(hBs,8);
553 bytes--;
554 if (temp != 0xa5) {
555 error = AAC_DEC_PARSE_ERROR;
556 break;
557 }
558 }
559 *count = bytes<<3;
560 }
561 break;
562
563 case EXT_DATA_ELEMENT:
564 {
565 int dataElementVersion;
566
567 dataElementVersion = FDKreadBits(hBs,4);
568 *count -= 4;
569 if (dataElementVersion == 0) /* ANC_DATA */
570 {
571 int temp, dataElementLength = 0;
572 do {
573 temp = FDKreadBits(hBs,8);
574 *count -= 8;
575 dataElementLength += temp;
576 } while (temp == 255 );
577
578 CAacDecoder_AncDataParse(&self->ancData, hBs, dataElementLength);
579 *count -= (dataElementLength<<3);
580 } else {
581 /* align = 0 */
582 error = AAC_DEC_PARSE_ERROR;
583 goto bail;
584 }
585 }
586 break;
587
588 case EXT_DATA_LENGTH:
589 if ( !fIsFillElement /* Makes no sens to have an additional length in a fill ... */
590 && (self->flags & AC_ER) ) /* ... element because this extension payload type was ... */
591 { /* ... created to circumvent the missing length in ER-Syntax. */
592 int bitCnt, len = FDKreadBits(hBs, 4);
593 *count -= 4;
594
595 if (len == 15) {
596 int add_len = FDKreadBits(hBs, 8);
597 *count -= 8;
598 len += add_len;
599
600 if (add_len == 255) {
601 len += FDKreadBits(hBs, 16);
602 *count -= 16;
603 }
604 }
605 len <<= 3;
606 bitCnt = len;
607
608 if ( (EXT_PAYLOAD_TYPE)FDKreadBits(hBs, 4) == EXT_DATA_LENGTH ) {
609 /* Check NOTE 2: The extension_payload() included here must
610 not have extension_type == EXT_DATA_LENGTH. */
611 error = AAC_DEC_PARSE_ERROR;
612 goto bail;
613 }
614 else {
615 /* rewind and call myself again. */
616 FDKpushBack(hBs, 4);
617
618 error =
619 CAacDecoder_ExtPayloadParse (
620 self,
621 hBs,
622 &bitCnt,
623 previous_element,
624 elIndex,
625 1 ); /* Treat same as fill element */
626
627 *count -= len - bitCnt;
628 }
629 /* Note: the fall through in case the if statement above is not taken is intentional. */
630 break;
631 }
632
633 case EXT_FIL:
634
635 default:
636 /* align = 4 */
637 FDKpushFor(hBs, *count);
638 *count = 0;
639 break;
640 }
641
642 bail:
643 if ( (error != AAC_DEC_OK)
644 && fIsFillElement )
645 { /* Skip the remaining extension bytes */
646 FDKpushBiDirectional(hBs, *count);
647 *count = 0;
648 /* Patch error code because decoding can go on. */
649 error = AAC_DEC_OK;
650 /* Be sure that parsing errors have been stored. */
651 }
652 return error;
653 }
654
655 /* Stream Configuration and Information.
656
657 This class holds configuration and information data for a stream to be decoded. It
658 provides the calling application as well as the decoder with substantial information,
659 e.g. profile, sampling rate, number of channels found in the bitstream etc.
660 */
661 static
CStreamInfoInit(CStreamInfo * pStreamInfo)662 void CStreamInfoInit(CStreamInfo *pStreamInfo)
663 {
664 pStreamInfo->aacSampleRate = 0;
665 pStreamInfo->profile = -1;
666 pStreamInfo->aot = AOT_NONE;
667
668 pStreamInfo->channelConfig = -1;
669 pStreamInfo->bitRate = 0;
670 pStreamInfo->aacSamplesPerFrame = 0;
671
672 pStreamInfo->extAot = AOT_NONE;
673 pStreamInfo->extSamplingRate = 0;
674
675 pStreamInfo->flags = 0;
676
677 pStreamInfo->epConfig = -1; /* default is no ER */
678
679 pStreamInfo->numChannels = 0;
680 pStreamInfo->sampleRate = 0;
681 pStreamInfo->frameSize = 0;
682 }
683
684 /*!
685 \brief Initialization of AacDecoderChannelInfo
686
687 The function initializes the pointers to AacDecoderChannelInfo for each channel,
688 set the start values for window shape and window sequence of overlap&add to zero,
689 set the overlap buffer to zero and initializes the pointers to the window coefficients.
690 \param bsFormat is the format of the AAC bitstream
691
692 \return AACDECODER instance
693 */
CAacDecoder_Open(TRANSPORT_TYPE bsFormat)694 LINKSPEC_CPP HANDLE_AACDECODER CAacDecoder_Open(TRANSPORT_TYPE bsFormat) /*!< bitstream format (adif,adts,loas,...). */
695 {
696 HANDLE_AACDECODER self;
697
698 self = GetAacDecoder();
699 if (self == NULL) {
700 goto bail;
701 }
702
703 /* Assign channel mapping info arrays (doing so removes dependency of settings header in API header). */
704 self->streamInfo.pChannelIndices = self->channelIndices;
705 self->streamInfo.pChannelType = self->channelType;
706
707 /* set default output mode */
708 self->outputInterleaved = 1; /* interleaved */
709
710 /* initialize anc data */
711 CAacDecoder_AncDataInit(&self->ancData, NULL, 0);
712
713 /* initialize stream info */
714 CStreamInfoInit(&self->streamInfo);
715
716 /* initialize error concealment common data */
717 CConcealment_InitCommonData(&self->concealCommonData);
718
719 self->hDrcInfo = GetDrcInfo();
720 if (self->hDrcInfo == NULL) {
721 goto bail;
722 }
723 /* Init common DRC structure */
724 aacDecoder_drcInit( self->hDrcInfo );
725 /* Set default frame delay */
726 aacDecoder_drcSetParam (
727 self->hDrcInfo,
728 DRC_BS_DELAY,
729 CConcealment_GetDelay(&self->concealCommonData)
730 );
731
732
733 self->aacCommonData.workBufferCore1 = GetWorkBufferCore1();
734 self->aacCommonData.workBufferCore2 = GetWorkBufferCore2();
735 if (self->aacCommonData.workBufferCore1 == NULL
736 ||self->aacCommonData.workBufferCore2 == NULL )
737 goto bail;
738
739 return self;
740
741 bail:
742 CAacDecoder_Close( self );
743
744 return NULL;
745 }
746
747 /* Destroy aac decoder */
CAacDecoder_Close(HANDLE_AACDECODER self)748 LINKSPEC_CPP void CAacDecoder_Close(HANDLE_AACDECODER self)
749 {
750 int ch;
751
752 if (self == NULL)
753 return;
754
755 for (ch=0; ch<(6); ch++) {
756 if (self->pAacDecoderStaticChannelInfo[ch] != NULL) {
757 FreeOverlapBuffer (&self->pAacDecoderStaticChannelInfo[ch]->pOverlapBuffer);
758 FreeAacDecoderStaticChannelInfo (&self->pAacDecoderStaticChannelInfo[ch]);
759 }
760 if (self->pAacDecoderChannelInfo[ch] != NULL) {
761 FreeAacDecoderChannelInfo (&self->pAacDecoderChannelInfo[ch]);
762 }
763 }
764
765 self->aacChannels = 0;
766
767 if (self->hDrcInfo) {
768 FreeDrcInfo(&self->hDrcInfo);
769 }
770
771 FreeWorkBufferCore1 (&self->aacCommonData.workBufferCore1);
772 FreeWorkBufferCore2 (&self->aacCommonData.workBufferCore2);
773
774 FreeAacDecoder ( &self);
775 }
776
777
778 /*!
779 \brief Initialization of decoder instance
780
781 The function initializes the decoder.
782
783 \return error status: 0 for success, <>0 for unsupported configurations
784 */
CAacDecoder_Init(HANDLE_AACDECODER self,const CSAudioSpecificConfig * asc)785 LINKSPEC_CPP AAC_DECODER_ERROR CAacDecoder_Init(HANDLE_AACDECODER self, const CSAudioSpecificConfig *asc)
786 {
787 AAC_DECODER_ERROR err = AAC_DEC_OK;
788 INT ascChannels, ch, ascChanged = 0;
789
790 if (!self)
791 return AAC_DEC_INVALID_HANDLE;
792
793 // set profile and check for supported aot
794 // leave profile on default (=-1) for all other supported MPEG-4 aot's except aot=2 (=AAC-LC)
795 switch (asc->m_aot) {
796 case AOT_AAC_LC:
797 self->streamInfo.profile = 1;
798 break;
799
800 case AOT_SBR:
801 case AOT_PS:
802 case AOT_ER_AAC_LD:
803 case AOT_ER_AAC_ELD:
804 break;
805
806 default:
807 return AAC_DEC_UNSUPPORTED_AOT;
808 }
809
810 CProgramConfig_Init(&self->pce);
811
812 /* set channels */
813 switch (asc->m_channelConfiguration) {
814 case 0:
815 #ifdef TP_PCE_ENABLE
816 /* get channels from program config (ASC) */
817 if (CProgramConfig_IsValid(&asc->m_progrConfigElement)) {
818 ascChannels = asc->m_progrConfigElement.NumChannels;
819 if (ascChannels > 0) {
820 int el;
821 /* valid number of channels -> copy program config element (PCE) from ASC */
822 FDKmemcpy(&self->pce, &asc->m_progrConfigElement, sizeof(CProgramConfig));
823 /* Built element table */
824 el = CProgramConfig_GetElementTable(&asc->m_progrConfigElement, self->elements, 7);
825 for (; el<7; el++) {
826 self->elements[el] = ID_NONE;
827 }
828 } else {
829 return AAC_DEC_UNSUPPORTED_CHANNELCONFIG;
830 }
831 } else {
832 if (transportDec_GetFormat(self->hInput) == TT_MP4_ADTS) {
833 /* set default max_channels for memory allocation because in implicit channel mapping mode
834 we don't know the actual number of channels until we processed at least one raw_data_block(). */
835 ascChannels = (6);
836 } else {
837 return AAC_DEC_UNSUPPORTED_CHANNELCONFIG;
838 }
839 }
840 #else /* TP_PCE_ENABLE */
841 return AAC_DEC_UNSUPPORTED_CHANNELCONFIG;
842 #endif /* TP_PCE_ENABLE */
843 break;
844 case 1: case 2: case 3: case 4: case 5: case 6:
845 ascChannels = asc->m_channelConfiguration;
846 break;
847 case 7:
848 ascChannels = 8;
849 break;
850 default:
851 return AAC_DEC_UNSUPPORTED_CHANNELCONFIG;
852 }
853
854 /* Initialize constant mappings for channel config 1-7 */
855 if (asc->m_channelConfiguration > 0) {
856 int el;
857 FDKmemcpy(self->elements, elementsTab[asc->m_channelConfiguration-1], sizeof(MP4_ELEMENT_ID)*FDKmin(7,7));
858 for (el=7; el<7; el++) {
859 self->elements[el] = ID_NONE;
860 }
861 for (ch=0; ch<ascChannels; ch++) {
862 self->chMapping[ch] = ch;
863 }
864 for (; ch<(6); ch++) {
865 self->chMapping[ch] = 255;
866 }
867 }
868 #ifdef TP_PCE_ENABLE
869 else {
870 if (CProgramConfig_IsValid(&asc->m_progrConfigElement)) {
871 /* Set matrix mixdown infos if available from PCE. */
872 pcmDmx_SetMatrixMixdownFromPce ( self->hPcmUtils,
873 asc->m_progrConfigElement.MatrixMixdownIndexPresent,
874 asc->m_progrConfigElement.MatrixMixdownIndex,
875 asc->m_progrConfigElement.PseudoSurroundEnable );
876 }
877 }
878 #endif
879
880 self->streamInfo.channelConfig = asc->m_channelConfiguration;
881
882 if (ascChannels > (6)) {
883 return AAC_DEC_UNSUPPORTED_CHANNELCONFIG;
884 }
885 if (self->streamInfo.aot != asc->m_aot) {
886 self->streamInfo.aot = asc->m_aot;
887 ascChanged = 1;
888 }
889
890 if (self->streamInfo.aacSamplesPerFrame != (INT)asc->m_samplesPerFrame) {
891 self->streamInfo.aacSamplesPerFrame = asc->m_samplesPerFrame;
892 ascChanged = 1;
893 }
894
895 self->streamInfo.bitRate = 0;
896
897 /* Set syntax flags */
898 self->flags = 0;
899
900 self->streamInfo.extAot = asc->m_extensionAudioObjectType;
901 self->streamInfo.extSamplingRate = asc->m_extensionSamplingFrequency;
902 self->flags |= (asc->m_sbrPresentFlag) ? AC_SBR_PRESENT : 0;
903 self->flags |= (asc->m_psPresentFlag) ? AC_PS_PRESENT : 0;
904 self->sbrEnabled = 0;
905
906 /* --------- vcb11 ------------ */
907 self->flags |= (asc->m_vcb11Flag) ? AC_ER_VCB11 : 0;
908
909 /* ---------- rvlc ------------ */
910 self->flags |= (asc->m_rvlcFlag) ? AC_ER_RVLC : 0;
911
912 /* ----------- hcr ------------ */
913 self->flags |= (asc->m_hcrFlag) ? AC_ER_HCR : 0;
914
915 if (asc->m_aot == AOT_ER_AAC_ELD) {
916 self->flags |= AC_ELD;
917 self->flags |= (asc->m_sc.m_eldSpecificConfig.m_sbrCrcFlag) ? AC_SBRCRC : 0;
918 self->flags |= (asc->m_sc.m_eldSpecificConfig.m_useLdQmfTimeAlign) ? AC_LD_MPS : 0;
919 }
920 self->flags |= (asc->m_aot == AOT_ER_AAC_LD) ? AC_LD : 0;
921 self->flags |= (asc->m_epConfig >= 0) ? AC_ER : 0;
922
923
924 if (asc->m_sbrPresentFlag) {
925 self->sbrEnabled = 1;
926 self->sbrEnabledPrev = 1;
927 }
928 if (asc->m_psPresentFlag) {
929 self->flags |= AC_PS_PRESENT;
930 }
931
932 if ( (asc->m_epConfig >= 0)
933 && (asc->m_channelConfiguration <= 0) ) {
934 /* we have to know the number of channels otherwise no decoding is possible */
935 return AAC_DEC_UNSUPPORTED_ER_FORMAT;
936 }
937
938 self->streamInfo.epConfig = asc->m_epConfig;
939 /* self->hInput->asc.m_epConfig = asc->m_epConfig; */
940
941 if (asc->m_epConfig > 1)
942 return AAC_DEC_UNSUPPORTED_ER_FORMAT;
943
944 /* Check if samplerate changed. */
945 if (self->streamInfo.aacSampleRate != (INT)asc->m_samplingFrequency) {
946 AAC_DECODER_ERROR error;
947
948 ascChanged = 1;
949
950 /* Update samplerate info. */
951 error = getSamplingRateInfo(&self->samplingRateInfo, asc->m_samplesPerFrame, asc->m_samplingFrequencyIndex, asc->m_samplingFrequency);
952 if (error != AAC_DEC_OK) {
953 return error;
954 }
955 self->streamInfo.aacSampleRate = self->samplingRateInfo.samplingRate;
956 }
957
958 /* Check if amount of channels has changed. */
959 if (self->ascChannels != ascChannels)
960 {
961 ascChanged = 1;
962
963 /* Allocate all memory structures for each channel */
964 {
965 for (ch = 0; ch < ascChannels; ch++) {
966 CAacDecoderDynamicData *aacDecoderDynamicData = &self->aacCommonData.workBufferCore1->pAacDecoderDynamicData[ch%2];
967
968 /* initialize pointer to CAacDecoderChannelInfo */
969 if (self->pAacDecoderChannelInfo[ch] == NULL) {
970 self->pAacDecoderChannelInfo[ch] = GetAacDecoderChannelInfo(ch);
971 /* This is temporary until the DynamicData is split into two or more regions!
972 The memory could be reused after completed core decoding. */
973 if (self->pAacDecoderChannelInfo[ch] == NULL) {
974 goto bail;
975 }
976 /* Hook shared work memory into channel data structure */
977 self->pAacDecoderChannelInfo[ch]->pDynData = aacDecoderDynamicData;
978 self->pAacDecoderChannelInfo[ch]->pComData = &self->aacCommonData;
979 }
980
981 /* Allocate persistent channel memory */
982 if (self->pAacDecoderStaticChannelInfo[ch] == NULL) {
983 self->pAacDecoderStaticChannelInfo[ch] = GetAacDecoderStaticChannelInfo(ch);
984 if (self->pAacDecoderStaticChannelInfo[ch] == NULL) {
985 goto bail;
986 }
987 self->pAacDecoderStaticChannelInfo[ch]->pOverlapBuffer = GetOverlapBuffer(ch); /* This area size depends on the AOT */
988 if (self->pAacDecoderStaticChannelInfo[ch]->pOverlapBuffer == NULL) {
989 goto bail;
990 }
991 self->pAacDecoderChannelInfo[ch]->pSpectralCoefficient = (SPECTRAL_PTR) &self->aacCommonData.workBufferCore2[ch*1024];
992
993 }
994 CPns_InitPns(&self->pAacDecoderChannelInfo[ch]->data.aac.PnsData, &self->aacCommonData.pnsInterChannelData, &self->aacCommonData.pnsCurrentSeed, self->aacCommonData.pnsRandomSeed);
995 }
996
997
998 HcrInitRom(&self->aacCommonData.overlay.aac.erHcrInfo);
999 setHcrType(&self->aacCommonData.overlay.aac.erHcrInfo, ID_SCE);
1000
1001 /* Make allocated channel count persistent in decoder context. */
1002 self->aacChannels = ascChannels;
1003 }
1004
1005 /* Make amount of signalled channels persistent in decoder context. */
1006 self->ascChannels = ascChannels;
1007 }
1008
1009 /* Update structures */
1010 if (ascChanged) {
1011
1012 /* Things to be done for each channel, which do not involved allocating memory. */
1013 for (ch = 0; ch < ascChannels; ch++) {
1014 switch (self->streamInfo.aot) {
1015 case AOT_ER_AAC_ELD:
1016 case AOT_ER_AAC_LD:
1017 self->pAacDecoderChannelInfo[ch]->granuleLength = self->streamInfo.aacSamplesPerFrame;
1018 break;
1019 default:
1020 self->pAacDecoderChannelInfo[ch]->granuleLength = self->streamInfo.aacSamplesPerFrame / 8;
1021 break;
1022 }
1023 mdct_init( &self->pAacDecoderStaticChannelInfo[ch]->IMdct,
1024 self->pAacDecoderStaticChannelInfo[ch]->pOverlapBuffer,
1025 OverlapBufferSize );
1026
1027
1028 /* Reset DRC control data for this channel */
1029 aacDecoder_drcInitChannelData ( &self->pAacDecoderStaticChannelInfo[ch]->drcData );
1030
1031 /* Reset concealment only if ASC changed. Otherwise it will be done with any config callback.
1032 E.g. every time the LATM SMC is present. */
1033 CConcealment_InitChannelData(&self->pAacDecoderStaticChannelInfo[ch]->concealmentInfo,
1034 &self->concealCommonData,
1035 self->streamInfo.aacSamplesPerFrame );
1036 }
1037 }
1038
1039 /* Update externally visible copy of flags */
1040 self->streamInfo.flags = self->flags;
1041
1042 return err;
1043
1044 bail:
1045 aacDecoder_Close( self );
1046 return AAC_DEC_OUT_OF_MEMORY;
1047 }
1048
1049
CAacDecoder_DecodeFrame(HANDLE_AACDECODER self,const UINT flags,INT_PCM * pTimeData,const INT timeDataSize,const INT interleaved)1050 LINKSPEC_CPP AAC_DECODER_ERROR CAacDecoder_DecodeFrame(
1051 HANDLE_AACDECODER self,
1052 const UINT flags,
1053 INT_PCM *pTimeData,
1054 const INT timeDataSize,
1055 const INT interleaved
1056 )
1057 {
1058 AAC_DECODER_ERROR ErrorStatus = AAC_DEC_OK;
1059
1060 CProgramConfig *pce;
1061 HANDLE_FDK_BITSTREAM bs = transportDec_GetBitstream(self->hInput, 0);
1062
1063 MP4_ELEMENT_ID type = ID_NONE; /* Current element type */
1064 INT aacChannels=0; /* Channel counter for channels found in the bitstream */
1065
1066 INT auStartAnchor = (INT)FDKgetValidBits(bs); /* AU start bit buffer position for AU byte alignment */
1067
1068 self->frameOK = 1;
1069
1070 /* Any supported base layer valid AU will require more than 16 bits. */
1071 if ( (transportDec_GetAuBitsRemaining(self->hInput, 0) < 15) && (flags & (AACDEC_CONCEAL|AACDEC_FLUSH)) == 0) {
1072 self->frameOK = 0;
1073 ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
1074 }
1075
1076
1077 /* Reset Program Config structure */
1078 pce = &self->pce;
1079 CProgramConfig_Reset(pce);
1080
1081 CAacDecoder_AncDataReset(&self->ancData);
1082
1083 {
1084 int ch;
1085
1086 if (self->streamInfo.channelConfig == 0) {
1087 /* Init Channel/Element mapping table */
1088 for (ch=0; ch<(6); ch++) {
1089 self->chMapping[ch] = 255;
1090 }
1091 if (!CProgramConfig_IsValid(pce)) {
1092 int el;
1093 for (el=0; el<7; el++) {
1094 self->elements[el] = ID_NONE;
1095 }
1096 }
1097 }
1098 }
1099
1100 /* Check sampling frequency */
1101 switch ( self->streamInfo.aacSampleRate ) {
1102 case 16000:
1103 case 12000:
1104 case 11025:
1105 case 8000:
1106 case 7350:
1107 case 48000:
1108 case 44100:
1109 case 32000:
1110 case 24000:
1111 case 22050:
1112 break;
1113 default:
1114 if ( ! (self->flags & (AC_USAC|AC_RSVD50)) ) {
1115 return AAC_DEC_UNSUPPORTED_SAMPLINGRATE;
1116 }
1117 break;
1118 }
1119
1120
1121 if ( flags & AACDEC_CLRHIST )
1122 {
1123 int ch;
1124 /* Clear history */
1125 for (ch = 0; ch < self->aacChannels; ch++) {
1126 /* Reset concealment */
1127 CConcealment_InitChannelData(&self->pAacDecoderStaticChannelInfo[ch]->concealmentInfo,
1128 &self->concealCommonData,
1129 self->streamInfo.aacSamplesPerFrame );
1130 /* Clear concealment buffers to get rid of the complete history */
1131 FDKmemclear(self->pAacDecoderStaticChannelInfo[ch]->concealmentInfo.spectralCoefficient, 1024 * sizeof(FIXP_CNCL));
1132 FDKmemclear(self->pAacDecoderStaticChannelInfo[ch]->concealmentInfo.specScale, 8 * sizeof(SHORT));
1133 /* Clear overlap-add buffers to avoid clicks. */
1134 FDKmemclear(self->pAacDecoderStaticChannelInfo[ch]->IMdct.overlap.freq, OverlapBufferSize*sizeof(FIXP_DBL));
1135 }
1136 }
1137
1138
1139
1140 #ifdef TP_PCE_ENABLE
1141 int pceRead = 0; /* Flag indicating a PCE in the current raw_data_block() */
1142 #endif
1143
1144
1145 INT hdaacDecoded = 0;
1146 MP4_ELEMENT_ID previous_element = ID_END; /* Last element ID (required for extension payload mapping */
1147 UCHAR previous_element_index = 0; /* Canonical index of last element */
1148 int element_count = 0; /* Element counter for elements found in the bitstream */
1149 int el_cnt[ID_LAST] = { 0 }; /* element counter ( robustness ) */
1150
1151 while ( (type != ID_END) && (! (flags & (AACDEC_CONCEAL | AACDEC_FLUSH))) && self->frameOK )
1152 {
1153 int el_channels;
1154
1155 if (! (self->flags & (AC_USAC|AC_RSVD50|AC_ELD|AC_SCALABLE|AC_ER)))
1156 type = (MP4_ELEMENT_ID) FDKreadBits(bs,3);
1157 else
1158 type = self->elements[element_count];
1159
1160 setHcrType(&self->aacCommonData.overlay.aac.erHcrInfo, type);
1161
1162
1163 if ((INT)FDKgetValidBits(bs) < 0)
1164 self->frameOK = 0;
1165
1166 switch (type)
1167 {
1168 case ID_SCE:
1169 case ID_CPE:
1170 case ID_LFE:
1171 /*
1172 Consistency check
1173 */
1174
1175 if (type == ID_CPE) {
1176 el_channels = 2;
1177 } else {
1178 el_channels = 1;
1179 }
1180
1181 if ( (el_cnt[type] >= (self->ascChannels>>(el_channels-1))) || (aacChannels > (self->ascChannels-el_channels)) ) {
1182 ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
1183 self->frameOK = 0;
1184 break;
1185 }
1186
1187 if ( !(self->flags & (AC_USAC|AC_RSVD50)) ) {
1188 int ch;
1189 for (ch=0; ch < el_channels; ch+=1) {
1190 CPns_ResetData(&self->pAacDecoderChannelInfo[aacChannels+ch]->data.aac.PnsData,
1191 &self->pAacDecoderChannelInfo[aacChannels+ch]->pComData->pnsInterChannelData);
1192 }
1193 }
1194
1195 if(self->frameOK) {
1196 ErrorStatus = CChannelElement_Read( bs,
1197 &self->pAacDecoderChannelInfo[aacChannels],
1198 &self->pAacDecoderStaticChannelInfo[aacChannels],
1199 self->streamInfo.aot,
1200 &self->samplingRateInfo,
1201 self->flags,
1202 self->streamInfo.aacSamplesPerFrame,
1203 el_channels,
1204 self->streamInfo.epConfig,
1205 self->hInput
1206 );
1207 if (ErrorStatus) {
1208 self->frameOK = 0;
1209 }
1210 }
1211
1212
1213 if ( self->frameOK) {
1214 /* Lookup the element and decode it only if it belongs to the current program */
1215 if ( CProgramConfig_LookupElement(
1216 pce,
1217 self->streamInfo.channelConfig,
1218 self->pAacDecoderChannelInfo[aacChannels]->ElementInstanceTag,
1219 aacChannels,
1220 self->chMapping,
1221 self->channelType,
1222 self->channelIndices,
1223 &previous_element_index,
1224 self->elements,
1225 type) )
1226 {
1227 if ( !hdaacDecoded ) {
1228 CChannelElement_Decode(
1229 &self->pAacDecoderChannelInfo[aacChannels],
1230 &self->pAacDecoderStaticChannelInfo[aacChannels],
1231 &self->samplingRateInfo,
1232 self->flags,
1233 el_channels
1234 );
1235 }
1236 aacChannels += 1;
1237 if (type == ID_CPE) {
1238 aacChannels += 1;
1239 }
1240 }
1241 else {
1242 self->frameOK = 0;
1243 }
1244 /* Create SBR element for SBR for upsampling. */
1245 if ( (type == ID_LFE)
1246 && ( (self->flags & AC_SBR_PRESENT)
1247 || (self->sbrEnabled == 1) ) )
1248 {
1249 SBR_ERROR sbrError;
1250
1251 sbrError = sbrDecoder_InitElement(
1252 self->hSbrDecoder,
1253 self->streamInfo.aacSampleRate,
1254 self->streamInfo.extSamplingRate,
1255 self->streamInfo.aacSamplesPerFrame,
1256 self->streamInfo.aot,
1257 ID_LFE,
1258 previous_element_index
1259 );
1260 if (sbrError != SBRDEC_OK) {
1261 /* Do not try to apply SBR because initializing the element failed. */
1262 self->sbrEnabled = 0;
1263 }
1264 }
1265 }
1266
1267 el_cnt[type]++;
1268 break;
1269
1270 case ID_CCE:
1271 /*
1272 Consistency check
1273 */
1274 if ( el_cnt[type] > self->ascChannels ) {
1275 ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
1276 self->frameOK = 0;
1277 break;
1278 }
1279
1280 if (self->frameOK)
1281 {
1282 /* memory for spectral lines temporal on scratch */
1283 C_ALLOC_SCRATCH_START(mdctSpec, FIXP_DBL, 1024);
1284
1285 /* create dummy channel for CCE parsing on stack */
1286 CAacDecoderChannelInfo tmpAacDecoderChannelInfo, *pTmpAacDecoderChannelInfo;
1287
1288 FDKmemclear(mdctSpec, 1024*sizeof(FIXP_DBL));
1289
1290 tmpAacDecoderChannelInfo.pDynData = self->aacCommonData.workBufferCore1->pAacDecoderDynamicData;
1291 tmpAacDecoderChannelInfo.pComData = &self->aacCommonData;
1292 tmpAacDecoderChannelInfo.pSpectralCoefficient = (SPECTRAL_PTR)mdctSpec;
1293 /* Assume AAC-LC */
1294 tmpAacDecoderChannelInfo.granuleLength = self->streamInfo.aacSamplesPerFrame / 8;
1295
1296 /* Reset PNS data. */
1297 CPns_ResetData(&tmpAacDecoderChannelInfo.data.aac.PnsData, &tmpAacDecoderChannelInfo.pComData->pnsInterChannelData);
1298
1299 pTmpAacDecoderChannelInfo = &tmpAacDecoderChannelInfo;
1300 /* do CCE parsing */
1301 ErrorStatus = CChannelElement_Read( bs,
1302 &pTmpAacDecoderChannelInfo,
1303 NULL,
1304 self->streamInfo.aot,
1305 &self->samplingRateInfo,
1306 self->flags,
1307 self->streamInfo.aacSamplesPerFrame,
1308 1,
1309 self->streamInfo.epConfig,
1310 self->hInput
1311 );
1312
1313 C_ALLOC_SCRATCH_END(mdctSpec, FIXP_DBL, 1024);
1314
1315 if (ErrorStatus) {
1316 self->frameOK = 0;
1317 }
1318
1319 if (self->frameOK) {
1320 /* Lookup the element and decode it only if it belongs to the current program */
1321 if (CProgramConfig_LookupElement(
1322 pce,
1323 self->streamInfo.channelConfig,
1324 pTmpAacDecoderChannelInfo->ElementInstanceTag,
1325 0,
1326 self->chMapping,
1327 self->channelType,
1328 self->channelIndices,
1329 &previous_element_index,
1330 self->elements,
1331 type) )
1332 {
1333 /* decoding of CCE not supported */
1334 }
1335 else {
1336 self->frameOK = 0;
1337 }
1338 }
1339 }
1340 el_cnt[type]++;
1341 break;
1342
1343 case ID_DSE:
1344 {
1345 UCHAR element_instance_tag;
1346
1347 CDataStreamElement_Read( bs,
1348 &self->ancData,
1349 self->hDrcInfo,
1350 self->hInput,
1351 &element_instance_tag,
1352 auStartAnchor );
1353
1354 if (!CProgramConfig_LookupElement(
1355 pce,
1356 self->streamInfo.channelConfig,
1357 element_instance_tag,
1358 0,
1359 self->chMapping,
1360 self->channelType,
1361 self->channelIndices,
1362 &previous_element_index,
1363 self->elements,
1364 type) )
1365 {
1366 /* most likely an error in bitstream occured */
1367 //self->frameOK = 0;
1368 }
1369 }
1370
1371 {
1372 UCHAR *pDvbAncData = NULL;
1373 AAC_DECODER_ERROR ancErr;
1374 int ancIndex;
1375 int dvbAncDataSize = 0;
1376
1377 /* Ask how many anc data elements are in buffer */
1378 ancIndex = self->ancData.nrElements - 1;
1379 /* Get the last one (if available) */
1380 ancErr = CAacDecoder_AncDataGet( &self->ancData,
1381 ancIndex,
1382 &pDvbAncData,
1383 &dvbAncDataSize );
1384
1385 if (ancErr == AAC_DEC_OK) {
1386 pcmDmx_ReadDvbAncData (
1387 self->hPcmUtils,
1388 pDvbAncData,
1389 dvbAncDataSize,
1390 0 /* not mpeg2 */ );
1391 }
1392 }
1393 break;
1394
1395 #ifdef TP_PCE_ENABLE
1396 case ID_PCE:
1397
1398 if ( CProgramConfigElement_Read( bs,
1399 self->hInput,
1400 pce,
1401 self->streamInfo.channelConfig,
1402 auStartAnchor ) )
1403 { /* Built element table */
1404 int elIdx = CProgramConfig_GetElementTable(pce, self->elements, 7);
1405 /* Reset the remaining tabs */
1406 for ( ; elIdx<7; elIdx++) {
1407 self->elements[elIdx] = ID_NONE;
1408 }
1409 /* Make new number of channel persistant */
1410 self->ascChannels = pce->NumChannels;
1411 /* If PCE is not first element conceal this frame to avoid inconsistencies */
1412 if ( element_count != 0 ) {
1413 self->frameOK = 0;
1414 }
1415 }
1416 pceRead = 1;
1417 break;
1418 #endif /* TP_PCE_ENABLE */
1419
1420 case ID_FIL:
1421 {
1422 int bitCnt = FDKreadBits(bs,4); /* bs_count */
1423
1424 if (bitCnt == 15)
1425 {
1426 int esc_count = FDKreadBits(bs,8); /* bs_esc_count */
1427 bitCnt = esc_count + 14;
1428 }
1429
1430 /* Convert to bits */
1431 bitCnt <<= 3;
1432
1433 while (bitCnt > 0) {
1434 ErrorStatus = CAacDecoder_ExtPayloadParse(self, bs, &bitCnt, previous_element, previous_element_index, 1);
1435 if (ErrorStatus != AAC_DEC_OK) {
1436 self->frameOK = 0;
1437 break;
1438 }
1439 }
1440 }
1441 break;
1442
1443 case ID_EXT:
1444 {
1445 INT bitCnt = 0;
1446
1447 /* get the remaining bits of this frame */
1448 bitCnt = transportDec_GetAuBitsRemaining(self->hInput, 0);
1449
1450 if ( (bitCnt > 0) && (self->flags & AC_SBR_PRESENT) && (self->flags & (AC_USAC|AC_RSVD50|AC_ELD)) )
1451 {
1452 SBR_ERROR err = SBRDEC_OK;
1453 int elIdx, numChElements = el_cnt[ID_SCE] + el_cnt[ID_CPE];
1454
1455 for (elIdx = 0; elIdx < numChElements; elIdx += 1)
1456 {
1457 err = sbrDecoder_Parse (
1458 self->hSbrDecoder,
1459 bs,
1460 &bitCnt,
1461 -1,
1462 self->flags & AC_SBRCRC,
1463 self->elements[elIdx],
1464 elIdx,
1465 self->flags & AC_INDEP );
1466
1467 if (err != SBRDEC_OK) {
1468 break;
1469 }
1470 }
1471 if (err == SBRDEC_OK) {
1472 self->sbrEnabled = 1;
1473 } else {
1474 self->frameOK = 0;
1475 }
1476 }
1477
1478
1479 if ( ! (self->flags & (AC_USAC|AC_RSVD50|AC_DRM)) )
1480 {
1481 while ( bitCnt > 7 ) {
1482 ErrorStatus = CAacDecoder_ExtPayloadParse(self, bs, &bitCnt, previous_element, previous_element_index, 0);
1483 if (ErrorStatus != AAC_DEC_OK) {
1484 self->frameOK = 0;
1485 ErrorStatus = AAC_DEC_PARSE_ERROR;
1486 break;
1487 }
1488 }
1489 }
1490 }
1491 break;
1492
1493 case ID_END:
1494 break;
1495
1496 default:
1497 ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
1498 self->frameOK = 0;
1499 break;
1500 }
1501
1502 previous_element = type;
1503 element_count++;
1504
1505 } /* while ( (type != ID_END) ... ) */
1506
1507 if ( !(flags & (AACDEC_CONCEAL|AACDEC_FLUSH)) )
1508 {
1509 /* Byte alignment with respect to the first bit of the raw_data_block(). */
1510 {
1511 FDKbyteAlign(bs, auStartAnchor);
1512 }
1513
1514 /* Check if all bits of the raw_data_block() have been read. */
1515 if ( transportDec_GetAuBitsTotal(self->hInput, 0) > 0 ) {
1516 INT unreadBits = transportDec_GetAuBitsRemaining(self->hInput, 0);
1517 if ( unreadBits != 0 ) {
1518
1519 self->frameOK = 0;
1520 /* Do not overwrite current error */
1521 if (ErrorStatus == AAC_DEC_OK && self->frameOK == 0) {
1522 ErrorStatus = AAC_DEC_PARSE_ERROR;
1523 }
1524 /* Always put the bitbuffer at the right position after the current Access Unit. */
1525 FDKpushBiDirectional(bs, unreadBits);
1526 }
1527 }
1528
1529 /* Check the last element. The terminator (ID_END) has to be the last one (even if ER syntax is used). */
1530 if ( self->frameOK && type != ID_END ) {
1531 /* Do not overwrite current error */
1532 if (ErrorStatus == AAC_DEC_OK) {
1533 ErrorStatus = AAC_DEC_PARSE_ERROR;
1534 }
1535 self->frameOK = 0;
1536 }
1537 }
1538
1539 /* More AAC channels than specified by the ASC not allowed. */
1540 if ( (aacChannels == 0 || aacChannels > self->aacChannels) && !(flags & (AACDEC_CONCEAL|AACDEC_FLUSH)) ) {
1541 {
1542 /* Do not overwrite current error */
1543 if (ErrorStatus == AAC_DEC_OK) {
1544 ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
1545 }
1546 self->frameOK = 0;
1547 }
1548 aacChannels = 0;
1549 }
1550 else if ( aacChannels > self->ascChannels ) {
1551 /* Do not overwrite current error */
1552 if (ErrorStatus == AAC_DEC_OK) {
1553 ErrorStatus = AAC_DEC_UNSUPPORTED_FORMAT;
1554 }
1555 self->frameOK = 0;
1556 aacChannels = 0;
1557 }
1558
1559 if ( TRANSPORTDEC_OK != transportDec_CrcCheck(self->hInput) )
1560 {
1561 self->frameOK=0;
1562 }
1563
1564 /* store or restore the number of channels */
1565 if ( self->frameOK && !(flags &(AACDEC_CONCEAL|AACDEC_FLUSH)) ) {
1566 self->concealChannels = aacChannels; /* store */
1567 self->sbrEnabledPrev = self->sbrEnabled;
1568 } else {
1569 if (self->aacChannels > 0) {
1570 aacChannels = self->concealChannels; /* restore */
1571 self->sbrEnabled = self->sbrEnabledPrev;
1572 }
1573 }
1574
1575 /* Update number of output channels */
1576 self->streamInfo.numChannels = aacChannels;
1577
1578 #ifdef TP_PCE_ENABLE
1579 if (pceRead == 1 && CProgramConfig_IsValid(pce)) {
1580 /* Set matrix mixdown infos if available from PCE. */
1581 pcmDmx_SetMatrixMixdownFromPce ( self->hPcmUtils,
1582 pce->MatrixMixdownIndexPresent,
1583 pce->MatrixMixdownIndex,
1584 pce->PseudoSurroundEnable );
1585 }
1586 #endif
1587
1588 /* If there is no valid data to transfrom into time domain, return. */
1589 if ( ! IS_OUTPUT_VALID(ErrorStatus) ) {
1590 return ErrorStatus;
1591 }
1592
1593 /*
1594 Inverse transform
1595 */
1596 {
1597 int stride, offset, c;
1598
1599 /* Extract DRC control data and map it to channels (without bitstream delay) */
1600 aacDecoder_drcProlog (
1601 self->hDrcInfo,
1602 bs,
1603 self->pAacDecoderStaticChannelInfo,
1604 self->pce.ElementInstanceTag,
1605 self->chMapping,
1606 aacChannels
1607 );
1608
1609 /* "c" iterates in canonical MPEG channel order */
1610 for (c=0; c < aacChannels; c++)
1611 {
1612 CAacDecoderChannelInfo *pAacDecoderChannelInfo;
1613
1614 /* Select correct pAacDecoderChannelInfo for current channel */
1615 if (self->chMapping[c] >= aacChannels) {
1616 pAacDecoderChannelInfo = self->pAacDecoderChannelInfo[c];
1617 } else {
1618 pAacDecoderChannelInfo = self->pAacDecoderChannelInfo[self->chMapping[c]];
1619 }
1620
1621 /* Setup offset and stride for time buffer traversal. */
1622 if (interleaved) {
1623 stride = aacChannels;
1624 offset = self->channelOutputMapping[aacChannels-1][c];
1625 } else {
1626 stride = 1;
1627 offset = self->channelOutputMapping[aacChannels-1][c] * self->streamInfo.aacSamplesPerFrame;
1628 }
1629
1630
1631 /*
1632 Conceal defective spectral data
1633 */
1634 CConcealment_Apply(&self->pAacDecoderStaticChannelInfo[c]->concealmentInfo,
1635 pAacDecoderChannelInfo,
1636 self->pAacDecoderStaticChannelInfo[c],
1637 &self->samplingRateInfo,
1638 self->streamInfo.aacSamplesPerFrame,
1639 0,
1640 (self->frameOK && !(flags&AACDEC_CONCEAL)),
1641 self->flags
1642 );
1643
1644
1645 if (flags & (AACDEC_INTR|AACDEC_CLRHIST)) {
1646 /* Reset DRC control data for this channel */
1647 aacDecoder_drcInitChannelData ( &self->pAacDecoderStaticChannelInfo[c]->drcData );
1648 }
1649 /* DRC processing */
1650 aacDecoder_drcApply (
1651 self->hDrcInfo,
1652 self->hSbrDecoder,
1653 pAacDecoderChannelInfo,
1654 &self->pAacDecoderStaticChannelInfo[c]->drcData,
1655 c,
1656 self->streamInfo.aacSamplesPerFrame,
1657 self->sbrEnabled
1658 );
1659
1660 switch (pAacDecoderChannelInfo->renderMode)
1661 {
1662 case AACDEC_RENDER_IMDCT:
1663 CBlock_FrequencyToTime(
1664 self->pAacDecoderStaticChannelInfo[c],
1665 pAacDecoderChannelInfo,
1666 pTimeData + offset,
1667 self->streamInfo.aacSamplesPerFrame,
1668 stride,
1669 (self->frameOK && !(flags&AACDEC_CONCEAL)),
1670 self->aacCommonData.workBufferCore1->mdctOutTemp
1671 );
1672 break;
1673 case AACDEC_RENDER_ELDFB:
1674 CBlock_FrequencyToTimeLowDelay(
1675 self->pAacDecoderStaticChannelInfo[c],
1676 pAacDecoderChannelInfo,
1677 pTimeData + offset,
1678 self->streamInfo.aacSamplesPerFrame,
1679 stride
1680 );
1681 break;
1682 default:
1683 ErrorStatus = AAC_DEC_UNKNOWN;
1684 break;
1685 }
1686 if ( flags&AACDEC_FLUSH ) {
1687 FDKmemclear(pAacDecoderChannelInfo->pSpectralCoefficient, sizeof(FIXP_DBL)*self->streamInfo.aacSamplesPerFrame);
1688 FDKmemclear(self->pAacDecoderStaticChannelInfo[c]->pOverlapBuffer, OverlapBufferSize*sizeof(FIXP_DBL));
1689 }
1690 }
1691
1692
1693 /* Extract DRC control data and map it to channels (with bitstream delay) */
1694 aacDecoder_drcEpilog (
1695 self->hDrcInfo,
1696 bs,
1697 self->pAacDecoderStaticChannelInfo,
1698 self->pce.ElementInstanceTag,
1699 self->chMapping,
1700 aacChannels
1701 );
1702 }
1703
1704
1705 /* Reorder channel type information tables. */
1706 {
1707 AUDIO_CHANNEL_TYPE types[(6)];
1708 UCHAR idx[(6)];
1709 int c;
1710
1711 FDK_ASSERT(sizeof(self->channelType) == sizeof(types));
1712 FDK_ASSERT(sizeof(self->channelIndices) == sizeof(idx));
1713
1714 FDKmemcpy(types, self->channelType, sizeof(types));
1715 FDKmemcpy(idx, self->channelIndices, sizeof(idx));
1716
1717 for (c=0; c<aacChannels; c++) {
1718 self->channelType[self->channelOutputMapping[aacChannels-1][c]] = types[c];
1719 self->channelIndices[self->channelOutputMapping[aacChannels-1][c]] = idx[c];
1720 }
1721 }
1722
1723 self->blockNumber++;
1724
1725 return ErrorStatus;
1726 }
1727
1728 /*!
1729 \brief returns the streaminfo pointer
1730
1731 The function hands back a pointer to the streaminfo structure
1732
1733 \return pointer to the struct
1734 */
CAacDecoder_GetStreamInfo(HANDLE_AACDECODER self)1735 LINKSPEC_CPP CStreamInfo* CAacDecoder_GetStreamInfo ( HANDLE_AACDECODER self )
1736 {
1737 if (!self) {
1738 return NULL;
1739 }
1740 return &self->streamInfo;
1741 }
1742
1743
1744
1745
1746