Skip to main content

usbdac_core/convert/
format.rs

1//! The vocabulary of conversion: sample layouts, PCM formats, options, kinds and errors.
2
3use std::fmt;
4
5/// How the samples of a PCM stream are stored.
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
7pub enum SampleFormat {
8    /// Signed two's-complement integers, little-endian: `bits` significant bits, left-justified
9    /// in a slot of `slot_bytes` bytes (the unused low bits of the slot are zero). This is the
10    /// wire layout of `docs/API.md` section 4: 16-bit in 2 bytes, packed 24-bit in 3, 24-bit in 4
11    /// (the sample shifted left by 8) and 32-bit in 4.
12    Int { bits: u8, slot_bytes: u8 },
13    /// 32-bit IEEE-754 floats, little-endian, nominal range -1.0 to 1.0.
14    Float32,
15}
16
17impl SampleFormat {
18    /// 16-bit in 2 bytes.
19    pub const I16: Self = Self::Int {
20        bits: 16,
21        slot_bytes: 2,
22    };
23    /// Packed 24-bit in 3 bytes.
24    pub const I24: Self = Self::Int {
25        bits: 24,
26        slot_bytes: 3,
27    };
28    /// 24-bit left-justified in a 4-byte slot (the low byte is zero).
29    pub const I24_IN_32: Self = Self::Int {
30        bits: 24,
31        slot_bytes: 4,
32    };
33    /// 32-bit in 4 bytes.
34    pub const I32: Self = Self::Int {
35        bits: 32,
36        slot_bytes: 4,
37    };
38
39    /// An integer layout, checked: 8 to 32 significant bits in a slot of 1 to 4 bytes that holds them.
40    pub fn int(bits: u8, slot_bytes: u8) -> Result<Self, ConvertError> {
41        if !(8..=32).contains(&bits)
42            || !(1..=4).contains(&slot_bytes)
43            || u32::from(bits) > u32::from(slot_bytes) * 8
44        {
45            return Err(ConvertError::InvalidArgument(format!(
46                "{bits} significant bits do not fit a slot of {slot_bytes} bytes (8 to 32 bits, slots of 1 to 4 bytes)"
47            )));
48        }
49        Ok(Self::Int { bits, slot_bytes })
50    }
51
52    /// Bytes one sample takes.
53    pub fn bytes_per_sample(self) -> usize {
54        match self {
55            Self::Int { slot_bytes, .. } => usize::from(slot_bytes),
56            Self::Float32 => 4,
57        }
58    }
59
60    /// Significant bits of an integer layout; 32 for floats.
61    pub fn valid_bits(self) -> u8 {
62        match self {
63            Self::Int { bits, .. } => bits,
64            Self::Float32 => 32,
65        }
66    }
67
68    pub fn is_float(self) -> bool {
69        matches!(self, Self::Float32)
70    }
71
72    /// A phrase for descriptions: "16-bit", "24-bit (3-byte slot)", "32-bit float".
73    pub fn describe(self) -> String {
74        match self {
75            Self::Float32 => "32-bit float".to_string(),
76            Self::Int { bits, slot_bytes } => {
77                if u32::from(bits) == u32::from(slot_bytes) * 8 && bits != 24 {
78                    format!("{bits}-bit")
79                } else if bits == 24 && slot_bytes == 3 {
80                    "24-bit packed".to_string()
81                } else {
82                    format!("{bits}-bit in a {slot_bytes}-byte slot")
83                }
84            }
85        }
86    }
87}
88
89/// A PCM stream: its frame rate, channel count and sample layout.
90#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
91pub struct PcmFormat {
92    pub sample_rate: u32,
93    pub channels: u16,
94    pub sample: SampleFormat,
95}
96
97impl PcmFormat {
98    pub fn new(sample_rate: u32, channels: u16, sample: SampleFormat) -> Self {
99        Self {
100            sample_rate,
101            channels,
102            sample,
103        }
104    }
105
106    /// Bytes of one frame (one sample for every channel).
107    pub fn bytes_per_frame(&self) -> usize {
108        self.sample.bytes_per_sample() * usize::from(self.channels)
109    }
110}
111
112/// What a conversion does to the audio, from nothing to something irreversible.
113/// The order is the order of severity: a plan's kind is the largest of its steps'.
114#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
115pub enum ConversionKind {
116    /// Nothing changes; the bytes pass through.
117    None,
118    /// Every sample value is exactly what it was: widening to more bits (zero-filled low bits) and
119    /// moving a sample between slot sizes. A stream that was bit-perfect stays bit-perfect.
120    BitExact,
121    /// No information is lost and the values can be got back, but the audio is not identical:
122    /// mono duplicated to two channels, integers carried in a float that holds them exactly.
123    Lossless,
124    /// Information is lost or rounded: fewer bits, a float turned into integers, a new sample rate.
125    Lossy,
126}
127
128impl ConversionKind {
129    /// A stable identifier: `none`, `bit_exact`, `lossless`, `lossy`.
130    pub fn code(self) -> &'static str {
131        match self {
132            Self::None => "none",
133            Self::BitExact => "bit_exact",
134            Self::Lossless => "lossless",
135            Self::Lossy => "lossy",
136        }
137    }
138
139    /// Whether a stream that was bit-perfect at the target is still bit-perfect with respect to the source.
140    pub fn preserves_bit_perfect(self) -> bool {
141        self <= Self::BitExact
142    }
143}
144
145/// What to do with the bits an integer narrowing or a float-to-integer step cannot keep.
146#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
147pub enum Narrowing {
148    /// Drop them: round toward negative infinity (an arithmetic shift). The error is correlated
149    /// with the signal and has a mean of half a step.
150    Truncate,
151    /// Add triangular-PDF noise of one step (peak) before rounding to nearest: the error becomes
152    /// signal-independent noise at about -98 dBFS for 16 bits. The default.
153    #[default]
154    TpdfDither,
155}
156
157/// How much work the sample-rate converter does for how clean a result.
158#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
159pub enum Quality {
160    /// Stopband of about 110 dB and no aliasing of any band into the output (the stopband starts
161    /// at the lower Nyquist frequency), passband flat to 91% of it. The default.
162    #[default]
163    High,
164    /// About 2.5 times cheaper: stopband of about 84 dB, passband flat to 90% of the lower
165    /// Nyquist frequency, and content above it may alias into the top 10% of the band.
166    Fast,
167}
168
169/// The knobs of a conversion. `ConvertOptions::default()` is what the tests measured.
170#[derive(Debug, Clone, Copy, PartialEq)]
171pub struct ConvertOptions {
172    /// Applied wherever bits are dropped (integer narrowing and float to integer).
173    pub narrowing: Narrowing,
174    /// Used for sample-rate conversion.
175    pub quality: Quality,
176    /// Gain in dB (zero or negative) applied after sample-rate conversion, to keep the overshoot
177    /// of a resampled full-scale signal from clipping. `0.0` leaves the gain at exactly unity at
178    /// DC. The default is -3.5 dB; 0.0 requests unity.
179    pub headroom_db: f64,
180    /// Seed of the dither's pseudo-random generator: the same seed gives the same output.
181    pub dither_seed: u64,
182    /// The layout of the source samples when it is not the one the request's bit depth implies
183    /// (16, 24 packed or 32 integer): 32-bit float, or 24-bit in a 4-byte slot.
184    pub source_sample: Option<SampleFormat>,
185}
186
187impl Default for ConvertOptions {
188    fn default() -> Self {
189        Self {
190            narrowing: Narrowing::default(),
191            quality: Quality::default(),
192            headroom_db: -3.5,
193            dither_seed: 0x853c_49e6_748f_ea9b,
194            source_sample: None,
195        }
196    }
197}
198
199/// Why a plan or a converter could not be made, or a call is not valid now.
200#[derive(Debug, Clone, PartialEq, Eq)]
201pub enum ConvertError {
202    /// The conversion is not one this module does: DoP or native DSD, a channel mapping other
203    /// than mono to stereo, a sample-rate ratio that needs too large a filter.
204    Unsupported(String),
205    /// A format or option that is out of range or inconsistent.
206    InvalidArgument(String),
207    /// The call is not valid now (processing after `finish` without a `reset`).
208    InvalidState(String),
209}
210
211impl ConvertError {
212    /// A stable identifier: `unsupported`, `invalid_argument`, `invalid_state`.
213    pub fn code(&self) -> &'static str {
214        match self {
215            Self::Unsupported(_) => "unsupported",
216            Self::InvalidArgument(_) => "invalid_argument",
217            Self::InvalidState(_) => "invalid_state",
218        }
219    }
220
221    pub fn message(&self) -> &str {
222        match self {
223            Self::Unsupported(message)
224            | Self::InvalidArgument(message)
225            | Self::InvalidState(message) => message,
226        }
227    }
228}
229
230impl fmt::Display for ConvertError {
231    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
232        write!(f, "{}: {}", self.code(), self.message())
233    }
234}
235
236impl std::error::Error for ConvertError {}