BlueGit

ict rusty-teams

Files

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

framing.rs

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