BlueGit

ict rusty-teams

Files

rusty-teams / crates / calling / examples / blur_bench.rs

blur_bench.rs

blur_bench.rs 9.4 KiB Download Raw
1use std::sync::Arc;
2use std::time::{Duration, Instant};
3
4use calling::camera::i420_from_rgba;
5use calling::background::BackgroundPicture;
6use calling::composite::{Backdrop, PicturePlanes, composite};
7use calling::motion::{LumaGrid, propagate};
8use calling::blur::{BlurSettings, MaskInference, MaskSource, compose, compose_i420, compose_image};
9use calling::segmentation::FixedSegmenter;
10use calling::segmentation::model::MEDIAPIPE;
11use calling::segmentation::runtime::Device;
12use calling::effects::{CameraEffects, EffectsStage};
13use calling::framing::{Crop, crop_and_scale};
14use calling::luma_effects::soften_luma;
15use calling::matte::{Planes, refine};
16use libwebrtc::native::yuv_helper::i420_to_abgr;
17use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};
18
19const WIDTH: usize = 640;
20const HEIGHT: usize = 360;
21const SEND_WIDTH: u32 = 1280;
22const SEND_HEIGHT: u32 = 720;
23const FRAMES: usize = 200;
24const WARMUP: usize = 10;
25const PACED_WARMUP: usize = 60;
26const FRAME_INTERVAL: Duration = Duration::from_millis(33);
27
28fn synthetic() -> Vec<u8> {
29 (0..WIDTH * HEIGHT * 4).map(|index| if index % 4 == 3 { 255 } else { ((index / 4 % WIDTH + index / 4 / WIDTH) * 255 / (WIDTH + HEIGHT)) as u8 }).collect()
30}
31
32fn send_frame() -> I420Buffer {
33 let mut buffer = I420Buffer::new(SEND_WIDTH, SEND_HEIGHT);
34 let stride = buffer.strides().0 as usize;
35 let (plane_y, plane_u, plane_v) = buffer.data_mut();
36 for (index, value) in plane_y.iter_mut().enumerate() {
37 *value = (((index % stride) + index / stride) * 255 / (SEND_WIDTH as usize + SEND_HEIGHT as usize)) as u8;
38 }
39 plane_u.fill(128);
40 plane_v.fill(128);
41 buffer
42}
43
44fn milliseconds_per_frame(started: Instant) -> f64 {
45 started.elapsed().as_secs_f64() * 1000. / FRAMES as f64
46}
47
48fn stage_cost(label: &str, blur: bool, effects: CameraEffects) {
49 let settings = Arc::new(BlurSettings::default());
50 settings.set_enabled(blur);
51 settings.set_effects(effects);
52 let mut stage = EffectsStage::new(settings);
53 let source = send_frame();
54 let run = |stage: &mut EffectsStage| {
55 let mut frame = I420Buffer::new(SEND_WIDTH, SEND_HEIGHT);
56 let (source_y, source_u, source_v) = source.data();
57 let (target_y, target_u, target_v) = frame.data_mut();
58 target_y.copy_from_slice(source_y);
59 target_u.copy_from_slice(source_u);
60 target_v.copy_from_slice(source_v);
61 stage.apply_i420(frame)
62 };
63 for _ in 0..PACED_WARMUP {
64 run(&mut stage);
65 std::thread::sleep(FRAME_INTERVAL);
66 }
67 let mut busy = Duration::ZERO;
68 for _ in 0..FRAMES {
69 let started = Instant::now();
70 run(&mut stage);
71 busy += started.elapsed();
72 std::thread::sleep(FRAME_INTERVAL);
73 }
74 println!("{label} {SEND_WIDTH}x{SEND_HEIGHT}: {:.2} ms/frame", busy.as_secs_f64() * 1000. / FRAMES as f64);
75}
76
77fn picture_backdrop() -> Arc<BackgroundPicture> {
78 let (width, height) = (64, 36);
79 let rgb = (0..width * height).flat_map(|index| {
80 let (x, y) = (index % width, index / width);
81 [(40 + x * 2) as u8, (90 + y) as u8, (150 + x) as u8]
82 });
83 Arc::new(BackgroundPicture::from_rgb(rgb.collect(), width, height).expect("backdrop"))
84}
85
86fn rgba_of(buffer: &I420Buffer) -> Vec<u8> {
87 let (width, height) = (buffer.width(), buffer.height());
88 let (stride_y, stride_u, stride_v) = buffer.strides();
89 let (plane_y, plane_u, plane_v) = buffer.data();
90 let mut rgba = vec![0u8; (width * height * 4) as usize];
91 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);
92 rgba
93}
94
95fn save_png(path: &str, rgba: Vec<u8>) {
96 image::RgbaImage::from_raw(SEND_WIDTH, SEND_HEIGHT, rgba).expect("frame size").save(path).expect("png written");
97}
98
99fn shots(input: &str, prefix: &str) {
100 let photo = image::open(input).expect("photo").resize_to_fill(SEND_WIDTH, SEND_HEIGHT, image::imageops::FilterType::Triangle).to_rgba8().into_raw();
101 let camera = i420_from_rgba(&photo, SEND_WIDTH, SEND_HEIGHT);
102 let mask = FixedSegmenter::new(MEDIAPIPE, Device::Cpu { threads: 1 }).expect("model").infer(i420_from_rgba(&photo, SEND_WIDTH, SEND_HEIGHT)).expect("mask");
103 let matte = refine(&mask, Planes::of(&camera));
104 image::GrayImage::from_raw(SEND_WIDTH, SEND_HEIGHT, matte.alpha.clone()).expect("matte size").save(format!("{prefix}-matte.png")).expect("png written");
105 let mut blurred = i420_from_rgba(&photo, SEND_WIDTH, SEND_HEIGHT);
106 compose_i420(&mut blurred, &mask);
107 save_png(&format!("{prefix}-blur.png"), rgba_of(&blurred));
108 let mut replaced = rgba_of(&camera);
109 let backdrop = PicturePlanes::new(&picture_backdrop().covering(SEND_WIDTH as usize, SEND_HEIGHT as usize), SEND_WIDTH as usize, SEND_HEIGHT as usize);
110 compose_image(&mut replaced, SEND_WIDTH as usize, SEND_HEIGHT as usize, &matte, &backdrop);
111 save_png(&format!("{prefix}-picture.png"), replaced);
112}
113
114fn main() {
115 let mut arguments = std::env::args().skip(1).peekable();
116 if arguments.next_if(|argument| argument == "--shots").is_some() {
117 shots(&arguments.next().expect("photo path"), &arguments.next().expect("output prefix"));
118 return;
119 }
120 let input = arguments.next();
121 let output = arguments.next();
122 let frame = input.map_or_else(synthetic, |path| std::fs::read(path).expect("raw rgba 640x360 input"));
123 assert_eq!(frame.len(), WIDTH * HEIGHT * 4, "input must be raw RGBA {WIDTH}x{HEIGHT}");
124 let mut masks = MaskSource::new().expect("model");
125 let mut segmenter = FixedSegmenter::new(MEDIAPIPE, Device::Cpu { threads: 1 }).expect("model");
126 for _ in 0..WARMUP {
127 masks.refresh(|| i420_from_rgba(&frame, WIDTH as u32, HEIGHT as u32));
128 }
129 let started = Instant::now();
130 for _ in 0..FRAMES {
131 segmenter.infer(i420_from_rgba(&frame, WIDTH as u32, HEIGHT as u32)).expect("mask");
132 }
133 println!("segmentation only: {:.2} ms/frame", milliseconds_per_frame(started));
134 let started = Instant::now();
135 let mut result = frame.clone();
136 for _ in 0..FRAMES {
137 result.copy_from_slice(&frame);
138 masks.refresh(|| i420_from_rgba(&frame, WIDTH as u32, HEIGHT as u32));
139 compose(&mut result, WIDTH, HEIGHT, masks.mask());
140 }
141 println!("segment + blur + compose {WIDTH}x{HEIGHT}: {:.2} ms/frame", milliseconds_per_frame(started));
142 if let Some(path) = output {
143 std::fs::write(path, &result).expect("output");
144 }
145 let off = CameraEffects::default();
146 let all = CameraEffects { auto_framing: true, adjust_brightness: true, soft_focus: true, ..off };
147 stage_cost("stage, brightness", false, CameraEffects { adjust_brightness: true, ..off });
148 stage_cost("stage, soft focus", false, CameraEffects { soft_focus: true, ..off });
149 stage_cost("stage, auto framing", false, CameraEffects { auto_framing: true, ..off });
150 stage_cost("stage, all three", false, all);
151 stage_cost("stage, all three + blur", true, all);
152 stage_cost("stage, blur only", true, off);
153 let mut frame = send_frame();
154 let stride = frame.strides().0 as usize;
155 let oval = calling::mask::Mask::from_fn(256, 144, |x, y| if ((x - 0.5) * (x - 0.5)) / 0.04 + ((y - 0.5) * (y - 0.5)) / 0.09 <= 1. { 1. } else { 0. });
156 let started = Instant::now();
157 for _ in 0..FRAMES {
158 soften_luma(frame.data_mut().0, stride, SEND_WIDTH as usize, SEND_HEIGHT as usize, &oval, 100);
159 }
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 matte = refine(&oval, Planes::of(&frame));
167 let mut target = send_frame();
168 let started = Instant::now();
169 for _ in 0..FRAMES {
170 composite(&mut target, &matte, Backdrop::Blur);
171 }
172 println!("blur composite only {SEND_WIDTH}x{SEND_HEIGHT}: {:.2} ms/frame", milliseconds_per_frame(started));
173 let reference = LumaGrid::of(&frame);
174 let started = Instant::now();
175 for _ in 0..FRAMES {
176 std::hint::black_box(propagate(&oval, &reference, &LumaGrid::of(&target)));
177 }
178 println!("mask propagation (grid + block matching + warp) {SEND_WIDTH}x{SEND_HEIGHT}: {:.2} ms/frame", milliseconds_per_frame(started));
179 let backdrop = PicturePlanes::new(&picture_backdrop().covering(SEND_WIDTH as usize, SEND_HEIGHT as usize), SEND_WIDTH as usize, SEND_HEIGHT as usize);
180 let camera = rgba_of(&frame);
181 let mut replaced = camera.clone();
182 let started = Instant::now();
183 for _ in 0..FRAMES {
184 replaced.copy_from_slice(&camera);
185 let matte = refine(&oval, Planes::of(&frame));
186 compose_image(&mut replaced, SEND_WIDTH as usize, SEND_HEIGHT as usize, &matte, &backdrop);
187 }
188 println!("picture compose {SEND_WIDTH}x{SEND_HEIGHT}: {:.2} ms/frame", milliseconds_per_frame(started));
189 let started = Instant::now();
190 for _ in 0..FRAMES {
191 let mut blurred = send_frame();
192 compose_i420(&mut blurred, &oval);
193 }
194 println!("blur compose i420 {SEND_WIDTH}x{SEND_HEIGHT} (incl. frame fill): {:.2} ms/frame", milliseconds_per_frame(started));
195 let source = send_frame();
196 let crop = Crop { center_x: 0.5, center_y: 0.5, zoom: 1.6 };
197 let started = Instant::now();
198 for _ in 0..FRAMES {
199 std::hint::black_box(crop_and_scale(&source, &crop));
200 }
201 println!("crop and scale {SEND_WIDTH}x{SEND_HEIGHT}: {:.2} ms/frame", milliseconds_per_frame(started));
202}