Skip to main content

usbdac_core/
format.rs

1//! Stream formats: what the host asks for and what goes on the wire.
2
3use crate::capabilities::{LinkSpeed, Pacing, SyncKind};
4use crate::clock_resolution::ClockChoice;
5
6/// How the audio is carried.
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub enum Encoding {
9    /// Linear PCM.
10    Pcm,
11    /// Type I unsigned 8-bit PCM; silence is 0x80, one byte per sample.
12    PcmU8,
13    /// Type I IEEE-754 binary32 PCM; exact little-endian bits, including NaN payloads.
14    PcmFloat32,
15    /// DSD over PCM: 16 DSD bits per channel per PCM frame, with the 0x05/0xFA
16    /// marker byte owned by the library. `sample_rate` of the request is the
17    /// carrier rate (DSD bit rate / 16: 176400 for DSD64).
18    DoP,
19    /// Native DSD alternate setting; `bit_rate` is the 1-bit rate per channel
20    /// (2822400 for DSD64).
21    DsdNative { bit_rate: u32 },
22}
23
24/// What to do when the DAC cannot run the requested rate.
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
26pub enum RatePolicy {
27    /// Fail with [`Error::Unsupported`](crate::Error::Unsupported). Nothing is
28    /// ever resampled by the library, so a host that cannot resample itself
29    /// wants this.
30    #[default]
31    Exact,
32    /// Prefer the highest supported integer divisor of the requested rate, then the highest
33    /// lower rate in the same rate family, then the highest other lower rate, then the lowest
34    /// higher rate. [`StreamFormat::sample_rate`] then
35    /// differs from the request; the host must resample, and the stream is not
36    /// reported bit-perfect.
37    NearestSupported,
38}
39
40/// A format the host would like.
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub struct StreamRequest {
43    /// PCM rate, or the DoP carrier rate. Ignored for native DSD (the wire
44    /// rate follows from `bit_rate` and the subslot size).
45    pub sample_rate: u32,
46    pub channels: u16,
47    /// Significant bits per sample: 16, 24 or 32 for PCM; 24 or 32 for DoP;
48    /// ignored for native DSD.
49    pub bit_depth: u8,
50    pub encoding: Encoding,
51    pub rate_policy: RatePolicy,
52}
53
54impl StreamRequest {
55    /// PCM at `sample_rate` with `bit_depth` significant bits.
56    pub fn pcm(sample_rate: u32, channels: u16, bit_depth: u8) -> Self {
57        Self {
58            sample_rate,
59            channels,
60            bit_depth,
61            encoding: Encoding::Pcm,
62            rate_policy: RatePolicy::Exact,
63        }
64    }
65
66    /// Unsigned Type I PCM with one byte per channel sample.
67    pub fn pcm_u8(sample_rate: u32, channels: u16) -> Self {
68        Self {
69            encoding: Encoding::PcmU8,
70            ..Self::pcm(sample_rate, channels, 8)
71        }
72    }
73
74    /// IEEE-754 binary32 Type I PCM, retained as exact wire bits.
75    pub fn pcm_float32(sample_rate: u32, channels: u16) -> Self {
76        Self {
77            encoding: Encoding::PcmFloat32,
78            ..Self::pcm(sample_rate, channels, 32)
79        }
80    }
81
82    /// DoP for a DSD stream of `dsd_bit_rate` (2822400 for DSD64) in a 24-bit
83    /// carrier.
84    pub fn dop(dsd_bit_rate: u32, channels: u16) -> Self {
85        Self {
86            sample_rate: dsd_bit_rate / 16,
87            channels,
88            bit_depth: 24,
89            encoding: Encoding::DoP,
90            rate_policy: RatePolicy::Exact,
91        }
92    }
93
94    /// Native DSD of `dsd_bit_rate` (2822400 for DSD64).
95    pub fn dsd_native(dsd_bit_rate: u32, channels: u16) -> Self {
96        Self {
97            sample_rate: 0,
98            channels,
99            bit_depth: 0,
100            encoding: Encoding::DsdNative {
101                bit_rate: dsd_bit_rate,
102            },
103            rate_policy: RatePolicy::Exact,
104        }
105    }
106
107    pub fn with_rate_policy(mut self, rate_policy: RatePolicy) -> Self {
108        self.rate_policy = rate_policy;
109        self
110    }
111}
112
113/// What will go on the wire, as chosen by
114/// [`Dac::negotiate`](crate::Dac::negotiate).
115///
116/// A `StreamFormat` cannot be built by hand; pass the one `negotiate` returned
117/// to [`Dac::open_stream`](crate::Dac::open_stream).
118#[derive(Debug, Clone, PartialEq)]
119#[non_exhaustive]
120pub struct StreamFormat {
121    /// The request this format answers.
122    pub request: StreamRequest,
123    pub encoding: Encoding,
124    /// Frame rate on the wire: the PCM rate, the DoP carrier rate, or for
125    /// native DSD the rate of subslot-sized words (`bit_rate / (8 *
126    /// subslot_bytes)`).
127    pub sample_rate: u32,
128    pub channels: u16,
129    /// Descriptor-backed identities in interleaved USB wire order; unnamed when unavailable.
130    pub channel_map: crate::capture::ChannelMap,
131    /// Significant bits of the alternate setting (PCM and DoP carrier). 1 for
132    /// native DSD.
133    pub valid_bits: u8,
134    /// Bytes per sample on the wire.
135    pub subslot_bytes: u8,
136    pub interface_number: u8,
137    pub alt_setting: u8,
138    pub endpoint_address: u8,
139    pub sync_type: SyncKind,
140    pub explicit_feedback: bool,
141    pub link_speed: LinkSpeed,
142    pub service_interval_us: u32,
143    /// How the stream is paced on the endpoint: what the transport does, named
144    /// (see [`Pacing`]). Consistent with `sync_type` and `explicit_feedback`.
145    pub pacing: Pacing,
146    /// The Clock Source the sample rate was set and verified on, and how it was
147    /// reached from the stream's terminal (see [`ClockChoice`]), as resolved by
148    /// [`Dac::negotiate`](crate::Dac::negotiate). `None` when the DAC has no
149    /// clock entities to set (UAC 1.0 sets the rate on the endpoint).
150    pub clock: Option<ClockChoice>,
151    /// Native word width, byte order and bit order frozen at negotiation.
152    pub(crate) native_dsd_signature: Option<(u8, bool, bool)>,
153}
154
155impl StreamFormat {
156    /// Bytes of one wire frame (one sample for every channel): the unit
157    /// [`DacStream::write`](crate::DacStream::write) counts in. Also the
158    /// granularity of everything the stream accepts.
159    pub fn bytes_per_frame(&self) -> usize {
160        usize::from(self.subslot_bytes) * usize::from(self.channels)
161    }
162
163    /// Rate of the unit that `played_frames()`, `latency_frames()` and the
164    /// stream statistics count in. For PCM and DoP it is the wire frame rate.
165    /// For native DSD it is `bit_rate / 8`: one frame is one DSD byte per
166    /// channel (8 DSD bits per channel).
167    pub fn counter_rate_hz(&self) -> u32 {
168        match self.encoding {
169            Encoding::DsdNative { bit_rate } => bit_rate / 8,
170            _ => self.sample_rate,
171        }
172    }
173
174    /// Whether the DAC runs a different rate than requested (only possible
175    /// with [`RatePolicy::NearestSupported`]).
176    pub fn rate_differs_from_request(&self) -> bool {
177        match self.encoding {
178            Encoding::DsdNative { .. } => false,
179            _ => self.sample_rate != self.request.sample_rate,
180        }
181    }
182}
183
184#[cfg(test)]
185mod tests {
186    use super::*;
187
188    #[test]
189    fn request_constructors_derive_the_carrier_rate() {
190        assert_eq!(StreamRequest::dop(2_822_400, 2).sample_rate, 176_400);
191        assert_eq!(StreamRequest::dop(5_644_800, 2).sample_rate, 352_800);
192        let native = StreamRequest::dsd_native(2_822_400, 2);
193        assert_eq!(native.sample_rate, 0);
194        assert_eq!(
195            native.encoding,
196            Encoding::DsdNative {
197                bit_rate: 2_822_400
198            }
199        );
200        assert_eq!(
201            StreamRequest::pcm(44_100, 2, 16).rate_policy,
202            RatePolicy::Exact
203        );
204    }
205}