aboutsummaryrefslogtreecommitdiffstats
path: root/libAACenc/src/adj_thr.cpp
blob: 239abd00f2643caf7fef17944eccf8efd2d65990 (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
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
/* -----------------------------------------------------------------------------
Software License for The Fraunhofer FDK AAC Codec Library for Android

© Copyright  1995 - 2019 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
----------------------------------------------------------------------------- */

/**************************** AAC encoder library ******************************

   Author(s):   M. Werner

   Description: Threshold compensation

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

#include "adj_thr.h"
#include "sf_estim.h"
#include "aacEnc_ram.h"

#define NUM_NRG_LEVS (8)
#define INV_INT_TAB_SIZE (8)
static const FIXP_DBL invInt[INV_INT_TAB_SIZE] = {
    0x7fffffff, 0x7fffffff, 0x40000000, 0x2aaaaaaa,
    0x20000000, 0x19999999, 0x15555555, 0x12492492};

#define INV_SQRT4_TAB_SIZE (8)
static const FIXP_DBL invSqrt4[INV_SQRT4_TAB_SIZE] = {
    0x7fffffff, 0x7fffffff, 0x6ba27e65, 0x61424bb5,
    0x5a827999, 0x55994845, 0x51c8e33c, 0x4eb160d1};

/*static const INT      invRedExp = 4;*/
static const FIXP_DBL SnrLdMin1 =
    (FIXP_DBL)0xfcad0ddf; /*FL2FXCONST_DBL(FDKlog(0.316)/FDKlog(2.0)/LD_DATA_SCALING);*/
static const FIXP_DBL SnrLdMin2 =
    (FIXP_DBL)0x0351e1a2; /*FL2FXCONST_DBL(FDKlog(3.16)
                             /FDKlog(2.0)/LD_DATA_SCALING);*/
static const FIXP_DBL SnrLdFac =
    (FIXP_DBL)0xff5b2c3e; /*FL2FXCONST_DBL(FDKlog(0.8)
                             /FDKlog(2.0)/LD_DATA_SCALING);*/

static const FIXP_DBL SnrLdMin3 =
    (FIXP_DBL)0xfe000000; /*FL2FXCONST_DBL(FDKlog(0.5)
                             /FDKlog(2.0)/LD_DATA_SCALING);*/
static const FIXP_DBL SnrLdMin4 =
    (FIXP_DBL)0x02000000; /*FL2FXCONST_DBL(FDKlog(2.0)
                             /FDKlog(2.0)/LD_DATA_SCALING);*/
static const FIXP_DBL SnrLdMin5 =
    (FIXP_DBL)0xfc000000; /*FL2FXCONST_DBL(FDKlog(0.25)
                             /FDKlog(2.0)/LD_DATA_SCALING);*/

/*
The bits2Pe factors are choosen for the case that some times
the crash recovery strategy will be activated once.
*/
#define AFTERBURNER_STATI 2
#define MAX_ALLOWED_EL_CHANNELS 2

typedef struct {
  INT bitrate;
  FIXP_DBL bits2PeFactor[AFTERBURNER_STATI][MAX_ALLOWED_EL_CHANNELS];
} BIT_PE_SFAC;

typedef struct {
  INT sampleRate;
  const BIT_PE_SFAC *pPeTab;
  INT nEntries;

} BITS2PE_CFG_TAB;

#define FL2B2PE(value) FL2FXCONST_DBL((value) / (1 << 2))

static const BIT_PE_SFAC S_Bits2PeTab16000[] = {
    /* bitrate|   afterburner off              |   afterburner on | |   nCh=1
       |   nCh=2       |   nCh=1       |   nCh=2        */
    {10000,
     {{FL2B2PE(1.60f), FL2B2PE(0.00f)}, {FL2B2PE(1.40f), FL2B2PE(0.00f)}}},
    {24000,
     {{FL2B2PE(1.80f), FL2B2PE(1.40f)}, {FL2B2PE(1.60f), FL2B2PE(1.20f)}}},
    {32000,
     {{FL2B2PE(1.80f), FL2B2PE(1.60f)}, {FL2B2PE(1.60f), FL2B2PE(1.40f)}}},
    {48000,
     {{FL2B2PE(1.60f), FL2B2PE(1.80f)}, {FL2B2PE(1.60f), FL2B2PE(1.60f)}}},
    {64000,
     {{FL2B2PE(1.20f), FL2B2PE(1.60f)}, {FL2B2PE(1.20f), FL2B2PE(1.60f)}}},
    {96000,
     {{FL2B2PE(1.40f), FL2B2PE(1.80f)}, {FL2B2PE(1.40f), FL2B2PE(1.60f)}}},
    {128000,
     {{FL2B2PE(1.40f), FL2B2PE(1.80f)}, {FL2B2PE(1.40f), FL2B2PE(1.80f)}}},
    {148000,
     {{FL2B2PE(1.40f), FL2B2PE(1.80f)}, {FL2B2PE(1.40f), FL2B2PE(1.40f)}}}};

static const BIT_PE_SFAC S_Bits2PeTab22050[] = {
    /* bitrate|   afterburner off              |   afterburner on | |   nCh=1
       |   nCh=2       |   nCh=1       |   nCh=2        */
    {16000,
     {{FL2B2PE(1.60f), FL2B2PE(1.40f)}, {FL2B2PE(1.20f), FL2B2PE(0.80f)}}},
    {24000,
     {{FL2B2PE(1.60f), FL2B2PE(1.40f)}, {FL2B2PE(1.40f), FL2B2PE(1.00f)}}},
    {32000,
     {{FL2B2PE(1.40f), FL2B2PE(1.40f)}, {FL2B2PE(1.40f), FL2B2PE(1.20f)}}},
    {48000,
     {{FL2B2PE(1.20f), FL2B2PE(1.60f)}, {FL2B2PE(1.20f), FL2B2PE(1.40f)}}},
    {64000,
     {{FL2B2PE(1.60f), FL2B2PE(1.60f)}, {FL2B2PE(1.60f), FL2B2PE(1.40f)}}},
    {96000,
     {{FL2B2PE(1.80f), FL2B2PE(1.60f)}, {FL2B2PE(1.80f), FL2B2PE(1.60f)}}},
    {128000,
     {{FL2B2PE(1.80f), FL2B2PE(1.80f)}, {FL2B2PE(1.60f), FL2B2PE(1.60f)}}},
    {148000,
     {{FL2B2PE(1.40f), FL2B2PE(1.80f)}, {FL2B2PE(1.40f), FL2B2PE(1.60f)}}}};

static const BIT_PE_SFAC S_Bits2PeTab24000[] = {
    /* bitrate|   afterburner off              |   afterburner on | |   nCh=1
       |   nCh=2       |   nCh=1      |   nCh=2         */
    {16000,
     {{FL2B2PE(1.40f), FL2B2PE(1.40f)}, {FL2B2PE(1.20f), FL2B2PE(0.80f)}}},
    {24000,
     {{FL2B2PE(1.60f), FL2B2PE(1.20f)}, {FL2B2PE(1.40f), FL2B2PE(1.00f)}}},
    {32000,
     {{FL2B2PE(1.40f), FL2B2PE(1.20f)}, {FL2B2PE(1.40f), FL2B2PE(0.80f)}}},
    {48000,
     {{FL2B2PE(1.40f), FL2B2PE(1.60f)}, {FL2B2PE(1.40f), FL2B2PE(1.40f)}}},
    {64000,
     {{FL2B2PE(1.60f), FL2B2PE(1.60f)}, {FL2B2PE(1.60f), FL2B2PE(1.40f)}}},
    {96000,
     {{FL2B2PE(1.80f), FL2B2PE(1.60f)}, {FL2B2PE(1.80f), FL2B2PE(1.60f)}}},
    {128000,
     {{FL2B2PE(1.40f), FL2B2PE(1.60f)}, {FL2B2PE(1.80f), FL2B2PE(1.80f)}}},
    {148000,
     {{FL2B2PE(1.40f), FL2B2PE(1.60f)}, {FL2B2PE(1.40f), FL2B2PE(1.80f)}}}};

static const BIT_PE_SFAC S_Bits2PeTab32000[] = {
    /* bitrate|   afterburner off              |   afterburner on | |   nCh=1
       |   nCh=2       |   nCh=1       |   nCh=2        */
    {16000,
     {{FL2B2PE(1.20f), FL2B2PE(1.40f)}, {FL2B2PE(0.80f), FL2B2PE(0.80f)}}},
    {24000,
     {{FL2B2PE(1.40f), FL2B2PE(1.20f)}, {FL2B2PE(1.00f), FL2B2PE(0.60f)}}},
    {32000,
     {{FL2B2PE(1.20f), FL2B2PE(1.20f)}, {FL2B2PE(1.00f), FL2B2PE(0.80f)}}},
    {48000,
     {{FL2B2PE(1.40f), FL2B2PE(1.40f)}, {FL2B2PE(1.20f), FL2B2PE(1.20f)}}},
    {64000,
     {{FL2B2PE(1.60f), FL2B2PE(1.40f)}, {FL2B2PE(1.60f), FL2B2PE(1.20f)}}},
    {96000,
     {{FL2B2PE(1.60f), FL2B2PE(1.40f)}, {FL2B2PE(1.60f), FL2B2PE(1.40f)}}},
    {128000,
     {{FL2B2PE(1.80f), FL2B2PE(1.60f)}, {FL2B2PE(1.80f), FL2B2PE(1.60f)}}},
    {148000,
     {{FL2B2PE(1.80f), FL2B2PE(1.60f)}, {FL2B2PE(1.80f), FL2B2PE(1.60f)}}},
    {160000,
     {{FL2B2PE(1.80f), FL2B2PE(1.60f)}, {FL2B2PE(1.80f), FL2B2PE(1.60f)}}},
    {200000,
     {{FL2B2PE(1.40f), FL2B2PE(1.60f)}, {FL2B2PE(1.40f), FL2B2PE(1.60f)}}},
    {320000,
     {{FL2B2PE(3.20f), FL2B2PE(1.80f)}, {FL2B2PE(3.20f), FL2B2PE(1.80f)}}}};

static const BIT_PE_SFAC S_Bits2PeTab44100[] = {
    /* bitrate|   afterburner off              |   afterburner on | |   nCh=1
       |   nCh=2       |   nCh=1       |   nCh=2        */
    {16000,
     {{FL2B2PE(1.20f), FL2B2PE(1.60f)}, {FL2B2PE(0.80f), FL2B2PE(1.00f)}}},
    {24000,
     {{FL2B2PE(1.00f), FL2B2PE(1.20f)}, {FL2B2PE(1.00f), FL2B2PE(0.80f)}}},
    {32000,
     {{FL2B2PE(1.20f), FL2B2PE(1.20f)}, {FL2B2PE(0.80f), FL2B2PE(0.60f)}}},
    {48000,
     {{FL2B2PE(1.20f), FL2B2PE(1.20f)}, {FL2B2PE(1.20f), FL2B2PE(0.80f)}}},
    {64000,
     {{FL2B2PE(1.40f), FL2B2PE(1.20f)}, {FL2B2PE(1.20f), FL2B2PE(1.00f)}}},
    {96000,
     {{FL2B2PE(1.60f), FL2B2PE(1.20f)}, {FL2B2PE(1.60f), FL2B2PE(1.20f)}}},
    {128000,
     {{FL2B2PE(1.60f), FL2B2PE(1.60f)}, {FL2B2PE(1.60f), FL2B2PE(1.40f)}}},
    {148000,
     {{FL2B2PE(1.60f), FL2B2PE(1.60f)}, {FL2B2PE(1.60f), FL2B2PE(1.60f)}}},
    {160000,
     {{FL2B2PE(1.60f), FL2B2PE(1.60f)}, {FL2B2PE(1.60f), FL2B2PE(1.60f)}}},
    {200000,
     {{FL2B2PE(1.80f), FL2B2PE(1.60f)}, {FL2B2PE(1.60f), FL2B2PE(1.60f)}}},
    {320000,
     {{FL2B2PE(3.20f), FL2B2PE(1.60f)}, {FL2B2PE(3.20f), FL2B2PE(1.60f)}}}};

static const BIT_PE_SFAC S_Bits2PeTab48000[] = {
    /* bitrate|   afterburner off              |   afterburner on | |   nCh=1
       |   nCh=2       |   nCh=1       |   nCh=2        */
    {16000,
     {{FL2B2PE(1.40f), FL2B2PE(0.00f)}, {FL2B2PE(0.80f), FL2B2PE(0.00f)}}},
    {24000,
     {{FL2B2PE(1.40f), FL2B2PE(1.20f)}, {FL2B2PE(1.00f), FL2B2PE(0.80f)}}},
    {32000,
     {{FL2B2PE(1.00f), FL2B2PE(1.20f)}, {FL2B2PE(0.60f), FL2B2PE(0.80f)}}},
    {48000,
     {{FL2B2PE(1.20f), FL2B2PE(1.00f)}, {FL2B2PE(0.80f), FL2B2PE(0.80f)}}},
    {64000,
     {{FL2B2PE(1.20f), FL2B2PE(1.20f)}, {FL2B2PE(1.20f), FL2B2PE(1.00f)}}},
    {96000,
     {{FL2B2PE(1.60f), FL2B2PE(1.40f)}, {FL2B2PE(1.60f), FL2B2PE(1.20f)}}},
    {128000,
     {{FL2B2PE(1.60f), FL2B2PE(1.60f)}, {FL2B2PE(1.60f), FL2B2PE(1.40f)}}},
    {148000,
     {{FL2B2PE(1.60f), FL2B2PE(1.60f)}, {FL2B2PE(1.60f), FL2B2PE(1.40f)}}},
    {160000,
     {{FL2B2PE(1.60f), FL2B2PE(1.60f)}, {FL2B2PE(1.60f), FL2B2PE(1.40f)}}},
    {200000,
     {{FL2B2PE(1.20f), FL2B2PE(1.60f)}, {FL2B2PE(1.60f), FL2B2PE(1.40f)}}},
    {320000,
     {{FL2B2PE(3.20f), FL2B2PE(1.60f)}, {FL2B2PE(3.20f), FL2B2PE(1.60f)}}}};

static const BITS2PE_CFG_TAB bits2PeConfigTab[] = {
    {16000, S_Bits2PeTab16000, sizeof(S_Bits2PeTab16000) / sizeof(BIT_PE_SFAC)},
    {22050, S_Bits2PeTab22050, sizeof(S_Bits2PeTab22050) / sizeof(BIT_PE_SFAC)},
    {24000, S_Bits2PeTab24000, sizeof(S_Bits2PeTab24000) / sizeof(BIT_PE_SFAC)},
    {32000, S_Bits2PeTab32000, sizeof(S_Bits2PeTab32000) / sizeof(BIT_PE_SFAC)},
    {44100, S_Bits2PeTab44100, sizeof(S_Bits2PeTab44100) / sizeof(BIT_PE_SFAC)},
    {48000, S_Bits2PeTab48000,
     sizeof(S_Bits2PeTab48000) / sizeof(BIT_PE_SFAC)}};

/* values for avoid hole flag */
enum _avoid_hole_state { NO_AH = 0, AH_INACTIVE = 1, AH_ACTIVE = 2 };

/*  Q format definitions */
#define Q_BITFAC \
  (24) /* Q scaling used in FDKaacEnc_bitresCalcBitFac() calculation */
#define Q_AVGBITS (17) /* scale bit values */

/*****************************************************************************
    functionname: FDKaacEnc_InitBits2PeFactor
    description:  retrieve bits2PeFactor from table
*****************************************************************************/
static void FDKaacEnc_InitBits2PeFactor(
    FIXP_DBL *bits2PeFactor_m, INT *bits2PeFactor_e, const INT bitRate,
    const INT nChannels, const INT sampleRate, const INT advancedBitsToPe,
    const INT dZoneQuantEnable, const INT invQuant) {
  /**** 1) Set default bits2pe factor ****/
  FIXP_DBL bit2PE_m = FL2FXCONST_DBL(1.18f / (1 << (1)));
  INT bit2PE_e = 1;

  /**** 2) For AAC-(E)LD, make use of advanced bits to pe factor table ****/
  if (advancedBitsToPe && nChannels <= (2)) {
    int i;
    const BIT_PE_SFAC *peTab = NULL;
    INT size = 0;

    /*** 2.1) Get correct table entry ***/
    for (i = 0; i < (INT)(sizeof(bits2PeConfigTab) / sizeof(BITS2PE_CFG_TAB));
         i++) {
      if (sampleRate >= bits2PeConfigTab[i].sampleRate) {
        peTab = bits2PeConfigTab[i].pPeTab;
        size = bits2PeConfigTab[i].nEntries;
      }
    }

    if ((peTab != NULL) && (size != 0)) {
      INT startB = -1; /* bitrate entry in table that is the next-lower to
                          actual bitrate  */
      INT stopB = -1;  /* bitrate entry in table that is the next-higher to
                          actual bitrate */
      FIXP_DBL startPF =
          FL2FXCONST_DBL(0.0f); /* bits2PE factor entry in table that is the
                                   next-lower to actual bits2PE factor  */
      FIXP_DBL stopPF = FL2FXCONST_DBL(0.0f); /* bits2PE factor entry in table
                                                 that is the next-higher to
                                                 actual bits2PE factor */
      FIXP_DBL slope = FL2FXCONST_DBL(
          0.0f); /* the slope from the start bits2Pe entry to the next one */
      const int qualityIdx = (invQuant == 0) ? 0 : 1;

      if (bitRate >= peTab[size - 1].bitrate) {
        /* Chosen bitrate is higher than the highest bitrate in table.
           The slope for extrapolating the bits2PE factor must be zero.
           Values are set accordingly.                                       */
        startB = peTab[size - 1].bitrate;
        stopB =
            bitRate +
            1; /* Can be an arbitrary value greater than startB and bitrate. */
        startPF = peTab[size - 1].bits2PeFactor[qualityIdx][nChannels - 1];
        stopPF = peTab[size - 1].bits2PeFactor[qualityIdx][nChannels - 1];
      } else {
        for (i = 0; i < size - 1; i++) {
          if ((peTab[i].bitrate <= bitRate) &&
              (peTab[i + 1].bitrate > bitRate)) {
            startB = peTab[i].bitrate;
            stopB = peTab[i + 1].bitrate;
            startPF = peTab[i].bits2PeFactor[qualityIdx][nChannels - 1];
            stopPF = peTab[i + 1].bits2PeFactor[qualityIdx][nChannels - 1];
            break;
          }
        }
      }

      /*** 2.2) Configuration available? ***/
      if (startB != -1) {
        /** 2.2.1) linear interpolate to actual PEfactor **/
        FIXP_DBL bit2PE = 0;

        const FIXP_DBL maxBit2PE = FL2FXCONST_DBL(3.f / 4.f);

        /* bit2PE = ((stopPF-startPF)/(stopB-startB))*(bitRate-startB)+startPF;
         */
        slope = fDivNorm(bitRate - startB, stopB - startB);
        bit2PE = fMult(slope, stopPF - startPF) + startPF;

        bit2PE = fMin(maxBit2PE, bit2PE);

        /** 2.2.2) sanity check if bits2pe value is high enough **/
        if (bit2PE >= (FL2FXCONST_DBL(0.35f) >> 2)) {
          bit2PE_m = bit2PE;
          bit2PE_e = 2; /*  table is fixed scaled */
        }
      } /* br */
    }   /* sr */
  }     /* advancedBitsToPe */

  if (dZoneQuantEnable) {
    if (bit2PE_m >= (FL2FXCONST_DBL(0.6f)) >> bit2PE_e) {
      /* Additional headroom for addition */
      bit2PE_m >>= 1;
      bit2PE_e += 1;
    }

    /* the quantTendencyCompensator compensates a lower bit consumption due to
     * increasing the tendency to quantize low spectral values to the lower
     * quantizer border for bitrates below a certain bitrate threshold --> see
     * also function calcSfbDistLD in quantize.c */
    if ((bitRate / nChannels > 32000) && (bitRate / nChannels <= 40000)) {
      bit2PE_m += (FL2FXCONST_DBL(0.4f)) >> bit2PE_e;
    } else if (bitRate / nChannels > 20000) {
      bit2PE_m += (FL2FXCONST_DBL(0.3f)) >> bit2PE_e;
    } else if (bitRate / nChannels >= 16000) {
      bit2PE_m += (FL2FXCONST_DBL(0.3f)) >> bit2PE_e;
    } else {
      bit2PE_m += (FL2FXCONST_DBL(0.0f)) >> bit2PE_e;
    }
  }

  /***** 3.) Return bits2pe factor *****/
  *bits2PeFactor_m = bit2PE_m;
  *bits2PeFactor_e = bit2PE_e;
}

/*****************************************************************************
functionname: FDKaacEnc_bits2pe2
description:  convert from bits to pe
*****************************************************************************/
FDK_INLINE INT FDKaacEnc_bits2pe2(const INT bits, const FIXP_DBL factor_m,
                                  const INT factor_e) {
  return (INT)(fMult(factor_m, (FIXP_DBL)(bits << Q_AVGBITS)) >>
               (Q_AVGBITS - factor_e));
}

/*****************************************************************************
functionname: FDKaacEnc_calcThreshExp
description:  loudness calculation (threshold to the power of redExp)
*****************************************************************************/
static void FDKaacEnc_calcThreshExp(
    FIXP_DBL thrExp[(2)][MAX_GROUPED_SFB],
    const QC_OUT_CHANNEL *const qcOutChannel[(2)],
    const PSY_OUT_CHANNEL *const psyOutChannel[(2)], const INT nChannels) {
  INT ch, sfb, sfbGrp;
  FIXP_DBL thrExpLdData;

  for (ch = 0; ch < nChannels; ch++) {
    for (sfbGrp = 0; sfbGrp < psyOutChannel[ch]->sfbCnt;
         sfbGrp += psyOutChannel[ch]->sfbPerGroup) {
      for (sfb = 0; sfb < psyOutChannel[ch]->maxSfbPerGroup; sfb++) {
        thrExpLdData = psyOutChannel[ch]->sfbThresholdLdData[sfbGrp + sfb] >> 2;
        thrExp[ch][sfbGrp + sfb] = CalcInvLdData(thrExpLdData);
      }
    }
  }
}

/*****************************************************************************
    functionname: FDKaacEnc_adaptMinSnr
    description:  reduce minSnr requirements for bands with relative low
energies
*****************************************************************************/
static void FDKaacEnc_adaptMinSnr(
    QC_OUT_CHANNEL *const qcOutChannel[(2)],
    const PSY_OUT_CHANNEL *const psyOutChannel[(2)],
    const MINSNR_ADAPT_PARAM *const msaParam, const INT nChannels) {
  INT ch, sfb, sfbGrp, nSfb;
  FIXP_DBL avgEnLD64, dbRatio, minSnrRed;
  FIXP_DBL minSnrLimitLD64 =
      FL2FXCONST_DBL(-0.00503012648262f); /* ld64(0.8f) */
  FIXP_DBL nSfbLD64;
  FIXP_DBL accu;

  FIXP_DBL msaParam_maxRed = msaParam->maxRed;
  FIXP_DBL msaParam_startRatio = msaParam->startRatio;
  FIXP_DBL msaParam_redRatioFac =
      fMult(msaParam->redRatioFac, FL2FXCONST_DBL(0.3010299956f));
  FIXP_DBL msaParam_redOffs = msaParam->redOffs;

  for (ch = 0; ch < nChannels; ch++) {
    /* calc average energy per scalefactor band */
    nSfb = 0;
    accu = FL2FXCONST_DBL(0.0f);

    DWORD_ALIGNED(psyOutChannel[ch]->sfbEnergy);

    for (sfbGrp = 0; sfbGrp < psyOutChannel[ch]->sfbCnt;
         sfbGrp += psyOutChannel[ch]->sfbPerGroup) {
      int maxSfbPerGroup = psyOutChannel[ch]->maxSfbPerGroup;
      nSfb += maxSfbPerGroup;
      for (sfb = 0; sfb < maxSfbPerGroup; sfb++) {
        accu += psyOutChannel[ch]->sfbEnergy[sfbGrp + sfb] >> 6;
      }
    }

    if ((accu == FL2FXCONST_DBL(0.0f)) || (nSfb == 0)) {
      avgEnLD64 = FL2FXCONST_DBL(-1.0f);
    } else {
      nSfbLD64 = CalcLdInt(nSfb);
      avgEnLD64 = CalcLdData(accu);
      avgEnLD64 = avgEnLD64 + FL2FXCONST_DBL(0.09375f) -
                  nSfbLD64; /* 0.09375f: compensate shift with 6 */
    }

    /* reduce minSnr requirement by minSnr^minSnrRed dependent on avgEn/sfbEn */
    int maxSfbPerGroup = psyOutChannel[ch]->maxSfbPerGroup;
    int sfbCnt = psyOutChannel[ch]->sfbCnt;
    int sfbPerGroup = psyOutChannel[ch]->sfbPerGroup;

    for (sfbGrp = 0; sfbGrp < sfbCnt; sfbGrp += sfbPerGroup) {
      FIXP_DBL *RESTRICT psfbEnergyLdData =
          &qcOutChannel[ch]->sfbEnergyLdData[sfbGrp];
      FIXP_DBL *RESTRICT psfbMinSnrLdData =
          &qcOutChannel[ch]->sfbMinSnrLdData[sfbGrp];
      for (sfb = 0; sfb < maxSfbPerGroup; sfb++) {
        FIXP_DBL sfbEnergyLdData = *psfbEnergyLdData++;
        FIXP_DBL sfbMinSnrLdData = *psfbMinSnrLdData;
        dbRatio = avgEnLD64 - sfbEnergyLdData;
        int update = (msaParam_startRatio < dbRatio) ? 1 : 0;
        minSnrRed = msaParam_redOffs + fMult(msaParam_redRatioFac,
                                             dbRatio); /* scaled by 1.0f/64.0f*/
        minSnrRed =
            fixMax(minSnrRed, msaParam_maxRed); /* scaled by 1.0f/64.0f*/
        minSnrRed = (fMult(sfbMinSnrLdData, minSnrRed)) << 6;
        minSnrRed = fixMin(minSnrLimitLD64, minSnrRed);
        *psfbMinSnrLdData++ = update ? minSnrRed : sfbMinSnrLdData;
      }
    }
  }
}

/*****************************************************************************
functionname: FDKaacEnc_initAvoidHoleFlag
description:  determine bands where avoid hole is not necessary resp. possible
*****************************************************************************/
static void FDKaacEnc_initAvoidHoleFlag(
    QC_OUT_CHANNEL *const qcOutChannel[(2)],
    const PSY_OUT_CHANNEL *const psyOutChannel[(2)],
    UCHAR ahFlag[(2)][MAX_GROUPED_SFB], const struct TOOLSINFO *const toolsInfo,
    const INT nChannels, const AH_PARAM *const ahParam) {
  INT ch, sfb, sfbGrp;
  FIXP_DBL sfbEn, sfbEnm1;
  FIXP_DBL sfbEnLdData;
  FIXP_DBL avgEnLdData;

  /* decrease spread energy by 3dB for long blocks, resp. 2dB for shorts
     (avoid more holes in long blocks) */
  for (ch = 0; ch < nChannels; ch++) {
    QC_OUT_CHANNEL *const qcOutChan = qcOutChannel[ch];

    if (psyOutChannel[ch]->lastWindowSequence != SHORT_WINDOW) {
      for (sfbGrp = 0; sfbGrp < psyOutChannel[ch]->sfbCnt;
           sfbGrp += psyOutChannel[ch]->sfbPerGroup)
        for (sfb = 0; sfb < psyOutChannel[ch]->maxSfbPerGroup; sfb++)
          qcOutChan->sfbSpreadEnergy[sfbGrp + sfb] >>= 1;
    } else {
      for (sfbGrp = 0; sfbGrp < psyOutChannel[ch]->sfbCnt;
           sfbGrp += psyOutChannel[ch]->sfbPerGroup)
        for (sfb = 0; sfb < psyOutChannel[ch]->maxSfbPerGroup; sfb++)
          qcOutChan->sfbSpreadEnergy[sfbGrp + sfb] = fMult(
              FL2FXCONST_DBL(0.63f), qcOutChan->sfbSpreadEnergy[sfbGrp + sfb]);
    }
  }

  /* increase minSnr for local peaks, decrease it for valleys */
  if (ahParam->modifyMinSnr) {
    for (ch = 0; ch < nChannels; ch++) {
      QC_OUT_CHANNEL *const qcOutChan = qcOutChannel[ch];
      for (sfbGrp = 0; sfbGrp < psyOutChannel[ch]->sfbCnt;
           sfbGrp += psyOutChannel[ch]->sfbPerGroup) {
        for (sfb = 0; sfb < psyOutChannel[ch]->maxSfbPerGroup; sfb++) {
          FIXP_DBL sfbEnp1, avgEn;
          if (sfb > 0)
            sfbEnm1 = qcOutChan->sfbEnergy[sfbGrp + sfb - 1];
          else
            sfbEnm1 = qcOutChan->sfbEnergy[sfbGrp + sfb];

          if (sfb < psyOutChannel[ch]->maxSfbPerGroup - 1)
            sfbEnp1 = qcOutChan->sfbEnergy[sfbGrp + sfb + 1];
          else
            sfbEnp1 = qcOutChan->sfbEnergy[sfbGrp + sfb];

          avgEn = (sfbEnm1 >> 1) + (sfbEnp1 >> 1);
          avgEnLdData = CalcLdData(avgEn);
          sfbEn = qcOutChan->sfbEnergy[sfbGrp + sfb];
          sfbEnLdData = qcOutChan->sfbEnergyLdData[sfbGrp + sfb];
          /* peak ? */
          if (sfbEn > avgEn) {
            FIXP_DBL tmpMinSnrLdData;
            if (psyOutChannel[ch]->lastWindowSequence == LONG_WINDOW)
              tmpMinSnrLdData = SnrLdFac + fixMax(avgEnLdData - sfbEnLdData,
                                                  SnrLdMin1 - SnrLdFac);
            else
              tmpMinSnrLdData = SnrLdFac + fixMax(avgEnLdData - sfbEnLdData,
                                                  SnrLdMin3 - SnrLdFac);

            qcOutChan->sfbMinSnrLdData[sfbGrp + sfb] = fixMin(
                qcOutChan->sfbMinSnrLdData[sfbGrp + sfb], tmpMinSnrLdData);
          }
          /* valley ? */
          if (((sfbEnLdData + (FIXP_DBL)SnrLdMin4) < (FIXP_DBL)avgEnLdData) &&
              (sfbEn > FL2FXCONST_DBL(0.0))) {
            FIXP_DBL tmpMinSnrLdData = avgEnLdData - sfbEnLdData -
                                       (FIXP_DBL)SnrLdMin4 +
                                       qcOutChan->sfbMinSnrLdData[sfbGrp + sfb];
            tmpMinSnrLdData = fixMin((FIXP_DBL)SnrLdFac, tmpMinSnrLdData);
            qcOutChan->sfbMinSnrLdData[sfbGrp + sfb] =
                fixMin(tmpMinSnrLdData,
                       (FIXP_DBL)(qcOutChan->sfbMinSnrLdData[sfbGrp + sfb] +
                                  SnrLdMin2));
          }
        }
      }
    }
  }

  /* stereo: adapt the minimum requirements sfbMinSnr of mid and
     side channels to avoid spending unnoticable bits */
  if (nChannels == 2) {
    QC_OUT_CHANNEL *qcOutChanM = qcOutChannel[0];
    QC_OUT_CHANNEL *qcOutChanS = qcOutChannel[1];
    const PSY_OUT_CHANNEL *const psyOutChanM = psyOutChannel[0];
    for (sfbGrp = 0; sfbGrp < psyOutChanM->sfbCnt;
         sfbGrp += psyOutChanM->sfbPerGroup) {
      for (sfb = 0; sfb < psyOutChanM->maxSfbPerGroup; sfb++) {
        if (toolsInfo->msMask[sfbGrp + sfb]) {
          FIXP_DBL maxSfbEnLd =
              fixMax(qcOutChanM->sfbEnergyLdData[sfbGrp + sfb],
                     qcOutChanS->sfbEnergyLdData[sfbGrp + sfb]);
          FIXP_DBL maxThrLd, sfbMinSnrTmpLd;

          if (((SnrLdMin5 >> 1) + (maxSfbEnLd >> 1) +
               (qcOutChanM->sfbMinSnrLdData[sfbGrp + sfb] >> 1)) <=
              FL2FXCONST_DBL(-0.5f))
            maxThrLd = FL2FXCONST_DBL(-1.0f);
          else
            maxThrLd = SnrLdMin5 + maxSfbEnLd +
                       qcOutChanM->sfbMinSnrLdData[sfbGrp + sfb];

          if (qcOutChanM->sfbEnergy[sfbGrp + sfb] > FL2FXCONST_DBL(0.0f))
            sfbMinSnrTmpLd =
                maxThrLd - qcOutChanM->sfbEnergyLdData[sfbGrp + sfb];
          else
            sfbMinSnrTmpLd = FL2FXCONST_DBL(0.0f);

          qcOutChanM->sfbMinSnrLdData[sfbGrp + sfb] =
              fixMax(qcOutChanM->sfbMinSnrLdData[sfbGrp + sfb], sfbMinSnrTmpLd);

          if (qcOutChanM->sfbMinSnrLdData[sfbGrp + sfb] <= FL2FXCONST_DBL(0.0f))
            qcOutChanM->sfbMinSnrLdData[sfbGrp + sfb] = fixMin(
                qcOutChanM->sfbMinSnrLdData[sfbGrp + sfb], (FIXP_DBL)SnrLdFac);

          if (qcOutChanS->sfbEnergy[sfbGrp + sfb] > FL2FXCONST_DBL(0.0f))
            sfbMinSnrTmpLd =
                maxThrLd - qcOutChanS->sfbEnergyLdData[sfbGrp + sfb];
          else
            sfbMinSnrTmpLd = FL2FXCONST_DBL(0.0f);

          qcOutChanS->sfbMinSnrLdData[sfbGrp + sfb] =
              fixMax(qcOutChanS->sfbMinSnrLdData[sfbGrp + sfb], sfbMinSnrTmpLd);

          if (qcOutChanS->sfbMinSnrLdData[sfbGrp + sfb] <= FL2FXCONST_DBL(0.0f))
            qcOutChanS->sfbMinSnrLdData[sfbGrp + sfb] = fixMin(
                qcOutChanS->sfbMinSnrLdData[sfbGrp + sfb], (FIXP_DBL)SnrLdFac);

          if (qcOutChanM->sfbEnergy[sfbGrp + sfb] >
              qcOutChanM->sfbSpreadEnergy[sfbGrp + sfb])
            qcOutChanS->sfbSpreadEnergy[sfbGrp + sfb] = fMult(
                qcOutChanS->sfbEnergy[sfbGrp + sfb], FL2FXCONST_DBL(0.9f));

          if (qcOutChanS->sfbEnergy[sfbGrp + sfb] >
              qcOutChanS->sfbSpreadEnergy[sfbGrp + sfb])
            qcOutChanM->sfbSpreadEnergy[sfbGrp + sfb] = fMult(
                qcOutChanM->sfbEnergy[sfbGrp + sfb], FL2FXCONST_DBL(0.9f));

        } /* if (toolsInfo->msMask[sfbGrp+sfb]) */
      }   /* sfb */
    }     /* sfbGrp */
  }       /* nChannels==2 */

  /* init ahFlag (0: no ah necessary, 1: ah possible, 2: ah active */
  for (ch = 0; ch < nChannels; ch++) {
    QC_OUT_CHANNEL *qcOutChan = qcOutChannel[ch];
    const PSY_OUT_CHANNEL *const psyOutChan = psyOutChannel[ch];
    for (sfbGrp = 0; sfbGrp < psyOutChan->sfbCnt;
         sfbGrp += psyOutChan->sfbPerGroup) {
      for (sfb = 0; sfb < psyOutChan->maxSfbPerGroup; sfb++) {
        if ((qcOutChan->sfbSpreadEnergy[sfbGrp + sfb] >
             qcOutChan->sfbEnergy[sfbGrp + sfb]) ||
            (qcOutChan->sfbMinSnrLdData[sfbGrp + sfb] > FL2FXCONST_DBL(0.0f))) {
          ahFlag[ch][sfbGrp + sfb] = NO_AH;
        } else {
          ahFlag[ch][sfbGrp + sfb] = AH_INACTIVE;
        }
      }
    }
  }
}

/**
 * \brief  Calculate constants that do not change during successive pe
 * calculations.
 *
 * \param peData                Pointer to structure containing PE data of
 * current element.
 * \param psyOutChannel         Pointer to PSY_OUT_CHANNEL struct holding
 * nChannels elements.
 * \param qcOutChannel          Pointer to QC_OUT_CHANNEL struct holding
 * nChannels elements.
 * \param nChannels             Number of channels in element.
 * \param peOffset              Fixed PE offset defined while
 * FDKaacEnc_AdjThrInit() depending on bitrate.
 *
 * \return  void
 */
static void FDKaacEnc_preparePe(PE_DATA *const peData,
                                const PSY_OUT_CHANNEL *const psyOutChannel[(2)],
                                const QC_OUT_CHANNEL *const qcOutChannel[(2)],
                                const INT nChannels, const INT peOffset) {
  INT ch;

  for (ch = 0; ch < nChannels; ch++) {
    const PSY_OUT_CHANNEL *const psyOutChan = psyOutChannel[ch];
    FDKaacEnc_prepareSfbPe(
        &peData->peChannelData[ch], psyOutChan->sfbEnergyLdData,
        psyOutChan->sfbThresholdLdData, qcOutChannel[ch]->sfbFormFactorLdData,
        psyOutChan->sfbOffsets, psyOutChan->sfbCnt, psyOutChan->sfbPerGroup,
        psyOutChan->maxSfbPerGroup);
  }
  peData->offset = peOffset;
}

/**
 * \brief  Calculate weighting factor for threshold adjustment.
 *
 * Calculate weighting factor to be applied at energies and thresholds in ld64
 * format.
 *
 * \param peData,               Pointer to PE data in current element.
 * \param psyOutChannel         Pointer to PSY_OUT_CHANNEL struct holding
 * nChannels elements.
 * \param qcOutChannel          Pointer to QC_OUT_CHANNEL struct holding
 * nChannels elements.
 * \param toolsInfo             Pointer to tools info struct of current element.
 * \param adjThrStateElement    Pointer to ATS_ELEMENT holding enFacPatch
 * states.
 * \param nChannels             Number of channels in element.
 * \param usePatchTool          Apply the weighting tool 0 (no) else (yes).
 *
 * \return  void
 */
static void FDKaacEnc_calcWeighting(
    const PE_DATA *const peData,
    const PSY_OUT_CHANNEL *const psyOutChannel[(2)],
    QC_OUT_CHANNEL *const qcOutChannel[(2)],
    const struct TOOLSINFO *const toolsInfo,
    ATS_ELEMENT *const adjThrStateElement, const INT nChannels,
    const INT usePatchTool) {
  int ch, noShortWindowInFrame = TRUE;
  INT exePatchM = 0;

  for (ch = 0; ch < nChannels; ch++) {
    if (psyOutChannel[ch]->lastWindowSequence == SHORT_WINDOW) {
      noShortWindowInFrame = FALSE;
    }
    FDKmemclear(qcOutChannel[ch]->sfbEnFacLd,
                MAX_GROUPED_SFB * sizeof(FIXP_DBL));
  }

  if (usePatchTool == 0) {
    return; /* tool is disabled */
  }

  for (ch = 0; ch < nChannels; ch++) {
    const PSY_OUT_CHANNEL *const psyOutChan = psyOutChannel[ch];

    if (noShortWindowInFrame) { /* retain energy ratio between blocks of
                                   different length */

      FIXP_DBL nrgSum14, nrgSum12, nrgSum34, nrgTotal;
      FIXP_DBL nrgFacLd_14, nrgFacLd_12, nrgFacLd_34;
      INT usePatch, exePatch;
      int sfb, sfbGrp, nLinesSum = 0;

      nrgSum14 = nrgSum12 = nrgSum34 = nrgTotal = FL2FXCONST_DBL(0.f);

      /* calculate flatness of audible spectrum, i.e. spectrum above masking
       * threshold. */
      for (sfbGrp = 0; sfbGrp < psyOutChannel[ch]->sfbCnt;
           sfbGrp += psyOutChannel[ch]->sfbPerGroup) {
        for (sfb = 0; sfb < psyOutChannel[ch]->maxSfbPerGroup; sfb++) {
          FIXP_DBL nrgFac12 = CalcInvLdData(
              psyOutChan->sfbEnergyLdData[sfbGrp + sfb] >> 1); /* nrg^(1/2) */
          FIXP_DBL nrgFac14 = CalcInvLdData(
              psyOutChan->sfbEnergyLdData[sfbGrp + sfb] >> 2); /* nrg^(1/4) */

          /* maximal number of bands is 64, results scaling factor 6 */
          nLinesSum += peData->peChannelData[ch]
                           .sfbNLines[sfbGrp + sfb]; /* relevant lines */
          nrgTotal +=
              (psyOutChan->sfbEnergy[sfbGrp + sfb] >> 6); /* sum up nrg */
          nrgSum12 += (nrgFac12 >> 6);                    /* sum up nrg^(2/4) */
          nrgSum14 += (nrgFac14 >> 6);                    /* sum up nrg^(1/4) */
          nrgSum34 += (fMult(nrgFac14, nrgFac12) >> 6);   /* sum up nrg^(3/4) */
        }
      }

      nrgTotal = CalcLdData(nrgTotal); /* get ld64 of total nrg */

      nrgFacLd_14 =
          CalcLdData(nrgSum14) - nrgTotal; /* ld64(nrgSum14/nrgTotal) */
      nrgFacLd_12 =
          CalcLdData(nrgSum12) - nrgTotal; /* ld64(nrgSum12/nrgTotal) */
      nrgFacLd_34 =
          CalcLdData(nrgSum34) - nrgTotal; /* ld64(nrgSum34/nrgTotal) */

      /* Note: nLinesSum cannot be larger than the number of total lines, thats
       * taken care of in line_pe.cpp FDKaacEnc_prepareSfbPe() */
      adjThrStateElement->chaosMeasureEnFac[ch] =
          fMax(FL2FXCONST_DBL(0.1875f),
               fDivNorm(nLinesSum, psyOutChan->sfbOffsets[psyOutChan->sfbCnt]));

      usePatch = (adjThrStateElement->chaosMeasureEnFac[ch] >
                  FL2FXCONST_DBL(0.78125f));
      exePatch = ((usePatch) && (adjThrStateElement->lastEnFacPatch[ch]));

      for (sfbGrp = 0; sfbGrp < psyOutChannel[ch]->sfbCnt;
           sfbGrp += psyOutChannel[ch]->sfbPerGroup) {
        for (sfb = 0; sfb < psyOutChannel[ch]->maxSfbPerGroup; sfb++) {
          INT sfbExePatch;
          /* for MS coupled SFBs, also execute patch in side channel if done in
           * mid channel */
          if ((ch == 1) && (toolsInfo->msMask[sfbGrp + sfb])) {
            sfbExePatch = exePatchM;
          } else {
            sfbExePatch = exePatch;
          }

          if ((sfbExePatch) &&
              (psyOutChan->sfbEnergy[sfbGrp + sfb] > FL2FXCONST_DBL(0.f))) {
            /* execute patch based on spectral flatness calculated above */
            if (adjThrStateElement->chaosMeasureEnFac[ch] >
                FL2FXCONST_DBL(0.8125f)) {
              qcOutChannel[ch]->sfbEnFacLd[sfbGrp + sfb] =
                  ((nrgFacLd_14 +
                    (psyOutChan->sfbEnergyLdData[sfbGrp + sfb] +
                     (psyOutChan->sfbEnergyLdData[sfbGrp + sfb] >> 1))) >>
                   1); /* sfbEnergy^(3/4) */
            } else if (adjThrStateElement->chaosMeasureEnFac[ch] >
                       FL2FXCONST_DBL(0.796875f)) {
              qcOutChannel[ch]->sfbEnFacLd[sfbGrp + sfb] =
                  ((nrgFacLd_12 + psyOutChan->sfbEnergyLdData[sfbGrp + sfb]) >>
                   1); /* sfbEnergy^(2/4) */
            } else {
              qcOutChannel[ch]->sfbEnFacLd[sfbGrp + sfb] =
                  ((nrgFacLd_34 +
                    (psyOutChan->sfbEnergyLdData[sfbGrp + sfb] >> 1)) >>
                   1); /* sfbEnergy^(1/4) */
            }
            qcOutChannel[ch]->sfbEnFacLd[sfbGrp + sfb] =
                fixMin(qcOutChannel[ch]->sfbEnFacLd[sfbGrp + sfb], (FIXP_DBL)0);
          }
        }
      } /* sfb loop */

      adjThrStateElement->lastEnFacPatch[ch] = usePatch;
      exePatchM = exePatch;
    } else {
      /* !noShortWindowInFrame */
      adjThrStateElement->chaosMeasureEnFac[ch] = FL2FXCONST_DBL(0.75f);
      adjThrStateElement->lastEnFacPatch[ch] =
          TRUE; /* allow use of sfbEnFac patch in upcoming frame */
    }

  } /* ch loop */
}

/*****************************************************************************
functionname: FDKaacEnc_calcPe
description:  calculate pe for both channels
*****************************************************************************/
static void FDKaacEnc_calcPe(const PSY_OUT_CHANNEL *const psyOutChannel[(2)],
                             const QC_OUT_CHANNEL *const qcOutChannel[(2)],
                             PE_DATA *const peData, const INT nChannels) {
  INT ch;

  peData->pe = peData->offset;
  peData->constPart = 0;
  peData->nActiveLines = 0;
  for (ch = 0; ch < nChannels; ch++) {
    PE_CHANNEL_DATA *peChanData = &peData->peChannelData[ch];

    FDKaacEnc_calcSfbPe(
        peChanData, qcOutChannel[ch]->sfbWeightedEnergyLdData,
        qcOutChannel[ch]->sfbThresholdLdData, psyOutChannel[ch]->sfbCnt,
        psyOutChannel[ch]->sfbPerGroup, psyOutChannel[ch]->maxSfbPerGroup,
        psyOutChannel[ch]->isBook, psyOutChannel[ch]->isScale);

    peData->pe += peChanData->pe;
    peData->constPart += peChanData->constPart;
    peData->nActiveLines += peChanData->nActiveLines;
  }
}

void FDKaacEnc_peCalculation(PE_DATA *const peData,
                             const PSY_OUT_CHANNEL *const psyOutChannel[(2)],
                             QC_OUT_CHANNEL *const qcOutChannel[(2)],
                             const struct TOOLSINFO *const toolsInfo,
                             ATS_ELEMENT *const adjThrStateElement,
                             const INT nChannels) {
  /* constants that will not change during successive pe calculations */
  FDKaacEnc_preparePe(peData, psyOutChannel, qcOutChannel, nChannels,
                      adjThrStateElement->peOffset);

  /* calculate weighting factor for threshold adjustment */
  FDKaacEnc_calcWeighting(peData, psyOutChannel, qcOutChannel, toolsInfo,
                          adjThrStateElement, nChannels, 1);
  {
    /* no weighting of threholds and energies for mlout */
    /* weight energies and thresholds */
    int ch;
    for (ch = 0; ch < nChannels; ch++) {
      int sfb, sfbGrp;
      QC_OUT_CHANNEL *pQcOutCh = qcOutChannel[ch];

      for (sfbGrp = 0; sfbGrp < psyOutChannel[ch]->sfbCnt;
           sfbGrp += psyOutChannel[ch]->sfbPerGroup) {
        for (sfb = 0; sfb < psyOutChannel[ch]->maxSfbPerGroup; sfb++) {
          pQcOutCh->sfbWeightedEnergyLdData[sfb + sfbGrp] =
              pQcOutCh->sfbEnergyLdData[sfb + sfbGrp] -
              pQcOutCh->sfbEnFacLd[sfb + sfbGrp];
          pQcOutCh->sfbThresholdLdData[sfb + sfbGrp] -=
              pQcOutCh->sfbEnFacLd[sfb + sfbGrp];
        }
      }
    }
  }

  /* pe without reduction */
  FDKaacEnc_calcPe(psyOutChannel, qcOutChannel, peData, nChannels);
}

/*****************************************************************************
functionname: FDKaacEnc_FDKaacEnc_calcPeNoAH
description:  sum the pe data only for bands where avoid hole is inactive
*****************************************************************************/
#define CONSTPART_HEADROOM 4
static void FDKaacEnc_FDKaacEnc_calcPeNoAH(
    INT *const pe, INT *const constPart, INT *const nActiveLines,
    const PE_DATA *const peData, const UCHAR ahFlag[(2)][MAX_GROUPED_SFB],
    const PSY_OUT_CHANNEL *const psyOutChannel[(2)], const INT nChannels) {
  INT ch, sfb, sfbGrp;

  INT pe_tmp = peData->offset;
  INT constPart_tmp = 0;
  INT nActiveLines_tmp = 0;
  for (ch = 0; ch < nChannels; ch++) {
    const PE_CHANNEL_DATA *const peChanData = &peData->peChannelData[ch];
    for (sfbGrp = 0; sfbGrp < psyOutChannel[ch]->sfbCnt;
         sfbGrp += psyOutChannel[ch]->sfbPerGroup) {
      for (sfb = 0; sfb < psyOutChannel[ch]->maxSfbPerGroup; sfb++) {
        if (ahFlag[ch][sfbGrp + sfb] < AH_ACTIVE) {
          pe_tmp += peChanData->sfbPe[sfbGrp + sfb];
          constPart_tmp +=
              peChanData->sfbConstPart[sfbGrp + sfb] >> CONSTPART_HEADROOM;
          nActiveLines_tmp += peChanData->sfbNActiveLines[sfbGrp + sfb];
        }
      }
    }
  }
  /* correct scaled pe and constPart values */
  *pe = pe_tmp >> PE_CONSTPART_SHIFT;
  *constPart = constPart_tmp >> (PE_CONSTPART_SHIFT - CONSTPART_HEADROOM);

  *nActiveLines = nActiveLines_tmp;
}

/*****************************************************************************
functionname: FDKaacEnc_reduceThresholdsCBR
description:  apply reduction formula
*****************************************************************************/
static const FIXP_DBL limitThrReducedLdData =
    (FIXP_DBL)0x00008000; /*FL2FXCONST_DBL(FDKpow(2.0,-LD_DATA_SCALING/4.0));*/

static void FDKaacEnc_reduceThresholdsCBR(
    QC_OUT_CHANNEL *const qcOutChannel[(2)],
    const PSY_OUT_CHANNEL *const psyOutChannel[(2)],
    UCHAR ahFlag[(2)][MAX_GROUPED_SFB],
    const FIXP_DBL thrExp[(2)][MAX_GROUPED_SFB], const INT nChannels,
    const FIXP_DBL redVal_m, const SCHAR redVal_e) {
  INT ch, sfb, sfbGrp;
  FIXP_DBL sfbEnLdData, sfbThrLdData, sfbThrReducedLdData;
  FIXP_DBL sfbThrExp;

  for (ch = 0; ch < nChannels; ch++) {
    QC_OUT_CHANNEL *qcOutChan = qcOutChannel[ch];
    for (sfbGrp = 0; sfbGrp < psyOutChannel[ch]->sfbCnt;
         sfbGrp += psyOutChannel[ch]->sfbPerGroup) {
      for (sfb = 0; sfb < psyOutChannel[ch]->maxSfbPerGroup; sfb++) {
        sfbEnLdData = qcOutChan->sfbWeightedEnergyLdData[sfbGrp + sfb];
        sfbThrLdData = qcOutChan->sfbThresholdLdData[sfbGrp + sfb];
        sfbThrExp = thrExp[ch][sfbGrp + sfb];
        if ((sfbEnLdData > sfbThrLdData) &&
            (ahFlag[ch][sfbGrp + sfb] != AH_ACTIVE)) {
          /* threshold reduction formula:
           float tmp = thrExp[ch][sfb]+redVal;
           tmp *= tmp;
           sfbThrReduced = tmp*tmp;
          */
          int minScale = fixMin(CountLeadingBits(sfbThrExp),
                                CountLeadingBits(redVal_m) - redVal_e) -
                         1;

          /* 4*log( sfbThrExp + redVal ) */
          sfbThrReducedLdData =
              CalcLdData(fAbs(scaleValue(sfbThrExp, minScale) +
                              scaleValue(redVal_m, redVal_e + minScale))) -
              (FIXP_DBL)(minScale << (DFRACT_BITS - 1 - LD_DATA_SHIFT));
          sfbThrReducedLdData <<= 2;

          /* avoid holes */
          if ((sfbThrReducedLdData >
               (qcOutChan->sfbMinSnrLdData[sfbGrp + sfb] + sfbEnLdData)) &&
              (ahFlag[ch][sfbGrp + sfb] != NO_AH)) {
            if (qcOutChan->sfbMinSnrLdData[sfbGrp + sfb] >
                (FL2FXCONST_DBL(-1.0f) - sfbEnLdData)) {
              sfbThrReducedLdData = fixMax(
                  (qcOutChan->sfbMinSnrLdData[sfbGrp + sfb] + sfbEnLdData),
                  sfbThrLdData);
            } else
              sfbThrReducedLdData = sfbThrLdData;
            ahFlag[ch][sfbGrp + sfb] = AH_ACTIVE;
          }

          /* minimum of 29 dB Ratio for Thresholds */
          if ((sfbEnLdData + (FIXP_DBL)MAXVAL_DBL) >
              FL2FXCONST_DBL(9.6336206 / LD_DATA_SCALING)) {
            sfbThrReducedLdData = fixMax(
                sfbThrReducedLdData,
                (sfbEnLdData - FL2FXCONST_DBL(9.6336206 / LD_DATA_SCALING)));
          }

          qcOutChan->sfbThresholdLdData[sfbGrp + sfb] = sfbThrReducedLdData;
        }
      }
    }
  }
}

/* similar to prepareSfbPe1() */
static FIXP_DBL FDKaacEnc_calcChaosMeasure(
    const PSY_OUT_CHANNEL *const psyOutChannel,
    const FIXP_DBL *const sfbFormFactorLdData) {
#define SCALE_FORM_FAC \
  (4) /* (SCALE_FORM_FAC+FORM_FAC_SHIFT) >= ld(FRAME_LENGTH)*/
#define SCALE_NRGS (8)
#define SCALE_NLINES (16)
#define SCALE_NRGS_SQRT4 (2)  /* 0.25 * SCALE_NRGS */
#define SCALE_NLINES_P34 (12) /* 0.75 * SCALE_NLINES */

  INT sfbGrp, sfb;
  FIXP_DBL chaosMeasure;
  INT frameNLines = 0;
  FIXP_DBL frameFormFactor = FL2FXCONST_DBL(0.f);
  FIXP_DBL frameEnergy = FL2FXCONST_DBL(0.f);

  for (sfbGrp = 0; sfbGrp < psyOutChannel->sfbCnt;
       sfbGrp += psyOutChannel->sfbPerGroup) {
    for (sfb = 0; sfb < psyOutChannel->maxSfbPerGroup; sfb++) {
      if (psyOutChannel->sfbEnergyLdData[sfbGrp + sfb] >
          psyOutChannel->sfbThresholdLdData[sfbGrp + sfb]) {
        frameFormFactor += (CalcInvLdData(sfbFormFactorLdData[sfbGrp + sfb]) >>
                            SCALE_FORM_FAC);
        frameNLines += (psyOutChannel->sfbOffsets[sfbGrp + sfb + 1] -
                        psyOutChannel->sfbOffsets[sfbGrp + sfb]);
        frameEnergy += (psyOutChannel->sfbEnergy[sfbGrp + sfb] >> SCALE_NRGS);
      }
    }
  }

  if (frameNLines > 0) {
    /*  frameNActiveLines = frameFormFactor*2^FORM_FAC_SHIFT * ((frameEnergy
       *2^SCALE_NRGS)/frameNLines)^-0.25 chaosMeasure      = frameNActiveLines /
       frameNLines */
    chaosMeasure = CalcInvLdData(
        (((CalcLdData(frameFormFactor) >> 1) -
          (CalcLdData(frameEnergy) >> (2 + 1))) -
         (fMultDiv2(FL2FXCONST_DBL(0.75f),
                    CalcLdData((FIXP_DBL)frameNLines
                               << (DFRACT_BITS - 1 - SCALE_NLINES))) -
          (((FIXP_DBL)(-((-SCALE_FORM_FAC + SCALE_NRGS_SQRT4 - FORM_FAC_SHIFT +
                          SCALE_NLINES_P34)
                         << (DFRACT_BITS - 1 - LD_DATA_SHIFT)))) >>
           1)))
        << 1);
  } else {
    /* assuming total chaos, if no sfb is above thresholds */
    chaosMeasure = FL2FXCONST_DBL(1.f);
  }

  return chaosMeasure;
}

/* apply reduction formula for VBR-mode */
static void FDKaacEnc_reduceThresholdsVBR(
    QC_OUT_CHANNEL *const qcOutChannel[(2)],
    const PSY_OUT_CHANNEL *const psyOutChannel[(2)],
    UCHAR ahFlag[(2)][MAX_GROUPED_SFB],
    const FIXP_DBL thrExp[(2)][MAX_GROUPED_SFB], const INT nChannels,
    const FIXP_DBL vbrQualFactor, FIXP_DBL *const chaosMeasureOld) {
  INT ch, sfbGrp, sfb;
  FIXP_DBL chGroupEnergy[TRANS_FAC][2]; /*energy for each group and channel*/
  FIXP_DBL chChaosMeasure[2];
  FIXP_DBL frameEnergy = FL2FXCONST_DBL(1e-10f);
  FIXP_DBL chaosMeasure = FL2FXCONST_DBL(0.f);
  FIXP_DBL sfbEnLdData, sfbThrLdData, sfbThrExp;
  FIXP_DBL sfbThrReducedLdData;
  FIXP_DBL chaosMeasureAvg;
  INT groupCnt;               /* loop counter */
  FIXP_DBL redVal[TRANS_FAC]; /* reduction values; in short-block case one
                                 redVal for each group */
  QC_OUT_CHANNEL *qcOutChan = NULL;
  const PSY_OUT_CHANNEL *psyOutChan = NULL;

#define SCALE_GROUP_ENERGY (8)

#define CONST_CHAOS_MEAS_AVG_FAC_0 (FL2FXCONST_DBL(0.25f))
#define CONST_CHAOS_MEAS_AVG_FAC_1 (FL2FXCONST_DBL(1.f - 0.25f))

#define MIN_LDTHRESH (FL2FXCONST_DBL(-0.515625f))

  for (ch = 0; ch < nChannels; ch++) {
    psyOutChan = psyOutChannel[ch];

    /* adding up energy for each channel and each group separately */
    FIXP_DBL chEnergy = FL2FXCONST_DBL(0.f);
    groupCnt = 0;

    for (sfbGrp = 0; sfbGrp < psyOutChan->sfbCnt;
         sfbGrp += psyOutChan->sfbPerGroup, groupCnt++) {
      chGroupEnergy[groupCnt][ch] = FL2FXCONST_DBL(0.f);
      for (sfb = 0; sfb < psyOutChan->maxSfbPerGroup; sfb++) {
        chGroupEnergy[groupCnt][ch] +=
            (psyOutChan->sfbEnergy[sfbGrp + sfb] >> SCALE_GROUP_ENERGY);
      }
      chEnergy += chGroupEnergy[groupCnt][ch];
    }
    frameEnergy += chEnergy;

    /* chaosMeasure */
    if (psyOutChannel[0]->lastWindowSequence == SHORT_WINDOW) {
      chChaosMeasure[ch] = FL2FXCONST_DBL(
          0.5f); /* assume a constant chaos measure of 0.5f for short blocks */
    } else {
      chChaosMeasure[ch] = FDKaacEnc_calcChaosMeasure(
          psyOutChannel[ch], qcOutChannel[ch]->sfbFormFactorLdData);
    }
    chaosMeasure += fMult(chChaosMeasure[ch], chEnergy);
  }

  if (frameEnergy > chaosMeasure) {
    INT scale = CntLeadingZeros(frameEnergy) - 1;
    FIXP_DBL num = chaosMeasure << scale;
    FIXP_DBL denum = frameEnergy << scale;
    chaosMeasure = schur_div(num, denum, 16);
  } else {
    chaosMeasure = FL2FXCONST_DBL(1.f);
  }

  chaosMeasureAvg = fMult(CONST_CHAOS_MEAS_AVG_FAC_0, chaosMeasure) +
                    fMult(CONST_CHAOS_MEAS_AVG_FAC_1,
                          *chaosMeasureOld); /* averaging chaos measure */
  *chaosMeasureOld = chaosMeasure = (fixMin(
      chaosMeasure, chaosMeasureAvg)); /* use min-value, safe for next frame */

  /* characteristic curve
     chaosMeasure = 0.2f + 0.7f/0.3f * (chaosMeasure - 0.2f);
     chaosMeasure = fixMin(1.0f, fixMax(0.1f, chaosMeasure));
     constants scaled by 4.f
  */
  chaosMeasure = ((FL2FXCONST_DBL(0.2f) >> 2) +
                  fMult(FL2FXCONST_DBL(0.7f / (4.f * 0.3f)),
                        (chaosMeasure - FL2FXCONST_DBL(0.2f))));
  chaosMeasure =
      (fixMin((FIXP_DBL)(FL2FXCONST_DBL(1.0f) >> 2),
              fixMax((FIXP_DBL)(FL2FXCONST_DBL(0.1f) >> 2), chaosMeasure)))
      << 2;

  /* calculation of reduction value */
  if (psyOutChannel[0]->lastWindowSequence == SHORT_WINDOW) { /* short-blocks */
    FDK_ASSERT(TRANS_FAC == 8);
#define WIN_TYPE_SCALE (3)

    groupCnt = 0;
    for (sfbGrp = 0; sfbGrp < psyOutChannel[0]->sfbCnt;
         sfbGrp += psyOutChannel[0]->sfbPerGroup, groupCnt++) {
      FIXP_DBL groupEnergy = FL2FXCONST_DBL(0.f);

      for (ch = 0; ch < nChannels; ch++) {
        groupEnergy +=
            chGroupEnergy[groupCnt]
                         [ch]; /* adding up the channels groupEnergy */
      }

      FDK_ASSERT(psyOutChannel[0]->groupLen[groupCnt] <= INV_INT_TAB_SIZE);
      groupEnergy = fMult(
          groupEnergy,
          invInt[psyOutChannel[0]->groupLen[groupCnt]]); /* correction of
                                                            group energy */
      groupEnergy = fixMin(groupEnergy,
                           frameEnergy >> WIN_TYPE_SCALE); /* do not allow an
                                                              higher redVal as
                                                              calculated
                                                              framewise */

      groupEnergy >>=
          2; /* 2*WIN_TYPE_SCALE = 6 => 6+2 = 8 ==> 8/4 = int number */

      redVal[groupCnt] =
          fMult(fMult(vbrQualFactor, chaosMeasure),
                CalcInvLdData(CalcLdData(groupEnergy) >> 2))
          << (int)((2 + (2 * WIN_TYPE_SCALE) + SCALE_GROUP_ENERGY) >> 2);
    }
  } else { /* long-block */

    redVal[0] = fMult(fMult(vbrQualFactor, chaosMeasure),
                      CalcInvLdData(CalcLdData(frameEnergy) >> 2))
                << (int)(SCALE_GROUP_ENERGY >> 2);
  }

  for (ch = 0; ch < nChannels; ch++) {
    qcOutChan = qcOutChannel[ch];
    psyOutChan = psyOutChannel[ch];

    for (sfbGrp = 0; sfbGrp < psyOutChan->sfbCnt;
         sfbGrp += psyOutChan->sfbPerGroup) {
      for (sfb = 0; sfb < psyOutChan->maxSfbPerGroup; sfb++) {
        sfbEnLdData = (qcOutChan->sfbWeightedEnergyLdData[sfbGrp + sfb]);
        sfbThrLdData = (qcOutChan->sfbThresholdLdData[sfbGrp + sfb]);
        sfbThrExp = thrExp[ch][sfbGrp + sfb];

        if ((sfbThrLdData >= MIN_LDTHRESH) && (sfbEnLdData > sfbThrLdData) &&
            (ahFlag[ch][sfbGrp + sfb] != AH_ACTIVE)) {
          /* Short-Window */
          if (psyOutChannel[ch]->lastWindowSequence == SHORT_WINDOW) {
            const int groupNumber = (int)sfb / psyOutChan->sfbPerGroup;

            FDK_ASSERT(INV_SQRT4_TAB_SIZE > psyOutChan->groupLen[groupNumber]);

            sfbThrExp =
                fMult(sfbThrExp,
                      fMult(FL2FXCONST_DBL(2.82f / 4.f),
                            invSqrt4[psyOutChan->groupLen[groupNumber]]))
                << 2;

            if (sfbThrExp <= (limitThrReducedLdData - redVal[groupNumber])) {
              sfbThrReducedLdData = FL2FXCONST_DBL(-1.0f);
            } else {
              if ((FIXP_DBL)redVal[groupNumber] >=
                  FL2FXCONST_DBL(1.0f) - sfbThrExp)
                sfbThrReducedLdData = FL2FXCONST_DBL(0.0f);
              else {
                /* threshold reduction formula */
                sfbThrReducedLdData =
                    CalcLdData(sfbThrExp + redVal[groupNumber]);
                sfbThrReducedLdData <<= 2;
              }
            }
            sfbThrReducedLdData +=
                (CalcLdInt(psyOutChan->groupLen[groupNumber]) -
                 ((FIXP_DBL)6 << (DFRACT_BITS - 1 - LD_DATA_SHIFT)));
          }

          /* Long-Window */
          else {
            if ((FIXP_DBL)redVal[0] >= FL2FXCONST_DBL(1.0f) - sfbThrExp) {
              sfbThrReducedLdData = FL2FXCONST_DBL(0.0f);
            } else {
              /* threshold reduction formula */
              sfbThrReducedLdData = CalcLdData(sfbThrExp + redVal[0]);
              sfbThrReducedLdData <<= 2;
            }
          }

          /* avoid holes */
          if (((sfbThrReducedLdData - sfbEnLdData) >
               qcOutChan->sfbMinSnrLdData[sfbGrp + sfb]) &&
              (ahFlag[ch][sfbGrp + sfb] != NO_AH)) {
            if (qcOutChan->sfbMinSnrLdData[sfbGrp + sfb] >
                (FL2FXCONST_DBL(-1.0f) - sfbEnLdData)) {
              sfbThrReducedLdData = fixMax(
                  (qcOutChan->sfbMinSnrLdData[sfbGrp + sfb] + sfbEnLdData),
                  sfbThrLdData);
            } else
              sfbThrReducedLdData = sfbThrLdData;
            ahFlag[ch][sfbGrp + sfb] = AH_ACTIVE;
          }

          if (sfbThrReducedLdData < FL2FXCONST_DBL(-0.5f))
            sfbThrReducedLdData = FL2FXCONST_DBL(-1.f);

          sfbThrReducedLdData = fixMax(MIN_LDTHRESH, sfbThrReducedLdData);

          qcOutChan->sfbThresholdLdData[sfbGrp + sfb] = sfbThrReducedLdData;
        }
      }
    }
  }
}

/*****************************************************************************
functionname: FDKaacEnc_correctThresh
description:  if pe difference deltaPe between desired pe and real pe is small
enough, the difference can be distributed among the scale factor bands. New
thresholds can be derived from this pe-difference
*****************************************************************************/
static void FDKaacEnc_correctThresh(
    const CHANNEL_MAPPING *const cm, QC_OUT_ELEMENT *const qcElement[((8))],
    const PSY_OUT_ELEMENT *const psyOutElement[((8))],
    UCHAR ahFlag[((8))][(2)][MAX_GROUPED_SFB],
    const FIXP_DBL thrExp[((8))][(2)][MAX_GROUPED_SFB], const FIXP_DBL redVal_m,
    const SCHAR redVal_e, const INT deltaPe, const INT processElements,
    const INT elementOffset) {
  INT ch, sfb, sfbGrp;
  QC_OUT_CHANNEL *qcOutChan;
  PSY_OUT_CHANNEL *psyOutChan;
  PE_CHANNEL_DATA *peChanData;
  FIXP_DBL thrFactorLdData;
  FIXP_DBL sfbEnLdData, sfbThrLdData, sfbThrReducedLdData;
  FIXP_DBL *sfbPeFactorsLdData[((8))][(2)];
  FIXP_DBL(*sfbNActiveLinesLdData)[(2)][MAX_GROUPED_SFB];

  INT normFactorInt;
  FIXP_DBL normFactorLdData;

  INT nElements = elementOffset + processElements;
  INT elementId;

  /* scratch is empty; use temporal memory from quantSpec in QC_OUT_CHANNEL */
  for (elementId = elementOffset; elementId < nElements; elementId++) {
    for (ch = 0; ch < cm->elInfo[elementId].nChannelsInEl; ch++) {
      /* The reinterpret_cast is used to suppress a compiler warning. We know
       * that qcElement[elementId]->qcOutChannel[ch]->quantSpec is sufficiently
       * aligned, so the cast is safe */
      sfbPeFactorsLdData[elementId][ch] =
          reinterpret_cast<FIXP_DBL *>(reinterpret_cast<void *>(
              qcElement[elementId]->qcOutChannel[ch]->quantSpec));
    }
  }
  /* The reinterpret_cast is used to suppress a compiler warning. We know that
   * qcElement[0]->dynMem_SfbNActiveLinesLdData is sufficiently aligned, so the
   * cast is safe */
  sfbNActiveLinesLdData = reinterpret_cast<FIXP_DBL(*)[(2)][MAX_GROUPED_SFB]>(
      reinterpret_cast<void *>(qcElement[0]->dynMem_SfbNActiveLinesLdData));

  /* for each sfb calc relative factors for pe changes */
  normFactorInt = 0;

  for (elementId = elementOffset; elementId < nElements; elementId++) {
    if (cm->elInfo[elementId].elType != ID_DSE) {
      for (ch = 0; ch < cm->elInfo[elementId].nChannelsInEl; ch++) {
        psyOutChan = psyOutElement[elementId]->psyOutChannel[ch];
        peChanData = &qcElement[elementId]->peData.peChannelData[ch];

        for (sfbGrp = 0; sfbGrp < psyOutChan->sfbCnt;
             sfbGrp += psyOutChan->sfbPerGroup) {
          for (sfb = 0; sfb < psyOutChan->maxSfbPerGroup; sfb++) {
            if (peChanData->sfbNActiveLines[sfbGrp + sfb] == 0) {
              sfbNActiveLinesLdData[elementId][ch][sfbGrp + sfb] =
                  FL2FXCONST_DBL(-1.0f);
            } else {
              /* Both CalcLdInt and CalcLdData can be used!
               * No offset has to be subtracted, because sfbNActiveLinesLdData
               * is shorted while thrFactor calculation */
              sfbNActiveLinesLdData[elementId][ch][sfbGrp + sfb] =
                  CalcLdInt(peChanData->sfbNActiveLines[sfbGrp + sfb]);
            }
            if (((ahFlag[elementId][ch][sfbGrp + sfb] < AH_ACTIVE) ||
                 (deltaPe > 0)) &&
                peChanData->sfbNActiveLines[sfbGrp + sfb] != 0) {
              if (thrExp[elementId][ch][sfbGrp + sfb] > -redVal_m) {
                /* sfbPeFactors[ch][sfbGrp+sfb] =
                   peChanData->sfbNActiveLines[sfbGrp+sfb] /
                                  (thrExp[elementId][ch][sfbGrp+sfb] +
                   redVal[elementId]); */

                int minScale =
                    fixMin(
                        CountLeadingBits(thrExp[elementId][ch][sfbGrp + sfb]),
                        CountLeadingBits(redVal_m) - redVal_e) -
                    1;

                /* sumld = ld64( sfbThrExp + redVal ) */
                FIXP_DBL sumLd =
                    CalcLdData(scaleValue(thrExp[elementId][ch][sfbGrp + sfb],
                                          minScale) +
                               scaleValue(redVal_m, redVal_e + minScale)) -
                    (FIXP_DBL)(minScale << (DFRACT_BITS - 1 - LD_DATA_SHIFT));

                if (sumLd < FL2FXCONST_DBL(0.f)) {
                  sfbPeFactorsLdData[elementId][ch][sfbGrp + sfb] =
                      sfbNActiveLinesLdData[elementId][ch][sfbGrp + sfb] -
                      sumLd;
                } else {
                  if (sfbNActiveLinesLdData[elementId][ch][sfbGrp + sfb] >
                      (FL2FXCONST_DBL(-1.f) + sumLd)) {
                    sfbPeFactorsLdData[elementId][ch][sfbGrp + sfb] =
                        sfbNActiveLinesLdData[elementId][ch][sfbGrp + sfb] -
                        sumLd;
                  } else {
                    sfbPeFactorsLdData[elementId][ch][sfbGrp + sfb] =
                        sfbNActiveLinesLdData[elementId][ch][sfbGrp + sfb];
                  }
                }

                normFactorInt += (INT)CalcInvLdData(
                    sfbPeFactorsLdData[elementId][ch][sfbGrp + sfb]);
              } else
                sfbPeFactorsLdData[elementId][ch][sfbGrp + sfb] =
                    FL2FXCONST_DBL(1.0f);
            } else
              sfbPeFactorsLdData[elementId][ch][sfbGrp + sfb] =
                  FL2FXCONST_DBL(-1.0f);
          }
        }
      }
    }
  }

  /* normFactorLdData = ld64(deltaPe/normFactorInt) */
  normFactorLdData =
      CalcLdData((FIXP_DBL)((deltaPe < 0) ? (-deltaPe) : (deltaPe))) -
      CalcLdData((FIXP_DBL)normFactorInt);

  /* distribute the pe difference to the scalefactors
     and calculate the according thresholds */
  for (elementId = elementOffset; elementId < nElements; elementId++) {
    if (cm->elInfo[elementId].elType != ID_DSE) {
      for (ch = 0; ch < cm->elInfo[elementId].nChannelsInEl; ch++) {
        qcOutChan = qcElement[elementId]->qcOutChannel[ch];
        psyOutChan = psyOutElement[elementId]->psyOutChannel[ch];
        peChanData = &qcElement[elementId]->peData.peChannelData[ch];

        for (sfbGrp = 0; sfbGrp < psyOutChan->sfbCnt;
             sfbGrp += psyOutChan->sfbPerGroup) {
          for (sfb = 0; sfb < psyOutChan->maxSfbPerGroup; sfb++) {
            if (peChanData->sfbNActiveLines[sfbGrp + sfb] > 0) {
              /* pe difference for this sfb */
              if ((sfbPeFactorsLdData[elementId][ch][sfbGrp + sfb] ==
                   FL2FXCONST_DBL(-1.0f)) ||
                  (deltaPe == 0)) {
                thrFactorLdData = FL2FXCONST_DBL(0.f);
              } else {
                /* new threshold */
                FIXP_DBL tmp = CalcInvLdData(
                    sfbPeFactorsLdData[elementId][ch][sfbGrp + sfb] +
                    normFactorLdData -
                    sfbNActiveLinesLdData[elementId][ch][sfbGrp + sfb] -
                    FL2FXCONST_DBL((float)LD_DATA_SHIFT / LD_DATA_SCALING));

                /* limit thrFactor to 60dB */
                tmp = (deltaPe < 0) ? tmp : (-tmp);
                thrFactorLdData =
                    fMin(tmp, FL2FXCONST_DBL(20.f / LD_DATA_SCALING));
              }

              /* new threshold */
              sfbThrLdData = qcOutChan->sfbThresholdLdData[sfbGrp + sfb];
              sfbEnLdData = qcOutChan->sfbWeightedEnergyLdData[sfbGrp + sfb];

              if (thrFactorLdData < FL2FXCONST_DBL(0.f)) {
                if (sfbThrLdData > (FL2FXCONST_DBL(-1.f) - thrFactorLdData)) {
                  sfbThrReducedLdData = sfbThrLdData + thrFactorLdData;
                } else {
                  sfbThrReducedLdData = FL2FXCONST_DBL(-1.f);
                }
              } else {
                sfbThrReducedLdData = sfbThrLdData + thrFactorLdData;
              }

              /* avoid hole */
              if ((sfbThrReducedLdData - sfbEnLdData >
                   qcOutChan->sfbMinSnrLdData[sfbGrp + sfb]) &&
                  (ahFlag[elementId][ch][sfbGrp + sfb] == AH_INACTIVE)) {
                /* sfbThrReduced = max(psyOutChan[ch]->sfbMinSnr[i] * sfbEn,
                 * sfbThr); */
                if (sfbEnLdData >
                    (sfbThrLdData - qcOutChan->sfbMinSnrLdData[sfbGrp + sfb])) {
                  sfbThrReducedLdData =
                      qcOutChan->sfbMinSnrLdData[sfbGrp + sfb] + sfbEnLdData;
                } else {
                  sfbThrReducedLdData = sfbThrLdData;
                }
                ahFlag[elementId][ch][sfbGrp + sfb] = AH_ACTIVE;
              }

              qcOutChan->sfbThresholdLdData[sfbGrp + sfb] = sfbThrReducedLdData;
            }
          }
        }
      }
    }
  }
}

/*****************************************************************************
    functionname: FDKaacEnc_reduceMinSnr
    description:  if the desired pe can not be reached, reduce pe by
                  reducing minSnr
*****************************************************************************/
static void FDKaacEnc_reduceMinSnr(
    const CHANNEL_MAPPING *const cm, QC_OUT_ELEMENT *const qcElement[((8))],
    const PSY_OUT_ELEMENT *const psyOutElement[((8))],
    const UCHAR ahFlag[((8))][(2)][MAX_GROUPED_SFB], const INT desiredPe,
    INT *const redPeGlobal, const INT processElements, const INT elementOffset)

{
  INT ch, elementId, globalMaxSfb = 0;
  const INT nElements = elementOffset + processElements;
  INT newGlobalPe = *redPeGlobal;

  if (newGlobalPe <= desiredPe) {
    goto bail;
  }

  /* global maximum of maxSfbPerGroup */
  for (elementId = elementOffset; elementId < nElements; elementId++) {
    if (cm->elInfo[elementId].elType != ID_DSE) {
      for (ch = 0; ch < cm->elInfo[elementId].nChannelsInEl; ch++) {
        globalMaxSfb =
            fMax(globalMaxSfb,
                 psyOutElement[elementId]->psyOutChannel[ch]->maxSfbPerGroup);
      }
    }
  }

  /* as long as globalPE is above desirePE reduce SNR to 1.0 dB, starting at
   * highest SFB */
  while ((newGlobalPe > desiredPe) && (--globalMaxSfb >= 0)) {
    for (elementId = elementOffset; elementId < nElements; elementId++) {
      if (cm->elInfo[elementId].elType != ID_DSE) {
        PE_DATA *peData = &qcElement[elementId]->peData;

        for (ch = 0; ch < cm->elInfo[elementId].nChannelsInEl; ch++) {
          QC_OUT_CHANNEL *qcOutChan = qcElement[elementId]->qcOutChannel[ch];
          PSY_OUT_CHANNEL *psyOutChan =
              psyOutElement[elementId]->psyOutChannel[ch];

          /* try to reduce SNR of channel's uppermost SFB(s) */
          if (globalMaxSfb < psyOutChan->maxSfbPerGroup) {
            INT sfb, deltaPe = 0;

            for (sfb = globalMaxSfb; sfb < psyOutChan->sfbCnt;
                 sfb += psyOutChan->sfbPerGroup) {
              if (ahFlag[elementId][ch][sfb] != NO_AH &&
                  qcOutChan->sfbMinSnrLdData[sfb] < SnrLdFac &&
                  (qcOutChan->sfbWeightedEnergyLdData[sfb] >
                   qcOutChan->sfbThresholdLdData[sfb] - SnrLdFac)) {
                /* increase threshold to new minSnr of 1dB */
                qcOutChan->sfbMinSnrLdData[sfb] = SnrLdFac;
                qcOutChan->sfbThresholdLdData[sfb] =
                    qcOutChan->sfbWeightedEnergyLdData[sfb] + SnrLdFac;

                /* calc new pe */
                /* C2 + C3*ld(1/0.8) = 1.5 */
                deltaPe -= peData->peChannelData[ch].sfbPe[sfb];

                /* sfbPe = 1.5 * sfbNLines */
                peData->peChannelData[ch].sfbPe[sfb] =
                    (3 * peData->peChannelData[ch].sfbNLines[sfb])
                    << (PE_CONSTPART_SHIFT - 1);
                deltaPe += peData->peChannelData[ch].sfbPe[sfb];
              }

            } /* sfb loop */

            deltaPe >>= PE_CONSTPART_SHIFT;
            peData->pe += deltaPe;
            peData->peChannelData[ch].pe += deltaPe;
            newGlobalPe += deltaPe;

          } /* if globalMaxSfb < maxSfbPerGroup */

          /* stop if enough has been saved */
          if (newGlobalPe <= desiredPe) {
            goto bail;
          }

        } /* ch loop */
      }   /* != ID_DSE */
    }     /* elementId loop */
  }       /* while ( newGlobalPe > desiredPe) && (--globalMaxSfb >= 0) ) */

bail:
  /* update global PE */
  *redPeGlobal = newGlobalPe;
}

/*****************************************************************************
    functionname: FDKaacEnc_allowMoreHoles
    description:  if the desired pe can not be reached, some more scalefactor
                  bands have to be quantized to zero
*****************************************************************************/
static void FDKaacEnc_allowMoreHoles(
    const CHANNEL_MAPPING *const cm, QC_OUT_ELEMENT *const qcElement[((8))],
    const PSY_OUT_ELEMENT *const psyOutElement[((8))],
    const ATS_ELEMENT *const AdjThrStateElement[((8))],
    UCHAR ahFlag[((8))][(2)][MAX_GROUPED_SFB], const INT desiredPe,
    const INT currentPe, const int processElements, const int elementOffset) {
  INT elementId;
  INT nElements = elementOffset + processElements;
  INT actPe = currentPe;

  if (actPe <= desiredPe) {
    return; /* nothing to do */
  }

  for (elementId = elementOffset; elementId < nElements; elementId++) {
    if (cm->elInfo[elementId].elType != ID_DSE) {
      INT ch, sfb, sfbGrp;

      PE_DATA *peData = &qcElement[elementId]->peData;
      const INT nChannels = cm->elInfo[elementId].nChannelsInEl;

      QC_OUT_CHANNEL *qcOutChannel[(2)] = {NULL};
      PSY_OUT_CHANNEL *psyOutChannel[(2)] = {NULL};

      for (ch = 0; ch < nChannels; ch++) {
        /* init pointers */
        qcOutChannel[ch] = qcElement[elementId]->qcOutChannel[ch];
        psyOutChannel[ch] = psyOutElement[elementId]->psyOutChannel[ch];

        for (sfbGrp = 0; sfbGrp < psyOutChannel[ch]->sfbCnt;
             sfbGrp += psyOutChannel[ch]->sfbPerGroup) {
          for (sfb = psyOutChannel[ch]->maxSfbPerGroup;
               sfb < psyOutChannel[ch]->sfbPerGroup; sfb++) {
            peData->peChannelData[ch].sfbPe[sfbGrp + sfb] = 0;
          }
        }
      }

      /* for MS allow hole in the channel with less energy */
      if (nChannels == 2 && psyOutChannel[0]->lastWindowSequence ==
                                psyOutChannel[1]->lastWindowSequence) {
        for (sfb = psyOutChannel[0]->maxSfbPerGroup - 1; sfb >= 0; sfb--) {
          for (sfbGrp = 0; sfbGrp < psyOutChannel[0]->sfbCnt;
               sfbGrp += psyOutChannel[0]->sfbPerGroup) {
            if (psyOutElement[elementId]->toolsInfo.msMask[sfbGrp + sfb]) {
              FIXP_DBL EnergyLd_L =
                  qcOutChannel[0]->sfbWeightedEnergyLdData[sfbGrp + sfb];
              FIXP_DBL EnergyLd_R =
                  qcOutChannel[1]->sfbWeightedEnergyLdData[sfbGrp + sfb];

              /* allow hole in side channel ? */
              if ((ahFlag[elementId][1][sfbGrp + sfb] != NO_AH) &&
                  (((FL2FXCONST_DBL(-0.02065512648f) >> 1) +
                    (qcOutChannel[0]->sfbMinSnrLdData[sfbGrp + sfb] >> 1)) >
                   ((EnergyLd_R >> 1) - (EnergyLd_L >> 1)))) {
                ahFlag[elementId][1][sfbGrp + sfb] = NO_AH;
                qcOutChannel[1]->sfbThresholdLdData[sfbGrp + sfb] =
                    FL2FXCONST_DBL(0.015625f) + EnergyLd_R;
                actPe -= peData->peChannelData[1].sfbPe[sfbGrp + sfb] >>
                         PE_CONSTPART_SHIFT;
              }
              /* allow hole in mid channel ? */
              else if ((ahFlag[elementId][0][sfbGrp + sfb] != NO_AH) &&
                       (((FL2FXCONST_DBL(-0.02065512648f) >> 1) +
                         (qcOutChannel[1]->sfbMinSnrLdData[sfbGrp + sfb] >>
                          1)) > ((EnergyLd_L >> 1) - (EnergyLd_R >> 1)))) {
                ahFlag[elementId][0][sfbGrp + sfb] = NO_AH;
                qcOutChannel[0]->sfbThresholdLdData[sfbGrp + sfb] =
                    FL2FXCONST_DBL(0.015625f) + EnergyLd_L;
                actPe -= peData->peChannelData[0].sfbPe[sfbGrp + sfb] >>
                         PE_CONSTPART_SHIFT;
              } /* if (ahFlag) */
            }   /* if MS */
          }     /* sfbGrp */
          if (actPe <= desiredPe) {
            return; /* stop if enough has been saved */
          }
        } /* sfb */
      }   /* MS possible ? */

    } /* EOF DSE-suppression */
  }   /* EOF for all elements... */

  if (actPe > desiredPe) {
    /* more holes necessary? subsequently erase bands starting with low energies
     */
    INT ch, sfb, sfbGrp;
    INT minSfb, maxSfb;
    INT enIdx, ahCnt, done;
    INT startSfb[(8)];
    INT sfbCnt[(8)];
    INT sfbPerGroup[(8)];
    INT maxSfbPerGroup[(8)];
    FIXP_DBL avgEn;
    FIXP_DBL minEnLD64;
    FIXP_DBL avgEnLD64;
    FIXP_DBL enLD64[NUM_NRG_LEVS];
    INT avgEn_e;

    /* get the scaling factor over all audio elements and channels */
    maxSfb = 0;
    for (elementId = elementOffset; elementId < nElements; elementId++) {
      if (cm->elInfo[elementId].elType != ID_DSE) {
        for (ch = 0; ch < cm->elInfo[elementId].nChannelsInEl; ch++) {
          for (sfbGrp = 0;
               sfbGrp < psyOutElement[elementId]->psyOutChannel[ch]->sfbCnt;
               sfbGrp +=
               psyOutElement[elementId]->psyOutChannel[ch]->sfbPerGroup) {
            maxSfb +=
                psyOutElement[elementId]->psyOutChannel[ch]->maxSfbPerGroup;
          }
        }
      }
    }
    avgEn_e =
        (DFRACT_BITS - fixnormz_D((LONG)fMax(0, maxSfb - 1))); /* ilog2() */

    ahCnt = 0;
    maxSfb = 0;
    minSfb = MAX_SFB;
    avgEn = FL2FXCONST_DBL(0.0f);
    minEnLD64 = FL2FXCONST_DBL(0.0f);

    for (elementId = elementOffset; elementId < nElements; elementId++) {
      if (cm->elInfo[elementId].elType != ID_DSE) {
        for (ch = 0; ch < cm->elInfo[elementId].nChannelsInEl; ch++) {
          const INT chIdx = cm->elInfo[elementId].ChannelIndex[ch];
          QC_OUT_CHANNEL *qcOutChannel = qcElement[elementId]->qcOutChannel[ch];
          PSY_OUT_CHANNEL *psyOutChannel =
              psyOutElement[elementId]->psyOutChannel[ch];

          maxSfbPerGroup[chIdx] = psyOutChannel->maxSfbPerGroup;
          sfbCnt[chIdx] = psyOutChannel->sfbCnt;
          sfbPerGroup[chIdx] = psyOutChannel->sfbPerGroup;

          maxSfb = fMax(maxSfb, psyOutChannel->maxSfbPerGroup);

          if (psyOutChannel->lastWindowSequence != SHORT_WINDOW) {
            startSfb[chIdx] = AdjThrStateElement[elementId]->ahParam.startSfbL;
          } else {
            startSfb[chIdx] = AdjThrStateElement[elementId]->ahParam.startSfbS;
          }

          minSfb = fMin(minSfb, startSfb[chIdx]);

          sfbGrp = 0;
          sfb = startSfb[chIdx];

          do {
            for (; sfb < psyOutChannel->maxSfbPerGroup; sfb++) {
              if ((ahFlag[elementId][ch][sfbGrp + sfb] != NO_AH) &&
                  (qcOutChannel->sfbWeightedEnergyLdData[sfbGrp + sfb] >
                   qcOutChannel->sfbThresholdLdData[sfbGrp + sfb])) {
                minEnLD64 = fixMin(minEnLD64,
                                   qcOutChannel->sfbEnergyLdData[sfbGrp + sfb]);
                avgEn += qcOutChannel->sfbEnergy[sfbGrp + sfb] >> avgEn_e;
                ahCnt++;
              }
            }

            sfbGrp += psyOutChannel->sfbPerGroup;
            sfb = startSfb[chIdx];

          } while (sfbGrp < psyOutChannel->sfbCnt);
        }
      } /* (cm->elInfo[elementId].elType != ID_DSE) */
    }   /* (elementId = elementOffset;elementId<nElements;elementId++) */

    if ((avgEn == FL2FXCONST_DBL(0.0f)) || (ahCnt == 0)) {
      avgEnLD64 = FL2FXCONST_DBL(0.0f);
    } else {
      avgEnLD64 = CalcLdData(avgEn) +
                  (FIXP_DBL)(avgEn_e << (DFRACT_BITS - 1 - LD_DATA_SHIFT)) -
                  CalcLdInt(ahCnt);
    }

    /* calc some energy borders between minEn and avgEn */

    /* for (enIdx = 0; enIdx < NUM_NRG_LEVS; enIdx++) {
         en[enIdx] = (2.0f*enIdx+1.0f)/(2.0f*NUM_NRG_LEVS-1.0f);
       } */
    enLD64[0] =
        minEnLD64 + fMult((avgEnLD64 - minEnLD64), FL2FXCONST_DBL(0.06666667f));
    enLD64[1] =
        minEnLD64 + fMult((avgEnLD64 - minEnLD64), FL2FXCONST_DBL(0.20000000f));
    enLD64[2] =
        minEnLD64 + fMult((avgEnLD64 - minEnLD64), FL2FXCONST_DBL(0.33333334f));
    enLD64[3] =
        minEnLD64 + fMult((avgEnLD64 - minEnLD64), FL2FXCONST_DBL(0.46666667f));
    enLD64[4] =
        minEnLD64 + fMult((avgEnLD64 - minEnLD64), FL2FXCONST_DBL(0.60000002f));
    enLD64[5] =
        minEnLD64 + fMult((avgEnLD64 - minEnLD64), FL2FXCONST_DBL(0.73333335f));
    enLD64[6] =
        minEnLD64 + fMult((avgEnLD64 - minEnLD64), FL2FXCONST_DBL(0.86666667f));
    enLD64[7] = minEnLD64 + (avgEnLD64 - minEnLD64);

    done = 0;
    enIdx = 0;
    sfb = maxSfb - 1;

    while (!done) {
      for (elementId = elementOffset; elementId < nElements; elementId++) {
        if (cm->elInfo[elementId].elType != ID_DSE) {
          PE_DATA *peData = &qcElement[elementId]->peData;
          for (ch = 0; ch < cm->elInfo[elementId].nChannelsInEl; ch++) {
            const INT chIdx = cm->elInfo[elementId].ChannelIndex[ch];
            QC_OUT_CHANNEL *qcOutChannel =
                qcElement[elementId]->qcOutChannel[ch];
            if (sfb >= startSfb[chIdx] && sfb < maxSfbPerGroup[chIdx]) {
              for (sfbGrp = 0; sfbGrp < sfbCnt[chIdx];
                   sfbGrp += sfbPerGroup[chIdx]) {
                /* sfb energy below border ? */
                if (ahFlag[elementId][ch][sfbGrp + sfb] != NO_AH &&
                    qcOutChannel->sfbEnergyLdData[sfbGrp + sfb] <
                        enLD64[enIdx]) {
                  /* allow hole */
                  ahFlag[elementId][ch][sfbGrp + sfb] = NO_AH;
                  qcOutChannel->sfbThresholdLdData[sfbGrp + sfb] =
                      FL2FXCONST_DBL(0.015625f) +
                      qcOutChannel->sfbWeightedEnergyLdData[sfbGrp + sfb];
                  actPe -= peData->peChannelData[ch].sfbPe[sfbGrp + sfb] >>
                           PE_CONSTPART_SHIFT;
                }
                if (actPe <= desiredPe) {
                  return; /* stop if enough has been saved */
                }
              } /* sfbGrp */
            }   /* sfb */
          }     /* nChannelsInEl */
        }       /* ID_DSE */
      }         /* elementID */

      sfb--;
      if (sfb < minSfb) {
        /* restart with next energy border */
        sfb = maxSfb;
        enIdx++;
        if (enIdx >= NUM_NRG_LEVS) {
          done = 1;
        }
      }
    } /* done */
  }   /* (actPe <= desiredPe) */
}

/* reset avoid hole flags from AH_ACTIVE to AH_INACTIVE  */
static void FDKaacEnc_resetAHFlags(
    UCHAR ahFlag[(2)][MAX_GROUPED_SFB], const INT nChannels,
    const PSY_OUT_CHANNEL *const psyOutChannel[(2)]) {
  int ch, sfb, sfbGrp;

  for (ch = 0; ch < nChannels; ch++) {
    for (sfbGrp = 0; sfbGrp < psyOutChannel[ch]->sfbCnt;
         sfbGrp += psyOutChannel[ch]->sfbPerGroup) {
      for (sfb = 0; sfb < psyOutChannel[ch]->maxSfbPerGroup; sfb++) {
        if (ahFlag[ch][sfbGrp + sfb] == AH_ACTIVE) {
          ahFlag[ch][sfbGrp + sfb] = AH_INACTIVE;
        }
      }
    }
  }
}

static FIXP_DBL CalcRedValPower(FIXP_DBL num, FIXP_DBL denum, INT *scaling) {
  FIXP_DBL value = FL2FXCONST_DBL(0.f);

  if (num >= FL2FXCONST_DBL(0.f)) {
    value = fDivNorm(num, denum, scaling);
  } else {
    value = -fDivNorm(-num, denum, scaling);
  }
  value = f2Pow(value, *scaling, scaling);

  return value;
}

/*****************************************************************************
functionname: FDKaacEnc_adaptThresholdsToPe
description:  two guesses for the reduction value and one final correction of
the thresholds
*****************************************************************************/
static void FDKaacEnc_adaptThresholdsToPe(
    const CHANNEL_MAPPING *const cm,
    ATS_ELEMENT *const AdjThrStateElement[((8))],
    QC_OUT_ELEMENT *const qcElement[((8))],
    const PSY_OUT_ELEMENT *const psyOutElement[((8))], const INT desiredPe,
    const INT maxIter2ndGuess, const INT processElements,
    const INT elementOffset) {
  FIXP_DBL reductionValue_m;
  SCHAR reductionValue_e;
  UCHAR(*pAhFlag)[(2)][MAX_GROUPED_SFB];
  FIXP_DBL(*pThrExp)[(2)][MAX_GROUPED_SFB];
  int iter;

  INT constPartGlobal, noRedPeGlobal, nActiveLinesGlobal, redPeGlobal;
  constPartGlobal = noRedPeGlobal = nActiveLinesGlobal = redPeGlobal = 0;

  int elementId;

  int nElements = elementOffset + processElements;
  if (nElements > cm->nElements) {
    nElements = cm->nElements;
  }

  /* The reinterpret_cast is used to suppress a compiler warning. We know that
   * qcElement[0]->dynMem_Ah_Flag is sufficiently aligned, so the cast is safe
   */
  pAhFlag = reinterpret_cast<UCHAR(*)[(2)][MAX_GROUPED_SFB]>(
      reinterpret_cast<void *>(qcElement[0]->dynMem_Ah_Flag));
  /* The reinterpret_cast is used to suppress a compiler warning. We know that
   * qcElement[0]->dynMem_Thr_Exp is sufficiently aligned, so the cast is safe
   */
  pThrExp = reinterpret_cast<FIXP_DBL(*)[(2)][MAX_GROUPED_SFB]>(
      reinterpret_cast<void *>(qcElement[0]->dynMem_Thr_Exp));

  /* ------------------------------------------------------- */
  /* Part I: Initialize data structures and variables... */
  /* ------------------------------------------------------- */
  for (elementId = elementOffset; elementId < nElements; elementId++) {
    if (cm->elInfo[elementId].elType != ID_DSE) {
      INT nChannels = cm->elInfo[elementId].nChannelsInEl;
      PE_DATA *peData = &qcElement[elementId]->peData;

      /* thresholds to the power of redExp */
      FDKaacEnc_calcThreshExp(
          pThrExp[elementId], qcElement[elementId]->qcOutChannel,
          psyOutElement[elementId]->psyOutChannel, nChannels);

      /* lower the minSnr requirements for low energies compared to the average
         energy in this frame */
      FDKaacEnc_adaptMinSnr(qcElement[elementId]->qcOutChannel,
                            psyOutElement[elementId]->psyOutChannel,
                            &AdjThrStateElement[elementId]->minSnrAdaptParam,
                            nChannels);

      /* init ahFlag (0: no ah necessary, 1: ah possible, 2: ah active */
      FDKaacEnc_initAvoidHoleFlag(
          qcElement[elementId]->qcOutChannel,
          psyOutElement[elementId]->psyOutChannel, pAhFlag[elementId],
          &psyOutElement[elementId]->toolsInfo, nChannels,
          &AdjThrStateElement[elementId]->ahParam);

      /* sum up */
      constPartGlobal += peData->constPart;
      noRedPeGlobal += peData->pe;
      nActiveLinesGlobal += fixMax((INT)peData->nActiveLines, 1);

    } /* EOF DSE-suppression */
  }   /* EOF for all elements... */

  /*
     First guess of reduction value:
     avgThrExp = (float)pow(2.0f, (constPartGlobal - noRedPeGlobal)/(4.0f *
     nActiveLinesGlobal)); redVal    = (float)pow(2.0f, (constPartGlobal -
     desiredPe)/(4.0f * nActiveLinesGlobal)) - avgThrExp; redVal    = max(0.f,
     redVal);
  */
  int redVal_e, avgThrExp_e, result_e;
  FIXP_DBL redVal_m, avgThrExp_m;

  redVal_m = CalcRedValPower(constPartGlobal - desiredPe,
                             4 * nActiveLinesGlobal, &redVal_e);
  avgThrExp_m = CalcRedValPower(constPartGlobal - noRedPeGlobal,
                                4 * nActiveLinesGlobal, &avgThrExp_e);
  result_e = fMax(redVal_e, avgThrExp_e) + 1;

  reductionValue_m = fMax(FL2FXCONST_DBL(0.f),
                          scaleValue(redVal_m, redVal_e - result_e) -
                              scaleValue(avgThrExp_m, avgThrExp_e - result_e));
  reductionValue_e = result_e;

  /* ----------------------------------------------------------------------- */
  /* Part II: Calculate bit consumption of initial bit constraints setup */
  /* ----------------------------------------------------------------------- */
  for (elementId = elementOffset; elementId < nElements; elementId++) {
    if (cm->elInfo[elementId].elType != ID_DSE) {
      INT nChannels = cm->elInfo[elementId].nChannelsInEl;
      PE_DATA *peData = &qcElement[elementId]->peData;

      /* reduce thresholds */
      FDKaacEnc_reduceThresholdsCBR(
          qcElement[elementId]->qcOutChannel,
          psyOutElement[elementId]->psyOutChannel, pAhFlag[elementId],
          pThrExp[elementId], nChannels, reductionValue_m, reductionValue_e);

      /* pe after first guess */
      FDKaacEnc_calcPe(psyOutElement[elementId]->psyOutChannel,
                       qcElement[elementId]->qcOutChannel, peData, nChannels);

      redPeGlobal += peData->pe;
    } /* EOF DSE-suppression */
  }   /* EOF for all elements... */

  /* -------------------------------------------------- */
  /* Part III: Iterate until bit constraints are met */
  /* -------------------------------------------------- */
  iter = 0;
  while ((fixp_abs(redPeGlobal - desiredPe) >
          fMultI(FL2FXCONST_DBL(0.05f), desiredPe)) &&
         (iter < maxIter2ndGuess)) {
    INT desiredPeNoAHGlobal;
    INT redPeNoAHGlobal = 0;
    INT constPartNoAHGlobal = 0;
    INT nActiveLinesNoAHGlobal = 0;

    for (elementId = elementOffset; elementId < nElements; elementId++) {
      if (cm->elInfo[elementId].elType != ID_DSE) {
        INT redPeNoAH, constPartNoAH, nActiveLinesNoAH;
        INT nChannels = cm->elInfo[elementId].nChannelsInEl;
        PE_DATA *peData = &qcElement[elementId]->peData;

        /* pe for bands where avoid hole is inactive */
        FDKaacEnc_FDKaacEnc_calcPeNoAH(
            &redPeNoAH, &constPartNoAH, &nActiveLinesNoAH, peData,
            pAhFlag[elementId], psyOutElement[elementId]->psyOutChannel,
            nChannels);

        redPeNoAHGlobal += redPeNoAH;
        constPartNoAHGlobal += constPartNoAH;
        nActiveLinesNoAHGlobal += nActiveLinesNoAH;
      } /* EOF DSE-suppression */
    }   /* EOF for all elements... */

    /* Calculate new redVal ... */
    if (desiredPe < redPeGlobal) {
      /* new desired pe without bands where avoid hole is active */
      desiredPeNoAHGlobal = desiredPe - (redPeGlobal - redPeNoAHGlobal);

      /* limit desiredPeNoAH to positive values, as the PE can not become
       * negative */
      desiredPeNoAHGlobal = fMax(0, desiredPeNoAHGlobal);

      /* second guess (only if there are bands left where avoid hole is
       * inactive)*/
      if (nActiveLinesNoAHGlobal > 0) {
        /*
          avgThrExp = (float)pow(2.0f, (constPartNoAHGlobal - redPeNoAHGlobal) /
          (4.0f * nActiveLinesNoAHGlobal)); redVal   += (float)pow(2.0f,
          (constPartNoAHGlobal - desiredPeNoAHGlobal) / (4.0f *
          nActiveLinesNoAHGlobal)) - avgThrExp; redVal    = max(0.0f, redVal);
        */

        redVal_m = CalcRedValPower(constPartNoAHGlobal - desiredPeNoAHGlobal,
                                   4 * nActiveLinesNoAHGlobal, &redVal_e);
        avgThrExp_m = CalcRedValPower(constPartNoAHGlobal - redPeNoAHGlobal,
                                      4 * nActiveLinesNoAHGlobal, &avgThrExp_e);
        result_e = fMax(reductionValue_e, fMax(redVal_e, avgThrExp_e) + 1) + 1;

        reductionValue_m =
            fMax(FL2FXCONST_DBL(0.f),
                 scaleValue(reductionValue_m, reductionValue_e - result_e) +
                     scaleValue(redVal_m, redVal_e - result_e) -
                     scaleValue(avgThrExp_m, avgThrExp_e - result_e));
        reductionValue_e = result_e;

      } /* nActiveLinesNoAHGlobal > 0 */
    } else {
      /* redVal *= redPeGlobal/desiredPe; */
      int sc0, sc1;
      reductionValue_m = fMultNorm(
          reductionValue_m,
          fDivNorm((FIXP_DBL)redPeGlobal, (FIXP_DBL)desiredPe, &sc0), &sc1);
      reductionValue_e += sc0 + sc1;

      for (elementId = elementOffset; elementId < nElements; elementId++) {
        if (cm->elInfo[elementId].elType != ID_DSE) {
          FDKaacEnc_resetAHFlags(pAhFlag[elementId],
                                 cm->elInfo[elementId].nChannelsInEl,
                                 psyOutElement[elementId]->psyOutChannel);
        } /* EOF DSE-suppression */
      }   /* EOF for all elements... */
    }

    redPeGlobal = 0;
    /* Calculate new redVal's PE... */
    for (elementId = elementOffset; elementId < nElements; elementId++) {
      if (cm->elInfo[elementId].elType != ID_DSE) {
        INT nChannels = cm->elInfo[elementId].nChannelsInEl;
        PE_DATA *peData = &qcElement[elementId]->peData;

        /* reduce thresholds */
        FDKaacEnc_reduceThresholdsCBR(
            qcElement[elementId]->qcOutChannel,
            psyOutElement[elementId]->psyOutChannel, pAhFlag[elementId],
            pThrExp[elementId], nChannels, reductionValue_m, reductionValue_e);

        /* pe after second guess */
        FDKaacEnc_calcPe(psyOutElement[elementId]->psyOutChannel,
                         qcElement[elementId]->qcOutChannel, peData, nChannels);
        redPeGlobal += peData->pe;

      } /* EOF DSE-suppression */
    }   /* EOF for all elements... */

    iter++;
  } /* EOF while */

  /* ------------------------------------------------------- */
  /* Part IV: if still required, further reduce constraints  */
  /* ------------------------------------------------------- */
  /*                  1.0*        1.15*       1.20*
   *               desiredPe   desiredPe   desiredPe
   *                   |           |           |
   * ...XXXXXXXXXXXXXXXXXXXXXXXXXXX|           |
   *                   |           |           |XXXXXXXXXXX...
   *                   |           |XXXXXXXXXXX|
   *            --- A ---          | --- B --- | --- C ---
   *
   * (X): redPeGlobal
   * (A): FDKaacEnc_correctThresh()
   * (B): FDKaacEnc_allowMoreHoles()
   * (C): FDKaacEnc_reduceMinSnr()
   */

  /* correct thresholds to get closer to the desired pe */
  if (redPeGlobal > desiredPe) {
    FDKaacEnc_correctThresh(cm, qcElement, psyOutElement, pAhFlag, pThrExp,
                            reductionValue_m, reductionValue_e,
                            desiredPe - redPeGlobal, processElements,
                            elementOffset);

    /* update PE */
    redPeGlobal = 0;
    for (elementId = elementOffset; elementId < nElements; elementId++) {
      if (cm->elInfo[elementId].elType != ID_DSE) {
        INT nChannels = cm->elInfo[elementId].nChannelsInEl;
        PE_DATA *peData = &qcElement[elementId]->peData;

        /* pe after correctThresh */
        FDKaacEnc_calcPe(psyOutElement[elementId]->psyOutChannel,
                         qcElement[elementId]->qcOutChannel, peData, nChannels);
        redPeGlobal += peData->pe;

      } /* EOF DSE-suppression */
    }   /* EOF for all elements... */
  }

  if (redPeGlobal > desiredPe) {
    /* reduce pe by reducing minSnr requirements */
    FDKaacEnc_reduceMinSnr(
        cm, qcElement, psyOutElement, pAhFlag,
        (fMultI(FL2FXCONST_DBL(0.15f), desiredPe) + desiredPe), &redPeGlobal,
        processElements, elementOffset);

    /* reduce pe by allowing additional spectral holes */
    FDKaacEnc_allowMoreHoles(cm, qcElement, psyOutElement, AdjThrStateElement,
                             pAhFlag, desiredPe, redPeGlobal, processElements,
                             elementOffset);
  }
}

/* similar to FDKaacEnc_adaptThresholdsToPe(), for  VBR-mode */
static void FDKaacEnc_AdaptThresholdsVBR(
    QC_OUT_CHANNEL *const qcOutChannel[(2)],
    const PSY_OUT_CHANNEL *const psyOutChannel[(2)],
    ATS_ELEMENT *const AdjThrStateElement,
    const struct TOOLSINFO *const toolsInfo, const INT nChannels) {
  UCHAR(*pAhFlag)[MAX_GROUPED_SFB];
  FIXP_DBL(*pThrExp)[MAX_GROUPED_SFB];

  /* allocate scratch memory */
  C_ALLOC_SCRATCH_START(_pAhFlag, UCHAR, (2) * MAX_GROUPED_SFB)
  C_ALLOC_SCRATCH_START(_pThrExp, FIXP_DBL, (2) * MAX_GROUPED_SFB)
  pAhFlag = (UCHAR(*)[MAX_GROUPED_SFB])_pAhFlag;
  pThrExp = (FIXP_DBL(*)[MAX_GROUPED_SFB])_pThrExp;

  /* thresholds to the power of redExp */
  FDKaacEnc_calcThreshExp(pThrExp, qcOutChannel, psyOutChannel, nChannels);

  /* lower the minSnr requirements for low energies compared to the average
     energy in this frame */
  FDKaacEnc_adaptMinSnr(qcOutChannel, psyOutChannel,
                        &AdjThrStateElement->minSnrAdaptParam, nChannels);

  /* init ahFlag (0: no ah necessary, 1: ah possible, 2: ah active */
  FDKaacEnc_initAvoidHoleFlag(qcOutChannel, psyOutChannel, pAhFlag, toolsInfo,
                              nChannels, &AdjThrStateElement->ahParam);

  /* reduce thresholds */
  FDKaacEnc_reduceThresholdsVBR(qcOutChannel, psyOutChannel, pAhFlag, pThrExp,
                                nChannels, AdjThrStateElement->vbrQualFactor,
                                &AdjThrStateElement->chaosMeasureOld);

  /* free scratch memory */
  C_ALLOC_SCRATCH_END(_pThrExp, FIXP_DBL, (2) * MAX_GROUPED_SFB)
  C_ALLOC_SCRATCH_END(_pAhFlag, UCHAR, (2) * MAX_GROUPED_SFB)
}

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

  functionname: FDKaacEnc_calcBitSave
  description:  Calculates percentage of bit save, see figure below
  returns:
  input:        parameters and bitres-fullness
  output:       percentage of bit save

*****************************************************************************/
/*
        bitsave
                    maxBitSave(%)|   clipLow
                                 |---\
                                 |    \
                                 |     \
                                 |      \
                                 |       \
                                 |--------\--------------> bitres
                                 |         \
                    minBitSave(%)|          \------------
                                          clipHigh      maxBitres
*/
static FIXP_DBL FDKaacEnc_calcBitSave(FIXP_DBL fillLevel,
                                      const FIXP_DBL clipLow,
                                      const FIXP_DBL clipHigh,
                                      const FIXP_DBL minBitSave,
                                      const FIXP_DBL maxBitSave,
                                      const FIXP_DBL bitsave_slope) {
  FIXP_DBL bitsave;

  fillLevel = fixMax(fillLevel, clipLow);
  fillLevel = fixMin(fillLevel, clipHigh);

  bitsave = maxBitSave - fMult((fillLevel - clipLow), bitsave_slope);

  return (bitsave);
}

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

  functionname: FDKaacEnc_calcBitSpend
  description:  Calculates percentage of bit spend, see figure below
  returns:
  input:        parameters and bitres-fullness
  output:       percentage of bit spend

*****************************************************************************/
/*
                              bitspend      clipHigh
                   maxBitSpend(%)|          /-----------maxBitres
                                 |         /
                                 |        /
                                 |       /
                                 |      /
                                 |     /
                                 |----/-----------------> bitres
                                 |   /
                   minBitSpend(%)|--/
                                   clipLow
*/
static FIXP_DBL FDKaacEnc_calcBitSpend(FIXP_DBL fillLevel,
                                       const FIXP_DBL clipLow,
                                       const FIXP_DBL clipHigh,
                                       const FIXP_DBL minBitSpend,
                                       const FIXP_DBL maxBitSpend,
                                       const FIXP_DBL bitspend_slope) {
  FIXP_DBL bitspend;

  fillLevel = fixMax(fillLevel, clipLow);
  fillLevel = fixMin(fillLevel, clipHigh);

  bitspend = minBitSpend + fMult(fillLevel - clipLow, bitspend_slope);

  return (bitspend);
}

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

  functionname: FDKaacEnc_adjustPeMinMax()
  description:  adjusts peMin and peMax parameters over time
  returns:
  input:        current pe, peMin, peMax, bitres size
  output:       adjusted peMin/peMax

*****************************************************************************/
static void FDKaacEnc_adjustPeMinMax(const INT currPe, INT *peMin, INT *peMax) {
  FIXP_DBL minFacHi = FL2FXCONST_DBL(0.3f), maxFacHi = (FIXP_DBL)MAXVAL_DBL,
           minFacLo = FL2FXCONST_DBL(0.14f), maxFacLo = FL2FXCONST_DBL(0.07f);
  INT diff;

  INT minDiff_fix = fMultI(FL2FXCONST_DBL(0.1666666667f), currPe);

  if (currPe > *peMax) {
    diff = (currPe - *peMax);
    *peMin += fMultI(minFacHi, diff);
    *peMax += fMultI(maxFacHi, diff);
  } else if (currPe < *peMin) {
    diff = (*peMin - currPe);
    *peMin -= fMultI(minFacLo, diff);
    *peMax -= fMultI(maxFacLo, diff);
  } else {
    *peMin += fMultI(minFacHi, (currPe - *peMin));
    *peMax -= fMultI(maxFacLo, (*peMax - currPe));
  }

  if ((*peMax - *peMin) < minDiff_fix) {
    INT peMax_fix = *peMax, peMin_fix = *peMin;
    FIXP_DBL partLo_fix, partHi_fix;

    partLo_fix = (FIXP_DBL)fixMax(0, currPe - peMin_fix);
    partHi_fix = (FIXP_DBL)fixMax(0, peMax_fix - currPe);

    peMax_fix =
        (INT)(currPe + fMultI(fDivNorm(partHi_fix, (partLo_fix + partHi_fix)),
                              minDiff_fix));
    peMin_fix =
        (INT)(currPe - fMultI(fDivNorm(partLo_fix, (partLo_fix + partHi_fix)),
                              minDiff_fix));
    peMin_fix = fixMax(0, peMin_fix);

    *peMax = peMax_fix;
    *peMin = peMin_fix;
  }
}

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

  functionname: BitresCalcBitFac
  description:  calculates factor of spending bits for one frame
  1.0 : take all frame dynpart bits
  >1.0 : take all frame dynpart bits + bitres
  <1.0 : put bits in bitreservoir
  returns:      BitFac
  input:        bitres-fullness, pe, blockType, parameter-settings
  output:

*****************************************************************************/
/*
                     bitfac(%)            pemax
                   bitspend(%)   |          /-----------maxBitres
                                 |         /
                                 |        /
                                 |       /
                                 |      /
                                 |     /
                                 |----/-----------------> pe
                                 |   /
                   bitsave(%)    |--/
                                    pemin
*/

void FDKaacEnc_bitresCalcBitFac(const INT bitresBits, const INT maxBitresBits,
                                const INT pe, const INT lastWindowSequence,
                                const INT avgBits, const FIXP_DBL maxBitFac,
                                const ADJ_THR_STATE *const AdjThr,
                                ATS_ELEMENT *const adjThrChan,
                                FIXP_DBL *const pBitresFac,
                                INT *const pBitresFac_e) {
  const BRES_PARAM *bresParam;
  INT pex;
  FIXP_DBL fillLevel;
  INT fillLevel_e = 0;

  FIXP_DBL bitresFac;
  INT bitresFac_e;

  FIXP_DBL bitSave, bitSpend;
  FIXP_DBL bitsave_slope, bitspend_slope;
  FIXP_DBL fillLevel_fix = MAXVAL_DBL;

  FIXP_DBL slope = MAXVAL_DBL;

  if (lastWindowSequence != SHORT_WINDOW) {
    bresParam = &(AdjThr->bresParamLong);
    bitsave_slope = FL2FXCONST_DBL(0.466666666);
    bitspend_slope = FL2FXCONST_DBL(0.666666666);
  } else {
    bresParam = &(AdjThr->bresParamShort);
    bitsave_slope = (FIXP_DBL)0x2E8BA2E9;
    bitspend_slope = (FIXP_DBL)0x7fffffff;
  }

  // fillLevel = (float)(bitresBits+avgBits) / (float)(maxBitresBits + avgBits);
  if (bitresBits < maxBitresBits) {
    fillLevel_fix = fDivNorm(bitresBits, maxBitresBits);
  }

  pex = fMax(pe, adjThrChan->peMin);
  pex = fMin(pex, adjThrChan->peMax);

  bitSave = FDKaacEnc_calcBitSave(
      fillLevel_fix, bresParam->clipSaveLow, bresParam->clipSaveHigh,
      bresParam->minBitSave, bresParam->maxBitSave, bitsave_slope);

  bitSpend = FDKaacEnc_calcBitSpend(
      fillLevel_fix, bresParam->clipSpendLow, bresParam->clipSpendHigh,
      bresParam->minBitSpend, bresParam->maxBitSpend, bitspend_slope);

  slope = schur_div((pex - adjThrChan->peMin),
                    (adjThrChan->peMax - adjThrChan->peMin), 31);

  /* scale down by 1 bit because the result of the following addition can be
   * bigger than 1 (though smaller than 2) */
  bitresFac = ((FIXP_DBL)(MAXVAL_DBL >> 1) - (bitSave >> 1));
  bitresFac_e = 1;                                                /* exp=1 */
  bitresFac = fMultAddDiv2(bitresFac, slope, bitSpend + bitSave); /* exp=1 */

  /*** limit bitresFac for small bitreservoir ***/
  fillLevel = fDivNorm(bitresBits, avgBits, &fillLevel_e);
  if (fillLevel_e < 0) {
    fillLevel = scaleValue(fillLevel, fillLevel_e);
    fillLevel_e = 0;
  }
  /* shift down value by 1 because of summation, ... */
  fillLevel >>= 1;
  fillLevel_e += 1;
  /* ..., this summation: */
  fillLevel += scaleValue(FL2FXCONST_DBL(0.7f), -fillLevel_e);
  /* set bitresfactor to same exponent as fillLevel */
  if (scaleValue(bitresFac, -fillLevel_e + 1) > fillLevel) {
    bitresFac = fillLevel;
    bitresFac_e = fillLevel_e;
  }

  /* limit bitresFac for high bitrates */
  if (scaleValue(bitresFac, bitresFac_e - (DFRACT_BITS - 1 - 24)) > maxBitFac) {
    bitresFac = maxBitFac;
    bitresFac_e = (DFRACT_BITS - 1 - 24);
  }

  FDKaacEnc_adjustPeMinMax(pe, &adjThrChan->peMin, &adjThrChan->peMax);

  /* output values */
  *pBitresFac = bitresFac;
  *pBitresFac_e = bitresFac_e;
}

/*****************************************************************************
functionname: FDKaacEnc_AdjThrNew
description:  allocate ADJ_THR_STATE
*****************************************************************************/
INT FDKaacEnc_AdjThrNew(ADJ_THR_STATE **phAdjThr, INT nElements) {
  INT err = 0;
  INT i;
  ADJ_THR_STATE *hAdjThr = GetRam_aacEnc_AdjustThreshold();
  if (hAdjThr == NULL) {
    err = 1;
    goto bail;
  }

  for (i = 0; i < nElements; i++) {
    hAdjThr->adjThrStateElem[i] = GetRam_aacEnc_AdjThrStateElement(i);
    if (hAdjThr->adjThrStateElem[i] == NULL) {
      err = 1;
      goto bail;
    }
  }

bail:
  *phAdjThr = hAdjThr;
  return err;
}

/*****************************************************************************
functionname: FDKaacEnc_AdjThrInit
description:  initialize ADJ_THR_STATE
*****************************************************************************/
void FDKaacEnc_AdjThrInit(
    ADJ_THR_STATE *const hAdjThr, const INT meanPe, const INT invQuant,
    const CHANNEL_MAPPING *const channelMapping, const INT sampleRate,
    const INT totalBitrate, const INT isLowDelay,
    const AACENC_BITRES_MODE bitResMode, const INT dZoneQuantEnable,
    const INT bitDistributionMode, const FIXP_DBL vbrQualFactor) {
  INT i;

  FIXP_DBL POINT8 = FL2FXCONST_DBL(0.8f);
  FIXP_DBL POINT6 = FL2FXCONST_DBL(0.6f);

  if (bitDistributionMode == 1) {
    hAdjThr->bitDistributionMode = AACENC_BD_MODE_INTRA_ELEMENT;
  } else {
    hAdjThr->bitDistributionMode = AACENC_BD_MODE_INTER_ELEMENT;
  }

  /* Max number of iterations in second guess is 3 for lowdelay aot and for
     configurations with multiple audio elements in general, otherwise iteration
     value is always 1. */
  hAdjThr->maxIter2ndGuess =
      (isLowDelay != 0 || channelMapping->nElements > 1) ? 3 : 1;

  /* common for all elements: */
  /* parameters for bitres control */
  hAdjThr->bresParamLong.clipSaveLow =
      (FIXP_DBL)0x1999999a; /* FL2FXCONST_DBL(0.2f); */
  hAdjThr->bresParamLong.clipSaveHigh =
      (FIXP_DBL)0x7999999a; /* FL2FXCONST_DBL(0.95f); */
  hAdjThr->bresParamLong.minBitSave =
      (FIXP_DBL)0xf999999a; /* FL2FXCONST_DBL(-0.05f); */
  hAdjThr->bresParamLong.maxBitSave =
      (FIXP_DBL)0x26666666; /* FL2FXCONST_DBL(0.3f); */
  hAdjThr->bresParamLong.clipSpendLow =
      (FIXP_DBL)0x1999999a; /* FL2FXCONST_DBL(0.2f); */
  hAdjThr->bresParamLong.clipSpendHigh =
      (FIXP_DBL)0x7999999a; /* FL2FXCONST_DBL(0.95f); */
  hAdjThr->bresParamLong.minBitSpend =
      (FIXP_DBL)0xf3333333; /* FL2FXCONST_DBL(-0.10f); */
  hAdjThr->bresParamLong.maxBitSpend =
      (FIXP_DBL)0x33333333; /* FL2FXCONST_DBL(0.4f); */

  hAdjThr->bresParamShort.clipSaveLow =
      (FIXP_DBL)0x199999a0; /* FL2FXCONST_DBL(0.2f); */
  hAdjThr->bresParamShort.clipSaveHigh =
      (FIXP_DBL)0x5fffffff; /* FL2FXCONST_DBL(0.75f); */
  hAdjThr->bresParamShort.minBitSave =
      (FIXP_DBL)0x00000000; /* FL2FXCONST_DBL(0.0f); */
  hAdjThr->bresParamShort.maxBitSave =
      (FIXP_DBL)0x199999a0; /* FL2FXCONST_DBL(0.2f); */
  hAdjThr->bresParamShort.clipSpendLow =
      (FIXP_DBL)0x199999a0; /* FL2FXCONST_DBL(0.2f); */
  hAdjThr->bresParamShort.clipSpendHigh =
      (FIXP_DBL)0x5fffffff; /* FL2FXCONST_DBL(0.75f); */
  hAdjThr->bresParamShort.minBitSpend =
      (FIXP_DBL)0xf9999998; /* FL2FXCONST_DBL(-0.05f); */
  hAdjThr->bresParamShort.maxBitSpend =
      (FIXP_DBL)0x40000000; /* FL2FXCONST_DBL(0.5f); */

  /* specific for each element: */
  for (i = 0; i < channelMapping->nElements; i++) {
    const FIXP_DBL relativeBits = channelMapping->elInfo[i].relativeBits;
    const INT nChannelsInElement = channelMapping->elInfo[i].nChannelsInEl;
    const INT bitrateInElement =
        (relativeBits != (FIXP_DBL)MAXVAL_DBL)
            ? (INT)fMultNorm(relativeBits, (FIXP_DBL)totalBitrate)
            : totalBitrate;
    const INT chBitrate = bitrateInElement >> (nChannelsInElement == 1 ? 0 : 1);

    ATS_ELEMENT *atsElem = hAdjThr->adjThrStateElem[i];
    MINSNR_ADAPT_PARAM *msaParam = &atsElem->minSnrAdaptParam;

    /* parameters for bitres control */
    if (isLowDelay) {
      atsElem->peMin = fMultI(POINT8, meanPe);
      atsElem->peMax = fMultI(POINT6, meanPe) << 1;
    } else {
      atsElem->peMin = fMultI(POINT8, meanPe) >> 1;
      atsElem->peMax = fMultI(POINT6, meanPe);
    }

    /* for use in FDKaacEnc_reduceThresholdsVBR */
    atsElem->chaosMeasureOld = FL2FXCONST_DBL(0.3f);

    /* additional pe offset to correct pe2bits for low bitrates */
    /* ---- no longer necessary, set by table ----- */
    atsElem->peOffset = 0;

    /* vbr initialisation */
    atsElem->vbrQualFactor = vbrQualFactor;
    if (chBitrate < 32000) {
      atsElem->peOffset =
          fixMax(50, 100 - fMultI((FIXP_DBL)0x666667, chBitrate));
    }

    /* avoid hole parameters */
    if (chBitrate >= 20000) {
      atsElem->ahParam.modifyMinSnr = TRUE;
      atsElem->ahParam.startSfbL = 15;
      atsElem->ahParam.startSfbS = 3;
    } else {
      atsElem->ahParam.modifyMinSnr = FALSE;
      atsElem->ahParam.startSfbL = 0;
      atsElem->ahParam.startSfbS = 0;
    }

    /* minSnr adaptation */
    msaParam->maxRed = FL2FXCONST_DBL(0.00390625f); /* 0.25f/64.0f */
    /* start adaptation of minSnr for avgEn/sfbEn > startRatio */
    msaParam->startRatio = FL2FXCONST_DBL(0.05190512648f); /* ld64(10.0f) */
    /* maximum minSnr reduction to minSnr^maxRed is reached for
       avgEn/sfbEn >= maxRatio */
    /* msaParam->maxRatio = 1000.0f; */
    /*msaParam->redRatioFac = ((float)1.0f - msaParam->maxRed) /
     * ((float)10.0f*log10(msaParam->startRatio/msaParam->maxRatio)/log10(2.0f)*(float)0.3010299956f);*/
    msaParam->redRatioFac = FL2FXCONST_DBL(-0.375f); /* -0.0375f * 10.0f */
    /*msaParam->redOffs = (float)1.0f - msaParam->redRatioFac * (float)10.0f *
     * log10(msaParam->startRatio)/log10(2.0f) * (float)0.3010299956f;*/
    msaParam->redOffs = FL2FXCONST_DBL(0.021484375); /* 1.375f/64.0f */

    /* init pe correction */
    atsElem->peCorrectionFactor_m = FL2FXCONST_DBL(0.5f); /* 1.0 */
    atsElem->peCorrectionFactor_e = 1;

    atsElem->dynBitsLast = -1;
    atsElem->peLast = 0;

    /* init bits to pe factor */

    /* init bits2PeFactor */
    FDKaacEnc_InitBits2PeFactor(
        &atsElem->bits2PeFactor_m, &atsElem->bits2PeFactor_e, bitrateInElement,
        nChannelsInElement, sampleRate, isLowDelay, dZoneQuantEnable, invQuant);

  } /* for nElements */
}

/*****************************************************************************
    functionname: FDKaacEnc_FDKaacEnc_calcPeCorrection
    description:  calc desired pe
*****************************************************************************/
static void FDKaacEnc_FDKaacEnc_calcPeCorrection(
    FIXP_DBL *const correctionFac_m, INT *const correctionFac_e,
    const INT peAct, const INT peLast, const INT bitsLast,
    const FIXP_DBL bits2PeFactor_m, const INT bits2PeFactor_e) {
  if ((bitsLast > 0) && (peAct < 1.5f * peLast) && (peAct > 0.7f * peLast) &&
      (FDKaacEnc_bits2pe2(bitsLast,
                          fMult(FL2FXCONST_DBL(1.2f / 2.f), bits2PeFactor_m),
                          bits2PeFactor_e + 1) > peLast) &&
      (FDKaacEnc_bits2pe2(bitsLast,
                          fMult(FL2FXCONST_DBL(0.65f), bits2PeFactor_m),
                          bits2PeFactor_e) < peLast)) {
    FIXP_DBL corrFac = *correctionFac_m;

    int scaling = 0;
    FIXP_DBL denum = (FIXP_DBL)FDKaacEnc_bits2pe2(bitsLast, bits2PeFactor_m,
                                                  bits2PeFactor_e);
    FIXP_DBL newFac = fDivNorm((FIXP_DBL)peLast, denum, &scaling);

    /* dead zone, newFac and corrFac are scaled by 0.5 */
    if ((FIXP_DBL)peLast <= denum) { /* ratio <= 1.f */
      newFac = fixMax(
          scaleValue(fixMin(fMult(FL2FXCONST_DBL(1.1f / 2.f), newFac),
                            scaleValue(FL2FXCONST_DBL(1.f / 2.f), -scaling)),
                     scaling),
          FL2FXCONST_DBL(0.85f / 2.f));
    } else { /* ratio < 1.f */
      newFac = fixMax(
          fixMin(scaleValue(fMult(FL2FXCONST_DBL(0.9f / 2.f), newFac), scaling),
                 FL2FXCONST_DBL(1.15f / 2.f)),
          FL2FXCONST_DBL(1.f / 2.f));
    }

    if (((newFac > FL2FXCONST_DBL(1.f / 2.f)) &&
         (corrFac < FL2FXCONST_DBL(1.f / 2.f))) ||
        ((newFac < FL2FXCONST_DBL(1.f / 2.f)) &&
         (corrFac > FL2FXCONST_DBL(1.f / 2.f)))) {
      corrFac = FL2FXCONST_DBL(1.f / 2.f);
    }

    /* faster adaptation towards 1.0, slower in the other direction */
    if ((corrFac < FL2FXCONST_DBL(1.f / 2.f) && newFac < corrFac) ||
        (corrFac > FL2FXCONST_DBL(1.f / 2.f) && newFac > corrFac)) {
      corrFac = fMult(FL2FXCONST_DBL(0.85f), corrFac) +
                fMult(FL2FXCONST_DBL(0.15f), newFac);
    } else {
      corrFac = fMult(FL2FXCONST_DBL(0.7f), corrFac) +
                fMult(FL2FXCONST_DBL(0.3f), newFac);
    }

    corrFac = fixMax(fixMin(corrFac, FL2FXCONST_DBL(1.15f / 2.f)),
                     FL2FXCONST_DBL(0.85 / 2.f));

    *correctionFac_m = corrFac;
    *correctionFac_e = 1;
  } else {
    *correctionFac_m = FL2FXCONST_DBL(1.f / 2.f);
    *correctionFac_e = 1;
  }
}

static void FDKaacEnc_calcPeCorrectionLowBitRes(
    FIXP_DBL *const correctionFac_m, INT *const correctionFac_e,
    const INT peLast, const INT bitsLast, const INT bitresLevel,
    const INT nChannels, const FIXP_DBL bits2PeFactor_m,
    const INT bits2PeFactor_e) {
  /* tuning params */
  const FIXP_DBL amp = FL2FXCONST_DBL(0.005);
  const FIXP_DBL maxDiff = FL2FXCONST_DBL(0.25f);

  if (bitsLast > 0) {
    /* Estimate deviation of granted and used dynamic bits in previous frame, in
     * PE units */
    const int bitsBalLast =
        peLast - FDKaacEnc_bits2pe2(bitsLast, bits2PeFactor_m, bits2PeFactor_e);

    /* reserve n bits per channel */
    int headroom = (bitresLevel >= 50 * nChannels) ? 0 : (100 * nChannels);

    /* in PE units */
    headroom = FDKaacEnc_bits2pe2(headroom, bits2PeFactor_m, bits2PeFactor_e);

    /*
     * diff = amp * ((bitsBalLast - headroom) / (bitresLevel + headroom)
     * diff = max ( min ( diff, maxDiff, -maxDiff)) / 2
     */
    FIXP_DBL denominator = (FIXP_DBL)FDKaacEnc_bits2pe2(
                               bitresLevel, bits2PeFactor_m, bits2PeFactor_e) +
                           (FIXP_DBL)headroom;

    int scaling = 0;
    FIXP_DBL diff =
        (bitsBalLast >= headroom)
            ? fMult(amp, fDivNorm((FIXP_DBL)(bitsBalLast - headroom),
                                  denominator, &scaling))
            : -fMult(amp, fDivNorm(-(FIXP_DBL)(bitsBalLast - headroom),
                                   denominator, &scaling));

    scaling -= 1; /* divide by 2 */

    diff = (scaling <= 0)
               ? fMax(fMin(diff >> (-scaling), maxDiff >> 1), -maxDiff >> 1)
               : fMax(fMin(diff, maxDiff >> (1 + scaling)),
                      -maxDiff >> (1 + scaling))
                     << scaling;

    /*
     * corrFac += diff
     * corrFac = max ( min ( corrFac/2.f, 1.f/2.f, 0.75f/2.f ) )
     */
    *correctionFac_m =
        fMax(fMin((*correctionFac_m) + diff, FL2FXCONST_DBL(1.0f / 2.f)),
             FL2FXCONST_DBL(0.75f / 2.f));
    *correctionFac_e = 1;
  } else {
    *correctionFac_m = FL2FXCONST_DBL(0.75 / 2.f);
    *correctionFac_e = 1;
  }
}

void FDKaacEnc_DistributeBits(
    ADJ_THR_STATE *adjThrState, ATS_ELEMENT *AdjThrStateElement,
    PSY_OUT_CHANNEL *psyOutChannel[(2)], PE_DATA *peData, INT *grantedPe,
    INT *grantedPeCorr, const INT nChannels, const INT commonWindow,
    const INT grantedDynBits, const INT bitresBits, const INT maxBitresBits,
    const FIXP_DBL maxBitFac, const AACENC_BITRES_MODE bitResMode) {
  FIXP_DBL bitFactor;
  INT bitFactor_e;
  INT noRedPe = peData->pe;

  /* prefer short windows for calculation of bitFactor */
  INT curWindowSequence = LONG_WINDOW;
  if (nChannels == 2) {
    if ((psyOutChannel[0]->lastWindowSequence == SHORT_WINDOW) ||
        (psyOutChannel[1]->lastWindowSequence == SHORT_WINDOW)) {
      curWindowSequence = SHORT_WINDOW;
    }
  } else {
    curWindowSequence = psyOutChannel[0]->lastWindowSequence;
  }

  if (grantedDynBits >= 1) {
    if (bitResMode != AACENC_BR_MODE_FULL) {
      /* small or disabled bitreservoir */
      *grantedPe = FDKaacEnc_bits2pe2(grantedDynBits,
                                      AdjThrStateElement->bits2PeFactor_m,
                                      AdjThrStateElement->bits2PeFactor_e);
    } else {
      /* factor dependend on current fill level and pe */
      FDKaacEnc_bitresCalcBitFac(
          bitresBits, maxBitresBits, noRedPe, curWindowSequence, grantedDynBits,
          maxBitFac, adjThrState, AdjThrStateElement, &bitFactor, &bitFactor_e);

      /* desired pe for actual frame */
      /* Worst case max of grantedDynBits is = 1024 * 5.27 * 2 */
      *grantedPe = FDKaacEnc_bits2pe2(
          grantedDynBits, fMult(bitFactor, AdjThrStateElement->bits2PeFactor_m),
          AdjThrStateElement->bits2PeFactor_e + bitFactor_e);
    }
  } else {
    *grantedPe = 0; /* prevent divsion by 0 */
  }

  /* correction of pe value */
  switch (bitResMode) {
    case AACENC_BR_MODE_DISABLED:
    case AACENC_BR_MODE_REDUCED:
      /* correction of pe value for low bitres */
      FDKaacEnc_calcPeCorrectionLowBitRes(
          &AdjThrStateElement->peCorrectionFactor_m,
          &AdjThrStateElement->peCorrectionFactor_e, AdjThrStateElement->peLast,
          AdjThrStateElement->dynBitsLast, bitresBits, nChannels,
          AdjThrStateElement->bits2PeFactor_m,
          AdjThrStateElement->bits2PeFactor_e);
      break;
    case AACENC_BR_MODE_FULL:
    default:
      /* correction of pe value for high bitres */
      FDKaacEnc_FDKaacEnc_calcPeCorrection(
          &AdjThrStateElement->peCorrectionFactor_m,
          &AdjThrStateElement->peCorrectionFactor_e,
          fixMin(*grantedPe, noRedPe), AdjThrStateElement->peLast,
          AdjThrStateElement->dynBitsLast, AdjThrStateElement->bits2PeFactor_m,
          AdjThrStateElement->bits2PeFactor_e);
      break;
  }

  *grantedPeCorr =
      (INT)(fMult((FIXP_DBL)(*grantedPe << Q_AVGBITS),
                  AdjThrStateElement->peCorrectionFactor_m) >>
            (Q_AVGBITS - AdjThrStateElement->peCorrectionFactor_e));

  /* update last pe */
  AdjThrStateElement->peLast = *grantedPe;
  AdjThrStateElement->dynBitsLast = -1;
}

/*****************************************************************************
functionname: FDKaacEnc_AdjustThresholds
description:  adjust thresholds
*****************************************************************************/
void FDKaacEnc_AdjustThresholds(
    ADJ_THR_STATE *const hAdjThr, QC_OUT_ELEMENT *const qcElement[((8))],
    QC_OUT *const qcOut, const PSY_OUT_ELEMENT *const psyOutElement[((8))],
    const INT CBRbitrateMode, const CHANNEL_MAPPING *const cm) {
  int i;

  if (CBRbitrateMode) {
    /* In case, no bits must be shifted between different elements, */
    /* an element-wise execution of the pe-dependent threshold- */
    /* adaption becomes necessary... */
    if (hAdjThr->bitDistributionMode == AACENC_BD_MODE_INTRA_ELEMENT) {
      for (i = 0; i < cm->nElements; i++) {
        ELEMENT_INFO elInfo = cm->elInfo[i];

        if ((elInfo.elType == ID_SCE) || (elInfo.elType == ID_CPE) ||
            (elInfo.elType == ID_LFE)) {
          /* qcElement[i]->grantedPe = 2000; */ /* Use this only for debugging
                                                 */
          // if (totalGrantedPeCorr < totalNoRedPe) {
          if (qcElement[i]->grantedPeCorr < qcElement[i]->peData.pe) {
            /* calc threshold necessary for desired pe */
            FDKaacEnc_adaptThresholdsToPe(
                cm, hAdjThr->adjThrStateElem, qcElement, psyOutElement,
                qcElement[i]->grantedPeCorr, hAdjThr->maxIter2ndGuess,
                1, /* Process only 1 element */
                i  /* Process exactly THIS element */
            );
          }
        } /*  -end- if(ID_SCE || ID_CPE || ID_LFE) */
      }   /* -end- element loop */
    }     /* AACENC_BD_MODE_INTRA_ELEMENT */
    else if (hAdjThr->bitDistributionMode == AACENC_BD_MODE_INTER_ELEMENT) {
      /* Use global Pe to obtain the thresholds? */
      if (qcOut->totalGrantedPeCorr < qcOut->totalNoRedPe) {
        /* add equal loadness quantization noise to match the */
        /* desired pe calc threshold necessary for desired pe */
        /* Now carried out globally to cover all(!) channels. */
        FDKaacEnc_adaptThresholdsToPe(cm, hAdjThr->adjThrStateElem, qcElement,
                                      psyOutElement, qcOut->totalGrantedPeCorr,
                                      hAdjThr->maxIter2ndGuess,
                                      cm->nElements, /* Process all elements */
                                      0); /* Process exactly THIS element */
      } else {
        /* In case global pe doesn't need to be reduced check each element to
           hold estimated bitrate below maximum element bitrate. */
        for (i = 0; i < cm->nElements; i++) {
          if ((cm->elInfo[i].elType == ID_SCE) ||
              (cm->elInfo[i].elType == ID_CPE) ||
              (cm->elInfo[i].elType == ID_LFE)) {
            /* Element pe applies to dynamic bits of maximum element bitrate. */
            const int maxElementPe = FDKaacEnc_bits2pe2(
                (cm->elInfo[i].nChannelsInEl * MIN_BUFSIZE_PER_EFF_CHAN) -
                    qcElement[i]->staticBitsUsed - qcElement[i]->extBitsUsed,
                hAdjThr->adjThrStateElem[i]->bits2PeFactor_m,
                hAdjThr->adjThrStateElem[i]->bits2PeFactor_e);

            if (maxElementPe < qcElement[i]->peData.pe) {
              FDKaacEnc_adaptThresholdsToPe(
                  cm, hAdjThr->adjThrStateElem, qcElement, psyOutElement,
                  maxElementPe, hAdjThr->maxIter2ndGuess, 1, i);
            }
          } /*  -end- if(ID_SCE || ID_CPE || ID_LFE) */
        }   /* -end- element loop */
      }     /* (qcOut->totalGrantedPeCorr < qcOut->totalNoRedPe) */
    }       /* AACENC_BD_MODE_INTER_ELEMENT */
  } else {
    for (i = 0; i < cm->nElements; i++) {
      ELEMENT_INFO elInfo = cm->elInfo[i];

      if ((elInfo.elType == ID_SCE) || (elInfo.elType == ID_CPE) ||
          (elInfo.elType == ID_LFE)) {
        /* for VBR-mode */
        FDKaacEnc_AdaptThresholdsVBR(
            qcElement[i]->qcOutChannel, psyOutElement[i]->psyOutChannel,
            hAdjThr->adjThrStateElem[i], &psyOutElement[i]->toolsInfo,
            cm->elInfo[i].nChannelsInEl);
      } /*  -end- if(ID_SCE || ID_CPE || ID_LFE) */

    } /* -end- element loop */
  }
  for (i = 0; i < cm->nElements; i++) {
    int ch, sfb, sfbGrp;
    /* no weighting of threholds and energies for mlout */
    /* weight energies and thresholds */
    for (ch = 0; ch < cm->elInfo[i].nChannelsInEl; ch++) {
      QC_OUT_CHANNEL *pQcOutCh = qcElement[i]->qcOutChannel[ch];
      for (sfbGrp = 0; sfbGrp < psyOutElement[i]->psyOutChannel[ch]->sfbCnt;
           sfbGrp += psyOutElement[i]->psyOutChannel[ch]->sfbPerGroup) {
        for (sfb = 0; sfb < psyOutElement[i]->psyOutChannel[ch]->maxSfbPerGroup;
             sfb++) {
          pQcOutCh->sfbThresholdLdData[sfb + sfbGrp] +=
              pQcOutCh->sfbEnFacLd[sfb + sfbGrp];
        }
      }
    }
  }
}

void FDKaacEnc_AdjThrClose(ADJ_THR_STATE **phAdjThr) {
  INT i;
  ADJ_THR_STATE *hAdjThr = *phAdjThr;

  if (hAdjThr != NULL) {
    for (i = 0; i < ((8)); i++) {
      if (hAdjThr->adjThrStateElem[i] != NULL) {
        FreeRam_aacEnc_AdjThrStateElement(&hAdjThr->adjThrStateElem[i]);
      }
    }
    FreeRam_aacEnc_AdjustThreshold(phAdjThr);
  }
}