BlueGit

ict rusty-teams

Files

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

video_frame.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
video_frame.rs 7.9 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::{
7 BoxVideoBuffer, BoxVideoFrame, I420Buffer, VideoBuffer, VideoFormatType,
8};
9use tokio::sync::mpsc::UnboundedSender;
10
11use crate::control::CallUpdate;
12
13pub const PERSON_FPS: u32 = 30;
14pub const SCREEN_FPS: u32 = 15;
15pub const PERSON_MAX_WIDTH: u32 = 640;
16pub const SCREEN_MAX_WIDTH: u32 = 2560;
17const BYTES_PER_PIXEL: usize = 4;
18
19#[derive(Debug, Clone, PartialEq, Eq, Hash)]
20pub enum VideoKey {
21 Person(String),
22 Screen,
23 LocalCamera,
24 LocalScreen,
25}
26
27impl 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)]
45pub struct VideoPicture {
46 pub width: u32,
47 pub height: u32,
48 pub bgra: Vec<u8>,
49}
50
51impl 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
77pub struct VideoHub {
78 frames: Mutex<HashMap<VideoKey, Arc<VideoPicture>>>,
79 pending: AtomicBool,
80 notify: UnboundedSender<CallUpdate>,
81}
82
83impl 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
116const GATE_SLACK: f64 = 0.8;
117
118pub struct FrameGate {
119 interval: Duration,
120 last: Option<Instant>,
121}
122
123impl 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
142pub 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
150pub 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
155pub 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
167pub 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)]
187mod 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}