oxideav-aac 0.1.7

Pure-Rust AAC-LC decoder and encoder for oxideav — ADTS framing, Huffman books 1-11, IMDCT, M/S stereo, TNS, PNS
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
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
//! `coupling_channel_element()` — ISO/IEC 14496-3 §4.6.8.3 / Table 4.8.
//!
//! The coupling channel element (CCE, `id_syn_ele == 0b010`) carries an
//! embedded `single_channel_element()` whose decoded spectrum is scaled
//! by a list of *gain elements* and added onto one or more target
//! channels (SCE / CPE) signalled by the coupling header. This module
//! owns the **coupling header + gain-list** half of Table 4.8:
//!
//! ```text
//! coupling_channel_element() {
//!     element_instance_tag;                4  uimsbf   // consumed by the walker
//!     ind_sw_cce_flag;                     1  uimsbf
//!     num_coupled_elements;                3  uimsbf
//!     num_gain_element_lists = 0;
//!     for (c = 0; c < num_coupled_elements+1; c++) {
//!         num_gain_element_lists++;
//!         cc_target_is_cpe[c];             1  uimsbf
//!         cc_target_tag_select[c];         4  uimsbf
//!         if (cc_target_is_cpe[c]) {
//!             cc_l[c];                     1  uimsbf
//!             cc_r[c];                     1  uimsbf
//!             if (cc_l[c] && cc_r[c])  num_gain_element_lists++;
//!         }
//!     }
//!     cc_domain;                           1  uimsbf
//!     gain_element_sign;                   1  uimsbf
//!     gain_element_scale;                  2  uimsbf
//!     individual_channel_stream(0,0);      // the embedded SCE body
//!     for (c=1; c<num_gain_element_lists; c++) {
//!         if (ind_sw_cce_flag) cge = 1;
//!         else { common_gain_element_present[c]; 1 uimsbf; cge = ...; }
//!         if (cge)  hcod_sf[common_gain_element[c]];   1..19 vlclbf
//!         else for (g) for (sfb) if (sfb_cb[g][sfb] != ZERO_HCB)
//!                          hcod_sf[dpcm_gain_element[c][g][sfb]]; 1..19 vlclbf
//!     }
//! }
//! ```
//!
//! ## Split of responsibility
//!
//! Like the CPE walk in [`crate::decode`], the embedded
//! `individual_channel_stream(0,0)` (Table 4.50) is parsed by the
//! caller through [`crate::ics_body::IcsBody`] +
//! [`crate::spectral_data::SpectralData`]; this module parses the
//! coupling header that *precedes* it ([`CouplingHeader::parse`]) and the
//! per-target gain lists that *follow* it
//! ([`CouplingGains::parse`]) — the caller threads the embedded SCE's
//! `IcsInfo` / `SectionData` between the two halves so the trailing gain
//! loop can walk the `num_window_groups × max_sfb` non-`ZERO_HCB` band
//! grid (the §4.6.8.3.3 `Note`: `sfb_cb` is the CCE's *embedded* SCE
//! codebooks, not the coupled target's).
//!
//! ## Reconstruction
//!
//! [`CouplingGains::cc_gain`] applies the §4.6.8.3.3 `couple_channel()`
//! scaling: `cc_gain = cc_sign · cc_scale^(−gain_element)`
//! (conformance-settled exponent sign — see [`CouplingGains::cc_gain`]),
//! with `cc_scale` from Table 4.154 ([`CC_SCALE_TABLE`]) and — when
//! `gain_element_sign == 1` — the in-phase / out-of-phase split taken
//! off **each transmitted DPCM delta** (`cc_sign = 1 − 2·(dpcm & 1)`,
//! accumulator fed with `dpcm >> 1`), per the ISO/IEC 14496-3:2001 /
//! 13818-7:2004 `couple_channel()` text as ruled in
//! `docs/audio/aac/cce-gain-sign-split.md` §3. A `common_gain_element`
//! is **never** sign-split (`cc_sign = 1` forced in that branch — so an
//! independently switched CCE, which must use common gains only, always
//! couples in phase). The first coupled target (`list_index == 0`) is
//! not transmitted: its gains are all `0`, i.e. the CCE is added in its
//! natural scaling (`cc_gain == 1`).
//!
//! ## Provenance
//!
//! Table 4.8 syntax, the §4.6.8.3.3 `decode_coupling_channel()` /
//! `couple_channel()` pseudocode, the Table 4.153 shared-gain-list table,
//! and the Table 4.154 `cc_scale_table` are all from ISO/IEC 14496-3
//! staged under `docs/audio/aac/`. The gain elements reuse the
//! §4.A.1 scalefactor Huffman codebook (codebook 12) via
//! [`crate::scale_factor_data::hcod_sf_decode`] /
//! [`crate::scale_factor_data::hcod_sf_encode`], exactly as the spec
//! directs ("gain_element values are differentially encoded using the
//! Huffman table for scalefactors").

use oxideav_core::bits::{BitReader, BitWriter};

use crate::ics_body::IcsBody;
use crate::ics_info::IcsInfo;
use crate::scale_factor_data::{hcod_sf_decode, hcod_sf_encode};
use crate::section_data::ZERO_HCB;
use crate::spectral_data::SpectralData;
use crate::{Error, Result};

/// Field width of `ind_sw_cce_flag` (Table 4.8).
pub const IND_SW_CCE_FLAG_BITS: u32 = 1;
/// Field width of `num_coupled_elements` (Table 4.8).
pub const NUM_COUPLED_ELEMENTS_BITS: u32 = 3;
/// Field width of `cc_target_tag_select` (Table 4.8).
pub const CC_TARGET_TAG_SELECT_BITS: u32 = 4;
/// Field width of `gain_element_scale` (Table 4.8).
pub const GAIN_ELEMENT_SCALE_BITS: u32 = 2;

/// Table 4.154 — the four `cc_scale` amplitude resolutions selected by
/// the 2-bit `gain_element_scale`. `cc_scale = 2^(1/8 · 2^scale)`:
/// `2^(1/8)`, `2^(1/4)`, `2^(1/2)`, `2^1` (step sizes 0.75 / 1.5 / 3.0 /
/// 6.0 dB).
pub const CC_SCALE_TABLE: [f64; 4] = [
    1.090_507_732_665_257_7,  // 2^(1/8)
    1.189_207_115_002_721,    // 2^(1/4)
    std::f64::consts::SQRT_2, // 2^(1/2)
    2.0,                      // 2^1
];

/// One coupled target of a CCE (Table 4.8 inner loop, one `c`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CoupledTarget {
    /// `cc_target_is_cpe[c]` — the coupled target is a CPE (`true`) or a
    /// SCE (`false`).
    pub is_cpe: bool,
    /// `cc_target_tag_select[c]` — the `element_instance_tag` of the
    /// coupled SCE / CPE.
    pub tag_select: u8,
    /// `cc_l[c]` — a gain list applies to the CPE's left channel. Always
    /// `false` for a SCE target.
    pub cc_l: bool,
    /// `cc_r[c]` — a gain list applies to the CPE's right channel. Always
    /// `false` for a SCE target.
    pub cc_r: bool,
}

impl CoupledTarget {
    /// The number of `num_gain_element_lists` slots this target
    /// contributes (Table 4.8): one per target, plus a *second* slot for
    /// a CPE target whose `cc_l && cc_r` (the shared-vs-split gain-list
    /// distinction, Table 4.153).
    fn gain_list_increment(&self) -> u32 {
        if self.is_cpe && self.cc_l && self.cc_r {
            2
        } else {
            1
        }
    }
}

/// Parsed `coupling_channel_element()` header (everything before the
/// embedded `individual_channel_stream(0,0)`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CouplingHeader {
    /// `ind_sw_cce_flag` — independently switched (`true`) vs dependently
    /// switched (`false`). An independently switched CCE must only use
    /// `common_gain_element` and is decoded to the time domain before
    /// coupling (§4.6.8.3.3); a dependently switched CCE shares the
    /// target window state and couples in the frequency domain.
    pub ind_sw_cce_flag: bool,
    /// `num_coupled_elements` — the number of coupled targets is
    /// `num_coupled_elements + 1` (minimum value `0` ⇒ one target).
    pub num_coupled_elements: u8,
    /// The `num_coupled_elements + 1` coupled targets.
    pub targets: Vec<CoupledTarget>,
    /// `cc_domain` — coupling performed before (`false`) or after
    /// (`true`) TNS decoding of the coupled target channels.
    pub cc_domain: bool,
    /// `gain_element_sign` — the transmitted gain elements carry
    /// in-phase / out-of-phase coupling information (`true`) or not
    /// (`false`).
    pub gain_element_sign: bool,
    /// `gain_element_scale` — 2-bit index into [`CC_SCALE_TABLE`].
    pub gain_element_scale: u8,
    /// `num_gain_element_lists` derived by the Table 4.8 loop. This is
    /// the number of transmitted gain lists; the trailing gain loop runs
    /// over `1 ..= num_gain_element_lists - 1` (list 0 is the implicit
    /// natural-scaling target).
    pub num_gain_element_lists: u32,
}

impl CouplingHeader {
    /// Parse the Table 4.8 coupling header. `reader` is positioned at
    /// `ind_sw_cce_flag` (i.e. the caller — typically the
    /// [`crate::raw_data_block`] walker — already consumed the 4-bit
    /// `element_instance_tag`).
    pub fn parse(reader: &mut BitReader<'_>) -> Result<Self> {
        let ind_sw_cce_flag = read_bit(reader)?;
        let num_coupled_elements = read_u8(reader, NUM_COUPLED_ELEMENTS_BITS)?;

        let mut num_gain_element_lists: u32 = 0;
        let mut targets = Vec::with_capacity(usize::from(num_coupled_elements) + 1);
        for _c in 0..(u32::from(num_coupled_elements) + 1) {
            num_gain_element_lists += 1;
            let is_cpe = read_bit(reader)?;
            let tag_select = read_u8(reader, CC_TARGET_TAG_SELECT_BITS)?;
            let (cc_l, cc_r) = if is_cpe {
                let cc_l = read_bit(reader)?;
                let cc_r = read_bit(reader)?;
                if cc_l && cc_r {
                    num_gain_element_lists += 1;
                }
                (cc_l, cc_r)
            } else {
                (false, false)
            };
            targets.push(CoupledTarget {
                is_cpe,
                tag_select,
                cc_l,
                cc_r,
            });
        }

        let cc_domain = read_bit(reader)?;
        let gain_element_sign = read_bit(reader)?;
        let gain_element_scale = read_u8(reader, GAIN_ELEMENT_SCALE_BITS)?;

        Ok(CouplingHeader {
            ind_sw_cce_flag,
            num_coupled_elements,
            targets,
            cc_domain,
            gain_element_sign,
            gain_element_scale,
            num_gain_element_lists,
        })
    }

    /// Write the Table 4.8 coupling header (mirror of [`Self::parse`]),
    /// **not** including the leading `element_instance_tag` (the caller /
    /// frame assembler owns that, exactly as the walker consumes it on
    /// the parse side).
    ///
    /// Rejects an inconsistent record: a `targets` count that disagrees
    /// with `num_coupled_elements + 1`, a `gain_element_scale > 3`, or a
    /// SCE target carrying a `cc_l` / `cc_r` flag.
    pub fn write(&self, writer: &mut BitWriter) -> Result<()> {
        if self.targets.len() != usize::from(self.num_coupled_elements) + 1 {
            return Err(Error::CceInvalid);
        }
        if self.gain_element_scale > 3 {
            return Err(Error::CceInvalid);
        }
        let mut derived_lists: u32 = 0;
        for t in &self.targets {
            if !t.is_cpe && (t.cc_l || t.cc_r) {
                return Err(Error::CceInvalid);
            }
            derived_lists += t.gain_list_increment();
        }
        if derived_lists != self.num_gain_element_lists {
            return Err(Error::CceInvalid);
        }

        writer.write_bit(self.ind_sw_cce_flag);
        writer.write_u32(
            u32::from(self.num_coupled_elements),
            NUM_COUPLED_ELEMENTS_BITS,
        );
        for t in &self.targets {
            writer.write_bit(t.is_cpe);
            writer.write_u32(u32::from(t.tag_select), CC_TARGET_TAG_SELECT_BITS);
            if t.is_cpe {
                writer.write_bit(t.cc_l);
                writer.write_bit(t.cc_r);
            }
        }
        writer.write_bit(self.cc_domain);
        writer.write_bit(self.gain_element_sign);
        writer.write_u32(u32::from(self.gain_element_scale), GAIN_ELEMENT_SCALE_BITS);
        Ok(())
    }
}

/// One decoded per-band coupling gain of a `dpcm_gain_element` list —
/// the §4.6.8.3.3 (2001 / 13818-7:2004) `couple_channel()` gain-decode
/// output for one `(g, sfb)`: the `cc_sign` out-of-phase flag split off
/// the transmitted DPCM delta, and the accumulated `gain_element`
/// exponent (see `docs/audio/aac/cce-gain-sign-split.md` §3).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct DpcmGain {
    /// `cc_sign == −1` (out-of-phase coupling) for this band. Set from
    /// the delta LSB (`dpcm & 1`) when `gain_element_sign == 1`; always
    /// `false` when the sign bit is clear.
    pub negative: bool,
    /// The accumulated `gain_element[g][sfb]` exponent —
    /// `a += dpcm >> 1` under `gain_element_sign == 1`, `a += dpcm`
    /// otherwise.
    pub gain: i32,
}

/// The decoded gain list for one coupled target (Table 4.8 trailing
/// loop, one `c`). Either a single `common_gain_element` applied to
/// every band, or a per-`(g, sfb)` `dpcm_gain_element` list decoded by
/// the §4.6.8.3.3 forward running sum.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GainList {
    /// `cge == 1`: one `common_gain_element` reused over every window
    /// group and scalefactor band (§4.6.8.3.3). Never sign-split — the
    /// 2001 / 13818-7 text forces `cc_sign = 1` in this branch.
    Common(i32),
    /// `cge == 0`: the per-band decoded gain grid, indexed
    /// `gains[g][sfb]`. Only the non-`ZERO_HCB` bands are transmitted;
    /// `ZERO_HCB` bands hold the running accumulator value with an
    /// in-phase sign (no delta is read there).
    Dpcm(Vec<Vec<DpcmGain>>),
}

/// The whole trailing gain-list block of a CCE (Table 4.8), one
/// [`GainList`] per transmitted list (`1 ..= num_gain_element_lists`).
///
/// The implicit list 0 (natural scaling) is **not** stored — the
/// [`Self::cc_gain`] helper returns `1.0` for it.
#[derive(Debug, Clone, PartialEq)]
pub struct CouplingGains {
    /// The `gain_element_scale`-selected `cc_scale` from Table 4.154.
    pub cc_scale: f64,
    /// `gain_element_sign` from the coupling header (informational —
    /// the in-phase / out-of-phase split is resolved per band at parse
    /// time into [`DpcmGain::negative`], per the
    /// `docs/audio/aac/cce-gain-sign-split.md` §3 ruling; the writer
    /// keys off the [`CouplingHeader`] it is handed).
    pub gain_element_sign: bool,
    /// The transmitted gain lists, in `c = 1 ..= num_gain_element_lists`
    /// order (`lists[0]` is the `c == 1` list).
    pub lists: Vec<GainList>,
}

impl CouplingGains {
    /// Parse the Table 4.8 trailing gain-list loop. `reader` is
    /// positioned immediately after the embedded
    /// `individual_channel_stream(0,0)`.
    ///
    /// * `header` — the already-parsed [`CouplingHeader`].
    /// * `num_window_groups` / `max_sfb` — from the embedded SCE's
    ///   `ics_info()`.
    /// * `sfb_cb` — the embedded SCE's per-`(g, sfb)` section codebooks
    ///   ([`crate::section_data::SectionData::sfb_cb`]); the §4.6.8.3.3
    ///   `Note` requires the CCE's *own* codebooks here, not the coupled
    ///   target's.
    pub fn parse(
        reader: &mut BitReader<'_>,
        header: &CouplingHeader,
        num_window_groups: usize,
        max_sfb: usize,
        sfb_cb: &[Vec<u8>],
    ) -> Result<Self> {
        let cc_scale = CC_SCALE_TABLE[usize::from(header.gain_element_scale & 0x3)];
        let mut lists = Vec::new();
        for _c in 1..header.num_gain_element_lists {
            let cge = if header.ind_sw_cce_flag {
                true
            } else {
                read_bit(reader)?
            };
            if cge {
                let common = i32::from(hcod_sf_decode(reader)?);
                lists.push(GainList::Common(common));
            } else {
                // An independently switched CCE must only use the common
                // gain element (§4.6.8.3.3); a per-band list here is
                // ill-formed. `cge` is already forced true above for that
                // case, so reaching the else branch with ind_sw set is
                // impossible, but guard against a hand-built record.
                if header.ind_sw_cce_flag {
                    return Err(Error::CceInvalid);
                }
                // §4.6.8.3.3 (2001 / 13818-7:2004) gain-decode loop —
                // under `gain_element_sign` the out-of-phase flag is
                // split off **each transmitted delta** (`cc_sign =
                // 1 − 2·(dpcm & 1)`) and the accumulator is fed with
                // the remaining magnitude (`a += dpcm >> 1`, arithmetic
                // shift); with the sign bit clear the delta accumulates
                // whole. Ruled in
                // `docs/audio/aac/cce-gain-sign-split.md` §3 (the
                // 14496-3:2009 fragment that splits the *accumulated*
                // value is an editorial defect of that edition).
                let mut acc: i32 = 0;
                let mut grid = vec![vec![DpcmGain::default(); max_sfb]; num_window_groups];
                for (g, row) in grid.iter_mut().enumerate() {
                    let cb_row = sfb_cb.get(g).ok_or(Error::CceInvalid)?;
                    for (sfb, cell) in row.iter_mut().enumerate() {
                        let cb = *cb_row.get(sfb).ok_or(Error::CceInvalid)?;
                        if cb != ZERO_HCB {
                            let dpcm = i32::from(hcod_sf_decode(reader)?);
                            if header.gain_element_sign {
                                acc += dpcm >> 1;
                                *cell = DpcmGain {
                                    negative: (dpcm & 1) != 0,
                                    gain: acc,
                                };
                            } else {
                                acc += dpcm;
                                *cell = DpcmGain {
                                    negative: false,
                                    gain: acc,
                                };
                            }
                        } else {
                            // ZERO_HCB band carries the running value but
                            // contributes no coupling (cc_gain unused).
                            *cell = DpcmGain {
                                negative: false,
                                gain: acc,
                            };
                        }
                    }
                }
                lists.push(GainList::Dpcm(grid));
            }
        }
        Ok(CouplingGains {
            cc_scale,
            gain_element_sign: header.gain_element_sign,
            lists,
        })
    }

    /// Write the trailing gain-list loop (mirror of [`Self::parse`]).
    /// `sfb_cb` must be the same embedded-SCE codebook grid the parse
    /// consumed so the `ZERO_HCB` bands are skipped identically.
    pub fn write(
        &self,
        writer: &mut BitWriter,
        header: &CouplingHeader,
        sfb_cb: &[Vec<u8>],
    ) -> Result<()> {
        if self.lists.len() + 1 != header.num_gain_element_lists as usize {
            return Err(Error::CceInvalid);
        }
        for list in &self.lists {
            match list {
                GainList::Common(common) => {
                    if !header.ind_sw_cce_flag {
                        // common_gain_element_present[c] = 1
                        writer.write_bit(true);
                    }
                    let dpcm = i8::try_from(*common).map_err(|_| Error::CceInvalid)?;
                    let (len, cw) = hcod_sf_encode(dpcm)?;
                    writer.write_u32(cw, u32::from(len));
                }
                GainList::Dpcm(grid) => {
                    if header.ind_sw_cce_flag {
                        return Err(Error::CceInvalid);
                    }
                    // common_gain_element_present[c] = 0
                    writer.write_bit(false);
                    // Exact inverse of the §4.6.8.3.3 gain-decode loop:
                    // under `gain_element_sign` each delta packs the
                    // out-of-phase flag into its LSB
                    // (`dpcm = ((gain − prev) << 1) | negative`, which
                    // `dpcm >> 1` / `dpcm & 1` recover for every signed
                    // delta); with the sign bit clear the delta is the
                    // plain gain difference and an out-of-phase band is
                    // unrepresentable (rejected).
                    let mut prev: i32 = 0;
                    for (g, row) in grid.iter().enumerate() {
                        let cb_row = sfb_cb.get(g).ok_or(Error::CceInvalid)?;
                        for (sfb, cell) in row.iter().enumerate() {
                            let cb = *cb_row.get(sfb).ok_or(Error::CceInvalid)?;
                            if cb != ZERO_HCB {
                                let delta = cell.gain - prev;
                                let dpcm = if header.gain_element_sign {
                                    (delta << 1) | i32::from(cell.negative)
                                } else {
                                    if cell.negative {
                                        return Err(Error::CceInvalid);
                                    }
                                    delta
                                };
                                let dpcm = i8::try_from(dpcm).map_err(|_| Error::CceInvalid)?;
                                let (len, cw) = hcod_sf_encode(dpcm)?;
                                writer.write_u32(cw, u32::from(len));
                                prev = cell.gain;
                            }
                        }
                    }
                }
            }
        }
        Ok(())
    }

    /// The §4.6.8.3.3 `couple_channel()` per-band gain factor for a given
    /// transmitted gain list and `(g, sfb)`.
    ///
    /// `list_index` is the §4.6.8.3.3 `couple_channel()` `gain_list_index`
    /// (`0` = the implicit natural-scaling target → `cc_gain == 1.0`;
    /// `1 ..= num_gain_element_lists - 1` index [`Self::lists`]).
    ///
    /// Returns `cc_gain = cc_sign · cc_scale^(−gain_element)`:
    /// * for a [`GainList::Dpcm`] band, `cc_sign` and `gain_element`
    ///   are the per-band values the parse loop split off the DPCM
    ///   deltas (`docs/audio/aac/cce-gain-sign-split.md` §3 — the
    ///   2001 / 13818-7:2004 `couple_channel()` gain decode);
    /// * for a [`GainList::Common`] list, `cc_sign = 1` always — the
    ///   ruled text never sign-splits a `common_gain_element`, so an
    ///   independently switched CCE (common gains only) couples in
    ///   phase regardless of `gain_element_sign`.
    ///
    /// The **negated** exponent is the conformance-settled reading of
    /// the §4.6.8.3.3 `cc_scale^gain_element` expression. All three
    /// staged editions print a positive exponent, but the ISO/IEC
    /// 14496-26 `am05_*` vectors (the only normative CCE bitstreams;
    /// every AU carries `common_gain_element = −1` lists) reconstruct
    /// their reference waveforms only with `cc_scale^(−ge)` — with the
    /// printed positive exponent every coupled target channel misses by
    /// ~1e-1 err/sig, with the negated form all six channels land at
    /// ~1e-4. This resolves the question
    /// `docs/audio/aac/cce-gain-sign-split.md` §4 left open (a
    /// black-box validator had measured the negated exponent; the
    /// conformance corpus now confirms it as the normative wire
    /// convention). The §3 sign-split ruling is orthogonal (the
    /// corpus's `gain_element_sign` is always 0) and is implemented in
    /// the parse loop.
    pub fn cc_gain(&self, list_index: usize, g: usize, sfb: usize) -> Result<f64> {
        if list_index == 0 {
            // The first coupled target's gains are not transmitted; the
            // CCE adds in its natural scaling (gain = 0 ⇒ cc_gain = 1).
            return Ok(1.0);
        }
        let list = self.lists.get(list_index - 1).ok_or(Error::CceInvalid)?;
        let (cc_sign, gain) = match list {
            GainList::Common(common) => (1.0, *common),
            GainList::Dpcm(grid) => {
                let cell = grid
                    .get(g)
                    .and_then(|row| row.get(sfb))
                    .ok_or(Error::CceInvalid)?;
                (if cell.negative { -1.0 } else { 1.0 }, cell.gain)
            }
        };
        Ok(cc_sign * self.cc_scale.powi(-gain))
    }

    /// §4.6.8.3.3 `couple_channel(source_spectrum, dest_spectrum,
    /// gain_list_index)` — scale the CCE's embedded-SCE spectrum by the
    /// `gain_list_index` gain list and **add** it onto one target
    /// channel's window-major spectrum in place.
    ///
    /// This is the per-band scale-and-add the spec pseudocode defines:
    ///
    /// ```text
    /// for (g = 0; g < num_window_groups; g++)
    ///   for (b = 0; b < window_group_length[g]; b++)
    ///     for (sfb = 0; sfb < max_sfb; sfb++)
    ///       if (sfb_cb[g][sfb] != ZERO_HCB)
    ///         for (i = swb_offset[sfb]; i < swb_offset[sfb+1]; i++)
    ///           dest[g][b][sfb][i] += cc_gain(idx,g,sfb) * source[g][b][sfb][i];
    /// ```
    ///
    /// `cc_gain` per band is [`Self::cc_gain`] (`cc_sign · cc_scale^(−gain)`);
    /// the implicit list 0 (`list_index == 0`) couples in natural scaling
    /// (`cc_gain == 1`) onto every non-`ZERO_HCB` band.
    ///
    /// * `source` / `dest` — window-major spectra
    ///   (`num_windows × window_len`), identical geometry. `source` is the
    ///   decoded embedded-SCE spectrum; `dest` is the addressed SCE / CPE
    ///   channel's spectrum at the §4.6.8.3.3 `cc_domain` stage (before or
    ///   after TNS).
    /// * `list_index` — the §4.6.8.3.3 `couple_channel()` `gain_list_index`
    ///   the [`CouplingHeader`] walk assigns to this target.
    /// * `sfb_cb` — the **embedded SCE's** per-`(g, sfb)` section
    ///   codebooks, per the §4.6.8.3.3 Note (`sfb_cb` is the CCE's own
    ///   codebook data, not the coupled target's). Drives the `ZERO_HCB`
    ///   band skip and, for a `GainList::Dpcm` list, the gain lookup.
    /// * `window_group_length` / `max_sfb` — the embedded SCE's
    ///   `ics_info()` group geometry.
    /// * `offsets` — the `swb_offset` table for the embedded SCE's window
    ///   length (`window_len + 1` entries; `offsets[sfb]..offsets[sfb+1]`
    ///   is band `sfb`).
    ///
    /// Returns [`Error::CceInvalid`] on any geometry mismatch (source /
    /// dest length, group / band shapes) so a malformed coupling does not
    /// corrupt the target out of bounds.
    #[allow(clippy::too_many_arguments)]
    pub fn couple_channel(
        &self,
        source: &[f64],
        dest: &mut [f64],
        list_index: usize,
        sfb_cb: &[Vec<u8>],
        window_group_length: &[u8],
        max_sfb: usize,
        offsets: &[u16],
    ) -> Result<()> {
        if source.len() != dest.len() {
            return Err(Error::CceInvalid);
        }
        if offsets.is_empty() {
            return Err(Error::CceInvalid);
        }
        // The last `swb_offset` entry is the window length (the first
        // coefficient past the last band). The window-major spectrum is
        // `num_windows * window_len` long.
        let window_len = usize::from(*offsets.last().expect("non-empty checked above"));
        if window_len == 0 || source.len() % window_len != 0 {
            return Err(Error::CceInvalid);
        }
        let num_swb = offsets.len() - 1;
        if max_sfb > num_swb {
            return Err(Error::CceInvalid);
        }
        if sfb_cb.len() != window_group_length.len() {
            return Err(Error::CceInvalid);
        }

        let mut window_base = 0usize;
        for (g, &wgl) in window_group_length.iter().enumerate() {
            let cb_row = sfb_cb.get(g).ok_or(Error::CceInvalid)?;
            if cb_row.len() < max_sfb {
                return Err(Error::CceInvalid);
            }
            let wgl = usize::from(wgl);
            for sfb in 0..max_sfb {
                if cb_row[sfb] == ZERO_HCB {
                    // §4.6.8.3.3: ZERO_HCB bands carry no coupling
                    // contribution (and, for a DPCM list, were not
                    // transmitted — the accumulator simply skipped them).
                    continue;
                }
                let start = usize::from(offsets[sfb]);
                let end = usize::from(offsets[sfb + 1]);
                let cc_gain = self.cc_gain(list_index, g, sfb)?;
                for b in 0..wgl {
                    let base = (window_base + b)
                        .checked_mul(window_len)
                        .ok_or(Error::CceInvalid)?;
                    let dst_end = base + end;
                    if dst_end > dest.len() {
                        return Err(Error::CceInvalid);
                    }
                    for i in start..end {
                        dest[base + i] += cc_gain * source[base + i];
                    }
                }
            }
            window_base += wgl;
        }
        Ok(())
    }
}

/// A fully-parsed `coupling_channel_element()` (Table 4.8): the coupling
/// header, the embedded `individual_channel_stream(0,0)` (body +
/// spectrum), and the trailing gain lists.
///
/// This is the single entry point a `raw_data_block()` walker uses to
/// **consume a whole CCE** from the bitstream (advancing the reader past
/// it). The decode loop can then either drop the element (a CCE
/// contributes no output channel of its own) or, once the cross-element
/// coupling is wired, scale [`Self::spectral`] by [`Self::gains`] and add
/// it onto the addressed target channels (§4.6.8.3.3 `couple_channel()`).
#[derive(Debug, Clone, PartialEq)]
pub struct CouplingChannelElement {
    /// `element_instance_tag` (4 bits) — the CCE's own instance tag.
    pub element_instance_tag: u8,
    /// The Table 4.8 coupling header.
    pub header: CouplingHeader,
    /// The embedded `individual_channel_stream(0,0)` body (Table 4.50),
    /// up to but not including `spectral_data()`.
    pub body: IcsBody,
    /// `ics_info()` of the embedded SCE (cloned out of [`Self::body`] for
    /// convenience; the embedded body always reads its own `ics_info`).
    pub ics_info: IcsInfo,
    /// The embedded SCE's `spectral_data()` (Table 4.56).
    pub spectral: SpectralData,
    /// The Table 4.8 trailing gain lists.
    pub gains: CouplingGains,
}

impl CouplingChannelElement {
    /// Parse a whole `coupling_channel_element()` (Table 4.8). `reader`
    /// is positioned at `element_instance_tag` (i.e. immediately after
    /// the `raw_data_block()` walker read the 3-bit `id_syn_ele == CCE`).
    ///
    /// * `aot` — the surrounding ASC's effective `audioObjectType`.
    /// * `fs_index` — the `samplingFrequencyIndex`.
    ///
    /// Walks, in spec order: the 4-bit instance tag, the
    /// [`CouplingHeader`], the embedded `individual_channel_stream(0,0)`
    /// ([`IcsBody`] + [`SpectralData`]), and the [`CouplingGains`]
    /// gain-list loop keyed off the embedded SCE's `sfb_cb`.
    pub fn parse(reader: &mut BitReader<'_>, aot: u8, fs_index: u8) -> Result<Self> {
        let element_instance_tag = read_u8(reader, 4)?;
        Self::parse_after_tag(reader, element_instance_tag, aot, fs_index)
    }

    /// Parse a `coupling_channel_element()` whose 4-bit
    /// `element_instance_tag` was already consumed by the surrounding
    /// `raw_data_block()` walker (which returns the tag in its
    /// `ChannelElement` event). `reader` is positioned at
    /// `ind_sw_cce_flag`; `element_instance_tag` is the walker-supplied
    /// tag. Otherwise identical to [`Self::parse`].
    pub fn parse_after_tag(
        reader: &mut BitReader<'_>,
        element_instance_tag: u8,
        aot: u8,
        fs_index: u8,
    ) -> Result<Self> {
        Self::parse_after_tag_family(
            reader,
            crate::swb_offset::FrameFamily::Lc1024,
            element_instance_tag,
            aot,
            fs_index,
        )
    }

    /// [`Self::parse_after_tag`] under an explicit §4.5.1.1
    /// frame-length family (a 960-line `raw_data_block()` may carry a
    /// CCE like any other; the ER payloads — including LD — have no
    /// CCE at all per §4.5.2.4, so the LD families never reach here).
    pub fn parse_after_tag_family(
        reader: &mut BitReader<'_>,
        family: crate::swb_offset::FrameFamily,
        element_instance_tag: u8,
        aot: u8,
        fs_index: u8,
    ) -> Result<Self> {
        let header = CouplingHeader::parse(reader)?;
        // Embedded individual_channel_stream(0,0): common_window = 0 and
        // scale_flag = 0 per Table 4.8.
        let body = IcsBody::parse_family(reader, family, aot, fs_index, false)?;
        let ics_info = body.ics_info.clone().ok_or(Error::CceInvalid)?;
        let spectral = SpectralData::parse(reader, &ics_info, &body.section_data, fs_index)?;
        let gains = CouplingGains::parse(
            reader,
            &header,
            usize::from(ics_info.num_window_groups),
            usize::from(ics_info.max_sfb),
            &body.section_data.sfb_cb,
        )?;
        Ok(CouplingChannelElement {
            element_instance_tag,
            header,
            body,
            ics_info,
            spectral,
            gains,
        })
    }
}

/// Helper: read a 1-bit flag, mapping underflow to [`Error::UnexpectedEnd`].
fn read_bit(reader: &mut BitReader<'_>) -> Result<bool> {
    reader.read_bit().map_err(|_| Error::UnexpectedEnd)
}

/// Helper: read an `n`-bit `uimsbf` field as a `u8`.
fn read_u8(reader: &mut BitReader<'_>, bits: u32) -> Result<u8> {
    Ok(reader.read_u32(bits).map_err(|_| Error::UnexpectedEnd)? as u8)
}

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

    /// Table 4.154 values are `2^(2^scale / 8)`.
    #[test]
    fn cc_scale_table_matches_spec_resolutions() {
        for (scale, &v) in CC_SCALE_TABLE.iter().enumerate() {
            let expected = 2f64.powf((1u32 << scale) as f64 / 8.0);
            assert!(
                (v - expected).abs() < 1e-12,
                "cc_scale[{scale}] = {v} != {expected}"
            );
        }
    }

    /// A header with a single SCE target derives `num_gain_element_lists
    /// == 1` (only the implicit list 0 — no trailing gains).
    #[test]
    fn single_sce_target_has_one_gain_list() {
        // ind_sw=0, num_coupled=0, target0: is_cpe=0 tag=0,
        // cc_domain=0 sign=0 scale=0
        let mut writer = BitWriter::new();
        writer.write_bit(false); // ind_sw_cce_flag
        writer.write_u32(0, 3); // num_coupled_elements
        writer.write_bit(false); // cc_target_is_cpe[0]
        writer.write_u32(0, 4); // cc_target_tag_select[0]
        writer.write_bit(false); // cc_domain
        writer.write_bit(false); // gain_element_sign
        writer.write_u32(0, 2); // gain_element_scale
        let bytes = writer.into_bytes();
        let mut reader = BitReader::new(&bytes);
        let h = CouplingHeader::parse(&mut reader).unwrap();
        assert_eq!(h.num_gain_element_lists, 1);
        assert_eq!(h.targets.len(), 1);
        assert!(!h.targets[0].is_cpe);
    }

    /// A CPE target with `cc_l && cc_r` adds a second gain list slot
    /// (Table 4.153: split left/right lists).
    #[test]
    fn cpe_target_with_both_channels_adds_a_list() {
        let mut writer = BitWriter::new();
        writer.write_bit(false); // ind_sw_cce_flag
        writer.write_u32(0, 3); // num_coupled_elements (=> 1 target)
        writer.write_bit(true); // cc_target_is_cpe[0]
        writer.write_u32(3, 4); // cc_target_tag_select[0]
        writer.write_bit(true); // cc_l[0]
        writer.write_bit(true); // cc_r[0]
        writer.write_bit(false); // cc_domain
        writer.write_bit(false); // gain_element_sign
        writer.write_u32(1, 2); // gain_element_scale
        let bytes = writer.into_bytes();
        let mut reader = BitReader::new(&bytes);
        let h = CouplingHeader::parse(&mut reader).unwrap();
        // 1 (target) + 1 (cc_l && cc_r) = 2.
        assert_eq!(h.num_gain_element_lists, 2);
        assert!(h.targets[0].is_cpe);
        assert!(h.targets[0].cc_l && h.targets[0].cc_r);
        assert_eq!(h.targets[0].tag_select, 3);
    }

    /// The header round-trips through write → parse.
    #[test]
    fn header_round_trips() {
        let h = CouplingHeader {
            ind_sw_cce_flag: true,
            num_coupled_elements: 1,
            targets: vec![
                CoupledTarget {
                    is_cpe: false,
                    tag_select: 2,
                    cc_l: false,
                    cc_r: false,
                },
                CoupledTarget {
                    is_cpe: true,
                    tag_select: 5,
                    cc_l: true,
                    cc_r: false,
                },
            ],
            cc_domain: true,
            gain_element_sign: true,
            gain_element_scale: 2,
            num_gain_element_lists: 2,
        };
        let mut writer = BitWriter::new();
        h.write(&mut writer).unwrap();
        let bytes = writer.into_bytes();
        let mut reader = BitReader::new(&bytes);
        let parsed = CouplingHeader::parse(&mut reader).unwrap();
        assert_eq!(parsed, h);
    }

    /// `write` rejects a SCE target carrying a `cc_l` flag.
    #[test]
    fn write_rejects_sce_target_with_cc_flag() {
        let h = CouplingHeader {
            ind_sw_cce_flag: false,
            num_coupled_elements: 0,
            targets: vec![CoupledTarget {
                is_cpe: false,
                tag_select: 0,
                cc_l: true,
                cc_r: false,
            }],
            cc_domain: false,
            gain_element_sign: false,
            gain_element_scale: 0,
            num_gain_element_lists: 1,
        };
        let mut writer = BitWriter::new();
        assert_eq!(h.write(&mut writer), Err(Error::CceInvalid));
    }

    /// `cc_gain` for the implicit list 0 is the natural scaling 1.0.
    #[test]
    fn cc_gain_list_zero_is_unity() {
        let gains = CouplingGains {
            cc_scale: CC_SCALE_TABLE[3],
            gain_element_sign: false,
            lists: vec![],
        };
        assert_eq!(gains.cc_gain(0, 0, 0).unwrap(), 1.0);
    }

    /// `cc_gain` applies `cc_scale^(−gain)` (conformance-settled
    /// exponent sign) for a common-gain list with the sign bit clear.
    #[test]
    fn cc_gain_common_no_sign() {
        let gains = CouplingGains {
            cc_scale: 2.0, // scale index 3 => 2^1
            gain_element_sign: false,
            lists: vec![GainList::Common(3)],
        };
        // gain = 3, cc_sign = 1 => 2^-3 = 1/8.
        assert!((gains.cc_gain(1, 0, 0).unwrap() - 0.125).abs() < 1e-12);
    }

    /// A `common_gain_element` is never sign-split, even when the
    /// header's `gain_element_sign` is set — the 2001 / 13818-7:2004
    /// `couple_channel()` forces `cc_sign = 1` in the common branch
    /// (`docs/audio/aac/cce-gain-sign-split.md` §3), which also makes
    /// every independently switched CCE couple in phase.
    #[test]
    fn cc_gain_common_never_sign_split() {
        let gains = CouplingGains {
            cc_scale: 2.0,
            gain_element_sign: true,
            lists: vec![GainList::Common(3)],
        };
        // gain_element = 3, cc_sign = +1 => +2^-3, not a split raw
        // value.
        assert!((gains.cc_gain(1, 0, 0).unwrap() - 0.125).abs() < 1e-12);
    }

    /// The sign-split DPCM decode takes `cc_sign` from each **delta**
    /// LSB and accumulates `dpcm >> 1` (§3 ruling): the worked
    /// `[3, 3]` sequence from `cce-gain-sign-split.md` §2.2 must land
    /// at `{−cc_scale^−1, −cc_scale^−2}` under the negated exponent
    /// (per-band signs both negative, exponents 1 then 2) — not the
    /// `{−1, +3}` split of the 2009 fragment-A misprint.
    #[test]
    fn cc_gain_dpcm_delta_split() {
        let sfb_cb = vec![vec![2u8, 2u8]];
        let header = CouplingHeader {
            ind_sw_cce_flag: false,
            num_coupled_elements: 1,
            targets: vec![
                CoupledTarget {
                    is_cpe: false,
                    tag_select: 0,
                    cc_l: false,
                    cc_r: false,
                },
                CoupledTarget {
                    is_cpe: false,
                    tag_select: 1,
                    cc_l: false,
                    cc_r: false,
                },
            ],
            cc_domain: false,
            gain_element_sign: true,
            gain_element_scale: 3, // cc_scale = 2
            num_gain_element_lists: 2,
        };
        // Transmit the deltas [3, 3] directly.
        let mut writer = BitWriter::new();
        writer.write_bit(false); // common_gain_element_present = 0
        for _ in 0..2 {
            let (len, cw) = hcod_sf_encode(3).unwrap();
            writer.write_u32(cw, u32::from(len));
        }
        let bytes = writer.into_bytes();
        let mut reader = BitReader::new(&bytes);
        let gains = CouplingGains::parse(&mut reader, &header, 1, 2, &sfb_cb).unwrap();
        // delta 3 => negative (3 & 1), a += 1 twice => gains 1, 2.
        assert_eq!(
            gains.lists,
            vec![GainList::Dpcm(vec![vec![
                DpcmGain {
                    negative: true,
                    gain: 1
                },
                DpcmGain {
                    negative: true,
                    gain: 2
                },
            ]])]
        );
        assert!((gains.cc_gain(1, 0, 0).unwrap() + 0.5).abs() < 1e-12);
        assert!((gains.cc_gain(1, 0, 1).unwrap() + 0.25).abs() < 1e-12);
    }

    /// The sign-split writer is the exact inverse of the parse loop,
    /// including negative deltas (arithmetic-shift packing) and an
    /// interior `ZERO_HCB` skip.
    #[test]
    fn dpcm_sign_split_round_trips() {
        let sfb_cb = vec![vec![2u8, ZERO_HCB, 4u8, 4u8]];
        let header = CouplingHeader {
            ind_sw_cce_flag: false,
            num_coupled_elements: 1,
            targets: vec![
                CoupledTarget {
                    is_cpe: false,
                    tag_select: 0,
                    cc_l: false,
                    cc_r: false,
                },
                CoupledTarget {
                    is_cpe: false,
                    tag_select: 1,
                    cc_l: false,
                    cc_r: false,
                },
            ],
            cc_domain: false,
            gain_element_sign: true,
            gain_element_scale: 1,
            num_gain_element_lists: 2,
        };
        let grid = vec![vec![
            DpcmGain {
                negative: true,
                gain: -2,
            },
            // ZERO_HCB carry cell (not transmitted).
            DpcmGain {
                negative: false,
                gain: -2,
            },
            DpcmGain {
                negative: false,
                gain: 1,
            },
            DpcmGain {
                negative: true,
                gain: 1,
            },
        ]];
        let gains = CouplingGains {
            cc_scale: CC_SCALE_TABLE[1],
            gain_element_sign: true,
            lists: vec![GainList::Dpcm(grid.clone())],
        };
        let mut writer = BitWriter::new();
        gains.write(&mut writer, &header, &sfb_cb).unwrap();
        let bytes = writer.into_bytes();
        let mut reader = BitReader::new(&bytes);
        let parsed = CouplingGains::parse(&mut reader, &header, 1, 4, &sfb_cb).unwrap();
        assert_eq!(parsed.lists, vec![GainList::Dpcm(grid)]);
    }

    /// An out-of-phase band under a clear `gain_element_sign` is
    /// unrepresentable on the wire and must be rejected by the writer,
    /// not silently dropped.
    #[test]
    fn write_rejects_negative_band_without_sign_bit() {
        let sfb_cb = vec![vec![2u8]];
        let header = CouplingHeader {
            ind_sw_cce_flag: false,
            num_coupled_elements: 1,
            targets: vec![
                CoupledTarget {
                    is_cpe: false,
                    tag_select: 0,
                    cc_l: false,
                    cc_r: false,
                },
                CoupledTarget {
                    is_cpe: false,
                    tag_select: 1,
                    cc_l: false,
                    cc_r: false,
                },
            ],
            cc_domain: false,
            gain_element_sign: false,
            gain_element_scale: 0,
            num_gain_element_lists: 2,
        };
        let gains = CouplingGains {
            cc_scale: CC_SCALE_TABLE[0],
            gain_element_sign: false,
            lists: vec![GainList::Dpcm(vec![vec![DpcmGain {
                negative: true,
                gain: 0,
            }]])],
        };
        let mut writer = BitWriter::new();
        assert_eq!(
            gains.write(&mut writer, &header, &sfb_cb),
            Err(Error::CceInvalid)
        );
    }

    /// A dependently switched per-band DPCM list round-trips through
    /// write → parse against a fixed `sfb_cb` grid, and the forward
    /// accumulator reconstructs the absolute gains.
    #[test]
    fn dpcm_gain_list_round_trips() {
        // One window group, three bands; band 1 is ZERO_HCB (skipped).
        let sfb_cb = vec![vec![2u8, ZERO_HCB, 4u8]];
        let header = CouplingHeader {
            ind_sw_cce_flag: false,
            num_coupled_elements: 1,
            targets: vec![
                CoupledTarget {
                    is_cpe: false,
                    tag_select: 0,
                    cc_l: false,
                    cc_r: false,
                },
                CoupledTarget {
                    is_cpe: false,
                    tag_select: 1,
                    cc_l: false,
                    cc_r: false,
                },
            ],
            cc_domain: false,
            gain_element_sign: false,
            gain_element_scale: 0,
            num_gain_element_lists: 2,
        };
        // Absolute gains: band0 = +2 (dpcm +2), band1 carries acc (2,
        // not transmitted), band2 = +5 (dpcm +3).
        let grid = vec![vec![
            DpcmGain {
                negative: false,
                gain: 2,
            },
            DpcmGain {
                negative: false,
                gain: 2,
            },
            DpcmGain {
                negative: false,
                gain: 5,
            },
        ]];
        let gains = CouplingGains {
            cc_scale: CC_SCALE_TABLE[0],
            gain_element_sign: false,
            lists: vec![GainList::Dpcm(grid.clone())],
        };
        let mut writer = BitWriter::new();
        gains.write(&mut writer, &header, &sfb_cb).unwrap();
        let bytes = writer.into_bytes();
        let mut reader = BitReader::new(&bytes);
        let parsed = CouplingGains::parse(&mut reader, &header, 1, 3, &sfb_cb).unwrap();
        assert_eq!(parsed.lists.len(), 1);
        match &parsed.lists[0] {
            GainList::Dpcm(g) => assert_eq!(g, &grid),
            other => panic!("expected Dpcm, got {other:?}"),
        }
    }

    /// `couple_channel` for the implicit list 0 (natural scaling) adds
    /// the source spectrum onto the target unchanged on every
    /// non-`ZERO_HCB` band, and skips the `ZERO_HCB` band entirely.
    #[test]
    fn couple_channel_list_zero_adds_natural_scaling() {
        // One window group, one window of length 8; two bands of width 4.
        // Band 0 is a spectrum book (couples), band 1 is ZERO_HCB (skip).
        let offsets = [0u16, 4, 8];
        let sfb_cb = vec![vec![2u8, ZERO_HCB]];
        let wgl = [1u8];
        let gains = CouplingGains {
            cc_scale: CC_SCALE_TABLE[3],
            gain_element_sign: false,
            lists: vec![],
        };
        let source = vec![1.0f64, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0];
        let mut dest = vec![10.0f64; 8];
        gains
            .couple_channel(&source, &mut dest, 0, &sfb_cb, &wgl, 2, &offsets)
            .unwrap();
        // Band 0 (indices 0..4): dest += 1*source.
        assert_eq!(&dest[0..4], &[11.0, 12.0, 13.0, 14.0]);
        // Band 1 (indices 4..8) is ZERO_HCB → untouched.
        assert_eq!(&dest[4..8], &[10.0, 10.0, 10.0, 10.0]);
    }

    /// `couple_channel` applies a non-unity common gain
    /// (`cc_scale^(−gain)`) onto every coupled band.
    #[test]
    fn couple_channel_common_gain_scales() {
        let offsets = [0u16, 4];
        let sfb_cb = vec![vec![2u8]];
        let wgl = [1u8];
        // gain element −1, sign clear, scale index 3 (cc_scale = 2) ⇒
        // cc_gain = 2^(−(−1)) = 2 (the am05 conformance vectors carry
        // exactly this −1 common gain).
        let gains = CouplingGains {
            cc_scale: 2.0,
            gain_element_sign: false,
            lists: vec![GainList::Common(-1)],
        };
        let source = vec![1.0f64, 2.0, 3.0, 4.0];
        let mut dest = vec![0.0f64; 4];
        gains
            .couple_channel(&source, &mut dest, 1, &sfb_cb, &wgl, 1, &offsets)
            .unwrap();
        assert_eq!(dest, vec![2.0, 4.0, 6.0, 8.0]);
    }

    /// `couple_channel` walks the multi-window short-block grid: a window
    /// group of length 2 applies the same per-sfb gain to both windows.
    #[test]
    fn couple_channel_multi_window_group() {
        // num_windows = 2, window_len = 4, one group of length 2, one band.
        let offsets = [0u16, 4];
        let sfb_cb = vec![vec![2u8]];
        let wgl = [2u8];
        let gains = CouplingGains {
            cc_scale: 2.0,
            gain_element_sign: false,
            lists: vec![GainList::Common(0)], // cc_gain = 2^0 = 1
        };
        let source = vec![1.0f64, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0];
        let mut dest = vec![0.0f64; 8];
        gains
            .couple_channel(&source, &mut dest, 1, &sfb_cb, &wgl, 1, &offsets)
            .unwrap();
        // Both windows of the group are coupled at gain 1.
        assert_eq!(dest, source);
    }

    /// `couple_channel` per-band DPCM gains scale each band independently.
    #[test]
    fn couple_channel_dpcm_per_band_gains() {
        let offsets = [0u16, 2, 4];
        let sfb_cb = vec![vec![2u8, 2u8]];
        let wgl = [1u8];
        // Absolute gains: band0 = 0 (cc_gain 1), band1 = −1 (cc_gain 2
        // under the conformance-settled negated exponent).
        let gains = CouplingGains {
            cc_scale: 2.0,
            gain_element_sign: false,
            lists: vec![GainList::Dpcm(vec![vec![
                DpcmGain {
                    negative: false,
                    gain: 0,
                },
                DpcmGain {
                    negative: false,
                    gain: -1,
                },
            ]])],
        };
        let source = vec![3.0f64, 3.0, 3.0, 3.0];
        let mut dest = vec![0.0f64; 4];
        gains
            .couple_channel(&source, &mut dest, 1, &sfb_cb, &wgl, 2, &offsets)
            .unwrap();
        // Band 0 (0..2): ×1; band 1 (2..4): ×2.
        assert_eq!(dest, vec![3.0, 3.0, 6.0, 6.0]);
    }

    /// `couple_channel` rejects a source / dest length mismatch.
    #[test]
    fn couple_channel_rejects_length_mismatch() {
        let offsets = [0u16, 4];
        let sfb_cb = vec![vec![2u8]];
        let gains = CouplingGains {
            cc_scale: 2.0,
            gain_element_sign: false,
            lists: vec![],
        };
        let source = vec![0.0f64; 4];
        let mut dest = vec![0.0f64; 8];
        assert_eq!(
            gains.couple_channel(&source, &mut dest, 0, &sfb_cb, &[1u8], 1, &offsets),
            Err(Error::CceInvalid)
        );
    }

    /// An independently switched CCE forces `cge == 1`: no
    /// `common_gain_element_present` bit is read, and the gain list is a
    /// single common element per target.
    #[test]
    fn ind_sw_cce_uses_common_gain_only() {
        let header = CouplingHeader {
            ind_sw_cce_flag: true,
            num_coupled_elements: 1,
            targets: vec![
                CoupledTarget {
                    is_cpe: false,
                    tag_select: 0,
                    cc_l: false,
                    cc_r: false,
                },
                CoupledTarget {
                    is_cpe: false,
                    tag_select: 1,
                    cc_l: false,
                    cc_r: false,
                },
            ],
            cc_domain: false,
            gain_element_sign: false,
            gain_element_scale: 0,
            num_gain_element_lists: 2,
        };
        let gains = CouplingGains {
            cc_scale: CC_SCALE_TABLE[0],
            gain_element_sign: false,
            lists: vec![GainList::Common(1)],
        };
        let mut writer = BitWriter::new();
        gains.write(&mut writer, &header, &[]).unwrap();
        let bytes = writer.into_bytes();
        let mut reader = BitReader::new(&bytes);
        // No common_gain_element_present bit is present; parse must read
        // exactly one hcod_sf codeword for the single list.
        let parsed = CouplingGains::parse(&mut reader, &header, 1, 1, &[]).unwrap();
        assert_eq!(parsed.lists, vec![GainList::Common(1)]);
    }
}