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 by up to two slots per loss batch and shrink one
175    /// slot after a quiet period, bounded by 64 ms and 255 packets.
176    /// Default geometry reaches at most 30 ms at 125 µs intervals, 32 ms otherwise.
177    pub adaptive_queue: bool,
178    /// Disable explicit and implicit feedback for diagnosis. Default `false`.
179    /// Asynchronous nominal playback still requires `allow_unsynchronized_async`.
180    pub disable_feedback: bool,
181    /// Explicit feedback timing policy. Direct by default; implicit cadence
182    /// vectors and nominal pacing are unaffected. Applied when a stream opens.
183    pub feedback_smoothing: FeedbackSmoothing,
184    /// Retain a bounded USB feedback support trace, including raw explicit
185    /// feedback bytes. Ask the listener to enable it before opening a session.
186    pub capture_feedback_trace: bool,
187    /// Ask for `SCHED_FIFO` (nice -16 as a fallback) on the output thread.
188    /// Android only; ignored elsewhere. Default `true`.
189    pub realtime_priority: bool,
190    /// What to do with the hardware volume level on close.
191    pub hand_back: HandBack,
192    /// How much audio, in milliseconds, is kept queued on the USB bus: the
193    /// transfers in flight together carry about this much. The same for every
194    /// service interval and encoding. It is what a pause or a flush still plays
195    /// out, and the headroom against a late output thread. 4 to 64, default 16. A transfer carries
196    /// `bus_queue_ms / transfers_in_flight` of audio (2 ms by default), at most
197    /// 32 packets, and the packets in flight never reach 256 (255 at most):
198    /// when the configured depth would, that cap wins and less is queued.
199    pub bus_queue_ms: u32,
200    /// How many isochronous transfers are in flight at once. 2 to 16,
201    /// default 8. See [`bus_queue_ms`](Self::bus_queue_ms).
202    pub transfers_in_flight: u32,
203    /// Optional target for one transfer in microseconds. 125 to 32,000.
204    /// When set, the worker rounds down to whole USB service intervals (at
205    /// least one), derives the slot count from the bus queue target and uses
206    /// `transfers_in_flight` as a ceiling. Keep two slots even when one service
207    /// interval exceeds the requested period. None uses the fixed slot count.
208    pub transfer_period_us: Option<u32>,
209    /// Cancel the transfers already on the bus when the stream is flushed, so
210    /// the audio of the old position is not heard after a seek or a track
211    /// change. The output thread cancels them, waits for the host controller to
212    /// hand every one back, and resumes with wire-correct silence until the
213    /// ring has refilled. Cancelled transfers are not lost audio, not
214    /// underruns, do not clear bit-perfect, and their music is not counted as
215    /// played. `pause` never cancels. `false` lets the queue play out (up to
216    /// `bus_queue_ms`). Default `true`.
217    pub cancel_in_flight_on_flush: bool,
218    /// What `Dac::open` does with the DAC's hardware volume before any stream
219    /// can start. Default: lower it to at most -40 dB.
220    pub startup_volume: StartupVolume,
221    /// `open_stream` fails with [`Error::VolumeUnavailable`] when the DAC has no
222    /// usable hardware volume control, so the host can ask the user to allow
223    /// fixed-level output and open the DAC again with this off. `negotiate` and
224    /// `capabilities` work either way. Default `true`.
225    pub require_hardware_volume: bool,
226}
227
228impl Default for DacConfig {
229    fn default() -> Self {
230        Self {
231            buffer_target_ms: 250,
232            buffer_capacity_ms: 500,
233            start_threshold_ms: 100,
234            processing_buffer_target_ms: 100,
235            require_verified_rate: true,
236            clock_settle_delay_ms: None,
237            dsd_big_endian: None,
238            dsd_subslot: None,
239            padded_24bit: None,
240            quirks: Vec::new(),
241            quirk_policy: crate::quirk::QuirkPolicy::VerifiedOnly,
242            allow_unsynchronized_async: false,
243            async_fallback_policy: AsyncFallbackPolicy::default(),
244            clock_readback_policy: ClockReadbackPolicy::default(),
245            adaptive_queue: true,
246            disable_feedback: false,
247            feedback_smoothing: FeedbackSmoothing::Direct,
248            capture_feedback_trace: false,
249            realtime_priority: true,
250            hand_back: HandBack::default(),
251            bus_queue_ms: DEFAULT_BUS_QUEUE_MS,
252            transfers_in_flight: DEFAULT_TRANSFERS_IN_FLIGHT,
253            transfer_period_us: None,
254            cancel_in_flight_on_flush: true,
255            startup_volume: StartupVolume::default(),
256            require_hardware_volume: true,
257        }
258    }
259}
260
261/// Starting points for USB bus queue tuning. Queue times are approximate and
262/// depend on the endpoint's service interval. The software ring is independent.
263#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
264pub enum UsbQueueProfile {
265    /// Shorter USB queue and smaller transfers for interactive playback.
266    LowLatency,
267    /// The default queue and transfer count.
268    #[default]
269    Balanced,
270    /// Same target queue as Balanced with fewer, larger transfers and wakeups.
271    LowCpu,
272}
273
274impl DacConfig {
275    /// Apply the USB queue profile. All other session settings are retained.
276    pub fn with_usb_queue_profile(mut self, profile: UsbQueueProfile) -> Self {
277        (
278            self.bus_queue_ms,
279            self.transfers_in_flight,
280            self.transfer_period_us,
281        ) = match profile {
282            UsbQueueProfile::LowLatency => (8, 8, Some(1_000)),
283            UsbQueueProfile::Balanced => (DEFAULT_BUS_QUEUE_MS, DEFAULT_TRANSFERS_IN_FLIGHT, None),
284            UsbQueueProfile::LowCpu => (16, 4, None),
285        };
286        self
287    }
288
289    /// Checks the combination of values.
290    pub fn validate(&self) -> Result<()> {
291        let bad = |message: &str| Err(Error::InvalidArgument(message.to_string()));
292        if self.buffer_capacity_ms == 0 || self.buffer_capacity_ms > 10_000 {
293            return bad("buffer_capacity_ms must be between 1 and 10000");
294        }
295        if self.buffer_target_ms == 0 || self.buffer_target_ms > self.buffer_capacity_ms {
296            return bad("buffer_target_ms must be between 1 and buffer_capacity_ms");
297        }
298        if self.start_threshold_ms == 0 {
299            return bad("start_threshold_ms must be at least 1");
300        }
301        if self.processing_buffer_target_ms == 0
302            || self.processing_buffer_target_ms > self.buffer_capacity_ms
303        {
304            return bad("processing_buffer_target_ms must be between 1 and buffer_capacity_ms");
305        }
306        if let Some(subslot) = self.dsd_subslot {
307            if !matches!(subslot, 1 | 2 | 4) {
308                return bad("dsd_subslot must be 1, 2 or 4");
309            }
310        }
311        if let StartupVolume::Attenuate { max_db } = self.startup_volume {
312            if !max_db.is_finite() || !(-128.0..=0.0).contains(&max_db) {
313                return bad("startup_volume max_db must be a level between -128 and 0 dB");
314            }
315        }
316        if !(4..=64).contains(&self.bus_queue_ms) {
317            return bad("bus_queue_ms must be between 4 and 64");
318        }
319        if !(2..=16).contains(&self.transfers_in_flight) {
320            return bad("transfers_in_flight must be between 2 and 16");
321        }
322        if self
323            .transfer_period_us
324            .is_some_and(|period| !(125..=32_000).contains(&period))
325        {
326            return bad("transfer_period_us must be between 125 and 32000");
327        }
328        Ok(())
329    }
330}
331
332#[cfg(test)]
333mod tests {
334    use super::*;
335
336    #[test]
337    fn defaults_are_the_values_the_transport_was_tuned_with() {
338        let config = DacConfig::default();
339        assert_eq!(config.buffer_target_ms, 250);
340        assert_eq!(config.buffer_capacity_ms, 500);
341        assert_eq!(config.start_threshold_ms, 100);
342        assert_eq!(config.processing_buffer_target_ms, 100);
343        assert!(config.require_verified_rate);
344        assert!(config.realtime_priority);
345        assert_eq!(config.feedback_smoothing, FeedbackSmoothing::Direct);
346        assert!(!config.allow_unsynchronized_async);
347        assert_eq!(config.hand_back, HandBack::RestoreOriginal);
348        assert_eq!(config.bus_queue_ms, 16);
349        assert_eq!(config.transfers_in_flight, 8);
350        assert!(config.cancel_in_flight_on_flush);
351        assert_eq!(
352            config.startup_volume,
353            StartupVolume::Attenuate { max_db: -40.0 }
354        );
355        assert!(config.require_hardware_volume);
356        config.validate().unwrap();
357    }
358
359    #[test]
360    fn validation_rejects_inconsistent_depths() {
361        let config = DacConfig {
362            buffer_target_ms: 600,
363            ..DacConfig::default()
364        };
365        assert!(matches!(config.validate(), Err(Error::InvalidArgument(_))));
366        let config = DacConfig {
367            dsd_subslot: Some(3),
368            ..DacConfig::default()
369        };
370        assert!(matches!(config.validate(), Err(Error::InvalidArgument(_))));
371        let config = DacConfig {
372            buffer_capacity_ms: 0,
373            ..DacConfig::default()
374        };
375        assert!(config.validate().is_err());
376    }
377
378    #[test]
379    fn the_startup_ceiling_must_be_a_level_a_dac_can_have() {
380        for (startup_volume, ok) in [
381            (StartupVolume::Keep, true),
382            (StartupVolume::Attenuate { max_db: -40.0 }, true),
383            (StartupVolume::Attenuate { max_db: 0.0 }, true),
384            (StartupVolume::Attenuate { max_db: -128.0 }, true),
385            (StartupVolume::Attenuate { max_db: 3.0 }, false),
386            (StartupVolume::Attenuate { max_db: -200.0 }, false),
387            (StartupVolume::Attenuate { max_db: f64::NAN }, false),
388            (
389                StartupVolume::Attenuate {
390                    max_db: f64::NEG_INFINITY,
391                },
392                false,
393            ),
394        ] {
395            let config = DacConfig {
396                startup_volume,
397                ..DacConfig::default()
398            };
399            assert_eq!(config.validate().is_ok(), ok, "{startup_volume:?}");
400        }
401        let error = DacConfig {
402            startup_volume: StartupVolume::Attenuate { max_db: 6.0 },
403            ..DacConfig::default()
404        }
405        .validate()
406        .unwrap_err();
407        assert!(matches!(&error, Error::InvalidArgument(message) if message.contains("max_db")));
408    }
409
410    #[test]
411    fn the_bus_queue_is_validated_at_both_ends_of_its_range() {
412        for (bus_queue_ms, ok) in [
413            (0, false),
414            (3, false),
415            (4, true),
416            (16, true),
417            (64, true),
418            (65, false),
419        ] {
420            let config = DacConfig {
421                bus_queue_ms,
422                ..DacConfig::default()
423            };
424            assert_eq!(config.validate().is_ok(), ok, "bus_queue_ms={bus_queue_ms}");
425        }
426        for (transfers_in_flight, ok) in [
427            (0, false),
428            (1, false),
429            (2, true),
430            (8, true),
431            (16, true),
432            (17, false),
433        ] {
434            let config = DacConfig {
435                transfers_in_flight,
436                ..DacConfig::default()
437            };
438            assert_eq!(
439                config.validate().is_ok(),
440                ok,
441                "transfers_in_flight={transfers_in_flight}"
442            );
443        }
444        let error = DacConfig {
445            bus_queue_ms: 3,
446            ..DacConfig::default()
447        }
448        .validate()
449        .unwrap_err();
450        assert!(
451            matches!(&error, Error::InvalidArgument(message) if message.contains("bus_queue_ms"))
452        );
453    }
454}