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