ferravex_play/audio/
mixer.rs

1use super::{Clip, frame_limit};
2/// A clip whose sample and metadata validation is complete. Keep a bank owner
3/// alive during real-time playback if the last Arc must not free in render.
4#[derive(Clone, Debug)]
5pub struct Sound(Clip);
6impl Sound {
7    /// Decode a validated PCM16 WAV once; playback reuses the owned sample Arc.
8    pub fn wav(bytes: &[u8]) -> Option<Self> {
9        let clip = Clip::wav(bytes)?;
10        if clip.samples.is_empty() {
11            None
12        } else {
13            Some(Self(clip))
14        }
15    }
16
17    pub fn new(clip: Clip) -> Option<Self> {
18        if clip.samples.is_empty()
19            || !(8000..=96000).contains(&clip.sample_rate)
20            || clip.samples.len() > frame_limit(clip.sample_rate)
21            || clip
22                .samples
23                .iter()
24                .flatten()
25                .any(|v| !v.is_finite() || v.abs() > 1.)
26        {
27            return None;
28        }
29        Some(Self(clip))
30    }
31    pub fn clip(&self) -> &Clip {
32        &self.0
33    }
34}
35#[derive(Clone, Copy, Debug, PartialEq, Eq)]
36#[repr(u8)]
37pub enum Bus {
38    Effects,
39    Ambience,
40    Music,
41    Ui,
42}
43#[derive(Clone, Copy, Debug, PartialEq)]
44pub enum Spatial {
45    /// Preserve stereo, without positional attenuation or panning.
46    None,
47    /// Inverse-square falloff beyond min_distance; silence at max_distance.
48    Attenuated {
49        min_distance: f32,
50        max_distance: f32,
51        rolloff: f32,
52    },
53}
54#[derive(Clone, Copy, Debug, PartialEq)]
55pub struct VoiceParams {
56    pub position: [f32; 3],
57    pub gain: f32,
58    pub pitch: f32,
59    pub looping: bool,
60    pub spatial: Spatial,
61    pub bus: Bus,
62    pub priority: u8,
63    /// Initial/changed voice and spatial gain smoothing. Bus/master controls
64    /// have independent timing. Zero gives sample-exact legacy playback.
65    pub ramp_frames: u16,
66    /// One-pole source filter; 24 kHz bypass preserves legacy sample output.
67    pub low_pass_hz: f32,
68}
69impl Default for VoiceParams {
70    fn default() -> Self {
71        Self {
72            position: [0.; 3],
73            gain: 1.,
74            pitch: 1.,
75            looping: false,
76            spatial: Spatial::None,
77            bus: Bus::Effects,
78            priority: 0,
79            ramp_frames: 128,
80            low_pass_hz: 24000.,
81        }
82    }
83}
84impl VoiceParams {
85    fn valid(self) -> bool {
86        self.low_pass_hz.is_finite()
87            && (80. ..=24000.).contains(&self.low_pass_hz)
88            && self.position.iter().all(|v| v.is_finite())
89            && self.gain.is_finite()
90            && (0. ..=4.).contains(&self.gain)
91            && self.pitch.is_finite()
92            && (0.25..=4.).contains(&self.pitch)
93            && match self.spatial {
94                Spatial::None => true,
95                Spatial::Attenuated {
96                    min_distance,
97                    max_distance,
98                    rolloff,
99                } => {
100                    min_distance.is_finite()
101                        && max_distance.is_finite()
102                        && rolloff.is_finite()
103                        && min_distance >= 0.
104                        && max_distance > min_distance
105                        && (0. ..=16.).contains(&rolloff)
106                }
107            }
108    }
109}
110#[derive(Clone, Copy, Debug, PartialEq, Eq)]
111pub struct VoiceHandle {
112    slot: u8,
113    generation: u64,
114}
115/// Opt-in reservation using the existing [`VoiceParams::priority`] scale.
116///
117/// Priorities at or above `critical_priority` are critical; lower priorities
118/// are cosmetic. Cosmetic voices may occupy at most `voice_limit -
119/// reserved_critical` slots, including voices fading out. Critical voices can
120/// use every slot. Within either class, higher priorities still steal the
121/// oldest voice of the lowest strictly lower priority; equal priorities drop.
122///
123/// The default policy reserves one slot for priorities 128..=255. A new
124/// [`Mixer`] has **no policy** until [`Mixer::set_voice_policy`] enables one.
125/// See that method for a compiling configuration example.
126#[derive(Clone, Copy, Debug, PartialEq, Eq)]
127pub struct VoicePolicy {
128    /// First critical priority, in 1..=255.
129    pub critical_priority: u8,
130    /// Number of slots cosmetic voices cannot occupy, in 0..=voice_limit.
131    pub reserved_critical: usize,
132}
133impl Default for VoicePolicy {
134    fn default() -> Self {
135        Self {
136            critical_priority: 128,
137            reserved_critical: 1,
138        }
139    }
140}
141/// Why [`Mixer::start_with_outcome`] did not admit a voice.
142#[derive(Clone, Copy, Debug, PartialEq, Eq)]
143pub enum VoiceRejection {
144    /// Invalid parameters; no voice, generation or statistic changed.
145    InvalidParams,
146    /// The cosmetic budget is full and no lower-priority cosmetic can be stolen.
147    ReservedForCritical,
148    /// All slots are occupied and none has a strictly lower priority.
149    NoLowerPriority,
150}
151/// Explicit admission result, including the invalidated handle after a steal.
152/// See [`Mixer::start_with_outcome`] for a compiling example.
153#[derive(Clone, Copy, Debug, PartialEq, Eq)]
154#[must_use]
155pub enum VoiceAdmission {
156    Started(VoiceHandle),
157    Stolen {
158        handle: VoiceHandle,
159        replaced: VoiceHandle,
160    },
161    Rejected(VoiceRejection),
162}
163impl VoiceAdmission {
164    /// The new handle on success. See [`Mixer::start_with_outcome`].
165    pub fn handle(self) -> Option<VoiceHandle> {
166        match self {
167            Self::Started(handle) | Self::Stolen { handle, .. } => Some(handle),
168            Self::Rejected(_) => None,
169        }
170    }
171    /// The stale handle invalidated by a steal, otherwise `None`.
172    /// See [`Mixer::start_with_outcome`].
173    pub fn replaced(self) -> Option<VoiceHandle> {
174        match self {
175            Self::Stolen { replaced, .. } => Some(replaced),
176            _ => None,
177        }
178    }
179    /// The rejection reason, otherwise `None`. See [`Mixer::start_with_outcome`].
180    pub fn rejection(self) -> Option<VoiceRejection> {
181        match self {
182            Self::Rejected(reason) => Some(reason),
183            _ => None,
184        }
185    }
186}
187struct Voice {
188    sound: Sound,
189    cursor: f64,
190    params: VoiceParams,
191    gains: [f32; 2],
192    targets: [f32; 2],
193    ramp_left: u16,
194    release: Option<u32>,
195    age: u64,
196    filtered: [f32; 2],
197}
198struct Slot {
199    generation: u64,
200    voice: Option<Voice>,
201}
202#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)]
203pub struct MixStats {
204    pub rendered_frames: u64,
205    pub dropped: u64,
206    pub stolen: u64,
207    pub active: usize,
208}
209/// A sample-timed linear envelope. Evaluating from its original endpoints keeps
210/// rendering invariant to callback partitioning, without a per-sample buffer.
211#[derive(Clone, Copy)]
212struct Gain {
213    start: f32,
214    target: f32,
215    frames: u64,
216    elapsed: u64,
217}
218impl Gain {
219    const fn new(value: f32) -> Self {
220        Self {
221            start: value,
222            target: value,
223            frames: 0,
224            elapsed: 0,
225        }
226    }
227    fn value_after(self, frames: u64) -> f32 {
228        let elapsed = self.elapsed.saturating_add(frames);
229        if elapsed >= self.frames {
230            self.target
231        } else {
232            let fraction = elapsed as f64 / self.frames as f64;
233            (f64::from(self.start) + (f64::from(self.target) - f64::from(self.start)) * fraction)
234                as f32
235        }
236    }
237    fn fading(self) -> bool {
238        self.elapsed < self.frames
239    }
240    fn set(&mut self, value: f32, seconds: f64, rate: u32) -> bool {
241        let frames = (seconds * f64::from(rate)).ceil();
242        if !value.is_finite()
243            || !(0. ..=1.).contains(&value)
244            || !seconds.is_finite()
245            || seconds < 0.
246            || frames >= u64::MAX as f64
247        {
248            return false;
249        }
250        let current = self.value_after(0);
251        *self = Self {
252            start: current,
253            target: value,
254            frames: if current == value { 0 } else { frames as u64 },
255            elapsed: 0,
256        };
257        true
258    }
259    fn cancel(&mut self) -> bool {
260        let was_fading = self.fading();
261        *self = Self::new(self.value_after(0));
262        was_fading
263    }
264    fn advance(&mut self, frames: u64) {
265        self.elapsed = self.elapsed.saturating_add(frames).min(self.frames);
266    }
267    fn resample(&mut self, old_rate: u32, new_rate: u32) -> bool {
268        if !self.fading() || old_rate == new_rate {
269            return true;
270        }
271        let remaining = u128::from(self.frames - self.elapsed);
272        let frames = (remaining * u128::from(new_rate)).div_ceil(u128::from(old_rate));
273        let Ok(frames) = u64::try_from(frames) else {
274            return false;
275        };
276        self.start = self.value_after(0);
277        self.frames = frames;
278        self.elapsed = 0;
279        true
280    }
281}
282pub struct Mixer {
283    sample_rate: u32,
284    voices: Vec<Slot>,
285    limit: usize,
286    voice_policy: Option<VoicePolicy>,
287    age: u64,
288    pub listener: [f32; 3],
289    pub right: [f32; 3],
290    master: Gain,
291    buses: [Gain; 4],
292    stats: MixStats,
293}
294impl Mixer {
295    pub fn new(sample_rate: u32, limit: usize) -> Option<Self> {
296        if !(8000..=96000).contains(&sample_rate) || !(1..=128).contains(&limit) {
297            return None;
298        }
299        Some(Self {
300            sample_rate,
301            voices: (0..limit)
302                .map(|_| Slot {
303                    generation: 1,
304                    voice: None,
305                })
306                .collect(),
307            limit,
308            voice_policy: None,
309            age: 0,
310            listener: [0.; 3],
311            right: [1., 0., 0.],
312            master: Gain::new(1.),
313            buses: [Gain::new(1.); 4],
314            stats: MixStats::default(),
315        })
316    }
317    pub fn sample_rate(&self) -> u32 {
318        self.sample_rate
319    }
320    /// Does not restart voices. Fractional source positions survive a device-rate change.
321    /// Active gain fades keep their current value and remaining duration, rounded
322    /// up to the next frame at the new rate. Returns false without changes for an
323    /// unsupported rate or if a fade's remaining frame count would overflow u64.
324    pub fn set_sample_rate(&mut self, rate: u32) -> bool {
325        if !(8000..=96000).contains(&rate) {
326            return false;
327        }
328        let mut master = self.master;
329        let mut buses = self.buses;
330        if !master.resample(self.sample_rate, rate)
331            || buses
332                .iter_mut()
333                .any(|gain| !gain.resample(self.sample_rate, rate))
334        {
335            return false;
336        }
337        self.master = master;
338        self.buses = buses;
339        self.sample_rate = rate;
340        true
341    }
342    /// Current master gain, including any rendered or skipped portion of a fade.
343    pub fn master_gain(&self) -> f32 {
344        self.master.value_after(0)
345    }
346    /// Set a finite gain in 0..=1 immediately, cancelling its fade. Invalid
347    /// input leaves both the current gain and any active fade unchanged.
348    pub fn set_master_gain(&mut self, gain: f32) -> bool {
349        self.master.set(gain, 0., self.sample_rate)
350    }
351    /// Current bus gain, including any rendered or skipped portion of a fade.
352    pub fn bus_gain(&self, bus: Bus) -> f32 {
353        self.buses[bus as usize].value_after(0)
354    }
355    /// Set a finite gain in 0..=1 immediately, cancelling this bus's fade.
356    /// Invalid input leaves the current gain and fade unchanged.
357    pub fn set_bus_gain(&mut self, bus: Bus, gain: f32) -> bool {
358        self.buses[bus as usize].set(gain, 0., self.sample_rate)
359    }
360    /// Fade linearly from the current master gain to `gain` over `seconds`.
361    ///
362    /// Retargeting starts from the current value without a jump. Each rendered
363    /// or skipped output frame advances the fade once, even without voices.
364    /// Duration rounds up to whole output frames; the last frame reaches the
365    /// target exactly. Zero seconds applies immediately. Gain must be finite
366    /// in 0..=1; duration must be finite, nonnegative and fit in a u64 frame
367    /// count. Invalid input returns false without changing an existing fade.
368    ///
369    /// Fading to zero mutes exactly, independently of voice gain smoothing.
370    /// Muted voices keep advancing; fade back to a saved gain to unmute.
371    /// [`Self::suspend`] does not advance or cancel fades; [`Self::skip`] does
372    /// advance them when a host stops rendering PCM.
373    ///
374    /// ```
375    /// use ferravex_play::audio::Mixer;
376    /// let mut mixer = Mixer::new(48_000, 16).unwrap();
377    /// let resume_gain = mixer.master_gain();
378    /// assert!(mixer.fade_master_gain(0.0, 0.01));
379    /// mixer.render(&mut [[0.0; 2]; 480]);
380    /// assert_eq!(mixer.master_gain(), 0.0);
381    /// assert!(!mixer.is_master_fading());
382    /// assert!(mixer.fade_master_gain(resume_gain, 0.01));
383    /// ```
384    pub fn fade_master_gain(&mut self, gain: f32, seconds: f64) -> bool {
385        self.master.set(gain, seconds, self.sample_rate)
386    }
387    /// Fade one bus independently of the master and other buses. Validation,
388    /// timing, retargeting and mute behavior match [`Self::fade_master_gain`].
389    ///
390    /// ```
391    /// use ferravex_play::audio::{Bus, Mixer};
392    /// let mut mixer = Mixer::new(48_000, 16).unwrap();
393    /// assert!(mixer.fade_bus_gain(Bus::Music, 0.2, 0.25));
394    /// mixer.skip(6_000);
395    /// assert_eq!(mixer.bus_gain(Bus::Music), 0.6);
396    /// // A new fade starts at 0.6, including when it reverses direction.
397    /// assert!(mixer.fade_bus_gain(Bus::Music, 1.0, 0.25));
398    /// assert_eq!(mixer.bus_gain(Bus::Effects), 1.0);
399    /// ```
400    pub fn fade_bus_gain(&mut self, bus: Bus, gain: f32, seconds: f64) -> bool {
401        self.buses[bus as usize].set(gain, seconds, self.sample_rate)
402    }
403    /// Freeze the master at its current gain; return whether a fade was active.
404    ///
405    /// ```
406    /// use ferravex_play::audio::Mixer;
407    /// let mut mixer = Mixer::new(8_000, 1).unwrap();
408    /// mixer.fade_master_gain(0.0, 1.0);
409    /// mixer.skip(4_000);
410    /// assert!(mixer.cancel_master_fade());
411    /// mixer.skip(8_000);
412    /// assert_eq!(mixer.master_gain(), 0.5);
413    /// assert!(!mixer.is_master_fading());
414    /// ```
415    pub fn cancel_master_fade(&mut self) -> bool {
416        self.master.cancel()
417    }
418    /// Freeze this bus at its current gain; return whether a fade was active.
419    ///
420    /// ```
421    /// use ferravex_play::audio::{Bus, Mixer};
422    /// let mut mixer = Mixer::new(8_000, 1).unwrap();
423    /// mixer.fade_bus_gain(Bus::Music, 0.0, 1.0);
424    /// mixer.skip(4_000);
425    /// assert!(mixer.cancel_bus_fade(Bus::Music));
426    /// assert!(!mixer.is_bus_fading(Bus::Music));
427    /// assert!(!mixer.cancel_bus_fade(Bus::Music));
428    /// ```
429    pub fn cancel_bus_fade(&mut self, bus: Bus) -> bool {
430        self.buses[bus as usize].cancel()
431    }
432    /// Whether the master fade still has output frames to advance.
433    /// See [`Self::fade_master_gain`] for an example.
434    pub fn is_master_fading(&self) -> bool {
435        self.master.fading()
436    }
437    /// Whether this bus's fade still has output frames to advance.
438    /// See [`Self::cancel_bus_fade`] for an example.
439    pub fn is_bus_fading(&self, bus: Bus) -> bool {
440        self.buses[bus as usize].fading()
441    }
442    pub fn stats(&self) -> MixStats {
443        MixStats {
444            active: self.active_voices(),
445            ..self.stats
446        }
447    }
448    /// Current opt-in policy; `None` preserves legacy priority-only admission.
449    /// See [`Self::set_voice_policy`] for configuration and validation.
450    pub fn voice_policy(&self) -> Option<VoicePolicy> {
451        self.voice_policy
452    }
453    /// Enable, replace or disable critical-slot reservations without allocating.
454    ///
455    /// Returns false without changes if the critical threshold is zero, the
456    /// reserve exceeds the voice limit, or existing cosmetic voices (including
457    /// releases) exceed the proposed cosmetic budget. Stop those voices first
458    /// or wait for them to finish. `None` disables the policy immediately.
459    /// Successful changes preserve voices, handles, statistics and all fades.
460    ///
461    /// ```
462    /// use ferravex_play::audio::Mixer;
463    /// let mut mixer = Mixer::new(48_000, 16).unwrap();
464    /// assert_eq!(mixer.voice_policy(), None);
465    /// assert!(mixer.set_voice_policy(Some(Default::default())));
466    /// let mut policy = mixer.voice_policy().unwrap();
467    /// policy.critical_priority = 200;
468    /// policy.reserved_critical = 4; // At most 12 cosmetic voices.
469    /// assert!(mixer.set_voice_policy(Some(policy)));
470    /// policy.reserved_critical = 17;
471    /// assert!(!mixer.set_voice_policy(Some(policy)));
472    /// assert_eq!(mixer.voice_policy().unwrap().reserved_critical, 4);
473    /// assert!(mixer.set_voice_policy(None));
474    /// ```
475    pub fn set_voice_policy(&mut self, policy: Option<VoicePolicy>) -> bool {
476        if let Some(policy) = policy
477            && (policy.critical_priority == 0
478                || policy.reserved_critical > self.limit
479                || self.cosmetic_voices(policy) > self.limit - policy.reserved_critical)
480        {
481            return false;
482        }
483        self.voice_policy = policy;
484        true
485    }
486    fn cosmetic_voices(&self, policy: VoicePolicy) -> usize {
487        self.voices
488            .iter()
489            .filter(|slot| {
490                slot.voice
491                    .as_ref()
492                    .is_some_and(|voice| voice.params.priority < policy.critical_priority)
493            })
494            .count()
495    }
496    /// Compatibility entry point. Use a validated Sound for repeated playback.
497    pub fn play(&mut self, clip: Clip, position: [f32; 3], gain: f32, looping: bool) -> bool {
498        let Some(sound) = Sound::new(clip) else {
499            return false;
500        };
501        self.start(
502            &sound,
503            VoiceParams {
504                position,
505                gain,
506                looping,
507                spatial: Spatial::Attenuated {
508                    min_distance: 0.,
509                    max_distance: f32::MAX,
510                    rolloff: 0.05,
511                },
512                ramp_frames: 0,
513                ..Default::default()
514            },
515        )
516        .is_some()
517    }
518    /// Bounded insertion; a higher-priority sound can replace the oldest voice
519    /// of the lowest lower priority. Equal-priority overload drops the new voice.
520    /// Honors any opt-in [`Self::set_voice_policy`] reservation. Use
521    /// [`Self::start_with_outcome`] to distinguish rejection from stealing.
522    pub fn start(&mut self, sound: &Sound, params: VoiceParams) -> Option<VoiceHandle> {
523        self.start_with_outcome(sound, params).handle()
524    }
525    /// Admit a voice with an explicit result, scanning at most 128 fixed slots.
526    ///
527    /// A cosmetic cue at its budget can replace a lower-priority cosmetic even
528    /// when reserved slots are empty. Critical cues first use any empty slot,
529    /// then steal the oldest voice of the lowest strictly lower priority.
530    /// Critical cues can still be rejected when all voices have equal or higher
531    /// priority. A disabled policy uses the original priority-only behavior.
532    ///
533    /// Stealing immediately retires the replaced voice, including its release
534    /// fade, and invalidates its handle. The new voice uses its own gain ramp;
535    /// no overlapping tail or extra voice is allocated. Other voices and
536    /// bus/master fades are unchanged. Rejections increment `stats().dropped`
537    /// except for invalid parameters; steals increment `stats().stolen`.
538    /// Keep a bank owner alive if the last sample Arc must not free on stealing.
539    ///
540    /// ```
541    /// use ferravex_play::audio::{Clip, Mixer, Sound, VoiceParams};
542    /// let sound = Sound::new(Clip::tone(8_000, 440.0, 0.1).unwrap()).unwrap();
543    /// let mut mixer = Mixer::new(8_000, 2).unwrap();
544    /// assert!(mixer.set_voice_policy(Some(Default::default())));
545    /// let cosmetic = mixer.start_with_outcome(&sound, VoiceParams::default());
546    /// let first = cosmetic.handle().unwrap();
547    /// assert_eq!(cosmetic.replaced(), None);
548    /// let denied = mixer.start_with_outcome(&sound, VoiceParams::default());
549    /// assert!(denied.rejection().is_some()); // One slot is reserved.
550    /// let critical = VoiceParams { priority: 128, ..Default::default() };
551    /// assert!(mixer.start_with_outcome(&sound, critical).handle().is_some());
552    /// let replacement = mixer.start_with_outcome(&sound, critical);
553    /// assert_eq!(replacement.replaced(), Some(first));
554    /// assert!(mixer.params(first).is_none());
555    /// assert_eq!(mixer.stats().stolen, 1);
556    /// ```
557    pub fn start_with_outcome(&mut self, sound: &Sound, params: VoiceParams) -> VoiceAdmission {
558        if !params.valid() {
559            return VoiceAdmission::Rejected(VoiceRejection::InvalidParams);
560        }
561        let cosmetic_full = self.voice_policy.is_some_and(|policy| {
562            policy.reserved_critical > 0
563                && params.priority < policy.critical_priority
564                && self.cosmetic_voices(policy) >= self.limit - policy.reserved_critical
565        });
566        let index = self
567            .voices
568            .iter()
569            .position(|v| !cosmetic_full && v.voice.is_none())
570            .or_else(|| {
571                self.voices
572                    .iter()
573                    .enumerate()
574                    .filter_map(|(i, s)| {
575                        s.voice
576                            .as_ref()
577                            .filter(|v| v.params.priority < params.priority)
578                            .map(|v| (i, v.params.priority, v.age))
579                    })
580                    .min_by_key(|&(_, p, a)| (p, a))
581                    .map(|(i, _, _)| i)
582            });
583        let Some(index) = index else {
584            self.stats.dropped = self.stats.dropped.saturating_add(1);
585            return VoiceAdmission::Rejected(if cosmetic_full {
586                VoiceRejection::ReservedForCritical
587            } else {
588                VoiceRejection::NoLowerPriority
589            });
590        };
591        let slot = &mut self.voices[index];
592        let replaced = slot.voice.as_ref().map(|_| VoiceHandle {
593            slot: index as u8,
594            generation: slot.generation,
595        });
596        if slot.voice.is_some() {
597            self.stats.stolen = self.stats.stolen.saturating_add(1);
598            slot.generation = slot.generation.wrapping_add(1).max(1);
599        }
600        self.age = self.age.wrapping_add(1);
601        slot.voice = Some(Voice {
602            sound: sound.clone(),
603            cursor: 0.,
604            params,
605            gains: [0.; 2],
606            targets: [0.; 2],
607            ramp_left: 0,
608            release: None,
609            age: self.age,
610            filtered: [0.; 2],
611        });
612        let handle = VoiceHandle {
613            slot: index as u8,
614            generation: slot.generation,
615        };
616        match replaced {
617            Some(replaced) => VoiceAdmission::Stolen { handle, replaced },
618            None => VoiceAdmission::Started(handle),
619        }
620    }
621    pub fn params(&self, handle: VoiceHandle) -> Option<VoiceParams> {
622        self.voices
623            .get(handle.slot as usize)
624            .filter(|s| s.generation == handle.generation)?
625            .voice
626            .as_ref()
627            .map(|v| v.params)
628    }
629    /// Change a live voice's parameters. Invalid input or a stale handle leaves
630    /// it unchanged. With a voice policy, demoting a critical voice to cosmetic
631    /// also fails if the cosmetic budget is full; other parameter changes keep
632    /// their existing behavior, including during release fades.
633    pub fn set_params(&mut self, handle: VoiceHandle, params: VoiceParams) -> bool {
634        if !params.valid() {
635            return false;
636        }
637        if let Some(policy) = self.voice_policy
638            && params.priority < policy.critical_priority
639            && self
640                .params(handle)
641                .is_some_and(|old| old.priority >= policy.critical_priority)
642            && self.cosmetic_voices(policy) >= self.limit - policy.reserved_critical
643        {
644            return false;
645        }
646        let Some(slot) = self
647            .voices
648            .get_mut(handle.slot as usize)
649            .filter(|s| s.generation == handle.generation)
650        else {
651            return false;
652        };
653        let Some(v) = slot.voice.as_mut() else {
654            return false;
655        };
656        v.params = params;
657        true
658    }
659    pub fn stop(&mut self, handle: VoiceHandle, fade_frames: u32) -> bool {
660        let Some(slot) = self
661            .voices
662            .get_mut(handle.slot as usize)
663            .filter(|s| s.generation == handle.generation)
664        else {
665            return false;
666        };
667        let Some(v) = slot.voice.as_mut() else {
668            return false;
669        };
670        if fade_frames == 0 {
671            retire(slot);
672        } else {
673            v.release = Some(fade_frames.min(96000));
674            v.targets = [0.; 2];
675            v.ramp_left = fade_frames.min(u16::MAX as u32) as u16;
676        }
677        true
678    }
679    pub fn stop_all(&mut self) {
680        for slot in &mut self.voices {
681            if slot.voice.is_some() {
682                retire(slot);
683            }
684        }
685    }
686    /// Drop transient/releasing voices and prime continuous loops for a quiet
687    /// resume. Used at output focus/mute boundaries, with no allocation.
688    pub fn suspend(&mut self) {
689        for slot in &mut self.voices {
690            if let Some(voice) = slot.voice.as_mut() {
691                if !voice.params.looping || voice.release.is_some() {
692                    retire(slot);
693                } else {
694                    voice.gains = [0.; 2];
695                    voice.targets = [0.; 2];
696                    voice.ramp_left = 0;
697                }
698            }
699        }
700    }
701    pub fn active_voices(&self) -> usize {
702        self.voices.iter().filter(|s| s.voice.is_some()).count()
703    }
704    /// Bounded work, no allocations. Finished voices release their Sound Arc.
705    pub fn render(&mut self, out: &mut [[f32; 2]]) {
706        out.fill([0.; 2]);
707        let right = self.right.map(f64::from);
708        let right_len = right.iter().map(|v| v * v).sum::<f64>().sqrt();
709        let listener_valid = self.listener.iter().all(|v| v.is_finite());
710        for slot in &mut self.voices {
711            let Some(voice) = slot.voice.as_mut() else {
712                continue;
713            };
714            let delta = std::array::from_fn::<_, 3, _>(|i| {
715                f64::from(voice.params.position[i]) - f64::from(self.listener[i])
716            });
717            let dist = delta.iter().map(|v| v * v).sum::<f64>().sqrt();
718            let (attenuation, pan) = match voice.params.spatial {
719                Spatial::None => (1., 0.),
720                Spatial::Attenuated {
721                    min_distance,
722                    max_distance,
723                    rolloff,
724                } => {
725                    let d = (dist - f64::from(min_distance)).max(0.);
726                    let gain = if dist >= f64::from(max_distance) {
727                        0.
728                    } else {
729                        1. / (1. + d * d * f64::from(rolloff))
730                    };
731                    let pan = if dist > 1e-5 && right_len > 1e-5 && right_len.is_finite() {
732                        (delta.iter().zip(right).map(|(a, b)| a * b).sum::<f64>()
733                            / (dist * right_len))
734                            .clamp(-1., 1.)
735                    } else {
736                        0.
737                    };
738                    (gain, pan)
739                }
740            };
741            let gain = if listener_valid {
742                voice.params.gain * attenuation as f32
743            } else {
744                0.
745            };
746            let target = if voice.release.is_some() {
747                [0.; 2]
748            } else if voice.params.spatial == Spatial::None {
749                [gain; 2]
750            } else {
751                [
752                    ((1. - pan) * 0.5).sqrt() as f32 * gain,
753                    ((1. + pan) * 0.5).sqrt() as f32 * gain,
754                ]
755            };
756            if voice.release.is_none() && voice.params.ramp_frames == 0 {
757                voice.gains = target;
758            } else if voice.release.is_none() && voice.targets != target {
759                voice.ramp_left = voice.params.ramp_frames;
760            }
761            voice.targets = target;
762            let step = f64::from(voice.sound.0.sample_rate) / f64::from(self.sample_rate)
763                * f64::from(voice.params.pitch);
764            let len = voice.sound.0.samples.len();
765            let filter = if voice.params.low_pass_hz >= 24000. {
766                1.
767            } else {
768                1. - (-std::f32::consts::TAU * voice.params.low_pass_hz / self.sample_rate as f32)
769                    .exp()
770            };
771            let bus = self.buses[voice.params.bus as usize];
772            for (frame, sample) in out.iter_mut().enumerate() {
773                if voice.cursor >= len as f64 {
774                    if voice.params.looping {
775                        voice.cursor %= len as f64;
776                    } else {
777                        break;
778                    }
779                }
780                if voice.release == Some(0) {
781                    break;
782                }
783                if voice.ramp_left > 0 {
784                    for (gain, target) in voice.gains.iter_mut().zip(target) {
785                        *gain += (target - *gain) / f32::from(voice.ramp_left);
786                    }
787                    voice.ramp_left -= 1;
788                }
789                let index = voice.cursor as usize;
790                let next = if index + 1 < len {
791                    index + 1
792                } else if voice.params.looping {
793                    0
794                } else {
795                    index
796                };
797                let fraction = (voice.cursor - index as f64) as f32;
798                let mut source = std::array::from_fn::<_, 2, _>(|c| {
799                    let a = voice.sound.0.samples[index][c];
800                    let b = voice.sound.0.samples[next][c];
801                    a + (b - a) * fraction
802                });
803                if filter == 1. {
804                    voice.filtered = source;
805                } else {
806                    for (value, state) in source.iter_mut().zip(&mut voice.filtered) {
807                        *state += (*value - *state) * filter;
808                        *value = *state;
809                    }
810                }
811                let mono = (source[0] + source[1]) * 0.5;
812                let tail = if !voice.params.looping && voice.params.ramp_frames > 0 {
813                    (((len as f64 - voice.cursor) / step) / f64::from(voice.params.ramp_frames))
814                        .clamp(0., 1.) as f32
815                } else {
816                    1.
817                };
818                let bus_gain = bus.value_after(frame as u64 + 1);
819                for (c, sample) in sample.iter_mut().enumerate() {
820                    let value = if voice.params.spatial == Spatial::None {
821                        source[c]
822                    } else {
823                        mono
824                    };
825                    *sample += value * voice.gains[c] * tail * bus_gain;
826                }
827                voice.cursor += step;
828                if let Some(left) = voice.release.as_mut() {
829                    *left = left.saturating_sub(1);
830                }
831            }
832            if voice.release == Some(0) || (!voice.params.looping && voice.cursor >= len as f64) {
833                retire(slot);
834            }
835        }
836        for (index, frame) in out.iter_mut().enumerate() {
837            let master_gain = self.master.value_after(index as u64 + 1);
838            for value in frame {
839                *value *= master_gain;
840                *value = if value.is_finite() {
841                    value.clamp(-1., 1.)
842                } else {
843                    0.
844                };
845            }
846        }
847        self.advance_gains(out.len() as u64);
848        self.stats.rendered_frames = self.stats.rendered_frames.saturating_add(out.len() as u64);
849    }
850    /// Advance inaudible/suspended hosts in bounded O(voices), without generating PCM.
851    /// Gain fades advance by the same output time, including when no voices exist.
852    pub fn skip(&mut self, frames: u32) {
853        self.advance_gains(u64::from(frames));
854        for slot in &mut self.voices {
855            if let Some(v) = slot.voice.as_mut() {
856                v.gains = [0.; 2];
857                v.targets = [0.; 2];
858                v.ramp_left = 0;
859                v.cursor += f64::from(frames) * f64::from(v.sound.0.sample_rate)
860                    / f64::from(self.sample_rate)
861                    * f64::from(v.params.pitch);
862                if v.params.looping {
863                    v.cursor %= v.sound.0.samples.len() as f64;
864                }
865                if let Some(left) = v.release.as_mut() {
866                    *left = left.saturating_sub(frames);
867                }
868                if v.release == Some(0)
869                    || (!v.params.looping && v.cursor >= v.sound.0.samples.len() as f64)
870                {
871                    retire(slot);
872                }
873            }
874        }
875    }
876    fn advance_gains(&mut self, frames: u64) {
877        self.master.advance(frames);
878        for bus in &mut self.buses {
879            bus.advance(frames);
880        }
881    }
882    pub fn voice_limit(&self) -> usize {
883        self.limit
884    }
885}
886fn retire(slot: &mut Slot) {
887    slot.voice = None;
888    slot.generation = slot.generation.wrapping_add(1).max(1);
889}
890#[cfg(test)]
891mod tests {
892    use super::*;
893    fn sound() -> Sound {
894        Sound::new(Clip {
895            sample_rate: 8000,
896            samples: vec![[0.5; 2]; 800].into(),
897        })
898        .unwrap()
899    }
900    fn loop_voice(mixer: &mut Mixer, bus: Bus, ramp_frames: u16) -> VoiceHandle {
901        mixer
902            .start(
903                &sound(),
904                VoiceParams {
905                    bus,
906                    looping: true,
907                    ramp_frames,
908                    ..Default::default()
909                },
910            )
911            .unwrap()
912    }
913    #[test]
914    fn critical_reservations_apply_to_all_playback_entry_points() {
915        let sound = sound();
916        let mut m = Mixer::new(8000, 2).unwrap();
917        assert!(m.set_voice_policy(Some(VoicePolicy::default())));
918        let cosmetic = m.start(&sound, VoiceParams::default()).unwrap();
919        assert!(!m.play(sound.clip().clone(), [0.; 3], 1., false));
920        assert_eq!(
921            m.start_with_outcome(&sound, VoiceParams::default()),
922            VoiceAdmission::Rejected(VoiceRejection::ReservedForCritical)
923        );
924        assert_eq!(m.active_voices(), 1);
925        let critical = VoiceParams {
926            priority: 128,
927            ..Default::default()
928        };
929        let first = m.start_with_outcome(&sound, critical);
930        assert!(matches!(first, VoiceAdmission::Started(_)));
931        let second = m.start_with_outcome(&sound, critical);
932        assert_eq!(second.replaced(), Some(cosmetic));
933        assert!(second.rejection().is_none());
934        assert_ne!(second.handle(), Some(cosmetic));
935        assert!(!m.stop(cosmetic, 0));
936        assert!(!m.set_params(cosmetic, critical));
937        assert_eq!(
938            m.start_with_outcome(&sound, critical),
939            VoiceAdmission::Rejected(VoiceRejection::NoLowerPriority)
940        );
941        assert_eq!(m.stats().stolen, 1);
942        assert_eq!(m.stats().dropped, 3);
943        assert_eq!(m.stats().active, 2);
944    }
945    #[test]
946    fn cosmetic_replacement_leaves_reserved_slots_empty() {
947        let sound = sound();
948        let mut m = Mixer::new(8000, 2).unwrap();
949        m.set_voice_policy(Some(VoicePolicy::default()));
950        let first = m.start(&sound, VoiceParams::default()).unwrap();
951        let params = VoiceParams {
952            priority: 127,
953            ..Default::default()
954        };
955        let replacement = m.start_with_outcome(&sound, params);
956        assert_eq!(replacement.replaced(), Some(first));
957        assert_eq!(m.active_voices(), 1);
958        assert_eq!(
959            m.start_with_outcome(&sound, params).rejection(),
960            Some(VoiceRejection::ReservedForCritical)
961        );
962        assert!(m.params(replacement.handle().unwrap()).is_some());
963        assert!(
964            m.start(
965                &sound,
966                VoiceParams {
967                    priority: 128,
968                    ..params
969                }
970            )
971            .is_some()
972        );
973        assert_eq!(m.active_voices(), 2);
974    }
975    #[test]
976    fn policy_configuration_and_invalid_admission_are_transactional() {
977        let sound = sound();
978        let mut m = Mixer::new(8000, 2).unwrap();
979        let first = loop_voice(&mut m, Bus::Music, 16);
980        let second = m.start(&sound, VoiceParams::default()).unwrap();
981        assert!(m.fade_master_gain(0., 0.001));
982        assert!(m.fade_bus_gain(Bus::Music, 0., 0.001));
983        let before = m.stats();
984        for policy in [
985            VoicePolicy::default(), // Existing cosmetic voices exceed the budget.
986            VoicePolicy {
987                critical_priority: 0,
988                reserved_critical: 0,
989            },
990            VoicePolicy {
991                critical_priority: 255,
992                reserved_critical: usize::MAX,
993            },
994        ] {
995            assert!(!m.set_voice_policy(Some(policy)));
996            assert_eq!(m.voice_policy(), None);
997        }
998        assert_eq!(
999            m.start_with_outcome(
1000                &sound,
1001                VoiceParams {
1002                    gain: f32::NAN,
1003                    ..Default::default()
1004                }
1005            ),
1006            VoiceAdmission::Rejected(VoiceRejection::InvalidParams)
1007        );
1008        assert_eq!(m.stats(), before);
1009        assert!(m.params(first).is_some());
1010        assert!(m.params(second).is_some());
1011        assert_eq!(m.master_gain(), 1.);
1012        assert_eq!(m.bus_gain(Bus::Music), 1.);
1013        assert!(m.stop(second, 0));
1014        assert!(m.set_voice_policy(Some(VoicePolicy::default())));
1015        assert!(!m.set_voice_policy(Some(VoicePolicy {
1016            reserved_critical: 2,
1017            ..Default::default()
1018        })));
1019        assert_eq!(m.voice_policy(), Some(VoicePolicy::default()));
1020        m.render(&mut [[0.; 2]; 8]);
1021        assert_eq!(m.master_gain(), 0.);
1022        assert_eq!(m.bus_gain(Bus::Music), 0.);
1023        assert!(m.params(first).is_some());
1024    }
1025    #[test]
1026    fn priority_changes_cannot_exceed_the_cosmetic_budget() {
1027        let sound = sound();
1028        let mut m = Mixer::new(8000, 2).unwrap();
1029        m.set_voice_policy(Some(VoicePolicy::default()));
1030        let cosmetic = VoiceParams::default();
1031        let critical = VoiceParams {
1032            priority: 128,
1033            ..cosmetic
1034        };
1035        let first = m.start(&sound, cosmetic).unwrap();
1036        let second = m.start(&sound, critical).unwrap();
1037        let stats = m.stats();
1038        assert!(!m.set_params(second, cosmetic));
1039        assert_eq!(m.params(second), Some(critical));
1040        assert_eq!(m.stats(), stats);
1041        assert!(m.set_params(
1042            second,
1043            VoiceParams {
1044                gain: 0.2,
1045                ..critical
1046            }
1047        ));
1048        assert!(m.set_params(first, critical)); // Promoting frees cosmetic capacity.
1049        assert!(m.set_params(second, cosmetic));
1050        assert!(!m.set_params(first, cosmetic));
1051        assert!(m.stop(second, 0));
1052        assert!(m.set_params(first, cosmetic));
1053    }
1054    #[test]
1055    fn critical_stealing_selects_lowest_priority_then_oldest_voice() {
1056        let sound = sound();
1057        let mut m = Mixer::new(8000, 4).unwrap();
1058        m.set_voice_policy(Some(VoicePolicy::default()));
1059        let params = VoiceParams {
1060            priority: 10,
1061            ..Default::default()
1062        };
1063        let reused = m.start(&sound, params).unwrap();
1064        let oldest = m.start(&sound, params).unwrap();
1065        let younger = m.start(&sound, params).unwrap();
1066        m.stop(reused, 0);
1067        let newest = m.start(&sound, params).unwrap();
1068        let critical = VoiceParams {
1069            priority: 128,
1070            ..params
1071        };
1072        m.start(&sound, critical).unwrap();
1073        assert_eq!(
1074            m.start_with_outcome(&sound, critical).replaced(),
1075            Some(oldest)
1076        );
1077        assert!(m.params(newest).is_some());
1078        assert!(m.set_params(
1079            newest,
1080            VoiceParams {
1081                priority: 1,
1082                ..params
1083            }
1084        ));
1085        assert_eq!(
1086            m.start_with_outcome(&sound, critical).replaced(),
1087            Some(newest)
1088        );
1089        assert!(m.params(younger).is_some());
1090    }
1091    #[test]
1092    fn releasing_and_retired_voices_update_reservations_without_extra_storage() {
1093        let sound = sound();
1094        let mut m = Mixer::new(8000, 2).unwrap();
1095        m.set_voice_policy(Some(VoicePolicy::default()));
1096        let params = VoiceParams {
1097            looping: true,
1098            ramp_frames: 0,
1099            ..Default::default()
1100        };
1101        let first = m.start(&sound, params).unwrap();
1102        m.render(&mut [[0.; 2]; 1]);
1103        m.stop(first, 8);
1104        assert!(m.start(&sound, params).is_none());
1105        let mut out = [[0.; 2]; 8];
1106        m.render(&mut out[..7]);
1107        assert!(m.start(&sound, params).is_none());
1108        m.render(&mut out[7..]);
1109        assert_eq!(out[0], [0.4375; 2]);
1110        assert_eq!(out[7], [0.; 2]);
1111        let next = m.start(&sound, params).unwrap();
1112        m.stop(next, 8);
1113        m.skip(8);
1114        assert!(m.start(&sound, VoiceParams::default()).is_some());
1115        m.suspend();
1116        assert!(m.start(&sound, params).is_some());
1117        m.stop_all();
1118        assert_eq!(m.active_voices(), 0);
1119        assert!(m.start(&sound, VoiceParams::default()).is_some());
1120        m.render(&mut [[0.; 2]; 800]);
1121        assert!(m.start(&sound, params).is_some());
1122    }
1123    #[test]
1124    fn policy_admission_preserves_fades_and_block_partitioning() {
1125        let sound = sound();
1126        let mut legacy = Mixer::new(8000, 2).unwrap();
1127        let mut policy = Mixer::new(8000, 2).unwrap();
1128        policy.set_voice_policy(Some(VoicePolicy::default()));
1129        let params = VoiceParams {
1130            priority: 128,
1131            looping: true,
1132            bus: Bus::Music,
1133            ramp_frames: 8,
1134            ..Default::default()
1135        };
1136        for m in [&mut legacy, &mut policy] {
1137            m.fade_master_gain(0.5, 0.002);
1138            m.fade_bus_gain(Bus::Music, 0., 0.002);
1139            let old = m
1140                .start(
1141                    &sound,
1142                    VoiceParams {
1143                        priority: 0,
1144                        ..params
1145                    },
1146                )
1147                .unwrap();
1148            m.start(&sound, params).unwrap();
1149            m.render(&mut [[0.; 2]; 4]);
1150            m.stop(old, 8);
1151            let replacement = m.start_with_outcome(&sound, params);
1152            assert_eq!(replacement.replaced(), Some(old));
1153            assert!(m.set_sample_rate(16000));
1154        }
1155        let mut whole = [[0.; 2]; 32];
1156        let mut pieces = whole;
1157        legacy.render(&mut whole);
1158        for part in pieces.chunks_mut(3) {
1159            policy.render(part);
1160        }
1161        assert_eq!(whole, pieces);
1162        assert_eq!(whole[24..], [[0.; 2]; 8]);
1163        assert_eq!(legacy.stats(), policy.stats());
1164        assert_eq!(policy.master_gain(), 0.5);
1165        assert_eq!(policy.bus_gain(Bus::Music), 0.);
1166    }
1167    #[test]
1168    fn disabled_and_zero_reservations_keep_legacy_admission() {
1169        let sound = sound();
1170        for enabled in [false, true] {
1171            let mut legacy = Mixer::new(8000, 3).unwrap();
1172            let mut m = Mixer::new(8000, 3).unwrap();
1173            m.set_voice_policy(Some(VoicePolicy {
1174                reserved_critical: 0,
1175                ..Default::default()
1176            }));
1177            if !enabled {
1178                assert!(m.set_voice_policy(None));
1179            }
1180            for priority in [0, 0, 1, 0, 1, 2, 127, 128, 255, 255, 255, 255] {
1181                let params = VoiceParams {
1182                    priority,
1183                    ..Default::default()
1184                };
1185                assert_eq!(
1186                    m.start_with_outcome(&sound, params),
1187                    legacy.start_with_outcome(&sound, params)
1188                );
1189            }
1190            assert_eq!(m.stats(), legacy.stats());
1191        }
1192    }
1193    #[test]
1194    fn all_slots_can_be_reserved_at_both_capacity_bounds() {
1195        let sound = sound();
1196        for limit in [1, 128] {
1197            let mut m = Mixer::new(8000, limit).unwrap();
1198            assert!(m.set_voice_policy(Some(VoicePolicy {
1199                critical_priority: 255,
1200                reserved_critical: limit
1201            })));
1202            let cosmetic = VoiceParams {
1203                priority: 254,
1204                ..Default::default()
1205            };
1206            assert_eq!(
1207                m.start_with_outcome(&sound, cosmetic).rejection(),
1208                Some(VoiceRejection::ReservedForCritical)
1209            );
1210            let critical = VoiceParams {
1211                priority: 255,
1212                ..cosmetic
1213            };
1214            for _ in 0..limit {
1215                assert!(m.start(&sound, critical).is_some());
1216            }
1217            assert_eq!(
1218                m.start_with_outcome(&sound, critical).rejection(),
1219                Some(VoiceRejection::NoLowerPriority)
1220            );
1221            assert_eq!(m.active_voices(), limit);
1222            assert_eq!(m.voices.len(), limit);
1223        }
1224    }
1225    #[test]
1226    fn bus_fades_retarget_from_current_gain_and_cancel_without_jumps() {
1227        let mut m = Mixer::new(8000, 1).unwrap();
1228        loop_voice(&mut m, Bus::Music, 0);
1229        assert!(m.fade_bus_gain(Bus::Music, 0., 0.001));
1230        let mut out = [[0.; 2]; 3];
1231        m.render(&mut out);
1232        assert_eq!(out, [[0.4375; 2], [0.375; 2], [0.3125; 2]]);
1233        assert_eq!(m.bus_gain(Bus::Music), 0.625);
1234        assert!(m.fade_bus_gain(Bus::Music, 1., 0.0005));
1235        assert_eq!(m.bus_gain(Bus::Music), 0.625);
1236        m.render(&mut out[..2]);
1237        assert_eq!(out[..2], [[0.359375; 2], [0.40625; 2]]);
1238        assert!(m.cancel_bus_fade(Bus::Music));
1239        assert!(!m.is_bus_fading(Bus::Music));
1240        assert!(!m.cancel_bus_fade(Bus::Music));
1241        m.render(&mut out);
1242        assert_eq!(out, [[0.40625; 2]; 3]);
1243        assert_eq!(m.bus_gain(Bus::Effects), 1.);
1244        assert_eq!(m.master_gain(), 1.);
1245    }
1246    #[test]
1247    fn master_fades_retarget_cancel_and_immediate_controls_override() {
1248        let mut m = Mixer::new(8000, 1).unwrap();
1249        loop_voice(&mut m, Bus::Music, 0);
1250        assert!(m.fade_master_gain(0., 0.001));
1251        let mut out = [[0.; 2]; 4];
1252        m.render(&mut out);
1253        assert_eq!(out[3], [0.25; 2]);
1254        assert!(m.fade_master_gain(1., 0.0005));
1255        assert_eq!(m.master_gain(), 0.5);
1256        m.render(&mut out[..2]);
1257        assert_eq!(out[..2], [[0.3125; 2], [0.375; 2]]);
1258        assert!(m.cancel_master_fade());
1259        assert!(!m.cancel_master_fade());
1260        m.render(&mut out);
1261        assert_eq!(out, [[0.375; 2]; 4]);
1262
1263        assert!(m.fade_master_gain(0., 1.));
1264        assert!(m.fade_bus_gain(Bus::Music, 0., 1.));
1265        assert!(m.set_master_gain(0.5));
1266        assert!(m.set_bus_gain(Bus::Music, 0.5));
1267        assert!(!m.is_master_fading());
1268        assert!(!m.is_bus_fading(Bus::Music));
1269        m.render(&mut out);
1270        assert_eq!(out, [[0.125; 2]; 4]);
1271    }
1272    #[test]
1273    fn fades_validate_transactionally_and_accept_zero_or_subframe_duration() {
1274        let mut m = Mixer::new(8000, 1).unwrap();
1275        assert!(m.fade_master_gain(0., 0.001));
1276        assert!(m.fade_bus_gain(Bus::Ambience, 0., 0.001));
1277        m.skip(2);
1278        for gain in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -0.1, 1.1] {
1279            assert!(!m.fade_master_gain(gain, 0.001));
1280            assert!(!m.fade_bus_gain(Bus::Ambience, gain, 0.001));
1281            assert!(!m.set_master_gain(gain));
1282            assert!(!m.set_bus_gain(Bus::Ambience, gain));
1283        }
1284        for seconds in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -0.1, f64::MAX] {
1285            assert!(!m.fade_master_gain(1., seconds));
1286            assert!(!m.fade_bus_gain(Bus::Ambience, 1., seconds));
1287        }
1288        assert_eq!(m.master_gain(), 0.75);
1289        assert_eq!(m.bus_gain(Bus::Ambience), 0.75);
1290        assert!(m.is_master_fading());
1291        assert!(m.is_bus_fading(Bus::Ambience));
1292        m.skip(6);
1293        assert_eq!(m.master_gain(), 0.);
1294        assert_eq!(m.bus_gain(Bus::Ambience), 0.);
1295        assert!(!m.is_master_fading());
1296        assert!(!m.is_bus_fading(Bus::Ambience));
1297
1298        assert!(m.fade_master_gain(0.5, 0.));
1299        assert!(m.fade_bus_gain(Bus::Ambience, 0.25, 0.));
1300        assert_eq!(m.master_gain(), 0.5);
1301        assert_eq!(m.bus_gain(Bus::Ambience), 0.25);
1302        assert!(!m.is_master_fading());
1303        assert!(!m.is_bus_fading(Bus::Ambience));
1304        assert!(m.fade_master_gain(1., f64::MIN_POSITIVE));
1305        m.render(&mut []);
1306        assert_eq!(m.master_gain(), 0.5);
1307        assert!(m.is_master_fading());
1308        m.skip(1);
1309        assert_eq!(m.master_gain(), 1.);
1310        assert!(!m.is_master_fading());
1311    }
1312    #[test]
1313    fn simultaneous_fades_share_one_clock_across_voices_and_callback_sizes() {
1314        let mut a = Mixer::new(8000, 3).unwrap();
1315        let mut b = Mixer::new(8000, 3).unwrap();
1316        for m in [&mut a, &mut b] {
1317            for bus in [Bus::Music, Bus::Music, Bus::Effects] {
1318                let handle = loop_voice(m, bus, 0);
1319                let mut params = m.params(handle).unwrap();
1320                params.gain = 0.25;
1321                assert!(m.set_params(handle, params));
1322            }
1323            assert!(m.fade_bus_gain(Bus::Music, 0., 0.008));
1324            assert!(m.fade_master_gain(0.5, 0.008));
1325        }
1326        let mut whole = [[0.; 2]; 100];
1327        let mut pieces = whole;
1328        a.render(&mut whole);
1329        for part in pieces.chunks_mut(13) {
1330            b.render(part);
1331        }
1332        assert_eq!(whole, pieces);
1333        for (i, frame) in whole.iter().enumerate() {
1334            let progress = ((i + 1) as f32 / 64.).min(1.);
1335            let expected = (0.25 * (1. - progress) + 0.125) * (1. - progress * 0.5);
1336            assert_eq!(*frame, [expected; 2]);
1337        }
1338        assert_eq!(a.bus_gain(Bus::Music), 0.);
1339        assert_eq!(a.master_gain(), 0.5);
1340    }
1341    #[test]
1342    fn fade_seconds_and_remaining_duration_survive_sample_rate_changes() {
1343        for rate in [8000, 16000, 44100, 48000, 96000] {
1344            let mut m = Mixer::new(rate, 1).unwrap();
1345            loop_voice(&mut m, Bus::Ui, 0);
1346            assert!(m.fade_master_gain(0., 0.02));
1347            assert!(m.fade_bus_gain(Bus::Ui, 0., 0.02));
1348            let half = rate / 100;
1349            let mut out = vec![[0.; 2]; half as usize];
1350            m.render(&mut out);
1351            assert_eq!(m.master_gain(), 0.5);
1352            assert_eq!(m.bus_gain(Bus::Ui), 0.5);
1353            assert_eq!(*out.last().unwrap(), [0.125; 2]);
1354            assert!(m.set_sample_rate(48000));
1355            assert_eq!(m.master_gain(), 0.5);
1356            assert_eq!(m.bus_gain(Bus::Ui), 0.5);
1357            m.render(&mut [[0.; 2]; 479]);
1358            assert!(m.is_master_fading());
1359            assert!(m.is_bus_fading(Bus::Ui));
1360            let mut last = [[1.; 2]; 1];
1361            m.render(&mut last);
1362            assert_eq!(last, [[0.; 2]]);
1363            assert_eq!(m.master_gain(), 0.);
1364            assert_eq!(m.bus_gain(Bus::Ui), 0.);
1365            assert!(!m.is_master_fading());
1366            assert!(!m.is_bus_fading(Bus::Ui));
1367        }
1368    }
1369    #[test]
1370    fn rate_changes_round_up_remaining_frames_and_reject_overflow_transactionally() {
1371        let mut m = Mixer::new(8000, 1).unwrap();
1372        assert!(m.fade_master_gain(0., 0.001));
1373        assert!(m.fade_bus_gain(Bus::Effects, 0., 0.001));
1374        m.skip(1);
1375        assert!(!m.set_sample_rate(0));
1376        assert_eq!(m.sample_rate(), 8000);
1377        assert!(m.set_sample_rate(12000));
1378        assert_eq!(m.master_gain(), 0.875);
1379        assert_eq!(m.bus_gain(Bus::Effects), 0.875);
1380        m.skip(10);
1381        assert!(m.is_master_fading());
1382        m.skip(1);
1383        assert_eq!(m.master_gain(), 0.);
1384        assert_eq!(m.bus_gain(Bus::Effects), 0.);
1385
1386        // A representable duration at 8 kHz need not fit at 96 kHz. Even
1387        // an earlier successful master rescale must be rolled back on error.
1388        assert!(m.set_sample_rate(8000));
1389        assert!(m.fade_master_gain(1., 1.));
1390        assert!(m.fade_bus_gain(Bus::Music, 0., 1e15));
1391        assert!(!m.set_sample_rate(96000));
1392        assert_eq!(m.sample_rate(), 8000);
1393        m.skip(4000);
1394        assert_eq!(m.master_gain(), 0.5);
1395    }
1396    #[test]
1397    fn empty_and_suspended_mixing_and_skip_advance_the_same_fade_time() {
1398        let mut rendered = Mixer::new(8000, 1).unwrap();
1399        let mut skipped = Mixer::new(8000, 1).unwrap();
1400        for m in [&mut rendered, &mut skipped] {
1401            assert!(m.fade_master_gain(0., 0.001));
1402            assert!(m.fade_bus_gain(Bus::Music, 0., 0.001));
1403        }
1404        rendered.render(&mut [[0.; 2]; 3]);
1405        skipped.skip(3);
1406        assert_eq!(rendered.master_gain(), skipped.master_gain());
1407        assert_eq!(rendered.bus_gain(Bus::Music), skipped.bus_gain(Bus::Music));
1408        skipped.suspend();
1409        assert_eq!(skipped.master_gain(), 0.625);
1410        assert!(skipped.is_master_fading());
1411        rendered.render(&mut [[0.; 2]; 5]);
1412        skipped.skip(u32::MAX);
1413        assert_eq!(rendered.master_gain(), 0.);
1414        assert_eq!(skipped.master_gain(), 0.);
1415        assert_eq!(skipped.bus_gain(Bus::Music), 0.);
1416        assert!(!skipped.is_master_fading());
1417        assert!(!skipped.is_bus_fading(Bus::Music));
1418    }
1419    #[test]
1420    fn fades_mute_exactly_despite_voice_smoothing_and_keep_playback_time() {
1421        for master in [true, false] {
1422            let mut m = Mixer::new(8000, 2).unwrap();
1423            let handle = loop_voice(&mut m, Bus::Music, 128);
1424            let mut warmup = [[0.; 2]; 128];
1425            m.render(&mut warmup);
1426            assert_eq!(warmup[127], [0.5; 2]);
1427            if master {
1428                assert!(m.fade_master_gain(0., 0.001));
1429            } else {
1430                assert!(m.fade_bus_gain(Bus::Music, 0., 0.001));
1431            }
1432            let mut out = [[0.; 2]; 16];
1433            m.render(&mut out);
1434            for (i, frame) in out[..8].iter().enumerate() {
1435                assert_eq!(*frame, [0.5 * (1. - (i + 1) as f32 / 8.); 2]);
1436            }
1437            assert_eq!(out[8..], [[0.; 2]; 8]);
1438            let one_shot = m.start(&sound(), VoiceParams::default()).unwrap();
1439            // Music remains silent; the one-shot on Effects is also muted by
1440            // the master in that case, and still reaches its natural end.
1441            let mut silent = [[0.; 2]; 800];
1442            m.render(&mut silent);
1443            if master {
1444                assert_eq!(silent, [[0.; 2]; 800]);
1445            }
1446            assert!(m.params(one_shot).is_none());
1447            assert!(m.params(handle).is_some());
1448            assert_eq!(
1449                m.voices[handle.slot as usize]
1450                    .voice
1451                    .as_ref()
1452                    .unwrap()
1453                    .cursor,
1454                144.
1455            );
1456            if master {
1457                assert!(m.fade_master_gain(1., 0.001));
1458            } else {
1459                assert!(m.fade_bus_gain(Bus::Music, 1., 0.001));
1460            }
1461            m.render(&mut out[..8]);
1462            for (i, frame) in out[..8].iter().enumerate() {
1463                assert_eq!(*frame, [0.5 * (i + 1) as f32 / 8.; 2]);
1464            }
1465        }
1466    }
1467    #[test]
1468    fn handles_stops_priority_and_validation_are_transactional() {
1469        let sound = sound();
1470        let mut m = Mixer::new(8000, 1).unwrap();
1471        let h = m.start(&sound, VoiceParams::default()).unwrap();
1472        assert!(m.start(&sound, VoiceParams::default()).is_none());
1473        let h2 = m
1474            .start(
1475                &sound,
1476                VoiceParams {
1477                    priority: 1,
1478                    ..Default::default()
1479                },
1480            )
1481            .unwrap();
1482        assert_ne!(h, h2);
1483        assert!(m.params(h).is_none());
1484        assert!(!m.stop(h, 0));
1485        let before = m.params(h2).unwrap();
1486        assert!(!m.set_params(
1487            h2,
1488            VoiceParams {
1489                pitch: f32::NAN,
1490                ..before
1491            }
1492        ));
1493        assert_eq!(m.params(h2), Some(before));
1494        assert!(m.stop(h2, 16));
1495        m.render(&mut [[0.; 2]; 16]);
1496        assert_eq!(m.active_voices(), 0);
1497        assert_eq!(m.stats().stolen, 1);
1498        assert_eq!(m.stats().dropped, 1);
1499    }
1500    #[test]
1501    fn buses_pitch_spatial_and_mute_have_finite_output() {
1502        let sound = sound();
1503        let mut m = Mixer::new(8000, 2).unwrap();
1504        let h = m
1505            .start(
1506                &sound,
1507                VoiceParams {
1508                    pitch: 4.,
1509                    ramp_frames: 0,
1510                    ..Default::default()
1511                },
1512            )
1513            .unwrap();
1514        let mut out = [[0.; 2]; 200];
1515        m.render(&mut out);
1516        assert_eq!(m.active_voices(), 0);
1517        assert_eq!(out[0], [0.5; 2]);
1518        assert!(m.params(h).is_none());
1519        m.set_bus_gain(Bus::Effects, 0.2);
1520        m.start(
1521            &sound,
1522            VoiceParams {
1523                ramp_frames: 0,
1524                ..Default::default()
1525            },
1526        );
1527        m.render(&mut out[..1]);
1528        assert_eq!(out[0], [0.1; 2]);
1529        m.set_master_gain(0.);
1530        m.render(&mut out[..1]);
1531        assert_eq!(out[0], [0.; 2]);
1532        assert!(!m.set_master_gain(f32::INFINITY));
1533        m.skip(8000);
1534        assert_eq!(m.active_voices(), 0);
1535    }
1536    #[test]
1537    fn suspension_discards_one_shots_and_resumes_loops_from_silence() {
1538        let sound = sound();
1539        let mut m = Mixer::new(8000, 2).unwrap();
1540        let shot = m.start(&sound, VoiceParams::default()).unwrap();
1541        let motor = m
1542            .start(
1543                &sound,
1544                VoiceParams {
1545                    looping: true,
1546                    ..Default::default()
1547                },
1548            )
1549            .unwrap();
1550        m.render(&mut [[0.; 2]; 128]);
1551        m.suspend();
1552        assert!(m.params(shot).is_none());
1553        assert!(m.params(motor).is_some());
1554        let mut out = [[0.; 2]; 1];
1555        m.render(&mut out);
1556        assert!(out[0][0] > 0. && out[0][0] < 0.01);
1557    }
1558    #[test]
1559    fn positional_stereo_is_downmixed_and_explicit_stop_fades_even_without_gain_smoothing() {
1560        let sound = Sound::new(Clip {
1561            sample_rate: 8000,
1562            samples: vec![[1., 0.]; 800].into(),
1563        })
1564        .unwrap();
1565        let mut m = Mixer::new(8000, 1).unwrap();
1566        let h = m
1567            .start(
1568                &sound,
1569                VoiceParams {
1570                    ramp_frames: 0,
1571                    position: [2., 0., 0.],
1572                    spatial: Spatial::Attenuated {
1573                        min_distance: 3.,
1574                        max_distance: 10.,
1575                        rolloff: 1.,
1576                    },
1577                    ..Default::default()
1578                },
1579            )
1580            .unwrap();
1581        let mut out = [[0.; 2]; 16];
1582        m.render(&mut out[..1]);
1583        assert_eq!(out[0], [0., 0.5]);
1584        m.stop(h, 16);
1585        m.render(&mut out);
1586        assert!(out[0][1] > 0.4);
1587        assert_eq!(out[15], [0.; 2]);
1588        assert_eq!(m.active_voices(), 0);
1589    }
1590    #[test]
1591    fn ramp_partition_and_device_rate_change_preserve_source_time() {
1592        let sound = sound();
1593        let mut a = Mixer::new(8000, 1).unwrap();
1594        let mut b = Mixer::new(8000, 1).unwrap();
1595        for m in [&mut a, &mut b] {
1596            m.start(
1597                &sound,
1598                VoiceParams {
1599                    looping: true,
1600                    ..Default::default()
1601                },
1602            );
1603        }
1604        let mut whole = [[0.; 2]; 256];
1605        let mut pieces = whole;
1606        a.render(&mut whole);
1607        for part in pieces.chunks_mut(13) {
1608            b.render(part);
1609        }
1610        assert_eq!(whole, pieces);
1611        a.set_sample_rate(16000);
1612        a.render(&mut whole);
1613        assert!(
1614            whole
1615                .iter()
1616                .flatten()
1617                .all(|v| v.is_finite() && v.abs() <= 0.5)
1618        );
1619    }
1620}