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::blob_url_store::UrlWithBlobClaim;
14use net_traits::image_cache::{
15    ImageCache, ImageCacheResult, ImageLoadListener, ImageOrMetadataAvailable, ImageResponse,
16    PendingImageId,
17};
18use net_traits::request::{CredentialsMode, Destination, RequestBuilder, RequestId};
19use net_traits::{
20    CoreResourceThread, FetchMetadata, FetchResponseMsg, NetworkError, ResourceFetchTiming,
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, USVString};
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::url::ensure_blob_referenced_by_url_is_kept_alive;
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        cx: &mut js::context::JSContext,
84        local_name: LocalName,
85        prefix: Option<Prefix>,
86        document: &Document,
87        proto: Option<HandleObject>,
88    ) -> DomRoot<HTMLVideoElement> {
89        Node::reflect_node_with_proto(
90            cx,
91            Box::new(HTMLVideoElement::new_inherited(
92                local_name, prefix, document,
93            )),
94            document,
95            proto,
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 global = self.owner_global();
170        let poster_url = match self
171            .owner_document()
172            .encoding_parse_a_url(poster_url)
173            .map(|url| ensure_blob_referenced_by_url_is_kept_alive(&global, url))
174        {
175            Ok(url) => url,
176            Err(_) => {
177                self.htmlmediaelement.set_poster_frame(None);
178                return;
179            },
180        };
181
182        // We use the image cache for poster frames so we save as much
183        // network activity as possible.
184        let window = self.owner_window();
185        let image_cache = window.image_cache();
186        let cache_result = image_cache.get_cached_image_status(
187            poster_url.url(),
188            window.origin().immutable().clone(),
189            None,
190        );
191
192        let id = match cache_result {
193            ImageCacheResult::Available(ImageOrMetadataAvailable::ImageAvailable {
194                image,
195                url,
196                ..
197            }) => {
198                self.process_image_response(ImageResponse::Loaded(image, url), cx);
199                return;
200            },
201            ImageCacheResult::Available(ImageOrMetadataAvailable::MetadataAvailable(_, id)) => id,
202            ImageCacheResult::ReadyForRequest(id) => {
203                self.do_fetch_poster_frame(poster_url, id, cx);
204                id
205            },
206            ImageCacheResult::FailedToLoadOrDecode => {
207                self.process_image_response(ImageResponse::FailedToLoadOrDecode, cx);
208                return;
209            },
210            ImageCacheResult::Pending(id) => id,
211        };
212
213        let trusted_node = Trusted::new(self);
214        let generation = self.generation_id();
215        let callback = window.register_image_cache_listener(id, move |response, cx| {
216            let element = trusted_node.root();
217
218            // Ignore any image response for a previous request that has been discarded.
219            if generation != element.generation_id() {
220                return;
221            }
222            element.process_image_response(response.response, cx);
223        });
224
225        image_cache.add_listener(ImageLoadListener::new(callback, window.pipeline_id(), id));
226    }
227
228    /// <https://html.spec.whatwg.org/multipage/#poster-frame>
229    fn do_fetch_poster_frame(
230        &self,
231        poster_url: UrlWithBlobClaim,
232        id: PendingImageId,
233        cx: &mut js::context::JSContext,
234    ) {
235        // Step 5. Let request be a new request whose URL is url, client is the element's node
236        // document's relevant settings object, destination is "image", initiator type is "video",
237        // credentials mode is "include", and whose use-URL-credentials flag is set.
238        let document = self.owner_document();
239        let global = self.owner_global();
240        let request = RequestBuilder::new(
241            Some(document.webview_id()),
242            poster_url.clone(),
243            global.get_referrer(),
244        )
245        .destination(Destination::Image)
246        .credentials_mode(CredentialsMode::Include)
247        .use_url_credentials(true)
248        .with_global_scope(&global);
249
250        // Step 6. Fetch request. This must delay the load event of the element's node document.
251        // This delay must be independent from the ones created by HTMLMediaElement during
252        // its media load algorithm, otherwise a code like
253        // <video poster="poster.png"></video>
254        // (which triggers no media load algorithm unless a explicit call to .load() is done)
255        // will block the document's load event forever.
256        let blocker = &self.load_blocker;
257        LoadBlocker::terminate(blocker, cx);
258        *blocker.borrow_mut() = Some(LoadBlocker::new(
259            &self.owner_document(),
260            LoadType::Image(poster_url.url()),
261        ));
262
263        let context = PosterFrameFetchContext::new(
264            self,
265            poster_url.url(),
266            id,
267            request.id,
268            self.global().core_resource_thread(),
269        );
270        self.owner_document().fetch_background(request, context);
271    }
272
273    fn generation_id(&self) -> u32 {
274        self.generation_id.get()
275    }
276
277    /// <https://html.spec.whatwg.org/multipage/#poster-frame>
278    fn process_image_response(&self, response: ImageResponse, cx: &mut js::context::JSContext) {
279        // Step 7. If an image is thus obtained, the poster frame is that image.
280        // Otherwise, there is no poster frame.
281        match response {
282            ImageResponse::Loaded(image, url) => {
283                debug!("Loaded poster image for video element: {:?}", url);
284                match image.as_raster_image() {
285                    Some(image) => self.htmlmediaelement.set_poster_frame(Some(image)),
286                    None => warn!("Vector images are not yet supported in video poster"),
287                }
288                LoadBlocker::terminate(&self.load_blocker, cx);
289            },
290            ImageResponse::MetadataLoaded(..) => {},
291            // The image cache may have loaded a placeholder for an invalid poster url
292            ImageResponse::FailedToLoadOrDecode => {
293                self.htmlmediaelement.set_poster_frame(None);
294                // A failed load should unblock the document load.
295                LoadBlocker::terminate(&self.load_blocker, cx);
296            },
297        }
298    }
299
300    /// <https://html.spec.whatwg.org/multipage/#check-the-usability-of-the-image-argument>
301    pub(crate) fn is_usable(&self) -> bool {
302        !matches!(
303            self.htmlmediaelement.get_ready_state(),
304            ReadyState::HaveNothing | ReadyState::HaveMetadata
305        )
306    }
307
308    pub(crate) fn origin_is_clean(&self) -> bool {
309        self.htmlmediaelement.origin_is_clean()
310    }
311
312    pub(crate) fn is_network_state_empty(&self) -> bool {
313        self.htmlmediaelement.network_state() == NetworkState::Empty
314    }
315}
316
317impl HTMLVideoElementMethods<crate::DomTypeHolder> for HTMLVideoElement {
318    // <https://html.spec.whatwg.org/multipage/#dom-video-width>
319    make_dimension_uint_getter!(Width, "width");
320
321    // <https://html.spec.whatwg.org/multipage/#dom-video-width>
322    make_dimension_uint_setter!(SetWidth, "width");
323
324    // <https://html.spec.whatwg.org/multipage/#dom-video-height>
325    make_dimension_uint_getter!(Height, "height");
326
327    // <https://html.spec.whatwg.org/multipage/#dom-video-height>
328    make_dimension_uint_setter!(SetHeight, "height");
329
330    /// <https://html.spec.whatwg.org/multipage/#dom-video-videowidth>
331    fn VideoWidth(&self) -> u32 {
332        if self.htmlmediaelement.get_ready_state() == ReadyState::HaveNothing {
333            return 0;
334        }
335        self.video_width.get().unwrap_or(0)
336    }
337
338    /// <https://html.spec.whatwg.org/multipage/#dom-video-videoheight>
339    fn VideoHeight(&self) -> u32 {
340        if self.htmlmediaelement.get_ready_state() == ReadyState::HaveNothing {
341            return 0;
342        }
343        self.video_height.get().unwrap_or(0)
344    }
345
346    // https://html.spec.whatwg.org/multipage/#dom-video-poster
347    make_url_getter!(Poster, "poster");
348
349    // https://html.spec.whatwg.org/multipage/#dom-video-poster
350    make_url_setter!(SetPoster, "poster");
351
352    // For testing purposes only. This is not an event from
353    // https://html.spec.whatwg.org/multipage/#dom-video-poster
354    event_handler!(postershown, GetOnpostershown, SetOnpostershown);
355}
356
357impl VirtualMethods for HTMLVideoElement {
358    fn super_type(&self) -> Option<&dyn VirtualMethods> {
359        Some(self.upcast::<HTMLMediaElement>() as &dyn VirtualMethods)
360    }
361
362    fn attribute_mutated(
363        &self,
364        cx: &mut js::context::JSContext,
365        attr: &Attr,
366        mutation: AttributeMutation,
367    ) {
368        self.super_type()
369            .unwrap()
370            .attribute_mutated(cx, attr, mutation);
371
372        if attr.local_name() == &local_name!("poster") {
373            if let Some(new_value) = mutation.new_value(attr) {
374                self.update_poster_frame(Some(&new_value), cx)
375            } else {
376                self.update_poster_frame(None, cx)
377            }
378        };
379    }
380
381    fn attribute_affects_presentational_hints(&self, attr: &Attr) -> bool {
382        match attr.local_name() {
383            &local_name!("width") | &local_name!("height") => true,
384            _ => self
385                .super_type()
386                .unwrap()
387                .attribute_affects_presentational_hints(attr),
388        }
389    }
390
391    fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
392        match name {
393            &local_name!("width") | &local_name!("height") => {
394                AttrValue::from_dimension(value.into())
395            },
396            _ => self
397                .super_type()
398                .unwrap()
399                .parse_plain_attribute(name, value),
400        }
401    }
402}
403
404struct PosterFrameFetchContext {
405    /// Reference to the script thread image cache.
406    image_cache: Arc<dyn ImageCache>,
407    /// The element that initiated the request.
408    elem: Trusted<HTMLVideoElement>,
409    /// The cache ID for this request.
410    id: PendingImageId,
411    /// True if this response is invalid and should be ignored.
412    cancelled: bool,
413    /// Url for the resource
414    url: ServoUrl,
415    /// A [`FetchCanceller`] for this request.
416    fetch_canceller: FetchCanceller,
417}
418
419impl FetchResponseListener for PosterFrameFetchContext {
420    fn process_request_body(&mut self, _: RequestId) {
421        self.fetch_canceller.ignore()
422    }
423
424    fn process_response(
425        &mut self,
426        _: &mut js::context::JSContext,
427        request_id: RequestId,
428        metadata: Result<FetchMetadata, NetworkError>,
429    ) {
430        self.image_cache.notify_pending_response(
431            self.id,
432            FetchResponseMsg::ProcessResponse(request_id, metadata.clone()),
433        );
434
435        let metadata = metadata.ok().map(|meta| match meta {
436            FetchMetadata::Unfiltered(m) => m,
437            FetchMetadata::Filtered { unsafe_, .. } => unsafe_,
438        });
439
440        let status_is_ok = metadata
441            .as_ref()
442            .map_or(true, |m| m.status.in_range(200..300));
443
444        if !status_is_ok {
445            self.cancelled = true;
446            self.fetch_canceller.abort();
447        }
448    }
449
450    fn process_response_chunk(
451        &mut self,
452        _: &mut js::context::JSContext,
453        request_id: RequestId,
454        payload: Vec<u8>,
455    ) {
456        if self.cancelled {
457            // An error was received previously, skip processing the payload.
458            return;
459        }
460
461        self.image_cache.notify_pending_response(
462            self.id,
463            FetchResponseMsg::ProcessResponseChunk(request_id, payload.into()),
464        );
465    }
466
467    fn process_response_eof(
468        self,
469        cx: &mut js::context::JSContext,
470        request_id: RequestId,
471        response: Result<(), NetworkError>,
472        timing: ResourceFetchTiming,
473    ) {
474        self.image_cache.notify_pending_response(
475            self.id,
476            FetchResponseMsg::ProcessResponseEOF(request_id, response.clone(), timing.clone()),
477        );
478        network_listener::submit_timing(cx, &self, &response, &timing);
479    }
480
481    fn process_csp_violations(&mut self, _request_id: RequestId, violations: Vec<Violation>) {
482        let global = &self.resource_timing_global();
483        global.report_csp_violations(violations, None, None);
484    }
485}
486
487impl ResourceTimingListener for PosterFrameFetchContext {
488    fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
489        let initiator_type = InitiatorType::LocalName(
490            self.elem
491                .root()
492                .upcast::<Element>()
493                .local_name()
494                .to_string(),
495        );
496        (initiator_type, self.url.clone())
497    }
498
499    fn resource_timing_global(&self) -> DomRoot<GlobalScope> {
500        self.elem.root().owner_document().global()
501    }
502}
503
504impl PosterFrameFetchContext {
505    fn new(
506        elem: &HTMLVideoElement,
507        url: ServoUrl,
508        id: PendingImageId,
509        request_id: RequestId,
510        core_resource_thread: CoreResourceThread,
511    ) -> PosterFrameFetchContext {
512        let window = elem.owner_window();
513        PosterFrameFetchContext {
514            image_cache: window.image_cache(),
515            elem: Trusted::new(elem),
516            id,
517            cancelled: false,
518            url,
519            fetch_canceller: FetchCanceller::new(request_id, false, core_resource_thread),
520        }
521    }
522}
523
524pub(crate) trait LayoutHTMLVideoElementHelpers {
525    fn data(self) -> HTMLMediaData;
526    fn get_width(self) -> LengthOrPercentageOrAuto;
527    fn get_height(self) -> LengthOrPercentageOrAuto;
528}
529
530impl LayoutHTMLVideoElementHelpers for LayoutDom<'_, HTMLVideoElement> {
531    fn data(self) -> HTMLMediaData {
532        let video = self.unsafe_get();
533
534        // Get the current frame being rendered.
535        let current_frame = video.htmlmediaelement.get_current_frame_to_present();
536
537        // This value represents the natural width and height of the video.
538        // It may exist even if there is no current frame (for example, after the
539        // metadata of the video is loaded).
540        let metadata = video
541            .get_video_width()
542            .zip(video.get_video_height())
543            .map(|(width, height)| MediaMetadata { width, height });
544
545        HTMLMediaData {
546            current_frame,
547            metadata,
548        }
549    }
550
551    fn get_width(self) -> LengthOrPercentageOrAuto {
552        self.upcast::<Element>()
553            .get_attr_for_layout(&ns!(), &local_name!("width"))
554            .map(AttrValue::as_dimension)
555            .cloned()
556            .unwrap_or(LengthOrPercentageOrAuto::Auto)
557    }
558
559    fn get_height(self) -> LengthOrPercentageOrAuto {
560        self.upcast::<Element>()
561            .get_attr_for_layout(&ns!(), &local_name!("height"))
562            .map(AttrValue::as_dimension)
563            .cloned()
564            .unwrap_or(LengthOrPercentageOrAuto::Auto)
565    }
566}