mirage-engine 0.1.1

Mirage, an immediate-mode 3D engine for simple games on desktop and the browser
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
//! What a frame submits for playback: the commands, the part of a clip a
//! voice plays, and the levels it is heard at.

use core::f32::consts::FRAC_PI_4;
use core::time::Duration;
use std::sync::Arc;

use crate::View;
use crate::math::Vec3;
use crate::sound::build::Knobs;
use crate::sound::data::{Clip, ClipFrame};

/// Voices the mixer plays at once.
///
/// The cap is an allocation: every batch of commands the mixer ranks what it
/// holds by audibility and plays the loudest this many. It never refuses a
/// declaration.
pub const MAX_VOICES: usize = 64;

/// Span a change of levels slides over where a cue states none, and the span
/// the master volume always slides over.
pub(crate) const GLIDE: Duration = Duration::from_millis(50);

/// How far past the frame now playing a streamed clip stays decoded and
/// scheduled.
pub(crate) const STREAM_AHEAD: Duration = Duration::from_millis(1_500);

/// Mixer volume limit; past it the mix curves towards one.
const LIMITER_KNEE: f32 = 0.75;

/// Names which of the bank's sounds a voice plays.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub(crate) struct SoundId(pub(crate) u32);

/// What a sustain keeps one voice alive under: a sound, and which of the
/// places it sounds at this voice is.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub(crate) struct Sustained {
    pub(crate) sound: SoundId,
    pub(crate) instance: u32,
}

impl Sustained {
    /// What `knobs` sustain `sound` under, or nothing where they play it
    /// once.
    ///
    /// A one-shot is a voice of its own, so it keeps none alive and takes no
    /// instance; a debug log reports the instance it set.
    pub(crate) fn of(sound: SoundId, knobs: &Knobs, sustained: bool) -> Option<Self> {
        if !sustained {
            if knobs.instance != 0 {
                log::debug!("a one-shot is a voice of its own; ignoring the instance it names");
            }
            return None;
        }

        Some(Self {
            sound,
            instance: knobs.instance,
        })
    }
}

/// Frame request for sound controls, in submission order.
pub(crate) enum Command {
    /// A voice of its own, which plays out and ends.
    Play(Voicing),
    /// Everything the frame declared sustained, in declaration order, which
    /// is the whole set the game wants sounding.
    ///
    /// A mix that reads no command batch keeps the last set; one that reads
    /// more than one takes the last, since each is the whole set.
    Sustained(Vec<(Sustained, Voicing)>),
    /// The master gain, as of this frame.
    Volume(f32),
}

/// Everything a voice needs when it starts.
///
/// The window is the one part a voice keeps for as long as it sounds.
pub(crate) struct Voicing {
    /// Which of the bank's sounds it plays.
    // The page's backend holds one buffer per sound; the desktop's plays the
    // clip this carries and never reads which sound it is, and a `cfg` on the
    // target may only select a module.
    #[allow(dead_code)]
    pub(crate) sound: SoundId,
    pub(crate) clip: Arc<Clip>,
    pub(crate) window: Window,
    pub(crate) live: LiveKnobs,
}

impl Voicing {
    /// The level this is heard at, which is where it enters the rank.
    pub(crate) fn audibility(&self) -> f32 {
        self.live.levels.loudest()
    }
}

/// The knobs a frame sets on a voice, whether it is starting or already
/// sounding.
///
/// The levels slide to their new values over the `glide`. A new pitch plays
/// on from the frame the voice is at. A new fade sets the pace of every fade
/// from then on, one already moving included.
#[derive(Clone, Copy, Debug)]
pub(crate) struct LiveKnobs {
    pub(crate) levels: Levels,
    pub(crate) pitch: f32,
    pub(crate) fade: Duration,
    pub(crate) glide: Duration,
}

/// Level a voice is heard at in each ear, as of this frame.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Levels {
    pub(crate) left: f32,
    pub(crate) right: f32,
}

impl Levels {
    /// The louder of the two ears, which is what the rank reads.
    pub(crate) fn loudest(self) -> f32 {
        self.left.max(self.right)
    }
}

/// The part of a clip a voice plays, and where it comes back to.
///
/// Positions are frames of the clip's own timeline.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct Window {
    pub(crate) start: ClipFrame,
    pub(crate) end: ClipFrame,
    pub(crate) wrap: ClipFrame,
    pub(crate) looping: bool,
}

impl Window {
    /// The part of `clip` that `knobs` plays, or nothing where the trim
    /// leaves no room.
    pub(crate) fn of(clip: &Clip, knobs: &Knobs, looping: bool) -> Option<Self> {
        let total = ClipFrame::new(clip.frames);
        let (start, end) = match knobs.trim {
            Some((from, to)) => {
                let (from, to) = (clip.rate.frame_at(from), clip.rate.frame_at(to));
                if from > total || to > total {
                    log::debug!("a trim asks for more than the sound has; keeping what it has");
                }
                (from.min(total), to.min(total))
            }
            None => (ClipFrame::ZERO, total),
        };
        if end <= start {
            log::debug!("a trim leaves nothing of the sound to play");
            return None;
        }

        let wrap = match knobs.loop_from {
            Some(_) if !looping => {
                log::debug!("a one-shot never comes back around; ignoring where it would loop");
                start
            }
            Some(at) if !(start..end).contains(&clip.rate.frame_at(at)) => {
                log::debug!("a loop starts outside what is played; coming back to the start");
                start
            }
            Some(at) => clip.rate.frame_at(at),
            None => start,
        };

        Some(Self {
            start,
            end,
            wrap,
            looping,
        })
    }

    /// The clip frame after `played` frames of playback, or nothing once a
    /// one-shot has played out.
    pub(crate) fn at(&self, played: ClipFrame) -> Option<ClipFrame> {
        let intro = self.end - self.start;
        if played < intro {
            return Some(self.start + played);
        }
        if !self.looping {
            return None;
        }

        Some(self.wrap + (played - intro) % (self.end - self.wrap))
    }
}

/// What a frame declared sustained, in declaration order.
///
/// The last call for one value in a frame is the one that counts, and the
/// call it replaces is dropped with a debug log.
#[derive(Default)]
pub(crate) struct Declared(Vec<(Sustained, Voicing)>);

impl Declared {
    pub(crate) fn declare(&mut self, sustained: Sustained, voicing: Voicing) {
        match self.0.iter_mut().find(|(kept, _)| *kept == sustained) {
            Some(kept) => {
                log::debug!(
                    "a sound is sustained twice at one instance in one frame; keeping the last call"
                );
                kept.1 = voicing;
            }
            None => self.0.push((sustained, voicing)),
        }
    }

    /// The whole set the frame declared, which leaves this empty for the
    /// next one.
    pub(crate) fn take(&mut self) -> Vec<(Sustained, Voicing)> {
        core::mem::take(&mut self.0)
    }
}

/// A voice a backend plays, as the cap and the fades read it.
pub(crate) trait Audible {
    /// What paces a change: the mix rate on the desktop, the reading of the
    /// page's clock in a browser.
    type Pace: Copy;

    /// The level it is heard at, which is where it enters the rank.
    fn audibility(&self, pace: Self::Pace) -> f32;

    /// Fades it over its `fade`, where no set declares it.
    fn stop(&mut self, pace: Self::Pace);

    /// Rises back over its `fade`, where a set declares it again.
    fn rise(&mut self, pace: Self::Pace);

    /// Fades it over its `glide`, where the rank leaves it out.
    fn cut(&mut self, pace: Self::Pace);

    /// Rises back over its `glide`, where the rank keeps it again.
    fn recover(&mut self, pace: Self::Pace);

    /// Whether it is heard no more: its fade landed, or it played out.
    fn spent(&self, pace: Self::Pace) -> bool;
}

/// What a sustained value is doing: the voice the rank gave it, or none.
pub(crate) enum Playing<V> {
    /// No voice at all, which is what a value below the cut holds.
    Virtual,
    /// The voice the rank keeps for it.
    Voiced(V),
    /// A voice on its way out, which frees its slot where the fade lands.
    Fading(V, Fade),
}

/// Why a voice fades, which states what is left of the value where the fade
/// lands.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum Fade {
    /// No set declares it: the value is over where the fade lands.
    Stop,
    /// The rank left it out: the value is virtual where the fade lands.
    Cut,
}

impl<V: Audible> Playing<V> {
    /// The voice it holds, for the frames a backend takes out of it.
    pub(crate) fn voice(&self) -> Option<&V> {
        match self {
            Self::Virtual => None,
            Self::Voiced(voice) | Self::Fading(voice, _) => Some(voice),
        }
    }

    pub(crate) fn voice_mut(&mut self) -> Option<&mut V> {
        match self {
            Self::Virtual => None,
            Self::Voiced(voice) | Self::Fading(voice, _) => Some(voice),
        }
    }

    /// Takes a set that declares this one again: a voice fading because no
    /// set declared it rises back and plays on, and one the rank cut fades
    /// on, since only the rank takes the cut back.
    pub(crate) fn declared(&mut self, pace: V::Pace) {
        *self = match core::mem::replace(self, Self::Virtual) {
            Self::Fading(mut voice, Fade::Stop) => {
                voice.rise(pace);
                Self::Voiced(voice)
            }
            held => held,
        };
    }

    /// States that no set declares this one, and returns whether anything is
    /// left to hold: a value with no voice is over here and now.
    #[must_use]
    pub(crate) fn stopped(&mut self, pace: V::Pace) -> bool {
        *self = match core::mem::replace(self, Self::Virtual) {
            Self::Virtual => return false,
            Self::Voiced(mut voice) | Self::Fading(mut voice, _) => {
                voice.stop(pace);
                Self::Fading(voice, Fade::Stop)
            }
        };

        true
    }

    /// Takes what the rank decided: a value it keeps virtual takes the voice
    /// `start` makes for it, and one it leaves out fades over its `glide`.
    ///
    /// A backend that makes no voice leaves the value virtual, for the rank
    /// to take up again.
    pub(crate) fn voiced(&mut self, wins: bool, pace: V::Pace, start: impl FnOnce() -> Option<V>) {
        *self = match (wins, core::mem::replace(self, Self::Virtual)) {
            (true, Self::Virtual) => match start() {
                Some(voice) => Self::Voiced(voice),
                None => Self::Virtual,
            },
            (true, Self::Fading(mut voice, Fade::Cut)) => {
                voice.recover(pace);
                Self::Voiced(voice)
            }
            (false, Self::Voiced(mut voice)) => {
                voice.cut(pace);
                Self::Fading(voice, Fade::Cut)
            }
            (_, held) => held,
        };
    }

    /// The level the voice it holds is heard at, and no level at all where
    /// it holds none.
    pub(crate) fn audibility(&self, pace: V::Pace) -> f32 {
        self.voice().map_or(0.0, |voice| voice.audibility(pace))
    }

    /// Whether the voice it holds is heard no more, which is when a one-shot
    /// is over.
    pub(crate) fn spent(&self, pace: V::Pace) -> bool {
        self.voice().is_none_or(|voice| voice.spent(pace))
    }

    /// The voice of one whose fade has landed, with why it faded, leaving
    /// the value virtual; the backend takes the position and the levels it
    /// reached out of it.
    pub(crate) fn landed(&mut self, pace: V::Pace) -> Option<(V, Fade)> {
        match core::mem::replace(self, Self::Virtual) {
            Self::Fading(voice, why) if voice.spent(pace) => Some((voice, why)),
            held => {
                *self = held;
                None
            }
        }
    }
}

/// One sustained value a backend holds, voiced or virtual, as [`Sustains`]
/// reads it.
pub(crate) trait Sustaining: Sized {
    /// What paces a change: the mix rate on the desktop, the reading of the
    /// page's clock in a browser.
    type Pace: Copy;

    /// What the backend takes a voice out of: nothing on the desktop, the
    /// page's graph in a browser.
    type Voices<'a>;

    /// A value a set declared for the first time, at its window start and
    /// with no voice until the rank takes one for it.
    fn started(sustained: Sustained, voicing: Voicing, pace: Self::Pace) -> Self;

    /// What a set keeps this one sounding under.
    fn sustained(&self) -> Sustained;

    /// Takes what this frame declared: the knobs are live, and the window
    /// stays the one the voice started on.
    fn declare(&mut self, voicing: Voicing, pace: Self::Pace);

    /// States that the last set left this one out, and returns whether the
    /// table still holds it.
    fn stop(&mut self, pace: Self::Pace) -> bool;

    /// Takes a voice for this one, or fades the one it holds, as the rank
    /// decided.
    fn voiced(&mut self, wins: bool, voices: &mut Self::Voices<'_>, pace: Self::Pace);

    /// The level it is heard at, which is where it enters the rank.
    fn audibility(&self, pace: Self::Pace) -> f32;

    /// Frees a voice whose fade has landed, and returns whether the table
    /// still holds this one.
    fn settle(&mut self, pace: Self::Pace) -> bool;
}

/// Every sustained value a backend holds, voiced or virtual, in declaration
/// order, followed by the ones the last set left out while they fade.
pub(crate) struct Sustains<S: Sustaining> {
    held: Vec<S>,
    allocation: Allocation,
}

impl<S: Sustaining> Default for Sustains<S> {
    fn default() -> Self {
        Self {
            held: Vec::new(),
            allocation: Allocation::default(),
        }
    }
}

impl<S: Sustaining> Sustains<S> {
    /// Takes `declared` as the whole set the game wants sounding: each of
    /// them plays on or starts, and every value left out fades over its fade
    /// and is then dropped.
    pub(crate) fn declare(&mut self, declared: Vec<(Sustained, Voicing)>, pace: S::Pace) {
        let mut was = core::mem::take(&mut self.held);
        let mut table = Vec::with_capacity(declared.len());
        for (sustained, voicing) in declared {
            let held = match was
                .iter()
                .position(|held| held.sustained() == sustained)
                .map(|at| was.swap_remove(at))
            {
                Some(mut held) => {
                    held.declare(voicing, pace);
                    held
                }
                None => S::started(sustained, voicing, pace),
            };
            table.push(held);
        }

        table.extend(
            was.into_iter()
                .filter_map(|mut gone| gone.stop(pace).then_some(gone)),
        );
        self.held = table;
    }

    /// Ranks everything the backend holds and voices the loudest of them:
    /// these sustains, then the one-shots it plays, then the one-shots this
    /// batch played, in that order.
    ///
    /// Every sustain and every one-shot takes, keeps or loses its voice
    /// here. What is left of `starting` is what the rank kept, in the order
    /// it was played; the rest never start.
    pub(crate) fn allocate<V: Audible<Pace = S::Pace>>(
        &mut self,
        shots: &mut [Playing<V>],
        starting: &mut Vec<Voicing>,
        voices: &mut S::Voices<'_>,
        pace: S::Pace,
    ) {
        self.allocation.rank(
            self.held
                .iter()
                .map(|held| held.audibility(pace))
                .chain(shots.iter().map(|shot| shot.audibility(pace)))
                .chain(starting.iter().map(Voicing::audibility)),
        );

        let mut voiced = self.allocation.voiced();
        for (held, wins) in self.held.iter_mut().zip(voiced.by_ref()) {
            held.voiced(wins, voices, pace);
        }
        for (shot, wins) in shots.iter_mut().zip(voiced.by_ref()) {
            // A one-shot holds its voice from the frame it starts, so the
            // rank never starts one here; `starting` is the list that does.
            shot.voiced(wins, pace, || None);
        }
        starting.retain(|_| {
            let wins = voiced.next().unwrap_or(false);
            if !wins {
                log::debug!("a one-shot is quieter than what is sounding; it does not start");
            }
            wins
        });
    }

    /// Frees every voice whose fade has landed, and drops the values no set
    /// declares any longer.
    pub(crate) fn settle(&mut self, pace: S::Pace) {
        self.held.retain_mut(|held| held.settle(pace));
    }

    pub(crate) fn iter_mut(&mut self) -> impl Iterator<Item = &mut S> {
        self.held.iter_mut()
    }

    /// The values themselves, for the tests that read what they hold.
    #[cfg(test)]
    pub(crate) fn iter(&self) -> impl Iterator<Item = &S> {
        self.held.iter()
    }
}

/// Which of what a backend holds the cap voices, for one batch of commands.
///
/// Rank everything the backend holds by audibility, then read back whether
/// each of them is voiced, in the order they were ranked. One allocation is
/// kept and ranked again every batch, so a mix makes no allocation of its
/// own.
#[derive(Default)]
struct Allocation {
    /// Level of each, with where it came in, loudest first once ranked.
    ranked: Vec<(f32, usize)>,
    voiced: Vec<bool>,
}

impl Allocation {
    /// Voices the loudest [`MAX_VOICES`] of `audibility`, the level of
    /// everything the backend holds, in declaration order.
    ///
    /// Two at one level keep the order they come in, so the game's own order
    /// is the only thing between them. Nothing at no level is voiced at all,
    /// however few are sounding.
    fn rank(&mut self, audibility: impl Iterator<Item = f32>) {
        self.ranked.clear();
        self.ranked
            .extend(audibility.enumerate().map(|(at, level)| (level, at)));
        self.voiced.clear();
        self.voiced.resize(self.ranked.len(), false);
        self.ranked
            .sort_by(|(one, _), (other, _)| other.total_cmp(one));

        for (_, at) in self
            .ranked
            .iter()
            .take(MAX_VOICES)
            .filter(|(level, _)| *level > 0.0)
        {
            self.voiced[*at] = true;
        }
    }

    /// Whether each of the ranked holds a voice, in the order they were
    /// ranked.
    fn voiced(&self) -> impl Iterator<Item = bool> {
        self.voiced.iter().copied()
    }
}

/// Level `knobs` are heard at in each ear, from where the listener is: a
/// placed sound is panned and falls off with its distance.
pub(crate) fn levels(knobs: &Knobs, listener: &View) -> Levels {
    let Some(position) = knobs.position else {
        return Levels {
            left: knobs.gain,
            right: knobs.gain,
        };
    };

    let towards = position - listener.eye();
    let falloff = knobs.falloff.level(towards.length());
    let forward = (listener.target() - listener.eye()).normalize_or_zero();
    let side = forward.cross(listener.up()).normalize_or_zero();
    let pan = towards.normalize_or(Vec3::ZERO).dot(side).clamp(-1.0, 1.0);

    // Constant power: each gain is `cos` or `sin` of one angle, so the total
    // power is the same at every pan.
    let angle = (pan + 1.0) * FRAC_PI_4;
    Levels {
        left: knobs.gain * falloff * angle.cos(),
        right: knobs.gain * falloff * angle.sin(),
    }
}

/// Curves `sample` towards one instead of cutting it off, leaving everything
/// below the knee alone.
pub(crate) fn limit(sample: f32) -> f32 {
    let over = sample.abs() - LIMITER_KNEE;
    if over <= 0.0 {
        return sample;
    }

    let room = 1.0 - LIMITER_KNEE;
    (LIMITER_KNEE + room * (over / room).tanh()).copysign(sample)
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;
    use crate::sound::build::Falloff;
    use crate::sound::data::{Body, Channels, SampleRate};
    use crate::sound::output::MixRate;

    pub(crate) const RATE: SampleRate = SampleRate::new(8);

    /// The rate the mixes under test run at, which is the rate a decode
    /// leaves their clips at.
    pub(crate) const MIX: MixRate = MixRate::chosen(RATE);

    /// The number a frame number is divided by to make a sample of it: not
    /// loud enough for the limiter to touch any of them, and a power of
    /// two, so that it divides exactly.
    pub(crate) const QUIET: f32 = 64.0;

    /// A tone of `hertz`, `frames` long at `rate`, at half of full scale so
    /// that the limiter leaves it alone.
    pub(crate) fn tone(rate: SampleRate, hertz: f64, frames: usize) -> Vec<f32> {
        (0..frames)
            .map(|at| {
                let turn = core::f64::consts::TAU * hertz * at as f64 / f64::from(rate);
                (0.5 * turn.sin()) as f32
            })
            .collect()
    }

    /// A clip whose every sample holds which frame it is, so a mix of it
    /// reads back the order its frames came out in.
    pub(crate) fn counted(frames: u64) -> Arc<Clip> {
        clip((0..frames).map(|at| at as f32 / QUIET).collect())
    }

    pub(crate) fn clip(samples: Vec<f32>) -> Arc<Clip> {
        Arc::new(Clip {
            rate: RATE,
            channels: Channels::Mono,
            frames: samples.len() as u64,
            body: Body::Samples(samples.into()),
        })
    }

    pub(crate) fn knobs() -> Knobs {
        Knobs {
            gain: 1.0,
            pitch: 1.0,
            position: None,
            falloff: Falloff::DEFAULT,
            fade: Duration::ZERO,
            glide: Duration::ZERO,
            trim: None,
            loop_from: None,
            instance: 0,
        }
    }

    /// The first place `sound` sounds at, which is where a sustain naming no
    /// instance goes.
    pub(crate) fn sustained(sound: u32) -> Sustained {
        Sustained {
            sound: SoundId(sound),
            instance: 0,
        }
    }

    pub(crate) fn seconds(frames: u64) -> Duration {
        Duration::from_secs_f64(frames as f64 / f64::from(RATE))
    }

    pub(crate) fn voicing(clip: &Arc<Clip>, knobs: &Knobs, looping: bool) -> Voicing {
        leveled(clip, knobs, looping, 1.0)
    }

    /// A [`Voicing`] of `clip` heard at `level` in both ears, which is what
    /// the rank reads.
    pub(crate) fn leveled(clip: &Arc<Clip>, knobs: &Knobs, looping: bool, level: f32) -> Voicing {
        Voicing {
            sound: SoundId(0),
            clip: Arc::clone(clip),
            window: Window::of(clip, knobs, looping).expect("the window holds something"),
            live: LiveKnobs {
                levels: Levels {
                    left: level,
                    right: level,
                },
                pitch: knobs.pitch,
                fade: knobs.fade,
                glide: knobs.glide,
            },
        }
    }

    #[test]
    fn a_value_sustained_twice_in_one_frame_goes_out_once_from_the_last_call() {
        let clip = counted(10);
        let faster = Knobs {
            pitch: 2.0,
            ..knobs()
        };
        let mut declared = Declared::default();

        declared.declare(sustained(1), voicing(&clip, &knobs(), true));
        declared.declare(sustained(1), voicing(&clip, &faster, true));
        declared.declare(sustained(2), voicing(&clip, &knobs(), true));

        let set = declared.take();
        assert!(
            matches!(set.as_slice(), [(first, kept), (second, _)]
                if *first == sustained(1) && kept.live.pitch == faster.pitch && *second == sustained(2)),
            "one entry apiece, the first from its last call, in declaration order"
        );
        assert!(declared.take().is_empty(), "and the frame starts empty");
    }

    /// A voice under test: what the value holding it did to it, in order,
    /// and whether it is heard no more.
    #[derive(Default)]
    struct Fake {
        done: Vec<&'static str>,
        spent: bool,
    }

    impl Audible for Fake {
        type Pace = ();

        fn audibility(&self, _: ()) -> f32 {
            1.0
        }

        fn stop(&mut self, _: ()) {
            self.done.push("stop");
        }

        fn rise(&mut self, _: ()) {
            self.done.push("rise");
        }

        fn cut(&mut self, _: ()) {
            self.done.push("cut");
        }

        fn recover(&mut self, _: ()) {
            self.done.push("recover");
        }

        fn spent(&self, _: ()) -> bool {
            self.spent
        }
    }

    /// What `playing` did to the voice it holds, in order.
    fn done(playing: &Playing<Fake>) -> Vec<&'static str> {
        playing
            .voice()
            .map(|voice| voice.done.clone())
            .unwrap_or_default()
    }

    #[test]
    fn a_value_declared_again_while_it_fades_out_rises_back_and_keeps_its_voice() {
        let mut playing = Playing::Voiced(Fake::default());

        assert!(playing.stopped(()), "a voice fades before the value goes");
        playing.declared(());

        assert!(matches!(playing, Playing::Voiced(_)));
        assert_eq!(done(&playing), ["stop", "rise"], "and it plays on");
    }

    #[test]
    fn a_value_with_no_voice_is_over_where_no_set_declares_it() {
        let mut playing: Playing<Fake> = Playing::Virtual;

        assert!(!playing.stopped(()), "nothing fades, so nothing is held");
    }

    #[test]
    fn a_value_the_rank_cuts_keeps_its_voice_until_the_fade_lands() {
        let mut playing = Playing::Voiced(Fake::default());

        playing.voiced(false, (), || None);

        assert_eq!(done(&playing), ["cut"], "the rank leaves it out");
        assert!(playing.landed(()).is_none(), "and the fade runs on");

        playing.voice_mut().expect("it holds a voice").spent = true;
        let (_, why) = playing.landed(()).expect("the fade landed");

        assert_eq!(why, Fade::Cut, "so the value goes on virtual");
        assert!(matches!(playing, Playing::Virtual));
    }

    #[test]
    fn a_value_the_rank_voices_again_rises_back_and_keeps_the_voice_it_had() {
        let mut playing = Playing::Voiced(Fake::default());
        playing.voiced(false, (), || None);

        playing.voiced(true, (), || None);

        assert!(matches!(playing, Playing::Voiced(_)), "the voice it had");
        assert_eq!(done(&playing), ["cut", "recover"]);
    }

    #[test]
    fn a_declaration_never_takes_back_the_cut_the_rank_made() {
        let mut playing = Playing::Voiced(Fake::default());
        playing.voiced(false, (), || None);

        playing.declared(());

        assert!(matches!(playing, Playing::Fading(_, Fade::Cut)));
        assert_eq!(done(&playing), ["cut"], "only the rank voices it again");
    }

    #[test]
    fn the_rank_has_no_say_over_a_value_no_set_declares() {
        let mut playing = Playing::Voiced(Fake::default());
        assert!(playing.stopped(()), "the value is on its way out");

        playing.voiced(true, (), || Some(Fake::default()));
        playing.voiced(false, (), || None);

        assert!(matches!(playing, Playing::Fading(_, Fade::Stop)));
        assert_eq!(done(&playing), ["stop"], "neither risen nor cut again");
    }

    #[test]
    fn the_backend_starts_a_voice_for_a_virtual_value_the_rank_keeps() {
        let mut playing: Playing<Fake> = Playing::Virtual;
        let mut refused: Playing<Fake> = Playing::Virtual;

        playing.voiced(true, (), || Some(Fake::default()));
        refused.voiced(true, (), || None);

        assert!(matches!(playing, Playing::Voiced(_)));
        assert!(
            matches!(refused, Playing::Virtual),
            "and one the backend made no voice for stays virtual"
        );
    }

    #[test]
    fn the_rank_voices_the_loudest_and_nothing_at_no_level() {
        let mut allocation = Allocation::default();

        allocation.rank([0.5, 1.0, 0.0, 0.25].into_iter());

        assert_eq!(
            allocation.voiced().collect::<Vec<bool>>(),
            [true, true, false, true],
            "room for all of them, but never for one at no level"
        );
    }

    #[test]
    fn the_rank_cuts_at_the_cap_and_ties_keep_the_order_they_came_in() {
        let over = MAX_VOICES + 8;
        let mut allocation = Allocation::default();

        allocation.rank(core::iter::repeat_n(0.5, over));

        let voiced: Vec<bool> = allocation.voiced().collect();
        assert_eq!(voiced.len(), over, "every one of them is ranked");
        assert_eq!(
            voiced.iter().filter(|voiced| **voiced).count(),
            MAX_VOICES,
            "and the cap is what is voiced"
        );
        assert!(
            voiced[..MAX_VOICES].iter().all(|voiced| *voiced),
            "the ones declared first, since nothing is louder than another"
        );
    }

    #[test]
    fn the_rank_takes_the_loudest_however_late_it_came_in() {
        let mut levels = vec![0.5; MAX_VOICES];
        levels.push(1.0);
        let mut allocation = Allocation::default();

        allocation.rank(levels.into_iter());

        let voiced: Vec<bool> = allocation.voiced().collect();
        assert!(voiced[MAX_VOICES], "the loudest, declared last of all");
        assert_eq!(
            voiced.iter().filter(|voiced| **voiced).count(),
            MAX_VOICES,
            "and one of the rest lost its voice for it"
        );
        assert!(!voiced[MAX_VOICES - 1], "the last of the ones that tied");
    }

    #[test]
    fn a_trim_clamps_to_the_clip_and_an_empty_one_plays_nothing() {
        let clip = counted(10);
        let past_the_end = Knobs {
            trim: Some((seconds(4), seconds(40))),
            ..knobs()
        };
        let backwards = Knobs {
            trim: Some((seconds(6), seconds(2))),
            ..knobs()
        };

        let window = Window::of(&clip, &past_the_end, false).expect("what is there still plays");
        assert_eq!((window.start.get(), window.end.get()), (4, 10));
        assert!(Window::of(&clip, &backwards, false).is_none());
    }

    #[test]
    fn a_loop_outside_the_window_comes_back_to_its_start_instead() {
        let clip = counted(10);
        let outside = Knobs {
            trim: Some((seconds(4), seconds(8))),
            loop_from: Some(seconds(1)),
            ..knobs()
        };
        let inside = Knobs {
            loop_from: Some(seconds(6)),
            ..outside
        };

        assert_eq!(
            Window::of(&clip, &outside, true)
                .expect("it plays")
                .wrap
                .get(),
            4
        );
        assert_eq!(
            Window::of(&clip, &inside, true)
                .expect("it plays")
                .wrap
                .get(),
            6
        );
        assert_eq!(
            Window::of(&clip, &inside, false)
                .expect("it plays")
                .wrap
                .get(),
            4,
            "a one-shot never comes back around"
        );
    }

    #[test]
    fn a_window_walks_its_intro_once_and_its_body_forever() {
        let clip = counted(10);
        let looped = Knobs {
            trim: Some((seconds(2), seconds(8))),
            loop_from: Some(seconds(5)),
            ..knobs()
        };
        let window = Window::of(&clip, &looped, true).expect("it plays");

        let walked: Vec<u64> = (0..12u64)
            .filter_map(|played| window.at(ClipFrame::new(played)).map(ClipFrame::get))
            .collect();
        assert_eq!(walked, [2, 3, 4, 5, 6, 7, 5, 6, 7, 5, 6, 7]);

        let once = Window::of(&clip, &looped, false).expect("it plays");
        assert_eq!(once.at(ClipFrame::new(5)), Some(ClipFrame::new(7)));
        assert_eq!(once.at(ClipFrame::new(6)), None, "and then it is over");
    }

    #[test]
    fn one_value_at_two_instances_is_two_sustained_values_and_a_one_shot_is_none() {
        let second = Knobs {
            instance: 1,
            ..knobs()
        };

        assert_eq!(
            Sustained::of(SoundId(3), &knobs(), true),
            Some(sustained(3))
        );
        assert_eq!(
            Sustained::of(SoundId(3), &second, true),
            Some(Sustained {
                sound: SoundId(3),
                instance: 1
            }),
            "which the first one is not"
        );
        assert_eq!(
            Sustained::of(SoundId(3), &second, false),
            None,
            "and a one-shot keeps no voice alive to name"
        );
    }

    #[test]
    fn the_limiter_leaves_a_quiet_mix_alone_and_bends_a_loud_one() {
        assert_eq!(limit(0.5), 0.5);
        assert_eq!(limit(-LIMITER_KNEE), -LIMITER_KNEE);
        assert!(limit(1.0) > LIMITER_KNEE && limit(1.0) < 1.0);
        assert!(limit(64.0) <= 1.0, "nothing ever leaves past one");
        assert_eq!(limit(-4.0), -limit(4.0), "and it bends both ways alike");
    }

    #[test]
    fn a_placed_sound_is_panned_and_fades_with_distance() {
        let listener = View::look_at(Vec3::ZERO, Vec3::NEG_Z);
        let placed = |position| {
            levels(
                &Knobs {
                    position: Some(position),
                    falloff: Falloff::DEFAULT.with_range(10.0),
                    ..knobs()
                },
                &listener,
            )
        };

        let right = placed(Vec3::X);
        let left = placed(Vec3::NEG_X);
        let ahead = placed(Vec3::NEG_Z);

        assert!(right.right > right.left, "to the right is heard right");
        assert!(
            (left.left - right.right).abs() < 1e-6 && (left.right - right.left).abs() < 1e-6,
            "and one side is the other side turned around"
        );
        assert!(
            (ahead.left - ahead.right).abs() < 1e-6,
            "and straight ahead is heard in both"
        );
        assert!(placed(Vec3::NEG_Z * 5.0).left < ahead.left, "fading out");
        assert_eq!(placed(Vec3::NEG_Z * 20.0).left, 0.0, "to nothing at range");
    }

    #[test]
    fn a_placed_sound_holds_its_level_to_the_reference_and_halves_at_twice_it() {
        let listener = View::look_at(Vec3::ZERO, Vec3::NEG_Z);
        let straight = FRAC_PI_4.cos();
        let level = |meters: f32, falloff| {
            levels(
                &Knobs {
                    position: Some(Vec3::NEG_Z * meters),
                    falloff,
                    ..knobs()
                },
                &listener,
            )
            .left
                / straight
        };
        let far = Falloff::DEFAULT.with_reference(2.0).with_range(1_000.0);
        let near = Falloff::DEFAULT.with_range(10.0);

        assert_eq!(level(1.0, far), 1.0, "full level within the reference");
        assert_eq!(level(2.0, far), 1.0, "and at the reference itself");
        assert!(
            (level(4.0, far) - 0.5).abs() < 2e-3,
            "half of it at twice the reference, but for the shift's share"
        );
        assert_eq!(level(10.0, near), 0.0, "nothing at the range");
        assert_eq!(level(20.0, near), 0.0, "and nothing past it");
    }

    #[test]
    fn a_sound_with_no_place_is_heard_the_same_in_both_ears() {
        let listener = View::look_at(Vec3::ZERO, Vec3::NEG_Z);
        let heard = levels(
            &Knobs {
                gain: 0.5,
                ..knobs()
            },
            &listener,
        );

        assert_eq!(
            heard,
            Levels {
                left: 0.5,
                right: 0.5
            }
        );
    }
}