From d671fb1c1856e003a640c81f9ea9dafcfcb36aaf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 25 Nov 2026 14:49:17 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9A=A1=20perf:=20convert=20and=20scale=20pix?= =?UTF-8?q?els=20with=20simd=20in=20an=20always=20optimized=20crate?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cargo.toml | 6 +- crates/client/Cargo.toml | 1 + crates/client/src/media/convert.rs | 61 +------------- crates/client/src/share/convert.rs | 93 ++------------------- crates/client/src/share/encode.rs | 4 +- crates/pixel/Cargo.toml | 11 +++ crates/pixel/src/lib.rs | 127 +++++++++++++++++++++++++++++ 7 files changed, 157 insertions(+), 146 deletions(-) create mode 100644 crates/pixel/Cargo.toml create mode 100644 crates/pixel/src/lib.rs diff --git a/Cargo.toml b/Cargo.toml index 27ab7de..e7462e6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] resolver = "2" -members = ["crates/client", "crates/common", "crates/server"] +members = ["crates/client", "crates/common", "crates/pixel", "crates/server"] [profile.dev] debug = "line-tables-only" @@ -8,6 +8,9 @@ debug = "line-tables-only" [profile.dev.package."*"] opt-level = 3 +[profile.dev.package.pixel] +opt-level = 3 + [profile.harness] inherits = "dev" opt-level = 3 @@ -26,6 +29,7 @@ unsafe_code = "forbid" [workspace.dependencies] common = { path = "crates/common" } +pixel = { path = "crates/pixel" } tokio = { version = "1.54.1", features = ["full"] } bitcode = "0.6.9" quinn = { version = "0.11.12", default-features = false, features = [ diff --git a/crates/client/Cargo.toml b/crates/client/Cargo.toml index e02a109..1285c07 100644 --- a/crates/client/Cargo.toml +++ b/crates/client/Cargo.toml @@ -5,6 +5,7 @@ edition = "2024" [dependencies] common.workspace = true +pixel.workspace = true reed-solomon-simd = "3.1.0" tokio.workspace = true quinn = { workspace = true, features = ["rustls-ring", "platform-verifier"] } diff --git a/crates/client/src/media/convert.rs b/crates/client/src/media/convert.rs index 8719873..1e67bc7 100644 --- a/crates/client/src/media/convert.rs +++ b/crates/client/src/media/convert.rs @@ -1,61 +1,4 @@ +pub use pixel::yuv_to_bgra; + pub const ATTACHMENT_WIDTH: u32 = 1280; pub const SHARE_WIDTH: u32 = 1920; - -pub fn yuv_to_bgra( - y: &[u8], - y_stride: usize, - u: &[u8], - v: &[u8], - uv_stride: usize, - width: u32, - height: u32, - max_width: u32, -) -> Option<(u32, u32, Vec)> { - if width == 0 || height == 0 { - return None; - } - let step = width.div_ceil(max_width); - let out_width = width.div_ceil(step); - let out_height = height.div_ceil(step); - let mut out = Vec::with_capacity(out_width as usize * out_height as usize * 4); - for row in 0..out_height { - let py = (row * step).min(height - 1) as usize; - for column in 0..out_width { - let px = (column * step).min(width - 1) as usize; - let luma = sample(y, y_stride, px, py) - 16; - let cb = sample(u, uv_stride, px / 2, py / 2) - 128; - let cr = sample(v, uv_stride, px / 2, py / 2) - 128; - let scaled = 298 * luma; - let red = clamp((scaled + 459 * cr + 128) >> 8); - let green = clamp((scaled - 55 * cb - 136 * cr + 128) >> 8); - let blue = clamp((scaled + 541 * cb + 128) >> 8); - out.extend_from_slice(&[blue, green, red, 255]); - } - } - Some((out_width, out_height, out)) -} - -fn sample(plane: &[u8], stride: usize, x: usize, y: usize) -> i32 { - plane - .get(y * stride + x) - .map_or(0, |&value| i32::from(value)) -} - -fn clamp(value: i32) -> u8 { - value.clamp(0, 255) as u8 -} - -#[cfg(test)] -mod tests { - use super::*; - - fn bgra(luma: u8) -> Option<(u32, u32, Vec)> { - yuv_to_bgra(&[luma; 4], 2, &[128], &[128], 1, 2, 2, ATTACHMENT_WIDTH) - } - - #[test] - fn i420_limits_map_to_black_and_white_bgra() { - assert_eq!(bgra(235), Some((2, 2, [255, 255, 255, 255].repeat(4)))); - assert_eq!(bgra(16), Some((2, 2, [0, 0, 0, 255].repeat(4)))); - } -} diff --git a/crates/client/src/share/convert.rs b/crates/client/src/share/convert.rs index 41f4bc4..ed5a70d 100644 --- a/crates/client/src/share/convert.rs +++ b/crates/client/src/share/convert.rs @@ -1,88 +1,13 @@ -use std::ops::Range; +pub use pixel::I420; use super::frame::Frame; -pub struct I420 { - pub y: Vec, - pub u: Vec, - pub v: Vec, - pub width: u32, - pub height: u32, -} - -pub fn bgra_to_i420(frame: &Frame, width: u32, height: u32) -> I420 { - let (w, h) = (width as usize, height as usize); - let mut y = vec![0; w * h]; - let mut cb_full = vec![0; w * h]; - let mut cr_full = vec![0; w * h]; - for dy in 0..h { - let rows = span(dy, h, frame.height as usize); - for dx in 0..w { - let columns = span(dx, w, frame.width as usize); - let (r, g, b) = average(frame, columns, rows.clone()); - let index = dy * w + dx; - y[index] = luma(r, g, b); - cb_full[index] = chroma_blue(r, g, b); - cr_full[index] = chroma_red(r, g, b); - } - } - I420 { - y, - u: subsample(&cb_full, w, h), - v: subsample(&cr_full, w, h), - width, - height, - } -} - -fn span(index: usize, target: usize, source: usize) -> Range { - let start = index * source / target; - let end = ((index + 1) * source / target).max(start + 1); - start..end -} - -fn average(frame: &Frame, columns: Range, rows: Range) -> (i32, i32, i32) { - let stride = frame.stride as usize; - let (mut r, mut g, mut b, mut count) = (0u32, 0u32, 0u32, 0u32); - for y in rows { - for x in columns.clone() { - let pixel = y * stride + x * 4; - b += u32::from(frame.bgra[pixel]); - g += u32::from(frame.bgra[pixel + 1]); - r += u32::from(frame.bgra[pixel + 2]); - count += 1; - } - } - ((r / count) as i32, (g / count) as i32, (b / count) as i32) -} - -fn luma(r: i32, g: i32, b: i32) -> u8 { - (((47 * r + 157 * g + 16 * b + 128) >> 8) + 16) as u8 -} - -fn chroma_blue(r: i32, g: i32, b: i32) -> u8 { - (((-26 * r - 86 * g + 112 * b + 128) >> 8) + 128) as u8 -} - -fn chroma_red(r: i32, g: i32, b: i32) -> u8 { - (((112 * r - 102 * g - 10 * b + 128) >> 8) + 128) as u8 -} - -fn subsample(plane: &[u8], width: usize, height: usize) -> Vec { - let mut out = Vec::with_capacity(width / 2 * height / 2); - for y in (0..height).step_by(2) { - for x in (0..width).step_by(2) { - let sum: u32 = [ - plane[y * width + x], - plane[y * width + x + 1], - plane[(y + 1) * width + x], - plane[(y + 1) * width + x + 1], - ] - .into_iter() - .map(u32::from) - .sum(); - out.push(((sum + 2) / 4) as u8); - } - } - out +pub fn bgra_to_i420(frame: &Frame, width: u32, height: u32) -> Option { + let source = pixel::Bgra { + data: &frame.bgra, + width: frame.width, + height: frame.height, + stride: frame.stride, + }; + pixel::bgra_to_i420(&source, width, height) } diff --git a/crates/client/src/share/encode.rs b/crates/client/src/share/encode.rs index 7de6a1a..4a3f6c3 100644 --- a/crates/client/src/share/encode.rs +++ b/crates/client/src/share/encode.rs @@ -115,7 +115,7 @@ impl Backend { match self { Self::Hardware(encoder) => encoder.encode(frame, settings, force), Self::H264(encoder) => { - let planes = convert::bgra_to_i420(frame, settings.width, settings.height); + let planes = convert::bgra_to_i420(frame, settings.width, settings.height)?; let picture = ec_h264::PictureView::i420( planes.width, planes.height, @@ -165,7 +165,7 @@ mod hardware { }; self.0.encode_rgb(&rgb, meta) } else { - let planes = convert::bgra_to_i420(frame, settings.width, settings.height); + let planes = convert::bgra_to_i420(frame, settings.width, settings.height)?; let picture = ec_hw::I420 { y: planes.y, u: planes.u, diff --git a/crates/pixel/Cargo.toml b/crates/pixel/Cargo.toml new file mode 100644 index 0000000..0e1aab3 --- /dev/null +++ b/crates/pixel/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "pixel" +version = "0.1.0" +edition = "2024" + +[dependencies] +yuv = "0.8.21" +fast_image_resize = "6.2.0" + +[lints] +workspace = true diff --git a/crates/pixel/src/lib.rs b/crates/pixel/src/lib.rs new file mode 100644 index 0000000..ec1bf9d --- /dev/null +++ b/crates/pixel/src/lib.rs @@ -0,0 +1,127 @@ +use fast_image_resize::{ + FilterType, PixelType, ResizeAlg, ResizeOptions, Resizer, + images::{Image, ImageRef}, +}; +use yuv::{ + YuvChromaSubsampling, YuvConversionMode, YuvPlanarImage, YuvPlanarImageMut, YuvRange, + YuvStandardMatrix, +}; + +const BYTES_PER_PIXEL: u32 = 4; +const RANGE: YuvRange = YuvRange::Limited; +const MATRIX: YuvStandardMatrix = YuvStandardMatrix::Bt709; + +pub struct Bgra<'a> { + pub data: &'a [u8], + pub width: u32, + pub height: u32, + pub stride: u32, +} + +pub struct I420 { + pub y: Vec, + pub u: Vec, + pub v: Vec, + pub width: u32, + pub height: u32, +} + +pub fn yuv_to_bgra( + y: &[u8], + y_stride: usize, + u: &[u8], + v: &[u8], + uv_stride: usize, + width: u32, + height: u32, + max_width: u32, +) -> Option<(u32, u32, Vec)> { + if width == 0 || height == 0 { + return None; + } + let image = YuvPlanarImage { + y_plane: y, + y_stride: y_stride as u32, + u_plane: u, + u_stride: uv_stride as u32, + v_plane: v, + v_stride: uv_stride as u32, + width, + height, + }; + let mut out = vec![0; (width * height * BYTES_PER_PIXEL) as usize]; + yuv::yuv420_to_bgra(&image, &mut out, width * BYTES_PER_PIXEL, RANGE, MATRIX).ok()?; + if width <= max_width { + return Some((width, height, out)); + } + let out_height = (u64::from(height) * u64::from(max_width) / u64::from(width)).max(1) as u32; + let source = Bgra { + data: &out, + width, + height, + stride: width * BYTES_PER_PIXEL, + }; + Some(( + max_width, + out_height, + scale(&source, max_width, out_height)?, + )) +} + +pub fn bgra_to_i420(source: &Bgra, width: u32, height: u32) -> Option { + let scaled = (source.width, source.height) != (width, height); + let resized = match scaled { + true => scale(source, width, height)?, + false => Vec::new(), + }; + let (data, stride) = match scaled { + true => (resized.as_slice(), width * BYTES_PER_PIXEL), + false => (source.data, source.stride), + }; + let mut planes = YuvPlanarImageMut::alloc(width, height, YuvChromaSubsampling::Yuv420); + yuv::bgra_to_yuv420( + &mut planes, + data, + stride, + RANGE, + MATRIX, + YuvConversionMode::Balanced, + ) + .ok()?; + Some(I420 { + y: planes.y_plane.borrow().to_vec(), + u: planes.u_plane.borrow().to_vec(), + v: planes.v_plane.borrow().to_vec(), + width, + height, + }) +} + +fn scale(source: &Bgra, width: u32, height: u32) -> Option> { + let view = ImageRef::new( + source.stride / BYTES_PER_PIXEL, + source.height, + source.data, + PixelType::U8x4, + ) + .ok()?; + let mut target = Image::new(width, height, PixelType::U8x4); + let options = ResizeOptions::new() + .resize_alg(ResizeAlg::Convolution(FilterType::Box)) + .use_alpha(false) + .crop(0.0, 0.0, f64::from(source.width), f64::from(source.height)); + Resizer::new().resize(&view, &mut target, &options).ok()?; + Some(target.into_vec()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn limited_range_maps_to_black_and_white() { + let bgra = |luma| yuv_to_bgra(&[luma; 4], 2, &[128], &[128], 1, 2, 2, 1920); + assert_eq!(bgra(235), Some((2, 2, [255, 255, 255, 255].repeat(4)))); + assert_eq!(bgra(16), Some((2, 2, [0, 0, 0, 255].repeat(4)))); + } +}