fader_master/core/src/volume.rs

219 lines
6.6 KiB
Rust

use thiserror::Error;
/// Why a scalar gain was rejected.
#[derive(Clone, Copy, Debug, Error, PartialEq)]
pub enum GainError {
/// NaN and infinities cannot represent observable audio state.
#[error("gain must be finite, found {0}")]
NonFinite(f64),
/// Negative amplitude is outside the domain.
#[error("gain must be non-negative, found {0}")]
Negative(f64),
}
/// Finite, non-negative linear amplitude gain.
///
/// `1.0` is unity and `0.0` is silence. Values above unity are representable
/// so external observations are not silently clamped; write paths apply their
/// configured ceiling separately.
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
pub struct Gain(f64);
impl Gain {
/// Silence.
pub const SILENCE: Self = Self(0.0);
/// Unity gain.
pub const UNITY: Self = Self(1.0);
/// Validates a linear amplitude value.
///
/// # Errors
///
/// Returns [`GainError`] for negative, NaN, or infinite values.
pub fn new(value: f64) -> Result<Self, GainError> {
if !value.is_finite() {
return Err(GainError::NonFinite(value));
}
if value < 0.0 {
return Err(GainError::Negative(value));
}
Ok(Self(value))
}
/// Returns the linear amplitude value.
#[must_use]
pub const fn get(self) -> f64 {
self.0
}
/// Returns whether this value represents silence.
#[must_use]
pub fn is_silent(self) -> bool {
self == Self::SILENCE
}
}
/// Why a vector of channel gains or a balance-preserving operation failed.
#[derive(Clone, Debug, Error, PartialEq)]
pub enum ChannelGainError {
/// A stream must expose at least one channel.
#[error("channel gain vector must not be empty")]
Empty,
/// The requested maximum exceeds the configured write ceiling.
#[error("target gain {target} exceeds write ceiling {ceiling}")]
AboveWriteCeiling {
/// Requested output maximum.
target: f64,
/// Configured maximum write gain.
ceiling: f64,
},
/// A calculated scalar failed gain validation.
#[error(transparent)]
InvalidGain(#[from] GainError),
}
/// Non-empty per-channel gain snapshot.
#[derive(Clone, Debug, PartialEq)]
pub struct ChannelGains(Vec<Gain>);
impl ChannelGains {
/// Constructs a non-empty channel vector.
///
/// # Errors
///
/// Returns [`ChannelGainError::Empty`] when no channels are provided.
pub fn new(channels: Vec<Gain>) -> Result<Self, ChannelGainError> {
if channels.is_empty() {
return Err(ChannelGainError::Empty);
}
Ok(Self(channels))
}
/// Returns the channel values.
#[must_use]
pub fn as_slice(&self) -> &[Gain] {
&self.0
}
/// Consumes the snapshot and returns its channel values.
#[must_use]
pub fn into_vec(self) -> Vec<Gain> {
self.0
}
/// Returns the loudest channel.
#[must_use]
pub fn maximum(&self) -> Gain {
self.0
.iter()
.copied()
.fold(Gain::SILENCE, |maximum, channel| {
if channel > maximum { channel } else { maximum }
})
}
/// Scales every channel so the loudest reaches `target`.
///
/// Existing balance is preserved. An all-silent vector has no balance to
/// preserve, so every channel is initialized to `target`.
///
/// # Errors
///
/// Returns [`ChannelGainError::AboveWriteCeiling`] when `target` exceeds
/// `write_ceiling`.
pub fn scaled_to(&self, target: Gain, write_ceiling: Gain) -> Result<Self, ChannelGainError> {
if target > write_ceiling {
return Err(ChannelGainError::AboveWriteCeiling {
target: target.get(),
ceiling: write_ceiling.get(),
});
}
let old_maximum = self.maximum();
if old_maximum.is_silent() {
return Ok(Self(vec![target; self.0.len()]));
}
let channels = self
.0
.iter()
.map(|channel| Gain::new((channel.get() / old_maximum.get()) * target.get()))
.collect::<Result<Vec<_>, _>>()?;
Ok(Self(channels))
}
}
#[cfg(test)]
mod tests {
use proptest::prelude::*;
use super::*;
fn gain(value: f64) -> Gain {
Gain::new(value).expect("test gain must be valid")
}
#[test]
fn rejects_non_finite_and_negative_gain() {
assert!(matches!(Gain::new(f64::NAN), Err(GainError::NonFinite(_))));
assert!(matches!(
Gain::new(f64::INFINITY),
Err(GainError::NonFinite(_))
));
assert_eq!(Gain::new(-0.01), Err(GainError::Negative(-0.01)));
assert_eq!(Gain::new(-0.0), Ok(Gain::SILENCE));
}
#[test]
fn initializes_silent_channels_equally() {
let channels = ChannelGains::new(vec![Gain::SILENCE, Gain::SILENCE])
.expect("non-empty channel vector");
let scaled = channels
.scaled_to(gain(0.75), Gain::UNITY)
.expect("target is below ceiling");
assert_eq!(scaled.as_slice(), &[gain(0.75), gain(0.75)]);
}
#[test]
fn rejects_writes_above_the_explicit_ceiling() {
let channels = ChannelGains::new(vec![Gain::UNITY]).expect("non-empty channel vector");
assert_eq!(
channels.scaled_to(gain(1.5), Gain::UNITY),
Err(ChannelGainError::AboveWriteCeiling {
target: 1.5,
ceiling: 1.0,
})
);
}
proptest! {
#[test]
fn valid_gain_round_trips(value in 0.0_f64..=32.0) {
let value = Gain::new(value).expect("generated gain is valid");
prop_assert!(value.get().is_finite());
prop_assert!(value.get() >= 0.0);
}
#[test]
fn scaling_preserves_balance(
left in 0.000_001_f64..=8.0,
right in 0.000_001_f64..=8.0,
target in 0.0_f64..=4.0,
) {
let original = ChannelGains::new(vec![gain(left), gain(right)])
.expect("generated vector is non-empty");
let scaled = original
.scaled_to(gain(target), gain(4.0))
.expect("generated target is within ceiling");
prop_assert!((scaled.maximum().get() - target).abs() <= f64::EPSILON * 8.0);
if target > 0.0 {
let original_ratio = left / right;
let scaled_ratio = scaled.as_slice()[0].get() / scaled.as_slice()[1].get();
prop_assert!((original_ratio - scaled_ratio).abs() <= original_ratio.abs() * 1e-12 + 1e-12);
}
}
}
}