BlueGit

ict rusty-teams

Files

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

matte.rs

matte.rs 16.8 KiB Download Raw
1use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};
2
3use crate::blur::{Axis, MASK_HEIGHT, MASK_WIDTH, axis};
4use crate::camera::i420_from_rgba;
5
6const GUIDE_WIDTH: usize = 160;
7const FILTER_RADIUS: usize = 3;
8const FILTER_EPSILON: f32 = 3e-3;
9const CHROMA_WEIGHT: f32 = 2.;
10const MATTE_LOW: f32 = 0.45;
11const MATTE_HIGH: f32 = 0.8;
12const SURE_PERSON: f32 = 0.85;
13const SURE_BACKGROUND: f32 = 0.1;
14const CERTAINTY_RAMP: f32 = 0.05;
15const MAX_BANDS: usize = 4;
16const CHANNELS: usize = 3;
17
18/// Person alpha (0..255) per pixel of a `width` x `height` frame.
19pub struct Matte {
20 pub width: usize,
21 pub height: usize,
22 pub alpha: Vec<u8>,
23}
24
25impl Matte {
26 /// Same matte at half resolution, for 4:2:0 chroma planes.
27 pub fn halved(&self) -> Matte {
28 let (width, height) = (self.width.div_ceil(2), self.height.div_ceil(2));
29 let mut alpha = vec![0u8; width * height];
30 for (row, line) in alpha.chunks_exact_mut(width).enumerate() {
31 let (top, bottom) = (row * 2, (row * 2 + 1).min(self.height - 1));
32 for (column, slot) in line.iter_mut().enumerate() {
33 let (left, right) = (column * 2, (column * 2 + 1).min(self.width - 1));
34 let sum: u32 = [(top, left), (top, right), (bottom, left), (bottom, right)].iter().map(|&(y, x)| u32::from(self.alpha[y * self.width + x])).sum();
35 *slot = ((sum + 2) / 4) as u8;
36 }
37 }
38 Matte { width, height, alpha }
39 }
40}
41
42/// The 4:2:0 planes of the frame the matte follows.
43#[derive(Clone, Copy)]
44pub struct Planes<'a> {
45 pub luma: &'a [u8],
46 pub luma_stride: usize,
47 pub blue: &'a [u8],
48 pub blue_stride: usize,
49 pub red: &'a [u8],
50 pub red_stride: usize,
51 pub width: usize,
52 pub height: usize,
53}
54
55impl<'a> Planes<'a> {
56 pub fn of(buffer: &'a I420Buffer) -> Planes<'a> {
57 let (luma_stride, blue_stride, red_stride) = buffer.strides();
58 let (luma, blue, red) = buffer.data();
59 Planes { luma, luma_stride: luma_stride as usize, blue, blue_stride: blue_stride as usize, red, red_stride: red_stride as usize, width: buffer.width() as usize, height: buffer.height() as usize }
60 }
61
62 fn pixel(&self, column: usize, row: usize) -> [f32; CHANNELS] {
63 let chroma = |plane: &[u8], stride: usize| (f32::from(plane[row / 2 * stride + column / 2]) - 128.) * CHROMA_WEIGHT / 255.;
64 [f32::from(self.luma[row * self.luma_stride + column]) / 255., chroma(self.blue, self.blue_stride), chroma(self.red, self.red_stride)]
65 }
66}
67
68fn ramp(value: f32, start: f32) -> f32 {
69 ((value - start) / CERTAINTY_RAMP).clamp(0., 1.)
70}
71
72fn edge_curve(value: f32) -> f32 {
73 let t = ((value - MATTE_LOW) / (MATTE_HIGH - MATTE_LOW)).clamp(0., 1.);
74 t * t * (3. - 2. * t)
75}
76
77fn box_filter(input: &[f32], width: usize, height: usize, radius: usize) -> Vec<f32> {
78 let mut across = vec![0f32; input.len()];
79 let mut prefix = vec![0f32; width + 1];
80 for (line, output) in input.chunks_exact(width).zip(across.chunks_exact_mut(width)) {
81 for (index, &value) in line.iter().enumerate() {
82 prefix[index + 1] = prefix[index] + value;
83 }
84 for (index, slot) in output.iter_mut().enumerate() {
85 let (low, high) = (index.saturating_sub(radius), (index + radius + 1).min(width));
86 *slot = (prefix[high] - prefix[low]) / (high - low) as f32;
87 }
88 }
89 let mut output = vec![0f32; input.len()];
90 let mut sums = vec![0f32; width];
91 for line in across.chunks_exact(width).take(radius.min(height)) {
92 sums.iter_mut().zip(line).for_each(|(sum, value)| *sum += value);
93 }
94 for row in 0..height {
95 if row + radius < height {
96 sums.iter_mut().zip(&across[(row + radius) * width..][..width]).for_each(|(sum, value)| *sum += value);
97 }
98 if row > radius {
99 sums.iter_mut().zip(&across[(row - radius - 1) * width..][..width]).for_each(|(sum, value)| *sum -= value);
100 }
101 let count = ((row + radius + 1).min(height) - row.saturating_sub(radius)) as f32;
102 output[row * width..][..width].iter_mut().zip(&sums).for_each(|(slot, sum)| *slot = sum / count);
103 }
104 output
105}
106
107fn cell_means(plane: &[u8], stride: usize, subsampling: usize, (plane_width, plane_height): (usize, usize), factor: usize, (small_width, small_height): (usize, usize)) -> Vec<f32> {
108 let span = |cell: usize, limit: usize| {
109 let first = (cell * factor / subsampling).min(limit - 1);
110 first..((cell + 1) * factor).div_ceil(subsampling).clamp(first + 1, limit)
111 };
112 let columns: Vec<_> = (0..small_width).map(|column| span(column, plane_width)).collect();
113 let mut means = Vec::with_capacity(small_width * small_height);
114 let mut sums = vec![0u32; plane_width];
115 for row in 0..small_height {
116 let rows = span(row, plane_height);
117 sums.fill(0);
118 for line in rows.clone() {
119 sums.iter_mut().zip(&plane[line * stride..][..plane_width]).for_each(|(sum, &value)| *sum += u32::from(value));
120 }
121 for range in &columns {
122 means.push(sums[range.clone()].iter().sum::<u32>() as f32 / (rows.len() * range.len()) as f32);
123 }
124 }
125 means
126}
127
128fn small_guide(planes: &Planes, factor: usize) -> ([Vec<f32>; CHANNELS], usize, usize) {
129 let small = (planes.width.div_ceil(factor), planes.height.div_ceil(factor));
130 let chroma = (planes.width.div_ceil(2), planes.height.div_ceil(2));
131 let luma = cell_means(planes.luma, planes.luma_stride, 1, (planes.width, planes.height), factor, small).into_iter().map(|value| value / 255.).collect();
132 let colour = |plane: &[u8], stride: usize| cell_means(plane, stride, 2, chroma, factor, small).into_iter().map(|value| (value - 128.) * CHROMA_WEIGHT / 255.).collect();
133 ([luma, colour(planes.blue, planes.blue_stride), colour(planes.red, planes.red_stride)], small.0, small.1)
134}
135
136fn small_mask(mask: &[f32], width: usize, height: usize) -> Vec<f32> {
137 let (mask_x, mask_y) = (axis(width, MASK_WIDTH), axis(height, MASK_HEIGHT));
138 let mut small = Vec::with_capacity(width * height);
139 for row in 0..height {
140 let (top, bottom, down) = (mask_y.first[row] * MASK_WIDTH, mask_y.second[row] * MASK_WIDTH, mask_y.weight[row]);
141 for column in 0..width {
142 let (left, right, across) = (mask_x.first[column], mask_x.second[column], mask_x.weight[column]);
143 let upper = mask[top + left] * (1. - across) + mask[top + right] * across;
144 let lower = mask[bottom + left] * (1. - across) + mask[bottom + right] * across;
145 small.push(upper * (1. - down) + lower * down);
146 }
147 }
148 small
149}
150
151struct Coefficients {
152 slope: [Vec<f32>; CHANNELS],
153 offset: Vec<f32>,
154 width: usize,
155}
156
157fn solve(covariance: [[f32; CHANNELS]; CHANNELS], target: [f32; CHANNELS]) -> [f32; CHANNELS] {
158 let [[a, b, c], [_, d, e], [_, _, f]] = covariance;
159 let cofactors = [[d * f - e * e, c * e - b * f, b * e - c * d], [c * e - b * f, a * f - c * c, b * c - a * e], [b * e - c * d, b * c - a * e, a * d - b * b]];
160 let determinant = a * cofactors[0][0] + b * cofactors[0][1] + c * cofactors[0][2];
161 std::array::from_fn(|row| (0..CHANNELS).map(|column| cofactors[row][column] * target[column]).sum::<f32>() / determinant)
162}
163
164fn coefficients(guide: &[Vec<f32>; CHANNELS], person: &[f32], width: usize, height: usize) -> Coefficients {
165 let mean = |values: Vec<f32>| box_filter(&values, width, height, FILTER_RADIUS);
166 let mean_guide: [Vec<f32>; CHANNELS] = std::array::from_fn(|channel| mean(guide[channel].clone()));
167 let mean_person = mean(person.to_vec());
168 let mean_product: [Vec<f32>; CHANNELS] = std::array::from_fn(|channel| mean(guide[channel].iter().zip(person).map(|(guide, person)| guide * person).collect()));
169 let pairs = [(0, 0), (0, 1), (0, 2), (1, 1), (1, 2), (2, 2)];
170 let mean_pair: Vec<Vec<f32>> = pairs.iter().map(|&(first, second)| mean(guide[first].iter().zip(&guide[second]).map(|(first, second)| first * second).collect())).collect();
171 let mut slope: [Vec<f32>; CHANNELS] = std::array::from_fn(|_| vec![0f32; person.len()]);
172 let mut offset = vec![0f32; person.len()];
173 for index in 0..person.len() {
174 let mut covariance = [[0f32; CHANNELS]; CHANNELS];
175 for (&(first, second), pair) in pairs.iter().zip(&mean_pair) {
176 let value = pair[index] - mean_guide[first][index] * mean_guide[second][index] + if first == second { FILTER_EPSILON } else { 0. };
177 covariance[first][second] = value;
178 covariance[second][first] = value;
179 }
180 let target = std::array::from_fn(|channel| mean_product[channel][index] - mean_guide[channel][index] * mean_person[index]);
181 let solution = solve(covariance, target);
182 offset[index] = mean_person[index] - (0..CHANNELS).map(|channel| solution[channel] * mean_guide[channel][index]).sum::<f32>();
183 for channel in 0..CHANNELS {
184 slope[channel][index] = solution[channel];
185 }
186 }
187 Coefficients { slope: slope.map(mean), offset: mean(offset), width }
188}
189
190struct Upsampler<'a> {
191 coefficients: &'a Coefficients,
192 prior: &'a [f32],
193 planes: Planes<'a>,
194 across: Axis,
195 down: Axis,
196}
197
198impl Upsampler<'_> {
199 fn rows(&self, alpha: &mut [u8], first_row: usize) {
200 let small_width = self.coefficients.width;
201 let mut lines = vec![[0f32; CHANNELS + 2]; small_width];
202 for (offset, line) in alpha.chunks_exact_mut(self.planes.width).enumerate() {
203 let row = first_row + offset;
204 let (top, bottom, vertical) = (self.down.first[row] * small_width, self.down.second[row] * small_width, self.down.weight[row]);
205 let blend = |grid: &[f32], column: usize| grid[top + column] * (1. - vertical) + grid[bottom + column] * vertical;
206 for (column, slot) in lines.iter_mut().enumerate() {
207 *slot = [blend(&self.coefficients.slope[0], column), blend(&self.coefficients.slope[1], column), blend(&self.coefficients.slope[2], column), blend(&self.coefficients.offset, column), blend(self.prior, column)];
208 }
209 for (column, slot) in line.iter_mut().enumerate() {
210 let (left, right, horizontal) = (&lines[self.across.first[column]], &lines[self.across.second[column]], self.across.weight[column]);
211 let at = |index: usize| left[index] * (1. - horizontal) + right[index] * horizontal;
212 let prior = at(4);
213 let (floor, ceiling) = (ramp(prior, SURE_PERSON), ramp(prior, SURE_BACKGROUND - CERTAINTY_RAMP));
214 if floor >= 1. || ceiling <= 0. {
215 *slot = if floor >= 1. { u8::MAX } else { 0 };
216 continue;
217 }
218 let guide = self.planes.pixel(column, row);
219 let person = at(0) * guide[0] + at(1) * guide[1] + at(2) * guide[2] + at(3);
220 *slot = (edge_curve(person).max(floor).min(ceiling) * 255. + 0.5) as u8;
221 }
222 }
223 }
224}
225
226/// Snaps the low-resolution `mask` to the colour edges of the full-resolution frame with a fast colour guided filter.
227pub fn refine(mask: &[f32], planes: Planes) -> Matte {
228 let (width, height) = (planes.width, planes.height);
229 let factor = (width / GUIDE_WIDTH).max(1);
230 let (guide, small_width, small_height) = small_guide(&planes, factor);
231 let prior = small_mask(mask, small_width, small_height);
232 let coefficients = coefficients(&guide, &prior, small_width, small_height);
233 let upsampler = Upsampler { coefficients: &coefficients, prior: &prior, planes, across: axis(width, small_width), down: axis(height, small_height) };
234 let mut alpha = vec![0u8; width * height];
235 let bands = std::thread::available_parallelism().map_or(1, usize::from).min(MAX_BANDS);
236 let rows_per_band = height.div_ceil(bands);
237 std::thread::scope(|scope| {
238 for (index, band) in alpha.chunks_mut(rows_per_band * width).enumerate() {
239 let upsampler = &upsampler;
240 scope.spawn(move || upsampler.rows(band, index * rows_per_band));
241 }
242 });
243 Matte { width, height, alpha }
244}
245
246pub fn refine_rgba(mask: &[f32], rgba: &[u8], width: usize, height: usize) -> Matte {
247 refine(mask, Planes::of(&i420_from_rgba(rgba, width as u32, height as u32)))
248}
249
250#[cfg(test)]
251mod tests {
252 use super::*;
253
254 const WIDTH: usize = 1280;
255 const HEIGHT: usize = 720;
256 const LEFT: usize = 403;
257 const RIGHT: usize = 877;
258 const TOP: usize = 161;
259 const BOTTOM: usize = 598;
260 const BLOCK: usize = 3;
261
262 fn frame(width: usize, height: usize, luma: impl Fn(usize, usize) -> u8) -> I420Buffer {
263 let mut buffer = I420Buffer::new(width as u32, height as u32);
264 let stride = buffer.strides().0 as usize;
265 let (plane_y, plane_u, plane_v) = buffer.data_mut();
266 for row in 0..height {
267 for column in 0..width {
268 plane_y[row * stride + column] = luma(column, row);
269 }
270 }
271 plane_u.fill(128);
272 plane_v.fill(128);
273 buffer
274 }
275
276 fn square_frame() -> I420Buffer {
277 frame(WIDTH, HEIGHT, |column, row| if (LEFT..RIGHT).contains(&column) && (TOP..BOTTOM).contains(&row) { 200 } else { 50 })
278 }
279
280 fn blocky_mask() -> Vec<f32> {
281 (0..MASK_WIDTH * MASK_HEIGHT)
282 .map(|index| {
283 let (block_column, block_row) = ((index % MASK_WIDTH) / BLOCK * BLOCK, (index / MASK_WIDTH) / BLOCK * BLOCK);
284 let center_x = (block_column as f32 + BLOCK as f32 / 2.) * WIDTH as f32 / MASK_WIDTH as f32;
285 let center_y = (block_row as f32 + BLOCK as f32 / 2.) * HEIGHT as f32 / MASK_HEIGHT as f32;
286 let inside = (LEFT as f32..RIGHT as f32).contains(&center_x) && (TOP as f32..BOTTOM as f32).contains(&center_y);
287 if inside { 0.9 } else { 0.1 }
288 })
289 .collect()
290 }
291
292 fn crossing(values: impl Iterator<Item = u8>) -> Vec<usize> {
293 let values: Vec<u8> = values.collect();
294 values.windows(2).enumerate().filter(|(_, pair)| (pair[0] < 128) != (pair[1] < 128)).map(|(index, _)| index + 1).collect()
295 }
296
297 #[test]
298 fn a_blocky_mask_snaps_to_the_sharp_edge_of_the_frame() {
299 let matte = refine(&blocky_mask(), Planes::of(&square_frame()));
300 for row in [TOP + 40, HEIGHT / 2, BOTTOM - 40] {
301 let edges = crossing(matte.alpha[row * WIDTH..][..WIDTH].iter().copied());
302 assert_eq!(edges.len(), 2, "row {row}: {edges:?}");
303 assert!(edges[0].abs_diff(LEFT) <= 2 && edges[1].abs_diff(RIGHT) <= 2, "row {row}: {edges:?}");
304 }
305 for column in [LEFT + 40, WIDTH / 2, RIGHT - 40] {
306 let edges = crossing((0..HEIGHT).map(|row| matte.alpha[row * WIDTH + column]));
307 assert!(edges.len() == 2 && edges[0].abs_diff(TOP) <= 2 && edges[1].abs_diff(BOTTOM) <= 2, "column {column}: {edges:?}");
308 }
309 }
310
311 #[test]
312 fn a_colour_edge_without_a_brightness_step_still_guides_the_matte() {
313 let mut colour = frame(WIDTH, HEIGHT, |_, _| 120);
314 let stride = colour.strides().1 as usize;
315 let blue = colour.data_mut().1;
316 for row in 0..HEIGHT / 2 {
317 for column in 0..WIDTH / 2 {
318 let inside = (LEFT / 2..RIGHT / 2).contains(&column) && (TOP / 2..BOTTOM / 2).contains(&row);
319 blue[row * stride + column] = if inside { 170 } else { 90 };
320 }
321 }
322 let matte = refine(&blocky_mask(), Planes::of(&colour));
323 let edges = crossing(matte.alpha[HEIGHT / 2 * WIDTH..][..WIDTH].iter().copied());
324 assert!(edges.len() == 2 && edges[0].abs_diff(LEFT) <= 2 && edges[1].abs_diff(RIGHT) <= 2, "{edges:?}");
325 }
326
327 #[test]
328 fn no_background_shows_outside_the_true_edge() {
329 let matte = refine(&blocky_mask(), Planes::of(&square_frame()));
330 let line = &matte.alpha[HEIGHT / 2 * WIDTH..][..WIDTH];
331 assert!(line[..LEFT - 1].iter().chain(&line[RIGHT + 1..]).all(|&alpha| alpha == 0), "{:?} {:?}", &line[LEFT - 8..LEFT + 2], &line[RIGHT - 2..RIGHT + 8]);
332 assert!(line[LEFT + 1..RIGHT - 1].iter().all(|&alpha| alpha > 128), "{:?}", &line[RIGHT - 16..RIGHT]);
333 }
334
335 #[test]
336 fn flat_regions_keep_the_mask_and_halving_averages() {
337 let flat = frame(64, 36, |_, _| 120);
338 let everyone = refine(&vec![1.; MASK_WIDTH * MASK_HEIGHT], Planes::of(&flat));
339 assert!(everyone.alpha.iter().all(|&alpha| alpha == 255));
340 let nobody = refine(&vec![0.; MASK_WIDTH * MASK_HEIGHT], Planes::of(&flat));
341 assert!(nobody.alpha.iter().all(|&alpha| alpha == 0));
342 let halved = Matte { width: 3, height: 2, alpha: vec![0, 255, 255, 0, 255, 255] }.halved();
343 assert_eq!((halved.width, halved.height, halved.alpha), (2, 1, vec![128, 255]));
344 }
345
346 #[test]
347 fn the_box_filter_averages_clamped_windows() {
348 let filtered = box_filter(&[0., 3., 6., 9.], 4, 1, 1);
349 assert_eq!(filtered, vec![1.5, 3., 6., 7.5]);
350 let tall = box_filter(&[0., 3., 6., 9.], 1, 4, 1);
351 assert_eq!(tall, vec![1.5, 3., 6., 7.5]);
352 }
353}