psx_seq/format.rs
1//! The two containers: a song (`PSQ1`) and a bank set (`PSQB`).
2//!
3//! A **song** is the sequence bytecode, byte for byte, behind a short header.
4//! The bytecode keeps its original big-endian operands and absolute offsets,
5//! because jumps, calls, layer loads and envelope pointers all refer to
6//! positions inside it. The header is little-endian.
7//!
8//! ```text
9//! 0 "PSQ1"
10//! 4 u16 version = 1
11//! 6 u16 flags bit0 patches itself, bit1 reads IO, bit2 uses runseq
12//! 8 u8 n_fonts u8 peak_voices u16 code_len u16 channels_used u16 reserved
13//! 16 u8 font_id[n_fonts] padded with zeros to a multiple of 4
14//! .. bytecode (code_len bytes)
15//! ```
16//!
17//! A **bank** is everything a scene's songs play: instrument and drum
18//! tables, envelopes, a sample table and the SPU-ADPCM data, laid out so the
19//! ADPCM region goes to SPU RAM in one transfer. All little-endian except the
20//! envelope words, which keep the bytecode's big-endian layout so a song's own
21//! envelopes and the bank's read through one reader.
22//!
23//! ```text
24//! 0 "PSQB" u16 version = 1 u16 flags u32 total_bytes
25//! 12 u16 n_fonts u16 n_samples u16 n_env_words u16 reserved
26//! 20 u32 off_fonts u32 off_samples u32 off_env u32 off_adpcm u32 adpcm_bytes
27//! FontDesc[n_fonts] (12 B) u8 id, u8 n_inst, u8 n_drum, u8 pad, u32 off_inst, u32 off_drum
28//! InstDesc (32 B) u8 lo, u8 hi, u8 decay, u8 present, u16 env, u16 pad,
29//! 3 x { u16 sample, u16 pad, u32 tuning_q16 } (low, normal, high)
30//! DrumDesc (16 B) u8 decay, u8 pan, u16 env, u16 sample, u16 present, u32 tuning_q16, u32 pad
31//! SampleDesc (16 B) u32 adpcm_off, u32 end_samples, u16 blocks, u16 rate_hz, u16 loop_block, u16 flags
32//! ```
33//!
34//! `tuning_q16` already includes the ratio of the original 32 kHz playback
35//! rate to the cooked rate and the loop-stretch correction, so the runtime
36//! multiplies one number. `0xFFFF` means "none" for sample and envelope
37//! indices.
38
39use psx_sfx::Sample;
40use psx_spu::SpuAddr;
41
42/// Song magic.
43pub const SONG_MAGIC: [u8; 4] = *b"PSQ1";
44/// Bank magic.
45pub const BANK_MAGIC: [u8; 4] = *b"PSQB";
46/// "No sample" / "no envelope" marker.
47pub const NONE16: u16 = 0xffff;
48/// Song flag: the bytecode writes to itself.
49pub const FLAG_SELF_MODIFYING: u16 = 1;
50
51/// Reasons a container is rejected.
52#[derive(Clone, Copy, Debug, PartialEq, Eq)]
53pub enum FormatError {
54 /// Wrong magic or version.
55 BadHeader,
56 /// A table runs past the end of the data.
57 Truncated,
58}
59
60fn le16(b: &[u8], at: usize) -> Option<u16> {
61 Some(u16::from_le_bytes([*b.get(at)?, *b.get(at + 1)?]))
62}
63
64fn le32(b: &[u8], at: usize) -> Option<u32> {
65 Some(u32::from_le_bytes([
66 *b.get(at)?,
67 *b.get(at + 1)?,
68 *b.get(at + 2)?,
69 *b.get(at + 3)?,
70 ]))
71}
72
73/// The parsed header of a song.
74#[derive(Clone, Copy, Debug, PartialEq, Eq)]
75pub struct SongHeader {
76 /// Flag bits.
77 pub flags: u16,
78 /// Number of soundfont ids.
79 pub n_fonts: u8,
80 /// Voices the song needs at most (measured by the cook).
81 pub peak_voices: u8,
82 /// Bytes of bytecode.
83 pub code_len: u16,
84 /// Soundfont ids, in the original table order (slot `s` is `n - 1 - s`).
85 pub font_ids: [u8; 8],
86 /// Offset of the bytecode in the file.
87 pub code_off: u16,
88}
89
90impl SongHeader {
91 /// Parse the header of `bytes`.
92 ///
93 /// ```
94 /// use psx_seq::format::*;
95 /// let mut f = vec![];
96 /// f.extend_from_slice(b"PSQ1");
97 /// f.extend_from_slice(&[1, 0, 0, 0, 1, 6, 2, 0, 1, 0, 0, 0]);
98 /// f.extend_from_slice(&[7, 0, 0, 0]);
99 /// f.extend_from_slice(&[0xFF, 0xFF]);
100 /// let h = SongHeader::parse(&f).unwrap();
101 /// assert_eq!((h.n_fonts, h.peak_voices, h.code_len, h.font_ids[0]), (1, 6, 2, 7));
102 /// assert_eq!(h.code_off, 20);
103 /// ```
104 pub fn parse(bytes: &[u8]) -> Result<Self, FormatError> {
105 if bytes.get(0..4) != Some(&SONG_MAGIC) || le16(bytes, 4) != Some(1) {
106 return Err(FormatError::BadHeader);
107 }
108 let flags = le16(bytes, 6).ok_or(FormatError::Truncated)?;
109 let n_fonts = *bytes.get(8).ok_or(FormatError::Truncated)?;
110 let peak_voices = *bytes.get(9).ok_or(FormatError::Truncated)?;
111 let code_len = le16(bytes, 10).ok_or(FormatError::Truncated)?;
112 if n_fonts as usize > 8 {
113 return Err(FormatError::BadHeader);
114 }
115 let mut font_ids = [0xff; 8];
116 for (i, f) in font_ids.iter_mut().enumerate().take(n_fonts as usize) {
117 *f = *bytes.get(16 + i).ok_or(FormatError::Truncated)?;
118 }
119 let code_off = 16 + ((n_fonts as usize + 3) & !3);
120 if bytes.len() < code_off + code_len as usize {
121 return Err(FormatError::Truncated);
122 }
123 Ok(Self {
124 flags,
125 n_fonts,
126 peak_voices,
127 code_len,
128 font_ids,
129 code_off: code_off as u16,
130 })
131 }
132
133 /// The bytecode inside `bytes`.
134 pub fn code<'a>(&self, bytes: &'a [u8]) -> &'a [u8] {
135 &bytes[self.code_off as usize..self.code_off as usize + self.code_len as usize]
136 }
137
138 /// The bytecode inside `bytes`, writable (songs that patch themselves
139 /// need RAM; the file is normally loaded into RAM anyway).
140 pub fn code_mut<'a>(&self, bytes: &'a mut [u8]) -> &'a mut [u8] {
141 &mut bytes[self.code_off as usize..self.code_off as usize + self.code_len as usize]
142 }
143}
144
145/// A sample and its tuning, as an instrument or drum names it.
146#[derive(Clone, Copy, Debug, PartialEq, Eq)]
147pub struct Tuned {
148 /// Index into the bank's sample table, or [`NONE16`].
149 pub sample: u16,
150 /// Pitch multiplier, Q16.
151 pub tuning_q16: u32,
152}
153
154/// An instrument.
155#[derive(Clone, Copy, Debug, PartialEq, Eq)]
156pub struct Instrument {
157 /// Keys below this use `low`.
158 pub range_lo: u8,
159 /// Keys above this use `high`.
160 pub range_hi: u8,
161 /// Release rate index.
162 pub decay: u8,
163 /// Envelope start (word index into the bank) or [`NONE16`].
164 pub env: u16,
165 /// Sample for the low range.
166 pub low: Tuned,
167 /// Sample for the normal range.
168 pub normal: Tuned,
169 /// Sample for the high range.
170 pub high: Tuned,
171}
172
173impl Instrument {
174 /// The sample entry for `key`.
175 pub fn for_key(&self, key: u8) -> Tuned {
176 if key < self.range_lo {
177 self.low
178 } else if key <= self.range_hi {
179 self.normal
180 } else {
181 self.high
182 }
183 }
184}
185
186/// A drum.
187#[derive(Clone, Copy, Debug, PartialEq, Eq)]
188pub struct Drum {
189 /// Release rate index.
190 pub decay: u8,
191 /// Fixed pan.
192 pub pan: u8,
193 /// Envelope start or [`NONE16`].
194 pub env: u16,
195 /// Its sample.
196 pub tuned: Tuned,
197}
198
199/// One cooked sample.
200#[derive(Clone, Copy, Debug, PartialEq, Eq)]
201pub struct SampleInfo {
202 /// Offset of its ADPCM data in the ADPCM region.
203 pub adpcm_off: u32,
204 /// Length of the original sample in samples (loop end), for notes with no
205 /// written length.
206 pub end_samples: u32,
207 /// ADPCM blocks.
208 pub blocks: u16,
209 /// Cooked sample rate in Hz.
210 pub rate_hz: u16,
211 /// Block the hardware loop re-enters, or [`NONE16`].
212 pub loop_block: u16,
213}
214
215/// A parsed bank.
216#[derive(Clone, Copy, Debug)]
217pub struct Bank<'a> {
218 bytes: &'a [u8],
219 n_fonts: u16,
220 n_samples: u16,
221 n_env_words: u16,
222 off_fonts: u32,
223 off_samples: u32,
224 off_env: u32,
225 off_adpcm: u32,
226 adpcm_bytes: u32,
227 /// Whether `bytes` includes the ADPCM region.
228 adpcm_held: bool,
229}
230
231impl<'a> Bank<'a> {
232 /// Parse `bytes`.
233 pub fn parse(bytes: &'a [u8]) -> Result<Self, FormatError> {
234 let b = Self::parse_header(bytes)?;
235 if b.off_adpcm as usize + b.adpcm_bytes as usize > bytes.len() {
236 return Err(FormatError::Truncated);
237 }
238 Ok(b)
239 }
240
241 /// Parse only the tables of a bank. `bytes` is the container up to the end of
242 /// the tables ([`Bank::tables_used`] bytes at least), without the ADPCM
243 /// region: a game that streams the samples from disc straight into SPU RAM
244 /// never holds them in main RAM. Everything works except [`Bank::adpcm`],
245 /// which returns an empty slice; [`Bank::adpcm_range`] says where the
246 /// region is in the full container.
247 ///
248 /// # Errors
249 /// As [`Bank::parse`], except that the ADPCM region need not be present.
250 ///
251 /// ```
252 /// use psx_seq::format::Bank;
253 /// let mut f = vec![0u8; 64];
254 /// f[..4].copy_from_slice(b"PSQB");
255 /// f[4] = 1;
256 /// f[28..32].copy_from_slice(&64u32.to_le_bytes()); // off_env
257 /// f[32..36].copy_from_slice(&64u32.to_le_bytes()); // off_adpcm
258 /// f[36..40].copy_from_slice(&4096u32.to_le_bytes()); // adpcm_bytes
259 /// assert!(Bank::parse(&f).is_err());
260 /// let b = Bank::parse_tables(&f).unwrap();
261 /// assert_eq!(b.adpcm_range(), (64, 4096));
262 /// assert!(b.adpcm().is_empty());
263 /// ```
264 pub fn parse_tables(bytes: &'a [u8]) -> Result<Self, FormatError> {
265 let mut b = Self::parse_header(bytes)?;
266 if b.tables_used() > bytes.len() {
267 return Err(FormatError::Truncated);
268 }
269 b.adpcm_held = b.off_adpcm as usize + b.adpcm_bytes as usize <= bytes.len();
270 Ok(b)
271 }
272
273 /// Bytes from the start of the container to the end of the last table
274 /// (envelopes included): what [`Bank::parse_tables`] needs resident. The
275 /// ADPCM region starts at or after this, at [`Bank::adpcm_range`].
276 #[must_use]
277 pub fn tables_used(&self) -> usize {
278 self.off_env as usize + 4 * self.n_env_words as usize
279 }
280
281 /// Where the ADPCM region sits in the full container, as
282 /// `(offset, length)` in bytes.
283 #[must_use]
284 pub fn adpcm_range(&self) -> (u32, u32) {
285 (self.off_adpcm, self.adpcm_bytes)
286 }
287
288 fn parse_header(bytes: &'a [u8]) -> Result<Self, FormatError> {
289 if bytes.get(0..4) != Some(&BANK_MAGIC) || le16(bytes, 4) != Some(1) {
290 return Err(FormatError::BadHeader);
291 }
292 let t = FormatError::Truncated;
293 let b = Self {
294 bytes,
295 n_fonts: le16(bytes, 12).ok_or(t)?,
296 n_samples: le16(bytes, 14).ok_or(t)?,
297 n_env_words: le16(bytes, 16).ok_or(t)?,
298 off_fonts: le32(bytes, 20).ok_or(t)?,
299 off_samples: le32(bytes, 24).ok_or(t)?,
300 off_env: le32(bytes, 28).ok_or(t)?,
301 off_adpcm: le32(bytes, 32).ok_or(t)?,
302 adpcm_bytes: le32(bytes, 36).ok_or(t)?,
303 adpcm_held: true,
304 };
305 Ok(b)
306 }
307
308 /// The ADPCM region, to upload to SPU RAM (empty for a bank parsed with
309 /// [`Bank::parse_tables`] over the tables alone).
310 pub fn adpcm(&self) -> &'a [u8] {
311 if !self.adpcm_held {
312 return &[];
313 }
314 &self.bytes[self.off_adpcm as usize..(self.off_adpcm + self.adpcm_bytes) as usize]
315 }
316
317 /// Number of samples.
318 pub fn sample_count(&self) -> u16 {
319 self.n_samples
320 }
321
322 /// Index of the font whose original id is `id`.
323 pub fn font_index(&self, id: u8) -> Option<u8> {
324 (0..self.n_fonts).find_map(|i| {
325 let at = self.off_fonts as usize + 12 * i as usize;
326 (*self.bytes.get(at)? == id).then_some(i as u8)
327 })
328 }
329
330 fn font_field(&self, font: u8, field: usize) -> Option<usize> {
331 ((font as u16) < self.n_fonts).then_some(())?;
332 Some(self.off_fonts as usize + 12 * font as usize + field)
333 }
334
335 /// Instrument `inst` of font index `font`.
336 pub fn instrument(&self, font: u8, inst: u8) -> Option<Instrument> {
337 let desc = self.font_field(font, 0)?;
338 if inst >= *self.bytes.get(desc + 1)? {
339 return None;
340 }
341 let at = le32(self.bytes, desc + 4)? as usize + 32 * inst as usize;
342 if *self.bytes.get(at + 3)? == 0 {
343 return None;
344 }
345 let tuned = |o: usize| -> Option<Tuned> {
346 Some(Tuned {
347 sample: le16(self.bytes, at + o)?,
348 tuning_q16: le32(self.bytes, at + o + 4)?,
349 })
350 };
351 Some(Instrument {
352 range_lo: *self.bytes.get(at)?,
353 range_hi: *self.bytes.get(at + 1)?,
354 decay: *self.bytes.get(at + 2)?,
355 env: le16(self.bytes, at + 4)?,
356 low: tuned(8)?,
357 normal: tuned(16)?,
358 high: tuned(24)?,
359 })
360 }
361
362 /// Drum `key` of font index `font`.
363 pub fn drum(&self, font: u8, key: u8) -> Option<Drum> {
364 let desc = self.font_field(font, 0)?;
365 if key >= *self.bytes.get(desc + 2)? {
366 return None;
367 }
368 let at = le32(self.bytes, desc + 8)? as usize + 16 * key as usize;
369 if le16(self.bytes, at + 6)? == 0 {
370 return None;
371 }
372 Some(Drum {
373 decay: *self.bytes.get(at)?,
374 pan: *self.bytes.get(at + 1)?,
375 env: le16(self.bytes, at + 2)?,
376 tuned: Tuned {
377 sample: le16(self.bytes, at + 4)?,
378 tuning_q16: le32(self.bytes, at + 8)?,
379 },
380 })
381 }
382
383 /// Sample `idx`.
384 pub fn sample(&self, idx: u16) -> Option<SampleInfo> {
385 if idx >= self.n_samples {
386 return None;
387 }
388 let at = self.off_samples as usize + 16 * idx as usize;
389 Some(SampleInfo {
390 adpcm_off: le32(self.bytes, at)?,
391 end_samples: le32(self.bytes, at + 4)?,
392 blocks: le16(self.bytes, at + 8)?,
393 rate_hz: le16(self.bytes, at + 10)?,
394 loop_block: le16(self.bytes, at + 12)?,
395 })
396 }
397
398 /// The resident [`Sample`] for `idx` when the ADPCM region sits at
399 /// `base` in SPU RAM.
400 pub fn resident(&self, idx: u16, base: u32) -> Option<Sample> {
401 let s = self.sample(idx)?;
402 Some(Sample::resident(
403 SpuAddr::new(base + s.adpcm_off),
404 s.rate_hz as u32,
405 s.blocks as u32,
406 ))
407 }
408
409 /// Envelope point `word` as `(delay, arg)`.
410 pub fn envelope_point(&self, word: u32) -> Option<(i16, i16)> {
411 if word >= self.n_env_words as u32 {
412 return None;
413 }
414 let at = self.off_env as usize + 4 * word as usize;
415 let b = self.bytes.get(at..at + 4)?;
416 Some((
417 i16::from_be_bytes([b[0], b[1]]),
418 i16::from_be_bytes([b[2], b[3]]),
419 ))
420 }
421}