Truly independent web browser
LibWeb: Keep media elements and source buffers alive to fire events
Zaggy10244f7182ead755
diff --git a/Libraries/LibWeb/HTML/HTMLMediaElement.cpp b/Libraries/LibWeb/HTML/HTMLMediaElement.cppindex a13b64b1b0d..2cd8e26cc56 100644--- a/Libraries/LibWeb/HTML/HTMLMediaElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLMediaElement.cpp@@ -249,13 +249,13 @@ void HTMLMediaElement::initialize_element()// the document is active again.pause_element();- // AD-HOC: Let the fetch stop so that the element can be reclaimed by GC. The fetch callbacks hold a strong- // reference to their media element to ensure that load/error events are fired as expected.+ // AD-HOC: Let the fetch stop while the document is inactive.// FIXME: Add a heuristic to also go idle when enough data is buffered ahead.if (m_remote_fetch_data)m_remote_fetch_data->stream->set_may_idle(true);detach_video_sink_edge();+ update_activity_root();});m_document_observer->set_document_became_active([this]() {@@ -265,6 +265,7 @@ void HTMLMediaElement::initialize_element()m_remote_fetch_data->stream->set_may_idle(m_remote_fetch_data->download_is_suspended);add_current_video_sink();+ update_activity_root();});m_document_observer->set_document_visibility_state_observer([this](VisibilityState visibility_state) {@@ -381,6 +382,7 @@ void HTMLMediaElement::attribute_changed(Utf16FlyString const& name, Optional<Utcontinue_fetching_the_resource_after_an_implementation_defined_event();}update_download_suspension();+ update_activity_root();}}@@ -508,10 +510,10 @@ void HTMLMediaElement::set_decoder_error(Utf16String error_message)m_error = MediaError::create(MediaError::Code::Decode, error_message);// 3. Set the element's networkState attribute to the NETWORK_IDLE value.- m_network_state = NetworkState::Idle;+ set_network_state(NetworkState::Idle);// 4. Set the element's delaying-the-load-event flag to false. This stops delaying the load event.- m_delaying_the_load_event.clear();+ set_delaying_the_load_event(false);// 5. Fire an event named error at the media element.dispatch_event(create_event_for_element(*this, HTML::EventNames::error));@@ -593,6 +595,7 @@ void HTMLMediaElement::set_seeking(bool seeking)m_seeking = seeking;CSS::Invalidation::invalidate_style_after_media_seeking_state_change(*this, seeking);update_download_suspension();+ update_activity_root();}// https://html.spec.whatwg.org/multipage/media.html#dom-media-load@@ -992,7 +995,7 @@ WebIDL::ExceptionOr<void> HTMLMediaElement::load_element()// 9. Set the error attribute to null and the can autoplay flag to true.m_error = nullptr;- m_can_autoplay = true;+ set_can_autoplay(true);// 10. Invoke the media element's resource selection algorithm.select_resource();@@ -1134,7 +1137,7 @@ private:void waiting(GC::Ref<DOM::Node> previous_candidate){// 17. ⌛ Waiting: Set the element's networkState attribute to the NETWORK_NO_SOURCE value.- m_media_element->m_network_state = HTMLMediaElement::NetworkState::NoSource;+ m_media_element->set_network_state(HTMLMediaElement::NetworkState::NoSource);// 18. ⌛ Set the element's show poster flag to true.m_media_element->set_show_poster(true);@@ -1142,7 +1145,7 @@ private:// 19. ⌛ Queue a media element task given the media element to set the element's delaying-the-load-event flag// to false. This stops delaying the load event.m_media_element->queue_a_media_element_task([this](HTMLMediaElement&) {- m_media_element->m_delaying_the_load_event.clear();+ m_media_element->set_delaying_the_load_event(false);});// 20. End the synchronous section, continuing the remaining steps in parallel.@@ -1167,10 +1170,10 @@ private:// 23. ⌛ Set the element's delaying-the-load-event flag back to true (this delays the load event again, in case// it hasn't been fired yet).- m_media_element->m_delaying_the_load_event.emplace(m_media_element->document());+ m_media_element->set_delaying_the_load_event(true);// 24. ⌛ Set the networkState back to NETWORK_LOADING.- m_media_element->m_network_state = HTMLMediaElement::NetworkState::Loading;+ m_media_element->set_network_state(HTMLMediaElement::NetworkState::Loading);// 25. ⌛ Jump back to the find next candidate step above.find_next_candidate(previous_candidate);@@ -1201,13 +1204,13 @@ void HTMLMediaElement::select_resource()void HTMLMediaElement::select_resource_for_current_load(){// 1. Set the element's networkState attribute to the NETWORK_NO_SOURCE value.- m_network_state = NetworkState::NoSource;+ set_network_state(NetworkState::NoSource);// 2. Set the element's show poster flag to true.set_show_poster(true);// 3. Set the media element's delaying-the-load-event flag to true (this delays the load event).- m_delaying_the_load_event.emplace(document());+ set_delaying_the_load_event(true);// 4. Await a stable state, allowing the task that invoked this algorithm to continue. The synchronous section consists of all the remaining// steps of this algorithm until the algorithm says the synchronous section has ended. (Steps in synchronous sections are marked with ⌛.)@@ -1235,17 +1238,17 @@ void HTMLMediaElement::select_resource_for_current_load()// ⌛ Otherwise the media element has no assigned media provider object and has neither a src attribute nor a source element child:else {// 1. ⌛ Set the networkState to NETWORK_EMPTY.- self.m_network_state = NetworkState::Empty;+ self.set_network_state(NetworkState::Empty);// 2. ⌛ Set the element's delaying-the-load-event flag to false. This stops delaying the load event.- self.m_delaying_the_load_event.clear();+ self.set_delaying_the_load_event(false);// 3. End the synchronous section and return.return;}// 7. ⌛ Set the media element's networkState to NETWORK_LOADING.- self.m_network_state = NetworkState::Loading;+ self.set_network_state(NetworkState::Loading);// 8. ⌛ Queue a media element task given the media element to fire an event named loadstart at the media element.self.queue_a_media_element_task([](HTMLMediaElement& self) {@@ -1502,7 +1505,7 @@ void HTMLMediaElement::update_download_suspension()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.set_network_state(NetworkState::Idle);self.dispatch_event(DOM::Event::create(HTML::relevant_global_object(self), HTML::EventNames::suspend));});@@ -1555,7 +1558,7 @@ void HTMLMediaElement::wait_for_an_implementation_defined_event_before_fetching_m_waiting_for_an_implementation_defined_event_to_fetch_the_resource = true;// 1. Set the networkState to NETWORK_IDLE.- m_network_state = NetworkState::Idle;+ set_network_state(NetworkState::Idle);// 2. Queue a media element task given the media element to fire an event named suspend at the element.queue_a_media_element_task([fetch_generation](HTMLMediaElement& self) {@@ -1573,7 +1576,7 @@ void HTMLMediaElement::wait_for_an_implementation_defined_event_before_fetching_|| !self.m_waiting_for_an_implementation_defined_event_to_fetch_the_resource) {return;}- self.m_delaying_the_load_event.clear();+ self.set_delaying_the_load_event(false);});// 4. Wait for the task to be run.@@ -1593,10 +1596,10 @@ void HTMLMediaElement::continue_fetching_the_resource_after_an_implementation_de// 6. Set the element's delaying-the-load-event flag back to true (this delays the load event again, in case it hasn't been fired yet).if (document().readiness() != DocumentReadyState::Complete)- m_delaying_the_load_event.emplace(document());+ set_delaying_the_load_event(true);// 7. Set the networkState to NETWORK_LOADING.- m_network_state = NetworkState::Loading;+ set_network_state(NetworkState::Loading);run_remote_mode_resource_fetch_steps(EntireResource {}, ++m_current_fetch_generation);}@@ -1681,7 +1684,10 @@ void HTMLMediaElement::run_remote_mode_resource_fetch_steps(ByteRange byte_range// 8. Fetch request, with processResponse set to the following steps given response response:Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input { Fetch::Engine::BodyIntent::DeliverStreamToConsumerAgent };- fetch_algorithms_input.process_response = [self = GC::Ref(*this), byte_range = move(byte_range), fetch_generation](auto response) mutable {+ fetch_algorithms_input.process_response = [weak_self = GC::Weak(*this), byte_range = move(byte_range), fetch_generation](auto response) mutable {+ if (!weak_self)+ return;+ GC::Ref self = *weak_self;auto& fetch_data = self->m_remote_fetch_data;auto response_is_cors_cross_origin = response->is_cors_cross_origin();@@ -1837,7 +1843,7 @@ void HTMLMediaElement::load_local_resource(MediaProvider const& media_provider,media_source->set_has_ever_been_attached();// 2. Set the media element's delaying-the-load-event-flag to false.- m_delaying_the_load_event.clear();+ set_delaying_the_load_event(false);// FIXME: 3. If the MediaSource was constructed in a DedicatedWorkerGlobalScope, then setup worker// attachment communication and open the MediaSource:@@ -1859,6 +1865,7 @@ void HTMLMediaElement::load_local_resource(MediaProvider const& media_provider,media_source->set_assigned_to_media_element({}, *this);m_attached_media_source = media_source;+ update_activity_root();set_up_playback_manager_for_local(move(failure_callback));// 4. Set the readyState attribute to "open".@@ -2567,7 +2574,7 @@ void HTMLMediaElement::process_media_data(FetchingStatus fetching_status)return;// Set the networkState to NETWORK_IDLE and fire an event named suspend at the media element.- m_network_state = NetworkState::Idle;+ set_network_state(NetworkState::Idle);dispatch_event(create_event_for_element(*this, HTML::EventNames::suspend));update_ready_state();@@ -2582,7 +2589,7 @@ void HTMLMediaElement::process_media_data(FetchingStatus fetching_status)// 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;+ self.set_network_state(NetworkState::Loading);});// While the load is not suspended (see below), every 350ms (±200ms) or for every byte received, whichever is@@ -2618,10 +2625,10 @@ void HTMLMediaElement::process_media_data(FetchingStatus fetching_status)m_error = MediaError::create(MediaError::Code::Network, "Connection interrupted"_utf16);// 3. Set the element's networkState attribute to the NETWORK_IDLE value.- m_network_state = NetworkState::Idle;+ set_network_state(NetworkState::Idle);// 4. Set the element's delaying-the-load-event flag to false. This stops delaying the load event.- m_delaying_the_load_event.clear();+ set_delaying_the_load_event(false);// 5. Fire an event named error at the media element.dispatch_event(create_event_for_element(*this, HTML::EventNames::error));@@ -2663,7 +2670,7 @@ void HTMLMediaElement::handle_media_source_failure(Span<GC::Ref<WebIDL::Promise>forget_media_resource_specific_tracks();// 3. Set the element's networkState attribute to the NETWORK_NO_SOURCE value.- m_network_state = NetworkState::NoSource;+ set_network_state(NetworkState::NoSource);// 4. Set the element's show poster flag to true.set_show_poster(true);@@ -2681,7 +2688,7 @@ void HTMLMediaElement::handle_media_source_failure(Span<GC::Ref<WebIDL::Promise>reject_pending_play_promises<WebIDL::NotSupportedError>(promises, "Media is not supported"_utf16);// 7. Set the element's delaying-the-load-event flag to false. This stops delaying the load event.- m_delaying_the_load_event.clear();+ set_delaying_the_load_event(false);}// https://w3c.github.io/media-source/#mediasource-detach@@ -2691,6 +2698,7 @@ void HTMLMediaElement::detach_attached_media_source()return;m_attached_media_source->detach_from_media_element({});m_attached_media_source = nullptr;+ update_activity_root();}// https://html.spec.whatwg.org/multipage/media.html#forget-the-media-element's-media-resource-specific-tracks@@ -2741,6 +2749,7 @@ void HTMLMediaElement::set_ready_state(ReadyState ready_state)update_screen_wake_lock();update_representation();update_download_suspension();+ update_activity_root();} };// When the ready state of a media element whose networkState is not NETWORK_EMPTY changes, the user agent must@@ -2774,7 +2783,7 @@ void HTMLMediaElement::set_ready_state(ReadyState ready_state)// https://html.spec.whatwg.org/multipage/media.html#loading-the-media-resource:dom-media-readystate-4// Once the readyState attribute reaches HAVE_CURRENT_DATA, after the loadeddata event has been fired, set the// element's delaying-the-load-event flag to false. This stops delaying the load event.- m_delaying_the_load_event.clear();+ set_delaying_the_load_event(false);// If the new ready state is HAVE_FUTURE_DATA or HAVE_ENOUGH_DATA, then the relevant steps below must then be run also.if (ready_state != ReadyState::HaveFutureData && ready_state != ReadyState::HaveEnoughData)@@ -3103,14 +3112,14 @@ void HTMLMediaElement::play_element()}// 5. Set the media element's can autoplay flag to false.- m_can_autoplay = false;+ set_can_autoplay(false);}// https://html.spec.whatwg.org/multipage/media.html#internal-pause-stepsvoid HTMLMediaElement::pause_element(){// 1. Set the media element's can autoplay flag to false.- m_can_autoplay = false;+ set_can_autoplay(false);// 2. If the media element's paused attribute is false, run the following steps:if (!paused()) {@@ -3366,6 +3375,7 @@ void HTMLMediaElement::set_paused(bool paused)update_representation();CSS::Invalidation::invalidate_style_after_media_paused_state_change(*this, paused);+ update_activity_root();}void HTMLMediaElement::set_ended(bool ended)@@ -3376,6 +3386,7 @@ void HTMLMediaElement::set_ended(bool ended)m_ended = ended;update_screen_wake_lock();+ update_activity_root();}// https://html.spec.whatwg.org/multipage/media.html#dom-media-defaultplaybackrate@@ -3476,6 +3487,68 @@ bool HTMLMediaElement::is_eligible_for_autoplay() constdocument().is_allowed_to_use_feature(DOM::PolicyControlledFeature::Autoplay));}+void HTMLMediaElement::set_network_state(NetworkState network_state)+{+ m_network_state = network_state;+ update_activity_root();+}++void HTMLMediaElement::set_can_autoplay(bool can_autoplay)+{+ m_can_autoplay = can_autoplay;+ update_activity_root();+}++void HTMLMediaElement::set_delaying_the_load_event(bool delaying)+{+ if (delaying)+ m_delaying_the_load_event.emplace(document());+ else+ m_delaying_the_load_event.clear();+ update_activity_root();+}++// https://html.spec.whatwg.org/multipage/media.html#playing-the-media-resource+bool HTMLMediaElement::should_be_kept_alive() const+{+ // Media elements must not stop playing just because all references to them have been removed; only once a media+ // element is in a state where no further audio could ever be played by that element may the element be garbage+ // collected.+ // NB: Playback stops while the node document is not fully active, and resumes only if something reaches the element.+ if (!document().is_fully_active())+ return false;++ // NB: The load may still fire events, and reach the readyState at which the element starts playing.+ if (m_delaying_the_load_event.has_value())+ return true;++ // NB: The fetch may still fire events, e.g. a suspend event whose listener begins playback. An attached+ // MediaSource keeps the networkState at NETWORK_LOADING for as long as it is open, so it does not count.+ if (m_network_state == NetworkState::Loading && !m_attached_media_source)+ return true;++ // NB: After an error, only a new load can fire further events or play, and that needs a reference to the element.+ if (error())+ return false;++ if (seeking())+ return true;++ if (!paused() && !ended())+ return true;++ // NB: Autoplay starts playback once the readyState reaches HAVE_ENOUGH_DATA.+ return is_eligible_for_autoplay() && m_ready_state != ReadyState::HaveEnoughData && m_network_state != NetworkState::Empty;+}++void HTMLMediaElement::update_activity_root()+{+ if (should_be_kept_alive())+ m_activity_root.take(*this);+ else+ m_activity_root.release();+}+// https://html.spec.whatwg.org/multipage/media.html#allowed-to-playbool HTMLMediaElement::is_allowed_to_play() const{diff --git a/Libraries/LibWeb/HTML/HTMLMediaElement.h b/Libraries/LibWeb/HTML/HTMLMediaElement.hindex 60120d7d876..5583c16068b 100644--- a/Libraries/LibWeb/HTML/HTMLMediaElement.h+++ b/Libraries/LibWeb/HTML/HTMLMediaElement.h@@ -17,6 +17,7 @@#include <LibCompositing/DisplayList/DisplayListResourceIds.h>#include <LibCompositing/Video/VideoFrameHold.h>#include <LibCore/Forward.h>+#include <LibGC/ActivityRoot.h>#include <LibGC/RootVector.h>#include <LibGfx/Rect.h>#include <LibJS/Forward.h>@@ -339,6 +340,12 @@ private:bool is_eligible_for_autoplay() const;bool is_allowed_to_play() const;+ void set_network_state(NetworkState);+ void set_can_autoplay(bool);+ void set_delaying_the_load_event(bool);+ bool should_be_kept_alive() const;+ void update_activity_root();+enum class PlaybackDirection : u8 {Forwards,Backwards,@@ -468,6 +475,8 @@ private:// https://html.spec.whatwg.org/multipage/media.html#delaying-the-load-event-flagOptional<DOM::DocumentLoadEventDelayer> m_delaying_the_load_event;+ GC::ActivityRoot m_activity_root;+bool m_running_time_update_event_handler { false };Optional<MonotonicTime> m_last_time_update_event_time;diff --git a/Libraries/LibWeb/MediaSourceExtensions/SourceBuffer.cpp b/Libraries/LibWeb/MediaSourceExtensions/SourceBuffer.cppindex 76b5c350820..02e5f62624f 100644--- a/Libraries/LibWeb/MediaSourceExtensions/SourceBuffer.cpp+++ b/Libraries/LibWeb/MediaSourceExtensions/SourceBuffer.cpp@@ -333,6 +333,15 @@ bool SourceBuffer::updating() constreturn m_updating;}+void SourceBuffer::set_updating(bool updating)+{+ m_updating = updating;+ if (updating)+ m_activity_root.take(*this);+ else+ m_activity_root.release();+}+// https://w3c.github.io/media-source/#dom-sourcebuffer-bufferedGC::Ref<HTML::TimeRanges> SourceBuffer::buffered(){@@ -491,7 +500,7 @@ WebIDL::ExceptionOr<void> SourceBuffer::append_buffer(WebIDL::BufferSourceVarian}// 3. Set the updating attribute to true.- m_updating = true;+ set_updating(true);// 4. Queue a task to fire an event named updatestart at this SourceBuffer object.m_media_source->queue_a_media_source_task(GC::create_function(GC::Heap::the(), [this] {@@ -531,7 +540,7 @@ void SourceBuffer::abort_if_updating(Badge<MediaSource>)abort_buffer_append_algorithm();// 2.2. Set the sourceBuffer.updating attribute to false.- m_updating = false;+ set_updating(false);// 2.3. Queue a task to fire an event named abort at sourceBuffer.m_media_source->queue_a_media_source_task(GC::create_function(GC::Heap::the(), [this] {@@ -567,7 +576,7 @@ WebIDL::ExceptionOr<void> SourceBuffer::abort()abort_buffer_append_algorithm();// 4.2. Set the updating attribute to false.- m_updating = false;+ set_updating(false);// 4.3. Queue a task to fire an event named abort at this SourceBuffer object.m_media_source->queue_a_media_source_task(GC::create_function(GC::Heap::the(), [this] {@@ -724,7 +733,7 @@ void SourceBuffer::run_range_removal(AK::Duration start, AK::Duration end)m_range_removal_running = true;// 3. Set the updating attribute to true.- m_updating = true;+ set_updating(true);// 4. Queue a task to fire an event named updatestart at this SourceBuffer object.m_media_source->queue_a_media_source_task(GC::create_function(heap(), [this] {@@ -761,7 +770,7 @@ void SourceBuffer::finish_range_removal()m_range_removal_running = false;// 7. Set the updating attribute to false.- m_updating = false;+ set_updating(false);// 8. Queue a task to fire an event named update at this SourceBuffer object.m_media_source->queue_a_media_source_task(GC::create_function(heap(), [this] {@@ -781,7 +790,7 @@ void SourceBuffer::run_append_error_algorithm()m_remote_source_buffer->reset_parser_state();// 2. Set the updating attribute to false.- m_updating = false;+ set_updating(false);// 3. Queue a task to fire an event named error at this SourceBuffer object.m_media_source->queue_a_media_source_task(GC::create_function(GC::Heap::the(), [this] {@@ -1094,7 +1103,7 @@ bool SourceBuffer::is_associated_with_an_enabled_or_selected_track() constvoid SourceBuffer::finish_buffer_append(){// 3. Set the updating attribute to false.- m_updating = false;+ set_updating(false);// 4. Queue a task to fire an event named update at this SourceBuffer object.m_media_source->queue_a_media_source_task(GC::create_function(GC::Heap::the(), [this] {diff --git a/Libraries/LibWeb/MediaSourceExtensions/SourceBuffer.h b/Libraries/LibWeb/MediaSourceExtensions/SourceBuffer.hindex 8f5e81f1867..106a63b02c3 100644--- a/Libraries/LibWeb/MediaSourceExtensions/SourceBuffer.h+++ b/Libraries/LibWeb/MediaSourceExtensions/SourceBuffer.h@@ -9,6 +9,7 @@#include <AK/NonnullRefPtr.h>#include <AK/Types.h>+#include <LibGC/ActivityRoot.h>#include <LibMedia/Track.h>#include <LibMediaClient/Forward.h>#include <LibWeb/Bindings/SourceBuffer.h>@@ -116,6 +117,7 @@ private:void finish_range_removal();void update_ready_state_and_duration_after_coded_frame_processing(AK::Duration group_end_timestamp);void finish_buffer_append();+ void set_updating(bool);GC::Ref<MediaSource> m_media_source;NonnullRefPtr<MediaClient::RemoteSourceBuffer> m_remote_source_buffer;@@ -123,6 +125,10 @@ private:// https://w3c.github.io/media-source/#dom-sourcebuffer-updatingbool m_updating { false };+ // NB: The operation's events may still begin playback, so they keep this, its MediaSource and the media element+ // alive.+ GC::ActivityRoot m_activity_root;+// https://w3c.github.io/media-source/#dom-sourcebuffer-timestampoffsetdouble m_timestamp_offset_assigned_by_script { 0 };diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.iniindex 6b7a7b2a7d6..cca0a78b130 100644--- a/Tests/LibWeb/TestConfig.ini+++ b/Tests/LibWeb/TestConfig.ini@@ -138,6 +138,7 @@ Text/input/wpt-import/xhr/send-usp.any.htmlCrash/HTML/media-element-load-with-pending-source-buffer-append.htmlText/input/HTML/HTMLMediaElement-bodyless-response.htmlText/input/HTML/HTMLMediaElement-failed-range-response-after-metadata.html+Text/input/HTML/HTMLMediaElement-gc-during-download.htmlText/input/HTML/HTMLMediaElement-gc-during-load.htmlText/input/HTML/HTMLMediaElement-preload-metadata-suspends-download.htmlText/input/HTML/HTMLMediaElement-seek-past-fetched-data-after-network-error.html@@ -157,6 +158,7 @@ Text/input/HTML/media-source-duration.htmlText/input/HTML/media-source-duration-truncation.htmlText/input/HTML/media-source-ended-cleared-by-seek-after-remove.htmlText/input/HTML/media-source-frame-rate-change.html+Text/input/HTML/media-source-gc-during-append.htmlText/input/HTML/media-source-metadata-after-every-first-initialization-segment.htmlText/input/HTML/media-source-mp4.htmlText/input/HTML/media-source-mp4-byte-stream-parser.htmldiff --git a/Tests/LibWeb/Text/expected/HTML/HTMLMediaElement-gc-after-error-while-eligible-for-autoplay.txt b/Tests/LibWeb/Text/expected/HTML/HTMLMediaElement-gc-after-error-while-eligible-for-autoplay.txtnew file mode 100644index 00000000000..7b8acb4aee0--- /dev/null+++ b/Tests/LibWeb/Text/expected/HTML/HTMLMediaElement-gc-after-error-while-eligible-for-autoplay.txt@@ -0,0 +1 @@+audio collected: truediff --git a/Tests/LibWeb/Text/expected/HTML/HTMLMediaElement-gc-during-download.txt b/Tests/LibWeb/Text/expected/HTML/HTMLMediaElement-gc-during-download.txtnew file mode 100644index 00000000000..0e4299ccbbe--- /dev/null+++ b/Tests/LibWeb/Text/expected/HTML/HTMLMediaElement-gc-during-download.txt@@ -0,0 +1 @@+suspend event fired, networkState=1diff --git a/Tests/LibWeb/Text/expected/HTML/HTMLMediaElement-gc-during-playback.txt b/Tests/LibWeb/Text/expected/HTML/HTMLMediaElement-gc-during-playback.txtnew file mode 100644index 00000000000..e2e937787c0--- /dev/null+++ b/Tests/LibWeb/Text/expected/HTML/HTMLMediaElement-gc-during-playback.txt@@ -0,0 +1 @@+ended event fireddiff --git a/Tests/LibWeb/Text/expected/HTML/media-source-gc-during-append.txt b/Tests/LibWeb/Text/expected/HTML/media-source-gc-during-append.txtnew file mode 100644index 00000000000..e6aa7a329ee--- /dev/null+++ b/Tests/LibWeb/Text/expected/HTML/media-source-gc-during-append.txt@@ -0,0 +1 @@+updateend fired for the second appenddiff --git a/Tests/LibWeb/Text/input/HTML/HTMLMediaElement-gc-after-error-while-eligible-for-autoplay.html b/Tests/LibWeb/Text/input/HTML/HTMLMediaElement-gc-after-error-while-eligible-for-autoplay.htmlnew file mode 100644index 00000000000..3ff0025af54--- /dev/null+++ b/Tests/LibWeb/Text/input/HTML/HTMLMediaElement-gc-after-error-while-eligible-for-autoplay.html@@ -0,0 +1,24 @@+<!DOCTYPE html>+<script>internals.setAutoplayPolicy("allow-audio-and-video");</script>+<script src="../include.js"></script>+<script>+ // An autoplay element whose resource failed can never reach HAVE_ENOUGH_DATA, so it must not be kept alive.++ // NB: This is not done in the async test function, whose suspended frame could keep the element alive.+ function loadUnsupportedAutoplayAudio(onError) {+ const audio = document.createElement("audio");+ audio.autoplay = true;+ audio.src = "../../../Assets/HashSans.woff";+ audio.addEventListener("error", () => onError(), { once: true });+ audio.gcSentinel = true;+ return new WeakRef(audio);+ }++ asyncTest(async done => {+ let weakAudio;+ await new Promise(resolve => weakAudio = loadUnsupportedAutoplayAudio(resolve));+ await collectGarbageUntilCleared([weakAudio]);+ println(`audio collected: ${weakAudio.deref() === undefined}`);+ done();+ });+</script>diff --git a/Tests/LibWeb/Text/input/HTML/HTMLMediaElement-gc-during-download.html b/Tests/LibWeb/Text/input/HTML/HTMLMediaElement-gc-during-download.htmlnew file mode 100644index 00000000000..163669fa9f0--- /dev/null+++ b/Tests/LibWeb/Text/input/HTML/HTMLMediaElement-gc-during-download.html@@ -0,0 +1,54 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ // A media element that nothing else references must stay alive while it is still fetching, even once it is paused+ // with data for the current playback position, since a listener for the events of the fetch could begin playback.++ // NB: This is not done in the async test function, whose suspended frame could keep the element alive.+ function startLoadingUnreferencedAudio(url, onLoadedData, onSuspend) {+ const audio = document.createElement("audio");+ audio.preload = "auto";+ audio.src = url;+ audio.addEventListener("loadeddata", () => onLoadedData(), { once: true });+ audio.addEventListener("suspend", () => onSuspend(audio.networkState));+ }++ asyncTest(async done => {+ const server = httpTestServer();+ // Build a constant-bitrate MP3 of about 64 KiB 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((64 * 1024) / audioFrames.length);+ const media = new Uint8Array(audioFrames.length * repetitions);+ for (let i = 0; i < repetitions; i++)+ media.set(audioFrames, i * audioFrames.length);+ let binary = "";+ for (const byte of media)+ binary += String.fromCharCode(byte);+ const token = `gc-during-download-${crypto.randomUUID()}`;+ const mediaURL = new URL(await server.createEcho("GET", `/${token}.mp3`, {+ status: 200,+ headers: { "Content-Type": "audio/mpeg", "Content-Length": String(media.length), "Cache-Control": "no-store" },+ body: btoa(binary),+ body_encoding: "base64",+ }));+ // The first chunk holds the first frames. The rest is held back until the element has been collected for.+ mediaURL.search = `?chunks=16384&chunk_unblock_tokens=${token}`;+ const unblockURL = new URL(`/unblock/${token}`, mediaURL);+ unblockURL.hostname = uniqueLocalhostHostname("gc-during-download-unblock");++ const loadedData = new Promise(resolve => startLoadingUnreferencedAudio(mediaURL, resolve, networkState => {+ println(`suspend event fired, networkState=${networkState}`);+ done();+ }));+ await loadedData;++ // The element's queued tasks keep it alive while they wait to run, so collect a few times.+ for (let i = 0; i < 5; i++) {+ await internals.gcAsync();+ await new Promise(resolve => setTimeout(resolve, 30));+ }+ await fetch(unblockURL);+ });+</script>diff --git a/Tests/LibWeb/Text/input/HTML/HTMLMediaElement-gc-during-playback.html b/Tests/LibWeb/Text/input/HTML/HTMLMediaElement-gc-during-playback.htmlnew file mode 100644index 00000000000..a926e26ddb0--- /dev/null+++ b/Tests/LibWeb/Text/input/HTML/HTMLMediaElement-gc-during-playback.html@@ -0,0 +1,31 @@+<!DOCTYPE html>+<script>internals.setAutoplayPolicy("allow-audio-and-video");</script>+<script src="../include.js"></script>+<script>+ // A media element that nothing else references must stay alive while it is playing, so that it can finish.++ // NB: This is not done in the async test function, whose suspended frame could keep the element alive.+ function startPlayingUnreferencedAudio(onPlaying, onEnded) {+ const audio = document.createElement("audio");+ audio.src = "../../../Assets/tone.mp3";+ audio.addEventListener("playing", () => onPlaying(), { once: true });+ audio.addEventListener("ended", () => onEnded());+ audio.play();+ }++ asyncTest(async done => {+ let ended = false;+ const playing = new Promise(resolve => startPlayingUnreferencedAudio(resolve, () => {+ ended = true;+ println("ended event fired");+ done();+ }));+ await playing;++ // The element's queued tasks keep it alive while they wait to run, so collect a few times during playback.+ while (!ended) {+ await internals.gcAsync();+ await new Promise(resolve => setTimeout(resolve, 30));+ }+ });+</script>diff --git a/Tests/LibWeb/Text/input/HTML/media-source-gc-during-append.html b/Tests/LibWeb/Text/input/HTML/media-source-gc-during-append.htmlnew file mode 100644index 00000000000..30107ea9570--- /dev/null+++ b/Tests/LibWeb/Text/input/HTML/media-source-gc-during-append.html@@ -0,0 +1,51 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ // A SourceBuffer that nothing else references must stay alive while it is updating, along with its MediaSource and+ // media element, so that the update can still fire its events.++ // NB: This is not done in the async test function, whose suspended frame could keep the objects alive.+ function startSecondAppendToUnreferencedSourceBuffer(media, onSecondAppendStarted, onSecondUpdateEnd) {+ const video = document.createElement("video");+ const mediaSource = new MediaSource();+ const url = URL.createObjectURL(mediaSource);+ video.src = url;+ mediaSource.addEventListener("sourceopen", () => {+ URL.revokeObjectURL(url);+ const sourceBuffer = mediaSource.addSourceBuffer('video/webm;codecs="vp9"');+ let updateEndCount = 0;+ sourceBuffer.addEventListener("updateend", () => {+ if (++updateEndCount === 2)+ onSecondUpdateEnd();+ });+ // Once the element has data for the current playback position, nothing but an update keeps it alive.+ const loaded = Promise.all([+ new Promise(resolve => video.addEventListener("loadeddata", resolve, { once: true })),+ new Promise(resolve => sourceBuffer.addEventListener("updateend", resolve, { once: true })),+ ]);+ sourceBuffer.appendBuffer(media);+ // Let the tasks that the load queued run, since they keep the objects alive until they do.+ loaded.then(() => setTimeout(() => {+ // A large append keeps the SourceBuffer updating across several collections.+ const repeated = new Uint8Array(media.byteLength * 20);+ for (let i = 0; i < 20; i++)+ repeated.set(new Uint8Array(media), i * media.byteLength);+ sourceBuffer.timestampOffset = 1;+ sourceBuffer.appendBuffer(repeated);+ onSecondAppendStarted();+ }, 50));+ }, { once: true });+ }++ asyncTest(async done => {+ const media = await (await fetch("../../../Assets/vp9-frame-rate-change.webm")).arrayBuffer();+ let secondUpdateEnded = false;+ await new Promise(resolve => startSecondAppendToUnreferencedSourceBuffer(media, () => resolve(), () => {+ secondUpdateEnded = true;+ println("updateend fired for the second append");+ done();+ }));+ while (!secondUpdateEnded)+ await internals.gcAsync();+ });+</script>