| 1 | use std::collections::HashMap; |
| 2 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 3 | use std::sync::{Arc, Mutex}; |
| 4 | use std::time::{Duration, Instant}; |
| 5 | |
| 6 | use libwebrtc::video_frame::{ |
| 7 | BoxVideoBuffer, BoxVideoFrame, I420Buffer, VideoBuffer, VideoFormatType, |
| 8 | }; |
| 9 | use tokio::sync::mpsc::UnboundedSender; |
| 10 | |
| 11 | use crate::control::CallUpdate; |
| 12 | |
| 13 | pub const PERSON_FPS: u32 = 30; |
| 14 | pub const SCREEN_FPS: u32 = 15; |
| 15 | pub const PERSON_MAX_WIDTH: u32 = 640; |
| 16 | pub const SCREEN_MAX_WIDTH: u32 = 2560; |
| 17 | const BYTES_PER_PIXEL: usize = 4; |
| 18 | |
| 19 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] |
| 20 | pub enum VideoKey { |
| 21 | Person(String), |
| 22 | Screen, |
| 23 | LocalCamera, |
| 24 | LocalScreen, |
| 25 | } |
| 26 | |
| 27 | impl VideoKey { |
| 28 | pub fn max_width(&self) -> u32 { |
| 29 | match self { |
| 30 | VideoKey::Screen | VideoKey::LocalScreen => SCREEN_MAX_WIDTH, |
| 31 | VideoKey::Person(_) | VideoKey::LocalCamera => PERSON_MAX_WIDTH, |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | pub fn max_fps(&self) -> u32 { |
| 36 | match self { |
| 37 | VideoKey::Screen | VideoKey::LocalScreen => SCREEN_FPS, |
| 38 | VideoKey::Person(_) | VideoKey::LocalCamera => PERSON_FPS, |
| 39 | } |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | /// BGRA, tightly packed, the byte order the GPU atlas of the UI expects. |
| 44 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 45 | pub struct VideoPicture { |
| 46 | pub width: u32, |
| 47 | pub height: u32, |
| 48 | pub bgra: Vec<u8>, |
| 49 | } |
| 50 | |
| 51 | impl VideoPicture { |
| 52 | pub fn flip_horizontally(&mut self) { |
| 53 | for row in self |
| 54 | .bgra |
| 55 | .chunks_exact_mut(self.width as usize * BYTES_PER_PIXEL) |
| 56 | { |
| 57 | let (pixels, _) = row.as_chunks_mut::<BYTES_PER_PIXEL>(); |
| 58 | pixels.reverse(); |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | pub fn solid(width: u32, height: u32, blue: u8, green: u8, red: u8) -> Self { |
| 63 | let pixel = [blue, green, red, u8::MAX]; |
| 64 | VideoPicture { |
| 65 | width, |
| 66 | height, |
| 67 | bgra: pixel |
| 68 | .iter() |
| 69 | .copied() |
| 70 | .cycle() |
| 71 | .take(width as usize * height as usize * BYTES_PER_PIXEL) |
| 72 | .collect(), |
| 73 | } |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | pub struct VideoHub { |
| 78 | frames: Mutex<HashMap<VideoKey, Arc<VideoPicture>>>, |
| 79 | pending: AtomicBool, |
| 80 | notify: UnboundedSender<CallUpdate>, |
| 81 | } |
| 82 | |
| 83 | impl VideoHub { |
| 84 | pub fn new(notify: UnboundedSender<CallUpdate>) -> Arc<Self> { |
| 85 | Arc::new(VideoHub { |
| 86 | frames: Mutex::default(), |
| 87 | pending: AtomicBool::new(false), |
| 88 | notify, |
| 89 | }) |
| 90 | } |
| 91 | |
| 92 | pub fn publish(&self, key: VideoKey, picture: VideoPicture) { |
| 93 | self.frames |
| 94 | .lock() |
| 95 | .expect("video frames lock") |
| 96 | .insert(key, Arc::new(picture)); |
| 97 | if !self.pending.swap(true, Ordering::SeqCst) { |
| 98 | let _ = self.notify.send(CallUpdate::VideoReady); |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | pub fn drain(&self) -> Vec<(VideoKey, Arc<VideoPicture>)> { |
| 103 | self.pending.store(false, Ordering::SeqCst); |
| 104 | self.frames |
| 105 | .lock() |
| 106 | .expect("video frames lock") |
| 107 | .drain() |
| 108 | .collect() |
| 109 | } |
| 110 | |
| 111 | pub fn forget(&self, key: &VideoKey) { |
| 112 | self.frames.lock().expect("video frames lock").remove(key); |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | const GATE_SLACK: f64 = 0.8; |
| 117 | |
| 118 | pub struct FrameGate { |
| 119 | interval: Duration, |
| 120 | last: Option<Instant>, |
| 121 | } |
| 122 | |
| 123 | impl FrameGate { |
| 124 | pub fn new(frames_per_second: u32) -> Self { |
| 125 | FrameGate { |
| 126 | interval: Duration::from_secs(1).mul_f64(GATE_SLACK) / frames_per_second.max(1), |
| 127 | last: None, |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | pub fn admit(&mut self, now: Instant) -> bool { |
| 132 | let due = self |
| 133 | .last |
| 134 | .is_none_or(|last| now.duration_since(last) >= self.interval); |
| 135 | if due { |
| 136 | self.last = Some(now); |
| 137 | } |
| 138 | due |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | pub fn fit_width(width: u32, height: u32, max_width: u32) -> (u32, u32) { |
| 143 | if width <= max_width || width == 0 { |
| 144 | return (width & !1, height & !1); |
| 145 | } |
| 146 | let scaled_height = (u64::from(height) * u64::from(max_width) / u64::from(width)) as u32; |
| 147 | (max_width & !1, scaled_height.max(2) & !1) |
| 148 | } |
| 149 | |
| 150 | pub fn picture_from_frame(frame: BoxVideoFrame, max_width: u32) -> Option<VideoPicture> { |
| 151 | let buffer: BoxVideoBuffer = frame.buffer; |
| 152 | picture_from_i420(buffer.to_i420(), max_width) |
| 153 | } |
| 154 | |
| 155 | pub fn picture_from_i420(mut i420: I420Buffer, max_width: u32) -> Option<VideoPicture> { |
| 156 | let (width, height) = (i420.width(), i420.height()); |
| 157 | if width < 2 || height < 2 { |
| 158 | return None; |
| 159 | } |
| 160 | let (target_width, target_height) = fit_width(width, height, max_width); |
| 161 | if (target_width, target_height) != (width, height) { |
| 162 | i420 = i420.scale(target_width as i32, target_height as i32); |
| 163 | } |
| 164 | Some(bgra_from_i420(i420)) |
| 165 | } |
| 166 | |
| 167 | pub fn bgra_from_i420(i420: I420Buffer) -> VideoPicture { |
| 168 | let (width, height) = (i420.width(), i420.height()); |
| 169 | let stride = width as usize * BYTES_PER_PIXEL; |
| 170 | let mut bgra = vec![0u8; stride * height as usize]; |
| 171 | let buffer: BoxVideoBuffer = Box::new(i420); |
| 172 | buffer.to_argb( |
| 173 | VideoFormatType::ARGB, |
| 174 | &mut bgra, |
| 175 | stride as u32, |
| 176 | width as i32, |
| 177 | height as i32, |
| 178 | ); |
| 179 | VideoPicture { |
| 180 | width, |
| 181 | height, |
| 182 | bgra, |
| 183 | } |
| 184 | } |
| 185 | |
| 186 | #[cfg(test)] |
| 187 | mod tests { |
| 188 | use super::*; |
| 189 | |
| 190 | #[test] |
| 191 | fn flipping_mirrors_every_row() { |
| 192 | let mut picture = VideoPicture { |
| 193 | width: 3, |
| 194 | height: 2, |
| 195 | bgra: (0u8..24).collect(), |
| 196 | }; |
| 197 | picture.flip_horizontally(); |
| 198 | assert_eq!(&picture.bgra[..12], &[8, 9, 10, 11, 4, 5, 6, 7, 0, 1, 2, 3]); |
| 199 | assert_eq!(&picture.bgra[12..16], &[20, 21, 22, 23]); |
| 200 | } |
| 201 | |
| 202 | #[test] |
| 203 | fn the_gate_caps_a_fast_source_at_thirty_frames_a_second() { |
| 204 | let mut gate = FrameGate::new(30); |
| 205 | let start = Instant::now(); |
| 206 | let admitted = (0..120) |
| 207 | .filter(|tick| gate.admit(start + Duration::from_millis(tick * 8))) |
| 208 | .count(); |
| 209 | assert!( |
| 210 | (28..=32).contains(&admitted), |
| 211 | "{admitted} frames in a second" |
| 212 | ); |
| 213 | } |
| 214 | |
| 215 | #[test] |
| 216 | fn the_gate_keeps_every_frame_of_a_steady_thirty_fps_source() { |
| 217 | let mut gate = FrameGate::new(30); |
| 218 | let start = Instant::now(); |
| 219 | let admitted = (0..30) |
| 220 | .filter(|tick| gate.admit(start + Duration::from_micros(tick * 33_000))) |
| 221 | .count(); |
| 222 | assert_eq!(admitted, 30); |
| 223 | } |
| 224 | |
| 225 | #[test] |
| 226 | fn wide_frames_shrink_to_the_cap_with_even_sides() { |
| 227 | assert_eq!(fit_width(1920, 1080, 640), (640, 360)); |
| 228 | assert_eq!(fit_width(1280, 720, 640), (640, 360)); |
| 229 | assert_eq!(fit_width(321, 241, 640), (320, 240)); |
| 230 | assert_eq!(fit_width(1000, 1001, 500), (500, 500)); |
| 231 | } |
| 232 | |
| 233 | #[test] |
| 234 | fn the_hub_notifies_once_until_it_is_drained() { |
| 235 | let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel(); |
| 236 | let hub = VideoHub::new(sender); |
| 237 | hub.publish(VideoKey::Screen, VideoPicture::solid(2, 2, 0, 0, 0)); |
| 238 | hub.publish(VideoKey::LocalCamera, VideoPicture::solid(2, 2, 0, 0, 0)); |
| 239 | hub.publish(VideoKey::Screen, VideoPicture::solid(4, 4, 0, 0, 0)); |
| 240 | assert!(matches!(receiver.try_recv(), Ok(CallUpdate::VideoReady))); |
| 241 | assert!(receiver.try_recv().is_err()); |
| 242 | let drained = hub.drain(); |
| 243 | assert_eq!(drained.len(), 2); |
| 244 | assert!( |
| 245 | drained |
| 246 | .iter() |
| 247 | .any(|(key, picture)| *key == VideoKey::Screen && picture.width == 4) |
| 248 | ); |
| 249 | hub.publish(VideoKey::Screen, VideoPicture::solid(2, 2, 0, 0, 0)); |
| 250 | assert!(matches!(receiver.try_recv(), Ok(CallUpdate::VideoReady))); |
| 251 | } |
| 252 | |
| 253 | #[test] |
| 254 | fn a_red_i420_frame_becomes_bgra_red() { |
| 255 | let mut buffer = I420Buffer::new(4, 4); |
| 256 | let (y_plane, u_plane, v_plane) = buffer.data_mut(); |
| 257 | y_plane.fill(82); |
| 258 | u_plane.fill(90); |
| 259 | v_plane.fill(240); |
| 260 | let picture = bgra_from_i420(buffer); |
| 261 | let [blue, green, red, alpha] = [ |
| 262 | picture.bgra[0], |
| 263 | picture.bgra[1], |
| 264 | picture.bgra[2], |
| 265 | picture.bgra[3], |
| 266 | ]; |
| 267 | assert!( |
| 268 | red > 200 && green < 60 && blue < 60 && alpha == 255, |
| 269 | "{blue} {green} {red} {alpha}" |
| 270 | ); |
| 271 | } |
| 272 | } |