rusty_aac 2.1.1

Pure-Rust AAC decoder (LC, Main, LTP, HE-AAC v1/v2 SBR+PS, ER LD/ELD; sample-exact vs FFmpeg on the ISO conformance suite) and AAC-LC encoder (~5x faster than FFmpeg's native encoder, PEAQ-measured). No C/FFI. ADTS/MP4/LATM-LOAS, 7.1 + PCE layouts.
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
//! The AAC decoder: `raw_data_block` / `er_raw_data_block` → channel elements →
//! spectral tools → synthesis → PCM (ISO 14496-3 §4.4 / §4.6).
//!
//! Coverage: AAC Main (backward-adaptive prediction), LC, SSR (gain control
//! parsed and ignored, as every practical decoder does), LTP; the 960-sample
//! frame variant; ER AAC-LC/LTP, ER AAC-LD (512/480) and ER AAC-ELD (low-delay
//! filterbank); every channel configuration 1-7 and 11-14 plus PCE-described
//! programs; coupling channel elements (dependent before/after TNS and
//! independent after IMDCT); PNS, intensity and M/S stereo, pulses, TNS.
//! HE-AAC (SBR/PS) is layered on top in [`crate::sbr`].
//!
//! Output order and element routing follow FFmpeg's model (see [`layout`]) so a
//! multichannel stream comes out in the same channel order, and noise bands are
//! generated by the same LCG, which is what lets the conformance census compare
//! sample-for-sample.

pub(crate) mod channel;
pub mod layout;
pub(crate) mod spectral;
pub(crate) mod synth;
pub(crate) mod tools;

pub(crate) use channel::TNS_MAX_LONG;

use crate::bits::BitReader;
use crate::config::{aot, StreamConfig};
use crate::ics::WindowSequence;
use crate::tables::SCALEFACTOR_BOOK;
use crate::{DecodedAudio, Error, Result};
use channel::{decode_ics, decode_ltp, parse_ics_info, ChannelData, Ics, Syntax, MAX_PREDICTORS};
use layout::{OutputConfig, Tag, TYPE_CCE, TYPE_CPE, TYPE_LFE, TYPE_SCE};
use tools::{Coupling, PredState};

const ID_SCE: u32 = 0;
const ID_CPE: u32 = 1;
const ID_CCE: u32 = 2;
const ID_LFE: u32 = 3;
const ID_DSE: u32 = 4;
const ID_PCE: u32 = 5;
const ID_FIL: u32 = 6;
const ID_END: u32 = 7;

const EXT_DYNAMIC_RANGE: u32 = 11;
const EXT_SBR_DATA: u32 = 13;
const EXT_SBR_DATA_CRC: u32 = 14;

/// One channel's persistent decode state + this frame's payload.
#[derive(Clone)]
pub(crate) struct Sce {
    pub ics: Ics,
    pub data: ChannelData,
    pub saved: Vec<f32>,
    pub output: Vec<f32>,
    pub ltp_state: Vec<f32>,
    pub pred: Vec<PredState>,
    pub pred_init: bool,
}

impl Sce {
    fn new() -> Self {
        Self {
            ics: Ics::default(),
            data: ChannelData::default(),
            saved: vec![0.0; 1536],
            output: vec![0.0; 2048],
            ltp_state: vec![0.0; 3072],
            pred: vec![PredState::default(); MAX_PREDICTORS],
            pred_init: false,
        }
    }
}

/// A channel element (SCE/LFE use `ch[0]`; CPE both; CCE `ch[0]` + coupling).
#[derive(Clone)]
pub(crate) struct Element {
    pub ch: [Sce; 2],
    pub coup: Coupling,
    pub present: bool,
    pub ms_mask: Vec<bool>,
    pub ms_present: u8,
    pub common_window: bool,
    /// Raw SBR extension payloads seen this frame (consumed by the SBR stage).
    pub sbr_payload: Option<(Vec<u8>, usize, bool)>,
    pub sbr: Option<Box<crate::sbr::dec::SbrChannelState>>,
}

impl Element {
    fn new() -> Self {
        Self {
            ch: [Sce::new(), Sce::new()],
            coup: Coupling::default(),
            present: false,
            ms_mask: vec![false; 128],
            ms_present: 0,
            common_window: false,
            sbr_payload: None,
            sbr: None,
        }
    }
}

/// Stateful AAC decoder for one elementary stream.
pub struct Decoder {
    cfg: StreamConfig,
    syntax: Syntax,
    windows: synth::Windows,
    ld_sine: Vec<f32>,
    ld_low_overlap: Vec<f32>,
    elements: Vec<Vec<Option<Box<Element>>>>,
    /// The previous block failed part-way (its elements may still be marked
    /// present with half-updated state); see `decode_block`.
    partial: bool,
    oc: OutputConfig,
    /// The configuration's `channelConfiguration` (0 = PCE-routed).
    chan_config: u8,
    tags_mapped: usize,
    rng: u32,
    saw_sbr: bool,
    /// SBR: Some(true) explicitly present, Some(false) explicitly absent, None = unknown.
    sbr_state: Option<bool>,
    ps_state: Option<bool>,
    locked: bool,
    buf: Vec<f32>,
    /// No layout known (raw access units with no config, or an ADTS
    /// `channel_configuration` of 0 without a PCE): the first frame's elements
    /// define it, in arrival order.
    discovery: Option<Vec<Tag>>,
}

impl Decoder {
    /// A plain AAC-LC decoder at `sample_rate` (layout learned from the stream).
    ///
    /// # Panics
    ///
    /// Never: an unsupported `sample_rate` falls back to 44.1 kHz, and that
    /// AAC-LC stereo configuration is always accepted.
    #[must_use]
    pub fn new(sample_rate: u32) -> Self {
        // Cannot fail: AAC-LC stereo at 44.1 kHz is always a supported configuration.
        Self::with_stream_config(StreamConfig::lc(2, sample_rate, 0))
            .unwrap_or_else(|_| Self::with_stream_config(StreamConfig::lc(2, 44100, 0)).unwrap())
    }

    /// A decoder for a fully parsed configuration.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Unsupported`] or [`Error::InvalidData`] for a configuration
    /// this decoder cannot run.
    pub fn with_stream_config(cfg: StreamConfig) -> Result<Self> {
        let syntax = Syntax {
            aot: cfg.object_type,
            sf_index: cfg.sf_index,
            frame_len: cfg.frame_length,
        };
        match cfg.object_type {
            aot::AAC_MAIN
            | aot::AAC_LC
            | aot::AAC_SSR
            | aot::AAC_LTP
            | aot::ER_AAC_LC
            | aot::ER_AAC_LTP => {}
            aot::ER_AAC_LD => {
                if !(3..=7).contains(&cfg.sf_index) {
                    return Err(Error::invalid("aac: invalid low-delay sampling rate"));
                }
            }
            aot::ER_AAC_ELD => {}
            o => {
                return Err(Error::unsupported(format!(
                    "aac: object type {o} not supported"
                )));
            }
        }
        if cfg.section_data_resilience
            || cfg.scalefactor_data_resilience
            || cfg.spectral_data_resilience
        {
            return Err(Error::unsupported(
                "aac: error-resilience data tools (HCR/RVLC/VCB11) are not supported",
            ));
        }
        // The LTP history and its state update are built on 1024-sample frames;
        // a 960-sample LTP stream used to reach them and index past the frame.
        if cfg.object_type == aot::AAC_LTP && cfg.frame_length != 1024 {
            return Err(Error::unsupported(
                "aac: AAC-LTP with 960-sample frames is not supported",
            ));
        }
        let fl = match cfg.object_type {
            aot::ER_AAC_LD | aot::ER_AAC_ELD => cfg.frame_length,
            _ => cfg.frame_length,
        };
        let win_len = if fl <= 512 { 1024 } else { fl };
        let mut d = Self {
            windows: synth::Windows::new(win_len),
            ld_sine: crate::dsp::sine_window(2 * fl)[..fl].to_vec(),
            ld_low_overlap: crate::dsp::sine_window(2 * (fl / 4))[..fl / 4].to_vec(),
            syntax,
            partial: false,
            elements: (0..4).map(|_| (0..16).map(|_| None).collect()).collect(),
            oc: OutputConfig::default(),
            chan_config: cfg.channel_config,
            tags_mapped: 0,
            rng: 0x1f2e3d4c,
            saw_sbr: false,
            sbr_state: if cfg.sbr {
                Some(true)
            } else if cfg.sbr_explicitly_absent {
                Some(false)
            } else {
                None
            },
            ps_state: if cfg.ps { Some(true) } else { None },
            locked: false,
            buf: vec![0.0; 2048],
            discovery: if cfg.channel_config == 0 && cfg.pce.is_none() {
                Some(Vec::new())
            } else {
                None
            },
            cfg,
        };
        d.configure_initial()?;
        Ok(d)
    }

    /// The configuration this decoder runs.
    #[must_use]
    pub fn stream_config(&self) -> &StreamConfig {
        &self.cfg
    }

    fn configure_initial(&mut self) -> Result<()> {
        let map = if let Some(p) = &self.cfg.pce {
            layout::pce_layout(p)
        } else if self.cfg.channel_config != 0 {
            layout::default_layout(self.cfg.channel_config, false)
                .ok_or_else(|| Error::unsupported("aac: unsupported channel configuration"))?
        } else {
            return Ok(()); // layout learned from an in-band PCE
        };
        // A mono program carrying SBR may carry implicit PS: FFmpeg outputs it
        // as stereo, and so do we.
        let mono = map
            .iter()
            .map(|t| 1 + usize::from(t.syn_ele == TYPE_CPE) * usize::from(t.pos != 5))
            .sum::<usize>()
            <= 1;
        if !mono {
            self.ps_state = Some(false);
        } else if self.sbr_state == Some(true) && self.ps_state.is_none() {
            self.ps_state = Some(true);
        }
        self.output_configure(map);
        Ok(())
    }

    /// Positions for elements discovered in arrival order: a sequence matching a
    /// standard configuration takes that configuration's positions.
    fn discovered_layout(rows: Vec<Tag>) -> Vec<Tag> {
        for cc in [1u8, 2, 3, 4, 5, 6, 7] {
            if let Some(std_rows) = layout::default_layout(cc, false) {
                if std_rows.len() == rows.len()
                    && std_rows
                        .iter()
                        .zip(&rows)
                        .all(|(a, b)| a.syn_ele == b.syn_ele)
                {
                    return std_rows
                        .iter()
                        .zip(&rows)
                        .map(|(a, b)| Tag {
                            syn_ele: b.syn_ele,
                            id: b.id,
                            pos: a.pos,
                        })
                        .collect();
                }
            }
        }
        rows.into_iter()
            .map(|r| Tag {
                pos: if r.syn_ele == TYPE_LFE {
                    layout::POS_LFE
                } else if r.syn_ele == TYPE_CCE {
                    layout::POS_CC
                } else {
                    layout::POS_FRONT
                },
                ..r
            })
            .collect()
    }

    pub(crate) fn ps_on(&self) -> bool {
        self.ps_state == Some(true)
    }

    fn output_configure(&mut self, map: Vec<Tag>) {
        self.oc = OutputConfig::configure(map, self.ps_on());
        self.discovery = None;
        for ty in 0..4 {
            for iid in 0..16 {
                if self.oc.allocated[ty][iid] && self.elements[ty][iid].is_none() {
                    self.elements[ty][iid] = Some(Box::new(Element::new()));
                }
            }
        }
    }

    /// Whether an SBR fill payload has been seen (implicit HE-AAC signalling).
    #[must_use]
    pub fn saw_sbr(&self) -> bool {
        self.saw_sbr
    }

    /// The output channel count of the current configuration.
    #[must_use]
    pub fn channels(&self) -> usize {
        self.oc.channels()
    }

    fn instance(&self, ty: u8, iid: u8) -> Option<(usize, usize)> {
        let (t, i) = (ty as usize, iid as usize);
        if self.elements[t][i].is_some() {
            Some((t, i))
        } else {
            None
        }
    }

    /// `ff_aac_get_che`: route an element (type, tag) to its instance.
    fn get_che(&mut self, ty: u8, tag: u8) -> Option<(usize, usize)> {
        if let Some(rows) = self.discovery.as_mut() {
            let t = ty as usize;
            if self.oc.tag_to_instance[t][tag as usize].is_none() {
                let iid = rows.iter().filter(|r| r.syn_ele == ty).count() as u8;
                rows.push(Tag {
                    syn_ele: ty,
                    id: tag,
                    pos: layout::POS_FRONT,
                });
                self.oc.tag_to_instance[t][tag as usize] = Some(iid);
                if self.elements[t][iid as usize].is_none() {
                    self.elements[t][iid as usize] = Some(Box::new(Element::new()));
                }
            }
            let iid = self.oc.tag_to_instance[t][tag as usize]?;
            return self.instance(ty, iid);
        }
        if self.chan_config == 0 {
            let iid = self.oc.tag_to_instance[ty as usize][tag as usize]?;
            return self.instance(ty, iid);
        }
        if self.tags_mapped == 0 && ty == TYPE_CPE && self.chan_config == 1 {
            // Mono configuration carrying a CPE: decode as stereo.
            // Cannot fail: channel configuration 2 always has a default layout.
            self.output_configure(layout::default_layout(2, false).unwrap());
            self.chan_config = 2;
            self.ps_state = Some(false);
        }
        if self.tags_mapped == 0 && ty == TYPE_SCE && self.chan_config == 2 {
            // Stereo configuration carrying SCEs: two front SCEs.
            self.output_configure(vec![
                Tag {
                    syn_ele: TYPE_SCE,
                    id: 0,
                    pos: layout::POS_FRONT,
                },
                Tag {
                    syn_ele: TYPE_SCE,
                    id: 1,
                    pos: layout::POS_FRONT,
                },
            ]);
            if self.sbr_state == Some(true) {
                self.ps_state = None;
            }
        }
        let cc = self.chan_config;
        let tm = self.tags_mapped;
        let tags_per =
            |c: u8| -> usize { [0, 1, 1, 2, 3, 3, 4, 5, 0, 0, 0, 5, 5, 16, 5, 0][c as usize & 15] };
        let hit = |s: &mut Self, t: usize, i: usize| -> Option<(usize, usize)> {
            s.tags_mapped += 1;
            s.instance(t as u8, i as u8)
        };
        // The fall-through cascade of the reference's switch on chan_config.
        let level = match cc {
            14 => 0,
            13 => 1,
            12 | 7 => 2,
            11 => 3,
            6 => 4,
            5 => 5,
            4 => 6,
            3 | 2 => 7,
            1 => 8,
            _ => 9,
        };
        if level <= 0 && tm > 2 && ((ty == TYPE_CPE && tag < 3) || (ty == TYPE_LFE && tag < 1)) {
            return hit(self, ty as usize, tag as usize);
        }
        if level <= 1
            && tm > 3
            && ((ty == TYPE_CPE && tag < 8)
                || (ty == TYPE_SCE && tag < 6)
                || (ty == TYPE_LFE && tag < 2))
        {
            return hit(self, ty as usize, tag as usize);
        }
        if level <= 2 && tm == 3 && ty == TYPE_CPE {
            return hit(self, TYPE_CPE as usize, 2);
        }
        if level <= 3 && tm == 3 && ty == TYPE_SCE {
            return hit(self, TYPE_SCE as usize, 1);
        }
        if level <= 4 && tm + 1 == tags_per(cc) && (ty == TYPE_LFE || ty == TYPE_SCE) {
            return hit(self, TYPE_LFE as usize, 0);
        }
        if level <= 5 && tm == 2 && ty == TYPE_CPE {
            return hit(self, TYPE_CPE as usize, 1);
        }
        if level <= 6 {
            if tm + 1 == tags_per(cc) && (ty == TYPE_LFE || ty == TYPE_SCE) {
                return hit(self, TYPE_SCE as usize, 1);
            }
            if tm == 2 && cc == 4 && ty == TYPE_SCE {
                return hit(self, TYPE_SCE as usize, 1);
            }
        }
        if level <= 7 {
            if tm == usize::from(cc != 2) && ty == TYPE_CPE {
                return hit(self, TYPE_CPE as usize, 0);
            } else if tm == 1 && cc == 2 && ty == TYPE_SCE {
                return hit(self, TYPE_SCE as usize, 1);
            }
        }
        if level <= 8 && tm == 0 && ty == TYPE_SCE {
            return hit(self, TYPE_SCE as usize, 0);
        }
        None
    }

    fn el(&mut self, at: (usize, usize)) -> &mut Element {
        // Cannot fail: `at` comes from `get_che`, which returns only allocated slots (`instance`).
        self.elements[at.0][at.1].as_mut().unwrap()
    }

    /// Decode one access unit (`raw_data_block` or `er_raw_data_block`).
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidData`] for a malformed access unit and
    /// [`Error::Unsupported`] for a syntax element this decoder does not implement.
    /// The decoder stays usable: feed the next access unit.
    pub fn decode(&mut self, au: &[u8], pts: Option<i64>) -> Result<DecodedAudio> {
        Ok(self.decode_block(au, pts)?.0)
    }

    /// Decode one block and report how many bytes it occupied (byte-aligned
    /// after its `ID_END`), for containers that pack several per frame.
    ///
    /// # Errors
    ///
    /// As [`decode`](Self::decode).
    pub fn decode_block(&mut self, au: &[u8], pts: Option<i64>) -> Result<(DecodedAudio, usize)> {
        let mut r = BitReader::new(au);
        // Only elements parsed in THIS block may be rendered. A block that
        // fails part-way leaves its elements marked present with half-updated
        // state (e.g. a new long-window ICS beside the previous frame's
        // eight-window TNS); without this, a later block that does not carry
        // them rendered that mix and indexed past the spectrum (fuzz finding).
        // A successful block ends with every flag cleared already, so the walk
        // runs only after a failure.
        if self.partial {
            for el in self.elements.iter_mut().flatten().flatten() {
                el.present = false;
            }
        }
        self.partial = true;
        if self.cfg.is_er() {
            self.decode_er_frame(&mut r)?;
        } else {
            self.decode_ga_frame(&mut r)?;
        }
        self.partial = false;
        Ok((self.collect_output(pts), r.position().div_ceil(8)))
    }

    #[warn(
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss,
        clippy::cast_possible_wrap
    )]
    fn decode_ga_frame(&mut self, r: &mut BitReader) -> Result<()> {
        self.tags_mapped = 0;
        let mut presence = [[0u8; 16]; 4];
        let mut prev: Option<((usize, usize), u8)> = None;
        let mut audio_found = false;
        let mut pce_found = false;
        let payload_alignment = r.position();
        let sx = self.syntax;
        loop {
            let elem_type8 = r.read_u8(3)?;
            let elem_type = u32::from(elem_type8);
            if elem_type == ID_END {
                break;
            }
            let elem_id8 = r.read_u8(4)?;
            let mut elem_id = usize::from(elem_id8);
            if self.oc.channels() == 0 && elem_type != ID_PCE && self.discovery.is_none() {
                return Err(Error::invalid("aac: channel element before any layout"));
            }
            let mut at = None;
            if elem_type < ID_DSE {
                let p = &mut presence[elem_type as usize][elem_id];
                if *p > 1 {
                    return Err(Error::invalid("aac: duplicate channel element"));
                }
                *p += 1;
                at = Some(
                    self.get_che(elem_type8, elem_id8)
                        .ok_or_else(|| Error::invalid("aac: channel element is not allocated"))?,
                );
                // Cannot fail: `at` was set on the line above.
                self.el(at.unwrap()).present = true;
            }
            match elem_type {
                ID_SCE | ID_LFE => {
                    // Cannot fail: SCE/LFE are below ID_DSE, so `at` was set above.
                    let at = at.unwrap();
                    let rng = &mut self.rng;
                    // Cannot fail: `at` comes from `get_che`, which returns only allocated slots (`instance`).
                    // Cannot fail: `at` comes from `get_che`, which returns only allocated slots (`instance`).
                    let el = self.elements[at.0][at.1].as_mut().unwrap();
                    let sce = &mut el.ch[0];
                    decode_ics(r, &sx, &mut sce.ics, &mut sce.data, false, rng)?;
                    if sx.aot == aot::AAC_MAIN {
                        let (ics, data, pred, init) =
                            (&sce.ics, &mut sce.data, &mut sce.pred, &mut sce.pred_init);
                        tools::apply_prediction(ics, sx.sf_index, &mut data.coeffs, pred, init);
                    }
                    audio_found = true;
                }
                ID_CPE => {
                    // Cannot fail: CPE is below ID_DSE, so `at` was set above.
                    self.decode_cpe(r, at.unwrap())?;
                    audio_found = true;
                }
                // Cannot fail: CCE is below ID_DSE, so `at` was set above.
                ID_CCE => self.decode_cce(r, at.unwrap())?,
                ID_DSE => {
                    let align = r.read_bool()?;
                    let mut count = r.read_bits(8)? as usize;
                    if count == 255 {
                        count += r.read_bits(8)? as usize;
                    }
                    if align {
                        r.byte_align();
                    }
                    r.skip(8 * count)?;
                }
                ID_PCE => {
                    let p = crate::config::Pce::parse_after_tag(r, elem_id8, payload_alignment)?;
                    if !pce_found {
                        self.output_configure(layout::pce_layout(&p));
                        self.chan_config = 0;
                        pce_found = true;
                    }
                }
                ID_FIL => {
                    if elem_id == 15 {
                        // `cnt = 15 + esc_count - 1` (ISO 14496-3 §4.4.2.7). Add
                        // first: `esc as usize - 1` underflowed for esc = 0, a
                        // panic in any build with overflow checks.
                        elem_id += r.read_bits(8)? as usize;
                        elem_id -= 1;
                    }
                    if r.bits_left() < 8 * elem_id {
                        return Err(Error::invalid("aac: fill element overruns the frame"));
                    }
                    let mut cnt = elem_id;
                    while cnt > 0 {
                        let used = self.decode_extension_payload(r, cnt, prev)?;
                        cnt = cnt.saturating_sub(used.max(1));
                    }
                }
                _ => unreachable!(),
            }
            if elem_type < ID_DSE {
                // Cannot fail: guarded by `elem_type < ID_DSE`, the same condition that set `at`.
                prev = Some((at.unwrap(), elem_type8));
            }
            if r.bits_left() < 3 {
                return Err(Error::invalid("aac: frame ends before ID_END"));
            }
        }
        if let Some(rows) = self.discovery.take() {
            if rows.is_empty() {
                self.discovery = Some(rows);
            } else {
                self.output_configure(Self::discovered_layout(rows));
            }
        }
        if self.oc.channels() == 0 {
            return Err(Error::Again);
        }
        self.spectral_to_sample();
        if audio_found {
            self.locked = true;
        }
        Ok(())
    }

    #[warn(
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss,
        clippy::cast_possible_wrap
    )]
    fn decode_er_frame(&mut self, r: &mut BitReader) -> Result<()> {
        self.tags_mapped = 0;
        let cc = self.chan_config;
        let rows = layout::default_layout(cc, false)
            .ok_or_else(|| Error::unsupported("aac: unknown ER channel configuration"))?;
        let sx = self.syntax;
        for row in rows {
            let at = self
                .get_che(row.syn_ele, row.id)
                .ok_or_else(|| Error::invalid("aac: channel element is not allocated"))?;
            self.el(at).present = true;
            if !sx.eld() {
                r.skip(4)?;
            }
            if row.syn_ele == TYPE_CPE {
                self.decode_cpe(r, at)?;
            } else {
                let rng = &mut self.rng;
                // Cannot fail: `at` comes from `get_che`, which returns only allocated slots (`instance`).
                // Cannot fail: `at` comes from `get_che`, which returns only allocated slots (`instance`).
                let el = self.elements[at.0][at.1].as_mut().unwrap();
                let sce = &mut el.ch[0];
                decode_ics(r, &sx, &mut sce.ics, &mut sce.data, false, rng)?;
            }
        }
        // An ELD frame with low-delay SBR carries the LD-SBR payload after the
        // channel elements. It is not reconstructed (it needs the complex
        // low-delay filterbank); the core is output at the core rate.
        self.spectral_to_sample();
        self.locked = true;
        Ok(())
    }

    #[warn(
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss,
        clippy::cast_possible_wrap
    )]
    fn decode_cpe(&mut self, r: &mut BitReader, at: (usize, usize)) -> Result<()> {
        let sx = self.syntax;
        let rng = &mut self.rng;
        // Cannot fail: `at` comes from `get_che`, which returns only allocated slots (`instance`).
        // Cannot fail: `at` comes from `get_che`, which returns only allocated slots (`instance`).
        let el = self.elements[at.0][at.1].as_mut().unwrap();
        let common_window = sx.eld() || r.read_bool()?;
        el.common_window = common_window;
        el.ms_present = 0;
        if common_window {
            parse_ics_info(r, &sx, &mut el.ch[0].ics)?;
            let kbd1 = el.ch[1].ics.info.window_shape_kbd;
            // Channel 1 takes channel 0's ICS, its grouping copied into the
            // Vec channel 1 already owns (a plain clone allocated a new one
            // and freed the old every CPE frame).
            let g0 = std::mem::take(&mut el.ch[0].ics.info.window_group_length);
            let mut g1 = std::mem::take(&mut el.ch[1].ics.info.window_group_length);
            g1.clone_from(&g0);
            el.ch[1].ics = el.ch[0].ics.clone();
            el.ch[0].ics.info.window_group_length = g0;
            el.ch[1].ics.info.window_group_length = g1;
            el.ch[1].ics.prev_kbd = kbd1;
            if el.ch[1].ics.predictor_present && sx.aot != aot::AAC_MAIN {
                el.ch[1].ics.ltp.present = r.read_bool()?;
                if el.ch[1].ics.ltp.present {
                    let m = el.ch[1].ics.info.max_sfb as usize;
                    decode_ltp(r, &mut el.ch[1].ics.ltp, m)?;
                }
            }
            let msp = r.read_u8(2)?;
            if msp == 3 {
                return Err(Error::invalid("aac: ms_mask_present = 3 is reserved"));
            }
            el.ms_present = msp;
            let info = &el.ch[0].ics.info;
            let n = info.num_window_groups * info.max_sfb as usize;
            for i in 0..n {
                el.ms_mask[i] = match msp {
                    1 => r.read_bool()?,
                    2 => true,
                    _ => false,
                };
            }
        }
        {
            let [c0, c1] = &mut el.ch;
            decode_ics(r, &sx, &mut c0.ics, &mut c0.data, common_window, rng)?;
            decode_ics(r, &sx, &mut c1.ics, &mut c1.data, common_window, rng)?;
        }
        if common_window {
            if el.ms_present != 0 {
                let [c0, c1] = &mut el.ch;
                tools::apply_ms(&c0.ics, &el.ms_mask, &mut c0.data, &mut c1.data);
            }
            if sx.aot == aot::AAC_MAIN {
                for c in &mut el.ch {
                    let (ics, data, pred, init) =
                        (&c.ics, &mut c.data, &mut c.pred, &mut c.pred_init);
                    tools::apply_prediction(ics, sx.sf_index, &mut data.coeffs, pred, init);
                }
            }
        } else if sx.aot == aot::AAC_MAIN {
            for c in &mut el.ch {
                let (ics, data, pred, init) = (&c.ics, &mut c.data, &mut c.pred, &mut c.pred_init);
                tools::apply_prediction(ics, sx.sf_index, &mut data.coeffs, pred, init);
            }
        }
        let [c0, c1] = &mut el.ch;
        tools::apply_is(
            &c1.ics,
            el.ms_present != 0,
            &el.ms_mask,
            &c0.data,
            &mut c1.data,
        );
        Ok(())
    }

    #[warn(
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss,
        clippy::cast_possible_wrap
    )]
    fn decode_cce(&mut self, r: &mut BitReader, at: (usize, usize)) -> Result<()> {
        let sx = self.syntax;
        let rng = &mut self.rng;
        // Cannot fail: `at` comes from `get_che`, which returns only allocated slots (`instance`).
        // Cannot fail: `at` comes from `get_che`, which returns only allocated slots (`instance`).
        let el = self.elements[at.0][at.1].as_mut().unwrap();
        let mut point = 2 * r.read_u8(1)?;
        let num_coupled = r.read_bits(3)? as usize;
        let mut num_gain = 0usize;
        let mut targets = Vec::new();
        for _ in 0..=num_coupled {
            num_gain += 1;
            let is_cpe = r.read_bool()?;
            let id = r.read_u8(4)?;
            let ch_select = if is_cpe {
                let s = r.read_u8(2)?;
                if s == 3 {
                    num_gain += 1;
                }
                s
            } else {
                2
            };
            targets.push((if is_cpe { TYPE_CPE } else { TYPE_SCE }, id, ch_select));
        }
        point += u8::from(r.read_bool()? || (point >> 1) != 0);
        let sign = r.read_bool()?;
        let scale =
            [1.090_507_7f32, 1.189_207_1, std::f32::consts::SQRT_2, 2.0][r.read_bits(2)? as usize];
        decode_ics(r, &sx, &mut el.ch[0].ics, &mut el.ch[0].data, false, rng)?;
        let info = el.ch[0].ics.info.clone();
        let max_sfb = info.max_sfb as usize;
        let mut gains = vec![vec![0f32; 128]; num_gain];
        for (c, gc) in gains.iter_mut().enumerate() {
            let mut cge = true;
            let mut gain = 0i32;
            let mut gain_cache = 1.0f32;
            if c > 0 {
                cge = if point == tools::AFTER_IMDCT {
                    true
                } else {
                    r.read_bool()?
                };
                gain = if cge {
                    i32::from(SCALEFACTOR_BOOK.decode(r)?) - 60
                } else {
                    0
                };
                gain_cache = scale.powf(-(gain as f32));
            }
            if point == tools::AFTER_IMDCT {
                gc[0] = gain_cache;
            } else {
                for g in 0..info.num_window_groups {
                    for sfb in 0..max_sfb {
                        let idx = g * max_sfb + sfb;
                        if el.ch[0].data.band_type[idx] != 0 {
                            if !cge {
                                let mut t = i32::from(SCALEFACTOR_BOOK.decode(r)?) - 60;
                                if t != 0 {
                                    let mut s = 1.0f32;
                                    gain += t;
                                    t = gain;
                                    if sign {
                                        s -= 2.0 * (t & 1) as f32;
                                        t >>= 1;
                                    }
                                    gain_cache = scale.powf(-(t as f32)) * s;
                                }
                            }
                            gc[idx] = gain_cache;
                        }
                    }
                }
            }
        }
        el.coup = Coupling {
            point,
            targets,
            gains,
        };
        Ok(())
    }

    /// `extension_payload` inside a fill element. Returns bytes consumed.
    #[warn(
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss,
        clippy::cast_possible_wrap
    )]
    fn decode_extension_payload(
        &mut self,
        r: &mut BitReader,
        cnt: usize,
        prev: Option<((usize, usize), u8)>,
    ) -> Result<usize> {
        let start = r.position();
        let ext = r.read_bits(4)?;
        match ext {
            EXT_SBR_DATA | EXT_SBR_DATA_CRC => {
                self.saw_sbr = true;
                let Some((at, prev_type)) = prev else {
                    r.skip(8 * cnt - 4)?;
                    return Ok(cnt);
                };
                if self.sbr_state == Some(false) {
                    r.skip(8 * cnt - 4)?;
                    return Ok(cnt);
                }
                if self.sbr_state.is_none() {
                    if self.locked {
                        // Implicit SBR first seen after the first frame: ignored.
                        r.skip(8 * cnt - 4)?;
                        return Ok(cnt);
                    }
                    self.sbr_state = Some(true);
                    if self.ps_state.is_none()
                        && self.oc.channels() == 1
                        && self.cfg.object_type == aot::AAC_LC
                    {
                        self.ps_state = Some(true);
                        let map = self.oc.map.clone();
                        self.output_configure(map);
                    }
                }
                // Hand the raw payload to the SBR stage.
                let bits = 8 * cnt - 4;
                let mut payload = Vec::with_capacity(cnt);
                let mut left = bits;
                while left >= 8 {
                    payload.push(r.read_u8(8)?);
                    left -= 8;
                }
                if left > 0 {
                    // `left` < 8 here, so the shifted value fills one byte exactly.
                    payload.push(r.read_u8(u32::try_from(left).unwrap_or(7))? << (8 - left));
                }
                let el = self.el(at);
                el.sbr_payload = Some((payload, bits, ext == EXT_SBR_DATA_CRC));
                let _ = prev_type;
                Ok(cnt)
            }
            EXT_DYNAMIC_RANGE => {
                // Parsed for its length; DRC is metadata and not applied (as
                // in the reference decoder's default configuration).
                let mut n = 1usize;
                if r.read_bool()? {
                    r.skip(8)?;
                    n += 1;
                }
                if r.read_bool()? {
                    let mut k = 0;
                    loop {
                        r.skip(7)?;
                        k += 7;
                        if k >= 64 - 7 || !r.read_bool()? {
                            break;
                        }
                    }
                    n += k / 7;
                }
                let mut bands = 1usize;
                if r.read_bool()? {
                    let incr = r.read_bits(4)? as usize;
                    r.skip(4)?;
                    n += 1;
                    bands += incr;
                    r.skip(8 * bands)?;
                    n += bands;
                }
                if r.read_bool()? {
                    r.skip(8)?;
                    n += 1;
                }
                r.skip(8 * bands)?;
                n += bands;
                Ok(n)
            }
            _ => {
                let _ = start;
                r.skip(8 * cnt - 4)?;
                Ok(cnt)
            }
        }
    }

    fn frame_samples(&self) -> usize {
        self.syntax.frame_len
    }

    /// `spectral_to_sample`: tools + synthesis for every element, in the
    /// reference's order (LFE, CCE, CPE, SCE; coupling interleaved).
    fn spectral_to_sample(&mut self) {
        let sx = self.syntax;
        let n = self.frame_samples();
        let sbr_on = self.sbr_active();
        for ty in (0..4usize).rev() {
            for id in 0..16usize {
                let Some(el) = self.elements[ty][id].as_ref() else {
                    continue;
                };
                if !el.present {
                    // Cannot fail: the `let Some(el) = ... else { continue }` above checked this slot.
                    let el = self.elements[ty][id].as_mut().unwrap();
                    for c in &mut el.ch {
                        c.output.iter_mut().for_each(|v| *v = 0.0);
                    }
                    continue;
                }
                let is_cce = ty == TYPE_CCE as usize;
                if ty <= TYPE_CPE as usize {
                    self.apply_coupling(ty, id, tools::BEFORE_TNS);
                }
                // Cannot fail: the slot was checked above and every take is restored before the next.
                let mut el = self.elements[ty][id].take().unwrap();
                if sx.aot == aot::AAC_LTP && el.ch[0].ics.predictor_present {
                    let nch = if ty == TYPE_CPE as usize { 2 } else { 1 };
                    for c in 0..nch {
                        if el.ch[c].ics.ltp.present {
                            self.apply_ltp(&mut el.ch[c]);
                        }
                    }
                }
                for c in &mut el.ch {
                    if c.data.tns.present {
                        let (data, ics) = (&mut c.data, &c.ics);
                        tools::apply_tns(&mut data.coeffs, &data.tns, ics, true);
                    }
                }
                self.elements[ty][id] = Some(el);
                if ty <= TYPE_CPE as usize {
                    self.apply_coupling(ty, id, tools::BETWEEN_TNS_AND_IMDCT);
                }
                // Cannot fail: the slot was checked above and every take is restored before the next.
                let mut el = self.elements[ty][id].take().unwrap();
                if !is_cce || el.coup.point == tools::AFTER_IMDCT {
                    let nch = if ty == TYPE_CPE as usize { 2 } else { 1 };
                    for c in 0..nch {
                        self.synthesize(&mut el.ch[c]);
                    }
                    if sbr_on {
                        crate::sbr::dec::apply(self, &mut el, ty as u8, n);
                    }
                }
                self.elements[ty][id] = Some(el);
                if ty <= TYPE_CCE as usize {
                    self.apply_coupling(ty, id, tools::AFTER_IMDCT);
                }
                // Cannot fail: the element was restored to its slot just above.
                self.elements[ty][id].as_mut().unwrap().present = false;
            }
        }
    }

    fn apply_coupling(&mut self, ty: usize, id: usize, point: u8) {
        for i in 0..16 {
            let Some(cce) = self.elements[TYPE_CCE as usize][i].as_ref() else {
                continue;
            };
            if cce.coup.point != point || cce.coup.targets.is_empty() {
                continue;
            }
            let cce = cce.clone();
            let mut index = 0usize;
            for &(t, eid, sel) in &cce.coup.targets {
                if t as usize == ty && eid as usize == id {
                    // Cannot fail: coupling runs only on a present element, which occupies this slot.
                    let target = self.elements[ty][id].as_mut().unwrap();
                    if sel != 1 {
                        Self::couple(&cce, index, point, &mut target.ch[0]);
                        if sel != 0 {
                            index += 1;
                        }
                    }
                    if sel != 2 {
                        Self::couple(&cce, index, point, &mut target.ch[1]);
                        index += 1;
                    }
                } else {
                    index += 1 + usize::from(sel == 3);
                }
            }
        }
    }

    fn couple(cce: &Element, index: usize, point: u8, target: &mut Sce) {
        let Some(gains) = cce.coup.gains.get(index) else {
            return;
        };
        if point == tools::AFTER_IMDCT {
            let g = gains[0];
            for (d, s) in target.output.iter_mut().zip(cce.ch[0].output.iter()) {
                *d += g * s;
            }
        } else {
            tools::apply_dependent_coupling(
                &cce.ch[0].ics,
                &cce.ch[0].data,
                gains,
                &mut target.data.coeffs,
            );
        }
    }

    fn apply_ltp(&self, sce: &mut Sce) {
        if sce.ics.info.window_sequence == WindowSequence::EightShort {
            return;
        }
        let ltp = sce.ics.ltp;
        let mut pred_time = vec![0f32; 2048];
        let num = if ltp.lag < 1024 { ltp.lag + 1024 } else { 2048 };
        for (i, p) in pred_time.iter_mut().enumerate().take(num) {
            let src = i + 2048 - ltp.lag;
            *p = sce.ltp_state.get(src).copied().unwrap_or(0.0) * ltp.coef;
        }
        let si = synth::SynthIn {
            coeffs: &[],
            seq: sce.ics.info.window_sequence,
            prev_seq: sce.ics.prev_seq,
            kbd: sce.ics.info.window_shape_kbd,
            prev_kbd: sce.ics.prev_kbd,
        };
        let mut pred_freq = synth::ltp_analysis(&self.windows, &si, &mut pred_time);
        if sce.data.tns.present {
            tools::apply_tns(&mut pred_freq, &sce.data.tns, &sce.ics, false);
        }
        for sfb in 0..(sce.ics.info.max_sfb as usize).min(channel::MAX_LTP_LONG_SFB) {
            if ltp.used[sfb] {
                for i in sce.ics.swb[sfb] as usize..sce.ics.swb[sfb + 1] as usize {
                    sce.data.coeffs[i] += pred_freq[i];
                }
            }
        }
    }

    fn synthesize(&mut self, sce: &mut Sce) {
        let _prof = crate::prof::scope(crate::prof::Stage::DecImdct);
        let sx = self.syntax;
        let n = sx.frame_len;
        match sx.aot {
            aot::ER_AAC_LD => {
                // Disjoint field borrows: cloning both windows (two Vec copies
                // per channel per frame) only dodged borrowing `self.buf`.
                let (ld_sine, lo) = (&self.ld_sine, &self.ld_low_overlap);
                synth::imdct_and_window_ld(
                    ld_sine,
                    lo,
                    n,
                    &sce.data.coeffs,
                    sce.ics.prev_kbd,
                    &mut self.buf,
                    &mut sce.saved,
                    &mut sce.output,
                );
            }
            aot::ER_AAC_ELD => {
                let window: &[f32] = if n == 480 {
                    &crate::tables_ext::ELD_WINDOW_480
                } else {
                    &crate::tables_ext::ELD_WINDOW_512
                };
                synth::imdct_and_window_eld(
                    window,
                    n,
                    &mut sce.data.coeffs,
                    &mut self.buf,
                    &mut sce.saved,
                    &mut sce.output,
                );
            }
            _ => {
                let si = synth::SynthIn {
                    coeffs: &sce.data.coeffs,
                    seq: sce.ics.info.window_sequence,
                    prev_seq: sce.ics.prev_seq,
                    kbd: sce.ics.info.window_shape_kbd,
                    prev_kbd: sce.ics.prev_kbd,
                };
                synth::imdct_and_window(
                    &self.windows,
                    n,
                    &si,
                    &mut self.buf,
                    &mut sce.saved,
                    &mut sce.output,
                );
                if sx.aot == aot::AAC_LTP {
                    let (seq, kbd) = (sce.ics.info.window_sequence, sce.ics.info.window_shape_kbd);
                    synth::ltp_update(
                        &self.windows,
                        seq,
                        kbd,
                        &self.buf,
                        &sce.saved,
                        &sce.output,
                        &mut sce.ltp_state,
                    );
                }
            }
        }
    }

    /// The SBR output rate: the signalled extension rate, or twice the core
    /// rate when SBR was found implicitly. Equal to the core rate for
    /// downsampled SBR.
    pub(crate) fn sbr_ext_rate(&self) -> u32 {
        if self.cfg.sbr || self.cfg.ext_rate_signalled {
            self.cfg.ext_sample_rate
        } else {
            2 * self.cfg.sample_rate
        }
    }

    /// SBR is reconstructed for this stream (ELD's low-delay SBR is not).
    pub(crate) fn sbr_active(&self) -> bool {
        self.sbr_state == Some(true) && !self.syntax.eld()
    }

    /// Output samples per channel for this frame (doubled by dual-rate SBR).
    pub(crate) fn output_len(&self) -> usize {
        let n = self.frame_samples();
        if self.sbr_active() && self.sbr_ext_rate() > self.cfg.sample_rate {
            2 * n
        } else {
            n
        }
    }

    /// The current output sample rate.
    #[must_use]
    pub fn output_sample_rate(&self) -> u32 {
        if self.output_len() > self.frame_samples() {
            self.cfg.sample_rate * 2
        } else {
            self.cfg.sample_rate
        }
    }

    fn collect_output(&self, pts: Option<i64>) -> DecodedAudio {
        let _prof = crate::prof::scope(crate::prof::Stage::DecOutput);
        let n = self.output_len();
        let outs = &self.oc.outputs;
        let nch = outs.len();
        // A missing element is silence: the zero fill stands for it.
        let mut samples = vec![0f32; n * nch];
        let chan = |&(ty, iid, sub): &(u8, u8, u8)| -> Option<&[f32]> {
            self.elements[ty as usize][iid as usize]
                .as_ref()
                .map(|e| &e.ch[sub as usize].output[..n])
        };
        // Whole-slice interleaves (no per-sample push / capacity check), with
        // the common layouts spelled out so they vectorise.
        match outs.as_slice() {
            [a] => {
                if let Some(a) = chan(a) {
                    samples.copy_from_slice(a);
                }
            }
            [a, b] => {
                if let (Some(a), Some(b)) = (chan(a), chan(b)) {
                    for ((d, &l), &r) in samples.chunks_exact_mut(2).zip(a).zip(b) {
                        d[0] = l;
                        d[1] = r;
                    }
                } else {
                    for (c, o) in outs.iter().enumerate() {
                        if let Some(src) = chan(o) {
                            for (d, &v) in samples[c..].iter_mut().step_by(nch).zip(src) {
                                *d = v;
                            }
                        }
                    }
                }
            }
            _ => {
                for (c, o) in outs.iter().enumerate() {
                    if let Some(src) = chan(o) {
                        for (d, &v) in samples[c..].iter_mut().step_by(nch).zip(src) {
                            *d = v;
                        }
                    }
                }
            }
        }
        DecodedAudio {
            sample_rate: self.output_sample_rate(),
            channels: outs.len() as u16,
            samples,
            pts,
        }
    }
}