BlueGit

ict rusty-teams

Files

rusty-teams / crates / calling / src / framing.rs

framing.rs

framing.rs 12.3 KiB Download Raw
1use std::time::Duration;
2
3use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};
4
5const PERSON_THRESHOLD: f32 = 0.5;
6const MIN_REGION_AREA: f32 = 0.02;
7const CROP_WIDTH_PER_SUBJECT_WIDTH: f32 = 1.8;
8const HEADROOM: f32 = 0.12;
9const MIN_ZOOM: f32 = 1.0;
10const MAX_ZOOM: f32 = 2.0;
11const POSITION_DEADBAND: f32 = 0.06;
12const SIZE_DEADBAND: f32 = 0.10;
13const PAN_TIME_CONSTANT: f32 = 0.7;
14const ZOOM_TIME_CONSTANT: f32 = 1.4;
15const PAN_SPEED_CAP: f32 = 0.25;
16const ZOOM_SPEED_CAP: f32 = 0.4;
17const LOST_HOLD: f32 = 1.5;
18const MAX_STEP: f32 = 0.25;
19const SETTLED: f32 = 0.001;
20const FULL_ZOOM_LIMIT: f32 = 1.001;
21
22#[derive(Debug, Clone, Copy, PartialEq)]
23pub struct Subject {
24 pub left: f32,
25 pub top: f32,
26 pub right: f32,
27 pub bottom: f32,
28}
29
30/// The crop is centered at (`center_x`, `center_y`) in frame fractions and keeps the frame's aspect ratio.
31#[derive(Debug, Clone, Copy, PartialEq)]
32pub struct Crop {
33 pub center_x: f32,
34 pub center_y: f32,
35 pub zoom: f32,
36}
37
38pub const FULL_FRAME: Crop = Crop { center_x: 0.5, center_y: 0.5, zoom: MIN_ZOOM };
39
40pub fn find_subject(mask: &[f32], width: usize, height: usize) -> Option<Subject> {
41 let mut visited = vec![false; mask.len()];
42 let mut stack = Vec::new();
43 let mut best: Option<(usize, Subject)> = None;
44 for start in 0..mask.len() {
45 if visited[start] || mask[start] < PERSON_THRESHOLD {
46 continue;
47 }
48 visited[start] = true;
49 stack.push(start);
50 let (mut area, mut left, mut right, mut top, mut bottom) = (0usize, width, 0usize, height, 0usize);
51 while let Some(index) = stack.pop() {
52 let (x, y) = (index % width, index / width);
53 area += 1;
54 (left, right, top, bottom) = (left.min(x), right.max(x), top.min(y), bottom.max(y));
55 let neighbors = [(x > 0).then(|| index - 1), (x + 1 < width).then(|| index + 1), (y > 0).then(|| index - width), (y + 1 < height).then(|| index + width)];
56 for next in neighbors.into_iter().flatten() {
57 if !visited[next] && mask[next] >= PERSON_THRESHOLD {
58 visited[next] = true;
59 stack.push(next);
60 }
61 }
62 }
63 let large_enough = area as f32 >= MIN_REGION_AREA * mask.len() as f32;
64 if large_enough && best.is_none_or(|(largest, _)| area > largest) {
65 let subject = Subject {
66 left: left as f32 / width as f32,
67 top: top as f32 / height as f32,
68 right: (right + 1) as f32 / width as f32,
69 bottom: (bottom + 1) as f32 / height as f32,
70 };
71 best = Some((area, subject));
72 }
73 }
74 best.map(|(_, subject)| subject)
75}
76
77fn fit_center(center: f32, size: f32) -> f32 {
78 center.clamp(size / 2., 1. - size / 2.)
79}
80
81pub fn crop_for(subject: &Subject) -> Crop {
82 let crop_width = (subject.right - subject.left) * CROP_WIDTH_PER_SUBJECT_WIDTH;
83 let zoom = (1. / crop_width).clamp(MIN_ZOOM, MAX_ZOOM);
84 let size = 1. / zoom;
85 let crop_top = subject.top - HEADROOM * size;
86 Crop {
87 center_x: fit_center((subject.left + subject.right) / 2., size),
88 center_y: fit_center(crop_top + size / 2., size),
89 zoom,
90 }
91}
92
93fn ease(current: f32, target: f32, time_constant: f32, speed_cap: f32, seconds: f32) -> f32 {
94 let weight = 1. - (-seconds / time_constant).exp();
95 let cap = speed_cap * seconds;
96 let remaining = target - current;
97 if remaining.abs() < SETTLED {
98 return target;
99 }
100 current + (remaining * weight).clamp(-cap, cap)
101}
102
103pub fn step_crop(current: Crop, target: Crop, seconds: f32, deadband: bool) -> Crop {
104 let current_size = 1. / current.zoom;
105 let offset = (target.center_x - current.center_x).abs().max((target.center_y - current.center_y).abs());
106 let resize = (1. / target.zoom - current_size).abs();
107 let pans = !deadband || offset / current_size > POSITION_DEADBAND;
108 let zooms = !deadband || resize / current_size > SIZE_DEADBAND;
109 let zoom = if zooms { ease(current.zoom, target.zoom, ZOOM_TIME_CONSTANT, ZOOM_SPEED_CAP, seconds) } else { current.zoom };
110 let size = 1. / zoom;
111 let (center_x, center_y) = if pans {
112 (ease(current.center_x, target.center_x, PAN_TIME_CONSTANT, PAN_SPEED_CAP, seconds), ease(current.center_y, target.center_y, PAN_TIME_CONSTANT, PAN_SPEED_CAP, seconds))
113 } else {
114 (current.center_x, current.center_y)
115 };
116 Crop { center_x: fit_center(center_x, size), center_y: fit_center(center_y, size), zoom }
117}
118
119pub struct CropPlanner {
120 crop: Crop,
121 lost_seconds: f32,
122}
123
124impl Default for CropPlanner {
125 fn default() -> Self {
126 CropPlanner { crop: FULL_FRAME, lost_seconds: 0. }
127 }
128}
129
130impl CropPlanner {
131 pub fn advance(&mut self, subject: Option<&Subject>, elapsed: Duration) -> Crop {
132 let seconds = elapsed.as_secs_f32().min(MAX_STEP);
133 match subject {
134 Some(subject) => {
135 self.lost_seconds = 0.;
136 self.crop = step_crop(self.crop, crop_for(subject), seconds, true);
137 }
138 None => {
139 self.lost_seconds += seconds;
140 if self.lost_seconds >= LOST_HOLD {
141 self.crop = step_crop(self.crop, FULL_FRAME, seconds, false);
142 }
143 }
144 }
145 self.crop
146 }
147
148 pub fn reset(&mut self) {
149 *self = CropPlanner::default();
150 }
151}
152
153pub fn is_full_frame(crop: &Crop) -> bool {
154 crop.zoom < FULL_ZOOM_LIMIT
155}
156
157pub fn crop_rectangle(crop: &Crop, width: usize, height: usize) -> (usize, usize, usize, usize) {
158 let even = |value: f32| (value.round() as usize) & !1;
159 let crop_width = even(width as f32 / crop.zoom).clamp(2, width);
160 let crop_height = even(height as f32 / crop.zoom).clamp(2, height);
161 let left = even(crop.center_x * width as f32 - crop_width as f32 / 2.).min(width - crop_width);
162 let top = even(crop.center_y * height as f32 - crop_height as f32 / 2.).min(height - crop_height);
163 (left, top, crop_width, crop_height)
164}
165
166fn copy_plane(source: &[u8], source_stride: usize, rectangle: (usize, usize, usize, usize), target: &mut [u8], target_stride: usize) {
167 let (left, top, width, height) = rectangle;
168 for row in 0..height {
169 target[row * target_stride..][..width].copy_from_slice(&source[(top + row) * source_stride + left..][..width]);
170 }
171}
172
173pub fn crop_and_scale(buffer: &I420Buffer, crop: &Crop) -> I420Buffer {
174 let (width, height) = (buffer.width() as usize, buffer.height() as usize);
175 let (left, top, crop_width, crop_height) = crop_rectangle(crop, width, height);
176 let mut cropped = I420Buffer::new(crop_width as u32, crop_height as u32);
177 let (source_strides, target_strides) = (buffer.strides(), cropped.strides());
178 let (source_y, source_u, source_v) = buffer.data();
179 let (target_y, target_u, target_v) = cropped.data_mut();
180 copy_plane(source_y, source_strides.0 as usize, (left, top, crop_width, crop_height), target_y, target_strides.0 as usize);
181 copy_plane(source_u, source_strides.1 as usize, (left / 2, top / 2, crop_width / 2, crop_height / 2), target_u, target_strides.1 as usize);
182 copy_plane(source_v, source_strides.2 as usize, (left / 2, top / 2, crop_width / 2, crop_height / 2), target_v, target_strides.2 as usize);
183 cropped.scale(width as i32, height as i32)
184}
185
186#[cfg(test)]
187mod tests {
188 use super::*;
189
190 const WIDTH: usize = 64;
191 const HEIGHT: usize = 36;
192 const FRAME: Duration = Duration::from_millis(33);
193
194 fn mask_with(regions: &[(usize, usize, usize, usize)]) -> Vec<f32> {
195 let mut mask = vec![0.; WIDTH * HEIGHT];
196 for &(left, top, right, bottom) in regions {
197 for y in top..bottom {
198 for x in left..right {
199 mask[y * WIDTH + x] = 0.9;
200 }
201 }
202 }
203 mask
204 }
205
206 fn small_person() -> Subject {
207 Subject { left: 0.4, top: 0.3, right: 0.5, bottom: 0.7 }
208 }
209
210 fn settle(planner: &mut CropPlanner, subject: Option<&Subject>, seconds: u32) -> Crop {
211 let mut crop = planner.crop;
212 for _ in 0..seconds * 30 {
213 crop = planner.advance(subject, FRAME);
214 }
215 crop
216 }
217
218 #[test]
219 fn the_largest_region_wins_and_small_ones_are_dropped() {
220 let mask = mask_with(&[(10, 5, 30, 30), (40, 5, 46, 10), (50, 20, 54, 24)]);
221 let subject = find_subject(&mask, WIDTH, HEIGHT).expect("a person");
222 assert_eq!(subject, Subject { left: 10. / 64., top: 5. / 36., right: 30. / 64., bottom: 30. / 36. });
223 assert!(find_subject(&mask_with(&[(40, 5, 46, 10)]), WIDTH, HEIGHT).is_none());
224 assert!(find_subject(&vec![0.4; WIDTH * HEIGHT], WIDTH, HEIGHT).is_none());
225 assert!(find_subject(&vec![0.6; WIDTH * HEIGHT], WIDTH, HEIGHT).is_some());
226 assert!(find_subject(&vec![0.; WIDTH * HEIGHT], WIDTH, HEIGHT).is_none());
227 }
228
229 #[test]
230 fn the_target_crop_is_wide_enough_has_headroom_and_stays_in_the_frame() {
231 let crop = crop_for(&small_person());
232 assert_eq!(crop.zoom, 2.);
233 let size = 1. / crop.zoom;
234 assert!(crop.center_y - size / 2. <= 0.3 - 0.12 * size + 1e-4);
235 assert!(crop.center_x - size / 2. >= 0. && crop.center_y + size / 2. <= 1.);
236 let wide = Subject { left: 0.1, top: 0.1, right: 0.9, bottom: 0.9 };
237 assert_eq!(crop_for(&wide).zoom, 1.);
238 let medium = Subject { left: 0.3, top: 0.2, right: 0.7, bottom: 0.9 };
239 assert!((crop_for(&medium).zoom - 1. / 0.72).abs() < 1e-4);
240 }
241
242 #[test]
243 fn the_crop_holds_while_the_target_is_inside_the_deadband() {
244 let current = Crop { center_x: 0.5, center_y: 0.5, zoom: 1.5 };
245 let size = 1. / current.zoom;
246 let near = Crop { center_x: 0.5 + 0.05 * size, center_y: 0.5, zoom: 1. / (size * 1.09) };
247 assert_eq!(step_crop(current, near, 0.033, true), current);
248 let far = Crop { center_x: 0.5 + 0.2 * size, ..current };
249 assert!(step_crop(current, far, 0.033, true).center_x > current.center_x);
250 let bigger = Crop { zoom: 1. / (size * 1.2), ..current };
251 assert!(step_crop(current, bigger, 0.033, true).zoom < current.zoom);
252 }
253
254 #[test]
255 fn smoothing_converges_on_the_target_without_overshoot() {
256 let mut planner = CropPlanner::default();
257 let target = crop_for(&small_person());
258 let crop = settle(&mut planner, Some(&small_person()), 20);
259 assert!((crop.zoom - target.zoom).abs() < 0.1 * target.zoom);
260 assert!((crop.center_x - target.center_x).abs() <= POSITION_DEADBAND / crop.zoom + 1e-4);
261 assert!(crop.zoom <= MAX_ZOOM && crop.zoom >= MIN_ZOOM);
262 }
263
264 #[test]
265 fn panning_never_exceeds_the_speed_cap() {
266 let current = Crop { center_x: 0.3, center_y: 0.5, zoom: 2. };
267 let target = Crop { center_x: 0.7, center_y: 0.5, zoom: 2. };
268 let moved = step_crop(current, target, 0.1, true);
269 assert!((moved.center_x - current.center_x) <= PAN_SPEED_CAP * 0.1 + 1e-6);
270 assert!(moved.center_x > current.center_x);
271 let zoomed = step_crop(FULL_FRAME, Crop { zoom: 2., ..FULL_FRAME }, 0.5, true);
272 assert!(zoomed.zoom - 1. <= ZOOM_SPEED_CAP * 0.5 + 1e-6);
273 }
274
275 #[test]
276 fn a_lost_subject_is_held_then_eased_out_to_the_full_frame() {
277 let mut planner = CropPlanner::default();
278 let zoomed = settle(&mut planner, Some(&small_person()), 20);
279 assert!(zoomed.zoom > 1.5);
280 let held = settle(&mut planner, None, 1);
281 assert_eq!(held, zoomed);
282 let easing = settle(&mut planner, None, 2);
283 assert!(easing.zoom < zoomed.zoom);
284 let full = settle(&mut planner, None, 10);
285 assert_eq!(full, FULL_FRAME);
286 planner.advance(Some(&small_person()), FRAME);
287 assert_eq!(planner.lost_seconds, 0.);
288 }
289
290 #[test]
291 fn the_crop_rectangle_is_even_inside_the_frame_and_scales_back() {
292 let (left, top, width, height) = crop_rectangle(&Crop { center_x: 0.9, center_y: 0.1, zoom: 2. }, 1280, 720);
293 assert_eq!((width, height), (640, 360));
294 assert_eq!((left, top), (640, 0));
295 assert!(left % 2 == 0 && top % 2 == 0);
296 assert_eq!(crop_rectangle(&FULL_FRAME, 1280, 720), (0, 0, 1280, 720));
297 let buffer = I420Buffer::new(64, 36);
298 let scaled = crop_and_scale(&buffer, &Crop { center_x: 0.5, center_y: 0.5, zoom: 2. });
299 assert_eq!((scaled.width(), scaled.height()), (64, 36));
300 }
301}