Skip to main content
← PSoXide SDK guides and examples · SDK 80d1c329e977 · All Cargo features enabled; check feature gates before use.

psx_sfx/
vloop.rs

1//! Virtual loops: many loops, few voices.
2//!
3//! Half-Life authors thirty-two ambient loops on seven voices, Quake thirty-two
4//! on eleven, WipEout a crowd plus rival engines of which only the nearest two
5//! sound. The shape is always the same: a table of loop emitters, each with the
6//! level it would have if it had a voice, and a rule that gives the voices to the
7//! loudest. [`LoopTable`] is that rule.
8//!
9//! A loop only changes hands when a waiting loop beats the weakest holder by a
10//! margin (25 percent), so two loops of nearly equal level do not trade voices
11//! every frame and click.
12//!
13//! The lane the loops play on should use [`Policy::FirstFree`](crate::mixer::Policy)
14//! and hold nothing else: the table does its own stealing, with the margin, and
15//! must not have the mixer do it behind its back.
16
17use crate::hw::Hw;
18use crate::mixer::{Handle, Mixer, Play, Sound};
19
20/// How much louder (in percent) a waiting loop must be than the weakest loop
21/// holding a voice before it takes that voice. Half-Life's `claim_if_louder`.
22pub const HYSTERESIS_PERCENT: i32 = 25;
23
24#[derive(Clone, Copy, Debug)]
25struct Entry {
26    sound: Option<Sound>,
27    left: i16,
28    right: i16,
29    handle: Option<Handle>,
30}
31
32impl Entry {
33    const EMPTY: Entry = Entry {
34        sound: None,
35        left: 0,
36        right: 0,
37        handle: None,
38    };
39
40    fn audibility(&self) -> i32 {
41        (self.left.max(self.right) as i32).max(0)
42    }
43}
44
45/// A table of `M` loop emitters sharing the voices of one lane.
46///
47/// # Example
48///
49/// ```
50/// use psx_sfx::hw::Recorder;
51/// use psx_sfx::mixer::*;
52/// use psx_sfx::vloop::LoopTable;
53/// use psx_sfx::Sample;
54/// use psx_spu::SpuAddr;
55///
56/// // Two voices for ambient loops, three loops competing for them.
57/// let mut mixer = Mixer::new([Lane::new(0b11, Policy::FirstFree)], 60);
58/// let mut hw = Recorder::<64>::new();
59/// let wind = Sound::looped(SoundId(1), Sample::resident(SpuAddr::new(0x2000), 11025, 8), 0);
60///
61/// let mut loops = LoopTable::<3>::new();
62/// loops.set(0, &wind, 4000, 4000);
63/// loops.set(1, &wind, 2000, 2000);
64/// loops.set(2, &wind, 500, 500);
65/// loops.update(&mut mixer, &mut hw, 4);
66/// assert!(loops.handle(0).is_some() && loops.handle(1).is_some());
67/// assert!(loops.handle(2).is_none()); // the quietest waits
68/// ```
69#[derive(Clone, Debug)]
70pub struct LoopTable<const M: usize> {
71    entries: [Entry; M],
72}
73
74impl<const M: usize> LoopTable<M> {
75    /// An empty table.
76    ///
77    /// ```
78    /// # use psx_sfx::vloop::LoopTable;
79    /// let t = LoopTable::<8>::new();
80    /// assert!(t.handle(0).is_none());
81    /// ```
82    pub const fn new() -> Self {
83        Self {
84            entries: [Entry::EMPTY; M],
85        }
86    }
87
88    /// Register loop `index`, or refresh the levels it would have. The levels
89    /// are what the loop would sound like with a voice; a loop at or below the
90    /// mixer's cull threshold gives its voice up at the next
91    /// [`update`](Self::update).
92    pub fn set(&mut self, index: usize, sound: &Sound, left: i16, right: i16) {
93        let e = &mut self.entries[index];
94        e.sound = Some(*sound);
95        e.left = left;
96        e.right = right;
97    }
98
99    /// The handle of the voice loop `index` currently holds, if any.
100    ///
101    /// ```
102    /// # use psx_sfx::vloop::LoopTable;
103    /// assert!(LoopTable::<2>::new().handle(1).is_none());
104    /// ```
105    pub fn handle(&self, index: usize) -> Option<Handle> {
106        self.entries[index].handle
107    }
108
109    /// Remove loop `index`, stopping its voice if it has one.
110    ///
111    /// ```
112    /// # use psx_sfx::{hw::NullHw, mixer::*, vloop::LoopTable, Sample};
113    /// # use psx_spu::SpuAddr;
114    /// # let mut mixer = Mixer::new([Lane::new(1, Policy::FirstFree)], 60);
115    /// # let sound = Sound::looped(SoundId(1), Sample::resident(SpuAddr::new(0x2000), 11025, 8), 0);
116    /// let mut loops = LoopTable::<1>::new();
117    /// loops.set(0, &sound, 900, 900);
118    /// loops.update(&mut mixer, &mut NullHw, 1);
119    /// loops.clear(&mut mixer, &mut NullHw, 0);
120    /// assert_eq!(mixer.playing(), 0);
121    /// ```
122    pub fn clear<H: Hw, const L: usize>(&mut self, mixer: &mut Mixer<L>, hw: &mut H, index: usize) {
123        let e = &mut self.entries[index];
124        if let Some(h) = e.handle.take() {
125            mixer.stop(hw, h);
126        }
127        *e = Entry::EMPTY;
128    }
129
130    /// Remove every loop, stopping the voices they hold.
131    ///
132    /// ```
133    /// # use psx_sfx::{hw::NullHw, mixer::*, vloop::LoopTable};
134    /// # let mut mixer = Mixer::new([Lane::new(1, Policy::FirstFree)], 60);
135    /// let mut loops = LoopTable::<4>::new();
136    /// loops.clear_all(&mut mixer, &mut NullHw);
137    /// ```
138    pub fn clear_all<H: Hw, const L: usize>(&mut self, mixer: &mut Mixer<L>, hw: &mut H) {
139        for i in 0..M {
140            self.clear(mixer, hw, i);
141        }
142    }
143
144    /// Refresh the levels of loops that hold a voice, release the voices of
145    /// loops that fell silent, and hand free or weakly held voices to waiting
146    /// loops, at most `max_changes` hand-overs per call.
147    ///
148    /// Cost is linear in `M` plus a scan per hand-over; call it every second
149    /// to fourth frame rather than every frame.
150    pub fn update<H: Hw, const L: usize>(
151        &mut self,
152        mixer: &mut Mixer<L>,
153        hw: &mut H,
154        max_changes: usize,
155    ) {
156        let cull = mixer.cull() as i32;
157        for e in self.entries.iter_mut() {
158            let Some(h) = e.handle else { continue };
159            if !mixer.is_alive(h) {
160                e.handle = None; // stolen, or stopped elsewhere
161            } else if e.audibility() <= cull {
162                mixer.stop(hw, h);
163                e.handle = None;
164            } else {
165                mixer.update(hw, h, e.left, e.right);
166            }
167        }
168
169        let mut changes = 0;
170        while changes < max_changes {
171            let Some(waiting) = self.loudest_waiting(cull) else {
172                break;
173            };
174            let Some(sound) = self.entries[waiting].sound else {
175                break;
176            };
177            let lane = lane_of(&sound);
178            if !mixer.has_free(lane) {
179                let Some(weak) = self.weakest_holder(lane) else {
180                    break;
181                };
182                let need = self.entries[weak].audibility() * (100 + HYSTERESIS_PERCENT) / 100;
183                if self.entries[waiting].audibility() <= need {
184                    break;
185                }
186                if let Some(h) = self.entries[weak].handle.take() {
187                    mixer.stop(hw, h);
188                }
189            }
190            let e = &mut self.entries[waiting];
191            e.handle = mixer.play(hw, &sound, Play::new(e.left, e.right));
192            if e.handle.is_none() {
193                break; // the lane refused it; do not spin on it
194            }
195            changes += 1;
196        }
197    }
198
199    fn loudest_waiting(&self, cull: i32) -> Option<usize> {
200        let mut best: Option<(usize, i32)> = None;
201        for (i, e) in self.entries.iter().enumerate() {
202            if e.sound.is_some() && e.handle.is_none() {
203                let a = e.audibility();
204                if a > cull && best.is_none_or(|(_, b)| a > b) {
205                    best = Some((i, a));
206                }
207            }
208        }
209        best.map(|(i, _)| i)
210    }
211
212    fn weakest_holder(&self, lane: usize) -> Option<usize> {
213        let mut weak: Option<(usize, i32)> = None;
214        for (i, e) in self.entries.iter().enumerate() {
215            if e.handle.is_some() && e.sound.as_ref().map(lane_of) == Some(lane) {
216                let a = e.audibility();
217                if weak.is_none_or(|(_, w)| a < w) {
218                    weak = Some((i, a));
219                }
220            }
221        }
222        weak.map(|(i, _)| i)
223    }
224}
225
226impl<const M: usize> Default for LoopTable<M> {
227    fn default() -> Self {
228        Self::new()
229    }
230}
231
232fn lane_of(sound: &Sound) -> usize {
233    sound.lane() as usize
234}
235
236#[cfg(test)]
237mod tests {
238    use super::*;
239    use crate::hw::Recorder;
240    use crate::mixer::{Lane, Policy, SoundId};
241    use crate::Sample;
242    use psx_spu::SpuAddr;
243
244    type Rec = Recorder<512>;
245
246    fn wind() -> Sound {
247        Sound::looped(
248            SoundId(1),
249            Sample::resident(SpuAddr::new(0x2000), 11025, 8),
250            0,
251        )
252    }
253
254    fn rig(voices: u32) -> (Mixer<1>, Rec) {
255        (
256            Mixer::new([Lane::new(voices, Policy::FirstFree)], 60),
257            Rec::new(),
258        )
259    }
260
261    #[test]
262    fn the_loudest_loops_get_the_voices() {
263        let (mut m, mut hw) = rig(0b11);
264        let mut t = LoopTable::<4>::new();
265        for (i, a) in [100, 4000, 300, 2500].into_iter().enumerate() {
266            t.set(i, &wind(), a, a);
267        }
268        t.update(&mut m, &mut hw, 8);
269        let held: [bool; 4] = core::array::from_fn(|i| t.handle(i).is_some());
270        assert_eq!(held, [false, true, false, true]);
271    }
272
273    #[test]
274    fn a_waiting_loop_must_beat_the_weakest_holder_by_the_margin() {
275        let (mut m, mut hw) = rig(0b1);
276        let mut t = LoopTable::<2>::new();
277        t.set(0, &wind(), 1000, 1000);
278        t.set(1, &wind(), 1100, 1100); // louder, but not by 25 percent
279        t.update(&mut m, &mut hw, 8);
280        // Loop 1 is louder so it was served first; loop 0 waits.
281        assert!(t.handle(1).is_some() && t.handle(0).is_none());
282        // Loop 0 draws level with the holder: no swap, however often we update.
283        for _ in 0..10 {
284            t.set(0, &wind(), 1200, 1200);
285            t.update(&mut m, &mut hw, 8);
286            assert!(t.handle(1).is_some() && t.handle(0).is_none());
287        }
288        // Clearly louder (more than 1100 * 1.25 = 1375): it takes the voice.
289        t.set(0, &wind(), 1400, 1400);
290        t.update(&mut m, &mut hw, 8);
291        assert!(t.handle(0).is_some() && t.handle(1).is_none());
292    }
293
294    #[test]
295    fn two_nearly_equal_loops_do_not_trade_voices_frame_after_frame() {
296        let (mut m, mut hw) = rig(0b1);
297        let mut t = LoopTable::<2>::new();
298        t.set(0, &wind(), 1000, 1000);
299        t.set(1, &wind(), 1010, 1010);
300        t.update(&mut m, &mut hw, 8);
301        hw.clear();
302        for frame in 0..200 {
303            let wobble = (frame % 7) as i16 * 10;
304            t.set(0, &wind(), 1000 + wobble, 1000 + wobble);
305            t.set(1, &wind(), 1040 - wobble, 1040 - wobble);
306            t.update(&mut m, &mut hw, 8);
307        }
308        assert_eq!(hw.keyed_on(), 0, "no key-on after the first assignment");
309    }
310
311    #[test]
312    fn a_loop_that_falls_silent_gives_its_voice_to_a_waiting_one() {
313        let (mut m, mut hw) = rig(0b1);
314        let mut t = LoopTable::<2>::new();
315        t.set(0, &wind(), 3000, 3000);
316        t.set(1, &wind(), 500, 500);
317        t.update(&mut m, &mut hw, 8);
318        assert!(t.handle(0).is_some() && t.handle(1).is_none());
319        t.set(0, &wind(), 0, 0);
320        t.update(&mut m, &mut hw, 8);
321        assert!(t.handle(0).is_none() && t.handle(1).is_some());
322    }
323
324    #[test]
325    fn held_loops_follow_their_levels() {
326        let (mut m, mut hw) = rig(0b1);
327        let mut t = LoopTable::<1>::new();
328        t.set(0, &wind(), 1000, 2000);
329        t.update(&mut m, &mut hw, 1);
330        t.set(0, &wind(), 1500, 500);
331        t.update(&mut m, &mut hw, 1);
332        assert_eq!(hw.last_volume(0), Some((1500, 500)));
333    }
334
335    #[test]
336    fn a_voice_taken_elsewhere_is_noticed_and_the_loop_waits_again() {
337        let (mut m, mut hw) = rig(0b1);
338        let mut t = LoopTable::<1>::new();
339        t.set(0, &wind(), 1000, 1000);
340        t.update(&mut m, &mut hw, 1);
341        let h = t.handle(0).unwrap();
342        m.stop(&mut hw, h);
343        // The mixer is still ringing; the table drops the dead handle and
344        // re-claims the voice in the same update.
345        t.update(&mut m, &mut hw, 1);
346        let again = t.handle(0).unwrap();
347        assert_ne!(again, h);
348        assert!(m.is_alive(again));
349    }
350
351    #[test]
352    fn at_most_max_changes_loops_are_started_per_update() {
353        let (mut m, mut hw) = rig(0b1111);
354        let mut t = LoopTable::<4>::new();
355        for i in 0..4 {
356            t.set(i, &wind(), 1000 + i as i16, 1000);
357        }
358        t.update(&mut m, &mut hw, 2);
359        assert_eq!(m.playing().count_ones(), 2);
360        t.update(&mut m, &mut hw, 2);
361        assert_eq!(m.playing().count_ones(), 4);
362    }
363
364    #[test]
365    fn clearing_a_loop_stops_its_voice() {
366        let (mut m, mut hw) = rig(0b11);
367        let mut t = LoopTable::<2>::new();
368        t.set(0, &wind(), 1000, 1000);
369        t.set(1, &wind(), 1000, 1000);
370        t.update(&mut m, &mut hw, 4);
371        assert_eq!(m.playing().count_ones(), 2);
372        t.clear(&mut m, &mut hw, 0);
373        assert_eq!(m.playing().count_ones(), 1);
374        t.clear_all(&mut m, &mut hw);
375        assert_eq!(m.playing(), 0);
376        assert!(t.handle(0).is_none() && t.handle(1).is_none());
377    }
378}