BlueGit

ict rusty-teams

Files

rusty-teams / crates / calling / src / blur.rs

blur.rs

blur.rs 33.6 KiB Download Raw
1use std::io::Cursor;
2use std::sync::{Arc, Condvar, Mutex};
3use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
4use std::thread::JoinHandle;
5use std::time::{Duration, Instant};
6
7use tract_onnx::prelude::*;
8
9use libwebrtc::native::yuv_helper::i420_to_abgr;
10use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};
11
12use crate::background::BackgroundPicture;
13use crate::effects::CameraEffects;
14use crate::error::{Error, Result};
15use crate::matte::{Matte, Planes, refine, refine_rgba};
16use crate::standout::Cutout;
17
18const MODEL: &[u8] = include_bytes!("../assets/selfie_segmentation_landscape.onnx");
19pub const MASK_WIDTH: usize = 256;
20pub const MASK_HEIGHT: usize = 144;
21const CHANNELS: usize = 4;
22const BACKGROUND_SCALE: usize = 4;
23const BLUR_RADIUS: usize = 3;
24const BLUR_PASSES: usize = 2;
25const MASK_SMOOTHING: f32 = 0.35;
26const MOTION_GAIN: f32 = 2.;
27const SLOW_INFERENCE: Duration = Duration::from_millis(22);
28const VERY_SLOW_INFERENCE: Duration = Duration::from_millis(45);
29const MAX_BANDS: usize = 4;
30const MASK_INPUT_WIDTH: u32 = 512;
31
32type Plan = std::sync::Arc<TypedRunnableModel>;
33
34/// MediaPipe selfie segmentation (landscape, 256x144); answers the probability of "person" per mask pixel.
35pub struct Segmenter {
36 plan: Plan,
37}
38
39impl Segmenter {
40 pub fn new() -> Result<Self> {
41 let plan = Self::load().map_err(|error| Error::Webrtc(format!("segmentation model: {error}")))?;
42 Ok(Segmenter { plan })
43 }
44
45 fn load() -> TractResult<Plan> {
46 let model = tract_onnx::onnx().model_for_read(&mut Cursor::new(MODEL))?;
47 let batch = model.symbols.sym("batch_size");
48 let one_image = std::collections::HashMap::from([(batch, TDim::from(1))]);
49 model.into_typed()?.set_symbols(&one_image)?.into_optimized()?.into_runnable()
50 }
51
52 pub fn mask(&self, rgba: &[u8], width: usize, height: usize) -> Result<Vec<f32>> {
53 let input = model_input(rgba, width, height);
54 let outputs = self.plan.run(tvec!(input.into())).map_err(|error| Error::Webrtc(format!("segmentation: {error}")))?;
55 let values = outputs[0].to_plain_array_view::<f32>().map_err(|error| Error::Webrtc(format!("segmentation output: {error}")))?;
56 if values.len() != MASK_WIDTH * MASK_HEIGHT {
57 return Err(Error::Webrtc(format!("segmentation output has {} values", values.len())));
58 }
59 Ok(values.iter().map(|value| value.clamp(0., 1.)).collect())
60 }
61}
62
63fn model_input(rgba: &[u8], width: usize, height: usize) -> Tensor {
64 let plane = MASK_WIDTH * MASK_HEIGHT;
65 let mut data = vec![0f32; 3 * plane];
66 for row in 0..MASK_HEIGHT {
67 let top = (row * 2 * height / (MASK_HEIGHT * 2)).min(height - 1);
68 let bottom = ((row * 2 + 1) * height / (MASK_HEIGHT * 2)).min(height - 1);
69 for column in 0..MASK_WIDTH {
70 let left = (column * 2 * width / (MASK_WIDTH * 2)).min(width - 1);
71 let right = ((column * 2 + 1) * width / (MASK_WIDTH * 2)).min(width - 1);
72 for channel in 0..3 {
73 let sum: u32 = [(top, left), (top, right), (bottom, left), (bottom, right)]
74 .iter()
75 .map(|&(y, x)| u32::from(rgba[(y * width + x) * CHANNELS + channel]))
76 .sum();
77 data[channel * plane + row * MASK_WIDTH + column] = sum as f32 / (4. * 255.);
78 }
79 }
80 }
81 Tensor::from_shape(&[1, 3, MASK_HEIGHT, MASK_WIDTH], &data).expect("shape matches data")
82}
83
84pub(crate) struct Axis {
85 pub(crate) first: Vec<usize>,
86 pub(crate) second: Vec<usize>,
87 pub(crate) weight: Vec<f32>,
88}
89
90pub(crate) fn axis(output: usize, input: usize) -> Axis {
91 let mut axis = Axis { first: Vec::with_capacity(output), second: Vec::with_capacity(output), weight: Vec::with_capacity(output) };
92 for index in 0..output {
93 let position = ((index as f32 + 0.5) * input as f32 / output as f32 - 0.5).clamp(0., (input - 1) as f32);
94 let first = position.floor() as usize;
95 axis.first.push(first);
96 axis.second.push((first + 1).min(input - 1));
97 axis.weight.push(position - first as f32);
98 }
99 axis
100}
101
102fn downscaled(rgba: &[u8], width: usize, height: usize) -> (Vec<u8>, usize, usize) {
103 let small_width = width.div_ceil(BACKGROUND_SCALE);
104 let small_height = height.div_ceil(BACKGROUND_SCALE);
105 let mut small = vec![0u8; small_width * small_height * 3];
106 for row in 0..small_height {
107 for column in 0..small_width {
108 let mut sums = [0u32; 3];
109 let mut count = 0u32;
110 for y in row * BACKGROUND_SCALE..((row + 1) * BACKGROUND_SCALE).min(height) {
111 for x in column * BACKGROUND_SCALE..((column + 1) * BACKGROUND_SCALE).min(width) {
112 for (channel, sum) in sums.iter_mut().enumerate() {
113 *sum += u32::from(rgba[(y * width + x) * CHANNELS + channel]);
114 }
115 count += 1;
116 }
117 }
118 for (channel, sum) in sums.iter().enumerate() {
119 small[(row * small_width + column) * 3 + channel] = (sum / count) as u8;
120 }
121 }
122 }
123 (small, small_width, small_height)
124}
125
126fn blur_pass(input: &[u8], output: &mut [u8], lines: usize, length: usize, line_stride: usize, step: usize, channels: usize) {
127 let radius = BLUR_RADIUS as isize;
128 let window = (BLUR_RADIUS * 2 + 1) as u32;
129 for line in 0..lines {
130 for channel in 0..channels {
131 let base = line * line_stride + channel;
132 let read = |index: isize| u32::from(input[base + index.clamp(0, length as isize - 1) as usize * step]);
133 let mut sum: u32 = (-radius..=radius).map(read).sum();
134 for index in 0..length {
135 output[base + index * step] = (sum / window) as u8;
136 sum = sum + read(index as isize + radius + 1) - read(index as isize - radius);
137 }
138 }
139 }
140}
141
142fn box_blur(image: &mut [u8], width: usize, height: usize, scratch: &mut [u8], channels: usize) {
143 blur_pass(image, scratch, height, width, width * channels, channels, channels);
144 blur_pass(scratch, image, width, height, channels, width * channels, channels);
145}
146
147fn blurred_background(rgba: &[u8], width: usize, height: usize) -> (Vec<u8>, usize, usize) {
148 let (mut small, small_width, small_height) = downscaled(rgba, width, height);
149 let mut scratch = vec![0u8; small.len()];
150 for _ in 0..BLUR_PASSES {
151 box_blur(&mut small, small_width, small_height, &mut scratch, 3);
152 }
153 (small, small_width, small_height)
154}
155
156struct Composer<'a> {
157 background: &'a [u8],
158 matte: &'a Matte,
159 width: usize,
160 small_x: Axis,
161 small_y: Axis,
162 small_width: usize,
163}
164
165impl Composer<'_> {
166 fn rows(&self, rgba: &mut [u8], first_row: usize) {
167 for (offset, line) in rgba.chunks_exact_mut(self.width * CHANNELS).enumerate() {
168 self.row(line, first_row + offset);
169 }
170 }
171
172 fn row(&self, line: &mut [u8], row: usize) {
173 let (small_top, small_bottom, small_fraction) = (self.small_y.first[row] * self.small_width, self.small_y.second[row] * self.small_width, self.small_y.weight[row]);
174 let alphas = &self.matte.alpha[row * self.matte.width..][..self.matte.width];
175 for (column, (pixel, &alpha)) in line.as_chunks_mut::<CHANNELS>().0.iter_mut().zip(alphas).enumerate() {
176 if alpha == u8::MAX {
177 continue;
178 }
179 let person = f32::from(alpha) / 255.;
180 let (left, right, across) = (self.small_x.first[column], self.small_x.second[column], self.small_x.weight[column]);
181 for (channel, value) in pixel.iter_mut().take(3).enumerate() {
182 let sample = |line: usize, index: usize| f32::from(self.background[(line + index) * 3 + channel]);
183 let upper = sample(small_top, left) * (1. - across) + sample(small_top, right) * across;
184 let lower = sample(small_bottom, left) * (1. - across) + sample(small_bottom, right) * across;
185 let blurred = upper * (1. - small_fraction) + lower * small_fraction;
186 *value = (f32::from(*value) * person + blurred * (1. - person) + 0.5) as u8;
187 }
188 }
189 }
190}
191
192fn compose_over(rgba: &mut [u8], width: usize, height: usize, matte: &Matte, background: &[u8], background_width: usize, background_height: usize) {
193 let composer = Composer {
194 background,
195 matte,
196 width,
197 small_x: axis(width, background_width),
198 small_y: axis(height, background_height),
199 small_width: background_width,
200 };
201 let bands = std::thread::available_parallelism().map_or(1, usize::from).min(MAX_BANDS);
202 let rows_per_band = height.div_ceil(bands);
203 std::thread::scope(|scope| {
204 for (index, band) in rgba.chunks_mut(rows_per_band * width * CHANNELS).enumerate() {
205 let composer = &composer;
206 scope.spawn(move || composer.rows(band, index * rows_per_band));
207 }
208 });
209}
210
211fn downscaled_plane(plane: &[u8], stride: usize, width: usize, height: usize, factor: usize) -> (Vec<u8>, usize, usize) {
212 let small_width = width.div_ceil(factor);
213 let small_height = height.div_ceil(factor);
214 let mut small = vec![0u8; small_width * small_height];
215 for (row, line) in small.chunks_exact_mut(small_width).enumerate() {
216 let rows = row * factor..((row + 1) * factor).min(height);
217 let mut sums = vec![0u32; small_width];
218 for source_row in rows.clone() {
219 for (sum, group) in sums.iter_mut().zip(plane[source_row * stride..][..width].chunks(factor)) {
220 *sum += group.iter().map(|&value| u32::from(value)).sum::<u32>();
221 }
222 }
223 for (column, (slot, sum)) in line.iter_mut().zip(&sums).enumerate() {
224 let columns = factor.min(width - column * factor);
225 *slot = (sum / (rows.len() * columns) as u32) as u8;
226 }
227 }
228 (small, small_width, small_height)
229}
230
231fn blurred_plane(plane: &[u8], stride: usize, width: usize, height: usize, factor: usize) -> (Vec<u8>, usize, usize) {
232 let (mut small, small_width, small_height) = downscaled_plane(plane, stride, width, height, factor);
233 let mut scratch = vec![0u8; small.len()];
234 for _ in 0..BLUR_PASSES {
235 box_blur(&mut small, small_width, small_height, &mut scratch, 1);
236 }
237 (small, small_width, small_height)
238}
239
240struct PlaneComposer<'a> {
241 background: &'a [u8],
242 matte: &'a Matte,
243 width: usize,
244 small_x: Axis,
245 small_y: Axis,
246 small_width: usize,
247}
248
249impl PlaneComposer<'_> {
250 fn new<'a>(background: &'a [u8], small_width: usize, small_height: usize, matte: &'a Matte) -> PlaneComposer<'a> {
251 let (width, height) = (matte.width, matte.height);
252 PlaneComposer {
253 background,
254 matte,
255 width,
256 small_x: axis(width, small_width),
257 small_y: axis(height, small_height),
258 small_width,
259 }
260 }
261
262 fn rows(&self, plane: &mut [u8], stride: usize, first_row: usize) {
263 for (offset, line) in plane.chunks_mut(stride).enumerate() {
264 let length = self.width.min(line.len());
265 self.row(&mut line[..length], first_row + offset);
266 }
267 }
268
269 fn row(&self, line: &mut [u8], row: usize) {
270 let (small_top, small_bottom, small_fraction) = (self.small_y.first[row] * self.small_width, self.small_y.second[row] * self.small_width, self.small_y.weight[row]);
271 let alphas = &self.matte.alpha[row * self.width..][..self.width];
272 for (column, (value, &alpha)) in line.iter_mut().zip(alphas).enumerate() {
273 if alpha == u8::MAX {
274 continue;
275 }
276 let person = f32::from(alpha) / 255.;
277 let (left, right, across) = (self.small_x.first[column], self.small_x.second[column], self.small_x.weight[column]);
278 let sample = |line: usize, index: usize| f32::from(self.background[line + index]);
279 let upper = sample(small_top, left) * (1. - across) + sample(small_top, right) * across;
280 let lower = sample(small_bottom, left) * (1. - across) + sample(small_bottom, right) * across;
281 let blurred = upper * (1. - small_fraction) + lower * small_fraction;
282 *value = (f32::from(*value) * person + blurred * (1. - person) + 0.5) as u8;
283 }
284 }
285}
286
287/// `compose` on I420 planes: luma blurs at `BACKGROUND_SCALE`, chroma at the same grid, with no RGBA round trip.
288pub fn compose_i420(buffer: &mut I420Buffer, mask: &[f32]) {
289 let (width, height) = (buffer.width() as usize, buffer.height() as usize);
290 let (chroma_width, chroma_height) = (width.div_ceil(2), height.div_ceil(2));
291 let (stride_y, stride_u, stride_v) = buffer.strides();
292 let (stride_y, stride_u, stride_v) = (stride_y as usize, stride_u as usize, stride_v as usize);
293 let luma_matte = refine(mask, Planes::of(buffer));
294 let chroma_matte = luma_matte.halved();
295 let (plane_y, plane_u, plane_v) = buffer.data_mut();
296 let (background_y, small_width, small_height) = blurred_plane(plane_y, stride_y, width, height, BACKGROUND_SCALE);
297 let (background_u, ..) = blurred_plane(plane_u, stride_u, chroma_width, chroma_height, BACKGROUND_SCALE / 2);
298 let (background_v, ..) = blurred_plane(plane_v, stride_v, chroma_width, chroma_height, BACKGROUND_SCALE / 2);
299 let luma = PlaneComposer::new(&background_y, small_width, small_height, &luma_matte);
300 let blue = PlaneComposer::new(&background_u, small_width, small_height, &chroma_matte);
301 let red = PlaneComposer::new(&background_v, small_width, small_height, &chroma_matte);
302 let bands = std::thread::available_parallelism().map_or(1, usize::from).min(MAX_BANDS);
303 std::thread::scope(|scope| {
304 for (composer, plane, stride, rows) in [(&luma, plane_y, stride_y, height), (&blue, plane_u, stride_u, chroma_height), (&red, plane_v, stride_v, chroma_height)] {
305 let rows_per_band = rows.div_ceil(bands);
306 for (index, band) in plane.chunks_mut(rows_per_band * stride).enumerate() {
307 scope.spawn(move || composer.rows(band, stride, index * rows_per_band));
308 }
309 }
310 });
311}
312
313/// Keeps the person (mask near 1) sharp and replaces the rest with a blurred copy; `mask` is `MASK_WIDTH` x `MASK_HEIGHT`.
314pub fn compose(rgba: &mut [u8], width: usize, height: usize, mask: &[f32]) {
315 let matte = refine_rgba(mask, rgba, width, height);
316 compose_blurred(rgba, width, height, &matte);
317}
318
319fn compose_blurred(rgba: &mut [u8], width: usize, height: usize, matte: &Matte) {
320 let (background, small_width, small_height) = blurred_background(rgba, width, height);
321 compose_over(rgba, width, height, matte, &background, small_width, small_height);
322}
323
324pub fn compose_image(rgba: &mut [u8], width: usize, height: usize, matte: &Matte, covered: &[u8]) {
325 compose_over(rgba, width, height, matte, covered, width, height);
326}
327
328/// Shared between the UI command and the camera thread.
329#[derive(Default)]
330pub struct BlurSettings {
331 enabled: AtomicBool,
332 standout: AtomicBool,
333 average_micros: AtomicU32,
334 picture: Mutex<Option<Arc<BackgroundPicture>>>,
335 effects: Mutex<CameraEffects>,
336 cutout: Mutex<Option<Arc<Cutout>>>,
337}
338
339impl BlurSettings {
340 pub fn set_enabled(&self, enabled: bool) {
341 self.enabled.store(enabled, Ordering::Relaxed);
342 }
343
344 pub fn enabled(&self) -> bool {
345 self.enabled.load(Ordering::Relaxed)
346 }
347
348 pub fn set_standout(&self, standout: bool) {
349 self.standout.store(standout, Ordering::Relaxed);
350 if !standout {
351 self.set_cutout(None);
352 }
353 }
354
355 pub fn standout(&self) -> bool {
356 self.standout.load(Ordering::Relaxed)
357 }
358
359 pub fn set_cutout(&self, cutout: Option<Arc<Cutout>>) {
360 *self.cutout.lock().expect("cutout lock") = cutout;
361 }
362
363 pub fn cutout(&self) -> Option<Arc<Cutout>> {
364 self.cutout.lock().expect("cutout lock").clone()
365 }
366
367 pub fn set_picture(&self, picture: Option<Arc<BackgroundPicture>>) {
368 *self.picture.lock().expect("picture lock") = picture;
369 }
370
371 fn picture(&self) -> Option<Arc<BackgroundPicture>> {
372 self.picture.lock().expect("picture lock").clone()
373 }
374
375 pub fn set_effects(&self, effects: CameraEffects) {
376 *self.effects.lock().expect("effects lock") = effects;
377 }
378
379 pub fn effects(&self) -> CameraEffects {
380 *self.effects.lock().expect("effects lock")
381 }
382
383 pub fn active(&self) -> bool {
384 self.enabled() || self.standout() || self.effects().alters_frame()
385 }
386
387 pub fn average_ms(&self) -> f32 {
388 self.average_micros.load(Ordering::Relaxed) as f32 / 1000.
389 }
390
391 pub fn set_average_ms(&self, average_ms: f64) {
392 self.average_micros.store((average_ms * 1000.) as u32, Ordering::Relaxed);
393 }
394}
395
396/// Replaces the background of a frame; the mask comes from the shared `MaskSource`.
397pub struct BlurStage {
398 settings: Arc<BlurSettings>,
399 covered: Option<CoveredPicture>,
400}
401
402struct CoveredPicture {
403 picture: Arc<BackgroundPicture>,
404 width: usize,
405 height: usize,
406 rgb: Vec<u8>,
407}
408
409impl BlurStage {
410 pub fn new(settings: Arc<BlurSettings>) -> Self {
411 BlurStage { settings, covered: None }
412 }
413
414 fn refresh_covered(&mut self, width: usize, height: usize) {
415 let Some(picture) = self.settings.picture() else {
416 self.covered = None;
417 return;
418 };
419 let fresh = self.covered.as_ref().is_some_and(|covered| Arc::ptr_eq(&covered.picture, &picture) && covered.width == width && covered.height == height);
420 if !fresh {
421 let rgb = picture.covering(width, height);
422 self.covered = Some(CoveredPicture { picture, width, height, rgb });
423 }
424 }
425
426 pub fn covers(&mut self, width: usize, height: usize) -> bool {
427 self.refresh_covered(width, height);
428 self.covered.is_some()
429 }
430
431 pub fn compose(&mut self, rgba: &mut [u8], width: usize, height: usize, matte: &Matte) {
432 self.refresh_covered(width, height);
433 match &self.covered {
434 Some(covered) => compose_image(rgba, width, height, matte, &covered.rgb),
435 None => compose_blurred(rgba, width, height, matte),
436 }
437 }
438}
439
440pub trait MaskInference: Send + 'static {
441 fn infer(&self, frame: I420Buffer) -> Result<Vec<f32>>;
442}
443
444impl MaskInference for Segmenter {
445 fn infer(&self, frame: I420Buffer) -> Result<Vec<f32>> {
446 let (rgba, width, height) = mask_input(frame);
447 self.mask(&rgba, width, height)
448 }
449}
450
451fn mask_input(mut buffer: I420Buffer) -> (Vec<u8>, usize, usize) {
452 let (width, height) = (buffer.width(), buffer.height());
453 let small_width = width.min(MASK_INPUT_WIDTH) & !1;
454 let small_height = (u64::from(height) * u64::from(small_width) / u64::from(width)) as u32 & !1;
455 let small = if (small_width, small_height) == (width, height) { None } else { Some(buffer.scale(small_width as i32, small_height as i32)) };
456 let source = small.as_ref().unwrap_or(&buffer);
457 let (stride_y, stride_u, stride_v) = source.strides();
458 let (plane_y, plane_u, plane_v) = source.data();
459 let mut rgba = vec![0u8; small_width as usize * small_height as usize * CHANNELS];
460 i420_to_abgr(plane_y, stride_y, plane_u, stride_u, plane_v, stride_v, &mut rgba, small_width * CHANNELS as u32, small_width as i32, small_height as i32);
461 (rgba, small_width as usize, small_height as usize)
462}
463
464type Frame = I420Buffer;
465
466#[derive(Default)]
467struct Inbox {
468 newest: Option<Frame>,
469 closed: bool,
470}
471
472#[derive(Default)]
473struct Outbox {
474 mask: Vec<f32>,
475 version: u64,
476}
477
478struct WorkerShared {
479 inbox: Mutex<Inbox>,
480 wake: Condvar,
481 outbox: Mutex<Outbox>,
482 stride: AtomicU64,
483}
484
485fn stride_for(inference: Duration) -> u64 {
486 if inference > VERY_SLOW_INFERENCE {
487 3
488 } else if inference > SLOW_INFERENCE {
489 2
490 } else {
491 1
492 }
493}
494
495fn smooth_into(current: &mut Vec<f32>, fresh: Vec<f32>) {
496 if current.is_empty() {
497 *current = fresh;
498 return;
499 }
500 for (value, new) in current.iter_mut().zip(fresh) {
501 let change = new - *value;
502 let smoothing = MASK_SMOOTHING * (1. - change.abs() * MOTION_GAIN).max(0.);
503 *value += change * (1. - smoothing);
504 }
505}
506
507fn run_worker(shared: &WorkerShared, inference: &dyn MaskInference) {
508 let mut smoothed = Vec::new();
509 loop {
510 let frame = {
511 let mut inbox = shared.inbox.lock().expect("inbox lock");
512 loop {
513 if inbox.closed {
514 return;
515 }
516 if let Some(frame) = inbox.newest.take() {
517 break frame;
518 }
519 inbox = shared.wake.wait(inbox).expect("inbox lock");
520 }
521 };
522 let started = Instant::now();
523 let Ok(fresh) = inference.infer(frame) else { continue };
524 shared.stride.store(stride_for(started.elapsed()), Ordering::Relaxed);
525 smooth_into(&mut smoothed, fresh);
526 let mut outbox = shared.outbox.lock().expect("outbox lock");
527 outbox.mask.clone_from(&smoothed);
528 outbox.version += 1;
529 }
530}
531
532/// One segmentation mask for every effect: a worker thread segments the newest frame, the caller never waits on it.
533pub struct MaskSource {
534 shared: Arc<WorkerShared>,
535 worker: Option<JoinHandle<()>>,
536 mask: Vec<f32>,
537 seen_version: u64,
538 frames: u64,
539}
540
541impl MaskSource {
542 pub fn new() -> Result<Self> {
543 Ok(Self::with_inference(Segmenter::new()?))
544 }
545
546 pub fn with_inference(inference: impl MaskInference) -> Self {
547 let shared = Arc::new(WorkerShared { inbox: Mutex::default(), wake: Condvar::new(), outbox: Mutex::default(), stride: AtomicU64::new(1) });
548 let worker_shared = shared.clone();
549 let worker = std::thread::Builder::new()
550 .name("segmentation".to_owned())
551 .spawn(move || run_worker(&worker_shared, &inference))
552 .expect("segmentation thread");
553 MaskSource { shared, worker: Some(worker), mask: Vec::new(), seen_version: 0, frames: 0 }
554 }
555
556 pub fn due(&self) -> bool {
557 self.frames.is_multiple_of(self.shared.stride.load(Ordering::Relaxed)) || self.mask.is_empty()
558 }
559
560 pub fn mask(&self) -> &[f32] {
561 &self.mask
562 }
563
564 /// Call once per frame; `frame` is only read when `due`. Answers whether a newer mask arrived.
565 pub fn refresh(&mut self, frame: impl FnOnce() -> Frame) -> bool {
566 let due = self.due();
567 self.frames += 1;
568 if due {
569 self.shared.inbox.lock().expect("inbox lock").newest = Some(frame());
570 self.shared.wake.notify_one();
571 }
572 let outbox = self.shared.outbox.lock().expect("outbox lock");
573 if outbox.version == self.seen_version {
574 return false;
575 }
576 self.seen_version = outbox.version;
577 self.mask.clone_from(&outbox.mask);
578 true
579 }
580}
581
582impl Drop for MaskSource {
583 fn drop(&mut self) {
584 self.shared.inbox.lock().expect("inbox lock").closed = true;
585 self.shared.wake.notify_one();
586 if let Some(worker) = self.worker.take() {
587 let _ = worker.join();
588 }
589 }
590}
591
592#[cfg(test)]
593mod tests {
594 use super::*;
595 use crate::camera::i420_from_rgba;
596
597 const WIDTH: usize = 160;
598 const HEIGHT: usize = 90;
599
600 fn checkerboard() -> Vec<u8> {
601 let mut rgba = vec![255u8; WIDTH * HEIGHT * CHANNELS];
602 for row in 0..HEIGHT {
603 for column in 0..WIDTH {
604 let value = if (row / 3 + column / 3) % 2 == 0 { 20 } else { 235 };
605 rgba[(row * WIDTH + column) * CHANNELS..][..3].fill(value);
606 }
607 }
608 rgba
609 }
610
611 fn oval_mask() -> Vec<f32> {
612 (0..MASK_WIDTH * MASK_HEIGHT)
613 .map(|index| {
614 let (x, y) = ((index % MASK_WIDTH) as f32 / MASK_WIDTH as f32 - 0.5, (index / MASK_WIDTH) as f32 / MASK_HEIGHT as f32 - 0.5);
615 if (x * x) / 0.04 + (y * y) / 0.09 <= 1. { 1. } else { 0. }
616 })
617 .collect()
618 }
619
620 fn pixel(rgba: &[u8], x: usize, y: usize) -> u8 {
621 rgba[(y * WIDTH + x) * CHANNELS]
622 }
623
624 fn roughness(rgba: &[u8], x: usize, y: usize) -> i32 {
625 (0..8).map(|step| (i32::from(pixel(rgba, x + step + 1, y)) - i32::from(pixel(rgba, x + step, y))).abs()).sum()
626 }
627
628 #[test]
629 fn the_person_stays_sharp_and_the_background_is_smoothed() {
630 let original = checkerboard();
631 let mut blurred = original.clone();
632 compose(&mut blurred, WIDTH, HEIGHT, &oval_mask());
633 let (center_x, center_y) = (WIDTH / 2, HEIGHT / 2);
634 assert_eq!(pixel(&blurred, center_x, center_y), pixel(&original, center_x, center_y));
635 assert_eq!(roughness(&blurred, center_x - 4, center_y), roughness(&original, center_x - 4, center_y));
636 assert!(roughness(&blurred, 2, 2) * 4 < roughness(&original, 2, 2));
637 assert!(roughness(&blurred, WIDTH - 12, HEIGHT - 3) * 4 < roughness(&original, WIDTH - 12, HEIGHT - 3));
638 }
639
640 fn checkerboard_i420() -> I420Buffer {
641 let mut buffer = I420Buffer::new(WIDTH as u32, HEIGHT as u32);
642 let (stride_y, stride_u, _) = buffer.strides();
643 let (plane_y, plane_u, plane_v) = buffer.data_mut();
644 for row in 0..HEIGHT {
645 for column in 0..WIDTH {
646 plane_y[row * stride_y as usize + column] = if (row / 3 + column / 3) % 2 == 0 { 20 } else { 235 };
647 }
648 }
649 for row in 0..HEIGHT / 2 {
650 for column in 0..WIDTH / 2 {
651 plane_u[row * stride_u as usize + column] = if (row / 3 + column / 3) % 2 == 0 { 60 } else { 200 };
652 }
653 }
654 plane_v.fill(128);
655 buffer
656 }
657
658 fn luma_roughness(buffer: &mut I420Buffer, x: usize, y: usize) -> i32 {
659 let stride = buffer.strides().0 as usize;
660 let plane = buffer.data_mut().0;
661 (0..8).map(|step| (i32::from(plane[y * stride + x + step + 1]) - i32::from(plane[y * stride + x + step])).abs()).sum()
662 }
663
664 #[test]
665 fn the_planar_blur_keeps_the_person_and_smooths_luma_and_chroma_outside() {
666 let mut original = checkerboard_i420();
667 let mut blurred = checkerboard_i420();
668 compose_i420(&mut blurred, &oval_mask());
669 let (center_x, center_y) = (WIDTH / 2, HEIGHT / 2);
670 assert_eq!(luma_roughness(&mut blurred, center_x - 4, center_y), luma_roughness(&mut original, center_x - 4, center_y));
671 assert!(luma_roughness(&mut blurred, 2, 2) * 4 < luma_roughness(&mut original, 2, 2));
672 let chroma = |buffer: &mut I420Buffer, x: usize, y: usize| {
673 let stride = buffer.strides().1 as usize;
674 i32::from(buffer.data_mut().1[y * stride + x])
675 };
676 assert_eq!(chroma(&mut blurred, center_x / 2, center_y / 2), chroma(&mut original, center_x / 2, center_y / 2));
677 let spread = |buffer: &mut I420Buffer| (2..10).map(|x| (chroma(buffer, x + 1, 2) - chroma(buffer, x, 2)).abs()).sum::<i32>();
678 assert!(spread(&mut blurred) * 4 < spread(&mut original));
679 }
680
681 #[test]
682 fn the_planar_blur_matches_the_rgba_blur_on_gray_frames() {
683 let mut planar = checkerboard_i420();
684 planar.data_mut().1.fill(128);
685 compose_i420(&mut planar, &oval_mask());
686 let mut rgba = checkerboard();
687 compose(&mut rgba, WIDTH, HEIGHT, &oval_mask());
688 let stride = planar.strides().0 as usize;
689 let plane = planar.data().0;
690 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();
691 assert!(worst <= 24, "worst luma difference {worst}");
692 }
693
694 #[test]
695 fn a_full_person_mask_leaves_the_planes_untouched() {
696 let mut untouched = checkerboard_i420();
697 compose_i420(&mut untouched, &vec![1.; MASK_WIDTH * MASK_HEIGHT]);
698 let reference = checkerboard_i420();
699 assert_eq!(untouched.data(), reference.data());
700 }
701
702 #[test]
703 fn the_edge_between_person_and_background_is_feathered() {
704 let original = checkerboard();
705 let mut blurred = original.clone();
706 let mut mask = oval_mask();
707 compose(&mut blurred, WIDTH, HEIGHT, &mask);
708 let edge_row = HEIGHT / 2;
709 let changed_steps = (0..WIDTH - 1)
710 .filter(|&x| pixel(&blurred, x, edge_row) != pixel(&original, x, edge_row) && pixel(&blurred, x + 1, edge_row) == pixel(&original, x + 1, edge_row))
711 .count();
712 assert!(changed_steps <= 2, "a hard seam shows as one switch per side");
713 mask.fill(1.);
714 let mut untouched = original.clone();
715 compose(&mut untouched, WIDTH, HEIGHT, &mask);
716 assert_eq!(untouched, original);
717 }
718
719 #[test]
720 fn an_empty_mask_blurs_the_whole_frame() {
721 let original = checkerboard();
722 let mut blurred = original.clone();
723 compose(&mut blurred, WIDTH, HEIGHT, &vec![0.; MASK_WIDTH * MASK_HEIGHT]);
724 assert!(roughness(&blurred, 70, 40) * 4 < roughness(&original, 70, 40));
725 assert!(blurred.chunks(CHANNELS).all(|pixel| pixel[3] == 255));
726 }
727
728 fn cover_of(color: [u8; 3]) -> Vec<u8> {
729 BackgroundPicture::from_rgb(color.repeat(4 * 4), 4, 4).unwrap().covering(WIDTH, HEIGHT)
730 }
731
732 #[test]
733 fn the_person_stays_and_the_picture_replaces_everything_else() {
734 let original = checkerboard();
735 let mut replaced = original.clone();
736 compose_image(&mut replaced, WIDTH, HEIGHT, &refine_rgba(&oval_mask(), &original, WIDTH, HEIGHT), &cover_of([10, 120, 200]));
737 let (center_x, center_y) = (WIDTH / 2, HEIGHT / 2);
738 assert_eq!(pixel(&replaced, center_x, center_y), pixel(&original, center_x, center_y));
739 for (x, y) in [(2, 2), (WIDTH - 3, HEIGHT - 3), (2, HEIGHT - 3)] {
740 assert_eq!(&replaced[(y * WIDTH + x) * CHANNELS..][..4], &[10, 120, 200, 255]);
741 }
742 }
743
744 #[test]
745 fn the_picture_edge_is_feathered_like_the_blur_edge() {
746 let original = checkerboard();
747 let mut replaced = original.clone();
748 compose_image(&mut replaced, WIDTH, HEIGHT, &refine_rgba(&oval_mask(), &original, WIDTH, HEIGHT), &cover_of([0, 0, 0]));
749 let edge_row = HEIGHT / 2;
750 let switches = (0..WIDTH - 1)
751 .filter(|&x| pixel(&replaced, x, edge_row) != pixel(&original, x, edge_row) && pixel(&replaced, x + 1, edge_row) == pixel(&original, x + 1, edge_row))
752 .count();
753 assert!(switches <= 2);
754 let mut everyone = original.clone();
755 compose_image(&mut everyone, WIDTH, HEIGHT, &refine_rgba(&vec![1.; MASK_WIDTH * MASK_HEIGHT], &original, WIDTH, HEIGHT), &cover_of([0, 0, 0]));
756 assert_eq!(everyone, original);
757 let empty = refine_rgba(&vec![0.; MASK_WIDTH * MASK_HEIGHT], &original, WIDTH, HEIGHT);
758 let mut nobody = original;
759 compose_image(&mut nobody, WIDTH, HEIGHT, &empty, &cover_of([0, 0, 0]));
760 assert!(nobody.chunks(CHANNELS).all(|pixel| pixel[..3] == [0, 0, 0] && pixel[3] == 255));
761 }
762
763 #[test]
764 fn the_model_answers_one_probability_per_mask_pixel() {
765 let segmenter = Segmenter::new().expect("model loads");
766 let mask = segmenter.mask(&checkerboard(), WIDTH, HEIGHT).expect("inference runs");
767 assert_eq!(mask.len(), MASK_WIDTH * MASK_HEIGHT);
768 assert!(mask.iter().all(|value| (0. ..=1.).contains(value)));
769 }
770
771 fn wait_for_mask(source: &mut MaskSource, frame: impl Fn() -> Frame) -> bool {
772 let deadline = Instant::now() + Duration::from_secs(10);
773 while Instant::now() < deadline {
774 if source.refresh(&frame) {
775 return true;
776 }
777 std::thread::sleep(Duration::from_millis(5));
778 }
779 false
780 }
781
782 #[test]
783 fn the_mask_source_segments_when_due_and_keeps_one_mask() {
784 let mut source = MaskSource::new().expect("model loads");
785 assert!(wait_for_mask(&mut source, || i420_from_rgba(&checkerboard(), WIDTH as u32, HEIGHT as u32)));
786 assert_eq!(source.mask().len(), MASK_WIDTH * MASK_HEIGHT);
787 source.shared.stride.store(3, Ordering::Relaxed);
788 source.frames = 1;
789 assert!(!source.due());
790 assert!(!source.refresh(|| unreachable!("a skipped frame is not read")));
791 }
792
793 struct SlowSegmenter {
794 delay: Duration,
795 seen: Arc<Mutex<Vec<u8>>>,
796 }
797
798 impl MaskInference for SlowSegmenter {
799 fn infer(&self, frame: I420Buffer) -> Result<Vec<f32>> {
800 let marker = frame.data().0[0];
801 self.seen.lock().unwrap().push(marker);
802 std::thread::sleep(self.delay);
803 Ok(vec![f32::from(marker) / 255.; MASK_WIDTH * MASK_HEIGHT])
804 }
805 }
806
807 fn marked_frame(marker: u8) -> Frame {
808 let mut buffer = I420Buffer::new(2, 2);
809 buffer.data_mut().0.fill(marker);
810 buffer
811 }
812
813 #[test]
814 fn a_slow_segmenter_never_blocks_the_sender() {
815 let seen = Arc::new(Mutex::new(Vec::new()));
816 let mut source = MaskSource::with_inference(SlowSegmenter { delay: Duration::from_millis(300), seen });
817 let started = Instant::now();
818 for _ in 0..30 {
819 source.refresh(|| marked_frame(1));
820 }
821 assert!(started.elapsed() < Duration::from_millis(150));
822 }
823
824 #[test]
825 fn the_worker_hands_over_the_newest_frame_and_drops_stale_ones() {
826 let seen = Arc::new(Mutex::new(Vec::new()));
827 let mut source = MaskSource::with_inference(SlowSegmenter { delay: Duration::from_millis(100), seen: seen.clone() });
828 for marker in [10, 20, 30, 40] {
829 source.refresh(|| marked_frame(marker));
830 std::thread::sleep(Duration::from_millis(5));
831 }
832 let deadline = Instant::now() + Duration::from_secs(10);
833 while seen.lock().unwrap().last() != Some(&40) && Instant::now() < deadline {
834 source.refresh(|| marked_frame(40));
835 std::thread::sleep(Duration::from_millis(10));
836 }
837 let processed = seen.lock().unwrap().clone();
838 assert_eq!(processed.last(), Some(&40));
839 assert!(!processed.contains(&20) || !processed.contains(&30), "stale frames pile up: {processed:?}");
840 }
841}