BlueGit

ict rusty-teams

Files

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

matte.rs

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