From bbd0689bb9fde0f993736efe3e414149242e7b0d Mon Sep 17 00:00:00 2001 From: Kyzer <36684609+kyzer1023@users.noreply.github.com> Date: Sun, 25 Oct 2026 03:33:20 +0800 Subject: [PATCH 01/10] Reuse camera upload texture and media buffers on Windows --- crates/recording/src/feeds/camera.rs | 68 ++++++---- crates/recording/src/output_pipeline/win.rs | 132 +++++++++++++++----- 2 files changed, 147 insertions(+), 53 deletions(-) diff --git a/crates/recording/src/feeds/camera.rs b/crates/recording/src/feeds/camera.rs index e70151f06b8..d8c04725ad0 100644 --- a/crates/recording/src/feeds/camera.rs +++ b/crates/recording/src/feeds/camera.rs @@ -1159,6 +1159,7 @@ async fn setup_camera( let (ready_tx, ready_rx) = oneshot::channel(); let mut ready_signal = Some(ready_tx); + let mut native_buffers: Vec<(NativeCameraFrame, usize)> = Vec::new(); let capture_handle = camera .start_capturing(format.clone(), move |frame| { let callback_num = @@ -1178,33 +1179,56 @@ async fn setup_camera( use windows::Win32::Media::MediaFoundation::MFCreateMemoryBuffer; let data_len = bytes.len(); - if let Ok(buffer) = unsafe { MFCreateMemoryBuffer(data_len as u32) } { - let buffer_ready = { - if let Ok(mut lock) = buffer.lock_for_write() { - lock.copy_from_slice(&bytes); + let reusable = native_buffers + .iter() + .find(|(frame, capacity)| { + *capacity >= data_len + && Arc::strong_count(&frame.buffer) == 1 + && !frame.buffer.is_poisoned() + }) + .map(|(frame, _)| frame.buffer.clone()); + let buffer = match reusable { + Some(buffer) => Ok(buffer), + None => unsafe { MFCreateMemoryBuffer(data_len as u32) } + .map(std::sync::Mutex::new) + .map(Arc::from), + }; + if let Ok(buffer) = buffer { + let buffer_ready = buffer.lock().is_ok_and(|guard| { + let copied = if let Ok(mut lock) = guard.lock_for_write() { + lock[..data_len].copy_from_slice(&bytes); true } else { false - } - }; + }; + copied && unsafe { guard.SetCurrentLength(data_len as u32) }.is_ok() + }); if buffer_ready { - let _ = unsafe { buffer.SetCurrentLength(data_len as u32) }; - - #[allow(clippy::arc_with_non_send_sync)] - let buffer = std::sync::Arc::new(std::sync::Mutex::new(buffer)); - hand_native_frame_to_feed( - &native_recipient, - &native_ingress, - NativeCameraFrame { - buffer, - pixel_format: frame.native().pixel_format, - width: frame.native().width as u32, - height: frame.native().height as u32, - is_bottom_up: frame.native().is_bottom_up, - timestamp, - }, - ); + let native_frame = NativeCameraFrame { + buffer, + pixel_format: frame.native().pixel_format, + width: frame.native().width as u32, + height: frame.native().height as u32, + is_bottom_up: frame.native().is_bottom_up, + timestamp, + }; + if !native_buffers + .iter() + .any(|(frame, _)| Arc::ptr_eq(&frame.buffer, &native_frame.buffer)) + { + if let Some(slot) = native_buffers + .iter_mut() + .find(|(frame, _)| Arc::strong_count(&frame.buffer) == 1) + { + *slot = (native_frame.clone(), data_len); + } else if native_buffers.len() < 3 { + native_buffers.push((native_frame.clone(), data_len)); + } + } + hand_native_frame_to_feed(&native_recipient, &native_ingress, native_frame); + } else { + native_buffers.retain(|(frame, _)| !Arc::ptr_eq(&frame.buffer, &buffer)); } } } diff --git a/crates/recording/src/output_pipeline/win.rs b/crates/recording/src/output_pipeline/win.rs index faab33d6e76..a8cc7ef122c 100644 --- a/crates/recording/src/output_pipeline/win.rs +++ b/crates/recording/src/output_pipeline/win.rs @@ -1098,6 +1098,15 @@ impl AudioMuxer for WindowsCameraMuxer { pub struct CameraBuffers { uyvy_buffer: Vec, flip_buffer: Vec, + texture: Option, +} + +struct CameraUploadTexture { + key: (u32, u32, DXGI_FORMAT), + device: ID3D11Device, + context: windows::Win32::Graphics::Direct3D11::ID3D11DeviceContext, + texture: windows::Win32::Graphics::Direct3D11::ID3D11Texture2D, + dynamic: bool, } impl CameraBuffers { @@ -1105,6 +1114,7 @@ impl CameraBuffers { Self { uyvy_buffer: Vec::new(), flip_buffer: Vec::new(), + texture: None, } } @@ -1810,8 +1820,8 @@ pub fn upload_mf_buffer_to_texture( ) -> windows::core::Result { use cap_mediafoundation_utils::IMFMediaBufferExt; use windows::Win32::Graphics::Direct3D11::{ - D3D11_BIND_SHADER_RESOURCE, D3D11_SUBRESOURCE_DATA, D3D11_TEXTURE2D_DESC, - D3D11_USAGE_DEFAULT, + D3D11_BIND_SHADER_RESOURCE, D3D11_CPU_ACCESS_WRITE, D3D11_MAP_WRITE_DISCARD, + D3D11_MAPPED_SUBRESOURCE, D3D11_TEXTURE2D_DESC, D3D11_USAGE_DEFAULT, D3D11_USAGE_DYNAMIC, }; use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; @@ -1842,6 +1852,56 @@ pub fn upload_mf_buffer_to_texture( ) })?; + let key = (frame.width, frame.height, dxgi_format); + if buffers + .texture + .as_ref() + .is_none_or(|cached| cached.key != key || cached.device != *device) + { + let mut desc = D3D11_TEXTURE2D_DESC { + Width: frame.width, + Height: frame.height, + MipLevels: 1, + ArraySize: 1, + Format: dxgi_format, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Usage: D3D11_USAGE_DYNAMIC, + BindFlags: D3D11_BIND_SHADER_RESOURCE.0 as u32, + CPUAccessFlags: D3D11_CPU_ACCESS_WRITE.0 as u32, + MiscFlags: 0, + }; + let mut texture = None; + let dynamic = unsafe { + device + .CreateTexture2D(&desc, None, Some(&mut texture)) + .is_ok() + }; + if !dynamic { + desc.Usage = D3D11_USAGE_DEFAULT; + desc.CPUAccessFlags = 0; + unsafe { device.CreateTexture2D(&desc, None, Some(&mut texture))? }; + } + buffers.texture = Some(CameraUploadTexture { + key, + device: device.clone(), + context: unsafe { device.GetImmediateContext()? }, + texture: texture.ok_or_else(|| { + windows::core::Error::new( + windows::core::HRESULT(-1), + "CreateTexture2D succeeded but returned no texture", + ) + })?, + dynamic, + }); + } + let cached = buffers.texture.as_ref().unwrap(); + let texture = cached.texture.clone(); + let context = cached.context.clone(); + let dynamic = cached.dynamic; + let needs_uyvy_conversion = frame.pixel_format == cap_camera_windows::PixelFormat::UYVY422; let needs_flip = frame.is_bottom_up; let mut row_pitch = layout.primary_stride as u32; @@ -1926,36 +1986,46 @@ pub fn upload_mf_buffer_to_texture( } }; - let texture_desc = D3D11_TEXTURE2D_DESC { - Width: frame.width, - Height: frame.height, - MipLevels: 1, - ArraySize: 1, - Format: dxgi_format, - 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 subresource_data = D3D11_SUBRESOURCE_DATA { - pSysMem: data.as_ptr() as *const _, - SysMemPitch: row_pitch, - SysMemSlicePitch: 0, + let (row_bytes, rows) = match dxgi_format { + DXGI_FORMAT_NV12 => ( + frame.width as usize, + frame.height as usize + frame.height as usize / 2, + ), + DXGI_FORMAT_YUY2 => (frame.width as usize * 2, frame.height as usize), + _ => (frame.width as usize * 4, frame.height as usize), }; - + if (row_pitch as usize) < row_bytes || data.len() < (rows - 1) * row_pitch as usize + row_bytes + { + return Err(windows::core::Error::new( + windows::Win32::Foundation::E_INVALIDARG, + "Camera buffer is too small for the upload texture", + )); + } unsafe { - let mut texture = None; - device.CreateTexture2D(&texture_desc, Some(&subresource_data), Some(&mut texture))?; - texture.ok_or_else(|| { - windows::core::Error::new( - windows::core::HRESULT(-1), - "CreateTexture2D succeeded but returned no texture", - ) - }) + if dynamic { + let mut mapped = D3D11_MAPPED_SUBRESOURCE::default(); + context.Map(&texture, 0, D3D11_MAP_WRITE_DISCARD, 0, Some(&mut mapped))?; + if (mapped.RowPitch as usize) < row_bytes { + context.Unmap(&texture, 0); + return Err(windows::core::Error::new( + windows::Win32::Foundation::E_INVALIDARG, + "Mapped camera texture row pitch is too small", + )); + } + for row in 0..rows { + std::ptr::copy_nonoverlapping( + data.as_ptr().add(row * row_pitch as usize), + mapped + .pData + .cast::() + .add(row * mapped.RowPitch as usize), + row_bytes, + ); + } + context.Unmap(&texture, 0); + } else { + context.UpdateSubresource(&texture, 0, None, data.as_ptr().cast(), row_pitch, 0); + } } + Ok(texture) } From 81272ff61632b48f4d92606ba45ac63501af7e82 Mon Sep 17 00:00:00 2001 From: Kyzer <36684609+kyzer1023@users.noreply.github.com> Date: Sun, 25 Oct 2026 03:47:55 +0800 Subject: [PATCH 02/10] Add Windows camera upload benchmark example --- .../windows-camera-upload-benchmark.rs | 613 ++++++++++++++++++ 1 file changed, 613 insertions(+) create mode 100644 crates/recording/examples/windows-camera-upload-benchmark.rs diff --git a/crates/recording/examples/windows-camera-upload-benchmark.rs b/crates/recording/examples/windows-camera-upload-benchmark.rs new file mode 100644 index 00000000000..f689266cc2b --- /dev/null +++ b/crates/recording/examples/windows-camera-upload-benchmark.rs @@ -0,0 +1,613 @@ +//! Measures the Windows native camera upload path: the per-frame media buffer +//! copy plus `upload_mf_buffer_to_texture`. `before` replays frames through an +//! inline copy of the previous path (new `MFCreateMemoryBuffer` and new +//! `CreateTexture2D` per frame), `after` through the pooled buffers and the +//! library upload. +//! +//! cargo build --release -p cap-recording --example windows-camera-upload-benchmark +//! windows-camera-upload-benchmark capture frames.bin [camera name] +//! windows-camera-upload-benchmark both frames.bin +//! windows-camera-upload-benchmark before frames.bin +//! windows-camera-upload-benchmark after frames.bin +//! windows-camera-upload-benchmark validate + +#[cfg(not(target_os = "windows"))] +fn main() { + eprintln!("windows-camera-upload-benchmark: skipped (not Windows)"); +} + +#[cfg(target_os = "windows")] +fn main() -> anyhow::Result<()> { + windows_bench::run() +} + +#[cfg(target_os = "windows")] +mod windows_bench { + use anyhow::{Context, bail}; + use cap_camera_windows::PixelFormat; + use cap_mediafoundation_utils::IMFMediaBufferExt; + use cap_recording::{CameraBuffers, NativeCameraFrame, upload_mf_buffer_to_texture}; + use std::{ + fs::File, + io::{BufReader, BufWriter, Read, Write}, + sync::{Arc, Mutex, mpsc}, + time::{Duration, Instant}, + }; + use windows::Win32::{ + Foundation::{FILETIME, HMODULE}, + Graphics::{ + Direct3D::D3D_DRIVER_TYPE_HARDWARE, + Direct3D11::*, + Dxgi::{Common::*, IDXGIDevice}, + }, + Media::MediaFoundation::{IMFMediaBuffer, MFCreateMemoryBuffer}, + System::Threading::{GetCurrentProcess, GetProcessTimes}, + }; + use windows::core::Interface; + + const FRAME_COUNT: usize = 300; + const WARMUP_FRAMES: usize = 30; + const REPEATS: usize = 5; + const POOL_SIZE: usize = 3; + + struct RawFrame { + bytes: Vec, + width: u32, + height: u32, + pixel_format: PixelFormat, + bottom_up: bool, + counter: i64, + } + + #[derive(Clone, Copy, PartialEq)] + enum Side { + Before, + After, + } + + struct Stats { + median: f64, + p95: f64, + mean: f64, + cpu: f64, + } + + struct Gpu { + device: ID3D11Device, + context: ID3D11DeviceContext, + query: ID3D11Query, + } + + impl Gpu { + fn new() -> anyhow::Result { + let mut device = None; + unsafe { + D3D11CreateDevice( + None, + D3D_DRIVER_TYPE_HARDWARE, + HMODULE::default(), + D3D11_CREATE_DEVICE_BGRA_SUPPORT, + None, + D3D11_SDK_VERSION, + Some(&mut device), + None, + None, + )?; + } + let device = device.context("No hardware D3D11 device")?; + let adapter = unsafe { device.cast::()?.GetAdapter()?.GetDesc()? }; + println!( + "GPU: {}", + String::from_utf16_lossy(&adapter.Description).trim_end_matches('\0') + ); + let context = unsafe { device.GetImmediateContext()? }; + let mut query = None; + unsafe { + device.CreateQuery( + &D3D11_QUERY_DESC { + Query: D3D11_QUERY_EVENT, + MiscFlags: 0, + }, + Some(&mut query), + )?; + } + Ok(Self { + device, + context, + query: query.context("No event query")?, + }) + } + + fn flush(&self) { + unsafe { self.context.Flush() }; + } + + fn wait(&self) -> anyhow::Result<()> { + unsafe { + self.context.End(&self.query); + self.context.Flush(); + } + let start = Instant::now(); + loop { + let mut done = 0u32; + unsafe { + self.context.GetData( + &self.query, + Some((&mut done as *mut u32).cast()), + 4, + D3D11_ASYNC_GETDATA_DONOTFLUSH.0 as u32, + )?; + } + if done != 0 { + return Ok(()); + } + if start.elapsed() > Duration::from_secs(10) { + bail!("GPU completion timeout"); + } + std::hint::spin_loop(); + } + } + } + + fn format_code(format: PixelFormat) -> anyhow::Result { + Ok(match format { + PixelFormat::YUYV422 => 0, + PixelFormat::UYVY422 => 1, + PixelFormat::NV12 => 2, + PixelFormat::RGB32 => 3, + PixelFormat::ARGB => 4, + _ => bail!("Unsupported capture format {format:?}"), + }) + } + + fn format_from_code(code: u32) -> anyhow::Result { + Ok(match code { + 0 => PixelFormat::YUYV422, + 1 => PixelFormat::UYVY422, + 2 => PixelFormat::NV12, + 3 => PixelFormat::RGB32, + 4 => PixelFormat::ARGB, + _ => bail!("Invalid saved format {code}"), + }) + } + + fn capture(path: &str, name: Option<&str>) -> anyhow::Result<()> { + let camera = cap_camera::list_cameras() + .find(|camera| name.is_none_or(|name| camera.display_name().contains(name))) + .context("Camera not found")?; + println!("Camera: {} {:?}", camera.display_name(), camera.model_id()); + let mut formats = camera.formats().context("No camera formats")?; + formats.retain(|format| { + matches!( + format.pixel_format_name().as_deref(), + Some("YUYV422" | "UYVY422" | "NV12" | "RGB32" | "ARGB") + ) + }); + formats.sort_by_key(|format| { + ( + format.width().abs_diff(1920) + format.height().abs_diff(1080), + ((format.frame_rate() - 30.0).abs() * 100.0) as u32, + format.pixel_format_name().as_deref() != Some("YUYV422"), + ) + }); + let format = formats + .into_iter() + .next() + .context("No uncompressed camera format")?; + println!( + "Mode: {}x{} @ {} fps {:?}", + format.width(), + format.height(), + format.frame_rate(), + format.pixel_format_name() + ); + + let (tx, rx) = mpsc::sync_channel(FRAME_COUNT); + let handle = camera.start_capturing(format, move |frame| { + let native = frame.native(); + if let Ok(bytes) = native.bytes() { + let _ = tx.try_send(RawFrame { + bytes: bytes.to_vec(), + width: native.width as u32, + height: native.height as u32, + pixel_format: native.pixel_format, + bottom_up: native.is_bottom_up, + counter: native.perf_counter, + }); + } + })?; + let frames = (0..FRAME_COUNT) + .map(|_| rx.recv_timeout(Duration::from_secs(15))) + .collect::, _>>()?; + handle.stop_capturing().map_err(anyhow::Error::msg)?; + + let mut file = BufWriter::new(File::create(path)?); + for frame in &frames { + for value in [ + frame.width, + frame.height, + format_code(frame.pixel_format)?, + u32::from(frame.bottom_up), + frame.bytes.len() as u32, + ] { + file.write_all(&value.to_le_bytes())?; + } + file.write_all(&frame.counter.to_le_bytes())?; + file.write_all(&frame.bytes)?; + } + file.flush()?; + println!( + "Captured {} frames {:?} {}x{} bottom_up={} bytes={}", + frames.len(), + frames[0].pixel_format, + frames[0].width, + frames[0].height, + frames[0].bottom_up, + frames[0].bytes.len() + ); + Ok(()) + } + + fn load(path: &str) -> anyhow::Result> { + let mut file = BufReader::new(File::open(path)?); + let mut frames = Vec::with_capacity(FRAME_COUNT); + for _ in 0..FRAME_COUNT { + let mut values = [0u32; 5]; + for value in &mut values { + let mut bytes = [0; 4]; + file.read_exact(&mut bytes)?; + *value = u32::from_le_bytes(bytes); + } + let mut counter = [0; 8]; + file.read_exact(&mut counter)?; + let mut bytes = vec![0; values[4] as usize]; + file.read_exact(&mut bytes)?; + frames.push(RawFrame { + bytes, + width: values[0], + height: values[1], + pixel_format: format_from_code(values[2])?, + bottom_up: values[3] != 0, + counter: i64::from_le_bytes(counter), + }); + } + Ok(frames) + } + + fn fill_buffer(buffer: &IMFMediaBuffer, bytes: &[u8]) -> anyhow::Result<()> { + buffer.lock_for_write()?[..bytes.len()].copy_from_slice(bytes); + unsafe { buffer.SetCurrentLength(bytes.len() as u32)? }; + Ok(()) + } + + fn native_frame(raw: &RawFrame, buffer: Arc>) -> NativeCameraFrame { + NativeCameraFrame { + buffer, + pixel_format: raw.pixel_format, + width: raw.width, + height: raw.height, + is_bottom_up: raw.bottom_up, + timestamp: cap_timestamp::Timestamp::PerformanceCounter( + cap_timestamp::PerformanceCounterTimestamp::new(raw.counter), + ), + } + } + + fn new_frame(raw: &RawFrame) -> anyhow::Result { + let buffer = unsafe { MFCreateMemoryBuffer(raw.bytes.len() as u32)? }; + fill_buffer(&buffer, &raw.bytes)?; + Ok(native_frame(raw, Arc::from(Mutex::new(buffer)))) + } + + fn pooled_frame( + raw: &RawFrame, + pool: &mut Vec<(NativeCameraFrame, usize)>, + ) -> anyhow::Result { + let reusable = pool + .iter() + .find(|(frame, capacity)| { + *capacity >= raw.bytes.len() && Arc::strong_count(&frame.buffer) == 1 + }) + .map(|(frame, _)| frame.buffer.clone()); + let Some(buffer) = reusable else { + let frame = new_frame(raw)?; + if pool.len() < POOL_SIZE { + pool.push((frame.clone(), raw.bytes.len())); + } + return Ok(frame); + }; + { + let guard = buffer + .lock() + .map_err(|_| anyhow::anyhow!("Buffer poisoned"))?; + fill_buffer(&guard, &raw.bytes)?; + } + Ok(native_frame(raw, buffer)) + } + + fn legacy_upload(device: &ID3D11Device, raw: &RawFrame) -> anyhow::Result { + let (format, rows) = match (raw.pixel_format, raw.bottom_up) { + (PixelFormat::NV12, false) => (DXGI_FORMAT_NV12, raw.height + raw.height / 2), + (PixelFormat::YUYV422, false) => (DXGI_FORMAT_YUY2, raw.height), + (PixelFormat::RGB32 | PixelFormat::ARGB, false) => { + (DXGI_FORMAT_B8G8R8A8_UNORM, raw.height) + } + _ => bail!("The before path supports top-down NV12, YUYV422, RGB32 and ARGB frames"), + }; + let frame = new_frame(raw)?; + let buffer = frame + .buffer + .lock() + .map_err(|_| anyhow::anyhow!("Buffer poisoned"))?; + let lock = buffer.lock()?; + let data = &*lock; + let desc = D3D11_TEXTURE2D_DESC { + Width: raw.width, + Height: raw.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: 0, + }; + let init = D3D11_SUBRESOURCE_DATA { + pSysMem: data.as_ptr().cast(), + SysMemPitch: (data.len() / rows as usize) as u32, + SysMemSlicePitch: 0, + }; + let mut texture = None; + unsafe { device.CreateTexture2D(&desc, Some(&init), Some(&mut texture))? }; + texture.context("CreateTexture2D returned no texture") + } + + fn process_cpu_seconds() -> anyhow::Result { + let mut creation = FILETIME::default(); + let mut exit = FILETIME::default(); + let mut kernel = FILETIME::default(); + let mut user = FILETIME::default(); + unsafe { + GetProcessTimes( + GetCurrentProcess(), + &mut creation, + &mut exit, + &mut kernel, + &mut user, + )?; + } + let ticks = + |time: FILETIME| ((time.dwHighDateTime as u64) << 32) | time.dwLowDateTime as u64; + Ok((ticks(kernel) + ticks(user)) as f64 / 10_000_000.0) + } + + fn measure(gpu: &Gpu, frames: &[RawFrame], side: Side, wait: bool) -> anyhow::Result { + let mut samples = Vec::with_capacity(frames.len() * REPEATS); + let mut cpu = 0.0; + for _ in 0..REPEATS { + let mut buffers = CameraBuffers::new(); + let mut pool = Vec::new(); + let mut upload = |raw: &RawFrame| -> anyhow::Result { + match side { + Side::Before => legacy_upload(&gpu.device, raw), + Side::After => { + let frame = pooled_frame(raw, &mut pool)?; + Ok(upload_mf_buffer_to_texture( + &gpu.device, + &frame, + &mut buffers, + )?) + } + } + }; + for raw in frames.iter().take(WARMUP_FRAMES) { + drop(upload(raw)?); + gpu.flush(); + } + gpu.wait()?; + let cpu_start = process_cpu_seconds()?; + for raw in frames { + let start = Instant::now(); + let texture = upload(raw)?; + if wait { + gpu.wait()?; + } else { + gpu.flush(); + } + drop(texture); + samples.push(start.elapsed().as_secs_f64() * 1000.0); + } + gpu.wait()?; + cpu += process_cpu_seconds()? - cpu_start; + } + samples.sort_by(f64::total_cmp); + Ok(Stats { + median: samples[samples.len() / 2], + p95: samples[(samples.len() * 95).div_ceil(100) - 1], + mean: samples.iter().sum::() / samples.len() as f64, + cpu, + }) + } + + fn bench(path: &str, sides: &[Side]) -> anyhow::Result<()> { + let frames = load(path)?; + let gpu = Gpu::new()?; + println!( + "Frames: {} x {:?} {}x{}, {WARMUP_FRAMES} warmup, {REPEATS} repeats", + frames.len(), + frames[0].pixel_format, + frames[0].width, + frames[0].height + ); + for (wait, mode) in [(false, "submit"), (true, "gpu-complete")] { + let mut results = Vec::new(); + for &side in sides { + let stats = measure(&gpu, &frames, side, wait)?; + println!( + "{mode} {}: median_ms={:.3} p95_ms={:.3} mean_ms={:.3} cpu_s={:.3}", + if side == Side::Before { + "before" + } else { + "after" + }, + stats.median, + stats.p95, + stats.mean, + stats.cpu + ); + results.push(stats); + } + if let [before, after] = results.as_slice() { + println!( + "{mode} speedup: median {:.2}x p95 {:.2}x mean {:.2}x cpu {:.2}x", + before.median / after.median, + before.p95 / after.p95, + before.mean / after.mean, + before.cpu / after.cpu + ); + } + } + Ok(()) + } + + fn validate() -> anyhow::Result<()> { + let gpu = Gpu::new()?; + let mut buffers = CameraBuffers::new(); + let mut checks = Vec::new(); + for (width, height) in [(64u32, 32u32), (128, 48), (64, 32)] { + for format in [ + PixelFormat::YUYV422, + PixelFormat::UYVY422, + PixelFormat::NV12, + PixelFormat::RGB32, + PixelFormat::ARGB, + ] { + for flip in [false, true] { + for sequence in 0..3u8 { + let row_bytes = width as usize + * match format { + PixelFormat::NV12 => 1, + PixelFormat::RGB32 | PixelFormat::ARGB => 4, + _ => 2, + }; + let pitch = row_bytes + 16; + let rows = height as usize + + if format == PixelFormat::NV12 { + height as usize / 2 + } else { + 0 + }; + let mut bytes = vec![0; pitch * rows]; + for (row, data) in bytes.chunks_exact_mut(pitch).enumerate() { + for (column, value) in data.iter_mut().enumerate() { + *value = (row as u8) + .wrapping_mul(7) + .wrapping_add(column as u8) + .wrapping_add(sequence.wrapping_mul(53)); + } + } + let mut expected = vec![0; row_bytes * rows]; + for row in 0..rows { + let source_row = if !flip { + row + } else if row < height as usize { + height as usize - 1 - row + } else { + rows - 1 - (row - height as usize) + }; + let source = &bytes[source_row * pitch..source_row * pitch + row_bytes]; + let dest = &mut expected[row * row_bytes..(row + 1) * row_bytes]; + if format == PixelFormat::UYVY422 { + for (src, dst) in + source.chunks_exact(4).zip(dest.chunks_exact_mut(4)) + { + dst.copy_from_slice(&[src[1], src[0], src[3], src[2]]); + } + } else { + dest.copy_from_slice(source); + } + } + let raw = RawFrame { + bytes, + width, + height, + pixel_format: format, + bottom_up: flip, + counter: 0, + }; + let frame = new_frame(&raw)?; + let texture = + upload_mf_buffer_to_texture(&gpu.device, &frame, &mut buffers)?; + let mut desc = D3D11_TEXTURE2D_DESC::default(); + unsafe { texture.GetDesc(&mut desc) }; + desc.Usage = D3D11_USAGE_STAGING; + desc.BindFlags = 0; + desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ.0 as u32; + let mut readback = None; + unsafe { + gpu.device + .CreateTexture2D(&desc, None, Some(&mut readback))?; + gpu.context.CopyResource( + readback.as_ref().context("No readback texture")?, + &texture, + ); + } + checks.push((readback, expected, row_bytes, rows, format, flip)); + } + } + } + } + gpu.wait()?; + let count = checks.len(); + for (readback, expected, row_bytes, rows, format, flip) in checks { + let readback = readback.context("No readback texture")?; + let mut mapped = D3D11_MAPPED_SUBRESOURCE::default(); + unsafe { + gpu.context + .Map(&readback, 0, D3D11_MAP_READ, 0, Some(&mut mapped))?; + } + let matches = (0..rows).all(|row| { + let actual = unsafe { + std::slice::from_raw_parts( + mapped + .pData + .cast::() + .add(row * mapped.RowPitch as usize), + row_bytes, + ) + }; + actual == &expected[row * row_bytes..(row + 1) * row_bytes] + }); + unsafe { gpu.context.Unmap(&readback, 0) }; + if !matches { + bail!("Readback mismatch for {format:?} flip={flip}"); + } + } + println!("Validation: {count} GPU readbacks matched"); + Ok(()) + } + + pub fn run() -> anyhow::Result<()> { + cap_mediafoundation_utils::thread_init(); + let args: Vec = std::env::args().skip(1).collect(); + let path = || { + args.get(1) + .map(String::as_str) + .context("Expected a frames file path") + }; + match args.first().map(String::as_str) { + Some("capture") => capture(path()?, args.get(2).map(String::as_str)), + Some("before") => bench(path()?, &[Side::Before]), + Some("after") => bench(path()?, &[Side::After]), + Some("both") => bench(path()?, &[Side::Before, Side::After]), + Some("validate") => validate(), + _ => bail!( + "Usage: capture [camera name] | before | after | both | validate" + ), + } + } +} From 1cdc0f8897b6032030853f24e253af6a35e55542 Mon Sep 17 00:00:00 2001 From: Kyzer <36684609+kyzer1023@users.noreply.github.com> Date: Sun, 25 Oct 2026 04:07:37 +0800 Subject: [PATCH 03/10] Limit camera benchmark capture to modes both upload paths support --- crates/recording/examples/windows-camera-upload-benchmark.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/recording/examples/windows-camera-upload-benchmark.rs b/crates/recording/examples/windows-camera-upload-benchmark.rs index f689266cc2b..6dbde115e1f 100644 --- a/crates/recording/examples/windows-camera-upload-benchmark.rs +++ b/crates/recording/examples/windows-camera-upload-benchmark.rs @@ -180,7 +180,7 @@ mod windows_bench { formats.retain(|format| { matches!( format.pixel_format_name().as_deref(), - Some("YUYV422" | "UYVY422" | "NV12" | "RGB32" | "ARGB") + Some("YUYV422" | "NV12" | "RGB32" | "ARGB") ) }); formats.sort_by_key(|format| { @@ -220,6 +220,9 @@ mod windows_bench { .map(|_| rx.recv_timeout(Duration::from_secs(15))) .collect::, _>>()?; handle.stop_capturing().map_err(anyhow::Error::msg)?; + if frames.iter().any(|frame| frame.bottom_up) { + bail!("The before path does not support bottom-up frames"); + } let mut file = BufWriter::new(File::create(path)?); for frame in &frames { From 14fd49b57c85f6d49d43b07bf2ae3900e27bedc9 Mon Sep 17 00:00:00 2001 From: Kyzer <36684609+kyzer1023@users.noreply.github.com> Date: Sun, 1 Nov 2026 01:56:13 +0800 Subject: [PATCH 04/10] chore: remove camera benchmark header narration --- .../examples/windows-camera-upload-benchmark.rs | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/crates/recording/examples/windows-camera-upload-benchmark.rs b/crates/recording/examples/windows-camera-upload-benchmark.rs index 6dbde115e1f..13ca622bde9 100644 --- a/crates/recording/examples/windows-camera-upload-benchmark.rs +++ b/crates/recording/examples/windows-camera-upload-benchmark.rs @@ -1,16 +1,3 @@ -//! Measures the Windows native camera upload path: the per-frame media buffer -//! copy plus `upload_mf_buffer_to_texture`. `before` replays frames through an -//! inline copy of the previous path (new `MFCreateMemoryBuffer` and new -//! `CreateTexture2D` per frame), `after` through the pooled buffers and the -//! library upload. -//! -//! cargo build --release -p cap-recording --example windows-camera-upload-benchmark -//! windows-camera-upload-benchmark capture frames.bin [camera name] -//! windows-camera-upload-benchmark both frames.bin -//! windows-camera-upload-benchmark before frames.bin -//! windows-camera-upload-benchmark after frames.bin -//! windows-camera-upload-benchmark validate - #[cfg(not(target_os = "windows"))] fn main() { eprintln!("windows-camera-upload-benchmark: skipped (not Windows)"); From 6189790fefd299dffda37aaeb5f0db4646b32dd7 Mon Sep 17 00:00:00 2001 From: Kyzer <36684609+kyzer1023@users.noreply.github.com> Date: Sun, 1 Nov 2026 02:11:16 +0800 Subject: [PATCH 05/10] fix: configure current Hyprland in the Linux harness --- scripts/linux-desktop-harness/arch-up.sh | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/scripts/linux-desktop-harness/arch-up.sh b/scripts/linux-desktop-harness/arch-up.sh index 6a1a8028862..043d83d2e23 100755 --- a/scripts/linux-desktop-harness/arch-up.sh +++ b/scripts/linux-desktop-harness/arch-up.sh @@ -30,6 +30,17 @@ debug { disable_logs = false } exec-once = sh -c '$export_session' exec-once = waybar CONF + cat >"$HOME/.config/hypr/hyprland.lua" <"$HOME/.config/hypr/xdph.conf" < Date: Sun, 1 Nov 2026 02:40:44 +0800 Subject: [PATCH 06/10] fix: allow busy Wayland compositors to enumerate displays --- .../src/platform/linux/wayland.rs | 43 ++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) diff --git a/crates/scap-targets/src/platform/linux/wayland.rs b/crates/scap-targets/src/platform/linux/wayland.rs index c4b8bcdbf6a..8c0118f92bb 100644 --- a/crates/scap-targets/src/platform/linux/wayland.rs +++ b/crates/scap-targets/src/platform/linux/wayland.rs @@ -15,6 +15,8 @@ use wayland_protocols::xdg::xdg_output::zv1::client::{zxdg_output_manager_v1, zx use super::{DisplayImpl, LogicalBounds, LogicalPosition, LogicalSize}; +const QUERY_TIMEOUT: Duration = Duration::from_secs(1); + #[derive(Clone, Copy, Default)] struct OutputGeometry { position: (i32, i32), @@ -108,7 +110,7 @@ pub(super) fn displays() -> Option> { runtime.join(display) }; let connection = Connection::from_socket(UnixStream::connect(socket).ok()?).ok()?; - query(&connection, Duration::from_millis(250)) + query(&connection, QUERY_TIMEOUT) } fn output_uuid(name: &str) -> Option { @@ -453,6 +455,45 @@ mod tests { assert!(started.elapsed() < Duration::from_secs(1)); } + #[test] + fn busy_compositor_can_finish_display_enumeration_after_a_quarter_second() { + use std::io::{Read, Write}; + + let (client, mut server) = UnixStream::pair().unwrap(); + let (finished_tx, finished_rx) = std::sync::mpsc::channel(); + let responder = std::thread::spawn(move || -> std::io::Result<()> { + for reply in 0..2 { + loop { + let mut header = [0u8; 8]; + server.read_exact(&mut header)?; + let object = u32::from_ne_bytes(header[..4].try_into().unwrap()); + let message = u32::from_ne_bytes(header[4..].try_into().unwrap()); + let mut payload = vec![0; (message >> 16) as usize - header.len()]; + server.read_exact(&mut payload)?; + if object != 1 || message & 0xffff != 0 { + continue; + } + if reply == 0 { + std::thread::sleep(Duration::from_millis(350)); + } + let callback = u32::from_ne_bytes(payload[..4].try_into().unwrap()); + server.write_all(&callback.to_ne_bytes())?; + server.write_all(&(12u32 << 16).to_ne_bytes())?; + server.write_all(&0u32.to_ne_bytes())?; + break; + } + } + let _ = finished_rx.recv(); + Ok(()) + }); + let connection = Connection::from_socket(client).unwrap(); + let result = query(&connection, QUERY_TIMEOUT); + drop(connection); + let _ = finished_tx.send(()); + responder.join().unwrap().unwrap(); + assert!(result.is_some()); + } + #[test] fn wayland_session_does_not_use_xwayland_dimensions() { assert!(super::super::prefers_wayland_environment( From b3b0250afe2a2d94a45ba2ca98bf9832f1a6ca24 Mon Sep 17 00:00:00 2001 From: Kyzer <36684609+kyzer1023@users.noreply.github.com> Date: Sun, 1 Nov 2026 15:29:26 +0800 Subject: [PATCH 07/10] chore: retry CI after hosted runner disconnect From ff7c5752afdaa46f9372e86296664fe57ef8a93a Mon Sep 17 00:00:00 2001 From: Kyzer <36684609+kyzer1023@users.noreply.github.com> Date: Thu, 5 Nov 2026 03:13:30 +0800 Subject: [PATCH 08/10] fix: convert RGB24/BGR24 camera frames to BGRA before upload --- .../windows-camera-upload-benchmark.rs | 50 +++++- .../src/output_pipeline/camera_rgb.rs | 151 ++++++++++++++++++ crates/recording/src/output_pipeline/mod.rs | 2 + crates/recording/src/output_pipeline/win.rs | 44 ++++- 4 files changed, 234 insertions(+), 13 deletions(-) create mode 100644 crates/recording/src/output_pipeline/camera_rgb.rs diff --git a/crates/recording/examples/windows-camera-upload-benchmark.rs b/crates/recording/examples/windows-camera-upload-benchmark.rs index 13ca622bde9..c8fb44829fa 100644 --- a/crates/recording/examples/windows-camera-upload-benchmark.rs +++ b/crates/recording/examples/windows-camera-upload-benchmark.rs @@ -468,22 +468,34 @@ mod windows_bench { let gpu = Gpu::new()?; let mut buffers = CameraBuffers::new(); let mut checks = Vec::new(); - for (width, height) in [(64u32, 32u32), (128, 48), (64, 32)] { + for (width, height) in [(64u32, 32u32), (128, 48), (64, 32), (3, 2)] { for format in [ PixelFormat::YUYV422, PixelFormat::UYVY422, PixelFormat::NV12, PixelFormat::RGB32, PixelFormat::ARGB, + PixelFormat::RGB24, + PixelFormat::BGR24, ] { + let is_rgb24 = matches!(format, PixelFormat::RGB24 | PixelFormat::BGR24); + if !width.is_multiple_of(2) && !is_rgb24 { + continue; + } for flip in [false, true] { for sequence in 0..3u8 { let row_bytes = width as usize * match format { PixelFormat::NV12 => 1, PixelFormat::RGB32 | PixelFormat::ARGB => 4, + PixelFormat::RGB24 | PixelFormat::BGR24 => 3, _ => 2, }; + let upload_row_bytes = if is_rgb24 { + width as usize * 4 + } else { + row_bytes + }; let pitch = row_bytes + 16; let rows = height as usize + if format == PixelFormat::NV12 { @@ -500,7 +512,7 @@ mod windows_bench { .wrapping_add(sequence.wrapping_mul(53)); } } - let mut expected = vec![0; row_bytes * rows]; + let mut expected = vec![0; upload_row_bytes * rows]; for row in 0..rows { let source_row = if !flip { row @@ -510,8 +522,15 @@ mod windows_bench { rows - 1 - (row - height as usize) }; let source = &bytes[source_row * pitch..source_row * pitch + row_bytes]; - let dest = &mut expected[row * row_bytes..(row + 1) * row_bytes]; - if format == PixelFormat::UYVY422 { + let dest = + &mut expected[row * upload_row_bytes..(row + 1) * upload_row_bytes]; + if is_rgb24 { + for (src, dst) in + source.chunks_exact(3).zip(dest.chunks_exact_mut(4)) + { + dst.copy_from_slice(&[src[0], src[1], src[2], 255]); + } + } else if format == PixelFormat::UYVY422 { for (src, dst) in source.chunks_exact(4).zip(dest.chunks_exact_mut(4)) { @@ -534,6 +553,9 @@ mod windows_bench { upload_mf_buffer_to_texture(&gpu.device, &frame, &mut buffers)?; let mut desc = D3D11_TEXTURE2D_DESC::default(); unsafe { texture.GetDesc(&mut desc) }; + if is_rgb24 && desc.Format != DXGI_FORMAT_B8G8R8A8_UNORM { + bail!("Expected BGRA texture for {format:?}"); + } desc.Usage = D3D11_USAGE_STAGING; desc.BindFlags = 0; desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ.0 as u32; @@ -546,7 +568,7 @@ mod windows_bench { &texture, ); } - checks.push((readback, expected, row_bytes, rows, format, flip)); + checks.push((readback, expected, upload_row_bytes, rows, format, flip)); } } } @@ -577,6 +599,24 @@ mod windows_bench { bail!("Readback mismatch for {format:?} flip={flip}"); } } + for pixel_format in [PixelFormat::RGB24, PixelFormat::BGR24] { + for bottom_up in [false, true] { + for len in [8, 17] { + let raw = RawFrame { + bytes: vec![0; len], + width: 3, + height: 2, + pixel_format, + bottom_up, + counter: 0, + }; + let frame = new_frame(&raw)?; + if upload_mf_buffer_to_texture(&gpu.device, &frame, &mut buffers).is_ok() { + bail!("Accepted malformed {pixel_format:?} buffer with {len} bytes"); + } + } + } + } println!("Validation: {count} GPU readbacks matched"); Ok(()) } diff --git a/crates/recording/src/output_pipeline/camera_rgb.rs b/crates/recording/src/output_pipeline/camera_rgb.rs new file mode 100644 index 00000000000..84abce8a6df --- /dev/null +++ b/crates/recording/src/output_pipeline/camera_rgb.rs @@ -0,0 +1,151 @@ +pub(super) fn convert_rgb24_to_bgra_into<'a>( + src: &[u8], + dst: &'a mut Vec, + width: usize, + height: usize, + src_stride: usize, + red_first: bool, + bottom_up: bool, +) -> Result<&'a [u8], &'static str> { + let invalid_layout = "Invalid 24-bit camera buffer layout"; + if width == 0 || height == 0 { + return Err(invalid_layout); + } + let src_row_bytes = width.checked_mul(3).ok_or(invalid_layout)?; + let dst_row_bytes = width.checked_mul(4).ok_or(invalid_layout)?; + let required_src_len = (height - 1) + .checked_mul(src_stride) + .and_then(|offset| offset.checked_add(src_row_bytes)) + .ok_or(invalid_layout)?; + let dst_len = height.checked_mul(dst_row_bytes).ok_or(invalid_layout)?; + if src_stride < src_row_bytes || src.len() < required_src_len { + return Err(invalid_layout); + } + + dst.resize(dst_len, 0); + let (blue, red) = if red_first { (2, 0) } else { (0, 2) }; + for (row, dst_row) in dst.chunks_exact_mut(dst_row_bytes).enumerate() { + let src_row = if bottom_up { height - 1 - row } else { row }; + let start = src_row * src_stride; + for (src_pixel, dst_pixel) in src[start..start + src_row_bytes] + .chunks_exact(3) + .zip(dst_row.chunks_exact_mut(4)) + { + dst_pixel.copy_from_slice(&[src_pixel[blue], src_pixel[1], src_pixel[red], 255]); + } + } + Ok(dst) +} + +#[cfg(test)] +mod tests { + use super::convert_rgb24_to_bgra_into; + + #[test] + fn rgb24_to_bgra_channel_order() { + let mut dst = Vec::new(); + let result = convert_rgb24_to_bgra_into( + &[255, 0, 0, 0, 255, 0, 0, 0, 255], + &mut dst, + 3, + 1, + 9, + true, + false, + ) + .unwrap(); + assert_eq!(result, &[0, 0, 255, 255, 0, 255, 0, 255, 255, 0, 0, 255]); + } + + #[test] + fn bgr24_to_bgra_channel_order() { + let mut dst = Vec::new(); + let result = convert_rgb24_to_bgra_into( + &[0, 0, 255, 0, 255, 0, 255, 0, 0], + &mut dst, + 3, + 1, + 9, + false, + false, + ) + .unwrap(); + assert_eq!(result, &[0, 0, 255, 255, 0, 255, 0, 255, 255, 0, 0, 255]); + } + + #[test] + fn padded_odd_width_rows_in_both_orientations() { + let src = [ + 1, 2, 3, 4, 5, 6, 7, 8, 9, 222, 222, 222, 10, 11, 12, 13, 14, 15, 16, 17, 18, + ]; + for red_first in [false, true] { + let (top, bottom) = if red_first { + ( + [3, 2, 1, 255, 6, 5, 4, 255, 9, 8, 7, 255], + [12, 11, 10, 255, 15, 14, 13, 255, 18, 17, 16, 255], + ) + } else { + ( + [1, 2, 3, 255, 4, 5, 6, 255, 7, 8, 9, 255], + [10, 11, 12, 255, 13, 14, 15, 255, 16, 17, 18, 255], + ) + }; + for bottom_up in [false, true] { + let mut dst = Vec::new(); + let result = + convert_rgb24_to_bgra_into(&src, &mut dst, 3, 2, 12, red_first, bottom_up) + .unwrap(); + let expected = if bottom_up { + [bottom, top].concat() + } else { + [top, bottom].concat() + }; + assert_eq!(result, expected); + } + } + } + + #[test] + fn rejects_malformed_buffers_before_writing() { + for (width, height, stride, len) in [ + (3, 2, 12, 20), + (3, 2, 8, 24), + (0, 2, 12, 24), + (3, 0, 12, 24), + (usize::MAX, 1, 12, 24), + (3, usize::MAX, 12, 24), + ] { + for red_first in [false, true] { + for bottom_up in [false, true] { + let mut dst = vec![42; 4]; + assert!( + convert_rgb24_to_bgra_into( + &[0; 24][..len], + &mut dst, + width, + height, + stride, + red_first, + bottom_up, + ) + .is_err() + ); + assert_eq!(dst, [42; 4]); + } + } + } + } + + #[test] + fn reuses_scratch_buffer_and_overwrites_previous_frame() { + let mut dst = Vec::new(); + convert_rgb24_to_bgra_into(&[1; 18], &mut dst, 3, 2, 9, false, false).unwrap(); + let ptr = dst.as_ptr(); + let capacity = dst.capacity(); + let result = + convert_rgb24_to_bgra_into(&[2, 3, 4], &mut dst, 1, 1, 3, true, false).unwrap(); + assert_eq!(result, &[4, 3, 2, 255]); + assert_eq!(dst.as_ptr(), ptr); + assert_eq!(dst.capacity(), capacity); + } +} diff --git a/crates/recording/src/output_pipeline/mod.rs b/crates/recording/src/output_pipeline/mod.rs index 25ecb5c52aa..0193c3877ba 100644 --- a/crates/recording/src/output_pipeline/mod.rs +++ b/crates/recording/src/output_pipeline/mod.rs @@ -1,4 +1,6 @@ mod async_camera; +#[cfg(any(windows, test))] +mod camera_rgb; mod core; pub mod ffmpeg; #[cfg(any(windows, test))] diff --git a/crates/recording/src/output_pipeline/win.rs b/crates/recording/src/output_pipeline/win.rs index a8cc7ef122c..6f118bf55db 100644 --- a/crates/recording/src/output_pipeline/win.rs +++ b/crates/recording/src/output_pipeline/win.rs @@ -1,7 +1,9 @@ use crate::{ AudioFrame, AudioMuxer, Muxer, TaskPool, VideoFrame, VideoMuxer, output_pipeline::{ - HealthSender, PipelineHealthEvent, emit_health, + HealthSender, PipelineHealthEvent, + camera_rgb::convert_rgb24_to_bgra_into, + emit_health, frame_pacing::{FramePacer, Paced}, mjpeg::MjpegDecoder, }, @@ -122,8 +124,7 @@ use windows::{ Win32::Graphics::{ Direct3D11::ID3D11Device, Dxgi::Common::{ - DXGI_FORMAT, DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_NV12, DXGI_FORMAT_R8G8B8A8_UNORM, - DXGI_FORMAT_YUY2, + DXGI_FORMAT, DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_NV12, DXGI_FORMAT_YUY2, }, }, }; @@ -628,10 +629,10 @@ impl NativeCameraFrame { cap_camera_windows::PixelFormat::YUYV422 | cap_camera_windows::PixelFormat::UYVY422 => { DXGI_FORMAT_YUY2 } - cap_camera_windows::PixelFormat::ARGB | cap_camera_windows::PixelFormat::RGB32 => { - DXGI_FORMAT_B8G8R8A8_UNORM - } - cap_camera_windows::PixelFormat::RGB24 => DXGI_FORMAT_R8G8B8A8_UNORM, + cap_camera_windows::PixelFormat::ARGB + | cap_camera_windows::PixelFormat::RGB32 + | cap_camera_windows::PixelFormat::RGB24 + | cap_camera_windows::PixelFormat::BGR24 => DXGI_FORMAT_B8G8R8A8_UNORM, _ => DXGI_FORMAT_NV12, } } @@ -669,7 +670,7 @@ fn ffmpeg_pixel_to_dxgi(pixel: ffmpeg::format::Pixel) -> DXGI_FORMAT { ffmpeg::format::Pixel::NV12 => DXGI_FORMAT_NV12, ffmpeg::format::Pixel::YUYV422 | ffmpeg::format::Pixel::UYVY422 => DXGI_FORMAT_YUY2, ffmpeg::format::Pixel::BGRA | ffmpeg::format::Pixel::RGBA => DXGI_FORMAT_B8G8R8A8_UNORM, - ffmpeg::format::Pixel::BGR24 | ffmpeg::format::Pixel::RGB24 => DXGI_FORMAT_R8G8B8A8_UNORM, + ffmpeg::format::Pixel::BGR24 | ffmpeg::format::Pixel::RGB24 => DXGI_FORMAT_B8G8R8A8_UNORM, _ => DXGI_FORMAT_NV12, } } @@ -1098,6 +1099,7 @@ impl AudioMuxer for WindowsCameraMuxer { pub struct CameraBuffers { uyvy_buffer: Vec, flip_buffer: Vec, + bgra_buffer: Vec, texture: Option, } @@ -1114,6 +1116,7 @@ impl CameraBuffers { Self { uyvy_buffer: Vec::new(), flip_buffer: Vec::new(), + bgra_buffer: Vec::new(), texture: None, } } @@ -1903,10 +1906,35 @@ pub fn upload_mf_buffer_to_texture( let dynamic = cached.dynamic; let needs_uyvy_conversion = frame.pixel_format == cap_camera_windows::PixelFormat::UYVY422; + let needs_rgb_conversion = matches!( + frame.pixel_format, + cap_camera_windows::PixelFormat::RGB24 | cap_camera_windows::PixelFormat::BGR24 + ); let needs_flip = frame.is_bottom_up; let mut row_pitch = layout.primary_stride as u32; let data: &[u8] = match (needs_uyvy_conversion, needs_flip) { + (false, flip) if needs_rgb_conversion => { + row_pitch = frame.width.checked_mul(4).ok_or_else(|| { + windows::core::Error::new( + windows::Win32::Foundation::E_INVALIDARG, + "Camera BGRA row pitch is too large", + ) + })?; + // Windows RGB24 stores BGR bytes, just like BGR24 and the FFmpeg fallback. + convert_rgb24_to_bgra_into( + original_data, + &mut buffers.bgra_buffer, + frame.width as usize, + frame.height as usize, + layout.primary_stride, + false, + flip, + ) + .map_err(|message| { + windows::core::Error::new(windows::Win32::Foundation::E_INVALIDARG, message) + })? + } (false, false) => original_data, (true, false) => { let uyvy_size = (frame.width * frame.height * 2) as usize; From e0eaaecfb0e832ddbc5365c7b23ba950cf34f624 Mon Sep 17 00:00:00 2001 From: Kyzer <36684609+kyzer1023@users.noreply.github.com> Date: Thu, 5 Nov 2026 03:44:59 +0800 Subject: [PATCH 09/10] ci: retrigger (unrelated rendering transition flake) From 2ee4778d0f40777f1e0b19aa049142f3cf1d3ee1 Mon Sep 17 00:00:00 2001 From: Kyzer <36684609+kyzer1023@users.noreply.github.com> Date: Fri, 6 Nov 2026 15:49:58 +0800 Subject: [PATCH 10/10] ci: retrigger after macos-intel native-deps fetch flake