BlueGit

ict rusty-teams

Files

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

blur_bench.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
blur_bench.rs 10.7 KiB Download Raw
1use std::sync::Arc;
2use std::time::{Duration, Instant};
3
4use calling::background::BackgroundPicture;
5use calling::blur::{
6 BlurSettings, MaskInference, MaskSource, compose, compose_i420, compose_image,
7};
8use calling::camera::i420_from_rgba;
9use calling::composite::{Backdrop, PicturePlanes, composite};
10use calling::effects::{CameraEffects, EffectsStage};
11use calling::framing::{Crop, crop_and_scale};
12use calling::luma_effects::soften_luma;
13use calling::matte::{Planes, refine};
14use calling::motion::{LumaGrid, propagate};
15use calling::segmentation::FixedSegmenter;
16use calling::segmentation::model::MEDIAPIPE;
17use calling::segmentation::runtime::Device;
18use libwebrtc::native::yuv_helper::i420_to_abgr;
19use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};
20
21const WIDTH: usize = 640;
22const HEIGHT: usize = 360;
23const SEND_WIDTH: u32 = 1280;
24const SEND_HEIGHT: u32 = 720;
25const FRAMES: usize = 200;
26const WARMUP: usize = 10;
27const PACED_WARMUP: usize = 60;
28const FRAME_INTERVAL: Duration = Duration::from_millis(33);
29
30fn synthetic() -> Vec<u8> {
31 (0..WIDTH * HEIGHT * 4)
32 .map(|index| {
33 if index % 4 == 3 {
34 255
35 } else {
36 ((index / 4 % WIDTH + index / 4 / WIDTH) * 255 / (WIDTH + HEIGHT)) as u8
37 }
38 })
39 .collect()
40}
41
42fn send_frame() -> I420Buffer {
43 let mut buffer = I420Buffer::new(SEND_WIDTH, SEND_HEIGHT);
44 let stride = buffer.strides().0 as usize;
45 let (plane_y, plane_u, plane_v) = buffer.data_mut();
46 for (index, value) in plane_y.iter_mut().enumerate() {
47 *value = (((index % stride) + index / stride) * 255
48 / (SEND_WIDTH as usize + SEND_HEIGHT as usize)) as u8;
49 }
50 plane_u.fill(128);
51 plane_v.fill(128);
52 buffer
53}
54
55fn milliseconds_per_frame(started: Instant) -> f64 {
56 started.elapsed().as_secs_f64() * 1000. / FRAMES as f64
57}
58
59fn stage_cost(label: &str, blur: bool, effects: CameraEffects) {
60 let settings = Arc::new(BlurSettings::default());
61 settings.set_enabled(blur);
62 settings.set_effects(effects);
63 let mut stage = EffectsStage::new(settings);
64 let source = send_frame();
65 let run = |stage: &mut EffectsStage| {
66 let mut frame = I420Buffer::new(SEND_WIDTH, SEND_HEIGHT);
67 let (source_y, source_u, source_v) = source.data();
68 let (target_y, target_u, target_v) = frame.data_mut();
69 target_y.copy_from_slice(source_y);
70 target_u.copy_from_slice(source_u);
71 target_v.copy_from_slice(source_v);
72 stage.apply_i420(frame)
73 };
74 for _ in 0..PACED_WARMUP {
75 run(&mut stage);
76 std::thread::sleep(FRAME_INTERVAL);
77 }
78 let mut busy = Duration::ZERO;
79 for _ in 0..FRAMES {
80 let started = Instant::now();
81 run(&mut stage);
82 busy += started.elapsed();
83 std::thread::sleep(FRAME_INTERVAL);
84 }
85 println!(
86 "{label} {SEND_WIDTH}x{SEND_HEIGHT}: {:.2} ms/frame",
87 busy.as_secs_f64() * 1000. / FRAMES as f64
88 );
89}
90
91fn picture_backdrop() -> Arc<BackgroundPicture> {
92 let (width, height) = (64, 36);
93 let rgb = (0..width * height).flat_map(|index| {
94 let (x, y) = (index % width, index / width);
95 [(40 + x * 2) as u8, (90 + y) as u8, (150 + x) as u8]
96 });
97 Arc::new(BackgroundPicture::from_rgb(rgb.collect(), width, height).expect("backdrop"))
98}
99
100fn rgba_of(buffer: &I420Buffer) -> Vec<u8> {
101 let (width, height) = (buffer.width(), buffer.height());
102 let (stride_y, stride_u, stride_v) = buffer.strides();
103 let (plane_y, plane_u, plane_v) = buffer.data();
104 let mut rgba = vec![0u8; (width * height * 4) as usize];
105 i420_to_abgr(
106 plane_y,
107 stride_y,
108 plane_u,
109 stride_u,
110 plane_v,
111 stride_v,
112 &mut rgba,
113 width * 4,
114 width as i32,
115 height as i32,
116 );
117 rgba
118}
119
120fn save_png(path: &str, rgba: Vec<u8>) {
121 image::RgbaImage::from_raw(SEND_WIDTH, SEND_HEIGHT, rgba)
122 .expect("frame size")
123 .save(path)
124 .expect("png written");
125}
126
127fn shots(input: &str, prefix: &str) {
128 let photo = image::open(input)
129 .expect("photo")
130 .resize_to_fill(
131 SEND_WIDTH,
132 SEND_HEIGHT,
133 image::imageops::FilterType::Triangle,
134 )
135 .to_rgba8()
136 .into_raw();
137 let camera = i420_from_rgba(&photo, SEND_WIDTH, SEND_HEIGHT);
138 let mask = FixedSegmenter::new(MEDIAPIPE, Device::Cpu { threads: 1 })
139 .expect("model")
140 .infer(i420_from_rgba(&photo, SEND_WIDTH, SEND_HEIGHT))
141 .expect("mask");
142 let matte = refine(&mask, Planes::of(&camera));
143 image::GrayImage::from_raw(SEND_WIDTH, SEND_HEIGHT, matte.alpha.clone())
144 .expect("matte size")
145 .save(format!("{prefix}-matte.png"))
146 .expect("png written");
147 let mut blurred = i420_from_rgba(&photo, SEND_WIDTH, SEND_HEIGHT);
148 compose_i420(&mut blurred, &mask);
149 save_png(&format!("{prefix}-blur.png"), rgba_of(&blurred));
150 let mut replaced = rgba_of(&camera);
151 let backdrop = PicturePlanes::new(
152 &picture_backdrop().covering(SEND_WIDTH as usize, SEND_HEIGHT as usize),
153 SEND_WIDTH as usize,
154 SEND_HEIGHT as usize,
155 );
156 compose_image(
157 &mut replaced,
158 SEND_WIDTH as usize,
159 SEND_HEIGHT as usize,
160 &matte,
161 &backdrop,
162 );
163 save_png(&format!("{prefix}-picture.png"), replaced);
164}
165
166fn main() {
167 let mut arguments = std::env::args().skip(1).peekable();
168 if arguments
169 .next_if(|argument| argument == "--shots")
170 .is_some()
171 {
172 shots(
173 &arguments.next().expect("photo path"),
174 &arguments.next().expect("output prefix"),
175 );
176 return;
177 }
178 let input = arguments.next();
179 let output = arguments.next();
180 let frame = input.map_or_else(synthetic, |path| {
181 std::fs::read(path).expect("raw rgba 640x360 input")
182 });
183 assert_eq!(
184 frame.len(),
185 WIDTH * HEIGHT * 4,
186 "input must be raw RGBA {WIDTH}x{HEIGHT}"
187 );
188 let mut masks = MaskSource::new().expect("model");
189 let mut segmenter = FixedSegmenter::new(MEDIAPIPE, Device::Cpu { threads: 1 }).expect("model");
190 for _ in 0..WARMUP {
191 masks.refresh(|| i420_from_rgba(&frame, WIDTH as u32, HEIGHT as u32));
192 }
193 let started = Instant::now();
194 for _ in 0..FRAMES {
195 segmenter
196 .infer(i420_from_rgba(&frame, WIDTH as u32, HEIGHT as u32))
197 .expect("mask");
198 }
199 println!(
200 "segmentation only: {:.2} ms/frame",
201 milliseconds_per_frame(started)
202 );
203 let started = Instant::now();
204 let mut result = frame.clone();
205 for _ in 0..FRAMES {
206 result.copy_from_slice(&frame);
207 masks.refresh(|| i420_from_rgba(&frame, WIDTH as u32, HEIGHT as u32));
208 compose(&mut result, WIDTH, HEIGHT, masks.mask());
209 }
210 println!(
211 "segment + blur + compose {WIDTH}x{HEIGHT}: {:.2} ms/frame",
212 milliseconds_per_frame(started)
213 );
214 if let Some(path) = output {
215 std::fs::write(path, &result).expect("output");
216 }
217 let off = CameraEffects::default();
218 let all = CameraEffects {
219 auto_framing: true,
220 adjust_brightness: true,
221 soft_focus: true,
222 ..off
223 };
224 stage_cost(
225 "stage, brightness",
226 false,
227 CameraEffects {
228 adjust_brightness: true,
229 ..off
230 },
231 );
232 stage_cost(
233 "stage, soft focus",
234 false,
235 CameraEffects {
236 soft_focus: true,
237 ..off
238 },
239 );
240 stage_cost(
241 "stage, auto framing",
242 false,
243 CameraEffects {
244 auto_framing: true,
245 ..off
246 },
247 );
248 stage_cost("stage, all three", false, all);
249 stage_cost("stage, all three + blur", true, all);
250 stage_cost("stage, blur only", true, off);
251 let mut frame = send_frame();
252 let stride = frame.strides().0 as usize;
253 let oval = calling::mask::Mask::from_fn(256, 144, |x, y| {
254 if ((x - 0.5) * (x - 0.5)) / 0.04 + ((y - 0.5) * (y - 0.5)) / 0.09 <= 1. {
255 1.
256 } else {
257 0.
258 }
259 });
260 let started = Instant::now();
261 for _ in 0..FRAMES {
262 soften_luma(
263 frame.data_mut().0,
264 stride,
265 SEND_WIDTH as usize,
266 SEND_HEIGHT as usize,
267 &oval,
268 100,
269 );
270 }
271 println!(
272 "soft focus only, oval person {SEND_WIDTH}x{SEND_HEIGHT}: {:.2} ms/frame",
273 milliseconds_per_frame(started)
274 );
275 let started = Instant::now();
276 for _ in 0..FRAMES {
277 std::hint::black_box(refine(&oval, Planes::of(&frame)));
278 }
279 println!(
280 "matte refinement {SEND_WIDTH}x{SEND_HEIGHT}: {:.2} ms/frame",
281 milliseconds_per_frame(started)
282 );
283 let matte = refine(&oval, Planes::of(&frame));
284 let mut target = send_frame();
285 let started = Instant::now();
286 for _ in 0..FRAMES {
287 composite(&mut target, &matte, Backdrop::Blur);
288 }
289 println!(
290 "blur composite only {SEND_WIDTH}x{SEND_HEIGHT}: {:.2} ms/frame",
291 milliseconds_per_frame(started)
292 );
293 let reference = LumaGrid::of(&frame);
294 let started = Instant::now();
295 for _ in 0..FRAMES {
296 std::hint::black_box(propagate(&oval, &reference, &LumaGrid::of(&target)));
297 }
298 println!(
299 "mask propagation (grid + block matching + warp) {SEND_WIDTH}x{SEND_HEIGHT}: {:.2} ms/frame",
300 milliseconds_per_frame(started)
301 );
302 let backdrop = PicturePlanes::new(
303 &picture_backdrop().covering(SEND_WIDTH as usize, SEND_HEIGHT as usize),
304 SEND_WIDTH as usize,
305 SEND_HEIGHT as usize,
306 );
307 let camera = rgba_of(&frame);
308 let mut replaced = camera.clone();
309 let started = Instant::now();
310 for _ in 0..FRAMES {
311 replaced.copy_from_slice(&camera);
312 let matte = refine(&oval, Planes::of(&frame));
313 compose_image(
314 &mut replaced,
315 SEND_WIDTH as usize,
316 SEND_HEIGHT as usize,
317 &matte,
318 &backdrop,
319 );
320 }
321 println!(
322 "picture compose {SEND_WIDTH}x{SEND_HEIGHT}: {:.2} ms/frame",
323 milliseconds_per_frame(started)
324 );
325 let started = Instant::now();
326 for _ in 0..FRAMES {
327 let mut blurred = send_frame();
328 compose_i420(&mut blurred, &oval);
329 }
330 println!(
331 "blur compose i420 {SEND_WIDTH}x{SEND_HEIGHT} (incl. frame fill): {:.2} ms/frame",
332 milliseconds_per_frame(started)
333 );
334 let source = send_frame();
335 let crop = Crop {
336 center_x: 0.5,
337 center_y: 0.5,
338 zoom: 1.6,
339 };
340 let started = Instant::now();
341 for _ in 0..FRAMES {
342 std::hint::black_box(crop_and_scale(&source, &crop));
343 }
344 println!(
345 "crop and scale {SEND_WIDTH}x{SEND_HEIGHT}: {:.2} ms/frame",
346 milliseconds_per_frame(started)
347 );
348}