• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
869   self->streamInfo.channelConfig = asc->m_channelConfiguration;
870 
871   if (ascChannels > (6)) {
872     return AAC_DEC_UNSUPPORTED_CHANNELCONFIG;
873   }
874   if (self->streamInfo.aot != asc->m_aot) {
875     self->streamInfo.aot = asc->m_aot;
876     ascChanged = 1;
877   }
878 
879   if (self->streamInfo.aacSamplesPerFrame != (INT)asc->m_samplesPerFrame) {
880     self->streamInfo.aacSamplesPerFrame = asc->m_samplesPerFrame;
881     ascChanged = 1;
882   }
883 
884   self->streamInfo.bitRate            = 0;
885 
886   /* Set syntax flags */
887   self->flags = 0;
888 
889   self->streamInfo.extAot               = asc->m_extensionAudioObjectType;
890   self->streamInfo.extSamplingRate      = asc->m_extensionSamplingFrequency;
891   self->flags |= (asc->m_sbrPresentFlag) ? AC_SBR_PRESENT : 0;
892   self->flags |= (asc->m_psPresentFlag) ? AC_PS_PRESENT : 0;
893   self->sbrEnabled = 0;
894 
895   /* --------- vcb11 ------------ */
896   self->flags |= (asc->m_vcb11Flag) ? AC_ER_VCB11 : 0;
897 
898   /* ---------- rvlc ------------ */
899   self->flags |= (asc->m_rvlcFlag) ? AC_ER_RVLC : 0;
900 
901   /* ----------- hcr ------------ */
902   self->flags |= (asc->m_hcrFlag) ? AC_ER_HCR : 0;
903 
904   if (asc->m_aot == AOT_ER_AAC_ELD) {
905     self->flags |=  AC_ELD;
906     self->flags |= (asc->m_sc.m_eldSpecificConfig.m_sbrCrcFlag) ? AC_SBRCRC : 0;
907     self->flags |= (asc->m_sc.m_eldSpecificConfig.m_useLdQmfTimeAlign) ? AC_LD_MPS : 0;
908   }
909   self->flags |= (asc->m_aot == AOT_ER_AAC_LD) ? AC_LD : 0;
910   self->flags |= (asc->m_epConfig >= 0) ? AC_ER : 0;
911 
912 
913   if (asc->m_sbrPresentFlag) {
914     self->sbrEnabled = 1;
915     self->sbrEnabledPrev = 1;
916   }
917   if (asc->m_psPresentFlag) {
918     self->flags |= AC_PS_PRESENT;
919   }
920 
921   if ( (asc->m_epConfig >= 0)
922     && (asc->m_channelConfiguration <= 0) ) {
923     /* we have to know the number of channels otherwise no decoding is possible */
924     return AAC_DEC_UNSUPPORTED_ER_FORMAT;
925   }
926 
927   self->streamInfo.epConfig = asc->m_epConfig;
928   /* self->hInput->asc.m_epConfig = asc->m_epConfig; */
929 
930   if (asc->m_epConfig > 1)
931     return AAC_DEC_UNSUPPORTED_ER_FORMAT;
932 
933   /* Check if samplerate changed. */
934   if (self->streamInfo.aacSampleRate != (INT)asc->m_samplingFrequency) {
935     AAC_DECODER_ERROR error;
936 
937     ascChanged = 1;
938 
939     /* Update samplerate info. */
940     error = getSamplingRateInfo(&self->samplingRateInfo, asc->m_samplesPerFrame, asc->m_samplingFrequencyIndex, asc->m_samplingFrequency);
941     if (error != AAC_DEC_OK) {
942       return error;
943     }
944     self->streamInfo.aacSampleRate = self->samplingRateInfo.samplingRate;
945   }
946 
947   /* Check if amount of channels has changed. */
948   if (self->ascChannels != ascChannels)
949   {
950      ascChanged = 1;
951 
952      /* Allocate all memory structures for each channel */
953      {
954        for (ch = 0; ch < ascChannels; ch++) {
955          CAacDecoderDynamicData *aacDecoderDynamicData = &self->aacCommonData.workBufferCore1->pAacDecoderDynamicData[ch%2];
956 
957          /* initialize pointer to CAacDecoderChannelInfo */
958          if (self->pAacDecoderChannelInfo[ch] == NULL) {
959            self->pAacDecoderChannelInfo[ch] = GetAacDecoderChannelInfo(ch);
960            /* This is temporary until the DynamicData is split into two or more regions!
961               The memory could be reused after completed core decoding. */
962            if (self->pAacDecoderChannelInfo[ch] == NULL) {
963              goto bail;
964            }
965            /* Hook shared work memory into channel data structure */
966            self->pAacDecoderChannelInfo[ch]->pDynData =  aacDecoderDynamicData;
967            self->pAacDecoderChannelInfo[ch]->pComData = &self->aacCommonData;
968          }
969 
970          /* Allocate persistent channel memory */
971          if (self->pAacDecoderStaticChannelInfo[ch] == NULL) {
972            self->pAacDecoderStaticChannelInfo[ch] = GetAacDecoderStaticChannelInfo(ch);
973            if (self->pAacDecoderStaticChannelInfo[ch] == NULL) {
974              goto bail;
975            }
976            self->pAacDecoderStaticChannelInfo[ch]->pOverlapBuffer = GetOverlapBuffer(ch); /* This area size depends on the AOT */
977            if (self->pAacDecoderStaticChannelInfo[ch]->pOverlapBuffer == NULL) {
978              goto bail;
979            }
980            self->pAacDecoderChannelInfo[ch]->pSpectralCoefficient = (SPECTRAL_PTR) &self->aacCommonData.workBufferCore2[ch*1024];
981 
982          }
983          CPns_InitPns(&self->pAacDecoderChannelInfo[ch]->data.aac.PnsData, &self->aacCommonData.pnsInterChannelData, &self->aacCommonData.pnsCurrentSeed, self->aacCommonData.pnsRandomSeed);
984        }
985 
986 
987        HcrInitRom(&self->aacCommonData.overlay.aac.erHcrInfo);
988        setHcrType(&self->aacCommonData.overlay.aac.erHcrInfo, ID_SCE);
989 
990        /* Make allocated channel count persistent in decoder context. */
991        self->aacChannels = ascChannels;
992     }
993 
994     /* Make amount of signalled channels persistent in decoder context. */
995     self->ascChannels = ascChannels;
996   }
997 
998   /* Update structures */
999   if (ascChanged) {
1000 
1001      /* Things to be done for each channel, which do not involved allocating memory. */
1002      for (ch = 0; ch < ascChannels; ch++) {
1003        switch (self->streamInfo.aot) {
1004          case AOT_ER_AAC_ELD:
1005          case AOT_ER_AAC_LD:
1006            self->pAacDecoderChannelInfo[ch]->granuleLength = self->streamInfo.aacSamplesPerFrame;
1007            break;
1008          default:
1009            self->pAacDecoderChannelInfo[ch]->granuleLength = self->streamInfo.aacSamplesPerFrame / 8;
1010            break;
1011        }
1012        mdct_init( &self->pAacDecoderStaticChannelInfo[ch]->IMdct,
1013                    self->pAacDecoderStaticChannelInfo[ch]->pOverlapBuffer,
1014                    OverlapBufferSize );
1015 
1016 
1017         /* Reset DRC control data for this channel */
1018         aacDecoder_drcInitChannelData ( &self->pAacDecoderStaticChannelInfo[ch]->drcData );
1019 
1020        /* Reset concealment only if ASC changed. Otherwise it will be done with any config callback.
1021           E.g. every time the LATM SMC is present. */
1022        CConcealment_InitChannelData(&self->pAacDecoderStaticChannelInfo[ch]->concealmentInfo,
1023                                     &self->concealCommonData,
1024                                      self->streamInfo.aacSamplesPerFrame );
1025      }
1026   }
1027 
1028   /* Update externally visible copy of flags */
1029   self->streamInfo.flags = self->flags;
1030 
1031   return err;
1032 
1033 bail:
1034   aacDecoder_Close( self );
1035   return AAC_DEC_OUT_OF_MEMORY;
1036 }
1037 
1038 
CAacDecoder_DecodeFrame(HANDLE_AACDECODER self,const UINT flags,INT_PCM * pTimeData,const INT timeDataSize,const INT interleaved)1039 LINKSPEC_CPP AAC_DECODER_ERROR CAacDecoder_DecodeFrame(
1040         HANDLE_AACDECODER self,
1041         const UINT flags,
1042         INT_PCM *pTimeData,
1043         const INT  timeDataSize,
1044         const INT interleaved
1045         )
1046 {
1047   AAC_DECODER_ERROR ErrorStatus = AAC_DEC_OK;
1048 
1049   CProgramConfig *pce;
1050   HANDLE_FDK_BITSTREAM bs = transportDec_GetBitstream(self->hInput, 0);
1051 
1052   MP4_ELEMENT_ID type = ID_NONE;            /* Current element type */
1053   INT aacChannels=0;                        /* Channel counter for channels found in the bitstream */
1054 
1055   INT auStartAnchor = (INT)FDKgetValidBits(bs);  /* AU start bit buffer position for AU byte alignment */
1056 
1057   self->frameOK = 1;
1058 
1059   /* Any supported base layer valid AU will require more than 16 bits. */
1060   if ( (transportDec_GetAuBitsRemaining(self->hInput, 0) < 15) && (flags & (AACDEC_CONCEAL|AACDEC_FLUSH)) == 0) {
1061     self->frameOK = 0;
1062     ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
1063   }
1064 
1065 
1066   /* Reset Program Config structure */
1067   pce = &self->pce;
1068   CProgramConfig_Reset(pce);
1069 
1070   CAacDecoder_AncDataReset(&self->ancData);
1071 
1072   {
1073     int ch;
1074 
1075     if (self->streamInfo.channelConfig == 0) {
1076       /* Init Channel/Element mapping table */
1077       for (ch=0; ch<(6); ch++) {
1078         self->chMapping[ch] = 255;
1079       }
1080       if (!CProgramConfig_IsValid(pce)) {
1081         int el;
1082         for (el=0; el<7; el++) {
1083           self->elements[el] = ID_NONE;
1084         }
1085       }
1086     }
1087   }
1088 
1089   /* Check sampling frequency  */
1090   switch ( self->streamInfo.aacSampleRate ) {
1091     case 16000:
1092     case 12000:
1093    case 11025:
1094    case  8000:
1095     case  7350:
1096     case 48000:
1097     case 44100:
1098     case 32000:
1099     case 24000:
1100     case 22050:
1101       break;
1102     default:
1103       if ( ! (self->flags & (AC_USAC|AC_RSVD50)) ) {
1104         return AAC_DEC_UNSUPPORTED_SAMPLINGRATE;
1105       }
1106       break;
1107   }
1108 
1109 
1110   if ( flags & AACDEC_CLRHIST )
1111   {
1112     int ch;
1113     /* Clear history */
1114     for (ch = 0; ch < self->aacChannels; ch++) {
1115       /* Reset concealment */
1116       CConcealment_InitChannelData(&self->pAacDecoderStaticChannelInfo[ch]->concealmentInfo,
1117                                    &self->concealCommonData,
1118                                     self->streamInfo.aacSamplesPerFrame );
1119       /* Clear concealment buffers to get rid of the complete history */
1120       FDKmemclear(self->pAacDecoderStaticChannelInfo[ch]->concealmentInfo.spectralCoefficient, 1024 * sizeof(FIXP_CNCL));
1121       FDKmemclear(self->pAacDecoderStaticChannelInfo[ch]->concealmentInfo.specScale, 8 * sizeof(SHORT));
1122       /* Clear overlap-add buffers to avoid clicks. */
1123       FDKmemclear(self->pAacDecoderStaticChannelInfo[ch]->IMdct.overlap.freq, OverlapBufferSize*sizeof(FIXP_DBL));
1124      }
1125   }
1126 
1127 
1128 
1129 #ifdef TP_PCE_ENABLE
1130   int pceRead = 0;                          /* Flag indicating a PCE in the current raw_data_block() */
1131 #endif
1132 
1133 
1134   INT hdaacDecoded = 0;
1135   MP4_ELEMENT_ID previous_element = ID_END; /* Last element ID (required for extension payload mapping */
1136   UCHAR previous_element_index = 0;         /* Canonical index of last element */
1137   int element_count = 0;                    /* Element counter for elements found in the bitstream */
1138   int el_cnt[ID_LAST] = { 0 };              /* element counter ( robustness ) */
1139 
1140   while ( (type != ID_END) && (! (flags & (AACDEC_CONCEAL | AACDEC_FLUSH))) && self->frameOK )
1141   {
1142     int el_channels;
1143 
1144     if (! (self->flags & (AC_USAC|AC_RSVD50|AC_ELD|AC_SCALABLE|AC_ER)))
1145       type = (MP4_ELEMENT_ID) FDKreadBits(bs,3);
1146     else
1147       type = self->elements[element_count];
1148 
1149     setHcrType(&self->aacCommonData.overlay.aac.erHcrInfo, type);
1150 
1151 
1152     if ((INT)FDKgetValidBits(bs) < 0)
1153       self->frameOK = 0;
1154 
1155     switch (type)
1156     {
1157       case ID_SCE:
1158       case ID_CPE:
1159       case ID_LFE:
1160         /*
1161           Consistency check
1162         */
1163 
1164         if (type == ID_CPE) {
1165           el_channels = 2;
1166         } else {
1167           el_channels = 1;
1168         }
1169 
1170         if ( (el_cnt[type] >= (self->ascChannels>>(el_channels-1))) || (aacChannels > (self->ascChannels-el_channels)) ) {
1171           ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
1172           self->frameOK = 0;
1173           break;
1174         }
1175 
1176         if ( !(self->flags & (AC_USAC|AC_RSVD50)) ) {
1177           int ch;
1178           for (ch=0; ch < el_channels; ch+=1) {
1179             CPns_ResetData(&self->pAacDecoderChannelInfo[aacChannels+ch]->data.aac.PnsData,
1180                            &self->pAacDecoderChannelInfo[aacChannels+ch]->pComData->pnsInterChannelData);
1181           }
1182         }
1183 
1184         if(self->frameOK) {
1185           ErrorStatus = CChannelElement_Read( bs,
1186                                              &self->pAacDecoderChannelInfo[aacChannels],
1187                                              &self->pAacDecoderStaticChannelInfo[aacChannels],
1188                                               self->streamInfo.aot,
1189                                              &self->samplingRateInfo,
1190                                               self->flags,
1191                                               self->streamInfo.aacSamplesPerFrame,
1192                                               el_channels,
1193                                               self->streamInfo.epConfig,
1194                                               self->hInput
1195                                               );
1196           if (ErrorStatus) {
1197             self->frameOK = 0;
1198           }
1199         }
1200 
1201 
1202         if ( self->frameOK) {
1203           /* Lookup the element and decode it only if it belongs to the current program */
1204           if ( CProgramConfig_LookupElement(
1205                   pce,
1206                   self->streamInfo.channelConfig,
1207                   self->pAacDecoderChannelInfo[aacChannels]->ElementInstanceTag,
1208                   aacChannels,
1209                   self->chMapping,
1210                   self->channelType,
1211                   self->channelIndices,
1212                  &previous_element_index,
1213                   self->elements,
1214                   type) )
1215           {
1216             if ( !hdaacDecoded ) {
1217               CChannelElement_Decode(
1218                      &self->pAacDecoderChannelInfo[aacChannels],
1219                      &self->pAacDecoderStaticChannelInfo[aacChannels],
1220                      &self->samplingRateInfo,
1221                       self->flags,
1222                       el_channels
1223                       );
1224             }
1225             aacChannels += 1;
1226             if (type == ID_CPE) {
1227               aacChannels += 1;
1228             }
1229           }
1230           else {
1231             self->frameOK = 0;
1232           }
1233           /* Create SBR element for SBR for upsampling. */
1234           if ( (type == ID_LFE)
1235             && ( (self->flags & AC_SBR_PRESENT)
1236               || (self->sbrEnabled == 1) ) )
1237           {
1238             SBR_ERROR sbrError;
1239 
1240             sbrError = sbrDecoder_InitElement(
1241                     self->hSbrDecoder,
1242                     self->streamInfo.aacSampleRate,
1243                     self->streamInfo.extSamplingRate,
1244                     self->streamInfo.aacSamplesPerFrame,
1245                     self->streamInfo.aot,
1246                     ID_LFE,
1247                     previous_element_index
1248                     );
1249             if (sbrError != SBRDEC_OK) {
1250               /* Do not try to apply SBR because initializing the element failed. */
1251               self->sbrEnabled = 0;
1252             }
1253           }
1254         }
1255 
1256         el_cnt[type]++;
1257         break;
1258 
1259       case ID_CCE:
1260         /*
1261           Consistency check
1262         */
1263         if ( el_cnt[type] > self->ascChannels ) {
1264           ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
1265           self->frameOK = 0;
1266           break;
1267         }
1268 
1269         if (self->frameOK)
1270         {
1271           /* memory for spectral lines temporal on scratch */
1272           C_ALLOC_SCRATCH_START(mdctSpec, FIXP_DBL, 1024);
1273 
1274           /* create dummy channel for CCE parsing on stack */
1275           CAacDecoderChannelInfo  tmpAacDecoderChannelInfo, *pTmpAacDecoderChannelInfo;
1276 
1277           FDKmemclear(mdctSpec, 1024*sizeof(FIXP_DBL));
1278 
1279           tmpAacDecoderChannelInfo.pDynData =   self->aacCommonData.workBufferCore1->pAacDecoderDynamicData;
1280           tmpAacDecoderChannelInfo.pComData =  &self->aacCommonData;
1281           tmpAacDecoderChannelInfo.pSpectralCoefficient  = (SPECTRAL_PTR)mdctSpec;
1282           /* Assume AAC-LC */
1283           tmpAacDecoderChannelInfo.granuleLength = self->streamInfo.aacSamplesPerFrame / 8;
1284 
1285           /* Reset PNS data. */
1286           CPns_ResetData(&tmpAacDecoderChannelInfo.data.aac.PnsData, &tmpAacDecoderChannelInfo.pComData->pnsInterChannelData);
1287 
1288           pTmpAacDecoderChannelInfo = &tmpAacDecoderChannelInfo;
1289           /* do CCE parsing */
1290           ErrorStatus = CChannelElement_Read( bs,
1291                                              &pTmpAacDecoderChannelInfo,
1292                                               NULL,
1293                                               self->streamInfo.aot,
1294                                              &self->samplingRateInfo,
1295                                               self->flags,
1296                                               self->streamInfo.aacSamplesPerFrame,
1297                                               1,
1298                                               self->streamInfo.epConfig,
1299                                               self->hInput
1300                                              );
1301 
1302           C_ALLOC_SCRATCH_END(mdctSpec, FIXP_DBL, 1024);
1303 
1304           if (ErrorStatus) {
1305             self->frameOK = 0;
1306           }
1307 
1308           if (self->frameOK) {
1309             /* Lookup the element and decode it only if it belongs to the current program */
1310             if (CProgramConfig_LookupElement(
1311                     pce,
1312                     self->streamInfo.channelConfig,
1313                     pTmpAacDecoderChannelInfo->ElementInstanceTag,
1314                     0,
1315                     self->chMapping,
1316                     self->channelType,
1317                     self->channelIndices,
1318                    &previous_element_index,
1319                     self->elements,
1320                     type) )
1321             {
1322               /* decoding of CCE not supported */
1323             }
1324             else {
1325               self->frameOK = 0;
1326             }
1327           }
1328         }
1329         el_cnt[type]++;
1330         break;
1331 
1332       case ID_DSE:
1333         {
1334           UCHAR element_instance_tag;
1335 
1336           CDataStreamElement_Read( bs,
1337                                   &self->ancData,
1338                                    self->hDrcInfo,
1339                                    self->hInput,
1340                                   &element_instance_tag,
1341                                    auStartAnchor );
1342 
1343           if (!CProgramConfig_LookupElement(
1344                    pce,
1345                    self->streamInfo.channelConfig,
1346                    element_instance_tag,
1347                    0,
1348                    self->chMapping,
1349                    self->channelType,
1350                    self->channelIndices,
1351                   &previous_element_index,
1352                    self->elements,
1353                    type) )
1354           {
1355             /* most likely an error in bitstream occured */
1356             //self->frameOK = 0;
1357           }
1358         }
1359 
1360         {
1361           UCHAR *pDvbAncData = NULL;
1362           AAC_DECODER_ERROR ancErr;
1363           int ancIndex;
1364           int dvbAncDataSize = 0;
1365 
1366           /* Ask how many anc data elements are in buffer */
1367           ancIndex = self->ancData.nrElements - 1;
1368           /* Get the last one (if available) */
1369           ancErr   = CAacDecoder_AncDataGet( &self->ancData,
1370                                               ancIndex,
1371                                              &pDvbAncData,
1372                                              &dvbAncDataSize );
1373 
1374           if (ancErr == AAC_DEC_OK) {
1375             pcmDmx_ReadDvbAncData (
1376                   self->hPcmUtils,
1377                   pDvbAncData,
1378                   dvbAncDataSize,
1379                   0 /* not mpeg2 */ );
1380           }
1381         }
1382         break;
1383 
1384 #ifdef TP_PCE_ENABLE
1385       case ID_PCE:
1386 
1387         if ( CProgramConfigElement_Read( bs,
1388                                     self->hInput,
1389                                     pce,
1390                                     self->streamInfo.channelConfig,
1391                                     auStartAnchor ) )
1392         { /* Built element table */
1393           int elIdx = CProgramConfig_GetElementTable(pce, self->elements, 7);
1394           /* Reset the remaining tabs */
1395           for ( ; elIdx<7; elIdx++) {
1396             self->elements[elIdx] = ID_NONE;
1397           }
1398           /* Make new number of channel persistant */
1399           self->ascChannels = pce->NumChannels;
1400           /* If PCE is not first element conceal this frame to avoid inconsistencies */
1401           if ( element_count != 0 ) {
1402             self->frameOK = 0;
1403           }
1404         }
1405         pceRead = 1;
1406         break;
1407 #endif /* TP_PCE_ENABLE */
1408 
1409       case ID_FIL:
1410         {
1411           int bitCnt = FDKreadBits(bs,4);           /* bs_count */
1412 
1413           if (bitCnt == 15)
1414           {
1415             int esc_count = FDKreadBits(bs,8);     /* bs_esc_count */
1416             bitCnt =  esc_count + 14;
1417           }
1418 
1419           /* Convert to bits */
1420           bitCnt <<= 3;
1421 
1422           while (bitCnt > 0) {
1423             ErrorStatus = CAacDecoder_ExtPayloadParse(self, bs, &bitCnt, previous_element, previous_element_index, 1);
1424             if (ErrorStatus != AAC_DEC_OK) {
1425               self->frameOK = 0;
1426               break;
1427             }
1428           }
1429         }
1430         break;
1431 
1432       case ID_EXT:
1433         {
1434           INT bitCnt = 0;
1435 
1436           /* get the remaining bits of this frame */
1437           bitCnt = transportDec_GetAuBitsRemaining(self->hInput, 0);
1438 
1439           if ( (bitCnt > 0) && (self->flags & AC_SBR_PRESENT) && (self->flags & (AC_USAC|AC_RSVD50|AC_ELD)) )
1440           {
1441             SBR_ERROR err = SBRDEC_OK;
1442             int  elIdx, numChElements = el_cnt[ID_SCE] + el_cnt[ID_CPE];
1443 
1444             for (elIdx = 0; elIdx < numChElements; elIdx += 1)
1445             {
1446               err = sbrDecoder_Parse (
1447                     self->hSbrDecoder,
1448                     bs,
1449                    &bitCnt,
1450                     -1,
1451                     self->flags & AC_SBRCRC,
1452                     self->elements[elIdx],
1453                     elIdx,
1454                     self->flags & AC_INDEP );
1455 
1456               if (err != SBRDEC_OK) {
1457                 break;
1458               }
1459             }
1460             if (err == SBRDEC_OK) {
1461               self->sbrEnabled = 1;
1462             } else {
1463               self->frameOK = 0;
1464             }
1465           }
1466 
1467 
1468           if ( ! (self->flags & (AC_USAC|AC_RSVD50|AC_DRM)) )
1469           {
1470             while ( bitCnt > 7 ) {
1471               ErrorStatus = CAacDecoder_ExtPayloadParse(self, bs, &bitCnt, previous_element, previous_element_index, 0);
1472               if (ErrorStatus != AAC_DEC_OK) {
1473                 self->frameOK = 0;
1474                 ErrorStatus = AAC_DEC_PARSE_ERROR;
1475                 break;
1476               }
1477             }
1478           }
1479         }
1480         break;
1481 
1482       case ID_END:
1483         break;
1484 
1485       default:
1486         ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
1487         self->frameOK = 0;
1488         break;
1489     }
1490 
1491     previous_element = type;
1492     element_count++;
1493 
1494   }   /* while ( (type != ID_END) ... ) */
1495 
1496   if ( !(flags & (AACDEC_CONCEAL|AACDEC_FLUSH)) )
1497   {
1498     /* Byte alignment with respect to the first bit of the raw_data_block(). */
1499     {
1500       FDKbyteAlign(bs, auStartAnchor);
1501     }
1502 
1503     /* Check if all bits of the raw_data_block() have been read. */
1504     if ( transportDec_GetAuBitsTotal(self->hInput, 0) > 0 ) {
1505       INT unreadBits = transportDec_GetAuBitsRemaining(self->hInput, 0);
1506       if ( unreadBits != 0 ) {
1507 
1508         self->frameOK = 0;
1509         /* Do not overwrite current error */
1510         if (ErrorStatus == AAC_DEC_OK && self->frameOK == 0) {
1511           ErrorStatus = AAC_DEC_PARSE_ERROR;
1512         }
1513         /* Always put the bitbuffer at the right position after the current Access Unit. */
1514         FDKpushBiDirectional(bs, unreadBits);
1515       }
1516     }
1517 
1518     /* Check the last element. The terminator (ID_END) has to be the last one (even if ER syntax is used). */
1519     if ( self->frameOK && type != ID_END ) {
1520       /* Do not overwrite current error */
1521       if (ErrorStatus == AAC_DEC_OK) {
1522         ErrorStatus = AAC_DEC_PARSE_ERROR;
1523       }
1524       self->frameOK = 0;
1525     }
1526   }
1527 
1528   /* More AAC channels than specified by the ASC not allowed. */
1529   if ( (aacChannels == 0 || aacChannels > self->aacChannels) && !(flags & (AACDEC_CONCEAL|AACDEC_FLUSH)) ) {
1530     {
1531       /* Do not overwrite current error */
1532       if (ErrorStatus == AAC_DEC_OK) {
1533         ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
1534       }
1535       self->frameOK = 0;
1536     }
1537     aacChannels = 0;
1538   }
1539   else if ( aacChannels > self->ascChannels ) {
1540     /* Do not overwrite current error */
1541     if (ErrorStatus == AAC_DEC_OK) {
1542       ErrorStatus = AAC_DEC_UNSUPPORTED_FORMAT;
1543     }
1544     self->frameOK = 0;
1545     aacChannels = 0;
1546   }
1547 
1548   if ( TRANSPORTDEC_OK != transportDec_CrcCheck(self->hInput) )
1549   {
1550     self->frameOK=0;
1551   }
1552 
1553   /* store or restore the number of channels */
1554   if ( self->frameOK && !(flags &(AACDEC_CONCEAL|AACDEC_FLUSH)) ) {
1555     self->concealChannels = aacChannels;  /* store */
1556     self->sbrEnabledPrev = self->sbrEnabled;
1557   } else {
1558     if (self->aacChannels > 0) {
1559       aacChannels = self->concealChannels;  /* restore */
1560       self->sbrEnabled = self->sbrEnabledPrev;
1561      }
1562   }
1563 
1564   /* Update number of output channels */
1565   self->streamInfo.numChannels = aacChannels;
1566 
1567  #ifdef TP_PCE_ENABLE
1568   if (pceRead == 1 || CProgramConfig_IsValid(pce)) {
1569     /* Set matrix mixdown infos if available from PCE. */
1570     pcmDmx_SetMatrixMixdownFromPce ( self->hPcmUtils,
1571                                      pce->MatrixMixdownIndexPresent,
1572                                      pce->MatrixMixdownIndex,
1573                                      pce->PseudoSurroundEnable );
1574   }
1575  #endif
1576 
1577   /* If there is no valid data to transfrom into time domain, return. */
1578   if ( ! IS_OUTPUT_VALID(ErrorStatus) ) {
1579     return ErrorStatus;
1580   }
1581 
1582   /*
1583     Inverse transform
1584   */
1585   {
1586     int stride, offset, c;
1587 
1588     /* Extract DRC control data and map it to channels (without bitstream delay) */
1589     aacDecoder_drcProlog (
1590             self->hDrcInfo,
1591             bs,
1592             self->pAacDecoderStaticChannelInfo,
1593             self->pce.ElementInstanceTag,
1594             self->chMapping,
1595             aacChannels
1596           );
1597 
1598     /* "c" iterates in canonical MPEG channel order */
1599     for (c=0; c < aacChannels; c++)
1600     {
1601       CAacDecoderChannelInfo *pAacDecoderChannelInfo;
1602 
1603       /* Select correct pAacDecoderChannelInfo for current channel */
1604       if (self->chMapping[c] >= aacChannels) {
1605         pAacDecoderChannelInfo = self->pAacDecoderChannelInfo[c];
1606       } else {
1607         pAacDecoderChannelInfo = self->pAacDecoderChannelInfo[self->chMapping[c]];
1608       }
1609 
1610       /* Setup offset and stride for time buffer traversal. */
1611       if (interleaved) {
1612         stride = aacChannels;
1613         offset = self->channelOutputMapping[aacChannels-1][c];
1614       } else {
1615         stride = 1;
1616         offset = self->channelOutputMapping[aacChannels-1][c] * self->streamInfo.aacSamplesPerFrame;
1617       }
1618 
1619 
1620       /*
1621         Conceal defective spectral data
1622       */
1623       CConcealment_Apply(&self->pAacDecoderStaticChannelInfo[c]->concealmentInfo,
1624                           pAacDecoderChannelInfo,
1625                           self->pAacDecoderStaticChannelInfo[c],
1626                          &self->samplingRateInfo,
1627                           self->streamInfo.aacSamplesPerFrame,
1628                           0,
1629                           (self->frameOK && !(flags&AACDEC_CONCEAL)),
1630                           self->flags
1631                         );
1632 
1633 
1634       if (flags & (AACDEC_INTR|AACDEC_CLRHIST)) {
1635         /* Reset DRC control data for this channel */
1636         aacDecoder_drcInitChannelData ( &self->pAacDecoderStaticChannelInfo[c]->drcData );
1637       }
1638       /* DRC processing */
1639       aacDecoder_drcApply (
1640               self->hDrcInfo,
1641               self->hSbrDecoder,
1642               pAacDecoderChannelInfo,
1643              &self->pAacDecoderStaticChannelInfo[c]->drcData,
1644               c,
1645               self->streamInfo.aacSamplesPerFrame,
1646               self->sbrEnabled
1647             );
1648 
1649       if ( flags&AACDEC_FLUSH ) {
1650         FDKmemclear(pAacDecoderChannelInfo->pSpectralCoefficient, sizeof(FIXP_DBL)*self->streamInfo.aacSamplesPerFrame);
1651       }
1652 
1653       switch (pAacDecoderChannelInfo->renderMode)
1654       {
1655         case AACDEC_RENDER_IMDCT:
1656           CBlock_FrequencyToTime(
1657                   self->pAacDecoderStaticChannelInfo[c],
1658                   pAacDecoderChannelInfo,
1659                   pTimeData + offset,
1660                   self->streamInfo.aacSamplesPerFrame,
1661                   stride,
1662                   (self->frameOK && !(flags&AACDEC_CONCEAL)),
1663                   self->aacCommonData.workBufferCore1->mdctOutTemp
1664                   );
1665           break;
1666         case AACDEC_RENDER_ELDFB:
1667           CBlock_FrequencyToTimeLowDelay(
1668                   self->pAacDecoderStaticChannelInfo[c],
1669                   pAacDecoderChannelInfo,
1670                   pTimeData + offset,
1671                   self->streamInfo.aacSamplesPerFrame,
1672                   stride
1673                   );
1674           break;
1675         default:
1676           ErrorStatus = AAC_DEC_UNKNOWN;
1677           break;
1678       }
1679       if ( flags&AACDEC_FLUSH ) {
1680         FDKmemclear(self->pAacDecoderStaticChannelInfo[c]->pOverlapBuffer, OverlapBufferSize*sizeof(FIXP_DBL));
1681       }
1682     }
1683 
1684 
1685     /* Extract DRC control data and map it to channels (with bitstream delay) */
1686     aacDecoder_drcEpilog (
1687             self->hDrcInfo,
1688             bs,
1689             self->pAacDecoderStaticChannelInfo,
1690             self->pce.ElementInstanceTag,
1691             self->chMapping,
1692             aacChannels
1693           );
1694   }
1695 
1696 
1697   /* Reorder channel type information tables.  */
1698   {
1699     AUDIO_CHANNEL_TYPE types[(6)];
1700     UCHAR idx[(6)];
1701     int c;
1702 
1703     FDK_ASSERT(sizeof(self->channelType) == sizeof(types));
1704     FDK_ASSERT(sizeof(self->channelIndices) == sizeof(idx));
1705 
1706     FDKmemcpy(types, self->channelType, sizeof(types));
1707     FDKmemcpy(idx, self->channelIndices, sizeof(idx));
1708 
1709     for (c=0; c<aacChannels; c++) {
1710       self->channelType[self->channelOutputMapping[aacChannels-1][c]] = types[c];
1711       self->channelIndices[self->channelOutputMapping[aacChannels-1][c]] = idx[c];
1712     }
1713   }
1714 
1715   self->blockNumber++;
1716 
1717   return ErrorStatus;
1718 }
1719 
1720 /*!
1721   \brief returns the streaminfo pointer
1722 
1723   The function hands back a pointer to the streaminfo structure
1724 
1725   \return pointer to the struct
1726 */
CAacDecoder_GetStreamInfo(HANDLE_AACDECODER self)1727 LINKSPEC_CPP CStreamInfo* CAacDecoder_GetStreamInfo ( HANDLE_AACDECODER self )
1728 {
1729   if (!self) {
1730     return NULL;
1731   }
1732   return &self->streamInfo;
1733 }
1734 
1735 
1736 
1737 
1738