Skip to main content

waft_widgets/media/
player.rs

1//! A player, as an app holds it, and the view that shows its video.
2
3use std::fmt;
4use std::rc::Rc;
5use std::sync::Arc;
6use std::time::Duration;
7
8use waft_embedder::{
9    CompositionLayer, Cue, MediaChangeFuture, MediaMetadata, MediaPlayer, PlayerState,
10    SeekTolerance, VideoOutput,
11};
12use waft_foundation::{
13    App, ChangeNotifier, ChangeNotifierData, Handle, Listenable, ListenableObject, Listener, Ref,
14};
15use waft_painting::AlignmentGeometry;
16
17use super::{SubtitleView, at_size};
18use crate::framework::{
19    BuildContext, IntoWidget, KeyRef, State, StateData, StatefulWidget, StatelessWidget, WidgetRef,
20};
21use crate::widgets::basic::{Positioned, SizedBox, Stack};
22use crate::widgets::composition_layer_view::CompositionLayerView;
23use crate::widgets::transitions::ListenableBuilder;
24
25/// A player of the media at one URL, which loads by itself: the host's player, whose listeners
26/// hear its state, its metadata or its cues change and its position jump, at each change its host
27/// tells. A URL the system cannot play gives a player whose state is a failure.
28pub struct Player {
29    change_notifier: ChangeNotifierData,
30    /// The host's player, until [`dispose`](Player::dispose).
31    host: Option<Rc<dyn MediaPlayer>>,
32    /// The host's state when it last changed.
33    state: PlayerState,
34    /// The host's metadata when it last changed.
35    metadata: MediaMetadata,
36    /// The host's cues when they last changed.
37    cues: Vec<Cue>,
38    /// Where the video was sent last, which a [`PlayerView`] sends it nowhere from only while
39    /// it is still the view's own layer.
40    video_output: Option<VideoOutput>,
41}
42
43impl Player {
44    /// A player of the media at `url`, which starts loading at once: a link, or a picked file's
45    /// `PickedFile::url`. `None` where the platform has no players.
46    pub fn new(app: &mut App, url: &str) -> Option<Ref<Player>> {
47        let platform = app.platform();
48        let host: Rc<dyn MediaPlayer> = Rc::from(platform.players()?.open(url));
49        let changed = host.changed();
50        let player = app.create(Player {
51            change_notifier: ChangeNotifierData::new(),
52            state: host.state(),
53            metadata: host.metadata(),
54            cues: host.cues(),
55            host: Some(host),
56            video_output: None,
57        });
58        player.follow(app, changed);
59        Some(player)
60    }
61
62    /// The player's state when it last changed.
63    pub fn state(self: Handle<Self>, app: &App) -> &PlayerState {
64        &app.get(self).state
65    }
66
67    /// What the media's tags say about it, when that last changed: Media3's `getMediaMetadata`.
68    pub fn metadata(self: Handle<Self>, app: &App) -> &MediaMetadata {
69        &app.get(self).metadata
70    }
71
72    /// The cues to show now, as the media styles them: Media3's `getCurrentCues`. A
73    /// [`PlayerView`] draws them over the video in the user's caption style; an app that draws
74    /// the frames itself puts a `SubtitleView` of them over its video.
75    pub fn cues(self: Handle<Self>, app: &App) -> &[Cue] {
76        &app.get(self).cues
77    }
78
79    /// Where the player is in the media now, read from the host's player at each call: Media3's
80    /// `getCurrentPosition`. It moves on by itself while the player plays, which its listeners do
81    /// not hear; they hear it jump. A widget that shows it while it plays reads it at each frame,
82    /// with a ticker running while the state says it plays.
83    ///
84    /// # Panics
85    ///
86    /// Once disposed.
87    pub fn position(self: Handle<Self>, app: &App) -> Duration {
88        self.host(app).position()
89    }
90
91    pub fn play(self: Handle<Self>, app: &App) {
92        self.host(app).play();
93    }
94
95    pub fn pause(self: Handle<Self>, app: &App) {
96        self.host(app).pause();
97    }
98
99    /// Moves to `position`, or as near it as `tolerance` lets the system land for speed,
100    /// playing on from there if it was playing; the state tells the seek under way until it
101    /// lands.
102    pub fn seek_to(self: Handle<Self>, app: &App, position: Duration, tolerance: SeekTolerance) {
103        self.host(app).seek(position, tolerance);
104    }
105
106    /// How fast it plays, `1.0` the media's own speed.
107    pub fn set_rate(self: Handle<Self>, app: &App, rate: f64) {
108        self.host(app).set_rate(rate);
109    }
110
111    /// How loud it plays, from `0.0` to `1.0`.
112    pub fn set_volume(self: Handle<Self>, app: &App, volume: f64) {
113        self.host(app).set_volume(volume);
114    }
115
116    /// Whether its sound is off, apart from its volume.
117    pub fn set_muted(self: Handle<Self>, app: &App, muted: bool) {
118        self.host(app).set_muted(muted);
119    }
120
121    /// Whether it starts again from the beginning when it reaches the end.
122    pub fn set_looping(self: Handle<Self>, app: &App, looping: bool) {
123        self.host(app).set_looping(looping);
124    }
125
126    /// Plays the audio track `id`, one of the state's `tracks`, in place of the one playing.
127    pub fn select_audio_track(self: Handle<Self>, app: &App, id: &str) {
128        self.host(app).select_audio_track(id);
129    }
130
131    /// Shows the text track `id`, one of the state's `tracks`, or none: subtitles off.
132    pub fn select_text_track(self: Handle<Self>, app: &App, id: Option<&str>) {
133        self.host(app).select_text_track(id);
134    }
135
136    /// Sends the video to `output` from now on, and nowhere it went before; `None` sends it
137    /// nowhere: Media3's `setVideoSurface`. A [`PlayerView`] sends it to a composition layer of
138    /// its own as it is mounted, and nowhere as it is unmounted; an app that draws the frames
139    /// itself sends it to a reader it made, which a `VideoFrameView` draws.
140    pub fn set_video_output(self: Handle<Self>, app: &mut App, output: Option<VideoOutput>) {
141        self.host(app).set_video_output(output.clone());
142        app.get_mut(self).video_output = output;
143    }
144
145    /// Stops the player and lets go of the host's: its picture leaves the layer it was on.
146    /// Its listeners hear nothing more.
147    pub fn dispose(self: Handle<Self>, app: &mut App) {
148        let player = app.get_mut(self);
149        player.host = None;
150        player.video_output = None;
151        ChangeNotifierData::dispose(app, self);
152    }
153
154    /// The host's player.
155    ///
156    /// # Panics
157    ///
158    /// Once disposed.
159    fn host(self: Handle<Self>, app: &App) -> &dyn MediaPlayer {
160        app.get(self)
161            .host
162            .as_deref()
163            .expect("a Player used after dispose")
164    }
165
166    /// Takes the host's state at each of its changes, from the one `changed` resolves at, until
167    /// the player is disposed.
168    fn follow(self: Handle<Self>, app: &mut App, changed: MediaChangeFuture) {
169        let _following = app.spawn(async move |cx| {
170            let mut changed = changed;
171            loop {
172                changed.await;
173                let next = cx.update(|app| {
174                    let player = self.upgrade(app)?;
175                    player.take_host_state(app)
176                });
177                match next {
178                    Some(next) => changed = next,
179                    None => return,
180                }
181            }
182        });
183    }
184
185    /// Takes the host's state, metadata and cues and tells the listeners, since the host's
186    /// change may have been a jump of the position, which nothing taken shows; answers the future
187    /// of the host's next change, asked before they are read so that no change goes unheard, or
188    /// `None` once the player is disposed.
189    fn take_host_state(self: Handle<Self>, app: &mut App) -> Option<MediaChangeFuture> {
190        let host = app.get(self).host.clone()?;
191        let next = host.changed();
192        let (state, metadata, cues) = (host.state(), host.metadata(), host.cues());
193        let player = app.get_mut(self);
194        player.state = state;
195        player.metadata = metadata;
196        player.cues = cues;
197        self.notify_listeners(app);
198        Some(next)
199    }
200}
201
202impl ChangeNotifier for Player {
203    fn change_notifier_data(&self) -> &ChangeNotifierData {
204        &self.change_notifier
205    }
206
207    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
208        &mut self.change_notifier
209    }
210}
211
212impl fmt::Debug for Player {
213    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
214        f.debug_struct("Player")
215            .field("state", &self.state)
216            .finish_non_exhaustive()
217    }
218}
219
220impl Player {
221    /// Puts the video on `layer` from now on; `None` sends it nowhere.
222    fn set_video_layer(
223        self: Handle<Self>,
224        app: &mut App,
225        layer: Option<Arc<dyn CompositionLayer>>,
226    ) {
227        self.set_video_output(app, layer.map(VideoOutput::Layer));
228    }
229
230    /// The layer the video was sent to last; `None` once sent nowhere or to a reader, or
231    /// disposed.
232    fn video_layer(self: Handle<Self>, app: &App) -> Option<&Arc<dyn CompositionLayer>> {
233        match &app.get(self).video_output {
234            Some(VideoOutput::Layer(layer)) => Some(layer),
235            _ => None,
236        }
237    }
238}
239
240/// A player's video, Media3's `PlayerView`, laid out at its size in logical pixels, or as large as
241/// the constraints let it be at that aspect; no room until the size is known. It shows the player
242/// on a composition layer of its own, which the system draws the video into: the cheapest way, and
243/// the only one protected and HDR video show in. The player shows on the view built for it last.
244/// Over the video a [`SubtitleView`] draws the player's cues. For a video the framework draws,
245/// under effects a layer cannot take, see `VideoFrameView`.
246#[derive(Clone)]
247pub struct PlayerView {
248    pub key: Option<KeyRef>,
249    pub player: Ref<Player>,
250}
251
252impl PlayerView {
253    pub fn new(player: Ref<Player>) -> PlayerView {
254        PlayerView { key: None, player }
255    }
256
257    pub fn key(mut self, key: KeyRef) -> PlayerView {
258        self.key = Some(key);
259        self
260    }
261}
262
263impl fmt::Debug for PlayerView {
264    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
265        f.debug_struct("PlayerView").finish_non_exhaustive()
266    }
267}
268
269impl StatelessWidget for PlayerView {
270    fn key(&self) -> Option<&KeyRef> {
271        self.key.as_ref()
272    }
273
274    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
275        PlayerPicture {
276            player: self.player.clone(),
277            overlay: subtitles_of(self.player.clone()),
278        }
279        .into_widget()
280    }
281}
282
283/// `player`'s video on a composition layer of the widget's own, laid out at the video's size in
284/// logical pixels, as large as the constraints let it be at that aspect, with `overlay` over the
285/// video's rectangle, as Media3's content frame holds its subtitle view over the surface.
286struct PlayerPicture {
287    player: Ref<Player>,
288    overlay: WidgetRef,
289}
290
291impl fmt::Debug for PlayerPicture {
292    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
293        f.debug_struct("PlayerPicture").finish_non_exhaustive()
294    }
295}
296
297impl StatefulWidget for PlayerPicture {
298    type State = PlayerPictureState;
299
300    fn create_state(&self) -> PlayerPictureState {
301        PlayerPictureState {
302            state: StateData::new(),
303            layer: None,
304        }
305    }
306}
307
308struct PlayerPictureState {
309    state: StateData<PlayerPicture>,
310    /// The layer the player shows on, made as the widget is mounted; `None` where the host has
311    /// no compositor.
312    layer: Option<Arc<dyn CompositionLayer>>,
313}
314
315impl PlayerPictureState {
316    fn player_changed(self: Handle<Self>, app: &mut App) {
317        self.set_state(app, |_| {});
318    }
319
320    /// Puts `player`'s video on the widget's layer.
321    fn show(self: Handle<Self>, app: &mut App, player: Handle<Player>) {
322        if let Some(layer) = app.get(self).layer.clone() {
323            player.set_video_layer(app, Some(layer));
324        }
325    }
326
327    /// Sends `player`'s video nowhere, if it is still on this widget's layer: a later view may
328    /// have taken the player since.
329    fn release(self: Handle<Self>, app: &mut App, player: Handle<Player>) {
330        let Some(ours) = &app.get(self).layer else {
331            return;
332        };
333        let still_ours = player
334            .video_layer(app)
335            .is_some_and(|shown| Arc::ptr_eq(shown, ours));
336        if still_ours {
337            player.set_video_layer(app, None);
338        }
339    }
340}
341
342impl State for PlayerPictureState {
343    type Widget = PlayerPicture;
344    crate::state_accessors!();
345
346    fn init_state(self: Handle<Self>, app: &mut App) {
347        let player = self.widget(app).player.handle();
348        player.add_listener(app, Listener::handle_method(self, Self::player_changed));
349        let layer = app
350            .platform()
351            .compositor()
352            .map(|compositor| compositor.make_layer(false));
353        app.get_mut(self).layer = layer;
354        self.show(app, player);
355    }
356
357    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &PlayerPicture) {
358        let player = self.widget(app).player.handle();
359        if player == old_widget.player {
360            return;
361        }
362        let listener = Listener::handle_method(self, Self::player_changed);
363        old_widget.player.remove_listener(app, &listener);
364        player.add_listener(app, listener);
365        self.release(app, old_widget.player.handle());
366        self.show(app, player);
367    }
368
369    fn dispose(self: Handle<Self>, app: &mut App) {
370        let player = self.widget(app).player.handle();
371        self.release(app, player);
372        player.remove_listener(app, &Listener::handle_method(self, Self::player_changed));
373    }
374
375    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
376        let player = self.widget(app).player.handle();
377        let Some(size) = player.state(app).size else {
378            return SizedBox::shrink().into_widget();
379        };
380        let video = match app.get(self).layer.clone() {
381            Some(layer) => CompositionLayerView::new(layer).into_widget(),
382            None => SizedBox::expand().into_widget(),
383        };
384        let overlay = self.widget(app).overlay.clone();
385        at_size(size, with_overlay(video, overlay))
386    }
387}
388
389/// `video` with `overlay` filling its rectangle above it.
390fn with_overlay(video: WidgetRef, overlay: WidgetRef) -> WidgetRef {
391    Stack::new()
392        .alignment(AlignmentGeometry::TOP_LEFT)
393        .children([video, Positioned::fill(overlay).into_widget()])
394        .into_widget()
395}
396
397/// A [`SubtitleView`] of `player`'s cues, built again each time they change: Media3's
398/// `PlayerView` setting its subtitle view's cues at each `onCues`.
399fn subtitles_of(player: Ref<Player>) -> WidgetRef {
400    let listenable: Rc<dyn Listenable> = Rc::new(player.clone());
401    ListenableBuilder::new(listenable, move |app, _, _| {
402        SubtitleView::new(Player::cues(player.handle(), app).to_vec()).into_widget()
403    })
404    .into_widget()
405}
406
407#[cfg(test)]
408mod tests {
409    use std::path::PathBuf;
410    use std::time::Duration;
411
412    use waft_embedder::{
413        CueContent, CueTextRun, EncodedImage, MediaTrack, MediaTrackKind, PickedFile, PlayerStatus,
414        Size, TargetPlatform,
415    };
416    use waft_foundation::AppCell;
417    use waft_test::{
418        MockCompositor, MockLayer, MockPlayers, MockVideoFrameReaders, PlayerCall, TestPlatform,
419        TestView, VideoOutputKind,
420    };
421
422    use super::*;
423    use crate::testing::WidgetTester;
424
425    fn app_with(
426        players: &MockPlayers,
427        compositor: &MockCompositor,
428        view: &Rc<TestView>,
429    ) -> Rc<AppCell> {
430        let platform = platform_with(players, compositor)
431            .on(TargetPlatform::MacOS)
432            .with_view(Rc::clone(view) as waft_embedder::ViewRef);
433        AppCell::with_platform(Rc::new(platform))
434    }
435
436    /// A platform with `players`, compositing through `compositor`.
437    fn platform_with(players: &MockPlayers, compositor: &MockCompositor) -> TestPlatform {
438        TestPlatform::new()
439            .with_players(Rc::new(players.clone()))
440            .with_compositor(Arc::new(compositor.clone()))
441    }
442
443    fn ready(size: Size) -> PlayerState {
444        PlayerState {
445            status: PlayerStatus::Ready,
446            size: Some(size),
447            duration: Some(Duration::from_secs(10)),
448            ..PlayerState::loading()
449        }
450    }
451
452    #[test]
453    fn a_player_opens_its_source_and_its_listeners_hear_its_state_change() {
454        let players = MockPlayers::new();
455        let cell = app_with(
456            &players,
457            &MockCompositor::new(),
458            &Rc::new(TestView::new(800.0, 600.0)),
459        );
460        // A rootless path gains the current drive on Windows, as `std::path::absolute` then
461        // answers, so the URL carries it.
462        let (path, url) = if cfg!(windows) {
463            (
464                PathBuf::from(r"C:\movies\a b.mov"),
465                "file:///C:/movies/a%20b.mov",
466            )
467        } else {
468            (PathBuf::from("/movies/a b.mov"), "file:///movies/a%20b.mov")
469        };
470        let picked = PickedFile::Path(path);
471        let player = Player::new(&mut cell.borrow_mut(), &picked.url()).unwrap();
472        let opened = players.opened();
473        assert_eq!(opened[0].url(), url);
474        assert_eq!(player.state(&cell.borrow()).status, PlayerStatus::Loading);
475
476        let heard = Rc::new(std::cell::Cell::new(0));
477        {
478            let heard = Rc::clone(&heard);
479            let listenable: Rc<dyn waft_foundation::Listenable> = Rc::new(player.clone());
480            listenable.add_listener(
481                &mut cell.borrow_mut(),
482                waft_foundation::Listener::new(move |_app| heard.set(heard.get() + 1)),
483            );
484        }
485        opened[0].set_state(ready(Size::new(640.0, 360.0)));
486        cell.checkpoint();
487        assert_eq!(heard.get(), 1);
488        assert_eq!(
489            player.state(&cell.borrow()).size,
490            Some(Size::new(640.0, 360.0))
491        );
492
493        player.play(&cell.borrow());
494        player.seek_to(&cell.borrow(), Duration::from_secs(3), SeekTolerance::EXACT);
495        player.set_muted(&cell.borrow(), true);
496        player.set_looping(&cell.borrow(), true);
497        assert_eq!(
498            opened[0].calls(),
499            vec![
500                PlayerCall::Play,
501                PlayerCall::Seek(Duration::from_secs(3), SeekTolerance::EXACT),
502                PlayerCall::SetMuted(true),
503                PlayerCall::SetLooping(true)
504            ]
505        );
506
507        player.dispose(&mut cell.borrow_mut());
508        assert!(
509            opened[0].is_dropped(),
510            "disposing lets go of the host's player"
511        );
512        opened[0].set_state(ready(Size::new(1.0, 1.0)));
513        cell.checkpoint();
514        assert_eq!(
515            heard.get(),
516            1,
517            "a disposed player's listeners hear nothing more"
518        );
519    }
520
521    #[test]
522    fn a_player_reads_its_position_from_its_host_and_its_listeners_hear_it_jump() {
523        let players = MockPlayers::new();
524        let cell = app_with(
525            &players,
526            &MockCompositor::new(),
527            &Rc::new(TestView::new(800.0, 600.0)),
528        );
529        let player = Player::new(&mut cell.borrow_mut(), "https://example.com/a.mp4").unwrap();
530        let host = &players.opened()[0];
531        let heard = Rc::new(std::cell::Cell::new(0));
532        {
533            let heard = Rc::clone(&heard);
534            let listenable: Rc<dyn waft_foundation::Listenable> = Rc::new(player.clone());
535            listenable.add_listener(
536                &mut cell.borrow_mut(),
537                waft_foundation::Listener::new(move |_app| heard.set(heard.get() + 1)),
538            );
539        }
540        assert_eq!(player.position(&cell.borrow()), Duration::ZERO);
541
542        host.move_to(Duration::from_millis(1500));
543        cell.checkpoint();
544        assert_eq!(
545            player.position(&cell.borrow()),
546            Duration::from_millis(1500),
547            "read from the host as it moves on"
548        );
549        assert_eq!(heard.get(), 0, "moving on is not told");
550
551        host.jump_to(Duration::from_secs(7));
552        cell.checkpoint();
553        assert_eq!(player.position(&cell.borrow()), Duration::from_secs(7));
554        assert_eq!(heard.get(), 1, "a jump is heard");
555    }
556
557    #[test]
558    fn a_player_hears_its_tracks_metadata_and_cues_and_asks_its_host_to_select_tracks() {
559        let players = MockPlayers::new();
560        let cell = app_with(
561            &players,
562            &MockCompositor::new(),
563            &Rc::new(TestView::new(800.0, 600.0)),
564        );
565        let player = Player::new(&mut cell.borrow_mut(), "https://example.com/a.m3u8").unwrap();
566        let host = &players.opened()[0];
567        let heard = Rc::new(std::cell::Cell::new(0));
568        {
569            let heard = Rc::clone(&heard);
570            let listenable: Rc<dyn waft_foundation::Listenable> = Rc::new(player.clone());
571            listenable.add_listener(
572                &mut cell.borrow_mut(),
573                waft_foundation::Listener::new(move |_app| heard.set(heard.get() + 1)),
574            );
575        }
576
577        let english = MediaTrack {
578            id: "legible:0".to_owned(),
579            kind: MediaTrackKind::Text,
580            language: "en".to_owned(),
581            label: "English".to_owned(),
582            selected: false,
583        };
584        host.set_state(PlayerState {
585            tracks: vec![english.clone()],
586            ..ready(Size::new(640.0, 360.0))
587        });
588        cell.checkpoint();
589        assert_eq!(player.state(&cell.borrow()).tracks, vec![english]);
590
591        player.select_text_track(&cell.borrow(), Some("legible:0"));
592        player.select_audio_track(&cell.borrow(), "audible:1");
593        assert_eq!(
594            host.calls(),
595            vec![
596                PlayerCall::SelectTextTrack(Some("legible:0".to_owned())),
597                PlayerCall::SelectAudioTrack("audible:1".to_owned()),
598            ]
599        );
600
601        let metadata = MediaMetadata {
602            title: Some("Bip Bop".to_owned()),
603            artwork: Some(EncodedImage {
604                mime_type: "image/png".to_owned(),
605                data: Arc::from([0x89, b'P', b'N', b'G'].as_slice()),
606            }),
607            ..MediaMetadata::default()
608        };
609        host.set_metadata(metadata.clone());
610        cell.checkpoint();
611        assert_eq!(player.metadata(&cell.borrow()), &metadata);
612
613        let cues = vec![Cue::new(CueContent::Text(vec![CueTextRun::new("Hello")]))];
614        host.set_cues(cues.clone());
615        cell.checkpoint();
616        assert_eq!(player.cues(&cell.borrow()), cues.as_slice());
617        assert_eq!(heard.get(), 3, "each change heard once");
618    }
619
620    #[test]
621    fn a_player_view_draws_its_players_cues_over_the_video() {
622        let players = MockPlayers::new();
623        let tester =
624            &mut WidgetTester::with_platform(platform_with(&players, &MockCompositor::new()));
625        let player = tester
626            .update(|app| Player::new(app, "https://example.com/a.mp4"))
627            .unwrap();
628        let host = &players.opened()[0];
629        tester.pump_widget(PlayerView::new(player));
630        host.set_state(ready(Size::new(320.0, 180.0)));
631        tester.cell.checkpoint();
632        tester.pump();
633        assert!(glyph_runs(tester).is_empty(), "no cues, no text");
634
635        host.set_cues(vec![Cue::new(CueContent::Text(vec![CueTextRun::new(
636            "Hello",
637        )]))]);
638        tester.cell.checkpoint();
639        tester.pump();
640        assert!(!glyph_runs(tester).is_empty(), "the cue's text is drawn");
641
642        host.set_cues(Vec::new());
643        tester.cell.checkpoint();
644        tester.pump();
645        assert!(glyph_runs(tester).is_empty(), "a cue gone is drawn no more");
646    }
647
648    #[test]
649    fn a_platform_without_players_gives_no_player() {
650        let cell = AppCell::with_platform(Rc::new(TestPlatform::new()));
651        let player = Player::new(&mut cell.borrow_mut(), "https://example.com/a.mp4");
652        assert!(player.is_none());
653    }
654
655    #[test]
656    fn a_player_view_shows_its_player_on_a_layer_it_places_at_the_videos_size() {
657        let players = MockPlayers::new();
658        let compositor = MockCompositor::new();
659        let tester = &mut WidgetTester::with_platform(platform_with(&players, &compositor));
660        let player = tester
661            .update(|app| Player::new(app, "https://example.com/a.mp4"))
662            .unwrap();
663        tester.pump_widget(crate::Center::new().child(PlayerView::new(player)));
664
665        let made = compositor.made();
666        assert_eq!(made.len(), 1, "one layer, of the view's own");
667        assert!(!made[0].opaque());
668        let video_layer = players.opened()[0]
669            .video_layer()
670            .expect("put on the view's layer");
671        assert!(
672            MockLayer::of(&*video_layer).is_some_and(|layer| std::ptr::eq(layer, &*made[0])),
673            "the layer the compositor made"
674        );
675        assert_eq!(
676            placements(tester).len(),
677            0,
678            "nothing placed until the size is known"
679        );
680
681        players.opened()[0].set_state(ready(Size::new(320.0, 180.0)));
682        tester.cell.checkpoint();
683        tester.pump();
684        let placements = placements(tester);
685        assert_eq!(placements.len(), 1);
686        let (placed, placement) = &placements[0];
687        assert!(MockLayer::of(&**placed).is_some_and(|layer| std::ptr::eq(layer, &*made[0])));
688        assert_eq!(
689            placement.bounds(),
690            waft_embedder::Rect::from_ltwh(720.0, 630.0, 960.0, 540.0),
691            "the logical 320x180 at the centre of the view, in physical pixels"
692        );
693    }
694
695    #[test]
696    fn a_player_view_puts_its_player_nowhere_as_it_goes_unless_another_took_it_since() {
697        let players = MockPlayers::new();
698        let tester =
699            &mut WidgetTester::with_platform(platform_with(&players, &MockCompositor::new()));
700        let player = tester
701            .update(|app| Player::new(app, "https://example.com/a.mp4"))
702            .unwrap();
703        let host = &players.opened()[0];
704        tester.pump_widget(PlayerView::new(player.clone()));
705        assert!(host.video_layer().is_some());
706        tester.pump_widget(crate::SizedBox::new());
707        assert!(
708            host.video_layer().is_none(),
709            "unmounted, it puts the video nowhere"
710        );
711        assert_eq!(host.calls().last(), Some(&PlayerCall::SetVideoOutput(None)));
712
713        tester.pump_widget(PlayerView::new(player.clone()));
714        let elsewhere = waft_embedder::test_support::idle_layer();
715        tester.update(|app| {
716            player.set_video_output(app, Some(VideoOutput::Layer(Arc::clone(&elsewhere))))
717        });
718        tester.pump_widget(crate::SizedBox::new());
719        assert!(
720            host.video_layer()
721                .is_some_and(|layer| Arc::ptr_eq(&layer, &elsewhere)),
722            "a view leaves alone a layer it did not set"
723        );
724    }
725
726    #[test]
727    fn a_reader_the_app_made_takes_the_video_from_a_view_which_leaves_it_alone() {
728        let players = MockPlayers::new();
729        let readers = MockVideoFrameReaders::new();
730        let tester = &mut WidgetTester::with_platform(
731            platform_with(&players, &MockCompositor::new())
732                .with_video_frame_readers(Rc::new(readers.clone())),
733        );
734        let player = tester
735            .update(|app| Player::new(app, "https://example.com/a.mp4"))
736            .unwrap();
737        let host = &players.opened()[0];
738        tester.pump_widget(PlayerView::new(player.clone()));
739
740        let reader = tester.update(|app| {
741            app.platform()
742                .video_frame_readers()
743                .expect("the platform's readers")
744                .make_reader()
745        });
746        assert!(Arc::ptr_eq(&reader, &readers.made()[0]));
747        tester.update(|app| {
748            player.set_video_output(app, Some(VideoOutput::Frames(Arc::clone(&reader))))
749        });
750        assert_eq!(
751            host.calls().last(),
752            Some(&PlayerCall::SetVideoOutput(Some(VideoOutputKind::Frames)))
753        );
754        assert!(host.video_layer().is_none(), "one destination at a time");
755
756        tester.pump_widget(crate::VideoFrameView::new(Arc::clone(&reader)));
757        assert!(
758            host.frame_reader()
759                .is_some_and(|read_by| Arc::ptr_eq(&read_by, &reader)),
760            "an unmounted view leaves alone a reader it did not set"
761        );
762    }
763
764    /// The glyph runs the tester's view last drew.
765    fn glyph_runs(tester: &WidgetTester) -> Vec<waft_embedder::valo::Op> {
766        let scene = tester.view().last_scene().expect("a frame was presented");
767        waft_embedder::flattened_ops(&waft_embedder::slices(&scene, |_| None).picture_with_room())
768            .into_iter()
769            .filter(|op| matches!(op, waft_embedder::valo::Op::GlyphRun { .. }))
770            .collect()
771    }
772
773    /// The composition layers the tester's view last placed, with their placements.
774    fn placements(
775        tester: &WidgetTester,
776    ) -> Vec<(
777        Arc<dyn waft_embedder::CompositionLayer>,
778        waft_embedder::Placement,
779    )> {
780        let scene = tester.view().last_scene().expect("a frame was presented");
781        waft_embedder::slices(&scene, |_| None)
782            .composition_layers()
783            .map(|(layer, placement)| (Arc::clone(layer), placement.clone()))
784            .collect()
785    }
786}