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