Skip to main content

usbdac_core/transport/
routing_hw.rs

1//! Session-bound standard UAC routing with dormant unpublished vendor controls.
2
3use super::*;
4use crate::error::OrControl;
5use crate::routing::{
6    self, Access, ControlKey, ControlRequest, InputCluster, InvalidRoute, MixerUnit, RouteChange,
7    RouteReport, RouteValue, RoutingError, RoutingInventory, RoutingIo, RoutingUnit, SelectorUnit,
8    TransactionError, MAX_ROUTE_CHANGES,
9};
10use std::collections::BTreeMap;
11
12// Release boundary: vendor routing was not shipped by the shared ALSA baseline.
13// This private compile-time fence has no feature, host-claim or runtime opt-in.
14const VENDOR_ROUTING_RELEASED: bool = false;
15const VENDOR_ROUTING_UNAVAILABLE: &str =
16    "proprietary vendor routing is not available in this release";
17
18fn require_vendor_routing_release() -> Result<(), RoutingSessionError> {
19    if VENDOR_ROUTING_RELEASED {
20        Ok(())
21    } else {
22        Err(RoutingSessionError::UnsupportedTopology(
23            VENDOR_ROUTING_UNAVAILABLE.into(),
24        ))
25    }
26}
27
28const MAX_TOPOLOGY_DEPTH: usize = 16;
29const MAX_RECORDED_ROUTES: usize = 1024;
30
31/// Optimistic concurrency check and desired value for one routing control.
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub struct RouteEdit {
34    pub key: ControlKey,
35    pub expected: RouteValue,
36    pub value: RouteValue,
37}
38
39/// Immutable discovery result, tied to an attachment and active configuration.
40/// Keeping a snapshot does not retain the host's USB claims after Dac::close.
41#[derive(Debug, Clone)]
42pub struct RoutingSnapshot {
43    device: UsbDevice,
44    configuration: u8,
45    descriptors: Vec<u8>,
46    inventory: RoutingInventory,
47    selectors: Vec<RouteChange>,
48    hc_clusters: BTreeMap<(u8, u16), RoutingCluster>,
49    diagnostics: Vec<RoutingDiagnostic>,
50    hand_back_report: Arc<Mutex<Option<RoutingHandBackReport>>>,
51}
52
53impl RoutingSnapshot {
54    /// None until final retirement completes; remains available after close.
55    pub fn hand_back_report(&self) -> Option<RoutingHandBackReport> {
56        self.hand_back_report.lock().clone()
57    }
58    pub fn diagnostics(&self) -> &[RoutingDiagnostic] {
59        &self.diagnostics
60    }
61    pub fn configuration(&self) -> u8 {
62        self.configuration
63    }
64    pub fn inventory(&self) -> &RoutingInventory {
65        &self.inventory
66    }
67    pub fn selector_values(&self) -> &[RouteChange] {
68        &self.selectors
69    }
70}
71
72/// A routing unit or function omitted because its addressing cannot be proven.
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub struct RoutingDiagnostic {
75    pub interface: u8,
76    pub entity_id: Option<u8>,
77    pub detail: String,
78}
79
80/// Outcome for one control when the session relinquishes routing ownership.
81#[derive(Debug, Clone, PartialEq, Eq)]
82pub enum RoutingHandBackOutcome {
83    Restored,
84    AlreadyOriginal,
85    ExternallyChanged,
86    Unreadable(String),
87    IdentityOrTopologyChanged(String),
88    RestoreUncertain(String),
89    DeadlineExpired,
90    Disabled,
91}
92
93#[derive(Debug, Clone, PartialEq, Eq)]
94pub struct RoutingHandBackReport {
95    pub controls: Vec<(ControlKey, RoutingHandBackOutcome)>,
96}
97
98/// Typed failures preserve failed-change and rollback information.
99#[derive(Debug)]
100pub enum RoutingSessionError {
101    Session(Error),
102    Invalid(InvalidRoute),
103    UnsupportedTopology(String),
104    Drift(String),
105    Control(RoutingError<String>),
106    Transaction(TransactionError<String>),
107    /// Scoped ADC3 power hand-back failed. Preserve an operation failure in its
108    /// original typed form; `None` means the routing operation itself succeeded.
109    PowerRestore {
110        operation: Option<Box<RoutingSessionError>>,
111        detail: String,
112    },
113    Scarlett(crate::scarlett::ReadError<String>),
114    ScarlettMix(crate::scarlett::MixWriteError<String>),
115    ScarlettMux(crate::scarlett::MuxWriteError<String>),
116    Fcp(crate::scarlett::FcpWriteError<String>),
117    Gen1Read(crate::scarlett::Gen1Failure<String>),
118    Gen1(crate::scarlett::Gen1WriteError<String>),
119}
120
121impl std::fmt::Display for RoutingSessionError {
122    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
123        write!(f, "{self:?}")
124    }
125}
126impl std::error::Error for RoutingSessionError {}
127
128fn djm_usb_error(error: rusb::Error) -> RoutingSessionError {
129    RoutingSessionError::Session(match error {
130        rusb::Error::NoDevice => Error::DeviceLost,
131        _ => Error::Control(error.to_string()),
132    })
133}
134
135/// Called only while the session gate, controls mutex and idle owner are held.
136/// Descriptor proof reuses streaming admission; a USB ID alone authorizes nothing.
137fn djm_route_identity(
138    device: &UsbDevice,
139    idle: &IdleLock,
140    info: &crate::DeviceInfo,
141) -> Result<(crate::pioneer::DjmModel, u8), RoutingSessionError> {
142    let usb = idle.handle.device();
143    let identity = usb.device_descriptor().map_err(djm_usb_error)?;
144    if identity.vendor_id() != device.vendor_id
145        || identity.product_id() != device.product_id
146        || identity.vendor_id() != info.vendor_id
147        || identity.product_id() != info.product_id
148    {
149        return Err(RoutingSessionError::Drift(
150            "DJM host and live USB identities differ".into(),
151        ));
152    }
153    let model = crate::pioneer::DjmModel::from_usb_id(identity.vendor_id(), identity.product_id())
154        .ok_or_else(|| {
155            RoutingSessionError::UnsupportedTopology("no supported DJM routing model".into())
156        })?;
157    let configuration = idle.handle.active_configuration().map_err(djm_usb_error)?;
158    let config = usb.active_config_descriptor().map_err(djm_usb_error)?;
159    if config.number() != configuration
160        || info.configuration_id.is_some_and(|id| id != configuration)
161    {
162        return Err(RoutingSessionError::Drift(
163            "DJM selected and active configurations differ".into(),
164        ));
165    }
166    let profile = vendor_pcm::discover(&idle.handle, &config, resolve_device_speed(&usb))
167        .or_control()
168        .map_err(RoutingSessionError::Session)?
169        .ok_or_else(|| {
170            RoutingSessionError::UnsupportedTopology(
171                "DJM routing requires a proven vendor PCM configuration".into(),
172            )
173        })?;
174    if profile.configuration_number != configuration
175        || !profile.claims_match(&device.claimed_interfaces)
176        || !profile.claims_match(&idle.claimed_interfaces)
177    {
178        return Err(RoutingSessionError::Session(Error::Claim(
179            "DJM routing requires exactly the proven vendor PCM interface claims".into(),
180        )));
181    }
182    if idle.handle.active_configuration().map_err(djm_usb_error)? != configuration {
183        return Err(RoutingSessionError::Drift(
184            "DJM active configuration changed during proof".into(),
185        ));
186    }
187    Ok((model, configuration))
188}
189
190pub(crate) fn djm_discover(
191    shared: &crate::dac::DacShared,
192) -> Result<crate::pioneer::DjmRoutingProfile, RoutingSessionError> {
193    require_vendor_routing_release()?;
194    let _gate = USB_SESSION_GATE.lock();
195    shared.ensure_open().map_err(RoutingSessionError::Session)?;
196    let _controls = HARDWARE_VOLUME_MUTEX.lock();
197    let device = idle_device()?;
198    let idle = IDLE_LOCK.lock();
199    let idle = idle
200        .as_ref()
201        .filter(|idle| idle.device_fd == device.fd)
202        .ok_or_else(|| {
203            RoutingSessionError::Session(Error::InvalidState(
204                "DJM routing requires the idle USB owner".into(),
205            ))
206        })?;
207    let (model, configuration) = djm_route_identity(&device, idle, &shared.info)?;
208    Ok(crate::pioneer::DjmRoutingProfile {
209        model,
210        configuration,
211        controls: model.controls(),
212    })
213}
214
215pub(crate) fn djm_apply(
216    shared: &crate::dac::DacShared,
217    model: crate::pioneer::DjmModel,
218    configuration: u8,
219    key: crate::pioneer::DjmControlKey,
220    option: u8,
221) -> Result<(), RoutingSessionError> {
222    require_vendor_routing_release()?;
223    let _gate = USB_SESSION_GATE.lock();
224    shared.ensure_open().map_err(RoutingSessionError::Session)?;
225    let _controls = HARDWARE_VOLUME_MUTEX.lock();
226    let device = idle_device()?;
227    let idle = IDLE_LOCK.lock();
228    let idle = idle
229        .as_ref()
230        .filter(|idle| idle.device_fd == device.fd)
231        .ok_or_else(|| {
232            RoutingSessionError::Session(Error::InvalidState(
233                "DJM routing requires the idle USB owner".into(),
234            ))
235        })?;
236    let actual = djm_route_identity(&device, idle, &shared.info)?;
237    if actual != (model, configuration) {
238        return Err(RoutingSessionError::Drift(
239            "DJM model or configuration changed; rediscover routing".into(),
240        ));
241    }
242    let (value, index) = model.request(key, option).ok_or_else(|| {
243        RoutingSessionError::Session(Error::InvalidArgument(
244            "unsupported DJM control or option ID".into(),
245        ))
246    })?;
247    // Every admitted DJM has exactly interface 0; derive the interface set from
248    // fresh streaming proof rather than adding a vendor/Android claim.
249    for interface in idle.claimed_interfaces.iter().copied() {
250        let mut alternate = [0u8];
251        let read = idle
252            .handle
253            .read_control(
254                0x81,
255                0x0a,
256                0,
257                u16::from(interface),
258                &mut alternate,
259                Duration::from_millis(500),
260            )
261            .map_err(djm_usb_error)?;
262        if read != 1 || alternate[0] != 0 {
263            return Err(RoutingSessionError::Session(Error::InvalidState(
264                "DJM routing requires verified idle alternate zero".into(),
265            )));
266        }
267    }
268    if idle.handle.active_configuration().map_err(djm_usb_error)? != configuration {
269        return Err(RoutingSessionError::Drift(
270            "DJM configuration changed before option write".into(),
271        ));
272    }
273    shared.ensure_open().map_err(RoutingSessionError::Session)?;
274    let written = idle
275        .handle
276        .write_control(0x40, 0x03, value, index, &[], Duration::from_millis(500))
277        .map_err(djm_usb_error)?;
278    if written != 0 {
279        return Err(RoutingSessionError::Session(Error::Control(
280            "DJM option request returned an unexpected payload length".into(),
281        )));
282    }
283    Ok(())
284}
285
286/// Return one unambiguous, exact-model optional vendor claim. This is admission
287/// of an already opted-in host claim, never an instruction to acquire a claim.
288pub(super) fn scarlett_claim_interface(
289    config: &ConfigDescriptor,
290    vendor: u16,
291    product: u16,
292) -> Option<u8> {
293    if !VENDOR_ROUTING_RELEASED {
294        return None;
295    }
296    scarlett_endpoint(config, vendor, product).map(|(interface, _)| interface)
297}
298
299/// Descriptor-only host preclaim proof. Never claims an interface or initializes Scarlett.
300pub(crate) fn scarlett_preflight(
301    fd: RawFd,
302    info: &crate::DeviceInfo,
303) -> Result<Option<crate::scarlett::ReadCapability>, Error> {
304    if !VENDOR_ROUTING_RELEASED {
305        return Ok(None);
306    }
307    if !cfg!(any(target_os = "linux", target_os = "android")) {
308        return Err(Error::PlatformUnsupported);
309    }
310    let device = UsbDevice::try_new(
311        fd,
312        info.vendor_id,
313        info.product_id,
314        info.product_name.clone(),
315        info.device_name.clone(),
316        Vec::new(),
317    )
318    .map_err(Error::Claim)?;
319    let wrapped = wrap_android_usb_handle(&device).map_err(Error::Claim)?;
320    let usb = wrapped.handle.device();
321    let identity = usb
322        .device_descriptor()
323        .map_err(|e| Error::Control(e.to_string()))?;
324    if identity.vendor_id() != info.vendor_id || identity.product_id() != info.product_id {
325        return Err(Error::Claim(
326            "host and USB device identities differ during Scarlett preflight".into(),
327        ));
328    }
329    let config = usb
330        .active_config_descriptor()
331        .map_err(|e| Error::Control(e.to_string()))?;
332    if info.configuration_id != Some(config.number()) {
333        return Err(Error::Claim(
334            "Scarlett preflight requires the selected active configuration".into(),
335        ));
336    }
337    let Some(candidate) =
338        crate::scarlett::CandidateModel::recognize(identity.vendor_id(), identity.product_id())
339    else {
340        return Ok(None);
341    };
342    Ok(
343        scarlett_endpoint(&config, identity.vendor_id(), identity.product_id()).map(
344            |(interface, notification_endpoint)| crate::scarlett::ReadCapability {
345                candidate,
346                configuration: config.number(),
347                interface,
348                notification_endpoint,
349                interface_claimed: false,
350            },
351        ),
352    )
353}
354
355fn scarlett_endpoint(config: &ConfigDescriptor, vendor: u16, product: u16) -> Option<(u8, u8)> {
356    crate::scarlett::CandidateModel::recognize(vendor, product)?;
357    let mut found = None;
358    for interface in config.interfaces() {
359        for descriptor in interface.descriptors() {
360            if descriptor.setting_number() != 0 || descriptor.class_code() != 0xff {
361                continue;
362            }
363            // Reject ambiguity, including a second vendor interface with a
364            // different shape, instead of guessing Focusrite Control ownership.
365            if found.is_some() || descriptor.num_endpoints() != 1 {
366                return None;
367            }
368            let endpoint = descriptor.endpoint_descriptors().next()?;
369            if endpoint.transfer_type() != TransferType::Interrupt
370                || endpoint.direction() != Direction::In
371                || endpoint.max_packet_size() != 8
372                || endpoint.interval() == 0
373                || endpoint.address() & 0x70 != 0
374                || endpoint.address() & 0x0f == 0
375            {
376                return None;
377            }
378            found = Some((descriptor.interface_number(), endpoint.address()));
379        }
380    }
381    found
382}
383
384fn scarlett_capability(
385    device: &UsbDevice,
386    configuration: u8,
387) -> Result<Option<crate::scarlett::ReadCapability>, RoutingSessionError> {
388    let idle = IDLE_LOCK.lock();
389    let idle = idle
390        .as_ref()
391        .filter(|idle| idle.device_fd == device.fd)
392        .ok_or_else(|| {
393            RoutingSessionError::Session(Error::InvalidState(
394                "Scarlett discovery requires the idle USB owner".into(),
395            ))
396        })?;
397    let usb_device = idle.handle.device();
398    let identity = usb_device
399        .device_descriptor()
400        .map_err(|e| RoutingSessionError::Session(Error::Control(e.to_string())))?;
401    if identity.vendor_id() != device.vendor_id || identity.product_id() != device.product_id {
402        return Err(RoutingSessionError::Drift(
403            "host and USB device identities differ".into(),
404        ));
405    }
406    let Some(candidate) =
407        crate::scarlett::CandidateModel::recognize(identity.vendor_id(), identity.product_id())
408    else {
409        return Ok(None);
410    };
411    let config = usb_device
412        .active_config_descriptor()
413        .map_err(|e| RoutingSessionError::Session(Error::Control(e.to_string())))?;
414    if config.number() != configuration {
415        return Err(RoutingSessionError::Drift(
416            "configuration changed during Scarlett discovery".into(),
417        ));
418    }
419    let Some((interface, notification_endpoint)) =
420        scarlett_endpoint(&config, identity.vendor_id(), identity.product_id())
421    else {
422        return Ok(None);
423    };
424    Ok(Some(crate::scarlett::ReadCapability {
425        candidate,
426        configuration,
427        interface,
428        notification_endpoint,
429        interface_claimed: device.claimed_interfaces.contains(&interface),
430    }))
431}
432
433/// Descriptor-only read capability; does not initialize the vendor protocol.
434pub(crate) fn scarlett_discover(
435) -> Result<Option<crate::scarlett::ReadCapability>, RoutingSessionError> {
436    if !VENDOR_ROUTING_RELEASED {
437        return Ok(None);
438    }
439    let _gate = USB_SESSION_GATE.lock();
440    let _controls = HARDWARE_VOLUME_MUTEX.lock();
441    let device = idle_device()?;
442    let (configuration, _) = active_descriptors(&device)?;
443    scarlett_capability(&device, configuration)
444}
445
446struct UsbScarlettIo<'a> {
447    device: &'a UsbDevice,
448    handle: &'a DeviceHandle<Context>,
449    interface: u8,
450    endpoint: u8,
451    max_payload: usize,
452}
453
454impl crate::scarlett::ReadIo for UsbScarlettIo<'_> {
455    type Error = String;
456    fn initial_read(&mut self, bytes: &mut [u8; 24]) -> Result<usize, String> {
457        if !VENDOR_ROUTING_RELEASED {
458            return Err(VENDOR_ROUTING_UNAVAILABLE.into());
459        }
460        self.device
461            .feature_unit_control(0xa1, 0, 0, u16::from(self.interface), bytes)
462            .map_err(|e| e.to_string())
463    }
464    fn prepare_notifications(&mut self) -> Result<(), String> {
465        if !VENDOR_ROUTING_RELEASED {
466            return Err(VENDOR_ROUTING_UNAVAILABLE.into());
467        }
468        let deadline = Instant::now() + Duration::from_millis(20);
469        // Drain outstanding ACKs before either initialization request. The
470        // synchronous interrupt helper owns/retires its transfer before return.
471        for _ in 0..16 {
472            let remaining = deadline.saturating_duration_since(Instant::now());
473            if remaining.is_zero() {
474                return Ok(());
475            }
476            let mut data = [0; 8];
477            match self.handle.read_interrupt(
478                self.endpoint,
479                &mut data,
480                remaining.max(Duration::from_millis(1)),
481            ) {
482                Ok(8) => {}
483                Ok(_) => return Err("short Scarlett initialization notification".into()),
484                Err(rusb::Error::Timeout) => return Ok(()),
485                Err(e) => return Err(e.to_string()),
486            }
487        }
488        Err("Scarlett notification drain exceeded its bounded packet budget".into())
489    }
490    fn send_request(&mut self, bytes: &[u8]) -> Result<usize, String> {
491        if !VENDOR_ROUTING_RELEASED {
492            return Err(VENDOR_ROUTING_UNAVAILABLE.into());
493        }
494        if bytes.len() < 16 || bytes.len() > 16 + self.max_payload {
495            return Err("unbounded Scarlett request refused".into());
496        }
497        let mut request = bytes.to_vec();
498        self.device
499            .feature_unit_control(0x21, 2, 0, u16::from(self.interface), &mut request)
500            .map_err(|e| e.to_string())
501    }
502    fn next_notification(
503        &mut self,
504        bytes: &mut [u8; 8],
505        timeout: Duration,
506    ) -> Result<usize, String> {
507        if !VENDOR_ROUTING_RELEASED {
508            return Err(VENDOR_ROUTING_UNAVAILABLE.into());
509        }
510        self.handle
511            .read_interrupt(self.endpoint, bytes, timeout.max(Duration::from_millis(1)))
512            .map_err(|e| e.to_string())
513    }
514    fn receive_response(&mut self, bytes: &mut [u8]) -> Result<usize, String> {
515        if !VENDOR_ROUTING_RELEASED {
516            return Err(VENDOR_ROUTING_UNAVAILABLE.into());
517        }
518        if bytes.len() < 16 || bytes.len() > 16 + self.max_payload {
519            return Err("unbounded Scarlett response refused".into());
520        }
521        self.device
522            .feature_unit_control(0xa1, 3, 0, u16::from(self.interface), bytes)
523            .map_err(|e| e.to_string())
524    }
525}
526
527/// Explicit vendor read: initialize only the already claimed, exact candidate,
528/// then admit firmware and read mux-zero/mixer state. Never SET_MUX/SET_MIX.
529pub(crate) fn scarlett_read() -> Result<crate::scarlett::RoutingReadback, RoutingSessionError> {
530    require_vendor_routing_release()?;
531    let _gate = USB_SESSION_GATE.lock();
532    let _controls = HARDWARE_VOLUME_MUTEX.lock();
533    let device = idle_device()?;
534    let (configuration, descriptors) = active_descriptors(&device)?;
535    let readback = with_scarlett(&device, configuration, |session| {
536        session.read_all().map_err(RoutingSessionError::Scarlett)
537    })?;
538    let (after, raw) = active_descriptors(&device)?;
539    if configuration != after || descriptors != raw {
540        return Err(RoutingSessionError::Drift(
541            "configuration changed during Scarlett routing read".into(),
542        ));
543    }
544    Ok(readback)
545}
546
547pub(super) struct RecordedScarlett {
548    device: UsbDevice,
549    configuration: u8,
550    descriptors: Vec<u8>,
551    rows: BTreeMap<u8, (crate::scarlett::MixReadback, crate::scarlett::MixReadback)>,
552    mux: Option<(crate::scarlett::MuxSnapshot, crate::scarlett::MuxSnapshot)>,
553}
554static ORIGINAL_SCARLETT: context::ScopedMutex<Option<RecordedScarlett>> =
555    context::ScopedMutex::new(|context| context.scarlett.clone());
556
557/// The caller owns session/volume serialization. Recheck exact claim and USB
558/// identity for every operation, including configured hand-back.
559fn with_scarlett<T>(
560    device: &UsbDevice,
561    configuration: u8,
562    operation: impl FnOnce(
563        &mut crate::scarlett::ReadSession<UsbScarlettIo<'_>>,
564    ) -> Result<T, RoutingSessionError>,
565) -> Result<T, RoutingSessionError> {
566    with_scarlett_io(device, configuration, false, |io, candidate| {
567        let mut session = crate::scarlett::ReadSession::initialize(io, candidate)
568            .map_err(RoutingSessionError::Scarlett)?;
569        operation(&mut session)
570    })
571}
572
573/// Share exact identity/claim admission between legacy controls and FCP reads.
574fn with_scarlett_io<T>(
575    device: &UsbDevice,
576    configuration: u8,
577    fcp: bool,
578    operation: impl FnOnce(
579        UsbScarlettIo<'_>,
580        crate::scarlett::CandidateModel,
581    ) -> Result<T, RoutingSessionError>,
582) -> Result<T, RoutingSessionError> {
583    let capability = scarlett_capability(device, configuration)?.ok_or_else(|| {
584        RoutingSessionError::UnsupportedTopology("no exact Scarlett candidate".into())
585    })?;
586    if capability.candidate.is_fcp() != fcp {
587        let message = if fcp {
588            "firmware-described routing requires a modern FCP interface"
589        } else {
590            "modern FCP routing is available through fcp_routing_read"
591        };
592        return Err(RoutingSessionError::UnsupportedTopology(message.into()));
593    }
594    if !capability.interface_claimed {
595        return Err(RoutingSessionError::Session(Error::Claim(
596            "Focusrite routing requires an explicit vendor-interface claim".into(),
597        )));
598    }
599    let idle = IDLE_LOCK.lock();
600    let idle = idle
601        .as_ref()
602        .filter(|idle| idle.device_fd == device.fd)
603        .ok_or_else(|| {
604            RoutingSessionError::Session(Error::InvalidState(
605                "Scarlett mixer lost idle USB owner".into(),
606            ))
607        })?;
608    let io = UsbScarlettIo {
609        device,
610        handle: &idle.handle,
611        interface: capability.interface,
612        endpoint: capability.notification_endpoint,
613        max_payload: if fcp {
614            crate::scarlett::FCP_MAX_PAYLOAD
615        } else {
616            crate::scarlett::MAX_PAYLOAD
617        },
618    };
619    operation(io, capability.candidate)
620}
621
622/// Read only firmware-defined FCP topology on a proven, explicitly claimed idle owner.
623pub(crate) fn fcp_read() -> Result<crate::scarlett::FcpReadback, RoutingSessionError> {
624    require_vendor_routing_release()?;
625    let _gate = USB_SESSION_GATE.lock();
626    let _controls = HARDWARE_VOLUME_MUTEX.lock();
627    let device = idle_device()?;
628    let (configuration, descriptors) = active_descriptors(&device)?;
629    let readback = with_scarlett_io(&device, configuration, true, |io, candidate| {
630        crate::scarlett::read_fcp(io, candidate).map_err(RoutingSessionError::Scarlett)
631    })?;
632    let (after, raw) = active_descriptors(&device)?;
633    if configuration != after || descriptors != raw {
634        return Err(RoutingSessionError::Drift(
635            "configuration changed during FCP routing read".into(),
636        ));
637    }
638    Ok(readback)
639}
640
641// Gen1 uses standard two-byte class CUR controls on the already claimed AC
642// interface. Never infer a vendor-interface claim from the product identity.
643fn gen1_interface(raw: &[u8], claims: &[u8]) -> Result<u8, RoutingSessionError> {
644    let fail = || {
645        RoutingSessionError::UnsupportedTopology(
646            "Gen1 requires one claimed UAC2 AC alt0 with an owning streaming function".into(),
647        )
648    };
649    // Validate configuration framing before inspecting ownership descriptors.
650    routing_interfaces(raw, claims)?;
651    let framed = framed(raw)?;
652    let controls: Vec<_> = framed
653        .iter()
654        .filter(|b| b[1] == 4 && b.len() == 9 && b[3] == 0 && b[5] == 1 && b[6] == 1)
655        .collect();
656    if controls.len() != 1 {
657        return Err(fail());
658    }
659    let ac = controls[0][2];
660    if controls[0][7] != 0x20 || !claims.contains(&ac) {
661        return Err(fail());
662    }
663    if framed.iter().any(|b| b[1] == 11 && b.len() != 8) {
664        return Err(fail());
665    }
666    let associations: Vec<_> = framed
667        .iter()
668        .filter(|b| {
669            b[1] == 11
670                && b.len() == 8
671                && ac >= b[2]
672                && u16::from(ac) < u16::from(b[2]) + u16::from(b[3])
673        })
674        .copied()
675        .collect();
676    if associations.len() > 1 {
677        return Err(fail());
678    }
679    let iad = associations.first().copied();
680    if iad.is_some_and(|b| b[4] != 1 || b[6] != 0x20) {
681        return Err(fail());
682    }
683    let interfaces = routing_interfaces(raw, claims)?;
684    let entities = &interfaces.get(&ac).ok_or_else(fail)?.1;
685    let headers: Vec<_> = entities
686        .iter()
687        .filter(|b| b.len() >= 3 && b[2] == 1)
688        .collect();
689    if headers.len() != 1
690        || headers[0].len() != 9
691        || headers[0][3..5] != [0, 2]
692        || usize::from(u16::from_le_bytes([headers[0][6], headers[0][7]]))
693            != entities.iter().map(|b| b.len()).sum::<usize>()
694    {
695        return Err(fail());
696    }
697    let mut entity_ids = BTreeMap::new();
698    for b in entities.iter().filter(|b| b.len() >= 3 && b[2] != 1) {
699        if b.len() < 4
700            || b[3] == 0
701            || entity_ids.insert(b[3], ()).is_some()
702            || (b[2] == 2 && b.len() != 17)
703            || (b[2] == 3 && b.len() != 12)
704        {
705            return Err(fail());
706        }
707    }
708    let terminals: Vec<_> = entities
709        .iter()
710        .filter(|b| b.len() >= 4 && matches!(b[2], 2 | 3) && b[4..6] == [1, 1])
711        .map(|b| b[3])
712        .collect();
713    if terminals.is_empty() {
714        return Err(fail());
715    }
716    let mut stream = None;
717    let mut linked_terminal = None;
718    let mut linked = false;
719    for b in &framed {
720        if b[1] == 4 {
721            linked_terminal = None;
722            stream = if b.len() == 9
723                && b[3] != 0
724                && b[4] != 0
725                && b[5] == 1
726                && b[6] == 2
727                && b[7] == 0x20
728                && iad.map_or(true, |iad| {
729                    b[2] >= iad[2] && u16::from(b[2]) < u16::from(iad[2]) + u16::from(iad[3])
730                }) {
731                Some(b[2])
732            } else {
733                None
734            };
735        } else if b[1] == 0x24
736            && b.len() == 16
737            && b[2] == 1
738            && stream.is_some()
739            && terminals.contains(&b[3])
740        {
741            let number = stream.unwrap();
742            let owners: Vec<_> = framed
743                .iter()
744                .filter(|d| {
745                    d[1] == 11
746                        && d.len() == 8
747                        && number >= d[2]
748                        && u16::from(number) < u16::from(d[2]) + u16::from(d[3])
749                })
750                .copied()
751                .collect();
752            if owners.len() > 1 || owners.first().is_some_and(|owner| iad != Some(*owner)) {
753                return Err(fail());
754            }
755            linked_terminal = entities
756                .iter()
757                .find(|d| d.len() >= 6 && d[3] == b[3] && matches!(d[2], 2 | 3))
758                .map(|d| d[2]);
759        } else if b[1] == 5
760            && matches!(b.len(), 7 | 9)
761            && b[2] & 0x0f != 0
762            && b[3] & 3 == 1
763            && b[3] & 0x30 == 0
764            && linked_terminal.is_some_and(|subtype| (b[2] & 0x80 != 0) == (subtype == 3))
765        {
766            linked = true;
767        }
768    }
769    if !linked {
770        return Err(fail());
771    }
772    Ok(ac)
773}
774
775struct UsbGen1Io<'a> {
776    device: &'a UsbDevice,
777    interface: u8,
778}
779impl crate::scarlett::Gen1Io for UsbGen1Io<'_> {
780    type Error = String;
781    fn read(&mut self, entity: u8, value: u16) -> Result<i16, String> {
782        if !VENDOR_ROUTING_RELEASED {
783            return Err(VENDOR_ROUTING_UNAVAILABLE.into());
784        }
785        let mut data = [0u8; 2];
786        let n = self
787            .device
788            .feature_unit_control(
789                0xa1,
790                1,
791                value,
792                (u16::from(entity) << 8) | u16::from(self.interface),
793                &mut data,
794            )
795            .map_err(|e| e.to_string())?;
796        if n != 2 {
797            return Err("short Gen1 CUR read".into());
798        }
799        Ok(i16::from_le_bytes(data))
800    }
801    fn write(&mut self, entity: u8, value: u16, data: i16) -> Result<(), String> {
802        if !VENDOR_ROUTING_RELEASED {
803            return Err(VENDOR_ROUTING_UNAVAILABLE.into());
804        }
805        let mut bytes = data.to_le_bytes();
806        let n = self
807            .device
808            .feature_unit_control(
809                0x21,
810                1,
811                value,
812                (u16::from(entity) << 8) | u16::from(self.interface),
813                &mut bytes,
814            )
815            .map_err(|e| e.to_string())?;
816        if n != 2 {
817            return Err("short Gen1 CUR write".into());
818        }
819        Ok(())
820    }
821}
822
823#[derive(Clone)]
824struct Gen1Binding {
825    device: UsbDevice,
826    configuration: u8,
827    descriptors: Vec<u8>,
828}
829pub(super) struct RecordedGen1 {
830    binding: Gen1Binding,
831    original: crate::scarlett::Gen1Readback,
832    last: crate::scarlett::Gen1Readback,
833    uncertain: bool,
834}
835static ORIGINAL_GEN1: context::ScopedMutex<Option<RecordedGen1>> =
836    context::ScopedMutex::new(|context| context.gen1.clone());
837
838fn gen1_target(
839    device: &UsbDevice,
840    descriptors: &[u8],
841) -> Result<(crate::scarlett::Gen1Model, u8), RoutingSessionError> {
842    let idle = IDLE_LOCK.lock();
843    let idle = idle
844        .as_ref()
845        .filter(|idle| idle.device_fd == device.fd)
846        .ok_or_else(|| {
847            RoutingSessionError::Session(Error::InvalidState(
848                "Gen1 requires the idle USB owner".into(),
849            ))
850        })?;
851    let identity = idle
852        .handle
853        .device()
854        .device_descriptor()
855        .map_err(|e| RoutingSessionError::Session(Error::Control(e.to_string())))?;
856    if identity.vendor_id() != device.vendor_id || identity.product_id() != device.product_id {
857        return Err(RoutingSessionError::Drift(
858            "Gen1 host and actual USB identities differ".into(),
859        ));
860    }
861    let model = crate::scarlett::Gen1Model::recognize(identity.vendor_id(), identity.product_id())
862        .ok_or_else(|| RoutingSessionError::UnsupportedTopology("no exact Gen1 model".into()))?;
863    Ok((
864        model,
865        gen1_interface(descriptors, &device.claimed_interfaces)?,
866    ))
867}
868fn check_gen1_binding(
869    binding: &Gen1Binding,
870    device: &UsbDevice,
871    configuration: u8,
872    descriptors: &[u8],
873) -> Result<(), RoutingSessionError> {
874    if !binding.device.same_owner(device)
875        || binding.configuration != configuration
876        || binding.descriptors != descriptors
877    {
878        return Err(RoutingSessionError::Drift(
879            "Gen1 attachment or configuration changed".into(),
880        ));
881    }
882    gen1_interface(descriptors, &device.claimed_interfaces)?;
883    Ok(())
884}
885fn check_gen1_after(
886    device: &UsbDevice,
887    configuration: u8,
888    descriptors: &[u8],
889) -> Result<(), RoutingSessionError> {
890    let (after, raw) = active_descriptors(device)?;
891    if after != configuration || raw != descriptors {
892        return Err(RoutingSessionError::Drift(
893            "Gen1 configuration changed during control access".into(),
894        ));
895    }
896    gen1_target(device, &raw)?;
897    Ok(())
898}
899
900pub(crate) fn scarlett_gen1_read() -> Result<crate::scarlett::Gen1Readback, RoutingSessionError> {
901    require_vendor_routing_release()?;
902    let _gate = USB_SESSION_GATE.lock();
903    let _controls = HARDWARE_VOLUME_MUTEX.lock();
904    let device = idle_device()?;
905    let (configuration, descriptors) = active_descriptors(&device)?;
906    let (model, interface) = gen1_target(&device, &descriptors)?;
907    let readback = crate::scarlett::read_gen1(
908        &mut UsbGen1Io {
909            device: &device,
910            interface,
911        },
912        model,
913    )
914    .map_err(RoutingSessionError::Gen1Read);
915    let after = check_gen1_after(&device, configuration, &descriptors);
916    match readback {
917        Ok(readback) => {
918            after?;
919            Ok(readback)
920        }
921        Err(error) => {
922            if let Err(drift) = after {
923                log_warn!("[USB] Gen1 read also lost binding: {drift}");
924            }
925            Err(error)
926        }
927    }
928}
929
930// Keep independently owned controls even when a later read contains external
931// changes to them. Such external values must never become a restore target.
932fn merge_gen1_provenance(
933    original: &crate::scarlett::Gen1Readback,
934    last: &crate::scarlett::Gen1Readback,
935    before: &crate::scarlett::Gen1Readback,
936    verified: &crate::scarlett::Gen1Readback,
937) -> (crate::scarlett::Gen1Readback, crate::scarlett::Gen1Readback) {
938    let mut saved = before.clone();
939    let mut recent = verified.clone();
940    for (index, control) in before.controls.iter().enumerate() {
941        if let (Some(old), Some(previous)) = (
942            original.controls.iter().find(|c| c.key == control.key),
943            last.controls.iter().find(|c| c.key == control.key),
944        ) {
945            if old != previous {
946                saved.controls[index] = *old;
947                if control == &verified.controls[index] {
948                    recent.controls[index] = *previous;
949                }
950            }
951        }
952    }
953    (saved, recent)
954}
955
956pub(crate) fn scarlett_gen1_apply(
957    expected: &crate::scarlett::Gen1Readback,
958    edits: &[crate::scarlett::Gen1Edit],
959) -> Result<crate::scarlett::Gen1Report, RoutingSessionError> {
960    require_vendor_routing_release()?;
961    let _gate = USB_SESSION_GATE.lock();
962    let _controls = HARDWARE_VOLUME_MUTEX.lock();
963    let device = idle_device()?;
964    let (configuration, descriptors) = active_descriptors(&device)?;
965    let (model, interface) = gen1_target(&device, &descriptors)?;
966    let binding = Gen1Binding {
967        device: device.clone(),
968        configuration,
969        descriptors: descriptors.clone(),
970    };
971    if expected.model != model {
972        return Err(RoutingSessionError::Drift(
973            "Gen1 readback belongs to another model".into(),
974        ));
975    }
976    let mut records = ORIGINAL_GEN1.lock();
977    if let Some(record) = records.as_ref() {
978        check_gen1_binding(&record.binding, &device, configuration, &descriptors)?;
979        if record.uncertain || !crate::scarlett::same_gen1_layout(&record.last, expected) {
980            return Err(RoutingSessionError::Drift(
981                "Gen1 layout or rollback state changed".into(),
982            ));
983        }
984        for control in &expected.controls {
985            if edits.iter().any(|e| e.key == control.key) {
986                if let (Some(old), Some(last)) = (
987                    record
988                        .original
989                        .controls
990                        .iter()
991                        .find(|c| c.key == control.key),
992                    record.last.controls.iter().find(|c| c.key == control.key),
993                ) {
994                    if old != last && control != last {
995                        return Err(RoutingSessionError::Drift(
996                            "Gen1 control differs from last verified write".into(),
997                        ));
998                    }
999                }
1000            }
1001        }
1002    }
1003    let result = crate::scarlett::apply_gen1(
1004        &mut UsbGen1Io {
1005            device: &device,
1006            interface,
1007        },
1008        model,
1009        expected,
1010        edits,
1011    );
1012    // Invalidate on attempted transactions, including errors and uncertain rollback.
1013    invalidate_route_caches();
1014    let report = match result {
1015        Ok(report) => report,
1016        Err(failure) => {
1017            if !failure.rollback.is_empty() {
1018                let record = records.get_or_insert_with(|| RecordedGen1 {
1019                    binding: binding.clone(),
1020                    original: expected.clone(),
1021                    last: expected.clone(),
1022                    uncertain: true,
1023                });
1024                record.uncertain = true;
1025            }
1026            // Recheck actual USB identity/config even on transaction errors.
1027            if let Err(drift) = check_gen1_after(&device, configuration, &descriptors) {
1028                log_warn!("[USB] Gen1 transaction also lost binding: {drift}");
1029            }
1030            return Err(RoutingSessionError::Gen1(failure));
1031        }
1032    };
1033    if report.original != report.verified {
1034        let record = records.get_or_insert_with(|| RecordedGen1 {
1035            binding: binding.clone(),
1036            original: report.original.clone(),
1037            last: report.verified.clone(),
1038            uncertain: false,
1039        });
1040        let (original, last) = merge_gen1_provenance(
1041            &record.original,
1042            &record.last,
1043            &report.original,
1044            &report.verified,
1045        );
1046        record.original = original;
1047        record.last = last;
1048    }
1049    check_gen1_after(&device, configuration, &descriptors)?;
1050    Ok(report)
1051}
1052
1053fn finish_gen1_hand_back() {
1054    let Some(record) = ORIGINAL_GEN1.lock().take() else {
1055        return;
1056    };
1057    if settings().config.hand_back != crate::HandBack::RestoreOriginal {
1058        return;
1059    }
1060    let Some(device) = SESSION_STATE.lock().as_ref().map(|s| s.device.clone()) else {
1061        return;
1062    };
1063    let restore = || -> Result<(), RoutingSessionError> {
1064        let (configuration, descriptors) = active_descriptors(&device)?;
1065        check_gen1_binding(&record.binding, &device, configuration, &descriptors)?;
1066        let (model, interface) = gen1_target(&device, &descriptors)?;
1067        let result = crate::scarlett::restore_gen1(
1068            &mut UsbGen1Io {
1069                device: &device,
1070                interface,
1071            },
1072            model,
1073            &record.last,
1074            &record.original,
1075        )
1076        .map_err(RoutingSessionError::Gen1);
1077        invalidate_route_caches();
1078        let after = check_gen1_after(&device, configuration, &descriptors);
1079        match result {
1080            Ok(()) => after,
1081            Err(error) => {
1082                if let Err(drift) = after {
1083                    log_warn!("[USB] Gen1 restoration also lost binding: {drift}");
1084                }
1085                Err(error)
1086            }
1087        }
1088    };
1089    if let Err(error) = restore() {
1090        log_warn!("[USB] Original Gen1 controls not restored: {error}");
1091    }
1092}
1093
1094pub(super) struct RecordedFcp {
1095    device: UsbDevice,
1096    configuration: u8,
1097    descriptors: Vec<u8>,
1098    original: crate::scarlett::FcpReadback,
1099    last: crate::scarlett::FcpReadback,
1100    uncertain: bool,
1101}
1102static ORIGINAL_FCP: context::ScopedMutex<Option<RecordedFcp>> =
1103    context::ScopedMutex::new(|context| context.fcp.clone());
1104
1105pub(crate) fn fcp_apply(
1106    expected: &crate::scarlett::FcpReadback,
1107    routes: &[crate::scarlett::FcpRouteEdit],
1108    mixes: &[crate::scarlett::FcpMixEdit],
1109) -> Result<crate::scarlett::FcpWriteReport, RoutingSessionError> {
1110    require_vendor_routing_release()?;
1111    let _gate = USB_SESSION_GATE.lock();
1112    let _controls = HARDWARE_VOLUME_MUTEX.lock();
1113    let device = idle_device()?;
1114    let (configuration, descriptors) = active_descriptors(&device)?;
1115    let mut records = ORIGINAL_FCP.lock();
1116    if let Some(record) = records.as_ref() {
1117        if !record.device.same_owner(&device)
1118            || record.configuration != configuration
1119            || record.descriptors != descriptors
1120            || record.uncertain
1121            || !crate::scarlett::same_fcp_layout(&record.last, expected)
1122        {
1123            return Err(RoutingSessionError::Drift(
1124                "FCP attachment/configuration or rollback state changed".into(),
1125            ));
1126        }
1127        for bank in &expected.banks {
1128            if routes.iter().any(|edit| edit.bank == bank.bank) {
1129                if let (Some(original), Some(last)) = (
1130                    record.original.banks.iter().find(|b| b.bank == bank.bank),
1131                    record.last.banks.iter().find(|b| b.bank == bank.bank),
1132                ) {
1133                    if original != last && bank != last {
1134                        return Err(RoutingSessionError::Drift(
1135                            "FCP bank differs from last verified library write".into(),
1136                        ));
1137                    }
1138                }
1139            }
1140        }
1141        for row in &expected.mixes {
1142            if mixes.iter().any(|edit| edit.output == row.output) {
1143                if let (Some(original), Some(last)) = (
1144                    record
1145                        .original
1146                        .mixes
1147                        .iter()
1148                        .find(|r| r.output == row.output),
1149                    record.last.mixes.iter().find(|r| r.output == row.output),
1150                ) {
1151                    if original != last && row != last {
1152                        return Err(RoutingSessionError::Drift(
1153                            "FCP row differs from last verified library write".into(),
1154                        ));
1155                    }
1156                }
1157            }
1158        }
1159    }
1160    let report = match with_scarlett_io(&device, configuration, true, |io, candidate| {
1161        crate::scarlett::apply_fcp(io, candidate, expected, routes, mixes)
1162            .map_err(RoutingSessionError::Fcp)
1163    }) {
1164        Ok(report) => report,
1165        Err(error) => {
1166            if let RoutingSessionError::Fcp(failure) = &error {
1167                invalidate_route_caches();
1168                if !failure.rollback.is_empty() {
1169                    let record = records.get_or_insert_with(|| RecordedFcp {
1170                        device: device.clone(),
1171                        configuration,
1172                        descriptors: descriptors.clone(),
1173                        original: expected.clone(),
1174                        last: expected.clone(),
1175                        uncertain: true,
1176                    });
1177                    record.uncertain = true;
1178                    log_warn!("[USB] FCP rollback uncertain; configured hand-back will preserve targets differing from prior verified state");
1179                }
1180            }
1181            return Err(error);
1182        }
1183    };
1184    if report.original != report.verified {
1185        invalidate_route_caches();
1186        let record = records.get_or_insert_with(|| RecordedFcp {
1187            device: device.clone(),
1188            configuration,
1189            descriptors: descriptors.clone(),
1190            original: report.original.clone(),
1191            last: report.verified.clone(),
1192            uncertain: false,
1193        });
1194        let (original, last) = merge_fcp_provenance(
1195            &record.original,
1196            &record.last,
1197            &report.original,
1198            &report.verified,
1199        );
1200        record.original = original;
1201        record.last = last;
1202    }
1203    let (after, raw) = active_descriptors(&device)?;
1204    if configuration != after || descriptors != raw {
1205        return Err(RoutingSessionError::Drift(
1206            "configuration changed during FCP routing write".into(),
1207        ));
1208    }
1209    Ok(report)
1210}
1211
1212// Preserve per-target first-before/last-verified pairs. A later read may contain
1213// unrelated external edits; those must never become owned hand-back changes.
1214fn merge_fcp_provenance(
1215    original: &crate::scarlett::FcpReadback,
1216    last: &crate::scarlett::FcpReadback,
1217    before: &crate::scarlett::FcpReadback,
1218    verified: &crate::scarlett::FcpReadback,
1219) -> (crate::scarlett::FcpReadback, crate::scarlett::FcpReadback) {
1220    let mut merged_original = before.clone();
1221    let mut merged_last = verified.clone();
1222    for (index, bank) in before.banks.iter().enumerate() {
1223        if let (Some(old), Some(previous)) = (
1224            original.banks.iter().find(|b| b.bank == bank.bank),
1225            last.banks.iter().find(|b| b.bank == bank.bank),
1226        ) {
1227            if old != previous {
1228                merged_original.banks[index] = old.clone();
1229                if bank == &verified.banks[index] {
1230                    merged_last.banks[index] = previous.clone();
1231                }
1232            }
1233        }
1234    }
1235    for (index, row) in before.mixes.iter().enumerate() {
1236        if let (Some(old), Some(previous)) = (
1237            original.mixes.iter().find(|r| r.output == row.output),
1238            last.mixes.iter().find(|r| r.output == row.output),
1239        ) {
1240            if old != previous {
1241                merged_original.mixes[index] = old.clone();
1242                if row == &verified.mixes[index] {
1243                    merged_last.mixes[index] = previous.clone();
1244                }
1245            }
1246        }
1247    }
1248    (merged_original, merged_last)
1249}
1250
1251fn finish_fcp_hand_back() {
1252    let Some(record) = ORIGINAL_FCP.lock().take() else {
1253        return;
1254    };
1255    if settings().config.hand_back != crate::HandBack::RestoreOriginal {
1256        return;
1257    }
1258    if record.uncertain {
1259        log_warn!("[USB] FCP rollback uncertain; hand-back will restore only targets matching prior verified values");
1260    }
1261    let Some(device) = SESSION_STATE.lock().as_ref().map(|s| s.device.clone()) else {
1262        return;
1263    };
1264    let restore = || -> Result<(), RoutingSessionError> {
1265        if !record.device.same_owner(&device) {
1266            return Err(RoutingSessionError::Drift(
1267                "FCP attachment changed before hand-back".into(),
1268            ));
1269        }
1270        let (number, raw) = active_descriptors(&device)?;
1271        if number != record.configuration || raw != record.descriptors {
1272            return Err(RoutingSessionError::Drift(
1273                "FCP configuration changed before hand-back".into(),
1274            ));
1275        }
1276        with_scarlett_io(&device, number, true, |io, candidate| {
1277            crate::scarlett::restore_fcp(io, candidate, &record.last, &record.original)
1278                .map_err(RoutingSessionError::Fcp)
1279        })
1280    };
1281    if let Err(error) = restore() {
1282        log_warn!("[USB] Original FCP routing not restored: {error}");
1283    }
1284}
1285
1286pub(crate) fn scarlett_mix_apply(
1287    edit: &crate::scarlett::MixRowEdit,
1288) -> Result<crate::scarlett::MixWriteReport, RoutingSessionError> {
1289    require_vendor_routing_release()?;
1290    let _gate = USB_SESSION_GATE.lock();
1291    let _controls = HARDWARE_VOLUME_MUTEX.lock();
1292    let device = idle_device()?;
1293    let (configuration, descriptors) = active_descriptors(&device)?;
1294    let mut records = ORIGINAL_SCARLETT.lock();
1295    if let Some(record) = records.as_ref() {
1296        if !record.device.same_owner(&device)
1297            || record.configuration != configuration
1298            || record.descriptors != descriptors
1299        {
1300            return Err(RoutingSessionError::Drift(
1301                "Scarlett attachment/configuration changed since mixer write".into(),
1302            ));
1303        }
1304        if let Some((_, last)) = record.rows.get(&edit.expected.output) {
1305            if last != &edit.expected {
1306                return Err(RoutingSessionError::Drift(
1307                    "Scarlett row differs from last verified library write".into(),
1308                ));
1309            }
1310        }
1311    }
1312    let report = match with_scarlett(&device, configuration, |session| {
1313        session
1314            .apply_mix(edit)
1315            .map_err(RoutingSessionError::ScarlettMix)
1316    }) {
1317        Ok(report) => report,
1318        Err(error) => {
1319            if matches!(&error, RoutingSessionError::ScarlettMix(failure) if failure.rollback.is_some())
1320            {
1321                invalidate_route_caches();
1322            }
1323            return Err(error);
1324        }
1325    };
1326    // Record before the post-write descriptor check so a confirmed row is never
1327    // forgotten if configuration inspection itself fails after the write.
1328    if report.original != report.verified {
1329        invalidate_route_caches();
1330        let record = records.get_or_insert_with(|| RecordedScarlett {
1331            device: device.clone(),
1332            configuration,
1333            descriptors: descriptors.clone(),
1334            rows: BTreeMap::new(),
1335            mux: None,
1336        });
1337        record
1338            .rows
1339            .entry(report.original.output)
1340            .and_modify(|row| row.1 = report.verified.clone())
1341            .or_insert((report.original.clone(), report.verified.clone()));
1342    }
1343    let (after, raw) = active_descriptors(&device)?;
1344    if configuration != after || descriptors != raw {
1345        return Err(RoutingSessionError::Drift(
1346            "configuration changed during Scarlett mixer write".into(),
1347        ));
1348    }
1349    Ok(report)
1350}
1351
1352/// Explicit capability probe and complete per-bank read; legacy reads do not
1353/// invoke these optional commands, so unsupported replies leave those usable.
1354pub(crate) fn scarlett_mux_read() -> Result<crate::scarlett::MuxSnapshot, RoutingSessionError> {
1355    require_vendor_routing_release()?;
1356    let _gate = USB_SESSION_GATE.lock();
1357    let _controls = HARDWARE_VOLUME_MUTEX.lock();
1358    let device = idle_device()?;
1359    let (configuration, descriptors) = active_descriptors(&device)?;
1360    let snapshot = with_scarlett(&device, configuration, |session| {
1361        session
1362            .read_mux_banks()
1363            .map_err(RoutingSessionError::Scarlett)
1364    })?;
1365    let (after, raw) = active_descriptors(&device)?;
1366    if after != configuration || raw != descriptors {
1367        return Err(RoutingSessionError::Drift(
1368            "configuration changed during Scarlett bank read".into(),
1369        ));
1370    }
1371    Ok(snapshot)
1372}
1373
1374pub(crate) fn scarlett_mux_apply(
1375    edit: &crate::scarlett::MuxEdit,
1376) -> Result<crate::scarlett::MuxWriteReport, RoutingSessionError> {
1377    require_vendor_routing_release()?;
1378    let _gate = USB_SESSION_GATE.lock();
1379    let _controls = HARDWARE_VOLUME_MUTEX.lock();
1380    let device = idle_device()?;
1381    let (configuration, descriptors) = active_descriptors(&device)?;
1382    let mut records = ORIGINAL_SCARLETT.lock();
1383    if let Some(record) = records.as_ref() {
1384        if !record.device.same_owner(&device)
1385            || record.configuration != configuration
1386            || record.descriptors != descriptors
1387        {
1388            return Err(RoutingSessionError::Drift(
1389                "Scarlett attachment/configuration changed since vendor write".into(),
1390            ));
1391        }
1392        if let Some((_, last)) = &record.mux {
1393            if last != &edit.expected {
1394                return Err(RoutingSessionError::Drift(
1395                    "Scarlett banks differ from last verified library write".into(),
1396                ));
1397            }
1398        }
1399    }
1400    let report = match with_scarlett(&device, configuration, |session| {
1401        session
1402            .apply_mux(edit)
1403            .map_err(RoutingSessionError::ScarlettMux)
1404    }) {
1405        Ok(report) => report,
1406        Err(error) => {
1407            if matches!(&error, RoutingSessionError::ScarlettMux(failure) if !failure.rollback.is_empty())
1408            {
1409                invalidate_route_caches();
1410            }
1411            return Err(error);
1412        }
1413    };
1414    if report.original != report.verified {
1415        invalidate_route_caches();
1416        let record = records.get_or_insert_with(|| RecordedScarlett {
1417            device: device.clone(),
1418            configuration,
1419            descriptors: descriptors.clone(),
1420            rows: BTreeMap::new(),
1421            mux: None,
1422        });
1423        match &mut record.mux {
1424            Some((_, last)) => *last = report.verified.clone(),
1425            entry @ None => *entry = Some((report.original.clone(), report.verified.clone())),
1426        }
1427    }
1428    let (after, raw) = active_descriptors(&device)?;
1429    if configuration != after || descriptors != raw {
1430        return Err(RoutingSessionError::Drift(
1431            "configuration changed during Scarlett mux write".into(),
1432        ));
1433    }
1434    Ok(report)
1435}
1436
1437fn finish_scarlett_hand_back() {
1438    if !VENDOR_ROUTING_RELEASED {
1439        ORIGINAL_GEN1.lock().take();
1440        ORIGINAL_FCP.lock().take();
1441        ORIGINAL_SCARLETT.lock().take();
1442        return;
1443    }
1444    finish_gen1_hand_back();
1445    finish_fcp_hand_back();
1446    let Some(record) = ORIGINAL_SCARLETT.lock().take() else {
1447        return;
1448    };
1449    if settings().config.hand_back != crate::HandBack::RestoreOriginal {
1450        return;
1451    }
1452    let Some(device) = SESSION_STATE.lock().as_ref().map(|s| s.device.clone()) else {
1453        return;
1454    };
1455    let restore = || -> Result<(), RoutingSessionError> {
1456        if !record.device.same_owner(&device) {
1457            return Err(RoutingSessionError::Drift(
1458                "Scarlett attachment changed before hand-back".into(),
1459            ));
1460        }
1461        let (number, raw) = active_descriptors(&device)?;
1462        if number != record.configuration || raw != record.descriptors {
1463            return Err(RoutingSessionError::Drift(
1464                "Scarlett configuration changed before hand-back".into(),
1465            ));
1466        }
1467        with_scarlett(&device, number, |session| {
1468            if let Some((original, last)) = &record.mux {
1469                if let Err(error) = session.replace_mux(last, original) {
1470                    log_warn!("[USB] Scarlett mux banks not restored: {:?}", error);
1471                }
1472            }
1473            for (original, last) in record.rows.values() {
1474                // A fresh whole-row equality check prevents overwriting any
1475                // external edit, even in an otherwise untouched coefficient.
1476                if let Err(error) = session.replace_mix(last, original) {
1477                    log_warn!(
1478                        "[USB] Scarlett mixer row {} not restored: {:?}",
1479                        original.output,
1480                        error
1481                    );
1482                    // A poisoned failed recovery forbids subsequent writes.
1483                }
1484            }
1485            Ok(())
1486        })
1487    };
1488    if let Err(error) = restore() {
1489        log_warn!("[USB] Original Scarlett mixer not restored: {error}");
1490    }
1491}
1492
1493const ROUTING_OPERATION_BUDGET: Duration = Duration::from_secs(4);
1494const ROUTING_RECOVERY_BUDGET: Duration = Duration::from_secs(2);
1495fn remaining(deadline: Instant) -> Result<Duration, RoutingSessionError> {
1496    let left = deadline.saturating_duration_since(Instant::now());
1497    if left.is_zero() {
1498        return Err(RoutingSessionError::Session(Error::Control(
1499            "routing deadline expired".into(),
1500        )));
1501    }
1502    Ok(left.min(Duration::from_secs(1)))
1503}
1504
1505struct UsbRoutingIo<'a> {
1506    deadline: Instant,
1507    recovery: Arc<Mutex<Option<Instant>>>,
1508    device: &'a UsbDevice,
1509    descriptors: &'a [u8],
1510}
1511
1512/// Enforce the small set of setup packets this adapter is allowed to issue.
1513#[cfg(test)]
1514fn validate_request(request: ControlRequest, input: bool, length: usize) -> Result<(), String> {
1515    validate_protocol_request(request, input, length, 0x20)
1516}
1517fn validate_protocol_request(
1518    request: ControlRequest,
1519    input: bool,
1520    length: usize,
1521    protocol: u8,
1522) -> Result<(), String> {
1523    if protocol == 0 {
1524        let valid = request.request_type == if input { 0xa1 } else { 0x21 }
1525            && request.index >> 8 != 0
1526            && usize::from(request.length) == length
1527            && if input {
1528                matches!(request.request, 0x81..=0x84)
1529            } else {
1530                request.request == 1
1531            }
1532            && if request.value == 0 {
1533                length == 1 && matches!(request.request, 1 | 0x81)
1534            } else {
1535                request.value >> 8 != 0
1536                    && request.value as u8 != 0
1537                    && request.value != 0xffff
1538                    && length == 2
1539            };
1540        return if valid {
1541            Ok(())
1542        } else {
1543            Err("refused non-routing UAC1 control".into())
1544        };
1545    }
1546    if ![0x20, 0x30].contains(&protocol) {
1547        return Err("unsupported routing protocol".into());
1548    }
1549    let valid_length = if request.request == 1 {
1550        matches!(length, 1 | 2)
1551    } else {
1552        input && (2..=2 + routing::MAX_GAIN_RANGES * 6).contains(&length) && (length - 2) % 6 == 0
1553    };
1554    if request.request_type != if input { 0xa1 } else { 0x21 }
1555        || !matches!(request.request, 1 | 2)
1556        || (!input && request.request != 1)
1557        || request.value >> 8 != 1
1558        || request.index >> 8 == 0
1559        || usize::from(request.length) != length
1560        || !valid_length
1561    {
1562        return Err("refused non-routing or unbounded USB class control".to_string());
1563    }
1564    Ok(())
1565}
1566
1567impl UsbRoutingIo<'_> {
1568    fn validate(&self, request: ControlRequest, input: bool, length: usize) -> Result<(), String> {
1569        let interfaces =
1570            routing_interfaces_unambiguous(self.descriptors, &self.device.claimed_interfaces)
1571                .map_err(|e| e.to_string())?;
1572        let protocol = interfaces
1573            .get(&(request.index as u8))
1574            .ok_or("routing interface is not claimed")?
1575            .0;
1576        validate_protocol_request(request, input, length, protocol)
1577    }
1578}
1579
1580impl RoutingIo for UsbRoutingIo<'_> {
1581    type Error = String;
1582    fn read(&mut self, r: ControlRequest, bytes: &mut [u8]) -> Result<usize, String> {
1583        self.validate(r, true, bytes.len())?;
1584        self.device
1585            .feature_unit_control_timed(
1586                r.request_type,
1587                r.request,
1588                r.value,
1589                r.index,
1590                bytes,
1591                remaining(self.deadline).map_err(|e| e.to_string())?,
1592            )
1593            .map_err(|e| e.to_string())
1594    }
1595    fn write(&mut self, r: ControlRequest, bytes: &[u8]) -> Result<usize, String> {
1596        self.validate(r, false, bytes.len())?;
1597        let mut data = bytes.to_vec();
1598        self.device
1599            .feature_unit_control_timed(
1600                r.request_type,
1601                r.request,
1602                r.value,
1603                r.index,
1604                &mut data,
1605                remaining(self.deadline).map_err(|e| e.to_string())?,
1606            )
1607            .map_err(|e| e.to_string())
1608    }
1609    fn begin_recovery(&mut self) {
1610        let mut recovery = self.recovery.lock();
1611        self.deadline = *recovery.get_or_insert_with(|| Instant::now() + ROUTING_RECOVERY_BUDGET);
1612    }
1613}
1614
1615fn idle_device() -> Result<UsbDevice, RoutingSessionError> {
1616    idle_device_until(None)
1617}
1618fn idle_device_until(deadline: Option<Instant>) -> Result<UsbDevice, RoutingSessionError> {
1619    if USB_SESSION_CLEAR_PENDING.load(Ordering::SeqCst) {
1620        return Err(RoutingSessionError::Session(Error::InvalidState(
1621            "the DAC is being closed".into(),
1622        )));
1623    }
1624    if is_usb_session_active() {
1625        return Err(RoutingSessionError::Session(Error::InvalidState(
1626            "close all streams before routing controls".into(),
1627        )));
1628    }
1629    let state = match deadline {
1630        Some(deadline) => SESSION_STATE
1631            .try_lock_for(remaining(deadline)?)
1632            .ok_or_else(|| {
1633                RoutingSessionError::Session(Error::Control(
1634                    "routing deadline waiting for session state".into(),
1635                ))
1636            })?,
1637        None => SESSION_STATE.lock(),
1638    };
1639    let state = state.as_ref().ok_or_else(|| {
1640        RoutingSessionError::Session(Error::InvalidState("no DAC is open".into()))
1641    })?;
1642    if state.stream_active {
1643        return Err(RoutingSessionError::Session(Error::InvalidState(
1644            "a stream is still active".into(),
1645        )));
1646    }
1647    Ok(state.device.clone())
1648}
1649
1650fn active_descriptors(device: &UsbDevice) -> Result<(u8, Vec<u8>), RoutingSessionError> {
1651    active_descriptors_until(device, None)
1652}
1653fn active_descriptors_until(
1654    device: &UsbDevice,
1655    deadline: Option<Instant>,
1656) -> Result<(u8, Vec<u8>), RoutingSessionError> {
1657    let idle = match deadline {
1658        Some(deadline) => IDLE_LOCK
1659            .try_lock_for(remaining(deadline)?)
1660            .ok_or_else(|| {
1661                RoutingSessionError::Session(Error::Control(
1662                    "routing deadline waiting for idle owner".into(),
1663                ))
1664            })?,
1665        None => IDLE_LOCK.lock(),
1666    };
1667    let idle = idle
1668        .as_ref()
1669        .filter(|idle| idle.device_fd == device.fd)
1670        .ok_or_else(|| {
1671            RoutingSessionError::Session(Error::InvalidState(
1672                "routing requires the idle USB owner".into(),
1673            ))
1674        })?;
1675    if let Some(deadline) = deadline {
1676        let identity = idle
1677            .handle
1678            .device()
1679            .device_descriptor()
1680            .map_err(|e| RoutingSessionError::Session(Error::Control(e.to_string())))?;
1681        if identity.vendor_id() != device.vendor_id || identity.product_id() != device.product_id {
1682            return Err(RoutingSessionError::Drift(
1683                "routing device identity changed".into(),
1684            ));
1685        }
1686        let read_config = |value: u16, bytes: &mut [u8]| -> Result<usize, RoutingSessionError> {
1687            idle.handle
1688                .read_control(0x80, 6, value, 0, bytes, remaining(deadline)?)
1689                .map_err(|e| RoutingSessionError::Session(Error::Control(e.to_string())))
1690        };
1691        let read_active = || -> Result<u8, RoutingSessionError> {
1692            let mut number = [0];
1693            let n = idle
1694                .handle
1695                .read_control(0x80, 8, 0, 0, &mut number, remaining(deadline)?)
1696                .map_err(|e| RoutingSessionError::Session(Error::Control(e.to_string())))?;
1697            if n != 1 {
1698                return Err(RoutingSessionError::Session(Error::Control(
1699                    "short GET_CONFIGURATION".into(),
1700                )));
1701            }
1702            Ok(number[0])
1703        };
1704        let active = read_active()?;
1705        for index in 0..identity.num_configurations() {
1706            let mut header = [0u8; 9];
1707            if read_config(0x0200 | u16::from(index), &mut header)? != header.len() {
1708                continue;
1709            }
1710            if header[0] != 9 || header[1] != 2 {
1711                return Err(RoutingSessionError::Invalid(
1712                    InvalidRoute::MalformedDescriptor,
1713                ));
1714            }
1715            if header[5] != active {
1716                continue;
1717            }
1718            let length = usize::from(u16::from_le_bytes([header[2], header[3]]));
1719            if length < header.len() {
1720                return Err(RoutingSessionError::Invalid(
1721                    InvalidRoute::MalformedDescriptor,
1722                ));
1723            }
1724            let mut raw = vec![0; length];
1725            if read_config(0x0200 | u16::from(index), &mut raw)? != length
1726                || raw[..header.len()] != header
1727                || read_active()? != active
1728            {
1729                return Err(RoutingSessionError::Drift(
1730                    "active configuration changed during discovery".into(),
1731                ));
1732            }
1733            return Ok((active, raw));
1734        }
1735        return Err(RoutingSessionError::Drift(
1736            "active configuration descriptor unavailable".into(),
1737        ));
1738    }
1739    let identity = idle
1740        .handle
1741        .device()
1742        .device_descriptor()
1743        .map_err(|e| RoutingSessionError::Session(Error::Control(e.to_string())))?;
1744    if identity.vendor_id() != device.vendor_id || identity.product_id() != device.product_id {
1745        return Err(RoutingSessionError::Drift(
1746            "routing device identity changed".into(),
1747        ));
1748    }
1749    let number = idle
1750        .handle
1751        .active_configuration()
1752        .map_err(|e| RoutingSessionError::Session(Error::Control(e.to_string())))?;
1753    let config = idle
1754        .handle
1755        .device()
1756        .active_config_descriptor()
1757        .map_err(|e| RoutingSessionError::Session(Error::Control(e.to_string())))?;
1758    if config.number() != number {
1759        return Err(RoutingSessionError::Drift(
1760            "active configuration changed during discovery".into(),
1761        ));
1762    }
1763    let raw = read_active_configuration_bytes(&idle.handle, &config).ok_or_else(|| {
1764        RoutingSessionError::Session(Error::Control(
1765            "failed bounded active configuration read".into(),
1766        ))
1767    })?;
1768    if idle
1769        .handle
1770        .active_configuration()
1771        .map_err(|e| RoutingSessionError::Session(Error::Control(e.to_string())))?
1772        != number
1773    {
1774        return Err(RoutingSessionError::Drift(
1775            "active configuration changed during descriptor read".into(),
1776        ));
1777    }
1778    Ok((number, raw))
1779}
1780
1781/// Require complete descriptor framing; truncated topology cannot authorize I/O.
1782fn framed(bytes: &[u8]) -> Result<Vec<&[u8]>, RoutingSessionError> {
1783    let mut slices = Vec::new();
1784    let mut position = 0;
1785    while position < bytes.len() {
1786        let length = usize::from(*bytes.get(position).unwrap());
1787        if length < 2 || position + length > bytes.len() {
1788            return Err(RoutingSessionError::Invalid(
1789                InvalidRoute::MalformedDescriptor,
1790            ));
1791        }
1792        slices.push(&bytes[position..position + length]);
1793        position += length;
1794    }
1795    Ok(slices)
1796}
1797
1798/// Preserve optional/common/unknown segments too: a selector requires equal
1799/// Cluster content, not merely equal counts or the parsed speaker relationships.
1800#[derive(Debug, Clone, PartialEq, Eq)]
1801struct RoutingCluster {
1802    parsed: crate::descriptors::uac3::Cluster,
1803    content: Vec<u8>,
1804}
1805impl RoutingCluster {
1806    fn identity(&self) -> Vec<u8> {
1807        // Unique descriptor IDs may differ while the described content matches.
1808        self.content[..4]
1809            .iter()
1810            .chain(&self.content[6..])
1811            .copied()
1812            .collect()
1813    }
1814}
1815fn query_routing_cluster(
1816    handle: &DeviceHandle<Context>,
1817    interface: u8,
1818    id: u16,
1819    deadline: Instant,
1820) -> Result<RoutingCluster, RoutingSessionError> {
1821    use crate::descriptors::uac3;
1822    let fail = |e: String| RoutingSessionError::UnsupportedTopology(e);
1823    let mut prefix = [0; 6];
1824    let n = handle
1825        .read_control(
1826            0xa1,
1827            6,
1828            id,
1829            u16::from(interface),
1830            &mut prefix,
1831            remaining(deadline)?,
1832        )
1833        .map_err(|e| fail(e.to_string()))?;
1834    let header =
1835        uac3::parse_cluster_header(&prefix[..n], id, 16 * 1024).map_err(|e| fail(e.to_string()))?;
1836    let mut content = vec![0; usize::from(header.length)];
1837    let n = handle
1838        .read_control(
1839            0xa1,
1840            6,
1841            id,
1842            u16::from(interface),
1843            &mut content,
1844            remaining(deadline)?,
1845        )
1846        .map_err(|e| fail(e.to_string()))?;
1847    let parsed = uac3::parse_cluster(&content[..n], header).map_err(|e| fail(e.to_string()))?;
1848    Ok(RoutingCluster { parsed, content })
1849}
1850
1851#[derive(Debug, Clone, PartialEq, Eq)]
1852struct Cluster {
1853    channels: u8,
1854    identity: ClusterIdentity,
1855}
1856#[derive(Debug, Clone, PartialEq, Eq)]
1857enum ClusterIdentity {
1858    Unknown,
1859    Explicit { locations: u32, names: u8 },
1860    Adc3(Vec<u8>),
1861}
1862
1863fn explicit_cluster(
1864    bytes: &[u8],
1865    offset: usize,
1866    protocol: u8,
1867) -> Result<Cluster, RoutingSessionError> {
1868    let width = if protocol == 0 { 4 } else { 6 };
1869    let part = bytes
1870        .get(offset..offset + width)
1871        .ok_or(RoutingSessionError::Invalid(
1872            InvalidRoute::MalformedDescriptor,
1873        ))?;
1874    if part[0] == 0 {
1875        return Err(RoutingSessionError::Invalid(
1876            InvalidRoute::UnknownInputChannels,
1877        ));
1878    }
1879    let locations = if protocol == 0 {
1880        u32::from(u16::from_le_bytes([part[1], part[2]]))
1881    } else {
1882        u32::from_le_bytes([part[1], part[2], part[3], part[4]])
1883    };
1884    Ok(Cluster {
1885        channels: part[0],
1886        identity: ClusterIdentity::Explicit {
1887            locations,
1888            names: part[width - 1],
1889        },
1890    })
1891}
1892
1893fn resolve_cluster_cached(
1894    id: u8,
1895    nodes: &BTreeMap<u8, &[u8]>,
1896    path: &mut Vec<u8>,
1897    cache: &mut BTreeMap<u8, Cluster>,
1898    protocol: u8,
1899    interface: u8,
1900    hc: &BTreeMap<(u8, u16), RoutingCluster>,
1901) -> Result<Cluster, RoutingSessionError> {
1902    if path.contains(&id) || path.len() >= MAX_TOPOLOGY_DEPTH {
1903        return Err(RoutingSessionError::UnsupportedTopology(
1904            "cyclic or excessive source topology".into(),
1905        ));
1906    }
1907    if let Some(cluster) = cache.get(&id) {
1908        return Ok(cluster.clone());
1909    }
1910    let bytes = *nodes.get(&id).ok_or_else(|| {
1911        RoutingSessionError::UnsupportedTopology(format!("unresolved source entity {id}"))
1912    })?;
1913    path.push(id);
1914    let mixer_subtype = if protocol == 0x30 { 5 } else { 4 };
1915    let selector_subtype = if protocol == 0x30 { 6 } else { 5 };
1916    let feature_subtype = if protocol == 0x30 { 7 } else { 6 };
1917    let result = (|| {
1918        let queried = |at: usize| -> Result<Cluster, RoutingSessionError> {
1919            let pair = bytes.get(at..at + 2).ok_or(RoutingSessionError::Invalid(
1920                InvalidRoute::MalformedDescriptor,
1921            ))?;
1922            let cluster_id = u16::from_le_bytes([pair[0], pair[1]]);
1923            let c = hc.get(&(interface, cluster_id)).ok_or_else(|| {
1924                RoutingSessionError::UnsupportedTopology(
1925                    "ADC3 routing requires a resolved HC Cluster".into(),
1926                )
1927            })?;
1928            let channels = u8::try_from(c.parsed.channels.len())
1929                .map_err(|_| RoutingSessionError::Invalid(InvalidRoute::UnknownInputChannels))?;
1930            if channels == 0 {
1931                return Err(RoutingSessionError::Invalid(
1932                    InvalidRoute::UnknownInputChannels,
1933                ));
1934            }
1935            Ok(Cluster {
1936                channels,
1937                identity: ClusterIdentity::Adc3(c.identity()),
1938            })
1939        };
1940        if bytes[2] == 2 {
1941            return match protocol {
1942                0 if bytes.len() == 12 => explicit_cluster(bytes, 7, protocol),
1943                0x20 if bytes.len() == 17 => explicit_cluster(bytes, 8, protocol),
1944                0x30 => {
1945                    crate::descriptors::uac3::parse_input_terminal(bytes)
1946                        .map_err(|e| RoutingSessionError::UnsupportedTopology(e.to_string()))?;
1947                    queried(12)
1948                }
1949                _ => Err(RoutingSessionError::Invalid(
1950                    InvalidRoute::MalformedDescriptor,
1951                )),
1952            };
1953        }
1954        if bytes[2] == mixer_subtype || bytes[2] == selector_subtype {
1955            let count = usize::from(*bytes.get(4).ok_or(RoutingSessionError::Invalid(
1956                InvalidRoute::MalformedDescriptor,
1957            ))?);
1958            let sources = bytes.get(5..5 + count).ok_or(RoutingSessionError::Invalid(
1959                InvalidRoute::MalformedDescriptor,
1960            ))?;
1961            let mut clusters = Vec::new();
1962            let mut inputs = Vec::new();
1963            for &source_id in sources {
1964                let cluster =
1965                    resolve_cluster_cached(source_id, nodes, path, cache, protocol, interface, hc)?;
1966                inputs.push(InputCluster {
1967                    source_id,
1968                    channels: cluster.channels,
1969                });
1970                clusters.push(cluster);
1971            }
1972            if bytes[2] == mixer_subtype {
1973                let output = if protocol == 0x30 {
1974                    queried(5 + count)?
1975                } else {
1976                    explicit_cluster(bytes, 5 + count, protocol)?
1977                };
1978                parse_mixer(interface, bytes, &inputs, protocol, output.channels)?;
1979                return Ok(output);
1980            }
1981            parse_selector(interface, bytes, protocol)?;
1982            if clusters.is_empty() || clusters.iter().any(|c| c.channels != clusters[0].channels) {
1983                return Err(RoutingSessionError::UnsupportedTopology(
1984                    "selector input widths differ or are empty".into(),
1985                ));
1986            }
1987            let first = clusters.remove(0);
1988            return Ok(if clusters.iter().all(|c| c.identity == first.identity) {
1989                first
1990            } else {
1991                Cluster {
1992                    channels: first.channels,
1993                    identity: ClusterIdentity::Unknown,
1994                }
1995            });
1996        }
1997        if bytes[2] == feature_subtype && bytes.len() >= 6 {
1998            let cluster =
1999                resolve_cluster_cached(bytes[4], nodes, path, cache, protocol, interface, hc)?;
2000            let valid = match protocol {
2001                0 => {
2002                    bytes[5] > 0
2003                        && bytes.len()
2004                            == 7 + (usize::from(cluster.channels) + 1) * usize::from(bytes[5])
2005                }
2006                0x20 => bytes.len() == 6 + (usize::from(cluster.channels) + 1) * 4,
2007                0x30 => crate::descriptors::uac3::parse_feature_unit(bytes)
2008                    .is_ok_and(|f| f.controls.len() == usize::from(cluster.channels) + 1),
2009                _ => false,
2010            };
2011            if !valid {
2012                return Err(RoutingSessionError::Invalid(
2013                    InvalidRoute::MalformedDescriptor,
2014                ));
2015            }
2016            return Ok(cluster);
2017        }
2018        Err(RoutingSessionError::UnsupportedTopology(format!(
2019            "source entity {id} has unsupported channel topology"
2020        )))
2021    })();
2022    path.pop();
2023    if let Ok(cluster) = &result {
2024        cache.insert(id, cluster.clone());
2025    }
2026    result
2027}
2028
2029fn parse_selector(
2030    interface: u8,
2031    bytes: &[u8],
2032    protocol: u8,
2033) -> Result<SelectorUnit, RoutingSessionError> {
2034    match protocol {
2035        0 => SelectorUnit::parse_uac1(interface, bytes),
2036        0x30 => SelectorUnit::parse_adc3(interface, bytes),
2037        _ => SelectorUnit::parse(interface, bytes),
2038    }
2039    .map_err(RoutingSessionError::Invalid)
2040}
2041fn parse_mixer(
2042    interface: u8,
2043    bytes: &[u8],
2044    inputs: &[InputCluster],
2045    protocol: u8,
2046    outputs: u8,
2047) -> Result<MixerUnit, RoutingSessionError> {
2048    match protocol {
2049        0 => MixerUnit::parse_uac1(interface, bytes, inputs),
2050        0x30 => MixerUnit::parse_adc3(interface, bytes, inputs, outputs),
2051        _ => MixerUnit::parse(interface, bytes, inputs),
2052    }
2053    .map_err(RoutingSessionError::Invalid)
2054}
2055
2056fn routing_interfaces<'a>(
2057    raw: &'a [u8],
2058    claims: &[u8],
2059) -> Result<BTreeMap<u8, (u8, Vec<&'a [u8]>)>, RoutingSessionError> {
2060    let (interfaces, diagnostics) = routing_interfaces_with_diagnostics(raw, claims)?;
2061    if !diagnostics.is_empty() {
2062        return Err(RoutingSessionError::Invalid(InvalidRoute::DuplicateEntity));
2063    }
2064    Ok(interfaces)
2065}
2066fn routing_interfaces_unambiguous<'a>(
2067    raw: &'a [u8],
2068    claims: &[u8],
2069) -> Result<BTreeMap<u8, (u8, Vec<&'a [u8]>)>, RoutingSessionError> {
2070    Ok(routing_interfaces_with_diagnostics(raw, claims)?.0)
2071}
2072
2073fn routing_interfaces_with_diagnostics<'a>(
2074    raw: &'a [u8],
2075    claims: &[u8],
2076) -> Result<(BTreeMap<u8, (u8, Vec<&'a [u8]>)>, Vec<RoutingDiagnostic>), RoutingSessionError> {
2077    if raw.len() < 9
2078        || raw[0] != 9
2079        || raw[1] != 2
2080        || usize::from(u16::from_le_bytes([raw[2], raw[3]])) != raw.len()
2081    {
2082        return Err(RoutingSessionError::Invalid(
2083            InvalidRoute::MalformedDescriptor,
2084        ));
2085    }
2086    let mut interfaces = BTreeMap::new();
2087    let mut ambiguous = std::collections::BTreeSet::new();
2088    let mut current = None;
2089    for bytes in framed(raw)? {
2090        if bytes[1] == 4 {
2091            if bytes.len() != 9 {
2092                return Err(RoutingSessionError::Invalid(
2093                    InvalidRoute::MalformedDescriptor,
2094                ));
2095            }
2096            current = None;
2097            if bytes[3] == 0
2098                && bytes[5] == 1
2099                && bytes[6] == 1
2100                && [0, 0x20, 0x30].contains(&bytes[7])
2101                && claims.contains(&bytes[2])
2102            {
2103                if ambiguous.contains(&bytes[2]) {
2104                    continue;
2105                }
2106                if interfaces
2107                    .insert(bytes[2], (bytes[7], Vec::new()))
2108                    .is_some()
2109                {
2110                    interfaces.remove(&bytes[2]);
2111                    ambiguous.insert(bytes[2]);
2112                    continue;
2113                }
2114                current = Some(bytes[2]);
2115            }
2116        } else if bytes[1] == 0x24 {
2117            if let Some(interface) = current {
2118                interfaces.get_mut(&interface).unwrap().1.push(bytes);
2119            }
2120        }
2121    }
2122    let diagnostics = ambiguous
2123        .into_iter()
2124        .map(|interface| RoutingDiagnostic {
2125            interface,
2126            entity_id: None,
2127            detail: "ambiguous AudioControl function".into(),
2128        })
2129        .collect();
2130    Ok((interfaces, diagnostics))
2131}
2132
2133#[cfg(test)]
2134fn inventory_from_config(
2135    raw: &[u8],
2136    claims: &[u8],
2137) -> Result<RoutingInventory, RoutingSessionError> {
2138    inventory_with_clusters(raw, claims, &BTreeMap::new())
2139}
2140#[cfg(test)]
2141fn inventory_with_clusters(
2142    raw: &[u8],
2143    claims: &[u8],
2144    hc: &BTreeMap<(u8, u16), RoutingCluster>,
2145) -> Result<RoutingInventory, RoutingSessionError> {
2146    let mut inventory = RoutingInventory::default();
2147    for (interface, (protocol, descriptors)) in routing_interfaces(raw, claims)? {
2148        let mut nodes = BTreeMap::new();
2149        let mut header = None;
2150        for &bytes in &descriptors {
2151            if bytes.len() < 4 {
2152                return Err(RoutingSessionError::Invalid(
2153                    InvalidRoute::MalformedDescriptor,
2154                ));
2155            }
2156            if bytes[2] == 1 {
2157                if header.replace(bytes).is_some() {
2158                    return Err(RoutingSessionError::Invalid(
2159                        InvalidRoute::MalformedDescriptor,
2160                    ));
2161                }
2162            } else if bytes[3] == 0 || nodes.insert(bytes[3], bytes).is_some() {
2163                return Err(RoutingSessionError::Invalid(InvalidRoute::DuplicateEntity));
2164            }
2165        }
2166        let header = header.ok_or(RoutingSessionError::Invalid(
2167            InvalidRoute::MalformedDescriptor,
2168        ))?;
2169        let total = match protocol {
2170            0 if header.len() >= 8
2171                && header[3..5] == [0, 1]
2172                && header.len() == 8 + usize::from(header[7]) =>
2173            {
2174                u16::from_le_bytes([header[5], header[6]])
2175            }
2176            0x20 if header.len() == 9 && header[3..5] == [0, 2] => {
2177                u16::from_le_bytes([header[6], header[7]])
2178            }
2179            0x30 => {
2180                crate::descriptors::uac3::parse_ac_header(header)
2181                    .map_err(|e| RoutingSessionError::UnsupportedTopology(e.to_string()))?
2182                    .total_length
2183            }
2184            _ => {
2185                return Err(RoutingSessionError::Invalid(
2186                    InvalidRoute::MalformedDescriptor,
2187                ))
2188            }
2189        };
2190        if usize::from(total) != descriptors.iter().map(|d| d.len()).sum::<usize>() {
2191            return Err(RoutingSessionError::Invalid(
2192                InvalidRoute::MalformedDescriptor,
2193            ));
2194        }
2195        let mut cache = BTreeMap::new();
2196        for &bytes in nodes.values() {
2197            let mixer = if protocol == 0x30 { 5 } else { 4 };
2198            let selector = if protocol == 0x30 { 6 } else { 5 };
2199            if bytes[2] != mixer && bytes[2] != selector {
2200                continue;
2201            }
2202            let output = resolve_cluster_cached(
2203                bytes[3],
2204                &nodes,
2205                &mut Vec::new(),
2206                &mut cache,
2207                protocol,
2208                interface,
2209                hc,
2210            )?;
2211            let unit = if bytes[2] == selector {
2212                RoutingUnit::Selector(parse_selector(interface, bytes, protocol)?)
2213            } else {
2214                let count = usize::from(bytes[4]);
2215                let inputs = bytes[5..5 + count]
2216                    .iter()
2217                    .map(|&source_id| {
2218                        Ok(InputCluster {
2219                            source_id,
2220                            channels: resolve_cluster_cached(
2221                                source_id,
2222                                &nodes,
2223                                &mut Vec::new(),
2224                                &mut cache,
2225                                protocol,
2226                                interface,
2227                                hc,
2228                            )?
2229                            .channels,
2230                        })
2231                    })
2232                    .collect::<Result<Vec<_>, RoutingSessionError>>()?;
2233                RoutingUnit::Mixer(parse_mixer(
2234                    interface,
2235                    bytes,
2236                    &inputs,
2237                    protocol,
2238                    output.channels,
2239                )?)
2240            };
2241            inventory
2242                .insert(unit)
2243                .map_err(RoutingSessionError::Invalid)?;
2244        }
2245    }
2246    Ok(inventory)
2247}
2248
2249fn inventory_partial(
2250    raw: &[u8],
2251    claims: &[u8],
2252    hc: &BTreeMap<(u8, u16), RoutingCluster>,
2253) -> Result<(RoutingInventory, Vec<RoutingDiagnostic>), RoutingSessionError> {
2254    inventory_partial_for(raw, claims, hc, None)
2255}
2256
2257fn inventory_partial_for(
2258    raw: &[u8],
2259    claims: &[u8],
2260    hc: &BTreeMap<(u8, u16), RoutingCluster>,
2261    only_interface: Option<u8>,
2262) -> Result<(RoutingInventory, Vec<RoutingDiagnostic>), RoutingSessionError> {
2263    let mut inventory = RoutingInventory::default();
2264    let mut diagnostics = Vec::new();
2265    for (interface, (protocol, descriptors)) in routing_interfaces_unambiguous(raw, claims)? {
2266        if only_interface.is_some_and(|id| id != interface) {
2267            continue;
2268        }
2269        let function = (|| -> Result<(), RoutingSessionError> {
2270            let mut nodes = BTreeMap::new();
2271            let mut header = None;
2272            for &bytes in &descriptors {
2273                if bytes.len() < 4 {
2274                    return Err(RoutingSessionError::Invalid(
2275                        InvalidRoute::MalformedDescriptor,
2276                    ));
2277                }
2278                if bytes[2] == 1 {
2279                    if header.replace(bytes).is_some() {
2280                        return Err(RoutingSessionError::Invalid(
2281                            InvalidRoute::MalformedDescriptor,
2282                        ));
2283                    }
2284                } else if bytes[3] == 0 || nodes.insert(bytes[3], bytes).is_some() {
2285                    return Err(RoutingSessionError::Invalid(InvalidRoute::DuplicateEntity));
2286                }
2287            }
2288            let header = header.ok_or(RoutingSessionError::Invalid(
2289                InvalidRoute::MalformedDescriptor,
2290            ))?;
2291            let total = match protocol {
2292                0 if header.len() >= 8
2293                    && header[3..5] == [0, 1]
2294                    && header.len() == 8 + usize::from(header[7]) =>
2295                {
2296                    u16::from_le_bytes([header[5], header[6]])
2297                }
2298                0x20 if header.len() == 9 && header[3..5] == [0, 2] => {
2299                    u16::from_le_bytes([header[6], header[7]])
2300                }
2301                0x30 => {
2302                    crate::descriptors::uac3::parse_ac_header(header)
2303                        .map_err(|e| RoutingSessionError::UnsupportedTopology(e.to_string()))?
2304                        .total_length
2305                }
2306                _ => {
2307                    return Err(RoutingSessionError::Invalid(
2308                        InvalidRoute::MalformedDescriptor,
2309                    ))
2310                }
2311            };
2312            if usize::from(total) != descriptors.iter().map(|d| d.len()).sum::<usize>() {
2313                return Err(RoutingSessionError::Invalid(
2314                    InvalidRoute::MalformedDescriptor,
2315                ));
2316            }
2317            let mut cache = BTreeMap::new();
2318            for &bytes in nodes.values() {
2319                let mixer = if protocol == 0x30 { 5 } else { 4 };
2320                let selector = if protocol == 0x30 { 6 } else { 5 };
2321                if bytes[2] != mixer && bytes[2] != selector {
2322                    continue;
2323                }
2324                let unit = (|| -> Result<RoutingUnit, RoutingSessionError> {
2325                    if bytes[2] == selector {
2326                        return Ok(RoutingUnit::Selector(parse_selector(
2327                            interface, bytes, protocol,
2328                        )?));
2329                    }
2330                    let output = resolve_cluster_cached(
2331                        bytes[3],
2332                        &nodes,
2333                        &mut Vec::new(),
2334                        &mut cache,
2335                        protocol,
2336                        interface,
2337                        hc,
2338                    )?;
2339                    let unit = if bytes[2] == selector {
2340                        RoutingUnit::Selector(parse_selector(interface, bytes, protocol)?)
2341                    } else {
2342                        let count = usize::from(bytes[4]);
2343                        let inputs = bytes[5..5 + count]
2344                            .iter()
2345                            .map(|&source_id| {
2346                                Ok(InputCluster {
2347                                    source_id,
2348                                    channels: resolve_cluster_cached(
2349                                        source_id,
2350                                        &nodes,
2351                                        &mut Vec::new(),
2352                                        &mut cache,
2353                                        protocol,
2354                                        interface,
2355                                        hc,
2356                                    )?
2357                                    .channels,
2358                                })
2359                            })
2360                            .collect::<Result<Vec<_>, RoutingSessionError>>()?;
2361                        RoutingUnit::Mixer(parse_mixer(
2362                            interface,
2363                            bytes,
2364                            &inputs,
2365                            protocol,
2366                            output.channels,
2367                        )?)
2368                    };
2369                    Ok(unit)
2370                })();
2371                match unit {
2372                    Ok(unit) => inventory
2373                        .insert(unit)
2374                        .map_err(RoutingSessionError::Invalid)?,
2375                    Err(error) => diagnostics.push(RoutingDiagnostic {
2376                        interface,
2377                        entity_id: Some(bytes[3]),
2378                        detail: error.to_string(),
2379                    }),
2380                }
2381            }
2382            Ok(())
2383        })();
2384        if let Err(error) = function {
2385            diagnostics.push(RoutingDiagnostic {
2386                interface,
2387                entity_id: None,
2388                detail: error.to_string(),
2389            });
2390        }
2391    }
2392    Ok((inventory, diagnostics))
2393}
2394
2395/// Descriptor-only scope proof shared by no-wake discovery and explicit wake.
2396#[cfg(test)]
2397fn adc3_routing_scope(
2398    descriptors: &[&[u8]],
2399) -> Result<
2400    (
2401        Vec<crate::descriptors::uac3::PowerDomain>,
2402        std::collections::BTreeSet<u8>,
2403    ),
2404    RoutingSessionError,
2405> {
2406    adc3_routing_scope_for(descriptors, None)
2407}
2408
2409fn adc3_routing_scope_for(
2410    descriptors: &[&[u8]],
2411    root: Option<u8>,
2412) -> Result<
2413    (
2414        Vec<crate::descriptors::uac3::PowerDomain>,
2415        std::collections::BTreeSet<u8>,
2416    ),
2417    RoutingSessionError,
2418> {
2419    let mut domains = BTreeMap::new();
2420    let mut members = std::collections::BTreeSet::new();
2421    for bytes in descriptors {
2422        if bytes.get(2) != Some(&0x10) {
2423            continue;
2424        }
2425        let domain = crate::descriptors::uac3::parse_power_domain(bytes)
2426            .map_err(|e| RoutingSessionError::UnsupportedTopology(e.to_string()))?;
2427        if domains.insert(domain.id, domain.clone()).is_some()
2428            || domain.entities.iter().any(|e| !members.insert(*e))
2429        {
2430            return Err(RoutingSessionError::UnsupportedTopology(
2431                "ADC3 routing power domains overlap or repeat".into(),
2432            ));
2433        }
2434    }
2435    let mut nodes = BTreeMap::new();
2436    for bytes in descriptors.iter().filter(|b| b.len() >= 4 && b[2] != 1) {
2437        if nodes.insert(bytes[3], *bytes).is_some() {
2438            return Err(RoutingSessionError::Invalid(InvalidRoute::DuplicateEntity));
2439        }
2440    }
2441    let mut affected = std::collections::BTreeSet::new();
2442    let mut pending: Vec<_> = nodes
2443        .values()
2444        .filter(|b| matches!(b[2], 5 | 6) && root.map_or(true, |id| b[3] == id))
2445        .map(|b| b[3])
2446        .collect();
2447    while let Some(id) = pending.pop() {
2448        if !affected.insert(id) {
2449            continue;
2450        }
2451        let bytes = nodes.get(&id).ok_or_else(|| {
2452            RoutingSessionError::UnsupportedTopology("unresolved ADC3 routing source".into())
2453        })?;
2454        match bytes[2] {
2455            5 | 6 => {
2456                let pins = usize::from(*bytes.get(4).ok_or(RoutingSessionError::Invalid(
2457                    InvalidRoute::MalformedDescriptor,
2458                ))?);
2459                pending.extend(bytes.get(5..5 + pins).ok_or(RoutingSessionError::Invalid(
2460                    InvalidRoute::MalformedDescriptor,
2461                ))?);
2462            }
2463            7 => pending.push(*bytes.get(4).ok_or(RoutingSessionError::Invalid(
2464                InvalidRoute::MalformedDescriptor,
2465            ))?),
2466            _ => {}
2467        }
2468    }
2469    Ok((
2470        domains
2471            .into_values()
2472            .filter(|d| d.entities.iter().any(|e| affected.contains(e)))
2473            .collect(),
2474        affected,
2475    ))
2476}
2477
2478/// Require every interface in the affected full ADC3 function to be claimed
2479/// and every AS interface to be idle before the first power write.
2480fn routing_power_interfaces(
2481    raw: &[u8],
2482    claims: &[u8],
2483    control: u8,
2484) -> Result<Vec<u8>, RoutingSessionError> {
2485    let descriptors = framed(raw)?;
2486    if descriptors.iter().any(|b| b[1] == 11 && b.len() != 8) {
2487        return Err(RoutingSessionError::Invalid(
2488            InvalidRoute::MalformedDescriptor,
2489        ));
2490    }
2491    let owners: Vec<_> = descriptors
2492        .iter()
2493        .filter(|b| {
2494            b[1] == 11
2495                && b.len() == 8
2496                && u16::from(control) >= u16::from(b[2])
2497                && u16::from(control) < u16::from(b[2]) + u16::from(b[3])
2498        })
2499        .collect();
2500    let fail = || {
2501        RoutingSessionError::UnsupportedTopology(
2502            "powered ADC3 routing requires one fully claimed full Audio function".into(),
2503        )
2504    };
2505    if owners.len() != 1 {
2506        return Err(fail());
2507    }
2508    let owner = owners[0];
2509    if owner[2] != control
2510        || owner[3] == 0
2511        || owner[4..7] != [1, 0, 0x30]
2512        || u16::from(owner[2]) + u16::from(owner[3]) > 256
2513    {
2514        return Err(fail());
2515    }
2516    let mut streams = Vec::new();
2517    for interface in u16::from(owner[2])..u16::from(owner[2]) + u16::from(owner[3]) {
2518        let interface = interface as u8;
2519        if descriptors
2520            .iter()
2521            .filter(|b| {
2522                b[1] == 11
2523                    && b.len() == 8
2524                    && u16::from(interface) >= u16::from(b[2])
2525                    && u16::from(interface) < u16::from(b[2]) + u16::from(b[3])
2526            })
2527            .count()
2528            != 1
2529        {
2530            return Err(fail());
2531        }
2532        let alts: Vec<_> = descriptors
2533            .iter()
2534            .filter(|b| b[1] == 4 && b.len() == 9 && b[2] == interface && b[3] == 0)
2535            .collect();
2536        if !claims.contains(&interface)
2537            || alts.len() != 1
2538            || alts[0][5] != 1
2539            || alts[0][7] != 0x30
2540            || alts[0][6] != if interface == control { 1 } else { 2 }
2541        {
2542            return Err(fail());
2543        }
2544        if interface != control {
2545            streams.push(interface);
2546        }
2547    }
2548    Ok(streams)
2549}
2550
2551// Keep panic unwinding subject to the same no-external-drift-overwrite rule.
2552struct RoutingPowerLease(super::adc3::Adc3PowerLease);
2553impl Drop for RoutingPowerLease {
2554    fn drop(&mut self) {
2555        if let Err(error) = self.0.restore_checked() {
2556            log_warn!("[USB] ADC3 routing power hand-back: {error}");
2557        }
2558    }
2559}
2560
2561fn with_routing_power<T>(
2562    device: &UsbDevice,
2563    raw: &[u8],
2564    powered: bool,
2565    deadline: Instant,
2566    recovery: &Arc<Mutex<Option<Instant>>>,
2567    keys: Option<&[ControlKey]>,
2568    operation: impl FnOnce() -> Result<T, RoutingSessionError>,
2569) -> Result<T, RoutingSessionError> {
2570    if !powered {
2571        return operation();
2572    }
2573    let guard = RoutingPowerLease(super::adc3::Adc3PowerLease::new(
2574        device.fd,
2575        device.control_handle(),
2576    ));
2577    let lease = &guard.0;
2578    lease.set_routing_deadline(deadline);
2579    let result = (|| {
2580        let mut scopes = Vec::new();
2581        for (interface, (protocol, descriptors)) in
2582            routing_interfaces_unambiguous(raw, &device.claimed_interfaces)?
2583        {
2584            if protocol != 0x30 {
2585                continue;
2586            }
2587            let roots: Vec<_> = descriptors
2588                .iter()
2589                .filter(|d| d.len() >= 4 && matches!(d[2], 5 | 6))
2590                .map(|d| d[3])
2591                .filter(|id| {
2592                    keys.map_or(true, |keys| {
2593                        keys.iter().any(|key| match key {
2594                            ControlKey::Selector(entity)
2595                            | ControlKey::Crosspoint { entity, .. } => {
2596                                entity.interface == interface && entity.id == *id
2597                            }
2598                        })
2599                    })
2600                })
2601                .collect();
2602            let mut domains = Vec::new();
2603            for root in roots {
2604                match adc3_routing_scope_for(&descriptors, Some(root)) {
2605                    Ok((found, _)) => {
2606                        for domain in found {
2607                            if !domains.iter().any(
2608                                |existing: &crate::descriptors::uac3::PowerDomain| {
2609                                    existing.id == domain.id
2610                                },
2611                            ) {
2612                                domains.push(domain);
2613                            }
2614                        }
2615                    }
2616                    Err(error) if keys.is_some() => return Err(error),
2617                    Err(_) => continue,
2618                }
2619            }
2620            if domains.is_empty() {
2621                continue;
2622            }
2623            let streams = routing_power_interfaces(raw, &device.claimed_interfaces, interface)?;
2624            for stream in streams {
2625                lease
2626                    .verify_idle(stream)
2627                    .map_err(|e| RoutingSessionError::Session(Error::Control(e)))?;
2628            }
2629            scopes.push((interface, domains));
2630        }
2631        // Complete every scope/claim/idle proof before waking any domain.
2632        for (interface, domains) in scopes {
2633            for domain in domains {
2634                lease
2635                    .acquire(interface, &domain)
2636                    .map_err(|e| RoutingSessionError::Session(Error::Control(e)))?;
2637            }
2638        }
2639        operation()
2640    })();
2641    let recovery_deadline = *recovery
2642        .lock()
2643        .get_or_insert_with(|| Instant::now() + ROUTING_RECOVERY_BUDGET);
2644    lease.set_routing_deadline(recovery_deadline);
2645    finish_routing_power(result, lease.restore_checked())
2646}
2647
2648fn finish_routing_power<T>(
2649    operation: Result<T, RoutingSessionError>,
2650    restoration: Result<(), String>,
2651) -> Result<T, RoutingSessionError> {
2652    match restoration {
2653        Ok(()) => operation,
2654        Err(detail) => Err(RoutingSessionError::PowerRestore {
2655            operation: operation.err().map(Box::new),
2656            detail,
2657        }),
2658    }
2659}
2660
2661/// Query only already claimed AC functions. Sleeping/unknown domains are a
2662/// typed refusal: capability discovery never changes a device's power state.
2663fn routing_clusters(
2664    device: &UsbDevice,
2665    raw: &[u8],
2666    deadline: Instant,
2667    filter: Option<&[ControlKey]>,
2668) -> Result<(BTreeMap<(u8, u16), RoutingCluster>, Vec<RoutingDiagnostic>), RoutingSessionError> {
2669    routing_clusters_for(device, raw, deadline, filter, None)
2670}
2671
2672fn routing_clusters_for(
2673    device: &UsbDevice,
2674    raw: &[u8],
2675    deadline: Instant,
2676    filter: Option<&[ControlKey]>,
2677    only_interface: Option<u8>,
2678) -> Result<(BTreeMap<(u8, u16), RoutingCluster>, Vec<RoutingDiagnostic>), RoutingSessionError> {
2679    let interfaces = routing_interfaces_unambiguous(raw, &device.claimed_interfaces)?;
2680    let idle = IDLE_LOCK
2681        .try_lock_for(remaining(deadline)?)
2682        .ok_or_else(|| {
2683            RoutingSessionError::Session(Error::Control(
2684                "routing deadline waiting for idle owner".into(),
2685            ))
2686        })?;
2687    let idle = idle
2688        .as_ref()
2689        .filter(|i| i.device_fd == device.fd)
2690        .ok_or_else(|| {
2691            RoutingSessionError::Session(Error::InvalidState("routing lost idle owner".into()))
2692        })?;
2693    let mut clusters = BTreeMap::new();
2694    let mut diagnostics = Vec::new();
2695    for (interface, (protocol, descriptors)) in interfaces {
2696        if only_interface.is_some_and(|id| id != interface) {
2697            continue;
2698        }
2699        if protocol != 0x30 {
2700            continue;
2701        }
2702        let roots: Vec<_> = descriptors
2703            .iter()
2704            .filter(|d| d.len() >= 4 && matches!(d[2], 5 | 6))
2705            .map(|d| d[3])
2706            .collect();
2707        for root in roots {
2708            if filter.is_some_and(|keys| {
2709                !keys.iter().any(|key| match key {
2710                    ControlKey::Selector(entity) | ControlKey::Crosspoint { entity, .. } => {
2711                        entity.interface == interface && entity.id == root
2712                    }
2713                })
2714            }) {
2715                continue;
2716            }
2717            let result =
2718                (|| -> Result<BTreeMap<(u8, u16), RoutingCluster>, RoutingSessionError> {
2719                    let mut local = BTreeMap::new();
2720                    let (domains, affected) = adc3_routing_scope_for(&descriptors, Some(root))?;
2721                    // Prove D0 only for domains containing exposed units or their sources.
2722                    for id in domains.iter().map(|d| d.id) {
2723                        let mut state = [0xff];
2724                        let n = idle
2725                            .handle
2726                            .read_control(
2727                                0xa1,
2728                                1,
2729                                0x0200,
2730                                (u16::from(id) << 8) | u16::from(interface),
2731                                &mut state,
2732                                remaining(deadline)?,
2733                            )
2734                            .map_err(|e| {
2735                                RoutingSessionError::Session(Error::Control(e.to_string()))
2736                            })?;
2737                        if n != 1 || state[0] != 0 {
2738                            return Err(RoutingSessionError::UnsupportedTopology("ADC3 routing requires already-D0 entity domains; waking requires an owned power lease".into()));
2739                        }
2740                    }
2741                    for bytes in &descriptors {
2742                        if bytes.len() < 4 || !affected.contains(&bytes[3]) {
2743                            continue;
2744                        }
2745                        let id = match bytes.get(2) {
2746                            Some(2) => Some(
2747                                crate::descriptors::uac3::parse_input_terminal(bytes)
2748                                    .map_err(|e| {
2749                                        RoutingSessionError::UnsupportedTopology(e.to_string())
2750                                    })?
2751                                    .cluster_id,
2752                            ),
2753                            Some(5) => {
2754                                let pins = usize::from(*bytes.get(4).ok_or(
2755                                    RoutingSessionError::Invalid(InvalidRoute::MalformedDescriptor),
2756                                )?);
2757                                let pair = bytes.get(5 + pins..7 + pins).ok_or(
2758                                    RoutingSessionError::Invalid(InvalidRoute::MalformedDescriptor),
2759                                )?;
2760                                Some(u16::from_le_bytes([pair[0], pair[1]]))
2761                            }
2762                            _ => None,
2763                        };
2764                        if let Some(id) = id {
2765                            if let std::collections::btree_map::Entry::Vacant(e) =
2766                                local.entry((interface, id))
2767                            {
2768                                let cluster =
2769                                    query_routing_cluster(&idle.handle, interface, id, deadline)?;
2770                                e.insert(cluster);
2771                            }
2772                        }
2773                    }
2774                    Ok(local)
2775                })();
2776            match result {
2777                Ok(local) => clusters.extend(local),
2778                Err(error) => diagnostics.push(RoutingDiagnostic {
2779                    interface,
2780                    entity_id: Some(root),
2781                    detail: error.to_string(),
2782                }),
2783            }
2784        }
2785    }
2786    Ok((clusters, diagnostics))
2787}
2788
2789fn verify_descriptor_identity(
2790    snapshot: &RoutingSnapshot,
2791    device: &UsbDevice,
2792    deadline: Instant,
2793) -> Result<(), RoutingSessionError> {
2794    if !snapshot.device.same_owner(device) {
2795        return Err(RoutingSessionError::Drift(
2796            "routing snapshot belongs to another attachment".into(),
2797        ));
2798    }
2799    let (configuration, descriptors) = active_descriptors_until(device, Some(deadline))?;
2800    remaining(deadline)?;
2801    if configuration != snapshot.configuration || descriptors != snapshot.descriptors {
2802        return Err(RoutingSessionError::Drift(
2803            "configuration or descriptors changed; rediscover routing".into(),
2804        ));
2805    }
2806    Ok(())
2807}
2808fn selector_dependencies(
2809    snapshot: &RoutingSnapshot,
2810    key: ControlKey,
2811) -> Result<Vec<RouteChange>, RoutingSessionError> {
2812    let entity = match key {
2813        ControlKey::Selector(_) => return Ok(Vec::new()),
2814        ControlKey::Crosspoint { entity, .. } => entity,
2815    };
2816    let interfaces =
2817        routing_interfaces_unambiguous(&snapshot.descriptors, &snapshot.device.claimed_interfaces)?;
2818    let (protocol, descriptors) = interfaces
2819        .get(&entity.interface)
2820        .ok_or_else(|| RoutingSessionError::Drift("routing function disappeared".into()))?;
2821    let nodes: BTreeMap<_, _> = descriptors
2822        .iter()
2823        .filter(|d| d.len() >= 4 && d[2] != 1)
2824        .map(|d| (d[3], *d))
2825        .collect();
2826    let mut pending = vec![entity.id];
2827    let mut seen = std::collections::BTreeSet::new();
2828    let mut dependencies = Vec::new();
2829    while let Some(id) = pending.pop() {
2830        if !seen.insert(id) {
2831            continue;
2832        }
2833        let bytes = nodes
2834            .get(&id)
2835            .ok_or_else(|| RoutingSessionError::Drift("routing source unavailable".into()))?;
2836        let mixer = if *protocol == 0x30 { 5 } else { 4 };
2837        let selector = if *protocol == 0x30 { 6 } else { 5 };
2838        let feature = if *protocol == 0x30 { 7 } else { 6 };
2839        if bytes[2] == selector {
2840            let selector_key = ControlKey::Selector(routing::Entity {
2841                interface: entity.interface,
2842                id,
2843            });
2844            let expected = snapshot
2845                .selectors
2846                .iter()
2847                .find(|v| v.key == selector_key)
2848                .ok_or_else(|| {
2849                    RoutingSessionError::Drift(format!("selector {id} is unavailable"))
2850                })?;
2851            dependencies.push(*expected);
2852        }
2853        if bytes[2] == selector || bytes[2] == mixer {
2854            let count = usize::from(*bytes.get(4).ok_or(RoutingSessionError::Invalid(
2855                InvalidRoute::MalformedDescriptor,
2856            ))?);
2857            pending.extend_from_slice(bytes.get(5..5 + count).ok_or(
2858                RoutingSessionError::Invalid(InvalidRoute::MalformedDescriptor),
2859            )?);
2860        } else if bytes[2] == feature {
2861            pending.push(*bytes.get(4).ok_or(RoutingSessionError::Invalid(
2862                InvalidRoute::MalformedDescriptor,
2863            ))?);
2864        }
2865    }
2866    dependencies.sort_by_key(|v| v.key);
2867    Ok(dependencies)
2868}
2869
2870fn cluster_dependencies(
2871    snapshot: &RoutingSnapshot,
2872    key: ControlKey,
2873) -> Result<Vec<(u8, u16)>, RoutingSessionError> {
2874    let entity = match key {
2875        ControlKey::Selector(entity) | ControlKey::Crosspoint { entity, .. } => entity,
2876    };
2877    let interfaces =
2878        routing_interfaces_unambiguous(&snapshot.descriptors, &snapshot.device.claimed_interfaces)?;
2879    let Some((protocol, descriptors)) = interfaces.get(&entity.interface) else {
2880        return Err(RoutingSessionError::Drift(
2881            "routing function disappeared".into(),
2882        ));
2883    };
2884    if *protocol != 0x30 {
2885        return Ok(Vec::new());
2886    }
2887    let (_, affected) = adc3_routing_scope_for(descriptors, Some(entity.id))?;
2888    let mut ids = Vec::new();
2889    for bytes in descriptors
2890        .iter()
2891        .filter(|b| b.len() >= 4 && affected.contains(&b[3]))
2892    {
2893        let id = match bytes[2] {
2894            2 => Some(
2895                crate::descriptors::uac3::parse_input_terminal(bytes)
2896                    .map_err(|e| RoutingSessionError::UnsupportedTopology(e.to_string()))?
2897                    .cluster_id,
2898            ),
2899            5 => {
2900                let count = usize::from(*bytes.get(4).ok_or(RoutingSessionError::Invalid(
2901                    InvalidRoute::MalformedDescriptor,
2902                ))?);
2903                let pair = bytes
2904                    .get(5 + count..7 + count)
2905                    .ok_or(RoutingSessionError::Invalid(
2906                        InvalidRoute::MalformedDescriptor,
2907                    ))?;
2908                Some(u16::from_le_bytes([pair[0], pair[1]]))
2909            }
2910            _ => None,
2911        };
2912        if let Some(id) = id {
2913            ids.push((entity.interface, id));
2914        }
2915    }
2916    Ok(ids)
2917}
2918
2919// Compare the full captured HC content, not just the channel count used to
2920// establish address offsets. Both edits and hand-back use this same proof.
2921fn cluster_content_matches(
2922    current: &BTreeMap<(u8, u16), RoutingCluster>,
2923    saved: &BTreeMap<(u8, u16), RoutingCluster>,
2924    dependencies: &[(u8, u16)],
2925) -> bool {
2926    dependencies
2927        .iter()
2928        .all(|id| current.contains_key(id) && current.get(id) == saved.get(id))
2929}
2930
2931fn verify_snapshot(
2932    snapshot: &RoutingSnapshot,
2933    device: &UsbDevice,
2934    deadline: Instant,
2935    recovery: &Arc<Mutex<Option<Instant>>>,
2936    keys: &[ControlKey],
2937) -> Result<(), RoutingSessionError> {
2938    verify_descriptor_identity(snapshot, device, deadline)?;
2939    let (clusters, failures) =
2940        routing_clusters(device, &snapshot.descriptors, deadline, Some(keys))?;
2941    for &key in keys {
2942        let entity = match key {
2943            ControlKey::Selector(e) | ControlKey::Crosspoint { entity: e, .. } => e,
2944        };
2945        if failures.iter().any(|failure| {
2946            failure.interface == entity.interface
2947                && failure.entity_id.map_or(true, |id| id == entity.id)
2948        }) || !cluster_content_matches(
2949            &clusters,
2950            &snapshot.hc_clusters,
2951            &cluster_dependencies(snapshot, key)?,
2952        ) {
2953            return Err(RoutingSessionError::Drift(
2954                "ADC3 HC Clusters changed or unavailable for this control".into(),
2955            ));
2956        }
2957    }
2958    let mut io = UsbRoutingIo {
2959        deadline,
2960        recovery: recovery.clone(),
2961        device,
2962        descriptors: &snapshot.descriptors,
2963    };
2964    for &key in keys {
2965        let expected = selector_dependencies(snapshot, key)?;
2966        verify_values(&snapshot.inventory, &mut io, &expected)?;
2967    }
2968    Ok(())
2969}
2970
2971fn verify_values<I: RoutingIo<Error = String>>(
2972    inventory: &RoutingInventory,
2973    io: &mut I,
2974    expected: &[RouteChange],
2975) -> Result<(), RoutingSessionError> {
2976    for value in expected {
2977        let control = inventory
2978            .control(value.key)
2979            .map_err(RoutingSessionError::Invalid)?;
2980        let actual = control
2981            .read_current(io)
2982            .map_err(RoutingSessionError::Control)?;
2983        if actual != value.value {
2984            return Err(RoutingSessionError::Drift(format!(
2985                "control {:?} changed from {:?} to {:?}",
2986                value.key, value.value, actual
2987            )));
2988        }
2989    }
2990    Ok(())
2991}
2992
2993struct DiscoveredFunction {
2994    inventory: RoutingInventory,
2995    clusters: BTreeMap<(u8, u16), RoutingCluster>,
2996    selectors: Vec<RouteChange>,
2997    diagnostics: Vec<RoutingDiagnostic>,
2998}
2999
3000fn collect_discovery_function(
3001    device: &UsbDevice,
3002    raw: &[u8],
3003    interface: u8,
3004    deadline: Instant,
3005    recovery: &Arc<Mutex<Option<Instant>>>,
3006) -> Result<DiscoveredFunction, RoutingSessionError> {
3007    let (clusters, mut diagnostics) =
3008        routing_clusters_for(device, raw, deadline, None, Some(interface))?;
3009    let (inventory, unit_diagnostics) =
3010        inventory_partial_for(raw, &device.claimed_interfaces, &clusters, Some(interface))?;
3011    diagnostics.extend(unit_diagnostics);
3012    let mut selectors = Vec::new();
3013    let mut io = UsbRoutingIo {
3014        deadline,
3015        recovery: recovery.clone(),
3016        device,
3017        descriptors: raw,
3018    };
3019    for unit in inventory.units() {
3020        if let RoutingUnit::Selector(selector) = unit {
3021            if selector.access() != Access::Absent {
3022                let key = ControlKey::Selector(selector.entity());
3023                match inventory
3024                    .control(key)
3025                    .map_err(RoutingSessionError::Invalid)?
3026                    .read_current(&mut io)
3027                {
3028                    Ok(value) => selectors.push(RouteChange { key, value }),
3029                    Err(error) => diagnostics.push(RoutingDiagnostic {
3030                        interface,
3031                        entity_id: Some(selector.entity().id),
3032                        detail: format!("selector CUR unavailable: {error:?}"),
3033                    }),
3034                }
3035            }
3036        }
3037    }
3038    Ok(DiscoveredFunction {
3039        inventory,
3040        clusters,
3041        selectors,
3042        diagnostics,
3043    })
3044}
3045
3046// The runner never invokes a later function after an uncertain hand-back.
3047fn discovery_scopes<T>(
3048    interfaces: impl IntoIterator<Item = u8>,
3049    mut run: impl FnMut(u8) -> Result<T, RoutingSessionError>,
3050) -> Result<(Vec<T>, Vec<RoutingDiagnostic>), RoutingSessionError> {
3051    let mut completed = Vec::new();
3052    let mut diagnostics = Vec::new();
3053    for interface in interfaces {
3054        match run(interface) {
3055            Ok(value) => completed.push(value),
3056            Err(error @ RoutingSessionError::PowerRestore { .. })
3057            | Err(error @ RoutingSessionError::Drift(_))
3058            | Err(error @ RoutingSessionError::Session(Error::DeviceLost)) => return Err(error),
3059            Err(error) => diagnostics.push(RoutingDiagnostic {
3060                interface,
3061                entity_id: None,
3062                detail: error.to_string(),
3063            }),
3064        }
3065    }
3066    Ok((completed, diagnostics))
3067}
3068
3069fn discover_powered_functions(
3070    device: &UsbDevice,
3071    raw: &[u8],
3072    deadline: Instant,
3073    recovery_deadline: Instant,
3074) -> Result<DiscoveredFunction, RoutingSessionError> {
3075    let (interfaces, mut diagnostics) =
3076        routing_interfaces_with_diagnostics(raw, &device.claimed_interfaces)?;
3077    let recovery = Arc::new(Mutex::new(Some(recovery_deadline)));
3078    let (completed, scope_diagnostics) =
3079        discovery_scopes(interfaces.keys().copied(), |interface| {
3080            remaining(deadline)?;
3081            let (protocol, descriptors) = interfaces
3082                .get(&interface)
3083                .expect("scope indexed under lock");
3084            let collect =
3085                || collect_discovery_function(device, raw, interface, deadline, &recovery);
3086            let result = if *protocol != 0x30 {
3087                collect()
3088            } else {
3089                // Prove all function ownership and domain membership before waking.
3090                let streams = routing_power_interfaces(raw, &device.claimed_interfaces, interface)?;
3091                let mut domains = BTreeMap::new();
3092                for root in descriptors
3093                    .iter()
3094                    .filter(|d| d.len() >= 4 && matches!(d[2], 5 | 6))
3095                    .map(|d| d[3])
3096                {
3097                    let (found, _) = adc3_routing_scope_for(descriptors, Some(root))?;
3098                    for domain in found {
3099                        domains.insert(domain.id, domain);
3100                    }
3101                }
3102                let guard = RoutingPowerLease(super::adc3::Adc3PowerLease::new(
3103                    device.fd,
3104                    device.control_handle(),
3105                ));
3106                guard.0.set_routing_deadline(deadline);
3107                let operation = (|| {
3108                    for stream in streams {
3109                        guard
3110                            .0
3111                            .verify_idle(stream)
3112                            .map_err(|e| RoutingSessionError::Session(Error::Control(e)))?;
3113                    }
3114                    for domain in domains.values() {
3115                        guard
3116                            .0
3117                            .acquire(interface, domain)
3118                            .map_err(|e| RoutingSessionError::Session(Error::Control(e)))?;
3119                    }
3120                    collect()
3121                })();
3122                guard.0.set_routing_deadline(recovery_deadline);
3123                finish_routing_power(operation, guard.0.restore_checked())
3124            };
3125            if matches!(&result, Err(RoutingSessionError::PowerRestore { .. })) {
3126                return result;
3127            }
3128            // A recoverable local failure is only isolated while this remains the
3129            // same attachment and configuration. Expiry prevents further USB I/O.
3130            if remaining(deadline).is_ok() {
3131                let (number, observed) =
3132                    active_descriptors_until(device, Some(deadline)).map_err(|error| {
3133                        RoutingSessionError::Drift(format!(
3134                            "cannot reprove attachment after powered discovery scope: {error}"
3135                        ))
3136                    })?;
3137                if observed != raw || number != raw[5] {
3138                    return Err(RoutingSessionError::Drift(
3139                        "attachment or configuration changed during powered discovery".into(),
3140                    ));
3141                }
3142            }
3143            result
3144        })?;
3145    diagnostics.extend(scope_diagnostics);
3146    let mut inventory = RoutingInventory::default();
3147    let mut clusters = BTreeMap::new();
3148    let mut selectors = Vec::new();
3149    for function in completed {
3150        for unit in function.inventory.units() {
3151            inventory
3152                .insert(unit.clone())
3153                .map_err(RoutingSessionError::Invalid)?;
3154        }
3155        for (key, cluster) in function.clusters {
3156            if clusters.insert(key, cluster).is_some() {
3157                return Err(RoutingSessionError::Invalid(InvalidRoute::DuplicateEntity));
3158            }
3159        }
3160        selectors.extend(function.selectors);
3161        diagnostics.extend(function.diagnostics);
3162    }
3163    Ok(DiscoveredFunction {
3164        inventory,
3165        clusters,
3166        selectors,
3167        diagnostics,
3168    })
3169}
3170
3171pub(crate) fn discover() -> Result<RoutingSnapshot, RoutingSessionError> {
3172    discover_with_power(false)
3173}
3174pub(crate) fn discover_with_power(powered: bool) -> Result<RoutingSnapshot, RoutingSessionError> {
3175    let deadline = Instant::now() + ROUTING_OPERATION_BUDGET;
3176    let recovery = Arc::new(Mutex::new(None));
3177    let _gate = USB_SESSION_GATE
3178        .try_lock_for(remaining(deadline)?)
3179        .ok_or_else(|| {
3180            RoutingSessionError::Session(Error::Control(
3181                "routing deadline waiting for session gate".into(),
3182            ))
3183        })?;
3184    let _controls = HARDWARE_VOLUME_MUTEX
3185        .try_lock_for(remaining(deadline)?)
3186        .ok_or_else(|| {
3187            RoutingSessionError::Session(Error::Control(
3188                "routing deadline waiting for control gate".into(),
3189            ))
3190        })?;
3191    let device = idle_device_until(Some(deadline))?;
3192    let (configuration, descriptors) = active_descriptors_until(&device, Some(deadline))?;
3193    if powered {
3194        let recovery_deadline = deadline
3195            .checked_add(ROUTING_RECOVERY_BUDGET)
3196            .ok_or_else(|| {
3197                RoutingSessionError::Session(Error::Control(
3198                    "routing recovery deadline overflow".into(),
3199                ))
3200            })?;
3201        let result =
3202            discover_powered_functions(&device, &descriptors, deadline, recovery_deadline)?;
3203        return Ok(RoutingSnapshot {
3204            device,
3205            configuration,
3206            descriptors,
3207            inventory: result.inventory,
3208            selectors: result.selectors,
3209            hc_clusters: result.clusters,
3210            diagnostics: result.diagnostics,
3211            hand_back_report: context::current().routing_report.clone(),
3212        });
3213    }
3214    with_routing_power(
3215        &device,
3216        &descriptors,
3217        powered,
3218        deadline,
3219        &recovery,
3220        None,
3221        || {
3222            let (_, mut diagnostics) =
3223                routing_interfaces_with_diagnostics(&descriptors, &device.claimed_interfaces)?;
3224            let (hc_clusters, cluster_diagnostics) =
3225                routing_clusters(&device, &descriptors, deadline, None)?;
3226            diagnostics.extend(cluster_diagnostics);
3227            let (inventory, inventory_diagnostics) =
3228                inventory_partial(&descriptors, &device.claimed_interfaces, &hc_clusters)?;
3229            diagnostics.extend(inventory_diagnostics);
3230            let mut selectors = Vec::new();
3231            let mut io = UsbRoutingIo {
3232                deadline,
3233                recovery: recovery.clone(),
3234                device: &device,
3235                descriptors: &descriptors,
3236            };
3237            for unit in inventory.units() {
3238                if let RoutingUnit::Selector(selector) = unit {
3239                    if selector.access() != Access::Absent {
3240                        let key = ControlKey::Selector(selector.entity());
3241                        match inventory
3242                            .control(key)
3243                            .map_err(RoutingSessionError::Invalid)?
3244                            .read_current(&mut io)
3245                        {
3246                            Ok(value) => selectors.push(RouteChange { key, value }),
3247                            Err(error) => diagnostics.push(RoutingDiagnostic {
3248                                interface: selector.entity().interface,
3249                                entity_id: Some(selector.entity().id),
3250                                detail: format!("selector CUR unavailable: {error:?}"),
3251                            }),
3252                        }
3253                    }
3254                }
3255            }
3256            Ok(RoutingSnapshot {
3257                device: device.clone(),
3258                configuration,
3259                descriptors: descriptors.clone(),
3260                inventory,
3261                selectors,
3262                hc_clusters,
3263                diagnostics,
3264                hand_back_report: context::current().routing_report.clone(),
3265            })
3266        },
3267    )
3268}
3269
3270pub(crate) fn read(
3271    snapshot: &RoutingSnapshot,
3272    key: ControlKey,
3273) -> Result<RouteValue, RoutingSessionError> {
3274    read_with_power(snapshot, key, false)
3275}
3276pub(crate) fn read_with_power(
3277    snapshot: &RoutingSnapshot,
3278    key: ControlKey,
3279    powered: bool,
3280) -> Result<RouteValue, RoutingSessionError> {
3281    let deadline = Instant::now() + ROUTING_OPERATION_BUDGET;
3282    let recovery = Arc::new(Mutex::new(None));
3283    let _gate = USB_SESSION_GATE
3284        .try_lock_for(remaining(deadline)?)
3285        .ok_or_else(|| {
3286            RoutingSessionError::Session(Error::Control(
3287                "routing deadline waiting for session gate".into(),
3288            ))
3289        })?;
3290    let _controls = HARDWARE_VOLUME_MUTEX
3291        .try_lock_for(remaining(deadline)?)
3292        .ok_or_else(|| {
3293            RoutingSessionError::Session(Error::Control(
3294                "routing deadline waiting for control gate".into(),
3295            ))
3296        })?;
3297    let device = idle_device_until(Some(deadline))?;
3298    verify_descriptor_identity(snapshot, &device, deadline)?;
3299    with_routing_power(
3300        &device,
3301        &snapshot.descriptors,
3302        powered,
3303        deadline,
3304        &recovery,
3305        Some(&[key]),
3306        || {
3307            verify_snapshot(snapshot, &device, deadline, &recovery, &[key])?;
3308            snapshot
3309                .inventory
3310                .control(key)
3311                .map_err(RoutingSessionError::Invalid)?
3312                .read_current(&mut UsbRoutingIo {
3313                    deadline,
3314                    recovery: recovery.clone(),
3315                    device: &device,
3316                    descriptors: &snapshot.descriptors,
3317                })
3318                .map_err(RoutingSessionError::Control)
3319        },
3320    )
3321}
3322
3323#[derive(Debug)]
3324pub(super) struct RecordedRouting {
3325    snapshot: RoutingSnapshot,
3326    // The first actual pre-write CUR and bounded current ownership evidence.
3327    values: BTreeMap<ControlKey, RecordedRoute>,
3328    powered: bool,
3329}
3330#[derive(Debug)]
3331struct RecordedRoute {
3332    original: RouteValue,
3333    ownership: Ownership,
3334    selectors: Vec<RouteChange>,
3335    forfeited: bool,
3336}
3337
3338#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3339enum Ownership {
3340    None,
3341    Verified(RouteValue),
3342    Uncertain {
3343        previous: Option<RouteValue>,
3344        target: RouteValue,
3345    },
3346}
3347impl Ownership {
3348    fn owns(self, value: RouteValue) -> bool {
3349        match self {
3350            Self::None => false,
3351            Self::Verified(current) => current == value,
3352            Self::Uncertain { previous, target } => previous == Some(value) || target == value,
3353        }
3354    }
3355}
3356impl RecordedRoute {
3357    fn record_attempt(
3358        &mut self,
3359        before: RouteValue,
3360        target: RouteValue,
3361        success: bool,
3362        rollback_failed: bool,
3363    ) {
3364        let prior_owned = before == self.original || self.ownership.owns(before);
3365        if !prior_owned {
3366            self.forfeited = true;
3367        }
3368        self.ownership = if self.forfeited {
3369            Ownership::None
3370        } else if success {
3371            Ownership::Verified(target)
3372        } else if rollback_failed {
3373            Ownership::Uncertain {
3374                previous: prior_owned.then_some(before),
3375                target,
3376            }
3377        } else {
3378            Ownership::Verified(before)
3379        };
3380    }
3381}
3382
3383static ORIGINAL_ROUTING: context::ScopedMutex<Option<RecordedRouting>> =
3384    context::ScopedMutex::new(|context| context.routing.clone());
3385
3386pub(crate) fn apply(
3387    snapshot: &RoutingSnapshot,
3388    edits: &[RouteEdit],
3389) -> Result<RouteReport, RoutingSessionError> {
3390    apply_with_power(snapshot, edits, false)
3391}
3392pub(crate) fn apply_with_power(
3393    snapshot: &RoutingSnapshot,
3394    edits: &[RouteEdit],
3395    powered: bool,
3396) -> Result<RouteReport, RoutingSessionError> {
3397    let deadline = Instant::now() + ROUTING_OPERATION_BUDGET;
3398    let recovery = Arc::new(Mutex::new(None));
3399    let _gate = USB_SESSION_GATE
3400        .try_lock_for(remaining(deadline)?)
3401        .ok_or_else(|| {
3402            RoutingSessionError::Session(Error::Control(
3403                "routing deadline waiting for session gate".into(),
3404            ))
3405        })?;
3406    let _controls = HARDWARE_VOLUME_MUTEX
3407        .try_lock_for(remaining(deadline)?)
3408        .ok_or_else(|| {
3409            RoutingSessionError::Session(Error::Control(
3410                "routing deadline waiting for control gate".into(),
3411            ))
3412        })?;
3413    let device = idle_device_until(Some(deadline))?;
3414    verify_descriptor_identity(snapshot, &device, deadline)?;
3415    with_routing_power(
3416        &device,
3417        &snapshot.descriptors,
3418        powered,
3419        deadline,
3420        &recovery,
3421        Some(&edits.iter().map(|edit| edit.key).collect::<Vec<_>>()),
3422        || {
3423            verify_snapshot(
3424                snapshot,
3425                &device,
3426                deadline,
3427                &recovery,
3428                &edits.iter().map(|edit| edit.key).collect::<Vec<_>>(),
3429            )?;
3430            if edits.len() > MAX_ROUTE_CHANGES {
3431                return Err(RoutingSessionError::Invalid(InvalidRoute::TooManyChanges));
3432            }
3433            let mut originals = ORIGINAL_ROUTING.lock();
3434            if originals.as_ref().is_some_and(|prior| {
3435                prior.snapshot.configuration != snapshot.configuration
3436                    || prior.snapshot.descriptors != snapshot.descriptors
3437            }) {
3438                return Err(RoutingSessionError::Drift(
3439                    "configuration changed since the first routing edit".into(),
3440                ));
3441            }
3442            if originals
3443                .as_ref()
3444                .is_some_and(|prior| !prior.snapshot.device.same_owner(&device))
3445            {
3446                return Err(RoutingSessionError::Drift(
3447                    "routing restoration record belongs to another attachment".into(),
3448                ));
3449            }
3450            let old_count = originals.as_ref().map_or(0, |prior| prior.values.len());
3451            let new_count = edits
3452                .iter()
3453                .map(|edit| edit.key)
3454                .collect::<std::collections::BTreeSet<_>>()
3455                .iter()
3456                .filter(|key| {
3457                    !originals
3458                        .as_ref()
3459                        .is_some_and(|r| r.values.contains_key(*key))
3460                })
3461                .count();
3462            if old_count + new_count > MAX_RECORDED_ROUTES {
3463                return Err(RoutingSessionError::Invalid(InvalidRoute::TooManyChanges));
3464            }
3465            if let Some(prior) = originals.as_ref() {
3466                for edit in edits {
3467                    if matches!(edit.key, ControlKey::Crosspoint { .. })
3468                        && prior.values.get(&edit.key).is_some_and(|entry| {
3469                            entry.selectors
3470                                != selector_dependencies(snapshot, edit.key).unwrap_or_default()
3471                        })
3472                    {
3473                        return Err(RoutingSessionError::Drift(
3474                            "mixer mapping changed since its first edit".into(),
3475                        ));
3476                    }
3477                }
3478            }
3479            let expected = edits
3480                .iter()
3481                .map(|e| RouteChange {
3482                    key: e.key,
3483                    value: e.expected,
3484                })
3485                .collect::<Vec<_>>();
3486            let changes = edits
3487                .iter()
3488                .map(|e| RouteChange {
3489                    key: e.key,
3490                    value: e.value,
3491                })
3492                .collect::<Vec<_>>();
3493            let mut io = UsbRoutingIo {
3494                deadline,
3495                recovery: recovery.clone(),
3496                device: &device,
3497                descriptors: &snapshot.descriptors,
3498            };
3499            verify_values(&snapshot.inventory, &mut io, &expected)?;
3500            if let Some(recorded) = originals.as_mut() {
3501                for edit in edits {
3502                    if let Some(entry) = recorded.values.get_mut(&edit.key) {
3503                        if edit.expected != entry.original && !entry.ownership.owns(edit.expected) {
3504                            entry.forfeited = true;
3505                            entry.ownership = Ownership::None;
3506                        }
3507                    }
3508                }
3509            }
3510            let mut attempted = Vec::new();
3511            let result = routing::apply_routes_traced(
3512                &snapshot.inventory,
3513                &mut io,
3514                &changes,
3515                &mut attempted,
3516            );
3517            for (key, before, target) in attempted {
3518                let rollback_failed = match &result {
3519                    Ok(_) => false,
3520                    Err(failure) => failure
3521                        .rollback_failures
3522                        .iter()
3523                        .any(|(failed, _)| *failed == key),
3524                };
3525                let success = result.is_ok();
3526                // A new, fully rolled-back edit creates no outstanding ownership.
3527                if !success
3528                    && !rollback_failed
3529                    && !originals
3530                        .as_ref()
3531                        .is_some_and(|r| r.values.contains_key(&key))
3532                {
3533                    continue;
3534                }
3535                let recorded = originals.get_or_insert_with(|| RecordedRouting {
3536                    snapshot: snapshot.clone(),
3537                    values: BTreeMap::new(),
3538                    powered,
3539                });
3540                recorded.powered |= powered;
3541                let dependencies = selector_dependencies(snapshot, key)?;
3542                let entry = recorded.values.entry(key).or_insert_with(|| RecordedRoute {
3543                    original: before,
3544                    ownership: Ownership::None,
3545                    selectors: dependencies,
3546                    forfeited: false,
3547                });
3548                entry.record_attempt(before, target, success, rollback_failed);
3549            }
3550            match result {
3551                Ok(report) => {
3552                    if !report.changed.is_empty() {
3553                        invalidate_route_caches();
3554                    }
3555                    Ok(report)
3556                }
3557                Err(failure) => {
3558                    if !failure.rollback_failures.is_empty() {
3559                        invalidate_route_caches();
3560                    }
3561                    Err(RoutingSessionError::Transaction(failure))
3562                }
3563            }
3564        },
3565    )
3566}
3567
3568fn invalidate_route_caches() {
3569    // Do not let the previous route's Feature Unit masquerade as protection for
3570    // a new selector path. Original volume records and actual device levels
3571    // remain intact; normal negotiation rediscovers and admits the new route.
3572    install_volume_control(None);
3573    set_hardware_volume_error(Some(
3574        "routing changed; negotiate to rediscover the playback volume route".into(),
3575    ));
3576    if let Some(state) = SESSION_STATE.lock().as_mut() {
3577        state.playback_format = None;
3578        state.requested_playback_format = None;
3579        state.clock_verification_passed = false;
3580    }
3581}
3582
3583/// Caller holds USB_SESSION_GATE and HARDWARE_VOLUME_MUTEX. Restore only when
3584/// configured HandBack requests it, attachment/configuration still match and
3585/// edited controls still contain the last library-written values. A volume-only
3586/// close override never changes this policy. Always retire the record on close.
3587pub(super) fn finish_routing_hand_back() {
3588    finish_scarlett_hand_back();
3589    let Some(record) = ORIGINAL_ROUTING.lock().take() else {
3590        return;
3591    };
3592    let sink = record.snapshot.hand_back_report.clone();
3593    let mut report = RoutingHandBackReport {
3594        controls: Vec::new(),
3595    };
3596    let fail_all = |report: &mut RoutingHandBackReport, reason: String| {
3597        report.controls = record
3598            .values
3599            .keys()
3600            .map(|&key| {
3601                (
3602                    key,
3603                    RoutingHandBackOutcome::IdentityOrTopologyChanged(reason.clone()),
3604                )
3605            })
3606            .collect();
3607    };
3608    if settings().config.hand_back != crate::HandBack::RestoreOriginal {
3609        report.controls = record
3610            .values
3611            .keys()
3612            .map(|&key| (key, RoutingHandBackOutcome::Disabled))
3613            .collect();
3614        *sink.lock() = Some(report);
3615        return;
3616    }
3617    let Some(device) = SESSION_STATE.lock().as_ref().map(|s| s.device.clone()) else {
3618        fail_all(&mut report, "attachment detached".into());
3619        *sink.lock() = Some(report);
3620        return;
3621    };
3622    let deadline = Instant::now() + ROUTING_RECOVERY_BUDGET;
3623    let recovery = Arc::new(Mutex::new(Some(deadline)));
3624    let mut restore = || -> Result<RoutingHandBackReport, RoutingSessionError> {
3625        if !record.snapshot.device.same_owner(&device) {
3626            return Err(RoutingSessionError::Drift(
3627                "attachment changed before routing hand-back".into(),
3628            ));
3629        }
3630        let (number, raw) = active_descriptors_until(&device, Some(deadline))?;
3631        if number != record.snapshot.configuration || raw != record.snapshot.descriptors {
3632            return Err(RoutingSessionError::Drift(
3633                "configuration changed before routing hand-back".into(),
3634            ));
3635        }
3636        with_routing_power(
3637            &device,
3638            &raw,
3639            record.powered,
3640            deadline,
3641            &recovery,
3642            Some(&record.values.keys().copied().collect::<Vec<_>>()),
3643            || {
3644                let cluster_result = routing_clusters(
3645                    &device,
3646                    &raw,
3647                    deadline,
3648                    Some(&record.values.keys().copied().collect::<Vec<_>>()),
3649                );
3650                let mut io = UsbRoutingIo {
3651                    deadline,
3652                    recovery: recovery.clone(),
3653                    device: &device,
3654                    descriptors: &record.snapshot.descriptors,
3655                };
3656                let mut entries: Vec<_> = record.values.iter().collect();
3657                // Selectors are independent addressable controls; mixer mappings must
3658                // be checked against the selector state at their own first edit.
3659                entries.sort_by_key(|(key, _)| matches!(key, ControlKey::Selector(_)));
3660                let mut controls = Vec::with_capacity(entries.len());
3661                let mut restored_selectors = std::collections::BTreeSet::new();
3662                let mut deferred = Vec::new();
3663                for (&key, saved) in entries {
3664                    let entity = match key {
3665                        ControlKey::Selector(e) | ControlKey::Crosspoint { entity: e, .. } => e,
3666                    };
3667                    let clusters_ok = cluster_result.as_ref().is_ok_and(|(clusters, failures)| {
3668                        !failures.iter().any(|failure| {
3669                            failure.interface == entity.interface
3670                                && failure.entity_id.map_or(true, |id| id == entity.id)
3671                        }) && cluster_dependencies(&record.snapshot, key).is_ok_and(|ids| {
3672                            cluster_content_matches(clusters, &record.snapshot.hc_clusters, &ids)
3673                        })
3674                    });
3675                    let mut outcome = if remaining(deadline).is_err() {
3676                        RoutingHandBackOutcome::DeadlineExpired
3677                    } else if matches!(key, ControlKey::Crosspoint { .. })
3678                        && (!clusters_ok
3679                            || verify_values(&record.snapshot.inventory, &mut io, &saved.selectors)
3680                                .is_err())
3681                    {
3682                        RoutingHandBackOutcome::IdentityOrTopologyChanged(
3683                            "selector or cluster mapping changed or unreadable".into(),
3684                        )
3685                    } else {
3686                        restore_recorded_control(&record.snapshot.inventory, &mut io, key, saved)
3687                    };
3688                    if remaining(deadline).is_err()
3689                        && matches!(
3690                            outcome,
3691                            RoutingHandBackOutcome::Unreadable(_)
3692                                | RoutingHandBackOutcome::RestoreUncertain(_)
3693                        )
3694                    {
3695                        outcome = RoutingHandBackOutcome::DeadlineExpired;
3696                    }
3697                    if matches!(key, ControlKey::Crosspoint { .. })
3698                        && matches!(
3699                            outcome,
3700                            RoutingHandBackOutcome::IdentityOrTopologyChanged(_)
3701                        )
3702                        && clusters_ok
3703                    {
3704                        deferred.push((controls.len(), key, saved));
3705                    }
3706                    if matches!(key, ControlKey::Selector(_))
3707                        && outcome == RoutingHandBackOutcome::Restored
3708                    {
3709                        restored_selectors.insert(key);
3710                    }
3711                    controls.push((key, outcome));
3712                }
3713                for (index, key, saved) in deferred {
3714                    if remaining(deadline).is_err() {
3715                        controls[index].1 = RoutingHandBackOutcome::DeadlineExpired;
3716                        continue;
3717                    }
3718                    if saved
3719                        .selectors
3720                        .iter()
3721                        .any(|dependency| restored_selectors.contains(&dependency.key))
3722                        && verify_values(&record.snapshot.inventory, &mut io, &saved.selectors)
3723                            .is_ok()
3724                    {
3725                        controls[index].1 = restore_recorded_control(
3726                            &record.snapshot.inventory,
3727                            &mut io,
3728                            key,
3729                            saved,
3730                        );
3731                    }
3732                }
3733                report = RoutingHandBackReport {
3734                    controls: controls.clone(),
3735                };
3736                Ok(RoutingHandBackReport { controls })
3737            },
3738        )
3739    };
3740    match restore() {
3741        Ok(result) => report = result,
3742        Err(error) if report.controls.is_empty() => fail_all(&mut report, error.to_string()),
3743        Err(error) => {
3744            for (_, outcome) in &mut report.controls {
3745                if *outcome == RoutingHandBackOutcome::Restored {
3746                    *outcome = RoutingHandBackOutcome::RestoreUncertain(error.to_string());
3747                }
3748            }
3749        }
3750    }
3751    *sink.lock() = Some(report);
3752}
3753
3754fn restore_recorded_control<I: RoutingIo>(
3755    inventory: &RoutingInventory,
3756    io: &mut I,
3757    key: ControlKey,
3758    saved: &RecordedRoute,
3759) -> RoutingHandBackOutcome
3760where
3761    I::Error: std::fmt::Debug,
3762{
3763    let control = match inventory.control(key) {
3764        Ok(control) => control,
3765        Err(error) => {
3766            return RoutingHandBackOutcome::IdentityOrTopologyChanged(format!("{error:?}"))
3767        }
3768    };
3769    let current = match control.read_current(io) {
3770        Ok(value) => value,
3771        Err(error) => return RoutingHandBackOutcome::Unreadable(format!("{error:?}")),
3772    };
3773    if current == saved.original {
3774        return RoutingHandBackOutcome::AlreadyOriginal;
3775    }
3776    if saved.forfeited || !saved.ownership.owns(current) {
3777        return RoutingHandBackOutcome::ExternallyChanged;
3778    }
3779    match routing::write_verified(io, control, saved.original) {
3780        Ok(()) => RoutingHandBackOutcome::Restored,
3781        Err(error) => RoutingHandBackOutcome::RestoreUncertain(format!("{error:?}")),
3782    }
3783}
3784
3785#[cfg(test)]
3786mod tests {
3787    use super::*;
3788    use crate::routing::Entity;
3789
3790    #[test]
3791    fn shared_release_refuses_vendor_reads_before_usb_session_access() {
3792        const _: () = assert!(!VENDOR_ROUTING_RELEASED);
3793        assert!(matches!(
3794            require_vendor_routing_release(),
3795            Err(RoutingSessionError::UnsupportedTopology(_))
3796        ));
3797        assert!(scarlett_discover().unwrap().is_none());
3798        // A deliberately invalid fd proves Android/native preflight does not
3799        // wrap or inspect a device before refusing the unpublished capability.
3800        let info = crate::DeviceInfo::new(0x1235, 0x8211, "Scarlett");
3801        assert!(scarlett_preflight(-1, &info).unwrap().is_none());
3802        assert!(matches!(
3803            scarlett_read(),
3804            Err(RoutingSessionError::UnsupportedTopology(_))
3805        ));
3806        assert!(matches!(
3807            fcp_read(),
3808            Err(RoutingSessionError::UnsupportedTopology(_))
3809        ));
3810        assert!(matches!(
3811            scarlett_gen1_read(),
3812            Err(RoutingSessionError::UnsupportedTopology(_))
3813        ));
3814        assert!(matches!(
3815            scarlett_mux_read(),
3816            Err(RoutingSessionError::UnsupportedTopology(_))
3817        ));
3818    }
3819
3820    #[test]
3821    fn discovery_scope_runner_continues_only_after_checked_recovery() {
3822        let mut events = Vec::new();
3823        let (scopes, diagnostics) = discovery_scopes([1, 2, 3], |id| {
3824            events.push(format!("wake:{id}"));
3825            events.push(format!("restore:{id}"));
3826            if id == 2 {
3827                finish_routing_power(
3828                    Err(RoutingSessionError::Session(Error::Control(
3829                        "wake failed".into(),
3830                    ))),
3831                    Ok(()),
3832                )
3833            } else {
3834                finish_routing_power(Ok(id), Ok(()))
3835            }
3836        })
3837        .unwrap();
3838        assert_eq!(scopes, vec![1, 3]);
3839        assert_eq!(diagnostics.len(), 1);
3840        assert_eq!(
3841            events,
3842            [
3843                "wake:1",
3844                "restore:1",
3845                "wake:2",
3846                "restore:2",
3847                "wake:3",
3848                "restore:3"
3849            ]
3850        );
3851        let mut attempted = Vec::new();
3852        let error = discovery_scopes([1, 2], |id| -> Result<(), RoutingSessionError> {
3853            attempted.push(id);
3854            finish_routing_power(
3855                Err(RoutingSessionError::Session(Error::Control(
3856                    "wake failed".into(),
3857                ))),
3858                Err("unreadable".into()),
3859            )
3860        })
3861        .unwrap_err();
3862        assert!(matches!(error, RoutingSessionError::PowerRestore { .. }));
3863        assert_eq!(attempted, [1]);
3864    }
3865
3866    #[test]
3867    fn routing_power_hand_back_preserves_transaction_and_rollback_failures() {
3868        let key = ControlKey::Selector(Entity {
3869            interface: 3,
3870            id: 8,
3871        });
3872        let operation = Err::<(), _>(RoutingSessionError::Transaction(TransactionError {
3873            failed_change: Some(2),
3874            cause: RoutingError::Io("write".into()),
3875            rollback_failures: vec![(key, RoutingError::Io("route restore".into()))],
3876        }));
3877        let error = finish_routing_power(operation, Err("power restore".into())).unwrap_err();
3878        let RoutingSessionError::PowerRestore {
3879            operation: Some(operation),
3880            detail,
3881        } = error
3882        else {
3883            panic!("expected both routing and power failures");
3884        };
3885        assert_eq!(detail, "power restore");
3886        let RoutingSessionError::Transaction(transaction) = *operation else {
3887            panic!("expected the original typed transaction");
3888        };
3889        assert_eq!(transaction.failed_change, Some(2));
3890        assert_eq!(transaction.cause, RoutingError::Io("write".into()));
3891        assert_eq!(
3892            transaction.rollback_failures,
3893            vec![(key, RoutingError::Io("route restore".into()))]
3894        );
3895    }
3896
3897    #[test]
3898    fn routing_power_hand_back_keeps_single_failures_and_success_distinct() {
3899        assert_eq!(finish_routing_power(Ok(7), Ok(())).unwrap(), 7);
3900        assert!(matches!(finish_routing_power::<()>(
3901            Err(RoutingSessionError::Drift("changed".into())), Ok(())),
3902            Err(RoutingSessionError::Drift(detail)) if detail == "changed"));
3903        assert!(
3904            matches!(finish_routing_power(Ok(()), Err("power restore".into())),
3905            Err(RoutingSessionError::PowerRestore { operation: None, detail })
3906                if detail == "power restore")
3907        );
3908    }
3909
3910    fn terminal(id: u8, channels: u8, locations: u32) -> Vec<u8> {
3911        let mut bytes = vec![17, 0x24, 2, id, 1, 1, 0, 10, channels];
3912        bytes.extend(locations.to_le_bytes());
3913        bytes.extend([0, 0, 0, 0]);
3914        bytes
3915    }
3916
3917    fn configuration(entities: &[Vec<u8>], protocol: u8) -> Vec<u8> {
3918        let ac_length = 9 + entities.iter().map(Vec::len).sum::<usize>();
3919        let total = 18 + ac_length;
3920        let mut raw = vec![9, 2, total as u8, (total >> 8) as u8, 1, 1, 0, 0x80, 50];
3921        raw.extend([9, 4, 3, 0, 0, 1, 1, protocol, 0]);
3922        raw.extend([
3923            9,
3924            0x24,
3925            1,
3926            0,
3927            2,
3928            1,
3929            ac_length as u8,
3930            (ac_length >> 8) as u8,
3931            0,
3932        ]);
3933        for entity in entities {
3934            raw.extend(entity);
3935        }
3936        raw
3937    }
3938
3939    fn selector() -> Vec<u8> {
3940        vec![9, 0x24, 5, 7, 2, 1, 2, 3, 0]
3941    }
3942
3943    #[test]
3944    fn powered_scope_requires_complete_claims_unique_iad_and_full_protocol() {
3945        let mut raw = vec![9, 2, 0, 0, 3, 1, 0, 0x80, 50];
3946        raw.extend([8, 11, 3, 3, 1, 0, 0x30, 0]);
3947        raw.extend([9, 4, 3, 0, 0, 1, 1, 0x30, 0]);
3948        raw.extend([9, 4, 4, 0, 0, 1, 2, 0x30, 0]);
3949        raw.extend([9, 4, 5, 0, 0, 1, 2, 0x30, 0]);
3950        assert_eq!(
3951            routing_power_interfaces(&raw, &[3, 4, 5], 3).unwrap(),
3952            vec![4, 5]
3953        );
3954        assert!(routing_power_interfaces(&raw, &[3, 4], 3).is_err());
3955        assert!(routing_power_interfaces(&raw, &[3, 4, 5], 4).is_err());
3956        let mut badd = raw.clone();
3957        badd[15] = 0x20;
3958        assert!(routing_power_interfaces(&badd, &[3, 4, 5], 3).is_err());
3959        raw.extend([8, 11, 4, 2, 1, 0, 0x30, 0]);
3960        assert!(routing_power_interfaces(&raw, &[3, 4, 5], 3).is_err());
3961    }
3962
3963    #[test]
3964    fn powered_scope_selects_only_routing_dependencies_and_rejects_ambiguity() {
3965        let terminal = [4, 0x24, 2, 1];
3966        let unrelated = [4, 0x24, 2, 2];
3967        let selector = [9, 0x24, 6, 7, 1, 1, 0, 0, 0];
3968        let domain = [12, 0x24, 0x10, 9, 0, 0, 0, 0, 1, 1, 0, 0];
3969        let other = [12, 0x24, 0x10, 10, 0, 0, 0, 0, 1, 2, 0, 0];
3970        let descriptors: Vec<&[u8]> = vec![&terminal, &unrelated, &selector, &domain, &other];
3971        let (domains, entities) = adc3_routing_scope(&descriptors).unwrap();
3972        assert_eq!(domains.iter().map(|d| d.id).collect::<Vec<_>>(), vec![9]);
3973        assert_eq!(entities.into_iter().collect::<Vec<_>>(), vec![1, 7]);
3974        let mut duplicate = descriptors.clone();
3975        duplicate.push(&terminal);
3976        assert!(adc3_routing_scope(&duplicate).is_err());
3977        let missing: Vec<&[u8]> = vec![&selector, &domain];
3978        assert!(adc3_routing_scope(&missing).is_err());
3979    }
3980
3981    #[test]
3982    fn claimed_uac2_topology_resolves_feature_mixer_and_selector_sources() {
3983        let mut feature = vec![18, 0x24, 6, 5, 1];
3984        feature.extend([0; 13]);
3985        let mixer = vec![16, 0x24, 4, 9, 2, 5, 7, 2, 0, 0, 0, 0, 0, 0xff, 0, 0];
3986        let raw = configuration(
3987            &[
3988                terminal(1, 2, 3),
3989                terminal(2, 2, 3),
3990                feature,
3991                selector(),
3992                mixer,
3993            ],
3994            0x20,
3995        );
3996        let inventory = inventory_from_config(&raw, &[3]).unwrap();
3997        assert_eq!(inventory.units().count(), 2);
3998        let control = inventory
3999            .control(ControlKey::Crosspoint {
4000                entity: Entity {
4001                    interface: 3,
4002                    id: 9,
4003                },
4004                input_pin: 2,
4005                input_channel: 2,
4006                output_channel: 2,
4007            })
4008            .unwrap();
4009        assert_eq!(control.current_request().unwrap().value, 0x0107);
4010        assert_eq!(control.current_request().unwrap().index, 0x0903);
4011    }
4012
4013    #[test]
4014    fn partial_inventory_keeps_independent_selector_when_mixer_width_is_unknown() {
4015        let mixer = vec![16, 0x24, 4, 9, 2, 99, 7, 2, 0, 0, 0, 0, 0, 0xff, 0, 0];
4016        let raw = configuration(
4017            &[terminal(1, 2, 3), terminal(2, 2, 3), selector(), mixer],
4018            0x20,
4019        );
4020        let (inventory, diagnostics) = inventory_partial(&raw, &[3], &BTreeMap::new()).unwrap();
4021        assert!(inventory
4022            .control(ControlKey::Selector(Entity {
4023                interface: 3,
4024                id: 7
4025            }))
4026            .is_ok());
4027        assert!(inventory
4028            .control(ControlKey::Crosspoint {
4029                entity: Entity {
4030                    interface: 3,
4031                    id: 9
4032                },
4033                input_pin: 2,
4034                input_channel: 1,
4035                output_channel: 1
4036            })
4037            .is_err());
4038        assert!(diagnostics
4039            .iter()
4040            .any(|d| d.interface == 3 && d.entity_id == Some(9)));
4041    }
4042
4043    #[test]
4044    fn equal_width_selector_with_distinct_spatial_labels_keeps_mixer_indices() {
4045        let mixer = vec![16, 0x24, 4, 9, 2, 1, 7, 2, 0, 0, 0, 0, 0, 0xff, 0, 0];
4046        let raw = configuration(
4047            &[terminal(1, 2, 3), terminal(2, 2, 12), selector(), mixer],
4048            0x20,
4049        );
4050        let (inventory, diagnostics) = inventory_partial(&raw, &[3], &BTreeMap::new()).unwrap();
4051        assert!(diagnostics.is_empty());
4052        let point = inventory
4053            .control(ControlKey::Crosspoint {
4054                entity: Entity {
4055                    interface: 3,
4056                    id: 9,
4057                },
4058                input_pin: 2,
4059                input_channel: 1,
4060                output_channel: 1,
4061            })
4062            .unwrap();
4063        assert_eq!(point.current_request().unwrap().value, 0x0104);
4064    }
4065
4066    #[test]
4067    fn deadline_never_returns_a_timeout_after_expiry() {
4068        assert!(remaining(Instant::now() - Duration::from_millis(1)).is_err());
4069        assert!(
4070            remaining(Instant::now() + Duration::from_secs(10)).unwrap() <= Duration::from_secs(1)
4071        );
4072    }
4073
4074    #[test]
4075    fn unclaimed_unknown_and_mismatched_protocols_never_expose_controls() {
4076        let entities = [terminal(1, 2, 3), terminal(2, 2, 3), selector()];
4077        assert_eq!(
4078            inventory_from_config(&configuration(&entities, 0x20), &[4])
4079                .unwrap()
4080                .units()
4081                .count(),
4082            0
4083        );
4084        assert_eq!(
4085            inventory_from_config(&configuration(&entities, 0xff), &[3])
4086                .unwrap()
4087                .units()
4088                .count(),
4089            0
4090        );
4091        // Reinterpreting UAC2 descriptor bytes under another protocol is refused.
4092        for protocol in [0, 0x30] {
4093            assert!(inventory_from_config(&configuration(&entities, protocol), &[3]).is_err());
4094        }
4095    }
4096
4097    #[test]
4098    fn no_default_counts_for_missing_cyclic_or_unsupported_sources() {
4099        let missing = configuration(&[terminal(1, 2, 3), selector()], 0x20);
4100        assert!(matches!(
4101            inventory_from_config(&missing, &[3]),
4102            Err(RoutingSessionError::UnsupportedTopology(_))
4103        ));
4104        let cycle = configuration(&[vec![8, 0x24, 5, 7, 1, 7, 3, 0]], 0x20);
4105        assert!(matches!(
4106            inventory_from_config(&cycle, &[3]),
4107            Err(RoutingSessionError::UnsupportedTopology(_))
4108        ));
4109        let unknown = configuration(
4110            &[
4111                terminal(1, 2, 3),
4112                vec![8, 0x24, 9, 2, 0, 0, 0, 0],
4113                selector(),
4114            ],
4115            0x20,
4116        );
4117        assert!(matches!(
4118            inventory_from_config(&unknown, &[3]),
4119            Err(RoutingSessionError::UnsupportedTopology(_))
4120        ));
4121    }
4122
4123    #[test]
4124    fn selector_cluster_retains_width_without_claiming_spatial_identity() {
4125        let different_width =
4126            configuration(&[terminal(1, 2, 3), terminal(2, 1, 1), selector()], 0x20);
4127        assert!(matches!(
4128            inventory_from_config(&different_width, &[3]),
4129            Err(RoutingSessionError::UnsupportedTopology(_))
4130        ));
4131        for other in [terminal(2, 2, 12), {
4132            let mut terminal = terminal(2, 2, 3);
4133            terminal[13] = 5;
4134            terminal
4135        }] {
4136            let raw = configuration(&[terminal(1, 2, 3), other, selector()], 0x20);
4137            assert!(inventory_from_config(&raw, &[3]).is_ok());
4138        }
4139    }
4140
4141    #[test]
4142    fn malformed_framing_lengths_ids_and_feature_counts_fail_closed() {
4143        let raw = configuration(&[terminal(1, 2, 3), terminal(2, 2, 3), selector()], 0x20);
4144        let mut short = raw.clone();
4145        short.pop();
4146        assert!(inventory_from_config(&short, &[3]).is_err());
4147        let mut malformed = raw.clone();
4148        malformed[18] = 0;
4149        assert!(inventory_from_config(&malformed, &[3]).is_err());
4150        let duplicate = configuration(&[terminal(1, 2, 3), terminal(1, 2, 3), selector()], 0x20);
4151        assert!(matches!(
4152            inventory_from_config(&duplicate, &[3]),
4153            Err(RoutingSessionError::Invalid(InvalidRoute::DuplicateEntity))
4154        ));
4155        let bad_feature = configuration(
4156            &[
4157                terminal(1, 2, 3),
4158                vec![10, 0x24, 6, 2, 1, 0, 0, 0, 0, 0],
4159                selector(),
4160            ],
4161            0x20,
4162        );
4163        assert!(matches!(
4164            inventory_from_config(&bad_feature, &[3]),
4165            Err(RoutingSessionError::Invalid(
4166                InvalidRoute::MalformedDescriptor
4167            ))
4168        ));
4169    }
4170
4171    #[test]
4172    fn uac1_inventory_resolves_explicit_source_clusters() {
4173        let terminal = vec![12, 0x24, 2, 1, 1, 1, 0, 2, 3, 0, 0, 0];
4174        let selector = vec![7, 0x24, 5, 7, 1, 1, 0];
4175        let mixer = vec![12, 0x24, 4, 9, 1, 7, 2, 3, 0, 0, 0xf0, 0];
4176        let mut raw = configuration(&[terminal, selector, mixer], 0);
4177        raw[21..23].copy_from_slice(&[0, 1]);
4178        let total = raw.len() - 18;
4179        raw[23..25].copy_from_slice(&(total as u16).to_le_bytes());
4180        raw[25] = 1;
4181        raw[26] = 4;
4182        let inventory = inventory_from_config(&raw, &[3]).unwrap();
4183        let control = inventory
4184            .control(ControlKey::Crosspoint {
4185                entity: Entity {
4186                    interface: 3,
4187                    id: 9,
4188                },
4189                input_pin: 1,
4190                input_channel: 2,
4191                output_channel: 2,
4192            })
4193            .unwrap();
4194        assert_eq!(
4195            (
4196                control.current_request().unwrap().request,
4197                control.current_request().unwrap().value
4198            ),
4199            (0x81, 0x0202)
4200        );
4201        assert!(validate_protocol_request(control.current_request().unwrap(), true, 2, 0).is_ok());
4202        assert!(
4203            validate_protocol_request(control.current_request().unwrap(), true, 2, 0x20).is_err()
4204        );
4205    }
4206
4207    #[test]
4208    fn adc3_inventory_requires_hc_and_preserves_cluster_content_identity() {
4209        use crate::descriptors::uac3::{Channel, ChannelRelationship, Cluster as HcCluster};
4210        let terminal = |id, cluster| {
4211            vec![
4212                20, 0x24, 2, id, 1, 1, 0, 10, 0, 0, 0, 0, cluster, 0, 0, 0, 0, 0, 0, 0,
4213            ]
4214        };
4215        let selector = vec![13, 0x24, 6, 7, 2, 1, 2, 3, 0, 0, 0, 0, 0];
4216        let mixer = vec![15, 0x24, 5, 9, 1, 7, 3, 0, 0xf0, 0, 0, 0, 0, 0, 0];
4217        let entities = [terminal(1, 1), terminal(2, 2), selector, mixer];
4218        let total = 10 + entities.iter().map(Vec::len).sum::<usize>();
4219        let mut raw = vec![9, 2, 0, 0, 1, 1, 0, 0x80, 50, 9, 4, 3, 0, 0, 1, 1, 0x30, 0];
4220        raw.extend([10, 0x24, 1, 1, total as u8, (total >> 8) as u8, 0, 0, 0, 0]);
4221        for entity in entities {
4222            raw.extend(entity);
4223        }
4224        let len = raw.len() as u16;
4225        raw[2..4].copy_from_slice(&len.to_le_bytes());
4226        assert!(inventory_from_config(&raw, &[3]).is_err());
4227        let channel = |relationship| Channel::Information {
4228            purpose: 1,
4229            relationship,
4230            group: 0,
4231        };
4232        let channels = vec![
4233            channel(ChannelRelationship::Left),
4234            channel(ChannelRelationship::Right),
4235        ];
4236        let mut hc = BTreeMap::new();
4237        for id in 1..=3 {
4238            hc.insert(
4239                (3, id),
4240                RoutingCluster {
4241                    parsed: HcCluster {
4242                        id,
4243                        channels: channels.clone(),
4244                    },
4245                    content: vec![9, 0, 0x26, 0, id as u8, 0, 2, 2, 3],
4246                },
4247            );
4248        }
4249        let inventory = inventory_with_clusters(&raw, &[3], &hc).unwrap();
4250        assert_eq!(inventory.units().count(), 2);
4251        // Equal widths preserve addressing despite distinct spatial labels.
4252        // A prior snapshot must still reject the changed HC content for both
4253        // apply and hand-back, which share cluster_content_matches.
4254        let saved = hc.clone();
4255        let dependencies = [(3, 1), (3, 2), (3, 3)];
4256        assert!(cluster_content_matches(&hc, &saved, &dependencies));
4257        hc.get_mut(&(3, 2)).unwrap().content[7] = 1;
4258        let changed = inventory_with_clusters(&raw, &[3], &hc).unwrap();
4259        assert_eq!(changed, inventory);
4260        assert!(!cluster_content_matches(&hc, &saved, &dependencies));
4261        assert!(cluster_content_matches(&hc, &saved, &[(3, 1), (3, 3)]));
4262        hc.remove(&(3, 2));
4263        assert!(!cluster_content_matches(&hc, &saved, &dependencies));
4264        hc.clear();
4265        assert_eq!(
4266            inventory_with_clusters(&raw, &[4], &hc)
4267                .unwrap()
4268                .units()
4269                .count(),
4270            0
4271        );
4272    }
4273
4274    #[test]
4275    fn usb_adapter_only_allows_bounded_standard_routing_requests() {
4276        let request = ControlRequest {
4277            request_type: 0xa1,
4278            request: 1,
4279            value: 0x01ff,
4280            index: 0x0903,
4281            length: 2,
4282        };
4283        assert!(validate_request(request, true, 2).is_ok());
4284        assert!(validate_request(
4285            ControlRequest {
4286                request_type: 0x21,
4287                ..request
4288            },
4289            false,
4290            2
4291        )
4292        .is_ok());
4293        assert!(validate_request(
4294            ControlRequest {
4295                request: 2,
4296                length: 8,
4297                ..request
4298            },
4299            true,
4300            8
4301        )
4302        .is_ok());
4303        for bad in [
4304            ControlRequest {
4305                request_type: 0xc1,
4306                ..request
4307            },
4308            ControlRequest {
4309                request: 0xff,
4310                ..request
4311            },
4312            ControlRequest {
4313                value: 0x0200,
4314                ..request
4315            },
4316            ControlRequest {
4317                index: 3,
4318                ..request
4319            },
4320            ControlRequest {
4321                length: 3,
4322                ..request
4323            },
4324            ControlRequest {
4325                request: 2,
4326                length: 512,
4327                ..request
4328            },
4329        ] {
4330            assert!(validate_request(bad, true, usize::from(bad.length)).is_err());
4331        }
4332        assert!(validate_request(
4333            ControlRequest {
4334                request_type: 0x21,
4335                request: 2,
4336                ..request
4337            },
4338            false,
4339            2
4340        )
4341        .is_err());
4342    }
4343
4344    struct ReadIo {
4345        pin: u8,
4346        reads: usize,
4347    }
4348    impl RoutingIo for ReadIo {
4349        type Error = String;
4350        fn read(&mut self, _: ControlRequest, bytes: &mut [u8]) -> Result<usize, String> {
4351            self.reads += 1;
4352            bytes[0] = self.pin;
4353            Ok(1)
4354        }
4355        fn write(&mut self, _: ControlRequest, _: &[u8]) -> Result<usize, String> {
4356            panic!("drift verification must never write")
4357        }
4358    }
4359
4360    #[test]
4361    fn ownership_discards_settled_history_and_preserves_ambiguous_pair() {
4362        let pin = RouteValue::SelectorPin;
4363        let mut entry = RecordedRoute {
4364            original: pin(1),
4365            ownership: Ownership::None,
4366            selectors: Vec::new(),
4367            forfeited: false,
4368        };
4369        entry.record_attempt(pin(1), pin(2), true, false);
4370        entry.record_attempt(pin(2), pin(3), true, false);
4371        assert!(!entry.ownership.owns(pin(2)));
4372        assert!(entry.ownership.owns(pin(3)));
4373        entry.record_attempt(pin(3), pin(4), false, true);
4374        assert!(entry.ownership.owns(pin(3)) && entry.ownership.owns(pin(4)));
4375        assert!(!entry.ownership.owns(pin(2)));
4376        entry.record_attempt(pin(3), pin(5), false, false);
4377        assert_eq!(entry.ownership, Ownership::Verified(pin(3)));
4378        entry.record_attempt(pin(9), pin(6), true, false);
4379        assert!(entry.forfeited);
4380        assert_eq!(entry.ownership, Ownership::None);
4381        assert_eq!(entry.original, pin(1));
4382    }
4383
4384    #[test]
4385    fn foreign_live_selector_never_triggers_hand_back_write() {
4386        let raw = configuration(&[terminal(1, 2, 3), terminal(2, 2, 3), selector()], 0x20);
4387        let inventory = inventory_from_config(&raw, &[3]).unwrap();
4388        let key = ControlKey::Selector(Entity {
4389            interface: 3,
4390            id: 7,
4391        });
4392        let saved = RecordedRoute {
4393            original: RouteValue::SelectorPin(1),
4394            ownership: Ownership::Verified(RouteValue::SelectorPin(3)),
4395            selectors: Vec::new(),
4396            forfeited: false,
4397        };
4398        let mut io = ReadIo { pin: 2, reads: 0 };
4399        assert_eq!(
4400            restore_recorded_control(&inventory, &mut io, key, &saved),
4401            RoutingHandBackOutcome::ExternallyChanged
4402        );
4403        io.pin = 1;
4404        assert_eq!(
4405            restore_recorded_control(&inventory, &mut io, key, &saved),
4406            RoutingHandBackOutcome::AlreadyOriginal
4407        );
4408    }
4409
4410    #[test]
4411    fn expected_values_reject_external_selector_changes_without_writing() {
4412        let raw = configuration(&[terminal(1, 2, 3), terminal(2, 2, 3), selector()], 0x20);
4413        let inventory = inventory_from_config(&raw, &[3]).unwrap();
4414        let expected = [RouteChange {
4415            key: ControlKey::Selector(Entity {
4416                interface: 3,
4417                id: 7,
4418            }),
4419            value: RouteValue::SelectorPin(1),
4420        }];
4421        let mut io = ReadIo { pin: 2, reads: 0 };
4422        assert!(matches!(
4423            verify_values(&inventory, &mut io, &expected),
4424            Err(RoutingSessionError::Drift(_))
4425        ));
4426        io.pin = 1;
4427        assert!(verify_values(&inventory, &mut io, &expected).is_ok());
4428    }
4429}
4430
4431#[cfg(test)]
4432mod fcp_provenance_tests {
4433    use super::*;
4434    use crate::scarlett::{CandidateModel, FcpBank, FcpReadback, MixReadback};
4435    #[test]
4436    fn unrelated_external_values_never_become_hand_back_changes() {
4437        let original = FcpReadback {
4438            model: CandidateModel::Scarlett16i16Gen4,
4439            firmware: 1,
4440            mixer_inputs: 1,
4441            mixer_outputs: 2,
4442            sources: vec![],
4443            destinations: vec![],
4444            banks: vec![
4445                FcpBank {
4446                    bank: 0,
4447                    raw_words: vec![1],
4448                },
4449                FcpBank {
4450                    bank: 1,
4451                    raw_words: vec![2],
4452                },
4453            ],
4454            mixes: vec![
4455                MixReadback {
4456                    output: 1,
4457                    coefficients: vec![3],
4458                },
4459                MixReadback {
4460                    output: 2,
4461                    coefficients: vec![4],
4462                },
4463            ],
4464        };
4465        let mut last = original.clone();
4466        last.banks[0].raw_words[0] = 10;
4467        last.mixes[0].coefficients[0] = 30;
4468        let mut before = last.clone();
4469        before.banks[1].raw_words[0] = 20; // External change before a later unrelated edit.
4470        before.mixes[0].coefficients[0] = 31; // External change to an earlier owned target.
4471        let mut verified = before.clone();
4472        verified.mixes[1].coefficients[0] = 40;
4473        let (saved, recent) = merge_fcp_provenance(&original, &last, &before, &verified);
4474        assert_eq!(saved.banks[1], recent.banks[1]);
4475        assert_eq!(saved.banks[1].raw_words, vec![20]);
4476        assert_eq!(saved.banks[0], original.banks[0]);
4477        assert_eq!(recent.banks[0], last.banks[0]);
4478        assert_eq!(saved.mixes[0], original.mixes[0]);
4479        assert_eq!(recent.mixes[0], last.mixes[0]); // Fresh restore detects external 31 versus 30.
4480        assert_eq!(saved.mixes[1], original.mixes[1]);
4481        assert_eq!(recent.mixes[1], verified.mixes[1]);
4482    }
4483}
4484
4485#[cfg(test)]
4486mod gen1_transport_tests {
4487    use super::*;
4488    use crate::scarlett::{Gen1Control, Gen1Key, Gen1Model, Gen1Readback};
4489
4490    fn topology(iad: bool) -> Vec<u8> {
4491        let mut raw = vec![9, 2, 0, 0, 2, 1, 0, 0x80, 50];
4492        if iad {
4493            raw.extend([8, 11, 3, 2, 1, 0, 0x20, 0]);
4494        }
4495        raw.extend([9, 4, 3, 0, 0, 1, 1, 0x20, 0]);
4496        raw.extend([9, 0x24, 1, 0, 2, 0, 26, 0, 0]);
4497        raw.extend([17, 0x24, 2, 1, 1, 1, 0, 9, 2, 3, 0, 0, 0, 0, 0, 0, 0]);
4498        raw.extend([9, 4, 4, 1, 1, 1, 2, 0x20, 0]);
4499        raw.extend([16, 0x24, 1, 1, 0, 1, 1, 0, 0, 0, 2, 3, 0, 0, 0, 0]);
4500        raw.extend([7, 5, 1, 1, 64, 0, 1]);
4501        let length = (raw.len() as u16).to_le_bytes();
4502        raw[2..4].copy_from_slice(&length);
4503        raw
4504    }
4505    fn device() -> UsbDevice {
4506        UsbDevice {
4507            fd: DeviceKey::Usbfs(-1),
4508            #[cfg(target_os = "macos")]
4509            darwin: None,
4510            _fd_owner: Some(Arc::new(OwnedUsbFd(-1))),
4511            claimed_interfaces: vec![3].into(),
4512            vendor_id: 0x1235,
4513            product_id: 0x8012,
4514            product_name: String::new(),
4515            device_name: None,
4516        }
4517    }
4518    #[test]
4519    fn gen1_binding_requires_claimed_unique_uac2_function_and_terminal_link() {
4520        for iad in [false, true] {
4521            let raw = topology(iad);
4522            assert_eq!(gen1_interface(&raw, &[3]).unwrap(), 3);
4523            assert!(gen1_interface(&raw, &[4]).is_err());
4524            let mut unlinked = raw.clone();
4525            let link = unlinked.len() - 20;
4526            unlinked[link] = 99;
4527            assert!(gen1_interface(&unlinked, &[3]).is_err());
4528            let mut wrong_protocol = raw.clone();
4529            let ac_protocol = if iad { 24 } else { 16 };
4530            wrong_protocol[ac_protocol] = 0;
4531            assert!(gen1_interface(&wrong_protocol, &[3]).is_err());
4532        }
4533        let mut conflicting = topology(true);
4534        conflicting[13] = 0xff; // IAD owns AC but declares the wrong function class.
4535        assert!(gen1_interface(&conflicting, &[3]).is_err());
4536        let mut wrong_direction = topology(false);
4537        let endpoint_address = wrong_direction.len() - 5;
4538        wrong_direction[endpoint_address] = 0x81;
4539        assert!(gen1_interface(&wrong_direction, &[3]).is_err());
4540        let mut zero_alt = topology(false);
4541        zero_alt[47] = 0;
4542        assert!(gen1_interface(&zero_alt, &[3]).is_err());
4543        let raw = topology(true);
4544        let target = device();
4545        let binding = Gen1Binding {
4546            device: target.clone(),
4547            configuration: 1,
4548            descriptors: raw.clone(),
4549        };
4550        assert!(check_gen1_binding(&binding, &target, 1, &raw).is_ok());
4551        assert!(check_gen1_binding(&binding, &device(), 1, &raw).is_err());
4552        assert!(check_gen1_binding(&binding, &target, 2, &raw).is_err());
4553        let mut changed = raw.clone();
4554        changed[8] = 51;
4555        assert!(check_gen1_binding(&binding, &target, 1, &changed).is_err());
4556    }
4557    #[test]
4558    fn gen1_independent_control_provenance_preserves_external_drift() {
4559        let original = Gen1Readback {
4560            model: Gen1Model::Scarlett6i6,
4561            source_offsets: [0; 5],
4562            matrix_sources: 0,
4563            output_sources: 0,
4564            controls: vec![
4565                Gen1Control {
4566                    key: Gen1Key::Output(1),
4567                    value: 1,
4568                },
4569                Gen1Control {
4570                    key: Gen1Key::Output(2),
4571                    value: 2,
4572                },
4573            ],
4574        };
4575        let mut last = original.clone();
4576        last.controls[0].value = 10;
4577        let mut before = last.clone();
4578        before.controls[0].value = 11;
4579        let mut verified = before.clone();
4580        verified.controls[1].value = 20;
4581        let (saved, recent) = merge_gen1_provenance(&original, &last, &before, &verified);
4582        assert_eq!(saved.controls, original.controls);
4583        assert_eq!(recent.controls[0], last.controls[0]);
4584        assert_eq!(recent.controls[1], verified.controls[1]);
4585    }
4586}