Skip to main content

rayengine_core/
audio.rs

1//! Display-independent audio buses, settings, and frame-clock gain envelopes.
2
3use serde::{Deserialize, Serialize};
4use std::{collections::BTreeMap, fmt, time::Duration};
5
6/// A bus in one mixer. Handles must not be shared between mixers or runs.
7#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
8pub struct BusId(usize);
9impl BusId {
10    /// Parent gain applied once to every bus.
11    pub const MASTER: Self = Self(0);
12    /// Default bus for streamed music.
13    pub const MUSIC: Self = Self(1);
14    /// Default bus for short sound effects.
15    pub const SFX: Self = Self(2);
16}
17
18/// Invalid audio controls. Invalid operations preserve the previous state.
19#[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
28/// Validates a finite gain in the inclusive range 0..=1.
29pub 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/// Linear amplitude envelope with saturating, integer-duration frame timing.
38#[derive(Clone, Debug)]
39pub struct GainFade {
40    start: f32,
41    target: f32,
42    elapsed: Duration,
43    duration: Duration,
44}
45impl GainFade {
46    /// Creates a fade; zero duration immediately yields the target gain.
47    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    /// Current amplitude gain.
58    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    /// Advances by wall time without simulation catch-up limits.
66    pub fn advance(&mut self, delta: Duration) {
67        self.elapsed = self.elapsed.saturating_add(delta).min(self.duration);
68    }
69    /// Whether the target has been reached.
70    pub fn finished(&self) -> bool {
71        self.elapsed >= self.duration
72    }
73    /// Changes the target without a jump from the current gain.
74    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/// User-controlled bus values suitable for a game-owned versioned save payload.
81#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
82pub struct BusSettings {
83    /// User volume in 0..=1; retained while muted or ducked.
84    pub volume: f32,
85    /// Silence this bus without changing its volume.
86    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/// Bus settings keyed by stable names, independent of run-local handles.
97/// The game owns the save schema; this type performs no filesystem I/O.
98#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
99pub struct AudioSettings {
100    /// Persistent volume/mute values. Transient ducking is intentionally omitted.
101    pub buses: BTreeMap<String, BusSettings>,
102}
103struct Bus {
104    name: String,
105    settings: BusSettings,
106    duck: GainFade,
107}
108/// Flat named buses under master; music/sfx are available by default.
109/// Muting affects gain only; envelopes and stream clocks continue advancing.
110pub 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    /// Resolves an existing name.
124    pub fn find(&self, name: &str) -> Option<BusId> {
125        self.buses
126            .iter()
127            .position(|bus| bus.name == name)
128            .map(BusId)
129    }
130    /// Adds a game-defined bus, or returns the existing handle for that name.
131    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    /// Reads persistent controls, independent of ducking and parent gain.
157    pub fn settings_for(&self, id: BusId) -> Result<BusSettings, AudioError> {
158        Ok(self.bus(id)?.settings)
159    }
160    /// Sets a user volume; rejects nonfinite/out-of-range values.
161    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    /// Mutes a bus, preserving the stored volume.
167    pub fn set_muted(&mut self, id: BusId, muted: bool) -> Result<(), AudioError> {
168        self.bus_mut(id)?.settings.muted = muted;
169        Ok(())
170    }
171    /// Fades a transient multiplier, e.g. 0.25 while a pause menu covers play.
172    /// This does not alter the persisted user volume.
173    pub fn duck(&mut self, id: BusId, gain: f32, duration: Duration) -> Result<(), AudioError> {
174        self.bus_mut(id)?.duck.retarget(gain, duration)
175    }
176    /// Effective bus gain, including master exactly once.
177    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    /// Advances every duck envelope by one frame's wall time.
193    pub fn advance(&mut self, delta: Duration) {
194        for bus in &mut self.buses {
195            bus.duck.advance(delta);
196        }
197    }
198    /// Captures user values for serialization into the game's save container.
199    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    /// Atomically applies named settings, creating extra buses when needed.
209    /// Unlisted buses and all transient duck envelopes retain their values.
210    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;