Skip to main content

usbdac_core/
scarlett.rs

1//! Focusrite routing protocol primitives independently implemented from Linux
2//! v7.0 `mixer_scarlett2.c` protocol evidence. New exact-model firmware-minimum
3//! profiles additionally require live complete protocol and geometry proof.
4//!
5//! Model ports and packet decoding are source-backed; physical routing has not
6//! been validated on Scarlett hardware. Legacy GET_MUX selector zero remains
7//! independent of the optional, runtime-probed complete per-bank transaction.
8//! Original coefficients remain unsigned wire values for exact restoration.
9
10use std::time::{Duration, Instant};
11
12mod fcp;
13mod gen1;
14pub use fcp::{
15    apply_fcp, read_fcp, FcpBank, FcpFailure, FcpMixEdit, FcpPort, FcpReadback, FcpRouteEdit,
16    FcpTarget, FcpWriteError, FcpWriteReport,
17};
18pub use gen1::{
19    apply_gen1, read_gen1, Gen1Control, Gen1Edit, Gen1Failure, Gen1Io, Gen1Key, Gen1Model,
20    Gen1Readback, Gen1Report, Gen1WriteError,
21};
22pub(crate) use gen1::{restore_gen1, same_gen1_layout};
23
24const HEADER: usize = 16;
25pub(crate) use fcp::{restore_fcp, same_fcp_layout};
26
27pub(crate) const FCP_MAX_PAYLOAD: usize = 1024;
28// Largest admitted bank: 77 words plus the four-byte SET_MUX header.
29pub(crate) const MAX_PAYLOAD: usize = 312;
30const ACK_TIMEOUT: Duration = Duration::from_secs(1);
31const MAX_NOTIFICATIONS: usize = 16;
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum CandidateModel {
35    Scarlett18i20Gen2,
36    Scarlett6i6Gen2,
37    Scarlett18i8Gen2,
38    Scarlett4i4Gen3,
39    Scarlett8i6Gen3,
40    Scarlett18i8Gen3,
41    Scarlett18i20Gen3,
42    // Exact USB identities from pinned ALSA model map (2256–2262);
43    // USB/Plus share protocol geometry, never their public model identity.
44    ClarettUsb2Pre,
45    ClarettUsb4Pre,
46    ClarettUsb8Pre,
47    ClarettPlus2Pre,
48    ClarettPlus4Pre,
49    ClarettPlus8Pre,
50    VocasterOne,
51    VocasterTwo,
52    ScarlettSoloGen4,
53    Scarlett2i2Gen4,
54    Scarlett4i4Gen4,
55    Scarlett16i16Gen4,
56    Scarlett18i16Gen4,
57    Scarlett18i20Gen4,
58    IsaC8x,
59}
60
61impl CandidateModel {
62    pub fn recognize(vendor: u16, product: u16) -> Option<Self> {
63        if vendor != 0x1235 {
64            return None;
65        }
66        match product {
67            0x8201 => Some(Self::Scarlett18i20Gen2),
68            0x8203 => Some(Self::Scarlett6i6Gen2),
69            0x8204 => Some(Self::Scarlett18i8Gen2),
70            0x8212 => Some(Self::Scarlett4i4Gen3),
71            0x8213 => Some(Self::Scarlett8i6Gen3),
72            0x8214 => Some(Self::Scarlett18i8Gen3),
73            0x8215 => Some(Self::Scarlett18i20Gen3),
74            0x8206 => Some(Self::ClarettUsb2Pre),
75            0x8207 => Some(Self::ClarettUsb4Pre),
76            0x8208 => Some(Self::ClarettUsb8Pre),
77            0x820a => Some(Self::ClarettPlus2Pre),
78            0x820b => Some(Self::ClarettPlus4Pre),
79            0x820c => Some(Self::ClarettPlus8Pre),
80            0x8216 => Some(Self::VocasterOne),
81            0x8217 => Some(Self::VocasterTwo),
82            0x8218 => Some(Self::ScarlettSoloGen4),
83            0x8219 => Some(Self::Scarlett2i2Gen4),
84            0x821a => Some(Self::Scarlett4i4Gen4),
85            0x821b => Some(Self::Scarlett16i16Gen4),
86            0x821c => Some(Self::Scarlett18i16Gen4),
87            0x821d => Some(Self::Scarlett18i20Gen4),
88            0x821e => Some(Self::IsaC8x),
89            _ => None,
90        }
91    }
92    pub fn is_fcp(self) -> bool {
93        matches!(
94            self,
95            Self::Scarlett16i16Gen4
96                | Self::Scarlett18i16Gen4
97                | Self::Scarlett18i20Gen4
98                | Self::IsaC8x
99        )
100    }
101    pub fn key(self) -> &'static str {
102        match self {
103            Self::Scarlett18i20Gen2 => "scarlett_18i20_gen2",
104            Self::Scarlett6i6Gen2 => "scarlett_6i6_gen2",
105            Self::Scarlett18i8Gen2 => "scarlett_18i8_gen2",
106            Self::Scarlett4i4Gen3 => "scarlett_4i4_gen3",
107            Self::Scarlett8i6Gen3 => "scarlett_8i6_gen3",
108            Self::Scarlett18i8Gen3 => "scarlett_18i8_gen3",
109            Self::Scarlett18i20Gen3 => "scarlett_18i20_gen3",
110            Self::ClarettUsb2Pre => "clarett_usb_2pre",
111            Self::ClarettUsb4Pre => "clarett_usb_4pre",
112            Self::ClarettUsb8Pre => "clarett_usb_8pre",
113            Self::ClarettPlus2Pre => "clarett_plus_2pre",
114            Self::ClarettPlus4Pre => "clarett_plus_4pre",
115            Self::ClarettPlus8Pre => "clarett_plus_8pre",
116            Self::VocasterOne => "vocaster_one",
117            Self::VocasterTwo => "vocaster_two",
118            Self::ScarlettSoloGen4 => "scarlett_solo_gen4",
119            Self::Scarlett2i2Gen4 => "scarlett_2i2_gen4",
120            Self::Scarlett4i4Gen4 => "scarlett_4i4_gen4",
121            Self::Scarlett16i16Gen4 => "scarlett_16i16_gen4",
122            Self::Scarlett18i16Gen4 => "scarlett_18i16_gen4",
123            Self::Scarlett18i20Gen4 => "scarlett_18i20_gen4",
124            Self::IsaC8x => "isa_c8x",
125        }
126    }
127    pub fn name(self) -> &'static str {
128        match self {
129            Self::Scarlett18i20Gen2 => "Scarlett 18i20 Gen 2",
130            Self::Scarlett6i6Gen2 => "Scarlett 6i6 Gen 2",
131            Self::Scarlett18i8Gen2 => "Scarlett 18i8 Gen 2",
132            Self::Scarlett4i4Gen3 => "Scarlett 4i4 Gen 3",
133            Self::Scarlett8i6Gen3 => "Scarlett 8i6 Gen 3",
134            Self::Scarlett18i8Gen3 => "Scarlett 18i8 Gen 3",
135            Self::Scarlett18i20Gen3 => "Scarlett 18i20 Gen 3",
136            Self::ClarettUsb2Pre => "Clarett USB 2Pre",
137            Self::ClarettUsb4Pre => "Clarett USB 4Pre",
138            Self::ClarettUsb8Pre => "Clarett USB 8Pre",
139            Self::ClarettPlus2Pre => "Clarett+ 2Pre",
140            Self::ClarettPlus4Pre => "Clarett+ 4Pre",
141            Self::ClarettPlus8Pre => "Clarett+ 8Pre",
142            Self::VocasterOne => "Vocaster One",
143            Self::VocasterTwo => "Vocaster Two",
144            Self::ScarlettSoloGen4 => "Scarlett Solo Gen 4",
145            Self::Scarlett2i2Gen4 => "Scarlett 2i2 Gen 4",
146            Self::Scarlett4i4Gen4 => "Scarlett 4i4 Gen 4",
147            Self::Scarlett16i16Gen4 => "Scarlett 16i16 Gen 4",
148            Self::Scarlett18i16Gen4 => "Scarlett 18i16 Gen 4",
149            Self::Scarlett18i20Gen4 => "Scarlett 18i20 Gen 4",
150            Self::IsaC8x => "ISA C8X",
151        }
152    }
153    pub fn validate_firmware(self, firmware: u32) -> Result<ReadModel, ProtocolError> {
154        let admitted = match self {
155            // Preserve the original captured-only profile. Other legacy models
156            // publish no minimum in the pinned driver: require a nonzero
157            // handshake plus complete live mux-zero and mixer proof below.
158            Self::Scarlett18i20Gen2 => firmware == 1083,
159            Self::Scarlett6i6Gen2 => firmware != 0,
160            Self::Scarlett18i8Gen2 => firmware != 0,
161            Self::Scarlett4i4Gen3 => firmware != 0,
162            Self::Scarlett8i6Gen3 => firmware != 0,
163            Self::Scarlett18i8Gen3 => firmware != 0,
164            Self::Scarlett18i20Gen3 => firmware != 0,
165            Self::ClarettUsb2Pre
166            | Self::ClarettUsb4Pre
167            | Self::ClarettUsb8Pre
168            | Self::ClarettPlus2Pre
169            | Self::ClarettPlus4Pre
170            | Self::ClarettPlus8Pre => firmware != 0,
171            Self::VocasterOne | Self::VocasterTwo => firmware >= 1769,
172            Self::ScarlettSoloGen4 | Self::Scarlett2i2Gen4 => firmware >= 2115,
173            Self::Scarlett4i4Gen4 => firmware >= 2089,
174            Self::Scarlett16i16Gen4
175            | Self::Scarlett18i16Gen4
176            | Self::Scarlett18i20Gen4
177            | Self::IsaC8x => {
178                return Err(ProtocolError::UnsupportedProtocol);
179            }
180        };
181        if !admitted {
182            return Err(ProtocolError::UnsupportedFirmware(firmware));
183        }
184        Ok(ReadModel {
185            candidate: self,
186            firmware,
187        })
188    }
189}
190
191/// A model whose firmware passed its exact capture, published minimum, or
192/// nonzero legacy handshake guard. Legacy guard alone proves no geometry.
193/// New profiles also require live protocol proof before a ReadSession is returned.
194#[derive(Debug, Clone, Copy, PartialEq, Eq)]
195pub struct ReadModel {
196    candidate: CandidateModel,
197    firmware: u32,
198}
199
200#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
201pub enum PortKind {
202    Off,
203    Analogue,
204    Spdif,
205    Adat,
206    Mix,
207    Pcm,
208}
209
210#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
211pub enum Port {
212    Off,
213    /// One-based channel identity within this port kind.
214    Channel {
215        kind: PortKind,
216        channel: u8,
217    },
218}
219
220impl ReadModel {
221    pub fn candidate(self) -> CandidateModel {
222        self.candidate
223    }
224    pub fn firmware(self) -> u32 {
225        self.firmware
226    }
227    // Counts are protocol channel identities, not user-facing connector labels.
228    // Gen4/Vocaster DSP endpoints share MIX IDs but have no mixer controls.
229    fn dsp_count(self) -> u8 {
230        match self.candidate {
231            CandidateModel::Scarlett18i20Gen2
232            | CandidateModel::Scarlett6i6Gen2
233            | CandidateModel::Scarlett18i8Gen2
234            | CandidateModel::Scarlett4i4Gen3
235            | CandidateModel::Scarlett8i6Gen3
236            | CandidateModel::Scarlett18i8Gen3
237            | CandidateModel::Scarlett18i20Gen3 => 0,
238            CandidateModel::ClarettUsb2Pre
239            | CandidateModel::ClarettUsb4Pre
240            | CandidateModel::ClarettUsb8Pre
241            | CandidateModel::ClarettPlus2Pre
242            | CandidateModel::ClarettPlus4Pre
243            | CandidateModel::ClarettPlus8Pre => 0,
244            CandidateModel::Scarlett16i16Gen4
245            | CandidateModel::Scarlett18i16Gen4
246            | CandidateModel::Scarlett18i20Gen4
247            | CandidateModel::IsaC8x => 0,
248            CandidateModel::VocasterOne => 1,
249            _ => 2,
250        }
251    }
252    pub fn mixer_inputs(self) -> u8 {
253        self.count(PortKind::Mix, false) - self.dsp_count()
254    }
255    pub fn mixer_outputs(self) -> u8 {
256        self.count(PortKind::Mix, true) - self.dsp_count()
257    }
258    pub fn mux_destinations(self) -> usize {
259        [
260            PortKind::Analogue,
261            PortKind::Spdif,
262            PortKind::Adat,
263            PortKind::Mix,
264            PortKind::Pcm,
265        ]
266        .iter()
267        .map(|&kind| usize::from(self.count(kind, false)))
268        .sum()
269    }
270    fn bank_widths(self) -> [u16; 3] {
271        match self.candidate {
272            CandidateModel::Scarlett18i20Gen2 => [64, 56, 46],
273            CandidateModel::Scarlett6i6Gen2 => [38, 38, 38],
274            CandidateModel::Scarlett18i8Gen2 => [52, 48, 40],
275            CandidateModel::Scarlett4i4Gen3 => [34, 34, 34],
276            // ALSA s8i6_gen3_info: 8 PCM + 4 analogue + 2 S/PDIF +
277            // 2 PCM + 8 mix + 18 padding = 42 words in each bank.
278            CandidateModel::Scarlett8i6Gen3 => [42, 42, 42],
279            CandidateModel::Scarlett18i8Gen3 => [60, 56, 50],
280            CandidateModel::Scarlett18i20Gen3 => [77, 73, 46],
281            // Independent geometry contract from pinned ALSA lines 2053–2226:
282            // USB and Plus identities share the 2/4/8Pre shapes.
283            CandidateModel::ClarettUsb2Pre | CandidateModel::ClarettPlus2Pre => [42, 38, 32],
284            CandidateModel::ClarettUsb4Pre | CandidateModel::ClarettPlus4Pre => [52, 48, 44],
285            CandidateModel::ClarettUsb8Pre | CandidateModel::ClarettPlus8Pre => [64, 56, 46],
286            CandidateModel::VocasterOne => [23, 0, 0],
287            CandidateModel::VocasterTwo => [34, 0, 0],
288            CandidateModel::ScarlettSoloGen4 | CandidateModel::Scarlett2i2Gen4 => [12; 3],
289            CandidateModel::Scarlett4i4Gen4 => [24; 3],
290            CandidateModel::Scarlett16i16Gen4
291            | CandidateModel::Scarlett18i16Gen4
292            | CandidateModel::Scarlett18i20Gen4
293            | CandidateModel::IsaC8x => [0; 3],
294        }
295    }
296    fn count(self, kind: PortKind, source: bool) -> u8 {
297        let pair = match (self.candidate, kind) {
298            (_, PortKind::Off) => [1, 0],
299            (CandidateModel::Scarlett18i20Gen2, PortKind::Analogue) => [8, 10],
300            (CandidateModel::Scarlett18i20Gen2, PortKind::Spdif) => [2, 2],
301            (CandidateModel::Scarlett18i20Gen2, PortKind::Adat) => [8, 8],
302            (CandidateModel::Scarlett18i20Gen2, PortKind::Mix) => [10, 18],
303            (CandidateModel::Scarlett18i20Gen2, PortKind::Pcm) => [20, 18],
304            (CandidateModel::Scarlett6i6Gen2, PortKind::Analogue) => [4, 4],
305            (CandidateModel::Scarlett6i6Gen2, PortKind::Spdif) => [2, 2],
306            (CandidateModel::Scarlett6i6Gen2, PortKind::Adat) => [0, 0],
307            (CandidateModel::Scarlett6i6Gen2, PortKind::Mix) => [10, 18],
308            (CandidateModel::Scarlett6i6Gen2, PortKind::Pcm) => [6, 6],
309            (CandidateModel::Scarlett18i8Gen2, PortKind::Analogue) => [8, 6],
310            (CandidateModel::Scarlett18i8Gen2, PortKind::Spdif) => [2, 2],
311            (CandidateModel::Scarlett18i8Gen2, PortKind::Adat) => [8, 0],
312            (CandidateModel::Scarlett18i8Gen2, PortKind::Mix) => [10, 18],
313            (CandidateModel::Scarlett18i8Gen2, PortKind::Pcm) => [8, 18],
314            (CandidateModel::Scarlett4i4Gen3, PortKind::Analogue) => [4, 4],
315            (CandidateModel::Scarlett4i4Gen3, PortKind::Spdif) => [0, 0],
316            (CandidateModel::Scarlett4i4Gen3, PortKind::Adat) => [0, 0],
317            (CandidateModel::Scarlett4i4Gen3, PortKind::Mix) => [6, 8],
318            (CandidateModel::Scarlett4i4Gen3, PortKind::Pcm) => [4, 6],
319            (CandidateModel::Scarlett8i6Gen3, PortKind::Analogue) => [6, 4],
320            (CandidateModel::Scarlett8i6Gen3, PortKind::Spdif) => [2, 2],
321            (CandidateModel::Scarlett8i6Gen3, PortKind::Adat) => [0, 0],
322            (CandidateModel::Scarlett8i6Gen3, PortKind::Mix) => [8, 8],
323            (CandidateModel::Scarlett8i6Gen3, PortKind::Pcm) => [6, 10],
324            (CandidateModel::Scarlett18i8Gen3, PortKind::Analogue) => [8, 8],
325            (CandidateModel::Scarlett18i8Gen3, PortKind::Spdif) => [2, 2],
326            (CandidateModel::Scarlett18i8Gen3, PortKind::Adat) => [8, 0],
327            (CandidateModel::Scarlett18i8Gen3, PortKind::Mix) => [10, 20],
328            (CandidateModel::Scarlett18i8Gen3, PortKind::Pcm) => [8, 20],
329            (CandidateModel::Scarlett18i20Gen3, PortKind::Analogue) => [9, 10],
330            (CandidateModel::Scarlett18i20Gen3, PortKind::Spdif) => [2, 2],
331            (CandidateModel::Scarlett18i20Gen3, PortKind::Adat) => [8, 8],
332            (CandidateModel::Scarlett18i20Gen3, PortKind::Mix) => [12, 25],
333            (CandidateModel::Scarlett18i20Gen3, PortKind::Pcm) => [20, 20],
334            (
335                CandidateModel::ClarettUsb2Pre | CandidateModel::ClarettPlus2Pre,
336                PortKind::Analogue,
337            ) => [2, 4],
338            (
339                CandidateModel::ClarettUsb4Pre | CandidateModel::ClarettPlus4Pre,
340                PortKind::Analogue,
341            ) => [8, 6],
342            (
343                CandidateModel::ClarettUsb8Pre | CandidateModel::ClarettPlus8Pre,
344                PortKind::Analogue,
345            ) => [8, 10],
346            (CandidateModel::ClarettUsb2Pre | CandidateModel::ClarettPlus2Pre, PortKind::Spdif) => {
347                [2, 0]
348            }
349            (CandidateModel::ClarettUsb4Pre | CandidateModel::ClarettPlus4Pre, PortKind::Spdif) => {
350                [2, 2]
351            }
352            (CandidateModel::ClarettUsb8Pre | CandidateModel::ClarettPlus8Pre, PortKind::Spdif) => {
353                [2, 2]
354            }
355            (CandidateModel::ClarettUsb2Pre | CandidateModel::ClarettPlus2Pre, PortKind::Adat) => {
356                [8, 0]
357            }
358            (CandidateModel::ClarettUsb4Pre | CandidateModel::ClarettPlus4Pre, PortKind::Adat) => {
359                [8, 0]
360            }
361            (CandidateModel::ClarettUsb8Pre | CandidateModel::ClarettPlus8Pre, PortKind::Adat) => {
362                [8, 8]
363            }
364            (CandidateModel::ClarettUsb2Pre | CandidateModel::ClarettPlus2Pre, PortKind::Mix) => {
365                [10, 18]
366            }
367            (CandidateModel::ClarettUsb4Pre | CandidateModel::ClarettPlus4Pre, PortKind::Mix) => {
368                [10, 18]
369            }
370            (CandidateModel::ClarettUsb8Pre | CandidateModel::ClarettPlus8Pre, PortKind::Mix) => {
371                [10, 18]
372            }
373            (CandidateModel::ClarettUsb2Pre | CandidateModel::ClarettPlus2Pre, PortKind::Pcm) => {
374                [4, 12]
375            }
376            (CandidateModel::ClarettUsb4Pre | CandidateModel::ClarettPlus4Pre, PortKind::Pcm) => {
377                [8, 18]
378            }
379            (CandidateModel::ClarettUsb8Pre | CandidateModel::ClarettPlus8Pre, PortKind::Pcm) => {
380                [20, 18]
381            }
382            (CandidateModel::VocasterOne, PortKind::Analogue) => [2, 4],
383            (CandidateModel::VocasterOne, PortKind::Mix) => [9, 9],
384            (CandidateModel::VocasterOne, PortKind::Pcm) => [4, 10],
385            (CandidateModel::VocasterTwo, PortKind::Analogue) => [6, 6],
386            (CandidateModel::VocasterTwo, PortKind::Mix) => [12, 14],
387            (CandidateModel::VocasterTwo, PortKind::Pcm) => [4, 14],
388            (CandidateModel::ScarlettSoloGen4, PortKind::Analogue)
389            | (CandidateModel::Scarlett2i2Gen4, PortKind::Analogue) => [2, 2],
390            (CandidateModel::ScarlettSoloGen4, PortKind::Mix) => [8, 6],
391            (CandidateModel::Scarlett2i2Gen4, PortKind::Mix) => [6, 6],
392            (CandidateModel::ScarlettSoloGen4, PortKind::Pcm)
393            | (CandidateModel::Scarlett2i2Gen4, PortKind::Pcm) => [2, 4],
394            (CandidateModel::Scarlett4i4Gen4, PortKind::Analogue) => [4, 6],
395            (CandidateModel::Scarlett4i4Gen4, PortKind::Mix) => [8, 12],
396            (CandidateModel::Scarlett4i4Gen4, PortKind::Pcm) => [6, 6],
397            // FCP models cannot construct a legacy ReadModel; all their
398            // actual counts and pins come from the firmware-described map.
399            (
400                CandidateModel::Scarlett16i16Gen4
401                | CandidateModel::Scarlett18i16Gen4
402                | CandidateModel::Scarlett18i20Gen4
403                | CandidateModel::IsaC8x,
404                PortKind::Analogue | PortKind::Mix | PortKind::Pcm,
405            ) => [0, 0],
406            (_, PortKind::Spdif | PortKind::Adat) => [0, 0],
407        };
408        pair[usize::from(!source)]
409    }
410
411    fn port(self, id: u16, source: bool) -> Result<Port, ProtocolError> {
412        if id == 0 && source {
413            return Ok(Port::Off);
414        }
415        for (kind, base) in [
416            (PortKind::Analogue, 0x080),
417            (PortKind::Spdif, 0x180),
418            (PortKind::Adat, 0x200),
419            (PortKind::Mix, 0x300),
420            (PortKind::Pcm, 0x600),
421        ] {
422            if id >= base && id - base < u16::from(self.count(kind, source)) {
423                return Ok(Port::Channel {
424                    kind,
425                    channel: (id - base + 1) as u8,
426                });
427            }
428        }
429        Err(ProtocolError::UnknownPort { id, source })
430    }
431}
432
433/// Descriptor-only capability. Firmware admission happens during the explicit
434/// read operation; this object alone authorizes no protocol transfer.
435#[derive(Debug, Clone, Copy, PartialEq, Eq)]
436pub struct ReadCapability {
437    pub candidate: CandidateModel,
438    pub configuration: u8,
439    pub interface: u8,
440    pub notification_endpoint: u8,
441    pub interface_claimed: bool,
442}
443
444#[derive(Debug, Clone, Copy, PartialEq, Eq)]
445pub struct MuxRoute {
446    pub source: Port,
447    pub destination: Port,
448}
449
450#[derive(Debug, Clone, PartialEq, Eq)]
451pub struct MixReadback {
452    /// One-based mixer output. Coefficients preserve the selected model's input order.
453    pub output: u8,
454    pub coefficients: Vec<u16>,
455}
456
457/// Bounded half-dB gain; -160 means -80 dB, 24 means +12 dB.
458#[derive(Debug, Clone, Copy, PartialEq, Eq)]
459pub struct MixGain(i16);
460impl MixGain {
461    pub fn from_half_db(value: i16) -> Result<Self, ProtocolError> {
462        if !(-160..=24).contains(&value) {
463            return Err(ProtocolError::InvalidMixGain(value));
464        }
465        Ok(Self(value))
466    }
467    pub fn half_db(self) -> i16 {
468        self.0
469    }
470    pub fn coefficient(self) -> u16 {
471        (8192.0 * 10.0_f64.powf(f64::from(self.0) / 40.0)).floor() as u16
472    }
473}
474
475#[derive(Debug, Clone, Copy, PartialEq, Eq)]
476pub struct MixGainEdit {
477    /// One-based input in the selected output row.
478    pub input: u8,
479    pub gain: MixGain,
480}
481
482/// Expected complete raw row and bounded gain replacements. Untouched values
483/// are carried through exactly, even when they are outside the editable scale.
484#[derive(Debug, Clone, PartialEq, Eq)]
485pub struct MixRowEdit {
486    pub expected: MixReadback,
487    pub gains: Vec<MixGainEdit>,
488}
489
490#[derive(Debug, Clone, PartialEq, Eq)]
491pub struct MixWriteReport {
492    pub original: MixReadback,
493    pub verified: MixReadback,
494}
495
496#[derive(Debug, PartialEq, Eq)]
497pub enum MixFailure<E> {
498    Read(ReadError<E>),
499    Invalid(ProtocolError),
500    Drift { actual: MixReadback },
501    Verification { actual: MixReadback },
502}
503
504/// `rollback` is present only when the attempted row could not be restored and
505/// verified. The original failure is always retained, including transport errors.
506#[derive(Debug, PartialEq, Eq)]
507pub struct MixWriteError<E> {
508    pub failure: MixFailure<E>,
509    pub rollback: Option<MixFailure<E>>,
510}
511
512/// Full source-backed per-bank payload. Private words prevent callers from
513/// inventing a rollback baseline; every transaction also freshly rereads it.
514#[derive(Debug, Clone, PartialEq, Eq)]
515pub struct MuxBankSnapshot {
516    bank: u8,
517    model: ReadModel,
518    words: Vec<u32>,
519}
520impl MuxBankSnapshot {
521    pub fn bank(&self) -> u8 {
522        self.bank
523    }
524    pub fn raw_words(&self) -> &[u32] {
525        &self.words
526    }
527    pub fn routes(&self) -> Vec<MuxRoute> {
528        let model = self.model;
529        self.words
530            .iter()
531            .copied()
532            .filter(|word| *word != 0)
533            .map(|word| MuxRoute {
534                source: model.port(((word >> 12) & 0xfff) as u16, true).unwrap(),
535                destination: model.port((word & 0xfff) as u16, false).unwrap(),
536            })
537            .collect()
538    }
539}
540
541/// Runtime-observed complete bank geometry for the admitted firmware only.
542#[derive(Debug, Clone, PartialEq, Eq)]
543pub struct MuxSnapshot {
544    pub model: ReadModel,
545    pub banks: Vec<MuxBankSnapshot>,
546}
547#[derive(Debug, Clone, Copy, PartialEq, Eq)]
548pub struct MuxRouteEdit {
549    /// 0 = base rate, 1 = double rate, 2 = quad rate.
550    pub bank: u8,
551    pub destination: Port,
552    pub source: Port,
553}
554#[derive(Debug, Clone, PartialEq, Eq)]
555pub struct MuxEdit {
556    pub expected: MuxSnapshot,
557    pub routes: Vec<MuxRouteEdit>,
558}
559#[derive(Debug, Clone, PartialEq, Eq)]
560pub struct MuxWriteReport {
561    pub original: MuxSnapshot,
562    pub verified: MuxSnapshot,
563}
564#[derive(Debug, PartialEq, Eq)]
565pub enum MuxFailure<E> {
566    Read(ReadError<E>),
567    Invalid(ProtocolError),
568    Drift { actual: MuxSnapshot },
569    Verification { bank: u8, actual: MuxBankSnapshot },
570}
571#[derive(Debug, PartialEq, Eq)]
572pub struct MuxWriteError<E> {
573    pub failure: MuxFailure<E>,
574    /// Every attempted bank is restored separately, including an uncertain SET.
575    /// Empty means all attempted banks were restored and verified (or no SET).
576    pub rollback: Vec<(u8, MuxFailure<E>)>,
577}
578
579#[derive(Debug, Clone, PartialEq, Eq)]
580pub struct RoutingReadback {
581    pub model: ReadModel,
582    /// GET_MUX with wire argument zero; not a snapshot of every rate bank.
583    pub mux_zero: Vec<MuxRoute>,
584    pub mixes: Vec<MixReadback>,
585}
586
587#[derive(Debug, Clone, PartialEq, Eq)]
588pub enum ProtocolError {
589    UnsupportedProtocol,
590    InvalidDeviceMap,
591    UnsupportedFirmware(u32),
592    InvalidMixOutput(u8),
593    InvalidMixInput(u8),
594    InvalidMixGain(i16),
595    DuplicateMixInput(u8),
596    InvalidLength { expected: usize, actual: usize },
597    InvalidCommand,
598    InvalidSequence,
599    InvalidPayloadSize,
600    DeviceStatus(u32),
601    NonzeroReserved,
602    UnknownPort { id: u16, source: bool },
603    DuplicateDestination,
604    InvalidMuxBits,
605    UnsupportedMuxGeometry,
606    InvalidMuxBank(u8),
607    InvalidMuxEdit,
608    AcknowledgementTimeout,
609    InvalidNotification,
610    SessionPoisoned,
611}
612
613#[derive(Debug, PartialEq, Eq)]
614pub enum ReadError<E> {
615    Protocol(ProtocolError),
616    Io(E),
617}
618
619/// Adapter ownership must cover the whole initialization/read sequence. It must
620/// hold the exact device's already claimed vendor interface and interrupt IN
621/// endpoint, with all audio streams stopped. No generic command API is exposed.
622pub trait ReadIo {
623    type Error;
624    fn initial_read(&mut self, bytes: &mut [u8; 24]) -> Result<usize, Self::Error>;
625    /// Start owning notifications and discard stale packets for the documented
626    /// 20 ms initialization settling window, with a bounded drain.
627    fn prepare_notifications(&mut self) -> Result<(), Self::Error>;
628    fn send_request(&mut self, bytes: &[u8]) -> Result<usize, Self::Error>;
629    /// Return actual length; respect the supplied total remaining timeout.
630    fn next_notification(
631        &mut self,
632        bytes: &mut [u8; 8],
633        timeout: Duration,
634    ) -> Result<usize, Self::Error>;
635    fn receive_response(&mut self, bytes: &mut [u8]) -> Result<usize, Self::Error>;
636}
637
638#[derive(Debug, Clone, Copy, PartialEq, Eq)]
639enum Command {
640    MixInfo,
641    DevmapInfo,
642    DevmapRead,
643    Init,
644    Info,
645    Mux,
646    Mix,
647    SetMix,
648    MuxInfo,
649    SetMux,
650}
651impl Command {
652    fn code(self) -> u32 {
653        match self {
654            Self::MixInfo => 0x2000,
655            Self::DevmapInfo => 0x80000c,
656            Self::DevmapRead => 0x80000d,
657            Self::Init => 0,
658            Self::Info => 2,
659            Self::Mux => 0x3001,
660            Self::Mix => 0x2001,
661            Self::SetMix => 0x2002,
662            Self::MuxInfo => 0x3000,
663            Self::SetMux => 0x3002,
664        }
665    }
666    fn initializing(self) -> bool {
667        matches!(self, Self::Init | Self::Info)
668    }
669}
670
671fn packet(command: Command, sequence: u16, payload: &[u8]) -> Vec<u8> {
672    let mut bytes = Vec::with_capacity(HEADER + payload.len());
673    bytes.extend(command.code().to_le_bytes());
674    bytes.extend((payload.len() as u16).to_le_bytes());
675    bytes.extend(sequence.to_le_bytes());
676    bytes.extend([0; 8]);
677    bytes.extend(payload);
678    bytes
679}
680
681#[cfg(test)]
682fn decode_reply(
683    command: Command,
684    sequence: u16,
685    size: usize,
686    bytes: &[u8],
687) -> Result<&[u8], ProtocolError> {
688    decode_reply_mode(command, sequence, size, bytes, false)
689}
690
691#[cfg(any(test, feature = "fuzzing"))]
692pub(crate) fn fuzz_reply(data: &[u8]) {
693    for fcp in [false, true] {
694        // Vary the expected size independently of the supplied packet length.
695        for size in [
696            0,
697            data.len().saturating_sub(HEADER),
698            data.first().copied().unwrap_or(0) as usize,
699        ] {
700            let _ = decode_reply_mode(Command::Mux, 1, size, data, fcp);
701        }
702    }
703    let model = ReadModel {
704        candidate: CandidateModel::Scarlett18i20Gen2,
705        firmware: 1,
706    };
707    let _ = decode_mux(model, data);
708}
709
710fn decode_reply_mode(
711    command: Command,
712    sequence: u16,
713    size: usize,
714    bytes: &[u8],
715    fcp: bool,
716) -> Result<&[u8], ProtocolError> {
717    let expected = HEADER + size;
718    if size > if fcp { FCP_MAX_PAYLOAD } else { MAX_PAYLOAD } || bytes.len() != expected {
719        return Err(ProtocolError::InvalidLength {
720            expected,
721            actual: bytes.len(),
722        });
723    }
724    if u32::from_le_bytes(bytes[0..4].try_into().unwrap()) != command.code() {
725        return Err(ProtocolError::InvalidCommand);
726    }
727    if usize::from(u16::from_le_bytes(bytes[4..6].try_into().unwrap())) != size {
728        return Err(ProtocolError::InvalidPayloadSize);
729    }
730    let reply_sequence = u16::from_le_bytes(bytes[6..8].try_into().unwrap());
731    if reply_sequence != sequence
732        && !(!fcp && command.initializing() && sequence == 1 && reply_sequence == 0)
733    {
734        return Err(ProtocolError::InvalidSequence);
735    }
736    let status = u32::from_le_bytes(bytes[8..12].try_into().unwrap());
737    if status != 0 {
738        return Err(ProtocolError::DeviceStatus(status));
739    }
740    if bytes[12..16] != [0; 4] {
741        return Err(ProtocolError::NonzeroReserved);
742    }
743    Ok(&bytes[HEADER..])
744}
745
746fn transact<I: ReadIo>(
747    io: &mut I,
748    command: Command,
749    sequence: u16,
750    payload: &[u8],
751    size: usize,
752) -> Result<Vec<u8>, ReadError<I::Error>> {
753    transact_mode(io, command, sequence, payload, size, false)
754}
755
756fn transact_mode<I: ReadIo>(
757    io: &mut I,
758    command: Command,
759    sequence: u16,
760    payload: &[u8],
761    size: usize,
762    fcp: bool,
763) -> Result<Vec<u8>, ReadError<I::Error>> {
764    let limit = if fcp { FCP_MAX_PAYLOAD } else { MAX_PAYLOAD };
765    if size > limit || payload.len() > limit {
766        return Err(ReadError::Protocol(ProtocolError::InvalidPayloadSize));
767    }
768    let request = packet(command, sequence, payload);
769    exact(
770        io.send_request(&request).map_err(ReadError::Io)?,
771        request.len(),
772    )?;
773    let deadline = Instant::now() + ACK_TIMEOUT;
774    let mut acknowledged = false;
775    for _ in 0..MAX_NOTIFICATIONS {
776        let timeout = deadline.saturating_duration_since(Instant::now());
777        if timeout.is_zero() {
778            break;
779        }
780        let mut notification = [0; 8];
781        let n = io
782            .next_notification(&mut notification, timeout)
783            .map_err(ReadError::Io)?;
784        if n != notification.len() {
785            return Err(ReadError::Protocol(ProtocolError::InvalidNotification));
786        }
787        if u32::from_le_bytes(notification[..4].try_into().unwrap()) & 1 != 0 {
788            acknowledged = true;
789            break;
790        }
791    }
792    if !acknowledged {
793        return Err(ReadError::Protocol(ProtocolError::AcknowledgementTimeout));
794    }
795    let mut reply = vec![0; HEADER + size];
796    exact(
797        io.receive_response(&mut reply).map_err(ReadError::Io)?,
798        reply.len(),
799    )?;
800    decode_reply_mode(command, sequence, size, &reply, fcp)
801        .map_err(ReadError::Protocol)
802        .map(Vec::from)
803}
804
805fn exact<E>(actual: usize, expected: usize) -> Result<(), ReadError<E>> {
806    if actual == expected {
807        Ok(())
808    } else {
809        Err(ReadError::Protocol(ProtocolError::InvalidLength {
810            expected,
811            actual,
812        }))
813    }
814}
815
816/// Stateful, bounded protocol. Transfer/protocol failures poison normal calls;
817/// failed write restoration and optional bank probes may reinitialize independently.
818pub struct ReadSession<I> {
819    io: I,
820    model: ReadModel,
821    sequence: u16,
822    poisoned: bool,
823}
824
825impl<I: ReadIo> ReadSession<I> {
826    pub fn initialize(mut io: I, candidate: CandidateModel) -> Result<Self, ReadError<I::Error>> {
827        if candidate.is_fcp() {
828            return Err(ReadError::Protocol(ProtocolError::UnsupportedProtocol));
829        }
830        let mut startup = [0; 24];
831        exact(
832            io.initial_read(&mut startup).map_err(ReadError::Io)?,
833            startup.len(),
834        )?;
835        io.prepare_notifications().map_err(ReadError::Io)?;
836        transact(&mut io, Command::Init, 1, &[], 0)?;
837        // The documented handshake resets sequence to one for its second command.
838        let info = transact(&mut io, Command::Info, 1, &[], 84)?;
839        let firmware = u32::from_le_bytes(info[8..12].try_into().unwrap());
840        let model = candidate
841            .validate_firmware(firmware)
842            .map_err(ReadError::Protocol)?;
843        let mut session = Self {
844            io,
845            model,
846            sequence: 2,
847            poisoned: false,
848        };
849        // Firmware admission alone never authorizes a new profile. Require
850        // observed envelope, lengths, every mux-zero port and mixer row.
851        if candidate != CandidateModel::Scarlett18i20Gen2 {
852            session.read_all()?;
853            // Legacy firmwares may not implement MUX_INFO. Bank proof is an
854            // independent explicit operation, never a prerequisite for mix.
855            if matches!(
856                candidate,
857                CandidateModel::VocasterOne
858                    | CandidateModel::VocasterTwo
859                    | CandidateModel::ScarlettSoloGen4
860                    | CandidateModel::Scarlett2i2Gen4
861                    | CandidateModel::Scarlett4i4Gen4
862            ) {
863                session.read_mux_banks()?;
864            }
865        }
866        Ok(session)
867    }
868
869    pub fn model(&self) -> ReadModel {
870        self.model
871    }
872
873    fn request(
874        &mut self,
875        command: Command,
876        payload: &[u8],
877        size: usize,
878    ) -> Result<Vec<u8>, ReadError<I::Error>> {
879        if self.poisoned {
880            return Err(ReadError::Protocol(ProtocolError::SessionPoisoned));
881        }
882        let sequence = self.sequence;
883        self.sequence = self.sequence.wrapping_add(1);
884        let result = transact(&mut self.io, command, sequence, payload, size);
885        if result.is_err() {
886            self.poisoned = true;
887        }
888        result
889    }
890
891    pub fn read_mux_zero(&mut self) -> Result<Vec<MuxRoute>, ReadError<I::Error>> {
892        let count = self.model.mux_destinations();
893        let request = [0, 0, count as u8, 0];
894        let bytes = self.request(Command::Mux, &request, count * 4)?;
895        let result = decode_mux(self.model, &bytes).map_err(ReadError::Protocol);
896        if result.is_err() {
897            self.poisoned = true;
898        }
899        result
900    }
901
902    pub fn read_mix(&mut self, output: u8) -> Result<MixReadback, ReadError<I::Error>> {
903        if output == 0 || output > self.model.mixer_outputs() {
904            return Err(ReadError::Protocol(ProtocolError::InvalidMixOutput(output)));
905        }
906        let request = [output - 1, 0, self.model.mixer_inputs(), 0];
907        let bytes = self.request(
908            Command::Mix,
909            &request,
910            usize::from(self.model.mixer_inputs()) * 2,
911        )?;
912        Ok(MixReadback {
913            output,
914            coefficients: bytes
915                .chunks_exact(2)
916                .map(|b| u16::from_le_bytes([b[0], b[1]]))
917                .collect(),
918        })
919    }
920
921    fn validate_row(&self, row: &MixReadback) -> Result<(), ProtocolError> {
922        if row.output == 0 || row.output > self.model.mixer_outputs() {
923            return Err(ProtocolError::InvalidMixOutput(row.output));
924        }
925        let expected = usize::from(self.model.mixer_inputs());
926        if row.coefficients.len() != expected {
927            return Err(ProtocolError::InvalidLength {
928                expected,
929                actual: row.coefficients.len(),
930            });
931        }
932        Ok(())
933    }
934
935    fn set_mix(&mut self, row: &MixReadback) -> Result<(), ReadError<I::Error>> {
936        let mut payload = u16::from(row.output - 1).to_le_bytes().to_vec();
937        for value in &row.coefficients {
938            payload.extend(value.to_le_bytes());
939        }
940        self.request(Command::SetMix, &payload, 0).map(|_| ())
941    }
942
943    // Recovery must re-establish notification/sequence state rather than reuse a
944    // poisoned request stream after an uncertain write or malformed response.
945    fn recover(&mut self) -> Result<(), ReadError<I::Error>> {
946        let mut startup = [0; 24];
947        exact(
948            self.io.initial_read(&mut startup).map_err(ReadError::Io)?,
949            startup.len(),
950        )?;
951        self.io.prepare_notifications().map_err(ReadError::Io)?;
952        transact(&mut self.io, Command::Init, 1, &[], 0)?;
953        let info = transact(&mut self.io, Command::Info, 1, &[], 84)?;
954        let firmware = u32::from_le_bytes(info[8..12].try_into().unwrap());
955        self.model
956            .candidate
957            .validate_firmware(firmware)
958            .map_err(ReadError::Protocol)?;
959        if firmware != self.model.firmware {
960            return Err(ReadError::Protocol(ProtocolError::UnsupportedFirmware(
961                firmware,
962            )));
963        }
964        self.sequence = 2;
965        self.poisoned = false;
966        Ok(())
967    }
968
969    /// Fresh-check, set and verify an entire row. A failed attempted SET always
970    /// triggers bounded restoration, including when the SET response is lost.
971    pub fn apply_mix(
972        &mut self,
973        edit: &MixRowEdit,
974    ) -> Result<MixWriteReport, MixWriteError<I::Error>> {
975        let invalid = |error| MixWriteError {
976            failure: MixFailure::Invalid(error),
977            rollback: None,
978        };
979        self.validate_row(&edit.expected).map_err(invalid)?;
980        let mut target = edit.expected.clone();
981        let mut seen = Vec::new();
982        for gain in &edit.gains {
983            if gain.input == 0 || gain.input > self.model.mixer_inputs() {
984                return Err(invalid(ProtocolError::InvalidMixInput(gain.input)));
985            }
986            if seen.contains(&gain.input) {
987                return Err(invalid(ProtocolError::DuplicateMixInput(gain.input)));
988            }
989            seen.push(gain.input);
990            target.coefficients[usize::from(gain.input - 1)] = gain.gain.coefficient();
991        }
992        self.replace_mix(&edit.expected, &target)
993    }
994
995    pub(crate) fn replace_mix(
996        &mut self,
997        expected: &MixReadback,
998        target: &MixReadback,
999    ) -> Result<MixWriteReport, MixWriteError<I::Error>> {
1000        let fail = |failure| MixWriteError {
1001            failure,
1002            rollback: None,
1003        };
1004        self.validate_row(expected)
1005            .map_err(|e| fail(MixFailure::Invalid(e)))?;
1006        self.validate_row(target)
1007            .map_err(|e| fail(MixFailure::Invalid(e)))?;
1008        if expected.output != target.output {
1009            return Err(fail(MixFailure::Invalid(ProtocolError::InvalidMixOutput(
1010                target.output,
1011            ))));
1012        }
1013        let actual = self
1014            .read_mix(expected.output)
1015            .map_err(|e| fail(MixFailure::Read(e)))?;
1016        if actual != *expected {
1017            return Err(fail(MixFailure::Drift { actual }));
1018        }
1019        if expected == target {
1020            return Ok(MixWriteReport {
1021                original: actual.clone(),
1022                verified: actual,
1023            });
1024        }
1025        let attempt = self
1026            .set_mix(target)
1027            .map_err(MixFailure::Read)
1028            .and_then(|_| {
1029                let actual = self.read_mix(target.output).map_err(MixFailure::Read)?;
1030                if actual != *target {
1031                    return Err(MixFailure::Verification { actual });
1032                }
1033                Ok(actual)
1034            });
1035        match attempt {
1036            Ok(verified) => Ok(MixWriteReport {
1037                original: expected.clone(),
1038                verified,
1039            }),
1040            Err(failure) => {
1041                let rollback = (|| {
1042                    if self.poisoned {
1043                        self.recover().map_err(MixFailure::Read)?;
1044                    }
1045                    self.set_mix(expected).map_err(MixFailure::Read)?;
1046                    let actual = self.read_mix(expected.output).map_err(MixFailure::Read)?;
1047                    if actual != *expected {
1048                        return Err(MixFailure::Verification { actual });
1049                    }
1050                    Ok(())
1051                })()
1052                .err();
1053                if rollback.is_some() {
1054                    self.poisoned = true;
1055                }
1056                Err(MixWriteError { failure, rollback })
1057            }
1058        }
1059    }
1060
1061    /// Probe the complete bank contract against the exact model geometry.
1062    /// Missing banks are never synthesized from another model or selector zero.
1063    pub fn read_mux_banks(&mut self) -> Result<MuxSnapshot, ReadError<I::Error>> {
1064        let result = self.probe_mux_banks();
1065        // A rejected optional bank probe must not strand independently verified
1066        // legacy mixer controls. Reinitialize only the poisoned stream; keep
1067        // the original error and leave the session poisoned if recovery fails.
1068        if result.is_err() && self.poisoned {
1069            let _ = self.recover();
1070        }
1071        result
1072    }
1073
1074    fn probe_mux_banks(&mut self) -> Result<MuxSnapshot, ReadError<I::Error>> {
1075        let info = self.request(Command::MuxInfo, &[], 12)?;
1076        let widths: Vec<_> = info[..6]
1077            .chunks_exact(2)
1078            .map(|v| u16::from_le_bytes([v[0], v[1]]))
1079            .collect();
1080        if widths != self.model.bank_widths() {
1081            return Err(ReadError::Protocol(ProtocolError::UnsupportedMuxGeometry));
1082        }
1083        let mut banks = Vec::new();
1084        for (bank, width) in self.model.bank_widths().iter().enumerate() {
1085            if *width != 0 {
1086                banks.push(self.read_mux_bank(bank as u8)?);
1087            }
1088        }
1089        Ok(MuxSnapshot {
1090            model: self.model,
1091            banks,
1092        })
1093    }
1094
1095    fn read_mux_bank(&mut self, bank: u8) -> Result<MuxBankSnapshot, ReadError<I::Error>> {
1096        let width = *self
1097            .model
1098            .bank_widths()
1099            .get(usize::from(bank))
1100            .filter(|&&width| width != 0)
1101            .ok_or(ReadError::Protocol(ProtocolError::InvalidMuxBank(bank)))?
1102            as u8;
1103        let bytes = self.request(Command::Mux, &[0, 0, width, bank], usize::from(width) * 4)?;
1104        let snapshot = MuxBankSnapshot {
1105            bank,
1106            model: self.model,
1107            words: bytes
1108                .chunks_exact(4)
1109                .map(|v| u32::from_le_bytes(v.try_into().unwrap()))
1110                .collect(),
1111        };
1112        validate_bank(self.model, &snapshot).map_err(ReadError::Protocol)?;
1113        Ok(snapshot)
1114    }
1115
1116    fn set_mux_bank(&mut self, bank: &MuxBankSnapshot) -> Result<(), ReadError<I::Error>> {
1117        let mut bytes = vec![0, 0, bank.bank, 0];
1118        for word in &bank.words {
1119            bytes.extend(word.to_le_bytes());
1120        }
1121        self.request(Command::SetMux, &bytes, 0).map(|_| ())
1122    }
1123
1124    pub fn apply_mux(&mut self, edit: &MuxEdit) -> Result<MuxWriteReport, MuxWriteError<I::Error>> {
1125        let invalid = |e| MuxWriteError {
1126            failure: MuxFailure::Invalid(e),
1127            rollback: Vec::new(),
1128        };
1129        validate_snapshot(self.model, &edit.expected).map_err(invalid)?;
1130        let mut target = edit.expected.clone();
1131        let mut seen = Vec::new();
1132        for route in &edit.routes {
1133            if seen.contains(&(route.bank, route.destination)) {
1134                return Err(invalid(ProtocolError::InvalidMuxEdit));
1135            }
1136            seen.push((route.bank, route.destination));
1137            let source = port_id(self.model, route.source, true).map_err(invalid)?;
1138            let destination = port_id(self.model, route.destination, false).map_err(invalid)?;
1139            let bank = target
1140                .banks
1141                .get_mut(usize::from(route.bank))
1142                .ok_or_else(|| invalid(ProtocolError::InvalidMuxBank(route.bank)))?;
1143            let word = bank
1144                .words
1145                .iter_mut()
1146                .find(|word| **word != 0 && (**word & 0xfff) == u32::from(destination))
1147                .ok_or_else(|| invalid(ProtocolError::InvalidMuxEdit))?;
1148            *word = u32::from(destination) | (u32::from(source) << 12);
1149        }
1150        self.replace_mux(&edit.expected, &target)
1151    }
1152
1153    pub(crate) fn replace_mux(
1154        &mut self,
1155        expected: &MuxSnapshot,
1156        target: &MuxSnapshot,
1157    ) -> Result<MuxWriteReport, MuxWriteError<I::Error>> {
1158        let fail = |failure| MuxWriteError {
1159            failure,
1160            rollback: Vec::new(),
1161        };
1162        validate_snapshot(self.model, expected).map_err(|e| fail(MuxFailure::Invalid(e)))?;
1163        validate_snapshot(self.model, target).map_err(|e| fail(MuxFailure::Invalid(e)))?;
1164        // Includes info and every bank, so no write can rely on selector zero or
1165        // a snapshot captured before another controller changed the graph.
1166        let actual = self
1167            .read_mux_banks()
1168            .map_err(|e| fail(MuxFailure::Read(e)))?;
1169        if actual != *expected {
1170            return Err(fail(MuxFailure::Drift { actual }));
1171        }
1172        let mut attempted = Vec::new();
1173        let mut verified = actual.clone();
1174        for (old, new) in expected.banks.iter().zip(&target.banks) {
1175            if old == new {
1176                continue;
1177            }
1178            attempted.push(old);
1179            let result = self
1180                .set_mux_bank(new)
1181                .map_err(MuxFailure::Read)
1182                .and_then(|_| {
1183                    let actual = self.read_mux_bank(new.bank).map_err(MuxFailure::Read)?;
1184                    if actual != *new {
1185                        return Err(MuxFailure::Verification {
1186                            bank: new.bank,
1187                            actual,
1188                        });
1189                    }
1190                    Ok(actual)
1191                });
1192            match result {
1193                Ok(bank) => {
1194                    let index = usize::from(bank.bank);
1195                    verified.banks[index] = bank;
1196                }
1197                Err(failure) => {
1198                    let mut rollback = Vec::new();
1199                    for original in attempted.iter().rev() {
1200                        let restore = (|| {
1201                            if self.poisoned {
1202                                self.recover().map_err(MuxFailure::Read)?;
1203                            }
1204                            self.set_mux_bank(original).map_err(MuxFailure::Read)?;
1205                            let actual = self
1206                                .read_mux_bank(original.bank)
1207                                .map_err(MuxFailure::Read)?;
1208                            if actual != **original {
1209                                return Err(MuxFailure::Verification {
1210                                    bank: original.bank,
1211                                    actual,
1212                                });
1213                            }
1214                            Ok(())
1215                        })();
1216                        if let Err(error) = restore {
1217                            rollback.push((original.bank, error));
1218                        }
1219                    }
1220                    if !rollback.is_empty() {
1221                        self.poisoned = true;
1222                    }
1223                    return Err(MuxWriteError { failure, rollback });
1224                }
1225            }
1226        }
1227        Ok(MuxWriteReport {
1228            original: actual,
1229            verified,
1230        })
1231    }
1232
1233    pub fn read_all(&mut self) -> Result<RoutingReadback, ReadError<I::Error>> {
1234        let mux_zero = self.read_mux_zero()?;
1235        let mixes = (1..=self.model.mixer_outputs())
1236            .map(|output| self.read_mix(output))
1237            .collect::<Result<Vec<_>, _>>()?;
1238        Ok(RoutingReadback {
1239            model: self.model,
1240            mux_zero,
1241            mixes,
1242        })
1243    }
1244}
1245
1246// Independent geometry contract from the pinned ALSA model: destination
1247// groups and trailing empty slots, never inferred from a successful zero read.
1248fn bank_destinations_for(model: ReadModel, bank: u8) -> Result<Vec<u16>, ProtocolError> {
1249    use CandidateModel::*;
1250    if bank > 2 || model.bank_widths()[usize::from(bank)] == 0 {
1251        return Err(ProtocolError::InvalidMuxBank(bank));
1252    }
1253    let groups: Vec<(u16, u16, u16)> = match model.candidate {
1254        Scarlett6i6Gen2 => vec![
1255            (0x600, 0, 6),
1256            (0x080, 0, 4),
1257            (0x180, 0, 2),
1258            (0x300, 0, 18),
1259            (0, 0, 8),
1260        ],
1261        Scarlett18i8Gen2 => vec![
1262            (0x600, 0, [18, 14, 10][bank as usize]),
1263            (0x080, 0, 6),
1264            (0x180, 0, 2),
1265            (0x300, 0, 18),
1266            (0, 0, if bank == 2 { 4 } else { 8 }),
1267        ],
1268        Scarlett4i4Gen3 => vec![(0x600, 0, 6), (0x080, 0, 4), (0x300, 0, 8), (0, 0, 16)],
1269        Scarlett8i6Gen3 => vec![
1270            (0x600, 0, 8),
1271            (0x080, 0, 4),
1272            (0x180, 0, 2),
1273            (0x600, 8, 2),
1274            (0x300, 0, 8),
1275            (0, 0, 18),
1276        ],
1277        Scarlett18i8Gen3 => {
1278            let mut groups = vec![(0x600, 0, 10)];
1279            if bank < 2 {
1280                groups.push((0x600, 12, if bank == 0 { 8 } else { 4 }));
1281            }
1282            groups.extend([(0x080, 0, 2), (0x080, 6, 2), (0x080, 2, 4), (0x180, 0, 2)]);
1283            if bank < 2 {
1284                groups.push((0x600, 10, 2));
1285            }
1286            groups.extend([(0x300, 0, 20), (0, 0, 10)]);
1287            groups
1288        }
1289        Scarlett18i20Gen3 if bank == 2 => {
1290            vec![(0x600, 0, 10), (0x080, 0, 10), (0x180, 0, 2), (0, 0, 24)]
1291        }
1292        Scarlett18i20Gen3 => vec![
1293            (0x600, 0, 8),
1294            (0x600, 10, if bank == 0 { 10 } else { 8 }),
1295            (0x080, 0, 10),
1296            (0x180, 0, 2),
1297            (0x200, 0, 8),
1298            (0x600, 8, 2),
1299            (0x300, 0, 25),
1300            (0, 0, if bank == 0 { 12 } else { 10 }),
1301        ],
1302        ClarettUsb2Pre | ClarettPlus2Pre => {
1303            let mut groups = vec![(0x600, 0, [12, 8, 2][bank as usize]), (0x080, 0, 4)];
1304            if bank < 2 {
1305                groups.push((0x300, 0, 18));
1306            }
1307            groups.push((0, 0, if bank == 2 { 26 } else { 8 }));
1308            groups
1309        }
1310        ClarettUsb4Pre | ClarettPlus4Pre => {
1311            let mut groups = vec![
1312                (0x600, 0, [18, 14, 12][bank as usize]),
1313                (0x080, 0, 6),
1314                (0x180, 0, 2),
1315            ];
1316            if bank < 2 {
1317                groups.push((0x300, 0, 18));
1318            }
1319            groups.push((0, 0, if bank == 2 { 24 } else { 8 }));
1320            groups
1321        }
1322        ClarettUsb8Pre | ClarettPlus8Pre => {
1323            let mut groups = vec![
1324                (0x600, 0, [18, 14, 12][bank as usize]),
1325                (0x080, 0, 10),
1326                (0x180, 0, 2),
1327            ];
1328            if bank < 2 {
1329                groups.extend([(0x200, 0, if bank == 0 { 8 } else { 4 }), (0x300, 0, 18)]);
1330            }
1331            groups.push((0, 0, if bank == 2 { 22 } else { 8 }));
1332            groups
1333        }
1334        VocasterOne => vec![
1335            (0x300, 8, 1),
1336            (0x600, 5, 5),
1337            (0x300, 6, 2),
1338            (0x600, 0, 5),
1339            (0x300, 0, 6),
1340            (0x080, 0, 4),
1341        ],
1342        VocasterTwo => vec![
1343            (0x300, 12, 2),
1344            (0x600, 6, 8),
1345            (0x300, 10, 2),
1346            (0x600, 0, 6),
1347            (0x300, 0, 10),
1348            (0x080, 0, 6),
1349        ],
1350        ScarlettSoloGen4 | Scarlett2i2Gen4 => vec![
1351            (0x300, 4, 2),
1352            (0x300, 2, 2),
1353            (0x600, 0, 4),
1354            (0x300, 0, 2),
1355            (0x080, 0, 2),
1356        ],
1357        Scarlett4i4Gen4 => vec![(0x300, 10, 2), (0x600, 0, 6), (0x300, 0, 10), (0x080, 0, 6)],
1358        Scarlett18i20Gen2 => Vec::new(),
1359        Scarlett16i16Gen4 | Scarlett18i16Gen4 | Scarlett18i20Gen4 | IsaC8x => {
1360            return Err(ProtocolError::UnsupportedProtocol);
1361        }
1362    };
1363    if !groups.is_empty() {
1364        return Ok(groups
1365            .iter()
1366            .flat_map(|&(base, first, count)| {
1367                (first..first + count)
1368                    .map(move |channel| if base == 0 { 0 } else { base + channel })
1369            })
1370            .collect());
1371    }
1372    let (pcm, adat, padding) = match bank {
1373        0 => (18, 8, 8),
1374        1 => (14, 4, 8),
1375        2 => (10, 0, 6),
1376        _ => return Err(ProtocolError::InvalidMuxBank(bank)),
1377    };
1378    let mut ids = Vec::new();
1379    for (base, count) in [
1380        (0x600, pcm),
1381        (0x080, 10),
1382        (0x180, 2),
1383        (0x200, adat),
1384        (0x300, 18),
1385    ] {
1386        ids.extend((0..count).map(|channel| base + channel));
1387    }
1388    ids.extend(std::iter::repeat(0).take(padding));
1389    Ok(ids)
1390}
1391fn validate_bank(model: ReadModel, bank: &MuxBankSnapshot) -> Result<(), ProtocolError> {
1392    let destinations = bank_destinations_for(model, bank.bank)?;
1393    if bank.model != model {
1394        return Err(ProtocolError::UnsupportedMuxGeometry);
1395    }
1396    if destinations.len() != bank.words.len() {
1397        return Err(ProtocolError::UnsupportedMuxGeometry);
1398    }
1399    for (&destination, &word) in destinations.iter().zip(&bank.words) {
1400        if destination == 0 {
1401            if word != 0 {
1402                return Err(ProtocolError::UnsupportedMuxGeometry);
1403            }
1404        } else {
1405            if word >> 24 != 0 || word & 0xfff != u32::from(destination) {
1406                return Err(ProtocolError::UnsupportedMuxGeometry);
1407            }
1408            model.port(destination, false)?;
1409            model.port(((word >> 12) & 0xfff) as u16, true)?;
1410        }
1411    }
1412    Ok(())
1413}
1414fn validate_snapshot(model: ReadModel, snapshot: &MuxSnapshot) -> Result<(), ProtocolError> {
1415    if snapshot.model != model
1416        || snapshot.banks.len()
1417            != model
1418                .bank_widths()
1419                .iter()
1420                .filter(|&&width| width != 0)
1421                .count()
1422    {
1423        return Err(ProtocolError::UnsupportedMuxGeometry);
1424    }
1425    for (index, bank) in snapshot.banks.iter().enumerate() {
1426        if usize::from(bank.bank) != index {
1427            return Err(ProtocolError::UnsupportedMuxGeometry);
1428        }
1429        validate_bank(model, bank)?;
1430    }
1431    Ok(())
1432}
1433fn port_id(model: ReadModel, port: Port, source: bool) -> Result<u16, ProtocolError> {
1434    if port == Port::Off && source {
1435        return Ok(0);
1436    }
1437    if let Port::Channel { kind, channel } = port {
1438        let base = match kind {
1439            PortKind::Analogue => 0x080,
1440            PortKind::Spdif => 0x180,
1441            PortKind::Adat => 0x200,
1442            PortKind::Mix => 0x300,
1443            PortKind::Pcm => 0x600,
1444            PortKind::Off => return Err(ProtocolError::InvalidMuxEdit),
1445        };
1446        if channel != 0 && channel <= model.count(kind, source) {
1447            return Ok(base + u16::from(channel - 1));
1448        }
1449    }
1450    Err(ProtocolError::InvalidMuxEdit)
1451}
1452
1453pub fn decode_mux(model: ReadModel, bytes: &[u8]) -> Result<Vec<MuxRoute>, ProtocolError> {
1454    let expected = model.mux_destinations() * 4;
1455    if bytes.len() != expected {
1456        return Err(ProtocolError::InvalidLength {
1457            expected,
1458            actual: bytes.len(),
1459        });
1460    }
1461    let mut routes = Vec::with_capacity(model.mux_destinations());
1462    for part in bytes.chunks_exact(4) {
1463        let word = u32::from_le_bytes(part.try_into().unwrap());
1464        if word >> 24 != 0 {
1465            return Err(ProtocolError::InvalidMuxBits);
1466        }
1467        let source = model.port(((word >> 12) & 0xfff) as u16, true)?;
1468        let destination = model.port((word & 0xfff) as u16, false)?;
1469        if routes
1470            .iter()
1471            .any(|route: &MuxRoute| route.destination == destination)
1472        {
1473            return Err(ProtocolError::DuplicateDestination);
1474        }
1475        routes.push(MuxRoute {
1476            source,
1477            destination,
1478        });
1479    }
1480    Ok(routes)
1481}
1482
1483#[cfg(test)]
1484mod tests {
1485    use super::*;
1486
1487    fn model() -> ReadModel {
1488        CandidateModel::Scarlett18i20Gen2
1489            .validate_firmware(1083)
1490            .unwrap()
1491    }
1492
1493    fn mux_bytes() -> Vec<u8> {
1494        let mut bytes = Vec::new();
1495        for (base, count) in [
1496            (0x080u32, 10),
1497            (0x180, 2),
1498            (0x200, 8),
1499            (0x300, 18),
1500            (0x600, 18),
1501        ] {
1502            for channel in 0..count {
1503                bytes.extend((base + channel).to_le_bytes());
1504            }
1505        }
1506        bytes
1507    }
1508
1509    #[test]
1510    fn identity_and_firmware_guards_do_not_match_sibling_products() {
1511        assert_eq!(
1512            CandidateModel::recognize(0x1235, 0x8201),
1513            Some(CandidateModel::Scarlett18i20Gen2)
1514        );
1515        for (vendor, product) in [
1516            (0x1234, 0x8201),
1517            (0x1235, 0x8202),
1518            (0x1235, 0x8210),
1519            (0x1235, 0x821f),
1520        ] {
1521            assert_eq!(CandidateModel::recognize(vendor, product), None);
1522        }
1523        for (product, candidate) in [
1524            (0x821b, CandidateModel::Scarlett16i16Gen4),
1525            (0x821c, CandidateModel::Scarlett18i16Gen4),
1526            (0x821d, CandidateModel::Scarlett18i20Gen4),
1527            (0x821e, CandidateModel::IsaC8x),
1528        ] {
1529            assert_eq!(CandidateModel::recognize(0x1235, product), Some(candidate));
1530            assert_eq!(CandidateModel::recognize(0x1234, product), None);
1531            assert_eq!(
1532                candidate.validate_firmware(2778),
1533                Err(ProtocolError::UnsupportedProtocol)
1534            );
1535        }
1536        for firmware in [0, 1082, 1084, u32::MAX] {
1537            assert_eq!(
1538                CandidateModel::Scarlett18i20Gen2.validate_firmware(firmware),
1539                Err(ProtocolError::UnsupportedFirmware(firmware))
1540            );
1541        }
1542        assert_eq!(model().mixer_inputs(), 18);
1543        assert_eq!(model().mixer_outputs(), 10);
1544    }
1545
1546    #[test]
1547    fn envelope_uses_exact_little_endian_header_and_payload_length() {
1548        assert_eq!(
1549            packet(Command::Mix, 0x1234, &[9, 0, 18, 0]),
1550            vec![1, 32, 0, 0, 4, 0, 0x34, 0x12, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 18, 0]
1551        );
1552        let reply = packet(Command::Mix, 0x1234, &[1, 2]);
1553        assert_eq!(
1554            decode_reply(Command::Mix, 0x1234, 2, &reply),
1555            Ok(&[1, 2][..])
1556        );
1557    }
1558
1559    #[test]
1560    fn reply_rejects_command_sequence_status_padding_and_short_or_extra_bytes() {
1561        let good = packet(Command::Mix, 7, &[0, 1]);
1562        for (offset, value, expected) in [
1563            (0, 2, ProtocolError::InvalidCommand),
1564            (4, 1, ProtocolError::InvalidPayloadSize),
1565            (6, 8, ProtocolError::InvalidSequence),
1566            (8, 5, ProtocolError::DeviceStatus(5)),
1567            (12, 1, ProtocolError::NonzeroReserved),
1568        ] {
1569            let mut bad = good.clone();
1570            bad[offset] = value;
1571            assert_eq!(decode_reply(Command::Mix, 7, 2, &bad), Err(expected));
1572        }
1573        for len in [0, 15, 17, 19] {
1574            let mut bad = good.clone();
1575            bad.resize(len, 0);
1576            assert!(matches!(
1577                decode_reply(Command::Mix, 7, 2, &bad),
1578                Err(ProtocolError::InvalidLength { .. })
1579            ));
1580        }
1581        assert!(decode_reply(Command::Init, 1, 0, &packet(Command::Init, 0, &[])).is_ok());
1582        assert!(decode_reply(Command::Info, 1, 84, &packet(Command::Info, 0, &[0; 84])).is_ok());
1583        assert_eq!(
1584            decode_reply(Command::Mux, 1, 0, &packet(Command::Mux, 0, &[])),
1585            Err(ProtocolError::InvalidSequence)
1586        );
1587    }
1588
1589    #[test]
1590    fn mux_decodes_typed_ports_and_rejects_unknown_duplicate_and_reserved_bits() {
1591        let bytes = mux_bytes();
1592        let routes = decode_mux(model(), &bytes).unwrap();
1593        assert_eq!(routes.len(), 56);
1594        assert_eq!(
1595            routes[0],
1596            MuxRoute {
1597                source: Port::Off,
1598                destination: Port::Channel {
1599                    kind: PortKind::Analogue,
1600                    channel: 1
1601                }
1602            }
1603        );
1604        assert_eq!(
1605            routes[55].destination,
1606            Port::Channel {
1607                kind: PortKind::Pcm,
1608                channel: 18
1609            }
1610        );
1611        let mut source = bytes.clone();
1612        source[..4].copy_from_slice(&(0x613u32 << 12 | 0x080).to_le_bytes());
1613        assert_eq!(
1614            decode_mux(model(), &source).unwrap()[0].source,
1615            Port::Channel {
1616                kind: PortKind::Pcm,
1617                channel: 20
1618            }
1619        );
1620        source[..4].copy_from_slice(&(0x614u32 << 12 | 0x080).to_le_bytes());
1621        assert!(matches!(
1622            decode_mux(model(), &source),
1623            Err(ProtocolError::UnknownPort { source: true, .. })
1624        ));
1625        let mut duplicate = bytes.clone();
1626        duplicate[4..8].copy_from_slice(&bytes[..4]);
1627        assert_eq!(
1628            decode_mux(model(), &duplicate),
1629            Err(ProtocolError::DuplicateDestination)
1630        );
1631        let mut reserved = bytes.clone();
1632        reserved[3] = 1;
1633        assert_eq!(
1634            decode_mux(model(), &reserved),
1635            Err(ProtocolError::InvalidMuxBits)
1636        );
1637        let mut unknown = bytes.clone();
1638        unknown[..4].copy_from_slice(&0u32.to_le_bytes());
1639        assert!(matches!(
1640            decode_mux(model(), &unknown),
1641            Err(ProtocolError::UnknownPort { source: false, .. })
1642        ));
1643    }
1644
1645    struct MockIo {
1646        sent: Vec<Vec<u8>>,
1647        last: Vec<u8>,
1648        firmware: u32,
1649        notifications: usize,
1650        ack: bool,
1651        wrong_sequence: bool,
1652        short_send: bool,
1653        prepared: bool,
1654        row: Vec<u16>,
1655        writes: usize,
1656        fail_writes: Vec<usize>,
1657        corrupt_writes: Vec<usize>,
1658    }
1659    impl Default for MockIo {
1660        fn default() -> Self {
1661            Self {
1662                sent: Vec::new(),
1663                last: Vec::new(),
1664                firmware: 1083,
1665                notifications: 0,
1666                ack: true,
1667                wrong_sequence: false,
1668                short_send: false,
1669                prepared: false,
1670                row: vec![0x1234; 18],
1671                writes: 0,
1672                fail_writes: Vec::new(),
1673                corrupt_writes: Vec::new(),
1674            }
1675        }
1676    }
1677    impl ReadIo for MockIo {
1678        type Error = &'static str;
1679        fn initial_read(&mut self, _: &mut [u8; 24]) -> Result<usize, Self::Error> {
1680            Ok(24)
1681        }
1682        fn prepare_notifications(&mut self) -> Result<(), Self::Error> {
1683            self.prepared = true;
1684            Ok(())
1685        }
1686        fn send_request(&mut self, bytes: &[u8]) -> Result<usize, Self::Error> {
1687            assert!(self.prepared);
1688            self.sent.push(bytes.to_vec());
1689            self.last = bytes.to_vec();
1690            if u32::from_le_bytes(bytes[..4].try_into().unwrap()) == 0x2002 {
1691                self.writes += 1;
1692                self.row = bytes[HEADER + 2..]
1693                    .chunks_exact(2)
1694                    .map(|part| u16::from_le_bytes([part[0], part[1]]))
1695                    .collect();
1696                if self.corrupt_writes.contains(&self.writes) {
1697                    self.row[17] ^= 1;
1698                }
1699                if self.fail_writes.contains(&self.writes) {
1700                    return Err("lost SET response");
1701                }
1702            }
1703            Ok(if self.short_send { 0 } else { bytes.len() })
1704        }
1705        fn next_notification(
1706            &mut self,
1707            bytes: &mut [u8; 8],
1708            timeout: Duration,
1709        ) -> Result<usize, Self::Error> {
1710            assert!(timeout <= ACK_TIMEOUT && !timeout.is_zero());
1711            self.notifications += 1;
1712            bytes[0] = if self.ack { 1 } else { 2 };
1713            Ok(8)
1714        }
1715        fn receive_response(&mut self, bytes: &mut [u8]) -> Result<usize, Self::Error> {
1716            bytes[..HEADER].copy_from_slice(&self.last[..HEADER]);
1717            let command = u32::from_le_bytes(bytes[..4].try_into().unwrap());
1718            let payload_size = (bytes.len() - HEADER) as u16;
1719            bytes[4..6].copy_from_slice(&payload_size.to_le_bytes());
1720            match command {
1721                0 => bytes[6..8].copy_from_slice(&0u16.to_le_bytes()),
1722                2 => {
1723                    bytes[6..8].copy_from_slice(&0u16.to_le_bytes());
1724                    bytes[24..28].copy_from_slice(&self.firmware.to_le_bytes());
1725                }
1726                0x3001 => bytes[HEADER..].copy_from_slice(&mux_bytes()),
1727                0x2001 => {
1728                    for (part, value) in bytes[HEADER..].chunks_exact_mut(2).zip(&self.row) {
1729                        part.copy_from_slice(&value.to_le_bytes());
1730                    }
1731                }
1732                0x2002 => {}
1733                _ => panic!("unexpected command"),
1734            }
1735            if self.wrong_sequence {
1736                bytes[6] = 255;
1737            }
1738            Ok(bytes.len())
1739        }
1740    }
1741
1742    #[test]
1743    fn handshake_resets_sequence_then_reads_mux_and_mix_without_set_commands() {
1744        let mut session =
1745            ReadSession::initialize(MockIo::default(), CandidateModel::Scarlett18i20Gen2).unwrap();
1746        let result = session.read_all().unwrap();
1747        assert_eq!(result.mixes.len(), 10);
1748        assert_eq!(result.mixes[0].coefficients, vec![0x1234; 18]);
1749        assert_eq!(session.io.sent.len(), 13);
1750        let commands = session
1751            .io
1752            .sent
1753            .iter()
1754            .map(|packet| u32::from_le_bytes(packet[..4].try_into().unwrap()))
1755            .collect::<Vec<_>>();
1756        assert_eq!(&commands[..3], &[0, 2, 0x3001]);
1757        assert!(commands[3..].iter().all(|&code| code == 0x2001));
1758        let sequences = session
1759            .io
1760            .sent
1761            .iter()
1762            .map(|packet| u16::from_le_bytes(packet[6..8].try_into().unwrap()))
1763            .collect::<Vec<_>>();
1764        assert_eq!(&sequences[..4], &[1, 1, 2, 3]);
1765        assert_eq!(&session.io.sent[2][HEADER..], &[0, 0, 56, 0]);
1766        assert_eq!(&session.io.sent[12][HEADER..], &[9, 0, 18, 0]);
1767    }
1768
1769    #[test]
1770    fn unsupported_firmware_stops_before_any_routing_query() {
1771        let result = ReadSession::initialize(
1772            MockIo {
1773                firmware: 1084,
1774                ..MockIo::default()
1775            },
1776            CandidateModel::Scarlett18i20Gen2,
1777        );
1778        assert!(matches!(
1779            result,
1780            Err(ReadError::Protocol(ProtocolError::UnsupportedFirmware(
1781                1084
1782            )))
1783        ));
1784    }
1785
1786    #[test]
1787    fn ack_budget_invalid_mix_and_poisoned_sequence_are_bounded() {
1788        let mut io = MockIo {
1789            ack: false,
1790            ..MockIo::default()
1791        };
1792        io.prepare_notifications().unwrap();
1793        assert_eq!(
1794            transact(&mut io, Command::Init, 1, &[], 0),
1795            Err(ReadError::Protocol(ProtocolError::AcknowledgementTimeout))
1796        );
1797        assert_eq!(io.notifications, MAX_NOTIFICATIONS);
1798        let mut session =
1799            ReadSession::initialize(MockIo::default(), CandidateModel::Scarlett18i20Gen2).unwrap();
1800        for output in [0, 11, 255] {
1801            assert_eq!(
1802                session.read_mix(output),
1803                Err(ReadError::Protocol(ProtocolError::InvalidMixOutput(output)))
1804            );
1805        }
1806        assert_eq!(session.io.sent.len(), 2);
1807        session.io.wrong_sequence = true;
1808        assert_eq!(
1809            session.read_mix(1),
1810            Err(ReadError::Protocol(ProtocolError::InvalidSequence))
1811        );
1812        let sent = session.io.sent.len();
1813        assert_eq!(
1814            session.read_mix(1),
1815            Err(ReadError::Protocol(ProtocolError::SessionPoisoned))
1816        );
1817        assert_eq!(session.io.sent.len(), sent);
1818    }
1819
1820    #[test]
1821    fn short_out_transfer_does_not_wait_for_ack_or_attempt_response() {
1822        let mut io = MockIo {
1823            short_send: true,
1824            ..MockIo::default()
1825        };
1826        io.prepare_notifications().unwrap();
1827        assert!(matches!(
1828            transact(&mut io, Command::Init, 1, &[], 0),
1829            Err(ReadError::Protocol(ProtocolError::InvalidLength { .. }))
1830        ));
1831        assert_eq!(io.notifications, 0);
1832    }
1833    fn row_edit() -> MixRowEdit {
1834        MixRowEdit {
1835            expected: MixReadback {
1836                output: 2,
1837                coefficients: vec![0x1234; 18],
1838            },
1839            gains: vec![MixGainEdit {
1840                input: 3,
1841                gain: MixGain::from_half_db(-12).unwrap(),
1842            }],
1843        }
1844    }
1845
1846    #[test]
1847    fn bounded_half_db_formula_and_whole_row_preservation() {
1848        assert!(MixGain::from_half_db(-161).is_err());
1849        assert!(MixGain::from_half_db(25).is_err());
1850        assert_eq!(MixGain::from_half_db(-160).unwrap().coefficient(), 0);
1851        assert_eq!(MixGain::from_half_db(0).unwrap().coefficient(), 8192);
1852        assert_eq!(MixGain::from_half_db(24).unwrap().coefficient(), 32612);
1853        let mut edit = row_edit();
1854        edit.expected.coefficients[17] = u16::MAX;
1855        let mut session = ReadSession::initialize(
1856            MockIo {
1857                row: edit.expected.coefficients.clone(),
1858                ..MockIo::default()
1859            },
1860            CandidateModel::Scarlett18i20Gen2,
1861        )
1862        .unwrap();
1863        let report = session.apply_mix(&edit).unwrap();
1864        assert_eq!(report.verified.coefficients[17], u16::MAX);
1865        assert_eq!(
1866            report.verified.coefficients[2],
1867            edit.gains[0].gain.coefficient()
1868        );
1869        let set = session
1870            .io
1871            .sent
1872            .iter()
1873            .find(|p| p[..4] == 0x2002u32.to_le_bytes())
1874            .unwrap();
1875        assert_eq!(set.len(), HEADER + 38);
1876        assert_eq!(&set[HEADER..HEADER + 2], &[1, 0]);
1877        assert_eq!(session.io.writes, 1);
1878    }
1879
1880    #[test]
1881    fn stale_and_invalid_rows_never_write() {
1882        let mut session =
1883            ReadSession::initialize(MockIo::default(), CandidateModel::Scarlett18i20Gen2).unwrap();
1884        let mut edit = row_edit();
1885        edit.expected.coefficients[0] ^= 1;
1886        assert!(matches!(
1887            session.apply_mix(&edit).unwrap_err().failure,
1888            MixFailure::Drift { .. }
1889        ));
1890        edit.expected.coefficients.pop();
1891        assert!(matches!(
1892            session.apply_mix(&edit).unwrap_err().failure,
1893            MixFailure::Invalid(ProtocolError::InvalidLength { .. })
1894        ));
1895        edit = row_edit();
1896        edit.gains.push(edit.gains[0]);
1897        assert!(matches!(
1898            session.apply_mix(&edit).unwrap_err().failure,
1899            MixFailure::Invalid(ProtocolError::DuplicateMixInput(3))
1900        ));
1901        assert_eq!(session.io.writes, 0);
1902    }
1903
1904    #[test]
1905    fn failed_write_and_bad_readback_restore_exact_original() {
1906        for io in [
1907            MockIo {
1908                fail_writes: vec![1],
1909                ..MockIo::default()
1910            },
1911            MockIo {
1912                corrupt_writes: vec![1],
1913                ..MockIo::default()
1914            },
1915        ] {
1916            let mut session =
1917                ReadSession::initialize(io, CandidateModel::Scarlett18i20Gen2).unwrap();
1918            let error = session.apply_mix(&row_edit()).unwrap_err();
1919            assert!(error.rollback.is_none());
1920            assert_eq!(session.io.row, row_edit().expected.coefficients);
1921            assert_eq!(session.io.writes, 2);
1922        }
1923    }
1924
1925    #[test]
1926    fn rollback_uncertainty_retains_original_failure_and_blocks_reuse() {
1927        let io = MockIo {
1928            fail_writes: vec![1, 2],
1929            ..MockIo::default()
1930        };
1931        let mut session = ReadSession::initialize(io, CandidateModel::Scarlett18i20Gen2).unwrap();
1932        let error = session.apply_mix(&row_edit()).unwrap_err();
1933        assert_eq!(
1934            error.failure,
1935            MixFailure::Read(ReadError::Io("lost SET response"))
1936        );
1937        assert_eq!(
1938            error.rollback,
1939            Some(MixFailure::Read(ReadError::Io("lost SET response")))
1940        );
1941        assert_eq!(
1942            session.read_mix(2),
1943            Err(ReadError::Protocol(ProtocolError::SessionPoisoned))
1944        );
1945    }
1946
1947    #[test]
1948    fn hand_back_row_check_preserves_external_coefficient_drift() {
1949        let mut session =
1950            ReadSession::initialize(MockIo::default(), CandidateModel::Scarlett18i20Gen2).unwrap();
1951        let report = session.apply_mix(&row_edit()).unwrap();
1952        session.io.row[17] ^= 1;
1953        assert!(matches!(
1954            session
1955                .replace_mix(&report.verified, &report.original)
1956                .unwrap_err()
1957                .failure,
1958            MixFailure::Drift { .. }
1959        ));
1960        assert_eq!(session.io.writes, 1);
1961    }
1962    // Inline independent protocol peer: existing legacy mocks remain unchanged.
1963    struct ProfileIo {
1964        base: MockIo,
1965        model: ReadModel,
1966        corrupt: u8,
1967    }
1968    impl ReadIo for ProfileIo {
1969        type Error = &'static str;
1970        fn initial_read(&mut self, bytes: &mut [u8; 24]) -> Result<usize, Self::Error> {
1971            self.base.initial_read(bytes)
1972        }
1973        fn prepare_notifications(&mut self) -> Result<(), Self::Error> {
1974            self.base.prepare_notifications()
1975        }
1976        fn send_request(&mut self, bytes: &[u8]) -> Result<usize, Self::Error> {
1977            self.base.send_request(bytes)
1978        }
1979        fn next_notification(
1980            &mut self,
1981            bytes: &mut [u8; 8],
1982            timeout: Duration,
1983        ) -> Result<usize, Self::Error> {
1984            self.base.next_notification(bytes, timeout)
1985        }
1986        fn receive_response(&mut self, bytes: &mut [u8]) -> Result<usize, Self::Error> {
1987            let command = u32::from_le_bytes(self.base.last[..4].try_into().unwrap());
1988            if command == 0 || command == 2 {
1989                return self.base.receive_response(bytes);
1990            }
1991            bytes[..HEADER].copy_from_slice(&self.base.last[..HEADER]);
1992            let payload_size = (bytes.len() - HEADER) as u16;
1993            bytes[4..6].copy_from_slice(&payload_size.to_le_bytes());
1994            match command {
1995                0x3000 => {
1996                    for (part, width) in bytes[HEADER..]
1997                        .chunks_exact_mut(2)
1998                        .zip(self.model.bank_widths())
1999                    {
2000                        part.copy_from_slice(&width.to_le_bytes());
2001                    }
2002                    if self.corrupt == 1 {
2003                        bytes[HEADER] ^= 1;
2004                    }
2005                    if self.corrupt == 5 {
2006                        bytes[8..12].copy_from_slice(&1u32.to_le_bytes());
2007                    }
2008                }
2009                0x3001 => {
2010                    let bank = self.base.last[HEADER + 3];
2011                    for (part, id) in bytes[HEADER..]
2012                        .chunks_exact_mut(4)
2013                        .zip(bank_destinations_for(self.model, bank).unwrap())
2014                    {
2015                        part.copy_from_slice(&u32::from(id).to_le_bytes());
2016                    }
2017                    if self.corrupt == 2 {
2018                        bytes[HEADER..HEADER + 4].copy_from_slice(&0x180u32.to_le_bytes());
2019                    }
2020                }
2021                0x2001 => {
2022                    assert_eq!(
2023                        bytes.len() - HEADER,
2024                        usize::from(self.model.mixer_inputs()) * 2
2025                    );
2026                    if self.corrupt == 3 {
2027                        return Ok(bytes.len() - 1);
2028                    }
2029                }
2030                _ => panic!("profile proof must never write"),
2031            }
2032            if self.corrupt == 4 {
2033                bytes[6] ^= 1;
2034            }
2035            Ok(bytes.len())
2036        }
2037    }
2038    #[test]
2039    fn new_profiles_require_complete_live_geometry_and_correct_dsp_dimensions() {
2040        for (product, firmware, inputs, outputs, destinations, banks) in [
2041            (0x8216, 1769, 8, 8, 23, 1),
2042            (0x8217, 1769, 12, 10, 34, 1),
2043            (0x8218, 2115, 4, 6, 12, 3),
2044            (0x8219, 2115, 4, 4, 12, 3),
2045            (0x821a, 2089, 10, 6, 24, 3),
2046        ] {
2047            let candidate = CandidateModel::recognize(0x1235, product).unwrap();
2048            assert!(candidate.validate_firmware(firmware - 1).is_err());
2049            let model = candidate.validate_firmware(firmware).unwrap();
2050            assert_eq!(
2051                (
2052                    model.mixer_inputs(),
2053                    model.mixer_outputs(),
2054                    model.mux_destinations()
2055                ),
2056                (inputs, outputs, destinations)
2057            );
2058            assert!(model.port(0x180, true).is_err());
2059            assert!(model
2060                .port(
2061                    0x080 + u16::from(model.count(PortKind::Analogue, false)),
2062                    false
2063                )
2064                .is_err());
2065            for corrupt in 0..=4 {
2066                let io = ProfileIo {
2067                    base: MockIo {
2068                        firmware,
2069                        ..MockIo::default()
2070                    },
2071                    model,
2072                    corrupt,
2073                };
2074                let result = ReadSession::initialize(io, candidate);
2075                if corrupt == 0 {
2076                    let mut session = result.unwrap();
2077                    let snapshot = session.read_mux_banks().unwrap();
2078                    assert_eq!(snapshot.banks.len(), banks);
2079                    for bank in &snapshot.banks {
2080                        assert_eq!(bank.routes().len(), bank.raw_words().len());
2081                        assert_eq!(bank.model, model);
2082                    }
2083                    assert_eq!(session.io.base.writes, 0);
2084                } else {
2085                    assert!(
2086                        result.is_err(),
2087                        "{candidate:?} accepted corrupt proof {corrupt}"
2088                    );
2089                }
2090            }
2091        }
2092    }
2093
2094    #[test]
2095    fn legacy_profiles_require_nonzero_firmware_and_full_read_proof() {
2096        for (product, inputs, outputs, destinations, widths) in [
2097            (0x8203, 18, 10, 30, [38, 38, 38]),
2098            (0x8204, 18, 10, 44, [52, 48, 40]),
2099            (0x8212, 8, 6, 18, [34, 34, 34]),
2100            (0x8213, 8, 8, 24, [42, 42, 42]),
2101            (0x8214, 20, 10, 50, [60, 56, 50]),
2102            (0x8215, 25, 12, 65, [77, 73, 46]),
2103        ] {
2104            let candidate = CandidateModel::recognize(0x1235, product).unwrap();
2105            assert!(candidate.validate_firmware(0).is_err());
2106            // No invented firmware floor: published geometry plus live proof.
2107            for firmware in [1, 1083, 4096] {
2108                let model = candidate.validate_firmware(firmware).unwrap();
2109                assert_eq!(
2110                    (
2111                        model.mixer_inputs(),
2112                        model.mixer_outputs(),
2113                        model.mux_destinations()
2114                    ),
2115                    (inputs, outputs, destinations)
2116                );
2117                assert_eq!(model.bank_widths(), widths);
2118                for corrupt in [0, 2, 3, 4] {
2119                    let io = ProfileIo {
2120                        base: MockIo {
2121                            firmware,
2122                            ..MockIo::default()
2123                        },
2124                        model,
2125                        corrupt,
2126                    };
2127                    let result = ReadSession::initialize(io, candidate);
2128                    if corrupt == 0 {
2129                        let mut session = result.unwrap();
2130                        let snapshot = session.read_mux_banks().unwrap();
2131                        assert_eq!(snapshot.banks.len(), 3);
2132                        for bank in snapshot.banks {
2133                            assert_eq!(bank.words.len(), usize::from(widths[bank.bank as usize]));
2134                            validate_bank(model, &bank).unwrap();
2135                        }
2136                        assert_eq!(session.io.base.writes, 0);
2137                    } else {
2138                        assert!(
2139                            result.is_err(),
2140                            "{candidate:?} accepted corrupt live proof {corrupt}"
2141                        );
2142                    }
2143                }
2144            }
2145        }
2146    }
2147
2148    #[test]
2149    fn clarett_exact_usb_and_plus_identities_require_complete_live_reads() {
2150        use CandidateModel::*;
2151        for (product, candidate, key, name) in [
2152            (
2153                0x8206,
2154                ClarettUsb2Pre,
2155                "clarett_usb_2pre",
2156                "Clarett USB 2Pre",
2157            ),
2158            (
2159                0x8207,
2160                ClarettUsb4Pre,
2161                "clarett_usb_4pre",
2162                "Clarett USB 4Pre",
2163            ),
2164            (
2165                0x8208,
2166                ClarettUsb8Pre,
2167                "clarett_usb_8pre",
2168                "Clarett USB 8Pre",
2169            ),
2170            (
2171                0x820a,
2172                ClarettPlus2Pre,
2173                "clarett_plus_2pre",
2174                "Clarett+ 2Pre",
2175            ),
2176            (
2177                0x820b,
2178                ClarettPlus4Pre,
2179                "clarett_plus_4pre",
2180                "Clarett+ 4Pre",
2181            ),
2182            (
2183                0x820c,
2184                ClarettPlus8Pre,
2185                "clarett_plus_8pre",
2186                "Clarett+ 8Pre",
2187            ),
2188        ] {
2189            assert_eq!(CandidateModel::recognize(0x1235, product), Some(candidate));
2190            assert_eq!(CandidateModel::recognize(0x1234, product), None);
2191            assert_eq!(candidate.key(), key);
2192            assert_eq!(candidate.name(), name);
2193            assert_eq!(
2194                candidate.validate_firmware(0),
2195                Err(ProtocolError::UnsupportedFirmware(0))
2196            );
2197            for firmware in [1, 1083, 4096] {
2198                let model = candidate.validate_firmware(firmware).unwrap();
2199                // Wrong destination, short MIX row and wrong reply sequence
2200                // must fail admission even with an accepted nonzero firmware.
2201                for corrupt in [0, 2, 3, 4] {
2202                    let io = ProfileIo {
2203                        base: MockIo {
2204                            firmware,
2205                            ..MockIo::default()
2206                        },
2207                        model,
2208                        corrupt,
2209                    };
2210                    let result = ReadSession::initialize(io, candidate);
2211                    if corrupt == 0 {
2212                        let session = result.unwrap();
2213                        assert_eq!(session.model(), model);
2214                        let mux_reads = session
2215                            .io
2216                            .base
2217                            .sent
2218                            .iter()
2219                            .filter(|p| p[..4] == 0x3001u32.to_le_bytes())
2220                            .count();
2221                        let mix_reads = session
2222                            .io
2223                            .base
2224                            .sent
2225                            .iter()
2226                            .filter(|p| p[..4] == 0x2001u32.to_le_bytes())
2227                            .count();
2228                        assert_eq!((mux_reads, mix_reads), (1, 10));
2229                        assert_eq!(session.io.base.writes, 0);
2230                    } else {
2231                        assert!(
2232                            result.is_err(),
2233                            "{candidate:?} accepted corrupt proof {corrupt}"
2234                        );
2235                    }
2236                }
2237                // Unsupported or wrong optional bank geometry must not prevent
2238                // read-only admission or authorize a bank write.
2239                for corrupt in [1, 5] {
2240                    let io = ProfileIo {
2241                        base: MockIo {
2242                            firmware,
2243                            ..MockIo::default()
2244                        },
2245                        model,
2246                        corrupt,
2247                    };
2248                    let mut session = ReadSession::initialize(io, candidate).unwrap();
2249                    assert!(session.read_mux_banks().is_err());
2250                    assert!(!session.poisoned);
2251                    assert_eq!(session.io.base.writes, 0);
2252                }
2253            }
2254        }
2255        for product in [0x8205, 0x8209, 0x820d] {
2256            assert_eq!(CandidateModel::recognize(0x1235, product), None);
2257        }
2258    }
2259
2260    #[test]
2261    fn clarett_geometry_matches_independent_port_and_bank_contracts() {
2262        use CandidateModel::*;
2263        // Source/destination counts are independent expected protocol identities;
2264        // in particular 2Pre has S/PDIF sources but no S/PDIF destinations.
2265        for (candidates, counts, widths, banks) in [
2266            (
2267                [ClarettUsb2Pre, ClarettPlus2Pre],
2268                [[2, 4], [2, 0], [8, 0], [10, 18], [4, 12]],
2269                [42, 38, 32],
2270                [
2271                    vec![(0x600, 12), (0x080, 4), (0x300, 18), (0, 8)],
2272                    vec![(0x600, 8), (0x080, 4), (0x300, 18), (0, 8)],
2273                    vec![(0x600, 2), (0x080, 4), (0, 26)],
2274                ],
2275            ),
2276            (
2277                [ClarettUsb4Pre, ClarettPlus4Pre],
2278                [[8, 6], [2, 2], [8, 0], [10, 18], [8, 18]],
2279                [52, 48, 44],
2280                [
2281                    vec![(0x600, 18), (0x080, 6), (0x180, 2), (0x300, 18), (0, 8)],
2282                    vec![(0x600, 14), (0x080, 6), (0x180, 2), (0x300, 18), (0, 8)],
2283                    vec![(0x600, 12), (0x080, 6), (0x180, 2), (0, 24)],
2284                ],
2285            ),
2286            (
2287                [ClarettUsb8Pre, ClarettPlus8Pre],
2288                [[8, 10], [2, 2], [8, 8], [10, 18], [20, 18]],
2289                [64, 56, 46],
2290                [
2291                    vec![
2292                        (0x600, 18),
2293                        (0x080, 10),
2294                        (0x180, 2),
2295                        (0x200, 8),
2296                        (0x300, 18),
2297                        (0, 8),
2298                    ],
2299                    vec![
2300                        (0x600, 14),
2301                        (0x080, 10),
2302                        (0x180, 2),
2303                        (0x200, 4),
2304                        (0x300, 18),
2305                        (0, 8),
2306                    ],
2307                    vec![(0x600, 12), (0x080, 10), (0x180, 2), (0, 22)],
2308                ],
2309            ),
2310        ] {
2311            for candidate in candidates {
2312                let model = candidate.validate_firmware(1).unwrap();
2313                assert_eq!((model.mixer_inputs(), model.mixer_outputs()), (18, 10));
2314                assert_eq!(model.bank_widths(), widths);
2315                for (kind, [sources, destinations]) in [
2316                    PortKind::Analogue,
2317                    PortKind::Spdif,
2318                    PortKind::Adat,
2319                    PortKind::Mix,
2320                    PortKind::Pcm,
2321                ]
2322                .into_iter()
2323                .zip(counts)
2324                {
2325                    assert_eq!(model.count(kind, true), sources);
2326                    assert_eq!(model.count(kind, false), destinations);
2327                }
2328                for (bank, groups) in banks.iter().enumerate() {
2329                    let expected: Vec<u16> = groups
2330                        .iter()
2331                        .flat_map(|&(base, count)| {
2332                            (0..count)
2333                                .map(move |channel| if base == 0 { 0 } else { base + channel })
2334                        })
2335                        .collect();
2336                    assert_eq!(expected.len(), usize::from(widths[bank]));
2337                    assert_eq!(bank_destinations_for(model, bank as u8).unwrap(), expected);
2338                    let snapshot = MuxBankSnapshot {
2339                        bank: bank as u8,
2340                        model,
2341                        words: expected.iter().copied().map(u32::from).collect(),
2342                    };
2343                    validate_bank(model, &snapshot).unwrap();
2344                    let mut wrong = snapshot.clone();
2345                    wrong.words.swap(0, 1);
2346                    assert_eq!(
2347                        validate_bank(model, &wrong),
2348                        Err(ProtocolError::UnsupportedMuxGeometry)
2349                    );
2350                    let mut short = snapshot;
2351                    short.words.pop();
2352                    assert_eq!(
2353                        validate_bank(model, &short),
2354                        Err(ProtocolError::UnsupportedMuxGeometry)
2355                    );
2356                }
2357            }
2358        }
2359    }
2360
2361    #[test]
2362    fn unsupported_legacy_bank_probe_recovers_independent_mixer_reads() {
2363        let candidate = CandidateModel::Scarlett18i20Gen3;
2364        let model = candidate.validate_firmware(1).unwrap();
2365        let io = ProfileIo {
2366            base: MockIo {
2367                firmware: 1,
2368                ..MockIo::default()
2369            },
2370            model,
2371            corrupt: 5,
2372        };
2373        let mut session = ReadSession::initialize(io, candidate).unwrap();
2374        assert!(matches!(
2375            session.read_mux_banks(),
2376            Err(ReadError::Protocol(ProtocolError::DeviceStatus(1)))
2377        ));
2378        assert!(!session.poisoned);
2379        let read = session.read_all().unwrap();
2380        assert_eq!(read.mixes.len(), 12);
2381        assert_eq!(read.mixes[11].coefficients.len(), 25);
2382        assert_eq!(session.io.base.writes, 0);
2383        session.io.base.short_send = true;
2384        assert!(session.read_mux_banks().is_err());
2385        assert!(session.poisoned);
2386        assert!(matches!(
2387            session.read_mix(1),
2388            Err(ReadError::Protocol(ProtocolError::SessionPoisoned))
2389        ));
2390    }
2391
2392    struct BankIo {
2393        base: MockIo,
2394        banks: Vec<MuxBankSnapshot>,
2395        writes: Vec<u8>,
2396        lost: Vec<usize>,
2397        corrupt: Vec<usize>,
2398        unsupported: bool,
2399        bad_width: bool,
2400    }
2401    impl Default for BankIo {
2402        fn default() -> Self {
2403            Self {
2404                base: MockIo::default(),
2405                banks: (0..3)
2406                    .map(|bank| MuxBankSnapshot {
2407                        bank,
2408                        model: model(),
2409                        words: bank_destinations_for(model(), bank)
2410                            .unwrap()
2411                            .into_iter()
2412                            .map(u32::from)
2413                            .collect(),
2414                    })
2415                    .collect(),
2416                writes: Vec::new(),
2417                lost: Vec::new(),
2418                corrupt: Vec::new(),
2419                unsupported: false,
2420                bad_width: false,
2421            }
2422        }
2423    }
2424    impl ReadIo for BankIo {
2425        type Error = &'static str;
2426        fn initial_read(&mut self, bytes: &mut [u8; 24]) -> Result<usize, Self::Error> {
2427            self.base.initial_read(bytes)
2428        }
2429        fn prepare_notifications(&mut self) -> Result<(), Self::Error> {
2430            self.base.prepare_notifications()
2431        }
2432        fn send_request(&mut self, bytes: &[u8]) -> Result<usize, Self::Error> {
2433            let n = self.base.send_request(bytes)?;
2434            if bytes[..4] == 0x3002u32.to_le_bytes() {
2435                let bank = bytes[HEADER + 2];
2436                self.writes.push(bank);
2437                self.banks[usize::from(bank)].words = bytes[HEADER + 4..]
2438                    .chunks_exact(4)
2439                    .map(|word| u32::from_le_bytes(word.try_into().unwrap()))
2440                    .collect();
2441                if self.corrupt.contains(&self.writes.len()) {
2442                    self.banks[usize::from(bank)].words[0] ^= 1 << 12;
2443                }
2444            }
2445            Ok(n)
2446        }
2447        fn next_notification(
2448            &mut self,
2449            bytes: &mut [u8; 8],
2450            timeout: Duration,
2451        ) -> Result<usize, Self::Error> {
2452            self.base.next_notification(bytes, timeout)
2453        }
2454        fn receive_response(&mut self, bytes: &mut [u8]) -> Result<usize, Self::Error> {
2455            let command = u32::from_le_bytes(self.base.last[..4].try_into().unwrap());
2456            if command != 0x3000 && command != 0x3001 && command != 0x3002 {
2457                return self.base.receive_response(bytes);
2458            }
2459            if command == 0x3002 && self.lost.contains(&self.writes.len()) {
2460                return Err("lost mux response");
2461            }
2462            bytes[..HEADER].copy_from_slice(&self.base.last[..HEADER]);
2463            let payload_size = (bytes.len() - HEADER) as u16;
2464            bytes[4..6].copy_from_slice(&payload_size.to_le_bytes());
2465            match command {
2466                0x3000 => {
2467                    for (part, width) in bytes[HEADER..]
2468                        .chunks_exact_mut(2)
2469                        .zip([64u16, 56, 46, 0, 0, 0])
2470                    {
2471                        part.copy_from_slice(&width.to_le_bytes());
2472                    }
2473                    if self.bad_width {
2474                        bytes[HEADER] = 63;
2475                    }
2476                    if self.unsupported {
2477                        bytes[8..12].copy_from_slice(&1u32.to_le_bytes());
2478                    }
2479                }
2480                0x3001 => {
2481                    let bank = self.base.last[HEADER + 3];
2482                    assert_eq!(self.base.last[HEADER], 0);
2483                    assert_eq!(self.base.last[HEADER + 1], 0);
2484                    assert_eq!(
2485                        usize::from(self.base.last[HEADER + 2]) * 4,
2486                        bytes.len() - HEADER
2487                    );
2488                    for (part, word) in bytes[HEADER..]
2489                        .chunks_exact_mut(4)
2490                        .zip(&self.banks[usize::from(bank)].words)
2491                    {
2492                        part.copy_from_slice(&word.to_le_bytes());
2493                    }
2494                }
2495                0x3002 => {}
2496                _ => unreachable!(),
2497            }
2498            Ok(bytes.len())
2499        }
2500    }
2501    fn bank_session(io: BankIo) -> ReadSession<BankIo> {
2502        ReadSession::initialize(io, CandidateModel::Scarlett18i20Gen2).unwrap()
2503    }
2504    fn bank_edit(session: &mut ReadSession<BankIo>) -> MuxEdit {
2505        MuxEdit {
2506            expected: session.read_mux_banks().unwrap(),
2507            routes: vec![0, 1]
2508                .into_iter()
2509                .map(|bank| MuxRouteEdit {
2510                    bank,
2511                    destination: Port::Channel {
2512                        kind: PortKind::Analogue,
2513                        channel: 1,
2514                    },
2515                    source: Port::Channel {
2516                        kind: PortKind::Pcm,
2517                        channel: 2,
2518                    },
2519                })
2520                .collect(),
2521        }
2522    }
2523    #[test]
2524    fn mux_probe_requires_exact_complete_geometry_and_preserves_raw_banks() {
2525        for io in [
2526            BankIo {
2527                unsupported: true,
2528                ..BankIo::default()
2529            },
2530            BankIo {
2531                bad_width: true,
2532                ..BankIo::default()
2533            },
2534        ] {
2535            let mut session = bank_session(io);
2536            assert!(session.read_mux_banks().is_err());
2537            assert!(session.io.writes.is_empty());
2538        }
2539        let mut session = bank_session(BankIo::default());
2540        let edit = bank_edit(&mut session);
2541        let report = session.apply_mux(&edit).unwrap();
2542        assert_eq!(session.io.writes, vec![0, 1]);
2543        assert_eq!(report.original, edit.expected);
2544        assert_eq!(report.verified.banks[2], edit.expected.banks[2]);
2545        assert_eq!(&report.verified.banks[0].raw_words()[56..], &[0; 8]);
2546        let mut restored = session
2547            .replace_mux(&report.verified, &report.original)
2548            .unwrap();
2549        assert_eq!(restored.verified, edit.expected);
2550        restored.verified.banks.swap(0, 1);
2551        assert!(validate_snapshot(model(), &restored.verified).is_err());
2552    }
2553    #[test]
2554    fn mux_drift_invalid_destination_and_padding_never_write() {
2555        let mut session = bank_session(BankIo::default());
2556        let mut edit = bank_edit(&mut session);
2557        let source = port_id(
2558            model(),
2559            Port::Channel {
2560                kind: PortKind::Pcm,
2561                channel: 2,
2562            },
2563            true,
2564        )
2565        .unwrap();
2566        session.io.banks[2].words[0] |= u32::from(source) << 12;
2567        assert!(matches!(
2568            session.apply_mux(&edit).unwrap_err().failure,
2569            MuxFailure::Drift { .. }
2570        ));
2571        edit.routes[0].destination = Port::Channel {
2572            kind: PortKind::Adat,
2573            channel: 8,
2574        };
2575        edit.routes[0].bank = 2;
2576        assert!(matches!(
2577            session.apply_mux(&edit).unwrap_err().failure,
2578            MuxFailure::Invalid(_)
2579        ));
2580        edit.expected.banks[0].words[63] = 1;
2581        assert!(matches!(
2582            session.apply_mux(&edit).unwrap_err().failure,
2583            MuxFailure::Invalid(_)
2584        ));
2585        assert!(session.io.writes.is_empty());
2586    }
2587    #[test]
2588    fn mux_partial_lost_set_restores_each_attempted_bank_and_retains_failures() {
2589        for (lost, corrupt) in [(vec![2], vec![]), (vec![], vec![2])] {
2590            let mut session = bank_session(BankIo {
2591                lost,
2592                corrupt,
2593                ..BankIo::default()
2594            });
2595            let edit = bank_edit(&mut session);
2596            let error = session.apply_mux(&edit).unwrap_err();
2597            assert!(error.rollback.is_empty());
2598            assert_eq!(session.io.writes, vec![0, 1, 1, 0]);
2599            assert_eq!(session.io.banks, edit.expected.banks);
2600        }
2601        let mut session = bank_session(BankIo {
2602            lost: vec![2, 3],
2603            ..BankIo::default()
2604        });
2605        let edit = bank_edit(&mut session);
2606        let error = session.apply_mux(&edit).unwrap_err();
2607        assert_eq!(error.rollback.len(), 1);
2608        assert_eq!(error.rollback[0].0, 1);
2609        assert_eq!(session.io.writes, vec![0, 1, 1, 0]);
2610        assert!(session.poisoned);
2611    }
2612}