Skip to content

Truly independent web browser

LibMediaCodecs+Compositor: Decode VP9 and AV1 with Vulkan Video

Zaggy102436bd728c3c3e
diff --git a/Libraries/LibMediaCodecs/CMakeLists.txt b/Libraries/LibMediaCodecs/CMakeLists.txt
index a1736a76d8c..075363edc2d 100644
--- a/Libraries/LibMediaCodecs/CMakeLists.txt
+++ b/Libraries/LibMediaCodecs/CMakeLists.txt
@@ -32,7 +32,7 @@ if (APPLE)
endif()
if (USE_VULKAN_DMABUF_IMAGES)
- list(APPEND SOURCES Vulkan/VulkanVideoDevice.cpp)
+ list(APPEND SOURCES FFmpeg/FFmpegVulkanVideoDecoder.cpp Vulkan/VulkanVideoDevice.cpp)
endif()
set(GENERATED_SOURCES
diff --git a/Libraries/LibMediaCodecs/FFmpeg/FFmpegFunctions.h b/Libraries/LibMediaCodecs/FFmpeg/FFmpegFunctions.h
index 5825e9b3aa2..10004e1b77e 100644
--- a/Libraries/LibMediaCodecs/FFmpeg/FFmpegFunctions.h
+++ b/Libraries/LibMediaCodecs/FFmpeg/FFmpegFunctions.h
@@ -15,6 +15,7 @@
extern "C" {
#include <libavcodec/avcodec.h>
+#include <libavutil/hwcontext.h>
#include <libavutil/opt.h>
}
@@ -36,6 +37,7 @@ static_assert(sizeof(void*) != 8 || (sizeof(AVChannelLayout) == 24 && offsetof(A
#define FFMPEG_ENUMERATE_FUNCTIONS(F) \
F(avcodec_version) \
F(avcodec_find_decoder) \
+ F(avcodec_find_decoder_by_name) \
F(avcodec_descriptor_get_by_name) \
F(avcodec_alloc_context3) \
F(avcodec_free_context) \
@@ -43,6 +45,9 @@ static_assert(sizeof(void*) != 8 || (sizeof(AVChannelLayout) == 24 && offsetof(A
F(avcodec_send_packet) \
F(avcodec_receive_frame) \
F(avcodec_flush_buffers) \
+ F(avcodec_get_hw_config) \
+ F(avcodec_get_hw_frames_parameters) \
+ F(avcodec_default_get_buffer2) \
F(avcodec_parameters_alloc) \
F(avcodec_parameters_free) \
F(avcodec_parameters_to_context) \
@@ -54,6 +59,14 @@ static_assert(sizeof(void*) != 8 || (sizeof(AVChannelLayout) == 24 && offsetof(A
F(av_frame_alloc) \
F(av_frame_free) \
F(av_frame_unref) \
+ F(av_frame_ref) \
+ F(av_frame_move_ref) \
+ F(av_buffer_ref) \
+ F(av_buffer_unref) \
+ F(av_hwdevice_ctx_alloc) \
+ F(av_hwdevice_ctx_init) \
+ F(av_hwframe_ctx_init) \
+ F(av_hwframe_map) \
F(av_malloc) \
F(av_opt_set_int) \
F(av_opt_set_chlayout) \
diff --git a/Libraries/LibMediaCodecs/FFmpeg/FFmpegHelpers.cpp b/Libraries/LibMediaCodecs/FFmpeg/FFmpegHelpers.cpp
index d6e99517a28..efb60575310 100644
--- a/Libraries/LibMediaCodecs/FFmpeg/FFmpegHelpers.cpp
+++ b/Libraries/LibMediaCodecs/FFmpeg/FFmpegHelpers.cpp
@@ -5,6 +5,7 @@
*/
#include <AK/ScopeGuard.h>
+#include <LibMediaCodecs/CodedFrame.h>
#include "FFmpegHelpers.h"
@@ -45,4 +46,84 @@ DecoderErrorOr<void> add_new_extradata_to_packet(FFmpegFunctions const& function
return {};
}
+// Frames that FFmpeg never output, such as ones it drops for corruption, stop being kept once this many later ones
+// have gone in.
+static constexpr u64 MAXIMUM_FRAMES_AWAITING_OUTPUT = 256;
+
+DecoderErrorOr<u64> VideoFramesAwaitingOutput::add(CodedFrame const& coded_frame, DecodeIntent intent)
+{
+ auto key = m_next_key++;
+ if (m_frames.size() >= MAXIMUM_FRAMES_AWAITING_OUTPUT) {
+ auto stale_frame_count = m_frames.size();
+ m_frames.remove_all_matching([&](u64 frame_key, auto const&) { return frame_key + MAXIMUM_FRAMES_AWAITING_OUTPUT <= key; });
+ stale_frame_count -= m_frames.size();
+ if (stale_frame_count > 0)
+ dbgln("FFmpeg: {} frames were never output", stale_frame_count);
+ }
+ DECODER_TRY_ALLOC(m_frames.try_set(key, { coded_frame.presentation_timestamp(), coded_frame.duration(), intent }));
+ return key;
+}
+
+Optional<VideoFramesAwaitingOutput::Frame> VideoFramesAwaitingOutput::take(i64 key)
+{
+ return m_frames.take(static_cast<u64>(key));
+}
+
+DecoderErrorOr<void> send_coded_frame(FFmpegFunctions const& functions, AVCodecContext& codec_context, AVPacket& packet, CodedFrame const& coded_frame, u64 key)
+{
+ auto coded_data = coded_frame.data();
+ VERIFY(coded_data.size() < NumericLimits<int>::max());
+
+ packet.data = const_cast<u8*>(coded_data.data());
+ packet.size = static_cast<int>(coded_data.size());
+ packet.pts = static_cast<i64>(key);
+ packet.dts = AV_NOPTS_VALUE;
+
+ ScopeGuard clear_packet_side_data { [&] { functions.av_packet_free_side_data(&packet); } };
+ auto new_codec_configuration = coded_frame.new_codec_configuration();
+ if (new_codec_configuration.has_value() && !new_codec_configuration->is_empty())
+ TRY(add_new_extradata_to_packet(functions, packet, *new_codec_configuration));
+
+ auto result = functions.avcodec_send_packet(&codec_context, &packet);
+ switch (result) {
+ case 0:
+ return {};
+ case AVERROR(EAGAIN):
+ return DecoderError::with_description(DecoderErrorCategory::TryAgain, "FFmpeg decoder cannot decode any more data until frames have been retrieved"sv);
+ case AVERROR_EOF:
+ return DecoderError::with_description(DecoderErrorCategory::EndOfStream, "FFmpeg decoder has been flushed"sv);
+ case AVERROR(EINVAL):
+ return DecoderError::with_description(DecoderErrorCategory::Invalid, "FFmpeg codec has not been opened"sv);
+ case AVERROR(ENOMEM):
+ return DecoderError::with_description(DecoderErrorCategory::Memory, "FFmpeg codec ran out of internal memory"sv);
+ default:
+ return DecoderError::with_description(DecoderErrorCategory::Corrupted, "FFmpeg codec reports that the data is corrupted"sv);
+ }
+}
+
+CodingIndependentCodePoints coding_independent_code_points_of(FFmpegFunctions const& functions, AVCodecContext& codec_context, CodingIndependentCodePoints const& container_cicp)
+{
+ auto option = [&](char const* name) {
+ i64 value = 0;
+ VERIFY(functions.av_opt_get_int(&codec_context, name, 0, &value) == 0);
+ return value;
+ };
+ auto color_primaries = static_cast<ColorPrimaries>(option("color_primaries"));
+ auto transfer_characteristics = static_cast<TransferCharacteristics>(option("color_trc"));
+ auto matrix_coefficients = static_cast<MatrixCoefficients>(option("colorspace"));
+ auto color_range = [&] {
+ switch (option("color_range")) {
+ case AVColorRange::AVCOL_RANGE_MPEG:
+ return VideoFullRangeFlag::Studio;
+ case AVColorRange::AVCOL_RANGE_JPEG:
+ return VideoFullRangeFlag::Full;
+ default:
+ return VideoFullRangeFlag::Unspecified;
+ }
+ }();
+ auto cicp = container_cicp;
+ cicp.adopt_specified_values({ color_primaries, transfer_characteristics, matrix_coefficients, color_range });
+ return cicp;
+}
+
}
diff --git a/Libraries/LibMediaCodecs/FFmpeg/FFmpegHelpers.h b/Libraries/LibMediaCodecs/FFmpeg/FFmpegHelpers.h
index 165d3d97d9e..e3b936ccbaa 100644
--- a/Libraries/LibMediaCodecs/FFmpeg/FFmpegHelpers.h
+++ b/Libraries/LibMediaCodecs/FFmpeg/FFmpegHelpers.h
@@ -8,9 +8,12 @@
#include <AK/Span.h>
#include <LibMediaCodecs/CodecID.h>
+#include <LibMediaCodecs/Color/CodingIndependentCodePoints.h>
#include <LibMediaCodecs/DecoderError.h>
#include <LibMediaCodecs/Export.h>
#include <LibMediaCodecs/FFmpeg/FFmpegFunctions.h>
+#include <LibMediaCodecs/FFmpeg/VideoFramesAwaitingOutput.h>
+#include <LibMediaCodecs/Forward.h>
#include <LibMediaCodecs/TrackType.h>
extern "C" {
@@ -145,6 +148,8 @@ static inline TrackType track_type_from_ffmpeg_media_type(AVMediaType media_type
MEDIACODECS_API DecoderErrorOr<void> set_codec_initialization_data(FFmpegFunctions const&, AVCodecContext&, CodecID, ReadonlyBytes);
MEDIACODECS_API DecoderErrorOr<void> add_new_extradata_to_packet(FFmpegFunctions const&, AVPacket&, ReadonlyBytes);
+MEDIACODECS_API DecoderErrorOr<void> send_coded_frame(FFmpegFunctions const&, AVCodecContext&, AVPacket&, CodedFrame const&, u64 key);
+MEDIACODECS_API CodingIndependentCodePoints coding_independent_code_points_of(FFmpegFunctions const&, AVCodecContext&, CodingIndependentCodePoints const& container_cicp);
constexpr StringView av_error_code_to_string(int error)
{
diff --git a/Libraries/LibMediaCodecs/FFmpeg/FFmpegVideoDecoder.cpp b/Libraries/LibMediaCodecs/FFmpeg/FFmpegVideoDecoder.cpp
index 03baece8677..3008bb11ae3 100644
--- a/Libraries/LibMediaCodecs/FFmpeg/FFmpegVideoDecoder.cpp
+++ b/Libraries/LibMediaCodecs/FFmpeg/FFmpegVideoDecoder.cpp
@@ -15,8 +15,6 @@
namespace Media::FFmpeg {
-static constexpr size_t MAXIMUM_FRAMES_IN_FLIGHT = 256;
-
Optional<DecoderCapabilities> FFmpegVideoDecoder::capabilities(FFmpegFunctions const& functions, ParsedCodec const& codec)
{
if (track_type_from_codec_id(codec.codec_id()) != TrackType::Video)
@@ -98,44 +96,8 @@ FFmpegVideoDecoder::~FFmpegVideoDecoder()
DecoderErrorOr<void> FFmpegVideoDecoder::receive_coded_data(CodedFrame const& coded_frame, DecodeIntent intent)
{
- auto coded_data = coded_frame.data();
- VERIFY(coded_data.size() < NumericLimits<int>::max());
-
- auto key = m_next_frame_key++;
- m_packet->data = const_cast<u8*>(coded_data.data());
- m_packet->size = static_cast<int>(coded_data.size());
- m_packet->pts = static_cast<i64>(key);
- m_packet->dts = AV_NOPTS_VALUE;
-
- if (m_frames_in_flight.size() >= MAXIMUM_FRAMES_IN_FLIGHT) {
- auto stale_frame_count = m_frames_in_flight.size();
- m_frames_in_flight.remove_all_matching([&](u64 in_flight_key, auto const&) { return in_flight_key + MAXIMUM_FRAMES_IN_FLIGHT <= key; });
- stale_frame_count -= m_frames_in_flight.size();
- if (stale_frame_count > 0)
- dbgln("FFmpegVideoDecoder: {} frames were never output", stale_frame_count);
- }
- DECODER_TRY_ALLOC(m_frames_in_flight.try_set(key, { coded_frame.presentation_timestamp(), coded_frame.duration(), intent }));
-
- ScopeGuard clear_packet_side_data { [&] { m_functions.av_packet_free_side_data(m_packet); } };
- auto new_codec_configuration = coded_frame.new_codec_configuration();
- if (new_codec_configuration.has_value() && !new_codec_configuration->is_empty())
- TRY(add_new_extradata_to_packet(m_functions, *m_packet, *new_codec_configuration));
-
- auto result = m_functions.avcodec_send_packet(m_codec_context, m_packet);
- switch (result) {
- case 0:
- return {};
- case AVERROR(EAGAIN):
- return DecoderError::with_description(DecoderErrorCategory::TryAgain, "FFmpeg decoder cannot decode any more data until frames have been retrieved"sv);
- case AVERROR_EOF:
- return DecoderError::with_description(DecoderErrorCategory::EndOfStream, "FFmpeg decoder has been flushed"sv);
- case AVERROR(EINVAL):
- return DecoderError::with_description(DecoderErrorCategory::Invalid, "FFmpeg codec has not been opened"sv);
- case AVERROR(ENOMEM):
- return DecoderError::with_description(DecoderErrorCategory::Memory, "FFmpeg codec ran out of internal memory"sv);
- default:
- return DecoderError::with_description(DecoderErrorCategory::Corrupted, "FFmpeg codec reports that the data is corrupted"sv);
- }
+ auto key = TRY(m_frames_awaiting_output.add(coded_frame, intent));
+ return send_coded_frame(m_functions, *m_codec_context, *m_packet, coded_frame, key);
}
void FFmpegVideoDecoder::signal_end_of_stream()
@@ -156,14 +118,14 @@ DecoderErrorOr<NonnullRefPtr<VideoFrame>> FFmpegVideoDecoder::take_next_output(C
switch (result) {
case 0: {
- auto in_flight_frame = m_frames_in_flight.take(static_cast<u64>(m_frame->pts));
- if (!in_flight_frame.has_value()) {
+ auto frame = m_frames_awaiting_output.take(m_frame->pts);
+ if (!frame.has_value()) {
dbgln("FFmpegVideoDecoder: Dropping a frame whose timing was forgotten");
continue;
}
- if (in_flight_frame->intent == DecodeIntent::Reference)
+ if (frame->intent == DecodeIntent::Reference)
continue;
- m_pending_frame = in_flight_frame.release_value();
+ m_pending_frame = frame.release_value();
break;
}
case AVERROR(EAGAIN):
@@ -177,21 +139,7 @@ DecoderErrorOr<NonnullRefPtr<VideoFrame>> FFmpegVideoDecoder::take_next_output(C
}
}
- auto color_primaries = static_cast<ColorPrimaries>(codec_context_option("color_primaries"));
- auto transfer_characteristics = static_cast<TransferCharacteristics>(codec_context_option("color_trc"));
- auto matrix_coefficients = static_cast<MatrixCoefficients>(codec_context_option("colorspace"));
- auto color_range = [&] {
- switch (codec_context_option("color_range")) {
- case AVColorRange::AVCOL_RANGE_MPEG:
- return VideoFullRangeFlag::Studio;
- case AVColorRange::AVCOL_RANGE_JPEG:
- return VideoFullRangeFlag::Full;
- default:
- return VideoFullRangeFlag::Unspecified;
- }
- }();
- auto cicp = container_cicp;
- cicp.adopt_specified_values({ color_primaries, transfer_characteristics, matrix_coefficients, color_range });
+ auto cicp = coding_independent_code_points_of(m_functions, *m_codec_context, container_cicp);
auto pixel_format = static_cast<AVPixelFormat>(m_frame->format);
auto bit_depth = [&]() -> Optional<u8> {
@@ -297,18 +245,11 @@ DecoderErrorOr<void> FFmpegVideoDecoder::copy_pending_frame_into(Gfx::YUVData& y
return {};
}
-i64 FFmpegVideoDecoder::codec_context_option(char const* name) const
-{
- i64 value = 0;
- VERIFY(m_functions.av_opt_get_int(m_codec_context, name, 0, &value) == 0);
- return value;
-}
-
void FFmpegVideoDecoder::flush()
{
m_functions.avcodec_flush_buffers(m_codec_context);
m_pending_frame.clear();
- m_frames_in_flight.clear();
+ m_frames_awaiting_output.clear();
}
}
diff --git a/Libraries/LibMediaCodecs/FFmpeg/FFmpegVideoDecoder.h b/Libraries/LibMediaCodecs/FFmpeg/FFmpegVideoDecoder.h
index 7a1865a8d84..327a2aa1ddf 100644
--- a/Libraries/LibMediaCodecs/FFmpeg/FFmpegVideoDecoder.h
+++ b/Libraries/LibMediaCodecs/FFmpeg/FFmpegVideoDecoder.h
@@ -6,7 +6,6 @@
#pragma once
-#include <AK/HashMap.h>
#include <LibMediaCodecs/CodecID.h>
#include <LibMediaCodecs/CodecParameters.h>
#include <LibMediaCodecs/DecoderCapabilities.h>
@@ -15,6 +14,7 @@
#include <LibMediaCodecs/VideoFramePool.h>
#include <LibMediaCodecs/FFmpeg/FFmpegForward.h>
+#include <LibMediaCodecs/FFmpeg/VideoFramesAwaitingOutput.h>
namespace Media::FFmpeg {
@@ -39,25 +39,15 @@ public:
virtual void flush() override;
private:
- struct InFlightFrame {
- AK::Duration timestamp;
- AK::Duration duration;
- DecodeIntent intent;
- };
-
DecoderErrorOr<void> copy_pending_frame_into(Gfx::YUVData&);
- i64 codec_context_option(char const* name) const;
FFmpegFunctions const& m_functions;
AVCodecContext* m_codec_context;
AVPacket* m_packet;
AVFrame* m_frame;
NonnullRefPtr<VideoFramePool> m_frame_pool;
- Optional<InFlightFrame> m_pending_frame;
-
- // The decoder returns a packet's timestamp with the frame it produces, so a key stands in for it.
- u64 m_next_frame_key { 0 };
- HashMap<u64, InFlightFrame> m_frames_in_flight;
+ Optional<VideoFramesAwaitingOutput::Frame> m_pending_frame;
+ VideoFramesAwaitingOutput m_frames_awaiting_output;
};
}
diff --git a/Libraries/LibMediaCodecs/FFmpeg/FFmpegVulkanVideoDecoder.cpp b/Libraries/LibMediaCodecs/FFmpeg/FFmpegVulkanVideoDecoder.cpp
new file mode 100644
index 00000000000..c9ae9773159
--- /dev/null
+++ b/Libraries/LibMediaCodecs/FFmpeg/FFmpegVulkanVideoDecoder.cpp
@@ -0,0 +1,706 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/Atomic.h>
+#include <AK/NeverDestroyed.h>
+#include <AK/ScopeGuard.h>
+#include <LibIPC/File.h>
+#include <LibMediaCodecs/CodedFrame.h>
+#include <LibMediaCodecs/FFmpeg/FFmpegFunctions.h>
+#include <LibMediaCodecs/FFmpeg/FFmpegHelpers.h>
+#include <LibMediaCodecs/FFmpeg/FFmpegVulkanVideoDecoder.h>
+#include <LibMediaCodecs/VideoFrame.h>
+#include <LibThreading/Thread.h>
+#include <string.h>
+
+extern "C" {
+#include <libavutil/hwcontext_drm.h>
+#include <libavutil/hwcontext_vulkan.h>
+}
+
+namespace Media::FFmpeg {
+
+namespace {
+
+constexpr u32 drm_fourcc(char a, char b, char c, char d)
+{
+ return static_cast<u32>(a) | (static_cast<u32>(b) << 8) | (static_cast<u32>(c) << 16) | (static_cast<u32>(d) << 24);
+}
+
+constexpr u32 DRM_FORMAT_NV12 = drm_fourcc('N', 'V', '1', '2');
+constexpr u32 DRM_FORMAT_P010 = drm_fourcc('P', '0', '1', '0');
+
+constexpr AK::Duration DEVICE_WORK_STALL_UNTIL_TREATED_AS_FAILED = AK::Duration::from_seconds(5);
+
+// Surfaces are told apart by ID in every process that sees them, and each decoder's images are distinct.
+Atomic<u32> s_next_surface_id { 1 };
+
+char const* decoder_name_for(CodecID codec_id)
+{
+ switch (codec_id) {
+ case CodecID::VP9:
+ return "vp9";
+ case CodecID::AV1:
+ return "av1";
+ default:
+ return nullptr;
+ }
+}
+
+StringView decode_extension_for(CodecID codec_id)
+{
+ switch (codec_id) {
+ case CodecID::VP9:
+ return VK_KHR_VIDEO_DECODE_VP9_EXTENSION_NAME ""sv;
+ case CodecID::AV1:
+ return VK_KHR_VIDEO_DECODE_AV1_EXTENSION_NAME ""sv;
+ default:
+ VERIFY_NOT_REACHED();
+ }
+}
+
+FFmpegFunctions const* ffmpeg_for(CodecID codec_id)
+{
+ switch (codec_id) {
+ case CodecID::VP9:
+ case CodecID::AV1:
+ return &FFmpegFunctions::bundled();
+ default:
+ return nullptr;
+ }
+}
+
+AVCodec const* vulkan_capable_decoder(FFmpegFunctions const& functions, CodecID codec_id)
+{
+ auto const* codec = functions.avcodec_find_decoder_by_name(decoder_name_for(codec_id));
+ if (codec == nullptr)
+ return nullptr;
+ for (int index = 0;; index++) {
+ auto const* config = functions.avcodec_get_hw_config(codec, index);
+ if (config == nullptr)
+ return nullptr;
+ if (config->device_type == AV_HWDEVICE_TYPE_VULKAN && (config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX) != 0)
+ return codec;
+ }
+}
+
+Optional<VkVideoComponentBitDepthFlagBitsKHR> component_bit_depth_for(u8 bit_depth)
+{
+ switch (bit_depth) {
+ case 8:
+ return VK_VIDEO_COMPONENT_BIT_DEPTH_8_BIT_KHR;
+ case 10:
+ return VK_VIDEO_COMPONENT_BIT_DEPTH_10_BIT_KHR;
+ case 12:
+ return VK_VIDEO_COMPONENT_BIT_DEPTH_12_BIT_KHR;
+ default:
+ return {};
+ }
+}
+
+// Every decoder in the process shares one device context around the process's device, which lives as long as it does.
+DecoderErrorOr<AVBufferRef*> device_context_for(FFmpegFunctions const& functions, VulkanVideoDevice& device)
+{
+ static NeverDestroyed<Mutex> mutex;
+ static AVBufferRef* device_context_reference = nullptr;
+
+ MutexLocker locker { *mutex };
+ if (device_context_reference != nullptr)
+ return device_context_reference;
+
+ auto* reference = functions.av_hwdevice_ctx_alloc(AV_HWDEVICE_TYPE_VULKAN);
+ if (reference == nullptr)
+ return DecoderError::with_description(DecoderErrorCategory::Memory, "Could not allocate an FFmpeg Vulkan device context"sv);
+ ArmedScopeGuard free_reference = [&] { functions.av_buffer_unref(&reference); };
+
+ auto& device_context = *reinterpret_cast<AVHWDeviceContext*>(reference->data);
+ auto& vulkan_context = *static_cast<AVVulkanDeviceContext*>(device_context.hwctx);
+ vulkan_context.get_proc_addr = vkGetInstanceProcAddr;
+ vulkan_context.inst = device.instance();
+ vulkan_context.phys_dev = device.physical_device();
+ vulkan_context.act_dev = device.logical_device();
+ vulkan_context.device_features = device.enabled_features();
+ vulkan_context.enabled_dev_extensions = device.enabled_extensions().data();
+ vulkan_context.nb_enabled_dev_extensions = static_cast<int>(device.enabled_extensions().size());
+ for (auto const& family : device.queue_families()) {
+ auto& queue_family = vulkan_context.qf[vulkan_context.nb_qf++];
+ queue_family.idx = static_cast<int>(family.index);
+ queue_family.num = 1;
+ queue_family.flags = static_cast<VkQueueFlagBits>(family.flags);
+ }
+
+ if (functions.av_hwdevice_ctx_init(reference) < 0)
+ return DecoderError::with_description(DecoderErrorCategory::NotImplemented, "FFmpeg could not use the Vulkan device"sv);
+
+ free_reference.disarm();
+ device_context_reference = reference;
+ return reference;
+}
+
+bool wait_for_semaphore(VkDevice device, VkSemaphore semaphore, u64 value)
+{
+ VkSemaphoreWaitInfo wait_info {};
+ wait_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO;
+ wait_info.semaphoreCount = 1;
+ wait_info.pSemaphores = &semaphore;
+ wait_info.pValues = &value;
+ return vkWaitSemaphores(device, &wait_info, static_cast<u64>(DEVICE_WORK_STALL_UNTIL_TREATED_AS_FAILED.to_nanoseconds())) == VK_SUCCESS;
+}
+
+AVHWFramesContext& frames_context_of(AVFrame const& frame)
+{
+ return *reinterpret_cast<AVHWFramesContext*>(frame.hw_frames_ctx->data);
+}
+
+struct SemaphoreValue {
+ VkSemaphore semaphore { VK_NULL_HANDLE };
+ u64 value { 0 };
+};
+
+// Reads the semaphore and the value that the frame's latest work signals, which FFmpeg updates on whichever thread
+// submits work using the frame.
+SemaphoreValue semaphore_value_of(AVFrame const& frame)
+{
+ auto& frames_context = frames_context_of(frame);
+ auto& vulkan_frames_context = *static_cast<AVVulkanFramesContext*>(frames_context.hwctx);
+ auto* vulkan_frame = reinterpret_cast<AVVkFrame*>(frame.data[0]);
+ vulkan_frames_context.lock_frame(&frames_context, vulkan_frame);
+ SemaphoreValue result { vulkan_frame->sem[0], vulkan_frame->sem_value[0] };
+ vulkan_frames_context.unlock_frame(&frames_context, vulkan_frame);
+ return result;
+}
+
+u8 bit_depth_of(AVHWFramesContext const& frames_context)
+{
+ return frames_context.sw_format == AV_PIX_FMT_P010 ? 10 : 8;
+}
+
+// Keeps a decoded image out of FFmpeg's pool, so that it is not decoded over while its frame is held anywhere.
+class VulkanFrameContents final : public VideoSurfaceContents {
+public:
+ VulkanFrameContents(FFmpegFunctions const& functions, AVFrame* frame)
+ : m_functions(functions)
+ , m_frame(frame)
+ {
+ }
+
+ virtual ~VulkanFrameContents() override
+ {
+ m_functions.av_frame_free(&m_frame);
+ }
+
+private:
+ FFmpegFunctions const& m_functions;
+ AVFrame* m_frame { nullptr };
+};
+
+}
+
+Optional<DecoderCapabilities> FFmpegVulkanVideoDecoder::capabilities(ParsedCodec const& codec)
+{
+ auto* device = VulkanVideoDevice::the();
+ if (device == nullptr)
+ return {};
+
+ auto codec_id = codec.codec_id();
+ auto const* functions = ffmpeg_for(codec_id);
+ if (functions == nullptr || !device->has_enabled_extension(decode_extension_for(codec_id)))
+ return {};
+ if (vulkan_capable_decoder(*functions, codec_id) == nullptr)
+ return {};
+
+ VkVideoDecodeVP9ProfileInfoKHR vp9_profile {};
+ vp9_profile.sType = VK_STRUCTURE_TYPE_VIDEO_DECODE_VP9_PROFILE_INFO_KHR;
+ VkVideoDecodeAV1ProfileInfoKHR av1_profile {};
+ av1_profile.sType = VK_STRUCTURE_TYPE_VIDEO_DECODE_AV1_PROFILE_INFO_KHR;
+ VkVideoDecodeVP9CapabilitiesKHR vp9_capabilities {};
+ vp9_capabilities.sType = VK_STRUCTURE_TYPE_VIDEO_DECODE_VP9_CAPABILITIES_KHR;
+ VkVideoDecodeAV1CapabilitiesKHR av1_capabilities {};
+ av1_capabilities.sType = VK_STRUCTURE_TYPE_VIDEO_DECODE_AV1_CAPABILITIES_KHR;
+
+ VkVideoProfileInfoKHR profile_info {};
+ profile_info.sType = VK_STRUCTURE_TYPE_VIDEO_PROFILE_INFO_KHR;
+ profile_info.chromaSubsampling = VK_VIDEO_CHROMA_SUBSAMPLING_420_BIT_KHR;
+ VkVideoDecodeCapabilitiesKHR decode_capabilities {};
+ decode_capabilities.sType = VK_STRUCTURE_TYPE_VIDEO_DECODE_CAPABILITIES_KHR;
+
+ // Only 4:2:0 profiles decode to the formats that export.
+ u8 bit_depth = 8;
+ switch (codec_id) {
+ case CodecID::VP9: {
+ u8 profile = 0;
+ if (auto parameters = codec.vp9_parameters(); parameters.has_value()) {
+ profile = parameters->profile;
+ bit_depth = max(parameters->bit_depth, static_cast<u8>(8));
+ }
+ if (profile != 0 && profile != 2)
+ return {};
+ vp9_profile.stdProfile = static_cast<StdVideoVP9Profile>(profile);
+ profile_info.pNext = &vp9_profile;
+ profile_info.videoCodecOperation = VK_VIDEO_CODEC_OPERATION_DECODE_VP9_BIT_KHR;
+ decode_capabilities.pNext = &vp9_capabilities;
+ break;
+ }
+ case CodecID::AV1: {
+ u8 profile = 0;
+ if (auto parameters = codec.av1_parameters(); parameters.has_value()) {
+ profile = parameters->profile;
+ bit_depth = max(parameters->bit_depth, static_cast<u8>(8));
+ }
+ if (profile != 0)
+ return {};
+ av1_profile.stdProfile = STD_VIDEO_AV1_PROFILE_MAIN;
+ profile_info.pNext = &av1_profile;
+ profile_info.videoCodecOperation = VK_VIDEO_CODEC_OPERATION_DECODE_AV1_BIT_KHR;
+ decode_capabilities.pNext = &av1_capabilities;
+ break;
+ }
+ default:
+ VERIFY_NOT_REACHED();
+ }
+
+ // Only 8 and 10 bit samples decode into the formats that export.
+ if (bit_depth != 8 && bit_depth != 10)
+ return {};
+ auto component_bit_depth = component_bit_depth_for(bit_depth);
+ if (!component_bit_depth.has_value())
+ return {};
+ profile_info.lumaBitDepth = *component_bit_depth;
+ profile_info.chromaBitDepth = *component_bit_depth;
+
+ VkVideoCapabilitiesKHR video_capabilities {};
+ video_capabilities.sType = VK_STRUCTURE_TYPE_VIDEO_CAPABILITIES_KHR;
+ video_capabilities.pNext = &decode_capabilities;
+ if (device->video_capabilities(profile_info, video_capabilities).is_error())
+ return {};
+
+ return DecoderCapabilities { .smooth = true, .power_efficient = true };
+}
+
+DecoderErrorOr<NonnullOwnPtr<FFmpegVulkanVideoDecoder>> FFmpegVulkanVideoDecoder::try_create(CodecID codec_id, ReadonlyBytes codec_initialization_data)
+{
+ auto* device = VulkanVideoDevice::the();
+ if (device == nullptr)
+ return DecoderError::with_description(DecoderErrorCategory::NotImplemented, "No Vulkan device can decode video in this process"sv);
+ auto const* ffmpeg = ffmpeg_for(codec_id);
+ if (ffmpeg == nullptr || !device->has_enabled_extension(decode_extension_for(codec_id)))
+ return DecoderError::format(DecoderErrorCategory::NotImplemented, "The Vulkan device cannot decode codec {}", codec_id);
+ auto const& functions = *ffmpeg;
+
+ auto* device_context = TRY(device_context_for(functions, *device));
+
+ AVCodecContext* codec_context = nullptr;
+ AVPacket* packet = nullptr;
+ AVFrame* frame = nullptr;
+ ArmedScopeGuard memory_guard {
+ [&] {
+ functions.avcodec_free_context(&codec_context);
+ functions.av_packet_free(&packet);
+ functions.av_frame_free(&frame);
+ }
+ };
+
+ auto const* codec = vulkan_capable_decoder(functions, codec_id);
+ if (codec == nullptr)
+ return DecoderError::format(DecoderErrorCategory::NotImplemented, "FFmpeg cannot decode codec {} through Vulkan", codec_id);
+
+ codec_context = functions.avcodec_alloc_context3(codec);
+ if (codec_context == nullptr)
+ return DecoderError::format(DecoderErrorCategory::Memory, "Failed to allocate FFmpeg codec context for codec {}", codec_id);
+
+ TRY(set_codec_initialization_data(functions, *codec_context, codec_id, codec_initialization_data));
+ // The device already decodes several frames at a time, and frame threading would only hold frames back.
+ VERIFY(functions.av_opt_set_int(codec_context, "threads", 1, 0) == 0);
+ codec_context->hw_device_ctx = functions.av_buffer_ref(device_context);
+ if (codec_context->hw_device_ctx == nullptr)
+ return DecoderError::with_description(DecoderErrorCategory::Memory, "Failed to reference the FFmpeg Vulkan device context"sv);
+ codec_context->get_format = negotiate_pixel_format;
+ codec_context->get_buffer2 = get_buffer;
+
+ if (functions.avcodec_open2(codec_context, codec, nullptr) < 0)
+ return DecoderError::format(DecoderErrorCategory::Unknown, "Unknown error occurred when opening FFmpeg codec {}", codec_id);
+
+ packet = functions.av_packet_alloc();
+ if (packet == nullptr)
+ return DecoderError::with_description(DecoderErrorCategory::Memory, "Failed to allocate FFmpeg packet"sv);
+
+ frame = functions.av_frame_alloc();
+ if (frame == nullptr)
+ return DecoderError::with_description(DecoderErrorCategory::Memory, "Failed to allocate FFmpeg frame"sv);
+
+ auto surface_pool = VideoFrameSurfacePool::create();
+ if (surface_pool.is_error())
+ return DecoderError::format(DecoderErrorCategory::Memory, "Failed to create a video surface pool: {}", surface_pool.release_error());
+
+ memory_guard.disarm();
+ auto decoder = DECODER_TRY_ALLOC(adopt_nonnull_own_or_enomem(new (nothrow) FFmpegVulkanVideoDecoder(functions, *device, codec_context, packet, frame, surface_pool.release_value())));
+ codec_context->opaque = decoder.ptr();
+
+ decoder->m_completion_thread = DECODER_TRY_ALLOC(Threading::Thread::try_create("VulkanDecode"sv, [decoder = decoder.ptr()] -> intptr_t {
+ decoder->complete_frames_until_exit();
+ return 0;
+ }));
+ decoder->m_completion_thread->start();
+ return decoder;
+}
+
+FFmpegVulkanVideoDecoder::FFmpegVulkanVideoDecoder(FFmpegFunctions const& functions, VulkanVideoDevice& device, AVCodecContext* codec_context, AVPacket* packet, AVFrame* received_frame, NonnullRefPtr<VideoFrameSurfacePool> surface_pool)
+ : m_functions(functions)
+ , m_device(device)
+ , m_codec_context(codec_context)
+ , m_packet(packet)
+ , m_received_frame(received_frame)
+ , m_surface_pool(move(surface_pool))
+{
+}
+
+FFmpegVulkanVideoDecoder::~FFmpegVulkanVideoDecoder()
+{
+ Vector<DecodingFrame> decoding_frames;
+ {
+ MutexLocker locker { m_mutex };
+ m_completion_thread_should_exit = true;
+ m_condition.broadcast();
+ }
+ if (m_completion_thread)
+ (void)m_completion_thread->join();
+ while (!m_decoding_frames.is_empty())
+ decoding_frames.append(m_decoding_frames.dequeue());
+ free_decoding_frames(decoding_frames);
+ m_outputs.clear();
+
+ m_surface_pool->shed_storage();
+ m_functions.av_packet_free(&m_packet);
+ m_functions.av_frame_free(&m_received_frame);
+ m_functions.avcodec_free_context(&m_codec_context);
+}
+
+AVPixelFormat FFmpegVulkanVideoDecoder::negotiate_pixel_format(AVCodecContext* codec_context, AVPixelFormat const* pixel_formats)
+{
+ auto& decoder = *static_cast<FFmpegVulkanVideoDecoder*>(codec_context->opaque);
+ for (auto const* pixel_format = pixel_formats; *pixel_format != AV_PIX_FMT_NONE; pixel_format++) {
+ if (*pixel_format != AV_PIX_FMT_VULKAN)
+ continue;
+ auto result = decoder.create_frames_context();
+ if (result.is_error()) {
+ decoder.m_pixel_format_error = result.release_error();
+ return AV_PIX_FMT_NONE;
+ }
+ return AV_PIX_FMT_VULKAN;
+ }
+ decoder.m_pixel_format_error = DecoderError::with_description(DecoderErrorCategory::NotImplemented, "FFmpeg cannot decode this stream through Vulkan"sv);
+ return AV_PIX_FMT_NONE;
+}
+
+int FFmpegVulkanVideoDecoder::get_buffer(AVCodecContext* codec_context, AVFrame* frame, int flags)
+{
+ auto& decoder = *static_cast<FFmpegVulkanVideoDecoder*>(codec_context->opaque);
+ MutexLocker locker { decoder.m_frames_context_mutex };
+ return decoder.m_functions.avcodec_default_get_buffer2(codec_context, frame, flags);
+}
+
+DecoderErrorOr<void> FFmpegVulkanVideoDecoder::create_frames_context()
+{
+ AVBufferRef* frames_reference = nullptr;
+ if (m_functions.avcodec_get_hw_frames_parameters(m_codec_context, m_codec_context->hw_device_ctx, AV_PIX_FMT_VULKAN, &frames_reference) < 0)
+ return DecoderError::with_description(DecoderErrorCategory::NotImplemented, "FFmpeg cannot describe Vulkan frames for this stream"sv);
+ ArmedScopeGuard free_frames_reference = [&] { m_functions.av_buffer_unref(&frames_reference); };
+
+ auto& frames_context = *reinterpret_cast<AVHWFramesContext*>(frames_reference->data);
+ auto& vulkan_frames_context = *static_cast<AVVulkanFramesContext*>(frames_context.hwctx);
+ if (frames_context.sw_format != AV_PIX_FMT_NV12 && frames_context.sw_format != AV_PIX_FMT_P010)
+ return DecoderError::with_description(DecoderErrorCategory::NotImplemented, "The stream decodes to a format that cannot be exported"sv);
+
+ // Storage use is only for FFmpeg's own filters, and can rule out the modifiers that export.
+ vulkan_frames_context.usage = static_cast<VkImageUsageFlagBits>(vulkan_frames_context.usage & ~VK_IMAGE_USAGE_STORAGE_BIT);
+
+ m_drm_format_modifiers = m_device.exportable_drm_format_modifiers(vulkan_frames_context.format[0], vulkan_frames_context.usage, vulkan_frames_context.img_flags, vulkan_frames_context.create_pnext);
+ if (m_drm_format_modifiers.is_empty())
+ return DecoderError::with_description(DecoderErrorCategory::NotImplemented, "No DRM format modifier can export the decoded images"sv);
+
+ // FFmpeg chains the video profile in, and leaves choosing a modifier to us.
+ m_drm_format_modifier_list = {};
+ m_drm_format_modifier_list.sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_LIST_CREATE_INFO_EXT;
+ m_drm_format_modifier_list.pNext = vulkan_frames_context.create_pnext;
+ m_drm_format_modifier_list.drmFormatModifierCount = m_drm_format_modifiers.size();
+ m_drm_format_modifier_list.pDrmFormatModifiers = m_drm_format_modifiers.data();
+ vulkan_frames_context.tiling = VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT;
+ vulkan_frames_context.create_pnext = &m_drm_format_modifier_list;
+
+ if (m_functions.av_hwframe_ctx_init(frames_reference) < 0)
+ return DecoderError::with_description(DecoderErrorCategory::NotImplemented, "FFmpeg could not create exportable Vulkan frames"sv);
+
+ m_functions.av_buffer_unref(&m_codec_context->hw_frames_ctx);
+ m_codec_context->hw_frames_ctx = frames_reference;
+ free_frames_reference.disarm();
+ return {};
+}
+
+DecoderErrorOr<void> FFmpegVulkanVideoDecoder::receive_coded_data(CodedFrame const& coded_frame, DecodeIntent intent)
+{
+ if (m_pixel_format_error.has_value())
+ return *m_pixel_format_error;
+
+ auto key = TRY(m_frames_awaiting_output.add(coded_frame, intent));
+ auto result = send_coded_frame(m_functions, *m_codec_context, *m_packet, coded_frame, key);
+ // FFmpeg takes no more until the frames it has decoded are taken out.
+ if (result.is_error() && result.error().category() == DecoderErrorCategory::TryAgain) {
+ TRY(receive_decoded_frames());
+ result = send_coded_frame(m_functions, *m_codec_context, *m_packet, coded_frame, key);
+ }
+ if (result.is_error() && m_pixel_format_error.has_value())
+ return *m_pixel_format_error;
+ TRY(result);
+
+ return receive_decoded_frames();
+}
+
+void FFmpegVulkanVideoDecoder::signal_end_of_stream()
+{
+ m_packet->data = nullptr;
+ m_packet->size = 0;
+ m_packet->pts = 0;
+ m_packet->dts = 0;
+
+ auto result = m_functions.avcodec_send_packet(m_codec_context, m_packet);
+ VERIFY(result == 0 || result == AVERROR_EOF);
+ if (auto received = receive_decoded_frames(); received.is_error()) {
+ MutexLocker locker { m_mutex };
+ if (!m_decode_failure.has_value())
+ m_decode_failure = received.release_error();
+ }
+}
+
+DecoderErrorOr<void> FFmpegVulkanVideoDecoder::receive_decoded_frames()
+{
+ while (true) {
+ auto result = m_functions.avcodec_receive_frame(m_codec_context, m_received_frame);
+ if (result == AVERROR(EAGAIN))
+ return {};
+ if (result == AVERROR_EOF) {
+ if (!m_received_end_of_stream) {
+ m_received_end_of_stream = true;
+ DecodingFrame end_of_stream;
+ end_of_stream.generation = m_generation;
+ enqueue_decoding_frame(move(end_of_stream));
+ }
+ return {};
+ }
+ if (result < 0) {
+ if (m_pixel_format_error.has_value())
+ return *m_pixel_format_error;
+ return DecoderError::format(DecoderErrorCategory::Unknown, "FFmpeg codec encountered an unexpected error retrieving frames with code {:x}", result);
+ }
+
+ auto timing = m_frames_awaiting_output.take(m_received_frame->pts);
+ if (!timing.has_value() || timing->intent == DecodeIntent::Reference) {
+ m_functions.av_frame_unref(m_received_frame);
+ continue;
+ }
+
+ auto* frame = m_functions.av_frame_alloc();
+ if (frame == nullptr) {
+ m_functions.av_frame_unref(m_received_frame);
+ return DecoderError::with_description(DecoderErrorCategory::Memory, "Failed to allocate FFmpeg frame"sv);
+ }
+ m_functions.av_frame_move_ref(frame, m_received_frame);
+
+ DecodingFrame decoding_frame;
+ decoding_frame.frame = frame;
+ decoding_frame.timing = *timing;
+ decoding_frame.generation = m_generation;
+ auto decoded = semaphore_value_of(*frame);
+ decoding_frame.semaphore = decoded.semaphore;
+ decoding_frame.decoded_semaphore_value = decoded.value;
+ enqueue_decoding_frame(move(decoding_frame));
+ }
+}
+
+void FFmpegVulkanVideoDecoder::enqueue_decoding_frame(DecodingFrame decoding_frame)
+{
+ MutexLocker locker { m_mutex };
+ m_decoding_frames.enqueue(move(decoding_frame));
+ m_condition.broadcast();
+}
+
+void FFmpegVulkanVideoDecoder::free_decoding_frames(Vector<DecodingFrame>& decoding_frames)
+{
+ for (auto& decoding_frame : decoding_frames)
+ m_functions.av_frame_free(&decoding_frame.frame);
+ decoding_frames.clear();
+}
+
+void FFmpegVulkanVideoDecoder::complete_frames_until_exit()
+{
+ while (true) {
+ DecodingFrame decoding_frame;
+ {
+ MutexLocker locker { m_mutex };
+ while (m_decoding_frames.is_empty() && !m_completion_thread_should_exit)
+ m_condition.wait();
+ if (m_completion_thread_should_exit)
+ return;
+ decoding_frame = m_decoding_frames.dequeue();
+ }
+
+ Optional<DecoderErrorOr<DecodedOutput>> output;
+ if (decoding_frame.frame != nullptr)
+ output = complete_frame(decoding_frame);
+
+ auto caller_needs_waking = false;
+ {
+ MutexLocker locker { m_mutex };
+ if (decoding_frame.generation == m_generation) {
+ if (!output.has_value())
+ m_completed_end_of_stream = true;
+ else if (output->is_error())
+ m_decode_failure = output->release_error();
+ else
+ m_outputs.append(output->release_value());
+ caller_needs_waking = !m_caller_is_waiting_for_output;
+ }
+ m_condition.broadcast();
+ }
+
+ if (caller_needs_waking && m_output_arrived_callback)
+ m_output_arrived_callback();
+ }
+}
+
+DecoderErrorOr<FFmpegVulkanVideoDecoder::DecodedOutput> FFmpegVulkanVideoDecoder::complete_frame(DecodingFrame& decoding_frame)
+{
+ ScopeGuard free_frame = [&] { m_functions.av_frame_free(&decoding_frame.frame); };
+ auto& frame = *decoding_frame.frame;
+ auto logical_device = m_device.logical_device();
+
+ if (!wait_for_semaphore(logical_device, decoding_frame.semaphore, decoding_frame.decoded_semaphore_value))
+ return DecoderError::with_description(DecoderErrorCategory::Unknown, "The Vulkan device failed or stalled while decoding a frame"sv);
+
+ // Mapping the frame to dma-bufs hands its image over to whichever device samples it next, which the frame then waits
+ // for, so that it leaves the decoder ready to be drawn.
+ auto* exported_frame = m_functions.av_frame_alloc();
+ if (exported_frame == nullptr)
+ return DecoderError::with_description(DecoderErrorCategory::Memory, "Failed to allocate FFmpeg frame"sv);
+ ScopeGuard free_exported_frame = [&] { m_functions.av_frame_free(&exported_frame); };
+ exported_frame->format = AV_PIX_FMT_DRM_PRIME;
+ {
+ MutexLocker locker { m_frames_context_mutex };
+ if (m_functions.av_hwframe_map(exported_frame, &frame, AV_HWFRAME_MAP_READ) < 0)
+ return DecoderError::with_description(DecoderErrorCategory::Unknown, "Could not export a decoded frame as dma-bufs"sv);
+ }
+ auto exported = semaphore_value_of(frame);
+ if (!wait_for_semaphore(logical_device, exported.semaphore, exported.value))
+ return DecoderError::with_description(DecoderErrorCategory::Unknown, "The Vulkan device failed or stalled while readying a frame for export"sv);
+
+ auto surface = TRY(surface_for_exported_frame(frame, *exported_frame));
+ auto const& frames_context = frames_context_of(frame);
+ Gfx::Size<u32> size { static_cast<u32>(frame.width), static_cast<u32>(frame.height) };
+ auto bit_depth = bit_depth_of(frames_context);
+ auto contents = DECODER_TRY_ALLOC(try_make_ref_counted<VulkanFrameContents>(m_functions, exchange(decoding_frame.frame, nullptr)));
+ return DecodedOutput { move(surface), move(contents), decoding_frame.timing, size, bit_depth };
+}
+
+DecoderErrorOr<NonnullRefPtr<VideoSurface>> FFmpegVulkanVideoDecoder::surface_for_exported_frame(AVFrame const& frame, AVFrame const& exported_frame)
+{
+ auto const& frames_context = frames_context_of(frame);
+ if (&frames_context != m_frames_context_of_surfaces) {
+ m_surfaces_by_image.clear();
+ m_frames_context_of_surfaces = &frames_context;
+ }
+
+ auto const& vulkan_frame = *reinterpret_cast<AVVkFrame const*>(frame.data[0]);
+ u64 image_key = 0;
+ static_assert(sizeof(vulkan_frame.img[0]) <= sizeof(image_key));
+ memcpy(&image_key, &vulkan_frame.img[0], sizeof(vulkan_frame.img[0]));
+ if (auto surface = m_surfaces_by_image.get(image_key); surface.has_value())
+ return NonnullRefPtr { **surface };
+
+ auto const& descriptor = *reinterpret_cast<AVDRMFrameDescriptor const*>(exported_frame.data[0]);
+ if (descriptor.nb_objects < 1 || static_cast<size_t>(descriptor.nb_objects) > Gfx::LinuxDmaBufHandle::MAXIMUM_PLANE_COUNT)
+ return DecoderError::with_description(DecoderErrorCategory::NotImplemented, "A decoded image exported to an unusable number of dma-bufs"sv);
+
+ Gfx::LinuxDmaBufHandle dma_buf;
+ dma_buf.size = { frames_context.width, frames_context.height };
+ dma_buf.drm_format = frames_context.sw_format == AV_PIX_FMT_P010 ? DRM_FORMAT_P010 : DRM_FORMAT_NV12;
+ dma_buf.modifier = descriptor.objects[0].format_modifier;
+ for (int object_index = 0; object_index < descriptor.nb_objects; object_index++) {
+ auto object = IPC::File::clone_fd(descriptor.objects[object_index].fd);
+ if (object.is_error())
+ return DecoderError::format(DecoderErrorCategory::Memory, "Could not duplicate a decoded image's dma-buf: {}", object.error());
+ dma_buf.objects.append(object.release_value());
+ }
+ for (int layer_index = 0; layer_index < descriptor.nb_layers; layer_index++) {
+ auto const& layer = descriptor.layers[layer_index];
+ for (int plane_index = 0; plane_index < layer.nb_planes; plane_index++) {
+ if (dma_buf.planes.size() == Gfx::LinuxDmaBufHandle::MAXIMUM_PLANE_COUNT)
+ return DecoderError::with_description(DecoderErrorCategory::NotImplemented, "A decoded image exported too many planes"sv);
+ auto const& plane = layer.planes[plane_index];
+ dma_buf.planes.append({ static_cast<u32>(plane.object_index), static_cast<u32>(plane.offset), static_cast<u32>(plane.pitch) });
+ }
+ }
+
+ auto surface = VideoSurface::create_from_dma_buf(s_next_surface_id.fetch_add(1, AK::MemoryOrder::memory_order_relaxed), move(dma_buf));
+ if (surface.is_error())
+ return DecoderError::format(DecoderErrorCategory::Memory, "Could not create a surface for a decoded image: {}", surface.error());
+ DECODER_TRY_ALLOC(m_surfaces_by_image.try_set(image_key, surface.value()));
+ return surface.release_value();
+}
+
+DecoderErrorOr<NonnullRefPtr<VideoFrame>> FFmpegVulkanVideoDecoder::take_next_output(CodingIndependentCodePoints const& container_cicp, Optional<AK::Duration>)
+{
+ TRY(receive_decoded_frames());
+
+ MutexLocker locker { m_mutex };
+ while (m_outputs.is_empty()) {
+ if (m_decode_failure.has_value())
+ return m_decode_failure.release_value();
+ if (m_completed_end_of_stream)
+ return DecoderError::with_description(DecoderErrorCategory::EndOfStream, "FFmpeg decoder has been flushed"sv);
+ // Frames still being completed wake the caller when they come out, unless it is draining, when nothing else
+ // can arrive to do so.
+ if (!m_received_end_of_stream)
+ return DecoderError::with_description(DecoderErrorCategory::NeedsMoreInput, "The Vulkan device has no finished frame to hand out"sv);
+
+ m_caller_is_waiting_for_output = true;
+ m_condition.wait();
+ m_caller_is_waiting_for_output = false;
+ }
+
+ auto const& output = m_outputs.first();
+ auto acquired_slot = m_surface_pool->try_acquire(output.surface, output.contents);
+ if (!acquired_slot.has_value())
+ return DecoderError::with_description(DecoderErrorCategory::TryAgain, "Every video frame slot is held elsewhere"sv);
+ auto pool_slot = m_surface_pool->try_adopt_acquired_slot(*acquired_slot);
+ if (pool_slot.is_error())
+ return DecoderError::with_description(DecoderErrorCategory::Memory, "Failed to allocate a pooled frame slot reference"sv);
+
+ auto cicp = coding_independent_code_points_of(m_functions, *m_codec_context, container_cicp);
+ auto frame = DECODER_TRY_ALLOC(try_make_ref_counted<VideoFrame>(output.timing.timestamp, output.timing.duration, output.size, output.bit_depth, Subsampling::yuv420(), cicp, pool_slot.release_value()));
+ m_outputs.take_first();
+ return frame;
+}
+
+void FFmpegVulkanVideoDecoder::flush()
+{
+ m_functions.avcodec_flush_buffers(m_codec_context);
+ m_frames_awaiting_output.clear();
+ m_received_end_of_stream = false;
+
+ Vector<DecodingFrame> stale_frames;
+ Vector<DecodedOutput> stale_outputs;
+ {
+ MutexLocker locker { m_mutex };
+ m_generation++;
+ while (!m_decoding_frames.is_empty())
+ stale_frames.append(m_decoding_frames.dequeue());
+ stale_outputs = move(m_outputs);
+ m_decode_failure.clear();
+ m_completed_end_of_stream = false;
+ }
+ free_decoding_frames(stale_frames);
+}
+
+}
diff --git a/Libraries/LibMediaCodecs/FFmpeg/FFmpegVulkanVideoDecoder.h b/Libraries/LibMediaCodecs/FFmpeg/FFmpegVulkanVideoDecoder.h
new file mode 100644
index 00000000000..c93621c50ea
--- /dev/null
+++ b/Libraries/LibMediaCodecs/FFmpeg/FFmpegVulkanVideoDecoder.h
@@ -0,0 +1,121 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#ifdef USE_VULKAN_DMABUF_IMAGES
+
+# include <AK/ConditionVariable.h>
+# include <AK/HashMap.h>
+# include <AK/Mutex.h>
+# include <AK/Queue.h>
+# include <LibMediaCodecs/CodecID.h>
+# include <LibMediaCodecs/CodecParameters.h>
+# include <LibMediaCodecs/DecoderCapabilities.h>
+# include <LibMediaCodecs/Export.h>
+# include <LibMediaCodecs/FFmpeg/FFmpegFunctions.h>
+# include <LibMediaCodecs/FFmpeg/VideoFramesAwaitingOutput.h>
+# include <LibMediaCodecs/VideoDecoder.h>
+# include <LibMediaCodecs/VideoFramePool.h>
+# include <LibMediaCodecs/VideoSurface.h>
+# include <LibMediaCodecs/Vulkan/VulkanVideoDevice.h>
+# include <LibThreading/Forward.h>
+
+namespace Media::FFmpeg {
+
+// Decodes through FFmpeg's Vulkan hardware acceleration into images that export as dma-bufs. The device decodes
+// asynchronously, so a thread of the decoder's own waits for each frame to finish, readies it for another device to
+// sample, and hands it out.
+class MEDIACODECS_API FFmpegVulkanVideoDecoder final : public VideoDecoder {
+public:
+ AK_ALLOC_WITH_KMALLOC;
+
+ static Optional<DecoderCapabilities> capabilities(ParsedCodec const&);
+ static DecoderErrorOr<NonnullOwnPtr<FFmpegVulkanVideoDecoder>> try_create(CodecID, ReadonlyBytes codec_initialization_data);
+ virtual ~FFmpegVulkanVideoDecoder() override;
+
+ virtual void set_storage_freed_callback(Function<void()> callback) override { m_surface_pool->set_slot_freed_callback(move(callback)); }
+ virtual void set_output_arrived_callback(Function<void()> callback) override { m_output_arrived_callback = move(callback); }
+
+ virtual DecoderErrorOr<void> receive_coded_data(CodedFrame const&, DecodeIntent) override;
+ virtual void signal_end_of_stream() override;
+ virtual DecoderErrorOr<NonnullRefPtr<VideoFrame>> take_next_output(CodingIndependentCodePoints const& container_cicp, Optional<AK::Duration> target = {}) override;
+ virtual void flush() override;
+
+private:
+ struct DecodingFrame {
+ // None marks the end of the stream, after the last frame.
+ AVFrame* frame { nullptr };
+ VideoFramesAwaitingOutput::Frame timing;
+ u64 generation { 0 };
+ // Later decodes that reference the frame advance its semaphore further, so the value its own decode signals
+ // is taken as soon as FFmpeg hands the frame out.
+ VkSemaphore semaphore { VK_NULL_HANDLE };
+ u64 decoded_semaphore_value { 0 };
+ };
+
+ struct DecodedOutput {
+ NonnullRefPtr<VideoSurface> surface;
+ // Holds the decoded image out of FFmpeg's pool until the slot the frame goes out in is released.
+ NonnullRefPtr<VideoSurfaceContents> contents;
+ VideoFramesAwaitingOutput::Frame timing;
+ Gfx::Size<u32> size;
+ u8 bit_depth { 0 };
+ };
+
+ FFmpegVulkanVideoDecoder(FFmpegFunctions const&, VulkanVideoDevice&, AVCodecContext*, AVPacket*, AVFrame*, NonnullRefPtr<VideoFrameSurfacePool>);
+
+ static AVPixelFormat negotiate_pixel_format(AVCodecContext*, AVPixelFormat const*);
+ static int get_buffer(AVCodecContext*, AVFrame*, int flags);
+ DecoderErrorOr<void> create_frames_context();
+
+ DecoderErrorOr<void> receive_decoded_frames();
+ void enqueue_decoding_frame(DecodingFrame);
+ void free_decoding_frames(Vector<DecodingFrame>&);
+
+ void complete_frames_until_exit();
+ DecoderErrorOr<DecodedOutput> complete_frame(DecodingFrame&);
+ DecoderErrorOr<NonnullRefPtr<VideoSurface>> surface_for_exported_frame(AVFrame const& frame, AVFrame const& exported_frame);
+
+ FFmpegFunctions const& m_functions;
+ VulkanVideoDevice& m_device;
+ AVCodecContext* m_codec_context { nullptr };
+ AVPacket* m_packet { nullptr };
+ AVFrame* m_received_frame { nullptr };
+ NonnullRefPtr<VideoFrameSurfacePool> m_surface_pool;
+
+ // Only the caller's thread uses these.
+ VideoFramesAwaitingOutput m_frames_awaiting_output;
+ Optional<DecoderError> m_pixel_format_error;
+ bool m_received_end_of_stream { false };
+ Vector<u64> m_drm_format_modifiers;
+ VkImageDrmFormatModifierListCreateInfoEXT m_drm_format_modifier_list {};
+
+ // FFmpeg records the work that allocates images and readies them for export on a frames context's own command
+ // buffers, which it does not keep threads from sharing.
+ Mutex m_frames_context_mutex;
+
+ mutable Mutex m_mutex;
+ ConditionVariable m_condition { m_mutex };
+ Queue<DecodingFrame> m_decoding_frames;
+ Vector<DecodedOutput> m_outputs;
+ Optional<DecoderError> m_decode_failure;
+ bool m_completed_end_of_stream { false };
+ bool m_caller_is_waiting_for_output { false };
+ bool m_completion_thread_should_exit { false };
+ u64 m_generation { 0 };
+ Function<void()> m_output_arrived_callback;
+ RefPtr<Threading::Thread> m_completion_thread;
+
+ // Only the completion thread uses these. A frames context recycles its images, so each one's surface is kept and
+ // recognized when it comes back.
+ AVHWFramesContext const* m_frames_context_of_surfaces { nullptr };
+ HashMap<u64, NonnullRefPtr<VideoSurface>> m_surfaces_by_image;
+};
+
+}
+
+#endif
diff --git a/Libraries/LibMediaCodecs/FFmpeg/VideoFramesAwaitingOutput.h b/Libraries/LibMediaCodecs/FFmpeg/VideoFramesAwaitingOutput.h
new file mode 100644
index 00000000000..a6dfc94fc50
--- /dev/null
+++ b/Libraries/LibMediaCodecs/FFmpeg/VideoFramesAwaitingOutput.h
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/HashMap.h>
+#include <AK/Optional.h>
+#include <AK/Time.h>
+#include <LibMediaCodecs/DecoderError.h>
+#include <LibMediaCodecs/Export.h>
+#include <LibMediaCodecs/Forward.h>
+#include <LibMediaCodecs/VideoDecoder.h>
+
+namespace Media::FFmpeg {
+
+// FFmpeg returns each packet's timestamp with the frame decoded from it, so a video decoder hands it a key instead and
+// keeps the frame's timing and intent under that key until the frame comes out.
+class MEDIACODECS_API VideoFramesAwaitingOutput {
+public:
+ struct Frame {
+ AK::Duration timestamp;
+ AK::Duration duration;
+ DecodeIntent intent;
+ };
+
+ DecoderErrorOr<u64> add(CodedFrame const&, DecodeIntent);
+ Optional<Frame> take(i64 key);
+ size_t size() const { return m_frames.size(); }
+ void clear() { m_frames.clear(); }
+
+private:
+ u64 m_next_key { 0 };
+ HashMap<u64, Frame> m_frames;
+};
+
+}
diff --git a/Libraries/LibMediaCodecs/HardwareVideoDecoders.cpp b/Libraries/LibMediaCodecs/HardwareVideoDecoders.cpp
index c55988f0087..140c4586a2a 100644
--- a/Libraries/LibMediaCodecs/HardwareVideoDecoders.cpp
+++ b/Libraries/LibMediaCodecs/HardwareVideoDecoders.cpp
@@ -9,6 +9,9 @@
#ifdef AK_OS_MACOS
# include <LibMediaCodecs/VideoToolbox/VideoToolboxVideoDecoder.h>
#endif
+#ifdef USE_VULKAN_DMABUF_IMAGES
+# include <LibMediaCodecs/FFmpeg/FFmpegVulkanVideoDecoder.h>
+#endif
namespace Media {
@@ -19,13 +22,26 @@ static DecoderErrorOr<NonnullOwnPtr<VideoDecoder>> create_videotoolbox_video_dec
}
#endif
+#ifdef USE_VULKAN_DMABUF_IMAGES
+static DecoderErrorOr<NonnullOwnPtr<VideoDecoder>> create_vulkan_video_decoder(CodecID codec_id, ReadonlyBytes codec_initialization_data)
+{
+ return NonnullOwnPtr<VideoDecoder> { TRY(FFmpeg::FFmpegVulkanVideoDecoder::try_create(codec_id, codec_initialization_data)) };
+}
+#endif
+
ReadonlySpan<VideoDecoderRegistration> hardware_video_decoders()
{
-#ifdef AK_OS_MACOS
+#if defined(AK_OS_MACOS)
static constexpr Array decoders {
VideoDecoderRegistration { VideoToolbox::VideoToolboxVideoDecoder::capabilities, create_videotoolbox_video_decoder },
};
return decoders;
+#elif defined(USE_VULKAN_DMABUF_IMAGES)
+ // Without a Vulkan device in the process, this answers no capabilities and creates nothing.
+ static constexpr Array decoders {
+ VideoDecoderRegistration { FFmpeg::FFmpegVulkanVideoDecoder::capabilities, create_vulkan_video_decoder },
+ };
+ return decoders;
#else
return {};
#endif
diff --git a/Libraries/LibMediaCodecs/Vulkan/VulkanVideoDevice.cpp b/Libraries/LibMediaCodecs/Vulkan/VulkanVideoDevice.cpp
index 1512f3fc489..6c082e8fff1 100644
--- a/Libraries/LibMediaCodecs/Vulkan/VulkanVideoDevice.cpp
+++ b/Libraries/LibMediaCodecs/Vulkan/VulkanVideoDevice.cpp
@@ -231,6 +231,11 @@ VulkanVideoDevice::~VulkanVideoDevice()
vkDestroyInstance(m_instance, nullptr);
}
+bool VulkanVideoDevice::has_enabled_extension(StringView name) const
+{
+ return any_of(m_enabled_extensions, [&](auto enabled) { return StringView { enabled, strlen(enabled) } == name; });
+}
+
ErrorOr<void> VulkanVideoDevice::video_capabilities(VkVideoProfileInfoKHR const& profile, VkVideoCapabilitiesKHR& capabilities) const
{
if (m_get_physical_device_video_capabilities(m_physical_device, &profile, &capabilities) != VK_SUCCESS)
diff --git a/Libraries/LibMediaCodecs/Vulkan/VulkanVideoDevice.h b/Libraries/LibMediaCodecs/Vulkan/VulkanVideoDevice.h
index 4f438411f38..94a0f2d993f 100644
--- a/Libraries/LibMediaCodecs/Vulkan/VulkanVideoDevice.h
+++ b/Libraries/LibMediaCodecs/Vulkan/VulkanVideoDevice.h
@@ -45,6 +45,7 @@ public:
ReadonlySpan<QueueFamily> queue_families() const { return m_queue_families; }
ReadonlySpan<char const*> enabled_extensions() const { return m_enabled_extensions; }
VkPhysicalDeviceFeatures2 const& enabled_features() const { return m_features; }
+ bool has_enabled_extension(StringView) const;
// Fills in the capabilities, and whatever codec-specific capabilities are chained to them, for a video profile.
ErrorOr<void> video_capabilities(VkVideoProfileInfoKHR const&, VkVideoCapabilitiesKHR&) const;
diff --git a/Services/Compositor/CMakeLists.txt b/Services/Compositor/CMakeLists.txt
index 5851a3f55c0..4e13242b32b 100644
--- a/Services/Compositor/CMakeLists.txt
+++ b/Services/Compositor/CMakeLists.txt
@@ -73,6 +73,10 @@ target_link_libraries(Compositor PRIVATE compositorservice LibCore LibMain LibSa
# OpenGL framework pulled in by Skia.
target_link_libraries(compositorservice PRIVATE LibCore LibGfx LibIPC LibMedia LibCompositing ${ANGLE_TARGETS} skia)
+if (USE_VULKAN_DMABUF_IMAGES)
+ target_sources(compositorservice PRIVATE VideoFrameSkiaVulkan.cpp)
+endif()
+
if (APPLE)
target_sources(compositorservice PRIVATE VideoFrameSkia.mm)
target_link_libraries(compositorservice PUBLIC "-framework CoreGraphics" "-framework CoreVideo")
diff --git a/Services/Compositor/DisplayListPlayerSkia.cpp b/Services/Compositor/DisplayListPlayerSkia.cpp
index 28248e39fee..8154be49299 100644
--- a/Services/Compositor/DisplayListPlayerSkia.cpp
+++ b/Services/Compositor/DisplayListPlayerSkia.cpp
@@ -364,12 +364,13 @@ void DisplayListPlayerSkia::play_command(DrawCanvas const& command)
void DisplayListPlayerSkia::play_command(DrawVideoFrame const& command)
{
- auto image = raster_cache().image_for_video_sink(resource_storage(), command.video_sink_id, m_skia_backend_context);
+ Gfx::IntSize visible_size;
+ auto image = raster_cache().image_for_video_sink(resource_storage(), command.video_sink_id, m_skia_backend_context, visible_size);
if (!image)
return;
auto dst_rect = to_skia_rect(command.dst_rect);
- SkRect src_rect = SkRect::MakeIWH(image->width(), image->height());
+ SkRect src_rect = SkRect::MakeIWH(min(visible_size.width(), image->width()), min(visible_size.height(), image->height()));
auto& canvas = surface().canvas();
SkPaint paint;
paint.setAntiAlias(true);
diff --git a/Services/Compositor/DisplayListRasterCache.cpp b/Services/Compositor/DisplayListRasterCache.cpp
index e5d7b139a2b..4816ab54587 100644
--- a/Services/Compositor/DisplayListRasterCache.cpp
+++ b/Services/Compositor/DisplayListRasterCache.cpp
@@ -54,14 +54,12 @@ struct DisplayListRasterCache::VideoSinkImage {
Media::VideoFramePoolID pool_id { 0 };
u32 slot_index { 0 };
u64 slot_acquisition_id { 0 };
- // A surface-backed image samples the surface where it lies, so it stays valid for every frame decoded into
- // that surface rather than only for the one acquisition.
- u32 surface_id { 0 };
// Drawing is recorded here but read by the GPU afterwards, so the frame stays held, and its surface's pixels
// with it, until a different frame is drawn in its place.
RefPtr<Media::VideoFrame const> drawn_frame;
RefPtr<Gfx::SkiaBackendContext> skia_backend_context;
sk_sp<SkImage> image;
+ Gfx::IntSize visible_size;
};
struct DisplayListRasterCache::RepeatedTileRaster {
@@ -181,7 +179,7 @@ sk_sp<SkImage> DisplayListRasterCache::image_for_image_frame(DisplayListResource
return image;
}
-sk_sp<SkImage> DisplayListRasterCache::image_for_video_sink(DisplayListResourceStorage const& resource_storage, VideoSinkResourceId id, RefPtr<Gfx::SkiaBackendContext> const& skia_backend_context)
+sk_sp<SkImage> DisplayListRasterCache::image_for_video_sink(DisplayListResourceStorage const& resource_storage, VideoSinkResourceId id, RefPtr<Gfx::SkiaBackendContext> const& skia_backend_context, Gfx::IntSize& visible_size)
{
auto sink = resource_storage.video_sink(id);
if (!sink)
@@ -192,15 +190,12 @@ sk_sp<SkImage> DisplayListRasterCache::image_for_video_sink(DisplayListResourceS
auto handle = Media::VideoFrameHandle::for_frame(*frame);
auto surface = frame->surface();
- auto surface_id = surface ? surface->id() : 0;
auto& cached_image = *m_video_sink_images.ensure(id.value(), [] { return make<VideoSinkImage>(); });
auto cached_image_matches = [&] {
if (!cached_image.image)
return false;
if (cached_image.skia_backend_context != skia_backend_context)
return false;
- if (surface_id != 0)
- return cached_image.surface_id == surface_id;
if (cached_image.pool_id != handle.pool_id)
return false;
if (cached_image.slot_index != handle.slot_index)
@@ -211,6 +206,7 @@ sk_sp<SkImage> DisplayListRasterCache::image_for_video_sink(DisplayListResourceS
}();
if (cached_image_matches) {
cached_image.drawn_frame = frame;
+ visible_size = cached_image.visible_size;
return cached_image.image;
}
@@ -225,10 +221,11 @@ sk_sp<SkImage> DisplayListRasterCache::image_for_video_sink(DisplayListResourceS
cached_image.pool_id = handle.pool_id;
cached_image.slot_index = handle.slot_index;
cached_image.slot_acquisition_id = handle.slot_acquisition_id;
- cached_image.surface_id = surface_id;
cached_image.drawn_frame = frame;
cached_image.skia_backend_context = skia_backend_context;
cached_image.image = image;
+ cached_image.visible_size = frame->size().to_type<int>();
+ visible_size = cached_image.visible_size;
return image;
}
diff --git a/Services/Compositor/DisplayListRasterCache.h b/Services/Compositor/DisplayListRasterCache.h
index 72c6ee04db6..8a1ee0a69b1 100644
--- a/Services/Compositor/DisplayListRasterCache.h
+++ b/Services/Compositor/DisplayListRasterCache.h
@@ -66,7 +66,8 @@ public:
void evict(Compositing::DisplayListResourceSet const& removed_resources);
sk_sp<SkImage> image_for_image_frame(Compositing::DisplayListResourceStorage const&, Compositing::ImageFrameResourceId, RefPtr<Gfx::SkiaBackendContext> const&);
- sk_sp<SkImage> image_for_video_sink(Compositing::DisplayListResourceStorage const&, Compositing::VideoSinkResourceId, RefPtr<Gfx::SkiaBackendContext> const&);
+ // The image can be larger than the frame, whose visible size is the part of it to draw.
+ sk_sp<SkImage> image_for_video_sink(Compositing::DisplayListResourceStorage const&, Compositing::VideoSinkResourceId, RefPtr<Gfx::SkiaBackendContext> const&, Gfx::IntSize& visible_size);
sk_sp<SkImage> repeated_tile_raster(u64 tile_key, Gfx::IntSize, RefPtr<Gfx::SkiaBackendContext> const&) const;
void add_repeated_tile_raster(u64 tile_key, Gfx::IntSize, RefPtr<Gfx::SkiaBackendContext> const&, sk_sp<SkImage>);
sk_sp<SkImage> nested_display_list_raster(Compositing::DisplayListResourceId, RefPtr<Gfx::SkiaBackendContext> const&, Gfx::IntRect visible_rect_in_list_space, Gfx::IntRect& raster_rect_in_list_space);
diff --git a/Services/Compositor/VideoFrameSkia.cpp b/Services/Compositor/VideoFrameSkia.cpp
index 28911e75f21..238453419c7 100644
--- a/Services/Compositor/VideoFrameSkia.cpp
+++ b/Services/Compositor/VideoFrameSkia.cpp
@@ -4,6 +4,7 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <AK/HashMap.h>
#include <Compositor/VideoFrameSkia.h>
#include <LibGfx/Bitmap.h>
#include <LibGfx/ColorSpace.h>
@@ -12,6 +13,7 @@
#include <LibGfx/SkiaUtils.h>
#include <LibGfx/YUVData.h>
#include <LibMediaCodecs/VideoFrame.h>
+#include <LibMediaCodecs/VideoFrameHandle.h>
#include <LibMediaCodecs/VideoSurface.h>
#include <core/SkCanvas.h>
@@ -23,13 +25,19 @@
namespace Compositor {
-#ifndef AK_OS_MACOS
+#if !defined(AK_OS_MACOS) && !defined(USE_VULKAN_DMABUF_IMAGES)
sk_sp<SkImage> sk_image_from_video_surface(Media::VideoSurface const&, Media::CodingIndependentCodePoints, Gfx::SkiaBackendContext&)
{
return nullptr;
}
#endif
+#ifndef USE_VULKAN_DMABUF_IMAGES
+void video_surface_image_will_show_new_frame(SkImage&)
+{
+}
+#endif
+
SkYUVColorSpace skia_yuv_color_space(Media::CodingIndependentCodePoints cicp)
{
bool full_range = cicp.video_full_range_flag() == Media::VideoFullRangeFlag::Full;
@@ -154,6 +162,62 @@ SkYUVAPixmaps make_yuva_pixmaps(Gfx::YUVData const& yuv_data)
return SkYUVAPixmaps::FromExternalPixmaps(yuva_info, plane_pixmaps);
}
+// A surface-backed image samples the surface where it lies, so it stays valid for every frame decoded into that
+// surface. A decoder recycles a bounded set of surfaces, so each one's image is kept for as long as the surface is.
+struct VideoSurfaceImage {
+ AK_ALLOC_WITH_KMALLOC;
+
+ NonnullRefPtr<Media::VideoSurface const> surface;
+ NonnullRefPtr<Gfx::SkiaBackendContext> skia_backend_context;
+ Media::CodingIndependentCodePoints cicp;
+ sk_sp<SkImage> image;
+ Media::VideoFramePoolID shown_pool_id { 0 };
+ u32 shown_slot_index { 0 };
+ u64 shown_slot_acquisition_id { 0 };
+};
+
+static HashMap<u32, NonnullOwnPtr<VideoSurfaceImage>>& video_surface_images()
+{
+ // Leaked so that no image outlives the GPU context at exit.
+ static auto& images = *new HashMap<u32, NonnullOwnPtr<VideoSurfaceImage>>;
+ return images;
+}
+
+static sk_sp<SkImage> image_for_video_surface(Media::VideoFrame const& frame, Media::VideoSurface const& surface, Gfx::SkiaBackendContext& skia_backend_context)
+{
+ auto& images = video_surface_images();
+ auto* cached_image = [&]() -> VideoSurfaceImage* {
+ auto cached = images.get(surface.id());
+ if (!cached.has_value())
+ return nullptr;
+ auto& image = **cached;
+ if (image.surface.ptr() != &surface || image.skia_backend_context.ptr() != &skia_backend_context || image.cicp != frame.cicp())
+ return nullptr;
+ return &image;
+ }();
+
+ if (!cached_image) {
+ // A surface that only this cache still holds will not be handed out again.
+ images.remove_all_matching([](auto, auto const& image) { return image->surface->ref_count() == 1; });
+
+ auto image = sk_image_from_video_surface(surface, frame.cicp(), skia_backend_context);
+ if (!image)
+ return nullptr;
+ auto new_image = make<VideoSurfaceImage>(surface, skia_backend_context, frame.cicp(), move(image));
+ cached_image = new_image.ptr();
+ images.set(surface.id(), move(new_image));
+ }
+
+ auto handle = Media::VideoFrameHandle::for_frame(frame);
+ if (cached_image->shown_pool_id != handle.pool_id || cached_image->shown_slot_index != handle.slot_index || cached_image->shown_slot_acquisition_id != handle.slot_acquisition_id) {
+ video_surface_image_will_show_new_frame(*cached_image->image);
+ cached_image->shown_pool_id = handle.pool_id;
+ cached_image->shown_slot_index = handle.slot_index;
+ cached_image->shown_slot_acquisition_id = handle.slot_acquisition_id;
+ }
+ return cached_image->image;
+}
+
sk_sp<SkImage> sk_image_from_video_frame(Media::VideoFrame const& frame, RefPtr<Gfx::SkiaBackendContext> const& skia_backend_context)
{
sk_sp<SkImage> image;
@@ -161,7 +225,7 @@ sk_sp<SkImage> sk_image_from_video_frame(Media::VideoFrame const& frame, RefPtr<
auto surface = frame.surface();
if (surface != nullptr && skia_backend_context)
- image = sk_image_from_video_surface(*surface, frame.cicp(), *skia_backend_context);
+ image = image_for_video_surface(frame, *surface, *skia_backend_context);
auto yuv_data = image ? Optional<Gfx::YUVData> {} : frame.yuv_data();
if (!image && !yuv_data.has_value() && surface == nullptr)
diff --git a/Services/Compositor/VideoFrameSkia.h b/Services/Compositor/VideoFrameSkia.h
index 400ddf5c189..4be89a549ea 100644
--- a/Services/Compositor/VideoFrameSkia.h
+++ b/Services/Compositor/VideoFrameSkia.h
@@ -32,6 +32,10 @@ SkYUVAPixmaps make_yuva_pixmaps(Gfx::YUVData const&);
// sample its surfaces yet.
sk_sp<SkImage> sk_image_from_video_surface(Media::VideoSurface const&, Media::CodingIndependentCodePoints, Gfx::SkiaBackendContext&);
+// A surface's image stays valid for every frame decoded into the surface, but the decoder hands the surface over afresh
+// with each one, which Skia has to be told before it next samples the image.
+void video_surface_image_will_show_new_frame(SkImage&);
+
// Makes an image of the frame's pixels, on the GPU when there is a backend context, and in memory otherwise.
sk_sp<SkImage> sk_image_from_video_frame(Media::VideoFrame const&, RefPtr<Gfx::SkiaBackendContext> const&);
diff --git a/Services/Compositor/VideoFrameSkiaVulkan.cpp b/Services/Compositor/VideoFrameSkiaVulkan.cpp
new file mode 100644
index 00000000000..cc7b879a5c7
--- /dev/null
+++ b/Services/Compositor/VideoFrameSkiaVulkan.cpp
@@ -0,0 +1,128 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <Compositor/VideoFrameSkia.h>
+#include <LibGfx/ColorSpace.h>
+#include <LibGfx/ImportedYCbCrVulkanImage.h>
+#include <LibGfx/SkiaBackendContext.h>
+#include <LibGfx/SkiaUtils.h>
+#include <LibMediaCodecs/VideoSurface.h>
+
+#include <core/SkColorSpace.h>
+#include <core/SkImage.h>
+#include <gpu/MutableTextureState.h>
+#include <gpu/ganesh/GrBackendSurface.h>
+#include <gpu/ganesh/GrDirectContext.h>
+#include <gpu/ganesh/SkImageGanesh.h>
+#include <gpu/ganesh/vk/GrVkBackendSurface.h>
+#include <gpu/ganesh/vk/GrVkTypes.h>
+#include <gpu/vk/VulkanMutableTextureState.h>
+
+namespace Compositor {
+
+// The decoder hands each frame over in the general layout, released to whichever device takes the image next.
+static constexpr VkImageLayout HANDED_OVER_LAYOUT = VK_IMAGE_LAYOUT_GENERAL;
+static constexpr u32 HANDED_OVER_QUEUE_FAMILY = VK_QUEUE_FAMILY_EXTERNAL;
+
+static VkSamplerYcbcrModelConversion ycbcr_model_for(Media::CodingIndependentCodePoints cicp)
+{
+ switch (cicp.matrix_coefficients()) {
+ case Media::MatrixCoefficients::BT470BG:
+ case Media::MatrixCoefficients::BT601:
+ return VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_601;
+ case Media::MatrixCoefficients::BT2020NonConstantLuminance:
+ case Media::MatrixCoefficients::BT2020ConstantLuminance:
+ return VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_2020;
+ case Media::MatrixCoefficients::Identity:
+ return VK_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY;
+ default:
+ return VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_709;
+ }
+}
+
+// 4:2:0 video sites its chroma level with the first luma sample of each pair and between the two rows, where the
+// format can sample it there.
+static VkChromaLocation chroma_location(VkFormatFeatureFlags format_features, bool cosited)
+{
+ if (cosited && (format_features & VK_FORMAT_FEATURE_COSITED_CHROMA_SAMPLES_BIT) != 0)
+ return VK_CHROMA_LOCATION_COSITED_EVEN;
+ if ((format_features & VK_FORMAT_FEATURE_MIDPOINT_CHROMA_SAMPLES_BIT) != 0)
+ return VK_CHROMA_LOCATION_MIDPOINT;
+ return VK_CHROMA_LOCATION_COSITED_EVEN;
+}
+
+sk_sp<SkImage> sk_image_from_video_surface(Media::VideoSurface const& surface, Media::CodingIndependentCodePoints cicp, Gfx::SkiaBackendContext& skia_backend_context)
+{
+ auto* gr_context = skia_backend_context.sk_context();
+ if (!gr_context)
+ return nullptr;
+ auto const& vulkan_context = skia_backend_context.vulkan_context();
+ if (!vulkan_context.can_sample_through_ycbcr_conversion)
+ return nullptr;
+
+ auto imported_or_error = Gfx::ImportedYCbCrVulkanImage::import_dma_buf(vulkan_context, surface.dma_buf());
+ if (imported_or_error.is_error()) {
+ dbgln("Could not import a video surface: {}", imported_or_error.error());
+ return nullptr;
+ }
+ auto imported = imported_or_error.release_value();
+
+ auto format_features = imported->format_features();
+ auto chroma_filter = VK_FILTER_NEAREST;
+ if ((format_features & VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_LINEAR_FILTER_BIT) != 0)
+ chroma_filter = VK_FILTER_LINEAR;
+ auto range = VK_SAMPLER_YCBCR_RANGE_ITU_NARROW;
+ if (cicp.video_full_range_flag() == Media::VideoFullRangeFlag::Full)
+ range = VK_SAMPLER_YCBCR_RANGE_ITU_FULL;
+ skgpu::VulkanYcbcrConversionInfo ycbcr_info {
+ imported->format(),
+ ycbcr_model_for(cicp),
+ range,
+ chroma_location(format_features, true),
+ chroma_location(format_features, false),
+ chroma_filter,
+ VK_FALSE,
+ {},
+ format_features,
+ };
+
+ // The image is only borrowed, so its memory is named for Skia's bookkeeping and never freed by it.
+ auto const& memory = imported->memories().first();
+ GrVkImageInfo image_info;
+ image_info.fImage = imported->image();
+ image_info.fAlloc.fMemory = memory.memory;
+ image_info.fAlloc.fSize = memory.size;
+ image_info.fImageTiling = VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT;
+ image_info.fImageLayout = HANDED_OVER_LAYOUT;
+ image_info.fFormat = imported->format();
+ image_info.fImageUsageFlags = Gfx::ImportedYCbCrVulkanImage::USAGE;
+ image_info.fLevelCount = 1;
+ image_info.fCurrentQueueFamily = HANDED_OVER_QUEUE_FAMILY;
+ image_info.fYcbcrConversionInfo = ycbcr_info;
+
+ auto color_space = Gfx::ColorSpace {};
+ if (auto color_space_result = Gfx::ColorSpace::from_cicp(cicp); !color_space_result.is_error())
+ color_space = color_space_result.release_value();
+
+ auto size = surface.dma_buf().size;
+ auto backend_texture = GrBackendTextures::MakeVk(size.width(), size.height(), image_info);
+ auto release_image = [](void* context) { delete static_cast<Gfx::ImportedYCbCrVulkanImage*>(context); };
+ // Skia only wraps each YCbCr format as the color type with the same sample depth.
+ auto color_type = kRGB_888x_SkColorType;
+ if (imported->format() == VK_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16)
+ color_type = kRGBA_1010102_SkColorType;
+ return SkImages::BorrowTextureFrom(gr_context, backend_texture, kTopLeft_GrSurfaceOrigin, color_type, kOpaque_SkAlphaType, Gfx::to_skia_color_space(color_space), release_image, imported.leak_ptr());
+}
+
+void video_surface_image_will_show_new_frame(SkImage& image)
+{
+ GrBackendTexture backend_texture;
+ if (!SkImages::GetBackendTextureFromImage(&image, &backend_texture, false))
+ return;
+ backend_texture.setMutableState(skgpu::MutableTextureStates::MakeVulkan(HANDED_OVER_LAYOUT, HANDED_OVER_QUEUE_FAMILY));
+}
+
+}