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
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
//! The mix the engine makes for itself on the desktop. A browser build
//! leaves it out; the page mixes there instead.

use core::time::Duration;
use std::collections::VecDeque;
use std::sync::Arc;

use crate::assets::Stream;
use crate::sound::MixRate;
use crate::sound::data::{Body, Clip, ClipFrame, Encoded, SampleRate};
use crate::sound::mixer::{
    Audible, Command, Fade, GLIDE, Levels, LiveKnobs, Playing, STREAM_AHEAD, Sustained, Sustaining,
    Sustains, Voicing, Window, limit,
};

/// Frames of a streamed clip one mixed block decodes, which bounds the
/// work of the block a voice starts in.
const DECODE_PER_BLOCK: usize = 8_192;

/// Everything the game wants sounding, and what the voices it holds add up
/// to.
pub(crate) struct Mixer {
    rate: SampleRate,
    sustained: Sustains<Sustain>,
    /// One-shots with a voice, in the order they started.
    shots: Vec<Playing<Voice>>,
    /// One-shots this batch played; the rank takes the ones it voices, and
    /// what is left never starts.
    starting: Vec<Voicing>,
    volume: Slide,
}

impl Mixer {
    pub(crate) fn new(rate: MixRate) -> Self {
        Self {
            rate: rate.get(),
            sustained: Sustains::default(),
            shots: Vec::new(),
            starting: Vec::new(),
            volume: Slide::held(1.0),
        }
    }

    pub(crate) fn apply(&mut self, command: Command) {
        match command {
            Command::Play(voicing) => self.starting.push(voicing),
            Command::Sustained(declared) => self.sustained.declare(declared, self.rate),
            Command::Volume(volume) => self.volume.aim(volume.max(0.0), GLIDE, self.rate),
        }
    }

    /// Fills `block` with what everything sounding adds up to.
    pub(crate) fn mix(&mut self, block: &mut [MixFrame]) {
        let rate = self.rate;
        self.allocate();
        for sustain in self.sustained.iter_mut() {
            sustain.decode();
        }
        for shot in self.shots.iter_mut().filter_map(Playing::voice_mut) {
            shot.decode();
        }

        let frames = block.len();
        for frame in block {
            let mut mixed = MixFrame::SILENT;
            for sustain in self.sustained.iter_mut() {
                mixed += sustain.frame();
            }
            for shot in self.shots.iter_mut().filter_map(Playing::voice_mut) {
                mixed += shot.frame();
            }
            let volume = self.volume.advance();
            *frame = MixFrame::new(limit(mixed.left() * volume), limit(mixed.right() * volume));
        }

        for sustain in self.sustained.iter_mut() {
            sustain.advance(frames as f64);
        }
        self.shots.retain(|shot| !shot.spent(rate));
        self.sustained.settle(rate);
    }

    /// Number of voices sounding, for the tests that count them.
    #[cfg(test)]
    pub(crate) fn sounding(&self) -> usize {
        self.shots.len()
            + self
                .sustained
                .iter()
                .filter(|sustain| sustain.playing.voice().is_some())
                .count()
    }

    /// Ranks everything the mixer holds, so that the loudest of them take the
    /// voices, and starts the one-shots the rank kept.
    fn allocate(&mut self) {
        let rate = self.rate;
        self.sustained
            .allocate(&mut self.shots, &mut self.starting, &mut (), rate);

        for voicing in self.starting.drain(..) {
            let levels = Sliding::held(voicing.live.levels);
            let voice = Voice::new(voicing, ClipFrame::ZERO, levels, rate);
            self.shots.push(Playing::Voiced(voice));
        }
    }
}

/// One sustained value the game wants sounding, with the voice the rank gave
/// it or none while it is virtual.
struct Sustain {
    sustained: Sustained,
    clip: Arc<Clip>,
    /// The window it started on; a later declaration never moves it.
    window: Window,
    live: LiveKnobs,
    /// The level it is heard at, which goes on sliding while it is virtual;
    /// a voice it holds keeps the slide while it plays.
    levels: Sliding,
    /// Where its playback has reached, which advances whether a voice plays
    /// it or not; a voice it holds keeps the position while it plays.
    played: Played,
    playing: Playing<Voice>,
}

impl Sustaining for Sustain {
    type Pace = SampleRate;
    type Voices<'a> = ();

    fn started(sustained: Sustained, voicing: Voicing, _: SampleRate) -> Self {
        Self {
            sustained,
            clip: voicing.clip,
            window: voicing.window,
            levels: Sliding::held(voicing.live.levels),
            live: voicing.live,
            played: Played::default(),
            playing: Playing::Virtual,
        }
    }

    fn sustained(&self) -> Sustained {
        self.sustained
    }

    fn declare(&mut self, voicing: Voicing, rate: SampleRate) {
        if voicing.window != self.window {
            log::debug!(
                "a sustained value declared a different window while sounding; keeping the one it started on"
            );
        }
        self.live = voicing.live;
        match self.playing.voice_mut() {
            Some(voice) => voice.retarget(self.live, rate),
            None => self.levels.aim(self.live.levels, self.live.glide, rate),
        }
        self.playing.declared(rate);
    }

    fn stop(&mut self, rate: SampleRate) -> bool {
        self.playing.stopped(rate)
    }

    fn voiced(&mut self, wins: bool, _: &mut (), rate: SampleRate) {
        let started = || {
            let voicing = Voicing {
                sound: self.sustained.sound,
                clip: Arc::clone(&self.clip),
                window: self.window,
                live: self.live,
            };

            Some(Voice::new(voicing, self.played.at(), self.levels, rate))
        };

        self.playing.voiced(wins, rate, started);
    }

    fn audibility(&self, rate: SampleRate) -> f32 {
        match self.playing.voice() {
            Some(voice) => voice.audibility(rate),
            None => self.levels.loudest(),
        }
    }

    fn settle(&mut self, rate: SampleRate) -> bool {
        match self.playing.landed(rate) {
            Some((voice, Fade::Cut)) => {
                self.played = Played::reached(voice.reached());
                self.levels = voice.levels;
                true
            }
            Some((_, Fade::Stop)) => false,
            None => true,
        }
    }
}

impl Sustain {
    /// The voice's next mixed frame, and silence while it is virtual.
    fn frame(&mut self) -> MixFrame {
        match self.playing.voice_mut() {
            Some(voice) => voice.frame(),
            None => MixFrame::SILENT,
        }
    }

    /// Advances a virtual value over `frames` of the mix as if a voice had
    /// played it: the position and the levels it would have reached.
    fn advance(&mut self, frames: f64) {
        if self.playing.voice().is_none() {
            self.played.advance(f64::from(self.live.pitch) * frames);
            self.levels.advance_by(frames);
        }
    }

    fn decode(&mut self) {
        if let Some(voice) = self.playing.voice_mut() {
            voice.decode();
        }
    }
}

/// Frames of playback a sustained value has taken, to a fraction of a frame.
#[derive(Clone, Copy, Default)]
struct Played {
    frames: ClipFrame,
    over: f64,
}

impl Played {
    /// The position a voice played to.
    fn reached(frames: ClipFrame) -> Self {
        Self { frames, over: 0.0 }
    }

    /// The clip frame it has reached, which is where a voice enters.
    fn at(self) -> ClipFrame {
        self.frames
    }

    /// Takes `frames` of playback, which may be a fraction of a frame.
    fn advance(&mut self, frames: f64) {
        self.over += frames;
        let whole = self.over.trunc();
        self.over -= whole;
        self.frames += whole as u64;
    }
}

/// One sound being played.
struct Voice {
    clip: Arc<Clip>,
    source: Source,
    window: Window,
    /// Frames of playback taken from the clip so far.
    played: ClipFrame,
    /// The level it is heard at, sliding to the one the last declaration set.
    levels: Sliding,
    envelope: Envelope,
    /// Span its start and its stop fade over.
    fade: Duration,
    /// Span a change of levels slides over, and the span the rank cutting it
    /// fades it over.
    glide: Duration,
    /// Clip frames one mixed frame advances by: the pitch, since the clip is
    /// already at the mix's rate.
    step: f64,
    /// Fraction the mix lies between the two clip frames `previous` and
    /// `next`.
    over: f64,
    previous: MixFrame,
    next: MixFrame,
    ended: bool,
}

impl Voice {
    /// A voice playing `voicing` from clip frame `played`, at the levels
    /// `levels` has reached.
    fn new(voicing: Voicing, played: ClipFrame, levels: Sliding, rate: SampleRate) -> Self {
        let Voicing {
            clip,
            window,
            live: LiveKnobs {
                pitch, fade, glide, ..
            },
            ..
        } = voicing;
        let source = match &clip.body {
            Body::Samples(samples) => Source::Resident(Arc::clone(samples)),
            Body::Encoded(encoded) => {
                Source::Streamed(Streaming::new(Arc::clone(encoded), played, clip.rate))
            }
        };

        Self {
            step: f64::from(pitch),
            clip,
            source,
            window,
            played,
            levels,
            envelope: Envelope::rising(fade, rate),
            fade,
            glide,
            // Two clip frames must be read before a mixed frame can lie
            // between them.
            over: 2.0,
            previous: MixFrame::SILENT,
            next: MixFrame::SILENT,
            ended: false,
        }
    }

    /// Takes the knobs a frame set without moving the voice: the levels slide
    /// over the `glide`, playback plays on at the new step, and a fade from
    /// here on takes the new span.
    fn retarget(&mut self, live: LiveKnobs, rate: SampleRate) {
        self.levels.aim(live.levels, live.glide, rate);
        self.fade = live.fade;
        self.glide = live.glide;
        self.step = f64::from(live.pitch);
    }

    /// The clip frame that comes out next, which is one behind what the voice
    /// has read: a mixed frame lies between the two clip frames around it.
    fn reached(&self) -> ClipFrame {
        self.played.back(1)
    }

    /// The voice's next mixed frame, at its current gain.
    fn frame(&mut self) -> MixFrame {
        while self.over >= 1.0 {
            if self.ended {
                return MixFrame::SILENT;
            }
            match self.pull() {
                Pulled::Waiting => return MixFrame::SILENT,
                Pulled::Frame(frame) => {
                    self.previous = self.next;
                    self.next = frame;
                    self.over -= 1.0;
                }
                Pulled::Done => {
                    self.previous = self.next;
                    self.next = MixFrame::SILENT;
                    self.ended = true;
                    self.over -= 1.0;
                }
            }
        }

        let over = self.over as f32;
        let gain = self.envelope.advance();
        let (left, right) = self.levels.advance();
        let frame = MixFrame::new(
            (self.previous.left() + (self.next.left() - self.previous.left()) * over) * gain * left,
            (self.previous.right() + (self.next.right() - self.previous.right()) * over)
                * gain
                * right,
        );
        self.over += self.step;

        frame
    }

    /// The next frame of the clip, in playback order.
    fn pull(&mut self) -> Pulled {
        let channels = self.clip.channels.count();
        let window = self.window;
        let played = self.played;
        let pulled = match &mut self.source {
            Source::Resident(samples) => match window.at(played) {
                Some(at) => match samples.get(at.get() as usize * channels..) {
                    Some(from) if from.len() >= channels => {
                        Pulled::Frame(MixFrame::spread(&from[..channels]))
                    }
                    _ => Pulled::Done,
                },
                None => Pulled::Done,
            },
            Source::Streamed(streaming) => streaming.pull(&window, channels),
        };

        if matches!(pulled, Pulled::Frame(_)) {
            self.played += 1;
        }
        pulled
    }

    /// Decodes more of a streamed clip, if that is what this voice plays.
    fn decode(&mut self) {
        let ahead = (STREAM_AHEAD.as_secs_f64() * f64::from(self.clip.rate)) as usize;
        let channels = self.clip.channels.count();
        let window = self.window;
        if let Source::Streamed(streaming) = &mut self.source {
            streaming.decode(&window, channels, ahead);
        }
    }
}

impl Audible for Voice {
    type Pace = SampleRate;

    fn audibility(&self, _: SampleRate) -> f32 {
        self.levels.loudest() * self.envelope.reach()
    }

    fn stop(&mut self, rate: SampleRate) {
        self.envelope.aim(0.0, self.fade, rate);
    }

    fn rise(&mut self, rate: SampleRate) {
        self.envelope.aim(1.0, self.fade, rate);
    }

    fn cut(&mut self, rate: SampleRate) {
        self.envelope.aim(0.0, self.glide, rate);
    }

    fn recover(&mut self, rate: SampleRate) {
        self.envelope.aim(1.0, self.glide, rate);
    }

    fn spent(&self, rate: SampleRate) -> bool {
        (self.ended && self.over >= 1.0) || self.audibility(rate) == 0.0
    }
}

/// Source of a voice's frames.
enum Source {
    Resident(Arc<[f32]>),
    Streamed(Streaming),
}

/// A clip decoded as it plays, and what has been decoded so far.
struct Streaming {
    /// Absent once the clip is spent or has stopped decoding; boxed
    /// because a decoder is far larger than the samples it makes.
    stream: Option<Box<Stream>>,
    /// Frames decoded and not yet played, in playback order.
    ahead: VecDeque<f32>,
    produced: ClipFrame,
}

impl Streaming {
    fn new(clip: Arc<Encoded>, played: ClipFrame, rate: SampleRate) -> Self {
        Self {
            stream: Stream::open(clip, rate)
                .inspect_err(|error| log::debug!("{error}"))
                .map(Box::new)
                .ok(),
            ahead: VecDeque::new(),
            produced: played,
        }
    }

    fn pull(&mut self, window: &Window, channels: usize) -> Pulled {
        if self.ahead.len() < channels {
            return match (self.stream.is_some(), window.at(self.produced)) {
                (true, Some(_)) => Pulled::Waiting,
                _ => Pulled::Done,
            };
        }

        let left = self.ahead.pop_front().unwrap_or_default();
        Pulled::Frame(MixFrame::new(
            left,
            match channels {
                1 => left,
                _ => self.ahead.pop_front().unwrap_or_default(),
            },
        ))
    }

    /// Decodes until `ahead` frames are left to play, doing at most one
    /// block's worth of the work.
    fn decode(&mut self, window: &Window, channels: usize, ahead: usize) {
        let Some(mut stream) = self.stream.take() else {
            return;
        };

        let mut budget = DECODE_PER_BLOCK;
        while self.ahead.len() / channels < ahead && budget > 0 {
            let Some(at) = window.at(self.produced) else {
                return;
            };
            if stream.position() != at
                && let Err(error) = stream.seek(at)
            {
                log::debug!("{error}");
                return;
            }

            match stream.read(
                budget.min((window.end - at).get() as usize),
                &mut self.ahead,
            ) {
                Ok(0) => return,
                Ok(read) => {
                    self.produced += read as u64;
                    budget -= read;
                }
                Err(error) => {
                    log::debug!("{error}");
                    return;
                }
            }
        }

        self.stream = Some(stream);
    }
}

/// A frame of a voice, or why there is none.
enum Pulled {
    Frame(MixFrame),
    /// The decode has not caught up; the voice keeps its place.
    Waiting,
    Done,
}

/// A voice's own gain as it comes up and goes down.
#[derive(Clone, Copy)]
struct Envelope {
    level: f32,
    target: f32,
    pace: f32,
}

impl Envelope {
    fn rising(fade: Duration, rate: SampleRate) -> Self {
        Self {
            level: 0.0,
            target: 1.0,
            pace: Self::paced(fade, rate),
        }
    }

    /// Fraction of a fade one frame at `rate` covers.
    fn paced(fade: Duration, rate: SampleRate) -> f32 {
        let frames = fade.as_secs_f32() * f32::from(rate);
        match frames > 1.0 {
            true => 1.0 / frames,
            false => 1.0,
        }
    }

    /// Fades to `target` over `span`, from where it stands.
    fn aim(&mut self, target: f32, span: Duration, rate: SampleRate) {
        self.pace = Self::paced(span, rate);
        self.target = target;
    }

    /// What the fade counts for in the rank: one on its way up counts as the
    /// level it will reach, one on its way down as the level it has.
    fn reach(&self) -> f32 {
        self.level.max(self.target)
    }

    /// A step towards the target, and the gain that leaves for this frame.
    fn advance(&mut self) -> f32 {
        self.level = match self.level < self.target {
            true => (self.level + self.pace).min(self.target),
            false => (self.level - self.pace).max(self.target),
        };

        self.level
    }
}

/// The level a sound is heard at in each ear, each ear sliding to the target
/// the last declaration set.
#[derive(Clone, Copy)]
struct Sliding {
    left: Slide,
    right: Slide,
}

impl Sliding {
    /// Levels that stay where they are until a frame sets a target.
    fn held(levels: Levels) -> Self {
        Self {
            left: Slide::held(levels.left),
            right: Slide::held(levels.right),
        }
    }

    /// Slides to `levels`, which both ears reach `span` from here.
    fn aim(&mut self, levels: Levels, span: Duration, rate: SampleRate) {
        self.left.aim(levels.left, span, rate);
        self.right.aim(levels.right, span, rate);
    }

    /// The louder of what the two ears are at and what they slide to, which
    /// is what the rank reads: a level on its way down still counts while it
    /// is there.
    fn loudest(&self) -> f32 {
        self.left.loudest().max(self.right.loudest())
    }

    /// One frame of the slide, and the level that leaves for each ear.
    fn advance(&mut self) -> (f32, f32) {
        (self.left.advance(), self.right.advance())
    }

    /// As many frames of the slide as a mixed block holds, for a value no
    /// voice is playing.
    fn advance_by(&mut self, frames: f64) {
        self.left.advance_by(frames);
        self.right.advance_by(frames);
    }
}

/// A level that slides to the target a frame sets, linear over a span.
#[derive(Clone, Copy)]
struct Slide {
    level: f32,
    target: f32,
    step: f32,
}

impl Slide {
    /// A level that stays where it is until a frame sets a target.
    fn held(level: f32) -> Self {
        Self {
            level,
            target: level,
            step: 0.0,
        }
    }

    /// Slides to `target`, which it reaches `span` from here; a span shorter
    /// than one frame is a step, taken here and now.
    ///
    /// A target it is already sliding to keeps the course it is on, so a
    /// frame loop that declares one gain every frame slides over one span.
    fn aim(&mut self, target: f32, span: Duration, rate: SampleRate) {
        if target == self.target {
            return;
        }

        let frames = span.as_secs_f32() * f32::from(rate);
        match frames > 1.0 {
            true => self.step = (target - self.level) / frames,
            false => {
                self.step = 0.0;
                self.level = target;
            }
        }
        self.target = target;
    }

    /// The louder of where it is and where it slides to.
    fn loudest(&self) -> f32 {
        self.level.max(self.target)
    }

    /// One frame of the slide, and the level that leaves for this frame.
    fn advance(&mut self) -> f32 {
        self.advance_by(1.0);

        self.level
    }

    /// Slides as far as `frames` of the mix take it.
    fn advance_by(&mut self, frames: f64) {
        let step = self.step * frames as f32;
        self.level = match self.step < 0.0 {
            true => (self.level + step).max(self.target),
            false => (self.level + step).min(self.target),
        };
    }
}

/// One frame of the mix: the sample heard in each ear, left then right.
#[derive(Clone, Copy)]
#[repr(transparent)]
pub(crate) struct MixFrame([f32; 2]);

impl MixFrame {
    /// A frame nothing is heard in.
    pub(crate) const SILENT: Self = Self([0.0; 2]);

    /// A frame heard at `left` in one ear and `right` in the other.
    #[inline]
    fn new(left: f32, right: f32) -> Self {
        Self([left, right])
    }

    /// One frame of a clip as a frame of the mix: a mono frame is heard in
    /// both ears.
    #[inline]
    fn spread(frame: &[f32]) -> Self {
        Self(match frame {
            [mono] => [*mono, *mono],
            [left, right, ..] => [*left, *right],
            [] => [0.0; 2],
        })
    }

    /// The sample one of a device's channels takes, and silence past the
    /// two the mix holds.
    #[inline]
    pub(crate) fn ear(self, channel: usize) -> f32 {
        self.0.get(channel).copied().unwrap_or_default()
    }

    #[inline]
    fn left(self) -> f32 {
        self.0[0]
    }

    #[inline]
    fn right(self) -> f32 {
        self.0[1]
    }
}

impl core::ops::AddAssign for MixFrame {
    #[inline]
    fn add_assign(&mut self, other: Self) {
        self.0[0] += other.0[0];
        self.0[1] += other.0[1];
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::sound::SoundData;
    use crate::sound::build::Knobs;
    use crate::sound::data::Channels;
    use crate::sound::mixer::tests::{
        MIX, QUIET, clip, counted, knobs, leveled, seconds, sustained, tone, voicing,
    };
    use crate::sound::mixer::{MAX_VOICES, SoundId};

    /// The rate the master volume tests mix at: [`GLIDE`] spans four frames
    /// here, which is what they read.
    const MASTER: MixRate = MixRate::chosen(SampleRate::new(80));

    /// A clip whose every sample is the same, for what a mix does to its
    /// gain.
    fn flat(frames: u64) -> Arc<Clip> {
        clip(vec![0.5; frames as usize])
    }

    /// A clip nothing is heard of, for the declarations that fill the cap
    /// without being heard.
    fn silent(frames: u64) -> Arc<Clip> {
        clip(vec![0.0; frames as usize])
    }

    /// A clip of one level at the rate [`MASTER`] mixes at.
    fn steady() -> Arc<Clip> {
        Arc::new(Clip {
            rate: MASTER.get(),
            channels: Channels::Mono,
            frames: 64,
            body: Body::Samples(vec![0.5; 64].into()),
        })
    }

    /// Declares `set` as the whole of what the game wants sounding.
    fn declare(mixer: &mut Mixer, set: Vec<(Sustained, Voicing)>) {
        mixer.apply(Command::Sustained(set));
    }

    /// One sustained value of `clip`, heard at `level`.
    fn one(
        sustained: Sustained,
        clip: &Arc<Clip>,
        knobs: &Knobs,
        level: f32,
    ) -> (Sustained, Voicing) {
        (sustained, leveled(clip, knobs, true, level))
    }

    /// `count` sustained values of `clip` at `level`, one per instance from
    /// `first` on, for filling the cap.
    fn filling(clip: &Arc<Clip>, first: u32, count: u32, level: f32) -> Vec<(Sustained, Voicing)> {
        (first..first + count)
            .map(|instance| {
                let sustained = Sustained {
                    sound: SoundId(0),
                    instance,
                };
                one(sustained, clip, &knobs(), level)
            })
            .collect()
    }

    /// The test tone as a game that streams it plays it: decoded a packet
    /// at a time, out of the bytes its source loaded.
    fn streamed() -> Arc<Clip> {
        let encoded = Arc::new(
            crate::assets::ogg::decode(crate::assets::SWEEP).expect("the fixture decodes"),
        );

        Arc::new(Clip {
            rate: encoded.rate(),
            channels: encoded.channels(),
            frames: encoded.frames(),
            body: Body::Encoded(encoded),
        })
    }

    /// Samples a mix of [`counted`] reads back when it plays these frames of
    /// it.
    fn heard(frames: &[u64]) -> Vec<f32> {
        frames.iter().map(|&at| at as f32 / QUIET).collect()
    }

    /// Samples the left ear hears over the next `frames` mixed frames.
    fn mixed(mixer: &mut Mixer, frames: usize) -> Vec<f32> {
        let mut block = vec![MixFrame::SILENT; frames];
        mixer.mix(&mut block);
        block.iter().map(|frame| frame.left()).collect()
    }

    /// The left ear of what a mix at `rate` plays `data` as, over the next
    /// `frames` of it.
    fn played(data: &SoundData, rate: MixRate, frames: usize) -> Vec<f32> {
        let clip = Arc::new(crate::sound::resolve(data, Some(rate)));
        let mut mixer = Mixer::new(rate);
        mixer.apply(Command::Play(voicing(&clip, &knobs(), false)));

        mixed(&mut mixer, frames)
    }

    /// How loud everything in `heard` but the tone at `hertz` is, against
    /// that tone, in decibels; `heard` must hold whole turns of it.
    fn noise(heard: &[f32], hertz: f64, rate: SampleRate) -> f32 {
        let turn = |at: usize| core::f64::consts::TAU * hertz * at as f64 / f64::from(rate);
        let paired = |by: fn(f64) -> f64| {
            heard
                .iter()
                .enumerate()
                .map(|(at, &sample)| f64::from(sample) * by(turn(at)))
                .sum::<f64>()
                / (heard.len() as f64 / 2.0)
        };
        let (cosine, sine) = (paired(f64::cos), paired(f64::sin));

        let left: f64 = heard
            .iter()
            .enumerate()
            .map(|(at, &sample)| {
                let tone = cosine * turn(at).cos() + sine * turn(at).sin();
                (f64::from(sample) - tone).powi(2)
            })
            .sum();
        let whole = (cosine * cosine + sine * sine) / 2.0 * heard.len() as f64;

        (10.0 * (left / whole).log10()) as f32
    }

    #[test]
    fn a_clip_of_another_rate_is_heard_as_its_tone_and_nothing_over_the_noise_floor() {
        let rate = MixRate::chosen(SampleRate::new(44_100));
        let recorded = SampleRate::new(48_000);
        let heard = played(
            &SoundData::mono(48_000, tone(recorded, 10_000.0, 12_000)),
            rate,
            8_820,
        );
        let noise = noise(&heard[2_205..6_615], 10_000.0, rate.get());

        assert!(
            noise < -96.0,
            "a tone is heard with {noise} dB beside it, over the floor of a 16-bit recording"
        );
    }

    #[test]
    fn a_clip_decoded_as_it_plays_is_heard_as_the_one_decoded_at_the_start_is() {
        let rate = MixRate::chosen(SampleRate::new(48_000));
        let loaded = SoundData::loaded(Arc::new(
            crate::assets::ogg::decode(crate::assets::SWEEP).expect("the fixture decodes"),
        ));

        let whole = played(&loaded, rate, 4_000);
        let streamed = played(&loaded.clone().streamed(), rate, 4_000);

        assert_eq!(whole, streamed, "a packet at a time reads the same frames");
    }

    #[test]
    fn a_clip_of_the_mix_rate_is_heard_frame_for_frame() {
        let rate = MixRate::chosen(SampleRate::new(48_000));
        let tone = tone(rate.get(), 1_000.0, 2_000);

        let played = played(&SoundData::mono(48_000, tone.clone()), rate, 1_000);

        assert_eq!(played.as_slice(), &tone[..1_000]);
    }

    #[test]
    fn a_one_shot_plays_its_window_and_ends() {
        let clip = counted(10);
        let trimmed = Knobs {
            trim: Some((seconds(2), seconds(5))),
            ..knobs()
        };
        let mut mixer = Mixer::new(MIX);
        mixer.apply(Command::Play(voicing(&clip, &trimmed, false)));

        assert_eq!(mixed(&mut mixer, 6), heard(&[2, 3, 4, 0, 0, 0]));
        assert_eq!(mixer.sounding(), 0, "and it is gone");
    }

    #[test]
    fn a_voice_takes_its_fade_to_come_up() {
        let clip = flat(64);
        let faded = Knobs {
            fade: seconds(4),
            ..knobs()
        };
        let mut mixer = Mixer::new(MIX);
        mixer.apply(Command::Play(voicing(&clip, &faded, false)));

        assert_eq!(mixed(&mut mixer, 4), [0.125, 0.25, 0.375, 0.5]);
    }

    #[test]
    fn a_loop_splices_its_seam_frame_for_frame() {
        let clip = counted(10);
        let looped = Knobs {
            trim: Some((seconds(1), seconds(6))),
            loop_from: Some(seconds(3)),
            ..knobs()
        };
        let mut mixer = Mixer::new(MIX);
        declare(&mut mixer, vec![one(sustained(0), &clip, &looped, 1.0)]);

        assert_eq!(
            mixed(&mut mixer, 11),
            heard(&[1, 2, 3, 4, 5, 3, 4, 5, 3, 4, 5]),
            "the seam neither repeats a frame nor drops one"
        );
    }

    #[test]
    fn a_streamed_clip_reads_what_a_whole_decode_gives_and_wraps_the_same() {
        let clip = streamed();
        let whole = {
            let Body::Encoded(encoded) = &clip.body else {
                panic!("the fixture is streamed");
            };
            crate::assets::ogg::samples(Arc::clone(encoded), clip.rate).expect("it decodes")
        };
        let window = |frames: u64| Duration::from_secs_f64(frames as f64 / f64::from(clip.rate));
        let looped = Knobs {
            trim: Some((Duration::ZERO, window(1_000))),
            loop_from: Some(window(500)),
            ..knobs()
        };

        let mut mixer = Mixer::new(MixRate::chosen(clip.rate));
        declare(&mut mixer, vec![one(sustained(4), &clip, &looped, 1.0)]);
        let heard = mixed(&mut mixer, 1_500);

        let played = |window: core::ops::Range<ClipFrame>| {
            &whole[window.start.get() as usize..window.end.get() as usize]
        };
        let window = Window::of(&clip, &looped, true).expect("it plays");
        let wanted = played(window.start..window.end)
            .iter()
            .chain(played(window.wrap..window.end));
        let off = heard
            .iter()
            .zip(wanted)
            .map(|(from, to)| (from - to).abs())
            .fold(0.0f32, f32::max);
        assert_eq!(off, 0.0, "a stream plays and wraps sample for sample");
    }

    #[test]
    fn a_streamed_clip_of_another_rate_wraps_where_a_whole_one_wraps() {
        let rate = MixRate::chosen(SampleRate::new(48_000));
        let loaded = SoundData::loaded(Arc::new(
            crate::assets::ogg::decode(crate::assets::SWEEP).expect("the fixture decodes"),
        ));
        let at = |frames: u64| Duration::from_secs_f64(frames as f64 / f64::from(rate.get()));
        let looped = Knobs {
            trim: Some((Duration::ZERO, at(1_000))),
            loop_from: Some(at(500)),
            ..knobs()
        };
        let heard = |data: &SoundData| {
            let clip = Arc::new(crate::sound::resolve(data, Some(rate)));
            let mut mixer = Mixer::new(rate);
            declare(&mut mixer, vec![one(sustained(8), &clip, &looped, 1.0)]);

            mixed(&mut mixer, 1_500)
        };

        assert_eq!(
            heard(&loaded),
            heard(&loaded.clone().streamed()),
            "a seam spliced out of packets reads as one spliced out of memory"
        );
    }

    #[test]
    fn a_re_declared_pitch_plays_on_at_the_new_step() {
        let clip = counted(64);
        let faster = Knobs {
            pitch: 2.0,
            ..knobs()
        };
        let mut mixer = Mixer::new(MIX);

        declare(&mut mixer, vec![one(sustained(5), &clip, &knobs(), 1.0)]);
        assert_eq!(mixed(&mut mixer, 4), heard(&[0, 1, 2, 3]));

        declare(&mut mixer, vec![one(sustained(5), &clip, &faster, 1.0)]);
        assert_eq!(
            mixed(&mut mixer, 4),
            heard(&[4, 6, 8, 10]),
            "twice the step, from the frame it had reached"
        );
    }

    #[test]
    fn a_re_declared_fade_paces_the_stop_that_follows() {
        let clip = flat(64);
        let slower = Knobs {
            fade: seconds(4),
            ..knobs()
        };
        let mut mixer = Mixer::new(MIX);

        declare(&mut mixer, vec![one(sustained(6), &clip, &knobs(), 1.0)]);
        assert_eq!(mixed(&mut mixer, 1), [0.5], "up at once on no fade");

        declare(&mut mixer, vec![one(sustained(6), &clip, &slower, 1.0)]);
        declare(&mut mixer, Vec::new());
        assert_eq!(mixed(&mut mixer, 4), [0.375, 0.25, 0.125, 0.0]);
    }

    #[test]
    fn a_re_declared_window_leaves_the_voice_on_the_one_it_started_on() {
        let clip = counted(16);
        let first = Knobs {
            trim: Some((seconds(0), seconds(4))),
            ..knobs()
        };
        let moved = Knobs {
            trim: Some((seconds(8), seconds(12))),
            ..knobs()
        };
        let mut mixer = Mixer::new(MIX);

        declare(&mut mixer, vec![one(sustained(7), &clip, &first, 1.0)]);
        assert_eq!(mixed(&mut mixer, 4), heard(&[0, 1, 2, 3]));

        declare(&mut mixer, vec![one(sustained(7), &clip, &moved, 1.0)]);
        assert_eq!(
            mixed(&mut mixer, 4),
            heard(&[0, 1, 2, 3]),
            "around the window it started on, not the one just declared"
        );
    }

    #[test]
    fn two_instances_of_one_value_sound_at_two_places_and_stop_one_at_a_time() {
        let clip = clip(vec![0.25; 64]);
        let here = sustained(1);
        let elsewhere = Sustained {
            sound: here.sound,
            instance: 1,
        };
        let mut mixer = Mixer::new(MIX);

        declare(
            &mut mixer,
            vec![
                one(here, &clip, &knobs(), 1.0),
                one(elsewhere, &clip, &knobs(), 1.0),
            ],
        );
        assert_eq!(mixed(&mut mixer, 1), [0.5], "both are heard at once");
        assert_eq!(mixer.sounding(), 2, "on a voice each");

        declare(
            &mut mixer,
            vec![
                one(here, &clip, &knobs(), 1.0),
                one(elsewhere, &clip, &knobs(), 0.5),
            ],
        );
        assert_eq!(
            mixed(&mut mixer, 1),
            [0.375],
            "the levels of the instance they name, and of no other"
        );

        declare(&mut mixer, vec![one(here, &clip, &knobs(), 1.0)]);
        mixed(&mut mixer, 1);
        assert_eq!(mixer.sounding(), 1);
        assert_eq!(mixed(&mut mixer, 1), [0.25], "and the other sounds on");
    }

    #[test]
    fn a_sustain_declared_again_after_a_gap_starts_at_its_window_start() {
        let clip = counted(64);
        let mut mixer = Mixer::new(MIX);

        declare(&mut mixer, vec![one(sustained(3), &clip, &knobs(), 1.0)]);
        assert_eq!(mixed(&mut mixer, 4), heard(&[0, 1, 2, 3]));

        declare(&mut mixer, Vec::new());
        mixed(&mut mixer, 1);
        assert_eq!(mixer.sounding(), 0, "with no fade it goes at once");

        declare(&mut mixer, vec![one(sustained(3), &clip, &knobs(), 1.0)]);
        assert_eq!(
            mixed(&mut mixer, 2),
            heard(&[0, 1]),
            "from the top, since a value no frame declared is forgotten"
        );
    }

    #[test]
    fn a_sustain_the_rank_leaves_out_holds_no_voice_and_is_not_heard() {
        let probe = counted(64);
        let quiet = silent(64);
        let mut mixer = Mixer::new(MIX);

        let mut set = vec![one(sustained(9), &probe, &knobs(), 1.0)];
        set.extend(filling(&quiet, 0, MAX_VOICES as u32 - 1, 0.5));
        declare(&mut mixer, set);
        assert_eq!(
            mixed(&mut mixer, 4),
            heard(&[0, 1, 2, 3]),
            "heard while the rank voices it"
        );

        let mut set = vec![one(sustained(9), &probe, &knobs(), 0.25)];
        set.extend(filling(&quiet, 0, MAX_VOICES as u32, 0.5));
        declare(&mut mixer, set);
        assert_eq!(
            mixed(&mut mixer, 4),
            heard(&[0, 0, 0, 0]),
            "and silent once a louder one takes the last voice"
        );
        assert_eq!(mixer.sounding(), MAX_VOICES, "which the cap still bounds");
    }

    #[test]
    fn a_sustain_voiced_again_enters_where_it_would_have_played_to() {
        let probe = counted(64);
        let quiet = silent(64);
        let mut mixer = Mixer::new(MIX);

        let mut set = vec![one(sustained(9), &probe, &knobs(), 1.0)];
        set.extend(filling(&quiet, 0, MAX_VOICES as u32 - 1, 0.5));
        declare(&mut mixer, set);
        mixed(&mut mixer, 4);

        let mut set = vec![one(sustained(9), &probe, &knobs(), 0.25)];
        set.extend(filling(&quiet, 0, MAX_VOICES as u32, 0.5));
        declare(&mut mixer, set);
        mixed(&mut mixer, 4);

        let mut set = vec![one(sustained(9), &probe, &knobs(), 1.0)];
        set.extend(filling(&quiet, 0, MAX_VOICES as u32, 0.5));
        declare(&mut mixer, set);
        assert_eq!(
            mixed(&mut mixer, 2),
            heard(&[8, 9]),
            "four frames voiced and four virtual, so it enters at the eighth"
        );
    }

    #[test]
    fn a_one_shot_the_rank_leaves_out_never_starts() {
        let clip = counted(64);
        let quiet = silent(64);
        let mut mixer = Mixer::new(MIX);
        declare(&mut mixer, filling(&quiet, 0, MAX_VOICES as u32, 0.5));
        mixed(&mut mixer, 1);

        mixer.apply(Command::Play(leveled(&clip, &knobs(), false, 0.25)));

        assert_eq!(mixed(&mut mixer, 2), heard(&[0, 0]), "nothing of it plays");
        assert_eq!(mixer.sounding(), MAX_VOICES, "and it holds no voice");
    }

    #[test]
    fn a_one_shot_louder_than_what_is_sounding_takes_a_voice_off_it() {
        let clip = counted(64);
        let quiet = silent(64);
        let mut mixer = Mixer::new(MIX);
        declare(&mut mixer, filling(&quiet, 0, MAX_VOICES as u32, 0.25));
        mixed(&mut mixer, 1);

        mixer.apply(Command::Play(leveled(&clip, &knobs(), false, 1.0)));

        assert_eq!(mixed(&mut mixer, 2), heard(&[0, 1]), "it is heard at once");
        assert_eq!(mixer.sounding(), MAX_VOICES, "inside the cap all the same");
    }

    #[test]
    fn a_playing_one_shot_the_rank_drops_fades_over_its_glide() {
        let clip = flat(64);
        let gliding = Knobs {
            glide: seconds(4),
            ..knobs()
        };
        let mut mixer = Mixer::new(MIX);
        mixer.apply(Command::Play(leveled(&clip, &gliding, false, 1.0)));
        assert_eq!(mixed(&mut mixer, 1), [0.5], "up at once on no fade");

        declare(&mut mixer, filling(&silent(64), 0, MAX_VOICES as u32, 1.0));
        assert_eq!(
            mixed(&mut mixer, 4),
            [0.375, 0.25, 0.125, 0.0],
            "down over the glide it named"
        );
        assert_eq!(mixer.sounding(), MAX_VOICES, "and its voice is free");
    }

    #[test]
    fn a_one_shot_the_rank_voices_again_rises_back_over_its_glide_and_plays_out() {
        let clip = flat(64);
        let gliding = Knobs {
            glide: seconds(4),
            ..knobs()
        };
        let quiet = silent(64);
        let mut mixer = Mixer::new(MIX);
        mixer.apply(Command::Play(leveled(&clip, &gliding, false, 1.0)));
        assert_eq!(mixed(&mut mixer, 1), [0.5], "up at once on no fade");

        declare(&mut mixer, filling(&quiet, 0, MAX_VOICES as u32, 2.0));
        assert_eq!(mixed(&mut mixer, 2), [0.375, 0.25], "the rank cuts it");

        declare(&mut mixer, filling(&quiet, 0, MAX_VOICES as u32, 0.25));
        assert_eq!(
            mixed(&mut mixer, 2),
            [0.375, 0.5],
            "back up over the same glide, since the rank voices it again"
        );
        assert_eq!(mixer.sounding(), MAX_VOICES, "and it plays on");
    }

    #[test]
    fn a_sustain_at_no_gain_holds_no_voice() {
        let clip = counted(64);
        let mut mixer = Mixer::new(MIX);

        declare(&mut mixer, vec![one(sustained(2), &clip, &knobs(), 0.0)]);

        assert_eq!(mixed(&mut mixer, 4), heard(&[0, 0, 0, 0]));
        assert_eq!(mixer.sounding(), 0, "however few are sounding");
    }

    #[test]
    fn a_gain_a_frame_changes_slides_over_the_glide_it_named() {
        let clip = flat(64);
        let gliding = Knobs {
            glide: seconds(4),
            ..knobs()
        };
        let mut mixer = Mixer::new(MIX);

        declare(&mut mixer, vec![one(sustained(4), &clip, &gliding, 1.0)]);
        assert_eq!(mixed(&mut mixer, 1), [0.5]);

        declare(&mut mixer, vec![one(sustained(4), &clip, &gliding, 0.5)]);
        assert_eq!(
            mixed(&mut mixer, 4),
            [0.4375, 0.375, 0.3125, 0.25],
            "a quarter of the way down each frame, and no step"
        );
    }

    #[test]
    fn two_sustains_swapping_their_gains_crossfade_over_the_glide() {
        let clip = flat(64);
        let gliding = Knobs {
            glide: seconds(4),
            ..knobs()
        };
        let here = sustained(1);
        let there = Sustained {
            sound: here.sound,
            instance: 1,
        };
        let mut mixer = Mixer::new(MIX);
        let swap = |mixer: &mut Mixer, over: f32| {
            declare(
                mixer,
                vec![
                    one(here, &clip, &gliding, 1.0 - over),
                    one(there, &clip, &gliding, over),
                ],
            );
        };

        swap(&mut mixer, 0.0);
        assert_eq!(mixed(&mut mixer, 1), [0.5], "one of them carries it all");
        assert_eq!(mixer.sounding(), 1, "and the one at no gain holds no voice");

        swap(&mut mixer, 1.0);
        assert_eq!(
            mixed(&mut mixer, 4),
            [0.5; 4],
            "the two together hold the mix steady while they swap"
        );
        assert_eq!(mixer.sounding(), 2, "both voiced while they slide");
        assert_eq!(mixed(&mut mixer, 1), [0.5], "and the one left plays on");
        assert_eq!(mixer.sounding(), 1, "with the faded one virtual again");
    }

    #[test]
    fn the_master_volume_slides_to_what_a_frame_sets() {
        let clip = steady();
        let mut mixer = Mixer::new(MASTER);

        declare(&mut mixer, vec![one(sustained(0), &clip, &knobs(), 1.0)]);
        assert_eq!(mixed(&mut mixer, 1), [0.5]);

        mixer.apply(Command::Volume(0.0));
        assert_eq!(
            mixed(&mut mixer, 4),
            [0.375, 0.25, 0.125, 0.0],
            "down over the glide, never a step"
        );
    }

    #[test]
    fn the_master_volume_declared_every_frame_slides_over_one_glide() {
        let clip = steady();
        let mut mixer = Mixer::new(MASTER);

        declare(&mut mixer, vec![one(sustained(0), &clip, &knobs(), 1.0)]);
        assert_eq!(mixed(&mut mixer, 1), [0.5]);

        let heard: Vec<f32> = (0..4)
            .map(|_| {
                mixer.apply(Command::Volume(0.0));
                mixed(&mut mixer, 1)[0]
            })
            .collect();

        assert_eq!(
            heard,
            [0.375, 0.25, 0.125, 0.0],
            "a frame loop that states the volume every frame slides over one glide, not one a frame"
        );
    }

    #[test]
    fn a_gain_declared_every_frame_reaches_its_target_at_the_end_of_one_glide() {
        let clip = flat(64);
        let gliding = Knobs {
            glide: seconds(4),
            ..knobs()
        };
        let mut mixer = Mixer::new(MIX);

        declare(&mut mixer, vec![one(sustained(4), &clip, &gliding, 1.0)]);
        assert_eq!(mixed(&mut mixer, 1), [0.5]);

        let heard: Vec<f32> = (0..4)
            .map(|_| {
                declare(&mut mixer, vec![one(sustained(4), &clip, &gliding, 0.5)]);
                mixed(&mut mixer, 1)[0]
            })
            .collect();

        assert_eq!(
            heard,
            [0.4375, 0.375, 0.3125, 0.25],
            "a frame loop that declares one gain every frame slides over one glide, not one a frame"
        );
    }

    #[test]
    fn a_sustain_the_rank_cuts_is_heard_fading_over_its_glide_and_plays_on_through_the_fade() {
        let probe = counted(64);
        let quiet = silent(64);
        let gliding = Knobs {
            glide: seconds(4),
            ..knobs()
        };
        let declaring = |mixer: &mut Mixer, fillers: u32, level: f32| {
            let mut set = vec![(sustained(9), leveled(&probe, &gliding, true, 1.0))];
            set.extend(filling(&quiet, 0, fillers, level));
            declare(mixer, set);
        };

        let mut mixer = Mixer::new(MIX);
        declaring(&mut mixer, MAX_VOICES as u32 - 1, 0.5);
        assert_eq!(mixed(&mut mixer, 4), heard(&[0, 1, 2, 3]));

        declaring(&mut mixer, MAX_VOICES as u32, 2.0);
        assert_eq!(
            mixed(&mut mixer, 4),
            [3.0 / QUIET, 2.5 / QUIET, 1.5 / QUIET, 0.0],
            "the frames it plays on through, at a level falling over the glide"
        );
        assert_eq!(mixer.sounding(), MAX_VOICES, "and then its slot is free");

        declaring(&mut mixer, MAX_VOICES as u32, 0.5);
        assert_eq!(
            mixed(&mut mixer, 2),
            heard(&[8, 9]),
            "voiced again where the fade played it to"
        );
    }
}