diff --git a/apps/desktop-gpui/examples/camera-preview-convert-benchmark.rs b/apps/desktop-gpui/examples/camera-preview-convert-benchmark.rs index cff351041ee..e4bd957298d 100644 --- a/apps/desktop-gpui/examples/camera-preview-convert-benchmark.rs +++ b/apps/desktop-gpui/examples/camera-preview-convert-benchmark.rs @@ -11,11 +11,23 @@ //! Metal-compatible IOSurface-backed BGRA buffer from a fixed ring, ready for //! `paint_surface` with zero further CPU touches. //! -//! Run: cargo run -p cap-desktop-gpui --example camera-preview-convert-benchmark --release +//! Run from `apps/desktop-gpui` (macOS keeps the IOSurface comparison above; +//! Linux and Windows compare swscale with the BT.601 kernel): +//! cargo run --release --example camera-preview-convert-benchmark +//! +//! From the repo root the same example is: +//! cargo run --manifest-path apps/desktop-gpui/Cargo.toml --release --example camera-preview-convert-benchmark +//! +//! Windows: `node scripts/setup.js` first, then put `target\ffmpeg\bin` on `PATH` +//! so the example can load the shared FFmpeg the desktop app is built against. +//! The command is unchanged. `CAP_CAMERA_BGRA_SIMD=portable`, `sse4.1`, `avx2`, or +//! `swscale` selects the kernel. `swscale` skips it and times only the swscale +//! columns. The CSV reports median, p90, and spread for mirrored and unmirrored +//! frames. No display and no GPU. #[cfg(not(target_os = "macos"))] fn main() { - eprintln!("macOS only"); + portable::run(); } #[cfg(target_os = "macos")] @@ -250,3 +262,273 @@ mod macos { } } } + +/// Linux and Windows. Each column is timed alone. `sws_convert` is `scaler.run` +/// into a reused BGRA frame (plus a reused-buffer mirror when `mirrored=1`). +/// `sws_app` is the old preview: `Video::empty` plus `copy_rows` every frame. +/// `CAP_CAMERA_BGRA_SIMD=portable`, `sse4.1`, `avx2`, or `swscale`. +#[cfg(not(target_os = "macos"))] +mod portable { + use std::{hint::black_box, time::Instant}; + + use cap_gpui_kernels::{ + camera_bgra::{self, Packed422}, + frame, + }; + use ffmpeg::{ + format::Pixel, + software::scaling::{Context, Flags}, + }; + + const REPS: usize = 7; + const WARMUP: usize = 12; + const SAMPLES: usize = 40; + + pub fn run() { + ffmpeg::init().expect("ffmpeg"); + burn_in(); + println!("cpu,{}", cpu_model()); + println!("arch,{}", std::env::consts::ARCH); + println!("simd,{}", camera_bgra::simd_path()); + println!( + "case,width,height,mirrored,reps,sws_convert_median_ms,sws_convert_p90_ms,sws_convert_spread_ms,sws_app_median_ms,sws_app_p90_ms,sws_app_spread_ms,kernel_median_ms,kernel_p90_ms,kernel_spread_ms,speedup_vs_convert,speedup_vs_app,max_abs_diff" + ); + println!( + "# {REPS} reps x {SAMPLES} frames after {WARMUP} warmup, each column alone. spread_ms is max(rep median) - min(rep median). sws_convert reuses its BGRA frame. sws_app allocates every frame." + ); + for (name, pixel, width, height) in [ + ("YUYV", Pixel::YUYV422, 1280, 720), + ("YUYV", Pixel::YUYV422, 1920, 1080), + ("UYVY", Pixel::UYVY422, 1280, 720), + ("UYVY", Pixel::UYVY422, 1920, 1080), + ("NV12", Pixel::NV12, 1280, 720), + ("NV12", Pixel::NV12, 1920, 1080), + ] { + for mirrored in [false, true] { + bench(name, pixel, width, height, mirrored); + } + } + } + + fn cpu_model() -> String { + #[cfg(target_os = "linux")] + if let Ok(text) = std::fs::read_to_string("/proc/cpuinfo") { + for line in text.lines() { + if let Some(model) = line.strip_prefix("model name") { + return model.trim_start_matches([' ', ':', '\t']).to_string(); + } + } + } + std::env::consts::ARCH.to_string() + } + + fn burn_in() { + let mut frame = ffmpeg::frame::Video::new(Pixel::YUYV422, 1920, 1080); + fill(&mut frame); + let mut scaler = Context::get( + Pixel::YUYV422, + 1920, + 1080, + Pixel::BGRA, + 1920, + 1080, + Flags::BILINEAR, + ) + .expect("swscale context"); + for _ in 0..12 { + black_box(swscale_app(&mut scaler, &frame, false)); + black_box(kernel_bgra(&frame, false)); + } + } + + fn bench(name: &str, pixel: Pixel, width: u32, height: u32, mirrored: bool) { + let mut frame = ffmpeg::frame::Video::new(pixel, width, height); + fill(&mut frame); + let mut scaler = Context::get( + pixel, + width, + height, + Pixel::BGRA, + width, + height, + Flags::BILINEAR, + ) + .expect("swscale context"); + let mut reused = ffmpeg::frame::Video::new(Pixel::BGRA, width, height); + let mut tight = vec![0u8; width as usize * height as usize * 4]; + scaler.run(&frame, &mut reused).expect("swscale"); + blit(&reused, &mut tight, mirrored); + let kernel_frame = kernel_bgra(&frame, mirrored); + let max_abs_diff = kernel_frame.as_ref().map(|kernel_frame| { + assert_eq!(tight.len(), kernel_frame.len()); + tight + .iter() + .zip(kernel_frame) + .map(|(before, after)| before.abs_diff(*after)) + .max() + .unwrap_or(0) + }); + + let convert_stats = time_path(|| { + scaler.run(&frame, &mut reused).expect("swscale"); + if mirrored { + blit(&reused, &mut tight, true); + black_box(tight[0]); + } else { + black_box(reused.data(0)[0]); + } + }); + let app_stats = time_path(|| { + black_box(swscale_app(&mut scaler, &frame, mirrored)); + }); + let flag = u8::from(mirrored); + let Some(max_abs_diff) = max_abs_diff else { + println!( + "{name},{width},{height},{flag},{REPS},{:.3},{:.3},{:.3},{:.3},{:.3},{:.3},fallback,fallback,fallback,,,", + convert_stats.median, + convert_stats.p90, + convert_stats.spread, + app_stats.median, + app_stats.p90, + app_stats.spread, + ); + return; + }; + let kernel_stats = time_path(|| { + black_box(kernel_bgra(&frame, mirrored)); + }); + println!( + "{name},{width},{height},{flag},{REPS},{:.3},{:.3},{:.3},{:.3},{:.3},{:.3},{:.3},{:.3},{:.3},{:.2},{:.2},{max_abs_diff}", + convert_stats.median, + convert_stats.p90, + convert_stats.spread, + app_stats.median, + app_stats.p90, + app_stats.spread, + kernel_stats.median, + kernel_stats.p90, + kernel_stats.spread, + convert_stats.median / kernel_stats.median, + app_stats.median / kernel_stats.median, + ); + } + + struct PathStats { + median: f64, + p90: f64, + spread: f64, + } + + fn time_path(mut body: impl FnMut()) -> PathStats { + let mut pooled = Vec::with_capacity(REPS * SAMPLES); + let mut rep_medians = Vec::with_capacity(REPS); + for _ in 0..REPS { + for _ in 0..WARMUP { + body(); + } + let mut rep = Vec::with_capacity(SAMPLES); + for _ in 0..SAMPLES { + rep.push(elapsed_ms(&mut body)); + } + pooled.extend_from_slice(&rep); + rep_medians.push(percentile(&mut rep, 50)); + } + let median = percentile(&mut pooled, 50); + let p90 = percentile(&mut pooled, 90); + rep_medians.sort_by(f64::total_cmp); + let spread = rep_medians[rep_medians.len() - 1] - rep_medians[0]; + PathStats { + median, + p90, + spread, + } + } + + fn elapsed_ms(body: impl FnOnce()) -> f64 { + let started = Instant::now(); + body(); + started.elapsed().as_secs_f64() * 1_000.0 + } + + fn percentile(samples: &mut [f64], pct: usize) -> f64 { + samples.sort_by(f64::total_cmp); + let index = (samples.len() - 1) * pct / 100; + samples[index] + } + + fn fill(frame: &mut ffmpeg::frame::Video) { + let planes = if frame.format() == Pixel::NV12 { 2 } else { 1 }; + for plane in 0..planes { + for (index, byte) in frame.data_mut(plane).iter_mut().enumerate() { + *byte = index.wrapping_mul(17).wrapping_add(plane * 41) as u8; + } + } + } + + fn blit(frame: &ffmpeg::frame::Video, dst: &mut [u8], mirrored: bool) { + let width = frame.width() as usize; + let height = frame.height() as usize; + let stride = frame.stride(0); + let row_bytes = width * 4; + let src = frame.data(0); + for row in 0..height { + let input = &src[row * stride..row * stride + row_bytes]; + let output = &mut dst[row * row_bytes..(row + 1) * row_bytes]; + if mirrored { + let (dst_px, _) = output.as_chunks_mut::<4>(); + let (src_px, _) = input.as_chunks::<4>(); + for (slot, pixel) in dst_px.iter_mut().zip(src_px.iter().rev()) { + *slot = *pixel; + } + } else { + output.copy_from_slice(input); + } + } + } + + fn swscale_app(scaler: &mut Context, frame: &ffmpeg::frame::Video, mirrored: bool) -> Vec { + let mut converted = ffmpeg::frame::Video::empty(); + scaler.run(frame, &mut converted).expect("swscale"); + frame::copy_rows( + converted.data(0), + converted.width() as usize * 4, + converted.stride(0), + converted.height() as usize, + mirrored, + ) + .expect("tight bgra rows") + } + + fn kernel_bgra(frame: &ffmpeg::frame::Video, mirrored: bool) -> Option> { + let width = frame.width() as usize; + let height = frame.height() as usize; + match frame.format() { + Pixel::YUYV422 => camera_bgra::packed422_to_bgra( + frame.data(0), + width, + height, + frame.stride(0), + Packed422::Yuyv, + mirrored, + ), + Pixel::UYVY422 => camera_bgra::packed422_to_bgra( + frame.data(0), + width, + height, + frame.stride(0), + Packed422::Uyvy, + mirrored, + ), + Pixel::NV12 => camera_bgra::nv12_to_bgra( + frame.data(0), + frame.data(1), + width, + height, + frame.stride(0), + frame.stride(1), + mirrored, + ), + _ => None, + } + } +} diff --git a/apps/desktop-gpui/kernels/src/camera_bgra.rs b/apps/desktop-gpui/kernels/src/camera_bgra.rs new file mode 100644 index 00000000000..f9fe73b7e2a --- /dev/null +++ b/apps/desktop-gpui/kernels/src/camera_bgra.rs @@ -0,0 +1,891 @@ +//! Even-width 1:1 YUYV, UYVY, and NV12 to BGRA for the non-macOS camera preview. +//! +//! The 8.8 gains match `cap_rendering::cpu_yuv`, which this crate does not call: +//! that crate depends on the renderer, writes RGBA, and does not sample packed +//! 4:2:2 or swscale's quantized NV12 vertical filter. Odd widths return `None` +//! so the preview keeps swscale, which resamples that chroma. The pair loop is +//! autovectorized (SSE4.1 or AVX2 on x86, NEON on aarch64). x86 without SSE4.1 +//! stays on swscale: its SSE2 loop loses to swscale on 720p NV12. + +use std::mem::MaybeUninit; +use std::sync::OnceLock; + +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +use std::arch::is_x86_feature_detected; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Packed422 { + Yuyv, + Uyvy, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Level { + Portable, + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + Sse41, + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + Avx2, + /// x86 with neither SSE4.1 nor AVX2. The public API returns `None`. + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + Swscale, +} + +pub fn simd_path() -> &'static str { + match level() { + Level::Portable => "portable", + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + Level::Sse41 => "sse4.1", + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + Level::Avx2 => "avx2", + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + Level::Swscale => "swscale", + } +} + +pub fn packed422_to_bgra( + data: &[u8], + width: usize, + height: usize, + stride: usize, + format: Packed422, + mirrored: bool, +) -> Option> { + if width == 0 || height == 0 || !width.is_multiple_of(2) { + return None; + } + let sample_bytes = width * 2; + if stride < sample_bytes { + return None; + } + let plane_len = stride.checked_mul(height)?; + if data.len() < plane_len || !kernel_enabled() { + return None; + } + let output_len = width.checked_mul(4)?.checked_mul(height)?; + Some(alloc_filled(output_len, |pixels| { + dispatch_packed(data, pixels, width, height, stride, format, mirrored); + })) +} + +pub fn nv12_to_bgra( + y: &[u8], + uv: &[u8], + width: usize, + height: usize, + y_stride: usize, + uv_stride: usize, + mirrored: bool, +) -> Option> { + if width == 0 || height == 0 || !width.is_multiple_of(2) { + return None; + } + let uv_rows = height.div_ceil(2); + if y_stride < width || uv_stride < width { + return None; + } + let y_plane = y_stride.checked_mul(height)?; + let uv_plane = uv_stride.checked_mul(uv_rows)?; + if y.len() < y_plane || uv.len() < uv_plane || !kernel_enabled() { + return None; + } + let output_len = width.checked_mul(4)?.checked_mul(height)?; + Some(alloc_filled(output_len, |pixels| { + dispatch_nv12( + Nv12Planes { + y, + uv, + y_stride, + uv_stride, + }, + pixels, + width, + height, + mirrored, + ); + })) +} + +struct Nv12Planes<'a> { + y: &'a [u8], + uv: &'a [u8], + y_stride: usize, + uv_stride: usize, +} + +fn dispatch_packed( + data: &[u8], + pixels: &mut [MaybeUninit], + width: usize, + height: usize, + stride: usize, + format: Packed422, + mirrored: bool, +) { + match level() { + Level::Portable => write_packed_rows(data, pixels, width, height, stride, format, mirrored), + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + Level::Sse41 => unsafe { + // SAFETY: `level` is `Sse41` only after `is_x86_feature_detected!("sse4.1")`. + write_packed_sse41(data, pixels, width, height, stride, format, mirrored); + }, + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + Level::Avx2 => unsafe { + // SAFETY: `level` is `Avx2` only after `is_x86_feature_detected!("avx2")`. + write_packed_avx2(data, pixels, width, height, stride, format, mirrored); + }, + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + Level::Swscale => write_packed_rows(data, pixels, width, height, stride, format, mirrored), + } +} + +fn dispatch_nv12( + planes: Nv12Planes<'_>, + pixels: &mut [MaybeUninit], + width: usize, + height: usize, + mirrored: bool, +) { + match level() { + Level::Portable => write_nv12_rows(planes, pixels, width, height, mirrored), + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + Level::Sse41 => unsafe { + // SAFETY: `level` is `Sse41` only after `is_x86_feature_detected!("sse4.1")`. + write_nv12_sse41(planes, pixels, width, height, mirrored); + }, + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + Level::Avx2 => unsafe { + // SAFETY: `level` is `Avx2` only after `is_x86_feature_detected!("avx2")`. + write_nv12_avx2(planes, pixels, width, height, mirrored); + }, + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + Level::Swscale => write_nv12_rows(planes, pixels, width, height, mirrored), + } +} + +fn level() -> Level { + static LEVEL: OnceLock = OnceLock::new(); + *LEVEL.get_or_init(detect) +} + +fn kernel_enabled() -> bool { + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + { + !matches!(level(), Level::Swscale) + } + #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))] + { + true + } +} + +fn detect() -> Level { + if let Ok(choice) = std::env::var("CAP_CAMERA_BGRA_SIMD") { + match choice.as_str() { + "portable" | "sse2" => return Level::Portable, + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + "swscale" => return Level::Swscale, + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + "sse4.1" | "sse41" if is_x86_feature_detected!("sse4.1") => return Level::Sse41, + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + "avx2" if is_x86_feature_detected!("avx2") => return Level::Avx2, + _ => {} + } + } + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + { + if is_x86_feature_detected!("avx2") { + return Level::Avx2; + } + if is_x86_feature_detected!("sse4.1") { + return Level::Sse41; + } + Level::Swscale + } + #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))] + Level::Portable +} + +fn alloc_filled(output_len: usize, fill: impl FnOnce(&mut [MaybeUninit])) -> Vec { + let mut pixels = Vec::with_capacity(output_len); + fill(&mut pixels.spare_capacity_mut()[..output_len]); + // SAFETY: `fill` writes every element of this spare prefix before `set_len`. + unsafe { pixels.set_len(output_len) } + pixels +} + +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +#[target_feature(enable = "sse4.1")] +unsafe fn write_packed_sse41( + data: &[u8], + pixels: &mut [MaybeUninit], + width: usize, + height: usize, + stride: usize, + format: Packed422, + mirrored: bool, +) { + write_packed_rows(data, pixels, width, height, stride, format, mirrored); +} + +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +#[target_feature(enable = "sse4.1")] +unsafe fn write_nv12_sse41( + planes: Nv12Planes<'_>, + pixels: &mut [MaybeUninit], + width: usize, + height: usize, + mirrored: bool, +) { + write_nv12_rows(planes, pixels, width, height, mirrored); +} + +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +#[target_feature(enable = "avx2")] +unsafe fn write_packed_avx2( + data: &[u8], + pixels: &mut [MaybeUninit], + width: usize, + height: usize, + stride: usize, + format: Packed422, + mirrored: bool, +) { + write_packed_rows(data, pixels, width, height, stride, format, mirrored); +} + +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +#[target_feature(enable = "avx2")] +unsafe fn write_nv12_avx2( + planes: Nv12Planes<'_>, + pixels: &mut [MaybeUninit], + width: usize, + height: usize, + mirrored: bool, +) { + write_nv12_rows(planes, pixels, width, height, mirrored); +} + +#[inline(always)] +fn write_packed_rows( + data: &[u8], + pixels: &mut [MaybeUninit], + width: usize, + height: usize, + stride: usize, + format: Packed422, + mirrored: bool, +) { + let sample_bytes = width * 2; + let row_bytes = width * 4; + for row in 0..height { + let src = &data[row * stride..row * stride + sample_bytes]; + let dst = &mut pixels[row * row_bytes..(row + 1) * row_bytes]; + match (format, mirrored) { + (Packed422::Yuyv, false) => packed_pairs::(src, dst), + (Packed422::Yuyv, true) => packed_pairs::(src, dst), + (Packed422::Uyvy, false) => packed_pairs::(src, dst), + (Packed422::Uyvy, true) => packed_pairs::(src, dst), + } + } +} + +#[inline(always)] +fn write_nv12_rows( + planes: Nv12Planes<'_>, + pixels: &mut [MaybeUninit], + width: usize, + height: usize, + mirrored: bool, +) { + let row_bytes = width * 4; + for row in 0..height { + let (uv_index, blend) = vertical_tap(row, height); + let y_row = &planes.y[row * planes.y_stride..row * planes.y_stride + width]; + let uv_at = uv_index * planes.uv_stride; + let uv_row = &planes.uv[uv_at..uv_at + width]; + let uv_next = if blend { + let next = uv_at + planes.uv_stride; + &planes.uv[next..next + width] + } else { + uv_row + }; + let dst = &mut pixels[row * row_bytes..(row + 1) * row_bytes]; + if mirrored { + if blend { + nv12_pairs::(y_row, uv_row, uv_next, dst); + } else { + nv12_pairs::(y_row, uv_row, uv_next, dst); + } + } else if blend { + nv12_pairs::(y_row, uv_row, uv_next, dst); + } else { + nv12_pairs::(y_row, uv_row, uv_next, dst); + } + } +} + +#[inline(always)] +fn packed_pairs(src: &[u8], dst: &mut [MaybeUninit]) { + debug_assert!(src.len().is_multiple_of(4)); + debug_assert_eq!(dst.len(), src.len() * 2); + let (src_pairs, _) = src.as_chunks::<4>(); + let (dst_pairs, _) = dst.as_chunks_mut::<8>(); + if MIRROR { + for (sample, pixel) in src_pairs.iter().zip(dst_pairs.iter_mut().rev()) { + write_packed_pair::(sample, pixel); + } + } else { + for (sample, pixel) in src_pairs.iter().zip(dst_pairs.iter_mut()) { + write_packed_pair::(sample, pixel); + } + } +} + +#[inline(always)] +fn write_packed_pair( + sample: &[u8; 4], + pixel: &mut [MaybeUninit; 8], +) { + let (y0, cb, y1, cr) = if YUYV { + (sample[0], sample[1], sample[2], sample[3]) + } else { + (sample[1], sample[0], sample[3], sample[2]) + }; + let l0 = 298 * (i32::from(y0) - 16); + let l1 = 298 * (i32::from(y1) - 16); + let cb = i32::from(cb) - 128; + let cr = i32::from(cr) - 128; + if MIRROR { + store_bgra(pixel, l1, l0, cb, cr); + } else { + store_bgra(pixel, l0, l1, cb, cr); + } +} + +#[inline(always)] +fn nv12_pairs( + y: &[u8], + uv0: &[u8], + uv1: &[u8], + dst: &mut [MaybeUninit], +) { + debug_assert!(y.len().is_multiple_of(2)); + debug_assert!(uv0.len() >= y.len()); + debug_assert!(!BLEND || uv1.len() >= y.len()); + debug_assert_eq!(dst.len(), y.len() * 4); + let (lumas, _) = y.as_chunks::<2>(); + let (chroma0, _) = uv0.as_chunks::<2>(); + let (chroma1, _) = uv1.as_chunks::<2>(); + let (pixels, _) = dst.as_chunks_mut::<8>(); + if MIRROR { + for (((luma, c0), c1), pixel) in lumas + .iter() + .zip(chroma0) + .zip(chroma1) + .zip(pixels.iter_mut().rev()) + { + write_nv12_pair::(luma, c0, c1, pixel); + } + } else { + for (((luma, c0), c1), pixel) in lumas.iter().zip(chroma0).zip(chroma1).zip(pixels) { + write_nv12_pair::(luma, c0, c1, pixel); + } + } +} + +#[inline(always)] +fn write_nv12_pair( + luma: &[u8; 2], + chroma0: &[u8; 2], + chroma1: &[u8; 2], + pixel: &mut [MaybeUninit; 8], +) { + let (cb, cr) = if BLEND { + ( + i32::from(avg_u8(chroma0[0], chroma1[0])) - 128, + i32::from(avg_u8(chroma0[1], chroma1[1])) - 128, + ) + } else { + (i32::from(chroma0[0]) - 128, i32::from(chroma0[1]) - 128) + }; + let l0 = 298 * (i32::from(luma[0]) - 16); + let l1 = 298 * (i32::from(luma[1]) - 16); + if MIRROR { + store_bgra(pixel, l1, l0, cb, cr); + } else { + store_bgra(pixel, l0, l1, cb, cr); + } +} + +#[inline(always)] +fn store_bgra(pixel: &mut [MaybeUninit; 8], l0: i32, l1: i32, cb: i32, cr: i32) { + let bytes = [ + clamp8((l0 + 516 * cb + 128) >> 8), + clamp8((l0 - 100 * cb - 208 * cr + 128) >> 8), + clamp8((l0 + 409 * cr + 128) >> 8), + 255, + clamp8((l1 + 516 * cb + 128) >> 8), + clamp8((l1 - 100 * cb - 208 * cr + 128) >> 8), + clamp8((l1 + 409 * cr + 128) >> 8), + 255, + ]; + // SAFETY: `pixel` is eight bytes. `bytes` is initialized, so this store + // initializes the whole array. The caller `set_len`s only after every pixel. + unsafe { + pixel.as_mut_ptr().cast::<[u8; 8]>().write(bytes); + } +} + +#[cfg(test)] +fn bt601_bgra(y: u8, cb: u8, cr: u8) -> [u8; 4] { + let mut pixel = [MaybeUninit::uninit(); 8]; + let luma = 298 * (i32::from(y) - 16); + store_bgra( + &mut pixel, + luma, + luma, + i32::from(cb) - 128, + i32::from(cr) - 128, + ); + // SAFETY: `store_bgra` writes all eight elements. + let pixel = unsafe { pixel.map(|byte| byte.assume_init()) }; + [pixel[0], pixel[1], pixel[2], pixel[3]] +} + +#[inline(always)] +fn clamp8(value: i32) -> u8 { + value.clamp(0, 255) as u8 +} + +#[inline(always)] +fn avg_u8(a: u8, b: u8) -> u8 { + ((u16::from(a) + u16::from(b) + 1) >> 1) as u8 +} + +// swscale's packed-BGRA bilinear, collapsed to one chroma row or a rounded +// average of two. The preview parity test is what notices if this drifts. +fn vertical_tap(y: usize, height: usize) -> (usize, bool) { + let src_h = height.div_ceil(2); + let x_inc = (((src_h as u64) << 16) + ((height as u64) >> 1)) / (height as u64); + let filter_size = src_h.saturating_sub(2).clamp(1, 3); + let x = (x_inc as i64 - 65_536) + (y as i64) * (2 * x_inc as i64); + let mut pos = (x - (filter_size as i64 - 2) * 65_536) / (1 << 17); + let mut coeffs = [0i64; 3]; + let mut count = 0usize; + for sample in pos..pos + filter_size as i64 { + let delta = sample * (1i64 << 17) - x; + let mut coeff = (1i64 << 30) - (delta.abs() << 13); + if coeff < 0 { + coeff = 0; + } + coeffs[count] = coeff; + count += 1; + } + let cutoff = (1i64 << 30) / 500; + while count > 1 && coeffs[0] <= cutoff { + coeffs.copy_within(1..count, 0); + count -= 1; + pos += 1; + } + while count > 1 && coeffs[count - 1] <= cutoff { + count -= 1; + } + if src_h <= 3 { + return (pos.clamp(0, src_h as i64 - 1) as usize, false); + } + let mut pair = [coeffs[0], if count > 1 { coeffs[1] } else { 0 }]; + if pos < 0 { + pos = 0; + } + if pos + 2 > src_h as i64 { + let shift = pos + (2 - src_h as i64).min(0); + let mut acc = 0i64; + let mut tmp = pair; + for index in (0..2).rev() { + if pos + index as i64 >= src_h as i64 { + acc += tmp[index]; + tmp[index] = 0; + } + } + let mut shifted = [0i64; 2]; + for index in (0..2).rev() { + if index as i64 >= shift { + shifted[index] = tmp[(index as i64 - shift) as usize]; + } + } + pos -= shift; + let edge = src_h as i64 - 1 - pos; + if (0..2).contains(&edge) { + shifted[edge as usize] += acc; + } + pair = shifted; + } + let pos = pos.clamp(0, src_h as i64 - 1); + let total = pair[0] + pair[1]; + let norm = ((total + 2048) / 4096).max(1); + let second = if pair[1] > 0 { + (pair[1] + (norm >> 1)) / norm + } else { + (pair[1] - (norm >> 1)) / norm + }; + (pos as usize, second >= 2048) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn pattern(len: usize, seed: u32) -> Vec { + let mut state = seed; + (0..len) + .map(|_| { + state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + (state >> 24) as u8 + }) + .collect() + } + + fn padded_rows(sample_bytes: usize, stride: usize, height: usize, seed: u32) -> Vec { + let mut data = vec![0xA5; stride * height]; + let samples = pattern(sample_bytes * height, seed); + for row in 0..height { + let start = row * stride; + data[start..start + sample_bytes] + .copy_from_slice(&samples[row * sample_bytes..(row + 1) * sample_bytes]); + } + data + } + + fn levels() -> Vec { + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + { + let mut levels = vec![Level::Portable]; + if is_x86_feature_detected!("sse4.1") { + levels.push(Level::Sse41); + } + if is_x86_feature_detected!("avx2") { + levels.push(Level::Avx2); + } + levels + } + #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))] + { + vec![Level::Portable] + } + } + + fn convert_packed( + data: &[u8], + width: usize, + height: usize, + stride: usize, + format: Packed422, + mirrored: bool, + level: Level, + ) -> Vec { + alloc_filled(width * 4 * height, |pixels| match level { + Level::Portable => { + write_packed_rows(data, pixels, width, height, stride, format, mirrored); + } + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + Level::Sse41 => unsafe { + // SAFETY: `levels` only yields `Sse41` after `is_x86_feature_detected!("sse4.1")`. + write_packed_sse41(data, pixels, width, height, stride, format, mirrored); + }, + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + Level::Avx2 => unsafe { + // SAFETY: `levels` only yields `Avx2` after `is_x86_feature_detected!("avx2")`. + write_packed_avx2(data, pixels, width, height, stride, format, mirrored); + }, + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + Level::Swscale => { + write_packed_rows(data, pixels, width, height, stride, format, mirrored); + } + }) + } + + fn convert_nv12( + y: &[u8], + uv: &[u8], + width: usize, + height: usize, + strides: (usize, usize), + level: Level, + mirrored: bool, + ) -> Vec { + alloc_filled(width * 4 * height, |pixels| { + let planes = Nv12Planes { + y, + uv, + y_stride: strides.0, + uv_stride: strides.1, + }; + match level { + Level::Portable => write_nv12_rows(planes, pixels, width, height, mirrored), + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + Level::Sse41 => unsafe { + // SAFETY: `levels` only yields `Sse41` after `is_x86_feature_detected!("sse4.1")`. + write_nv12_sse41(planes, pixels, width, height, mirrored); + }, + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + Level::Avx2 => unsafe { + // SAFETY: `levels` only yields `Avx2` after `is_x86_feature_detected!("avx2")`. + write_nv12_avx2(planes, pixels, width, height, mirrored); + }, + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + Level::Swscale => write_nv12_rows(planes, pixels, width, height, mirrored), + } + }) + } + + fn mirror_rows(pixels: &mut [u8], width: usize) { + let row_bytes = width * 4; + for row in pixels.chunks_mut(row_bytes) { + let (pixels, _) = row.as_chunks_mut::<4>(); + pixels.reverse(); + } + } + + fn assert_packed(format: Packed422, width: usize, height: usize, stride: usize) { + let sample_bytes = width * 2; + let data = padded_rows(sample_bytes, stride, height, 0x1234_0000 | width as u32); + let portable = convert_packed(&data, width, height, stride, format, false, Level::Portable); + for level in levels() { + let pixels = convert_packed(&data, width, height, stride, format, false, level); + assert_eq!(pixels, portable, "{format:?} {width}x{height} {level:?}"); + let mirrored = convert_packed(&data, width, height, stride, format, true, level); + let mut expected = portable.clone(); + mirror_rows(&mut expected, width); + assert_eq!(mirrored, expected, "{format:?} mirrored {level:?}"); + } + let straight = packed422_to_bgra(&data, width, height, stride, format, false); + let mirrored = packed422_to_bgra(&data, width, height, stride, format, true); + if simd_path() == "swscale" { + assert!(straight.is_none()); + assert!(mirrored.is_none()); + } else { + assert_eq!(straight.unwrap(), portable); + let mut expected = portable; + mirror_rows(&mut expected, width); + assert_eq!(mirrored.unwrap(), expected); + } + } + + fn assert_nv12(width: usize, height: usize, y_stride: usize, uv_stride: usize) { + let uv_rows = height.div_ceil(2); + let y = padded_rows(width, y_stride, height, 7); + let uv = padded_rows(width, uv_stride, uv_rows, 11); + let strides = (y_stride, uv_stride); + let portable = convert_nv12(&y, &uv, width, height, strides, Level::Portable, false); + for level in levels() { + let pixels = convert_nv12(&y, &uv, width, height, strides, level, false); + assert_eq!(pixels, portable, "nv12 {width}x{height} {level:?}"); + let mirrored = convert_nv12(&y, &uv, width, height, strides, level, true); + let mut expected = portable.clone(); + mirror_rows(&mut expected, width); + assert_eq!(mirrored, expected, "nv12 mirrored {level:?}"); + } + let public = nv12_to_bgra(&y, &uv, width, height, y_stride, uv_stride, false); + let mirrored = nv12_to_bgra(&y, &uv, width, height, y_stride, uv_stride, true); + if simd_path() == "swscale" { + assert!(public.is_none()); + assert!(mirrored.is_none()); + } else { + assert_eq!(public.unwrap(), portable); + let mut expected = portable; + mirror_rows(&mut expected, width); + assert_eq!(mirrored.unwrap(), expected); + } + } + + #[test] + fn limited_range_grey_axis_is_exact() { + assert_eq!(bt601_bgra(16, 128, 128), [0, 0, 0, 255]); + assert_eq!(bt601_bgra(235, 128, 128), [255, 255, 255, 255]); + assert_eq!(bt601_bgra(128, 128, 128), [130, 130, 130, 255]); + assert_eq!(bt601_bgra(128, 16, 240), [0, 83, 255, 255]); + } + + #[test] + fn odd_widths_are_left_to_swscale() { + let yuyv = [16u8, 128, 235, 128, 16, 128, 0, 0]; + assert!(packed422_to_bgra(&yuyv, 3, 1, 8, Packed422::Yuyv, false).is_none()); + assert!(packed422_to_bgra(&yuyv, 3, 1, 8, Packed422::Uyvy, true).is_none()); + assert!(nv12_to_bgra(&[128, 128, 128], &[128, 128], 3, 2, 3, 4, false).is_none()); + } + + #[test] + fn packed_formats_match_across_simd_paths_and_padded_strides() { + for format in [Packed422::Yuyv, Packed422::Uyvy] { + for (width, height, stride) in [(2, 2, 4), (8, 1, 16), (16, 2, 40), (30, 5, 64)] { + assert_packed(format, width, height, stride); + } + } + } + + fn vstep_planes(width: usize, height: usize) -> (Vec, Vec) { + let y = vec![128u8; width * height]; + let mut uv = vec![0u8; width * height.div_ceil(2)]; + for row in 0..height.div_ceil(2) { + let (cb, cr) = if row.is_multiple_of(2) { + (16, 240) + } else { + (240, 16) + }; + for col in (0..width).step_by(2) { + let index = row * width + col; + uv[index] = cb; + uv[index + 1] = cr; + } + } + (y, uv) + } + + fn assert_row_color(pixels: &[u8], width: usize, row: usize, expected: [u8; 4]) { + let start = row * width * 4; + let (row_pixels, rest) = pixels[start..start + width * 4].as_chunks::<4>(); + assert!(rest.is_empty()); + for pixel in row_pixels { + assert_eq!(*pixel, expected, "row {row}"); + } + } + + #[test] + fn nv12_vertical_chroma_follows_swscale_bilinear_taps() { + assert_eq!( + (0..8).map(|y| vertical_tap(y, 8)).collect::>(), + vec![ + (0, false), + (0, false), + (0, true), + (1, false), + (1, true), + (2, false), + (2, true), + (2, true), + ] + ); + assert_eq!( + (0..6).map(|y| vertical_tap(y, 6)).collect::>(), + vec![ + (0, false), + (0, false), + (1, false), + (1, false), + (2, false), + (2, false) + ] + ); + assert_eq!(vertical_tap(0, 3), (0, false)); + assert_eq!(vertical_tap(1, 3), (1, false)); + assert_eq!(vertical_tap(2, 3), (1, false)); + assert_eq!(vertical_tap(0, 1080), (0, false)); + assert_eq!(vertical_tap(1, 1080), (0, false)); + assert_eq!(vertical_tap(2, 1080), (0, true)); + assert_eq!(vertical_tap(1076, 1080), (537, true)); + assert_eq!(vertical_tap(1077, 1080), (538, false)); + assert_eq!(vertical_tap(1078, 1080), (538, true)); + assert_eq!(vertical_tap(1079, 1080), (538, true)); + + let pure_a = [0, 83, 255, 255]; + let pure_b = [255, 178, 0, 255]; + let mixed = [130, 130, 130, 255]; + let (y, uv) = vstep_planes(16, 8); + let public = nv12_to_bgra(&y, &uv, 16, 8, 16, 16, false); + let pixels = if simd_path() == "swscale" { + assert!(public.is_none()); + convert_nv12(&y, &uv, 16, 8, (16, 16), Level::Portable, false) + } else { + public.unwrap() + }; + for (row, color) in [pure_a, pure_a, mixed, pure_b, mixed, pure_a, mixed, mixed] + .into_iter() + .enumerate() + { + assert_row_color(&pixels, 16, row, color); + } + for level in levels() { + let got = convert_nv12(&y, &uv, 16, 8, (16, 16), level, false); + assert_eq!(got, pixels, "{level:?}"); + } + + let (y, uv) = vstep_planes(8, 6); + let public = nv12_to_bgra(&y, &uv, 8, 6, 8, 8, false); + let nearest = if simd_path() == "swscale" { + assert!(public.is_none()); + convert_nv12(&y, &uv, 8, 6, (8, 8), Level::Portable, false) + } else { + public.unwrap() + }; + for (row, color) in [pure_a, pure_a, pure_b, pure_b, pure_a, pure_a] + .into_iter() + .enumerate() + { + assert_row_color(&nearest, 8, row, color); + } + + let (y, uv) = vstep_planes(8, 9); + let odd_height = nv12_to_bgra(&y, &uv, 8, 9, 8, 8, true); + let straight = nv12_to_bgra(&y, &uv, 8, 9, 8, 8, false); + if simd_path() == "swscale" { + assert!(odd_height.is_none()); + assert!(straight.is_none()); + let straight = convert_nv12(&y, &uv, 8, 9, (8, 8), Level::Portable, false); + let odd_height = convert_nv12(&y, &uv, 8, 9, (8, 8), Level::Portable, true); + let mut expected = straight; + mirror_rows(&mut expected, 8); + assert_eq!(odd_height, expected); + } else { + let mut expected = straight.unwrap(); + mirror_rows(&mut expected, 8); + assert_eq!(odd_height.unwrap(), expected); + } + } + + #[test] + fn nv12_matches_across_simd_paths_and_padded_strides() { + for (width, height, y_stride, uv_stride) in + [(2, 2, 8, 8), (8, 4, 8, 8), (16, 8, 32, 16), (14, 9, 32, 32)] + { + assert_nv12(width, height, y_stride, uv_stride); + } + } + + #[test] + fn short_or_empty_planes_are_rejected() { + assert!(packed422_to_bgra(&[0; 8], 0, 2, 4, Packed422::Yuyv, false).is_none()); + assert!(packed422_to_bgra(&[0; 4], 2, 2, 4, Packed422::Yuyv, false).is_none()); + assert!(packed422_to_bgra(&[0; 8], 3, 1, 4, Packed422::Uyvy, false).is_none()); + assert!(nv12_to_bgra(&[0; 8], &[0; 2], 2, 4, 2, 2, false).is_none()); + assert!(nv12_to_bgra(&[16, 16], &[128, 128], 2, 1, 1, 2, false).is_none()); + } + + #[test] + fn padding_bytes_do_not_change_active_pixels() { + let tight_data = [16, 128, 235, 128]; + let mut padded = vec![0xA5; 16]; + padded[..4].copy_from_slice(&tight_data); + let tight = convert_packed( + &tight_data, + 2, + 1, + 4, + Packed422::Yuyv, + false, + Level::Portable, + ); + let wide = convert_packed(&padded, 2, 1, 16, Packed422::Yuyv, false, Level::Portable); + assert_eq!(tight, [0, 0, 0, 255, 255, 255, 255, 255]); + assert_eq!(wide, tight); + let public_tight = packed422_to_bgra(&tight_data, 2, 1, 4, Packed422::Yuyv, false); + let public_wide = packed422_to_bgra(&padded, 2, 1, 16, Packed422::Yuyv, false); + if simd_path() == "swscale" { + assert!(public_tight.is_none()); + assert!(public_wide.is_none()); + } else { + assert_eq!(public_tight.unwrap(), tight); + assert_eq!(public_wide.unwrap(), tight); + } + } +} diff --git a/apps/desktop-gpui/kernels/src/lib.rs b/apps/desktop-gpui/kernels/src/lib.rs index 3971ea2da35..01ecec6b7f4 100644 --- a/apps/desktop-gpui/kernels/src/lib.rs +++ b/apps/desktop-gpui/kernels/src/lib.rs @@ -1,3 +1,4 @@ +pub mod camera_bgra; pub mod codec; pub mod frame; pub mod mask_cache; diff --git a/apps/desktop-gpui/src/feeds.rs b/apps/desktop-gpui/src/feeds.rs index c8333393972..fa9ed8635a2 100644 --- a/apps/desktop-gpui/src/feeds.rs +++ b/apps/desktop-gpui/src/feeds.rs @@ -1489,6 +1489,15 @@ pub(crate) fn camera_preview_image( None => return None, }; + // Even-width 1:1 YUYV, UYVY, and NV12. Odd widths stay here: swscale + // resamples that chroma, and the kernel does not. + if width == source_width + && height == source_height + && let Some(pixels) = bt601_preview_bgra(frame, mirrored) + { + return bgra_preview_image(pixels, width, height); + } + let mut converted = ffmpeg::frame::Video::empty(); let source = if frame.format() == ffmpeg::format::Pixel::BGRA && width == source_width @@ -1530,11 +1539,56 @@ pub(crate) fn camera_preview_image( height, mirrored, )?; - let image = image::RgbaImage::from_raw(width as u32, height as u32, pixels)?; + bgra_preview_image(pixels, width as u32, height as u32) +} + +#[cfg(any(not(target_os = "macos"), test))] +fn bt601_preview_bgra(frame: &ffmpeg::frame::Video, mirrored: bool) -> Option> { + use cap_gpui_kernels::camera_bgra::{self, Packed422}; + + let width = frame.width() as usize; + let height = frame.height() as usize; + match frame.format() { + ffmpeg::format::Pixel::YUYV422 => camera_bgra::packed422_to_bgra( + frame.data(0), + width, + height, + frame.stride(0), + Packed422::Yuyv, + mirrored, + ), + ffmpeg::format::Pixel::UYVY422 => camera_bgra::packed422_to_bgra( + frame.data(0), + width, + height, + frame.stride(0), + Packed422::Uyvy, + mirrored, + ), + ffmpeg::format::Pixel::NV12 => camera_bgra::nv12_to_bgra( + frame.data(0), + frame.data(1), + width, + height, + frame.stride(0), + frame.stride(1), + mirrored, + ), + _ => None, + } +} + +#[cfg(any(not(target_os = "macos"), test))] +fn bgra_preview_image( + pixels: Vec, + width: u32, + height: u32, +) -> Option<(Arc, (usize, usize))> { + let image = image::RgbaImage::from_raw(width, height, pixels)?; let image = Arc::new(gpui::RenderImage::new(smallvec::smallvec![ image::Frame::new(image) ])); - Some((image, (width, height))) + Some((image, (width as usize, height as usize))) } /// The quietest level any meter draws: `bar_level` bottoms out at -60 dB and @@ -2346,6 +2400,468 @@ mod tests { camera_preview_image(&frame, &mut scaler, false, Some((16, 16))).unwrap(); assert_eq!(recapped, (16, 8)); } + + fn preview_uses_kernel() -> bool { + cap_gpui_kernels::camera_bgra::simd_path() != "swscale" + } + + fn assert_preview_scaler(scaler: &Option) { + if preview_uses_kernel() { + assert!(scaler.is_none()); + } else { + assert!(scaler.is_some()); + } + } + + fn assert_preview_bytes(bytes: &[u8], expected: &[u8]) { + if preview_uses_kernel() { + assert_eq!(bytes, expected); + return; + } + assert_eq!(bytes.len(), expected.len()); + let gap = bytes + .iter() + .zip(expected) + .map(|(got, expected)| got.abs_diff(*expected)) + .max() + .unwrap_or(0); + assert!(gap <= 3, "{bytes:?}"); + } + + #[test] + fn camera_preview_converts_packed_422_and_nv12_without_swscale() { + let mut yuyv = ffmpeg::frame::Video::new(ffmpeg::format::Pixel::YUYV422, 2, 1); + yuyv.data_mut(0)[..4].copy_from_slice(&[16, 128, 235, 128]); + let mut scaler = None; + let (image, dims) = camera_preview_image(&yuyv, &mut scaler, false, None).unwrap(); + assert_eq!(dims, (2, 1)); + assert_preview_scaler(&scaler); + assert_preview_bytes( + image.as_bytes(0).unwrap(), + &[0, 0, 0, 255, 255, 255, 255, 255], + ); + + let (mirrored, _) = camera_preview_image(&yuyv, &mut scaler, true, None).unwrap(); + assert_preview_scaler(&scaler); + assert_preview_bytes( + mirrored.as_bytes(0).unwrap(), + &[255, 255, 255, 255, 0, 0, 0, 255], + ); + + let mut uyvy = ffmpeg::frame::Video::new(ffmpeg::format::Pixel::UYVY422, 2, 1); + uyvy.data_mut(0)[..4].copy_from_slice(&[128, 16, 128, 235]); + let (image, _) = camera_preview_image(&uyvy, &mut scaler, false, None).unwrap(); + assert_preview_scaler(&scaler); + assert_preview_bytes( + image.as_bytes(0).unwrap(), + &[0, 0, 0, 255, 255, 255, 255, 255], + ); + + let mut nv12 = ffmpeg::frame::Video::new(ffmpeg::format::Pixel::NV12, 2, 2); + let y_stride = nv12.stride(0); + nv12.data_mut(0)[..2].copy_from_slice(&[128, 128]); + nv12.data_mut(0)[y_stride..y_stride + 2].copy_from_slice(&[128, 128]); + nv12.data_mut(1)[..2].copy_from_slice(&[128, 128]); + let (image, dims) = camera_preview_image(&nv12, &mut scaler, false, None).unwrap(); + assert_eq!(dims, (2, 2)); + assert_preview_scaler(&scaler); + assert_preview_bytes(image.as_bytes(0).unwrap(), &[130, 130, 130, 255].repeat(4)); + } + + #[test] + fn preview_stays_within_three_codes_of_swscale_bilinear() { + if !preview_uses_kernel() { + for pixel in [ + ffmpeg::format::Pixel::YUYV422, + ffmpeg::format::Pixel::UYVY422, + ffmpeg::format::Pixel::NV12, + ] { + let frame = ffmpeg::frame::Video::new(pixel, 16, 8); + let mut scaler = None; + let (_, dims) = camera_preview_image(&frame, &mut scaler, false, None).unwrap(); + assert_eq!(dims, (16, 8)); + assert!(scaler.is_some(), "{pixel:?}"); + let (_, mirrored) = camera_preview_image(&frame, &mut scaler, true, None).unwrap(); + assert_eq!(mirrored, (16, 8)); + assert!(scaler.is_some(), "{pixel:?} mirrored"); + } + assert!(nv12_gap_vs_swscale(16, 8, false, Nv12Pattern::VerticalStep).is_none()); + assert!(packed_gap_vs_swscale(ffmpeg::format::Pixel::YUYV422, 16, 8, false).is_none()); + return; + } + expect_gap_at_most_3( + nv12_gap_vs_swscale(128, 16, false, Nv12Pattern::HighFrequency), + "nv12 128x16 high frequency", + ); + expect_gap_at_most_3( + nv12_gap_vs_swscale(16, 8, false, Nv12Pattern::VerticalStep), + "nv12 16x8 vertical step", + ); + expect_gap_at_most_3( + nv12_gap_vs_swscale(64, 32, false, Nv12Pattern::Smooth), + "nv12 64x32 smooth", + ); + expect_gap_at_most_3( + nv12_gap_vs_swscale(1920, 8, false, Nv12Pattern::HighFrequency), + "nv12 1920x8 high frequency", + ); + expect_gap_at_most_3( + nv12_gap_vs_swscale(128, 15, false, Nv12Pattern::HighFrequency), + "nv12 128x15 high frequency", + ); + expect_gap_at_most_3( + nv12_gap_vs_swscale(64, 32, true, Nv12Pattern::HighFrequency), + "nv12 64x32 high frequency mirrored", + ); + expect_gap_at_most_3( + nv12_gap_vs_swscale(16, 9, true, Nv12Pattern::VerticalStep), + "nv12 16x9 vertical step mirrored", + ); + expect_gap_at_most_3( + packed_gap_vs_swscale(ffmpeg::format::Pixel::YUYV422, 128, 16, false), + "yuyv 128x16", + ); + expect_gap_at_most_3( + packed_gap_vs_swscale(ffmpeg::format::Pixel::YUYV422, 128, 15, true), + "yuyv 128x15 mirrored", + ); + expect_gap_at_most_3( + packed_gap_vs_swscale(ffmpeg::format::Pixel::UYVY422, 64, 32, true), + "uyvy 64x32 mirrored", + ); + } + + fn expect_gap_at_most_3(gap: Option, what: &str) { + expect_gap_at_most(gap, 3, what); + } + + fn expect_gap_at_most(gap: Option, limit: u8, what: &str) { + let gap = gap.unwrap_or_else(|| panic!("{what}: kernel unavailable")); + assert!(gap <= limit, "{what} gap {gap}"); + } + + /// `ff_nv12_to_bgra_neon` repeats each chroma row for two luma rows. With + /// the kernel's coefficients that is 41 codes on the Smooth pattern and 42 + /// against `SWS_POINT` at 1920x8; a vertical gradient stays at 3. Packed + /// 4:2:2 is not that converter, and its bilinear gap is already 3. + #[cfg(target_arch = "aarch64")] + const NEON_SMOOTH_GAP: u8 = 42; + + #[cfg(target_arch = "aarch64")] + #[test] + fn preview_stays_near_the_neon_swscale_path() { + expect_gap_at_most( + nv12_gap_vs_native_swscale(64, 32, false, Nv12Pattern::Smooth), + NEON_SMOOTH_GAP, + "nv12 64x32 smooth neon", + ); + expect_gap_at_most( + nv12_gap_vs_native_swscale(1920, 8, false, Nv12Pattern::Smooth), + NEON_SMOOTH_GAP, + "nv12 1920x8 smooth neon", + ); + expect_gap_at_most_3( + gradient_nv12_gap_vs_native_swscale(64, 32), + "nv12 64x32 gradient neon", + ); + expect_gap_at_most_3( + packed_ramp_gap_vs_native_swscale(ffmpeg::format::Pixel::YUYV422, 128, 32), + "yuyv 128x32 ramp neon", + ); + expect_gap_at_most_3( + packed_ramp_gap_vs_native_swscale(ffmpeg::format::Pixel::UYVY422, 64, 32), + "uyvy 64x32 ramp neon", + ); + } + + #[test] + fn odd_width_preview_stays_on_swscale() { + for pixel in [ + ffmpeg::format::Pixel::YUYV422, + ffmpeg::format::Pixel::UYVY422, + ffmpeg::format::Pixel::NV12, + ] { + let frame = ffmpeg::frame::Video::new(pixel, 3, 2); + let mut scaler = None; + let (_, dims) = camera_preview_image(&frame, &mut scaler, false, None).unwrap(); + assert_eq!(dims, (3, 2)); + assert!(scaler.is_some(), "{pixel:?}"); + } + } + + enum Nv12Pattern { + HighFrequency, + VerticalStep, + Smooth, + } + + fn nv12_gap_vs_swscale( + width: u32, + height: u32, + mirrored: bool, + pattern: Nv12Pattern, + ) -> Option { + nv12_gap(width, height, mirrored, pattern, false) + } + + #[cfg(target_arch = "aarch64")] + fn nv12_gap_vs_native_swscale( + width: u32, + height: u32, + mirrored: bool, + pattern: Nv12Pattern, + ) -> Option { + nv12_gap(width, height, mirrored, pattern, true) + } + + fn nv12_gap( + width: u32, + height: u32, + mirrored: bool, + pattern: Nv12Pattern, + native_swscale: bool, + ) -> Option { + let mut frame = ffmpeg::frame::Video::new(ffmpeg::format::Pixel::NV12, width, height); + let y_stride = frame.stride(0); + let uv_stride = frame.stride(1); + let uv_rows = height.div_ceil(2) as usize; + match pattern { + Nv12Pattern::HighFrequency => { + for plane in 0..2 { + for (index, byte) in frame.data_mut(plane).iter_mut().enumerate() { + *byte = index.wrapping_mul(17).wrapping_add(plane * 41) as u8; + } + } + } + Nv12Pattern::VerticalStep => { + frame.data_mut(0)[..height as usize * y_stride].fill(128); + let uv = frame.data_mut(1); + for row in 0..uv_rows { + let (cb, cr) = if row.is_multiple_of(2) { + (16, 240) + } else { + (240, 16) + }; + for col in (0..width as usize).step_by(2) { + uv[row * uv_stride + col] = cb; + uv[row * uv_stride + col + 1] = cr; + } + } + } + Nv12Pattern::Smooth => { + let y = frame.data_mut(0); + for row in 0..height as usize { + for col in 0..width as usize { + y[row * y_stride + col] = 16 + ((col + row) % 200) as u8; + } + } + let uv = frame.data_mut(1); + for row in 0..uv_rows { + for col in (0..width as usize).step_by(2) { + let value = 108 + ((col / 2 + row) % 40) as u8; + uv[row * uv_stride + col] = value; + uv[row * uv_stride + col + 1] = value.wrapping_add(8); + } + } + } + } + let kernel = cap_gpui_kernels::camera_bgra::nv12_to_bgra( + frame.data(0), + frame.data(1), + width as usize, + height as usize, + y_stride, + uv_stride, + mirrored, + )?; + Some(if native_swscale { + gap_vs_native_swscale(&frame, &kernel, mirrored) + } else { + gap_vs_swscale(&frame, &kernel, mirrored) + }) + } + + #[cfg(target_arch = "aarch64")] + fn gradient_nv12_gap_vs_native_swscale(width: u32, height: u32) -> Option { + let mut frame = ffmpeg::frame::Video::new(ffmpeg::format::Pixel::NV12, width, height); + let y_stride = frame.stride(0); + let uv_stride = frame.stride(1); + let height = height as usize; + let width = width as usize; + for row in 0..height { + for col in 0..width { + frame.data_mut(0)[row * y_stride + col] = + (16 + (row * 180 / height.max(1)) + (col % 8)) as u8; + } + } + for row in 0..height.div_ceil(2) { + for col in (0..width).step_by(2) { + frame.data_mut(1)[row * uv_stride + col] = (48 + row * 3).min(224) as u8; + frame.data_mut(1)[row * uv_stride + col + 1] = + u8::try_from(208u16.saturating_sub((row * 2) as u16)).unwrap_or(0); + } + } + let kernel = cap_gpui_kernels::camera_bgra::nv12_to_bgra( + frame.data(0), + frame.data(1), + width, + height, + y_stride, + uv_stride, + false, + )?; + Some(gap_vs_native_swscale(&frame, &kernel, false)) + } + + #[cfg(target_arch = "aarch64")] + fn packed_ramp_gap_vs_native_swscale( + pixel: ffmpeg::format::Pixel, + width: u32, + height: u32, + ) -> Option { + use cap_gpui_kernels::camera_bgra::{self, Packed422}; + + let mut frame = ffmpeg::frame::Video::new(pixel, width, height); + for (index, byte) in frame.data_mut(0).iter_mut().enumerate() { + *byte = 16 + ((index / 4) % 200) as u8; + } + let format = if pixel == ffmpeg::format::Pixel::UYVY422 { + Packed422::Uyvy + } else { + Packed422::Yuyv + }; + let kernel = camera_bgra::packed422_to_bgra( + frame.data(0), + width as usize, + height as usize, + frame.stride(0), + format, + false, + )?; + Some(gap_vs_native_swscale(&frame, &kernel, false)) + } + + fn packed_gap_vs_swscale( + pixel: ffmpeg::format::Pixel, + width: u32, + height: u32, + mirrored: bool, + ) -> Option { + use cap_gpui_kernels::camera_bgra::{self, Packed422}; + + let mut frame = ffmpeg::frame::Video::new(pixel, width, height); + for (index, byte) in frame.data_mut(0).iter_mut().enumerate() { + *byte = index.wrapping_mul(17).wrapping_add(41) as u8; + } + let format = if pixel == ffmpeg::format::Pixel::UYVY422 { + Packed422::Uyvy + } else { + Packed422::Yuyv + }; + let kernel = camera_bgra::packed422_to_bgra( + frame.data(0), + width as usize, + height as usize, + frame.stride(0), + format, + mirrored, + )?; + Some(gap_vs_swscale(&frame, &kernel, mirrored)) + } + + // FFmpeg 7.1's aarch64 bilinear scaler keeps NEON `hscale` / `yuv2planeX` + // after `SWS_ACCURATE_RND` has skipped `ff_nv12_to_bgra_neon`. The strict + // check wants the C filters instead. `av_force_cpu_flags` is process-global, + // so the mutex keeps parallel tests from observing flags mid-flip, and `-1` + // turns auto-detection back on before the guard drops. + #[cfg(target_arch = "aarch64")] + unsafe extern "C" { + fn av_force_cpu_flags(flags: i32); + } + + #[cfg(target_arch = "aarch64")] + fn swscale_cpu_guard() -> std::sync::MutexGuard<'static, ()> { + static CPU: std::sync::Mutex<()> = std::sync::Mutex::new(()); + CPU.lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } + + #[cfg(target_arch = "aarch64")] + struct RestoreSwscaleCpu; + + #[cfg(target_arch = "aarch64")] + impl Drop for RestoreSwscaleCpu { + fn drop(&mut self) { + unsafe { av_force_cpu_flags(-1) } + } + } + + fn gap_vs_swscale(frame: &ffmpeg::frame::Video, kernel: &[u8], mirrored: bool) -> u8 { + gap_vs_bilinear(frame, kernel, mirrored, true) + } + + fn gap_vs_native_swscale(frame: &ffmpeg::frame::Video, kernel: &[u8], mirrored: bool) -> u8 { + gap_vs_bilinear(frame, kernel, mirrored, false) + } + + fn gap_vs_bilinear( + frame: &ffmpeg::frame::Video, + kernel: &[u8], + mirrored: bool, + c_reference: bool, + ) -> u8 { + #[cfg(target_arch = "aarch64")] + let _guard = swscale_cpu_guard(); + #[cfg(target_arch = "aarch64")] + let _restore = c_reference.then(|| { + unsafe { av_force_cpu_flags(0) } + RestoreSwscaleCpu + }); + #[cfg(not(target_arch = "aarch64"))] + let _ = c_reference; + let mut scaler = ffmpeg::software::scaling::Context::get( + frame.format(), + frame.width(), + frame.height(), + ffmpeg::format::Pixel::BGRA, + frame.width(), + frame.height(), + ffmpeg::software::scaling::Flags::BILINEAR, + ) + .unwrap(); + let mut converted = ffmpeg::frame::Video::empty(); + scaler.run(frame, &mut converted).unwrap(); + let swscale = cap_gpui_kernels::frame::copy_rows( + converted.data(0), + frame.width() as usize * 4, + converted.stride(0), + frame.height() as usize, + mirrored, + ) + .unwrap(); + kernel + .iter() + .zip(&swscale) + .map(|(kernel, swscale)| kernel.abs_diff(*swscale)) + .max() + .unwrap_or(0) + } + + #[test] + fn camera_preview_keeps_swscale_for_downscale_and_yuv420p() { + let yuyv = ffmpeg::frame::Video::new(ffmpeg::format::Pixel::YUYV422, 64, 32); + let mut scaler = None; + let (_, capped) = camera_preview_image(&yuyv, &mut scaler, false, Some((32, 32))).unwrap(); + assert_eq!(capped, (32, 16)); + assert!(scaler.is_some()); + + let yuv420 = ffmpeg::frame::Video::new(ffmpeg::format::Pixel::YUV420P, 4, 4); + let mut scaler = None; + let (image, dims) = camera_preview_image(&yuv420, &mut scaler, false, None).unwrap(); + assert_eq!(dims, (4, 4)); + assert!(scaler.is_some()); + assert_eq!(image.as_bytes(0).unwrap().len(), 4 * 4 * 4); + } } #[cfg(test)]