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