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

psx_sfx/
mixer.rs

1//! Voice lanes, priorities, stealing, and sound handles.
2//!
3//! Ten programs on the demo disc each own a private way of sharing the SPU's 24
4//! voices: a voice per job, a round robin of four, a rotating pool of fifteen,
5//! first-free with strict priority. [`Mixer`] is the one version. The 24 voices
6//! are split once, at construction, into [`Lane`]s; each lane carries a
7//! [`Policy`] that decides what a new sound does when its lane is busy.
8//!
9//! A [`Mixer`] is bookkeeping only. It never touches a register; every decision
10//! goes out through [`Hw`], which on the host is a [`Recorder`](crate::hw::Recorder).
11//!
12//! # Time
13//!
14//! The mixer has a clock it does not own: call [`Mixer::tick`] once per frame
15//! (or per whatever unit the game's sound durations are in) with a counter that
16//! only goes up. One-shot lifetimes, release tails and the wrap of that counter
17//! are all handled against it. An idle mixer pays two compares per tick.
18//!
19//! # Example
20//!
21//! ```
22//! use psx_sfx::hw::Recorder;
23//! use psx_sfx::mixer::*;
24//! use psx_sfx::Sample;
25//! use psx_spu::SpuAddr;
26//!
27//! // UI sounds get two voices, round robin; the world gets the rest.
28//! let mut mixer = Mixer::new(
29//!     [
30//!         Lane::new(0x00_0003, Policy::RoundRobin),
31//!         Lane::new(0xFF_FFFC, Policy::Smart),
32//!     ],
33//!     60,
34//! );
35//! let mut hw = Recorder::<32>::new();
36//!
37//! let beep = Sound::one_shot(SoundId(1), Sample::resident(SpuAddr::new(0x1010), 22050, 40), 0);
38//! mixer.tick(&mut hw, 0);
39//! let h = mixer.play(&mut hw, &beep, Play::new(0x2000, 0x2000)).unwrap();
40//! assert!(mixer.is_alive(h));
41//!
42//! // 40 blocks at 22.05 kHz is 3 ticks of sound plus the 2 tick margin.
43//! mixer.tick(&mut hw, 4);
44//! assert!(mixer.is_alive(h));
45//! mixer.tick(&mut hw, 5);
46//! assert!(!mixer.is_alive(h));
47//! ```
48
49use crate::hw::Hw;
50use crate::master::Master;
51use crate::{expired, Sample};
52use psx_spu::Pitch;
53
54/// Voices on the SPU.
55pub const VOICES: usize = 24;
56
57/// Mask of all 24 voices.
58pub const ALL_VOICES: u32 = 0x00ff_ffff;
59
60/// Ticks a keyed-off voice is considered still ringing before the mixer treats
61/// it as free again.
62pub const RELEASE_TICKS: u32 = 2;
63
64/// A playing one-shot with this many ticks or fewer left counts as finishing,
65/// and is taken before a victim is chosen.
66const FINISHING_TICKS: u32 = 2;
67
68/// Unity pitch multiplier.
69const PITCH_UNITY: u16 = 4096;
70
71/// How the voices in a lane are shared out.
72///
73/// # Example
74///
75/// ```
76/// use psx_sfx::mixer::{Lane, Policy};
77///
78/// let lane = Lane::new(0x00_00F0, Policy::FirstFree);
79/// assert_eq!(lane.policy(), Policy::FirstFree);
80/// ```
81#[derive(Clone, Copy, Debug, PartialEq, Eq)]
82#[non_exhaustive]
83pub enum Policy {
84    /// Take the next voice in the lane after the last one used, whether it is
85    /// idle or not. Cheap; a new sound cuts the oldest. Protected sounds are
86    /// skipped.
87    RoundRobin,
88    /// Take the lowest free voice; with none free, drop the new sound. Never
89    /// steals, so it suits lanes of loops that something else supervises.
90    FirstFree,
91    /// The default for new code: a free voice, else one that is finishing or
92    /// ringing, else the least important live sound, else drop. See
93    /// [`Mixer::play`] for the exact order.
94    Smart,
95    /// Allocation exactly as WipEout's retail sound driver makes it: the first
96    /// idle voice in the lane, else the first finite sound with a strictly
97    /// lower priority (a larger number); loops are never taken and an equal
98    /// priority cannot steal. Expiry ends a sound at once with no release tail,
99    /// and the playing sound is keyed off without being silenced first.
100    StrictRetail,
101}
102
103/// A set of voices and the policy that shares them.
104///
105/// # Example
106///
107/// ```
108/// use psx_sfx::mixer::{Lane, Policy};
109///
110/// // Voices 0..=1, round robin.
111/// let ui = Lane::new(0b11, Policy::RoundRobin);
112/// assert_eq!(ui.voices(), 0b11);
113/// ```
114#[derive(Clone, Copy, Debug, PartialEq, Eq)]
115pub struct Lane {
116    voices: u32,
117    policy: Policy,
118}
119
120impl Lane {
121    /// A lane over the voices set in `voices` (bit `n` is voice `n`).
122    pub const fn new(voices: u32, policy: Policy) -> Self {
123        Self { voices, policy }
124    }
125
126    /// The voice mask.
127    pub const fn voices(&self) -> u32 {
128        self.voices
129    }
130
131    /// The lane's policy.
132    pub const fn policy(&self) -> Policy {
133        self.policy
134    }
135}
136
137/// How much a sound matters, most important first.
138///
139/// # Example
140///
141/// ```
142/// use psx_sfx::mixer::Class;
143///
144/// assert!(Class::Protected < Class::High);
145/// assert!(Class::High < Class::Low);
146/// ```
147#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
148pub enum Class {
149    /// Never stolen, by anything, and never dropped for being quiet: a goal
150    /// horn, a whistle, dialogue. If every voice a protected sound could use
151    /// is protected too, the new one is dropped instead.
152    Protected,
153    /// Gameplay-critical effects.
154    High,
155    /// Ordinary effects.
156    Normal,
157    /// Ambient and decorative sounds, first to go.
158    Low,
159}
160
161/// A sound's identity in the caller's tables. The mixer carries it through and
162/// never interprets it.
163///
164/// # Example
165///
166/// ```
167/// use psx_sfx::mixer::SoundId;
168///
169/// const HIT: SoundId = SoundId(3);
170/// assert_eq!(HIT.0, 3);
171/// ```
172#[derive(Clone, Copy, Debug, PartialEq, Eq)]
173pub struct SoundId(pub u16);
174
175/// A sample together with how the mixer should treat it.
176///
177/// Within a class a smaller `prio` is more important, matching WipEout's signed
178/// priority and Quake's channel order.
179///
180/// # Example
181///
182/// ```
183/// use psx_sfx::mixer::*;
184/// use psx_sfx::Sample;
185/// use psx_spu::SpuAddr;
186///
187/// let s = Sample::resident(SpuAddr::new(0x1010), 22050, 40);
188/// let horn = Sound::one_shot(SoundId(9), s, 1).with_class(Class::Protected).with_volume(0x3000);
189/// assert_eq!(horn.class(), Class::Protected);
190/// assert!(!horn.is_looped());
191/// ```
192#[derive(Clone, Copy, Debug)]
193pub struct Sound {
194    id: SoundId,
195    sample: Sample,
196    lane: u8,
197    class: Class,
198    prio: i16,
199    looped: bool,
200    volume: i16,
201    pitch_q12: u16,
202    duck_q12: u16,
203}
204
205impl Sound {
206    const fn base(id: SoundId, sample: Sample, lane: u8, looped: bool) -> Self {
207        Self {
208            id,
209            sample,
210            lane,
211            class: Class::Normal,
212            prio: 0,
213            looped,
214            volume: 0x3fff,
215            pitch_q12: PITCH_UNITY,
216            duck_q12: 4096,
217        }
218    }
219
220    /// A sample that plays once and ends, on lane `lane`.
221    pub const fn one_shot(id: SoundId, sample: Sample, lane: u8) -> Self {
222        Self::base(id, sample, lane, false)
223    }
224
225    /// A sample whose cooked blocks form a hardware loop, on lane `lane`. It
226    /// plays until stopped.
227    pub const fn looped(id: SoundId, sample: Sample, lane: u8) -> Self {
228        Self::base(id, sample, lane, true)
229    }
230
231    /// Set the importance class.
232    pub const fn with_class(mut self, class: Class) -> Self {
233        self.class = class;
234        self
235    }
236
237    /// Set the priority within the class; smaller is more important.
238    pub const fn with_prio(mut self, prio: i16) -> Self {
239        self.prio = prio;
240        self
241    }
242
243    /// Set the default per-ear level used by [`Play::for_sound`].
244    pub const fn with_volume(mut self, volume: i16) -> Self {
245        self.volume = volume;
246        self
247    }
248
249    /// Set the default pitch multiplier (`4096` = as cooked).
250    pub const fn with_pitch(mut self, pitch_q12: u16) -> Self {
251        self.pitch_q12 = pitch_q12;
252        self
253    }
254
255    /// While this sound plays, ask for the music to be ducked to `gain_q12`
256    /// (`4096` = no duck, `2048` = half).
257    pub const fn with_duck(mut self, gain_q12: u16) -> Self {
258        self.duck_q12 = gain_q12;
259        self
260    }
261
262    /// The caller's identity for this sound.
263    pub const fn id(&self) -> SoundId {
264        self.id
265    }
266
267    /// The sample.
268    pub const fn sample(&self) -> Sample {
269        self.sample
270    }
271
272    /// The lane this sound plays on.
273    pub const fn lane(&self) -> u8 {
274        self.lane
275    }
276
277    /// The importance class.
278    pub const fn class(&self) -> Class {
279        self.class
280    }
281
282    /// Priority within the class.
283    pub const fn prio(&self) -> i16 {
284        self.prio
285    }
286
287    /// Does it loop until stopped?
288    pub const fn is_looped(&self) -> bool {
289        self.looped
290    }
291}
292
293/// How one play request should be voiced.
294///
295/// # Example
296///
297/// ```
298/// use psx_sfx::mixer::Play;
299///
300/// let p = Play::new(0x2000, 0x1000).with_key(7).with_ticks(30);
301/// assert_eq!((p.left(), p.right()), (0x2000, 0x1000));
302/// ```
303#[derive(Clone, Copy, Debug)]
304pub struct Play {
305    left: i16,
306    right: i16,
307    pitch_q12: u16,
308    key: u16,
309    ticks: u32,
310}
311
312impl Play {
313    /// Play at these per-ear levels (signed SPU range, before the master
314    /// volume), at the sound's own pitch, replacing nothing, lasting as long as
315    /// its sample.
316    pub const fn new(left: i16, right: i16) -> Self {
317        Self {
318            left,
319            right,
320            pitch_q12: 0,
321            key: 0,
322            ticks: 0,
323        }
324    }
325
326    /// Play at `sound`'s default level on both ears.
327    pub const fn for_sound(sound: &Sound) -> Self {
328        Self::new(sound.volume, sound.volume)
329    }
330
331    /// Override the pitch multiplier for this play (`0` keeps the sound's own).
332    pub const fn with_pitch(mut self, pitch_q12: u16) -> Self {
333        self.pitch_q12 = pitch_q12;
334        self
335    }
336
337    /// Replace in place: if a sound with the same non-zero `key` is already
338    /// playing in the lane, this one takes its voice instead of a second one.
339    /// Quake's (owner, channel) rule.
340    pub const fn with_key(mut self, key: u16) -> Self {
341        self.key = key;
342        self
343    }
344
345    /// Length in ticks, overriding the one computed from the sample's block
346    /// count. Needed for samples with no recorded length, and for games that
347    /// time a sound in their own steps.
348    pub const fn with_ticks(mut self, ticks: u32) -> Self {
349        self.ticks = ticks;
350        self
351    }
352
353    /// Left level.
354    pub const fn left(&self) -> i16 {
355        self.left
356    }
357
358    /// Right level.
359    pub const fn right(&self) -> i16 {
360        self.right
361    }
362}
363
364/// A claim on one playing sound, safe to hold across frames.
365///
366/// It names a voice and a generation. Once the sound ends or its voice is
367/// stolen the generation moves on and every call with the old handle does
368/// nothing, so an engine loop can keep its handle without checking whether it
369/// still owns the voice. The generation is 11 bits; a stale handle could alias a
370/// live one only after 2048 reallocations of the same voice.
371///
372/// # Example
373///
374/// ```
375/// use psx_sfx::mixer::Handle;
376///
377/// let h = Handle::from_raw(0b00001_00000_00101);
378/// assert_eq!(h.voice(), 5);
379/// assert_eq!(Handle::from_raw(h.raw()), h);
380/// ```
381#[derive(Clone, Copy, Debug, PartialEq, Eq)]
382pub struct Handle(u16);
383
384impl Handle {
385    const fn pack(voice: usize, generation: u16) -> Self {
386        Self((generation << 5) | voice as u16)
387    }
388
389    /// Rebuild a handle from [`raw`](Self::raw), for a game that stores them in
390    /// a compact table.
391    pub const fn from_raw(raw: u16) -> Self {
392        Self(raw)
393    }
394
395    /// The packed value: voice in the low 5 bits, generation above.
396    pub const fn raw(self) -> u16 {
397        self.0
398    }
399
400    /// The voice number this handle names.
401    pub const fn voice(self) -> u8 {
402        (self.0 & 31) as u8
403    }
404
405    /// The generation, 11 bits.
406    pub const fn generation(self) -> u16 {
407        self.0 >> 5
408    }
409}
410
411#[derive(Clone, Copy, Debug, PartialEq, Eq)]
412enum State {
413    Idle,
414    Playing,
415    Releasing,
416}
417
418#[derive(Clone, Copy, Debug)]
419struct Slot {
420    state: State,
421    generation: u16,
422    looped: bool,
423    retail: bool,
424    has_deadline: bool,
425    class: Class,
426    prio: i16,
427    key: u16,
428    addr: u32,
429    rate_hz: u32,
430    off_at: u32,
431    left: i16,
432    right: i16,
433    duck_q12: u16,
434}
435
436impl Slot {
437    const IDLE: Slot = Slot {
438        state: State::Idle,
439        generation: 0,
440        looped: false,
441        retail: false,
442        has_deadline: false,
443        class: Class::Normal,
444        prio: 0,
445        key: 0,
446        addr: 0,
447        rate_hz: 0,
448        off_at: 0,
449        left: 0,
450        right: 0,
451        duck_q12: 4096,
452    };
453
454    fn rank(&self) -> i32 {
455        rank(self.class, self.prio)
456    }
457
458    fn loudness(&self) -> i32 {
459        self.left.max(self.right) as i32
460    }
461
462    fn remaining(&self, now: u32) -> u32 {
463        if self.looped || !self.has_deadline {
464            u32::MAX
465        } else if expired(now, self.off_at) {
466            0
467        } else {
468            self.off_at.wrapping_sub(now)
469        }
470    }
471}
472
473/// Importance as a single number, smaller is more important: class first, then
474/// priority.
475const fn rank(class: Class, prio: i16) -> i32 {
476    (class as i32) * 65536 + prio as i32 + 32768
477}
478
479/// Is `a` strictly earlier than `b` on a wrapping counter?
480const fn before(a: u32, b: u32) -> bool {
481    a != b && b.wrapping_sub(a) < u32::MAX / 2
482}
483
484/// The pitch multiplier the hardware can actually reach for a sample cooked at
485/// `rate_hz`: the SPU's pitch register tops out at 0x3FFF, which is 4x the 44.1
486/// kHz base.
487fn pitch_cap_q12(rate_hz: u32) -> u32 {
488    let rate = if rate_hz == 0 { 44_100 } else { rate_hz };
489    ((Pitch::MAX.raw_value() as u32 * 44_100) / rate).min(u16::MAX as u32)
490}
491
492/// The voice allocator: lanes, policies, handles and lifetimes over the SPU's 24
493/// voices, for `L` lanes.
494///
495/// # Example
496///
497/// ```
498/// use psx_sfx::hw::{Event, Recorder};
499/// use psx_sfx::mixer::*;
500/// use psx_sfx::Sample;
501/// use psx_spu::SpuAddr;
502///
503/// let mut mixer = Mixer::new([Lane::new(0b1, Policy::Smart)], 60);
504/// let mut hw = Recorder::<16>::new();
505/// let hum = Sound::looped(SoundId(2), Sample::resident(SpuAddr::new(0x2000), 11025, 8), 0);
506///
507/// let h = mixer.play(&mut hw, &hum, Play::new(1000, 1000)).unwrap();
508/// mixer.update(&mut hw, h, 2000, 500);
509/// assert_eq!(hw.last_volume(0), Some((2000, 500)));
510///
511/// mixer.stop(&mut hw, h);
512/// assert!(!mixer.is_alive(h));
513/// assert!(!mixer.update(&mut hw, h, 1, 1)); // a stale handle is a no-op
514/// assert_eq!(hw.keyed_off(), 1);
515/// ```
516#[derive(Clone, Debug)]
517pub struct Mixer<const L: usize> {
518    lanes: [Lane; L],
519    slots: [Slot; VOICES],
520    cursor: [u8; L],
521    pending: u32,
522    next_due: u32,
523    ducking: u32,
524    now: u32,
525    ticks_hz: u32,
526    cull: i16,
527    master: Master,
528}
529
530impl<const L: usize> Mixer<L> {
531    /// A mixer over `lanes`, with durations measured against a clock that runs
532    /// at `ticks_hz` (60 for NTSC frames, 50 for PAL).
533    ///
534    /// Lanes must lie inside the 24 voices and must not share a voice. Built in
535    /// a `const`, a violation is a compile error.
536    ///
537    /// # Panics
538    /// If a lane is empty, uses a voice above 23, or overlaps another lane.
539    pub const fn new(lanes: [Lane; L], ticks_hz: u32) -> Self {
540        let mut seen = 0u32;
541        let mut i = 0;
542        while i < L {
543            let m = lanes[i].voices;
544            assert!(m != 0, "a lane needs at least one voice");
545            assert!(m & !ALL_VOICES == 0, "a lane uses a voice above 23");
546            assert!(m & seen == 0, "lanes must not share a voice");
547            seen |= m;
548            i += 1;
549        }
550        Self {
551            lanes,
552            slots: [Slot::IDLE; VOICES],
553            cursor: [0; L],
554            pending: 0,
555            next_due: 0,
556            ducking: 0,
557            now: 0,
558            ticks_hz,
559            cull: 0,
560            master: Master::new(),
561        }
562    }
563
564    /// Sounds whose louder ear is at or below `cull` do not take a voice (unless
565    /// protected). Default `0`.
566    ///
567    /// ```
568    /// # use psx_sfx::mixer::*;
569    /// let mut mixer = Mixer::new([Lane::new(1, Policy::Smart)], 60);
570    /// mixer.set_cull(100);
571    /// assert_eq!(mixer.cull(), 100);
572    /// ```
573    pub fn set_cull(&mut self, cull: i16) {
574        self.cull = cull;
575    }
576
577    /// The cull threshold.
578    pub const fn cull(&self) -> i16 {
579        self.cull
580    }
581
582    /// The master volumes and duck.
583    pub const fn master(&self) -> &Master {
584        &self.master
585    }
586
587    /// Replace the master volumes and re-apply them to every live voice at
588    /// once, from the unscaled levels the mixer kept.
589    ///
590    /// ```
591    /// # use psx_sfx::{hw::Recorder, mixer::*, Sample};
592    /// # use psx_spu::SpuAddr;
593    /// # let mut mixer = Mixer::new([Lane::new(0b11, Policy::Smart)], 60);
594    /// # let mut hw = Recorder::<16>::new();
595    /// # let sound = Sound::looped(SoundId(1), Sample::resident(SpuAddr::new(0x2000), 11025, 8), 0);
596    /// # let h = mixer.play(&mut hw, &sound, Play::new(1000, 1000)).unwrap();
597    /// use psx_sfx::master::{Master, Ratio};
598    /// let mut half = Master::new();
599    /// half.set_sfx(Ratio::new(1, 2));
600    /// mixer.set_master(&mut hw, half);
601    /// assert_eq!(hw.last_volume(h.voice()), Some((500, 500)));
602    /// ```
603    pub fn set_master<H: Hw>(&mut self, hw: &mut H, master: Master) {
604        self.master = master;
605        for v in 0..VOICES {
606            if self.slots[v].state == State::Playing {
607                self.write_levels(hw, v);
608            }
609        }
610    }
611
612    /// Advance the clock to `now` and retire what has finished.
613    ///
614    /// Call once per frame before anything that might start a sound. When no
615    /// sound is due and no duck is moving this is two compares.
616    ///
617    /// ```
618    /// # use psx_sfx::{hw::NullHw, mixer::*};
619    /// let mut mixer = Mixer::new([Lane::new(1, Policy::Smart)], 60);
620    /// for frame in 0..3 {
621    ///     mixer.tick(&mut NullHw, frame);
622    /// }
623    /// ```
624    pub fn tick<H: Hw>(&mut self, hw: &mut H, now: u32) {
625        self.now = now;
626        if self.pending != 0 && expired(now, self.next_due) {
627            self.retire(hw);
628        }
629        if self.ducking != 0 || !self.master.duck_settled(4096) {
630            let mut target = 4096u16;
631            for v in 0..VOICES {
632                if self.ducking & (1 << v) != 0 {
633                    target = target.min(self.slots[v].duck_q12);
634                }
635            }
636            self.master.step_duck(target);
637        }
638    }
639
640    fn retire<H: Hw>(&mut self, hw: &mut H) {
641        let now = self.now;
642        let mut off = 0u32;
643        let mut first: Option<u32> = None;
644        for v in 0..VOICES {
645            let bit = 1u32 << v;
646            if self.pending & bit == 0 {
647                continue;
648            }
649            let s = &mut self.slots[v];
650            if expired(now, s.off_at) {
651                match s.state {
652                    State::Playing => {
653                        off |= bit;
654                        self.ducking &= !bit;
655                        if s.retail {
656                            s.state = State::Idle;
657                            self.pending &= !bit;
658                        } else {
659                            hw.set_volume(v as u8, 0, 0);
660                            s.state = State::Releasing;
661                            s.off_at = now.wrapping_add(RELEASE_TICKS);
662                            first = Some(Self::earlier(first, s.off_at));
663                        }
664                    }
665                    State::Releasing | State::Idle => {
666                        s.state = State::Idle;
667                        self.pending &= !bit;
668                    }
669                }
670            } else {
671                first = Some(Self::earlier(first, s.off_at));
672            }
673        }
674        if let Some(at) = first {
675            self.next_due = at;
676        }
677        if off != 0 {
678            hw.key_off(off);
679        }
680    }
681
682    fn earlier(a: Option<u32>, b: u32) -> u32 {
683        match a {
684            Some(a) if !before(b, a) => a,
685            _ => b,
686        }
687    }
688
689    fn arm(&mut self, v: usize, at: u32) {
690        self.slots[v].off_at = at;
691        if self.pending == 0 || before(at, self.next_due) {
692            self.next_due = at;
693        }
694        self.pending |= 1 << v;
695    }
696
697    fn write_levels<H: Hw>(&self, hw: &mut H, v: usize) {
698        let s = &self.slots[v];
699        hw.set_volume(
700            v as u8,
701            self.master.scale_level(s.left),
702            self.master.scale_level(s.right),
703        );
704    }
705
706    fn lane_of(&self, sound: &Sound) -> Option<(usize, Lane)> {
707        let i = sound.lane as usize;
708        self.lanes.get(i).map(|l| (i, *l))
709    }
710
711    /// Start `sound`, or decide not to.
712    ///
713    /// Returns a [`Handle`] for the new sound, or `None` when it was culled or
714    /// the lane had nothing to give. The order in which a lane under
715    /// [`Policy::Smart`] finds a voice:
716    ///
717    /// 1. The same non-zero [`Play::with_key`] already playing in the lane: take
718    ///    its voice.
719    /// 2. An idle voice.
720    /// 3. A voice that is only ringing from a key-off, or a one-shot with a
721    ///    tick or two left.
722    /// 4. The least important live sound that is not protected and is no more
723    ///    important than the new one: lowest importance first, then quietest,
724    ///    then least time left. Equal importance may steal, but not a loop, and
725    ///    not a louder sound.
726    /// 5. Otherwise the new sound is dropped. A protected sound is never taken.
727    ///
728    /// Sounds that are inaudible (see [`set_cull`](Self::set_cull)) are
729    /// dropped before any of this, unless protected.
730    pub fn play<H: Hw>(&mut self, hw: &mut H, sound: &Sound, play: Play) -> Option<Handle> {
731        let (lane_index, lane) = self.lane_of(sound)?;
732        let loud = play.left.max(play.right);
733        if sound.class != Class::Protected && loud <= self.cull {
734            return None;
735        }
736        let v = self.pick(lane_index, lane, sound, play.key, loud as i32)?;
737
738        let rate = sound.sample.sample_rate_hz();
739        let requested = u32::from(if play.pitch_q12 != 0 {
740            play.pitch_q12
741        } else if sound.pitch_q12 != 0 {
742            sound.pitch_q12
743        } else {
744            PITCH_UNITY
745        });
746        let pitch = requested.clamp(1, pitch_cap_q12(rate).max(1)) as u16;
747
748        let deadline = if sound.looped {
749            None
750        } else if play.ticks != 0 {
751            Some(play.ticks)
752        } else {
753            sound.sample.ticks_at(self.ticks_hz).map(|base| {
754                // Half the pitch is twice the duration: stretch the cutoff.
755                base.saturating_mul(PITCH_UNITY as u32) / pitch as u32
756            })
757        };
758
759        let s = &mut self.slots[v];
760        s.generation = (s.generation + 1) & 0x7ff;
761        s.state = State::Playing;
762        s.looped = sound.looped;
763        s.retail = lane.policy == Policy::StrictRetail;
764        s.has_deadline = deadline.is_some();
765        s.class = sound.class;
766        s.prio = sound.prio;
767        s.key = play.key;
768        s.addr = sound.sample.addr().byte_offset();
769        s.rate_hz = rate;
770        s.left = play.left;
771        s.right = play.right;
772        s.duck_q12 = sound.duck_q12;
773        let generation = s.generation;
774        let bit = 1u32 << v;
775        match deadline {
776            Some(t) => {
777                let at = self.now.wrapping_add(t);
778                self.arm(v, at);
779            }
780            None => self.pending &= !bit,
781        }
782        if sound.duck_q12 < 4096 {
783            self.ducking |= bit;
784        } else {
785            self.ducking &= !bit;
786        }
787
788        hw.configure(v as u8, &sound.sample, sound.looped, pitch);
789        self.write_levels(hw, v);
790        hw.key_on(bit);
791        Some(Handle::pack(v, generation))
792    }
793
794    fn pick(
795        &mut self,
796        lane_index: usize,
797        lane: Lane,
798        sound: &Sound,
799        key: u16,
800        loud: i32,
801    ) -> Option<usize> {
802        let mask = lane.voices;
803        if key != 0 {
804            for v in 0..VOICES {
805                let s = &self.slots[v];
806                if mask & (1 << v) != 0 && s.state == State::Playing && s.key == key {
807                    return Some(v);
808                }
809            }
810        }
811        match lane.policy {
812            Policy::RoundRobin => self.pick_round_robin(lane_index, mask),
813            Policy::FirstFree => self.pick_first_free(mask),
814            Policy::Smart => self.pick_smart(mask, rank(sound.class, sound.prio), loud),
815            Policy::StrictRetail => self.pick_strict(mask, rank(sound.class, sound.prio)),
816        }
817    }
818
819    fn pick_round_robin(&mut self, lane_index: usize, mask: u32) -> Option<usize> {
820        let start = self.cursor[lane_index] as usize;
821        for k in 1..=VOICES {
822            let v = (start + k) % VOICES;
823            if mask & (1 << v) == 0 {
824                continue;
825            }
826            let s = &self.slots[v];
827            if s.state == State::Playing && s.class == Class::Protected {
828                continue;
829            }
830            self.cursor[lane_index] = v as u8;
831            return Some(v);
832        }
833        None
834    }
835
836    fn pick_first_free(&self, mask: u32) -> Option<usize> {
837        let mut ringing = None;
838        for v in 0..VOICES {
839            if mask & (1 << v) == 0 {
840                continue;
841            }
842            match self.slots[v].state {
843                State::Idle => return Some(v),
844                State::Releasing if ringing.is_none() => ringing = Some(v),
845                _ => {}
846            }
847        }
848        ringing
849    }
850
851    fn pick_strict(&self, mask: u32, new_rank: i32) -> Option<usize> {
852        let mut steal = None;
853        for v in 0..VOICES {
854            if mask & (1 << v) == 0 {
855                continue;
856            }
857            let s = &self.slots[v];
858            match s.state {
859                State::Idle => return Some(v),
860                State::Playing
861                    if steal.is_none()
862                        && !s.looped
863                        && s.class != Class::Protected
864                        && new_rank < s.rank() =>
865                {
866                    steal = Some(v);
867                }
868                _ => {}
869            }
870        }
871        steal
872    }
873
874    fn pick_smart(&self, mask: u32, new_rank: i32, new_loud: i32) -> Option<usize> {
875        let mut ringing = None;
876        let mut finishing = None;
877        // (voice, rank, loudness, remaining)
878        let mut victim: Option<(usize, i32, i32, u32)> = None;
879        for v in 0..VOICES {
880            if mask & (1 << v) == 0 {
881                continue;
882            }
883            let s = &self.slots[v];
884            match s.state {
885                State::Idle => return Some(v),
886                State::Releasing => {
887                    if ringing.is_none() {
888                        ringing = Some(v);
889                    }
890                }
891                State::Playing => {
892                    if s.class == Class::Protected {
893                        continue;
894                    }
895                    let rem = s.remaining(self.now);
896                    if rem <= FINISHING_TICKS && finishing.is_none() {
897                        finishing = Some(v);
898                    }
899                    let r = s.rank();
900                    if r < new_rank {
901                        continue; // more important than the newcomer
902                    }
903                    let loud = s.loudness();
904                    if r == new_rank && (s.looped || new_loud < loud) {
905                        continue; // never trade a loud sound for a quiet one
906                    }
907                    let better = match victim {
908                        None => true,
909                        Some((_, br, bl, brem)) => {
910                            r > br || (r == br && (loud < bl || (loud == bl && rem < brem)))
911                        }
912                    };
913                    if better {
914                        victim = Some((v, r, loud, rem));
915                    }
916                }
917            }
918        }
919        ringing.or(finishing).or(victim.map(|(v, ..)| v))
920    }
921
922    /// Is `handle` still the sound it was issued for?
923    ///
924    /// ```
925    /// # use psx_sfx::{hw::Recorder, mixer::*, Sample};
926    /// # use psx_spu::SpuAddr;
927    /// # let mut mixer = Mixer::new([Lane::new(0b11, Policy::Smart)], 60);
928    /// # let mut hw = Recorder::<16>::new();
929    /// # let sound = Sound::looped(SoundId(1), Sample::resident(SpuAddr::new(0x2000), 11025, 8), 0);
930    /// # let h = mixer.play(&mut hw, &sound, Play::new(1000, 1000)).unwrap();
931    /// assert!(mixer.is_alive(h));
932    /// mixer.stop(&mut hw, h);
933    /// assert!(!mixer.is_alive(h));
934    /// ```
935    pub fn is_alive(&self, handle: Handle) -> bool {
936        let s = &self.slots[handle.voice() as usize % VOICES];
937        s.state == State::Playing && s.generation == handle.generation()
938    }
939
940    /// Change a live sound's levels (before the master volume). Writes nothing
941    /// when the levels are unchanged. Returns `false` and does nothing for a
942    /// stale handle.
943    ///
944    /// ```
945    /// # use psx_sfx::{hw::Recorder, mixer::*, Sample};
946    /// # use psx_spu::SpuAddr;
947    /// # let mut mixer = Mixer::new([Lane::new(0b11, Policy::Smart)], 60);
948    /// # let mut hw = Recorder::<16>::new();
949    /// # let sound = Sound::looped(SoundId(1), Sample::resident(SpuAddr::new(0x2000), 11025, 8), 0);
950    /// # let h = mixer.play(&mut hw, &sound, Play::new(1000, 1000)).unwrap();
951    /// assert!(mixer.update(&mut hw, h, 3000, 100));
952    /// assert_eq!(hw.last_volume(h.voice()), Some((3000, 100)));
953    /// ```
954    pub fn update<H: Hw>(&mut self, hw: &mut H, handle: Handle, left: i16, right: i16) -> bool {
955        if !self.is_alive(handle) {
956            return false;
957        }
958        let v = handle.voice() as usize;
959        let s = &mut self.slots[v];
960        if s.left != left || s.right != right {
961            s.left = left;
962            s.right = right;
963            self.write_levels(hw, v);
964        }
965        true
966    }
967
968    /// Change a live sound's pitch multiplier (`4096` = as cooked), clamped to
969    /// what the hardware can reach. Returns `false` for a stale handle. The
970    /// sound's cutoff is not recomputed; use it for loops.
971    ///
972    /// ```
973    /// # use psx_sfx::{hw::Recorder, mixer::*, Sample};
974    /// # use psx_spu::SpuAddr;
975    /// # let mut mixer = Mixer::new([Lane::new(0b11, Policy::Smart)], 60);
976    /// # let mut hw = Recorder::<16>::new();
977    /// # let sound = Sound::looped(SoundId(1), Sample::resident(SpuAddr::new(0x2000), 11025, 8), 0);
978    /// # let h = mixer.play(&mut hw, &sound, Play::new(1000, 1000)).unwrap();
979    /// assert!(mixer.set_pitch(&mut hw, h, 6144)); // a fifth up
980    /// ```
981    pub fn set_pitch<H: Hw>(&mut self, hw: &mut H, handle: Handle, pitch_q12: u16) -> bool {
982        if !self.is_alive(handle) {
983            return false;
984        }
985        let rate_hz = self.slots[handle.voice() as usize].rate_hz;
986        let pitch = (pitch_q12 as u32).clamp(1, pitch_cap_q12(rate_hz).max(1)) as u16;
987        hw.set_pitch(handle.voice(), pitch);
988        true
989    }
990
991    /// End a live sound `ticks` ticks from now, whatever it was going to do. A
992    /// retail-style "kill with a release". Returns `false` for a stale handle.
993    ///
994    /// ```
995    /// # use psx_sfx::{hw::Recorder, mixer::*, Sample};
996    /// # use psx_spu::SpuAddr;
997    /// # let mut mixer = Mixer::new([Lane::new(0b11, Policy::Smart)], 60);
998    /// # let mut hw = Recorder::<16>::new();
999    /// # let sound = Sound::looped(SoundId(1), Sample::resident(SpuAddr::new(0x2000), 11025, 8), 0);
1000    /// # let h = mixer.play(&mut hw, &sound, Play::new(1000, 1000)).unwrap();
1001    /// mixer.tick(&mut hw, 0);
1002    /// mixer.end_in(h, 8);
1003    /// mixer.tick(&mut hw, 7);
1004    /// assert!(mixer.is_alive(h));
1005    /// mixer.tick(&mut hw, 8);
1006    /// assert!(!mixer.is_alive(h));
1007    /// ```
1008    pub fn end_in(&mut self, handle: Handle, ticks: u32) -> bool {
1009        if !self.is_alive(handle) {
1010            return false;
1011        }
1012        let v = handle.voice() as usize;
1013        self.slots[v].looped = false;
1014        self.slots[v].has_deadline = true;
1015        let at = self.now.wrapping_add(ticks);
1016        self.arm(v, at);
1017        true
1018    }
1019
1020    /// Silence a live sound and release its voice. Returns `false` for a stale
1021    /// handle.
1022    ///
1023    /// ```
1024    /// # use psx_sfx::{hw::Recorder, mixer::*, Sample};
1025    /// # use psx_spu::SpuAddr;
1026    /// # let mut mixer = Mixer::new([Lane::new(0b11, Policy::Smart)], 60);
1027    /// # let mut hw = Recorder::<16>::new();
1028    /// # let sound = Sound::looped(SoundId(1), Sample::resident(SpuAddr::new(0x2000), 11025, 8), 0);
1029    /// # let h = mixer.play(&mut hw, &sound, Play::new(1000, 1000)).unwrap();
1030    /// assert!(mixer.stop(&mut hw, h));
1031    /// assert!(!mixer.stop(&mut hw, h)); // already gone
1032    /// ```
1033    pub fn stop<H: Hw>(&mut self, hw: &mut H, handle: Handle) -> bool {
1034        if !self.is_alive(handle) {
1035            return false;
1036        }
1037        self.silence(hw, handle.voice() as usize);
1038        true
1039    }
1040
1041    fn silence<H: Hw>(&mut self, hw: &mut H, v: usize) {
1042        let bit = 1u32 << v;
1043        let s = &mut self.slots[v];
1044        self.ducking &= !bit;
1045        if s.retail {
1046            s.state = State::Idle;
1047            self.pending &= !bit;
1048        } else {
1049            hw.set_volume(v as u8, 0, 0);
1050            s.state = State::Releasing;
1051            let at = self.now.wrapping_add(RELEASE_TICKS);
1052            self.arm(v, at);
1053        }
1054        hw.key_off(bit);
1055    }
1056
1057    /// Stop every playing sound.
1058    ///
1059    /// ```
1060    /// # use psx_sfx::{hw::Recorder, mixer::*, Sample};
1061    /// # use psx_spu::SpuAddr;
1062    /// # let mut mixer = Mixer::new([Lane::new(0b11, Policy::Smart)], 60);
1063    /// # let mut hw = Recorder::<16>::new();
1064    /// # let sound = Sound::looped(SoundId(1), Sample::resident(SpuAddr::new(0x2000), 11025, 8), 0);
1065    /// # let h = mixer.play(&mut hw, &sound, Play::new(1000, 1000)).unwrap();
1066    /// mixer.stop_all(&mut hw);
1067    /// assert_eq!(mixer.playing(), 0);
1068    /// ```
1069    pub fn stop_all<H: Hw>(&mut self, hw: &mut H) {
1070        self.stop_where(hw, |_| true);
1071    }
1072
1073    /// Stop every sound whose sample starts in `lo..hi` (SPU RAM byte offsets).
1074    /// Call before a DMA over samples that may be playing.
1075    ///
1076    /// ```
1077    /// # use psx_sfx::{hw::Recorder, mixer::*, Sample};
1078    /// # use psx_spu::SpuAddr;
1079    /// # let mut mixer = Mixer::new([Lane::new(0b11, Policy::Smart)], 60);
1080    /// # let mut hw = Recorder::<16>::new();
1081    /// # let sound = Sound::looped(SoundId(1), Sample::resident(SpuAddr::new(0x2000), 11025, 8), 0);
1082    /// # let h = mixer.play(&mut hw, &sound, Play::new(1000, 1000)).unwrap();
1083    /// mixer.stop_range(&mut hw, 0x2000, 0x3000); // the sound starts at 0x2000
1084    /// assert!(!mixer.is_alive(h));
1085    /// ```
1086    pub fn stop_range<H: Hw>(&mut self, hw: &mut H, lo: u32, hi: u32) {
1087        self.stop_where(hw, |s| s.addr >= lo && s.addr < hi);
1088    }
1089
1090    fn stop_where<H: Hw>(&mut self, hw: &mut H, hit: impl Fn(&Slot) -> bool) {
1091        for v in 0..VOICES {
1092            if self.slots[v].state == State::Playing && hit(&self.slots[v]) {
1093                self.silence(hw, v);
1094            }
1095        }
1096    }
1097
1098    /// The voices holding a live sound, as a mask.
1099    ///
1100    /// ```
1101    /// # use psx_sfx::{hw::Recorder, mixer::*, Sample};
1102    /// # use psx_spu::SpuAddr;
1103    /// # let mut mixer = Mixer::new([Lane::new(0b11, Policy::Smart)], 60);
1104    /// # let mut hw = Recorder::<16>::new();
1105    /// # let sound = Sound::looped(SoundId(1), Sample::resident(SpuAddr::new(0x2000), 11025, 8), 0);
1106    /// # let h = mixer.play(&mut hw, &sound, Play::new(1000, 1000)).unwrap();
1107    /// assert_eq!(mixer.playing(), 1 << h.voice());
1108    /// ```
1109    pub fn playing(&self) -> u32 {
1110        let mut m = 0;
1111        for (v, s) in self.slots.iter().enumerate() {
1112            if s.state == State::Playing {
1113                m |= 1 << v;
1114            }
1115        }
1116        m
1117    }
1118
1119    /// The voices of `lane` that could take a sound without stealing: idle, or
1120    /// only ringing from a key-off.
1121    ///
1122    /// ```
1123    /// # use psx_sfx::{hw::Recorder, mixer::*, Sample};
1124    /// # use psx_spu::SpuAddr;
1125    /// # let mut mixer = Mixer::new([Lane::new(0b11, Policy::Smart)], 60);
1126    /// # let mut hw = Recorder::<16>::new();
1127    /// # let sound = Sound::looped(SoundId(1), Sample::resident(SpuAddr::new(0x2000), 11025, 8), 0);
1128    /// # let h = mixer.play(&mut hw, &sound, Play::new(1000, 1000)).unwrap();
1129    /// assert_eq!(mixer.free_in_lane(0), 0b11 & !(1 << h.voice()));
1130    /// ```
1131    pub fn free_in_lane(&self, lane: usize) -> u32 {
1132        let Some(l) = self.lanes.get(lane) else {
1133            return 0;
1134        };
1135        let mut m = 0;
1136        for (v, s) in self.slots.iter().enumerate() {
1137            if l.voices & (1 << v) != 0 && s.state != State::Playing {
1138                m |= 1 << v;
1139            }
1140        }
1141        m
1142    }
1143
1144    /// Is any voice of `lane` free? See [`free_in_lane`](Self::free_in_lane).
1145    ///
1146    /// ```
1147    /// # use psx_sfx::{hw::Recorder, mixer::*, Sample};
1148    /// # use psx_spu::SpuAddr;
1149    /// # let mut mixer = Mixer::new([Lane::new(0b11, Policy::Smart)], 60);
1150    /// # let mut hw = Recorder::<16>::new();
1151    /// # let sound = Sound::looped(SoundId(1), Sample::resident(SpuAddr::new(0x2000), 11025, 8), 0);
1152    /// # let h = mixer.play(&mut hw, &sound, Play::new(1000, 1000)).unwrap();
1153    /// assert!(mixer.has_free(0));
1154    /// assert!(!mixer.has_free(7)); // no such lane
1155    /// ```
1156    pub fn has_free(&self, lane: usize) -> bool {
1157        self.free_in_lane(lane) != 0
1158    }
1159}
1160
1161#[cfg(test)]
1162mod tests {
1163    use super::*;
1164    use crate::hw::{Event, Recorder};
1165    use crate::master::Ratio;
1166    use psx_spu::SpuAddr;
1167
1168    type Rec = Recorder<256>;
1169
1170    fn sample() -> Sample {
1171        // 400 blocks at 22.05 kHz: 30 ticks of sound plus the 2 tick margin.
1172        Sample::resident(SpuAddr::new(0x1010), 22050, 400)
1173    }
1174
1175    fn shot(class: Class, prio: i16) -> Sound {
1176        Sound::one_shot(SoundId(1), sample(), 0)
1177            .with_class(class)
1178            .with_prio(prio)
1179    }
1180
1181    fn looped(class: Class, prio: i16) -> Sound {
1182        Sound::looped(SoundId(2), sample(), 0)
1183            .with_class(class)
1184            .with_prio(prio)
1185    }
1186
1187    fn smart(voices: u32) -> Mixer<1> {
1188        Mixer::new([Lane::new(voices, Policy::Smart)], 60)
1189    }
1190
1191    fn at(level: i16) -> Play {
1192        Play::new(level, level)
1193    }
1194
1195    #[test]
1196    fn a_free_voice_is_taken_before_anything_is_stolen() {
1197        let mut m = smart(0b111);
1198        let mut hw = Rec::new();
1199        let a = m.play(&mut hw, &shot(Class::Normal, 0), at(100)).unwrap();
1200        let b = m.play(&mut hw, &shot(Class::Normal, 0), at(100)).unwrap();
1201        let c = m.play(&mut hw, &shot(Class::Normal, 0), at(100)).unwrap();
1202        let mut voices = [a.voice(), b.voice(), c.voice()];
1203        voices.sort_unstable();
1204        assert_eq!(voices, [0, 1, 2]);
1205        assert!(m.is_alive(a) && m.is_alive(b) && m.is_alive(c));
1206    }
1207
1208    #[test]
1209    fn a_protected_sound_is_never_stolen_by_anything() {
1210        let mut m = smart(0b11);
1211        let mut hw = Rec::new();
1212        let p1 = m.play(&mut hw, &shot(Class::Protected, 0), at(10)).unwrap();
1213        let p2 = m.play(&mut hw, &shot(Class::Protected, 0), at(10)).unwrap();
1214        // A very important, very loud effect still cannot take either voice.
1215        assert!(m
1216            .play(&mut hw, &shot(Class::High, -1000), at(0x3fff))
1217            .is_none());
1218        // Nor can another protected sound: the lane is full of them.
1219        assert!(m
1220            .play(&mut hw, &shot(Class::Protected, -1000), at(0x3fff))
1221            .is_none());
1222        assert!(m.is_alive(p1) && m.is_alive(p2));
1223    }
1224
1225    #[test]
1226    fn a_protected_sound_steals_an_ordinary_one_and_leaves_other_protected_alone() {
1227        let mut m = smart(0b11);
1228        let mut hw = Rec::new();
1229        let p = m.play(&mut hw, &shot(Class::Protected, 0), at(10)).unwrap();
1230        let n = m.play(&mut hw, &shot(Class::Normal, 0), at(5000)).unwrap();
1231        let p2 = m.play(&mut hw, &shot(Class::Protected, 0), at(10)).unwrap();
1232        assert!(m.is_alive(p) && m.is_alive(p2));
1233        assert!(!m.is_alive(n));
1234        assert_eq!(p2.voice(), n.voice());
1235    }
1236
1237    #[test]
1238    fn equal_importance_may_steal_if_at_least_as_loud_but_never_if_quieter() {
1239        let mut m = smart(0b1);
1240        let mut hw = Rec::new();
1241        let first = m.play(&mut hw, &shot(Class::Normal, 5), at(1000)).unwrap();
1242        // Quieter at the same importance: dropped, the loud sound stays.
1243        assert!(m.play(&mut hw, &shot(Class::Normal, 5), at(999)).is_none());
1244        assert!(m.is_alive(first));
1245        // Equally loud: allowed to take the voice.
1246        let second = m.play(&mut hw, &shot(Class::Normal, 5), at(1000)).unwrap();
1247        assert!(!m.is_alive(first));
1248        assert!(m.is_alive(second));
1249    }
1250
1251    #[test]
1252    fn a_more_important_sound_steals_even_when_it_is_quieter() {
1253        let mut m = smart(0b1);
1254        let mut hw = Rec::new();
1255        let loud_low = m.play(&mut hw, &shot(Class::Low, 0), at(0x3000)).unwrap();
1256        let quiet_high = m.play(&mut hw, &shot(Class::High, 0), at(10)).unwrap();
1257        assert!(!m.is_alive(loud_low));
1258        assert!(m.is_alive(quiet_high));
1259    }
1260
1261    #[test]
1262    fn a_less_important_sound_never_steals() {
1263        let mut m = smart(0b1);
1264        let mut hw = Rec::new();
1265        let high = m.play(&mut hw, &shot(Class::High, 0), at(10)).unwrap();
1266        assert!(m
1267            .play(&mut hw, &shot(Class::Normal, 0), at(0x3000))
1268            .is_none());
1269        assert!(m.play(&mut hw, &shot(Class::High, 1), at(0x3000)).is_none());
1270        assert!(m.is_alive(high));
1271    }
1272
1273    #[test]
1274    fn a_loop_is_only_taken_by_something_strictly_more_important() {
1275        let mut m = smart(0b1);
1276        let mut hw = Rec::new();
1277        let engine = m
1278            .play(&mut hw, &looped(Class::Normal, 3), at(1000))
1279            .unwrap();
1280        assert!(m
1281            .play(&mut hw, &shot(Class::Normal, 3), at(0x3000))
1282            .is_none());
1283        assert!(m.is_alive(engine));
1284        let crash = m.play(&mut hw, &shot(Class::Normal, 2), at(1000)).unwrap();
1285        assert!(!m.is_alive(engine));
1286        assert!(m.is_alive(crash));
1287    }
1288
1289    #[test]
1290    fn the_victim_is_the_least_important_then_the_quietest_then_the_one_closest_to_ending() {
1291        let mut m = smart(0b1111);
1292        let mut hw = Rec::new();
1293        m.tick(&mut hw, 0);
1294        // Voice 0: Low, loud. 1: Low, quiet, long. 2: Low, quiet, short. 3: Normal.
1295        let low_loud = m
1296            .play(&mut hw, &shot(Class::Low, 0), at(3000).with_ticks(50))
1297            .unwrap();
1298        let low_quiet_long = m
1299            .play(&mut hw, &shot(Class::Low, 0), at(100).with_ticks(50))
1300            .unwrap();
1301        let low_quiet_short = m
1302            .play(&mut hw, &shot(Class::Low, 0), at(100).with_ticks(20))
1303            .unwrap();
1304        let normal = m
1305            .play(&mut hw, &shot(Class::Normal, 0), at(10).with_ticks(50))
1306            .unwrap();
1307        // Importance first: the Normal sound survives although it is quietest.
1308        // Then quietest: not the loud Low. Then least time left: the short one.
1309        let new = m
1310            .play(&mut hw, &shot(Class::Normal, 0), at(500).with_ticks(50))
1311            .unwrap();
1312        assert_eq!(new.voice(), low_quiet_short.voice());
1313        assert!(m.is_alive(low_loud) && m.is_alive(low_quiet_long) && m.is_alive(normal));
1314    }
1315
1316    #[test]
1317    fn a_voice_that_is_finishing_is_taken_before_a_victim_is_chosen() {
1318        let mut m = smart(0b11);
1319        let mut hw = Rec::new();
1320        m.tick(&mut hw, 0);
1321        let long = m
1322            .play(&mut hw, &shot(Class::Low, 0), at(100).with_ticks(50))
1323            .unwrap();
1324        let ending = m
1325            .play(&mut hw, &shot(Class::Normal, 0), at(5000).with_ticks(10))
1326            .unwrap();
1327        m.tick(&mut hw, 9); // one tick to go
1328        let new = m.play(&mut hw, &shot(Class::Normal, 0), at(5000)).unwrap();
1329        assert_eq!(new.voice(), ending.voice());
1330        assert!(m.is_alive(long));
1331    }
1332
1333    #[test]
1334    fn a_stale_handle_changes_nothing() {
1335        let mut m = smart(0b1);
1336        let mut hw = Rec::new();
1337        let old = m.play(&mut hw, &shot(Class::Normal, 5), at(1000)).unwrap();
1338        let new = m.play(&mut hw, &shot(Class::Normal, 5), at(1000)).unwrap();
1339        assert_ne!(old, new);
1340        hw.clear();
1341        assert!(!m.update(&mut hw, old, 1, 1));
1342        assert!(!m.stop(&mut hw, old));
1343        assert!(!m.set_pitch(&mut hw, old, 2000));
1344        assert!(!m.end_in(old, 1));
1345        assert!(hw.events().is_empty());
1346        assert!(m.is_alive(new));
1347    }
1348
1349    #[test]
1350    fn a_handle_goes_stale_when_its_sound_ends() {
1351        let mut m = smart(0b1);
1352        let mut hw = Rec::new();
1353        m.tick(&mut hw, 0);
1354        let h = m
1355            .play(&mut hw, &shot(Class::Normal, 0), at(100).with_ticks(4))
1356            .unwrap();
1357        m.tick(&mut hw, 3);
1358        assert!(m.is_alive(h));
1359        m.tick(&mut hw, 4);
1360        assert!(!m.is_alive(h));
1361        assert!(!m.update(&mut hw, h, 5, 5));
1362    }
1363
1364    #[test]
1365    fn the_same_key_replaces_a_sound_in_place() {
1366        let mut m = smart(0b111);
1367        let mut hw = Rec::new();
1368        let a = m
1369            .play(&mut hw, &shot(Class::Normal, 0), at(100).with_key(42))
1370            .unwrap();
1371        let b = m
1372            .play(&mut hw, &shot(Class::Normal, 0), at(100).with_key(42))
1373            .unwrap();
1374        assert_eq!(a.voice(), b.voice());
1375        assert!(!m.is_alive(a));
1376        assert!(m.is_alive(b));
1377        // A different key takes a second voice.
1378        let c = m
1379            .play(&mut hw, &shot(Class::Normal, 0), at(100).with_key(43))
1380            .unwrap();
1381        assert_ne!(c.voice(), b.voice());
1382    }
1383
1384    #[test]
1385    fn deadlines_survive_the_tick_counter_wrapping() {
1386        let mut m = smart(0b1);
1387        let mut hw = Rec::new();
1388        let start = u32::MAX - 2;
1389        m.tick(&mut hw, start);
1390        let h = m
1391            .play(&mut hw, &shot(Class::Normal, 0), at(100).with_ticks(5))
1392            .unwrap();
1393        m.tick(&mut hw, u32::MAX);
1394        assert!(m.is_alive(h));
1395        m.tick(&mut hw, 1); // start + 4
1396        assert!(m.is_alive(h));
1397        m.tick(&mut hw, 2); // start + 5
1398        assert!(!m.is_alive(h));
1399    }
1400
1401    #[test]
1402    fn an_ended_one_shot_is_silenced_keyed_off_and_then_freed_after_its_tail() {
1403        let mut m = smart(0b1);
1404        let mut hw = Rec::new();
1405        m.tick(&mut hw, 10);
1406        let h = m
1407            .play(&mut hw, &shot(Class::Normal, 0), at(100).with_ticks(2))
1408            .unwrap();
1409        hw.clear();
1410        m.tick(&mut hw, 12);
1411        assert_eq!(
1412            hw.events(),
1413            &[
1414                Event::Volume {
1415                    voice: 0,
1416                    left: 0,
1417                    right: 0
1418                },
1419                Event::KeyOff(1),
1420            ]
1421        );
1422        assert!(!m.is_alive(h));
1423        // Ringing: free to take, but not counted as idle.
1424        assert_eq!(m.free_in_lane(0), 1);
1425        m.tick(&mut hw, 12 + RELEASE_TICKS);
1426        assert_eq!(m.free_in_lane(0), 1);
1427        assert_eq!(m.playing(), 0);
1428    }
1429
1430    #[test]
1431    fn an_idle_voice_is_preferred_to_one_still_ringing() {
1432        let mut m = smart(0b11);
1433        let mut hw = Rec::new();
1434        m.tick(&mut hw, 0);
1435        let a = m
1436            .play(&mut hw, &shot(Class::Normal, 0), at(100).with_ticks(1))
1437            .unwrap();
1438        m.tick(&mut hw, 1); // a has ended and is ringing on voice a
1439        let b = m.play(&mut hw, &shot(Class::Normal, 0), at(100)).unwrap();
1440        assert_ne!(b.voice(), a.voice());
1441    }
1442
1443    #[test]
1444    fn inaudible_sounds_take_no_voice_unless_protected() {
1445        let mut m = smart(0b1);
1446        let mut hw = Rec::new();
1447        m.set_cull(50);
1448        assert!(m.play(&mut hw, &shot(Class::Normal, 0), at(50)).is_none());
1449        assert!(m
1450            .play(&mut hw, &shot(Class::Normal, 0), Play::new(10, 50))
1451            .is_none());
1452        assert!(hw.events().is_empty());
1453        assert!(m
1454            .play(&mut hw, &shot(Class::Normal, 0), Play::new(10, 51))
1455            .is_some());
1456        let mut m = smart(0b1);
1457        m.set_cull(50);
1458        assert!(m.play(&mut hw, &shot(Class::Protected, 0), at(0)).is_some());
1459    }
1460
1461    #[test]
1462    fn round_robin_cuts_the_oldest_and_skips_protected_sounds() {
1463        let mut m = Mixer::new([Lane::new(0b111, Policy::RoundRobin)], 60);
1464        let mut hw = Rec::new();
1465        let mut order = [0u8; 4];
1466        for o in order.iter_mut() {
1467            *o = m
1468                .play(&mut hw, &shot(Class::Normal, 0), at(100))
1469                .unwrap()
1470                .voice();
1471        }
1472        assert_eq!(order, [1, 2, 0, 1]);
1473        // Voice 2 is protected: the rotation steps over it.
1474        let mut m = Mixer::new([Lane::new(0b111, Policy::RoundRobin)], 60);
1475        m.play(&mut hw, &shot(Class::Normal, 0), at(100)); // voice 1
1476        let p = m
1477            .play(&mut hw, &shot(Class::Protected, 0), at(100))
1478            .unwrap(); // voice 2
1479        for _ in 0..4 {
1480            let h = m.play(&mut hw, &shot(Class::Normal, 0), at(100)).unwrap();
1481            assert_ne!(h.voice(), p.voice());
1482        }
1483        assert!(m.is_alive(p));
1484    }
1485
1486    #[test]
1487    fn first_free_never_steals() {
1488        let mut m = Mixer::new([Lane::new(0b11, Policy::FirstFree)], 60);
1489        let mut hw = Rec::new();
1490        let a = m.play(&mut hw, &looped(Class::Low, 100), at(10)).unwrap();
1491        let b = m.play(&mut hw, &looped(Class::Low, 100), at(10)).unwrap();
1492        assert_eq!((a.voice(), b.voice()), (0, 1));
1493        assert!(m
1494            .play(&mut hw, &shot(Class::Protected, -5), at(0x3000))
1495            .is_none());
1496        assert!(m.is_alive(a) && m.is_alive(b));
1497    }
1498
1499    #[test]
1500    fn lanes_keep_their_voices_apart() {
1501        let mut m = Mixer::new(
1502            [
1503                Lane::new(0b0011, Policy::Smart),
1504                Lane::new(0b1100, Policy::Smart),
1505            ],
1506            60,
1507        );
1508        let mut hw = Rec::new();
1509        let ui = Sound::one_shot(SoundId(1), sample(), 0);
1510        let world = Sound::one_shot(SoundId(2), sample(), 1);
1511        for _ in 0..4 {
1512            let h = m.play(&mut hw, &ui, at(100)).unwrap();
1513            assert!(h.voice() < 2);
1514        }
1515        for _ in 0..4 {
1516            let h = m.play(&mut hw, &world, at(100)).unwrap();
1517            assert!((2..4).contains(&h.voice()));
1518        }
1519        assert!(m
1520            .play(&mut hw, &Sound::one_shot(SoundId(3), sample(), 9), at(100))
1521            .is_none());
1522    }
1523
1524    #[test]
1525    #[should_panic(expected = "lanes must not share a voice")]
1526    fn overlapping_lanes_are_rejected() {
1527        let _ = Mixer::new(
1528            [
1529                Lane::new(0b011, Policy::Smart),
1530                Lane::new(0b110, Policy::Smart),
1531            ],
1532            60,
1533        );
1534    }
1535
1536    #[test]
1537    #[should_panic(expected = "a lane uses a voice above 23")]
1538    fn a_lane_beyond_voice_23_is_rejected() {
1539        let _ = Mixer::new([Lane::new(1 << 24, Policy::Smart)], 60);
1540    }
1541
1542    #[test]
1543    fn update_writes_only_when_the_levels_change() {
1544        let mut m = smart(0b1);
1545        let mut hw = Rec::new();
1546        let h = m.play(&mut hw, &looped(Class::Normal, 0), at(100)).unwrap();
1547        hw.clear();
1548        assert!(m.update(&mut hw, h, 100, 100));
1549        assert!(hw.events().is_empty());
1550        assert!(m.update(&mut hw, h, 200, 50));
1551        assert_eq!(
1552            hw.events(),
1553            &[Event::Volume {
1554                voice: 0,
1555                left: 200,
1556                right: 50
1557            }]
1558        );
1559    }
1560
1561    #[test]
1562    fn play_configures_sets_the_level_then_keys_on_in_that_order() {
1563        let mut m = smart(0b100);
1564        let mut hw = Rec::new();
1565        m.play(&mut hw, &shot(Class::Normal, 0), Play::new(1234, -77));
1566        assert_eq!(
1567            hw.events(),
1568            &[
1569                Event::Configure {
1570                    voice: 2,
1571                    addr: 0x1010,
1572                    rate_hz: 22050,
1573                    looped: false,
1574                    pitch_q12: 4096
1575                },
1576                Event::Volume {
1577                    voice: 2,
1578                    left: 1234,
1579                    right: -77
1580                },
1581                Event::KeyOn(1 << 2),
1582            ]
1583        );
1584    }
1585
1586    #[test]
1587    fn the_master_volume_scales_new_sounds_and_rescales_live_ones() {
1588        let mut m = smart(0b11);
1589        let mut hw = Rec::new();
1590        let mut master = Master::new();
1591        master.set_sfx(Ratio::new(1, 2));
1592        m.set_master(&mut hw, master);
1593        let h = m
1594            .play(&mut hw, &looped(Class::Normal, 0), Play::new(1000, -3001))
1595            .unwrap();
1596        assert_eq!(hw.last_volume(h.voice()), Some((500, -1500)));
1597        let mut louder = Master::new();
1598        louder.set_sfx(Ratio::new(2, 1));
1599        m.set_master(&mut hw, louder);
1600        assert_eq!(hw.last_volume(h.voice()), Some((2000, -6002)));
1601        // Unscaled levels are what update compares, so the slider is reversible.
1602        m.set_master(&mut hw, Master::new());
1603        assert_eq!(hw.last_volume(h.voice()), Some((1000, -3001)));
1604    }
1605
1606    #[test]
1607    fn a_ducking_sound_pulls_the_music_down_and_lets_it_back() {
1608        let mut m = smart(0b11);
1609        let mut hw = Rec::new();
1610        let mut master = Master::new();
1611        master.set_duck_rates(1024, 512);
1612        m.set_master(&mut hw, master);
1613        m.tick(&mut hw, 0);
1614        let horn = shot(Class::Protected, 0).with_duck(1024);
1615        m.play(&mut hw, &horn, at(100).with_ticks(6)).unwrap();
1616        m.tick(&mut hw, 1);
1617        assert_eq!(m.master().duck_gain_q12(), 3072);
1618        for t in 2..6 {
1619            m.tick(&mut hw, t);
1620        }
1621        assert_eq!(m.master().duck_gain_q12(), 1024);
1622        // The horn ends on tick 6: the music climbs back at the release rate.
1623        m.tick(&mut hw, 6);
1624        assert_eq!(m.master().duck_gain_q12(), 1536);
1625        for t in 7..12 {
1626            m.tick(&mut hw, t);
1627        }
1628        assert_eq!(m.master().duck_gain_q12(), 4096);
1629    }
1630
1631    #[test]
1632    fn pitch_stretches_the_cutoff_and_is_held_to_the_hardware_ceiling() {
1633        let mut m = smart(0b11);
1634        let mut hw = Rec::new();
1635        m.tick(&mut hw, 0);
1636        let plain = m.play(&mut hw, &shot(Class::Normal, 0), at(100)).unwrap();
1637        let half = m
1638            .play(&mut hw, &shot(Class::Normal, 0), at(100).with_pitch(2048))
1639            .unwrap();
1640        // 32 ticks plain, twice that at half pitch.
1641        m.tick(&mut hw, 31);
1642        assert!(m.is_alive(plain) && m.is_alive(half));
1643        m.tick(&mut hw, 32);
1644        assert!(!m.is_alive(plain) && m.is_alive(half));
1645        m.tick(&mut hw, 63);
1646        assert!(m.is_alive(half));
1647        m.tick(&mut hw, 64);
1648        assert!(!m.is_alive(half));
1649
1650        // 22050 Hz may go up to 0x3FFF * 44100 / 22050 = 32766 in Q12.
1651        hw.clear();
1652        let mut m = smart(0b1);
1653        m.play(&mut hw, &shot(Class::Normal, 0), at(100).with_pitch(60000));
1654        assert!(matches!(
1655            hw.events()[0],
1656            Event::Configure {
1657                pitch_q12: 32766,
1658                ..
1659            }
1660        ));
1661    }
1662
1663    #[test]
1664    fn stopping_a_range_silences_only_samples_inside_it() {
1665        let mut m = smart(0b11);
1666        let mut hw = Rec::new();
1667        let inside = Sound::looped(
1668            SoundId(1),
1669            Sample::resident(SpuAddr::new(0x4000), 22050, 8),
1670            0,
1671        );
1672        let outside = Sound::looped(
1673            SoundId(2),
1674            Sample::resident(SpuAddr::new(0x9000), 22050, 8),
1675            0,
1676        );
1677        let a = m.play(&mut hw, &inside, at(100)).unwrap();
1678        let b = m.play(&mut hw, &outside, at(100)).unwrap();
1679        m.stop_range(&mut hw, 0x4000, 0x8000);
1680        assert!(!m.is_alive(a));
1681        assert!(m.is_alive(b));
1682        m.stop_all(&mut hw);
1683        assert_eq!(m.playing(), 0);
1684    }
1685
1686    #[test]
1687    fn a_looped_sound_has_no_deadline_and_a_sample_of_unknown_length_none_either() {
1688        let mut m = smart(0b11);
1689        let mut hw = Rec::new();
1690        m.tick(&mut hw, 0);
1691        let l = m.play(&mut hw, &looped(Class::Normal, 0), at(100)).unwrap();
1692        let unknown = Sound::one_shot(
1693            SoundId(5),
1694            Sample::resident(SpuAddr::new(0x1010), 22050, 0),
1695            0,
1696        );
1697        let u = m.play(&mut hw, &unknown, at(100)).unwrap();
1698        m.tick(&mut hw, 100_000);
1699        assert!(m.is_alive(l) && m.is_alive(u));
1700    }
1701
1702    #[test]
1703    fn ticking_an_idle_mixer_does_nothing() {
1704        let mut m = smart(0b1);
1705        let mut hw = Rec::new();
1706        for t in 0..1000 {
1707            m.tick(&mut hw, t);
1708        }
1709        assert!(hw.events().is_empty());
1710    }
1711}