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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
// SPDX-License-Identifier: LGPL-3.0-or-later
// Copyright (c) 2020 Takashi Sakamoto

//! Hardware specification and application protocol specific to Avid Mbox 3 Pro
//!
//! The module includes structure, enumeration, and trait and its implementation for hardware
//! specification and application protocol specific to Avid Mbox 3 Pro.
//!
//! ## Diagram of internal signal flow
//!
//! ```text
//!
//! XLR input 1 -----------------+-------+-------> analog-input-1/2
//! Phone input 1 ---------------+       |
//!                                      |
//! XLR input 2 -----------------+-------+
//! Phone input 2 ---------------+
//!
//! XLR input 3 -----------------+-------+-------> analog-input-3/4
//! Phone input 3 ---------------+       |
//!                                      |
//! XLR input 4 -----------------+-------+
//! Phone input 4 ---------------+
//!
//! RCA input 5/6 ---------------or--------------> analog-input-5/6
//! Mini Phone ------------------+
//! coaxial input 1/2 ---------------------------> spdif-input-1/2
//!
//!                          ++=============++
//! analog-input-1/2 ------> ||             || --> analog-output-1/2
//! analog-input-3/4 ------> ||             || --> analog-output-3/4
//! analog-input-5/6 ------> ||             || --> analog-output-5/6
//! spdif-input-1/2 -------> ||             || --> spdif-output-1/2
//!                          ||             ||
//!                          ||             || --> headphone-output-1/2
//!                          ||             || --> headphone-output-3/4
//!                          ||   34 x 42   ||
//! reberb-output-1/2 -----> ||             || --> reverb-input-1/2
//!                          ||   router    ||
//! stream-input-1/2 ------> ||             || --> stream-output-1/2
//! stream-input-3/4 ------> ||   up to     || --> stream-output-3/4
//! stream-input-5/6 ------> ||             || --> stream-output-5/6
//! stream-input-7/8 ------> || 128 entries || --> stream-output-7/8
//!                          ||             ||
//! mixer-output-1/2 ------> ||             || --> mixer-input-1/2
//! mixer-output-3/4 ------> ||             || --> mixer-input-3/4
//! mixer-output-5/6 ------> ||             || --> mixer-input-5/6
//! mixer-output-7/8 ------> ||             || --> mixer-input-7/8
//! mixer-output-9/10 -----> ||             || --> mixer-input-9/10
//! mixer-output-11/12 ----> ||             || --> mixer-input-11/12
//! mixer-output-13/14 ----> ||             || --> mixer-input-13/14
//! mixer-output-15/16 ----> ||             || --> mixer-input-15/16
//!                          ||             || --> mixer-input-17/18
//!                          ||             ||
//!                          ||             || --> control-room-output-1/2
//!                          ++=============++
//!
//!                          ++=============++
//! reverb-input-1/2 ------> ||    reverb   || --> reverb-output-1/2
//!                          ||    effect   ||
//!                          ++=============++
//!
//!                          ++=============++
//! mixer-input-1/2 -------> ||             || --> mixer-output-1/2
//! mixer-input-3/4 -------> ||             || --> mixer-output-3/4
//! mixer-input-5/6 -------> ||             || --> mixer-output-5/6
//! mixer-input-7/8 -------> ||   18 x 16   || --> mixer-output-7/8
//! mixer-input-9/10 ------> ||             || --> mixer-output-9/10
//! mixer-input-11/11 -----> ||    mixer    || --> mixer-output-11/12
//! mixer-input-13/14 -----> ||             || --> mixer-output-13/14
//! mixer-input-15/16 -----> ||             || --> mixer-output-15/16
//! mixer-input-17/18 -----> ||             ||
//!                          ++=============++
//!
//! analog-output-1/2 ---------------------------> Phone output 1/2
//! analog-output-3/4 ---------------------------> Phone output 3/4
//! analog-output-5/6 ---------------------------> Phone output 5/6
//!
//! headphone-output-1/2 ------------------------> Headphone output 1/2
//! headphone-output-3/4 ------------------------> Headphone output 3/4
//!
//! spdif-output-1/2 ----------------------------> Coaxial output 1/2
//!
//! ```

use super::{
    tcat::{extension::*, tcd22xx_spec::*, *},
    *,
};

// const USE_CASE_OFFSET: usize = 0x00;
// (0x04 is unclear)
// const MASTER_KNOB_VALUE_OFFSET: usize = 0x08;
// const MASTER_KNOB_ASSIGN_OFFSET: usize = 0x0c;
// const MUTE_BUTTON_LED_OFFSET: usize = 0x10;
// const MONO_BUTTON_LED_OFFSET: usize = 0x14;  // 0x08 enables playback routing to analog input 3/4.
// const SPKR_BUTTON_LED_OFFSET: usize = 0x14;
// const ALL_LEDS_BRIGHTNESS_OFFSET: usize = 0x18;   // 0x00 - 0x7f.
// const FORCE_LEDS_BRIGHTNESS_OFFSET: usize = 0x1c;   // 0x00 - 0x7f.
// const BUTTON_HOLD_DURATION_OFFSET: usize = 0x20;
// const HPF_ENABLE_OFFSET: usize = 0x24; // High pass filter for analog inputs.
// const OUT_0_TRIM_OFFSET: usize = 0x28;
// const OUT_1_TRIM_OFFSET: usize = 0x2c;
// const OUT_2_TRIM_OFFSET: usize = 0x30;
// const OUT_3_TRIM_OFFSET: usize = 0x34;
// const OUT_4_TRIM_OFFSET: usize = 0x38;
// const OUT_5_TRIM_OFFSET: usize = 0x3c;
// const REVERB_TYPE_OFFSET: usize = 0x40;
// const REVERB_VOLUME_OFFSET: usize = 0x44;
// const REVERB_DURATION_OFFSET: usize = 0x48;
// const REVERB_FEEDBACK_OFFSET: usize = 0x4c;

/// Protocol implementation of Avid Mbox 3 Pro.
#[derive(Default, Debug)]
pub struct Mbox3Protocol;

impl TcatOperation for Mbox3Protocol {}

impl TcatGlobalSectionSpecification for Mbox3Protocol {}

impl TcatExtensionOperation for Mbox3Protocol {}

impl Tcd22xxSpecification for Mbox3Protocol {
    const INPUTS: &'static [Input] = &[
        Input {
            id: SrcBlkId::Ins0,
            offset: 0,
            count: 6,
            label: None,
        },
        Input {
            id: SrcBlkId::Ins1,
            offset: 0,
            count: 2,
            label: Some("Reverb"),
        },
        Input {
            id: SrcBlkId::Aes,
            offset: 0,
            count: 2,
            label: None,
        },
    ];
    const OUTPUTS: &'static [Output] = &[
        Output {
            id: DstBlkId::Ins0,
            offset: 0,
            count: 6,
            label: None,
        },
        Output {
            id: DstBlkId::Ins1,
            offset: 0,
            count: 4,
            label: Some("Headphone"),
        },
        Output {
            id: DstBlkId::Ins1,
            offset: 4,
            count: 2,
            label: Some("Reverb"),
        },
        Output {
            id: DstBlkId::Aes,
            offset: 0,
            count: 2,
            label: None,
        },
        Output {
            id: DstBlkId::Reserved(0x08),
            offset: 0,
            count: 2,
            label: Some("ControlRoom"),
        },
    ];
    const FIXED: &'static [SrcBlk] = &[
        SrcBlk {
            id: SrcBlkId::Ins0,
            ch: 0,
        },
        SrcBlk {
            id: SrcBlkId::Ins0,
            ch: 1,
        },
        SrcBlk {
            id: SrcBlkId::Ins0,
            ch: 2,
        },
        SrcBlk {
            id: SrcBlkId::Ins0,
            ch: 3,
        },
    ];
}

/// Usecase of standalone mode.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum StandaloneUseCase {
    /// For microphone pre-amplifier.
    Preamp,
    /// For A/D and D/A conversion.
    AdDa,
    /// For signal mixing.
    Mixer,
    /// Not decided yet.
    Undefined,
}

impl Default for StandaloneUseCase {
    fn default() -> Self {
        Self::Preamp
    }
}

impl StandaloneUseCase {
    const MIXER: u32 = 0x00;
    const AD_DA: u32 = 0x01;
    const PREAMP: u32 = 0x02;
    const UNDEFINED: u32 = 0x03;

    const MASK: u32 = 0x03;
}

fn serialize_standalone_use_case(
    use_case: &StandaloneUseCase,
    raw: &mut [u8],
) -> Result<(), String> {
    assert!(raw.len() >= 4);

    let mut val = 0u32;
    deserialize_u32(&mut val, raw);

    let flag = match use_case {
        StandaloneUseCase::Mixer => StandaloneUseCase::MIXER,
        StandaloneUseCase::AdDa => StandaloneUseCase::AD_DA,
        StandaloneUseCase::Preamp => StandaloneUseCase::PREAMP,
        StandaloneUseCase::Undefined => StandaloneUseCase::UNDEFINED,
    };

    val &= !StandaloneUseCase::MASK;
    val |= flag;
    serialize_u32(&val, raw);

    Ok(())
}

fn deserialize_standalone_use_case(
    use_case: &mut StandaloneUseCase,
    raw: &[u8],
) -> Result<(), String> {
    assert!(raw.len() >= 4);

    let mut val = 0u32;
    deserialize_u32(&mut val, raw);

    val &= StandaloneUseCase::MASK;
    *use_case = match val {
        StandaloneUseCase::MIXER => StandaloneUseCase::Mixer,
        StandaloneUseCase::AD_DA => StandaloneUseCase::AdDa,
        StandaloneUseCase::PREAMP => StandaloneUseCase::Preamp,
        _ => StandaloneUseCase::Undefined,
    };

    Ok(())
}

const MASTER_KNOB_MASK: u32 = 0x0000003f;

fn serialize_master_knob_assigns(assigns: &[bool; 6], raw: &mut [u8]) -> Result<(), String> {
    assert!(raw.len() >= 4);

    let mut val = 0u32;
    deserialize_u32(&mut val, raw);
    val &= !MASTER_KNOB_MASK;

    assigns
        .iter()
        .enumerate()
        .filter(|(_, &assign)| assign)
        .for_each(|(i, _)| val |= 1 << i);
    serialize_u32(&val, raw);

    Ok(())
}

fn deserialize_master_knob_assigns(assigns: &mut [bool; 6], raw: &[u8]) -> Result<(), String> {
    assert!(raw.len() >= 4);

    let mut val = 0u32;
    deserialize_u32(&mut val, raw);
    assigns
        .iter_mut()
        .enumerate()
        .for_each(|(i, assign)| *assign = val & (1 << i) > 0);

    Ok(())
}

/// LED state of mute button.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum MuteLedState {
    /// Turn Off.
    Off,
    /// Blink.
    Blink,
    /// Turn on.
    On,
}

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

impl MuteLedState {
    const LED_MASK: u32 = 0x00000003;
    const LED_BLINK_MASK: u32 = 0x00000001;
}

fn serialize_mute_led_state(state: &MuteLedState, raw: &mut [u8]) -> Result<(), String> {
    assert!(raw.len() >= 4);

    let mut val = 0u32;
    deserialize_u32(&mut val, raw);
    val &= !MuteLedState::LED_MASK;

    match state {
        MuteLedState::Off => (),
        MuteLedState::Blink => val |= MuteLedState::LED_BLINK_MASK,
        MuteLedState::On => val |= MuteLedState::LED_MASK & !MuteLedState::LED_BLINK_MASK,
    }

    serialize_u32(&val, raw);

    Ok(())
}

fn deserialize_mute_led_state(state: &mut MuteLedState, raw: &[u8]) -> Result<(), String> {
    assert!(raw.len() >= 4);

    let mut val = 0u32;
    deserialize_u32(&mut val, raw);

    *state = if val & MuteLedState::LED_MASK == 0 {
        MuteLedState::Off
    } else if val & MuteLedState::LED_BLINK_MASK > 0 {
        MuteLedState::Blink
    } else {
        MuteLedState::On
    };

    Ok(())
}

/// LED state of mono button.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum MonoLedState {
    /// Turn off.
    Off,
    /// Turn on.
    On,
}

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

impl MonoLedState {
    const LED_MASK: u32 = 0x0000000c;
}

fn serialize_mono_led_state(state: &MonoLedState, raw: &mut [u8]) -> Result<(), String> {
    assert!(raw.len() >= 4);

    let mut val = 0u32;
    deserialize_u32(&mut val, raw);
    val &= !MonoLedState::LED_MASK;

    match state {
        MonoLedState::Off => (),
        MonoLedState::On => val |= MonoLedState::LED_MASK,
    }

    serialize_u32(&val, raw);

    Ok(())
}

fn deserialize_mono_led_state(state: &mut MonoLedState, raw: &[u8]) -> Result<(), String> {
    assert!(raw.len() >= 4);

    let mut val = 0u32;
    deserialize_u32(&mut val, raw);

    *state = if val & MonoLedState::LED_MASK > 0 {
        MonoLedState::On
    } else {
        MonoLedState::Off
    };

    Ok(())
}

/// LED state of spkr button.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum SpkrLedState {
    /// Turn off.
    Off,
    /// Green light.
    Green,
    /// Blinking green light.
    GreenBlink,
    /// Red light.
    Red,
    /// Blinking red light.
    RedBlink,
    /// Orange light.
    Orange,
    /// Blinking orange light.
    OrangeBlink,
}

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

impl SpkrLedState {
    const COLOR_MASK: u32 = 0x00000060;
    const COLOR_SHIFT: usize = 5;
    const BLINK_MASK: u32 = 0x00000010;
    const BLINK_SHIFT: u32 = 4;

    const NONE: u32 = 0;
    const GREEN: u32 = 1;
    const RED: u32 = 2;
    const ORANGE: u32 = 3;
}

fn serialize_spkr_led_state(state: &SpkrLedState, raw: &mut [u8]) -> Result<(), String> {
    assert!(raw.len() >= 4);

    let mut val = 0u32;
    deserialize_u32(&mut val, raw);
    val &= !(SpkrLedState::COLOR_MASK | SpkrLedState::BLINK_MASK);

    let (color, blink) = match state {
        SpkrLedState::GreenBlink => (SpkrLedState::GREEN, true),
        SpkrLedState::Green => (SpkrLedState::GREEN, false),
        SpkrLedState::RedBlink => (SpkrLedState::RED, true),
        SpkrLedState::Red => (SpkrLedState::RED, false),
        SpkrLedState::OrangeBlink => (SpkrLedState::RED, true),
        SpkrLedState::Orange => (SpkrLedState::ORANGE, false),
        SpkrLedState::Off => (SpkrLedState::NONE, false),
    };

    val |= color << SpkrLedState::COLOR_SHIFT;
    if blink {
        val |= SpkrLedState::BLINK_MASK;
    }

    serialize_u32(&val, raw);

    Ok(())
}

fn deserialize_spkr_led_state(state: &mut SpkrLedState, raw: &[u8]) -> Result<(), String> {
    assert!(raw.len() >= 4);

    let mut val = 0u32;
    deserialize_u32(&mut val, raw);

    let color = (val & SpkrLedState::COLOR_MASK) >> SpkrLedState::COLOR_SHIFT;
    let blink = (val & SpkrLedState::BLINK_MASK) >> SpkrLedState::BLINK_SHIFT > 0;

    *state = match color {
        SpkrLedState::NONE => SpkrLedState::Off,
        SpkrLedState::GREEN => {
            if blink {
                SpkrLedState::GreenBlink
            } else {
                SpkrLedState::Green
            }
        }
        SpkrLedState::RED => {
            if blink {
                SpkrLedState::RedBlink
            } else {
                SpkrLedState::Red
            }
        }
        SpkrLedState::ORANGE => {
            if blink {
                SpkrLedState::OrangeBlink
            } else {
                SpkrLedState::Orange
            }
        }
        _ => Err(format!("Speaker LED state not found for value {}", val))?,
    };

    Ok(())
}

const PHANTOM_POWERING_MASK: u32 = 0x00000001;
const INPUT_HPF_ENABLES_MASK: u32 = 0x000000f0;
const INPUT_HPF_ENABLES_SHIFT: usize = 4;

fn serialize_phantom_powering(enable: &bool, raw: &mut [u8]) -> Result<(), String> {
    assert!(raw.len() >= 4);

    let mut val = 0u32;
    deserialize_u32(&mut val, raw);
    val &= !PHANTOM_POWERING_MASK;

    if *enable {
        val |= PHANTOM_POWERING_MASK;
    }

    serialize_u32(&val, raw);

    Ok(())
}

fn deserialize_phantom_powering(enable: &mut bool, raw: &[u8]) -> Result<(), String> {
    assert!(raw.len() >= 4);

    let mut val = 0u32;
    deserialize_u32(&mut val, raw);

    *enable = val & PHANTOM_POWERING_MASK > 0;

    Ok(())
}

fn serialize_hpf_enables(enables: &[bool; 4], raw: &mut [u8]) -> Result<(), String> {
    assert!(raw.len() >= 4);

    let mut val = 0u32;
    deserialize_u32(&mut val, raw);
    val &= !INPUT_HPF_ENABLES_MASK;

    enables
        .iter()
        .enumerate()
        .filter(|(_, &enabled)| enabled)
        .for_each(|(i, _)| val |= 1 << (i + INPUT_HPF_ENABLES_SHIFT));

    serialize_u32(&val, raw);

    Ok(())
}

fn deserialize_hpf_enables(enables: &mut [bool; 4], raw: &[u8]) -> Result<(), String> {
    assert!(raw.len() >= 4);

    let mut val = 0u32;
    deserialize_u32(&mut val, raw);

    enables
        .iter_mut()
        .enumerate()
        .for_each(|(i, enabled)| *enabled = val & (1 << (i + INPUT_HPF_ENABLES_SHIFT)) > 0);

    Ok(())
}

fn serialize_output_trims(trims: &[u8; 6], raw: &mut [u8]) -> Result<(), String> {
    assert!(raw.len() >= 24);

    trims.iter().enumerate().for_each(|(i, &trim)| {
        let pos = i * 4;
        serialize_u8(&(u8::MAX - trim), &mut raw[pos..(pos + 4)]);
    });

    Ok(())
}

fn deserialize_output_trims(trims: &mut [u8; 6], raw: &[u8]) -> Result<(), String> {
    assert!(raw.len() >= 24);

    let mut val = 0u8;
    trims.iter_mut().enumerate().for_each(|(i, trim)| {
        let pos = i * 4;
        deserialize_u8(&mut val, &raw[pos..(pos + 4)]);
        *trim = u8::MAX - val;
    });

    Ok(())
}

/// Type of reverb DSP.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum ReverbType {
    /// Room 1.
    Room1,
    /// Room 2.
    Room2,
    /// Room 3.
    Room3,
    /// Hall 1.
    Hall1,
    /// Hall 2.
    Hall2,
    /// Plate.
    Plate,
    /// Delay.
    Delay,
    /// Echo.
    Echo,
}

impl Default for ReverbType {
    fn default() -> Self {
        Self::Room1
    }
}

impl ReverbType {
    const ROOM_1: u32 = 0x01;
    const ROOM_2: u32 = 0x04;
    const ROOM_3: u32 = 0x05;
    const HALL_1: u32 = 0x06;
    const HALL_2: u32 = 0x08;
    const PLATE: u32 = 0x0b;
    const DELAY: u32 = 0x13;
    const ECHO: u32 = 0x14;
}

fn serialize_reverb_type(reverb_type: &ReverbType, raw: &mut [u8]) -> Result<(), String> {
    assert!(raw.len() >= 4);

    let val = match reverb_type {
        ReverbType::Room1 => ReverbType::ROOM_1,
        ReverbType::Room2 => ReverbType::ROOM_2,
        ReverbType::Room3 => ReverbType::ROOM_3,
        ReverbType::Hall1 => ReverbType::HALL_1,
        ReverbType::Hall2 => ReverbType::HALL_2,
        ReverbType::Plate => ReverbType::PLATE,
        ReverbType::Delay => ReverbType::DELAY,
        ReverbType::Echo => ReverbType::ECHO,
    };
    serialize_u32(&val, raw);

    Ok(())
}

fn deserialize_reverb_type(reverb_type: &mut ReverbType, raw: &[u8]) -> Result<(), String> {
    assert!(raw.len() >= 4);

    let mut val = 0u32;
    deserialize_u32(&mut val, raw);

    *reverb_type = match val {
        ReverbType::ROOM_1 => ReverbType::Room1,
        ReverbType::ROOM_2 => ReverbType::Room2,
        ReverbType::ROOM_3 => ReverbType::Room3,
        ReverbType::HALL_1 => ReverbType::Hall1,
        ReverbType::HALL_2 => ReverbType::Hall2,
        ReverbType::PLATE => ReverbType::Plate,
        ReverbType::DELAY => ReverbType::Delay,
        ReverbType::ECHO => ReverbType::Echo,
        _ => Err(format!("Reverb type not found for value {}", val))?,
    };

    Ok(())
}

/// Parameters specific to Mbox 3 pro.
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
pub struct Mbox3SpecificParams {
    /// Usecase at standalone mode.
    pub standalone_use_case: StandaloneUseCase,
    /// State of master knob.
    pub master_knob_value: u8,
    /// Assignment map for master knob.
    pub master_knob_assigns: [bool; 6],
    /// State of mute LED.
    pub mute_led: MuteLedState,
    /// State of mono LED.
    pub mono_led: MonoLedState,
    /// State of spkr LED.
    pub spkr_led: SpkrLedState,
    /// Whether to use dim LED.
    pub dim_led: bool,
    /// Duration till being activate by holding button.
    pub duration_hold: u8,
    /// Whether to supply phantom powering.
    pub phantom_powering: bool,
    /// Whether to enable High Pass Filter.
    pub hpf_enables: [bool; 4],
    /// Volume of analog outputs.
    pub output_trims: [u8; 6],
    /// The type of reverb.
    pub reverb_type: ReverbType,
    /// Volume of reverb return.
    pub reverb_volume: u8,
    /// Duration of reverb.
    pub reverb_duration: u8,
    /// Feedback of reverb.
    pub reverb_feedback: u8,
}

const MIN_SIZE: usize = 0x50;

fn serialize(params: &Mbox3SpecificParams, raw: &mut [u8]) -> Result<(), String> {
    assert!(raw.len() >= MIN_SIZE);

    serialize_standalone_use_case(&params.standalone_use_case, &mut raw[..0x04])?;
    serialize_u8(&params.master_knob_value, &mut raw[0x08..0x0c]);
    serialize_master_knob_assigns(&params.master_knob_assigns, &mut raw[0x0c..0x10])?;
    serialize_mute_led_state(&params.mute_led, &mut raw[0x10..0x14])?;
    serialize_mono_led_state(&params.mono_led, &mut raw[0x14..0x18])?;
    serialize_spkr_led_state(&params.spkr_led, &mut raw[0x14..0x18])?;
    serialize_bool(&params.dim_led, &mut raw[0x1c..0x20]);
    serialize_u8(&params.duration_hold, &mut raw[0x20..0x24]);
    serialize_phantom_powering(&params.phantom_powering, &mut raw[0x24..0x28])?;
    serialize_hpf_enables(&params.hpf_enables, &mut raw[0x24..0x28])?;
    serialize_output_trims(&params.output_trims, &mut raw[0x28..0x40])?;
    serialize_reverb_type(&params.reverb_type, &mut raw[0x40..0x44])?;
    serialize_u8(&params.reverb_volume, &mut raw[0x44..0x48]);
    serialize_u8(&params.reverb_duration, &mut raw[0x48..0x4c]);
    serialize_u8(&params.reverb_feedback, &mut raw[0x4c..0x50]);

    Ok(())
}

fn deserialize(params: &mut Mbox3SpecificParams, raw: &[u8]) -> Result<(), String> {
    assert!(raw.len() >= MIN_SIZE);

    deserialize_standalone_use_case(&mut params.standalone_use_case, &raw[..0x04])?;
    deserialize_u8(&mut params.master_knob_value, &raw[0x08..0x0c]);
    deserialize_master_knob_assigns(&mut params.master_knob_assigns, &raw[0x0c..0x10])?;
    deserialize_mute_led_state(&mut params.mute_led, &raw[0x10..0x14])?;
    deserialize_mono_led_state(&mut params.mono_led, &raw[0x14..0x18])?;
    deserialize_spkr_led_state(&mut params.spkr_led, &raw[0x14..0x18])?;
    deserialize_bool(&mut params.dim_led, &raw[0x1c..0x20]);
    deserialize_u8(&mut params.duration_hold, &raw[0x20..0x24]);
    deserialize_phantom_powering(&mut params.phantom_powering, &raw[0x24..0x28])?;
    deserialize_hpf_enables(&mut params.hpf_enables, &raw[0x24..0x28])?;
    deserialize_output_trims(&mut params.output_trims, &raw[0x28..0x40])?;
    deserialize_reverb_type(&mut params.reverb_type, &raw[0x40..0x44])?;
    deserialize_u8(&mut params.reverb_volume, &raw[0x44..0x48]);
    deserialize_u8(&mut params.reverb_duration, &raw[0x48..0x4c]);
    deserialize_u8(&mut params.reverb_feedback, &raw[0x4c..0x50]);

    Ok(())
}

const PHANTOM_POWERING_CHANGED: u32 = 0x10000000;
const MASTER_KNOB_CHANGED: u32 = 0x08000000;
const SPKR_BUTTON_PUSHED: u32 = 0x04000000;
const SPKR_BUTTON_HELD: u32 = 0x02000000;
const MONO_BUTTON_PUSHED: u32 = 0x00800000;
const MUTE_BUTTON_PUSHED: u32 = 0x00400000;
const MUTE_BUTTON_HELD: u32 = 0x00200000;

impl TcatExtensionSectionParamsOperation<Mbox3SpecificParams> for Mbox3Protocol {
    fn cache_extension_whole_params(
        req: &FwReq,
        node: &FwNode,
        sections: &ExtensionSections,
        _: &ExtensionCaps,
        params: &mut Mbox3SpecificParams,
        timeout_ms: u32,
    ) -> Result<(), Error> {
        let mut raw = vec![0u8; MIN_SIZE];
        Self::read_extension(req, node, &sections.application, 0, &mut raw, timeout_ms)?;
        deserialize(params, &raw).map_err(|cause| Error::new(ProtocolExtensionError::Appl, &cause))
    }
}

impl TcatExtensionSectionPartialMutableParamsOperation<Mbox3SpecificParams> for Mbox3Protocol {
    fn update_extension_partial_params(
        req: &FwReq,
        node: &FwNode,
        sections: &ExtensionSections,
        _: &ExtensionCaps,
        params: &Mbox3SpecificParams,
        prev: &mut Mbox3SpecificParams,
        timeout_ms: u32,
    ) -> Result<(), Error> {
        let mut new = vec![0u8; MIN_SIZE];
        serialize(params, &mut new)
            .map_err(|cause| Error::new(ProtocolExtensionError::Appl, &cause))?;

        let mut old = vec![0u8; MIN_SIZE];
        serialize(prev, &mut old)
            .map_err(|cause| Error::new(ProtocolExtensionError::Appl, &cause))?;

        (0..MIN_SIZE).step_by(4).try_for_each(|pos| {
            if new[pos..(pos + 4)] != old[pos..(pos + 4)] {
                Self::write_extension(
                    req,
                    node,
                    &sections.application,
                    pos,
                    &mut new[pos..(pos + 4)],
                    timeout_ms,
                )
            } else {
                Ok(())
            }
        })?;

        deserialize(prev, &new).map_err(|cause| Error::new(ProtocolExtensionError::Appl, &cause))
    }
}

impl TcatExtensionSectionNotifiedParamsOperation<Mbox3SpecificParams> for Mbox3Protocol {
    fn cache_extension_notified_params(
        req: &FwReq,
        node: &FwNode,
        sections: &ExtensionSections,
        caps: &ExtensionCaps,
        params: &mut Mbox3SpecificParams,
        msg: u32,
        timeout_ms: u32,
    ) -> Result<(), Error> {
        if msg & (PHANTOM_POWERING_CHANGED | MASTER_KNOB_CHANGED) > 0 {
            Self::cache_extension_whole_params(req, node, sections, caps, params, timeout_ms)?;
        }

        let mut p = params.clone();
        if msg & SPKR_BUTTON_PUSHED > 0 {
            p.spkr_led = match params.spkr_led {
                SpkrLedState::Off => SpkrLedState::Green,
                SpkrLedState::GreenBlink => SpkrLedState::Green,
                SpkrLedState::Green => SpkrLedState::Red,
                SpkrLedState::RedBlink => SpkrLedState::Red,
                SpkrLedState::Red => SpkrLedState::Orange,
                SpkrLedState::OrangeBlink => SpkrLedState::Orange,
                SpkrLedState::Orange => SpkrLedState::Off,
            };
        }

        if msg & SPKR_BUTTON_HELD > 0 {
            p.spkr_led = match params.spkr_led {
                SpkrLedState::Off => SpkrLedState::Off,
                SpkrLedState::GreenBlink => SpkrLedState::Green,
                SpkrLedState::Green => SpkrLedState::GreenBlink,
                SpkrLedState::RedBlink => SpkrLedState::Red,
                SpkrLedState::Red => SpkrLedState::RedBlink,
                SpkrLedState::OrangeBlink => SpkrLedState::Orange,
                SpkrLedState::Orange => SpkrLedState::OrangeBlink,
            };
        }

        if msg & MONO_BUTTON_PUSHED > 0 {
            p.mono_led = match params.mono_led {
                MonoLedState::Off => MonoLedState::On,
                MonoLedState::On => MonoLedState::Off,
            };
        }

        if msg & MUTE_BUTTON_PUSHED > 0 {
            p.mute_led = match params.mute_led {
                MuteLedState::Off => MuteLedState::On,
                MuteLedState::Blink => MuteLedState::On,
                MuteLedState::On => MuteLedState::Off,
            };
        }

        if msg & MUTE_BUTTON_HELD > 0 {
            p.mute_led = match params.mute_led {
                MuteLedState::Off => MuteLedState::Off,
                MuteLedState::Blink => MuteLedState::On,
                MuteLedState::On => MuteLedState::Blink,
            };
        }

        if !p.eq(params) {
            Self::update_extension_partial_params(
                req, node, sections, caps, &p, params, timeout_ms,
            )?;
        }

        Ok(())
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn mbox3_specific_params_serdes() {
        let params = Mbox3SpecificParams {
            standalone_use_case: StandaloneUseCase::AdDa,
            master_knob_value: 0xf9,
            master_knob_assigns: [true, false, true, true, false, true],
            mute_led: MuteLedState::Blink,
            mono_led: MonoLedState::On,
            spkr_led: SpkrLedState::RedBlink,
            dim_led: false,
            duration_hold: 10,
            phantom_powering: true,
            hpf_enables: [false, false, true, false],
            output_trims: [0, 1, 2, 3, 4, 5],
            reverb_type: ReverbType::Hall2,
            reverb_volume: 0xb3,
            reverb_duration: 0xa5,
            reverb_feedback: 0x17,
        };

        let mut raw = [0; MIN_SIZE];
        serialize(&params, &mut raw).unwrap();

        let mut p = Mbox3SpecificParams::default();
        deserialize(&mut p, &raw).unwrap();

        assert_eq!(params, p);
    }
}