Truly independent web browser
LibWeb: Resume media resource selection from a media element task
sideshowbarkerd49bcd080cd7
diff --git a/Libraries/LibWeb/HTML/HTMLMediaElement.cpp b/Libraries/LibWeb/HTML/HTMLMediaElement.cppindex 5fd8e39365f..01523154318 100644--- a/Libraries/LibWeb/HTML/HTMLMediaElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLMediaElement.cpp@@ -965,6 +965,8 @@ WebIDL::ExceptionOr<void> HTMLMediaElement::load_element()// source, or run as part of the fetch. Step 3 will remove any subroutine from the queue. Step 7.2 will stop// any ongoing fetch operation. Therefore, all resource selection algorithms will be cancelled before a new// one begins.+ // NB: A source element selector also resumes from changes to the element's children, so drop it too.+ m_source_element_selector = nullptr;// 3. Let pending tasks be a list of all tasks from the media element's media element event task source in one of// the task queues.@@ -1151,7 +1153,16 @@ public:if (!m_waiting)return;- wait_for_next_candidate();+ // NB: Resume from a media element task, which runs only while the document is fully active: A selection+ // resumed synchronously would fetch a candidate for a document that isn't (one whose iframe was removed,+ // e.g.). The pointer itself is still kept in place synchronously, by node_removed(). Each change queues a+ // task of its own, and once one task has resumed the selection, the rest find it no longer waiting.+ m_media_element->queue_a_media_element_task(GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& selector, HTMLMediaElement&) {+ // A later load replaced this selector, and that selection decides what loads now.+ if (!selector.is_current() || !selector.m_waiting)+ return;+ selector.wait_for_next_candidate();+ }));}// If the node before pointer is removed: Let pointer be the point between the node after pointer and the node@@ -1168,10 +1179,16 @@ public:}private:+ bool is_current() const { return m_media_element->m_source_element_selector.ptr() == this; }+void failed_with_elements(){// 9. Failed with elements: Queue a media element task given the media element to fire an event named error at candidate.m_media_element->queue_a_media_element_task(GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& selector, HTMLMediaElement&) {+ // A later load replaced this selector, and that selection decides what loads now.+ if (!selector.is_current())+ return;+selector.m_candidate->dispatch_event(DOM::Event::create(HTML::relevant_global_object(*selector.m_candidate), HTML::EventNames::error));// 10. Await a stable state. The synchronous section consists of all the remaining steps of this algorithm until@@ -1229,8 +1246,12 @@ 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(GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& selector, HTMLMediaElement&) {- selector.m_media_element->set_delaying_the_load_event(false);+ // NB: Only if this same wait still goes on when the task runs: Once it ends, the fetch it went on to start+ // delays the load event, and a later wait queues a task of its own.+ auto wait = ++m_wait_count;+ m_media_element->queue_a_media_element_task(GC::create_function(GC::Heap::the(), GC::captures(*this, wait), [](auto& selector, auto wait, HTMLMediaElement&) {+ if (selector.is_current() && selector.m_waiting && selector.m_wait_count == wait)+ selector.m_media_element->set_delaying_the_load_event(false);}));// 20. End the synchronous section, continuing the remaining steps in parallel.@@ -1267,6 +1288,7 @@ private:GC::Ref<HTMLMediaElement> m_media_element;GC::Ref<HTMLSourceElement> m_candidate;bool m_waiting { false };+ u64 m_wait_count { 0 };GC::Ptr<DOM::Node> m_node_before_pointer;};diff --git a/Tests/LibWeb/Text/expected/HTML/media-source-added-in-detached-iframe-document.txt b/Tests/LibWeb/Text/expected/HTML/media-source-added-in-detached-iframe-document.txtnew file mode 100644index 00000000000..cf32d324112--- /dev/null+++ b/Tests/LibWeb/Text/expected/HTML/media-source-added-in-detached-iframe-document.txt@@ -0,0 +1 @@+survived; networkState 3diff --git a/Tests/LibWeb/Text/expected/HTML/media-source-added-while-inactive-then-adopted.txt b/Tests/LibWeb/Text/expected/HTML/media-source-added-while-inactive-then-adopted.txtnew file mode 100644index 00000000000..04a0c9a64fd--- /dev/null+++ b/Tests/LibWeb/Text/expected/HTML/media-source-added-while-inactive-then-adopted.txt@@ -0,0 +1,3 @@+source added while inactive, then adopted: loaded metadata: 160x120+adopted, then its iframe removed: loaded metadata: 160x120+src set before adoption: loaded metadata: 160x120diff --git a/Tests/LibWeb/Text/expected/HTML/media-source-wait-keeps-later-fetch-delaying-load.txt b/Tests/LibWeb/Text/expected/HTML/media-source-wait-keeps-later-fetch-delaying-load.txtnew file mode 100644index 00000000000..8b02f4d4862--- /dev/null+++ b/Tests/LibWeb/Text/expected/HTML/media-source-wait-keeps-later-fetch-delaying-load.txt@@ -0,0 +1,2 @@+source appended: loadedmetadata, load+source appended between two resumes: loadedmetadata, loaddiff --git a/Tests/LibWeb/Text/input/HTML/media-source-added-in-detached-iframe-document.html b/Tests/LibWeb/Text/input/HTML/media-source-added-in-detached-iframe-document.htmlnew file mode 100644index 00000000000..4d96f5ace06--- /dev/null+++ b/Tests/LibWeb/Text/input/HTML/media-source-added-in-detached-iframe-document.html@@ -0,0 +1,40 @@+<!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 => {+ // A video in an iframe's document waits for a source. The iframe is then removed, and a source is appended to+ // the video and another moved into it, in the document that's no longer fully active.+ 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;++ iframe.remove();+ const appended = doc.createElement("source");+ appended.src = "../../../Assets/h264-reordered-frames.mp4";+ video.appendChild(appended);+ const moved = doc.createElement("source");+ moved.src = "../../../Assets/h264-reordered-frames.mp4";+ elsewhere.appendChild(moved);+ video.moveBefore(moved, null);+ await new Promise(resolve => setTimeout(resolve, 200));++ println(`survived; networkState ${video.networkState}`);+ done();+ });+</script>diff --git a/Tests/LibWeb/Text/input/HTML/media-source-added-while-inactive-then-adopted.html b/Tests/LibWeb/Text/input/HTML/media-source-added-while-inactive-then-adopted.htmlnew file mode 100644index 00000000000..80fa709320b--- /dev/null+++ b/Tests/LibWeb/Text/input/HTML/media-source-added-while-inactive-then-adopted.html@@ -0,0 +1,79 @@+<!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}`);+ }++ async function waitingVideoInIframe() {+ // 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);+ doc.body.append(video);+ await waits;+ return { iframe, doc, video };+ }++ function playableSource(doc) {+ const source = doc.createElement("source");+ source.src = "../../../Assets/h264-reordered-frames.mp4";+ return source;+ }++ function loadedMetadata(video, label) {+ return new Promise(resolve => {+ video.addEventListener("loadedmetadata", () => {+ println(`${label}: loaded metadata: ${video.videoWidth}x${video.videoHeight}`);+ resolve();+ });+ });+ }++ const settle = () => new Promise(resolve => setTimeout(resolve, 100));++ asyncTest(async done => {+ {+ // A source is appended while the iframe's document isn't fully active, then the video is adopted here.+ const { iframe, doc, video } = await waitingVideoInIframe();+ iframe.remove();+ video.appendChild(playableSource(doc));+ await settle();+ const loaded = loadedMetadata(video, "source added while inactive, then adopted");+ document.body.appendChild(video);+ await loaded;+ }+ {+ // A source is appended, the video adopted, and its iframe removed, all in one task.+ const { iframe, doc, video } = await waitingVideoInIframe();+ const loaded = loadedMetadata(video, "adopted, then its iframe removed");+ video.appendChild(playableSource(doc));+ document.body.appendChild(video);+ iframe.remove();+ await loaded;+ }+ {+ // While the iframe's document isn't fully active, an empty source is appended and src is set, then the+ // video is adopted: the load that src started wins over the old selection, which never gets to the source.+ const { iframe, doc, video } = await waitingVideoInIframe();+ iframe.remove();+ const empty = doc.createElement("source");+ empty.addEventListener("error", () => println("src set before adoption: error at the appended source"));+ video.appendChild(empty);+ video.src = "../../../Assets/h264-reordered-frames.mp4";+ const loaded = loadedMetadata(video, "src set before adoption");+ document.body.appendChild(video);+ await loaded;+ }+ done();+ });+</script>diff --git a/Tests/LibWeb/Text/input/HTML/media-source-wait-keeps-later-fetch-delaying-load.html b/Tests/LibWeb/Text/input/HTML/media-source-wait-keeps-later-fetch-delaying-load.htmlnew file mode 100644index 00000000000..7db5bdba531--- /dev/null+++ b/Tests/LibWeb/Text/input/HTML/media-source-wait-keeps-later-fetch-delaying-load.html@@ -0,0 +1,62 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ // Resource selection waits for another source. Two children are appended in one task, and each change resumes+ // the selection in a task of its own. The first one finds no source, and waits again. Before the second one+ // runs, a playable source is appended, so the second one starts fetching it. Clearing the first wait's+ // delay mustn't stop that fetch from delaying the load event.+ function run(label, appendBeforeSource) {+ return new Promise(resolve => {+ const iframe = document.createElement("iframe");+ document.body.appendChild(iframe);+ const doc = iframe.contentDocument;+ doc.open();+ doc.write("<body>");+ const order = [];+ const finish = () => {+ if (order.length < 2)+ return;+ println(`${label}: ${order.join(", ")}`);+ window.removeEventListener("message", onMessage);+ iframe.remove();+ resolve();+ };+ iframe.contentWindow.addEventListener("load", () => {+ order.push("load");+ finish();+ });+ const video = doc.createElement("video");+ const first = doc.createElement("source");+ video.append(first);+ video.addEventListener("loadedmetadata", () => {+ order.push("loadedmetadata");+ finish();+ });+ const onMessage = event => {+ if (event.data === "waiting") {+ if (appendBeforeSource)+ video.append(doc.createTextNode("a"));+ window.postMessage("append source", "*");+ if (appendBeforeSource)+ video.append(doc.createTextNode("b"));+ } else if (event.data === "append source") {+ const playable = doc.createElement("source");+ playable.src = "../../../Assets/h264-reordered-frames.mp4";+ video.append(playable);+ window.postMessage("close", "*");+ } else if (event.data === "close") {+ doc.close();+ }+ };+ window.addEventListener("message", onMessage);+ first.addEventListener("error", () => window.postMessage("waiting", "*"));+ doc.body.appendChild(video);+ });+ }++ asyncTest(async done => {+ await run("source appended", false);+ await run("source appended between two resumes", true);+ done();+ });+</script>