summaryrefslogtreecommitdiffstats
path: root/libAACdec/src/conceal.cpp
blob: dc5d99fcfd3d3d882bf26b7e430d426bb8313029 (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
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825

/* -----------------------------------------------------------------------------------------------------------
Software License for The Fraunhofer FDK AAC Codec Library for Android

© Copyright  1995 - 2012 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):   Josef Hoepfl
   Description: independent channel concealment

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

/*!
  \page concealment AAC core concealment

  This AAC core implementation includes a concealment function, which can be enabled
  using the several defines during compilation.

  There are various tests inside the core, starting with simple CRC tests and ending in
  a variety of plausibility checks. If such a check indicates an invalid bitstream, then
  concealment is applied.

  Concealment is also applied when the calling main program indicates a distorted or missing
  data frame using the frameOK flag. This is used for error detection on the transport layer.
  (See below)

  There are three concealment-modes:

  1) Muting: The spectral data is simply set to zero in case of an detected error.

  2) Noise substitution: In case of an detected error, concealment copies the last frame and adds
     attenuates the spectral data. For this mode you have to set the #CONCEAL_NOISE define.
     Noise substitution adds no additional delay.

  3) Interpolation: The interpolation routine swaps the spectral data from the previous and the
     current frame just before the final frequency to time conversion. In case a single frame is
     corrupted, concealmant interpolates between the last good and the first good frame to create
     the spectral data for the missing frame. If multiple frames are corrupted, concealment
     implements first a fade out based on slightly modified spectral values from the last good
     frame. As soon as good frames are available, concealmant fades in the new spectral data.
     For this mode you have to set the #CONCEAL_INTER define. Note that in this case, you also
     need to set #SBR_BS_DELAY_ENABLE, which basically adds approriate delay in the SBR decoder.
     Note that the Interpolating-Concealment increases the delay of your decoder by one frame
     and that it does require additional resources such as memory and computational complexity.

  <h2>How concealment can be used with errors on the transport layer</h2>

  Many errors can or have to be detected on the transport layer. For example in IP based systems
  packet loss can occur. The transport protocol used should indicate such packet loss by inserting
  an empty frame with frameOK=0.
*/

#include "conceal.h"

#include "aac_rom.h"
#include "genericStds.h"


/* PNS (of block) */
#include "aacdec_pns.h"
#include "block.h"

#include "FDK_tools_rom.h"

#define CONCEAL_DFLT_COMF_NOISE_LEVEL     ( 46 )  /* ~= -70 dB */


/* default settings */
#define CONCEAL_DFLT_FADEOUT_FRAMES       ( 5 )
#define CONCEAL_DFLT_FADEIN_FRAMES        ( 5 )
#define CONCEAL_DFLT_MUTE_RELEASE_FRAMES  ( 3 )

#define CONCEAL_DFLT_FADE_FACTOR          ( 0.707106781186548f )   /* 1/sqrt(2) */

/* some often used constants: */
#define FIXP_ZERO           FL2FXCONST_DBL(0.0f)
#define FIXP_ONE            FL2FXCONST_DBL(1.0f)
#define FIXP_FL_CORRECTION  FL2FXCONST_DBL(0.53333333333333333f)

/* For parameter conversion */
#define CONCEAL_PARAMETER_BITS              ( 8 )
#define CONCEAL_MAX_QUANT_FACTOR            ( (1<<CONCEAL_PARAMETER_BITS)-1 )
/*#define CONCEAL_MIN_ATTENUATION_FACTOR_025  ( FL2FXCONST_DBL(0.971627951577106174) )*/  /* -0.25 dB */
#define CONCEAL_MIN_ATTENUATION_FACTOR_025_LD  FL2FXCONST_DBL(-0.041524101186092029596853445212299)
/*#define CONCEAL_MIN_ATTENUATION_FACTOR_050  ( FL2FXCONST_DBL(0.944060876285923380) )*/  /* -0.50 dB */
#define CONCEAL_MIN_ATTENUATION_FACTOR_050_LD FL2FXCONST_DBL(-0.083048202372184059253597008145293)

typedef enum {
  CConcealment_NoExpand,
  CConcealment_Expand,
  CConcealment_Compress
}
CConcealmentExpandType;

static const FIXP_SGL facMod4Table[4] = {
  FL2FXCONST_SGL(0.500000000f),   /* FIXP_SGL(0x4000),  2^-(1-0,00) */
  FL2FXCONST_SGL(0.594603558f),   /* FIXP_SGL(0x4c1b),  2^-(1-0,25) */
  FL2FXCONST_SGL(0.707106781f),   /* FIXP_SGL(0x5a82),  2^-(1-0,50) */
  FL2FXCONST_SGL(0.840896415f)    /* FIXP_SGL(0x6ba2)   2^-(1-0,75) */
};




static void
  CConcealment_CalcBandEnergy (
    FIXP_DBL               *spectrum,
    const SamplingRateInfo *pSamplingRateInfo,
    const int               blockType,
    CConcealmentExpandType  ex,
    int                    *sfbEnergy
  );

static void
  CConcealment_InterpolateBuffer (
    FIXP_DBL    *spectrum,
    SHORT       *pSpecScalePrev,
    SHORT       *pSpecScaleAct,
    SHORT       *pSpecScaleOut,
    int         *enPrv,
    int         *enAct,
    int          sfbCnt,
    const SHORT *pSfbOffset
  );

static int
  CConcealment_ApplyInter (
    CConcealmentInfo       *pConcealmentInfo,
    CAacDecoderChannelInfo *pAacDecoderChannelInfo,
    const SamplingRateInfo *pSamplingRateInfo,
    const int  samplesPerFrame,
    const int  improveTonal,
    const int  frameOk
  );



static int
  CConcealment_ApplyNoise (
    CConcealmentInfo *pConcealmentInfo,
    CAacDecoderChannelInfo *pAacDecoderChannelInfo,
    CAacDecoderStaticChannelInfo *pAacDecoderStaticChannelInfo,
    const SamplingRateInfo *pSamplingRateInfo,
    const int    samplesPerFrame,
    const UINT flags
  );

static void
  CConcealment_UpdateState (
    CConcealmentInfo *pConcealmentInfo,
    int frameOk
  );

static void
  CConcealment_ApplyRandomSign (
    int        iRandomPhase,
    FIXP_DBL  *spec,
    int        samplesPerFrame
  );


static int CConcealment_GetWinSeq(int prevWinSeq)
{
  int newWinSeq = OnlyLongSequence;

  /* Try to have only long blocks */
  if ( prevWinSeq == LongStartSequence
    || prevWinSeq == EightShortSequence )
  {
    newWinSeq = LongStopSequence;
  }

  return (newWinSeq);
}


/*!
  \brief Init common concealment information data

  \pConcealCommonData Pointer to the concealment common data structure.

  \return  none
*/
void
  CConcealment_InitCommonData (CConcealParams *pConcealCommonData)
{
  if (pConcealCommonData != NULL)
  {
    int i;

    /* Set default error concealment technique */
    pConcealCommonData->method = ConcealMethodInter;

    pConcealCommonData->numFadeOutFrames     = CONCEAL_DFLT_FADEOUT_FRAMES;
    pConcealCommonData->numFadeInFrames      = CONCEAL_DFLT_FADEIN_FRAMES;
    pConcealCommonData->numMuteReleaseFrames = CONCEAL_DFLT_MUTE_RELEASE_FRAMES;

    pConcealCommonData->comfortNoiseLevel    = CONCEAL_DFLT_COMF_NOISE_LEVEL;

    /* Init fade factors (symetric) */
    pConcealCommonData->fadeOutFactor[0] = FL2FXCONST_SGL( CONCEAL_DFLT_FADE_FACTOR );
    pConcealCommonData->fadeInFactor[0]  = pConcealCommonData->fadeOutFactor[0];

    for (i = 1; i < CONCEAL_MAX_NUM_FADE_FACTORS; i++) {
      pConcealCommonData->fadeOutFactor[i] = FX_DBL2FX_SGL(fMult(pConcealCommonData->fadeOutFactor[i-1],FL2FXCONST_SGL(CONCEAL_DFLT_FADE_FACTOR)));
      pConcealCommonData->fadeInFactor[i]  = pConcealCommonData->fadeOutFactor[i];
    }
  }
}



/*!
  \brief Get current concealment method.

  \pConcealCommonData Pointer to common concealment data (for all channels)

  \return Concealment method.
*/
CConcealmentMethod
  CConcealment_GetMethod( CConcealParams *pConcealCommonData )
{
  CConcealmentMethod method = ConcealMethodNone;

  if (pConcealCommonData != NULL) {
    method = pConcealCommonData->method;
  }

  return (method);
}


/*!
  \brief Init concealment information for each channel

  The function initializes the concealment information. Two methods can be chosen:
             0 = interpolation method (adds delay)
             1 = noise substitution (no delay, low complexity)

  \return  none
*/
void
  CConcealment_InitChannelData (
    CConcealmentInfo *pConcealChannelInfo,
    CConcealParams   *pConcealCommonData,
    int samplesPerFrame )
{
  int i;

  pConcealChannelInfo->pConcealParams = pConcealCommonData;

  FDKmemclear(pConcealChannelInfo->spectralCoefficient, 1024 * sizeof(FIXP_CNCL));

  for (i = 0; i < 8; i++) {
    pConcealChannelInfo->specScale[i] = 0;
  }

  pConcealChannelInfo->iRandomPhase   = 0;

  pConcealChannelInfo->windowSequence = 0;
  pConcealChannelInfo->windowShape    = 0;

  pConcealChannelInfo->prevFrameOk[0] = 1;
  pConcealChannelInfo->prevFrameOk[1] = 1;

  pConcealChannelInfo->cntFadeFrames  = 0;
  pConcealChannelInfo->cntValidFrames = 0;

  pConcealChannelInfo->concealState   = ConcealState_Ok;

}


/*!
  \brief Set error concealment parameters

  \concealParams
  \method
  \fadeOutSlope
  \fadeInSlope
  \muteRelease
  \comfNoiseLevel

  \return  none
*/
AAC_DECODER_ERROR
  CConcealment_SetParams (
    CConcealParams *concealParams,
    int  method,
    int  fadeOutSlope,
    int  fadeInSlope,
    int  muteRelease,
    int  comfNoiseLevel )
{
  /* set concealment technique */
  if (method != AACDEC_CONCEAL_PARAM_NOT_SPECIFIED) {
    switch ((CConcealmentMethod)method)
    {
    case ConcealMethodMute:
    case ConcealMethodNoise:
    case ConcealMethodInter:
      /* Be sure to enable delay adjustment of SBR decoder! */
      if (concealParams == NULL) {
        return AAC_DEC_INVALID_HANDLE;
      } else {
        /* set param */
        concealParams->method = (CConcealmentMethod)method;
      }
      break;

    default:
      return AAC_DEC_SET_PARAM_FAIL;
    }
  }

  /* set number of frames for fade-out slope */
  if (fadeOutSlope != AACDEC_CONCEAL_PARAM_NOT_SPECIFIED) {
    if ( (fadeOutSlope < CONCEAL_MAX_NUM_FADE_FACTORS)
      && (fadeOutSlope >= 0) )
    {
      if (concealParams == NULL) {
        return AAC_DEC_INVALID_HANDLE;
      } else {
        /* set param */
        concealParams->numFadeOutFrames = fadeOutSlope;
      }
    } else {
      return AAC_DEC_SET_PARAM_FAIL;
    }
  }

  /* set number of frames for fade-in slope */
  if (fadeInSlope != AACDEC_CONCEAL_PARAM_NOT_SPECIFIED) {
    if ( (fadeInSlope < CONCEAL_MAX_NUM_FADE_FACTORS)
      && (fadeInSlope >= 1) )
    {
      if (concealParams == NULL) {
        return AAC_DEC_INVALID_HANDLE;
      } else {
        /* set param */
        concealParams->numFadeInFrames = fadeInSlope;
      }
    } else {
      return AAC_DEC_SET_PARAM_FAIL;
    }
  }

  /* set number of error-free frames after which the muting will be released */
  if (muteRelease != AACDEC_CONCEAL_PARAM_NOT_SPECIFIED) {
    if ( (muteRelease < (CONCEAL_MAX_NUM_FADE_FACTORS<<1))
      && (muteRelease >= 0) )
    {
      if (concealParams == NULL) {
        return AAC_DEC_INVALID_HANDLE;
      } else {
        /* set param */
        concealParams->numMuteReleaseFrames = muteRelease;
      }
    } else {
      return AAC_DEC_SET_PARAM_FAIL;
    }
  }

  /* set confort noise level which will be inserted while in state 'muting' */
  if (comfNoiseLevel != AACDEC_CONCEAL_PARAM_NOT_SPECIFIED) {
    if ( (comfNoiseLevel < 0) 
      || (comfNoiseLevel > 127) ) {
      return AAC_DEC_SET_PARAM_FAIL;
    }
    if (concealParams == NULL) {
      return AAC_DEC_INVALID_HANDLE;
    } else {
      concealParams->comfortNoiseLevel = comfNoiseLevel;
    }
  }

  return (AAC_DEC_OK);
}


/*!
  \brief Set fade-out/in attenuation factor vectors

  \concealParams
  \fadeOutAttenuationVector
  \fadeInAttenuationVector

  \return 0 if OK all other values indicate errors
*/
AAC_DECODER_ERROR
  CConcealment_SetAttenuation (
    CConcealParams *concealParams,
    SHORT *fadeOutAttenuationVector,
    SHORT *fadeInAttenuationVector )
{
  if ( (fadeOutAttenuationVector == NULL)
    && (fadeInAttenuationVector  == NULL) ) {
    return AAC_DEC_SET_PARAM_FAIL;
  }

  /* Fade-out factors */
  if (fadeOutAttenuationVector != NULL)
  {
    int i;

    /* check quantized factors first */
    for (i = 0; i < CONCEAL_MAX_NUM_FADE_FACTORS; i++) {
      if ((fadeOutAttenuationVector[i] < 0) || (fadeOutAttenuationVector[i] > CONCEAL_MAX_QUANT_FACTOR)) {
        return AAC_DEC_SET_PARAM_FAIL;
      }
    }
    if (concealParams == NULL) {
      return AAC_DEC_INVALID_HANDLE;
    }

    /* now dequantize factors */
    for (i = 0; i < CONCEAL_MAX_NUM_FADE_FACTORS; i++) 
    {
      concealParams->fadeOutFactor[i] =
        FX_DBL2FX_SGL( fLdPow(    CONCEAL_MIN_ATTENUATION_FACTOR_025_LD,
                                  0,
                                  (FIXP_DBL)((INT)(FL2FXCONST_DBL(1.0/2.0)>>(CONCEAL_PARAMETER_BITS-1)) * (INT)fadeOutAttenuationVector[i]),
                                  CONCEAL_PARAMETER_BITS
                                  )
                     );
    }
  }

  /* Fade-in factors */
  if (fadeInAttenuationVector != NULL)
  {
    int i;

    /* check quantized factors first */
    for (i = 0; i < CONCEAL_MAX_NUM_FADE_FACTORS; i++) {
      if ((fadeInAttenuationVector[i] < 0) || (fadeInAttenuationVector[i] > CONCEAL_MAX_QUANT_FACTOR)) {
        return AAC_DEC_SET_PARAM_FAIL;
      }
    }
    if (concealParams == NULL) {
      return AAC_DEC_INVALID_HANDLE;
    }

    /* now dequantize factors */
    for (i = 0; i < CONCEAL_MAX_NUM_FADE_FACTORS; i++)
    {
      concealParams->fadeInFactor[i] =
        FX_DBL2FX_SGL( fLdPow( CONCEAL_MIN_ATTENUATION_FACTOR_025_LD,
                               0,
                             (FIXP_DBL)((INT)(FIXP_ONE>>CONCEAL_PARAMETER_BITS) * (INT)fadeInAttenuationVector[i]),
                             CONCEAL_PARAMETER_BITS
                             )
                     );
    }
  }

  return (AAC_DEC_OK);
}


/*!
  \brief Get state of concealment module.

  \pConcealChannelInfo

  \return Concealment state.
*/
CConcealmentState
  CConcealment_GetState (
    CConcealmentInfo *pConcealChannelInfo
  )
{
  CConcealmentState state = ConcealState_Ok;

  if (pConcealChannelInfo != NULL) {
    state = pConcealChannelInfo->concealState;
  }

  return (state);
}


static void CConcealment_fakePnsData (
   CPnsData *pPnsData,
   CIcsInfo *pIcsInfo,
   const SamplingRateInfo *pSamplingRateInfo,
   SHORT *pSpecScale,
   SHORT *pScaleFactor,
   const int level )
{
  CPnsInterChannelData *pInterChannelData = pPnsData->pPnsInterChannelData;

  int  pnsBand, band, group, win;
  //int  delta = 0;
  int  windowsPerFrame = GetWindowsPerFrame(pIcsInfo);
  int  refLevel = (windowsPerFrame > 1) ? 82 : 91;

  FDK_ASSERT(level >= 0 && level <= 127);

  for (win = 0; win < windowsPerFrame; win++) {
    pSpecScale[win] = 31;
  }

  /* fake ICS info if necessary */
  if (!IsValid(pIcsInfo)) {
    pIcsInfo->WindowGroups = 1;
    if (IsLongBlock(pIcsInfo)) {
      pIcsInfo->TotalSfBands = pSamplingRateInfo->NumberOfScaleFactorBands_Long;
      pIcsInfo->WindowGroupLength[0] = 1;
    }
    else {
      pIcsInfo->TotalSfBands = pSamplingRateInfo->NumberOfScaleFactorBands_Short;
      pIcsInfo->WindowGroupLength[0] = 8;
    }
    pIcsInfo->MaxSfBands = pIcsInfo->TotalSfBands;
  }

  /* global activate PNS */
  pPnsData->PnsActive = 1;
  /* set energy level */
  pPnsData->CurrentEnergy = fixMax( 0, refLevel - level );

  /*
    value: | Avg. RMS power | Avg. RMS power |
           | specScale = 22 | specScale = 31 |
    -------+----------------+----------------+
        5  |                |  -99.0 dB
       15  |                |  -90.0 dB
       25  |                |  -89.7 dB 
       35  |                |  -85.3 dB
      ...  |    ...         |   ...
       45  |  -69.9 dB      |  -70.0 dB
       50  |  -62.2 dB      |  
       55  |  -55.6 dB      |  -54.6 dB
       60  |  -47.0 dB      |
       65  |  -39.5 dB      |  -39.5 dB
       70  |  -31.9 dB      |  
       75  |  -24.4 dB      |  -24.4 dB
       80  |  -16.9 dB      |  
       85  |   -9.4 dB (c)  |   -9.4 dB
       90  |   -3.9 dB (c)  |  
       95  |                |   -2.1 dB
      100  |                |   -1.6 dB
      105  |                |   -1.4 dB
  */

  for (group=0; group < GetWindowGroups(pIcsInfo); group++)
  {
    for (band=0; band < GetScaleFactorBandsTransmitted(pIcsInfo); band++)
    {
      pnsBand = group * 16 + band;

      if (pnsBand >= NO_OFBANDS) {
        return;
      }
      //pPnsData->CurrentEnergy += delta ;
      pScaleFactor[pnsBand] = pPnsData->CurrentEnergy;
      pInterChannelData->correlated[pnsBand] = 0;
      pPnsData->pnsUsed[pnsBand] = 1;
    }
  }
}


/*!
  \brief Store data for concealment techniques applied later

  Interface function to store data for different concealment strategies

   \return  none
 */
void
  CConcealment_Store (
    CConcealmentInfo *hConcealmentInfo,
    CAacDecoderChannelInfo *pAacDecoderChannelInfo,
    CAacDecoderStaticChannelInfo *pAacDecoderStaticChannelInfo )
{
  if ( !(pAacDecoderChannelInfo->renderMode == AACDEC_RENDER_LPD
      ) )
  {
    FIXP_DBL *pSpectralCoefficient =  SPEC_LONG(pAacDecoderChannelInfo->pSpectralCoefficient);
    SHORT    *pSpecScale           =  pAacDecoderChannelInfo->specScale;
    CIcsInfo *pIcsInfo             = &pAacDecoderChannelInfo->icsInfo;

    SHORT  tSpecScale[8];
    UCHAR  tWindowShape, tWindowSequence;

    /* store old window infos for swapping */
    tWindowSequence = hConcealmentInfo->windowSequence;
    tWindowShape    = hConcealmentInfo->windowShape;

    /* store old scale factors for swapping */
    FDKmemcpy(tSpecScale, hConcealmentInfo->specScale, 8*sizeof(SHORT));

    /* store new window infos */
    hConcealmentInfo->windowSequence = GetWindowSequence(pIcsInfo);
    hConcealmentInfo->windowShape    = GetWindowShape(pIcsInfo);
    hConcealmentInfo->lastWinGrpLen  = *(GetWindowGroupLengthTable(pIcsInfo)+GetWindowGroups(pIcsInfo)-1);

    /* store new scale factors */
    FDKmemcpy(hConcealmentInfo->specScale, pSpecScale, 8*sizeof(SHORT));

    if (CConcealment_GetDelay(hConcealmentInfo->pConcealParams) == 0)
    {
      /* store new spectral bins */
#if (CNCL_FRACT_BITS == DFRACT_BITS)
      FDKmemcpy(hConcealmentInfo->spectralCoefficient, pSpectralCoefficient, 1024 * sizeof(FIXP_CNCL));
#else
      FIXP_CNCL *RESTRICT pCncl = &hConcealmentInfo->spectralCoefficient[1024-1];
      FIXP_DBL  *RESTRICT pSpec = &pSpectralCoefficient[1024-1];
      int i;

      for (i = 1024; i != 0; i--) {
        *pCncl-- = FX_DBL2FX_CNCL(*pSpec--);
      }
#endif
    }
    else
    {
      FIXP_CNCL *RESTRICT pCncl = &hConcealmentInfo->spectralCoefficient[1024-1];
      FIXP_DBL  *RESTRICT pSpec = &pSpectralCoefficient[1024-1];
      int i;

      /* swap spectral data */
      for (i = 1024; i != 0; i--) {
        FIXP_DBL tSpec = *pSpec;
        *pSpec-- = FX_CNCL2FX_DBL(*pCncl);
        *pCncl-- = FX_DBL2FX_CNCL( tSpec);
      }

      /* complete swapping of window infos */
      pIcsInfo->WindowSequence = tWindowSequence;
      pIcsInfo->WindowShape    = tWindowShape;

      /* complete swapping of scale factors */
      FDKmemcpy(pSpecScale, tSpecScale, 8*sizeof(SHORT));
    }
  }
  
}


/*!
  \brief Apply concealment

  Interface function to different concealment strategies

   \return  none
 */
int
  CConcealment_Apply (
    CConcealmentInfo *hConcealmentInfo,
    CAacDecoderChannelInfo *pAacDecoderChannelInfo,
    CAacDecoderStaticChannelInfo *pAacDecoderStaticChannelInfo,
    const SamplingRateInfo *pSamplingRateInfo,
    const int samplesPerFrame,
    const UCHAR lastLpdMode,
    const int frameOk,
    const UINT flags)
{
  int appliedProcessing = 0;

  if ( (frameOk == 0)
    && (pAacDecoderChannelInfo->renderMode != (AACDEC_RENDER_MODE)hConcealmentInfo->lastRenderMode) ) {
    /* restore the last render mode to stay in the same domain which allows to do a proper concealment */
    pAacDecoderChannelInfo->renderMode = (AACDEC_RENDER_MODE)hConcealmentInfo->lastRenderMode;
  } else {
    /* otherwise store the current mode */
    hConcealmentInfo->lastRenderMode = (SCHAR)pAacDecoderChannelInfo->renderMode;
  }

  if ( frameOk )
  {
    /* Rescue current data for concealment in future frames */
    CConcealment_Store ( hConcealmentInfo,
                         pAacDecoderChannelInfo,
                         pAacDecoderStaticChannelInfo );
    /* Reset index to random sign vector to make sign calculation frame agnostic 
       (only depends on number of subsequently concealed spectral blocks) */
        hConcealmentInfo->iRandomPhase = 0;
  }

  /* hand current frame status to the state machine */
  CConcealment_UpdateState( hConcealmentInfo,
                            frameOk );

  if ( !frameOk )
  {
    /* Create data for signal rendering according to the selected concealment method and decoder operating mode. */


    if ( !(pAacDecoderChannelInfo->renderMode == AACDEC_RENDER_LPD
        )
        )
    {
      switch (hConcealmentInfo->pConcealParams->method)
      {
      default:
      case ConcealMethodMute:
        /* Mute spectral data in case of errors */
        FDKmemclear(pAacDecoderChannelInfo->pSpectralCoefficient, samplesPerFrame * sizeof(FIXP_DBL));
        /* Set last window shape */
        pAacDecoderChannelInfo->icsInfo.WindowShape = hConcealmentInfo->windowShape;
        appliedProcessing = 1;
        break;

      case ConcealMethodNoise:
        /* Noise substitution error concealment technique */
        appliedProcessing =
          CConcealment_ApplyNoise (hConcealmentInfo,
                                   pAacDecoderChannelInfo,
                                   pAacDecoderStaticChannelInfo,
                                   pSamplingRateInfo,
                                   samplesPerFrame,
                                   flags);
        break;

      case ConcealMethodInter:
        /* Energy interpolation concealment based on 3GPP */
        appliedProcessing =
          CConcealment_ApplyInter (hConcealmentInfo,
                                   pAacDecoderChannelInfo,
                                   pSamplingRateInfo,
                                   samplesPerFrame,
                                   0,  /* don't use tonal improvement */
                                   0);
        break;

      }
    }
  }
  /* update history */
  hConcealmentInfo->prevFrameOk[0] = hConcealmentInfo->prevFrameOk[1];
  hConcealmentInfo->prevFrameOk[1] = frameOk;

  return appliedProcessing;
}

/*!
\brief Apply concealment noise substitution

  In case of frame lost this function produces a noisy frame with respect to the
  energies values of past frame.

\return  none
 */
static int
  CConcealment_ApplyNoise (CConcealmentInfo *pConcealmentInfo,
                           CAacDecoderChannelInfo *pAacDecoderChannelInfo,
                           CAacDecoderStaticChannelInfo *pAacDecoderStaticChannelInfo,
                           const SamplingRateInfo *pSamplingRateInfo,
                           const int samplesPerFrame,
                           const UINT flags)
{
  CConcealParams *pConcealCommonData = pConcealmentInfo->pConcealParams;

  FIXP_DBL *pSpectralCoefficient =  SPEC_LONG(pAacDecoderChannelInfo->pSpectralCoefficient);
  SHORT    *pSpecScale           =  pAacDecoderChannelInfo->specScale;
  CIcsInfo *pIcsInfo             = &pAacDecoderChannelInfo->icsInfo;

  int appliedProcessing = 0;

  FDK_ASSERT((samplesPerFrame>=480) && (samplesPerFrame<=1024));
  FDK_ASSERT((samplesPerFrame&0x1F) == 0);

  switch (pConcealmentInfo->concealState)
  {
  case ConcealState_Ok:
    /* Nothing to do here! */
    break;

  case ConcealState_Single:
  case ConcealState_FadeOut:
    {
      /* restore frequency coefficients from buffer with a specific muting */
      FIXP_SGL  fac;
      int win, numWindows = 1;
      int windowLen = samplesPerFrame;
      int tFadeFrames, lastWindow = 0;
      int win_idx_stride = 1;

      FDK_ASSERT(pConcealmentInfo != NULL);
      FDK_ASSERT(pConcealmentInfo->cntFadeFrames >= 0);
      FDK_ASSERT(pConcealmentInfo->cntFadeFrames < CONCEAL_MAX_NUM_FADE_FACTORS);
      FDK_ASSERT(pConcealmentInfo->cntFadeFrames <= pConcealCommonData->numFadeOutFrames);

      /* get attenuation factor */
      tFadeFrames = pConcealmentInfo->cntFadeFrames;
      fac = pConcealCommonData->fadeOutFactor[tFadeFrames];

      /* set old window parameters */
      {
        pIcsInfo->WindowShape    = pConcealmentInfo->windowShape;
        pIcsInfo->WindowSequence = pConcealmentInfo->windowSequence;

        if (pConcealmentInfo->windowSequence == 2) {
          /* short block handling */
          numWindows = 8;
          windowLen  = samplesPerFrame >> 3;
          lastWindow = numWindows - pConcealmentInfo->lastWinGrpLen;
        }
      }

      for (win = 0; win < numWindows; win++) {
        FIXP_CNCL *pCncl = pConcealmentInfo->spectralCoefficient + (lastWindow * windowLen);
        FIXP_DBL  *pOut  = pSpectralCoefficient + (win * windowLen);
        int i;

        FDK_ASSERT((lastWindow * windowLen + windowLen) <= samplesPerFrame);

        /* restore frequency coefficients from buffer with a specific attenuation */
        for (i = 0; i < windowLen; i++) {
          pOut[i] = fMult(pCncl[i], fac);
        }

        /* apply random change of sign for spectral coefficients */
        CConcealment_ApplyRandomSign(pConcealmentInfo->iRandomPhase,
                                            pOut,
                                            windowLen );

        /* Increment random phase index to avoid repetition artifacts. */
        pConcealmentInfo->iRandomPhase = (pConcealmentInfo->iRandomPhase + 1) & (AAC_NF_NO_RANDOM_VAL - 1);

        /* set old scale factors */
        pSpecScale[win*win_idx_stride] = pConcealmentInfo->specScale[win_idx_stride*lastWindow++];

        if ( (lastWindow >= numWindows)
          && (numWindows >  1) )
        {
          /* end of sequence -> rewind */
          lastWindow = numWindows - pConcealmentInfo->lastWinGrpLen;
          /* update the attenuation factor to get a faster fade-out */
          tFadeFrames += 1;
          if (tFadeFrames < pConcealCommonData->numFadeOutFrames) {
            fac = pConcealCommonData->fadeOutFactor[tFadeFrames];
          } else {
            fac = (FIXP_SGL)0;
          }
        }
      }

      /* store temp vars */
      pConcealmentInfo->cntFadeFrames = tFadeFrames;
      appliedProcessing = 1;
    }
    break;

  case ConcealState_Mute:
    {
      /* set dummy window parameters */
      pIcsInfo->Valid          = 0;                                /* Trigger the generation of a consitent IcsInfo */
      pIcsInfo->WindowShape    = pConcealmentInfo->windowShape;    /* Prevent an invalid WindowShape (required for F/T transform) */
      pIcsInfo->WindowSequence = CConcealment_GetWinSeq(pConcealmentInfo->windowSequence);
      pConcealmentInfo->windowSequence = pIcsInfo->WindowSequence; /* Store for next frame (spectrum in concealment buffer can't be used at all) */

      /* mute spectral data */
      FDKmemclear(pSpectralCoefficient, samplesPerFrame * sizeof(FIXP_DBL));

      if ( !(flags & (AC_USAC|AC_RSVD50)) 
           && pConcealCommonData->comfortNoiseLevel >= 0
           && pConcealCommonData->comfortNoiseLevel <= 61 /* -90dB */)
        {
        /* insert comfort noise using PNS */
        CConcealment_fakePnsData (
         &pAacDecoderChannelInfo->data.aac.PnsData,
          pIcsInfo,
          pSamplingRateInfo,
          pAacDecoderChannelInfo->pDynData->aSfbScale,
          pAacDecoderChannelInfo->pDynData->aScaleFactor,
          pConcealCommonData->comfortNoiseLevel
        );

        CPns_Apply (
               &pAacDecoderChannelInfo->data.aac.PnsData,
                pIcsInfo,
                pAacDecoderChannelInfo->pSpectralCoefficient,
                pAacDecoderChannelInfo->specScale,
                pAacDecoderChannelInfo->pDynData->aScaleFactor,
                pSamplingRateInfo,
                pAacDecoderChannelInfo->granuleLength,
                0  /* always apply to first channel */
              );
      }
      appliedProcessing = 1;
    }
    break;

  case ConcealState_FadeIn:
    {
      FDK_ASSERT(pConcealmentInfo->cntFadeFrames >= 0);
      FDK_ASSERT(pConcealmentInfo->cntFadeFrames < CONCEAL_MAX_NUM_FADE_FACTORS);
      FDK_ASSERT(pConcealmentInfo->cntFadeFrames < pConcealCommonData->numFadeInFrames);

      /* attenuate signal to get a smooth fade-in */
      FIXP_DBL *RESTRICT pOut = &pSpectralCoefficient[samplesPerFrame-1];
      FIXP_SGL fac = pConcealCommonData->fadeInFactor[pConcealmentInfo->cntFadeFrames];
      int i;

      for (i = samplesPerFrame; i != 0; i--) {
        *pOut = fMult(*pOut, fac);
        pOut--;
      }
      appliedProcessing = 1;
    }
    break;

  default:
    /* we shouldn't come here anyway */
    FDK_ASSERT(0);
    break;
  }

  return appliedProcessing;
}


/*!
  \brief Apply concealment interpolation

  The function swaps the data from the current and the previous frame. If an
  error has occured, frame interpolation is performed to restore the missing
  frame. In case of multiple faulty frames, fade-in and fade-out is applied.

  \return  none
*/
static int
  CConcealment_ApplyInter (
    CConcealmentInfo       *pConcealmentInfo,
    CAacDecoderChannelInfo *pAacDecoderChannelInfo,
    const SamplingRateInfo *pSamplingRateInfo,
    const int  samplesPerFrame,
    const int  improveTonal,
    const int  frameOk )
{
  CConcealParams   *pConcealCommonData    =  pConcealmentInfo->pConcealParams;

  FIXP_DBL         *pSpectralCoefficient  =  SPEC_LONG(pAacDecoderChannelInfo->pSpectralCoefficient);
  CIcsInfo         *pIcsInfo              = &pAacDecoderChannelInfo->icsInfo;
  SHORT            *pSpecScale            =  pAacDecoderChannelInfo->specScale;


  int sfbEnergyPrev[64];
  int sfbEnergyAct [64];

  int i, appliedProcessing = 0;

  /* clear/init */
  FDKmemclear(sfbEnergyPrev, 64 * sizeof(int));
  FDKmemclear(sfbEnergyAct,  64 * sizeof(int));


  if (!frameOk)
  {
    /* Restore last frame from concealment buffer */
    pIcsInfo->WindowShape    = pConcealmentInfo->windowShape;
    pIcsInfo->WindowSequence = pConcealmentInfo->windowSequence;

    /* Restore spectral data */
    for (i = 0; i < samplesPerFrame; i++) {
      pSpectralCoefficient[i] = FX_CNCL2FX_DBL(pConcealmentInfo->spectralCoefficient[i]);
    }

    /* Restore scale factors */
    FDKmemcpy(pSpecScale, pConcealmentInfo->specScale, 8*sizeof(SHORT));
  }

  /* if previous frame was not ok */
  if (!pConcealmentInfo->prevFrameOk[1]) {

    /* if current frame (f_n) is ok and the last but one frame (f_(n-2))
       was ok, too, then interpolate both frames in order to generate
       the current output frame (f_(n-1)). Otherwise, use the last stored
       frame (f_(n-2) or f_(n-3) or ...). */
    if (frameOk && pConcealmentInfo->prevFrameOk[0])
    {
      appliedProcessing = 1;


      /* Interpolate both frames in order to generate the current output frame (f_(n-1)). */
      if (pIcsInfo->WindowSequence == EightShortSequence) {
        /* f_(n-2) == EightShortSequence */
        /* short--??????--short, short--??????--long interpolation */
        /* short--short---short, short---long---long interpolation */

        int wnd;

        if (pConcealmentInfo->windowSequence == EightShortSequence) { /* f_n == EightShortSequence */
          /* short--short---short interpolation */

          int scaleFactorBandsTotal = pSamplingRateInfo->NumberOfScaleFactorBands_Short;
          const SHORT *pSfbOffset   = pSamplingRateInfo->ScaleFactorBands_Short;
          pIcsInfo->WindowShape = 1;
          pIcsInfo->WindowSequence = EightShortSequence;

          for (wnd = 0; wnd < 8; wnd++)
          {
            CConcealment_CalcBandEnergy(
              &pSpectralCoefficient[wnd * (samplesPerFrame / 8)], /* spec_(n-2) */
               pSamplingRateInfo,
               EightShortSequence,
               CConcealment_NoExpand,
               sfbEnergyPrev);

            CConcealment_CalcBandEnergy(
              &pConcealmentInfo->spectralCoefficient[wnd * (samplesPerFrame / 8)], /* spec_n */
               pSamplingRateInfo,
               EightShortSequence,
               CConcealment_NoExpand,
               sfbEnergyAct);

            CConcealment_InterpolateBuffer(
              &pSpectralCoefficient[wnd * (samplesPerFrame / 8)], /* spec_(n-1) */
              &pSpecScale[wnd],
              &pConcealmentInfo->specScale[wnd],
              &pSpecScale[wnd],
               sfbEnergyPrev,
               sfbEnergyAct,
               scaleFactorBandsTotal,
               pSfbOffset);

          }
        } else { /* f_n != EightShortSequence */
          /* short---long---long interpolation */

          int scaleFactorBandsTotal = pSamplingRateInfo->NumberOfScaleFactorBands_Long;
          const SHORT *pSfbOffset   = pSamplingRateInfo->ScaleFactorBands_Long;
          SHORT specScaleOut;

          CConcealment_CalcBandEnergy(&pSpectralCoefficient[samplesPerFrame - (samplesPerFrame / 8)], /* [wnd] spec_(n-2) */
                                      pSamplingRateInfo,
                                      EightShortSequence,
                                      CConcealment_Expand,
                                      sfbEnergyAct);

          CConcealment_CalcBandEnergy(pConcealmentInfo->spectralCoefficient, /* spec_n */
                                      pSamplingRateInfo,
                                      OnlyLongSequence,
                                      CConcealment_NoExpand,
                                      sfbEnergyPrev);

          pIcsInfo->WindowShape = 0;
          pIcsInfo->WindowSequence = LongStopSequence;

          for (i = 0; i < samplesPerFrame ; i++) {
            pSpectralCoefficient[i] = pConcealmentInfo->spectralCoefficient[i]; /* spec_n */
          }

          for (i = 0; i < 8; i++) { /* search for max(specScale) */
            if (pSpecScale[i] > pSpecScale[0]) {
              pSpecScale[0] = pSpecScale[i];
            }
          }

          CConcealment_InterpolateBuffer(
            pSpectralCoefficient, /* spec_(n-1) */
           &pConcealmentInfo->specScale[0],
           &pSpecScale[0],
           &specScaleOut,
            sfbEnergyPrev,
            sfbEnergyAct,
            scaleFactorBandsTotal,
            pSfbOffset);

          pSpecScale[0] = specScaleOut;
        }
      } else {
        /* long--??????--short, long--??????--long interpolation */
        /* long---long---short, long---long---long interpolation */

        int scaleFactorBandsTotal = pSamplingRateInfo->NumberOfScaleFactorBands_Long;
        const SHORT *pSfbOffset   = pSamplingRateInfo->ScaleFactorBands_Long;
        SHORT specScaleAct        = pConcealmentInfo->specScale[0];

        CConcealment_CalcBandEnergy(pSpectralCoefficient,  /* spec_(n-2) */
                                    pSamplingRateInfo,
                                    OnlyLongSequence,
                                    CConcealment_NoExpand,
                                    sfbEnergyPrev);

        if (pConcealmentInfo->windowSequence == EightShortSequence) {  /* f_n == EightShortSequence */
          /* long---long---short interpolation */

          pIcsInfo->WindowShape = 1;
          pIcsInfo->WindowSequence = LongStartSequence;

          for (i = 1; i < 8; i++) { /* search for max(specScale) */
            if (pConcealmentInfo->specScale[i] > specScaleAct) {
              specScaleAct = pConcealmentInfo->specScale[i];
            }
          }

          /* Expand first short spectrum */
          CConcealment_CalcBandEnergy(pConcealmentInfo->spectralCoefficient,  /* spec_n */
                                      pSamplingRateInfo,
                                      EightShortSequence,
                                      CConcealment_Expand,  /* !!! */
                                      sfbEnergyAct);
        } else {
          /* long---long---long interpolation */

          pIcsInfo->WindowShape = 0;
          pIcsInfo->WindowSequence = OnlyLongSequence;

          CConcealment_CalcBandEnergy(pConcealmentInfo->spectralCoefficient,  /* spec_n */
                                      pSamplingRateInfo,
                                      OnlyLongSequence,
                                      CConcealment_NoExpand,
                                      sfbEnergyAct);
        }

          CConcealment_InterpolateBuffer(
            pSpectralCoefficient,  /* spec_(n-1) */
           &pSpecScale[0],
           &specScaleAct,
           &pSpecScale[0],
            sfbEnergyPrev,
            sfbEnergyAct,
            scaleFactorBandsTotal,
            pSfbOffset);

      }
    }

      /* Noise substitution of sign of the output spectral coefficients */
      CConcealment_ApplyRandomSign (pConcealmentInfo->iRandomPhase,
                                    pSpectralCoefficient,
                                    samplesPerFrame);
      /* Increment random phase index to avoid repetition artifacts. */
      pConcealmentInfo->iRandomPhase = (pConcealmentInfo->iRandomPhase + 1) & (AAC_NF_NO_RANDOM_VAL - 1);
  }

  /* scale spectrum according to concealment state */
  switch (pConcealmentInfo->concealState)
  {
  case ConcealState_Single:
    appliedProcessing = 1;
    break;

  case ConcealState_FadeOut:
    {
      FDK_ASSERT(pConcealmentInfo->cntFadeFrames >= 0);
      FDK_ASSERT(pConcealmentInfo->cntFadeFrames < CONCEAL_MAX_NUM_FADE_FACTORS);
      FDK_ASSERT(pConcealmentInfo->cntFadeFrames < pConcealCommonData->numFadeOutFrames);

      /* restore frequency coefficients from buffer with a specific muting */
      FIXP_DBL *RESTRICT pOut = &pSpectralCoefficient[samplesPerFrame-1];
      FIXP_SGL fac = pConcealCommonData->fadeOutFactor[pConcealmentInfo->cntFadeFrames];

      for (i = samplesPerFrame; i != 0; i--) {
        *pOut = fMult(*pOut, fac);
        pOut--;
      }
      appliedProcessing = 1;
    }
    break;

  case ConcealState_FadeIn:
    {
      FDK_ASSERT(pConcealmentInfo->cntFadeFrames >= 0);
      FDK_ASSERT(pConcealmentInfo->cntFadeFrames < CONCEAL_MAX_NUM_FADE_FACTORS);
      FDK_ASSERT(pConcealmentInfo->cntFadeFrames < pConcealCommonData->numFadeInFrames);

      /* attenuate signal to get a smooth fade-in */
      FIXP_DBL *RESTRICT pOut = &pSpectralCoefficient[samplesPerFrame-1];
      FIXP_SGL fac = pConcealCommonData->fadeInFactor[pConcealmentInfo->cntFadeFrames];

      for (i = samplesPerFrame; i != 0; i--) {
        *pOut = fMult(*pOut, fac);
        pOut--;
      }
      appliedProcessing = 1;
    }
    break;

  case ConcealState_Mute:
    {
      int fac = pConcealCommonData->comfortNoiseLevel;

      /* set dummy window parameters */
      pIcsInfo->Valid          = 0;                                /* Trigger the generation of a consitent IcsInfo */
      pIcsInfo->WindowShape    = pConcealmentInfo->windowShape;    /* Prevent an invalid WindowShape (required for F/T transform) */
      pIcsInfo->WindowSequence = CConcealment_GetWinSeq(pConcealmentInfo->windowSequence);
      pConcealmentInfo->windowSequence = pIcsInfo->WindowSequence; /* Store for next frame (spectrum in concealment buffer can't be used at all) */

      /* mute spectral data */
      FDKmemclear(pSpectralCoefficient, samplesPerFrame * sizeof(FIXP_DBL));

      if (fac >= 0 && fac <= 61) {
        /* insert comfort noise using PNS */
        CConcealment_fakePnsData (
         &pAacDecoderChannelInfo->data.aac.PnsData,
          pIcsInfo,
          pSamplingRateInfo,
          pAacDecoderChannelInfo->specScale,
          pAacDecoderChannelInfo->pDynData->aScaleFactor,
          fac
        );

        CPns_Apply (
               &pAacDecoderChannelInfo->data.aac.PnsData,
                pIcsInfo,
                pAacDecoderChannelInfo->pSpectralCoefficient,
                pAacDecoderChannelInfo->specScale,
                pAacDecoderChannelInfo->pDynData->aScaleFactor,
                pSamplingRateInfo,
                pAacDecoderChannelInfo->granuleLength,
                0  /* always apply to first channel */
              );
      }
      appliedProcessing = 1;
    }
    break;

  default:
    /* nothing to do here */
    break;
  }

  return appliedProcessing;
}


/*!
  \brief Calculate the spectral energy

  The function calculates band-wise the spectral energy. This is used for
  frame interpolation.

  \return  none
*/
static void
  CConcealment_CalcBandEnergy (
    FIXP_DBL               *spectrum,
    const SamplingRateInfo *pSamplingRateInfo,
    const int               blockType,
    CConcealmentExpandType  expandType,
    int                    *sfbEnergy )
{
  const SHORT *pSfbOffset;
  int line, sfb, scaleFactorBandsTotal = 0;
  
  /* In the following calculations, enAccu is initialized with LSB-value in order to avoid zero energy-level */

  line = 0;

  switch(blockType) {

  case OnlyLongSequence:
  case LongStartSequence:
  case LongStopSequence:

    if (expandType == CConcealment_NoExpand) {
      /* standard long calculation */
      scaleFactorBandsTotal = pSamplingRateInfo->NumberOfScaleFactorBands_Long;
      pSfbOffset            = pSamplingRateInfo->ScaleFactorBands_Long;

      for (sfb = 0; sfb < scaleFactorBandsTotal; sfb++) {
        FIXP_DBL enAccu = (FIXP_DBL)(LONG)1;
        int sfbScale = (sizeof(LONG)<<3) - CntLeadingZeros(pSfbOffset[sfb+1] - pSfbOffset[sfb]) - 1;
        /* scaling depends on sfb width. */
        for ( ; line < pSfbOffset[sfb+1]; line++) {
          enAccu += fPow2Div2(*(spectrum + line)) >> sfbScale;
        }
        *(sfbEnergy + sfb) = CntLeadingZeros(enAccu) - 1;
      }
    }
    else {
      /* compress long to short */
      scaleFactorBandsTotal = pSamplingRateInfo->NumberOfScaleFactorBands_Short;
      pSfbOffset            = pSamplingRateInfo->ScaleFactorBands_Short;

      for (sfb = 0; sfb < scaleFactorBandsTotal; sfb++) {
        FIXP_DBL enAccu = (FIXP_DBL)(LONG)1;
        int sfbScale = (sizeof(LONG)<<3) - CntLeadingZeros(pSfbOffset[sfb+1] - pSfbOffset[sfb]) - 1;
        /* scaling depends on sfb width. */
        for (; line < pSfbOffset[sfb+1] << 3; line++) {
          enAccu += (enAccu + (fPow2Div2(*(spectrum + line)) >> sfbScale)) >> 3;
        }
        *(sfbEnergy + sfb) = CntLeadingZeros(enAccu) - 1;
      }
    }
    break;

  case EightShortSequence:

    if (expandType == CConcealment_NoExpand) {
      /*   standard short calculation */
      scaleFactorBandsTotal = pSamplingRateInfo->NumberOfScaleFactorBands_Short;
      pSfbOffset            = pSamplingRateInfo->ScaleFactorBands_Short;

      for (sfb = 0; sfb < scaleFactorBandsTotal; sfb++) {
        FIXP_DBL enAccu = (FIXP_DBL)(LONG)1;
        int sfbScale = (sizeof(LONG)<<3) - CntLeadingZeros(pSfbOffset[sfb+1] - pSfbOffset[sfb]) - 1;
        /* scaling depends on sfb width. */
        for ( ; line < pSfbOffset[sfb+1]; line++) {
          enAccu += fPow2Div2(*(spectrum + line)) >> sfbScale;
        }
        *(sfbEnergy + sfb) = CntLeadingZeros(enAccu) - 1;
      }
    }
    else {
      /*  expand short to long spectrum */
      scaleFactorBandsTotal = pSamplingRateInfo->NumberOfScaleFactorBands_Long;
      pSfbOffset            = pSamplingRateInfo->ScaleFactorBands_Long;

      for (sfb = 0; sfb < scaleFactorBandsTotal; sfb++) {
        FIXP_DBL enAccu = (FIXP_DBL)(LONG)1;
        int sfbScale = (sizeof(LONG)<<3) - CntLeadingZeros(pSfbOffset[sfb+1] - pSfbOffset[sfb]) - 1;
        /* scaling depends on sfb width. */
        for ( ; line < pSfbOffset[sfb+1]; line++) {
          enAccu += fPow2Div2(*(spectrum + (line >> 3))) >> sfbScale;
        }
        *(sfbEnergy + sfb) = CntLeadingZeros(enAccu) - 1;
      }
    }
    break;
  }
}


/*!
  \brief Interpolate buffer

  The function creates the interpolated spectral data according to the
  energy of the last good frame and the current (good) frame.

  \return  none
*/
static void
  CConcealment_InterpolateBuffer (
    FIXP_DBL    *spectrum,
    SHORT       *pSpecScalePrv,
    SHORT       *pSpecScaleAct,
    SHORT       *pSpecScaleOut,
    int         *enPrv,
    int         *enAct,
    int          sfbCnt,
    const SHORT *pSfbOffset )
{
  int    sfb, line = 0;
  int    fac_shift;
  int    fac_mod;
  FIXP_DBL accu;

  for (sfb = 0; sfb < sfbCnt; sfb++) {

    fac_shift = enPrv[sfb] - enAct[sfb] + ((*pSpecScaleAct - *pSpecScalePrv) << 1);
    fac_mod   = fac_shift & 3;
    fac_shift = (fac_shift >> 2) + 1;
    fac_shift += *pSpecScalePrv - fixMax(*pSpecScalePrv, *pSpecScaleAct);

    for (; line < pSfbOffset[sfb+1]; line++) {
      accu = fMult(*(spectrum+line), facMod4Table[fac_mod]);
      if (fac_shift < 0) {
        accu >>= -fac_shift;
      } else {
        accu <<= fac_shift;
      }
      *(spectrum+line) = accu;
    }
  }
  *pSpecScaleOut = fixMax(*pSpecScalePrv, *pSpecScaleAct);
}




static INT findEquiFadeFrame (
    CConcealParams *pConcealCommonData,
    INT actFadeIndex,
    int direction )
{
  FIXP_SGL *pFactor;
  FIXP_SGL  referenceVal;
  FIXP_SGL  minDiff = (FIXP_SGL)MAXVAL_SGL;

  INT  numFrames = 0;
  INT  nextFadeIndex = 0;

  int  i;

  /* init depending on direction */
  if (direction == 0) {  /* FADE-OUT => FADE-IN */
    numFrames = pConcealCommonData->numFadeInFrames;
    referenceVal = pConcealCommonData->fadeOutFactor[actFadeIndex] >> 1;
    pFactor = pConcealCommonData->fadeInFactor;
  }
  else {  /* FADE-IN => FADE-OUT */
    numFrames = pConcealCommonData->numFadeOutFrames;
    referenceVal = pConcealCommonData->fadeInFactor[actFadeIndex] >> 1;
    pFactor = pConcealCommonData->fadeOutFactor;
  }

  /* search for minimum difference */
  for (i = 0; i < numFrames; i++) {
    FIXP_SGL diff = fixp_abs((pFactor[i]>>1) - referenceVal);
    if (diff < minDiff) {
      minDiff = diff;
      nextFadeIndex = i;
    }
  }

  /* check and adjust depending on direction */
  if (direction == 0) {  /* FADE-OUT => FADE-IN */
    if (((pFactor[nextFadeIndex]>>1) <= referenceVal) && (nextFadeIndex > 0)) {
      nextFadeIndex -= 1;
    }
  }
  else {  /* FADE-IN => FADE-OUT */
    if (((pFactor[nextFadeIndex]>>1) >= referenceVal) && (nextFadeIndex < numFrames-1)) {
      nextFadeIndex += 1;
    }
  }

  return (nextFadeIndex);
}


/*!
  \brief Update the concealment state

  The function updates the state of the concealment state-machine. The
  states are: mute, fade-in, fade-out, interpolate and frame-ok.

  \return  none
*/
static void
  CConcealment_UpdateState (
    CConcealmentInfo *pConcealmentInfo,
    int frameOk )
{
  CConcealParams *pConcealCommonData = pConcealmentInfo->pConcealParams;

  switch (pConcealCommonData->method)
  {
  case ConcealMethodNoise:
    {
      if (pConcealmentInfo->concealState != ConcealState_Ok) {
        /* count the valid frames during concealment process */
        if (frameOk) {
          pConcealmentInfo->cntValidFrames += 1;
        } else {
          pConcealmentInfo->cntValidFrames  = 0;
        }
      }

      /* -- STATE MACHINE for Noise Substitution -- */
      switch (pConcealmentInfo->concealState)
      {
      case ConcealState_Ok:
        if (!frameOk) {
          /* change to state SINGLE-FRAME-LOSS */
          pConcealmentInfo->concealState   = ConcealState_Single;
          pConcealmentInfo->cntFadeFrames  = 0;
          pConcealmentInfo->cntValidFrames = 0;
        }
        break;

      case ConcealState_Single:  /* Just a pre-stage before fade-out begins. Stay here only one frame! */
        pConcealmentInfo->cntFadeFrames += 1;
        if (frameOk) {
          if (pConcealmentInfo->cntValidFrames > pConcealCommonData->numMuteReleaseFrames) {
            /* change to state FADE-IN */
            pConcealmentInfo->concealState  = ConcealState_FadeIn;
            pConcealmentInfo->cntFadeFrames = findEquiFadeFrame( pConcealCommonData,
                                                                 pConcealmentInfo->cntFadeFrames-1,
                                                                 0 /* FadeOut -> FadeIn */);
          } else {
            /* change to state OK */
            pConcealmentInfo->concealState = ConcealState_Ok;
          }
        } else {
          if (pConcealmentInfo->cntFadeFrames >= pConcealCommonData->numFadeOutFrames) {
            /* change to state MUTE */
            pConcealmentInfo->concealState = ConcealState_Mute;
          } else {
            /* change to state FADE-OUT */
            pConcealmentInfo->concealState = ConcealState_FadeOut;
          }
        }
        break;

      case ConcealState_FadeOut:
        pConcealmentInfo->cntFadeFrames += 1;  /* used to address the fade-out factors */
        if (pConcealmentInfo->cntValidFrames > pConcealCommonData->numMuteReleaseFrames) {
          /* change to state FADE-IN */
          pConcealmentInfo->concealState  = ConcealState_FadeIn;
          pConcealmentInfo->cntFadeFrames = findEquiFadeFrame( pConcealCommonData,
                                                               pConcealmentInfo->cntFadeFrames-1,
                                                               0 /* FadeOut -> FadeIn */);
        } else {
          if (pConcealmentInfo->cntFadeFrames >= pConcealCommonData->numFadeOutFrames) {
            /* change to state MUTE */
            pConcealmentInfo->concealState = ConcealState_Mute;
          }
        }
        break;

      case ConcealState_Mute:
        if (pConcealmentInfo->cntValidFrames > pConcealCommonData->numMuteReleaseFrames) {
          /* change to state FADE-IN */
          pConcealmentInfo->concealState = ConcealState_FadeIn;
          pConcealmentInfo->cntFadeFrames = pConcealCommonData->numFadeInFrames - 1;
        }
        break;

      case ConcealState_FadeIn:
        pConcealmentInfo->cntFadeFrames -= 1;  /* used to address the fade-in factors */
        if (frameOk) {
          if (pConcealmentInfo->cntFadeFrames < 0) {
            /* change to state OK */
            pConcealmentInfo->concealState = ConcealState_Ok;
          }
        } else {
          /* change to state FADE-OUT */
          pConcealmentInfo->concealState  = ConcealState_FadeOut;
          pConcealmentInfo->cntFadeFrames = findEquiFadeFrame( pConcealCommonData,
                                                               pConcealmentInfo->cntFadeFrames+1,
                                                               1 /* FadeIn -> FadeOut */);
        }
        break;

      default:
        FDK_ASSERT(0);
        break;
      }
    }
    break;

  case ConcealMethodInter:
  case ConcealMethodTonal:
    {
      if (pConcealmentInfo->concealState != ConcealState_Ok) {
        /* count the valid frames during concealment process */
        if ( pConcealmentInfo->prevFrameOk[1] ||
            (pConcealmentInfo->prevFrameOk[0] && !pConcealmentInfo->prevFrameOk[1] && frameOk) ) {
          /* The frame is OK even if it can be estimated by the energy interpolation algorithm */
          pConcealmentInfo->cntValidFrames += 1;
        } else {
          pConcealmentInfo->cntValidFrames  = 0;
        }
      }

      /* -- STATE MACHINE for energy interpolation -- */
      switch (pConcealmentInfo->concealState)
      {
      case ConcealState_Ok:
        if (!(pConcealmentInfo->prevFrameOk[1] ||
             (pConcealmentInfo->prevFrameOk[0] && !pConcealmentInfo->prevFrameOk[1] && frameOk))) {
          /* Fade out only if the energy interpolation algorithm can not be applied! */
          pConcealmentInfo->concealState   = ConcealState_FadeOut;
          pConcealmentInfo->cntFadeFrames  = 0;
          pConcealmentInfo->cntValidFrames = 0;
        }
        break;

      case ConcealState_Single:
        pConcealmentInfo->concealState = ConcealState_Ok;
        break;

      case ConcealState_FadeOut:
        pConcealmentInfo->cntFadeFrames += 1;

        if (pConcealmentInfo->cntValidFrames > pConcealCommonData->numMuteReleaseFrames) {
          /* change to state FADE-IN */
          pConcealmentInfo->concealState  = ConcealState_FadeIn;
          pConcealmentInfo->cntFadeFrames = findEquiFadeFrame( pConcealCommonData,
                                                               pConcealmentInfo->cntFadeFrames-1,
                                                               0 /* FadeOut -> FadeIn */);
        } else {
          if (pConcealmentInfo->cntFadeFrames >= pConcealCommonData->numFadeOutFrames) {
            /* change to state MUTE */
            pConcealmentInfo->concealState = ConcealState_Mute;
          }
        }
        break;

      case ConcealState_Mute:
        if (pConcealmentInfo->cntValidFrames > pConcealCommonData->numMuteReleaseFrames) {
          /* change to state FADE-IN */
          pConcealmentInfo->concealState = ConcealState_FadeIn;
          pConcealmentInfo->cntFadeFrames = pConcealCommonData->numFadeInFrames - 1;
        }
        break;

      case ConcealState_FadeIn:
        pConcealmentInfo->cntFadeFrames -= 1;  /* used to address the fade-in factors */

        if (frameOk || pConcealmentInfo->prevFrameOk[1]) {
          if (pConcealmentInfo->cntFadeFrames < 0) {
            /* change to state OK */
            pConcealmentInfo->concealState = ConcealState_Ok;
          }
        } else {
          /* change to state FADE-OUT */
          pConcealmentInfo->concealState  = ConcealState_FadeOut;
          pConcealmentInfo->cntFadeFrames = findEquiFadeFrame( pConcealCommonData,
                                                               pConcealmentInfo->cntFadeFrames+1,
                                                               1 /* FadeIn -> FadeOut */);
        }
        break;
      } /* End switch(pConcealmentInfo->concealState) */
    }
    break;

  default:
    /* Don't need a state machine for other concealment methods. */
    break;
  }

}


/*!
\brief Randomizes the sign of the spectral data

  The function toggles the sign of the spectral data randomly. This is
  useful to ensure the quality of the concealed frames.

\return  none
 */
static
void CConcealment_ApplyRandomSign (int randomPhase,
                                   FIXP_DBL *spec,
                                   int samplesPerFrame
                                               )
{
  int i;
  USHORT packedSign=0;

  /* random table 512x16bit has been reduced to 512 packed sign bits = 32x16 bit */

  /* read current packed sign word */
  packedSign = randomSign[randomPhase>>4];
  packedSign >>= (randomPhase&0xf);

  for (i = 0; i < samplesPerFrame ; i++) {
    if ((randomPhase & 0xf) == 0) {
      packedSign = randomSign[randomPhase>>4];
    }

    if (packedSign & 0x1) {
      spec[i] = -spec[i];
    }
    packedSign >>= 1;

    randomPhase = (randomPhase + 1) & (AAC_NF_NO_RANDOM_VAL - 1);
  }
}


/*!
  \brief Get fadeing factor for current concealment state.

  The function returns the factor used for fading that belongs to the current internal state.

  \return Fade factor
 */
FIXP_DBL
  CConcealment_GetFadeFactor (
      CConcealmentInfo *hConcealmentInfo,
      const int fPreviousFactor
  )
{
  FIXP_DBL fac = (FIXP_DBL)0;

  CConcealParams *pConcealCommonData = hConcealmentInfo->pConcealParams;

  if (hConcealmentInfo->pConcealParams->method > ConcealMethodMute) {
    switch (hConcealmentInfo->concealState) {
      default:
      case ConcealState_Mute:
        /* Nothing to do here */
        break;
      case ConcealState_Ok:
        fac = (FIXP_DBL)MAXVAL_DBL;
        break;
      case ConcealState_Single:
      case ConcealState_FadeOut:
        {
          int idx = hConcealmentInfo->cntFadeFrames - ((fPreviousFactor != 0) ? 1 : 0);
          fac = (idx < 0) ? (FIXP_DBL)MAXVAL_DBL : FX_SGL2FX_DBL(pConcealCommonData->fadeOutFactor[idx]);
        }
        break;
      case ConcealState_FadeIn:
        {
          int idx = hConcealmentInfo->cntFadeFrames + ((fPreviousFactor != 0) ? 1 : 0);
          fac = (idx >= hConcealmentInfo->pConcealParams->numFadeInFrames) ? (FIXP_DBL)0 : FX_SGL2FX_DBL(pConcealCommonData->fadeInFactor[idx]);
        }
        break;
    }
  }

  return (fac);
}


/*!
  \brief Get fadeing factor for current concealment state.

  The function returns the state (ok or not) of the previous frame.
  If called before the function CConcealment_Apply() set the fBeforeApply
  flag to get the correct value.

  \return Frame OK flag of previous frame.
 */
int
  CConcealment_GetLastFrameOk (
      CConcealmentInfo *hConcealmentInfo,
      const int fBeforeApply
  )
{
  int prevFrameOk = 1;

  if (hConcealmentInfo != NULL) {
    prevFrameOk = hConcealmentInfo->prevFrameOk[fBeforeApply & 0x1];
  }

  return prevFrameOk;
}

/*!
  \brief Get the number of delay frames introduced by concealment technique. 

  \return Number of delay frames.
 */
UINT
  CConcealment_GetDelay (
      CConcealParams *pConcealCommonData
  )
{
  UINT frameDelay = 0;

  if (pConcealCommonData != NULL) {
    switch (pConcealCommonData->method) {
    case ConcealMethodTonal:
    case ConcealMethodInter:
      frameDelay = 1;
      break;
    default:
      break;
    }
  }

  return frameDelay;
}