BlueGit

ict rusty-teams

Files

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

motion.rs

motion.rs 16.7 KiB Download Raw
1use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};
2
3use crate::mask::{Mask, axis};
4
5pub const GRID_WIDTH: usize = 160;
6const BLOCK: usize = 4;
7const WINDOW: usize = 8;
8const COARSE_REACH: isize = 4;
9const FINE_REACH: isize = 1;
10const MOTION_COST: f32 = 0.4;
11const PERSON_SHARE: f32 = 0.2;
12const MAX_BANDS: usize = 4;
13
14/// Mean luma (0..255) on a grid about `GRID_WIDTH` cells wide; the frame a mask was made from and the frame it is shown on are compared on it.
15#[derive(Clone, Debug, Default, PartialEq)]
16pub struct LumaGrid {
17 pub width: usize,
18 pub height: usize,
19 pub values: Vec<f32>,
20}
21
22impl LumaGrid {
23 pub fn of(buffer: &I420Buffer) -> LumaGrid {
24 LumaGrid::of_plane(buffer.data().0, buffer.strides().0 as usize, buffer.width() as usize, buffer.height() as usize)
25 }
26
27 pub fn of_plane(plane: &[u8], stride: usize, width: usize, height: usize) -> LumaGrid {
28 let factor = (width / GRID_WIDTH).max(1);
29 let (grid_width, grid_height) = (width / factor, height / factor);
30 let mut values = vec![0f32; grid_width * grid_height];
31 let mut sums = vec![0u32; grid_width];
32 let scale = 1. / (factor * factor) as f32;
33 for (row, line) in values.chunks_exact_mut(grid_width).enumerate() {
34 sums.fill(0);
35 for source_row in row * factor..(row + 1) * factor {
36 for (sum, group) in sums.iter_mut().zip(plane[source_row * stride..][..grid_width * factor].chunks_exact(factor)) {
37 *sum += group.iter().map(|&value| u32::from(value)).sum::<u32>();
38 }
39 }
40 for (slot, &sum) in line.iter_mut().zip(&sums) {
41 *slot = sum as f32 * scale;
42 }
43 }
44 LumaGrid { width: grid_width, height: grid_height, values }
45 }
46
47 pub fn is_empty(&self) -> bool {
48 self.values.is_empty()
49 }
50
51 fn halved(&self) -> LumaGrid {
52 let (width, height) = (self.width / 2, self.height / 2);
53 let mut values = Vec::with_capacity(width * height);
54 for row in 0..height {
55 for column in 0..width {
56 let at = |y: usize, x: usize| self.values[(row * 2 + y) * self.width + column * 2 + x];
57 values.push((at(0, 0) + at(0, 1) + at(1, 0) + at(1, 1)) / 4.);
58 }
59 }
60 LumaGrid { width, height, values }
61 }
62
63 fn at(&self, column: isize, row: isize) -> f32 {
64 let column = column.clamp(0, self.width as isize - 1) as usize;
65 let row = row.clamp(0, self.height as isize - 1) as usize;
66 self.values[row * self.width + column]
67 }
68}
69
70/// Where each block of the current frame was in the reference frame, in grid cells.
71#[derive(Clone, Debug, PartialEq)]
72pub struct Flow {
73 pub columns: usize,
74 pub rows: usize,
75 pub grid_width: usize,
76 pub grid_height: usize,
77 pub offsets: Vec<(f32, f32)>,
78}
79
80impl Flow {
81 pub fn is_still(&self) -> bool {
82 self.offsets.iter().all(|&(across, down)| across == 0. && down == 0.)
83 }
84}
85
86struct Level<'a> {
87 reference: &'a LumaGrid,
88 current: &'a LumaGrid,
89 person: Option<&'a LumaGrid>,
90}
91
92impl Level<'_> {
93 fn fits(grid: &LumaGrid, (left, top): (isize, isize), size: isize) -> bool {
94 left >= 0 && top >= 0 && left + size <= grid.width as isize && top + size <= grid.height as isize
95 }
96
97 /// Mean difference; where the reference mask shows the person, only person pixels count, so blocks on the edge follow the person instead of the still background.
98 fn cost(&self, (left, top): (isize, isize), size: isize, (across, down): (isize, isize)) -> f32 {
99 let (mut plain, mut weighted, mut weight) = (0f32, 0f32, 0f32);
100 if Self::fits(self.current, (left, top), size) && Self::fits(self.reference, (left + across, top + down), size) {
101 let length = size as usize;
102 for row in top..top + size {
103 let now = &self.current.values[row as usize * self.current.width + left as usize..][..length];
104 let source = (row + down) as usize * self.reference.width + (left + across) as usize;
105 let before = &self.reference.values[source..][..length];
106 match self.person {
107 Some(person) => {
108 for ((now, before), share) in now.iter().zip(before).zip(&person.values[source..][..length]) {
109 let difference = (now - before).abs();
110 plain += difference;
111 weighted += difference * share;
112 weight += share;
113 }
114 }
115 None => plain += now.iter().zip(before).map(|(now, before)| (now - before).abs()).sum::<f32>(),
116 }
117 }
118 } else {
119 for row in top..top + size {
120 for column in left..left + size {
121 let difference = (self.current.at(column, row) - self.reference.at(column + across, row + down)).abs();
122 let share = self.person.map_or(0., |person| person.at(column + across, row + down));
123 plain += difference;
124 weighted += difference * share;
125 weight += share;
126 }
127 }
128 }
129 let count = (size * size) as f32;
130 let mean = if weight >= PERSON_SHARE * count { weighted / weight } else { plain / count };
131 mean + MOTION_COST * (across.abs() + down.abs()) as f32
132 }
133
134 fn best_offset(&self, corner: (isize, isize), size: isize, centre: (isize, isize), reach: isize) -> ((isize, isize), f32) {
135 let mut best = (centre, f32::MAX);
136 for down in centre.1 - reach..=centre.1 + reach {
137 for across in centre.0 - reach..=centre.0 + reach {
138 let value = self.cost(corner, size, (across, down));
139 if value < best.1 {
140 best = ((across, down), value);
141 }
142 }
143 }
144 best
145 }
146}
147
148fn parabola(before: f32, at: f32, after: f32) -> f32 {
149 let curvature = before - 2. * at + after;
150 if curvature <= f32::EPSILON { 0. } else { ((before - after) / (2. * curvature)).clamp(-0.5, 0.5) }
151}
152
153fn median_of_nine(values: &mut [f32]) -> f32 {
154 values.sort_by(f32::total_cmp);
155 values[values.len() / 2]
156}
157
158fn median_filtered(offsets: &[(f32, f32)], columns: usize, rows: usize) -> Vec<(f32, f32)> {
159 let mut output = Vec::with_capacity(offsets.len());
160 let (mut across, mut down) = (Vec::with_capacity(9), Vec::with_capacity(9));
161 for row in 0..rows {
162 for column in 0..columns {
163 across.clear();
164 down.clear();
165 for neighbour_row in row.saturating_sub(1)..(row + 2).min(rows) {
166 for neighbour_column in column.saturating_sub(1)..(column + 2).min(columns) {
167 let (x, y) = offsets[neighbour_row * columns + neighbour_column];
168 across.push(x);
169 down.push(y);
170 }
171 }
172 output.push((median_of_nine(&mut across), median_of_nine(&mut down)));
173 }
174 }
175 output
176}
177
178fn band_offsets(fine: &Level, coarse: &Level, columns: usize, rows: std::ops::Range<usize>) -> Vec<(f32, f32)> {
179 let half_window = (WINDOW / 2) as isize;
180 let size = WINDOW as isize;
181 let mut offsets: Vec<(f32, f32)> = Vec::with_capacity(columns * rows.len());
182 let first_row = rows.start;
183 for row in rows {
184 for column in 0..columns {
185 let centre = ((column * BLOCK + BLOCK / 2) as isize, (row * BLOCK + BLOCK / 2) as isize);
186 let coarse_corner = (centre.0 / 2 - half_window / 2, centre.1 / 2 - half_window / 2);
187 let ((coarse_across, coarse_down), _) = coarse.best_offset(coarse_corner, half_window, (0, 0), COARSE_REACH);
188 let corner = (centre.0 - half_window, centre.1 - half_window);
189 let neighbour = |index: Option<usize>| {
190 index.map(|index: usize| -> (isize, isize) {
191 let (across, down) = offsets[index];
192 (across.round() as isize, down.round() as isize)
193 })
194 };
195 let left = neighbour((column > 0).then(|| offsets.len() - 1));
196 let above = neighbour((row > first_row).then(|| offsets.len() - columns));
197 let (found, found_cost) = [Some((coarse_across * 2, coarse_down * 2)), left, above]
198 .into_iter()
199 .flatten()
200 .map(|start| fine.best_offset(corner, size, start, FINE_REACH))
201 .min_by(|first, second| first.1.total_cmp(&second.1))
202 .expect("the coarse guess is always there");
203 if fine.cost(corner, size, (0, 0)) <= found_cost {
204 offsets.push((0., 0.));
205 continue;
206 }
207 let sample = |across: isize, down: isize| fine.cost(corner, size, (found.0 + across, found.1 + down));
208 let fine_across = parabola(sample(-1, 0), found_cost, sample(1, 0));
209 let fine_down = parabola(sample(0, -1), found_cost, sample(0, 1));
210 offsets.push((found.0 as f32 + fine_across, found.1 as f32 + fine_down));
211 }
212 }
213 offsets
214}
215
216/// Block matching, coarse to fine with a sub-cell fit; a small cost per cell of motion keeps flat and still areas at zero.
217/// `person` is the mask of the reference frame; it may be empty.
218pub fn estimate(reference: &LumaGrid, current: &LumaGrid, person: &Mask) -> Option<Flow> {
219 if reference.is_empty() || (reference.width, reference.height) != (current.width, current.height) || current.width < WINDOW * 2 || current.height < WINDOW * 2 {
220 return None;
221 }
222 let person = (!person.is_empty()).then(|| LumaGrid { width: reference.width, height: reference.height, values: person.resampled(reference.width, reference.height) });
223 let coarse_person = person.as_ref().map(LumaGrid::halved);
224 let (coarse_reference, coarse_current) = (reference.halved(), current.halved());
225 let fine = Level { reference, current, person: person.as_ref() };
226 let coarse = Level { reference: &coarse_reference, current: &coarse_current, person: coarse_person.as_ref() };
227 let (columns, rows) = (current.width.div_ceil(BLOCK), current.height.div_ceil(BLOCK));
228 let bands = std::thread::available_parallelism().map_or(1, usize::from).min(MAX_BANDS);
229 let rows_per_band = rows.div_ceil(bands);
230 let offsets: Vec<(f32, f32)> = std::thread::scope(|scope| {
231 let (fine, coarse) = (&fine, &coarse);
232 let workers: Vec<_> = (0..rows).step_by(rows_per_band).map(|first| scope.spawn(move || band_offsets(fine, coarse, columns, first..(first + rows_per_band).min(rows)))).collect();
233 workers.into_iter().flat_map(|worker| worker.join().expect("block matching band")).collect()
234 });
235 let offsets = median_filtered(&offsets, columns, rows);
236 Some(Flow { columns, rows, grid_width: current.width, grid_height: current.height, offsets })
237}
238
239fn sample(mask: &Mask, column: f32, row: f32) -> f32 {
240 let column = column.clamp(0., (mask.width - 1) as f32);
241 let row = row.clamp(0., (mask.height - 1) as f32);
242 let (left, top) = (column.floor() as usize, row.floor() as usize);
243 let (right, bottom) = ((left + 1).min(mask.width - 1), (top + 1).min(mask.height - 1));
244 let (horizontal, vertical) = (column - left as f32, row - top as f32);
245 let at = |x: usize, y: usize| mask.values[y * mask.width + x];
246 let upper = at(left, top) * (1. - horizontal) + at(right, top) * horizontal;
247 let lower = at(left, bottom) * (1. - horizontal) + at(right, bottom) * horizontal;
248 upper * (1. - vertical) + lower * vertical
249}
250
251/// Moves the mask along `flow`: every cell takes the value from where its content was in the reference frame.
252pub fn warp(mask: &Mask, flow: &Flow) -> Mask {
253 if mask.is_empty() || flow.is_still() {
254 return mask.clone();
255 }
256 let block_axis = |cells: usize, blocks: usize, grid: usize| {
257 let mut positions = axis(cells, blocks);
258 for index in 0..cells {
259 let grid_position = (index as f32 + 0.5) * grid as f32 / cells as f32 - 0.5;
260 let block_position = ((grid_position - (BLOCK / 2) as f32 + 0.5) / BLOCK as f32).clamp(0., (blocks - 1) as f32);
261 positions.first[index] = block_position.floor() as usize;
262 positions.second[index] = (positions.first[index] + 1).min(blocks - 1);
263 positions.weight[index] = block_position - positions.first[index] as f32;
264 }
265 positions
266 };
267 let (across, down) = (block_axis(mask.width, flow.columns, flow.grid_width), block_axis(mask.height, flow.rows, flow.grid_height));
268 let (scale_across, scale_down) = (mask.width as f32 / flow.grid_width as f32, mask.height as f32 / flow.grid_height as f32);
269 let mut values = Vec::with_capacity(mask.values.len());
270 for row in 0..mask.height {
271 let (top, bottom, vertical) = (down.first[row] * flow.columns, down.second[row] * flow.columns, down.weight[row]);
272 for column in 0..mask.width {
273 let (left, right, horizontal) = (across.first[column], across.second[column], across.weight[column]);
274 let blend = |pick: fn(&(f32, f32)) -> f32| {
275 let upper = pick(&flow.offsets[top + left]) * (1. - horizontal) + pick(&flow.offsets[top + right]) * horizontal;
276 let lower = pick(&flow.offsets[bottom + left]) * (1. - horizontal) + pick(&flow.offsets[bottom + right]) * horizontal;
277 upper * (1. - vertical) + lower * vertical
278 };
279 let (offset_across, offset_down) = (blend(|offset| offset.0), blend(|offset| offset.1));
280 values.push(sample(mask, column as f32 + offset_across * scale_across, row as f32 + offset_down * scale_down));
281 }
282 }
283 Mask { width: mask.width, height: mask.height, values, matte: mask.matte }
284}
285
286/// The mask of `reference`, moved to where the person is in `current`.
287pub fn propagate(mask: &Mask, reference: &LumaGrid, current: &LumaGrid) -> Mask {
288 propagate_for_display(mask, reference, current).0
289}
290
291/// Like `propagate`, and answers whether anything moved; a moved matte has lost its exact edges and wants the guided filter again.
292pub fn propagate_for_display(mask: &Mask, reference: &LumaGrid, current: &LumaGrid) -> (Mask, bool) {
293 match estimate(reference, current, mask) {
294 Some(flow) if !flow.is_still() => (warp(mask, &flow), true),
295 _ => (mask.clone(), false),
296 }
297}
298
299#[cfg(test)]
300mod tests {
301 use super::*;
302
303 const WIDTH: usize = 160;
304 const HEIGHT: usize = 90;
305
306 fn texture(column: isize, row: isize) -> f32 {
307 let hash = (column.wrapping_mul(73_856_093) ^ row.wrapping_mul(19_349_663)).rem_euclid(97) as f32;
308 40. + hash * 1.5
309 }
310
311 fn scene(shift: isize) -> (LumaGrid, Mask) {
312 let inside = |column: isize, row: isize| (60 + shift..100 + shift).contains(&column) && (20..80).contains(&row);
313 let mut values = Vec::with_capacity(WIDTH * HEIGHT);
314 let mut person = Vec::with_capacity(WIDTH * HEIGHT);
315 for row in 0..HEIGHT as isize {
316 for column in 0..WIDTH as isize {
317 let person_here = inside(column, row);
318 values.push(if person_here { 60. + texture(column - shift, row) } else { texture(column / 3, row / 3) });
319 person.push(if person_here { 1. } else { 0. });
320 }
321 }
322 (LumaGrid { width: WIDTH, height: HEIGHT, values }, Mask::new(WIDTH, HEIGHT, person))
323 }
324
325 fn error(mask: &Mask, truth: &Mask) -> f32 {
326 mask.values.iter().zip(&truth.values).map(|(value, truth)| (value - truth).abs()).sum()
327 }
328
329 #[test]
330 fn a_still_frame_keeps_the_mask_as_it_is() {
331 let (grid, mask) = scene(0);
332 let flow = estimate(&grid, &grid, &mask).expect("same size");
333 assert!(flow.is_still());
334 assert_eq!(propagate(&mask, &grid, &grid), mask);
335 }
336
337 #[test]
338 fn the_mask_follows_the_person_to_the_current_frame() {
339 let (reference, mask) = scene(0);
340 for shift in [3, 6, -5] {
341 let (current, truth) = scene(shift);
342 let moved = propagate(&mask, &reference, &current);
343 assert!(error(&moved, &truth) * 4. < error(&mask, &truth), "shift {shift}: {} vs stale {}", error(&moved, &truth), error(&mask, &truth));
344 }
345 }
346
347 #[test]
348 fn the_grid_averages_cells_of_the_frame() {
349 let width = 320;
350 let plane: Vec<u8> = (0..width * 4).map(|index| if index % width < 2 { 100 } else { 0 }).collect();
351 let grid = LumaGrid::of_plane(&plane, width, width, 4);
352 assert_eq!((grid.width, grid.height), (160, 2));
353 assert_eq!(grid.values[0], 100.);
354 assert_eq!(grid.values[1], 0.);
355 }
356
357 #[test]
358 fn different_sizes_leave_the_mask_alone() {
359 let (reference, mask) = scene(0);
360 assert!(estimate(&reference, &LumaGrid::default(), &mask).is_none());
361 assert_eq!(propagate(&mask, &LumaGrid::default(), &reference), mask);
362 }
363}