Skip to main content

waft_widgets/widgets/
video_frame_view.rs

1//! A video's frames drawn in the widget tree: Android's `TextureView` beside `SurfaceView`,
2//! Flutter's `Texture`, over [`RenderVideoFrameView`].
3//!
4//! The framework draws the frames as part of its picture, so they clip, turn, fade and take
5//! effects like anything painted, where a `PlayerView` has the system show a player on a
6//! composition layer of its own. Pick this one for what a layer cannot take, glass over the video,
7//! a fade into what is painted beneath it, a shader, or on a host with no compositor; the
8//! `PlayerView` otherwise, the cheaper way and the only one for protected and HDR video. The
9//! widget fills the box it is given; keeping the video's aspect is its parent's. The reader is the
10//! widget's to read: a reader is read by one consumer, and the host reads it when it draws.
11
12use std::fmt::{self, Debug};
13use std::sync::Arc;
14
15use waft_embedder::VideoFrameReader;
16use waft_foundation::App;
17use waft_rendering::{AnyRenderObject, RenderBox, RenderHandle, RenderVideoFrameView};
18
19use crate::framework::{BuildContext, KeyRef, LeafRenderObjectWidget, RenderObjectWidget};
20
21/// Draws a video's newest frame where it is placed.
22#[derive(Clone)]
23pub struct VideoFrameView {
24    /// See [`Widget::key`](crate::Widget::key).
25    pub key: Option<KeyRef>,
26    /// The frames drawn: a reader the app made and gave a player or a camera session.
27    pub reader: Arc<dyn VideoFrameReader>,
28}
29
30impl VideoFrameView {
31    pub fn new(reader: Arc<dyn VideoFrameReader>) -> VideoFrameView {
32        VideoFrameView { key: None, reader }
33    }
34
35    pub fn key(mut self, key: KeyRef) -> VideoFrameView {
36        self.key = Some(key);
37        self
38    }
39}
40
41impl Debug for VideoFrameView {
42    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43        f.debug_struct("VideoFrameView")
44            .field("reader", &Arc::as_ptr(&self.reader).cast::<()>())
45            .finish()
46    }
47}
48
49impl RenderObjectWidget for VideoFrameView {
50    type RenderObject = RenderVideoFrameView;
51
52    fn key(&self) -> Option<&KeyRef> {
53        self.key.as_ref()
54    }
55
56    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
57        RenderVideoFrameView::new(app, Arc::clone(&self.reader)).as_object()
58    }
59
60    fn update_render_object(
61        &self,
62        app: &mut App,
63        _context: BuildContext,
64        render_object: RenderHandle<RenderVideoFrameView>,
65    ) {
66        render_object.set_reader(app, Arc::clone(&self.reader));
67    }
68}
69
70impl LeafRenderObjectWidget for VideoFrameView {}
71
72#[cfg(test)]
73mod tests {
74    use waft_embedder::{Layer, Rect, VideoFrame};
75
76    use super::*;
77    use crate::testing::test_widgets;
78
79    /// A reader with no frame yet.
80    struct NoFrames;
81
82    impl VideoFrameReader for NoFrames {
83        fn frame_for(&self, _display_time: std::time::Instant) -> Option<Arc<dyn VideoFrame>> {
84            None
85        }
86    }
87
88    /// The widget puts the reader itself in the frame's scene, at the box it fills, for the host
89    /// to take the frame from as it draws.
90    #[test]
91    fn a_video_frame_view_puts_its_reader_in_the_scene_at_its_box() {
92        test_widgets(|tester| {
93            let reader: Arc<dyn VideoFrameReader> = Arc::new(NoFrames);
94            tester.pump_widget(
95                crate::Center::new().child(
96                    crate::SizedBox::new()
97                        .width(320.0)
98                        .height(180.0)
99                        .child(VideoFrameView::new(Arc::clone(&reader))),
100                ),
101            );
102
103            let scene = tester.view().last_scene().expect("a frame was presented");
104            let shown = std::cell::RefCell::new(Vec::new());
105            waft_embedder::slices(&scene, |asked_for| {
106                shown.borrow_mut().push(Arc::clone(asked_for));
107                None
108            });
109            let shown = shown.into_inner();
110            assert_eq!(shown.len(), 1);
111            assert!(Arc::ptr_eq(&shown[0], &reader));
112            let video = find_video_frames(&scene.root.children).expect("the reader's layer");
113            assert_eq!(
114                video.rect.size(),
115                Rect::from_ltwh(0.0, 0.0, 320.0, 180.0).size()
116            );
117        });
118    }
119
120    fn find_video_frames(layers: &[Layer]) -> Option<waft_embedder::VideoLayer> {
121        layers.iter().find_map(|layer| match layer {
122            Layer::Video(video) => Some(video.clone()),
123            Layer::Container(container) => find_video_frames(&container.children),
124            _ => None,
125        })
126    }
127}