Truly independent web browser
LibGfx+Compositor+UI/Qt: Share frames in the GPU's own layouts
Andreas Kling95224275fc44
diff --git a/Libraries/LibGfx/VulkanContext.cpp b/Libraries/LibGfx/VulkanContext.cppindex 767abc255f7..4bc186a170f 100644--- a/Libraries/LibGfx/VulkanContext.cpp+++ b/Libraries/LibGfx/VulkanContext.cpp@@ -255,6 +255,7 @@ ErrorOr<VulkanContext> create_vulkan_context(Optional<GpuDeviceIdentity> const&.instance = instance,.physical_device = physical_device,.device_identity = gpu_device_identity_of(physical_device),+ .is_preferred_device = preferred_device.has_value() && gpu_device_identity_of(physical_device) == *preferred_device,.logical_device = logical_device,.graphics_queue = graphics_queue,.graphics_queue_family = graphics_queue_family,diff --git a/Libraries/LibGfx/VulkanContext.h b/Libraries/LibGfx/VulkanContext.hindex 08f635cf538..9ac2edf3129 100644--- a/Libraries/LibGfx/VulkanContext.h+++ b/Libraries/LibGfx/VulkanContext.h@@ -20,6 +20,9 @@ struct VulkanContext {VkInstance instance { VK_NULL_HANDLE };VkPhysicalDevice physical_device { VK_NULL_HANDLE };GpuDeviceIdentity device_identity;+ // Whether this is the device the context was asked to prefer, which tells the context's user that whoever asked+ // can import the memory it shares in any layout this device renders to.+ bool is_preferred_device { false };VkDevice logical_device { VK_NULL_HANDLE };VkQueue graphics_queue { VK_NULL_HANDLE };uint32_t graphics_queue_family { 0 };diff --git a/Libraries/LibGfx/VulkanImage.cpp b/Libraries/LibGfx/VulkanImage.cppindex bb4eb7fbe86..9d064b46561 100644--- a/Libraries/LibGfx/VulkanImage.cpp+++ b/Libraries/LibGfx/VulkanImage.cpp@@ -228,11 +228,22 @@ ErrorOr<NonnullRefPtr<VulkanImage>> create_shared_vulkan_image(VulkanContext conreturn Error::from_string_literal("image creation failed");}+ // NB: The driver picks one of the layouts offered when it creates the image.+ VkImageDrmFormatModifierPropertiesEXT image_format_mod_props = {};+ image_format_mod_props.sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_PROPERTIES_EXT;+ image_format_mod_props.pNext = nullptr;+ result = context.ext_procs.get_image_drm_format_modifier_properties(context.logical_device, image->image, &image_format_mod_props);+ if (result != VK_SUCCESS) {+ dbgln("vkGetImageDrmFormatModifierPropertiesEXT returned {}", to_underlying(result));+ return Error::from_string_literal("image format modifier retrieval failed");+ }+VkMemoryRequirements mem_reqs;vkGetImageMemoryRequirements(context.logical_device, image->image, &mem_reqs);VkPhysicalDeviceMemoryProperties mem_props;vkGetPhysicalDeviceMemoryProperties(context.physical_device, &mem_props);- bool const is_linear_image = format_mods.size() == 1 && format_mods[0] == DRM_FORMAT_MOD_LINEAR;+ // NB: The importers map a linear image's memory, so that has to be visible to the CPU.+ bool const is_linear_image = image_format_mod_props.drmFormatModifier == DRM_FORMAT_MOD_LINEAR;uint32_t mem_type_idx = mem_props.memoryTypeCount;if (is_linear_image) {@@ -284,15 +295,6 @@ ErrorOr<NonnullRefPtr<VulkanImage>> create_shared_vulkan_image(VulkanContext conVkSubresourceLayout subresource_layout = {};vkGetImageSubresourceLayout(context.logical_device, image->image, &subresource, &subresource_layout);- VkImageDrmFormatModifierPropertiesEXT image_format_mod_props = {};- image_format_mod_props.sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_PROPERTIES_EXT;- image_format_mod_props.pNext = nullptr;- result = context.ext_procs.get_image_drm_format_modifier_properties(context.logical_device, image->image, &image_format_mod_props);- if (result != VK_SUCCESS) {- dbgln("vkGetImageDrmFormatModifierPropertiesEXT returned {}", to_underlying(result));- return Error::from_string_literal("image format modifier retrieval failed");- }-// NB: Our dma-bufs name a single plane at the start of its memory, as the importers expect.if (subresource_layout.offset != 0)return Error::from_string_literal("image plane does not start at the start of its memory");diff --git a/Services/Compositor/BackingStoreManager.cpp b/Services/Compositor/BackingStoreManager.cppindex 5fd9bef563f..e2421fb7dfc 100644--- a/Services/Compositor/BackingStoreManager.cpp+++ b/Services/Compositor/BackingStoreManager.cpp@@ -63,8 +63,11 @@ struct GpuBackingStore {static ErrorOr<GpuBackingStore> create_shared_gpu_backing_store(Gfx::IntSize size, Gfx::SkiaBackendContext& skia_backend_context){auto const& vulkan_context = skia_backend_context.vulkan_context();+ // A presentation on another GPU can only import a linear layout. On ours, the driver picks the layout that suits it,+ // which matters to GPUs such as NVIDIA's that cannot render to a linear one at all.static constexpr Array<u64, 1> linear_modifiers = { DRM_FORMAT_MOD_LINEAR };- auto image = TRY(Gfx::create_shared_vulkan_image(vulkan_context, size.width(), size.height(), VK_FORMAT_B8G8R8A8_UNORM, linear_modifiers.span()));+ auto const modifiers = vulkan_context.is_preferred_device ? Gfx::renderable_drm_format_modifiers(vulkan_context, VK_FORMAT_B8G8R8A8_UNORM) : Vector<u64>(linear_modifiers.span());+ auto image = TRY(Gfx::create_shared_vulkan_image(vulkan_context, size.width(), size.height(), VK_FORMAT_B8G8R8A8_UNORM, modifiers.span()));auto shared_image = Gfx::duplicate_shared_image(*image);return GpuBackingStore {@@ -173,7 +176,11 @@ Optional<BackingStoreManager::Publication> BackingStoreManager::allocate_backingfor (size_t i = 0; i < buffer_count; ++i) {auto backing_store = create_shared_gpu_backing_store(allocation.size, *skia_backend_context);if (backing_store.is_error()) {- dbgln("Failed to allocate shared GPU backing store ({}), falling back to shareable bitmaps", backing_store.error());+ static bool reported_failure = false;+ if (!reported_failure) {+ dbgln("Failed to allocate shared GPU backing store ({}), falling back to shareable bitmaps", backing_store.error());+ reported_failure = true;+ }allocation_succeeded = false;break;}diff --git a/UI/Qt/WebContentView.cpp b/UI/Qt/WebContentView.cppindex 4fd5a396620..e8055c42b5f 100644--- a/UI/Qt/WebContentView.cpp+++ b/UI/Qt/WebContentView.cpp@@ -1127,6 +1127,7 @@ Optional<WebContentView::Paintable> WebContentView::current_paintable() constvoid WebContentView::schedule_repaint(){#if defined(LADYBIRD_QT_USE_VULKAN_WINDOW)+ m_frame_read_from_gpu = {};schedule_vulkan_window_update();#elif defined(LADYBIRD_QT_USE_IOSURFACE_LAYER)present_current_paintable_as_layer_contents();@@ -1180,10 +1181,10 @@ void WebContentView::paintEvent(QPaintEvent*)painter.scale(1 / m_device_pixel_ratio, 1 / m_device_pixel_ratio);auto paintable = current_paintable();- Gfx::Bitmap const* bitmap = nullptr;+ RefPtr<Gfx::Bitmap const> bitmap;Gfx::IntSize bitmap_size;if (paintable.has_value()) {- bitmap = paintable->shared_image_buffer->bitmap().ptr();+ bitmap = cpu_bitmap_to_paint(*paintable);bitmap_size = paintable->bitmap_size;}@@ -1228,6 +1229,18 @@ void WebContentView::paintEvent(QPaintEvent*)}#endif+#if !defined(LADYBIRD_QT_USE_VULKAN_WINDOW)+RefPtr<Gfx::Bitmap const> WebContentView::cpu_bitmap_of(Paintable const& paintable) const+{+ return paintable.shared_image_buffer->bitmap_if_present();+}++RefPtr<Gfx::Bitmap const> WebContentView::cpu_bitmap_to_paint(Paintable const& paintable) const+{+ return cpu_bitmap_of(paintable);+}+#endif+// The page as the view currently shows it, in device pixels.QImage WebContentView::visible_snapshot() const{@@ -1235,7 +1248,7 @@ QImage WebContentView::visible_snapshot() constif (!paintable.has_value())return {};- if (auto bitmap = paintable->shared_image_buffer->bitmap_if_present()) {+ if (auto bitmap = cpu_bitmap_of(*paintable)) {auto width = min(bitmap->width(), paintable->bitmap_size.width());auto height = min(bitmap->height(), paintable->bitmap_size.height());if (width <= 0 || height <= 0)diff --git a/UI/Qt/WebContentView.h b/UI/Qt/WebContentView.hindex 27c2c85a505..8c1d70c660a 100644--- a/UI/Qt/WebContentView.h+++ b/UI/Qt/WebContentView.h@@ -223,6 +223,10 @@ private:};Optional<Paintable> current_paintable() const;+ // The pixels of a frame, which a frame that lives only in GPU memory has once they are read back from there.+ RefPtr<Gfx::Bitmap const> cpu_bitmap_of(Paintable const&) const;+ // The pixels of a frame for Qt to paint, which there is no need to read back while the page's window covers them.+ RefPtr<Gfx::Bitmap const> cpu_bitmap_to_paint(Paintable const&) const;QImage visible_snapshot() const;void update_viewport_size();@@ -388,6 +392,13 @@ private:QWidget* m_vulkan_window_container { nullptr };Optional<bool> m_vulkan_window_supports_alpha_blending;+ // The pixels of the frame on screen, read back from GPU memory once for each frame that Qt paints itself.+ struct FrameReadFromGpu {+ Gfx::SharedImageBuffer const* shared_image_buffer { nullptr };+ RefPtr<Gfx::Bitmap const> bitmap;+ };+ mutable FrameReadFromGpu m_frame_read_from_gpu;+int m_vertical_tab_overlay_left { 0 };int m_vertical_tab_overlay_right { 0 };int m_bookmarks_bar_overlay_height { 0 };diff --git a/UI/Qt/WebContentViewLinux.cpp b/UI/Qt/WebContentViewLinux.cppindex 010d93eb77b..05624412c15 100644--- a/UI/Qt/WebContentViewLinux.cpp+++ b/UI/Qt/WebContentViewLinux.cpp@@ -16,6 +16,8 @@#include <AK/kmalloc.h>#include <LibGfx/SharedImageBuffer.h>#include <LibGfx/VulkanContext.h>+#include <LibGfx/VulkanImage.h>+#include <LibWebView/Application.h>#include <UI/Qt/NativeWindowContainer.h>#include <UI/Qt/WebContentView.h>#ifdef LADYBIRD_HAS_WAYLAND_GPU_QUERY@@ -145,22 +147,60 @@ Optional<Gfx::GpuDeviceIdentity> WebContentView::presentation_gpu_device()return {};}-#include <WebContentViewLinuxFragShader.h>-#include <WebContentViewLinuxVertShader.h>+// A device of our own to read frames back from GPU memory with, since a view's window has no device while it is hidden.+static Gfx::VulkanContext const* readback_vulkan_context()+{+ static NeverDestroyed<Optional<Gfx::VulkanContext>> context = []() -> Optional<Gfx::VulkanContext> {+ auto context = Gfx::create_vulkan_context(WebContentView::presentation_gpu_device());+ if (context.is_error()) {+ dbgln("Unable to create a Vulkan context to read frames back with: {}", context.error());+ return {};+ }+ return context.release_value();+ }();+ return context->has_value() ? &context->value() : nullptr;+}++RefPtr<Gfx::Bitmap const> WebContentView::cpu_bitmap_to_paint(Paintable const& paintable) const+{+ if (auto bitmap = paintable.shared_image_buffer->bitmap_if_present())+ return bitmap;++ // NB: Qt repaints this widget at every step of a resize. While the page's window covers the widget, nobody sees+ // what it paints, and reading each frame back from GPU memory for it would be slow. The strips that hover-+ // expanded chrome punches out of the page's window are the only part of the page that shows through.+ bool page_window_covers_widget = m_vulkan_window_container && m_vulkan_window_container->isVisible()+ && m_vertical_tab_overlay_left == 0 && m_vertical_tab_overlay_right == 0 && m_bookmarks_bar_overlay_height == 0;+ if (page_window_covers_widget)+ return {};+ return cpu_bitmap_of(paintable);+}-static Optional<u32> find_memory_type_index(VkPhysicalDevice physical_device, u32 memory_type_bits)+RefPtr<Gfx::Bitmap const> WebContentView::cpu_bitmap_of(Paintable const& paintable) const{- VkPhysicalDeviceMemoryProperties memory_properties;- vkGetPhysicalDeviceMemoryProperties(physical_device, &memory_properties);+ if (auto bitmap = paintable.shared_image_buffer->bitmap_if_present())+ return bitmap;- for (u32 i = 0; i < memory_properties.memoryTypeCount; ++i) {- if (memory_type_bits & (1u << i))- return i;- }+ auto const* dmabuf = paintable.shared_image_buffer->linux_dmabuf_handle();+ if (!dmabuf)+ return {};+ if (m_frame_read_from_gpu.shared_image_buffer == paintable.shared_image_buffer)+ return m_frame_read_from_gpu.bitmap;- return {};+ RefPtr<Gfx::Bitmap const> bitmap;+ if (auto const* context = readback_vulkan_context()) {+ if (auto result = Gfx::read_linux_dmabuf_into_bitmap(*context, *dmabuf); result.is_error())+ dbgln("Unable to read a frame back from GPU memory: {}", result.error());+ else+ bitmap = result.release_value();+ }+ m_frame_read_from_gpu = { paintable.shared_image_buffer, bitmap };+ return bitmap;}+#include <WebContentViewLinuxFragShader.h>+#include <WebContentViewLinuxVertShader.h>+static VkFormat vk_format_from_drm_format(u32 drm_format){switch (drm_format) {@@ -611,113 +651,26 @@ struct WebContentView::VulkanRenderer {return imported_texture_for(shared_image_buffer);}+ // Whether the device can never import frames like this one, as opposed to failing to now.+ bool cannot_import_frames_like(Gfx::SharedImageBuffer const& shared_image_buffer) const+ {+ auto const* dmabuf = shared_image_buffer.linux_dmabuf_handle();+ if (!dmabuf)+ return false;+ auto vk_format = vk_format_from_drm_format(dmabuf->drm_format);+ return vk_format == VK_FORMAT_UNDEFINED || !Gfx::can_import_dmabuf_image(physical_device, vk_format, dmabuf->modifier, VK_IMAGE_USAGE_SAMPLED_BIT);+ }+OwnPtr<ImportedTexture> import_texture(Gfx::LinuxDmaBufHandle const& dmabuf, DmaBufIdentity const& dmabuf_identity){auto vk_format = vk_format_from_drm_format(dmabuf.drm_format);- if (vk_format == VK_FORMAT_UNDEFINED || dmabuf.modifier != DRM_FORMAT_MOD_LINEAR)+ if (vk_format == VK_FORMAT_UNDEFINED)return {};-- VkImageDrmFormatModifierListCreateInfoEXT modifier_list {- .sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_LIST_CREATE_INFO_EXT,- .pNext = nullptr,- .drmFormatModifierCount = 1,- .pDrmFormatModifiers = &dmabuf.modifier,- };- VkExternalMemoryImageCreateInfo external_memory_image_info {- .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,- .pNext = &modifier_list,- .handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT,- };- VkImageCreateInfo image_info {- .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,- .pNext = &external_memory_image_info,- .flags = 0,- .imageType = VK_IMAGE_TYPE_2D,- .format = vk_format,- .extent = {- .width = static_cast<u32>(dmabuf.size.width()),- .height = static_cast<u32>(dmabuf.size.height()),- .depth = 1,- },- .mipLevels = 1,- .arrayLayers = 1,- .samples = VK_SAMPLE_COUNT_1_BIT,- .tiling = VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT,- .usage = VK_IMAGE_USAGE_SAMPLED_BIT,- .sharingMode = VK_SHARING_MODE_EXCLUSIVE,- .queueFamilyIndexCount = 0,- .pQueueFamilyIndices = nullptr,- .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,- };-- VkImage image { VK_NULL_HANDLE };- if (vkCreateImage(device, &image_info, nullptr, &image) != VK_SUCCESS)+ auto imported = Gfx::import_linux_dmabuf_image(physical_device, device, get_memory_fd_properties, dmabuf, vk_format, VK_IMAGE_USAGE_SAMPLED_BIT);+ if (imported.is_error())return {};-- VkImageSubresource subresource { VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT, 0, 0 };- VkSubresourceLayout subresource_layout {};- vkGetImageSubresourceLayout(device, image, &subresource, &subresource_layout);- if (subresource_layout.rowPitch != dmabuf.planes.first().pitch) {- vkDestroyImage(device, image, nullptr);- return {};- }-- VkMemoryRequirements memory_requirements;- vkGetImageMemoryRequirements(device, image, &memory_requirements);-- VkMemoryFdPropertiesKHR memory_fd_properties {- .sType = VK_STRUCTURE_TYPE_MEMORY_FD_PROPERTIES_KHR,- .pNext = nullptr,- .memoryTypeBits = 0,- };- if (get_memory_fd_properties(device, VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT, dmabuf.objects.first().fd(), &memory_fd_properties) != VK_SUCCESS) {- vkDestroyImage(device, image, nullptr);- return {};- }-- auto memory_type_index = find_memory_type_index(physical_device, memory_requirements.memoryTypeBits & memory_fd_properties.memoryTypeBits);- if (!memory_type_index.has_value()) {- vkDestroyImage(device, image, nullptr);- return {};- }-- int imported_fd = fcntl(dmabuf.objects.first().fd(), F_DUPFD_CLOEXEC, 0);- if (imported_fd < 0) {- vkDestroyImage(device, image, nullptr);- return {};- }-- VkMemoryDedicatedAllocateInfo dedicated_allocate_info {- .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,- .pNext = nullptr,- .image = image,- .buffer = VK_NULL_HANDLE,- };- VkImportMemoryFdInfoKHR import_memory_fd_info {- .sType = VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR,- .pNext = &dedicated_allocate_info,- .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT,- .fd = imported_fd,- };- VkMemoryAllocateInfo memory_allocate_info {- .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,- .pNext = &import_memory_fd_info,- .allocationSize = memory_requirements.size,- .memoryTypeIndex = *memory_type_index,- };-- VkDeviceMemory memory { VK_NULL_HANDLE };- if (vkAllocateMemory(device, &memory_allocate_info, nullptr, &memory) != VK_SUCCESS) {- ::close(imported_fd);- vkDestroyImage(device, image, nullptr);- return {};- }-- if (vkBindImageMemory(device, image, memory, 0) != VK_SUCCESS) {- vkFreeMemory(device, memory, nullptr);- vkDestroyImage(device, image, nullptr);- return {};- }+ auto image = imported.value().image;+ auto memory = imported.value().memory;VkImageViewCreateInfo image_view_info {.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,@@ -905,8 +858,15 @@ struct WebContentView::VulkanWindowRenderer final : public QVulkanWindowRendererauto paintable = m_view.current_paintable();bool can_render = paintable.has_value()&& !paintable->bitmap_size.is_empty()- && m_renderer.prepare(m_window)- && m_renderer.can_render(*paintable->shared_image_buffer);+ && m_renderer.prepare(m_window);+ if (can_render && !m_renderer.can_render(*paintable->shared_image_buffer)) {+ // NB: Reading every frame back from GPU memory would be slow, so a frame in a format or layout we cannot+ // import makes the Compositor share its frames as bitmaps instead. A frame kept from backing stores+ // that are gone may be from an old allocation, and says nothing about the frames to come.+ if (!paintable->shared_image_buffer->bitmap_if_present() && paintable->bitmap_id >= 0 && m_renderer.cannot_import_frames_like(*paintable->shared_image_buffer))+ WebView::Application::the().notify_compositor_gpu_presentation_unavailable();+ can_render = false;+ }if (!can_render) {m_window.frameReady();m_view.fall_back_to_bitmap_rendering();