summaryrefslogtreecommitdiffstats
path: root/libAACdec/src/aacdecoder_lib.cpp
blob: 94eb3c056db6131890681f5cf9b8e0e000c40730 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
/* -----------------------------------------------------------------------------------------------------------
Software License for The Fraunhofer FDK AAC Codec Library for Android

� Copyright  1995 - 2013 Fraunhofer-Gesellschaft zur F�rderung der angewandten Forschung e.V.
  All rights reserved.

 1.    INTRODUCTION
The Fraunhofer FDK AAC Codec Library for Android ("FDK AAC Codec") is software that implements
the MPEG Advanced Audio Coding ("AAC") encoding and decoding scheme for digital audio.
This FDK AAC Codec software is intended to be used on a wide variety of Android devices.

AAC's HE-AAC and HE-AAC v2 versions are regarded as today's most efficient general perceptual
audio codecs. AAC-ELD is considered the best-performing full-bandwidth communications codec by
independent studies and is widely deployed. AAC has been standardized by ISO and IEC as part
of the MPEG specifications.

Patent licenses for necessary patent claims for the FDK AAC Codec (including those of Fraunhofer)
may be obtained through Via Licensing (www.vialicensing.com) or through the respective patent owners
individually for the purpose of encoding or decoding bit streams in products that are compliant with
the ISO/IEC MPEG audio standards. Please note that most manufacturers of Android devices already license
these patent claims through Via Licensing or directly from the patent owners, and therefore FDK AAC Codec
software may already be covered under those patent licenses when it is used for those licensed purposes only.

Commercially-licensed AAC software libraries, including floating-point versions with enhanced sound quality,
are also available from Fraunhofer. Users are encouraged to check the Fraunhofer website for additional
applications information and documentation.

2.    COPYRIGHT LICENSE

Redistribution and use in source and binary forms, with or without modification, are permitted without
payment of copyright license fees provided that you satisfy the following conditions:

You must retain the complete text of this software license in redistributions of the FDK AAC Codec or
your modifications thereto in source code form.

You must retain the complete text of this software license in the documentation and/or other materials
provided with redistributions of the FDK AAC Codec or your modifications thereto in binary form.
You must make available free of charge copies of the complete source code of the FDK AAC Codec and your
modifications thereto to recipients of copies in binary form.

The name of Fraunhofer may not be used to endorse or promote products derived from this library without
prior written permission.

You may not charge copyright license fees for anyone to use, copy or distribute the FDK AAC Codec
software or your modifications thereto.

Your modified versions of the FDK AAC Codec must carry prominent notices stating that you changed the software
and the date of any change. For modified versions of the FDK AAC Codec, the term
"Fraunhofer FDK AAC Codec Library for Android" must be replaced by the term
"Third-Party Modified Version of the Fraunhofer FDK AAC Codec Library for Android."

3.    NO PATENT LICENSE

NO EXPRESS OR IMPLIED LICENSES TO ANY PATENT CLAIMS, including without limitation the patents of Fraunhofer,
ARE GRANTED BY THIS SOFTWARE LICENSE. Fraunhofer provides no warranty of patent non-infringement with
respect to this software.

You may use this FDK AAC Codec software or modifications thereto only for purposes that are authorized
by appropriate patent licenses.

4.    DISCLAIMER

This FDK AAC Codec software is provided by Fraunhofer on behalf of the copyright holders and contributors
"AS IS" and WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, including but not limited to the implied warranties
of merchantability and fitness for a particular purpose. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE for any direct, indirect, incidental, special, exemplary, or consequential damages,
including but not limited to procurement of substitute goods or services; loss of use, data, or profits,
or business interruption, however caused and on any theory of liability, whether in contract, strict
liability, or tort (including negligence), arising in any way out of the use of this software, even if
advised of the possibility of such damage.

5.    CONTACT INFORMATION

Fraunhofer Institute for Integrated Circuits IIS
Attention: Audio and Multimedia Departments - FDK AAC LL
Am Wolfsmantel 33
91058 Erlangen, Germany

www.iis.fraunhofer.de/amm
amm-info@iis.fraunhofer.de
----------------------------------------------------------------------------------------------------------- */

/*****************************  MPEG-4 AAC Decoder  **************************

   Author(s):   Manuel Jander
   Description:

******************************************************************************/

#include "aacdecoder_lib.h"

#include "aac_ram.h"
#include "aacdecoder.h"
#include "tpdec_lib.h"
#include "FDK_core.h" /* FDK_tools version info */


 #include "sbrdecoder.h"




#include "conceal.h"

 #include "aacdec_drc.h"



/* Decoder library info */
#define AACDECODER_LIB_VL0 2
#define AACDECODER_LIB_VL1 5
#define AACDECODER_LIB_VL2 10
#define AACDECODER_LIB_TITLE "AAC Decoder Lib"
#ifdef __ANDROID__
#define AACDECODER_LIB_BUILD_DATE ""
#define AACDECODER_LIB_BUILD_TIME ""
#else
#define AACDECODER_LIB_BUILD_DATE __DATE__
#define AACDECODER_LIB_BUILD_TIME __TIME__
#endif

static AAC_DECODER_ERROR
setConcealMethod ( const HANDLE_AACDECODER  self,
                   const INT                method );


LINKSPEC_CPP AAC_DECODER_ERROR aacDecoder_GetFreeBytes ( const HANDLE_AACDECODER  self, UINT *pFreeBytes){

  /* reset free bytes */
  *pFreeBytes = 0;

  /* check handle */
  if(!self)
    return AAC_DEC_INVALID_HANDLE;

  /* return nr of free bytes */
  HANDLE_FDK_BITSTREAM hBs = transportDec_GetBitstream(self->hInput, 0);
  *pFreeBytes = FDKgetFreeBits(hBs) >> 3;

  /* success */
  return AAC_DEC_OK;
}

/**
 * Config Decoder using a CSAudioSpecificConfig struct.
 */
static
LINKSPEC_CPP AAC_DECODER_ERROR aacDecoder_Config(HANDLE_AACDECODER self, const CSAudioSpecificConfig *pAscStruct)
{
  AAC_DECODER_ERROR err;

  /* Initialize AAC core decoder, and update self->streaminfo */
  err = CAacDecoder_Init(self, pAscStruct);

  return err;
}

LINKSPEC_CPP AAC_DECODER_ERROR aacDecoder_ConfigRaw (
        HANDLE_AACDECODER self,
        UCHAR *conf[],
        const UINT length[] )
{
  AAC_DECODER_ERROR err = AAC_DEC_OK;
  TRANSPORTDEC_ERROR   errTp;
  UINT layer, nrOfLayers = self->nrOfLayers;

  for(layer = 0; layer < nrOfLayers; layer++){
    if(length[layer] > 0){
      errTp = transportDec_OutOfBandConfig(self->hInput, conf[layer], length[layer], layer);
      if (errTp != TRANSPORTDEC_OK) {
        switch (errTp) {
        case TRANSPORTDEC_NEED_TO_RESTART:
          err = AAC_DEC_NEED_TO_RESTART;
          break;
        case TRANSPORTDEC_UNSUPPORTED_FORMAT:
          err = AAC_DEC_UNSUPPORTED_FORMAT;
          break;
        default:
          err = AAC_DEC_UNKNOWN;
          break;
        }
        /* if baselayer is OK we continue decoding */
        if(layer  >= 1){
          self->nrOfLayers = layer;
        }
        break;
      }
    }
  }

  return err;
}



static INT aacDecoder_ConfigCallback(void *handle, const CSAudioSpecificConfig *pAscStruct)
{
  HANDLE_AACDECODER self = (HANDLE_AACDECODER)handle;
  AAC_DECODER_ERROR err = AAC_DEC_OK;
  TRANSPORTDEC_ERROR errTp;

  {
    {
      err = aacDecoder_Config(self, pAscStruct);
    }
  }
  if (err == AAC_DEC_OK) {
    if ( self->flags & (AC_USAC|AC_RSVD50|AC_LD|AC_ELD)
      && CConcealment_GetDelay(&self->concealCommonData) > 0 )
    {
      /* Revert to error concealment method Noise Substitution.
         Because interpolation is not implemented for USAC/RSVD50 or
         the additional delay is unwanted for low delay codecs. */
      setConcealMethod(self, 1);
#ifdef DEBUG
      FDKprintf("  Concealment method was reverted to 1 !\n");
#endif
    }
    errTp = TRANSPORTDEC_OK;
  } else {
    if (IS_INIT_ERROR(err)) {
      errTp = TRANSPORTDEC_UNSUPPORTED_FORMAT;
    } /* Fatal errors */
    else if (err == AAC_DEC_NEED_TO_RESTART) {
      errTp = TRANSPORTDEC_NEED_TO_RESTART;
    } else {
      errTp = TRANSPORTDEC_UNKOWN_ERROR;
    }
  }

  return errTp;
}



LINKSPEC_CPP AAC_DECODER_ERROR
aacDecoder_AncDataInit ( HANDLE_AACDECODER self,
                         UCHAR *buffer,
                         int size )
{
  CAncData *ancData = &self->ancData;

  return CAacDecoder_AncDataInit(ancData, buffer, size);
}


LINKSPEC_CPP AAC_DECODER_ERROR
aacDecoder_AncDataGet ( HANDLE_AACDECODER self,
                        int     index,
                        UCHAR **ptr,
                        int    *size )
{
  CAncData *ancData = &self->ancData;

  return CAacDecoder_AncDataGet(ancData, index, ptr, size);
}


static AAC_DECODER_ERROR
setConcealMethod ( const HANDLE_AACDECODER  self,   /*!< Handle of the decoder instance */
                   const INT                method )
{
  AAC_DECODER_ERROR errorStatus = AAC_DEC_OK;
  CConcealParams  *pConcealData = NULL;
  HANDLE_SBRDECODER hSbrDec = NULL;
  HANDLE_AAC_DRC hDrcInfo = NULL;
  HANDLE_PCM_DOWNMIX hPcmDmx = NULL;
  CConcealmentMethod backupMethod = ConcealMethodNone;
  int backupDelay = 0;
  int bsDelay = 0;

  /* check decoder handle */
  if (self != NULL) {
    pConcealData = &self->concealCommonData;
    hSbrDec = self->hSbrDecoder;
    hDrcInfo = self->hDrcInfo;
    hPcmDmx = self->hPcmUtils;
  }


  /* Get current method/delay */
  backupMethod = CConcealment_GetMethod(pConcealData);
  backupDelay  = CConcealment_GetDelay(pConcealData);

  /* Be sure to set AAC and SBR concealment method simultaneously! */
  errorStatus =
    CConcealment_SetParams(
      pConcealData,
      (int)method,                         // concealMethod
      AACDEC_CONCEAL_PARAM_NOT_SPECIFIED,  // concealFadeOutSlope
      AACDEC_CONCEAL_PARAM_NOT_SPECIFIED,  // concealFadeInSlope
      AACDEC_CONCEAL_PARAM_NOT_SPECIFIED,  // concealMuteRelease
      AACDEC_CONCEAL_PARAM_NOT_SPECIFIED   // concealComfNoiseLevel
    );
  if ( (errorStatus != AAC_DEC_OK)
    && (errorStatus != AAC_DEC_INVALID_HANDLE) ) {
    goto bail;
  }

  /* Get new delay */
  bsDelay = CConcealment_GetDelay(pConcealData);

  {
    SBR_ERROR sbrErr = SBRDEC_OK;

    /* set SBR bitstream delay */
    sbrErr = sbrDecoder_SetParam (
      hSbrDec,
      SBR_SYSTEM_BITSTREAM_DELAY,
      bsDelay
    );

    switch (sbrErr) {
    case SBRDEC_OK:
    case SBRDEC_NOT_INITIALIZED:
      if (self != NULL) {
        /* save the param value and set later
           (when SBR has been initialized) */
        self->sbrParams.bsDelay = bsDelay;
      }
      break;
    default:
      errorStatus = AAC_DEC_SET_PARAM_FAIL;
      goto bail;
    }
  }

  errorStatus =
    aacDecoder_drcSetParam (
      hDrcInfo,
      DRC_BS_DELAY,
      bsDelay
    );
  if ( (errorStatus != AAC_DEC_OK)
    && (errorStatus != AAC_DEC_INVALID_HANDLE) ) {
    goto bail;
  }

  if (errorStatus == AAC_DEC_OK) {
    PCMDMX_ERROR err =
      pcmDmx_SetParam (
        hPcmDmx,
        DMX_BS_DATA_DELAY,
        bsDelay
      );
    switch (err) {
    case PCMDMX_INVALID_HANDLE:
      errorStatus = AAC_DEC_INVALID_HANDLE;
    case PCMDMX_OK:
      break;
    default:
      errorStatus = AAC_DEC_SET_PARAM_FAIL;
      goto bail;
    }
  }


bail:
  if ( (errorStatus != AAC_DEC_OK)
    && (errorStatus != AAC_DEC_INVALID_HANDLE) )
  {
    /* Revert to the initial state */
    CConcealment_SetParams (
        pConcealData,
        (int)backupMethod,
        AACDEC_CONCEAL_PARAM_NOT_SPECIFIED,
        AACDEC_CONCEAL_PARAM_NOT_SPECIFIED,
        AACDEC_CONCEAL_PARAM_NOT_SPECIFIED,
        AACDEC_CONCEAL_PARAM_NOT_SPECIFIED
      );
    /* Revert SBR bitstream delay */
    sbrDecoder_SetParam (
        hSbrDec,
        SBR_SYSTEM_BITSTREAM_DELAY,
        backupDelay
      );
    /* Revert DRC bitstream delay */
    aacDecoder_drcSetParam (
        hDrcInfo,
        DRC_BS_DELAY,
        backupDelay
      );
    /* Revert PCM mixdown bitstream delay */
    pcmDmx_SetParam (
        hPcmDmx,
        DMX_BS_DATA_DELAY,
        backupDelay
      );
  }

  return errorStatus;
}


LINKSPEC_CPP AAC_DECODER_ERROR
aacDecoder_SetParam ( const HANDLE_AACDECODER  self,   /*!< Handle of the decoder instance */
                      const AACDEC_PARAM       param,  /*!< Parameter to set               */
                      const INT                value)  /*!< Parameter valued               */
{
  AAC_DECODER_ERROR errorStatus = AAC_DEC_OK;
  CConcealParams  *pConcealData = NULL;
  HANDLE_AAC_DRC hDrcInfo = NULL;
  HANDLE_PCM_DOWNMIX hPcmDmx = NULL;
  TDLimiterPtr hPcmTdl = NULL;

  /* check decoder handle */
  if (self != NULL) {
    pConcealData = &self->concealCommonData;
    hDrcInfo = self->hDrcInfo;
    hPcmDmx = self->hPcmUtils;
    hPcmTdl = self->hLimiter;
  } else {
    errorStatus = AAC_DEC_INVALID_HANDLE;
  }

  /* configure the subsystems */
  switch (param)
  {
  case AAC_PCM_OUTPUT_INTERLEAVED:
    if (value < 0 || value > 1) {
      return AAC_DEC_SET_PARAM_FAIL;
    }
    if (self == NULL) {
      return AAC_DEC_INVALID_HANDLE;
    }
    self->outputInterleaved = value;
    break;

  case AAC_PCM_MIN_OUTPUT_CHANNELS:
    if (value < -1 || value > (8)) {
      return AAC_DEC_SET_PARAM_FAIL;
    }
    {
      PCMDMX_ERROR err;

      err = pcmDmx_SetParam (
              hPcmDmx,
              MIN_NUMBER_OF_OUTPUT_CHANNELS,
              value );

      switch (err) {
      case PCMDMX_OK:
        break;
      case PCMDMX_INVALID_HANDLE:
        return AAC_DEC_INVALID_HANDLE;
      default:
        return AAC_DEC_SET_PARAM_FAIL;
      }
    }
    break;

  case AAC_PCM_MAX_OUTPUT_CHANNELS:
    if (value < -1 || value > (8)) {
      return AAC_DEC_SET_PARAM_FAIL;
    }
    {
      PCMDMX_ERROR err;

      err = pcmDmx_SetParam (
              hPcmDmx,
              MAX_NUMBER_OF_OUTPUT_CHANNELS,
              value );

      switch (err) {
      case PCMDMX_OK:
        break;
      case PCMDMX_INVALID_HANDLE:
        return AAC_DEC_INVALID_HANDLE;
      default:
        return AAC_DEC_SET_PARAM_FAIL;
      }
    }
    break;

  case AAC_PCM_DUAL_CHANNEL_OUTPUT_MODE:
    {
      PCMDMX_ERROR err;

      err = pcmDmx_SetParam (
              hPcmDmx,
              DMX_DUAL_CHANNEL_MODE,
              value );

      switch (err) {
      case PCMDMX_OK:
        break;
      case PCMDMX_INVALID_HANDLE:
        return AAC_DEC_INVALID_HANDLE;
      default:
        return AAC_DEC_SET_PARAM_FAIL;
      }
    }
    break;


  case AAC_PCM_LIMITER_ENABLE:
    if (value < -1 || value > 1) {
      return AAC_DEC_SET_PARAM_FAIL;
    }
    if (self == NULL) {
      return AAC_DEC_INVALID_HANDLE;
    }
    self->limiterEnableUser = value;
    break;

  case AAC_PCM_LIMITER_ATTACK_TIME:
    if (value <= 0) {  /* module function converts value to unsigned */
      return AAC_DEC_SET_PARAM_FAIL;
    }
    switch (setLimiterAttack(hPcmTdl, value)) {
    case TDLIMIT_OK:
      break;
    case TDLIMIT_INVALID_HANDLE:
      return AAC_DEC_INVALID_HANDLE;
    case TDLIMIT_INVALID_PARAMETER:
    default:
      return AAC_DEC_SET_PARAM_FAIL;
    }
    break;

  case AAC_PCM_LIMITER_RELEAS_TIME:
    if (value <= 0) {  /* module function converts value to unsigned */
      return AAC_DEC_SET_PARAM_FAIL;
    }
    switch (setLimiterRelease(hPcmTdl, value)) {
    case TDLIMIT_OK:
      break;
    case TDLIMIT_INVALID_HANDLE:
      return AAC_DEC_INVALID_HANDLE;
    case TDLIMIT_INVALID_PARAMETER:
    default:
      return AAC_DEC_SET_PARAM_FAIL;
    }
    break;

  case AAC_PCM_OUTPUT_CHANNEL_MAPPING:
    switch (value) {
      case 0:
        if (self != NULL) {
          self->channelOutputMapping = channelMappingTablePassthrough;
        }
        break;
      case 1:
        if (self != NULL) {
          self->channelOutputMapping = channelMappingTableWAV;
        }
        break;
      default:
        errorStatus = AAC_DEC_SET_PARAM_FAIL;
        break;
    }
    break;


  case AAC_QMF_LOWPOWER:
    if (value < -1 || value > 1) {
      return AAC_DEC_SET_PARAM_FAIL;
    }
    if (self == NULL) {
      return AAC_DEC_INVALID_HANDLE;
    }

    /**
     * Set QMF mode (might be overriden)
     *  0:HQ (complex)
     *  1:LP (partially complex)
     */
    self->qmfModeUser = (QMF_MODE)value;
    break;


  case AAC_DRC_ATTENUATION_FACTOR:
    /* DRC compression factor (where 0 is no and 127 is max compression) */
    errorStatus =
      aacDecoder_drcSetParam (
        hDrcInfo,
        DRC_CUT_SCALE,
        value
      );
    break;

  case AAC_DRC_BOOST_FACTOR:
    /* DRC boost factor (where 0 is no and 127 is max boost) */
    errorStatus =
      aacDecoder_drcSetParam (
        hDrcInfo,
        DRC_BOOST_SCALE,
        value
      );
    break;

  case AAC_DRC_REFERENCE_LEVEL:
    /* DRC reference level quantized in 0.25dB steps using values [0..127] it is '-' for analog scaling */
    errorStatus =
      aacDecoder_drcSetParam (
        hDrcInfo,
        TARGET_REF_LEVEL,
        value
      );
    break;

  case AAC_DRC_HEAVY_COMPRESSION:
    /* Don't need to overwrite cut/boost values */
    errorStatus =
      aacDecoder_drcSetParam (
        hDrcInfo,
        APPLY_HEAVY_COMPRESSION,
        value
      );
    break;


  case AAC_TPDEC_CLEAR_BUFFER:
    transportDec_SetParam(self->hInput, TPDEC_PARAM_RESET, 1);
    self->streamInfo.numLostAccessUnits = 0;
    self->streamInfo.numBadBytes = 0;
    self->streamInfo.numTotalBytes = 0;
    /* aacDecoder_SignalInterruption(self); */
    break;

  case AAC_CONCEAL_METHOD:
    /* Changing the concealment method can introduce additional bitstream delay. And
       that in turn affects sub libraries and modules which makes the whole thing quite
       complex.  So the complete changing routine is packed into a helper function which
       keeps all modules and libs in a consistent state even in the case an error occures. */
    errorStatus = setConcealMethod ( self, value );
    break;

  default:
    return AAC_DEC_SET_PARAM_FAIL;
  }  /* switch(param) */

  return (errorStatus);
}


LINKSPEC_CPP HANDLE_AACDECODER aacDecoder_Open(TRANSPORT_TYPE transportFmt, UINT nrOfLayers)
{
  AAC_DECODER_INSTANCE *aacDec = NULL;
  HANDLE_TRANSPORTDEC pIn;
  int err = 0;

  /* Allocate transport layer struct. */
  pIn = transportDec_Open(transportFmt, TP_FLAG_MPEG4);
  if (pIn == NULL) {
    return NULL;
  }

  transportDec_SetParam(pIn, TPDEC_PARAM_IGNORE_BUFFERFULLNESS, 1);

  /* Allocate AAC decoder core struct. */
  aacDec = CAacDecoder_Open(transportFmt);

  if (aacDec == NULL) {
    transportDec_Close(&pIn);
    goto bail;
  }
  aacDec->hInput = pIn;

  aacDec->nrOfLayers = nrOfLayers;

  aacDec->channelOutputMapping = channelMappingTableWAV;

  /* Register Config Update callback. */
  transportDec_RegisterAscCallback(pIn, aacDecoder_ConfigCallback, (void*)aacDec);

  /* open SBR decoder */
  if ( SBRDEC_OK != sbrDecoder_Open ( &aacDec->hSbrDecoder )) {
    err = -1;
    goto bail;
  }
  aacDec->qmfModeUser = NOT_DEFINED;
  transportDec_RegisterSbrCallback(aacDec->hInput, (cbSbr_t)sbrDecoder_Header, (void*)aacDec->hSbrDecoder);


  pcmDmx_Open( &aacDec->hPcmUtils );
  if (aacDec->hPcmUtils == NULL) {
    err = -1;
    goto bail;
  }

  aacDec->hLimiter = createLimiter(TDL_ATTACK_DEFAULT_MS, TDL_RELEASE_DEFAULT_MS, SAMPLE_MAX, (8), 96000);
  if (NULL == aacDec->hLimiter) {
    err = -1;
    goto bail;
  }
  aacDec->limiterEnableUser = (UCHAR)-1;
  aacDec->limiterEnableCurr = 0;



  /* Assure that all modules have same delay */
  if ( setConcealMethod(aacDec, CConcealment_GetMethod(&aacDec->concealCommonData)) ) {
    err = -1;
    goto bail;
  }

bail:
  if (err == -1) {
    aacDecoder_Close(aacDec);
    aacDec = NULL;
  }
  return aacDec;
}

LINKSPEC_CPP AAC_DECODER_ERROR aacDecoder_Fill(
        HANDLE_AACDECODER   self,
        UCHAR              *pBuffer[],
        const UINT          bufferSize[],
        UINT               *pBytesValid
        )
{
  TRANSPORTDEC_ERROR tpErr;
  /* loop counter for layers; if not TT_MP4_RAWPACKETS used as index for only 
     available layer                                                           */
  INT layer      = 0;
  INT nrOfLayers = self->nrOfLayers;

  {
    for (layer = 0; layer < nrOfLayers; layer++){
      {
        tpErr = transportDec_FillData( self->hInput, pBuffer[layer], bufferSize[layer], &pBytesValid[layer], layer );
        if (tpErr != TRANSPORTDEC_OK) {
          return AAC_DEC_UNKNOWN;  /* Must be an internal error */
        }
      }
    }
  }

  return AAC_DEC_OK;
}


static void aacDecoder_SignalInterruption(HANDLE_AACDECODER self)
{
  CAacDecoder_SignalInterruption(self);

  if ( self->hSbrDecoder != NULL ) {
    sbrDecoder_SetParam(self->hSbrDecoder, SBR_BS_INTERRUPTION, 0);
  }
}

static void aacDecoder_UpdateBitStreamCounters(CStreamInfo *pSi, HANDLE_FDK_BITSTREAM hBs, int nBits, AAC_DECODER_ERROR ErrorStatus)
{
  /* calculate bit difference (amount of bits moved forward) */
  nBits = nBits - FDKgetValidBits(hBs);

  /* Note: The amount of bits consumed might become negative when parsing a
     bit stream with several sub frames, and we find out at the last sub frame
     that the total frame length does not match the sum of sub frame length. 
     If this happens, the transport decoder might want to rewind to the supposed
     ending of the transport frame, and this position might be before the last
     access unit beginning. */

  /* Calc bitrate. */
  if (pSi->frameSize > 0) {
    pSi->bitRate = (nBits * pSi->sampleRate)/pSi->frameSize;
  }

  /* bit/byte counters */
  {
    int nBytes;

    nBytes = nBits>>3;
    pSi->numTotalBytes += nBytes;
    if (IS_OUTPUT_VALID(ErrorStatus)) {
      pSi->numTotalAccessUnits++;
    }
    if (IS_DECODE_ERROR(ErrorStatus)) {
      pSi->numBadBytes += nBytes;
      pSi->numBadAccessUnits++;
    }
  }
}

static INT aacDecoder_EstimateNumberOfLostFrames(HANDLE_AACDECODER self)
{
  INT n;

  transportDec_GetMissingAccessUnitCount( &n, self->hInput);

  return n;
}

LINKSPEC_CPP AAC_DECODER_ERROR aacDecoder_DecodeFrame(
        HANDLE_AACDECODER  self,
        INT_PCM           *pTimeData,
        const INT          timeDataSize,
        const UINT         flags)
{
    AAC_DECODER_ERROR ErrorStatus;
    INT layer;
    INT nBits;
    INT interleaved = self->outputInterleaved;
    HANDLE_FDK_BITSTREAM hBs;
    int fTpInterruption = 0;  /* Transport originated interruption detection. */
    int fTpConceal = 0;       /* Transport originated concealment. */


    if (self == NULL) {
      return AAC_DEC_INVALID_HANDLE;
    }

    if (flags & AACDEC_INTR) {
      self->streamInfo.numLostAccessUnits = 0;
    }

    hBs = transportDec_GetBitstream(self->hInput, 0);

    /* Get current bits position for bitrate calculation. */
    nBits = FDKgetValidBits(hBs);
    if (! (flags & (AACDEC_CONCEAL | AACDEC_FLUSH) ) )
    {
      TRANSPORTDEC_ERROR err;

      for(layer = 0; layer < self->nrOfLayers; layer++)
      {
        err = transportDec_ReadAccessUnit(self->hInput, layer);
        if (err != TRANSPORTDEC_OK) {
          switch (err) {
          case TRANSPORTDEC_NOT_ENOUGH_BITS:
            ErrorStatus = AAC_DEC_NOT_ENOUGH_BITS;
            goto bail;
          case TRANSPORTDEC_SYNC_ERROR:
            self->streamInfo.numLostAccessUnits = aacDecoder_EstimateNumberOfLostFrames(self);
            fTpInterruption = 1;
            break;
          case TRANSPORTDEC_NEED_TO_RESTART:
            ErrorStatus = AAC_DEC_NEED_TO_RESTART;
            goto bail;
          case TRANSPORTDEC_CRC_ERROR:
            fTpConceal = 1;
            break;
          default:
            ErrorStatus = AAC_DEC_UNKNOWN;
            goto bail;
          }
        }
      }
    } else {
      if (self->streamInfo.numLostAccessUnits > 0) {
        self->streamInfo.numLostAccessUnits--;
      }
    }

    /* Signal bit stream interruption to other modules if required. */
    if ( fTpInterruption || (flags & (AACDEC_INTR|AACDEC_CLRHIST)) )
    {
      sbrDecoder_SetParam(self->hSbrDecoder, SBR_CLEAR_HISTORY, (flags&AACDEC_CLRHIST));
      aacDecoder_SignalInterruption(self);
      if ( ! (flags & AACDEC_INTR) ) {
        ErrorStatus = AAC_DEC_TRANSPORT_SYNC_ERROR;
        goto bail;
      }
    }

    /* Empty bit buffer in case of flush request. */
    if (flags & AACDEC_FLUSH)
    {
      transportDec_SetParam(self->hInput, TPDEC_PARAM_RESET, 1);
      self->streamInfo.numLostAccessUnits = 0;
      self->streamInfo.numBadBytes = 0;
      self->streamInfo.numTotalBytes = 0;
    }
    /* Reset the output delay field. The modules will add their figures one after another. */
    self->streamInfo.outputDelay = 0;

    if (self->limiterEnableUser==(UCHAR)-1) {
      /* Enbale limiter for all non-lowdelay AOT's. */
      self->limiterEnableCurr = ( self->flags & (AC_LD|AC_ELD) ) ? 0 : 1;
    }
    else {
      /* Use limiter configuration as requested. */
      self->limiterEnableCurr = self->limiterEnableUser;
    }
    /* reset limiter gain on a per frame basis */
    self->extGain[0] = FL2FXCONST_DBL(1.0f/(float)(1<<TDL_GAIN_SCALING));


    ErrorStatus = CAacDecoder_DecodeFrame(self,
                                          flags | (fTpConceal ? AACDEC_CONCEAL : 0),
                                          pTimeData,
                                          timeDataSize,
                                          interleaved);

    if (!(flags & (AACDEC_CONCEAL|AACDEC_FLUSH))) {
      TRANSPORTDEC_ERROR tpErr;
      tpErr = transportDec_EndAccessUnit(self->hInput);
      if (tpErr != TRANSPORTDEC_OK) {
        self->frameOK = 0;
      }
    }

    /* If the current pTimeData does not contain a valid signal, there nothing else we can do, so bail. */
    if ( ! IS_OUTPUT_VALID(ErrorStatus) ) {
      goto bail;
    }

    {
      /* Export data into streaminfo structure */
      self->streamInfo.sampleRate = self->streamInfo.aacSampleRate;
      self->streamInfo.frameSize  = self->streamInfo.aacSamplesPerFrame;
    }
    self->streamInfo.numChannels = self->streamInfo.aacNumChannels;



    CAacDecoder_SyncQmfMode(self);

/* sbr decoder */

    if (ErrorStatus || (flags & AACDEC_CONCEAL) || self->pAacDecoderStaticChannelInfo[0]->concealmentInfo.concealState > ConcealState_FadeIn)
    {
      self->frameOK = 0;  /* if an error has occured do concealment in the SBR decoder too */
    }

    if (self->sbrEnabled)
    {
      SBR_ERROR sbrError = SBRDEC_OK;
      int chOutMapIdx = ((self->chMapIndex==0) && (self->streamInfo.numChannels<7)) ? self->streamInfo.numChannels : self->chMapIndex;

      /* set params */
      sbrDecoder_SetParam ( self->hSbrDecoder,
                            SBR_SYSTEM_BITSTREAM_DELAY,
                            self->sbrParams.bsDelay);
      sbrDecoder_SetParam ( self->hSbrDecoder,
                            SBR_FLUSH_DATA,
                            (flags & AACDEC_FLUSH) );

      if ( self->streamInfo.aot == AOT_ER_AAC_ELD ) {
        /* Configure QMF */
        sbrDecoder_SetParam ( self->hSbrDecoder,
                              SBR_LD_QMF_TIME_ALIGN,
                              (self->flags & AC_LD_MPS) ? 1 : 0 );
      }

      {
        PCMDMX_ERROR dmxErr;
        INT  maxOutCh = 0;

        dmxErr = pcmDmx_GetParam(self->hPcmUtils, MAX_NUMBER_OF_OUTPUT_CHANNELS, &maxOutCh);
        if ( (dmxErr == PCMDMX_OK) && (maxOutCh == 1) ) {
          /* Disable PS processing if we have to create a mono output signal. */
          self->psPossible = 0;
        }
      }


      /* apply SBR processing */
      sbrError = sbrDecoder_Apply ( self->hSbrDecoder,
                                    pTimeData,
                                   &self->streamInfo.numChannels,
                                   &self->streamInfo.sampleRate,
                                    self->channelOutputMapping[chOutMapIdx],
                                    interleaved,
                                    self->frameOK,
                                   &self->psPossible);


     if (sbrError == SBRDEC_OK) {
       #define UPS_SCALE  2  /* Maximum upsampling factor is 4 (CELP+SBR) */
       FIXP_DBL  upsampleFactor = FL2FXCONST_DBL(1.0f/(1<<UPS_SCALE));

       /* Update data in streaminfo structure. Assume that the SBR upsampling factor is either 1 or 2 */
       self->flags |= AC_SBR_PRESENT;
       if (self->streamInfo.aacSampleRate != self->streamInfo.sampleRate) {
         if (self->streamInfo.frameSize == 768) {
           upsampleFactor = FL2FXCONST_DBL(8.0f/(3<<UPS_SCALE));
         } else {
           upsampleFactor = FL2FXCONST_DBL(2.0f/(1<<UPS_SCALE));
         }
       }
       /* Apply upsampling factor to both the core frame length and the core delay */
       self->streamInfo.frameSize    =       (INT)fMult((FIXP_DBL)self->streamInfo.aacSamplesPerFrame<<UPS_SCALE, upsampleFactor);
       self->streamInfo.outputDelay  = (UINT)(INT)fMult((FIXP_DBL)self->streamInfo.outputDelay<<UPS_SCALE, upsampleFactor);
       self->streamInfo.outputDelay += sbrDecoder_GetDelay( self->hSbrDecoder );

       if (self->psPossible) {
         self->flags |= AC_PS_PRESENT;
         self->channelType[0] = ACT_FRONT;
         self->channelType[1] = ACT_FRONT;
         self->channelIndices[0] = 0;
         self->channelIndices[1] = 1;
       }
     }
   }


    {
    INT pcmLimiterScale = 0;
    PCMDMX_ERROR dmxErr = PCMDMX_OK;
    if ( flags & (AACDEC_INTR | AACDEC_CLRHIST) ) {
      /* delete data from the past (e.g. mixdown coeficients) */
      pcmDmx_Reset( self->hPcmUtils, PCMDMX_RESET_BS_DATA );
    }
    /* do PCM post processing */
    dmxErr = pcmDmx_ApplyFrame (
            self->hPcmUtils,
            pTimeData,
            self->streamInfo.frameSize,
           &self->streamInfo.numChannels,
            interleaved,
            self->channelType,
            self->channelIndices,
            self->channelOutputMapping,
            (self->limiterEnableCurr) ? &pcmLimiterScale : NULL
      );
    if (dmxErr == PCMDMX_INVALID_MODE) {
      /* Announce the framework that the current combination of channel configuration and downmix
       * settings are not know to produce a predictable behavior and thus maybe produce strange output. */
      ErrorStatus = AAC_DEC_DECODE_FRAME_ERROR;
    }

    if ( flags & AACDEC_CLRHIST ) {
      /* Delete the delayed signal. */
      resetLimiter(self->hLimiter);
    }
    if (self->limiterEnableCurr)
    {
      /* Set actual signal parameters */
      setLimiterNChannels(self->hLimiter, self->streamInfo.numChannels);
      setLimiterSampleRate(self->hLimiter, self->streamInfo.sampleRate);

      applyLimiter(
              self->hLimiter,
              pTimeData,
              self->extGain,
             &pcmLimiterScale,
              1,
              self->extGainDelay,
              self->streamInfo.frameSize
              );

      /* Announce the additional limiter output delay */
      self->streamInfo.outputDelay += getLimiterDelay(self->hLimiter);
    }
    }


    /* Signal interruption to take effect in next frame. */
    if ( flags & AACDEC_FLUSH ) {
      aacDecoder_SignalInterruption(self);
    }

    /* Update externally visible copy of flags */
    self->streamInfo.flags = self->flags;

bail:

    /* Update Statistics */
    aacDecoder_UpdateBitStreamCounters(&self->streamInfo, hBs, nBits, ErrorStatus);

    return ErrorStatus;
}

LINKSPEC_CPP void aacDecoder_Close ( HANDLE_AACDECODER self )
{
  if (self == NULL)
    return;


  if (self->hLimiter != NULL) {
    destroyLimiter(self->hLimiter);
  }

  if (self->hPcmUtils != NULL) {
    pcmDmx_Close( &self->hPcmUtils );
  }



  if (self->hSbrDecoder != NULL) {
    sbrDecoder_Close(&self->hSbrDecoder);
  }

  if (self->hInput != NULL) {
    transportDec_Close(&self->hInput);
  }

  CAacDecoder_Close(self);
}


LINKSPEC_CPP CStreamInfo* aacDecoder_GetStreamInfo ( HANDLE_AACDECODER self )
{
  return CAacDecoder_GetStreamInfo(self);
}

LINKSPEC_CPP INT aacDecoder_GetLibInfo ( LIB_INFO *info )
{
  int i;

  if (info == NULL) {
    return -1;
  }

  sbrDecoder_GetLibInfo( info );
  transportDec_GetLibInfo( info );
  FDK_toolsGetLibInfo( info );
  pcmDmx_GetLibInfo( info );

  /* search for next free tab */
  for (i = 0; i < FDK_MODULE_LAST; i++) {
    if (info[i].module_id == FDK_NONE) break;
  }
  if (i == FDK_MODULE_LAST) {
    return -1;
  }
  info += i;

  info->module_id = FDK_AACDEC;
  /* build own library info */
  info->version = LIB_VERSION(AACDECODER_LIB_VL0, AACDECODER_LIB_VL1, AACDECODER_LIB_VL2);
  LIB_VERSION_STRING(info);
  info->build_date = AACDECODER_LIB_BUILD_DATE;
  info->build_time = AACDECODER_LIB_BUILD_TIME;
  info->title = AACDECODER_LIB_TITLE;

  /* Set flags */
  info->flags = 0
      | CAPF_AAC_LC
      | CAPF_AAC_VCB11
      | CAPF_AAC_HCR
      | CAPF_AAC_RVLC
      | CAPF_ER_AAC_LD
      | CAPF_ER_AAC_ELD
      | CAPF_AAC_CONCEALMENT
      | CAPF_AAC_DRC

      | CAPF_AAC_MPEG4


      | CAPF_AAC_1024
      | CAPF_AAC_960

      | CAPF_AAC_512

      | CAPF_AAC_480

      ;
  /* End of flags */

  return 0;
}