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 fn ensure_open(&self) -> Result<()> {
94 self.shared.ensure_open()
95 }
96
97 /// The writable range, or [`Error::Control`] if the control disappeared
98 /// (for example the active stream moved to another terminal).
99 pub fn range(&self) -> Result<VolumeRange> {
100 self.ensure_open()?;
101 transport::volume_hw::hardware_volume_range()
102 .ok_or_else(|| Error::Control("the DAC has no usable volume control".into()))
103 }
104
105 /// Reads the live level from the device.
106 pub fn get(&self) -> Result<VolumeState> {
107 self.ensure_open()?;
108 let before = transport::volume_hw::cached_volume_state();
109 let state = self.finish(transport::volume_hw::read_volume_state())?;
110 if before != Some(state) {
111 self.shared.events.emit_dac(DacEvent::VolumeChanged(state));
112 }
113 Ok(state)
114 }
115
116 /// Sets the level in dB. The value is clamped to the range and snapped to
117 /// the nearest step the DAC supports (a tie goes to the quieter one). Returns
118 /// the level read back.
119 pub fn set_db(&self, db: f64) -> Result<VolumeState> {
120 self.ensure_open()?;
121 if !db.is_finite() {
122 return Err(Error::InvalidArgument("volume must be finite".into()));
123 }
124 let state = self.finish(transport::volume_hw::write_volume_db(db))?;
125 self.shared.events.emit_dac(DacEvent::VolumeChanged(state));
126 Ok(state)
127 }
128
129 /// Sets the level on the 0..1 curve (see [`VolumeState::fraction`]). The
130 /// exact inverse of the read-back mapping: feeding a read-back fraction
131 /// back in reproduces the same step.
132 pub fn set_fraction(&self, fraction: f64) -> Result<VolumeState> {
133 self.ensure_open()?;
134 if !fraction.is_finite() {
135 return Err(Error::InvalidArgument("volume must be finite".into()));
136 }
137 let state = self.finish(transport::volume_hw::write_volume_fraction(fraction))?;
138 self.shared.events.emit_dac(DacEvent::VolumeChanged(state));
139 Ok(state)
140 }
141
142 /// Moves the level up (`direction > 0`) or down (`direction < 0`) by
143 /// `1/steps` of the 0..1 curve, always by at least one DAC step.
144 /// `steps == 0` selects [`DEFAULT_VOLUME_STEPS`]. A direction of 0 only
145 /// reads the level.
146 pub fn step(&self, direction: i8, steps: u8) -> Result<VolumeState> {
147 self.ensure_open()?;
148 let steps = if steps == 0 { DEFAULT_VOLUME_STEPS } else { steps };
149 let state = self.finish(transport::volume_hw::step_volume(direction, steps))?;
150 self.shared.events.emit_dac(DacEvent::VolumeChanged(state));
151 Ok(state)
152 }
153
154 /// Sets the master mute. [`Error::Control`] if the DAC has no writable
155 /// mute or the readback disagrees.
156 pub fn set_mute(&self, muted: bool) -> Result<VolumeState> {
157 self.ensure_open()?;
158 let state = self.finish(transport::volume_hw::write_mute(muted))?;
159 self.shared.events.emit_dac(DacEvent::VolumeChanged(state));
160 Ok(state)
161 }
162
163 /// What the library did with the DAC's level when it was opened, before any
164 /// stream could start: the level each channel had, the level it has now and
165 /// the limit a host should not restore above. See [`StartupVolumeReport`].
166 ///
167 /// On connect a host reads this, then restores the level it remembers for
168 /// this DAC capped by `limit_db`, or leaves the attenuated level.
169 pub fn startup(&self) -> StartupVolumeReport {
170 transport::volume_hw::startup_report().unwrap_or_else(|| {
171 // Not reachable through `Dac::volume`: a control is only installed
172 // together with its start-up step.
173 StartupVolumeReport {
174 original_db: Vec::new(),
175 applied_db: Vec::new(),
176 limit_db: 0.0,
177 attenuated: false,
178 clamped_to_minimum: false,
179 max_db: None,
180 }
181 })
182 }
183
184 /// The level the DAC had before the library first wrote to it, in dB, if
185 /// it was recorded (all channels agreed).
186 pub fn original_db(&self) -> Option<f64> {
187 transport::volume_hw::original_volume_db()
188 }
189
190 /// Writes the original level back now and ends the record. `Ok(false)` if
191 /// there was nothing to restore or it was already in place.
192 pub fn hand_back(&self) -> Result<bool> {
193 self.ensure_open()?;
194 transport::volume_hw::hand_back_original_volume().or_else_control()
195 }
196
197 fn finish(&self, result: std::result::Result<VolumeState, String>) -> Result<VolumeState> {
198 match result {
199 Ok(state) => Ok(state),
200 Err(message) => {
201 let error = if crate::error::is_device_gone(&message) {
202 Error::DeviceLost
203 } else {
204 Error::Control(message)
205 };
206 if error == Error::DeviceLost {
207 self.shared.events.emit_dac(DacEvent::DeviceLost);
208 }
209 Err(error)
210 }
211 }
212 }
213}
214
215trait OrElseControl<T> {
216 fn or_else_control(self) -> Result<T>;
217}
218
219impl<T> OrElseControl<T> for std::result::Result<T, String> {
220 fn or_else_control(self) -> Result<T> {
221 crate::error::OrControl::or_control(self)
222 }
223}
224
225/// dB for a raw UAC volume value.
226pub(crate) fn raw_to_db(raw: i16) -> f64 {
227 f64::from(raw) / RAW_PER_DB
228}
229
230#[cfg(test)]
231mod tests {
232 use super::*;
233
234 #[test]
235 fn raw_units_are_256ths_of_a_db() {
236 assert_eq!(raw_to_db(-256), -1.0);
237 assert_eq!(raw_to_db(-12800), -50.0);
238 assert_eq!(raw_to_db(i16::MIN), -128.0);
239 }
240}