BlueGit

ict rusty-teams

Files

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

video_frame.rs

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