| 1 | use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _}; |
| 2 | |
| 3 | use crate::mask::{Mask, axis}; |
| 4 | |
| 5 | pub const GRID_WIDTH: usize = 160; |
| 6 | const BLOCK: usize = 4; |
| 7 | const WINDOW: usize = 8; |
| 8 | const COARSE_REACH: isize = 4; |
| 9 | const FINE_REACH: isize = 1; |
| 10 | const MOTION_COST: f32 = 0.4; |
| 11 | const PERSON_SHARE: f32 = 0.2; |
| 12 | const 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)] |
| 16 | pub struct LumaGrid { |
| 17 | pub width: usize, |
| 18 | pub height: usize, |
| 19 | pub values: Vec<f32>, |
| 20 | } |
| 21 | |
| 22 | impl LumaGrid { |
| 23 | pub fn of(buffer: &I420Buffer) -> LumaGrid { |
| 24 | LumaGrid::of_plane( |
| 25 | buffer.data().0, |
| 26 | buffer.strides().0 as usize, |
| 27 | buffer.width() as usize, |
| 28 | buffer.height() as usize, |
| 29 | ) |
| 30 | } |
| 31 | |
| 32 | pub fn of_plane(plane: &[u8], stride: usize, width: usize, height: usize) -> LumaGrid { |
| 33 | let factor = (width / GRID_WIDTH).max(1); |
| 34 | let (grid_width, grid_height) = (width / factor, height / factor); |
| 35 | let mut values = vec![0f32; grid_width * grid_height]; |
| 36 | let mut sums = vec![0u32; grid_width]; |
| 37 | let scale = 1. / (factor * factor) as f32; |
| 38 | for (row, line) in values.chunks_exact_mut(grid_width).enumerate() { |
| 39 | sums.fill(0); |
| 40 | for source_row in row * factor..(row + 1) * factor { |
| 41 | for (sum, group) in sums |
| 42 | .iter_mut() |
| 43 | .zip(plane[source_row * stride..][..grid_width * factor].chunks_exact(factor)) |
| 44 | { |
| 45 | *sum += group.iter().map(|&value| u32::from(value)).sum::<u32>(); |
| 46 | } |
| 47 | } |
| 48 | for (slot, &sum) in line.iter_mut().zip(&sums) { |
| 49 | *slot = sum as f32 * scale; |
| 50 | } |
| 51 | } |
| 52 | LumaGrid { |
| 53 | width: grid_width, |
| 54 | height: grid_height, |
| 55 | values, |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | pub fn is_empty(&self) -> bool { |
| 60 | self.values.is_empty() |
| 61 | } |
| 62 | |
| 63 | fn halved(&self) -> LumaGrid { |
| 64 | let (width, height) = (self.width / 2, self.height / 2); |
| 65 | let mut values = Vec::with_capacity(width * height); |
| 66 | for row in 0..height { |
| 67 | for column in 0..width { |
| 68 | let at = |
| 69 | |y: usize, x: usize| self.values[(row * 2 + y) * self.width + column * 2 + x]; |
| 70 | values.push((at(0, 0) + at(0, 1) + at(1, 0) + at(1, 1)) / 4.); |
| 71 | } |
| 72 | } |
| 73 | LumaGrid { |
| 74 | width, |
| 75 | height, |
| 76 | values, |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | fn at(&self, column: isize, row: isize) -> f32 { |
| 81 | let column = column.clamp(0, self.width as isize - 1) as usize; |
| 82 | let row = row.clamp(0, self.height as isize - 1) as usize; |
| 83 | self.values[row * self.width + column] |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | /// Where each block of the current frame was in the reference frame, in grid cells. |
| 88 | #[derive(Clone, Debug, PartialEq)] |
| 89 | pub struct Flow { |
| 90 | pub columns: usize, |
| 91 | pub rows: usize, |
| 92 | pub grid_width: usize, |
| 93 | pub grid_height: usize, |
| 94 | pub offsets: Vec<(f32, f32)>, |
| 95 | } |
| 96 | |
| 97 | impl Flow { |
| 98 | pub fn is_still(&self) -> bool { |
| 99 | self.offsets |
| 100 | .iter() |
| 101 | .all(|&(across, down)| across == 0. && down == 0.) |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | struct Level<'a> { |
| 106 | reference: &'a LumaGrid, |
| 107 | current: &'a LumaGrid, |
| 108 | person: Option<&'a LumaGrid>, |
| 109 | } |
| 110 | |
| 111 | impl Level<'_> { |
| 112 | fn fits(grid: &LumaGrid, (left, top): (isize, isize), size: isize) -> bool { |
| 113 | left >= 0 |
| 114 | && top >= 0 |
| 115 | && left + size <= grid.width as isize |
| 116 | && top + size <= grid.height as isize |
| 117 | } |
| 118 | |
| 119 | /// 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. |
| 120 | fn cost( |
| 121 | &self, |
| 122 | (left, top): (isize, isize), |
| 123 | size: isize, |
| 124 | (across, down): (isize, isize), |
| 125 | ) -> f32 { |
| 126 | let (mut plain, mut weighted, mut weight) = (0f32, 0f32, 0f32); |
| 127 | if Self::fits(self.current, (left, top), size) |
| 128 | && Self::fits(self.reference, (left + across, top + down), size) |
| 129 | { |
| 130 | let length = size as usize; |
| 131 | for row in top..top + size { |
| 132 | let now = &self.current.values[row as usize * self.current.width + left as usize..] |
| 133 | [..length]; |
| 134 | let source = |
| 135 | (row + down) as usize * self.reference.width + (left + across) as usize; |
| 136 | let before = &self.reference.values[source..][..length]; |
| 137 | match self.person { |
| 138 | Some(person) => { |
| 139 | for ((now, before), share) in now |
| 140 | .iter() |
| 141 | .zip(before) |
| 142 | .zip(&person.values[source..][..length]) |
| 143 | { |
| 144 | let difference = (now - before).abs(); |
| 145 | plain += difference; |
| 146 | weighted += difference * share; |
| 147 | weight += share; |
| 148 | } |
| 149 | } |
| 150 | None => { |
| 151 | plain += now |
| 152 | .iter() |
| 153 | .zip(before) |
| 154 | .map(|(now, before)| (now - before).abs()) |
| 155 | .sum::<f32>() |
| 156 | } |
| 157 | } |
| 158 | } |
| 159 | } else { |
| 160 | for row in top..top + size { |
| 161 | for column in left..left + size { |
| 162 | let difference = (self.current.at(column, row) |
| 163 | - self.reference.at(column + across, row + down)) |
| 164 | .abs(); |
| 165 | let share = self |
| 166 | .person |
| 167 | .map_or(0., |person| person.at(column + across, row + down)); |
| 168 | plain += difference; |
| 169 | weighted += difference * share; |
| 170 | weight += share; |
| 171 | } |
| 172 | } |
| 173 | } |
| 174 | let count = (size * size) as f32; |
| 175 | let mean = if weight >= PERSON_SHARE * count { |
| 176 | weighted / weight |
| 177 | } else { |
| 178 | plain / count |
| 179 | }; |
| 180 | mean + MOTION_COST * (across.abs() + down.abs()) as f32 |
| 181 | } |
| 182 | |
| 183 | fn best_offset( |
| 184 | &self, |
| 185 | corner: (isize, isize), |
| 186 | size: isize, |
| 187 | centre: (isize, isize), |
| 188 | reach: isize, |
| 189 | ) -> ((isize, isize), f32) { |
| 190 | let mut best = (centre, f32::MAX); |
| 191 | for down in centre.1 - reach..=centre.1 + reach { |
| 192 | for across in centre.0 - reach..=centre.0 + reach { |
| 193 | let value = self.cost(corner, size, (across, down)); |
| 194 | if value < best.1 { |
| 195 | best = ((across, down), value); |
| 196 | } |
| 197 | } |
| 198 | } |
| 199 | best |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | fn parabola(before: f32, at: f32, after: f32) -> f32 { |
| 204 | let curvature = before - 2. * at + after; |
| 205 | if curvature <= f32::EPSILON { |
| 206 | 0. |
| 207 | } else { |
| 208 | ((before - after) / (2. * curvature)).clamp(-0.5, 0.5) |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | fn median_of_nine(values: &mut [f32]) -> f32 { |
| 213 | values.sort_by(f32::total_cmp); |
| 214 | values[values.len() / 2] |
| 215 | } |
| 216 | |
| 217 | fn median_filtered(offsets: &[(f32, f32)], columns: usize, rows: usize) -> Vec<(f32, f32)> { |
| 218 | let mut output = Vec::with_capacity(offsets.len()); |
| 219 | let (mut across, mut down) = (Vec::with_capacity(9), Vec::with_capacity(9)); |
| 220 | for row in 0..rows { |
| 221 | for column in 0..columns { |
| 222 | across.clear(); |
| 223 | down.clear(); |
| 224 | for neighbour_row in row.saturating_sub(1)..(row + 2).min(rows) { |
| 225 | for neighbour_column in column.saturating_sub(1)..(column + 2).min(columns) { |
| 226 | let (x, y) = offsets[neighbour_row * columns + neighbour_column]; |
| 227 | across.push(x); |
| 228 | down.push(y); |
| 229 | } |
| 230 | } |
| 231 | output.push((median_of_nine(&mut across), median_of_nine(&mut down))); |
| 232 | } |
| 233 | } |
| 234 | output |
| 235 | } |
| 236 | |
| 237 | fn band_offsets( |
| 238 | fine: &Level, |
| 239 | coarse: &Level, |
| 240 | columns: usize, |
| 241 | rows: std::ops::Range<usize>, |
| 242 | ) -> Vec<(f32, f32)> { |
| 243 | let half_window = (WINDOW / 2) as isize; |
| 244 | let size = WINDOW as isize; |
| 245 | let mut offsets: Vec<(f32, f32)> = Vec::with_capacity(columns * rows.len()); |
| 246 | let first_row = rows.start; |
| 247 | for row in rows { |
| 248 | for column in 0..columns { |
| 249 | let centre = ( |
| 250 | (column * BLOCK + BLOCK / 2) as isize, |
| 251 | (row * BLOCK + BLOCK / 2) as isize, |
| 252 | ); |
| 253 | let coarse_corner = ( |
| 254 | centre.0 / 2 - half_window / 2, |
| 255 | centre.1 / 2 - half_window / 2, |
| 256 | ); |
| 257 | let ((coarse_across, coarse_down), _) = |
| 258 | coarse.best_offset(coarse_corner, half_window, (0, 0), COARSE_REACH); |
| 259 | let corner = (centre.0 - half_window, centre.1 - half_window); |
| 260 | let neighbour = |index: Option<usize>| { |
| 261 | index.map(|index: usize| -> (isize, isize) { |
| 262 | let (across, down) = offsets[index]; |
| 263 | (across.round() as isize, down.round() as isize) |
| 264 | }) |
| 265 | }; |
| 266 | let left = neighbour((column > 0).then(|| offsets.len() - 1)); |
| 267 | let above = neighbour((row > first_row).then(|| offsets.len() - columns)); |
| 268 | let (found, found_cost) = [Some((coarse_across * 2, coarse_down * 2)), left, above] |
| 269 | .into_iter() |
| 270 | .flatten() |
| 271 | .map(|start| fine.best_offset(corner, size, start, FINE_REACH)) |
| 272 | .min_by(|first, second| first.1.total_cmp(&second.1)) |
| 273 | .expect("the coarse guess is always there"); |
| 274 | if fine.cost(corner, size, (0, 0)) <= found_cost { |
| 275 | offsets.push((0., 0.)); |
| 276 | continue; |
| 277 | } |
| 278 | let sample = |across: isize, down: isize| { |
| 279 | fine.cost(corner, size, (found.0 + across, found.1 + down)) |
| 280 | }; |
| 281 | let fine_across = parabola(sample(-1, 0), found_cost, sample(1, 0)); |
| 282 | let fine_down = parabola(sample(0, -1), found_cost, sample(0, 1)); |
| 283 | offsets.push((found.0 as f32 + fine_across, found.1 as f32 + fine_down)); |
| 284 | } |
| 285 | } |
| 286 | offsets |
| 287 | } |
| 288 | |
| 289 | /// Block matching, coarse to fine with a sub-cell fit; a small cost per cell of motion keeps flat and still areas at zero. |
| 290 | /// `person` is the mask of the reference frame; it may be empty. |
| 291 | pub fn estimate(reference: &LumaGrid, current: &LumaGrid, person: &Mask) -> Option<Flow> { |
| 292 | if reference.is_empty() |
| 293 | || (reference.width, reference.height) != (current.width, current.height) |
| 294 | || current.width < WINDOW * 2 |
| 295 | || current.height < WINDOW * 2 |
| 296 | { |
| 297 | return None; |
| 298 | } |
| 299 | let person = (!person.is_empty()).then(|| LumaGrid { |
| 300 | width: reference.width, |
| 301 | height: reference.height, |
| 302 | values: person.resampled(reference.width, reference.height), |
| 303 | }); |
| 304 | let coarse_person = person.as_ref().map(LumaGrid::halved); |
| 305 | let (coarse_reference, coarse_current) = (reference.halved(), current.halved()); |
| 306 | let fine = Level { |
| 307 | reference, |
| 308 | current, |
| 309 | person: person.as_ref(), |
| 310 | }; |
| 311 | let coarse = Level { |
| 312 | reference: &coarse_reference, |
| 313 | current: &coarse_current, |
| 314 | person: coarse_person.as_ref(), |
| 315 | }; |
| 316 | let (columns, rows) = ( |
| 317 | current.width.div_ceil(BLOCK), |
| 318 | current.height.div_ceil(BLOCK), |
| 319 | ); |
| 320 | let bands = std::thread::available_parallelism() |
| 321 | .map_or(1, usize::from) |
| 322 | .min(MAX_BANDS); |
| 323 | let rows_per_band = rows.div_ceil(bands); |
| 324 | let offsets: Vec<(f32, f32)> = std::thread::scope(|scope| { |
| 325 | let (fine, coarse) = (&fine, &coarse); |
| 326 | let workers: Vec<_> = (0..rows) |
| 327 | .step_by(rows_per_band) |
| 328 | .map(|first| { |
| 329 | scope.spawn(move || { |
| 330 | band_offsets( |
| 331 | fine, |
| 332 | coarse, |
| 333 | columns, |
| 334 | first..(first + rows_per_band).min(rows), |
| 335 | ) |
| 336 | }) |
| 337 | }) |
| 338 | .collect(); |
| 339 | workers |
| 340 | .into_iter() |
| 341 | .flat_map(|worker| worker.join().expect("block matching band")) |
| 342 | .collect() |
| 343 | }); |
| 344 | let offsets = median_filtered(&offsets, columns, rows); |
| 345 | Some(Flow { |
| 346 | columns, |
| 347 | rows, |
| 348 | grid_width: current.width, |
| 349 | grid_height: current.height, |
| 350 | offsets, |
| 351 | }) |
| 352 | } |
| 353 | |
| 354 | fn sample(mask: &Mask, column: f32, row: f32) -> f32 { |
| 355 | let column = column.clamp(0., (mask.width - 1) as f32); |
| 356 | let row = row.clamp(0., (mask.height - 1) as f32); |
| 357 | let (left, top) = (column.floor() as usize, row.floor() as usize); |
| 358 | let (right, bottom) = ( |
| 359 | (left + 1).min(mask.width - 1), |
| 360 | (top + 1).min(mask.height - 1), |
| 361 | ); |
| 362 | let (horizontal, vertical) = (column - left as f32, row - top as f32); |
| 363 | let at = |x: usize, y: usize| mask.values[y * mask.width + x]; |
| 364 | let upper = at(left, top) * (1. - horizontal) + at(right, top) * horizontal; |
| 365 | let lower = at(left, bottom) * (1. - horizontal) + at(right, bottom) * horizontal; |
| 366 | upper * (1. - vertical) + lower * vertical |
| 367 | } |
| 368 | |
| 369 | /// Moves the mask along `flow`: every cell takes the value from where its content was in the reference frame. |
| 370 | pub fn warp(mask: &Mask, flow: &Flow) -> Mask { |
| 371 | if mask.is_empty() || flow.is_still() { |
| 372 | return mask.clone(); |
| 373 | } |
| 374 | let block_axis = |cells: usize, blocks: usize, grid: usize| { |
| 375 | let mut positions = axis(cells, blocks); |
| 376 | for index in 0..cells { |
| 377 | let grid_position = (index as f32 + 0.5) * grid as f32 / cells as f32 - 0.5; |
| 378 | let block_position = ((grid_position - (BLOCK / 2) as f32 + 0.5) / BLOCK as f32) |
| 379 | .clamp(0., (blocks - 1) as f32); |
| 380 | positions.first[index] = block_position.floor() as usize; |
| 381 | positions.second[index] = (positions.first[index] + 1).min(blocks - 1); |
| 382 | positions.weight[index] = block_position - positions.first[index] as f32; |
| 383 | } |
| 384 | positions |
| 385 | }; |
| 386 | let (across, down) = ( |
| 387 | block_axis(mask.width, flow.columns, flow.grid_width), |
| 388 | block_axis(mask.height, flow.rows, flow.grid_height), |
| 389 | ); |
| 390 | let (scale_across, scale_down) = ( |
| 391 | mask.width as f32 / flow.grid_width as f32, |
| 392 | mask.height as f32 / flow.grid_height as f32, |
| 393 | ); |
| 394 | let mut values = Vec::with_capacity(mask.values.len()); |
| 395 | for row in 0..mask.height { |
| 396 | let (top, bottom, vertical) = ( |
| 397 | down.first[row] * flow.columns, |
| 398 | down.second[row] * flow.columns, |
| 399 | down.weight[row], |
| 400 | ); |
| 401 | for column in 0..mask.width { |
| 402 | let (left, right, horizontal) = ( |
| 403 | across.first[column], |
| 404 | across.second[column], |
| 405 | across.weight[column], |
| 406 | ); |
| 407 | let blend = |pick: fn(&(f32, f32)) -> f32| { |
| 408 | let upper = pick(&flow.offsets[top + left]) * (1. - horizontal) |
| 409 | + pick(&flow.offsets[top + right]) * horizontal; |
| 410 | let lower = pick(&flow.offsets[bottom + left]) * (1. - horizontal) |
| 411 | + pick(&flow.offsets[bottom + right]) * horizontal; |
| 412 | upper * (1. - vertical) + lower * vertical |
| 413 | }; |
| 414 | let (offset_across, offset_down) = (blend(|offset| offset.0), blend(|offset| offset.1)); |
| 415 | values.push(sample( |
| 416 | mask, |
| 417 | column as f32 + offset_across * scale_across, |
| 418 | row as f32 + offset_down * scale_down, |
| 419 | )); |
| 420 | } |
| 421 | } |
| 422 | Mask { |
| 423 | width: mask.width, |
| 424 | height: mask.height, |
| 425 | values, |
| 426 | matte: mask.matte, |
| 427 | } |
| 428 | } |
| 429 | |
| 430 | /// The mask of `reference`, moved to where the person is in `current`. |
| 431 | pub fn propagate(mask: &Mask, reference: &LumaGrid, current: &LumaGrid) -> Mask { |
| 432 | propagate_for_display(mask, reference, current).0 |
| 433 | } |
| 434 | |
| 435 | /// Like `propagate`, and answers whether anything moved; a moved matte has lost its exact edges and wants the guided filter again. |
| 436 | pub fn propagate_for_display( |
| 437 | mask: &Mask, |
| 438 | reference: &LumaGrid, |
| 439 | current: &LumaGrid, |
| 440 | ) -> (Mask, bool) { |
| 441 | match estimate(reference, current, mask) { |
| 442 | Some(flow) if !flow.is_still() => (warp(mask, &flow), true), |
| 443 | _ => (mask.clone(), false), |
| 444 | } |
| 445 | } |
| 446 | |
| 447 | #[cfg(test)] |
| 448 | mod tests { |
| 449 | use super::*; |
| 450 | |
| 451 | const WIDTH: usize = 160; |
| 452 | const HEIGHT: usize = 90; |
| 453 | |
| 454 | fn texture(column: isize, row: isize) -> f32 { |
| 455 | let hash = |
| 456 | (column.wrapping_mul(73_856_093) ^ row.wrapping_mul(19_349_663)).rem_euclid(97) as f32; |
| 457 | 40. + hash * 1.5 |
| 458 | } |
| 459 | |
| 460 | fn scene(shift: isize) -> (LumaGrid, Mask) { |
| 461 | let inside = |column: isize, row: isize| { |
| 462 | (60 + shift..100 + shift).contains(&column) && (20..80).contains(&row) |
| 463 | }; |
| 464 | let mut values = Vec::with_capacity(WIDTH * HEIGHT); |
| 465 | let mut person = Vec::with_capacity(WIDTH * HEIGHT); |
| 466 | for row in 0..HEIGHT as isize { |
| 467 | for column in 0..WIDTH as isize { |
| 468 | let person_here = inside(column, row); |
| 469 | values.push(if person_here { |
| 470 | 60. + texture(column - shift, row) |
| 471 | } else { |
| 472 | texture(column / 3, row / 3) |
| 473 | }); |
| 474 | person.push(if person_here { 1. } else { 0. }); |
| 475 | } |
| 476 | } |
| 477 | ( |
| 478 | LumaGrid { |
| 479 | width: WIDTH, |
| 480 | height: HEIGHT, |
| 481 | values, |
| 482 | }, |
| 483 | Mask::new(WIDTH, HEIGHT, person), |
| 484 | ) |
| 485 | } |
| 486 | |
| 487 | fn error(mask: &Mask, truth: &Mask) -> f32 { |
| 488 | mask.values |
| 489 | .iter() |
| 490 | .zip(&truth.values) |
| 491 | .map(|(value, truth)| (value - truth).abs()) |
| 492 | .sum() |
| 493 | } |
| 494 | |
| 495 | #[test] |
| 496 | fn a_still_frame_keeps_the_mask_as_it_is() { |
| 497 | let (grid, mask) = scene(0); |
| 498 | let flow = estimate(&grid, &grid, &mask).expect("same size"); |
| 499 | assert!(flow.is_still()); |
| 500 | assert_eq!(propagate(&mask, &grid, &grid), mask); |
| 501 | } |
| 502 | |
| 503 | #[test] |
| 504 | fn the_mask_follows_the_person_to_the_current_frame() { |
| 505 | let (reference, mask) = scene(0); |
| 506 | for shift in [3, 6, -5] { |
| 507 | let (current, truth) = scene(shift); |
| 508 | let moved = propagate(&mask, &reference, ¤t); |
| 509 | assert!( |
| 510 | error(&moved, &truth) * 4. < error(&mask, &truth), |
| 511 | "shift {shift}: {} vs stale {}", |
| 512 | error(&moved, &truth), |
| 513 | error(&mask, &truth) |
| 514 | ); |
| 515 | } |
| 516 | } |
| 517 | |
| 518 | #[test] |
| 519 | fn the_grid_averages_cells_of_the_frame() { |
| 520 | let width = 320; |
| 521 | let plane: Vec<u8> = (0..width * 4) |
| 522 | .map(|index| if index % width < 2 { 100 } else { 0 }) |
| 523 | .collect(); |
| 524 | let grid = LumaGrid::of_plane(&plane, width, width, 4); |
| 525 | assert_eq!((grid.width, grid.height), (160, 2)); |
| 526 | assert_eq!(grid.values[0], 100.); |
| 527 | assert_eq!(grid.values[1], 0.); |
| 528 | } |
| 529 | |
| 530 | #[test] |
| 531 | fn different_sizes_leave_the_mask_alone() { |
| 532 | let (reference, mask) = scene(0); |
| 533 | assert!(estimate(&reference, &LumaGrid::default(), &mask).is_none()); |
| 534 | assert_eq!(propagate(&mask, &LumaGrid::default(), &reference), mask); |
| 535 | } |
| 536 | } |