servo-script 0.2.0

A component of the servo web-engine.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

use std::cell::Cell;
use std::sync::Arc;

use dom_struct::dom_struct;
use euclid::default::Size2D;
use html5ever::{LocalName, Prefix, local_name, ns};
use js::rust::HandleObject;
use layout_api::{HTMLMediaData, MediaMetadata};
use net_traits::blob_url_store::UrlWithBlobClaim;
use net_traits::image_cache::{
    ImageCache, ImageCacheResult, ImageLoadListener, ImageOrMetadataAvailable, ImageResponse,
    PendingImageId,
};
use net_traits::request::{CredentialsMode, Destination, RequestBuilder, RequestId};
use net_traits::{
    CoreResourceThread, FetchMetadata, FetchResponseMsg, NetworkError, ResourceFetchTiming,
};
use pixels::{Snapshot, SnapshotAlphaMode, SnapshotPixelFormat};
use servo_media::player::video::VideoFrame;
use servo_url::ServoUrl;
use style::attr::{AttrValue, LengthOrPercentageOrAuto};

use crate::document_loader::{LoadBlocker, LoadType};
use crate::dom::attr::Attr;
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::HTMLVideoElementBinding::HTMLVideoElementMethods;
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::refcounted::Trusted;
use crate::dom::bindings::reflector::DomGlobal;
use crate::dom::bindings::root::{DomRoot, LayoutDom};
use crate::dom::bindings::str::{DOMString, USVString};
use crate::dom::csp::{GlobalCspReporting, Violation};
use crate::dom::document::Document;
use crate::dom::element::{AttributeMutation, Element};
use crate::dom::globalscope::GlobalScope;
use crate::dom::html::htmlmediaelement::{HTMLMediaElement, NetworkState, ReadyState};
use crate::dom::node::{Node, NodeDamage, NodeTraits};
use crate::dom::performance::performanceresourcetiming::InitiatorType;
use crate::dom::virtualmethods::VirtualMethods;
use crate::fetch::{FetchCanceller, RequestWithGlobalScope};
use crate::network_listener::{self, FetchResponseListener, ResourceTimingListener};
use crate::url::ensure_blob_referenced_by_url_is_kept_alive;

#[dom_struct]
pub(crate) struct HTMLVideoElement {
    htmlmediaelement: HTMLMediaElement,
    /// <https://html.spec.whatwg.org/multipage/#dom-video-videowidth>
    video_width: Cell<Option<u32>>,
    /// <https://html.spec.whatwg.org/multipage/#dom-video-videoheight>
    video_height: Cell<Option<u32>>,
    /// Incremented whenever tasks associated with this element are cancelled.
    generation_id: Cell<u32>,
    /// Load event blocker. Will block the load event while the poster frame
    /// is being fetched.
    load_blocker: DomRefCell<Option<LoadBlocker>>,
    /// A copy of the last frame
    #[ignore_malloc_size_of = "VideoFrame"]
    #[no_trace]
    last_frame: DomRefCell<Option<VideoFrame>>,
}

impl HTMLVideoElement {
    fn new_inherited(
        local_name: LocalName,
        prefix: Option<Prefix>,
        document: &Document,
    ) -> HTMLVideoElement {
        HTMLVideoElement {
            htmlmediaelement: HTMLMediaElement::new_inherited(local_name, prefix, document),
            video_width: Cell::new(None),
            video_height: Cell::new(None),
            generation_id: Cell::new(0),
            load_blocker: Default::default(),
            last_frame: Default::default(),
        }
    }

    pub(crate) fn new(
        cx: &mut js::context::JSContext,
        local_name: LocalName,
        prefix: Option<Prefix>,
        document: &Document,
        proto: Option<HandleObject>,
    ) -> DomRoot<HTMLVideoElement> {
        Node::reflect_node_with_proto(
            cx,
            Box::new(HTMLVideoElement::new_inherited(
                local_name, prefix, document,
            )),
            document,
            proto,
        )
    }

    pub(crate) fn get_video_width(&self) -> Option<u32> {
        self.video_width.get()
    }

    pub(crate) fn get_video_height(&self) -> Option<u32> {
        self.video_height.get()
    }

    pub(crate) fn set_natural_dimensions(&self, width: Option<u32>, height: Option<u32>) -> bool {
        if self.video_width.get() == width && self.video_height.get() == height {
            return false;
        }

        self.video_width.set(width);
        self.video_height.set(height);

        self.upcast::<Node>().dirty(NodeDamage::Other);
        true
    }

    /// Gets the copy of the video frame at the current playback position,
    /// if that is available, or else (e.g. when the video is seeking or buffering)
    /// its previous appearance, if any.
    pub(crate) fn get_current_frame_data(&self) -> Option<Snapshot> {
        let frame = self.htmlmediaelement.get_current_frame();
        if frame.is_some() {
            *self.last_frame.borrow_mut() = frame;
        }

        match self.last_frame.borrow().as_ref() {
            Some(frame) => {
                let size = Size2D::new(frame.get_width() as u32, frame.get_height() as u32);
                if !frame.is_gl_texture() {
                    let alpha_mode = SnapshotAlphaMode::Transparent {
                        premultiplied: false,
                    };

                    Some(Snapshot::from_vec(
                        size.cast(),
                        SnapshotPixelFormat::BGRA,
                        alpha_mode,
                        frame.get_data().to_vec(),
                    ))
                } else {
                    // XXX(victor): here we only have the GL texture ID.
                    Some(Snapshot::cleared(size.cast()))
                }
            },
            None => None,
        }
    }

    /// <https://html.spec.whatwg.org/multipage/#poster-frame>
    fn update_poster_frame(&self, poster_url: Option<&str>, cx: &mut js::context::JSContext) {
        // Step 1. If there is an existing instance of this algorithm running
        // for this video element, abort that instance of this algorithm without
        // changing the poster frame.
        self.generation_id.set(self.generation_id.get() + 1);

        // Step 2. If the poster attribute's value is the empty string or
        // if the attribute is absent, then there is no poster frame; return.
        let Some(poster_url) = poster_url.filter(|poster_url| !poster_url.is_empty()) else {
            self.htmlmediaelement.set_poster_frame(None);
            return;
        };

        // Step 3. Let url be the result of encoding-parsing a URL given
        // the poster attribute's value, relative to the element's node
        // document.
        // Step 4. If url is failure, then return. There is no poster frame.
        let global = self.owner_global();
        let poster_url = match self
            .owner_document()
            .encoding_parse_a_url(poster_url)
            .map(|url| ensure_blob_referenced_by_url_is_kept_alive(&global, url))
        {
            Ok(url) => url,
            Err(_) => {
                self.htmlmediaelement.set_poster_frame(None);
                return;
            },
        };

        // We use the image cache for poster frames so we save as much
        // network activity as possible.
        let window = self.owner_window();
        let image_cache = window.image_cache();
        let cache_result = image_cache.get_cached_image_status(
            poster_url.url(),
            window.origin().immutable().clone(),
            None,
        );

        let id = match cache_result {
            ImageCacheResult::Available(ImageOrMetadataAvailable::ImageAvailable {
                image,
                url,
                ..
            }) => {
                self.process_image_response(ImageResponse::Loaded(image, url), cx);
                return;
            },
            ImageCacheResult::Available(ImageOrMetadataAvailable::MetadataAvailable(_, id)) => id,
            ImageCacheResult::ReadyForRequest(id) => {
                self.do_fetch_poster_frame(poster_url, id, cx);
                id
            },
            ImageCacheResult::FailedToLoadOrDecode => {
                self.process_image_response(ImageResponse::FailedToLoadOrDecode, cx);
                return;
            },
            ImageCacheResult::Pending(id) => id,
        };

        let trusted_node = Trusted::new(self);
        let generation = self.generation_id();
        let callback = window.register_image_cache_listener(id, move |response, cx| {
            let element = trusted_node.root();

            // Ignore any image response for a previous request that has been discarded.
            if generation != element.generation_id() {
                return;
            }
            element.process_image_response(response.response, cx);
        });

        image_cache.add_listener(ImageLoadListener::new(callback, window.pipeline_id(), id));
    }

    /// <https://html.spec.whatwg.org/multipage/#poster-frame>
    fn do_fetch_poster_frame(
        &self,
        poster_url: UrlWithBlobClaim,
        id: PendingImageId,
        cx: &mut js::context::JSContext,
    ) {
        // Step 5. Let request be a new request whose URL is url, client is the element's node
        // document's relevant settings object, destination is "image", initiator type is "video",
        // credentials mode is "include", and whose use-URL-credentials flag is set.
        let document = self.owner_document();
        let global = self.owner_global();
        let request = RequestBuilder::new(
            Some(document.webview_id()),
            poster_url.clone(),
            global.get_referrer(),
        )
        .destination(Destination::Image)
        .credentials_mode(CredentialsMode::Include)
        .use_url_credentials(true)
        .with_global_scope(&global);

        // Step 6. Fetch request. This must delay the load event of the element's node document.
        // This delay must be independent from the ones created by HTMLMediaElement during
        // its media load algorithm, otherwise a code like
        // <video poster="poster.png"></video>
        // (which triggers no media load algorithm unless a explicit call to .load() is done)
        // will block the document's load event forever.
        let blocker = &self.load_blocker;
        LoadBlocker::terminate(blocker, cx);
        *blocker.borrow_mut() = Some(LoadBlocker::new(
            &self.owner_document(),
            LoadType::Image(poster_url.url()),
        ));

        let context = PosterFrameFetchContext::new(
            self,
            poster_url.url(),
            id,
            request.id,
            self.global().core_resource_thread(),
        );
        self.owner_document().fetch_background(request, context);
    }

    fn generation_id(&self) -> u32 {
        self.generation_id.get()
    }

    /// <https://html.spec.whatwg.org/multipage/#poster-frame>
    fn process_image_response(&self, response: ImageResponse, cx: &mut js::context::JSContext) {
        // Step 7. If an image is thus obtained, the poster frame is that image.
        // Otherwise, there is no poster frame.
        match response {
            ImageResponse::Loaded(image, url) => {
                debug!("Loaded poster image for video element: {:?}", url);
                match image.as_raster_image() {
                    Some(image) => self.htmlmediaelement.set_poster_frame(Some(image)),
                    None => warn!("Vector images are not yet supported in video poster"),
                }
                LoadBlocker::terminate(&self.load_blocker, cx);
            },
            ImageResponse::MetadataLoaded(..) => {},
            // The image cache may have loaded a placeholder for an invalid poster url
            ImageResponse::FailedToLoadOrDecode => {
                self.htmlmediaelement.set_poster_frame(None);
                // A failed load should unblock the document load.
                LoadBlocker::terminate(&self.load_blocker, cx);
            },
        }
    }

    /// <https://html.spec.whatwg.org/multipage/#check-the-usability-of-the-image-argument>
    pub(crate) fn is_usable(&self) -> bool {
        !matches!(
            self.htmlmediaelement.get_ready_state(),
            ReadyState::HaveNothing | ReadyState::HaveMetadata
        )
    }

    pub(crate) fn origin_is_clean(&self) -> bool {
        self.htmlmediaelement.origin_is_clean()
    }

    pub(crate) fn is_network_state_empty(&self) -> bool {
        self.htmlmediaelement.network_state() == NetworkState::Empty
    }
}

impl HTMLVideoElementMethods<crate::DomTypeHolder> for HTMLVideoElement {
    // <https://html.spec.whatwg.org/multipage/#dom-video-width>
    make_dimension_uint_getter!(Width, "width");

    // <https://html.spec.whatwg.org/multipage/#dom-video-width>
    make_dimension_uint_setter!(SetWidth, "width");

    // <https://html.spec.whatwg.org/multipage/#dom-video-height>
    make_dimension_uint_getter!(Height, "height");

    // <https://html.spec.whatwg.org/multipage/#dom-video-height>
    make_dimension_uint_setter!(SetHeight, "height");

    /// <https://html.spec.whatwg.org/multipage/#dom-video-videowidth>
    fn VideoWidth(&self) -> u32 {
        if self.htmlmediaelement.get_ready_state() == ReadyState::HaveNothing {
            return 0;
        }
        self.video_width.get().unwrap_or(0)
    }

    /// <https://html.spec.whatwg.org/multipage/#dom-video-videoheight>
    fn VideoHeight(&self) -> u32 {
        if self.htmlmediaelement.get_ready_state() == ReadyState::HaveNothing {
            return 0;
        }
        self.video_height.get().unwrap_or(0)
    }

    // https://html.spec.whatwg.org/multipage/#dom-video-poster
    make_url_getter!(Poster, "poster");

    // https://html.spec.whatwg.org/multipage/#dom-video-poster
    make_url_setter!(SetPoster, "poster");

    // For testing purposes only. This is not an event from
    // https://html.spec.whatwg.org/multipage/#dom-video-poster
    event_handler!(postershown, GetOnpostershown, SetOnpostershown);
}

impl VirtualMethods for HTMLVideoElement {
    fn super_type(&self) -> Option<&dyn VirtualMethods> {
        Some(self.upcast::<HTMLMediaElement>() as &dyn VirtualMethods)
    }

    fn attribute_mutated(
        &self,
        cx: &mut js::context::JSContext,
        attr: &Attr,
        mutation: AttributeMutation,
    ) {
        self.super_type()
            .unwrap()
            .attribute_mutated(cx, attr, mutation);

        if attr.local_name() == &local_name!("poster") {
            if let Some(new_value) = mutation.new_value(attr) {
                self.update_poster_frame(Some(&new_value), cx)
            } else {
                self.update_poster_frame(None, cx)
            }
        };
    }

    fn attribute_affects_presentational_hints(&self, attr: &Attr) -> bool {
        match attr.local_name() {
            &local_name!("width") | &local_name!("height") => true,
            _ => self
                .super_type()
                .unwrap()
                .attribute_affects_presentational_hints(attr),
        }
    }

    fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
        match name {
            &local_name!("width") | &local_name!("height") => {
                AttrValue::from_dimension(value.into())
            },
            _ => self
                .super_type()
                .unwrap()
                .parse_plain_attribute(name, value),
        }
    }
}

struct PosterFrameFetchContext {
    /// Reference to the script thread image cache.
    image_cache: Arc<dyn ImageCache>,
    /// The element that initiated the request.
    elem: Trusted<HTMLVideoElement>,
    /// The cache ID for this request.
    id: PendingImageId,
    /// True if this response is invalid and should be ignored.
    cancelled: bool,
    /// Url for the resource
    url: ServoUrl,
    /// A [`FetchCanceller`] for this request.
    fetch_canceller: FetchCanceller,
}

impl FetchResponseListener for PosterFrameFetchContext {
    fn process_request_body(&mut self, _: RequestId) {
        self.fetch_canceller.ignore()
    }

    fn process_response(
        &mut self,
        _: &mut js::context::JSContext,
        request_id: RequestId,
        metadata: Result<FetchMetadata, NetworkError>,
    ) {
        self.image_cache.notify_pending_response(
            self.id,
            FetchResponseMsg::ProcessResponse(request_id, metadata.clone()),
        );

        let metadata = metadata.ok().map(|meta| match meta {
            FetchMetadata::Unfiltered(m) => m,
            FetchMetadata::Filtered { unsafe_, .. } => unsafe_,
        });

        let status_is_ok = metadata
            .as_ref()
            .is_none_or(|m| m.status.in_range(200..300));

        if !status_is_ok {
            self.cancelled = true;
            self.fetch_canceller.abort();
        }
    }

    fn process_response_chunk(
        &mut self,
        _: &mut js::context::JSContext,
        request_id: RequestId,
        payload: Vec<u8>,
    ) {
        if self.cancelled {
            // An error was received previously, skip processing the payload.
            return;
        }

        self.image_cache.notify_pending_response(
            self.id,
            FetchResponseMsg::ProcessResponseChunk(request_id, payload.into()),
        );
    }

    fn process_response_eof(
        self,
        cx: &mut js::context::JSContext,
        request_id: RequestId,
        response: Result<(), NetworkError>,
        timing: ResourceFetchTiming,
    ) {
        self.image_cache.notify_pending_response(
            self.id,
            FetchResponseMsg::ProcessResponseEOF(request_id, response.clone(), timing.clone()),
        );
        network_listener::submit_timing(cx, &self, &response, &timing);
    }

    fn process_csp_violations(&mut self, _request_id: RequestId, violations: Vec<Violation>) {
        let global = &self.resource_timing_global();
        global.report_csp_violations(violations, None, None);
    }
}

impl ResourceTimingListener for PosterFrameFetchContext {
    fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
        let initiator_type = InitiatorType::LocalName(
            self.elem
                .root()
                .upcast::<Element>()
                .local_name()
                .to_string(),
        );
        (initiator_type, self.url.clone())
    }

    fn resource_timing_global(&self) -> DomRoot<GlobalScope> {
        self.elem.root().owner_document().global()
    }
}

impl PosterFrameFetchContext {
    fn new(
        elem: &HTMLVideoElement,
        url: ServoUrl,
        id: PendingImageId,
        request_id: RequestId,
        core_resource_thread: CoreResourceThread,
    ) -> PosterFrameFetchContext {
        let window = elem.owner_window();
        PosterFrameFetchContext {
            image_cache: window.image_cache(),
            elem: Trusted::new(elem),
            id,
            cancelled: false,
            url,
            fetch_canceller: FetchCanceller::new(request_id, false, core_resource_thread),
        }
    }
}

impl LayoutDom<'_, HTMLVideoElement> {
    pub(crate) fn data(self) -> HTMLMediaData {
        let video = self.unsafe_get();

        // Get the current frame being rendered.
        let current_frame = video.htmlmediaelement.get_current_frame_to_present();

        // This value represents the natural width and height of the video.
        // It may exist even if there is no current frame (for example, after the
        // metadata of the video is loaded).
        let metadata = video
            .get_video_width()
            .zip(video.get_video_height())
            .map(|(width, height)| MediaMetadata { width, height });

        HTMLMediaData {
            current_frame,
            metadata,
        }
    }

    pub(crate) fn get_width(self) -> LengthOrPercentageOrAuto {
        self.upcast::<Element>()
            .get_attr_for_layout(&ns!(), &local_name!("width"))
            .map(AttrValue::as_dimension)
            .cloned()
            .unwrap_or(LengthOrPercentageOrAuto::Auto)
    }

    pub(crate) fn get_height(self) -> LengthOrPercentageOrAuto {
        self.upcast::<Element>()
            .get_attr_for_layout(&ns!(), &local_name!("height"))
            .map(AttrValue::as_dimension)
            .cloned()
            .unwrap_or(LengthOrPercentageOrAuto::Auto)
    }
}