Skip to main content

usbdac_core/descriptors/
uac3.rs

1//! Independent ADC 3.0 / Basic Audio Device Definition 3.0 descriptor decoding.
2//!
3//! Layouts follow USB-IF ADC3 sections 4.3, 4.5 and 4.7 and BADD sections 4 and 8.
4//! This module performs no USB requests. In particular, a cluster's six-byte HC
5//! header must be checked before allocating its body and checked again on receipt.
6use super::{DescriptorError, Iad};
7
8fn invalid(message: &str) -> DescriptorError {
9    DescriptorError::Invalid(format!("UAC3: {message}"))
10}
11fn le16(d: &[u8], at: usize) -> u16 {
12    u16::from_le_bytes([d[at], d[at + 1]])
13}
14fn le32(d: &[u8], at: usize) -> u32 {
15    u32::from_le_bytes([d[at], d[at + 1], d[at + 2], d[at + 3]])
16}
17fn descriptor(d: &[u8], subtype: u8, length: usize) -> Result<&[u8], DescriptorError> {
18    if d.len() < length || d[0] as usize != length || d[1] != 0x24 || d[2] != subtype {
19        return Err(invalid("wrong descriptor length, type or subtype"));
20    }
21    Ok(&d[..length])
22}
23fn entity(id: u8) -> Result<u8, DescriptorError> {
24    if id == 0 {
25        Err(invalid("zero entity ID"))
26    } else {
27        Ok(id)
28    }
29}
30
31/// ADC3 controls use two bits per selector and retain their full 32-bit width.
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub struct Controls(pub u32);
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub enum ControlAccess {
36    Absent,
37    ReadOnly,
38    ReadWrite,
39    Reserved,
40}
41impl Controls {
42    pub fn access(self, selector: u8) -> ControlAccess {
43        if !(1..=16).contains(&selector) {
44            return ControlAccess::Absent;
45        }
46        match (self.0 >> (2 * (selector - 1))) & 3 {
47            0 => ControlAccess::Absent,
48            1 => ControlAccess::ReadOnly,
49            3 => ControlAccess::ReadWrite,
50            _ => ControlAccess::Reserved,
51        }
52    }
53}
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub struct AsHeader {
56    pub terminal_link: u8,
57    pub controls: Controls,
58    pub cluster_id: u16,
59    pub formats: u64,
60    pub subslot_size: u8,
61    pub bit_resolution: u8,
62    pub auxiliary_protocols: u16,
63    pub control_size: u8,
64}
65pub fn parse_as_header(data: &[u8]) -> Result<AsHeader, DescriptorError> {
66    let d = descriptor(data, 1, 23)?;
67    entity(d[3])?;
68    if le16(d, 8) == 0 {
69        return Err(invalid("zero AS cluster ID"));
70    }
71    let formats = u64::from_le_bytes(d[10..18].try_into().unwrap());
72    if formats == 0 || d[18] == 0 || d[19] == 0 || u16::from(d[19]) > u16::from(d[18]) * 8 {
73        return Err(invalid("invalid AS format geometry"));
74    }
75    Ok(AsHeader {
76        terminal_link: d[3],
77        controls: Controls(le32(d, 4)),
78        cluster_id: le16(d, 8),
79        formats,
80        subslot_size: d[18],
81        bit_resolution: d[19],
82        auxiliary_protocols: le16(d, 20),
83        control_size: d[22],
84    })
85}
86
87/// Decode the union of an alternate's ADC3 AS valid frequency ranges (ยง4.7.3).
88/// An empty result means the alternate imposes no additional clock restriction.
89pub(crate) fn parse_as_frequency_ranges(extra: &[u8]) -> Result<Vec<(u32, u32)>, DescriptorError> {
90    let mut ranges = Vec::new();
91    let mut remaining = extra;
92    while !remaining.is_empty() {
93        if remaining.len() < 2 {
94            return Err(invalid("truncated AS descriptor header"));
95        }
96        let length = usize::from(remaining[0]);
97        if length < 2 || length > remaining.len() {
98            return Err(invalid("invalid AS descriptor length"));
99        }
100        let d = &remaining[..length];
101        if d[1] == 0x24 {
102            if length < 3 {
103                return Err(invalid("missing AS descriptor subtype"));
104            }
105            if d[2] == 0x02 {
106                if length != 11 {
107                    return Err(invalid("invalid AS valid frequency range length"));
108                }
109                let min = le32(d, 3);
110                let max = le32(d, 7);
111                if min == 0 || max < min {
112                    return Err(invalid("invalid AS valid frequency range bounds"));
113                }
114                ranges.push((min, max));
115            }
116        }
117        remaining = &remaining[length..];
118    }
119
120    ranges.sort_unstable();
121    let mut normalized: Vec<(u32, u32)> = Vec::with_capacity(ranges.len());
122    for (min, max) in ranges {
123        if let Some(previous) = normalized.last_mut() {
124            if min <= previous.1.saturating_add(1) {
125                previous.1 = previous.1.max(max);
126                continue;
127            }
128        }
129        normalized.push((min, max));
130    }
131    Ok(normalized)
132}
133
134#[cfg(test)]
135mod as_frequency_range_tests {
136    use super::parse_as_frequency_ranges;
137
138    fn wire_range(min: u32, max: u32) -> Vec<u8> {
139        let mut bytes = vec![11, 0x24, 0x02];
140        bytes.extend_from_slice(&min.to_le_bytes());
141        bytes.extend_from_slice(&max.to_le_bytes());
142        bytes
143    }
144
145    #[test]
146    fn omitted_ranges_are_unconstrained_and_unrelated_descriptors_are_ignored() {
147        assert_eq!(parse_as_frequency_ranges(&[]).unwrap(), vec![]);
148        assert_eq!(
149            parse_as_frequency_ranges(&[3, 0x24, 1, 2, 0x25]).unwrap(),
150            vec![]
151        );
152    }
153
154    #[test]
155    fn little_endian_bounds_are_inclusive_and_keep_disjoint_gaps() {
156        let mut bytes = vec![3, 0x24, 1];
157        bytes.extend(wire_range(96_000, 192_000));
158        bytes.extend(wire_range(44_100, 48_000));
159        bytes.extend(wire_range(22_050, 22_050));
160        assert_eq!(
161            parse_as_frequency_ranges(&bytes).unwrap(),
162            vec![(22_050, 22_050), (44_100, 48_000), (96_000, 192_000)]
163        );
164    }
165
166    #[test]
167    fn overlapping_adjacent_and_duplicate_ranges_form_a_canonical_union() {
168        let mut bytes = wire_range(48_001, 96_000);
169        bytes.extend(wire_range(44_100, 48_000));
170        bytes.extend(wire_range(47_000, 50_000));
171        bytes.extend(wire_range(44_100, 48_000));
172        bytes.extend(wire_range(u32::MAX, u32::MAX));
173        bytes.extend(wire_range(u32::MAX - 1, u32::MAX));
174        assert_eq!(
175            parse_as_frequency_ranges(&bytes).unwrap(),
176            vec![(44_100, 96_000), (u32::MAX - 1, u32::MAX)]
177        );
178    }
179
180    #[test]
181    fn zero_and_reversed_bounds_are_rejected() {
182        for (min, max) in [(0, 0), (0, 48_000), (48_000, 44_100)] {
183            assert!(parse_as_frequency_ranges(&wire_range(min, max)).is_err());
184        }
185    }
186
187    #[test]
188    fn malformed_descriptor_streams_are_rejected_even_after_a_valid_range() {
189        let valid = wire_range(44_100, 48_000);
190        for prefix_length in 1..valid.len() {
191            assert!(parse_as_frequency_ranges(&valid[..prefix_length]).is_err());
192        }
193        for suffix in [
194            vec![0],
195            vec![0, 0x24],
196            vec![1, 0x24],
197            vec![2, 0x24],
198            vec![3, 0x25],
199            vec![3, 0x24, 0x02],
200            vec![12, 0x24, 0x02, 1, 0, 0, 0, 2, 0, 0, 0, 0],
201        ] {
202            let mut bytes = valid.clone();
203            bytes.extend(suffix);
204            assert!(parse_as_frequency_ranges(&bytes).is_err());
205        }
206    }
207}
208
209#[derive(Debug, Clone, PartialEq, Eq)]
210pub struct AcHeader {
211    pub category: u8,
212    pub total_length: u16,
213    pub controls: Controls,
214}
215pub fn parse_ac_header(data: &[u8]) -> Result<AcHeader, DescriptorError> {
216    let d = descriptor(data, 1, 10)?;
217    if le16(d, 4) < 10 {
218        return Err(invalid("AC total length shorter than header"));
219    }
220    Ok(AcHeader {
221        category: d[3],
222        total_length: le16(d, 4),
223        controls: Controls(le32(d, 6)),
224    })
225}
226#[derive(Debug, Clone, PartialEq, Eq)]
227pub struct InputTerminal {
228    pub id: u8,
229    pub terminal_type: u16,
230    pub associated_terminal: u8,
231    pub clock_id: u8,
232    pub controls: Controls,
233    pub cluster_id: u16,
234    pub extended_terminal_id: u16,
235    pub connectors_id: u16,
236    pub string_id: u16,
237}
238pub fn parse_input_terminal(data: &[u8]) -> Result<InputTerminal, DescriptorError> {
239    let d = descriptor(data, 2, 20)?;
240    entity(d[3])?;
241    entity(d[7])?;
242    if le16(d, 12) == 0 {
243        return Err(invalid("zero terminal cluster ID"));
244    }
245    Ok(InputTerminal {
246        id: d[3],
247        terminal_type: le16(d, 4),
248        associated_terminal: d[6],
249        clock_id: d[7],
250        controls: Controls(le32(d, 8)),
251        cluster_id: le16(d, 12),
252        extended_terminal_id: le16(d, 14),
253        connectors_id: le16(d, 16),
254        string_id: le16(d, 18),
255    })
256}
257#[derive(Debug, Clone, PartialEq, Eq)]
258pub struct OutputTerminal {
259    pub id: u8,
260    pub terminal_type: u16,
261    pub associated_terminal: u8,
262    pub source_id: u8,
263    pub clock_id: u8,
264    pub controls: Controls,
265    pub extended_terminal_id: u16,
266    pub connectors_id: u16,
267    pub string_id: u16,
268}
269pub fn parse_output_terminal(data: &[u8]) -> Result<OutputTerminal, DescriptorError> {
270    let d = descriptor(data, 3, 19)?;
271    entity(d[3])?;
272    entity(d[7])?;
273    entity(d[8])?;
274    Ok(OutputTerminal {
275        id: d[3],
276        terminal_type: le16(d, 4),
277        associated_terminal: d[6],
278        source_id: d[7],
279        clock_id: d[8],
280        controls: Controls(le32(d, 9)),
281        extended_terminal_id: le16(d, 13),
282        connectors_id: le16(d, 15),
283        string_id: le16(d, 17),
284    })
285}
286#[derive(Debug, Clone, PartialEq, Eq)]
287pub struct ClockSource {
288    pub id: u8,
289    pub attributes: u8,
290    pub controls: Controls,
291    pub reference_terminal: u8,
292    pub string_id: u16,
293}
294impl ClockSource {
295    pub fn is_internal(&self) -> bool {
296        self.attributes & 1 != 0
297    }
298    pub fn is_synchronous_to_sof(&self) -> bool {
299        self.attributes & 2 != 0
300    }
301}
302pub fn parse_clock_source(data: &[u8]) -> Result<ClockSource, DescriptorError> {
303    let d = descriptor(data, 0x0b, 12)?;
304    entity(d[3])?;
305    if d[4] & !3 != 0 || d[4] == 2 {
306        return Err(invalid("invalid ADC3 clock attributes"));
307    }
308    Ok(ClockSource {
309        id: d[3],
310        attributes: d[4],
311        controls: Controls(le32(d, 5)),
312        reference_terminal: d[9],
313        string_id: le16(d, 10),
314    })
315}
316#[derive(Debug, Clone, PartialEq, Eq)]
317pub struct ClockSelector {
318    pub id: u8,
319    pub sources: Vec<u8>,
320    pub controls: Controls,
321    pub string_id: u16,
322}
323pub fn parse_clock_selector(data: &[u8]) -> Result<ClockSelector, DescriptorError> {
324    if data.len() < 5 || data[4] == 0 {
325        return Err(invalid("missing clock selector pins"));
326    }
327    let n = data[4] as usize;
328    let d = descriptor(data, 0x0c, 11 + n)?;
329    entity(d[3])?;
330    for &id in &d[5..5 + n] {
331        entity(id)?;
332    }
333    Ok(ClockSelector {
334        id: d[3],
335        sources: d[5..5 + n].to_vec(),
336        controls: Controls(le32(d, 5 + n)),
337        string_id: le16(d, 9 + n),
338    })
339}
340#[derive(Debug, Clone, PartialEq, Eq)]
341pub struct ClockMultiplier {
342    pub id: u8,
343    pub source_id: u8,
344    pub controls: Controls,
345    pub string_id: u16,
346}
347pub fn parse_clock_multiplier(data: &[u8]) -> Result<ClockMultiplier, DescriptorError> {
348    let d = descriptor(data, 0x0d, 11)?;
349    entity(d[3])?;
350    entity(d[4])?;
351    Ok(ClockMultiplier {
352        id: d[3],
353        source_id: d[4],
354        controls: Controls(le32(d, 5)),
355        string_id: le16(d, 9),
356    })
357}
358#[derive(Debug, Clone, PartialEq, Eq)]
359pub struct PowerDomain {
360    pub id: u8,
361    pub recovery_d1: u16,
362    pub recovery_d2: u16,
363    pub entities: Vec<u8>,
364    pub string_id: u16,
365}
366impl PowerDomain {
367    pub fn recovery_d1_micros(&self) -> u32 {
368        u32::from(self.recovery_d1) * 50
369    }
370    pub fn recovery_d2_micros(&self) -> u32 {
371        u32::from(self.recovery_d2) * 50
372    }
373}
374pub fn parse_power_domain(data: &[u8]) -> Result<PowerDomain, DescriptorError> {
375    if data.len() < 9 {
376        return Err(invalid("truncated power domain"));
377    }
378    let n = data[8] as usize;
379    let d = descriptor(data, 0x10, 11 + n)?;
380    entity(d[3])?;
381    for (i, &id) in d[9..9 + n].iter().enumerate() {
382        entity(id)?;
383        if id == d[3] || d[9..9 + i].contains(&id) {
384            return Err(invalid("duplicate or self power-domain member"));
385        }
386    }
387    Ok(PowerDomain {
388        id: d[3],
389        recovery_d1: le16(d, 4),
390        recovery_d2: le16(d, 6),
391        entities: d[9..9 + n].to_vec(),
392        string_id: le16(d, 9 + n),
393    })
394}
395
396/// Feature Unit controls include master channel 0 and one word per channel.
397#[derive(Debug, Clone, PartialEq, Eq)]
398pub struct FeatureUnit {
399    pub id: u8,
400    pub source_id: u8,
401    pub controls: Vec<Controls>,
402    pub string_id: u16,
403}
404pub fn parse_feature_unit(data: &[u8]) -> Result<FeatureUnit, DescriptorError> {
405    if data.len() < 11 {
406        return Err(invalid("truncated ADC3 feature unit"));
407    }
408    let length = usize::from(data[0]);
409    if length < 11 || (length - 7) % 4 != 0 {
410        return Err(invalid("invalid ADC3 feature control words"));
411    }
412    let d = descriptor(data, 7, length)?;
413    entity(d[3])?;
414    entity(d[4])?;
415    Ok(FeatureUnit {
416        id: d[3],
417        source_id: d[4],
418        controls: (5..length - 2)
419            .step_by(4)
420            .map(|at| Controls(le32(d, at)))
421            .collect(),
422        string_id: le16(d, length - 2),
423    })
424}
425
426/// Allocation bound for one USB control transfer. Callers may impose a lower bound.
427pub const MAX_CLUSTER_LENGTH: usize = u16::MAX as usize;
428#[derive(Debug, Clone, Copy, PartialEq, Eq)]
429pub struct ClusterHeader {
430    pub length: u16,
431    pub id: u16,
432}
433/// Validate exactly the six bytes returned by the first HIGH_CAPABILITY request.
434pub fn parse_cluster_header(
435    data: &[u8],
436    requested_id: u16,
437    max_length: usize,
438) -> Result<ClusterHeader, DescriptorError> {
439    if data.len() != 6 || requested_id == 0 {
440        return Err(invalid("invalid HC header transfer or ID"));
441    }
442    let length = le16(data, 0);
443    if data[2] != 0x26
444        || data[3] != 0
445        || le16(data, 4) != requested_id
446        || length < 7
447        || usize::from(length) > max_length.min(MAX_CLUSTER_LENGTH)
448    {
449        return Err(invalid("invalid HC cluster type, ID or allocation length"));
450    }
451    Ok(ClusterHeader {
452        length,
453        id: requested_id,
454    })
455}
456/// Spatial channel identities in ADC3 wire order, Appendix A.12.
457#[derive(Debug, Clone, Copy, PartialEq, Eq)]
458#[repr(u8)]
459pub enum SpatialPosition {
460    FrontLeft = 0x80,
461    FrontRight = 0x81,
462    FrontCenter = 0x82,
463    FrontLeftOfCenter = 0x83,
464    FrontRightOfCenter = 0x84,
465    FrontWideLeft = 0x85,
466    FrontWideRight = 0x86,
467    SideLeft = 0x87,
468    SideRight = 0x88,
469    SurroundArrayLeft = 0x89,
470    SurroundArrayRight = 0x8a,
471    BackLeft = 0x8b,
472    BackRight = 0x8c,
473    BackCenter = 0x8d,
474    BackLeftOfCenter = 0x8e,
475    BackRightOfCenter = 0x8f,
476    BackWideLeft = 0x90,
477    BackWideRight = 0x91,
478    TopCenter = 0x92,
479    TopFrontLeft = 0x93,
480    TopFrontRight = 0x94,
481    TopFrontCenter = 0x95,
482    TopFrontLeftOfCenter = 0x96,
483    TopFrontRightOfCenter = 0x97,
484    TopFrontWideLeft = 0x98,
485    TopFrontWideRight = 0x99,
486    TopSideLeft = 0x9a,
487    TopSideRight = 0x9b,
488    TopSurroundArrayLeft = 0x9c,
489    TopSurroundArrayRight = 0x9d,
490    TopBackLeft = 0x9e,
491    TopBackRight = 0x9f,
492    TopBackCenter = 0xa0,
493    TopBackLeftOfCenter = 0xa1,
494    TopBackRightOfCenter = 0xa2,
495    TopBackWideLeft = 0xa3,
496    TopBackWideRight = 0xa4,
497    BottomCenter = 0xa5,
498    BottomFrontLeft = 0xa6,
499    BottomFrontRight = 0xa7,
500    BottomFrontCenter = 0xa8,
501    BottomFrontLeftOfCenter = 0xa9,
502    BottomFrontRightOfCenter = 0xaa,
503    BottomFrontWideLeft = 0xab,
504    BottomFrontWideRight = 0xac,
505    BottomSideLeft = 0xad,
506    BottomSideRight = 0xae,
507    BottomSurroundArrayLeft = 0xaf,
508    BottomSurroundArrayRight = 0xb0,
509    BottomBackLeft = 0xb1,
510    BottomBackRight = 0xb2,
511    BottomBackCenter = 0xb3,
512    BottomBackLeftOfCenter = 0xb4,
513    BottomBackRightOfCenter = 0xb5,
514    BottomBackWideLeft = 0xb6,
515    BottomBackWideRight = 0xb7,
516    LowFrequencyEffects = 0xb8,
517    LfeLeft = 0xb9,
518    LfeRight = 0xba,
519    HeadphoneLeft = 0xbb,
520    HeadphoneRight = 0xbc,
521}
522impl SpatialPosition {
523    pub fn from_code(code: u8) -> Option<Self> {
524        match code {
525            0x80 => Some(Self::FrontLeft),
526            0x81 => Some(Self::FrontRight),
527            0x82 => Some(Self::FrontCenter),
528            0x83 => Some(Self::FrontLeftOfCenter),
529            0x84 => Some(Self::FrontRightOfCenter),
530            0x85 => Some(Self::FrontWideLeft),
531            0x86 => Some(Self::FrontWideRight),
532            0x87 => Some(Self::SideLeft),
533            0x88 => Some(Self::SideRight),
534            0x89 => Some(Self::SurroundArrayLeft),
535            0x8a => Some(Self::SurroundArrayRight),
536            0x8b => Some(Self::BackLeft),
537            0x8c => Some(Self::BackRight),
538            0x8d => Some(Self::BackCenter),
539            0x8e => Some(Self::BackLeftOfCenter),
540            0x8f => Some(Self::BackRightOfCenter),
541            0x90 => Some(Self::BackWideLeft),
542            0x91 => Some(Self::BackWideRight),
543            0x92 => Some(Self::TopCenter),
544            0x93 => Some(Self::TopFrontLeft),
545            0x94 => Some(Self::TopFrontRight),
546            0x95 => Some(Self::TopFrontCenter),
547            0x96 => Some(Self::TopFrontLeftOfCenter),
548            0x97 => Some(Self::TopFrontRightOfCenter),
549            0x98 => Some(Self::TopFrontWideLeft),
550            0x99 => Some(Self::TopFrontWideRight),
551            0x9a => Some(Self::TopSideLeft),
552            0x9b => Some(Self::TopSideRight),
553            0x9c => Some(Self::TopSurroundArrayLeft),
554            0x9d => Some(Self::TopSurroundArrayRight),
555            0x9e => Some(Self::TopBackLeft),
556            0x9f => Some(Self::TopBackRight),
557            0xa0 => Some(Self::TopBackCenter),
558            0xa1 => Some(Self::TopBackLeftOfCenter),
559            0xa2 => Some(Self::TopBackRightOfCenter),
560            0xa3 => Some(Self::TopBackWideLeft),
561            0xa4 => Some(Self::TopBackWideRight),
562            0xa5 => Some(Self::BottomCenter),
563            0xa6 => Some(Self::BottomFrontLeft),
564            0xa7 => Some(Self::BottomFrontRight),
565            0xa8 => Some(Self::BottomFrontCenter),
566            0xa9 => Some(Self::BottomFrontLeftOfCenter),
567            0xaa => Some(Self::BottomFrontRightOfCenter),
568            0xab => Some(Self::BottomFrontWideLeft),
569            0xac => Some(Self::BottomFrontWideRight),
570            0xad => Some(Self::BottomSideLeft),
571            0xae => Some(Self::BottomSideRight),
572            0xaf => Some(Self::BottomSurroundArrayLeft),
573            0xb0 => Some(Self::BottomSurroundArrayRight),
574            0xb1 => Some(Self::BottomBackLeft),
575            0xb2 => Some(Self::BottomBackRight),
576            0xb3 => Some(Self::BottomBackCenter),
577            0xb4 => Some(Self::BottomBackLeftOfCenter),
578            0xb5 => Some(Self::BottomBackRightOfCenter),
579            0xb6 => Some(Self::BottomBackWideLeft),
580            0xb7 => Some(Self::BottomBackWideRight),
581            0xb8 => Some(Self::LowFrequencyEffects),
582            0xb9 => Some(Self::LfeLeft),
583            0xba => Some(Self::LfeRight),
584            0xbb => Some(Self::HeadphoneLeft),
585            0xbc => Some(Self::HeadphoneRight),
586            _ => None,
587        }
588    }
589}
590
591/// ADC3 relationships are not a UAC1/2 speaker-position bitmap.
592#[derive(Debug, Clone, Copy, PartialEq, Eq)]
593pub enum ChannelRelationship {
594    Undefined,
595    Mono,
596    Left,
597    Right,
598    Array,
599    Pattern(u8),
600    /// Defined spatial position code in ADC3 Appendix A.12 (0x80 through 0xbc).
601    Spatial(SpatialPosition),
602    Unknown(u8),
603}
604impl From<u8> for ChannelRelationship {
605    fn from(value: u8) -> Self {
606        match value {
607            0 => Self::Undefined,
608            1 => Self::Mono,
609            2 => Self::Left,
610            3 => Self::Right,
611            4 => Self::Array,
612            0x20..=0x25 => Self::Pattern(value),
613            0x80..=0xbc => Self::Spatial(SpatialPosition::from_code(value).unwrap()),
614            _ => Self::Unknown(value),
615        }
616    }
617}
618#[derive(Debug, Clone, PartialEq, Eq)]
619pub enum Channel {
620    Information {
621        purpose: u8,
622        relationship: ChannelRelationship,
623        group: u8,
624    },
625    Ambisonic {
626        ordering: u8,
627        acn: u8,
628        normalization: u8,
629        group: u8,
630    },
631}
632#[derive(Debug, Clone, PartialEq, Eq)]
633pub struct Cluster {
634    pub id: u16,
635    pub channels: Vec<Channel>,
636}
637/// Validate body length and ID against the previously validated first read.
638/// Optional unknown segments are bounded and skipped, never interpreted as speakers.
639pub fn parse_cluster(data: &[u8], expected: ClusterHeader) -> Result<Cluster, DescriptorError> {
640    if data.len() != usize::from(expected.length) || data.len() < 7 {
641        return Err(invalid("HC body transfer length changed"));
642    }
643    if parse_cluster_header(&data[..6], expected.id, usize::from(expected.length))? != expected {
644        return Err(invalid("HC body header changed"));
645    }
646    let count = data[6] as usize;
647    if count == 0 {
648        return if data.len() == 7 {
649            Ok(Cluster {
650                id: expected.id,
651                channels: vec![],
652            })
653        } else {
654            Err(invalid("empty cluster has trailing blocks"))
655        };
656    }
657    let mut channels = Vec::with_capacity(count);
658    let mut current = None;
659    let mut common = false;
660    let mut common_done = false;
661    let mut block_open = false;
662    let mut at = 7;
663    while at < data.len() {
664        if data.len() - at < 3 {
665            return Err(invalid("truncated cluster segment"));
666        }
667        let length = usize::from(le16(data, at));
668        if length < 3 || length > data.len() - at {
669            return Err(invalid("invalid cluster segment length"));
670        }
671        let d = &data[at..at + length];
672        match d[2] {
673            0xff => {
674                if length != 3 {
675                    return Err(invalid("invalid end segment"));
676                }
677                block_open = false;
678                if common {
679                    common = false;
680                    common_done = true;
681                } else if at == 7 && !common_done && !block_open {
682                    // A single leading End may represent an empty Common Block.
683                    // The final count and identity checks still require every channel.
684                    common_done = true;
685                } else {
686                    channels.push(current.take().ok_or_else(|| {
687                        invalid("channel has no information or ambisonic segment")
688                    })?);
689                }
690            }
691            0x01 | 0x1f => {
692                if common_done || current.is_some() || !channels.is_empty() {
693                    return Err(invalid("common segment inside channel block"));
694                }
695                if d[2] == 1 && length != 5 {
696                    return Err(invalid("invalid cluster description length"));
697                }
698                common = true;
699                block_open = true;
700            }
701            0x20 | 0x21 => {
702                if common || current.is_some() {
703                    return Err(invalid(
704                        "unterminated common block or duplicate channel identity",
705                    ));
706                }
707                common_done = true;
708                block_open = true;
709                current = Some(if d[2] == 0x20 {
710                    if length != 6 {
711                        return Err(invalid("invalid channel information length"));
712                    }
713                    Channel::Information {
714                        purpose: d[3],
715                        relationship: d[4].into(),
716                        group: d[5],
717                    }
718                } else {
719                    if length != 7 {
720                        return Err(invalid("invalid ambisonic segment length"));
721                    }
722                    Channel::Ambisonic {
723                        ordering: d[3],
724                        acn: d[4],
725                        normalization: d[5],
726                        group: d[6],
727                    }
728                });
729            }
730            // Channel description and vendor-specific data do not change wire order.
731            0x22 | 0xfe => {
732                if common {
733                    return Err(invalid("channel segment inside common block"));
734                }
735                if d[2] == 0x22 && length != 5 {
736                    return Err(invalid("invalid channel description length"));
737                }
738                common_done = true;
739                block_open = true;
740            }
741            _ => return Err(invalid("reserved cluster segment type")),
742        }
743        if channels.len() > count {
744            return Err(invalid("too many cluster channel blocks"));
745        }
746        at += length;
747    }
748    if block_open || common || current.is_some() || channels.len() != count {
749        return Err(invalid("unterminated or missing cluster blocks"));
750    }
751    Ok(Cluster {
752        id: expected.id,
753        channels,
754    })
755}
756
757#[derive(Debug, Clone, Copy, PartialEq, Eq)]
758pub enum FunctionProfile {
759    Full,
760    Badd(BaddProfile),
761}
762#[derive(Debug, Clone, Copy, PartialEq, Eq)]
763pub enum BaddProfile {
764    GenericIo,
765    Headphone,
766    Speaker,
767    Microphone,
768    Headset,
769    HeadsetAdapter,
770    Speakerphone,
771}
772/// Require protocol agreement before interpreting the IAD profile.
773pub fn function_profile(
774    iad: &Iad,
775    interface_protocol: u8,
776) -> Result<FunctionProfile, DescriptorError> {
777    if iad.b_function_class != 1
778        || iad.b_function_protocol != 0x30
779        || interface_protocol != 0x30
780        || iad.b_interface_count == 0
781        || u16::from(iad.b_first_interface) + u16::from(iad.b_interface_count) > 256
782    {
783        return Err(invalid("not an ADC3 audio function"));
784    }
785    let p = match iad.b_function_sub_class {
786        1 => return Ok(FunctionProfile::Full),
787        0x20 => BaddProfile::GenericIo,
788        0x21 => BaddProfile::Headphone,
789        0x22 => BaddProfile::Speaker,
790        0x23 => BaddProfile::Microphone,
791        0x24 => BaddProfile::Headset,
792        0x25 => BaddProfile::HeadsetAdapter,
793        0x26 => BaddProfile::Speakerphone,
794        _ => return Err(invalid("reserved ADC3 function profile")),
795    };
796    let n = iad.b_interface_count;
797    if match p {
798        BaddProfile::GenericIo => !(2..=3).contains(&n),
799        BaddProfile::Headphone | BaddProfile::Speaker | BaddProfile::Microphone => n != 2,
800        _ => n != 3,
801    } {
802        return Err(invalid("BADD profile interface count mismatch"));
803    }
804    Ok(FunctionProfile::Badd(p))
805}
806#[derive(Debug, Clone, Copy, PartialEq, Eq)]
807pub enum BusSpeed {
808    Full,
809    High,
810    Super,
811}
812#[derive(Debug, Clone, Copy, PartialEq, Eq)]
813pub enum Direction {
814    Playback,
815    Capture,
816}
817#[derive(Debug, Clone, Copy, PartialEq, Eq)]
818pub enum Synchronization {
819    Synchronous,
820    Asynchronous,
821}
822#[derive(Debug, Clone, PartialEq, Eq)]
823pub struct BaddFormat {
824    pub direction: Direction,
825    pub synchronization: Synchronization,
826    pub sample_rate: u32,
827    pub channels: u8,
828    pub subslot_size: u8,
829    pub bit_resolution: u8,
830    pub clock_id: u8,
831    pub power_domain_id: u8,
832}
833/// Interpret a nonzero Continuous Mode alternate with the exact 1 ms capacity
834/// table (BADD section 4.2 and Table 8-26). The caller must separately prove the
835/// function's mandatory alternates and common direction/synchronization contract.
836/// Bursting intervals must not reuse this table: BADD section 8 explicitly
837/// derives sample width/channels from Alternate Setting 1 only. Section 4.2.2
838/// permits burst alternates but defines no interval-scaled replacement table;
839/// packet padding and synchronization headroom cannot prove an arbitrary burst
840/// alternate's format. Retain the exact continuous alternates instead.
841/// SuperSpeed interpretation here
842/// is profile geometry only; runtime admission also requires companion validation.
843pub fn infer_badd_format(
844    profile: BaddProfile,
845    speed: BusSpeed,
846    alternate: u8,
847    endpoint: &[u8],
848    explicit_feedback: bool,
849) -> Result<BaddFormat, DescriptorError> {
850    if endpoint.len() < 7 || endpoint[0] != 7 || endpoint[1] != 5 || alternate == 0 {
851        return Err(invalid(
852            "BADD requires a standard endpoint in a nonzero continuous alternate",
853        ));
854    }
855    let address = endpoint[2];
856    if address & 0x0f == 0 || address & 0x70 != 0 {
857        return Err(invalid("invalid BADD endpoint address"));
858    }
859    let direction = if address & 0x80 == 0 {
860        Direction::Playback
861    } else {
862        Direction::Capture
863    };
864    let synchronization = match endpoint[3] {
865        0x05 => Synchronization::Asynchronous,
866        0x0d => Synchronization::Synchronous,
867        _ => {
868            return Err(invalid(
869                "BADD requires synchronous or asynchronous audio data endpoint",
870            ))
871        }
872    };
873    let required_interval = if speed == BusSpeed::Full { 1 } else { 4 };
874    if endpoint[6] != required_interval {
875        return Err(invalid("BADD continuous service interval must be 1 ms"));
876    }
877    let capacity = le16(endpoint, 4);
878    let asynchronous = synchronization == Synchronization::Asynchronous;
879    let (channels, subslot_size) = match (capacity, asynchronous) {
880        (96, false) | (98, true) => (1, 2),
881        (144, false) | (147, true) => (1, 3),
882        (192, false) | (196, true) => (2, 2),
883        (288, false) | (294, true) => (2, 3),
884        _ => return Err(invalid("BADD capacity does not match synchronization type")),
885    };
886    let capture = direction == Direction::Capture;
887    if (capture && matches!(profile, BaddProfile::Headphone | BaddProfile::Speaker))
888        || (!capture && profile == BaddProfile::Microphone)
889        || (capture
890            && matches!(profile, BaddProfile::Headset | BaddProfile::HeadsetAdapter)
891            && channels != 1)
892        || (profile == BaddProfile::Speakerphone && channels != 1)
893    {
894        return Err(invalid(
895            "BADD endpoint direction or channels conflict with profile",
896        ));
897    }
898    if !capture && asynchronous && !explicit_feedback {
899        return Err(invalid("asynchronous BADD sink needs explicit feedback"));
900    }
901    Ok(BaddFormat {
902        direction,
903        synchronization,
904        sample_rate: 48_000,
905        channels,
906        subslot_size,
907        bit_resolution: subslot_size * 8,
908        clock_id: 9,
909        power_domain_id: if capture { 11 } else { 10 },
910    })
911}
912
913#[cfg(test)]
914mod tests;