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