BlueGit

ict rusty-teams

Files

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

blur_bench.rs

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