aboutsummaryrefslogtreecommitdiffstats
path: root/fdk-aac/libSBRdec/src/lpp_tran.cpp
blob: 68a25bff087dfcca0385f8be4cc1c331edcd428a (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
/* -----------------------------------------------------------------------------
Software License for The Fraunhofer FDK AAC Codec Library for Android

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

/**************************** SBR decoder library ******************************

   Author(s):

   Description:

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

/*!
  \file
  \brief  Low Power Profile Transposer
  This module provides the transposer. The main entry point is lppTransposer().
  The function generates high frequency content by copying data from the low
  band (provided by core codec) into the high band. This process is also
  referred to as "patching". The function also implements spectral whitening by
  means of inverse filtering based on LPC coefficients.

  Together with the QMF filterbank the transposer can be tested using a supplied
  test program. See main_audio.cpp for details. This module does use fractional
  arithmetic and the accuracy of the computations has an impact on the overall
  sound quality. The module also needs to take into account the different
  scaling of spectral data.

  \sa lppTransposer(), main_audio.cpp, sbr_scale.h, \ref documentationOverview
*/

#ifdef __ANDROID__
#include "log/log.h"
#endif

#include "lpp_tran.h"

#include "sbr_ram.h"
#include "sbr_rom.h"

#include "genericStds.h"
#include "autocorr2nd.h"

#include "HFgen_preFlat.h"

#define LPC_SCALE_FACTOR 2

/*!
 *
 * \brief Get bandwidth expansion factor from filtering level
 *
 * Returns a filter parameter (bandwidth expansion factor) depending on
 * the desired filtering level signalled in the bitstream.
 * When switching the filtering level from LOW to OFF, an additional
 * level is being inserted to achieve a smooth transition.
 */

static FIXP_DBL mapInvfMode(INVF_MODE mode, INVF_MODE prevMode,
                            WHITENING_FACTORS whFactors) {
  switch (mode) {
    case INVF_LOW_LEVEL:
      if (prevMode == INVF_OFF)
        return whFactors.transitionLevel;
      else
        return whFactors.lowLevel;

    case INVF_MID_LEVEL:
      return whFactors.midLevel;

    case INVF_HIGH_LEVEL:
      return whFactors.highLevel;

    default:
      if (prevMode == INVF_LOW_LEVEL)
        return whFactors.transitionLevel;
      else
        return whFactors.off;
  }
}

/*!
 *
 * \brief Perform inverse filtering level emphasis
 *
 * Retrieve bandwidth expansion factor and apply smoothing for each filter band
 *
 */

static void inverseFilteringLevelEmphasis(
    HANDLE_SBR_LPP_TRANS hLppTrans, /*!< Handle of lpp transposer  */
    UCHAR nInvfBands,              /*!< Number of bands for inverse filtering */
    INVF_MODE *sbr_invf_mode,      /*!< Current inverse filtering modes */
    INVF_MODE *sbr_invf_mode_prev, /*!< Previous inverse filtering modes */
    FIXP_DBL *bwVector             /*!< Resulting filtering levels */
) {
  for (int i = 0; i < nInvfBands; i++) {
    FIXP_DBL accu;
    FIXP_DBL bwTmp = mapInvfMode(sbr_invf_mode[i], sbr_invf_mode_prev[i],
                                 hLppTrans->pSettings->whFactors);

    if (bwTmp < hLppTrans->bwVectorOld[i]) {
      accu = fMultDiv2(FL2FXCONST_DBL(0.75f), bwTmp) +
             fMultDiv2(FL2FXCONST_DBL(0.25f), hLppTrans->bwVectorOld[i]);
    } else {
      accu = fMultDiv2(FL2FXCONST_DBL(0.90625f), bwTmp) +
             fMultDiv2(FL2FXCONST_DBL(0.09375f), hLppTrans->bwVectorOld[i]);
    }

    if (accu<FL2FXCONST_DBL(0.015625f)>> 1) {
      bwVector[i] = FL2FXCONST_DBL(0.0f);
    } else {
      bwVector[i] = fixMin(accu << 1, FL2FXCONST_DBL(0.99609375f));
    }
  }
}

/* Resulting autocorrelation determinant exponent */
#define ACDET_EXP \
  (2 * (DFRACT_BITS + sbrScaleFactor->lb_scale + 10 - ac.det_scale))
#define AC_EXP (-sbrScaleFactor->lb_scale + LPC_SCALE_FACTOR)
#define ALPHA_EXP (-sbrScaleFactor->lb_scale + LPC_SCALE_FACTOR + 1)
/* Resulting transposed QMF values exponent 16 bit normalized samplebits
 * assumed. */
#define QMFOUT_EXP ((SAMPLE_BITS - 15) - sbrScaleFactor->lb_scale)

static inline void calc_qmfBufferReal(FIXP_DBL **qmfBufferReal,
                                      const FIXP_DBL *const lowBandReal,
                                      const int startSample,
                                      const int stopSample, const UCHAR hiBand,
                                      const int dynamicScale,
                                      const FIXP_SGL a0r, const FIXP_SGL a1r) {
  const int dynscale = fixMax(0, dynamicScale - 1) + 1;
  const int rescale = -fixMin(0, dynamicScale - 1) + 1;
  const int descale =
      fixMin(DFRACT_BITS - 1, LPC_SCALE_FACTOR + dynamicScale + rescale);

  for (int i = 0; i < stopSample - startSample; i++) {
    FIXP_DBL accu;

    accu = fMultDiv2(a1r, lowBandReal[i]) + fMultDiv2(a0r, lowBandReal[i + 1]);
    accu = (lowBandReal[i + 2] >> descale) + (accu >> dynscale);

    qmfBufferReal[i + startSample][hiBand] =
        SATURATE_LEFT_SHIFT(accu, rescale, DFRACT_BITS);
  }
}

/*!
 *
 * \brief Perform transposition by patching of subband samples.
 * This function serves as the main entry point into the module. The function
 * determines the areas for the patching process (these are the source range as
 * well as the target range) and implements spectral whitening by means of
 * inverse filtering. The function autoCorrelation2nd() is an auxiliary function
 * for calculating the LPC coefficients for the filtering.  The actual
 * calculation of the LPC coefficients and the implementation of the filtering
 * are done as part of lppTransposer().
 *
 * Note that the filtering is done on all available QMF subsamples, whereas the
 * patching is only done on those QMF subsamples that will be used in the next
 * QMF synthesis. The filtering is also implemented before the patching includes
 * further dependencies on parameters from the SBR data.
 *
 */

void lppTransposer(
    HANDLE_SBR_LPP_TRANS hLppTrans,   /*!< Handle of lpp transposer  */
    QMF_SCALE_FACTOR *sbrScaleFactor, /*!< Scaling factors */
    FIXP_DBL **qmfBufferReal, /*!< Pointer to pointer to real part of subband
                                 samples (source) */

    FIXP_DBL *degreeAlias,    /*!< Vector for results of aliasing estimation */
    FIXP_DBL **qmfBufferImag, /*!< Pointer to pointer to imaginary part of
                                 subband samples (source) */
    const int useLP, const int fPreWhitening, const int v_k_master0,
    const int timeStep,       /*!< Time step of envelope */
    const int firstSlotOffs,  /*!< Start position in time */
    const int lastSlotOffs,   /*!< Number of overlap-slots into next frame */
    const int nInvfBands,     /*!< Number of bands for inverse filtering */
    INVF_MODE *sbr_invf_mode, /*!< Current inverse filtering modes */
    INVF_MODE *sbr_invf_mode_prev /*!< Previous inverse filtering modes */
) {
  INT bwIndex[MAX_NUM_PATCHES];
  FIXP_DBL bwVector[MAX_NUM_PATCHES]; /*!< pole moving factors */
  FIXP_DBL preWhiteningGains[(64) / 2];
  int preWhiteningGains_exp[(64) / 2];

  int i;
  int loBand, start, stop;
  TRANSPOSER_SETTINGS *pSettings = hLppTrans->pSettings;
  PATCH_PARAM *patchParam = pSettings->patchParam;
  int patch;

  FIXP_SGL alphar[LPC_ORDER], a0r, a1r;
  FIXP_SGL alphai[LPC_ORDER], a0i = 0, a1i = 0;
  FIXP_SGL bw = FL2FXCONST_SGL(0.0f);

  int autoCorrLength;

  FIXP_DBL k1, k1_below = 0, k1_below2 = 0;

  ACORR_COEFS ac;
  int startSample;
  int stopSample;
  int stopSampleClear;

  int comLowBandScale;
  int ovLowBandShift;
  int lowBandShift;
  /*  int ovHighBandShift;*/

  alphai[0] = FL2FXCONST_SGL(0.0f);
  alphai[1] = FL2FXCONST_SGL(0.0f);

  startSample = firstSlotOffs * timeStep;
  stopSample = pSettings->nCols + lastSlotOffs * timeStep;
  FDK_ASSERT((lastSlotOffs * timeStep) <= pSettings->overlap);

  inverseFilteringLevelEmphasis(hLppTrans, nInvfBands, sbr_invf_mode,
                                sbr_invf_mode_prev, bwVector);

  stopSampleClear = stopSample;

  autoCorrLength = pSettings->nCols + pSettings->overlap;

  if (pSettings->noOfPatches > 0) {
    /* Set upper subbands to zero:
       This is required in case that the patches do not cover the complete
       highband (because the last patch would be too short). Possible
       optimization: Clearing bands up to usb would be sufficient here. */
    int targetStopBand =
        patchParam[pSettings->noOfPatches - 1].targetStartBand +
        patchParam[pSettings->noOfPatches - 1].numBandsInPatch;

    int memSize = ((64) - targetStopBand) * sizeof(FIXP_DBL);

    if (!useLP) {
      for (i = startSample; i < stopSampleClear; i++) {
        FDKmemclear(&qmfBufferReal[i][targetStopBand], memSize);
        FDKmemclear(&qmfBufferImag[i][targetStopBand], memSize);
      }
    } else {
      for (i = startSample; i < stopSampleClear; i++) {
        FDKmemclear(&qmfBufferReal[i][targetStopBand], memSize);
      }
    }
  }
#ifdef __ANDROID__
  else {
    // Safetynet logging
    android_errorWriteLog(0x534e4554, "112160868");
  }
#endif

  /* init bwIndex for each patch */
  FDKmemclear(bwIndex, sizeof(bwIndex));

  /*
    Calc common low band scale factor
  */
  comLowBandScale =
      fixMin(sbrScaleFactor->ov_lb_scale, sbrScaleFactor->lb_scale);

  ovLowBandShift = sbrScaleFactor->ov_lb_scale - comLowBandScale;
  lowBandShift = sbrScaleFactor->lb_scale - comLowBandScale;
  /*  ovHighBandShift = firstSlotOffs == 0 ? ovLowBandShift:0;*/

  if (fPreWhitening) {
    sbrDecoder_calculateGainVec(
        qmfBufferReal, qmfBufferImag,
        DFRACT_BITS - 1 - 16 -
            sbrScaleFactor->ov_lb_scale, /* convert scale to exponent */
        DFRACT_BITS - 1 - 16 -
            sbrScaleFactor->lb_scale, /* convert scale to exponent */
        pSettings->overlap, preWhiteningGains, preWhiteningGains_exp,
        v_k_master0, startSample, stopSample);
  }

  /* outer loop over bands to do analysis only once for each band */

  if (!useLP) {
    start = pSettings->lbStartPatching;
    stop = pSettings->lbStopPatching;
  } else {
    start = fixMax(1, pSettings->lbStartPatching - 2);
    stop = patchParam[0].targetStartBand;
  }

  for (loBand = start; loBand < stop; loBand++) {
    FIXP_DBL lowBandReal[(((1024) / (32) * (4) / 2) + (3 * (4))) + LPC_ORDER];
    FIXP_DBL *plowBandReal = lowBandReal;
    FIXP_DBL **pqmfBufferReal =
        qmfBufferReal + firstSlotOffs * timeStep /* + pSettings->overlap */;
    FIXP_DBL lowBandImag[(((1024) / (32) * (4) / 2) + (3 * (4))) + LPC_ORDER];
    FIXP_DBL *plowBandImag = lowBandImag;
    FIXP_DBL **pqmfBufferImag =
        qmfBufferImag + firstSlotOffs * timeStep /* + pSettings->overlap */;
    int resetLPCCoeffs = 0;
    int dynamicScale = DFRACT_BITS - 1 - LPC_SCALE_FACTOR;
    int acDetScale = 0; /* scaling of autocorrelation determinant */

    for (i = 0;
         i < LPC_ORDER + firstSlotOffs * timeStep /*+pSettings->overlap*/;
         i++) {
      *plowBandReal++ = hLppTrans->lpcFilterStatesRealLegSBR[i][loBand];
      if (!useLP)
        *plowBandImag++ = hLppTrans->lpcFilterStatesImagLegSBR[i][loBand];
    }

    /*
      Take old slope length qmf slot source values out of (overlap)qmf buffer
    */
    if (!useLP) {
      for (i = 0;
           i < pSettings->nCols + pSettings->overlap - firstSlotOffs * timeStep;
           i++) {
        *plowBandReal++ = (*pqmfBufferReal++)[loBand];
        *plowBandImag++ = (*pqmfBufferImag++)[loBand];
      }
    } else {
      /* pSettings->overlap is always even */
      FDK_ASSERT((pSettings->overlap & 1) == 0);
      for (i = 0; i < ((pSettings->nCols + pSettings->overlap -
                        firstSlotOffs * timeStep) >>
                       1);
           i++) {
        *plowBandReal++ = (*pqmfBufferReal++)[loBand];
        *plowBandReal++ = (*pqmfBufferReal++)[loBand];
      }
      if (pSettings->nCols & 1) {
        *plowBandReal++ = (*pqmfBufferReal++)[loBand];
      }
    }

    /*
      Determine dynamic scaling value.
     */
    dynamicScale =
        fixMin(dynamicScale,
               getScalefactor(lowBandReal, LPC_ORDER + pSettings->overlap) +
                   ovLowBandShift);
    dynamicScale =
        fixMin(dynamicScale,
               getScalefactor(&lowBandReal[LPC_ORDER + pSettings->overlap],
                              pSettings->nCols) +
                   lowBandShift);
    if (!useLP) {
      dynamicScale =
          fixMin(dynamicScale,
                 getScalefactor(lowBandImag, LPC_ORDER + pSettings->overlap) +
                     ovLowBandShift);
      dynamicScale =
          fixMin(dynamicScale,
                 getScalefactor(&lowBandImag[LPC_ORDER + pSettings->overlap],
                                pSettings->nCols) +
                     lowBandShift);
    }

    if (dynamicScale == 0) {
      /* In this special case the available headroom bits as well as
         ovLowBandShift and lowBandShift are zero. The spectrum is limited to
         prevent -1.0, so negative values for dynamicScale can be avoided. */
      for (i = 0; i < (LPC_ORDER + pSettings->overlap + pSettings->nCols);
           i++) {
        lowBandReal[i] = fixMax(lowBandReal[i], (FIXP_DBL)0x80000001);
      }
      if (!useLP) {
        for (i = 0; i < (LPC_ORDER + pSettings->overlap + pSettings->nCols);
             i++) {
          lowBandImag[i] = fixMax(lowBandImag[i], (FIXP_DBL)0x80000001);
        }
      }
    } else {
      dynamicScale =
          fixMax(0, dynamicScale -
                        1); /* one additional bit headroom to prevent -1.0 */
    }

    /*
      Scale temporal QMF buffer.
     */
    scaleValues(&lowBandReal[0], LPC_ORDER + pSettings->overlap,
                dynamicScale - ovLowBandShift);
    scaleValues(&lowBandReal[LPC_ORDER + pSettings->overlap], pSettings->nCols,
                dynamicScale - lowBandShift);

    if (!useLP) {
      scaleValues(&lowBandImag[0], LPC_ORDER + pSettings->overlap,
                  dynamicScale - ovLowBandShift);
      scaleValues(&lowBandImag[LPC_ORDER + pSettings->overlap],
                  pSettings->nCols, dynamicScale - lowBandShift);
    }

    if (!useLP) {
      acDetScale += autoCorr2nd_cplx(&ac, lowBandReal + LPC_ORDER,
                                     lowBandImag + LPC_ORDER, autoCorrLength);
    } else {
      acDetScale +=
          autoCorr2nd_real(&ac, lowBandReal + LPC_ORDER, autoCorrLength);
    }

    /* Examine dynamic of determinant in autocorrelation. */
    acDetScale += 2 * (comLowBandScale + dynamicScale);
    acDetScale *= 2;            /* two times reflection coefficent scaling */
    acDetScale += ac.det_scale; /* ac scaling of determinant */

    /* In case of determinant < 10^-38, resetLPCCoeffs=1 has to be enforced. */
    if (acDetScale > 126) {
      resetLPCCoeffs = 1;
    }

    alphar[1] = FL2FXCONST_SGL(0.0f);
    if (!useLP) alphai[1] = FL2FXCONST_SGL(0.0f);

    if (ac.det != FL2FXCONST_DBL(0.0f)) {
      FIXP_DBL tmp, absTmp, absDet;

      absDet = fixp_abs(ac.det);

      if (!useLP) {
        tmp = (fMultDiv2(ac.r01r, ac.r12r) >> (LPC_SCALE_FACTOR - 1)) -
              ((fMultDiv2(ac.r01i, ac.r12i) + fMultDiv2(ac.r02r, ac.r11r)) >>
               (LPC_SCALE_FACTOR - 1));
      } else {
        tmp = (fMultDiv2(ac.r01r, ac.r12r) >> (LPC_SCALE_FACTOR - 1)) -
              (fMultDiv2(ac.r02r, ac.r11r) >> (LPC_SCALE_FACTOR - 1));
      }
      absTmp = fixp_abs(tmp);

      /*
        Quick check: is first filter coeff >= 1(4)
       */
      {
        INT scale;
        FIXP_DBL result = fDivNorm(absTmp, absDet, &scale);
        scale = scale + ac.det_scale;

        if ((scale > 0) && (result >= (FIXP_DBL)MAXVAL_DBL >> scale)) {
          resetLPCCoeffs = 1;
        } else {
          alphar[1] = FX_DBL2FX_SGL(scaleValueSaturate(result, scale));
          if ((tmp < FL2FX_DBL(0.0f)) ^ (ac.det < FL2FX_DBL(0.0f))) {
            alphar[1] = -alphar[1];
          }
        }
      }

      if (!useLP) {
        tmp = (fMultDiv2(ac.r01i, ac.r12r) >> (LPC_SCALE_FACTOR - 1)) +
              ((fMultDiv2(ac.r01r, ac.r12i) -
                (FIXP_DBL)fMultDiv2(ac.r02i, ac.r11r)) >>
               (LPC_SCALE_FACTOR - 1));

        absTmp = fixp_abs(tmp);

        /*
        Quick check: is second filter coeff >= 1(4)
        */
        {
          INT scale;
          FIXP_DBL result = fDivNorm(absTmp, absDet, &scale);
          scale = scale + ac.det_scale;

          if ((scale > 0) &&
              (result >= /*FL2FXCONST_DBL(1.f)*/ (FIXP_DBL)MAXVAL_DBL >>
               scale)) {
            resetLPCCoeffs = 1;
          } else {
            alphai[1] = FX_DBL2FX_SGL(scaleValueSaturate(result, scale));
            if ((tmp < FL2FX_DBL(0.0f)) ^ (ac.det < FL2FX_DBL(0.0f))) {
              alphai[1] = -alphai[1];
            }
          }
        }
      }
    }

    alphar[0] = FL2FXCONST_SGL(0.0f);
    if (!useLP) alphai[0] = FL2FXCONST_SGL(0.0f);

    if (ac.r11r != FL2FXCONST_DBL(0.0f)) {
      /* ac.r11r is always >=0 */
      FIXP_DBL tmp, absTmp;

      if (!useLP) {
        tmp = (ac.r01r >> (LPC_SCALE_FACTOR + 1)) +
              (fMultDiv2(alphar[1], ac.r12r) + fMultDiv2(alphai[1], ac.r12i));
      } else {
        if (ac.r01r >= FL2FXCONST_DBL(0.0f))
          tmp = (ac.r01r >> (LPC_SCALE_FACTOR + 1)) +
                fMultDiv2(alphar[1], ac.r12r);
        else
          tmp = -((-ac.r01r) >> (LPC_SCALE_FACTOR + 1)) +
                fMultDiv2(alphar[1], ac.r12r);
      }

      absTmp = fixp_abs(tmp);

      /*
        Quick check: is first filter coeff >= 1(4)
      */

      if (absTmp >= (ac.r11r >> 1)) {
        resetLPCCoeffs = 1;
      } else {
        INT scale;
        FIXP_DBL result = fDivNorm(absTmp, fixp_abs(ac.r11r), &scale);
        alphar[0] = FX_DBL2FX_SGL(scaleValueSaturate(result, scale + 1));

        if ((tmp > FL2FX_DBL(0.0f)) ^ (ac.r11r < FL2FX_DBL(0.0f)))
          alphar[0] = -alphar[0];
      }

      if (!useLP) {
        tmp = (ac.r01i >> (LPC_SCALE_FACTOR + 1)) +
              (fMultDiv2(alphai[1], ac.r12r) - fMultDiv2(alphar[1], ac.r12i));

        absTmp = fixp_abs(tmp);

        /*
        Quick check: is second filter coeff >= 1(4)
        */
        if (absTmp >= (ac.r11r >> 1)) {
          resetLPCCoeffs = 1;
        } else {
          INT scale;
          FIXP_DBL result = fDivNorm(absTmp, fixp_abs(ac.r11r), &scale);
          alphai[0] = FX_DBL2FX_SGL(scaleValueSaturate(result, scale + 1));
          if ((tmp > FL2FX_DBL(0.0f)) ^ (ac.r11r < FL2FX_DBL(0.0f)))
            alphai[0] = -alphai[0];
        }
      }
    }

    if (!useLP) {
      /* Now check the quadratic criteria */
      if ((fMultDiv2(alphar[0], alphar[0]) + fMultDiv2(alphai[0], alphai[0])) >=
          FL2FXCONST_DBL(0.5f))
        resetLPCCoeffs = 1;
      if ((fMultDiv2(alphar[1], alphar[1]) + fMultDiv2(alphai[1], alphai[1])) >=
          FL2FXCONST_DBL(0.5f))
        resetLPCCoeffs = 1;
    }

    if (resetLPCCoeffs) {
      alphar[0] = FL2FXCONST_SGL(0.0f);
      alphar[1] = FL2FXCONST_SGL(0.0f);
      if (!useLP) {
        alphai[0] = FL2FXCONST_SGL(0.0f);
        alphai[1] = FL2FXCONST_SGL(0.0f);
      }
    }

    if (useLP) {
      /* Aliasing detection */
      if (ac.r11r == FL2FXCONST_DBL(0.0f)) {
        k1 = FL2FXCONST_DBL(0.0f);
      } else {
        if (fixp_abs(ac.r01r) >= fixp_abs(ac.r11r)) {
          if (fMultDiv2(ac.r01r, ac.r11r) < FL2FX_DBL(0.0f)) {
            k1 = (FIXP_DBL)MAXVAL_DBL /*FL2FXCONST_SGL(1.0f)*/;
          } else {
            /* Since this value is squared later, it must not ever become -1.0f.
             */
            k1 = (FIXP_DBL)(MINVAL_DBL + 1) /*FL2FXCONST_SGL(-1.0f)*/;
          }
        } else {
          INT scale;
          FIXP_DBL result =
              fDivNorm(fixp_abs(ac.r01r), fixp_abs(ac.r11r), &scale);
          k1 = scaleValueSaturate(result, scale);

          if (!((ac.r01r < FL2FX_DBL(0.0f)) ^ (ac.r11r < FL2FX_DBL(0.0f)))) {
            k1 = -k1;
          }
        }
      }
      if ((loBand > 1) && (loBand < v_k_master0)) {
        /* Check if the gain should be locked */
        FIXP_DBL deg =
            /*FL2FXCONST_DBL(1.0f)*/ (FIXP_DBL)MAXVAL_DBL - fPow2(k1_below);
        degreeAlias[loBand] = FL2FXCONST_DBL(0.0f);
        if (((loBand & 1) == 0) && (k1 < FL2FXCONST_DBL(0.0f))) {
          if (k1_below < FL2FXCONST_DBL(0.0f)) { /* 2-Ch Aliasing Detection */
            degreeAlias[loBand] = (FIXP_DBL)MAXVAL_DBL /*FL2FXCONST_DBL(1.0f)*/;
            if (k1_below2 >
                FL2FXCONST_DBL(0.0f)) { /* 3-Ch Aliasing Detection */
              degreeAlias[loBand - 1] = deg;
            }
          } else if (k1_below2 >
                     FL2FXCONST_DBL(0.0f)) { /* 3-Ch Aliasing Detection */
            degreeAlias[loBand] = deg;
          }
        }
        if (((loBand & 1) == 1) && (k1 > FL2FXCONST_DBL(0.0f))) {
          if (k1_below > FL2FXCONST_DBL(0.0f)) { /* 2-CH Aliasing Detection */
            degreeAlias[loBand] = (FIXP_DBL)MAXVAL_DBL /*FL2FXCONST_DBL(1.0f)*/;
            if (k1_below2 <
                FL2FXCONST_DBL(0.0f)) { /* 3-CH Aliasing Detection */
              degreeAlias[loBand - 1] = deg;
            }
          } else if (k1_below2 <
                     FL2FXCONST_DBL(0.0f)) { /* 3-CH Aliasing Detection */
            degreeAlias[loBand] = deg;
          }
        }
      }
      /* remember k1 values of the 2 QMF channels below the current channel */
      k1_below2 = k1_below;
      k1_below = k1;
    }

    patch = 0;

    while (patch < pSettings->noOfPatches) { /* inner loop over every patch */

      int hiBand = loBand + patchParam[patch].targetBandOffs;

      if (loBand < patchParam[patch].sourceStartBand ||
          loBand >= patchParam[patch].sourceStopBand
          //|| hiBand >= hLppTrans->pSettings->noChannels
      ) {
        /* Lowband not in current patch - proceed */
        patch++;
        continue;
      }

      FDK_ASSERT(hiBand < (64));

      /* bwIndex[patch] is already initialized with value from previous band
       * inside this patch */
      while (hiBand >= pSettings->bwBorders[bwIndex[patch]] &&
             bwIndex[patch] < MAX_NUM_PATCHES - 1) {
        bwIndex[patch]++;
      }

      /*
        Filter Step 2: add the left slope with the current filter to the buffer
                       pure source values are already in there
      */
      bw = FX_DBL2FX_SGL(bwVector[bwIndex[patch]]);

      a0r = FX_DBL2FX_SGL(
          fMult(bw, alphar[0])); /* Apply current bandwidth expansion factor */

      if (!useLP) a0i = FX_DBL2FX_SGL(fMult(bw, alphai[0]));
      bw = FX_DBL2FX_SGL(fPow2(bw));
      a1r = FX_DBL2FX_SGL(fMult(bw, alphar[1]));
      if (!useLP) a1i = FX_DBL2FX_SGL(fMult(bw, alphai[1]));

      /*
        Filter Step 3: insert the middle part which won't be windowed
      */
      if (bw <= FL2FXCONST_SGL(0.0f)) {
        if (!useLP) {
          int descale =
              fixMin(DFRACT_BITS - 1, (LPC_SCALE_FACTOR + dynamicScale));
          for (i = startSample; i < stopSample; i++) {
            FIXP_DBL accu1, accu2;
            accu1 = lowBandReal[LPC_ORDER + i] >> descale;
            accu2 = lowBandImag[LPC_ORDER + i] >> descale;
            if (fPreWhitening) {
              accu1 = scaleValueSaturate(
                  fMultDiv2(accu1, preWhiteningGains[loBand]),
                  preWhiteningGains_exp[loBand] + 1);
              accu2 = scaleValueSaturate(
                  fMultDiv2(accu2, preWhiteningGains[loBand]),
                  preWhiteningGains_exp[loBand] + 1);
            }
            qmfBufferReal[i][hiBand] = accu1;
            qmfBufferImag[i][hiBand] = accu2;
          }
        } else {
          int descale =
              fixMin(DFRACT_BITS - 1, (LPC_SCALE_FACTOR + dynamicScale));
          for (i = startSample; i < stopSample; i++) {
            qmfBufferReal[i][hiBand] = lowBandReal[LPC_ORDER + i] >> descale;
          }
        }
      } else { /* bw <= 0 */

        if (!useLP) {
          const int dynscale = fixMax(0, dynamicScale - 2) + 1;
          const int rescale = -fixMin(0, dynamicScale - 2) + 1;
          const int descale = fixMin(DFRACT_BITS - 1,
                                     LPC_SCALE_FACTOR + dynamicScale + rescale);

          for (i = startSample; i < stopSample; i++) {
            FIXP_DBL accu1, accu2;

            accu1 = ((fMultDiv2(a0r, lowBandReal[LPC_ORDER + i - 1]) -
                      fMultDiv2(a0i, lowBandImag[LPC_ORDER + i - 1])) >>
                     1) +
                    ((fMultDiv2(a1r, lowBandReal[LPC_ORDER + i - 2]) -
                      fMultDiv2(a1i, lowBandImag[LPC_ORDER + i - 2])) >>
                     1);
            accu2 = ((fMultDiv2(a0i, lowBandReal[LPC_ORDER + i - 1]) +
                      fMultDiv2(a0r, lowBandImag[LPC_ORDER + i - 1])) >>
                     1) +
                    ((fMultDiv2(a1i, lowBandReal[LPC_ORDER + i - 2]) +
                      fMultDiv2(a1r, lowBandImag[LPC_ORDER + i - 2])) >>
                     1);

            accu1 =
                (lowBandReal[LPC_ORDER + i] >> descale) + (accu1 >> dynscale);
            accu2 =
                (lowBandImag[LPC_ORDER + i] >> descale) + (accu2 >> dynscale);
            if (fPreWhitening) {
              qmfBufferReal[i][hiBand] = scaleValueSaturate(
                  fMultDiv2(accu1, preWhiteningGains[loBand]),
                  preWhiteningGains_exp[loBand] + 1 + rescale);
              qmfBufferImag[i][hiBand] = scaleValueSaturate(
                  fMultDiv2(accu2, preWhiteningGains[loBand]),
                  preWhiteningGains_exp[loBand] + 1 + rescale);
            } else {
              qmfBufferReal[i][hiBand] =
                  SATURATE_LEFT_SHIFT(accu1, rescale, DFRACT_BITS);
              qmfBufferImag[i][hiBand] =
                  SATURATE_LEFT_SHIFT(accu2, rescale, DFRACT_BITS);
            }
          }
        } else {
          FDK_ASSERT(dynamicScale >= 0);
          calc_qmfBufferReal(
              qmfBufferReal, &(lowBandReal[LPC_ORDER + startSample - 2]),
              startSample, stopSample, hiBand, dynamicScale, a0r, a1r);
        }
      } /* bw <= 0 */

      patch++;

    } /* inner loop over patches */

    /*
     * store the unmodified filter coefficients if there is
     * an overlapping envelope
     *****************************************************************/

  } /* outer loop over bands (loBand) */

  if (useLP) {
    for (loBand = pSettings->lbStartPatching;
         loBand < pSettings->lbStopPatching; loBand++) {
      patch = 0;
      while (patch < pSettings->noOfPatches) {
        UCHAR hiBand = loBand + patchParam[patch].targetBandOffs;

        if (loBand < patchParam[patch].sourceStartBand ||
            loBand >= patchParam[patch].sourceStopBand ||
            hiBand >= (64) /* Highband out of range (biterror) */
        ) {
          /* Lowband not in current patch or highband out of range (might be
           * caused by biterrors)- proceed */
          patch++;
          continue;
        }

        if (hiBand != patchParam[patch].targetStartBand)
          degreeAlias[hiBand] = degreeAlias[loBand];

        patch++;
      }
    } /* end  for loop */
  }

  for (i = 0; i < nInvfBands; i++) {
    hLppTrans->bwVectorOld[i] = bwVector[i];
  }

  /*
    set high band scale factor
  */
  sbrScaleFactor->hb_scale = comLowBandScale - (LPC_SCALE_FACTOR);
}

void lppTransposerHBE(
    HANDLE_SBR_LPP_TRANS hLppTrans, /*!< Handle of lpp transposer  */
    HANDLE_HBE_TRANSPOSER hQmfTransposer,
    QMF_SCALE_FACTOR *sbrScaleFactor, /*!< Scaling factors */
    FIXP_DBL **qmfBufferReal, /*!< Pointer to pointer to real part of subband
                                 samples (source) */
    FIXP_DBL **qmfBufferImag, /*!< Pointer to pointer to imaginary part of
                                 subband samples (source) */
    const int timeStep,       /*!< Time step of envelope */
    const int firstSlotOffs,  /*!< Start position in time */
    const int lastSlotOffs,   /*!< Number of overlap-slots into next frame */
    const int nInvfBands,     /*!< Number of bands for inverse filtering */
    INVF_MODE *sbr_invf_mode, /*!< Current inverse filtering modes */
    INVF_MODE *sbr_invf_mode_prev /*!< Previous inverse filtering modes */
) {
  INT bwIndex;
  FIXP_DBL bwVector[MAX_NUM_PATCHES_HBE]; /*!< pole moving factors */

  int i;
  int loBand, start, stop;
  TRANSPOSER_SETTINGS *pSettings = hLppTrans->pSettings;
  PATCH_PARAM *patchParam = pSettings->patchParam;

  FIXP_SGL alphar[LPC_ORDER], a0r, a1r;
  FIXP_SGL alphai[LPC_ORDER], a0i = 0, a1i = 0;
  FIXP_SGL bw = FL2FXCONST_SGL(0.0f);

  int autoCorrLength;

  ACORR_COEFS ac;
  int startSample;
  int stopSample;
  int stopSampleClear;

  int comBandScale;
  int ovLowBandShift;
  int lowBandShift;
  /*  int ovHighBandShift;*/

  alphai[0] = FL2FXCONST_SGL(0.0f);
  alphai[1] = FL2FXCONST_SGL(0.0f);

  startSample = firstSlotOffs * timeStep;
  stopSample = pSettings->nCols + lastSlotOffs * timeStep;

  inverseFilteringLevelEmphasis(hLppTrans, nInvfBands, sbr_invf_mode,
                                sbr_invf_mode_prev, bwVector);

  stopSampleClear = stopSample;

  autoCorrLength = pSettings->nCols + pSettings->overlap;

  if (pSettings->noOfPatches > 0) {
    /* Set upper subbands to zero:
       This is required in case that the patches do not cover the complete
       highband (because the last patch would be too short). Possible
       optimization: Clearing bands up to usb would be sufficient here. */
    int targetStopBand =
        patchParam[pSettings->noOfPatches - 1].targetStartBand +
        patchParam[pSettings->noOfPatches - 1].numBandsInPatch;

    int memSize = ((64) - targetStopBand) * sizeof(FIXP_DBL);

    for (i = startSample; i < stopSampleClear; i++) {
      FDKmemclear(&qmfBufferReal[i][targetStopBand], memSize);
      FDKmemclear(&qmfBufferImag[i][targetStopBand], memSize);
    }
  }
#ifdef __ANDROID__
  else {
    // Safetynet logging
    android_errorWriteLog(0x534e4554, "112160868");
  }
#endif

  /*
  Calc common low band scale factor
  */
  comBandScale = sbrScaleFactor->hb_scale;

  ovLowBandShift = sbrScaleFactor->hb_scale - comBandScale;
  lowBandShift = sbrScaleFactor->hb_scale - comBandScale;
  /*  ovHighBandShift = firstSlotOffs == 0 ? ovLowBandShift:0;*/

  /* outer loop over bands to do analysis only once for each band */

  start = hQmfTransposer->startBand;
  stop = hQmfTransposer->stopBand;

  for (loBand = start; loBand < stop; loBand++) {
    bwIndex = 0;

    FIXP_DBL lowBandReal[(((1024) / (32) * (4) / 2) + (3 * (4))) + LPC_ORDER];
    FIXP_DBL lowBandImag[(((1024) / (32) * (4) / 2) + (3 * (4))) + LPC_ORDER];

    int resetLPCCoeffs = 0;
    int dynamicScale = DFRACT_BITS - 1 - LPC_SCALE_FACTOR;
    int acDetScale = 0; /* scaling of autocorrelation determinant */

    for (i = 0; i < LPC_ORDER; i++) {
      lowBandReal[i] = hLppTrans->lpcFilterStatesRealHBE[i][loBand];
      lowBandImag[i] = hLppTrans->lpcFilterStatesImagHBE[i][loBand];
    }

    for (; i < LPC_ORDER + firstSlotOffs * timeStep; i++) {
      lowBandReal[i] = hLppTrans->lpcFilterStatesRealHBE[i][loBand];
      lowBandImag[i] = hLppTrans->lpcFilterStatesImagHBE[i][loBand];
    }

    /*
    Take old slope length qmf slot source values out of (overlap)qmf buffer
    */
    for (i = firstSlotOffs * timeStep;
         i < pSettings->nCols + pSettings->overlap; i++) {
      lowBandReal[i + LPC_ORDER] = qmfBufferReal[i][loBand];
      lowBandImag[i + LPC_ORDER] = qmfBufferImag[i][loBand];
    }

    /* store unmodified values to buffer */
    for (i = 0; i < LPC_ORDER + pSettings->overlap; i++) {
      hLppTrans->lpcFilterStatesRealHBE[i][loBand] =
          qmfBufferReal[pSettings->nCols - LPC_ORDER + i][loBand];
      hLppTrans->lpcFilterStatesImagHBE[i][loBand] =
          qmfBufferImag[pSettings->nCols - LPC_ORDER + i][loBand];
    }

    /*
    Determine dynamic scaling value.
    */
    dynamicScale =
        fixMin(dynamicScale,
               getScalefactor(lowBandReal, LPC_ORDER + pSettings->overlap) +
                   ovLowBandShift);
    dynamicScale =
        fixMin(dynamicScale,
               getScalefactor(&lowBandReal[LPC_ORDER + pSettings->overlap],
                              pSettings->nCols) +
                   lowBandShift);
    dynamicScale =
        fixMin(dynamicScale,
               getScalefactor(lowBandImag, LPC_ORDER + pSettings->overlap) +
                   ovLowBandShift);
    dynamicScale =
        fixMin(dynamicScale,
               getScalefactor(&lowBandImag[LPC_ORDER + pSettings->overlap],
                              pSettings->nCols) +
                   lowBandShift);

    dynamicScale =
        dynamicScale - 1; /* one additional bit headroom to prevent -1.0 */

    /*
    Scale temporal QMF buffer.
    */
    scaleValues(&lowBandReal[0], LPC_ORDER + pSettings->overlap,
                dynamicScale - ovLowBandShift);
    scaleValues(&lowBandReal[LPC_ORDER + pSettings->overlap], pSettings->nCols,
                dynamicScale - lowBandShift);
    scaleValues(&lowBandImag[0], LPC_ORDER + pSettings->overlap,
                dynamicScale - ovLowBandShift);
    scaleValues(&lowBandImag[LPC_ORDER + pSettings->overlap], pSettings->nCols,
                dynamicScale - lowBandShift);

    acDetScale += autoCorr2nd_cplx(&ac, lowBandReal + LPC_ORDER,
                                   lowBandImag + LPC_ORDER, autoCorrLength);

    /* Examine dynamic of determinant in autocorrelation. */
    acDetScale += 2 * (comBandScale + dynamicScale);
    acDetScale *= 2;            /* two times reflection coefficent scaling */
    acDetScale += ac.det_scale; /* ac scaling of determinant */

    /* In case of determinant < 10^-38, resetLPCCoeffs=1 has to be enforced. */
    if (acDetScale > 126) {
      resetLPCCoeffs = 1;
    }

    alphar[1] = FL2FXCONST_SGL(0.0f);
    alphai[1] = FL2FXCONST_SGL(0.0f);

    if (ac.det != FL2FXCONST_DBL(0.0f)) {
      FIXP_DBL tmp, absTmp, absDet;

      absDet = fixp_abs(ac.det);

      tmp = (fMultDiv2(ac.r01r, ac.r12r) >> (LPC_SCALE_FACTOR - 1)) -
            ((fMultDiv2(ac.r01i, ac.r12i) + fMultDiv2(ac.r02r, ac.r11r)) >>
             (LPC_SCALE_FACTOR - 1));
      absTmp = fixp_abs(tmp);

      /*
      Quick check: is first filter coeff >= 1(4)
      */
      {
        INT scale;
        FIXP_DBL result = fDivNorm(absTmp, absDet, &scale);
        scale = scale + ac.det_scale;

        if ((scale > 0) && (result >= (FIXP_DBL)MAXVAL_DBL >> scale)) {
          resetLPCCoeffs = 1;
        } else {
          alphar[1] = FX_DBL2FX_SGL(scaleValueSaturate(result, scale));
          if ((tmp < FL2FX_DBL(0.0f)) ^ (ac.det < FL2FX_DBL(0.0f))) {
            alphar[1] = -alphar[1];
          }
        }
      }

      tmp = (fMultDiv2(ac.r01i, ac.r12r) >> (LPC_SCALE_FACTOR - 1)) +
            ((fMultDiv2(ac.r01r, ac.r12i) -
              (FIXP_DBL)fMultDiv2(ac.r02i, ac.r11r)) >>
             (LPC_SCALE_FACTOR - 1));

      absTmp = fixp_abs(tmp);

      /*
      Quick check: is second filter coeff >= 1(4)
      */
      {
        INT scale;
        FIXP_DBL result = fDivNorm(absTmp, absDet, &scale);
        scale = scale + ac.det_scale;

        if ((scale > 0) &&
            (result >= /*FL2FXCONST_DBL(1.f)*/ (FIXP_DBL)MAXVAL_DBL >> scale)) {
          resetLPCCoeffs = 1;
        } else {
          alphai[1] = FX_DBL2FX_SGL(scaleValueSaturate(result, scale));
          if ((tmp < FL2FX_DBL(0.0f)) ^ (ac.det < FL2FX_DBL(0.0f))) {
            alphai[1] = -alphai[1];
          }
        }
      }
    }

    alphar[0] = FL2FXCONST_SGL(0.0f);
    alphai[0] = FL2FXCONST_SGL(0.0f);

    if (ac.r11r != FL2FXCONST_DBL(0.0f)) {
      /* ac.r11r is always >=0 */
      FIXP_DBL tmp, absTmp;

      tmp = (ac.r01r >> (LPC_SCALE_FACTOR + 1)) +
            (fMultDiv2(alphar[1], ac.r12r) + fMultDiv2(alphai[1], ac.r12i));

      absTmp = fixp_abs(tmp);

      /*
      Quick check: is first filter coeff >= 1(4)
      */

      if (absTmp >= (ac.r11r >> 1)) {
        resetLPCCoeffs = 1;
      } else {
        INT scale;
        FIXP_DBL result = fDivNorm(absTmp, fixp_abs(ac.r11r), &scale);
        alphar[0] = FX_DBL2FX_SGL(scaleValueSaturate(result, scale + 1));

        if ((tmp > FL2FX_DBL(0.0f)) ^ (ac.r11r < FL2FX_DBL(0.0f)))
          alphar[0] = -alphar[0];
      }

      tmp = (ac.r01i >> (LPC_SCALE_FACTOR + 1)) +
            (fMultDiv2(alphai[1], ac.r12r) - fMultDiv2(alphar[1], ac.r12i));

      absTmp = fixp_abs(tmp);

      /*
      Quick check: is second filter coeff >= 1(4)
      */
      if (absTmp >= (ac.r11r >> 1)) {
        resetLPCCoeffs = 1;
      } else {
        INT scale;
        FIXP_DBL result = fDivNorm(absTmp, fixp_abs(ac.r11r), &scale);
        alphai[0] = FX_DBL2FX_SGL(scaleValueSaturate(result, scale + 1));
        if ((tmp > FL2FX_DBL(0.0f)) ^ (ac.r11r < FL2FX_DBL(0.0f))) {
          alphai[0] = -alphai[0];
        }
      }
    }

    /* Now check the quadratic criteria */
    if ((fMultDiv2(alphar[0], alphar[0]) + fMultDiv2(alphai[0], alphai[0])) >=
        FL2FXCONST_DBL(0.5f)) {
      resetLPCCoeffs = 1;
    }
    if ((fMultDiv2(alphar[1], alphar[1]) + fMultDiv2(alphai[1], alphai[1])) >=
        FL2FXCONST_DBL(0.5f)) {
      resetLPCCoeffs = 1;
    }

    if (resetLPCCoeffs) {
      alphar[0] = FL2FXCONST_SGL(0.0f);
      alphar[1] = FL2FXCONST_SGL(0.0f);
      alphai[0] = FL2FXCONST_SGL(0.0f);
      alphai[1] = FL2FXCONST_SGL(0.0f);
    }

    while (bwIndex < MAX_NUM_PATCHES - 1 &&
           loBand >= pSettings->bwBorders[bwIndex]) {
      bwIndex++;
    }

    /*
    Filter Step 2: add the left slope with the current filter to the buffer
    pure source values are already in there
    */
    bw = FX_DBL2FX_SGL(bwVector[bwIndex]);

    a0r = FX_DBL2FX_SGL(
        fMult(bw, alphar[0])); /* Apply current bandwidth expansion factor */
    a0i = FX_DBL2FX_SGL(fMult(bw, alphai[0]));
    bw = FX_DBL2FX_SGL(fPow2(bw));
    a1r = FX_DBL2FX_SGL(fMult(bw, alphar[1]));
    a1i = FX_DBL2FX_SGL(fMult(bw, alphai[1]));

    /*
    Filter Step 3: insert the middle part which won't be windowed
    */
    if (bw <= FL2FXCONST_SGL(0.0f)) {
      int descale = fixMin(DFRACT_BITS - 1, (LPC_SCALE_FACTOR + dynamicScale));
      for (i = startSample; i < stopSample; i++) {
        qmfBufferReal[i][loBand] = lowBandReal[LPC_ORDER + i] >> descale;
        qmfBufferImag[i][loBand] = lowBandImag[LPC_ORDER + i] >> descale;
      }
    } else { /* bw <= 0 */

      int descale = fixMin(DFRACT_BITS - 1, (LPC_SCALE_FACTOR + dynamicScale));
      dynamicScale +=
          1; /* prevent negativ scale factor due to 'one additional bit
                headroom' */

      for (i = startSample; i < stopSample; i++) {
        FIXP_DBL accu1, accu2;

        accu1 = (fMultDiv2(a0r, lowBandReal[LPC_ORDER + i - 1]) -
                 fMultDiv2(a0i, lowBandImag[LPC_ORDER + i - 1]) +
                 fMultDiv2(a1r, lowBandReal[LPC_ORDER + i - 2]) -
                 fMultDiv2(a1i, lowBandImag[LPC_ORDER + i - 2])) >>
                dynamicScale;
        accu2 = (fMultDiv2(a0i, lowBandReal[LPC_ORDER + i - 1]) +
                 fMultDiv2(a0r, lowBandImag[LPC_ORDER + i - 1]) +
                 fMultDiv2(a1i, lowBandReal[LPC_ORDER + i - 2]) +
                 fMultDiv2(a1r, lowBandImag[LPC_ORDER + i - 2])) >>
                dynamicScale;

        qmfBufferReal[i][loBand] =
            (lowBandReal[LPC_ORDER + i] >> descale) + (accu1 << (1 + 1));
        qmfBufferImag[i][loBand] =
            (lowBandImag[LPC_ORDER + i] >> descale) + (accu2 << (1 + 1));
      }
    } /* bw <= 0 */

    /*
     * store the unmodified filter coefficients if there is
     * an overlapping envelope
     *****************************************************************/

  } /* outer loop over bands (loBand) */

  for (i = 0; i < nInvfBands; i++) {
    hLppTrans->bwVectorOld[i] = bwVector[i];
  }

  /*
  set high band scale factor
  */
  sbrScaleFactor->hb_scale = comBandScale - (LPC_SCALE_FACTOR);
}

/*!
 *
 * \brief Initialize one low power transposer instance
 *
 *
 */
SBR_ERROR
createLppTransposer(
    HANDLE_SBR_LPP_TRANS hs,        /*!< Handle of low power transposer  */
    TRANSPOSER_SETTINGS *pSettings, /*!< Pointer to settings */
    const int highBandStartSb,      /*!< ? */
    UCHAR *v_k_master,              /*!< Master table */
    const int numMaster,            /*!< Valid entries in master table */
    const int usb,                  /*!< Highband area stop subband */
    const int timeSlots,            /*!< Number of time slots */
    const int nCols,                /*!< Number of colums (codec qmf bank) */
    UCHAR *noiseBandTable,  /*!< Mapping of SBR noise bands to QMF bands */
    const int noNoiseBands, /*!< Number of noise bands */
    UINT fs,                /*!< Sample Frequency */
    const int chan,         /*!< Channel number */
    const int overlap) {
  /* FB inverse filtering settings */
  hs->pSettings = pSettings;

  pSettings->nCols = nCols;
  pSettings->overlap = overlap;

  switch (timeSlots) {
    case 15:
    case 16:
      break;

    default:
      return SBRDEC_UNSUPPORTED_CONFIG; /* Unimplemented */
  }

  if (chan == 0) {
    /* Init common data only once */
    hs->pSettings->nCols = nCols;

    return resetLppTransposer(hs, highBandStartSb, v_k_master, numMaster,
                              noiseBandTable, noNoiseBands, usb, fs);
  }
  return SBRDEC_OK;
}

static int findClosestEntry(UCHAR goalSb, UCHAR *v_k_master, UCHAR numMaster,
                            UCHAR direction) {
  int index;

  if (goalSb <= v_k_master[0]) return v_k_master[0];

  if (goalSb >= v_k_master[numMaster]) return v_k_master[numMaster];

  if (direction) {
    index = 0;
    while (v_k_master[index] < goalSb) {
      index++;
    }
  } else {
    index = numMaster;
    while (v_k_master[index] > goalSb) {
      index--;
    }
  }

  return v_k_master[index];
}

/*!
 *
 * \brief Reset memory for one lpp transposer instance
 *
 * \return SBRDEC_OK on success, SBRDEC_UNSUPPORTED_CONFIG on error
 */
SBR_ERROR
resetLppTransposer(
    HANDLE_SBR_LPP_TRANS hLppTrans, /*!< Handle of lpp transposer  */
    UCHAR highBandStartSb,          /*!< High band area: start subband */
    UCHAR *v_k_master,              /*!< Master table */
    UCHAR numMaster,                /*!< Valid entries in master table */
    UCHAR *noiseBandTable, /*!< Mapping of SBR noise bands to QMF bands */
    UCHAR noNoiseBands,    /*!< Number of noise bands */
    UCHAR usb,             /*!< High band area: stop subband */
    UINT fs                /*!< SBR output sampling frequency */
) {
  TRANSPOSER_SETTINGS *pSettings = hLppTrans->pSettings;
  PATCH_PARAM *patchParam = pSettings->patchParam;

  int i, patch;
  int targetStopBand;
  int sourceStartBand;
  int patchDistance;
  int numBandsInPatch;

  int lsb = v_k_master[0]; /* Start subband expressed in "non-critical" sampling
                              terms*/
  int xoverOffset = highBandStartSb -
                    lsb; /* Calculate distance in QMF bands between k0 and kx */
  int startFreqHz;

  int desiredBorder;

  usb = fixMin(usb, v_k_master[numMaster]); /* Avoid endless loops (compare with
                                               float code). */

  /*
   * Plausibility check
   */

  if (pSettings->nCols == 64) {
    if (lsb < 4) {
      /* 4:1 SBR Requirement k0 >= 4 missed! */
      return SBRDEC_UNSUPPORTED_CONFIG;
    }
  } else if (lsb - SHIFT_START_SB < 4) {
    return SBRDEC_UNSUPPORTED_CONFIG;
  }

  /*
   * Initialize the patching parameter
   */
  /* ISO/IEC 14496-3 (Figure 4.48): goalSb = round( 2.048e6 / fs ) */
  desiredBorder = (((2048000 * 2) / fs) + 1) >> 1;

  desiredBorder = findClosestEntry(desiredBorder, v_k_master, numMaster,
                                   1); /* Adapt region to master-table */

  /* First patch */
  sourceStartBand = SHIFT_START_SB + xoverOffset;
  targetStopBand = lsb + xoverOffset; /* upperBand */

  /* Even (odd) numbered channel must be patched to even (odd) numbered channel
   */
  patch = 0;
  while (targetStopBand < usb) {
    /* Too many patches?
       Allow MAX_NUM_PATCHES+1 patches here.
       we need to check later again, since patch might be the highest patch
       AND contain less than 3 bands => actual number of patches will be reduced
       by 1.
    */
    if (patch > MAX_NUM_PATCHES) {
      return SBRDEC_UNSUPPORTED_CONFIG;
    }

    patchParam[patch].guardStartBand = targetStopBand;
    patchParam[patch].targetStartBand = targetStopBand;

    numBandsInPatch =
        desiredBorder - targetStopBand; /* Get the desired range of the patch */

    if (numBandsInPatch >= lsb - sourceStartBand) {
      /* Desired number bands are not available -> patch whole source range */
      patchDistance =
          targetStopBand - sourceStartBand; /* Get the targetOffset */
      patchDistance =
          patchDistance & ~1; /* Rounding off odd numbers and make all even */
      numBandsInPatch =
          lsb - (targetStopBand -
                 patchDistance); /* Update number of bands to be patched */
      numBandsInPatch = findClosestEntry(targetStopBand + numBandsInPatch,
                                         v_k_master, numMaster, 0) -
                        targetStopBand; /* Adapt region to master-table */
    }

    if (pSettings->nCols == 64) {
      if (numBandsInPatch == 0 && sourceStartBand == SHIFT_START_SB) {
        return SBRDEC_UNSUPPORTED_CONFIG;
      }
    }

    /* Desired number bands are available -> get the minimal even patching
     * distance */
    patchDistance =
        numBandsInPatch + targetStopBand - lsb; /* Get minimal distance */
    patchDistance = (patchDistance + 1) &
                    ~1; /* Rounding up odd numbers and make all even */

    if (numBandsInPatch > 0) {
      patchParam[patch].sourceStartBand = targetStopBand - patchDistance;
      patchParam[patch].targetBandOffs = patchDistance;
      patchParam[patch].numBandsInPatch = numBandsInPatch;
      patchParam[patch].sourceStopBand =
          patchParam[patch].sourceStartBand + numBandsInPatch;

      targetStopBand += patchParam[patch].numBandsInPatch;
      patch++;
    }

    /* All patches but first */
    sourceStartBand = SHIFT_START_SB;

    /* Check if we are close to desiredBorder */
    if (desiredBorder - targetStopBand < 3) /* MPEG doc */
    {
      desiredBorder = usb;
    }
  }

  patch--;

  /* If highest patch contains less than three subband: skip it */
  if ((patch > 0) && (patchParam[patch].numBandsInPatch < 3)) {
    patch--;
    targetStopBand =
        patchParam[patch].targetStartBand + patchParam[patch].numBandsInPatch;
  }

  /* now check if we don't have one too many */
  if (patch >= MAX_NUM_PATCHES) {
    return SBRDEC_UNSUPPORTED_CONFIG;
  }

  pSettings->noOfPatches = patch + 1;

  /* Check lowest and highest source subband */
  pSettings->lbStartPatching = targetStopBand;
  pSettings->lbStopPatching = 0;
  for (patch = 0; patch < pSettings->noOfPatches; patch++) {
    pSettings->lbStartPatching =
        fixMin(pSettings->lbStartPatching, patchParam[patch].sourceStartBand);
    pSettings->lbStopPatching =
        fixMax(pSettings->lbStopPatching, patchParam[patch].sourceStopBand);
  }

  for (i = 0; i < noNoiseBands; i++) {
    pSettings->bwBorders[i] = noiseBandTable[i + 1];
  }
  for (; i < MAX_NUM_NOISE_VALUES; i++) {
    pSettings->bwBorders[i] = 255;
  }

  /*
   * Choose whitening factors
   */

  startFreqHz =
      ((lsb + xoverOffset) * fs) >> 7; /* Shift does a division by 2*(64) */

  for (i = 1; i < NUM_WHFACTOR_TABLE_ENTRIES; i++) {
    if (startFreqHz < FDK_sbrDecoder_sbr_whFactorsIndex[i]) break;
  }
  i--;

  pSettings->whFactors.off = FDK_sbrDecoder_sbr_whFactorsTable[i][0];
  pSettings->whFactors.transitionLevel =
      FDK_sbrDecoder_sbr_whFactorsTable[i][1];
  pSettings->whFactors.lowLevel = FDK_sbrDecoder_sbr_whFactorsTable[i][2];
  pSettings->whFactors.midLevel = FDK_sbrDecoder_sbr_whFactorsTable[i][3];
  pSettings->whFactors.highLevel = FDK_sbrDecoder_sbr_whFactorsTable[i][4];

  return SBRDEC_OK;
}