Truly independent web browser
Compositor+VideoDecoderServer+More: Share the GPU for video decoding
Zaggy10241cf2a231c546
diff --git a/Libraries/LibMediaCodecs/CMakeLists.txt b/Libraries/LibMediaCodecs/CMakeLists.txtindex b3770ba2729..a1736a76d8c 100644--- a/Libraries/LibMediaCodecs/CMakeLists.txt+++ b/Libraries/LibMediaCodecs/CMakeLists.txt@@ -31,6 +31,10 @@ if (APPLE)list(APPEND SOURCES VideoToolbox/VideoToolboxVideoDecoder.mm)endif()+if (USE_VULKAN_DMABUF_IMAGES)+ list(APPEND SOURCES Vulkan/VulkanVideoDevice.cpp)+endif()+set(GENERATED_SOURCESVideoDecoderClientEndpoint.hVideoDecoderServerEndpoint.h@@ -62,3 +66,7 @@ endif()if (APPLE)target_link_libraries(LibMediaCodecs PRIVATE "-framework VideoToolbox" "-framework CoreMedia" "-framework CoreVideo")endif()++if (USE_VULKAN_DMABUF_IMAGES)+ target_link_libraries(LibMediaCodecs PRIVATE Vulkan::Vulkan)+endif()diff --git a/Libraries/LibMediaCodecs/Vulkan/VulkanVideoDevice.cpp b/Libraries/LibMediaCodecs/Vulkan/VulkanVideoDevice.cppnew file mode 100644index 00000000000..1512f3fc489--- /dev/null+++ b/Libraries/LibMediaCodecs/Vulkan/VulkanVideoDevice.cpp@@ -0,0 +1,304 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/Array.h>+#include <AK/NeverDestroyed.h>+#include <AK/OwnPtr.h>+#include <LibGfx/ImportedYCbCrVulkanImage.h>+#include <LibGfx/VulkanContext.h>+#include <LibMediaCodecs/Vulkan/VulkanVideoDevice.h>++namespace Media {++namespace {++constexpr Array required_extensions {+ VK_KHR_VIDEO_QUEUE_EXTENSION_NAME,+ VK_KHR_VIDEO_DECODE_QUEUE_EXTENSION_NAME,+ VK_KHR_EXTERNAL_MEMORY_FD_EXTENSION_NAME,+ VK_EXT_EXTERNAL_MEMORY_DMA_BUF_EXTENSION_NAME,+ VK_EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION_NAME,+};++constexpr Array optional_extensions {+ VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME,+ VK_KHR_VIDEO_DECODE_VP9_EXTENSION_NAME,+ VK_KHR_VIDEO_DECODE_AV1_EXTENSION_NAME,+ VK_KHR_VIDEO_MAINTENANCE_1_EXTENSION_NAME,+ VK_KHR_VIDEO_MAINTENANCE_2_EXTENSION_NAME,+};++NeverDestroyed<OwnPtr<VulkanVideoDevice>> s_process_device;++Vector<VkExtensionProperties> device_extensions_of(VkPhysicalDevice physical_device)+{+ u32 count = 0;+ vkEnumerateDeviceExtensionProperties(physical_device, nullptr, &count, nullptr);+ Vector<VkExtensionProperties> extensions;+ extensions.resize(count);+ vkEnumerateDeviceExtensionProperties(physical_device, nullptr, &count, extensions.data());+ return extensions;+}++bool contains_extension(ReadonlySpan<VkExtensionProperties> extensions, StringView name)+{+ return any_of(extensions, [&](auto const& extension) { return StringView { extension.extensionName, strlen(extension.extensionName) } == name; });+}++Vector<VkQueueFamilyProperties> queue_families_of(VkPhysicalDevice physical_device)+{+ u32 count = 0;+ vkGetPhysicalDeviceQueueFamilyProperties(physical_device, &count, nullptr);+ Vector<VkQueueFamilyProperties> families;+ families.resize(count);+ vkGetPhysicalDeviceQueueFamilyProperties(physical_device, &count, families.data());+ return families;+}++Optional<u32> first_queue_family_with(ReadonlySpan<VkQueueFamilyProperties> families, VkQueueFlags flags)+{+ for (u32 index = 0; index < families.size(); index++) {+ if ((families[index].queueFlags & flags) == flags && families[index].queueCount > 0)+ return index;+ }+ return {};+}++bool can_decode_video(VkPhysicalDevice physical_device)+{+ VkPhysicalDeviceProperties properties;+ vkGetPhysicalDeviceProperties(physical_device, &properties);+ if (properties.apiVersion < VK_API_VERSION_1_3)+ return false;+ auto extensions = device_extensions_of(physical_device);+ if (!all_of(required_extensions, [&](auto name) { return contains_extension(extensions, { name, strlen(name) }); }))+ return false;+ return first_queue_family_with(queue_families_of(physical_device), VK_QUEUE_VIDEO_DECODE_BIT_KHR).has_value();+}++}++ErrorOr<void> VulkanVideoDevice::create_for_process(Gfx::GpuDeviceIdentity const& identity)+{+ VERIFY(!*s_process_device);+ *s_process_device = TRY(create(identity));+ return {};+}++VulkanVideoDevice* VulkanVideoDevice::the()+{+ return s_process_device->ptr();+}++ErrorOr<NonnullOwnPtr<VulkanVideoDevice>> VulkanVideoDevice::create(Gfx::GpuDeviceIdentity const& identity)+{+ auto device = adopt_own(*new VulkanVideoDevice);+ device->m_api_version = VK_API_VERSION_1_3;++ VkApplicationInfo application_info {};+ application_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;+ application_info.pApplicationName = "Ladybird";+ application_info.apiVersion = device->m_api_version;++ VkInstanceCreateInfo instance_info {};+ instance_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;+ instance_info.pApplicationInfo = &application_info;+ if (vkCreateInstance(&instance_info, nullptr, &device->m_instance) != VK_SUCCESS)+ return Error::from_string_literal("Could not create a Vulkan instance");++ u32 physical_device_count = 0;+ vkEnumeratePhysicalDevices(device->m_instance, &physical_device_count, nullptr);+ Vector<VkPhysicalDevice> physical_devices;+ physical_devices.resize(physical_device_count);+ vkEnumeratePhysicalDevices(device->m_instance, &physical_device_count, physical_devices.data());++ for (auto* physical_device : physical_devices) {+ if (Gfx::gpu_device_identity_of(physical_device) == identity) {+ device->m_physical_device = physical_device;+ break;+ }+ }+ if (device->m_physical_device == VK_NULL_HANDLE)+ return Error::from_string_literal("The named GPU is not a Vulkan device here");+ if (!can_decode_video(device->m_physical_device))+ return Error::from_string_literal("The named GPU cannot decode video into images that export as dma-bufs");++ auto available_extensions = device_extensions_of(device->m_physical_device);+ for (auto const* name : required_extensions)+ device->m_enabled_extensions.append(name);++ VkPhysicalDeviceVideoMaintenance2FeaturesKHR supported_video_maintenance2 {};+ supported_video_maintenance2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VIDEO_MAINTENANCE_2_FEATURES_KHR;+ VkPhysicalDeviceVideoMaintenance1FeaturesKHR supported_video_maintenance1 {};+ supported_video_maintenance1.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VIDEO_MAINTENANCE_1_FEATURES_KHR;+ supported_video_maintenance1.pNext = &supported_video_maintenance2;+ VkPhysicalDeviceVulkan13Features supported_vulkan13 {};+ supported_vulkan13.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES;+ supported_vulkan13.pNext = &supported_video_maintenance1;+ VkPhysicalDeviceVulkan12Features supported_vulkan12 {};+ supported_vulkan12.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;+ supported_vulkan12.pNext = &supported_vulkan13;+ VkPhysicalDeviceFeatures2 supported_features {};+ supported_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;+ supported_features.pNext = &supported_vulkan12;+ vkGetPhysicalDeviceFeatures2(device->m_physical_device, &supported_features);++ // FFmpeg submits with synchronization2 and tracks its frames with timeline semaphores, without checking for either.+ if (!supported_vulkan12.timelineSemaphore || !supported_vulkan13.synchronization2)+ return Error::from_string_literal("The Vulkan device lacks timeline semaphores or synchronization2");++ device->m_vulkan13_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES;+ device->m_vulkan13_features.synchronization2 = VK_TRUE;+ device->m_vulkan12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;+ device->m_vulkan12_features.timelineSemaphore = VK_TRUE;+ device->m_vulkan12_features.pNext = &device->m_vulkan13_features;+ device->m_vulkan11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;+ device->m_vulkan11_features.pNext = &device->m_vulkan12_features;+ device->m_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;+ device->m_features.pNext = &device->m_vulkan11_features;+ void** feature_chain_end = &device->m_vulkan13_features.pNext;++ // FFmpeg also trusts the extension's name alone, so an extension whose feature is missing stays disabled.+ for (auto const* name : optional_extensions) {+ StringView name_view { name, strlen(name) };+ if (!contains_extension(available_extensions, name_view))+ continue;+ if (name_view == VK_KHR_VIDEO_MAINTENANCE_1_EXTENSION_NAME ""sv) {+ if (!supported_video_maintenance1.videoMaintenance1)+ continue;+ device->m_video_maintenance1_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VIDEO_MAINTENANCE_1_FEATURES_KHR;+ device->m_video_maintenance1_features.videoMaintenance1 = VK_TRUE;+ *feature_chain_end = &device->m_video_maintenance1_features;+ feature_chain_end = &device->m_video_maintenance1_features.pNext;+ } else if (name_view == VK_KHR_VIDEO_MAINTENANCE_2_EXTENSION_NAME ""sv) {+ if (!supported_video_maintenance2.videoMaintenance2)+ continue;+ device->m_video_maintenance2_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VIDEO_MAINTENANCE_2_FEATURES_KHR;+ device->m_video_maintenance2_features.videoMaintenance2 = VK_TRUE;+ *feature_chain_end = &device->m_video_maintenance2_features;+ feature_chain_end = &device->m_video_maintenance2_features.pNext;+ }+ device->m_enabled_extensions.append(name);+ }++ // FFmpeg needs a family for compute and one for transfers alongside the decoding one.+ auto queue_families = queue_families_of(device->m_physical_device);+ auto decode_family = first_queue_family_with(queue_families, VK_QUEUE_VIDEO_DECODE_BIT_KHR);+ auto compute_family = first_queue_family_with(queue_families, VK_QUEUE_COMPUTE_BIT);+ auto transfer_family = first_queue_family_with(queue_families, VK_QUEUE_TRANSFER_BIT);+ if (!decode_family.has_value() || !compute_family.has_value() || !transfer_family.has_value())+ return Error::from_string_literal("The Vulkan device lacks a decode, compute or transfer queue");++ Vector<VkDeviceQueueCreateInfo> queue_infos;+ float const queue_priority = 1.0f;+ for (auto family : { *decode_family, *compute_family, *transfer_family }) {+ if (any_of(device->m_queue_families, [&](auto const& existing) { return existing.index == family; }))+ continue;+ device->m_queue_families.append({ family, queue_families[family].queueFlags });+ VkDeviceQueueCreateInfo queue_info {};+ queue_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;+ queue_info.queueFamilyIndex = family;+ queue_info.queueCount = 1;+ queue_info.pQueuePriorities = &queue_priority;+ queue_infos.append(queue_info);+ }++ VkDeviceCreateInfo device_info {};+ device_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;+ device_info.pNext = &device->m_features;+ device_info.queueCreateInfoCount = queue_infos.size();+ device_info.pQueueCreateInfos = queue_infos.data();+ device_info.enabledExtensionCount = device->m_enabled_extensions.size();+ device_info.ppEnabledExtensionNames = device->m_enabled_extensions.data();+ if (vkCreateDevice(device->m_physical_device, &device_info, nullptr, &device->m_logical_device) != VK_SUCCESS)+ return Error::from_string_literal("Could not create a Vulkan device for decoding video");++ device->m_get_physical_device_video_capabilities = reinterpret_cast<PFN_vkGetPhysicalDeviceVideoCapabilitiesKHR>(vkGetInstanceProcAddr(device->m_instance, "vkGetPhysicalDeviceVideoCapabilitiesKHR"));+ if (device->m_get_physical_device_video_capabilities == nullptr)+ return Error::from_string_literal("vkGetPhysicalDeviceVideoCapabilitiesKHR is unavailable");++ return device;+}++VulkanVideoDevice::~VulkanVideoDevice()+{+ if (m_logical_device != VK_NULL_HANDLE)+ vkDestroyDevice(m_logical_device, nullptr);+ if (m_instance != VK_NULL_HANDLE)+ vkDestroyInstance(m_instance, nullptr);+}++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)+ return Error::from_string_literal("The Vulkan device cannot decode this video profile");+ return {};+}++Vector<u64> VulkanVideoDevice::exportable_drm_format_modifiers(VkFormat format, VkImageUsageFlags usage, VkImageCreateFlags flags, void const* video_profile_list) const+{+ VkDrmFormatModifierPropertiesListEXT modifier_list {};+ modifier_list.sType = VK_STRUCTURE_TYPE_DRM_FORMAT_MODIFIER_PROPERTIES_LIST_EXT;+ VkFormatProperties2 format_properties {};+ format_properties.sType = VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2;+ format_properties.pNext = &modifier_list;+ vkGetPhysicalDeviceFormatProperties2(m_physical_device, format, &format_properties);++ Vector<VkDrmFormatModifierPropertiesEXT> modifier_properties;+ modifier_properties.resize(modifier_list.drmFormatModifierCount);+ modifier_list.pDrmFormatModifierProperties = modifier_properties.data();+ vkGetPhysicalDeviceFormatProperties2(m_physical_device, format, &format_properties);++ Vector<u32> queue_family_indices;+ for (auto const& family : m_queue_families)+ queue_family_indices.append(family.index);++ Vector<u64> modifiers;+ for (auto const& properties : modifier_properties) {+ // The Compositor runs on the same device and driver, so it sees the same features under each modifier.+ auto required_features = Gfx::ImportedYCbCrVulkanImage::REQUIRED_FORMAT_FEATURES;+ if ((properties.drmFormatModifierTilingFeatures & required_features) != required_features)+ continue;++ VkPhysicalDeviceImageDrmFormatModifierInfoEXT modifier_info {};+ modifier_info.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_DRM_FORMAT_MODIFIER_INFO_EXT;+ modifier_info.pNext = video_profile_list;+ modifier_info.drmFormatModifier = properties.drmFormatModifier;+ if (queue_family_indices.size() > 1) {+ modifier_info.sharingMode = VK_SHARING_MODE_CONCURRENT;+ modifier_info.queueFamilyIndexCount = queue_family_indices.size();+ modifier_info.pQueueFamilyIndices = queue_family_indices.data();+ }++ VkPhysicalDeviceExternalImageFormatInfo external_info {};+ external_info.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO;+ external_info.pNext = &modifier_info;+ external_info.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;++ VkPhysicalDeviceImageFormatInfo2 image_info {};+ image_info.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2;+ image_info.pNext = &external_info;+ image_info.format = format;+ image_info.type = VK_IMAGE_TYPE_2D;+ image_info.tiling = VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT;+ image_info.usage = usage;+ image_info.flags = flags;++ VkExternalImageFormatProperties external_properties {};+ external_properties.sType = VK_STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES;+ VkImageFormatProperties2 image_properties {};+ image_properties.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2;+ image_properties.pNext = &external_properties;+ if (vkGetPhysicalDeviceImageFormatProperties2(m_physical_device, &image_info, &image_properties) != VK_SUCCESS)+ continue;+ if ((external_properties.externalMemoryProperties.externalMemoryFeatures & VK_EXTERNAL_MEMORY_FEATURE_EXPORTABLE_BIT) == 0)+ continue;+ modifiers.append(properties.drmFormatModifier);+ }+ return modifiers;+}++}diff --git a/Libraries/LibMediaCodecs/Vulkan/VulkanVideoDevice.h b/Libraries/LibMediaCodecs/Vulkan/VulkanVideoDevice.hnew file mode 100644index 00000000000..4f438411f38--- /dev/null+++ b/Libraries/LibMediaCodecs/Vulkan/VulkanVideoDevice.h@@ -0,0 +1,80 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#ifdef USE_VULKAN_DMABUF_IMAGES++# include <AK/Error.h>+# include <AK/NonnullOwnPtr.h>+# include <AK/Vector.h>+# include <LibGfx/GpuDeviceIdentity.h>+# include <LibMediaCodecs/Export.h>+# include <vulkan/vulkan.h>++namespace Media {++// A Vulkan device for decoding video into images that export as dma-bufs. One serves every decoder in a process, and+// outlives every frame decoded on it.+class MEDIACODECS_API VulkanVideoDevice {+ AK_MAKE_NONCOPYABLE(VulkanVideoDevice);+ AK_MAKE_NONMOVABLE(VulkanVideoDevice);++public:+ AK_ALLOC_WITH_KMALLOC;++ struct QueueFamily {+ u32 index { 0 };+ VkQueueFlags flags { 0 };+ };++ // Decoding happens on the GPU that will display the frames, so it is named by the process that displays them. The+ // device is created before the process starts any other threads, and is never destroyed.+ static ErrorOr<void> create_for_process(Gfx::GpuDeviceIdentity const&);+ static VulkanVideoDevice* the();++ ~VulkanVideoDevice();++ VkInstance instance() const { return m_instance; }+ VkPhysicalDevice physical_device() const { return m_physical_device; }+ VkDevice logical_device() const { return m_logical_device; }+ u32 api_version() const { return m_api_version; }+ 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; }++ // 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;++ // The DRM format modifiers that images of the format can be created and exported under, among those that the+ // Compositor can import images with.+ Vector<u64> exportable_drm_format_modifiers(VkFormat, VkImageUsageFlags, VkImageCreateFlags, void const* video_profile_list) const;++private:+ VulkanVideoDevice() = default;++ static ErrorOr<NonnullOwnPtr<VulkanVideoDevice>> create(Gfx::GpuDeviceIdentity const&);++ u32 m_api_version { 0 };+ VkInstance m_instance { VK_NULL_HANDLE };+ VkPhysicalDevice m_physical_device { VK_NULL_HANDLE };+ VkDevice m_logical_device { VK_NULL_HANDLE };+ Vector<QueueFamily> m_queue_families;+ Vector<char const*> m_enabled_extensions;++ VkPhysicalDeviceFeatures2 m_features {};+ VkPhysicalDeviceVulkan11Features m_vulkan11_features {};+ VkPhysicalDeviceVulkan12Features m_vulkan12_features {};+ VkPhysicalDeviceVulkan13Features m_vulkan13_features {};+ VkPhysicalDeviceVideoMaintenance1FeaturesKHR m_video_maintenance1_features {};+ VkPhysicalDeviceVideoMaintenance2FeaturesKHR m_video_maintenance2_features {};++ PFN_vkGetPhysicalDeviceVideoCapabilitiesKHR m_get_physical_device_video_capabilities { nullptr };+};++}++#endifdiff --git a/Libraries/LibWebView/Application.cpp b/Libraries/LibWebView/Application.cppindex 3c1fd8aa461..b7692fae174 100644--- a/Libraries/LibWebView/Application.cpp+++ b/Libraries/LibWebView/Application.cpp@@ -1770,6 +1770,9 @@ ErrorOr<void> Application::launch_compositor_process()m_compositor_client->on_death = [this]() {handle_compositor_process_death();};+ m_compositor_client->on_gpu_device_identity_reported = [this](Optional<Gfx::GpuDeviceIdentity> identity) {+ compositor_reported_gpu_device_identity(move(identity));+ };if (!platform_reports_scroll_momentum())m_compositor_client->async_set_synthesizes_scroll_momentum(true);@@ -1785,6 +1788,29 @@ ErrorOr<void> Application::launch_compositor_process()return {};}+void Application::compositor_reported_gpu_device_identity(Optional<Gfx::GpuDeviceIdentity> identity)+{+ auto previous_identity = exchange(m_compositor_gpu_device_identity, identity);++ // Frames decoded on another GPU cannot be displayed by this Compositor, so decoding starts over on its own. Each+ // MediaServer relaunches its server when it next asks for one.+ if (previous_identity.has_value() && *previous_identity != identity)+ shut_down_video_decoder_servers();++ auto callbacks = move(m_callbacks_awaiting_compositor_gpu_device_identity);+ for (auto& callback : callbacks)+ callback(identity);+}++void Application::when_compositor_gpu_device_identity_is_known(CompositorGpuDeviceIdentityCallback callback)+{+ if (m_compositor_gpu_device_identity.has_value()) {+ callback(*m_compositor_gpu_device_identity);+ return;+ }+ m_callbacks_awaiting_compositor_gpu_device_identity.append(move(callback));+}+void Application::notify_compositor_gpu_presentation_unavailable(){if (m_reported_compositor_gpu_presentation_unavailable)diff --git a/Libraries/LibWebView/Application.h b/Libraries/LibWebView/Application.hindex 4200d6e3ed0..463906cde96 100644--- a/Libraries/LibWebView/Application.h+++ b/Libraries/LibWebView/Application.h@@ -24,6 +24,7 @@#include <LibDatabase/Forward.h>#include <LibDevTools/DevToolsDelegate.h>#include <LibDevTools/Forward.h>+#include <LibGfx/GpuDeviceIdentity.h>#include <LibGfx/Point.h>#include <LibGfx/Size.h>#include <LibIPC/Forward.h>@@ -399,6 +400,11 @@ public:// CPU-shared backing stores.void notify_compositor_gpu_presentation_unavailable();+ // Runs the callback with the GPU that hardware decoders must output to for the Compositor to display their frames,+ // if there is one, as soon as the Compositor has reported it.+ using CompositorGpuDeviceIdentityCallback = Function<void(Optional<Gfx::GpuDeviceIdentity> const&)>;+ void when_compositor_gpu_device_identity_is_known(CompositorGpuDeviceIdentityCallback);+protected:explicit Application(Optional<ByteString> ladybird_binary_path = {});@@ -438,6 +444,7 @@ private:ErrorOr<void> launch_services();void launch_spare_web_content_process();ErrorOr<void> launch_compositor_process();+ void compositor_reported_gpu_device_identity(Optional<Gfx::GpuDeviceIdentity>);void handle_compositor_process_death();void recover_compositor_process();void crash_compositor_process();@@ -619,6 +626,9 @@ private:#endifRefPtr<CompositorClient> m_compositor_client;bool m_reported_compositor_gpu_presentation_unavailable { false };+ // The last identity a Compositor reported, which outlives that Compositor until its replacement reports.+ Optional<Optional<Gfx::GpuDeviceIdentity>> m_compositor_gpu_device_identity;+ Vector<CompositorGpuDeviceIdentityCallback> m_callbacks_awaiting_compositor_gpu_device_identity;size_t m_compositor_restart_count { 0 };enum class CompositorRecoveryState {Idle,diff --git a/Libraries/LibWebView/CompositorClient.cpp b/Libraries/LibWebView/CompositorClient.cppindex 2eb170af0d5..a1c1e3c59a5 100644--- a/Libraries/LibWebView/CompositorClient.cpp+++ b/Libraries/LibWebView/CompositorClient.cpp@@ -27,6 +27,12 @@ void CompositorClient::die()}}+void CompositorClient::gpu_device_identity_reported(Optional<Gfx::GpuDeviceIdentity> identity)+{+ if (on_gpu_device_identity_reported)+ on_gpu_device_identity_reported(move(identity));+}+void CompositorClient::did_allocate_backing_stores(Web::CompositorContextId context_id, Vector<i32> bitmap_ids, Vector<Gfx::SharedImage> backing_stores){auto web_content_client = WebContentClient::client_for_compositor_context_id(context_id);diff --git a/Libraries/LibWebView/CompositorClient.h b/Libraries/LibWebView/CompositorClient.hindex 9d41da15e8a..3c6d25b4ccb 100644--- a/Libraries/LibWebView/CompositorClient.h+++ b/Libraries/LibWebView/CompositorClient.h@@ -10,6 +10,7 @@#include <Compositor/CompositorControlClientEndpoint.h>#include <Compositor/CompositorControlServerEndpoint.h>#include <LibCompositing/Types.h>+#include <LibGfx/GpuDeviceIdentity.h>#include <LibGfx/Rect.h>#include <LibGfx/SharedImage.h>#include <LibIPC/ConnectionToServer.h>@@ -26,10 +27,12 @@ public:explicit CompositorClient(NonnullOwnPtr<IPC::Transport>);Function<void()> on_death;+ Function<void(Optional<Gfx::GpuDeviceIdentity>)> on_gpu_device_identity_reported;private:virtual void die() override;+ virtual void gpu_device_identity_reported(Optional<Gfx::GpuDeviceIdentity>) override;virtual void did_allocate_backing_stores(Web::CompositorContextId, Vector<i32> bitmap_ids, Vector<Gfx::SharedImage> backing_stores) override;virtual void did_add_backing_stores(Web::CompositorContextId, Vector<i32> bitmap_ids, Vector<Gfx::SharedImage> backing_stores) override;virtual void did_retire_backing_stores(Web::CompositorContextId, Vector<i32> bitmap_ids) override;diff --git a/Libraries/LibWebView/HelperProcess.cpp b/Libraries/LibWebView/HelperProcess.cppindex 4d1e62f5d66..455c47c2a14 100644--- a/Libraries/LibWebView/HelperProcess.cpp+++ b/Libraries/LibWebView/HelperProcess.cpp@@ -5,6 +5,7 @@*/#include <AK/Enumerate.h>+#include <AK/NeverDestroyed.h>#include <AK/ScopeGuard.h>#include <LibCore/ElapsedTimer.h>#include <LibCore/File.h>@@ -462,7 +463,9 @@ ErrorOr<NonnullRefPtr<MediaClient::Client>> launch_media_server_process()return launch_server_process<MediaClient::Client>("MediaServer"sv, arguments);}-ErrorOr<NonnullRefPtr<VideoDecoderServerControlClient>> launch_video_decoder_server_process()+static NeverDestroyed<Vector<WeakPtr<VideoDecoderServerControlClient>>> s_video_decoder_servers;++ErrorOr<NonnullRefPtr<VideoDecoderServerControlClient>> launch_video_decoder_server_process(Optional<Gfx::GpuDeviceIdentity> const& gpu_device_identity){auto const& browser_options = WebView::Application::browser_options();@@ -471,12 +474,28 @@ ErrorOr<NonnullRefPtr<VideoDecoderServerControlClient>> launch_video_decoder_serarguments.append("--disable-sandbox"sv);if (browser_options.force_video_decoder_server == ForceVideoDecoderServer::Yes)arguments.append("--host-software-decoders"sv);+ if (gpu_device_identity.has_value()) {+ arguments.append("--gpu-device"sv);+ arguments.append(gpu_device_identity->to_byte_string());+ }if (auto server = mach_server_name(); server.has_value()) {arguments.append("--mach-server-name"sv);arguments.append(server.value());}- return launch_server_process<VideoDecoderServerControlClient>("VideoDecoderServer"sv, arguments);+ auto server = TRY(launch_server_process<VideoDecoderServerControlClient>("VideoDecoderServer"sv, arguments));+ s_video_decoder_servers->remove_all_matching([](auto const& weak_server) { return !weak_server; });+ s_video_decoder_servers->append(server->make_weak_ptr<VideoDecoderServerControlClient>());+ return server;+}++void shut_down_video_decoder_servers()+{+ for (auto& weak_server : *s_video_decoder_servers) {+ if (weak_server)+ weak_server->shutdown();+ }+ s_video_decoder_servers->clear();}#if defined(HAVE_WASM_COMPILER_SERVICE)@@ -672,10 +691,18 @@ ErrorOr<IPC::TransportHandle> connect_new_audio_server_client(RefPtr<AudioServerreturn response->take_handle().release_value();}-static ErrorOr<IPC::TransportHandle> connect_new_video_decoder_server_client(RefPtr<VideoDecoderServerControlClient>& controller)+namespace {++struct VideoDecoderServerHolder : public RefCounted<VideoDecoderServerHolder> {+ RefPtr<VideoDecoderServerControlClient> controller;+};++}++static ErrorOr<IPC::TransportHandle> connect_new_video_decoder_server_client(RefPtr<VideoDecoderServerControlClient>& controller, Optional<Gfx::GpuDeviceIdentity> const& gpu_device_identity){if (!controller || !controller->is_open())- controller = TRY(launch_video_decoder_server_process());+ controller = TRY(launch_video_decoder_server_process(gpu_device_identity));auto response = controller->send_sync_but_allow_failure<Messages::VideoDecoderServerControl::ConnectNewClient>();if (!response || !response->handle().has_value())@@ -688,9 +715,12 @@ ErrorOr<MediaServerClientConnection> connect_new_media_server_client(RefPtr<Mediif (!controller || !controller->is_open()) {controller = TRY(launch_media_server_process());controller->on_request_audio_server_connection = move(connect_audio_server);- // Each MediaServer has a VideoDecoderServer of its own, which lives as long as the controller holding it.- controller->on_request_video_decoder_server_connection = [video_decoder_server = RefPtr<VideoDecoderServerControlClient> {}](auto answer) mutable {- answer(connect_new_video_decoder_server_client(video_decoder_server));+ // Each MediaServer has a VideoDecoderServer of its own, which lives as long as the controller holding it. The+ // server is launched once the Compositor has named the GPU that hardware decoders must output to.+ controller->on_request_video_decoder_server_connection = [video_decoder_server = make_ref_counted<VideoDecoderServerHolder>()](auto answer) {+ Application::the().when_compositor_gpu_device_identity_is_known([video_decoder_server, answer = move(answer)](auto const& gpu_device_identity) {+ answer(connect_new_video_decoder_server_client(video_decoder_server->controller, gpu_device_identity));+ });};}diff --git a/Libraries/LibWebView/HelperProcess.h b/Libraries/LibWebView/HelperProcess.hindex 35667aa553a..92933390cb7 100644--- a/Libraries/LibWebView/HelperProcess.h+++ b/Libraries/LibWebView/HelperProcess.h@@ -8,6 +8,7 @@#include <AK/Error.h>#include <AK/Optional.h>+#include <LibGfx/GpuDeviceIdentity.h>#include <LibIPC/TransportHandle.h>#include <LibMediaClient/Client.h>#include <LibRequests/RequestClient.h>@@ -30,7 +31,8 @@ WEBVIEW_API ErrorOr<NonnullRefPtr<WebView::WebContentClient>> launch_web_contentWEBVIEW_API ErrorOr<NonnullRefPtr<MediaClient::Client>> launch_media_server_process();WEBVIEW_API ErrorOr<NonnullRefPtr<AudioServerControlClient>> launch_audio_server_process();-WEBVIEW_API ErrorOr<NonnullRefPtr<VideoDecoderServerControlClient>> launch_video_decoder_server_process();+WEBVIEW_API ErrorOr<NonnullRefPtr<VideoDecoderServerControlClient>> launch_video_decoder_server_process(Optional<Gfx::GpuDeviceIdentity> const&);+WEBVIEW_API void shut_down_video_decoder_servers();WEBVIEW_API ErrorOr<NonnullRefPtr<WebView::CompositorClient>> launch_compositor_process();WEBVIEW_API ErrorOr<NonnullRefPtr<WebView::WebWorkerClient>> launch_web_worker_process(Web::HTML::AgentType, IsPrivate, Web::HTML::WorkerAgentId);WEBVIEW_API ErrorOr<NonnullRefPtr<Requests::RequestControlClient>> launch_request_server_process(ByteString const& cache_path, Optional<Utf16String> const& site, HTTPDiskCacheMode);diff --git a/Libraries/LibWebView/Process.cpp b/Libraries/LibWebView/Process.cppindex 00dc9e6b76c..3637ef5a448 100644--- a/Libraries/LibWebView/Process.cpp+++ b/Libraries/LibWebView/Process.cpp@@ -124,7 +124,7 @@ Vector<ByteString> Process::helper_process_environment(ProcessType type)}if (type == ProcessType::AudioServer)is_allowed |= audio_names.contains_slow(entry.name);- if (type == ProcessType::Compositor)+ if (type == ProcessType::Compositor || type == ProcessType::VideoDecoderServer)is_allowed |= any_of(gpu_prefixes, [&](auto prefix) { return entry.name.starts_with(prefix); });if (is_allowed)environment.append(entry.full_entry);diff --git a/Services/Compositor/CompositorControlClient.ipc b/Services/Compositor/CompositorControlClient.ipcindex c81d41bec6b..ec9b7b280fe 100644--- a/Services/Compositor/CompositorControlClient.ipc+++ b/Services/Compositor/CompositorControlClient.ipc@@ -1,9 +1,12 @@+#include <LibGfx/GpuDeviceIdentity.h>#include <LibGfx/Rect.h>#include <LibGfx/SharedImage.h>#include <LibCompositing/Types.h>endpoint CompositorControlClient{+ // Sent once at startup: the GPU that decoders must output to for their frames to be shown without a copy.+ gpu_device_identity_reported(Optional<Gfx::GpuDeviceIdentity> identity) =|did_allocate_backing_stores(Web::CompositorContextId context_id, Vector<i32> bitmap_ids, Vector<Gfx::SharedImage> backing_stores) =|did_add_backing_stores(Web::CompositorContextId context_id, Vector<i32> bitmap_ids, Vector<Gfx::SharedImage> backing_stores) =|did_retire_backing_stores(Web::CompositorContextId context_id, Vector<i32> bitmap_ids) =|diff --git a/Services/Compositor/main.cpp b/Services/Compositor/main.cppindex c82d368fce6..114f36f3627 100644--- a/Services/Compositor/main.cpp+++ b/Services/Compositor/main.cpp@@ -15,6 +15,7 @@#include <LibCore/ResourceImplementationFile.h>#include <LibGfx/Font/Font.h>#include <LibGfx/Font/FontDatabase.h>+#include <LibGfx/GpuDeviceIdentity.h>#include <LibGfx/SkiaBackendContext.h>#include <LibIPC/SingleServer.h>#include <LibMain/Main.h>@@ -84,8 +85,15 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)if (!disable_sandbox)TRY(Compositor::apply_sandbox(mach_server_name, cache_path, resource_root));+ Optional<Gfx::GpuDeviceIdentity> gpu_device_identity;+#ifdef USE_VULKAN_DMABUF_IMAGES+ if (skia_backend_context && skia_backend_context->vulkan_context().can_sample_through_ycbcr_conversion)+ gpu_device_identity = skia_backend_context->vulkan_context().device_identity;+#endif+auto client = TRY(IPC::take_over_accepted_client_from_system_server<Compositor::ConnectionFromClient>(mach_server_name, move(skia_backend_context)));+ client->async_gpu_device_identity_reported(move(gpu_device_identity));return event_loop.exec();}diff --git a/Services/VideoDecoderServer/CMakeLists.txt b/Services/VideoDecoderServer/CMakeLists.txtindex 66ee1333e20..d3cefc2dcc9 100644--- a/Services/VideoDecoderServer/CMakeLists.txt+++ b/Services/VideoDecoderServer/CMakeLists.txt@@ -21,7 +21,7 @@ add_dependencies(videodecoderserverservicetarget_include_directories(videodecoderserverservice PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/../..)target_include_directories(videodecoderserverservice PRIVATE ${LADYBIRD_SOURCE_DIR}/Services/)-target_link_libraries(VideoDecoderServer PRIVATE videodecoderserverservice LibCore LibMain LibMediaCodecs LibSandbox)+target_link_libraries(VideoDecoderServer PRIVATE videodecoderserverservice LibCore LibGfx LibMain LibMediaCodecs LibSandbox)target_link_libraries(videodecoderserverservice PRIVATE LibCore LibIPC LibMediaCodecs)if (WIN32)diff --git a/Services/VideoDecoderServer/Sandbox.h b/Services/VideoDecoderServer/Sandbox.hindex b1dc0774387..d7ff7105ff6 100644--- a/Services/VideoDecoderServer/Sandbox.h+++ b/Services/VideoDecoderServer/Sandbox.h@@ -7,10 +7,17 @@#pragma once#include <AK/Error.h>+#include <AK/Platform.h>#include <AK/StringView.h>namespace VideoDecoderServer {+#if defined(AK_OS_LINUX)+// Landlock confines only the calling thread and the threads that it starts later, so this has to run before the GPU+// driver starts its threads. apply_sandbox() then installs the rest of the sandbox.+[[nodiscard]] ErrorOr<void> restrict_filesystem(bool allow_gpu_driver);+#endif+[[nodiscard]] ErrorOr<void> apply_sandbox(StringView mach_server_name);}diff --git a/Services/VideoDecoderServer/SandboxLinux.cpp b/Services/VideoDecoderServer/SandboxLinux.cppindex 4d23924d61a..c904f5a138c 100644--- a/Services/VideoDecoderServer/SandboxLinux.cpp+++ b/Services/VideoDecoderServer/SandboxLinux.cpp@@ -12,8 +12,7 @@namespace VideoDecoderServer {-// FIXME: Grant the GPU access that hardware decoders need once the server hosts one.-ErrorOr<void> apply_sandbox(StringView)+ErrorOr<void> restrict_filesystem(bool allow_gpu_driver){TRY(Sandbox::install_no_new_privileges());TRY(Sandbox::configure_runtime());@@ -26,9 +25,16 @@ ErrorOr<void> apply_sandbox(StringView)TRY(Sandbox::add_landlock_path_if_exists(paths, executable_path, Sandbox::LandlockPath::Access::ReadOnly));TRY(Sandbox::add_landlock_path_if_exists(paths, LexicalPath::join(build_root, "lib"sv).string(), Sandbox::LandlockPath::Access::ReadOnly));TRY(Sandbox::add_landlock_path_if_exists(paths, "/proc/self"sv, Sandbox::LandlockPath::Access::ReadOnly));+ if (allow_gpu_driver)+ TRY(Sandbox::add_gpu_driver_landlock_paths(paths));TRY(Sandbox::restrict_filesystem_with_landlock(paths.span()));+ return {};+}+// FIXME: Narrow the GPU access to what decoding needs, once hardware decoders run here.+ErrorOr<void> apply_sandbox(StringView)+{Sandbox::SeccompPolicy policy;policy.allow_readonly_file_opens();policy.allow_filesystem_metadata_queries();@@ -36,6 +42,11 @@ ErrorOr<void> apply_sandbox(StringView)policy.allow_ipc();policy.allow_socket_pairs();policy.allow_common_runtime();+ // The driver opens its device files for writing once decoding starts. Landlock limits writes to those.+ policy.allow_filesystem_writes();+ policy.allow_gpu_device_operations();+ policy.allow_executable_memory_mappings();+ policy.allow_writable_executable_memory_mappings();TRY(policy.install());return {};diff --git a/Services/VideoDecoderServer/main.cpp b/Services/VideoDecoderServer/main.cppindex d1949cb262f..e94279c22bd 100644--- a/Services/VideoDecoderServer/main.cpp+++ b/Services/VideoDecoderServer/main.cpp@@ -11,11 +11,13 @@#include <LibCore/Platform/TaskRole.h>#include <LibCore/Platform/ThreadQoS.h>#include <LibCore/Process.h>+#include <LibGfx/GpuDeviceIdentity.h>#include <LibIPC/SingleServer.h>#include <LibMain/Main.h>#include <LibMediaCodecs/FFmpeg/FFmpegVideoDecoder.h>#include <LibMediaCodecs/HardwareVideoDecoders.h>#include <LibMediaCodecs/VideoDecoderRegistry.h>+#include <LibMediaCodecs/Vulkan/VulkanVideoDevice.h>#include <VideoDecoderServer/ControlConnection.h>#include <VideoDecoderServer/Sandbox.h>@@ -43,6 +45,7 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)bool wait_for_debugger = false;bool disable_sandbox = false;bool host_software_decoders = false;+ StringView gpu_device;Core::ArgsParser args_parser;args_parser.add_option(crash_report_fd, "Descriptor for anonymous crash diagnostics", "crash-report-fd", 0, "fd");@@ -50,6 +53,7 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)args_parser.add_option(wait_for_debugger, "Wait for debugger", "wait-for-debugger");args_parser.add_option(disable_sandbox, "Disable process sandboxing", "disable-sandbox");args_parser.add_option(host_software_decoders, "Host software decoders, for testing", "host-software-decoders");+ args_parser.add_option(gpu_device, "The GPU to decode on, as the Compositor identifies it", "gpu-device", 0, "identity");args_parser.parse(arguments);if (crash_report_fd >= 0) {@@ -67,6 +71,26 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)auto& event_loop = Core::EventLoop::initialize_for_current_thread();+ Optional<Gfx::GpuDeviceIdentity> gpu_device_identity;+ if (!gpu_device.is_empty()) {+ gpu_device_identity = Gfx::GpuDeviceIdentity::from_string(gpu_device);+ if (!gpu_device_identity.has_value())+ return Error::from_string_literal("Malformed GPU device identity");+ }++#if defined(AK_OS_LINUX)+ if (!disable_sandbox)+ TRY(VideoDecoderServer::restrict_filesystem(gpu_device_identity.has_value()));+#endif++#ifdef USE_VULKAN_DMABUF_IMAGES+ // The driver loads before the rest of the sandbox applies. Without a device, the GPU's decoders go unused.+ if (gpu_device_identity.has_value()) {+ if (auto result = Media::VulkanVideoDevice::create_for_process(*gpu_device_identity); result.is_error())+ warnln("Could not create a Vulkan device for decoding video: {}", result.error());+ }+#endif+Vector<Media::VideoDecoderRegistration> hosted_decoders;auto hardware_decoders = Media::hardware_video_decoders();hosted_decoders.append(hardware_decoders.data(), hardware_decoders.size());