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 /// AU2.2 — Doppler pitch for a live source: a playback-rate factor
76 /// from [`crate::doppler_factor`] (`1.0` = neutral, `> 1`
77 /// approaching). Backends without pitch control may ignore it —
78 /// the default is a no-op — and implementations should tween
79 /// (~120 ms) like the other per-source parameters. Meant for
80 /// loops and long tails; bending a one-shot mid-envelope reads as
81 /// a glitch. Stale ids are ignored.
82 fn set_source_pitch(&mut self, id: SourceId, factor: f32) {
83 let _ = (id, factor);
84 }
85
86 /// WT.3 — a LISTENER-side lowpass over the whole mix (the master
87 /// path): the underwater muffle. A cutoff at or above
88 /// [`LISTENER_LOWPASS_OPEN_HZ`] is neutral; a few hundred Hz is
89 /// the canonical submerged value. Unlike the per-source occlusion
90 /// lowpass this dulls EVERYTHING — every voice and the reverb
91 /// tail alike.
92 ///
93 /// Drive it per frame from the submersion signal
94 /// (`CharacterBody::eye_in_water` in roxlap-scene): the dunk must
95 /// track the camera crossing the surface at FRAME rate, which is
96 /// why this is its own method and not a [`ListenerAcoustics`]
97 /// field — the reverb environment rides a ~2 Hz probe cadence
98 /// with ~1 s tweens, and a muffle quantized to that would lag a
99 /// head-dip by up to a second. Implementations tween fast
100 /// (~120 ms). Default: no-op (a backend without a master filter
101 /// simply stays clear — the [`set_source_pitch`](Self::set_source_pitch)
102 /// contract).
103 fn set_listener_lowpass(&mut self, cutoff_hz: f32) {
104 let _ = cutoff_hz;
105 }
106}
107
108/// WT.3 — the neutral (fully open) listener-lowpass cutoff: passing
109/// this (or anything above) to [`AudioOut::set_listener_lowpass`]
110/// means "not submerged". Defined AS [`crate::OPEN_CUTOFF_HZ`] —
111/// "open" means the same thing on the per-source and listener paths
112/// by construction, not by a pin test.
113pub const LISTENER_LOWPASS_OPEN_HZ: f32 = crate::OPEN_CUTOFF_HZ;
114
115/// WT.3 — the canonical SUBMERGED listener-lowpass cutoff: the value
116/// the demos (and any host without its own tuning) pass while the
117/// eye is under water. One named default so every call site muffles
118/// identically and a listening-pass retune is a one-line change.
119/// Tuned dark enough to read as "under the surface" while speech-band
120/// content stays intelligible.
121pub const LISTENER_LOWPASS_SUBMERGED_HZ: f32 = 700.0;
122
123/// How a pooled slot is currently used.
124#[derive(Debug, Clone, Copy, PartialEq, Eq)]
125enum SlotUse {
126 Free,
127 /// A one-shot: stealable once finished, and the OLDEST one is
128 /// stolen when the pool is full (a new sound beats a stale tail).
129 OneShot,
130 /// A loop: never stolen; freed only by an explicit stop.
131 Looping,
132}
133
134/// Backend-agnostic voice-slot policy for a fixed pool of spatial
135/// tracks — pure and unit-tested here so every backend (the built-in
136/// kira one, or a host's own [`AudioOut`]) inherits the same behaviour
137/// (hazard 2: tracks are created up front and reused; a per-shot
138/// allocation storm is the classic mistake). One-shots are stealable
139/// (oldest first) when the pool is full; loops hold their slot until
140/// explicitly stopped.
141#[derive(Debug)]
142pub struct SourcePool {
143 slots: Vec<Slot>,
144 next_id: u64,
145 clock: u64,
146}
147
148#[derive(Debug, Clone, Copy)]
149struct Slot {
150 used: SlotUse,
151 id: SourceId,
152 started: u64,
153}
154
155impl SourcePool {
156 /// A pool of `capacity` voice slots (at least 1).
157 #[must_use]
158 pub fn new(capacity: usize) -> Self {
159 Self {
160 slots: vec![
161 Slot {
162 used: SlotUse::Free,
163 id: SourceId(0),
164 started: 0,
165 };
166 capacity.max(1)
167 ],
168 next_id: 1,
169 clock: 0,
170 }
171 }
172
173 /// Allocate a slot for a new source. `finished` reports whether the
174 /// backend says slot `i`'s current sound has stopped on its own
175 /// (finished one-shots are reclaimed eagerly). Returns
176 /// `(slot index, fresh id)`; `None` only when every slot holds a
177 /// loop or a younger one-shot than everything stealable.
178 #[must_use]
179 pub fn allocate(
180 &mut self,
181 looping: bool,
182 mut finished: impl FnMut(usize) -> bool,
183 ) -> Option<(usize, SourceId)> {
184 self.clock += 1;
185 // Reclaim finished one-shots first.
186 for i in 0..self.slots.len() {
187 if self.slots[i].used == SlotUse::OneShot && finished(i) {
188 self.slots[i].used = SlotUse::Free;
189 }
190 }
191 // A free slot, else steal the OLDEST one-shot.
192 let idx = match self.slots.iter().position(|s| s.used == SlotUse::Free) {
193 Some(i) => i,
194 None => self
195 .slots
196 .iter()
197 .enumerate()
198 .filter(|(_, s)| s.used == SlotUse::OneShot)
199 .min_by_key(|(_, s)| s.started)
200 .map(|(i, _)| i)?,
201 };
202 let id = SourceId(self.next_id);
203 self.next_id += 1;
204 self.slots[idx] = Slot {
205 used: if looping {
206 SlotUse::Looping
207 } else {
208 SlotUse::OneShot
209 },
210 id,
211 started: self.clock,
212 };
213 Some((idx, id))
214 }
215
216 /// The slot currently owned by `id`, if it hasn't been stolen or
217 /// stopped since.
218 #[must_use]
219 pub fn slot_of(&self, id: SourceId) -> Option<usize> {
220 self.slots
221 .iter()
222 .position(|s| s.used != SlotUse::Free && s.id == id)
223 }
224
225 /// Free `id`'s slot (explicit stop). Stale ids are ignored.
226 pub fn release(&mut self, id: SourceId) -> Option<usize> {
227 let i = self.slot_of(id)?;
228 self.slots[i].used = SlotUse::Free;
229 Some(i)
230 }
231}
232
233#[cfg(test)]
234mod tests {
235 use super::*;
236
237 #[test]
238 fn pool_reuses_freed_and_finished_slots() {
239 let mut p = SourcePool::new(2);
240 let (i0, a) = p.allocate(false, |_| false).expect("slot 0");
241 let (i1, _b) = p.allocate(false, |_| false).expect("slot 1");
242 assert_ne!(i0, i1);
243 // Full, nothing finished ⇒ steals the OLDEST one-shot (a).
244 let (i2, c) = p.allocate(false, |_| false).expect("steal oldest");
245 assert_eq!(i2, i0);
246 assert_eq!(p.slot_of(a), None, "stolen id is stale");
247 assert_eq!(p.slot_of(c), Some(i0));
248 // Finished slots are reclaimed before stealing.
249 let (i3, _d) = p.allocate(false, |i| i == i1).expect("reclaim finished");
250 assert_eq!(i3, i1);
251 }
252
253 #[test]
254 fn loops_are_never_stolen() {
255 let mut p = SourcePool::new(2);
256 let (_, l0) = p.allocate(true, |_| false).expect("loop 0");
257 let (_, _l1) = p.allocate(true, |_| false).expect("loop 1");
258 assert!(
259 p.allocate(false, |_| false).is_none(),
260 "a pool full of loops refuses one-shots"
261 );
262 // Explicit stop frees the slot for the next allocation.
263 let freed = p.release(l0).expect("live loop releases");
264 let (i, _) = p.allocate(false, |_| false).expect("freed slot");
265 assert_eq!(i, freed);
266 assert!(p.release(l0).is_none(), "double release is a no-op");
267 }
268
269 /// A device-free [`AudioOut`] mock over a real [`SourcePool`], to
270 /// pin the trait contract the (untestable, device-bound) kira
271 /// backend follows: register keys, play/stop through the pool, and
272 /// ignore calls on stale ids.
273 #[derive(Default)]
274 struct MockOut {
275 sounds: usize,
276 pool: Option<SourcePool>,
277 applied: Vec<SourceId>,
278 stopped: Vec<SourceId>,
279 }
280
281 impl AudioOut for MockOut {
282 fn register(&mut self, _sound: &SoundBuffer) -> SoundKey {
283 let k = SoundKey(self.sounds);
284 self.sounds += 1;
285 k
286 }
287 fn set_listener(&mut self, _pos: glam::DVec3, _orientation: glam::DQuat) {}
288 fn play(
289 &mut self,
290 _sound: SoundKey,
291 _at: glam::DVec3,
292 _initial: Option<&SourceAcoustics>,
293 ) -> Option<SourceId> {
294 let p = self.pool.get_or_insert_with(|| SourcePool::new(2));
295 p.allocate(false, |_| false).map(|(_, id)| id)
296 }
297 fn play_loop(
298 &mut self,
299 _sound: SoundKey,
300 _at: glam::DVec3,
301 _initial: Option<&SourceAcoustics>,
302 ) -> Option<SourceId> {
303 let p = self.pool.get_or_insert_with(|| SourcePool::new(2));
304 p.allocate(true, |_| false).map(|(_, id)| id)
305 }
306 fn stop(&mut self, id: SourceId) {
307 if let Some(p) = self.pool.as_mut() {
308 if p.release(id).is_some() {
309 self.stopped.push(id);
310 }
311 }
312 }
313 fn set_source_position(&mut self, _id: SourceId, _pos: glam::DVec3) {}
314 fn apply_source(&mut self, id: SourceId, _a: &SourceAcoustics) {
315 // Contract: only act on a live id.
316 if self.pool.as_ref().and_then(|p| p.slot_of(id)).is_some() {
317 self.applied.push(id);
318 }
319 }
320 fn apply_listener(&mut self, _a: &ListenerAcoustics) {}
321 }
322
323 #[test]
324 fn audio_out_contract_via_mock() {
325 use crate::{AcousticsConfig, SoundBuffer, SourceAcoustics};
326 // AudioOut is object-safe (hosts store `Box<dyn AudioOut>`).
327 let _obj: Box<dyn AudioOut> = Box::new(MockOut::default());
328
329 let buf = SoundBuffer {
330 sample_rate: 8,
331 samples: vec![0.0; 8],
332 };
333 let mut out = MockOut::default();
334 let k0 = out.register(&buf);
335 let k1 = out.register(&buf);
336 assert_ne!(k0, k1, "distinct sound keys");
337
338 let a = out.play(k0, glam::DVec3::ZERO, None).expect("first voice");
339 let b = out.play(k1, glam::DVec3::ZERO, None).expect("second voice");
340 // Applying to live sources is honoured.
341 let clear = SourceAcoustics::clear(&AcousticsConfig::default());
342 out.apply_source(a, &clear);
343 out.apply_source(b, &clear);
344 // Stop `a`, then a stale apply on `a` must be ignored.
345 out.stop(a);
346 out.apply_source(a, &clear);
347
348 assert_eq!(out.stopped, vec![a]);
349 assert_eq!(out.applied, vec![a, b], "stale apply on `a` was dropped");
350 }
351
352 /// WT.3 — the listener-lowpass default is a REAL no-op: a backend
353 /// that never implements it (the mock) inherits a method that
354 /// leaves every bit of its state untouched — not merely "doesn't
355 /// panic". ("Open == per-source open" needs no pin anymore:
356 /// [`LISTENER_LOWPASS_OPEN_HZ`] is DEFINED as
357 /// [`crate::OPEN_CUTOFF_HZ`], the same constant the config
358 /// default uses.)
359 #[test]
360 fn listener_lowpass_default_is_a_no_op() {
361 let mut out = MockOut::default();
362 let s = out.register(&SoundBuffer {
363 samples: vec![0.0],
364 sample_rate: 44_100,
365 });
366 let id = out.play(s, glam::DVec3::ZERO, None).expect("voice");
367 out.set_listener_lowpass(400.0);
368 out.set_listener_lowpass(f32::NAN);
369 out.set_listener_lowpass(super::LISTENER_LOWPASS_OPEN_HZ);
370 // Nothing observable moved: no stops, no applies, the pool
371 // still owns the voice, no extra sounds registered.
372 assert!(out.stopped.is_empty());
373 assert!(out.applied.is_empty());
374 assert_eq!(out.sounds, 1);
375 assert!(out.pool.as_ref().is_some_and(|p| p.slot_of(id).is_some()));
376 }
377}