Skip to main content

usbdac_core/
config.rs

1//! Configuration of a [`Dac`](crate::Dac) session.
2
3/// Policy for asynchronous endpoints without a proven feedback source.
4#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
5pub enum AsyncFallbackPolicy {
6    /// Admit only full-speed UAC1 PCM with no declared feedback pipe.
7    #[default]
8    FullSpeedUac1,
9    /// Require explicit or proven implicit feedback.
10    Forbid,
11}
12
13/// Policy for unusable frequency readback after an acknowledged rate write.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
15pub enum ClockReadbackPolicy {
16    #[default]
17    RequireVerified,
18    /// Continue unverified after three unusable reads; never hide a mismatch.
19    AllowUnusableAfterSuccessfulSet,
20}
21
22/// How validated explicit feedback reports change packet timing.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
24pub enum FeedbackSmoothing {
25    /// Apply each accepted report directly, without averaging or rate rounding.
26    #[default]
27    Direct,
28    /// Legacy filter: first report directly, then old + 0.2 * (report - old).
29    Ewma,
30}
31
32impl FeedbackSmoothing {
33    pub fn as_str(self) -> &'static str {
34        match self {
35            Self::Direct => "direct",
36            Self::Ewma => "ewma",
37        }
38    }
39}
40
41use crate::error::{Error, Result};
42use crate::iso_packet_scheduler::{DEFAULT_BUS_QUEUE_MS, DEFAULT_TRANSFERS_IN_FLIGHT};
43use crate::quirk::Quirk;
44
45/// What happens to the DAC's hardware volume when the [`Dac`](crate::Dac) is
46/// closed.
47///
48/// The library records the level the DAC had the first time it read its volume
49/// control (before it wrote anything), keyed by the device. This decides what is
50/// done with that record on close.
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
52pub enum HandBack {
53    /// Write the recorded original level back to every channel, verify it, and
54    /// end the record. Use this when the DAC goes back to another audio stack
55    /// (for example Android's own USB audio driver).
56    #[default]
57    RestoreOriginal,
58    /// Leave the DAC at its current level and keep the record, so a later
59    /// [`Dac::open`](crate::Dac::open) of the same device in this process still
60    /// knows the true original level. Use this when the host takes the DAC
61    /// straight back.
62    Keep,
63}
64
65/// What [`Dac::close_with`](crate::Dac::close_with) does with the level the DAC
66/// had before the library first changed it, decided at close rather than at
67/// open.
68///
69/// [`HandBack`] is fixed in the [`DacConfig`] when the DAC opens. A host that
70/// only learns at the end what happens next (Android's own driver gets the DAC,
71/// the host takes it straight back, the DAC was unplugged) closes with this.
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub enum CloseVolume {
74    /// Write the recorded original level back, verify it, and end the record.
75    Restore,
76    /// Leave the DAC at its current level and keep the record, so a later
77    /// [`Dac::open`](crate::Dac::open) of the same device in this process still
78    /// knows the true original level.
79    Keep,
80    /// End the record without touching the DAC: it is gone, so a later
81    /// attachment of the same device starts with a fresh record.
82    Forget,
83}
84
85/// What [`Dac::open`](crate::Dac::open) does with the DAC's hardware volume
86/// before any stream can start.
87///
88/// A DAC keeps the level it had, and many default to full scale. The first
89/// audio would then play at whatever that is.
90#[derive(Debug, Clone, Copy, PartialEq)]
91pub enum StartupVolume {
92    /// Lower every controlled channel to `min(its level, max_db)` and verify it
93    /// by reading it back. A channel is never raised, and one that is already
94    /// quieter (or at the device's silent value) is left alone. `max_db` is
95    /// rounded down to a step the DAC supports; below the DAC's minimum the
96    /// channels go to the minimum and the report says so. The level each
97    /// channel had is recorded first, so [`HandBack::RestoreOriginal`]
98    /// restores it. If the attenuation cannot be verified the volume control is
99    /// treated as unusable (see
100    /// [`DacConfig::require_hardware_volume`](DacConfig::require_hardware_volume)).
101    Attenuate { max_db: f64 },
102    /// Leave the DAC's level alone.
103    Keep,
104}
105
106impl Default for StartupVolume {
107    /// `Attenuate { max_db: -40.0 }`.
108    fn default() -> Self {
109        Self::Attenuate { max_db: -40.0 }
110    }
111}
112
113/// Extra quirks for one VID/PID, added to the built-in table.
114#[derive(Debug, Clone, PartialEq, Eq)]
115pub struct QuirkOverride {
116    pub vendor_id: u16,
117    pub product_id: u16,
118    /// Only apply when the product name contains this text; `None` matches any
119    /// name.
120    pub name_contains: Option<String>,
121    pub quirks: Vec<Quirk>,
122}
123
124/// Every tunable of a session. `DacConfig::default()` is what the library was
125/// tuned with.
126#[derive(Debug, Clone, PartialEq)]
127pub struct DacConfig {
128    /// Depth the host should keep the ring at: [`DacStream::writable_bytes`]
129    /// reports room up to this much. Absorbs a stall upstream (storage,
130    /// network, scheduling) shorter than this. Default 250 ms.
131    ///
132    /// [`DacStream::writable_bytes`]: crate::DacStream::writable_bytes
133    pub buffer_target_ms: u32,
134    /// Hard capacity of the ring; `write` never accepts more. Default 500 ms.
135    pub buffer_capacity_ms: u32,
136    /// How much audio the ring must hold before the stream starts, and before a
137    /// flushed ring resumes. Never above the target. Default 100 ms.
138    pub start_threshold_ms: u32,
139    /// The recommended ring depth while software gain is not 1.0, so a host
140    /// that processes audio itself sees changes sooner. Default 100 ms.
141    pub processing_buffer_target_ms: u32,
142    /// Refuse to stream unless the DAC confirms the sampling frequency it was
143    /// told. Default `true`. Turning it off lets a DAC with a broken clock
144    /// readback play, but the stream is then never reported bit-perfect.
145    pub require_verified_rate: bool,
146    /// Wait after programming the clock. `None` uses the device's quirk value,
147    /// else 20 ms.
148    pub clock_settle_delay_ms: Option<u64>,
149    /// Native DSD byte order on the wire. `None` follows the device quirk
150    /// (little-endian when there is none).
151    pub dsd_big_endian: Option<bool>,
152    /// Subslot size (1, 2 or 4) for native DSD alternate settings. `None`
153    /// follows the device quirk, else the descriptor.
154    pub dsd_subslot: Option<u8>,
155    /// Prefer the 4-byte subslot for 24-bit PCM. `None` follows the device
156    /// quirk (off when there is none).
157    pub padded_24bit: Option<bool>,
158    /// Quirks added to the built-in table for this session.
159    pub quirks: Vec<QuirkOverride>,
160    /// Apply supported exact-identity ALSA facts only when explicitly selected.
161    pub quirk_policy: crate::quirk::QuirkPolicy,
162    /// Allow streaming an asynchronous endpoint that has no explicit feedback
163    /// source, beyond the narrow default [`AsyncFallbackPolicy`] tier.
164    /// Otherwise `negotiate` and `open_stream` refuse it with
165    /// [`Error::ImplicitFeedbackUnsupported`]. Allowed, it streams at the nominal
166    /// rate, host-paced, and any drift between the DAC's clock and the host's
167    /// timing ends in underruns or overruns on the DAC; the stream is never
168    /// bit-perfect (`DacStream::bit_perfect_blocker` says why). Default `false`.
169    pub allow_unsynchronized_async: bool,
170    /// Narrow default fallback; never bit-perfect.
171    pub async_fallback_policy: AsyncFallbackPolicy,
172    /// Permit the unverified clock tier only after an acknowledged SET.
173    pub clock_readback_policy: ClockReadbackPolicy,
174    /// Adapt active URB count to loss, bounded by 64 ms and 255 packets.
175    pub adaptive_queue: bool,
176    /// Disable explicit and implicit feedback for diagnosis. Default `false`.
177    /// Asynchronous nominal playback still requires `allow_unsynchronized_async`.
178    pub disable_feedback: bool,
179    /// Explicit feedback timing policy. Direct by default; implicit cadence
180    /// vectors and nominal pacing are unaffected. Applied when a stream opens.
181    pub feedback_smoothing: FeedbackSmoothing,
182    /// Retain a bounded USB feedback support trace, including raw explicit
183    /// feedback bytes. Ask the listener to enable it before opening a session.
184    pub capture_feedback_trace: bool,
185    /// Ask for `SCHED_FIFO` (nice -16 as a fallback) on the output thread.
186    /// Android only; ignored elsewhere. Default `true`.
187    pub realtime_priority: bool,
188    /// What to do with the hardware volume level on close.
189    pub hand_back: HandBack,
190    /// How much audio, in milliseconds, is kept queued on the USB bus: the
191    /// transfers in flight together carry about this much. The same for every
192    /// service interval and encoding. It is what a pause or a flush still plays
193    /// out, and the headroom against a late output thread. 4 to 64, default 16. A transfer carries
194    /// `bus_queue_ms / transfers_in_flight` of audio (2 ms by default), at most
195    /// 32 packets, and the packets in flight never reach 256 (255 at most):
196    /// when the configured depth would, that cap wins and less is queued.
197    pub bus_queue_ms: u32,
198    /// How many isochronous transfers are in flight at once. 2 to 16,
199    /// default 8. See [`bus_queue_ms`](Self::bus_queue_ms).
200    pub transfers_in_flight: u32,
201    /// Optional target for one transfer in microseconds. 125 to 32,000.
202    /// When set, the worker rounds down to whole USB service intervals (at
203    /// least one), derives the slot count from the bus queue target and uses
204    /// `transfers_in_flight` as a ceiling. Keep two slots even when one service
205    /// interval exceeds the requested period. None uses the fixed slot count.
206    pub transfer_period_us: Option<u32>,
207    /// Cancel the transfers already on the bus when the stream is flushed, so
208    /// the audio of the old position is not heard after a seek or a track
209    /// change. The output thread cancels them, waits for the host controller to
210    /// hand every one back, and resumes with wire-correct silence until the
211    /// ring has refilled. Cancelled transfers are not lost audio, not
212    /// underruns, do not clear bit-perfect, and their music is not counted as
213    /// played. `pause` never cancels. `false` lets the queue play out (up to
214    /// `bus_queue_ms`). Default `true`.
215    pub cancel_in_flight_on_flush: bool,
216    /// What `Dac::open` does with the DAC's hardware volume before any stream
217    /// can start. Default: lower it to at most -40 dB.
218    pub startup_volume: StartupVolume,
219    /// `open_stream` fails with [`Error::VolumeUnavailable`] when the DAC has no
220    /// usable hardware volume control, so the host can ask the user to allow
221    /// fixed-level output and open the DAC again with this off. `negotiate` and
222    /// `capabilities` work either way. Default `true`.
223    pub require_hardware_volume: bool,
224}
225
226impl Default for DacConfig {
227    fn default() -> Self {
228        Self {
229            buffer_target_ms: 250,
230            buffer_capacity_ms: 500,
231            start_threshold_ms: 100,
232            processing_buffer_target_ms: 100,
233            require_verified_rate: true,
234            clock_settle_delay_ms: None,
235            dsd_big_endian: None,
236            dsd_subslot: None,
237            padded_24bit: None,
238            quirks: Vec::new(),
239            quirk_policy: crate::quirk::QuirkPolicy::VerifiedOnly,
240            allow_unsynchronized_async: false,
241            async_fallback_policy: AsyncFallbackPolicy::default(),
242            clock_readback_policy: ClockReadbackPolicy::default(),
243            adaptive_queue: true,
244            disable_feedback: false,
245            feedback_smoothing: FeedbackSmoothing::Direct,
246            capture_feedback_trace: false,
247            realtime_priority: true,
248            hand_back: HandBack::default(),
249            bus_queue_ms: DEFAULT_BUS_QUEUE_MS,
250            transfers_in_flight: DEFAULT_TRANSFERS_IN_FLIGHT,
251            transfer_period_us: None,
252            cancel_in_flight_on_flush: true,
253            startup_volume: StartupVolume::default(),
254            require_hardware_volume: true,
255        }
256    }
257}
258
259/// Starting points for USB bus queue tuning. Queue times are approximate and
260/// depend on the endpoint's service interval. The software ring is independent.
261#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
262pub enum UsbQueueProfile {
263    /// Shorter USB queue and smaller transfers for interactive playback.
264    LowLatency,
265    /// The default queue and transfer count.
266    #[default]
267    Balanced,
268    /// Same target queue as Balanced with fewer, larger transfers and wakeups.
269    LowCpu,
270}
271
272impl DacConfig {
273    /// Apply the USB queue profile. All other session settings are retained.
274    pub fn with_usb_queue_profile(mut self, profile: UsbQueueProfile) -> Self {
275        (
276            self.bus_queue_ms,
277            self.transfers_in_flight,
278            self.transfer_period_us,
279        ) = match profile {
280            UsbQueueProfile::LowLatency => (8, 8, Some(1_000)),
281            UsbQueueProfile::Balanced => (DEFAULT_BUS_QUEUE_MS, DEFAULT_TRANSFERS_IN_FLIGHT, None),
282            UsbQueueProfile::LowCpu => (16, 4, None),
283        };
284        self
285    }
286
287    /// Checks the combination of values.
288    pub fn validate(&self) -> Result<()> {
289        let bad = |message: &str| Err(Error::InvalidArgument(message.to_string()));
290        if self.buffer_capacity_ms == 0 || self.buffer_capacity_ms > 10_000 {
291            return bad("buffer_capacity_ms must be between 1 and 10000");
292        }
293        if self.buffer_target_ms == 0 || self.buffer_target_ms > self.buffer_capacity_ms {
294            return bad("buffer_target_ms must be between 1 and buffer_capacity_ms");
295        }
296        if self.start_threshold_ms == 0 {
297            return bad("start_threshold_ms must be at least 1");
298        }
299        if self.processing_buffer_target_ms == 0
300            || self.processing_buffer_target_ms > self.buffer_capacity_ms
301        {
302            return bad("processing_buffer_target_ms must be between 1 and buffer_capacity_ms");
303        }
304        if let Some(subslot) = self.dsd_subslot {
305            if !matches!(subslot, 1 | 2 | 4) {
306                return bad("dsd_subslot must be 1, 2 or 4");
307            }
308        }
309        if let StartupVolume::Attenuate { max_db } = self.startup_volume {
310            if !max_db.is_finite() || !(-128.0..=0.0).contains(&max_db) {
311                return bad("startup_volume max_db must be a level between -128 and 0 dB");
312            }
313        }
314        if !(4..=64).contains(&self.bus_queue_ms) {
315            return bad("bus_queue_ms must be between 4 and 64");
316        }
317        if !(2..=16).contains(&self.transfers_in_flight) {
318            return bad("transfers_in_flight must be between 2 and 16");
319        }
320        if self
321            .transfer_period_us
322            .is_some_and(|period| !(125..=32_000).contains(&period))
323        {
324            return bad("transfer_period_us must be between 125 and 32000");
325        }
326        Ok(())
327    }
328}
329
330#[cfg(test)]
331mod tests {
332    use super::*;
333
334    #[test]
335    fn defaults_are_the_values_the_transport_was_tuned_with() {
336        let config = DacConfig::default();
337        assert_eq!(config.buffer_target_ms, 250);
338        assert_eq!(config.buffer_capacity_ms, 500);
339        assert_eq!(config.start_threshold_ms, 100);
340        assert_eq!(config.processing_buffer_target_ms, 100);
341        assert!(config.require_verified_rate);
342        assert!(config.realtime_priority);
343        assert_eq!(config.feedback_smoothing, FeedbackSmoothing::Direct);
344        assert!(!config.allow_unsynchronized_async);
345        assert_eq!(config.hand_back, HandBack::RestoreOriginal);
346        assert_eq!(config.bus_queue_ms, 16);
347        assert_eq!(config.transfers_in_flight, 8);
348        assert!(config.cancel_in_flight_on_flush);
349        assert_eq!(
350            config.startup_volume,
351            StartupVolume::Attenuate { max_db: -40.0 }
352        );
353        assert!(config.require_hardware_volume);
354        config.validate().unwrap();
355    }
356
357    #[test]
358    fn validation_rejects_inconsistent_depths() {
359        let config = DacConfig {
360            buffer_target_ms: 600,
361            ..DacConfig::default()
362        };
363        assert!(matches!(config.validate(), Err(Error::InvalidArgument(_))));
364        let config = DacConfig {
365            dsd_subslot: Some(3),
366            ..DacConfig::default()
367        };
368        assert!(matches!(config.validate(), Err(Error::InvalidArgument(_))));
369        let config = DacConfig {
370            buffer_capacity_ms: 0,
371            ..DacConfig::default()
372        };
373        assert!(config.validate().is_err());
374    }
375
376    #[test]
377    fn the_startup_ceiling_must_be_a_level_a_dac_can_have() {
378        for (startup_volume, ok) in [
379            (StartupVolume::Keep, true),
380            (StartupVolume::Attenuate { max_db: -40.0 }, true),
381            (StartupVolume::Attenuate { max_db: 0.0 }, true),
382            (StartupVolume::Attenuate { max_db: -128.0 }, true),
383            (StartupVolume::Attenuate { max_db: 3.0 }, false),
384            (StartupVolume::Attenuate { max_db: -200.0 }, false),
385            (StartupVolume::Attenuate { max_db: f64::NAN }, false),
386            (
387                StartupVolume::Attenuate {
388                    max_db: f64::NEG_INFINITY,
389                },
390                false,
391            ),
392        ] {
393            let config = DacConfig {
394                startup_volume,
395                ..DacConfig::default()
396            };
397            assert_eq!(config.validate().is_ok(), ok, "{startup_volume:?}");
398        }
399        let error = DacConfig {
400            startup_volume: StartupVolume::Attenuate { max_db: 6.0 },
401            ..DacConfig::default()
402        }
403        .validate()
404        .unwrap_err();
405        assert!(matches!(&error, Error::InvalidArgument(message) if message.contains("max_db")));
406    }
407
408    #[test]
409    fn the_bus_queue_is_validated_at_both_ends_of_its_range() {
410        for (bus_queue_ms, ok) in [
411            (0, false),
412            (3, false),
413            (4, true),
414            (16, true),
415            (64, true),
416            (65, false),
417        ] {
418            let config = DacConfig {
419                bus_queue_ms,
420                ..DacConfig::default()
421            };
422            assert_eq!(config.validate().is_ok(), ok, "bus_queue_ms={bus_queue_ms}");
423        }
424        for (transfers_in_flight, ok) in [
425            (0, false),
426            (1, false),
427            (2, true),
428            (8, true),
429            (16, true),
430            (17, false),
431        ] {
432            let config = DacConfig {
433                transfers_in_flight,
434                ..DacConfig::default()
435            };
436            assert_eq!(
437                config.validate().is_ok(),
438                ok,
439                "transfers_in_flight={transfers_in_flight}"
440            );
441        }
442        let error = DacConfig {
443            bus_queue_ms: 3,
444            ..DacConfig::default()
445        }
446        .validate()
447        .unwrap_err();
448        assert!(
449            matches!(&error, Error::InvalidArgument(message) if message.contains("bus_queue_ms"))
450        );
451    }
452}