BlueGit

ict rusty-teams

Files

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

video_send.rs

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