psx_sfx/hw.rs
1//! The seam between sound bookkeeping and the SPU.
2//!
3//! Everything above layer 0 in this crate ([`crate::mixer`], [`crate::vloop`])
4//! decides *what* the 24 voices should be doing and never touches a register
5//! itself. It reports each decision through [`Hw`]. On the console an
6//! implementation of [`Hw`] forwards to `psx_spu::Voice`; on a host, and in
7//! emulator golden tests, [`Recorder`] logs the calls in order so a test can
8//! assert on exactly what would have been written, and in which order.
9//!
10//! The trait is deliberately the same size as the SPU's own per-voice surface,
11//! so each method is one to three register writes and a recording is a faithful
12//! write trace.
13
14use crate::Sample;
15
16/// What the mixer needs from a sound chip.
17///
18/// Voice numbers are `0..24`. Masks have bit `n` set for voice `n`.
19///
20/// # Example
21///
22/// ```
23/// use psx_sfx::hw::{Hw, NullHw};
24///
25/// let mut hw = NullHw;
26/// hw.key_off(0b101); // accepted and ignored
27/// ```
28pub trait Hw {
29 /// Point `voice` at `sample` without starting it. `looped` selects the
30 /// hardware-loop setup; a one-shot also gets its repeat address written so
31 /// it parks on silence. `pitch_q12` is a multiplier of the cooked rate
32 /// (`4096` plays it as recorded).
33 fn configure(&mut self, voice: u8, sample: &Sample, looped: bool, pitch_q12: u16);
34
35 /// Write a voice's left and right volume (signed SPU levels, already
36 /// scaled by the master volume).
37 fn set_volume(&mut self, voice: u8, left: i16, right: i16);
38
39 /// Change a playing voice's pitch multiplier (`4096` = as cooked).
40 fn set_pitch(&mut self, voice: u8, pitch_q12: u16);
41
42 /// Key on every voice in `mask`.
43 fn key_on(&mut self, mask: u32);
44
45 /// Key off (release) every voice in `mask`.
46 fn key_off(&mut self, mask: u32);
47}
48
49/// An [`Hw`] that ignores everything. Useful when only the bookkeeping is
50/// being measured.
51///
52/// # Example
53///
54/// ```
55/// use psx_sfx::hw::{Hw, NullHw};
56///
57/// NullHw.key_on(1);
58/// ```
59#[derive(Clone, Copy, Debug, Default)]
60pub struct NullHw;
61
62impl Hw for NullHw {
63 fn configure(&mut self, _voice: u8, _sample: &Sample, _looped: bool, _pitch_q12: u16) {}
64 fn set_volume(&mut self, _voice: u8, _left: i16, _right: i16) {}
65 fn set_pitch(&mut self, _voice: u8, _pitch_q12: u16) {}
66 fn key_on(&mut self, _mask: u32) {}
67 fn key_off(&mut self, _mask: u32) {}
68}
69
70/// One call made through [`Hw`], as [`Recorder`] logged it.
71#[derive(Clone, Copy, Debug, PartialEq, Eq)]
72pub enum Event {
73 /// [`Hw::configure`].
74 Configure {
75 /// Voice number.
76 voice: u8,
77 /// Byte offset of the sample in SPU RAM.
78 addr: u32,
79 /// The rate the sample was cooked at.
80 rate_hz: u32,
81 /// Hardware-loop setup rather than one-shot setup.
82 looped: bool,
83 /// Pitch multiplier, `4096` = as cooked.
84 pitch_q12: u16,
85 },
86 /// [`Hw::set_volume`].
87 Volume {
88 /// Voice number.
89 voice: u8,
90 /// Left level.
91 left: i16,
92 /// Right level.
93 right: i16,
94 },
95 /// [`Hw::set_pitch`].
96 Pitch {
97 /// Voice number.
98 voice: u8,
99 /// Pitch multiplier, `4096` = as cooked.
100 pitch_q12: u16,
101 },
102 /// [`Hw::key_on`] with this voice mask.
103 KeyOn(u32),
104 /// [`Hw::key_off`] with this voice mask.
105 KeyOff(u32),
106}
107
108/// An [`Hw`] that logs every call into a fixed buffer, in order.
109///
110/// It needs no heap, so it also runs on the console, where a golden test can
111/// compare the trace of two builds. When more than `CAP` calls arrive the
112/// extra ones are counted in [`dropped`](Self::dropped) and not stored.
113///
114/// # Example
115///
116/// ```
117/// use psx_sfx::hw::{Event, Hw, Recorder};
118///
119/// let mut rec = Recorder::<8>::new();
120/// rec.set_volume(3, 100, -100);
121/// rec.key_on(1 << 3);
122/// assert_eq!(
123/// rec.events(),
124/// &[
125/// Event::Volume { voice: 3, left: 100, right: -100 },
126/// Event::KeyOn(1 << 3),
127/// ]
128/// );
129/// ```
130#[derive(Clone, Debug)]
131pub struct Recorder<const CAP: usize> {
132 events: [Event; CAP],
133 len: usize,
134 dropped: u32,
135}
136
137impl<const CAP: usize> Recorder<CAP> {
138 /// An empty recorder.
139 ///
140 /// ```
141 /// # use psx_sfx::hw::Recorder;
142 /// assert!(Recorder::<4>::new().events().is_empty());
143 /// ```
144 pub const fn new() -> Self {
145 Self {
146 events: [Event::KeyOn(0); CAP],
147 len: 0,
148 dropped: 0,
149 }
150 }
151
152 /// Everything logged so far, oldest first.
153 ///
154 /// ```
155 /// # use psx_sfx::hw::{Event, Hw, Recorder};
156 /// let mut r = Recorder::<4>::new();
157 /// r.key_off(2);
158 /// assert_eq!(r.events(), &[Event::KeyOff(2)]);
159 /// ```
160 pub fn events(&self) -> &[Event] {
161 &self.events[..self.len]
162 }
163
164 /// Calls that arrived after the buffer filled and were not stored.
165 ///
166 /// ```
167 /// # use psx_sfx::hw::{Hw, Recorder};
168 /// let mut r = Recorder::<1>::new();
169 /// r.key_on(1);
170 /// r.key_on(2);
171 /// assert_eq!(r.dropped(), 1);
172 /// ```
173 pub const fn dropped(&self) -> u32 {
174 self.dropped
175 }
176
177 /// Forget everything logged so far.
178 ///
179 /// ```
180 /// # use psx_sfx::hw::{Hw, Recorder};
181 /// let mut r = Recorder::<4>::new();
182 /// r.key_on(1);
183 /// r.clear();
184 /// assert!(r.events().is_empty());
185 /// ```
186 pub fn clear(&mut self) {
187 self.len = 0;
188 self.dropped = 0;
189 }
190
191 /// Union of every voice that was keyed on since the last
192 /// [`clear`](Self::clear).
193 ///
194 /// ```
195 /// # use psx_sfx::hw::{Hw, Recorder};
196 /// let mut r = Recorder::<4>::new();
197 /// r.key_on(0b01);
198 /// r.key_on(0b10);
199 /// assert_eq!(r.keyed_on(), 0b11);
200 /// ```
201 pub fn keyed_on(&self) -> u32 {
202 self.events()
203 .iter()
204 .fold(0, |m, e| if let Event::KeyOn(k) = e { m | k } else { m })
205 }
206
207 /// Union of every voice that was keyed off since the last
208 /// [`clear`](Self::clear).
209 ///
210 /// ```
211 /// # use psx_sfx::hw::{Hw, Recorder};
212 /// let mut r = Recorder::<4>::new();
213 /// r.key_off(0b100);
214 /// assert_eq!(r.keyed_off(), 0b100);
215 /// ```
216 pub fn keyed_off(&self) -> u32 {
217 self.events()
218 .iter()
219 .fold(0, |m, e| if let Event::KeyOff(k) = e { m | k } else { m })
220 }
221
222 /// The most recent volume written to `voice`, if any.
223 ///
224 /// ```
225 /// # use psx_sfx::hw::{Hw, Recorder};
226 /// let mut r = Recorder::<4>::new();
227 /// r.set_volume(5, 10, 20);
228 /// assert_eq!(r.last_volume(5), Some((10, 20)));
229 /// assert_eq!(r.last_volume(6), None);
230 /// ```
231 pub fn last_volume(&self, voice: u8) -> Option<(i16, i16)> {
232 self.events().iter().rev().find_map(|e| match *e {
233 Event::Volume {
234 voice: v,
235 left,
236 right,
237 } if v == voice => Some((left, right)),
238 _ => None,
239 })
240 }
241
242 fn push(&mut self, e: Event) {
243 if self.len < CAP {
244 self.events[self.len] = e;
245 self.len += 1;
246 } else {
247 self.dropped = self.dropped.saturating_add(1);
248 }
249 }
250}
251
252impl<const CAP: usize> Default for Recorder<CAP> {
253 fn default() -> Self {
254 Self::new()
255 }
256}
257
258impl<const CAP: usize> Hw for Recorder<CAP> {
259 fn configure(&mut self, voice: u8, sample: &Sample, looped: bool, pitch_q12: u16) {
260 self.push(Event::Configure {
261 voice,
262 addr: sample.addr().byte_offset(),
263 rate_hz: sample.sample_rate_hz(),
264 looped,
265 pitch_q12,
266 });
267 }
268
269 fn set_volume(&mut self, voice: u8, left: i16, right: i16) {
270 self.push(Event::Volume { voice, left, right });
271 }
272
273 fn set_pitch(&mut self, voice: u8, pitch_q12: u16) {
274 self.push(Event::Pitch { voice, pitch_q12 });
275 }
276
277 fn key_on(&mut self, mask: u32) {
278 self.push(Event::KeyOn(mask));
279 }
280
281 fn key_off(&mut self, mask: u32) {
282 self.push(Event::KeyOff(mask));
283 }
284}
285
286#[cfg(test)]
287mod tests {
288 use super::*;
289
290 #[test]
291 fn a_full_recorder_counts_what_it_could_not_keep() {
292 let mut r = Recorder::<2>::new();
293 r.key_on(1);
294 r.key_on(2);
295 r.key_off(4);
296 r.key_off(8);
297 assert_eq!(r.events(), &[Event::KeyOn(1), Event::KeyOn(2)]);
298 assert_eq!(r.dropped(), 2);
299 r.clear();
300 assert!(r.events().is_empty());
301 assert_eq!(r.dropped(), 0);
302 }
303
304 #[test]
305 fn the_recorder_summarises_key_ons_and_the_latest_volume() {
306 let mut r = Recorder::<16>::new();
307 r.key_on(0b001);
308 r.key_on(0b100);
309 r.key_off(0b010);
310 r.set_volume(2, 1, 2);
311 r.set_volume(2, 3, 4);
312 r.set_pitch(2, 5000);
313 assert_eq!(r.keyed_on(), 0b101);
314 assert_eq!(r.keyed_off(), 0b010);
315 assert_eq!(r.last_volume(2), Some((3, 4)));
316 assert_eq!(r.last_volume(3), None);
317 }
318}