BlueGit

ict rusty-teams

Files

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

blur_bench.rs

blur_bench.rs 8.6 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::blur::{BlurSettings, MaskInference, MaskSource, Segmenter, compose, compose_i420, compose_image};
7use calling::effects::{CameraEffects, EffectsStage};
8use calling::framing::{Crop, crop_and_scale};
9use calling::luma_effects::soften_luma;
10use calling::matte::{Planes, refine};
11use libwebrtc::native::yuv_helper::i420_to_abgr;
12use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};
13
14const WIDTH: usize = 640;
15const HEIGHT: usize = 360;
16const SEND_WIDTH: u32 = 1280;
17const SEND_HEIGHT: u32 = 720;
18const FRAMES: usize = 200;
19const WARMUP: usize = 10;
20const PACED_WARMUP: usize = 60;
21const FRAME_INTERVAL: Duration = Duration::from_millis(33);
22
23fn synthetic() -> Vec<u8> {
24 (0..WIDTH * HEIGHT * 4).map(|index| if index % 4 == 3 { 255 } else { ((index / 4 % WIDTH + index / 4 / WIDTH) * 255 / (WIDTH + HEIGHT)) as u8 }).collect()
25}
26
27fn send_frame() -> I420Buffer {
28 let mut buffer = I420Buffer::new(SEND_WIDTH, SEND_HEIGHT);
29 let stride = buffer.strides().0 as usize;
30 let (plane_y, plane_u, plane_v) = buffer.data_mut();
31 for (index, value) in plane_y.iter_mut().enumerate() {
32 *value = (((index % stride) + index / stride) * 255 / (SEND_WIDTH as usize + SEND_HEIGHT as usize)) as u8;
33 }
34 plane_u.fill(128);
35 plane_v.fill(128);
36 buffer
37}
38
39fn milliseconds_per_frame(started: Instant) -> f64 {
40 started.elapsed().as_secs_f64() * 1000. / FRAMES as f64
41}
42
43fn stage_cost(label: &str, blur: bool, effects: CameraEffects) {
44 let settings = Arc::new(BlurSettings::default());
45 settings.set_enabled(blur);
46 settings.set_effects(effects);
47 let mut stage = EffectsStage::new(settings);
48 let source = send_frame();
49 let run = |stage: &mut EffectsStage| {
50 let mut frame = I420Buffer::new(SEND_WIDTH, SEND_HEIGHT);
51 let (source_y, source_u, source_v) = source.data();
52 let (target_y, target_u, target_v) = frame.data_mut();
53 target_y.copy_from_slice(source_y);
54 target_u.copy_from_slice(source_u);
55 target_v.copy_from_slice(source_v);
56 stage.apply_i420(frame)
57 };
58 for _ in 0..PACED_WARMUP {
59 run(&mut stage);
60 std::thread::sleep(FRAME_INTERVAL);
61 }
62 let mut busy = Duration::ZERO;
63 for _ in 0..FRAMES {
64 let started = Instant::now();
65 run(&mut stage);
66 busy += started.elapsed();
67 std::thread::sleep(FRAME_INTERVAL);
68 }
69 println!("{label} {SEND_WIDTH}x{SEND_HEIGHT}: {:.2} ms/frame", busy.as_secs_f64() * 1000. / FRAMES as f64);
70}
71
72fn 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
81fn 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
90fn 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
94fn 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
109fn main() {
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 }
115 let input = arguments.next();
116 let output = arguments.next();
117 let frame = input.map_or_else(synthetic, |path| std::fs::read(path).expect("raw rgba 640x360 input"));
118 assert_eq!(frame.len(), WIDTH * HEIGHT * 4, "input must be raw RGBA {WIDTH}x{HEIGHT}");
119 let mut masks = MaskSource::new().expect("model");
120 let segmenter = Segmenter::new().expect("model");
121 for _ in 0..WARMUP {
122 masks.refresh(|| i420_from_rgba(&frame, WIDTH as u32, HEIGHT as u32));
123 }
124 let started = Instant::now();
125 for _ in 0..FRAMES {
126 segmenter.mask(&frame, WIDTH, HEIGHT).expect("mask");
127 }
128 println!("segmentation only: {:.2} ms/frame", milliseconds_per_frame(started));
129 let started = Instant::now();
130 let mut result = frame.clone();
131 for _ in 0..FRAMES {
132 result.copy_from_slice(&frame);
133 masks.refresh(|| i420_from_rgba(&frame, WIDTH as u32, HEIGHT as u32));
134 compose(&mut result, WIDTH, HEIGHT, masks.mask());
135 }
136 println!("segment + blur + compose {WIDTH}x{HEIGHT}: {:.2} ms/frame", milliseconds_per_frame(started));
137 if let Some(path) = output {
138 std::fs::write(path, &result).expect("output");
139 }
140 let off = CameraEffects::default();
141 let all = CameraEffects { auto_framing: true, adjust_brightness: true, soft_focus: true, ..off };
142 stage_cost("stage, brightness", false, CameraEffects { adjust_brightness: true, ..off });
143 stage_cost("stage, soft focus", false, CameraEffects { soft_focus: true, ..off });
144 stage_cost("stage, auto framing", false, CameraEffects { auto_framing: true, ..off });
145 stage_cost("stage, all three", false, all);
146 stage_cost("stage, all three + blur", true, all);
147 stage_cost("stage, blur only", true, off);
148 let mut frame = send_frame();
149 let stride = frame.strides().0 as usize;
150 let oval: Vec<f32> = (0..calling::blur::MASK_WIDTH * calling::blur::MASK_HEIGHT)
151 .map(|index| {
152 let (x, y) = ((index % calling::blur::MASK_WIDTH) as f32 / calling::blur::MASK_WIDTH as f32 - 0.5, (index / calling::blur::MASK_WIDTH) as f32 / calling::blur::MASK_HEIGHT as f32 - 0.5);
153 if (x * x) / 0.04 + (y * y) / 0.09 <= 1. { 1. } else { 0. }
154 })
155 .collect();
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 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));
182 let source = send_frame();
183 let crop = Crop { center_x: 0.5, center_y: 0.5, zoom: 1.6 };
184 let started = Instant::now();
185 for _ in 0..FRAMES {
186 std::hint::black_box(crop_and_scale(&source, &crop));
187 }
188 println!("crop and scale {SEND_WIDTH}x{SEND_HEIGHT}: {:.2} ms/frame", milliseconds_per_frame(started));
189}