BlueGit

ict rusty-teams

Files

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

blur.rs

blur.rs 19.7 KiB Download Raw
1use std::io::Cursor;
2use std::sync::{Arc, Mutex};
3use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
4use std::time::{Duration, Instant};
5
6use tract_onnx::prelude::*;
7
8use crate::background::BackgroundPicture;
9use crate::effects::CameraEffects;
10use crate::error::{Error, Result};
11use crate::standout::Cutout;
12
13const MODEL: &[u8] = include_bytes!("../assets/selfie_segmentation_landscape.onnx");
14pub const MASK_WIDTH: usize = 256;
15pub const MASK_HEIGHT: usize = 144;
16const CHANNELS: usize = 4;
17const BACKGROUND_SCALE: usize = 4;
18const BLUR_RADIUS: usize = 3;
19const BLUR_PASSES: usize = 2;
20const EDGE_LOW: f32 = 0.3;
21const EDGE_HIGH: f32 = 0.7;
22const OPAQUE: f32 = 0.985;
23const MASK_SMOOTHING: f32 = 0.35;
24const SLOW_INFERENCE: Duration = Duration::from_millis(22);
25const VERY_SLOW_INFERENCE: Duration = Duration::from_millis(45);
26const MAX_BANDS: usize = 4;
27
28type Plan = std::sync::Arc<TypedRunnableModel>;
29
30/// MediaPipe selfie segmentation (landscape, 256x144); answers the probability of "person" per mask pixel.
31pub struct Segmenter {
32 plan: Plan,
33}
34
35impl Segmenter {
36 pub fn new() -> Result<Self> {
37 let plan = Self::load().map_err(|error| Error::Webrtc(format!("segmentation model: {error}")))?;
38 Ok(Segmenter { plan })
39 }
40
41 fn load() -> TractResult<Plan> {
42 let model = tract_onnx::onnx().model_for_read(&mut Cursor::new(MODEL))?;
43 let batch = model.symbols.sym("batch_size");
44 let one_image = std::collections::HashMap::from([(batch, TDim::from(1))]);
45 model.into_typed()?.set_symbols(&one_image)?.into_optimized()?.into_runnable()
46 }
47
48 pub fn mask(&self, rgba: &[u8], width: usize, height: usize) -> Result<Vec<f32>> {
49 let input = model_input(rgba, width, height);
50 let outputs = self.plan.run(tvec!(input.into())).map_err(|error| Error::Webrtc(format!("segmentation: {error}")))?;
51 let values = outputs[0].to_plain_array_view::<f32>().map_err(|error| Error::Webrtc(format!("segmentation output: {error}")))?;
52 if values.len() != MASK_WIDTH * MASK_HEIGHT {
53 return Err(Error::Webrtc(format!("segmentation output has {} values", values.len())));
54 }
55 Ok(values.iter().map(|value| value.clamp(0., 1.)).collect())
56 }
57}
58
59fn model_input(rgba: &[u8], width: usize, height: usize) -> Tensor {
60 let plane = MASK_WIDTH * MASK_HEIGHT;
61 let mut data = vec![0f32; 3 * plane];
62 for row in 0..MASK_HEIGHT {
63 let top = (row * 2 * height / (MASK_HEIGHT * 2)).min(height - 1);
64 let bottom = ((row * 2 + 1) * height / (MASK_HEIGHT * 2)).min(height - 1);
65 for column in 0..MASK_WIDTH {
66 let left = (column * 2 * width / (MASK_WIDTH * 2)).min(width - 1);
67 let right = ((column * 2 + 1) * width / (MASK_WIDTH * 2)).min(width - 1);
68 for channel in 0..3 {
69 let sum: u32 = [(top, left), (top, right), (bottom, left), (bottom, right)]
70 .iter()
71 .map(|&(y, x)| u32::from(rgba[(y * width + x) * CHANNELS + channel]))
72 .sum();
73 data[channel * plane + row * MASK_WIDTH + column] = sum as f32 / (4. * 255.);
74 }
75 }
76 }
77 Tensor::from_shape(&[1, 3, MASK_HEIGHT, MASK_WIDTH], &data).expect("shape matches data")
78}
79
80pub(crate) fn smoothstep(value: f32) -> f32 {
81 let t = ((value - EDGE_LOW) / (EDGE_HIGH - EDGE_LOW)).clamp(0., 1.);
82 t * t * (3. - 2. * t)
83}
84
85pub(crate) struct Axis {
86 pub(crate) first: Vec<usize>,
87 pub(crate) second: Vec<usize>,
88 pub(crate) weight: Vec<f32>,
89}
90
91pub(crate) fn axis(output: usize, input: usize) -> Axis {
92 let mut axis = Axis { first: Vec::with_capacity(output), second: Vec::with_capacity(output), weight: Vec::with_capacity(output) };
93 for index in 0..output {
94 let position = ((index as f32 + 0.5) * input as f32 / output as f32 - 0.5).clamp(0., (input - 1) as f32);
95 let first = position.floor() as usize;
96 axis.first.push(first);
97 axis.second.push((first + 1).min(input - 1));
98 axis.weight.push(position - first as f32);
99 }
100 axis
101}
102
103fn downscaled(rgba: &[u8], width: usize, height: usize) -> (Vec<u8>, usize, usize) {
104 let small_width = width.div_ceil(BACKGROUND_SCALE);
105 let small_height = height.div_ceil(BACKGROUND_SCALE);
106 let mut small = vec![0u8; small_width * small_height * 3];
107 for row in 0..small_height {
108 for column in 0..small_width {
109 let mut sums = [0u32; 3];
110 let mut count = 0u32;
111 for y in row * BACKGROUND_SCALE..((row + 1) * BACKGROUND_SCALE).min(height) {
112 for x in column * BACKGROUND_SCALE..((column + 1) * BACKGROUND_SCALE).min(width) {
113 for (channel, sum) in sums.iter_mut().enumerate() {
114 *sum += u32::from(rgba[(y * width + x) * CHANNELS + channel]);
115 }
116 count += 1;
117 }
118 }
119 for (channel, sum) in sums.iter().enumerate() {
120 small[(row * small_width + column) * 3 + channel] = (sum / count) as u8;
121 }
122 }
123 }
124 (small, small_width, small_height)
125}
126
127fn blur_pass(input: &[u8], output: &mut [u8], lines: usize, length: usize, line_stride: usize, step: usize) {
128 let radius = BLUR_RADIUS as isize;
129 let window = (BLUR_RADIUS * 2 + 1) as u32;
130 for line in 0..lines {
131 for channel in 0..3 {
132 let base = line * line_stride + channel;
133 let read = |index: isize| u32::from(input[base + index.clamp(0, length as isize - 1) as usize * step]);
134 let mut sum: u32 = (-radius..=radius).map(read).sum();
135 for index in 0..length {
136 output[base + index * step] = (sum / window) as u8;
137 sum = sum + read(index as isize + radius + 1) - read(index as isize - radius);
138 }
139 }
140 }
141}
142
143fn box_blur(image: &mut [u8], width: usize, height: usize, scratch: &mut [u8]) {
144 blur_pass(image, scratch, height, width, width * 3, 3);
145 blur_pass(scratch, image, width, height, 3, width * 3);
146}
147
148fn blurred_background(rgba: &[u8], width: usize, height: usize) -> (Vec<u8>, usize, usize) {
149 let (mut small, small_width, small_height) = downscaled(rgba, width, height);
150 let mut scratch = vec![0u8; small.len()];
151 for _ in 0..BLUR_PASSES {
152 box_blur(&mut small, small_width, small_height, &mut scratch);
153 }
154 (small, small_width, small_height)
155}
156
157struct Composer<'a> {
158 background: &'a [u8],
159 mask: &'a [f32],
160 width: usize,
161 mask_x: Axis,
162 mask_y: Axis,
163 small_x: Axis,
164 small_y: Axis,
165 small_width: usize,
166}
167
168impl Composer<'_> {
169 fn rows(&self, rgba: &mut [u8], first_row: usize) {
170 for (offset, line) in rgba.chunks_exact_mut(self.width * CHANNELS).enumerate() {
171 self.row(line, first_row + offset);
172 }
173 }
174
175 fn row(&self, line: &mut [u8], row: usize) {
176 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]);
177 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]);
178 for (column, pixel) in line.as_chunks_mut::<CHANNELS>().0.iter_mut().enumerate() {
179 let (left, right, across) = (self.mask_x.first[column], self.mask_x.second[column], self.mask_x.weight[column]);
180 let top = self.mask[mask_top + left] * (1. - across) + self.mask[mask_top + right] * across;
181 let bottom = self.mask[mask_bottom + left] * (1. - across) + self.mask[mask_bottom + right] * across;
182 let person = smoothstep(top * (1. - mask_fraction) + bottom * mask_fraction);
183 if person >= OPAQUE {
184 continue;
185 }
186 let (left, right, across) = (self.small_x.first[column], self.small_x.second[column], self.small_x.weight[column]);
187 for (channel, value) in pixel.iter_mut().take(3).enumerate() {
188 let sample = |line: usize, index: usize| f32::from(self.background[(line + index) * 3 + channel]);
189 let upper = sample(small_top, left) * (1. - across) + sample(small_top, right) * across;
190 let lower = sample(small_bottom, left) * (1. - across) + sample(small_bottom, right) * across;
191 let blurred = upper * (1. - small_fraction) + lower * small_fraction;
192 *value = (f32::from(*value) * person + blurred * (1. - person) + 0.5) as u8;
193 }
194 }
195 }
196}
197
198fn compose_over(rgba: &mut [u8], width: usize, height: usize, mask: &[f32], background: &[u8], background_width: usize, background_height: usize) {
199 let composer = Composer {
200 background,
201 mask,
202 width,
203 mask_x: axis(width, MASK_WIDTH),
204 mask_y: axis(height, MASK_HEIGHT),
205 small_x: axis(width, background_width),
206 small_y: axis(height, background_height),
207 small_width: background_width,
208 };
209 let bands = std::thread::available_parallelism().map_or(1, usize::from).min(MAX_BANDS);
210 let rows_per_band = height.div_ceil(bands);
211 std::thread::scope(|scope| {
212 for (index, band) in rgba.chunks_mut(rows_per_band * width * CHANNELS).enumerate() {
213 let composer = &composer;
214 scope.spawn(move || composer.rows(band, index * rows_per_band));
215 }
216 });
217}
218
219/// Keeps the person (mask near 1) sharp and replaces the rest with a blurred copy; `mask` is `MASK_WIDTH` x `MASK_HEIGHT`.
220pub fn compose(rgba: &mut [u8], width: usize, height: usize, mask: &[f32]) {
221 let (background, small_width, small_height) = blurred_background(rgba, width, height);
222 compose_over(rgba, width, height, mask, &background, small_width, small_height);
223}
224
225pub fn compose_image(rgba: &mut [u8], width: usize, height: usize, mask: &[f32], covered: &[u8]) {
226 compose_over(rgba, width, height, mask, covered, width, height);
227}
228
229/// Shared between the UI command and the camera thread.
230#[derive(Default)]
231pub struct BlurSettings {
232 enabled: AtomicBool,
233 standout: AtomicBool,
234 average_micros: AtomicU32,
235 picture: Mutex<Option<Arc<BackgroundPicture>>>,
236 effects: Mutex<CameraEffects>,
237 cutout: Mutex<Option<Arc<Cutout>>>,
238}
239
240impl BlurSettings {
241 pub fn set_enabled(&self, enabled: bool) {
242 self.enabled.store(enabled, Ordering::Relaxed);
243 }
244
245 pub fn enabled(&self) -> bool {
246 self.enabled.load(Ordering::Relaxed)
247 }
248
249 pub fn set_standout(&self, standout: bool) {
250 self.standout.store(standout, Ordering::Relaxed);
251 if !standout {
252 self.set_cutout(None);
253 }
254 }
255
256 pub fn standout(&self) -> bool {
257 self.standout.load(Ordering::Relaxed)
258 }
259
260 pub fn set_cutout(&self, cutout: Option<Arc<Cutout>>) {
261 *self.cutout.lock().expect("cutout lock") = cutout;
262 }
263
264 pub fn cutout(&self) -> Option<Arc<Cutout>> {
265 self.cutout.lock().expect("cutout lock").clone()
266 }
267
268 pub fn set_picture(&self, picture: Option<Arc<BackgroundPicture>>) {
269 *self.picture.lock().expect("picture lock") = picture;
270 }
271
272 fn picture(&self) -> Option<Arc<BackgroundPicture>> {
273 self.picture.lock().expect("picture lock").clone()
274 }
275
276 pub fn set_effects(&self, effects: CameraEffects) {
277 *self.effects.lock().expect("effects lock") = effects;
278 }
279
280 pub fn effects(&self) -> CameraEffects {
281 *self.effects.lock().expect("effects lock")
282 }
283
284 pub fn active(&self) -> bool {
285 self.enabled() || self.standout() || self.effects().alters_frame()
286 }
287
288 pub fn average_ms(&self) -> f32 {
289 self.average_micros.load(Ordering::Relaxed) as f32 / 1000.
290 }
291
292 pub fn set_average_ms(&self, average_ms: f64) {
293 self.average_micros.store((average_ms * 1000.) as u32, Ordering::Relaxed);
294 }
295}
296
297/// Replaces the background of a frame; the mask comes from the shared `MaskSource`.
298pub struct BlurStage {
299 settings: Arc<BlurSettings>,
300 covered: Option<CoveredPicture>,
301}
302
303struct CoveredPicture {
304 picture: Arc<BackgroundPicture>,
305 width: usize,
306 height: usize,
307 rgb: Vec<u8>,
308}
309
310impl BlurStage {
311 pub fn new(settings: Arc<BlurSettings>) -> Self {
312 BlurStage { settings, covered: None }
313 }
314
315 fn refresh_covered(&mut self, width: usize, height: usize) {
316 let Some(picture) = self.settings.picture() else {
317 self.covered = None;
318 return;
319 };
320 let fresh = self.covered.as_ref().is_some_and(|covered| Arc::ptr_eq(&covered.picture, &picture) && covered.width == width && covered.height == height);
321 if !fresh {
322 let rgb = picture.covering(width, height);
323 self.covered = Some(CoveredPicture { picture, width, height, rgb });
324 }
325 }
326
327 pub fn compose(&mut self, rgba: &mut [u8], width: usize, height: usize, mask: &[f32]) {
328 self.refresh_covered(width, height);
329 match &self.covered {
330 Some(covered) => compose_image(rgba, width, height, mask, &covered.rgb),
331 None => compose(rgba, width, height, mask),
332 }
333 }
334}
335
336/// One segmentation mask for every effect: segments every `stride` frames and slows down when inference is slow.
337pub struct MaskSource {
338 segmenter: Segmenter,
339 mask: Vec<f32>,
340 frames: u64,
341 stride: u64,
342}
343
344impl MaskSource {
345 pub fn new() -> Result<Self> {
346 Ok(MaskSource { segmenter: Segmenter::new()?, mask: Vec::new(), frames: 0, stride: 1 })
347 }
348
349 pub fn due(&self) -> bool {
350 self.frames.is_multiple_of(self.stride) || self.mask.is_empty()
351 }
352
353 pub fn mask(&self) -> &[f32] {
354 &self.mask
355 }
356
357 /// Call once per frame; `rgba` is only read when `due`. Answers whether the mask changed.
358 pub fn refresh(&mut self, rgba: impl FnOnce() -> (Vec<u8>, usize, usize)) -> bool {
359 let due = self.due();
360 self.frames += 1;
361 if !due {
362 return false;
363 }
364 let (rgba, width, height) = rgba();
365 let started = Instant::now();
366 let Ok(fresh) = self.segmenter.mask(&rgba, width, height) else {
367 return false;
368 };
369 let inference = started.elapsed();
370 self.stride = if inference > VERY_SLOW_INFERENCE {
371 3
372 } else if inference > SLOW_INFERENCE {
373 2
374 } else {
375 1
376 };
377 if self.mask.is_empty() {
378 self.mask = fresh;
379 return true;
380 }
381 for (current, new) in self.mask.iter_mut().zip(fresh) {
382 *current += (new - *current) * (1. - MASK_SMOOTHING);
383 }
384 true
385 }
386}
387
388#[cfg(test)]
389mod tests {
390 use super::*;
391
392 const WIDTH: usize = 160;
393 const HEIGHT: usize = 90;
394
395 fn checkerboard() -> Vec<u8> {
396 let mut rgba = vec![255u8; WIDTH * HEIGHT * CHANNELS];
397 for row in 0..HEIGHT {
398 for column in 0..WIDTH {
399 let value = if (row / 3 + column / 3) % 2 == 0 { 20 } else { 235 };
400 rgba[(row * WIDTH + column) * CHANNELS..][..3].fill(value);
401 }
402 }
403 rgba
404 }
405
406 fn oval_mask() -> Vec<f32> {
407 (0..MASK_WIDTH * MASK_HEIGHT)
408 .map(|index| {
409 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);
410 if (x * x) / 0.04 + (y * y) / 0.09 <= 1. { 1. } else { 0. }
411 })
412 .collect()
413 }
414
415 fn pixel(rgba: &[u8], x: usize, y: usize) -> u8 {
416 rgba[(y * WIDTH + x) * CHANNELS]
417 }
418
419 fn roughness(rgba: &[u8], x: usize, y: usize) -> i32 {
420 (0..8).map(|step| (i32::from(pixel(rgba, x + step + 1, y)) - i32::from(pixel(rgba, x + step, y))).abs()).sum()
421 }
422
423 #[test]
424 fn the_person_stays_sharp_and_the_background_is_smoothed() {
425 let original = checkerboard();
426 let mut blurred = original.clone();
427 compose(&mut blurred, WIDTH, HEIGHT, &oval_mask());
428 let (center_x, center_y) = (WIDTH / 2, HEIGHT / 2);
429 assert_eq!(pixel(&blurred, center_x, center_y), pixel(&original, center_x, center_y));
430 assert_eq!(roughness(&blurred, center_x - 4, center_y), roughness(&original, center_x - 4, center_y));
431 assert!(roughness(&blurred, 2, 2) * 4 < roughness(&original, 2, 2));
432 assert!(roughness(&blurred, WIDTH - 12, HEIGHT - 3) * 4 < roughness(&original, WIDTH - 12, HEIGHT - 3));
433 }
434
435 #[test]
436 fn the_edge_between_person_and_background_is_feathered() {
437 let original = checkerboard();
438 let mut blurred = original.clone();
439 let mut mask = oval_mask();
440 compose(&mut blurred, WIDTH, HEIGHT, &mask);
441 let edge_row = HEIGHT / 2;
442 let changed_steps = (0..WIDTH - 1)
443 .filter(|&x| pixel(&blurred, x, edge_row) != pixel(&original, x, edge_row) && pixel(&blurred, x + 1, edge_row) == pixel(&original, x + 1, edge_row))
444 .count();
445 assert!(changed_steps <= 2, "a hard seam shows as one switch per side");
446 mask.fill(1.);
447 let mut untouched = original.clone();
448 compose(&mut untouched, WIDTH, HEIGHT, &mask);
449 assert_eq!(untouched, original);
450 }
451
452 #[test]
453 fn an_empty_mask_blurs_the_whole_frame() {
454 let original = checkerboard();
455 let mut blurred = original.clone();
456 compose(&mut blurred, WIDTH, HEIGHT, &vec![0.; MASK_WIDTH * MASK_HEIGHT]);
457 assert!(roughness(&blurred, 70, 40) * 4 < roughness(&original, 70, 40));
458 assert!(blurred.chunks(CHANNELS).all(|pixel| pixel[3] == 255));
459 }
460
461 fn cover_of(color: [u8; 3]) -> Vec<u8> {
462 BackgroundPicture::from_rgb(color.repeat(4 * 4), 4, 4).unwrap().covering(WIDTH, HEIGHT)
463 }
464
465 #[test]
466 fn the_person_stays_and_the_picture_replaces_everything_else() {
467 let original = checkerboard();
468 let mut replaced = original.clone();
469 compose_image(&mut replaced, WIDTH, HEIGHT, &oval_mask(), &cover_of([10, 120, 200]));
470 let (center_x, center_y) = (WIDTH / 2, HEIGHT / 2);
471 assert_eq!(pixel(&replaced, center_x, center_y), pixel(&original, center_x, center_y));
472 for (x, y) in [(2, 2), (WIDTH - 3, HEIGHT - 3), (2, HEIGHT - 3)] {
473 assert_eq!(&replaced[(y * WIDTH + x) * CHANNELS..][..4], &[10, 120, 200, 255]);
474 }
475 }
476
477 #[test]
478 fn the_picture_edge_is_feathered_like_the_blur_edge() {
479 let original = checkerboard();
480 let mut replaced = original.clone();
481 compose_image(&mut replaced, WIDTH, HEIGHT, &oval_mask(), &cover_of([0, 0, 0]));
482 let edge_row = HEIGHT / 2;
483 let switches = (0..WIDTH - 1)
484 .filter(|&x| pixel(&replaced, x, edge_row) != pixel(&original, x, edge_row) && pixel(&replaced, x + 1, edge_row) == pixel(&original, x + 1, edge_row))
485 .count();
486 assert!(switches <= 2);
487 let mut everyone = original.clone();
488 compose_image(&mut everyone, WIDTH, HEIGHT, &vec![1.; MASK_WIDTH * MASK_HEIGHT], &cover_of([0, 0, 0]));
489 assert_eq!(everyone, original);
490 let mut nobody = original;
491 compose_image(&mut nobody, WIDTH, HEIGHT, &vec![0.; MASK_WIDTH * MASK_HEIGHT], &cover_of([0, 0, 0]));
492 assert!(nobody.chunks(CHANNELS).all(|pixel| pixel[..3] == [0, 0, 0] && pixel[3] == 255));
493 }
494
495 #[test]
496 fn the_model_answers_one_probability_per_mask_pixel() {
497 let segmenter = Segmenter::new().expect("model loads");
498 let mask = segmenter.mask(&checkerboard(), WIDTH, HEIGHT).expect("inference runs");
499 assert_eq!(mask.len(), MASK_WIDTH * MASK_HEIGHT);
500 assert!(mask.iter().all(|value| (0. ..=1.).contains(value)));
501 }
502
503 #[test]
504 fn the_mask_source_segments_when_due_and_keeps_one_mask() {
505 let mut source = MaskSource::new().expect("model loads");
506 let frame = || (checkerboard(), WIDTH, HEIGHT);
507 assert!(source.refresh(frame));
508 assert_eq!(source.mask().len(), MASK_WIDTH * MASK_HEIGHT);
509 source.stride = 3;
510 assert!(!source.due());
511 assert!(!source.refresh(|| unreachable!("a skipped frame is not read")));
512 }
513}