BlueGit

ict rusty-teams

Files

rusty-teams / crates / calling / src / composite.rs

composite.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
composite.rs 17.3 KiB Download Raw
1use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};
2
3use crate::camera::i420_from_rgba;
4use crate::mask::{Axis, axis};
5use crate::matte::{Matte, box_filter};
6
7const BACKGROUND_SCALE: usize = 4;
8const BLUR_RADIUS: usize = 3;
9const BLUR_PASSES: usize = 2;
10const ESTIMATE_REGULARISER: f32 = 0.005;
11const DEBLEED_RADIUS: usize = 2;
12const MIN_FOREGROUND_ALPHA: f32 = 0.05;
13const WRAP_RADIUS: usize = 1;
14const WRAP_PASSES: usize = 2;
15const WRAP_STRENGTH: f32 = 0.3;
16const MAX_BANDS: usize = 4;
17
18struct Grid {
19 values: Vec<f32>,
20 width: usize,
21 across: Axis,
22 down: Axis,
23}
24
25impl Grid {
26 fn new(
27 values: Vec<f32>,
28 (width, height): (usize, usize),
29 (plane_width, plane_height): (usize, usize),
30 ) -> Grid {
31 Grid {
32 values,
33 width,
34 across: axis(plane_width, width),
35 down: axis(plane_height, height),
36 }
37 }
38
39 fn row(&self, row: usize) -> (usize, usize, f32) {
40 (
41 self.down.first[row] * self.width,
42 self.down.second[row] * self.width,
43 self.down.weight[row],
44 )
45 }
46
47 fn at(&self, (top, bottom, vertical): (usize, usize, f32), column: usize) -> f32 {
48 let (left, right, horizontal) = (
49 self.across.first[column],
50 self.across.second[column],
51 self.across.weight[column],
52 );
53 let upper =
54 self.values[top + left] * (1. - horizontal) + self.values[top + right] * horizontal;
55 let lower = self.values[bottom + left] * (1. - horizontal)
56 + self.values[bottom + right] * horizontal;
57 upper * (1. - vertical) + lower * vertical
58 }
59}
60
61fn cell_means(
62 plane: &[u8],
63 stride: usize,
64 width: usize,
65 height: usize,
66 factor: usize,
67) -> (Vec<f32>, usize, usize) {
68 let (small_width, small_height) = (width.div_ceil(factor), height.div_ceil(factor));
69 let mut small = vec![0f32; small_width * small_height];
70 let mut sums = vec![0u32; small_width];
71 for (row, line) in small.chunks_exact_mut(small_width).enumerate() {
72 let rows = row * factor..((row + 1) * factor).min(height);
73 sums.fill(0);
74 for source_row in rows.clone() {
75 for (sum, group) in sums
76 .iter_mut()
77 .zip(plane[source_row * stride..][..width].chunks(factor))
78 {
79 *sum += group.iter().map(|&value| u32::from(value)).sum::<u32>();
80 }
81 }
82 for (column, (slot, sum)) in line.iter_mut().zip(&sums).enumerate() {
83 let columns = factor.min(width - column * factor);
84 *slot = *sum as f32 / (rows.len() * columns) as f32;
85 }
86 }
87 (small, small_width, small_height)
88}
89
90fn blurred(values: &[f32], width: usize, height: usize, radius: usize, passes: usize) -> Vec<f32> {
91 (0..passes).fold(values.to_vec(), |current, _| {
92 box_filter(&current, width, height, radius)
93 })
94}
95
96fn dilated(values: &[f32], width: usize, height: usize) -> Vec<f32> {
97 let mut across = vec![0f32; values.len()];
98 for (line, output) in values
99 .chunks_exact(width)
100 .zip(across.chunks_exact_mut(width))
101 {
102 for (column, slot) in output.iter_mut().enumerate() {
103 *slot = line[column.saturating_sub(1)..(column + 2).min(width)]
104 .iter()
105 .copied()
106 .fold(0f32, f32::max);
107 }
108 }
109 let mut output = vec![0f32; values.len()];
110 for row in 0..height {
111 let (first, last) = (row.saturating_sub(1), (row + 1).min(height - 1));
112 let target = &mut output[row * width..][..width];
113 for neighbour in first..=last {
114 target
115 .iter_mut()
116 .zip(&across[neighbour * width..][..width])
117 .for_each(|(slot, &value)| *slot = slot.max(value));
118 }
119 }
120 output
121}
122
123/// The person on the small background grid, the same for luma and both chroma planes.
124struct PersonGrid {
125 width: usize,
126 height: usize,
127 weight: Vec<f32>,
128 blurred_weight: Vec<f32>,
129 wide: Option<Vec<f32>>,
130}
131
132impl PersonGrid {
133 fn new(matte: &Matte, (radius, passes): (usize, usize), wrap: bool) -> PersonGrid {
134 let (person, width, height) = cell_means(
135 &matte.alpha,
136 matte.width,
137 matte.width,
138 matte.height,
139 BACKGROUND_SCALE,
140 );
141 let weight: Vec<f32> = dilated(&person, width, height)
142 .iter()
143 .map(|&alpha| (1. - alpha / 255.).powi(2))
144 .collect();
145 let blurred_weight = blurred(&weight, width, height, radius, passes);
146 let wide = wrap.then(|| {
147 blurred(&person, width, height, WRAP_RADIUS, WRAP_PASSES)
148 .iter()
149 .map(|alpha| alpha / 255.)
150 .collect()
151 });
152 PersonGrid {
153 width,
154 height,
155 weight,
156 blurred_weight,
157 wide,
158 }
159 }
160}
161
162/// Normalised convolution: only pixels the matte calls background count, so the person never bleeds into it.
163fn background_estimate(
164 plane: &[u8],
165 stride: usize,
166 (width, height): (usize, usize),
167 factor: usize,
168 person: &PersonGrid,
169 (radius, passes): (usize, usize),
170) -> Vec<f32> {
171 let (values, small_width, small_height) = cell_means(plane, stride, width, height, factor);
172 debug_assert_eq!((small_width, small_height), (person.width, person.height));
173 let weighted: Vec<f32> = values
174 .iter()
175 .zip(&person.weight)
176 .map(|(value, weight)| value * weight)
177 .collect();
178 let (weighted, plain) = (
179 blurred(&weighted, small_width, small_height, radius, passes),
180 blurred(&values, small_width, small_height, radius, passes),
181 );
182 weighted
183 .iter()
184 .zip(&person.blurred_weight)
185 .zip(&plain)
186 .map(|((weighted, weight), plain)| {
187 (weighted + ESTIMATE_REGULARISER * plain) / (weight + ESTIMATE_REGULARISER)
188 })
189 .collect()
190}
191
192pub struct PicturePlanes {
193 width: usize,
194 height: usize,
195 planes: [Vec<u8>; 3],
196 soft: [(Vec<f32>, usize, usize); 3],
197}
198
199impl PicturePlanes {
200 pub fn new(rgb: &[u8], width: usize, height: usize) -> PicturePlanes {
201 let rgba: Vec<u8> = rgb
202 .chunks_exact(3)
203 .flat_map(|pixel| [pixel[0], pixel[1], pixel[2], 255])
204 .collect();
205 let buffer = i420_from_rgba(&rgba, width as u32, height as u32);
206 let (stride_y, stride_u, stride_v) = buffer.strides();
207 let (plane_y, plane_u, plane_v) = buffer.data();
208 let (chroma_width, chroma_height) = (width.div_ceil(2), height.div_ceil(2));
209 let copy = |plane: &[u8], stride: u32, plane_width: usize, plane_height: usize| {
210 (0..plane_height)
211 .flat_map(|row| plane[row * stride as usize..][..plane_width].to_vec())
212 .collect::<Vec<u8>>()
213 };
214 let planes = [
215 copy(plane_y, stride_y, width, height),
216 copy(plane_u, stride_u, chroma_width, chroma_height),
217 copy(plane_v, stride_v, chroma_width, chroma_height),
218 ];
219 let soft = std::array::from_fn(|index| {
220 let (plane_width, plane_height, factor) = if index == 0 {
221 (width, height, BACKGROUND_SCALE)
222 } else {
223 (chroma_width, chroma_height, BACKGROUND_SCALE / 2)
224 };
225 let (values, small_width, small_height) = cell_means(
226 &planes[index],
227 plane_width,
228 plane_width,
229 plane_height,
230 factor,
231 );
232 (
233 blurred(&values, small_width, small_height, BLUR_RADIUS, BLUR_PASSES),
234 small_width,
235 small_height,
236 )
237 });
238 PicturePlanes {
239 width,
240 height,
241 planes,
242 soft,
243 }
244 }
245
246 pub fn fits(&self, width: usize, height: usize) -> bool {
247 (self.width, self.height) == (width, height)
248 }
249}
250
251pub enum Backdrop<'a> {
252 Blur,
253 Picture(&'a PicturePlanes),
254}
255
256struct PlaneJob<'a> {
257 matte: &'a Matte,
258 estimate: Grid,
259 picture: Option<(&'a [u8], Grid, Grid)>,
260}
261
262impl PlaneJob<'_> {
263 fn rows(&self, plane: &mut [u8], stride: usize, first_row: usize) {
264 for (offset, line) in plane.chunks_mut(stride).enumerate() {
265 let length = self.matte.width.min(line.len());
266 self.row(&mut line[..length], first_row + offset);
267 }
268 }
269
270 fn row(&self, line: &mut [u8], row: usize) {
271 let width = self.matte.width;
272 let alphas = &self.matte.alpha[row * width..][..width];
273 let estimate_row = self.estimate.row(row);
274 match &self.picture {
275 None => {
276 for (column, (value, &alpha)) in line.iter_mut().zip(alphas).enumerate() {
277 if alpha == u8::MAX {
278 continue;
279 }
280 let person = f32::from(alpha) / 255.;
281 *value = (f32::from(*value) * person
282 + self.estimate.at(estimate_row, column) * (1. - person)
283 + 0.5) as u8;
284 }
285 }
286 Some((picture, soft, wide_alpha)) => {
287 let picture = &picture[row * width..][..width];
288 let (soft_row, wide_row) = (soft.row(row), wide_alpha.row(row));
289 for (column, (value, &alpha)) in line.iter_mut().zip(alphas).enumerate() {
290 let wrap = WRAP_STRENGTH * (1. - wide_alpha.at(wide_row, column));
291 if alpha == u8::MAX && wrap < 1e-3 {
292 continue;
293 }
294 let person = f32::from(alpha) / 255.;
295 let background = f32::from(picture[column]);
296 let foreground = if person >= 1. {
297 f32::from(*value)
298 } else {
299 ((f32::from(*value)
300 - (1. - person) * self.estimate.at(estimate_row, column))
301 / person.max(MIN_FOREGROUND_ALPHA))
302 .clamp(0., 255.)
303 };
304 let wrapped = foreground + wrap * (soft.at(soft_row, column) - foreground);
305 *value =
306 (wrapped * person + background * (1. - person) + 0.5).clamp(0., 255.) as u8;
307 }
308 }
309 }
310 }
311}
312
313fn plane_job<'a>(
314 plane: &[u8],
315 stride: usize,
316 matte: &'a Matte,
317 factor: usize,
318 person: &PersonGrid,
319 reach: (usize, usize),
320 picture: Option<(&'a [u8], &(Vec<f32>, usize, usize))>,
321) -> PlaneJob<'a> {
322 let size = (matte.width, matte.height);
323 let estimate = background_estimate(plane, stride, size, factor, person, reach);
324 let picture = picture.map(|(planar, (soft, soft_width, soft_height))| {
325 let wide = person
326 .wide
327 .clone()
328 .unwrap_or_else(|| vec![0.; person.width * person.height]);
329 (
330 planar,
331 Grid::new(soft.clone(), (*soft_width, *soft_height), size),
332 Grid::new(wide, (person.width, person.height), size),
333 )
334 });
335 PlaneJob {
336 matte,
337 estimate: Grid::new(estimate, (person.width, person.height), size),
338 picture,
339 }
340}
341
342pub fn composite(buffer: &mut I420Buffer, matte: &Matte, backdrop: Backdrop) {
343 let (width, height) = (buffer.width() as usize, buffer.height() as usize);
344 let chroma_height = height.div_ceil(2);
345 let (stride_y, stride_u, stride_v) = buffer.strides();
346 let (stride_y, stride_u, stride_v) = (stride_y as usize, stride_u as usize, stride_v as usize);
347 let picture = match backdrop {
348 Backdrop::Picture(picture) if picture.fits(width, height) => Some(picture),
349 _ => None,
350 };
351 let reach = if picture.is_some() {
352 (DEBLEED_RADIUS, 1)
353 } else {
354 (BLUR_RADIUS, BLUR_PASSES)
355 };
356 let (chroma_matte, person) = std::thread::scope(|scope| {
357 let halved = scope.spawn(|| matte.halved());
358 let person = PersonGrid::new(matte, reach, picture.is_some());
359 (halved.join().expect("chroma matte"), person)
360 });
361 let (plane_y, plane_u, plane_v) = buffer.data_mut();
362 let layer = |index: usize| {
363 picture.map(|picture| (picture.planes[index].as_slice(), &picture.soft[index]))
364 };
365 let jobs = std::thread::scope(|scope| {
366 let (person, chroma_matte, layer) = (&person, &chroma_matte, &layer);
367 let (blue, red) = (&*plane_u, &*plane_v);
368 let blue = scope.spawn(move || {
369 plane_job(
370 blue,
371 stride_u,
372 chroma_matte,
373 BACKGROUND_SCALE / 2,
374 person,
375 reach,
376 layer(1),
377 )
378 });
379 let red = scope.spawn(move || {
380 plane_job(
381 red,
382 stride_v,
383 chroma_matte,
384 BACKGROUND_SCALE / 2,
385 person,
386 reach,
387 layer(2),
388 )
389 });
390 let luma = plane_job(
391 plane_y,
392 stride_y,
393 matte,
394 BACKGROUND_SCALE,
395 person,
396 reach,
397 layer(0),
398 );
399 [
400 luma,
401 blue.join().expect("blue job"),
402 red.join().expect("red job"),
403 ]
404 });
405 let bands = std::thread::available_parallelism()
406 .map_or(1, usize::from)
407 .min(MAX_BANDS);
408 std::thread::scope(|scope| {
409 for (job, plane, stride, rows) in [
410 (&jobs[0], plane_y, stride_y, height),
411 (&jobs[1], plane_u, stride_u, chroma_height),
412 (&jobs[2], plane_v, stride_v, chroma_height),
413 ] {
414 let rows_per_band = rows.div_ceil(bands);
415 for (index, band) in plane.chunks_mut(rows_per_band * stride).enumerate() {
416 scope.spawn(move || job.rows(band, stride, index * rows_per_band));
417 }
418 }
419 });
420}
421
422#[cfg(test)]
423mod tests {
424 use super::*;
425
426 const WIDTH: usize = 320;
427 const HEIGHT: usize = 180;
428 const LEFT: usize = 120;
429 const RIGHT: usize = 200;
430
431 fn frame(person_luma: u8, background_luma: u8) -> I420Buffer {
432 let mut buffer = I420Buffer::new(WIDTH as u32, HEIGHT as u32);
433 let stride = buffer.strides().0 as usize;
434 let (plane_y, plane_u, plane_v) = buffer.data_mut();
435 for row in 0..HEIGHT {
436 for column in 0..WIDTH {
437 plane_y[row * stride + column] = if (LEFT..RIGHT).contains(&column) {
438 person_luma
439 } else {
440 background_luma
441 };
442 }
443 }
444 plane_u.fill(128);
445 plane_v.fill(128);
446 buffer
447 }
448
449 fn matte(edge: impl Fn(usize) -> u8) -> Matte {
450 Matte {
451 width: WIDTH,
452 height: HEIGHT,
453 alpha: (0..WIDTH * HEIGHT)
454 .map(|index| edge(index % WIDTH))
455 .collect(),
456 }
457 }
458
459 fn luma(buffer: &I420Buffer, column: usize) -> u8 {
460 let stride = buffer.strides().0 as usize;
461 buffer.data().0[HEIGHT / 2 * stride + column]
462 }
463
464 #[test]
465 fn the_blurred_background_takes_no_colour_from_the_person() {
466 let mut buffer = frame(250, 60);
467 let exact = matte(|column| {
468 if (LEFT..RIGHT).contains(&column) {
469 255
470 } else {
471 0
472 }
473 });
474 composite(&mut buffer, &exact, Backdrop::Blur);
475 for column in [LEFT - 2, LEFT - 6, RIGHT + 1, RIGHT + 5] {
476 assert!(
477 luma(&buffer, column).abs_diff(60) <= 3,
478 "column {column}: {}",
479 luma(&buffer, column)
480 );
481 }
482 assert_eq!(luma(&buffer, WIDTH / 2), 250);
483 }
484
485 #[test]
486 fn a_picture_replaces_the_old_background_inside_soft_edges() {
487 let mut buffer = frame(40, 240);
488 let soft = matte(|column| match column {
489 column if (LEFT + 4..RIGHT - 4).contains(&column) => 255,
490 column if (LEFT..RIGHT).contains(&column) => 128,
491 _ => 0,
492 });
493 let stride = buffer.strides().0 as usize;
494 let plane = buffer.data_mut().0;
495 for row in 0..HEIGHT {
496 for column in (LEFT..LEFT + 4).chain(RIGHT - 4..RIGHT) {
497 plane[row * stride + column] = 140;
498 }
499 }
500 let black = PicturePlanes::new(&vec![0u8; WIDTH * HEIGHT * 3], WIDTH, HEIGHT);
501 composite(&mut buffer, &soft, Backdrop::Picture(&black));
502 let edge = luma(&buffer, LEFT + 1);
503 assert!(
504 edge < 50,
505 "the old bright background shows through the soft edge: {edge}"
506 );
507 assert!(luma(&buffer, 4) <= 17, "background {}", luma(&buffer, 4));
508 assert!(luma(&buffer, WIDTH / 2).abs_diff(40) <= 1);
509 }
510
511 #[test]
512 fn light_from_the_picture_wraps_onto_the_edge_of_the_person() {
513 let mut buffer = frame(40, 40);
514 let exact = matte(|column| {
515 if (LEFT..RIGHT).contains(&column) {
516 255
517 } else {
518 0
519 }
520 });
521 let white = PicturePlanes::new(&vec![255u8; WIDTH * HEIGHT * 3], WIDTH, HEIGHT);
522 composite(&mut buffer, &exact, Backdrop::Picture(&white));
523 assert!(luma(&buffer, LEFT) > 60, "edge {}", luma(&buffer, LEFT));
524 assert!(luma(&buffer, WIDTH / 2).abs_diff(40) <= 1);
525 }
526}