1
2/* -----------------------------------------------------------------------------------------------------------
3Software License for The Fraunhofer FDK AAC Codec Library for Android
4
5� Copyright  1995 - 2013 Fraunhofer-Gesellschaft zur F�rderung der angewandten Forschung e.V.
6  All rights reserved.
7
8 1.    INTRODUCTION
9The Fraunhofer FDK AAC Codec Library for Android ("FDK AAC Codec") is software that implements
10the MPEG Advanced Audio Coding ("AAC") encoding and decoding scheme for digital audio.
11This FDK AAC Codec software is intended to be used on a wide variety of Android devices.
12
13AAC's HE-AAC and HE-AAC v2 versions are regarded as today's most efficient general perceptual
14audio codecs. AAC-ELD is considered the best-performing full-bandwidth communications codec by
15independent studies and is widely deployed. AAC has been standardized by ISO and IEC as part
16of the MPEG specifications.
17
18Patent licenses for necessary patent claims for the FDK AAC Codec (including those of Fraunhofer)
19may be obtained through Via Licensing (www.vialicensing.com) or through the respective patent owners
20individually for the purpose of encoding or decoding bit streams in products that are compliant with
21the ISO/IEC MPEG audio standards. Please note that most manufacturers of Android devices already license
22these patent claims through Via Licensing or directly from the patent owners, and therefore FDK AAC Codec
23software may already be covered under those patent licenses when it is used for those licensed purposes only.
24
25Commercially-licensed AAC software libraries, including floating-point versions with enhanced sound quality,
26are also available from Fraunhofer. Users are encouraged to check the Fraunhofer website for additional
27applications information and documentation.
28
292.    COPYRIGHT LICENSE
30
31Redistribution and use in source and binary forms, with or without modification, are permitted without
32payment of copyright license fees provided that you satisfy the following conditions:
33
34You must retain the complete text of this software license in redistributions of the FDK AAC Codec or
35your modifications thereto in source code form.
36
37You must retain the complete text of this software license in the documentation and/or other materials
38provided with redistributions of the FDK AAC Codec or your modifications thereto in binary form.
39You must make available free of charge copies of the complete source code of the FDK AAC Codec and your
40modifications thereto to recipients of copies in binary form.
41
42The name of Fraunhofer may not be used to endorse or promote products derived from this library without
43prior written permission.
44
45You may not charge copyright license fees for anyone to use, copy or distribute the FDK AAC Codec
46software or your modifications thereto.
47
48Your modified versions of the FDK AAC Codec must carry prominent notices stating that you changed the software
49and 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
533.    NO PATENT LICENSE
54
55NO EXPRESS OR IMPLIED LICENSES TO ANY PATENT CLAIMS, including without limitation the patents of Fraunhofer,
56ARE GRANTED BY THIS SOFTWARE LICENSE. Fraunhofer provides no warranty of patent non-infringement with
57respect to this software.
58
59You may use this FDK AAC Codec software or modifications thereto only for purposes that are authorized
60by appropriate patent licenses.
61
624.    DISCLAIMER
63
64This 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
66of merchantability and fitness for a particular purpose. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
67CONTRIBUTORS BE LIABLE for any direct, indirect, incidental, special, exemplary, or consequential damages,
68including but not limited to procurement of substitute goods or services; loss of use, data, or profits,
69or business interruption, however caused and on any theory of liability, whether in contract, strict
70liability, or tort (including negligence), arising in any way out of the use of this software, even if
71advised of the possibility of such damage.
72
735.    CONTACT INFORMATION
74
75Fraunhofer Institute for Integrated Circuits IIS
76Attention: Audio and Multimedia Departments - FDK AAC LL
77Am Wolfsmantel 33
7891058 Erlangen, Germany
79
80www.iis.fraunhofer.de/amm
81amm-info@iis.fraunhofer.de
82----------------------------------------------------------------------------------------------------------- */
83
84/*****************************  MPEG-4 AAC Decoder  **************************
85
86   Author(s):   Manuel Jander
87   Description:
88
89******************************************************************************/
90
91#include "aacdecoder_lib.h"
92
93#include "aac_ram.h"
94#include "aacdecoder.h"
95#include "tpdec_lib.h"
96#include "FDK_core.h" /* FDK_tools version info */
97
98
99 #include "sbrdecoder.h"
100
101
102
103
104#include "conceal.h"
105
106 #include "aacdec_drc.h"
107
108
109
110/* Decoder library info */
111#define AACDECODER_LIB_VL0 2
112#define AACDECODER_LIB_VL1 5
113#define AACDECODER_LIB_VL2 10
114#define AACDECODER_LIB_TITLE "AAC Decoder Lib"
115#define AACDECODER_LIB_BUILD_DATE __DATE__
116#define AACDECODER_LIB_BUILD_TIME __TIME__
117
118static AAC_DECODER_ERROR
119setConcealMethod ( const HANDLE_AACDECODER  self,
120                   const INT                method );
121
122
123LINKSPEC_CPP AAC_DECODER_ERROR aacDecoder_GetFreeBytes ( const HANDLE_AACDECODER  self, UINT *pFreeBytes){
124
125  /* reset free bytes */
126  *pFreeBytes = 0;
127
128  /* check handle */
129  if(!self)
130    return AAC_DEC_INVALID_HANDLE;
131
132  /* return nr of free bytes */
133  HANDLE_FDK_BITSTREAM hBs = transportDec_GetBitstream(self->hInput, 0);
134  *pFreeBytes = FDKgetFreeBits(hBs) >> 3;
135
136  /* success */
137  return AAC_DEC_OK;
138}
139
140/**
141 * Config Decoder using a CSAudioSpecificConfig struct.
142 */
143static
144LINKSPEC_CPP AAC_DECODER_ERROR aacDecoder_Config(HANDLE_AACDECODER self, const CSAudioSpecificConfig *pAscStruct)
145{
146  AAC_DECODER_ERROR err;
147
148  /* Initialize AAC core decoder, and update self->streaminfo */
149  err = CAacDecoder_Init(self, pAscStruct);
150
151  return err;
152}
153
154LINKSPEC_CPP AAC_DECODER_ERROR aacDecoder_ConfigRaw (
155        HANDLE_AACDECODER self,
156        UCHAR *conf[],
157        const UINT length[] )
158{
159  AAC_DECODER_ERROR err = AAC_DEC_OK;
160  TRANSPORTDEC_ERROR   errTp;
161  UINT layer, nrOfLayers = self->nrOfLayers;
162
163  for(layer = 0; layer < nrOfLayers; layer++){
164    if(length[layer] > 0){
165      errTp = transportDec_OutOfBandConfig(self->hInput, conf[layer], length[layer], layer);
166      if (errTp != TRANSPORTDEC_OK) {
167        switch (errTp) {
168        case TRANSPORTDEC_NEED_TO_RESTART:
169          err = AAC_DEC_NEED_TO_RESTART;
170          break;
171        case TRANSPORTDEC_UNSUPPORTED_FORMAT:
172          err = AAC_DEC_UNSUPPORTED_FORMAT;
173          break;
174        default:
175          err = AAC_DEC_UNKNOWN;
176          break;
177        }
178        /* if baselayer is OK we continue decoding */
179        if(layer  >= 1){
180          self->nrOfLayers = layer;
181        }
182        break;
183      }
184    }
185  }
186
187  return err;
188}
189
190
191
192static INT aacDecoder_ConfigCallback(void *handle, const CSAudioSpecificConfig *pAscStruct)
193{
194  HANDLE_AACDECODER self = (HANDLE_AACDECODER)handle;
195  AAC_DECODER_ERROR err = AAC_DEC_OK;
196  TRANSPORTDEC_ERROR errTp;
197
198  {
199    {
200      err = aacDecoder_Config(self, pAscStruct);
201    }
202  }
203  if (err == AAC_DEC_OK) {
204    if ( self->flags & (AC_USAC|AC_RSVD50|AC_LD|AC_ELD)
205      && CConcealment_GetDelay(&self->concealCommonData) > 0 )
206    {
207      /* Revert to error concealment method Noise Substitution.
208         Because interpolation is not implemented for USAC/RSVD50 or
209         the additional delay is unwanted for low delay codecs. */
210      setConcealMethod(self, 1);
211#ifdef DEBUG
212      FDKprintf("  Concealment method was reverted to 1 !\n");
213#endif
214    }
215    errTp = TRANSPORTDEC_OK;
216  } else {
217    if (IS_INIT_ERROR(err)) {
218      errTp = TRANSPORTDEC_UNSUPPORTED_FORMAT;
219    } /* Fatal errors */
220    else if (err == AAC_DEC_NEED_TO_RESTART) {
221      errTp = TRANSPORTDEC_NEED_TO_RESTART;
222    } else {
223      errTp = TRANSPORTDEC_UNKOWN_ERROR;
224    }
225  }
226
227  return errTp;
228}
229
230
231
232LINKSPEC_CPP AAC_DECODER_ERROR
233aacDecoder_AncDataInit ( HANDLE_AACDECODER self,
234                         UCHAR *buffer,
235                         int size )
236{
237  CAncData *ancData = &self->ancData;
238
239  return CAacDecoder_AncDataInit(ancData, buffer, size);
240}
241
242
243LINKSPEC_CPP AAC_DECODER_ERROR
244aacDecoder_AncDataGet ( HANDLE_AACDECODER self,
245                        int     index,
246                        UCHAR **ptr,
247                        int    *size )
248{
249  CAncData *ancData = &self->ancData;
250
251  return CAacDecoder_AncDataGet(ancData, index, ptr, size);
252}
253
254
255static AAC_DECODER_ERROR
256setConcealMethod ( const HANDLE_AACDECODER  self,   /*!< Handle of the decoder instance */
257                   const INT                method )
258{
259  AAC_DECODER_ERROR errorStatus = AAC_DEC_OK;
260  CConcealParams  *pConcealData = NULL;
261  HANDLE_SBRDECODER hSbrDec = NULL;
262  HANDLE_AAC_DRC hDrcInfo = NULL;
263  HANDLE_PCM_DOWNMIX hPcmDmx = NULL;
264  CConcealmentMethod backupMethod = ConcealMethodNone;
265  int backupDelay = 0;
266  int bsDelay = 0;
267
268  /* check decoder handle */
269  if (self != NULL) {
270    pConcealData = &self->concealCommonData;
271    hSbrDec = self->hSbrDecoder;
272    hDrcInfo = self->hDrcInfo;
273    hPcmDmx = self->hPcmUtils;
274  }
275
276
277  /* Get current method/delay */
278  backupMethod = CConcealment_GetMethod(pConcealData);
279  backupDelay  = CConcealment_GetDelay(pConcealData);
280
281  /* Be sure to set AAC and SBR concealment method simultaneously! */
282  errorStatus =
283    CConcealment_SetParams(
284      pConcealData,
285      (int)method,                         // concealMethod
286      AACDEC_CONCEAL_PARAM_NOT_SPECIFIED,  // concealFadeOutSlope
287      AACDEC_CONCEAL_PARAM_NOT_SPECIFIED,  // concealFadeInSlope
288      AACDEC_CONCEAL_PARAM_NOT_SPECIFIED,  // concealMuteRelease
289      AACDEC_CONCEAL_PARAM_NOT_SPECIFIED   // concealComfNoiseLevel
290    );
291  if ( (errorStatus != AAC_DEC_OK)
292    && (errorStatus != AAC_DEC_INVALID_HANDLE) ) {
293    goto bail;
294  }
295
296  /* Get new delay */
297  bsDelay = CConcealment_GetDelay(pConcealData);
298
299  {
300    SBR_ERROR sbrErr = SBRDEC_OK;
301
302    /* set SBR bitstream delay */
303    sbrErr = sbrDecoder_SetParam (
304      hSbrDec,
305      SBR_SYSTEM_BITSTREAM_DELAY,
306      bsDelay
307    );
308
309    switch (sbrErr) {
310    case SBRDEC_OK:
311    case SBRDEC_NOT_INITIALIZED:
312      if (self != NULL) {
313        /* save the param value and set later
314           (when SBR has been initialized) */
315        self->sbrParams.bsDelay = bsDelay;
316      }
317      break;
318    default:
319      errorStatus = AAC_DEC_SET_PARAM_FAIL;
320      goto bail;
321    }
322  }
323
324  errorStatus =
325    aacDecoder_drcSetParam (
326      hDrcInfo,
327      DRC_BS_DELAY,
328      bsDelay
329    );
330  if ( (errorStatus != AAC_DEC_OK)
331    && (errorStatus != AAC_DEC_INVALID_HANDLE) ) {
332    goto bail;
333  }
334
335  if (errorStatus == AAC_DEC_OK) {
336    PCMDMX_ERROR err =
337      pcmDmx_SetParam (
338        hPcmDmx,
339        DMX_BS_DATA_DELAY,
340        bsDelay
341      );
342    switch (err) {
343    case PCMDMX_INVALID_HANDLE:
344      errorStatus = AAC_DEC_INVALID_HANDLE;
345    case PCMDMX_OK:
346      break;
347    default:
348      errorStatus = AAC_DEC_SET_PARAM_FAIL;
349      goto bail;
350    }
351  }
352
353
354bail:
355  if ( (errorStatus != AAC_DEC_OK)
356    && (errorStatus != AAC_DEC_INVALID_HANDLE) )
357  {
358    /* Revert to the initial state */
359    CConcealment_SetParams (
360        pConcealData,
361        (int)backupMethod,
362        AACDEC_CONCEAL_PARAM_NOT_SPECIFIED,
363        AACDEC_CONCEAL_PARAM_NOT_SPECIFIED,
364        AACDEC_CONCEAL_PARAM_NOT_SPECIFIED,
365        AACDEC_CONCEAL_PARAM_NOT_SPECIFIED
366      );
367    /* Revert SBR bitstream delay */
368    sbrDecoder_SetParam (
369        hSbrDec,
370        SBR_SYSTEM_BITSTREAM_DELAY,
371        backupDelay
372      );
373    /* Revert DRC bitstream delay */
374    aacDecoder_drcSetParam (
375        hDrcInfo,
376        DRC_BS_DELAY,
377        backupDelay
378      );
379    /* Revert PCM mixdown bitstream delay */
380    pcmDmx_SetParam (
381        hPcmDmx,
382        DMX_BS_DATA_DELAY,
383        backupDelay
384      );
385  }
386
387  return errorStatus;
388}
389
390
391LINKSPEC_CPP AAC_DECODER_ERROR
392aacDecoder_SetParam ( const HANDLE_AACDECODER  self,   /*!< Handle of the decoder instance */
393                      const AACDEC_PARAM       param,  /*!< Parameter to set               */
394                      const INT                value)  /*!< Parameter valued               */
395{
396  AAC_DECODER_ERROR errorStatus = AAC_DEC_OK;
397  CConcealParams  *pConcealData = NULL;
398  HANDLE_AAC_DRC hDrcInfo = NULL;
399  HANDLE_PCM_DOWNMIX hPcmDmx = NULL;
400  TDLimiterPtr hPcmTdl = NULL;
401
402  /* check decoder handle */
403  if (self != NULL) {
404    pConcealData = &self->concealCommonData;
405    hDrcInfo = self->hDrcInfo;
406    hPcmDmx = self->hPcmUtils;
407    hPcmTdl = self->hLimiter;
408  } else {
409    errorStatus = AAC_DEC_INVALID_HANDLE;
410  }
411
412  /* configure the subsystems */
413  switch (param)
414  {
415  case AAC_PCM_OUTPUT_INTERLEAVED:
416    if (value < 0 || value > 1) {
417      return AAC_DEC_SET_PARAM_FAIL;
418    }
419    if (self == NULL) {
420      return AAC_DEC_INVALID_HANDLE;
421    }
422    self->outputInterleaved = value;
423    break;
424
425  case AAC_PCM_MIN_OUTPUT_CHANNELS:
426    if (value < -1 || value > (8)) {
427      return AAC_DEC_SET_PARAM_FAIL;
428    }
429    {
430      PCMDMX_ERROR err;
431
432      err = pcmDmx_SetParam (
433              hPcmDmx,
434              MIN_NUMBER_OF_OUTPUT_CHANNELS,
435              value );
436
437      switch (err) {
438      case PCMDMX_OK:
439        break;
440      case PCMDMX_INVALID_HANDLE:
441        return AAC_DEC_INVALID_HANDLE;
442      default:
443        return AAC_DEC_SET_PARAM_FAIL;
444      }
445    }
446    break;
447
448  case AAC_PCM_MAX_OUTPUT_CHANNELS:
449    if (value < -1 || value > (8)) {
450      return AAC_DEC_SET_PARAM_FAIL;
451    }
452    {
453      PCMDMX_ERROR err;
454
455      err = pcmDmx_SetParam (
456              hPcmDmx,
457              MAX_NUMBER_OF_OUTPUT_CHANNELS,
458              value );
459
460      switch (err) {
461      case PCMDMX_OK:
462        break;
463      case PCMDMX_INVALID_HANDLE:
464        return AAC_DEC_INVALID_HANDLE;
465      default:
466        return AAC_DEC_SET_PARAM_FAIL;
467      }
468    }
469    break;
470
471  case AAC_PCM_DUAL_CHANNEL_OUTPUT_MODE:
472    {
473      PCMDMX_ERROR err;
474
475      err = pcmDmx_SetParam (
476              hPcmDmx,
477              DMX_DUAL_CHANNEL_MODE,
478              value );
479
480      switch (err) {
481      case PCMDMX_OK:
482        break;
483      case PCMDMX_INVALID_HANDLE:
484        return AAC_DEC_INVALID_HANDLE;
485      default:
486        return AAC_DEC_SET_PARAM_FAIL;
487      }
488    }
489    break;
490
491
492  case AAC_PCM_LIMITER_ENABLE:
493    if (value < -1 || value > 1) {
494      return AAC_DEC_SET_PARAM_FAIL;
495    }
496    if (self == NULL) {
497      return AAC_DEC_INVALID_HANDLE;
498    }
499    self->limiterEnableUser = value;
500    break;
501
502  case AAC_PCM_LIMITER_ATTACK_TIME:
503    if (value <= 0) {  /* module function converts value to unsigned */
504      return AAC_DEC_SET_PARAM_FAIL;
505    }
506    switch (setLimiterAttack(hPcmTdl, value)) {
507    case TDLIMIT_OK:
508      break;
509    case TDLIMIT_INVALID_HANDLE:
510      return AAC_DEC_INVALID_HANDLE;
511    case TDLIMIT_INVALID_PARAMETER:
512    default:
513      return AAC_DEC_SET_PARAM_FAIL;
514    }
515    break;
516
517  case AAC_PCM_LIMITER_RELEAS_TIME:
518    if (value <= 0) {  /* module function converts value to unsigned */
519      return AAC_DEC_SET_PARAM_FAIL;
520    }
521    switch (setLimiterRelease(hPcmTdl, value)) {
522    case TDLIMIT_OK:
523      break;
524    case TDLIMIT_INVALID_HANDLE:
525      return AAC_DEC_INVALID_HANDLE;
526    case TDLIMIT_INVALID_PARAMETER:
527    default:
528      return AAC_DEC_SET_PARAM_FAIL;
529    }
530    break;
531
532  case AAC_PCM_OUTPUT_CHANNEL_MAPPING:
533    switch (value) {
534      case 0:
535        if (self != NULL) {
536          self->channelOutputMapping = channelMappingTablePassthrough;
537        }
538        break;
539      case 1:
540        if (self != NULL) {
541          self->channelOutputMapping = channelMappingTableWAV;
542        }
543        break;
544      default:
545        errorStatus = AAC_DEC_SET_PARAM_FAIL;
546        break;
547    }
548    break;
549
550
551  case AAC_QMF_LOWPOWER:
552    if (value < -1 || value > 1) {
553      return AAC_DEC_SET_PARAM_FAIL;
554    }
555    if (self == NULL) {
556      return AAC_DEC_INVALID_HANDLE;
557    }
558
559    /**
560     * Set QMF mode (might be overriden)
561     *  0:HQ (complex)
562     *  1:LP (partially complex)
563     */
564    self->qmfModeUser = (QMF_MODE)value;
565    break;
566
567
568  case AAC_DRC_ATTENUATION_FACTOR:
569    /* DRC compression factor (where 0 is no and 127 is max compression) */
570    errorStatus =
571      aacDecoder_drcSetParam (
572        hDrcInfo,
573        DRC_CUT_SCALE,
574        value
575      );
576    break;
577
578  case AAC_DRC_BOOST_FACTOR:
579    /* DRC boost factor (where 0 is no and 127 is max boost) */
580    errorStatus =
581      aacDecoder_drcSetParam (
582        hDrcInfo,
583        DRC_BOOST_SCALE,
584        value
585      );
586    break;
587
588  case AAC_DRC_REFERENCE_LEVEL:
589    /* DRC reference level quantized in 0.25dB steps using values [0..127] it is '-' for analog scaling */
590    errorStatus =
591      aacDecoder_drcSetParam (
592        hDrcInfo,
593        TARGET_REF_LEVEL,
594        value
595      );
596    break;
597
598  case AAC_DRC_HEAVY_COMPRESSION:
599    /* Don't need to overwrite cut/boost values */
600    errorStatus =
601      aacDecoder_drcSetParam (
602        hDrcInfo,
603        APPLY_HEAVY_COMPRESSION,
604        value
605      );
606    break;
607
608
609  case AAC_TPDEC_CLEAR_BUFFER:
610    transportDec_SetParam(self->hInput, TPDEC_PARAM_RESET, 1);
611    self->streamInfo.numLostAccessUnits = 0;
612    self->streamInfo.numBadBytes = 0;
613    self->streamInfo.numTotalBytes = 0;
614    /* aacDecoder_SignalInterruption(self); */
615    break;
616
617  case AAC_CONCEAL_METHOD:
618    /* Changing the concealment method can introduce additional bitstream delay. And
619       that in turn affects sub libraries and modules which makes the whole thing quite
620       complex.  So the complete changing routine is packed into a helper function which
621       keeps all modules and libs in a consistent state even in the case an error occures. */
622    errorStatus = setConcealMethod ( self, value );
623    break;
624
625  default:
626    return AAC_DEC_SET_PARAM_FAIL;
627  }  /* switch(param) */
628
629  return (errorStatus);
630}
631
632
633LINKSPEC_CPP HANDLE_AACDECODER aacDecoder_Open(TRANSPORT_TYPE transportFmt, UINT nrOfLayers)
634{
635  AAC_DECODER_INSTANCE *aacDec = NULL;
636  HANDLE_TRANSPORTDEC pIn;
637  int err = 0;
638
639  /* Allocate transport layer struct. */
640  pIn = transportDec_Open(transportFmt, TP_FLAG_MPEG4);
641  if (pIn == NULL) {
642    return NULL;
643  }
644
645  transportDec_SetParam(pIn, TPDEC_PARAM_IGNORE_BUFFERFULLNESS, 1);
646
647  /* Allocate AAC decoder core struct. */
648  aacDec = CAacDecoder_Open(transportFmt);
649
650  if (aacDec == NULL) {
651    transportDec_Close(&pIn);
652    goto bail;
653  }
654  aacDec->hInput = pIn;
655
656  aacDec->nrOfLayers = nrOfLayers;
657
658  aacDec->channelOutputMapping = channelMappingTableWAV;
659
660  /* Register Config Update callback. */
661  transportDec_RegisterAscCallback(pIn, aacDecoder_ConfigCallback, (void*)aacDec);
662
663  /* open SBR decoder */
664  if ( SBRDEC_OK != sbrDecoder_Open ( &aacDec->hSbrDecoder )) {
665    err = -1;
666    goto bail;
667  }
668  aacDec->qmfModeUser = NOT_DEFINED;
669  transportDec_RegisterSbrCallback(aacDec->hInput, (cbSbr_t)sbrDecoder_Header, (void*)aacDec->hSbrDecoder);
670
671
672  pcmDmx_Open( &aacDec->hPcmUtils );
673  if (aacDec->hPcmUtils == NULL) {
674    err = -1;
675    goto bail;
676  }
677
678  aacDec->hLimiter = createLimiter(TDL_ATTACK_DEFAULT_MS, TDL_RELEASE_DEFAULT_MS, SAMPLE_MAX, (8), 96000);
679  if (NULL == aacDec->hLimiter) {
680    err = -1;
681    goto bail;
682  }
683  aacDec->limiterEnableUser = (UCHAR)-1;
684  aacDec->limiterEnableCurr = 0;
685
686
687
688  /* Assure that all modules have same delay */
689  if ( setConcealMethod(aacDec, CConcealment_GetMethod(&aacDec->concealCommonData)) ) {
690    err = -1;
691    goto bail;
692  }
693
694bail:
695  if (err == -1) {
696    aacDecoder_Close(aacDec);
697    aacDec = NULL;
698  }
699  return aacDec;
700}
701
702LINKSPEC_CPP AAC_DECODER_ERROR aacDecoder_Fill(
703        HANDLE_AACDECODER   self,
704        UCHAR              *pBuffer[],
705        const UINT          bufferSize[],
706        UINT               *pBytesValid
707        )
708{
709  TRANSPORTDEC_ERROR tpErr;
710  /* loop counter for layers; if not TT_MP4_RAWPACKETS used as index for only
711     available layer                                                           */
712  INT layer      = 0;
713  INT nrOfLayers = self->nrOfLayers;
714
715  {
716    for (layer = 0; layer < nrOfLayers; layer++){
717      {
718        tpErr = transportDec_FillData( self->hInput, pBuffer[layer], bufferSize[layer], &pBytesValid[layer], layer );
719        if (tpErr != TRANSPORTDEC_OK) {
720          return AAC_DEC_UNKNOWN;  /* Must be an internal error */
721        }
722      }
723    }
724  }
725
726  return AAC_DEC_OK;
727}
728
729
730static void aacDecoder_SignalInterruption(HANDLE_AACDECODER self)
731{
732  CAacDecoder_SignalInterruption(self);
733
734  if ( self->hSbrDecoder != NULL ) {
735    sbrDecoder_SetParam(self->hSbrDecoder, SBR_BS_INTERRUPTION, 0);
736  }
737}
738
739static void aacDecoder_UpdateBitStreamCounters(CStreamInfo *pSi, HANDLE_FDK_BITSTREAM hBs, int nBits, AAC_DECODER_ERROR ErrorStatus)
740{
741  /* calculate bit difference (amount of bits moved forward) */
742  nBits = nBits - FDKgetValidBits(hBs);
743
744  /* Note: The amount of bits consumed might become negative when parsing a
745     bit stream with several sub frames, and we find out at the last sub frame
746     that the total frame length does not match the sum of sub frame length.
747     If this happens, the transport decoder might want to rewind to the supposed
748     ending of the transport frame, and this position might be before the last
749     access unit beginning. */
750
751  /* Calc bitrate. */
752  if (pSi->frameSize > 0) {
753    pSi->bitRate = (nBits * pSi->sampleRate)/pSi->frameSize;
754  }
755
756  /* bit/byte counters */
757  {
758    int nBytes;
759
760    nBytes = nBits>>3;
761    pSi->numTotalBytes += nBytes;
762    if (IS_OUTPUT_VALID(ErrorStatus)) {
763      pSi->numTotalAccessUnits++;
764    }
765    if (IS_DECODE_ERROR(ErrorStatus)) {
766      pSi->numBadBytes += nBytes;
767      pSi->numBadAccessUnits++;
768    }
769  }
770}
771
772static INT aacDecoder_EstimateNumberOfLostFrames(HANDLE_AACDECODER self)
773{
774  INT n;
775
776  transportDec_GetMissingAccessUnitCount( &n, self->hInput);
777
778  return n;
779}
780
781LINKSPEC_CPP AAC_DECODER_ERROR aacDecoder_DecodeFrame(
782        HANDLE_AACDECODER  self,
783        INT_PCM           *pTimeData,
784        const INT          timeDataSize,
785        const UINT         flags)
786{
787    AAC_DECODER_ERROR ErrorStatus;
788    INT layer;
789    INT nBits;
790    INT interleaved = self->outputInterleaved;
791    HANDLE_FDK_BITSTREAM hBs;
792    int fTpInterruption = 0;  /* Transport originated interruption detection. */
793    int fTpConceal = 0;       /* Transport originated concealment. */
794
795
796    if (self == NULL) {
797      return AAC_DEC_INVALID_HANDLE;
798    }
799
800    if (flags & AACDEC_INTR) {
801      self->streamInfo.numLostAccessUnits = 0;
802    }
803
804    hBs = transportDec_GetBitstream(self->hInput, 0);
805
806    /* Get current bits position for bitrate calculation. */
807    nBits = FDKgetValidBits(hBs);
808    if (! (flags & (AACDEC_CONCEAL | AACDEC_FLUSH) ) )
809    {
810      TRANSPORTDEC_ERROR err;
811
812      for(layer = 0; layer < self->nrOfLayers; layer++)
813      {
814        err = transportDec_ReadAccessUnit(self->hInput, layer);
815        if (err != TRANSPORTDEC_OK) {
816          switch (err) {
817          case TRANSPORTDEC_NOT_ENOUGH_BITS:
818            ErrorStatus = AAC_DEC_NOT_ENOUGH_BITS;
819            goto bail;
820          case TRANSPORTDEC_SYNC_ERROR:
821            self->streamInfo.numLostAccessUnits = aacDecoder_EstimateNumberOfLostFrames(self);
822            fTpInterruption = 1;
823            break;
824          case TRANSPORTDEC_NEED_TO_RESTART:
825            ErrorStatus = AAC_DEC_NEED_TO_RESTART;
826            goto bail;
827          case TRANSPORTDEC_CRC_ERROR:
828            fTpConceal = 1;
829            break;
830          default:
831            ErrorStatus = AAC_DEC_UNKNOWN;
832            goto bail;
833          }
834        }
835      }
836    } else {
837      if (self->streamInfo.numLostAccessUnits > 0) {
838        self->streamInfo.numLostAccessUnits--;
839      }
840    }
841
842    /* Signal bit stream interruption to other modules if required. */
843    if ( fTpInterruption || (flags & (AACDEC_INTR|AACDEC_CLRHIST)) )
844    {
845      sbrDecoder_SetParam(self->hSbrDecoder, SBR_CLEAR_HISTORY, (flags&AACDEC_CLRHIST));
846      aacDecoder_SignalInterruption(self);
847      if ( ! (flags & AACDEC_INTR) ) {
848        ErrorStatus = AAC_DEC_TRANSPORT_SYNC_ERROR;
849        goto bail;
850      }
851    }
852
853    /* Empty bit buffer in case of flush request. */
854    if (flags & AACDEC_FLUSH)
855    {
856      transportDec_SetParam(self->hInput, TPDEC_PARAM_RESET, 1);
857      self->streamInfo.numLostAccessUnits = 0;
858      self->streamInfo.numBadBytes = 0;
859      self->streamInfo.numTotalBytes = 0;
860    }
861    /* Reset the output delay field. The modules will add their figures one after another. */
862    self->streamInfo.outputDelay = 0;
863
864    if (self->limiterEnableUser==(UCHAR)-1) {
865      /* Enbale limiter for all non-lowdelay AOT's. */
866      self->limiterEnableCurr = ( self->flags & (AC_LD|AC_ELD) ) ? 0 : 1;
867    }
868    else {
869      /* Use limiter configuration as requested. */
870      self->limiterEnableCurr = self->limiterEnableUser;
871    }
872    /* reset limiter gain on a per frame basis */
873    self->extGain[0] = FL2FXCONST_DBL(1.0f/(float)(1<<TDL_GAIN_SCALING));
874
875
876    ErrorStatus = CAacDecoder_DecodeFrame(self,
877                                          flags | (fTpConceal ? AACDEC_CONCEAL : 0),
878                                          pTimeData,
879                                          timeDataSize,
880                                          interleaved);
881
882    if (!(flags & (AACDEC_CONCEAL|AACDEC_FLUSH))) {
883      TRANSPORTDEC_ERROR tpErr;
884      tpErr = transportDec_EndAccessUnit(self->hInput);
885      if (tpErr != TRANSPORTDEC_OK) {
886        self->frameOK = 0;
887      }
888    }
889
890    /* If the current pTimeData does not contain a valid signal, there nothing else we can do, so bail. */
891    if ( ! IS_OUTPUT_VALID(ErrorStatus) ) {
892      goto bail;
893    }
894
895    {
896      /* Export data into streaminfo structure */
897      self->streamInfo.sampleRate = self->streamInfo.aacSampleRate;
898      self->streamInfo.frameSize  = self->streamInfo.aacSamplesPerFrame;
899    }
900    self->streamInfo.numChannels = self->streamInfo.aacNumChannels;
901
902
903
904    CAacDecoder_SyncQmfMode(self);
905
906/* sbr decoder */
907
908    if (ErrorStatus || (flags & AACDEC_CONCEAL) || self->pAacDecoderStaticChannelInfo[0]->concealmentInfo.concealState > ConcealState_FadeIn)
909    {
910      self->frameOK = 0;  /* if an error has occured do concealment in the SBR decoder too */
911    }
912
913    if (self->sbrEnabled)
914    {
915      SBR_ERROR sbrError = SBRDEC_OK;
916      int chOutMapIdx = ((self->chMapIndex==0) && (self->streamInfo.numChannels<7)) ? self->streamInfo.numChannels : self->chMapIndex;
917
918      /* set params */
919      sbrDecoder_SetParam ( self->hSbrDecoder,
920                            SBR_SYSTEM_BITSTREAM_DELAY,
921                            self->sbrParams.bsDelay);
922      sbrDecoder_SetParam ( self->hSbrDecoder,
923                            SBR_FLUSH_DATA,
924                            (flags & AACDEC_FLUSH) );
925
926      if ( self->streamInfo.aot == AOT_ER_AAC_ELD ) {
927        /* Configure QMF */
928        sbrDecoder_SetParam ( self->hSbrDecoder,
929                              SBR_LD_QMF_TIME_ALIGN,
930                              (self->flags & AC_LD_MPS) ? 1 : 0 );
931      }
932
933      {
934        PCMDMX_ERROR dmxErr;
935        INT  maxOutCh = 0;
936
937        dmxErr = pcmDmx_GetParam(self->hPcmUtils, MAX_NUMBER_OF_OUTPUT_CHANNELS, &maxOutCh);
938        if ( (dmxErr == PCMDMX_OK) && (maxOutCh == 1) ) {
939          /* Disable PS processing if we have to create a mono output signal. */
940          self->psPossible = 0;
941        }
942      }
943
944
945      /* apply SBR processing */
946      sbrError = sbrDecoder_Apply ( self->hSbrDecoder,
947                                    pTimeData,
948                                   &self->streamInfo.numChannels,
949                                   &self->streamInfo.sampleRate,
950                                    self->channelOutputMapping[chOutMapIdx],
951                                    interleaved,
952                                    self->frameOK,
953                                   &self->psPossible);
954
955
956     if (sbrError == SBRDEC_OK) {
957       #define UPS_SCALE  2  /* Maximum upsampling factor is 4 (CELP+SBR) */
958       FIXP_DBL  upsampleFactor = FL2FXCONST_DBL(1.0f/(1<<UPS_SCALE));
959
960       /* Update data in streaminfo structure. Assume that the SBR upsampling factor is either 1 or 2 */
961       self->flags |= AC_SBR_PRESENT;
962       if (self->streamInfo.aacSampleRate != self->streamInfo.sampleRate) {
963         if (self->streamInfo.frameSize == 768) {
964           upsampleFactor = FL2FXCONST_DBL(8.0f/(3<<UPS_SCALE));
965         } else {
966           upsampleFactor = FL2FXCONST_DBL(2.0f/(1<<UPS_SCALE));
967         }
968       }
969       /* Apply upsampling factor to both the core frame length and the core delay */
970       self->streamInfo.frameSize    =       (INT)fMult((FIXP_DBL)self->streamInfo.aacSamplesPerFrame<<UPS_SCALE, upsampleFactor);
971       self->streamInfo.outputDelay  = (UINT)(INT)fMult((FIXP_DBL)self->streamInfo.outputDelay<<UPS_SCALE, upsampleFactor);
972       self->streamInfo.outputDelay += sbrDecoder_GetDelay( self->hSbrDecoder );
973
974       if (self->psPossible) {
975         self->flags |= AC_PS_PRESENT;
976         self->channelType[0] = ACT_FRONT;
977         self->channelType[1] = ACT_FRONT;
978         self->channelIndices[0] = 0;
979         self->channelIndices[1] = 1;
980       }
981     }
982   }
983
984
985    {
986    INT pcmLimiterScale = 0;
987    PCMDMX_ERROR dmxErr = PCMDMX_OK;
988    if ( flags & (AACDEC_INTR | AACDEC_CLRHIST) ) {
989      /* delete data from the past (e.g. mixdown coeficients) */
990      pcmDmx_Reset( self->hPcmUtils, PCMDMX_RESET_BS_DATA );
991    }
992    /* do PCM post processing */
993    dmxErr = pcmDmx_ApplyFrame (
994            self->hPcmUtils,
995            pTimeData,
996            self->streamInfo.frameSize,
997           &self->streamInfo.numChannels,
998            interleaved,
999            self->channelType,
1000            self->channelIndices,
1001            self->channelOutputMapping,
1002            (self->limiterEnableCurr) ? &pcmLimiterScale : NULL
1003      );
1004    if (dmxErr == PCMDMX_INVALID_MODE) {
1005      /* Announce the framework that the current combination of channel configuration and downmix
1006       * settings are not know to produce a predictable behavior and thus maybe produce strange output. */
1007      ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
1008    }
1009
1010    if ( flags & AACDEC_CLRHIST ) {
1011      /* Delete the delayed signal. */
1012      resetLimiter(self->hLimiter);
1013    }
1014    if (self->limiterEnableCurr)
1015    {
1016      /* Set actual signal parameters */
1017      setLimiterNChannels(self->hLimiter, self->streamInfo.numChannels);
1018      setLimiterSampleRate(self->hLimiter, self->streamInfo.sampleRate);
1019
1020      applyLimiter(
1021              self->hLimiter,
1022              pTimeData,
1023              self->extGain,
1024             &pcmLimiterScale,
1025              1,
1026              self->extGainDelay,
1027              self->streamInfo.frameSize
1028              );
1029
1030      /* Announce the additional limiter output delay */
1031      self->streamInfo.outputDelay += getLimiterDelay(self->hLimiter);
1032    }
1033    }
1034
1035
1036    /* Signal interruption to take effect in next frame. */
1037    if ( flags & AACDEC_FLUSH ) {
1038      aacDecoder_SignalInterruption(self);
1039    }
1040
1041    /* Update externally visible copy of flags */
1042    self->streamInfo.flags = self->flags;
1043
1044bail:
1045
1046    /* Update Statistics */
1047    aacDecoder_UpdateBitStreamCounters(&self->streamInfo, hBs, nBits, ErrorStatus);
1048
1049    return ErrorStatus;
1050}
1051
1052LINKSPEC_CPP void aacDecoder_Close ( HANDLE_AACDECODER self )
1053{
1054  if (self == NULL)
1055    return;
1056
1057
1058  if (self->hLimiter != NULL) {
1059    destroyLimiter(self->hLimiter);
1060  }
1061
1062  if (self->hPcmUtils != NULL) {
1063    pcmDmx_Close( &self->hPcmUtils );
1064  }
1065
1066
1067
1068  if (self->hSbrDecoder != NULL) {
1069    sbrDecoder_Close(&self->hSbrDecoder);
1070  }
1071
1072  if (self->hInput != NULL) {
1073    transportDec_Close(&self->hInput);
1074  }
1075
1076  CAacDecoder_Close(self);
1077}
1078
1079
1080LINKSPEC_CPP CStreamInfo* aacDecoder_GetStreamInfo ( HANDLE_AACDECODER self )
1081{
1082  return CAacDecoder_GetStreamInfo(self);
1083}
1084
1085LINKSPEC_CPP INT aacDecoder_GetLibInfo ( LIB_INFO *info )
1086{
1087  int i;
1088
1089  if (info == NULL) {
1090    return -1;
1091  }
1092
1093  sbrDecoder_GetLibInfo( info );
1094  transportDec_GetLibInfo( info );
1095  FDK_toolsGetLibInfo( info );
1096  pcmDmx_GetLibInfo( info );
1097
1098  /* search for next free tab */
1099  for (i = 0; i < FDK_MODULE_LAST; i++) {
1100    if (info[i].module_id == FDK_NONE) break;
1101  }
1102  if (i == FDK_MODULE_LAST) {
1103    return -1;
1104  }
1105  info += i;
1106
1107  info->module_id = FDK_AACDEC;
1108  /* build own library info */
1109  info->version = LIB_VERSION(AACDECODER_LIB_VL0, AACDECODER_LIB_VL1, AACDECODER_LIB_VL2);
1110  LIB_VERSION_STRING(info);
1111  info->build_date = AACDECODER_LIB_BUILD_DATE;
1112  info->build_time = AACDECODER_LIB_BUILD_TIME;
1113  info->title = AACDECODER_LIB_TITLE;
1114
1115  /* Set flags */
1116  info->flags = 0
1117      | CAPF_AAC_LC
1118      | CAPF_AAC_VCB11
1119      | CAPF_AAC_HCR
1120      | CAPF_AAC_RVLC
1121      | CAPF_ER_AAC_LD
1122      | CAPF_ER_AAC_ELD
1123      | CAPF_AAC_CONCEALMENT
1124      | CAPF_AAC_DRC
1125
1126      | CAPF_AAC_MPEG4
1127
1128
1129      | CAPF_AAC_1024
1130      | CAPF_AAC_960
1131
1132      | CAPF_AAC_512
1133
1134      | CAPF_AAC_480
1135
1136      ;
1137  /* End of flags */
1138
1139  return 0;
1140}
1141
1142
1143
1144
1145