mirage-engine 0.2.0

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
use std::collections::{HashMap, VecDeque};
use std::sync::Arc;

use js_sys::Float32Array;
use wasm_bindgen::JsCast;
use wasm_bindgen::closure::Closure;
use web_sys::{
    AudioBuffer, AudioBufferSourceNode, AudioContext, AudioContextState, AudioScheduledSourceNode,
    GainNode, StereoPannerNode, WaveShaperNode,
};

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

/// Seconds of a streamed clip one frame decodes and schedules, which
/// spreads the work over the frames before it is heard.
const CHUNK: f64 = 0.25;

/// Points of the limiter's curve the page is passed; enough that what
/// it plays between them is inaudibly close to the curve.
const LIMITER_POINTS: usize = 1 << 10;

/// The page's audio graph: the browser mixes, and the engine sets what
/// to mix.
pub(crate) struct Backend {
    context: AudioContext,
    master: GainNode,
    sustained: Sustains<Sustain>,
    /// One-shots with nodes of their own, 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>,
    buffers: Buffers,
    /// The master gain the page is playing at, which it slides to only where
    /// a frame states another.
    volume: f32,
    unlocked: bool,
    /// Kept alive so that the page keeps calling it.
    _hidden: Closure<dyn FnMut()>,
}

impl Backend {
    /// The page's graph takes a clip at the clip's own rate and resamples
    /// for itself.
    pub(crate) fn rate(&self) -> Option<MixRate> {
        None
    }

    pub(crate) fn frame(&mut self, commands: impl Iterator<Item = Command>) {
        let now = self.context.current_time();
        for command in commands {
            self.apply(command, now);
        }

        self.allocate(now);
        for sustain in self.sustained.iter_mut() {
            sustain.top_up(now);
        }
        for shot in self.shots.iter_mut().filter_map(Playing::voice_mut) {
            shot.top_up(now);
        }

        self.shots.retain(|shot| !shot.spent(now));
        self.sustained.settle(now);
    }

    /// The page plays only once the player has done something.
    pub(crate) fn unlocked(&self) -> bool {
        self.unlocked
    }

    pub(crate) fn unlock(&mut self) {
        if !self.unlocked {
            let _ = self.context.resume();
            self.unlocked = true;
        }
    }

    fn apply(&mut self, command: Command, now: f64) {
        match command {
            Command::Play(voicing) => match self.unlocked {
                true => self.starting.push(voicing),
                false => log::debug!("a sound played before the page could; ignoring it"),
            },
            Command::Sustained(declared) => self.sustained.declare(declared, now),
            Command::Volume(volume) => self.set_volume(volume.max(0.0), now),
        }
    }

    /// Slides the whole mix to `volume` over [`GLIDE`]; a volume it is
    /// already playing at keeps the course it is on.
    fn set_volume(&mut self, volume: f32, now: f64) {
        if volume == self.volume {
            return;
        }

        self.volume = volume;
        let gain = self.master.gain();
        let _ = gain.set_value_at_time(gain.value(), now);
        let _ = gain.linear_ramp_to_value_at_time(volume, now + GLIDE.as_secs_f64());
    }

    /// Ranks everything the page holds, so that the loudest of them take the
    /// nodes, and starts the one-shots the rank kept.
    fn allocate(&mut self, now: f64) {
        let mut graph = Graph {
            context: &self.context,
            master: &self.master,
            buffers: &mut self.buffers,
        };
        self.sustained
            .allocate(&mut self.shots, &mut self.starting, &mut graph, now);

        for voicing in self.starting.drain(..) {
            let levels = Sliding::held(voicing.live.levels);
            if let Some(voice) = Voice::start(&mut graph, voicing, ClipFrame::ZERO, levels, now) {
                self.shots.push(Playing::Voiced(voice));
            }
        }
    }
}

/// What the page takes a voice out of: its graph, and the buffers it holds.
struct Graph<'a> {
    context: &'a AudioContext,
    master: &'a GainNode,
    buffers: &'a mut Buffers,
}

/// One sustained value the game wants sounding, with the nodes 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 holds no
    /// nodes; nodes it holds keep the slide while they play.
    levels: Sliding,
    /// Frames of playback it had taken when it last held no voice, and the
    /// time on the page's clock it reached them at.
    taken: f64,
    since: f64,
    playing: Playing<Voice>,
}

impl Sustaining for Sustain {
    type Pace = f64;
    type Voices<'a> = Graph<'a>;

    fn started(sustained: Sustained, voicing: Voicing, now: f64) -> Self {
        Self {
            sustained,
            clip: voicing.clip,
            window: voicing.window,
            levels: Sliding::held(voicing.live.levels),
            live: voicing.live,
            taken: 0.0,
            since: now,
            playing: Playing::Virtual,
        }
    }

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

    fn declare(&mut self, voicing: Voicing, now: f64) {
        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, now),
            None => {
                self.levels
                    .aim(self.live.levels, self.live.glide.as_secs_f64(), now);
            }
        }
        self.playing.declared(now);
    }

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

    fn voiced(&mut self, wins: bool, graph: &mut Graph<'_>, now: f64) {
        let at = ClipFrame::new(self.played(now) as u64);
        let started = || {
            let voicing = Voicing {
                sound: self.sustained.sound,
                clip: Arc::clone(&self.clip),
                window: self.window,
                live: self.live,
            };

            Voice::start(graph, voicing, at, self.levels, now)
        };

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

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

    fn settle(&mut self, now: f64) -> bool {
        match self.playing.landed(now) {
            Some((voice, Fade::Cut)) => {
                self.taken = voice.played(now);
                self.since = now;
                self.levels = voice.levels;
                true
            }
            Some((_, Fade::Stop)) => false,
            None => true,
        }
    }
}

impl Sustain {
    /// Frames of playback it has taken, which advance whether it holds nodes
    /// or not.
    fn played(&self, now: f64) -> f64 {
        match self.playing.voice() {
            Some(voice) => voice.played(now),
            None => {
                let rate = f64::from(self.clip.rate) * f64::from(self.live.pitch);
                self.taken + (now - self.since) * rate
            }
        }
    }

    fn top_up(&mut self, now: f64) {
        if let Some(voice) = self.playing.voice_mut() {
            voice.top_up(now);
        }
    }
}

/// The level a sound is heard at in each ear, read off the page's clock, so
/// that it goes on sliding while the value it belongs to holds no nodes.
#[derive(Clone, Copy)]
struct Sliding {
    from: Levels,
    to: Levels,
    /// When the slide started on the page's clock, and how long it takes.
    since: f64,
    span: f64,
}

impl Sliding {
    /// Levels that stay where they are until a frame sets a target.
    fn held(levels: Levels) -> Self {
        Self {
            from: levels,
            to: levels,
            since: 0.0,
            span: 0.0,
        }
    }

    /// Slides to `levels` over `span` seconds, from where it stands at `now`,
    /// and returns whether that changed where it slides to.
    ///
    /// Levels it is already sliding to keep the course it is on, so a frame
    /// loop that declares one gain every frame slides over one span.
    fn aim(&mut self, levels: Levels, span: f64, now: f64) -> bool {
        if levels == self.to {
            return false;
        }

        self.from = self.at(now);
        self.to = levels;
        self.since = now;
        self.span = span;

        true
    }

    /// The level it has reached at `now`.
    fn at(&self, now: f64) -> Levels {
        let over = match self.span > 0.0 {
            true => (((now - self.since) / self.span).clamp(0.0, 1.0)) as f32,
            false => 1.0,
        };

        Levels {
            left: self.from.left + (self.to.left - self.from.left) * over,
            right: self.from.right + (self.to.right - self.from.right) * over,
        }
    }

    /// When the slide is over on the page's clock.
    fn until(&self) -> f64 {
        self.since + self.span
    }

    /// The louder of where it stands and where it slides to, which is what
    /// the rank reads.
    fn loudest(&self, now: f64) -> f32 {
        self.at(now).loudest().max(self.to.loudest())
    }
}

/// Clips the page holds, one buffer per sound, passed over the first time
/// each is played.
#[derive(Default)]
struct Buffers(HashMap<SoundId, AudioBuffer>);

impl Buffers {
    /// The buffer for `sound`, or nothing where the clip is decoded as it
    /// plays.
    fn of(&mut self, context: &AudioContext, sound: SoundId, clip: &Clip) -> Option<AudioBuffer> {
        if let Some(held) = self.0.get(&sound) {
            return Some(held.clone());
        }
        let Body::Samples(samples) = &clip.body else {
            return None;
        };

        let buffer = upload(context, samples, clip)?;
        self.0.insert(sound, buffer.clone());
        Some(buffer)
    }
}

/// A fade a voice is on: when it lands on the page's clock, and the span it
/// covers.
#[derive(Clone, Copy)]
struct Release {
    lands: f64,
    span: f64,
}

impl Release {
    /// What is left of the fade at `now`, one where it has not started and
    /// nothing where it has landed.
    fn left(self, now: f64) -> f32 {
        match self.span > 0.0 {
            true => (((self.lands - now) / self.span) as f32).clamp(0.0, 1.0),
            false => 0.0,
        }
    }
}

/// One sound the browser is playing.
struct Voice {
    context: AudioContext,
    clip: Arc<Clip>,
    window: Window,
    gain: GainNode,
    pan: StereoPannerNode,
    /// Each buffer passed to the page, and when it stops playing.
    scheduled: Vec<(AudioBufferSourceNode, f64)>,
    chain: Option<Chain>,
    /// The level it is heard at, sliding to the one the last declaration set.
    levels: Sliding,
    pitch: f32,
    /// Seconds its start and its stop fade over.
    fade: f64,
    /// Seconds a change of levels slides over, and the span the rank cutting
    /// it fades it over.
    glide: f64,
    /// Frames of playback the voice had taken when it last changed
    /// pitch.
    taken: f64,
    /// Time on the page's clock, in seconds, when the voice took that
    /// pitch.
    since: f64,
    /// Time on the page's clock, in seconds, when the clip it plays runs
    /// out, once that is known.
    ends_at: Option<f64>,
    /// The fade it is on, which the rank cutting it or no set declaring it
    /// starts; a clip that plays out never sets it.
    releasing: Option<Release>,
}

impl Voice {
    /// A voice playing `voicing` from clip frame `at`, out of the buffer the
    /// page holds or a chain it decodes; nothing where the page refused a
    /// node.
    fn start(
        graph: &mut Graph<'_>,
        voicing: Voicing,
        at: ClipFrame,
        levels: Sliding,
        now: f64,
    ) -> Option<Self> {
        let held = graph
            .buffers
            .of(graph.context, voicing.sound, &voicing.clip);
        let mut voice = Self::new(graph, voicing, at, levels, now)?;
        match (held, &voice.clip.body) {
            (Some(buffer), _) => voice.play_buffer(&buffer, now),
            (None, Body::Encoded(encoded)) => {
                let encoded = Arc::clone(encoded);
                voice.open_chain(encoded, now);
            }
            (None, Body::Samples(_)) => return None,
        }

        Some(voice)
    }

    fn new(
        graph: &Graph<'_>,
        voicing: Voicing,
        played: ClipFrame,
        levels: Sliding,
        now: f64,
    ) -> Option<Self> {
        let gain = graph.context.create_gain().ok()?;
        let pan = graph.context.create_stereo_panner().ok()?;
        gain.connect_with_audio_node(&pan).ok()?;
        pan.connect_with_audio_node(graph.master).ok()?;

        let mut voice = Self {
            context: graph.context.clone(),
            clip: voicing.clip,
            window: voicing.window,
            gain,
            pan,
            scheduled: Vec::new(),
            chain: None,
            levels,
            pitch: voicing.live.pitch,
            fade: voicing.live.fade.as_secs_f64(),
            glide: voicing.live.glide.as_secs_f64(),
            taken: played.get() as f64,
            since: now,
            ends_at: None,
            releasing: None,
        };
        let (level, panned) = split(&levels.at(now));
        voice.pan.pan().set_value(panned);
        voice.gain.gain().set_value_at_time(0.0, now).ok()?;
        voice
            .gain
            .gain()
            .linear_ramp_to_value_at_time(level, now + voice.fade)
            .ok()?;
        voice.aim(now);

        Some(voice)
    }

    /// Takes the knobs a frame set: the levels, the pitch the voice
    /// plays at from now on, and the spans its fades take.
    fn retarget(&mut self, live: &LiveKnobs, now: f64) {
        self.fade = live.fade.as_secs_f64();
        self.glide = live.glide.as_secs_f64();
        if self.levels.aim(live.levels, self.glide, now) && self.releasing.is_none() {
            self.aim(now);
        }
        self.repitch(live.pitch, now);
    }

    /// Plays on at `pitch` from the frame the voice is at: a clip
    /// the page holds changes playback rate in place, and a streamed
    /// voice is cut off where [`Scheduled::cut`] puts it and scheduled
    /// again from there.
    fn repitch(&mut self, pitch: f32, now: f64) {
        if pitch == self.pitch {
            return;
        }

        match self.recut(now) {
            Some(cut) => {
                self.taken = cut.produced.get() as f64;
                self.since = cut.at;
            }
            None => {
                self.taken = self.played(now);
                self.since = now;
                for (source, _) in &self.scheduled {
                    source.playback_rate().set_value(pitch);
                }
            }
        }
        self.pitch = pitch;
    }

    /// Stops a streamed voice's buffers at the cut and moves its chain
    /// back to that point, so the frames after the cut are decoded and
    /// scheduled again; nothing where the page holds the whole clip.
    fn recut(&mut self, now: f64) -> Option<Cut> {
        let ends: Vec<f64> = self.scheduled.iter().map(|(_, until)| *until).collect();
        let rate = f64::from(self.clip.rate) * f64::from(self.pitch);
        let chain = self.chain.as_mut()?;
        let cut = Scheduled {
            ends: &ends,
            until: chain.next_at,
            produced: chain.produced,
            rate,
        }
        .cut(now);

        chain.next_at = cut.at;
        chain.produced = cut.produced;
        chain.decoded.clear();
        for (source, until) in &mut self.scheduled {
            let scheduled: &AudioScheduledSourceNode = source;
            let _ = scheduled.stop_with_when(cut.at);
            *until = until.min(cut.at);
        }

        Some(cut)
    }

    /// Slides the gain and pan to where the levels are heading, which they
    /// reach when the slide is over.
    fn aim(&mut self, now: f64) {
        let (level, panned) = split(&self.levels.to);
        let until = self.levels.until().max(now + self.fade);
        let _ = self.gain.gain().linear_ramp_to_value_at_time(level, until);
        let _ = self.pan.pan().linear_ramp_to_value_at_time(panned, until);
    }

    /// Fades the voice to nothing over `span`; a fade it is already on that
    /// lands earlier keeps the course it is on.
    fn release(&mut self, span: f64, now: f64) {
        let lands = now + span;
        if self.releasing.is_some_and(|release| release.lands <= lands) {
            return;
        }

        self.releasing = Some(Release { lands, span });
        let gain = self.gain.gain();
        let _ = gain.cancel_scheduled_values(now);
        let _ = gain.set_value_at_time(gain.value(), now);
        let _ = gain.linear_ramp_to_value_at_time(0.0, lands);
    }

    /// Takes the voice off the fade it is on and slides it back over `span`
    /// to the level it is heard at.
    fn revive(&mut self, span: f64, now: f64) {
        self.releasing = None;
        let (level, panned) = split(&self.levels.to);
        let gain = self.gain.gain();
        let _ = gain.cancel_scheduled_values(now);
        let _ = gain.set_value_at_time(gain.value(), now);
        let _ = gain.linear_ramp_to_value_at_time(level, now + span);
        let _ = self
            .pan
            .pan()
            .linear_ramp_to_value_at_time(panned, now + span);
    }

    /// Frames of playback the voice has taken.
    fn played(&self, now: f64) -> f64 {
        let rate = f64::from(self.clip.rate) * f64::from(self.pitch);
        self.taken + (now - self.since) * rate
    }

    /// Plays a clip the page already holds, looping it where it is kept
    /// alive.
    fn play_buffer(&mut self, buffer: &AudioBuffer, now: f64) {
        let Some(source) = self.source() else {
            return;
        };
        source.set_buffer(Some(buffer));

        let rate = f64::from(self.clip.rate);
        let at = self
            .window
            .at(ClipFrame::new(self.taken as u64))
            .unwrap_or(self.window.start);
        let until = match self.window.looping {
            true => {
                source.set_loop(true);
                source.set_loop_start(self.window.wrap.get() as f64 / rate);
                source.set_loop_end(self.window.end.get() as f64 / rate);
                f64::INFINITY
            }
            false => {
                let left = (self.window.end - at).get() as f64 / rate / f64::from(self.pitch);
                self.ends_at = Some(now + left);
                now + left
            }
        };

        let _ = source.start_with_when_and_grain_offset(now, at.get() as f64 / rate);
        self.scheduled.push((source, until));
    }

    /// Starts decoding a streamed clip; the frames that follow schedule
    /// it, a chunk at a time.
    fn open_chain(&mut self, encoded: Arc<Encoded>, now: f64) {
        self.chain = Some(Chain {
            stream: Stream::open(encoded, self.clip.rate)
                .inspect_err(|error| log::debug!("{error}"))
                .map(Box::new)
                .ok(),
            produced: ClipFrame::new(self.taken as u64),
            next_at: now,
            decoded: VecDeque::new(),
        });
    }

    /// Schedules more of a streamed clip, so that what is scheduled
    /// always extends past what is heard.
    fn top_up(&mut self, now: f64) {
        self.scheduled.retain(|(_, until)| *until > now);

        let channels = self.clip.channels.count();
        let rate = f64::from(self.clip.rate);
        let pitch = f64::from(self.pitch);
        let window = self.window;
        let Some(chain) = &mut self.chain else {
            return;
        };
        if chain.next_at > now + STREAM_AHEAD.as_secs_f64() {
            return;
        }

        let Some(spliced) = chain.decode(&window, channels, (CHUNK * rate) as usize) else {
            let spent = chain.next_at;
            self.ends_at = Some(spent);
            return;
        };
        let at = chain.next_at.max(now);
        let until = at + (spliced.len() / channels) as f64 / rate / pitch;
        chain.next_at = until;

        let Some(buffer) = upload(&self.context, &spliced, &self.clip) else {
            return;
        };
        let Some(source) = self.source() else {
            return;
        };
        source.set_buffer(Some(&buffer));
        let _ = source.start_with_when(at);
        self.scheduled.push((source, until));
    }

    /// A buffer player of this voice's own, at its own pitch.
    fn source(&self) -> Option<AudioBufferSourceNode> {
        let source = self.context.create_buffer_source().ok()?;
        source.playback_rate().set_value(self.pitch);
        source.connect_with_audio_node(&self.gain).ok()?;

        Some(source)
    }
}

impl Audible for Voice {
    type Pace = f64;

    /// One on a fade counts by how much of that fade is left.
    fn audibility(&self, now: f64) -> f32 {
        self.levels.loudest(now) * self.releasing.map_or(1.0, |release| release.left(now))
    }

    fn stop(&mut self, now: f64) {
        self.release(self.fade, now);
    }

    fn rise(&mut self, now: f64) {
        self.revive(self.fade, now);
    }

    fn cut(&mut self, now: f64) {
        self.release(self.glide, now);
    }

    fn recover(&mut self, now: f64) {
        self.revive(self.glide, now);
    }

    fn spent(&self, now: f64) -> bool {
        let landed = |at: f64| at <= now;

        self.releasing.is_some_and(|release| landed(release.lands))
            || self.ends_at.is_some_and(landed)
    }
}

impl Drop for Voice {
    /// Stops what the page has scheduled and takes the voice out of the
    /// graph.
    fn drop(&mut self) {
        for (source, _) in &self.scheduled {
            let scheduled: &AudioScheduledSourceNode = source;
            let _ = scheduled.stop();
        }
        let _ = self.gain.disconnect();
        let _ = self.pan.disconnect();
    }
}

/// A streamed clip as a run of buffers, each scheduled to start where
/// the one before it ends.
struct Chain {
    /// 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>>,
    produced: ClipFrame,
    next_at: f64,
    decoded: VecDeque<f32>,
}

impl Chain {
    /// The next `frames` of the clip in playback order, or nothing once
    /// it is spent.
    fn decode(&mut self, window: &Window, channels: usize, frames: usize) -> Option<Vec<f32>> {
        let mut stream = self.stream.take()?;
        while self.decoded.len() / channels < frames {
            let Some(at) = window.at(self.produced) else {
                break;
            };
            if stream.position() != at
                && let Err(error) = stream.seek(at)
            {
                log::debug!("{error}");
                break;
            }

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

        let taken: Vec<f32> = self.decoded.drain(..).collect();
        self.stream = Some(stream);
        (!taken.is_empty()).then_some(taken)
    }
}

pub(crate) fn open() -> Option<Backend> {
    let context = AudioContext::new()
        .inspect_err(|_| log::debug!("this browser has no audio; playing nothing"))
        .ok()?;
    let master = context.create_gain().ok()?;
    let limiter = limiter(&context)?;
    master.connect_with_audio_node(&limiter).ok()?;
    limiter
        .connect_with_audio_node(&context.destination())
        .ok()?;

    Some(Backend {
        _hidden: watch_visibility(&context),
        unlocked: matches!(context.state(), AudioContextState::Running),
        context,
        master,
        sustained: Sustains::default(),
        shots: Vec::new(),
        starting: Vec::new(),
        buffers: Buffers::default(),
        volume: 1.0,
    })
}

/// The master limiter, as a curve the page plays the whole mix through.
fn limiter(context: &AudioContext) -> Option<WaveShaperNode> {
    let curve: Vec<f32> = (0..LIMITER_POINTS)
        .map(|at| limit(at as f32 / (LIMITER_POINTS - 1) as f32 * 2.0 - 1.0))
        .collect();
    let shaper = context.create_wave_shaper().ok()?;
    shaper.set_curve_opt_f32_array(Some(&copied(&curve)));

    Some(shaper)
}

/// A copy of `samples` in a buffer outside the shared memory, because the
/// audio graph takes no view over shared memory.
fn copied(samples: &[f32]) -> Float32Array {
    let buffer = Float32Array::new_with_length(samples.len() as u32);
    buffer.copy_from(samples);
    buffer
}

/// Stops the sound while the page is hidden, which is also when frames
/// stop and with them every sustain.
fn watch_visibility(context: &AudioContext) -> Closure<dyn FnMut()> {
    let watched = context.clone();
    let hidden = Closure::<dyn FnMut()>::new(move || {
        let Some(document) = web_sys::window().and_then(|window| window.document()) else {
            return;
        };
        let _ = match document.hidden() {
            true => watched.suspend(),
            false => watched.resume(),
        };
    });

    if let Some(document) = web_sys::window().and_then(|window| window.document()) {
        document.set_onvisibilitychange(Some(hidden.as_ref().unchecked_ref()));
    }
    hidden
}

/// Passes interleaved samples to the browser as a buffer it can play.
fn upload(context: &AudioContext, samples: &[f32], clip: &Clip) -> Option<AudioBuffer> {
    let channels = clip.channels.count();
    let frames = samples.len() / channels;
    let buffer = context
        .create_buffer(channels as u32, frames as u32, f32::from(clip.rate))
        .ok()?;

    let mut channel = Vec::with_capacity(frames);
    for at in 0..channels {
        channel.clear();
        channel.extend(samples.iter().skip(at).step_by(channels));
        buffer
            .copy_to_channel_with_f32_array(&copied(&channel), at as i32)
            .ok()?;
    }

    Some(buffer)
}