Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Implement D3D11 zero-copy texture sharing and pipeline cache

Richie McIlroya21d2a8397a3
diff --git a/crates/editor/src/editor.rs b/crates/editor/src/editor.rs
index 9e817f2e3..200775522 100644
--- a/crates/editor/src/editor.rs
+++ b/crates/editor/src/editor.rs
@@ -143,7 +143,6 @@ impl Renderer {
break;
}
}
-
let frame = frame_renderer
.render(
current.segment_frames,
@@ -153,7 +152,6 @@ impl Renderer {
)
.await
.unwrap();
-
(self.frame_cb)(frame);
let _ = current.finished.send(());
diff --git a/crates/editor/src/editor_instance.rs b/crates/editor/src/editor_instance.rs
index d9fdc7c74..fb1f2b735 100644
--- a/crates/editor/src/editor_instance.rs
+++ b/crates/editor/src/editor_instance.rs
@@ -441,9 +441,11 @@ impl EditorInstance {
&segment_medias.cursor,
&segment_frames,
);
+ tracing::debug!(frame_number, "Preview: sending frame to renderer");
self.renderer
.render_frame(segment_frames, uniforms, segment_medias.cursor.clone())
.await;
+ tracing::debug!(frame_number, "Preview: renderer accepted frame");
} else {
warn!("Preview renderer: no frames returned for frame {}", frame_number);
}
diff --git a/crates/editor/src/playback.rs b/crates/editor/src/playback.rs
index 4e76a9390..16bbac6de 100644
--- a/crates/editor/src/playback.rs
+++ b/crates/editor/src/playback.rs
@@ -32,7 +32,7 @@ use crate::{
};
const PREFETCH_BUFFER_SIZE: usize = 60;
-const PARALLEL_DECODE_TASKS: usize = 8;
+const PARALLEL_DECODE_TASKS: usize = 4;
const MAX_PREFETCH_AHEAD: u32 = 90;
const PREFETCH_BEHIND: u32 = 15;
const FRAME_CACHE_SIZE: usize = 60;
@@ -150,7 +150,7 @@ impl Playback {
let mut in_flight: FuturesUnordered<PrefetchFuture> = FuturesUnordered::new();
let mut frames_decoded: u32 = 0;
let mut prefetched_behind: HashSet<u32> = HashSet::new();
- const INITIAL_PARALLEL_TASKS: usize = 8;
+ const INITIAL_PARALLEL_TASKS: usize = 4;
const RAMP_UP_AFTER_FRAMES: u32 = 5;
let mut cached_project = prefetch_project.borrow().clone();
@@ -313,6 +313,7 @@ impl Playback {
in_flight_guard.remove(&frame_num);
}
frames_decoded = frames_decoded.saturating_add(1);
+
if let Some(segment_frames) = result {
let _ = prefetch_tx.send(PrefetchedFrame {
frame_number: frame_num,
@@ -353,13 +354,13 @@ impl Playback {
let mut prefetch_buffer: VecDeque<PrefetchedFrame> =
VecDeque::with_capacity(PREFETCH_BUFFER_SIZE);
let mut frame_cache = FrameCache::new(FRAME_CACHE_SIZE);
- let aggressive_skip_threshold = 5u32;
+ let aggressive_skip_threshold = 10u32;
let mut total_frames_rendered = 0u64;
let mut _total_frames_skipped = 0u64;
- let warmup_target_frames = 1usize;
- let warmup_after_first_timeout = Duration::from_millis(16);
+ let warmup_target_frames = 60usize;
+ let warmup_after_first_timeout = Duration::from_millis(1000);
let mut first_frame_time: Option<Instant> = None;
while !*stop_rx.borrow() {
@@ -464,7 +465,7 @@ impl Playback {
if is_in_flight {
let wait_start = Instant::now();
- let max_wait = Duration::from_millis(150);
+ let max_wait = Duration::from_millis(200);
let mut found_frame = None;
while wait_start.elapsed() < max_wait {
@@ -515,7 +516,7 @@ impl Playback {
let _ = frame_request_tx.send(frame_number);
let wait_result = tokio::time::timeout(
- Duration::from_millis(100),
+ Duration::from_millis(200),
prefetch_rx.recv(),
)
.await;
@@ -562,7 +563,7 @@ impl Playback {
guard.insert(frame_number);
}
- let max_wait = Duration::from_millis(150);
+ let max_wait = Duration::from_millis(200);
let data = tokio::select! {
_ = stop_rx.changed() => {
if let Ok(mut guard) = main_in_flight.write() {
@@ -650,7 +651,7 @@ impl Playback {
continue;
}
- let skipped = (frames_behind / 2).min(fps / 4);
+ let skipped = frames_behind.saturating_sub(1);
if skipped > 0 {
frame_number += skipped;
_total_frames_skipped += skipped as u64;
diff --git a/crates/ffmpeg-hw-device/Cargo.toml b/crates/ffmpeg-hw-device/Cargo.toml
index f1fd52e78..e5285acc8 100644
--- a/crates/ffmpeg-hw-device/Cargo.toml
+++ b/crates/ffmpeg-hw-device/Cargo.toml
@@ -5,6 +5,7 @@ edition = "2024"
[dependencies]
ffmpeg.workspace = true
+tracing.workspace = true
workspace-hack = { version = "0.1", path = "../workspace-hack" }
[lints]
diff --git a/crates/rendering/Cargo.toml b/crates/rendering/Cargo.toml
index 5ef892c5a..8727008bc 100644
--- a/crates/rendering/Cargo.toml
+++ b/crates/rendering/Cargo.toml
@@ -33,6 +33,7 @@ tracing.workspace = true
resvg = "0.45"
tiny-skia = "0.11"
clap = { version = "4.5", features = ["derive"] }
+dirs = "5.0"
workspace-hack = { version = "0.1", path = "../workspace-hack" }
[target.'cfg(target_os = "macos")'.dependencies]
@@ -55,6 +56,10 @@ windows = { workspace = true, features = [
"Win32_Graphics_Dxgi_Common",
"Win32_System_Threading",
] }
+windows_0_58 = { package = "windows", version = "0.58", features = [
+ "Win32_Foundation",
+ "Win32_Graphics_Direct3D12",
+] }
[dev-dependencies]
pretty_assertions = "1.4.1"
diff --git a/crates/rendering/src/adapter_luid.rs b/crates/rendering/src/adapter_luid.rs
new file mode 100644
index 000000000..3adc1252d
--- /dev/null
+++ b/crates/rendering/src/adapter_luid.rs
@@ -0,0 +1,67 @@
+#[cfg(target_os = "windows")]
+use windows::Win32::{
+ Foundation::LUID,
+ Graphics::Dxgi::{CreateDXGIFactory1, IDXGIAdapter, IDXGIFactory1},
+};
+
+#[cfg(target_os = "windows")]
+#[derive(Clone, Copy, Debug)]
+pub struct AdapterLuid {
+ pub low: u32,
+ pub high: i32,
+}
+
+#[cfg(target_os = "windows")]
+pub fn detect_adapter_luid_for_wgpu(adapter: &wgpu::Adapter) -> Option<AdapterLuid> {
+ let info = adapter.get_info();
+
+ unsafe {
+ let factory: IDXGIFactory1 = match CreateDXGIFactory1() {
+ Ok(f) => f,
+ Err(_) => return None,
+ };
+
+ let mut i = 0u32;
+ loop {
+ let dxgi_adapter: IDXGIAdapter = match factory.EnumAdapters(i) {
+ Ok(a) => a,
+ Err(_) => break,
+ };
+
+ let desc = match dxgi_adapter.GetDesc() {
+ Ok(d) => d,
+ Err(_) => {
+ i += 1;
+ continue;
+ }
+ };
+
+ let vendor_id = desc.VendorId;
+ let device_id = desc.DeviceId;
+
+ if vendor_id == info.vendor && device_id == info.device {
+ let LUID { LowPart, HighPart } = desc.AdapterLuid;
+ return Some(AdapterLuid {
+ low: LowPart,
+ high: HighPart,
+ });
+ }
+
+ i += 1;
+ }
+ }
+
+ None
+}
+
+#[cfg(not(target_os = "windows"))]
+#[derive(Clone, Copy, Debug)]
+pub struct AdapterLuid {
+ pub low: u32,
+ pub high: i32,
+}
+
+#[cfg(not(target_os = "windows"))]
+pub fn detect_adapter_luid_for_wgpu(_: &wgpu::Adapter) -> Option<AdapterLuid> {
+ None
+}
diff --git a/crates/rendering/src/composite_frame.rs b/crates/rendering/src/composite_frame.rs
index ee39a5f29..9d84b479f 100644
--- a/crates/rendering/src/composite_frame.rs
+++ b/crates/rendering/src/composite_frame.rs
@@ -1,14 +1,68 @@
use bytemuck::{Pod, Zeroable};
use wgpu::{include_wgsl, util::DeviceExt};
-use crate::create_shader_render_pipeline;
-
pub struct CompositeVideoFramePipeline {
pub bind_group_layout: wgpu::BindGroupLayout,
pub render_pipeline: wgpu::RenderPipeline,
sampler: wgpu::Sampler,
}
+static PIPELINE_CACHE_DATA: std::sync::OnceLock<Vec<u8>> = std::sync::OnceLock::new();
+
+fn get_cache_path() -> Option<std::path::PathBuf> {
+ dirs::data_local_dir().map(|p| p.join("Cap").join("shader_cache.bin"))
+}
+
+fn load_pipeline_cache(device: &wgpu::Device) -> Option<wgpu::PipelineCache> {
+ if !device.features().contains(wgpu::Features::PIPELINE_CACHE) {
+ return None;
+ }
+
+ if let Some(cached_data) = PIPELINE_CACHE_DATA.get() {
+ return Some(unsafe {
+ device.create_pipeline_cache(&wgpu::PipelineCacheDescriptor {
+ label: Some("Cap Pipeline Cache"),
+ data: Some(cached_data),
+ fallback: true,
+ })
+ });
+ }
+
+ let cache_path = get_cache_path()?;
+ if cache_path.exists() {
+ if let Ok(data) = std::fs::read(&cache_path) {
+ let _ = PIPELINE_CACHE_DATA.set(data.clone());
+ return Some(unsafe {
+ device.create_pipeline_cache(&wgpu::PipelineCacheDescriptor {
+ label: Some("Cap Pipeline Cache"),
+ data: Some(&data),
+ fallback: true,
+ })
+ });
+ }
+ }
+
+ Some(unsafe {
+ device.create_pipeline_cache(&wgpu::PipelineCacheDescriptor {
+ label: Some("Cap Pipeline Cache"),
+ data: None,
+ fallback: true,
+ })
+ })
+}
+
+fn save_pipeline_cache(cache: &wgpu::PipelineCache) {
+ if let Some(data) = cache.get_data() {
+ let _ = PIPELINE_CACHE_DATA.set(data.clone());
+ if let Some(cache_path) = get_cache_path() {
+ if let Some(parent) = cache_path.parent() {
+ let _ = std::fs::create_dir_all(parent);
+ }
+ let _ = std::fs::write(cache_path, &data);
+ }
+ }
+}
+
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
#[repr(C)]
pub struct CompositeVideoFrameUniforms {
@@ -86,12 +140,64 @@ impl CompositeVideoFrameUniforms {
impl CompositeVideoFramePipeline {
pub fn new(device: &wgpu::Device) -> Self {
+ let pipeline_cache = load_pipeline_cache(device);
let bind_group_layout = Self::bind_group_layout(device);
- let render_pipeline = create_shader_render_pipeline(
- device,
- &bind_group_layout,
- include_wgsl!("shaders/composite-video-frame.wgsl"),
- );
+ let shader_desc = include_wgsl!("shaders/composite-video-frame.wgsl");
+ let shader = device.create_shader_module(shader_desc);
+
+ let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: Some("Composite Render Pipeline Layout"),
+ bind_group_layouts: &[&bind_group_layout],
+ push_constant_ranges: &[],
+ });
+
+ let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: Some("Composite Render Pipeline"),
+ layout: Some(&pipeline_layout),
+ vertex: wgpu::VertexState {
+ module: &shader,
+ entry_point: Some("vs_main"),
+ buffers: &[],
+ compilation_options: wgpu::PipelineCompilationOptions {
+ constants: &[],
+ zero_initialize_workgroup_memory: false,
+ },
+ },
+ fragment: Some(wgpu::FragmentState {
+ module: &shader,
+ entry_point: Some("fs_main"),
+ targets: &[Some(wgpu::ColorTargetState {
+ format: wgpu::TextureFormat::Rgba8Unorm,
+ blend: Some(wgpu::BlendState::ALPHA_BLENDING),
+ write_mask: wgpu::ColorWrites::ALL,
+ })],
+ compilation_options: wgpu::PipelineCompilationOptions {
+ constants: &[],
+ zero_initialize_workgroup_memory: false,
+ },
+ }),
+ primitive: wgpu::PrimitiveState {
+ topology: wgpu::PrimitiveTopology::TriangleList,
+ strip_index_format: None,
+ front_face: wgpu::FrontFace::Ccw,
+ cull_mode: Some(wgpu::Face::Back),
+ polygon_mode: wgpu::PolygonMode::Fill,
+ unclipped_depth: false,
+ conservative: false,
+ },
+ depth_stencil: None,
+ multisample: wgpu::MultisampleState {
+ count: 1,
+ mask: !0,
+ alpha_to_coverage_enabled: false,
+ },
+ multiview: None,
+ cache: pipeline_cache.as_ref(),
+ });
+
+ if let Some(cache) = &pipeline_cache {
+ save_pipeline_cache(cache);
+ }
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
address_mode_u: wgpu::AddressMode::ClampToEdge,
diff --git a/crates/rendering/src/d3d_texture.rs b/crates/rendering/src/d3d_texture.rs
index e7201faee..d117d6f41 100644
--- a/crates/rendering/src/d3d_texture.rs
+++ b/crates/rendering/src/d3d_texture.rs
@@ -6,6 +6,8 @@ pub enum D3DTextureError {
WgpuImportFailed(String),
UnsupportedFormat,
DeviceMismatch,
+ OpenSharedHandleFailed(String),
+ HalTextureCreationFailed(String),
#[cfg(not(target_os = "windows"))]
NotSupported,
}
@@ -19,6 +21,8 @@ impl std::fmt::Display for D3DTextureError {
Self::WgpuImportFailed(e) => write!(f, "Failed to import texture to wgpu: {e}"),
Self::UnsupportedFormat => write!(f, "Unsupported pixel format for zero-copy"),
Self::DeviceMismatch => write!(f, "D3D11 and D3D12 device mismatch"),
+ Self::OpenSharedHandleFailed(e) => write!(f, "Failed to open shared handle: {e}"),
+ Self::HalTextureCreationFailed(e) => write!(f, "Failed to create HAL texture: {e}"),
#[cfg(not(target_os = "windows"))]
Self::NotSupported => write!(f, "D3D textures are only supported on Windows"),
}
@@ -30,6 +34,8 @@ impl std::error::Error for D3DTextureError {}
#[cfg(target_os = "windows")]
mod windows_impl {
use super::D3DTextureError;
+ use std::sync::atomic::{AtomicBool, Ordering};
+ use wgpu_hal::api::Dx12 as dx12;
use windows::{
Win32::{
Foundation::HANDLE,
@@ -185,7 +191,8 @@ mod windows_impl {
}
}
- #[allow(unused_variables)]
+ static ZERO_COPY_LOGGED: AtomicBool = AtomicBool::new(false);
+
pub fn import_d3d11_texture_to_wgpu(
device: &wgpu::Device,
shared_handle: HANDLE,
@@ -194,26 +201,115 @@ mod windows_impl {
height: u32,
label: Option<&str>,
) -> Result<wgpu::Texture, D3DTextureError> {
- Err(D3DTextureError::WgpuImportFailed(
- "D3D11-to-wgpu HAL interop not yet implemented - requires wgpu HAL API updates"
- .to_string(),
- ))
+ let dxgi_format = wgpu_to_dxgi_format(format);
+ if dxgi_format == DXGI_FORMAT_UNKNOWN {
+ return Err(D3DTextureError::UnsupportedFormat);
+ }
+
+ let handle_raw_value = shared_handle.0 as isize;
+
+ let result: Result<wgpu::Texture, D3DTextureError> = unsafe {
+ device.as_hal::<dx12, _, _>(|hal_device| {
+ let hal_device = hal_device.ok_or(D3DTextureError::NoD3D12Device)?;
+
+ let d3d12_device = hal_device.raw_device();
+
+ use windows_0_58::Win32::Foundation::HANDLE as HAL_HANDLE;
+ use windows_0_58::Win32::Graphics::Direct3D12::ID3D12Resource;
+
+ let hal_handle = HAL_HANDLE(handle_raw_value as *mut std::ffi::c_void);
+
+ let mut d3d12_resource: Option<ID3D12Resource> = None;
+ d3d12_device
+ .OpenSharedHandle(hal_handle, &mut d3d12_resource)
+ .map_err(|e| D3DTextureError::OpenSharedHandleFailed(format!("{e:?}")))?;
+ let d3d12_resource = d3d12_resource.ok_or_else(|| {
+ D3DTextureError::OpenSharedHandleFailed(
+ "OpenSharedHandle returned null".to_string(),
+ )
+ })?;
+
+ let hal_texture = wgpu_hal::dx12::Device::texture_from_raw(
+ d3d12_resource,
+ format,
+ wgpu::TextureDimension::D2,
+ wgpu::Extent3d {
+ width,
+ height,
+ depth_or_array_layers: 1,
+ },
+ 1,
+ 1,
+ );
+
+ if !ZERO_COPY_LOGGED.swap(true, Ordering::Relaxed) {
+ tracing::info!(
+ "D3D11→D3D12 zero-copy texture sharing enabled via shared handles"
+ );
+ }
+
+ tracing::debug!(
+ width = width,
+ height = height,
+ format = ?format,
+ "Opened D3D12 shared texture from D3D11 handle"
+ );
+
+ let wgpu_texture = device.create_texture_from_hal::<dx12>(
+ hal_texture,
+ &wgpu::TextureDescriptor {
+ label,
+ size: wgpu::Extent3d {
+ width,
+ height,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format,
+ usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC,
+ view_formats: &[],
+ },
+ );
+
+ Ok(wgpu_texture)
+ })
+ };
+
+ result
}
- #[derive(Default)]
pub struct D3D11WgpuInterop {
- _cached_width: u32,
- _cached_height: u32,
- _y_wgpu_texture: Option<wgpu::Texture>,
- _uv_wgpu_texture: Option<wgpu::Texture>,
+ cached_width: u32,
+ cached_height: u32,
+ y_wgpu_texture: Option<wgpu::Texture>,
+ uv_wgpu_texture: Option<wgpu::Texture>,
+ last_y_handle: Option<isize>,
+ last_uv_handle: Option<isize>,
+ }
+
+ unsafe impl Send for D3D11WgpuInterop {}
+ unsafe impl Sync for D3D11WgpuInterop {}
+
+ impl Default for D3D11WgpuInterop {
+ fn default() -> Self {
+ Self::new()
+ }
}
impl D3D11WgpuInterop {
pub fn new() -> Self {
- Self::default()
+ Self {
+ cached_width: 0,
+ cached_height: 0,
+ y_wgpu_texture: None,
+ uv_wgpu_texture: None,
+ last_y_handle: None,
+ last_uv_handle: None,
+ }
}
- #[allow(unused_variables)]
pub fn import_nv12_planes(
&mut self,
device: &wgpu::Device,
@@ -222,10 +318,59 @@ mod windows_impl {
width: u32,
height: u32,
) -> Result<(&wgpu::Texture, &wgpu::Texture), D3DTextureError> {
- Err(D3DTextureError::WgpuImportFailed(
- "D3D11-to-wgpu HAL interop not yet implemented".to_string(),
+ let y_handle_value = y_handle.0 as isize;
+ let uv_handle_value = uv_handle.0 as isize;
+
+ let need_recreate = self.cached_width != width
+ || self.cached_height != height
+ || self.last_y_handle != Some(y_handle_value)
+ || self.last_uv_handle != Some(uv_handle_value)
+ || self.y_wgpu_texture.is_none()
+ || self.uv_wgpu_texture.is_none();
+
+ if need_recreate {
+ self.y_wgpu_texture = Some(import_d3d11_texture_to_wgpu(
+ device,
+ y_handle,
+ wgpu::TextureFormat::R8Unorm,
+ width,
+ height,
+ Some("D3D11 Y Plane Zero-Copy"),
+ )?);
+
+ self.uv_wgpu_texture = Some(import_d3d11_texture_to_wgpu(
+ device,
+ uv_handle,
+ wgpu::TextureFormat::Rg8Unorm,
+ width / 2,
+ height / 2,
+ Some("D3D11 UV Plane Zero-Copy"),
+ )?);
+
+ self.cached_width = width;
+ self.cached_height = height;
+ self.last_y_handle = Some(y_handle_value);
+ self.last_uv_handle = Some(uv_handle_value);
+
+ tracing::debug!(
+ width = width,
+ height = height,
+ "Created zero-copy NV12 textures from D3D11 shared handles"
+ );
+ }
+
+ Ok((
+ self.y_wgpu_texture.as_ref().unwrap(),
+ self.uv_wgpu_texture.as_ref().unwrap(),
))
}
+
+ pub fn invalidate(&mut self) {
+ self.y_wgpu_texture = None;
+ self.uv_wgpu_texture = None;
+ self.last_y_handle = None;
+ self.last_uv_handle = None;
+ }
}
}
diff --git a/crates/rendering/src/decoder/media_foundation.rs b/crates/rendering/src/decoder/media_foundation.rs
index ee8d46e08..706ff986d 100644
--- a/crates/rendering/src/decoder/media_foundation.rs
+++ b/crates/rendering/src/decoder/media_foundation.rs
@@ -99,6 +99,20 @@ struct CachedFrame {
impl CachedFrame {
fn to_decoded_frame(&self) -> DecodedFrame {
+ let null_ptr = std::ptr::null_mut();
+ let y_handle = self._y_handle.filter(|h| h.0 != null_ptr);
+ let uv_handle = self._uv_handle.filter(|h| h.0 != null_ptr);
+ if let (Some(y_handle), Some(uv_handle)) = (y_handle, uv_handle) {
+ return DecodedFrame::new_nv12_with_d3d11_texture_and_yuv_handles(
+ self.width,
+ self.height,
+ self._texture.clone(),
+ self._shared_handle,
+ Some(y_handle),
+ Some(uv_handle),
+ );
+ }
+
if let Some(nv12_data) = &self.nv12_data {
DecodedFrame::new_nv12(
nv12_data.data.clone(),
@@ -237,7 +251,7 @@ impl MFDecoder {
let frame_number = pts_100ns_to_frame(mf_frame.pts, fps);
let nv12_data = match decoder.read_texture_to_cpu(
- &mf_frame.texture,
+ &mf_frame.textures.nv12.texture,
mf_frame.width,
mf_frame.height,
) {
@@ -256,10 +270,10 @@ impl MFDecoder {
let cached = CachedFrame {
number: frame_number,
- _texture: mf_frame.texture,
- _shared_handle: mf_frame.shared_handle,
- _y_handle: mf_frame.y_handle,
- _uv_handle: mf_frame.uv_handle,
+ _texture: mf_frame.textures.nv12.texture.clone(),
+ _shared_handle: Some(mf_frame.textures.nv12.handle),
+ _y_handle: Some(mf_frame.textures.y.handle),
+ _uv_handle: Some(mf_frame.textures.uv.handle),
nv12_data,
width: mf_frame.width,
height: mf_frame.height,
@@ -297,10 +311,11 @@ impl MFDecoder {
{
let _ = s.send(frame.to_decoded_frame());
}
- break;
}
- if frame_number > cache_max {
+ let readahead_target = requested_frame + 30;
+ if frame_number >= readahead_target || frame_number > cache_max
+ {
break;
}
}
diff --git a/crates/rendering/src/decoder/mod.rs b/crates/rendering/src/decoder/mod.rs
index 0a5b4a289..81cf7a3db 100644
--- a/crates/rendering/src/decoder/mod.rs
+++ b/crates/rendering/src/decoder/mod.rs
@@ -7,8 +7,6 @@ use std::{
};
use tokio::sync::oneshot;
use tracing::info;
-#[cfg(target_os = "windows")]
-use tracing::warn;
#[cfg(target_os = "macos")]
mod avassetreader;
@@ -548,65 +546,20 @@ pub async fn spawn_decoder(
let (ready_tx, ready_rx) = oneshot::channel::<Result<DecoderInitResult, String>>();
let (tx, rx) = mpsc::channel();
- if let Ok(()) = media_foundation::MFDecoder::spawn(name, path.clone(), fps, rx, ready_tx) {
- match tokio::time::timeout(timeout_duration, ready_rx).await {
- Ok(Ok(Ok(init_result))) => {
- info!(
- "Video '{}' using {} decoder ({}x{})",
- name, init_result.decoder_type, init_result.width, init_result.height
- );
- let status = DecoderStatus {
- decoder_type: init_result.decoder_type,
- video_width: init_result.width,
- video_height: init_result.height,
- fallback_reason: None,
- };
- return Ok(AsyncVideoDecoderHandle {
- sender: tx,
- offset,
- status,
- });
- }
- Ok(Ok(Err(e))) => {
- warn!(
- "MediaFoundation decoder ready but failed for '{}': {}, falling back to FFmpeg",
- name, e
- );
- }
- Ok(Err(e)) => {
- warn!(
- "MediaFoundation decoder channel closed for '{}': {}, falling back to FFmpeg",
- name, e
- );
- }
- Err(_) => {
- warn!(
- "MediaFoundation decoder timed out for '{}', falling back to FFmpeg",
- name
- );
- }
- }
- }
-
- let fallback_reason =
- format!("MediaFoundation decoder unavailable for '{name}', using FFmpeg fallback");
- let (ready_tx, ready_rx) = oneshot::channel::<Result<DecoderInitResult, String>>();
- let (tx, rx) = mpsc::channel();
-
ffmpeg::FfmpegDecoder::spawn(name, path, fps, rx, ready_tx)
- .map_err(|e| format!("'{name}' FFmpeg fallback decoder / {e}"))?;
+ .map_err(|e| format!("'{name}' FFmpeg decoder / {e}"))?;
match tokio::time::timeout(timeout_duration, ready_rx).await {
Ok(Ok(Ok(init_result))) => {
info!(
- "Video '{}' using {} decoder ({}x{}) [fallback]",
+ "Video '{}' using {} decoder ({}x{})",
name, init_result.decoder_type, init_result.width, init_result.height
);
let status = DecoderStatus {
decoder_type: init_result.decoder_type,
video_width: init_result.width,
video_height: init_result.height,
- fallback_reason: Some(fallback_reason),
+ fallback_reason: None,
};
Ok(AsyncVideoDecoderHandle {
sender: tx,
diff --git a/crates/rendering/src/layers/camera.rs b/crates/rendering/src/layers/camera.rs
index a0c1d85c3..60ff16b6a 100644
--- a/crates/rendering/src/layers/camera.rs
+++ b/crates/rendering/src/layers/camera.rs
@@ -1,9 +1,11 @@
use cap_project::XY;
+use std::sync::Arc;
use wgpu::util::DeviceExt;
use crate::{
CompositeVideoFrameUniforms, DecodedFrame, PixelFormat,
- composite_frame::CompositeVideoFramePipeline, yuv_converter::YuvToRgbaConverter,
+ composite_frame::CompositeVideoFramePipeline,
+ yuv_converter::{YuvConverterPipelines, YuvToRgbaConverter},
};
pub struct CameraLayer {
@@ -12,7 +14,7 @@ pub struct CameraLayer {
current_texture: usize,
uniforms_buffer: wgpu::Buffer,
bind_groups: [Option<wgpu::BindGroup>; 2],
- pipeline: CompositeVideoFramePipeline,
+ pipeline: Arc<CompositeVideoFramePipeline>,
hidden: bool,
last_recording_time: Option<f32>,
yuv_converter: YuvToRgbaConverter,
@@ -20,13 +22,31 @@ pub struct CameraLayer {
impl CameraLayer {
pub fn new(device: &wgpu::Device) -> Self {
+ Self::new_with_all_shared_pipelines(
+ device,
+ Arc::new(YuvConverterPipelines::new(device)),
+ Arc::new(CompositeVideoFramePipeline::new(device)),
+ )
+ }
+
+ pub fn new_with_shared_pipelines(
+ device: &wgpu::Device,
+ yuv_pipelines: Arc<YuvConverterPipelines>,
+ composite_pipeline: Arc<CompositeVideoFramePipeline>,
+ ) -> Self {
+ Self::new_with_all_shared_pipelines(device, yuv_pipelines, composite_pipeline)
+ }
+
+ pub fn new_with_all_shared_pipelines(
+ device: &wgpu::Device,
+ yuv_pipelines: Arc<YuvConverterPipelines>,
+ composite_pipeline: Arc<CompositeVideoFramePipeline>,
+ ) -> Self {
let frame_texture_0 = CompositeVideoFramePipeline::create_frame_texture(device, 1920, 1080);
let frame_texture_1 = CompositeVideoFramePipeline::create_frame_texture(device, 1920, 1080);
let frame_texture_view_0 = frame_texture_0.create_view(&Default::default());
let frame_texture_view_1 = frame_texture_1.create_view(&Default::default());
- let pipeline = CompositeVideoFramePipeline::new(device);
-
let uniforms_buffer = device.create_buffer_init(
&(wgpu::util::BufferInitDescriptor {
label: Some("CameraLayer Uniforms Buffer"),
@@ -36,11 +56,11 @@ impl CameraLayer {
);
let bind_group_0 =
- Some(pipeline.bind_group(device, &uniforms_buffer, &frame_texture_view_0));
+ Some(composite_pipeline.bind_group(device, &uniforms_buffer, &frame_texture_view_0));
let bind_group_1 =
- Some(pipeline.bind_group(device, &uniforms_buffer, &frame_texture_view_1));
+ Some(composite_pipeline.bind_group(device, &uniforms_buffer, &frame_texture_view_1));
- let yuv_converter = YuvToRgbaConverter::new(device);
+ let yuv_converter = YuvToRgbaConverter::new_with_shared_pipelines(device, yuv_pipelines);
Self {
frame_textures: [frame_texture_0, frame_texture_1],
@@ -48,7 +68,7 @@ impl CameraLayer {
current_texture: 0,
uniforms_buffer,
bind_groups: [bind_group_0, bind_group_1],
- pipeline,
+ pipeline: composite_pipeline,
hidden: false,
last_recording_time: None,
yuv_converter,
@@ -130,6 +150,59 @@ impl CameraLayer {
);
}
PixelFormat::Nv12 => {
+ if let Err(e) = self.yuv_converter.prepare_for_dimensions(
+ device,
+ frame_size.x,
+ frame_size.y,
+ ) {
+ tracing::warn!(error = %e, "YUV converter prepare failed");
+ return;
+ }
+
+ #[cfg(target_os = "windows")]
+ {
+ if let Some(nv12_texture) = camera_frame.d3d11_texture_backing() {
+ if let Ok(d3d11_device) = unsafe { nv12_texture.GetDevice() } {
+ if let Ok(d3d11_context) =
+ unsafe { d3d11_device.GetImmediateContext() }
+ {
+ if self
+ .yuv_converter
+ .convert_nv12_with_fallback(
+ device,
+ queue,
+ &d3d11_device,
+ &d3d11_context,
+ nv12_texture,
+ camera_frame.d3d11_y_handle(),
+ camera_frame.d3d11_uv_handle(),
+ frame_size.x,
+ frame_size.y,
+ )
+ .is_ok()
+ && self.yuv_converter.output_texture().is_some()
+ {
+ self.copy_from_yuv_output(
+ device,
+ queue,
+ next_texture,
+ frame_size,
+ );
+ self.last_recording_time = Some(recording_time);
+ self.current_texture = next_texture;
+ return;
+ }
+ } else {
+ tracing::warn!(
+ "Failed to get D3D11 immediate context for camera frame"
+ );
+ }
+ } else {
+ tracing::warn!("Failed to get D3D11 device for camera frame");
+ }
+ }
+ }
+
if let (Some(y_data), Some(uv_data)) =
(camera_frame.y_plane(), camera_frame.uv_plane())
&& self
@@ -150,6 +223,15 @@ impl CameraLayer {
}
}
PixelFormat::Yuv420p => {
+ if let Err(e) = self.yuv_converter.prepare_for_dimensions(
+ device,
+ frame_size.x,
+ frame_size.y,
+ ) {
+ tracing::warn!(error = %e, "YUV converter prepare failed");
+ return;
+ }
+
if let (Some(y_data), Some(u_data), Some(v_data)) = (
camera_frame.y_plane(),
camera_frame.u_plane(),
diff --git a/crates/rendering/src/layers/display.rs b/crates/rendering/src/layers/display.rs
index 898ad16d0..e7669c391 100644
--- a/crates/rendering/src/layers/display.rs
+++ b/crates/rendering/src/layers/display.rs
@@ -241,44 +241,45 @@ impl DisplayLayer {
let y_stride = screen_frame.y_stride();
let uv_stride = screen_frame.uv_stride();
- let convert_result = if self.prefer_cpu_conversion {
- self.yuv_converter.convert_nv12_cpu(
- device,
- queue,
- y_data,
- uv_data,
- actual_width,
- actual_height,
- y_stride,
- uv_stride,
- )
+ let convert_ok = if self.prefer_cpu_conversion {
+ self.yuv_converter
+ .convert_nv12_cpu(
+ device,
+ queue,
+ y_data,
+ uv_data,
+ actual_width,
+ actual_height,
+ y_stride,
+ uv_stride,
+ )
+ .is_ok()
} else {
- self.yuv_converter.convert_nv12(
- device,
- queue,
- y_data,
- uv_data,
- actual_width,
- actual_height,
- y_stride,
- uv_stride,
- )
+ self.yuv_converter
+ .convert_nv12(
+ device,
+ queue,
+ y_data,
+ uv_data,
+ actual_width,
+ actual_height,
+ y_stride,
+ uv_stride,
+ )
+ .is_ok()
};
- match convert_result {
- Ok(_) => {
- if self.yuv_converter.output_texture().is_some() {
- self.pending_copy = Some(PendingTextureCopy {
- width: actual_width,
- height: actual_height,
- dst_texture_index: next_texture,
- });
- true
- } else {
- false
- }
- }
- Err(_) => false,
+ let has_output = self.yuv_converter.output_texture().is_some();
+
+ if convert_ok && has_output {
+ self.pending_copy = Some(PendingTextureCopy {
+ width: actual_width,
+ height: actual_height,
+ dst_texture_index: next_texture,
+ });
+ true
+ } else {
+ false
}
} else {
false
diff --git a/crates/rendering/src/yuv_converter.rs b/crates/rendering/src/yuv_converter.rs
index a4fe8e58e..e93c29f30 100644
--- a/crates/rendering/src/yuv_converter.rs
+++ b/crates/rendering/src/yuv_converter.rs
@@ -121,15 +121,6 @@ fn validate_dimensions(
let new_width = ((width as f32 * scale) as u32).max(2) & !1;
let new_height = ((height as f32 * scale) as u32).max(2) & !1;
- tracing::warn!(
- original_width = width,
- original_height = height,
- scaled_width = new_width,
- scaled_height = new_height,
- gpu_max = gpu_max_texture_size,
- "Video dimensions exceed GPU limits, downscaling enabled"
- );
-
Ok((new_width, new_height, true))
}
@@ -249,46 +240,18 @@ impl BindGroupCache {
}
}
-pub struct YuvToRgbaConverter {
- nv12_pipeline: wgpu::ComputePipeline,
- yuv420p_pipeline: wgpu::ComputePipeline,
- nv12_bind_group_layout: wgpu::BindGroupLayout,
- yuv420p_bind_group_layout: wgpu::BindGroupLayout,
- y_texture: wgpu::Texture,
- y_view: wgpu::TextureView,
- uv_texture: wgpu::Texture,
- uv_view: wgpu::TextureView,
- u_texture: wgpu::Texture,
- u_view: wgpu::TextureView,
- v_texture: wgpu::Texture,
- v_view: wgpu::TextureView,
- output_textures: [wgpu::Texture; 2],
- output_views: [wgpu::TextureView; 2],
- current_output: usize,
- allocated_width: u32,
- allocated_height: u32,
- gpu_max_texture_size: u32,
- bind_group_cache: BindGroupCache,
- #[cfg(target_os = "macos")]
- iosurface_cache: Option<IOSurfaceTextureCache>,
- #[cfg(target_os = "windows")]
- d3d11_staging_texture: Option<ID3D11Texture2D>,
- #[cfg(target_os = "windows")]
- d3d11_staging_width: u32,
- #[cfg(target_os = "windows")]
- d3d11_staging_height: u32,
- #[cfg(target_os = "windows")]
- zero_copy_failed: bool,
+use std::sync::Arc;
+
+pub struct YuvConverterPipelines {
+ pub nv12_pipeline: wgpu::ComputePipeline,
+ pub yuv420p_pipeline: wgpu::ComputePipeline,
+ pub nv12_bind_group_layout: wgpu::BindGroupLayout,
+ pub yuv420p_bind_group_layout: wgpu::BindGroupLayout,
}
-impl YuvToRgbaConverter {
+impl YuvConverterPipelines {
pub fn new(device: &wgpu::Device) -> Self {
- let gpu_max_texture_size = device.limits().max_texture_dimension_2d;
-
- tracing::info!(
- gpu_max_texture_size = gpu_max_texture_size,
- "Initializing YUV converter with GPU texture limit"
- );
+ tracing::info!("Creating shared YUV converter pipelines (shader compilation)");
let nv12_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("NV12 to RGBA Converter"),
@@ -419,6 +382,63 @@ impl YuvToRgbaConverter {
cache: None,
});
+ tracing::info!("Shared YUV converter pipelines created successfully");
+
+ Self {
+ nv12_pipeline,
+ yuv420p_pipeline,
+ nv12_bind_group_layout,
+ yuv420p_bind_group_layout,
+ }
+ }
+}
+
+pub struct YuvToRgbaConverter {
+ pipelines: Arc<YuvConverterPipelines>,
+ y_texture: wgpu::Texture,
+ y_view: wgpu::TextureView,
+ uv_texture: wgpu::Texture,
+ uv_view: wgpu::TextureView,
+ u_texture: wgpu::Texture,
+ u_view: wgpu::TextureView,
+ v_texture: wgpu::Texture,
+ v_view: wgpu::TextureView,
+ output_textures: [wgpu::Texture; 2],
+ output_views: [wgpu::TextureView; 2],
+ current_output: usize,
+ allocated_width: u32,
+ allocated_height: u32,
+ gpu_max_texture_size: u32,
+ bind_group_cache: BindGroupCache,
+ #[cfg(target_os = "macos")]
+ iosurface_cache: Option<IOSurfaceTextureCache>,
+ #[cfg(target_os = "windows")]
+ d3d11_staging_texture: Option<ID3D11Texture2D>,
+ #[cfg(target_os = "windows")]
+ d3d11_staging_width: u32,
+ #[cfg(target_os = "windows")]
+ d3d11_staging_height: u32,
+ #[cfg(target_os = "windows")]
+ zero_copy_failed: bool,
+}
+
+impl YuvToRgbaConverter {
+ pub fn new(device: &wgpu::Device) -> Self {
+ let pipelines = Arc::new(YuvConverterPipelines::new(device));
+ Self::new_with_shared_pipelines(device, pipelines)
+ }
+
+ pub fn new_with_shared_pipelines(
+ device: &wgpu::Device,
+ pipelines: Arc<YuvConverterPipelines>,
+ ) -> Self {
+ let gpu_max_texture_size = device.limits().max_texture_dimension_2d;
+
+ tracing::info!(
+ gpu_max_texture_size = gpu_max_texture_size,
+ "Initializing YUV converter textures (using shared pipelines)"
+ );
+
let initial_width = INITIAL_TEXTURE_WIDTH;
let initial_height = INITIAL_TEXTURE_HEIGHT;
@@ -430,10 +450,7 @@ impl YuvToRgbaConverter {
Self::create_output_textures(device, initial_width, initial_height);
Self {
- nv12_pipeline,
- yuv420p_pipeline,
- nv12_bind_group_layout,
- yuv420p_bind_group_layout,
+ pipelines,
y_texture,
y_view,
uv_texture,
@@ -632,6 +649,18 @@ impl YuvToRgbaConverter {
self.gpu_max_texture_size
}
+ pub fn prepare_for_dimensions(
+ &mut self,
+ device: &wgpu::Device,
+ width: u32,
+ height: u32,
+ ) -> Result<(), YuvConversionError> {
+ let (effective_width, effective_height, _) =
+ validate_dimensions(width, height, self.gpu_max_texture_size)?;
+ self.ensure_texture_size(device, effective_width, effective_height);
+ Ok(())
+ }
+
fn swap_output_buffer(&mut self) {
self.current_output = 1 - self.current_output;
}
@@ -696,7 +725,7 @@ impl YuvToRgbaConverter {
let output_index = self.current_output;
let bind_group = self.bind_group_cache.get_or_create_nv12(
device,
- &self.nv12_bind_group_layout,
+ &self.pipelines.nv12_bind_group_layout,
&self.y_view,
&self.uv_view,
&self.output_views[output_index],
@@ -714,7 +743,7 @@ impl YuvToRgbaConverter {
label: Some("NV12 Conversion Pass"),
..Default::default()
});
- compute_pass.set_pipeline(&self.nv12_pipeline);
+ compute_pass.set_pipeline(&self.pipelines.nv12_pipeline);
compute_pass.set_bind_group(0, bind_group, &[]);
compute_pass.dispatch_workgroups(width.div_ceil(8), height.div_ceil(8), 1);
}
@@ -774,7 +803,7 @@ impl YuvToRgbaConverter {
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("NV12 IOSurface Converter Bind Group"),
- layout: &self.nv12_bind_group_layout,
+ layout: &self.pipelines.nv12_bind_group_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
@@ -800,7 +829,7 @@ impl YuvToRgbaConverter {
label: Some("NV12 IOSurface Conversion Pass"),
..Default::default()
});
- compute_pass.set_pipeline(&self.nv12_pipeline);
+ compute_pass.set_pipeline(&self.pipelines.nv12_pipeline);
compute_pass.set_bind_group(0, &bind_group, &[]);
compute_pass.dispatch_workgroups(width.div_ceil(8), height.div_ceil(8), 1);
}
@@ -855,7 +884,7 @@ impl YuvToRgbaConverter {
let output_index = self.current_output;
let bind_group = self.bind_group_cache.get_or_create_yuv420p(
device,
- &self.yuv420p_bind_group_layout,
+ &self.pipelines.yuv420p_bind_group_layout,
&self.y_view,
&self.u_view,
&self.v_view,
@@ -874,7 +903,7 @@ impl YuvToRgbaConverter {
label: Some("YUV420P Conversion Pass"),
..Default::default()
});
- compute_pass.set_pipeline(&self.yuv420p_pipeline);
+ compute_pass.set_pipeline(&self.pipelines.yuv420p_pipeline);
compute_pass.set_bind_group(0, bind_group, &[]);
compute_pass.dispatch_workgroups(width.div_ceil(8), height.div_ceil(8), 1);
}
@@ -899,6 +928,11 @@ impl YuvToRgbaConverter {
let (effective_width, effective_height, _downscaled) =
validate_dimensions(width, height, self.gpu_max_texture_size)?;
self.ensure_texture_size(wgpu_device, effective_width, effective_height);
+ tracing::debug!(
+ width = width,
+ height = height,
+ "Using staging NV12 conversion path"
+ );
use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_NV12;
@@ -1006,7 +1040,7 @@ impl YuvToRgbaConverter {
let bind_group = wgpu_device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("NV12 D3D11 Converter Bind Group"),
- layout: &self.nv12_bind_group_layout,
+ layout: &self.pipelines.nv12_bind_group_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
@@ -1032,7 +1066,7 @@ impl YuvToRgbaConverter {
label: Some("NV12 D3D11 Conversion Pass"),
..Default::default()
});
- compute_pass.set_pipeline(&self.nv12_pipeline);
+ compute_pass.set_pipeline(&self.pipelines.nv12_pipeline);
compute_pass.set_bind_group(0, &bind_group, &[]);
compute_pass.dispatch_workgroups(width.div_ceil(8), height.div_ceil(8), 1);
}
@@ -1080,6 +1114,13 @@ impl YuvToRgbaConverter {
match (y_import_result, uv_import_result) {
(Ok(y_wgpu_texture), Ok(uv_wgpu_texture)) => {
+ tracing::debug!(
+ width = width,
+ height = height,
+ y_handle = y_handle.0 as usize,
+ uv_handle = uv_handle.0 as usize,
+ "Zero-copy D3D11 texture import starting"
+ );
tracing::debug!(
width = width,
height = height,
@@ -1091,7 +1132,7 @@ impl YuvToRgbaConverter {
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("NV12 D3D11 Zero-Copy Converter Bind Group"),
- layout: &self.nv12_bind_group_layout,
+ layout: &self.pipelines.nv12_bind_group_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
@@ -1120,7 +1161,7 @@ impl YuvToRgbaConverter {
label: Some("NV12 D3D11 Zero-Copy Conversion Pass"),
..Default::default()
});
- compute_pass.set_pipeline(&self.nv12_pipeline);
+ compute_pass.set_pipeline(&self.pipelines.nv12_pipeline);
compute_pass.set_bind_group(0, &bind_group, &[]);
compute_pass.dispatch_workgroups(width.div_ceil(8), height.div_ceil(8), 1);
}
diff --git a/crates/video-decode/Cargo.toml b/crates/video-decode/Cargo.toml
index ef3c82a9d..35f362662 100644
--- a/crates/video-decode/Cargo.toml
+++ b/crates/video-decode/Cargo.toml
@@ -9,7 +9,7 @@ workspace = true
[dependencies]
ffmpeg.workspace = true
ffmpeg-hw-device = { path = "../ffmpeg-hw-device" }
-num_cpus = "1.16"
+num_cpus = "1.17.0"
tokio = { workspace = true, features = ["rt", "rt-multi-thread"] }
tracing = "0.1.41"
workspace-hack = { version = "0.1", path = "../workspace-hack" }
@@ -22,6 +22,7 @@ windows = { workspace = true, features = [
"Win32_Foundation",
"Win32_Graphics_Direct3D",
"Win32_Graphics_Direct3D11",
+ "Win32_Graphics_Direct3D_Fxc",
"Win32_Graphics_Dxgi",
"Win32_Graphics_Dxgi_Common",
"Win32_Media",
diff --git a/crates/video-decode/src/lib.rs b/crates/video-decode/src/lib.rs
index d14bd8269..682df7a77 100644
--- a/crates/video-decode/src/lib.rs
+++ b/crates/video-decode/src/lib.rs
@@ -9,6 +9,6 @@ pub use avassetreader::{AVAssetReaderDecoder, KeyframeIndex};
pub use ffmpeg::FFmpegDecoder;
#[cfg(target_os = "windows")]
pub use media_foundation::{
- MFDecodedFrame, MFDecoderCapabilities, MediaFoundationDecoder, NV12Data,
+ FrameTextures, MFDecodedFrame, MFDecoderCapabilities, MediaFoundationDecoder, NV12Data,
get_mf_decoder_capabilities,
};
diff --git a/crates/video-decode/src/media_foundation.rs b/crates/video-decode/src/media_foundation.rs
index a2aa9e2c3..acc83c037 100644
--- a/crates/video-decode/src/media_foundation.rs
+++ b/crates/video-decode/src/media_foundation.rs
@@ -1,21 +1,37 @@
use std::path::Path;
-use std::sync::OnceLock;
+use std::sync::{Arc, OnceLock};
+use std::time::{Duration, Instant};
use tracing::{info, warn};
+#[cfg(target_os = "windows")]
+use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
+use windows::core::PCSTR;
use windows::{
Win32::{
Foundation::{HANDLE, HMODULE},
Graphics::{
- Direct3D::{D3D_DRIVER_TYPE_HARDWARE, D3D_FEATURE_LEVEL},
+ Direct3D::{
+ D3D_DRIVER_TYPE_HARDWARE, D3D_FEATURE_LEVEL, D3D_SRV_DIMENSION_TEXTURE2D, ID3DBlob,
+ },
Direct3D11::{
- D3D11_BIND_SHADER_RESOURCE, D3D11_CPU_ACCESS_READ,
+ D3D11_BIND_CONSTANT_BUFFER, D3D11_BIND_SHADER_RESOURCE,
+ D3D11_BIND_UNORDERED_ACCESS, D3D11_BUFFER_DESC, D3D11_CPU_ACCESS_READ,
D3D11_CREATE_DEVICE_BGRA_SUPPORT, D3D11_CREATE_DEVICE_VIDEO_SUPPORT,
D3D11_DECODER_PROFILE_H264_VLD_NOFGT, D3D11_DECODER_PROFILE_HEVC_VLD_MAIN,
- D3D11_MAP_READ, D3D11_MAPPED_SUBRESOURCE, D3D11_SDK_VERSION, D3D11_TEXTURE2D_DESC,
+ D3D11_MAP_READ, D3D11_MAPPED_SUBRESOURCE, D3D11_RESOURCE_MISC_SHARED_NTHANDLE,
+ D3D11_SDK_VERSION, D3D11_SHADER_RESOURCE_VIEW_DESC1,
+ D3D11_SHADER_RESOURCE_VIEW_DESC1_0, D3D11_TEX2D_SRV1, D3D11_TEX2D_UAV,
+ D3D11_TEXTURE2D_DESC, D3D11_UAV_DIMENSION_TEXTURE2D,
+ D3D11_UNORDERED_ACCESS_VIEW_DESC, D3D11_UNORDERED_ACCESS_VIEW_DESC_0,
D3D11_USAGE_DEFAULT, D3D11_USAGE_STAGING, D3D11_VIDEO_DECODER_DESC,
- D3D11CreateDevice, ID3D11Device, ID3D11DeviceContext, ID3D11Texture2D,
+ D3D11CreateDevice, ID3D11Buffer, ID3D11ComputeShader, ID3D11Device, ID3D11Device3,
+ ID3D11DeviceContext, ID3D11DeviceContext1, ID3D11ShaderResourceView,
+ ID3D11ShaderResourceView1, ID3D11Texture2D, ID3D11UnorderedAccessView,
ID3D11VideoDevice,
},
- Dxgi::Common::{DXGI_FORMAT_NV12, DXGI_SAMPLE_DESC},
+ Dxgi::Common::{
+ DXGI_FORMAT_NV12, DXGI_FORMAT_R8_UNORM, DXGI_FORMAT_R8G8_UNORM, DXGI_SAMPLE_DESC,
+ },
+ Dxgi::{DXGI_SHARED_RESOURCE_READ, DXGI_SHARED_RESOURCE_WRITE, IDXGIResource1},
},
Media::MediaFoundation::{
IMFAttributes, IMFDXGIBuffer, IMFDXGIDeviceManager, IMFSample, IMFSourceReader,
@@ -115,21 +131,8 @@ fn query_mf_decoder_capabilities(device: &ID3D11Device) -> MFDecoderCapabilities
})();
match result {
- Ok(caps) => {
- info!(
- max_width = caps.max_width,
- max_height = caps.max_height,
- supports_h264 = caps.supports_h264,
- supports_hevc = caps.supports_hevc,
- feature_level = ?caps.feature_level,
- "MediaFoundation decoder capabilities detected"
- );
- caps
- }
- Err(e) => {
- warn!("Failed to query MediaFoundation decoder capabilities: {e}, using defaults");
- MFDecoderCapabilities::default()
- }
+ Ok(caps) => caps,
+ Err(_) => MFDecoderCapabilities::default(),
}
}
@@ -138,15 +141,11 @@ pub fn get_mf_decoder_capabilities() -> Option<&'static MFDecoderCapabilities> {
}
pub struct MFDecodedFrame {
- pub texture: ID3D11Texture2D,
- pub shared_handle: Option<HANDLE>,
- pub y_texture: Option<ID3D11Texture2D>,
- pub y_handle: Option<HANDLE>,
- pub uv_texture: Option<ID3D11Texture2D>,
- pub uv_handle: Option<HANDLE>,
+ pub textures: Arc<FrameTextures>,
pub width: u32,
pub height: u32,
pub pts: i64,
+ pub plane_time: Duration,
}
pub struct NV12Data {
@@ -154,140 +153,480 @@ pub struct NV12Data {
pub y_stride: u32,
pub uv_stride: u32,
}
+#[derive(Clone)]
+pub struct FrameTexture {
+ pub texture: ID3D11Texture2D,
+ pub handle: HANDLE,
+ pub width: u32,
+ pub height: u32,
+}
+
+#[derive(Clone)]
+pub struct FrameTextures {
+ pub nv12: FrameTexture,
+ pub y: FrameTexture,
+ pub uv: FrameTexture,
+ pub y_uav: ID3D11UnorderedAccessView,
+ pub uv_uav: ID3D11UnorderedAccessView,
+}
+
+impl FrameTextures {
+ fn create(device: &ID3D11Device, width: u32, height: u32) -> Result<Self, String> {
+ let nv12 = create_internal_texture(
+ device,
+ width,
+ height,
+ DXGI_FORMAT_NV12,
+ D3D11_BIND_SHADER_RESOURCE.0 as u32,
+ )
+ .map_err(|ie| format!("[NV12] {ie}"))?;
+
+ let y = create_internal_texture(
+ device,
+ width,
+ height,
+ DXGI_FORMAT_R8_UNORM,
+ (D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_UNORDERED_ACCESS).0 as u32,
+ )
+ .map_err(|ie| format!("[Y-plane] {ie}"))?;
+
+ let uv = create_internal_texture(
+ device,
+ width / 2,
+ height / 2,
+ DXGI_FORMAT_R8G8_UNORM,
+ (D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_UNORDERED_ACCESS).0 as u32,
+ )
+ .map_err(|ie| format!("[UV-plane] {ie}"))?;
+
+ let y_uav = create_uav(device, &y.texture, DXGI_FORMAT_R8_UNORM)?;
+ let uv_uav = create_uav(device, &uv.texture, DXGI_FORMAT_R8G8_UNORM)?;
+
+ Ok(Self {
+ nv12,
+ y,
+ uv,
+ y_uav,
+ uv_uav,
+ })
+ }
+}
-struct TexturePool {
- output_texture: Option<ID3D11Texture2D>,
- y_texture: Option<ID3D11Texture2D>,
- uv_texture: Option<ID3D11Texture2D>,
+pub struct FramePool {
+ free: Vec<FrameTextures>,
width: u32,
height: u32,
}
-impl TexturePool {
- fn new() -> Self {
+impl FramePool {
+ pub fn new() -> Self {
Self {
- output_texture: None,
- y_texture: None,
- uv_texture: None,
+ free: Vec::new(),
width: 0,
height: 0,
}
}
- fn get_or_create_output_texture(
+ pub fn acquire(
&mut self,
device: &ID3D11Device,
width: u32,
height: u32,
- ) -> Result<&ID3D11Texture2D, String> {
- if self.width != width || self.height != height || self.output_texture.is_none() {
- let desc = D3D11_TEXTURE2D_DESC {
- Width: width,
- Height: height,
- MipLevels: 1,
- ArraySize: 1,
- Format: DXGI_FORMAT_NV12,
- SampleDesc: DXGI_SAMPLE_DESC {
- Count: 1,
- Quality: 0,
- },
- Usage: D3D11_USAGE_DEFAULT,
- BindFlags: D3D11_BIND_SHADER_RESOURCE.0 as u32,
- CPUAccessFlags: 0,
- MiscFlags: 0,
- };
-
- let texture = unsafe {
- let mut tex: Option<ID3D11Texture2D> = None;
- device
- .CreateTexture2D(&desc, None, Some(&mut tex))
- .map_err(|e| format!("CreateTexture2D failed: {e:?}"))?;
- tex.ok_or("CreateTexture2D returned null")?
- };
-
- self.output_texture = Some(texture);
+ ) -> Result<FrameTextures, String> {
+ if self.width != width || self.height != height {
+ self.free.clear();
self.width = width;
self.height = height;
- self.y_texture = None;
- self.uv_texture = None;
}
- self.output_texture
- .as_ref()
- .ok_or_else(|| "Output texture not initialized".to_string())
+ if let Some(textures) = self.free.pop() {
+ return Ok(textures);
+ }
+
+ FrameTextures::create(device, width, height)
}
- fn get_or_create_yuv_textures(
- &mut self,
- device: &ID3D11Device,
+ pub fn recycle(&mut self, textures: FrameTextures) {
+ self.free.push(textures);
+ }
+}
+
+#[repr(C)]
+struct PlaneConstants {
+ width: u32,
+ height: u32,
+ uv_width: u32,
+ uv_height: u32,
+}
+
+pub struct Nv12PlaneConverter {
+ device3: ID3D11Device3,
+ context1: ID3D11DeviceContext1,
+ shader: ID3D11ComputeShader,
+ constants: ID3D11Buffer,
+}
+
+impl Nv12PlaneConverter {
+ pub fn new(device: &ID3D11Device, context: &ID3D11DeviceContext) -> Result<Self, String> {
+ let device3: ID3D11Device3 = device
+ .cast()
+ .map_err(|e| format!("Failed to cast to ID3D11Device3: {e:?}"))?;
+ let context1: ID3D11DeviceContext1 = context
+ .cast()
+ .map_err(|e| format!("Failed to cast to ID3D11DeviceContext1: {e:?}"))?;
+
+ let shader = compile_plane_shader(&device3)?;
+
+ let constants = create_constant_buffer(&device3)?;
+
+ Ok(Self {
+ device3,
+ context1,
+ shader,
+ constants,
+ })
+ }
+
+ pub fn convert(
+ &self,
+ input: &ID3D11Texture2D,
+ outputs: &FrameTextures,
width: u32,
height: u32,
- ) -> Result<(&ID3D11Texture2D, &ID3D11Texture2D), String> {
- use windows::Win32::Graphics::Dxgi::Common::{
- DXGI_FORMAT_R8_UNORM, DXGI_FORMAT_R8G8_UNORM,
+ ) -> Result<(), String> {
+ let y_srv_desc = D3D11_SHADER_RESOURCE_VIEW_DESC1 {
+ Format: DXGI_FORMAT_R8_UNORM,
+ ViewDimension: D3D_SRV_DIMENSION_TEXTURE2D,
+ Anonymous: D3D11_SHADER_RESOURCE_VIEW_DESC1_0 {
+ Texture2D: D3D11_TEX2D_SRV1 {
+ MostDetailedMip: 0,
+ MipLevels: 1,
+ PlaneSlice: 0,
+ },
+ },
};
- if self.width != width || self.height != height || self.y_texture.is_none() {
- let y_desc = D3D11_TEXTURE2D_DESC {
- Width: width,
- Height: height,
- MipLevels: 1,
- ArraySize: 1,
- Format: DXGI_FORMAT_R8_UNORM,
- SampleDesc: DXGI_SAMPLE_DESC {
- Count: 1,
- Quality: 0,
+ let uv_srv_desc = D3D11_SHADER_RESOURCE_VIEW_DESC1 {
+ Format: DXGI_FORMAT_R8G8_UNORM,
+ ViewDimension: D3D_SRV_DIMENSION_TEXTURE2D,
+ Anonymous: D3D11_SHADER_RESOURCE_VIEW_DESC1_0 {
+ Texture2D: D3D11_TEX2D_SRV1 {
+ MostDetailedMip: 0,
+ MipLevels: 1,
+ PlaneSlice: 1,
},
- Usage: D3D11_USAGE_DEFAULT,
- BindFlags: D3D11_BIND_SHADER_RESOURCE.0 as u32,
- CPUAccessFlags: 0,
- MiscFlags: 0,
- };
+ },
+ };
- let y_texture = unsafe {
- let mut tex: Option<ID3D11Texture2D> = None;
- device
- .CreateTexture2D(&y_desc, None, Some(&mut tex))
- .map_err(|e| format!("CreateTexture2D Y failed: {e:?}"))?;
- tex.ok_or("CreateTexture2D Y returned null")?
- };
+ let y_srv = unsafe {
+ let mut srv: Option<ID3D11ShaderResourceView1> = None;
+ self.device3
+ .CreateShaderResourceView1(input, Some(&y_srv_desc), Some(&mut srv))
+ .map_err(|e| format!("CreateShaderResourceView1 for Y failed: {e:?}"))?;
+ srv.ok_or("Y SRV creation returned null")?
+ };
- let uv_desc = D3D11_TEXTURE2D_DESC {
- Width: width / 2,
- Height: height / 2,
- MipLevels: 1,
- ArraySize: 1,
- Format: DXGI_FORMAT_R8G8_UNORM,
- SampleDesc: DXGI_SAMPLE_DESC {
- Count: 1,
- Quality: 0,
- },
- Usage: D3D11_USAGE_DEFAULT,
- BindFlags: D3D11_BIND_SHADER_RESOURCE.0 as u32,
- CPUAccessFlags: 0,
- MiscFlags: 0,
- };
+ let uv_srv = unsafe {
+ let mut srv: Option<ID3D11ShaderResourceView1> = None;
+ self.device3
+ .CreateShaderResourceView1(input, Some(&uv_srv_desc), Some(&mut srv))
+ .map_err(|e| format!("CreateShaderResourceView1 for UV failed: {e:?}"))?;
+ srv.ok_or("UV SRV creation returned null")?
+ };
- let uv_texture = unsafe {
- let mut tex: Option<ID3D11Texture2D> = None;
- device
- .CreateTexture2D(&uv_desc, None, Some(&mut tex))
- .map_err(|e| format!("CreateTexture2D UV failed: {e:?}"))?;
- tex.ok_or("CreateTexture2D UV returned null")?
- };
+ let y_srv_base: ID3D11ShaderResourceView = y_srv
+ .cast()
+ .map_err(|e| format!("Cast Y SRV1 to base failed: {e:?}"))?;
+ let uv_srv_base: ID3D11ShaderResourceView = uv_srv
+ .cast()
+ .map_err(|e| format!("Cast UV SRV1 to base failed: {e:?}"))?;
- self.y_texture = Some(y_texture);
- self.uv_texture = Some(uv_texture);
- self.width = width;
- self.height = height;
+ let constants = PlaneConstants {
+ width,
+ height,
+ uv_width: width / 2,
+ uv_height: height / 2,
+ };
+
+ unsafe {
+ self.context1.UpdateSubresource(
+ &self.constants,
+ 0,
+ None,
+ &constants as *const _ as *const std::ffi::c_void,
+ 0,
+ 0,
+ );
+
+ self.context1.CSSetShader(Some(&self.shader), None);
+ self.context1
+ .CSSetConstantBuffers(0, Some(&[Some(self.constants.clone())]));
+ self.context1.CSSetShaderResources(
+ 0,
+ Some(&[Some(y_srv_base.clone()), Some(uv_srv_base.clone())]),
+ );
+ let uavs = [Some(outputs.y_uav.clone()), Some(outputs.uv_uav.clone())];
+ self.context1.CSSetUnorderedAccessViews(
+ 0,
+ uavs.len() as u32,
+ Some(uavs.as_ptr()),
+ None,
+ );
+
+ let groups_x = width.div_ceil(16);
+ let groups_y = height.div_ceil(16);
+ self.context1.Dispatch(groups_x, groups_y, 1);
+
+ self.context1.CSSetShaderResources(0, Some(&[None, None]));
+ let null_uavs: [Option<ID3D11UnorderedAccessView>; 2] = [None, None];
+ self.context1.CSSetUnorderedAccessViews(
+ 0,
+ null_uavs.len() as u32,
+ Some(null_uavs.as_ptr()),
+ None,
+ );
+ self.context1.CSSetConstantBuffers(0, Some(&[None]));
+ self.context1.CSSetShader(None, None);
}
- Ok((
- self.y_texture.as_ref().ok_or("Y texture not initialized")?,
- self.uv_texture
- .as_ref()
- .ok_or("UV texture not initialized")?,
- ))
+ Ok(())
+ }
+}
+
+fn compile_plane_shader(device: &ID3D11Device3) -> Result<ID3D11ComputeShader, String> {
+ let source = br#"
+cbuffer FrameSize : register(b0) {
+ uint width;
+ uint height;
+ uint uv_width;
+ uint uv_height;
+};
+Texture2D<uint> YPlane : register(t0);
+Texture2D<uint2> UVPlane : register(t1);
+RWTexture2D<uint> OutY : register(u0);
+RWTexture2D<uint2> OutUV : register(u1);
+
+[numthreads(16,16,1)]
+void main(uint3 dtid : SV_DispatchThreadID) {
+ uint x = dtid.x;
+ uint y = dtid.y;
+ if (x < width && y < height) {
+ OutY[uint2(x, y)] = YPlane.Load(int3(x, y, 0));
+ }
+ if (x < uv_width && y < uv_height) {
+ OutUV[uint2(x, y)] = UVPlane.Load(int3(x, y, 0));
+ }
+}
+"#;
+
+ let mut shader_blob: Option<ID3DBlob> = None;
+ let mut error_blob: Option<ID3DBlob> = None;
+ let shader_blob_ptr: *mut Option<ID3DBlob> = &mut shader_blob;
+ let error_blob_ptr: *mut Option<ID3DBlob> = &mut error_blob;
+
+ unsafe {
+ D3DCompile(
+ source.as_ptr() as *const std::ffi::c_void,
+ source.len(),
+ None,
+ None,
+ None,
+ PCSTR(b"main\0".as_ptr()),
+ PCSTR(b"cs_5_0\0".as_ptr()),
+ 0,
+ 0,
+ shader_blob_ptr,
+ Some(error_blob_ptr),
+ )
+ .map_err(|e| format!("D3DCompile failed: {e:?}"))?;
+ }
+
+ let shader_blob =
+ shader_blob.ok_or_else(|| "Shader compilation produced no blob".to_string())?;
+
+ let shader_bytes = unsafe {
+ std::slice::from_raw_parts(
+ shader_blob.GetBufferPointer() as *const u8,
+ shader_blob.GetBufferSize(),
+ )
+ };
+
+ let mut shader = None;
+ unsafe {
+ device
+ .CreateComputeShader(shader_bytes, None, Some(&mut shader))
+ .map_err(|e| format!("CreateComputeShader failed: {e:?}"))?;
+ }
+
+ shader.ok_or_else(|| "CreateComputeShader returned null".to_string())
+}
+
+fn create_constant_buffer(device: &ID3D11Device3) -> Result<ID3D11Buffer, String> {
+ let desc = D3D11_BUFFER_DESC {
+ ByteWidth: std::mem::size_of::<PlaneConstants>() as u32,
+ Usage: D3D11_USAGE_DEFAULT,
+ BindFlags: D3D11_BIND_CONSTANT_BUFFER.0 as u32,
+ CPUAccessFlags: 0,
+ MiscFlags: 0,
+ StructureByteStride: 0,
+ };
+
+ unsafe {
+ let mut buffer = None;
+ device
+ .CreateBuffer(&desc, None, Some(&mut buffer))
+ .map_err(|e| format!("CreateBuffer failed: {e:?}"))?;
+ buffer.ok_or_else(|| "CreateBuffer returned null".to_string())
+ }
+}
+
+fn create_nv12_texture(
+ device: &ID3D11Device,
+ width: u32,
+ height: u32,
+) -> Result<FrameTexture, String> {
+ let desc = D3D11_TEXTURE2D_DESC {
+ Width: width,
+ Height: height,
+ MipLevels: 1,
+ ArraySize: 1,
+ Format: DXGI_FORMAT_NV12,
+ SampleDesc: DXGI_SAMPLE_DESC {
+ Count: 1,
+ Quality: 0,
+ },
+ Usage: D3D11_USAGE_DEFAULT,
+ BindFlags: D3D11_BIND_SHADER_RESOURCE.0 as u32,
+ CPUAccessFlags: 0,
+ MiscFlags: 0,
+ };
+
+ let texture = unsafe {
+ let mut tex: Option<ID3D11Texture2D> = None;
+ device
+ .CreateTexture2D(&desc, None, Some(&mut tex))
+ .map_err(|e| format!("CreateTexture2D NV12 failed: {e:?}"))?;
+ tex.ok_or("CreateTexture2D NV12 returned null")?
+ };
+
+ Ok(FrameTexture {
+ texture,
+ handle: HANDLE::default(),
+ width,
+ height,
+ })
+}
+
+fn create_internal_texture(
+ device: &ID3D11Device,
+ width: u32,
+ height: u32,
+ format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT,
+ bind: u32,
+) -> Result<FrameTexture, String> {
+ let desc = D3D11_TEXTURE2D_DESC {
+ Width: width,
+ Height: height,
+ MipLevels: 1,
+ ArraySize: 1,
+ Format: format,
+ SampleDesc: DXGI_SAMPLE_DESC {
+ Count: 1,
+ Quality: 0,
+ },
+ Usage: D3D11_USAGE_DEFAULT,
+ BindFlags: bind,
+ CPUAccessFlags: 0,
+ MiscFlags: 0,
+ };
+
+ let texture = unsafe {
+ let mut tex: Option<ID3D11Texture2D> = None;
+ device
+ .CreateTexture2D(&desc, None, Some(&mut tex))
+ .map_err(|e| format!("CreateTexture2D failed: {e:?}"))?;
+ tex.ok_or("CreateTexture2D returned null")?
+ };
+
+ Ok(FrameTexture {
+ texture,
+ handle: HANDLE::default(),
+ width,
+ height,
+ })
+}
+
+fn create_shared_texture(
+ device: &ID3D11Device,
+ width: u32,
+ height: u32,
+ format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT,
+ bind: u32,
+) -> Result<FrameTexture, String> {
+ let desc = D3D11_TEXTURE2D_DESC {
+ Width: width,
+ Height: height,
+ MipLevels: 1,
+ ArraySize: 1,
+ Format: format,
+ SampleDesc: DXGI_SAMPLE_DESC {
+ Count: 1,
+ Quality: 0,
+ },
+ Usage: D3D11_USAGE_DEFAULT,
+ BindFlags: bind,
+ CPUAccessFlags: 0,
+ MiscFlags: D3D11_RESOURCE_MISC_SHARED_NTHANDLE.0 as u32,
+ };
+
+ let texture = unsafe {
+ let mut tex: Option<ID3D11Texture2D> = None;
+ if let Err(e) = device.CreateTexture2D(&desc, None, Some(&mut tex)) {
+ return Err(format!("CreateTexture2D failed: {e:?}"));
+ }
+ tex.ok_or("CreateTexture2D returned null")?
+ };
+
+ let handle = unsafe {
+ let resource: IDXGIResource1 = texture
+ .cast()
+ .map_err(|e| format!("Failed to cast texture to IDXGIResource1: {e:?}"))?;
+ resource
+ .CreateSharedHandle(
+ None,
+ DXGI_SHARED_RESOURCE_READ.0 | DXGI_SHARED_RESOURCE_WRITE.0,
+ None,
+ )
+ .map_err(|e| format!("CreateSharedHandle failed: {e:?}"))?
+ };
+
+ Ok(FrameTexture {
+ texture,
+ handle,
+ width,
+ height,
+ })
+}
+
+fn create_uav(
+ device: &ID3D11Device,
+ texture: &ID3D11Texture2D,
+ format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT,
+) -> Result<ID3D11UnorderedAccessView, String> {
+ let desc = D3D11_UNORDERED_ACCESS_VIEW_DESC {
+ Format: format,
+ ViewDimension: D3D11_UAV_DIMENSION_TEXTURE2D,
+ Anonymous: D3D11_UNORDERED_ACCESS_VIEW_DESC_0 {
+ Texture2D: D3D11_TEX2D_UAV { MipSlice: 0 },
+ },
+ };
+
+ unsafe {
+ let mut uav = None;
+ device
+ .CreateUnorderedAccessView(texture, Some(&desc), Some(&mut uav))
+ .map_err(|e| format!("CreateUnorderedAccessView failed: {e:?}"))?;
+ uav.ok_or_else(|| "CreateUnorderedAccessView returned null".to_string())
}
}
@@ -303,7 +642,8 @@ pub struct MediaFoundationDecoder {
staging_texture: Option<ID3D11Texture2D>,
staging_width: u32,
staging_height: u32,
- texture_pool: TexturePool,
+ frame_pool: FramePool,
+ plane_converter: Nv12PlaneConverter,
capabilities: MFDecoderCapabilities,
}
@@ -349,6 +689,8 @@ impl MediaFoundationDecoder {
.get_or_init(|| query_mf_decoder_capabilities(&d3d11_device))
.clone();
+ let plane_converter = Nv12PlaneConverter::new(&d3d11_device, &d3d11_context)?;
+
if width > capabilities.max_width || height > capabilities.max_height {
warn!(
video_width = width,
@@ -381,7 +723,8 @@ impl MediaFoundationDecoder {
staging_texture: None,
staging_width: 0,
staging_height: 0,
- texture_pool: TexturePool::new(),
+ frame_pool: FramePool::new(),
+ plane_converter,
capabilities,
})
}
@@ -492,6 +835,14 @@ impl MediaFoundationDecoder {
unsafe { self.read_sample_inner() }
}
+ pub fn recycle_textures(&mut self, textures: Arc<FrameTextures>) {
+ if Arc::strong_count(&textures) == 1 {
+ if let Ok(textures) = Arc::try_unwrap(textures) {
+ self.frame_pool.recycle(textures);
+ }
+ }
+ }
+
unsafe fn read_sample_inner(&mut self) -> Result<Option<MFDecodedFrame>, String> {
let mut stream_index = 0u32;
let mut flags = 0u32;
@@ -550,14 +901,15 @@ impl MediaFoundationDecoder {
.map_err(|e| format!("GetSubresourceIndex failed: {e:?}"))?
};
- let output_texture = self
- .texture_pool
- .get_or_create_output_texture(&self.d3d11_device, self.width, self.height)?
- .clone();
+ let frame_textures =
+ self.frame_pool
+ .acquire(&self.d3d11_device, self.width, self.height)?;
+
+ let plane_start = Instant::now();
unsafe {
self.d3d11_context.CopySubresourceRegion(
- &output_texture,
+ &frame_textures.nv12.texture,
0,
0,
0,
@@ -566,71 +918,23 @@ impl MediaFoundationDecoder {
subresource_index,
None,
);
- }
-
- let shared_handle = None;
- let (y_texture, y_handle, uv_texture, uv_handle) = {
- let (y_tex, uv_tex) = self.texture_pool.get_or_create_yuv_textures(
- &self.d3d11_device,
+ self.plane_converter.convert(
+ &frame_textures.nv12.texture,
+ &frame_textures,
self.width,
self.height,
)?;
+ }
- let y_texture = y_tex.clone();
- let uv_texture = uv_tex.clone();
-
- unsafe {
- self.d3d11_context.CopySubresourceRegion(
- &y_texture,
- 0,
- 0,
- 0,
- 0,
- &output_texture,
- 0,
- Some(&windows::Win32::Graphics::Direct3D11::D3D11_BOX {
- left: 0,
- top: 0,
- front: 0,
- right: self.width,
- bottom: self.height,
- back: 1,
- }),
- );
-
- self.d3d11_context.CopySubresourceRegion(
- &uv_texture,
- 0,
- 0,
- 0,
- 0,
- &output_texture,
- 1,
- Some(&windows::Win32::Graphics::Direct3D11::D3D11_BOX {
- left: 0,
- top: 0,
- front: 0,
- right: self.width / 2,
- bottom: self.height / 2,
- back: 1,
- }),
- );
- }
-
- (Some(y_texture), None, Some(uv_texture), None)
- };
+ let plane_time = plane_start.elapsed();
Ok(Some(MFDecodedFrame {
- texture: output_texture,
- shared_handle,
- y_texture,
- y_handle,
- uv_texture,
- uv_handle,
+ textures: Arc::new(frame_textures),
width: self.width,
height: self.height,
pts: timestamp,
+ plane_time,
}))
}