Skip to main content

usbdac_core/
clock_resolution.rs

1//! Which Clock Source feeds a streaming terminal (UAC 2.0, section 4.7.2).
2//!
3//! A terminal's `bCSourceID` names the clock entity that drives it. That entity
4//! is a Clock Source (0x0A) on simple DACs, but it can also be a Clock Selector
5//! (0x0B) that chooses between several clocks, or a Clock Multiplier (0x0C) fed
6//! by another clock entity. Setting and verifying the sample rate has to happen
7//! on the Clock Source at the end of that chain, not on whichever source the
8//! descriptor happens to list first.
9//!
10//! This module is plain data and callbacks so every case can be unit-tested
11//! without libusb. The caller supplies the AudioControl class-specific
12//! descriptor bytes and a callback that asks the device which pin a Clock
13//! Selector currently has selected.
14
15use crate::descriptors::AudioControlParser;
16use std::collections::HashMap;
17use std::fmt;
18
19const USB_DT_INTERFACE: u8 = 0x04;
20const USB_DT_CS_INTERFACE: u8 = 0x24;
21const USB_CLASS_AUDIO: u8 = 0x01;
22const USB_SUBCLASS_AUDIOCONTROL: u8 = 0x01;
23const UAC2_INPUT_TERMINAL: u8 = 0x02;
24const UAC2_OUTPUT_TERMINAL: u8 = 0x03;
25const UAC2_CLOCK_SOURCE: u8 = 0x0a;
26const UAC2_CLOCK_SELECTOR: u8 = 0x0b;
27const UAC2_CLOCK_MULTIPLIER: u8 = 0x0c;
28
29/// Upper bound on hops. Real topologies are two or three entities deep; this
30/// only stops a pathological descriptor from walking for long.
31const MAX_CLOCK_PATH: usize = 16;
32
33/// How the clock the library programs the sample rate on was reached, for
34/// diagnosing a DAC with more than one clock. Read-only: nothing here changes
35/// what the library does.
36///
37/// UAC 2.0 routes a streaming terminal to its clock through Clock Selectors
38/// (several inputs, one active) and Clock Multipliers, ending at a Clock Source
39/// (section 4.7.2). The sampling frequency is set and read back on that source.
40#[derive(Debug, Clone, PartialEq, Eq)]
41pub struct ClockChoice {
42    /// Interface number of the AudioControl interface the clock requests go to.
43    pub control_interface: u8,
44    /// Entity ID of the Clock Source the sample rate is set and verified on.
45    pub source_id: u8,
46    /// The entities followed, in order: the streaming terminal, then each clock
47    /// entity down to the Clock Source (the last hop, whose `id` is `source_id`).
48    ///
49    /// For [`ClockResolution::FallbackFirstSource`] nothing was followed, so the
50    /// path is the Clock Source alone.
51    pub path: Vec<ClockHop>,
52    pub resolution: ClockResolution,
53}
54
55/// How [`ClockChoice::source_id`] was found.
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57#[non_exhaustive]
58pub enum ClockResolution {
59    /// The stream's terminal was traced to the Clock Source through the
60    /// descriptors (and, at a Clock Selector with several inputs, the pin the
61    /// device reports as selected).
62    Resolved,
63    /// The topology could not be traced (no terminal link, a malformed or
64    /// looping entity, a selector that would not say which pin is active), so
65    /// the first Clock Source in descriptor order was used. On a DAC with more
66    /// than one clock the rate may then be set on the wrong one.
67    FallbackFirstSource,
68}
69
70impl ClockResolution {
71    /// Stable identifier: `resolved`, `fallback_first_source`.
72    pub fn code(self) -> &'static str {
73        match self {
74            Self::Resolved => "resolved",
75            Self::FallbackFirstSource => "fallback_first_source",
76        }
77    }
78}
79
80/// One entity on the path from a streaming terminal to its Clock Source.
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub struct ClockHop {
83    /// The entity ID (the terminal ID for [`ClockHopKind::Terminal`]).
84    pub id: u8,
85    pub kind: ClockHopKind,
86}
87
88/// What a [`ClockHop`] is.
89#[derive(Debug, Clone, Copy, PartialEq, Eq)]
90#[non_exhaustive]
91pub enum ClockHopKind {
92    /// The streaming terminal the path starts at.
93    Terminal,
94    /// A Clock Selector. Pins are 1-based. A selector with one input has
95    /// nothing to choose and is reported as `selected_pin: 1, pin_count: 1`
96    /// without being asked; with several, the pin is what the device reported.
97    Selector { selected_pin: u8, pin_count: u8 },
98    /// A Clock Multiplier (one clock input).
99    Multiplier,
100    /// A Clock Source: the end of the path.
101    Source,
102}
103
104impl ClockHopKind {
105    /// Stable identifier: `terminal`, `selector`, `multiplier`, `source`.
106    pub fn code(self) -> &'static str {
107        match self {
108            Self::Terminal => "terminal",
109            Self::Selector { .. } => "selector",
110            Self::Multiplier => "multiplier",
111            Self::Source => "source",
112        }
113    }
114}
115
116#[derive(Debug, Clone, PartialEq, Eq)]
117enum ClockEntity {
118    Source,
119    /// Input pins in descriptor order. Pin numbers on the wire are 1-based.
120    Selector(Vec<u8>),
121    Multiplier(u8),
122    /// A selector or multiplier descriptor that is too short to trust.
123    Malformed,
124}
125
126/// The clock part of one AudioControl interface's class-specific descriptors.
127#[derive(Debug, Default)]
128pub(crate) struct ClockGraph {
129    /// Terminal ID to the clock entity ID named by its `bCSourceID`.
130    terminal_clock: HashMap<u8, u8>,
131    entities: HashMap<u8, ClockEntity>,
132    first_source: Option<u8>,
133}
134
135impl ClockGraph {
136    /// Scan class-specific AudioControl descriptors (the interface's `extra`
137    /// bytes). Unknown or truncated descriptors are skipped, never fatal.
138    pub(crate) fn parse(descriptors: &[u8]) -> Self {
139        let mut graph = Self::default();
140        let mut index = 0usize;
141        while index + 2 < descriptors.len() {
142            let length = descriptors[index] as usize;
143            if length < 3 || index + length > descriptors.len() {
144                break;
145            }
146            let descriptor = &descriptors[index..index + length];
147            index += length;
148            if descriptor[1] != USB_DT_CS_INTERFACE {
149                continue;
150            }
151            match descriptor[2] {
152                // bTerminalID at 3; bCSourceID at 7 (Input Terminal, 4.7.2.4).
153                UAC2_INPUT_TERMINAL if length >= 8 => {
154                    graph.terminal_clock.insert(descriptor[3], descriptor[7]);
155                }
156                // bTerminalID at 3; bSourceID at 7 and bCSourceID at 8 (Output
157                // Terminal, 4.7.2.5).
158                UAC2_OUTPUT_TERMINAL if length >= 9 => {
159                    graph.terminal_clock.insert(descriptor[3], descriptor[8]);
160                }
161                UAC2_CLOCK_SOURCE if length >= 4 => {
162                    graph.entities.insert(descriptor[3], ClockEntity::Source);
163                    graph.first_source.get_or_insert(descriptor[3]);
164                }
165                UAC2_CLOCK_SELECTOR if length >= 4 => {
166                    let entity = AudioControlParser
167                        .parse_clock_selector(descriptor)
168                        .map(|selector| ClockEntity::Selector(selector.ba_c_source_id))
169                        .unwrap_or(ClockEntity::Malformed);
170                    graph.entities.insert(descriptor[3], entity);
171                }
172                UAC2_CLOCK_MULTIPLIER if length >= 4 => {
173                    let entity = AudioControlParser
174                        .parse_clock_multiplier(descriptor)
175                        .map(|multiplier| ClockEntity::Multiplier(multiplier.b_c_source_id))
176                        .unwrap_or(ClockEntity::Malformed);
177                    graph.entities.insert(descriptor[3], entity);
178                }
179                _ => {}
180            }
181        }
182        graph
183    }
184
185    /// True if any clock entity was described. Without one (UAC 1.0 has none)
186    /// there is no clock topology to resolve.
187    pub(crate) fn has_clock_entities(&self) -> bool {
188        !self.entities.is_empty()
189    }
190
191    /// The first Clock Source in descriptor order: the last-resort answer when
192    /// the topology cannot be resolved.
193    pub(crate) fn first_clock_source(&self) -> Option<u8> {
194        self.first_source
195    }
196
197    /// Walk from `terminal_id` to the Clock Source currently feeding it.
198    ///
199    /// `selected_pin` is asked for the 1-based current input pin of a Clock
200    /// Selector, and only for a selector with more than one input. A selector
201    /// with one input has nothing to choose, and a multiplier has a single
202    /// clock input, so neither needs a request.
203    ///
204    /// An ID with no clock descriptor of its own is taken to be the source:
205    /// sparse descriptors do exist, and the old behaviour of treating it as
206    /// unusable sent the sample rate to the wrong clock.
207    pub(crate) fn resolve_terminal_clock(
208        &self,
209        terminal_id: u8,
210        mut selected_pin: impl FnMut(u8) -> Result<u8, String>,
211    ) -> Result<ResolvedClock, ClockResolveError> {
212        let first = *self
213            .terminal_clock
214            .get(&terminal_id)
215            .ok_or(ClockResolveError::TerminalNotFound(terminal_id))?;
216        if first == 0 {
217            return Err(ClockResolveError::TerminalHasNoClock(terminal_id));
218        }
219
220        let mut path = vec![first];
221        let mut hops = vec![ClockHop {
222            id: terminal_id,
223            kind: ClockHopKind::Terminal,
224        }];
225        loop {
226            let current = *path.last().expect("path starts non-empty");
227            match self.entities.get(&current) {
228                None | Some(ClockEntity::Source) => {
229                    let assumed_source = !self.entities.contains_key(&current);
230                    hops.push(ClockHop {
231                        id: current,
232                        kind: ClockHopKind::Source,
233                    });
234                    return Ok(ResolvedClock {
235                        clock_id: current,
236                        path,
237                        hops,
238                        assumed_source,
239                    });
240                }
241                Some(ClockEntity::Malformed) => {
242                    return Err(ClockResolveError::MalformedEntity(current));
243                }
244                Some(ClockEntity::Multiplier(input)) => {
245                    if *input == 0 {
246                        return Err(ClockResolveError::MalformedEntity(current));
247                    }
248                    hops.push(ClockHop {
249                        id: current,
250                        kind: ClockHopKind::Multiplier,
251                    });
252                    path.push(*input);
253                }
254                Some(ClockEntity::Selector(inputs)) => {
255                    let pin_count = u8::try_from(inputs.len()).unwrap_or(u8::MAX);
256                    let (next, pin) = match inputs.as_slice() {
257                        [] => return Err(ClockResolveError::SelectorWithoutInputs(current)),
258                        [only] => (*only, 1),
259                        many => {
260                            let pin = selected_pin(current).map_err(|reason| {
261                                ClockResolveError::PinUnavailable {
262                                    selector: current,
263                                    reason,
264                                }
265                            })?;
266                            if pin == 0 || usize::from(pin) > many.len() {
267                                return Err(ClockResolveError::PinOutOfRange {
268                                    selector: current,
269                                    pin,
270                                    inputs: many.len(),
271                                });
272                            }
273                            (many[usize::from(pin) - 1], pin)
274                        }
275                    };
276                    if next == 0 {
277                        return Err(ClockResolveError::MalformedEntity(current));
278                    }
279                    hops.push(ClockHop {
280                        id: current,
281                        kind: ClockHopKind::Selector {
282                            selected_pin: pin,
283                            pin_count,
284                        },
285                    });
286                    path.push(next);
287                }
288            }
289            // An entity may appear once; reaching one again is a loop.
290            let last = *path.last().expect("path is non-empty");
291            if path[..path.len() - 1].contains(&last) {
292                return Err(ClockResolveError::Loop(last));
293            }
294            if path.len() > MAX_CLOCK_PATH {
295                return Err(ClockResolveError::TooDeep);
296            }
297        }
298    }
299
300    /// The clock the sample rate is programmed on for the stream whose
301    /// AudioStreaming interface links `terminal_link`, on the AudioControl
302    /// interface `control_interface`.
303    ///
304    /// The terminal is traced to its Clock Source with
305    /// [`resolve_terminal_clock`](Self::resolve_terminal_clock). When that
306    /// fails (or the stream names no terminal) the first Clock Source in
307    /// descriptor order is used instead, and the result says so. `Err` carries
308    /// the reason when there is no clock to choose: the interface describes no
309    /// clock entities, or none is a Clock Source to fall back on.
310    pub(crate) fn select_clock(
311        &self,
312        control_interface: u8,
313        terminal_link: Option<u8>,
314        selected_pin: impl FnMut(u8) -> Result<u8, String>,
315    ) -> Result<ClockSelection, String> {
316        // UAC 1.0 describes no clock entities, and its terminal descriptors must
317        // not be read as if they named one.
318        if !self.has_clock_entities() {
319            return Err("the AudioControl interface describes no clock entities".to_string());
320        }
321        let unresolved = match terminal_link {
322            None => "the stream has no bTerminalLink to trace its clock from".to_string(),
323            Some(terminal) => match self.resolve_terminal_clock(terminal, selected_pin) {
324                Ok(resolved) => {
325                    return Ok(ClockSelection {
326                        choice: ClockChoice {
327                            control_interface,
328                            source_id: resolved.clock_id,
329                            path: resolved.hops,
330                            resolution: ClockResolution::Resolved,
331                        },
332                        assumed_source: resolved.assumed_source,
333                        unresolved: None,
334                    });
335                }
336                Err(error) => error.to_string(),
337            },
338        };
339        match self.first_clock_source() {
340            Some(source_id) => Ok(ClockSelection {
341                choice: ClockChoice {
342                    control_interface,
343                    source_id,
344                    path: vec![ClockHop {
345                        id: source_id,
346                        kind: ClockHopKind::Source,
347                    }],
348                    resolution: ClockResolution::FallbackFirstSource,
349                },
350                assumed_source: false,
351                unresolved: Some(unresolved),
352            }),
353            None => Err(unresolved),
354        }
355    }
356}
357
358/// What [`ClockGraph::select_clock`] chose, with what the transport logs about it.
359#[derive(Debug, Clone, PartialEq, Eq)]
360pub(crate) struct ClockSelection {
361    pub choice: ClockChoice,
362    /// The source has no descriptor of its own and was taken to be one.
363    pub assumed_source: bool,
364    /// Why the topology could not be traced. Set exactly when the choice is
365    /// [`ClockResolution::FallbackFirstSource`].
366    pub unresolved: Option<String>,
367}
368
369#[derive(Debug, Clone, PartialEq, Eq)]
370pub(crate) struct ResolvedClock {
371    pub clock_id: u8,
372    /// Entity IDs from the terminal's `bCSourceID` to `clock_id`, inclusive.
373    pub path: Vec<u8>,
374    /// The same walk with what each entity is, starting at the terminal itself.
375    pub hops: Vec<ClockHop>,
376    /// `clock_id` has no descriptor of its own and was taken to be the source.
377    pub assumed_source: bool,
378}
379
380impl ResolvedClock {
381    /// Shared source IDs prove equal sample cadence only without an unknown
382    /// multiplier ratio, and only when the source is actually described.
383    pub(crate) fn proves_identity_cadence(&self) -> bool {
384        !self.assumed_source
385            && !self
386                .hops
387                .iter()
388                .any(|hop| matches!(hop.kind, ClockHopKind::Multiplier))
389    }
390}
391
392#[derive(Debug, Clone, PartialEq, Eq)]
393pub(crate) enum ClockResolveError {
394    TerminalNotFound(u8),
395    TerminalHasNoClock(u8),
396    MalformedEntity(u8),
397    SelectorWithoutInputs(u8),
398    PinUnavailable {
399        selector: u8,
400        reason: String,
401    },
402    PinOutOfRange {
403        selector: u8,
404        pin: u8,
405        inputs: usize,
406    },
407    Loop(u8),
408    TooDeep,
409}
410
411impl fmt::Display for ClockResolveError {
412    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
413        match self {
414            Self::TerminalNotFound(id) => {
415                write!(f, "terminal {id} is not in the AudioControl descriptors")
416            }
417            Self::TerminalHasNoClock(id) => {
418                write!(f, "terminal {id} names no clock (bCSourceID 0)")
419            }
420            Self::MalformedEntity(id) => write!(f, "clock entity {id} has a malformed descriptor"),
421            Self::SelectorWithoutInputs(id) => write!(f, "clock selector {id} has no input pins"),
422            Self::PinUnavailable { selector, reason } => {
423                write!(
424                    f,
425                    "current pin of clock selector {selector} is unavailable: {reason}"
426                )
427            }
428            Self::PinOutOfRange {
429                selector,
430                pin,
431                inputs,
432            } => write!(
433                f,
434                "clock selector {selector} reports pin {pin}, outside its {inputs} inputs"
435            ),
436            Self::Loop(id) => write!(f, "clock entity {id} feeds itself"),
437            Self::TooDeep => write!(f, "clock topology is deeper than {MAX_CLOCK_PATH} entities"),
438        }
439    }
440}
441
442/// Concatenate the class-specific descriptors of one AudioControl interface
443/// from a raw configuration descriptor. Used when the platform hands back no
444/// `extra` bytes for the interface.
445pub(crate) fn audio_control_descriptors_from_config(
446    raw: &[u8],
447    ac_interface_number: u8,
448) -> Vec<u8> {
449    let mut collected = Vec::new();
450    let mut inside_ac_interface = false;
451    let mut pos = 0usize;
452    while pos + 1 < raw.len() {
453        let length = raw[pos] as usize;
454        if length < 2 || pos + length > raw.len() {
455            break;
456        }
457        let descriptor = &raw[pos..pos + length];
458        pos += length;
459        if descriptor[1] == USB_DT_INTERFACE && length >= 9 {
460            inside_ac_interface = descriptor[2] == ac_interface_number
461                && descriptor[5] == USB_CLASS_AUDIO
462                && descriptor[6] == USB_SUBCLASS_AUDIOCONTROL;
463        } else if inside_ac_interface && descriptor[1] == USB_DT_CS_INTERFACE {
464            collected.extend_from_slice(descriptor);
465        }
466    }
467    collected
468}
469
470#[cfg(test)]
471mod implicit_clock_tests {
472    use super::*;
473    #[test]
474    fn implicit_proof_rejects_sparse_sources_and_unknown_multiplier_ratios() {
475        let terminal = [8, 0x24, 2, 1, 0, 0, 0, 10];
476        let mut descriptors = terminal.to_vec();
477        let sparse = ClockGraph::parse(&descriptors)
478            .resolve_terminal_clock(1, |_| unreachable!())
479            .unwrap();
480        assert!(!sparse.proves_identity_cadence());
481        descriptors.extend_from_slice(&[8, 0x24, 0x0a, 10, 0, 0, 0, 0]);
482        let direct = ClockGraph::parse(&descriptors)
483            .resolve_terminal_clock(1, |_| unreachable!())
484            .unwrap();
485        assert!(direct.proves_identity_cadence());
486        descriptors[7] = 11;
487        descriptors.extend_from_slice(&[7, 0x24, 0x0c, 11, 10, 0, 0]);
488        let multiplied = ClockGraph::parse(&descriptors)
489            .resolve_terminal_clock(1, |_| unreachable!())
490            .unwrap();
491        assert!(!multiplied.proves_identity_cadence());
492    }
493}