| 1 | use std::time::Duration; |
| 2 | |
| 3 | use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _}; |
| 4 | |
| 5 | const PERSON_THRESHOLD: f32 = 0.5; |
| 6 | const MIN_REGION_AREA: f32 = 0.02; |
| 7 | const CROP_WIDTH_PER_SUBJECT_WIDTH: f32 = 1.8; |
| 8 | const HEADROOM: f32 = 0.12; |
| 9 | const MIN_ZOOM: f32 = 1.0; |
| 10 | const MAX_ZOOM: f32 = 2.0; |
| 11 | const POSITION_DEADBAND: f32 = 0.06; |
| 12 | const SIZE_DEADBAND: f32 = 0.10; |
| 13 | const PAN_TIME_CONSTANT: f32 = 0.7; |
| 14 | const ZOOM_TIME_CONSTANT: f32 = 1.4; |
| 15 | const PAN_SPEED_CAP: f32 = 0.25; |
| 16 | const ZOOM_SPEED_CAP: f32 = 0.4; |
| 17 | const LOST_HOLD: f32 = 1.5; |
| 18 | const MAX_STEP: f32 = 0.25; |
| 19 | const SETTLED: f32 = 0.001; |
| 20 | const FULL_ZOOM_LIMIT: f32 = 1.001; |
| 21 | const ARRIVED: f32 = 0.01; |
| 22 | |
| 23 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 24 | pub 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)] |
| 33 | pub struct Crop { |
| 34 | pub center_x: f32, |
| 35 | pub center_y: f32, |
| 36 | pub zoom: f32, |
| 37 | } |
| 38 | |
| 39 | pub const FULL_FRAME: Crop = Crop { |
| 40 | center_x: 0.5, |
| 41 | center_y: 0.5, |
| 42 | zoom: MIN_ZOOM, |
| 43 | }; |
| 44 | |
| 45 | pub fn find_subject(mask: &[f32], width: usize, height: usize) -> Option<Subject> { |
| 46 | let mut visited = vec![false; mask.len()]; |
| 47 | let mut stack = Vec::new(); |
| 48 | let mut best: Option<(usize, Subject)> = None; |
| 49 | for start in 0..mask.len() { |
| 50 | if visited[start] || mask[start] < PERSON_THRESHOLD { |
| 51 | continue; |
| 52 | } |
| 53 | visited[start] = true; |
| 54 | stack.push(start); |
| 55 | let (mut area, mut left, mut right, mut top, mut bottom) = |
| 56 | (0usize, width, 0usize, height, 0usize); |
| 57 | while let Some(index) = stack.pop() { |
| 58 | let (x, y) = (index % width, index / width); |
| 59 | area += 1; |
| 60 | (left, right, top, bottom) = (left.min(x), right.max(x), top.min(y), bottom.max(y)); |
| 61 | let neighbors = [ |
| 62 | (x > 0).then(|| index - 1), |
| 63 | (x + 1 < width).then(|| index + 1), |
| 64 | (y > 0).then(|| index - width), |
| 65 | (y + 1 < height).then(|| index + width), |
| 66 | ]; |
| 67 | for next in neighbors.into_iter().flatten() { |
| 68 | if !visited[next] && mask[next] >= PERSON_THRESHOLD { |
| 69 | visited[next] = true; |
| 70 | stack.push(next); |
| 71 | } |
| 72 | } |
| 73 | } |
| 74 | let large_enough = area as f32 >= MIN_REGION_AREA * mask.len() as f32; |
| 75 | if large_enough && best.is_none_or(|(largest, _)| area > largest) { |
| 76 | let subject = Subject { |
| 77 | left: left as f32 / width as f32, |
| 78 | top: top as f32 / height as f32, |
| 79 | right: (right + 1) as f32 / width as f32, |
| 80 | bottom: (bottom + 1) as f32 / height as f32, |
| 81 | }; |
| 82 | best = Some((area, subject)); |
| 83 | } |
| 84 | } |
| 85 | best.map(|(_, subject)| subject) |
| 86 | } |
| 87 | |
| 88 | fn fit_center(center: f32, size: f32) -> f32 { |
| 89 | center.clamp(size / 2., 1. - size / 2.) |
| 90 | } |
| 91 | |
| 92 | pub fn crop_for(subject: &Subject) -> Crop { |
| 93 | let crop_width = (subject.right - subject.left) * CROP_WIDTH_PER_SUBJECT_WIDTH; |
| 94 | let zoom = (1. / crop_width).clamp(MIN_ZOOM, MAX_ZOOM); |
| 95 | let size = 1. / zoom; |
| 96 | let crop_top = subject.top - HEADROOM * size; |
| 97 | Crop { |
| 98 | center_x: fit_center((subject.left + subject.right) / 2., size), |
| 99 | center_y: fit_center(crop_top + size / 2., size), |
| 100 | zoom, |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | fn ease(current: f32, target: f32, time_constant: f32, speed_cap: f32, seconds: f32) -> f32 { |
| 105 | let weight = 1. - (-seconds / time_constant).exp(); |
| 106 | let cap = speed_cap * seconds; |
| 107 | let remaining = target - current; |
| 108 | if remaining.abs() < SETTLED { |
| 109 | return target; |
| 110 | } |
| 111 | current + (remaining * weight).clamp(-cap, cap) |
| 112 | } |
| 113 | |
| 114 | pub fn step_crop(current: Crop, target: Crop, seconds: f32, deadband: bool) -> Crop { |
| 115 | let current_size = 1. / current.zoom; |
| 116 | let offset = (target.center_x - current.center_x) |
| 117 | .abs() |
| 118 | .max((target.center_y - current.center_y).abs()); |
| 119 | let resize = (1. / target.zoom - current_size).abs(); |
| 120 | let pans = !deadband || offset / current_size > POSITION_DEADBAND; |
| 121 | let zooms = !deadband || resize / current_size > SIZE_DEADBAND; |
| 122 | let zoom = if zooms { |
| 123 | ease( |
| 124 | current.zoom, |
| 125 | target.zoom, |
| 126 | ZOOM_TIME_CONSTANT, |
| 127 | ZOOM_SPEED_CAP, |
| 128 | seconds, |
| 129 | ) |
| 130 | } else { |
| 131 | current.zoom |
| 132 | }; |
| 133 | let size = 1. / zoom; |
| 134 | let (center_x, center_y) = if pans { |
| 135 | ( |
| 136 | ease( |
| 137 | current.center_x, |
| 138 | target.center_x, |
| 139 | PAN_TIME_CONSTANT, |
| 140 | PAN_SPEED_CAP, |
| 141 | seconds, |
| 142 | ), |
| 143 | ease( |
| 144 | current.center_y, |
| 145 | target.center_y, |
| 146 | PAN_TIME_CONSTANT, |
| 147 | PAN_SPEED_CAP, |
| 148 | seconds, |
| 149 | ), |
| 150 | ) |
| 151 | } else { |
| 152 | (current.center_x, current.center_y) |
| 153 | }; |
| 154 | Crop { |
| 155 | center_x: fit_center(center_x, size), |
| 156 | center_y: fit_center(center_y, size), |
| 157 | zoom, |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | pub struct CropPlanner { |
| 162 | crop: Crop, |
| 163 | lost_seconds: f32, |
| 164 | moving: bool, |
| 165 | } |
| 166 | |
| 167 | impl Default for CropPlanner { |
| 168 | fn default() -> Self { |
| 169 | CropPlanner { |
| 170 | crop: FULL_FRAME, |
| 171 | lost_seconds: 0., |
| 172 | moving: false, |
| 173 | } |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | fn settled(current: &Crop, target: &Crop) -> bool { |
| 178 | let size = 1. / current.zoom; |
| 179 | let offset = (target.center_x - current.center_x) |
| 180 | .abs() |
| 181 | .max((target.center_y - current.center_y).abs()); |
| 182 | offset / size < ARRIVED && (1. / target.zoom - size).abs() / size < ARRIVED |
| 183 | } |
| 184 | |
| 185 | impl CropPlanner { |
| 186 | pub fn advance(&mut self, subject: Option<&Subject>, elapsed: Duration) -> Crop { |
| 187 | let seconds = elapsed.as_secs_f32().min(MAX_STEP); |
| 188 | match subject { |
| 189 | Some(subject) => { |
| 190 | self.lost_seconds = 0.; |
| 191 | let target = crop_for(subject); |
| 192 | let next = step_crop(self.crop, target, seconds, !self.moving); |
| 193 | self.moving = next != self.crop && !settled(&next, &target); |
| 194 | self.crop = next; |
| 195 | } |
| 196 | None => { |
| 197 | self.lost_seconds += seconds; |
| 198 | if self.lost_seconds >= LOST_HOLD { |
| 199 | self.crop = step_crop(self.crop, FULL_FRAME, seconds, false); |
| 200 | } |
| 201 | } |
| 202 | } |
| 203 | self.crop |
| 204 | } |
| 205 | |
| 206 | pub fn reset(&mut self) { |
| 207 | *self = CropPlanner::default(); |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | pub fn is_full_frame(crop: &Crop) -> bool { |
| 212 | crop.zoom < FULL_ZOOM_LIMIT |
| 213 | } |
| 214 | |
| 215 | pub fn crop_rectangle(crop: &Crop, width: usize, height: usize) -> (usize, usize, usize, usize) { |
| 216 | let even = |value: f32| (value.round() as usize) & !1; |
| 217 | let crop_width = even(width as f32 / crop.zoom).clamp(2, width); |
| 218 | let crop_height = even(height as f32 / crop.zoom).clamp(2, height); |
| 219 | let left = even(crop.center_x * width as f32 - crop_width as f32 / 2.).min(width - crop_width); |
| 220 | let top = |
| 221 | even(crop.center_y * height as f32 - crop_height as f32 / 2.).min(height - crop_height); |
| 222 | (left, top, crop_width, crop_height) |
| 223 | } |
| 224 | |
| 225 | fn copy_plane( |
| 226 | source: &[u8], |
| 227 | source_stride: usize, |
| 228 | rectangle: (usize, usize, usize, usize), |
| 229 | target: &mut [u8], |
| 230 | target_stride: usize, |
| 231 | ) { |
| 232 | let (left, top, width, height) = rectangle; |
| 233 | for row in 0..height { |
| 234 | target[row * target_stride..][..width] |
| 235 | .copy_from_slice(&source[(top + row) * source_stride + left..][..width]); |
| 236 | } |
| 237 | } |
| 238 | |
| 239 | pub fn crop_and_scale(buffer: &I420Buffer, crop: &Crop) -> I420Buffer { |
| 240 | let (width, height) = (buffer.width() as usize, buffer.height() as usize); |
| 241 | let (left, top, crop_width, crop_height) = crop_rectangle(crop, width, height); |
| 242 | let mut cropped = I420Buffer::new(crop_width as u32, crop_height as u32); |
| 243 | let (source_strides, target_strides) = (buffer.strides(), cropped.strides()); |
| 244 | let (source_y, source_u, source_v) = buffer.data(); |
| 245 | let (target_y, target_u, target_v) = cropped.data_mut(); |
| 246 | copy_plane( |
| 247 | source_y, |
| 248 | source_strides.0 as usize, |
| 249 | (left, top, crop_width, crop_height), |
| 250 | target_y, |
| 251 | target_strides.0 as usize, |
| 252 | ); |
| 253 | copy_plane( |
| 254 | source_u, |
| 255 | source_strides.1 as usize, |
| 256 | (left / 2, top / 2, crop_width / 2, crop_height / 2), |
| 257 | target_u, |
| 258 | target_strides.1 as usize, |
| 259 | ); |
| 260 | copy_plane( |
| 261 | source_v, |
| 262 | source_strides.2 as usize, |
| 263 | (left / 2, top / 2, crop_width / 2, crop_height / 2), |
| 264 | target_v, |
| 265 | target_strides.2 as usize, |
| 266 | ); |
| 267 | cropped.scale(width as i32, height as i32) |
| 268 | } |
| 269 | |
| 270 | #[cfg(test)] |
| 271 | mod tests { |
| 272 | use super::*; |
| 273 | |
| 274 | const WIDTH: usize = 64; |
| 275 | const HEIGHT: usize = 36; |
| 276 | const FRAME: Duration = Duration::from_millis(33); |
| 277 | |
| 278 | fn mask_with(regions: &[(usize, usize, usize, usize)]) -> Vec<f32> { |
| 279 | let mut mask = vec![0.; WIDTH * HEIGHT]; |
| 280 | for &(left, top, right, bottom) in regions { |
| 281 | for y in top..bottom { |
| 282 | for x in left..right { |
| 283 | mask[y * WIDTH + x] = 0.9; |
| 284 | } |
| 285 | } |
| 286 | } |
| 287 | mask |
| 288 | } |
| 289 | |
| 290 | fn small_person() -> Subject { |
| 291 | Subject { |
| 292 | left: 0.4, |
| 293 | top: 0.3, |
| 294 | right: 0.5, |
| 295 | bottom: 0.7, |
| 296 | } |
| 297 | } |
| 298 | |
| 299 | fn settle(planner: &mut CropPlanner, subject: Option<&Subject>, seconds: u32) -> Crop { |
| 300 | let mut crop = planner.crop; |
| 301 | for _ in 0..seconds * 30 { |
| 302 | crop = planner.advance(subject, FRAME); |
| 303 | } |
| 304 | crop |
| 305 | } |
| 306 | |
| 307 | #[test] |
| 308 | fn the_largest_region_wins_and_small_ones_are_dropped() { |
| 309 | let mask = mask_with(&[(10, 5, 30, 30), (40, 5, 46, 10), (50, 20, 54, 24)]); |
| 310 | let subject = find_subject(&mask, WIDTH, HEIGHT).expect("a person"); |
| 311 | assert_eq!( |
| 312 | subject, |
| 313 | Subject { |
| 314 | left: 10. / 64., |
| 315 | top: 5. / 36., |
| 316 | right: 30. / 64., |
| 317 | bottom: 30. / 36. |
| 318 | } |
| 319 | ); |
| 320 | assert!(find_subject(&mask_with(&[(40, 5, 46, 10)]), WIDTH, HEIGHT).is_none()); |
| 321 | assert!(find_subject(&vec![0.4; WIDTH * HEIGHT], WIDTH, HEIGHT).is_none()); |
| 322 | assert!(find_subject(&vec![0.6; WIDTH * HEIGHT], WIDTH, HEIGHT).is_some()); |
| 323 | assert!(find_subject(&vec![0.; WIDTH * HEIGHT], WIDTH, HEIGHT).is_none()); |
| 324 | } |
| 325 | |
| 326 | #[test] |
| 327 | fn the_target_crop_is_wide_enough_has_headroom_and_stays_in_the_frame() { |
| 328 | let crop = crop_for(&small_person()); |
| 329 | assert_eq!(crop.zoom, 2.); |
| 330 | let size = 1. / crop.zoom; |
| 331 | assert!(crop.center_y - size / 2. <= 0.3 - 0.12 * size + 1e-4); |
| 332 | assert!(crop.center_x - size / 2. >= 0. && crop.center_y + size / 2. <= 1.); |
| 333 | let wide = Subject { |
| 334 | left: 0.1, |
| 335 | top: 0.1, |
| 336 | right: 0.9, |
| 337 | bottom: 0.9, |
| 338 | }; |
| 339 | assert_eq!(crop_for(&wide).zoom, 1.); |
| 340 | let medium = Subject { |
| 341 | left: 0.3, |
| 342 | top: 0.2, |
| 343 | right: 0.7, |
| 344 | bottom: 0.9, |
| 345 | }; |
| 346 | assert!((crop_for(&medium).zoom - 1. / 0.72).abs() < 1e-4); |
| 347 | } |
| 348 | |
| 349 | #[test] |
| 350 | fn the_crop_holds_while_the_target_is_inside_the_deadband() { |
| 351 | let current = Crop { |
| 352 | center_x: 0.5, |
| 353 | center_y: 0.5, |
| 354 | zoom: 1.5, |
| 355 | }; |
| 356 | let size = 1. / current.zoom; |
| 357 | let near = Crop { |
| 358 | center_x: 0.5 + 0.05 * size, |
| 359 | center_y: 0.5, |
| 360 | zoom: 1. / (size * 1.09), |
| 361 | }; |
| 362 | assert_eq!(step_crop(current, near, 0.033, true), current); |
| 363 | let far = Crop { |
| 364 | center_x: 0.5 + 0.2 * size, |
| 365 | ..current |
| 366 | }; |
| 367 | assert!(step_crop(current, far, 0.033, true).center_x > current.center_x); |
| 368 | let bigger = Crop { |
| 369 | zoom: 1. / (size * 1.2), |
| 370 | ..current |
| 371 | }; |
| 372 | assert!(step_crop(current, bigger, 0.033, true).zoom < current.zoom); |
| 373 | } |
| 374 | |
| 375 | #[test] |
| 376 | fn smoothing_converges_on_the_target_without_overshoot() { |
| 377 | let mut planner = CropPlanner::default(); |
| 378 | let target = crop_for(&small_person()); |
| 379 | let crop = settle(&mut planner, Some(&small_person()), 20); |
| 380 | assert!(settled(&crop, &target)); |
| 381 | assert!(crop.zoom <= MAX_ZOOM && crop.zoom >= MIN_ZOOM); |
| 382 | } |
| 383 | |
| 384 | #[test] |
| 385 | fn panning_never_exceeds_the_speed_cap() { |
| 386 | let current = Crop { |
| 387 | center_x: 0.3, |
| 388 | center_y: 0.5, |
| 389 | zoom: 2., |
| 390 | }; |
| 391 | let target = Crop { |
| 392 | center_x: 0.7, |
| 393 | center_y: 0.5, |
| 394 | zoom: 2., |
| 395 | }; |
| 396 | let moved = step_crop(current, target, 0.1, true); |
| 397 | assert!((moved.center_x - current.center_x) <= PAN_SPEED_CAP * 0.1 + 1e-6); |
| 398 | assert!(moved.center_x > current.center_x); |
| 399 | let zoomed = step_crop( |
| 400 | FULL_FRAME, |
| 401 | Crop { |
| 402 | zoom: 2., |
| 403 | ..FULL_FRAME |
| 404 | }, |
| 405 | 0.5, |
| 406 | true, |
| 407 | ); |
| 408 | assert!(zoomed.zoom - 1. <= ZOOM_SPEED_CAP * 0.5 + 1e-6); |
| 409 | } |
| 410 | |
| 411 | #[test] |
| 412 | fn a_lost_subject_is_held_then_eased_out_to_the_full_frame() { |
| 413 | let mut planner = CropPlanner::default(); |
| 414 | let zoomed = settle(&mut planner, Some(&small_person()), 20); |
| 415 | assert!(zoomed.zoom > 1.5); |
| 416 | let held = settle(&mut planner, None, 1); |
| 417 | assert_eq!(held, zoomed); |
| 418 | let easing = settle(&mut planner, None, 2); |
| 419 | assert!(easing.zoom < zoomed.zoom); |
| 420 | let full = settle(&mut planner, None, 10); |
| 421 | assert_eq!(full, FULL_FRAME); |
| 422 | planner.advance(Some(&small_person()), FRAME); |
| 423 | assert_eq!(planner.lost_seconds, 0.); |
| 424 | } |
| 425 | |
| 426 | #[test] |
| 427 | fn the_crop_rectangle_is_even_inside_the_frame_and_scales_back() { |
| 428 | let (left, top, width, height) = crop_rectangle( |
| 429 | &Crop { |
| 430 | center_x: 0.9, |
| 431 | center_y: 0.1, |
| 432 | zoom: 2., |
| 433 | }, |
| 434 | 1280, |
| 435 | 720, |
| 436 | ); |
| 437 | assert_eq!((width, height), (640, 360)); |
| 438 | assert_eq!((left, top), (640, 0)); |
| 439 | assert!(left % 2 == 0 && top % 2 == 0); |
| 440 | assert_eq!(crop_rectangle(&FULL_FRAME, 1280, 720), (0, 0, 1280, 720)); |
| 441 | let buffer = I420Buffer::new(64, 36); |
| 442 | let scaled = crop_and_scale( |
| 443 | &buffer, |
| 444 | &Crop { |
| 445 | center_x: 0.5, |
| 446 | center_y: 0.5, |
| 447 | zoom: 2., |
| 448 | }, |
| 449 | ); |
| 450 | assert_eq!((scaled.width(), scaled.height()), (64, 36)); |
| 451 | } |
| 452 | } |