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, HashSet};
17use std::fmt;
18
19mod rate_ratio;
20pub(crate) use rate_ratio::RateRatio;
21
22const USB_DT_INTERFACE: u8 = 0x04;
23const USB_DT_CS_INTERFACE: u8 = 0x24;
24const USB_CLASS_AUDIO: u8 = 0x01;
25const USB_SUBCLASS_AUDIOCONTROL: u8 = 0x01;
26const UAC2_INPUT_TERMINAL: u8 = 0x02;
27const UAC2_OUTPUT_TERMINAL: u8 = 0x03;
28const UAC2_CLOCK_SOURCE: u8 = 0x0a;
29const UAC2_CLOCK_SELECTOR: u8 = 0x0b;
30const UAC2_CLOCK_MULTIPLIER: u8 = 0x0c;
31
32/// Upper bound on hops. Real topologies are two or three entities deep; this
33/// only stops a pathological descriptor from walking for long.
34const MAX_CLOCK_PATH: usize = 16;
35
36/// How the clock the library programs the sample rate on was reached, for
37/// diagnosing a DAC with more than one clock. Read-only: nothing here changes
38/// what the library does.
39///
40/// UAC 2.0 routes a streaming terminal to its clock through Clock Selectors
41/// (several inputs, one active) and Clock Multipliers, ending at a Clock Source
42/// (section 4.7.2). The sampling frequency is set and read back on that source.
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub struct ClockChoice {
45    /// Interface number of the AudioControl interface the clock requests go to.
46    pub control_interface: u8,
47    /// Entity ID of the Clock Source the sample rate is set and verified on.
48    pub source_id: u8,
49    /// The entities followed, in order: the streaming terminal, then each clock
50    /// entity down to the Clock Source (the last hop, whose `id` is `source_id`).
51    ///
52    /// For [`ClockResolution::FallbackFirstSource`] nothing was followed, so the
53    /// path is the Clock Source alone.
54    pub path: Vec<ClockHop>,
55    pub resolution: ClockResolution,
56}
57
58/// How [`ClockChoice::source_id`] was found.
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60#[non_exhaustive]
61pub enum ClockResolution {
62    /// The stream's terminal was traced to the Clock Source through the
63    /// descriptors (and, at a Clock Selector with several inputs, the pin the
64    /// device reports as selected).
65    Resolved,
66    /// The topology could not be traced (no terminal link, a malformed or
67    /// looping entity, a selector that would not say which pin is active), so
68    /// the first Clock Source in descriptor order was used. On a DAC with more
69    /// than one clock the rate may then be set on the wrong one.
70    FallbackFirstSource,
71}
72
73impl ClockResolution {
74    /// Stable identifier: `resolved`, `fallback_first_source`.
75    pub fn code(self) -> &'static str {
76        match self {
77            Self::Resolved => "resolved",
78            Self::FallbackFirstSource => "fallback_first_source",
79        }
80    }
81}
82
83/// One entity on the path from a streaming terminal to its Clock Source.
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85pub struct ClockHop {
86    /// The entity ID (the terminal ID for [`ClockHopKind::Terminal`]).
87    pub id: u8,
88    pub kind: ClockHopKind,
89}
90
91/// What a [`ClockHop`] is.
92#[derive(Debug, Clone, Copy, PartialEq, Eq)]
93#[non_exhaustive]
94pub enum ClockHopKind {
95    /// The streaming terminal the path starts at.
96    Terminal,
97    /// A Clock Selector. Pins are 1-based. A selector with one input has
98    /// nothing to choose and is reported as `selected_pin: 1, pin_count: 1`
99    /// without being asked; with several, the pin is what the device reported.
100    Selector { selected_pin: u8, pin_count: u8 },
101    /// A Clock Multiplier (one clock input).
102    Multiplier,
103    /// A Clock Multiplier whose exact current ratio was read back.
104    /// The output cadence is the input cadence times numerator/denominator.
105    RateMultiplier { numerator: u16, denominator: u16 },
106    /// A Clock Source: the end of the path.
107    Source,
108}
109
110impl ClockHopKind {
111    /// Stable identifier: `terminal`, `selector`, `multiplier`, `source`.
112    pub fn code(self) -> &'static str {
113        match self {
114            Self::Terminal => "terminal",
115            Self::Selector { .. } => "selector",
116            Self::Multiplier | Self::RateMultiplier { .. } => "multiplier",
117            Self::Source => "source",
118        }
119    }
120}
121
122#[derive(Debug, Clone, PartialEq, Eq)]
123enum ClockEntity {
124    Source,
125    /// Input pins in descriptor order. Pin numbers on the wire are 1-based.
126    Selector(Vec<u8>),
127    Multiplier(u8),
128    /// A selector or multiplier descriptor that is too short to trust.
129    Malformed,
130}
131
132/// The clock part of one AudioControl interface's class-specific descriptors.
133#[derive(Debug, Default)]
134pub(crate) struct ClockGraph {
135    /// Terminal ID to the clock entity ID named by its `bCSourceID`.
136    terminal_clock: HashMap<u8, u8>,
137    entities: HashMap<u8, ClockEntity>,
138    first_source: Option<u8>,
139    // Strict selectable topology is separate from the legacy sparse fallback.
140    exact_sources: HashSet<u8>,
141    selector_controls: HashMap<u8, u32>,
142    source_controls: HashMap<u8, u32>,
143    /// Multipliers with exact descriptors and readable numerator/denominator.
144    readable_multipliers: HashSet<u8>,
145    duplicate_ids: HashSet<u8>,
146    multiplier_ids: HashSet<u8>,
147}
148
149impl ClockGraph {
150    /// Scan class-specific AudioControl descriptors (the interface's `extra`
151    /// bytes). Unknown or truncated descriptors are skipped, never fatal.
152    pub(crate) fn parse(descriptors: &[u8]) -> Self {
153        let mut graph = Self::default();
154        let mut index = 0usize;
155        let mut seen_ids = HashSet::new();
156        while index + 2 < descriptors.len() {
157            let length = descriptors[index] as usize;
158            if length < 3 || index + length > descriptors.len() {
159                // Retain an identifiable truncated multiplier as malformed.
160                // Otherwise its terminal link could become an assumed source.
161                let remainder = &descriptors[index..];
162                if remainder.len() >= 4
163                    && remainder[1] == USB_DT_CS_INTERFACE
164                    && remainder[2] == UAC2_CLOCK_MULTIPLIER
165                {
166                    graph.multiplier_ids.insert(remainder[3]);
167                    graph.entities.insert(remainder[3], ClockEntity::Malformed);
168                }
169                break;
170            }
171            let descriptor = &descriptors[index..index + length];
172            index += length;
173            if descriptor[1] != USB_DT_CS_INTERFACE {
174                continue;
175            }
176            if length >= 4
177                && matches!(
178                    descriptor[2],
179                    UAC2_INPUT_TERMINAL
180                        | UAC2_OUTPUT_TERMINAL
181                        | UAC2_CLOCK_SOURCE
182                        | UAC2_CLOCK_SELECTOR
183                        | UAC2_CLOCK_MULTIPLIER
184                )
185                && !seen_ids.insert(descriptor[3])
186            {
187                graph.duplicate_ids.insert(descriptor[3]);
188            }
189            match descriptor[2] {
190                // bTerminalID at 3; bCSourceID at 7 (Input Terminal, 4.7.2.4).
191                UAC2_INPUT_TERMINAL if length >= 8 => {
192                    graph.terminal_clock.insert(descriptor[3], descriptor[7]);
193                }
194                // bTerminalID at 3; bSourceID at 7 and bCSourceID at 8 (Output
195                // Terminal, 4.7.2.5).
196                UAC2_OUTPUT_TERMINAL if length >= 9 => {
197                    graph.terminal_clock.insert(descriptor[3], descriptor[8]);
198                }
199                UAC2_CLOCK_SOURCE if length >= 4 => {
200                    graph.entities.insert(descriptor[3], ClockEntity::Source);
201                    graph.first_source.get_or_insert(descriptor[3]);
202                    if length >= 8 && descriptor[3] != 0 {
203                        graph.exact_sources.insert(descriptor[3]);
204                        graph
205                            .source_controls
206                            .insert(descriptor[3], u32::from(descriptor[5]));
207                    }
208                }
209                UAC2_CLOCK_SELECTOR if length >= 4 => {
210                    if length >= 5 {
211                        let pins = usize::from(descriptor[4]);
212                        if length >= 7 + pins {
213                            graph
214                                .selector_controls
215                                .insert(descriptor[3], u32::from(descriptor[5 + pins]));
216                        }
217                    }
218                    let entity = AudioControlParser
219                        .parse_clock_selector(descriptor)
220                        .map(|selector| ClockEntity::Selector(selector.ba_c_source_id))
221                        .unwrap_or(ClockEntity::Malformed);
222                    graph.entities.insert(descriptor[3], entity);
223                }
224                UAC2_CLOCK_MULTIPLIER if length >= 4 => {
225                    graph.multiplier_ids.insert(descriptor[3]);
226                    // Audio 2.0 4.7.2.3: both controls must be read-only.
227                    if length == 7
228                        && descriptor[3] != 0
229                        && descriptor[4] != 0
230                        && descriptor[5] == 0x05
231                    {
232                        graph.readable_multipliers.insert(descriptor[3]);
233                    }
234                    let entity = AudioControlParser
235                        .parse_clock_multiplier(descriptor)
236                        .map(|multiplier| ClockEntity::Multiplier(multiplier.b_c_source_id))
237                        .unwrap_or(ClockEntity::Malformed);
238                    graph.entities.insert(descriptor[3], entity);
239                }
240                _ => {}
241            }
242        }
243        graph
244    }
245
246    /// Parse full ADC3 descriptors without narrowing their 32-bit controls.
247    /// Strict parsing prevents UAC2 subtype/layout assumptions from admitting
248    /// a selector in another function or an unresolved multiplier path.
249    pub(crate) fn parse_adc3(descriptors: &[u8]) -> Result<Self, String> {
250        use crate::descriptors::uac3 as wire;
251        let mut graph = Self::default();
252        let mut at = 0;
253        let mut ids = HashSet::new();
254        while at < descriptors.len() {
255            let length = usize::from(descriptors[at]);
256            if length < 3 || length > descriptors.len() - at {
257                return Err("ADC3 malformed clock descriptor chain".into());
258            }
259            let d = &descriptors[at..at + length];
260            at += length;
261            if d[1] != USB_DT_CS_INTERFACE || d[2] == 1 {
262                continue;
263            }
264            if d.len() < 4 || d[3] == 0 || !ids.insert(d[3]) {
265                return Err("ADC3 ambiguous clock entity ID".into());
266            }
267            match d[2] {
268                2 => {
269                    let t = wire::parse_input_terminal(d).map_err(|e| e.to_string())?;
270                    graph.terminal_clock.insert(t.id, t.clock_id);
271                }
272                3 => {
273                    let t = wire::parse_output_terminal(d).map_err(|e| e.to_string())?;
274                    graph.terminal_clock.insert(t.id, t.clock_id);
275                }
276                0x0b => {
277                    let c = wire::parse_clock_source(d).map_err(|e| e.to_string())?;
278                    graph.entities.insert(c.id, ClockEntity::Source);
279                    graph.exact_sources.insert(c.id);
280                    graph.source_controls.insert(c.id, c.controls.0);
281                }
282                0x0c => {
283                    let c = wire::parse_clock_selector(d).map_err(|e| e.to_string())?;
284                    graph.selector_controls.insert(c.id, c.controls.0);
285                    graph
286                        .entities
287                        .insert(c.id, ClockEntity::Selector(c.sources));
288                }
289                0x0d => {
290                    let c = wire::parse_clock_multiplier(d).map_err(|e| e.to_string())?;
291                    if matches!(c.controls.0 & 3, 1 | 3) && matches!((c.controls.0 >> 2) & 3, 1 | 3)
292                    {
293                        graph.readable_multipliers.insert(c.id);
294                    }
295                    graph
296                        .entities
297                        .insert(c.id, ClockEntity::Multiplier(c.source_id));
298                }
299                _ => {}
300            }
301        }
302        Ok(graph)
303    }
304
305    pub(crate) fn multiplier_choice_source_exact(&self, choice: &ClockChoice) -> bool {
306        self.exact_sources.contains(&choice.source_id)
307            && matches!(
308                self.source_controls
309                    .get(&choice.source_id)
310                    .copied()
311                    .unwrap_or(0)
312                    & 3,
313                1 | 3
314            )
315            && choice
316                .path
317                .iter()
318                .all(|h| h.id != 0 && !self.duplicate_ids.contains(&h.id))
319    }
320
321    pub(crate) fn multiplier_readable(&self, id: u8) -> bool {
322        self.readable_multipliers.contains(&id) && !self.duplicate_ids.contains(&id)
323    }
324
325    pub(crate) fn choice_for_plan(
326        &self,
327        control: u8,
328        terminal: u8,
329        plan: &ClockPlan,
330    ) -> ClockChoice {
331        let mut path = vec![ClockHop {
332            id: terminal,
333            kind: ClockHopKind::Terminal,
334        }];
335        for &id in &plan.path {
336            let kind = match self.entities.get(&id) {
337                Some(ClockEntity::Multiplier(_)) => ClockHopKind::Multiplier,
338                Some(ClockEntity::Selector(inputs)) => ClockHopKind::Selector {
339                    selected_pin: plan
340                        .selectors
341                        .iter()
342                        .find(|p| p.selector == id)
343                        .map_or(1, |p| p.target),
344                    pin_count: inputs.len() as u8,
345                },
346                _ => ClockHopKind::Source,
347            };
348            path.push(ClockHop { id, kind });
349        }
350        ClockChoice {
351            control_interface: control,
352            source_id: plan.source_id,
353            path,
354            resolution: ClockResolution::Resolved,
355        }
356    }
357
358    // Only the affected terminal branch loses legacy fallback; unrelated sparse
359    // topologies retain it. Traversal is bounded and never asks hardware.
360    pub(crate) fn terminal_may_use_multiplier(&self, terminal: u8) -> bool {
361        let mut pending: Vec<_> = self
362            .terminal_clock
363            .get(&terminal)
364            .copied()
365            .into_iter()
366            .collect();
367        let mut seen = HashSet::new();
368        while let Some(id) = pending.pop() {
369            if !seen.insert(id) {
370                continue;
371            }
372            if self.multiplier_ids.contains(&id) {
373                return true;
374            }
375            if let Some(ClockEntity::Selector(inputs)) = self.entities.get(&id) {
376                pending.extend(inputs);
377            }
378        }
379        false
380    }
381
382    /// Enumerate exact selectable UAC2 paths, current pin first at every branch.
383    /// Reads are cached per selector; a failed/illegal read cannot be safely
384    /// restored and therefore excludes that selector entirely. This never uses
385    /// the legacy first-source or sparse-descriptor fallback. Exact readable
386    /// multiplier descriptors may be traversed; transport must read and verify
387    /// their current raw factors before treating a plan as a known cadence.
388    pub(crate) fn enumerate_plans(
389        &self,
390        terminal_id: u8,
391        mut read_pin: impl FnMut(u8) -> Result<u8, String>,
392    ) -> Result<Vec<ClockPlan>, String> {
393        if self.duplicate_ids.contains(&terminal_id) {
394            return Err(format!("terminal {terminal_id} has a duplicate entity ID"));
395        }
396        let first = *self
397            .terminal_clock
398            .get(&terminal_id)
399            .ok_or_else(|| format!("terminal {terminal_id} has no clock link"))?;
400        let mut search = ClockSearch {
401            graph: self,
402            pins: HashMap::new(),
403            read_pin: &mut read_pin,
404            remaining: 4096,
405            plans: Vec::new(),
406        };
407        search.walk(first, &mut Vec::new(), &mut Vec::new())?;
408        if search.plans.is_empty() {
409            return Err(format!(
410                "terminal {terminal_id} has no exact selectable clock path"
411            ));
412        }
413        Ok(search.plans)
414    }
415
416    /// True if any clock entity was described. Without one (UAC 1.0 has none)
417    /// there is no clock topology to resolve.
418    pub(crate) fn has_clock_entities(&self) -> bool {
419        !self.entities.is_empty()
420    }
421
422    /// The first Clock Source in descriptor order: the last-resort answer when
423    /// the topology cannot be resolved.
424    pub(crate) fn first_clock_source(&self) -> Option<u8> {
425        self.first_source
426    }
427
428    /// Walk from `terminal_id` to the Clock Source currently feeding it.
429    ///
430    /// `selected_pin` is asked for the 1-based current input pin of a Clock
431    /// Selector, and only for a selector with more than one input. A selector
432    /// with one input has nothing to choose, and a multiplier has a single
433    /// clock input, so neither needs a request.
434    ///
435    /// An ID with no clock descriptor of its own is taken to be the source:
436    /// sparse descriptors do exist, and the old behaviour of treating it as
437    /// unusable sent the sample rate to the wrong clock.
438    pub(crate) fn resolve_terminal_clock(
439        &self,
440        terminal_id: u8,
441        mut selected_pin: impl FnMut(u8) -> Result<u8, String>,
442    ) -> Result<ResolvedClock, ClockResolveError> {
443        let first = *self
444            .terminal_clock
445            .get(&terminal_id)
446            .ok_or(ClockResolveError::TerminalNotFound(terminal_id))?;
447        if first == 0 {
448            return Err(ClockResolveError::TerminalHasNoClock(terminal_id));
449        }
450
451        let mut path = vec![first];
452        let mut hops = vec![ClockHop {
453            id: terminal_id,
454            kind: ClockHopKind::Terminal,
455        }];
456        loop {
457            let current = *path.last().expect("path starts non-empty");
458            match self.entities.get(&current) {
459                None | Some(ClockEntity::Source) => {
460                    let assumed_source = !self.entities.contains_key(&current);
461                    hops.push(ClockHop {
462                        id: current,
463                        kind: ClockHopKind::Source,
464                    });
465                    return Ok(ResolvedClock {
466                        clock_id: current,
467                        path,
468                        hops,
469                        assumed_source,
470                    });
471                }
472                Some(ClockEntity::Malformed) => {
473                    return Err(ClockResolveError::MalformedEntity(current));
474                }
475                Some(ClockEntity::Multiplier(input)) => {
476                    if *input == 0 {
477                        return Err(ClockResolveError::MalformedEntity(current));
478                    }
479                    hops.push(ClockHop {
480                        id: current,
481                        kind: ClockHopKind::Multiplier,
482                    });
483                    path.push(*input);
484                }
485                Some(ClockEntity::Selector(inputs)) => {
486                    let pin_count = u8::try_from(inputs.len()).unwrap_or(u8::MAX);
487                    let (next, pin) = match inputs.as_slice() {
488                        [] => return Err(ClockResolveError::SelectorWithoutInputs(current)),
489                        [only] => (*only, 1),
490                        many => {
491                            let pin = selected_pin(current).map_err(|reason| {
492                                ClockResolveError::PinUnavailable {
493                                    selector: current,
494                                    reason,
495                                }
496                            })?;
497                            if pin == 0 || usize::from(pin) > many.len() {
498                                return Err(ClockResolveError::PinOutOfRange {
499                                    selector: current,
500                                    pin,
501                                    inputs: many.len(),
502                                });
503                            }
504                            (many[usize::from(pin) - 1], pin)
505                        }
506                    };
507                    if next == 0 {
508                        return Err(ClockResolveError::MalformedEntity(current));
509                    }
510                    hops.push(ClockHop {
511                        id: current,
512                        kind: ClockHopKind::Selector {
513                            selected_pin: pin,
514                            pin_count,
515                        },
516                    });
517                    path.push(next);
518                }
519            }
520            // An entity may appear once; reaching one again is a loop.
521            let last = *path.last().expect("path is non-empty");
522            if path[..path.len() - 1].contains(&last) {
523                return Err(ClockResolveError::Loop(last));
524            }
525            if path.len() > MAX_CLOCK_PATH {
526                return Err(ClockResolveError::TooDeep);
527            }
528        }
529    }
530
531    /// The clock the sample rate is programmed on for the stream whose
532    /// AudioStreaming interface links `terminal_link`, on the AudioControl
533    /// interface `control_interface`.
534    ///
535    /// The terminal is traced to its Clock Source with
536    /// [`resolve_terminal_clock`](Self::resolve_terminal_clock). When that
537    /// fails (or the stream names no terminal) the first Clock Source in
538    /// descriptor order is used instead, and the result says so. `Err` carries
539    /// the reason when there is no clock to choose: the interface describes no
540    /// clock entities, or none is a Clock Source to fall back on.
541    pub(crate) fn select_clock(
542        &self,
543        control_interface: u8,
544        terminal_link: Option<u8>,
545        selected_pin: impl FnMut(u8) -> Result<u8, String>,
546    ) -> Result<ClockSelection, String> {
547        // UAC 1.0 describes no clock entities, and its terminal descriptors must
548        // not be read as if they named one.
549        if !self.has_clock_entities() {
550            return Err("the AudioControl interface describes no clock entities".to_string());
551        }
552        let unresolved = match terminal_link {
553            None => "the stream has no bTerminalLink to trace its clock from".to_string(),
554            Some(terminal) => match self.resolve_terminal_clock(terminal, selected_pin) {
555                Ok(resolved) => {
556                    return Ok(ClockSelection {
557                        choice: ClockChoice {
558                            control_interface,
559                            source_id: resolved.clock_id,
560                            path: resolved.hops,
561                            resolution: ClockResolution::Resolved,
562                        },
563                        assumed_source: resolved.assumed_source,
564                        unresolved: None,
565                    });
566                }
567                Err(error) => error.to_string(),
568            },
569        };
570        if terminal_link.is_some_and(|id| self.terminal_may_use_multiplier(id)) {
571            return Err(format!("unresolved multiplier clock path: {unresolved}"));
572        }
573        match self.first_clock_source() {
574            Some(source_id) => Ok(ClockSelection {
575                choice: ClockChoice {
576                    control_interface,
577                    source_id,
578                    path: vec![ClockHop {
579                        id: source_id,
580                        kind: ClockHopKind::Source,
581                    }],
582                    resolution: ClockResolution::FallbackFirstSource,
583                },
584                assumed_source: false,
585                unresolved: Some(unresolved),
586            }),
587            None => Err(unresolved),
588        }
589    }
590}
591
592/// Descriptor-aware clock validity, shared by UAC2 and full ADC3.
593#[derive(Debug, Clone, Copy, PartialEq, Eq)]
594pub(crate) enum ClockValidity {
595    Unreported,
596    ReportedValid,
597}
598
599pub(crate) fn clock_validity(
600    controls: u32,
601    mut read: impl FnMut() -> Result<bool, String>,
602) -> Result<ClockValidity, String> {
603    match (controls >> 2) & 3 {
604        0 => Ok(ClockValidity::Unreported),
605        1 | 3 => match read()? {
606            true => Ok(ClockValidity::ReportedValid),
607            false => Err("clock source reports invalid".into()),
608        },
609        _ => Err("clock validity access is reserved".into()),
610    }
611}
612
613/// One selector's snapshot and requested 1-based pin. Kept even for unchanged
614/// selectors so opening a negotiated plan can reject intervening route changes.
615#[derive(Debug, Clone, PartialEq, Eq)]
616pub(crate) struct ClockPinPlan {
617    pub selector: u8,
618    pub original: u8,
619    pub target: u8,
620}
621
622#[derive(Debug, Clone, PartialEq, Eq)]
623pub(crate) struct ClockPlan {
624    pub source_id: u8,
625    /// Descriptor controls at protocol width; absent validity is not a valid response.
626    pub source_controls: u32,
627    /// Root-to-source entity IDs, excluding the streaming terminal.
628    pub path: Vec<u8>,
629    /// Root-to-leaf selector order, including unchanged pins.
630    pub selectors: Vec<ClockPinPlan>,
631}
632
633/// Transport boundary shared by plan application and hand-back. Implementations
634/// must perform exact-length control transfers, including GET after each SET.
635pub(crate) trait ClockPlanIo {
636    fn read_pin(&mut self, selector: u8) -> Result<u8, String>;
637    fn write_pin(&mut self, selector: u8, pin: u8) -> Result<(), String>;
638    /// Check validity and requested sampling cadence on this exact source.
639    /// Called after the whole path is selected, even when no selector changes.
640    fn validate_source(&mut self, source: u8, controls: u32) -> Result<(), String>;
641}
642
643#[derive(Debug, Clone, PartialEq, Eq)]
644pub(crate) struct ClockPlanError {
645    pub reason: String,
646    /// A non-empty list means the hardware route could not be restored.
647    pub rollback_errors: Vec<String>,
648}
649
650impl fmt::Display for ClockPlanError {
651    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
652        write!(f, "{}", self.reason)?;
653        for error in &self.rollback_errors {
654            write!(f, "; rollback: {error}")?;
655        }
656        Ok(())
657    }
658}
659
660impl ClockPlan {
661    /// Reject stale negotiation before any write. Apply downstream selectors
662    /// first, verify each write, then validate the exact source. A failed SET
663    /// may have reached hardware, so include it in the rollback attempt.
664    pub(crate) fn apply(&self, io: &mut impl ClockPlanIo) -> Result<(), ClockPlanError> {
665        let mut attempted = Vec::new();
666        let result = (|| {
667            for pin in &self.selectors {
668                verify_pin(io, pin.selector, pin.original)?;
669            }
670            for pin in self
671                .selectors
672                .iter()
673                .rev()
674                .filter(|pin| pin.original != pin.target)
675            {
676                attempted.push(pin);
677                io.write_pin(pin.selector, pin.target)?;
678                verify_pin(io, pin.selector, pin.target)?;
679            }
680            // Re-read unchanged selectors too: a route change during apply
681            // must not turn an unrelated source's validity into acceptance.
682            for pin in &self.selectors {
683                verify_pin(io, pin.selector, pin.target)?;
684            }
685            io.validate_source(self.source_id, self.source_controls)
686        })();
687        match result {
688            Ok(()) => Ok(()),
689            Err(reason) => Err(ClockPlanError {
690                reason,
691                rollback_errors: restore_pins(io, attempted.into_iter().rev()),
692            }),
693        }
694    }
695
696    /// Explicit hand-back after a successful apply. Check the whole selected
697    /// route before restoring anything, to avoid overwriting an external change.
698    pub(crate) fn restore(&self, io: &mut impl ClockPlanIo) -> Result<(), ClockPlanError> {
699        for pin in &self.selectors {
700            verify_pin(io, pin.selector, pin.target).map_err(|reason| ClockPlanError {
701                reason,
702                rollback_errors: Vec::new(),
703            })?;
704        }
705        let errors = restore_pins(io, self.selectors.iter().filter(|p| p.original != p.target));
706        if errors.is_empty() {
707            Ok(())
708        } else {
709            Err(ClockPlanError {
710                reason: "clock hand-back failed".into(),
711                rollback_errors: errors,
712            })
713        }
714    }
715}
716
717fn verify_pin(io: &mut impl ClockPlanIo, selector: u8, expected: u8) -> Result<(), String> {
718    let actual = io.read_pin(selector)?;
719    if actual != expected {
720        return Err(format!(
721            "clock selector {selector} expected pin {expected}, read {actual}"
722        ));
723    }
724    Ok(())
725}
726
727fn restore_pins<'a>(
728    io: &mut impl ClockPlanIo,
729    pins: impl Iterator<Item = &'a ClockPinPlan>,
730) -> Vec<String> {
731    let mut errors = Vec::new();
732    for pin in pins {
733        if let Err(error) = io
734            .write_pin(pin.selector, pin.original)
735            .and_then(|()| verify_pin(io, pin.selector, pin.original))
736        {
737            errors.push(format!("selector {}: {error}", pin.selector));
738        }
739    }
740    errors
741}
742
743struct ClockSearch<'a, F> {
744    graph: &'a ClockGraph,
745    pins: HashMap<u8, Option<u8>>,
746    read_pin: &'a mut F,
747    remaining: usize,
748    plans: Vec<ClockPlan>,
749}
750
751impl<F: FnMut(u8) -> Result<u8, String>> ClockSearch<'_, F> {
752    fn walk(
753        &mut self,
754        id: u8,
755        path: &mut Vec<u8>,
756        selectors: &mut Vec<ClockPinPlan>,
757    ) -> Result<(), String> {
758        // Bound work as well as path depth: shared DAG branches can otherwise
759        // produce exponentially many paths despite per-path cycle detection.
760        if self.remaining == 0 || self.plans.len() >= 256 {
761            return Err("clock graph enumeration exceeds its bounded search budget".into());
762        }
763        self.remaining -= 1;
764        if id == 0
765            || self.graph.duplicate_ids.contains(&id)
766            || path.len() >= MAX_CLOCK_PATH
767            || path.contains(&id)
768        {
769            return Ok(());
770        }
771        path.push(id);
772        match self.graph.entities.get(&id) {
773            Some(ClockEntity::Source) if self.graph.exact_sources.contains(&id) => {
774                self.plans.push(ClockPlan {
775                    source_id: id,
776                    source_controls: self.graph.source_controls[&id],
777                    path: path.clone(),
778                    selectors: selectors.clone(),
779                });
780            }
781            Some(ClockEntity::Selector(inputs))
782                if !inputs.is_empty() && self.graph.selector_controls.contains_key(&id) =>
783            {
784                let controls = self.graph.selector_controls.get(&id).copied().unwrap_or(0) & 3;
785                // UAC2: 00 absent, 01 read-only, 10 reserved, 11 read/write.
786                if inputs.len() == 1 {
787                    self.walk(inputs[0], path, selectors)?;
788                } else if controls == 1 || controls == 3 {
789                    let current = *self.pins.entry(id).or_insert_with(|| {
790                        (self.read_pin)(id)
791                            .ok()
792                            .filter(|pin| *pin > 0 && usize::from(*pin) <= inputs.len())
793                    });
794                    if let Some(current) = current {
795                        let order = std::iter::once(current).chain(
796                            (1..=inputs.len() as u8).filter(|pin| controls == 3 && *pin != current),
797                        );
798                        for target in order {
799                            selectors.push(ClockPinPlan {
800                                selector: id,
801                                original: current,
802                                target,
803                            });
804                            self.walk(inputs[usize::from(target) - 1], path, selectors)?;
805                            selectors.pop();
806                        }
807                    }
808                }
809            }
810            Some(ClockEntity::Multiplier(input))
811                if self.graph.readable_multipliers.contains(&id) =>
812            {
813                self.walk(*input, path, selectors)?;
814            }
815            // Missing/malformed entities and unresolved multiplier ratios do
816            // not prove a programmable source and never produce a fallback.
817            _ => {}
818        }
819        path.pop();
820        Ok(())
821    }
822}
823
824/// What [`ClockGraph::select_clock`] chose, with what the transport logs about it.
825#[derive(Debug, Clone, PartialEq, Eq)]
826pub(crate) struct ClockSelection {
827    pub choice: ClockChoice,
828    /// The source has no descriptor of its own and was taken to be one.
829    pub assumed_source: bool,
830    /// Why the topology could not be traced. Set exactly when the choice is
831    /// [`ClockResolution::FallbackFirstSource`].
832    pub unresolved: Option<String>,
833}
834
835#[derive(Debug, Clone, PartialEq, Eq)]
836pub(crate) struct ResolvedClock {
837    pub clock_id: u8,
838    /// Entity IDs from the terminal's `bCSourceID` to `clock_id`, inclusive.
839    pub path: Vec<u8>,
840    /// The same walk with what each entity is, starting at the terminal itself.
841    pub hops: Vec<ClockHop>,
842    /// `clock_id` has no descriptor of its own and was taken to be the source.
843    pub assumed_source: bool,
844}
845
846#[cfg(test)]
847impl ResolvedClock {
848    /// Shared source IDs prove equal sample cadence only without an unknown
849    /// multiplier ratio, and only when the source is actually described.
850    pub(crate) fn proves_identity_cadence(&self) -> bool {
851        if self.assumed_source
852            || self
853                .hops
854                .iter()
855                .any(|hop| matches!(hop.kind, ClockHopKind::Multiplier))
856        {
857            return false;
858        }
859        let factors: Vec<_> = self
860            .hops
861            .iter()
862            .filter_map(|hop| match hop.kind {
863                ClockHopKind::RateMultiplier {
864                    numerator,
865                    denominator,
866                } => Some((numerator, denominator)),
867                _ => None,
868            })
869            .collect();
870        RateRatio::from_factors(&factors) == Ok(RateRatio::IDENTITY)
871    }
872}
873
874#[derive(Debug, Clone, PartialEq, Eq)]
875pub(crate) enum ClockResolveError {
876    TerminalNotFound(u8),
877    TerminalHasNoClock(u8),
878    MalformedEntity(u8),
879    SelectorWithoutInputs(u8),
880    PinUnavailable {
881        selector: u8,
882        reason: String,
883    },
884    PinOutOfRange {
885        selector: u8,
886        pin: u8,
887        inputs: usize,
888    },
889    Loop(u8),
890    TooDeep,
891}
892
893impl fmt::Display for ClockResolveError {
894    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
895        match self {
896            Self::TerminalNotFound(id) => {
897                write!(f, "terminal {id} is not in the AudioControl descriptors")
898            }
899            Self::TerminalHasNoClock(id) => {
900                write!(f, "terminal {id} names no clock (bCSourceID 0)")
901            }
902            Self::MalformedEntity(id) => write!(f, "clock entity {id} has a malformed descriptor"),
903            Self::SelectorWithoutInputs(id) => write!(f, "clock selector {id} has no input pins"),
904            Self::PinUnavailable { selector, reason } => {
905                write!(
906                    f,
907                    "current pin of clock selector {selector} is unavailable: {reason}"
908                )
909            }
910            Self::PinOutOfRange {
911                selector,
912                pin,
913                inputs,
914            } => write!(
915                f,
916                "clock selector {selector} reports pin {pin}, outside its {inputs} inputs"
917            ),
918            Self::Loop(id) => write!(f, "clock entity {id} feeds itself"),
919            Self::TooDeep => write!(f, "clock topology is deeper than {MAX_CLOCK_PATH} entities"),
920        }
921    }
922}
923
924/// Concatenate the class-specific descriptors of one AudioControl interface
925/// from a raw configuration descriptor. Used when the platform hands back no
926/// `extra` bytes for the interface.
927pub(crate) fn audio_control_descriptors_from_config(
928    raw: &[u8],
929    ac_interface_number: u8,
930) -> Vec<u8> {
931    let mut collected = Vec::new();
932    let mut inside_ac_interface = false;
933    let mut pos = 0usize;
934    while pos + 1 < raw.len() {
935        let length = raw[pos] as usize;
936        if length < 2 || pos + length > raw.len() {
937            break;
938        }
939        let descriptor = &raw[pos..pos + length];
940        pos += length;
941        if descriptor[1] == USB_DT_INTERFACE && length >= 9 {
942            inside_ac_interface = descriptor[2] == ac_interface_number
943                && descriptor[5] == USB_CLASS_AUDIO
944                && descriptor[6] == USB_SUBCLASS_AUDIOCONTROL;
945        } else if inside_ac_interface && descriptor[1] == USB_DT_CS_INTERFACE {
946            collected.extend_from_slice(descriptor);
947        }
948    }
949    collected
950}
951
952#[cfg(test)]
953mod implicit_clock_tests {
954    use super::*;
955    #[test]
956    fn implicit_proof_rejects_sparse_sources_and_unknown_multiplier_ratios() {
957        let terminal = [8, 0x24, 2, 1, 0, 0, 0, 10];
958        let mut descriptors = terminal.to_vec();
959        let sparse = ClockGraph::parse(&descriptors)
960            .resolve_terminal_clock(1, |_| unreachable!())
961            .unwrap();
962        assert!(!sparse.proves_identity_cadence());
963        descriptors.extend_from_slice(&[8, 0x24, 0x0a, 10, 0, 0, 0, 0]);
964        let direct = ClockGraph::parse(&descriptors)
965            .resolve_terminal_clock(1, |_| unreachable!())
966            .unwrap();
967        assert!(direct.proves_identity_cadence());
968        descriptors[7] = 11;
969        descriptors.extend_from_slice(&[7, 0x24, 0x0c, 11, 10, 0, 0]);
970        let multiplied = ClockGraph::parse(&descriptors)
971            .resolve_terminal_clock(1, |_| unreachable!())
972            .unwrap();
973        assert!(!multiplied.proves_identity_cadence());
974    }
975
976    #[test]
977    fn implicit_proof_accounts_for_exact_multiplier_ratios() {
978        let mut clock = ResolvedClock {
979            clock_id: 10,
980            path: vec![11, 10],
981            hops: vec![ClockHop {
982                id: 11,
983                kind: ClockHopKind::RateMultiplier {
984                    numerator: 3,
985                    denominator: 2,
986                },
987            }],
988            assumed_source: false,
989        };
990        assert_eq!(clock.hops[0].kind.code(), "multiplier");
991        assert!(!clock.proves_identity_cadence());
992        clock.hops.push(ClockHop {
993            id: 12,
994            kind: ClockHopKind::RateMultiplier {
995                numerator: 2,
996                denominator: 3,
997            },
998        });
999        assert!(clock.proves_identity_cadence());
1000        clock.hops.push(ClockHop {
1001            id: 13,
1002            kind: ClockHopKind::Multiplier,
1003        });
1004        assert!(!clock.proves_identity_cadence());
1005        clock.hops.pop();
1006        clock.hops[0].kind = ClockHopKind::RateMultiplier {
1007            numerator: 0,
1008            denominator: 1,
1009        };
1010        assert!(!clock.proves_identity_cadence());
1011    }
1012}
1013
1014#[cfg(test)]
1015mod adc3_multiplier_graph_tests {
1016    use super::*;
1017
1018    fn descriptors(controls: u8) -> Vec<u8> {
1019        // Input Terminal 1 -> Multiplier 11 -> Source 10.
1020        let mut terminal = vec![0; 20];
1021        terminal[..4].copy_from_slice(&[20, 0x24, 2, 1]);
1022        terminal[4..6].copy_from_slice(&0x0101u16.to_le_bytes());
1023        terminal[7] = 11;
1024        terminal[12..14].copy_from_slice(&1u16.to_le_bytes());
1025        terminal.extend_from_slice(&[11, 0x24, 0x0d, 11, 10, controls, 0, 0, 0, 0, 0]);
1026        terminal.extend_from_slice(&[12, 0x24, 0x0b, 10, 1, 3, 0, 0, 0, 0, 0, 0]);
1027        terminal
1028    }
1029
1030    #[test]
1031    fn adc3_enumerates_only_multipliers_with_both_controls_readable() {
1032        for controls in [0x05, 0x07, 0x0d, 0x0f] {
1033            let graph = ClockGraph::parse_adc3(&descriptors(controls)).unwrap();
1034            let plans = graph.enumerate_plans(1, |_| unreachable!()).unwrap();
1035            assert_eq!(plans.len(), 1);
1036            assert_eq!(plans[0].path, vec![11, 10]);
1037            assert_eq!(plans[0].source_id, 10);
1038        }
1039        for controls in [0x00, 0x01, 0x04, 0x06, 0x09, 0x0a] {
1040            let graph = ClockGraph::parse_adc3(&descriptors(controls)).unwrap();
1041            assert!(graph.enumerate_plans(1, |_| unreachable!()).is_err());
1042        }
1043    }
1044
1045    #[test]
1046    fn adc3_multiplier_paths_remain_bounded_and_require_described_sources() {
1047        let mut missing = descriptors(0x05);
1048        missing.truncate(31);
1049        assert!(ClockGraph::parse_adc3(&missing)
1050            .unwrap()
1051            .enumerate_plans(1, |_| unreachable!())
1052            .is_err());
1053        let mut cycle = descriptors(0x05);
1054        cycle[24] = 11;
1055        assert!(ClockGraph::parse_adc3(&cycle)
1056            .unwrap()
1057            .enumerate_plans(1, |_| unreachable!())
1058            .is_err());
1059    }
1060}
1061
1062#[cfg(test)]
1063mod selectable_clock_tests {
1064    use super::*;
1065
1066    fn graph(extra: &[u8]) -> ClockGraph {
1067        let mut bytes = vec![8, 0x24, 2, 1, 0, 0, 0, 10];
1068        bytes.extend_from_slice(extra);
1069        ClockGraph::parse(&bytes)
1070    }
1071
1072    const SOURCES: &[u8] = &[8, 0x24, 0x0a, 20, 0, 0, 0, 0, 8, 0x24, 0x0a, 21, 0, 0, 0, 0];
1073
1074    fn selector(controls: u8) -> ClockGraph {
1075        let mut extra = vec![9, 0x24, 0x0b, 10, 2, 20, 21, controls, 0];
1076        extra.extend_from_slice(SOURCES);
1077        graph(&extra)
1078    }
1079
1080    #[derive(Default)]
1081    struct Device {
1082        pins: HashMap<u8, u8>,
1083        writes: Vec<(u8, u8)>,
1084        checked: Vec<u8>,
1085        invalid_source: bool,
1086        reported_valid: bool,
1087        validity_read_fails: bool,
1088        validity_reads: usize,
1089        bad_write: bool,
1090        fail_restore: bool,
1091    }
1092
1093    impl ClockPlanIo for Device {
1094        fn read_pin(&mut self, id: u8) -> Result<u8, String> {
1095            self.pins
1096                .get(&id)
1097                .copied()
1098                .ok_or_else(|| "missing pin".into())
1099        }
1100        fn write_pin(&mut self, id: u8, pin: u8) -> Result<(), String> {
1101            self.writes.push((id, pin));
1102            if self.fail_restore && pin == 1 {
1103                return Err("restore transfer failed".into());
1104            }
1105            if !self.bad_write {
1106                self.pins.insert(id, pin);
1107            }
1108            Ok(())
1109        }
1110        fn validate_source(&mut self, id: u8, controls: u32) -> Result<(), String> {
1111            self.checked.push(id);
1112            clock_validity(controls, || {
1113                self.validity_reads += 1;
1114                if self.validity_read_fails {
1115                    Err("advertised read failed".into())
1116                } else {
1117                    Ok(self.reported_valid)
1118                }
1119            })?;
1120            if self.invalid_source {
1121                Err("source invalid or unsupported rate".into())
1122            } else {
1123                Ok(())
1124            }
1125        }
1126    }
1127
1128    #[test]
1129    fn source_validity_uses_descriptor_capability_and_preserves_unreported_state() {
1130        assert_eq!(
1131            clock_validity(0, || panic!("absent control must not be read")),
1132            Ok(ClockValidity::Unreported)
1133        );
1134        assert_eq!(
1135            clock_validity(4, || Ok(true)),
1136            Ok(ClockValidity::ReportedValid)
1137        );
1138        assert!(clock_validity(4, || Ok(false)).is_err());
1139        assert!(clock_validity(12, || Err("advertised read failed".into())).is_err());
1140        assert!(clock_validity(8, || panic!("reserved must not be read")).is_err());
1141        assert_eq!(
1142            clock_validity(0xffff_fff3, || panic!(
1143                "high ADC3 bits must not imply validity"
1144            )),
1145            Ok(ClockValidity::Unreported)
1146        );
1147        let plans = selector(3).enumerate_plans(1, |_| Ok(1)).unwrap();
1148        assert_eq!(plans[0].source_controls, 0);
1149    }
1150
1151    #[test]
1152    fn valid_current_route_has_priority_and_never_sets() {
1153        let plans = selector(3).enumerate_plans(1, |_| Ok(2)).unwrap();
1154        assert_eq!(
1155            plans.iter().map(|p| p.source_id).collect::<Vec<_>>(),
1156            [21, 20]
1157        );
1158        let mut io = Device {
1159            pins: HashMap::from([(10, 2)]),
1160            ..Device::default()
1161        };
1162        plans[0].apply(&mut io).unwrap();
1163        assert!(io.writes.is_empty());
1164        assert_eq!(io.checked, [21]);
1165        assert_eq!(io.validity_reads, 0);
1166    }
1167
1168    #[test]
1169    fn selector_capabilities_and_illegal_pins_block_unsafe_alternatives() {
1170        assert_eq!(selector(1).enumerate_plans(1, |_| Ok(1)).unwrap().len(), 1);
1171        for controls in [0, 2] {
1172            assert!(selector(controls)
1173                .enumerate_plans(1, |_| panic!("unreadable"))
1174                .is_err());
1175        }
1176        for pin in [0, 3] {
1177            assert!(selector(3).enumerate_plans(1, |_| Ok(pin)).is_err());
1178        }
1179        assert!(selector(3)
1180            .enumerate_plans(1, |_| Err("GET failed".into()))
1181            .is_err());
1182    }
1183
1184    #[test]
1185    fn alternatives_are_verified_and_restored_on_failure_or_hand_back() {
1186        let plan = selector(3).enumerate_plans(1, |_| Ok(1)).unwrap().remove(1);
1187        let mut io = Device {
1188            pins: HashMap::from([(10, 1)]),
1189            invalid_source: true,
1190            ..Device::default()
1191        };
1192        let failure = plan.apply(&mut io).unwrap_err();
1193        assert!(failure.rollback_errors.is_empty());
1194        assert_eq!(io.writes, [(10, 2), (10, 1)]);
1195        io.invalid_source = false;
1196        plan.apply(&mut io).unwrap();
1197        plan.restore(&mut io).unwrap();
1198        assert_eq!(io.pins[&10], 1);
1199    }
1200
1201    #[test]
1202    fn advertised_validity_failures_restore_the_original_selector() {
1203        for read_fails in [false, true] {
1204            let mut extra = vec![9, 0x24, 0x0b, 10, 2, 20, 21, 3, 0];
1205            let mut sources = SOURCES.to_vec();
1206            sources[13] = 7; // source 21: frequency R/W, validity readable.
1207            extra.extend_from_slice(&sources);
1208            let plan = graph(&extra)
1209                .enumerate_plans(1, |_| Ok(1))
1210                .unwrap()
1211                .remove(1);
1212            assert_eq!(plan.source_controls, 7);
1213            let mut io = Device {
1214                pins: HashMap::from([(10, 1)]),
1215                validity_read_fails: read_fails,
1216                ..Device::default()
1217            };
1218            let error = plan.apply(&mut io).unwrap_err();
1219            assert!(error.rollback_errors.is_empty());
1220            assert_eq!(io.writes, [(10, 2), (10, 1)]);
1221            assert_eq!(io.validity_reads, 1);
1222            assert_eq!(io.pins[&10], 1);
1223        }
1224    }
1225
1226    #[test]
1227    fn stale_route_and_unverified_set_cannot_validate_an_unrelated_source() {
1228        let plan = selector(3).enumerate_plans(1, |_| Ok(1)).unwrap().remove(1);
1229        let mut io = Device {
1230            pins: HashMap::from([(10, 2)]),
1231            ..Device::default()
1232        };
1233        assert!(plan.apply(&mut io).is_err());
1234        assert!(io.writes.is_empty());
1235        io.pins.insert(10, 1);
1236        io.bad_write = true;
1237        assert!(plan.apply(&mut io).is_err());
1238        assert!(io.checked.is_empty());
1239    }
1240
1241    #[test]
1242    fn path_local_cycles_do_not_poison_shared_source_sibling() {
1243        // First branch loops back to the selector; second reaches a source.
1244        let mut bytes = vec![9, 0x24, 0x0b, 10, 2, 10, 20, 3, 0];
1245        bytes.extend_from_slice(SOURCES);
1246        let plans = graph(&bytes).enumerate_plans(1, |_| Ok(1)).unwrap();
1247        assert_eq!(plans.len(), 1);
1248        assert_eq!(plans[0].source_id, 20);
1249        // Both sibling branches may reach the same source independently.
1250        bytes[5] = 20;
1251        assert_eq!(
1252            graph(&bytes).enumerate_plans(1, |_| Ok(1)).unwrap().len(),
1253            2
1254        );
1255    }
1256
1257    #[test]
1258    fn strict_routes_reject_missing_sources_multipliers_and_truncated_selectors() {
1259        assert!(graph(&[]).enumerate_plans(1, |_| unreachable!()).is_err());
1260        let mut bytes = vec![7, 0x24, 0x0c, 10, 20, 0, 0];
1261        bytes.extend_from_slice(SOURCES);
1262        assert!(graph(&bytes)
1263            .enumerate_plans(1, |_| unreachable!())
1264            .is_err());
1265        let mut bytes = vec![6, 0x24, 0x0b, 10, 1, 20];
1266        bytes.extend_from_slice(SOURCES);
1267        assert!(graph(&bytes)
1268            .enumerate_plans(1, |_| unreachable!())
1269            .is_err());
1270        // Legacy sparse behaviour remains explicitly available.
1271        assert_eq!(
1272            graph(&[])
1273                .resolve_terminal_clock(1, |_| unreachable!())
1274                .unwrap()
1275                .clock_id,
1276            10
1277        );
1278    }
1279
1280    #[test]
1281    fn failed_rollback_is_visible_and_hand_back_never_overwrites_drift() {
1282        let plan = selector(3).enumerate_plans(1, |_| Ok(1)).unwrap().remove(1);
1283        let mut io = Device {
1284            pins: HashMap::from([(10, 1)]),
1285            invalid_source: true,
1286            fail_restore: true,
1287            ..Device::default()
1288        };
1289        let error = plan.apply(&mut io).unwrap_err();
1290        assert_eq!(error.rollback_errors.len(), 1);
1291        assert_eq!(io.pins[&10], 2);
1292        io.writes.clear();
1293        io.pins.insert(10, 1);
1294        assert!(plan.restore(&mut io).is_err());
1295        assert!(io.writes.is_empty());
1296    }
1297
1298    #[test]
1299    fn duplicate_ids_and_excessive_depth_never_produce_selectable_routes() {
1300        let mut bytes = vec![8, 0x24, 0x0a, 10, 0, 0, 0, 0, 8, 0x24, 0x0a, 10, 0, 0, 0, 0];
1301        assert!(graph(&bytes)
1302            .enumerate_plans(1, |_| unreachable!())
1303            .is_err());
1304        bytes.clear();
1305        for id in 10..27 {
1306            bytes.extend_from_slice(&[8, 0x24, 0x0b, id, 1, id + 1, 0, 0]);
1307        }
1308        bytes.extend_from_slice(&[8, 0x24, 0x0a, 27, 0, 0, 0, 0]);
1309        assert!(graph(&bytes)
1310            .enumerate_plans(1, |_| unreachable!())
1311            .is_err());
1312    }
1313
1314    #[test]
1315    fn nested_plan_changes_leaf_first_and_restores_root_first() {
1316        let mut bytes = vec![
1317            9, 0x24, 0x0b, 10, 2, 20, 11, 3, 0, 9, 0x24, 0x0b, 11, 2, 20, 21, 3, 0,
1318        ];
1319        bytes.extend_from_slice(SOURCES);
1320        let plan = graph(&bytes)
1321            .enumerate_plans(1, |_| Ok(1))
1322            .unwrap()
1323            .pop()
1324            .unwrap();
1325        let mut io = Device {
1326            pins: HashMap::from([(10, 1), (11, 1)]),
1327            ..Device::default()
1328        };
1329        plan.apply(&mut io).unwrap();
1330        assert_eq!(io.writes, [(11, 2), (10, 2)]);
1331        plan.restore(&mut io).unwrap();
1332        assert_eq!(io.writes, [(11, 2), (10, 2), (10, 1), (11, 1)]);
1333    }
1334}
1335
1336#[cfg(test)]
1337mod adc3_plan_tests {
1338    use super::*;
1339    fn descriptors(controls: u32) -> Vec<u8> {
1340        let mut bytes = vec![
1341            20, 0x24, 2, 1, 1, 1, 0, 10, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
1342        ];
1343        bytes.extend_from_slice(&[13, 0x24, 0x0c, 10, 2, 20, 21]);
1344        bytes.extend_from_slice(&controls.to_le_bytes());
1345        bytes.extend_from_slice(&[0, 0]);
1346        for id in [20, 21] {
1347            bytes.extend_from_slice(&[12, 0x24, 0x0b, id, 1]);
1348            bytes.extend_from_slice(&0x8000_0007u32.to_le_bytes());
1349            bytes.extend_from_slice(&[0, 0, 0]);
1350        }
1351        bytes
1352    }
1353    #[test]
1354    fn adc3_current_first_enumeration_preserves_wide_controls_and_pin_snapshot() {
1355        let graph = ClockGraph::parse_adc3(&descriptors(0x8000_0003)).unwrap();
1356        let plans = graph.enumerate_plans(1, |_| Ok(2)).unwrap();
1357        assert_eq!(
1358            plans.iter().map(|p| p.source_id).collect::<Vec<_>>(),
1359            vec![21, 20]
1360        );
1361        assert_eq!(plans[1].source_controls, 0x8000_0007);
1362        assert_eq!(
1363            plans[1].selectors,
1364            vec![ClockPinPlan {
1365                selector: 10,
1366                original: 2,
1367                target: 1
1368            }]
1369        );
1370    }
1371    #[test]
1372    fn adc3_readonly_invalid_and_duplicate_selectors_cannot_mutate() {
1373        let readonly = ClockGraph::parse_adc3(&descriptors(0x8000_0001)).unwrap();
1374        assert_eq!(readonly.enumerate_plans(1, |_| Ok(1)).unwrap().len(), 1);
1375        assert!(readonly.enumerate_plans(1, |_| Ok(0)).is_err());
1376        let reserved = ClockGraph::parse_adc3(&descriptors(0x8000_0002)).unwrap();
1377        assert!(reserved.enumerate_plans(1, |_| Ok(1)).is_err());
1378        let mut duplicate = descriptors(3);
1379        duplicate.extend_from_slice(&[12, 0x24, 0x0b, 20, 1, 7, 0, 0, 0, 0, 0, 0]);
1380        assert!(ClockGraph::parse_adc3(&duplicate).is_err());
1381    }
1382}
1383
1384#[cfg(test)]
1385mod uac2_exact_multiplier_graph_tests {
1386    use super::*;
1387    fn descriptors(controls: u8) -> Vec<u8> {
1388        vec![
1389            8, 0x24, 2, 1, 0, 0, 0, 11, 7, 0x24, 0x0c, 11, 10, controls, 0, 8, 0x24, 0x0a, 10, 0,
1390            5, 0, 0,
1391        ]
1392    }
1393    #[test]
1394    fn only_exact_readonly_multiplier_controls_produce_plans() {
1395        for controls in 0..=15 {
1396            let graph = ClockGraph::parse(&descriptors(controls));
1397            assert_eq!(
1398                graph.enumerate_plans(1, |_| unreachable!()).is_ok(),
1399                controls == 5
1400            );
1401        }
1402        let graph = ClockGraph::parse(&descriptors(5));
1403        let plan = graph
1404            .enumerate_plans(1, |_| unreachable!())
1405            .unwrap()
1406            .remove(0);
1407        assert_eq!(plan.path, vec![11, 10]);
1408        assert!(matches!(
1409            graph.choice_for_plan(0, 1, &plan).path[1].kind,
1410            ClockHopKind::Multiplier
1411        ));
1412    }
1413    #[test]
1414    fn malformed_multiplier_branch_cannot_erase_into_fallback() {
1415        let graph = ClockGraph::parse(&[
1416            8, 0x24, 2, 1, 0, 0, 0, 11, 4, 0x24, 0x0c, 11, 8, 0x24, 0x0a, 10, 0, 5, 0, 0,
1417        ]);
1418        assert!(graph.select_clock(0, Some(1), |_| unreachable!()).is_err());
1419        // An unrelated missing terminal retains the historical source fallback.
1420        assert!(graph.select_clock(0, Some(2), |_| unreachable!()).is_ok());
1421        let truncated = ClockGraph::parse(&[
1422            8, 0x24, 2, 1, 0, 0, 0, 11, 8, 0x24, 0x0a, 10, 0, 5, 0, 0, 7, 0x24, 0x0c, 11,
1423        ]);
1424        assert!(truncated
1425            .select_clock(0, Some(1), |_| unreachable!())
1426            .is_err());
1427    }
1428}