| 1 | use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _}; |
| 2 | |
| 3 | use crate::camera::i420_from_rgba; |
| 4 | use crate::mask::{Axis, axis}; |
| 5 | use crate::matte::{Matte, box_filter}; |
| 6 | |
| 7 | const BACKGROUND_SCALE: usize = 4; |
| 8 | const BLUR_RADIUS: usize = 3; |
| 9 | const BLUR_PASSES: usize = 2; |
| 10 | const ESTIMATE_REGULARISER: f32 = 0.005; |
| 11 | const DEBLEED_RADIUS: usize = 2; |
| 12 | const MIN_FOREGROUND_ALPHA: f32 = 0.05; |
| 13 | const WRAP_RADIUS: usize = 1; |
| 14 | const WRAP_PASSES: usize = 2; |
| 15 | const WRAP_STRENGTH: f32 = 0.3; |
| 16 | const MAX_BANDS: usize = 4; |
| 17 | |
| 18 | struct Grid { |
| 19 | values: Vec<f32>, |
| 20 | width: usize, |
| 21 | across: Axis, |
| 22 | down: Axis, |
| 23 | } |
| 24 | |
| 25 | impl Grid { |
| 26 | fn new(values: Vec<f32>, (width, height): (usize, usize), (plane_width, plane_height): (usize, usize)) -> Grid { |
| 27 | Grid { values, width, across: axis(plane_width, width), down: axis(plane_height, height) } |
| 28 | } |
| 29 | |
| 30 | fn row(&self, row: usize) -> (usize, usize, f32) { |
| 31 | (self.down.first[row] * self.width, self.down.second[row] * self.width, self.down.weight[row]) |
| 32 | } |
| 33 | |
| 34 | fn at(&self, (top, bottom, vertical): (usize, usize, f32), column: usize) -> f32 { |
| 35 | let (left, right, horizontal) = (self.across.first[column], self.across.second[column], self.across.weight[column]); |
| 36 | let upper = self.values[top + left] * (1. - horizontal) + self.values[top + right] * horizontal; |
| 37 | let lower = self.values[bottom + left] * (1. - horizontal) + self.values[bottom + right] * horizontal; |
| 38 | upper * (1. - vertical) + lower * vertical |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | fn cell_means(plane: &[u8], stride: usize, width: usize, height: usize, factor: usize) -> (Vec<f32>, usize, usize) { |
| 43 | let (small_width, small_height) = (width.div_ceil(factor), height.div_ceil(factor)); |
| 44 | let mut small = vec![0f32; small_width * small_height]; |
| 45 | let mut sums = vec![0u32; small_width]; |
| 46 | for (row, line) in small.chunks_exact_mut(small_width).enumerate() { |
| 47 | let rows = row * factor..((row + 1) * factor).min(height); |
| 48 | sums.fill(0); |
| 49 | for source_row in rows.clone() { |
| 50 | for (sum, group) in sums.iter_mut().zip(plane[source_row * stride..][..width].chunks(factor)) { |
| 51 | *sum += group.iter().map(|&value| u32::from(value)).sum::<u32>(); |
| 52 | } |
| 53 | } |
| 54 | for (column, (slot, sum)) in line.iter_mut().zip(&sums).enumerate() { |
| 55 | let columns = factor.min(width - column * factor); |
| 56 | *slot = *sum as f32 / (rows.len() * columns) as f32; |
| 57 | } |
| 58 | } |
| 59 | (small, small_width, small_height) |
| 60 | } |
| 61 | |
| 62 | fn blurred(values: &[f32], width: usize, height: usize, radius: usize, passes: usize) -> Vec<f32> { |
| 63 | (0..passes).fold(values.to_vec(), |current, _| box_filter(¤t, width, height, radius)) |
| 64 | } |
| 65 | |
| 66 | fn dilated(values: &[f32], width: usize, height: usize) -> Vec<f32> { |
| 67 | let mut across = vec![0f32; values.len()]; |
| 68 | for (line, output) in values.chunks_exact(width).zip(across.chunks_exact_mut(width)) { |
| 69 | for (column, slot) in output.iter_mut().enumerate() { |
| 70 | *slot = line[column.saturating_sub(1)..(column + 2).min(width)].iter().copied().fold(0f32, f32::max); |
| 71 | } |
| 72 | } |
| 73 | let mut output = vec![0f32; values.len()]; |
| 74 | for row in 0..height { |
| 75 | let (first, last) = (row.saturating_sub(1), (row + 1).min(height - 1)); |
| 76 | let target = &mut output[row * width..][..width]; |
| 77 | for neighbour in first..=last { |
| 78 | target.iter_mut().zip(&across[neighbour * width..][..width]).for_each(|(slot, &value)| *slot = slot.max(value)); |
| 79 | } |
| 80 | } |
| 81 | output |
| 82 | } |
| 83 | |
| 84 | /// The person on the small background grid, the same for luma and both chroma planes. |
| 85 | struct PersonGrid { |
| 86 | width: usize, |
| 87 | height: usize, |
| 88 | weight: Vec<f32>, |
| 89 | blurred_weight: Vec<f32>, |
| 90 | wide: Option<Vec<f32>>, |
| 91 | } |
| 92 | |
| 93 | impl PersonGrid { |
| 94 | fn new(matte: &Matte, (radius, passes): (usize, usize), wrap: bool) -> PersonGrid { |
| 95 | let (person, width, height) = cell_means(&matte.alpha, matte.width, matte.width, matte.height, BACKGROUND_SCALE); |
| 96 | let weight: Vec<f32> = dilated(&person, width, height).iter().map(|&alpha| (1. - alpha / 255.).powi(2)).collect(); |
| 97 | let blurred_weight = blurred(&weight, width, height, radius, passes); |
| 98 | let wide = wrap.then(|| blurred(&person, width, height, WRAP_RADIUS, WRAP_PASSES).iter().map(|alpha| alpha / 255.).collect()); |
| 99 | PersonGrid { width, height, weight, blurred_weight, wide } |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | /// Normalised convolution: only pixels the matte calls background count, so the person never bleeds into it. |
| 104 | fn background_estimate(plane: &[u8], stride: usize, (width, height): (usize, usize), factor: usize, person: &PersonGrid, (radius, passes): (usize, usize)) -> Vec<f32> { |
| 105 | let (values, small_width, small_height) = cell_means(plane, stride, width, height, factor); |
| 106 | debug_assert_eq!((small_width, small_height), (person.width, person.height)); |
| 107 | let weighted: Vec<f32> = values.iter().zip(&person.weight).map(|(value, weight)| value * weight).collect(); |
| 108 | let (weighted, plain) = (blurred(&weighted, small_width, small_height, radius, passes), blurred(&values, small_width, small_height, radius, passes)); |
| 109 | weighted.iter().zip(&person.blurred_weight).zip(&plain).map(|((weighted, weight), plain)| (weighted + ESTIMATE_REGULARISER * plain) / (weight + ESTIMATE_REGULARISER)).collect() |
| 110 | } |
| 111 | |
| 112 | pub struct PicturePlanes { |
| 113 | width: usize, |
| 114 | height: usize, |
| 115 | planes: [Vec<u8>; 3], |
| 116 | soft: [(Vec<f32>, usize, usize); 3], |
| 117 | } |
| 118 | |
| 119 | impl PicturePlanes { |
| 120 | pub fn new(rgb: &[u8], width: usize, height: usize) -> PicturePlanes { |
| 121 | let rgba: Vec<u8> = rgb.chunks_exact(3).flat_map(|pixel| [pixel[0], pixel[1], pixel[2], 255]).collect(); |
| 122 | let buffer = i420_from_rgba(&rgba, width as u32, height as u32); |
| 123 | let (stride_y, stride_u, stride_v) = buffer.strides(); |
| 124 | let (plane_y, plane_u, plane_v) = buffer.data(); |
| 125 | let (chroma_width, chroma_height) = (width.div_ceil(2), height.div_ceil(2)); |
| 126 | let copy = |plane: &[u8], stride: u32, plane_width: usize, plane_height: usize| (0..plane_height).flat_map(|row| plane[row * stride as usize..][..plane_width].to_vec()).collect::<Vec<u8>>(); |
| 127 | let planes = [copy(plane_y, stride_y, width, height), copy(plane_u, stride_u, chroma_width, chroma_height), copy(plane_v, stride_v, chroma_width, chroma_height)]; |
| 128 | let soft = std::array::from_fn(|index| { |
| 129 | let (plane_width, plane_height, factor) = if index == 0 { (width, height, BACKGROUND_SCALE) } else { (chroma_width, chroma_height, BACKGROUND_SCALE / 2) }; |
| 130 | let (values, small_width, small_height) = cell_means(&planes[index], plane_width, plane_width, plane_height, factor); |
| 131 | (blurred(&values, small_width, small_height, BLUR_RADIUS, BLUR_PASSES), small_width, small_height) |
| 132 | }); |
| 133 | PicturePlanes { width, height, planes, soft } |
| 134 | } |
| 135 | |
| 136 | pub fn fits(&self, width: usize, height: usize) -> bool { |
| 137 | (self.width, self.height) == (width, height) |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | pub enum Backdrop<'a> { |
| 142 | Blur, |
| 143 | Picture(&'a PicturePlanes), |
| 144 | } |
| 145 | |
| 146 | struct PlaneJob<'a> { |
| 147 | matte: &'a Matte, |
| 148 | estimate: Grid, |
| 149 | picture: Option<(&'a [u8], Grid, Grid)>, |
| 150 | } |
| 151 | |
| 152 | impl PlaneJob<'_> { |
| 153 | fn rows(&self, plane: &mut [u8], stride: usize, first_row: usize) { |
| 154 | for (offset, line) in plane.chunks_mut(stride).enumerate() { |
| 155 | let length = self.matte.width.min(line.len()); |
| 156 | self.row(&mut line[..length], first_row + offset); |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | fn row(&self, line: &mut [u8], row: usize) { |
| 161 | let width = self.matte.width; |
| 162 | let alphas = &self.matte.alpha[row * width..][..width]; |
| 163 | let estimate_row = self.estimate.row(row); |
| 164 | match &self.picture { |
| 165 | None => { |
| 166 | for (column, (value, &alpha)) in line.iter_mut().zip(alphas).enumerate() { |
| 167 | if alpha == u8::MAX { |
| 168 | continue; |
| 169 | } |
| 170 | let person = f32::from(alpha) / 255.; |
| 171 | *value = (f32::from(*value) * person + self.estimate.at(estimate_row, column) * (1. - person) + 0.5) as u8; |
| 172 | } |
| 173 | } |
| 174 | Some((picture, soft, wide_alpha)) => { |
| 175 | let picture = &picture[row * width..][..width]; |
| 176 | let (soft_row, wide_row) = (soft.row(row), wide_alpha.row(row)); |
| 177 | for (column, (value, &alpha)) in line.iter_mut().zip(alphas).enumerate() { |
| 178 | let wrap = WRAP_STRENGTH * (1. - wide_alpha.at(wide_row, column)); |
| 179 | if alpha == u8::MAX && wrap < 1e-3 { |
| 180 | continue; |
| 181 | } |
| 182 | let person = f32::from(alpha) / 255.; |
| 183 | let background = f32::from(picture[column]); |
| 184 | let foreground = if person >= 1. { |
| 185 | f32::from(*value) |
| 186 | } else { |
| 187 | ((f32::from(*value) - (1. - person) * self.estimate.at(estimate_row, column)) / person.max(MIN_FOREGROUND_ALPHA)).clamp(0., 255.) |
| 188 | }; |
| 189 | let wrapped = foreground + wrap * (soft.at(soft_row, column) - foreground); |
| 190 | *value = (wrapped * person + background * (1. - person) + 0.5).clamp(0., 255.) as u8; |
| 191 | } |
| 192 | } |
| 193 | } |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | fn plane_job<'a>(plane: &[u8], stride: usize, matte: &'a Matte, factor: usize, person: &PersonGrid, reach: (usize, usize), picture: Option<(&'a [u8], &(Vec<f32>, usize, usize))>) -> PlaneJob<'a> { |
| 198 | let size = (matte.width, matte.height); |
| 199 | let estimate = background_estimate(plane, stride, size, factor, person, reach); |
| 200 | let picture = picture.map(|(planar, (soft, soft_width, soft_height))| { |
| 201 | let wide = person.wide.clone().unwrap_or_else(|| vec![0.; person.width * person.height]); |
| 202 | (planar, Grid::new(soft.clone(), (*soft_width, *soft_height), size), Grid::new(wide, (person.width, person.height), size)) |
| 203 | }); |
| 204 | PlaneJob { matte, estimate: Grid::new(estimate, (person.width, person.height), size), picture } |
| 205 | } |
| 206 | |
| 207 | pub fn composite(buffer: &mut I420Buffer, matte: &Matte, backdrop: Backdrop) { |
| 208 | let (width, height) = (buffer.width() as usize, buffer.height() as usize); |
| 209 | let chroma_height = height.div_ceil(2); |
| 210 | let (stride_y, stride_u, stride_v) = buffer.strides(); |
| 211 | let (stride_y, stride_u, stride_v) = (stride_y as usize, stride_u as usize, stride_v as usize); |
| 212 | let picture = match backdrop { |
| 213 | Backdrop::Picture(picture) if picture.fits(width, height) => Some(picture), |
| 214 | _ => None, |
| 215 | }; |
| 216 | let reach = if picture.is_some() { (DEBLEED_RADIUS, 1) } else { (BLUR_RADIUS, BLUR_PASSES) }; |
| 217 | let (chroma_matte, person) = std::thread::scope(|scope| { |
| 218 | let halved = scope.spawn(|| matte.halved()); |
| 219 | let person = PersonGrid::new(matte, reach, picture.is_some()); |
| 220 | (halved.join().expect("chroma matte"), person) |
| 221 | }); |
| 222 | let (plane_y, plane_u, plane_v) = buffer.data_mut(); |
| 223 | let layer = |index: usize| picture.map(|picture| (picture.planes[index].as_slice(), &picture.soft[index])); |
| 224 | let jobs = std::thread::scope(|scope| { |
| 225 | let (person, chroma_matte, layer) = (&person, &chroma_matte, &layer); |
| 226 | let (blue, red) = (&*plane_u, &*plane_v); |
| 227 | let blue = scope.spawn(move || plane_job(blue, stride_u, chroma_matte, BACKGROUND_SCALE / 2, person, reach, layer(1))); |
| 228 | let red = scope.spawn(move || plane_job(red, stride_v, chroma_matte, BACKGROUND_SCALE / 2, person, reach, layer(2))); |
| 229 | let luma = plane_job(plane_y, stride_y, matte, BACKGROUND_SCALE, person, reach, layer(0)); |
| 230 | [luma, blue.join().expect("blue job"), red.join().expect("red job")] |
| 231 | }); |
| 232 | let bands = std::thread::available_parallelism().map_or(1, usize::from).min(MAX_BANDS); |
| 233 | std::thread::scope(|scope| { |
| 234 | for (job, plane, stride, rows) in [(&jobs[0], plane_y, stride_y, height), (&jobs[1], plane_u, stride_u, chroma_height), (&jobs[2], plane_v, stride_v, chroma_height)] { |
| 235 | let rows_per_band = rows.div_ceil(bands); |
| 236 | for (index, band) in plane.chunks_mut(rows_per_band * stride).enumerate() { |
| 237 | scope.spawn(move || job.rows(band, stride, index * rows_per_band)); |
| 238 | } |
| 239 | } |
| 240 | }); |
| 241 | } |
| 242 | |
| 243 | #[cfg(test)] |
| 244 | mod tests { |
| 245 | use super::*; |
| 246 | |
| 247 | const WIDTH: usize = 320; |
| 248 | const HEIGHT: usize = 180; |
| 249 | const LEFT: usize = 120; |
| 250 | const RIGHT: usize = 200; |
| 251 | |
| 252 | fn frame(person_luma: u8, background_luma: u8) -> I420Buffer { |
| 253 | let mut buffer = I420Buffer::new(WIDTH as u32, HEIGHT as u32); |
| 254 | let stride = buffer.strides().0 as usize; |
| 255 | let (plane_y, plane_u, plane_v) = buffer.data_mut(); |
| 256 | for row in 0..HEIGHT { |
| 257 | for column in 0..WIDTH { |
| 258 | plane_y[row * stride + column] = if (LEFT..RIGHT).contains(&column) { person_luma } else { background_luma }; |
| 259 | } |
| 260 | } |
| 261 | plane_u.fill(128); |
| 262 | plane_v.fill(128); |
| 263 | buffer |
| 264 | } |
| 265 | |
| 266 | fn matte(edge: impl Fn(usize) -> u8) -> Matte { |
| 267 | Matte { width: WIDTH, height: HEIGHT, alpha: (0..WIDTH * HEIGHT).map(|index| edge(index % WIDTH)).collect() } |
| 268 | } |
| 269 | |
| 270 | fn luma(buffer: &I420Buffer, column: usize) -> u8 { |
| 271 | let stride = buffer.strides().0 as usize; |
| 272 | buffer.data().0[HEIGHT / 2 * stride + column] |
| 273 | } |
| 274 | |
| 275 | #[test] |
| 276 | fn the_blurred_background_takes_no_colour_from_the_person() { |
| 277 | let mut buffer = frame(250, 60); |
| 278 | let exact = matte(|column| if (LEFT..RIGHT).contains(&column) { 255 } else { 0 }); |
| 279 | composite(&mut buffer, &exact, Backdrop::Blur); |
| 280 | for column in [LEFT - 2, LEFT - 6, RIGHT + 1, RIGHT + 5] { |
| 281 | assert!(luma(&buffer, column).abs_diff(60) <= 3, "column {column}: {}", luma(&buffer, column)); |
| 282 | } |
| 283 | assert_eq!(luma(&buffer, WIDTH / 2), 250); |
| 284 | } |
| 285 | |
| 286 | #[test] |
| 287 | fn a_picture_replaces_the_old_background_inside_soft_edges() { |
| 288 | let mut buffer = frame(40, 240); |
| 289 | let soft = matte(|column| match column { |
| 290 | column if (LEFT + 4..RIGHT - 4).contains(&column) => 255, |
| 291 | column if (LEFT..RIGHT).contains(&column) => 128, |
| 292 | _ => 0, |
| 293 | }); |
| 294 | let stride = buffer.strides().0 as usize; |
| 295 | let plane = buffer.data_mut().0; |
| 296 | for row in 0..HEIGHT { |
| 297 | for column in (LEFT..LEFT + 4).chain(RIGHT - 4..RIGHT) { |
| 298 | plane[row * stride + column] = 140; |
| 299 | } |
| 300 | } |
| 301 | let black = PicturePlanes::new(&vec![0u8; WIDTH * HEIGHT * 3], WIDTH, HEIGHT); |
| 302 | composite(&mut buffer, &soft, Backdrop::Picture(&black)); |
| 303 | let edge = luma(&buffer, LEFT + 1); |
| 304 | assert!(edge < 50, "the old bright background shows through the soft edge: {edge}"); |
| 305 | assert!(luma(&buffer, 4) <= 17, "background {}", luma(&buffer, 4)); |
| 306 | assert!(luma(&buffer, WIDTH / 2).abs_diff(40) <= 1); |
| 307 | } |
| 308 | |
| 309 | #[test] |
| 310 | fn light_from_the_picture_wraps_onto_the_edge_of_the_person() { |
| 311 | let mut buffer = frame(40, 40); |
| 312 | let exact = matte(|column| if (LEFT..RIGHT).contains(&column) { 255 } else { 0 }); |
| 313 | let white = PicturePlanes::new(&vec![255u8; WIDTH * HEIGHT * 3], WIDTH, HEIGHT); |
| 314 | composite(&mut buffer, &exact, Backdrop::Picture(&white)); |
| 315 | assert!(luma(&buffer, LEFT) > 60, "edge {}", luma(&buffer, LEFT)); |
| 316 | assert!(luma(&buffer, WIDTH / 2).abs_diff(40) <= 1); |
| 317 | } |
| 318 | } |