Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Add Windows Media Foundation decoder and D3D11 interop

Richie McIlroy7687f5b22e5d
diff --git a/Cargo.lock b/Cargo.lock
index 4fc058cb1..e08cae4f2 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1604,6 +1604,7 @@ dependencies = [
"wgpu",
"wgpu-core",
"wgpu-hal",
+ "windows 0.60.0",
"workspace-hack",
]
@@ -1662,6 +1663,7 @@ dependencies = [
"ffmpeg-next",
"tokio",
"tracing",
+ "windows 0.60.0",
"workspace-hack",
]
diff --git a/apps/desktop/src-tauri/src/gpu_context.rs b/apps/desktop/src-tauri/src/gpu_context.rs
index 28372a58c..50c87ea7e 100644
--- a/apps/desktop/src-tauri/src/gpu_context.rs
+++ b/apps/desktop/src-tauri/src/gpu_context.rs
@@ -42,6 +42,7 @@ pub struct SharedGpuContext {
pub queue: Arc<wgpu::Queue>,
pub adapter: Arc<wgpu::Adapter>,
pub instance: Arc<wgpu::Instance>,
+ pub is_software_adapter: bool,
}
static GPU: OnceCell<Option<SharedGpuContext>> = OnceCell::const_new();
@@ -49,14 +50,41 @@ static GPU: OnceCell<Option<SharedGpuContext>> = OnceCell::const_new();
pub async fn get_shared_gpu() -> Option<&'static SharedGpuContext> {
GPU.get_or_init(|| async {
let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor::default());
- let adapter = instance
+
+ let hardware_adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::HighPerformance,
force_fallback_adapter: false,
compatible_surface: None,
})
.await
- .ok()?;
+ .ok();
+
+ let (adapter, is_software_adapter) = if let Some(adapter) = hardware_adapter {
+ tracing::info!(
+ adapter_name = adapter.get_info().name,
+ adapter_backend = ?adapter.get_info().backend,
+ "Using hardware GPU adapter for shared context"
+ );
+ (adapter, false)
+ } else {
+ tracing::warn!("No hardware GPU adapter found, attempting software fallback for shared context");
+ let software_adapter = instance
+ .request_adapter(&wgpu::RequestAdapterOptions {
+ power_preference: wgpu::PowerPreference::LowPower,
+ force_fallback_adapter: true,
+ compatible_surface: None,
+ })
+ .await
+ .ok()?;
+
+ tracing::info!(
+ adapter_name = software_adapter.get_info().name,
+ adapter_backend = ?software_adapter.get_info().backend,
+ "Using software adapter for shared context (CPU rendering - performance may be reduced)"
+ );
+ (software_adapter, true)
+ };
let (device, queue) = adapter
.request_device(&wgpu::DeviceDescriptor {
@@ -72,6 +100,7 @@ pub async fn get_shared_gpu() -> Option<&'static SharedGpuContext> {
queue: Arc::new(queue),
adapter: Arc::new(adapter),
instance: Arc::new(instance),
+ is_software_adapter,
})
})
.await
diff --git a/apps/desktop/src-tauri/src/screenshot_editor.rs b/apps/desktop/src-tauri/src/screenshot_editor.rs
index 4b0e41d91..58f7a5f8f 100644
--- a/apps/desktop/src-tauri/src/screenshot_editor.rs
+++ b/apps/desktop/src-tauri/src/screenshot_editor.rs
@@ -232,13 +232,14 @@ impl ScreenshotEditorInstances {
}
};
- let (instance, adapter, device, queue) =
+ let (instance, adapter, device, queue, is_software_adapter) =
if let Some(shared) = gpu_context::get_shared_gpu().await {
(
shared.instance.clone(),
shared.adapter.clone(),
shared.device.clone(),
shared.queue.clone(),
+ shared.is_software_adapter,
)
} else {
let instance =
@@ -262,7 +263,7 @@ impl ScreenshotEditorInstances {
})
.await
.map_err(|e| e.to_string())?;
- (instance, adapter, Arc::new(device), Arc::new(queue))
+ (instance, adapter, Arc::new(device), Arc::new(queue), false)
};
let options = cap_rendering::RenderOptions {
@@ -285,6 +286,7 @@ impl ScreenshotEditorInstances {
meta: studio_meta,
recording_meta: recording_meta.clone(),
background_textures: Arc::new(tokio::sync::RwLock::new(HashMap::new())),
+ is_software_adapter,
};
let (config_tx, mut config_rx) = watch::channel(loaded_config.unwrap_or_default());
@@ -304,7 +306,11 @@ impl ScreenshotEditorInstances {
tokio::spawn(async move {
let mut frame_renderer = FrameRenderer::new(&constants);
- let mut layers = RendererLayers::new(&constants.device, &constants.queue);
+ let mut layers = RendererLayers::new_with_options(
+ &constants.device,
+ &constants.queue,
+ constants.is_software_adapter,
+ );
let shutdown_token = render_shutdown_token;
// Initial render
diff --git a/apps/desktop/src/utils/frame-worker.ts b/apps/desktop/src/utils/frame-worker.ts
index 8bd4223a8..5b61309b6 100644
--- a/apps/desktop/src/utils/frame-worker.ts
+++ b/apps/desktop/src/utils/frame-worker.ts
@@ -125,6 +125,12 @@ let lastRawFrameData: Uint8ClampedArray | null = null;
let lastRawFrameWidth = 0;
let lastRawFrameHeight = 0;
+let webgpuFrameBuffer: Uint8ClampedArray | null = null;
+let webgpuFrameBufferSize = 0;
+
+let frameDropCount = 0;
+let lastFrameDropLogTime = 0;
+
let consumer: Consumer | null = null;
let useSharedBuffer = false;
@@ -214,6 +220,10 @@ function cleanup() {
lastRawFrameData = null;
lastRawFrameWidth = 0;
lastRawFrameHeight = 0;
+ webgpuFrameBuffer = null;
+ webgpuFrameBufferSize = 0;
+ frameDropCount = 0;
+ lastFrameDropLogTime = 0;
}
function initWorker() {
@@ -385,17 +395,39 @@ async function processFrame(buffer: ArrayBuffer): Promise<DecodeResult> {
}
if (renderMode === "webgpu" && webgpuRenderer) {
- const frameDataCopy = new Uint8ClampedArray(processedFrameData);
+ if (pendingRenderFrame !== null) {
+ frameDropCount++;
+ const now = performance.now();
+ if (now - lastFrameDropLogTime > 1000) {
+ if (frameDropCount > 0) {
+ console.warn(
+ `[frame-worker] Dropped ${frameDropCount} frames in the last second`,
+ );
+ }
+ frameDropCount = 0;
+ lastFrameDropLogTime = now;
+ }
+ }
+
+ if (!webgpuFrameBuffer || webgpuFrameBufferSize < expectedLength) {
+ webgpuFrameBuffer = new Uint8ClampedArray(expectedLength);
+ webgpuFrameBufferSize = expectedLength;
+ }
+ webgpuFrameBuffer.set(processedFrameData);
+
pendingRenderFrame = {
mode: "webgpu",
- data: frameDataCopy,
+ data: webgpuFrameBuffer,
width,
height,
};
return { type: "frame-queued", width, height };
}
- lastRawFrameData = new Uint8ClampedArray(processedFrameData);
+ if (!lastRawFrameData || lastRawFrameData.length < expectedLength) {
+ lastRawFrameData = new Uint8ClampedArray(expectedLength);
+ }
+ lastRawFrameData.set(processedFrameData);
lastRawFrameWidth = width;
lastRawFrameHeight = height;
diff --git a/crates/editor/src/editor.rs b/crates/editor/src/editor.rs
index 82d443f24..9e817f2e3 100644
--- a/crates/editor/src/editor.rs
+++ b/crates/editor/src/editor.rs
@@ -73,8 +73,11 @@ impl Renderer {
async fn run(mut self) {
let mut frame_renderer = FrameRenderer::new(&self.render_constants);
- let mut layers =
- RendererLayers::new(&self.render_constants.device, &self.render_constants.queue);
+ let mut layers = RendererLayers::new_with_options(
+ &self.render_constants.device,
+ &self.render_constants.queue,
+ self.render_constants.is_software_adapter,
+ );
struct PendingFrame {
segment_frames: DecodedSegmentFrames,
diff --git a/crates/rendering/Cargo.toml b/crates/rendering/Cargo.toml
index 95ea663cd..6735427df 100644
--- a/crates/rendering/Cargo.toml
+++ b/crates/rendering/Cargo.toml
@@ -42,6 +42,19 @@ wgpu-hal = { workspace = true, features = ["metal"] }
wgpu-core.workspace = true
foreign-types = "0.5"
+[target.'cfg(target_os = "windows")'.dependencies]
+wgpu-hal = { workspace = true, features = ["dx12"] }
+wgpu-core.workspace = true
+windows = { workspace = true, features = [
+ "Win32_Foundation",
+ "Win32_Graphics_Direct3D",
+ "Win32_Graphics_Direct3D11",
+ "Win32_Graphics_Direct3D12",
+ "Win32_Graphics_Dxgi",
+ "Win32_Graphics_Dxgi_Common",
+ "Win32_System_Threading",
+] }
+
[dev-dependencies]
pretty_assertions = "1.4.1"
diff --git a/crates/rendering/src/cpu_yuv.rs b/crates/rendering/src/cpu_yuv.rs
new file mode 100644
index 000000000..c9e333549
--- /dev/null
+++ b/crates/rendering/src/cpu_yuv.rs
@@ -0,0 +1,462 @@
+pub fn nv12_to_rgba(
+ y_data: &[u8],
+ uv_data: &[u8],
+ width: u32,
+ height: u32,
+ y_stride: u32,
+ uv_stride: u32,
+ output: &mut [u8],
+) {
+ let width = width as usize;
+ let height = height as usize;
+ let y_stride = y_stride as usize;
+ let uv_stride = uv_stride as usize;
+
+ for row in 0..height {
+ let y_row_start = row * y_stride;
+ let uv_row_start = (row / 2) * uv_stride;
+ let out_row_start = row * width * 4;
+
+ for col in 0..width {
+ let y_idx = y_row_start + col;
+ let uv_idx = uv_row_start + (col / 2) * 2;
+
+ let y = y_data.get(y_idx).copied().unwrap_or(0) as i32;
+ let u = uv_data.get(uv_idx).copied().unwrap_or(128) as i32;
+ let v = uv_data.get(uv_idx + 1).copied().unwrap_or(128) as i32;
+
+ let c = y - 16;
+ let d = u - 128;
+ let e = v - 128;
+
+ let r = clamp_u8((298 * c + 409 * e + 128) >> 8);
+ let g = clamp_u8((298 * c - 100 * d - 208 * e + 128) >> 8);
+ let b = clamp_u8((298 * c + 516 * d + 128) >> 8);
+
+ let out_idx = out_row_start + col * 4;
+ if out_idx + 3 < output.len() {
+ output[out_idx] = r;
+ output[out_idx + 1] = g;
+ output[out_idx + 2] = b;
+ output[out_idx + 3] = 255;
+ }
+ }
+ }
+}
+
+pub fn yuv420p_to_rgba(
+ y_data: &[u8],
+ u_data: &[u8],
+ v_data: &[u8],
+ width: u32,
+ height: u32,
+ y_stride: u32,
+ uv_stride: u32,
+ output: &mut [u8],
+) {
+ let width = width as usize;
+ let height = height as usize;
+ let y_stride = y_stride as usize;
+ let uv_stride = uv_stride as usize;
+
+ for row in 0..height {
+ let y_row_start = row * y_stride;
+ let uv_row_start = (row / 2) * uv_stride;
+ let out_row_start = row * width * 4;
+
+ for col in 0..width {
+ let y_idx = y_row_start + col;
+ let uv_idx = uv_row_start + (col / 2);
+
+ let y = y_data.get(y_idx).copied().unwrap_or(0) as i32;
+ let u = u_data.get(uv_idx).copied().unwrap_or(128) as i32;
+ let v = v_data.get(uv_idx).copied().unwrap_or(128) as i32;
+
+ let c = y - 16;
+ let d = u - 128;
+ let e = v - 128;
+
+ let r = clamp_u8((298 * c + 409 * e + 128) >> 8);
+ let g = clamp_u8((298 * c - 100 * d - 208 * e + 128) >> 8);
+ let b = clamp_u8((298 * c + 516 * d + 128) >> 8);
+
+ let out_idx = out_row_start + col * 4;
+ if out_idx + 3 < output.len() {
+ output[out_idx] = r;
+ output[out_idx + 1] = g;
+ output[out_idx + 2] = b;
+ output[out_idx + 3] = 255;
+ }
+ }
+ }
+}
+
+#[cfg(any(target_arch = "x86_64", target_arch = "x86"))]
+pub fn nv12_to_rgba_simd(
+ y_data: &[u8],
+ uv_data: &[u8],
+ width: u32,
+ height: u32,
+ y_stride: u32,
+ uv_stride: u32,
+ output: &mut [u8],
+) {
+ #[cfg(target_arch = "x86")]
+ use std::arch::x86::*;
+ #[cfg(target_arch = "x86_64")]
+ use std::arch::x86_64::*;
+
+ if !is_x86_feature_detected!("sse2") {
+ return nv12_to_rgba(y_data, uv_data, width, height, y_stride, uv_stride, output);
+ }
+
+ let width_usize = width as usize;
+ let height_usize = height as usize;
+ let y_stride_usize = y_stride as usize;
+ let uv_stride_usize = uv_stride as usize;
+
+ let simd_width = (width_usize / 8) * 8;
+
+ unsafe {
+ let c16 = _mm_set1_epi16(16);
+ let c128 = _mm_set1_epi16(128);
+ let c298 = _mm_set1_epi16(298);
+ let c409 = _mm_set1_epi16(409);
+ let c100 = _mm_set1_epi16(100);
+ let c208 = _mm_set1_epi16(208);
+ let c516 = _mm_set1_epi16(516);
+ let zero = _mm_setzero_si128();
+
+ for row in 0..height_usize {
+ let y_row_start = row * y_stride_usize;
+ let uv_row_start = (row / 2) * uv_stride_usize;
+ let out_row_start = row * width_usize * 4;
+
+ let mut col = 0usize;
+
+ while col + 8 <= simd_width {
+ let y_ptr = y_data.as_ptr().add(y_row_start + col);
+ let uv_ptr = uv_data.as_ptr().add(uv_row_start + (col / 2) * 2);
+
+ let y8 = _mm_loadl_epi64(y_ptr as *const __m128i);
+ let y16 = _mm_unpacklo_epi8(y8, zero);
+ let y_adj = _mm_sub_epi16(y16, c16);
+
+ let uv8 = _mm_loadl_epi64(uv_ptr as *const __m128i);
+
+ let u8_val = _mm_and_si128(uv8, _mm_set1_epi16(0x00FF));
+ let v8_val = _mm_srli_epi16(uv8, 8);
+
+ let u_dup = _mm_unpacklo_epi16(u8_val, u8_val);
+ let v_dup = _mm_unpacklo_epi16(v8_val, v8_val);
+
+ let u16 = _mm_unpacklo_epi8(u_dup, zero);
+ let v16 = _mm_unpacklo_epi8(v_dup, zero);
+
+ let d = _mm_sub_epi16(u16, c128);
+ let e = _mm_sub_epi16(v16, c128);
+
+ let c_scaled = _mm_mullo_epi16(y_adj, c298);
+
+ let r_raw = _mm_add_epi16(c_scaled, _mm_mullo_epi16(e, c409));
+ let r_raw = _mm_add_epi16(r_raw, c128);
+ let r_raw = _mm_srai_epi16(r_raw, 8);
+
+ let g_raw = _mm_sub_epi16(c_scaled, _mm_mullo_epi16(d, c100));
+ let g_raw = _mm_sub_epi16(g_raw, _mm_mullo_epi16(e, c208));
+ let g_raw = _mm_add_epi16(g_raw, c128);
+ let g_raw = _mm_srai_epi16(g_raw, 8);
+
+ let b_raw = _mm_add_epi16(c_scaled, _mm_mullo_epi16(d, c516));
+ let b_raw = _mm_add_epi16(b_raw, c128);
+ let b_raw = _mm_srai_epi16(b_raw, 8);
+
+ let r = _mm_packus_epi16(r_raw, zero);
+ let g = _mm_packus_epi16(g_raw, zero);
+ let b = _mm_packus_epi16(b_raw, zero);
+ let a = _mm_set1_epi8(-1i8);
+
+ let rg_lo = _mm_unpacklo_epi8(r, g);
+ let ba_lo = _mm_unpacklo_epi8(b, a);
+ let rgba_lo = _mm_unpacklo_epi16(rg_lo, ba_lo);
+ let rgba_hi = _mm_unpackhi_epi16(rg_lo, ba_lo);
+
+ let out_ptr = output.as_mut_ptr().add(out_row_start + col * 4);
+ _mm_storeu_si128(out_ptr as *mut __m128i, rgba_lo);
+ _mm_storeu_si128(out_ptr.add(16) as *mut __m128i, rgba_hi);
+
+ col += 8;
+ }
+
+ for col in simd_width..width_usize {
+ let y_idx = y_row_start + col;
+ let uv_idx = uv_row_start + (col / 2) * 2;
+
+ let y = y_data.get(y_idx).copied().unwrap_or(0) as i32;
+ let u = uv_data.get(uv_idx).copied().unwrap_or(128) as i32;
+ let v = uv_data.get(uv_idx + 1).copied().unwrap_or(128) as i32;
+
+ let c = y - 16;
+ let d = u - 128;
+ let e = v - 128;
+
+ let r = clamp_u8((298 * c + 409 * e + 128) >> 8);
+ let g = clamp_u8((298 * c - 100 * d - 208 * e + 128) >> 8);
+ let b = clamp_u8((298 * c + 516 * d + 128) >> 8);
+
+ let out_idx = out_row_start + col * 4;
+ if out_idx + 3 < output.len() {
+ output[out_idx] = r;
+ output[out_idx + 1] = g;
+ output[out_idx + 2] = b;
+ output[out_idx + 3] = 255;
+ }
+ }
+ }
+ }
+}
+
+#[cfg(not(any(target_arch = "x86_64", target_arch = "x86")))]
+pub fn nv12_to_rgba_simd(
+ y_data: &[u8],
+ uv_data: &[u8],
+ width: u32,
+ height: u32,
+ y_stride: u32,
+ uv_stride: u32,
+ output: &mut [u8],
+) {
+ nv12_to_rgba(y_data, uv_data, width, height, y_stride, uv_stride, output);
+}
+
+#[cfg(any(target_arch = "x86_64", target_arch = "x86"))]
+pub fn yuv420p_to_rgba_simd(
+ y_data: &[u8],
+ u_data: &[u8],
+ v_data: &[u8],
+ width: u32,
+ height: u32,
+ y_stride: u32,
+ uv_stride: u32,
+ output: &mut [u8],
+) {
+ #[cfg(target_arch = "x86")]
+ use std::arch::x86::*;
+ #[cfg(target_arch = "x86_64")]
+ use std::arch::x86_64::*;
+
+ if !is_x86_feature_detected!("sse2") {
+ return yuv420p_to_rgba(
+ y_data, u_data, v_data, width, height, y_stride, uv_stride, output,
+ );
+ }
+
+ let width_usize = width as usize;
+ let height_usize = height as usize;
+ let y_stride_usize = y_stride as usize;
+ let uv_stride_usize = uv_stride as usize;
+
+ let simd_width = (width_usize / 8) * 8;
+
+ unsafe {
+ let c16 = _mm_set1_epi16(16);
+ let c128 = _mm_set1_epi16(128);
+ let c298 = _mm_set1_epi16(298);
+ let c409 = _mm_set1_epi16(409);
+ let c100 = _mm_set1_epi16(100);
+ let c208 = _mm_set1_epi16(208);
+ let c516 = _mm_set1_epi16(516);
+ let zero = _mm_setzero_si128();
+
+ for row in 0..height_usize {
+ let y_row_start = row * y_stride_usize;
+ let uv_row_start = (row / 2) * uv_stride_usize;
+ let out_row_start = row * width_usize * 4;
+
+ let mut col = 0usize;
+
+ while col + 8 <= simd_width {
+ let y_ptr = y_data.as_ptr().add(y_row_start + col);
+ let u_ptr = u_data.as_ptr().add(uv_row_start + col / 2);
+ let v_ptr = v_data.as_ptr().add(uv_row_start + col / 2);
+
+ let y8 = _mm_loadl_epi64(y_ptr as *const __m128i);
+ let y16 = _mm_unpacklo_epi8(y8, zero);
+ let y_adj = _mm_sub_epi16(y16, c16);
+
+ let u4 = _mm_set_epi32(0, 0, 0, *(u_ptr as *const i32));
+ let v4 = _mm_set_epi32(0, 0, 0, *(v_ptr as *const i32));
+
+ let u_dup = _mm_unpacklo_epi8(u4, u4);
+ let v_dup = _mm_unpacklo_epi8(v4, v4);
+
+ let u16 = _mm_unpacklo_epi8(u_dup, zero);
+ let v16 = _mm_unpacklo_epi8(v_dup, zero);
+
+ let d = _mm_sub_epi16(u16, c128);
+ let e = _mm_sub_epi16(v16, c128);
+
+ let c_scaled = _mm_mullo_epi16(y_adj, c298);
+
+ let r_raw = _mm_add_epi16(c_scaled, _mm_mullo_epi16(e, c409));
+ let r_raw = _mm_add_epi16(r_raw, c128);
+ let r_raw = _mm_srai_epi16(r_raw, 8);
+
+ let g_raw = _mm_sub_epi16(c_scaled, _mm_mullo_epi16(d, c100));
+ let g_raw = _mm_sub_epi16(g_raw, _mm_mullo_epi16(e, c208));
+ let g_raw = _mm_add_epi16(g_raw, c128);
+ let g_raw = _mm_srai_epi16(g_raw, 8);
+
+ let b_raw = _mm_add_epi16(c_scaled, _mm_mullo_epi16(d, c516));
+ let b_raw = _mm_add_epi16(b_raw, c128);
+ let b_raw = _mm_srai_epi16(b_raw, 8);
+
+ let r = _mm_packus_epi16(r_raw, zero);
+ let g = _mm_packus_epi16(g_raw, zero);
+ let b = _mm_packus_epi16(b_raw, zero);
+ let a = _mm_set1_epi8(-1i8);
+
+ let rg_lo = _mm_unpacklo_epi8(r, g);
+ let ba_lo = _mm_unpacklo_epi8(b, a);
+ let rgba_lo = _mm_unpacklo_epi16(rg_lo, ba_lo);
+ let rgba_hi = _mm_unpackhi_epi16(rg_lo, ba_lo);
+
+ let out_ptr = output.as_mut_ptr().add(out_row_start + col * 4);
+ _mm_storeu_si128(out_ptr as *mut __m128i, rgba_lo);
+ _mm_storeu_si128(out_ptr.add(16) as *mut __m128i, rgba_hi);
+
+ col += 8;
+ }
+
+ for col in simd_width..width_usize {
+ let y_idx = y_row_start + col;
+ let uv_idx = uv_row_start + (col / 2);
+
+ let y = y_data.get(y_idx).copied().unwrap_or(0) as i32;
+ let u = u_data.get(uv_idx).copied().unwrap_or(128) as i32;
+ let v = v_data.get(uv_idx).copied().unwrap_or(128) as i32;
+
+ let c = y - 16;
+ let d = u - 128;
+ let e = v - 128;
+
+ let r = clamp_u8((298 * c + 409 * e + 128) >> 8);
+ let g = clamp_u8((298 * c - 100 * d - 208 * e + 128) >> 8);
+ let b = clamp_u8((298 * c + 516 * d + 128) >> 8);
+
+ let out_idx = out_row_start + col * 4;
+ if out_idx + 3 < output.len() {
+ output[out_idx] = r;
+ output[out_idx + 1] = g;
+ output[out_idx + 2] = b;
+ output[out_idx + 3] = 255;
+ }
+ }
+ }
+ }
+}
+
+#[cfg(not(any(target_arch = "x86_64", target_arch = "x86")))]
+pub fn yuv420p_to_rgba_simd(
+ y_data: &[u8],
+ u_data: &[u8],
+ v_data: &[u8],
+ width: u32,
+ height: u32,
+ y_stride: u32,
+ uv_stride: u32,
+ output: &mut [u8],
+) {
+ yuv420p_to_rgba(
+ y_data, u_data, v_data, width, height, y_stride, uv_stride, output,
+ );
+}
+
+#[inline(always)]
+fn clamp_u8(val: i32) -> u8 {
+ val.clamp(0, 255) as u8
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_nv12_basic_conversion() {
+ let width = 4u32;
+ let height = 4u32;
+ let y_stride = 4u32;
+ let uv_stride = 4u32;
+
+ let y_data: Vec<u8> = vec![
+ 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
+ ];
+ let uv_data: Vec<u8> = vec![128, 128, 128, 128, 128, 128, 128, 128];
+
+ let mut output = vec![0u8; (width * height * 4) as usize];
+ nv12_to_rgba(
+ &y_data,
+ &uv_data,
+ width,
+ height,
+ y_stride,
+ uv_stride,
+ &mut output,
+ );
+
+ for pixel in output.chunks(4) {
+ assert!(pixel[0] > 100 && pixel[0] < 140);
+ assert!(pixel[1] > 100 && pixel[1] < 140);
+ assert!(pixel[2] > 100 && pixel[2] < 140);
+ assert_eq!(pixel[3], 255);
+ }
+ }
+
+ #[test]
+ fn test_nv12_simd_matches_scalar() {
+ let width = 16u32;
+ let height = 8u32;
+ let y_stride = 16u32;
+ let uv_stride = 16u32;
+
+ let y_data: Vec<u8> = (0..width * height).map(|i| ((i * 7) % 256) as u8).collect();
+ let uv_data: Vec<u8> = (0..uv_stride * height / 2)
+ .map(|i| ((i * 11 + 64) % 256) as u8)
+ .collect();
+
+ let mut output_scalar = vec![0u8; (width * height * 4) as usize];
+ let mut output_simd = vec![0u8; (width * height * 4) as usize];
+
+ nv12_to_rgba(
+ &y_data,
+ &uv_data,
+ width,
+ height,
+ y_stride,
+ uv_stride,
+ &mut output_scalar,
+ );
+
+ nv12_to_rgba_simd(
+ &y_data,
+ &uv_data,
+ width,
+ height,
+ y_stride,
+ uv_stride,
+ &mut output_simd,
+ );
+
+ for (i, (s, d)) in output_scalar.iter().zip(output_simd.iter()).enumerate() {
+ let diff = (*s as i32 - *d as i32).abs();
+ assert!(
+ diff <= 2,
+ "Mismatch at index {}: scalar={}, simd={}, diff={}",
+ i,
+ s,
+ d,
+ diff
+ );
+ }
+ }
+}
diff --git a/crates/rendering/src/d3d_texture.rs b/crates/rendering/src/d3d_texture.rs
new file mode 100644
index 000000000..239c79758
--- /dev/null
+++ b/crates/rendering/src/d3d_texture.rs
@@ -0,0 +1,237 @@
+#[derive(Debug)]
+pub enum D3DTextureError {
+ NoD3D12Device,
+ TextureCreationFailed(String),
+ SharedHandleFailed(String),
+ WgpuImportFailed(String),
+ UnsupportedFormat,
+ DeviceMismatch,
+ #[cfg(not(target_os = "windows"))]
+ NotSupported,
+}
+
+impl std::fmt::Display for D3DTextureError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Self::NoD3D12Device => write!(f, "No D3D12 device available"),
+ Self::TextureCreationFailed(e) => write!(f, "Failed to create D3D texture: {e}"),
+ Self::SharedHandleFailed(e) => write!(f, "Failed to create shared handle: {e}"),
+ 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"),
+ #[cfg(not(target_os = "windows"))]
+ Self::NotSupported => write!(f, "D3D textures are only supported on Windows"),
+ }
+ }
+}
+
+impl std::error::Error for D3DTextureError {}
+
+#[cfg(target_os = "windows")]
+mod windows_impl {
+ use super::D3DTextureError;
+ use windows::{
+ Win32::{
+ Foundation::HANDLE,
+ Graphics::{
+ Direct3D11::{
+ D3D11_BIND_SHADER_RESOURCE, D3D11_RESOURCE_MISC_SHARED_NTHANDLE,
+ D3D11_TEXTURE2D_DESC, D3D11_USAGE_DEFAULT, ID3D11Device, ID3D11Texture2D,
+ },
+ Dxgi::Common::{
+ DXGI_FORMAT, DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_NV12,
+ DXGI_FORMAT_R8_UNORM, DXGI_FORMAT_R8G8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM,
+ DXGI_FORMAT_UNKNOWN, DXGI_SAMPLE_DESC,
+ },
+ },
+ },
+ core::Interface,
+ };
+
+ pub struct D3DTextureCache {
+ d3d11_device: ID3D11Device,
+ }
+
+ impl D3DTextureCache {
+ pub fn new(d3d11_device: ID3D11Device) -> Self {
+ Self { d3d11_device }
+ }
+
+ pub fn d3d11_device(&self) -> &ID3D11Device {
+ &self.d3d11_device
+ }
+
+ pub fn create_shared_texture(
+ &self,
+ width: u32,
+ height: u32,
+ format: DXGI_FORMAT,
+ ) -> Result<SharedD3D11Texture, D3DTextureError> {
+ SharedD3D11Texture::create(&self.d3d11_device, width, height, format)
+ }
+ }
+
+ pub struct SharedD3D11Texture {
+ pub texture: ID3D11Texture2D,
+ pub width: u32,
+ pub height: u32,
+ pub format: DXGI_FORMAT,
+ }
+
+ impl SharedD3D11Texture {
+ pub fn create_nv12(
+ device: &ID3D11Device,
+ width: u32,
+ height: u32,
+ ) -> Result<Self, D3DTextureError> {
+ Self::create(device, width, height, DXGI_FORMAT_NV12)
+ }
+
+ pub fn create_r8(
+ device: &ID3D11Device,
+ width: u32,
+ height: u32,
+ ) -> Result<Self, D3DTextureError> {
+ Self::create(device, width, height, DXGI_FORMAT_R8_UNORM)
+ }
+
+ pub fn create_rg8(
+ device: &ID3D11Device,
+ width: u32,
+ height: u32,
+ ) -> Result<Self, D3DTextureError> {
+ Self::create(device, width, height, DXGI_FORMAT_R8G8_UNORM)
+ }
+
+ pub fn create(
+ device: &ID3D11Device,
+ width: u32,
+ height: u32,
+ format: DXGI_FORMAT,
+ ) -> Result<Self, D3DTextureError> {
+ 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: D3D11_BIND_SHADER_RESOURCE.0 as u32,
+ CPUAccessFlags: 0,
+ MiscFlags: D3D11_RESOURCE_MISC_SHARED_NTHANDLE.0 as u32,
+ };
+
+ let texture = unsafe {
+ let mut texture: Option<ID3D11Texture2D> = None;
+ device
+ .CreateTexture2D(&desc, None, Some(&mut texture))
+ .map_err(|e| D3DTextureError::TextureCreationFailed(format!("{e:?}")))?;
+ texture.ok_or_else(|| {
+ D3DTextureError::TextureCreationFailed(
+ "CreateTexture2D returned null".to_string(),
+ )
+ })?
+ };
+
+ Ok(Self {
+ texture,
+ width,
+ height,
+ format,
+ })
+ }
+
+ pub fn as_raw_ptr(&self) -> *mut std::ffi::c_void {
+ self.texture.as_raw()
+ }
+ }
+
+ pub struct D3DYuvTextures {
+ pub y_texture: SharedD3D11Texture,
+ pub uv_texture: SharedD3D11Texture,
+ pub width: u32,
+ pub height: u32,
+ }
+
+ impl D3DYuvTextures {
+ pub fn create_nv12(
+ device: &ID3D11Device,
+ width: u32,
+ height: u32,
+ ) -> Result<Self, D3DTextureError> {
+ let y_texture = SharedD3D11Texture::create_r8(device, width, height)?;
+ let uv_texture = SharedD3D11Texture::create_rg8(device, width / 2, height / 2)?;
+
+ Ok(Self {
+ y_texture,
+ uv_texture,
+ width,
+ height,
+ })
+ }
+ }
+
+ pub fn wgpu_to_dxgi_format(format: wgpu::TextureFormat) -> DXGI_FORMAT {
+ match format {
+ wgpu::TextureFormat::R8Unorm => DXGI_FORMAT_R8_UNORM,
+ wgpu::TextureFormat::Rg8Unorm => DXGI_FORMAT_R8G8_UNORM,
+ wgpu::TextureFormat::Rgba8Unorm => DXGI_FORMAT_R8G8B8A8_UNORM,
+ wgpu::TextureFormat::Bgra8Unorm => DXGI_FORMAT_B8G8R8A8_UNORM,
+ _ => DXGI_FORMAT_UNKNOWN,
+ }
+ }
+
+ #[allow(unused_variables)]
+ pub fn import_d3d11_texture_to_wgpu(
+ device: &wgpu::Device,
+ shared_handle: HANDLE,
+ format: wgpu::TextureFormat,
+ width: u32,
+ 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(),
+ ))
+ }
+
+ pub struct D3D11WgpuInterop {
+ cached_width: u32,
+ cached_height: u32,
+ y_wgpu_texture: Option<wgpu::Texture>,
+ uv_wgpu_texture: Option<wgpu::Texture>,
+ }
+
+ impl D3D11WgpuInterop {
+ pub fn new() -> Self {
+ Self {
+ cached_width: 0,
+ cached_height: 0,
+ y_wgpu_texture: None,
+ uv_wgpu_texture: None,
+ }
+ }
+
+ #[allow(unused_variables)]
+ pub fn import_nv12_planes(
+ &mut self,
+ device: &wgpu::Device,
+ y_handle: HANDLE,
+ uv_handle: HANDLE,
+ width: u32,
+ height: u32,
+ ) -> Result<(&wgpu::Texture, &wgpu::Texture), D3DTextureError> {
+ Err(D3DTextureError::WgpuImportFailed(
+ "D3D11-to-wgpu HAL interop not yet implemented".to_string(),
+ ))
+ }
+ }
+}
+
+#[cfg(target_os = "windows")]
+pub use windows_impl::*;
diff --git a/crates/rendering/src/decoder/media_foundation.rs b/crates/rendering/src/decoder/media_foundation.rs
new file mode 100644
index 000000000..9a42f8ba1
--- /dev/null
+++ b/crates/rendering/src/decoder/media_foundation.rs
@@ -0,0 +1,259 @@
+use std::{
+ collections::BTreeMap,
+ path::PathBuf,
+ sync::{Arc, mpsc},
+};
+use tokio::sync::oneshot;
+use tracing::{debug, info, warn};
+use windows::Win32::{Foundation::HANDLE, Graphics::Direct3D11::ID3D11Texture2D};
+
+use super::{DecodedFrame, FRAME_CACHE_SIZE, VideoDecoderMessage};
+
+#[derive(Clone)]
+struct CachedFrame {
+ number: u32,
+ texture: ID3D11Texture2D,
+ shared_handle: Option<HANDLE>,
+ y_handle: Option<HANDLE>,
+ uv_handle: Option<HANDLE>,
+ nv12_data: Option<Arc<cap_video_decode::NV12Data>>,
+ width: u32,
+ height: u32,
+}
+
+impl CachedFrame {
+ fn to_decoded_frame(&self) -> DecodedFrame {
+ if let Some(nv12_data) = &self.nv12_data {
+ DecodedFrame::new_nv12(
+ nv12_data.data.clone(),
+ self.width,
+ self.height,
+ nv12_data.y_stride,
+ nv12_data.uv_stride,
+ )
+ } else {
+ warn!(
+ "CachedFrame has no CPU data, creating black frame (D3D11 zero-copy not implemented)"
+ );
+ let black_data = vec![0u8; (self.width * self.height * 3 / 2) as usize];
+ DecodedFrame::new_nv12(black_data, self.width, self.height, self.width, self.width)
+ }
+ }
+}
+
+pub struct MFDecoder;
+
+impl MFDecoder {
+ pub fn spawn(
+ name: &'static str,
+ path: PathBuf,
+ fps: u32,
+ rx: mpsc::Receiver<VideoDecoderMessage>,
+ ready_tx: oneshot::Sender<Result<(), String>>,
+ ) -> Result<(), String> {
+ let (continue_tx, continue_rx) = mpsc::channel();
+
+ std::thread::spawn(move || {
+ let mut decoder = match cap_video_decode::MediaFoundationDecoder::new(&path) {
+ Err(e) => {
+ let _ = continue_tx.send(Err(e));
+ return;
+ }
+ Ok(v) => {
+ info!(
+ "MediaFoundation decoder created for '{}': {}x{} @ {:?}fps",
+ name,
+ v.width(),
+ v.height(),
+ v.frame_rate()
+ );
+ let _ = continue_tx.send(Ok(()));
+ v
+ }
+ };
+
+ let video_width = decoder.width();
+ let video_height = decoder.height();
+
+ let mut cache = BTreeMap::<u32, CachedFrame>::new();
+ let mut last_decoded_frame: Option<u32> = None;
+
+ let _ = ready_tx.send(Ok(()));
+
+ while let Ok(r) = rx.recv() {
+ match r {
+ VideoDecoderMessage::GetFrame(requested_time, sender) => {
+ if sender.is_closed() {
+ continue;
+ }
+
+ let requested_frame = (requested_time * fps as f32).floor() as u32;
+
+ if let Some(cached) = cache.get(&requested_frame) {
+ if sender.send(cached.to_decoded_frame()).is_err() {
+ warn!(
+ "Failed to send cached frame {requested_frame}: receiver dropped"
+ );
+ }
+ continue;
+ }
+
+ let cache_min = requested_frame.saturating_sub(FRAME_CACHE_SIZE as u32 / 2);
+ let cache_max = requested_frame + FRAME_CACHE_SIZE as u32 / 2;
+
+ let needs_seek = last_decoded_frame
+ .map(|last| {
+ requested_frame < last
+ || requested_frame.saturating_sub(last)
+ > FRAME_CACHE_SIZE as u32
+ })
+ .unwrap_or(true);
+
+ if needs_seek {
+ debug!("MediaFoundation seeking to frame {requested_frame}");
+ let time_100ns = frame_to_100ns(requested_frame, fps);
+ if let Err(e) = decoder.seek(time_100ns) {
+ warn!("MediaFoundation seek failed: {e}");
+ }
+ cache.clear();
+ last_decoded_frame = None;
+ }
+
+ let mut sender = Some(sender);
+ let mut last_valid_frame: Option<CachedFrame> = None;
+
+ loop {
+ match decoder.read_sample() {
+ Ok(Some(mf_frame)) => {
+ 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.width,
+ mf_frame.height,
+ ) {
+ Ok(data) => {
+ debug!(
+ frame = frame_number,
+ data_len = data.data.len(),
+ y_stride = data.y_stride,
+ uv_stride = data.uv_stride,
+ width = mf_frame.width,
+ height = mf_frame.height,
+ "read_texture_to_cpu succeeded"
+ );
+ Some(Arc::new(data))
+ }
+ Err(e) => {
+ warn!(
+ "Failed to read texture to CPU for frame {frame_number}: {e}"
+ );
+ None
+ }
+ };
+
+ 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,
+ nv12_data,
+ width: mf_frame.width,
+ height: mf_frame.height,
+ };
+
+ last_decoded_frame = Some(frame_number);
+
+ if frame_number >= cache_min && frame_number <= cache_max {
+ if cache.len() >= FRAME_CACHE_SIZE {
+ let key_to_remove = if frame_number > requested_frame {
+ *cache.keys().next().unwrap()
+ } else {
+ *cache.keys().next_back().unwrap()
+ };
+ cache.remove(&key_to_remove);
+ }
+ cache.insert(frame_number, cached.clone());
+ }
+
+ if frame_number <= requested_frame {
+ last_valid_frame = Some(cached);
+ }
+
+ if frame_number >= requested_frame {
+ let frame_to_send = if frame_number == requested_frame {
+ cache.get(&requested_frame)
+ } else {
+ last_valid_frame
+ .as_ref()
+ .or_else(|| cache.get(&frame_number))
+ };
+
+ if let Some(frame) = frame_to_send {
+ if let Some(s) = sender.take() {
+ if s.send(frame.to_decoded_frame()).is_err() {
+ warn!(
+ "Failed to send frame {}: receiver dropped",
+ frame.number
+ );
+ }
+ }
+ }
+ break;
+ }
+
+ if frame_number > cache_max {
+ break;
+ }
+ }
+ Ok(None) => {
+ debug!("MediaFoundation end of stream");
+ break;
+ }
+ Err(e) => {
+ warn!("MediaFoundation read_sample error: {e}");
+ break;
+ }
+ }
+ }
+
+ if let Some(s) = sender.take() {
+ if let Some(frame) = last_valid_frame
+ .or_else(|| cache.values().max_by_key(|f| f.number).cloned())
+ {
+ if s.send(frame.to_decoded_frame()).is_err() {
+ warn!("Failed to send fallback frame: receiver dropped");
+ }
+ } else {
+ debug!(
+ "No frames available for request {requested_frame}, sending black frame"
+ );
+ let black_frame = DecodedFrame::new(
+ vec![0u8; (video_width * video_height * 4) as usize],
+ video_width,
+ video_height,
+ );
+ if s.send(black_frame).is_err() {
+ warn!("Failed to send black frame: receiver dropped");
+ }
+ }
+ }
+ }
+ }
+ }
+ });
+
+ continue_rx.recv().map_err(|e| e.to_string())??;
+
+ Ok(())
+ }
+}
+
+fn frame_to_100ns(frame: u32, fps: u32) -> i64 {
+ ((frame as i64) * 10_000_000) / (fps as i64)
+}
+
+fn pts_100ns_to_frame(pts_100ns: i64, fps: u32) -> u32 {
+ ((pts_100ns * fps as i64) / 10_000_000) as u32
+}
diff --git a/crates/rendering/src/decoder/mod.rs b/crates/rendering/src/decoder/mod.rs
index c0ebef38a..ca83553cf 100644
--- a/crates/rendering/src/decoder/mod.rs
+++ b/crates/rendering/src/decoder/mod.rs
@@ -11,10 +11,15 @@ use tracing::debug;
mod avassetreader;
mod ffmpeg;
mod frame_converter;
+#[cfg(target_os = "windows")]
+mod media_foundation;
#[cfg(target_os = "macos")]
use cidre::{arc::R, cv};
+#[cfg(target_os = "windows")]
+use windows::Win32::{Foundation::HANDLE, Graphics::Direct3D11::ID3D11Texture2D};
+
#[cfg(target_os = "macos")]
pub struct SendableImageBuf(R<cv::ImageBuf>);
@@ -34,6 +39,70 @@ impl SendableImageBuf {
}
}
+#[cfg(target_os = "windows")]
+pub struct SendableD3D11Texture {
+ texture: ID3D11Texture2D,
+ shared_handle: Option<HANDLE>,
+ y_handle: Option<HANDLE>,
+ uv_handle: Option<HANDLE>,
+}
+
+#[cfg(target_os = "windows")]
+unsafe impl Send for SendableD3D11Texture {}
+#[cfg(target_os = "windows")]
+unsafe impl Sync for SendableD3D11Texture {}
+
+#[cfg(target_os = "windows")]
+impl SendableD3D11Texture {
+ pub fn new(texture: ID3D11Texture2D) -> Self {
+ Self {
+ texture,
+ shared_handle: None,
+ y_handle: None,
+ uv_handle: None,
+ }
+ }
+
+ pub fn new_with_handle(texture: ID3D11Texture2D, shared_handle: Option<HANDLE>) -> Self {
+ Self {
+ texture,
+ shared_handle,
+ y_handle: None,
+ uv_handle: None,
+ }
+ }
+
+ pub fn new_with_yuv_handles(
+ texture: ID3D11Texture2D,
+ shared_handle: Option<HANDLE>,
+ y_handle: Option<HANDLE>,
+ uv_handle: Option<HANDLE>,
+ ) -> Self {
+ Self {
+ texture,
+ shared_handle,
+ y_handle,
+ uv_handle,
+ }
+ }
+
+ pub fn inner(&self) -> &ID3D11Texture2D {
+ &self.texture
+ }
+
+ pub fn shared_handle(&self) -> Option<HANDLE> {
+ self.shared_handle
+ }
+
+ pub fn y_handle(&self) -> Option<HANDLE> {
+ self.y_handle
+ }
+
+ pub fn uv_handle(&self) -> Option<HANDLE> {
+ self.uv_handle
+ }
+}
+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PixelFormat {
Rgba,
@@ -51,6 +120,8 @@ pub struct DecodedFrame {
uv_stride: u32,
#[cfg(target_os = "macos")]
iosurface_backing: Option<Arc<SendableImageBuf>>,
+ #[cfg(target_os = "windows")]
+ d3d11_texture_backing: Option<Arc<SendableD3D11Texture>>,
}
impl fmt::Debug for DecodedFrame {
@@ -77,6 +148,8 @@ impl DecodedFrame {
uv_stride: 0,
#[cfg(target_os = "macos")]
iosurface_backing: None,
+ #[cfg(target_os = "windows")]
+ d3d11_texture_backing: None,
}
}
@@ -90,6 +163,8 @@ impl DecodedFrame {
uv_stride,
#[cfg(target_os = "macos")]
iosurface_backing: None,
+ #[cfg(target_os = "windows")]
+ d3d11_texture_backing: None,
}
}
@@ -109,6 +184,8 @@ impl DecodedFrame {
uv_stride,
#[cfg(target_os = "macos")]
iosurface_backing: None,
+ #[cfg(target_os = "windows")]
+ d3d11_texture_backing: None,
}
}
@@ -137,6 +214,91 @@ impl DecodedFrame {
self.iosurface_backing.as_ref().map(|b| b.inner())
}
+ #[cfg(target_os = "windows")]
+ pub fn new_nv12_with_d3d11_texture(width: u32, height: u32, texture: ID3D11Texture2D) -> Self {
+ Self {
+ data: Arc::new(Vec::new()),
+ width,
+ height,
+ format: PixelFormat::Nv12,
+ y_stride: width,
+ uv_stride: width,
+ d3d11_texture_backing: Some(Arc::new(SendableD3D11Texture::new(texture))),
+ }
+ }
+
+ #[cfg(target_os = "windows")]
+ pub fn new_nv12_with_d3d11_texture_and_handle(
+ width: u32,
+ height: u32,
+ texture: ID3D11Texture2D,
+ shared_handle: Option<HANDLE>,
+ ) -> Self {
+ Self {
+ data: Arc::new(Vec::new()),
+ width,
+ height,
+ format: PixelFormat::Nv12,
+ y_stride: width,
+ uv_stride: width,
+ d3d11_texture_backing: Some(Arc::new(SendableD3D11Texture::new_with_handle(
+ texture,
+ shared_handle,
+ ))),
+ }
+ }
+
+ #[cfg(target_os = "windows")]
+ pub fn new_nv12_with_d3d11_texture_and_yuv_handles(
+ width: u32,
+ height: u32,
+ texture: ID3D11Texture2D,
+ shared_handle: Option<HANDLE>,
+ y_handle: Option<HANDLE>,
+ uv_handle: Option<HANDLE>,
+ ) -> Self {
+ Self {
+ data: Arc::new(Vec::new()),
+ width,
+ height,
+ format: PixelFormat::Nv12,
+ y_stride: width,
+ uv_stride: width,
+ d3d11_texture_backing: Some(Arc::new(SendableD3D11Texture::new_with_yuv_handles(
+ texture,
+ shared_handle,
+ y_handle,
+ uv_handle,
+ ))),
+ }
+ }
+
+ #[cfg(target_os = "windows")]
+ pub fn d3d11_texture_backing(&self) -> Option<&ID3D11Texture2D> {
+ self.d3d11_texture_backing.as_ref().map(|b| b.inner())
+ }
+
+ #[cfg(target_os = "windows")]
+ pub fn d3d11_shared_handle(&self) -> Option<HANDLE> {
+ self.d3d11_texture_backing
+ .as_ref()
+ .and_then(|b| b.shared_handle())
+ }
+
+ #[cfg(target_os = "windows")]
+ pub fn d3d11_y_handle(&self) -> Option<HANDLE> {
+ self.d3d11_texture_backing
+ .as_ref()
+ .and_then(|b| b.y_handle())
+ }
+
+ #[cfg(target_os = "windows")]
+ pub fn d3d11_uv_handle(&self) -> Option<HANDLE> {
+ self.d3d11_texture_backing
+ .as_ref()
+ .and_then(|b| b.uv_handle())
+ }
+
pub fn data(&self) -> &[u8] {
&self.data
}
@@ -276,10 +438,44 @@ pub async fn spawn_decoder(
let path_display = path.display().to_string();
- if cfg!(target_os = "macos") {
- #[cfg(target_os = "macos")]
+ #[cfg(target_os = "macos")]
+ {
avassetreader::AVAssetReaderDecoder::spawn(name, path, fps, rx, ready_tx);
- } else {
+ }
+
+ #[cfg(target_os = "windows")]
+ {
+ match media_foundation::MFDecoder::spawn(name, path.clone(), fps, rx, ready_tx) {
+ Ok(()) => {
+ debug!("Using MediaFoundation decoder for '{name}'");
+ }
+ Err(mf_err) => {
+ debug!(
+ "MediaFoundation decoder failed for '{name}': {mf_err}, falling back to FFmpeg"
+ );
+ let (ready_tx, ready_rx_new) = oneshot::channel::<Result<(), String>>();
+ let (tx, rx) = mpsc::channel();
+ let handle = AsyncVideoDecoderHandle { sender: tx, offset };
+
+ ffmpeg::FfmpegDecoder::spawn(name, path, fps, rx, ready_tx)
+ .map_err(|e| format!("'{name}' decoder / {e}"))?;
+
+ return match tokio::time::timeout(std::time::Duration::from_secs(30), ready_rx_new)
+ .await
+ {
+ Ok(result) => result
+ .map_err(|e| format!("'{name}' decoder channel closed: {e}"))?
+ .map(|()| handle),
+ Err(_) => Err(format!(
+ "'{name}' decoder timed out after 30s initializing: {path_display}"
+ )),
+ };
+ }
+ }
+ }
+
+ #[cfg(not(any(target_os = "macos", target_os = "windows")))]
+ {
ffmpeg::FfmpegDecoder::spawn(name, path, fps, rx, ready_tx)
.map_err(|e| format!("'{name}' decoder / {e}"))?;
}
diff --git a/crates/rendering/src/layers/display.rs b/crates/rendering/src/layers/display.rs
index 701a34b37..1db8a3537 100644
--- a/crates/rendering/src/layers/display.rs
+++ b/crates/rendering/src/layers/display.rs
@@ -22,10 +22,15 @@ pub struct DisplayLayer {
last_recording_time: Option<f32>,
yuv_converter: YuvToRgbaConverter,
pending_copy: Option<PendingTextureCopy>,
+ prefer_cpu_conversion: bool,
}
impl DisplayLayer {
pub fn new(device: &wgpu::Device) -> Self {
+ Self::new_with_options(device, false)
+ }
+
+ pub fn new_with_options(device: &wgpu::Device, prefer_cpu_conversion: bool) -> 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());
@@ -40,6 +45,10 @@ impl DisplayLayer {
let yuv_converter = YuvToRgbaConverter::new(device);
+ if prefer_cpu_conversion {
+ tracing::info!("DisplayLayer initialized with CPU YUV conversion preference");
+ }
+
Self {
frame_textures: [frame_texture_0, frame_texture_1],
frame_texture_views: [frame_texture_view_0, frame_texture_view_1],
@@ -50,6 +59,7 @@ impl DisplayLayer {
last_recording_time: None,
yuv_converter,
pending_copy: None,
+ prefer_cpu_conversion,
}
}
@@ -139,14 +149,64 @@ impl DisplayLayer {
});
#[cfg(target_os = "macos")]
- if let Some(Ok(_)) = iosurface_result {
- if self.yuv_converter.output_texture().is_some() {
- self.pending_copy = Some(PendingTextureCopy {
- width: frame_size.x,
- height: frame_size.y,
- dst_texture_index: next_texture,
- });
- true
+ if !self.prefer_cpu_conversion {
+ if let Some(Ok(_)) = iosurface_result {
+ if self.yuv_converter.output_texture().is_some() {
+ self.pending_copy = Some(PendingTextureCopy {
+ width: frame_size.x,
+ height: frame_size.y,
+ dst_texture_index: next_texture,
+ });
+ true
+ } else {
+ false
+ }
+ } else if let (Some(y_data), Some(uv_data)) =
+ (screen_frame.y_plane(), screen_frame.uv_plane())
+ {
+ let y_stride = screen_frame.y_stride();
+ let uv_stride = screen_frame.uv_stride();
+ let convert_result = self.yuv_converter.convert_nv12(
+ device,
+ queue,
+ y_data,
+ uv_data,
+ frame_size.x,
+ frame_size.y,
+ y_stride,
+ uv_stride,
+ );
+
+ match convert_result {
+ Ok(_) => {
+ if self.yuv_converter.output_texture().is_some() {
+ self.pending_copy = Some(PendingTextureCopy {
+ width: frame_size.x,
+ height: frame_size.y,
+ dst_texture_index: next_texture,
+ });
+ true
+ } else {
+ tracing::debug!(
+ width = frame_size.x,
+ height = frame_size.y,
+ y_stride,
+ "NV12 conversion succeeded but output texture is None, skipping copy"
+ );
+ false
+ }
+ }
+ Err(e) => {
+ tracing::debug!(
+ error = ?e,
+ width = frame_size.x,
+ height = frame_size.y,
+ y_stride,
+ "NV12 to RGBA conversion failed"
+ );
+ false
+ }
+ }
} else {
false
}
@@ -155,7 +215,7 @@ impl DisplayLayer {
{
let y_stride = screen_frame.y_stride();
let uv_stride = screen_frame.uv_stride();
- let convert_result = self.yuv_converter.convert_nv12(
+ let convert_result = self.yuv_converter.convert_nv12_cpu(
device,
queue,
y_data,
@@ -176,23 +236,11 @@ impl DisplayLayer {
});
true
} else {
- tracing::debug!(
- width = frame_size.x,
- height = frame_size.y,
- y_stride,
- "NV12 conversion succeeded but output texture is None, skipping copy"
- );
false
}
}
Err(e) => {
- tracing::debug!(
- error = ?e,
- width = frame_size.x,
- height = frame_size.y,
- y_stride,
- "NV12 to RGBA conversion failed"
- );
+ tracing::debug!(error = ?e, "CPU NV12 conversion failed");
false
}
}
@@ -200,23 +248,166 @@ impl DisplayLayer {
false
}
- #[cfg(not(target_os = "macos"))]
+ #[cfg(target_os = "windows")]
+ {
+ let mut d3d11_succeeded = false;
+
+ let has_y_handle = screen_frame.d3d11_y_handle().is_some();
+ let has_uv_handle = screen_frame.d3d11_uv_handle().is_some();
+ let has_y_plane = screen_frame.y_plane().is_some();
+ let has_uv_plane = screen_frame.uv_plane().is_some();
+
+ tracing::debug!(
+ has_y_handle,
+ has_uv_handle,
+ has_y_plane,
+ has_uv_plane,
+ data_len = screen_frame.data().len(),
+ y_stride = screen_frame.y_stride(),
+ uv_stride = screen_frame.uv_stride(),
+ actual_width,
+ actual_height,
+ frame_size_x = frame_size.x,
+ frame_size_y = frame_size.y,
+ "Windows NV12 frame info"
+ );
+
+ if let (Some(y_handle), Some(uv_handle)) = (
+ screen_frame.d3d11_y_handle(),
+ screen_frame.d3d11_uv_handle(),
+ ) {
+ tracing::trace!("Using D3D11 zero-copy path for NV12 conversion");
+ match self.yuv_converter.convert_nv12_from_d3d11_shared_handles(
+ device,
+ queue,
+ y_handle,
+ uv_handle,
+ actual_width,
+ actual_height,
+ ) {
+ 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,
+ });
+ d3d11_succeeded = true;
+ }
+ }
+ Err(e) => {
+ tracing::debug!(error = ?e, "D3D11 zero-copy conversion failed, falling back to CPU path");
+ }
+ }
+ }
+
+ if d3d11_succeeded {
+ true
+ } else if let (Some(y_data), Some(uv_data)) =
+ (screen_frame.y_plane(), screen_frame.uv_plane())
+ {
+ let y_stride = screen_frame.y_stride();
+ let uv_stride = screen_frame.uv_stride();
+
+ tracing::debug!(
+ y_data_len = y_data.len(),
+ uv_data_len = uv_data.len(),
+ y_stride,
+ uv_stride,
+ actual_width,
+ actual_height,
+ prefer_cpu = self.prefer_cpu_conversion,
+ "Attempting NV12 conversion"
+ );
+
+ 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,
+ )
+ } else {
+ self.yuv_converter.convert_nv12(
+ device,
+ queue,
+ y_data,
+ uv_data,
+ actual_width,
+ actual_height,
+ y_stride,
+ uv_stride,
+ )
+ };
+
+ if let Err(e) = device.poll(wgpu::PollType::Wait) {
+ tracing::warn!(error = ?e, "Failed to poll device after NV12 conversion");
+ }
+
+ match convert_result {
+ Ok(_) => {
+ tracing::debug!("NV12 conversion succeeded");
+ 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 {
+ tracing::warn!(
+ "NV12 conversion succeeded but output texture is None"
+ );
+ false
+ }
+ }
+ Err(e) => {
+ tracing::warn!(error = ?e, "NV12 conversion failed");
+ false
+ }
+ }
+ } else {
+ tracing::warn!(
+ "No D3D11 handles and no CPU data available for NV12 frame"
+ );
+ false
+ }
+ }
+
+ #[cfg(not(any(target_os = "macos", target_os = "windows")))]
if let (Some(y_data), Some(uv_data)) =
(screen_frame.y_plane(), screen_frame.uv_plane())
{
let y_stride = screen_frame.y_stride();
let uv_stride = screen_frame.uv_stride();
- let convert_result = self.yuv_converter.convert_nv12(
- device,
- queue,
- y_data,
- uv_data,
- frame_size.x,
- frame_size.y,
- y_stride,
- uv_stride,
- );
+ let convert_result = if self.prefer_cpu_conversion {
+ self.yuv_converter.convert_nv12_cpu(
+ device,
+ queue,
+ y_data,
+ uv_data,
+ frame_size.x,
+ frame_size.y,
+ y_stride,
+ uv_stride,
+ )
+ } else {
+ self.yuv_converter.convert_nv12(
+ device,
+ queue,
+ y_data,
+ uv_data,
+ frame_size.x,
+ frame_size.y,
+ y_stride,
+ uv_stride,
+ )
+ };
if let Err(e) = device.poll(wgpu::PollType::Wait) {
tracing::warn!(error = ?e, "Failed to poll device after NV12 conversion");
@@ -249,17 +440,31 @@ impl DisplayLayer {
if let (Some(y_data), Some(u_data), Some(v_data)) = (y_plane, u_plane, v_plane)
{
- let convert_result = self.yuv_converter.convert_yuv420p(
- device,
- queue,
- y_data,
- u_data,
- v_data,
- frame_size.x,
- frame_size.y,
- screen_frame.y_stride(),
- screen_frame.uv_stride(),
- );
+ let convert_result = if self.prefer_cpu_conversion {
+ self.yuv_converter.convert_yuv420p_cpu(
+ device,
+ queue,
+ y_data,
+ u_data,
+ v_data,
+ frame_size.x,
+ frame_size.y,
+ screen_frame.y_stride(),
+ screen_frame.uv_stride(),
+ )
+ } else {
+ self.yuv_converter.convert_yuv420p(
+ device,
+ queue,
+ y_data,
+ u_data,
+ v_data,
+ frame_size.x,
+ frame_size.y,
+ screen_frame.y_stride(),
+ screen_frame.uv_stride(),
+ )
+ };
if let Err(e) = device.poll(wgpu::PollType::Wait) {
tracing::warn!(error = ?e, "Failed to poll device after YUV420P conversion");
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index 0f0167a2a..b781874bf 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -22,7 +22,10 @@ use tokio::sync::mpsc;
mod composite_frame;
mod coord;
+pub mod cpu_yuv;
mod cursor_interpolation;
+#[cfg(target_os = "windows")]
+pub mod d3d_texture;
pub mod decoder;
mod frame_pipeline;
#[cfg(target_os = "macos")]
@@ -268,7 +271,11 @@ pub async fn render_video_to_channel(
let mut frame_renderer = FrameRenderer::new(constants);
- let mut layers = RendererLayers::new(&constants.device, &constants.queue);
+ let mut layers = RendererLayers::new_with_options(
+ &constants.device,
+ &constants.queue,
+ constants.is_software_adapter,
+ );
loop {
if frame_number >= total_frames {
@@ -372,6 +379,7 @@ pub struct RenderVideoConstants {
pub meta: StudioRecordingMeta,
pub recording_meta: RecordingMeta,
pub background_textures: std::sync::Arc<tokio::sync::RwLock<HashMap<String, wgpu::Texture>>>,
+ pub is_software_adapter: bool,
}
impl RenderVideoConstants {
@@ -391,14 +399,41 @@ impl RenderVideoConstants {
};
let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor::default());
- let adapter = instance
+
+ let hardware_adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::HighPerformance,
force_fallback_adapter: false,
compatible_surface: None,
})
.await
- .map_err(|_| RenderingError::NoAdapter)?;
+ .ok();
+
+ let (adapter, is_software_adapter) = if let Some(adapter) = hardware_adapter {
+ tracing::info!(
+ adapter_name = adapter.get_info().name,
+ adapter_backend = ?adapter.get_info().backend,
+ "Using hardware GPU adapter"
+ );
+ (adapter, false)
+ } else {
+ tracing::warn!("No hardware GPU adapter found, attempting software fallback");
+ let software_adapter = instance
+ .request_adapter(&wgpu::RequestAdapterOptions {
+ power_preference: wgpu::PowerPreference::LowPower,
+ force_fallback_adapter: true,
+ compatible_surface: None,
+ })
+ .await
+ .map_err(|_| RenderingError::NoAdapter)?;
+
+ tracing::info!(
+ adapter_name = software_adapter.get_info().name,
+ adapter_backend = ?software_adapter.get_info().backend,
+ "Using software adapter (CPU rendering - performance may be reduced)"
+ );
+ (software_adapter, true)
+ };
let device_descriptor = wgpu::DeviceDescriptor {
label: Some("cap-rendering-device"),
@@ -419,6 +454,7 @@ impl RenderVideoConstants {
background_textures,
meta,
recording_meta,
+ is_software_adapter,
})
}
}
@@ -1598,10 +1634,18 @@ pub struct RendererLayers {
impl RendererLayers {
pub fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Self {
+ Self::new_with_options(device, queue, false)
+ }
+
+ pub fn new_with_options(
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ prefer_cpu_conversion: bool,
+ ) -> Self {
Self {
background: BackgroundLayer::new(device),
background_blur: BlurLayer::new(device),
- display: DisplayLayer::new(device),
+ display: DisplayLayer::new_with_options(device, prefer_cpu_conversion),
cursor: CursorLayer::new(device),
camera: CameraLayer::new(device),
camera_only: CameraLayer::new(device),
diff --git a/crates/rendering/src/yuv_converter.rs b/crates/rendering/src/yuv_converter.rs
index cb5786bda..32097dbc9 100644
--- a/crates/rendering/src/yuv_converter.rs
+++ b/crates/rendering/src/yuv_converter.rs
@@ -1,3 +1,4 @@
+use crate::cpu_yuv;
use crate::decoder::PixelFormat;
#[cfg(target_os = "macos")]
@@ -8,6 +9,15 @@ use crate::iosurface_texture::{
#[cfg(target_os = "macos")]
use cidre::cv;
+#[cfg(target_os = "windows")]
+use crate::d3d_texture::D3DTextureError;
+
+#[cfg(target_os = "windows")]
+use windows::Win32::Graphics::Direct3D11::{
+ D3D11_CPU_ACCESS_READ, D3D11_MAP_READ, D3D11_MAPPED_SUBRESOURCE, D3D11_TEXTURE2D_DESC,
+ D3D11_USAGE_STAGING, ID3D11Device, ID3D11DeviceContext, ID3D11Texture2D,
+};
+
#[derive(Debug, thiserror::Error)]
pub enum YuvConversionError {
#[error("{plane} plane size mismatch: expected {expected}, got {actual}")]
@@ -19,6 +29,12 @@ pub enum YuvConversionError {
#[cfg(target_os = "macos")]
#[error("IOSurface error: {0}")]
IOSurfaceError(#[from] IOSurfaceTextureError),
+ #[cfg(target_os = "windows")]
+ #[error("D3D texture error: {0}")]
+ D3DTextureError(#[from] D3DTextureError),
+ #[cfg(target_os = "windows")]
+ #[error("D3D11 error: {0}")]
+ D3D11Error(String),
}
fn upload_plane_with_stride(
@@ -81,6 +97,12 @@ pub struct YuvToRgbaConverter {
cached_format: Option<PixelFormat>,
#[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,
}
impl YuvToRgbaConverter {
@@ -234,6 +256,12 @@ impl YuvToRgbaConverter {
cached_format: None,
#[cfg(target_os = "macos")]
iosurface_cache: IOSurfaceTextureCache::new(),
+ #[cfg(target_os = "windows")]
+ d3d11_staging_texture: None,
+ #[cfg(target_os = "windows")]
+ d3d11_staging_width: 0,
+ #[cfg(target_os = "windows")]
+ d3d11_staging_height: 0,
}
}
@@ -655,6 +683,405 @@ impl YuvToRgbaConverter {
Ok(self.output_view.as_ref().unwrap())
}
+ #[cfg(target_os = "windows")]
+ pub fn convert_nv12_from_d3d11_texture(
+ &mut self,
+ wgpu_device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ d3d11_device: &ID3D11Device,
+ d3d11_context: &ID3D11DeviceContext,
+ nv12_texture: &ID3D11Texture2D,
+ width: u32,
+ height: u32,
+ ) -> Result<&wgpu::TextureView, YuvConversionError> {
+ use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_NV12;
+
+ if self.d3d11_staging_width != width
+ || self.d3d11_staging_height != height
+ || self.d3d11_staging_texture.is_none()
+ {
+ let desc = D3D11_TEXTURE2D_DESC {
+ Width: width,
+ Height: height,
+ MipLevels: 1,
+ ArraySize: 1,
+ Format: DXGI_FORMAT_NV12,
+ SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC {
+ Count: 1,
+ Quality: 0,
+ },
+ Usage: D3D11_USAGE_STAGING,
+ BindFlags: 0,
+ CPUAccessFlags: D3D11_CPU_ACCESS_READ.0 as u32,
+ MiscFlags: 0,
+ };
+
+ let staging_texture = unsafe {
+ let mut texture: Option<ID3D11Texture2D> = None;
+ d3d11_device
+ .CreateTexture2D(&desc, None, Some(&mut texture))
+ .map_err(|e| {
+ YuvConversionError::D3D11Error(format!("CreateTexture2D failed: {e:?}"))
+ })?;
+ texture.ok_or_else(|| {
+ YuvConversionError::D3D11Error("CreateTexture2D returned null".to_string())
+ })?
+ };
+
+ self.d3d11_staging_texture = Some(staging_texture);
+ self.d3d11_staging_width = width;
+ self.d3d11_staging_height = height;
+ }
+
+ let staging_texture = self.d3d11_staging_texture.as_ref().unwrap();
+
+ unsafe {
+ d3d11_context.CopyResource(staging_texture, nv12_texture);
+ }
+
+ let mut mapped = D3D11_MAPPED_SUBRESOURCE::default();
+ unsafe {
+ d3d11_context
+ .Map(staging_texture, 0, D3D11_MAP_READ, 0, Some(&mut mapped))
+ .map_err(|e| YuvConversionError::D3D11Error(format!("Map failed: {e:?}")))?;
+ }
+
+ let y_stride = mapped.RowPitch;
+ let uv_stride = mapped.RowPitch;
+
+ let y_size = (y_stride * height) as usize;
+ let uv_size = (uv_stride * height / 2) as usize;
+
+ let (y_data_vec, uv_data_vec) = unsafe {
+ let y_data = std::slice::from_raw_parts(mapped.pData as *const u8, y_size);
+ let uv_data =
+ std::slice::from_raw_parts((mapped.pData as *const u8).add(y_size), uv_size);
+ (y_data.to_vec(), uv_data.to_vec())
+ };
+
+ unsafe {
+ d3d11_context.Unmap(staging_texture, 0);
+ }
+
+ self.ensure_textures(wgpu_device, width, height, PixelFormat::Nv12);
+
+ let y_texture = self.y_texture.as_ref().unwrap();
+ let uv_texture = self.uv_texture.as_ref().unwrap();
+ let output_texture = self.output_texture.as_ref().unwrap();
+
+ upload_plane_with_stride(queue, y_texture, &y_data_vec, width, height, y_stride, "Y")?;
+
+ let half_height = height / 2;
+ queue.write_texture(
+ wgpu::TexelCopyTextureInfo {
+ texture: uv_texture,
+ mip_level: 0,
+ origin: wgpu::Origin3d::ZERO,
+ aspect: wgpu::TextureAspect::All,
+ },
+ &uv_data_vec,
+ wgpu::TexelCopyBufferLayout {
+ offset: 0,
+ bytes_per_row: Some(uv_stride),
+ rows_per_image: Some(half_height),
+ },
+ wgpu::Extent3d {
+ width: width / 2,
+ height: half_height,
+ depth_or_array_layers: 1,
+ },
+ );
+
+ let bind_group = wgpu_device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("NV12 D3D11 Converter Bind Group"),
+ layout: &self.nv12_bind_group_layout,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::TextureView(
+ &y_texture.create_view(&Default::default()),
+ ),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(
+ &uv_texture.create_view(&Default::default()),
+ ),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::TextureView(
+ &output_texture.create_view(&Default::default()),
+ ),
+ },
+ ],
+ });
+
+ let mut encoder = wgpu_device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("NV12 D3D11 Conversion Encoder"),
+ });
+
+ {
+ let mut compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
+ label: Some("NV12 D3D11 Conversion Pass"),
+ ..Default::default()
+ });
+ compute_pass.set_pipeline(&self.nv12_pipeline);
+ compute_pass.set_bind_group(0, &bind_group, &[]);
+ compute_pass.dispatch_workgroups(width.div_ceil(8), height.div_ceil(8), 1);
+ }
+
+ queue.submit(std::iter::once(encoder.finish()));
+
+ Ok(self.output_view.as_ref().unwrap())
+ }
+
+ #[cfg(target_os = "windows")]
+ pub fn convert_nv12_from_d3d11_shared_handles(
+ &mut self,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ y_handle: windows::Win32::Foundation::HANDLE,
+ uv_handle: windows::Win32::Foundation::HANDLE,
+ width: u32,
+ height: u32,
+ ) -> Result<&wgpu::TextureView, YuvConversionError> {
+ use crate::d3d_texture::import_d3d11_texture_to_wgpu;
+
+ let y_wgpu_texture = import_d3d11_texture_to_wgpu(
+ device,
+ y_handle,
+ wgpu::TextureFormat::R8Unorm,
+ width,
+ height,
+ Some("D3D11 Y Plane Zero-Copy"),
+ )?;
+
+ let uv_wgpu_texture = import_d3d11_texture_to_wgpu(
+ device,
+ uv_handle,
+ wgpu::TextureFormat::Rg8Unorm,
+ width / 2,
+ height / 2,
+ Some("D3D11 UV Plane Zero-Copy"),
+ )?;
+
+ if self.cached_width != width
+ || self.cached_height != height
+ || self.cached_format != Some(PixelFormat::Nv12)
+ {
+ self.output_texture = Some(device.create_texture(&wgpu::TextureDescriptor {
+ label: Some("RGBA Output Texture"),
+ size: wgpu::Extent3d {
+ width,
+ height,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::Rgba8Unorm,
+ usage: wgpu::TextureUsages::STORAGE_BINDING
+ | wgpu::TextureUsages::TEXTURE_BINDING
+ | wgpu::TextureUsages::COPY_SRC,
+ view_formats: &[],
+ }));
+
+ self.output_view = Some(
+ self.output_texture
+ .as_ref()
+ .unwrap()
+ .create_view(&Default::default()),
+ );
+
+ self.cached_width = width;
+ self.cached_height = height;
+ self.cached_format = Some(PixelFormat::Nv12);
+ }
+
+ let output_texture = self.output_texture.as_ref().unwrap();
+
+ let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("NV12 D3D11 Zero-Copy Converter Bind Group"),
+ layout: &self.nv12_bind_group_layout,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::TextureView(
+ &y_wgpu_texture.create_view(&Default::default()),
+ ),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(
+ &uv_wgpu_texture.create_view(&Default::default()),
+ ),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::TextureView(
+ &output_texture.create_view(&Default::default()),
+ ),
+ },
+ ],
+ });
+
+ let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("NV12 D3D11 Zero-Copy Conversion Encoder"),
+ });
+
+ {
+ let mut compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
+ label: Some("NV12 D3D11 Zero-Copy Conversion Pass"),
+ ..Default::default()
+ });
+ compute_pass.set_pipeline(&self.nv12_pipeline);
+ compute_pass.set_bind_group(0, &bind_group, &[]);
+ compute_pass.dispatch_workgroups(width.div_ceil(8), height.div_ceil(8), 1);
+ }
+
+ queue.submit(std::iter::once(encoder.finish()));
+
+ Ok(self.output_view.as_ref().unwrap())
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ pub fn convert_nv12_cpu(
+ &mut self,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ y_data: &[u8],
+ uv_data: &[u8],
+ width: u32,
+ height: u32,
+ y_stride: u32,
+ uv_stride: u32,
+ ) -> Result<&wgpu::TextureView, YuvConversionError> {
+ self.ensure_output_texture_only(device, width, height);
+
+ let mut rgba_data = vec![0u8; (width * height * 4) as usize];
+
+ cpu_yuv::nv12_to_rgba_simd(
+ y_data,
+ uv_data,
+ width,
+ height,
+ y_stride,
+ uv_stride,
+ &mut rgba_data,
+ );
+
+ let output_texture = self.output_texture.as_ref().unwrap();
+
+ queue.write_texture(
+ wgpu::TexelCopyTextureInfo {
+ texture: output_texture,
+ mip_level: 0,
+ origin: wgpu::Origin3d::ZERO,
+ aspect: wgpu::TextureAspect::All,
+ },
+ &rgba_data,
+ wgpu::TexelCopyBufferLayout {
+ offset: 0,
+ bytes_per_row: Some(width * 4),
+ rows_per_image: Some(height),
+ },
+ wgpu::Extent3d {
+ width,
+ height,
+ depth_or_array_layers: 1,
+ },
+ );
+
+ Ok(self.output_view.as_ref().unwrap())
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ pub fn convert_yuv420p_cpu(
+ &mut self,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ y_data: &[u8],
+ u_data: &[u8],
+ v_data: &[u8],
+ width: u32,
+ height: u32,
+ y_stride: u32,
+ uv_stride: u32,
+ ) -> Result<&wgpu::TextureView, YuvConversionError> {
+ self.ensure_output_texture_only(device, width, height);
+
+ let mut rgba_data = vec![0u8; (width * height * 4) as usize];
+
+ cpu_yuv::yuv420p_to_rgba_simd(
+ y_data,
+ u_data,
+ v_data,
+ width,
+ height,
+ y_stride,
+ uv_stride,
+ &mut rgba_data,
+ );
+
+ let output_texture = self.output_texture.as_ref().unwrap();
+
+ queue.write_texture(
+ wgpu::TexelCopyTextureInfo {
+ texture: output_texture,
+ mip_level: 0,
+ origin: wgpu::Origin3d::ZERO,
+ aspect: wgpu::TextureAspect::All,
+ },
+ &rgba_data,
+ wgpu::TexelCopyBufferLayout {
+ offset: 0,
+ bytes_per_row: Some(width * 4),
+ rows_per_image: Some(height),
+ },
+ wgpu::Extent3d {
+ width,
+ height,
+ depth_or_array_layers: 1,
+ },
+ );
+
+ Ok(self.output_view.as_ref().unwrap())
+ }
+
+ fn ensure_output_texture_only(&mut self, device: &wgpu::Device, width: u32, height: u32) {
+ if self.cached_width == width && self.cached_height == height {
+ return;
+ }
+
+ self.output_texture = Some(device.create_texture(&wgpu::TextureDescriptor {
+ label: Some("RGBA Output Texture (CPU)"),
+ size: wgpu::Extent3d {
+ width,
+ height,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::Rgba8Unorm,
+ usage: wgpu::TextureUsages::TEXTURE_BINDING
+ | wgpu::TextureUsages::COPY_DST
+ | wgpu::TextureUsages::COPY_SRC,
+ view_formats: &[],
+ }));
+
+ self.output_view = Some(
+ self.output_texture
+ .as_ref()
+ .unwrap()
+ .create_view(&Default::default()),
+ );
+
+ self.cached_width = width;
+ self.cached_height = height;
+ }
+
pub fn output_texture(&self) -> Option<&wgpu::Texture> {
self.output_texture.as_ref()
}
diff --git a/crates/video-decode/Cargo.toml b/crates/video-decode/Cargo.toml
index 09bb6c359..c4396ac6c 100644
--- a/crates/video-decode/Cargo.toml
+++ b/crates/video-decode/Cargo.toml
@@ -15,3 +15,19 @@ workspace-hack = { version = "0.1", path = "../workspace-hack" }
[target.'cfg(target_os = "macos")'.dependencies]
cidre = { workspace = true }
+
+[target.'cfg(target_os = "windows")'.dependencies]
+windows = { workspace = true, features = [
+ "Win32_Foundation",
+ "Win32_Graphics_Direct3D",
+ "Win32_Graphics_Direct3D11",
+ "Win32_Graphics_Dxgi",
+ "Win32_Graphics_Dxgi_Common",
+ "Win32_Media",
+ "Win32_Media_MediaFoundation",
+ "Win32_Security",
+ "Win32_System_Com",
+ "Win32_System_Com_StructuredStorage",
+ "Win32_System_Ole",
+ "Win32_System_Variant",
+] }
diff --git a/crates/video-decode/src/lib.rs b/crates/video-decode/src/lib.rs
index 65ea1d5a1..6cd4e8217 100644
--- a/crates/video-decode/src/lib.rs
+++ b/crates/video-decode/src/lib.rs
@@ -1,7 +1,11 @@
#[cfg(target_os = "macos")]
pub mod avassetreader;
pub mod ffmpeg;
+#[cfg(target_os = "windows")]
+pub mod media_foundation;
#[cfg(target_os = "macos")]
pub use avassetreader::AVAssetReaderDecoder;
pub use ffmpeg::FFmpegDecoder;
+#[cfg(target_os = "windows")]
+pub use media_foundation::{MFDecodedFrame, MediaFoundationDecoder, NV12Data};
diff --git a/crates/video-decode/src/media_foundation.rs b/crates/video-decode/src/media_foundation.rs
new file mode 100644
index 000000000..2217a65c0
--- /dev/null
+++ b/crates/video-decode/src/media_foundation.rs
@@ -0,0 +1,675 @@
+#![cfg(target_os = "windows")]
+
+use std::path::Path;
+use tracing::info;
+use windows::{
+ Win32::{
+ Foundation::{HANDLE, HMODULE},
+ Graphics::{
+ Direct3D::D3D_DRIVER_TYPE_HARDWARE,
+ Direct3D11::{
+ D3D11_BIND_SHADER_RESOURCE, D3D11_CPU_ACCESS_READ,
+ D3D11_CREATE_DEVICE_BGRA_SUPPORT, D3D11_CREATE_DEVICE_VIDEO_SUPPORT,
+ D3D11_MAP_READ, D3D11_MAPPED_SUBRESOURCE, D3D11_RESOURCE_MISC_SHARED_NTHANDLE,
+ D3D11_SDK_VERSION, D3D11_TEXTURE2D_DESC, D3D11_USAGE_DEFAULT, D3D11_USAGE_STAGING,
+ D3D11CreateDevice, ID3D11Device, ID3D11DeviceContext, ID3D11Texture2D,
+ },
+ Dxgi::{
+ Common::{DXGI_FORMAT_NV12, DXGI_SAMPLE_DESC},
+ DXGI_SHARED_RESOURCE_READ, IDXGIResource1,
+ },
+ },
+ Media::MediaFoundation::{
+ IMFAttributes, IMFDXGIBuffer, IMFDXGIDeviceManager, IMFSample, IMFSourceReader,
+ MF_API_VERSION, MF_MT_FRAME_RATE, MF_MT_FRAME_SIZE, MF_MT_MAJOR_TYPE, MF_MT_SUBTYPE,
+ MF_READWRITE_ENABLE_HARDWARE_TRANSFORMS, MF_SOURCE_READER_D3D_MANAGER,
+ MF_SOURCE_READER_ENABLE_ADVANCED_VIDEO_PROCESSING, MF_SOURCE_READER_FIRST_VIDEO_STREAM,
+ MFCreateAttributes, MFCreateDXGIDeviceManager, MFCreateMediaType,
+ MFCreateSourceReaderFromURL, MFMediaType_Video, MFSTARTUP_NOSOCKET, MFShutdown,
+ MFStartup, MFVideoFormat_NV12,
+ },
+ System::Com::{COINIT_MULTITHREADED, CoInitializeEx, CoUninitialize},
+ },
+ core::{Interface, PCWSTR},
+};
+
+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 width: u32,
+ pub height: u32,
+ pub pts: i64,
+}
+
+pub struct NV12Data {
+ pub data: Vec<u8>,
+ pub y_stride: u32,
+ pub uv_stride: u32,
+}
+
+pub struct MediaFoundationDecoder {
+ source_reader: IMFSourceReader,
+ d3d11_device: ID3D11Device,
+ d3d11_context: ID3D11DeviceContext,
+ _device_manager: IMFDXGIDeviceManager,
+ width: u32,
+ height: u32,
+ frame_rate_num: u32,
+ frame_rate_den: u32,
+ staging_texture: Option<ID3D11Texture2D>,
+ staging_width: u32,
+ staging_height: u32,
+}
+
+impl MediaFoundationDecoder {
+ pub fn new(path: impl AsRef<Path>) -> Result<Self, String> {
+ unsafe { Self::new_inner(path.as_ref()) }
+ }
+
+ unsafe fn new_inner(path: &Path) -> Result<Self, String> {
+ unsafe {
+ CoInitializeEx(None, COINIT_MULTITHREADED)
+ .ok()
+ .map_err(|e| format!("Failed to initialize COM: {e:?}"))?;
+
+ MFStartup(MF_API_VERSION, MFSTARTUP_NOSOCKET)
+ .map_err(|e| format!("Failed to start Media Foundation: {e:?}"))?;
+ }
+
+ let (d3d11_device, d3d11_context) = unsafe { create_d3d11_device()? };
+ let device_manager = unsafe { create_dxgi_device_manager(&d3d11_device)? };
+
+ let source_reader = unsafe { create_source_reader(path, &device_manager)? };
+
+ unsafe { configure_output_type(&source_reader)? };
+
+ let (width, height, frame_rate_num, frame_rate_den) =
+ unsafe { get_video_info(&source_reader)? };
+
+ info!(
+ "MediaFoundation decoder initialized: {}x{} @ {}/{}fps",
+ width, height, frame_rate_num, frame_rate_den
+ );
+
+ Ok(Self {
+ source_reader,
+ d3d11_device,
+ d3d11_context,
+ _device_manager: device_manager,
+ width,
+ height,
+ frame_rate_num,
+ frame_rate_den,
+ staging_texture: None,
+ staging_width: 0,
+ staging_height: 0,
+ })
+ }
+
+ pub fn width(&self) -> u32 {
+ self.width
+ }
+
+ pub fn height(&self) -> u32 {
+ self.height
+ }
+
+ pub fn frame_rate(&self) -> (u32, u32) {
+ (self.frame_rate_num, self.frame_rate_den)
+ }
+
+ pub fn d3d11_device(&self) -> &ID3D11Device {
+ &self.d3d11_device
+ }
+
+ pub fn read_texture_to_cpu(
+ &mut self,
+ texture: &ID3D11Texture2D,
+ width: u32,
+ height: u32,
+ ) -> Result<NV12Data, String> {
+ unsafe { self.read_texture_to_cpu_inner(texture, width, height) }
+ }
+
+ unsafe fn read_texture_to_cpu_inner(
+ &mut self,
+ texture: &ID3D11Texture2D,
+ width: u32,
+ height: u32,
+ ) -> Result<NV12Data, String> {
+ if self.staging_width != width
+ || self.staging_height != height
+ || self.staging_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_STAGING,
+ BindFlags: 0,
+ CPUAccessFlags: D3D11_CPU_ACCESS_READ.0 as u32,
+ MiscFlags: 0,
+ };
+
+ let staging_texture = unsafe {
+ let mut tex: Option<ID3D11Texture2D> = None;
+ self.d3d11_device
+ .CreateTexture2D(&desc, None, Some(&mut tex))
+ .map_err(|e| format!("CreateTexture2D staging failed: {e:?}"))?;
+ tex.ok_or("CreateTexture2D staging returned null")?
+ };
+
+ self.staging_texture = Some(staging_texture);
+ self.staging_width = width;
+ self.staging_height = height;
+ }
+
+ let staging = self.staging_texture.as_ref().unwrap();
+
+ unsafe {
+ self.d3d11_context.CopyResource(staging, texture);
+ }
+
+ let mut mapped = D3D11_MAPPED_SUBRESOURCE::default();
+ unsafe {
+ self.d3d11_context
+ .Map(staging, 0, D3D11_MAP_READ, 0, Some(&mut mapped))
+ .map_err(|e| format!("Map staging texture failed: {e:?}"))?;
+ }
+
+ let y_stride = mapped.RowPitch;
+ let y_height = height;
+ let uv_height = height / 2;
+
+ let y_size = (y_stride * y_height) as usize;
+ let uv_size = (y_stride * uv_height) as usize;
+ let total_size = y_size + uv_size;
+
+ let mut data = vec![0u8; total_size];
+ unsafe {
+ std::ptr::copy_nonoverlapping(mapped.pData as *const u8, data.as_mut_ptr(), total_size);
+ self.d3d11_context.Unmap(staging, 0);
+ }
+
+ Ok(NV12Data {
+ data,
+ y_stride,
+ uv_stride: y_stride,
+ })
+ }
+
+ pub fn read_sample(&mut self) -> Result<Option<MFDecodedFrame>, String> {
+ unsafe { self.read_sample_inner() }
+ }
+
+ unsafe fn read_sample_inner(&mut self) -> Result<Option<MFDecodedFrame>, String> {
+ let mut stream_index = 0u32;
+ let mut flags = 0u32;
+ let mut timestamp = 0i64;
+ let mut sample: Option<IMFSample> = None;
+
+ unsafe {
+ self.source_reader
+ .ReadSample(
+ MF_SOURCE_READER_FIRST_VIDEO_STREAM.0 as u32,
+ 0,
+ Some(&mut stream_index),
+ Some(&mut flags),
+ Some(&mut timestamp),
+ Some(&mut sample),
+ )
+ .map_err(|e| format!("ReadSample failed: {e:?}"))?;
+ }
+
+ const MF_SOURCE_READERF_ENDOFSTREAM: u32 = 0x00000001;
+ const MF_SOURCE_READERF_ERROR: u32 = 0x00000002;
+
+ if flags & MF_SOURCE_READERF_ENDOFSTREAM != 0 {
+ return Ok(None);
+ }
+
+ if flags & MF_SOURCE_READERF_ERROR != 0 {
+ return Err("Stream error".to_string());
+ }
+
+ let Some(sample) = sample else {
+ return Ok(None);
+ };
+
+ let buffer = unsafe {
+ sample
+ .GetBufferByIndex(0)
+ .map_err(|e| format!("GetBufferByIndex failed: {e:?}"))?
+ };
+
+ let dxgi_buffer: IMFDXGIBuffer = buffer
+ .cast()
+ .map_err(|e| format!("Failed to cast to IMFDXGIBuffer: {e:?}"))?;
+
+ let texture = unsafe {
+ let mut texture: Option<ID3D11Texture2D> = None;
+ dxgi_buffer
+ .GetResource(&ID3D11Texture2D::IID, &mut texture as *mut _ as *mut _)
+ .map_err(|e| format!("GetResource failed: {e:?}"))?;
+ texture.ok_or("GetResource returned null texture")?
+ };
+
+ let subresource_index = unsafe {
+ dxgi_buffer
+ .GetSubresourceIndex()
+ .map_err(|e| format!("GetSubresourceIndex failed: {e:?}"))?
+ };
+
+ let (output_texture, shared_handle) = unsafe {
+ copy_texture_subresource(
+ &self.d3d11_device,
+ &self.d3d11_context,
+ &texture,
+ subresource_index,
+ self.width,
+ self.height,
+ )?
+ };
+
+ let yuv_planes = unsafe {
+ create_yuv_plane_textures(
+ &self.d3d11_device,
+ &self.d3d11_context,
+ &output_texture,
+ self.width,
+ self.height,
+ )
+ .ok()
+ };
+
+ let (y_texture, y_handle, uv_texture, uv_handle) = yuv_planes
+ .map(|p| {
+ (
+ Some(p.y_texture),
+ p.y_handle,
+ Some(p.uv_texture),
+ p.uv_handle,
+ )
+ })
+ .unwrap_or((None, None, None, None));
+
+ Ok(Some(MFDecodedFrame {
+ texture: output_texture,
+ shared_handle,
+ y_texture,
+ y_handle,
+ uv_texture,
+ uv_handle,
+ width: self.width,
+ height: self.height,
+ pts: timestamp,
+ }))
+ }
+
+ pub fn seek(&mut self, time_100ns: i64) -> Result<(), String> {
+ use std::mem::MaybeUninit;
+ use windows::Win32::System::Com::StructuredStorage::PROPVARIANT;
+
+ let mut prop = MaybeUninit::<PROPVARIANT>::zeroed();
+ unsafe {
+ let prop_ptr = prop.as_mut_ptr();
+ let inner_ptr = std::ptr::addr_of_mut!((*prop_ptr).Anonymous.Anonymous);
+ std::ptr::addr_of_mut!((*inner_ptr).vt).write(windows::Win32::System::Variant::VT_I8);
+ std::ptr::addr_of_mut!((*inner_ptr).Anonymous.hVal).write(time_100ns);
+
+ let prop = prop.assume_init();
+ self.source_reader
+ .SetCurrentPosition(&windows::core::GUID::zeroed(), &prop)
+ .map_err(|e| format!("Seek failed: {e:?}"))?;
+ }
+
+ Ok(())
+ }
+}
+
+impl Drop for MediaFoundationDecoder {
+ fn drop(&mut self) {
+ unsafe {
+ let _ = MFShutdown();
+ CoUninitialize();
+ }
+ }
+}
+
+unsafe fn create_d3d11_device() -> Result<(ID3D11Device, ID3D11DeviceContext), String> {
+ let flags = D3D11_CREATE_DEVICE_VIDEO_SUPPORT | D3D11_CREATE_DEVICE_BGRA_SUPPORT;
+
+ let feature_levels = [
+ windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_1,
+ windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0,
+ windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_10_1,
+ windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_10_0,
+ ];
+
+ let mut device: Option<ID3D11Device> = None;
+ let mut context: Option<ID3D11DeviceContext> = None;
+
+ unsafe {
+ D3D11CreateDevice(
+ None,
+ D3D_DRIVER_TYPE_HARDWARE,
+ HMODULE::default(),
+ flags,
+ Some(&feature_levels),
+ D3D11_SDK_VERSION,
+ Some(&mut device),
+ None,
+ Some(&mut context),
+ )
+ .map_err(|e| format!("D3D11CreateDevice failed: {e:?}"))?;
+ }
+
+ let device = device.ok_or("D3D11CreateDevice returned null device")?;
+ let context = context.ok_or("D3D11CreateDevice returned null context")?;
+
+ let multithread: windows::Win32::Graphics::Direct3D11::ID3D11Multithread = device
+ .cast()
+ .map_err(|e| format!("Failed to get ID3D11Multithread: {e:?}"))?;
+ unsafe {
+ let _ = multithread.SetMultithreadProtected(true);
+ }
+
+ Ok((device, context))
+}
+
+unsafe fn create_dxgi_device_manager(
+ device: &ID3D11Device,
+) -> Result<IMFDXGIDeviceManager, String> {
+ let mut reset_token = 0u32;
+ let mut manager: Option<IMFDXGIDeviceManager> = None;
+
+ unsafe {
+ MFCreateDXGIDeviceManager(&mut reset_token, &mut manager)
+ .map_err(|e| format!("MFCreateDXGIDeviceManager failed: {e:?}"))?;
+ }
+
+ let manager = manager.ok_or("MFCreateDXGIDeviceManager returned null")?;
+
+ unsafe {
+ manager
+ .ResetDevice(device, reset_token)
+ .map_err(|e| format!("ResetDevice failed: {e:?}"))?;
+ }
+
+ Ok(manager)
+}
+
+unsafe fn create_source_reader(
+ path: &Path,
+ device_manager: &IMFDXGIDeviceManager,
+) -> Result<IMFSourceReader, String> {
+ let mut attributes: Option<IMFAttributes> = None;
+ unsafe {
+ MFCreateAttributes(&mut attributes, 4)
+ .map_err(|e| format!("MFCreateAttributes failed: {e:?}"))?;
+ }
+
+ let attributes = attributes.ok_or("MFCreateAttributes returned null")?;
+
+ unsafe {
+ attributes
+ .SetUnknown(&MF_SOURCE_READER_D3D_MANAGER, device_manager)
+ .map_err(|e| format!("SetUnknown D3D_MANAGER failed: {e:?}"))?;
+
+ attributes
+ .SetUINT32(&MF_READWRITE_ENABLE_HARDWARE_TRANSFORMS, 1)
+ .map_err(|e| format!("SetUINT32 ENABLE_HARDWARE_TRANSFORMS failed: {e:?}"))?;
+
+ attributes
+ .SetUINT32(&MF_SOURCE_READER_ENABLE_ADVANCED_VIDEO_PROCESSING, 1)
+ .map_err(|e| format!("SetUINT32 ENABLE_ADVANCED_VIDEO_PROCESSING failed: {e:?}"))?;
+ }
+
+ let path_wide: Vec<u16> = path
+ .to_string_lossy()
+ .encode_utf16()
+ .chain(std::iter::once(0))
+ .collect();
+
+ let source_reader = unsafe {
+ MFCreateSourceReaderFromURL(PCWSTR(path_wide.as_ptr()), &attributes)
+ .map_err(|e| format!("MFCreateSourceReaderFromURL failed: {e:?}"))?
+ };
+
+ Ok(source_reader)
+}
+
+unsafe fn configure_output_type(source_reader: &IMFSourceReader) -> Result<(), String> {
+ let media_type =
+ unsafe { MFCreateMediaType().map_err(|e| format!("MFCreateMediaType failed: {e:?}"))? };
+
+ unsafe {
+ media_type
+ .SetGUID(&MF_MT_MAJOR_TYPE, &MFMediaType_Video)
+ .map_err(|e| format!("SetGUID MAJOR_TYPE failed: {e:?}"))?;
+
+ media_type
+ .SetGUID(&MF_MT_SUBTYPE, &MFVideoFormat_NV12)
+ .map_err(|e| format!("SetGUID SUBTYPE failed: {e:?}"))?;
+
+ source_reader
+ .SetCurrentMediaType(
+ MF_SOURCE_READER_FIRST_VIDEO_STREAM.0 as u32,
+ None,
+ &media_type,
+ )
+ .map_err(|e| format!("SetCurrentMediaType failed: {e:?}"))?;
+ }
+
+ Ok(())
+}
+
+unsafe fn get_video_info(source_reader: &IMFSourceReader) -> Result<(u32, u32, u32, u32), String> {
+ let media_type = unsafe {
+ source_reader
+ .GetCurrentMediaType(MF_SOURCE_READER_FIRST_VIDEO_STREAM.0 as u32)
+ .map_err(|e| format!("GetCurrentMediaType failed: {e:?}"))?
+ };
+
+ let frame_size = unsafe {
+ media_type
+ .GetUINT64(&MF_MT_FRAME_SIZE)
+ .map_err(|e| format!("GetUINT64 FRAME_SIZE failed: {e:?}"))?
+ };
+
+ let width = (frame_size >> 32) as u32;
+ let height = frame_size as u32;
+
+ let frame_rate = unsafe {
+ media_type
+ .GetUINT64(&MF_MT_FRAME_RATE)
+ .unwrap_or((30 << 32) | 1)
+ };
+
+ let frame_rate_num = (frame_rate >> 32) as u32;
+ let frame_rate_den = frame_rate as u32;
+
+ Ok((width, height, frame_rate_num, frame_rate_den.max(1)))
+}
+
+unsafe fn get_shared_handle(texture: &ID3D11Texture2D) -> Result<HANDLE, String> {
+ use windows::Win32::Security::SECURITY_ATTRIBUTES;
+
+ let dxgi_resource: IDXGIResource1 = texture
+ .cast()
+ .map_err(|e| format!("Failed to cast to IDXGIResource1: {e:?}"))?;
+
+ let handle = unsafe {
+ dxgi_resource
+ .CreateSharedHandle(
+ None::<*const SECURITY_ATTRIBUTES>,
+ DXGI_SHARED_RESOURCE_READ.0,
+ PCWSTR::null(),
+ )
+ .map_err(|e| format!("CreateSharedHandle failed: {e:?}"))?
+ };
+
+ Ok(handle)
+}
+
+struct YuvPlaneTextures {
+ y_texture: ID3D11Texture2D,
+ y_handle: Option<HANDLE>,
+ uv_texture: ID3D11Texture2D,
+ uv_handle: Option<HANDLE>,
+}
+
+unsafe fn create_yuv_plane_textures(
+ device: &ID3D11Device,
+ context: &ID3D11DeviceContext,
+ nv12_texture: &ID3D11Texture2D,
+ width: u32,
+ height: u32,
+) -> Result<YuvPlaneTextures, String> {
+ use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8_UNORM, DXGI_FORMAT_R8G8_UNORM};
+
+ 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,
+ },
+ Usage: D3D11_USAGE_DEFAULT,
+ BindFlags: D3D11_BIND_SHADER_RESOURCE.0 as u32,
+ CPUAccessFlags: 0,
+ MiscFlags: 0,
+ };
+
+ let mut y_texture: Option<ID3D11Texture2D> = None;
+ unsafe {
+ device
+ .CreateTexture2D(&y_desc, None, Some(&mut y_texture))
+ .map_err(|e| format!("CreateTexture2D Y failed: {e:?}"))?;
+ }
+ let y_texture = y_texture.ok_or("CreateTexture2D Y 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 mut uv_texture: Option<ID3D11Texture2D> = None;
+ unsafe {
+ device
+ .CreateTexture2D(&uv_desc, None, Some(&mut uv_texture))
+ .map_err(|e| format!("CreateTexture2D UV failed: {e:?}"))?;
+ }
+ let uv_texture = uv_texture.ok_or("CreateTexture2D UV returned null")?;
+
+ unsafe {
+ context.CopySubresourceRegion(
+ &y_texture,
+ 0,
+ 0,
+ 0,
+ 0,
+ nv12_texture,
+ 0,
+ Some(&windows::Win32::Graphics::Direct3D11::D3D11_BOX {
+ left: 0,
+ top: 0,
+ front: 0,
+ right: width,
+ bottom: height,
+ back: 1,
+ }),
+ );
+
+ context.CopySubresourceRegion(
+ &uv_texture,
+ 0,
+ 0,
+ 0,
+ 0,
+ nv12_texture,
+ 1,
+ Some(&windows::Win32::Graphics::Direct3D11::D3D11_BOX {
+ left: 0,
+ top: 0,
+ front: 0,
+ right: width / 2,
+ bottom: height / 2,
+ back: 1,
+ }),
+ );
+ }
+
+ Ok(YuvPlaneTextures {
+ y_texture,
+ y_handle: None,
+ uv_texture,
+ uv_handle: None,
+ })
+}
+
+unsafe fn copy_texture_subresource(
+ device: &ID3D11Device,
+ context: &ID3D11DeviceContext,
+ source: &ID3D11Texture2D,
+ subresource_index: u32,
+ width: u32,
+ height: u32,
+) -> Result<(ID3D11Texture2D, Option<HANDLE>), 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 mut output_texture: Option<ID3D11Texture2D> = None;
+ unsafe {
+ device
+ .CreateTexture2D(&desc, None, Some(&mut output_texture))
+ .map_err(|e| format!("CreateTexture2D failed: {e:?}"))?;
+ }
+
+ let output_texture = output_texture.ok_or("CreateTexture2D returned null")?;
+
+ unsafe {
+ context.CopySubresourceRegion(&output_texture, 0, 0, 0, 0, source, subresource_index, None);
+ }
+
+ Ok((output_texture, None))
+}
+
+unsafe impl Send for MediaFoundationDecoder {}