1use glam::{DQuat, DVec3};
12
13use crate::{synth::SoundBuffer, ListenerAcoustics, SourceAcoustics};
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
17pub struct SoundKey(pub(crate) usize);
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
23pub struct SourceId(pub(crate) u64);
24
25pub trait AudioOut {
30 fn register(&mut self, sound: &SoundBuffer) -> SoundKey;
33
34 fn set_listener(&mut self, pos: DVec3, orientation: DQuat);
36
37 fn play(
46 &mut self,
47 sound: SoundKey,
48 at: DVec3,
49 initial: Option<&SourceAcoustics>,
50 ) -> Option<SourceId>;
51
52 fn play_loop(
57 &mut self,
58 sound: SoundKey,
59 at: DVec3,
60 initial: Option<&SourceAcoustics>,
61 ) -> Option<SourceId>;
62
63 fn stop(&mut self, id: SourceId);
65
66 fn set_source_position(&mut self, id: SourceId, pos: DVec3);
68
69 fn apply_source(&mut self, id: SourceId, acoustics: &SourceAcoustics);
71
72 fn apply_listener(&mut self, acoustics: &ListenerAcoustics);
74}
75
76#[derive(Debug, Clone, Copy, PartialEq, Eq)]
78enum SlotUse {
79 Free,
80 OneShot,
83 Looping,
85}
86
87#[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 #[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 #[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 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 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 #[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 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 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 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 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 #[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 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 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 let clear = SourceAcoustics::clear(&AcousticsConfig::default());
295 out.apply_source(a, &clear);
296 out.apply_source(b, &clear);
297 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}