| 1 | use std::sync::{Arc, Mutex}; |
| 2 | use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; |
| 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::effects::CameraEffects; |
| 11 | use crate::error::Result; |
| 12 | use crate::camera::i420_from_rgba; |
| 13 | use crate::composite::{Backdrop, PicturePlanes, composite}; |
| 14 | use crate::latest::Latest; |
| 15 | use crate::mask::Mask; |
| 16 | use crate::motion::{LumaGrid, propagate}; |
| 17 | use crate::segmentation::LadderSegmenter; |
| 18 | use crate::matte::{Matte, Planes, refine}; |
| 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(plane_y, stride_y, plane_u, stride_u, plane_v, stride_v, rgba, (width * CHANNELS) as u32, width as i32, height as i32); |
| 38 | } |
| 39 | |
| 40 | /// Keeps the person (mask near 1) sharp and replaces the rest with a blurred copy. |
| 41 | pub fn compose(rgba: &mut [u8], width: usize, height: usize, mask: &Mask) { |
| 42 | through_i420(rgba, width, height, |buffer| compose_i420(buffer, mask)); |
| 43 | } |
| 44 | |
| 45 | pub fn compose_image(rgba: &mut [u8], width: usize, height: usize, matte: &Matte, picture: &PicturePlanes) { |
| 46 | through_i420(rgba, width, height, |buffer| composite(buffer, matte, Backdrop::Picture(picture))); |
| 47 | } |
| 48 | |
| 49 | /// Shared between the UI command and the camera thread. |
| 50 | #[derive(Default)] |
| 51 | pub struct BlurSettings { |
| 52 | enabled: AtomicBool, |
| 53 | standout: AtomicBool, |
| 54 | average_micros: AtomicU32, |
| 55 | picture: Mutex<Option<Arc<BackgroundPicture>>>, |
| 56 | effects: Mutex<CameraEffects>, |
| 57 | cutout: Mutex<Option<Arc<Cutout>>>, |
| 58 | } |
| 59 | |
| 60 | impl BlurSettings { |
| 61 | pub fn set_enabled(&self, enabled: bool) { |
| 62 | self.enabled.store(enabled, Ordering::Relaxed); |
| 63 | } |
| 64 | |
| 65 | pub fn enabled(&self) -> bool { |
| 66 | self.enabled.load(Ordering::Relaxed) |
| 67 | } |
| 68 | |
| 69 | pub fn set_standout(&self, standout: bool) { |
| 70 | self.standout.store(standout, Ordering::Relaxed); |
| 71 | if !standout { |
| 72 | self.set_cutout(None); |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | pub fn standout(&self) -> bool { |
| 77 | self.standout.load(Ordering::Relaxed) |
| 78 | } |
| 79 | |
| 80 | pub fn set_cutout(&self, cutout: Option<Arc<Cutout>>) { |
| 81 | *self.cutout.lock().expect("cutout lock") = cutout; |
| 82 | } |
| 83 | |
| 84 | pub fn cutout(&self) -> Option<Arc<Cutout>> { |
| 85 | self.cutout.lock().expect("cutout lock").clone() |
| 86 | } |
| 87 | |
| 88 | pub fn set_picture(&self, picture: Option<Arc<BackgroundPicture>>) { |
| 89 | *self.picture.lock().expect("picture lock") = picture; |
| 90 | } |
| 91 | |
| 92 | fn picture(&self) -> Option<Arc<BackgroundPicture>> { |
| 93 | self.picture.lock().expect("picture lock").clone() |
| 94 | } |
| 95 | |
| 96 | pub fn set_effects(&self, effects: CameraEffects) { |
| 97 | *self.effects.lock().expect("effects lock") = effects; |
| 98 | } |
| 99 | |
| 100 | pub fn effects(&self) -> CameraEffects { |
| 101 | *self.effects.lock().expect("effects lock") |
| 102 | } |
| 103 | |
| 104 | pub fn active(&self) -> bool { |
| 105 | self.enabled() || self.standout() || self.effects().alters_frame() |
| 106 | } |
| 107 | |
| 108 | pub fn average_ms(&self) -> f32 { |
| 109 | self.average_micros.load(Ordering::Relaxed) as f32 / 1000. |
| 110 | } |
| 111 | |
| 112 | pub fn set_average_ms(&self, average_ms: f64) { |
| 113 | self.average_micros.store((average_ms * 1000.) as u32, Ordering::Relaxed); |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | /// Replaces the background of a frame; the mask comes from the shared `MaskSource`. |
| 118 | pub struct BlurStage { |
| 119 | settings: Arc<BlurSettings>, |
| 120 | covered: Option<CoveredPicture>, |
| 121 | } |
| 122 | |
| 123 | struct CoveredPicture { |
| 124 | picture: Arc<BackgroundPicture>, |
| 125 | planes: PicturePlanes, |
| 126 | } |
| 127 | |
| 128 | impl BlurStage { |
| 129 | pub fn new(settings: Arc<BlurSettings>) -> Self { |
| 130 | BlurStage { settings, covered: None } |
| 131 | } |
| 132 | |
| 133 | fn refresh_covered(&mut self, width: usize, height: usize) { |
| 134 | let Some(picture) = self.settings.picture() else { |
| 135 | self.covered = None; |
| 136 | return; |
| 137 | }; |
| 138 | let fresh = self.covered.as_ref().is_some_and(|covered| Arc::ptr_eq(&covered.picture, &picture) && covered.planes.fits(width, height)); |
| 139 | if !fresh { |
| 140 | let planes = PicturePlanes::new(&picture.covering(width, height), width, height); |
| 141 | self.covered = Some(CoveredPicture { picture, planes }); |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | pub fn compose(&mut self, buffer: &mut I420Buffer, matte: &Matte) { |
| 146 | self.refresh_covered(buffer.width() as usize, buffer.height() as usize); |
| 147 | let backdrop = self.covered.as_ref().map_or(Backdrop::Blur, |covered| Backdrop::Picture(&covered.planes)); |
| 148 | composite(buffer, matte, backdrop); |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | pub trait MaskInference: Send + 'static { |
| 153 | fn infer(&mut self, frame: I420Buffer) -> Result<Mask>; |
| 154 | |
| 155 | /// A model on the GPU takes no CPU from the frames, so it may segment every frame. |
| 156 | fn accelerated(&self) -> bool { |
| 157 | false |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | type Frame = I420Buffer; |
| 162 | |
| 163 | #[derive(Default)] |
| 164 | struct Outbox { |
| 165 | mask: Mask, |
| 166 | reference: LumaGrid, |
| 167 | source_frame: u64, |
| 168 | version: u64, |
| 169 | } |
| 170 | |
| 171 | struct WorkerShared { |
| 172 | inbox: Latest<(u64, Frame)>, |
| 173 | outbox: Mutex<Outbox>, |
| 174 | stride: AtomicU64, |
| 175 | } |
| 176 | |
| 177 | fn stride_for(inference: Duration) -> u64 { |
| 178 | if inference > VERY_SLOW_INFERENCE { |
| 179 | 3 |
| 180 | } else if inference > SLOW_INFERENCE { |
| 181 | 2 |
| 182 | } else { |
| 183 | 1 |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | fn smooth_into(current: &mut Mask, fresh: Mask) { |
| 188 | if (current.width, current.height, current.matte) != (fresh.width, fresh.height, fresh.matte) { |
| 189 | *current = fresh; |
| 190 | return; |
| 191 | } |
| 192 | for (value, new) in current.values.iter_mut().zip(fresh.values) { |
| 193 | let change = new - *value; |
| 194 | let smoothing = MASK_SMOOTHING * (1. - change.abs() * MOTION_GAIN).max(0.); |
| 195 | *value += change * (1. - smoothing); |
| 196 | } |
| 197 | } |
| 198 | |
| 199 | fn run_worker(shared: &WorkerShared, inference: &mut dyn MaskInference) { |
| 200 | let mut smoothed = Mask::default(); |
| 201 | let mut smoothed_reference = LumaGrid::default(); |
| 202 | while let Some((source_frame, frame)) = shared.inbox.take() { |
| 203 | let reference = LumaGrid::of(&frame); |
| 204 | let started = Instant::now(); |
| 205 | let Ok(fresh) = inference.infer(frame) else { continue }; |
| 206 | let stride = if inference.accelerated() { 1 } else { stride_for(started.elapsed()) }; |
| 207 | shared.stride.store(stride, Ordering::Relaxed); |
| 208 | smoothed = propagate(&smoothed, &smoothed_reference, &reference); |
| 209 | smooth_into(&mut smoothed, fresh); |
| 210 | smoothed_reference.clone_from(&reference); |
| 211 | let mut outbox = shared.outbox.lock().expect("outbox lock"); |
| 212 | outbox.mask.clone_from(&smoothed); |
| 213 | outbox.reference = reference; |
| 214 | outbox.source_frame = source_frame; |
| 215 | outbox.version += 1; |
| 216 | } |
| 217 | } |
| 218 | |
| 219 | /// One segmentation mask for every effect: a worker thread segments the newest frame, the caller never waits on it. |
| 220 | pub struct MaskSource { |
| 221 | shared: Arc<WorkerShared>, |
| 222 | worker: Option<JoinHandle<()>>, |
| 223 | mask: Mask, |
| 224 | reference: LumaGrid, |
| 225 | source_frame: u64, |
| 226 | seen_version: u64, |
| 227 | frames: u64, |
| 228 | } |
| 229 | |
| 230 | impl MaskSource { |
| 231 | /// The models load on the worker, so the first frames pass unchanged instead of the camera thread waiting on them. |
| 232 | pub fn new() -> Result<Self> { |
| 233 | Ok(Self::spawn(|| LadderSegmenter::new().ok())) |
| 234 | } |
| 235 | |
| 236 | pub fn with_inference(inference: impl MaskInference) -> Self { |
| 237 | Self::spawn(move || Some(inference)) |
| 238 | } |
| 239 | |
| 240 | fn spawn<Inference: MaskInference>(create: impl FnOnce() -> Option<Inference> + Send + 'static) -> Self { |
| 241 | let shared = Arc::new(WorkerShared { inbox: Latest::default(), outbox: Mutex::default(), stride: AtomicU64::new(1) }); |
| 242 | let worker_shared = shared.clone(); |
| 243 | let worker = std::thread::Builder::new() |
| 244 | .name("segmentation".to_owned()) |
| 245 | .spawn(move || { |
| 246 | if let Some(mut inference) = create() { |
| 247 | run_worker(&worker_shared, &mut inference); |
| 248 | } |
| 249 | }) |
| 250 | .expect("segmentation thread"); |
| 251 | MaskSource { shared, worker: Some(worker), mask: Mask::default(), reference: LumaGrid::default(), source_frame: 0, seen_version: 0, frames: 0 } |
| 252 | } |
| 253 | |
| 254 | pub fn due(&self) -> bool { |
| 255 | self.frames.is_multiple_of(self.shared.stride.load(Ordering::Relaxed)) || self.mask.is_empty() |
| 256 | } |
| 257 | |
| 258 | pub fn mask(&self) -> &Mask { |
| 259 | &self.mask |
| 260 | } |
| 261 | |
| 262 | /// The luma grid of the frame the mask was made from. |
| 263 | pub fn reference(&self) -> &LumaGrid { |
| 264 | &self.reference |
| 265 | } |
| 266 | |
| 267 | /// Frames shown since the frame the current mask was made from. |
| 268 | pub fn age(&self) -> u64 { |
| 269 | self.frames.saturating_sub(self.source_frame + 1) |
| 270 | } |
| 271 | |
| 272 | /// Call once per frame; `frame` is only read when `due`. Answers whether a newer mask arrived. |
| 273 | pub fn refresh(&mut self, frame: impl FnOnce() -> Frame) -> bool { |
| 274 | if self.due() { |
| 275 | self.shared.inbox.put((self.frames, frame())); |
| 276 | } |
| 277 | self.frames += 1; |
| 278 | let outbox = self.shared.outbox.lock().expect("outbox lock"); |
| 279 | if outbox.version == self.seen_version { |
| 280 | return false; |
| 281 | } |
| 282 | self.seen_version = outbox.version; |
| 283 | self.mask.clone_from(&outbox.mask); |
| 284 | self.reference.clone_from(&outbox.reference); |
| 285 | self.source_frame = outbox.source_frame; |
| 286 | true |
| 287 | } |
| 288 | } |
| 289 | |
| 290 | impl Drop for MaskSource { |
| 291 | fn drop(&mut self) { |
| 292 | self.shared.inbox.close(); |
| 293 | if let Some(worker) = self.worker.take() { |
| 294 | let _ = worker.join(); |
| 295 | } |
| 296 | } |
| 297 | } |
| 298 | |
| 299 | #[cfg(test)] |
| 300 | mod tests { |
| 301 | use super::*; |
| 302 | use crate::camera::i420_from_rgba; |
| 303 | |
| 304 | const MASK_WIDTH: usize = 256; |
| 305 | const MASK_HEIGHT: usize = 144; |
| 306 | const WIDTH: usize = 160; |
| 307 | const HEIGHT: usize = 90; |
| 308 | |
| 309 | fn checkerboard() -> Vec<u8> { |
| 310 | let mut rgba = vec![255u8; WIDTH * HEIGHT * CHANNELS]; |
| 311 | for row in 0..HEIGHT { |
| 312 | for column in 0..WIDTH { |
| 313 | let value = if (row / 3 + column / 3) % 2 == 0 { 20 } else { 235 }; |
| 314 | rgba[(row * WIDTH + column) * CHANNELS..][..3].fill(value); |
| 315 | } |
| 316 | } |
| 317 | rgba |
| 318 | } |
| 319 | |
| 320 | fn oval_mask() -> Mask { |
| 321 | Mask::from_fn(MASK_WIDTH, MASK_HEIGHT, |x, y| if ((x - 0.5) * (x - 0.5)) / 0.04 + ((y - 0.5) * (y - 0.5)) / 0.09 <= 1. { 1. } else { 0. }) |
| 322 | } |
| 323 | |
| 324 | fn pixel(rgba: &[u8], x: usize, y: usize) -> u8 { |
| 325 | rgba[(y * WIDTH + x) * CHANNELS] |
| 326 | } |
| 327 | |
| 328 | fn roughness(rgba: &[u8], x: usize, y: usize) -> i32 { |
| 329 | (0..8).map(|step| (i32::from(pixel(rgba, x + step + 1, y)) - i32::from(pixel(rgba, x + step, y))).abs()).sum() |
| 330 | } |
| 331 | |
| 332 | #[test] |
| 333 | fn the_person_stays_sharp_and_the_background_is_smoothed() { |
| 334 | let original = checkerboard(); |
| 335 | let mut blurred = original.clone(); |
| 336 | compose(&mut blurred, WIDTH, HEIGHT, &oval_mask()); |
| 337 | let (center_x, center_y) = (WIDTH / 2, HEIGHT / 2); |
| 338 | assert_eq!(pixel(&blurred, center_x, center_y), pixel(&original, center_x, center_y)); |
| 339 | assert_eq!(roughness(&blurred, center_x - 4, center_y), roughness(&original, center_x - 4, center_y)); |
| 340 | assert!(roughness(&blurred, 2, 2) * 4 < roughness(&original, 2, 2)); |
| 341 | assert!(roughness(&blurred, WIDTH - 12, HEIGHT - 3) * 4 < roughness(&original, WIDTH - 12, HEIGHT - 3)); |
| 342 | } |
| 343 | |
| 344 | fn checkerboard_i420() -> I420Buffer { |
| 345 | let mut buffer = I420Buffer::new(WIDTH as u32, HEIGHT as u32); |
| 346 | let (stride_y, stride_u, _) = buffer.strides(); |
| 347 | let (plane_y, plane_u, plane_v) = buffer.data_mut(); |
| 348 | for row in 0..HEIGHT { |
| 349 | for column in 0..WIDTH { |
| 350 | plane_y[row * stride_y as usize + column] = if (row / 3 + column / 3) % 2 == 0 { 20 } else { 235 }; |
| 351 | } |
| 352 | } |
| 353 | for row in 0..HEIGHT / 2 { |
| 354 | for column in 0..WIDTH / 2 { |
| 355 | plane_u[row * stride_u as usize + column] = if (row / 3 + column / 3) % 2 == 0 { 60 } else { 200 }; |
| 356 | } |
| 357 | } |
| 358 | plane_v.fill(128); |
| 359 | buffer |
| 360 | } |
| 361 | |
| 362 | fn luma_roughness(buffer: &mut I420Buffer, x: usize, y: usize) -> i32 { |
| 363 | let stride = buffer.strides().0 as usize; |
| 364 | let plane = buffer.data_mut().0; |
| 365 | (0..8).map(|step| (i32::from(plane[y * stride + x + step + 1]) - i32::from(plane[y * stride + x + step])).abs()).sum() |
| 366 | } |
| 367 | |
| 368 | #[test] |
| 369 | fn the_planar_blur_keeps_the_person_and_smooths_luma_and_chroma_outside() { |
| 370 | let mut original = checkerboard_i420(); |
| 371 | let mut blurred = checkerboard_i420(); |
| 372 | compose_i420(&mut blurred, &oval_mask()); |
| 373 | let (center_x, center_y) = (WIDTH / 2, HEIGHT / 2); |
| 374 | assert_eq!(luma_roughness(&mut blurred, center_x - 4, center_y), luma_roughness(&mut original, center_x - 4, center_y)); |
| 375 | assert!(luma_roughness(&mut blurred, 2, 2) * 4 < luma_roughness(&mut original, 2, 2)); |
| 376 | let chroma = |buffer: &mut I420Buffer, x: usize, y: usize| { |
| 377 | let stride = buffer.strides().1 as usize; |
| 378 | i32::from(buffer.data_mut().1[y * stride + x]) |
| 379 | }; |
| 380 | assert_eq!(chroma(&mut blurred, center_x / 2, center_y / 2), chroma(&mut original, center_x / 2, center_y / 2)); |
| 381 | let spread = |buffer: &mut I420Buffer| (2..10).map(|x| (chroma(buffer, x + 1, 2) - chroma(buffer, x, 2)).abs()).sum::<i32>(); |
| 382 | assert!(spread(&mut blurred) * 4 < spread(&mut original)); |
| 383 | } |
| 384 | |
| 385 | #[test] |
| 386 | fn the_planar_blur_matches_the_rgba_blur_on_gray_frames() { |
| 387 | let mut planar = checkerboard_i420(); |
| 388 | planar.data_mut().1.fill(128); |
| 389 | compose_i420(&mut planar, &oval_mask()); |
| 390 | let mut rgba = checkerboard(); |
| 391 | compose(&mut rgba, WIDTH, HEIGHT, &oval_mask()); |
| 392 | let stride = planar.strides().0 as usize; |
| 393 | let plane = planar.data().0; |
| 394 | let worst = (0..HEIGHT).flat_map(|y| (0..WIDTH).map(move |x| (x, y))).map(|(x, y)| (i32::from(plane[y * stride + x]) - i32::from(pixel(&rgba, x, y))).abs()).max().unwrap(); |
| 395 | assert!(worst <= 24, "worst luma difference {worst}"); |
| 396 | } |
| 397 | |
| 398 | #[test] |
| 399 | fn a_full_person_mask_leaves_the_planes_untouched() { |
| 400 | let mut untouched = checkerboard_i420(); |
| 401 | compose_i420(&mut untouched, &Mask::filled(MASK_WIDTH, MASK_HEIGHT, 1.)); |
| 402 | let reference = checkerboard_i420(); |
| 403 | assert_eq!(untouched.data(), reference.data()); |
| 404 | } |
| 405 | |
| 406 | #[test] |
| 407 | fn the_edge_between_person_and_background_is_feathered() { |
| 408 | let original = checkerboard(); |
| 409 | let mut blurred = original.clone(); |
| 410 | let mut mask = oval_mask(); |
| 411 | compose(&mut blurred, WIDTH, HEIGHT, &mask); |
| 412 | let edge_row = HEIGHT / 2; |
| 413 | let changed_steps = (0..WIDTH - 1) |
| 414 | .filter(|&x| pixel(&blurred, x, edge_row) != pixel(&original, x, edge_row) && pixel(&blurred, x + 1, edge_row) == pixel(&original, x + 1, edge_row)) |
| 415 | .count(); |
| 416 | assert!(changed_steps <= 2, "a hard seam shows as one switch per side"); |
| 417 | mask.values.fill(1.); |
| 418 | let mut untouched = original.clone(); |
| 419 | compose(&mut untouched, WIDTH, HEIGHT, &mask); |
| 420 | assert_eq!(untouched, original); |
| 421 | } |
| 422 | |
| 423 | #[test] |
| 424 | fn an_empty_mask_blurs_the_whole_frame() { |
| 425 | let original = checkerboard(); |
| 426 | let mut blurred = original.clone(); |
| 427 | compose(&mut blurred, WIDTH, HEIGHT, &Mask::filled(MASK_WIDTH, MASK_HEIGHT, 0.)); |
| 428 | assert!(roughness(&blurred, 70, 40) * 4 < roughness(&original, 70, 40)); |
| 429 | assert!(blurred.chunks(CHANNELS).all(|pixel| pixel[3] == 255)); |
| 430 | } |
| 431 | |
| 432 | fn cover_of(color: [u8; 3]) -> PicturePlanes { |
| 433 | PicturePlanes::new(&BackgroundPicture::from_rgb(color.repeat(4 * 4), 4, 4).unwrap().covering(WIDTH, HEIGHT), WIDTH, HEIGHT) |
| 434 | } |
| 435 | |
| 436 | fn refine_rgba(mask: &Mask, rgba: &[u8], width: usize, height: usize) -> Matte { |
| 437 | crate::matte::refine_rgba(mask, rgba, width, height) |
| 438 | } |
| 439 | |
| 440 | #[test] |
| 441 | fn the_person_stays_and_the_picture_replaces_everything_else() { |
| 442 | let original = checkerboard(); |
| 443 | let mut replaced = original.clone(); |
| 444 | compose_image(&mut replaced, WIDTH, HEIGHT, &refine_rgba(&oval_mask(), &original, WIDTH, HEIGHT), &cover_of([10, 120, 200])); |
| 445 | let (center_x, center_y) = (WIDTH / 2, HEIGHT / 2); |
| 446 | assert_eq!(pixel(&replaced, center_x, center_y), pixel(&original, center_x, center_y)); |
| 447 | for (x, y) in [(2, 2), (WIDTH - 3, HEIGHT - 3), (2, HEIGHT - 3)] { |
| 448 | let shown = &replaced[(y * WIDTH + x) * CHANNELS..][..4]; |
| 449 | assert!(shown.iter().zip([10, 120, 200, 255]).all(|(&shown, wanted)| shown.abs_diff(wanted) <= 3), "{shown:?}"); |
| 450 | } |
| 451 | } |
| 452 | |
| 453 | #[test] |
| 454 | fn the_picture_edge_is_feathered_like_the_blur_edge() { |
| 455 | let original = checkerboard(); |
| 456 | let mut replaced = original.clone(); |
| 457 | compose_image(&mut replaced, WIDTH, HEIGHT, &refine_rgba(&oval_mask(), &original, WIDTH, HEIGHT), &cover_of([0, 0, 0])); |
| 458 | let edge_row = HEIGHT / 2; |
| 459 | let switches = (0..WIDTH - 1) |
| 460 | .filter(|&x| pixel(&replaced, x, edge_row) != pixel(&original, x, edge_row) && pixel(&replaced, x + 1, edge_row) == pixel(&original, x + 1, edge_row)) |
| 461 | .count(); |
| 462 | assert!(switches <= 2); |
| 463 | let mut everyone = original.clone(); |
| 464 | compose_image(&mut everyone, WIDTH, HEIGHT, &refine_rgba(&Mask::filled(MASK_WIDTH, MASK_HEIGHT, 1.), &original, WIDTH, HEIGHT), &cover_of([0, 0, 0])); |
| 465 | assert_eq!(everyone, original); |
| 466 | let empty = refine_rgba(&Mask::filled(MASK_WIDTH, MASK_HEIGHT, 0.), &original, WIDTH, HEIGHT); |
| 467 | let mut nobody = original; |
| 468 | compose_image(&mut nobody, WIDTH, HEIGHT, &empty, &cover_of([0, 0, 0])); |
| 469 | assert!(nobody.chunks(CHANNELS).all(|pixel| pixel[..3] == [0, 0, 0] && pixel[3] == 255)); |
| 470 | } |
| 471 | |
| 472 | fn wait_for_mask(source: &mut MaskSource, frame: impl Fn() -> Frame) -> bool { |
| 473 | let deadline = Instant::now() + Duration::from_secs(10); |
| 474 | while Instant::now() < deadline { |
| 475 | if source.refresh(&frame) { |
| 476 | return true; |
| 477 | } |
| 478 | std::thread::sleep(Duration::from_millis(5)); |
| 479 | } |
| 480 | false |
| 481 | } |
| 482 | |
| 483 | #[test] |
| 484 | fn the_mask_source_segments_when_due_and_keeps_one_mask() { |
| 485 | let mut source = MaskSource::new().expect("model loads"); |
| 486 | assert!(wait_for_mask(&mut source, || i420_from_rgba(&checkerboard(), WIDTH as u32, HEIGHT as u32))); |
| 487 | assert_eq!(source.mask().values.len(), MASK_WIDTH * MASK_HEIGHT); |
| 488 | source.shared.stride.store(3, Ordering::Relaxed); |
| 489 | source.frames = 1; |
| 490 | assert!(!source.due()); |
| 491 | assert!(!source.refresh(|| unreachable!("a skipped frame is not read"))); |
| 492 | } |
| 493 | |
| 494 | struct SlowSegmenter { |
| 495 | delay: Duration, |
| 496 | seen: Arc<Mutex<Vec<u8>>>, |
| 497 | } |
| 498 | |
| 499 | impl MaskInference for SlowSegmenter { |
| 500 | fn infer(&mut self, frame: I420Buffer) -> Result<Mask> { |
| 501 | let marker = frame.data().0[0]; |
| 502 | self.seen.lock().unwrap().push(marker); |
| 503 | std::thread::sleep(self.delay); |
| 504 | Ok(Mask::filled(MASK_WIDTH, MASK_HEIGHT, f32::from(marker) / 255.)) |
| 505 | } |
| 506 | } |
| 507 | |
| 508 | fn marked_frame(marker: u8) -> Frame { |
| 509 | let mut buffer = I420Buffer::new(2, 2); |
| 510 | buffer.data_mut().0.fill(marker); |
| 511 | buffer |
| 512 | } |
| 513 | |
| 514 | #[test] |
| 515 | fn a_slow_segmenter_never_blocks_the_sender() { |
| 516 | let seen = Arc::new(Mutex::new(Vec::new())); |
| 517 | let mut source = MaskSource::with_inference(SlowSegmenter { delay: Duration::from_millis(300), seen }); |
| 518 | let started = Instant::now(); |
| 519 | for _ in 0..30 { |
| 520 | source.refresh(|| marked_frame(1)); |
| 521 | } |
| 522 | assert!(started.elapsed() < Duration::from_millis(150)); |
| 523 | } |
| 524 | |
| 525 | #[test] |
| 526 | fn the_mask_age_counts_the_frames_shown_since_its_source_frame() { |
| 527 | let seen = Arc::new(Mutex::new(Vec::new())); |
| 528 | let mut source = MaskSource::with_inference(SlowSegmenter { delay: Duration::from_millis(60), seen }); |
| 529 | assert!(!source.refresh(|| marked_frame(5))); |
| 530 | let deadline = Instant::now() + Duration::from_secs(10); |
| 531 | let mut shown = 1; |
| 532 | while !source.refresh(|| marked_frame(6)) && Instant::now() < deadline { |
| 533 | shown += 1; |
| 534 | std::thread::sleep(Duration::from_millis(10)); |
| 535 | } |
| 536 | assert!(shown >= 3, "the mask came back before the model was done"); |
| 537 | assert_eq!(source.age(), shown - 1); |
| 538 | assert_eq!(source.reference().values.len(), 4); |
| 539 | assert!(!source.refresh(|| marked_frame(7))); |
| 540 | assert_eq!(source.age(), shown); |
| 541 | } |
| 542 | |
| 543 | #[test] |
| 544 | fn the_worker_hands_over_the_newest_frame_and_drops_stale_ones() { |
| 545 | let seen = Arc::new(Mutex::new(Vec::new())); |
| 546 | let mut source = MaskSource::with_inference(SlowSegmenter { delay: Duration::from_millis(100), seen: seen.clone() }); |
| 547 | for marker in [10, 20, 30, 40] { |
| 548 | source.refresh(|| marked_frame(marker)); |
| 549 | std::thread::sleep(Duration::from_millis(5)); |
| 550 | } |
| 551 | let deadline = Instant::now() + Duration::from_secs(10); |
| 552 | while seen.lock().unwrap().last() != Some(&40) && Instant::now() < deadline { |
| 553 | source.refresh(|| marked_frame(40)); |
| 554 | std::thread::sleep(Duration::from_millis(10)); |
| 555 | } |
| 556 | let processed = seen.lock().unwrap().clone(); |
| 557 | assert_eq!(processed.last(), Some(&40)); |
| 558 | assert!(!processed.contains(&20) || !processed.contains(&30), "stale frames pile up: {processed:?}"); |
| 559 | } |
| 560 | } |