Merge branch 'perf/better-segmentation' into integrate/calls-10
@@ -2,11 +2,14 @@ use std::sync::Arc;
2
2
use std::time::{Duration, Instant};
3
3
4
4
use calling::camera::i420_from_rgba;
5
use calling::blur::{BlurSettings, MaskSource, Segmenter, compose};
5
use calling::background::BackgroundPicture;
6
use calling::blur::{BlurSettings, MaskInference, MaskSource, Segmenter, compose, compose_i420, compose_image};
6
7
use calling::effects::{CameraEffects, EffectsStage};
7
8
use calling::framing::{Crop, crop_and_scale};
8
9
use calling::luma_effects::soften_luma;
9
use libwebrtc::video_frame::I420Buffer;
10
use calling::matte::{Planes, refine};
11
use libwebrtc::native::yuv_helper::i420_to_abgr;
12
use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};
10
13
11
14
const WIDTH: usize = 640;
12
15
const HEIGHT: usize = 360;
@@ -66,8 +69,49 @@ fn stage_cost(label: &str, blur: bool, effects: CameraEffects) {
66
69
println!("{label} {SEND_WIDTH}x{SEND_HEIGHT}: {:.2} ms/frame", busy.as_secs_f64() * 1000. / FRAMES as f64);
67
70
}
68
71
72
fn picture_backdrop() -> Arc<BackgroundPicture> {
73
let (width, height) = (64, 36);
74
let rgb = (0..width * height).flat_map(|index| {
75
let (x, y) = (index % width, index / width);
76
[(40 + x * 2) as u8, (90 + y) as u8, (150 + x) as u8]
77
});
78
Arc::new(BackgroundPicture::from_rgb(rgb.collect(), width, height).expect("backdrop"))
79
}
80
81
fn rgba_of(buffer: &I420Buffer) -> Vec<u8> {
82
let (width, height) = (buffer.width(), buffer.height());
83
let (stride_y, stride_u, stride_v) = buffer.strides();
84
let (plane_y, plane_u, plane_v) = buffer.data();
85
let mut rgba = vec![0u8; (width * height * 4) as usize];
86
i420_to_abgr(plane_y, stride_y, plane_u, stride_u, plane_v, stride_v, &mut rgba, width * 4, width as i32, height as i32);
87
rgba
88
}
89
90
fn save_png(path: &str, rgba: Vec<u8>) {
91
image::RgbaImage::from_raw(SEND_WIDTH, SEND_HEIGHT, rgba).expect("frame size").save(path).expect("png written");
92
}
93
94
fn shots(input: &str, prefix: &str) {
95
let photo = image::open(input).expect("photo").resize_to_fill(SEND_WIDTH, SEND_HEIGHT, image::imageops::FilterType::Triangle).to_rgba8().into_raw();
96
let camera = i420_from_rgba(&photo, SEND_WIDTH, SEND_HEIGHT);
97
let mask = Segmenter::new().expect("model").infer(i420_from_rgba(&photo, SEND_WIDTH, SEND_HEIGHT)).expect("mask");
98
let matte = refine(&mask, Planes::of(&camera));
99
image::GrayImage::from_raw(SEND_WIDTH, SEND_HEIGHT, matte.alpha.clone()).expect("matte size").save(format!("{prefix}-matte.png")).expect("png written");
100
let mut blurred = i420_from_rgba(&photo, SEND_WIDTH, SEND_HEIGHT);
101
compose_i420(&mut blurred, &mask);
102
save_png(&format!("{prefix}-blur.png"), rgba_of(&blurred));
103
let mut replaced = rgba_of(&camera);
104
let backdrop = picture_backdrop().covering(SEND_WIDTH as usize, SEND_HEIGHT as usize);
105
compose_image(&mut replaced, SEND_WIDTH as usize, SEND_HEIGHT as usize, &matte, &backdrop);
106
save_png(&format!("{prefix}-picture.png"), replaced);
107
}
108
69
109
fn main() {
70
let mut arguments = std::env::args().skip(1);
110
let mut arguments = std::env::args().skip(1).peekable();
111
if arguments.next_if(|argument| argument == "--shots").is_some() {
112
shots(&arguments.next().expect("photo path"), &arguments.next().expect("output prefix"));
113
return;
114
}
71
115
let input = arguments.next();
72
116
let output = arguments.next();
73
117
let frame = input.map_or_else(synthetic, |path| std::fs::read(path).expect("raw rgba 640x360 input"));
@@ -114,6 +158,27 @@ fn main() {
114
158
soften_luma(frame.data_mut().0, stride, SEND_WIDTH as usize, SEND_HEIGHT as usize, &oval, 100);
115
159
}
116
160
println!("soft focus only, oval person {SEND_WIDTH}x{SEND_HEIGHT}: {:.2} ms/frame", milliseconds_per_frame(started));
161
let started = Instant::now();
162
for _ in 0..FRAMES {
163
std::hint::black_box(refine(&oval, Planes::of(&frame)));
164
}
165
println!("matte refinement {SEND_WIDTH}x{SEND_HEIGHT}: {:.2} ms/frame", milliseconds_per_frame(started));
166
let backdrop = picture_backdrop().covering(SEND_WIDTH as usize, SEND_HEIGHT as usize);
167
let camera = rgba_of(&frame);
168
let mut replaced = camera.clone();
169
let started = Instant::now();
170
for _ in 0..FRAMES {
171
replaced.copy_from_slice(&camera);
172
let matte = refine(&oval, Planes::of(&frame));
173
compose_image(&mut replaced, SEND_WIDTH as usize, SEND_HEIGHT as usize, &matte, &backdrop);
174
}
175
println!("picture compose {SEND_WIDTH}x{SEND_HEIGHT}: {:.2} ms/frame", milliseconds_per_frame(started));
176
let started = Instant::now();
177
for _ in 0..FRAMES {
178
let mut blurred = send_frame();
179
compose_i420(&mut blurred, &oval);
180
}
181
println!("blur compose i420 {SEND_WIDTH}x{SEND_HEIGHT} (incl. frame fill): {:.2} ms/frame", milliseconds_per_frame(started));
117
182
let source = send_frame();
118
183
let crop = Crop { center_x: 0.5, center_y: 0.5, zoom: 1.6 };
119
184
let started = Instant::now();
@@ -2,11 +2,14 @@ use std::sync::Arc;2
use std::time::{Duration, Instant};2
use std::time::{Duration, Instant};3
3
4
use calling::camera::i420_from_rgba;4
use calling::camera::i420_from_rgba;5
use calling::blur::{BlurSettings, MaskSource, Segmenter, compose};5
use calling::background::BackgroundPicture;6
use calling::blur::{BlurSettings, MaskInference, MaskSource, Segmenter, compose, compose_i420, compose_image};6
use calling::effects::{CameraEffects, EffectsStage};7
use calling::effects::{CameraEffects, EffectsStage};7
use calling::framing::{Crop, crop_and_scale};8
use calling::framing::{Crop, crop_and_scale};8
use calling::luma_effects::soften_luma;9
use calling::luma_effects::soften_luma;9
use libwebrtc::video_frame::I420Buffer;10
use calling::matte::{Planes, refine};11
use libwebrtc::native::yuv_helper::i420_to_abgr;12
use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};10
13
11
const WIDTH: usize = 640;14
const WIDTH: usize = 640;12
const HEIGHT: usize = 360;15
const HEIGHT: usize = 360;@@ -66,8 +69,49 @@ fn stage_cost(label: &str, blur: bool, effects: CameraEffects) {66
println!("{label} {SEND_WIDTH}x{SEND_HEIGHT}: {:.2} ms/frame", busy.as_secs_f64() * 1000. / FRAMES as f64);69
println!("{label} {SEND_WIDTH}x{SEND_HEIGHT}: {:.2} ms/frame", busy.as_secs_f64() * 1000. / FRAMES as f64);67
}70
}68
71
72
fn picture_backdrop() -> Arc<BackgroundPicture> {73
let (width, height) = (64, 36);74
let rgb = (0..width * height).flat_map(|index| {75
let (x, y) = (index % width, index / width);76
[(40 + x * 2) as u8, (90 + y) as u8, (150 + x) as u8]77
});78
Arc::new(BackgroundPicture::from_rgb(rgb.collect(), width, height).expect("backdrop"))79
}80
81
fn rgba_of(buffer: &I420Buffer) -> Vec<u8> {82
let (width, height) = (buffer.width(), buffer.height());83
let (stride_y, stride_u, stride_v) = buffer.strides();84
let (plane_y, plane_u, plane_v) = buffer.data();85
let mut rgba = vec![0u8; (width * height * 4) as usize];86
i420_to_abgr(plane_y, stride_y, plane_u, stride_u, plane_v, stride_v, &mut rgba, width * 4, width as i32, height as i32);87
rgba88
}89
90
fn save_png(path: &str, rgba: Vec<u8>) {91
image::RgbaImage::from_raw(SEND_WIDTH, SEND_HEIGHT, rgba).expect("frame size").save(path).expect("png written");92
}93
94
fn shots(input: &str, prefix: &str) {95
let photo = image::open(input).expect("photo").resize_to_fill(SEND_WIDTH, SEND_HEIGHT, image::imageops::FilterType::Triangle).to_rgba8().into_raw();96
let camera = i420_from_rgba(&photo, SEND_WIDTH, SEND_HEIGHT);97
let mask = Segmenter::new().expect("model").infer(i420_from_rgba(&photo, SEND_WIDTH, SEND_HEIGHT)).expect("mask");98
let matte = refine(&mask, Planes::of(&camera));99
image::GrayImage::from_raw(SEND_WIDTH, SEND_HEIGHT, matte.alpha.clone()).expect("matte size").save(format!("{prefix}-matte.png")).expect("png written");100
let mut blurred = i420_from_rgba(&photo, SEND_WIDTH, SEND_HEIGHT);101
compose_i420(&mut blurred, &mask);102
save_png(&format!("{prefix}-blur.png"), rgba_of(&blurred));103
let mut replaced = rgba_of(&camera);104
let backdrop = picture_backdrop().covering(SEND_WIDTH as usize, SEND_HEIGHT as usize);105
compose_image(&mut replaced, SEND_WIDTH as usize, SEND_HEIGHT as usize, &matte, &backdrop);106
save_png(&format!("{prefix}-picture.png"), replaced);107
}108
69
fn main() {109
fn main() {70
let mut arguments = std::env::args().skip(1);110
let mut arguments = std::env::args().skip(1).peekable();111
if arguments.next_if(|argument| argument == "--shots").is_some() {112
shots(&arguments.next().expect("photo path"), &arguments.next().expect("output prefix"));113
return;114
}71
let input = arguments.next();115
let input = arguments.next();72
let output = arguments.next();116
let output = arguments.next();73
let frame = input.map_or_else(synthetic, |path| std::fs::read(path).expect("raw rgba 640x360 input"));117
let frame = input.map_or_else(synthetic, |path| std::fs::read(path).expect("raw rgba 640x360 input"));@@ -114,6 +158,27 @@ fn main() {114
soften_luma(frame.data_mut().0, stride, SEND_WIDTH as usize, SEND_HEIGHT as usize, &oval, 100);158
soften_luma(frame.data_mut().0, stride, SEND_WIDTH as usize, SEND_HEIGHT as usize, &oval, 100);115
}159
}116
println!("soft focus only, oval person {SEND_WIDTH}x{SEND_HEIGHT}: {:.2} ms/frame", milliseconds_per_frame(started));160
println!("soft focus only, oval person {SEND_WIDTH}x{SEND_HEIGHT}: {:.2} ms/frame", milliseconds_per_frame(started));161
let started = Instant::now();162
for _ in 0..FRAMES {163
std::hint::black_box(refine(&oval, Planes::of(&frame)));164
}165
println!("matte refinement {SEND_WIDTH}x{SEND_HEIGHT}: {:.2} ms/frame", milliseconds_per_frame(started));166
let backdrop = picture_backdrop().covering(SEND_WIDTH as usize, SEND_HEIGHT as usize);167
let camera = rgba_of(&frame);168
let mut replaced = camera.clone();169
let started = Instant::now();170
for _ in 0..FRAMES {171
replaced.copy_from_slice(&camera);172
let matte = refine(&oval, Planes::of(&frame));173
compose_image(&mut replaced, SEND_WIDTH as usize, SEND_HEIGHT as usize, &matte, &backdrop);174
}175
println!("picture compose {SEND_WIDTH}x{SEND_HEIGHT}: {:.2} ms/frame", milliseconds_per_frame(started));176
let started = Instant::now();177
for _ in 0..FRAMES {178
let mut blurred = send_frame();179
compose_i420(&mut blurred, &oval);180
}181
println!("blur compose i420 {SEND_WIDTH}x{SEND_HEIGHT} (incl. frame fill): {:.2} ms/frame", milliseconds_per_frame(started));117
let source = send_frame();182
let source = send_frame();118
let crop = Crop { center_x: 0.5, center_y: 0.5, zoom: 1.6 };183
let crop = Crop { center_x: 0.5, center_y: 0.5, zoom: 1.6 };119
let started = Instant::now();184
let started = Instant::now();@@ -12,6 +12,7 @@ use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};
12
12
use crate::background::BackgroundPicture;
13
13
use crate::effects::CameraEffects;
14
14
use crate::error::{Error, Result};
15
use crate::matte::{Matte, Planes, refine, refine_rgba};
15
16
use crate::standout::Cutout;
16
17
17
18
const MODEL: &[u8] = include_bytes!("../assets/selfie_segmentation_landscape.onnx");
@@ -21,10 +22,8 @@ const CHANNELS: usize = 4;
21
22
const BACKGROUND_SCALE: usize = 4;
22
23
const BLUR_RADIUS: usize = 3;
23
24
const BLUR_PASSES: usize = 2;
24
const EDGE_LOW: f32 = 0.3;
25
const EDGE_HIGH: f32 = 0.7;
26
const OPAQUE: f32 = 0.985;
27
25
const MASK_SMOOTHING: f32 = 0.35;
26
const MOTION_GAIN: f32 = 2.;
28
27
const SLOW_INFERENCE: Duration = Duration::from_millis(22);
29
28
const VERY_SLOW_INFERENCE: Duration = Duration::from_millis(45);
30
29
const MAX_BANDS: usize = 4;
@@ -82,11 +81,6 @@ fn model_input(rgba: &[u8], width: usize, height: usize) -> Tensor {
82
81
Tensor::from_shape(&[1, 3, MASK_HEIGHT, MASK_WIDTH], &data).expect("shape matches data")
83
82
}
84
83
85
pub(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
90
84
pub(crate) struct Axis {
91
85
pub(crate) first: Vec<usize>,
92
86
pub(crate) second: Vec<usize>,
@@ -159,19 +153,10 @@ fn blurred_background(rgba: &[u8], width: usize, height: usize) -> (Vec<u8>, usi
159
153
(small, small_width, small_height)
160
154
}
161
155
162
fn 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
169
156
struct Composer<'a> {
170
157
background: &'a [u8],
171
mask: &'a [f32],
158
matte: &'a Matte,
172
159
width: usize,
173
mask_x: Axis,
174
mask_y: Axis,
175
160
small_x: Axis,
176
161
small_y: Axis,
177
162
small_width: usize,
@@ -185,13 +170,13 @@ impl Composer<'_> {
185
170
}
186
171
187
172
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
173
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 {
174
let alphas = &self.matte.alpha[row * self.matte.width..][..self.matte.width];
175
for (column, (pixel, &alpha)) in line.as_chunks_mut::<CHANNELS>().0.iter_mut().zip(alphas).enumerate() {
176
if alpha == u8::MAX {
193
177
continue;
194
178
}
179
let person = f32::from(alpha) / 255.;
195
180
let (left, right, across) = (self.small_x.first[column], self.small_x.second[column], self.small_x.weight[column]);
196
181
for (channel, value) in pixel.iter_mut().take(3).enumerate() {
197
182
let sample = |line: usize, index: usize| f32::from(self.background[(line + index) * 3 + channel]);
@@ -204,13 +189,11 @@ impl Composer<'_> {
204
189
}
205
190
}
206
191
207
fn compose_over(rgba: &mut [u8], width: usize, height: usize, mask: &[f32], background: &[u8], background_width: usize, background_height: usize) {
192
fn compose_over(rgba: &mut [u8], width: usize, height: usize, matte: &Matte, background: &[u8], background_width: usize, background_height: usize) {
208
193
let composer = Composer {
209
194
background,
210
mask,
195
matte,
211
196
width,
212
mask_x: axis(width, MASK_WIDTH),
213
mask_y: axis(height, MASK_HEIGHT),
214
197
small_x: axis(width, background_width),
215
198
small_y: axis(height, background_height),
216
199
small_width: background_width,
@@ -256,23 +239,20 @@ fn blurred_plane(plane: &[u8], stride: usize, width: usize, height: usize, facto
256
239
257
240
struct PlaneComposer<'a> {
258
241
background: &'a [u8],
259
mask: &'a [f32],
242
matte: &'a Matte,
260
243
width: usize,
261
mask_x: Axis,
262
mask_y: Axis,
263
244
small_x: Axis,
264
245
small_y: Axis,
265
246
small_width: usize,
266
247
}
267
248
268
249
impl PlaneComposer<'_> {
269
fn new<'a>(background: &'a [u8], small_width: usize, small_height: usize, mask: &'a [f32], width: usize, height: usize) -> PlaneComposer<'a> {
250
fn new<'a>(background: &'a [u8], small_width: usize, small_height: usize, matte: &'a Matte) -> PlaneComposer<'a> {
251
let (width, height) = (matte.width, matte.height);
270
252
PlaneComposer {
271
253
background,
272
mask,
254
matte,
273
255
width,
274
mask_x: axis(width, MASK_WIDTH),
275
mask_y: axis(height, MASK_HEIGHT),
276
256
small_x: axis(width, small_width),
277
257
small_y: axis(height, small_height),
278
258
small_width,
@@ -287,13 +267,13 @@ impl PlaneComposer<'_> {
287
267
}
288
268
289
269
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
270
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 {
271
let alphas = &self.matte.alpha[row * self.width..][..self.width];
272
for (column, (value, &alpha)) in line.iter_mut().zip(alphas).enumerate() {
273
if alpha == u8::MAX {
295
274
continue;
296
275
}
276
let person = f32::from(alpha) / 255.;
297
277
let (left, right, across) = (self.small_x.first[column], self.small_x.second[column], self.small_x.weight[column]);
298
278
let sample = |line: usize, index: usize| f32::from(self.background[line + index]);
299
279
let upper = sample(small_top, left) * (1. - across) + sample(small_top, right) * across;
@@ -310,13 +290,15 @@ pub fn compose_i420(buffer: &mut I420Buffer, mask: &[f32]) {
310
290
let (chroma_width, chroma_height) = (width.div_ceil(2), height.div_ceil(2));
311
291
let (stride_y, stride_u, stride_v) = buffer.strides();
312
292
let (stride_y, stride_u, stride_v) = (stride_y as usize, stride_u as usize, stride_v as usize);
293
let luma_matte = refine(mask, Planes::of(buffer));
294
let chroma_matte = luma_matte.halved();
313
295
let (plane_y, plane_u, plane_v) = buffer.data_mut();
314
296
let (background_y, small_width, small_height) = blurred_plane(plane_y, stride_y, width, height, BACKGROUND_SCALE);
315
297
let (background_u, ..) = blurred_plane(plane_u, stride_u, chroma_width, chroma_height, BACKGROUND_SCALE / 2);
316
298
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);
299
let luma = PlaneComposer::new(&background_y, small_width, small_height, &luma_matte);
300
let blue = PlaneComposer::new(&background_u, small_width, small_height, &chroma_matte);
301
let red = PlaneComposer::new(&background_v, small_width, small_height, &chroma_matte);
320
302
let bands = std::thread::available_parallelism().map_or(1, usize::from).min(MAX_BANDS);
321
303
std::thread::scope(|scope| {
322
304
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)] {
@@ -330,12 +312,17 @@ pub fn compose_i420(buffer: &mut I420Buffer, mask: &[f32]) {
330
312
331
313
/// Keeps the person (mask near 1) sharp and replaces the rest with a blurred copy; `mask` is `MASK_WIDTH` x `MASK_HEIGHT`.
332
314
pub fn compose(rgba: &mut [u8], width: usize, height: usize, mask: &[f32]) {
315
let matte = refine_rgba(mask, rgba, width, height);
316
compose_blurred(rgba, width, height, &matte);
317
}
318
319
fn compose_blurred(rgba: &mut [u8], width: usize, height: usize, matte: &Matte) {
333
320
let (background, small_width, small_height) = blurred_background(rgba, width, height);
334
compose_over(rgba, width, height, mask, &background, small_width, small_height);
321
compose_over(rgba, width, height, matte, &background, small_width, small_height);
335
322
}
336
323
337
pub fn compose_image(rgba: &mut [u8], width: usize, height: usize, mask: &[f32], covered: &[u8]) {
338
compose_over(rgba, width, height, mask, covered, width, height);
324
pub fn compose_image(rgba: &mut [u8], width: usize, height: usize, matte: &Matte, covered: &[u8]) {
325
compose_over(rgba, width, height, matte, covered, width, height);
339
326
}
340
327
341
328
/// Shared between the UI command and the camera thread.
@@ -441,11 +428,11 @@ impl BlurStage {
441
428
self.covered.is_some()
442
429
}
443
430
444
pub fn compose(&mut self, rgba: &mut [u8], width: usize, height: usize, mask: &[f32]) {
431
pub fn compose(&mut self, rgba: &mut [u8], width: usize, height: usize, matte: &Matte) {
445
432
self.refresh_covered(width, height);
446
433
match &self.covered {
447
Some(covered) => compose_image(rgba, width, height, mask, &covered.rgb),
448
None => compose(rgba, width, height, mask),
434
Some(covered) => compose_image(rgba, width, height, matte, &covered.rgb),
435
None => compose_blurred(rgba, width, height, matte),
449
436
}
450
437
}
451
438
}
@@ -511,7 +498,9 @@ fn smooth_into(current: &mut Vec<f32>, fresh: Vec<f32>) {
511
498
return;
512
499
}
513
500
for (value, new) in current.iter_mut().zip(fresh) {
514
*value += (new - *value) * (1. - MASK_SMOOTHING);
501
let change = new - *value;
502
let smoothing = MASK_SMOOTHING * (1. - change.abs() * MOTION_GAIN).max(0.);
503
*value += change * (1. - smoothing);
515
504
}
516
505
}
517
506
@@ -744,7 +733,7 @@ mod tests {
744
733
fn the_person_stays_and_the_picture_replaces_everything_else() {
745
734
let original = checkerboard();
746
735
let mut replaced = original.clone();
747
compose_image(&mut replaced, WIDTH, HEIGHT, &oval_mask(), &cover_of([10, 120, 200]));
736
compose_image(&mut replaced, WIDTH, HEIGHT, &refine_rgba(&oval_mask(), &original, WIDTH, HEIGHT), &cover_of([10, 120, 200]));
748
737
let (center_x, center_y) = (WIDTH / 2, HEIGHT / 2);
749
738
assert_eq!(pixel(&replaced, center_x, center_y), pixel(&original, center_x, center_y));
750
739
for (x, y) in [(2, 2), (WIDTH - 3, HEIGHT - 3), (2, HEIGHT - 3)] {
@@ -756,17 +745,18 @@ mod tests {
756
745
fn the_picture_edge_is_feathered_like_the_blur_edge() {
757
746
let original = checkerboard();
758
747
let mut replaced = original.clone();
759
compose_image(&mut replaced, WIDTH, HEIGHT, &oval_mask(), &cover_of([0, 0, 0]));
748
compose_image(&mut replaced, WIDTH, HEIGHT, &refine_rgba(&oval_mask(), &original, WIDTH, HEIGHT), &cover_of([0, 0, 0]));
760
749
let edge_row = HEIGHT / 2;
761
750
let switches = (0..WIDTH - 1)
762
751
.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
752
.count();
764
753
assert!(switches <= 2);
765
754
let mut everyone = original.clone();
766
compose_image(&mut everyone, WIDTH, HEIGHT, &vec![1.; MASK_WIDTH * MASK_HEIGHT], &cover_of([0, 0, 0]));
755
compose_image(&mut everyone, WIDTH, HEIGHT, &refine_rgba(&vec![1.; MASK_WIDTH * MASK_HEIGHT], &original, WIDTH, HEIGHT), &cover_of([0, 0, 0]));
767
756
assert_eq!(everyone, original);
757
let empty = refine_rgba(&vec![0.; MASK_WIDTH * MASK_HEIGHT], &original, WIDTH, HEIGHT);
768
758
let mut nobody = original;
769
compose_image(&mut nobody, WIDTH, HEIGHT, &vec![0.; MASK_WIDTH * MASK_HEIGHT], &cover_of([0, 0, 0]));
759
compose_image(&mut nobody, WIDTH, HEIGHT, &empty, &cover_of([0, 0, 0]));
770
760
assert!(nobody.chunks(CHANNELS).all(|pixel| pixel[..3] == [0, 0, 0] && pixel[3] == 255));
771
761
}
772
762
@@ -12,6 +12,7 @@ use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};12
use crate::background::BackgroundPicture;12
use crate::background::BackgroundPicture;13
use crate::effects::CameraEffects;13
use crate::effects::CameraEffects;14
use crate::error::{Error, Result};14
use crate::error::{Error, Result};15
use crate::matte::{Matte, Planes, refine, refine_rgba};15
use crate::standout::Cutout;16
use crate::standout::Cutout;16
17
17
const MODEL: &[u8] = include_bytes!("../assets/selfie_segmentation_landscape.onnx");18
const MODEL: &[u8] = include_bytes!("../assets/selfie_segmentation_landscape.onnx");@@ -21,10 +22,8 @@ const CHANNELS: usize = 4;21
const BACKGROUND_SCALE: usize = 4;22
const BACKGROUND_SCALE: usize = 4;22
const BLUR_RADIUS: usize = 3;23
const BLUR_RADIUS: usize = 3;23
const BLUR_PASSES: usize = 2;24
const BLUR_PASSES: usize = 2;24
const EDGE_LOW: f32 = 0.3;25
const EDGE_HIGH: f32 = 0.7;26
const OPAQUE: f32 = 0.985;27
const MASK_SMOOTHING: f32 = 0.35;25
const MASK_SMOOTHING: f32 = 0.35;26
const MOTION_GAIN: f32 = 2.;28
const SLOW_INFERENCE: Duration = Duration::from_millis(22);27
const SLOW_INFERENCE: Duration = Duration::from_millis(22);29
const VERY_SLOW_INFERENCE: Duration = Duration::from_millis(45);28
const VERY_SLOW_INFERENCE: Duration = Duration::from_millis(45);30
const MAX_BANDS: usize = 4;29
const MAX_BANDS: usize = 4;@@ -82,11 +81,6 @@ fn model_input(rgba: &[u8], width: usize, height: usize) -> Tensor {82
Tensor::from_shape(&[1, 3, MASK_HEIGHT, MASK_WIDTH], &data).expect("shape matches data")81
Tensor::from_shape(&[1, 3, MASK_HEIGHT, MASK_WIDTH], &data).expect("shape matches data")83
}82
}84
83
85
pub(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
90
pub(crate) struct Axis {84
pub(crate) struct Axis {91
pub(crate) first: Vec<usize>,85
pub(crate) first: Vec<usize>,92
pub(crate) second: Vec<usize>,86
pub(crate) second: Vec<usize>,@@ -159,19 +153,10 @@ fn blurred_background(rgba: &[u8], width: usize, height: usize) -> (Vec<u8>, usi159
(small, small_width, small_height)153
(small, small_width, small_height)160
}154
}161
155
162
fn 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 * fraction167
}168
169
struct Composer<'a> {156
struct Composer<'a> {170
background: &'a [u8],157
background: &'a [u8],171
mask: &'a [f32],158
matte: &'a Matte,172
width: usize,159
width: usize,173
mask_x: Axis,174
mask_y: Axis,175
small_x: Axis,160
small_x: Axis,176
small_y: Axis,161
small_y: Axis,177
small_width: usize,162
small_width: usize,@@ -185,13 +170,13 @@ impl Composer<'_> {185
}170
}186
171
187
fn row(&self, line: &mut [u8], row: usize) {172
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]);173
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() {174
let alphas = &self.matte.alpha[row * self.matte.width..][..self.matte.width];191
let person = smoothstep(sample_mask(self.mask, &self.mask_x, column, (mask_top, mask_bottom, mask_fraction)));175
for (column, (pixel, &alpha)) in line.as_chunks_mut::<CHANNELS>().0.iter_mut().zip(alphas).enumerate() {192
if person >= OPAQUE {176
if alpha == u8::MAX {193
continue;177
continue;194
}178
}179
let person = f32::from(alpha) / 255.;195
let (left, right, across) = (self.small_x.first[column], self.small_x.second[column], self.small_x.weight[column]);180
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() {181
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]);182
let sample = |line: usize, index: usize| f32::from(self.background[(line + index) * 3 + channel]);@@ -204,13 +189,11 @@ impl Composer<'_> {204
}189
}205
}190
}206
191
207
fn compose_over(rgba: &mut [u8], width: usize, height: usize, mask: &[f32], background: &[u8], background_width: usize, background_height: usize) {192
fn compose_over(rgba: &mut [u8], width: usize, height: usize, matte: &Matte, background: &[u8], background_width: usize, background_height: usize) {208
let composer = Composer {193
let composer = Composer {209
background,194
background,210
mask,195
matte,211
width,196
width,212
mask_x: axis(width, MASK_WIDTH),213
mask_y: axis(height, MASK_HEIGHT),214
small_x: axis(width, background_width),197
small_x: axis(width, background_width),215
small_y: axis(height, background_height),198
small_y: axis(height, background_height),216
small_width: background_width,199
small_width: background_width,@@ -256,23 +239,20 @@ fn blurred_plane(plane: &[u8], stride: usize, width: usize, height: usize, facto256
239
257
struct PlaneComposer<'a> {240
struct PlaneComposer<'a> {258
background: &'a [u8],241
background: &'a [u8],259
mask: &'a [f32],242
matte: &'a Matte,260
width: usize,243
width: usize,261
mask_x: Axis,262
mask_y: Axis,263
small_x: Axis,244
small_x: Axis,264
small_y: Axis,245
small_y: Axis,265
small_width: usize,246
small_width: usize,266
}247
}267
248
268
impl PlaneComposer<'_> {249
impl PlaneComposer<'_> {269
fn new<'a>(background: &'a [u8], small_width: usize, small_height: usize, mask: &'a [f32], width: usize, height: usize) -> PlaneComposer<'a> {250
fn new<'a>(background: &'a [u8], small_width: usize, small_height: usize, matte: &'a Matte) -> PlaneComposer<'a> {251
let (width, height) = (matte.width, matte.height);270
PlaneComposer {252
PlaneComposer {271
background,253
background,272
mask,254
matte,273
width,255
width,274
mask_x: axis(width, MASK_WIDTH),275
mask_y: axis(height, MASK_HEIGHT),276
small_x: axis(width, small_width),256
small_x: axis(width, small_width),277
small_y: axis(height, small_height),257
small_y: axis(height, small_height),278
small_width,258
small_width,@@ -287,13 +267,13 @@ impl PlaneComposer<'_> {287
}267
}288
268
289
fn row(&self, line: &mut [u8], row: usize) {269
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]);270
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() {271
let alphas = &self.matte.alpha[row * self.width..][..self.width];293
let person = smoothstep(sample_mask(self.mask, &self.mask_x, column, mask_rows));272
for (column, (value, &alpha)) in line.iter_mut().zip(alphas).enumerate() {294
if person >= OPAQUE {273
if alpha == u8::MAX {295
continue;274
continue;296
}275
}276
let person = f32::from(alpha) / 255.;297
let (left, right, across) = (self.small_x.first[column], self.small_x.second[column], self.small_x.weight[column]);277
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]);278
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;279
let upper = sample(small_top, left) * (1. - across) + sample(small_top, right) * across;@@ -310,13 +290,15 @@ pub fn compose_i420(buffer: &mut I420Buffer, mask: &[f32]) {310
let (chroma_width, chroma_height) = (width.div_ceil(2), height.div_ceil(2));290
let (chroma_width, chroma_height) = (width.div_ceil(2), height.div_ceil(2));311
let (stride_y, stride_u, stride_v) = buffer.strides();291
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);292
let (stride_y, stride_u, stride_v) = (stride_y as usize, stride_u as usize, stride_v as usize);293
let luma_matte = refine(mask, Planes::of(buffer));294
let chroma_matte = luma_matte.halved();313
let (plane_y, plane_u, plane_v) = buffer.data_mut();295
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);296
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);297
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);298
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);299
let luma = PlaneComposer::new(&background_y, small_width, small_height, &luma_matte);318
let blue = PlaneComposer::new(&background_u, small_width, small_height, mask, chroma_width, chroma_height);300
let blue = PlaneComposer::new(&background_u, small_width, small_height, &chroma_matte);319
let red = PlaneComposer::new(&background_v, small_width, small_height, mask, chroma_width, chroma_height);301
let red = PlaneComposer::new(&background_v, small_width, small_height, &chroma_matte);320
let bands = std::thread::available_parallelism().map_or(1, usize::from).min(MAX_BANDS);302
let bands = std::thread::available_parallelism().map_or(1, usize::from).min(MAX_BANDS);321
std::thread::scope(|scope| {303
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)] {304
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)] {@@ -330,12 +312,17 @@ pub fn compose_i420(buffer: &mut I420Buffer, mask: &[f32]) {330
312
331
/// Keeps the person (mask near 1) sharp and replaces the rest with a blurred copy; `mask` is `MASK_WIDTH` x `MASK_HEIGHT`.313
/// Keeps the person (mask near 1) sharp and replaces the rest with a blurred copy; `mask` is `MASK_WIDTH` x `MASK_HEIGHT`.332
pub fn compose(rgba: &mut [u8], width: usize, height: usize, mask: &[f32]) {314
pub fn compose(rgba: &mut [u8], width: usize, height: usize, mask: &[f32]) {315
let matte = refine_rgba(mask, rgba, width, height);316
compose_blurred(rgba, width, height, &matte);317
}318
319
fn compose_blurred(rgba: &mut [u8], width: usize, height: usize, matte: &Matte) {333
let (background, small_width, small_height) = blurred_background(rgba, width, height);320
let (background, small_width, small_height) = blurred_background(rgba, width, height);334
compose_over(rgba, width, height, mask, &background, small_width, small_height);321
compose_over(rgba, width, height, matte, &background, small_width, small_height);335
}322
}336
323
337
pub fn compose_image(rgba: &mut [u8], width: usize, height: usize, mask: &[f32], covered: &[u8]) {324
pub fn compose_image(rgba: &mut [u8], width: usize, height: usize, matte: &Matte, covered: &[u8]) {338
compose_over(rgba, width, height, mask, covered, width, height);325
compose_over(rgba, width, height, matte, covered, width, height);339
}326
}340
327
341
/// Shared between the UI command and the camera thread.328
/// Shared between the UI command and the camera thread.@@ -441,11 +428,11 @@ impl BlurStage {441
self.covered.is_some()428
self.covered.is_some()442
}429
}443
430
444
pub fn compose(&mut self, rgba: &mut [u8], width: usize, height: usize, mask: &[f32]) {431
pub fn compose(&mut self, rgba: &mut [u8], width: usize, height: usize, matte: &Matte) {445
self.refresh_covered(width, height);432
self.refresh_covered(width, height);446
match &self.covered {433
match &self.covered {447
Some(covered) => compose_image(rgba, width, height, mask, &covered.rgb),434
Some(covered) => compose_image(rgba, width, height, matte, &covered.rgb),448
None => compose(rgba, width, height, mask),435
None => compose_blurred(rgba, width, height, matte),449
}436
}450
}437
}451
}438
}@@ -511,7 +498,9 @@ fn smooth_into(current: &mut Vec<f32>, fresh: Vec<f32>) {511
return;498
return;512
}499
}513
for (value, new) in current.iter_mut().zip(fresh) {500
for (value, new) in current.iter_mut().zip(fresh) {514
*value += (new - *value) * (1. - MASK_SMOOTHING);501
let change = new - *value;502
let smoothing = MASK_SMOOTHING * (1. - change.abs() * MOTION_GAIN).max(0.);503
*value += change * (1. - smoothing);515
}504
}516
}505
}517
506
@@ -744,7 +733,7 @@ mod tests {744
fn the_person_stays_and_the_picture_replaces_everything_else() {733
fn the_person_stays_and_the_picture_replaces_everything_else() {745
let original = checkerboard();734
let original = checkerboard();746
let mut replaced = original.clone();735
let mut replaced = original.clone();747
compose_image(&mut replaced, WIDTH, HEIGHT, &oval_mask(), &cover_of([10, 120, 200]));736
compose_image(&mut replaced, WIDTH, HEIGHT, &refine_rgba(&oval_mask(), &original, WIDTH, HEIGHT), &cover_of([10, 120, 200]));748
let (center_x, center_y) = (WIDTH / 2, HEIGHT / 2);737
let (center_x, center_y) = (WIDTH / 2, HEIGHT / 2);749
assert_eq!(pixel(&replaced, center_x, center_y), pixel(&original, center_x, center_y));738
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)] {739
for (x, y) in [(2, 2), (WIDTH - 3, HEIGHT - 3), (2, HEIGHT - 3)] {@@ -756,17 +745,18 @@ mod tests {756
fn the_picture_edge_is_feathered_like_the_blur_edge() {745
fn the_picture_edge_is_feathered_like_the_blur_edge() {757
let original = checkerboard();746
let original = checkerboard();758
let mut replaced = original.clone();747
let mut replaced = original.clone();759
compose_image(&mut replaced, WIDTH, HEIGHT, &oval_mask(), &cover_of([0, 0, 0]));748
compose_image(&mut replaced, WIDTH, HEIGHT, &refine_rgba(&oval_mask(), &original, WIDTH, HEIGHT), &cover_of([0, 0, 0]));760
let edge_row = HEIGHT / 2;749
let edge_row = HEIGHT / 2;761
let switches = (0..WIDTH - 1)750
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))751
.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();752
.count();764
assert!(switches <= 2);753
assert!(switches <= 2);765
let mut everyone = original.clone();754
let mut everyone = original.clone();766
compose_image(&mut everyone, WIDTH, HEIGHT, &vec![1.; MASK_WIDTH * MASK_HEIGHT], &cover_of([0, 0, 0]));755
compose_image(&mut everyone, WIDTH, HEIGHT, &refine_rgba(&vec![1.; MASK_WIDTH * MASK_HEIGHT], &original, WIDTH, HEIGHT), &cover_of([0, 0, 0]));767
assert_eq!(everyone, original);756
assert_eq!(everyone, original);757
let empty = refine_rgba(&vec![0.; MASK_WIDTH * MASK_HEIGHT], &original, WIDTH, HEIGHT);768
let mut nobody = original;758
let mut nobody = original;769
compose_image(&mut nobody, WIDTH, HEIGHT, &vec![0.; MASK_WIDTH * MASK_HEIGHT], &cover_of([0, 0, 0]));759
compose_image(&mut nobody, WIDTH, HEIGHT, &empty, &cover_of([0, 0, 0]));770
assert!(nobody.chunks(CHANNELS).all(|pixel| pixel[..3] == [0, 0, 0] && pixel[3] == 255));760
assert!(nobody.chunks(CHANNELS).all(|pixel| pixel[..3] == [0, 0, 0] && pixel[3] == 255));771
}761
}772
762
@@ -8,6 +8,7 @@ use crate::blur::{BlurSettings, BlurStage, compose_i420, MASK_HEIGHT, MASK_WIDTH
8
8
use crate::camera::i420_from_rgba;
9
9
use crate::standout::Cutout;
10
10
use crate::framing::{CropPlanner, Subject, crop_and_scale, find_subject, is_full_frame};
11
use crate::matte::{Planes, refine};
11
12
use crate::luma_effects::{apply_table, gamma_table, mean_luma, smooth_gamma, soften_luma, target_gamma};
12
13
13
14
pub const SOFT_FOCUS_DEFAULT: u8 = 50;
@@ -168,11 +169,12 @@ impl EffectsStage {
168
169
compose_i420(&mut buffer, masks.mask());
169
170
return buffer;
170
171
}
172
let matte = refine(masks.mask(), Planes::of(&buffer));
171
173
let (stride_y, stride_u, stride_v) = buffer.strides();
172
174
let (plane_y, plane_u, plane_v) = buffer.data();
173
175
let mut rgba = vec![0u8; width * height * RGBA_BYTES];
174
176
i420_to_abgr(plane_y, stride_y, plane_u, stride_u, plane_v, stride_v, &mut rgba, (width * RGBA_BYTES) as u32, width as i32, height as i32);
175
self.blur.compose(&mut rgba, width, height, masks.mask());
177
self.blur.compose(&mut rgba, width, height, &matte);
176
178
i420_from_rgba(&rgba, width as u32, height as u32)
177
179
}
178
180
@@ -8,6 +8,7 @@ use crate::blur::{BlurSettings, BlurStage, compose_i420, MASK_HEIGHT, MASK_WIDTH8
use crate::camera::i420_from_rgba;8
use crate::camera::i420_from_rgba;9
use crate::standout::Cutout;9
use crate::standout::Cutout;10
use crate::framing::{CropPlanner, Subject, crop_and_scale, find_subject, is_full_frame};10
use crate::framing::{CropPlanner, Subject, crop_and_scale, find_subject, is_full_frame};11
use crate::matte::{Planes, refine};11
use crate::luma_effects::{apply_table, gamma_table, mean_luma, smooth_gamma, soften_luma, target_gamma};12
use crate::luma_effects::{apply_table, gamma_table, mean_luma, smooth_gamma, soften_luma, target_gamma};12
13
13
pub const SOFT_FOCUS_DEFAULT: u8 = 50;14
pub const SOFT_FOCUS_DEFAULT: u8 = 50;@@ -168,11 +169,12 @@ impl EffectsStage {168
compose_i420(&mut buffer, masks.mask());169
compose_i420(&mut buffer, masks.mask());169
return buffer;170
return buffer;170
}171
}172
let matte = refine(masks.mask(), Planes::of(&buffer));171
let (stride_y, stride_u, stride_v) = buffer.strides();173
let (stride_y, stride_u, stride_v) = buffer.strides();172
let (plane_y, plane_u, plane_v) = buffer.data();174
let (plane_y, plane_u, plane_v) = buffer.data();173
let mut rgba = vec![0u8; width * height * RGBA_BYTES];175
let mut rgba = vec![0u8; width * height * RGBA_BYTES];174
i420_to_abgr(plane_y, stride_y, plane_u, stride_u, plane_v, stride_v, &mut rgba, (width * RGBA_BYTES) as u32, width as i32, height as i32);176
i420_to_abgr(plane_y, stride_y, plane_u, stride_u, plane_v, stride_v, &mut rgba, (width * RGBA_BYTES) as u32, width as i32, height as i32);175
self.blur.compose(&mut rgba, width, height, masks.mask());177
self.blur.compose(&mut rgba, width, height, &matte);176
i420_from_rgba(&rgba, width as u32, height as u32)178
i420_from_rgba(&rgba, width as u32, height as u32)177
}179
}178
180
@@ -22,6 +22,7 @@ pub mod hold;
22
22
pub mod join;
23
23
pub mod level;
24
24
pub mod luma_effects;
25
pub mod matte;
25
26
#[cfg(windows)]
26
27
mod loopback_windows;
27
28
pub mod meeting;
@@ -22,6 +22,7 @@ pub mod hold;22
pub mod join;22
pub mod join;23
pub mod level;23
pub mod level;24
pub mod luma_effects;24
pub mod luma_effects;25
pub mod matte;25
#[cfg(windows)]26
#[cfg(windows)]26
mod loopback_windows;27
mod loopback_windows;27
pub mod meeting;28
pub mod meeting;@@ -0,0 +1,353 @@
1
use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};
2
3
use crate::blur::{Axis, MASK_HEIGHT, MASK_WIDTH, axis};
4
use crate::camera::i420_from_rgba;
5
6
const GUIDE_WIDTH: usize = 160;
7
const FILTER_RADIUS: usize = 3;
8
const FILTER_EPSILON: f32 = 3e-3;
9
const CHROMA_WEIGHT: f32 = 2.;
10
const MATTE_LOW: f32 = 0.45;
11
const MATTE_HIGH: f32 = 0.8;
12
const SURE_PERSON: f32 = 0.85;
13
const SURE_BACKGROUND: f32 = 0.1;
14
const CERTAINTY_RAMP: f32 = 0.05;
15
const MAX_BANDS: usize = 4;
16
const CHANNELS: usize = 3;
17
18
/// Person alpha (0..255) per pixel of a `width` x `height` frame.
19
pub struct Matte {
20
pub width: usize,
21
pub height: usize,
22
pub alpha: Vec<u8>,
23
}
24
25
impl Matte {
26
/// Same matte at half resolution, for 4:2:0 chroma planes.
27
pub fn halved(&self) -> Matte {
28
let (width, height) = (self.width.div_ceil(2), self.height.div_ceil(2));
29
let mut alpha = vec![0u8; width * height];
30
for (row, line) in alpha.chunks_exact_mut(width).enumerate() {
31
let (top, bottom) = (row * 2, (row * 2 + 1).min(self.height - 1));
32
for (column, slot) in line.iter_mut().enumerate() {
33
let (left, right) = (column * 2, (column * 2 + 1).min(self.width - 1));
34
let sum: u32 = [(top, left), (top, right), (bottom, left), (bottom, right)].iter().map(|&(y, x)| u32::from(self.alpha[y * self.width + x])).sum();
35
*slot = ((sum + 2) / 4) as u8;
36
}
37
}
38
Matte { width, height, alpha }
39
}
40
}
41
42
/// The 4:2:0 planes of the frame the matte follows.
43
#[derive(Clone, Copy)]
44
pub struct Planes<'a> {
45
pub luma: &'a [u8],
46
pub luma_stride: usize,
47
pub blue: &'a [u8],
48
pub blue_stride: usize,
49
pub red: &'a [u8],
50
pub red_stride: usize,
51
pub width: usize,
52
pub height: usize,
53
}
54
55
impl<'a> Planes<'a> {
56
pub fn of(buffer: &'a I420Buffer) -> Planes<'a> {
57
let (luma_stride, blue_stride, red_stride) = buffer.strides();
58
let (luma, blue, red) = buffer.data();
59
Planes { luma, luma_stride: luma_stride as usize, blue, blue_stride: blue_stride as usize, red, red_stride: red_stride as usize, width: buffer.width() as usize, height: buffer.height() as usize }
60
}
61
62
fn pixel(&self, column: usize, row: usize) -> [f32; CHANNELS] {
63
let chroma = |plane: &[u8], stride: usize| (f32::from(plane[row / 2 * stride + column / 2]) - 128.) * CHROMA_WEIGHT / 255.;
64
[f32::from(self.luma[row * self.luma_stride + column]) / 255., chroma(self.blue, self.blue_stride), chroma(self.red, self.red_stride)]
65
}
66
}
67
68
fn ramp(value: f32, start: f32) -> f32 {
69
((value - start) / CERTAINTY_RAMP).clamp(0., 1.)
70
}
71
72
fn edge_curve(value: f32) -> f32 {
73
let t = ((value - MATTE_LOW) / (MATTE_HIGH - MATTE_LOW)).clamp(0., 1.);
74
t * t * (3. - 2. * t)
75
}
76
77
fn box_filter(input: &[f32], width: usize, height: usize, radius: usize) -> Vec<f32> {
78
let mut across = vec![0f32; input.len()];
79
let mut prefix = vec![0f32; width + 1];
80
for (line, output) in input.chunks_exact(width).zip(across.chunks_exact_mut(width)) {
81
for (index, &value) in line.iter().enumerate() {
82
prefix[index + 1] = prefix[index] + value;
83
}
84
for (index, slot) in output.iter_mut().enumerate() {
85
let (low, high) = (index.saturating_sub(radius), (index + radius + 1).min(width));
86
*slot = (prefix[high] - prefix[low]) / (high - low) as f32;
87
}
88
}
89
let mut output = vec![0f32; input.len()];
90
let mut sums = vec![0f32; width];
91
for line in across.chunks_exact(width).take(radius.min(height)) {
92
sums.iter_mut().zip(line).for_each(|(sum, value)| *sum += value);
93
}
94
for row in 0..height {
95
if row + radius < height {
96
sums.iter_mut().zip(&across[(row + radius) * width..][..width]).for_each(|(sum, value)| *sum += value);
97
}
98
if row > radius {
99
sums.iter_mut().zip(&across[(row - radius - 1) * width..][..width]).for_each(|(sum, value)| *sum -= value);
100
}
101
let count = ((row + radius + 1).min(height) - row.saturating_sub(radius)) as f32;
102
output[row * width..][..width].iter_mut().zip(&sums).for_each(|(slot, sum)| *slot = sum / count);
103
}
104
output
105
}
106
107
fn cell_means(plane: &[u8], stride: usize, subsampling: usize, (plane_width, plane_height): (usize, usize), factor: usize, (small_width, small_height): (usize, usize)) -> Vec<f32> {
108
let span = |cell: usize, limit: usize| {
109
let first = (cell * factor / subsampling).min(limit - 1);
110
first..((cell + 1) * factor).div_ceil(subsampling).clamp(first + 1, limit)
111
};
112
let columns: Vec<_> = (0..small_width).map(|column| span(column, plane_width)).collect();
113
let mut means = Vec::with_capacity(small_width * small_height);
114
let mut sums = vec![0u32; plane_width];
115
for row in 0..small_height {
116
let rows = span(row, plane_height);
117
sums.fill(0);
118
for line in rows.clone() {
119
sums.iter_mut().zip(&plane[line * stride..][..plane_width]).for_each(|(sum, &value)| *sum += u32::from(value));
120
}
121
for range in &columns {
122
means.push(sums[range.clone()].iter().sum::<u32>() as f32 / (rows.len() * range.len()) as f32);
123
}
124
}
125
means
126
}
127
128
fn small_guide(planes: &Planes, factor: usize) -> ([Vec<f32>; CHANNELS], usize, usize) {
129
let small = (planes.width.div_ceil(factor), planes.height.div_ceil(factor));
130
let chroma = (planes.width.div_ceil(2), planes.height.div_ceil(2));
131
let luma = cell_means(planes.luma, planes.luma_stride, 1, (planes.width, planes.height), factor, small).into_iter().map(|value| value / 255.).collect();
132
let colour = |plane: &[u8], stride: usize| cell_means(plane, stride, 2, chroma, factor, small).into_iter().map(|value| (value - 128.) * CHROMA_WEIGHT / 255.).collect();
133
([luma, colour(planes.blue, planes.blue_stride), colour(planes.red, planes.red_stride)], small.0, small.1)
134
}
135
136
fn small_mask(mask: &[f32], width: usize, height: usize) -> Vec<f32> {
137
let (mask_x, mask_y) = (axis(width, MASK_WIDTH), axis(height, MASK_HEIGHT));
138
let mut small = Vec::with_capacity(width * height);
139
for row in 0..height {
140
let (top, bottom, down) = (mask_y.first[row] * MASK_WIDTH, mask_y.second[row] * MASK_WIDTH, mask_y.weight[row]);
141
for column in 0..width {
142
let (left, right, across) = (mask_x.first[column], mask_x.second[column], mask_x.weight[column]);
143
let upper = mask[top + left] * (1. - across) + mask[top + right] * across;
144
let lower = mask[bottom + left] * (1. - across) + mask[bottom + right] * across;
145
small.push(upper * (1. - down) + lower * down);
146
}
147
}
148
small
149
}
150
151
struct Coefficients {
152
slope: [Vec<f32>; CHANNELS],
153
offset: Vec<f32>,
154
width: usize,
155
}
156
157
fn solve(covariance: [[f32; CHANNELS]; CHANNELS], target: [f32; CHANNELS]) -> [f32; CHANNELS] {
158
let [[a, b, c], [_, d, e], [_, _, f]] = covariance;
159
let cofactors = [[d * f - e * e, c * e - b * f, b * e - c * d], [c * e - b * f, a * f - c * c, b * c - a * e], [b * e - c * d, b * c - a * e, a * d - b * b]];
160
let determinant = a * cofactors[0][0] + b * cofactors[0][1] + c * cofactors[0][2];
161
std::array::from_fn(|row| (0..CHANNELS).map(|column| cofactors[row][column] * target[column]).sum::<f32>() / determinant)
162
}
163
164
fn coefficients(guide: &[Vec<f32>; CHANNELS], person: &[f32], width: usize, height: usize) -> Coefficients {
165
let mean = |values: Vec<f32>| box_filter(&values, width, height, FILTER_RADIUS);
166
let mean_guide: [Vec<f32>; CHANNELS] = std::array::from_fn(|channel| mean(guide[channel].clone()));
167
let mean_person = mean(person.to_vec());
168
let mean_product: [Vec<f32>; CHANNELS] = std::array::from_fn(|channel| mean(guide[channel].iter().zip(person).map(|(guide, person)| guide * person).collect()));
169
let pairs = [(0, 0), (0, 1), (0, 2), (1, 1), (1, 2), (2, 2)];
170
let mean_pair: Vec<Vec<f32>> = pairs.iter().map(|&(first, second)| mean(guide[first].iter().zip(&guide[second]).map(|(first, second)| first * second).collect())).collect();
171
let mut slope: [Vec<f32>; CHANNELS] = std::array::from_fn(|_| vec![0f32; person.len()]);
172
let mut offset = vec![0f32; person.len()];
173
for index in 0..person.len() {
174
let mut covariance = [[0f32; CHANNELS]; CHANNELS];
175
for (&(first, second), pair) in pairs.iter().zip(&mean_pair) {
176
let value = pair[index] - mean_guide[first][index] * mean_guide[second][index] + if first == second { FILTER_EPSILON } else { 0. };
177
covariance[first][second] = value;
178
covariance[second][first] = value;
179
}
180
let target = std::array::from_fn(|channel| mean_product[channel][index] - mean_guide[channel][index] * mean_person[index]);
181
let solution = solve(covariance, target);
182
offset[index] = mean_person[index] - (0..CHANNELS).map(|channel| solution[channel] * mean_guide[channel][index]).sum::<f32>();
183
for channel in 0..CHANNELS {
184
slope[channel][index] = solution[channel];
185
}
186
}
187
Coefficients { slope: slope.map(mean), offset: mean(offset), width }
188
}
189
190
struct Upsampler<'a> {
191
coefficients: &'a Coefficients,
192
prior: &'a [f32],
193
planes: Planes<'a>,
194
across: Axis,
195
down: Axis,
196
}
197
198
impl Upsampler<'_> {
199
fn rows(&self, alpha: &mut [u8], first_row: usize) {
200
let small_width = self.coefficients.width;
201
let mut lines = vec![[0f32; CHANNELS + 2]; small_width];
202
for (offset, line) in alpha.chunks_exact_mut(self.planes.width).enumerate() {
203
let row = first_row + offset;
204
let (top, bottom, vertical) = (self.down.first[row] * small_width, self.down.second[row] * small_width, self.down.weight[row]);
205
let blend = |grid: &[f32], column: usize| grid[top + column] * (1. - vertical) + grid[bottom + column] * vertical;
206
for (column, slot) in lines.iter_mut().enumerate() {
207
*slot = [blend(&self.coefficients.slope[0], column), blend(&self.coefficients.slope[1], column), blend(&self.coefficients.slope[2], column), blend(&self.coefficients.offset, column), blend(self.prior, column)];
208
}
209
for (column, slot) in line.iter_mut().enumerate() {
210
let (left, right, horizontal) = (&lines[self.across.first[column]], &lines[self.across.second[column]], self.across.weight[column]);
211
let at = |index: usize| left[index] * (1. - horizontal) + right[index] * horizontal;
212
let prior = at(4);
213
let (floor, ceiling) = (ramp(prior, SURE_PERSON), ramp(prior, SURE_BACKGROUND - CERTAINTY_RAMP));
214
if floor >= 1. || ceiling <= 0. {
215
*slot = if floor >= 1. { u8::MAX } else { 0 };
216
continue;
217
}
218
let guide = self.planes.pixel(column, row);
219
let person = at(0) * guide[0] + at(1) * guide[1] + at(2) * guide[2] + at(3);
220
*slot = (edge_curve(person).max(floor).min(ceiling) * 255. + 0.5) as u8;
221
}
222
}
223
}
224
}
225
226
/// Snaps the low-resolution `mask` to the colour edges of the full-resolution frame with a fast colour guided filter.
227
pub fn refine(mask: &[f32], planes: Planes) -> Matte {
228
let (width, height) = (planes.width, planes.height);
229
let factor = (width / GUIDE_WIDTH).max(1);
230
let (guide, small_width, small_height) = small_guide(&planes, factor);
231
let prior = small_mask(mask, small_width, small_height);
232
let coefficients = coefficients(&guide, &prior, small_width, small_height);
233
let upsampler = Upsampler { coefficients: &coefficients, prior: &prior, planes, across: axis(width, small_width), down: axis(height, small_height) };
234
let mut alpha = vec![0u8; width * height];
235
let bands = std::thread::available_parallelism().map_or(1, usize::from).min(MAX_BANDS);
236
let rows_per_band = height.div_ceil(bands);
237
std::thread::scope(|scope| {
238
for (index, band) in alpha.chunks_mut(rows_per_band * width).enumerate() {
239
let upsampler = &upsampler;
240
scope.spawn(move || upsampler.rows(band, index * rows_per_band));
241
}
242
});
243
Matte { width, height, alpha }
244
}
245
246
pub fn refine_rgba(mask: &[f32], rgba: &[u8], width: usize, height: usize) -> Matte {
247
refine(mask, Planes::of(&i420_from_rgba(rgba, width as u32, height as u32)))
248
}
249
250
#[cfg(test)]
251
mod tests {
252
use super::*;
253
254
const WIDTH: usize = 1280;
255
const HEIGHT: usize = 720;
256
const LEFT: usize = 403;
257
const RIGHT: usize = 877;
258
const TOP: usize = 161;
259
const BOTTOM: usize = 598;
260
const BLOCK: usize = 3;
261
262
fn frame(width: usize, height: usize, luma: impl Fn(usize, usize) -> u8) -> I420Buffer {
263
let mut buffer = I420Buffer::new(width as u32, height as u32);
264
let stride = buffer.strides().0 as usize;
265
let (plane_y, plane_u, plane_v) = buffer.data_mut();
266
for row in 0..height {
267
for column in 0..width {
268
plane_y[row * stride + column] = luma(column, row);
269
}
270
}
271
plane_u.fill(128);
272
plane_v.fill(128);
273
buffer
274
}
275
276
fn square_frame() -> I420Buffer {
277
frame(WIDTH, HEIGHT, |column, row| if (LEFT..RIGHT).contains(&column) && (TOP..BOTTOM).contains(&row) { 200 } else { 50 })
278
}
279
280
fn blocky_mask() -> Vec<f32> {
281
(0..MASK_WIDTH * MASK_HEIGHT)
282
.map(|index| {
283
let (block_column, block_row) = ((index % MASK_WIDTH) / BLOCK * BLOCK, (index / MASK_WIDTH) / BLOCK * BLOCK);
284
let center_x = (block_column as f32 + BLOCK as f32 / 2.) * WIDTH as f32 / MASK_WIDTH as f32;
285
let center_y = (block_row as f32 + BLOCK as f32 / 2.) * HEIGHT as f32 / MASK_HEIGHT as f32;
286
let inside = (LEFT as f32..RIGHT as f32).contains(¢er_x) && (TOP as f32..BOTTOM as f32).contains(¢er_y);
287
if inside { 0.9 } else { 0.1 }
288
})
289
.collect()
290
}
291
292
fn crossing(values: impl Iterator<Item = u8>) -> Vec<usize> {
293
let values: Vec<u8> = values.collect();
294
values.windows(2).enumerate().filter(|(_, pair)| (pair[0] < 128) != (pair[1] < 128)).map(|(index, _)| index + 1).collect()
295
}
296
297
#[test]
298
fn a_blocky_mask_snaps_to_the_sharp_edge_of_the_frame() {
299
let matte = refine(&blocky_mask(), Planes::of(&square_frame()));
300
for row in [TOP + 40, HEIGHT / 2, BOTTOM - 40] {
301
let edges = crossing(matte.alpha[row * WIDTH..][..WIDTH].iter().copied());
302
assert_eq!(edges.len(), 2, "row {row}: {edges:?}");
303
assert!(edges[0].abs_diff(LEFT) <= 2 && edges[1].abs_diff(RIGHT) <= 2, "row {row}: {edges:?}");
304
}
305
for column in [LEFT + 40, WIDTH / 2, RIGHT - 40] {
306
let edges = crossing((0..HEIGHT).map(|row| matte.alpha[row * WIDTH + column]));
307
assert!(edges.len() == 2 && edges[0].abs_diff(TOP) <= 2 && edges[1].abs_diff(BOTTOM) <= 2, "column {column}: {edges:?}");
308
}
309
}
310
311
#[test]
312
fn a_colour_edge_without_a_brightness_step_still_guides_the_matte() {
313
let mut colour = frame(WIDTH, HEIGHT, |_, _| 120);
314
let stride = colour.strides().1 as usize;
315
let blue = colour.data_mut().1;
316
for row in 0..HEIGHT / 2 {
317
for column in 0..WIDTH / 2 {
318
let inside = (LEFT / 2..RIGHT / 2).contains(&column) && (TOP / 2..BOTTOM / 2).contains(&row);
319
blue[row * stride + column] = if inside { 170 } else { 90 };
320
}
321
}
322
let matte = refine(&blocky_mask(), Planes::of(&colour));
323
let edges = crossing(matte.alpha[HEIGHT / 2 * WIDTH..][..WIDTH].iter().copied());
324
assert!(edges.len() == 2 && edges[0].abs_diff(LEFT) <= 2 && edges[1].abs_diff(RIGHT) <= 2, "{edges:?}");
325
}
326
327
#[test]
328
fn no_background_shows_outside_the_true_edge() {
329
let matte = refine(&blocky_mask(), Planes::of(&square_frame()));
330
let line = &matte.alpha[HEIGHT / 2 * WIDTH..][..WIDTH];
331
assert!(line[..LEFT - 1].iter().chain(&line[RIGHT + 1..]).all(|&alpha| alpha == 0), "{:?} {:?}", &line[LEFT - 8..LEFT + 2], &line[RIGHT - 2..RIGHT + 8]);
332
assert!(line[LEFT + 1..RIGHT - 1].iter().all(|&alpha| alpha > 128), "{:?}", &line[RIGHT - 16..RIGHT]);
333
}
334
335
#[test]
336
fn flat_regions_keep_the_mask_and_halving_averages() {
337
let flat = frame(64, 36, |_, _| 120);
338
let everyone = refine(&vec![1.; MASK_WIDTH * MASK_HEIGHT], Planes::of(&flat));
339
assert!(everyone.alpha.iter().all(|&alpha| alpha == 255));
340
let nobody = refine(&vec![0.; MASK_WIDTH * MASK_HEIGHT], Planes::of(&flat));
341
assert!(nobody.alpha.iter().all(|&alpha| alpha == 0));
342
let halved = Matte { width: 3, height: 2, alpha: vec![0, 255, 255, 0, 255, 255] }.halved();
343
assert_eq!((halved.width, halved.height, halved.alpha), (2, 1, vec![128, 255]));
344
}
345
346
#[test]
347
fn the_box_filter_averages_clamped_windows() {
348
let filtered = box_filter(&[0., 3., 6., 9.], 4, 1, 1);
349
assert_eq!(filtered, vec![1.5, 3., 6., 7.5]);
350
let tall = box_filter(&[0., 3., 6., 9.], 1, 4, 1);
351
assert_eq!(tall, vec![1.5, 3., 6., 7.5]);
352
}
353
}
@@ -0,0 +1,353 @@1
use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};2
3
use crate::blur::{Axis, MASK_HEIGHT, MASK_WIDTH, axis};4
use crate::camera::i420_from_rgba;5
6
const GUIDE_WIDTH: usize = 160;7
const FILTER_RADIUS: usize = 3;8
const FILTER_EPSILON: f32 = 3e-3;9
const CHROMA_WEIGHT: f32 = 2.;10
const MATTE_LOW: f32 = 0.45;11
const MATTE_HIGH: f32 = 0.8;12
const SURE_PERSON: f32 = 0.85;13
const SURE_BACKGROUND: f32 = 0.1;14
const CERTAINTY_RAMP: f32 = 0.05;15
const MAX_BANDS: usize = 4;16
const CHANNELS: usize = 3;17
18
/// Person alpha (0..255) per pixel of a `width` x `height` frame.19
pub struct Matte {20
pub width: usize,21
pub height: usize,22
pub alpha: Vec<u8>,23
}24
25
impl Matte {26
/// Same matte at half resolution, for 4:2:0 chroma planes.27
pub fn halved(&self) -> Matte {28
let (width, height) = (self.width.div_ceil(2), self.height.div_ceil(2));29
let mut alpha = vec![0u8; width * height];30
for (row, line) in alpha.chunks_exact_mut(width).enumerate() {31
let (top, bottom) = (row * 2, (row * 2 + 1).min(self.height - 1));32
for (column, slot) in line.iter_mut().enumerate() {33
let (left, right) = (column * 2, (column * 2 + 1).min(self.width - 1));34
let sum: u32 = [(top, left), (top, right), (bottom, left), (bottom, right)].iter().map(|&(y, x)| u32::from(self.alpha[y * self.width + x])).sum();35
*slot = ((sum + 2) / 4) as u8;36
}37
}38
Matte { width, height, alpha }39
}40
}41
42
/// The 4:2:0 planes of the frame the matte follows.43
#[derive(Clone, Copy)]44
pub struct Planes<'a> {45
pub luma: &'a [u8],46
pub luma_stride: usize,47
pub blue: &'a [u8],48
pub blue_stride: usize,49
pub red: &'a [u8],50
pub red_stride: usize,51
pub width: usize,52
pub height: usize,53
}54
55
impl<'a> Planes<'a> {56
pub fn of(buffer: &'a I420Buffer) -> Planes<'a> {57
let (luma_stride, blue_stride, red_stride) = buffer.strides();58
let (luma, blue, red) = buffer.data();59
Planes { luma, luma_stride: luma_stride as usize, blue, blue_stride: blue_stride as usize, red, red_stride: red_stride as usize, width: buffer.width() as usize, height: buffer.height() as usize }60
}61
62
fn pixel(&self, column: usize, row: usize) -> [f32; CHANNELS] {63
let chroma = |plane: &[u8], stride: usize| (f32::from(plane[row / 2 * stride + column / 2]) - 128.) * CHROMA_WEIGHT / 255.;64
[f32::from(self.luma[row * self.luma_stride + column]) / 255., chroma(self.blue, self.blue_stride), chroma(self.red, self.red_stride)]65
}66
}67
68
fn ramp(value: f32, start: f32) -> f32 {69
((value - start) / CERTAINTY_RAMP).clamp(0., 1.)70
}71
72
fn edge_curve(value: f32) -> f32 {73
let t = ((value - MATTE_LOW) / (MATTE_HIGH - MATTE_LOW)).clamp(0., 1.);74
t * t * (3. - 2. * t)75
}76
77
fn box_filter(input: &[f32], width: usize, height: usize, radius: usize) -> Vec<f32> {78
let mut across = vec![0f32; input.len()];79
let mut prefix = vec![0f32; width + 1];80
for (line, output) in input.chunks_exact(width).zip(across.chunks_exact_mut(width)) {81
for (index, &value) in line.iter().enumerate() {82
prefix[index + 1] = prefix[index] + value;83
}84
for (index, slot) in output.iter_mut().enumerate() {85
let (low, high) = (index.saturating_sub(radius), (index + radius + 1).min(width));86
*slot = (prefix[high] - prefix[low]) / (high - low) as f32;87
}88
}89
let mut output = vec![0f32; input.len()];90
let mut sums = vec![0f32; width];91
for line in across.chunks_exact(width).take(radius.min(height)) {92
sums.iter_mut().zip(line).for_each(|(sum, value)| *sum += value);93
}94
for row in 0..height {95
if row + radius < height {96
sums.iter_mut().zip(&across[(row + radius) * width..][..width]).for_each(|(sum, value)| *sum += value);97
}98
if row > radius {99
sums.iter_mut().zip(&across[(row - radius - 1) * width..][..width]).for_each(|(sum, value)| *sum -= value);100
}101
let count = ((row + radius + 1).min(height) - row.saturating_sub(radius)) as f32;102
output[row * width..][..width].iter_mut().zip(&sums).for_each(|(slot, sum)| *slot = sum / count);103
}104
output105
}106
107
fn cell_means(plane: &[u8], stride: usize, subsampling: usize, (plane_width, plane_height): (usize, usize), factor: usize, (small_width, small_height): (usize, usize)) -> Vec<f32> {108
let span = |cell: usize, limit: usize| {109
let first = (cell * factor / subsampling).min(limit - 1);110
first..((cell + 1) * factor).div_ceil(subsampling).clamp(first + 1, limit)111
};112
let columns: Vec<_> = (0..small_width).map(|column| span(column, plane_width)).collect();113
let mut means = Vec::with_capacity(small_width * small_height);114
let mut sums = vec![0u32; plane_width];115
for row in 0..small_height {116
let rows = span(row, plane_height);117
sums.fill(0);118
for line in rows.clone() {119
sums.iter_mut().zip(&plane[line * stride..][..plane_width]).for_each(|(sum, &value)| *sum += u32::from(value));120
}121
for range in &columns {122
means.push(sums[range.clone()].iter().sum::<u32>() as f32 / (rows.len() * range.len()) as f32);123
}124
}125
means126
}127
128
fn small_guide(planes: &Planes, factor: usize) -> ([Vec<f32>; CHANNELS], usize, usize) {129
let small = (planes.width.div_ceil(factor), planes.height.div_ceil(factor));130
let chroma = (planes.width.div_ceil(2), planes.height.div_ceil(2));131
let luma = cell_means(planes.luma, planes.luma_stride, 1, (planes.width, planes.height), factor, small).into_iter().map(|value| value / 255.).collect();132
let colour = |plane: &[u8], stride: usize| cell_means(plane, stride, 2, chroma, factor, small).into_iter().map(|value| (value - 128.) * CHROMA_WEIGHT / 255.).collect();133
([luma, colour(planes.blue, planes.blue_stride), colour(planes.red, planes.red_stride)], small.0, small.1)134
}135
136
fn small_mask(mask: &[f32], width: usize, height: usize) -> Vec<f32> {137
let (mask_x, mask_y) = (axis(width, MASK_WIDTH), axis(height, MASK_HEIGHT));138
let mut small = Vec::with_capacity(width * height);139
for row in 0..height {140
let (top, bottom, down) = (mask_y.first[row] * MASK_WIDTH, mask_y.second[row] * MASK_WIDTH, mask_y.weight[row]);141
for column in 0..width {142
let (left, right, across) = (mask_x.first[column], mask_x.second[column], mask_x.weight[column]);143
let upper = mask[top + left] * (1. - across) + mask[top + right] * across;144
let lower = mask[bottom + left] * (1. - across) + mask[bottom + right] * across;145
small.push(upper * (1. - down) + lower * down);146
}147
}148
small149
}150
151
struct Coefficients {152
slope: [Vec<f32>; CHANNELS],153
offset: Vec<f32>,154
width: usize,155
}156
157
fn solve(covariance: [[f32; CHANNELS]; CHANNELS], target: [f32; CHANNELS]) -> [f32; CHANNELS] {158
let [[a, b, c], [_, d, e], [_, _, f]] = covariance;159
let cofactors = [[d * f - e * e, c * e - b * f, b * e - c * d], [c * e - b * f, a * f - c * c, b * c - a * e], [b * e - c * d, b * c - a * e, a * d - b * b]];160
let determinant = a * cofactors[0][0] + b * cofactors[0][1] + c * cofactors[0][2];161
std::array::from_fn(|row| (0..CHANNELS).map(|column| cofactors[row][column] * target[column]).sum::<f32>() / determinant)162
}163
164
fn coefficients(guide: &[Vec<f32>; CHANNELS], person: &[f32], width: usize, height: usize) -> Coefficients {165
let mean = |values: Vec<f32>| box_filter(&values, width, height, FILTER_RADIUS);166
let mean_guide: [Vec<f32>; CHANNELS] = std::array::from_fn(|channel| mean(guide[channel].clone()));167
let mean_person = mean(person.to_vec());168
let mean_product: [Vec<f32>; CHANNELS] = std::array::from_fn(|channel| mean(guide[channel].iter().zip(person).map(|(guide, person)| guide * person).collect()));169
let pairs = [(0, 0), (0, 1), (0, 2), (1, 1), (1, 2), (2, 2)];170
let mean_pair: Vec<Vec<f32>> = pairs.iter().map(|&(first, second)| mean(guide[first].iter().zip(&guide[second]).map(|(first, second)| first * second).collect())).collect();171
let mut slope: [Vec<f32>; CHANNELS] = std::array::from_fn(|_| vec![0f32; person.len()]);172
let mut offset = vec![0f32; person.len()];173
for index in 0..person.len() {174
let mut covariance = [[0f32; CHANNELS]; CHANNELS];175
for (&(first, second), pair) in pairs.iter().zip(&mean_pair) {176
let value = pair[index] - mean_guide[first][index] * mean_guide[second][index] + if first == second { FILTER_EPSILON } else { 0. };177
covariance[first][second] = value;178
covariance[second][first] = value;179
}180
let target = std::array::from_fn(|channel| mean_product[channel][index] - mean_guide[channel][index] * mean_person[index]);181
let solution = solve(covariance, target);182
offset[index] = mean_person[index] - (0..CHANNELS).map(|channel| solution[channel] * mean_guide[channel][index]).sum::<f32>();183
for channel in 0..CHANNELS {184
slope[channel][index] = solution[channel];185
}186
}187
Coefficients { slope: slope.map(mean), offset: mean(offset), width }188
}189
190
struct Upsampler<'a> {191
coefficients: &'a Coefficients,192
prior: &'a [f32],193
planes: Planes<'a>,194
across: Axis,195
down: Axis,196
}197
198
impl Upsampler<'_> {199
fn rows(&self, alpha: &mut [u8], first_row: usize) {200
let small_width = self.coefficients.width;201
let mut lines = vec![[0f32; CHANNELS + 2]; small_width];202
for (offset, line) in alpha.chunks_exact_mut(self.planes.width).enumerate() {203
let row = first_row + offset;204
let (top, bottom, vertical) = (self.down.first[row] * small_width, self.down.second[row] * small_width, self.down.weight[row]);205
let blend = |grid: &[f32], column: usize| grid[top + column] * (1. - vertical) + grid[bottom + column] * vertical;206
for (column, slot) in lines.iter_mut().enumerate() {207
*slot = [blend(&self.coefficients.slope[0], column), blend(&self.coefficients.slope[1], column), blend(&self.coefficients.slope[2], column), blend(&self.coefficients.offset, column), blend(self.prior, column)];208
}209
for (column, slot) in line.iter_mut().enumerate() {210
let (left, right, horizontal) = (&lines[self.across.first[column]], &lines[self.across.second[column]], self.across.weight[column]);211
let at = |index: usize| left[index] * (1. - horizontal) + right[index] * horizontal;212
let prior = at(4);213
let (floor, ceiling) = (ramp(prior, SURE_PERSON), ramp(prior, SURE_BACKGROUND - CERTAINTY_RAMP));214
if floor >= 1. || ceiling <= 0. {215
*slot = if floor >= 1. { u8::MAX } else { 0 };216
continue;217
}218
let guide = self.planes.pixel(column, row);219
let person = at(0) * guide[0] + at(1) * guide[1] + at(2) * guide[2] + at(3);220
*slot = (edge_curve(person).max(floor).min(ceiling) * 255. + 0.5) as u8;221
}222
}223
}224
}225
226
/// Snaps the low-resolution `mask` to the colour edges of the full-resolution frame with a fast colour guided filter.227
pub fn refine(mask: &[f32], planes: Planes) -> Matte {228
let (width, height) = (planes.width, planes.height);229
let factor = (width / GUIDE_WIDTH).max(1);230
let (guide, small_width, small_height) = small_guide(&planes, factor);231
let prior = small_mask(mask, small_width, small_height);232
let coefficients = coefficients(&guide, &prior, small_width, small_height);233
let upsampler = Upsampler { coefficients: &coefficients, prior: &prior, planes, across: axis(width, small_width), down: axis(height, small_height) };234
let mut alpha = vec![0u8; width * height];235
let bands = std::thread::available_parallelism().map_or(1, usize::from).min(MAX_BANDS);236
let rows_per_band = height.div_ceil(bands);237
std::thread::scope(|scope| {238
for (index, band) in alpha.chunks_mut(rows_per_band * width).enumerate() {239
let upsampler = &upsampler;240
scope.spawn(move || upsampler.rows(band, index * rows_per_band));241
}242
});243
Matte { width, height, alpha }244
}245
246
pub fn refine_rgba(mask: &[f32], rgba: &[u8], width: usize, height: usize) -> Matte {247
refine(mask, Planes::of(&i420_from_rgba(rgba, width as u32, height as u32)))248
}249
250
#[cfg(test)]251
mod tests {252
use super::*;253
254
const WIDTH: usize = 1280;255
const HEIGHT: usize = 720;256
const LEFT: usize = 403;257
const RIGHT: usize = 877;258
const TOP: usize = 161;259
const BOTTOM: usize = 598;260
const BLOCK: usize = 3;261
262
fn frame(width: usize, height: usize, luma: impl Fn(usize, usize) -> u8) -> I420Buffer {263
let mut buffer = I420Buffer::new(width as u32, height as u32);264
let stride = buffer.strides().0 as usize;265
let (plane_y, plane_u, plane_v) = buffer.data_mut();266
for row in 0..height {267
for column in 0..width {268
plane_y[row * stride + column] = luma(column, row);269
}270
}271
plane_u.fill(128);272
plane_v.fill(128);273
buffer274
}275
276
fn square_frame() -> I420Buffer {277
frame(WIDTH, HEIGHT, |column, row| if (LEFT..RIGHT).contains(&column) && (TOP..BOTTOM).contains(&row) { 200 } else { 50 })278
}279
280
fn blocky_mask() -> Vec<f32> {281
(0..MASK_WIDTH * MASK_HEIGHT)282
.map(|index| {283
let (block_column, block_row) = ((index % MASK_WIDTH) / BLOCK * BLOCK, (index / MASK_WIDTH) / BLOCK * BLOCK);284
let center_x = (block_column as f32 + BLOCK as f32 / 2.) * WIDTH as f32 / MASK_WIDTH as f32;285
let center_y = (block_row as f32 + BLOCK as f32 / 2.) * HEIGHT as f32 / MASK_HEIGHT as f32;286
let inside = (LEFT as f32..RIGHT as f32).contains(¢er_x) && (TOP as f32..BOTTOM as f32).contains(¢er_y);287
if inside { 0.9 } else { 0.1 }288
})289
.collect()290
}291
292
fn crossing(values: impl Iterator<Item = u8>) -> Vec<usize> {293
let values: Vec<u8> = values.collect();294
values.windows(2).enumerate().filter(|(_, pair)| (pair[0] < 128) != (pair[1] < 128)).map(|(index, _)| index + 1).collect()295
}296
297
#[test]298
fn a_blocky_mask_snaps_to_the_sharp_edge_of_the_frame() {299
let matte = refine(&blocky_mask(), Planes::of(&square_frame()));300
for row in [TOP + 40, HEIGHT / 2, BOTTOM - 40] {301
let edges = crossing(matte.alpha[row * WIDTH..][..WIDTH].iter().copied());302
assert_eq!(edges.len(), 2, "row {row}: {edges:?}");303
assert!(edges[0].abs_diff(LEFT) <= 2 && edges[1].abs_diff(RIGHT) <= 2, "row {row}: {edges:?}");304
}305
for column in [LEFT + 40, WIDTH / 2, RIGHT - 40] {306
let edges = crossing((0..HEIGHT).map(|row| matte.alpha[row * WIDTH + column]));307
assert!(edges.len() == 2 && edges[0].abs_diff(TOP) <= 2 && edges[1].abs_diff(BOTTOM) <= 2, "column {column}: {edges:?}");308
}309
}310
311
#[test]312
fn a_colour_edge_without_a_brightness_step_still_guides_the_matte() {313
let mut colour = frame(WIDTH, HEIGHT, |_, _| 120);314
let stride = colour.strides().1 as usize;315
let blue = colour.data_mut().1;316
for row in 0..HEIGHT / 2 {317
for column in 0..WIDTH / 2 {318
let inside = (LEFT / 2..RIGHT / 2).contains(&column) && (TOP / 2..BOTTOM / 2).contains(&row);319
blue[row * stride + column] = if inside { 170 } else { 90 };320
}321
}322
let matte = refine(&blocky_mask(), Planes::of(&colour));323
let edges = crossing(matte.alpha[HEIGHT / 2 * WIDTH..][..WIDTH].iter().copied());324
assert!(edges.len() == 2 && edges[0].abs_diff(LEFT) <= 2 && edges[1].abs_diff(RIGHT) <= 2, "{edges:?}");325
}326
327
#[test]328
fn no_background_shows_outside_the_true_edge() {329
let matte = refine(&blocky_mask(), Planes::of(&square_frame()));330
let line = &matte.alpha[HEIGHT / 2 * WIDTH..][..WIDTH];331
assert!(line[..LEFT - 1].iter().chain(&line[RIGHT + 1..]).all(|&alpha| alpha == 0), "{:?} {:?}", &line[LEFT - 8..LEFT + 2], &line[RIGHT - 2..RIGHT + 8]);332
assert!(line[LEFT + 1..RIGHT - 1].iter().all(|&alpha| alpha > 128), "{:?}", &line[RIGHT - 16..RIGHT]);333
}334
335
#[test]336
fn flat_regions_keep_the_mask_and_halving_averages() {337
let flat = frame(64, 36, |_, _| 120);338
let everyone = refine(&vec![1.; MASK_WIDTH * MASK_HEIGHT], Planes::of(&flat));339
assert!(everyone.alpha.iter().all(|&alpha| alpha == 255));340
let nobody = refine(&vec![0.; MASK_WIDTH * MASK_HEIGHT], Planes::of(&flat));341
assert!(nobody.alpha.iter().all(|&alpha| alpha == 0));342
let halved = Matte { width: 3, height: 2, alpha: vec![0, 255, 255, 0, 255, 255] }.halved();343
assert_eq!((halved.width, halved.height, halved.alpha), (2, 1, vec![128, 255]));344
}345
346
#[test]347
fn the_box_filter_averages_clamped_windows() {348
let filtered = box_filter(&[0., 3., 6., 9.], 4, 1, 1);349
assert_eq!(filtered, vec![1.5, 3., 6., 7.5]);350
let tall = box_filter(&[0., 3., 6., 9.], 1, 4, 1);351
assert_eq!(tall, vec![1.5, 3., 6., 7.5]);352
}353
}@@ -2,7 +2,8 @@ use std::sync::Arc;
2
2
3
3
use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};
4
4
5
use crate::blur::{MASK_HEIGHT, MASK_WIDTH, axis, smoothstep};
5
use crate::blur::{MASK_HEIGHT, MASK_WIDTH, axis};
6
use crate::matte::{Planes, refine};
6
7
use crate::blur::BlurSettings;
7
8
8
9
const CUTOUT_WIDTH: u32 = 480;
@@ -40,8 +41,7 @@ impl Cutout {
40
41
let (width, height) = (width as usize, height as usize);
41
42
let (stride_y, stride_u, stride_v) = scaled.strides();
42
43
let (plane_y, plane_u, plane_v) = scaled.data();
43
let mask_x = axis(width, MASK_WIDTH);
44
let mask_y = axis(height, MASK_HEIGHT);
44
let matte = refine(mask, Planes::of(&scaled));
45
45
let radius = width as f32 * CORNER_SHARE;
46
46
let mut cutout = Cutout {
47
47
width,
@@ -52,12 +52,8 @@ impl Cutout {
52
52
alpha: Vec::with_capacity(width * height),
53
53
};
54
54
for row in 0..height {
55
let (top, bottom, vertical) = (mask_y.first[row] * MASK_WIDTH, mask_y.second[row] * MASK_WIDTH, mask_y.weight[row]);
56
55
for column in 0..width {
57
let (left, right, across) = (mask_x.first[column], mask_x.second[column], mask_x.weight[column]);
58
let upper = mask[top + left] * (1. - across) + mask[top + right] * across;
59
let lower = mask[bottom + left] * (1. - across) + mask[bottom + right] * across;
60
let person = smoothstep(upper * (1. - vertical) + lower * vertical);
56
let person = f32::from(matte.alpha[row * width + column]) / 255.;
61
57
let coverage = person * corner_coverage(column, row, width, height, radius);
62
58
cutout.luma.push(plane_y[row * stride_y as usize + column]);
63
59
cutout.chroma_blue.push(plane_u[(row / 2) * stride_u as usize + column / 2]);
@@ -2,7 +2,8 @@ use std::sync::Arc;2
2
3
use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};3
use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};4
4
5
use crate::blur::{MASK_HEIGHT, MASK_WIDTH, axis, smoothstep};5
use crate::blur::{MASK_HEIGHT, MASK_WIDTH, axis};6
use crate::matte::{Planes, refine};6
use crate::blur::BlurSettings;7
use crate::blur::BlurSettings;7
8
8
const CUTOUT_WIDTH: u32 = 480;9
const CUTOUT_WIDTH: u32 = 480;@@ -40,8 +41,7 @@ impl Cutout {40
let (width, height) = (width as usize, height as usize);41
let (width, height) = (width as usize, height as usize);41
let (stride_y, stride_u, stride_v) = scaled.strides();42
let (stride_y, stride_u, stride_v) = scaled.strides();42
let (plane_y, plane_u, plane_v) = scaled.data();43
let (plane_y, plane_u, plane_v) = scaled.data();43
let mask_x = axis(width, MASK_WIDTH);44
let matte = refine(mask, Planes::of(&scaled));44
let mask_y = axis(height, MASK_HEIGHT);45
let radius = width as f32 * CORNER_SHARE;45
let radius = width as f32 * CORNER_SHARE;46
let mut cutout = Cutout {46
let mut cutout = Cutout {47
width,47
width,@@ -52,12 +52,8 @@ impl Cutout {52
alpha: Vec::with_capacity(width * height),52
alpha: Vec::with_capacity(width * height),53
};53
};54
for row in 0..height {54
for row in 0..height {55
let (top, bottom, vertical) = (mask_y.first[row] * MASK_WIDTH, mask_y.second[row] * MASK_WIDTH, mask_y.weight[row]);56
for column in 0..width {55
for column in 0..width {57
let (left, right, across) = (mask_x.first[column], mask_x.second[column], mask_x.weight[column]);56
let person = f32::from(matte.alpha[row * width + column]) / 255.;58
let upper = mask[top + left] * (1. - across) + mask[top + right] * across;59
let lower = mask[bottom + left] * (1. - across) + mask[bottom + right] * across;60
let person = smoothstep(upper * (1. - vertical) + lower * vertical);61
let coverage = person * corner_coverage(column, row, width, height, radius);57
let coverage = person * corner_coverage(column, row, width, height, radius);62
cutout.luma.push(plane_y[row * stride_y as usize + column]);58
cutout.luma.push(plane_y[row * stride_y as usize + column]);63
cutout.chroma_blue.push(plane_u[(row / 2) * stride_u as usize + column / 2]);59
cutout.chroma_blue.push(plane_u[(row / 2) * stride_u as usize + column / 2]);