BlueGit

ict rusty-teams

Files

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

blur.rs

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