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