use crate::descriptors::AudioControlParser;
use std::collections::HashMap;
use std::fmt;
const USB_DT_INTERFACE: u8 = 0x04;
const USB_DT_CS_INTERFACE: u8 = 0x24;
const USB_CLASS_AUDIO: u8 = 0x01;
const USB_SUBCLASS_AUDIOCONTROL: u8 = 0x01;
const UAC2_INPUT_TERMINAL: u8 = 0x02;
const UAC2_OUTPUT_TERMINAL: u8 = 0x03;
const UAC2_CLOCK_SOURCE: u8 = 0x0a;
const UAC2_CLOCK_SELECTOR: u8 = 0x0b;
const UAC2_CLOCK_MULTIPLIER: u8 = 0x0c;
const MAX_CLOCK_PATH: usize = 16;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClockChoice {
pub control_interface: u8,
pub source_id: u8,
pub path: Vec<ClockHop>,
pub resolution: ClockResolution,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ClockResolution {
Resolved,
FallbackFirstSource,
}
impl ClockResolution {
pub fn code(self) -> &'static str {
match self {
Self::Resolved => "resolved",
Self::FallbackFirstSource => "fallback_first_source",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ClockHop {
pub id: u8,
pub kind: ClockHopKind,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ClockHopKind {
Terminal,
Selector { selected_pin: u8, pin_count: u8 },
Multiplier,
Source,
}
impl ClockHopKind {
pub fn code(self) -> &'static str {
match self {
Self::Terminal => "terminal",
Self::Selector { .. } => "selector",
Self::Multiplier => "multiplier",
Self::Source => "source",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum ClockEntity {
Source,
Selector(Vec<u8>),
Multiplier(u8),
Malformed,
}
#[derive(Debug, Default)]
pub(crate) struct ClockGraph {
terminal_clock: HashMap<u8, u8>,
entities: HashMap<u8, ClockEntity>,
first_source: Option<u8>,
}
impl ClockGraph {
pub(crate) fn parse(descriptors: &[u8]) -> Self {
let mut graph = Self::default();
let mut index = 0usize;
while index + 2 < descriptors.len() {
let length = descriptors[index] as usize;
if length < 3 || index + length > descriptors.len() {
break;
}
let descriptor = &descriptors[index..index + length];
index += length;
if descriptor[1] != USB_DT_CS_INTERFACE {
continue;
}
match descriptor[2] {
UAC2_INPUT_TERMINAL if length >= 8 => {
graph.terminal_clock.insert(descriptor[3], descriptor[7]);
}
UAC2_OUTPUT_TERMINAL if length >= 9 => {
graph.terminal_clock.insert(descriptor[3], descriptor[8]);
}
UAC2_CLOCK_SOURCE if length >= 4 => {
graph.entities.insert(descriptor[3], ClockEntity::Source);
graph.first_source.get_or_insert(descriptor[3]);
}
UAC2_CLOCK_SELECTOR if length >= 4 => {
let entity = AudioControlParser
.parse_clock_selector(descriptor)
.map(|selector| ClockEntity::Selector(selector.ba_c_source_id))
.unwrap_or(ClockEntity::Malformed);
graph.entities.insert(descriptor[3], entity);
}
UAC2_CLOCK_MULTIPLIER if length >= 4 => {
let entity = AudioControlParser
.parse_clock_multiplier(descriptor)
.map(|multiplier| ClockEntity::Multiplier(multiplier.b_c_source_id))
.unwrap_or(ClockEntity::Malformed);
graph.entities.insert(descriptor[3], entity);
}
_ => {}
}
}
graph
}
pub(crate) fn has_clock_entities(&self) -> bool {
!self.entities.is_empty()
}
pub(crate) fn first_clock_source(&self) -> Option<u8> {
self.first_source
}
pub(crate) fn resolve_terminal_clock(
&self,
terminal_id: u8,
mut selected_pin: impl FnMut(u8) -> Result<u8, String>,
) -> Result<ResolvedClock, ClockResolveError> {
let first = *self
.terminal_clock
.get(&terminal_id)
.ok_or(ClockResolveError::TerminalNotFound(terminal_id))?;
if first == 0 {
return Err(ClockResolveError::TerminalHasNoClock(terminal_id));
}
let mut path = vec![first];
let mut hops = vec![ClockHop {
id: terminal_id,
kind: ClockHopKind::Terminal,
}];
loop {
let current = *path.last().expect("path starts non-empty");
match self.entities.get(¤t) {
None | Some(ClockEntity::Source) => {
let assumed_source = !self.entities.contains_key(¤t);
hops.push(ClockHop {
id: current,
kind: ClockHopKind::Source,
});
return Ok(ResolvedClock {
clock_id: current,
path,
hops,
assumed_source,
});
}
Some(ClockEntity::Malformed) => {
return Err(ClockResolveError::MalformedEntity(current));
}
Some(ClockEntity::Multiplier(input)) => {
if *input == 0 {
return Err(ClockResolveError::MalformedEntity(current));
}
hops.push(ClockHop {
id: current,
kind: ClockHopKind::Multiplier,
});
path.push(*input);
}
Some(ClockEntity::Selector(inputs)) => {
let pin_count = u8::try_from(inputs.len()).unwrap_or(u8::MAX);
let (next, pin) = match inputs.as_slice() {
[] => return Err(ClockResolveError::SelectorWithoutInputs(current)),
[only] => (*only, 1),
many => {
let pin = selected_pin(current).map_err(|reason| {
ClockResolveError::PinUnavailable {
selector: current,
reason,
}
})?;
if pin == 0 || usize::from(pin) > many.len() {
return Err(ClockResolveError::PinOutOfRange {
selector: current,
pin,
inputs: many.len(),
});
}
(many[usize::from(pin) - 1], pin)
}
};
if next == 0 {
return Err(ClockResolveError::MalformedEntity(current));
}
hops.push(ClockHop {
id: current,
kind: ClockHopKind::Selector {
selected_pin: pin,
pin_count,
},
});
path.push(next);
}
}
let last = *path.last().expect("path is non-empty");
if path[..path.len() - 1].contains(&last) {
return Err(ClockResolveError::Loop(last));
}
if path.len() > MAX_CLOCK_PATH {
return Err(ClockResolveError::TooDeep);
}
}
}
pub(crate) fn select_clock(
&self,
control_interface: u8,
terminal_link: Option<u8>,
selected_pin: impl FnMut(u8) -> Result<u8, String>,
) -> Result<ClockSelection, String> {
if !self.has_clock_entities() {
return Err("the AudioControl interface describes no clock entities".to_string());
}
let unresolved = match terminal_link {
None => "the stream has no bTerminalLink to trace its clock from".to_string(),
Some(terminal) => match self.resolve_terminal_clock(terminal, selected_pin) {
Ok(resolved) => {
return Ok(ClockSelection {
choice: ClockChoice {
control_interface,
source_id: resolved.clock_id,
path: resolved.hops,
resolution: ClockResolution::Resolved,
},
assumed_source: resolved.assumed_source,
unresolved: None,
});
}
Err(error) => error.to_string(),
},
};
match self.first_clock_source() {
Some(source_id) => Ok(ClockSelection {
choice: ClockChoice {
control_interface,
source_id,
path: vec![ClockHop {
id: source_id,
kind: ClockHopKind::Source,
}],
resolution: ClockResolution::FallbackFirstSource,
},
assumed_source: false,
unresolved: Some(unresolved),
}),
None => Err(unresolved),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ClockSelection {
pub choice: ClockChoice,
pub assumed_source: bool,
pub unresolved: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ResolvedClock {
pub clock_id: u8,
pub path: Vec<u8>,
pub hops: Vec<ClockHop>,
pub assumed_source: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum ClockResolveError {
TerminalNotFound(u8),
TerminalHasNoClock(u8),
MalformedEntity(u8),
SelectorWithoutInputs(u8),
PinUnavailable { selector: u8, reason: String },
PinOutOfRange { selector: u8, pin: u8, inputs: usize },
Loop(u8),
TooDeep,
}
impl fmt::Display for ClockResolveError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::TerminalNotFound(id) => {
write!(f, "terminal {id} is not in the AudioControl descriptors")
}
Self::TerminalHasNoClock(id) => write!(f, "terminal {id} names no clock (bCSourceID 0)"),
Self::MalformedEntity(id) => write!(f, "clock entity {id} has a malformed descriptor"),
Self::SelectorWithoutInputs(id) => write!(f, "clock selector {id} has no input pins"),
Self::PinUnavailable { selector, reason } => {
write!(f, "current pin of clock selector {selector} is unavailable: {reason}")
}
Self::PinOutOfRange {
selector,
pin,
inputs,
} => write!(
f,
"clock selector {selector} reports pin {pin}, outside its {inputs} inputs"
),
Self::Loop(id) => write!(f, "clock entity {id} feeds itself"),
Self::TooDeep => write!(f, "clock topology is deeper than {MAX_CLOCK_PATH} entities"),
}
}
}
pub(crate) fn audio_control_descriptors_from_config(raw: &[u8], ac_interface_number: u8) -> Vec<u8> {
let mut collected = Vec::new();
let mut inside_ac_interface = false;
let mut pos = 0usize;
while pos + 1 < raw.len() {
let length = raw[pos] as usize;
if length < 2 || pos + length > raw.len() {
break;
}
let descriptor = &raw[pos..pos + length];
pos += length;
if descriptor[1] == USB_DT_INTERFACE && length >= 9 {
inside_ac_interface = descriptor[2] == ac_interface_number
&& descriptor[5] == USB_CLASS_AUDIO
&& descriptor[6] == USB_SUBCLASS_AUDIOCONTROL;
} else if inside_ac_interface && descriptor[1] == USB_DT_CS_INTERFACE {
collected.extend_from_slice(descriptor);
}
}
collected
}