1use serde::{Deserialize, Serialize};
4use std::{collections::BTreeMap, fmt, time::Duration};
5
6#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
8pub struct BusId(usize);
9impl BusId {
10 pub const MASTER: Self = Self(0);
12 pub const MUSIC: Self = Self(1);
14 pub const SFX: Self = Self(2);
16}
17
18#[derive(Clone, Debug, PartialEq, Eq)]
20pub struct AudioError(pub &'static str);
21impl fmt::Display for AudioError {
22 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23 f.write_str(self.0)
24 }
25}
26impl std::error::Error for AudioError {}
27
28pub fn validate_gain(value: f32) -> Result<(), AudioError> {
30 if value.is_finite() && (0.0..=1.0).contains(&value) {
31 Ok(())
32 } else {
33 Err(AudioError("volume must be finite and in 0..=1"))
34 }
35}
36
37#[derive(Clone, Debug)]
39pub struct GainFade {
40 start: f32,
41 target: f32,
42 elapsed: Duration,
43 duration: Duration,
44}
45impl GainFade {
46 pub fn new(start: f32, target: f32, duration: Duration) -> Result<Self, AudioError> {
48 validate_gain(start)?;
49 validate_gain(target)?;
50 Ok(Self {
51 start,
52 target,
53 elapsed: Duration::ZERO,
54 duration,
55 })
56 }
57 pub fn gain(&self) -> f32 {
59 if self.finished() {
60 return self.target;
61 }
62 let fraction = self.elapsed.as_secs_f64() / self.duration.as_secs_f64();
63 (f64::from(self.start) + f64::from(self.target - self.start) * fraction) as f32
64 }
65 pub fn advance(&mut self, delta: Duration) {
67 self.elapsed = self.elapsed.saturating_add(delta).min(self.duration);
68 }
69 pub fn finished(&self) -> bool {
71 self.elapsed >= self.duration
72 }
73 pub fn retarget(&mut self, target: f32, duration: Duration) -> Result<(), AudioError> {
75 *self = Self::new(self.gain(), target, duration)?;
76 Ok(())
77 }
78}
79
80#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
82pub struct BusSettings {
83 pub volume: f32,
85 pub muted: bool,
87}
88impl Default for BusSettings {
89 fn default() -> Self {
90 Self {
91 volume: 1.0,
92 muted: false,
93 }
94 }
95}
96#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
99pub struct AudioSettings {
100 pub buses: BTreeMap<String, BusSettings>,
102}
103struct Bus {
104 name: String,
105 settings: BusSettings,
106 duck: GainFade,
107}
108pub struct AudioBuses {
111 buses: Vec<Bus>,
112}
113impl Default for AudioBuses {
114 fn default() -> Self {
115 let mut buses = Self { buses: Vec::new() };
116 for name in ["master", "music", "sfx"] {
117 buses.add(name).expect("default bus");
118 }
119 buses
120 }
121}
122impl AudioBuses {
123 pub fn find(&self, name: &str) -> Option<BusId> {
125 self.buses
126 .iter()
127 .position(|bus| bus.name == name)
128 .map(BusId)
129 }
130 pub fn add(&mut self, name: &str) -> Result<BusId, AudioError> {
132 if name.trim().is_empty() {
133 return Err(AudioError("bus name must not be empty"));
134 }
135 if let Some(id) = self.find(name) {
136 return Ok(id);
137 }
138 let id = BusId(self.buses.len());
139 self.buses.push(Bus {
140 name: name.into(),
141 settings: BusSettings::default(),
142 duck: GainFade::new(1.0, 1.0, Duration::ZERO)?,
143 });
144 Ok(id)
145 }
146 fn bus(&self, id: BusId) -> Result<&Bus, AudioError> {
147 self.buses
148 .get(id.0)
149 .ok_or(AudioError("bus does not belong to this mixer"))
150 }
151 fn bus_mut(&mut self, id: BusId) -> Result<&mut Bus, AudioError> {
152 self.buses
153 .get_mut(id.0)
154 .ok_or(AudioError("bus does not belong to this mixer"))
155 }
156 pub fn settings_for(&self, id: BusId) -> Result<BusSettings, AudioError> {
158 Ok(self.bus(id)?.settings)
159 }
160 pub fn set_volume(&mut self, id: BusId, volume: f32) -> Result<(), AudioError> {
162 validate_gain(volume)?;
163 self.bus_mut(id)?.settings.volume = volume;
164 Ok(())
165 }
166 pub fn set_muted(&mut self, id: BusId, muted: bool) -> Result<(), AudioError> {
168 self.bus_mut(id)?.settings.muted = muted;
169 Ok(())
170 }
171 pub fn duck(&mut self, id: BusId, gain: f32, duration: Duration) -> Result<(), AudioError> {
174 self.bus_mut(id)?.duck.retarget(gain, duration)
175 }
176 pub fn gain(&self, id: BusId) -> Result<f32, AudioError> {
178 let own = |bus: &Bus| {
179 if bus.settings.muted {
180 0.0
181 } else {
182 bus.settings.volume * bus.duck.gain()
183 }
184 };
185 let gain = own(self.bus(id)?);
186 Ok(if id == BusId::MASTER {
187 gain
188 } else {
189 gain * own(&self.buses[0])
190 })
191 }
192 pub fn advance(&mut self, delta: Duration) {
194 for bus in &mut self.buses {
195 bus.duck.advance(delta);
196 }
197 }
198 pub fn settings(&self) -> AudioSettings {
200 AudioSettings {
201 buses: self
202 .buses
203 .iter()
204 .map(|bus| (bus.name.clone(), bus.settings))
205 .collect(),
206 }
207 }
208 pub fn apply_settings(&mut self, settings: &AudioSettings) -> Result<(), AudioError> {
211 for (name, values) in &settings.buses {
212 if name.trim().is_empty() {
213 return Err(AudioError("bus name must not be empty"));
214 }
215 validate_gain(values.volume)?;
216 }
217 for (name, values) in &settings.buses {
218 let id = self.add(name)?;
219 self.bus_mut(id)?.settings = *values;
220 }
221 Ok(())
222 }
223}
224
225#[cfg(test)]
226mod tests;