Truly independent web browser
LibWeb: Requeue a media element’s pending tasks when it’s adopted
sideshowbarkerf721d9181c54
diff --git a/Libraries/LibWeb/HTML/HTMLMediaElement.cpp b/Libraries/LibWeb/HTML/HTMLMediaElement.cppindex 56bd6c1f621..5fd8e39365f 100644--- a/Libraries/LibWeb/HTML/HTMLMediaElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLMediaElement.cpp@@ -315,16 +315,42 @@ void HTMLMediaElement::finalize()// https://html.spec.whatwg.org/multipage/media.html#queue-a-media-element-taskvoid HTMLMediaElement::queue_a_media_element_task(GC::Ref<GC::Function<void(HTMLMediaElement&)>> steps)+{+ m_pending_media_element_tasks.append({ .key = ++m_next_media_element_task_key, .task_id = {}, .steps = steps });+ queue_pending_media_element_task(m_pending_media_element_tasks.last());+}++void HTMLMediaElement::queue_pending_media_element_task(PendingMediaElementTask& pending_task){// To queue a media element task with a media element element and a series of steps steps, queue an element task on the media element's// media element event task source given element and steps.- queue_an_element_task(media_element_event_task_source(), GC::create_function(GC::Heap::the(), GC::captures(*this, steps), [](auto& self, auto& steps) {+ pending_task.task_id = queue_an_element_task(media_element_event_task_source(), GC::create_function(GC::Heap::the(), GC::captures(*this, pending_task.key), [](auto& self, auto key) {+ // NB: A task that doesn't run here stays pending, so that it can run once the element is adopted into a+ // document that's fully active.if (!self.document().is_fully_active())return;+ auto index = self.m_pending_media_element_tasks.find_first_index_if([key](auto const& pending_task) { return pending_task.key == key; });+ if (!index.has_value())+ return;+ auto steps = self.m_pending_media_element_tasks.take(*index).steps;steps->function()(self);}));}+// NB: Tasks are queued for the document of the element's relevant global object at the time. So once the element is+// adopted, the tasks it still has pending won't run while the old document isn't fully active, and are removed if+// that document is destroyed. Instead, take them out of the queue, and queue them again, in the same order, for+// the document that adopted the element.+void HTMLMediaElement::requeue_pending_media_element_tasks()+{+ main_thread_event_loop().task_queue().remove_tasks_matching([&](auto const& task) {+ return task.source() == media_element_event_task_source()+ && any_of(m_pending_media_element_tasks, [&](auto const& pending_task) { return pending_task.task_id == task.id(); });+ });+ for (auto& pending_task : m_pending_media_element_tasks)+ queue_pending_media_element_task(pending_task);+}+void HTMLMediaElement::visit_edges(Cell::Visitor& visitor){Base::visit_edges(visitor);@@ -335,6 +361,8 @@ void HTMLMediaElement::visit_edges(Cell::Visitor& visitor)visitor.visit(m_list_of_newly_introduced_cues);visitor.visit(m_document_observer);visitor.visit(m_source_element_selector);+ for (auto const& pending_task : m_pending_media_element_tasks)+ visitor.visit(pending_task.steps);visitor.visit(m_pending_play_promises);visitor.visit(m_selected_video_track);visitor.visit(m_attached_media_source);@@ -472,25 +500,13 @@ void HTMLMediaElement::adopted_from(DOM::Document& old_document)// While the delaying-the-load-event flag is true, the element must delay the load event of its document.// NB: The flag delays the load event of the element's current node document, so it follows the element when it is// adopted into another document.- if (m_delaying_the_load_event.has_value()) {+ if (m_delaying_the_load_event.has_value())m_delaying_the_load_event.emplace(document());- // AD-HOC: If the resource selection algorithm was invoked while the element's node document was not fully- // active, its queued media element tasks are associated with the old document and will never run.- // That would leave this element delaying the load event of the document that adopted it forever.- // Drop those stale tasks and re-invoke the resource selection algorithm so that it can proceed with- // tasks associated with the new document. This matches the major engines, where a pending media load- // continues after adoption and delays the new document's load event until it completes. Once a fetch- // is in flight the pending work lives in the fetch machinery rather than in queued media element- // tasks, and the synthesized activity transitions above take care of stopping and resuming it, so- // only restart resource selection when no fetch has begun.- if (!old_document.is_fully_active() && !m_remote_fetch_data) {- main_thread_event_loop().task_queue().remove_tasks_matching([&](auto const& task) {- return task.source() == media_element_event_task_source();- });- select_resource_for_current_load();- }- }+ // NB: So a load that's under way when the element is adopted carries on in the document that adopted it, and+ // delays that document's load event until it's done. Once a fetch is in flight, the activity transitions+ // synthesized above stop and resume it.+ requeue_pending_media_element_tasks();if (m_screen_wake_lock.has_value()) {m_screen_wake_lock.clear();@@ -958,6 +974,7 @@ WebIDL::ExceptionOr<void> HTMLMediaElement::load_element()main_thread_event_loop().task_queue().remove_tasks_matching([&](auto& task) {return task.source() == media_element_event_task_source();});+ m_pending_media_element_tasks.clear();// 6. If the media element's networkState is set to NETWORK_LOADING or NETWORK_IDLE, queue a media element task given the media element to// fire an event named abort at the media element.diff --git a/Libraries/LibWeb/HTML/HTMLMediaElement.h b/Libraries/LibWeb/HTML/HTMLMediaElement.hindex d14747f2107..7c3ab6b324d 100644--- a/Libraries/LibWeb/HTML/HTMLMediaElement.h+++ b/Libraries/LibWeb/HTML/HTMLMediaElement.h@@ -383,6 +383,18 @@ private:// https://html.spec.whatwg.org/multipage/media.html#media-element-event-task-sourceUniqueTaskSource m_media_element_event_task_source;+ // NB: The media element tasks that haven't run yet, in the order they were queued, so that they can follow the+ // element when it's adopted into another document.+ struct PendingMediaElementTask {+ u64 key { 0 };+ TaskID task_id;+ GC::Ref<GC::Function<void(HTMLMediaElement&)>> steps;+ };+ void queue_pending_media_element_task(PendingMediaElementTask&);+ void requeue_pending_media_element_tasks();+ Vector<PendingMediaElementTask> m_pending_media_element_tasks;+ u64 m_next_media_element_task_key { 0 };+// https://html.spec.whatwg.org/multipage/media.html#dom-media-errorGC::Ptr<MediaError> m_error;diff --git a/Tests/LibWeb/Text/expected/HTML/media-source-failure-pending-when-adopted.txt b/Tests/LibWeb/Text/expected/HTML/media-source-failure-pending-when-adopted.txtnew file mode 100644index 00000000000..cb2b8fc9b01--- /dev/null+++ b/Tests/LibWeb/Text/expected/HTML/media-source-failure-pending-when-adopted.txt@@ -0,0 +1 @@+next candidate after adoption: loaded metadatadiff --git a/Tests/LibWeb/Text/expected/HTML/media-source-failure-survives-adoption-round-trip.txt b/Tests/LibWeb/Text/expected/HTML/media-source-failure-survives-adoption-round-trip.txtnew file mode 100644index 00000000000..8f9047e1909--- /dev/null+++ b/Tests/LibWeb/Text/expected/HTML/media-source-failure-survives-adoption-round-trip.txt@@ -0,0 +1,2 @@+error at the first source+loaded metadata: solid-blue-160x120.webmdiff --git a/Tests/LibWeb/Text/expected/HTML/media-src-load-survives-adoption-then-iframe-removal.txt b/Tests/LibWeb/Text/expected/HTML/media-src-load-survives-adoption-then-iframe-removal.txtnew file mode 100644index 00000000000..c89538aa17a--- /dev/null+++ b/Tests/LibWeb/Text/expected/HTML/media-src-load-survives-adoption-then-iframe-removal.txt@@ -0,0 +1 @@+after adoption: loaded metadatadiff --git a/Tests/LibWeb/Text/input/HTML/media-source-failure-pending-when-adopted.html b/Tests/LibWeb/Text/input/HTML/media-source-failure-pending-when-adopted.htmlnew file mode 100644index 00000000000..b149f2d710b--- /dev/null+++ b/Tests/LibWeb/Text/input/HTML/media-source-failure-pending-when-adopted.html@@ -0,0 +1,46 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ // Resolves once resource selection has failed on the source and waits for another one. The selection goes on to+ // wait after the error event's dispatch, in the same task, so check in a later one.+ async function selectionWaits(video, source) {+ await new Promise(resolve => source.addEventListener("error", resolve, { once: true }));+ await new Promise(resolve => setTimeout(resolve, 0));+ if (video.networkState !== HTMLMediaElement.NETWORK_NO_SOURCE)+ println(`not waiting: networkState ${video.networkState}`);+ }++ asyncTest(async done => {+ // Resource selection fails on a source without a src and waits for another one.+ const iframe = document.createElement("iframe");+ document.body.appendChild(iframe);+ const doc = iframe.contentDocument;+ const video = doc.createElement("video");+ const source = doc.createElement("source");+ const waits = selectionWaits(video, source);+ video.appendChild(source);+ const elsewhere = doc.createElement("div");+ doc.body.append(video, elsewhere);+ await waits;++ // A source without a src moves in, then a playable one is appended. The selection resumes in a task, fails+ // on the moved source, and queues the failure's task. The message below runs before that task, and adopts+ // the video here and removes the iframe, so the failure's task never runs in the iframe's document.+ const empty = doc.createElement("source");+ elsewhere.appendChild(empty);+ video.moveBefore(empty, null);+ const playable = doc.createElement("source");+ playable.src = "../../../Assets/h264-reordered-frames.mp4";+ video.appendChild(playable);+ window.addEventListener("message", () => {+ document.body.appendChild(video);+ iframe.remove();+ }, { once: true });+ window.postMessage("adopt", "*");++ const loaded = new Promise(resolve => video.addEventListener("loadedmetadata", () => resolve("loaded metadata")));+ const timedOut = new Promise(resolve => setTimeout(() => resolve("never loaded"), 2000));+ println(`next candidate after adoption: ${await Promise.race([loaded, timedOut])}`);+ done();+ });+</script>diff --git a/Tests/LibWeb/Text/input/HTML/media-source-failure-survives-adoption-round-trip.html b/Tests/LibWeb/Text/input/HTML/media-source-failure-survives-adoption-round-trip.htmlnew file mode 100644index 00000000000..116e424dee1--- /dev/null+++ b/Tests/LibWeb/Text/input/HTML/media-source-failure-survives-adoption-round-trip.html@@ -0,0 +1,29 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ // The first source has no src, so resource selection fails on it and queues the error event. Before that task+ // runs, a playable source is inserted before the first one, and the video is adopted into a document that isn't+ // fully active and back. The selection carries on from where it was: The first source gets its error event, and+ // the next source after it loads, not the one inserted behind the selection.+ asyncTest(done => {+ const inactive = document.implementation.createHTMLDocument();+ const video = document.createElement("video");+ const first = document.createElement("source");+ const next = document.createElement("source");+ next.src = "../../../Assets/solid-blue-160x120.webm";+ video.append(first, next);+ first.addEventListener("error", () => println("error at the first source"));+ video.addEventListener("loadstart", () => {+ const inserted = document.createElement("source");+ inserted.src = "../../../Assets/h264-reordered-frames.mp4";+ video.insertBefore(inserted, first);+ inactive.body.appendChild(video);+ document.body.appendChild(video);+ }, { once: true });+ video.addEventListener("loadedmetadata", () => {+ println(`loaded metadata: ${video.currentSrc.split("/").pop()}`);+ done();+ });+ document.body.appendChild(video);+ });+</script>diff --git a/Tests/LibWeb/Text/input/HTML/media-src-load-survives-adoption-then-iframe-removal.html b/Tests/LibWeb/Text/input/HTML/media-src-load-survives-adoption-then-iframe-removal.htmlnew file mode 100644index 00000000000..70cfecabc2d--- /dev/null+++ b/Tests/LibWeb/Text/input/HTML/media-src-load-survives-adoption-then-iframe-removal.html@@ -0,0 +1,21 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ // src is set on a video in an iframe, and in the same task, the video is adopted here and the iframe removed. The+ // load that src started carries on in this document.+ asyncTest(async done => {+ const iframe = document.createElement("iframe");+ document.body.appendChild(iframe);+ const doc = iframe.contentDocument;+ const video = doc.createElement("video");+ doc.body.appendChild(video);+ video.src = "../../../Assets/h264-reordered-frames.mp4";+ document.body.appendChild(video);+ iframe.remove();++ const loaded = new Promise(resolve => video.addEventListener("loadedmetadata", () => resolve("loaded metadata")));+ const failed = new Promise(resolve => video.addEventListener("error", () => resolve(`error ${video.error.code}`)));+ println(`after adoption: ${await Promise.race([loaded, failed])}`);+ done();+ });+</script>