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
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (c) 2020 Takashi Sakamoto

//! A set of minimum items in TLV (Type-Length-Value) of ALSA control interface.

use super::*;

/// The data to express dB scale in TLV (Type-Length-Value) of ALSA control interface.
///
/// It has `SNDRV_CTL_TLVT_DB_SCALE` (=1) in its type field and has two elements in value field.
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
pub struct DbScale {
    /// The minimum value by dB expression, in 0.1 dB unit. This corresponds to the minimum
    /// value in the state of control element.
    pub min: i32,
    /// The step by dB expression, in 0.1 dB unit. This corresponds to one increase of the value
    /// in the state of control element.
    pub step: u16,
    /// If true, the value less than or equals to [`CTL_VALUE_MUTE`] (=-9999999) is available to
    /// mute the control element explicitly.
    pub mute_avail: bool,
}

/// When information about dB includes mute_avail, the value is available to mute the control
/// element. It's relevant to `SNDRV_CTL_TLVD_DB_GAIN_MUTE` macro in UAPI of Linux kernel.
pub const CTL_VALUE_MUTE: i32 = SNDRV_CTL_TLVD_DB_GAIN_MUTE;

/// The value of dB should be expressed in 0.1 dB unit in data of TLV and crate structures.
pub const DB_VALUE_MULTIPLIER: i32 = 100;

impl DbScale {
    const VALUE_COUNT: usize = 2;
}

impl<'a> TlvData<'a> for DbScale {
    fn value_type(&self) -> u32 {
        SNDRV_CTL_TLVT_DB_SCALE
    }

    fn value_length(&self) -> usize {
        Self::VALUE_COUNT
    }

    fn value(&self) -> Vec<u32> {
        let mut raw = Vec::new();
        raw.push(self.min as u32);
        raw.push(self.step as u32);
        if self.mute_avail {
            raw[1] |= SNDRV_CTL_TLVD_DB_SCALE_MUTE;
        }
        raw
    }
}

const TYPES_FOR_DB_SCALE: &'static [u32] = &[SNDRV_CTL_TLVT_DB_SCALE];

impl std::convert::TryFrom<&[u32]> for DbScale {
    type Error = TlvDecodeError;

    fn try_from(raw: &[u32]) -> Result<Self, Self::Error> {
        // At least, type and length field should be included.
        if raw.len() < 2 {
            Err(Self::Error::new(TlvDecodeErrorCtx::Length(raw.len(), 2), 0))
        // Check type field.
        } else if raw[0] != SNDRV_CTL_TLVT_DB_SCALE {
            Err(Self::Error::new(
                TlvDecodeErrorCtx::ValueType(raw[0], TYPES_FOR_DB_SCALE),
                0,
            ))
        } else {
            // Check length field against length of value field.
            let value_length = (raw[1] / 4) as usize;
            let value = &raw[2..];
            if value.len() < value_length {
                Err(Self::Error::new(
                    TlvDecodeErrorCtx::ValueLength(value_length, value.len()),
                    1,
                ))
            } else {
                // Decode value field.
                Ok(Self {
                    min: value[0] as i32,
                    step: (value[1] & SNDRV_CTL_TLVD_DB_SCALE_MASK) as u16,
                    mute_avail: value[1] & SNDRV_CTL_TLVD_DB_SCALE_MUTE > 0,
                })
            }
        }
    }
}

impl From<&DbScale> for Vec<u32> {
    fn from(data: &DbScale) -> Self {
        let mut raw = Vec::new();
        raw.push(data.value_type());
        raw.push(4 * data.value_length() as u32);
        raw.append(&mut data.value());
        raw
    }
}

impl From<DbScale> for Vec<u32> {
    fn from(data: DbScale) -> Self {
        (&data).into()
    }
}

/// The data to express dB interval in TLV (Type-Length-Value) of ALSA control interface.
///
/// It has three variants below;
///  * SNDRV_CTL_TLVT_DB_LINEAR(=2)
///  * SNDRV_CTL_TLVT_DB_MINMAX(=4)
///  * SNDRV_CTL_TLVT_DB_MINMAX_MUTE(=5)
///
///  All of them have two elements in value field.
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
pub struct DbInterval {
    /// The minimum value by dB expression, in 0.1 dB unit. This corresponds to the minimum
    /// value in the state of control element.
    pub min: i32,
    /// The maximum value by dB expression, 0.1 dB unit. This corresponds to the maximum value
    /// in the state of control element.
    pub max: i32,
    /// If true, the value in the state of control element increases linearly, thus need calculation
    /// to convert to the value by dB expression. The calculation shall be:
    ///
    /// 20 * log10( current_value / ( maximum_value - minimum_value ) ) (* 100 in 0.1dB unit)
    ///
    /// Else, the value in the state of control element corresponds to dB expression itself.
    pub linear: bool,
    /// If true, the value less than or equals to [`CTL_VALUE_MUTE`] (=-9999999) is available to
    /// mute the control element explicitly.
    pub mute_avail: bool,
}

impl DbInterval {
    const VALUE_COUNT: usize = 2;
}

impl<'a> TlvData<'a> for DbInterval {
    fn value_type(&self) -> u32 {
        if self.linear {
            SNDRV_CTL_TLVT_DB_LINEAR
        } else if self.mute_avail {
            SNDRV_CTL_TLVT_DB_MINMAX_MUTE
        } else {
            SNDRV_CTL_TLVT_DB_MINMAX
        }
    }

    fn value_length(&self) -> usize {
        Self::VALUE_COUNT
    }

    fn value(&self) -> Vec<u32> {
        vec![self.min as u32, self.max as u32]
    }
}

const TYPES_FOR_DB_INTERVAL: &'static [u32] = &[
    SNDRV_CTL_TLVT_DB_LINEAR,
    SNDRV_CTL_TLVT_DB_MINMAX,
    SNDRV_CTL_TLVT_DB_MINMAX_MUTE,
];

impl std::convert::TryFrom<&[u32]> for DbInterval {
    type Error = TlvDecodeError;

    fn try_from(raw: &[u32]) -> Result<Self, Self::Error> {
        // At least, type and length field should be included.
        if raw.len() < 2 {
            Err(Self::Error::new(TlvDecodeErrorCtx::Length(raw.len(), 2), 0))
        } else {
            // Check length field against length of value field.
            let value_length = (raw[1] / 4) as usize;
            let value = &raw[2..];
            if value.len() < value_length || value.len() < Self::VALUE_COUNT {
                Err(Self::Error::new(
                    TlvDecodeErrorCtx::ValueLength(value_length, value.len()),
                    1,
                ))
            } else {
                // Check type field.
                match raw[0] {
                    SNDRV_CTL_TLVT_DB_LINEAR => Ok(Self {
                        min: value[0] as i32,
                        max: value[1] as i32,
                        linear: true,
                        mute_avail: true,
                    }),
                    SNDRV_CTL_TLVT_DB_MINMAX => Ok(Self {
                        min: value[0] as i32,
                        max: value[1] as i32,
                        linear: false,
                        mute_avail: false,
                    }),
                    SNDRV_CTL_TLVT_DB_MINMAX_MUTE => Ok(Self {
                        min: value[0] as i32,
                        max: value[1] as i32,
                        linear: false,
                        mute_avail: true,
                    }),
                    _ => Err(Self::Error::new(
                        TlvDecodeErrorCtx::ValueType(raw[0], TYPES_FOR_DB_INTERVAL),
                        0,
                    )),
                }
            }
        }
    }
}

impl From<&DbInterval> for Vec<u32> {
    fn from(data: &DbInterval) -> Self {
        let mut raw = Vec::new();
        raw.push(data.value_type());
        raw.push(4 * data.value_length() as u32);
        raw.append(&mut data.value());
        raw
    }
}

impl From<DbInterval> for Vec<u32> {
    fn from(data: DbInterval) -> Self {
        (&data).into()
    }
}

/// The enumeration to express generic channel position corresponding to physical port on real
/// device. They are defined as `SNDRV_CHMAP_XXX` enumeration in UAPI of Linux kernel.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum ChmapGenericPos {
    Unknown,
    NotAvailable,
    Monaural,
    FrontLeft,
    FrontRight,
    RearLeft,
    RearRight,
    FrontCenter,
    LowFrequencyEffect,
    SideLeft,
    SideRight,
    RearCenter,
    FrontLeftCenter,
    FrontRightCenter,
    RearLeftCenter,
    RearRightCenter,
    FrontLeftWide,
    FrontRightWide,
    FrontLeftHigh,
    FrontCenterHigh,
    FrontRightHigh,
    TopCenter,
    TopFrontLeft,
    TopFrontRight,
    TopFrontCenter,
    TopRearLeft,
    TopRearRight,
    TopRearCenter,
    TopFrontLeftCenter,
    TopFrontRightCenter,
    TopSideLeft,
    TopSideRight,
    LeftLowFrequencyEffect,
    RightLowFrequencyEffect,
    BottomCenter,
    BottomLeftCenter,
    BottomRightCenter,
    Reserved(u16),
}

impl Default for ChmapGenericPos {
    fn default() -> Self {
        Self::Unknown
    }
}

impl std::convert::From<u16> for ChmapGenericPos {
    fn from(val: u16) -> Self {
        match val as u16 {
            SNDRV_CHMAP_UNKNOWN => Self::Unknown,
            SNDRV_CHMAP_NA => Self::NotAvailable,
            SNDRV_CHMAP_MONO => Self::Monaural,
            SNDRV_CHMAP_FL => Self::FrontLeft,
            SNDRV_CHMAP_FR => Self::FrontRight,
            SNDRV_CHMAP_RL => Self::RearLeft,
            SNDRV_CHMAP_RR => Self::RearRight,
            SNDRV_CHMAP_FC => Self::FrontCenter,
            SNDRV_CHMAP_LFE => Self::LowFrequencyEffect,
            SNDRV_CHMAP_SL => Self::SideLeft,
            SNDRV_CHMAP_SR => Self::SideRight,
            SNDRV_CHMAP_RC => Self::RearCenter,
            SNDRV_CHMAP_FLC => Self::FrontLeftCenter,
            SNDRV_CHMAP_FRC => Self::FrontRightCenter,
            SNDRV_CHMAP_RLC => Self::RearLeftCenter,
            SNDRV_CHMAP_RRC => Self::RearRightCenter,
            SNDRV_CHMAP_FLW => Self::FrontLeftWide,
            SNDRV_CHMAP_FRW => Self::FrontRightWide,
            SNDRV_CHMAP_FLH => Self::FrontLeftHigh,
            SNDRV_CHMAP_FCH => Self::FrontCenterHigh,
            SNDRV_CHMAP_FRH => Self::FrontRightHigh,
            SNDRV_CHMAP_TC => Self::TopCenter,
            SNDRV_CHMAP_TFL => Self::TopFrontLeft,
            SNDRV_CHMAP_TFR => Self::TopFrontRight,
            SNDRV_CHMAP_TFC => Self::TopFrontCenter,
            SNDRV_CHMAP_TRL => Self::TopRearLeft,
            SNDRV_CHMAP_TRR => Self::TopRearRight,
            SNDRV_CHMAP_TRC => Self::TopRearCenter,
            SNDRV_CHMAP_TFLC => Self::TopFrontLeftCenter,
            SNDRV_CHMAP_TFRC => Self::TopFrontRightCenter,
            SNDRV_CHMAP_TSL => Self::TopSideLeft,
            SNDRV_CHMAP_TSR => Self::TopSideRight,
            SNDRV_CHMAP_LLFE => Self::LeftLowFrequencyEffect,
            SNDRV_CHMAP_RLFE => Self::RightLowFrequencyEffect,
            SNDRV_CHMAP_BC => Self::BottomCenter,
            SNDRV_CHMAP_BLC => Self::BottomLeftCenter,
            SNDRV_CHMAP_BRC => Self::BottomRightCenter,
            _ => Self::Reserved(val),
        }
    }
}

impl From<ChmapGenericPos> for u16 {
    fn from(code: ChmapGenericPos) -> Self {
        match code {
            ChmapGenericPos::Unknown => SNDRV_CHMAP_UNKNOWN,
            ChmapGenericPos::NotAvailable => SNDRV_CHMAP_NA,
            ChmapGenericPos::Monaural => SNDRV_CHMAP_MONO,
            ChmapGenericPos::FrontLeft => SNDRV_CHMAP_FL,
            ChmapGenericPos::FrontRight => SNDRV_CHMAP_FR,
            ChmapGenericPos::RearLeft => SNDRV_CHMAP_RL,
            ChmapGenericPos::RearRight => SNDRV_CHMAP_RR,
            ChmapGenericPos::FrontCenter => SNDRV_CHMAP_FC,
            ChmapGenericPos::LowFrequencyEffect => SNDRV_CHMAP_LFE,
            ChmapGenericPos::SideLeft => SNDRV_CHMAP_SL,
            ChmapGenericPos::SideRight => SNDRV_CHMAP_SR,
            ChmapGenericPos::RearCenter => SNDRV_CHMAP_RC,
            ChmapGenericPos::FrontLeftCenter => SNDRV_CHMAP_FLC,
            ChmapGenericPos::FrontRightCenter => SNDRV_CHMAP_FRC,
            ChmapGenericPos::RearLeftCenter => SNDRV_CHMAP_RLC,
            ChmapGenericPos::RearRightCenter => SNDRV_CHMAP_RRC,
            ChmapGenericPos::FrontLeftWide => SNDRV_CHMAP_FLW,
            ChmapGenericPos::FrontRightWide => SNDRV_CHMAP_FRW,
            ChmapGenericPos::FrontLeftHigh => SNDRV_CHMAP_FLH,
            ChmapGenericPos::FrontCenterHigh => SNDRV_CHMAP_FCH,
            ChmapGenericPos::FrontRightHigh => SNDRV_CHMAP_FRH,
            ChmapGenericPos::TopCenter => SNDRV_CHMAP_TC,
            ChmapGenericPos::TopFrontLeft => SNDRV_CHMAP_TFL,
            ChmapGenericPos::TopFrontRight => SNDRV_CHMAP_TFR,
            ChmapGenericPos::TopFrontCenter => SNDRV_CHMAP_TFC,
            ChmapGenericPos::TopRearLeft => SNDRV_CHMAP_TRL,
            ChmapGenericPos::TopRearRight => SNDRV_CHMAP_TRR,
            ChmapGenericPos::TopRearCenter => SNDRV_CHMAP_TRC,
            ChmapGenericPos::TopFrontLeftCenter => SNDRV_CHMAP_TFLC,
            ChmapGenericPos::TopFrontRightCenter => SNDRV_CHMAP_TFRC,
            ChmapGenericPos::TopSideLeft => SNDRV_CHMAP_TSL,
            ChmapGenericPos::TopSideRight => SNDRV_CHMAP_TSR,
            ChmapGenericPos::LeftLowFrequencyEffect => SNDRV_CHMAP_LLFE,
            ChmapGenericPos::RightLowFrequencyEffect => SNDRV_CHMAP_RLFE,
            ChmapGenericPos::BottomCenter => SNDRV_CHMAP_BC,
            ChmapGenericPos::BottomLeftCenter => SNDRV_CHMAP_BLC,
            ChmapGenericPos::BottomRightCenter => SNDRV_CHMAP_BRC,
            ChmapGenericPos::Reserved(val) => val,
        }
    }
}

/// The enumeration to express channel position.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum ChmapPos {
    /// The position of channel is generic. It's relevant to the series of `SNDRV_CHMAP_XXX` macro.
    Generic(ChmapGenericPos),
    /// The position of channel is specific, programmed by driver. It's relevant to
    /// `SNDRV_CHMAP_DRIVER_SPEC` macro in UAPI of Linux kernel.
    Specific(u16),
}

impl Default for ChmapPos {
    fn default() -> Self {
        Self::Generic(Default::default())
    }
}

/// The entry to express information of each channel in channel map.
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
pub struct ChmapEntry {
    /// The position of channel.
    pub pos: ChmapPos,
    /// If true, phase is inverted (e.g. a microphone channel within multiple channels). It's
    /// relevant to `SNDRV_CHMAP_PHASE_INVERSE` macro in UAPI of Linux kernel.
    pub phase_inverse: bool,
}

impl std::convert::From<u32> for ChmapEntry {
    fn from(val: u32) -> Self {
        let pos_val = (val & 0x0000ffff) as u16;
        let phase_inverse = val & SNDRV_CHMAP_PHASE_INVERSE > 0;
        let driver_spec = val & SNDRV_CHMAP_DRIVER_SPEC > 0;
        let pos = if driver_spec {
            ChmapPos::Specific(pos_val)
        } else {
            ChmapPos::Generic(ChmapGenericPos::from(pos_val))
        };
        ChmapEntry { pos, phase_inverse }
    }
}

impl From<ChmapEntry> for u32 {
    fn from(entry: ChmapEntry) -> Self {
        let mut val = match entry.pos {
            ChmapPos::Generic(p) => u16::from(p) as u32,
            ChmapPos::Specific(p) => (p as u32) | SNDRV_CHMAP_DRIVER_SPEC,
        };
        if entry.phase_inverse {
            val |= SNDRV_CHMAP_PHASE_INVERSE;
        }
        val
    }
}

/// The mode for channel map.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum ChmapMode {
    /// The map is fixed and no way to change. It's relevant to `SNDRV_CTL_TLVT_CHMAP_FIXED`.
    Fixed,
    /// Each entry in the map is exchangeable arbitrarily. It's relevant to
    /// `SNDRV_CTL_TLVT_CHMAP_VAR`.
    ArbitraryExchangeable,
    /// The stereo pair of entries in the map is exchangeable. It's relevant to
    /// `SNDRV_CTL_TLVT_CHMAP_PAIRED`.
    PairedExchangeable,
}

impl Default for ChmapMode {
    fn default() -> Self {
        Self::Fixed
    }
}

/// The data to express channel map of PCM substream in TLV (Type-Length-Value) of ALSA control interface.
///
/// It has three variants below;
///  * `SNDRV_CTL_TLVT_CHMAP_FIXED` (=0x101)
///  * `SNDRV_CTL_TLVT_CHMAP_VAR` (=0x102)
///  * `SNDRV_CTL_TLVT_CHMAP_PAIRED` (=0x103)
///
/// The length of value field is variable depending on the number of channels.
#[derive(Default, Debug, Clone, PartialEq, Eq)]
pub struct Chmap {
    /// The mode of map.
    pub mode: ChmapMode,
    /// The entries of map corresponding to each channel.
    pub entries: Vec<ChmapEntry>,
}

impl<'a> TlvData<'a> for Chmap {
    fn value_type(&self) -> u32 {
        match self.mode {
            ChmapMode::Fixed => SNDRV_CTL_TLVT_CHMAP_FIXED,
            ChmapMode::ArbitraryExchangeable => SNDRV_CTL_TLVT_CHMAP_VAR,
            ChmapMode::PairedExchangeable => SNDRV_CTL_TLVT_CHMAP_PAIRED,
        }
    }

    fn value_length(&self) -> usize {
        self.entries.len()
    }

    fn value(&self) -> Vec<u32> {
        let mut raw = Vec::new();
        self.entries
            .iter()
            .for_each(|&entry| raw.push(u32::from(entry)));
        raw
    }
}

const TYPES_FOR_CHMAP: &'static [u32] = &[
    SNDRV_CTL_TLVT_CHMAP_FIXED,
    SNDRV_CTL_TLVT_CHMAP_VAR,
    SNDRV_CTL_TLVT_CHMAP_PAIRED,
];

impl std::convert::TryFrom<&[u32]> for Chmap {
    type Error = TlvDecodeError;

    fn try_from(raw: &[u32]) -> Result<Self, Self::Error> {
        // At least, type and length field should be included.
        if raw.len() < 2 {
            Err(Self::Error::new(TlvDecodeErrorCtx::Length(raw.len(), 2), 0))
        } else {
            // Check type field.
            let mode = match raw[0] {
                SNDRV_CTL_TLVT_CHMAP_FIXED => Ok(ChmapMode::Fixed),
                SNDRV_CTL_TLVT_CHMAP_VAR => Ok(ChmapMode::ArbitraryExchangeable),
                SNDRV_CTL_TLVT_CHMAP_PAIRED => Ok(ChmapMode::PairedExchangeable),
                _ => Err(Self::Error::new(
                    TlvDecodeErrorCtx::ValueType(raw[0], TYPES_FOR_CHMAP),
                    0,
                )),
            }?;

            // Check length field against length of value field.
            let value_length = (raw[1] / 4) as usize;
            let value = &raw[2..];
            if value.len() < value_length {
                Err(Self::Error::new(
                    TlvDecodeErrorCtx::ValueLength(value_length, value.len()),
                    1,
                ))
            } else if mode == ChmapMode::PairedExchangeable && value.len() % 2 > 0 {
                Err(Self::Error::new(
                    TlvDecodeErrorCtx::ValueLength(value_length, value.len()),
                    1,
                ))
            } else {
                // Decode value field.
                let entries = value.iter().map(|&val| ChmapEntry::from(val)).collect();
                Ok(Self { mode, entries })
            }
        }
    }
}

impl From<&Chmap> for Vec<u32> {
    fn from(data: &Chmap) -> Self {
        let mut raw = Vec::new();
        raw.push(data.value_type());
        raw.push(4 * data.value_length() as u32);
        raw.append(&mut data.value());
        raw
    }
}

impl From<Chmap> for Vec<u32> {
    fn from(data: Chmap) -> Self {
        (&data).into()
    }
}

#[cfg(test)]
mod test {
    use super::{Chmap, ChmapEntry, ChmapGenericPos, ChmapMode, ChmapPos};
    use super::{DbInterval, DbScale};
    use std::convert::TryFrom;

    #[test]
    fn test_dbitem() {
        let raw = [1u32, 8, -10i32 as u32, 0x00000010];
        let item = DbScale::try_from(raw.as_ref()).unwrap();
        assert_eq!(item.min, -10);
        assert_eq!(item.step, 16);
        assert_eq!(item.mute_avail, false);
        assert_eq!(&Vec::<u32>::from(item)[..], &raw[..]);
    }

    #[test]
    fn test_dbitem_mute_avail() {
        let raw = [1u32, 8, 10, 0x00010010];
        let item = DbScale::try_from(raw.as_ref()).unwrap();
        assert_eq!(item.min, 10);
        assert_eq!(item.step, 16);
        assert_eq!(item.mute_avail, true);
        assert_eq!(&Vec::<u32>::from(item)[..], &raw[..]);
    }

    #[test]
    fn test_dbinterval() {
        let raw = [4u32, 8, -100i32 as u32, 100];
        let item = DbInterval::try_from(&raw[..]).unwrap();
        assert_eq!(item.min, -100);
        assert_eq!(item.max, 100);
        assert_eq!(item.linear, false);
        assert_eq!(item.mute_avail, false);
        assert_eq!(&Vec::<u32>::from(item)[..], &raw[..]);
    }

    #[test]
    fn test_dbinterval_mute() {
        let raw = [5u32, 8, -100i32 as u32, 100];
        let item = DbInterval::try_from(&raw[..]).unwrap();
        assert_eq!(item.min, -100);
        assert_eq!(item.max, 100);
        assert_eq!(item.linear, false);
        assert_eq!(item.mute_avail, true);
        assert_eq!(&Vec::<u32>::from(item)[..], &raw[..]);
    }

    #[test]
    fn test_dbinterval_linear() {
        let raw = [2u32, 8, -100i32 as u32, 100];
        let item = DbInterval::try_from(&raw[..]).unwrap();
        assert_eq!(item.min, -100);
        assert_eq!(item.max, 100);
        assert_eq!(item.linear, true);
        assert_eq!(item.mute_avail, true);
        assert_eq!(&Vec::<u32>::from(item)[..], &raw[..]);
    }

    #[test]
    fn test_chmapgenericpos() {
        (0..u16::MAX).for_each(|val| {
            let generic_pos = ChmapGenericPos::from(val);
            assert_eq!(u16::from(generic_pos), val);
        });
    }

    #[test]
    fn test_chmapentry() {
        (0..37).for_each(|val| {
            let raw = val as u32;
            let entry = ChmapEntry::try_from(raw).unwrap();
            assert_eq!(entry.phase_inverse, false);
            assert_eq!(u32::from(entry), raw);

            let raw = 0x00010000u32 | (val as u32);
            let entry = ChmapEntry::try_from(raw).unwrap();
            assert_eq!(entry.phase_inverse, true);
            assert_eq!(u32::from(entry), raw);

            let raw = 0x00020000u32 | (val as u32);
            let entry = ChmapEntry::try_from(raw).unwrap();
            assert_eq!(entry.phase_inverse, false);
            assert_eq!(u32::from(entry), raw);
        });
    }

    #[test]
    fn test_chmap_fixed() {
        let raw = [0x101u32, 8, 3, 4];
        let map = Chmap::try_from(&raw[..]).unwrap();
        assert_eq!(map.mode, ChmapMode::Fixed);
        assert_eq!(
            &map.entries[..],
            &[
                ChmapEntry {
                    pos: ChmapPos::Generic(ChmapGenericPos::FrontLeft),
                    phase_inverse: false
                },
                ChmapEntry {
                    pos: ChmapPos::Generic(ChmapGenericPos::FrontRight),
                    phase_inverse: false
                },
            ]
        );
        assert_eq!(&Vec::<u32>::from(map)[..], &raw[..]);
    }

    #[test]
    fn test_chmap_arbitrary_exchangeable() {
        let raw = [0x102u32, 12, 3, 4, 8];
        let map = Chmap::try_from(&raw[..]).unwrap();
        assert_eq!(map.mode, ChmapMode::ArbitraryExchangeable);
        assert_eq!(
            &map.entries[..],
            &[
                ChmapEntry {
                    pos: ChmapPos::Generic(ChmapGenericPos::FrontLeft),
                    phase_inverse: false
                },
                ChmapEntry {
                    pos: ChmapPos::Generic(ChmapGenericPos::FrontRight),
                    phase_inverse: false
                },
                ChmapEntry {
                    pos: ChmapPos::Generic(ChmapGenericPos::LowFrequencyEffect),
                    phase_inverse: false
                },
            ][..]
        );
        assert_eq!(&Vec::<u32>::from(map)[..], &raw[..]);
    }

    #[test]
    fn test_chmap_paired_exchangeable() {
        let raw = [0x103u32, 16, 3, 4, 5, 6];
        let map = Chmap::try_from(&raw[..]).unwrap();
        assert_eq!(map.mode, ChmapMode::PairedExchangeable);
        assert_eq!(
            &map.entries[..],
            &[
                ChmapEntry {
                    pos: ChmapPos::Generic(ChmapGenericPos::FrontLeft),
                    phase_inverse: false
                },
                ChmapEntry {
                    pos: ChmapPos::Generic(ChmapGenericPos::FrontRight),
                    phase_inverse: false
                },
                ChmapEntry {
                    pos: ChmapPos::Generic(ChmapGenericPos::RearLeft),
                    phase_inverse: false
                },
                ChmapEntry {
                    pos: ChmapPos::Generic(ChmapGenericPos::RearRight),
                    phase_inverse: false
                },
            ][..]
        );
        assert_eq!(&Vec::<u32>::from(map)[..], &raw[..]);
    }
}