Skip to main content

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