//! RGB to YUV conversion. /// Packed sRGB RGBA8 to planar BT.709 limited-range I420 with MPEG-2 left chroma siting. Alpha is ignored; `width` and `height` must be even. pub fn rgba_to_i420_709( rgba: &[u8], width: usize, height: usize, y: &mut [u8], u: &mut [u8], v: &mut [u8], ) { i420_709(rgba, width, height, [0, 1, 2], y, u, v); } /// Packed sRGB BGRA8 to planar BT.709 limited-range I420 with MPEG-2 left chroma siting. Alpha is ignored; `width` and `height` must be even. pub fn bgra_to_i420_709( bgra: &[u8], width: usize, height: usize, y: &mut [u8], u: &mut [u8], v: &mut [u8], ) { i420_709(bgra, width, height, [2, 1, 0], y, u, v); } /// Box-filter downscale of packed 4-byte pixels (`src` rows `stride` bytes apart, `sw` x `sh` source) to `dw` x `dh` packed rows; each channel is the rounded mean of its source footprint. pub fn rgb_box_downscale( src: &[u8], sw: usize, sh: usize, stride: usize, dst: &mut [u8], dw: usize, dh: usize, ) { assert!( sw >= dw && sh >= dh && dw > 0 && dh > 0, "source smaller than output" ); assert!(stride >= sw * 4 && src.len() >= stride * sh); assert_eq!(dst.len(), dw * dh * 4); for oy in 0..dh { let (y0, y1) = footprint(oy, sh, dh); for ox in 0..dw { let (x0, x1) = footprint(ox, sw, dw); let mut sum = [0u32; 4]; for row in src[y0 * stride..y1 * stride].chunks_exact(stride) { for px in row[x0 * 4..x1 * 4].chunks_exact(4) { for (s, &c) in sum.iter_mut().zip(px) { *s += u32::from(c); } } } let n = ((x1 - x0) * (y1 - y0)) as u32; for (d, s) in dst[(oy * dw + ox) * 4..][..4].iter_mut().zip(sum) { *d = ((s + n / 2) / n) as u8; } } } } /// Integer 8-bit limited-range YUV to RGB: `R = (ky*(Y-16) + rv*(V-128) + 128) >> 8`, and `G` and `B` alike. The one source of these numbers: the Vulkan shader takes them as push constants. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct YuvToRgb { /// Luma scale. pub ky: i32, /// Red from Cr. pub rv: i32, /// Green from Cb. pub gu: i32, /// Green from Cr. pub gv: i32, /// Blue from Cb. pub bu: i32, } impl YuvToRgb { /// The five coefficients in shader push-constant order. pub fn words(self) -> [i32; 5] { [self.ky, self.rv, self.gu, self.gv, self.bu] } } /// BT.601, limited range. pub const BT601_LIMITED: YuvToRgb = YuvToRgb { ky: 298, rv: 409, gu: -100, gv: -208, bu: 516, }; /// BT.709, limited range. pub const BT709_LIMITED: YuvToRgb = YuvToRgb { ky: 298, rv: 459, gu: -55, gv: -136, bu: 541, }; /// Planar 8-bit I420 (`u` and `v` at half size, bilinear chroma) to packed 4-byte pixels at `dw` x `dh`, downscaled by a separable Catmull-Rom kernel widened by the scale ratio ([`taps`]); out == in is the plain conversion. Alpha is 255. `bgra` picks the byte order. pub fn i420_to_packed( y: &[u8], u: &[u8], v: &[u8], (w, h): (usize, usize), (dw, dh): (usize, usize), bgra: bool, k: &YuvToRgb, ) -> Vec { assert!(w % 2 == 0 && h % 2 == 0, "width and height must be even"); assert!( w >= dw && h >= dh && dw > 0 && dh > 0, "source smaller than output" ); assert!(y.len() == w * h && u.len() == w * h / 4 && v.len() == w * h / 4); let cw = w / 2; let mut rgb = vec![[0i32; 3]; w * h]; for sy in 0..h { for sx in 0..w { let yy = i32::from(y[sy * w + sx]) - 16; let uu = chroma_at(u, (cw, h / 2), sx, sy) - 128; let vv = chroma_at(v, (cw, h / 2), sx, sy) - 128; let r = ((k.ky * yy + k.rv * vv + 128) >> 8).clamp(0, 255); let g = ((k.ky * yy + k.gu * uu + k.gv * vv + 128) >> 8).clamp(0, 255); let b = ((k.ky * yy + k.bu * uu + 128) >> 8).clamp(0, 255); rgb[sy * w + sx] = [r, g, b]; } } let xt: Vec<(i32, Vec)> = (0..dw).map(|o| taps(o, w, dw)).collect(); let yt: Vec<(i32, Vec)> = (0..dh).map(|o| taps(o, h, dh)).collect(); let mut rows = vec![[0i32; 3]; h * dw]; for sy in 0..h { for (ox, (lo, wx)) in xt.iter().enumerate() { let mut s = [0i32; 3]; for (i, &c) in wx.iter().enumerate() { let px = rgb[sy * w + edge(lo + i as i32, w)]; for (s, p) in s.iter_mut().zip(px) { *s += c * p; } } rows[sy * dw + ox] = s; } } let mut out = vec![255u8; dw * dh * 4]; for (oy, (lo, wy)) in yt.iter().enumerate() { for ox in 0..dw { let mut s = [0i32; 3]; for (j, &c) in wy.iter().enumerate() { let row = rows[edge(lo + j as i32, h) * dw + ox]; for (s, p) in s.iter_mut().zip(row) { *s += c * p; } } let [r, g, b] = s.map(|s| ((s + (1 << (2 * TAP_BITS - 1))) >> (2 * TAP_BITS)).clamp(0, 255) as u8); let o = (oy * dw + ox) * 4; let px = if bgra { [b, g, r] } else { [r, g, b] }; out[o..o + 3].copy_from_slice(&px); } } out } const TAP_BITS: i32 = 10; /// Catmull-Rom (a = -0.5) taps of output sample `o` scaling `n_in` to `n_out <= n_in` samples: support 2 * n_in / n_out source samples each side of the output centre, weights in Q12 normalised to sum to 1 << TAP_BITS (the rounding residue goes to the tap nearest the centre). Returns the first tap's index (may lie outside the picture: [`edge`] clamps) and the weights. The Vulkan shader nv12_to_rgb.comp computes the same integers. fn taps(o: usize, n_in: usize, n_out: usize) -> (i32, Vec) { let (o, n, m) = (o as i32, n_in as i32, n_out as i32); let c2 = (2 * o + 1) * n - m; let centre = (c2 + m) / (2 * m); let reach = 2 * n / m + 2; let (lo, hi) = (centre - reach, centre + reach); let kernel = |i: i32| { let t = ((2 * m * i - c2).abs() * 4096 / (2 * n)).min(8192); let t2 = (t * t) >> 12; let t3 = (t2 * t) >> 12; if t < 4096 { (3 * t3 - 5 * t2 + 8192) >> 1 } else { (-t3 + 5 * t2 - 8 * t + 16384) >> 1 } }; let k: Vec = (lo..=hi).map(kernel).collect(); let sum: i32 = k.iter().sum(); let mut wts: Vec = k .iter() .map(|&k| k.signum() * ((k.abs() * (1 << TAP_BITS) + (sum >> 1)) / sum)) .collect(); wts[(centre - lo) as usize] += (1 << TAP_BITS) - wts.iter().sum::(); (lo, wts) } fn edge(i: i32, n: usize) -> usize { i.clamp(0, n as i32 - 1) as usize } /// Bilinear 4:2:0 chroma at luma `(x, y)`: samples left-sited on even columns and centred between row pairs, as the RGB to I420 conversions write them. fn chroma_at(plane: &[u8], (cw, ch): (usize, usize), x: usize, y: usize) -> i32 { let j = x / 2; let row = |r: usize| { let a = i32::from(plane[r * cw + j]); if x % 2 == 0 { 2 * a } else { a + i32::from(plane[r * cw + (j + 1).min(cw - 1)]) } }; let k = y / 2; let s = if y % 2 == 0 { row(k.saturating_sub(1)) + 3 * row(k) } else { 3 * row(k) + row((k + 1).min(ch - 1)) }; (s + 4) >> 3 } fn footprint(o: usize, n_in: usize, n_out: usize) -> (usize, usize) { (o * n_in / n_out, ((o + 1) * n_in).div_ceil(n_out)) } fn i420_709( rgba: &[u8], width: usize, height: usize, order: [usize; 3], y: &mut [u8], u: &mut [u8], v: &mut [u8], ) { assert!( width.is_multiple_of(2) && height.is_multiple_of(2), "width and height must be even" ); assert_eq!(rgba.len(), width * height * 4); assert_eq!(y.len(), width * height); let (cw, ch) = (width / 2, height / 2); assert_eq!(u.len(), cw * ch); assert_eq!(v.len(), cw * ch); if ch == 0 { return; } let k = Coeffs::bt709(); let threads = std::thread::available_parallelism() .map_or(1, |n| n.get()) .min(8) .min(ch); let rows = ch.div_ceil(threads); let band = rows * 2 * width; std::thread::scope(|s| { let bands = rgba .chunks(band * 4) .zip(y.chunks_mut(band)) .zip(u.chunks_mut(rows * cw)) .zip(v.chunks_mut(rows * cw)); for (((src, y), u), v) in bands { let k = &k; s.spawn(move || convert_band(src, width, order, k, y, u, v)); } }); } struct Coeffs { y: [i32; 3], cb: [i32; 3], cr: [i32; 3], } impl Coeffs { fn bt709() -> Self { let kr = 0.2126; let kb = 0.0722; let kg = 1.0 - kr - kb; let ky = 219.0 / 255.0; let kc = 224.0 / 255.0; let q = |c: f64| (c * 65536.0).round() as i32; Self { y: [q(ky * kr), q(ky * kg), q(ky * kb)], cb: [ q(-kc * kr / (2.0 * (1.0 - kb))), q(-kc * kg / (2.0 * (1.0 - kb))), q(kc / 2.0), ], cr: [ q(kc / 2.0), q(-kc * kg / (2.0 * (1.0 - kr))), q(-kc * kb / (2.0 * (1.0 - kr))), ], } } } fn convert_band( rgba: &[u8], width: usize, order: [usize; 3], k: &Coeffs, y: &mut [u8], u: &mut [u8], v: &mut [u8], ) { let cw = width / 2; let mut cb = vec![0i32; width]; let mut cr = vec![0i32; width]; let pairs = rgba .chunks_exact(2 * width * 4) .zip(y.chunks_exact_mut(2 * width)) .zip(u.chunks_exact_mut(cw)) .zip(v.chunks_exact_mut(cw)); for (((pair, luma), u), v) in pairs { let (top, bottom) = pair.split_at(width * 4); let (y0, y1) = luma.split_at_mut(width); cb.fill(0); cr.fill(0); pixel_row(top, order, y0, &mut cb, &mut cr, k); pixel_row(bottom, order, y1, &mut cb, &mut cr, k); subsample(&cb, u); subsample(&cr, v); } } fn pixel_row( rgba: &[u8], order: [usize; 3], y: &mut [u8], cb: &mut [i32], cr: &mut [i32], k: &Coeffs, ) { let px = rgba.as_chunks::<4>().0; for (((px, y), cb), cr) in px .iter() .zip(y.iter_mut()) .zip(cb.iter_mut()) .zip(cr.iter_mut()) { let (r, g, b) = ( i32::from(px[order[0]]), i32::from(px[order[1]]), i32::from(px[order[2]]), ); let luma = k.y[0] * r + k.y[1] * g + k.y[2] * b; *y = (((luma + 0x8000) >> 16) + 16).clamp(0, 255) as u8; *cb += k.cb[0] * r + k.cb[1] * g + k.cb[2] * b; *cr += k.cr[0] * r + k.cr[1] * g + k.cr[2] * b; } } fn subsample(sums: &[i32], out: &mut [u8]) { const HALF: i32 = 1 << 18; let fin = |acc: i32| (((acc + HALF) >> 19) + 128).clamp(0, 255) as u8; out[0] = fin(3 * sums[0] + sums[1]); for (o, w) in out[1..].iter_mut().zip(sums[1..].windows(3).step_by(2)) { *o = fin(w[0] + 2 * w[1] + w[2]); } } #[cfg(test)] mod tests { use super::*; #[test] fn four_by_two_matches_hand_values() { let white = [255, 255, 255, 255]; let red = [255, 0, 0, 255]; let black = [0, 0, 0, 255]; let rgba: Vec = [white, white, red, red, black, black, black, black] .into_iter() .flatten() .collect(); let (mut y, mut u, mut v) = (vec![0u8; 8], vec![0u8; 2], vec![0u8; 2]); rgba_to_i420_709(&rgba, 4, 2, &mut y, &mut u, &mut v); let close = |got: u8, want: i32| (i32::from(got) - want).abs() <= 1; for (got, want) in y.iter().zip([235, 235, 63, 63, 16, 16, 16, 16]) { assert!(close(*got, want), "y {got} vs {want}"); } assert!(close(u[0], 128) && close(v[0], 128)); assert!(close(u[1], 118), "u {}", u[1]); assert!(close(v[1], 170), "v {}", v[1]); } }