psx_sfx/lib.rs
1//! Sample playback and shared voice management on the SPU.
2//!
3//! Four programs on the PSoXide demo disc grew their own copy of this: the
4//! launcher, VoXide, NitroXide and the Celeste collection. Three of them are
5//! not engine applications, so the helpers in `psx-engine` were out of reach
6//! and each rewrote the same three things. That mattered more than the
7//! duplication itself, because what they were rewriting is the part emulators
8//! get wrong:
9//!
10//! * A one-shot's repeat address has to be written by hand. Silicon latches it
11//! only from a block carrying the loop-start flag, and a one-shot has none,
12//! so it otherwise keeps whatever the previous sound left there and the
13//! voice ends up playing an unrelated sample. [`psx_spu::Voice::
14//! configure_sample`] does this now; going through it is the point.
15//! * A one-shot does not stop itself. END drops the voice into RELEASE at the
16//! ADSR's release rate rather than muting it, so a slow release leaves the
17//! voice running audibly past its own data. A fast release hides that, which
18//! is why the bug survived so long: the Celeste collection is inaudibly
19//! wrong rather than right. The honest fix is to silence the voice on a
20//! clock, which is what [`Player::tick`] does.
21//! * Voices have to be shared out, or a new sound cuts off the one before it.
22//!
23//! ```ignore
24//! let mut bank = Bank::new(SpuAddr::new(0x1010));
25//! let blip = bank.upload_on(&mut spu, include_bytes!("blip.psau"));
26//! let mut player: Player<3> = Player::new([Voice::V0, Voice::V1, Voice::V2], 60);
27//!
28//! // once a frame
29//! player.tick(tick);
30//! if pressed { player.play(&OneShot::new(blip, Volume::HALF), tick); }
31//! ```
32//!
33//! Map ambience whose ADPCM carries loop flags uses [`LoopingSample`].
34//!
35//! # Above the plumbing
36//!
37//! Everything above is hardware plumbing: no policy, one decision per call. The
38//! modules below add the policy that ten programs each wrote for themselves, as
39//! `no_std`, heap-free, `i32`-only bookkeeping that never touches a register and
40//! so runs, and is tested, on the host:
41//!
42//! * [`mixer`]: the 24 voices split into lanes, with priority classes, `Smart`
43//! and `StrictRetail` stealing policies, generation-checked handles for
44//! one-shots and loops, and wrap-safe lifetimes.
45//! * [`vloop`]: more loops than voices, with the voices going to the loudest.
46//! * [`space`]: distance curves (including the Quake and GoldSrc laws), pan
47//! laws and the split-screen listener rules, turning positions into ear levels.
48//! * [`master`]: the effects and music master volumes and the music duck.
49//! * [`hw`]: the [`Hw`](hw::Hw) trait through which the bookkeeping drives the
50//! chip, and a [`Recorder`](hw::Recorder) that logs the calls instead.
51//! * [`retail`]: WipEout's retail note owner, as the reference for the
52//! `StrictRetail` policy.
53
54#![no_std]
55
56#[cfg(test)]
57extern crate std;
58
59pub mod hw;
60pub mod master;
61pub mod mixer;
62pub mod retail;
63pub mod space;
64pub mod vloop;
65
66use psx_asset::Audio;
67use psx_spu::{Adsr, Pitch, Spu, SpuAddr, Voice, Volume};
68
69/// Highest level the SPU accepts in a volume register.
70pub(crate) const SPU_LEVEL_MAX: i16 = 0x3fff;
71
72/// Lowest level the SPU accepts in a volume register (phase inverted).
73pub(crate) const SPU_LEVEL_MIN: i16 = -0x4000;
74
75/// Decoded samples in one ADPCM block. Fourteen data bytes, two nibbles each.
76const SAMPLES_PER_BLOCK: u32 = 28;
77
78/// Bytes in one ADPCM block: a shift/filter byte, a flags byte, and fourteen
79/// of data.
80const BLOCK_BYTES: u32 = 16;
81
82/// One ADPCM block of silence that loops onto itself, written after every
83/// uploaded sample so a voice running past its own END lands on nothing.
84///
85/// Shift/filter 0, flags `0x07` = LOOP-START | REPEAT | END, then fourteen
86/// bytes of zero nibbles. LOOP-START is the bit that matters: the hardware
87/// latches the repeat address off this block while decoding it, which does not
88/// depend on anything written before key-on.
89/// Self-looping silent ADPCM block appended after each packed one-shot.
90///
91/// Cookers that build a bank for later bulk upload should append this after
92/// every sample. This gives silicon the same loop-start marker as [`Bank`]
93/// without duplicating the hardware-specific byte sequence outside the SDK.
94pub const PARKING_TAIL: [u8; BLOCK_BYTES as usize] =
95 [0x00, 0x07, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
96
97/// Ticks of margin added past a sample's own length before its voice is
98/// silenced, so the cutoff never clips a sound that is still sounding.
99///
100/// This margin is exactly the window the browse blip was audibly wandering in
101/// before SAMPLE_TAIL existed: 0.250 s of sample against a 0.283 s cutoff left
102/// 33 ms in which the voice played the next sample in the bank. The margin is
103/// safe to keep now that the sample parks itself.
104///
105/// The length is computed from the block count, which rounds up to a whole
106/// block, and the key-on itself lands somewhere inside the current tick.
107const TAIL_TICKS: u32 = 2;
108
109/// A sample resident in SPU RAM.
110#[derive(Clone, Copy, Debug, PartialEq, Eq)]
111pub struct Sample {
112 addr: SpuAddr,
113 rate_hz: u32,
114 frames: u32,
115}
116
117impl Sample {
118 /// Describe a sample already resident in SPU RAM, for banks uploaded by
119 /// something other than [`Bank`] -- VoXide streams its straight off the
120 /// disc into the SPU, never holding it in main RAM.
121 ///
122 /// `blocks` is the sample's ADPCM block count, or 0 when the bank format
123 /// does not record one. Length is what a cutoff is computed from, so a
124 /// sample without it gets no cutoff and falls back to the envelope: see
125 /// [`Sample::ticks_at`].
126 pub const fn resident(addr: SpuAddr, rate_hz: u32, blocks: u32) -> Self {
127 Self {
128 addr,
129 rate_hz,
130 frames: blocks,
131 }
132 }
133
134 /// Where the sample starts in SPU RAM.
135 pub const fn addr(&self) -> SpuAddr {
136 self.addr
137 }
138
139 /// The rate the sample was cooked at.
140 pub const fn sample_rate_hz(&self) -> u32 {
141 self.rate_hz
142 }
143
144 /// Decoded length in samples.
145 pub const fn len_samples(&self) -> u32 {
146 self.frames * SAMPLES_PER_BLOCK
147 }
148
149 /// How long this sample runs, in ticks of a `ticks_hz` clock, played at
150 /// its own rate, with [`TAIL_TICKS`] of margin. `None` when the block
151 /// count is unknown, which means no cutoff can be computed and the
152 /// envelope has to finish the sound instead.
153 ///
154 /// Pitch-shifted playback stretches this: see [`OneShot::with_pitch`].
155 pub const fn ticks_at(&self, ticks_hz: u32) -> Option<u32> {
156 if self.frames == 0 {
157 return None;
158 }
159 let rate = if self.rate_hz == 0 { 1 } else { self.rate_hz };
160 Some(self.len_samples() * ticks_hz / rate + TAIL_TICKS)
161 }
162}
163
164/// A sequential SPU RAM allocator: uploads cooked `.psau` samples one after
165/// another and hands back where each landed.
166///
167/// Start it at or above [`psx_spu::SILENCE_BLOCK`] plus one block. `psx-spu`
168/// keeps the first usable block of SPU RAM for the silence every finished
169/// one-shot parks on, and [`psx_spu::Spu::upload_adpcm`] rejects a bank laid over
170/// it rather than letting the collision be silent.
171pub struct Bank {
172 next: SpuAddr,
173}
174
175impl Bank {
176 /// Start a bank at `base`.
177 pub const fn new(base: SpuAddr) -> Self {
178 Self { next: base }
179 }
180
181 /// Where the next upload will land, and so the first address free after
182 /// everything uploaded so far.
183 pub const fn next_addr(&self) -> SpuAddr {
184 self.next
185 }
186
187 /// Upload one cooked `.psau` sample through `spu`.
188 ///
189 /// # Panics
190 /// If `psau` is not a valid cooked sample, matching the rest of the SDK's
191 /// asset handling: a bad `include_bytes!` is a build mistake, not a
192 /// runtime condition worth threading a Result through a sound effect for.
193 pub fn upload_on(&mut self, spu: &mut Spu, psau: &[u8]) -> Sample {
194 self.upload_with(psau, |dest, bytes| spu.upload_adpcm(dest, bytes))
195 }
196
197 /// [`upload_on`](Self::upload_on) on a token the caller does not hold.
198 ///
199 /// # Panics
200 /// As [`upload_on`](Self::upload_on).
201 #[deprecated(note = "use `Bank::upload_on` with the `Spu` driver")]
202 #[allow(deprecated)]
203 pub fn upload(&mut self, psau: &[u8]) -> Sample {
204 self.upload_with(psau, psx_spu::upload_adpcm)
205 }
206
207 fn upload_with(&mut self, psau: &[u8], mut put: impl FnMut(SpuAddr, &[u8])) -> Sample {
208 let audio = Audio::from_bytes(psau).expect("cooked psau sample");
209 let adpcm = audio.adpcm_bytes();
210 put(self.next, adpcm);
211 let sample = Sample {
212 addr: self.next,
213 rate_hz: audio.sample_rate_hz(),
214 frames: adpcm.len() as u32 / BLOCK_BYTES,
215 };
216 self.next = SpuAddr::new(self.next.byte_offset() + adpcm.len() as u32);
217 // A parking block after every sample, not just one shared block that
218 // the repeat register points at.
219 //
220 // Pointing the register at psx_spu::SILENCE_BLOCK is not enough on
221 // silicon. The 2026-08-04 launcher capture caught the browse voice
222 // running off the end of jump at 0x1010 straight into pickup_coin at
223 // 0x28B0: the stray 40 ms burst matched the coin's opening spectrum on
224 // all five peaks, 2800/2825/2850/8450/8475 Hz. SB2 had read the repeat
225 // register back as 0x0200, which is that shared block, so the register
226 // was right and the voice went past it anyway.
227 //
228 // VoXide is the counter-example that says what actually works: its
229 // cooker appends a self-looping silent block to every sample and it has
230 // never had the artefact. The difference is the loop-start bit. This
231 // block carries END, REPEAT and LOOP-START, so the hardware latches the
232 // repeat address to the block itself as it decodes it, rather than
233 // relying on a value written before key-on.
234 put(self.next, &PARKING_TAIL);
235 self.next = SpuAddr::new(self.next.byte_offset() + BLOCK_BYTES);
236 sample
237 }
238}
239
240/// A sample with the settings it should be played at.
241#[derive(Clone, Copy)]
242pub struct OneShot {
243 sample: Sample,
244 volume: Volume,
245 adsr: Adsr,
246 pitch: Option<Pitch>,
247}
248
249impl OneShot {
250 /// A one-shot at its own recorded rate, under [`Adsr::default_tone`].
251 ///
252 /// `default_tone` rather than `percussive`: percussive self-fades in about
253 /// 150 ms, which is most of a quarter-second sound. The cutoff, not the
254 /// envelope, is what stops this.
255 pub const fn new(sample: Sample, volume: Volume) -> Self {
256 Self {
257 sample,
258 volume,
259 adsr: Adsr::default_tone(),
260 pitch: None,
261 }
262 }
263
264 /// Play at a different level. For sounds whose loudness depends on what
265 /// happened -- how hard a hit landed, a volume setting -- rather than on
266 /// which sample it is.
267 pub const fn with_volume(mut self, volume: Volume) -> Self {
268 self.volume = volume;
269 self
270 }
271
272 /// Override the envelope.
273 pub const fn with_adsr(mut self, adsr: Adsr) -> Self {
274 self.adsr = adsr;
275 self
276 }
277
278 /// Play at an explicit pitch instead of the sample's own rate. `0x1000` is
279 /// unity; lower stretches the sound and raises how long it lasts, which
280 /// [`OneShot::ticks`] accounts for.
281 pub const fn with_pitch(mut self, pitch: Pitch) -> Self {
282 self.pitch = Some(pitch);
283 self
284 }
285
286 /// The sample behind this one-shot.
287 pub const fn sample(&self) -> Sample {
288 self.sample
289 }
290
291 /// How long this will sound, in ticks of a `ticks_hz` clock, with any
292 /// pitch override applied. `None` when the sample's length is unknown.
293 pub const fn ticks(&self, ticks_hz: u32) -> Option<u32> {
294 let Some(base) = self.sample.ticks_at(ticks_hz) else {
295 return None;
296 };
297 match self.pitch {
298 // Pitch is Q4.12, so unity is 0x1000: half the pitch is twice the
299 // duration. Guard the zero a caller could hand us rather than
300 // dividing by it.
301 //
302 // Clamped, because the hardware clamps. Pitch::raw takes any u16
303 // but silicon caps the register at 0x3FFF: the 2026-08-03 SB2
304 // capture played 0x3FFF and 0x5000 back at the same 15169 Hz. A
305 // cutoff timed off the requested 0x5000 would expect the sound to
306 // finish in four fifths of the time it actually takes, and clip it.
307 Some(p) => {
308 let requested = p.raw_value();
309 let cap = Pitch::MAX.raw_value();
310 let raw = if requested > cap { cap } else { requested };
311 match raw {
312 0 => Some(base),
313 raw => Some(base * 0x1000 / raw as u32),
314 }
315 }
316 None => Some(base),
317 }
318 }
319
320 /// Point `voice` at this one-shot without starting it.
321 ///
322 /// Separate from [`OneShot::play`] because a program that keeps one voice
323 /// per sound can set it up once at boot and then only key on. A program
324 /// sharing voices has to do both together.
325 pub fn configure(&self, voice: Voice) {
326 voice.configure_sample(
327 self.sample.addr,
328 self.sample.rate_hz,
329 self.volume,
330 self.adsr,
331 );
332 if let Some(pitch) = self.pitch {
333 voice.set_pitch(pitch);
334 }
335 }
336
337 /// Key this one-shot on `voice`.
338 ///
339 /// Volume is set on every key-on rather than once at upload, because the
340 /// cutoff silences a voice by writing volume 0 and `start` does not
341 /// restore it. Omitting this is how the demo disc's v0.11 pressing ended
342 /// up with a browse blip that played exactly once and never again.
343 pub fn play(&self, voice: Voice) {
344 self.configure(voice);
345 Voice::start(voice.mask());
346 }
347}
348
349/// A resident ADPCM sample whose cooked block flags form a hardware loop.
350///
351/// The sample must carry a LOOP-START block and an END|REPEAT block. This
352/// handle owns the common voice setup and key-on policy, while the caller may
353/// update the voice's left and right volumes each frame for spatial audio.
354#[derive(Clone, Copy)]
355pub struct LoopingSample {
356 sample: Sample,
357 volume: Volume,
358 adsr: Adsr,
359 pitch: Option<Pitch>,
360}
361
362impl LoopingSample {
363 /// A loop at its recorded rate and a sustained full-level envelope.
364 pub const fn new(sample: Sample, volume: Volume) -> Self {
365 Self {
366 sample,
367 volume,
368 adsr: Adsr::default_tone(),
369 pitch: None,
370 }
371 }
372
373 /// Change the initial equal left/right level used at key-on.
374 pub const fn with_volume(mut self, volume: Volume) -> Self {
375 self.volume = volume;
376 self
377 }
378
379 /// Override the sustained envelope.
380 pub const fn with_adsr(mut self, adsr: Adsr) -> Self {
381 self.adsr = adsr;
382 self
383 }
384
385 /// Override playback pitch. `0x1000` is unity.
386 pub const fn with_pitch(mut self, pitch: Pitch) -> Self {
387 self.pitch = Some(pitch);
388 self
389 }
390
391 /// The resident sample behind this loop.
392 pub const fn sample(&self) -> Sample {
393 self.sample
394 }
395
396 /// Configure `voice` without starting it.
397 pub fn configure(&self, voice: Voice) {
398 voice.configure_sample(
399 self.sample.addr,
400 self.sample.rate_hz,
401 self.volume,
402 self.adsr,
403 );
404 if let Some(pitch) = self.pitch {
405 voice.set_pitch(pitch);
406 }
407 }
408
409 /// Configure and start this hardware loop on `voice`.
410 pub fn play(&self, voice: Voice) {
411 self.configure(voice);
412 Voice::start(voice.mask());
413 }
414
415 /// Stop a loop and silence its voice immediately.
416 pub fn stop(voice: Voice) {
417 voice.set_volume(Volume::SILENCE, Volume::SILENCE);
418 Voice::release(voice.mask());
419 }
420}
421
422/// Has `now` reached `deadline`, on a tick counter that wraps?
423///
424/// Split out so the wrap is testable off-hardware. A plain `now >= deadline`
425/// stops working the first time the counter rolls over, which on a 60 Hz clock
426/// is a little over two years of uptime, but the comparison costs the same
427/// either way.
428const fn expired(now: u32, deadline: u32) -> bool {
429 now.wrapping_sub(deadline) < u32::MAX / 2
430}
431
432/// Plays one-shots across a fixed set of voices, silencing each when its
433/// sample has run out.
434///
435/// `N` voices are driven round-robin by [`Player::play`], or addressed
436/// directly by [`Player::play_on`] when a sound wants a voice of its own.
437pub struct Player<const N: usize> {
438 voices: [Voice; N],
439 /// Tick each voice must be silenced on, or `None` when it is idle.
440 off_at: [Option<u32>; N],
441 next: usize,
442 ticks_hz: u32,
443}
444
445impl<const N: usize> Player<N> {
446 /// Drive `voices` from a clock running at `ticks_hz` (60 for NTSC frames,
447 /// 50 for PAL).
448 pub const fn new(voices: [Voice; N], ticks_hz: u32) -> Self {
449 Self {
450 voices,
451 off_at: [None; N],
452 next: 0,
453 ticks_hz,
454 }
455 }
456
457 /// Silence any voice whose sample has ended. Call once per tick, before
458 /// anything that might start a new sound.
459 pub fn tick(&mut self, now: u32) {
460 for (slot, deadline) in self.off_at.iter_mut().enumerate() {
461 if let Some(at) = *deadline {
462 if expired(now, at) {
463 self.voices[slot].set_volume(Volume::SILENCE, Volume::SILENCE);
464 *deadline = None;
465 }
466 }
467 }
468 }
469
470 /// Fire `shot` on a specific voice slot.
471 ///
472 /// A shot whose sample has no recorded length gets no cutoff: the voice
473 /// runs until its envelope finishes it, which is what every one-shot did
474 /// before this crate existed.
475 pub fn play_on(&mut self, slot: usize, shot: &OneShot, now: u32) {
476 let voice = self.voices[slot];
477 shot.play(voice);
478 self.off_at[slot] = shot.ticks(self.ticks_hz).map(|t| now.wrapping_add(t));
479 }
480
481 /// Fire `shot` on the next voice in the rotation, and return which slot
482 /// took it.
483 ///
484 /// Round-robin rather than picking an idle voice: finding the idle one
485 /// costs a scan, and a rotation of a few voices means a new sound rarely
486 /// lands on one that is still sounding anyway.
487 pub fn play(&mut self, shot: &OneShot, now: u32) -> usize {
488 let slot = self.next;
489 self.next = (self.next + 1) % N;
490 self.play_on(slot, shot, now);
491 slot
492 }
493
494 /// Silence every voice now, whatever it was doing.
495 pub fn silence_all(&mut self) {
496 for (slot, voice) in self.voices.iter().enumerate() {
497 voice.set_volume(Volume::SILENCE, Volume::SILENCE);
498 self.off_at[slot] = None;
499 }
500 }
501
502 /// The voice in `slot`.
503 pub const fn voice(&self, slot: usize) -> Voice {
504 self.voices[slot]
505 }
506}
507
508#[cfg(test)]
509mod tests {
510 use super::*;
511
512 fn sample(rate_hz: u32, frames: u32) -> Sample {
513 Sample {
514 addr: SpuAddr::new(0x1010),
515 rate_hz,
516 frames,
517 }
518 }
519
520 #[test]
521 fn the_parking_block_ends_repeats_and_marks_a_loop_start() {
522 // LOOP-START is the bit that separates this from psx-spu's shared
523 // silence block, which the browse voice ran straight past on silicon
524 // despite the repeat register naming it. The hardware latches the
525 // repeat address off a block carrying 0x04 as it decodes it, which
526 // owes nothing to a register written before key-on.
527 assert_eq!(PARKING_TAIL[1] & 0x01, 0x01, "END");
528 assert_eq!(PARKING_TAIL[1] & 0x02, 0x02, "REPEAT");
529 assert_eq!(PARKING_TAIL[1] & 0x04, 0x04, "LOOP-START");
530 assert_eq!(PARKING_TAIL[0], 0x00, "shift and filter zero");
531 assert!(
532 PARKING_TAIL[2..].iter().all(|&b| b == 0),
533 "decodes to silence"
534 );
535 }
536
537 #[test]
538 fn a_samples_length_follows_its_block_count_and_rate() {
539 // 126 blocks at 44100 Hz is ui_beep: 3528 samples, 0.08 s, so five
540 // ticks of a 60 Hz clock once the margin is on.
541 let s = sample(44100, 126);
542 assert_eq!(s.len_samples(), 3528);
543 assert_eq!(s.ticks_at(60), Some(3528 * 60 / 44100 + TAIL_TICKS));
544 }
545
546 #[test]
547 fn a_zero_rate_sample_does_not_divide_by_zero() {
548 assert_eq!(sample(0, 10).ticks_at(60), Some(10 * 28 * 60 + TAIL_TICKS));
549 }
550
551 #[test]
552 fn stretching_the_pitch_stretches_the_cutoff() {
553 let s = sample(44100, 394); // jump, 0.25 s
554 let plain = OneShot::new(s, Volume::MAX);
555 let half = plain.with_pitch(Pitch::raw(0x0800));
556 // Half the pitch is twice the duration, so the cutoff has to wait
557 // twice as long or it clips the sound it is meant to be following.
558 assert_eq!(half.ticks(60).unwrap(), plain.ticks(60).unwrap() * 2);
559 }
560
561 #[test]
562 fn a_pitch_above_the_hardware_ceiling_is_timed_at_the_ceiling() {
563 // SB2 played 0x3FFF and 0x5000 back at the same 15169 Hz on silicon.
564 // Timing the cutoff off 0x5000 would cut the sound at four fifths.
565 let s = sample(44100, 394);
566 let asked = OneShot::new(s, Volume::MAX).with_pitch(Pitch::raw(0x5000));
567 let capped = OneShot::new(s, Volume::MAX).with_pitch(Pitch::MAX);
568 assert_eq!(asked.ticks(60), capped.ticks(60));
569 }
570
571 #[test]
572 fn a_zero_pitch_falls_back_rather_than_dividing_by_zero() {
573 let s = sample(44100, 394);
574 let shot = OneShot::new(s, Volume::MAX).with_pitch(Pitch::raw(0));
575 assert_eq!(shot.ticks(60), s.ticks_at(60));
576 }
577
578 #[test]
579 fn a_sample_of_unknown_length_gets_no_cutoff() {
580 // VoXide's cooked bank records an offset and a rate but no block
581 // count, so there is nothing to compute a deadline from. Better to
582 // say so than to invent a length and clip the sound.
583 let s = Sample::resident(SpuAddr::new(0x1010), 22050, 0);
584 assert_eq!(s.ticks_at(60), None);
585 assert_eq!(OneShot::new(s, Volume::MAX).ticks(60), None);
586 }
587
588 #[test]
589 fn a_loop_keeps_its_resident_sample() {
590 let resident = sample(11025, 73);
591 assert_eq!(
592 LoopingSample::new(resident, Volume::HALF).sample(),
593 resident
594 );
595 }
596
597 #[test]
598 fn the_cutoff_survives_the_tick_counter_wrapping() {
599 assert!(!expired(10, 20));
600 assert!(expired(20, 20));
601 assert!(expired(21, 20));
602 // Deadline set just before the counter rolls over, checked just
603 // after: the naive `now >= deadline` says "not yet" here and leaves
604 // the voice running for the rest of time.
605 assert!(!expired(u32::MAX - 5, u32::MAX - 2));
606 assert!(expired(2, u32::MAX - 2));
607 }
608}