Skip to content

Truly independent web browser

LibWeb: Stop ticking video sinks outside of the viewport

Zaggy1024f22b5b603cfc
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cpp
index c00a3e0eb47..b81abc98e7d 100644
--- a/Libraries/LibWeb/DOM/Document.cpp
+++ b/Libraries/LibWeb/DOM/Document.cpp
@@ -34,6 +34,7 @@
#include <LibJS/Console.h>
#include <LibJS/HostClassBuilder.h>
#include <LibJS/Runtime/Iterator.h>
+#include <LibJS/Runtime/NativeFunction.h>
#include <LibTextCodec/Decoder.h>
#include <LibURL/Origin.h>
#include <LibURL/Parser.h>
@@ -1064,6 +1065,7 @@ void Document::visit_edges(Cell::Visitor& visitor)
visitor.visit(m_first_base_element_with_target_in_tree_order);
visitor.visit(m_parser);
visitor.visit(m_lazy_load_intersection_observer);
+ visitor.visit(m_video_viewport_intersection_observer);
visitor.visit(m_visual_viewport);
visitor.visit(m_named_timelines);
visitor.visit(m_scripts_to_execute_when_parsing_has_finished);
@@ -7911,6 +7913,42 @@ void Document::stop_intersection_observing_a_lazy_loading_element(Element& eleme
m_lazy_load_intersection_observer->unobserve(element);
}
+void Document::start_observing_video_viewport_intersection(HTML::HTMLVideoElement& video)
+{
+ VERIFY(&video.document() == this);
+ if (!m_video_viewport_intersection_observer) {
+ auto options = IntersectionObserver::IntersectionObserverOptions {};
+ // Videos start decoding a little before they scroll into view, so that their frames are ready when they do.
+ options.root_margin = "250px"_utf16;
+
+ // The sinks read the observations themselves, in the rendering update that made them.
+ auto& realm = relevant_settings_object().realm();
+ auto callback = JS::NativeFunction::create(realm, Utf16FlyString {}, GC::create_function(GC::Heap::the(), [](JS::VM&) -> JS::ThrowCompletionOr<JS::Value> {
+ return JS::js_undefined();
+ }));
+ auto wrapped_callback = GC::Heap::the().allocate<WebIDL::CallbackType>(callback, realm);
+ m_video_viewport_intersection_observer = IntersectionObserver::IntersectionObserver::create_with_implicit_root_document(wrapped_callback, options, *this).release_value_but_fixme_should_propagate_errors();
+ }
+ m_video_viewport_intersection_observer->observe(video);
+}
+
+void Document::stop_observing_video_viewport_intersection(HTML::HTMLVideoElement& video)
+{
+ if (m_video_viewport_intersection_observer)
+ m_video_viewport_intersection_observer->unobserve(video);
+}
+
+bool Document::video_intersects_viewport(HTML::HTMLVideoElement const& video) const
+{
+ if (!m_video_viewport_intersection_observer)
+ return false;
+ for (auto const& observation_target : m_video_viewport_intersection_observer->observation_targets()) {
+ if (observation_target.target.ptr().ptr() == &video)
+ return observation_target.previous_is_intersecting;
+ }
+ return false;
+}
+
void Document::process_lazy_load_intersection_observer_entries(ReadonlySpan<GC::Ref<IntersectionObserver::IntersectionObserverEntry>> entries)
{
// For each entry in entries using a method of iteration which does not
diff --git a/Libraries/LibWeb/DOM/Document.h b/Libraries/LibWeb/DOM/Document.h
index df140647fde..a8171e9239c 100644
--- a/Libraries/LibWeb/DOM/Document.h
+++ b/Libraries/LibWeb/DOM/Document.h
@@ -1397,6 +1397,11 @@ public:
void stop_intersection_observing_a_lazy_loading_element(Element&);
void process_lazy_load_intersection_observer_entries(ReadonlySpan<GC::Ref<IntersectionObserver::IntersectionObserverEntry>>);
+ void start_observing_video_viewport_intersection(HTML::HTMLVideoElement&);
+ void stop_observing_video_viewport_intersection(HTML::HTMLVideoElement&);
+ // Whether the last update of intersection observations found the video near enough to the viewport to be shown.
+ bool video_intersects_viewport(HTML::HTMLVideoElement const&) const;
+
void shared_declarative_refresh_steps(Utf16View input, GC::Ptr<HTML::HTMLMetaElement const> meta_element = nullptr);
struct TopOfTheDocument { };
@@ -2396,6 +2401,8 @@ private:
// Each Document has a lazy load intersection observer, initially set to null but can be set to an IntersectionObserver instance.
GC::Ptr<IntersectionObserver::IntersectionObserver> m_lazy_load_intersection_observer;
+ GC::Ptr<IntersectionObserver::IntersectionObserver> m_video_viewport_intersection_observer;
+
Vector<GC::Weak<ResizeObserver::ResizeObserver>> m_resize_observers;
ShadowRoot::DocumentSlotAssignmentList m_shadow_roots_needing_slot_assignment;
diff --git a/Libraries/LibWeb/HTML/HTMLMediaElement.cpp b/Libraries/LibWeb/HTML/HTMLMediaElement.cpp
index 65d11c204cd..dcd00d67623 100644
--- a/Libraries/LibWeb/HTML/HTMLMediaElement.cpp
+++ b/Libraries/LibWeb/HTML/HTMLMediaElement.cpp
@@ -488,6 +488,11 @@ void HTMLMediaElement::adopted_from(DOM::Document& old_document)
old_document.page().active_media_session_tracker().media_element_removed(*this);
+ if (auto* video_element = as_if<HTMLVideoElement>(this); video_element && m_active_video_sink) {
+ old_document.stop_observing_video_viewport_intersection(*video_element);
+ document().start_observing_video_viewport_intersection(*video_element);
+ }
+
// NB: The element's relevant global follows its node document, so the old document's global stops keeping it alive.
relevant_window_or_worker_global_scope(old_document).set_has_pending_activity(*this, false);
@@ -2330,6 +2335,8 @@ void HTMLMediaElement::attach_selected_video_track_sink(Media::Track const& trac
}));
m_active_video_sink = make<ActiveVideoSink>(handle);
m_video_sink_is_ticking = {};
+ if (auto* video_element = as_if<HTMLVideoElement>(this))
+ document().start_observing_video_viewport_intersection(*video_element);
add_current_video_sink(handle);
// NB: The input is not started until the sink's ticking state is decided, which a visible document does in the next
// rendering update.
@@ -2367,8 +2374,10 @@ void HTMLMediaElement::release_active_video_sink()
m_active_video_sink.clear();
if (m_playback_manager && handle.has_value())
m_playback_manager->disable_video_sink_by_handle(*handle);
- if (auto* video_element = as_if<HTMLVideoElement>(this))
+ if (auto* video_element = as_if<HTMLVideoElement>(this)) {
+ document().stop_observing_video_viewport_intersection(*video_element);
Painting::push_video_paint_facts(*video_element);
+ }
}
void HTMLMediaElement::set_selected_video_track(Badge<VideoTrack>, GC::Ptr<HTML::VideoTrack> video_track)
@@ -3262,7 +3271,12 @@ bool HTMLMediaElement::video_sink_should_tick(DocumentWasLaidOut document_was_la
if (document_was_laid_out == DocumentWasLaidOut::No)
return false;
auto const* layout_node = this->layout_node(read);
- return layout_node && Painting::has_committed_box(*layout_node) && Painting::is_visible(*layout_node);
+ if (!layout_node || !Painting::has_committed_box(*layout_node) || !Painting::is_visible(*layout_node))
+ return false;
+ // A video far enough outside the viewport isn't decoded, and resumes from the current time as it comes back.
+ if (auto const* video_element = as_if<HTMLVideoElement>(*this))
+ return document().video_intersects_viewport(*video_element);
+ return true;
}
void HTMLMediaElement::sync_video_sink_ticking(DocumentWasLaidOut document_was_laid_out) const
diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.ini
index d9715986f00..690db52895f 100644
--- a/Tests/LibWeb/TestConfig.ini
+++ b/Tests/LibWeb/TestConfig.ini
@@ -84,6 +84,8 @@ Text/input/HTML/HTMLVideoElement-capture-before-seek-keeps-frame.html
Text/input/HTML/HTMLVideoElement-cross-origin-media-data-taints-canvas.html
Text/input/HTML/HTMLVideoElement-requestVideoFrameCallback.html
Text/input/HTML/HTMLVideoElement-requestVideoFrameCallback-first-frame-is-usable.html
+Text/input/HTML/video-capture-of-an-offscreen-video-after-seeking.html
+Text/input/HTML/video-capture-of-an-offscreen-video-catches-up.html
Text/input/HTML/iframe-permissions-policy.html
Text/input/wpt-import/fetch/cross-origin-resource-policy/fetch-in-iframe.html
Text/input/wpt-import/fetch/cross-origin-resource-policy/iframe-loads.html
diff --git a/Tests/LibWeb/Text/expected/HTML/video-capture-of-an-offscreen-video-after-seeking.txt b/Tests/LibWeb/Text/expected/HTML/video-capture-of-an-offscreen-video-after-seeking.txt
new file mode 100644
index 00000000000..100e38ef91e
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/HTML/video-capture-of-an-offscreen-video-after-seeking.txt
@@ -0,0 +1,3 @@
+ticking before capturing: false
+frames presented before capturing: 0
+drawImage after seeking to 2.5s: second 2
diff --git a/Tests/LibWeb/Text/expected/HTML/video-capture-of-an-offscreen-video-catches-up.txt b/Tests/LibWeb/Text/expected/HTML/video-capture-of-an-offscreen-video-catches-up.txt
new file mode 100644
index 00000000000..680a8c9ee35
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/HTML/video-capture-of-an-offscreen-video-catches-up.txt
@@ -0,0 +1,4 @@
+ticking before capturing: false
+frames presented before capturing: 0
+drawImage: second 0
+createImageBitmap: second 0
diff --git a/Tests/LibWeb/Text/expected/HTML/video-sink-ticks-only-near-the-viewport.txt b/Tests/LibWeb/Text/expected/HTML/video-sink-ticks-only-near-the-viewport.txt
new file mode 100644
index 00000000000..728c6a8de86
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/HTML/video-sink-ticks-only-near-the-viewport.txt
@@ -0,0 +1,8 @@
+ticking while far below the viewport: false
+frames presented while far below the viewport: 0
+playing while far below the viewport: true
+ticking 100px below the viewport: true
+ticking in the viewport: true
+ticking 400px below the viewport: false
+ticking 400px above the viewport: false
+playing after leaving the viewport: true
diff --git a/Tests/LibWeb/Text/input/HTML/video-capture-of-an-offscreen-video-after-seeking.html b/Tests/LibWeb/Text/input/HTML/video-capture-of-an-offscreen-video-after-seeking.html
new file mode 100644
index 00000000000..a3ca31035be
--- /dev/null
+++ b/Tests/LibWeb/Text/input/HTML/video-capture-of-an-offscreen-video-after-seeking.html
@@ -0,0 +1,44 @@
+<!doctype html>
+<script src="../include.js"></script>
+<style>
+ body { margin: 0; }
+ video { display: block; width: 64px; height: 36px; }
+</style>
+<div style="height: 5000px"></div>
+<video id="video" muted></video>
+<script>
+ const video = document.getElementById("video");
+
+ // The left half of the video is blue, and the right half gray, 60 shades lighter each second.
+ function describeFrame(source) {
+ const canvas = document.createElement("canvas");
+ canvas.width = 64;
+ canvas.height = 36;
+ const context = canvas.getContext("2d");
+ context.drawImage(source, 0, 0);
+ const [red, green, blue, alpha] = context.getImageData(10, 18, 1, 1).data;
+ if (alpha === 0)
+ return "no frame";
+ if (red > 100 || blue < 150)
+ return "not the video";
+ return `second ${Math.round(context.getImageData(54, 18, 1, 1).data[0] / 60)}`;
+ }
+
+ asyncTest(async done => {
+ await new Promise(resolve => {
+ video.addEventListener("canplaythrough", resolve, { once: true });
+ video.src = "../../../Assets/blue-with-second-in-gray-64x36.webm";
+ });
+
+ // A seek of a video that isn't ticking finishes without decoding the frame it seeked to, and a capture after
+ // seeked has to wait for it.
+ await new Promise(resolve => {
+ video.addEventListener("seeked", resolve, { once: true });
+ video.currentTime = 2.5;
+ });
+ println(`ticking before capturing: ${internals.mediaElementVideoSinkIsTicking(video)}`);
+ println(`frames presented before capturing: ${video.getVideoPlaybackQuality().totalVideoFrames}`);
+ println(`drawImage after seeking to 2.5s: ${describeFrame(video)}`);
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/HTML/video-capture-of-an-offscreen-video-catches-up.html b/Tests/LibWeb/Text/input/HTML/video-capture-of-an-offscreen-video-catches-up.html
new file mode 100644
index 00000000000..4409c182255
--- /dev/null
+++ b/Tests/LibWeb/Text/input/HTML/video-capture-of-an-offscreen-video-catches-up.html
@@ -0,0 +1,41 @@
+<!doctype html>
+<script src="../include.js"></script>
+<style>
+ body { margin: 0; }
+ video { display: block; width: 64px; height: 36px; }
+</style>
+<div style="height: 5000px"></div>
+<video id="video" muted></video>
+<script>
+ const video = document.getElementById("video");
+
+ // The left half of the video is blue, and the right half gray, 60 shades lighter each second.
+ function describeFrame(source) {
+ const canvas = document.createElement("canvas");
+ canvas.width = 64;
+ canvas.height = 36;
+ const context = canvas.getContext("2d");
+ context.drawImage(source, 0, 0);
+ const [red, green, blue, alpha] = context.getImageData(10, 18, 1, 1).data;
+ if (alpha === 0)
+ return "no frame";
+ if (red > 100 || blue < 150)
+ return "not the video";
+ return `second ${Math.round(context.getImageData(54, 18, 1, 1).data[0] / 60)}`;
+ }
+
+ asyncTest(async done => {
+ await new Promise(resolve => {
+ video.addEventListener("canplaythrough", resolve, { once: true });
+ video.src = "../../../Assets/blue-with-second-in-gray-64x36.webm";
+ });
+
+ // An offscreen video starts without decoding a frame.
+ println(`ticking before capturing: ${internals.mediaElementVideoSinkIsTicking(video)}`);
+ println(`frames presented before capturing: ${video.getVideoPlaybackQuality().totalVideoFrames}`);
+
+ println(`drawImage: ${describeFrame(video)}`);
+ println(`createImageBitmap: ${describeFrame(await createImageBitmap(video))}`);
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/HTML/video-sink-ticks-only-near-the-viewport.html b/Tests/LibWeb/Text/input/HTML/video-sink-ticks-only-near-the-viewport.html
new file mode 100644
index 00000000000..2eea4fcb7d6
--- /dev/null
+++ b/Tests/LibWeb/Text/input/HTML/video-sink-ticks-only-near-the-viewport.html
@@ -0,0 +1,57 @@
+<!doctype html>
+<script src="../include.js"></script>
+<script src="frame-in-flight/frame-in-flight.js"></script>
+<style>
+ body { margin: 0; }
+ .spacer { height: 5000px; }
+ video { display: block; width: 320px; height: 240px; }
+</style>
+<div class="spacer"></div>
+<video id="video" muted autoplay loop></video>
+<div class="spacer"></div>
+<script>
+ const video = document.getElementById("video");
+
+ async function committedFrame() {
+ internals.setManualRenderingOpportunities(true);
+ try {
+ const frame = animationFrame();
+ internals.injectRenderingOpportunity(performance.now());
+ await frame;
+ do await nextTask();
+ while (internals.frameSchedulerState() !== "idle" || internals.clockLaneIsComing(document));
+ } finally {
+ internals.setManualRenderingOpportunities(false);
+ }
+ }
+
+ async function scrollVideoTopBelowTheViewportBy(distance) {
+ window.scrollTo(0, video.offsetTop - window.innerHeight - distance);
+ await committedFrame();
+ }
+
+ asyncTest(async done => {
+ video.src = "../../../Assets/test-webm.webm";
+ await new Promise(resolve => video.addEventListener("playing", resolve, { once: true }));
+ await committedFrame();
+ println(`ticking while far below the viewport: ${internals.mediaElementVideoSinkIsTicking(video)}`);
+ println(`frames presented while far below the viewport: ${video.getVideoPlaybackQuality().totalVideoFrames}`);
+ println(`playing while far below the viewport: ${!video.paused}`);
+
+ await scrollVideoTopBelowTheViewportBy(100);
+ println(`ticking 100px below the viewport: ${internals.mediaElementVideoSinkIsTicking(video)}`);
+
+ video.scrollIntoView();
+ await committedFrame();
+ println(`ticking in the viewport: ${internals.mediaElementVideoSinkIsTicking(video)}`);
+
+ await scrollVideoTopBelowTheViewportBy(400);
+ println(`ticking 400px below the viewport: ${internals.mediaElementVideoSinkIsTicking(video)}`);
+
+ window.scrollTo(0, video.offsetTop + video.offsetHeight + 400);
+ await committedFrame();
+ println(`ticking 400px above the viewport: ${internals.mediaElementVideoSinkIsTicking(video)}`);
+ println(`playing after leaving the viewport: ${!video.paused}`);
+ done();
+ });
+</script>