| 1 | use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; |
| 2 | use std::sync::{Arc, Mutex}; |
| 3 | use std::thread::JoinHandle; |
| 4 | use std::time::{Duration, Instant}; |
| 5 | |
| 6 | use libwebrtc::native::yuv_helper::i420_to_abgr; |
| 7 | use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _}; |
| 8 | |
| 9 | use crate::background::BackgroundPicture; |
| 10 | use crate::camera::i420_from_rgba; |
| 11 | use crate::composite::{Backdrop, PicturePlanes, composite}; |
| 12 | use crate::effects::CameraEffects; |
| 13 | use crate::error::Result; |
| 14 | use crate::latest::Latest; |
| 15 | use crate::mask::Mask; |
| 16 | use crate::matte::{Matte, Planes, refine}; |
| 17 | use crate::motion::{LumaGrid, propagate}; |
| 18 | use crate::segmentation::LadderSegmenter; |
| 19 | use crate::standout::Cutout; |
| 20 | |
| 21 | const CHANNELS: usize = 4; |
| 22 | const MASK_SMOOTHING: f32 = 0.35; |
| 23 | const MOTION_GAIN: f32 = 2.; |
| 24 | const SLOW_INFERENCE: Duration = Duration::from_millis(22); |
| 25 | const VERY_SLOW_INFERENCE: Duration = Duration::from_millis(45); |
| 26 | |
| 27 | pub fn compose_i420(buffer: &mut I420Buffer, mask: &Mask) { |
| 28 | let matte = refine(mask, Planes::of(buffer)); |
| 29 | composite(buffer, &matte, Backdrop::Blur); |
| 30 | } |
| 31 | |
| 32 | fn through_i420(rgba: &mut [u8], width: usize, height: usize, apply: impl FnOnce(&mut I420Buffer)) { |
| 33 | let mut buffer = i420_from_rgba(rgba, width as u32, height as u32); |
| 34 | apply(&mut buffer); |
| 35 | let (stride_y, stride_u, stride_v) = buffer.strides(); |
| 36 | let (plane_y, plane_u, plane_v) = buffer.data(); |
| 37 | i420_to_abgr( |
| 38 | plane_y, |
| 39 | stride_y, |
| 40 | plane_u, |
| 41 | stride_u, |
| 42 | plane_v, |
| 43 | stride_v, |
| 44 | rgba, |
| 45 | (width * CHANNELS) as u32, |
| 46 | width as i32, |
| 47 | height as i32, |
| 48 | ); |
| 49 | } |
| 50 | |
| 51 | /// Keeps the person (mask near 1) sharp and replaces the rest with a blurred copy. |
| 52 | pub fn compose(rgba: &mut [u8], width: usize, height: usize, mask: &Mask) { |
| 53 | through_i420(rgba, width, height, |buffer| compose_i420(buffer, mask)); |
| 54 | } |
| 55 | |
| 56 | pub fn compose_image( |
| 57 | rgba: &mut [u8], |
| 58 | width: usize, |
| 59 | height: usize, |
| 60 | matte: &Matte, |
| 61 | picture: &PicturePlanes, |
| 62 | ) { |
| 63 | through_i420(rgba, width, height, |buffer| { |
| 64 | composite(buffer, matte, Backdrop::Picture(picture)) |
| 65 | }); |
| 66 | } |
| 67 | |
| 68 | /// Shared between the UI command and the camera thread. |
| 69 | #[derive(Default)] |
| 70 | pub struct BlurSettings { |
| 71 | enabled: AtomicBool, |
| 72 | standout: AtomicBool, |
| 73 | average_micros: AtomicU32, |
| 74 | picture: Mutex<Option<Arc<BackgroundPicture>>>, |
| 75 | effects: Mutex<CameraEffects>, |
| 76 | cutout: Mutex<Option<Arc<Cutout>>>, |
| 77 | model: Mutex<&'static str>, |
| 78 | } |
| 79 | |
| 80 | impl BlurSettings { |
| 81 | pub fn set_enabled(&self, enabled: bool) { |
| 82 | self.enabled.store(enabled, Ordering::Relaxed); |
| 83 | } |
| 84 | |
| 85 | pub fn enabled(&self) -> bool { |
| 86 | self.enabled.load(Ordering::Relaxed) |
| 87 | } |
| 88 | |
| 89 | pub fn set_standout(&self, standout: bool) { |
| 90 | self.standout.store(standout, Ordering::Relaxed); |
| 91 | if !standout { |
| 92 | self.set_cutout(None); |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | pub fn standout(&self) -> bool { |
| 97 | self.standout.load(Ordering::Relaxed) |
| 98 | } |
| 99 | |
| 100 | pub fn set_cutout(&self, cutout: Option<Arc<Cutout>>) { |
| 101 | *self.cutout.lock().expect("cutout lock") = cutout; |
| 102 | } |
| 103 | |
| 104 | pub fn cutout(&self) -> Option<Arc<Cutout>> { |
| 105 | self.cutout.lock().expect("cutout lock").clone() |
| 106 | } |
| 107 | |
| 108 | pub fn set_picture(&self, picture: Option<Arc<BackgroundPicture>>) { |
| 109 | *self.picture.lock().expect("picture lock") = picture; |
| 110 | } |
| 111 | |
| 112 | fn picture(&self) -> Option<Arc<BackgroundPicture>> { |
| 113 | self.picture.lock().expect("picture lock").clone() |
| 114 | } |
| 115 | |
| 116 | pub fn set_effects(&self, effects: CameraEffects) { |
| 117 | *self.effects.lock().expect("effects lock") = effects; |
| 118 | } |
| 119 | |
| 120 | pub fn effects(&self) -> CameraEffects { |
| 121 | *self.effects.lock().expect("effects lock") |
| 122 | } |
| 123 | |
| 124 | pub fn active(&self) -> bool { |
| 125 | self.enabled() || self.standout() || self.effects().alters_frame() |
| 126 | } |
| 127 | |
| 128 | pub fn average_ms(&self) -> f32 { |
| 129 | self.average_micros.load(Ordering::Relaxed) as f32 / 1000. |
| 130 | } |
| 131 | |
| 132 | pub fn set_model(&self, model: &'static str) { |
| 133 | *self.model.lock().expect("model lock") = model; |
| 134 | } |
| 135 | |
| 136 | pub fn model(&self) -> &'static str { |
| 137 | *self.model.lock().expect("model lock") |
| 138 | } |
| 139 | |
| 140 | pub fn set_average_ms(&self, average_ms: f64) { |
| 141 | self.average_micros |
| 142 | .store((average_ms * 1000.) as u32, Ordering::Relaxed); |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | /// Replaces the background of a frame; the mask comes from the shared `MaskSource`. |
| 147 | pub struct BlurStage { |
| 148 | settings: Arc<BlurSettings>, |
| 149 | covered: Option<CoveredPicture>, |
| 150 | } |
| 151 | |
| 152 | struct CoveredPicture { |
| 153 | picture: Arc<BackgroundPicture>, |
| 154 | planes: PicturePlanes, |
| 155 | } |
| 156 | |
| 157 | impl BlurStage { |
| 158 | pub fn new(settings: Arc<BlurSettings>) -> Self { |
| 159 | BlurStage { |
| 160 | settings, |
| 161 | covered: None, |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | fn refresh_covered(&mut self, width: usize, height: usize) { |
| 166 | let Some(picture) = self.settings.picture() else { |
| 167 | self.covered = None; |
| 168 | return; |
| 169 | }; |
| 170 | let fresh = self.covered.as_ref().is_some_and(|covered| { |
| 171 | Arc::ptr_eq(&covered.picture, &picture) && covered.planes.fits(width, height) |
| 172 | }); |
| 173 | if !fresh { |
| 174 | let planes = PicturePlanes::new(&picture.covering(width, height), width, height); |
| 175 | self.covered = Some(CoveredPicture { picture, planes }); |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | pub fn compose(&mut self, buffer: &mut I420Buffer, matte: &Matte) { |
| 180 | self.refresh_covered(buffer.width() as usize, buffer.height() as usize); |
| 181 | let backdrop = self |
| 182 | .covered |
| 183 | .as_ref() |
| 184 | .map_or(Backdrop::Blur, |covered| Backdrop::Picture(&covered.planes)); |
| 185 | composite(buffer, matte, backdrop); |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | pub trait MaskInference: Send + 'static { |
| 190 | fn infer(&mut self, frame: I420Buffer) -> Result<Mask>; |
| 191 | |
| 192 | /// A model on the GPU takes no CPU from the frames, so it may segment every frame. |
| 193 | fn accelerated(&self) -> bool { |
| 194 | false |
| 195 | } |
| 196 | |
| 197 | fn model(&self) -> &'static str { |
| 198 | "custom" |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | type Frame = I420Buffer; |
| 203 | |
| 204 | #[derive(Default)] |
| 205 | struct Outbox { |
| 206 | mask: Mask, |
| 207 | reference: LumaGrid, |
| 208 | source_frame: u64, |
| 209 | version: u64, |
| 210 | } |
| 211 | |
| 212 | struct WorkerShared { |
| 213 | inbox: Latest<(u64, Frame)>, |
| 214 | outbox: Mutex<Outbox>, |
| 215 | stride: AtomicU64, |
| 216 | model: Mutex<&'static str>, |
| 217 | } |
| 218 | |
| 219 | fn stride_for(inference: Duration) -> u64 { |
| 220 | if inference > VERY_SLOW_INFERENCE { |
| 221 | 3 |
| 222 | } else if inference > SLOW_INFERENCE { |
| 223 | 2 |
| 224 | } else { |
| 225 | 1 |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | fn smooth_into(current: &mut Mask, fresh: Mask) { |
| 230 | if (current.width, current.height, current.matte) != (fresh.width, fresh.height, fresh.matte) { |
| 231 | *current = fresh; |
| 232 | return; |
| 233 | } |
| 234 | for (value, new) in current.values.iter_mut().zip(fresh.values) { |
| 235 | let change = new - *value; |
| 236 | let smoothing = MASK_SMOOTHING * (1. - change.abs() * MOTION_GAIN).max(0.); |
| 237 | *value += change * (1. - smoothing); |
| 238 | } |
| 239 | } |
| 240 | |
| 241 | fn run_worker(shared: &WorkerShared, inference: &mut dyn MaskInference) { |
| 242 | let mut smoothed = Mask::default(); |
| 243 | let mut smoothed_reference = LumaGrid::default(); |
| 244 | while let Some((source_frame, frame)) = shared.inbox.take() { |
| 245 | let reference = LumaGrid::of(&frame); |
| 246 | let started = Instant::now(); |
| 247 | let Ok(fresh) = inference.infer(frame) else { |
| 248 | continue; |
| 249 | }; |
| 250 | let stride = if inference.accelerated() { |
| 251 | 1 |
| 252 | } else { |
| 253 | stride_for(started.elapsed()) |
| 254 | }; |
| 255 | shared.stride.store(stride, Ordering::Relaxed); |
| 256 | *shared.model.lock().expect("model lock") = inference.model(); |
| 257 | smoothed = propagate(&smoothed, &smoothed_reference, &reference); |
| 258 | smooth_into(&mut smoothed, fresh); |
| 259 | smoothed_reference.clone_from(&reference); |
| 260 | let mut outbox = shared.outbox.lock().expect("outbox lock"); |
| 261 | outbox.mask.clone_from(&smoothed); |
| 262 | outbox.reference = reference; |
| 263 | outbox.source_frame = source_frame; |
| 264 | outbox.version += 1; |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | /// One segmentation mask for every effect: a worker thread segments the newest frame, the caller never waits on it. |
| 269 | pub struct MaskSource { |
| 270 | shared: Arc<WorkerShared>, |
| 271 | worker: Option<JoinHandle<()>>, |
| 272 | mask: Mask, |
| 273 | reference: LumaGrid, |
| 274 | source_frame: u64, |
| 275 | seen_version: u64, |
| 276 | frames: u64, |
| 277 | } |
| 278 | |
| 279 | impl MaskSource { |
| 280 | /// The models load on the worker, so the first frames pass unchanged instead of the camera thread waiting on them. |
| 281 | pub fn new() -> Result<Self> { |
| 282 | Ok(Self::spawn(|| LadderSegmenter::new().ok())) |
| 283 | } |
| 284 | |
| 285 | pub fn with_inference(inference: impl MaskInference) -> Self { |
| 286 | Self::spawn(move || Some(inference)) |
| 287 | } |
| 288 | |
| 289 | fn spawn<Inference: MaskInference>( |
| 290 | create: impl FnOnce() -> Option<Inference> + Send + 'static, |
| 291 | ) -> Self { |
| 292 | let shared = Arc::new(WorkerShared { |
| 293 | inbox: Latest::default(), |
| 294 | outbox: Mutex::default(), |
| 295 | stride: AtomicU64::new(1), |
| 296 | model: Mutex::new(""), |
| 297 | }); |
| 298 | let worker_shared = shared.clone(); |
| 299 | let worker = std::thread::Builder::new() |
| 300 | .name("segmentation".to_owned()) |
| 301 | .spawn(move || { |
| 302 | if let Some(mut inference) = create() { |
| 303 | run_worker(&worker_shared, &mut inference); |
| 304 | } |
| 305 | }) |
| 306 | .expect("segmentation thread"); |
| 307 | MaskSource { |
| 308 | shared, |
| 309 | worker: Some(worker), |
| 310 | mask: Mask::default(), |
| 311 | reference: LumaGrid::default(), |
| 312 | source_frame: 0, |
| 313 | seen_version: 0, |
| 314 | frames: 0, |
| 315 | } |
| 316 | } |
| 317 | |
| 318 | pub fn due(&self) -> bool { |
| 319 | self.frames |
| 320 | .is_multiple_of(self.shared.stride.load(Ordering::Relaxed)) |
| 321 | || self.mask.is_empty() |
| 322 | } |
| 323 | |
| 324 | pub fn mask(&self) -> &Mask { |
| 325 | &self.mask |
| 326 | } |
| 327 | |
| 328 | /// The model that made the newest mask, empty until the first one. |
| 329 | pub fn model(&self) -> &'static str { |
| 330 | *self.shared.model.lock().expect("model lock") |
| 331 | } |
| 332 | |
| 333 | /// The luma grid of the frame the mask was made from. |
| 334 | pub fn reference(&self) -> &LumaGrid { |
| 335 | &self.reference |
| 336 | } |
| 337 | |
| 338 | /// Frames shown since the frame the current mask was made from. |
| 339 | pub fn age(&self) -> u64 { |
| 340 | self.frames.saturating_sub(self.source_frame + 1) |
| 341 | } |
| 342 | |
| 343 | /// Call once per frame; `frame` is only read when `due`. Answers whether a newer mask arrived. |
| 344 | pub fn refresh(&mut self, frame: impl FnOnce() -> Frame) -> bool { |
| 345 | if self.due() { |
| 346 | self.shared.inbox.put((self.frames, frame())); |
| 347 | } |
| 348 | self.frames += 1; |
| 349 | let outbox = self.shared.outbox.lock().expect("outbox lock"); |
| 350 | if outbox.version == self.seen_version { |
| 351 | return false; |
| 352 | } |
| 353 | self.seen_version = outbox.version; |
| 354 | self.mask.clone_from(&outbox.mask); |
| 355 | self.reference.clone_from(&outbox.reference); |
| 356 | self.source_frame = outbox.source_frame; |
| 357 | true |
| 358 | } |
| 359 | } |
| 360 | |
| 361 | impl Drop for MaskSource { |
| 362 | fn drop(&mut self) { |
| 363 | self.shared.inbox.close(); |
| 364 | if let Some(worker) = self.worker.take() { |
| 365 | let _ = worker.join(); |
| 366 | } |
| 367 | } |
| 368 | } |
| 369 | |
| 370 | #[cfg(test)] |
| 371 | mod tests { |
| 372 | use super::*; |
| 373 | use crate::camera::i420_from_rgba; |
| 374 | |
| 375 | const MASK_WIDTH: usize = 256; |
| 376 | const MASK_HEIGHT: usize = 144; |
| 377 | const WIDTH: usize = 160; |
| 378 | const HEIGHT: usize = 90; |
| 379 | |
| 380 | fn checkerboard() -> Vec<u8> { |
| 381 | let mut rgba = vec![255u8; WIDTH * HEIGHT * CHANNELS]; |
| 382 | for row in 0..HEIGHT { |
| 383 | for column in 0..WIDTH { |
| 384 | let value = if (row / 3 + column / 3) % 2 == 0 { |
| 385 | 20 |
| 386 | } else { |
| 387 | 235 |
| 388 | }; |
| 389 | rgba[(row * WIDTH + column) * CHANNELS..][..3].fill(value); |
| 390 | } |
| 391 | } |
| 392 | rgba |
| 393 | } |
| 394 | |
| 395 | fn oval_mask() -> Mask { |
| 396 | Mask::from_fn(MASK_WIDTH, MASK_HEIGHT, |x, y| { |
| 397 | if ((x - 0.5) * (x - 0.5)) / 0.04 + ((y - 0.5) * (y - 0.5)) / 0.09 <= 1. { |
| 398 | 1. |
| 399 | } else { |
| 400 | 0. |
| 401 | } |
| 402 | }) |
| 403 | } |
| 404 | |
| 405 | fn pixel(rgba: &[u8], x: usize, y: usize) -> u8 { |
| 406 | rgba[(y * WIDTH + x) * CHANNELS] |
| 407 | } |
| 408 | |
| 409 | fn roughness(rgba: &[u8], x: usize, y: usize) -> i32 { |
| 410 | (0..8) |
| 411 | .map(|step| { |
| 412 | (i32::from(pixel(rgba, x + step + 1, y)) - i32::from(pixel(rgba, x + step, y))) |
| 413 | .abs() |
| 414 | }) |
| 415 | .sum() |
| 416 | } |
| 417 | |
| 418 | #[test] |
| 419 | fn the_person_stays_sharp_and_the_background_is_smoothed() { |
| 420 | let original = checkerboard(); |
| 421 | let mut blurred = original.clone(); |
| 422 | compose(&mut blurred, WIDTH, HEIGHT, &oval_mask()); |
| 423 | let (center_x, center_y) = (WIDTH / 2, HEIGHT / 2); |
| 424 | assert_eq!( |
| 425 | pixel(&blurred, center_x, center_y), |
| 426 | pixel(&original, center_x, center_y) |
| 427 | ); |
| 428 | assert_eq!( |
| 429 | roughness(&blurred, center_x - 4, center_y), |
| 430 | roughness(&original, center_x - 4, center_y) |
| 431 | ); |
| 432 | assert!(roughness(&blurred, 2, 2) * 4 < roughness(&original, 2, 2)); |
| 433 | assert!( |
| 434 | roughness(&blurred, WIDTH - 12, HEIGHT - 3) * 4 |
| 435 | < roughness(&original, WIDTH - 12, HEIGHT - 3) |
| 436 | ); |
| 437 | } |
| 438 | |
| 439 | fn checkerboard_i420() -> I420Buffer { |
| 440 | let mut buffer = I420Buffer::new(WIDTH as u32, HEIGHT as u32); |
| 441 | let (stride_y, stride_u, _) = buffer.strides(); |
| 442 | let (plane_y, plane_u, plane_v) = buffer.data_mut(); |
| 443 | for row in 0..HEIGHT { |
| 444 | for column in 0..WIDTH { |
| 445 | plane_y[row * stride_y as usize + column] = if (row / 3 + column / 3) % 2 == 0 { |
| 446 | 20 |
| 447 | } else { |
| 448 | 235 |
| 449 | }; |
| 450 | } |
| 451 | } |
| 452 | for row in 0..HEIGHT / 2 { |
| 453 | for column in 0..WIDTH / 2 { |
| 454 | plane_u[row * stride_u as usize + column] = if (row / 3 + column / 3) % 2 == 0 { |
| 455 | 60 |
| 456 | } else { |
| 457 | 200 |
| 458 | }; |
| 459 | } |
| 460 | } |
| 461 | plane_v.fill(128); |
| 462 | buffer |
| 463 | } |
| 464 | |
| 465 | fn luma_roughness(buffer: &mut I420Buffer, x: usize, y: usize) -> i32 { |
| 466 | let stride = buffer.strides().0 as usize; |
| 467 | let plane = buffer.data_mut().0; |
| 468 | (0..8) |
| 469 | .map(|step| { |
| 470 | (i32::from(plane[y * stride + x + step + 1]) |
| 471 | - i32::from(plane[y * stride + x + step])) |
| 472 | .abs() |
| 473 | }) |
| 474 | .sum() |
| 475 | } |
| 476 | |
| 477 | #[test] |
| 478 | fn the_planar_blur_keeps_the_person_and_smooths_luma_and_chroma_outside() { |
| 479 | let mut original = checkerboard_i420(); |
| 480 | let mut blurred = checkerboard_i420(); |
| 481 | compose_i420(&mut blurred, &oval_mask()); |
| 482 | let (center_x, center_y) = (WIDTH / 2, HEIGHT / 2); |
| 483 | assert_eq!( |
| 484 | luma_roughness(&mut blurred, center_x - 4, center_y), |
| 485 | luma_roughness(&mut original, center_x - 4, center_y) |
| 486 | ); |
| 487 | assert!(luma_roughness(&mut blurred, 2, 2) * 4 < luma_roughness(&mut original, 2, 2)); |
| 488 | let chroma = |buffer: &mut I420Buffer, x: usize, y: usize| { |
| 489 | let stride = buffer.strides().1 as usize; |
| 490 | i32::from(buffer.data_mut().1[y * stride + x]) |
| 491 | }; |
| 492 | assert_eq!( |
| 493 | chroma(&mut blurred, center_x / 2, center_y / 2), |
| 494 | chroma(&mut original, center_x / 2, center_y / 2) |
| 495 | ); |
| 496 | let spread = |buffer: &mut I420Buffer| { |
| 497 | (2..10) |
| 498 | .map(|x| (chroma(buffer, x + 1, 2) - chroma(buffer, x, 2)).abs()) |
| 499 | .sum::<i32>() |
| 500 | }; |
| 501 | assert!(spread(&mut blurred) * 4 < spread(&mut original)); |
| 502 | } |
| 503 | |
| 504 | #[test] |
| 505 | fn the_planar_blur_matches_the_rgba_blur_on_gray_frames() { |
| 506 | let mut planar = checkerboard_i420(); |
| 507 | planar.data_mut().1.fill(128); |
| 508 | compose_i420(&mut planar, &oval_mask()); |
| 509 | let mut rgba = checkerboard(); |
| 510 | compose(&mut rgba, WIDTH, HEIGHT, &oval_mask()); |
| 511 | let stride = planar.strides().0 as usize; |
| 512 | let plane = planar.data().0; |
| 513 | let worst = (0..HEIGHT) |
| 514 | .flat_map(|y| (0..WIDTH).map(move |x| (x, y))) |
| 515 | .map(|(x, y)| (i32::from(plane[y * stride + x]) - i32::from(pixel(&rgba, x, y))).abs()) |
| 516 | .max() |
| 517 | .unwrap(); |
| 518 | assert!(worst <= 24, "worst luma difference {worst}"); |
| 519 | } |
| 520 | |
| 521 | #[test] |
| 522 | fn a_full_person_mask_leaves_the_planes_untouched() { |
| 523 | let mut untouched = checkerboard_i420(); |
| 524 | compose_i420(&mut untouched, &Mask::filled(MASK_WIDTH, MASK_HEIGHT, 1.)); |
| 525 | let reference = checkerboard_i420(); |
| 526 | assert_eq!(untouched.data(), reference.data()); |
| 527 | } |
| 528 | |
| 529 | #[test] |
| 530 | fn the_edge_between_person_and_background_is_feathered() { |
| 531 | let original = checkerboard(); |
| 532 | let mut blurred = original.clone(); |
| 533 | let mut mask = oval_mask(); |
| 534 | compose(&mut blurred, WIDTH, HEIGHT, &mask); |
| 535 | let edge_row = HEIGHT / 2; |
| 536 | let changed_steps = (0..WIDTH - 1) |
| 537 | .filter(|&x| { |
| 538 | pixel(&blurred, x, edge_row) != pixel(&original, x, edge_row) |
| 539 | && pixel(&blurred, x + 1, edge_row) == pixel(&original, x + 1, edge_row) |
| 540 | }) |
| 541 | .count(); |
| 542 | assert!( |
| 543 | changed_steps <= 2, |
| 544 | "a hard seam shows as one switch per side" |
| 545 | ); |
| 546 | mask.values.fill(1.); |
| 547 | let mut untouched = original.clone(); |
| 548 | compose(&mut untouched, WIDTH, HEIGHT, &mask); |
| 549 | assert_eq!(untouched, original); |
| 550 | } |
| 551 | |
| 552 | #[test] |
| 553 | fn an_empty_mask_blurs_the_whole_frame() { |
| 554 | let original = checkerboard(); |
| 555 | let mut blurred = original.clone(); |
| 556 | compose( |
| 557 | &mut blurred, |
| 558 | WIDTH, |
| 559 | HEIGHT, |
| 560 | &Mask::filled(MASK_WIDTH, MASK_HEIGHT, 0.), |
| 561 | ); |
| 562 | assert!(roughness(&blurred, 70, 40) * 4 < roughness(&original, 70, 40)); |
| 563 | assert!(blurred.chunks(CHANNELS).all(|pixel| pixel[3] == 255)); |
| 564 | } |
| 565 | |
| 566 | fn cover_of(color: [u8; 3]) -> PicturePlanes { |
| 567 | PicturePlanes::new( |
| 568 | &BackgroundPicture::from_rgb(color.repeat(4 * 4), 4, 4) |
| 569 | .unwrap() |
| 570 | .covering(WIDTH, HEIGHT), |
| 571 | WIDTH, |
| 572 | HEIGHT, |
| 573 | ) |
| 574 | } |
| 575 | |
| 576 | fn refine_rgba(mask: &Mask, rgba: &[u8], width: usize, height: usize) -> Matte { |
| 577 | crate::matte::refine_rgba(mask, rgba, width, height) |
| 578 | } |
| 579 | |
| 580 | #[test] |
| 581 | fn the_person_stays_and_the_picture_replaces_everything_else() { |
| 582 | let original = checkerboard(); |
| 583 | let mut replaced = original.clone(); |
| 584 | compose_image( |
| 585 | &mut replaced, |
| 586 | WIDTH, |
| 587 | HEIGHT, |
| 588 | &refine_rgba(&oval_mask(), &original, WIDTH, HEIGHT), |
| 589 | &cover_of([10, 120, 200]), |
| 590 | ); |
| 591 | let (center_x, center_y) = (WIDTH / 2, HEIGHT / 2); |
| 592 | assert_eq!( |
| 593 | pixel(&replaced, center_x, center_y), |
| 594 | pixel(&original, center_x, center_y) |
| 595 | ); |
| 596 | for (x, y) in [(2, 2), (WIDTH - 3, HEIGHT - 3), (2, HEIGHT - 3)] { |
| 597 | let shown = &replaced[(y * WIDTH + x) * CHANNELS..][..4]; |
| 598 | assert!( |
| 599 | shown |
| 600 | .iter() |
| 601 | .zip([10, 120, 200, 255]) |
| 602 | .all(|(&shown, wanted)| shown.abs_diff(wanted) <= 3), |
| 603 | "{shown:?}" |
| 604 | ); |
| 605 | } |
| 606 | } |
| 607 | |
| 608 | #[test] |
| 609 | fn the_picture_edge_is_feathered_like_the_blur_edge() { |
| 610 | let original = checkerboard(); |
| 611 | let mut replaced = original.clone(); |
| 612 | compose_image( |
| 613 | &mut replaced, |
| 614 | WIDTH, |
| 615 | HEIGHT, |
| 616 | &refine_rgba(&oval_mask(), &original, WIDTH, HEIGHT), |
| 617 | &cover_of([0, 0, 0]), |
| 618 | ); |
| 619 | let edge_row = HEIGHT / 2; |
| 620 | let switches = (0..WIDTH - 1) |
| 621 | .filter(|&x| { |
| 622 | pixel(&replaced, x, edge_row) != pixel(&original, x, edge_row) |
| 623 | && pixel(&replaced, x + 1, edge_row) == pixel(&original, x + 1, edge_row) |
| 624 | }) |
| 625 | .count(); |
| 626 | assert!(switches <= 2); |
| 627 | let mut everyone = original.clone(); |
| 628 | compose_image( |
| 629 | &mut everyone, |
| 630 | WIDTH, |
| 631 | HEIGHT, |
| 632 | &refine_rgba( |
| 633 | &Mask::filled(MASK_WIDTH, MASK_HEIGHT, 1.), |
| 634 | &original, |
| 635 | WIDTH, |
| 636 | HEIGHT, |
| 637 | ), |
| 638 | &cover_of([0, 0, 0]), |
| 639 | ); |
| 640 | assert_eq!(everyone, original); |
| 641 | let empty = refine_rgba( |
| 642 | &Mask::filled(MASK_WIDTH, MASK_HEIGHT, 0.), |
| 643 | &original, |
| 644 | WIDTH, |
| 645 | HEIGHT, |
| 646 | ); |
| 647 | let mut nobody = original; |
| 648 | compose_image(&mut nobody, WIDTH, HEIGHT, &empty, &cover_of([0, 0, 0])); |
| 649 | assert!( |
| 650 | nobody |
| 651 | .chunks(CHANNELS) |
| 652 | .all(|pixel| pixel[..3] == [0, 0, 0] && pixel[3] == 255) |
| 653 | ); |
| 654 | } |
| 655 | |
| 656 | fn wait_for_mask(source: &mut MaskSource, frame: impl Fn() -> Frame) -> bool { |
| 657 | let deadline = Instant::now() + Duration::from_secs(10); |
| 658 | while Instant::now() < deadline { |
| 659 | if source.refresh(&frame) { |
| 660 | return true; |
| 661 | } |
| 662 | std::thread::sleep(Duration::from_millis(5)); |
| 663 | } |
| 664 | false |
| 665 | } |
| 666 | |
| 667 | #[test] |
| 668 | fn the_mask_source_segments_when_due_and_keeps_one_mask() { |
| 669 | let mut source = MaskSource::new().expect("model loads"); |
| 670 | assert!(wait_for_mask(&mut source, || i420_from_rgba( |
| 671 | &checkerboard(), |
| 672 | WIDTH as u32, |
| 673 | HEIGHT as u32 |
| 674 | ))); |
| 675 | assert_eq!(source.mask().values.len(), MASK_WIDTH * MASK_HEIGHT); |
| 676 | source.shared.stride.store(3, Ordering::Relaxed); |
| 677 | source.frames = 1; |
| 678 | assert!(!source.due()); |
| 679 | assert!(!source.refresh(|| unreachable!("a skipped frame is not read"))); |
| 680 | } |
| 681 | |
| 682 | struct SlowSegmenter { |
| 683 | delay: Duration, |
| 684 | seen: Arc<Mutex<Vec<u8>>>, |
| 685 | } |
| 686 | |
| 687 | impl MaskInference for SlowSegmenter { |
| 688 | fn infer(&mut self, frame: I420Buffer) -> Result<Mask> { |
| 689 | let marker = frame.data().0[0]; |
| 690 | self.seen.lock().unwrap().push(marker); |
| 691 | std::thread::sleep(self.delay); |
| 692 | Ok(Mask::filled( |
| 693 | MASK_WIDTH, |
| 694 | MASK_HEIGHT, |
| 695 | f32::from(marker) / 255., |
| 696 | )) |
| 697 | } |
| 698 | } |
| 699 | |
| 700 | fn marked_frame(marker: u8) -> Frame { |
| 701 | let mut buffer = I420Buffer::new(2, 2); |
| 702 | buffer.data_mut().0.fill(marker); |
| 703 | buffer |
| 704 | } |
| 705 | |
| 706 | #[test] |
| 707 | fn a_slow_segmenter_never_blocks_the_sender() { |
| 708 | let seen = Arc::new(Mutex::new(Vec::new())); |
| 709 | let mut source = MaskSource::with_inference(SlowSegmenter { |
| 710 | delay: Duration::from_millis(300), |
| 711 | seen, |
| 712 | }); |
| 713 | let started = Instant::now(); |
| 714 | for _ in 0..30 { |
| 715 | source.refresh(|| marked_frame(1)); |
| 716 | } |
| 717 | assert!(started.elapsed() < Duration::from_millis(150)); |
| 718 | } |
| 719 | |
| 720 | #[test] |
| 721 | fn the_mask_age_counts_the_frames_shown_since_its_source_frame() { |
| 722 | let seen = Arc::new(Mutex::new(Vec::new())); |
| 723 | let mut source = MaskSource::with_inference(SlowSegmenter { |
| 724 | delay: Duration::from_millis(60), |
| 725 | seen, |
| 726 | }); |
| 727 | assert!(!source.refresh(|| marked_frame(5))); |
| 728 | let deadline = Instant::now() + Duration::from_secs(10); |
| 729 | let mut shown = 1; |
| 730 | while !source.refresh(|| marked_frame(6)) && Instant::now() < deadline { |
| 731 | shown += 1; |
| 732 | std::thread::sleep(Duration::from_millis(10)); |
| 733 | } |
| 734 | assert!(shown >= 3, "the mask came back before the model was done"); |
| 735 | assert_eq!(source.age(), shown - 1); |
| 736 | assert_eq!(source.reference().values.len(), 4); |
| 737 | assert!(!source.refresh(|| marked_frame(7))); |
| 738 | assert_eq!(source.age(), shown); |
| 739 | } |
| 740 | |
| 741 | #[test] |
| 742 | fn the_worker_hands_over_the_newest_frame_and_drops_stale_ones() { |
| 743 | let seen = Arc::new(Mutex::new(Vec::new())); |
| 744 | let mut source = MaskSource::with_inference(SlowSegmenter { |
| 745 | delay: Duration::from_millis(100), |
| 746 | seen: seen.clone(), |
| 747 | }); |
| 748 | for marker in [10, 20, 30, 40] { |
| 749 | source.refresh(|| marked_frame(marker)); |
| 750 | std::thread::sleep(Duration::from_millis(5)); |
| 751 | } |
| 752 | let deadline = Instant::now() + Duration::from_secs(10); |
| 753 | while seen.lock().unwrap().last() != Some(&40) && Instant::now() < deadline { |
| 754 | source.refresh(|| marked_frame(40)); |
| 755 | std::thread::sleep(Duration::from_millis(10)); |
| 756 | } |
| 757 | let processed = seen.lock().unwrap().clone(); |
| 758 | assert_eq!(processed.last(), Some(&40)); |
| 759 | assert!( |
| 760 | !processed.contains(&20) || !processed.contains(&30), |
| 761 | "stale frames pile up: {processed:?}" |
| 762 | ); |
| 763 | } |
| 764 | } |