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

psx_seq/
lib.rs

1//! Sequenced music for the PS1 SPU.
2//!
3//! `psx-seq` plays songs written in the bytecode that Nintendo 64 games such
4//! as Ocarina of Time use for their music: one *sequence* script starts up to
5//! sixteen *channel* scripts, each channel starts up to four *layer* scripts,
6//! and the layers hold the notes. Scripts branch, loop, call, read and write
7//! IO ports the game also reads and writes, and so can follow the player:
8//! mute a channel, change the tune with the time of day, fade a part in with
9//! distance. That interactivity is why the bytecode runs at play time instead
10//! of being flattened to a list of notes.
11//!
12//! The engine is `no_std`, has no heap, no floating point and no 64-bit
13//! arithmetic. Sound goes out through [`psx_sfx::hw::Hw`], the same seam the
14//! sound-effect mixer uses, so on a host a `Recorder` captures every register
15//! write in order.
16//!
17//! # Time
18//!
19//! The engine advances in *updates* at [`UPDATE_HZ`] (180 per second). The
20//! caller owns the clock: [`Sequencer::pump`] takes the number of updates
21//! that have elapsed on whatever clock it has (a timer interrupt, the
22//! HBlank counter polled from a wait loop) and runs the ones that are due.
23//! After a long stall it runs at most [`MAX_CATCH_UP`] and drops the rest, so
24//! a slow frame sounds like a gap in the music, not a stampede of notes.
25//!
26//! # Fixed point
27//!
28//! Gains are Q15 (32768 = 1.0), pitch multipliers Q16 (65536 = 1.0), the
29//! envelope Q24. The original squares most volume terms (note velocity,
30//! channel volume, envelope level); that curve is kept because it is what
31//! shapes the dynamics.
32//!
33//! # Example
34//!
35//! A one-channel song (a hand-assembled sequence: `initchan`, `ldchan`,
36//! `tempo`, `vol`, then a channel that picks instrument 0, plays a note on
37//! layer 0 and ends) over an empty bank plays no sound but runs without error:
38//!
39//! ```
40//! use psx_seq::Sequencer;
41//! use psx_sfx::hw::Recorder;
42//!
43//! let mut hw = Recorder::<64>::new();
44//! let mut seq: Sequencer<'_, 1, 4> = Sequencer::new(0b1111);
45//! seq.update(&mut hw);
46//! assert!(hw.events().is_empty());
47//! ```
48
49#![cfg_attr(not(test), no_std)]
50#![warn(missing_docs)]
51
52mod engine;
53pub mod format;
54mod live;
55mod note;
56mod script;
57pub mod tables;
58mod types;
59
60pub use live::NoteHandle;
61pub use types::{CHANNELS, IO_NONE, IO_PORTS, LAYERS};
62
63use format::{Bank, FormatError, SongHeader, NONE16};
64use psx_sfx::hw::Hw;
65use types::*;
66
67/// Updates per second.
68pub const UPDATE_HZ: u32 = 180;
69
70/// Largest number of updates [`Sequencer::pump`] runs in one call.
71pub const MAX_CATCH_UP: u32 = 12;
72
73/// Tempo accumulator ceiling: updates per minute. A player at `bpm` runs
74/// `bpm * 48 / 60` script ticks per second.
75pub(crate) const MAX_TEMPO: u16 = (UPDATE_HZ * 60) as u16;
76
77/// Why a song would not start.
78#[derive(Clone, Copy, Debug, PartialEq, Eq)]
79pub enum StartError {
80    /// No bank is loaded.
81    NoBank,
82    /// The song container is malformed.
83    BadSong(FormatError),
84    /// There is no such player.
85    NoSuchPlayer,
86}
87
88/// The sequencer: `P` players sharing `N` voices.
89///
90/// Players are independent songs (background music, a fanfare over it, an
91/// overlay); each has its own tempo, IO ports and fade, and they compete for
92/// the same `N` voices by note priority.
93pub struct Sequencer<'a, const P: usize, const N: usize> {
94    pub(crate) players: [Player; P],
95    pub(crate) codes: [&'a mut [u8]; P],
96    pub(crate) notes: [Note; N],
97    pub(crate) voice_of: [u8; N],
98    pub(crate) bank: Option<Bank<'a>>,
99    pub(crate) spu_base: u32,
100    pub(crate) master_q12: u16,
101    pub(crate) rng: u32,
102    pub(crate) order: u32,
103    pub(crate) pos_min: i32,
104    pub(crate) pos_max: i32,
105    pub(crate) unsupported: u32,
106    clock: Option<u32>,
107}
108
109impl<'a, const P: usize, const N: usize> Sequencer<'a, P, N> {
110    /// A sequencer over the voices set in `voice_mask`, which must have
111    /// exactly `N` bits set.
112    ///
113    /// The sequencer is several kilobytes: a game that keeps one in a
114    /// `static` should build it in place with [`Sequencer::init_at`] and not
115    /// pass this return value through its stack.
116    ///
117    /// # Panics
118    ///
119    /// If `voice_mask` does not have `N` bits set.
120    pub fn new(voice_mask: u32) -> Self {
121        let mut slot = core::mem::MaybeUninit::<Self>::uninit();
122        // SAFETY: `init_at` writes every field of the sequencer it is given.
123        unsafe {
124            Self::init_at(slot.as_mut_ptr(), voice_mask);
125            slot.assume_init()
126        }
127    }
128
129    /// Build a sequencer over the voices set in `voice_mask` (exactly `N`
130    /// bits) directly in `slot`, field by field, without a copy of it on the
131    /// stack.
132    ///
133    /// # Safety
134    ///
135    /// `slot` must be valid for writes of a `Sequencer` and aligned for one;
136    /// whatever it held is overwritten without being read or dropped.
137    ///
138    /// # Panics
139    ///
140    /// If `voice_mask` does not have `N` bits set.
141    pub unsafe fn init_at(slot: *mut Self, voice_mask: u32) {
142        use core::ptr::addr_of_mut;
143        assert_eq!(
144            voice_mask.count_ones() as usize,
145            N,
146            "voice mask must have N bits"
147        );
148        // SAFETY: the caller guarantees `slot` is valid and aligned; every field is written once
149        // through a raw place, without forming a reference to the uninitialised sequencer.
150        unsafe {
151            let mut k = 0;
152            for v in 0..24u8 {
153                if voice_mask & (1 << v) != 0 {
154                    addr_of_mut!((*slot).voice_of[k]).write(v);
155                    k += 1;
156                }
157            }
158            for p in 0..P {
159                Player::init_at(addr_of_mut!((*slot).players[p]));
160                (*slot).players[p].enabled = false;
161                addr_of_mut!((*slot).codes[p]).write(<&mut [u8]>::default());
162            }
163            for n in 0..N {
164                addr_of_mut!((*slot).notes[n]).write(Note::INIT);
165            }
166            addr_of_mut!((*slot).bank).write(None);
167            addr_of_mut!((*slot).spu_base).write(0);
168            addr_of_mut!((*slot).master_q12).write(4096);
169            addr_of_mut!((*slot).rng).write(0x1234_5678);
170            addr_of_mut!((*slot).order).write(0);
171            addr_of_mut!((*slot).pos_min).write(0);
172            addr_of_mut!((*slot).pos_max).write(0);
173            addr_of_mut!((*slot).unsupported).write(0);
174            addr_of_mut!((*slot).clock).write(None);
175        }
176    }
177
178    /// Use `bank` for instruments. `spu_base` is where its ADPCM region was
179    /// uploaded in SPU RAM.
180    pub fn set_bank(&mut self, bank: Bank<'a>, spu_base: u32) {
181        self.bank = Some(bank);
182        self.spu_base = spu_base;
183    }
184
185    /// The font index in the bank whose id is `id`.
186    pub(crate) fn font_index(&self, id: u8) -> Option<u8> {
187        self.bank?.font_index(id)
188    }
189
190    /// Start `song` on `player`. `song` is the whole container as loaded;
191    /// songs that patch themselves need it in RAM.
192    pub fn start(&mut self, player: usize, song: &'a mut [u8]) -> Result<(), StartError> {
193        if player >= P {
194            return Err(StartError::NoSuchPlayer);
195        }
196        if self.bank.is_none() {
197            return Err(StartError::NoBank);
198        }
199        let header = SongHeader::parse(song).map_err(StartError::BadSong)?;
200        self.disable_player(player);
201        let code = header.code_mut(song);
202        self.codes[player] = code;
203        let n_fonts = header.n_fonts;
204        let fonts = header.font_ids;
205        let last = fonts[n_fonts.saturating_sub(1) as usize];
206        let default_font = if n_fonts > 0 {
207            self.font_index(last).unwrap_or(NONE8)
208        } else {
209            NONE8
210        };
211        // SAFETY: the slot is a valid, aligned `Player` owned by `self`; `init_at` overwrites it
212        // without reading it. Built in place: a `Player` is seven kilobytes, and a copy of it on
213        // the stack costs the caller that much for the whole call.
214        unsafe { Player::init_at(&raw mut self.players[player]) };
215        let pl = &mut self.players[player];
216        pl.n_fonts = n_fonts;
217        pl.fonts = fonts;
218        pl.default_font = default_font;
219        pl.enabled = true;
220        pl.state = 1;
221        for c in 0..CHANNELS {
222            pl.channels[c].font = default_font;
223        }
224        Ok(())
225    }
226
227    /// Stop `player`, fading its volume to nothing over `fade_updates`
228    /// updates first (0 stops now; held notes release at their own rate).
229    pub fn stop(&mut self, player: usize, fade_updates: u16) {
230        if player >= P || !self.players[player].enabled {
231            return;
232        }
233        if fade_updates == 0 {
234            self.disable_player(player);
235            return;
236        }
237        let pl = &mut self.players[player];
238        pl.fade_timer = fade_updates;
239        pl.state = 2;
240        pl.fade_vel_q24 = -pl.fade_q24 / fade_updates as i32;
241    }
242
243    /// Is `player` still running its song?
244    pub fn is_playing(&self, player: usize) -> bool {
245        player < P && self.players[player].enabled
246    }
247
248    /// Voices that are not free.
249    pub fn voices_in_use(&self) -> u32 {
250        self.notes
251            .iter()
252            .filter(|n| n.list != NoteList::Disabled)
253            .count() as u32
254    }
255
256    /// Opcodes met so far that this engine does not implement.
257    pub fn unsupported_ops(&self) -> u32 {
258        self.unsupported
259    }
260
261    /// Write a sequence-level IO port (what `ldio` in the song reads).
262    pub fn set_player_io(&mut self, player: usize, port: usize, value: u8) {
263        if player < P && port < IO_PORTS {
264            self.players[player].io[port] = value;
265        }
266    }
267
268    /// Read back a sequence-level IO port (what `stio` in the song wrote).
269    pub fn player_io(&self, player: usize, port: usize) -> Option<u8> {
270        let v = *self.players.get(player)?.io.get(port)?;
271        (v != IO_NONE).then_some(v)
272    }
273
274    /// Write a channel IO port.
275    pub fn set_channel_io(&mut self, player: usize, channel: usize, port: usize, value: u8) {
276        if player < P && channel < CHANNELS && port < IO_PORTS {
277            self.players[player].channels[channel].io[port] = value;
278        }
279    }
280
281    /// Read back a channel IO port.
282    pub fn channel_io(&self, player: usize, channel: usize, port: usize) -> Option<u8> {
283        let v = *self
284            .players
285            .get(player)?
286            .channels
287            .get(channel)?
288            .io
289            .get(port)?;
290        (v != IO_NONE).then_some(v)
291    }
292
293    /// Mute (set bits) or unmute channels of `player`. Muted channels start no
294    /// new notes.
295    pub fn set_channel_mute(&mut self, player: usize, mask: u16) {
296        if player < P {
297            for c in 0..CHANNELS {
298                self.players[player].channels[c].muted = mask & (1 << c) != 0;
299            }
300        }
301    }
302
303    /// Fade `player`'s volume to `target_q15` (32768 = full) over `updates`.
304    pub fn fade_to(&mut self, player: usize, target_q15: u16, updates: u16) {
305        if player >= P {
306            return;
307        }
308        let pl = &mut self.players[player];
309        let target = (target_q15 as i32) << 9;
310        if updates == 0 {
311            pl.fade_q24 = target;
312            pl.fade_timer = 0;
313        } else {
314            pl.fade_timer = updates;
315            pl.fade_vel_q24 = (target - pl.fade_q24) / updates as i32;
316        }
317        pl.recalc_volume = true;
318    }
319
320    /// Set the output gain applied to every voice (`4096` = 1.0). The game
321    /// passes the music volume times the duck gain from `psx_sfx::master`.
322    pub fn set_master(&mut self, q12: u16) {
323        self.master_q12 = q12;
324    }
325
326    /// Mute or unmute a whole player (what the pause menu does). Behaviour
327    /// follows the song's mute settings: by default notes stop and the rest is
328    /// softened.
329    pub fn set_player_muted(&mut self, player: usize, muted: bool) {
330        if player < P {
331            self.players[player].muted = muted;
332            self.players[player].recalc_volume = true;
333        }
334    }
335
336    /// Run the updates due at `now` (a count of [`UPDATE_HZ`] updates on the
337    /// caller's clock). The first call only sets the clock.
338    pub fn pump(&mut self, hw: &mut impl Hw, now: u32) {
339        let Some(last) = self.clock else {
340            self.clock = Some(now);
341            return;
342        };
343        let due = now.wrapping_sub(last);
344        if due == 0 || due > u32::MAX / 2 {
345            return;
346        }
347        let run = due.min(MAX_CATCH_UP);
348        self.clock = Some(now);
349        for _ in 0..run {
350            self.update(hw);
351        }
352    }
353
354    /// Run exactly one update.
355    pub fn update(&mut self, hw: &mut impl Hw) {
356        self.next_random();
357        for p in 0..P {
358            if self.players[p].enabled {
359                self.step_player(p);
360            }
361        }
362        self.process_notes(hw);
363    }
364
365    /// Key off every voice and forget all notes (before overwriting the
366    /// sample region in SPU RAM).
367    pub fn silence(&mut self, hw: &mut impl Hw) {
368        for p in 0..P {
369            self.disable_player(p);
370        }
371        for n in 0..N {
372            let v = self.voice_of[n];
373            if self.notes[n].keyed {
374                hw.set_volume(v, 0, 0);
375                hw.key_off(1 << v);
376            }
377            self.notes[n] = Note::INIT;
378        }
379    }
380
381    /// Whether the song header says `flag`.
382    pub fn song_flags(bytes: &[u8]) -> Result<u16, FormatError> {
383        SongHeader::parse(bytes).map(|h| h.flags)
384    }
385}
386
387#[allow(dead_code)]
388const _: u16 = NONE16;
389
390#[cfg(test)]
391mod tests;