BlueGit

ict rusty-teams

Files

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

matte.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
matte.rs 21.6 KiB Download Raw
1use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};
2
3use crate::camera::i420_from_rgba;
4use crate::mask::{Axis, Mask, axis};
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 {
31 guide_width: GUIDE_WIDTH,
32 edge_low: MATTE_LOW,
33 edge_high: MATTE_HIGH,
34 sure_person: SURE_PERSON,
35 sure_background: SURE_BACKGROUND,
36 }
37 }
38}
39
40/// Person alpha (0..255) per pixel of a `width` x `height` frame.
41pub struct Matte {
42 pub width: usize,
43 pub height: usize,
44 pub alpha: Vec<u8>,
45}
46
47impl Matte {
48 /// Same matte at half resolution, for 4:2:0 chroma planes.
49 pub fn halved(&self) -> Matte {
50 let (width, height) = (self.width.div_ceil(2), self.height.div_ceil(2));
51 let mut alpha = vec![0u8; width * height];
52 for (row, line) in alpha.chunks_exact_mut(width).enumerate() {
53 let (top, bottom) = (row * 2, (row * 2 + 1).min(self.height - 1));
54 for (column, slot) in line.iter_mut().enumerate() {
55 let (left, right) = (column * 2, (column * 2 + 1).min(self.width - 1));
56 let sum: u32 = [(top, left), (top, right), (bottom, left), (bottom, right)]
57 .iter()
58 .map(|&(y, x)| u32::from(self.alpha[y * self.width + x]))
59 .sum();
60 *slot = ((sum + 2) / 4) as u8;
61 }
62 }
63 Matte {
64 width,
65 height,
66 alpha,
67 }
68 }
69}
70
71/// The 4:2:0 planes of the frame the matte follows.
72#[derive(Clone, Copy)]
73pub struct Planes<'a> {
74 pub luma: &'a [u8],
75 pub luma_stride: usize,
76 pub blue: &'a [u8],
77 pub blue_stride: usize,
78 pub red: &'a [u8],
79 pub red_stride: usize,
80 pub width: usize,
81 pub height: usize,
82}
83
84impl<'a> Planes<'a> {
85 pub fn of(buffer: &'a I420Buffer) -> Planes<'a> {
86 let (luma_stride, blue_stride, red_stride) = buffer.strides();
87 let (luma, blue, red) = buffer.data();
88 Planes {
89 luma,
90 luma_stride: luma_stride as usize,
91 blue,
92 blue_stride: blue_stride as usize,
93 red,
94 red_stride: red_stride as usize,
95 width: buffer.width() as usize,
96 height: buffer.height() as usize,
97 }
98 }
99
100 fn pixel(&self, column: usize, row: usize) -> [f32; CHANNELS] {
101 let chroma = |plane: &[u8], stride: usize| {
102 (f32::from(plane[row / 2 * stride + column / 2]) - 128.) * CHROMA_WEIGHT / 255.
103 };
104 [
105 f32::from(self.luma[row * self.luma_stride + column]) / 255.,
106 chroma(self.blue, self.blue_stride),
107 chroma(self.red, self.red_stride),
108 ]
109 }
110}
111
112fn ramp(value: f32, start: f32) -> f32 {
113 ((value - start) / CERTAINTY_RAMP).clamp(0., 1.)
114}
115
116fn edge_curve(value: f32, settings: &RefineSettings) -> f32 {
117 let t = ((value - settings.edge_low) / (settings.edge_high - settings.edge_low)).clamp(0., 1.);
118 t * t * (3. - 2. * t)
119}
120
121pub(crate) fn box_filter(input: &[f32], width: usize, height: usize, radius: usize) -> Vec<f32> {
122 let mut across = vec![0f32; input.len()];
123 let mut prefix = vec![0f32; width + 1];
124 for (line, output) in input
125 .chunks_exact(width)
126 .zip(across.chunks_exact_mut(width))
127 {
128 for (index, &value) in line.iter().enumerate() {
129 prefix[index + 1] = prefix[index] + value;
130 }
131 for (index, slot) in output.iter_mut().enumerate() {
132 let (low, high) = (
133 index.saturating_sub(radius),
134 (index + radius + 1).min(width),
135 );
136 *slot = (prefix[high] - prefix[low]) / (high - low) as f32;
137 }
138 }
139 let mut output = vec![0f32; input.len()];
140 let mut sums = vec![0f32; width];
141 for line in across.chunks_exact(width).take(radius.min(height)) {
142 sums.iter_mut()
143 .zip(line)
144 .for_each(|(sum, value)| *sum += value);
145 }
146 for row in 0..height {
147 if row + radius < height {
148 sums.iter_mut()
149 .zip(&across[(row + radius) * width..][..width])
150 .for_each(|(sum, value)| *sum += value);
151 }
152 if row > radius {
153 sums.iter_mut()
154 .zip(&across[(row - radius - 1) * width..][..width])
155 .for_each(|(sum, value)| *sum -= value);
156 }
157 let count = ((row + radius + 1).min(height) - row.saturating_sub(radius)) as f32;
158 output[row * width..][..width]
159 .iter_mut()
160 .zip(&sums)
161 .for_each(|(slot, sum)| *slot = sum / count);
162 }
163 output
164}
165
166fn cell_means(
167 plane: &[u8],
168 stride: usize,
169 subsampling: usize,
170 (plane_width, plane_height): (usize, usize),
171 factor: usize,
172 (small_width, small_height): (usize, usize),
173) -> Vec<f32> {
174 let span = |cell: usize, limit: usize| {
175 let first = (cell * factor / subsampling).min(limit - 1);
176 first
177 ..((cell + 1) * factor)
178 .div_ceil(subsampling)
179 .clamp(first + 1, limit)
180 };
181 let columns: Vec<_> = (0..small_width)
182 .map(|column| span(column, plane_width))
183 .collect();
184 let mut means = Vec::with_capacity(small_width * small_height);
185 let mut sums = vec![0u32; plane_width];
186 for row in 0..small_height {
187 let rows = span(row, plane_height);
188 sums.fill(0);
189 for line in rows.clone() {
190 sums.iter_mut()
191 .zip(&plane[line * stride..][..plane_width])
192 .for_each(|(sum, &value)| *sum += u32::from(value));
193 }
194 for range in &columns {
195 means.push(
196 sums[range.clone()].iter().sum::<u32>() as f32 / (rows.len() * range.len()) as f32,
197 );
198 }
199 }
200 means
201}
202
203fn small_guide(planes: &Planes, factor: usize) -> ([Vec<f32>; CHANNELS], usize, usize) {
204 let small = (
205 planes.width.div_ceil(factor),
206 planes.height.div_ceil(factor),
207 );
208 let chroma = (planes.width.div_ceil(2), planes.height.div_ceil(2));
209 let luma = cell_means(
210 planes.luma,
211 planes.luma_stride,
212 1,
213 (planes.width, planes.height),
214 factor,
215 small,
216 )
217 .into_iter()
218 .map(|value| value / 255.)
219 .collect();
220 let colour = |plane: &[u8], stride: usize| {
221 cell_means(plane, stride, 2, chroma, factor, small)
222 .into_iter()
223 .map(|value| (value - 128.) * CHROMA_WEIGHT / 255.)
224 .collect()
225 };
226 (
227 [
228 luma,
229 colour(planes.blue, planes.blue_stride),
230 colour(planes.red, planes.red_stride),
231 ],
232 small.0,
233 small.1,
234 )
235}
236
237struct Coefficients {
238 slope: [Vec<f32>; CHANNELS],
239 offset: Vec<f32>,
240 width: usize,
241}
242
243fn solve(covariance: [[f32; CHANNELS]; CHANNELS], target: [f32; CHANNELS]) -> [f32; CHANNELS] {
244 let [[a, b, c], [_, d, e], [_, _, f]] = covariance;
245 let cofactors = [
246 [d * f - e * e, c * e - b * f, b * e - c * d],
247 [c * e - b * f, a * f - c * c, b * c - a * e],
248 [b * e - c * d, b * c - a * e, a * d - b * b],
249 ];
250 let determinant = a * cofactors[0][0] + b * cofactors[0][1] + c * cofactors[0][2];
251 std::array::from_fn(|row| {
252 (0..CHANNELS)
253 .map(|column| cofactors[row][column] * target[column])
254 .sum::<f32>()
255 / determinant
256 })
257}
258
259fn coefficients(
260 guide: &[Vec<f32>; CHANNELS],
261 person: &[f32],
262 width: usize,
263 height: usize,
264) -> Coefficients {
265 let mean = |values: Vec<f32>| box_filter(&values, width, height, FILTER_RADIUS);
266 let mean_guide: [Vec<f32>; CHANNELS] =
267 std::array::from_fn(|channel| mean(guide[channel].clone()));
268 let mean_person = mean(person.to_vec());
269 let mean_product: [Vec<f32>; CHANNELS] = std::array::from_fn(|channel| {
270 mean(
271 guide[channel]
272 .iter()
273 .zip(person)
274 .map(|(guide, person)| guide * person)
275 .collect(),
276 )
277 });
278 let pairs = [(0, 0), (0, 1), (0, 2), (1, 1), (1, 2), (2, 2)];
279 let mean_pair: Vec<Vec<f32>> = pairs
280 .iter()
281 .map(|&(first, second)| {
282 mean(
283 guide[first]
284 .iter()
285 .zip(&guide[second])
286 .map(|(first, second)| first * second)
287 .collect(),
288 )
289 })
290 .collect();
291 let mut slope: [Vec<f32>; CHANNELS] = std::array::from_fn(|_| vec![0f32; person.len()]);
292 let mut offset = vec![0f32; person.len()];
293 for index in 0..person.len() {
294 let mut covariance = [[0f32; CHANNELS]; CHANNELS];
295 for (&(first, second), pair) in pairs.iter().zip(&mean_pair) {
296 let value = pair[index] - mean_guide[first][index] * mean_guide[second][index]
297 + if first == second { FILTER_EPSILON } else { 0. };
298 covariance[first][second] = value;
299 covariance[second][first] = value;
300 }
301 let target = std::array::from_fn(|channel| {
302 mean_product[channel][index] - mean_guide[channel][index] * mean_person[index]
303 });
304 let solution = solve(covariance, target);
305 offset[index] = mean_person[index]
306 - (0..CHANNELS)
307 .map(|channel| solution[channel] * mean_guide[channel][index])
308 .sum::<f32>();
309 for channel in 0..CHANNELS {
310 slope[channel][index] = solution[channel];
311 }
312 }
313 Coefficients {
314 slope: slope.map(mean),
315 offset: mean(offset),
316 width,
317 }
318}
319
320struct Upsampler<'a> {
321 settings: RefineSettings,
322 coefficients: &'a Coefficients,
323 prior: &'a [f32],
324 planes: Planes<'a>,
325 across: Axis,
326 down: Axis,
327}
328
329impl Upsampler<'_> {
330 fn rows(&self, alpha: &mut [u8], first_row: usize) {
331 let small_width = self.coefficients.width;
332 let mut lines = vec![[0f32; CHANNELS + 2]; small_width];
333 for (offset, line) in alpha.chunks_exact_mut(self.planes.width).enumerate() {
334 let row = first_row + offset;
335 let (top, bottom, vertical) = (
336 self.down.first[row] * small_width,
337 self.down.second[row] * small_width,
338 self.down.weight[row],
339 );
340 let blend = |grid: &[f32], column: usize| {
341 grid[top + column] * (1. - vertical) + grid[bottom + column] * vertical
342 };
343 for (column, slot) in lines.iter_mut().enumerate() {
344 *slot = [
345 blend(&self.coefficients.slope[0], column),
346 blend(&self.coefficients.slope[1], column),
347 blend(&self.coefficients.slope[2], column),
348 blend(&self.coefficients.offset, column),
349 blend(self.prior, column),
350 ];
351 }
352 for (column, slot) in line.iter_mut().enumerate() {
353 let (left, right, horizontal) = (
354 &lines[self.across.first[column]],
355 &lines[self.across.second[column]],
356 self.across.weight[column],
357 );
358 let at = |index: usize| left[index] * (1. - horizontal) + right[index] * horizontal;
359 let prior = at(4);
360 let (floor, ceiling) = (
361 ramp(prior, self.settings.sure_person),
362 ramp(prior, self.settings.sure_background - CERTAINTY_RAMP),
363 );
364 if floor >= 1. || ceiling <= 0. {
365 *slot = if floor >= 1. { u8::MAX } else { 0 };
366 continue;
367 }
368 let guide = self.planes.pixel(column, row);
369 let person = at(0) * guide[0] + at(1) * guide[1] + at(2) * guide[2] + at(3);
370 *slot =
371 (edge_curve(person, &self.settings).max(floor).min(ceiling) * 255. + 0.5) as u8;
372 }
373 }
374 }
375}
376
377/// Snaps the low-resolution `mask` to the colour edges of the full-resolution frame with a fast colour guided filter.
378pub fn refine(mask: &Mask, planes: Planes) -> Matte {
379 refine_with(mask, planes, RefineSettings::default())
380}
381
382pub fn refine_with(mask: &Mask, planes: Planes, settings: RefineSettings) -> Matte {
383 let (width, height) = (planes.width, planes.height);
384 if mask.matte {
385 return upscaled(mask, width, height);
386 }
387 let factor = (width / settings.guide_width).max(1);
388 let (guide, small_width, small_height) = small_guide(&planes, factor);
389 let prior = mask.resampled(small_width, small_height);
390 let coefficients = coefficients(&guide, &prior, small_width, small_height);
391 let upsampler = Upsampler {
392 settings,
393 coefficients: &coefficients,
394 prior: &prior,
395 planes,
396 across: axis(width, small_width),
397 down: axis(height, small_height),
398 };
399 let mut alpha = vec![0u8; width * height];
400 let bands = std::thread::available_parallelism()
401 .map_or(1, usize::from)
402 .min(MAX_BANDS);
403 let rows_per_band = height.div_ceil(bands);
404 std::thread::scope(|scope| {
405 for (index, band) in alpha.chunks_mut(rows_per_band * width).enumerate() {
406 let upsampler = &upsampler;
407 scope.spawn(move || upsampler.rows(band, index * rows_per_band));
408 }
409 });
410 Matte {
411 width,
412 height,
413 alpha,
414 }
415}
416
417/// A matting model's alpha already follows hair and edges; bilinear scaling keeps it, a guided filter only costs time.
418fn upscaled(mask: &Mask, width: usize, height: usize) -> Matte {
419 let (across, down) = (axis(width, mask.width), axis(height, mask.height));
420 let mut alpha = vec![0u8; width * height];
421 let bands = std::thread::available_parallelism()
422 .map_or(1, usize::from)
423 .min(MAX_BANDS);
424 let rows_per_band = height.div_ceil(bands);
425 std::thread::scope(|scope| {
426 for (index, band) in alpha.chunks_mut(rows_per_band * width).enumerate() {
427 let (across, down) = (&across, &down);
428 scope.spawn(move || {
429 for (offset, line) in band.chunks_exact_mut(width).enumerate() {
430 let row = index * rows_per_band + offset;
431 let (top, bottom, vertical) = (
432 down.first[row] * mask.width,
433 down.second[row] * mask.width,
434 down.weight[row],
435 );
436 for (column, slot) in line.iter_mut().enumerate() {
437 let (left, right, horizontal) = (
438 across.first[column],
439 across.second[column],
440 across.weight[column],
441 );
442 let upper = mask.values[top + left] * (1. - horizontal)
443 + mask.values[top + right] * horizontal;
444 let lower = mask.values[bottom + left] * (1. - horizontal)
445 + mask.values[bottom + right] * horizontal;
446 *slot = ((upper * (1. - vertical) + lower * vertical) * 255. + 0.5) as u8;
447 }
448 }
449 });
450 }
451 });
452 Matte {
453 width,
454 height,
455 alpha,
456 }
457}
458
459pub fn refine_rgba(mask: &Mask, rgba: &[u8], width: usize, height: usize) -> Matte {
460 refine(
461 mask,
462 Planes::of(&i420_from_rgba(rgba, width as u32, height as u32)),
463 )
464}
465
466#[cfg(test)]
467mod tests {
468 use super::*;
469
470 const MASK_WIDTH: usize = 256;
471 const MASK_HEIGHT: usize = 144;
472 const WIDTH: usize = 1280;
473 const HEIGHT: usize = 720;
474 const LEFT: usize = 403;
475 const RIGHT: usize = 877;
476 const TOP: usize = 161;
477 const BOTTOM: usize = 598;
478 const BLOCK: usize = 3;
479
480 fn frame(width: usize, height: usize, luma: impl Fn(usize, usize) -> u8) -> I420Buffer {
481 let mut buffer = I420Buffer::new(width as u32, height as u32);
482 let stride = buffer.strides().0 as usize;
483 let (plane_y, plane_u, plane_v) = buffer.data_mut();
484 for row in 0..height {
485 for column in 0..width {
486 plane_y[row * stride + column] = luma(column, row);
487 }
488 }
489 plane_u.fill(128);
490 plane_v.fill(128);
491 buffer
492 }
493
494 fn square_frame() -> I420Buffer {
495 frame(WIDTH, HEIGHT, |column, row| {
496 if (LEFT..RIGHT).contains(&column) && (TOP..BOTTOM).contains(&row) {
497 200
498 } else {
499 50
500 }
501 })
502 }
503
504 fn blocky_mask() -> Mask {
505 let values = (0..MASK_WIDTH * MASK_HEIGHT)
506 .map(|index| {
507 let (block_column, block_row) = (
508 (index % MASK_WIDTH) / BLOCK * BLOCK,
509 (index / MASK_WIDTH) / BLOCK * BLOCK,
510 );
511 let center_x =
512 (block_column as f32 + BLOCK as f32 / 2.) * WIDTH as f32 / MASK_WIDTH as f32;
513 let center_y =
514 (block_row as f32 + BLOCK as f32 / 2.) * HEIGHT as f32 / MASK_HEIGHT as f32;
515 let inside = (LEFT as f32..RIGHT as f32).contains(&center_x)
516 && (TOP as f32..BOTTOM as f32).contains(&center_y);
517 if inside { 0.9 } else { 0.1 }
518 })
519 .collect();
520 Mask::new(MASK_WIDTH, MASK_HEIGHT, values)
521 }
522
523 fn crossing(values: impl Iterator<Item = u8>) -> Vec<usize> {
524 let values: Vec<u8> = values.collect();
525 values
526 .windows(2)
527 .enumerate()
528 .filter(|(_, pair)| (pair[0] < 128) != (pair[1] < 128))
529 .map(|(index, _)| index + 1)
530 .collect()
531 }
532
533 #[test]
534 fn a_blocky_mask_snaps_to_the_sharp_edge_of_the_frame() {
535 let matte = refine(&blocky_mask(), Planes::of(&square_frame()));
536 for row in [TOP + 40, HEIGHT / 2, BOTTOM - 40] {
537 let edges = crossing(matte.alpha[row * WIDTH..][..WIDTH].iter().copied());
538 assert_eq!(edges.len(), 2, "row {row}: {edges:?}");
539 assert!(
540 edges[0].abs_diff(LEFT) <= 2 && edges[1].abs_diff(RIGHT) <= 2,
541 "row {row}: {edges:?}"
542 );
543 }
544 for column in [LEFT + 40, WIDTH / 2, RIGHT - 40] {
545 let edges = crossing((0..HEIGHT).map(|row| matte.alpha[row * WIDTH + column]));
546 assert!(
547 edges.len() == 2 && edges[0].abs_diff(TOP) <= 2 && edges[1].abs_diff(BOTTOM) <= 2,
548 "column {column}: {edges:?}"
549 );
550 }
551 }
552
553 #[test]
554 fn a_colour_edge_without_a_brightness_step_still_guides_the_matte() {
555 let mut colour = frame(WIDTH, HEIGHT, |_, _| 120);
556 let stride = colour.strides().1 as usize;
557 let blue = colour.data_mut().1;
558 for row in 0..HEIGHT / 2 {
559 for column in 0..WIDTH / 2 {
560 let inside =
561 (LEFT / 2..RIGHT / 2).contains(&column) && (TOP / 2..BOTTOM / 2).contains(&row);
562 blue[row * stride + column] = if inside { 170 } else { 90 };
563 }
564 }
565 let matte = refine(&blocky_mask(), Planes::of(&colour));
566 let edges = crossing(matte.alpha[HEIGHT / 2 * WIDTH..][..WIDTH].iter().copied());
567 assert!(
568 edges.len() == 2 && edges[0].abs_diff(LEFT) <= 2 && edges[1].abs_diff(RIGHT) <= 2,
569 "{edges:?}"
570 );
571 }
572
573 #[test]
574 fn no_background_shows_outside_the_true_edge() {
575 let matte = refine(&blocky_mask(), Planes::of(&square_frame()));
576 let line = &matte.alpha[HEIGHT / 2 * WIDTH..][..WIDTH];
577 assert!(
578 line[..LEFT - 1]
579 .iter()
580 .chain(&line[RIGHT + 1..])
581 .all(|&alpha| alpha == 0),
582 "{:?} {:?}",
583 &line[LEFT - 8..LEFT + 2],
584 &line[RIGHT - 2..RIGHT + 8]
585 );
586 assert!(
587 line[LEFT + 1..RIGHT - 1].iter().all(|&alpha| alpha > 128),
588 "{:?}",
589 &line[RIGHT - 16..RIGHT]
590 );
591 }
592
593 #[test]
594 fn flat_regions_keep_the_mask_and_halving_averages() {
595 let flat = frame(64, 36, |_, _| 120);
596 let everyone = refine(
597 &Mask::filled(MASK_WIDTH, MASK_HEIGHT, 1.),
598 Planes::of(&flat),
599 );
600 assert!(everyone.alpha.iter().all(|&alpha| alpha == 255));
601 let nobody = refine(
602 &Mask::filled(MASK_WIDTH, MASK_HEIGHT, 0.),
603 Planes::of(&flat),
604 );
605 assert!(nobody.alpha.iter().all(|&alpha| alpha == 0));
606 let step = Mask::new(2, 1, vec![0., 1.]).into_matte();
607 let upscaled = refine(&step, Planes::of(&frame(4, 2, |_, _| 120)));
608 assert_eq!(&upscaled.alpha[..4], &[0, 64, 191, 255]);
609 let halved = Matte {
610 width: 3,
611 height: 2,
612 alpha: vec![0, 255, 255, 0, 255, 255],
613 }
614 .halved();
615 assert_eq!(
616 (halved.width, halved.height, halved.alpha),
617 (2, 1, vec![128, 255])
618 );
619 }
620
621 #[test]
622 fn the_box_filter_averages_clamped_windows() {
623 let filtered = box_filter(&[0., 3., 6., 9.], 4, 1, 1);
624 assert_eq!(filtered, vec![1.5, 3., 6., 7.5]);
625 let tall = box_filter(&[0., 3., 6., 9.], 1, 4, 1);
626 assert_eq!(tall, vec![1.5, 3., 6., 7.5]);
627 }
628}