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