usbdac_core/config.rs
1//! Configuration of a [`Dac`](crate::Dac) session.
2
3use crate::error::{Error, Result};
4use crate::iso_packet_scheduler::{DEFAULT_BUS_QUEUE_MS, DEFAULT_TRANSFERS_IN_FLIGHT};
5use crate::quirk::Quirk;
6
7/// What happens to the DAC's hardware volume when the [`Dac`](crate::Dac) is
8/// closed.
9///
10/// The library records the level the DAC had the first time it read its volume
11/// control (before it wrote anything), keyed by the device. This decides what is
12/// done with that record on close.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
14pub enum HandBack {
15 /// Write the recorded original level back to every channel, verify it, and
16 /// end the record. Use this when the DAC goes back to another audio stack
17 /// (for example Android's own USB audio driver).
18 #[default]
19 RestoreOriginal,
20 /// Leave the DAC at its current level and keep the record, so a later
21 /// [`Dac::open`](crate::Dac::open) of the same device in this process still
22 /// knows the true original level. Use this when the host takes the DAC
23 /// straight back.
24 Keep,
25}
26
27/// What [`Dac::close_with`](crate::Dac::close_with) does with the level the DAC
28/// had before the library first changed it, decided at close rather than at
29/// open.
30///
31/// [`HandBack`] is fixed in the [`DacConfig`] when the DAC opens. A host that
32/// only learns at the end what happens next (Android's own driver gets the DAC,
33/// the host takes it straight back, the DAC was unplugged) closes with this.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub enum CloseVolume {
36 /// Write the recorded original level back, verify it, and end the record.
37 Restore,
38 /// Leave the DAC at its current level and keep the record, so a later
39 /// [`Dac::open`](crate::Dac::open) of the same device in this process still
40 /// knows the true original level.
41 Keep,
42 /// End the record without touching the DAC: it is gone, so a later
43 /// attachment of the same device starts with a fresh record.
44 Forget,
45}
46
47/// What [`Dac::open`](crate::Dac::open) does with the DAC's hardware volume
48/// before any stream can start.
49///
50/// A DAC keeps the level it had, and many default to full scale. The first
51/// audio would then play at whatever that is.
52#[derive(Debug, Clone, Copy, PartialEq)]
53pub enum StartupVolume {
54 /// Lower every controlled channel to `min(its level, max_db)` and verify it
55 /// by reading it back. A channel is never raised, and one that is already
56 /// quieter (or at the device's silent value) is left alone. `max_db` is
57 /// rounded down to a step the DAC supports; below the DAC's minimum the
58 /// channels go to the minimum and the report says so. The level each
59 /// channel had is recorded first, so [`HandBack::RestoreOriginal`]
60 /// restores it. If the attenuation cannot be verified the volume control is
61 /// treated as unusable (see
62 /// [`DacConfig::require_hardware_volume`](DacConfig::require_hardware_volume)).
63 Attenuate { max_db: f64 },
64 /// Leave the DAC's level alone.
65 Keep,
66}
67
68impl Default for StartupVolume {
69 /// `Attenuate { max_db: -40.0 }`.
70 fn default() -> Self {
71 Self::Attenuate { max_db: -40.0 }
72 }
73}
74
75/// Extra quirks for one VID/PID, added to the built-in table.
76#[derive(Debug, Clone, PartialEq, Eq)]
77pub struct QuirkOverride {
78 pub vendor_id: u16,
79 pub product_id: u16,
80 /// Only apply when the product name contains this text; `None` matches any
81 /// name.
82 pub name_contains: Option<String>,
83 pub quirks: Vec<Quirk>,
84}
85
86/// Every tunable of a session. `DacConfig::default()` is what the library was
87/// tuned with.
88#[derive(Debug, Clone, PartialEq)]
89pub struct DacConfig {
90 /// Depth the host should keep the ring at: [`DacStream::writable_bytes`]
91 /// reports room up to this much. Absorbs a stall upstream (storage,
92 /// network, scheduling) shorter than this. Default 250 ms.
93 ///
94 /// [`DacStream::writable_bytes`]: crate::DacStream::writable_bytes
95 pub buffer_target_ms: u32,
96 /// Hard capacity of the ring; `write` never accepts more. Default 500 ms.
97 pub buffer_capacity_ms: u32,
98 /// How much audio the ring must hold before the stream starts, and before a
99 /// flushed ring resumes. Never above the target. Default 100 ms.
100 pub start_threshold_ms: u32,
101 /// The recommended ring depth while software gain is not 1.0, so a host
102 /// that processes audio itself sees changes sooner. Default 100 ms.
103 pub processing_buffer_target_ms: u32,
104 /// Refuse to stream unless the DAC confirms the sampling frequency it was
105 /// told. Default `true`. Turning it off lets a DAC with a broken clock
106 /// readback play, but the stream is then never reported bit-perfect.
107 pub require_verified_rate: bool,
108 /// Wait after programming the clock. `None` uses the device's quirk value,
109 /// else 20 ms.
110 pub clock_settle_delay_ms: Option<u64>,
111 /// Native DSD byte order on the wire. `None` follows the device quirk
112 /// (little-endian when there is none).
113 pub dsd_big_endian: Option<bool>,
114 /// Subslot size (1, 2 or 4) for native DSD alternate settings. `None`
115 /// follows the device quirk, else the descriptor.
116 pub dsd_subslot: Option<u8>,
117 /// Prefer the 4-byte subslot for 24-bit PCM. `None` follows the device
118 /// quirk (off when there is none).
119 pub padded_24bit: Option<bool>,
120 /// Quirks added to the built-in table for this session.
121 pub quirks: Vec<QuirkOverride>,
122 /// Allow streaming an asynchronous endpoint that has no explicit feedback
123 /// source. By
124 /// default `negotiate` and `open_stream` refuse it with
125 /// [`Error::ImplicitFeedbackUnsupported`]. Allowed, it streams at the nominal
126 /// rate, host-paced, and any drift between the DAC's clock and the host's
127 /// timing ends in underruns or overruns on the DAC; the stream is never
128 /// bit-perfect (`DacStream::bit_perfect_blocker` says why). Default `false`.
129 pub allow_unsynchronized_async: bool,
130 /// Disable explicit and implicit feedback for diagnosis. Default `false`.
131 /// Asynchronous nominal playback still requires `allow_unsynchronized_async`.
132 pub disable_feedback: bool,
133 /// Retain a bounded USB feedback support trace, including raw explicit
134 /// feedback bytes. Ask the listener to enable it before opening a session.
135 pub capture_feedback_trace: bool,
136 /// Ask for `SCHED_FIFO` (nice -16 as a fallback) on the output thread.
137 /// Android only; ignored elsewhere. Default `true`.
138 pub realtime_priority: bool,
139 /// What to do with the hardware volume level on close.
140 pub hand_back: HandBack,
141 /// How much audio, in milliseconds, is kept queued on the USB bus: the
142 /// transfers in flight together carry about this much. The same for every
143 /// service interval and encoding. It is what a pause or a flush still plays
144 /// out, and the headroom against a late output thread. 4 to 64, default 16. A transfer carries
145 /// `bus_queue_ms / transfers_in_flight` of audio (2 ms by default), at most
146 /// 32 packets, and the packets in flight never reach 256 (255 at most):
147 /// when the configured depth would, that cap wins and less is queued.
148 pub bus_queue_ms: u32,
149 /// How many isochronous transfers are in flight at once. 2 to 16,
150 /// default 8. See [`bus_queue_ms`](Self::bus_queue_ms).
151 pub transfers_in_flight: u32,
152 /// Cancel the transfers already on the bus when the stream is flushed, so
153 /// the audio of the old position is not heard after a seek or a track
154 /// change. The output thread cancels them, waits for the host controller to
155 /// hand every one back, and resumes with wire-correct silence until the
156 /// ring has refilled. Cancelled transfers are not lost audio, not
157 /// underruns, do not clear bit-perfect, and their music is not counted as
158 /// played. `pause` never cancels. `false` lets the queue play out (up to
159 /// `bus_queue_ms`). Default `true`.
160 pub cancel_in_flight_on_flush: bool,
161 /// What `Dac::open` does with the DAC's hardware volume before any stream
162 /// can start. Default: lower it to at most -40 dB.
163 pub startup_volume: StartupVolume,
164 /// `open_stream` fails with [`Error::VolumeUnavailable`] when the DAC has no
165 /// usable hardware volume control, so the host can ask the user to allow
166 /// fixed-level output and open the DAC again with this off. `negotiate` and
167 /// `capabilities` work either way. Default `true`.
168 pub require_hardware_volume: bool,
169}
170
171impl Default for DacConfig {
172 fn default() -> Self {
173 Self {
174 buffer_target_ms: 250,
175 buffer_capacity_ms: 500,
176 start_threshold_ms: 100,
177 processing_buffer_target_ms: 100,
178 require_verified_rate: true,
179 clock_settle_delay_ms: None,
180 dsd_big_endian: None,
181 dsd_subslot: None,
182 padded_24bit: None,
183 quirks: Vec::new(),
184 allow_unsynchronized_async: false,
185 disable_feedback: false,
186 capture_feedback_trace: false,
187 realtime_priority: true,
188 hand_back: HandBack::default(),
189 bus_queue_ms: DEFAULT_BUS_QUEUE_MS,
190 transfers_in_flight: DEFAULT_TRANSFERS_IN_FLIGHT,
191 cancel_in_flight_on_flush: true,
192 startup_volume: StartupVolume::default(),
193 require_hardware_volume: true,
194 }
195 }
196}
197
198impl DacConfig {
199 /// Checks the combination of values.
200 pub fn validate(&self) -> Result<()> {
201 let bad = |message: &str| Err(Error::InvalidArgument(message.to_string()));
202 if self.buffer_capacity_ms == 0 || self.buffer_capacity_ms > 10_000 {
203 return bad("buffer_capacity_ms must be between 1 and 10000");
204 }
205 if self.buffer_target_ms == 0 || self.buffer_target_ms > self.buffer_capacity_ms {
206 return bad("buffer_target_ms must be between 1 and buffer_capacity_ms");
207 }
208 if self.start_threshold_ms == 0 {
209 return bad("start_threshold_ms must be at least 1");
210 }
211 if self.processing_buffer_target_ms == 0
212 || self.processing_buffer_target_ms > self.buffer_capacity_ms
213 {
214 return bad("processing_buffer_target_ms must be between 1 and buffer_capacity_ms");
215 }
216 if let Some(subslot) = self.dsd_subslot {
217 if !matches!(subslot, 1 | 2 | 4) {
218 return bad("dsd_subslot must be 1, 2 or 4");
219 }
220 }
221 if let StartupVolume::Attenuate { max_db } = self.startup_volume {
222 if !max_db.is_finite() || !(-128.0..=0.0).contains(&max_db) {
223 return bad("startup_volume max_db must be a level between -128 and 0 dB");
224 }
225 }
226 if !(4..=64).contains(&self.bus_queue_ms) {
227 return bad("bus_queue_ms must be between 4 and 64");
228 }
229 if !(2..=16).contains(&self.transfers_in_flight) {
230 return bad("transfers_in_flight must be between 2 and 16");
231 }
232 Ok(())
233 }
234}
235
236#[cfg(test)]
237mod tests {
238 use super::*;
239
240 #[test]
241 fn defaults_are_the_values_the_transport_was_tuned_with() {
242 let config = DacConfig::default();
243 assert_eq!(config.buffer_target_ms, 250);
244 assert_eq!(config.buffer_capacity_ms, 500);
245 assert_eq!(config.start_threshold_ms, 100);
246 assert_eq!(config.processing_buffer_target_ms, 100);
247 assert!(config.require_verified_rate);
248 assert!(config.realtime_priority);
249 assert!(!config.allow_unsynchronized_async);
250 assert_eq!(config.hand_back, HandBack::RestoreOriginal);
251 assert_eq!(config.bus_queue_ms, 16);
252 assert_eq!(config.transfers_in_flight, 8);
253 assert!(config.cancel_in_flight_on_flush);
254 assert_eq!(
255 config.startup_volume,
256 StartupVolume::Attenuate { max_db: -40.0 }
257 );
258 assert!(config.require_hardware_volume);
259 config.validate().unwrap();
260 }
261
262 #[test]
263 fn validation_rejects_inconsistent_depths() {
264 let mut config = DacConfig::default();
265 config.buffer_target_ms = 600;
266 assert!(matches!(config.validate(), Err(Error::InvalidArgument(_))));
267 let mut config = DacConfig::default();
268 config.dsd_subslot = Some(3);
269 assert!(matches!(config.validate(), Err(Error::InvalidArgument(_))));
270 let mut config = DacConfig::default();
271 config.buffer_capacity_ms = 0;
272 assert!(config.validate().is_err());
273 }
274
275 #[test]
276 fn the_startup_ceiling_must_be_a_level_a_dac_can_have() {
277 for (startup_volume, ok) in [
278 (StartupVolume::Keep, true),
279 (StartupVolume::Attenuate { max_db: -40.0 }, true),
280 (StartupVolume::Attenuate { max_db: 0.0 }, true),
281 (StartupVolume::Attenuate { max_db: -128.0 }, true),
282 (StartupVolume::Attenuate { max_db: 3.0 }, false),
283 (StartupVolume::Attenuate { max_db: -200.0 }, false),
284 (StartupVolume::Attenuate { max_db: f64::NAN }, false),
285 (
286 StartupVolume::Attenuate {
287 max_db: f64::NEG_INFINITY,
288 },
289 false,
290 ),
291 ] {
292 let config = DacConfig {
293 startup_volume,
294 ..DacConfig::default()
295 };
296 assert_eq!(config.validate().is_ok(), ok, "{startup_volume:?}");
297 }
298 let error = DacConfig {
299 startup_volume: StartupVolume::Attenuate { max_db: 6.0 },
300 ..DacConfig::default()
301 }
302 .validate()
303 .unwrap_err();
304 assert!(matches!(&error, Error::InvalidArgument(message) if message.contains("max_db")));
305 }
306
307 #[test]
308 fn the_bus_queue_is_validated_at_both_ends_of_its_range() {
309 for (bus_queue_ms, ok) in [
310 (0, false),
311 (3, false),
312 (4, true),
313 (16, true),
314 (64, true),
315 (65, false),
316 ] {
317 let config = DacConfig {
318 bus_queue_ms,
319 ..DacConfig::default()
320 };
321 assert_eq!(config.validate().is_ok(), ok, "bus_queue_ms={bus_queue_ms}");
322 }
323 for (transfers_in_flight, ok) in [
324 (0, false),
325 (1, false),
326 (2, true),
327 (8, true),
328 (16, true),
329 (17, false),
330 ] {
331 let config = DacConfig {
332 transfers_in_flight,
333 ..DacConfig::default()
334 };
335 assert_eq!(
336 config.validate().is_ok(),
337 ok,
338 "transfers_in_flight={transfers_in_flight}"
339 );
340 }
341 let error = DacConfig {
342 bus_queue_ms: 3,
343 ..DacConfig::default()
344 }
345 .validate()
346 .unwrap_err();
347 assert!(
348 matches!(&error, Error::InvalidArgument(message) if message.contains("bus_queue_ms"))
349 );
350 }
351}