minidsp_protocol/
dialect.rs

1use crate::{
2    commands::{Addr, Value},
3    FixedPoint,
4};
5
6/// Dialect represents the different encodings between devices
7#[derive(Default)]
8#[cfg_attr(feature = "debug", derive(Debug))]
9pub struct Dialect {
10    /// Length of addresses sent (either 3 (default) or 2)
11    pub addr_encoding: AddrEncoding,
12
13    /// Encoding for floating point values
14    pub float_encoding: FloatEncoding,
15}
16
17impl Dialect {
18    pub const fn const_default() -> Self {
19        Self {
20            addr_encoding: AddrEncoding::AddrLen3,
21            float_encoding: FloatEncoding::Float32LE,
22        }
23    }
24}
25
26#[repr(u8)]
27#[derive(Clone, Copy)]
28#[cfg_attr(feature = "debug", derive(Debug))]
29pub enum AddrEncoding {
30    AddrLen2 = 2,
31    AddrLen3 = 3,
32}
33
34impl Default for AddrEncoding {
35    fn default() -> Self {
36        AddrEncoding::AddrLen3
37    }
38}
39
40#[derive(Clone, Copy)]
41#[cfg_attr(feature = "debug", derive(Debug))]
42pub enum FloatEncoding {
43    Float32LE,
44    FixedPoint,
45}
46
47impl Default for FloatEncoding {
48    fn default() -> Self {
49        FloatEncoding::Float32LE
50    }
51}
52
53impl Dialect {
54    pub fn addr(&self, value: u16) -> Addr {
55        Addr::new(value, self.addr_encoding as u8)
56    }
57
58    pub fn float(&self, value: f32) -> Value {
59        match self.float_encoding {
60            FloatEncoding::Float32LE => Value::Float(value),
61            FloatEncoding::FixedPoint => Value::FixedPoint(FixedPoint::from_f32(value)),
62        }
63    }
64
65    pub fn db(&self, value: f32) -> Value {
66        match self.float_encoding {
67            FloatEncoding::Float32LE => Value::Float(value),
68            FloatEncoding::FixedPoint => Value::FixedPoint(FixedPoint::from_db(value)),
69        }
70    }
71
72    pub fn int(&self, value: u16) -> Value {
73        Value::Int(value)
74    }
75
76    // FIXME: Don't rely on addr len here
77    pub fn delay(&self, num_samples: u32) -> Value {
78        match self.addr_encoding {
79            AddrEncoding::AddrLen2 => Value::Int32(num_samples),
80            AddrEncoding::AddrLen3 => Value::Int(num_samples as _),
81        }
82    }
83
84    pub fn mute(&self, mute: bool) -> Value {
85        match self.addr_encoding {
86            AddrEncoding::AddrLen2 => Value::Int32(if mute { 0x0 } else { 0x0080_0000 }),
87            AddrEncoding::AddrLen3 => Value::Int(if mute { 0x1 } else { 0x2 }),
88        }
89    }
90
91    pub fn invert(&self, value: bool) -> Value {
92        match self.addr_encoding {
93            AddrEncoding::AddrLen2 => Value::Int32(if value { 0xFF80_0000 } else { 0x0080_0000 }),
94            AddrEncoding::AddrLen3 => Value::Int(value as _),
95        }
96    }
97}