BlueGit

ict rusty-teams

Files

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

blur.rs

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