From ce0826aaace3abd635259d628496152d20ea1dca Mon Sep 17 00:00:00 2001 From: Timon Date: Mon, 26 Oct 2026 02:20:43 +0000 Subject: [PATCH] Desktop: Import dma-bufs through wgpu-hal with queue ownership transfers (#4814) Import dma-bufs through wgpu-hal with queue ownership transfers --- desktop/src/gpu_context.rs | 4 +- desktop/ui/src/frames/import.rs | 116 ++++++- desktop/ui/src/frames/import/d3d11.rs | 4 +- desktop/ui/src/frames/import/dmabuf.rs | 315 ++++++++---------- desktop/ui/src/frames/import/iosurface.rs | 2 +- desktop/ui/src/frames/surface.rs | 140 ++------ .../libraries/wgpu-executor/src/context.rs | 8 +- 7 files changed, 276 insertions(+), 313 deletions(-) diff --git a/desktop/src/gpu_context.rs b/desktop/src/gpu_context.rs index 019e2516ff..792efe6e06 100644 --- a/desktop/src/gpu_context.rs +++ b/desktop/src/gpu_context.rs @@ -1,7 +1,9 @@ use crate::wrapper::{WgpuContext, WgpuContextBuilder, WgpuFeatures}; pub(super) async fn create_wgpu_context() -> WgpuContext { - let mut wgpu_context_builder = WgpuContextBuilder::new().with_features(WgpuFeatures::IMMEDIATES); + let mut wgpu_context_builder = WgpuContextBuilder::new() + .with_features(WgpuFeatures::IMMEDIATES) + .with_optional_features(WgpuFeatures::VULKAN_EXTERNAL_MEMORY_DMA_BUF); // TODO: make this configurable via cli flags instead if let Some(index) = std::env::var("GRAPHITE_WGPU_ADAPTER").ok().and_then(|s| s.parse().ok()) { diff --git a/desktop/ui/src/frames/import.rs b/desktop/ui/src/frames/import.rs index 3edabfbe94..cb33cfd176 100644 --- a/desktop/ui/src/frames/import.rs +++ b/desktop/ui/src/frames/import.rs @@ -1,5 +1,7 @@ use cef::sys::cef_color_type_t; +use super::resample::Resampler; + #[cfg(target_os = "windows")] pub(crate) mod d3d11; #[cfg(target_os = "linux")] @@ -7,7 +9,7 @@ pub(crate) mod dmabuf; #[cfg(target_os = "macos")] pub(crate) mod iosurface; -pub(crate) type TextureImportResult = Result; +pub(crate) type TextureImportResult = Result; #[derive(Debug, thiserror::Error)] pub(crate) enum TextureImportError { @@ -18,9 +20,6 @@ pub(crate) enum TextureImportError { #[cfg(not(target_os = "macos"))] #[error("Hardware acceleration not available: {reason}")] HardwareUnavailable { reason: String }, - #[error("Vulkan operation failed: {operation}")] - #[cfg(target_os = "linux")] - VulkanError { operation: String }, #[error("Platform-specific error: {message}")] PlatformError { message: String }, } @@ -91,6 +90,115 @@ pub(crate) trait TextureImporter { fn import_to_wgpu(&self, device: &wgpu::Device) -> TextureImportResult; } +pub(crate) struct ImportedTexture { + texture: wgpu::Texture, + ownership: Option, +} + +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +struct OwnershipTransfer { + acquire: wgpu::CommandBuffer, + release: wgpu::CommandBuffer, + state: wgpu::TextureUses, +} + +impl From for ImportedTexture { + fn from(texture: wgpu::Texture) -> Self { + Self { texture, ownership: None } + } +} + +impl ImportedTexture { + pub(super) fn copy(self, device: &wgpu::Device, queue: &wgpu_sync::Queue, resampler: &Resampler, content_rect: ContentRect) -> wgpu::Texture { + let imported = self.texture; + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("CEF Frame Copy Encoder"), + }); + let output = match content_rect.mapping(imported.width(), imported.height()) { + ContentMapping::Identity => { + let output = device.create_texture(&wgpu::TextureDescriptor { + label: Some("CEF Imported Frame Copy"), + size: imported.size(), + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: imported.format(), + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + encoder.copy_texture_to_texture( + wgpu::TexelCopyTextureInfo { + texture: &imported, + mip_level: 0, + origin: wgpu::Origin3d::ZERO, + aspect: wgpu::TextureAspect::All, + }, + wgpu::TexelCopyTextureInfo { + texture: &output, + mip_level: 0, + origin: wgpu::Origin3d::ZERO, + aspect: wgpu::TextureAspect::All, + }, + imported.size(), + ); + output + } + ContentMapping::Scaled(content_rect) => { + let output = device.create_texture(&wgpu::TextureDescriptor { + label: Some("CEF Imported Scaled Frame Copy"), + size: wgpu::Extent3d { + width: content_rect.source_width, + height: content_rect.source_height, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: imported.format(), + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::RENDER_ATTACHMENT, + view_formats: &[], + }); + let size = wgpu::Extent3d { + width: content_rect.width, + height: content_rect.height, + depth_or_array_layers: 1, + }; + resampler.encode( + &mut encoder, + &imported, + wgpu::Origin3d { + x: content_rect.x, + y: content_rect.y, + z: 0, + }, + size, + &output, + ); + output + } + }; + + match self.ownership { + Some(OwnershipTransfer { acquire, release, state }) => { + encoder.transition_resources( + std::iter::empty(), + std::iter::once(wgpu::TextureTransition { + texture: &imported, + selector: None, + state, + }), + ); + queue.submit([acquire, encoder.finish(), release]); + } + None => { + queue.submit([encoder.finish()]); + } + } + + output + } +} + fn wgpu_format(format: cef_color_type_t) -> Result { match format { cef_color_type_t::CEF_COLOR_TYPE_BGRA_8888 => Ok(wgpu::TextureFormat::Bgra8Unorm), diff --git a/desktop/ui/src/frames/import/d3d11.rs b/desktop/ui/src/frames/import/d3d11.rs index 716ed2483c..2409515fd7 100644 --- a/desktop/ui/src/frames/import/d3d11.rs +++ b/desktop/ui/src/frames/import/d3d11.rs @@ -75,7 +75,7 @@ impl D3D11Importer { ) }; - Ok(texture) + Ok(texture.into()) } fn import_via_vulkan(&self, device: &wgpu::Device) -> TextureImportResult { @@ -122,7 +122,7 @@ impl D3D11Importer { ) }; - Ok(texture) + Ok(texture.into()) } fn import_d3d11_handle_to_d3d12(&self, hal_device: &::Device) -> Result { diff --git a/desktop/ui/src/frames/import/dmabuf.rs b/desktop/ui/src/frames/import/dmabuf.rs index de5968d7bb..148a0e25c1 100644 --- a/desktop/ui/src/frames/import/dmabuf.rs +++ b/desktop/ui/src/frames/import/dmabuf.rs @@ -1,7 +1,8 @@ -use super::{TextureImportError, TextureImportResult, TextureImporter, texture_descriptor, wgpu_format}; +use super::{ImportedTexture, OwnershipTransfer, TextureImportError, TextureImportResult, TextureImporter, texture_descriptor, wgpu_format}; use ash::vk; use cef::sys::cef_color_type_t; -use wgpu::hal::api; +use wgpu::TextureUses; +use wgpu::hal::api::Vulkan; pub struct DmaBufImporter { fds: Vec, @@ -28,9 +29,63 @@ impl TextureImporter for DmaBufImporter { ))); } - let texture = self.import_via_vulkan(device)?; + let max_dimension = device.limits().max_texture_dimension_2d; + if self.width == 0 || self.height == 0 || self.width > max_dimension || self.height > max_dimension { + return Err(TextureImportError::InvalidHandle(format!( + "Invalid DMA-BUF dimensions {}x{} for the device limit of {max_dimension}", + self.width, self.height + ))); + } + + if !device.features().contains(wgpu::Features::VULKAN_EXTERNAL_MEMORY_DMA_BUF) { + return Err(TextureImportError::HardwareUnavailable { + reason: "Device does not support VULKAN_EXTERNAL_MEMORY_DMA_BUF".to_string(), + }); + } + + let fd = self.fds[0].try_clone().map_err(|e| TextureImportError::PlatformError { + message: format!("Failed to duplicate DMA-BUF file descriptor: {e}"), + })?; + + let hal_texture = unsafe { + let Some(hal_device) = device.as_hal::() else { + return Err(TextureImportError::HardwareUnavailable { + reason: "Device is not using Vulkan backend".to_string(), + }); + }; + hal_device.texture_from_dmabuf_fd( + fd, + &wgpu::hal::TextureDescriptor { + label: Some("CEF DMA-BUF Texture"), + size: wgpu::Extent3d { + width: self.width, + height: self.height, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu_format(self.format)?, + usage: TextureUses::COPY_SRC | TextureUses::RESOURCE, + memory_flags: wgpu::hal::MemoryFlags::empty(), + view_formats: vec![], + }, + self.modifier, + u64::from(self.strides[0]), + u64::from(self.offsets[0]), + )? + }; + + let texture = unsafe { + device.create_texture_from_hal::( + hal_texture, + &texture_descriptor(self.width, self.height, self.format, "CEF DMA-BUF Texture")?, + TextureUses::COPY_SRC | TextureUses::RESOURCE, + ) + }; + let ownership = ownership_transfer(device, &texture)?; tracing::trace!("Successfully imported DMA-BUF texture via Vulkan"); - Ok(texture) + Ok(ImportedTexture { texture, ownership: Some(ownership) }) } } @@ -46,187 +101,81 @@ impl DmaBufImporter { offsets, } } - - fn import_via_vulkan(&self, device: &wgpu::Device) -> TextureImportResult { - use wgpu::{TextureUses, wgc::api::Vulkan}; - let hal_texture = unsafe { - let hal_device_guard = device.as_hal::(); - let Some(hal_device) = hal_device_guard else { - return Err(TextureImportError::HardwareUnavailable { - reason: "Device is not using Vulkan backend".to_string(), - }); - }; - - let (vk_image, device_memory) = self.create_vulkan_image_from_dmabuf(&hal_device)?; - - let hal_texture = ::Device::texture_from_raw( - &hal_device, - vk_image, - &wgpu::hal::TextureDescriptor { - label: Some("CEF DMA-BUF Texture"), - size: wgpu::Extent3d { - width: self.width, - height: self.height, - depth_or_array_layers: 1, - }, - mip_level_count: 1, - sample_count: 1, - dimension: wgpu::TextureDimension::D2, - format: wgpu_format(self.format)?, - usage: TextureUses::COPY_DST | TextureUses::COPY_SRC | TextureUses::RESOURCE, - memory_flags: wgpu::hal::MemoryFlags::empty(), - view_formats: vec![], - }, - None, - wgpu::hal::vulkan::TextureMemory::Dedicated(device_memory), - ); - - Ok::<_, TextureImportError>(hal_texture) - }?; - - let texture = unsafe { - device.create_texture_from_hal::( - hal_texture, - &texture_descriptor(self.width, self.height, self.format, "CEF DMA-BUF Texture")?, - wgpu::TextureUses::UNINITIALIZED, - ) - }; - - Ok(texture) - } - - fn create_vulkan_image_from_dmabuf(&self, hal_device: &::Device) -> Result<(vk::Image, vk::DeviceMemory), TextureImportError> { - let device = hal_device.raw_device(); - let instance = hal_device.shared_instance().raw_instance(); - - if self.width == 0 || self.height == 0 { - return Err(TextureImportError::InvalidHandle("Invalid DMA-BUF dimensions".to_string())); - } - - let image_create_info = vk::ImageCreateInfo::default() - .image_type(vk::ImageType::TYPE_2D) - .format(vulkan_format(self.format)?) - .extent(vk::Extent3D { - width: self.width, - height: self.height, - depth: 1, - }) - .mip_levels(1) - .array_layers(1) - .samples(vk::SampleCountFlags::TYPE_1) - .tiling(vk::ImageTiling::DRM_FORMAT_MODIFIER_EXT) - .usage(vk::ImageUsageFlags::SAMPLED | vk::ImageUsageFlags::COLOR_ATTACHMENT | vk::ImageUsageFlags::TRANSFER_SRC) - .sharing_mode(vk::SharingMode::EXCLUSIVE); - - let plane_layouts = self - .offsets - .iter() - .zip(&self.strides) - .map(|(&offset, &stride)| vk::SubresourceLayout { - offset: offset as u64, - size: 0, // Will be calculated by driver - row_pitch: stride as u64, - array_pitch: 0, - depth_pitch: 0, - }) - .collect::>(); - let mut drm_format_modifier = vk::ImageDrmFormatModifierExplicitCreateInfoEXT::default() - .drm_format_modifier(self.modifier) - .plane_layouts(&plane_layouts); - - let mut external_memory_info = vk::ExternalMemoryImageCreateInfo::default().handle_types(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT); - - let image_create_info = image_create_info.push_next(&mut drm_format_modifier).push_next(&mut external_memory_info); - - let image = unsafe { - device.create_image(&image_create_info, None).map_err(|e| TextureImportError::VulkanError { - operation: format!("Failed to create Vulkan image: {e:?}"), - })? - }; - - let memory_requirements = unsafe { device.get_image_memory_requirements(image) }; - - // Duplicate the file descriptor - let dup_fd = unsafe { libc::dup(std::os::fd::AsRawFd::as_raw_fd(&self.fds[0])) }; - if dup_fd == -1 { - // SAFETY: the image was created above and never bound or returned. - unsafe { device.destroy_image(image, None) }; - return Err(TextureImportError::PlatformError { - message: "Failed to duplicate DMA-BUF file descriptor".to_string(), - }); - } - - let external_memory_fd = ash::khr::external_memory_fd::Device::new(instance, device); - let mut fd_properties = vk::MemoryFdPropertiesKHR::default(); - if let Err(e) = unsafe { external_memory_fd.get_memory_fd_properties(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT, dup_fd, &mut fd_properties) } { - // SAFETY: import failed and the fd is still ours, need to clean up the image and close the fd - unsafe { - device.destroy_image(image, None); - libc::close(dup_fd); - } - return Err(TextureImportError::VulkanError { - operation: format!("Failed to query DMA-BUF fd memory properties: {e:?}"), - }); - } - - let mut import_memory_fd = vk::ImportMemoryFdInfoKHR::default().handle_type(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT).fd(dup_fd); - - let memory_properties = unsafe { instance.get_physical_device_memory_properties(hal_device.raw_physical_device()) }; - - let compatible_type_bits = memory_requirements.memory_type_bits & fd_properties.memory_type_bits; - let Some(memory_type_index) = find_memory_type_index(compatible_type_bits, vk::MemoryPropertyFlags::empty(), &memory_properties) else { - // SAFETY: import failed and the fd is still ours, need to clean up the image and close the fd - unsafe { - device.destroy_image(image, None); - libc::close(dup_fd); - } - return Err(TextureImportError::VulkanError { - operation: "Failed to find suitable memory type for DMA-BUF".to_string(), - }); - }; - - let allocate_info = vk::MemoryAllocateInfo::default() - .allocation_size(memory_requirements.size) - .memory_type_index(memory_type_index) - .push_next(&mut import_memory_fd); - - let device_memory = match unsafe { device.allocate_memory(&allocate_info, None) } { - Ok(memory) => memory, - Err(e) => { - // SAFETY: import failed and the fd is still ours, need to clean up the image and close the fd - unsafe { - device.destroy_image(image, None); - libc::close(dup_fd); - } - return Err(TextureImportError::VulkanError { - operation: format!("Failed to allocate memory for DMA-BUF: {e:?}"), - }); - } - }; - - if let Err(e) = unsafe { device.bind_image_memory(image, device_memory, 0) } { - // SAFETY: import failed, need to clean up the image and free the memory - unsafe { - device.destroy_image(image, None); - device.free_memory(device_memory, None); - } - return Err(TextureImportError::VulkanError { - operation: format!("Failed to bind memory to image: {e:?}"), - }); - } - - Ok((image, device_memory)) - } } -fn vulkan_format(format: cef_color_type_t) -> Result { - match format { - cef_color_type_t::CEF_COLOR_TYPE_BGRA_8888 => Ok(vk::Format::B8G8R8A8_UNORM), - cef_color_type_t::CEF_COLOR_TYPE_RGBA_8888 => Ok(vk::Format::R8G8B8A8_UNORM), - _ => Err(TextureImportError::UnsupportedFormat { format }), - } +fn ownership_transfer(device: &wgpu::Device, texture: &wgpu::Texture) -> Result { + let (raw_device, local_queue_family, external_queue_family, image) = unsafe { + let (Some(hal_device), Some(hal_texture)) = (device.as_hal::(), texture.as_hal::()) else { + return Err(TextureImportError::HardwareUnavailable { + reason: "Device is not using Vulkan backend".to_string(), + }); + }; + let external_queue_family = if hal_device.enabled_device_extensions().contains(&ash::ext::queue_family_foreign::NAME) { + vk::QUEUE_FAMILY_FOREIGN_EXT + } else { + vk::QUEUE_FAMILY_EXTERNAL + }; + (hal_device.raw_device().clone(), hal_device.queue_family_index(), external_queue_family, hal_texture.raw_handle()) + }; + + let barrier = vk::ImageMemoryBarrier::default() + .image(image) + .subresource_range(vk::ImageSubresourceRange { + aspect_mask: vk::ImageAspectFlags::COLOR, + base_mip_level: 0, + level_count: 1, + base_array_layer: 0, + layer_count: 1, + }) + .old_layout(vk::ImageLayout::GENERAL) + .new_layout(vk::ImageLayout::GENERAL); + + let acquire = record_barrier( + device, + &raw_device, + barrier + .src_queue_family_index(external_queue_family) + .dst_queue_family_index(local_queue_family) + .dst_access_mask(vk::AccessFlags::MEMORY_READ), + vk::PipelineStageFlags::TOP_OF_PIPE, + vk::PipelineStageFlags::ALL_COMMANDS, + )?; + let release = record_barrier( + device, + &raw_device, + barrier + .src_queue_family_index(local_queue_family) + .dst_queue_family_index(external_queue_family) + .src_access_mask(vk::AccessFlags::MEMORY_READ), + vk::PipelineStageFlags::ALL_COMMANDS, + vk::PipelineStageFlags::BOTTOM_OF_PIPE, + )?; + + Ok(OwnershipTransfer { + acquire, + release, + state: TextureUses::COPY_SRC | TextureUses::RESOURCE, + }) } -fn find_memory_type_index(type_filter: u32, properties: vk::MemoryPropertyFlags, mem_properties: &vk::PhysicalDeviceMemoryProperties) -> Option { - (0..mem_properties.memory_type_count).find(|&i| (type_filter & (1 << i)) != 0 && mem_properties.memory_types[i as usize].property_flags.contains(properties)) +fn record_barrier( + device: &wgpu::Device, + raw_device: &ash::Device, + barrier: vk::ImageMemoryBarrier<'_>, + src_stage: vk::PipelineStageFlags, + dst_stage: vk::PipelineStageFlags, +) -> Result { + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("CEF DMA-BUF Ownership Transfer"), + }); + unsafe { + encoder.as_hal_mut::(|hal_encoder| { + let hal_encoder = hal_encoder.ok_or_else(|| TextureImportError::HardwareUnavailable { + reason: "Command encoder is not using Vulkan backend".to_string(), + })?; + raw_device.cmd_pipeline_barrier(hal_encoder.raw_handle(), src_stage, dst_stage, vk::DependencyFlags::empty(), &[], &[], &[barrier]); + Ok::<_, TextureImportError>(()) + })?; + } + Ok(encoder.finish()) } diff --git a/desktop/ui/src/frames/import/iosurface.rs b/desktop/ui/src/frames/import/iosurface.rs index 9e6e2b88e7..c4921444e9 100644 --- a/desktop/ui/src/frames/import/iosurface.rs +++ b/desktop/ui/src/frames/import/iosurface.rs @@ -89,6 +89,6 @@ impl IOSurfaceImporter { texture }; - Ok(unsafe { device.create_texture_from_hal::(hal_tex, &texture_desc, wgpu::TextureUses::UNINITIALIZED) }) + Ok(unsafe { device.create_texture_from_hal::(hal_tex, &texture_desc, wgpu::TextureUses::UNINITIALIZED) }.into()) } } diff --git a/desktop/ui/src/frames/surface.rs b/desktop/ui/src/frames/surface.rs index c4a883381d..c533796ee7 100644 --- a/desktop/ui/src/frames/surface.rs +++ b/desktop/ui/src/frames/surface.rs @@ -1,7 +1,5 @@ use std::sync::{Arc, Mutex}; -#[cfg(feature = "accelerated_paint")] -use super::import::ContentMapping; #[cfg(feature = "accelerated_paint")] use super::resample::Resampler; @@ -33,7 +31,7 @@ impl FrameSurface { return None; }; - if buffer.chunks_exact(4).take(width as usize).all(|pixel| pixel[3] == 0) { + if buffer.as_chunks::<4>().0.iter().take(width as usize).all(|pixel| pixel[3] == 0) { tracing::debug!("Skipping fully transparent frame"); return None; } @@ -81,93 +79,15 @@ impl FrameSurface { #[cfg(feature = "accelerated_paint")] pub(crate) fn import_texture(&self, importer: impl crate::frames::import::TextureImporter, content_rect: crate::frames::import::ContentRect) -> Option { - let imported = match importer.import_to_wgpu(&self.device) { - Ok(texture) => texture, + let output = match importer.import_to_wgpu(&self.device) { + Ok(imported) => imported.copy(&self.device, &self.queue, &self.resampler, content_rect), Err(e) => { tracing::error!("Failed to import remote accelerated frame: {e}"); return None; } }; - let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { - label: Some("CEF Frame Copy Encoder"), - }); - let output = match content_rect.mapping(imported.width(), imported.height()) { - ContentMapping::Identity => { - let output = self.device.create_texture(&wgpu::TextureDescriptor { - label: Some("CEF Imported Frame Copy"), - size: imported.size(), - mip_level_count: 1, - sample_count: 1, - dimension: wgpu::TextureDimension::D2, - format: imported.format(), - usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST, - view_formats: &[], - }); - encoder.copy_texture_to_texture( - wgpu::TexelCopyTextureInfo { - texture: &imported, - mip_level: 0, - origin: wgpu::Origin3d::ZERO, - aspect: wgpu::TextureAspect::All, - }, - wgpu::TexelCopyTextureInfo { - texture: &output, - mip_level: 0, - origin: wgpu::Origin3d::ZERO, - aspect: wgpu::TextureAspect::All, - }, - imported.size(), - ); - output - } - ContentMapping::Scaled(content_rect) => { - let output = self.device.create_texture(&wgpu::TextureDescriptor { - label: Some("CEF Imported Scaled Frame Copy"), - size: wgpu::Extent3d { - width: content_rect.source_width, - height: content_rect.source_height, - depth_or_array_layers: 1, - }, - mip_level_count: 1, - sample_count: 1, - dimension: wgpu::TextureDimension::D2, - format: imported.format(), - usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::RENDER_ATTACHMENT, - view_formats: &[], - }); - let size = wgpu::Extent3d { - width: content_rect.width, - height: content_rect.height, - depth_or_array_layers: 1, - }; - self.resampler.encode( - &mut encoder, - &imported, - wgpu::Origin3d { - x: content_rect.x, - y: content_rect.y, - z: 0, - }, - size, - &output, - ); - output - } - }; - - let blank_check = blank_check::encode_readback(&self.device, &mut encoder, &output); - - let submission = self.queue.submit([encoder.finish()]); - - let blank_check = blank_check.map(); - - let _ = self.device.poll(wgpu::PollType::Wait { - submission_index: Some(submission), - timeout: None, - }); - - if blank_check.check_is_blank() { + if blank_check::is_blank(&self.device, &self.queue, &output) { tracing::debug!("Skipping fully transparent accelerated frame"); return None; } @@ -188,7 +108,7 @@ mod blank_check { const STRIP_BYTES: u32 = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; const STRIP_TEXELS: u32 = STRIP_BYTES / 4; - pub(super) fn encode_readback(device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, texture: &wgpu::Texture) -> PendingBlankCheck { + pub(super) fn is_blank(device: &wgpu::Device, queue: &wgpu_sync::Queue, texture: &wgpu::Texture) -> bool { let buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some("CEF Blank Check"), size: STRIP_BYTES as u64, @@ -196,6 +116,9 @@ mod blank_check { mapped_at_creation: false, }); let width = texture.width().min(STRIP_TEXELS); + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("CEF Blank Check Encoder"), + }); encoder.copy_texture_to_buffer( wgpu::TexelCopyTextureInfo { texture, @@ -221,43 +144,18 @@ mod blank_check { depth_or_array_layers: 1, }, ); - PendingBlankCheck { buffer, width } - } + let submission = queue.submit([encoder.finish()]); - pub(super) struct PendingBlankCheck { - buffer: wgpu::Buffer, - width: u32, - } + let slice = buffer.slice(..u64::from(width) * 4); + let (sender, receiver) = mpsc::channel(); + slice.map_async(wgpu::MapMode::Read, move |result| { + let _ = sender.send(result); + }); + let _ = device.poll(wgpu::PollType::Wait { + submission_index: Some(submission), + timeout: None, + }); - impl PendingBlankCheck { - pub(super) fn map(self) -> MappedBlankCheck { - let (sender, receiver) = mpsc::channel(); - self.buffer.slice(..u64::from(self.width) * 4).map_async(wgpu::MapMode::Read, move |result| { - let _ = sender.send(result); - }); - MappedBlankCheck { - buffer: self.buffer, - width: self.width, - receiver, - } - } - } - - pub(super) struct MappedBlankCheck { - buffer: wgpu::Buffer, - width: u32, - receiver: mpsc::Receiver>, - } - - impl MappedBlankCheck { - pub(super) fn check_is_blank(self) -> bool { - match self.receiver.try_recv() { - Ok(Ok(())) => { - let slice = self.buffer.slice(..u64::from(self.width) * 4); - slice.get_mapped_range().is_ok_and(|view| view.as_chunks::<4>().0.iter().all(|texel| texel[3] == 0)) - } - _ => false, - } - } + matches!(receiver.try_recv(), Ok(Ok(()))) && slice.get_mapped_range().is_ok_and(|view| view.as_chunks::<4>().0.iter().all(|texel| texel[3] == 0)) } } diff --git a/node-graph/libraries/wgpu-executor/src/context.rs b/node-graph/libraries/wgpu-executor/src/context.rs index b85eb8e3a0..e6d439ff41 100644 --- a/node-graph/libraries/wgpu-executor/src/context.rs +++ b/node-graph/libraries/wgpu-executor/src/context.rs @@ -22,6 +22,7 @@ impl Context { pub struct ContextBuilder { backends: Backends, features: Features, + optional_features: Features, selection: Option, } impl ContextBuilder { @@ -29,6 +30,7 @@ impl ContextBuilder { Self { backends: Backends::all(), features: Features::empty(), + optional_features: Features::empty(), selection: None, } } @@ -40,6 +42,10 @@ impl ContextBuilder { self.features = features; self } + pub fn with_optional_features(mut self, features: Features) -> Self { + self.optional_features = features; + self + } pub fn with_selection(mut self, index: usize) -> Self { self.selection = Some(index); self @@ -97,7 +103,7 @@ impl ContextBuilder { async fn request_device(&self, adapter: &Adapter) -> Option<(Device, Queue)> { let device_descriptor = wgpu::DeviceDescriptor { label: None, - required_features: self.features, + required_features: self.features | (self.optional_features & adapter.features()), required_limits: adapter.limits(), memory_hints: Default::default(), trace: wgpu::Trace::Off,