Skip to content

Truly independent web browser

LibWeb+LibCompositing+Compositor: Implement requestVideoFrameCallback()

Zaggy1024f8c2feef994c
diff --git a/Libraries/LibCompositing/Video/VideoFrameHold.cpp b/Libraries/LibCompositing/Video/VideoFrameHold.cpp
index a0f735c26cd..f5c52340121 100644
--- a/Libraries/LibCompositing/Video/VideoFrameHold.cpp
+++ b/Libraries/LibCompositing/Video/VideoFrameHold.cpp
@@ -18,6 +18,13 @@ RefPtr<VideoFrameHold> VideoFrameHold::hold_current_frame(NonnullRefPtr<VideoFra
return adopt_ref(*new VideoFrameHold(move(page), sink_handle, generation.value(), move(release_through_compositor)));
}
+RefPtr<VideoFrameHold> VideoFrameHold::hold_frame_of_generation(NonnullRefPtr<VideoFramePresentationPage> page, Media::VideoSinkHandle sink_handle, u64 generation, ReleaseThroughCompositor release_through_compositor)
+{
+ if (!page->hold_generation(generation))
+ return nullptr;
+ return adopt_ref(*new VideoFrameHold(move(page), sink_handle, generation, move(release_through_compositor)));
+}
+
VideoFrameHold::VideoFrameHold(NonnullRefPtr<VideoFramePresentationPage> page, Media::VideoSinkHandle sink_handle, u64 generation, ReleaseThroughCompositor release_through_compositor)
: m_page(move(page))
, m_sink_handle(sink_handle)
diff --git a/Libraries/LibCompositing/Video/VideoFrameHold.h b/Libraries/LibCompositing/Video/VideoFrameHold.h
index 937bfa7fd6d..9312d6caaea 100644
--- a/Libraries/LibCompositing/Video/VideoFrameHold.h
+++ b/Libraries/LibCompositing/Video/VideoFrameHold.h
@@ -24,6 +24,7 @@ public:
using ReleaseThroughCompositor = Function<void(Media::VideoSinkHandle, u64 generation)>;
static RefPtr<VideoFrameHold> hold_current_frame(NonnullRefPtr<VideoFramePresentationPage>, Media::VideoSinkHandle, ReleaseThroughCompositor);
+ static RefPtr<VideoFrameHold> hold_frame_of_generation(NonnullRefPtr<VideoFramePresentationPage>, Media::VideoSinkHandle, u64 generation, ReleaseThroughCompositor);
~VideoFrameHold();
Media::VideoSinkHandle sink_handle() const { return m_sink_handle; }
diff --git a/Libraries/LibCompositing/Video/VideoFramePresentationPage.cpp b/Libraries/LibCompositing/Video/VideoFramePresentationPage.cpp
index 29d8526a123..9ea2b27756f 100644
--- a/Libraries/LibCompositing/Video/VideoFramePresentationPage.cpp
+++ b/Libraries/LibCompositing/Video/VideoFramePresentationPage.cpp
@@ -16,19 +16,21 @@ static constexpr size_t max_compare_exchange_attempts_before_assuming_a_misbehav
ErrorOr<NonnullRefPtr<VideoFramePresentationPage>> VideoFramePresentationPage::create()
{
- return create(TRY(Core::AnonymousBuffer::create_with_size(sizeof(Atomic<u64>))));
+ auto buffer = TRY(Core::AnonymousBuffer::create_with_size(sizeof(SharedState)));
+ new (buffer.data<void>()) SharedState;
+ return create(move(buffer));
}
ErrorOr<NonnullRefPtr<VideoFramePresentationPage>> VideoFramePresentationPage::create(Core::AnonymousBuffer buffer)
{
- if (!buffer.is_valid() || buffer.size() < sizeof(Atomic<u64>))
+ if (!buffer.is_valid() || buffer.size() < sizeof(SharedState))
return Error::from_string_literal("Invalid video frame presentation page buffer");
return adopt_nonnull_ref_or_enomem(new (nothrow) VideoFramePresentationPage(move(buffer)));
}
VideoFramePresentationPage::VideoFramePresentationPage(Core::AnonymousBuffer buffer)
: m_buffer(move(buffer))
- , m_word(reinterpret_cast<Atomic<u64>*>(m_buffer.data<void>()))
+ , m_shared_state(reinterpret_cast<SharedState*>(m_buffer.data<void>()))
{
}
@@ -57,12 +59,24 @@ u64 VideoFramePresentationPage::current_generation() const
}
Optional<u64> VideoFramePresentationPage::hold_current_generation()
+{
+ return hold(OptionalNone {});
+}
+
+bool VideoFramePresentationPage::hold_generation(u64 generation)
+{
+ return hold(generation).has_value();
+}
+
+Optional<u64> VideoFramePresentationPage::hold(Optional<u64> required_generation)
{
auto expected = word().load(AK::MemoryOrder::memory_order_relaxed);
for (size_t attempt = 0; attempt < max_compare_exchange_attempts_before_assuming_a_misbehaving_peer; attempt++) {
auto current = unpack(expected);
if (current.generation == retired_generation || current.hold_count == max_hold_count)
return {};
+ if (required_generation.has_value() && current.generation != required_generation.value())
+ return {};
auto held = pack({ .generation = current.generation, .hold_count = current.hold_count + 1 });
if (word().compare_exchange_strong(expected, held, AK::MemoryOrder::memory_order_relaxed))
return current.generation;
@@ -70,6 +84,16 @@ Optional<u64> VideoFramePresentationPage::hold_current_generation()
return {};
}
+void VideoFramePresentationPage::publish_presented_frame(PresentedFrame const& presented_frame)
+{
+ m_shared_state->presented_frame.store(presented_frame);
+}
+
+Optional<VideoFramePresentationPage::PresentedFrame> VideoFramePresentationPage::presented_frame() const
+{
+ return m_shared_state->presented_frame.read();
+}
+
VideoFramePresentationPage::ReleaseResult VideoFramePresentationPage::release_hold_if_current(u64 generation)
{
auto expected = word().load(AK::MemoryOrder::memory_order_relaxed);
diff --git a/Libraries/LibCompositing/Video/VideoFramePresentationPage.h b/Libraries/LibCompositing/Video/VideoFramePresentationPage.h
index 4e46ce0c3e9..d45a261a4be 100644
--- a/Libraries/LibCompositing/Video/VideoFramePresentationPage.h
+++ b/Libraries/LibCompositing/Video/VideoFramePresentationPage.h
@@ -11,6 +11,8 @@
#include <AK/NonnullRefPtr.h>
#include <AK/Optional.h>
#include <AK/RefCounted.h>
+#include <AK/SeqLock.h>
+#include <AK/Time.h>
#include <LibCompositing/Export.h>
#include <LibCore/AnonymousBuffer.h>
#include <LibIPC/Forward.h>
@@ -46,16 +48,35 @@ public:
};
ReleaseResult release_hold_if_current(u64 generation);
+ struct PresentedFrame {
+ u64 generation { 0 };
+ u64 presented_frame_count { 0 };
+ AK::Duration media_time { AK::Duration::zero() };
+ MonotonicTime presentation_time;
+ u32 width { 0 };
+ u32 height { 0 };
+ };
+ void publish_presented_frame(PresentedFrame const&);
+ Optional<PresentedFrame> presented_frame() const;
+ bool hold_generation(u64 generation);
+
private:
+ struct SharedState {
+ Atomic<u64> word;
+ SeqLock<PresentedFrame> presented_frame;
+ };
+
VideoFramePresentationPage(Core::AnonymousBuffer);
+ Optional<u64> hold(Optional<u64> required_generation);
+
static u64 pack(GenerationAndHolds);
static GenerationAndHolds unpack(u64);
- Atomic<u64>& word() const { return *m_word; }
+ Atomic<u64>& word() const { return m_shared_state->word; }
Core::AnonymousBuffer m_buffer;
- Atomic<u64>* m_word { nullptr };
+ SharedState* m_shared_state { nullptr };
};
}
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cpp
index 982164986cb..da62ad26e3f 100644
--- a/Libraries/LibWeb/DOM/Document.cpp
+++ b/Libraries/LibWeb/DOM/Document.cpp
@@ -5564,6 +5564,18 @@ bool Document::append_pending_scroll_event(PendingScrollEvent event)
}
// https://drafts.csswg.org/cssom-view-1/#document-run-the-scroll-steps
+void Document::run_the_video_frame_request_callbacks(double now)
+{
+ for (auto& video_element : page().video_elements_of(*this))
+ video_element->run_the_video_frame_request_callbacks(now);
+}
+
+void Document::release_video_frames_held_for_callbacks()
+{
+ for (auto& video_element : page().video_elements_of(*this))
+ video_element->release_presented_video_frame_held_for_callbacks();
+}
+
void Document::run_the_scroll_steps()
{
// AD-HOC: Process auto-scroll ticks before dispatching scroll events. This is tied to the rendering update to
diff --git a/Libraries/LibWeb/DOM/Document.h b/Libraries/LibWeb/DOM/Document.h
index 059c2fd47d7..e226a06a60a 100644
--- a/Libraries/LibWeb/DOM/Document.h
+++ b/Libraries/LibWeb/DOM/Document.h
@@ -920,6 +920,10 @@ public:
void run_the_resize_steps();
void run_the_scroll_steps();
+ u32 increment_video_frame_request_callback_identifier() { return ++m_video_frame_request_callback_identifier; }
+ void run_the_video_frame_request_callbacks(double now);
+ void release_video_frames_held_for_callbacks();
+
void evaluate_media_queries_and_report_changes();
bool needs_media_query_list_evaluation() const { return m_needs_media_query_list_evaluation; }
bool needs_media_rule_evaluation() const { return m_needs_media_rule_evaluation; }
@@ -1863,6 +1867,9 @@ private:
GC::Ptr<HTML::HTMLParser> m_parser;
u64 m_parser_generation { 0 };
+
+ // https://wicg.github.io/video-rvfc/#video-frame-request-callback-identifier
+ u32 m_video_frame_request_callback_identifier { 0 };
bool m_active_parser_was_aborted { false };
bool m_has_been_destroyed { false };
diff --git a/Libraries/LibWeb/HTML/EventLoop/EventLoop.cpp b/Libraries/LibWeb/HTML/EventLoop/EventLoop.cpp
index 6519c60d406..1575330467f 100644
--- a/Libraries/LibWeb/HTML/EventLoop/EventLoop.cpp
+++ b/Libraries/LibWeb/HTML/EventLoop/EventLoop.cpp
@@ -925,12 +925,23 @@ void EventLoop::update_the_rendering()
// FIXME: 13. For each doc of docs, if the user agent detects that the backing storage associated with a CanvasRenderingContext2D or an OffscreenCanvasRenderingContext2D, context, has been lost, then it must run the context lost steps for each such context:
+ // https://wicg.github.io/video-rvfc/#video-rvfc-rendering-step
+ // For each fully active Document in docs, for each associated video element for that Document, run the video
+ // frame request callbacks passing now as the timestamp.
+ for (auto& document : docs)
+ document->run_the_video_frame_request_callbacks(relative_frame_timestamp_for(*document));
+
// 14. For each doc of docs, run the animation frame callbacks for doc, passing in the relative high resolution time given frameTimestamp and doc's relevant global object as the timestamp.
for (auto& document : docs) {
auto now = relative_frame_timestamp_for(*document);
run_animation_frame_callbacks(*document, now);
}
+ // AD-HOC: Captures in this update's video frame and animation frame callbacks draw the frame that the video frame
+ // callbacks' metadata described. Later captures draw whatever frame is presented then.
+ for (auto& document : docs)
+ document->release_video_frames_held_for_callbacks();
+
// FIXME: 15. Let unsafeStyleAndLayoutStartTime be the unsafe shared current time.
// AD-HOC: The rest of the last rendering update runs before anything of this one's style and layout.
diff --git a/Libraries/LibWeb/HTML/HTMLMediaElement.cpp b/Libraries/LibWeb/HTML/HTMLMediaElement.cpp
index 971a269f53a..4b15f7c8a45 100644
--- a/Libraries/LibWeb/HTML/HTMLMediaElement.cpp
+++ b/Libraries/LibWeb/HTML/HTMLMediaElement.cpp
@@ -97,6 +97,8 @@ public:
return;
unregister();
m_compositor_host = &compositor_host;
+ m_frames_presented_on_earlier_pages += m_frames_presented_on_this_page;
+ m_frames_presented_on_this_page = 0;
m_presentation_page = MUST(Compositing::VideoFramePresentationPage::create());
m_compositor_host->add_video_sink(m_handle, *m_presentation_page);
}
@@ -109,12 +111,15 @@ public:
m_compositor_host = nullptr;
m_presentation_page = nullptr;
m_latest_hold = nullptr;
+ m_hold_for_video_frame_callbacks = nullptr;
}
Optional<Compositing::CapturedVideoFrame> capture_current_frame()
{
if (!m_compositor_host || !m_presentation_page)
return {};
+ if (m_hold_for_video_frame_callbacks)
+ return Compositing::CapturedVideoFrame { .sink_handle = m_handle, .generation = m_hold_for_video_frame_callbacks->generation(), .hold = m_hold_for_video_frame_callbacks };
auto hold = m_latest_hold.strong_ref();
if (!hold || hold->generation() != m_presentation_page->current_generation()) {
hold = Compositing::VideoFrameHold::hold_current_frame(*m_presentation_page, m_handle, m_compositor_host->video_frame_hold_releaser_for_current_connection());
@@ -125,12 +130,53 @@ public:
return Compositing::CapturedVideoFrame { .sink_handle = m_handle, .generation = hold->generation(), .hold = hold };
}
+ Optional<PresentedVideoFrame> hold_presented_frame_for_video_frame_callbacks()
+ {
+ static constexpr size_t max_attempts_while_frames_are_presented = 8;
+ if (!m_compositor_host || !m_presentation_page)
+ return {};
+ for (size_t attempt = 0; attempt < max_attempts_while_frames_are_presented; attempt++) {
+ auto presented_frame = m_presentation_page->presented_frame();
+ if (!presented_frame.has_value())
+ return {};
+ m_frames_presented_on_this_page = presented_frame->presented_frame_count;
+ if (presented_frame->presented_frame_count == 0)
+ return {};
+ auto hold = Compositing::VideoFrameHold::hold_frame_of_generation(*m_presentation_page, m_handle, presented_frame->generation, m_compositor_host->video_frame_hold_releaser_for_current_connection());
+ if (!hold)
+ continue;
+ m_hold_for_video_frame_callbacks = move(hold);
+ return PresentedVideoFrame {
+ .presented_frames = total_presented_frames(),
+ .media_time = presented_frame->media_time,
+ .presentation_time = presented_frame->presentation_time,
+ .width = presented_frame->width,
+ .height = presented_frame->height,
+ };
+ }
+ return {};
+ }
+
+ void release_frame_held_for_video_frame_callbacks() { m_hold_for_video_frame_callbacks = nullptr; }
+
+ u64 total_presented_frames()
+ {
+ if (m_presentation_page) {
+ if (auto presented_frame = m_presentation_page->presented_frame(); presented_frame.has_value())
+ m_frames_presented_on_this_page = presented_frame->presented_frame_count;
+ }
+ return m_frames_presented_on_earlier_pages + m_frames_presented_on_this_page;
+ }
+
private:
Media::VideoSinkHandle m_handle;
Compositing::VideoSinkResourceId m_resource_id;
Compositor::CompositorHost* m_compositor_host { nullptr };
RefPtr<Compositing::VideoFramePresentationPage> m_presentation_page;
WeakPtr<Compositing::VideoFrameHold> m_latest_hold;
+ RefPtr<Compositing::VideoFrameHold> m_hold_for_video_frame_callbacks;
+ u64 m_frames_presented_on_earlier_pages { 0 };
+ u64 m_frames_presented_on_this_page { 0 };
};
static u64 s_next_remote_fetch_data_id = 0;
@@ -1965,6 +2011,30 @@ Optional<Compositing::CapturedVideoFrame> HTMLMediaElement::capture_current_vide
return m_active_video_sink->capture_current_frame();
}
+u64 HTMLMediaElement::presented_video_frame_count() const
+{
+ auto presented_frames = m_frames_presented_by_released_video_sinks;
+ if (m_active_video_sink)
+ presented_frames += m_active_video_sink->total_presented_frames();
+ return presented_frames;
+}
+
+Optional<HTMLMediaElement::PresentedVideoFrame> HTMLMediaElement::hold_presented_video_frame_for_callbacks()
+{
+ if (!m_active_video_sink)
+ return {};
+ auto presented_frame = m_active_video_sink->hold_presented_frame_for_video_frame_callbacks();
+ if (presented_frame.has_value())
+ presented_frame->presented_frames += m_frames_presented_by_released_video_sinks;
+ return presented_frame;
+}
+
+void HTMLMediaElement::release_presented_video_frame_held_for_callbacks()
+{
+ if (m_active_video_sink)
+ m_active_video_sink->release_frame_held_for_video_frame_callbacks();
+}
+
void HTMLMediaElement::attach_selected_video_track_sink(Media::Track const& track)
{
if (video_sink_handle().has_value())
@@ -2006,6 +2076,8 @@ void HTMLMediaElement::detach_video_sink_edge()
void HTMLMediaElement::release_active_video_sink()
{
auto handle = video_sink_handle();
+ if (m_active_video_sink)
+ m_frames_presented_by_released_video_sinks += m_active_video_sink->total_presented_frames();
m_active_video_sink.clear();
if (m_playback_manager && handle.has_value())
m_playback_manager->disable_video_sink_by_handle(*handle);
@@ -2597,6 +2669,7 @@ void HTMLMediaElement::set_ready_state(ReadyState ready_state)
auto old_ready_state = m_ready_state;
m_ready_state = ready_state;
CSS::Invalidation::invalidate_style_after_media_ready_state_change(*this, was_buffering);
+ request_rendering_update_for_video_frame_callbacks();
// https://html.spec.whatwg.org/multipage/media.html#text-track-cue-active-flag
if (m_ready_state == ReadyState::HaveNothing) {
@@ -2832,6 +2905,8 @@ bool HTMLMediaElement::video_sink_should_tick() const
Layout::ForcedReadScope read { document() };
if (m_video_frame_was_recently_captured)
return true;
+ if (auto const* video_element = as_if<HTMLVideoElement>(*this); video_element && video_element->has_video_frame_request_callbacks())
+ return true;
// Another element, such as one in a Picture-in-Picture window, shows the frames whatever happens to this one's box.
if (is_shown_elsewhere())
return true;
@@ -3026,6 +3101,8 @@ void HTMLMediaElement::seek_element(double playback_position, MediaSeekMode seek
// 4. Set the seeking IDL attribute to true.
set_seeking(true);
+ request_rendering_update_for_video_frame_callbacks();
+
// 5. If the seek was in response to a DOM method call or setting of an IDL attribute, then continue the script. The
// remainder of these steps must be run in parallel. With the exception of the steps marked with ⌛, they could be
// aborted at any time by another instance of this algorithm being invoked.
@@ -3217,6 +3294,7 @@ void HTMLMediaElement::set_paused(bool paused)
return;
m_paused = paused;
+ request_rendering_update_for_video_frame_callbacks();
if (m_paused) {
m_has_started_playback = false;
diff --git a/Libraries/LibWeb/HTML/HTMLMediaElement.h b/Libraries/LibWeb/HTML/HTMLMediaElement.h
index 5b285d87956..5564e9656f8 100644
--- a/Libraries/LibWeb/HTML/HTMLMediaElement.h
+++ b/Libraries/LibWeb/HTML/HTMLMediaElement.h
@@ -202,6 +202,18 @@ public:
Optional<Media::VideoSinkHandle> video_sink_handle() const;
Optional<Compositing::CapturedVideoFrame> capture_current_video_frame() const;
+ struct PresentedVideoFrame {
+ u64 presented_frames { 0 };
+ AK::Duration media_time;
+ MonotonicTime presentation_time;
+ u32 width { 0 };
+ u32 height { 0 };
+ };
+ u64 presented_video_frame_count() const;
+ Optional<PresentedVideoFrame> hold_presented_video_frame_for_callbacks();
+ void release_presented_video_frame_held_for_callbacks();
+ virtual void request_rendering_update_for_video_frame_callbacks() { }
+
Optional<Compositing::VideoSinkResourceId> video_sink_resource_id() const;
virtual void update_representation() { }
@@ -463,6 +475,7 @@ private:
RefPtr<Core::Timer> m_playback_position_update_timer;
GC::Ptr<VideoTrack> m_selected_video_track;
OwnPtr<ActiveVideoSink> m_active_video_sink;
+ u64 m_frames_presented_by_released_video_sinks { 0 };
mutable bool m_video_frame_was_recently_captured { false };
mutable RefPtr<Core::Timer> m_video_frame_capture_keepalive_timer;
Optional<ScreenWakeLockHandle> m_screen_wake_lock;
diff --git a/Libraries/LibWeb/HTML/HTMLVideoElement.cpp b/Libraries/LibWeb/HTML/HTMLVideoElement.cpp
index aeefca78853..107ed690bf0 100644
--- a/Libraries/LibWeb/HTML/HTMLVideoElement.cpp
+++ b/Libraries/LibWeb/HTML/HTMLVideoElement.cpp
@@ -6,9 +6,11 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <AK/ScopeGuard.h>
#include <LibGC/Heap.h>
#include <LibGfx/Bitmap.h>
#include <LibGfx/DecodedImageFrame.h>
+#include <LibJS/Runtime/Object.h>
#include <LibWeb/Bindings/Wrappable.h>
#include <LibWeb/Bindings/WrapperWorld.h>
#include <LibWeb/CSS/ElementBoxKind.h>
@@ -25,6 +27,7 @@
#include <LibWeb/HTML/EventNames.h>
#include <LibWeb/HTML/HTMLVideoElement.h>
#include <LibWeb/HTML/Scripting/Environments.h>
+#include <LibWeb/HTML/Scripting/ExceptionReporter.h>
#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
#include <LibWeb/HTML/VideoTrack.h>
#include <LibWeb/HTML/VideoTrackList.h>
@@ -36,6 +39,7 @@
#include <LibWeb/PictureInPicture/PictureInPictureController.h>
#include <LibWeb/PictureInPicture/PictureInPictureWindow.h>
#include <LibWeb/Platform/ImageCodecPlugin.h>
+#include <LibWeb/WebIDL/AbstractOperations.h>
#include <LibWeb/WebIDL/DOMException.h>
#include <LibWeb/WebIDL/Promise.h>
@@ -63,6 +67,10 @@ void HTMLVideoElement::visit_edges(Cell::Visitor& visitor)
visitor.visit(m_picture_in_picture_window);
visitor.visit(m_pending_picture_in_picture_promises);
visitor.visit(m_visual_source);
+ for (auto const& entry : m_list_of_video_frame_request_callbacks)
+ visitor.visit(entry.callback);
+ for (auto const& entry : m_running_video_frame_request_callbacks)
+ visitor.visit(entry.callback);
}
void HTMLVideoElement::set_visual_source(GC::Ptr<HTMLVideoElement> source)
@@ -118,6 +126,8 @@ void HTMLVideoElement::adopted_from(DOM::Document& old_document)
if (m_load_event_delayer.has_value())
m_load_event_delayer.emplace(document());
+
+ release_presented_video_frame_held_for_callbacks();
}
void HTMLVideoElement::attribute_changed(Utf16FlyString const& name, Optional<Utf16String> const& old_value, Optional<Utf16String> const& value, Optional<Utf16FlyString> const& namespace_)
@@ -518,4 +528,121 @@ void HTMLVideoElement::set_onleavepictureinpicture(WebIDL::CallbackType* event_h
set_event_handler_attribute(HTML::EventNames::leavepictureinpicture, event_handler);
}
+// https://wicg.github.io/video-rvfc/#dom-htmlvideoelement-requestvideoframecallback
+WebIDL::UnsignedLong HTMLVideoElement::request_video_frame_callback(GC::Ref<WebIDL::CallbackType> callback)
+{
+ // 1. Let video be the HTMLVideoElement on which requestVideoFrameCallback is invoked.
+ // 2. Increment video's ownerDocument's video frame request callback identifier by one.
+ // 3. Let callbackId be video's ownerDocument's video frame request callback identifier
+ auto callback_id = document().increment_video_frame_request_callback_identifier();
+
+ // AD-HOC: Callbacks are "fired the next time a frame is presented to the compositor", so to ensure we don't invoke
+ // the callback on a frame that was presented before the request, update the identifier here.
+ if (m_list_of_video_frame_request_callbacks.is_empty())
+ m_last_presented_frame_identifier = presented_video_frame_count();
+
+ // 4. Append callback to video's list of video frame request callbacks, associated with callbackId.
+ m_list_of_video_frame_request_callbacks.append({ .handle = callback_id, .callback = callback });
+
+ // AD-HOC: A video that is not shown still presents frames while it has callbacks waiting for them.
+ if (m_list_of_video_frame_request_callbacks.size() == 1)
+ sync_video_sink_ticking();
+
+ request_rendering_update_for_video_frame_callbacks();
+
+ // 5. Return callbackId.
+ return callback_id;
+}
+
+// https://wicg.github.io/video-rvfc/#dom-htmlvideoelement-cancelvideoframecallback
+void HTMLVideoElement::cancel_video_frame_callback(WebIDL::UnsignedLong handle)
+{
+ // 1. Let video be the target HTMLVideoElement object on which cancelVideoFrameCallback is invoked.
+ // 2. Find the entry in video's list of video frame request callbacks that is associated with the value handle.
+ // 3. If there is such an entry, set its canceled boolean to true and remove it from video's list of video frame
+ // request callbacks.
+ m_list_of_video_frame_request_callbacks.remove_first_matching([&](auto const& entry) { return entry.handle == handle; });
+ if (m_list_of_video_frame_request_callbacks.is_empty())
+ video_sink_ticking_inputs_changed();
+ // NB: A canceled entry that is already being run keeps its place without its callback.
+ for (auto& entry : m_running_video_frame_request_callbacks) {
+ if (entry.handle == handle)
+ entry.callback = nullptr;
+ }
+}
+
+// https://wicg.github.io/video-rvfc/#run-the-video-frame-request-callbacks
+void HTMLVideoElement::run_the_video_frame_request_callbacks(HighResolutionTime::DOMHighResTimeStamp now)
+{
+ // 1. If video's list of video frame request callbacks is empty, abort these steps.
+ if (m_list_of_video_frame_request_callbacks.is_empty())
+ return;
+
+ // NB: The video may present the frame for the callbacks in a later rendering update.
+ ScopeGuard request_rendering_update_for_pending_callbacks = [&] {
+ request_rendering_update_for_video_frame_callbacks();
+ };
+
+ // 2. Let metadata be the VideoFrameCallbackMetadata dictionary built from video's latest presented frame.
+ // AD-HOC: The frame stays held until the rendering update has run its animation frame callbacks, so that the
+ // callbacks capture the frame that metadata describes.
+ auto presented_frame = hold_presented_video_frame_for_callbacks();
+ if (!presented_frame.has_value())
+ return;
+
+ // 3. Let presentedFrames be the value of metadata's presentedFrames field.
+ auto presented_frames = presented_frame->presented_frames;
+
+ // 4. If the last presented frame identifier is equal to presentedFrames, abort these steps.
+ if (m_last_presented_frame_identifier == presented_frames) {
+ release_presented_video_frame_held_for_callbacks();
+ return;
+ }
+
+ // 5. Set the last presented frame identifier to presentedFrames.
+ m_last_presented_frame_identifier = presented_frames;
+
+ auto& realm = relevant_realm(*this);
+ auto& global = relevant_global_object(*this);
+ auto metadata = JS::Object::create(realm, realm.intrinsics().object_prototype());
+ auto presentation_time = HighResolutionTime::relative_high_resolution_time(presented_frame->presentation_time.to_seconds_f64() * 1000.0, global);
+ MUST(metadata->create_data_property_or_throw("presentationTime"_utf16_fly_string, JS::Value(max(0.0, presentation_time))));
+ MUST(metadata->create_data_property_or_throw("expectedDisplayTime"_utf16_fly_string, JS::Value(now + document().page().client().rendering_frame_interval_in_milliseconds())));
+ MUST(metadata->create_data_property_or_throw("width"_utf16_fly_string, JS::Value(presented_frame->width)));
+ MUST(metadata->create_data_property_or_throw("height"_utf16_fly_string, JS::Value(presented_frame->height)));
+ MUST(metadata->create_data_property_or_throw("mediaTime"_utf16_fly_string, JS::Value(presented_frame->media_time.to_seconds_f64())));
+ MUST(metadata->create_data_property_or_throw("presentedFrames"_utf16_fly_string, JS::Value(static_cast<double>(presented_frames))));
+
+ // 6. Let callbacks be the list of video frame request callbacks.
+ // 7. Set video's list of video frame request callbacks to be empty.
+ m_running_video_frame_request_callbacks = move(m_list_of_video_frame_request_callbacks);
+ ScopeGuard clear_running_callbacks = [&] {
+ m_running_video_frame_request_callbacks.clear();
+ if (m_list_of_video_frame_request_callbacks.is_empty())
+ video_sink_ticking_inputs_changed();
+ };
+
+ // 8. For each entry of callbacks:
+ for (size_t index = 0; index < m_running_video_frame_request_callbacks.size(); index++) {
+ // 1. If entry's canceled boolean is true, continue.
+ auto callback = m_running_video_frame_request_callbacks[index].callback;
+ if (!callback)
+ continue;
+
+ // 2. Invoke entry with « now, metadata » and "report".
+ auto result = WebIDL::invoke_callback(*callback, {}, { { JS::Value(now), metadata } });
+ if (result.is_error())
+ report_exception(result, realm);
+ }
+}
+
+void HTMLVideoElement::request_rendering_update_for_video_frame_callbacks()
+{
+ if (m_list_of_video_frame_request_callbacks.is_empty())
+ return;
+ auto may_present_a_frame = potentially_playing() || seeking() || ready_state() < ReadyState::HaveCurrentData;
+ if (may_present_a_frame)
+ document().page().client().request_frame();
+}
+
}
diff --git a/Libraries/LibWeb/HTML/HTMLVideoElement.h b/Libraries/LibWeb/HTML/HTMLVideoElement.h
index 7b136ceeee6..9f5e1c616dd 100644
--- a/Libraries/LibWeb/HTML/HTMLVideoElement.h
+++ b/Libraries/LibWeb/HTML/HTMLVideoElement.h
@@ -70,6 +70,12 @@ public:
void for_each_visual_clone(Function<void(HTMLVideoElement&)> const&) const;
void clear_visual_clones();
+ WebIDL::UnsignedLong request_video_frame_callback(GC::Ref<WebIDL::CallbackType>);
+ void cancel_video_frame_callback(WebIDL::UnsignedLong handle);
+ bool has_video_frame_request_callbacks() const { return !m_list_of_video_frame_request_callbacks.is_empty(); }
+ void run_the_video_frame_request_callbacks(HighResolutionTime::DOMHighResTimeStamp now);
+ virtual void request_rendering_update_for_video_frame_callbacks() override;
+
WebIDL::CallbackType* onenterpictureinpicture();
void set_onenterpictureinpicture(WebIDL::CallbackType*);
WebIDL::CallbackType* onleavepictureinpicture();
@@ -112,6 +118,17 @@ private:
GC::Ptr<HTMLVideoElement> m_visual_source;
Vector<GC::Weak<HTMLVideoElement>> m_visual_clones;
+
+ struct VideoFrameRequestCallback {
+ WebIDL::UnsignedLong handle { 0 };
+ GC::Ptr<WebIDL::CallbackType> callback;
+ };
+ // https://wicg.github.io/video-rvfc/#list-of-video-frame-request-callbacks
+ Vector<VideoFrameRequestCallback> m_list_of_video_frame_request_callbacks;
+ // NB: The callbacks being run, which cancelVideoFrameCallback() also cancels by clearing their callback.
+ Vector<VideoFrameRequestCallback> m_running_video_frame_request_callbacks;
+ // https://wicg.github.io/video-rvfc/#last-presented-frame-identifier
+ u64 m_last_presented_frame_identifier { 0 };
};
}
diff --git a/Libraries/LibWeb/HTML/VideoFrameRequestCallback.idl b/Libraries/LibWeb/HTML/VideoFrameRequestCallback.idl
new file mode 100644
index 00000000000..0cb1ce0483d
--- /dev/null
+++ b/Libraries/LibWeb/HTML/VideoFrameRequestCallback.idl
@@ -0,0 +1,25 @@
+// https://wicg.github.io/video-rvfc/#dictdef-videoframecallbackmetadata
+dictionary VideoFrameCallbackMetadata {
+ required DOMHighResTimeStamp presentationTime;
+ required DOMHighResTimeStamp expectedDisplayTime;
+
+ required unsigned long width;
+ required unsigned long height;
+ required double mediaTime;
+
+ required unsigned long presentedFrames;
+ double processingDuration;
+
+ DOMHighResTimeStamp captureTime;
+ DOMHighResTimeStamp receiveTime;
+ unsigned long rtpTimestamp;
+};
+
+// https://wicg.github.io/video-rvfc/#callbackdef-videoframerequestcallback
+callback VideoFrameRequestCallback = undefined(DOMHighResTimeStamp now, VideoFrameCallbackMetadata metadata);
+
+// https://wicg.github.io/video-rvfc/#htmlvideoelement-extensions
+partial interface HTMLVideoElement {
+ unsigned long requestVideoFrameCallback(VideoFrameRequestCallback callback);
+ undefined cancelVideoFrameCallback(unsigned long handle);
+};
diff --git a/Libraries/LibWeb/Page/Page.cpp b/Libraries/LibWeb/Page/Page.cpp
index d355640dfe6..6975b6a008a 100644
--- a/Libraries/LibWeb/Page/Page.cpp
+++ b/Libraries/LibWeb/Page/Page.cpp
@@ -1557,6 +1557,16 @@ void Page::for_each_media_element(Callback&& callback)
}
}
+Vector<GC::Root<HTML::HTMLVideoElement>> Page::video_elements_of(DOM::Document const& document)
+{
+ Vector<GC::Root<HTML::HTMLVideoElement>> video_elements;
+ for_each_media_element([&](auto& media_element) {
+ if (auto* video_element = as_if<HTML::HTMLVideoElement>(media_element); video_element && &video_element->document() == &document)
+ video_elements.append(*video_element);
+ });
+ return video_elements;
+}
+
bool Page::has_media_element_playing_audio(DOM::Document const& document) const
{
for (auto media_id : m_media_elements) {
diff --git a/Libraries/LibWeb/Page/Page.h b/Libraries/LibWeb/Page/Page.h
index af4308f888c..b22d81e2514 100644
--- a/Libraries/LibWeb/Page/Page.h
+++ b/Libraries/LibWeb/Page/Page.h
@@ -353,6 +353,7 @@ public:
void register_media_element(Badge<HTML::HTMLMediaElement>, UniqueNodeID media_id);
void unregister_media_element(Badge<HTML::HTMLMediaElement>, UniqueNodeID media_id);
bool has_media_element_playing_audio(DOM::Document const&) const;
+ Vector<GC::Root<HTML::HTMLVideoElement>> video_elements_of(DOM::Document const&);
void sync_media_element_video_sink_ticking();
void restore_all_media_element_video_sinks();
@@ -706,6 +707,7 @@ public:
}
virtual HTML::CrossProcessId allocate_navigable_id() { return allocate_cross_process_id(); }
virtual void request_frame() = 0;
+ virtual double rendering_frame_interval_in_milliseconds() const { return 1000.0 / 60.0; }
virtual void rendering_opportunity([[maybe_unused]] i64 frame_time_nanoseconds, [[maybe_unused]] double frame_interval_milliseconds) { }
virtual void will_begin_rendering_update() { }
virtual bool has_rendering_opportunity() const { return true; }
diff --git a/Libraries/LibWeb/idl_files.cmake b/Libraries/LibWeb/idl_files.cmake
index 43e85bfefd4..c2f76ca7beb 100644
--- a/Libraries/LibWeb/idl_files.cmake
+++ b/Libraries/LibWeb/idl_files.cmake
@@ -371,6 +371,7 @@ libweb_js_bindings(HTML/ToggleEvent)
libweb_js_bindings(HTML/TrackEvent)
libweb_js_bindings(HTML/UserActivation)
libweb_js_bindings(HTML/ValidityState)
+libweb_js_bindings(HTML/VideoFrameRequestCallback)
libweb_js_bindings(HTML/VideoTrack)
libweb_js_bindings(HTML/VideoTrackList)
libweb_js_bindings(HTML/Window)
diff --git a/Services/Compositor/VideoFrameHolds.cpp b/Services/Compositor/VideoFrameHolds.cpp
index 83ddc860655..6f66a976a25 100644
--- a/Services/Compositor/VideoFrameHolds.cpp
+++ b/Services/Compositor/VideoFrameHolds.cpp
@@ -4,6 +4,7 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <AK/Time.h>
#include <Compositor/VideoFrameHolds.h>
#include <LibMediaCodecs/VideoFrame.h>
@@ -37,6 +38,16 @@ void VideoFrameHolds::present_frame(Media::VideoSinkHandle handle, RefPtr<Media:
retire_current_generation(handle, *sink, next_generation);
sink->generation = next_generation;
sink->frame = move(frame);
+
+ Compositing::VideoFramePresentationPage::PresentedFrame presented_frame { .generation = next_generation, .presentation_time = MonotonicTime::now() };
+ if (sink->frame) {
+ sink->presented_frame_count++;
+ presented_frame.media_time = sink->frame->timestamp();
+ presented_frame.width = sink->frame->width();
+ presented_frame.height = sink->frame->height();
+ }
+ presented_frame.presented_frame_count = sink->presented_frame_count;
+ sink->page->publish_presented_frame(presented_frame);
}
void VideoFrameHolds::retire_current_generation(Media::VideoSinkHandle handle, Sink& sink, u64 next_generation)
diff --git a/Services/Compositor/VideoFrameHolds.h b/Services/Compositor/VideoFrameHolds.h
index 5b1de44ee9b..43a3d67c2f8 100644
--- a/Services/Compositor/VideoFrameHolds.h
+++ b/Services/Compositor/VideoFrameHolds.h
@@ -31,6 +31,7 @@ private:
NonnullRefPtr<Compositing::VideoFramePresentationPage> page;
u64 generation { 0 };
RefPtr<Media::VideoFrame> frame;
+ u64 presented_frame_count { 0 };
};
struct RetainedFrame {
RefPtr<Media::VideoFrame> frame;
diff --git a/Services/WebContent/PageClient.h b/Services/WebContent/PageClient.h
index 3952019d2f4..4be25783854 100644
--- a/Services/WebContent/PageClient.h
+++ b/Services/WebContent/PageClient.h
@@ -226,6 +226,7 @@ private:
virtual Web::CSS::PreferredMotion preferred_motion() const override { return m_preferred_motion; }
virtual void request_frame() override;
virtual void rendering_opportunity(i64 frame_time_nanoseconds, double frame_interval_milliseconds) override;
+ virtual double rendering_frame_interval_in_milliseconds() const override { return m_last_rendering_opportunity_frame_interval; }
virtual void will_begin_rendering_update() override;
virtual bool has_rendering_opportunity() const override;
virtual void did_finish_rendering_update() override;
diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.ini
index f3dfb4e1d2b..b4c8738a058 100644
--- a/Tests/LibWeb/TestConfig.ini
+++ b/Tests/LibWeb/TestConfig.ini
@@ -42,6 +42,7 @@ Text/input/SiteIsolation/popup-opened-onto-a-coop-page-leaves-its-opener.html
; Loads videos from absolute /media/ URLs.
Text/input/wpt-import/picture-in-picture/
+Text/input/wpt-import/video-rvfc/
; fetching a file only works from an HTTP server.
Text/input/wpt-import/fetch/api/basic/text-utf8.any.html
diff --git a/Tests/LibWeb/Text/expected/HTML/HTMLVideoElement-requestVideoFrameCallback.txt b/Tests/LibWeb/Text/expected/HTML/HTMLVideoElement-requestVideoFrameCallback.txt
new file mode 100644
index 00000000000..7a40df1eba6
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/HTML/HTMLVideoElement-requestVideoFrameCallback.txt
@@ -0,0 +1,6 @@
+Paused at the start: mediaTime 0, 64x36, presentedFrames positive: true
+Timestamps: presentation before now: true, expected display after now: true
+After seeking to 2.05: mediaTime 2, captured second 2, presentedFrames increased: true
+After seeking to 3.05: mediaTime 3, canceled callback ran: false
+After seeking to 1.05 with 4.05 already presented: mediaTime 1
+While playing: 0 captures differed from their metadata, 0 callbacks did not advance presentedFrames
diff --git a/Tests/LibWeb/Text/expected/wpt-import/video-rvfc/idlharness.window.txt b/Tests/LibWeb/Text/expected/wpt-import/video-rvfc/idlharness.window.txt
new file mode 100644
index 00000000000..e8f77ede50d
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/video-rvfc/idlharness.window.txt
@@ -0,0 +1,23 @@
+Harness status: OK
+
+Found 18 tests
+
+18 Pass
+Pass idl_test setup
+Pass idl_test validation
+Pass Partial interface HTMLVideoElement: original interface defined
+Pass Partial interface HTMLVideoElement: member names are unique
+Pass Partial interface Element: member names are unique
+Pass HTMLElement includes GlobalEventHandlers: member names are unique
+Pass HTMLElement includes ElementContentEditable: member names are unique
+Pass HTMLElement includes HTMLOrSVGElement: member names are unique
+Pass Element includes ParentNode: member names are unique
+Pass Element includes NonDocumentTypeChildNode: member names are unique
+Pass Element includes ChildNode: member names are unique
+Pass Element includes Slottable: member names are unique
+Pass HTMLVideoElement interface: operation requestVideoFrameCallback(VideoFrameRequestCallback)
+Pass HTMLVideoElement interface: operation cancelVideoFrameCallback(unsigned long)
+Pass HTMLVideoElement interface: video must inherit property "requestVideoFrameCallback(VideoFrameRequestCallback)" with the proper type
+Pass HTMLVideoElement interface: calling requestVideoFrameCallback(VideoFrameRequestCallback) on video with too few arguments must throw TypeError
+Pass HTMLVideoElement interface: video must inherit property "cancelVideoFrameCallback(unsigned long)" with the proper type
+Pass HTMLVideoElement interface: calling cancelVideoFrameCallback(unsigned long) on video with too few arguments must throw TypeError
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/video-rvfc/request-video-frame-callback-dom.txt b/Tests/LibWeb/Text/expected/wpt-import/video-rvfc/request-video-frame-callback-dom.txt
new file mode 100644
index 00000000000..068b098fcd3
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/video-rvfc/request-video-frame-callback-dom.txt
@@ -0,0 +1,8 @@
+Harness status: OK
+
+Found 3 tests
+
+3 Pass
+Pass Test a video outside of the DOM can still use video.rVFC.
+Pass Test video.rVFC works with "display:none".
+Pass Test video.rVFC works with "visibility:hidden".
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/video-rvfc/request-video-frame-callback-parallel.txt b/Tests/LibWeb/Text/expected/wpt-import/video-rvfc/request-video-frame-callback-parallel.txt
new file mode 100644
index 00000000000..10f7aec612e
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/video-rvfc/request-video-frame-callback-parallel.txt
@@ -0,0 +1,7 @@
+Harness status: OK
+
+Found 2 tests
+
+2 Pass
+Pass Test callbacks get the same information.
+Pass Test we can cancel callbacks from callbacks.
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/video-rvfc/request-video-frame-callback-repeating.txt b/Tests/LibWeb/Text/expected/wpt-import/video-rvfc/request-video-frame-callback-repeating.txt
new file mode 100644
index 00000000000..955144eb0c9
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/video-rvfc/request-video-frame-callback-repeating.txt
@@ -0,0 +1,7 @@
+Harness status: OK
+
+Found 2 tests
+
+2 Pass
+Pass Test new callbacks are only called on the next frame.
+Pass Test chaining calls to video.rVFC, and verify the required parameters.
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/video-rvfc/request-video-frame-callback.txt b/Tests/LibWeb/Text/expected/wpt-import/video-rvfc/request-video-frame-callback.txt
new file mode 100644
index 00000000000..37e7170add3
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/video-rvfc/request-video-frame-callback.txt
@@ -0,0 +1,10 @@
+Harness status: OK
+
+Found 5 tests
+
+5 Pass
+Pass Test we can register a video.rVFC callback.
+Pass Test video.rVFC callbacks run before window.rAF callbacks.
+Pass Test we can cancel a video.rVFC request.
+Pass Test invalid calls to the video.rVFC API.
+Pass Test video.rVFC does not stop when switching sources.
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/input/HTML/HTMLVideoElement-requestVideoFrameCallback.html b/Tests/LibWeb/Text/input/HTML/HTMLVideoElement-requestVideoFrameCallback.html
new file mode 100644
index 00000000000..23eae2d8b8c
--- /dev/null
+++ b/Tests/LibWeb/Text/input/HTML/HTMLVideoElement-requestVideoFrameCallback.html
@@ -0,0 +1,76 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // The left half of each frame is red, and the right half is gray at 60 times the whole second mod 5.
+ function grayCapturedFrom(video) {
+ const canvas = document.createElement("canvas");
+ canvas.width = 64;
+ canvas.height = 36;
+ const context = canvas.getContext("2d", { willReadFrequently: true });
+ context.drawImage(video, 0, 0);
+ return { context, gray: () => Math.round(context.getImageData(48, 18, 1, 1).data[1] / 60) };
+ }
+
+ function nextVideoFrame(video, onFrame = () => {}) {
+ return new Promise(resolve => video.requestVideoFrameCallback((now, metadata) => resolve({ now, metadata, result: onFrame(now, metadata) })));
+ }
+
+ async function seekAndWait(video, time) {
+ const seeked = new Promise(resolve => video.addEventListener("seeked", resolve, { once: true }));
+ video.currentTime = time;
+ await seeked;
+ }
+
+ promiseTest(async () => {
+ internals.setAutoplayPolicy("allow-audio-and-video");
+ const video = document.createElement("video");
+ video.muted = true;
+ video.src = "../../../Assets/red-with-second-in-gray-64x36.webm";
+ document.body.append(video);
+
+ const first = await nextVideoFrame(video);
+ println(`Paused at the start: mediaTime ${first.metadata.mediaTime}, ${first.metadata.width}x${first.metadata.height}, presentedFrames positive: ${first.metadata.presentedFrames > 0}`);
+ println(`Timestamps: presentation before now: ${first.metadata.presentationTime <= first.now + 1}, expected display after now: ${first.metadata.expectedDisplayTime > first.now}`);
+
+ // A seek presents a new frame, and a capture in the callback draws the frame that the metadata describes.
+ const afterSeek = nextVideoFrame(video, () => grayCapturedFrom(video));
+ await seekAndWait(video, 2.05);
+ const seekFrame = await afterSeek;
+ println(`After seeking to 2.05: mediaTime ${seekFrame.metadata.mediaTime}, captured second ${seekFrame.result.gray()}, presentedFrames increased: ${seekFrame.metadata.presentedFrames > first.metadata.presentedFrames}`);
+
+ // A canceled callback does not run.
+ let canceledCallbackRan = false;
+ const handle = video.requestVideoFrameCallback(() => { canceledCallbackRan = true; });
+ video.cancelVideoFrameCallback(handle);
+ const afterCanceledSeek = nextVideoFrame(video);
+ await seekAndWait(video, 3.05);
+ const canceledSeekFrame = await afterCanceledSeek;
+ println(`After seeking to 3.05: mediaTime ${canceledSeekFrame.metadata.mediaTime}, canceled callback ran: ${canceledCallbackRan}`);
+
+ // A frame presented before the callback was requested is not new to it.
+ await seekAndWait(video, 4.05);
+ for (let i = 0; i < 3; i++)
+ await new Promise(resolve => requestAnimationFrame(resolve));
+ const afterStaleFrame = nextVideoFrame(video);
+ await new Promise(resolve => requestAnimationFrame(resolve));
+ video.currentTime = 1.05;
+ const staleFrameSeekFrame = await afterStaleFrame;
+ println(`After seeking to 1.05 with 4.05 already presented: mediaTime ${staleFrameSeekFrame.metadata.mediaTime}`);
+
+ // While playing, every capture in a callback draws the frame its metadata describes.
+ await video.play();
+ let previousPresentedFrames = staleFrameSeekFrame.metadata.presentedFrames;
+ let mismatches = 0;
+ let nonIncreasingPresentedFrames = 0;
+ for (let i = 0; i < 10; i++) {
+ const frame = await nextVideoFrame(video, (now, metadata) => grayCapturedFrom(video));
+ if (frame.result.gray() !== Math.floor(frame.metadata.mediaTime + 1e-6) % 5)
+ mismatches++;
+ if (frame.metadata.presentedFrames <= previousPresentedFrames)
+ nonIncreasingPresentedFrames++;
+ previousPresentedFrames = frame.metadata.presentedFrames;
+ }
+ video.pause();
+ println(`While playing: ${mismatches} captures differed from their metadata, ${nonIncreasingPresentedFrames} callbacks did not advance presentedFrames`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/interfaces/video-rvfc.idl b/Tests/LibWeb/Text/input/wpt-import/interfaces/video-rvfc.idl
new file mode 100644
index 00000000000..adb4ef2301d
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/interfaces/video-rvfc.idl
@@ -0,0 +1,27 @@
+// GENERATED CONTENT - DO NOT EDIT
+// Content was automatically extracted by Reffy into webref
+// (https://github.com/w3c/webref)
+// Source: HTMLVideoElement.requestVideoFrameCallback() (https://wicg.github.io/video-rvfc/)
+
+dictionary VideoFrameCallbackMetadata {
+ required DOMHighResTimeStamp presentationTime;
+ required DOMHighResTimeStamp expectedDisplayTime;
+
+ required unsigned long width;
+ required unsigned long height;
+ required double mediaTime;
+
+ required unsigned long presentedFrames;
+ double processingDuration;
+
+ DOMHighResTimeStamp captureTime;
+ DOMHighResTimeStamp receiveTime;
+ unsigned long rtpTimestamp;
+};
+
+callback VideoFrameRequestCallback = undefined(DOMHighResTimeStamp now, VideoFrameCallbackMetadata metadata);
+
+partial interface HTMLVideoElement {
+ unsigned long requestVideoFrameCallback(VideoFrameRequestCallback callback);
+ undefined cancelVideoFrameCallback(unsigned long handle);
+};
diff --git a/Tests/LibWeb/Text/input/wpt-import/media/counting.webm b/Tests/LibWeb/Text/input/wpt-import/media/counting.webm
new file mode 100644
index 00000000000..56d1f1c8acb
Binary files /dev/null and b/Tests/LibWeb/Text/input/wpt-import/media/counting.webm differ
diff --git a/Tests/LibWeb/Text/input/wpt-import/video-rvfc/idlharness.window.html b/Tests/LibWeb/Text/input/wpt-import/video-rvfc/idlharness.window.html
new file mode 100644
index 00000000000..7dc9de3dd78
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/video-rvfc/idlharness.window.html
@@ -0,0 +1,9 @@
+<!doctype html>
+<meta charset=utf-8>
+<meta name="timeout" content="long">
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="../resources/WebIDLParser.js"></script>
+<script src="../resources/idlharness.js"></script>
+<div id=log></div>
+<script src="../video-rvfc/idlharness.window.js"></script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/video-rvfc/idlharness.window.js b/Tests/LibWeb/Text/input/wpt-import/video-rvfc/idlharness.window.js
new file mode 100644
index 00000000000..fa9e4e0988b
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/video-rvfc/idlharness.window.js
@@ -0,0 +1,17 @@
+// META: script=/resources/WebIDLParser.js
+// META: script=/resources/idlharness.js
+// META: timeout=long
+
+'use strict';
+
+idl_test(
+ ['video-rvfc'],
+ ['html', 'dom'],
+ idl_array => {
+ idl_array.add_objects({
+ HTMLVideoElement: ['video'],
+ });
+ self.video = document.createElement('video');
+ }
+);
+
diff --git a/Tests/LibWeb/Text/input/wpt-import/video-rvfc/request-video-frame-callback-dom.html b/Tests/LibWeb/Text/input/wpt-import/video-rvfc/request-video-frame-callback-dom.html
new file mode 100644
index 00000000000..baad618c393
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/video-rvfc/request-video-frame-callback-dom.html
@@ -0,0 +1,61 @@
+<!DOCTYPE html>
+<html>
+<title>Test the video.requestVideoFrameCallback() API for non visible video elements.</title>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="../common/media.js"></script>
+<body>
+</body>
+<script>
+var testVideo = {
+ url: getVideoURI('/media/movie_5'),
+ height: 240,
+ width: 320,
+}
+
+promise_test(async function(t) {
+ let done;
+ const promise = new Promise(resolve => done = resolve);
+
+ let video = document.createElement('video');
+ video.muted = true;
+
+ video.requestVideoFrameCallback(done);
+ video.src = testVideo.url;
+ await video.play();
+
+ return promise;
+}, 'Test a video outside of the DOM can still use video.rVFC.');
+
+function rvfcStyleTest(applyStyle, description) {
+ promise_test(async function(t) {
+ let done;
+ const promise = new Promise(resolve => done = resolve);
+
+ let video = document.createElement('video');
+ video.muted = true;
+ document.body.appendChild(video);
+ applyStyle(video);
+
+ video.requestVideoFrameCallback(
+ t.step_func( _ => {
+ // Make sure we can receive more than one callback.
+ video.requestVideoFrameCallback(done);
+ })
+ );
+
+ video.src = testVideo.url;
+ await video.play();
+
+ return promise;
+ }, description);
+}
+
+rvfcStyleTest((video) => { video.style.display = "none"},
+ 'Test video.rVFC works with "display:none".');
+
+rvfcStyleTest((video) => { video.style.visibility = "hidden"},
+ 'Test video.rVFC works with "visibility:hidden".');
+
+</script>
+</html>
diff --git a/Tests/LibWeb/Text/input/wpt-import/video-rvfc/request-video-frame-callback-parallel.html b/Tests/LibWeb/Text/input/wpt-import/video-rvfc/request-video-frame-callback-parallel.html
new file mode 100644
index 00000000000..1d507a8e24d
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/video-rvfc/request-video-frame-callback-parallel.html
@@ -0,0 +1,67 @@
+<!DOCTYPE html>
+<html>
+<title>Test having multiple video.rVFC callbacks in flight for a single element.</title>
+<body></body>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="../common/media.js"></script>
+<script>
+
+promise_test(async function(t) {
+ let done;
+ const promise = new Promise(resolve => done = resolve);
+
+ let video = document.createElement('video');
+ video.muted = true;
+ document.body.appendChild(video);
+
+ let firstTime;
+ let firstMetadata;
+
+ video.requestVideoFrameCallback(t.step_func((time, metadata) => {
+ firstTime = time;
+ firstMetadata = metadata;
+ }));
+
+ video.requestVideoFrameCallback(t.step_func((time, metadata) => {
+ assert_equals(firstTime, time);
+ assert_object_equals(firstMetadata, metadata);
+ done();
+ }));
+
+ video.src = getVideoURI('/media/movie_5');
+ video.play();
+
+ return promise;
+}, 'Test callbacks get the same information.');
+
+promise_test(async function(t) {
+ let done;
+ const promise = new Promise(resolve => done = resolve);
+
+ let video = document.createElement('video');
+ video.muted = true;
+ document.body.appendChild(video);
+
+ let secondCallbackId;
+
+ video.requestVideoFrameCallback(
+ t.step_func(_ => { video.cancelVideoFrameCallback(secondCallbackId); })
+ );
+
+ secondCallbackId = video.requestVideoFrameCallback(
+ t.step_func(_ => {
+ assert_unreached("Cancelled callbacks shouldn't be executed")
+ })
+ );
+
+ // NOTE: This callback should be executed last.
+ video.requestVideoFrameCallback(done);
+
+ video.src = getVideoURI('/media/movie_5');
+ video.play();
+
+ return promise;
+}, 'Test we can cancel callbacks from callbacks.');
+</script>
+</html>
diff --git a/Tests/LibWeb/Text/input/wpt-import/video-rvfc/request-video-frame-callback-repeating.html b/Tests/LibWeb/Text/input/wpt-import/video-rvfc/request-video-frame-callback-repeating.html
new file mode 100644
index 00000000000..a477a959051
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/video-rvfc/request-video-frame-callback-repeating.html
@@ -0,0 +1,91 @@
+<!DOCTYPE html>
+<html>
+<title>Test repeatedly chaining video.rVFC() callbacks.</title>
+<body></body>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="../common/media.js"></script>
+<script>
+
+promise_test(async function(t) {
+ let done;
+ const promise = new Promise(resolve => done = resolve);
+
+ let video = document.createElement('video');
+ video.muted = true;
+ document.body.appendChild(video);
+
+ let firstTime;
+ video.requestVideoFrameCallback(t.step_func((time) => {
+ firstTime = time;
+
+ // Queue up a callback and make sure it's not immediately executed.
+ let secondTime;
+ video.requestVideoFrameCallback(t.step_func((time) => {
+ secondTime = time;
+ assert_greater_than(secondTime, firstTime, "Callbacks should be executed on the next frame");
+ }))
+
+ // Queue up a second callback, and make sure it's called at the same time
+ // as the one we just queued up.
+ video.requestVideoFrameCallback(t.step_func((time) => {
+ assert_equals(time, secondTime, "Callbacks queued together should be called at the same time");
+ done();
+ }))
+
+ }));
+
+ video.src = getVideoURI('/media/movie_5');
+ await video.play();
+
+ return promise;
+}, 'Test new callbacks are only called on the next frame.');
+
+promise_test(async function(t) {
+ let done;
+ const promise = new Promise(resolve => done = resolve);
+
+ let video = document.createElement('video');
+ video.muted = true;
+ document.body.appendChild(video);
+
+ let maxNumberOfCalls = 10;
+ let currentCallNumber = 0;
+ let lastMetadata;
+
+ function verifyMetadata(last, current) {
+ assert_greater_than(current.presentedFrames, last.presentedFrames, "presentedFrames should be monotonically increasing");
+ assert_greater_than(current.presentationTime, last.presentationTime, "presentationTime should be monotonically increasing");
+ assert_greater_than(current.expectedDisplayTime, last.expectedDisplayTime, "expectedDisplayTime should be monotonically increasing");
+
+ // We aren't seeking through the file, so this should be increasing from frame to frame.
+ assert_greater_than(current.mediaTime, last.mediaTime, "mediaTime should be increasing");
+
+ // The test video's size doesn't change.
+ assert_equals(current.width, last.width, "width should remain constant");
+ assert_equals(current.height, last.height, "height should remain constant");
+ }
+
+ function repeatingCallback(time, metadata) {
+ // Skip the first call to verifyMetadata.
+ if (currentCallNumber)
+ verifyMetadata(lastMetadata, metadata)
+
+ lastMetadata = metadata;
+
+ if (++currentCallNumber > maxNumberOfCalls) {
+ done()
+ } else {
+ video.requestVideoFrameCallback(t.step_func(repeatingCallback));
+ }
+ }
+
+ video.requestVideoFrameCallback(t.step_func(repeatingCallback));
+
+ video.src = getVideoURI('/media/movie_5');
+ await video.play();
+
+ return promise;
+}, 'Test chaining calls to video.rVFC, and verify the required parameters.');
+</script>
+</html>
diff --git a/Tests/LibWeb/Text/input/wpt-import/video-rvfc/request-video-frame-callback.html b/Tests/LibWeb/Text/input/wpt-import/video-rvfc/request-video-frame-callback.html
new file mode 100644
index 00000000000..1e1731d4d49
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/video-rvfc/request-video-frame-callback.html
@@ -0,0 +1,172 @@
+<!DOCTYPE html>
+<html>
+<title>Test the basics of the video.requestVideoFrameCallback() API.</title>
+<body></body>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="../common/media.js"></script>
+<script>
+var testVideo = {
+ url: getVideoURI('/media/movie_5'),
+ height: 240,
+ width: 320,
+}
+
+var altTestVideo = {
+ url: getVideoURI('/media/counting'),
+ height: 240,
+ width: 320,
+}
+
+promise_test(async function(t) {
+ let done;
+ const promise = new Promise(resolve => done = resolve);
+
+ let video = document.createElement('video');
+ video.muted = true;
+ document.body.appendChild(video);
+
+ let id = video.requestVideoFrameCallback(
+ t.step_func((time, metadata) => {
+ assert_true(time > 0);
+ assert_equals(metadata.height, testVideo.height);
+ assert_equals(metadata.width, testVideo.width);
+ done();
+ })
+ );
+
+ assert_true(id > 0);
+
+ video.src = testVideo.url;
+ await video.play();
+
+ return promise;
+}, 'Test we can register a video.rVFC callback.');
+
+promise_test(async function(t) {
+ let done;
+ const promise = new Promise(resolve => done = resolve);
+
+ let video = document.createElement('video');
+ video.muted = true;
+ document.body.appendChild(video);
+
+ video.requestVideoFrameCallback(
+ t.step_func(video_now => {
+ // Queue a call to window.rAF, and make sure it is executed within the
+ // same turn of the event loop (with the same 'time' parameter).
+ window.requestAnimationFrame( t.step_func( window_now => {
+ assert_equals(video_now, window_now);
+ done();
+ }));
+ })
+ );
+
+ video.src = testVideo.url;
+ await video.play();
+
+ return promise;
+}, 'Test video.rVFC callbacks run before window.rAF callbacks.');
+
+
+promise_test(async function(t) {
+ let done;
+ const promise = new Promise(resolve => done = resolve);
+
+ let video = document.createElement('video');
+ video.muted = true;
+ document.body.appendChild(video);
+
+ let id = video.requestVideoFrameCallback(
+ t.step_func(_ => {
+ assert_unreached("Cancelled callbacks shouldn't be executed")
+ })
+ );
+
+ video.cancelVideoFrameCallback(id);
+
+ video.requestVideoFrameCallback(
+ t.step_func(_ => {
+ // At this point, the other callback shouldn't have fired, but
+ // give it some more time and really make sure it doesn't, by going
+ // throught the event loop once more.
+ t.step_timeout(() => { done(); }, 0);
+ })
+ );
+
+ video.src = testVideo.url;
+ await video.play();
+
+ return promise;
+}, 'Test we can cancel a video.rVFC request.');
+
+test(function(t) {
+ let video = document.createElement('video');
+ video.muted = true;
+ document.body.appendChild(video);
+
+ // requestVideoFrameCallback() expects 1 function as a parameter.
+ assert_throws_js(TypeError, _ => { video.requestVideoFrameCallback() } );
+ assert_throws_js(TypeError, _ => { video.requestVideoFrameCallback(0) });
+ assert_throws_js(TypeError, _ => { video.requestVideoFrameCallback("foo") });
+
+ // cancelVideoFrameCallback() expects 1 number as a parameter
+ assert_throws_js(TypeError, _ => { video.cancelVideoFrameCallback() } );
+
+ // Invalid calls are just no-ops
+ video.cancelVideoFrameCallback(_ => {});
+ video.cancelVideoFrameCallback(NaN);
+ video.cancelVideoFrameCallback("foo");
+ video.cancelVideoFrameCallback(12345);
+ video.cancelVideoFrameCallback(-1);
+
+}, 'Test invalid calls to the video.rVFC API.');
+
+promise_test(async function(t) {
+ let video = document.createElement('video');
+ video.muted = true;
+ video.autoplay = true;
+ document.body.appendChild(video);
+
+ let first_width = 0;
+ let first_height = 0;
+
+ video.src = testVideo.url;
+
+ await video.play();
+
+ // Switch to and from a second video, and make sure we get rVFC calls at
+ // each step.
+ return new Promise((resolve, reject) => {
+ let onReturnToOriginalVideo = t.step_func((now, metadata) => {
+ assert_equals(first_width, metadata.width);
+ assert_equals(first_height, metadata.height);
+
+ resolve();
+ });
+
+ let onAltVideoFirstFrame = t.step_func((now, metadata) => {
+ // The videos have different sizes, and shouldn't match.
+ assert_not_equals(first_width, metadata.width);
+ assert_not_equals(first_height, metadata.height);
+
+ // Swith back to the original video.
+ video.requestVideoFrameCallback(onReturnToOriginalVideo);
+ video.src = testVideo.url;
+ });
+
+ let onFirstFrame = t.step_func((now, metadata) => {
+ first_width = metadata.width;
+ first_height = metadata.height;
+
+ // Callbacks should persist after changing the source to the alt video.
+ video.requestVideoFrameCallback(onAltVideoFirstFrame);
+ video.src = altTestVideo.url;
+ })
+
+ video.requestVideoFrameCallback(onFirstFrame);
+ });
+}, 'Test video.rVFC does not stop when switching sources.');
+
+</script>
+</html>