Skip to main content

roxlap_audio/
backend.rs

1//! AU.2 — the playback boundary: the [`AudioOut`] trait the acoustics
2//! core feeds, and the pure [`SourcePool`] slot policy shared by any
3//! backend.
4//!
5//! Every backend type stays behind this trait (hazard 1 of the entry
6//! doc: kira has a history of breaking API redesigns — the acoustics
7//! core and the hosts must compile without it). The kira
8//! implementation lives in [`crate::kira_out`] behind the `kira`
9//! cargo feature.
10
11use glam::{DQuat, DVec3};
12
13use crate::{synth::SoundBuffer, ListenerAcoustics, SourceAcoustics};
14
15/// A registered sound asset (backend-owned decoded buffer).
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
17pub struct SoundKey(pub(crate) usize);
18
19/// One live spatial source (a pooled backend track). Stale after the
20/// source is stopped or stolen — backend calls on a stale id are
21/// no-ops by contract.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
23pub struct SourceId(pub(crate) u64);
24
25/// The playback backend the acoustics core drives. Implementations
26/// apply parameter changes with **tweens** (~120 ms for per-source
27/// occlusion, ~1 s for the listener's reverb) — never as raw jumps
28/// (hazard 3: parameter zippering).
29pub trait AudioOut {
30    /// Register a mono PCM buffer; the key is valid for this backend's
31    /// lifetime.
32    fn register(&mut self, sound: &SoundBuffer) -> SoundKey;
33
34    /// Update the listener pose (world position + orientation).
35    fn set_listener(&mut self, pos: DVec3, orientation: DQuat);
36
37    /// Fire a one-shot at a world position. `initial` sets the source's
38    /// occlusion parameters **instantly** at spawn (no tween) — a fresh
39    /// voice has nothing to zipper against, and a one-shot's envelope is
40    /// often gone before a 120 ms ramp would arrive, so it must start
41    /// already muffled; pass `None` for a fully-clear start. Returns
42    /// `None` when every pooled track is busy with something more
43    /// important (the pool steals finished/oldest one-shots first, never
44    /// loops).
45    fn play(
46        &mut self,
47        sound: SoundKey,
48        at: DVec3,
49        initial: Option<&SourceAcoustics>,
50    ) -> Option<SourceId>;
51
52    /// Start a looping source (crystal hum) with the same instant
53    /// `initial` occlusion as [`play`](Self::play) — a hum entering
54    /// earshot through rock must start muffled, not blip clear for
55    /// 120 ms. Loops hold their track until [`stop`](Self::stop).
56    fn play_loop(
57        &mut self,
58        sound: SoundKey,
59        at: DVec3,
60        initial: Option<&SourceAcoustics>,
61    ) -> Option<SourceId>;
62
63    /// Stop a source and free its track. Stale ids are ignored.
64    fn stop(&mut self, id: SourceId);
65
66    /// Move a live source (tracked emitters). Stale ids are ignored.
67    fn set_source_position(&mut self, id: SourceId, pos: DVec3);
68
69    /// Apply occlusion parameters to a live source (~120 ms tween).
70    fn apply_source(&mut self, id: SourceId, acoustics: &SourceAcoustics);
71
72    /// Apply the listener's reverb environment (~1 s tween).
73    fn apply_listener(&mut self, acoustics: &ListenerAcoustics);
74}
75
76/// How a pooled slot is currently used.
77#[derive(Debug, Clone, Copy, PartialEq, Eq)]
78enum SlotUse {
79    Free,
80    /// A one-shot: stealable once finished, and the OLDEST one is
81    /// stolen when the pool is full (a new sound beats a stale tail).
82    OneShot,
83    /// A loop: never stolen; freed only by an explicit stop.
84    Looping,
85}
86
87/// Backend-agnostic voice-slot policy for a fixed pool of spatial
88/// tracks — pure and unit-tested here so every backend (the built-in
89/// kira one, or a host's own [`AudioOut`]) inherits the same behaviour
90/// (hazard 2: tracks are created up front and reused; a per-shot
91/// allocation storm is the classic mistake). One-shots are stealable
92/// (oldest first) when the pool is full; loops hold their slot until
93/// explicitly stopped.
94#[derive(Debug)]
95pub struct SourcePool {
96    slots: Vec<Slot>,
97    next_id: u64,
98    clock: u64,
99}
100
101#[derive(Debug, Clone, Copy)]
102struct Slot {
103    used: SlotUse,
104    id: SourceId,
105    started: u64,
106}
107
108impl SourcePool {
109    /// A pool of `capacity` voice slots (at least 1).
110    #[must_use]
111    pub fn new(capacity: usize) -> Self {
112        Self {
113            slots: vec![
114                Slot {
115                    used: SlotUse::Free,
116                    id: SourceId(0),
117                    started: 0,
118                };
119                capacity.max(1)
120            ],
121            next_id: 1,
122            clock: 0,
123        }
124    }
125
126    /// Allocate a slot for a new source. `finished` reports whether the
127    /// backend says slot `i`'s current sound has stopped on its own
128    /// (finished one-shots are reclaimed eagerly). Returns
129    /// `(slot index, fresh id)`; `None` only when every slot holds a
130    /// loop or a younger one-shot than everything stealable.
131    #[must_use]
132    pub fn allocate(
133        &mut self,
134        looping: bool,
135        mut finished: impl FnMut(usize) -> bool,
136    ) -> Option<(usize, SourceId)> {
137        self.clock += 1;
138        // Reclaim finished one-shots first.
139        for i in 0..self.slots.len() {
140            if self.slots[i].used == SlotUse::OneShot && finished(i) {
141                self.slots[i].used = SlotUse::Free;
142            }
143        }
144        // A free slot, else steal the OLDEST one-shot.
145        let idx = match self.slots.iter().position(|s| s.used == SlotUse::Free) {
146            Some(i) => i,
147            None => self
148                .slots
149                .iter()
150                .enumerate()
151                .filter(|(_, s)| s.used == SlotUse::OneShot)
152                .min_by_key(|(_, s)| s.started)
153                .map(|(i, _)| i)?,
154        };
155        let id = SourceId(self.next_id);
156        self.next_id += 1;
157        self.slots[idx] = Slot {
158            used: if looping {
159                SlotUse::Looping
160            } else {
161                SlotUse::OneShot
162            },
163            id,
164            started: self.clock,
165        };
166        Some((idx, id))
167    }
168
169    /// The slot currently owned by `id`, if it hasn't been stolen or
170    /// stopped since.
171    #[must_use]
172    pub fn slot_of(&self, id: SourceId) -> Option<usize> {
173        self.slots
174            .iter()
175            .position(|s| s.used != SlotUse::Free && s.id == id)
176    }
177
178    /// Free `id`'s slot (explicit stop). Stale ids are ignored.
179    pub fn release(&mut self, id: SourceId) -> Option<usize> {
180        let i = self.slot_of(id)?;
181        self.slots[i].used = SlotUse::Free;
182        Some(i)
183    }
184}
185
186#[cfg(test)]
187mod tests {
188    use super::*;
189
190    #[test]
191    fn pool_reuses_freed_and_finished_slots() {
192        let mut p = SourcePool::new(2);
193        let (i0, a) = p.allocate(false, |_| false).expect("slot 0");
194        let (i1, _b) = p.allocate(false, |_| false).expect("slot 1");
195        assert_ne!(i0, i1);
196        // Full, nothing finished ⇒ steals the OLDEST one-shot (a).
197        let (i2, c) = p.allocate(false, |_| false).expect("steal oldest");
198        assert_eq!(i2, i0);
199        assert_eq!(p.slot_of(a), None, "stolen id is stale");
200        assert_eq!(p.slot_of(c), Some(i0));
201        // Finished slots are reclaimed before stealing.
202        let (i3, _d) = p.allocate(false, |i| i == i1).expect("reclaim finished");
203        assert_eq!(i3, i1);
204    }
205
206    #[test]
207    fn loops_are_never_stolen() {
208        let mut p = SourcePool::new(2);
209        let (_, l0) = p.allocate(true, |_| false).expect("loop 0");
210        let (_, _l1) = p.allocate(true, |_| false).expect("loop 1");
211        assert!(
212            p.allocate(false, |_| false).is_none(),
213            "a pool full of loops refuses one-shots"
214        );
215        // Explicit stop frees the slot for the next allocation.
216        let freed = p.release(l0).expect("live loop releases");
217        let (i, _) = p.allocate(false, |_| false).expect("freed slot");
218        assert_eq!(i, freed);
219        assert!(p.release(l0).is_none(), "double release is a no-op");
220    }
221
222    /// A device-free [`AudioOut`] mock over a real [`SourcePool`], to
223    /// pin the trait contract the (untestable, device-bound) kira
224    /// backend follows: register keys, play/stop through the pool, and
225    /// ignore calls on stale ids.
226    #[derive(Default)]
227    struct MockOut {
228        sounds: usize,
229        pool: Option<SourcePool>,
230        applied: Vec<SourceId>,
231        stopped: Vec<SourceId>,
232    }
233
234    impl AudioOut for MockOut {
235        fn register(&mut self, _sound: &SoundBuffer) -> SoundKey {
236            let k = SoundKey(self.sounds);
237            self.sounds += 1;
238            k
239        }
240        fn set_listener(&mut self, _pos: glam::DVec3, _orientation: glam::DQuat) {}
241        fn play(
242            &mut self,
243            _sound: SoundKey,
244            _at: glam::DVec3,
245            _initial: Option<&SourceAcoustics>,
246        ) -> Option<SourceId> {
247            let p = self.pool.get_or_insert_with(|| SourcePool::new(2));
248            p.allocate(false, |_| false).map(|(_, id)| id)
249        }
250        fn play_loop(
251            &mut self,
252            _sound: SoundKey,
253            _at: glam::DVec3,
254            _initial: Option<&SourceAcoustics>,
255        ) -> Option<SourceId> {
256            let p = self.pool.get_or_insert_with(|| SourcePool::new(2));
257            p.allocate(true, |_| false).map(|(_, id)| id)
258        }
259        fn stop(&mut self, id: SourceId) {
260            if let Some(p) = self.pool.as_mut() {
261                if p.release(id).is_some() {
262                    self.stopped.push(id);
263                }
264            }
265        }
266        fn set_source_position(&mut self, _id: SourceId, _pos: glam::DVec3) {}
267        fn apply_source(&mut self, id: SourceId, _a: &SourceAcoustics) {
268            // Contract: only act on a live id.
269            if self.pool.as_ref().and_then(|p| p.slot_of(id)).is_some() {
270                self.applied.push(id);
271            }
272        }
273        fn apply_listener(&mut self, _a: &ListenerAcoustics) {}
274    }
275
276    #[test]
277    fn audio_out_contract_via_mock() {
278        use crate::{AcousticsConfig, SoundBuffer, SourceAcoustics};
279        // AudioOut is object-safe (hosts store `Box<dyn AudioOut>`).
280        let _obj: Box<dyn AudioOut> = Box::new(MockOut::default());
281
282        let buf = SoundBuffer {
283            sample_rate: 8,
284            samples: vec![0.0; 8],
285        };
286        let mut out = MockOut::default();
287        let k0 = out.register(&buf);
288        let k1 = out.register(&buf);
289        assert_ne!(k0, k1, "distinct sound keys");
290
291        let a = out.play(k0, glam::DVec3::ZERO, None).expect("first voice");
292        let b = out.play(k1, glam::DVec3::ZERO, None).expect("second voice");
293        // Applying to live sources is honoured.
294        let clear = SourceAcoustics::clear(&AcousticsConfig::default());
295        out.apply_source(a, &clear);
296        out.apply_source(b, &clear);
297        // Stop `a`, then a stale apply on `a` must be ignored.
298        out.stop(a);
299        out.apply_source(a, &clear);
300
301        assert_eq!(out.stopped, vec![a]);
302        assert_eq!(out.applied, vec![a, b], "stale apply on `a` was dropped");
303    }
304}