script/dom/html/
htmlvideoelement.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::cell::Cell;
6use std::sync::Arc;
7
8use dom_struct::dom_struct;
9use euclid::default::Size2D;
10use html5ever::{LocalName, Prefix, local_name, ns};
11use js::rust::HandleObject;
12use layout_api::{HTMLMediaData, MediaMetadata};
13use net_traits::image_cache::{
14    ImageCache, ImageCacheResult, ImageLoadListener, ImageOrMetadataAvailable, ImageResponse,
15    PendingImageId,
16};
17use net_traits::request::{CredentialsMode, Destination, RequestBuilder, RequestId};
18use net_traits::{
19    CoreResourceThread, FetchMetadata, FetchResponseMsg, NetworkError, ResourceFetchTiming,
20};
21use pixels::{Snapshot, SnapshotAlphaMode, SnapshotPixelFormat};
22use script_bindings::script_runtime::temp_cx;
23use servo_media::player::video::VideoFrame;
24use servo_url::ServoUrl;
25use style::attr::{AttrValue, LengthOrPercentageOrAuto};
26
27use crate::document_loader::{LoadBlocker, LoadType};
28use crate::dom::attr::Attr;
29use crate::dom::bindings::cell::DomRefCell;
30use crate::dom::bindings::codegen::Bindings::HTMLVideoElementBinding::HTMLVideoElementMethods;
31use crate::dom::bindings::inheritance::Castable;
32use crate::dom::bindings::refcounted::Trusted;
33use crate::dom::bindings::reflector::DomGlobal;
34use crate::dom::bindings::root::{DomRoot, LayoutDom};
35use crate::dom::bindings::str::DOMString;
36use crate::dom::csp::{GlobalCspReporting, Violation};
37use crate::dom::document::Document;
38use crate::dom::element::{AttributeMutation, Element, LayoutElementHelpers};
39use crate::dom::globalscope::GlobalScope;
40use crate::dom::html::htmlmediaelement::{HTMLMediaElement, NetworkState, ReadyState};
41use crate::dom::node::{Node, NodeDamage, NodeTraits};
42use crate::dom::performance::performanceresourcetiming::InitiatorType;
43use crate::dom::virtualmethods::VirtualMethods;
44use crate::fetch::{FetchCanceller, RequestWithGlobalScope};
45use crate::network_listener::{self, FetchResponseListener, ResourceTimingListener};
46use crate::script_runtime::CanGc;
47
48#[dom_struct]
49pub(crate) struct HTMLVideoElement {
50    htmlmediaelement: HTMLMediaElement,
51    /// <https://html.spec.whatwg.org/multipage/#dom-video-videowidth>
52    video_width: Cell<Option<u32>>,
53    /// <https://html.spec.whatwg.org/multipage/#dom-video-videoheight>
54    video_height: Cell<Option<u32>>,
55    /// Incremented whenever tasks associated with this element are cancelled.
56    generation_id: Cell<u32>,
57    /// Load event blocker. Will block the load event while the poster frame
58    /// is being fetched.
59    load_blocker: DomRefCell<Option<LoadBlocker>>,
60    /// A copy of the last frame
61    #[ignore_malloc_size_of = "VideoFrame"]
62    #[no_trace]
63    last_frame: DomRefCell<Option<VideoFrame>>,
64}
65
66impl HTMLVideoElement {
67    fn new_inherited(
68        local_name: LocalName,
69        prefix: Option<Prefix>,
70        document: &Document,
71    ) -> HTMLVideoElement {
72        HTMLVideoElement {
73            htmlmediaelement: HTMLMediaElement::new_inherited(local_name, prefix, document),
74            video_width: Cell::new(None),
75            video_height: Cell::new(None),
76            generation_id: Cell::new(0),
77            load_blocker: Default::default(),
78            last_frame: Default::default(),
79        }
80    }
81
82    pub(crate) fn new(
83        local_name: LocalName,
84        prefix: Option<Prefix>,
85        document: &Document,
86        proto: Option<HandleObject>,
87        can_gc: CanGc,
88    ) -> DomRoot<HTMLVideoElement> {
89        Node::reflect_node_with_proto(
90            Box::new(HTMLVideoElement::new_inherited(
91                local_name, prefix, document,
92            )),
93            document,
94            proto,
95            can_gc,
96        )
97    }
98
99    pub(crate) fn get_video_width(&self) -> Option<u32> {
100        self.video_width.get()
101    }
102
103    pub(crate) fn get_video_height(&self) -> Option<u32> {
104        self.video_height.get()
105    }
106
107    pub(crate) fn set_natural_dimensions(&self, width: Option<u32>, height: Option<u32>) -> bool {
108        if self.video_width.get() == width && self.video_height.get() == height {
109            return false;
110        }
111
112        self.video_width.set(width);
113        self.video_height.set(height);
114
115        self.upcast::<Node>().dirty(NodeDamage::Other);
116        true
117    }
118
119    /// Gets the copy of the video frame at the current playback position,
120    /// if that is available, or else (e.g. when the video is seeking or buffering)
121    /// its previous appearance, if any.
122    pub(crate) fn get_current_frame_data(&self) -> Option<Snapshot> {
123        let frame = self.htmlmediaelement.get_current_frame();
124        if frame.is_some() {
125            *self.last_frame.borrow_mut() = frame;
126        }
127
128        match self.last_frame.borrow().as_ref() {
129            Some(frame) => {
130                let size = Size2D::new(frame.get_width() as u32, frame.get_height() as u32);
131                if !frame.is_gl_texture() {
132                    let alpha_mode = SnapshotAlphaMode::Transparent {
133                        premultiplied: false,
134                    };
135
136                    Some(Snapshot::from_vec(
137                        size.cast(),
138                        SnapshotPixelFormat::BGRA,
139                        alpha_mode,
140                        frame.get_data().to_vec(),
141                    ))
142                } else {
143                    // XXX(victor): here we only have the GL texture ID.
144                    Some(Snapshot::cleared(size.cast()))
145                }
146            },
147            None => None,
148        }
149    }
150
151    /// <https://html.spec.whatwg.org/multipage/#poster-frame>
152    fn update_poster_frame(&self, poster_url: Option<&str>, cx: &mut js::context::JSContext) {
153        // Step 1. If there is an existing instance of this algorithm running
154        // for this video element, abort that instance of this algorithm without
155        // changing the poster frame.
156        self.generation_id.set(self.generation_id.get() + 1);
157
158        // Step 2. If the poster attribute's value is the empty string or
159        // if the attribute is absent, then there is no poster frame; return.
160        let Some(poster_url) = poster_url.filter(|poster_url| !poster_url.is_empty()) else {
161            self.htmlmediaelement.set_poster_frame(None);
162            return;
163        };
164
165        // Step 3. Let url be the result of encoding-parsing a URL given
166        // the poster attribute's value, relative to the element's node
167        // document.
168        // Step 4. If url is failure, then return. There is no poster frame.
169        let poster_url = match self.owner_document().encoding_parse_a_url(poster_url) {
170            Ok(url) => url,
171            Err(_) => {
172                self.htmlmediaelement.set_poster_frame(None);
173                return;
174            },
175        };
176
177        // We use the image cache for poster frames so we save as much
178        // network activity as possible.
179        let window = self.owner_window();
180        let image_cache = window.image_cache();
181        let cache_result = image_cache.get_cached_image_status(
182            poster_url.clone(),
183            window.origin().immutable().clone(),
184            None,
185        );
186
187        let id = match cache_result {
188            ImageCacheResult::Available(ImageOrMetadataAvailable::ImageAvailable {
189                image,
190                url,
191                ..
192            }) => {
193                self.process_image_response(ImageResponse::Loaded(image, url), cx);
194                return;
195            },
196            ImageCacheResult::Available(ImageOrMetadataAvailable::MetadataAvailable(_, id)) => id,
197            ImageCacheResult::ReadyForRequest(id) => {
198                self.do_fetch_poster_frame(poster_url, id, cx);
199                id
200            },
201            ImageCacheResult::FailedToLoadOrDecode => {
202                self.process_image_response(ImageResponse::FailedToLoadOrDecode, cx);
203                return;
204            },
205            ImageCacheResult::Pending(id) => id,
206        };
207
208        let trusted_node = Trusted::new(self);
209        let generation = self.generation_id();
210        let callback = window.register_image_cache_listener(id, move |response, cx| {
211            let element = trusted_node.root();
212
213            // Ignore any image response for a previous request that has been discarded.
214            if generation != element.generation_id() {
215                return;
216            }
217            element.process_image_response(response.response, cx);
218        });
219
220        image_cache.add_listener(ImageLoadListener::new(callback, window.pipeline_id(), id));
221    }
222
223    /// <https://html.spec.whatwg.org/multipage/#poster-frame>
224    fn do_fetch_poster_frame(
225        &self,
226        poster_url: ServoUrl,
227        id: PendingImageId,
228        cx: &mut js::context::JSContext,
229    ) {
230        // Step 5. Let request be a new request whose URL is url, client is the element's node
231        // document's relevant settings object, destination is "image", initiator type is "video",
232        // credentials mode is "include", and whose use-URL-credentials flag is set.
233        let document = self.owner_document();
234        let global = self.owner_global();
235        let request = RequestBuilder::new(
236            Some(document.webview_id()),
237            poster_url.clone(),
238            global.get_referrer(),
239        )
240        .destination(Destination::Image)
241        .credentials_mode(CredentialsMode::Include)
242        .use_url_credentials(true)
243        .with_global_scope(&global);
244
245        // Step 6. Fetch request. This must delay the load event of the element's node document.
246        // This delay must be independent from the ones created by HTMLMediaElement during
247        // its media load algorithm, otherwise a code like
248        // <video poster="poster.png"></video>
249        // (which triggers no media load algorithm unless a explicit call to .load() is done)
250        // will block the document's load event forever.
251        let blocker = &self.load_blocker;
252        LoadBlocker::terminate(blocker, cx);
253        *blocker.borrow_mut() = Some(LoadBlocker::new(
254            &self.owner_document(),
255            LoadType::Image(poster_url.clone()),
256        ));
257
258        let context = PosterFrameFetchContext::new(
259            self,
260            poster_url,
261            id,
262            request.id,
263            self.global().core_resource_thread(),
264        );
265        self.owner_document().fetch_background(request, context);
266    }
267
268    fn generation_id(&self) -> u32 {
269        self.generation_id.get()
270    }
271
272    /// <https://html.spec.whatwg.org/multipage/#poster-frame>
273    fn process_image_response(&self, response: ImageResponse, cx: &mut js::context::JSContext) {
274        // Step 7. If an image is thus obtained, the poster frame is that image.
275        // Otherwise, there is no poster frame.
276        match response {
277            ImageResponse::Loaded(image, url) => {
278                debug!("Loaded poster image for video element: {:?}", url);
279                match image.as_raster_image() {
280                    Some(image) => self.htmlmediaelement.set_poster_frame(Some(image)),
281                    None => warn!("Vector images are not yet supported in video poster"),
282                }
283                LoadBlocker::terminate(&self.load_blocker, cx);
284            },
285            ImageResponse::MetadataLoaded(..) => {},
286            // The image cache may have loaded a placeholder for an invalid poster url
287            ImageResponse::FailedToLoadOrDecode => {
288                self.htmlmediaelement.set_poster_frame(None);
289                // A failed load should unblock the document load.
290                LoadBlocker::terminate(&self.load_blocker, cx);
291            },
292        }
293    }
294
295    /// <https://html.spec.whatwg.org/multipage/#check-the-usability-of-the-image-argument>
296    pub(crate) fn is_usable(&self) -> bool {
297        !matches!(
298            self.htmlmediaelement.get_ready_state(),
299            ReadyState::HaveNothing | ReadyState::HaveMetadata
300        )
301    }
302
303    pub(crate) fn origin_is_clean(&self) -> bool {
304        self.htmlmediaelement.origin_is_clean()
305    }
306
307    pub(crate) fn is_network_state_empty(&self) -> bool {
308        self.htmlmediaelement.network_state() == NetworkState::Empty
309    }
310}
311
312impl HTMLVideoElementMethods<crate::DomTypeHolder> for HTMLVideoElement {
313    // <https://html.spec.whatwg.org/multipage/#dom-video-width>
314    make_dimension_uint_getter!(Width, "width");
315
316    // <https://html.spec.whatwg.org/multipage/#dom-video-width>
317    make_dimension_uint_setter!(SetWidth, "width");
318
319    // <https://html.spec.whatwg.org/multipage/#dom-video-height>
320    make_dimension_uint_getter!(Height, "height");
321
322    // <https://html.spec.whatwg.org/multipage/#dom-video-height>
323    make_dimension_uint_setter!(SetHeight, "height");
324
325    /// <https://html.spec.whatwg.org/multipage/#dom-video-videowidth>
326    fn VideoWidth(&self) -> u32 {
327        if self.htmlmediaelement.get_ready_state() == ReadyState::HaveNothing {
328            return 0;
329        }
330        self.video_width.get().unwrap_or(0)
331    }
332
333    /// <https://html.spec.whatwg.org/multipage/#dom-video-videoheight>
334    fn VideoHeight(&self) -> u32 {
335        if self.htmlmediaelement.get_ready_state() == ReadyState::HaveNothing {
336            return 0;
337        }
338        self.video_height.get().unwrap_or(0)
339    }
340
341    // https://html.spec.whatwg.org/multipage/#dom-video-poster
342    make_getter!(Poster, "poster");
343
344    // https://html.spec.whatwg.org/multipage/#dom-video-poster
345    make_setter!(SetPoster, "poster");
346
347    // For testing purposes only. This is not an event from
348    // https://html.spec.whatwg.org/multipage/#dom-video-poster
349    event_handler!(postershown, GetOnpostershown, SetOnpostershown);
350}
351
352impl VirtualMethods for HTMLVideoElement {
353    fn super_type(&self) -> Option<&dyn VirtualMethods> {
354        Some(self.upcast::<HTMLMediaElement>() as &dyn VirtualMethods)
355    }
356
357    #[expect(unsafe_code)]
358    fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation, _can_gc: CanGc) {
359        // TODO: https://github.com/servo/servo/issues/42812
360        let mut cx = unsafe { temp_cx() };
361        let cx = &mut cx;
362        self.super_type()
363            .unwrap()
364            .attribute_mutated(attr, mutation, CanGc::from_cx(cx));
365
366        if attr.local_name() == &local_name!("poster") {
367            if let Some(new_value) = mutation.new_value(attr) {
368                self.update_poster_frame(Some(&new_value), cx)
369            } else {
370                self.update_poster_frame(None, cx)
371            }
372        };
373    }
374
375    fn attribute_affects_presentational_hints(&self, attr: &Attr) -> bool {
376        match attr.local_name() {
377            &local_name!("width") | &local_name!("height") => true,
378            _ => self
379                .super_type()
380                .unwrap()
381                .attribute_affects_presentational_hints(attr),
382        }
383    }
384
385    fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
386        match name {
387            &local_name!("width") | &local_name!("height") => {
388                AttrValue::from_dimension(value.into())
389            },
390            _ => self
391                .super_type()
392                .unwrap()
393                .parse_plain_attribute(name, value),
394        }
395    }
396}
397
398struct PosterFrameFetchContext {
399    /// Reference to the script thread image cache.
400    image_cache: Arc<dyn ImageCache>,
401    /// The element that initiated the request.
402    elem: Trusted<HTMLVideoElement>,
403    /// The cache ID for this request.
404    id: PendingImageId,
405    /// True if this response is invalid and should be ignored.
406    cancelled: bool,
407    /// Url for the resource
408    url: ServoUrl,
409    /// A [`FetchCanceller`] for this request.
410    fetch_canceller: FetchCanceller,
411}
412
413impl FetchResponseListener for PosterFrameFetchContext {
414    fn process_request_body(&mut self, _: RequestId) {}
415
416    fn process_request_eof(&mut self, _: RequestId) {
417        self.fetch_canceller.ignore()
418    }
419
420    fn process_response(
421        &mut self,
422        request_id: RequestId,
423        metadata: Result<FetchMetadata, NetworkError>,
424    ) {
425        self.image_cache.notify_pending_response(
426            self.id,
427            FetchResponseMsg::ProcessResponse(request_id, metadata.clone()),
428        );
429
430        let metadata = metadata.ok().map(|meta| match meta {
431            FetchMetadata::Unfiltered(m) => m,
432            FetchMetadata::Filtered { unsafe_, .. } => unsafe_,
433        });
434
435        let status_is_ok = metadata
436            .as_ref()
437            .map_or(true, |m| m.status.in_range(200..300));
438
439        if !status_is_ok {
440            self.cancelled = true;
441            self.fetch_canceller.abort();
442        }
443    }
444
445    fn process_response_chunk(&mut self, request_id: RequestId, payload: Vec<u8>) {
446        if self.cancelled {
447            // An error was received previously, skip processing the payload.
448            return;
449        }
450
451        self.image_cache.notify_pending_response(
452            self.id,
453            FetchResponseMsg::ProcessResponseChunk(request_id, payload.into()),
454        );
455    }
456
457    fn process_response_eof(
458        self,
459        cx: &mut js::context::JSContext,
460        request_id: RequestId,
461        response: Result<(), NetworkError>,
462        timing: ResourceFetchTiming,
463    ) {
464        self.image_cache.notify_pending_response(
465            self.id,
466            FetchResponseMsg::ProcessResponseEOF(request_id, response.clone(), timing.clone()),
467        );
468        network_listener::submit_timing(&self, &response, &timing, CanGc::from_cx(cx));
469    }
470
471    fn process_csp_violations(&mut self, _request_id: RequestId, violations: Vec<Violation>) {
472        let global = &self.resource_timing_global();
473        global.report_csp_violations(violations, None, None);
474    }
475}
476
477impl ResourceTimingListener for PosterFrameFetchContext {
478    fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
479        let initiator_type = InitiatorType::LocalName(
480            self.elem
481                .root()
482                .upcast::<Element>()
483                .local_name()
484                .to_string(),
485        );
486        (initiator_type, self.url.clone())
487    }
488
489    fn resource_timing_global(&self) -> DomRoot<GlobalScope> {
490        self.elem.root().owner_document().global()
491    }
492}
493
494impl PosterFrameFetchContext {
495    fn new(
496        elem: &HTMLVideoElement,
497        url: ServoUrl,
498        id: PendingImageId,
499        request_id: RequestId,
500        core_resource_thread: CoreResourceThread,
501    ) -> PosterFrameFetchContext {
502        let window = elem.owner_window();
503        PosterFrameFetchContext {
504            image_cache: window.image_cache(),
505            elem: Trusted::new(elem),
506            id,
507            cancelled: false,
508            url,
509            fetch_canceller: FetchCanceller::new(request_id, false, core_resource_thread),
510        }
511    }
512}
513
514pub(crate) trait LayoutHTMLVideoElementHelpers {
515    fn data(self) -> HTMLMediaData;
516    fn get_width(self) -> LengthOrPercentageOrAuto;
517    fn get_height(self) -> LengthOrPercentageOrAuto;
518}
519
520impl LayoutHTMLVideoElementHelpers for LayoutDom<'_, HTMLVideoElement> {
521    fn data(self) -> HTMLMediaData {
522        let video = self.unsafe_get();
523
524        // Get the current frame being rendered.
525        let current_frame = video.htmlmediaelement.get_current_frame_to_present();
526
527        // This value represents the natural width and height of the video.
528        // It may exist even if there is no current frame (for example, after the
529        // metadata of the video is loaded).
530        let metadata = video
531            .get_video_width()
532            .zip(video.get_video_height())
533            .map(|(width, height)| MediaMetadata { width, height });
534
535        HTMLMediaData {
536            current_frame,
537            metadata,
538        }
539    }
540
541    fn get_width(self) -> LengthOrPercentageOrAuto {
542        self.upcast::<Element>()
543            .get_attr_for_layout(&ns!(), &local_name!("width"))
544            .map(AttrValue::as_dimension)
545            .cloned()
546            .unwrap_or(LengthOrPercentageOrAuto::Auto)
547    }
548
549    fn get_height(self) -> LengthOrPercentageOrAuto {
550        self.upcast::<Element>()
551            .get_attr_for_layout(&ns!(), &local_name!("height"))
552            .map(AttrValue::as_dimension)
553            .cloned()
554            .unwrap_or(LengthOrPercentageOrAuto::Auto)
555    }
556}