oxideav-opus 0.0.12

Opus audio codec — orphan-rebuild scaffold pending clean-room re-implementation.
Documentation
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
//! SILK Long-Term Prediction (LTP) parameters — RFC 6716 §4.2.7.6.
//!
//! After the normalized LSF indices (and, for 20 ms frames, the LSF
//! interpolation index), **voiced** SILK frames (see §4.2.7.3) carry the
//! long-term-prediction parameters that drive the pitch filter:
//!
//!  * **§4.2.7.6.1 Pitch lags.** One primary pitch lag per SILK frame —
//!    coded either as an absolute value (a high part from the Table 29
//!    32-entry codebook plus a bandwidth-dependent low part from Table 30)
//!    or relative to the prior frame's lag (a Table 31 delta, where a
//!    decoded value of zero falls back to absolute coding). A "pitch
//!    contour" VQ index (Table 32 PDF; Tables 33–36 codebooks) then
//!    refines the primary lag into a separate lag per subframe, clamped to
//!    the bandwidth's `[lag_min, lag_max]`.
//!  * **§4.2.7.6.2 LTP filter coefficients.** A single 3-entry
//!    "periodicity index" (Table 37) selects one of three codebooks for
//!    the whole SILK frame; then each subframe reads a filter index from
//!    the periodicity-conditioned Table 38 PDF, yielding a 5-tap Q7 filter
//!    from Tables 39–41.
//!  * **§4.2.7.6.3 LTP scaling.** An optional Q14 scale factor (Table 42).
//!    When present it is one of `{15565, 12288, 8192}`; when absent the
//!    default `15565` (≈0.95) is used.
//!
//! This module decodes all three subsections behind [`LtpParameters`] and
//! its [`LtpConfig`]. It does **not** run the §4.2.7.9 LTP synthesis
//! filter — it only produces the decoded parameters that feed it.
//!
//! All truth is taken from RFC 6716 §4.2.7.6 (Tables 29–42); no external
//! library source is consulted.

use crate::range_decoder::RangeDecoder;
use crate::silk_frame::SignalType;
use crate::toc::Bandwidth;
use crate::Error;

/// Maximum subframes in a SILK frame (4 for 20 ms / Hybrid; 2 for 10 ms).
pub const LTP_MAX_SUBFRAMES: usize = 4;

/// Number of taps in a SILK LTP pitch filter (§4.2.7.6.2).
pub const LTP_FILTER_TAPS: usize = 5;

// =====================================================================
// Table 29 — PDF for the high part of the absolute primary pitch lag.
//
// {3, 3, 6, 11, 21, 30, 32, 19, 11, 10, 12, 13, 13, 12, 11, 9, 8, 7, 6,
//  4, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1}/256  (32 entries)
//
// Stored as the §4.1.3.3 inverse-CDF form (terminated by 0).
// =====================================================================
const LAG_HIGH_ICDF: &[u8] = &[
    253, 250, 244, 233, 212, 182, 150, 131, 120, 110, 98, 85, 72, 60, 49, 40, 32, 25, 19, 15, 13,
    11, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0,
];

// =====================================================================
// Table 30 — PDF + scale + lag range for the low part of the absolute
// primary pitch lag, per audio bandwidth.
// =====================================================================
const LAG_LOW_ICDF_NB: &[u8] = &[192, 128, 64, 0]; // {64,64,64,64}
const LAG_LOW_ICDF_MB: &[u8] = &[213, 171, 128, 85, 43, 0]; // {43,42,43,43,42,43}
const LAG_LOW_ICDF_WB: &[u8] = &[224, 192, 160, 128, 96, 64, 32, 0]; // eight 32s

// =====================================================================
// Table 31 — PDF for the relative (delta) primary pitch lag.
//
// {46, 2, 2, 3, 4, 6, 10, 15, 26, 38, 30, 22, 15, 10, 7, 6, 4, 4, 2, 2,
//  2}/256  (21 entries)
// =====================================================================
const LAG_DELTA_ICDF: &[u8] = &[
    210, 208, 206, 203, 199, 193, 183, 168, 142, 104, 74, 52, 37, 27, 20, 14, 10, 6, 4, 2, 0,
];

// =====================================================================
// Table 32 — PDFs for the subframe pitch-contour VQ index, selected by
// (bandwidth, SILK frame size).
// =====================================================================
const CONTOUR_ICDF_NB_10MS: &[u8] = &[113, 63, 0]; // {143,50,63}
const CONTOUR_ICDF_NB_20MS: &[u8] = &[
    // {68,12,21,17,19,22,30,24,17,16,10}/256
    188, 176, 155, 138, 119, 97, 67, 43, 26, 10, 0,
];
const CONTOUR_ICDF_MBWB_10MS: &[u8] = &[
    // {91,46,39,19,14,12,8,7,6,5,5,4}/256
    165, 119, 80, 61, 47, 35, 27, 20, 14, 9, 4, 0,
];
const CONTOUR_ICDF_MBWB_20MS: &[u8] = &[
    // {33,22,18,16,15,14,14,13,13,10,9,9,8,6,6,6,5,4,4,4,3,3,3,2,2,2,2,2,
    //  2,2,1,1,1,1}/256
    223, 201, 183, 167, 152, 138, 124, 111, 98, 88, 79, 70, 62, 56, 50, 44, 39, 35, 31, 27, 24, 21,
    18, 16, 14, 12, 10, 8, 6, 4, 3, 2, 1, 0,
];

// =====================================================================
// Tables 33–36 — pitch-contour codebooks. lag_cb[contour_index][k] is
// the offset added to the primary lag for subframe k.
// =====================================================================
const CONTOUR_NB_10MS: &[[i8; 2]; 3] = &[[0, 0], [1, 0], [0, 1]];

const CONTOUR_NB_20MS: &[[i8; 4]; 11] = &[
    [0, 0, 0, 0],
    [2, 1, 0, -1],
    [-1, 0, 1, 2],
    [-1, 0, 0, 1],
    [-1, 0, 0, 0],
    [0, 0, 0, 1],
    [0, 0, 1, 1],
    [1, 1, 0, 0],
    [1, 0, 0, 0],
    [0, 0, 0, -1],
    [1, 0, 0, -1],
];

const CONTOUR_MBWB_10MS: &[[i8; 2]; 12] = &[
    [0, 0],
    [0, 1],
    [1, 0],
    [-1, 1],
    [1, -1],
    [-1, 2],
    [2, -1],
    [-2, 2],
    [2, -2],
    [-2, 3],
    [3, -2],
    [-3, 3],
];

const CONTOUR_MBWB_20MS: &[[i8; 4]; 34] = &[
    [0, 0, 0, 0],
    [0, 0, 1, 1],
    [1, 1, 0, 0],
    [-1, 0, 0, 0],
    [0, 0, 0, 1],
    [1, 0, 0, 0],
    [-1, 0, 0, 1],
    [0, 0, 0, -1],
    [-1, 0, 1, 2],
    [1, 0, 0, -1],
    [-2, -1, 1, 2],
    [2, 1, 0, -1],
    [-2, 0, 0, 2],
    [-2, 0, 1, 3],
    [2, 1, -1, -2],
    [-3, -1, 1, 3],
    [2, 0, 0, -2],
    [3, 1, 0, -2],
    [-3, -1, 2, 4],
    [-4, -1, 1, 4],
    [3, 1, -1, -3],
    [-4, -1, 2, 5],
    [4, 2, -1, -3],
    [4, 1, -1, -4],
    [-5, -1, 2, 6],
    [5, 2, -1, -4],
    [-6, -2, 2, 6],
    [-5, -2, 2, 5],
    [6, 2, -1, -5],
    [-7, -2, 3, 8],
    [6, 2, -2, -6],
    [5, 2, -2, -5],
    [8, 3, -2, -7],
    [-9, -3, 3, 9],
];

// =====================================================================
// Table 37 — periodicity-index PDF: {77, 80, 99}/256.
// =====================================================================
const PERIODICITY_ICDF: &[u8] = &[179, 99, 0];

// =====================================================================
// Table 38 — LTP filter-index PDFs, selected by periodicity index.
// =====================================================================
const LTP_FILTER_ICDF_P0: &[u8] = &[
    // {185,15,13,13,9,9,6,6}/256
    71, 56, 43, 30, 21, 12, 6, 0,
];
const LTP_FILTER_ICDF_P1: &[u8] = &[
    // {57,34,21,20,15,13,12,13,10,10,9,10,9,8,7,8}/256
    199, 165, 144, 124, 109, 96, 84, 71, 61, 51, 42, 32, 23, 15, 8, 0,
];
const LTP_FILTER_ICDF_P2: &[u8] = &[
    // {15,16,14,12,12,12,11,11,11,10,9,9,9,9,8,8,8,8,7,7,6,6,5,4,5,4,4,4,
    //  3,4,3,2}/256
    241, 225, 211, 199, 187, 175, 164, 153, 142, 132, 123, 114, 105, 96, 88, 80, 72, 64, 57, 50, 44,
    38, 33, 29, 24, 20, 16, 12, 9, 5, 2, 0,
];

// =====================================================================
// Tables 39–41 — LTP filter codebooks (5 signed Q7 taps per index),
// selected by periodicity index. Codebook sizes are 8 / 16 / 32.
// =====================================================================
const LTP_TAPS_P0: &[[i8; LTP_FILTER_TAPS]; 8] = &[
    [4, 6, 24, 7, 5],
    [0, 0, 2, 0, 0],
    [12, 28, 41, 13, -4],
    [-9, 15, 42, 25, 14],
    [1, -2, 62, 41, -9],
    [-10, 37, 65, -4, 3],
    [-6, 4, 66, 7, -8],
    [16, 14, 38, -3, 33],
];

const LTP_TAPS_P1: &[[i8; LTP_FILTER_TAPS]; 16] = &[
    [13, 22, 39, 23, 12],
    [-1, 36, 64, 27, -6],
    [-7, 10, 55, 43, 17],
    [1, 1, 8, 1, 1],
    [6, -11, 74, 53, -9],
    [-12, 55, 76, -12, 8],
    [-3, 3, 93, 27, -4],
    [26, 39, 59, 3, -8],
    [2, 0, 77, 11, 9],
    [-8, 22, 44, -6, 7],
    [40, 9, 26, 3, 9],
    [-7, 20, 101, -7, 4],
    [3, -8, 42, 26, 0],
    [-15, 33, 68, 2, 23],
    [-2, 55, 46, -2, 15],
    [3, -1, 21, 16, 41],
];

const LTP_TAPS_P2: &[[i8; LTP_FILTER_TAPS]; 32] = &[
    [-6, 27, 61, 39, 5],
    [-11, 42, 88, 4, 1],
    [-2, 60, 65, 6, -4],
    [-1, -5, 73, 56, 1],
    [-9, 19, 94, 29, -9],
    [0, 12, 99, 6, 4],
    [8, -19, 102, 46, -13],
    [3, 2, 13, 3, 2],
    [9, -21, 84, 72, -18],
    [-11, 46, 104, -22, 8],
    [18, 38, 48, 23, 0],
    [-16, 70, 83, -21, 11],
    [5, -11, 117, 22, -8],
    [-6, 23, 117, -12, 3],
    [3, -8, 95, 28, 4],
    [-10, 15, 77, 60, -15],
    [-1, 4, 124, 2, -4],
    [3, 38, 84, 24, -25],
    [2, 13, 42, 13, 31],
    [21, -4, 56, 46, -1],
    [-1, 35, 79, -13, 19],
    [-7, 65, 88, -9, -14],
    [20, 4, 81, 49, -29],
    [20, 0, 75, 3, -17],
    [5, -9, 44, 92, -8],
    [1, -3, 22, 69, 31],
    [-6, 95, 41, -12, 5],
    [39, 67, 16, -4, 1],
    [0, -6, 120, 55, -36],
    [-13, 44, 122, 4, -24],
    [81, 5, 11, 3, 7],
    [2, 0, 9, 10, 88],
];

// =====================================================================
// Table 42 — LTP scaling PDF: {128, 64, 64}/256, mapping the decoded
// index to a Q14 scale factor.
// =====================================================================
const LTP_SCALING_ICDF: &[u8] = &[128, 64, 0];
const LTP_SCALING_VALUES_Q14: [u16; 3] = [15565, 12288, 8192];

/// Default Q14 LTP scaling factor (≈0.95) for frames that do not code one.
pub const LTP_SCALING_DEFAULT_Q14: u16 = 15565;

/// Per-bandwidth low-part PDF + scale + lag range from Table 30.
struct LagLowSpec {
    icdf: &'static [u8],
    scale: i32,
    lag_min: i32,
    lag_max: i32,
}

fn lag_low_spec(bandwidth: Bandwidth) -> Result<LagLowSpec, Error> {
    match bandwidth {
        Bandwidth::Nb => Ok(LagLowSpec {
            icdf: LAG_LOW_ICDF_NB,
            scale: 4,
            lag_min: 16,
            lag_max: 144,
        }),
        Bandwidth::Mb => Ok(LagLowSpec {
            icdf: LAG_LOW_ICDF_MB,
            scale: 6,
            lag_min: 24,
            lag_max: 216,
        }),
        Bandwidth::Wb => Ok(LagLowSpec {
            icdf: LAG_LOW_ICDF_WB,
            scale: 8,
            lag_min: 32,
            lag_max: 288,
        }),
        // SILK only operates on NB / MB / WB internal bandwidths.
        Bandwidth::Swb | Bandwidth::Fb => Err(Error::MalformedPacket),
    }
}

/// How the primary pitch lag is coded for this SILK frame (§4.2.7.6.1).
///
/// Absolute coding is used iff this is the first SILK frame of its type
/// for the channel in the current Opus frame, OR the previous SILK frame
/// of the same type was not coded, OR that previous frame was coded but
/// not voiced. Everything else uses relative coding against
/// `previous_lag` — and even relative coding falls back to absolute when
/// the decoded delta is zero.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LagCoding {
    /// Absolute coding: high part (Table 29) + low part (Table 30).
    Absolute,
    /// Relative coding: a Table 31 delta against `previous_lag`. A decoded
    /// delta of zero falls back to absolute coding.
    Relative {
        /// The primary pitch lag from the most recent frame in the same
        /// channel. Used as the base for the delta; carried unclamped per
        /// the §4.2.7.6.1 note.
        previous_lag: i32,
    },
}

/// Inputs to [`LtpParameters::decode`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LtpConfig {
    /// SILK-layer audio bandwidth (NB / MB / WB). Selects the Table 30
    /// low-part codebook + scale + lag range and the Table 32 contour PDF.
    pub bandwidth: Bandwidth,
    /// Signal type from §4.2.7.3. LTP parameters are present only for
    /// [`SignalType::Voiced`] frames; any other value yields an empty
    /// result with no bitstream reads.
    pub signal_type: SignalType,
    /// Number of subframes in this SILK frame: 2 (10 ms) or 4 (20 ms /
    /// Hybrid). Selects the Table 32 contour PDF and the contour codebook
    /// width; other values are rejected.
    pub num_subframes: u8,
    /// How the primary lag is coded (§4.2.7.6.1).
    pub lag_coding: LagCoding,
    /// Whether the §4.2.7.6.3 LTP scaling field is present in the
    /// bitstream. The caller computes this from the §4.2.7.6.3
    /// enumeration (first time interval of the Opus frame for its type,
    /// or an LBRR frame whose prior LBRR frame is not coded). When
    /// `false` the default Q14 factor (`15565`) is used and no symbol is
    /// read.
    pub ltp_scaling_present: bool,
}

/// Decoded §4.2.7.6 LTP parameters for one SILK frame.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LtpParameters {
    /// `true` when this is a voiced frame carrying real LTP parameters.
    /// `false` (with all other fields zeroed / default) for non-voiced
    /// frames, where no LTP symbols are present in the bitstream.
    voiced: bool,
    /// The primary pitch lag for the SILK frame (the unclamped value used
    /// as `previous_lag` for the next frame's relative coding).
    primary_lag: i32,
    /// The decoded pitch-contour VQ index.
    contour_index: u8,
    /// Per-subframe pitch lags, clamped to `[lag_min, lag_max]`. Only
    /// `0..len` entries are populated.
    pitch_lags: [i32; LTP_MAX_SUBFRAMES],
    /// The decoded periodicity index `0..=2` (§4.2.7.6.2).
    periodicity_index: u8,
    /// Per-subframe 5-tap Q7 LTP filter coefficients. Only `0..len` rows
    /// are populated.
    filter_taps_q7: [[i8; LTP_FILTER_TAPS]; LTP_MAX_SUBFRAMES],
    /// The decoded per-subframe filter indices into the periodicity's
    /// codebook. Only `0..len` entries are populated.
    filter_indices: [u8; LTP_MAX_SUBFRAMES],
    /// The Q14 LTP scaling factor (§4.2.7.6.3); the default `15565` when
    /// not coded.
    ltp_scaling_q14: u16,
    len: u8,
}

impl LtpParameters {
    /// Decode the §4.2.7.6 LTP parameters from `rd`.
    ///
    /// For a non-voiced frame this consumes no bits and returns an empty
    /// (`!is_voiced()`) result. For a voiced frame it decodes, in order:
    /// the §4.2.7.6.1 primary lag + contour → per-subframe pitch lags,
    /// the §4.2.7.6.2 periodicity index + per-subframe filter indices →
    /// 5-tap Q7 filters, and finally the §4.2.7.6.3 LTP scaling factor
    /// (when `cfg.ltp_scaling_present`).
    ///
    /// Returns `Error::MalformedPacket` if `cfg.num_subframes` is not 2
    /// or 4, or if `cfg.bandwidth` is not an internal SILK bandwidth
    /// (NB / MB / WB).
    pub fn decode(rd: &mut RangeDecoder<'_>, cfg: LtpConfig) -> Result<Self, Error> {
        if cfg.num_subframes != 2 && cfg.num_subframes != 4 {
            return Err(Error::MalformedPacket);
        }
        let spec = lag_low_spec(cfg.bandwidth)?;
        let num = cfg.num_subframes as usize;

        // Non-voiced frames carry no LTP parameters at all.
        if cfg.signal_type != SignalType::Voiced {
            return Ok(Self {
                voiced: false,
                primary_lag: 0,
                contour_index: 0,
                pitch_lags: [0; LTP_MAX_SUBFRAMES],
                periodicity_index: 0,
                filter_taps_q7: [[0; LTP_FILTER_TAPS]; LTP_MAX_SUBFRAMES],
                filter_indices: [0; LTP_MAX_SUBFRAMES],
                ltp_scaling_q14: LTP_SCALING_DEFAULT_Q14,
                len: cfg.num_subframes,
            });
        }

        // --- §4.2.7.6.1 primary pitch lag -----------------------------
        let primary_lag = Self::decode_primary_lag(rd, &spec, cfg.lag_coding);

        // --- §4.2.7.6.1 pitch contour → per-subframe lags -------------
        let contour_index = Self::decode_contour_index(rd, cfg.bandwidth, num);
        let mut pitch_lags = [0i32; LTP_MAX_SUBFRAMES];
        for (k, slot) in pitch_lags.iter_mut().enumerate().take(num) {
            let offset = contour_offset(cfg.bandwidth, num, contour_index, k) as i32;
            *slot = (primary_lag + offset).clamp(spec.lag_min, spec.lag_max);
        }

        // --- §4.2.7.6.2 LTP filter coefficients -----------------------
        let periodicity_index = rd.dec_icdf(PERIODICITY_ICDF, 8) as u8;
        let mut filter_indices = [0u8; LTP_MAX_SUBFRAMES];
        let mut filter_taps_q7 = [[0i8; LTP_FILTER_TAPS]; LTP_MAX_SUBFRAMES];
        let filter_icdf = ltp_filter_icdf(periodicity_index);
        for k in 0..num {
            let idx = rd.dec_icdf(filter_icdf, 8) as u8;
            filter_indices[k] = idx;
            filter_taps_q7[k] = ltp_filter_taps(periodicity_index, idx);
        }

        // --- §4.2.7.6.3 LTP scaling -----------------------------------
        let ltp_scaling_q14 = if cfg.ltp_scaling_present {
            let s = rd.dec_icdf(LTP_SCALING_ICDF, 8) as usize;
            LTP_SCALING_VALUES_Q14[s]
        } else {
            LTP_SCALING_DEFAULT_Q14
        };

        Ok(Self {
            voiced: true,
            primary_lag,
            contour_index,
            pitch_lags,
            periodicity_index,
            filter_taps_q7,
            filter_indices,
            ltp_scaling_q14,
            len: cfg.num_subframes,
        })
    }

    /// Decode the §4.2.7.6.1 primary pitch lag. Absolute coding combines
    /// a Table 29 high part with a Table 30 low part; relative coding adds
    /// a Table 31 delta to `previous_lag`, falling back to absolute coding
    /// when the decoded delta is zero.
    fn decode_primary_lag(rd: &mut RangeDecoder<'_>, spec: &LagLowSpec, coding: LagCoding) -> i32 {
        match coding {
            LagCoding::Absolute => Self::decode_absolute_lag(rd, spec),
            LagCoding::Relative { previous_lag } => {
                let delta_lag_index = rd.dec_icdf(LAG_DELTA_ICDF, 8) as i32;
                if delta_lag_index == 0 {
                    // Zero delta falls back to absolute coding.
                    Self::decode_absolute_lag(rd, spec)
                } else {
                    // lag = previous_lag + (delta_lag_index - 9); unclamped
                    // per the §4.2.7.6.1 note.
                    previous_lag + (delta_lag_index - 9)
                }
            }
        }
    }

    /// `lag = lag_high * lag_scale + lag_low + lag_min` (§4.2.7.6.1).
    fn decode_absolute_lag(rd: &mut RangeDecoder<'_>, spec: &LagLowSpec) -> i32 {
        let lag_high = rd.dec_icdf(LAG_HIGH_ICDF, 8) as i32;
        let lag_low = rd.dec_icdf(spec.icdf, 8) as i32;
        lag_high * spec.scale + lag_low + spec.lag_min
    }

    /// Decode the §4.2.7.6.1 pitch-contour VQ index from the Table 32 PDF
    /// selected by `(bandwidth, num_subframes)`.
    fn decode_contour_index(rd: &mut RangeDecoder<'_>, bandwidth: Bandwidth, num: usize) -> u8 {
        let icdf = contour_icdf(bandwidth, num);
        rd.dec_icdf(icdf, 8) as u8
    }

    /// `true` if this is a voiced frame carrying real LTP parameters.
    pub fn is_voiced(&self) -> bool {
        self.voiced
    }

    /// The primary pitch lag (unclamped; used as the next frame's
    /// `previous_lag` for relative coding). `0` for non-voiced frames.
    pub fn primary_lag(&self) -> i32 {
        self.primary_lag
    }

    /// The decoded pitch-contour VQ index. `0` for non-voiced frames.
    pub fn contour_index(&self) -> u8 {
        self.contour_index
    }

    /// Per-subframe pitch lags, clamped to the bandwidth's
    /// `[lag_min, lag_max]`. Empty for non-voiced frames.
    pub fn pitch_lags(&self) -> &[i32] {
        if self.voiced {
            &self.pitch_lags[..self.len as usize]
        } else {
            &[]
        }
    }

    /// The decoded periodicity index `0..=2`. `0` for non-voiced frames.
    pub fn periodicity_index(&self) -> u8 {
        self.periodicity_index
    }

    /// Per-subframe 5-tap Q7 LTP filter coefficients. Empty for non-voiced
    /// frames.
    pub fn filter_taps_q7(&self) -> &[[i8; LTP_FILTER_TAPS]] {
        if self.voiced {
            &self.filter_taps_q7[..self.len as usize]
        } else {
            &[]
        }
    }

    /// The decoded per-subframe filter indices. Empty for non-voiced
    /// frames.
    pub fn filter_indices(&self) -> &[u8] {
        if self.voiced {
            &self.filter_indices[..self.len as usize]
        } else {
            &[]
        }
    }

    /// The Q14 LTP scaling factor (§4.2.7.6.3); the default `15565` when
    /// not coded or for non-voiced frames.
    pub fn ltp_scaling_q14(&self) -> u16 {
        self.ltp_scaling_q14
    }

    /// Number of subframes this result was decoded for.
    pub fn len(&self) -> usize {
        self.len as usize
    }

    /// `true` if there are no subframes (never happens after a successful
    /// decode of a valid frame).
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }
}

/// Table 32 contour PDF (as iCDF) for `(bandwidth, num_subframes)`.
fn contour_icdf(bandwidth: Bandwidth, num: usize) -> &'static [u8] {
    match (bandwidth, num) {
        (Bandwidth::Nb, 2) => CONTOUR_ICDF_NB_10MS,
        (Bandwidth::Nb, _) => CONTOUR_ICDF_NB_20MS,
        // MB or WB.
        (_, 2) => CONTOUR_ICDF_MBWB_10MS,
        (_, _) => CONTOUR_ICDF_MBWB_20MS,
    }
}

/// Table 33–36 contour offset for `(bandwidth, num_subframes, index, k)`.
fn contour_offset(bandwidth: Bandwidth, num: usize, index: u8, k: usize) -> i8 {
    let i = index as usize;
    match (bandwidth, num) {
        (Bandwidth::Nb, 2) => CONTOUR_NB_10MS[i][k],
        (Bandwidth::Nb, _) => CONTOUR_NB_20MS[i][k],
        (_, 2) => CONTOUR_MBWB_10MS[i][k],
        (_, _) => CONTOUR_MBWB_20MS[i][k],
    }
}

/// Table 38 LTP filter-index PDF (as iCDF) for a periodicity index.
fn ltp_filter_icdf(periodicity_index: u8) -> &'static [u8] {
    match periodicity_index {
        0 => LTP_FILTER_ICDF_P0,
        1 => LTP_FILTER_ICDF_P1,
        // Periodicity index is decoded from a 3-entry PDF, so it is
        // always 0..=2.
        _ => LTP_FILTER_ICDF_P2,
    }
}

/// Table 39–41 filter taps for a `(periodicity_index, filter_index)`.
fn ltp_filter_taps(periodicity_index: u8, filter_index: u8) -> [i8; LTP_FILTER_TAPS] {
    let i = filter_index as usize;
    match periodicity_index {
        0 => LTP_TAPS_P0[i],
        1 => LTP_TAPS_P1[i],
        _ => LTP_TAPS_P2[i],
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // --- PDF → iCDF transcription self-checks -------------------------

    /// Re-derive the iCDF for a PDF and assert it matches, plus that the
    /// PDF sums to 256 and the iCDF is monotone-decreasing terminated by 0.
    fn check_icdf(pdf: &[u32], icdf: &[u8]) {
        assert_eq!(pdf.iter().sum::<u32>(), 256, "PDF must sum to 256");
        let mut cum = 0u32;
        let mut expected = Vec::new();
        for &p in pdf {
            cum += p;
            expected.push((256 - cum) as u8);
        }
        assert_eq!(icdf, expected.as_slice(), "iCDF mismatch");
        assert_eq!(*icdf.last().unwrap(), 0, "iCDF must terminate with 0");
        for w in icdf.windows(2) {
            assert!(w[0] > w[1], "iCDF not strictly decreasing: {icdf:?}");
        }
        assert_eq!(icdf.len(), pdf.len(), "iCDF length must equal PDF length");
    }

    #[test]
    fn table29_high_part_icdf() {
        check_icdf(
            &[
                3, 3, 6, 11, 21, 30, 32, 19, 11, 10, 12, 13, 13, 12, 11, 9, 8, 7, 6, 4, 2, 2, 2, 1,
                1, 1, 1, 1, 1, 1, 1, 1,
            ],
            LAG_HIGH_ICDF,
        );
        assert_eq!(LAG_HIGH_ICDF.len(), 32);
    }

    #[test]
    fn table30_low_part_icdfs() {
        check_icdf(&[64, 64, 64, 64], LAG_LOW_ICDF_NB);
        check_icdf(&[43, 42, 43, 43, 42, 43], LAG_LOW_ICDF_MB);
        check_icdf(&[32, 32, 32, 32, 32, 32, 32, 32], LAG_LOW_ICDF_WB);
    }

    #[test]
    fn table30_scales_and_ranges() {
        let nb = lag_low_spec(Bandwidth::Nb).unwrap();
        assert_eq!((nb.scale, nb.lag_min, nb.lag_max), (4, 16, 144));
        let mb = lag_low_spec(Bandwidth::Mb).unwrap();
        assert_eq!((mb.scale, mb.lag_min, mb.lag_max), (6, 24, 216));
        let wb = lag_low_spec(Bandwidth::Wb).unwrap();
        assert_eq!((wb.scale, wb.lag_min, wb.lag_max), (8, 32, 288));
        assert!(lag_low_spec(Bandwidth::Swb).is_err());
        assert!(lag_low_spec(Bandwidth::Fb).is_err());
    }

    #[test]
    fn table31_delta_icdf() {
        check_icdf(
            &[
                46, 2, 2, 3, 4, 6, 10, 15, 26, 38, 30, 22, 15, 10, 7, 6, 4, 4, 2, 2, 2,
            ],
            LAG_DELTA_ICDF,
        );
        assert_eq!(LAG_DELTA_ICDF.len(), 21);
    }

    #[test]
    fn table32_contour_icdfs() {
        check_icdf(&[143, 50, 63], CONTOUR_ICDF_NB_10MS);
        check_icdf(
            &[68, 12, 21, 17, 19, 22, 30, 24, 17, 16, 10],
            CONTOUR_ICDF_NB_20MS,
        );
        check_icdf(
            &[91, 46, 39, 19, 14, 12, 8, 7, 6, 5, 5, 4],
            CONTOUR_ICDF_MBWB_10MS,
        );
        check_icdf(
            &[
                33, 22, 18, 16, 15, 14, 14, 13, 13, 10, 9, 9, 8, 6, 6, 6, 5, 4, 4, 4, 3, 3, 3, 2,
                2, 2, 2, 2, 2, 2, 1, 1, 1, 1,
            ],
            CONTOUR_ICDF_MBWB_20MS,
        );
    }

    #[test]
    fn table37_periodicity_icdf() {
        check_icdf(&[77, 80, 99], PERIODICITY_ICDF);
    }

    #[test]
    fn table38_ltp_filter_icdfs() {
        check_icdf(&[185, 15, 13, 13, 9, 9, 6, 6], LTP_FILTER_ICDF_P0);
        check_icdf(
            &[57, 34, 21, 20, 15, 13, 12, 13, 10, 10, 9, 10, 9, 8, 7, 8],
            LTP_FILTER_ICDF_P1,
        );
        check_icdf(
            &[
                15, 16, 14, 12, 12, 12, 11, 11, 11, 10, 9, 9, 9, 9, 8, 8, 8, 8, 7, 7, 6, 6, 5, 4,
                5, 4, 4, 4, 3, 4, 3, 2,
            ],
            LTP_FILTER_ICDF_P2,
        );
    }

    #[test]
    fn table42_ltp_scaling_icdf() {
        check_icdf(&[128, 64, 64], LTP_SCALING_ICDF);
        assert_eq!(LTP_SCALING_VALUES_Q14, [15565, 12288, 8192]);
        assert_eq!(LTP_SCALING_DEFAULT_Q14, 15565);
    }

    // --- Contour codebook structural checks ---------------------------

    #[test]
    fn contour_codebook_sizes_match_pdfs() {
        assert_eq!(CONTOUR_NB_10MS.len(), CONTOUR_ICDF_NB_10MS.len());
        assert_eq!(CONTOUR_NB_20MS.len(), CONTOUR_ICDF_NB_20MS.len());
        assert_eq!(CONTOUR_MBWB_10MS.len(), CONTOUR_ICDF_MBWB_10MS.len());
        assert_eq!(CONTOUR_MBWB_20MS.len(), CONTOUR_ICDF_MBWB_20MS.len());
        // Index-0 vectors are all-zero (no offset) in every codebook.
        assert_eq!(CONTOUR_NB_10MS[0], [0, 0]);
        assert_eq!(CONTOUR_NB_20MS[0], [0, 0, 0, 0]);
        assert_eq!(CONTOUR_MBWB_10MS[0], [0, 0]);
        assert_eq!(CONTOUR_MBWB_20MS[0], [0, 0, 0, 0]);
        // Spot-check a few interior rows against the spec tables.
        assert_eq!(CONTOUR_NB_20MS[1], [2, 1, 0, -1]);
        assert_eq!(CONTOUR_MBWB_20MS[33], [-9, -3, 3, 9]);
        assert_eq!(CONTOUR_MBWB_10MS[11], [-3, 3]);
    }

    #[test]
    fn ltp_filter_codebook_sizes_match_pdfs() {
        assert_eq!(LTP_TAPS_P0.len(), LTP_FILTER_ICDF_P0.len());
        assert_eq!(LTP_TAPS_P1.len(), LTP_FILTER_ICDF_P1.len());
        assert_eq!(LTP_TAPS_P2.len(), LTP_FILTER_ICDF_P2.len());
        assert_eq!(LTP_TAPS_P0.len(), 8);
        assert_eq!(LTP_TAPS_P1.len(), 16);
        assert_eq!(LTP_TAPS_P2.len(), 32);
        // Spot-checks against Tables 39–41.
        assert_eq!(LTP_TAPS_P0[0], [4, 6, 24, 7, 5]);
        assert_eq!(LTP_TAPS_P0[7], [16, 14, 38, -3, 33]);
        assert_eq!(LTP_TAPS_P1[0], [13, 22, 39, 23, 12]);
        assert_eq!(LTP_TAPS_P1[15], [3, -1, 21, 16, 41]);
        assert_eq!(LTP_TAPS_P2[0], [-6, 27, 61, 39, 5]);
        assert_eq!(LTP_TAPS_P2[31], [2, 0, 9, 10, 88]);
    }

    // --- Non-voiced: no reads -----------------------------------------

    #[test]
    fn non_voiced_reads_nothing() {
        let buf = [0x5A, 0xC3, 0x17, 0x9E, 0x42, 0xFB, 0x08, 0x71, 0x2D, 0xB6];
        for signal_type in [SignalType::Inactive, SignalType::Unvoiced] {
            let mut rd = RangeDecoder::new(&buf);
            let tell_before = rd.tell();
            let cfg = LtpConfig {
                bandwidth: Bandwidth::Wb,
                signal_type,
                num_subframes: 4,
                lag_coding: LagCoding::Absolute,
                ltp_scaling_present: true,
            };
            let ltp = LtpParameters::decode(&mut rd, cfg).unwrap();
            assert_eq!(rd.tell(), tell_before, "non-voiced must consume no bits");
            assert!(!ltp.is_voiced());
            assert!(ltp.pitch_lags().is_empty());
            assert!(ltp.filter_taps_q7().is_empty());
            assert_eq!(ltp.ltp_scaling_q14(), LTP_SCALING_DEFAULT_Q14);
        }
    }

    // --- Malformed config rejection -----------------------------------

    #[test]
    fn rejects_bad_subframe_count() {
        let buf = [0x00u8; 8];
        let mut rd = RangeDecoder::new(&buf);
        let cfg = LtpConfig {
            bandwidth: Bandwidth::Nb,
            signal_type: SignalType::Voiced,
            num_subframes: 3,
            lag_coding: LagCoding::Absolute,
            ltp_scaling_present: false,
        };
        assert!(LtpParameters::decode(&mut rd, cfg).is_err());
    }

    #[test]
    fn rejects_non_silk_bandwidth() {
        let buf = [0x00u8; 8];
        for bw in [Bandwidth::Swb, Bandwidth::Fb] {
            let mut rd = RangeDecoder::new(&buf);
            let cfg = LtpConfig {
                bandwidth: bw,
                signal_type: SignalType::Voiced,
                num_subframes: 4,
                lag_coding: LagCoding::Absolute,
                ltp_scaling_present: false,
            };
            assert!(LtpParameters::decode(&mut rd, cfg).is_err());
        }
    }

    // --- Voiced end-to-end: structural invariants ---------------------

    /// Independent re-derivation of the absolute primary lag off a fresh
    /// decoder, used to confirm the production decode reads the same
    /// symbols in the same order.
    fn manual_absolute_lag(rd: &mut RangeDecoder<'_>, spec: &LagLowSpec) -> i32 {
        let high = rd.dec_icdf(LAG_HIGH_ICDF, 8) as i32;
        let low = rd.dec_icdf(spec.icdf, 8) as i32;
        high * spec.scale + low + spec.lag_min
    }

    #[test]
    fn voiced_absolute_pitch_lags_in_range_and_match_formula() {
        let buf = [
            0x12, 0x9C, 0x5E, 0xA3, 0x77, 0x10, 0xBB, 0x42, 0x88, 0x01, 0xFE, 0x6D,
        ];
        for bandwidth in [Bandwidth::Nb, Bandwidth::Mb, Bandwidth::Wb] {
            for &num in &[2usize, 4usize] {
                let spec = lag_low_spec(bandwidth).unwrap();

                // Production decode.
                let mut rd = RangeDecoder::new(&buf);
                let cfg = LtpConfig {
                    bandwidth,
                    signal_type: SignalType::Voiced,
                    num_subframes: num as u8,
                    lag_coding: LagCoding::Absolute,
                    ltp_scaling_present: true,
                };
                let ltp = LtpParameters::decode(&mut rd, cfg).unwrap();

                // Independent re-derivation of the lag pipeline.
                let mut rd2 = RangeDecoder::new(&buf);
                let primary = manual_absolute_lag(&mut rd2, &spec);
                let contour = rd2.dec_icdf(contour_icdf(bandwidth, num), 8) as u8;
                assert_eq!(ltp.primary_lag(), primary);
                assert_eq!(ltp.contour_index(), contour);

                assert_eq!(ltp.pitch_lags().len(), num);
                for (k, &lag) in ltp.pitch_lags().iter().enumerate() {
                    let off = contour_offset(bandwidth, num, contour, k) as i32;
                    let expected = (primary + off).clamp(spec.lag_min, spec.lag_max);
                    assert_eq!(lag, expected, "bw={bandwidth:?} num={num} k={k}");
                    assert!(
                        (spec.lag_min..=spec.lag_max).contains(&lag),
                        "lag {lag} out of [{}, {}]",
                        spec.lag_min,
                        spec.lag_max
                    );
                }

                // Filters: every subframe yields a 5-tap row from the
                // periodicity codebook, and the index is in-range.
                assert_eq!(ltp.filter_taps_q7().len(), num);
                let p = ltp.periodicity_index();
                assert!(p <= 2);
                for (k, &fi) in ltp.filter_indices().iter().enumerate() {
                    let expected = ltp_filter_taps(p, fi);
                    assert_eq!(ltp.filter_taps_q7()[k], expected);
                }
            }
        }
    }

    #[test]
    fn voiced_relative_nonzero_delta_uses_previous_lag() {
        // Craft a decode where the relative delta is non-zero by choosing
        // a buffer; verify the production result equals
        // previous_lag + (delta - 9) and that the contour follows.
        let buf = [
            0x7F, 0x3A, 0x91, 0x04, 0xCD, 0x6E, 0x22, 0xB0, 0x15, 0x88, 0x40, 0xEE,
        ];
        let bandwidth = Bandwidth::Wb;
        let num = 4usize;
        let spec = lag_low_spec(bandwidth).unwrap();
        let previous_lag = 100;

        let mut rd = RangeDecoder::new(&buf);
        let cfg = LtpConfig {
            bandwidth,
            signal_type: SignalType::Voiced,
            num_subframes: num as u8,
            lag_coding: LagCoding::Relative { previous_lag },
            ltp_scaling_present: false,
        };
        let ltp = LtpParameters::decode(&mut rd, cfg).unwrap();

        // Independent re-derivation: read the delta first.
        let mut rd2 = RangeDecoder::new(&buf);
        let delta = rd2.dec_icdf(LAG_DELTA_ICDF, 8) as i32;
        let primary = if delta == 0 {
            manual_absolute_lag(&mut rd2, &spec)
        } else {
            previous_lag + (delta - 9)
        };
        assert_eq!(ltp.primary_lag(), primary);
    }

    #[test]
    fn relative_zero_delta_falls_back_to_absolute() {
        // The fallback path reads the delta symbol, observes zero, then
        // reads the absolute high+low parts. We cannot easily force a
        // particular delta from an arbitrary buffer, so this test pins the
        // *logic*: a decoder that observes delta == 0 must read exactly as
        // many further symbols as the absolute path. We verify by mirroring
        // the production decode against an independent pass that branches on
        // the same observed delta.
        let buf = [
            0xAA, 0x55, 0xF0, 0x0F, 0x3C, 0xC3, 0x99, 0x66, 0x12, 0x34, 0x56, 0x78,
        ];
        let bandwidth = Bandwidth::Mb;
        let num = 2usize;
        let spec = lag_low_spec(bandwidth).unwrap();

        let mut rd = RangeDecoder::new(&buf);
        let cfg = LtpConfig {
            bandwidth,
            signal_type: SignalType::Voiced,
            num_subframes: num as u8,
            lag_coding: LagCoding::Relative { previous_lag: 50 },
            ltp_scaling_present: false,
        };
        let ltp = LtpParameters::decode(&mut rd, cfg).unwrap();

        let mut rd2 = RangeDecoder::new(&buf);
        let delta = rd2.dec_icdf(LAG_DELTA_ICDF, 8) as i32;
        let primary = if delta == 0 {
            manual_absolute_lag(&mut rd2, &spec)
        } else {
            50 + (delta - 9)
        };
        let contour = rd2.dec_icdf(contour_icdf(bandwidth, num), 8) as u8;
        assert_eq!(ltp.primary_lag(), primary);
        assert_eq!(ltp.contour_index(), contour);
        // Whichever branch was taken, the byte position after decoding the
        // lag + contour must agree between the two passes.
        assert!(rd.tell() >= rd2.tell());
    }

    // --- LTP scaling present vs default -------------------------------

    #[test]
    fn ltp_scaling_present_decodes_one_of_three() {
        let buf = [
            0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, 0x90, 0xA0, 0xB0, 0xC0,
        ];
        let mut rd = RangeDecoder::new(&buf);
        let cfg = LtpConfig {
            bandwidth: Bandwidth::Nb,
            signal_type: SignalType::Voiced,
            num_subframes: 4,
            lag_coding: LagCoding::Absolute,
            ltp_scaling_present: true,
        };
        let ltp = LtpParameters::decode(&mut rd, cfg).unwrap();
        assert!(LTP_SCALING_VALUES_Q14.contains(&ltp.ltp_scaling_q14()));
    }

    #[test]
    fn ltp_scaling_absent_uses_default_without_reading() {
        // With scaling absent, the decode stops after the filter indices.
        // Compare bit positions: a "present" decode must consume strictly
        // more bits than an otherwise-identical "absent" decode.
        let buf = [
            0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, 0x90, 0xA0, 0xB0, 0xC0,
        ];
        let base = LtpConfig {
            bandwidth: Bandwidth::Nb,
            signal_type: SignalType::Voiced,
            num_subframes: 4,
            lag_coding: LagCoding::Absolute,
            ltp_scaling_present: false,
        };

        let mut rd_absent = RangeDecoder::new(&buf);
        let ltp_absent = LtpParameters::decode(&mut rd_absent, base).unwrap();
        assert_eq!(ltp_absent.ltp_scaling_q14(), LTP_SCALING_DEFAULT_Q14);
        let tell_absent = rd_absent.tell();

        let mut rd_present = RangeDecoder::new(&buf);
        let _ = LtpParameters::decode(
            &mut rd_present,
            LtpConfig {
                ltp_scaling_present: true,
                ..base
            },
        )
        .unwrap();
        assert!(
            rd_present.tell() > tell_absent,
            "present scaling must consume more bits than absent"
        );
    }

    // --- Wide sweep: never panics, always in range --------------------

    #[test]
    fn voiced_sweep_never_panics_and_stays_in_range() {
        let buffers: [&[u8]; 3] = [
            &[0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99],
            &[0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA, 0x99, 0x88, 0x77, 0x66],
            &[0x5A, 0xA5, 0x3C, 0xC3, 0x0F, 0xF0, 0x69, 0x96, 0x12, 0x48],
        ];
        for buf in buffers {
            for bandwidth in [Bandwidth::Nb, Bandwidth::Mb, Bandwidth::Wb] {
                let spec = lag_low_spec(bandwidth).unwrap();
                for &num in &[2u8, 4u8] {
                    for &present in &[false, true] {
                        for coding in [
                            LagCoding::Absolute,
                            LagCoding::Relative { previous_lag: 80 },
                        ] {
                            let mut rd = RangeDecoder::new(buf);
                            let cfg = LtpConfig {
                                bandwidth,
                                signal_type: SignalType::Voiced,
                                num_subframes: num,
                                lag_coding: coding,
                                ltp_scaling_present: present,
                            };
                            let ltp = LtpParameters::decode(&mut rd, cfg).unwrap();
                            assert_eq!(ltp.pitch_lags().len(), num as usize);
                            for &lag in ltp.pitch_lags() {
                                assert!((spec.lag_min..=spec.lag_max).contains(&lag));
                            }
                            assert!(ltp.periodicity_index() <= 2);
                            assert_eq!(ltp.filter_taps_q7().len(), num as usize);
                        }
                    }
                }
            }
        }
    }
}