use serde::{Deserialize, Serialize};
use std::{collections::BTreeMap, fmt, time::Duration};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct BusId(usize);
impl BusId {
pub const MASTER: Self = Self(0);
pub const MUSIC: Self = Self(1);
pub const SFX: Self = Self(2);
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AudioError(pub &'static str);
impl fmt::Display for AudioError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.0)
}
}
impl std::error::Error for AudioError {}
pub fn validate_gain(value: f32) -> Result<(), AudioError> {
if value.is_finite() && (0.0..=1.0).contains(&value) {
Ok(())
} else {
Err(AudioError("volume must be finite and in 0..=1"))
}
}
#[derive(Clone, Debug)]
pub struct GainFade {
start: f32,
target: f32,
elapsed: Duration,
duration: Duration,
}
impl GainFade {
pub fn new(start: f32, target: f32, duration: Duration) -> Result<Self, AudioError> {
validate_gain(start)?;
validate_gain(target)?;
Ok(Self {
start,
target,
elapsed: Duration::ZERO,
duration,
})
}
pub fn gain(&self) -> f32 {
if self.finished() {
return self.target;
}
let fraction = self.elapsed.as_secs_f64() / self.duration.as_secs_f64();
(f64::from(self.start) + f64::from(self.target - self.start) * fraction) as f32
}
pub fn advance(&mut self, delta: Duration) {
self.elapsed = self.elapsed.saturating_add(delta).min(self.duration);
}
pub fn finished(&self) -> bool {
self.elapsed >= self.duration
}
pub fn retarget(&mut self, target: f32, duration: Duration) -> Result<(), AudioError> {
*self = Self::new(self.gain(), target, duration)?;
Ok(())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct BusSettings {
pub volume: f32,
pub muted: bool,
}
impl Default for BusSettings {
fn default() -> Self {
Self {
volume: 1.0,
muted: false,
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct AudioSettings {
pub buses: BTreeMap<String, BusSettings>,
}
struct Bus {
name: String,
settings: BusSettings,
duck: GainFade,
}
pub struct AudioBuses {
buses: Vec<Bus>,
}
impl Default for AudioBuses {
fn default() -> Self {
let mut buses = Self { buses: Vec::new() };
for name in ["master", "music", "sfx"] {
buses.add(name).expect("default bus");
}
buses
}
}
impl AudioBuses {
pub fn find(&self, name: &str) -> Option<BusId> {
self.buses
.iter()
.position(|bus| bus.name == name)
.map(BusId)
}
pub fn add(&mut self, name: &str) -> Result<BusId, AudioError> {
if name.trim().is_empty() {
return Err(AudioError("bus name must not be empty"));
}
if let Some(id) = self.find(name) {
return Ok(id);
}
let id = BusId(self.buses.len());
self.buses.push(Bus {
name: name.into(),
settings: BusSettings::default(),
duck: GainFade::new(1.0, 1.0, Duration::ZERO)?,
});
Ok(id)
}
fn bus(&self, id: BusId) -> Result<&Bus, AudioError> {
self.buses
.get(id.0)
.ok_or(AudioError("bus does not belong to this mixer"))
}
fn bus_mut(&mut self, id: BusId) -> Result<&mut Bus, AudioError> {
self.buses
.get_mut(id.0)
.ok_or(AudioError("bus does not belong to this mixer"))
}
pub fn settings_for(&self, id: BusId) -> Result<BusSettings, AudioError> {
Ok(self.bus(id)?.settings)
}
pub fn set_volume(&mut self, id: BusId, volume: f32) -> Result<(), AudioError> {
validate_gain(volume)?;
self.bus_mut(id)?.settings.volume = volume;
Ok(())
}
pub fn set_muted(&mut self, id: BusId, muted: bool) -> Result<(), AudioError> {
self.bus_mut(id)?.settings.muted = muted;
Ok(())
}
pub fn duck(&mut self, id: BusId, gain: f32, duration: Duration) -> Result<(), AudioError> {
self.bus_mut(id)?.duck.retarget(gain, duration)
}
pub fn gain(&self, id: BusId) -> Result<f32, AudioError> {
let own = |bus: &Bus| {
if bus.settings.muted {
0.0
} else {
bus.settings.volume * bus.duck.gain()
}
};
let gain = own(self.bus(id)?);
Ok(if id == BusId::MASTER {
gain
} else {
gain * own(&self.buses[0])
})
}
pub fn advance(&mut self, delta: Duration) {
for bus in &mut self.buses {
bus.duck.advance(delta);
}
}
pub fn settings(&self) -> AudioSettings {
AudioSettings {
buses: self
.buses
.iter()
.map(|bus| (bus.name.clone(), bus.settings))
.collect(),
}
}
pub fn apply_settings(&mut self, settings: &AudioSettings) -> Result<(), AudioError> {
for (name, values) in &settings.buses {
if name.trim().is_empty() {
return Err(AudioError("bus name must not be empty"));
}
validate_gain(values.volume)?;
}
for (name, values) in &settings.buses {
let id = self.add(name)?;
self.bus_mut(id)?.settings = *values;
}
Ok(())
}
}
#[cfg(test)]
mod tests;