firewire-motu-protocols 0.1.1

Implementation of protocols defined by Mark of the Unicorn for its FireWire series.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
// SPDX-License-Identifier: LGPL-3.0-or-later
// Copyright (c) 2021 Takashi Sakamoto

#![doc = include_str!("../README.md")]

pub mod command_dsp;
pub mod config_rom;
pub mod register_dsp;
pub mod version_1;
pub mod version_2;
pub mod version_3;

use {
    glib::{Error, FileError},
    hinawa::{prelude::{FwNodeExt, FwReqExtManual}, FwNode, FwReq, FwTcode},
    std::{thread, time},
};

const BASE_OFFSET: u64 = 0xfffff0000000;
const OFFSET_CLK: u32 = 0x0b14;
const OFFSET_PORT: u32 = 0x0c04;
const OFFSET_CLK_DISPLAY: u32 = 0x0c60;

fn read_quad(req: &FwReq, node: &mut FwNode, offset: u32, timeout_ms: u32) -> Result<u32, Error> {
    let mut frame = [0; 4];
    req.transaction_sync(
        node,
        FwTcode::ReadQuadletRequest,
        BASE_OFFSET + offset as u64,
        4,
        &mut frame,
        timeout_ms,
    )
    .map(|_| u32::from_be_bytes(frame))
}

// AudioExpress sometimes transfers response subaction with non-standard rcode. This causes
// Linux firewire subsystem to report 'unsolicited response' error. In the case, send error
// is reported to userspace applications. As a workaround, the change of register is ensured
// by following read transaction in failure of write transaction.
fn write_quad(
    req: &FwReq,
    node: &mut FwNode,
    offset: u32,
    quad: u32,
    timeout_ms: u32,
) -> Result<(), Error> {
    let mut frame = [0; 4];
    frame.copy_from_slice(&quad.to_be_bytes());
    req.transaction_sync(
        node,
        FwTcode::WriteQuadletRequest,
        BASE_OFFSET + offset as u64,
        4,
        &mut frame,
        timeout_ms,
    )
    .or_else(|err| {
        // For prevention of RCODE_BUSY.
        thread::sleep(time::Duration::from_millis(BUSY_DURATION));
        req.transaction_sync(
            node,
            FwTcode::WriteQuadletRequest,
            BASE_OFFSET + offset as u64,
            4,
            &mut frame,
            timeout_ms,
        )
        .and_then(|_| {
            if u32::from_be_bytes(frame) == quad {
                Ok(())
            } else {
                Err(err)
            }
        })
    })
}

fn get_idx_from_val(
    offset: u32,
    mask: u32,
    shift: usize,
    label: &str,
    req: &FwReq,
    node: &mut FwNode,
    vals: &[u8],
    timeout_ms: u32,
) -> Result<usize, Error> {
    let quad = read_quad(req, node, offset, timeout_ms)?;
    let val = ((quad & mask) >> shift) as u8;
    vals.iter().position(|&v| v == val).ok_or_else(|| {
        let label = format!("Detect invalid value for {}: {:02x}", label, val);
        Error::new(FileError::Io, &label)
    })
}

fn set_idx_to_val(
    offset: u32,
    mask: u32,
    shift: usize,
    label: &str,
    req: &FwReq,
    node: &mut FwNode,
    vals: &[u8],
    idx: usize,
    timeout_ms: u32,
) -> Result<(), Error> {
    if idx >= vals.len() {
        let label = format!("Invalid argument for {}: {} {}", label, vals.len(), idx);
        return Err(Error::new(FileError::Inval, &label));
    }
    let mut quad = read_quad(req, node, offset, timeout_ms)?;
    quad &= !mask;
    quad |= (vals[idx] as u32) << shift;
    write_quad(req, node, offset, quad, timeout_ms)
}

/// Nominal rate of sampling clock.
pub enum ClkRate {
    /// 44.1 kHx.
    R44100,
    /// 48.0 kHx.
    R48000,
    /// 88.2 kHx.
    R88200,
    /// 96.0 kHx.
    R96000,
    /// 176.4 kHx.
    R176400,
    /// 192.2 kHx.
    R192000,
}

const BUSY_DURATION: u64 = 150;
const DISPLAY_CHARS: usize = 4 * 4;

fn update_clk_display(
    req: &FwReq,
    node: &mut FwNode,
    label: &str,
    timeout_ms: u32,
) -> Result<(), Error> {
    let mut chars = [0x20; DISPLAY_CHARS];
    chars
        .iter_mut()
        .zip(label.bytes())
        .for_each(|(c, l)| *c = l);

    (0..(DISPLAY_CHARS / 4)).try_for_each(|i| {
        let mut frame = [0; 4];
        frame.copy_from_slice(&chars[(i * 4)..(i * 4 + 4)]);
        frame.reverse();
        let quad = u32::from_ne_bytes(frame);
        let offset = OFFSET_CLK_DISPLAY + 4 * i as u32;
        write_quad(req, node, offset, quad, timeout_ms)
    })
}

const PORT_PHONE_LABEL: &str = "phone-assign";
const PORT_PHONE_MASK: u32 = 0x0000000f;
const PORT_PHONE_SHIFT: usize = 0;

/// The trait for headphone assignment protocol.
pub trait AssignOperation {
    const ASSIGN_PORTS: &'static [(TargetPort, u8)];

    fn get_phone_assign(
        req: &mut FwReq,
        node: &mut FwNode,
        timeout_ms: u32,
    ) -> Result<usize, Error> {
        let vals: Vec<u8> = Self::ASSIGN_PORTS.iter().map(|e| e.1).collect();
        get_idx_from_val(
            OFFSET_PORT,
            PORT_PHONE_MASK,
            PORT_PHONE_SHIFT,
            PORT_PHONE_LABEL,
            req,
            node,
            &vals,
            timeout_ms,
        )
    }

    fn set_phone_assign(
        req: &mut FwReq,
        node: &mut FwNode,
        idx: usize,
        timeout_ms: u32,
    ) -> Result<(), Error> {
        let vals: Vec<u8> = Self::ASSIGN_PORTS.iter().map(|e| e.1).collect();
        set_idx_to_val(
            OFFSET_PORT,
            PORT_PHONE_MASK,
            PORT_PHONE_SHIFT,
            PORT_PHONE_LABEL,
            req,
            node,
            &vals,
            idx,
            timeout_ms,
        )
    }
}

/// Mode of speed for output signal of word clock on BNC interface.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum WordClkSpeedMode {
    /// The speed is forced to be 44.1/48.0 kHz.
    ForceLowRate,
    /// The speed is following to system clock.
    FollowSystemClk,
}

impl Default for WordClkSpeedMode {
    fn default() -> Self {
        Self::FollowSystemClk
    }
}

const WORD_OUT_LABEL: &str = "word-out";
const WORD_OUT_MASK: u32 = 0x08000000;
const WORD_OUT_SHIFT: usize = 27;

const WORD_OUT_VALS: [u8; 2] = [0x00, 0x01];

/// The trait for word-clock protocol.
pub trait WordClkOperation {
    fn get_word_out(
        req: &mut FwReq,
        node: &mut FwNode,
        timeout_ms: u32,
    ) -> Result<WordClkSpeedMode, Error> {
        get_idx_from_val(
            OFFSET_CLK,
            WORD_OUT_MASK,
            WORD_OUT_SHIFT,
            WORD_OUT_LABEL,
            req,
            node,
            &WORD_OUT_VALS,
            timeout_ms,
        )
        .map(|val| {
            if val == 0 {
                WordClkSpeedMode::ForceLowRate
            } else {
                WordClkSpeedMode::FollowSystemClk
            }
        })
    }

    fn set_word_out(
        req: &mut FwReq,
        node: &mut FwNode,
        mode: WordClkSpeedMode,
        timeout_ms: u32,
    ) -> Result<(), Error> {
        let idx = match mode {
            WordClkSpeedMode::ForceLowRate => 0,
            WordClkSpeedMode::FollowSystemClk => 1,
        };
        set_idx_to_val(
            OFFSET_CLK,
            WORD_OUT_MASK,
            WORD_OUT_SHIFT,
            WORD_OUT_LABEL,
            req,
            node,
            &WORD_OUT_VALS,
            idx,
            timeout_ms,
        )
    }
}

/// Mode of rate convert for AES/EBU input/output signals.
pub enum AesebuRateConvertMode {
    /// Not available.
    None,
    /// The rate of input signal is converted to system rate.
    InputToSystem,
    /// The rate of output signal is slave to input, ignoring system rate.
    OutputDependsInput,
    /// The rate of output signal is double rate than system rate.
    OutputDoubleSystem,
}

const AESEBU_RATE_CONVERT_LABEL: &str = "aesebu-rate-convert";

/// The trait for protocol of rate convert specific to AES/EBU input/output signals.
pub trait AesebuRateConvertOperation {
    const AESEBU_RATE_CONVERT_MASK: u32;
    const AESEBU_RATE_CONVERT_SHIFT: usize;

    const AESEBU_RATE_CONVERT_VALS: [u8; 4] = [0x00, 0x01, 0x02, 0x03];

    const AESEBU_RATE_CONVERT_MODES: [AesebuRateConvertMode; 4] = [
        AesebuRateConvertMode::None,
        AesebuRateConvertMode::InputToSystem,
        AesebuRateConvertMode::OutputDependsInput,
        AesebuRateConvertMode::OutputDoubleSystem,
    ];

    fn get_aesebu_rate_convert_mode(
        req: &mut FwReq,
        node: &mut FwNode,
        timeout_ms: u32,
    ) -> Result<usize, Error> {
        get_idx_from_val(
            OFFSET_CLK,
            Self::AESEBU_RATE_CONVERT_MASK,
            Self::AESEBU_RATE_CONVERT_SHIFT,
            AESEBU_RATE_CONVERT_LABEL,
            req,
            node,
            &Self::AESEBU_RATE_CONVERT_VALS,
            timeout_ms,
        )
    }

    fn set_aesebu_rate_convert_mode(
        req: &mut FwReq,
        node: &mut FwNode,
        idx: usize,
        timeout_ms: u32,
    ) -> Result<(), Error> {
        set_idx_to_val(
            OFFSET_CLK,
            Self::AESEBU_RATE_CONVERT_MASK,
            Self::AESEBU_RATE_CONVERT_SHIFT,
            AESEBU_RATE_CONVERT_LABEL,
            req,
            node,
            &Self::AESEBU_RATE_CONVERT_VALS,
            idx,
            timeout_ms,
        )
    }
}

/// Mode of hold time for clip and peak LEDs.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum LevelMetersHoldTimeMode {
    /// off.
    Off,
    /// 2 seconds.
    Sec2,
    /// 4 seconds.
    Sec4,
    /// 10 seconds.
    Sec10,
    /// 1 minute.
    Sec60,
    /// 5 minutes.
    Sec300,
    /// 8 minutes.
    Sec480,
    /// Infinite.
    Infinite,
}

impl Default for LevelMetersHoldTimeMode {
    fn default() -> Self {
        Self::Off
    }
}

/// Mode of programmable meter display.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum LevelMetersProgrammableMode {
    AnalogOutput,
    AdatInput,
    AdatOutput,
}

impl Default for LevelMetersProgrammableMode {
    fn default() -> Self {
        Self::AnalogOutput
    }
}

/// Mode of AES/EBU meter display.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum LevelMetersAesebuMode {
    Input,
    Output,
}

impl Default for LevelMetersAesebuMode {
    fn default() -> Self {
        Self::Input
    }
}

const LEVEL_METERS_OFFSET: u32 = 0x0b24;

const LEVEL_METERS_PEAK_HOLD_TIME_MASK: u32 = 0x00003800;
const LEVEL_METERS_PEAK_HOLD_TIME_SHIFT: usize = 11;

const LEVEL_METERS_CLIP_HOLD_TIME_MASK: u32 = 0x00000700;
const LEVEL_METERS_CLIP_HOLD_TIME_SHIFT: usize = 8;

const LEVEL_METERS_HOLD_TIME_VALS: [u8; 8] = [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07];

const LEVEL_METERS_AESEBU_MASK: u32 = 0x00000004;
const LEVEL_METERS_AESEBU_SHIFT: usize = 2;

const LEVEL_METERS_AESEBU_VALS: [u8; 2] = [0x00, 0x01];

const LEVEL_METERS_PROGRAMMABLE_MASK: u32 = 0x00000003;
const LEVEL_METERS_PROGRAMMABLE_SHIFT: usize = 0;
const LEVEL_METERS_PROGRAMMABLE_VALS: [u8; 3] = [0x00, 0x01, 0x02];

const LEVEL_METERS_PEAK_HOLD_TIME_LABEL: &str = "level-meters-peak-hold-time";
const LEVEL_METERS_CLIP_HOLD_TIME_LABEL: &str = "level-meters-clip-hold-time";
const LEVEL_METERS_PROGRAMMABLE_LABEL: &str = "level-meters-programmable";
const LEVEL_METERS_AESEBU_LABEL: &str = "level-meters-aesebu";

/// The trait for protocol of level meter.
pub trait LevelMetersOperation {
    const LEVEL_METERS_HOLD_TIME_MODES: [LevelMetersHoldTimeMode; 8] = [
        LevelMetersHoldTimeMode::Off,
        LevelMetersHoldTimeMode::Sec2,
        LevelMetersHoldTimeMode::Sec4,
        LevelMetersHoldTimeMode::Sec10,
        LevelMetersHoldTimeMode::Sec60,
        LevelMetersHoldTimeMode::Sec300,
        LevelMetersHoldTimeMode::Sec480,
        LevelMetersHoldTimeMode::Infinite,
    ];

    const LEVEL_METERS_AESEBU_MODES: [LevelMetersAesebuMode; 2] =
        [LevelMetersAesebuMode::Output, LevelMetersAesebuMode::Input];

    const LEVEL_METERS_PROGRAMMABLE_MODES: [LevelMetersProgrammableMode; 3] = [
        LevelMetersProgrammableMode::AnalogOutput,
        LevelMetersProgrammableMode::AdatInput,
        LevelMetersProgrammableMode::AdatOutput,
    ];

    fn get_level_meters_peak_hold_time_mode(
        req: &mut FwReq,
        node: &mut FwNode,
        timeout_ms: u32,
    ) -> Result<usize, Error> {
        get_idx_from_val(
            LEVEL_METERS_OFFSET,
            LEVEL_METERS_PEAK_HOLD_TIME_MASK,
            LEVEL_METERS_PEAK_HOLD_TIME_SHIFT,
            LEVEL_METERS_PEAK_HOLD_TIME_LABEL,
            req,
            node,
            &LEVEL_METERS_HOLD_TIME_VALS,
            timeout_ms,
        )
    }

    fn set_level_meters_peak_hold_time_mode(
        req: &mut FwReq,
        node: &mut FwNode,
        idx: usize,
        timeout_ms: u32,
    ) -> Result<(), Error> {
        set_idx_to_val(
            LEVEL_METERS_OFFSET,
            LEVEL_METERS_PEAK_HOLD_TIME_MASK,
            LEVEL_METERS_PEAK_HOLD_TIME_SHIFT,
            LEVEL_METERS_PEAK_HOLD_TIME_LABEL,
            req,
            node,
            &LEVEL_METERS_HOLD_TIME_VALS,
            idx,
            timeout_ms,
        )
    }

    fn get_level_meters_clip_hold_time_mode(
        req: &mut FwReq,
        node: &mut FwNode,
        timeout_ms: u32,
    ) -> Result<usize, Error> {
        get_idx_from_val(
            LEVEL_METERS_OFFSET,
            LEVEL_METERS_CLIP_HOLD_TIME_MASK,
            LEVEL_METERS_CLIP_HOLD_TIME_SHIFT,
            LEVEL_METERS_CLIP_HOLD_TIME_LABEL,
            req,
            node,
            &LEVEL_METERS_HOLD_TIME_VALS,
            timeout_ms,
        )
    }

    fn set_level_meters_clip_hold_time_mode(
        req: &mut FwReq,
        node: &mut FwNode,
        idx: usize,
        timeout_ms: u32,
    ) -> Result<(), Error> {
        set_idx_to_val(
            LEVEL_METERS_OFFSET,
            LEVEL_METERS_CLIP_HOLD_TIME_MASK,
            LEVEL_METERS_CLIP_HOLD_TIME_SHIFT,
            LEVEL_METERS_CLIP_HOLD_TIME_LABEL,
            req,
            node,
            &LEVEL_METERS_HOLD_TIME_VALS,
            idx,
            timeout_ms,
        )
    }

    fn get_level_meters_aesebu_mode(
        req: &mut FwReq,
        node: &mut FwNode,
        timeout_ms: u32,
    ) -> Result<usize, Error> {
        get_idx_from_val(
            LEVEL_METERS_OFFSET,
            LEVEL_METERS_AESEBU_MASK,
            LEVEL_METERS_AESEBU_SHIFT,
            LEVEL_METERS_AESEBU_LABEL,
            req,
            node,
            &LEVEL_METERS_AESEBU_VALS,
            timeout_ms,
        )
    }

    fn set_level_meters_aesebu_mode(
        req: &mut FwReq,
        node: &mut FwNode,
        idx: usize,
        timeout_ms: u32,
    ) -> Result<(), Error> {
        set_idx_to_val(
            LEVEL_METERS_OFFSET,
            LEVEL_METERS_AESEBU_MASK,
            LEVEL_METERS_AESEBU_SHIFT,
            LEVEL_METERS_AESEBU_LABEL,
            req,
            node,
            &LEVEL_METERS_AESEBU_VALS,
            idx,
            timeout_ms,
        )
    }

    fn get_level_meters_programmable_mode(
        req: &mut FwReq,
        node: &mut FwNode,
        timeout_ms: u32,
    ) -> Result<usize, Error> {
        get_idx_from_val(
            LEVEL_METERS_OFFSET,
            LEVEL_METERS_PROGRAMMABLE_MASK,
            LEVEL_METERS_PROGRAMMABLE_SHIFT,
            LEVEL_METERS_PROGRAMMABLE_LABEL,
            req,
            node,
            &LEVEL_METERS_PROGRAMMABLE_VALS,
            timeout_ms,
        )
    }

    fn set_level_meters_programmable_mode(
        req: &mut FwReq,
        node: &mut FwNode,
        idx: usize,
        timeout_ms: u32,
    ) -> Result<(), Error> {
        set_idx_to_val(
            LEVEL_METERS_OFFSET,
            LEVEL_METERS_PROGRAMMABLE_MASK,
            LEVEL_METERS_PROGRAMMABLE_SHIFT,
            LEVEL_METERS_PROGRAMMABLE_LABEL,
            req,
            node,
            &LEVEL_METERS_PROGRAMMABLE_VALS,
            idx,
            timeout_ms,
        )
    }
}

/// Port to assign.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum TargetPort {
    Disabled,
    AnalogPair(usize),
    AesEbuPair,
    PhonePair,
    MainPair,
    SpdifPair,
    AdatPair(usize),
    Analog6Pairs,
    Analog8Pairs,
    OpticalAPair(usize),
    OpticalBPair(usize),
    Analog(usize),
    AesEbu(usize),
    Phone(usize),
    Main(usize),
    Spdif(usize),
    Adat(usize),
    OpticalA(usize),
    OpticalB(usize),
}

impl Default for TargetPort {
    fn default() -> Self {
        Self::Disabled
    }
}

/// Nominal level of audio signal.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum NominalSignalLevel {
    /// -10 dBV.
    Consumer,
    /// +4 dBu.
    Professional,
}

impl Default for NominalSignalLevel {
    fn default() -> Self {
        Self::Consumer
    }
}