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