use glam::{DQuat, DVec3};
use crate::{synth::SoundBuffer, ListenerAcoustics, SourceAcoustics};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SoundKey(pub(crate) usize);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SourceId(pub(crate) u64);
pub trait AudioOut {
fn register(&mut self, sound: &SoundBuffer) -> SoundKey;
fn set_listener(&mut self, pos: DVec3, orientation: DQuat);
fn play(
&mut self,
sound: SoundKey,
at: DVec3,
initial: Option<&SourceAcoustics>,
) -> Option<SourceId>;
fn play_loop(
&mut self,
sound: SoundKey,
at: DVec3,
initial: Option<&SourceAcoustics>,
) -> Option<SourceId>;
fn stop(&mut self, id: SourceId);
fn set_source_position(&mut self, id: SourceId, pos: DVec3);
fn apply_source(&mut self, id: SourceId, acoustics: &SourceAcoustics);
fn apply_listener(&mut self, acoustics: &ListenerAcoustics);
fn set_source_pitch(&mut self, id: SourceId, factor: f32) {
let _ = (id, factor);
}
fn set_listener_lowpass(&mut self, cutoff_hz: f32) {
let _ = cutoff_hz;
}
}
pub const LISTENER_LOWPASS_OPEN_HZ: f32 = crate::OPEN_CUTOFF_HZ;
pub const LISTENER_LOWPASS_SUBMERGED_HZ: f32 = 700.0;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SlotUse {
Free,
OneShot,
Looping,
}
#[derive(Debug)]
pub struct SourcePool {
slots: Vec<Slot>,
next_id: u64,
clock: u64,
}
#[derive(Debug, Clone, Copy)]
struct Slot {
used: SlotUse,
id: SourceId,
started: u64,
}
impl SourcePool {
#[must_use]
pub fn new(capacity: usize) -> Self {
Self {
slots: vec![
Slot {
used: SlotUse::Free,
id: SourceId(0),
started: 0,
};
capacity.max(1)
],
next_id: 1,
clock: 0,
}
}
#[must_use]
pub fn allocate(
&mut self,
looping: bool,
mut finished: impl FnMut(usize) -> bool,
) -> Option<(usize, SourceId)> {
self.clock += 1;
for i in 0..self.slots.len() {
if self.slots[i].used == SlotUse::OneShot && finished(i) {
self.slots[i].used = SlotUse::Free;
}
}
let idx = match self.slots.iter().position(|s| s.used == SlotUse::Free) {
Some(i) => i,
None => self
.slots
.iter()
.enumerate()
.filter(|(_, s)| s.used == SlotUse::OneShot)
.min_by_key(|(_, s)| s.started)
.map(|(i, _)| i)?,
};
let id = SourceId(self.next_id);
self.next_id += 1;
self.slots[idx] = Slot {
used: if looping {
SlotUse::Looping
} else {
SlotUse::OneShot
},
id,
started: self.clock,
};
Some((idx, id))
}
#[must_use]
pub fn slot_of(&self, id: SourceId) -> Option<usize> {
self.slots
.iter()
.position(|s| s.used != SlotUse::Free && s.id == id)
}
pub fn release(&mut self, id: SourceId) -> Option<usize> {
let i = self.slot_of(id)?;
self.slots[i].used = SlotUse::Free;
Some(i)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn pool_reuses_freed_and_finished_slots() {
let mut p = SourcePool::new(2);
let (i0, a) = p.allocate(false, |_| false).expect("slot 0");
let (i1, _b) = p.allocate(false, |_| false).expect("slot 1");
assert_ne!(i0, i1);
let (i2, c) = p.allocate(false, |_| false).expect("steal oldest");
assert_eq!(i2, i0);
assert_eq!(p.slot_of(a), None, "stolen id is stale");
assert_eq!(p.slot_of(c), Some(i0));
let (i3, _d) = p.allocate(false, |i| i == i1).expect("reclaim finished");
assert_eq!(i3, i1);
}
#[test]
fn loops_are_never_stolen() {
let mut p = SourcePool::new(2);
let (_, l0) = p.allocate(true, |_| false).expect("loop 0");
let (_, _l1) = p.allocate(true, |_| false).expect("loop 1");
assert!(
p.allocate(false, |_| false).is_none(),
"a pool full of loops refuses one-shots"
);
let freed = p.release(l0).expect("live loop releases");
let (i, _) = p.allocate(false, |_| false).expect("freed slot");
assert_eq!(i, freed);
assert!(p.release(l0).is_none(), "double release is a no-op");
}
#[derive(Default)]
struct MockOut {
sounds: usize,
pool: Option<SourcePool>,
applied: Vec<SourceId>,
stopped: Vec<SourceId>,
}
impl AudioOut for MockOut {
fn register(&mut self, _sound: &SoundBuffer) -> SoundKey {
let k = SoundKey(self.sounds);
self.sounds += 1;
k
}
fn set_listener(&mut self, _pos: glam::DVec3, _orientation: glam::DQuat) {}
fn play(
&mut self,
_sound: SoundKey,
_at: glam::DVec3,
_initial: Option<&SourceAcoustics>,
) -> Option<SourceId> {
let p = self.pool.get_or_insert_with(|| SourcePool::new(2));
p.allocate(false, |_| false).map(|(_, id)| id)
}
fn play_loop(
&mut self,
_sound: SoundKey,
_at: glam::DVec3,
_initial: Option<&SourceAcoustics>,
) -> Option<SourceId> {
let p = self.pool.get_or_insert_with(|| SourcePool::new(2));
p.allocate(true, |_| false).map(|(_, id)| id)
}
fn stop(&mut self, id: SourceId) {
if let Some(p) = self.pool.as_mut() {
if p.release(id).is_some() {
self.stopped.push(id);
}
}
}
fn set_source_position(&mut self, _id: SourceId, _pos: glam::DVec3) {}
fn apply_source(&mut self, id: SourceId, _a: &SourceAcoustics) {
if self.pool.as_ref().and_then(|p| p.slot_of(id)).is_some() {
self.applied.push(id);
}
}
fn apply_listener(&mut self, _a: &ListenerAcoustics) {}
}
#[test]
fn audio_out_contract_via_mock() {
use crate::{AcousticsConfig, SoundBuffer, SourceAcoustics};
let _obj: Box<dyn AudioOut> = Box::new(MockOut::default());
let buf = SoundBuffer {
sample_rate: 8,
samples: vec![0.0; 8],
};
let mut out = MockOut::default();
let k0 = out.register(&buf);
let k1 = out.register(&buf);
assert_ne!(k0, k1, "distinct sound keys");
let a = out.play(k0, glam::DVec3::ZERO, None).expect("first voice");
let b = out.play(k1, glam::DVec3::ZERO, None).expect("second voice");
let clear = SourceAcoustics::clear(&AcousticsConfig::default());
out.apply_source(a, &clear);
out.apply_source(b, &clear);
out.stop(a);
out.apply_source(a, &clear);
assert_eq!(out.stopped, vec![a]);
assert_eq!(out.applied, vec![a, b], "stale apply on `a` was dropped");
}
#[test]
fn listener_lowpass_default_is_a_no_op() {
let mut out = MockOut::default();
let s = out.register(&SoundBuffer {
samples: vec![0.0],
sample_rate: 44_100,
});
let id = out.play(s, glam::DVec3::ZERO, None).expect("voice");
out.set_listener_lowpass(400.0);
out.set_listener_lowpass(f32::NAN);
out.set_listener_lowpass(super::LISTENER_LOWPASS_OPEN_HZ);
assert!(out.stopped.is_empty());
assert!(out.applied.is_empty());
assert_eq!(out.sounds, 1);
assert!(out.pool.as_ref().is_some_and(|p| p.slot_of(id).is_some()));
}
}