1use crate::hw::Hw;
18use crate::mixer::{Handle, Mixer, Play, Sound};
19
20pub 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#[derive(Clone, Debug)]
70pub struct LoopTable<const M: usize> {
71 entries: [Entry; M],
72}
73
74impl<const M: usize> LoopTable<M> {
75 pub const fn new() -> Self {
83 Self {
84 entries: [Entry::EMPTY; M],
85 }
86 }
87
88 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 pub fn handle(&self, index: usize) -> Option<Handle> {
106 self.entries[index].handle
107 }
108
109 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 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 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; } 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; }
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); t.update(&mut m, &mut hw, 8);
280 assert!(t.handle(1).is_some() && t.handle(0).is_none());
282 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 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 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}