Skip to main content

usbdac_core/
routing.rs

1//! Pure USB Audio 1/2/3 routing inventory and control transactions.
2//!
3//! Independent implementation of USB-IF Audio 2.0 sections 4.7.2.6–7,
4//! 5.2.2–3 and 5.2.5.5–6 (September 2026 errata). Mixer gains use signed
5//! 1/256 dB units; `i16::MIN` means silence. A mixer crosspoint is a gain,
6//! not an on/off switch. Fixed crosspoints remain readable.
7//!
8//! This module does not discover devices, claim interfaces, stop streams, or
9//! implement vendor protocols (including Scarlett). The caller must resolve
10//! upstream channel clusters, serialize control I/O and exclude concurrent
11//! topology changes before using an inventory or applying a transaction.
12
13use std::collections::BTreeMap;
14
15pub use crate::transport::routing_hw::{
16    RouteEdit, RoutingApplyError, RoutingDiagnostic, RoutingHandBackOutcome, RoutingHandBackReport,
17    RoutingSessionError, RoutingSnapshot,
18};
19
20/// AudioControl interface and entity identity, scoped to the active configuration.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
22pub struct Entity {
23    pub interface: u8,
24    pub id: u8,
25}
26
27/// Every pin and channel here is one-based, in descriptor/wire order.
28#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
29pub enum ControlKey {
30    Selector(Entity),
31    Crosspoint {
32        entity: Entity,
33        input_pin: u8,
34        input_channel: u8,
35        output_channel: u8,
36    },
37}
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub enum Access {
41    Absent,
42    ReadOnly,
43    ReadWrite,
44}
45
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub enum InvalidRoute {
48    MalformedDescriptor,
49    ReservedCapability,
50    UnknownInputChannels,
51    TooManyCrosspoints,
52    DuplicateEntity,
53    UnknownControl,
54    NotReadable,
55    NotWritable,
56    WrongValueType,
57    InvalidPin,
58    InvalidRange,
59    GainOutsideRange,
60    DuplicateChange,
61    TooManyChanges,
62}
63
64/// A source cluster already resolved under this AudioControl interface.
65/// Supply exactly one entry per mixer input pin; never infer these counts from
66/// the bitmap length or substitute a default for an unresolved upstream entity.
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68pub struct InputCluster {
69    pub source_id: u8,
70    pub channels: u8,
71}
72
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub enum RoutingProtocol {
75    Uac1,
76    Uac2,
77    Adc3,
78}
79
80#[derive(Debug, Clone, PartialEq, Eq)]
81pub struct SelectorUnit {
82    entity: Entity,
83    sources: Vec<u8>,
84    access: Access,
85    protocol: RoutingProtocol,
86}
87
88impl SelectorUnit {
89    /// Parse exactly one UAC2 Selector Unit descriptor (subtype 0x05).
90    /// This reports descriptor capabilities, not empirically tested hardware.
91    pub fn parse(interface: u8, bytes: &[u8]) -> Result<Self, InvalidRoute> {
92        let pins = header(bytes, 0x05)?;
93        if bytes.len() != 7 + pins || bytes[5..5 + pins].contains(&0) {
94            return Err(InvalidRoute::MalformedDescriptor);
95        }
96        let flags = bytes[5 + pins];
97        if flags & !3 != 0 {
98            return Err(InvalidRoute::ReservedCapability);
99        }
100        Ok(Self {
101            entity: Entity {
102                interface,
103                id: bytes[3],
104            },
105            sources: bytes[5..5 + pins].to_vec(),
106            access: access(flags)?,
107            protocol: RoutingProtocol::Uac2,
108        })
109    }
110
111    /// UAC1 selectors have mandatory GET_CUR/SET_CUR and no access bitmap.
112    pub fn parse_uac1(interface: u8, bytes: &[u8]) -> Result<Self, InvalidRoute> {
113        let pins = header(bytes, 5)?;
114        if bytes.len() != 6 + pins || bytes[5..5 + pins].contains(&0) {
115            return Err(InvalidRoute::MalformedDescriptor);
116        }
117        Ok(Self {
118            entity: Entity {
119                interface,
120                id: bytes[3],
121            },
122            sources: bytes[5..5 + pins].to_vec(),
123            access: Access::ReadWrite,
124            protocol: RoutingProtocol::Uac1,
125        })
126    }
127
128    /// Full ADC3 Selector Unit, including its 32-bit access field.
129    pub fn parse_adc3(interface: u8, bytes: &[u8]) -> Result<Self, InvalidRoute> {
130        let pins = header(bytes, 6)?;
131        if bytes.len() != 11 + pins || bytes[5..5 + pins].contains(&0) {
132            return Err(InvalidRoute::MalformedDescriptor);
133        }
134        let flags = u32::from_le_bytes(bytes[5 + pins..9 + pins].try_into().unwrap());
135        if flags & !3 != 0 {
136            return Err(InvalidRoute::ReservedCapability);
137        }
138        let access = access(flags as u8)?;
139        if access == Access::Absent {
140            return Err(InvalidRoute::ReservedCapability);
141        }
142        Ok(Self {
143            entity: Entity {
144                interface,
145                id: bytes[3],
146            },
147            sources: bytes[5..5 + pins].to_vec(),
148            access,
149            protocol: RoutingProtocol::Adc3,
150        })
151    }
152
153    pub fn entity(&self) -> Entity {
154        self.entity
155    }
156    pub fn sources(&self) -> &[u8] {
157        &self.sources
158    }
159    pub fn access(&self) -> Access {
160        self.access
161    }
162}
163
164#[derive(Debug, Clone, PartialEq, Eq)]
165pub struct MixerUnit {
166    entity: Entity,
167    inputs: Vec<InputCluster>,
168    outputs: u8,
169    programmable: Vec<u8>,
170    protocol: RoutingProtocol,
171}
172
173impl MixerUnit {
174    /// Parse exactly one UAC2 Mixer Unit descriptor (subtype 0x04), only after
175    /// resolving the channel count of every source in `baSourceID`.
176    pub fn parse(
177        interface: u8,
178        bytes: &[u8],
179        inputs: &[InputCluster],
180    ) -> Result<Self, InvalidRoute> {
181        let pins = header(bytes, 0x04)?;
182        if bytes.len() < 13 + pins {
183            return Err(InvalidRoute::MalformedDescriptor);
184        }
185        if inputs.len() != pins
186            || inputs
187                .iter()
188                .enumerate()
189                .any(|(i, c)| c.channels == 0 || c.source_id == 0 || c.source_id != bytes[5 + i])
190        {
191            return Err(InvalidRoute::UnknownInputChannels);
192        }
193        let outputs = bytes[5 + pins];
194        if outputs == 0 {
195            return Err(InvalidRoute::MalformedDescriptor);
196        }
197        let channels: usize = inputs.iter().map(|c| usize::from(c.channels)).sum();
198        let cells = channels * usize::from(outputs);
199        // MCN is an unsigned byte, numbered from zero (not an input channel).
200        if cells > 256 {
201            return Err(InvalidRoute::TooManyCrosspoints);
202        }
203        let bitmap_len = cells.div_ceil(8);
204        if bytes.len() != 13 + pins + bitmap_len {
205            return Err(InvalidRoute::MalformedDescriptor);
206        }
207        let start = 11 + pins;
208        let flags = bytes[start + bitmap_len];
209        if flags & 0xc0 != 0 {
210            return Err(InvalidRoute::ReservedCapability);
211        }
212        for shift in [0, 2, 4] {
213            access((flags >> shift) & 3)?;
214        }
215        let bitmap = &bytes[start..start + bitmap_len];
216        if cells % 8 != 0 && bitmap[bitmap_len - 1] & ((1 << (8 - cells % 8)) - 1) != 0 {
217            return Err(InvalidRoute::MalformedDescriptor);
218        }
219        Ok(Self {
220            entity: Entity {
221                interface,
222                id: bytes[3],
223            },
224            inputs: inputs.to_vec(),
225            outputs,
226            programmable: bitmap.to_vec(),
227            protocol: RoutingProtocol::Uac2,
228        })
229    }
230
231    /// UAC1 uses the descriptor's explicit four-byte output cluster.
232    pub fn parse_uac1(
233        interface: u8,
234        bytes: &[u8],
235        inputs: &[InputCluster],
236    ) -> Result<Self, InvalidRoute> {
237        Self::parse_other(interface, bytes, inputs, None, RoutingProtocol::Uac1)
238    }
239
240    /// Full ADC3 output count must come from the referenced, queried HC Cluster.
241    pub fn parse_adc3(
242        interface: u8,
243        bytes: &[u8],
244        inputs: &[InputCluster],
245        outputs: u8,
246    ) -> Result<Self, InvalidRoute> {
247        Self::parse_other(
248            interface,
249            bytes,
250            inputs,
251            Some(outputs),
252            RoutingProtocol::Adc3,
253        )
254    }
255
256    fn parse_other(
257        interface: u8,
258        bytes: &[u8],
259        inputs: &[InputCluster],
260        outputs: Option<u8>,
261        protocol: RoutingProtocol,
262    ) -> Result<Self, InvalidRoute> {
263        let pins = header(
264            bytes,
265            if protocol == RoutingProtocol::Adc3 {
266                5
267            } else {
268                4
269            },
270        )?;
271        if bytes.len() < 5 + pins {
272            return Err(InvalidRoute::MalformedDescriptor);
273        }
274        if inputs.len() != pins
275            || inputs
276                .iter()
277                .enumerate()
278                .any(|(i, c)| c.channels == 0 || c.source_id == 0 || c.source_id != bytes[5 + i])
279        {
280            return Err(InvalidRoute::UnknownInputChannels);
281        }
282        let outputs = outputs
283            .or_else(|| bytes.get(5 + pins).copied())
284            .ok_or(InvalidRoute::MalformedDescriptor)?;
285        if outputs == 0 {
286            return Err(InvalidRoute::UnknownInputChannels);
287        }
288        let channels: usize = inputs.iter().map(|c| usize::from(c.channels)).sum();
289        let cells = channels * usize::from(outputs);
290        if (protocol != RoutingProtocol::Uac1 && cells > 256)
291            || (protocol == RoutingProtocol::Uac1 && channels > 254)
292        {
293            return Err(InvalidRoute::TooManyCrosspoints);
294        }
295        let count = cells.div_ceil(8);
296        let (base, start) = if protocol == RoutingProtocol::Adc3 {
297            (13, 7)
298        } else {
299            (10, 9)
300        };
301        if bytes.len() != base + pins + count {
302            return Err(InvalidRoute::MalformedDescriptor);
303        }
304        if protocol == RoutingProtocol::Adc3 {
305            if u16::from_le_bytes([bytes[5 + pins], bytes[6 + pins]]) == 0 {
306                return Err(InvalidRoute::MalformedDescriptor);
307            }
308            let at = start + pins + count;
309            let flags = u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap());
310            if flags & !15 != 0 {
311                return Err(InvalidRoute::ReservedCapability);
312            }
313            access((flags & 3) as u8)?;
314            access(((flags >> 2) & 3) as u8)?;
315        }
316        let bitmap = &bytes[start + pins..start + pins + count];
317        if cells % 8 != 0 && bitmap[count - 1] & ((1 << (8 - cells % 8)) - 1) != 0 {
318            return Err(InvalidRoute::MalformedDescriptor);
319        }
320        Ok(Self {
321            entity: Entity {
322                interface,
323                id: bytes[3],
324            },
325            inputs: inputs.to_vec(),
326            outputs,
327            programmable: bitmap.to_vec(),
328            protocol,
329        })
330    }
331
332    pub fn entity(&self) -> Entity {
333        self.entity
334    }
335    pub fn inputs(&self) -> &[InputCluster] {
336        &self.inputs
337    }
338    pub fn output_channels(&self) -> u8 {
339        self.outputs
340    }
341
342    pub fn crosspoint(
343        &self,
344        pin: u8,
345        channel: u8,
346        output: u8,
347    ) -> Result<RouteControl, InvalidRoute> {
348        let input = pin
349            .checked_sub(1)
350            .and_then(|p| self.inputs.get(usize::from(p)))
351            .ok_or(InvalidRoute::UnknownControl)?;
352        if channel == 0 || channel > input.channels || output == 0 || output > self.outputs {
353            return Err(InvalidRoute::UnknownControl);
354        }
355        let previous: usize = self.inputs[..usize::from(pin - 1)]
356            .iter()
357            .map(|c| usize::from(c.channels))
358            .sum();
359        let mcn = (previous + usize::from(channel - 1)) * usize::from(self.outputs)
360            + usize::from(output - 1);
361        let writable = self.programmable[mcn / 8] & (0x80 >> (mcn % 8)) != 0;
362        Ok(RouteControl {
363            key: ControlKey::Crosspoint {
364                entity: self.entity,
365                input_pin: pin,
366                input_channel: channel,
367                output_channel: output,
368            },
369            access: if writable {
370                Access::ReadWrite
371            } else {
372                Access::ReadOnly
373            },
374            mcn: mcn as u8,
375            input_number: (previous + usize::from(channel)) as u8,
376            protocol: self.protocol,
377            pins: None,
378        })
379    }
380}
381
382fn header(bytes: &[u8], subtype: u8) -> Result<usize, InvalidRoute> {
383    if bytes.len() < 5
384        || usize::from(bytes[0]) != bytes.len()
385        || bytes[1] != 0x24
386        || bytes[2] != subtype
387        || bytes[3] == 0
388        || bytes[4] == 0
389    {
390        return Err(InvalidRoute::MalformedDescriptor);
391    }
392    Ok(usize::from(bytes[4]))
393}
394
395fn access(bits: u8) -> Result<Access, InvalidRoute> {
396    match bits {
397        0 => Ok(Access::Absent),
398        1 => Ok(Access::ReadOnly),
399        3 => Ok(Access::ReadWrite),
400        _ => Err(InvalidRoute::ReservedCapability),
401    }
402}
403
404#[derive(Debug, Clone, PartialEq, Eq)]
405pub enum RoutingUnit {
406    Selector(SelectorUnit),
407    Mixer(MixerUnit),
408}
409
410/// Descriptor-backed inventory. Entity IDs are never matched across AC interfaces.
411#[derive(Debug, Clone, Default, PartialEq, Eq)]
412pub struct RoutingInventory {
413    units: BTreeMap<Entity, RoutingUnit>,
414}
415
416impl RoutingInventory {
417    pub fn insert(&mut self, unit: RoutingUnit) -> Result<(), InvalidRoute> {
418        let entity = match &unit {
419            RoutingUnit::Selector(s) => s.entity,
420            RoutingUnit::Mixer(m) => m.entity,
421        };
422        if self.units.contains_key(&entity) {
423            return Err(InvalidRoute::DuplicateEntity);
424        }
425        self.units.insert(entity, unit);
426        Ok(())
427    }
428
429    pub fn units(&self) -> impl Iterator<Item = &RoutingUnit> {
430        self.units.values()
431    }
432
433    pub fn control(&self, key: ControlKey) -> Result<RouteControl, InvalidRoute> {
434        match key {
435            ControlKey::Selector(entity) => match self.units.get(&entity) {
436                Some(RoutingUnit::Selector(s)) => Ok(RouteControl {
437                    key,
438                    access: s.access,
439                    mcn: 0,
440                    input_number: 0,
441                    protocol: s.protocol,
442                    pins: Some(s.sources.len() as u8),
443                }),
444                _ => Err(InvalidRoute::UnknownControl),
445            },
446            ControlKey::Crosspoint {
447                entity,
448                input_pin,
449                input_channel,
450                output_channel,
451            } => match self.units.get(&entity) {
452                Some(RoutingUnit::Mixer(m)) => {
453                    m.crosspoint(input_pin, input_channel, output_channel)
454                }
455                _ => Err(InvalidRoute::UnknownControl),
456            },
457        }
458    }
459}
460
461/// USB setup fields, excluding the data stage. UAC2 CUR is 0x01 in both
462/// directions; RANGE is 0x02 and is read only here.
463#[derive(Debug, Clone, Copy, PartialEq, Eq)]
464pub struct ControlRequest {
465    pub request_type: u8,
466    pub request: u8,
467    pub value: u16,
468    pub index: u16,
469    pub length: u16,
470}
471
472#[derive(Debug, Clone, Copy, PartialEq, Eq)]
473pub enum RouteValue {
474    SelectorPin(u8),
475    MixerGain(i16),
476}
477
478#[derive(Debug, Clone, Copy, PartialEq, Eq)]
479pub struct RouteChange {
480    pub key: ControlKey,
481    pub value: RouteValue,
482}
483
484/// Only constructors backed by a parsed unit can create this control.
485#[derive(Debug, Clone, Copy, PartialEq, Eq)]
486pub struct RouteControl {
487    key: ControlKey,
488    access: Access,
489    mcn: u8,
490    input_number: u8,
491    protocol: RoutingProtocol,
492    pins: Option<u8>,
493}
494
495impl RouteControl {
496    pub fn key(&self) -> ControlKey {
497        self.key
498    }
499    pub fn access(&self) -> Access {
500        self.access
501    }
502
503    fn setup(&self, input: bool, request: u8, length: u16) -> ControlRequest {
504        let entity = match self.key {
505            ControlKey::Selector(e) => e,
506            ControlKey::Crosspoint { entity, .. } => entity,
507        };
508        ControlRequest {
509            request_type: if input { 0xa1 } else { 0x21 },
510            request: if input && self.protocol == RoutingProtocol::Uac1 {
511                request | 0x80
512            } else {
513                request
514            },
515            value: if self.protocol == RoutingProtocol::Uac1 {
516                match self.key {
517                    ControlKey::Selector(_) => 0,
518                    ControlKey::Crosspoint { output_channel, .. } => {
519                        (u16::from(self.input_number) << 8) | u16::from(output_channel)
520                    }
521                }
522            } else {
523                0x0100 | u16::from(self.mcn)
524            },
525            index: (u16::from(entity.id) << 8) | u16::from(entity.interface),
526            length,
527        }
528    }
529
530    pub fn current_request(&self) -> Result<ControlRequest, InvalidRoute> {
531        if self.access == Access::Absent {
532            return Err(InvalidRoute::NotReadable);
533        }
534        Ok(self.setup(true, 1, if self.pins.is_some() { 1 } else { 2 }))
535    }
536
537    /// Validate selector pins and value type; mixer values additionally require
538    /// a live RANGE check, performed by `apply_routes` before any SET_CUR.
539    pub fn write_request(
540        &self,
541        value: RouteValue,
542    ) -> Result<(ControlRequest, Vec<u8>), InvalidRoute> {
543        if self.access != Access::ReadWrite {
544            return Err(InvalidRoute::NotWritable);
545        }
546        self.validate(value)?;
547        let bytes = match value {
548            RouteValue::SelectorPin(p) => vec![p],
549            RouteValue::MixerGain(g) => g.to_le_bytes().to_vec(),
550        };
551        Ok((self.setup(false, 1, bytes.len() as u16), bytes))
552    }
553
554    fn validate(&self, value: RouteValue) -> Result<(), InvalidRoute> {
555        match (self.pins, value) {
556            (Some(pins), RouteValue::SelectorPin(p)) if p > 0 && p <= pins => Ok(()),
557            (Some(_), RouteValue::SelectorPin(_)) => Err(InvalidRoute::InvalidPin),
558            (None, RouteValue::MixerGain(_)) => Ok(()),
559            _ => Err(InvalidRoute::WrongValueType),
560        }
561    }
562
563    pub fn read_current<I: RoutingIo>(
564        &self,
565        io: &mut I,
566    ) -> Result<RouteValue, RoutingError<I::Error>> {
567        let request = self.current_request().map_err(RoutingError::Invalid)?;
568        let mut data = vec![0; usize::from(request.length)];
569        read_exact(io, request, &mut data)?;
570        let value = if self.pins.is_some() {
571            RouteValue::SelectorPin(data[0])
572        } else {
573            RouteValue::MixerGain(i16::from_le_bytes([data[0], data[1]]))
574        };
575        self.validate(value).map_err(RoutingError::Invalid)?;
576        Ok(value)
577    }
578
579    /// Fetch a bounded UAC2 Layout 2 RANGE using the count header first.
580    pub fn read_gain_ranges<I: RoutingIo>(
581        &self,
582        io: &mut I,
583    ) -> Result<Vec<GainRange>, RoutingError<I::Error>> {
584        if self.pins.is_some() {
585            return Err(RoutingError::Invalid(InvalidRoute::WrongValueType));
586        }
587        if self.protocol == RoutingProtocol::Uac1 {
588            let mut values = [0i16; 3];
589            for (slot, request) in values.iter_mut().zip([2, 3, 4]) {
590                let mut bytes = [0; 2];
591                read_exact(io, self.setup(true, request, 2), &mut bytes)?;
592                *slot = i16::from_le_bytes(bytes);
593            }
594            let range = GainRange {
595                minimum: values[0],
596                maximum: values[1],
597                resolution: values[2],
598            };
599            return if range.valid() {
600                Ok(vec![range])
601            } else {
602                Err(RoutingError::Invalid(InvalidRoute::InvalidRange))
603            };
604        }
605        let mut header = [0; 2];
606        read_exact(io, self.setup(true, 2, 2), &mut header)?;
607        let count = usize::from(u16::from_le_bytes(header));
608        if count == 0 || count > MAX_GAIN_RANGES {
609            return Err(RoutingError::Invalid(InvalidRoute::InvalidRange));
610        }
611        let length = 2 + count * 6;
612        let mut data = vec![0; length];
613        read_exact(io, self.setup(true, 2, length as u16), &mut data)?;
614        decode_gain_ranges(&data).map_err(RoutingError::Invalid)
615    }
616}
617
618pub const MAX_GAIN_RANGES: usize = 64;
619pub const MAX_ROUTE_CHANGES: usize = 32;
620
621#[derive(Debug, Clone, Copy, PartialEq, Eq)]
622pub struct GainRange {
623    pub minimum: i16,
624    pub maximum: i16,
625    pub resolution: i16,
626}
627
628impl GainRange {
629    fn valid(&self) -> bool {
630        self.minimum != i16::MIN && self.minimum <= self.maximum && self.resolution > 0
631    }
632    pub fn contains(&self, gain: i16) -> bool {
633        self.valid()
634            && (gain == i16::MIN
635                || (gain >= self.minimum
636                    && gain <= self.maximum
637                    && (i32::from(gain) - i32::from(self.minimum)) % i32::from(self.resolution)
638                        == 0))
639    }
640}
641
642pub fn decode_gain_ranges(bytes: &[u8]) -> Result<Vec<GainRange>, InvalidRoute> {
643    if bytes.len() < 2 {
644        return Err(InvalidRoute::InvalidRange);
645    }
646    let count = usize::from(u16::from_le_bytes([bytes[0], bytes[1]]));
647    if count == 0 || count > MAX_GAIN_RANGES || bytes.len() != 2 + count * 6 {
648        return Err(InvalidRoute::InvalidRange);
649    }
650    bytes[2..]
651        .chunks_exact(6)
652        .map(|b| {
653            let range = GainRange {
654                minimum: i16::from_le_bytes([b[0], b[1]]),
655                maximum: i16::from_le_bytes([b[2], b[3]]),
656                resolution: i16::from_le_bytes([b[4], b[5]]),
657            };
658            if range.valid() {
659                Ok(range)
660            } else {
661                Err(InvalidRoute::InvalidRange)
662            }
663        })
664        .collect()
665}
666
667/// An adapter must return actual transferred lengths, including on short I/O.
668/// A failed write may have changed hardware; transactions restore that control too.
669pub trait RoutingIo {
670    type Error;
671    fn read(&mut self, request: ControlRequest, data: &mut [u8]) -> Result<usize, Self::Error>;
672    fn write(&mut self, request: ControlRequest, data: &[u8]) -> Result<usize, Self::Error>;
673    /// Admit the full set of changed controls before the first SET.
674    fn admit_plan(&mut self, _changed: usize) -> Result<(), Self::Error> {
675        Ok(())
676    }
677    /// Reserve enough time for a complete SET and its verifying read.
678    fn admit_write(&mut self) -> Result<(), Self::Error> {
679        Ok(())
680    }
681    fn begin_recovery(&mut self) {}
682    fn begin_recovery_for(&mut self, _attempted: usize) {
683        self.begin_recovery();
684    }
685}
686
687#[derive(Debug, PartialEq, Eq)]
688pub enum RoutingError<E> {
689    Invalid(InvalidRoute),
690    Io(E),
691    TransferLength {
692        expected: usize,
693        actual: usize,
694    },
695    ReadbackMismatch {
696        expected: RouteValue,
697        actual: RouteValue,
698    },
699}
700
701#[derive(Debug)]
702pub struct TransactionError<E> {
703    pub failed_change: Option<usize>,
704    pub cause: RoutingError<E>,
705    /// Empty means every attempted write was restored and verified, or no write
706    /// was attempted. Nonempty means hardware state is uncertain for these keys.
707    pub rollback_failures: Vec<(ControlKey, RoutingError<E>)>,
708}
709
710#[derive(Debug, Clone, Default, PartialEq, Eq)]
711pub struct RouteReport {
712    pub changed: Vec<ControlKey>,
713    pub unchanged: Vec<ControlKey>,
714}
715
716fn read_exact<I: RoutingIo>(
717    io: &mut I,
718    request: ControlRequest,
719    data: &mut [u8],
720) -> Result<(), RoutingError<I::Error>> {
721    let actual = io.read(request, data).map_err(RoutingError::Io)?;
722    if actual != data.len() {
723        return Err(RoutingError::TransferLength {
724            expected: data.len(),
725            actual,
726        });
727    }
728    Ok(())
729}
730
731pub(crate) fn write_verified<I: RoutingIo>(
732    io: &mut I,
733    control: RouteControl,
734    value: RouteValue,
735) -> Result<(), RoutingError<I::Error>> {
736    let (request, bytes) = control
737        .write_request(value)
738        .map_err(RoutingError::Invalid)?;
739    let actual = io.write(request, &bytes).map_err(RoutingError::Io)?;
740    if actual != bytes.len() {
741        return Err(RoutingError::TransferLength {
742            expected: bytes.len(),
743            actual,
744        });
745    }
746    let readback = control.read_current(io)?;
747    if readback != value {
748        return Err(RoutingError::ReadbackMismatch {
749            expected: value,
750            actual: readback,
751        });
752    }
753    Ok(())
754}
755
756/// Preflight all keys, permissions, original values and mixer ranges before any
757/// write. Apply changes in order, verify every write, and on failure restore all
758/// attempted controls in reverse order with readback. This is best-effort USB
759/// rollback, not device-side atomicity. Stop/reconfigure affected streams first.
760pub fn apply_routes<I: RoutingIo>(
761    inventory: &RoutingInventory,
762    io: &mut I,
763    changes: &[RouteChange],
764) -> Result<RouteReport, TransactionError<I::Error>> {
765    apply_routes_traced(inventory, io, changes, &mut Vec::new())
766}
767
768/// Actual CUR and attempted target for each SET, including ambiguous failures.
769pub(crate) fn apply_routes_traced<I: RoutingIo>(
770    inventory: &RoutingInventory,
771    io: &mut I,
772    changes: &[RouteChange],
773    attempted_values: &mut Vec<(ControlKey, RouteValue, RouteValue)>,
774) -> Result<RouteReport, TransactionError<I::Error>> {
775    let error = |index, cause| TransactionError {
776        failed_change: index,
777        cause,
778        rollback_failures: Vec::new(),
779    };
780    if changes.len() > MAX_ROUTE_CHANGES {
781        return Err(error(
782            None,
783            RoutingError::Invalid(InvalidRoute::TooManyChanges),
784        ));
785    }
786    let mut controls = Vec::with_capacity(changes.len());
787    // Validate the entire request before touching USB, even for read-only I/O.
788    for (i, change) in changes.iter().enumerate() {
789        if changes[..i].iter().any(|prior| prior.key == change.key) {
790            return Err(error(
791                Some(i),
792                RoutingError::Invalid(InvalidRoute::DuplicateChange),
793            ));
794        }
795        let control = inventory
796            .control(change.key)
797            .map_err(|e| error(Some(i), RoutingError::Invalid(e)))?;
798        control
799            .write_request(change.value)
800            .map_err(|e| error(Some(i), RoutingError::Invalid(e)))?;
801        controls.push(control);
802    }
803    let mut originals = Vec::with_capacity(changes.len());
804    for (i, (control, change)) in controls.iter().zip(changes).enumerate() {
805        let original = control.read_current(io).map_err(|e| error(Some(i), e))?;
806        if let RouteValue::MixerGain(gain) = change.value {
807            let ranges = control
808                .read_gain_ranges(io)
809                .map_err(|e| error(Some(i), e))?;
810            if !ranges.iter().any(|range| range.contains(gain)) {
811                return Err(error(
812                    Some(i),
813                    RoutingError::Invalid(InvalidRoute::GainOutsideRange),
814                ));
815            }
816        }
817        originals.push(original);
818    }
819    let changed = changes
820        .iter()
821        .zip(&originals)
822        .filter(|(change, original)| change.value != **original)
823        .count();
824    io.admit_plan(changed)
825        .map_err(|cause| error(None, RoutingError::Io(cause)))?;
826    let mut report = RouteReport::default();
827    let mut attempted: Vec<usize> = Vec::new();
828    for (i, ((control, change), original)) in
829        controls.iter().zip(changes).zip(&originals).enumerate()
830    {
831        if change.value == *original {
832            report.unchanged.push(change.key);
833            continue;
834        }
835        if let Err(cause) = io.admit_write() {
836            let mut failure = error(Some(i), RoutingError::Io(cause));
837            if !attempted.is_empty() {
838                io.begin_recovery_for(attempted.len());
839                for &j in attempted.iter().rev() {
840                    if let Err(e) = write_verified(io, controls[j], originals[j]) {
841                        failure.rollback_failures.push((changes[j].key, e));
842                    }
843                }
844            }
845            return Err(failure);
846        }
847        attempted.push(i);
848        attempted_values.push((change.key, *original, change.value));
849        if let Err(cause) = write_verified(io, *control, change.value) {
850            let mut failure = error(Some(i), cause);
851            io.begin_recovery_for(attempted.len());
852            for &j in attempted.iter().rev() {
853                if let Err(e) = write_verified(io, controls[j], originals[j]) {
854                    failure.rollback_failures.push((changes[j].key, e));
855                }
856            }
857            return Err(failure);
858        }
859        report.changed.push(change.key);
860    }
861    Ok(report)
862}
863
864#[cfg(test)]
865mod tests {
866    use super::*;
867
868    #[test]
869    fn uac1_selector_and_crosspoint_use_legacy_setup_and_separate_ranges() {
870        let selector = SelectorUnit::parse_uac1(3, &[8, 0x24, 5, 7, 2, 1, 2, 0]).unwrap();
871        let mut inventory = RoutingInventory::default();
872        inventory.insert(RoutingUnit::Selector(selector)).unwrap();
873        let control = inventory
874            .control(ControlKey::Selector(Entity {
875                interface: 3,
876                id: 7,
877            }))
878            .unwrap();
879        let current = control.current_request().unwrap();
880        assert_eq!(
881            (current.request, current.value, current.length),
882            (0x81, 0, 1)
883        );
884        assert_eq!(
885            control
886                .write_request(RouteValue::SelectorPin(2))
887                .unwrap()
888                .0
889                .value,
890            0
891        );
892        let inputs = [
893            InputCluster {
894                source_id: 1,
895                channels: 1,
896            },
897            InputCluster {
898                source_id: 2,
899                channels: 1,
900            },
901        ];
902        let mixer =
903            MixerUnit::parse_uac1(3, &[13, 0x24, 4, 9, 2, 1, 2, 2, 3, 0, 0, 0xf0, 0], &inputs)
904                .unwrap();
905        let point = mixer.crosspoint(2, 1, 2).unwrap();
906        assert_eq!(point.current_request().unwrap().value, 0x0202);
907        struct LegacyIo {
908            requests: Vec<u8>,
909        }
910        impl RoutingIo for LegacyIo {
911            type Error = ();
912            fn read(&mut self, request: ControlRequest, bytes: &mut [u8]) -> Result<usize, ()> {
913                self.requests.push(request.request);
914                assert_eq!(request.value, 0x0202);
915                let value: i16 = match request.request {
916                    0x82 => -1024,
917                    0x83 => 0,
918                    0x84 => 256,
919                    _ => panic!("unexpected legacy request"),
920                };
921                bytes.copy_from_slice(&value.to_le_bytes());
922                Ok(bytes.len())
923            }
924            fn write(&mut self, _: ControlRequest, _: &[u8]) -> Result<usize, ()> {
925                panic!("range query wrote hardware")
926            }
927        }
928        let mut io = LegacyIo { requests: vec![] };
929        let ranges = point.read_gain_ranges(&mut io).unwrap();
930        assert_eq!(io.requests, [0x82, 0x83, 0x84]);
931        assert!(ranges[0].contains(-512));
932        assert!(!ranges[0].contains(-500));
933    }
934
935    #[test]
936    fn adc3_routes_use_full_access_words_mcn_and_layout_widths() {
937        let mut inventory = RoutingInventory::default();
938        inventory
939            .insert(RoutingUnit::Selector(
940                SelectorUnit::parse_adc3(3, &[13, 0x24, 6, 7, 2, 1, 2, 3, 0, 0, 0, 0, 0]).unwrap(),
941            ))
942            .unwrap();
943        let control = inventory
944            .control(ControlKey::Selector(Entity {
945                interface: 3,
946                id: 7,
947            }))
948            .unwrap();
949        assert_eq!(
950            (
951                control.current_request().unwrap().value,
952                control.current_request().unwrap().length
953            ),
954            (0x0100, 1)
955        );
956        assert!(SelectorUnit::parse_adc3(3, &[12, 0x24, 6, 7, 1, 1, 3, 0, 0, 1, 0, 0]).is_err());
957        let inputs = [InputCluster {
958            source_id: 1,
959            channels: 2,
960        }];
961        let mut bytes = vec![15, 0x24, 5, 9, 1, 1, 42, 0, 0x90, 0, 0, 0, 0, 0, 0];
962        let mixer = MixerUnit::parse_adc3(3, &bytes, &inputs, 2).unwrap();
963        let point = mixer.crosspoint(1, 2, 2).unwrap();
964        assert_eq!(
965            (
966                point.current_request().unwrap().value,
967                point.current_request().unwrap().length
968            ),
969            (0x0103, 2)
970        );
971        assert_eq!(
972            point.write_request(RouteValue::MixerGain(-512)).unwrap().1,
973            (-512i16).to_le_bytes()
974        );
975        assert_eq!(
976            mixer.crosspoint(1, 1, 2).unwrap().access(),
977            Access::ReadOnly
978        );
979        bytes[12] = 1; // reserved bit in the high byte of bmControls
980        assert!(MixerUnit::parse_adc3(3, &bytes, &inputs, 2).is_err());
981        assert!(MixerUnit::parse_adc3(3, &bytes[..7], &inputs, 2).is_err());
982    }
983
984    fn selector(interface: u8, id: u8, flags: u8) -> SelectorUnit {
985        SelectorUnit::parse(interface, &[9, 0x24, 5, id, 2, 1, 2, flags, 0]).unwrap()
986    }
987
988    fn mixer(
989        inputs: &[InputCluster],
990        outputs: u8,
991        bitmap: &[u8],
992    ) -> Result<MixerUnit, InvalidRoute> {
993        let mut bytes = vec![
994            (13 + inputs.len() + bitmap.len()) as u8,
995            0x24,
996            4,
997            9,
998            inputs.len() as u8,
999        ];
1000        bytes.extend(inputs.iter().map(|c| c.source_id));
1001        bytes.push(outputs);
1002        bytes.extend([0, 0, 0, 0, 0]); // channel config and names
1003        bytes.extend(bitmap);
1004        bytes.extend([0, 0]); // bmControls and iMixer
1005        MixerUnit::parse(3, &bytes, inputs)
1006    }
1007
1008    fn inventory() -> RoutingInventory {
1009        let mut result = RoutingInventory::default();
1010        for id in [7, 8] {
1011            result
1012                .insert(RoutingUnit::Selector(selector(3, id, 3)))
1013                .unwrap();
1014        }
1015        result
1016            .insert(RoutingUnit::Mixer(
1017                mixer(
1018                    &[InputCluster {
1019                        source_id: 1,
1020                        channels: 2,
1021                    }],
1022                    2,
1023                    &[0x90],
1024                )
1025                .unwrap(),
1026            ))
1027            .unwrap();
1028        result
1029    }
1030
1031    fn select(id: u8, pin: u8) -> RouteChange {
1032        RouteChange {
1033            key: ControlKey::Selector(Entity { interface: 3, id }),
1034            value: RouteValue::SelectorPin(pin),
1035        }
1036    }
1037
1038    #[derive(Default)]
1039    struct MockIo {
1040        current: BTreeMap<(u16, u16), Vec<u8>>,
1041        reads: Vec<ControlRequest>,
1042        writes: Vec<(ControlRequest, Vec<u8>)>,
1043        range: Vec<u8>,
1044        fail_writes: Vec<usize>,
1045        ignore_writes: Vec<usize>,
1046        short_reads: bool,
1047    }
1048
1049    impl MockIo {
1050        fn selectors() -> Self {
1051            Self {
1052                current: BTreeMap::from([((0x0703, 0x0100), vec![1]), ((0x0803, 0x0100), vec![1])]),
1053                ..Self::default()
1054            }
1055        }
1056    }
1057
1058    impl RoutingIo for MockIo {
1059        type Error = &'static str;
1060        fn read(&mut self, request: ControlRequest, data: &mut [u8]) -> Result<usize, Self::Error> {
1061            self.reads.push(request);
1062            assert_eq!(request.request_type, 0xa1);
1063            assert_eq!(usize::from(request.length), data.len());
1064            if self.short_reads {
1065                return Ok(0);
1066            }
1067            let value = if request.request == 2 {
1068                &self.range
1069            } else {
1070                self.current
1071                    .get(&(request.index, request.value))
1072                    .ok_or("missing")?
1073            };
1074            let len = data.len().min(value.len());
1075            data[..len].copy_from_slice(&value[..len]);
1076            Ok(len)
1077        }
1078        fn write(&mut self, request: ControlRequest, data: &[u8]) -> Result<usize, Self::Error> {
1079            assert_eq!(request.request_type, 0x21);
1080            assert_eq!(request.request, 1);
1081            self.writes.push((request, data.to_vec()));
1082            let ordinal = self.writes.len();
1083            if !self.ignore_writes.contains(&ordinal) {
1084                self.current
1085                    .insert((request.index, request.value), data.to_vec());
1086            }
1087            // Deliberately fail after applying the hardware write.
1088            if self.fail_writes.contains(&ordinal) {
1089                return Err("write failed");
1090            }
1091            Ok(data.len())
1092        }
1093    }
1094
1095    #[test]
1096    fn selector_uses_one_based_pin_and_ac_interface_in_request() {
1097        let control = inventory().control(select(7, 2).key).unwrap();
1098        assert_eq!(
1099            control.current_request().unwrap(),
1100            ControlRequest {
1101                request_type: 0xa1,
1102                request: 1,
1103                value: 0x0100,
1104                index: 0x0703,
1105                length: 1
1106            }
1107        );
1108        let (request, bytes) = control.write_request(RouteValue::SelectorPin(2)).unwrap();
1109        assert_eq!(request.request_type, 0x21);
1110        assert_eq!(bytes, vec![2]);
1111        for pin in [0, 3, 255] {
1112            assert_eq!(
1113                control.write_request(RouteValue::SelectorPin(pin)),
1114                Err(InvalidRoute::InvalidPin)
1115            );
1116        }
1117        assert_eq!(
1118            control.write_request(RouteValue::MixerGain(0)),
1119            Err(InvalidRoute::WrongValueType)
1120        );
1121        assert_eq!(
1122            inventory().control(ControlKey::Selector(Entity {
1123                interface: 4,
1124                id: 7
1125            })),
1126            Err(InvalidRoute::UnknownControl)
1127        );
1128    }
1129
1130    #[test]
1131    fn selector_permissions_and_descriptor_bounds() {
1132        for flags in [2, 4, 255] {
1133            assert_eq!(
1134                SelectorUnit::parse(0, &[9, 0x24, 5, 7, 2, 1, 2, flags, 0]),
1135                Err(InvalidRoute::ReservedCapability)
1136            );
1137        }
1138        for bytes in [
1139            &[5, 0x24, 5, 7, 255][..],
1140            &[8, 0x24, 5, 7, 1, 0, 3, 0][..],
1141            &[8, 0x24, 5, 0, 1, 1, 3, 0][..],
1142            &[7, 0x24, 5, 7, 0, 3, 0][..],
1143        ] {
1144            assert_eq!(
1145                SelectorUnit::parse(0, bytes),
1146                Err(InvalidRoute::MalformedDescriptor)
1147            );
1148        }
1149        for (flags, expected) in [
1150            (0, Access::Absent),
1151            (1, Access::ReadOnly),
1152            (3, Access::ReadWrite),
1153        ] {
1154            let mut inv = RoutingInventory::default();
1155            inv.insert(RoutingUnit::Selector(selector(3, 7, flags)))
1156                .unwrap();
1157            let control = inv.control(select(7, 1).key).unwrap();
1158            assert_eq!(control.access(), expected);
1159            if flags != 3 {
1160                assert_eq!(
1161                    control.write_request(RouteValue::SelectorPin(1)),
1162                    Err(InvalidRoute::NotWritable)
1163                );
1164            }
1165            if flags == 0 {
1166                assert_eq!(control.current_request(), Err(InvalidRoute::NotReadable));
1167            }
1168        }
1169    }
1170
1171    #[test]
1172    fn mixer_uses_msb_bitmap_and_flattened_zero_based_mcn() {
1173        let inputs = [
1174            InputCluster {
1175                source_id: 1,
1176                channels: 2,
1177            },
1178            InputCluster {
1179                source_id: 2,
1180                channels: 1,
1181            },
1182        ];
1183        let unit = mixer(&inputs, 3, &[0x80, 0x80]).unwrap();
1184        let first = unit.crosspoint(1, 1, 1).unwrap();
1185        assert_eq!(first.access(), Access::ReadWrite);
1186        assert_eq!(first.current_request().unwrap().value, 0x0100);
1187        let last = unit.crosspoint(2, 1, 3).unwrap();
1188        assert_eq!(last.access(), Access::ReadWrite);
1189        assert_eq!(last.current_request().unwrap().value, 0x0108);
1190        assert_eq!(last.current_request().unwrap().index, 0x0903);
1191        let fixed = unit.crosspoint(1, 1, 2).unwrap();
1192        assert_eq!(fixed.access(), Access::ReadOnly);
1193        assert!(fixed.current_request().is_ok());
1194        assert_eq!(
1195            fixed.write_request(RouteValue::MixerGain(0)),
1196            Err(InvalidRoute::NotWritable)
1197        );
1198        assert_eq!(
1199            last.write_request(RouteValue::MixerGain(-256)).unwrap().1,
1200            vec![0, 255]
1201        );
1202        assert_eq!(
1203            last.write_request(RouteValue::MixerGain(i16::MIN))
1204                .unwrap()
1205                .1,
1206            vec![0, 128]
1207        );
1208        for (pin, channel, output) in [
1209            (0, 1, 1),
1210            (3, 1, 1),
1211            (2, 2, 1),
1212            (1, 0, 1),
1213            (1, 1, 0),
1214            (1, 1, 4),
1215        ] {
1216            assert_eq!(
1217                unit.crosspoint(pin, channel, output),
1218                Err(InvalidRoute::UnknownControl)
1219            );
1220        }
1221    }
1222
1223    #[test]
1224    fn mixer_refuses_unproven_geometry_padding_and_overflow() {
1225        let inputs = [InputCluster {
1226            source_id: 1,
1227            channels: 2,
1228        }];
1229        assert_eq!(
1230            mixer(&inputs, 2, &[]),
1231            Err(InvalidRoute::MalformedDescriptor)
1232        );
1233        assert_eq!(
1234            mixer(&inputs, 2, &[0xff]),
1235            Err(InvalidRoute::MalformedDescriptor)
1236        );
1237        assert_eq!(
1238            mixer(
1239                &[InputCluster {
1240                    source_id: 1,
1241                    channels: 0
1242                }],
1243                2,
1244                &[0]
1245            ),
1246            Err(InvalidRoute::UnknownInputChannels)
1247        );
1248        assert_eq!(
1249            mixer(
1250                &[InputCluster {
1251                    source_id: 1,
1252                    channels: 129
1253                }],
1254                2,
1255                &[0; 33]
1256            ),
1257            Err(InvalidRoute::TooManyCrosspoints)
1258        );
1259        let max = mixer(
1260            &[InputCluster {
1261                source_id: 1,
1262                channels: 16,
1263            }],
1264            16,
1265            &[255; 32],
1266        )
1267        .unwrap();
1268        assert_eq!(
1269            max.crosspoint(1, 16, 16)
1270                .unwrap()
1271                .current_request()
1272                .unwrap()
1273                .value,
1274            0x01ff
1275        );
1276        let bytes = [15, 0x24, 4, 9, 1, 1, 2, 0, 0, 0, 0, 0, 0xf0, 0, 0];
1277        assert_eq!(
1278            MixerUnit::parse(
1279                3,
1280                &bytes,
1281                &[InputCluster {
1282                    source_id: 2,
1283                    channels: 2
1284                }]
1285            ),
1286            Err(InvalidRoute::UnknownInputChannels)
1287        );
1288        let mut reserved = bytes;
1289        reserved[13] = 2;
1290        assert_eq!(
1291            MixerUnit::parse(3, &reserved, &inputs),
1292            Err(InvalidRoute::ReservedCapability)
1293        );
1294    }
1295
1296    #[test]
1297    fn gain_ranges_are_signed_bounded_and_validate_steps() {
1298        let ranges = decode_gain_ranges(&[1, 0, 0, 254, 0, 0, 0, 1]).unwrap();
1299        assert!(ranges[0].contains(-256));
1300        assert!(ranges[0].contains(i16::MIN));
1301        assert!(!ranges[0].contains(-255));
1302        assert!(!ranges[0].contains(256));
1303        for bytes in [
1304            &[0, 0][..],
1305            &[65, 0][..],
1306            &[1, 0, 0, 128, 0, 0, 1, 0][..],
1307            &[1, 0, 0, 0, 0, 0, 0, 0][..],
1308            &[1, 0, 0, 0, 0, 255, 1, 0][..],
1309            &[1, 0][..],
1310        ] {
1311            assert_eq!(decode_gain_ranges(bytes), Err(InvalidRoute::InvalidRange));
1312        }
1313    }
1314
1315    #[test]
1316    fn grouped_changes_verify_readback_and_leave_current_route_untouched() {
1317        let mut io = MockIo::selectors();
1318        let report = apply_routes(&inventory(), &mut io, &[select(7, 1), select(8, 2)]).unwrap();
1319        assert_eq!(report.unchanged, vec![select(7, 1).key]);
1320        assert_eq!(report.changed, vec![select(8, 2).key]);
1321        assert_eq!(io.writes.len(), 1);
1322        assert_eq!(io.reads.len(), 3); // two originals and verified write
1323    }
1324
1325    #[test]
1326    fn rejected_plan_does_not_write_any_control() {
1327        struct PlanProbe(MockIo);
1328        impl RoutingIo for PlanProbe {
1329            type Error = &'static str;
1330            fn read(
1331                &mut self,
1332                request: ControlRequest,
1333                data: &mut [u8],
1334            ) -> Result<usize, Self::Error> {
1335                self.0.read(request, data)
1336            }
1337            fn write(
1338                &mut self,
1339                request: ControlRequest,
1340                data: &[u8],
1341            ) -> Result<usize, Self::Error> {
1342                self.0.write(request, data)
1343            }
1344            fn admit_plan(&mut self, changed: usize) -> Result<(), Self::Error> {
1345                assert_eq!(changed, 2);
1346                Err("plan deadline")
1347            }
1348        }
1349        let mut io = PlanProbe(MockIo::selectors());
1350        let result =
1351            apply_routes(&inventory(), &mut io, &[select(7, 2), select(8, 2)]).unwrap_err();
1352        assert_eq!(result.cause, RoutingError::Io("plan deadline"));
1353        assert!(io.0.writes.is_empty());
1354    }
1355
1356    #[test]
1357    fn admission_failure_restores_previous_writes_and_preserves_cause() {
1358        struct AdmissionProbe {
1359            inner: MockIo,
1360            admitted: usize,
1361            recovered: usize,
1362        }
1363        impl RoutingIo for AdmissionProbe {
1364            type Error = &'static str;
1365            fn read(
1366                &mut self,
1367                request: ControlRequest,
1368                data: &mut [u8],
1369            ) -> Result<usize, Self::Error> {
1370                self.inner.read(request, data)
1371            }
1372            fn write(
1373                &mut self,
1374                request: ControlRequest,
1375                data: &[u8],
1376            ) -> Result<usize, Self::Error> {
1377                self.inner.write(request, data)
1378            }
1379            fn admit_write(&mut self) -> Result<(), Self::Error> {
1380                self.admitted += 1;
1381                if self.admitted == 2 {
1382                    Err("deadline")
1383                } else {
1384                    Ok(())
1385                }
1386            }
1387            fn begin_recovery_for(&mut self, attempted: usize) {
1388                self.recovered = attempted;
1389            }
1390        }
1391        let mut io = AdmissionProbe {
1392            inner: MockIo::selectors(),
1393            admitted: 0,
1394            recovered: 0,
1395        };
1396        let failure =
1397            apply_routes(&inventory(), &mut io, &[select(7, 2), select(8, 2)]).unwrap_err();
1398        assert_eq!(failure.cause, RoutingError::Io("deadline"));
1399        assert!(failure.rollback_failures.is_empty());
1400        assert_eq!(io.recovered, 1);
1401        assert_eq!(
1402            io.inner
1403                .writes
1404                .iter()
1405                .map(|(r, b)| (r.index, b[0]))
1406                .collect::<Vec<_>>(),
1407            vec![(0x0703, 2), (0x0703, 1)]
1408        );
1409    }
1410
1411    #[test]
1412    fn stalled_set_and_expired_rollback_report_every_attempt_without_more_writes() {
1413        struct DeadlineIo {
1414            inner: MockIo,
1415            recovering: bool,
1416        }
1417        impl RoutingIo for DeadlineIo {
1418            type Error = &'static str;
1419            fn read(
1420                &mut self,
1421                request: ControlRequest,
1422                data: &mut [u8],
1423            ) -> Result<usize, Self::Error> {
1424                if self.recovering {
1425                    return Err("deadline");
1426                }
1427                self.inner.read(request, data)
1428            }
1429            fn write(
1430                &mut self,
1431                request: ControlRequest,
1432                data: &[u8],
1433            ) -> Result<usize, Self::Error> {
1434                if self.recovering {
1435                    return Err("deadline");
1436                }
1437                self.inner.write(request, data)
1438            }
1439            fn begin_recovery_for(&mut self, _: usize) {
1440                self.recovering = true;
1441            }
1442        }
1443        let mut inner = MockIo::selectors();
1444        inner.fail_writes = vec![2];
1445        let mut io = DeadlineIo {
1446            inner,
1447            recovering: false,
1448        };
1449        let changes = [select(7, 2), select(8, 2)];
1450        let failure = apply_routes(&inventory(), &mut io, &changes).unwrap_err();
1451        assert_eq!(io.inner.writes.len(), 2);
1452        assert_eq!(
1453            failure
1454                .rollback_failures
1455                .iter()
1456                .map(|(key, _)| *key)
1457                .collect::<Vec<_>>(),
1458            vec![changes[1].key, changes[0].key]
1459        );
1460        assert!(failure
1461            .rollback_failures
1462            .iter()
1463            .all(|(_, error)| *error == RoutingError::Io("deadline")));
1464    }
1465
1466    #[test]
1467    fn failed_write_is_included_in_reverse_verified_rollback() {
1468        let mut io = MockIo::selectors();
1469        io.fail_writes = vec![2];
1470        let failure =
1471            apply_routes(&inventory(), &mut io, &[select(7, 2), select(8, 2)]).unwrap_err();
1472        assert_eq!(failure.failed_change, Some(1));
1473        assert_eq!(failure.cause, RoutingError::Io("write failed"));
1474        assert!(failure.rollback_failures.is_empty());
1475        assert_eq!(
1476            io.writes
1477                .iter()
1478                .map(|(r, b)| (r.index, b[0]))
1479                .collect::<Vec<_>>(),
1480            vec![(0x0703, 2), (0x0803, 2), (0x0803, 1), (0x0703, 1)]
1481        );
1482        assert_eq!(io.current[&(0x0703, 0x0100)], vec![1]);
1483        assert_eq!(io.current[&(0x0803, 0x0100)], vec![1]);
1484    }
1485
1486    #[test]
1487    fn trace_retains_actual_prewrite_values_for_failed_and_uncertain_sets() {
1488        let mut io = MockIo::selectors();
1489        io.fail_writes = vec![2, 3];
1490        let edits = [select(7, 2), select(8, 2)];
1491        let mut trace = Vec::new();
1492        let error = apply_routes_traced(&inventory(), &mut io, &edits, &mut trace).unwrap_err();
1493        assert_eq!(
1494            trace,
1495            vec![
1496                (
1497                    edits[0].key,
1498                    RouteValue::SelectorPin(1),
1499                    RouteValue::SelectorPin(2)
1500                ),
1501                (
1502                    edits[1].key,
1503                    RouteValue::SelectorPin(1),
1504                    RouteValue::SelectorPin(2)
1505                ),
1506            ]
1507        );
1508        assert_eq!(error.rollback_failures[0].0, edits[1].key);
1509    }
1510
1511    #[test]
1512    fn mismatched_readback_restores_attempted_control() {
1513        let mut io = MockIo::selectors();
1514        io.ignore_writes = vec![1];
1515        let failure = apply_routes(&inventory(), &mut io, &[select(7, 2)]).unwrap_err();
1516        assert_eq!(
1517            failure.cause,
1518            RoutingError::ReadbackMismatch {
1519                expected: RouteValue::SelectorPin(2),
1520                actual: RouteValue::SelectorPin(1)
1521            }
1522        );
1523        assert!(failure.rollback_failures.is_empty());
1524        assert_eq!(io.writes.len(), 2);
1525    }
1526
1527    #[test]
1528    fn rollback_failures_are_reported_and_remaining_restores_continue() {
1529        let mut io = MockIo::selectors();
1530        io.fail_writes = vec![2, 3];
1531        let failure =
1532            apply_routes(&inventory(), &mut io, &[select(7, 2), select(8, 2)]).unwrap_err();
1533        assert_eq!(
1534            failure.rollback_failures,
1535            vec![(select(8, 2).key, RoutingError::Io("write failed"))]
1536        );
1537        assert_eq!(io.writes.len(), 4);
1538    }
1539
1540    #[test]
1541    fn invalid_batches_and_short_original_reads_never_write() {
1542        let mut io = MockIo::selectors();
1543        let inv = inventory();
1544        for changes in [
1545            vec![select(7, 2), select(8, 0)],
1546            vec![select(7, 2), select(7, 1)],
1547            vec![select(7, 2); MAX_ROUTE_CHANGES + 1],
1548        ] {
1549            assert!(apply_routes(&inv, &mut io, &changes).is_err());
1550            assert!(io.reads.is_empty());
1551            assert!(io.writes.is_empty());
1552        }
1553        io.short_reads = true;
1554        let failure = apply_routes(&inv, &mut io, &[select(7, 2)]).unwrap_err();
1555        assert_eq!(
1556            failure.cause,
1557            RoutingError::TransferLength {
1558                expected: 1,
1559                actual: 0
1560            }
1561        );
1562        assert!(io.writes.is_empty());
1563    }
1564
1565    #[test]
1566    fn raw_restore_replays_off_grid_cur_and_detects_mismatch() {
1567        let inv = inventory();
1568        let key = ControlKey::Crosspoint {
1569            entity: Entity {
1570                interface: 3,
1571                id: 9,
1572            },
1573            input_pin: 1,
1574            input_channel: 1,
1575            output_channel: 1,
1576        };
1577        let mut io = MockIo {
1578            current: BTreeMap::from([((0x0903, 0x0100), (-256i16).to_le_bytes().to_vec())]),
1579            range: vec![1, 0, 0, 254, 0, 0, 0, 1],
1580            ..MockIo::default()
1581        };
1582        let control = inv.control(key).unwrap();
1583        write_verified(&mut io, control, RouteValue::MixerGain(-255)).unwrap();
1584        assert_eq!(io.current[&(0x0903, 0x0100)], (-255i16).to_le_bytes());
1585        io.ignore_writes = vec![2];
1586        assert!(matches!(
1587            write_verified(&mut io, control, RouteValue::MixerGain(-256)),
1588            Err(RoutingError::ReadbackMismatch { .. })
1589        ));
1590    }
1591
1592    #[test]
1593    fn mixer_transaction_checks_live_range_before_writing() {
1594        let inv = inventory();
1595        let key = ControlKey::Crosspoint {
1596            entity: Entity {
1597                interface: 3,
1598                id: 9,
1599            },
1600            input_pin: 1,
1601            input_channel: 1,
1602            output_channel: 1,
1603        };
1604        let mut io = MockIo {
1605            current: BTreeMap::from([((0x0903, 0x0100), vec![0, 0])]),
1606            range: vec![1, 0, 0, 254, 0, 0, 0, 1],
1607            ..MockIo::default()
1608        };
1609        let failure = apply_routes(
1610            &inv,
1611            &mut io,
1612            &[RouteChange {
1613                key,
1614                value: RouteValue::MixerGain(-255),
1615            }],
1616        )
1617        .unwrap_err();
1618        assert_eq!(
1619            failure.cause,
1620            RoutingError::Invalid(InvalidRoute::GainOutsideRange)
1621        );
1622        assert!(io.writes.is_empty());
1623        apply_routes(
1624            &inv,
1625            &mut io,
1626            &[RouteChange {
1627                key,
1628                value: RouteValue::MixerGain(-256),
1629            }],
1630        )
1631        .unwrap();
1632        assert_eq!(io.writes[0].1, vec![0, 255]);
1633        assert!(io.reads.iter().any(|r| r.request == 2 && r.length == 2));
1634        assert!(io.reads.iter().any(|r| r.request == 2 && r.length == 8));
1635    }
1636}