BlueGit

ict rusty-teams

Files

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

video_send.rs

video_send.rs 11.1 KiB Download Raw
1use std::sync::Arc;
2use std::sync::atomic::{AtomicU32, Ordering};
3use std::time::{Instant, SystemTime, UNIX_EPOCH};
4
5use libwebrtc::media_stream_track::MediaStreamTrack;
6use libwebrtc::peer_connection_factory::PeerConnectionFactory;
7use libwebrtc::rtp_parameters::DegradationPreference;
8use libwebrtc::rtp_sender::RtpSender;
9use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
10use libwebrtc::video_frame::{I420Buffer, VideoFrame, VideoRotation};
11use libwebrtc::video_source::VideoResolution;
12use libwebrtc::video_source::native::NativeVideoSource;
13use libwebrtc::video_track::RtcVideoTrack;
14use tokio::sync::mpsc::UnboundedSender;
15
16use crate::background::BackgroundPicture;
17use crate::blur::BlurSettings;
18use crate::effects::{CameraEffects, EffectsStage};
19use crate::camera::start_camera;
20use crate::capture::Capture;
21use crate::control::CallUpdate;
22use crate::devices::DeviceChoice;
23use crate::error::{Error, Result};
24use crate::screen::{ShareSource, start_screen_capture};
25use crate::standout::StandoutOverlay;
26use crate::video_frame::{FrameGate, PERSON_FPS, SCREEN_FPS, VideoHub, VideoKey, picture_from_i420};
27use crate::video_layout::VideoLines;
28use crate::video_pattern::{PatternKind, spawn_pattern};
29
30pub const VIDEO_MODE_ENV: &str = "CALLING_VIDEO";
31const CAMERA_LABEL: &str = "camera";
32const SCREEN_LABEL: &str = "screen";
33pub const SCREEN_SHARE_FPS: u32 = 15;
34pub const MOTION_SHARE_FPS: u32 = 30;
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
37pub enum VideoMode {
38 #[default]
39 Platform,
40 Pattern,
41 Off,
42}
43
44impl VideoMode {
45 pub fn from_env() -> Self {
46 Self::parse(std::env::var(VIDEO_MODE_ENV).ok().as_deref())
47 }
48
49 pub fn parse(value: Option<&str>) -> Self {
50 match value.map(str::to_ascii_lowercase).as_deref() {
51 Some("pattern") => VideoMode::Pattern,
52 Some("off") => VideoMode::Off,
53 _ => VideoMode::Platform,
54 }
55 }
56}
57
58/// Where a captured frame goes: the encoder source and, for the self view, the UI hub.
59pub struct LocalSink {
60 source: NativeVideoSource,
61 self_view: Option<(Arc<VideoHub>, VideoKey, FrameGate)>,
62 mirror: Option<Arc<BlurSettings>>,
63 standout: Option<StandoutOverlay>,
64}
65
66impl LocalSink {
67 pub fn new(source: NativeVideoSource, hub: Option<(Arc<VideoHub>, VideoKey)>) -> Self {
68 let self_view = hub.map(|(hub, key)| {
69 let fps = if matches!(key, VideoKey::LocalScreen) { SCREEN_FPS } else { PERSON_FPS };
70 (hub, key, FrameGate::new(fps))
71 });
72 LocalSink { source, self_view, mirror: None, standout: None }
73 }
74
75 pub fn mirrored_by(mut self, settings: Arc<BlurSettings>) -> Self {
76 self.mirror = Some(settings);
77 self
78 }
79
80 pub fn with_standout(mut self, settings: Arc<BlurSettings>) -> Self {
81 self.standout = Some(StandoutOverlay::new(settings));
82 self
83 }
84
85 pub fn push(&mut self, buffer: I420Buffer) {
86 let buffer = match &mut self.standout {
87 Some(overlay) => overlay.apply(buffer),
88 None => buffer,
89 };
90 let mut frame = VideoFrame::new(VideoRotation::VideoRotation0, buffer);
91 frame.timestamp_us = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |elapsed| elapsed.as_micros() as i64);
92 self.source.capture_frame(&frame);
93 let Some((hub, key, gate)) = &mut self.self_view else { return };
94 if gate.admit(Instant::now())
95 && let Some(mut picture) = picture_from_i420(frame.buffer, key.max_width())
96 {
97 if self.mirror.as_ref().is_some_and(|settings| settings.effects().mirror) {
98 picture.flip_horizontally();
99 }
100 hub.publish(key.clone(), picture);
101 }
102 }
103}
104
105struct Outgoing {
106 source: NativeVideoSource,
107 track: RtcVideoTrack,
108 capture: Option<Capture>,
109}
110
111impl Outgoing {
112 fn new(factory: &PeerConnectionFactory, label: &str, kind: PatternKind, screencast: bool) -> Self {
113 let (width, height) = kind.size();
114 let source = NativeVideoSource::new(VideoResolution { width, height }, screencast);
115 let track = factory.create_video_track(label, source.clone());
116 Outgoing { source, track, capture: None }
117 }
118}
119
120/// Camera and screen share of the local user; frames come from devices or a generated pattern.
121pub struct LocalVideo {
122 mode: VideoMode,
123 hub: Arc<VideoHub>,
124 updates: UnboundedSender<CallUpdate>,
125 camera: Outgoing,
126 screen: Outgoing,
127 lines: Option<VideoLines>,
128 blur: Arc<BlurSettings>,
129 motion: bool,
130 share_fps: Arc<AtomicU32>,
131}
132
133impl LocalVideo {
134 pub fn new(factory: &PeerConnectionFactory, mode: VideoMode, hub: Arc<VideoHub>, updates: UnboundedSender<CallUpdate>) -> Self {
135 LocalVideo {
136 mode,
137 hub,
138 updates,
139 camera: Outgoing::new(factory, CAMERA_LABEL, PatternKind::Camera, false),
140 screen: Outgoing::new(factory, SCREEN_LABEL, PatternKind::Screen, true),
141 lines: None,
142 blur: Arc::new(BlurSettings::default()),
143 motion: false,
144 share_fps: Arc::new(AtomicU32::new(SCREEN_SHARE_FPS)),
145 }
146 }
147
148 pub fn set_motion(&mut self, motion: bool) {
149 self.motion = motion;
150 self.share_fps.store(if motion { MOTION_SHARE_FPS } else { SCREEN_SHARE_FPS }, Ordering::Relaxed);
151 if let Some(share) = self.lines.as_ref().and_then(|lines| lines.share.as_ref()).filter(|_| self.sharing()) {
152 let _ = self.tune_share(&share.sender());
153 }
154 }
155
156 pub fn set_standout(&self, standout: bool) {
157 self.blur.set_standout(standout);
158 }
159
160 fn tune_share(&self, sender: &RtpSender) -> Result<()> {
161 let mut parameters = sender.parameters();
162 parameters.set_degradation_preference(if self.motion {
163 DegradationPreference::MaintainFramerate
164 } else {
165 DegradationPreference::MaintainResolution
166 });
167 let fps = f64::from(self.share_fps.load(Ordering::Relaxed));
168 for encoding in &mut parameters.encodings {
169 encoding.max_framerate = Some(fps);
170 }
171 sender.set_parameters(parameters).map_err(|error| Error::Webrtc(error.to_string()))
172 }
173
174 pub fn set_background(&self, enabled: bool, picture: Option<Arc<BackgroundPicture>>) {
175 self.blur.set_picture(picture);
176 self.blur.set_enabled(enabled);
177 }
178
179 pub fn set_effects(&self, effects: CameraEffects) {
180 self.blur.set_effects(effects);
181 }
182
183 pub fn camera_track(&self) -> RtcVideoTrack {
184 self.camera.track.clone()
185 }
186
187 pub fn blur_average_ms(&self) -> Option<f32> {
188 (self.camera_on() && self.blur.active()).then(|| self.blur.average_ms())
189 }
190
191 pub fn has_lines(&self) -> bool {
192 self.lines.is_some()
193 }
194
195 pub fn is_available(&self) -> bool {
196 self.mode != VideoMode::Off
197 }
198
199 pub fn camera_on(&self) -> bool {
200 self.camera.capture.is_some()
201 }
202
203 pub fn sharing(&self) -> bool {
204 self.screen.capture.is_some()
205 }
206
207 pub fn set_lines(&mut self, lines: VideoLines) -> Result<()> {
208 if self.camera_on() {
209 Self::begin_sending(&lines.camera.sender(), &self.camera.track)?;
210 }
211 if self.sharing()
212 && let Some(share) = &lines.share
213 {
214 Self::begin_sending(&share.sender(), &self.screen.track)?;
215 }
216 self.lines = Some(lines);
217 Ok(())
218 }
219
220 fn begin_sending(sender: &RtpSender, track: &RtcVideoTrack) -> Result<()> {
221 sender
222 .set_track(Some(MediaStreamTrack::Video(track.clone())))
223 .map_err(|error| Error::Webrtc(error.to_string()))?;
224 Self::set_active(sender, true)
225 }
226
227 fn set_active(sender: &RtpSender, active: bool) -> Result<()> {
228 let mut parameters = sender.parameters();
229 for encoding in &mut parameters.encodings {
230 encoding.active = active;
231 }
232 sender.set_parameters(parameters).map_err(|error| Error::Webrtc(error.to_string()))
233 }
234
235 fn camera_sink(&self) -> LocalSink {
236 LocalSink::new(self.camera.source.clone(), Some((self.hub.clone(), VideoKey::LocalCamera))).mirrored_by(self.blur.clone())
237 }
238
239 fn report_failure(&self, what: &'static str) -> impl FnOnce(String) + Send + 'static {
240 let updates = self.updates.clone();
241 move |reason| {
242 let _ = updates.send(CallUpdate::Notice(format!("{what} stopped: {reason}")));
243 }
244 }
245
246 pub fn start_camera(&mut self, choice: &DeviceChoice) -> Result<()> {
247 let lines = self.lines.as_ref().ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?;
248 if !self.is_available() {
249 return Err(Error::Webrtc("video is switched off".into()));
250 }
251 self.camera.capture = None;
252 let mut sink = self.camera_sink();
253 let capture = match self.mode {
254 VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Camera, Some(EffectsStage::new(self.blur.clone())))),
255 _ => start_camera(choice, self.blur.clone(), move |buffer| sink.push(buffer), self.report_failure("Camera"))?,
256 };
257 Self::begin_sending(&lines.camera.sender(), &self.camera.track)?;
258 self.camera.capture = Some(capture);
259 Ok(())
260 }
261
262 pub fn stop_camera(&mut self) {
263 self.camera.capture = None;
264 self.blur.set_cutout(None);
265 if let Some(lines) = &self.lines {
266 let _ = Self::set_active(&lines.camera.sender(), false);
267 }
268 self.hub.forget(&VideoKey::LocalCamera);
269 }
270
271 pub fn start_share(&mut self, source: &ShareSource) -> Result<()> {
272 let lines = self.lines.as_ref().ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?;
273 let share = lines.share.as_ref().ok_or_else(|| Error::Webrtc("sharing needs a meeting".into()))?;
274 if !self.is_available() {
275 return Err(Error::Webrtc("video is switched off".into()));
276 }
277 self.screen.capture = None;
278 let mut sink = LocalSink::new(self.screen.source.clone(), None).with_standout(self.blur.clone());
279 let capture = match self.mode {
280 VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Screen, None)),
281 _ => start_screen_capture(source.clone(), self.share_fps.clone(), move |buffer| sink.push(buffer), self.report_failure("Screen share"))?,
282 };
283 Self::begin_sending(&share.sender(), &self.screen.track)?;
284 let _ = self.tune_share(&share.sender());
285 self.screen.capture = Some(capture);
286 Ok(())
287 }
288
289 pub fn stop_share(&mut self) {
290 self.screen.capture = None;
291 if let Some(share) = self.lines.as_ref().and_then(|lines| lines.share.as_ref()) {
292 let _ = Self::set_active(&share.sender(), false);
293 }
294 }
295
296 pub fn stop_all(&mut self) {
297 self.stop_camera();
298 self.stop_share();
299 }
300}
301
302#[cfg(test)]
303mod tests {
304 use super::*;
305
306 #[test]
307 fn the_video_mode_follows_the_environment_value() {
308 assert_eq!(VideoMode::parse(None), VideoMode::Platform);
309 assert_eq!(VideoMode::parse(Some("Pattern")), VideoMode::Pattern);
310 assert_eq!(VideoMode::parse(Some("off")), VideoMode::Off);
311 assert_eq!(VideoMode::parse(Some("whatever")), VideoMode::Platform);
312 }
313}