Truly independent web browser
LibWeb: Suspend media downloads in the Metadata preload state
Andreas Kling33517246657b
diff --git a/Libraries/LibWeb/HTML/HTMLMediaElement.cpp b/Libraries/LibWeb/HTML/HTMLMediaElement.cppindex 579084b9a7a..3b1806c83b1 100644--- a/Libraries/LibWeb/HTML/HTMLMediaElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLMediaElement.cpp@@ -141,6 +141,8 @@ struct HTMLMediaElement::RemoteFetchData {bool accepts_byte_ranges { false };u64 offset { 0 };bool resource_was_complete { false };+ bool download_is_suspended { false };+ bool may_suspend_after_first_frame { true };~RemoteFetchData(){@@ -202,9 +204,10 @@ void HTMLMediaElement::initialize_element()});m_document_observer->set_document_became_active([this]() {- // AD-HOC: Now that the document is active again, let the stream notify us when to start fetching again.+ // AD-HOC: Now that the document is active again, let the stream notify us when to start fetching again, unless+ // the download is suspended.if (m_remote_fetch_data)- m_remote_fetch_data->stream->set_may_idle(false);+ m_remote_fetch_data->stream->set_may_idle(m_remote_fetch_data->download_is_suspended);add_current_video_sink();});@@ -307,6 +310,7 @@ void HTMLMediaElement::attribute_changed(Utf16FlyString const& name, Optional<Ut// wait_for_an_implementation_defined_event_before_fetching_the_resource().continue_fetching_the_resource_after_an_implementation_defined_event();}+ update_download_suspension();}}@@ -510,6 +514,7 @@ void HTMLMediaElement::set_seeking(bool seeking)return;m_seeking = seeking;CSS::Invalidation::invalidate_style_after_media_seeking_state_change(*this, seeking);+ update_download_suspension();}// https://html.spec.whatwg.org/multipage/media.html#dom-media-load@@ -1347,6 +1352,9 @@ void HTMLMediaElement::load_url_resource(URL::URL const& url_record, Function<vo}));m_remote_fetch_data->failure_callback = move(failure_callback);+ // AD-HOC: If the poster is cleared, that means we've started playing or seeked, so continue the download.+ m_remote_fetch_data->may_suspend_after_first_frame = m_show_poster;+load_remote_resource(EntireResource {});}@@ -1357,6 +1365,89 @@ bool HTMLMediaElement::preload_attribute_is_in_none_state() constreturn preload.has_value() && preload->equals_ignoring_ascii_case(u"none"sv);}+// https://html.spec.whatwg.org/multipage/media.html#attr-media-preload+bool HTMLMediaElement::preload_attribute_is_in_automatic_state() const+{+ // The attribute's empty value default is the Automatic state.+ // NB: The missing value default and invalid value default are the Metadata state, as the spec suggests.+ auto preload = attribute(HTML::AttributeNames::preload);+ return preload.has_value() && (preload->is_empty() || preload->equals_ignoring_ascii_case(u"auto"sv));+}++bool HTMLMediaElement::should_suspend_the_download() const+{+ if (!m_remote_fetch_data || m_remote_fetch_data->resource_was_complete || m_error)+ return false;++ // NB: Once the media has been played, seeked or had its tracks changed, it is likely to be played again, so we+ // keep fetching for the rest of the load. Gecko and Blink do the same.+ if (!m_remote_fetch_data->may_suspend_after_first_frame)+ return false;++ // NB: The Metadata state hints that fetching the resource metadata, and maybe even the first few frames, is+ // reasonable. Once something made us fetch in the None state anyway, the same amount is enough there too.+ if (preload_attribute_is_in_automatic_state())+ return false;++ // NB: A media element that is playing, seeking or about to autoplay needs data regardless of the hint. As with the+ // None state, autoplay that isn't allowed to play doesn't keep the download going.+ if (!paused() || seeking())+ return false;+ if (is_eligible_for_autoplay() && is_allowed_to_play())+ return false;++ return m_ready_state >= ReadyState::HaveCurrentData;+}++// https://html.spec.whatwg.org/multipage/media.html#concept-media-load-resource+void HTMLMediaElement::update_download_suspension()+{+ if (!m_remote_fetch_data)+ return;++ auto should_suspend = should_suspend_the_download();+ if (m_remote_fetch_data->download_is_suspended == should_suspend)+ return;+ m_remote_fetch_data->download_is_suspended = should_suspend;++ // NB: The stream lets any reads that are waiting finish before it stops the fetch, and when the download resumes,+ // it fetches what reads are waiting on. An inactive document's stream stays idle until it becomes active.+ if (document().is_fully_active())+ m_remote_fetch_data->stream->set_may_idle(should_suspend);++ // NB: When the download resumes, processing the next media data sets the networkState back to NETWORK_LOADING.+ if (!should_suspend)+ return;++ // When a media element's download has been suspended, the user agent must queue a media element task given the+ // media element to set the networkState to NETWORK_IDLE and fire an event named suspend at the element.+ queue_a_media_element_task([fetch_data_id = m_remote_fetch_data->id](HTMLMediaElement& self) {+ if (!self.m_remote_fetch_data || self.m_remote_fetch_data->id != fetch_data_id || !self.m_remote_fetch_data->download_is_suspended)+ return;+ self.m_network_state = NetworkState::Idle;+ self.dispatch_event(DOM::Event::create(HTML::relevant_global_object(self), HTML::EventNames::suspend));+ });++ // NB: The spec also stops delaying the load event when a download is suspended, but we only suspend at+ // HAVE_CURRENT_DATA, and reaching that state already stopped delaying it.+}++void HTMLMediaElement::stop_suspending_the_download_after_first_frame()+{+ if (!m_remote_fetch_data)+ return;+ m_remote_fetch_data->may_suspend_after_first_frame = false;+ update_download_suspension();+}++void HTMLMediaElement::stop_suspending_the_download_after_a_track_change()+{+ // NB: The initial track selection happens before the first frame is available, and doesn't count as a change.+ if (m_ready_state < ReadyState::HaveCurrentData)+ return;+ stop_suspending_the_download_after_first_frame();+}+bool HTMLMediaElement::should_wait_for_an_implementation_defined_event_before_fetching_the_resource() const{// INTEROP: This is not specified, but matches Chromium and Firefox. An explicit load() call requests that loading@@ -1837,6 +1928,7 @@ void HTMLMediaElement::set_audio_track_enabled(Badge<AudioTrack>, GC::Ptr<HTML::m_playback_manager->enable_an_audio_track(audio_track->track_in_playback_manager());elsem_playback_manager->disable_an_audio_track(audio_track->track_in_playback_manager());+ stop_suspending_the_download_after_a_track_change();}update_audio_play_state();@@ -1922,6 +2014,7 @@ void HTMLMediaElement::set_selected_video_track(Badge<VideoTrack>, GC::Ptr<HTML:return;m_selected_video_track = video_track;+ stop_suspending_the_download_after_a_track_change();if (video_track) {attach_selected_video_track_sink(video_track->track_in_playback_manager());if (auto* video_element = as_if<HTMLVideoElement>(this)) {@@ -2320,6 +2413,7 @@ void HTMLMediaElement::maybe_complete_remote_fetch()return;// NB: Record the transition before dispatching events, which can synchronously start another load.fetch_data.resource_was_complete = resource_is_complete;+ update_download_suspension();if (resource_is_complete)process_media_data(FetchingStatus::Complete);}@@ -2349,6 +2443,10 @@ void HTMLMediaElement::process_media_data(FetchingStatus fetching_status)// NB: Once an error has been set in the meantime, the network state stays where that error left it.if (self.m_error)return;+ // NB: Data that arrives after we suspended the download only satisfies reads that were already waiting for+ // it, so the download stays suspended.+ if (self.m_remote_fetch_data && self.m_remote_fetch_data->download_is_suspended)+ return;self.m_network_state = NetworkState::Loading;});@@ -2356,12 +2454,14 @@ void HTMLMediaElement::process_media_data(FetchingStatus fetching_status)// least frequent, queue a media element task given the media element to:auto now = MonotonicTime::now();if (!m_last_progress_event_time.has_value() || now - m_last_progress_event_time.value() > AK::Duration::from_milliseconds(350)) {- m_last_progress_event_time = now;- queue_a_media_element_task([](HTMLMediaElement& self) {- // FIXME: 1. Set the element's is currently stalled to false.- // 2. Fire an event named progress at the element.- self.dispatch_event(DOM::Event::create(HTML::relevant_global_object(self), HTML::EventNames::progress));- });+ if (!m_remote_fetch_data || !m_remote_fetch_data->download_is_suspended) {+ m_last_progress_event_time = now;+ queue_a_media_element_task([](HTMLMediaElement& self) {+ // FIXME: 1. Set the element's is currently stalled to false.+ // 2. Fire an event named progress at the element.+ self.dispatch_event(DOM::Event::create(HTML::relevant_global_object(self), HTML::EventNames::progress));+ });+ }update_ready_state();}@@ -2494,6 +2594,7 @@ void HTMLMediaElement::set_ready_state(ReadyState ready_state)upon_has_ended_playback_possibly_changed();update_screen_wake_lock();update_representation();+ update_download_suspension();} };// When the ready state of a media element whose networkState is not NETWORK_EMPTY changes, the user agent must@@ -2605,6 +2706,9 @@ void HTMLMediaElement::set_ready_state(ReadyState ready_state)if (m_show_poster) {set_show_poster(false);time_marches_on();++ // AD-HOC: Playing indicates user interaction that should allow loading data ahead.+ stop_suspending_the_download_after_first_frame();}// Queue a media element task given the element to fire an event named play at the element.@@ -2815,6 +2919,9 @@ void HTMLMediaElement::play_element()if (m_show_poster) {set_show_poster(false);time_marches_on();++ // AD-HOC: Playing indicates user interaction that should allow loading data ahead.+ stop_suspending_the_download_after_first_frame();}// 3. Queue a media element task given the media element to fire an event named play at the element.@@ -2890,6 +2997,9 @@ void HTMLMediaElement::seek_element(double playback_position, MediaSeekMode seek// 1. Set the media element's show poster flag to false.set_show_poster(false);+ // AD-HOC: A seek that clears the poster indicates user interaction that should allow loading data ahead.+ stop_suspending_the_download_after_first_frame();+// 2. If the media element's readyState is HAVE_NOTHING, return.if (m_ready_state == ReadyState::HaveNothing)return;diff --git a/Libraries/LibWeb/HTML/HTMLMediaElement.h b/Libraries/LibWeb/HTML/HTMLMediaElement.hindex 3a756a03c7e..b006eae7823 100644--- a/Libraries/LibWeb/HTML/HTMLMediaElement.h+++ b/Libraries/LibWeb/HTML/HTMLMediaElement.h@@ -231,6 +231,11 @@ private:void load_remote_resource(ByteRange const&);void load_local_resource(MediaProvider const&, ESCAPING Function<void(Utf16String)> failure_callback);bool preload_attribute_is_in_none_state() const;+ bool preload_attribute_is_in_automatic_state() const;+ bool should_suspend_the_download() const;+ void update_download_suspension();+ void stop_suspending_the_download_after_first_frame();+ void stop_suspending_the_download_after_a_track_change();bool should_wait_for_an_implementation_defined_event_before_fetching_the_resource() const;void wait_for_an_implementation_defined_event_before_fetching_the_resource(u32 fetch_generation);void continue_fetching_the_resource_after_an_implementation_defined_event();diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.iniindex ea27ead5998..6acdb22075e 100644--- a/Tests/LibWeb/TestConfig.ini+++ b/Tests/LibWeb/TestConfig.ini@@ -46,6 +46,7 @@ Text/input/wpt-import/picture-in-picture/Text/input/wpt-import/fetch/api/basic/text-utf8.any.htmlCrash/HTML/media-element-load-with-pending-source-buffer-append.htmlText/input/HTML/HTMLMediaElement-failed-range-response-after-metadata.html+Text/input/HTML/HTMLMediaElement-preload-metadata-suspends-download.htmlCrash/HTML/video-track-switch-during-seek.htmlScreenshot/input/media-source-video.htmlText/input/WebAudio/AudioWorklet-global-port.htmldiff --git a/Tests/LibWeb/Text/expected/HTML/HTMLMediaElement-preload-metadata-suspends-download.txt b/Tests/LibWeb/Text/expected/HTML/HTMLMediaElement-preload-metadata-suspends-download.txtnew file mode 100644index 00000000000..ff8651f9b99--- /dev/null+++ b/Tests/LibWeb/Text/expected/HTML/HTMLMediaElement-preload-metadata-suspends-download.txt@@ -0,0 +1,10 @@+seek: readyState is at least HAVE_CURRENT_DATA: true+seek: networkState is NETWORK_IDLE: true+seek: entire resource is buffered: false+seek: fetch stopped+seek: download resumed+play: readyState is at least HAVE_CURRENT_DATA: true+play: networkState is NETWORK_IDLE: true+play: entire resource is buffered: false+play: fetch stopped+play: download resumeddiff --git a/Tests/LibWeb/Text/input/HTML/HTMLMediaElement-preload-metadata-suspends-download.html b/Tests/LibWeb/Text/input/HTML/HTMLMediaElement-preload-metadata-suspends-download.htmlnew file mode 100644index 00000000000..3a4ae989466--- /dev/null+++ b/Tests/LibWeb/Text/input/HTML/HTMLMediaElement-preload-metadata-suspends-download.html@@ -0,0 +1,80 @@+<!DOCTYPE html>+<script>internals.setAutoplayPolicy("allow-audio-and-video");</script>+<script src="../include.js"></script>+<script>+ // A paused media element in the Metadata preload state (the missing value default) suspends its download once it+ // has the current frame, instead of fetching the entire resource. Seeking or playing resumes the download.+ asyncTest(async done => {+ const server = httpTestServer();++ // Build a constant-bitrate MP3 of about 2 MiB by repeating the audio frames of tone.mp3 (all but its leading ID3+ // tag and Info frame).+ const tone = new Uint8Array(await (await fetch(server.getStaticURL("Assets/tone.mp3"))).arrayBuffer());+ const audioFrames = tone.subarray(226);+ const repetitions = Math.ceil((2 * 1024 * 1024) / audioFrames.length);+ const mediaBytes = new Uint8Array(audioFrames.length * repetitions);+ for (let i = 0; i < repetitions; ++i)+ mediaBytes.set(audioFrames, i * audioFrames.length);+ let binary = "";+ for (let i = 0; i < mediaBytes.length; i += 0x8000)+ binary += String.fromCharCode(...mediaBytes.subarray(i, i + 0x8000));+ const body = btoa(binary);++ async function loadUntilSuspended(name) {+ const testID = crypto.randomUUID();+ const mediaURL = new URL(await server.createEcho("GET", `/echo/preload-metadata-${testID}.mp3`, {+ status: 200,+ headers: {+ "Content-Type": "audio/mpeg",+ "Content-Length": String(mediaBytes.length),+ "Cache-Control": "no-store",+ },+ body,+ body_encoding: "base64",+ }));++ // Deliver the head of the resource, then hold the rest back until the download resumes, so that the download+ // is still going on once the current frame is available.+ const token = `preload-metadata-${testID}`;+ const unblockURL = new URL(`/unblock/${token}`, mediaURL);+ unblockURL.hostname = uniqueLocalhostHostname("preload-metadata-unblock");+ mediaURL.search = `?chunks=262144&chunk_unblock_tokens=${token}`;++ const audio = document.createElement("audio");+ audio.src = mediaURL;+ document.body.append(audio);++ await new Promise(resolve => audio.addEventListener("suspend", resolve, { once: true }));+ println(`${name}: readyState is at least HAVE_CURRENT_DATA: ${audio.readyState >= HTMLMediaElement.HAVE_CURRENT_DATA}`);+ println(`${name}: networkState is NETWORK_IDLE: ${audio.networkState === HTMLMediaElement.NETWORK_IDLE}`);+ const bufferedEnd = audio.buffered.length ? audio.buffered.end(audio.buffered.length - 1) : 0;+ println(`${name}: entire resource is buffered: ${bufferedEnd >= audio.duration}`);++ while (internals.mediaElementIsFetching(audio))+ await new Promise(resolve => setTimeout(resolve, 10));+ println(`${name}: fetch stopped`);+ return { audio, unblockURL };+ }++ // Once the held back data is released, a resumed download completes, which fires a progress event.+ async function releaseDataAndWaitForProgress({ audio, unblockURL }, name) {+ const progress = new Promise(resolve => audio.addEventListener("progress", resolve, { once: true }));+ await fetch(unblockURL);+ await progress;+ println(`${name}: download resumed`);+ }++ // Seeking past the buffered data has to fetch it.+ const seeking = await loadUntilSuspended("seek");+ seeking.audio.currentTime = seeking.audio.duration / 2;+ await releaseDataAndWaitForProgress(seeking, "seek");++ // Playing resumes the download.+ const playing = await loadUntilSuspended("play");+ playing.audio.play().catch(() => {});+ await releaseDataAndWaitForProgress(playing, "play");+ playing.audio.pause();++ done();+ });+</script>