1use crate::dac::DacShared;
10use crate::error::{Error, Result};
11use crate::events::DacEvent;
12use crate::transport;
13use std::sync::Arc;
14
15pub(crate) const RAW_PER_DB: f64 = 256.0;
17
18#[derive(Debug, Clone, Copy, PartialEq)]
20pub struct VolumeRange {
21 pub min_db: f64,
22 pub max_db: f64,
23 pub res_db: f64,
26}
27
28#[derive(Debug, Clone, Copy, PartialEq)]
30pub struct VolumeState {
31 pub db: f64,
33 pub fraction: f64,
37 pub muted: Option<bool>,
39}
40
41#[derive(Debug, Clone, PartialEq)]
47#[non_exhaustive]
48pub struct StartupVolumeReport {
49 pub original_db: Vec<f64>,
52 pub applied_db: Vec<f64>,
56 pub limit_db: f64,
60 pub attenuated: bool,
62 pub clamped_to_minimum: bool,
65 pub max_db: Option<f64>,
67}
68
69pub const DEFAULT_VOLUME_STEPS: u8 = 16;
71
72#[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 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 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 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 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 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 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 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 pub fn startup(&self) -> StartupVolumeReport {
197 let _scope = self.shared.context.enter();
198 transport::volume_hw::startup_report().unwrap_or_else(|| {
199 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 pub fn original_db(&self) -> Option<f64> {
215 let _scope = self.shared.context.enter();
216 transport::volume_hw::original_volume_db()
217 }
218
219 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
256pub(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}