BlueGit

ict rusty-teams

Files

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

composite.rs

composite.rs 13.7 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(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
42fn 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
62fn blurred(values: &[f32], width: usize, height: usize, radius: usize, passes: usize) -> Vec<f32> {
63 (0..passes).fold(values.to_vec(), |current, _| box_filter(&current, width, height, radius))
64}
65
66fn dilated(values: &[f32], width: usize, height: usize) -> Vec<f32> {
67 let mut output = vec![0f32; values.len()];
68 for row in 0..height {
69 for column in 0..width {
70 let mut largest = 0f32;
71 for neighbour_row in row.saturating_sub(1)..(row + 2).min(height) {
72 for neighbour_column in column.saturating_sub(1)..(column + 2).min(width) {
73 largest = largest.max(values[neighbour_row * width + neighbour_column]);
74 }
75 }
76 output[row * width + column] = largest;
77 }
78 }
79 output
80}
81
82/// Normalised convolution: only pixels the matte calls background count, so the person never bleeds into it.
83fn background_estimate(plane: &[u8], stride: usize, (width, height): (usize, usize), matte: &Matte, factor: usize, (radius, passes): (usize, usize)) -> (Vec<f32>, usize, usize) {
84 let (values, small_width, small_height) = cell_means(plane, stride, width, height, factor);
85 let (person, ..) = cell_means(&matte.alpha, matte.width, width, height, factor);
86 let weight: Vec<f32> = dilated(&person, small_width, small_height).iter().map(|&alpha| (1. - alpha / 255.).powi(2)).collect();
87 let weighted: Vec<f32> = values.iter().zip(&weight).map(|(value, weight)| value * weight).collect();
88 let (weighted, weight, plain) = (
89 blurred(&weighted, small_width, small_height, radius, passes),
90 blurred(&weight, small_width, small_height, radius, passes),
91 blurred(&values, small_width, small_height, radius, passes),
92 );
93 let estimate = weighted.iter().zip(&weight).zip(&plain).map(|((weighted, weight), plain)| (weighted + ESTIMATE_REGULARISER * plain) / (weight + ESTIMATE_REGULARISER)).collect();
94 (estimate, small_width, small_height)
95}
96
97pub struct PicturePlanes {
98 width: usize,
99 height: usize,
100 planes: [Vec<u8>; 3],
101 soft: [(Vec<f32>, usize, usize); 3],
102}
103
104impl PicturePlanes {
105 pub fn new(rgb: &[u8], width: usize, height: usize) -> PicturePlanes {
106 let rgba: Vec<u8> = rgb.chunks_exact(3).flat_map(|pixel| [pixel[0], pixel[1], pixel[2], 255]).collect();
107 let buffer = i420_from_rgba(&rgba, width as u32, height as u32);
108 let (stride_y, stride_u, stride_v) = buffer.strides();
109 let (plane_y, plane_u, plane_v) = buffer.data();
110 let (chroma_width, chroma_height) = (width.div_ceil(2), height.div_ceil(2));
111 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>>();
112 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)];
113 let soft = std::array::from_fn(|index| {
114 let (plane_width, plane_height, factor) = if index == 0 { (width, height, BACKGROUND_SCALE) } else { (chroma_width, chroma_height, BACKGROUND_SCALE / 2) };
115 let (values, small_width, small_height) = cell_means(&planes[index], plane_width, plane_width, plane_height, factor);
116 (blurred(&values, small_width, small_height, BLUR_RADIUS, BLUR_PASSES), small_width, small_height)
117 });
118 PicturePlanes { width, height, planes, soft }
119 }
120
121 pub fn fits(&self, width: usize, height: usize) -> bool {
122 (self.width, self.height) == (width, height)
123 }
124}
125
126pub enum Backdrop<'a> {
127 Blur,
128 Picture(&'a PicturePlanes),
129}
130
131struct PlaneJob<'a> {
132 matte: &'a Matte,
133 estimate: Grid,
134 picture: Option<(&'a [u8], Grid, Grid)>,
135}
136
137impl PlaneJob<'_> {
138 fn rows(&self, plane: &mut [u8], stride: usize, first_row: usize) {
139 for (offset, line) in plane.chunks_mut(stride).enumerate() {
140 let length = self.matte.width.min(line.len());
141 self.row(&mut line[..length], first_row + offset);
142 }
143 }
144
145 fn row(&self, line: &mut [u8], row: usize) {
146 let width = self.matte.width;
147 let alphas = &self.matte.alpha[row * width..][..width];
148 let estimate_row = self.estimate.row(row);
149 match &self.picture {
150 None => {
151 for (column, (value, &alpha)) in line.iter_mut().zip(alphas).enumerate() {
152 if alpha == u8::MAX {
153 continue;
154 }
155 let person = f32::from(alpha) / 255.;
156 *value = (f32::from(*value) * person + self.estimate.at(estimate_row, column) * (1. - person) + 0.5) as u8;
157 }
158 }
159 Some((picture, soft, wide_alpha)) => {
160 let picture = &picture[row * width..][..width];
161 let (soft_row, wide_row) = (soft.row(row), wide_alpha.row(row));
162 for (column, (value, &alpha)) in line.iter_mut().zip(alphas).enumerate() {
163 let wrap = WRAP_STRENGTH * (1. - wide_alpha.at(wide_row, column));
164 if alpha == u8::MAX && wrap < 1e-3 {
165 continue;
166 }
167 let person = f32::from(alpha) / 255.;
168 let background = f32::from(picture[column]);
169 let foreground = if person >= 1. {
170 f32::from(*value)
171 } else {
172 ((f32::from(*value) - (1. - person) * self.estimate.at(estimate_row, column)) / person.max(MIN_FOREGROUND_ALPHA)).clamp(0., 255.)
173 };
174 let wrapped = foreground + wrap * (soft.at(soft_row, column) - foreground);
175 *value = (wrapped * person + background * (1. - person) + 0.5).clamp(0., 255.) as u8;
176 }
177 }
178 }
179 }
180}
181
182fn plane_job<'a>(plane: &[u8], stride: usize, matte: &'a Matte, factor: usize, picture: Option<(&'a [u8], &(Vec<f32>, usize, usize))>) -> PlaneJob<'a> {
183 let size = (matte.width, matte.height);
184 let reach = if picture.is_some() { (DEBLEED_RADIUS, 1) } else { (BLUR_RADIUS, BLUR_PASSES) };
185 let (estimate, small_width, small_height) = background_estimate(plane, stride, size, matte, factor, reach);
186 let picture = picture.map(|(planar, (soft, soft_width, soft_height))| {
187 let (person, ..) = cell_means(&matte.alpha, matte.width, matte.width, matte.height, factor);
188 let wide: Vec<f32> = blurred(&person, small_width, small_height, WRAP_RADIUS, WRAP_PASSES).iter().map(|alpha| alpha / 255.).collect();
189 (planar, Grid::new(soft.clone(), (*soft_width, *soft_height), size), Grid::new(wide, (small_width, small_height), size))
190 });
191 PlaneJob { matte, estimate: Grid::new(estimate, (small_width, small_height), size), picture }
192}
193
194pub fn composite(buffer: &mut I420Buffer, matte: &Matte, backdrop: Backdrop) {
195 let (width, height) = (buffer.width() as usize, buffer.height() as usize);
196 let chroma_height = height.div_ceil(2);
197 let (stride_y, stride_u, stride_v) = buffer.strides();
198 let (stride_y, stride_u, stride_v) = (stride_y as usize, stride_u as usize, stride_v as usize);
199 let chroma_matte = matte.halved();
200 let picture = match backdrop {
201 Backdrop::Picture(picture) if picture.fits(width, height) => Some(picture),
202 _ => None,
203 };
204 let (plane_y, plane_u, plane_v) = buffer.data_mut();
205 let layer = |index: usize| picture.map(|picture| (picture.planes[index].as_slice(), &picture.soft[index]));
206 let jobs = [
207 plane_job(plane_y, stride_y, matte, BACKGROUND_SCALE, layer(0)),
208 plane_job(plane_u, stride_u, &chroma_matte, BACKGROUND_SCALE / 2, layer(1)),
209 plane_job(plane_v, stride_v, &chroma_matte, BACKGROUND_SCALE / 2, layer(2)),
210 ];
211 let bands = std::thread::available_parallelism().map_or(1, usize::from).min(MAX_BANDS);
212 std::thread::scope(|scope| {
213 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)] {
214 let rows_per_band = rows.div_ceil(bands);
215 for (index, band) in plane.chunks_mut(rows_per_band * stride).enumerate() {
216 scope.spawn(move || job.rows(band, stride, index * rows_per_band));
217 }
218 }
219 });
220}
221
222#[cfg(test)]
223mod tests {
224 use super::*;
225
226 const WIDTH: usize = 320;
227 const HEIGHT: usize = 180;
228 const LEFT: usize = 120;
229 const RIGHT: usize = 200;
230
231 fn frame(person_luma: u8, background_luma: u8) -> I420Buffer {
232 let mut buffer = I420Buffer::new(WIDTH as u32, HEIGHT as u32);
233 let stride = buffer.strides().0 as usize;
234 let (plane_y, plane_u, plane_v) = buffer.data_mut();
235 for row in 0..HEIGHT {
236 for column in 0..WIDTH {
237 plane_y[row * stride + column] = if (LEFT..RIGHT).contains(&column) { person_luma } else { background_luma };
238 }
239 }
240 plane_u.fill(128);
241 plane_v.fill(128);
242 buffer
243 }
244
245 fn matte(edge: impl Fn(usize) -> u8) -> Matte {
246 Matte { width: WIDTH, height: HEIGHT, alpha: (0..WIDTH * HEIGHT).map(|index| edge(index % WIDTH)).collect() }
247 }
248
249 fn luma(buffer: &I420Buffer, column: usize) -> u8 {
250 let stride = buffer.strides().0 as usize;
251 buffer.data().0[HEIGHT / 2 * stride + column]
252 }
253
254 #[test]
255 fn the_blurred_background_takes_no_colour_from_the_person() {
256 let mut buffer = frame(250, 60);
257 let exact = matte(|column| if (LEFT..RIGHT).contains(&column) { 255 } else { 0 });
258 composite(&mut buffer, &exact, Backdrop::Blur);
259 for column in [LEFT - 2, LEFT - 6, RIGHT + 1, RIGHT + 5] {
260 assert!(luma(&buffer, column).abs_diff(60) <= 3, "column {column}: {}", luma(&buffer, column));
261 }
262 assert_eq!(luma(&buffer, WIDTH / 2), 250);
263 }
264
265 #[test]
266 fn a_picture_replaces_the_old_background_inside_soft_edges() {
267 let mut buffer = frame(40, 240);
268 let soft = matte(|column| match column {
269 column if (LEFT + 4..RIGHT - 4).contains(&column) => 255,
270 column if (LEFT..RIGHT).contains(&column) => 128,
271 _ => 0,
272 });
273 let stride = buffer.strides().0 as usize;
274 let plane = buffer.data_mut().0;
275 for row in 0..HEIGHT {
276 for column in (LEFT..LEFT + 4).chain(RIGHT - 4..RIGHT) {
277 plane[row * stride + column] = 140;
278 }
279 }
280 let black = PicturePlanes::new(&vec![0u8; WIDTH * HEIGHT * 3], WIDTH, HEIGHT);
281 composite(&mut buffer, &soft, Backdrop::Picture(&black));
282 let edge = luma(&buffer, LEFT + 1);
283 assert!(edge < 50, "the old bright background shows through the soft edge: {edge}");
284 assert!(luma(&buffer, 4) <= 17, "background {}", luma(&buffer, 4));
285 assert!(luma(&buffer, WIDTH / 2).abs_diff(40) <= 1);
286 }
287
288 #[test]
289 fn light_from_the_picture_wraps_onto_the_edge_of_the_person() {
290 let mut buffer = frame(40, 40);
291 let exact = matte(|column| if (LEFT..RIGHT).contains(&column) { 255 } else { 0 });
292 let white = PicturePlanes::new(&vec![255u8; WIDTH * HEIGHT * 3], WIDTH, HEIGHT);
293 composite(&mut buffer, &exact, Backdrop::Picture(&white));
294 assert!(luma(&buffer, LEFT) > 60, "edge {}", luma(&buffer, LEFT));
295 assert!(luma(&buffer, WIDTH / 2).abs_diff(40) <= 1);
296 }
297}