1
//! Media playback state machine (ledger 11c).
2
//!
3
//! # Why this module exists
4
//!
5
//! `EventType::{Play, Pause, Ended, TimeUpdate, VolumeChange, MediaError}`
6
//! shipped in `azul_core::events` from the beginning, but there was nothing
7
//! behind them. `dll/src/unified/` has a decoder (`decode_mp4_h264`), an
8
//! encoder (`VideoEncoder`), an audio sink (`AudioSink::play`) and a screen
9
//! recorder — and **no player**: no transport, no `is_playing`, no position,
10
//! no duration, no volume. Six events described state changes in something
11
//! that did not exist, so they stayed pinned as *unmapped* in
12
//! `core/src/events_test.rs` and dispatched to nothing.
13
//!
14
//! This is the missing state machine: the smallest thing that can honestly
15
//! raise those six events. It is deliberately **not** a media stack. There is
16
//! no buffering, no playback rate, no track selection, no seeking semantics
17
//! beyond "the position moved", and no connection to the decoder or the sink.
18
//! It owns four numbers and a bool per node, and it says when they change.
19
//!
20
//! # Who drives the clock
21
//!
22
//! Nothing in azul decodes on a schedule, so nothing here can invent a wall
23
//! clock. [`MediaPlayerManager::advance`] is called by the app — from a
24
//! `Timer`, or from the decoder thread's write-back — through
25
//! `CallbackInfo::media_advance`. That is the honest wiring: the app owns the
26
//! media clock, the engine owns the state transitions and the events.
27
//!
28
//! # Event queueing
29
//!
30
//! Same shape as [`crate::managers::sensors`]: transitions push onto
31
//! `pending`, the `EventProvider` impl reads it non-destructively (it takes
32
//! `&self`), and the event pass calls
33
//! [`clear_pending_event`](MediaPlayerManager::clear_pending_event) once it
34
//! has collected them. A provider that never clears re-emits its whole queue
35
//! on every pass for the life of the window.
36

            
37
use alloc::{collections::BTreeMap, vec::Vec};
38

            
39
pub use azul_core::media_player::{OptionPlaybackState, PlaybackState};
40
use azul_core::{
41
    dom::{DomId, DomNodeId},
42
    events::{EventData, EventProvider, EventSource as CoreEventSource, EventType, SyntheticEvent},
43
    task::Instant,
44
};
45

            
46
use super::{NodeIdMap, NodeIdRemap};
47

            
48
/// How much media time must elapse between two `TimeUpdate` events.
49
///
50
/// The web fires `timeupdate` about four times a second — deliberately far
51
/// below the frame rate, because a progress bar does not need 60 updates a
52
/// second and an event per frame would flood the event pass for the whole
53
/// duration of a playing video. 250 ms is that same 4/s budget.
54
///
55
/// The throttle is measured in MEDIA time (the position), not wall time: it
56
/// makes the rule deterministic — the same `advance` sequence always produces
57
/// the same events, which is what lets a test pin it.
58
pub const TIME_UPDATE_INTERVAL_S: f32 = 0.25;
59

            
60
/// One player: the observable [`PlaybackState`] plus the throttle
61
/// bookkeeping, which is deliberately NOT part of the public struct — an app
62
/// reading its media state has no business seeing when the last `TimeUpdate`
63
/// went out.
64
#[derive(Debug, Copy, Clone, PartialEq, Default)]
65
struct Player {
66
    state: PlaybackState,
67
    /// The position at which the last `TimeUpdate` was emitted.
68
    last_time_update_s: f32,
69
}
70

            
71
/// Per-node playback state plus the transport that mutates it.
72
///
73
/// Keyed by [`DomNodeId`], so it is NODE-keyed state and takes part in
74
/// [`NodeIdRemap`] — a rebuild renumbers the arena and unremapped state would
75
/// silently re-attach to a different element (see `managers/mod.rs`).
76
#[derive(Debug, Clone, Default, PartialEq)]
77
pub struct MediaPlayerManager {
78
    /// One entry per node the app has ever driven. Created lazily by the
79
    /// first transport call on that node.
80
    players: BTreeMap<DomNodeId, Player>,
81
    /// Transitions this pass has not yet collected, in the order they
82
    /// happened. Drained by `clear_pending_event`.
83
    pub pending: Vec<(DomNodeId, EventType)>,
84
}
85

            
86
/// Clamp that also answers for NaN (which every `f32::clamp` refuses to).
87
/// A NaN volume or position is a caller bug; the defensible reading is the
88
/// low bound, never a poisoned state that compares unequal to itself.
89
19
fn sanitize(v: f32, lo: f32, hi: f32) -> f32 {
90
19
    if v.is_nan() || v < lo {
91
2
        lo
92
17
    } else if v > hi {
93
3
        hi
94
    } else {
95
14
        v
96
    }
97
19
}
98

            
99
/// One transport verb, so a callback can name an operation without holding a
100
/// `&mut MediaPlayerManager` (see `CallbackChange::MediaTransport`).
101
///
102
/// Data-carrying variants are TUPLE variants on purpose — the codegen the
103
/// repo shares refuses struct variants with anything but exactly one field,
104
/// and a habit that only holds in the FFI enums is a habit that breaks the
105
/// first time one of these is exposed.
106
#[derive(Debug, Copy, Clone, PartialEq)]
107
pub enum MediaTransportOp {
108
    /// Start playback (`play`).
109
    Play,
110
    /// Stop playback where it stands (`pause`).
111
    Pause,
112
    /// Play if paused, pause if playing (`toggle`).
113
    Toggle,
114
    /// Move the position, in seconds (`seek`).
115
    Seek(f32),
116
    /// Set the output gain, `0.0..=1.0` (`set_volume`).
117
    SetVolume(f32),
118
    /// Mute or unmute (`set_muted`).
119
    SetMuted(bool),
120
    /// Record the media's length in seconds (`set_duration`).
121
    SetDuration(f32),
122
    /// Advance the media clock by this many seconds (`advance`).
123
    Advance(f32),
124
    /// The pipeline failed (`report_error`).
125
    ReportError,
126
}
127

            
128
impl MediaPlayerManager {
129
    #[must_use]
130
7594
    pub fn new() -> Self {
131
7594
        Self::default()
132
7594
    }
133

            
134
    /// Apply one transport verb. The single seam the `CallbackChange` path
135
    /// uses, so a new verb cannot be added to the enum without being routed.
136
8
    pub fn apply(&mut self, node: DomNodeId, op: MediaTransportOp) {
137
8
        match op {
138
1
            MediaTransportOp::Play => self.play(node),
139
            MediaTransportOp::Pause => self.pause(node),
140
1
            MediaTransportOp::Toggle => self.toggle(node),
141
1
            MediaTransportOp::Seek(p) => self.seek(node, p),
142
1
            MediaTransportOp::SetVolume(v) => self.set_volume(node, v),
143
1
            MediaTransportOp::SetMuted(m) => self.set_muted(node, m),
144
1
            MediaTransportOp::SetDuration(d) => self.set_duration(node, d),
145
1
            MediaTransportOp::Advance(dt) => self.advance(node, dt),
146
1
            MediaTransportOp::ReportError => self.report_error(node),
147
        }
148
8
    }
149

            
150
    /// The current state of `node`, or `None` if no transport call has ever
151
    /// named it — "this is not a media node" is a real answer, distinct from
152
    /// a default state, and the app can act on the difference.
153
    #[must_use]
154
16
    pub fn state(&self, node: DomNodeId) -> Option<PlaybackState> {
155
16
        self.players.get(&node).map(|p| p.state)
156
16
    }
157

            
158
    /// The player for `node`, creating the default entry if this is its first
159
    /// transport call.
160
45
    fn entry(&mut self, node: DomNodeId) -> &mut Player {
161
45
        self.players.entry(node).or_default()
162
45
    }
163

            
164
    /// Start playback. Emits `Play` only on the transition — calling `play`
165
    /// on an already-playing node is a no-op, not a second event.
166
16
    pub fn play(&mut self, node: DomNodeId) {
167
16
        let p = self.entry(node);
168
16
        if p.state.playing {
169
1
            return;
170
15
        }
171
        // Playing from the end rewinds. Otherwise the very next `advance`
172
        // would re-reach the end and `Ended` again, and the transport would
173
        // be stuck at the tail forever.
174
15
        if p.state.duration_s > 0.0 && p.state.position_s >= p.state.duration_s {
175
1
            p.state.position_s = 0.0;
176
1
            p.last_time_update_s = 0.0;
177
14
        }
178
15
        p.state.playing = true;
179
15
        self.pending.push((node, EventType::Play));
180
16
    }
181

            
182
    /// Stop playback where it stands. Emits `Pause` only on the transition.
183
5
    pub fn pause(&mut self, node: DomNodeId) {
184
5
        let p = self.entry(node);
185
5
        if !p.state.playing {
186
1
            return;
187
4
        }
188
4
        p.state.playing = false;
189
4
        self.pending.push((node, EventType::Pause));
190
5
    }
191

            
192
    /// Play if paused, pause if playing. An unknown node starts playing (its
193
    /// default state is paused).
194
4
    pub fn toggle(&mut self, node: DomNodeId) {
195
4
        if self.players.get(&node).is_some_and(|p| p.state.playing) {
196
2
            self.pause(node);
197
2
        } else {
198
2
            self.play(node);
199
2
        }
200
4
    }
201

            
202
    /// Move the position. Clamped into `0..=duration` when a duration is
203
    /// known, `>= 0` otherwise.
204
    ///
205
    /// A seek is a discontinuity in the media clock, so it reports
206
    /// `TimeUpdate` immediately and resets the throttle rather than waiting
207
    /// for the next 250 ms boundary. There is no `seeking`/`seeked`
208
    /// `EventType` in azul, so `TimeUpdate` is the whole story. A seek that
209
    /// does not move the position emits nothing.
210
6
    pub fn seek(&mut self, node: DomNodeId, position_s: f32) {
211
6
        let p = self.entry(node);
212
6
        let hi = if p.state.duration_s > 0.0 {
213
6
            p.state.duration_s
214
        } else {
215
            f32::MAX
216
        };
217
6
        let target = sanitize(position_s, 0.0, hi);
218
6
        if p.state.position_s == target {
219
2
            return;
220
4
        }
221
4
        p.state.position_s = target;
222
4
        p.last_time_update_s = target;
223
4
        self.pending.push((node, EventType::TimeUpdate));
224
6
    }
225

            
226
    /// Set the output gain, clamped to `0.0..=1.0`. Emits `VolumeChange`
227
    /// only when the value actually moves.
228
8
    pub fn set_volume(&mut self, node: DomNodeId, volume: f32) {
229
8
        let p = self.entry(node);
230
8
        let target = sanitize(volume, 0.0, 1.0);
231
8
        if p.state.volume == target {
232
3
            return;
233
5
        }
234
5
        p.state.volume = target;
235
5
        self.pending.push((node, EventType::VolumeChange));
236
8
    }
237

            
238
    /// Mute or unmute. Reported as `VolumeChange` — the web spells a mute
239
    /// change the same way, and azul has no separate event for it.
240
3
    pub fn set_muted(&mut self, node: DomNodeId, muted: bool) {
241
3
        let p = self.entry(node);
242
3
        if p.state.muted == muted {
243
1
            return;
244
2
        }
245
2
        p.state.muted = muted;
246
2
        self.pending.push((node, EventType::VolumeChange));
247
3
    }
248

            
249
    /// Record the media's length once the app knows it (metadata, or a
250
    /// decoder's header parse). Negative and NaN lengths read as "unknown".
251
    ///
252
    /// Emits nothing: there is no `durationchange` `EventType`, and learning
253
    /// how long a file is is not playback reaching its end — so a position
254
    /// past the new duration is clamped WITHOUT raising `Ended`.
255
5
    pub fn set_duration(&mut self, node: DomNodeId, duration_s: f32) {
256
5
        let p = self.entry(node);
257
5
        p.state.duration_s = sanitize(duration_s, 0.0, f32::MAX);
258
5
        if p.state.duration_s > 0.0 && p.state.position_s > p.state.duration_s {
259
1
            p.state.position_s = p.state.duration_s;
260
4
        }
261
5
    }
262

            
263
    /// Advance the media clock by `dt_s` seconds of wall time.
264
    ///
265
    /// Does nothing while paused, on an unknown node, or for a non-positive
266
    /// or NaN `dt_s`. Emits at most one `TimeUpdate` (throttled to
267
    /// [`TIME_UPDATE_INTERVAL_S`]) and, on reaching a known duration, exactly
268
    /// one `Ended`: reaching the end also clears `playing`, so a second
269
    /// `advance` returns immediately and cannot emit `Ended` twice.
270
    // `!(dt_s > 0.0)` below is the NaN filter; `dt_s <= 0.0` would let NaN through.
271
    #[allow(clippy::neg_cmp_op_on_partial_ord)]
272
87
    pub fn advance(&mut self, node: DomNodeId, dt_s: f32) {
273
87
        let Some(p) = self.players.get_mut(&node) else {
274
            return;
275
        };
276
        // `!(dt > 0.0)` rather than `dt <= 0.0` so NaN is rejected too.
277
87
        if !p.state.playing || !(dt_s > 0.0) {
278
1
            return;
279
86
        }
280
86
        p.state.position_s += dt_s;
281
86
        let ended = if p.state.duration_s > 0.0 && p.state.position_s >= p.state.duration_s {
282
3
            p.state.position_s = p.state.duration_s;
283
3
            p.state.playing = false;
284
3
            true
285
        } else {
286
83
            false
287
        };
288
86
        let due = (p.state.position_s - p.last_time_update_s).abs() >= TIME_UPDATE_INTERVAL_S;
289
86
        if due {
290
11
            p.last_time_update_s = p.state.position_s;
291
75
        }
292
86
        if due {
293
11
            self.pending.push((node, EventType::TimeUpdate));
294
75
        }
295
86
        if ended {
296
3
            self.pending.push((node, EventType::Ended));
297
83
        }
298
87
    }
299

            
300
    /// The app's decoder/sink failed. Stops the transport and emits
301
    /// `MediaError` — every call emits, because two failures are two errors
302
    /// (there is no state here to transition).
303
2
    pub fn report_error(&mut self, node: DomNodeId) {
304
2
        let p = self.entry(node);
305
2
        p.state.playing = false;
306
2
        self.pending.push((node, EventType::MediaError));
307
2
    }
308

            
309
    /// Forget everything about `node` (the app tore its player down).
310
    pub fn remove(&mut self, node: DomNodeId) {
311
        self.players.remove(&node);
312
        self.pending.retain(|(n, _)| *n != node);
313
    }
314

            
315
    /// Drop the collected transitions. Called by the event pass right after
316
    /// determination, exactly like `SensorManager::clear_pending_event`.
317
158
    pub fn clear_pending_event(&mut self) {
318
158
        self.pending.clear();
319
158
    }
320

            
321
    /// Whether anything is queued (used by tests and by the e2e fingerprint).
322
    #[must_use]
323
    pub const fn has_pending(&self) -> bool {
324
        !self.pending.is_empty()
325
    }
326
}
327

            
328
impl EventProvider for MediaPlayerManager {
329
    /// One event per queued transition, targeted at the media node so the
330
    /// callback can ask which player moved.
331
    ///
332
    /// `EventSource::User` like every other capability manager — nothing in
333
    /// dispatch reads the source, and a transport call is the user pressing
334
    /// play as far as the app is concerned.
335
146
    fn get_pending_events(&self, timestamp: Instant) -> Vec<SyntheticEvent> {
336
146
        self.pending
337
146
            .iter()
338
147
            .map(|(node, ty)| {
339
4
                SyntheticEvent::new(
340
4
                    *ty,
341
4
                    CoreEventSource::User,
342
4
                    *node,
343
4
                    timestamp.clone(),
344
4
                    EventData::None,
345
                )
346
4
            })
347
146
            .collect()
348
146
    }
349
}
350

            
351
impl NodeIdRemap for MediaPlayerManager {
352
447
    fn remap_node_ids(&mut self, dom: DomId, map: &NodeIdMap) {
353
447
        let old = core::mem::take(&mut self.players);
354
449
        for (k, v) in old {
355
2
            if let Some(nk) = map.resolve_dom_node_id(dom, k) {
356
1
                self.players.insert(nk, v);
357
1
            }
358
        }
359
447
        let queued = core::mem::take(&mut self.pending);
360
447
        self.pending = queued
361
447
            .into_iter()
362
448
            .filter_map(|(n, ty)| map.resolve_dom_node_id(dom, n).map(|nn| (nn, ty)))
363
447
            .collect();
364
447
    }
365
}
366

            
367
#[cfg(test)]
368
mod tests {
369
    use azul_core::{
370
        id::NodeId,
371
        styled_dom::NodeHierarchyItemId,
372
        task::{Instant, SystemTick},
373
    };
374

            
375
    use super::*;
376

            
377
18
    fn node(idx: usize) -> DomNodeId {
378
18
        DomNodeId {
379
18
            dom: DomId::ROOT_ID,
380
18
            node: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(idx))),
381
18
        }
382
18
    }
383

            
384
21
    fn kinds(mgr: &MediaPlayerManager) -> Vec<EventType> {
385
21
        mgr.pending.iter().map(|(_, ty)| *ty).collect()
386
21
    }
387

            
388
    #[test]
389
1
    fn play_then_pause_emits_play_then_pause() {
390
1
        let mut mgr = MediaPlayerManager::new();
391
1
        let n = node(3);
392
1
        mgr.play(n);
393
1
        mgr.pause(n);
394
1
        assert_eq!(kinds(&mgr), vec![EventType::Play, EventType::Pause]);
395
1
        assert!(!mgr.state(n).unwrap().playing);
396
1
    }
397

            
398
    #[test]
399
1
    fn repeated_transport_calls_emit_only_on_the_transition() {
400
1
        let mut mgr = MediaPlayerManager::new();
401
1
        let n = node(1);
402
1
        mgr.play(n);
403
1
        mgr.play(n); // already playing — not a second Play
404
1
        mgr.pause(n);
405
1
        mgr.pause(n); // already paused — not a second Pause
406
1
        assert_eq!(kinds(&mgr), vec![EventType::Play, EventType::Pause]);
407
1
    }
408

            
409
    #[test]
410
1
    fn toggle_alternates_play_and_pause() {
411
1
        let mut mgr = MediaPlayerManager::new();
412
1
        let n = node(2);
413
1
        mgr.toggle(n);
414
1
        mgr.toggle(n);
415
1
        mgr.toggle(n);
416
1
        assert_eq!(
417
1
            kinds(&mgr),
418
1
            vec![EventType::Play, EventType::Pause, EventType::Play]
419
        );
420
1
    }
421

            
422
    #[test]
423
1
    fn advance_past_duration_ends_exactly_once() {
424
1
        let mut mgr = MediaPlayerManager::new();
425
1
        let n = node(4);
426
1
        mgr.set_duration(n, 1.0);
427
1
        mgr.play(n);
428
1
        mgr.clear_pending_event();
429

            
430
1
        mgr.advance(n, 5.0);
431
1
        assert!(
432
1
            kinds(&mgr).contains(&EventType::Ended),
433
            "reaching the end must raise Ended: {:?}",
434
            kinds(&mgr)
435
        );
436
1
        assert_eq!(
437
1
            kinds(&mgr)
438
1
                .iter()
439
2
                .filter(|t| **t == EventType::Ended)
440
1
                .count(),
441
            1
442
        );
443
1
        let st = mgr.state(n).unwrap();
444
1
        assert!(!st.playing, "the end stops the transport");
445
1
        assert_eq!(st.position_s, 1.0, "the position clamps at the duration");
446

            
447
        // A second advance on the ended player must not raise Ended again —
448
        // this is the "exactly once" half of the rule.
449
1
        mgr.clear_pending_event();
450
1
        mgr.advance(n, 5.0);
451
1
        assert!(kinds(&mgr).is_empty(), "{:?}", kinds(&mgr));
452
1
    }
453

            
454
    #[test]
455
1
    fn playing_again_after_the_end_rewinds_and_can_end_again() {
456
1
        let mut mgr = MediaPlayerManager::new();
457
1
        let n = node(5);
458
1
        mgr.set_duration(n, 2.0);
459
1
        mgr.play(n);
460
1
        mgr.advance(n, 10.0);
461
1
        mgr.clear_pending_event();
462

            
463
1
        mgr.play(n);
464
1
        assert_eq!(mgr.state(n).unwrap().position_s, 0.0, "play rewinds");
465
1
        mgr.advance(n, 10.0);
466
1
        assert_eq!(
467
1
            kinds(&mgr)
468
1
                .iter()
469
3
                .filter(|t| **t == EventType::Ended)
470
1
                .count(),
471
            1
472
        );
473
1
    }
474

            
475
    #[test]
476
1
    fn an_unknown_duration_never_ends() {
477
1
        let mut mgr = MediaPlayerManager::new();
478
1
        let n = node(6);
479
1
        mgr.play(n); // duration stays 0.0 = unknown (a live stream)
480
1
        mgr.clear_pending_event();
481
1
        mgr.advance(n, 3600.0);
482
1
        assert!(!kinds(&mgr).contains(&EventType::Ended));
483
1
        assert!(mgr.state(n).unwrap().playing);
484
1
    }
485

            
486
    #[test]
487
1
    fn time_update_is_throttled_to_the_250ms_budget() {
488
1
        let mut mgr = MediaPlayerManager::new();
489
1
        let n = node(7);
490
1
        mgr.play(n);
491
1
        mgr.clear_pending_event();
492

            
493
        // A 64 Hz tick, not 60: 1/64 is exact in binary, and with 1/60 the
494
        // accumulated f32 error puts the last boundary one ULP under the
495
        // threshold, which would make the count below flaky rather than
496
        // wrong. The throttle rule is what is under test, not float error.
497
1
        let frame = 1.0 / 64.0;
498

            
499
        // Sixteen frames = exactly 0.25 s of media time. Unthrottled that
500
        // would be 16 events; the budget allows one.
501
17
        for _ in 0..16 {
502
16
            mgr.advance(n, frame);
503
16
        }
504
1
        assert_eq!(
505
1
            kinds(&mgr),
506
1
            vec![EventType::TimeUpdate],
507
            "one TimeUpdate per {TIME_UPDATE_INTERVAL_S}s of media time, not one per frame"
508
        );
509

            
510
        // A full second more is exactly four more boundaries — the web's
511
        // ~4/s budget — out of 64 advance calls.
512
1
        mgr.clear_pending_event();
513
65
        for _ in 0..64 {
514
64
            mgr.advance(n, frame);
515
64
        }
516
1
        assert_eq!(kinds(&mgr).len(), 4, "{:?}", kinds(&mgr));
517
1
    }
518

            
519
    #[test]
520
1
    fn seek_reports_a_time_update_and_resets_the_throttle() {
521
1
        let mut mgr = MediaPlayerManager::new();
522
1
        let n = node(8);
523
1
        mgr.set_duration(n, 10.0);
524
1
        mgr.clear_pending_event();
525

            
526
1
        mgr.seek(n, 4.0);
527
1
        assert_eq!(kinds(&mgr), vec![EventType::TimeUpdate]);
528
1
        assert_eq!(mgr.state(n).unwrap().position_s, 4.0);
529

            
530
        // A seek to where we already are is not a change.
531
1
        mgr.clear_pending_event();
532
1
        mgr.seek(n, 4.0);
533
1
        assert!(kinds(&mgr).is_empty());
534

            
535
        // Out of range clamps rather than corrupting the state.
536
1
        mgr.seek(n, 99.0);
537
1
        assert_eq!(mgr.state(n).unwrap().position_s, 10.0);
538
1
        mgr.seek(n, -5.0);
539
1
        assert_eq!(mgr.state(n).unwrap().position_s, 0.0);
540
1
        mgr.seek(n, f32::NAN);
541
1
        assert_eq!(mgr.state(n).unwrap().position_s, 0.0, "NaN reads as 0");
542
1
    }
543

            
544
    #[test]
545
1
    fn set_volume_emits_only_on_an_actual_change() {
546
1
        let mut mgr = MediaPlayerManager::new();
547
1
        let n = node(9);
548
1
        mgr.set_volume(n, 1.0); // the default — not a change
549
1
        assert!(kinds(&mgr).is_empty());
550

            
551
1
        mgr.set_volume(n, 0.4);
552
1
        assert_eq!(kinds(&mgr), vec![EventType::VolumeChange]);
553

            
554
1
        mgr.clear_pending_event();
555
1
        mgr.set_volume(n, 0.4); // same value again
556
1
        assert!(kinds(&mgr).is_empty());
557

            
558
        // Clamping: 2.0 and 1.0 are the same volume, so only the first moves.
559
1
        mgr.set_volume(n, 2.0);
560
1
        assert_eq!(mgr.state(n).unwrap().volume, 1.0);
561
1
        mgr.clear_pending_event();
562
1
        mgr.set_volume(n, 5.0);
563
1
        assert!(kinds(&mgr).is_empty(), "already clamped to 1.0");
564
1
    }
565

            
566
    #[test]
567
1
    fn muting_is_reported_as_a_volume_change_and_spares_the_level() {
568
1
        let mut mgr = MediaPlayerManager::new();
569
1
        let n = node(10);
570
1
        mgr.set_volume(n, 0.7);
571
1
        mgr.clear_pending_event();
572

            
573
1
        mgr.set_muted(n, true);
574
1
        assert_eq!(kinds(&mgr), vec![EventType::VolumeChange]);
575
1
        assert_eq!(mgr.state(n).unwrap().volume, 0.7, "unmuting restores it");
576

            
577
1
        mgr.clear_pending_event();
578
1
        mgr.set_muted(n, true); // no change
579
1
        assert!(kinds(&mgr).is_empty());
580
1
    }
581

            
582
    #[test]
583
1
    fn report_error_stops_the_transport_and_emits() {
584
1
        let mut mgr = MediaPlayerManager::new();
585
1
        let n = node(11);
586
1
        mgr.play(n);
587
1
        mgr.clear_pending_event();
588

            
589
1
        mgr.report_error(n);
590
1
        assert_eq!(kinds(&mgr), vec![EventType::MediaError]);
591
1
        assert!(!mgr.state(n).unwrap().playing);
592
1
    }
593

            
594
    #[test]
595
1
    fn set_duration_clamps_without_ending() {
596
1
        let mut mgr = MediaPlayerManager::new();
597
1
        let n = node(12);
598
1
        mgr.play(n);
599
1
        mgr.advance(n, 30.0);
600
1
        mgr.clear_pending_event();
601

            
602
        // Metadata arrives late and says the file is shorter than where we are.
603
1
        mgr.set_duration(n, 5.0);
604
1
        assert_eq!(mgr.state(n).unwrap().position_s, 5.0);
605
1
        assert!(
606
1
            kinds(&mgr).is_empty(),
607
            "learning the length is not reaching the end: {:?}",
608
            kinds(&mgr)
609
        );
610
1
    }
611

            
612
    #[test]
613
1
    fn the_provider_yields_one_event_per_queued_transition() {
614
1
        let mut mgr = MediaPlayerManager::new();
615
1
        let n = node(13);
616
1
        mgr.play(n);
617
1
        mgr.set_volume(n, 0.5);
618
1
        let ts = Instant::Tick(SystemTick::new(0));
619

            
620
1
        let evs = mgr.get_pending_events(ts.clone());
621
1
        assert_eq!(evs.len(), 2);
622
1
        assert_eq!(evs[0].event_type, EventType::Play);
623
1
        assert_eq!(evs[1].event_type, EventType::VolumeChange);
624
1
        assert_eq!(evs[0].target, n, "the event names the media node");
625

            
626
        // Reading is NOT draining — only clear_pending_event retires them,
627
        // which is the contract every EventProvider in the tree shares.
628
1
        assert_eq!(mgr.get_pending_events(ts.clone()).len(), 2);
629
1
        mgr.clear_pending_event();
630
1
        assert!(mgr.get_pending_events(ts).is_empty());
631
1
    }
632

            
633
    #[test]
634
1
    fn every_transport_op_reaches_its_verb() {
635
        // The `CallbackChange` path goes through `apply`, so a verb that is
636
        // not routed here is a `CallbackInfo` method that silently does
637
        // nothing — the exact dead-wiring shape this item exists to close.
638
1
        let mut mgr = MediaPlayerManager::new();
639
1
        let n = node(20);
640
1
        mgr.apply(n, MediaTransportOp::SetDuration(10.0));
641
1
        mgr.apply(n, MediaTransportOp::Play);
642
1
        mgr.apply(n, MediaTransportOp::Advance(1.0));
643
1
        mgr.apply(n, MediaTransportOp::Seek(2.0));
644
1
        mgr.apply(n, MediaTransportOp::SetVolume(0.25));
645
1
        mgr.apply(n, MediaTransportOp::SetMuted(true));
646
1
        mgr.apply(n, MediaTransportOp::Toggle);
647
1
        mgr.apply(n, MediaTransportOp::ReportError);
648
1
        let st = mgr.state(n).unwrap();
649
1
        assert_eq!(st.duration_s, 10.0);
650
1
        assert_eq!(st.position_s, 2.0);
651
1
        assert_eq!(st.volume, 0.25);
652
1
        assert!(st.muted);
653
1
        assert!(!st.playing);
654
1
        assert_eq!(
655
1
            kinds(&mgr),
656
1
            vec![
657
1
                EventType::Play,
658
1
                EventType::TimeUpdate, // the 1 s advance
659
1
                EventType::TimeUpdate, // the seek
660
1
                EventType::VolumeChange,
661
1
                EventType::VolumeChange, // the mute
662
1
                EventType::Pause,        // toggle, from playing
663
1
                EventType::MediaError,
664
            ]
665
        );
666
1
    }
667

            
668
    #[test]
669
1
    fn remap_follows_a_moved_node_and_drops_an_unmounted_one() {
670
1
        let mut mgr = MediaPlayerManager::new();
671
1
        let moved = node(4);
672
1
        let gone = node(9);
673
1
        mgr.play(moved);
674
1
        mgr.play(gone);
675

            
676
        // Node 4 became node 2; node 9 was unmounted (absent from the map).
677
1
        let map = NodeIdMap::from_pairs([(NodeId::new(4), NodeId::new(2))]);
678
1
        mgr.remap_node_ids(DomId::ROOT_ID, &map);
679

            
680
1
        assert!(mgr.state(node(2)).is_some_and(|s| s.playing));
681
1
        assert!(mgr.state(moved).is_none(), "the old index must not survive");
682
1
        assert!(mgr.state(gone).is_none(), "unmounted state is dropped");
683
1
        assert_eq!(mgr.pending.len(), 1, "its queued Play went with it");
684
1
        assert_eq!(mgr.pending[0].0, node(2));
685
1
    }
686
}