script/dom/html/embedded_content/htmltrackelement.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;
6
7use bytes::Bytes;
8use content_security_policy::Destination;
9use dom_struct::dom_struct;
10use html5ever::{LocalName, Prefix, local_name};
11use js::context::{JSContext, NoGC};
12use js::rust::HandleObject;
13use net_traits::blob_url_store::UrlWithBlobClaim;
14use net_traits::fetch::fetch_controller::FetchController;
15use net_traits::request::RequestId;
16use net_traits::{FetchMetadata, NetworkError, ResourceFetchTiming};
17use script_bindings::cell::DomRefCell;
18use servo_url::ServoUrl;
19use servo_webvtt::cue::settings::WebVttCue;
20use servo_webvtt::{IncrementalWebVTTParser, WebVttParserSink};
21
22use crate::dom::bindings::codegen::Bindings::HTMLMediaElementBinding::HTMLMediaElementMethods;
23use crate::dom::bindings::codegen::Bindings::HTMLTrackElementBinding::{
24 HTMLTrackElementConstants, HTMLTrackElementMethods,
25};
26use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
27use crate::dom::bindings::codegen::Bindings::TextTrackBinding::{TextTrackMethods, TextTrackMode};
28use crate::dom::bindings::inheritance::Castable;
29use crate::dom::bindings::refcounted::Trusted;
30use crate::dom::bindings::reflector::DomGlobal;
31use crate::dom::bindings::root::{Dom, DomRoot, UnrootedDom};
32use crate::dom::bindings::str::{DOMString, USVString};
33use crate::dom::csp::Violation;
34use crate::dom::document::Document;
35use crate::dom::element::Element;
36use crate::dom::element::storage::AttrRef;
37use crate::dom::eventtarget::EventTarget;
38use crate::dom::globalscope::GlobalScope;
39use crate::dom::html::htmlelement::HTMLElement;
40use crate::dom::html::htmlmediaelement::HTMLMediaElement;
41use crate::dom::node::node::NodeTraits;
42use crate::dom::node::{BindContext, MoveContext, Node, UnbindContext};
43use crate::dom::performanceresourcetiming::InitiatorType;
44use crate::dom::security::csp::GlobalCspReporting;
45use crate::dom::texttrack::TextTrack;
46use crate::dom::virtualmethods::VirtualMethods;
47use crate::dom::webvtt::vttcue::VTTCue;
48use crate::dom::{AttributeMutation, cors_setting_for_element};
49use crate::event_loop::script_thread::ScriptThread;
50use crate::fetch::fetch::{RequestWithGlobalScope, create_a_potential_cors_request_with_claim};
51use crate::fetch::network_listener::{self, FetchResponseListener, ResourceTimingListener};
52use crate::realms::enter_auto_realm;
53use crate::runtime::job_queue::MicrotaskRunnable;
54use crate::url::ensure_blob_referenced_by_url_is_kept_alive;
55
56#[derive(Clone, Copy, Default, JSTraceable, MallocSizeOf, PartialEq)]
57#[repr(u16)]
58/// <https://html.spec.whatwg.org/multipage/#text-track-readiness-state>
59pub(crate) enum TextTrackReadinessState {
60 /// <https://html.spec.whatwg.org/multipage/#text-track-not-loaded>
61 #[default]
62 None = HTMLTrackElementConstants::NONE,
63 /// <https://html.spec.whatwg.org/multipage/#text-track-loading>
64 Loading = HTMLTrackElementConstants::LOADING,
65 /// <https://html.spec.whatwg.org/multipage/#text-track-loaded>
66 Loaded = HTMLTrackElementConstants::LOADED,
67 /// <https://html.spec.whatwg.org/multipage/#text-track-failed-to-load>
68 FailedToLoad = HTMLTrackElementConstants::ERROR,
69}
70
71#[dom_struct]
72pub(crate) struct HTMLTrackElement {
73 htmlelement: HTMLElement,
74 /// <https://html.spec.whatwg.org/multipage/#text-track-readiness-state>
75 readiness_state: Cell<TextTrackReadinessState>,
76 /// <https://html.spec.whatwg.org/multipage/#text-track>
77 track: Dom<TextTrack>,
78 /// <https://html.spec.whatwg.org/multipage/#track-url>
79 #[no_trace]
80 track_url: DomRefCell<Option<UrlWithBlobClaim>>,
81 /// The track_url used for the last load that was successful.
82 #[no_trace]
83 last_successful_load: DomRefCell<Option<ServoUrl>>,
84 /// Used as part of
85 /// <https://html.spec.whatwg.org/multipage/#start-the-track-processing-model>
86 /// whether the algorithm is running or not.
87 is_running_processing_model_algorithm: Cell<bool>,
88 /// Used as part of
89 /// <https://html.spec.whatwg.org/multipage/#start-the-track-processing-model>
90 /// whether the algorithm has at least once progressed past step 5.
91 has_started_tracking_processing_model: Cell<bool>,
92 /// Used to cancel previous fetch request if a new one has been scheduled.
93 #[no_trace]
94 controller: DomRefCell<Option<FetchController>>,
95}
96
97impl HTMLTrackElement {
98 fn new_inherited(
99 local_name: LocalName,
100 prefix: Option<Prefix>,
101 document: &Document,
102 track: &TextTrack,
103 ) -> HTMLTrackElement {
104 HTMLTrackElement {
105 htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
106 readiness_state: Default::default(),
107 track: Dom::from_ref(track),
108 track_url: Default::default(),
109 last_successful_load: Default::default(),
110 is_running_processing_model_algorithm: Default::default(),
111 has_started_tracking_processing_model: Default::default(),
112 controller: Default::default(),
113 }
114 }
115
116 pub(crate) fn new(
117 cx: &mut JSContext,
118 local_name: LocalName,
119 prefix: Option<Prefix>,
120 document: &Document,
121 proto: Option<HandleObject>,
122 ) -> DomRoot<HTMLTrackElement> {
123 // https://html.spec.whatwg.org/multipage/#sourcing-out-of-band-text-tracks
124 // > When a track element is created, it must be associated
125 // > with a new text track (with its value set as defined below).
126 let track = TextTrack::new(
127 cx,
128 document.window(),
129 Default::default(),
130 Default::default(),
131 Default::default(),
132 Default::default(),
133 Default::default(),
134 None,
135 );
136 let track_element = Node::reflect_node_with_proto(
137 cx,
138 Box::new(HTMLTrackElement::new_inherited(
139 local_name, prefix, document, &track,
140 )),
141 document,
142 proto,
143 );
144 track.set_associated_track(&track_element);
145 track_element
146 }
147
148 /// <https://html.spec.whatwg.org/multipage/#start-the-track-processing-model>
149 pub(crate) fn start_the_track_processing_model(&self, cx: &mut JSContext) {
150 // Step 1. If another occurrence of this algorithm is already running
151 // for this text track and its track element, return,
152 // letting that other algorithm take care of this element.
153 if self.is_running_processing_model_algorithm.get() {
154 return;
155 }
156 // Step 2. If the text track's text track mode is not set to one of hidden or showing, then return.
157 if !matches!(
158 self.track.Mode(),
159 TextTrackMode::Hidden | TextTrackMode::Showing
160 ) {
161 return;
162 }
163 // Step 3. If the text track's track element does not have a media element as a parent, return.
164 if self
165 .upcast::<Node>()
166 .GetParentElement()
167 .is_none_or(|parent| !parent.is::<HTMLMediaElement>())
168 {
169 return;
170 };
171 // Step 4. Run the remainder of these steps in parallel, allowing whatever caused these steps to run to continue.
172 self.has_started_tracking_processing_model.set(true);
173 // Step 5. Top: Await a stable state.
174 let task = TrackElementMicrotask::ProcessingModel {
175 element: Dom::from_ref(self),
176 };
177 self.is_running_processing_model_algorithm.set(true);
178
179 ScriptThread::await_stable_state(cx, Box::new(task));
180 }
181
182 fn check_if_track_parent_element_changed(&self, cx: &mut JSContext) {
183 if let Some(parent) = self
184 .upcast::<Node>()
185 .GetParentNode()
186 .and_then(DomRoot::downcast::<HTMLMediaElement>)
187 {
188 // https://html.spec.whatwg.org/multipage/#sourcing-out-of-band-text-tracks
189 // > When a track element's parent element changes and the new parent is a media element,
190 // > then the user agent must add the track element's corresponding text track to
191 // > the media element's list of text tracks, and then queue a media element task
192 // > given the media element to fire an event named addtrack at the media element's
193 // > textTracks attribute's TextTrackList object, using TrackEvent,
194 // > with the track attribute initialized to the text track's TextTrack object.
195 parent.TextTracks(cx).add(cx, &self.track);
196
197 // https://html.spec.whatwg.org/multipage/#sourcing-out-of-band-text-tracks:start-the-track-processing-model
198 // > The track element's parent element changes and the new parent is a media element.
199 self.start_the_track_processing_model(cx);
200 }
201 }
202
203 pub(crate) fn track<'a>(&self, no_gc: &'a NoGC) -> UnrootedDom<'a, TextTrack> {
204 self.track.as_unrooted(no_gc)
205 }
206
207 fn is_hidden_or_showing(&self) -> bool {
208 matches!(
209 self.track.Mode(),
210 TextTrackMode::Hidden | TextTrackMode::Showing
211 )
212 }
213
214 /// Step 10.4 of <https://html.spec.whatwg.org/multipage/#start-the-track-processing-model>
215 fn cancel_ongoing_request(&self) {
216 if let Some(mut controller) = self.controller.take() {
217 // > If, while fetching is ongoing, either:
218 // > the track URL changes so that it is no longer equal to URL,
219 // > while the text track mode is set to hidden or showing; or
220 // > the text track mode changes to hidden or showing,
221 // > while the track URL is not equal to URL,
222 // > ...then the user agent must abort fetching,
223 // > discarding any pending tasks generated by that algorithm
224 // > (and in particular, not adding any cues to the text track
225 // > list of cues after the moment the URL changed),
226 // > and then queue an element task on the DOM manipulation task source
227 // > given the track element that first changes the text track readiness state
228 // > to failed to load and then fires an event named error at the track element.
229 controller.abort();
230 self.fire_error_event_during_fetching();
231 }
232 }
233
234 fn fire_error_event_during_fetching(&self) {
235 let this = Trusted::new(self);
236 self.global()
237 .task_manager()
238 .dom_manipulation_task_source()
239 .queue(task!(failed_to_load: move |cx| {
240 let track = this.root();
241 track.readiness_state.set(TextTrackReadinessState::FailedToLoad);
242 track.upcast::<EventTarget>().fire_event(cx, atom!("error"));
243 }));
244 }
245}
246
247impl HTMLTrackElementMethods<crate::DomTypeHolder> for HTMLTrackElement {
248 /// <https://html.spec.whatwg.org/multipage/#dom-track-kind>
249 fn Kind(&self) -> DOMString {
250 let element = self.upcast::<Element>();
251 // Get the value of "kind" and transform all uppercase
252 // chars into lowercase.
253 let kind = element
254 .get_string_attribute(&local_name!("kind"))
255 .to_lowercase();
256 match &*kind {
257 "subtitles" | "captions" | "descriptions" | "chapters" | "metadata" => {
258 // The value of "kind" is valid. Return the lowercase version
259 // of it.
260 DOMString::from(kind)
261 },
262 _ if kind.is_empty() => {
263 // The default value should be "subtitles". If "kind" has not
264 // been set, the real value for "kind" is "subtitles"
265 DOMString::from_static("subtitles")
266 },
267 _ => {
268 // If "kind" has been set but it is not one of the valid
269 // values, return the default invalid value of "metadata"
270 DOMString::from_static("metadata")
271 },
272 }
273 }
274
275 // https://html.spec.whatwg.org/multipage/#dom-track-kind
276 // Do no transformations on the value of "kind" when setting it.
277 // All transformations should be done in the get method.
278 make_setter!(SetKind, "kind");
279
280 // https://html.spec.whatwg.org/multipage/#dom-track-src
281 make_url_getter!(Src, "src");
282 // https://html.spec.whatwg.org/multipage/#dom-track-src
283 make_url_setter!(SetSrc, "src");
284
285 // https://html.spec.whatwg.org/multipage/#dom-track-srclang
286 make_getter!(Srclang, "srclang");
287 // https://html.spec.whatwg.org/multipage/#dom-track-srclang
288 make_setter!(SetSrclang, "srclang");
289
290 // https://html.spec.whatwg.org/multipage/#dom-track-label
291 make_getter!(Label, "label");
292 // https://html.spec.whatwg.org/multipage/#dom-track-label
293 make_setter!(SetLabel, "label");
294
295 // https://html.spec.whatwg.org/multipage/#dom-track-default
296 make_bool_getter!(Default, "default");
297 // https://html.spec.whatwg.org/multipage/#dom-track-default
298 make_bool_setter!(SetDefault, "default");
299
300 /// <https://html.spec.whatwg.org/multipage/#dom-track-readystate>
301 fn ReadyState(&self) -> u16 {
302 self.readiness_state.get() as u16
303 }
304
305 /// <https://html.spec.whatwg.org/multipage/#dom-track-track>
306 fn Track(&self) -> DomRoot<TextTrack> {
307 DomRoot::from_ref(&*self.track)
308 }
309}
310
311impl VirtualMethods for HTMLTrackElement {
312 fn super_type(&self) -> Option<&dyn VirtualMethods> {
313 Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods)
314 }
315
316 fn attribute_mutated(
317 &self,
318 cx: &mut JSContext,
319 attr: AttrRef<'_>,
320 mutation: AttributeMutation,
321 ) {
322 self.super_type()
323 .unwrap()
324 .attribute_mutated(cx, attr, mutation);
325 match *attr.local_name() {
326 local_name!("src") => {
327 // https://html.spec.whatwg.org/multipage/#attr-track-src
328 // > When the element's src attribute is set, run these steps:
329 if matches!(mutation, AttributeMutation::Set(_)) {
330 // Step 2. Let value be the element's src attribute value.
331 let value = &**attr.value();
332 // Step 1. Let trackURL be failure.
333 // Step 3. If value is not the empty string,
334 // then set trackURL to the result of encoding-parsing-and-serializing
335 // a URL given value, relative to the element's node document.
336 // Step 4. Set the element's track URL to trackURL if it is not failure;
337 // otherwise to the empty string.
338 *self.track_url.borrow_mut() = if !value.is_empty() {
339 self.owner_document()
340 .encoding_parse_a_url(value)
341 .ok()
342 .map(|url| {
343 ensure_blob_referenced_by_url_is_kept_alive(&self.global(), url)
344 })
345 } else {
346 None
347 };
348 } else {
349 *self.track_url.borrow_mut() = None;
350 }
351
352 if mutation.old_value(attr) !=
353 mutation.new_value(attr).map(|value| value.to_string())
354 {
355 // https://html.spec.whatwg.org/multipage/#sourcing-out-of-band-text-tracks
356 // > Whenever a track element has its src attribute set, changed, or removed,
357 // > the user agent must immediately empty the element's text track's text track list of cues.
358 // > (This also causes the algorithm above to stop adding cues from the resource
359 // > being obtained using the previously given URL, if any.)
360 self.track.empty_cue_list();
361
362 if self.is_hidden_or_showing() {
363 // Step 10.4 of https://html.spec.whatwg.org/multipage/#start-the-track-processing-model
364 //
365 // > If, while fetching is ongoing, either:
366 // > the track URL changes so that it is no longer equal to URL,
367 // > while the text track mode is set to hidden or showing; or
368 // > the text track mode changes to hidden or showing,
369 // > while the track URL is not equal to URL,
370 // > ...then the user agent must abort fetching,
371 // > discarding any pending tasks generated by that algorithm
372 // > (and in particular, not adding any cues to the text track
373 // > list of cues after the moment the URL changed),
374 // > and then queue an element task on the DOM manipulation task source
375 // > given the track element that first changes the text track readiness state
376 // > to failed to load and then fires an event named error at the track element.
377 self.cancel_ongoing_request();
378
379 // https://html.spec.whatwg.org/multipage/#start-the-track-processing-model
380 // Step 11. Wait until the text track readiness state is no longer set to loading.
381 // Step 12. Wait until the track URL is no longer equal to URL,
382 // at the same time as the text track mode is set to hidden or showing.
383 //
384 // These conditions have been checked above by the if-statements
385 if self.has_started_tracking_processing_model.get() &&
386 !self.is_running_processing_model_algorithm.get()
387 {
388 // Step 13. Jump to the step labeled top.
389 let task = TrackElementMicrotask::ProcessingModel {
390 element: Dom::from_ref(self),
391 };
392 self.is_running_processing_model_algorithm.set(true);
393
394 // Step 5. Top: Await a stable state. The synchronous section consists
395 // of the following steps. (The steps in the synchronous section are marked with ⌛.)
396 ScriptThread::await_stable_state(cx, Box::new(task));
397 }
398 }
399 }
400 },
401 local_name!("kind") |
402 local_name!("label") |
403 local_name!("srclang") |
404 local_name!("id") => {
405 // https://html.spec.whatwg.org/multipage/#sourcing-out-of-band-text-tracks
406 // > As the kind, label, srclang, and id attributes are set, changed,
407 // > or removed, the text track must update accordingly, as per the definitions above.
408 self.track.update_attributes_from_track_element(self);
409 },
410 _ => {},
411 }
412 }
413
414 fn moving_steps(&self, cx: &mut JSContext, context: &MoveContext) {
415 if let Some(super_type) = self.super_type() {
416 super_type.moving_steps(cx, context);
417 }
418
419 if context.is_subtree_root &&
420 let Some(parent) = context.old_ancestor.downcast::<HTMLMediaElement>()
421 {
422 // https://html.spec.whatwg.org/multipage/#sourcing-out-of-band-text-tracks
423 // > When a track element's parent element changes and the old parent was a media element,
424 // > then the user agent must remove the track element's corresponding text track from
425 // > the media element's list of text tracks, and then queue a media element task
426 // > given the media element to fire an event named removetrack at the media element's
427 // > textTracks attribute's TextTrackList object, using TrackEvent,
428 // > with the track attribute initialized to the text track's TextTrack object.
429 parent.TextTracks(cx).remove(&self.track);
430 }
431
432 self.check_if_track_parent_element_changed(cx);
433 }
434
435 fn bind_to_tree(&self, cx: &mut JSContext, context: &BindContext) {
436 if let Some(super_type) = self.super_type() {
437 super_type.bind_to_tree(cx, context);
438 }
439
440 self.check_if_track_parent_element_changed(cx);
441 }
442
443 fn unbind_from_tree(&self, cx: &mut JSContext, context: &UnbindContext) {
444 if let Some(s) = self.super_type() {
445 s.unbind_from_tree(cx, context);
446 }
447
448 if let Some(parent) = context.parent.downcast::<HTMLMediaElement>() {
449 // https://html.spec.whatwg.org/multipage/#sourcing-out-of-band-text-tracks
450 // > When a track element's parent element changes and the old parent was a media element,
451 // > then the user agent must remove the track element's corresponding text track from
452 // > the media element's list of text tracks, and then queue a media element task
453 // > given the media element to fire an event named removetrack at the media element's
454 // > textTracks attribute's TextTrackList object, using TrackEvent,
455 // > with the track attribute initialized to the text track's TextTrack object.
456 parent.TextTracks(cx).remove(&self.track);
457 }
458 }
459}
460
461#[derive(JSTraceable, MallocSizeOf)]
462pub(crate) enum TrackElementMicrotask {
463 ProcessingModel { element: Dom<HTMLTrackElement> },
464}
465
466impl MicrotaskRunnable for TrackElementMicrotask {
467 fn handler(&self, cx: &mut JSContext) {
468 let _realm = match self {
469 TrackElementMicrotask::ProcessingModel { element, .. } => {
470 enter_auto_realm(cx, &**element)
471 },
472 };
473 match self {
474 // https://html.spec.whatwg.org/multipage/#start-the-track-processing-model
475 TrackElementMicrotask::ProcessingModel { element } => {
476 // Not specced, but required for browser compatibility:
477 // https://github.com/whatwg/html/issues/12796
478 if element.readiness_state.get() == TextTrackReadinessState::Loaded &&
479 element.track_url.borrow().as_deref() ==
480 element.last_successful_load.borrow().as_ref()
481 {
482 element.is_running_processing_model_algorithm.set(false);
483 return;
484 }
485
486 let media_parent = element
487 .upcast::<Node>()
488 .GetParentNode()
489 .and_then(DomRoot::downcast::<HTMLMediaElement>);
490
491 // The synchronous section consists of the following steps.
492 // (The steps in the synchronous section are marked with ⌛.)
493 // Step 6. ⌛ Set the text track readiness state to loading.
494 element
495 .readiness_state
496 .set(TextTrackReadinessState::Loading);
497 // Step 7. ⌛ Let URL be the track URL of the track element.
498 let url = element.track_url.borrow().clone();
499 // Step 8. ⌛ If the track element's parent is a media element,
500 // then let corsAttributeState be the state of the parent media element's
501 // crossorigin content attribute. Otherwise, let corsAttributeState be No CORS.
502 let cors_attribute_state =
503 media_parent.and_then(|parent| cors_setting_for_element(parent.upcast()));
504 // Step 9. End the synchronous section, continuing the remaining steps in parallel.
505 // TODO
506 // Step 10. If URL is not the empty string:
507 if let Some(url) = url {
508 // Step 10.1. Let request be the result of creating a potential-CORS request given URL,
509 // "track", and corsAttributeState, and with the same-origin fallback flag set.
510 let global = element.global();
511 let document = element.owner_document();
512 let request = create_a_potential_cors_request_with_claim(
513 Some(document.webview_id()),
514 url.clone(),
515 Destination::Track,
516 cors_attribute_state,
517 Some(true),
518 global.get_referrer(),
519 )
520 // Step 10.2. Set request's client to the track element's node document's relevant
521 // settings object.
522 .with_global_scope(&global);
523 // Step 10.3. Set request's initiator type to "track".
524 //
525 // Set in listener
526
527 // Step 10.4. Fetch request.
528 let listener = HTMLTrackElementFetchListener {
529 element: Trusted::new(element),
530 url: url.url(),
531 payload: vec![],
532 };
533 element.cancel_ongoing_request();
534 *element.controller.borrow_mut() = Some(FetchController::new(
535 request.id,
536 false,
537 global.core_resource_thread(),
538 ));
539 document.fetch_background(request, listener);
540 } else {
541 // > If fetching fails for any reason (network error, the server returns an error code, CORS fails, etc.),
542 // > or if URL is the empty string, then queue an element task on the DOM manipulation task source
543 // > given the media element to first change the text track readiness state to failed to load
544 // > and then fire an event named error at the track element.
545 //
546 // This is the "URL is the empty string" case
547 element.is_running_processing_model_algorithm.set(false);
548 *element.controller.borrow_mut() = None;
549 element.fire_error_event_during_fetching();
550 }
551 // Step 11. Wait until the text track readiness state is no longer set to loading.
552 // TODO
553 // Step 12. Wait until the track URL is no longer equal to URL,
554 // at the same time as the text track mode is set to hidden or showing.
555 // TODO
556 // Step 13. Jump to the step labeled top.
557 // TODO
558 },
559 }
560 }
561}
562
563struct TextTrackCueSink {
564 track_element: Trusted<HTMLTrackElement>,
565}
566
567impl WebVttParserSink<JSContext> for TextTrackCueSink {
568 fn consume_cue(&self, cx: &mut JSContext, cue: WebVttCue) {
569 let element = self.track_element.root();
570 let global = element.global();
571 let text_track = &element.track;
572
573 let cue = VTTCue::create_from_vtt(cx, cue, global.as_window(), Some(text_track));
574 text_track.text_track_cue_list(cx).add(cx, cue.upcast());
575 }
576}
577
578struct HTMLTrackElementFetchListener {
579 /// The element that initiated the request.
580 element: Trusted<HTMLTrackElement>,
581 /// URL for the resource.
582 url: ServoUrl,
583 /// The payload received
584 payload: Vec<u8>,
585}
586
587impl HTMLTrackElementFetchListener {
588 fn has_track_url_changed_since_fetch(&self) -> bool {
589 let element = self.element.root();
590 element
591 .track_url
592 .borrow()
593 .as_ref()
594 .is_none_or(|url| **url != self.url)
595 }
596}
597
598impl FetchResponseListener for HTMLTrackElementFetchListener {
599 fn process_request_body(&mut self, _: &GlobalScope, _: RequestId) {}
600
601 fn process_response(
602 &mut self,
603 _: &mut JSContext,
604 _: &GlobalScope,
605 _: RequestId,
606 _: Result<FetchMetadata, NetworkError>,
607 ) {
608 }
609
610 /// Step 10.4 of <https://html.spec.whatwg.org/multipage/#start-the-track-processing-model>
611 fn process_response_chunk(
612 &mut self,
613 _: &mut JSContext,
614 _: &GlobalScope,
615 _: RequestId,
616 payload: Bytes,
617 ) {
618 // > If, while fetching is ongoing, either:
619 // > the track URL changes so that it is no longer equal to URL,
620 // > while the text track mode is set to hidden or showing; or
621 // > the text track mode changes to hidden or showing,
622 // > while the track URL is not equal to URL,
623 // > ...then the user agent must abort fetching,
624 // > discarding any pending tasks generated by that algorithm
625 // > (and in particular, not adding any cues to the text track
626 // > list of cues after the moment the URL changed),
627 // > and then queue an element task on the DOM manipulation task source
628 // > given the track element that first changes the text track readiness state
629 // > to failed to load and then fires an event named error at the track element.
630 //
631 // Note that we don't abort here, since we do that when we schedule the new fetch.
632 // We only bail out here to avoid adding new cues to the list of cues
633 let element = self.element.root();
634 if self.has_track_url_changed_since_fetch() && element.is_hidden_or_showing() {
635 return;
636 }
637
638 self.payload.extend_from_slice(&payload);
639 }
640
641 /// Step 10.4 of <https://html.spec.whatwg.org/multipage/#start-the-track-processing-model>
642 fn process_response_eof(
643 self,
644 cx: &mut JSContext,
645 global: &GlobalScope,
646 _: RequestId,
647 status: Result<(), NetworkError>,
648 timing: ResourceFetchTiming,
649 ) {
650 let track = self.element.clone();
651 let element = self.element.root();
652 if status.is_err() || self.has_track_url_changed_since_fetch() {
653 // > If fetching fails for any reason (network error, the server returns an error code, CORS fails, etc.),
654 // > or if URL is the empty string, then queue an element task on the DOM manipulation task source
655 // > given the media element to first change the text track readiness state to failed to load
656 // > and then fire an event named error at the track element.
657 element.fire_error_event_during_fetching();
658 } else {
659 // > The tasks queued by the fetching algorithm on the networking task source to
660 // > process the data as it is being fetched must determine the type of the resource.
661 // > If the type of the resource is not a supported text track format, the load will fail,
662 // > as described below. Otherwise, the resource's data must be passed to the appropriate parser
663 // > (e.g., the WebVTT parser) as it is received, with the text track list of cues
664 // > being used for that parser's output. [WEBVTT]
665 let result = str::from_utf8(&self.payload)
666 .map_err(|str_error| debug!("WebVTT file contains non-utf8 data: {str_error}"))
667 .and_then(|payload| {
668 let sink = TextTrackCueSink {
669 track_element: track.clone(),
670 };
671 IncrementalWebVTTParser::new(sink)
672 .parse_sync(cx, payload)
673 .map_err(|parser_error| {
674 debug!("Failed to parse WEBVTT file: {parser_error}")
675 })
676 });
677 if result.is_ok() {
678 // > If fetching does not fail, and the file was successfully processed,
679 // > then the final task that is queued by the networking task source,
680 // > after it has finished parsing the data, must change the text track readiness state to loaded,
681 // > and fire an event named load at the track element.
682 let url = self.url.clone();
683 element
684 .global()
685 .task_manager()
686 .networking_task_source()
687 .queue(task!(successfully_loaded: move |cx| {
688 let track = track.root();
689 *track.last_successful_load.borrow_mut() = Some(url);
690 track.readiness_state.set(TextTrackReadinessState::Loaded);
691 track.upcast::<EventTarget>().fire_event(cx, atom!("load"));
692 }));
693 } else {
694 // > If fetching does not fail, but the type of the resource is not a supported text track format,
695 // > or the file was not successfully processed (e.g., the format in question is an XML format
696 // > and the file contained a well-formedness error that XML requires be detected
697 // > and reported to the application), then the task that is queued on the networking task source
698 // > in which the aforementioned problem is found must change the text track readiness state
699 // > to failed to load and fire an event named error at the track element.
700 element.fire_error_event_during_fetching();
701 }
702 }
703 *element.controller.borrow_mut() = None;
704 element.is_running_processing_model_algorithm.set(false);
705 network_listener::submit_timing(cx, global, &self, &status, &timing);
706 }
707
708 fn process_csp_violations(
709 &mut self,
710 cx: &mut JSContext,
711 global: &GlobalScope,
712 _: RequestId,
713 violations: Vec<Violation>,
714 ) {
715 global.report_csp_violations(cx, violations, None, None);
716 }
717
718 fn should_invoke(&self) -> bool {
719 true
720 }
721}
722
723impl ResourceTimingListener for HTMLTrackElementFetchListener {
724 /// Step 10.3. of <https://html.spec.whatwg.org/multipage/#start-the-track-processing-model>
725 fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
726 (InitiatorType::Track, self.url.clone())
727 }
728}