Repository navigation
net: Continue to clean up of FetchMetadata - #48748
Conversation
|
If somebody has better names for these types that would be good. I honestly have no idea why we even have the special fields for xmlhttprequest. |
|
| filtered: FilteredMetadata::Basic(metadata.unwrap()), | ||
| filtered: FilteredMetadata::Basic(metadata.unwrap().into()), | ||
| unsafe_: unsafe_metadata, | ||
| }), | ||
| ResponseType::Cors => Ok(FetchMetadata::Filtered { | ||
| filtered: FilteredMetadata::Cors(metadata.unwrap()), | ||
| filtered: FilteredMetadata::Cors(metadata.unwrap().into()), | ||
| unsafe_: unsafe_metadata, |
There was a problem hiding this comment.
This is a really good moment to remove these unwraps that have often resulted in panics in networking code. Either turn these into expect with an explanation of why they are always true handle missing metadata as an error, or (best) restructure the code to avoid having to unwrap here.
| /// Final URL after redirects. | ||
| pub final_url: ServoUrl, | ||
| /// Headers | ||
| pub headers: Option<Serde<HeaderMap>>, |
There was a problem hiding this comment.
Making this non-optional, should we have a default value or should this be an error?
| Basic(SpecialMetadata), | ||
| Cors(SpecialMetadata), |
There was a problem hiding this comment.
This would be reverted with my suggestion.
There was a problem hiding this comment.
Sorry I can't quite follow this. What do you mean?
b2c775a to
66bf5d6
Compare
71a2a2d to
f002a8e
Compare
f002a8e to
c6147bd
Compare
Signed-off-by: Narfinger <[email protected]>
Signed-off-by: Narfinger <[email protected]>
Signed-off-by: Narfinger <[email protected]>
c6147bd to
81f6c72
Compare
Signed-off-by: Narfinger <[email protected]>
|
Update on this part: Removing the unwrap actually produces wrong results (at least how I had it first). for Opaque Requests the url does not exist, so we would produce errors when we should not. I added a comment for this and kept the unwrap as I think it is clearer. |
mrobinson
left a comment
There was a problem hiding this comment.
Looks good with some nits. Please update the PR description to match the current state of the PR.
Signed-off-by: Narfinger <[email protected]>
FetchMetadata
|
@mrobinson I think dco is unhappy with the last changes you made. |
Signed-off-by: Martin Robinson <[email protected]>
0e576de to
3fdce99
Compare
Every fetch of a media element started out origin-clean, until the headers of its response arrived. A fetch that restarts the fetch of the same media resource, after a seek or once the player needs data again, therefore made a video that was fetched in no-cors mode from another origin count as origin-clean for as long as the server took to answer, so that drawing it to a canvas or into an ImageBitmap did not taint them. Start such a fetch with the origin-clean flag of the fetch that it replaces, and keep the flag false once a response of the resource was not CORS-same-origin. A new resource selection still starts with a fresh flag. Fork note: meant for upstream. Drop once upstream has it. Testing: a new WPT test draws a video from another origin, fetched without CORS, to a canvas while it seeks, from a server that delays its answer to a range request that starts past byte 0. Validation: the new test fails in 3 of 3 runs without this patch, where getImageData returns the pixels of the video while it seeks, and passes in 3 of 3 with it. drawing-images-to-the-canvas and imagebitmap (43 tests): on ohos-main only the new test fails, and all pass with the series. `./mach test-wpt --release --processes 6 --timeout-multiplier 2` of html/semantics/embedded-content/media-elements, the-video-element, and html/canvas/element/manual/drawing-images-to-the-canvas and imagebitmap (475 tests) with the series up to the last patch: no new failure; the unexpected results (media_fragment_seek, autoplay-default-permissions-policy, load-removes-queued-error-event) also occur on ohos-main. `./mach check --ohos` passes. AI-assisted: Yes (agent session; written and tested by the agent) AI-assisted: Yes (agent session; 2026-10-29 sync -- mechanical conflict resolution: the response's origin-clean flag now comes from upstream's `CorsStatus` (servo#48748), no semantic change) Signed-off-by: Jonathan Schwender <[email protected]>
…r is full When its player has enough data, a media element cancels a fetch with range support, to restart it with a Range request once the player needs data again, and keeps queueing the data of a fetch without range support, up to 32 MiB, before it cancels it and fetches the resource from its start again. Every restart costs a request, on HTTP/1.1 a new connection, and the bytes that were in flight. Ask net to suspend a fetch that is read from the network instead, and queue the data that was in flight. Net answers whether it suspended the fetch. If it did, flow control holds back the server, the download is suspended (NETWORK_IDLE and suspend, then NETWORK_LOADING once it resumes, and no progress events meanwhile), and once the player needs data, the same fetch resumes and the queue drains. If it did not, as for a cache hit or when two fetches to the origin are suspended already, the fetch backs off as before; so it does if the answer is lost, and it is resumed in case net suspended it. Responses that are not read from the network are handled as before, and the cap on the queue stays for data that keeps arriving. When a fetch completes, progress, then NETWORK_IDLE and suspend follow, also if the fetch was suspended. A fetch with range support that stays suspended for media_fetch_suspension_timeout_ms (30 s) is cancelled, to restart where the player stopped once it needs data again, so that an element paused for long does not hold a connection, which servers would time out anyway. A fetch without range support stays suspended, since its restart would fetch the resource from its start again, until net gives up on it after network_fetch_suspend_timeout_ms (60 s). Such a server, and net, end the fetch: net with a network error, which ran the fatal steps (MEDIA_ERR_NETWORK, "If the connection is interrupted after some media data has been received"), and a closed connection like a complete body, so the stream ended early. So if a fetch that was suspended ends with a network error, or with fewer bytes than its Content-Length, restart it at the byte where the player stopped, with a Range request, which a server without range support answers from the start of the resource, whose bytes before that position are discarded as after a seek: at once if the player accepts data, or else once it needs data again. A restart past the end of the resource, which the server answers with 416 or which the length of the resource tells, ends the stream, as when the server's Content-Length was too large; so does a restart without range support whose body ends without an error where the player stopped. Any other restart that ends early before it delivers data runs the fatal steps: net ends a body that loses its connection without an error. A restart that delivered data may be restarted again, so a fetch is only restarted while it makes progress. The Content-Length of an encoded body is not the length of the decoded body, so it is not compared. The state of the suspension in the fetch context grows HTMLVideoElement from 1264 to 1296 bytes. Fork note: meant for upstream. Drop once upstream has it. Testing: no test; a fetch only backs off once the 50 MiB queue of the GStreamer player is full. See Validation. Validation: Linux, GStreamer, a 150 MB, 40 s H.264 file in a muted <video preload=metadata> that plays, from a Python server that sends at most 25 MB/s per connection; the base is the parent commit. With range support: 1 request and 149.7 MB sent (base: 3 requests, 149.9 MB); networkState turns NETWORK_IDLE with a suspend event once net confirms the suspension 3.5 s in, and NETWORK_LOADING when the fetch resumes 17.4 s in, with no seeking, stalled or error event. Without range support: 1 request, 149.7 MB, peak RSS 422 MiB (base: 2 requests, 269.9 MB, 419 MiB); paused for 25 s, 1 request, 149.7 MB (base: 2 requests, 269.9 MB). Paused for 40 s with range support: the timeout cancels the fetch 30 s after the suspension, and the restart when playback needs data again plays to the end: 2 requests, 155.4 MB (base: 3 requests, 149.9 MB). Three elements on one origin: net suspends two fetches, which take 1 request each, and the third backs off when net declines its suspension: 4 requests, 449.1 MB (base: 9 requests, 449.8 MB). A suspension costs peak RSS (423 instead of 392 MiB for one element, 738 instead of 683 MiB for three), although only 53 bytes were queued when net confirmed it: once the fetch resumes, net reads at once what the socket buffers held. A server that closes a connection it could not write to for 5 s: the earlier revision of this patch without the restart ended playback after 16.5 s of the media, with no error; with it, the media plays to the end, in 3 requests and 149.7 MB with range support and 2 requests and 238.3 MB without. With network_fetch_suspend_timeout_ms=5000 and playback paused for 40 s, net ends the suspended fetch with a network error, and the media plays to the end after the restart: 3 requests and 156.9 MB with range support, 2 requests and 239.1 MB without, no error event. A server whose Content-Length is 10 MB too large: playback ends normally, as on the base; at 25 MB/s the restart fetches the 10.5 MB that were queued again (2 requests, 160.2 MB) and, without range support, the whole resource again (2 requests, 299.3 MB); at 8 and 12 MB/s the restart starts at the end of the file, which the server answers with 416 (2 requests, 149.7 MB). A server that closes idle connections and closes the restart right after its headers: MEDIA_ERR_NETWORK at the restart, 16.5 s into the media, with and without range support. `./mach test-wpt --release --processes 6 --timeout-multiplier 2` html/semantics/embedded-content/media-elements, the-video-element and html/canvas/element/manual/drawing-images-to-the-canvas with the series: 451 tests, 446 as expected; the other five behave the same on the parent commit of the series when run alone: autoplay-default-permissions-policy.https.sub.html passes where a timeout is expected (3/3 on both), media_fragment_seek.html fails a subtest (3/3 on both), src_object_blob.html times out 1 of 3 runs on both, video_timeupdate_on_seek.html passes a subtest that is expected to time out, and load-removes-queued-error-event.html hangs intermittently because GStreamer never reports the metadata of the 539-byte sound_0.mp3 (3 of 8 runs with the series, 4 of 8 without, alternating). In a later run of media-elements, track-cues-seeking.html timed out, which it does intermittently with and without the series (3 of 39 and 2 of 39 isolated runs, alternating); its 192 KB video never fills the player. `./mach check --ohos` passes at each commit; `./mach test-tidy` reports only the known rustls advisories. AI-assisted: Yes (agent session; implemented, tested and measured by the agent) AI-assisted: Yes (agent session; 2026-10-22 sync -- mechanical conflict resolution: the `media_fetch_suspension_timeout_ms` pref where upstream removed the `layout_unimplemented`, variable-fonts and writing-mode prefs (servo#48915), and the patch's +32 bytes of `HTMLVideoElement` applied to upstream's new size (servo#48082)) AI-assisted: Yes (agent session; 2026-10-22 sync -- compile fix folded in: the two early returns for a fetch that ended early pass the fetch listener's global to `submit_timing`, which takes it since upstream 51d1117 (servo#49032)) AI-assisted: Yes (agent session; 2026-10-29 sync -- mechanical conflict resolution: the pref next to upstream's `mathml_core_enabled` (servo#48631), the origin-clean line in upstream's `CorsStatus` form (servo#48748); `HTMLVideoElement` is 1256 bytes, measured at this commit with a compile-time probe, since patch 65 no longer adds a field) Signed-off-by: Jonathan Schwender <[email protected]>
The media cache fetches the bytes of a media resource through the Fetcher trait, on any thread, and decides which ranges to request and when to suspend, resume or cancel a fetch. Add the implementation of that trait for media elements. ScriptFetcher builds the request of a media element as the resource fetch algorithm does: destination audio or video, a potential-CORS request for the crossorigin attribute, the document as the client, and the referrer policy of the element. Each fetch copies it and adds a Range header for the byte where it starts and, for a request after the first, If-Range with the validator of the first response. It starts the fetch with fetch_async, so that the response arrives on the FetchThread of the content process rather than on the script thread, and controls it through a FetchController: a suspension carries a reply that tells the cache whether net suspended the fetch, and cancelling or dropping the handle aborts it. The response is classified for the cache: whether it is a 206 and where its body starts in the resource, the length of the resource from Content-Range or Content-Length, its strong ETag or else its Last-Modified date as the validator, whether it has a Content-Encoding, under which byte positions and lengths do not apply, whether it is CORS-cross-origin, and the origin of its final URL. A 416 ends the fetch as RangeNotSatisfiable, another status that is not a success as Status, a request that CSP, mixed content or a CORS check blocked as Blocked, and any other network error as Network. What only script can do is queued as tasks of the networking task source on the element, which they do not keep alive: CSP violation reports, resource timing entries for every fetch, and the failure steps of the element when the first fetch fails before its response, so that a request that its document blocks fails the element even if the cache serves other readers. The fetcher claims the blob of a blob URL for its lifetime, so that restarts and gap fetches still work after the page revoked the URL, and gives every fetch a token of its own (UrlWithBlobClaim::with_new_token), since net ends the claim of a request's token once that request is done. It accepts only a 200, or a 206 with a valid byte range, as "verify a media response" asks, and answers a suspension that cannot carry a reply as declined. Nothing uses the fetcher yet; the next patch moves the media element to the media cache. Fork note: meant for upstream. Drop once upstream has it. Testing: through the media element in the next patch. Validation: `./mach check` and `./mach check --ohos` pass. See the next patch for WPT and the scenarios. AI-assisted: Yes (agent session; implemented and tested by the agent) AI-assisted: Yes (agent session; 2026-10-22 sync -- compile fix folded in: `InitiatorType::LocalName` takes a `LocalName` since upstream 9abaf60 (servo#48953), and 51d1117 (servo#49032) removed `ResourceTimingListener::resource_timing_global`, so the timing of a media fetch goes to `submit_timing` with the global of the element's document, which that method returned) AI-assisted: Yes (agent session; 2026-10-29 sync -- compile fix: `FetchMetadata::is_cors_cross_origin()` became `cors_status()` (servo#48748), so the fetcher compares it with `CorsStatus::Unsafe`) Signed-off-by: Jonathan Schwender <[email protected]>
A media element fetched its media resource itself and pushed each chunk into the player as it arrived. To keep the player from being flooded, it backed off, suspended the fetch, cancelled it after a timeout, and restarted it where the player had stopped, after a lost connection, a 416 or a seek, with a cap on the bytes it queued and a document registry to cancel suspended fetches that nothing would resume. A loop on a backend without its own buffer, a second element and a reload of the same resource downloaded it again. In the resource fetch algorithm, the element now opens a reader of the media resource in the media cache of the content process instead, keyed by the requested URL, the CORS mode and the origin of the document, with a ScriptFetcher for the fetches that the cache needs. Blob and data URLs take the same path; MediaStream sources are unchanged, and preload=none still opens no reader until the media resource is needed. If the player accepts the reader as its data source, it reads from it. Otherwise the element pushes the data of the reader into the player: once the player needs data, it reads 64 KiB chunks from the byte where the player stopped and pushes them until the player has enough, when the refused chunk is read again later, or until the reader has no data there yet, when the waker of the reader continues; at most 1 MiB per task, so that cached data does not block the script thread. SeekData moves that position, and the end of the stream reaches the player as such. The resource is keyed on its URL without the fragment, so that `a.mp4#t=10` and `a.mp4` share it. The internal blob URL of a srcObject Blob is revoked once the fetcher has claimed the blob. The events of the reader map onto the media element: - The metadata of the resource sets the input size and seekability of the player, before the first data and only then, with the size first, since the OpenHarmony player reads both once. The reader reports the metadata again once it learns the length of a resource of unknown length, which the player learns as well. A CORS-cross-origin response makes the media data not origin-clean until the resource fetch algorithm runs again, as before. - Progress, which the reader reports at most every 350 ms, fires a progress event while the download is not suspended. - A suspended download sets the networkState to NETWORK_IDLE and fires suspend, and a resumed one sets it back to NETWORK_LOADING. When the download is suspended for preload=metadata, before playback was requested, the element stops delaying the load event, as the spec asks for a download suspended until the user starts playback. - Once the whole resource is cached, progress, NETWORK_IDLE and suspend follow. - An error before the media engine has the metadata runs the media data processing failure steps, which try the next source, and later, or for a resource that changed between two responses, the fatal steps with MEDIA_ERR_NETWORK, as other browsers do. So does the failure of the first fetch of the element's fetcher. The element tells the reader what it needs: playback at the bitrate of the resource, its length divided by its duration once both are known, while it plays; only the metadata for preload=metadata until playback is requested, unless it autoplays; and otherwise, as while its document is not fully active, what a paused reader keeps. Its reader is closed, also for a player that still holds it, so that the player's reads fail and the fetch stops, by the load algorithm, before the next source, by the failure and fatal steps, when the player goes away, and when its document is unloaded for good or its pipeline exits; documents keep weak references to the media elements that opened a reader for that and for their activity, and an adopted element moves to its new document. While it downloads with a reader, the element has pending activity, which the fetch listener provided before. The cache now owns what the element did for fetches, which goes: BufferedDataSource apart from the position of the push adapter, HTMLMediaElementFetchContext, the fetch listener of the media data, backing off, suspension and its timeout with the pref media_fetch_suspension_timeout_ms, the restarts, the handling of 416, the queue cap and the document registry of suspended fetches. The blob URL that the element kept for the fetches it restarted itself, for a Blob assigned to srcObject, goes too, since nothing reads it any more. Media fetches are no longer in the fetch group of the document. A navigation away from a document with a media download in progress still cancels it, since that makes the document unsalvageable, so that its unloading closes the readers; window.stop() and document.open() no longer cancel media downloads. Fork note: meant for upstream. Drop once upstream has it. Testing: the new mozilla/media-blob-url-revoked-seek.html seeks far into a blob after its URL was revoked (passes 5 of 5; phase 1 fails 5 of 5). fetch/range/non-matching-range-response.html now passes "Range response out of range of request should succeed", and html/browsers/browsing-the-web/read-media/cross-origin-video.html, whose server answers in parts, now plays (3 of 3 runs, 3 of 3 failures with phase 1); their expectations go; the other media, canvas and range tests cover the rest. See Validation for the scenarios that no WPT test covers. Validation: Linux host release builds with GStreamer, against the phase 1 build of ohos-main. `./mach test-wpt --release --timeout-multiplier 2` of html/semantics/embedded-content/media-elements, the-video-element, html/canvas/element/manual/drawing-images-to-the-canvas and imagebitmap (with drawimage_video_crossorigin_seek.sub.html), fetch/range and mozilla/media-autoplay-seek-after-ended.html, 493 tests: apart from the fixed range test, every unexpected result also occurs with the phase 1 build in isolated runs: load-removes-queued-error-event hangs while GStreamer never reports the metadata of the 539-byte sound_0.mp3 (also outside WPT: 8 of 12 runs here, 6 of 12 there), src_object_blob times out (2 of 16 and 3 of 16), seek-to-max-value fails (0 of 3 and 1 of 3), media_fragment_seek fails (3 of 3 either way), and autoplay-default-permissions-policy passes where a timeout is expected; track-cues-seeking, track-mode-disabled and video_loop_base passed 3 of 3 isolated runs on both. Scenarios with a 14 MB, 30 s H.264 file from a local server, requests and MB sent, with and without range support: play 2 / 14.3 and 1 / 14.3 (phase 1: 3 / 26.6 and 3 / 41.6), loop 2 / 14.3 and 1 / 14.3 (3 / 26.1 and 8 / 83.3), seek back 2 / 14.3 and 1 / 14.3 (3 / 25.9 and 3 / 40.1), two elements 2 / 14.3 and 1 / 14.3 (16 / 76.4 and 6 / 85.6), reload 2 / 14.3 and 1 / 14.3 (9 / 77.5 and 9 / 115.7), play again after the end 2 / 14.3 and 1 / 14.3 (3 / 26.0 and 3 / 40.9); the second request with range support reads the last 40 KB, and a loop, a seek back, a second element and a reload need no request. A 150 MB, 40 s file with preload=metadata at full speed: 1 request and 149.7 MB with and without range support (2 / 217.3 and 2 / 272.8); at 25 MB/s, two elements 2 and 1 requests for 149.7 MB (10 requests, 299.7 and 823.8 MB) and a pause of 40 s 1 request (2 / 155.4 with range support). Peak RSS is lower in every scenario, for example 397 instead of 418 MiB for the reload. At 5 MB/s, load() with another source 6 s in and a navigation away close the connection at 6.0 s, as with phase 1; a paused element removed from its document loads up to the read-ahead of a paused reader in the cache, here the whole file, where phase 1 closed the connection after 17 to 24 s. `./mach check` and `./mach check --ohos` pass; `./mach test-unit size_of` passes with HTMLVideoElement down from 1296 to 1200 bytes; `./mach test-tidy` reports only the known rustls advisories. 2026-10-29 sync: upstream's unload cleanup now closes the reader of a kept-alive element; on a DAYU200 the media set of patch 65's validation, with a page that navigates away from a playing video and back, ran without a crash with SpiderMonkey and with QuickJS. AI-assisted: Yes (agent session; implemented, tested and measured by the agent) AI-assisted: Yes (agent session; 2026-10-22 sync -- conflict resolution: the fetch listener this patch removes had upstream's new listener signatures (51d1117, servo#49032) and `LocalName` initiator type (servo#48953), which the fetcher of patch 99 now uses; imports merged next to upstream's `AtomicRefCell` (servo#49087) and `TracedScriptResult` (servo#48855); the patch's -96 bytes of `HTMLVideoElement` applied to upstream's new size (servo#48082). `./mach check` passes at this commit) AI-assisted: Yes (agent session; 2026-10-29 sync -- conflict resolution next to upstream's keep-alive (servo#48979): the keep-alive while the resource downloads moved into upstream's `should_keep_alive`, as patch 65 now extends it; `update_reader_activity` into the split `autoplay` arm; upstream's unload cleanup closes the media reader where it cancelled the fetch, as the rest of this patch does; the removed fetch listener drops upstream's `CorsStatus` edit to it (servo#48748); `HTMLVideoElement` stays at 1168 bytes, measured at this commit with a compile-time probe) Signed-off-by: Jonathan Schwender <[email protected]>
This is more cleanup of FetchMetadata with the reason to have less duplicated information that needs to be serialized/deserialized and allocated. - cors_status now returns CorStatus enum making it much harder to misuse. - Introduce new type ExposedMetadata that has only the fields xmlhttprequest need. This PR changes the behavior of the data_loader test. Testing: WPT tests will find errors (https://github.com/Narfinger/servo/actions/runs/39959524875). --------- Signed-off-by: Narfinger <[email protected]> Signed-off-by: Martin Robinson <[email protected]> Co-authored-by: Martin Robinson <[email protected]>
Every fetch of a media element started out origin-clean, until the headers of its response arrived. A fetch that restarts the fetch of the same media resource, after a seek or once the player needs data again, therefore made a video that was fetched in no-cors mode from another origin count as origin-clean for as long as the server took to answer, so that drawing it to a canvas or into an ImageBitmap did not taint them. Start such a fetch with the origin-clean flag of the fetch that it replaces, and keep the flag false once a response of the resource was not CORS-same-origin. A new resource selection still starts with a fresh flag. Fork note: meant for upstream. Drop once upstream has it. Testing: a new WPT test draws a video from another origin, fetched without CORS, to a canvas while it seeks, from a server that delays its answer to a range request that starts past byte 0. Validation: the new test fails in 3 of 3 runs without this patch, where getImageData returns the pixels of the video while it seeks, and passes in 3 of 3 with it. drawing-images-to-the-canvas and imagebitmap (43 tests): on ohos-main only the new test fails, and all pass with the series. `./mach test-wpt --release --processes 6 --timeout-multiplier 2` of html/semantics/embedded-content/media-elements, the-video-element, and html/canvas/element/manual/drawing-images-to-the-canvas and imagebitmap (475 tests) with the series up to the last patch: no new failure; the unexpected results (media_fragment_seek, autoplay-default-permissions-policy, load-removes-queued-error-event) also occur on ohos-main. `./mach check --ohos` passes. AI-assisted: Yes (agent session; written and tested by the agent) AI-assisted: Yes (agent session; 2026-10-29 sync -- mechanical conflict resolution: the response's origin-clean flag now comes from upstream's `CorsStatus` (servo#48748), no semantic change) Signed-off-by: Jonathan Schwender <[email protected]>
…r is full When its player has enough data, a media element cancels a fetch with range support, to restart it with a Range request once the player needs data again, and keeps queueing the data of a fetch without range support, up to 32 MiB, before it cancels it and fetches the resource from its start again. Every restart costs a request, on HTTP/1.1 a new connection, and the bytes that were in flight. Ask net to suspend a fetch that is read from the network instead, and queue the data that was in flight. Net answers whether it suspended the fetch. If it did, flow control holds back the server, the download is suspended (NETWORK_IDLE and suspend, then NETWORK_LOADING once it resumes, and no progress events meanwhile), and once the player needs data, the same fetch resumes and the queue drains. If it did not, as for a cache hit or when two fetches to the origin are suspended already, the fetch backs off as before; so it does if the answer is lost, and it is resumed in case net suspended it. Responses that are not read from the network are handled as before, and the cap on the queue stays for data that keeps arriving. When a fetch completes, progress, then NETWORK_IDLE and suspend follow, also if the fetch was suspended. A fetch with range support that stays suspended for media_fetch_suspension_timeout_ms (30 s) is cancelled, to restart where the player stopped once it needs data again, so that an element paused for long does not hold a connection, which servers would time out anyway. A fetch without range support stays suspended, since its restart would fetch the resource from its start again, until net gives up on it after network_fetch_suspend_timeout_ms (60 s). Such a server, and net, end the fetch: net with a network error, which ran the fatal steps (MEDIA_ERR_NETWORK, "If the connection is interrupted after some media data has been received"), and a closed connection like a complete body, so the stream ended early. So if a fetch that was suspended ends with a network error, or with fewer bytes than its Content-Length, restart it at the byte where the player stopped, with a Range request, which a server without range support answers from the start of the resource, whose bytes before that position are discarded as after a seek: at once if the player accepts data, or else once it needs data again. A restart past the end of the resource, which the server answers with 416 or which the length of the resource tells, ends the stream, as when the server's Content-Length was too large; so does a restart without range support whose body ends without an error where the player stopped. Any other restart that ends early before it delivers data runs the fatal steps: net ends a body that loses its connection without an error. A restart that delivered data may be restarted again, so a fetch is only restarted while it makes progress. The Content-Length of an encoded body is not the length of the decoded body, so it is not compared. The state of the suspension in the fetch context grows HTMLVideoElement from 1264 to 1296 bytes. Fork note: meant for upstream. Drop once upstream has it. Testing: no test; a fetch only backs off once the 50 MiB queue of the GStreamer player is full. See Validation. Validation: Linux, GStreamer, a 150 MB, 40 s H.264 file in a muted <video preload=metadata> that plays, from a Python server that sends at most 25 MB/s per connection; the base is the parent commit. With range support: 1 request and 149.7 MB sent (base: 3 requests, 149.9 MB); networkState turns NETWORK_IDLE with a suspend event once net confirms the suspension 3.5 s in, and NETWORK_LOADING when the fetch resumes 17.4 s in, with no seeking, stalled or error event. Without range support: 1 request, 149.7 MB, peak RSS 422 MiB (base: 2 requests, 269.9 MB, 419 MiB); paused for 25 s, 1 request, 149.7 MB (base: 2 requests, 269.9 MB). Paused for 40 s with range support: the timeout cancels the fetch 30 s after the suspension, and the restart when playback needs data again plays to the end: 2 requests, 155.4 MB (base: 3 requests, 149.9 MB). Three elements on one origin: net suspends two fetches, which take 1 request each, and the third backs off when net declines its suspension: 4 requests, 449.1 MB (base: 9 requests, 449.8 MB). A suspension costs peak RSS (423 instead of 392 MiB for one element, 738 instead of 683 MiB for three), although only 53 bytes were queued when net confirmed it: once the fetch resumes, net reads at once what the socket buffers held. A server that closes a connection it could not write to for 5 s: the earlier revision of this patch without the restart ended playback after 16.5 s of the media, with no error; with it, the media plays to the end, in 3 requests and 149.7 MB with range support and 2 requests and 238.3 MB without. With network_fetch_suspend_timeout_ms=5000 and playback paused for 40 s, net ends the suspended fetch with a network error, and the media plays to the end after the restart: 3 requests and 156.9 MB with range support, 2 requests and 239.1 MB without, no error event. A server whose Content-Length is 10 MB too large: playback ends normally, as on the base; at 25 MB/s the restart fetches the 10.5 MB that were queued again (2 requests, 160.2 MB) and, without range support, the whole resource again (2 requests, 299.3 MB); at 8 and 12 MB/s the restart starts at the end of the file, which the server answers with 416 (2 requests, 149.7 MB). A server that closes idle connections and closes the restart right after its headers: MEDIA_ERR_NETWORK at the restart, 16.5 s into the media, with and without range support. `./mach test-wpt --release --processes 6 --timeout-multiplier 2` html/semantics/embedded-content/media-elements, the-video-element and html/canvas/element/manual/drawing-images-to-the-canvas with the series: 451 tests, 446 as expected; the other five behave the same on the parent commit of the series when run alone: autoplay-default-permissions-policy.https.sub.html passes where a timeout is expected (3/3 on both), media_fragment_seek.html fails a subtest (3/3 on both), src_object_blob.html times out 1 of 3 runs on both, video_timeupdate_on_seek.html passes a subtest that is expected to time out, and load-removes-queued-error-event.html hangs intermittently because GStreamer never reports the metadata of the 539-byte sound_0.mp3 (3 of 8 runs with the series, 4 of 8 without, alternating). In a later run of media-elements, track-cues-seeking.html timed out, which it does intermittently with and without the series (3 of 39 and 2 of 39 isolated runs, alternating); its 192 KB video never fills the player. `./mach check --ohos` passes at each commit; `./mach test-tidy` reports only the known rustls advisories. AI-assisted: Yes (agent session; implemented, tested and measured by the agent) AI-assisted: Yes (agent session; 2026-10-22 sync -- mechanical conflict resolution: the `media_fetch_suspension_timeout_ms` pref where upstream removed the `layout_unimplemented`, variable-fonts and writing-mode prefs (servo#48915), and the patch's +32 bytes of `HTMLVideoElement` applied to upstream's new size (servo#48082)) AI-assisted: Yes (agent session; 2026-10-22 sync -- compile fix folded in: the two early returns for a fetch that ended early pass the fetch listener's global to `submit_timing`, which takes it since upstream 51d1117 (servo#49032)) AI-assisted: Yes (agent session; 2026-10-29 sync -- mechanical conflict resolution: the pref next to upstream's `mathml_core_enabled` (servo#48631), the origin-clean line in upstream's `CorsStatus` form (servo#48748); `HTMLVideoElement` is 1256 bytes, measured at this commit with a compile-time probe, since patch 65 no longer adds a field) Signed-off-by: Jonathan Schwender <[email protected]>
The media cache fetches the bytes of a media resource through the Fetcher trait, on any thread, and decides which ranges to request and when to suspend, resume or cancel a fetch. Add the implementation of that trait for media elements. ScriptFetcher builds the request of a media element as the resource fetch algorithm does: destination audio or video, a potential-CORS request for the crossorigin attribute, the document as the client, and the referrer policy of the element. Each fetch copies it and adds a Range header for the byte where it starts and, for a request after the first, If-Range with the validator of the first response. It starts the fetch with fetch_async, so that the response arrives on the FetchThread of the content process rather than on the script thread, and controls it through a FetchController: a suspension carries a reply that tells the cache whether net suspended the fetch, and cancelling or dropping the handle aborts it. The response is classified for the cache: whether it is a 206 and where its body starts in the resource, the length of the resource from Content-Range or Content-Length, its strong ETag or else its Last-Modified date as the validator, whether it has a Content-Encoding, under which byte positions and lengths do not apply, whether it is CORS-cross-origin, and the origin of its final URL. A 416 ends the fetch as RangeNotSatisfiable, another status that is not a success as Status, a request that CSP, mixed content or a CORS check blocked as Blocked, and any other network error as Network. What only script can do is queued as tasks of the networking task source on the element, which they do not keep alive: CSP violation reports, resource timing entries for every fetch, and the failure steps of the element when the first fetch fails before its response, so that a request that its document blocks fails the element even if the cache serves other readers. The fetcher claims the blob of a blob URL for its lifetime, so that restarts and gap fetches still work after the page revoked the URL, and gives every fetch a token of its own (UrlWithBlobClaim::with_new_token), since net ends the claim of a request's token once that request is done. It accepts only a 200, or a 206 with a valid byte range, as "verify a media response" asks, and answers a suspension that cannot carry a reply as declined. Nothing uses the fetcher yet; the next patch moves the media element to the media cache. Fork note: meant for upstream. Drop once upstream has it. Testing: through the media element in the next patch. Validation: `./mach check` and `./mach check --ohos` pass. See the next patch for WPT and the scenarios. AI-assisted: Yes (agent session; implemented and tested by the agent) AI-assisted: Yes (agent session; 2026-10-22 sync -- compile fix folded in: `InitiatorType::LocalName` takes a `LocalName` since upstream 9abaf60 (servo#48953), and 51d1117 (servo#49032) removed `ResourceTimingListener::resource_timing_global`, so the timing of a media fetch goes to `submit_timing` with the global of the element's document, which that method returned) AI-assisted: Yes (agent session; 2026-10-29 sync -- compile fix: `FetchMetadata::is_cors_cross_origin()` became `cors_status()` (servo#48748), so the fetcher compares it with `CorsStatus::Unsafe`) AI-assisted: Yes (agent session; 2026-11-09 sync -- import next to upstream's blob URL keep-alive import (servo#49206)) Signed-off-by: Jonathan Schwender <[email protected]>
A media element fetched its media resource itself and pushed each chunk into the player as it arrived. To keep the player from being flooded, it backed off, suspended the fetch, cancelled it after a timeout, and restarted it where the player had stopped, after a lost connection, a 416 or a seek, with a cap on the bytes it queued and a document registry to cancel suspended fetches that nothing would resume. A loop on a backend without its own buffer, a second element and a reload of the same resource downloaded it again. In the resource fetch algorithm, the element now opens a reader of the media resource in the media cache of the content process instead, keyed by the requested URL, the CORS mode and the origin of the document, with a ScriptFetcher for the fetches that the cache needs. Blob and data URLs take the same path; MediaStream sources are unchanged, and preload=none still opens no reader until the media resource is needed. If the player accepts the reader as its data source, it reads from it. Otherwise the element pushes the data of the reader into the player: once the player needs data, it reads 64 KiB chunks from the byte where the player stopped and pushes them until the player has enough, when the refused chunk is read again later, or until the reader has no data there yet, when the waker of the reader continues; at most 1 MiB per task, so that cached data does not block the script thread. SeekData moves that position, and the end of the stream reaches the player as such. The resource is keyed on its URL without the fragment, so that `a.mp4#t=10` and `a.mp4` share it. The internal blob URL of a srcObject Blob is revoked once the fetcher has claimed the blob. The events of the reader map onto the media element: - The metadata of the resource sets the input size and seekability of the player, before the first data and only then, with the size first, since the OpenHarmony player reads both once. The reader reports the metadata again once it learns the length of a resource of unknown length, which the player learns as well. A CORS-cross-origin response makes the media data not origin-clean until the resource fetch algorithm runs again, as before. - Progress, which the reader reports at most every 350 ms, fires a progress event while the download is not suspended. - A suspended download sets the networkState to NETWORK_IDLE and fires suspend, and a resumed one sets it back to NETWORK_LOADING. When the download is suspended for preload=metadata, before playback was requested, the element stops delaying the load event, as the spec asks for a download suspended until the user starts playback. - Once the whole resource is cached, progress, NETWORK_IDLE and suspend follow. - An error before the media engine has the metadata runs the media data processing failure steps, which try the next source, and later, or for a resource that changed between two responses, the fatal steps with MEDIA_ERR_NETWORK, as other browsers do. So does the failure of the first fetch of the element's fetcher. The element tells the reader what it needs: playback at the bitrate of the resource, its length divided by its duration once both are known, while it plays; only the metadata for preload=metadata until playback is requested, unless it autoplays; and otherwise, as while its document is not fully active, what a paused reader keeps. Its reader is closed, also for a player that still holds it, so that the player's reads fail and the fetch stops, by the load algorithm, before the next source, by the failure and fatal steps, when the player goes away, and when its document is unloaded for good or its pipeline exits; documents keep weak references to the media elements that opened a reader for that and for their activity, and an adopted element moves to its new document. While it downloads with a reader, the element has pending activity, which the fetch listener provided before. The cache now owns what the element did for fetches, which goes: BufferedDataSource apart from the position of the push adapter, HTMLMediaElementFetchContext, the fetch listener of the media data, backing off, suspension and its timeout with the pref media_fetch_suspension_timeout_ms, the restarts, the handling of 416, the queue cap and the document registry of suspended fetches. The blob URL that the element kept for the fetches it restarted itself, for a Blob assigned to srcObject, goes too, since nothing reads it any more. Media fetches are no longer in the fetch group of the document. A navigation away from a document with a media download in progress still cancels it, since that makes the document unsalvageable, so that its unloading closes the readers; window.stop() and document.open() no longer cancel media downloads. Fork note: meant for upstream. Drop once upstream has it. Testing: the new mozilla/media-blob-url-revoked-seek.html seeks far into a blob after its URL was revoked (passes 5 of 5; phase 1 fails 5 of 5). fetch/range/non-matching-range-response.html now passes "Range response out of range of request should succeed", and html/browsers/browsing-the-web/read-media/cross-origin-video.html, whose server answers in parts, now plays (3 of 3 runs, 3 of 3 failures with phase 1); their expectations go; the other media, canvas and range tests cover the rest. See Validation for the scenarios that no WPT test covers. Validation: Linux host release builds with GStreamer, against the phase 1 build of ohos-main. `./mach test-wpt --release --timeout-multiplier 2` of html/semantics/embedded-content/media-elements, the-video-element, html/canvas/element/manual/drawing-images-to-the-canvas and imagebitmap (with drawimage_video_crossorigin_seek.sub.html), fetch/range and mozilla/media-autoplay-seek-after-ended.html, 493 tests: apart from the fixed range test, every unexpected result also occurs with the phase 1 build in isolated runs: load-removes-queued-error-event hangs while GStreamer never reports the metadata of the 539-byte sound_0.mp3 (also outside WPT: 8 of 12 runs here, 6 of 12 there), src_object_blob times out (2 of 16 and 3 of 16), seek-to-max-value fails (0 of 3 and 1 of 3), media_fragment_seek fails (3 of 3 either way), and autoplay-default-permissions-policy passes where a timeout is expected; track-cues-seeking, track-mode-disabled and video_loop_base passed 3 of 3 isolated runs on both. Scenarios with a 14 MB, 30 s H.264 file from a local server, requests and MB sent, with and without range support: play 2 / 14.3 and 1 / 14.3 (phase 1: 3 / 26.6 and 3 / 41.6), loop 2 / 14.3 and 1 / 14.3 (3 / 26.1 and 8 / 83.3), seek back 2 / 14.3 and 1 / 14.3 (3 / 25.9 and 3 / 40.1), two elements 2 / 14.3 and 1 / 14.3 (16 / 76.4 and 6 / 85.6), reload 2 / 14.3 and 1 / 14.3 (9 / 77.5 and 9 / 115.7), play again after the end 2 / 14.3 and 1 / 14.3 (3 / 26.0 and 3 / 40.9); the second request with range support reads the last 40 KB, and a loop, a seek back, a second element and a reload need no request. A 150 MB, 40 s file with preload=metadata at full speed: 1 request and 149.7 MB with and without range support (2 / 217.3 and 2 / 272.8); at 25 MB/s, two elements 2 and 1 requests for 149.7 MB (10 requests, 299.7 and 823.8 MB) and a pause of 40 s 1 request (2 / 155.4 with range support). Peak RSS is lower in every scenario, for example 397 instead of 418 MiB for the reload. At 5 MB/s, load() with another source 6 s in and a navigation away close the connection at 6.0 s, as with phase 1; a paused element removed from its document loads up to the read-ahead of a paused reader in the cache, here the whole file, where phase 1 closed the connection after 17 to 24 s. `./mach check` and `./mach check --ohos` pass; `./mach test-unit size_of` passes with HTMLVideoElement down from 1296 to 1200 bytes; `./mach test-tidy` reports only the known rustls advisories. 2026-10-29 sync: upstream's unload cleanup now closes the reader of a kept-alive element; on a DAYU200 the media set of patch 65's validation, with a page that navigates away from a playing video and back, ran without a crash with SpiderMonkey and with QuickJS. AI-assisted: Yes (agent session; implemented, tested and measured by the agent) AI-assisted: Yes (agent session; 2026-10-22 sync -- conflict resolution: the fetch listener this patch removes had upstream's new listener signatures (51d1117, servo#49032) and `LocalName` initiator type (servo#48953), which the fetcher of patch 99 now uses; imports merged next to upstream's `AtomicRefCell` (servo#49087) and `TracedScriptResult` (servo#48855); the patch's -96 bytes of `HTMLVideoElement` applied to upstream's new size (servo#48082). `./mach check` passes at this commit) AI-assisted: Yes (agent session; 2026-10-29 sync -- conflict resolution next to upstream's keep-alive (servo#48979): the keep-alive while the resource downloads moved into upstream's `should_keep_alive`, as patch 65 now extends it; `update_reader_activity` into the split `autoplay` arm; upstream's unload cleanup closes the media reader where it cancelled the fetch, as the rest of this patch does; the removed fetch listener drops upstream's `CorsStatus` edit to it (servo#48748); `HTMLVideoElement` stays at 1168 bytes, measured at this commit with a compile-time probe) AI-assisted: Yes (agent session; 2026-11-09 sync -- fetch_request() stays deleted although upstream gave it a blob URL claim (servo#49206): the media cache's fetcher of patch 89 takes the same claim; its imports go with it) Signed-off-by: Jonathan Schwender <[email protected]>
Every fetch of a media element started out origin-clean, until the headers of its response arrived. A fetch that restarts the fetch of the same media resource, after a seek or once the player needs data again, therefore made a video that was fetched in no-cors mode from another origin count as origin-clean for as long as the server took to answer, so that drawing it to a canvas or into an ImageBitmap did not taint them. Start such a fetch with the origin-clean flag of the fetch that it replaces, and keep the flag false once a response of the resource was not CORS-same-origin. A new resource selection still starts with a fresh flag. Fork note: meant for upstream. Drop once upstream has it. Testing: a new WPT test draws a video from another origin, fetched without CORS, to a canvas while it seeks, from a server that delays its answer to a range request that starts past byte 0. Validation: the new test fails in 3 of 3 runs without this patch, where getImageData returns the pixels of the video while it seeks, and passes in 3 of 3 with it. drawing-images-to-the-canvas and imagebitmap (43 tests): on ohos-main only the new test fails, and all pass with the series. `./mach test-wpt --release --processes 6 --timeout-multiplier 2` of html/semantics/embedded-content/media-elements, the-video-element, and html/canvas/element/manual/drawing-images-to-the-canvas and imagebitmap (475 tests) with the series up to the last patch: no new failure; the unexpected results (media_fragment_seek, autoplay-default-permissions-policy, load-removes-queued-error-event) also occur on ohos-main. `./mach check --ohos` passes. AI-assisted: Yes (agent session; written and tested by the agent) AI-assisted: Yes (agent session; 2026-10-29 sync -- mechanical conflict resolution: the response's origin-clean flag now comes from upstream's `CorsStatus` (servo#48748), no semantic change) Signed-off-by: Jonathan Schwender <[email protected]>
…r is full When its player has enough data, a media element cancels a fetch with range support, to restart it with a Range request once the player needs data again, and keeps queueing the data of a fetch without range support, up to 32 MiB, before it cancels it and fetches the resource from its start again. Every restart costs a request, on HTTP/1.1 a new connection, and the bytes that were in flight. Ask net to suspend a fetch that is read from the network instead, and queue the data that was in flight. Net answers whether it suspended the fetch. If it did, flow control holds back the server, the download is suspended (NETWORK_IDLE and suspend, then NETWORK_LOADING once it resumes, and no progress events meanwhile), and once the player needs data, the same fetch resumes and the queue drains. If it did not, as for a cache hit or when two fetches to the origin are suspended already, the fetch backs off as before; so it does if the answer is lost, and it is resumed in case net suspended it. Responses that are not read from the network are handled as before, and the cap on the queue stays for data that keeps arriving. When a fetch completes, progress, then NETWORK_IDLE and suspend follow, also if the fetch was suspended. A fetch with range support that stays suspended for media_fetch_suspension_timeout_ms (30 s) is cancelled, to restart where the player stopped once it needs data again, so that an element paused for long does not hold a connection, which servers would time out anyway. A fetch without range support stays suspended, since its restart would fetch the resource from its start again, until net gives up on it after network_fetch_suspend_timeout_ms (60 s). Such a server, and net, end the fetch: net with a network error, which ran the fatal steps (MEDIA_ERR_NETWORK, "If the connection is interrupted after some media data has been received"), and a closed connection like a complete body, so the stream ended early. So if a fetch that was suspended ends with a network error, or with fewer bytes than its Content-Length, restart it at the byte where the player stopped, with a Range request, which a server without range support answers from the start of the resource, whose bytes before that position are discarded as after a seek: at once if the player accepts data, or else once it needs data again. A restart past the end of the resource, which the server answers with 416 or which the length of the resource tells, ends the stream, as when the server's Content-Length was too large; so does a restart without range support whose body ends without an error where the player stopped. Any other restart that ends early before it delivers data runs the fatal steps: net ends a body that loses its connection without an error. A restart that delivered data may be restarted again, so a fetch is only restarted while it makes progress. The Content-Length of an encoded body is not the length of the decoded body, so it is not compared. The state of the suspension in the fetch context grows HTMLVideoElement from 1264 to 1296 bytes. Fork note: meant for upstream. Drop once upstream has it. Testing: no test; a fetch only backs off once the 50 MiB queue of the GStreamer player is full. See Validation. Validation: Linux, GStreamer, a 150 MB, 40 s H.264 file in a muted <video preload=metadata> that plays, from a Python server that sends at most 25 MB/s per connection; the base is the parent commit. With range support: 1 request and 149.7 MB sent (base: 3 requests, 149.9 MB); networkState turns NETWORK_IDLE with a suspend event once net confirms the suspension 3.5 s in, and NETWORK_LOADING when the fetch resumes 17.4 s in, with no seeking, stalled or error event. Without range support: 1 request, 149.7 MB, peak RSS 422 MiB (base: 2 requests, 269.9 MB, 419 MiB); paused for 25 s, 1 request, 149.7 MB (base: 2 requests, 269.9 MB). Paused for 40 s with range support: the timeout cancels the fetch 30 s after the suspension, and the restart when playback needs data again plays to the end: 2 requests, 155.4 MB (base: 3 requests, 149.9 MB). Three elements on one origin: net suspends two fetches, which take 1 request each, and the third backs off when net declines its suspension: 4 requests, 449.1 MB (base: 9 requests, 449.8 MB). A suspension costs peak RSS (423 instead of 392 MiB for one element, 738 instead of 683 MiB for three), although only 53 bytes were queued when net confirmed it: once the fetch resumes, net reads at once what the socket buffers held. A server that closes a connection it could not write to for 5 s: the earlier revision of this patch without the restart ended playback after 16.5 s of the media, with no error; with it, the media plays to the end, in 3 requests and 149.7 MB with range support and 2 requests and 238.3 MB without. With network_fetch_suspend_timeout_ms=5000 and playback paused for 40 s, net ends the suspended fetch with a network error, and the media plays to the end after the restart: 3 requests and 156.9 MB with range support, 2 requests and 239.1 MB without, no error event. A server whose Content-Length is 10 MB too large: playback ends normally, as on the base; at 25 MB/s the restart fetches the 10.5 MB that were queued again (2 requests, 160.2 MB) and, without range support, the whole resource again (2 requests, 299.3 MB); at 8 and 12 MB/s the restart starts at the end of the file, which the server answers with 416 (2 requests, 149.7 MB). A server that closes idle connections and closes the restart right after its headers: MEDIA_ERR_NETWORK at the restart, 16.5 s into the media, with and without range support. `./mach test-wpt --release --processes 6 --timeout-multiplier 2` html/semantics/embedded-content/media-elements, the-video-element and html/canvas/element/manual/drawing-images-to-the-canvas with the series: 451 tests, 446 as expected; the other five behave the same on the parent commit of the series when run alone: autoplay-default-permissions-policy.https.sub.html passes where a timeout is expected (3/3 on both), media_fragment_seek.html fails a subtest (3/3 on both), src_object_blob.html times out 1 of 3 runs on both, video_timeupdate_on_seek.html passes a subtest that is expected to time out, and load-removes-queued-error-event.html hangs intermittently because GStreamer never reports the metadata of the 539-byte sound_0.mp3 (3 of 8 runs with the series, 4 of 8 without, alternating). In a later run of media-elements, track-cues-seeking.html timed out, which it does intermittently with and without the series (3 of 39 and 2 of 39 isolated runs, alternating); its 192 KB video never fills the player. `./mach check --ohos` passes at each commit; `./mach test-tidy` reports only the known rustls advisories. AI-assisted: Yes (agent session; implemented, tested and measured by the agent) AI-assisted: Yes (agent session; 2026-10-22 sync -- mechanical conflict resolution: the `media_fetch_suspension_timeout_ms` pref where upstream removed the `layout_unimplemented`, variable-fonts and writing-mode prefs (servo#48915), and the patch's +32 bytes of `HTMLVideoElement` applied to upstream's new size (servo#48082)) AI-assisted: Yes (agent session; 2026-10-22 sync -- compile fix folded in: the two early returns for a fetch that ended early pass the fetch listener's global to `submit_timing`, which takes it since upstream 51d1117 (servo#49032)) AI-assisted: Yes (agent session; 2026-10-29 sync -- mechanical conflict resolution: the pref next to upstream's `mathml_core_enabled` (servo#48631), the origin-clean line in upstream's `CorsStatus` form (servo#48748); `HTMLVideoElement` is 1256 bytes, measured at this commit with a compile-time probe, since patch 65 no longer adds a field) Signed-off-by: Jonathan Schwender <[email protected]>
The media cache fetches the bytes of a media resource through the Fetcher trait, on any thread, and decides which ranges to request and when to suspend, resume or cancel a fetch. Add the implementation of that trait for media elements. ScriptFetcher builds the request of a media element as the resource fetch algorithm does: destination audio or video, a potential-CORS request for the crossorigin attribute, the document as the client, and the referrer policy of the element. Each fetch copies it and adds a Range header for the byte where it starts and, for a request after the first, If-Range with the validator of the first response. It starts the fetch with fetch_async, so that the response arrives on the FetchThread of the content process rather than on the script thread, and controls it through a FetchController: a suspension carries a reply that tells the cache whether net suspended the fetch, and cancelling or dropping the handle aborts it. The response is classified for the cache: whether it is a 206 and where its body starts in the resource, the length of the resource from Content-Range or Content-Length, its strong ETag or else its Last-Modified date as the validator, whether it has a Content-Encoding, under which byte positions and lengths do not apply, whether it is CORS-cross-origin, and the origin of its final URL. A 416 ends the fetch as RangeNotSatisfiable, another status that is not a success as Status, a request that CSP, mixed content or a CORS check blocked as Blocked, and any other network error as Network. What only script can do is queued as tasks of the networking task source on the element, which they do not keep alive: CSP violation reports, resource timing entries for every fetch, and the failure steps of the element when the first fetch fails before its response, so that a request that its document blocks fails the element even if the cache serves other readers. The fetcher claims the blob of a blob URL for its lifetime, so that restarts and gap fetches still work after the page revoked the URL, and gives every fetch a token of its own (UrlWithBlobClaim::with_new_token), since net ends the claim of a request's token once that request is done. It accepts only a 200, or a 206 with a valid byte range, as "verify a media response" asks, and answers a suspension that cannot carry a reply as declined. Nothing uses the fetcher yet; the next patch moves the media element to the media cache. Fork note: meant for upstream. Drop once upstream has it. Testing: through the media element in the next patch. Validation: `./mach check` and `./mach check --ohos` pass. See the next patch for WPT and the scenarios. AI-assisted: Yes (agent session; implemented and tested by the agent) AI-assisted: Yes (agent session; 2026-10-22 sync -- compile fix folded in: `InitiatorType::LocalName` takes a `LocalName` since upstream 9abaf60 (servo#48953), and 51d1117 (servo#49032) removed `ResourceTimingListener::resource_timing_global`, so the timing of a media fetch goes to `submit_timing` with the global of the element's document, which that method returned) AI-assisted: Yes (agent session; 2026-10-29 sync -- compile fix: `FetchMetadata::is_cors_cross_origin()` became `cors_status()` (servo#48748), so the fetcher compares it with `CorsStatus::Unsafe`) AI-assisted: Yes (agent session; 2026-11-09 sync -- import next to upstream's blob URL keep-alive import (servo#49206)) Signed-off-by: Jonathan Schwender <[email protected]>
A media element fetched its media resource itself and pushed each chunk into the player as it arrived. To keep the player from being flooded, it backed off, suspended the fetch, cancelled it after a timeout, and restarted it where the player had stopped, after a lost connection, a 416 or a seek, with a cap on the bytes it queued and a document registry to cancel suspended fetches that nothing would resume. A loop on a backend without its own buffer, a second element and a reload of the same resource downloaded it again. In the resource fetch algorithm, the element now opens a reader of the media resource in the media cache of the content process instead, keyed by the requested URL, the CORS mode and the origin of the document, with a ScriptFetcher for the fetches that the cache needs. Blob and data URLs take the same path; MediaStream sources are unchanged, and preload=none still opens no reader until the media resource is needed. If the player accepts the reader as its data source, it reads from it. Otherwise the element pushes the data of the reader into the player: once the player needs data, it reads 64 KiB chunks from the byte where the player stopped and pushes them until the player has enough, when the refused chunk is read again later, or until the reader has no data there yet, when the waker of the reader continues; at most 1 MiB per task, so that cached data does not block the script thread. SeekData moves that position, and the end of the stream reaches the player as such. The resource is keyed on its URL without the fragment, so that `a.mp4#t=10` and `a.mp4` share it. The internal blob URL of a srcObject Blob is revoked once the fetcher has claimed the blob. The events of the reader map onto the media element: - The metadata of the resource sets the input size and seekability of the player, before the first data and only then, with the size first, since the OpenHarmony player reads both once. The reader reports the metadata again once it learns the length of a resource of unknown length, which the player learns as well. A CORS-cross-origin response makes the media data not origin-clean until the resource fetch algorithm runs again, as before. - Progress, which the reader reports at most every 350 ms, fires a progress event while the download is not suspended. - A suspended download sets the networkState to NETWORK_IDLE and fires suspend, and a resumed one sets it back to NETWORK_LOADING. When the download is suspended for preload=metadata, before playback was requested, the element stops delaying the load event, as the spec asks for a download suspended until the user starts playback. - Once the whole resource is cached, progress, NETWORK_IDLE and suspend follow. - An error before the media engine has the metadata runs the media data processing failure steps, which try the next source, and later, or for a resource that changed between two responses, the fatal steps with MEDIA_ERR_NETWORK, as other browsers do. So does the failure of the first fetch of the element's fetcher. The element tells the reader what it needs: playback at the bitrate of the resource, its length divided by its duration once both are known, while it plays; only the metadata for preload=metadata until playback is requested, unless it autoplays; and otherwise, as while its document is not fully active, what a paused reader keeps. Its reader is closed, also for a player that still holds it, so that the player's reads fail and the fetch stops, by the load algorithm, before the next source, by the failure and fatal steps, when the player goes away, and when its document is unloaded for good or its pipeline exits; documents keep weak references to the media elements that opened a reader for that and for their activity, and an adopted element moves to its new document. While it downloads with a reader, the element has pending activity, which the fetch listener provided before. The cache now owns what the element did for fetches, which goes: BufferedDataSource apart from the position of the push adapter, HTMLMediaElementFetchContext, the fetch listener of the media data, backing off, suspension and its timeout with the pref media_fetch_suspension_timeout_ms, the restarts, the handling of 416, the queue cap and the document registry of suspended fetches. The blob URL that the element kept for the fetches it restarted itself, for a Blob assigned to srcObject, goes too, since nothing reads it any more. Media fetches are no longer in the fetch group of the document. A navigation away from a document with a media download in progress still cancels it, since that makes the document unsalvageable, so that its unloading closes the readers; window.stop() and document.open() no longer cancel media downloads. Fork note: meant for upstream. Drop once upstream has it. Testing: the new mozilla/media-blob-url-revoked-seek.html seeks far into a blob after its URL was revoked (passes 5 of 5; phase 1 fails 5 of 5). fetch/range/non-matching-range-response.html now passes "Range response out of range of request should succeed", and html/browsers/browsing-the-web/read-media/cross-origin-video.html, whose server answers in parts, now plays (3 of 3 runs, 3 of 3 failures with phase 1); their expectations go; the other media, canvas and range tests cover the rest. See Validation for the scenarios that no WPT test covers. Validation: Linux host release builds with GStreamer, against the phase 1 build of ohos-main. `./mach test-wpt --release --timeout-multiplier 2` of html/semantics/embedded-content/media-elements, the-video-element, html/canvas/element/manual/drawing-images-to-the-canvas and imagebitmap (with drawimage_video_crossorigin_seek.sub.html), fetch/range and mozilla/media-autoplay-seek-after-ended.html, 493 tests: apart from the fixed range test, every unexpected result also occurs with the phase 1 build in isolated runs: load-removes-queued-error-event hangs while GStreamer never reports the metadata of the 539-byte sound_0.mp3 (also outside WPT: 8 of 12 runs here, 6 of 12 there), src_object_blob times out (2 of 16 and 3 of 16), seek-to-max-value fails (0 of 3 and 1 of 3), media_fragment_seek fails (3 of 3 either way), and autoplay-default-permissions-policy passes where a timeout is expected; track-cues-seeking, track-mode-disabled and video_loop_base passed 3 of 3 isolated runs on both. Scenarios with a 14 MB, 30 s H.264 file from a local server, requests and MB sent, with and without range support: play 2 / 14.3 and 1 / 14.3 (phase 1: 3 / 26.6 and 3 / 41.6), loop 2 / 14.3 and 1 / 14.3 (3 / 26.1 and 8 / 83.3), seek back 2 / 14.3 and 1 / 14.3 (3 / 25.9 and 3 / 40.1), two elements 2 / 14.3 and 1 / 14.3 (16 / 76.4 and 6 / 85.6), reload 2 / 14.3 and 1 / 14.3 (9 / 77.5 and 9 / 115.7), play again after the end 2 / 14.3 and 1 / 14.3 (3 / 26.0 and 3 / 40.9); the second request with range support reads the last 40 KB, and a loop, a seek back, a second element and a reload need no request. A 150 MB, 40 s file with preload=metadata at full speed: 1 request and 149.7 MB with and without range support (2 / 217.3 and 2 / 272.8); at 25 MB/s, two elements 2 and 1 requests for 149.7 MB (10 requests, 299.7 and 823.8 MB) and a pause of 40 s 1 request (2 / 155.4 with range support). Peak RSS is lower in every scenario, for example 397 instead of 418 MiB for the reload. At 5 MB/s, load() with another source 6 s in and a navigation away close the connection at 6.0 s, as with phase 1; a paused element removed from its document loads up to the read-ahead of a paused reader in the cache, here the whole file, where phase 1 closed the connection after 17 to 24 s. `./mach check` and `./mach check --ohos` pass; `./mach test-unit size_of` passes with HTMLVideoElement down from 1296 to 1200 bytes; `./mach test-tidy` reports only the known rustls advisories. 2026-10-29 sync: upstream's unload cleanup now closes the reader of a kept-alive element; on a DAYU200 the media set of patch 65's validation, with a page that navigates away from a playing video and back, ran without a crash with SpiderMonkey and with QuickJS. AI-assisted: Yes (agent session; implemented, tested and measured by the agent) AI-assisted: Yes (agent session; 2026-10-22 sync -- conflict resolution: the fetch listener this patch removes had upstream's new listener signatures (51d1117, servo#49032) and `LocalName` initiator type (servo#48953), which the fetcher of patch 99 now uses; imports merged next to upstream's `AtomicRefCell` (servo#49087) and `TracedScriptResult` (servo#48855); the patch's -96 bytes of `HTMLVideoElement` applied to upstream's new size (servo#48082). `./mach check` passes at this commit) AI-assisted: Yes (agent session; 2026-10-29 sync -- conflict resolution next to upstream's keep-alive (servo#48979): the keep-alive while the resource downloads moved into upstream's `should_keep_alive`, as patch 65 now extends it; `update_reader_activity` into the split `autoplay` arm; upstream's unload cleanup closes the media reader where it cancelled the fetch, as the rest of this patch does; the removed fetch listener drops upstream's `CorsStatus` edit to it (servo#48748); `HTMLVideoElement` stays at 1168 bytes, measured at this commit with a compile-time probe) AI-assisted: Yes (agent session; 2026-11-09 sync -- fetch_request() stays deleted although upstream gave it a blob URL claim (servo#49206): the media cache's fetcher of patch 89 takes the same claim; its imports go with it) Signed-off-by: Jonathan Schwender <[email protected]>
This is more cleanup of FetchMetadata with the reason to have less duplicated information that needs to be serialized/deserialized and allocated.
This PR changes the behavior of the data_loader test.
Testing: WPT tests will find errors (https://github.com/Narfinger/servo/actions/runs/39959524875).