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