kui-core 0.1.0-alpha.45

kui contract: flat per-frame tree, clay-style flex layout, text stack, events as data, quad display list
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
//! Audio as data: sounds are session resources, and playing one is a
//! command the frame driver drains and applies to the device.
//!
//! Register a sound's bytes with `Core::add_sound` (a [`SoundId`]), then
//! play it one of three ways: `NodeSpec::click_sound` / `hover_sound` on a
//! node; `Ui::audio` with an [`AudioSpec`], a playback that runs for as
//! long as the view declares the node; or `Core::play` / `Ui::play` with
//! [`PlayOptions`], plus `stop`, `set_volume`, `pause`, `resume` and
//! `set_master_volume` for a host that holds the core. The windowed runner
//! drains the resulting [`AudioCommand`]s; a host driving its own loop
//! drains `Core::take_audio_commands`. The core never touches a device, so
//! a headless test asserts on the queue.
//!
//! ```rust
//! use kui_core::{AudioCommand, AudioSpec, Core, NodeSpec, PlayOptions, Size};
//!
//! let mut core = Core::new();
//! let chime = core.add_sound(b"RIFF....WAVE".to_vec()); // the file's bytes
//!
//! // Imperative: start it now at half volume and ask for an `ended` event.
//! let playback = core.play(chime, PlayOptions::default().volume(0.5).tag("chime"));
//!
//! // Declarative, in a view: a click sound, and a loop that plays while declared.
//! let mut ui = core.frame(Size::new(400.0, 300.0), 1.0);
//! ui.leaf_keyed("go", NodeSpec::row().size(80.0, 24.0).on_click("go").click_sound(chime));
//! ui.audio_keyed("music", AudioSpec::new(chime).looped().volume(0.3));
//! ui.finish();
//!
//! // What a driver does with the queue.
//! for cmd in core.take_audio_commands() {
//!     match cmd {
//!         AudioCommand::Play { playback, sound, looped, .. } => {
//!             println!("play {sound:?} as {playback:?} (loop: {looped})");
//!         }
//!         AudioCommand::Stop { playback, .. } => println!("stop {playback:?}"),
//!         other => println!("{}", other.kind_name()),
//!     }
//! }
//! core.stop(playback, 0.0);
//! ```
//!
//! A playback started with a tag comes back as
//! `{kind:"sound", phase:"ended", playback, tag}` on the origin that
//! started it once the driver reports it finished (`Core::audio_ended`),
//! not when something stopped it. A play the device refused comes back as
//! `phase:"refused"` (`Core::audio_refused`), so nothing waits on an
//! `ended` that cannot come. A stop that cut a one-shot off mid-sound is
//! reported as the [`crate::diag::TRUNCATED_PLAYBACK`] warning
//! (`Core::audio_truncated`); [`AudioSpec::finish`] is the usual answer.

use rustc_hash::FxHashMap;

use crate::input::UiEvent;
use crate::key::Key;
use crate::resources::SoundId;
use crate::tree::OriginId;
use crate::value::Value;
use crate::window::WindowId;

/// One playback instance. Allocated by the core when the play command is
/// queued, so callers get it synchronously without a driver round trip;
/// 0 is never issued.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct PlaybackId(pub u64);

/// How to start a playback (`Core::play`).
#[derive(Clone, Debug, PartialEq)]
pub struct PlayOptions {
    /// Linear amplitude, 0..1 (1 = as recorded).
    pub volume: f32,
    pub looped: bool,
    /// Fade in from silence over this many ms (0 = none).
    pub fade_in_ms: f32,
    /// Carried back in the `ended` event; `None` = no event.
    pub tag: Option<Value>,
}

impl Default for PlayOptions {
    fn default() -> Self {
        Self {
            volume: 1.0,
            looped: false,
            fade_in_ms: 0.0,
            tag: None,
        }
    }
}

impl PlayOptions {
    pub fn volume(mut self, v: f32) -> Self {
        self.volume = v;
        self
    }

    pub fn looped(mut self) -> Self {
        self.looped = true;
        self
    }

    pub fn fade_in(mut self, ms: f32) -> Self {
        self.fade_in_ms = ms;
        self
    }

    /// Asks for an `ended` event carrying this tag.
    pub fn tag(mut self, tag: impl Into<Value>) -> Self {
        self.tag = Some(tag.into());
        self
    }
}

/// What an `audio` node declares each frame (`Core::audio_node`).
#[derive(Clone, Debug, PartialEq)]
pub struct AudioSpec {
    pub src: SoundId,
    /// Linear amplitude, 0..1; changes apply to the running playback.
    pub volume: f32,
    pub looped: bool,
    /// Holds the playback (resumes when cleared).
    pub paused: bool,
    /// What the node going away means: `false` stops the playback, `true`
    /// releases it — it finishes on its own. See [`AudioSpec::finish`].
    pub finish: bool,
    /// Carried back in the `ended` event; `None` = no event.
    pub tag: Option<Value>,
}

impl AudioSpec {
    pub fn new(src: SoundId) -> Self {
        Self {
            src,
            volume: 1.0,
            looped: false,
            paused: false,
            finish: false,
            tag: None,
        }
    }

    pub fn volume(mut self, v: f32) -> Self {
        self.volume = v;
        self
    }

    pub fn looped(mut self) -> Self {
        self.looped = true;
        self
    }

    pub fn paused(mut self, paused: bool) -> Self {
        self.paused = paused;
        self
    }

    /// The node's *removal* releases the playback instead of stopping it:
    /// it plays to its end, and a `tag` still reports `ended` when it gets
    /// there. Only removal changes — a `looped` playback still stops (it
    /// has no end to reach), and a changed `src` still restarts, since that
    /// is a replacement rather than a departure. A playback that is
    /// `paused` when its node goes has nothing to finish and the driver
    /// holds it forever, so a view that pauses should stop rather than
    /// release. Without this, a one-shot the view wants heard whole has to
    /// stay declared for the asset's length, which the view does not know.
    ///
    /// This is also what
    /// [`truncated-playback`](crate::diag::TRUNCATED_PLAYBACK) asks for: a
    /// one-shot removed mid-sound raises that warning, and the answer to
    /// it is either this flag or a node kept declared until the `ended`
    /// event. A node that means to cut the sound off says so by stopping
    /// what it started (`Core::stop`), which is not reported.
    ///
    /// A released playback is not free: it holds one of the device's 128
    /// voices until its file ends, and the 129th play is refused (reported
    /// as [`crate::diag::PLAYBACK_REFUSED`] and, for a tagged node,
    /// `{kind:"sound", phase:"refused"}`). A loop would hold a voice for
    /// ever, which is why a loop is stopped rather than released.
    pub fn finish(mut self) -> Self {
        self.finish = true;
        self
    }

    pub fn tag(mut self, tag: impl Into<Value>) -> Self {
        self.tag = Some(tag.into());
        self
    }
}

/// An audio intent for the frame driver. Durations are ms; volumes are
/// linear amplitude. Drivers ignore playbacks they no longer hold.
#[derive(Clone, Debug, PartialEq)]
pub enum AudioCommand {
    Play {
        playback: PlaybackId,
        sound: SoundId,
        volume: f32,
        looped: bool,
        fade_in_ms: f32,
    },
    Stop {
        playback: PlaybackId,
        fade_ms: f32,
    },
    SetVolume {
        playback: PlaybackId,
        volume: f32,
        tween_ms: f32,
    },
    Pause {
        playback: PlaybackId,
        fade_ms: f32,
    },
    Resume {
        playback: PlaybackId,
        fade_ms: f32,
    },
    MasterVolume {
        volume: f32,
        tween_ms: f32,
    },
    /// The sound was unregistered: drop any decoded copy.
    Unload {
        sound: SoundId,
    },
}

impl AudioCommand {
    /// The command's wire name: `play`, `stop`, `setVolume`, `pause`,
    /// `resume`, `masterVolume`, `unload`.
    pub fn kind_name(&self) -> &'static str {
        match self {
            AudioCommand::Play { .. } => "play",
            AudioCommand::Stop { .. } => "stop",
            AudioCommand::SetVolume { .. } => "setVolume",
            AudioCommand::Pause { .. } => "pause",
            AudioCommand::Resume { .. } => "resume",
            AudioCommand::MasterVolume { .. } => "masterVolume",
            AudioCommand::Unload { .. } => "unload",
        }
    }

    /// `{kind, ...}` with what the variant carries: `playback` (a small
    /// counter, an integer), `sound` (a resource id, spelled by `h`),
    /// `volume`, `loop`, and the durations in ms as `fade_in`, `fade`,
    /// `tween`.
    pub fn to_value(&self, h: crate::value::Handles) -> Value {
        let pb = |p: PlaybackId| Value::Int(p.0 as i64);
        let mut out = vec![("kind".to_string(), Value::str(self.kind_name()))];
        let mut push = |k: &str, v: Value| out.push((k.to_string(), v));
        match *self {
            AudioCommand::Play {
                playback,
                sound,
                volume,
                looped,
                fade_in_ms,
            } => {
                push("playback", pb(playback));
                push("sound", (h.id)(sound.to_ffi()));
                push("volume", Value::float(volume));
                push("loop", Value::Bool(looped));
                push("fade_in", Value::float(fade_in_ms));
            }
            AudioCommand::Stop { playback, fade_ms }
            | AudioCommand::Pause { playback, fade_ms }
            | AudioCommand::Resume { playback, fade_ms } => {
                push("playback", pb(playback));
                push("fade", Value::float(fade_ms));
            }
            AudioCommand::SetVolume {
                playback,
                volume,
                tween_ms,
            } => {
                push("playback", pb(playback));
                push("volume", Value::float(volume));
                push("tween", Value::float(tween_ms));
            }
            AudioCommand::MasterVolume { volume, tween_ms } => {
                push("volume", Value::float(volume));
                push("tween", Value::float(tween_ms));
            }
            AudioCommand::Unload { sound } => push("sound", (h.id)(sound.to_ffi())),
        }
        Value::Map(out)
    }
}

/// A playback that asked for an `ended` event.
struct Tagged {
    origin: OriginId,
    /// The window whose frame declared the node (or whose core called
    /// `play`), so the event lands there and not on whichever window's
    /// driver drained the device.
    window: WindowId,
    key: Key,
    tag: Value,
}

/// An `audio` node's retained playback.
struct Mounted {
    playback: PlaybackId,
    spec: AudioSpec,
}

/// What a mounted `audio` node is keyed by. The store is the session's
/// (one device), but a mount is one window's: it is reconciled against
/// *that window's* frame, so a second window's frame declaring no
/// `<audio>` says nothing about the first's.
type Mount = (WindowId, Key);

/// Why a one-shot playback was cut off — what
/// [`diag::TRUNCATED_PLAYBACK`](crate::diag::TRUNCATED_PLAYBACK) reports
/// once the driver confirms the sound was still running.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Why {
    /// The node declaring it went away without [`AudioSpec::finish`].
    Removed,
    /// The node changed its `src`, which replaces the playback.
    Restarted,
}

impl Why {
    /// The verb for the message ("removed at 0.5 s").
    pub(crate) fn verb(self) -> &'static str {
        match self {
            Why::Removed => "removed",
            Why::Restarted => "restarted",
        }
    }
}

/// Stops the driver has not answered for yet are remembered so a
/// truncation can name its node; a headless core has no driver to answer,
/// so the map is capped and the oldest entry — the lowest [`PlaybackId`],
/// which they are issued in — makes room for a newer one.
const MAX_STOPPED: usize = 256;

/// Playback bookkeeping on the session: the command queue, the tagged
/// playbacks awaiting their `ended` event, and the `audio` nodes' retained
/// playbacks. The queue and the ids are the session's, because the
/// process has one device; the mounts are keyed by window as well as by
/// node, because each is reconciled against one window's frame
/// (`finish_frame` hands in the window it finished, and only that
/// window's slice is diffed).
#[derive(Default)]
pub struct AudioStore {
    next: u64,
    commands: Vec<AudioCommand>,
    tagged: FxHashMap<PlaybackId, Tagged>,
    mounted: FxHashMap<Mount, Mounted>,
    /// `audio` nodes declared this frame, in tree order, each with the
    /// window whose frame declared it.
    declared: Vec<(Mount, OriginId, AudioSpec)>,
    /// One-shots `reconcile` stopped, awaiting the driver's word on
    /// whether they were still playing (`Core::audio_truncated`). The
    /// core cannot know that itself: `ended` is the driver's too, an
    /// untagged one-shot leaves no `tagged` entry to have heard it, and a
    /// headless `Ctx` has no driver at all — so nothing here is a warning
    /// until something answers for it.
    stopped: FxHashMap<PlaybackId, (Key, Why)>,
}

impl AudioStore {
    fn alloc(&mut self) -> PlaybackId {
        self.next += 1;
        PlaybackId(self.next)
    }

    /// Queues a play; `origin`/`window`/`key` say where an `ended` event
    /// lands.
    pub(crate) fn play(
        &mut self,
        origin: OriginId,
        window: WindowId,
        key: Key,
        sound: SoundId,
        opts: PlayOptions,
    ) -> PlaybackId {
        let playback = self.alloc();
        self.commands.push(AudioCommand::Play {
            playback,
            sound,
            volume: opts.volume,
            looped: opts.looped,
            fade_in_ms: opts.fade_in_ms,
        });
        if let Some(tag) = opts.tag {
            self.tagged.insert(
                playback,
                Tagged {
                    origin,
                    window,
                    key,
                    tag,
                },
            );
        }
        playback
    }

    /// Stops a playback; it will not report `ended`.
    pub(crate) fn stop(&mut self, playback: PlaybackId, fade_ms: f32) {
        self.tagged.remove(&playback);
        self.commands.push(AudioCommand::Stop { playback, fade_ms });
    }

    /// Remembers a stop that may have cut a sound off, so the driver's
    /// answer has a node to land on. Bounded: at the cap the oldest
    /// unanswered stop is dropped.
    fn record_stop(&mut self, playback: PlaybackId, key: Key, why: Why) {
        if self.stopped.len() >= MAX_STOPPED
            && let Some(oldest) = self.stopped.keys().min().copied()
        {
            self.stopped.remove(&oldest);
        }
        self.stopped.insert(playback, (key, why));
    }

    /// The driver reports it stopped `playback` while the sound was still
    /// running. Returns the node it was declared on and why it was cut,
    /// once — a stop that landed after the sound ended, or one of a
    /// playback nothing recorded (an imperative `stop`, a loop, a
    /// `finish` release), answers nothing.
    pub(crate) fn truncated(&mut self, playback: PlaybackId) -> Option<(Key, Why)> {
        self.stopped.remove(&playback)
    }

    pub(crate) fn set_volume(&mut self, playback: PlaybackId, volume: f32, tween_ms: f32) {
        self.commands.push(AudioCommand::SetVolume {
            playback,
            volume,
            tween_ms,
        });
    }

    pub(crate) fn pause(&mut self, playback: PlaybackId, fade_ms: f32) {
        self.commands
            .push(AudioCommand::Pause { playback, fade_ms });
    }

    pub(crate) fn resume(&mut self, playback: PlaybackId, fade_ms: f32) {
        self.commands
            .push(AudioCommand::Resume { playback, fade_ms });
    }

    pub(crate) fn master_volume(&mut self, volume: f32, tween_ms: f32) {
        self.commands
            .push(AudioCommand::MasterVolume { volume, tween_ms });
    }

    pub(crate) fn unload(&mut self, sound: SoundId) {
        self.commands.push(AudioCommand::Unload { sound });
    }

    /// Drains the queued commands (what `Core::take_audio_commands` hands
    /// the driver).
    pub fn take_commands(&mut self) -> Vec<AudioCommand> {
        std::mem::take(&mut self.commands)
    }

    /// Commands queued and not yet drained.
    pub fn pending(&self) -> &[AudioCommand] {
        &self.commands
    }

    /// The playback an `audio` node of `window` holds, if it is mounted.
    pub fn playback_of(&self, window: WindowId, key: Key) -> Option<PlaybackId> {
        self.mounted.get(&(window, key)).map(|m| m.playback)
    }

    /// Whether any `audio` node of `window` is mounted. The scene corpus's
    /// coverage derivation reads it: an `audio` element builds no tree
    /// node, so a mounted playback is the only trace one leaves.
    #[cfg(feature = "conformance")]
    pub(crate) fn any_mounted(&self, window: WindowId) -> bool {
        self.mounted.keys().any(|(w, _)| *w == window)
    }

    /// An `audio` node declared this frame by `window`; reconciled when
    /// that window's frame finishes.
    pub(crate) fn declare(
        &mut self,
        window: WindowId,
        key: Key,
        origin: OriginId,
        spec: AudioSpec,
    ) {
        self.declared.push(((window, key), origin, spec));
    }

    /// The driver reported a playback finished on its own. Returns the
    /// `ended` event when the playback asked for one.
    pub(crate) fn ended(&mut self, playback: PlaybackId) -> Option<UiEvent> {
        // It reached its end, so a stop queued for it in the same breath
        // cut nothing off.
        self.stopped.remove(&playback);
        let t = self.tagged.remove(&playback)?;
        Some(UiEvent {
            origin: t.origin,
            window: t.window,
            key: t.key,
            payload: Value::map([
                ("kind", Value::str("sound")),
                ("phase", Value::str("ended")),
                ("playback", Value::Int(playback.0 as i64)),
                ("tag", t.tag),
            ]),
            slot: None,
        })
    }

    /// The driver refused a play — the device's voices are all held, or
    /// the sound did not decode. The playback never started, so it will
    /// never reach [`Self::ended`]: a tagged one is handed the same event
    /// with `phase: "refused"` instead, which unsticks a view waiting on
    /// the sound and still tells it the sound was not heard. The warning
    /// comes back whether or not anything was waiting — an untagged
    /// refusal is silent otherwise.
    ///
    /// The `audio` node's mount is left alone: unmounting it would have
    /// the next frame re-declare, replay and be refused again, one line
    /// per frame, where leaving it mounted costs one.
    pub(crate) fn refused(
        &mut self,
        playback: PlaybackId,
    ) -> (Option<UiEvent>, crate::diag::Warning) {
        let warning = crate::diag::playback_refused(self.key_of(playback), playback);
        let event = self.tagged.remove(&playback).map(|t| UiEvent {
            origin: t.origin,
            window: t.window,
            key: t.key,
            payload: Value::map([
                ("kind", Value::str("sound")),
                ("phase", Value::str("refused")),
                ("playback", Value::Int(playback.0 as i64)),
                ("tag", t.tag),
            ]),
            slot: None,
        });
        (event, warning)
    }

    /// The node a warning about a playback hangs on: the node that asked
    /// for the sound when one did — a tagged playback's, or the `audio`
    /// element that mounted it — and the root otherwise, which is where an
    /// imperative `play` and a `click_sound` start from anyway.
    fn key_of(&self, playback: PlaybackId) -> Key {
        if let Some(t) = self.tagged.get(&playback) {
            return t.key;
        }
        self.mounted
            .iter()
            .find(|(_, m)| m.playback == playback)
            .map(|((_, k), _)| *k)
            .unwrap_or(Key::ROOT)
    }

    /// Diffs `window`'s frame's `audio` nodes against the playbacks
    /// mounted for that window — and that window only: another window's
    /// mounts are neither started nor stopped by a frame that is not
    /// theirs. New keys start, missing keys stop, a changed `src`/`looped`
    /// restarts, `volume`/`paused` changes apply live. A one-shot that
    /// finished stays mounted silently until its node goes away — so a
    /// view re-rendering does not replay it. A missing key that asked to
    /// [`finish`](AudioSpec::finish) is released rather than stopped.
    /// Every other stop of a one-shot is remembered (see `truncated`) in
    /// case the driver says the sound was still running.
    pub(crate) fn reconcile(&mut self, window: WindowId) {
        // Declarations are pushed while a frame is built and taken when it
        // finishes, so what is here is normally one window's; another
        // window's are left for its own finish.
        let (declared, others): (Vec<_>, Vec<_>) = std::mem::take(&mut self.declared)
            .into_iter()
            .partition(|(mount, _, _)| mount.0 == window);
        self.declared = others;
        let mut seen: Vec<Key> = Vec::with_capacity(declared.len());
        for (mount, origin, spec) in declared {
            let key = mount.1;
            if seen.contains(&key) {
                continue;
            }
            seen.push(key);
            let restart = match self.mounted.get(&mount) {
                None => true,
                Some(m) => m.spec.src != spec.src || m.spec.looped != spec.looped,
            };
            if restart {
                if let Some(old) = self.mounted.remove(&mount) {
                    self.stop(old.playback, 0.0);
                    // A replaced one-shot is cut off exactly as a removed
                    // one is; `finish` does not release it (it is not a
                    // departure), so it is also the opt-out here.
                    if !old.spec.looped && !old.spec.finish {
                        self.record_stop(old.playback, key, Why::Restarted);
                    }
                }
                let opts = PlayOptions {
                    volume: spec.volume,
                    looped: spec.looped,
                    fade_in_ms: 0.0,
                    tag: spec.tag.clone(),
                };
                let playback = self.play(origin, window, key, spec.src, opts);
                if spec.paused {
                    self.pause(playback, 0.0);
                }
                self.mounted.insert(mount, Mounted { playback, spec });
                continue;
            }
            let m = self.mounted.get_mut(&mount).expect("mounted");
            let playback = m.playback;
            if m.spec.volume != spec.volume {
                self.commands.push(AudioCommand::SetVolume {
                    playback,
                    volume: spec.volume,
                    tween_ms: 0.0,
                });
            }
            if m.spec.paused != spec.paused {
                self.commands.push(if spec.paused {
                    AudioCommand::Pause {
                        playback,
                        fade_ms: 0.0,
                    }
                } else {
                    AudioCommand::Resume {
                        playback,
                        fade_ms: 0.0,
                    }
                });
            }
            if m.spec.tag != spec.tag {
                match (&spec.tag, self.tagged.get_mut(&playback)) {
                    (Some(tag), Some(t)) => t.tag = tag.clone(),
                    (Some(tag), None) => {
                        self.tagged.insert(
                            playback,
                            Tagged {
                                origin,
                                window,
                                key,
                                tag: tag.clone(),
                            },
                        );
                    }
                    (None, _) => {
                        self.tagged.remove(&playback);
                    }
                }
            }
            m.spec = spec;
        }
        // A departure stops the playback, unless the node asked to be
        // released — then it is forgotten here and finishes on the device,
        // keeping its `tagged` entry so `ended` still arrives. A looped one
        // is stopped whatever it asked: it has no end to run to.
        let gone: Vec<(Key, PlaybackId, bool, bool)> = self
            .mounted
            .iter()
            .filter(|((w, k), _)| *w == window && !seen.contains(k))
            .map(|((_, k), m)| (*k, m.playback, m.spec.finish, m.spec.looped))
            .collect();
        for (key, playback, finish, looped) in gone {
            self.mounted.remove(&(window, key));
            if finish && !looped {
                continue;
            }
            self.stop(playback, 0.0);
            // A one-shot that did not ask to be released is the case
            // `truncated-playback` is about — if it was still running,
            // which only the driver can say.
            if !looped && !finish {
                self.record_stop(playback, key, Why::Removed);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::resources::{Resources, SessionId};

    fn sound() -> SoundId {
        Resources::new(SessionId::next()).add_sound(vec![0; 4])
    }

    #[test]
    fn play_allocates_ids_and_only_tagged_playbacks_report_ended() {
        let mut a = AudioStore::default();
        let s = sound();
        let quiet = a.play(
            OriginId::HOST,
            WindowId::MAIN,
            Key::ROOT,
            s,
            PlayOptions::default(),
        );
        let loud = a.play(
            OriginId::HOST,
            WindowId::MAIN,
            Key::ROOT,
            s,
            PlayOptions::default().tag(Value::str("t")),
        );
        assert_ne!(quiet, loud);
        assert_eq!(a.take_commands().len(), 2);
        assert!(a.ended(quiet).is_none());
        let ev = a.ended(loud).expect("tagged playback reports ended");
        assert_eq!(ev.kind(), Some("sound"));
        assert_eq!(ev.payload.get_str("tag"), Some("t"));
        assert_eq!(ev.payload.get_int("playback"), Some(loud.0 as i64));
        // Reported once.
        assert!(a.ended(loud).is_none());
    }

    #[test]
    fn stop_cancels_the_ended_event() {
        let mut a = AudioStore::default();
        let s = sound();
        let p = a.play(
            OriginId::HOST,
            WindowId::MAIN,
            Key::ROOT,
            s,
            PlayOptions::default().tag(Value::Null),
        );
        a.stop(p, 0.0);
        assert!(a.ended(p).is_none());
    }

    /// F29: the node's removal releases the playback, so a one-shot the
    /// view wants heard whole no longer has to stay declared for a length
    /// the view has to guess at.
    #[test]
    fn a_removed_node_that_asked_to_finish_is_not_stopped() {
        let mut a = AudioStore::default();
        let s = sound();
        let k = Key::ROOT.str("chime");
        a.declare(
            WindowId::MAIN,
            k,
            OriginId::HOST,
            AudioSpec::new(s).finish(),
        );
        a.reconcile(WindowId::MAIN);
        assert!(matches!(
            a.take_commands().as_slice(),
            [AudioCommand::Play { .. }]
        ));

        // Gone: released, not stopped — and the store forgets it, so a
        // later re-declare of the same key starts a new playback.
        a.reconcile(WindowId::MAIN);
        assert_eq!(a.take_commands(), vec![]);
        assert!(a.playback_of(WindowId::MAIN, k).is_none());
    }

    /// Release is meaningless for a loop — there is no end to run to — so
    /// the flag changes nothing and removal still stops it.
    #[test]
    fn a_removed_loop_stops_even_when_it_asked_to_finish() {
        let mut a = AudioStore::default();
        let s = sound();
        let k = Key::ROOT.str("bed");
        a.declare(
            WindowId::MAIN,
            k,
            OriginId::HOST,
            AudioSpec::new(s).looped().finish(),
        );
        a.reconcile(WindowId::MAIN);
        let p = a.playback_of(WindowId::MAIN, k).unwrap();
        a.take_commands();

        a.reconcile(WindowId::MAIN);
        assert_eq!(
            a.take_commands(),
            vec![AudioCommand::Stop {
                playback: p,
                fade_ms: 0.0
            }]
        );
    }

    /// The `ended` event is what the release hands the view instead of the
    /// guessed duration, so it has to survive the node going away — unlike
    /// a stop, which cancels it (`stop_cancels_the_ended_event`).
    #[test]
    fn a_released_playback_still_reports_ended() {
        let mut a = AudioStore::default();
        let s = sound();
        let k = Key::ROOT.str("chime");
        let spec = {
            let mut spec = AudioSpec::new(s).finish();
            spec.tag = Some(Value::str("chime"));
            spec
        };
        a.declare(WindowId::MAIN, k, OriginId::HOST, spec);
        a.reconcile(WindowId::MAIN);
        let p = a.playback_of(WindowId::MAIN, k).unwrap();
        a.take_commands();

        a.reconcile(WindowId::MAIN);
        assert_eq!(a.take_commands(), vec![]);
        let ev = a.ended(p).expect("a released playback still reports ended");
        assert_eq!(ev.key, k);
        assert_eq!(ev.payload.get_str("tag"), Some("chime"));
    }

    /// F35: the device refuses a play past its 128 voices, and the
    /// playback that never starts never ends — so a tagged node waiting
    /// for `ended` would wait forever. It hears `refused` instead, on the
    /// key it declared, and can tell the two phases apart.
    #[test]
    fn a_refused_tagged_playback_reports_refused_and_warns() {
        let mut a = AudioStore::default();
        let s = sound();
        let k = Key::ROOT.str("chime");
        let p = a.play(
            OriginId::HOST,
            WindowId::MAIN,
            k,
            s,
            PlayOptions::default().tag(Value::str("chime")),
        );
        let (event, warning) = a.refused(p);
        let ev = event.expect("a tagged playback hears the refusal");
        assert_eq!(ev.key, k);
        assert_eq!(ev.kind(), Some("sound"));
        assert_eq!(
            ev.payload.get_str("phase"),
            Some("refused"),
            "told apart from the `ended` that will never come"
        );
        assert_eq!(ev.payload.get_str("tag"), Some("chime"));
        assert_eq!(ev.payload.get_int("playback"), Some(p.0 as i64));
        assert_eq!(warning.code, crate::diag::PLAYBACK_REFUSED);
        assert_eq!(warning.key, k);

        // Reported once: the refusal is consumed like an end.
        assert!(a.refused(p).0.is_none());
        assert!(a.ended(p).is_none(), "and it can never end afterwards");
    }

    /// An untagged play — a `click_sound`, a bare `Core::play` — has no
    /// view waiting on it, so the warning is the whole report.
    #[test]
    fn a_refused_untagged_playback_is_the_warning_alone() {
        let mut a = AudioStore::default();
        let s = sound();
        let p = a.play(
            OriginId::HOST,
            WindowId::MAIN,
            Key::ROOT,
            s,
            PlayOptions::default(),
        );
        let (event, warning) = a.refused(p);
        assert!(event.is_none(), "nothing asked to hear about this one");
        assert_eq!(warning.code, crate::diag::PLAYBACK_REFUSED);
        assert_eq!(warning.key, Key::ROOT);
    }

    /// An `audio` node's playback survives the node — that is what
    /// `finish` means — so a refusal after the release still has the tag
    /// to report on, and the key the node declared it under.
    #[test]
    fn a_refused_released_playback_still_reports() {
        let mut a = AudioStore::default();
        let s = sound();
        let k = Key::ROOT.str("chime");
        let spec = {
            let mut spec = AudioSpec::new(s).finish();
            spec.tag = Some(Value::str("chime"));
            spec
        };
        a.declare(WindowId::MAIN, k, OriginId::HOST, spec);
        a.reconcile(WindowId::MAIN);
        let p = a.playback_of(WindowId::MAIN, k).unwrap();
        a.take_commands();

        // Gone: released, and the store forgets the mount.
        a.reconcile(WindowId::MAIN);
        assert!(a.playback_of(WindowId::MAIN, k).is_none());

        let (event, warning) = a.refused(p);
        let ev = event.expect("a released playback still hears the refusal");
        assert_eq!(ev.key, k);
        assert_eq!(ev.payload.get_str("phase"), Some("refused"));
        assert_eq!(warning.key, k);
    }

    /// A mounted `audio` node without a tag hangs its warning on the node
    /// rather than the root, so the line names the element that asked.
    #[test]
    fn an_untagged_audio_node_warns_on_its_own_key() {
        let mut a = AudioStore::default();
        let s = sound();
        let k = Key::ROOT.str("bed");
        a.declare(
            WindowId::MAIN,
            k,
            OriginId::HOST,
            AudioSpec::new(s).looped(),
        );
        a.reconcile(WindowId::MAIN);
        let p = a.playback_of(WindowId::MAIN, k).unwrap();

        let (event, warning) = a.refused(p);
        assert!(event.is_none());
        assert_eq!(warning.key, k);
    }

    #[test]
    fn audio_nodes_reconcile_by_key() {
        let mut a = AudioStore::default();
        let s = sound();
        let k = Key::ROOT.str("music");
        a.declare(
            WindowId::MAIN,
            k,
            OriginId::HOST,
            AudioSpec::new(s).looped(),
        );
        a.reconcile(WindowId::MAIN);
        let cmds = a.take_commands();
        assert!(matches!(
            cmds.as_slice(),
            [AudioCommand::Play { looped: true, .. }]
        ));
        let p = a.playback_of(WindowId::MAIN, k).unwrap();

        // Same declaration: nothing.
        a.declare(
            WindowId::MAIN,
            k,
            OriginId::HOST,
            AudioSpec::new(s).looped(),
        );
        a.reconcile(WindowId::MAIN);
        assert!(a.take_commands().is_empty());

        // Volume + pause apply live.
        a.declare(
            WindowId::MAIN,
            k,
            OriginId::HOST,
            AudioSpec::new(s).looped().volume(0.5).paused(true),
        );
        a.reconcile(WindowId::MAIN);
        let cmds = a.take_commands();
        assert_eq!(
            cmds,
            vec![
                AudioCommand::SetVolume {
                    playback: p,
                    volume: 0.5,
                    tween_ms: 0.0
                },
                AudioCommand::Pause {
                    playback: p,
                    fade_ms: 0.0
                }
            ]
        );

        // Gone: stopped.
        a.reconcile(WindowId::MAIN);
        assert_eq!(
            a.take_commands(),
            vec![AudioCommand::Stop {
                playback: p,
                fade_ms: 0.0
            }]
        );
        assert!(a.playback_of(WindowId::MAIN, k).is_none());
    }

    #[test]
    fn changing_src_restarts() {
        let mut a = AudioStore::default();
        let mut r = Resources::new(SessionId::next());
        let (s1, s2) = (r.add_sound(vec![0; 4]), r.add_sound(vec![1; 4]));
        let k = Key::ROOT.str("fx");
        a.declare(WindowId::MAIN, k, OriginId::HOST, AudioSpec::new(s1));
        a.reconcile(WindowId::MAIN);
        let p1 = a.playback_of(WindowId::MAIN, k).unwrap();
        a.take_commands();
        a.declare(WindowId::MAIN, k, OriginId::HOST, AudioSpec::new(s2));
        a.reconcile(WindowId::MAIN);
        let cmds = a.take_commands();
        assert!(matches!(
            cmds.as_slice(),
            [
                AudioCommand::Stop { playback, .. },
                AudioCommand::Play { sound, .. }
            ] if *playback == p1 && *sound == s2
        ));
    }
}