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

psx_sfx/
master.rs

1//! Master volumes and the music duck.
2//!
3//! Six games each scale their sound effects by an options-menu setting in six
4//! different ways. [`Master`] is the one copy: an exact rational for the effects
5//! level, the same for music, and a ducking gain that lets an important sound
6//! pull the music down and release it afterwards.
7//!
8//! The mixer applies the effects ratio at the point a level reaches the chip and
9//! remembers the unscaled level, so changing the setting while sounds play
10//! re-scales them immediately. Music is not routed here: [`Master::music_level_q15`]
11//! returns the value, and the game writes it to the CD volume register.
12
13use crate::{SPU_LEVEL_MAX, SPU_LEVEL_MIN};
14
15/// An exact fraction `num / den`.
16///
17/// Exact rather than Q12 so a game that today computes `x * full / base`
18/// keeps its rounding: [`apply`](Self::apply) multiplies first and divides once,
19/// truncating toward zero.
20///
21/// # Example
22///
23/// ```
24/// use psx_sfx::master::Ratio;
25///
26/// let two_thirds = Ratio::new(2, 3);
27/// assert_eq!(two_thirds.apply(100), 66);
28/// assert_eq!(Ratio::UNITY.apply(-5), -5);
29/// ```
30#[derive(Clone, Copy, Debug, PartialEq, Eq)]
31pub struct Ratio {
32    num: u16,
33    den: u16,
34}
35
36impl Ratio {
37    /// One: leaves a level unchanged.
38    pub const UNITY: Self = Self { num: 1, den: 1 };
39
40    /// Silence: every level becomes zero.
41    pub const MUTE: Self = Self { num: 0, den: 1 };
42
43    /// The fraction `num / den`.
44    ///
45    /// # Panics
46    /// If `den` is zero. In a `const` this is a build error.
47    pub const fn new(num: u16, den: u16) -> Self {
48        assert!(den != 0, "Ratio denominator must not be zero");
49        Self { num, den }
50    }
51
52    /// Numerator.
53    pub const fn num(self) -> u16 {
54        self.num
55    }
56
57    /// Denominator.
58    pub const fn den(self) -> u16 {
59        self.den
60    }
61
62    /// `value * num / den`, truncated toward zero.
63    ///
64    /// ```
65    /// # use psx_sfx::master::Ratio;
66    /// assert_eq!(Ratio::new(1, 4).apply(-10), -2);
67    /// ```
68    ///
69    /// `value` must keep `value * num` inside `i32`, which holds for any SPU
70    /// level (`i16`) and any `num` up to `u16::MAX`.
71    pub const fn apply(self, value: i32) -> i32 {
72        value * self.num as i32 / self.den as i32
73    }
74}
75
76/// Effects and music master volumes plus the music duck.
77///
78/// # Example
79///
80/// ```
81/// use psx_sfx::master::{Master, Ratio};
82///
83/// let mut m = Master::new();
84/// m.set_sfx(Ratio::new(1, 2));
85/// assert_eq!(m.scale_level(8000), 4000);
86///
87/// // A protected sound asks for the music to drop to a quarter, then lets go.
88/// m.set_duck_rates(1024, 128);
89/// m.step_duck(1024);
90/// assert_eq!(m.duck_gain_q12(), 3072);
91/// ```
92#[derive(Clone, Copy, Debug, PartialEq, Eq)]
93pub struct Master {
94    sfx: Ratio,
95    music: Ratio,
96    duck: u16,
97    attack: u16,
98    release: u16,
99}
100
101/// Duck gain meaning "music untouched": Q12 one.
102const DUCK_NONE: u16 = 4096;
103
104impl Master {
105    /// Everything at unity, no duck, a duck that moves the whole range in one
106    /// tick until [`set_duck_rates`](Self::set_duck_rates) says otherwise.
107    pub const fn new() -> Self {
108        Self {
109            sfx: Ratio::UNITY,
110            music: Ratio::UNITY,
111            duck: DUCK_NONE,
112            attack: DUCK_NONE,
113            release: DUCK_NONE,
114        }
115    }
116
117    /// Set the effects master.
118    ///
119    /// ```
120    /// # use psx_sfx::master::{Master, Ratio};
121    /// let mut m = Master::new();
122    /// m.set_sfx(Ratio::new(7, 10));
123    /// assert_eq!(m.sfx(), Ratio::new(7, 10));
124    /// ```
125    pub fn set_sfx(&mut self, sfx: Ratio) {
126        self.sfx = sfx;
127    }
128
129    /// Set the music master.
130    ///
131    /// ```
132    /// # use psx_sfx::master::{Master, Ratio};
133    /// let mut m = Master::new();
134    /// m.set_music(Ratio::MUTE);
135    /// assert_eq!(m.music_level_q15(), 0);
136    /// ```
137    pub fn set_music(&mut self, music: Ratio) {
138        self.music = music;
139    }
140
141    /// The effects master.
142    pub const fn sfx(&self) -> Ratio {
143        self.sfx
144    }
145
146    /// The music master.
147    pub const fn music(&self) -> Ratio {
148        self.music
149    }
150
151    /// Scale one signed SPU level by the effects master and clamp it to the
152    /// range the chip accepts.
153    ///
154    /// ```
155    /// # use psx_sfx::master::{Master, Ratio};
156    /// let mut m = Master::new();
157    /// m.set_sfx(Ratio::new(3, 2));
158    /// assert_eq!(m.scale_level(10000), 15000);
159    /// assert_eq!(m.scale_level(12000), 0x3FFF); // clamped to the chip's range
160    /// ```
161    pub const fn scale_level(&self, level: i16) -> i16 {
162        let v = self.sfx.apply(level as i32);
163        if v > SPU_LEVEL_MAX as i32 {
164            SPU_LEVEL_MAX
165        } else if v < SPU_LEVEL_MIN as i32 {
166            SPU_LEVEL_MIN
167        } else {
168            v as i16
169        }
170    }
171
172    /// How fast the duck moves, in Q12 gain per tick: `attack` when the music
173    /// is being pulled down, `release` when it is coming back.
174    ///
175    /// ```
176    /// # use psx_sfx::master::Master;
177    /// let mut m = Master::new();
178    /// m.set_duck_rates(2048, 256);
179    /// m.step_duck(0);
180    /// assert_eq!(m.duck_gain_q12(), 2048);
181    /// ```
182    pub fn set_duck_rates(&mut self, attack: u16, release: u16) {
183        self.attack = attack;
184        self.release = release;
185    }
186
187    /// Move the duck one tick toward `target` (Q12; `4096` is no duck).
188    /// [`Mixer::tick`](crate::mixer::Mixer::tick) calls this with the deepest
189    /// duck any live sound is asking for.
190    ///
191    /// ```
192    /// # use psx_sfx::master::Master;
193    /// let mut m = Master::new(); // rates default to the whole range per tick
194    /// m.step_duck(1000);
195    /// assert_eq!(m.duck_gain_q12(), 1000);
196    /// m.step_duck(4096);
197    /// assert_eq!(m.duck_gain_q12(), 4096);
198    /// ```
199    pub fn step_duck(&mut self, target: u16) {
200        let target = target.min(DUCK_NONE);
201        if self.duck > target {
202            self.duck = self.duck.saturating_sub(self.attack).max(target);
203        } else if self.duck < target {
204            self.duck = self.duck.saturating_add(self.release).min(target);
205        }
206    }
207
208    /// The current duck gain, Q12 (`4096` = music at full level).
209    ///
210    /// ```
211    /// # use psx_sfx::master::Master;
212    /// assert_eq!(Master::new().duck_gain_q12(), 4096);
213    /// ```
214    pub const fn duck_gain_q12(&self) -> u16 {
215        self.duck
216    }
217
218    /// Has the duck reached `target`?
219    ///
220    /// ```
221    /// # use psx_sfx::master::Master;
222    /// assert!(Master::new().duck_settled(4096));
223    /// ```
224    pub const fn duck_settled(&self, target: u16) -> bool {
225        self.duck == target
226    }
227
228    /// The music level to write to the CD volume register: the music master
229    /// times the duck, as signed Q15 (`0x7FFF` is full scale).
230    ///
231    /// ```
232    /// # use psx_sfx::master::{Master, Ratio};
233    /// let mut m = Master::new();
234    /// m.set_music(Ratio::new(1, 2));
235    /// assert_eq!(m.music_level_q15(), 0x3FFF);
236    /// ```
237    pub const fn music_level_q15(&self) -> i16 {
238        ((self.music.apply(0x7fff) * self.duck as i32) >> 12) as i16
239    }
240}
241
242impl Default for Master {
243    fn default() -> Self {
244        Self::new()
245    }
246}
247
248#[cfg(test)]
249mod tests {
250    use super::*;
251
252    #[test]
253    fn a_ratio_multiplies_first_and_truncates_toward_zero() {
254        assert_eq!(Ratio::new(1, 3).apply(100), 33);
255        assert_eq!(Ratio::new(1, 3).apply(-100), -33);
256        assert_eq!(Ratio::new(8190, 0x3fff).apply(16383), 8190);
257        assert_eq!(Ratio::MUTE.apply(12345), 0);
258        // WipEout's `x * full / base` shape: the same integer result.
259        for x in [-16384i32, -1, 0, 1, 777, 16383] {
260            assert_eq!(Ratio::new(3, 7).apply(x), x * 3 / 7);
261        }
262    }
263
264    #[test]
265    #[should_panic(expected = "denominator")]
266    fn a_zero_denominator_is_rejected() {
267        let _ = Ratio::new(1, 0);
268    }
269
270    #[test]
271    fn levels_are_clamped_to_the_spu_range_after_scaling() {
272        let mut m = Master::new();
273        m.set_sfx(Ratio::new(4, 1));
274        assert_eq!(m.scale_level(0x3000), 0x3fff);
275        assert_eq!(m.scale_level(-0x3000), -0x4000);
276        assert_eq!(m.scale_level(1000), 4000);
277        assert_eq!(m.scale_level(i16::MIN), -0x4000);
278    }
279
280    #[test]
281    fn the_duck_attacks_and_releases_at_their_own_rates_and_stops_on_target() {
282        let mut m = Master::new();
283        m.set_duck_rates(1000, 100);
284        let mut seen = [0u16; 6];
285        for s in seen.iter_mut() {
286            m.step_duck(2000);
287            *s = m.duck_gain_q12();
288        }
289        assert_eq!(seen, [3096, 2096, 2000, 2000, 2000, 2000]);
290        m.step_duck(4096);
291        assert_eq!(m.duck_gain_q12(), 2100);
292        for _ in 0..30 {
293            m.step_duck(4096);
294        }
295        assert_eq!(m.duck_gain_q12(), 4096);
296        assert!(m.duck_settled(4096));
297    }
298
299    #[test]
300    fn music_level_is_the_master_times_the_duck_in_signed_q15() {
301        let mut m = Master::new();
302        assert_eq!(m.music_level_q15(), 0x7fff);
303        m.set_music(Ratio::new(1, 2));
304        assert_eq!(m.music_level_q15(), 0x3fff);
305        m.set_duck_rates(4096, 4096);
306        m.step_duck(2048);
307        assert_eq!(m.music_level_q15(), 0x1fff);
308    }
309}