1use 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
29const MAX_CLOCK_PATH: usize = 16;
32
33#[derive(Debug, Clone, PartialEq, Eq)]
41pub struct ClockChoice {
42 pub control_interface: u8,
44 pub source_id: u8,
46 pub path: Vec<ClockHop>,
52 pub resolution: ClockResolution,
53}
54
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57#[non_exhaustive]
58pub enum ClockResolution {
59 Resolved,
63 FallbackFirstSource,
68}
69
70impl ClockResolution {
71 pub fn code(self) -> &'static str {
73 match self {
74 Self::Resolved => "resolved",
75 Self::FallbackFirstSource => "fallback_first_source",
76 }
77 }
78}
79
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub struct ClockHop {
83 pub id: u8,
85 pub kind: ClockHopKind,
86}
87
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
90#[non_exhaustive]
91pub enum ClockHopKind {
92 Terminal,
94 Selector { selected_pin: u8, pin_count: u8 },
98 Multiplier,
100 Source,
102}
103
104impl ClockHopKind {
105 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 Selector(Vec<u8>),
121 Multiplier(u8),
122 Malformed,
124}
125
126#[derive(Debug, Default)]
128pub(crate) struct ClockGraph {
129 terminal_clock: HashMap<u8, u8>,
131 entities: HashMap<u8, ClockEntity>,
132 first_source: Option<u8>,
133}
134
135impl ClockGraph {
136 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 UAC2_INPUT_TERMINAL if length >= 8 => {
154 graph.terminal_clock.insert(descriptor[3], descriptor[7]);
155 }
156 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 pub(crate) fn has_clock_entities(&self) -> bool {
188 !self.entities.is_empty()
189 }
190
191 pub(crate) fn first_clock_source(&self) -> Option<u8> {
194 self.first_source
195 }
196
197 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(¤t) {
228 None | Some(ClockEntity::Source) => {
229 let assumed_source = !self.entities.contains_key(¤t);
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 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 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 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#[derive(Debug, Clone, PartialEq, Eq)]
360pub(crate) struct ClockSelection {
361 pub choice: ClockChoice,
362 pub assumed_source: bool,
364 pub unresolved: Option<String>,
367}
368
369#[derive(Debug, Clone, PartialEq, Eq)]
370pub(crate) struct ResolvedClock {
371 pub clock_id: u8,
372 pub path: Vec<u8>,
374 pub hops: Vec<ClockHop>,
376 pub assumed_source: bool,
378}
379
380impl ResolvedClock {
381 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
442pub(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}