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, 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    fn begin_recovery(&mut self) {}
674}
675
676#[derive(Debug, PartialEq, Eq)]
677pub enum RoutingError<E> {
678    Invalid(InvalidRoute),
679    Io(E),
680    TransferLength {
681        expected: usize,
682        actual: usize,
683    },
684    ReadbackMismatch {
685        expected: RouteValue,
686        actual: RouteValue,
687    },
688}
689
690#[derive(Debug)]
691pub struct TransactionError<E> {
692    pub failed_change: Option<usize>,
693    pub cause: RoutingError<E>,
694    /// Empty means every attempted write was restored and verified, or no write
695    /// was attempted. Nonempty means hardware state is uncertain for these keys.
696    pub rollback_failures: Vec<(ControlKey, RoutingError<E>)>,
697}
698
699#[derive(Debug, Default, PartialEq, Eq)]
700pub struct RouteReport {
701    pub changed: Vec<ControlKey>,
702    pub unchanged: Vec<ControlKey>,
703}
704
705fn read_exact<I: RoutingIo>(
706    io: &mut I,
707    request: ControlRequest,
708    data: &mut [u8],
709) -> Result<(), RoutingError<I::Error>> {
710    let actual = io.read(request, data).map_err(RoutingError::Io)?;
711    if actual != data.len() {
712        return Err(RoutingError::TransferLength {
713            expected: data.len(),
714            actual,
715        });
716    }
717    Ok(())
718}
719
720pub(crate) fn write_verified<I: RoutingIo>(
721    io: &mut I,
722    control: RouteControl,
723    value: RouteValue,
724) -> Result<(), RoutingError<I::Error>> {
725    let (request, bytes) = control
726        .write_request(value)
727        .map_err(RoutingError::Invalid)?;
728    let actual = io.write(request, &bytes).map_err(RoutingError::Io)?;
729    if actual != bytes.len() {
730        return Err(RoutingError::TransferLength {
731            expected: bytes.len(),
732            actual,
733        });
734    }
735    let readback = control.read_current(io)?;
736    if readback != value {
737        return Err(RoutingError::ReadbackMismatch {
738            expected: value,
739            actual: readback,
740        });
741    }
742    Ok(())
743}
744
745/// Preflight all keys, permissions, original values and mixer ranges before any
746/// write. Apply changes in order, verify every write, and on failure restore all
747/// attempted controls in reverse order with readback. This is best-effort USB
748/// rollback, not device-side atomicity. Stop/reconfigure affected streams first.
749pub fn apply_routes<I: RoutingIo>(
750    inventory: &RoutingInventory,
751    io: &mut I,
752    changes: &[RouteChange],
753) -> Result<RouteReport, TransactionError<I::Error>> {
754    apply_routes_traced(inventory, io, changes, &mut Vec::new())
755}
756
757/// Actual CUR and attempted target for each SET, including ambiguous failures.
758pub(crate) fn apply_routes_traced<I: RoutingIo>(
759    inventory: &RoutingInventory,
760    io: &mut I,
761    changes: &[RouteChange],
762    attempted_values: &mut Vec<(ControlKey, RouteValue, RouteValue)>,
763) -> Result<RouteReport, TransactionError<I::Error>> {
764    let error = |index, cause| TransactionError {
765        failed_change: index,
766        cause,
767        rollback_failures: Vec::new(),
768    };
769    if changes.len() > MAX_ROUTE_CHANGES {
770        return Err(error(
771            None,
772            RoutingError::Invalid(InvalidRoute::TooManyChanges),
773        ));
774    }
775    let mut controls = Vec::with_capacity(changes.len());
776    // Validate the entire request before touching USB, even for read-only I/O.
777    for (i, change) in changes.iter().enumerate() {
778        if changes[..i].iter().any(|prior| prior.key == change.key) {
779            return Err(error(
780                Some(i),
781                RoutingError::Invalid(InvalidRoute::DuplicateChange),
782            ));
783        }
784        let control = inventory
785            .control(change.key)
786            .map_err(|e| error(Some(i), RoutingError::Invalid(e)))?;
787        control
788            .write_request(change.value)
789            .map_err(|e| error(Some(i), RoutingError::Invalid(e)))?;
790        controls.push(control);
791    }
792    let mut originals = Vec::with_capacity(changes.len());
793    for (i, (control, change)) in controls.iter().zip(changes).enumerate() {
794        let original = control.read_current(io).map_err(|e| error(Some(i), e))?;
795        if let RouteValue::MixerGain(gain) = change.value {
796            let ranges = control
797                .read_gain_ranges(io)
798                .map_err(|e| error(Some(i), e))?;
799            if !ranges.iter().any(|range| range.contains(gain)) {
800                return Err(error(
801                    Some(i),
802                    RoutingError::Invalid(InvalidRoute::GainOutsideRange),
803                ));
804            }
805        }
806        originals.push(original);
807    }
808    let mut report = RouteReport::default();
809    let mut attempted = Vec::new();
810    for (i, ((control, change), original)) in
811        controls.iter().zip(changes).zip(&originals).enumerate()
812    {
813        if change.value == *original {
814            report.unchanged.push(change.key);
815            continue;
816        }
817        attempted.push(i);
818        attempted_values.push((change.key, *original, change.value));
819        if let Err(cause) = write_verified(io, *control, change.value) {
820            let mut failure = error(Some(i), cause);
821            io.begin_recovery();
822            for &j in attempted.iter().rev() {
823                if let Err(e) = write_verified(io, controls[j], originals[j]) {
824                    failure.rollback_failures.push((changes[j].key, e));
825                }
826            }
827            return Err(failure);
828        }
829        report.changed.push(change.key);
830    }
831    Ok(report)
832}
833
834#[cfg(test)]
835mod tests {
836    use super::*;
837
838    #[test]
839    fn uac1_selector_and_crosspoint_use_legacy_setup_and_separate_ranges() {
840        let selector = SelectorUnit::parse_uac1(3, &[8, 0x24, 5, 7, 2, 1, 2, 0]).unwrap();
841        let mut inventory = RoutingInventory::default();
842        inventory.insert(RoutingUnit::Selector(selector)).unwrap();
843        let control = inventory
844            .control(ControlKey::Selector(Entity {
845                interface: 3,
846                id: 7,
847            }))
848            .unwrap();
849        let current = control.current_request().unwrap();
850        assert_eq!(
851            (current.request, current.value, current.length),
852            (0x81, 0, 1)
853        );
854        assert_eq!(
855            control
856                .write_request(RouteValue::SelectorPin(2))
857                .unwrap()
858                .0
859                .value,
860            0
861        );
862        let inputs = [
863            InputCluster {
864                source_id: 1,
865                channels: 1,
866            },
867            InputCluster {
868                source_id: 2,
869                channels: 1,
870            },
871        ];
872        let mixer =
873            MixerUnit::parse_uac1(3, &[13, 0x24, 4, 9, 2, 1, 2, 2, 3, 0, 0, 0xf0, 0], &inputs)
874                .unwrap();
875        let point = mixer.crosspoint(2, 1, 2).unwrap();
876        assert_eq!(point.current_request().unwrap().value, 0x0202);
877        struct LegacyIo {
878            requests: Vec<u8>,
879        }
880        impl RoutingIo for LegacyIo {
881            type Error = ();
882            fn read(&mut self, request: ControlRequest, bytes: &mut [u8]) -> Result<usize, ()> {
883                self.requests.push(request.request);
884                assert_eq!(request.value, 0x0202);
885                let value: i16 = match request.request {
886                    0x82 => -1024,
887                    0x83 => 0,
888                    0x84 => 256,
889                    _ => panic!("unexpected legacy request"),
890                };
891                bytes.copy_from_slice(&value.to_le_bytes());
892                Ok(bytes.len())
893            }
894            fn write(&mut self, _: ControlRequest, _: &[u8]) -> Result<usize, ()> {
895                panic!("range query wrote hardware")
896            }
897        }
898        let mut io = LegacyIo { requests: vec![] };
899        let ranges = point.read_gain_ranges(&mut io).unwrap();
900        assert_eq!(io.requests, [0x82, 0x83, 0x84]);
901        assert!(ranges[0].contains(-512));
902        assert!(!ranges[0].contains(-500));
903    }
904
905    #[test]
906    fn adc3_routes_use_full_access_words_mcn_and_layout_widths() {
907        let mut inventory = RoutingInventory::default();
908        inventory
909            .insert(RoutingUnit::Selector(
910                SelectorUnit::parse_adc3(3, &[13, 0x24, 6, 7, 2, 1, 2, 3, 0, 0, 0, 0, 0]).unwrap(),
911            ))
912            .unwrap();
913        let control = inventory
914            .control(ControlKey::Selector(Entity {
915                interface: 3,
916                id: 7,
917            }))
918            .unwrap();
919        assert_eq!(
920            (
921                control.current_request().unwrap().value,
922                control.current_request().unwrap().length
923            ),
924            (0x0100, 1)
925        );
926        assert!(SelectorUnit::parse_adc3(3, &[12, 0x24, 6, 7, 1, 1, 3, 0, 0, 1, 0, 0]).is_err());
927        let inputs = [InputCluster {
928            source_id: 1,
929            channels: 2,
930        }];
931        let mut bytes = vec![15, 0x24, 5, 9, 1, 1, 42, 0, 0x90, 0, 0, 0, 0, 0, 0];
932        let mixer = MixerUnit::parse_adc3(3, &bytes, &inputs, 2).unwrap();
933        let point = mixer.crosspoint(1, 2, 2).unwrap();
934        assert_eq!(
935            (
936                point.current_request().unwrap().value,
937                point.current_request().unwrap().length
938            ),
939            (0x0103, 2)
940        );
941        assert_eq!(
942            point.write_request(RouteValue::MixerGain(-512)).unwrap().1,
943            (-512i16).to_le_bytes()
944        );
945        assert_eq!(
946            mixer.crosspoint(1, 1, 2).unwrap().access(),
947            Access::ReadOnly
948        );
949        bytes[12] = 1; // reserved bit in the high byte of bmControls
950        assert!(MixerUnit::parse_adc3(3, &bytes, &inputs, 2).is_err());
951        assert!(MixerUnit::parse_adc3(3, &bytes[..7], &inputs, 2).is_err());
952    }
953
954    fn selector(interface: u8, id: u8, flags: u8) -> SelectorUnit {
955        SelectorUnit::parse(interface, &[9, 0x24, 5, id, 2, 1, 2, flags, 0]).unwrap()
956    }
957
958    fn mixer(
959        inputs: &[InputCluster],
960        outputs: u8,
961        bitmap: &[u8],
962    ) -> Result<MixerUnit, InvalidRoute> {
963        let mut bytes = vec![
964            (13 + inputs.len() + bitmap.len()) as u8,
965            0x24,
966            4,
967            9,
968            inputs.len() as u8,
969        ];
970        bytes.extend(inputs.iter().map(|c| c.source_id));
971        bytes.push(outputs);
972        bytes.extend([0, 0, 0, 0, 0]); // channel config and names
973        bytes.extend(bitmap);
974        bytes.extend([0, 0]); // bmControls and iMixer
975        MixerUnit::parse(3, &bytes, inputs)
976    }
977
978    fn inventory() -> RoutingInventory {
979        let mut result = RoutingInventory::default();
980        for id in [7, 8] {
981            result
982                .insert(RoutingUnit::Selector(selector(3, id, 3)))
983                .unwrap();
984        }
985        result
986            .insert(RoutingUnit::Mixer(
987                mixer(
988                    &[InputCluster {
989                        source_id: 1,
990                        channels: 2,
991                    }],
992                    2,
993                    &[0x90],
994                )
995                .unwrap(),
996            ))
997            .unwrap();
998        result
999    }
1000
1001    fn select(id: u8, pin: u8) -> RouteChange {
1002        RouteChange {
1003            key: ControlKey::Selector(Entity { interface: 3, id }),
1004            value: RouteValue::SelectorPin(pin),
1005        }
1006    }
1007
1008    #[derive(Default)]
1009    struct MockIo {
1010        current: BTreeMap<(u16, u16), Vec<u8>>,
1011        reads: Vec<ControlRequest>,
1012        writes: Vec<(ControlRequest, Vec<u8>)>,
1013        range: Vec<u8>,
1014        fail_writes: Vec<usize>,
1015        ignore_writes: Vec<usize>,
1016        short_reads: bool,
1017    }
1018
1019    impl MockIo {
1020        fn selectors() -> Self {
1021            Self {
1022                current: BTreeMap::from([((0x0703, 0x0100), vec![1]), ((0x0803, 0x0100), vec![1])]),
1023                ..Self::default()
1024            }
1025        }
1026    }
1027
1028    impl RoutingIo for MockIo {
1029        type Error = &'static str;
1030        fn read(&mut self, request: ControlRequest, data: &mut [u8]) -> Result<usize, Self::Error> {
1031            self.reads.push(request);
1032            assert_eq!(request.request_type, 0xa1);
1033            assert_eq!(usize::from(request.length), data.len());
1034            if self.short_reads {
1035                return Ok(0);
1036            }
1037            let value = if request.request == 2 {
1038                &self.range
1039            } else {
1040                self.current
1041                    .get(&(request.index, request.value))
1042                    .ok_or("missing")?
1043            };
1044            let len = data.len().min(value.len());
1045            data[..len].copy_from_slice(&value[..len]);
1046            Ok(len)
1047        }
1048        fn write(&mut self, request: ControlRequest, data: &[u8]) -> Result<usize, Self::Error> {
1049            assert_eq!(request.request_type, 0x21);
1050            assert_eq!(request.request, 1);
1051            self.writes.push((request, data.to_vec()));
1052            let ordinal = self.writes.len();
1053            if !self.ignore_writes.contains(&ordinal) {
1054                self.current
1055                    .insert((request.index, request.value), data.to_vec());
1056            }
1057            // Deliberately fail after applying the hardware write.
1058            if self.fail_writes.contains(&ordinal) {
1059                return Err("write failed");
1060            }
1061            Ok(data.len())
1062        }
1063    }
1064
1065    #[test]
1066    fn selector_uses_one_based_pin_and_ac_interface_in_request() {
1067        let control = inventory().control(select(7, 2).key).unwrap();
1068        assert_eq!(
1069            control.current_request().unwrap(),
1070            ControlRequest {
1071                request_type: 0xa1,
1072                request: 1,
1073                value: 0x0100,
1074                index: 0x0703,
1075                length: 1
1076            }
1077        );
1078        let (request, bytes) = control.write_request(RouteValue::SelectorPin(2)).unwrap();
1079        assert_eq!(request.request_type, 0x21);
1080        assert_eq!(bytes, vec![2]);
1081        for pin in [0, 3, 255] {
1082            assert_eq!(
1083                control.write_request(RouteValue::SelectorPin(pin)),
1084                Err(InvalidRoute::InvalidPin)
1085            );
1086        }
1087        assert_eq!(
1088            control.write_request(RouteValue::MixerGain(0)),
1089            Err(InvalidRoute::WrongValueType)
1090        );
1091        assert_eq!(
1092            inventory().control(ControlKey::Selector(Entity {
1093                interface: 4,
1094                id: 7
1095            })),
1096            Err(InvalidRoute::UnknownControl)
1097        );
1098    }
1099
1100    #[test]
1101    fn selector_permissions_and_descriptor_bounds() {
1102        for flags in [2, 4, 255] {
1103            assert_eq!(
1104                SelectorUnit::parse(0, &[9, 0x24, 5, 7, 2, 1, 2, flags, 0]),
1105                Err(InvalidRoute::ReservedCapability)
1106            );
1107        }
1108        for bytes in [
1109            &[5, 0x24, 5, 7, 255][..],
1110            &[8, 0x24, 5, 7, 1, 0, 3, 0][..],
1111            &[8, 0x24, 5, 0, 1, 1, 3, 0][..],
1112            &[7, 0x24, 5, 7, 0, 3, 0][..],
1113        ] {
1114            assert_eq!(
1115                SelectorUnit::parse(0, bytes),
1116                Err(InvalidRoute::MalformedDescriptor)
1117            );
1118        }
1119        for (flags, expected) in [
1120            (0, Access::Absent),
1121            (1, Access::ReadOnly),
1122            (3, Access::ReadWrite),
1123        ] {
1124            let mut inv = RoutingInventory::default();
1125            inv.insert(RoutingUnit::Selector(selector(3, 7, flags)))
1126                .unwrap();
1127            let control = inv.control(select(7, 1).key).unwrap();
1128            assert_eq!(control.access(), expected);
1129            if flags != 3 {
1130                assert_eq!(
1131                    control.write_request(RouteValue::SelectorPin(1)),
1132                    Err(InvalidRoute::NotWritable)
1133                );
1134            }
1135            if flags == 0 {
1136                assert_eq!(control.current_request(), Err(InvalidRoute::NotReadable));
1137            }
1138        }
1139    }
1140
1141    #[test]
1142    fn mixer_uses_msb_bitmap_and_flattened_zero_based_mcn() {
1143        let inputs = [
1144            InputCluster {
1145                source_id: 1,
1146                channels: 2,
1147            },
1148            InputCluster {
1149                source_id: 2,
1150                channels: 1,
1151            },
1152        ];
1153        let unit = mixer(&inputs, 3, &[0x80, 0x80]).unwrap();
1154        let first = unit.crosspoint(1, 1, 1).unwrap();
1155        assert_eq!(first.access(), Access::ReadWrite);
1156        assert_eq!(first.current_request().unwrap().value, 0x0100);
1157        let last = unit.crosspoint(2, 1, 3).unwrap();
1158        assert_eq!(last.access(), Access::ReadWrite);
1159        assert_eq!(last.current_request().unwrap().value, 0x0108);
1160        assert_eq!(last.current_request().unwrap().index, 0x0903);
1161        let fixed = unit.crosspoint(1, 1, 2).unwrap();
1162        assert_eq!(fixed.access(), Access::ReadOnly);
1163        assert!(fixed.current_request().is_ok());
1164        assert_eq!(
1165            fixed.write_request(RouteValue::MixerGain(0)),
1166            Err(InvalidRoute::NotWritable)
1167        );
1168        assert_eq!(
1169            last.write_request(RouteValue::MixerGain(-256)).unwrap().1,
1170            vec![0, 255]
1171        );
1172        assert_eq!(
1173            last.write_request(RouteValue::MixerGain(i16::MIN))
1174                .unwrap()
1175                .1,
1176            vec![0, 128]
1177        );
1178        for (pin, channel, output) in [
1179            (0, 1, 1),
1180            (3, 1, 1),
1181            (2, 2, 1),
1182            (1, 0, 1),
1183            (1, 1, 0),
1184            (1, 1, 4),
1185        ] {
1186            assert_eq!(
1187                unit.crosspoint(pin, channel, output),
1188                Err(InvalidRoute::UnknownControl)
1189            );
1190        }
1191    }
1192
1193    #[test]
1194    fn mixer_refuses_unproven_geometry_padding_and_overflow() {
1195        let inputs = [InputCluster {
1196            source_id: 1,
1197            channels: 2,
1198        }];
1199        assert_eq!(
1200            mixer(&inputs, 2, &[]),
1201            Err(InvalidRoute::MalformedDescriptor)
1202        );
1203        assert_eq!(
1204            mixer(&inputs, 2, &[0xff]),
1205            Err(InvalidRoute::MalformedDescriptor)
1206        );
1207        assert_eq!(
1208            mixer(
1209                &[InputCluster {
1210                    source_id: 1,
1211                    channels: 0
1212                }],
1213                2,
1214                &[0]
1215            ),
1216            Err(InvalidRoute::UnknownInputChannels)
1217        );
1218        assert_eq!(
1219            mixer(
1220                &[InputCluster {
1221                    source_id: 1,
1222                    channels: 129
1223                }],
1224                2,
1225                &[0; 33]
1226            ),
1227            Err(InvalidRoute::TooManyCrosspoints)
1228        );
1229        let max = mixer(
1230            &[InputCluster {
1231                source_id: 1,
1232                channels: 16,
1233            }],
1234            16,
1235            &[255; 32],
1236        )
1237        .unwrap();
1238        assert_eq!(
1239            max.crosspoint(1, 16, 16)
1240                .unwrap()
1241                .current_request()
1242                .unwrap()
1243                .value,
1244            0x01ff
1245        );
1246        let bytes = [15, 0x24, 4, 9, 1, 1, 2, 0, 0, 0, 0, 0, 0xf0, 0, 0];
1247        assert_eq!(
1248            MixerUnit::parse(
1249                3,
1250                &bytes,
1251                &[InputCluster {
1252                    source_id: 2,
1253                    channels: 2
1254                }]
1255            ),
1256            Err(InvalidRoute::UnknownInputChannels)
1257        );
1258        let mut reserved = bytes;
1259        reserved[13] = 2;
1260        assert_eq!(
1261            MixerUnit::parse(3, &reserved, &inputs),
1262            Err(InvalidRoute::ReservedCapability)
1263        );
1264    }
1265
1266    #[test]
1267    fn gain_ranges_are_signed_bounded_and_validate_steps() {
1268        let ranges = decode_gain_ranges(&[1, 0, 0, 254, 0, 0, 0, 1]).unwrap();
1269        assert!(ranges[0].contains(-256));
1270        assert!(ranges[0].contains(i16::MIN));
1271        assert!(!ranges[0].contains(-255));
1272        assert!(!ranges[0].contains(256));
1273        for bytes in [
1274            &[0, 0][..],
1275            &[65, 0][..],
1276            &[1, 0, 0, 128, 0, 0, 1, 0][..],
1277            &[1, 0, 0, 0, 0, 0, 0, 0][..],
1278            &[1, 0, 0, 0, 0, 255, 1, 0][..],
1279            &[1, 0][..],
1280        ] {
1281            assert_eq!(decode_gain_ranges(bytes), Err(InvalidRoute::InvalidRange));
1282        }
1283    }
1284
1285    #[test]
1286    fn grouped_changes_verify_readback_and_leave_current_route_untouched() {
1287        let mut io = MockIo::selectors();
1288        let report = apply_routes(&inventory(), &mut io, &[select(7, 1), select(8, 2)]).unwrap();
1289        assert_eq!(report.unchanged, vec![select(7, 1).key]);
1290        assert_eq!(report.changed, vec![select(8, 2).key]);
1291        assert_eq!(io.writes.len(), 1);
1292        assert_eq!(io.reads.len(), 3); // two originals and verified write
1293    }
1294
1295    #[test]
1296    fn failed_write_is_included_in_reverse_verified_rollback() {
1297        let mut io = MockIo::selectors();
1298        io.fail_writes = vec![2];
1299        let failure =
1300            apply_routes(&inventory(), &mut io, &[select(7, 2), select(8, 2)]).unwrap_err();
1301        assert_eq!(failure.failed_change, Some(1));
1302        assert_eq!(failure.cause, RoutingError::Io("write failed"));
1303        assert!(failure.rollback_failures.is_empty());
1304        assert_eq!(
1305            io.writes
1306                .iter()
1307                .map(|(r, b)| (r.index, b[0]))
1308                .collect::<Vec<_>>(),
1309            vec![(0x0703, 2), (0x0803, 2), (0x0803, 1), (0x0703, 1)]
1310        );
1311        assert_eq!(io.current[&(0x0703, 0x0100)], vec![1]);
1312        assert_eq!(io.current[&(0x0803, 0x0100)], vec![1]);
1313    }
1314
1315    #[test]
1316    fn trace_retains_actual_prewrite_values_for_failed_and_uncertain_sets() {
1317        let mut io = MockIo::selectors();
1318        io.fail_writes = vec![2, 3];
1319        let edits = [select(7, 2), select(8, 2)];
1320        let mut trace = Vec::new();
1321        let error = apply_routes_traced(&inventory(), &mut io, &edits, &mut trace).unwrap_err();
1322        assert_eq!(
1323            trace,
1324            vec![
1325                (
1326                    edits[0].key,
1327                    RouteValue::SelectorPin(1),
1328                    RouteValue::SelectorPin(2)
1329                ),
1330                (
1331                    edits[1].key,
1332                    RouteValue::SelectorPin(1),
1333                    RouteValue::SelectorPin(2)
1334                ),
1335            ]
1336        );
1337        assert_eq!(error.rollback_failures[0].0, edits[1].key);
1338    }
1339
1340    #[test]
1341    fn mismatched_readback_restores_attempted_control() {
1342        let mut io = MockIo::selectors();
1343        io.ignore_writes = vec![1];
1344        let failure = apply_routes(&inventory(), &mut io, &[select(7, 2)]).unwrap_err();
1345        assert_eq!(
1346            failure.cause,
1347            RoutingError::ReadbackMismatch {
1348                expected: RouteValue::SelectorPin(2),
1349                actual: RouteValue::SelectorPin(1)
1350            }
1351        );
1352        assert!(failure.rollback_failures.is_empty());
1353        assert_eq!(io.writes.len(), 2);
1354    }
1355
1356    #[test]
1357    fn rollback_failures_are_reported_and_remaining_restores_continue() {
1358        let mut io = MockIo::selectors();
1359        io.fail_writes = vec![2, 3];
1360        let failure =
1361            apply_routes(&inventory(), &mut io, &[select(7, 2), select(8, 2)]).unwrap_err();
1362        assert_eq!(
1363            failure.rollback_failures,
1364            vec![(select(8, 2).key, RoutingError::Io("write failed"))]
1365        );
1366        assert_eq!(io.writes.len(), 4);
1367    }
1368
1369    #[test]
1370    fn invalid_batches_and_short_original_reads_never_write() {
1371        let mut io = MockIo::selectors();
1372        let inv = inventory();
1373        for changes in [
1374            vec![select(7, 2), select(8, 0)],
1375            vec![select(7, 2), select(7, 1)],
1376            vec![select(7, 2); MAX_ROUTE_CHANGES + 1],
1377        ] {
1378            assert!(apply_routes(&inv, &mut io, &changes).is_err());
1379            assert!(io.reads.is_empty());
1380            assert!(io.writes.is_empty());
1381        }
1382        io.short_reads = true;
1383        let failure = apply_routes(&inv, &mut io, &[select(7, 2)]).unwrap_err();
1384        assert_eq!(
1385            failure.cause,
1386            RoutingError::TransferLength {
1387                expected: 1,
1388                actual: 0
1389            }
1390        );
1391        assert!(io.writes.is_empty());
1392    }
1393
1394    #[test]
1395    fn raw_restore_replays_off_grid_cur_and_detects_mismatch() {
1396        let inv = inventory();
1397        let key = ControlKey::Crosspoint {
1398            entity: Entity {
1399                interface: 3,
1400                id: 9,
1401            },
1402            input_pin: 1,
1403            input_channel: 1,
1404            output_channel: 1,
1405        };
1406        let mut io = MockIo {
1407            current: BTreeMap::from([((0x0903, 0x0100), (-256i16).to_le_bytes().to_vec())]),
1408            range: vec![1, 0, 0, 254, 0, 0, 0, 1],
1409            ..MockIo::default()
1410        };
1411        let control = inv.control(key).unwrap();
1412        write_verified(&mut io, control, RouteValue::MixerGain(-255)).unwrap();
1413        assert_eq!(io.current[&(0x0903, 0x0100)], (-255i16).to_le_bytes());
1414        io.ignore_writes = vec![2];
1415        assert!(matches!(
1416            write_verified(&mut io, control, RouteValue::MixerGain(-256)),
1417            Err(RoutingError::ReadbackMismatch { .. })
1418        ));
1419    }
1420
1421    #[test]
1422    fn mixer_transaction_checks_live_range_before_writing() {
1423        let inv = inventory();
1424        let key = ControlKey::Crosspoint {
1425            entity: Entity {
1426                interface: 3,
1427                id: 9,
1428            },
1429            input_pin: 1,
1430            input_channel: 1,
1431            output_channel: 1,
1432        };
1433        let mut io = MockIo {
1434            current: BTreeMap::from([((0x0903, 0x0100), vec![0, 0])]),
1435            range: vec![1, 0, 0, 254, 0, 0, 0, 1],
1436            ..MockIo::default()
1437        };
1438        let failure = apply_routes(
1439            &inv,
1440            &mut io,
1441            &[RouteChange {
1442                key,
1443                value: RouteValue::MixerGain(-255),
1444            }],
1445        )
1446        .unwrap_err();
1447        assert_eq!(
1448            failure.cause,
1449            RoutingError::Invalid(InvalidRoute::GainOutsideRange)
1450        );
1451        assert!(io.writes.is_empty());
1452        apply_routes(
1453            &inv,
1454            &mut io,
1455            &[RouteChange {
1456                key,
1457                value: RouteValue::MixerGain(-256),
1458            }],
1459        )
1460        .unwrap();
1461        assert_eq!(io.writes[0].1, vec![0, 255]);
1462        assert!(io.reads.iter().any(|r| r.request == 2 && r.length == 2));
1463        assert!(io.reads.iter().any(|r| r.request == 2 && r.length == 8));
1464    }
1465}