Skip to content

Truly independent web browser

LibCompositing+Compositor+LibWeb: Draw captured video in the Compositor

Zaggy1024ff4795475cc2
diff --git a/Libraries/LibCompositing/CMakeLists.txt b/Libraries/LibCompositing/CMakeLists.txt
index 6f2049c29b6..0a62b48c88e 100644
--- a/Libraries/LibCompositing/CMakeLists.txt
+++ b/Libraries/LibCompositing/CMakeLists.txt
@@ -20,6 +20,8 @@ set(SOURCES
Scrolling/WheelGestureIdentity.cpp
Types.cpp
UIOverlays.cpp
+ Video/VideoFrameHold.cpp
+ Video/VideoFramePresentationPage.cpp
WebGL/TextureUpload.cpp
WebGL/WebGLCommandList.cpp
)
diff --git a/Libraries/LibCompositing/DisplayList/Canvas2DCommandStream.cpp b/Libraries/LibCompositing/DisplayList/Canvas2DCommandStream.cpp
index fe19faf5ada..ee325a12433 100644
--- a/Libraries/LibCompositing/DisplayList/Canvas2DCommandStream.cpp
+++ b/Libraries/LibCompositing/DisplayList/Canvas2DCommandStream.cpp
@@ -27,6 +27,13 @@ Vector<DisplayListFontResource> Canvas2DCommandStream::take_fonts()
return fonts;
}
+void Canvas2DCommandStream::retain_video_frame_hold(NonnullRefPtr<VideoFrameHold> hold)
+{
+ if (!m_video_frame_holds.is_empty() && m_video_frame_holds.last().ptr() == hold.ptr())
+ return;
+ m_video_frame_holds.append(move(hold));
+}
+
void Canvas2DCommandStream::append_segment(CanvasId canvas_id, bool present)
{
if (!m_segments.is_empty())
diff --git a/Libraries/LibCompositing/DisplayList/Canvas2DCommandStream.h b/Libraries/LibCompositing/DisplayList/Canvas2DCommandStream.h
index 7169a5d377d..652d9cf267c 100644
--- a/Libraries/LibCompositing/DisplayList/Canvas2DCommandStream.h
+++ b/Libraries/LibCompositing/DisplayList/Canvas2DCommandStream.h
@@ -12,6 +12,7 @@
#include <LibCompositing/DisplayList/DisplayListResourceIds.h>
#include <LibCompositing/DisplayList/DisplayListResourceStorage.h>
#include <LibCompositing/Export.h>
+#include <LibCompositing/Video/VideoFrameHold.h>
#include <LibGfx/CanvasCommandList.h>
#include <LibIPC/Forward.h>
@@ -42,11 +43,15 @@ public:
FontResourceId add_font(Gfx::Font const&);
Vector<DisplayListFontResource> take_fonts();
+ void retain_video_frame_hold(NonnullRefPtr<VideoFrameHold>);
+ Vector<NonnullRefPtr<VideoFrameHold>> take_video_frame_holds() { return move(m_video_frame_holds); }
+
private:
void append_segment(CanvasId, bool present);
Vector<Canvas2DCommandStreamSegment> m_segments;
HashMap<u64, NonnullRefPtr<Gfx::Font const>> m_fonts;
+ Vector<NonnullRefPtr<VideoFrameHold>> m_video_frame_holds;
// The tail segment grows through the reference commands_for() hands out,
// so its command count is only known at query time.
size_t m_command_count_excluding_tail { 0 };
diff --git a/Libraries/LibCompositing/Video/VideoFrameHold.cpp b/Libraries/LibCompositing/Video/VideoFrameHold.cpp
new file mode 100644
index 00000000000..a0f735c26cd
--- /dev/null
+++ b/Libraries/LibCompositing/Video/VideoFrameHold.cpp
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibCompositing/Video/VideoFrameHold.h>
+#include <LibIPC/Decoder.h>
+#include <LibIPC/Encoder.h>
+
+namespace Compositing {
+
+RefPtr<VideoFrameHold> VideoFrameHold::hold_current_frame(NonnullRefPtr<VideoFramePresentationPage> page, Media::VideoSinkHandle sink_handle, ReleaseThroughCompositor release_through_compositor)
+{
+ auto generation = page->hold_current_generation();
+ if (!generation.has_value())
+ return nullptr;
+ return adopt_ref(*new VideoFrameHold(move(page), sink_handle, generation.value(), 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)
+ , m_generation(generation)
+ , m_release_through_compositor(move(release_through_compositor))
+{
+}
+
+VideoFrameHold::~VideoFrameHold()
+{
+ if (!m_was_sent_to_compositor && m_page->release_hold_if_current(m_generation) == VideoFramePresentationPage::ReleaseResult::Released)
+ return;
+ if (m_release_through_compositor)
+ m_release_through_compositor(m_sink_handle, m_generation);
+}
+
+}
+
+namespace IPC {
+
+template<>
+ErrorOr<void> encode(Encoder& encoder, Compositing::CapturedVideoFrame const& frame)
+{
+ TRY(encoder.encode(frame.sink_handle));
+ TRY(encoder.encode(frame.generation));
+ return {};
+}
+
+template<>
+ErrorOr<Compositing::CapturedVideoFrame> decode(Decoder& decoder)
+{
+ return Compositing::CapturedVideoFrame {
+ .sink_handle = TRY(decoder.decode<Media::VideoSinkHandle>()),
+ .generation = TRY(decoder.decode<u64>()),
+ .hold = nullptr,
+ };
+}
+
+}
diff --git a/Libraries/LibCompositing/Video/VideoFrameHold.h b/Libraries/LibCompositing/Video/VideoFrameHold.h
new file mode 100644
index 00000000000..937bfa7fd6d
--- /dev/null
+++ b/Libraries/LibCompositing/Video/VideoFrameHold.h
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Function.h>
+#include <AK/NonnullRefPtr.h>
+#include <AK/RefCounted.h>
+#include <AK/Weakable.h>
+#include <LibCompositing/Export.h>
+#include <LibCompositing/Video/VideoFramePresentationPage.h>
+#include <LibIPC/Forward.h>
+#include <LibMedia/VideoSinkHandle.h>
+
+namespace Compositing {
+
+class COMPOSITING_API VideoFrameHold final
+ : public RefCounted<VideoFrameHold>
+ , public Weakable<VideoFrameHold> {
+public:
+ using ReleaseThroughCompositor = Function<void(Media::VideoSinkHandle, u64 generation)>;
+
+ static RefPtr<VideoFrameHold> hold_current_frame(NonnullRefPtr<VideoFramePresentationPage>, Media::VideoSinkHandle, ReleaseThroughCompositor);
+ ~VideoFrameHold();
+
+ Media::VideoSinkHandle sink_handle() const { return m_sink_handle; }
+ u64 generation() const { return m_generation; }
+
+ void note_sent_to_compositor() { m_was_sent_to_compositor = true; }
+
+private:
+ VideoFrameHold(NonnullRefPtr<VideoFramePresentationPage>, Media::VideoSinkHandle, u64 generation, ReleaseThroughCompositor);
+
+ NonnullRefPtr<VideoFramePresentationPage> m_page;
+ Media::VideoSinkHandle m_sink_handle;
+ u64 m_generation { 0 };
+ ReleaseThroughCompositor m_release_through_compositor;
+ bool m_was_sent_to_compositor { false };
+};
+
+struct COMPOSITING_API CapturedVideoFrame {
+ Media::VideoSinkHandle sink_handle;
+ u64 generation { 0 };
+ RefPtr<VideoFrameHold> hold;
+};
+
+}
+
+namespace IPC {
+
+template<>
+COMPOSITING_API ErrorOr<void> encode(Encoder&, Compositing::CapturedVideoFrame const&);
+
+template<>
+COMPOSITING_API ErrorOr<Compositing::CapturedVideoFrame> decode(Decoder&);
+
+}
diff --git a/Libraries/LibCompositing/Video/VideoFramePresentationPage.cpp b/Libraries/LibCompositing/Video/VideoFramePresentationPage.cpp
new file mode 100644
index 00000000000..29d8526a123
--- /dev/null
+++ b/Libraries/LibCompositing/Video/VideoFramePresentationPage.cpp
@@ -0,0 +1,105 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibCompositing/Video/VideoFramePresentationPage.h>
+#include <LibIPC/Decoder.h>
+#include <LibIPC/Encoder.h>
+
+namespace Compositing {
+
+static_assert(__atomic_always_lock_free(sizeof(u64), nullptr));
+
+static constexpr size_t max_compare_exchange_attempts_before_assuming_a_misbehaving_peer = 64;
+
+ErrorOr<NonnullRefPtr<VideoFramePresentationPage>> VideoFramePresentationPage::create()
+{
+ return create(TRY(Core::AnonymousBuffer::create_with_size(sizeof(Atomic<u64>))));
+}
+
+ErrorOr<NonnullRefPtr<VideoFramePresentationPage>> VideoFramePresentationPage::create(Core::AnonymousBuffer buffer)
+{
+ if (!buffer.is_valid() || buffer.size() < sizeof(Atomic<u64>))
+ 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>()))
+{
+}
+
+u64 VideoFramePresentationPage::pack(GenerationAndHolds value)
+{
+ VERIFY(value.generation <= retired_generation);
+ VERIFY(value.hold_count <= max_hold_count);
+ return (value.generation << 16) | value.hold_count;
+}
+
+VideoFramePresentationPage::GenerationAndHolds VideoFramePresentationPage::unpack(u64 word)
+{
+ return { .generation = word >> 16, .hold_count = word & max_hold_count };
+}
+
+// Every change to the word is a read-modify-write, and it guards no other data, so nothing needs ordering.
+
+VideoFramePresentationPage::GenerationAndHolds VideoFramePresentationPage::replace_generation(u64 new_generation)
+{
+ return unpack(word().exchange(pack({ .generation = new_generation, .hold_count = 0 }), AK::MemoryOrder::memory_order_relaxed));
+}
+
+u64 VideoFramePresentationPage::current_generation() const
+{
+ return unpack(word().load(AK::MemoryOrder::memory_order_relaxed)).generation;
+}
+
+Optional<u64> VideoFramePresentationPage::hold_current_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 {};
+ 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;
+ }
+ return {};
+}
+
+VideoFramePresentationPage::ReleaseResult VideoFramePresentationPage::release_hold_if_current(u64 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 != generation)
+ return ReleaseResult::NotCurrent;
+ if (current.hold_count == 0)
+ return ReleaseResult::NotHeld;
+ auto released = pack({ .generation = current.generation, .hold_count = current.hold_count - 1 });
+ if (word().compare_exchange_strong(expected, released, AK::MemoryOrder::memory_order_relaxed))
+ return ReleaseResult::Released;
+ }
+ return ReleaseResult::NotHeld;
+}
+
+}
+
+namespace IPC {
+
+template<>
+ErrorOr<void> encode(Encoder& encoder, NonnullRefPtr<Compositing::VideoFramePresentationPage> const& page)
+{
+ return encoder.encode(page->buffer());
+}
+
+template<>
+ErrorOr<NonnullRefPtr<Compositing::VideoFramePresentationPage>> decode(Decoder& decoder)
+{
+ return Compositing::VideoFramePresentationPage::create(TRY(decoder.decode<Core::AnonymousBuffer>()));
+}
+
+}
diff --git a/Libraries/LibCompositing/Video/VideoFramePresentationPage.h b/Libraries/LibCompositing/Video/VideoFramePresentationPage.h
new file mode 100644
index 00000000000..4e46ce0c3e9
--- /dev/null
+++ b/Libraries/LibCompositing/Video/VideoFramePresentationPage.h
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Atomic.h>
+#include <AK/Error.h>
+#include <AK/NonnullRefPtr.h>
+#include <AK/Optional.h>
+#include <AK/RefCounted.h>
+#include <LibCompositing/Export.h>
+#include <LibCore/AnonymousBuffer.h>
+#include <LibIPC/Forward.h>
+
+namespace Compositing {
+
+// The generation and its hold count share one word, so a hold is either counted before the Compositor replaces the
+// generation, or fails and is retried on the new one.
+class COMPOSITING_API VideoFramePresentationPage : public RefCounted<VideoFramePresentationPage> {
+public:
+ static constexpr u64 retired_generation = (1ull << 48) - 1;
+ static constexpr u64 max_hold_count = (1ull << 16) - 1;
+
+ static ErrorOr<NonnullRefPtr<VideoFramePresentationPage>> create();
+ static ErrorOr<NonnullRefPtr<VideoFramePresentationPage>> create(Core::AnonymousBuffer);
+
+ Core::AnonymousBuffer const& buffer() const { return m_buffer; }
+
+ struct GenerationAndHolds {
+ u64 generation { 0 };
+ u64 hold_count { 0 };
+ };
+
+ GenerationAndHolds replace_generation(u64 new_generation);
+
+ u64 current_generation() const;
+ Optional<u64> hold_current_generation();
+
+ enum class ReleaseResult : u8 {
+ Released,
+ NotCurrent,
+ NotHeld,
+ };
+ ReleaseResult release_hold_if_current(u64 generation);
+
+private:
+ VideoFramePresentationPage(Core::AnonymousBuffer);
+
+ static u64 pack(GenerationAndHolds);
+ static GenerationAndHolds unpack(u64);
+
+ Atomic<u64>& word() const { return *m_word; }
+
+ Core::AnonymousBuffer m_buffer;
+ Atomic<u64>* m_word { nullptr };
+};
+
+}
+
+namespace IPC {
+
+template<>
+COMPOSITING_API ErrorOr<void> encode(Encoder&, NonnullRefPtr<Compositing::VideoFramePresentationPage> const&);
+
+template<>
+COMPOSITING_API ErrorOr<NonnullRefPtr<Compositing::VideoFramePresentationPage>> decode(Decoder&);
+
+}
diff --git a/Libraries/LibCompositing/WebGL/ImageSourceFrame.h b/Libraries/LibCompositing/WebGL/ImageSourceFrame.h
new file mode 100644
index 00000000000..c2e136bfc38
--- /dev/null
+++ b/Libraries/LibCompositing/WebGL/ImageSourceFrame.h
@@ -0,0 +1,17 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Variant.h>
+#include <LibCompositing/Video/VideoFrameHold.h>
+#include <LibGfx/DecodedImageFrame.h>
+
+namespace Compositing::WebGL {
+
+using ImageSourceFrame = Variant<Gfx::DecodedImageFrame, CapturedVideoFrame>;
+
+}
diff --git a/Libraries/LibGfx/CanvasCommandList.cpp b/Libraries/LibGfx/CanvasCommandList.cpp
index 242bee279de..592acff4be4 100644
--- a/Libraries/LibGfx/CanvasCommandList.cpp
+++ b/Libraries/LibGfx/CanvasCommandList.cpp
@@ -278,6 +278,35 @@ ErrorOr<Gfx::CanvasCommands::DrawCanvas> decode(Decoder& decoder)
};
}
+template<>
+ErrorOr<void> encode(Encoder& encoder, Gfx::CanvasCommands::DrawVideoFrame const& command)
+{
+ TRY(encoder.encode(command.video_sink_handle));
+ TRY(encoder.encode(command.generation));
+ TRY(encoder.encode(command.dst_rect));
+ TRY(encoder.encode(command.src_rect));
+ TRY(encoder.encode(command.scaling_mode));
+ TRY(encoder.encode(command.filter));
+ TRY(encoder.encode(command.global_alpha));
+ TRY(encoder.encode(command.compositing_and_blending_operator));
+ return {};
+}
+
+template<>
+ErrorOr<Gfx::CanvasCommands::DrawVideoFrame> decode(Decoder& decoder)
+{
+ return Gfx::CanvasCommands::DrawVideoFrame {
+ .video_sink_handle = TRY(decoder.decode<u64>()),
+ .generation = TRY(decoder.decode<u64>()),
+ .dst_rect = TRY(decoder.decode<Gfx::FloatRect>()),
+ .src_rect = TRY(decoder.decode<Gfx::IntRect>()),
+ .scaling_mode = TRY(decoder.decode<Gfx::ScalingMode>()),
+ .filter = TRY(decoder.decode<Optional<Gfx::Filter>>()),
+ .global_alpha = TRY(decoder.decode<float>()),
+ .compositing_and_blending_operator = TRY(decoder.decode<Gfx::CompositingAndBlendingOperator>()),
+ };
+}
+
template<>
ErrorOr<void> encode(Encoder& encoder, Gfx::CanvasCommands::FillPath const& command)
{
diff --git a/Libraries/LibGfx/CanvasCommandList.h b/Libraries/LibGfx/CanvasCommandList.h
index 12fc6f84768..f0262f03584 100644
--- a/Libraries/LibGfx/CanvasCommandList.h
+++ b/Libraries/LibGfx/CanvasCommandList.h
@@ -112,6 +112,17 @@ struct DrawCanvas {
CompositingAndBlendingOperator compositing_and_blending_operator { CompositingAndBlendingOperator::SourceOver };
};
+struct DrawVideoFrame {
+ u64 video_sink_handle { 0 };
+ u64 generation { 0 };
+ FloatRect dst_rect;
+ IntRect src_rect;
+ ScalingMode scaling_mode { ScalingMode::NearestNeighbor };
+ Optional<Filter> filter;
+ float global_alpha { 1 };
+ CompositingAndBlendingOperator compositing_and_blending_operator { CompositingAndBlendingOperator::SourceOver };
+};
+
struct FillPath {
Path path;
CanvasPaintStyle style;
@@ -164,6 +175,7 @@ using CanvasCommand = Variant<
CanvasCommands::FillRect,
CanvasCommands::DrawBitmap,
CanvasCommands::DrawCanvas,
+ CanvasCommands::DrawVideoFrame,
CanvasCommands::FillPath,
CanvasCommands::StrokePath,
CanvasCommands::SetTransform,
@@ -247,6 +259,11 @@ ErrorOr<void> encode(Encoder&, Gfx::CanvasCommands::DrawCanvas const&);
template<>
ErrorOr<Gfx::CanvasCommands::DrawCanvas> decode(Decoder&);
+template<>
+ErrorOr<void> encode(Encoder&, Gfx::CanvasCommands::DrawVideoFrame const&);
+template<>
+ErrorOr<Gfx::CanvasCommands::DrawVideoFrame> decode(Decoder&);
+
template<>
ErrorOr<void> encode(Encoder&, Gfx::CanvasCommands::FillPath const&);
template<>
diff --git a/Libraries/LibGfx/CanvasCommandPlayer.cpp b/Libraries/LibGfx/CanvasCommandPlayer.cpp
index fa9dc57b6f7..fd882031947 100644
--- a/Libraries/LibGfx/CanvasCommandPlayer.cpp
+++ b/Libraries/LibGfx/CanvasCommandPlayer.cpp
@@ -79,7 +79,22 @@ void CanvasCommandPlayer::play_command(CanvasCommands::DrawCanvas const& command
auto image = source_surface->sk_image_snapshot<sk_sp<SkImage>>();
if (!image)
return;
+ draw_image(*image, command);
+}
+
+void CanvasCommandPlayer::play_command(CanvasCommands::DrawVideoFrame const& command)
+{
+ if (!m_video_frame_image_resolver)
+ return;
+ auto image = m_video_frame_image_resolver(command.video_sink_handle, command.generation);
+ if (!image)
+ return;
+ draw_image(*image, command);
+}
+template<typename Command>
+void CanvasCommandPlayer::draw_image(SkImage const& image, Command const& command)
+{
SkPaint paint;
if (command.filter.has_value())
paint.setImageFilter(to_skia_image_filter(command.filter.value()));
@@ -87,7 +102,7 @@ void CanvasCommandPlayer::play_command(CanvasCommands::DrawCanvas const& command
paint.setBlender(to_skia_blender(command.compositing_and_blending_operator));
m_surface->canvas().drawImageRect(
- image.get(),
+ &image,
to_skia_rect(command.src_rect),
to_skia_rect(command.dst_rect),
to_skia_sampling_options(command.scaling_mode),
diff --git a/Libraries/LibGfx/CanvasCommandPlayer.h b/Libraries/LibGfx/CanvasCommandPlayer.h
index da04aa58b34..b7aa67e1c63 100644
--- a/Libraries/LibGfx/CanvasCommandPlayer.h
+++ b/Libraries/LibGfx/CanvasCommandPlayer.h
@@ -14,6 +14,10 @@
#include <LibGfx/CanvasCommandList.h>
#include <LibGfx/Forward.h>
+class SkImage;
+template<typename T>
+class sk_sp;
+
namespace Gfx {
class CanvasCommandPlayer {
@@ -25,12 +29,15 @@ public:
using FontResolver = Function<Font const*(u64)>;
using CanvasSurfaceResolver = Function<PaintingSurface const*(u64)>;
+ using VideoFrameImageResolver = Function<sk_sp<SkImage>(u64 video_sink_handle, u64 generation)>;
CanvasCommandPlayer(RefPtr<SkiaBackendContext>, IntSize, BitmapFormat, AlphaType, CanvasSurfaceResolver = {}, FontResolver = {});
~CanvasCommandPlayer();
NonnullRefPtr<PaintingSurface> surface() const;
+ void set_video_frame_image_resolver(VideoFrameImageResolver resolver) { m_video_frame_image_resolver = move(resolver); }
+
void clear(Color);
void play(CanvasCommandList const&);
@@ -41,6 +48,7 @@ private:
void play_command(CanvasCommands::FillRect const&);
void play_command(CanvasCommands::DrawBitmap const&);
void play_command(CanvasCommands::DrawCanvas const&);
+ void play_command(CanvasCommands::DrawVideoFrame const&);
void play_command(CanvasCommands::FillPath const&);
void play_command(CanvasCommands::StrokePath const&);
void play_command(CanvasCommands::SetTransform const&);
@@ -50,12 +58,16 @@ private:
void play_command(CanvasCommands::Reset const&);
void play_command(CanvasCommands::ClearCanvas const&);
+ template<typename Command>
+ void draw_image(SkImage const&, Command const&);
+
NonnullRefPtr<PaintStyle> resolve_paint_style(CanvasPaintStyle const&) const;
NonnullRefPtr<PaintingSurface> m_surface;
NonnullOwnPtr<PainterSkia> m_painter;
CanvasSurfaceResolver m_canvas_surface_resolver;
FontResolver m_font_resolver;
+ VideoFrameImageResolver m_video_frame_image_resolver;
};
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_gl/host.rs b/Libraries/LibWeb/Bindings/Rust/src/web_gl/host.rs
index 890e8947cb9..925ca2a1b1e 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/web_gl/host.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_gl/host.rs
@@ -113,7 +113,7 @@ pub(crate) struct Frame(NonNull<c_void>);
impl Frame {
/// # Safety
///
- /// `frame` is a Gfx::DecodedImageFrame allocated with `new`, which the value takes over.
+ /// `frame` is a Compositing::WebGL::ImageSourceFrame allocated with `new`, which the value takes over.
pub(crate) unsafe fn from_raw(frame: NonNull<c_void>) -> Self {
Self(frame)
}
diff --git a/Libraries/LibWeb/Compositor/CompositorConnection.cpp b/Libraries/LibWeb/Compositor/CompositorConnection.cpp
index cacae3e2b2c..de93ec028dd 100644
--- a/Libraries/LibWeb/Compositor/CompositorConnection.cpp
+++ b/Libraries/LibWeb/Compositor/CompositorConnection.cpp
@@ -271,12 +271,12 @@ void CompositorConnection::hand_frame_sink_to_paint_thread()
paint_stage_adopt_frame_sink(&sink.leak_ref());
}
-void CompositorConnection::add_video_sink(Media::VideoSinkHandle video_sink_handle)
+void CompositorConnection::add_video_sink(Media::VideoSinkHandle video_sink_handle, NonnullRefPtr<Compositing::VideoFramePresentationPage> presentation_page)
{
if (!can_send_message_to_compositor())
return;
ensure_video_presentation_channel();
- async_add_video_sink(video_sink_handle);
+ async_add_video_sink(video_sink_handle, move(presentation_page));
}
void CompositorConnection::remove_video_sink(Media::VideoSinkHandle video_sink_handle)
@@ -286,6 +286,21 @@ void CompositorConnection::remove_video_sink(Media::VideoSinkHandle video_sink_h
async_remove_video_sink(video_sink_handle);
}
+void CompositorConnection::release_video_frame_hold(Media::VideoSinkHandle video_sink_handle, u64 generation)
+{
+ if (!can_send_message_to_compositor())
+ return;
+ async_release_video_frame_hold(video_sink_handle, generation);
+}
+
+static void note_video_frame_holds_sent_to_compositor(Vector<Compositing::WebGL::ImageSourceFrame> const& frames)
+{
+ for (auto const& frame : frames) {
+ if (auto const* captured_frame = frame.get_pointer<Compositing::CapturedVideoFrame>(); captured_frame && captured_frame->hold)
+ captured_frame->hold->note_sent_to_compositor();
+ }
+}
+
void CompositorConnection::set_video_sink_ticking(Media::VideoSinkHandle video_sink_handle, bool should_tick)
{
if (!can_send_message_to_compositor())
@@ -342,11 +357,14 @@ void CompositorConnection::update_canvas_2d_stream(Compositing::Canvas2DCommandS
}
auto encoded_message = MUST(Messages::CompositorWebContentServer::UpdateCanvas2dStream::static_encode(stream.take_segments(), move(kept_font_ids), move(added_fonts)));
+ auto video_frame_holds = stream.take_video_frame_holds();
if (post_message(encoded_message).is_error()) {
did_lose_compositor();
return;
}
m_canvas_font_ids_held_by_compositor = move(font_ids_of_this_batch);
+ for (auto& hold : video_frame_holds)
+ hold->note_sent_to_compositor();
}
void CompositorConnection::destroy_canvas_context(Compositing::CanvasId canvas_id)
@@ -651,14 +669,17 @@ void CompositorConnection::set_webgl_command_buffer(Compositing::CanvasId canvas
did_lose_compositor();
}
-void CompositorConnection::send_webgl_commands_from_shared_buffer(Compositing::CanvasId canvas_id, u64 offset, u64 size_in_bytes, u64 flush_sequence_number, Vector<Gfx::DecodedImageFrame> const& bitmaps)
+void CompositorConnection::send_webgl_commands_from_shared_buffer(Compositing::CanvasId canvas_id, u64 offset, u64 size_in_bytes, u64 flush_sequence_number, Vector<Compositing::WebGL::ImageSourceFrame> const& frames)
{
if (!can_send_message_to_compositor())
return;
- auto encoded_message = MUST(Messages::CompositorWebContentServer::WebglCommandsFromSharedBuffer::static_encode(canvas_id, offset, size_in_bytes, flush_sequence_number, bitmaps));
- if (post_message(encoded_message).is_error())
+ auto encoded_message = MUST(Messages::CompositorWebContentServer::WebglCommandsFromSharedBuffer::static_encode(canvas_id, offset, size_in_bytes, flush_sequence_number, frames));
+ if (post_message(encoded_message).is_error()) {
did_lose_compositor();
+ return;
+ }
+ note_video_frame_holds_sent_to_compositor(frames);
}
bool CompositorConnection::drain_webgl_command_buffer(Compositing::CanvasId canvas_id)
@@ -674,7 +695,7 @@ bool CompositorConnection::drain_webgl_command_buffer(Compositing::CanvasId canv
return true;
}
-void CompositorConnection::send_webgl_commands(Compositing::CanvasId canvas_id, ReadonlyBytes commands, Vector<Gfx::DecodedImageFrame> const& bitmaps)
+void CompositorConnection::send_webgl_commands(Compositing::CanvasId canvas_id, ReadonlyBytes commands, Vector<Compositing::WebGL::ImageSourceFrame> const& frames)
{
if (!can_send_message_to_compositor())
return;
@@ -682,9 +703,12 @@ void CompositorConnection::send_webgl_commands(Compositing::CanvasId canvas_id,
auto shared_commands = MUST(Core::AnonymousBuffer::create_with_size(commands.size()));
commands.copy_to({ shared_commands.data<u8>(), shared_commands.size() });
- auto encoded_message = MUST(Messages::CompositorWebContentServer::WebglCommands::static_encode(canvas_id, shared_commands, bitmaps));
- if (post_message(encoded_message).is_error())
+ auto encoded_message = MUST(Messages::CompositorWebContentServer::WebglCommands::static_encode(canvas_id, shared_commands, frames));
+ if (post_message(encoded_message).is_error()) {
did_lose_compositor();
+ return;
+ }
+ note_video_frame_holds_sent_to_compositor(frames);
}
void CompositorConnection::present_webgl_canvas(Compositing::CanvasId canvas_id, bool preserve_drawing_buffer)
diff --git a/Libraries/LibWeb/Compositor/CompositorConnection.h b/Libraries/LibWeb/Compositor/CompositorConnection.h
index c6ff1717d1f..2e0114f4ec8 100644
--- a/Libraries/LibWeb/Compositor/CompositorConnection.h
+++ b/Libraries/LibWeb/Compositor/CompositorConnection.h
@@ -51,8 +51,9 @@ public:
void destroy_context(Web::CompositorContextId);
// Has the Paint thread present frames through this connection from now on.
void hand_frame_sink_to_paint_thread();
- void add_video_sink(Media::VideoSinkHandle);
+ void add_video_sink(Media::VideoSinkHandle, NonnullRefPtr<Compositing::VideoFramePresentationPage>);
void remove_video_sink(Media::VideoSinkHandle);
+ void release_video_frame_hold(Media::VideoSinkHandle, u64 generation);
void set_video_sink_ticking(Media::VideoSinkHandle, bool should_tick);
Optional<Compositing::CanvasId> create_canvas_2d_context(Gfx::IntSize, bool alpha);
void update_canvas_2d_stream(Compositing::Canvas2DCommandStream&);
@@ -81,9 +82,9 @@ public:
Optional<Compositing::CanvasId> create_webgl_context(Compositing::WebGL::WebGLVersion, Gfx::IntSize, bool depth, bool stencil, bool antialias, Vector<String>& out_supported_extensions);
void set_webgl_command_buffer(Compositing::CanvasId, Core::AnonymousBuffer const&);
- void send_webgl_commands_from_shared_buffer(Compositing::CanvasId, u64 offset, u64 size_in_bytes, u64 flush_sequence_number, Vector<Gfx::DecodedImageFrame> const& bitmaps);
+ void send_webgl_commands_from_shared_buffer(Compositing::CanvasId, u64 offset, u64 size_in_bytes, u64 flush_sequence_number, Vector<Compositing::WebGL::ImageSourceFrame> const& frames);
bool drain_webgl_command_buffer(Compositing::CanvasId);
- void send_webgl_commands(Compositing::CanvasId, ReadonlyBytes, Vector<Gfx::DecodedImageFrame> const& bitmaps);
+ void send_webgl_commands(Compositing::CanvasId, ReadonlyBytes, Vector<Compositing::WebGL::ImageSourceFrame> const& frames);
void present_webgl_canvas(Compositing::CanvasId, bool preserve_drawing_buffer);
void clear_webgl_drawing_buffer(Compositing::CanvasId);
ByteBuffer webgl_sync_call(Compositing::CanvasId, ByteBuffer request);
diff --git a/Libraries/LibWeb/Compositor/CompositorHost.cpp b/Libraries/LibWeb/Compositor/CompositorHost.cpp
index 8138aa389fb..75f9523c713 100644
--- a/Libraries/LibWeb/Compositor/CompositorHost.cpp
+++ b/Libraries/LibWeb/Compositor/CompositorHost.cpp
@@ -151,6 +151,7 @@ void CompositorHost::flush_canvas_2d_stream()
void CompositorHost::discard_canvas_2d_stream()
{
(void)m_canvas_2d_stream->take_segments();
+ (void)m_canvas_2d_stream->take_video_frame_holds();
}
class CompositorRemoteWebGLTransport final : public Web::WebGL::RemoteWebGLTransport {
@@ -193,11 +194,11 @@ private:
m_connection->set_webgl_command_buffer(*m_canvas_id, command_buffer);
}
- virtual void send_commands_from_shared_buffer(u64 offset, u64 size_in_bytes, u64 flush_sequence_number, Vector<Gfx::DecodedImageFrame> const& bitmaps) override
+ virtual void send_commands_from_shared_buffer(u64 offset, u64 size_in_bytes, u64 flush_sequence_number, Vector<Compositing::WebGL::ImageSourceFrame> const& frames) override
{
if (!m_canvas_id.has_value())
return;
- m_connection->send_webgl_commands_from_shared_buffer(*m_canvas_id, offset, size_in_bytes, flush_sequence_number, bitmaps);
+ m_connection->send_webgl_commands_from_shared_buffer(*m_canvas_id, offset, size_in_bytes, flush_sequence_number, frames);
}
virtual bool wait_until_published_commands_executed() override
@@ -207,11 +208,11 @@ private:
return m_connection->drain_webgl_command_buffer(*m_canvas_id);
}
- virtual void send_commands(ReadonlyBytes commands, Vector<Gfx::DecodedImageFrame> const& bitmaps) override
+ virtual void send_commands(ReadonlyBytes commands, Vector<Compositing::WebGL::ImageSourceFrame> const& frames) override
{
if (!m_canvas_id.has_value())
return;
- m_connection->send_webgl_commands(*m_canvas_id, commands, bitmaps);
+ m_connection->send_webgl_commands(*m_canvas_id, commands, frames);
}
virtual void present_canvas(bool preserve_drawing_buffer) override
@@ -398,10 +399,10 @@ void CompositorHost::stop_presenting_to_client(Web::CompositorContextId context_
connection->stop_presenting_to_client(context_id);
}
-void CompositorHost::add_video_sink(Media::VideoSinkHandle video_sink_handle)
+void CompositorHost::add_video_sink(Media::VideoSinkHandle video_sink_handle, NonnullRefPtr<Compositing::VideoFramePresentationPage> presentation_page)
{
if (auto* connection = compositor_connection())
- connection->add_video_sink(video_sink_handle);
+ connection->add_video_sink(video_sink_handle, move(presentation_page));
}
void CompositorHost::remove_video_sink(Media::VideoSinkHandle video_sink_handle)
@@ -416,6 +417,17 @@ void CompositorHost::set_video_sink_ticking(Media::VideoSinkHandle video_sink_ha
connection->set_video_sink_ticking(video_sink_handle, should_tick);
}
+Compositing::VideoFrameHold::ReleaseThroughCompositor CompositorHost::video_frame_hold_releaser_for_current_connection() const
+{
+ auto* connection = compositor_connection();
+ if (!connection)
+ return {};
+ return [weak_connection = connection->make_weak_ptr<CompositorConnection>()](Media::VideoSinkHandle video_sink_handle, u64 generation) {
+ if (auto connection = weak_connection.strong_ref())
+ connection->release_video_frame_hold(video_sink_handle, generation);
+ };
+}
+
void CompositorHost::invalidate_keyboard_scroll_state(Web::CompositorContextId context_id, u64 generation)
{
if (auto* connection = compositor_connection())
diff --git a/Libraries/LibWeb/Compositor/CompositorHost.h b/Libraries/LibWeb/Compositor/CompositorHost.h
index cff288beed2..45158f0d209 100644
--- a/Libraries/LibWeb/Compositor/CompositorHost.h
+++ b/Libraries/LibWeb/Compositor/CompositorHost.h
@@ -15,6 +15,7 @@
#include <LibCompositing/DisplayList/DisplayListResourceStorage.h>
#include <LibCompositing/Scrolling/AsyncScrollTree.h>
#include <LibCompositing/Types.h>
+#include <LibCompositing/Video/VideoFrameHold.h>
#include <LibGfx/Bitmap.h>
#include <LibGfx/Point.h>
#include <LibGfx/Rect.h>
@@ -115,9 +116,10 @@ public:
void set_parent_context(Web::CompositorContextId, Optional<Web::CompositorContextId>);
void stop_presenting_to_client(Web::CompositorContextId);
- void add_video_sink(Media::VideoSinkHandle);
+ void add_video_sink(Media::VideoSinkHandle, NonnullRefPtr<Compositing::VideoFramePresentationPage>);
void remove_video_sink(Media::VideoSinkHandle);
void set_video_sink_ticking(Media::VideoSinkHandle, bool should_tick);
+ Compositing::VideoFrameHold::ReleaseThroughCompositor video_frame_hold_releaser_for_current_connection() const;
void invalidate_wheel_event_listener_state(Web::CompositorContextId, u64 generation);
void invalidate_keyboard_scroll_state(Web::CompositorContextId, u64 generation);
Compositing::AsyncScrollEnqueueResult async_scroll_by(Web::CompositorContextId, UniqueNodeID expected_document_id, Gfx::FloatPoint position,
diff --git a/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp b/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp
index b1302fbc067..9059d146cf2 100644
--- a/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp
+++ b/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp
@@ -263,6 +263,29 @@ WebIDL::ExceptionOr<void> Canvas2DContextBase::draw_image_internal(CanvasImageSo
}
}
+ if (auto const* source_video = image.get_pointer<GC::Ref<HTMLVideoElement>>()) {
+ auto captured_frame = (*source_video)->capture_current_video_frame();
+ if (!captured_frame.has_value())
+ return {};
+ if (auto* canvas_command_list = this->canvas_command_list()) {
+ canvas_command_list->append(Gfx::CanvasCommands::DrawVideoFrame {
+ .video_sink_handle = captured_frame->sink_handle.value(),
+ .generation = captured_frame->generation,
+ .dst_rect = destination_rect,
+ .src_rect = source_rect.to_rounded<int>(),
+ .scaling_mode = scaling_mode,
+ .filter = drawing_state().filter,
+ .global_alpha = drawing_state().global_alpha,
+ .compositing_and_blending_operator = drawing_state().current_compositing_and_blending_operator,
+ });
+ m_transport->shared_stream().retain_video_frame_hold(*captured_frame->hold);
+ did_draw(destination_rect);
+ }
+ if (image_is_not_origin_clean(image))
+ m_origin_clean = false;
+ return {};
+ }
+
auto frame = canvas_image_source_frame(image);
if (!frame.has_value())
return {};
diff --git a/Libraries/LibWeb/HTML/Canvas/CanvasDrawImage.cpp b/Libraries/LibWeb/HTML/Canvas/CanvasDrawImage.cpp
index 554bb23759d..a4437eb58f4 100644
--- a/Libraries/LibWeb/HTML/Canvas/CanvasDrawImage.cpp
+++ b/Libraries/LibWeb/HTML/Canvas/CanvasDrawImage.cpp
@@ -96,8 +96,8 @@ Optional<Gfx::DecodedImageFrame> canvas_image_source_frame(CanvasImageSource con
return {};
return Gfx::DecodedImageFrame { *bitmap };
},
- [](GC::Ref<HTMLVideoElement> const& source) -> Optional<Gfx::DecodedImageFrame> {
- return source->current_decoded_image_frame();
+ [](GC::Ref<HTMLVideoElement> const&) -> Optional<Gfx::DecodedImageFrame> {
+ VERIFY_NOT_REACHED();
});
}
diff --git a/Libraries/LibWeb/HTML/CanvasPattern.cpp b/Libraries/LibWeb/HTML/CanvasPattern.cpp
index 7ecf9429d17..ca140318844 100644
--- a/Libraries/LibWeb/HTML/CanvasPattern.cpp
+++ b/Libraries/LibWeb/HTML/CanvasPattern.cpp
@@ -6,13 +6,19 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <LibCompositing/DisplayList/Canvas2DCommandStream.h>
#include <LibGC/Heap.h>
+#include <LibGfx/CanvasCommandList.h>
#include <LibGfx/DecodedImageFrame.h>
#include <LibJS/Runtime/VM.h>
#include <LibWeb/Bindings/DOMMatrixReadOnly.h>
+#include <LibWeb/Compositor/CompositorHost.h>
#include <LibWeb/Geometry/DOMMatrix.h>
+#include <LibWeb/HTML/Canvas/RemoteCanvas2DTransport.h>
#include <LibWeb/HTML/CanvasPattern.h>
#include <LibWeb/HTML/CanvasRenderingContext2D.h>
+#include <LibWeb/HTML/HTMLVideoElement.h>
+#include <LibWeb/Page/Page.h>
namespace Web::HTML {
@@ -25,6 +31,43 @@ CanvasPattern::CanvasPattern(Gfx::CanvasPatternPaintStyle& pattern)
CanvasPattern::~CanvasPattern() = default;
+// A pattern outlives any one video frame, so it reads the frame back instead of holding it.
+static Optional<Gfx::DecodedImageFrame> read_back_current_video_frame(HTMLVideoElement& video)
+{
+ auto captured_frame = video.capture_current_video_frame();
+ if (!captured_frame.has_value())
+ return {};
+ auto& page = video.document().page();
+ if (!page.has_compositor_host())
+ return {};
+ auto transport = page.compositor_host().create_canvas_2d_transport();
+ if (!transport)
+ return {};
+
+ Gfx::IntRect frame_rect { 0, 0, static_cast<int>(video.video_width()), static_cast<int>(video.video_height()) };
+ if (frame_rect.is_empty() || !transport->create_context(frame_rect.size(), true))
+ return {};
+
+ auto& stream = transport->shared_stream();
+ stream.commands_for(transport->canvas_id().value()).append(Gfx::CanvasCommands::DrawVideoFrame {
+ .video_sink_handle = captured_frame->sink_handle.value(),
+ .generation = captured_frame->generation,
+ .dst_rect = frame_rect.to_type<float>(),
+ .src_rect = frame_rect,
+ .scaling_mode = Gfx::ScalingMode::NearestNeighbor,
+ .filter = {},
+ .global_alpha = 1,
+ .compositing_and_blending_operator = Gfx::CompositingAndBlendingOperator::Copy,
+ });
+ stream.retain_video_frame_hold(*captured_frame->hold);
+ transport->flush_shared_stream();
+ auto bitmap = transport->read_back_pixels(frame_rect, Gfx::AlphaType::Premultiplied);
+ transport->destroy_context();
+ if (!bitmap)
+ return {};
+ return Gfx::DecodedImageFrame { NonnullRefPtr<Gfx::Bitmap const> { bitmap.release_nonnull() } };
+}
+
// https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-createpattern
WebIDL::ExceptionOr<GC::Ptr<CanvasPattern>> CanvasPattern::create(CanvasImageSource const& image, Utf16FlyString const& repetition)
{
@@ -60,7 +103,11 @@ WebIDL::ExceptionOr<GC::Ptr<CanvasPattern>> CanvasPattern::create(CanvasImageSou
return WebIDL::SyntaxError::create("Repetition value is not valid"_utf16);
// 6. Let pattern be a new CanvasPattern object with the image image and the repetition behavior given by repetition.
- auto frame = canvas_image_source_frame(image);
+ Optional<Gfx::DecodedImageFrame> frame;
+ if (auto const* video = image.get_pointer<GC::Ref<HTMLVideoElement>>())
+ frame = read_back_current_video_frame(*video);
+ else
+ frame = canvas_image_source_frame(image);
auto paint_style = TRY_OR_THROW_OOM(JS::VM::the(), Gfx::CanvasPatternPaintStyle::create(frame, *repetition_value));
// FIXME: 7. If image is not origin-clean, then mark pattern as not origin-clean.
diff --git a/Libraries/LibWeb/HTML/HTMLMediaElement.cpp b/Libraries/LibWeb/HTML/HTMLMediaElement.cpp
index ad70957d3df..77000450a0d 100644
--- a/Libraries/LibWeb/HTML/HTMLMediaElement.cpp
+++ b/Libraries/LibWeb/HTML/HTMLMediaElement.cpp
@@ -91,7 +91,8 @@ public:
return;
unregister();
m_compositor_host = &compositor_host;
- m_compositor_host->add_video_sink(m_handle);
+ m_presentation_page = MUST(Compositing::VideoFramePresentationPage::create());
+ m_compositor_host->add_video_sink(m_handle, *m_presentation_page);
}
void unregister()
@@ -100,12 +101,30 @@ public:
return;
m_compositor_host->remove_video_sink(m_handle);
m_compositor_host = nullptr;
+ m_presentation_page = nullptr;
+ m_latest_hold = nullptr;
+ }
+
+ Optional<Compositing::CapturedVideoFrame> capture_current_frame()
+ {
+ if (!m_compositor_host || !m_presentation_page)
+ return {};
+ 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());
+ if (!hold)
+ return {};
+ m_latest_hold = *hold;
+ }
+ return Compositing::CapturedVideoFrame { .sink_handle = m_handle, .generation = hold->generation(), .hold = hold };
}
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;
};
static u64 s_next_remote_fetch_data_id = 0;
@@ -1838,13 +1857,12 @@ Optional<Compositing::VideoSinkResourceId> HTMLMediaElement::video_sink_resource
return m_active_video_sink->resource_id();
}
-RefPtr<Media::VideoFrame> HTMLMediaElement::current_presented_frame() const
+Optional<Compositing::CapturedVideoFrame> HTMLMediaElement::capture_current_video_frame() const
{
- auto handle = video_sink_handle();
- if (!m_playback_manager || !handle.has_value())
- return nullptr;
+ if (!m_active_video_sink)
+ return {};
note_frame_captured();
- return m_playback_manager->current_presented_frame(*handle);
+ return m_active_video_sink->capture_current_frame();
}
void HTMLMediaElement::attach_selected_video_track_sink(Media::Track const& track)
diff --git a/Libraries/LibWeb/HTML/HTMLMediaElement.h b/Libraries/LibWeb/HTML/HTMLMediaElement.h
index 38ef8ec4d35..3a756a03c7e 100644
--- a/Libraries/LibWeb/HTML/HTMLMediaElement.h
+++ b/Libraries/LibWeb/HTML/HTMLMediaElement.h
@@ -15,6 +15,7 @@
#include <AK/Utf16View.h>
#include <AK/Variant.h>
#include <LibCompositing/DisplayList/DisplayListResourceIds.h>
+#include <LibCompositing/Video/VideoFrameHold.h>
#include <LibCore/Forward.h>
#include <LibGC/RootVector.h>
#include <LibGfx/Rect.h>
@@ -190,7 +191,7 @@ public:
CORSSettingAttribute crossorigin() const { return m_crossorigin; }
Optional<Media::VideoSinkHandle> video_sink_handle() const;
- RefPtr<Media::VideoFrame> current_presented_frame() const;
+ Optional<Compositing::CapturedVideoFrame> capture_current_video_frame() const;
Optional<Compositing::VideoSinkResourceId> video_sink_resource_id() const;
diff --git a/Libraries/LibWeb/HTML/HTMLVideoElement.cpp b/Libraries/LibWeb/HTML/HTMLVideoElement.cpp
index d339aa8a1a3..aeefca78853 100644
--- a/Libraries/LibWeb/HTML/HTMLVideoElement.cpp
+++ b/Libraries/LibWeb/HTML/HTMLVideoElement.cpp
@@ -9,7 +9,6 @@
#include <LibGC/Heap.h>
#include <LibGfx/Bitmap.h>
#include <LibGfx/DecodedImageFrame.h>
-#include <LibMediaCodecs/VideoFrame.h>
#include <LibWeb/Bindings/Wrappable.h>
#include <LibWeb/Bindings/WrapperWorld.h>
#include <LibWeb/CSS/ElementBoxKind.h>
@@ -395,26 +394,6 @@ HTMLVideoElement::Representation HTMLVideoElement::current_representation() cons
return Representation::VideoFrame;
}
-Optional<Gfx::DecodedImageFrame> HTMLVideoElement::current_decoded_image_frame() const
-{
- auto current_frame = current_presented_frame();
- if (!current_frame)
- return {};
-
- auto bitmap_or_error = current_frame->to_bitmap();
- if (bitmap_or_error.is_error()) {
- dbgln("Could not convert video frame to bitmap: {}", bitmap_or_error.release_error());
- return {};
- }
- if (!current_frame->revalidate_backing())
- return {};
- auto bitmap = bitmap_or_error.release_value();
- auto color_space = Gfx::ColorSpace {};
- if (auto color_space_result = Gfx::ColorSpace::from_cicp(current_frame->cicp()); !color_space_result.is_error())
- color_space = color_space_result.release_value();
- return Gfx::DecodedImageFrame { NonnullRefPtr<Gfx::Bitmap const> { *bitmap }, move(color_space) };
-}
-
// https://w3c.github.io/picture-in-picture/#request-picture-in-picture
GC::Ref<WebIDL::Promise> HTMLVideoElement::request_picture_in_picture()
{
diff --git a/Libraries/LibWeb/HTML/HTMLVideoElement.h b/Libraries/LibWeb/HTML/HTMLVideoElement.h
index ddf97b8a69b..7b136ceeee6 100644
--- a/Libraries/LibWeb/HTML/HTMLVideoElement.h
+++ b/Libraries/LibWeb/HTML/HTMLVideoElement.h
@@ -54,8 +54,6 @@ public:
};
Representation current_representation() const;
- Optional<Gfx::DecodedImageFrame> current_decoded_image_frame() const;
-
GC::Ref<WebIDL::Promise> request_picture_in_picture();
// Whether requestPictureInPicture() would enter Picture-in-Picture if it were given a user activation.
bool can_enter_picture_in_picture() const;
diff --git a/Libraries/LibWeb/WebGL/RemoteWebGLTransport.h b/Libraries/LibWeb/WebGL/RemoteWebGLTransport.h
index 46d46536aab..d1dc2c5c676 100644
--- a/Libraries/LibWeb/WebGL/RemoteWebGLTransport.h
+++ b/Libraries/LibWeb/WebGL/RemoteWebGLTransport.h
@@ -13,8 +13,8 @@
#include <AK/Vector.h>
#include <LibCompositing/DisplayList/DisplayListResourceIds.h>
#include <LibCompositing/Types.h>
+#include <LibCompositing/WebGL/ImageSourceFrame.h>
#include <LibCore/AnonymousBuffer.h>
-#include <LibGfx/DecodedImageFrame.h>
#include <LibGfx/Forward.h>
#include <LibGfx/ShareableBitmap.h>
#include <LibWeb/Export.h>
@@ -35,10 +35,10 @@ public:
virtual void destroy_context() = 0;
virtual void set_shared_command_buffer(Core::AnonymousBuffer const&) = 0;
- virtual void send_commands_from_shared_buffer(u64 offset, u64 size_in_bytes, u64 flush_sequence_number, Vector<Gfx::DecodedImageFrame> const& bitmaps) = 0;
+ virtual void send_commands_from_shared_buffer(u64 offset, u64 size_in_bytes, u64 flush_sequence_number, Vector<Compositing::WebGL::ImageSourceFrame> const& frames) = 0;
virtual bool wait_until_published_commands_executed() = 0;
- virtual void send_commands(ReadonlyBytes, Vector<Gfx::DecodedImageFrame> const& bitmaps) = 0;
+ virtual void send_commands(ReadonlyBytes, Vector<Compositing::WebGL::ImageSourceFrame> const& frames) = 0;
virtual void present_canvas(bool preserve_drawing_buffer) = 0;
virtual void clear_drawing_buffer() = 0;
virtual ByteBuffer sync_call(ByteBuffer request) = 0;
@@ -48,4 +48,11 @@ public:
virtual Gfx::ShareableBitmap read_back_drawing_buffer(Gfx::IntRect const&) = 0;
};
+// NB: The frame is a Variant, which cannot be allocated with kmalloc itself.
+struct ImageSourceFrameOwnedByRecorder {
+ AK_ALLOC_WITH_KMALLOC;
+
+ Compositing::WebGL::ImageSourceFrame frame;
+};
+
}
diff --git a/Libraries/LibWeb/WebGL/RemoteWebGLTransportFFI.cpp b/Libraries/LibWeb/WebGL/RemoteWebGLTransportFFI.cpp
index 738a96f79f2..c1e8fd36178 100644
--- a/Libraries/LibWeb/WebGL/RemoteWebGLTransportFFI.cpp
+++ b/Libraries/LibWeb/WebGL/RemoteWebGLTransportFFI.cpp
@@ -11,7 +11,6 @@
#include <LibCompositing/WebGL/WebGLSharedCommandBuffer.h>
#include <LibCore/AnonymousBuffer.h>
#include <LibGfx/Bitmap.h>
-#include <LibGfx/DecodedImageFrame.h>
#include <LibGfx/ShareableBitmap.h>
#include <LibIPC/Limits.h>
#include <LibWeb/Loader/ResourceLoader.h>
@@ -21,7 +20,7 @@
// which declares these functions in host.rs.
//
// The recorder holds a transport and a bitmap as a pointer that owns one reference, and an anonymous buffer and an
-// image frame as a pointer to an AnonymousBufferOwnedByRecorder or a Gfx::DecodedImageFrame that it owns.
+// image frame as a pointer to an AnonymousBufferOwnedByRecorder or an ImageSourceFrameOwnedByRecorder that it owns.
namespace Web::WebGL {
@@ -99,12 +98,12 @@ static Core::AnonymousBuffer const& anonymous_buffer_from(void const* anonymous_
return static_cast<AnonymousBufferOwnedByRecorder const*>(anonymous_buffer)->buffer;
}
-static Vector<Gfx::DecodedImageFrame> copy_frames(void const* const* frames, size_t frame_count)
+static Vector<Compositing::WebGL::ImageSourceFrame> copy_frames(void const* const* frames, size_t frame_count)
{
- Vector<Gfx::DecodedImageFrame> copied_frames;
+ Vector<Compositing::WebGL::ImageSourceFrame> copied_frames;
copied_frames.ensure_capacity(frame_count);
for (size_t i = 0; i < frame_count; ++i)
- copied_frames.unchecked_append(*static_cast<Gfx::DecodedImageFrame const*>(frames[i]));
+ copied_frames.unchecked_append(static_cast<ImageSourceFrameOwnedByRecorder const*>(frames[i])->frame);
return copied_frames;
}
@@ -226,7 +225,7 @@ void web_webgl_anonymous_buffer_destroy(void* anonymous_buffer)
void web_webgl_frame_destroy(void* frame)
{
- delete static_cast<Gfx::DecodedImageFrame*>(frame);
+ delete static_cast<ImageSourceFrameOwnedByRecorder*>(frame);
}
void web_webgl_bitmap_unref(void* bitmap)
diff --git a/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.cpp b/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.cpp
index 04c87d70216..70a0296af0b 100644
--- a/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.cpp
+++ b/Libraries/LibWeb/WebGL/WebGLRenderingContextBase.cpp
@@ -501,10 +501,11 @@ TexImageSourceResult web_webgl_read_tex_image_source(void* source_wrapper, TexIm
// a SECURITY_ERR exception must be thrown. See Origin Restrictions.
// FIXME: If source is null then an INVALID_VALUE error is generated.
auto& wrapper = *static_cast<JS::Object*>(source_wrapper);
- Optional<Gfx::DecodedImageFrame> frame;
+ Optional<Compositing::WebGL::ImageSourceFrame> frame;
switch (source_kind) {
case TexImageSourceKind::HTMLImageElement:
- frame = Bindings::impl_from<HTML::HTMLImageElement>(wrapper).current_image_frame();
+ if (auto image_frame = Bindings::impl_from<HTML::HTMLImageElement>(wrapper).current_image_frame(); image_frame.has_value())
+ frame = image_frame.release_value();
break;
case TexImageSourceKind::HTMLCanvasElement:
if (auto bitmap = Bindings::impl_from<HTML::HTMLCanvasElement>(wrapper).get_bitmap_from_surface())
@@ -515,7 +516,8 @@ TexImageSourceResult web_webgl_read_tex_image_source(void* source_wrapper, TexIm
frame = Gfx::DecodedImageFrame { *bitmap };
break;
case TexImageSourceKind::HTMLVideoElement:
- frame = Bindings::impl_from<HTML::HTMLVideoElement>(wrapper).current_decoded_image_frame();
+ if (auto captured_frame = Bindings::impl_from<HTML::HTMLVideoElement>(wrapper).capture_current_video_frame(); captured_frame.has_value())
+ frame = captured_frame.release_value();
break;
case TexImageSourceKind::ImageBitmap:
frame = Gfx::DecodedImageFrame { *Bindings::impl_from<HTML::ImageBitmap>(wrapper).bitmap() };
@@ -548,7 +550,7 @@ TexImageSourceResult web_webgl_read_tex_image_source(void* source_wrapper, TexIm
return TexImageSourceResult::NoFrame;
// FIXME: Respect unpackColorSpace
- *out_frame = new Gfx::DecodedImageFrame(frame.release_value());
+ *out_frame = new ImageSourceFrameOwnedByRecorder { frame.release_value() };
return TexImageSourceResult::Frame;
}
diff --git a/Services/Compositor/CMakeLists.txt b/Services/Compositor/CMakeLists.txt
index 487e8eedd3d..5851a3f55c0 100644
--- a/Services/Compositor/CMakeLists.txt
+++ b/Services/Compositor/CMakeLists.txt
@@ -24,6 +24,7 @@ set(SOURCES
ScrollFlingController.cpp
ScrollSnapController.cpp
ScrollbarController.cpp
+ VideoFrameHolds.cpp
VideoFrameSkia.cpp
VSyncScheduler.cpp
WebGLObjectMap.cpp
diff --git a/Services/Compositor/CanvasHost.cpp b/Services/Compositor/CanvasHost.cpp
index d711483494d..4e293880c65 100644
--- a/Services/Compositor/CanvasHost.cpp
+++ b/Services/Compositor/CanvasHost.cpp
@@ -6,20 +6,35 @@
#include <Compositor/CanvasHost.h>
#include <Compositor/HostWebGLContext.h>
+#include <Compositor/VideoFrameHolds.h>
+#include <Compositor/VideoFrameSkia.h>
#include <LibCompositing/DisplayList/Canvas2DCommandStream.h>
#include <LibCompositing/DisplayList/CanvasSurfaceRegistry.h>
#include <LibCompositing/DisplayList/DisplayList.h>
#include <LibGfx/Bitmap.h>
#include <LibGfx/CanvasCommandPlayer.h>
+#include <LibGfx/ColorSpace.h>
#include <LibGfx/PaintingSurface.h>
#include <LibGfx/SkiaBackendContext.h>
+#include <LibMediaCodecs/VideoFrame.h>
+#include <core/SkImage.h>
namespace Compositor {
-CanvasHost::CanvasHost(RefPtr<Gfx::SkiaBackendContext> skia_backend_context, Compositing::CanvasSurfaceRegistry& canvas_surface_registry)
+struct CanvasHost::VideoFrameImage {
+ AK_ALLOC_WITH_KMALLOC;
+
+ u64 generation { 0 };
+ // Kept until replaced, since the GPU samples the image after the commands are played.
+ RefPtr<Media::VideoFrame> frame;
+ sk_sp<SkImage> image;
+};
+
+CanvasHost::CanvasHost(RefPtr<Gfx::SkiaBackendContext> skia_backend_context, Compositing::CanvasSurfaceRegistry& canvas_surface_registry, VideoFrameHolds const& video_frame_holds)
: m_skia_backend_context(move(skia_backend_context))
, m_canvas_surface_registry(canvas_surface_registry)
, m_canvas_surface_owner_id(canvas_surface_registry.allocate_owner_id())
+ , m_video_frame_holds(video_frame_holds)
{
}
@@ -53,6 +68,9 @@ OwnPtr<Gfx::CanvasCommandPlayer> CanvasHost::create_2d_command_player(Gfx::IntSi
return &m_text_resources.font(Compositing::FontResourceId { font_id });
};
auto player = make<Gfx::CanvasCommandPlayer>(m_skia_backend_context, size, format, Gfx::AlphaType::Premultiplied, move(canvas_surface_resolver), move(font_resolver));
+ player->set_video_frame_image_resolver([this](u64 video_sink_handle, u64 generation) {
+ return held_video_frame_image(Media::VideoSinkHandle { video_sink_handle }, generation);
+ });
// https://html.spec.whatwg.org/multipage/canvas.html#the-canvas-settings:concept-canvas-alpha
// "Thus, the bitmap of such a context starts off as opaque black instead of transparent black"
@@ -152,6 +170,7 @@ void CanvasHost::execute_canvas_2d_stream(Vector<Compositing::Canvas2DCommandStr
resources.fonts.set(font.id);
}
m_text_resources.retain_only(resources);
+ Vector<NonnullRefPtr<Gfx::PaintingSurface>> surfaces_that_sample_video_frames;
for (auto const& segment : segments) {
// The canvas may have been destroyed while this segment was pending in
// WebContent, so a missing context is not a protocol violation.
@@ -161,20 +180,81 @@ void CanvasHost::execute_canvas_2d_stream(Vector<Compositing::Canvas2DCommandStr
continue;
if (!segment.commands.is_empty()) {
+ m_drew_video_frame_in_segment = false;
canvas_context->command_player->play(segment.commands);
canvas_context->has_uncommitted_commands = true;
+ if (m_drew_video_frame_in_segment && !surfaces_that_sample_video_frames.contains_slow(canvas_context->command_player->surface()))
+ surfaces_that_sample_video_frames.append(canvas_context->command_player->surface());
}
if (segment.present && canvas_context->has_uncommitted_commands)
present_canvas_2d_context(segment.canvas_id, *canvas_context);
}
+
+ // The frames stay held only until WebContent releases them, which follows this stream, so the GPU has to have
+ // finished sampling them by then.
+ if (m_skia_backend_context) {
+ for (auto& surface : surfaces_that_sample_video_frames)
+ m_skia_backend_context->flush_and_submit(surface);
+ }
+}
+
+sk_sp<SkImage> CanvasHost::held_video_frame_image(Media::VideoSinkHandle handle, u64 generation)
+{
+ if (auto cached = m_video_frame_images.get(handle); cached.has_value() && (*cached)->generation == generation)
+ return (*cached)->image;
+
+ m_drew_video_frame_in_segment = true;
+ auto frame = m_video_frame_holds.held_frame(handle, generation);
+ if (!frame)
+ return nullptr;
+ auto image = sk_image_from_video_frame(*frame, m_skia_backend_context);
+ if (!image)
+ return nullptr;
+ m_video_frame_images.set(handle, make<VideoFrameImage>(generation, move(frame), image));
+ return image;
+}
+
+void CanvasHost::forget_video_sink(Media::VideoSinkHandle handle)
+{
+ m_video_frame_images.remove(handle);
+}
+
+Vector<Gfx::DecodedImageFrame> CanvasHost::resolve_webgl_image_source_frames(Vector<Compositing::WebGL::ImageSourceFrame> const& frames) const
+{
+ Vector<Gfx::DecodedImageFrame> resolved_frames;
+ resolved_frames.ensure_capacity(frames.size());
+ for (auto const& frame : frames) {
+ auto resolved_frame = frame.visit(
+ [](Gfx::DecodedImageFrame const& decoded_frame) -> Optional<Gfx::DecodedImageFrame> {
+ return decoded_frame;
+ },
+ [&](Compositing::CapturedVideoFrame const& captured_frame) -> Optional<Gfx::DecodedImageFrame> {
+ auto video_frame = m_video_frame_holds.held_frame(captured_frame.sink_handle, captured_frame.generation);
+ if (!video_frame)
+ return {};
+ auto bitmap_or_error = video_frame->to_bitmap();
+ if (bitmap_or_error.is_error()) {
+ dbgln("Could not convert video frame to bitmap: {}", bitmap_or_error.release_error());
+ return {};
+ }
+ auto color_space = Gfx::ColorSpace {};
+ if (auto color_space_result = Gfx::ColorSpace::from_cicp(video_frame->cicp()); !color_space_result.is_error())
+ color_space = color_space_result.release_value();
+ return Gfx::DecodedImageFrame { NonnullRefPtr<Gfx::Bitmap const> { bitmap_or_error.release_value() }, move(color_space) };
+ });
+ if (!resolved_frame.has_value())
+ resolved_frame = Gfx::DecodedImageFrame { NonnullRefPtr<Gfx::Bitmap const> { MUST(Gfx::Bitmap::create(Gfx::BitmapFormat::BGRA8888, { 1, 1 })) } };
+ resolved_frames.unchecked_append(resolved_frame.release_value());
+ }
+ return resolved_frames;
}
-void CanvasHost::execute_webgl_commands(Compositing::CanvasId canvas_id, ReadonlyBytes commands, Vector<Gfx::DecodedImageFrame> const& bitmaps)
+void CanvasHost::execute_webgl_commands(Compositing::CanvasId canvas_id, ReadonlyBytes commands, Vector<Compositing::WebGL::ImageSourceFrame> const& frames)
{
auto* context = this->context(canvas_id);
VERIFY(context);
- MUST(as_webgl(*context).execute_commands(commands, bitmaps));
+ MUST(as_webgl(*context).execute_commands(commands, resolve_webgl_image_source_frames(frames)));
}
void CanvasHost::set_webgl_shared_command_buffer(Compositing::CanvasId canvas_id, Compositing::WebGL::WebGLSharedCommandBuffer shared_command_buffer)
@@ -184,7 +264,7 @@ void CanvasHost::set_webgl_shared_command_buffer(Compositing::CanvasId canvas_id
as_webgl(*context).set_shared_command_buffer(move(shared_command_buffer));
}
-bool CanvasHost::execute_webgl_commands_from_shared_buffer(Compositing::CanvasId canvas_id, u64 offset, u64 size_in_bytes, u64 flush_sequence_number, Vector<Gfx::DecodedImageFrame> const& bitmaps)
+bool CanvasHost::execute_webgl_commands_from_shared_buffer(Compositing::CanvasId canvas_id, u64 offset, u64 size_in_bytes, u64 flush_sequence_number, Vector<Compositing::WebGL::ImageSourceFrame> const& frames)
{
auto* context = this->context(canvas_id);
VERIFY(context);
@@ -196,7 +276,7 @@ bool CanvasHost::execute_webgl_commands_from_shared_buffer(Compositing::CanvasId
// WebContent can rewrite shared bytes while they execute, so a malformed stream is
// a misbehaving peer rather than a Compositor bug; report instead of crashing.
- if (webgl_context.execute_commands(*commands, bitmaps).is_error())
+ if (webgl_context.execute_commands(*commands, resolve_webgl_image_source_frames(frames)).is_error())
return false;
webgl_context.store_executed_flush_sequence_number(flush_sequence_number);
return true;
diff --git a/Services/Compositor/CanvasHost.h b/Services/Compositor/CanvasHost.h
index e290eb28cc6..2e795349e8b 100644
--- a/Services/Compositor/CanvasHost.h
+++ b/Services/Compositor/CanvasHost.h
@@ -22,11 +22,19 @@
#include <LibCompositing/DisplayList/DisplayListResourceIds.h>
#include <LibCompositing/Forward.h>
#include <LibCompositing/Types.h>
+#include <LibCompositing/WebGL/ImageSourceFrame.h>
#include <LibCompositing/WebGL/Types.h>
#include <LibCompositing/WebGL/WebGLSharedCommandBuffer.h>
#include <LibCore/AnonymousBuffer.h>
#include <LibGfx/Forward.h>
#include <LibGfx/ShareableBitmap.h>
+#include <LibMedia/VideoSinkHandle.h>
+#include <LibMediaCodecs/Forward.h>
+
+class SkImage;
+
+template<typename T>
+class sk_sp;
namespace Compositing {
@@ -37,6 +45,7 @@ class CanvasSurfaceRegistry;
namespace Compositor {
class HostWebGLContext;
+class VideoFrameHolds;
class CanvasHost {
public:
@@ -46,7 +55,7 @@ public:
Vector<String> supported_extensions;
};
- CanvasHost(RefPtr<Gfx::SkiaBackendContext>, Compositing::CanvasSurfaceRegistry&);
+ CanvasHost(RefPtr<Gfx::SkiaBackendContext>, Compositing::CanvasSurfaceRegistry&, VideoFrameHolds const&);
~CanvasHost();
bool create_2d_context(Compositing::CanvasId, Gfx::IntSize, bool alpha);
@@ -55,9 +64,9 @@ public:
bool has_context(Compositing::CanvasId) const;
void execute_canvas_2d_stream(Vector<Compositing::Canvas2DCommandStreamSegment> const&, Vector<Compositing::FontResourceId> const& kept_font_ids, Vector<Compositing::DisplayListFontResource> const& added_fonts);
- void execute_webgl_commands(Compositing::CanvasId, ReadonlyBytes, Vector<Gfx::DecodedImageFrame> const&);
+ void execute_webgl_commands(Compositing::CanvasId, ReadonlyBytes, Vector<Compositing::WebGL::ImageSourceFrame> const&);
void set_webgl_shared_command_buffer(Compositing::CanvasId, Compositing::WebGL::WebGLSharedCommandBuffer);
- [[nodiscard]] bool execute_webgl_commands_from_shared_buffer(Compositing::CanvasId, u64 offset, u64 size_in_bytes, u64 flush_sequence_number, Vector<Gfx::DecodedImageFrame> const&);
+ [[nodiscard]] bool execute_webgl_commands_from_shared_buffer(Compositing::CanvasId, u64 offset, u64 size_in_bytes, u64 flush_sequence_number, Vector<Compositing::WebGL::ImageSourceFrame> const&);
ErrorOr<ByteBuffer> execute_webgl_sync_call(Compositing::CanvasId, ByteBuffer request);
Compositing::WebGL::ReadPixelsResult webgl_read_pixels_robust_angle(Compositing::CanvasId, Compositing::WebGL::GLint x, Compositing::WebGL::GLint y, Compositing::WebGL::GLsizei width, Compositing::WebGL::GLsizei height, Compositing::WebGL::GLenum format, Compositing::WebGL::GLenum type, Compositing::WebGL::GLsizei buf_size, Core::AnonymousBuffer pixels);
bool webgl_read_buffer_sub_data(Compositing::CanvasId, Compositing::WebGL::GLenum target, Compositing::WebGL::GLintptr offset, Compositing::WebGL::GLintptr size, Core::AnonymousBuffer data);
@@ -69,6 +78,8 @@ public:
Gfx::ShareableBitmap read_back_pixels(Compositing::CanvasId, Gfx::IntRect, Gfx::AlphaType);
RefPtr<Gfx::PaintingSurface> presented_surface(Compositing::CanvasId);
+ void forget_video_sink(Media::VideoSinkHandle);
+
static Gfx::ShareableBitmap read_back_surface(Gfx::PaintingSurface&, Gfx::IntRect, Gfx::AlphaType = Gfx::AlphaType::Premultiplied);
private:
@@ -84,12 +95,19 @@ private:
OwnPtr<Gfx::CanvasCommandPlayer> create_2d_command_player(Gfx::IntSize, bool alpha);
static HostWebGLContext& as_webgl(Context&);
void present_canvas_2d_context(Compositing::CanvasId, Canvas2DContext&);
+ sk_sp<SkImage> held_video_frame_image(Media::VideoSinkHandle, u64 generation);
+ Vector<Gfx::DecodedImageFrame> resolve_webgl_image_source_frames(Vector<Compositing::WebGL::ImageSourceFrame> const&) const;
RefPtr<Gfx::SkiaBackendContext> m_skia_backend_context;
Compositing::CanvasSurfaceRegistry& m_canvas_surface_registry;
Compositing::CanvasSurfaceOwnerId m_canvas_surface_owner_id;
HashMap<Compositing::CanvasId, Context> m_contexts;
Compositing::DisplayListResourceStorage m_text_resources;
+
+ VideoFrameHolds const& m_video_frame_holds;
+ struct VideoFrameImage;
+ HashMap<Media::VideoSinkHandle, NonnullOwnPtr<VideoFrameImage>> m_video_frame_images;
+ bool m_drew_video_frame_in_segment { false };
};
}
diff --git a/Services/Compositor/CompositorState.cpp b/Services/Compositor/CompositorState.cpp
index 46db1358009..b1ce9a6d2be 100644
--- a/Services/Compositor/CompositorState.cpp
+++ b/Services/Compositor/CompositorState.cpp
@@ -312,6 +312,8 @@ void CompositorState::on_video_sink_ready(CompositorStateWebContentClient& clien
return;
sink_state->sink = sink;
sink->set_on_present_needed([this, &client, handle] {
+ if (auto* sink_state = video_sink_state(client, handle); sink_state && sink_state->sink)
+ client.video_sink_presented_frame(handle, sink_state->sink->current_frame());
present_contexts_drawing_video_sink(client, handle);
update_unpainted_video_update_scheduling();
});
diff --git a/Services/Compositor/CompositorState.h b/Services/Compositor/CompositorState.h
index 8e9b7597ef7..4186d0e44dd 100644
--- a/Services/Compositor/CompositorState.h
+++ b/Services/Compositor/CompositorState.h
@@ -64,6 +64,7 @@ public:
virtual void async_scroll_updates(Web::CompositorContextId, Compositing::PendingAsyncScrollUpdates const&) = 0;
virtual void create_video_edge(Media::VideoSinkHandle) = 0;
virtual void release_video_edge(Media::VideoSinkHandle) = 0;
+ virtual void video_sink_presented_frame(Media::VideoSinkHandle, RefPtr<Media::VideoFrame>) { }
virtual void placeholder_canvas_committed(Compositing::CanvasId, Gfx::IntSize, bool origin_clean) = 0;
// The owner of this client's canvases, which are the only ones its contexts may draw.
virtual Compositing::CanvasSurfaceOwnerId canvas_surface_owner_id() const = 0;
diff --git a/Services/Compositor/CompositorWebContentServer.ipc b/Services/Compositor/CompositorWebContentServer.ipc
index 396491631ed..2861ec51c4a 100644
--- a/Services/Compositor/CompositorWebContentServer.ipc
+++ b/Services/Compositor/CompositorWebContentServer.ipc
@@ -7,6 +7,8 @@
#include <LibCompositing/Forward.h>
#include <LibCompositing/Scrolling/ScrollState.h>
#include <LibCompositing/Types.h>
+#include <LibCompositing/Video/VideoFramePresentationPage.h>
+#include <LibCompositing/WebGL/ImageSourceFrame.h>
#include <LibCompositing/WebGL/Types.h>
#include <LibCore/AnonymousBuffer.h>
#include <LibGfx/CanvasCommandList.h>
@@ -22,8 +24,9 @@
endpoint CompositorWebContentServer
{
- add_video_sink(Media::VideoSinkHandle video_sink_handle) =|
+ add_video_sink(Media::VideoSinkHandle video_sink_handle, NonnullRefPtr<Compositing::VideoFramePresentationPage> presentation_page) =|
remove_video_sink(Media::VideoSinkHandle video_sink_handle) =|
+ release_video_frame_hold(Media::VideoSinkHandle video_sink_handle, u64 generation) =|
set_video_sink_ticking(Media::VideoSinkHandle video_sink_handle, bool should_tick) =|
set_parent_context(Web::CompositorContextId context_id, Optional<Web::CompositorContextId> parent_context_id) =|
@@ -53,9 +56,9 @@ endpoint CompositorWebContentServer
create_webgl_context(Compositing::WebGL::WebGLVersion webgl_version, Gfx::IntSize size, bool depth, bool stencil, bool antialias) => (bool success, Compositing::CanvasId canvas_id, Vector<String> supported_extensions)
webgl_set_command_buffer(Compositing::CanvasId canvas_id, Core::AnonymousBuffer command_buffer) =|
- webgl_commands_from_shared_buffer(Compositing::CanvasId canvas_id, u64 offset, u64 size_in_bytes, u64 flush_sequence_number, Vector<Gfx::DecodedImageFrame> bitmaps) =|
+ webgl_commands_from_shared_buffer(Compositing::CanvasId canvas_id, u64 offset, u64 size_in_bytes, u64 flush_sequence_number, Vector<Compositing::WebGL::ImageSourceFrame> frames) =|
webgl_drain_command_buffer(Compositing::CanvasId canvas_id) => ()
- webgl_commands(Compositing::CanvasId canvas_id, Core::AnonymousBuffer commands, Vector<Gfx::DecodedImageFrame> bitmaps) =|
+ webgl_commands(Compositing::CanvasId canvas_id, Core::AnonymousBuffer commands, Vector<Compositing::WebGL::ImageSourceFrame> frames) =|
webgl_present_canvas(Compositing::CanvasId canvas_id, bool preserve_drawing_buffer) =|
webgl_clear_drawing_buffer(Compositing::CanvasId canvas_id) =|
webgl_sync_call(Compositing::CanvasId canvas_id, ByteBuffer request) => (ByteBuffer reply)
diff --git a/Services/Compositor/ConnectionFromWebContent.cpp b/Services/Compositor/ConnectionFromWebContent.cpp
index c5b63a0dd74..5fcb4efcdc5 100644
--- a/Services/Compositor/ConnectionFromWebContent.cpp
+++ b/Services/Compositor/ConnectionFromWebContent.cpp
@@ -18,7 +18,7 @@ namespace Compositor {
ConnectionFromWebContent::ConnectionFromWebContent(NonnullOwnPtr<IPC::Transport> transport, NonnullRefPtr<CompositorState> compositor_state, int client_id)
: IPC::ConnectionFromClient<CompositorWebContentClientEndpoint, CompositorWebContentServerEndpoint>(*this, move(transport), client_id)
, m_compositor_state(move(compositor_state))
- , m_canvas_host(m_compositor_state->skia_backend_context(), m_compositor_state->canvas_surface_registry())
+ , m_canvas_host(m_compositor_state->skia_backend_context(), m_compositor_state->canvas_surface_registry(), m_video_frame_holds)
{
}
@@ -81,16 +81,30 @@ void ConnectionFromWebContent::pointer_left(Web::CompositorContextId context_id,
m_render_clock_connection->async_pointer_left(context_id, input_event_id);
}
-void ConnectionFromWebContent::add_video_sink(Media::VideoSinkHandle video_sink_handle)
+void ConnectionFromWebContent::add_video_sink(Media::VideoSinkHandle video_sink_handle, NonnullRefPtr<Compositing::VideoFramePresentationPage> presentation_page)
{
+ m_video_frame_holds.add_sink(video_sink_handle, move(presentation_page));
m_compositor_state->add_video_sink(*this, video_sink_handle);
}
void ConnectionFromWebContent::remove_video_sink(Media::VideoSinkHandle video_sink_handle)
{
+ m_video_frame_holds.remove_sink(video_sink_handle);
+ m_canvas_host.forget_video_sink(video_sink_handle);
m_compositor_state->remove_video_sink(*this, video_sink_handle);
}
+void ConnectionFromWebContent::release_video_frame_hold(Media::VideoSinkHandle video_sink_handle, u64 generation)
+{
+ if (m_video_frame_holds.release_hold(video_sink_handle, generation).is_error())
+ did_misbehave("WebContent released a video frame hold that it did not take");
+}
+
+void ConnectionFromWebContent::video_sink_presented_frame(Media::VideoSinkHandle video_sink_handle, RefPtr<Media::VideoFrame> frame)
+{
+ m_video_frame_holds.present_frame(video_sink_handle, move(frame));
+}
+
void ConnectionFromWebContent::set_video_sink_ticking(Media::VideoSinkHandle video_sink_handle, bool should_tick)
{
m_compositor_state->set_video_sink_ticking(*this, video_sink_handle, should_tick);
@@ -352,9 +366,9 @@ void ConnectionFromWebContent::webgl_set_command_buffer(Compositing::CanvasId ca
m_canvas_host.set_webgl_shared_command_buffer(canvas_id, shared_command_buffer.release_value());
}
-void ConnectionFromWebContent::webgl_commands_from_shared_buffer(Compositing::CanvasId canvas_id, u64 offset, u64 size_in_bytes, u64 flush_sequence_number, Vector<Gfx::DecodedImageFrame> bitmaps)
+void ConnectionFromWebContent::webgl_commands_from_shared_buffer(Compositing::CanvasId canvas_id, u64 offset, u64 size_in_bytes, u64 flush_sequence_number, Vector<Compositing::WebGL::ImageSourceFrame> frames)
{
- if (!m_canvas_host.execute_webgl_commands_from_shared_buffer(canvas_id, offset, size_in_bytes, flush_sequence_number, bitmaps))
+ if (!m_canvas_host.execute_webgl_commands_from_shared_buffer(canvas_id, offset, size_in_bytes, flush_sequence_number, frames))
did_misbehave("WebContent published an invalid WebGL shared command buffer range");
}
@@ -364,14 +378,14 @@ void ConnectionFromWebContent::webgl_drain_command_buffer(Compositing::CanvasId)
// including all published command ranges, has already been processed.
}
-void ConnectionFromWebContent::webgl_commands(Compositing::CanvasId canvas_id, Core::AnonymousBuffer commands, Vector<Gfx::DecodedImageFrame> bitmaps)
+void ConnectionFromWebContent::webgl_commands(Compositing::CanvasId canvas_id, Core::AnonymousBuffer commands, Vector<Compositing::WebGL::ImageSourceFrame> frames)
{
if (!commands.is_valid()) {
did_misbehave("WebContent sent an invalid WebGL command buffer");
return;
}
- m_canvas_host.execute_webgl_commands(canvas_id, commands.bytes(), bitmaps);
+ m_canvas_host.execute_webgl_commands(canvas_id, commands.bytes(), frames);
}
void ConnectionFromWebContent::webgl_present_canvas(Compositing::CanvasId canvas_id, bool preserve_drawing_buffer)
diff --git a/Services/Compositor/ConnectionFromWebContent.h b/Services/Compositor/ConnectionFromWebContent.h
index b850cf217f8..b855c4dc34e 100644
--- a/Services/Compositor/ConnectionFromWebContent.h
+++ b/Services/Compositor/ConnectionFromWebContent.h
@@ -13,6 +13,7 @@
#include <Compositor/CompositorWebContentClientEndpoint.h>
#include <Compositor/CompositorWebContentServerEndpoint.h>
#include <Compositor/RenderClockConnection.h>
+#include <Compositor/VideoFrameHolds.h>
#include <LibCompositing/DisplayList/DisplayList.h>
#include <LibCompositing/DisplayList/DisplayListResourceStorage.h>
#include <LibCompositing/WebGL/Types.h>
@@ -42,8 +43,9 @@ private:
virtual void die() override;
- virtual void add_video_sink(Media::VideoSinkHandle) override;
+ virtual void add_video_sink(Media::VideoSinkHandle, NonnullRefPtr<Compositing::VideoFramePresentationPage>) override;
virtual void remove_video_sink(Media::VideoSinkHandle) override;
+ virtual void release_video_frame_hold(Media::VideoSinkHandle, u64 generation) override;
virtual void set_video_sink_ticking(Media::VideoSinkHandle, bool should_tick) override;
virtual void set_parent_context(Web::CompositorContextId, Optional<Web::CompositorContextId>) override;
virtual void stop_presenting_to_client(Web::CompositorContextId) override;
@@ -65,9 +67,9 @@ private:
virtual Messages::CompositorWebContentServer::CreateWebglContextResponse create_webgl_context(Compositing::WebGL::WebGLVersion webgl_version, Gfx::IntSize size, bool depth, bool stencil, bool antialias) override;
virtual void webgl_set_command_buffer(Compositing::CanvasId canvas_id, Core::AnonymousBuffer command_buffer) override;
- virtual void webgl_commands_from_shared_buffer(Compositing::CanvasId canvas_id, u64 offset, u64 size_in_bytes, u64 flush_sequence_number, Vector<Gfx::DecodedImageFrame> bitmaps) override;
+ virtual void webgl_commands_from_shared_buffer(Compositing::CanvasId canvas_id, u64 offset, u64 size_in_bytes, u64 flush_sequence_number, Vector<Compositing::WebGL::ImageSourceFrame> frames) override;
virtual void webgl_drain_command_buffer(Compositing::CanvasId canvas_id) override;
- virtual void webgl_commands(Compositing::CanvasId canvas_id, Core::AnonymousBuffer commands, Vector<Gfx::DecodedImageFrame> bitmaps) override;
+ virtual void webgl_commands(Compositing::CanvasId canvas_id, Core::AnonymousBuffer commands, Vector<Compositing::WebGL::ImageSourceFrame> frames) override;
virtual void webgl_present_canvas(Compositing::CanvasId canvas_id, bool preserve_drawing_buffer) override;
virtual void webgl_clear_drawing_buffer(Compositing::CanvasId canvas_id) override;
virtual Messages::CompositorWebContentServer::WebglSyncCallResponse webgl_sync_call(Compositing::CanvasId canvas_id, ByteBuffer request) override;
@@ -100,11 +102,13 @@ private:
virtual void async_scroll_updates(Web::CompositorContextId, Compositing::PendingAsyncScrollUpdates const&) override;
virtual void create_video_edge(Media::VideoSinkHandle) override;
virtual void release_video_edge(Media::VideoSinkHandle) override;
+ virtual void video_sink_presented_frame(Media::VideoSinkHandle, RefPtr<Media::VideoFrame>) override;
virtual void placeholder_canvas_committed(Compositing::CanvasId, Gfx::IntSize, bool origin_clean) override;
virtual Compositing::CanvasSurfaceOwnerId canvas_surface_owner_id() const override { return m_canvas_host.canvas_surface_owner_id(); }
bool context_is_owned_by_this_connection(Web::CompositorContextId);
NonnullRefPtr<CompositorState> m_compositor_state;
+ VideoFrameHolds m_video_frame_holds;
CanvasHost m_canvas_host;
// The canvas IDs this WebContent has reserved and not yet named a 2D context with.
diff --git a/Services/Compositor/VideoFrameHolds.cpp b/Services/Compositor/VideoFrameHolds.cpp
new file mode 100644
index 00000000000..83ddc860655
--- /dev/null
+++ b/Services/Compositor/VideoFrameHolds.cpp
@@ -0,0 +1,90 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <Compositor/VideoFrameHolds.h>
+#include <LibMediaCodecs/VideoFrame.h>
+
+namespace Compositor {
+
+using Compositing::VideoFramePresentationPage;
+
+void VideoFrameHolds::add_sink(Media::VideoSinkHandle handle, NonnullRefPtr<VideoFramePresentationPage> page)
+{
+ // WebContent may already hold generation 0.
+ if (auto sink = m_sinks.get(handle); sink.has_value())
+ retire_current_generation(handle, *sink, VideoFramePresentationPage::retired_generation);
+ m_sinks.set(handle, Sink { .page = move(page), .generation = 0, .frame = nullptr });
+}
+
+void VideoFrameHolds::remove_sink(Media::VideoSinkHandle handle)
+{
+ auto sink = m_sinks.get(handle);
+ if (!sink.has_value())
+ return;
+ retire_current_generation(handle, *sink, VideoFramePresentationPage::retired_generation);
+ m_sinks.remove(handle);
+}
+
+void VideoFrameHolds::present_frame(Media::VideoSinkHandle handle, RefPtr<Media::VideoFrame> frame)
+{
+ auto sink = m_sinks.get(handle);
+ if (!sink.has_value() || sink->frame == frame)
+ return;
+ auto next_generation = sink->generation + 1;
+ retire_current_generation(handle, *sink, next_generation);
+ sink->generation = next_generation;
+ sink->frame = move(frame);
+}
+
+void VideoFrameHolds::retire_current_generation(Media::VideoSinkHandle handle, Sink& sink, u64 next_generation)
+{
+ auto replaced = sink.page->replace_generation(next_generation);
+ if (replaced.generation != sink.generation) {
+ dbgln("Compositor: WebContent overwrote the generation of video sink {}", handle.value());
+ return;
+ }
+ if (replaced.hold_count == 0)
+ return;
+ auto& retained_frames = m_retained_frames.ensure(handle);
+ retained_frames.set(sink.generation, RetainedFrame { .frame = sink.frame, .hold_count = replaced.hold_count });
+}
+
+ErrorOr<void> VideoFrameHolds::release_hold(Media::VideoSinkHandle handle, u64 generation)
+{
+ if (auto sink = m_sinks.get(handle); sink.has_value() && sink->generation == generation) {
+ if (sink->page->release_hold_if_current(generation) != VideoFramePresentationPage::ReleaseResult::Released)
+ return Error::from_string_literal("The current video frame was not held");
+ return {};
+ }
+
+ auto retained_frames = m_retained_frames.get(handle);
+ if (!retained_frames.has_value())
+ return Error::from_string_literal("The video frame was not retained");
+ auto retained_frame = retained_frames->get(generation);
+ if (!retained_frame.has_value())
+ return Error::from_string_literal("The video frame was not retained");
+ if (--retained_frame->hold_count > 0)
+ return {};
+ retained_frames->remove(generation);
+ if (retained_frames->is_empty())
+ m_retained_frames.remove(handle);
+ return {};
+}
+
+RefPtr<Media::VideoFrame> VideoFrameHolds::held_frame(Media::VideoSinkHandle handle, u64 generation) const
+{
+ if (auto sink = m_sinks.get(handle); sink.has_value() && sink->generation == generation)
+ return sink->frame;
+ auto retained_frames = m_retained_frames.get(handle);
+ if (!retained_frames.has_value())
+ return nullptr;
+ auto retained_frame = retained_frames->get(generation);
+ if (!retained_frame.has_value())
+ return nullptr;
+ return retained_frame->frame;
+}
+
+}
diff --git a/Services/Compositor/VideoFrameHolds.h b/Services/Compositor/VideoFrameHolds.h
new file mode 100644
index 00000000000..5b1de44ee9b
--- /dev/null
+++ b/Services/Compositor/VideoFrameHolds.h
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Error.h>
+#include <AK/HashMap.h>
+#include <AK/NonnullRefPtr.h>
+#include <AK/RefPtr.h>
+#include <LibCompositing/Video/VideoFramePresentationPage.h>
+#include <LibMedia/VideoSinkHandle.h>
+#include <LibMediaCodecs/Forward.h>
+
+namespace Compositor {
+
+class VideoFrameHolds {
+public:
+ void add_sink(Media::VideoSinkHandle, NonnullRefPtr<Compositing::VideoFramePresentationPage>);
+ void remove_sink(Media::VideoSinkHandle);
+
+ void present_frame(Media::VideoSinkHandle, RefPtr<Media::VideoFrame>);
+
+ ErrorOr<void> release_hold(Media::VideoSinkHandle, u64 generation);
+ RefPtr<Media::VideoFrame> held_frame(Media::VideoSinkHandle, u64 generation) const;
+
+private:
+ struct Sink {
+ NonnullRefPtr<Compositing::VideoFramePresentationPage> page;
+ u64 generation { 0 };
+ RefPtr<Media::VideoFrame> frame;
+ };
+ struct RetainedFrame {
+ RefPtr<Media::VideoFrame> frame;
+ u64 hold_count { 0 };
+ };
+
+ void retire_current_generation(Media::VideoSinkHandle, Sink&, u64 next_generation);
+
+ HashMap<Media::VideoSinkHandle, Sink> m_sinks;
+ HashMap<Media::VideoSinkHandle, HashMap<u64, RetainedFrame>> m_retained_frames;
+};
+
+}
diff --git a/Tests/LibCompositing/CMakeLists.txt b/Tests/LibCompositing/CMakeLists.txt
index e8ec2e18f80..dd720c9b0f6 100644
--- a/Tests/LibCompositing/CMakeLists.txt
+++ b/Tests/LibCompositing/CMakeLists.txt
@@ -8,6 +8,7 @@ set(TEST_SOURCES
TestSmoothScrollAnimation.cpp
TestTextureUpload.cpp
TestUIOverlays.cpp
+ TestVideoFrameHold.cpp
)
foreach(source IN LISTS TEST_SOURCES)
diff --git a/Tests/LibCompositing/TestVideoFrameHold.cpp b/Tests/LibCompositing/TestVideoFrameHold.cpp
new file mode 100644
index 00000000000..9a1d67b1357
--- /dev/null
+++ b/Tests/LibCompositing/TestVideoFrameHold.cpp
@@ -0,0 +1,105 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/Vector.h>
+#include <LibCompositing/Video/VideoFrameHold.h>
+#include <LibCompositing/Video/VideoFramePresentationPage.h>
+#include <LibTest/TestCase.h>
+
+using Compositing::VideoFrameHold;
+using Compositing::VideoFramePresentationPage;
+
+struct PagePair {
+ NonnullRefPtr<VideoFramePresentationPage> web_content;
+ NonnullRefPtr<VideoFramePresentationPage> compositor;
+};
+
+// Both processes map the same buffer, which two pages over one buffer stand in for.
+static PagePair create_page_pair()
+{
+ auto web_content = MUST(VideoFramePresentationPage::create());
+ auto compositor = MUST(VideoFramePresentationPage::create(web_content->buffer()));
+ return { move(web_content), move(compositor) };
+}
+
+TEST_CASE(holds_are_counted_on_the_generation_they_were_taken_on)
+{
+ auto pages = create_page_pair();
+ EXPECT_EQ(pages.compositor->replace_generation(1).generation, 0u);
+
+ EXPECT_EQ(pages.web_content->hold_current_generation(), 1u);
+ EXPECT_EQ(pages.web_content->hold_current_generation(), 1u);
+
+ auto replaced = pages.compositor->replace_generation(2);
+ EXPECT_EQ(replaced.generation, 1u);
+ EXPECT_EQ(replaced.hold_count, 2u);
+ EXPECT_EQ(pages.web_content->current_generation(), 2u);
+}
+
+TEST_CASE(holds_are_released_in_place_only_while_their_generation_is_current)
+{
+ auto pages = create_page_pair();
+ pages.compositor->replace_generation(1);
+ EXPECT_EQ(pages.web_content->hold_current_generation(), 1u);
+ EXPECT_EQ(pages.web_content->release_hold_if_current(1), VideoFramePresentationPage::ReleaseResult::Released);
+ EXPECT_EQ(pages.web_content->release_hold_if_current(1), VideoFramePresentationPage::ReleaseResult::NotHeld);
+
+ EXPECT_EQ(pages.web_content->hold_current_generation(), 1u);
+ EXPECT_EQ(pages.compositor->replace_generation(2).hold_count, 1u);
+ EXPECT_EQ(pages.web_content->release_hold_if_current(1), VideoFramePresentationPage::ReleaseResult::NotCurrent);
+}
+
+TEST_CASE(a_retired_sink_cannot_be_held)
+{
+ auto pages = create_page_pair();
+ pages.compositor->replace_generation(VideoFramePresentationPage::retired_generation);
+ EXPECT(!pages.web_content->hold_current_generation().has_value());
+}
+
+TEST_CASE(an_unsent_hold_is_released_in_place)
+{
+ auto pages = create_page_pair();
+ pages.compositor->replace_generation(1);
+ Vector<u64> released_through_compositor;
+ {
+ auto hold = VideoFrameHold::hold_current_frame(pages.web_content, Media::VideoSinkHandle { 1 }, [&](auto, u64 generation) {
+ released_through_compositor.append(generation);
+ });
+ EXPECT(hold);
+ EXPECT_EQ(hold->generation(), 1u);
+ }
+ EXPECT(released_through_compositor.is_empty());
+ EXPECT_EQ(pages.compositor->replace_generation(2).hold_count, 0u);
+}
+
+TEST_CASE(a_sent_hold_is_released_through_the_compositor)
+{
+ auto pages = create_page_pair();
+ pages.compositor->replace_generation(1);
+ Vector<u64> released_through_compositor;
+ {
+ auto hold = VideoFrameHold::hold_current_frame(pages.web_content, Media::VideoSinkHandle { 1 }, [&](auto, u64 generation) {
+ released_through_compositor.append(generation);
+ });
+ hold->note_sent_to_compositor();
+ }
+ EXPECT_EQ(released_through_compositor, (Vector<u64> { 1 }));
+ EXPECT_EQ(pages.compositor->replace_generation(2).hold_count, 1u);
+}
+
+TEST_CASE(an_unsent_hold_on_a_replaced_generation_is_released_through_the_compositor)
+{
+ auto pages = create_page_pair();
+ pages.compositor->replace_generation(1);
+ Vector<u64> released_through_compositor;
+ {
+ auto hold = VideoFrameHold::hold_current_frame(pages.web_content, Media::VideoSinkHandle { 1 }, [&](auto, u64 generation) {
+ released_through_compositor.append(generation);
+ });
+ EXPECT_EQ(pages.compositor->replace_generation(2).hold_count, 1u);
+ }
+ EXPECT_EQ(released_through_compositor, (Vector<u64> { 1 }));
+}
diff --git a/Tests/LibWeb/Text/expected/HTML/HTMLVideoElement-capture-before-seek-keeps-frame.txt b/Tests/LibWeb/Text/expected/HTML/HTMLVideoElement-capture-before-seek-keeps-frame.txt
new file mode 100644
index 00000000000..0349cfec723
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/HTML/HTMLVideoElement-capture-before-seek-keeps-frame.txt
@@ -0,0 +1,4 @@
+drawImage before the seek: 1
+createPattern before the seek: 1
+texImage2D before the seek: 1
+drawImage after the seek: 3
diff --git a/Tests/LibWeb/Text/input/HTML/HTMLVideoElement-capture-before-seek-keeps-frame.html b/Tests/LibWeb/Text/input/HTML/HTMLVideoElement-capture-before-seek-keeps-frame.html
new file mode 100644
index 00000000000..2e2d56b77a8
--- /dev/null
+++ b/Tests/LibWeb/Text/input/HTML/HTMLVideoElement-capture-before-seek-keeps-frame.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 grayIn(pixels) {
+ const [red, , blue] = pixels.slice(0, 4);
+ if (red < 150 || blue > 100)
+ return "not red";
+ return `${Math.round(pixels[4 * 48 + 1] / 60)}`;
+ }
+
+ function readRow(context) {
+ return context.getImageData(0, 18, 64, 1).data;
+ }
+
+ function create2DContext() {
+ const canvas = document.createElement("canvas");
+ canvas.width = 64;
+ canvas.height = 36;
+ return canvas.getContext("2d", { willReadFrequently: true });
+ }
+
+ function createWebGLTexture(gl) {
+ const texture = gl.createTexture();
+ gl.bindTexture(gl.TEXTURE_2D, texture);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
+ return texture;
+ }
+
+ function readWebGLTextureRow(gl, texture) {
+ const framebuffer = gl.createFramebuffer();
+ gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
+ const pixels = new Uint8Array(64 * 4);
+ gl.readPixels(0, 18, 64, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
+ return pixels;
+ }
+
+ async function seekAndWait(video, time) {
+ const seeked = new Promise(resolve => video.addEventListener("seeked", resolve, { once: true }));
+ video.currentTime = time;
+ await seeked;
+ }
+
+ promiseTest(async () => {
+ const video = document.createElement("video");
+ video.src = "../../../Assets/red-with-second-in-gray-64x36.webm";
+ document.body.append(video);
+ if (video.readyState < HTMLMediaElement.HAVE_CURRENT_DATA)
+ await new Promise(resolve => video.addEventListener("loadeddata", resolve, { once: true }));
+ await seekAndWait(video, 1.5);
+
+ const drawnContext = create2DContext();
+ drawnContext.drawImage(video, 0, 0);
+
+ const patternContext = create2DContext();
+ const pattern = patternContext.createPattern(video, "no-repeat");
+
+ const gl = document.createElement("canvas").getContext("webgl");
+ const texture = createWebGLTexture(gl);
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, video);
+
+ await seekAndWait(video, 3.5);
+
+ println(`drawImage before the seek: ${grayIn(readRow(drawnContext))}`);
+ patternContext.fillStyle = pattern;
+ patternContext.fillRect(0, 0, 64, 36);
+ println(`createPattern before the seek: ${grayIn(readRow(patternContext))}`);
+ println(`texImage2D before the seek: ${grayIn(readWebGLTextureRow(gl, texture))}`);
+
+ const laterContext = create2DContext();
+ laterContext.drawImage(video, 0, 0);
+ println(`drawImage after the seek: ${grayIn(readRow(laterContext))}`);
+ });
+</script>