Skip to main content

usbdac_core/scarlett/
gen1.rs

1//! First-generation Focusrite UAC2 routing, from pinned ALSA mixer_scarlett.c.
2//! Values are signed wire values: routes use -1 for Off; gains use 1/256 dB.
3//! Reading never initializes the mixer, clock, sample rate or preamps.
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6pub enum Gen1Model {
7    Scarlett6i6,
8    Scarlett8i6,
9    Scarlett18i6,
10    Scarlett18i8,
11    Scarlett18i20,
12    Forte,
13}
14
15impl Gen1Model {
16    pub fn recognize(vendor: u16, product: u16) -> Option<Self> {
17        if vendor != 0x1235 {
18            return None;
19        }
20        match product {
21            0x8012 => Some(Self::Scarlett6i6),
22            0x8002 => Some(Self::Scarlett8i6),
23            0x8004 => Some(Self::Scarlett18i6),
24            0x8014 => Some(Self::Scarlett18i8),
25            0x800c => Some(Self::Scarlett18i20),
26            0x8010 => Some(Self::Forte),
27            _ => None,
28        }
29    }
30    pub fn key(self) -> &'static str {
31        match self {
32            Self::Scarlett6i6 => "scarlett_6i6_gen1",
33            Self::Scarlett8i6 => "scarlett_8i6_gen1",
34            Self::Scarlett18i6 => "scarlett_18i6_gen1",
35            Self::Scarlett18i8 => "scarlett_18i8_gen1",
36            Self::Scarlett18i20 => "scarlett_18i20_gen1",
37            Self::Forte => "forte",
38        }
39    }
40    pub fn name(self) -> &'static str {
41        match self {
42            Self::Scarlett6i6 => "Scarlett 6i6 Gen 1",
43            Self::Scarlett8i6 => "Scarlett 8i6 Gen 1",
44            Self::Scarlett18i6 => "Scarlett 18i6 Gen 1",
45            Self::Scarlett18i8 => "Scarlett 18i8 Gen 1",
46            Self::Scarlett18i20 => "Scarlett 18i20 Gen 1",
47            Self::Forte => "Forte",
48        }
49    }
50    fn layout(self) -> Layout {
51        let (inputs, mixes, captures, outputs, matrix_sources, output_sources, offsets) = match self
52        {
53            Self::Scarlett6i6 => (18, 8, 6, 6, 19, 27, [0, 12, 16, 18, 18]),
54            Self::Scarlett8i6 => (18, 6, 8, 6, 19, 25, [0, 12, 16, 18, 18]),
55            Self::Scarlett18i6 => (18, 6, 18, 6, 25, 31, [0, 6, 14, 16, 24]),
56            Self::Scarlett18i8 => (18, 8, 18, 8, 27, 35, [0, 8, 16, 18, 26]),
57            Self::Scarlett18i20 => (18, 8, 18, 20, 39, 47, [0, 20, 28, 30, 38]),
58            // Forte's initializer creates no capture or output route controls.
59            Self::Forte => (6, 4, 0, 0, 7, 0, [0, 4, 6, 6, 6]),
60        };
61        Layout {
62            inputs,
63            mixes,
64            captures,
65            outputs,
66            matrix_sources,
67            output_sources,
68            offsets,
69        }
70    }
71}
72
73struct Layout {
74    inputs: u8,
75    mixes: u8,
76    captures: u8,
77    outputs: u8,
78    matrix_sources: u8,
79    output_sources: u8,
80    offsets: [u8; 5],
81}
82
83#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
84pub enum Gen1Key {
85    MatrixInput(u8),
86    Output(u8),
87    Capture(u8),
88    Gain { input: u8, mix: u8 },
89}
90#[derive(Debug, Clone, Copy, PartialEq, Eq)]
91pub struct Gen1Control {
92    pub key: Gen1Key,
93    pub value: i16,
94}
95#[derive(Debug, Clone, PartialEq, Eq)]
96pub struct Gen1Readback {
97    pub model: Gen1Model,
98    pub controls: Vec<Gen1Control>,
99    pub source_offsets: [u8; 5],
100    pub matrix_sources: u8,
101    pub output_sources: u8,
102}
103#[derive(Debug, Clone, Copy, PartialEq, Eq)]
104pub struct Gen1Edit {
105    pub key: Gen1Key,
106    pub value: i16,
107}
108#[derive(Debug, Clone, PartialEq, Eq)]
109pub struct Gen1Report {
110    pub original: Gen1Readback,
111    pub verified: Gen1Readback,
112}
113#[derive(Debug, PartialEq, Eq)]
114pub enum Gen1Failure<E> {
115    Io { key: Gen1Key, error: E },
116    Invalid { key: Gen1Key },
117    Drift { key: Option<Gen1Key> },
118    Verification { key: Gen1Key },
119}
120#[derive(Debug, PartialEq, Eq)]
121pub struct Gen1WriteError<E> {
122    pub failure: Gen1Failure<E>,
123    pub rollback: Vec<(Gen1Key, Gen1Failure<E>)>,
124}
125pub trait Gen1Io {
126    type Error;
127    fn read(&mut self, entity: u8, value: u16) -> Result<i16, Self::Error>;
128    fn write(&mut self, entity: u8, value: u16, data: i16) -> Result<(), Self::Error>;
129}
130
131fn keys(model: Gen1Model) -> Vec<Gen1Key> {
132    let l = model.layout();
133    let mut keys = Vec::new();
134    for input in 1..=l.inputs {
135        keys.push(Gen1Key::MatrixInput(input));
136        for mix in 1..=l.mixes {
137            keys.push(Gen1Key::Gain { input, mix });
138        }
139    }
140    keys.extend((1..=l.outputs).map(Gen1Key::Output));
141    keys.extend((1..=l.captures).map(Gen1Key::Capture));
142    keys
143}
144
145fn address(model: Gen1Model, key: Gen1Key) -> Option<(u8, u16)> {
146    let l = model.layout();
147    match key {
148        Gen1Key::MatrixInput(n) if n > 0 && n <= l.inputs => {
149            Some((0x32, 0x0600 | u16::from(n - 1)))
150        }
151        Gen1Key::Output(n) if n > 0 && n <= l.outputs => Some((0x33, u16::from(n - 1))),
152        Gen1Key::Capture(n) if n > 0 && n <= l.captures => Some((0x34, u16::from(n - 1))),
153        Gen1Key::Gain { input, mix }
154            if input > 0 && input <= l.inputs && mix > 0 && mix <= l.mixes =>
155        {
156            let (selector, shift) = if model == Gen1Model::Forte {
157                (0x0100, 2)
158            } else {
159                (0, 3)
160            };
161            Some((
162                0x3c,
163                selector | (u16::from(input - 1) << shift) | u16::from(mix - 1),
164            ))
165        }
166        _ => None,
167    }
168}
169
170fn valid_value(model: Gen1Model, key: Gen1Key, value: i16, edit: bool) -> bool {
171    if address(model, key).is_none() {
172        return false;
173    }
174    let l = model.layout();
175    match key {
176        Gen1Key::Gain { .. } => !edit || (value <= 6 * 256 && value % 256 == 0),
177        Gen1Key::MatrixInput(_) => value >= -1 && value < i16::from(l.matrix_sources) - 1,
178        _ => value >= -1 && value < i16::from(l.output_sources) - 1,
179    }
180}
181
182fn read_one<I: Gen1Io>(
183    io: &mut I,
184    model: Gen1Model,
185    key: Gen1Key,
186) -> Result<i16, Gen1Failure<I::Error>> {
187    let (entity, value) = address(model, key).ok_or(Gen1Failure::Invalid { key })?;
188    io.read(entity, value)
189        .map_err(|error| Gen1Failure::Io { key, error })
190}
191fn write_one<I: Gen1Io>(
192    io: &mut I,
193    model: Gen1Model,
194    key: Gen1Key,
195    data: i16,
196) -> Result<(), Gen1Failure<I::Error>> {
197    let (entity, value) = address(model, key).ok_or(Gen1Failure::Invalid { key })?;
198    io.write(entity, value, data)
199        .map_err(|error| Gen1Failure::Io { key, error })
200}
201
202pub fn read_gen1<I: Gen1Io>(
203    io: &mut I,
204    model: Gen1Model,
205) -> Result<Gen1Readback, Gen1Failure<I::Error>> {
206    let l = model.layout();
207    let mut controls = Vec::new();
208    for key in keys(model) {
209        let value = read_one(io, model, key)?;
210        if !valid_value(model, key, value, false) {
211            return Err(Gen1Failure::Invalid { key });
212        }
213        controls.push(Gen1Control { key, value });
214    }
215    Ok(Gen1Readback {
216        model,
217        controls,
218        source_offsets: l.offsets,
219        matrix_sources: l.matrix_sources,
220        output_sources: l.output_sources,
221    })
222}
223
224fn complete(r: &Gen1Readback) -> bool {
225    let l = r.model.layout();
226    r.source_offsets == l.offsets
227        && r.matrix_sources == l.matrix_sources
228        && r.output_sources == l.output_sources
229        && r.controls.iter().map(|c| c.key).eq(keys(r.model))
230        && r.controls
231            .iter()
232            .all(|c| valid_value(r.model, c.key, c.value, false))
233}
234pub(crate) fn same_gen1_layout(a: &Gen1Readback, b: &Gen1Readback) -> bool {
235    a.model == b.model && complete(a) && complete(b)
236}
237
238// Only undo values still held by this transaction. Failed writes are included:
239// a transport error may have occurred after the device accepted the transfer.
240fn rollback<I: Gen1Io>(
241    io: &mut I,
242    model: Gen1Model,
243    changed: &[(Gen1Key, i16, i16)],
244) -> Vec<(Gen1Key, Gen1Failure<I::Error>)> {
245    let mut errors = Vec::new();
246    for &(key, original, held) in changed.iter().rev() {
247        let result = (|| {
248            let live = read_one(io, model, key)?;
249            if live == original {
250                return Ok(());
251            }
252            if live != held {
253                return Err(Gen1Failure::Drift { key: Some(key) });
254            }
255            let write = write_one(io, model, key, original);
256            match read_one(io, model, key) {
257                Ok(value) if value == original => Ok(()),
258                read => {
259                    write?;
260                    read?;
261                    Err(Gen1Failure::Verification { key })
262                }
263            }
264        })();
265        if let Err(error) = result {
266            errors.push((key, error));
267        }
268    }
269    errors
270}
271
272pub fn apply_gen1<I: Gen1Io>(
273    io: &mut I,
274    model: Gen1Model,
275    expected: &Gen1Readback,
276    edits: &[Gen1Edit],
277) -> Result<Gen1Report, Gen1WriteError<I::Error>> {
278    let fail = |failure| Gen1WriteError {
279        failure,
280        rollback: Vec::new(),
281    };
282    if expected.model != model || !complete(expected) {
283        return Err(fail(Gen1Failure::Drift { key: None }));
284    }
285    for (i, edit) in edits.iter().enumerate() {
286        if !valid_value(model, edit.key, edit.value, true)
287            || edits[..i].iter().any(|e| e.key == edit.key)
288        {
289            return Err(fail(Gen1Failure::Invalid { key: edit.key }));
290        }
291    }
292    let original = read_gen1(io, model).map_err(fail)?;
293    if &original != expected {
294        return Err(fail(Gen1Failure::Drift { key: None }));
295    }
296    let mut desired = original.clone();
297    let mut changed = Vec::new();
298    let result = (|| {
299        for edit in edits {
300            let control = desired
301                .controls
302                .iter_mut()
303                .find(|c| c.key == edit.key)
304                .expect("validated key");
305            if read_one(io, model, edit.key)? != control.value {
306                return Err(Gen1Failure::Drift {
307                    key: Some(edit.key),
308                });
309            }
310            if control.value == edit.value {
311                continue;
312            }
313            changed.push((edit.key, control.value, edit.value));
314            write_one(io, model, edit.key, edit.value)?;
315            if read_one(io, model, edit.key)? != edit.value {
316                return Err(Gen1Failure::Verification { key: edit.key });
317            }
318            control.value = edit.value;
319        }
320        let verified = read_gen1(io, model)?;
321        if verified != desired {
322            return Err(Gen1Failure::Drift { key: None });
323        }
324        Ok(verified)
325    })();
326    match result {
327        Ok(verified) => Ok(Gen1Report { original, verified }),
328        Err(failure) => Err(Gen1WriteError {
329            failure,
330            rollback: rollback(io, model, &changed),
331        }),
332    }
333}
334
335pub(crate) fn restore_gen1<I: Gen1Io>(
336    io: &mut I,
337    model: Gen1Model,
338    last: &Gen1Readback,
339    original: &Gen1Readback,
340) -> Result<(), Gen1WriteError<I::Error>> {
341    if model != last.model || !same_gen1_layout(last, original) {
342        return Err(Gen1WriteError {
343            failure: Gen1Failure::Drift { key: None },
344            rollback: Vec::new(),
345        });
346    }
347    let changes: Vec<_> = original
348        .controls
349        .iter()
350        .zip(&last.controls)
351        .filter(|(a, b)| a.value != b.value)
352        .map(|(a, b)| (a.key, a.value, b.value))
353        .collect();
354    let mut errors = rollback(io, model, &changes).into_iter();
355    if let Some((_, failure)) = errors.next() {
356        Err(Gen1WriteError {
357            failure,
358            rollback: errors.collect(),
359        })
360    } else {
361        Ok(())
362    }
363}
364
365#[cfg(test)]
366mod tests {
367    use super::*;
368    use std::collections::BTreeMap;
369
370    struct Io {
371        values: BTreeMap<(u8, u16), i16>,
372        writes: Vec<(u8, u16, i16)>,
373        fail_write: Option<usize>,
374        external_on_failure: Option<((u8, u16), i16)>,
375    }
376    impl Io {
377        fn new(model: Gen1Model) -> Self {
378            Self {
379                values: keys(model)
380                    .into_iter()
381                    .map(|key| {
382                        (
383                            address(model, key).unwrap(),
384                            if matches!(key, Gen1Key::Gain { .. }) {
385                                -12345
386                            } else {
387                                -1
388                            },
389                        )
390                    })
391                    .collect(),
392                writes: Vec::new(),
393                fail_write: None,
394                external_on_failure: None,
395            }
396        }
397    }
398    impl Gen1Io for Io {
399        type Error = &'static str;
400        fn read(&mut self, entity: u8, value: u16) -> Result<i16, Self::Error> {
401            self.values
402                .get(&(entity, value))
403                .copied()
404                .ok_or("unexpected address")
405        }
406        fn write(&mut self, entity: u8, value: u16, data: i16) -> Result<(), Self::Error> {
407            self.writes.push((entity, value, data));
408            self.values.insert((entity, value), data);
409            if self.fail_write == Some(self.writes.len()) {
410                if let Some((address, data)) = self.external_on_failure {
411                    self.values.insert(address, data);
412                }
413                return Err("uncertain transfer");
414            }
415            Ok(())
416        }
417    }
418
419    #[test]
420    fn exact_model_and_wire_geometry() {
421        for (product, model, inputs, mixes, captures, outputs, matrix_sources, output_sources) in [
422            (0x8012, Gen1Model::Scarlett6i6, 18, 8, 6, 6, 19, 27),
423            (0x8002, Gen1Model::Scarlett8i6, 18, 6, 8, 6, 19, 25),
424            (0x8004, Gen1Model::Scarlett18i6, 18, 6, 18, 6, 25, 31),
425            (0x8014, Gen1Model::Scarlett18i8, 18, 8, 18, 8, 27, 35),
426            (0x800c, Gen1Model::Scarlett18i20, 18, 8, 18, 20, 39, 47),
427            (0x8010, Gen1Model::Forte, 6, 4, 0, 0, 7, 0),
428        ] {
429            assert_eq!(Gen1Model::recognize(0x1235, product), Some(model));
430            assert_eq!(Gen1Model::recognize(0xffff, product), None);
431            let mut io = Io::new(model);
432            let r = read_gen1(&mut io, model).unwrap();
433            assert_eq!(r.controls.len(), inputs * (mixes + 1) + captures + outputs);
434            assert_eq!(
435                (r.matrix_sources, r.output_sources),
436                (matrix_sources, output_sources)
437            );
438            assert!(io.writes.is_empty());
439        }
440        assert_eq!(Gen1Model::recognize(0x1235, 0x8215), None);
441        let s = Gen1Model::Scarlett18i20;
442        assert_eq!(address(s, Gen1Key::MatrixInput(18)), Some((0x32, 0x0611)));
443        assert_eq!(
444            address(s, Gen1Key::Gain { input: 18, mix: 8 }),
445            Some((0x3c, 0x008f))
446        );
447        assert_eq!(address(s, Gen1Key::Output(20)), Some((0x33, 19)));
448        assert_eq!(address(s, Gen1Key::Capture(18)), Some((0x34, 17)));
449        let f = Gen1Model::Forte;
450        assert_eq!(
451            address(f, Gen1Key::Gain { input: 6, mix: 4 }),
452            Some((0x3c, 0x0117))
453        );
454        assert_eq!(address(f, Gen1Key::MatrixInput(6)), Some((0x32, 0x0605)));
455        assert_eq!(address(f, Gen1Key::Output(1)), None);
456        assert_eq!(address(f, Gen1Key::Capture(1)), None);
457        assert_eq!(address(s, Gen1Key::MatrixInput(0)), None);
458    }
459
460    #[test]
461    fn signed_off_and_one_db_gain_writes_preserve_raw_original() {
462        let model = Gen1Model::Forte;
463        let mut io = Io::new(model);
464        let initial = read_gen1(&mut io, model).unwrap();
465        let edits = [
466            Gen1Edit {
467                key: Gen1Key::MatrixInput(6),
468                value: 5,
469            },
470            Gen1Edit {
471                key: Gen1Key::Gain { input: 6, mix: 4 },
472                value: 1536,
473            },
474        ];
475        let report = apply_gen1(&mut io, model, &initial, &edits).unwrap();
476        assert_eq!(io.writes, vec![(0x32, 0x0605, 5), (0x3c, 0x0117, 1536)]);
477        restore_gen1(&mut io, model, &report.verified, &report.original).unwrap();
478        assert_eq!(
479            &io.writes[2..],
480            &[(0x3c, 0x0117, -12345), (0x32, 0x0605, -1)]
481        );
482        for value in [-32768, -256, 0, 1536] {
483            assert!(valid_value(model, edits[1].key, value, true));
484        }
485        for value in [-32767, 1, 1537, 1792] {
486            assert!(!valid_value(model, edits[1].key, value, true));
487        }
488        assert!(!valid_value(model, edits[0].key, 6, true));
489    }
490
491    #[test]
492    fn uncertain_write_rolls_back_in_reverse_and_preserves_external_change() {
493        let model = Gen1Model::Scarlett6i6;
494        let mut io = Io::new(model);
495        let initial = read_gen1(&mut io, model).unwrap();
496        let edits = [
497            Gen1Edit {
498                key: Gen1Key::Output(1),
499                value: 0,
500            },
501            Gen1Edit {
502                key: Gen1Key::Capture(1),
503                value: 1,
504            },
505        ];
506        io.fail_write = Some(2);
507        let failure = apply_gen1(&mut io, model, &initial, &edits).unwrap_err();
508        assert!(matches!(
509            failure.failure,
510            Gen1Failure::Io {
511                key: Gen1Key::Capture(1),
512                ..
513            }
514        ));
515        assert!(failure.rollback.is_empty());
516        assert_eq!(
517            io.writes,
518            vec![(0x33, 0, 0), (0x34, 0, 1), (0x34, 0, -1), (0x33, 0, -1)]
519        );
520        io.writes.clear();
521        io.external_on_failure = Some(((0x33, 0), 4));
522        let failure = apply_gen1(&mut io, model, &initial, &edits).unwrap_err();
523        assert_eq!(failure.rollback.len(), 1);
524        assert_eq!(failure.rollback[0].0, Gen1Key::Output(1));
525        assert_eq!(io.values[&(0x33, 0)], 4);
526        assert_eq!(io.values[&(0x34, 0)], -1);
527    }
528
529    #[test]
530    fn full_snapshot_and_all_edit_validation_precede_writes() {
531        let model = Gen1Model::Scarlett18i8;
532        let mut io = Io::new(model);
533        let initial = read_gen1(&mut io, model).unwrap();
534        let edits = [Gen1Edit {
535            key: Gen1Key::Output(1),
536            value: 0,
537        }];
538        io.values.insert((0x3c, 0x008f), -10000);
539        assert!(matches!(
540            apply_gen1(&mut io, model, &initial, &edits)
541                .unwrap_err()
542                .failure,
543            Gen1Failure::Drift { .. }
544        ));
545        assert!(io.writes.is_empty());
546        let fresh = read_gen1(&mut io, model).unwrap();
547        let invalid = [
548            edits[0],
549            Gen1Edit {
550                key: Gen1Key::Gain { input: 1, mix: 1 },
551                value: 1,
552            },
553        ];
554        assert!(matches!(
555            apply_gen1(&mut io, model, &fresh, &invalid)
556                .unwrap_err()
557                .failure,
558            Gen1Failure::Invalid { .. }
559        ));
560        assert!(io.writes.is_empty());
561        let mut incomplete = fresh.clone();
562        incomplete.controls.pop();
563        assert!(!same_gen1_layout(&fresh, &incomplete));
564    }
565
566    #[test]
567    fn close_restores_independent_held_controls_despite_external_drift() {
568        let model = Gen1Model::Forte;
569        let mut io = Io::new(model);
570        let original = read_gen1(&mut io, model).unwrap();
571        let report = apply_gen1(
572            &mut io,
573            model,
574            &original,
575            &[
576                Gen1Edit {
577                    key: Gen1Key::MatrixInput(1),
578                    value: 0,
579                },
580                Gen1Edit {
581                    key: Gen1Key::MatrixInput(2),
582                    value: 1,
583                },
584            ],
585        )
586        .unwrap();
587        io.values.insert((0x32, 0x0601), 3);
588        assert!(restore_gen1(&mut io, model, &report.verified, &original).is_err());
589        assert_eq!(io.values[&(0x32, 0x0600)], -1);
590        assert_eq!(io.values[&(0x32, 0x0601)], 3);
591    }
592
593    #[test]
594    fn close_accepts_exact_readback_after_lost_restore_ack() {
595        let model = Gen1Model::Forte;
596        let mut io = Io::new(model);
597        let original = read_gen1(&mut io, model).unwrap();
598        let report = apply_gen1(
599            &mut io,
600            model,
601            &original,
602            &[Gen1Edit {
603                key: Gen1Key::Gain { input: 1, mix: 1 },
604                value: 0,
605            }],
606        )
607        .unwrap();
608        io.fail_write = Some(2);
609        restore_gen1(&mut io, model, &report.verified, &original).unwrap();
610        assert_eq!(io.values[&(0x3c, 0x0100)], -12345);
611    }
612}