Skip to main content

usbdac_core/
volume.rs

1//! Hardware volume: the DAC's Feature Unit.
2//!
3//! Volume belongs to the DAC, not to the sample path: the library never scales
4//! samples for volume unless software gain is explicitly enabled, which ends
5//! bit-perfect output. A [`VolumeControl`] reads and writes the Feature Unit's
6//! volume and mute controls over the control pipe, so it works with or without
7//! a stream while the device is held.
8
9use crate::dac::DacShared;
10use crate::error::{Error, Result};
11use crate::events::DacEvent;
12use crate::transport;
13use std::sync::Arc;
14
15/// UAC volume values are signed 1/256 dB units.
16pub(crate) const RAW_PER_DB: f64 = 256.0;
17
18/// The DAC's volume range in decibels.
19#[derive(Debug, Clone, Copy, PartialEq)]
20pub struct VolumeRange {
21    pub min_db: f64,
22    pub max_db: f64,
23    /// The finest step the DAC accepts (the smallest resolution over its
24    /// sub-ranges).
25    pub res_db: f64,
26}
27
28/// The DAC's volume as read back from the device.
29#[derive(Debug, Clone, Copy, PartialEq)]
30pub struct VolumeState {
31    /// Level in dB.
32    pub db: f64,
33    /// Position on the 0..1 curve: 0 is the DAC's minimum; anything above 0
34    /// spans `max(min, -80 dB)` to the maximum linearly in dB. A level below
35    /// -80 dB reads as 0.0 here but keeps its exact `db`.
36    pub fraction: f64,
37    /// `None` when the DAC has no writable mute, or its readback failed.
38    pub muted: Option<bool>,
39}
40
41/// What [`Dac::open`](crate::Dac::open) did with the DAC's level before any
42/// stream could start (see [`StartupVolume`](crate::StartupVolume)).
43///
44/// The lists hold one entry per controlled channel, in channel order (a single
45/// entry for a DAC with one master control).
46#[derive(Debug, Clone, PartialEq)]
47#[non_exhaustive]
48pub struct StartupVolumeReport {
49    /// The level each channel had before the library first touched it, in dB.
50    /// What [`VolumeControl::hand_back`] restores.
51    pub original_db: Vec<f64>,
52    /// The level each channel has now that the start-up step is done, in dB.
53    /// Equal to `original_db` when nothing needed lowering, and with
54    /// `StartupVolume::Keep`.
55    pub applied_db: Vec<f64>,
56    /// The quietest original channel, in dB. A host that restores a level it
57    /// remembered for this DAC should not go above it without the user's
58    /// action: that was how loud the DAC itself was when it connected.
59    pub limit_db: f64,
60    /// `applied_db` is below `original_db` on some channel.
61    pub attenuated: bool,
62    /// The ceiling was below the DAC's minimum, so the channels went to the
63    /// minimum instead.
64    pub clamped_to_minimum: bool,
65    /// The ceiling that was asked for; `None` for `StartupVolume::Keep`.
66    pub max_db: Option<f64>,
67}
68
69/// Default number of steps for [`VolumeControl::step`].
70pub const DEFAULT_VOLUME_STEPS: u8 = 16;
71
72/// Handle to the DAC's hardware volume control.
73///
74/// Cheap to clone. Calls serialize with each other and with the library's own
75/// volume I/O. Writes are verified by reading the level back; a failed
76/// multi-channel write restores the channels already written.
77#[derive(Clone)]
78pub struct VolumeControl {
79    shared: Arc<DacShared>,
80}
81
82impl std::fmt::Debug for VolumeControl {
83    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84        f.debug_struct("VolumeControl").finish_non_exhaustive()
85    }
86}
87
88impl VolumeControl {
89    pub(crate) fn new(shared: Arc<DacShared>) -> Self {
90        Self { shared }
91    }
92
93    /// Create a bounded, ordered worker for control I/O. Keep one controller per
94    /// device; requests never block the submitting or async executor thread.
95    /// Dropping a request does not cancel a write already accepted by the worker.
96    pub fn nonblocking(&self) -> Result<crate::AsyncVolumeControl> {
97        self.ensure_open()?;
98        crate::async_volume::AsyncVolumeControl::new(self.clone())
99    }
100
101    fn ensure_open(&self) -> Result<()> {
102        self.shared.ensure_open()
103    }
104
105    /// The writable range, or [`Error::Control`] if the control disappeared
106    /// (for example the active stream moved to another terminal).
107    pub fn range(&self) -> Result<VolumeRange> {
108        let _control = self.shared.control_guard.lock();
109        let _scope = self.shared.enter()?;
110        self.ensure_open()?;
111        transport::volume_hw::hardware_volume_range()
112            .ok_or_else(|| Error::Control("the DAC has no usable volume control".into()))
113    }
114
115    /// Reads the live level from the device.
116    pub fn get(&self) -> Result<VolumeState> {
117        let _control = self.shared.control_guard.lock();
118        let _scope = self.shared.enter()?;
119        self.ensure_open()?;
120        let before = transport::volume_hw::cached_volume_state();
121        let state = self.finish(transport::volume_hw::read_volume_state())?;
122        if before != Some(state) {
123            self.shared.events.emit_dac(DacEvent::VolumeChanged(state));
124        }
125        Ok(state)
126    }
127
128    /// Sets the level in dB (`NEG_INFINITY` selects the verified raw minimum).
129    /// The value is clamped to the range and snapped to
130    /// the nearest step the DAC supports (a tie goes to the quieter one). Returns
131    /// the level read back.
132    pub fn set_db(&self, db: f64) -> Result<VolumeState> {
133        let _control = self.shared.control_guard.lock();
134        let _scope = self.shared.enter()?;
135        self.ensure_open()?;
136        if db.is_nan() || db == f64::INFINITY {
137            return Err(Error::InvalidArgument(
138                "volume must be finite or negative infinity for silence".into(),
139            ));
140        }
141        let state = self.finish(transport::volume_hw::write_volume_db(db))?;
142        self.shared.events.emit_dac(DacEvent::VolumeChanged(state));
143        Ok(state)
144    }
145
146    /// Sets the level on the 0..1 curve (see [`VolumeState::fraction`]). The
147    /// exact inverse of the read-back mapping: feeding a read-back fraction
148    /// back in reproduces the same step.
149    pub fn set_fraction(&self, fraction: f64) -> Result<VolumeState> {
150        let _control = self.shared.control_guard.lock();
151        let _scope = self.shared.enter()?;
152        self.ensure_open()?;
153        if !fraction.is_finite() {
154            return Err(Error::InvalidArgument("volume must be finite".into()));
155        }
156        let state = self.finish(transport::volume_hw::write_volume_fraction(fraction))?;
157        self.shared.events.emit_dac(DacEvent::VolumeChanged(state));
158        Ok(state)
159    }
160
161    /// Moves the level up (`direction > 0`) or down (`direction < 0`) by
162    /// `1/steps` of the 0..1 curve, always by at least one DAC step.
163    /// `steps == 0` selects [`DEFAULT_VOLUME_STEPS`]. A direction of 0 only
164    /// reads the level.
165    pub fn step(&self, direction: i8, steps: u8) -> Result<VolumeState> {
166        let _control = self.shared.control_guard.lock();
167        let _scope = self.shared.enter()?;
168        self.ensure_open()?;
169        let steps = if steps == 0 {
170            DEFAULT_VOLUME_STEPS
171        } else {
172            steps
173        };
174        let state = self.finish(transport::volume_hw::step_volume(direction, steps))?;
175        self.shared.events.emit_dac(DacEvent::VolumeChanged(state));
176        Ok(state)
177    }
178
179    /// Sets the master mute. [`Error::Control`] if the DAC has no writable
180    /// mute or the readback disagrees.
181    pub fn set_mute(&self, muted: bool) -> Result<VolumeState> {
182        let _control = self.shared.control_guard.lock();
183        let _scope = self.shared.enter()?;
184        self.ensure_open()?;
185        let state = self.finish(transport::volume_hw::write_mute(muted))?;
186        self.shared.events.emit_dac(DacEvent::VolumeChanged(state));
187        Ok(state)
188    }
189
190    /// What the library did with the DAC's level when it was opened, before any
191    /// stream could start: the level each channel had, the level it has now and
192    /// the limit a host should not restore above. See [`StartupVolumeReport`].
193    ///
194    /// On connect a host reads this, then restores the level it remembers for
195    /// this DAC capped by `limit_db`, or leaves the attenuated level.
196    pub fn startup(&self) -> StartupVolumeReport {
197        let _scope = self.shared.context.enter();
198        transport::volume_hw::startup_report().unwrap_or_else(|| {
199            // Not reachable through `Dac::volume`: a control is only installed
200            // together with its start-up step.
201            StartupVolumeReport {
202                original_db: Vec::new(),
203                applied_db: Vec::new(),
204                limit_db: 0.0,
205                attenuated: false,
206                clamped_to_minimum: false,
207                max_db: None,
208            }
209        })
210    }
211
212    /// The level the DAC had before the library first wrote to it, in dB, if
213    /// it was recorded (all channels agreed).
214    pub fn original_db(&self) -> Option<f64> {
215        let _scope = self.shared.context.enter();
216        transport::volume_hw::original_volume_db()
217    }
218
219    /// Writes the original level back now and ends the record. `Ok(false)` if
220    /// there was nothing to restore or it was already in place.
221    pub fn hand_back(&self) -> Result<bool> {
222        let _control = self.shared.control_guard.lock();
223        let _scope = self.shared.enter()?;
224        self.ensure_open()?;
225        transport::volume_hw::hand_back_original_volume().or_else_control()
226    }
227
228    fn finish(&self, result: std::result::Result<VolumeState, String>) -> Result<VolumeState> {
229        match result {
230            Ok(state) => Ok(state),
231            Err(message) => {
232                let error = if crate::error::is_device_gone(&message) {
233                    Error::DeviceLost
234                } else {
235                    Error::Control(message)
236                };
237                if error == Error::DeviceLost {
238                    self.shared.events.emit_dac(DacEvent::DeviceLost);
239                }
240                Err(error)
241            }
242        }
243    }
244}
245
246trait OrElseControl<T> {
247    fn or_else_control(self) -> Result<T>;
248}
249
250impl<T> OrElseControl<T> for std::result::Result<T, String> {
251    fn or_else_control(self) -> Result<T> {
252        crate::error::OrControl::or_control(self)
253    }
254}
255
256/// dB for a raw UAC volume value.
257pub(crate) fn raw_to_db(raw: i16) -> f64 {
258    f64::from(raw) / RAW_PER_DB
259}
260
261#[cfg(test)]
262mod tests {
263    use super::*;
264
265    #[test]
266    fn raw_units_are_256ths_of_a_db() {
267        assert_eq!(raw_to_db(-256), -1.0);
268        assert_eq!(raw_to_db(-12800), -50.0);
269        assert_eq!(raw_to_db(i16::MIN), -128.0);
270    }
271}