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