BlueGit

ict rusty-teams

Files

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

video_send.rs

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