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