ferravex_render/audio/
batch.rs

1//! Bounded presentation-frame batching of caller-accepted events.
2//!
3//! This is a borrowed adapter over [`GameAudio`], not an event validator or ID
4//! deduplicator. Create one batch per presentation frame, collect across actual
5//! fixed updates, then flush once. Dropping it cancels pending work. Its exclusive
6//! borrow prevents changing/replacing the controller behind queued cues; use
7//! [`CueBatch::pause`] / [`CueBatch::reset`] during the borrow. Release the batch
8//! before resuming or restarting the owner. Never retain it across host frames.
9//! Runtime replacement cancels pending cues using the runtime's weak identity,
10//! the same lifetime boundary used by GameAudio's ownership repair.
11//!
12//! Category IDs are caller-authored, not gameplay event IDs. While a category is
13//! pending, its cue, policy and critical flag must agree at every position.
14//! Only equal category IDs **and equal positions** coalesce (`None` is distinct
15//! from `Some(Vec3::ZERO)`). No spatial averaging, gain summing, hidden volume
16//! multiplication or automatic event deduplication occurs. Strongest means the
17//! greatest raw gain; equal gains keep the first. Replacement retains the first
18//! slot's order. A new critical cue at capacity evicts the oldest noncritical
19//! slot and appends; otherwise overflow drops the incoming cue. All-critical
20//! overflow therefore keeps the earlier cues, regardless of gains. Critical is
21//! solely a storage guarantee against noncritical arrivals, **not** mixer priority
22//! or admission. Distinct positions can consume multiple slots of one category.
23//!
24//! Collection/flush uses only fixed arrays, bounded scans (at most 128 slots),
25//! and existing GameAudio submissions. After audio bank/mixer setup these paths
26//! allocate nothing. Runtime/bank creation, arbitrary host callbacks and their
27//! failures are outside that claim. Flush has no callbacks and consumes every
28//! retained request, including suppressed/rejected requests; it never retries.
29//! Mute may make admitted voices silent. PCM tests are not listening evidence.
30//!
31//! Runnable headless recipe: actual Magazine acceptance plus a timed first-party
32//! objective, driven by GameSession ticks. The objective completion, rather than
33//! a fabricated game result, supplies the terminal cue. No wall time or device is
34//! used. For spatial contacts use `Some(event.position)` instead of `None`.
35//!
36//! ```rust,check
37//! use ferravex_core::session::GameSession;
38//! use ferravex_play::{gameplay::magazine::Magazine,
39//!     objective::{ObjectiveGraph, ObjectiveSpec, ObjectiveKind}};
40//! use ferravex_render::audio::{self, Cue, GameAudio,
41//!     batch::{CueBatch, CueCategory, Coalesce}};
42//! let shot = CueCategory { key: 1, cue: Cue::Fire,
43//!     policy: Coalesce::Strongest, critical: false };
44//! let terminal = CueCategory { key: 2, cue: Cue::Success,
45//!     policy: Coalesce::First, critical: true };
46//! let mut session = GameSession::new(64., 4, true);
47//! let mut magazine = Magazine::new(3, 0, 1.).unwrap();
48//! let spec = ObjectiveSpec {
49//!     id: 1, all: 0, any: 0, exclusive_group: 0,
50//!     kind: ObjectiveKind::Timer { seconds: 3. / 64. },
51//! };
52//! let mut objective = ObjectiveGraph::new(1, [spec]).unwrap();
53//! let mut owner = GameAudio::new(); // Prepare bank outside collection/flush.
54//! {
55//!     let mut cues = CueBatch::<2>::new(&mut owner).unwrap();
56//!     assert_eq!(session.advance(0.).steps, 0);
57//!     assert_eq!(cues.flush().submitted, 0); // Zero-tick/empty frame.
58//! }
59//! {
60//!     let mut cues = CueBatch::<2>::new(&mut owner).unwrap();
61//!     let frame = session.advance(4. / 64.);
62//!     let mut executed = 0;
63//!     for dt in frame.ticks() {
64//!         if !session.is_playing() { break; }
65//!         executed += 1;
66//!         if magazine.fire() { let _ = cues.queue(shot, None, 0.4).unwrap(); }
67//!         if objective.advance(dt).unwrap().completed != 0 {
68//!             assert!(session.finish(true));
69//!             let _ = cues.queue(terminal, None, 0.6).unwrap();
70//!         }
71//!     }
72//!     assert_eq!((frame.steps, executed, session.tick()), (4, 3, 4));
73//!     let report = cues.flush(); // One presentation flush for three ticks.
74//!     assert_eq!((report.batch.coalesced, report.submitted, report.admitted()), (2, 2, 2));
75//!     assert_eq!(cues.flush().submitted, 0); // No replay on an empty frame.
76//! }
77//! let mut pcm = [[0.; 2]; 256];
78//! assert!(audio::render(&mut pcm, audio::SAMPLE_RATE)); // Offline PCM mixing.
79//! assert!(pcm.iter().flatten().all(|v| v.is_finite()));
80//! {
81//!     let mut cues = CueBatch::<2>::new(&mut owner).unwrap();
82//!     let _ = cues.queue(shot, None, 0.4).unwrap();
83//!     assert_eq!(cues.pause(), 1); // Discard pending work and owned gameplay voices.
84//!     assert_eq!(cues.flush().submitted, 0);
85//!     cues.reset(); // Preserves pause; no retry of the cancelled shot.
86//! }
87//! session.restart();
88//! magazine = Magazine::new(3, 0, 1.).unwrap();
89//! objective = ObjectiveGraph::new(1, [spec]).unwrap();
90//! owner.resume(); // Release batch first: no pending work survives resume.
91//! assert_eq!(session.tick(), 0);
92//! let mut retry = CueBatch::<2>::new(&mut owner).unwrap();
93//! assert_eq!(retry.flush().submitted, 0);
94//! for dt in session.advance(1. / 64.).ticks() {
95//!     if magazine.fire() { let _ = retry.queue(shot, None, 0.4).unwrap(); }
96//!     assert_eq!(objective.advance(dt).unwrap().completed, 0);
97//! }
98//! assert_eq!(retry.flush().submitted, 1); // Fresh accepted shot, no stale cue.
99//! ```
100
101use super::{Cue, GameAudio, VoiceAdmission, VoiceRejection};
102use crate::prelude::Vec3;
103use std::rc::{Rc, Weak};
104
105/// Selection among requests at the same category and exact position.
106/// See the module recipe for category construction and submission.
107#[derive(Clone, Copy, Debug, PartialEq, Eq)]
108pub enum Coalesce {
109    /// Keep the first gain, even when later gains are stronger.
110    First,
111    /// Keep the greatest gain; ties retain the first request.
112    Strongest,
113    /// Keep the latest gain, even when weaker; retain the original slot order.
114    Latest,
115}
116
117/// Caller-authored category. Configuration must agree while its key is pending.
118/// No key value is reserved. See the module recipe.
119#[derive(Clone, Copy, Debug, PartialEq, Eq)]
120pub struct CueCategory {
121    pub key: u32,
122    pub cue: Cue,
123    pub policy: Coalesce,
124    pub critical: bool,
125}
126
127/// One retained raw request, before GameAudio acoustics or mixer admission.
128/// Construct through [`CueBatch::queue`]; see the module recipe.
129#[derive(Clone, Copy, Debug, PartialEq)]
130pub struct BatchedCue {
131    pub category: CueCategory,
132    pub position: Option<Vec3>,
133    pub gain: f32,
134}
135
136/// Validation errors leave pending work and counters unchanged, even if the
137/// runtime has changed. A subsequent valid operation/flush reconciles runtime.
138#[derive(Clone, Copy, Debug, PartialEq, Eq)]
139pub enum BatchError {
140    /// The const capacity must be in `1..=128`.
141    Capacity,
142    /// Raw gain must be finite and in `0..=4`, including both endpoints.
143    Gain,
144    /// Every coordinate of a supplied position must be finite.
145    Position,
146    /// Same pending key, different cue, coalescing policy or critical flag.
147    CategoryConflict,
148}
149
150/// Immediate storage decision; independent of later voice admission.
151#[derive(Clone, Copy, Debug, PartialEq)]
152#[must_use]
153pub enum QueueOutcome {
154    Retained,
155    /// One request merged; `replaced` means its gain was selected as replacement.
156    Coalesced {
157        replaced: bool,
158    },
159    /// Incoming critical request retained; this older noncritical was evicted.
160    Evicted(BatchedCue),
161    /// Incoming request lost at capacity; no pending slot changed.
162    Dropped,
163}
164
165/// Saturating counts since the preceding flush (or construction).
166/// `retained` counts insertions, including evicting insertions; `replaced` is a
167/// subset of `coalesced`. Dropped arrivals, evictions, explicit cancellations
168/// and runtime discards are separate. Current occupancy is [`CueBatch::len`].
169#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
170pub struct BatchCounts {
171    pub retained: usize,
172    pub coalesced: usize,
173    pub replaced: usize,
174    pub evicted: usize,
175    pub dropped: usize,
176    pub cancelled: usize,
177    pub runtime_discarded: usize,
178}
179
180/// Exact result of submitting one retained request through GameAudio.
181#[derive(Clone, Copy, Debug, PartialEq)]
182pub struct CueOutcome {
183    pub request: BatchedCue,
184    /// `None` is actual GameAudio pause suppression. `Some` retains the exact
185    /// started/stolen/rejection outcome, including acoustic gain validation.
186    pub admission: Option<VoiceAdmission>,
187}
188
189/// Fixed-storage flush result. The first `submitted` entries of `outcomes` are
190/// `Some`, in retained insertion order; all remaining entries are `None`.
191/// Counts describe submissions, not voices still live after later steals.
192#[derive(Clone, Debug, PartialEq)]
193pub struct FlushReport<const N: usize> {
194    pub batch: BatchCounts,
195    pub submitted: usize,
196    pub started: usize,
197    pub stolen: usize,
198    pub suppressed: usize,
199    pub rejected_invalid: usize,
200    pub rejected_reserved: usize,
201    pub rejected_priority: usize,
202    pub outcomes: [Option<CueOutcome>; N],
203}
204impl<const N: usize> FlushReport<N> {
205    /// Started plus stolen admissions, including muted/zero-gain voices.
206    /// See the module recipe.
207    pub fn admitted(&self) -> usize {
208        self.started + self.stolen
209    }
210    /// All mixer rejections, excluding GameAudio `None` suppression.
211    /// See [`CueBatch::flush`] and the module recipe.
212    pub fn rejected(&self) -> usize {
213        self.rejected_invalid + self.rejected_reserved + self.rejected_priority
214    }
215}
216
217/// Exclusive, thread-bound, one-frame accumulator. No implicit flush on drop.
218/// See the module recipe for fixed updates, terminal feedback and lifecycle.
219///
220/// ```compile_fail
221/// use ferravex_render::audio::{GameAudio, batch::CueBatch};
222/// let mut owner = GameAudio::new();
223/// let mut frame = CueBatch::<5>::new(&mut owner).unwrap();
224/// owner.reset(); // Pending work prevents direct lifecycle/owner replacement.
225/// frame.flush();
226/// ```
227///
228/// ```compile_fail
229/// use ferravex_render::audio::{GameAudio, batch::CueBatch};
230/// let mut owner = GameAudio::new();
231/// let frame = CueBatch::<5>::new(&mut owner).unwrap();
232/// std::thread::scope(|scope| { scope.spawn(move || drop(frame)); });
233/// ```
234pub struct CueBatch<'a, const N: usize> {
235    owner: &'a mut GameAudio,
236    runtime: Weak<()>,
237    pending: [Option<BatchedCue>; N],
238    len: usize,
239    counts: BatchCounts,
240}
241
242fn runtime_identity() -> Weak<()> {
243    super::AUDIO.with(|cell| {
244        cell.borrow()
245            .as_ref()
246            .map_or_else(Weak::new, |audio| Rc::downgrade(&audio.identity))
247    })
248}
249
250impl<'a, const N: usize> CueBatch<'a, N> {
251    /// Borrow a controller for one presentation frame. Does not initialize or
252    /// replace the mixer; normally GameAudio construction has prepared its bank.
253    /// Rejects capacities outside `1..=128`. See the module recipe.
254    pub fn new(owner: &'a mut GameAudio) -> Result<Self, BatchError> {
255        if N == 0 || N > 128 {
256            return Err(BatchError::Capacity);
257        }
258        Ok(Self {
259            owner,
260            runtime: runtime_identity(),
261            pending: [None; N],
262            len: 0,
263            counts: BatchCounts::default(),
264        })
265    }
266
267    /// Pending slots (may include runtime-stale requests until reconciliation).
268    pub fn len(&self) -> usize {
269        self.len
270    }
271    /// Whether no slots are pending. See [`Self::len`].
272    pub fn is_empty(&self) -> bool {
273        self.len == 0
274    }
275    /// Copy counters without resetting or reconciling the runtime.
276    pub fn counts(&self) -> BatchCounts {
277        self.counts
278    }
279    fn reconcile(&mut self, runtime: Weak<()>) {
280        if !Weak::ptr_eq(&self.runtime, &runtime) {
281            self.counts.runtime_discarded = self.counts.runtime_discarded.saturating_add(self.len);
282            self.clear();
283            self.runtime = runtime;
284        }
285    }
286    fn clear(&mut self) -> usize {
287        let len = self.len;
288        self.pending[..len].fill(None);
289        self.len = 0;
290        len
291    }
292
293    /// Collect only a caller-accepted event. Validation precedes any mutation.
294    /// Raw gains are not clamped; GameAudio also validates its resulting acoustic
295    /// gain at flush. Distinct positions never coalesce. See the module recipe.
296    /// Paused collection is permitted, but flush uses GameAudio's real suppression
297    /// (nonpositional Click bypasses pause). No resume API exists on the batch:
298    /// release it before resuming, so paused work cannot cross that boundary.
299    #[must_use = "handle validation and the storage decision"]
300    pub fn queue(
301        &mut self,
302        category: CueCategory,
303        position: Option<Vec3>,
304        gain: f32,
305    ) -> Result<QueueOutcome, BatchError> {
306        if !gain.is_finite() || !(0. ..=4.).contains(&gain) {
307            return Err(BatchError::Gain);
308        }
309        if position.is_some_and(|position| !position.is_finite()) {
310            return Err(BatchError::Position);
311        }
312        let runtime = runtime_identity();
313        if Weak::ptr_eq(&self.runtime, &runtime)
314            && self.pending[..self.len]
315                .iter()
316                .flatten()
317                .any(|entry| entry.category.key == category.key && entry.category != category)
318        {
319            return Err(BatchError::CategoryConflict);
320        }
321        self.reconcile(runtime);
322        let incoming = BatchedCue {
323            category,
324            position,
325            gain,
326        };
327        for entry in self.pending[..self.len].iter_mut().flatten() {
328            if entry.category.key == category.key && entry.position == position {
329                let replaced = match category.policy {
330                    Coalesce::First => false,
331                    Coalesce::Strongest => gain > entry.gain,
332                    Coalesce::Latest => true,
333                };
334                if replaced {
335                    *entry = incoming;
336                    self.counts.replaced = self.counts.replaced.saturating_add(1);
337                }
338                self.counts.coalesced = self.counts.coalesced.saturating_add(1);
339                return Ok(QueueOutcome::Coalesced { replaced });
340            }
341        }
342        let mut outcome = QueueOutcome::Retained;
343        if self.len == N {
344            let victim = category
345                .critical
346                .then(|| {
347                    self.pending[..self.len]
348                        .iter()
349                        .position(|entry| !entry.as_ref().unwrap().category.critical)
350                })
351                .flatten();
352            let Some(victim) = victim else {
353                self.counts.dropped = self.counts.dropped.saturating_add(1);
354                return Ok(QueueOutcome::Dropped);
355            };
356            outcome = QueueOutcome::Evicted(self.pending[victim].unwrap());
357            self.pending.copy_within(victim + 1..self.len, victim);
358            self.len -= 1;
359            self.counts.evicted = self.counts.evicted.saturating_add(1);
360        }
361        self.pending[self.len] = Some(incoming);
362        self.len += 1;
363        self.counts.retained = self.counts.retained.saturating_add(1);
364        Ok(outcome)
365    }
366
367    /// Discard pending cues without touching any controller's voices/settings.
368    /// Returns discarded slots; records `cancelled`. See the module recipe.
369    pub fn cancel(&mut self) -> usize {
370        let discarded = self.clear();
371        self.counts.cancelled = self.counts.cancelled.saturating_add(discarded);
372        discarded
373    }
374
375    /// Cancel all pending cues, then pause this owner. Already-playing UI clicks
376    /// and other owners' voices retain GameAudio semantics. See the module recipe.
377    pub fn pause(&mut self) -> usize {
378        let discarded = self.cancel();
379        self.owner.pause();
380        discarded
381    }
382
383    /// Cancel all pending cues, then reset this owner, preserving its pause and
384    /// acoustics. Call alongside game/session restart. See the module recipe.
385    pub fn reset(&mut self) -> usize {
386        let discarded = self.cancel();
387        self.owner.reset();
388        discarded
389    }
390
391    /// Consume retained requests once, in retained order, calling exactly
392    /// `cue_with_outcome` for `None` positions and `at_with_outcome` otherwise.
393    /// Clears frame counters after reporting, including on an empty flush.
394    /// Runtime-stale slots are discarded before any submission. Rejected or
395    /// paused requests are not queued for retry. See the module recipe.
396    pub fn flush(&mut self) -> FlushReport<N> {
397        self.reconcile(runtime_identity());
398        let mut report = FlushReport {
399            batch: std::mem::take(&mut self.counts),
400            submitted: self.len,
401            started: 0,
402            stolen: 0,
403            suppressed: 0,
404            rejected_invalid: 0,
405            rejected_reserved: 0,
406            rejected_priority: 0,
407            outcomes: [None; N],
408        };
409        for (entry, output) in self.pending[..self.len]
410            .iter_mut()
411            .zip(&mut report.outcomes)
412        {
413            let request = entry.take().unwrap();
414            let admission = match request.position {
415                Some(position) => {
416                    self.owner
417                        .at_with_outcome(request.category.cue, position, request.gain)
418                }
419                None => self
420                    .owner
421                    .cue_with_outcome(request.category.cue, request.gain),
422            };
423            match admission {
424                None => report.suppressed += 1,
425                Some(VoiceAdmission::Started(_)) => report.started += 1,
426                Some(VoiceAdmission::Stolen { .. }) => report.stolen += 1,
427                Some(VoiceAdmission::Rejected(reason)) => match reason {
428                    VoiceRejection::InvalidParams => report.rejected_invalid += 1,
429                    VoiceRejection::ReservedForCritical => report.rejected_reserved += 1,
430                    VoiceRejection::NoLowerPriority => report.rejected_priority += 1,
431                },
432            }
433            *output = Some(CueOutcome { request, admission });
434        }
435        self.len = 0;
436        // First submission may initialize a replacement runtime. There can be
437        // no interleaved host callbacks in this synchronous, thread-bound flush.
438        self.runtime = runtime_identity();
439        report
440    }
441}
442
443#[cfg(test)]
444mod tests {
445    use super::*;
446    use crate::audio::{self, Bus, Mixer, VoiceParams, VoicePolicy, playing};
447
448    fn category(key: u32, policy: Coalesce, critical: bool) -> CueCategory {
449        CueCategory {
450            key,
451            cue: Cue::Jump,
452            policy,
453            critical,
454        }
455    }
456    fn fresh(limit: usize) -> GameAudio {
457        audio::reset();
458        audio::set_muted(false);
459        audio::OFFLINE.with(|v| v.set(true));
460        let owner = GameAudio::new();
461        audio::AUDIO.with(|cell| {
462            cell.borrow_mut().as_mut().unwrap().mixer =
463                Mixer::new(audio::SAMPLE_RATE, limit).unwrap();
464        });
465        owner
466    }
467
468    #[test]
469    fn validation_is_atomic_including_category_conflicts_and_runtime_change() {
470        let mut owner = fresh(8);
471        assert!(matches!(
472            CueBatch::<0>::new(&mut owner),
473            Err(BatchError::Capacity)
474        ));
475        assert!(matches!(
476            CueBatch::<129>::new(&mut owner),
477            Err(BatchError::Capacity)
478        ));
479        let mut batch = CueBatch::<2>::new(&mut owner).unwrap();
480        let cat = category(1, Coalesce::Strongest, false);
481        assert_eq!(batch.queue(cat, None, 0.5), Ok(QueueOutcome::Retained));
482        let before = batch.counts();
483        for gain in [
484            f32::NAN,
485            f32::INFINITY,
486            f32::NEG_INFINITY,
487            -0.01,
488            4.000001,
489            f32::MAX,
490        ] {
491            assert_eq!(batch.queue(cat, None, gain), Err(BatchError::Gain));
492            assert_eq!(batch.counts(), before);
493        }
494        for position in [Vec3::splat(f32::NAN), Vec3::new(0., f32::INFINITY, 0.)] {
495            assert_eq!(
496                batch.queue(cat, Some(position), 0.5),
497                Err(BatchError::Position)
498            );
499            assert_eq!(batch.counts(), before);
500        }
501        for conflict in [
502            CueCategory {
503                cue: Cue::Fire,
504                ..cat
505            },
506            CueCategory {
507                policy: Coalesce::Latest,
508                ..cat
509            },
510            CueCategory {
511                critical: true,
512                ..cat
513            },
514        ] {
515            assert_eq!(
516                batch.queue(conflict, Some(Vec3::ZERO), 0.7),
517                Err(BatchError::CategoryConflict)
518            );
519            assert_eq!(batch.counts(), before);
520        }
521        assert_eq!(batch.len(), 1);
522        assert_eq!(batch.pending[0].unwrap().gain, 0.5);
523        audio::reset();
524        assert_eq!(batch.queue(cat, None, f32::NAN), Err(BatchError::Gain));
525        assert_eq!((batch.len(), batch.counts()), (1, before));
526        let report = batch.flush();
527        assert_eq!((report.submitted, report.batch.runtime_discarded), (0, 1));
528        // A new runtime and fresh valid request can reuse the key/configuration.
529        audio::preload_cues();
530        assert_eq!(
531            batch.queue(
532                CueCategory {
533                    cue: Cue::Fire,
534                    ..cat
535                },
536                None,
537                4.
538            ),
539            Ok(QueueOutcome::Retained)
540        );
541        let report = batch.flush();
542        assert_eq!((report.submitted, report.admitted()), (1, 1));
543        let _ = batch.queue(cat, None, 0.5).unwrap();
544        audio::reset();
545        audio::preload_cues();
546        // Valid collection also reconciles; a stale configuration cannot
547        // conflict with a new runtime's category definition.
548        assert_eq!(
549            batch.queue(
550                CueCategory {
551                    cue: Cue::Fire,
552                    ..cat
553                },
554                None,
555                0.6
556            ),
557            Ok(QueueOutcome::Retained)
558        );
559        let report = batch.flush();
560        assert_eq!((report.submitted, report.batch.runtime_discarded), (1, 1));
561    }
562
563    #[test]
564    fn selection_policies_are_explicit_and_positions_never_merge() {
565        let mut owner = fresh(16);
566        let mut batch = CueBatch::<8>::new(&mut owner).unwrap();
567        for (key, policy) in [
568            (1, Coalesce::First),
569            (2, Coalesce::Strongest),
570            (3, Coalesce::Latest),
571        ] {
572            let cat = category(key, policy, false);
573            assert_eq!(batch.queue(cat, None, 0.5), Ok(QueueOutcome::Retained));
574            assert_eq!(
575                batch.queue(cat, None, 0.9),
576                Ok(QueueOutcome::Coalesced {
577                    replaced: policy != Coalesce::First
578                })
579            );
580            assert_eq!(
581                batch.queue(cat, None, 0.1),
582                Ok(QueueOutcome::Coalesced {
583                    replaced: policy == Coalesce::Latest
584                })
585            );
586        }
587        let spatial = category(2, Coalesce::Strongest, false);
588        for position in [Vec3::ZERO, Vec3::new(-2., 0., 0.), Vec3::new(2., 0., 0.)] {
589            assert_eq!(
590                batch.queue(spatial, Some(position), 0.4),
591                Ok(QueueOutcome::Retained)
592            );
593            assert_eq!(
594                batch.queue(spatial, Some(position), 0.4),
595                Ok(QueueOutcome::Coalesced { replaced: false })
596            );
597        }
598        let report = batch.flush();
599        assert_eq!((report.submitted, report.admitted()), (6, 6));
600        assert_eq!(
601            (
602                report.batch.retained,
603                report.batch.coalesced,
604                report.batch.replaced
605            ),
606            (6, 9, 3)
607        );
608        let requests: Vec<_> = report
609            .outcomes
610            .into_iter()
611            .flatten()
612            .map(|o| o.request)
613            .collect();
614        assert_eq!(
615            [requests[0].gain, requests[1].gain, requests[2].gain],
616            [0.5, 0.9, 0.1]
617        );
618        audio::AUDIO.with(|cell| {
619            let state = cell.borrow();
620            let mixer = &state.as_ref().unwrap().mixer;
621            for outcome in report.outcomes.into_iter().flatten() {
622                let params = mixer
623                    .params(outcome.admission.unwrap().handle().unwrap())
624                    .unwrap();
625                assert_eq!(params.gain, outcome.request.gain);
626                if let Some(position) = outcome.request.position {
627                    assert_eq!(params.position, position.to_array());
628                }
629            }
630        });
631        assert_eq!(batch.counts(), BatchCounts::default());
632        assert_eq!(batch.flush().submitted, 0);
633    }
634
635    #[test]
636    fn critical_retention_eviction_all_critical_overflow_and_order() {
637        let mut owner = fresh(16);
638        let mut batch = CueBatch::<3>::new(&mut owner).unwrap();
639        for (key, critical) in [(1, false), (2, true), (3, false)] {
640            assert_eq!(
641                batch.queue(category(key, Coalesce::First, critical), None, 0.4),
642                Ok(QueueOutcome::Retained)
643            );
644        }
645        for (key, evicted) in [(4, 1), (5, 3)] {
646            let outcome = batch
647                .queue(category(key, Coalesce::First, true), None, 0.4)
648                .unwrap();
649            assert!(matches!(outcome, QueueOutcome::Evicted(e) if e.category.key == evicted));
650        }
651        for critical in [false, true] {
652            assert_eq!(
653                batch.queue(category(6, Coalesce::First, critical), None, 4.),
654                Ok(QueueOutcome::Dropped)
655            );
656        }
657        assert_eq!(
658            batch.queue(category(4, Coalesce::First, true), None, 4.),
659            Ok(QueueOutcome::Coalesced { replaced: false })
660        );
661        let report = batch.flush();
662        assert_eq!(report.batch.coalesced, 1);
663        assert_eq!(
664            (
665                report.batch.retained,
666                report.batch.evicted,
667                report.batch.dropped
668            ),
669            (5, 2, 2)
670        );
671        assert_eq!(
672            report.outcomes.map(|o| o.unwrap().request.category.key),
673            [2, 4, 5]
674        );
675        assert_eq!(report.admitted(), 3);
676    }
677
678    #[test]
679    fn pause_reset_cancel_drop_and_ui_click_semantics_preserve_other_owners() {
680        let mut owner = fresh(16);
681        let mut other = GameAudio::new();
682        let other_voice = other
683            .cue_with_outcome(Cue::Fire, 0.5)
684            .unwrap()
685            .handle()
686            .unwrap();
687        let own_voice = owner
688            .cue_with_outcome(Cue::Jump, 0.5)
689            .unwrap()
690            .handle()
691            .unwrap();
692        let ui_voice = owner
693            .cue_with_outcome(Cue::Click, 0.5)
694            .unwrap()
695            .handle()
696            .unwrap();
697        let cat = category(1, Coalesce::First, false);
698        {
699            let mut batch = CueBatch::<3>::new(&mut owner).unwrap();
700            let _ = batch.queue(cat, None, 0.5).unwrap();
701            assert_eq!(batch.pause(), 1);
702            assert!(!playing(own_voice));
703            assert!(playing(other_voice) && playing(ui_voice));
704            assert_eq!(batch.pause(), 0);
705            let click = CueCategory {
706                cue: Cue::Click,
707                ..cat
708            };
709            let _ = batch.queue(click, None, 0.5).unwrap();
710            let _ = batch.queue(click, Some(Vec3::ZERO), 0.5).unwrap();
711            let _ = batch
712                .queue(category(2, Coalesce::First, true), None, 0.5)
713                .unwrap();
714            let report = batch.flush();
715            assert_eq!(
716                (
717                    report.submitted,
718                    report.admitted(),
719                    report.suppressed,
720                    report.rejected()
721                ),
722                (3, 1, 2, 0)
723            );
724            assert!(
725                report.outcomes[0]
726                    .unwrap()
727                    .admission
728                    .unwrap()
729                    .handle()
730                    .is_some()
731            );
732            assert_eq!(report.outcomes[1].unwrap().admission, None);
733            assert_eq!(report.outcomes[2].unwrap().admission, None);
734            assert_eq!(report.batch.cancelled, 1);
735            let _ = batch.queue(cat, None, 0.5).unwrap();
736            assert_eq!(batch.reset(), 1);
737            assert_eq!(batch.flush().submitted, 0);
738        }
739        assert!(owner.is_paused());
740        owner.resume();
741        {
742            let mut batch = CueBatch::<3>::new(&mut owner).unwrap();
743            let _ = batch.queue(cat, None, 0.5).unwrap();
744            assert_eq!(batch.cancel(), 1);
745            let _ = batch.queue(cat, None, 0.5).unwrap();
746            // Drop cancels without stopping voices or submitting work.
747        }
748        assert!(playing(other_voice) && playing(ui_voice));
749        assert_eq!(audio::stats().active, 3); // Other, original UI, paused-frame UI.
750        assert_eq!(CueBatch::<3>::new(&mut owner).unwrap().flush().submitted, 0);
751        // Controller replacement after releasing the borrow cannot inherit cues.
752        owner = GameAudio::new();
753        assert_eq!(CueBatch::<3>::new(&mut owner).unwrap().flush().submitted, 0);
754        assert!(playing(other_voice));
755    }
756
757    #[test]
758    fn runtime_replacement_discards_queue_and_preserves_reused_voice_handles() {
759        for operation in 0..3 {
760            let mut old = fresh(16);
761            let old_voice = old
762                .cue_with_outcome(Cue::Jump, 0.5)
763                .unwrap()
764                .handle()
765                .unwrap();
766            let mut batch = CueBatch::<2>::new(&mut old).unwrap();
767            let _ = batch
768                .queue(category(1, Coalesce::First, false), None, 0.5)
769                .unwrap();
770            audio::reset();
771            let mut replacement = GameAudio::new();
772            let new_voice = replacement
773                .cue_with_outcome(Cue::Fire, 0.5)
774                .unwrap()
775                .handle()
776                .unwrap();
777            assert_eq!(old_voice, new_voice); // Raw handle alias, different runtime.
778            if operation == 0 {
779                let report = batch.flush();
780                assert_eq!((report.submitted, report.batch.runtime_discarded), (0, 1));
781            } else if operation == 1 {
782                assert_eq!(batch.pause(), 1);
783            } else {
784                assert_eq!(batch.reset(), 1);
785            }
786            assert!(playing(new_voice));
787            // New work after reconciliation belongs to the current runtime.
788            let _ = batch
789                .queue(category(2, Coalesce::First, true), None, 0.4)
790                .unwrap();
791            let report = batch.flush();
792            assert_eq!(
793                (report.admitted(), report.suppressed),
794                if operation == 1 { (0, 1) } else { (1, 0) }
795            );
796            drop(batch);
797            drop(old);
798            assert!(playing(new_voice));
799        }
800    }
801
802    #[test]
803    fn reports_actual_admission_steals_reservations_and_mute_independently() {
804        let mut owner = fresh(2);
805        audio::AUDIO.with(|cell| {
806            assert!(
807                cell.borrow_mut()
808                    .as_mut()
809                    .unwrap()
810                    .mixer
811                    .set_voice_policy(Some(VoicePolicy {
812                        critical_priority: 5,
813                        reserved_critical: 1,
814                    }))
815            );
816        });
817        let mut batch = CueBatch::<5>::new(&mut owner).unwrap();
818        // Storage critical flags deliberately differ from mixer priorities.
819        for (key, cue, critical) in [
820            (1, Cue::Jump, false),
821            (2, Cue::Success, true),
822            (3, Cue::Fire, false),
823            (4, Cue::Failure, true),
824            (5, Cue::Fire, true),
825        ] {
826            let _ = batch
827                .queue(
828                    CueCategory {
829                        key,
830                        cue,
831                        policy: Coalesce::First,
832                        critical,
833                    },
834                    None,
835                    0.4,
836                )
837                .unwrap();
838        }
839        let report = batch.flush();
840        assert_eq!(
841            (
842                report.started,
843                report.stolen,
844                report.rejected_reserved,
845                report.rejected_priority,
846                report.suppressed
847            ),
848            (2, 1, 1, 1, 0)
849        );
850        assert_eq!((report.admitted(), report.rejected()), (3, 2));
851        let first = report.outcomes[0]
852            .unwrap()
853            .admission
854            .unwrap()
855            .handle()
856            .unwrap();
857        assert_eq!(
858            report.outcomes[3].unwrap().admission.unwrap().replaced(),
859            Some(first)
860        );
861        assert!(!playing(first));
862        audio::stop_all();
863        audio::set_muted(true);
864        let _ = batch
865            .queue(category(1, Coalesce::First, true), None, 0.5)
866            .unwrap();
867        let report = batch.flush();
868        assert_eq!(
869            (report.admitted(), report.suppressed, report.rejected()),
870            (1, 0, 0)
871        );
872        let mut pcm = [[1.; 2]; 512];
873        assert!(audio::render(&mut pcm, audio::SAMPLE_RATE));
874        assert!(pcm.iter().flatten().all(|v| v.is_finite() && *v == 0.));
875        audio::set_muted(false);
876        audio::stop_all();
877        let _ = batch
878            .queue(category(1, Coalesce::First, false), None, 0.)
879            .unwrap();
880        let _ = batch
881            .queue(category(2, Coalesce::First, false), None, 4.)
882            .unwrap();
883        let report = batch.flush();
884        assert_eq!((report.admitted(), report.rejected_reserved), (1, 1));
885        assert!(audio::render(&mut pcm, audio::SAMPLE_RATE));
886        assert!(pcm.iter().flatten().all(|v| v.is_finite()));
887    }
888
889    #[test]
890    fn minimum_and_maximum_capacity_use_full_bound_and_reset() {
891        let mut owner = fresh(128);
892        let mut batch = CueBatch::<128>::new(&mut owner).unwrap();
893        for key in 0..128 {
894            assert_eq!(
895                batch.queue(category(key, Coalesce::First, true), None, 0.1),
896                Ok(QueueOutcome::Retained)
897            );
898        }
899        assert_eq!(batch.len(), 128);
900        assert_eq!(
901            batch.queue(category(128, Coalesce::First, true), None, 4.),
902            Ok(QueueOutcome::Dropped)
903        );
904        let report = batch.flush();
905        assert_eq!(
906            (report.submitted, report.admitted(), report.batch.dropped),
907            (128, 128, 1)
908        );
909        assert!(report.outcomes.iter().all(Option::is_some));
910        assert_eq!(batch.reset(), 0);
911        assert_eq!(audio::stats().active, 0);
912        let mut one = CueBatch::<1>::new(&mut owner).unwrap();
913        let _ = one
914            .queue(category(1, Coalesce::First, false), None, 0.1)
915            .unwrap();
916        assert!(matches!(
917            one.queue(category(2, Coalesce::First, true), None, 0.1),
918            Ok(QueueOutcome::Evicted(_))
919        ));
920        assert_eq!(one.flush().admitted(), 1);
921    }
922
923    #[test]
924    fn acoustics_applied_once_and_spatial_click_stays_on_effects_bus() {
925        let mut owner = fresh(8);
926        assert!(owner.set_acoustics(audio::AcousticProfile {
927            gain: 0.5,
928            low_pass_hz: 1200.
929        }));
930        let mut batch = CueBatch::<2>::new(&mut owner).unwrap();
931        let cat = CueCategory {
932            cue: Cue::Click,
933            ..category(1, Coalesce::Strongest, false)
934        };
935        let _ = batch.queue(cat, None, 0.8).unwrap();
936        let _ = batch.queue(cat, Some(Vec3::new(-3., 2., 1.)), 0.8).unwrap();
937        let report = batch.flush();
938        audio::AUDIO.with(|cell| {
939            let state = cell.borrow();
940            let mixer = &state.as_ref().unwrap().mixer;
941            let ui = mixer
942                .params(
943                    report.outcomes[0]
944                        .unwrap()
945                        .admission
946                        .unwrap()
947                        .handle()
948                        .unwrap(),
949                )
950                .unwrap();
951            let spatial = mixer
952                .params(
953                    report.outcomes[1]
954                        .unwrap()
955                        .admission
956                        .unwrap()
957                        .handle()
958                        .unwrap(),
959                )
960                .unwrap();
961            assert_eq!((ui.gain, ui.bus, ui.priority), (0.8, Bus::Ui, 2));
962            assert_eq!(
963                (
964                    spatial.gain,
965                    spatial.bus,
966                    spatial.priority,
967                    spatial.low_pass_hz
968                ),
969                (0.4, Bus::Effects, 3, 1200.)
970            );
971            assert_eq!(spatial.position, [-3., 2., 1.]);
972            assert_ne!(spatial, VoiceParams::default());
973        });
974        let mut pcm = [[0.; 2]; 512];
975        assert!(audio::render(&mut pcm, audio::SAMPLE_RATE));
976        assert!(pcm.iter().flatten().all(|v| v.is_finite()));
977        assert!(pcm.iter().flatten().any(|v| v.abs() > 0.001));
978    }
979}