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

psx_sfx/
retail.rs

1//! WipEout's retail note owner, pinned by the tests that came with it.
2//!
3//! WipEout's PAL sound driver (`PlayNote` at 8003f2fc, `UpdateNotes` at
4//! 8003ec80) shares channels 1 to 23 between effects and loops, never uses
5//! channel 0, and decides everything audible from three numbers per channel
6//! and a program-to-channel table. [`Owner`] is that logic with no hardware in
7//! it. It is the reference a [`Policy::StrictRetail`](crate::mixer::Policy)
8//! lane is held to: the differential test in this module drives an `Owner` and
9//! a `StrictRetail` mixer lane through the same long sequence and requires the
10//! same channel every time.
11//!
12//! What an `Owner` has that a mixer lane does not is retail's bookkeeping around
13//! the allocation: the program-to-channel table that [`Owner::kill`] follows
14//! even after the channel was reused, the eight-update release, the fade
15//! window, and the pause save and restore. A game replaying retail behaviour
16//! uses `Owner` for those and the lane for everything else.
17//!
18//! The shared policy and the duration cadence are confirmed against the PAL
19//! retail build; the NTSC retail build has not been checked.
20//!
21//! # Example
22//!
23//! ```
24//! use psx_sfx::retail::Owner;
25//!
26//! let mut owner = Owner::new();
27//! // A loop (duration -1) takes channel 1 and is never stolen.
28//! assert_eq!(owner.play(19, 0, -1), Some(1));
29//! // An effect of priority 1 lasting 20 updates takes the next free channel.
30//! assert_eq!(owner.play(7, 1, 20), Some(2));
31//! ```
32
33/// Program identities: 35 original, plus 7 for the second local player.
34pub const PROGRAMS: usize = 42;
35
36/// Updates a killed note keeps playing before it is released.
37pub const NOTE_RELEASE: i32 = 8;
38
39/// Updates before the end of a note during which its volume fades.
40pub const NOTE_FADE_STEPS: i32 = 9;
41
42/// One channel of the owner.
43#[derive(Copy, Clone)]
44pub struct Channel {
45    /// Updates left: `0` is free, `-1` is a loop, positive is a finite note.
46    pub duration: i32,
47    /// Priority; a smaller number is more important.
48    pub priority: i16,
49}
50
51const EMPTY: Channel = Channel {
52    duration: 0,
53    priority: 0,
54};
55
56/// The channel table and program map.
57pub struct Owner {
58    /// The 24 channels; channel 0 is never allocated.
59    pub channels: [Channel; 24],
60    /// The last channel each program was given, kept after replacement.
61    pub latest: [u8; PROGRAMS],
62    paused: bool,
63}
64
65/// What one [`Owner::update`] asks the hardware to do.
66#[derive(Default)]
67pub struct Update {
68    /// Channels to key off.
69    pub key_off: u32,
70    /// Channels whose volume fades one step.
71    pub fade: u32,
72    /// Fade shift: 2 playing, 3 paused.
73    pub shift: u8,
74    /// Save every channel's volume (pause began).
75    pub save: bool,
76    /// Restore the saved volumes (pause ended).
77    pub restore: bool,
78}
79
80impl Owner {
81    /// An owner with every channel free.
82    pub const fn new() -> Self {
83        Self {
84            channels: [EMPTY; 24],
85            latest: [0; PROGRAMS],
86            paused: false,
87        }
88    }
89
90    /// Start a note for `program`: the first free channel, else the first
91    /// finite note with a strictly lower priority (a larger number). Loops are
92    /// never taken and equal priority cannot steal.
93    ///
94    /// ```
95    /// # use psx_sfx::retail::Owner;
96    /// let mut o = Owner::new();
97    /// for _ in 1..24 {
98    ///     o.play(7, 1, 20);
99    /// }
100    /// assert_eq!(o.play(7, 1, 20), None); // equal priority cannot steal
101    /// assert_eq!(o.play(7, 0, 20), Some(1)); // a more important note can
102    /// ```
103    pub fn play(&mut self, program: u8, priority: i16, duration: i16) -> Option<u8> {
104        let at = (1..24)
105            .find(|&i| self.channels[i].duration == 0)
106            .or_else(|| {
107                (1..24).find(|&i| {
108                    self.channels[i].duration > 0 && priority < self.channels[i].priority
109                })
110            })?;
111        self.channels[at] = Channel {
112            duration: duration as i32,
113            priority,
114        };
115        self.latest[program as usize] = at as u8;
116        Some(at as u8)
117    }
118
119    /// Native KillNote follows the program's last channel, even when its
120    /// prior note ended or was replaced. It releases after eight updates.
121    ///
122    /// ```
123    /// # use psx_sfx::retail::{Owner, NOTE_RELEASE};
124    /// let mut o = Owner::new();
125    /// let ch = o.play(3, 1, 50).unwrap();
126    /// o.kill(3);
127    /// assert_eq!(o.channels[ch as usize].duration, NOTE_RELEASE);
128    /// ```
129    pub fn kill(&mut self, program: u8) {
130        self.channels[self.latest[program as usize] as usize].duration = NOTE_RELEASE;
131    }
132
133    /// Free every channel. Like the original KillAllFx it keeps the
134    /// program-to-channel identities.
135    ///
136    /// ```
137    /// # use psx_sfx::retail::Owner;
138    /// let mut o = Owner::new();
139    /// o.play(1, 0, -1);
140    /// o.stop_all();
141    /// assert_eq!(o.channels[1].duration, 0);
142    /// ```
143    pub fn stop_all(&mut self) {
144        for channel in &mut self.channels {
145            channel.duration = 0;
146        }
147        self.paused = false;
148    }
149
150    /// One `UpdateNotes` call. A change of `paused` returns a save or restore
151    /// and no tick; otherwise every note ages by one, fading in its last
152    /// [`NOTE_FADE_STEPS`] updates and keying off on its last.
153    ///
154    /// ```
155    /// # use psx_sfx::retail::Owner;
156    /// let mut o = Owner::new();
157    /// o.play(1, 1, 1);
158    /// assert_eq!(o.update(false).key_off, 1 << 1);
159    /// ```
160    pub fn update(&mut self, paused: bool) -> Update {
161        if paused != self.paused {
162            self.paused = paused;
163            return Update {
164                save: paused,
165                restore: !paused,
166                ..Update::default()
167            };
168        }
169        let mut out = Update {
170            shift: if paused { 3 } else { 2 },
171            ..Update::default()
172        };
173        for i in 1..24 {
174            let d = self.channels[i].duration;
175            if paused || (1..=NOTE_FADE_STEPS).contains(&d) {
176                out.fade |= 1 << i;
177            }
178            if d == 1 {
179                out.key_off |= 1 << i;
180            }
181            if d > 0 {
182                self.channels[i].duration -= 1;
183            }
184        }
185        out
186    }
187}
188
189impl Default for Owner {
190    fn default() -> Self {
191        Self::new()
192    }
193}
194
195#[cfg(test)]
196mod tests {
197    use super::*;
198    use crate::hw::Recorder;
199    use crate::mixer::{Class, Lane, Mixer, Play, Policy, Sound, SoundId};
200    use crate::Sample;
201    use psx_spu::SpuAddr;
202
203    // The three tests below are WipEout's own `audio_voices.rs` tests, moved
204    // here unchanged apart from `crate::rate::NOTE_RELEASE`, which is
205    // `NOTE_RELEASE` in this module.
206
207    #[test]
208    fn native_audio_shared_pool_keeps_loops_and_strict_signed_priority() {
209        let mut owner = Owner::new();
210        assert_eq!(owner.play(19, 0, -1), Some(1));
211        assert_eq!(owner.play(30, 0, -1), Some(2));
212        for i in 3..24 {
213            assert_eq!(owner.play(7, 1, 20), Some(i));
214        }
215        assert_eq!(owner.play(0, 1, 30), None); // equal priority cannot steal
216        assert_eq!(owner.play(0, -1, 30), Some(3));
217        assert_eq!(
218            (owner.channels[1].duration, owner.channels[2].duration),
219            (-1, -1)
220        );
221        assert_eq!(owner.latest[0], 3);
222    }
223
224    #[test]
225    fn native_audio_program_latest_identity_and_finite_release_are_independent_of_sample_end() {
226        let mut owner = Owner::new();
227        assert_eq!(owner.play(7, 1, 20), Some(1));
228        assert_eq!(owner.play(7, 1, 20), Some(2));
229        owner.kill(7);
230        assert_eq!(
231            (owner.channels[1].duration, owner.channels[2].duration),
232            (20, 8)
233        );
234        for _ in 0..7 {
235            assert_eq!(owner.update(false).key_off, 0);
236        }
237        let last = owner.update(false);
238        assert_eq!(last.key_off, 1 << 2);
239        assert_eq!(last.fade & (1 << 2), 1 << 2);
240        assert_eq!(
241            (owner.channels[1].duration, owner.channels[2].duration),
242            (12, 0)
243        );
244        assert_eq!(owner.play(8, 1, 20), Some(2));
245        // Native last-program identity is retained after replacement.
246        owner.kill(7);
247        assert_eq!(owner.channels[2].duration, 8);
248    }
249
250    #[test]
251    fn native_audio_pause_transition_has_no_tick_and_preserves_reserved_loop() {
252        let mut owner = Owner::new();
253        owner.play(13, 0, -1);
254        owner.play(26, 1, 2);
255        let first = owner.update(true);
256        assert!(first.save);
257        assert_eq!(owner.channels[2].duration, 2);
258        let paused = owner.update(true);
259        assert_eq!(paused.shift, 3);
260        assert_eq!(paused.fade, 0x00fffffe);
261        assert_eq!(owner.channels[2].duration, 1);
262        assert!(owner.update(false).restore);
263        assert_eq!(owner.channels[2].duration, 1);
264        let resumed = owner.update(false);
265        assert_eq!(resumed.key_off, 1 << 2);
266        assert_eq!(resumed.shift, 2);
267        assert_eq!(owner.channels[1].duration, -1);
268    }
269
270    // ---- The same decisions through a StrictRetail mixer lane. ----
271
272    const RETAIL: u32 = 0x00ff_fffe; // channels 1..=23
273
274    fn sample() -> Sample {
275        Sample::resident(SpuAddr::new(0x1010), 44100, 100)
276    }
277
278    fn retail_mixer() -> Mixer<1> {
279        Mixer::new([Lane::new(RETAIL, Policy::StrictRetail)], 60)
280    }
281
282    fn sound(prio: i16, looped: bool) -> Sound {
283        let s = if looped {
284            Sound::looped(SoundId(0), sample(), 0)
285        } else {
286            Sound::one_shot(SoundId(0), sample(), 0)
287        };
288        s.with_class(Class::Normal).with_prio(prio)
289    }
290
291    #[test]
292    fn a_strict_retail_lane_reproduces_the_shared_pool_test() {
293        let mut m = retail_mixer();
294        let mut hw = Recorder::<256>::new();
295        let play = |m: &mut Mixer<1>, hw: &mut Recorder<256>, prio, looped, dur: u32| {
296            m.play(
297                hw,
298                &sound(prio, looped),
299                Play::new(100, 100).with_ticks(dur),
300            )
301            .map(|h| h.voice())
302        };
303        assert_eq!(play(&mut m, &mut hw, 0, true, 0), Some(1));
304        assert_eq!(play(&mut m, &mut hw, 0, true, 0), Some(2));
305        for i in 3..24 {
306            assert_eq!(play(&mut m, &mut hw, 1, false, 20), Some(i));
307        }
308        assert_eq!(play(&mut m, &mut hw, 1, false, 30), None);
309        assert_eq!(play(&mut m, &mut hw, -1, false, 30), Some(3));
310        // The two loops are still alive: only channel 3 changed hands.
311        assert_eq!(m.playing(), RETAIL);
312    }
313
314    #[test]
315    fn a_strict_retail_note_ends_on_the_update_that_keys_it_off() {
316        let mut m = retail_mixer();
317        let mut hw = Recorder::<64>::new();
318        m.tick(&mut hw, 0);
319        let h = m
320            .play(&mut hw, &sound(1, false), Play::new(100, 100).with_ticks(3))
321            .unwrap();
322        hw.clear();
323        for now in 1..=2 {
324            m.tick(&mut hw, now);
325            assert_eq!(hw.keyed_off(), 0, "alive on update {now}");
326        }
327        m.tick(&mut hw, 3);
328        assert_eq!(hw.keyed_off(), 1 << h.voice());
329        // Retail frees the channel immediately and does not zero its volume.
330        assert!(hw.last_volume(h.voice()).is_none());
331        assert_eq!(m.playing(), 0);
332    }
333
334    /// A small deterministic generator, so the sequence is the same everywhere.
335    struct Lcg(u32);
336    impl Lcg {
337        fn next(&mut self) -> u32 {
338            self.0 = self.0.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
339            self.0 >> 8
340        }
341    }
342
343    #[test]
344    fn a_strict_retail_lane_makes_the_same_choices_as_the_owner_over_a_long_sequence() {
345        let (mut dropped, mut stolen, mut ended) = (0, 0, 0);
346        for seed in 1..=8u32 {
347            let mut rng = Lcg(seed);
348            let mut owner = Owner::new();
349            let mut m = retail_mixer();
350            let mut hw = Recorder::<4>::new();
351            let mut now = 0u32;
352            m.tick(&mut hw, now);
353            for step in 0..4000 {
354                if rng.next().is_multiple_of(3) {
355                    // One UpdateNotes: the owner ages its notes, the mixer's
356                    // clock moves one tick.
357                    let out = owner.update(false);
358                    now += 1;
359                    let before = m.playing();
360                    m.tick(&mut hw, now);
361                    let gone = before & !m.playing();
362                    assert_eq!(gone, out.key_off, "seed {seed} step {step}: key-off set");
363                    ended += gone.count_ones();
364                } else {
365                    let prio = (rng.next() % 5) as i16 - 2;
366                    let looped = rng.next().is_multiple_of(9);
367                    let dur = 1 + (rng.next() % 40) as i16;
368                    let occupied = owner.channels.iter().skip(1).all(|c| c.duration != 0);
369                    let want = owner.play(0, prio, if looped { -1 } else { dur });
370                    match want {
371                        None => dropped += 1,
372                        Some(_) if occupied => stolen += 1,
373                        Some(_) => {}
374                    }
375                    let got = m
376                        .play(
377                            &mut hw,
378                            &sound(prio, looped),
379                            Play::new(100, 100).with_ticks(dur as u32),
380                        )
381                        .map(|h| h.voice());
382                    assert_eq!(got, want, "seed {seed} step {step}: channel");
383                }
384                // Channel occupancy agrees at every step.
385                let mut live = 0u32;
386                for (i, c) in owner.channels.iter().enumerate().skip(1) {
387                    if c.duration != 0 {
388                        live |= 1 << i;
389                    }
390                }
391                assert_eq!(m.playing(), live, "seed {seed} step {step}: occupancy");
392            }
393        }
394        // The sequence must actually exercise the interesting decisions.
395        assert!(
396            dropped > 100 && stolen > 100 && ended > 100,
397            "{dropped} {stolen} {ended}"
398        );
399    }
400
401    #[test]
402    fn ending_a_note_early_follows_the_retail_release_length() {
403        let mut m = retail_mixer();
404        let mut hw = Recorder::<64>::new();
405        m.tick(&mut hw, 100);
406        let h = m
407            .play(&mut hw, &sound(1, true), Play::new(100, 100))
408            .unwrap();
409        assert!(m.end_in(h, NOTE_RELEASE as u32));
410        m.tick(&mut hw, 107);
411        assert!(m.is_alive(h));
412        m.tick(&mut hw, 108);
413        assert!(!m.is_alive(h));
414    }
415}