| 1 | use std::sync::Arc; |
| 2 | use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; |
| 3 | use std::time::{Instant, SystemTime, UNIX_EPOCH}; |
| 4 | |
| 5 | use libwebrtc::media_stream_track::MediaStreamTrack; |
| 6 | use libwebrtc::peer_connection_factory::PeerConnectionFactory; |
| 7 | use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt; |
| 8 | use libwebrtc::rtp_parameters::DegradationPreference; |
| 9 | use libwebrtc::rtp_sender::RtpSender; |
| 10 | use libwebrtc::rtp_transceiver::{RtpTransceiver, RtpTransceiverDirection}; |
| 11 | use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _, VideoFrame, VideoRotation}; |
| 12 | use libwebrtc::video_source::VideoResolution; |
| 13 | use libwebrtc::video_source::native::NativeVideoSource; |
| 14 | use libwebrtc::video_track::RtcVideoTrack; |
| 15 | use tokio::sync::mpsc::UnboundedSender; |
| 16 | |
| 17 | use crate::background::BackgroundPicture; |
| 18 | use crate::blur::BlurSettings; |
| 19 | use crate::camera::{CameraCaptureStats, start_camera}; |
| 20 | use crate::capture::Capture; |
| 21 | use crate::control::{CallCommand, CallUpdate}; |
| 22 | use crate::devices::DeviceChoice; |
| 23 | use crate::effects::CameraEffects; |
| 24 | use crate::error::{Error, Result}; |
| 25 | use crate::notices::{CAMERA_STOPPED_NOTICE, SCREEN_SHARE_STOPPED_NOTICE, notice_with_detail}; |
| 26 | use crate::screen::{ |
| 27 | PortalFollowUp, ShareKind, ShareSource, start_portal_capture, start_screen_capture, |
| 28 | }; |
| 29 | use crate::send_control::{ |
| 30 | EncoderLimits, KEYFRAME_NUDGE, LayerPlan, SendLimit, encoder_limits, plan_layers, |
| 31 | }; |
| 32 | use crate::standout::StandoutOverlay; |
| 33 | use crate::timeline::Timeline; |
| 34 | use crate::video_frame::{ |
| 35 | FrameGate, PERSON_FPS, SCREEN_FPS, VideoHub, VideoKey, picture_from_i420, |
| 36 | }; |
| 37 | use crate::video_layout::VideoLines; |
| 38 | use crate::video_pattern::{PatternKind, spawn_pattern}; |
| 39 | use crate::video_quality::VideoQuality; |
| 40 | |
| 41 | pub const VIDEO_MODE_ENV: &str = "CALLING_VIDEO"; |
| 42 | const CAMERA_LABEL: &str = "camera"; |
| 43 | const SCREEN_LABEL: &str = "screen"; |
| 44 | pub const SCREEN_SHARE_FPS: u32 = 15; |
| 45 | pub const MOTION_SHARE_FPS: u32 = 30; |
| 46 | |
| 47 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 48 | pub enum VideoMode { |
| 49 | #[default] |
| 50 | Platform, |
| 51 | Pattern, |
| 52 | Off, |
| 53 | } |
| 54 | |
| 55 | impl VideoMode { |
| 56 | pub fn from_env() -> Self { |
| 57 | Self::parse(std::env::var(VIDEO_MODE_ENV).ok().as_deref()) |
| 58 | } |
| 59 | |
| 60 | pub fn parse(value: Option<&str>) -> Self { |
| 61 | match value.map(str::to_ascii_lowercase).as_deref() { |
| 62 | Some("pattern") => VideoMode::Pattern, |
| 63 | Some("off") => VideoMode::Off, |
| 64 | _ => VideoMode::Platform, |
| 65 | } |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | /// Where a captured frame goes: the encoder source and, for the self view, the UI hub. |
| 70 | pub struct LocalSink { |
| 71 | source: NativeVideoSource, |
| 72 | self_view: Option<(Arc<VideoHub>, VideoKey, FrameGate)>, |
| 73 | mirror: Option<Arc<BlurSettings>>, |
| 74 | standout: Option<StandoutOverlay>, |
| 75 | frame_size: Option<Arc<AtomicU64>>, |
| 76 | } |
| 77 | |
| 78 | impl LocalSink { |
| 79 | pub fn new(source: NativeVideoSource, hub: Option<(Arc<VideoHub>, VideoKey)>) -> Self { |
| 80 | let self_view = hub.map(|(hub, key)| { |
| 81 | let fps = if matches!(key, VideoKey::LocalScreen) { |
| 82 | SCREEN_FPS |
| 83 | } else { |
| 84 | PERSON_FPS |
| 85 | }; |
| 86 | (hub, key, FrameGate::new(fps)) |
| 87 | }); |
| 88 | LocalSink { |
| 89 | source, |
| 90 | self_view, |
| 91 | mirror: None, |
| 92 | standout: None, |
| 93 | frame_size: None, |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | pub fn reporting_size(mut self, frame_size: Arc<AtomicU64>) -> Self { |
| 98 | self.frame_size = Some(frame_size); |
| 99 | self |
| 100 | } |
| 101 | |
| 102 | pub fn mirrored_by(mut self, settings: Arc<BlurSettings>) -> Self { |
| 103 | self.mirror = Some(settings); |
| 104 | self |
| 105 | } |
| 106 | |
| 107 | pub fn with_standout(mut self, settings: Arc<BlurSettings>) -> Self { |
| 108 | self.standout = Some(StandoutOverlay::new(settings)); |
| 109 | self |
| 110 | } |
| 111 | |
| 112 | pub fn push(&mut self, buffer: I420Buffer) { |
| 113 | let buffer = match &mut self.standout { |
| 114 | Some(overlay) => overlay.apply(buffer), |
| 115 | None => buffer, |
| 116 | }; |
| 117 | if let Some(frame_size) = &self.frame_size { |
| 118 | frame_size.store( |
| 119 | pack_size(buffer.width(), buffer.height()), |
| 120 | Ordering::Relaxed, |
| 121 | ); |
| 122 | } |
| 123 | let mut frame = VideoFrame::new(VideoRotation::VideoRotation0, buffer); |
| 124 | frame.timestamp_us = SystemTime::now() |
| 125 | .duration_since(UNIX_EPOCH) |
| 126 | .map_or(0, |elapsed| elapsed.as_micros() as i64); |
| 127 | self.source.capture_frame(&frame); |
| 128 | let Some((hub, key, gate)) = &mut self.self_view else { |
| 129 | return; |
| 130 | }; |
| 131 | if gate.admit(Instant::now()) |
| 132 | && let Some(mut picture) = picture_from_i420(frame.buffer, key.max_width()) |
| 133 | { |
| 134 | if self |
| 135 | .mirror |
| 136 | .as_ref() |
| 137 | .is_some_and(|settings| settings.effects().mirror) |
| 138 | { |
| 139 | picture.flip_horizontally(); |
| 140 | } |
| 141 | hub.publish(key.clone(), picture); |
| 142 | } |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | fn pack_size(width: u32, height: u32) -> u64 { |
| 147 | (u64::from(width) << 32) | u64::from(height) |
| 148 | } |
| 149 | |
| 150 | fn unpack_size(packed: u64) -> Option<(u32, u32)> { |
| 151 | let (width, height) = ((packed >> 32) as u32, packed as u32); |
| 152 | (width > 0 && height > 0).then_some((width, height)) |
| 153 | } |
| 154 | |
| 155 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 156 | pub enum SendSource { |
| 157 | Camera, |
| 158 | Screen, |
| 159 | } |
| 160 | |
| 161 | struct Outgoing { |
| 162 | source: NativeVideoSource, |
| 163 | track: RtcVideoTrack, |
| 164 | capture: Option<Capture>, |
| 165 | frame_size: Arc<AtomicU64>, |
| 166 | requested: Option<RequestedLimits>, |
| 167 | } |
| 168 | |
| 169 | struct RequestedLimits { |
| 170 | limits: Vec<SendLimit>, |
| 171 | applied_for: Option<(u32, u32)>, |
| 172 | } |
| 173 | |
| 174 | impl Outgoing { |
| 175 | fn new( |
| 176 | factory: &PeerConnectionFactory, |
| 177 | label: &str, |
| 178 | kind: PatternKind, |
| 179 | screencast: bool, |
| 180 | ) -> Self { |
| 181 | let (width, height) = kind.size(); |
| 182 | let source = NativeVideoSource::new(VideoResolution { width, height }, screencast); |
| 183 | let track = factory.create_video_track(label, source.clone()); |
| 184 | Outgoing { |
| 185 | source, |
| 186 | track, |
| 187 | capture: None, |
| 188 | frame_size: Arc::new(AtomicU64::new(0)), |
| 189 | requested: None, |
| 190 | } |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | /// Camera and screen share of the local user; frames come from devices or a generated pattern. |
| 195 | pub struct LocalVideo { |
| 196 | mode: VideoMode, |
| 197 | hub: Arc<VideoHub>, |
| 198 | updates: UnboundedSender<CallUpdate>, |
| 199 | commands: Option<UnboundedSender<CallCommand>>, |
| 200 | camera_generation: Arc<AtomicU64>, |
| 201 | share_generation: Arc<AtomicU64>, |
| 202 | camera: Outgoing, |
| 203 | screen: Outgoing, |
| 204 | lines: Option<VideoLines>, |
| 205 | blur: Arc<BlurSettings>, |
| 206 | motion: bool, |
| 207 | share_fps: Arc<AtomicU32>, |
| 208 | camera_preview: bool, |
| 209 | quality: VideoQuality, |
| 210 | camera_stats: Arc<CameraCaptureStats>, |
| 211 | timeline: Option<Timeline>, |
| 212 | portal_generation: u64, |
| 213 | portal_armed: bool, |
| 214 | portal_keep: bool, |
| 215 | /// The desktop dialog already bound the PipeWire stream. Later `StartShare` |
| 216 | /// commands must attach that capturer, not replace it. |
| 217 | portal_bound: bool, |
| 218 | camera_bitrate_cap: Option<u64>, |
| 219 | } |
| 220 | |
| 221 | impl LocalVideo { |
| 222 | pub fn new( |
| 223 | factory: &PeerConnectionFactory, |
| 224 | mode: VideoMode, |
| 225 | hub: Arc<VideoHub>, |
| 226 | updates: UnboundedSender<CallUpdate>, |
| 227 | ) -> Self { |
| 228 | LocalVideo { |
| 229 | mode, |
| 230 | hub, |
| 231 | updates, |
| 232 | commands: None, |
| 233 | camera_generation: Arc::new(AtomicU64::new(0)), |
| 234 | share_generation: Arc::new(AtomicU64::new(0)), |
| 235 | camera: Outgoing::new(factory, CAMERA_LABEL, PatternKind::Camera, false), |
| 236 | screen: Outgoing::new(factory, SCREEN_LABEL, PatternKind::Screen, true), |
| 237 | lines: None, |
| 238 | blur: Arc::new(BlurSettings::default()), |
| 239 | motion: false, |
| 240 | share_fps: Arc::new(AtomicU32::new(SCREEN_SHARE_FPS)), |
| 241 | camera_preview: false, |
| 242 | quality: VideoQuality::default(), |
| 243 | camera_stats: CameraCaptureStats::new(), |
| 244 | timeline: None, |
| 245 | portal_generation: 0, |
| 246 | portal_armed: false, |
| 247 | portal_keep: false, |
| 248 | portal_bound: false, |
| 249 | camera_bitrate_cap: None, |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | pub fn attach_commands(&mut self, commands: UnboundedSender<CallCommand>) { |
| 254 | self.commands = Some(commands); |
| 255 | } |
| 256 | |
| 257 | pub fn attach_timeline(&mut self, timeline: Timeline) { |
| 258 | self.timeline = Some(timeline); |
| 259 | } |
| 260 | |
| 261 | pub fn video_quality(&self) -> VideoQuality { |
| 262 | self.quality |
| 263 | } |
| 264 | |
| 265 | pub fn set_video_quality(&mut self, quality: VideoQuality) { |
| 266 | self.quality = quality; |
| 267 | } |
| 268 | |
| 269 | pub fn set_motion(&mut self, motion: bool) { |
| 270 | self.motion = motion; |
| 271 | self.share_fps.store( |
| 272 | if motion { |
| 273 | MOTION_SHARE_FPS |
| 274 | } else { |
| 275 | SCREEN_SHARE_FPS |
| 276 | }, |
| 277 | Ordering::Relaxed, |
| 278 | ); |
| 279 | if let Some(share) = self |
| 280 | .lines |
| 281 | .as_ref() |
| 282 | .and_then(|lines| lines.share.as_ref()) |
| 283 | .filter(|_| self.sharing()) |
| 284 | { |
| 285 | let _ = self.tune_share(&share.sender()); |
| 286 | } |
| 287 | } |
| 288 | |
| 289 | pub fn set_standout(&self, standout: bool) { |
| 290 | self.blur.set_standout(standout); |
| 291 | } |
| 292 | |
| 293 | fn tune_share(&self, sender: &RtpSender) -> Result<()> { |
| 294 | let mut parameters = sender.parameters(); |
| 295 | parameters.set_degradation_preference(if self.motion { |
| 296 | DegradationPreference::MaintainFramerate |
| 297 | } else { |
| 298 | DegradationPreference::MaintainResolution |
| 299 | }); |
| 300 | let fps = f64::from(self.share_fps.load(Ordering::Relaxed)); |
| 301 | for encoding in &mut parameters.encodings { |
| 302 | encoding.max_framerate = Some(fps); |
| 303 | } |
| 304 | sender |
| 305 | .set_parameters(parameters) |
| 306 | .map_err(|error| Error::Webrtc(error.to_string())) |
| 307 | } |
| 308 | |
| 309 | fn sender_of(&self, source: SendSource) -> Option<RtpSender> { |
| 310 | let lines = self.lines.as_ref()?; |
| 311 | match source { |
| 312 | SendSource::Camera => Some(lines.camera.sender()), |
| 313 | SendSource::Screen => lines.share.as_ref().map(|share| share.sender()), |
| 314 | } |
| 315 | } |
| 316 | |
| 317 | pub fn apply_send_limit( |
| 318 | &mut self, |
| 319 | source: SendSource, |
| 320 | limits: &[SendLimit], |
| 321 | ) -> Result<Option<Vec<LayerPlan>>> { |
| 322 | let sending = match source { |
| 323 | SendSource::Camera => self.camera_on(), |
| 324 | SendSource::Screen => self.sharing(), |
| 325 | }; |
| 326 | let Some(sender) = self.sender_of(source).filter(|_| sending) else { |
| 327 | return Ok(None); |
| 328 | }; |
| 329 | let outgoing = match source { |
| 330 | SendSource::Camera => &mut self.camera, |
| 331 | SendSource::Screen => &mut self.screen, |
| 332 | }; |
| 333 | let frame = unpack_size(outgoing.frame_size.load(Ordering::Relaxed)); |
| 334 | outgoing.requested = Some(RequestedLimits { |
| 335 | limits: limits.to_vec(), |
| 336 | applied_for: frame, |
| 337 | }); |
| 338 | let rids: Vec<String> = sender |
| 339 | .parameters() |
| 340 | .encodings |
| 341 | .into_iter() |
| 342 | .map(|encoding| encoding.rid) |
| 343 | .collect(); |
| 344 | if rids.len() > 1 { |
| 345 | let mut plans = plan_layers(limits, frame, &rids); |
| 346 | if source == SendSource::Camera { |
| 347 | Self::apply_bitrate_cap_to_plans(&mut plans, self.camera_bitrate_cap); |
| 348 | } |
| 349 | if plans.iter().any(|plan| plan.keyframe) { |
| 350 | Self::set_layers(&sender, &plans, KEYFRAME_NUDGE)?; |
| 351 | } |
| 352 | Self::set_layers(&sender, &plans, 1.0)?; |
| 353 | return Ok(Some(plans)); |
| 354 | } |
| 355 | let Some(limit) = limits.first() else { |
| 356 | return Ok(None); |
| 357 | }; |
| 358 | let mut encoder = encoder_limits(limit, frame); |
| 359 | if source == SendSource::Camera |
| 360 | && let Some(cap) = self.camera_bitrate_cap |
| 361 | { |
| 362 | encoder.max_bitrate = Some(encoder.max_bitrate.map_or(cap, |max| max.min(cap))); |
| 363 | } |
| 364 | if limit.keyframe { |
| 365 | Self::set_limits(&sender, &encoder, KEYFRAME_NUDGE)?; |
| 366 | } |
| 367 | Self::set_limits(&sender, &encoder, 1.0)?; |
| 368 | Ok(Some(vec![LayerPlan { |
| 369 | rid: rids.into_iter().next().unwrap_or_default(), |
| 370 | active: true, |
| 371 | limits: Some(encoder), |
| 372 | keyframe: limit.keyframe, |
| 373 | }])) |
| 374 | } |
| 375 | |
| 376 | fn apply_bitrate_cap_to_plans(plans: &mut [LayerPlan], cap: Option<u64>) { |
| 377 | let Some(cap) = cap else { return }; |
| 378 | for plan in plans { |
| 379 | if let Some(limits) = plan.limits.as_mut() { |
| 380 | limits.max_bitrate = Some(limits.max_bitrate.map_or(cap, |max| max.min(cap))); |
| 381 | } |
| 382 | } |
| 383 | } |
| 384 | |
| 385 | /// The mixer sends its limits once, often before the first frame tells the size to scale from. |
| 386 | pub fn refresh_send_limits(&mut self) -> Vec<(SendSource, Result<Option<Vec<LayerPlan>>>)> { |
| 387 | let mut refreshed = Vec::new(); |
| 388 | for source in [SendSource::Camera, SendSource::Screen] { |
| 389 | let outgoing = match source { |
| 390 | SendSource::Camera => &self.camera, |
| 391 | SendSource::Screen => &self.screen, |
| 392 | }; |
| 393 | let frame = unpack_size(outgoing.frame_size.load(Ordering::Relaxed)); |
| 394 | let Some(requested) = outgoing |
| 395 | .requested |
| 396 | .as_ref() |
| 397 | .filter(|requested| frame.is_some() && requested.applied_for != frame) |
| 398 | else { |
| 399 | continue; |
| 400 | }; |
| 401 | let limits = requested.limits.clone(); |
| 402 | refreshed.push((source, self.apply_send_limit(source, &limits))); |
| 403 | } |
| 404 | refreshed |
| 405 | } |
| 406 | |
| 407 | fn set_layers(sender: &RtpSender, plans: &[LayerPlan], nudge: f64) -> Result<()> { |
| 408 | let mut parameters = sender.parameters(); |
| 409 | for encoding in &mut parameters.encodings { |
| 410 | let Some(plan) = plans.iter().find(|plan| plan.rid == encoding.rid) else { |
| 411 | continue; |
| 412 | }; |
| 413 | let nudged = nudge != 1.0 && plan.keyframe; |
| 414 | encoding.active = plan.active; |
| 415 | let Some(limits) = &plan.limits else { continue }; |
| 416 | encoding.scale_resolution_down_by = |
| 417 | Some(limits.scale_down_by * if nudged { nudge } else { 1.0 }); |
| 418 | if let Some(framerate) = limits.max_framerate { |
| 419 | encoding.max_framerate = Some(framerate); |
| 420 | } |
| 421 | encoding.max_bitrate = limits.max_bitrate; |
| 422 | } |
| 423 | sender |
| 424 | .set_parameters(parameters) |
| 425 | .map_err(|error| Error::Webrtc(error.to_string())) |
| 426 | } |
| 427 | |
| 428 | fn set_limits(sender: &RtpSender, limits: &EncoderLimits, nudge: f64) -> Result<()> { |
| 429 | let mut parameters = sender.parameters(); |
| 430 | for encoding in &mut parameters.encodings { |
| 431 | encoding.scale_resolution_down_by = Some(limits.scale_down_by * nudge); |
| 432 | if let Some(framerate) = limits.max_framerate { |
| 433 | encoding.max_framerate = Some(framerate); |
| 434 | } |
| 435 | encoding.max_bitrate = limits.max_bitrate; |
| 436 | } |
| 437 | sender |
| 438 | .set_parameters(parameters) |
| 439 | .map_err(|error| Error::Webrtc(error.to_string())) |
| 440 | } |
| 441 | |
| 442 | pub fn camera_size(&self) -> Option<(u32, u32)> { |
| 443 | unpack_size(self.camera.frame_size.load(Ordering::Relaxed)).filter(|_| self.camera_on()) |
| 444 | } |
| 445 | |
| 446 | pub fn set_background(&self, enabled: bool, picture: Option<Arc<BackgroundPicture>>) { |
| 447 | self.blur.set_picture(picture); |
| 448 | self.blur.set_enabled(enabled); |
| 449 | } |
| 450 | |
| 451 | pub fn set_effects(&self, effects: CameraEffects) { |
| 452 | self.blur.set_effects(effects); |
| 453 | } |
| 454 | |
| 455 | pub fn camera_track(&self) -> RtcVideoTrack { |
| 456 | self.camera.track.clone() |
| 457 | } |
| 458 | |
| 459 | pub fn share_track(&self) -> RtcVideoTrack { |
| 460 | self.screen.track.clone() |
| 461 | } |
| 462 | |
| 463 | pub fn take_effects_failure(&self) -> bool { |
| 464 | self.blur.take_unavailable() |
| 465 | } |
| 466 | |
| 467 | pub fn blur_average_ms(&self) -> Option<f32> { |
| 468 | (self.camera_on() && self.blur.active()).then(|| self.blur.average_ms()) |
| 469 | } |
| 470 | |
| 471 | pub fn blur_model(&self) -> Option<&'static str> { |
| 472 | (self.camera_on() && self.blur.active()) |
| 473 | .then(|| self.blur.model()) |
| 474 | .filter(|model| !model.is_empty()) |
| 475 | } |
| 476 | |
| 477 | pub fn has_lines(&self) -> bool { |
| 478 | self.lines.is_some() |
| 479 | } |
| 480 | |
| 481 | pub fn clear_lines(&mut self) { |
| 482 | if let Some(lines) = self.lines.take() { |
| 483 | let _ = lines.camera.sender().set_track(None); |
| 484 | let _ = Self::set_active(&lines.camera.sender(), false); |
| 485 | if let Some(share) = lines.share { |
| 486 | let _ = share.sender().set_track(None); |
| 487 | let _ = Self::set_active(&share.sender(), false); |
| 488 | } |
| 489 | } |
| 490 | } |
| 491 | |
| 492 | pub fn camera_mid(&self) -> Option<String> { |
| 493 | self.lines.as_ref().and_then(|lines| lines.camera.mid()) |
| 494 | } |
| 495 | |
| 496 | pub fn share_mid(&self) -> Option<String> { |
| 497 | self.lines |
| 498 | .as_ref() |
| 499 | .and_then(|lines| lines.share.as_ref()) |
| 500 | .and_then(|share| share.mid()) |
| 501 | } |
| 502 | |
| 503 | pub fn has_share_line(&self) -> bool { |
| 504 | self.lines |
| 505 | .as_ref() |
| 506 | .is_some_and(|lines| lines.share.is_some()) |
| 507 | } |
| 508 | |
| 509 | pub fn add_share_line( |
| 510 | &mut self, |
| 511 | share: RtpTransceiver, |
| 512 | camera: Option<RtpTransceiver>, |
| 513 | ) -> Result<()> { |
| 514 | match (self.lines.as_mut(), camera) { |
| 515 | (Some(lines), _) => lines.share = Some(share), |
| 516 | (None, Some(camera)) => { |
| 517 | self.lines = Some(VideoLines { |
| 518 | camera, |
| 519 | share: Some(share), |
| 520 | }) |
| 521 | } |
| 522 | (None, None) => return Err(Error::Webrtc("no video line negotiated".into())), |
| 523 | } |
| 524 | Ok(()) |
| 525 | } |
| 526 | |
| 527 | pub fn share_sending(&self) -> bool { |
| 528 | self.lines |
| 529 | .as_ref() |
| 530 | .and_then(|lines| lines.share.as_ref()) |
| 531 | .and_then(|share| share.current_direction()) |
| 532 | .is_some_and(|direction| { |
| 533 | matches!( |
| 534 | direction, |
| 535 | RtpTransceiverDirection::SendOnly | RtpTransceiverDirection::SendRecv |
| 536 | ) |
| 537 | }) |
| 538 | } |
| 539 | |
| 540 | pub fn is_available(&self) -> bool { |
| 541 | self.mode != VideoMode::Off |
| 542 | } |
| 543 | |
| 544 | pub fn camera_on(&self) -> bool { |
| 545 | self.camera.capture.is_some() && !self.camera_preview |
| 546 | } |
| 547 | |
| 548 | pub fn camera_previewing(&self) -> bool { |
| 549 | self.camera.capture.is_some() && self.camera_preview |
| 550 | } |
| 551 | |
| 552 | pub fn sharing(&self) -> bool { |
| 553 | self.screen.capture.is_some() |
| 554 | } |
| 555 | |
| 556 | pub fn portal_is_open(&self) -> bool { |
| 557 | self.portal_armed |
| 558 | } |
| 559 | |
| 560 | pub fn set_lines(&mut self, lines: VideoLines) -> Result<()> { |
| 561 | self.clear_lines(); |
| 562 | if self.camera_on() { |
| 563 | Self::begin_sending_on(&lines.camera, &self.camera.track)?; |
| 564 | } |
| 565 | if self.sharing() |
| 566 | && let Some(share) = &lines.share |
| 567 | { |
| 568 | Self::begin_sending_on(share, &self.screen.track)?; |
| 569 | } |
| 570 | self.lines = Some(lines); |
| 571 | Ok(()) |
| 572 | } |
| 573 | |
| 574 | fn ensure_send_direction(transceiver: &RtpTransceiver) -> Result<()> { |
| 575 | match transceiver.direction() { |
| 576 | RtpTransceiverDirection::SendRecv | RtpTransceiverDirection::SendOnly => Ok(()), |
| 577 | RtpTransceiverDirection::RecvOnly | RtpTransceiverDirection::Inactive => transceiver |
| 578 | .set_direction(RtpTransceiverDirection::SendRecv) |
| 579 | .map_err(|error| Error::Webrtc(error.to_string())), |
| 580 | RtpTransceiverDirection::Stopped => Err(Error::Webrtc("video line is stopped".into())), |
| 581 | } |
| 582 | } |
| 583 | |
| 584 | fn begin_sending_on(transceiver: &RtpTransceiver, track: &RtcVideoTrack) -> Result<()> { |
| 585 | Self::ensure_send_direction(transceiver)?; |
| 586 | Self::begin_sending(&transceiver.sender(), track) |
| 587 | } |
| 588 | |
| 589 | fn begin_sending(sender: &RtpSender, track: &RtcVideoTrack) -> Result<()> { |
| 590 | sender |
| 591 | .set_track(Some(MediaStreamTrack::Video(track.clone()))) |
| 592 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 593 | // Prefer dropping resolution over framerate when the uplink is tight. |
| 594 | let mut parameters = sender.parameters(); |
| 595 | parameters.set_degradation_preference(DegradationPreference::MaintainFramerate); |
| 596 | sender |
| 597 | .set_parameters(parameters) |
| 598 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 599 | Self::set_active(sender, true) |
| 600 | } |
| 601 | |
| 602 | pub fn cap_camera_bitrate(&mut self, cap: Option<u64>) -> Result<()> { |
| 603 | if self.camera_bitrate_cap == cap { |
| 604 | return Ok(()); |
| 605 | } |
| 606 | self.camera_bitrate_cap = cap; |
| 607 | if let Some(limits) = self |
| 608 | .camera |
| 609 | .requested |
| 610 | .as_ref() |
| 611 | .map(|requested| requested.limits.clone()) |
| 612 | { |
| 613 | let _ = self.apply_send_limit(SendSource::Camera, &limits)?; |
| 614 | return Ok(()); |
| 615 | } |
| 616 | let Some(sender) = self |
| 617 | .sender_of(SendSource::Camera) |
| 618 | .filter(|_| self.camera_on()) |
| 619 | else { |
| 620 | return Ok(()); |
| 621 | }; |
| 622 | let mut parameters = sender.parameters(); |
| 623 | for encoding in &mut parameters.encodings { |
| 624 | encoding.max_bitrate = match (encoding.max_bitrate, cap) { |
| 625 | (Some(max), Some(cap)) => Some(max.min(cap)), |
| 626 | (None, Some(cap)) => Some(cap), |
| 627 | (max, None) => max, |
| 628 | }; |
| 629 | } |
| 630 | sender |
| 631 | .set_parameters(parameters) |
| 632 | .map_err(|error| Error::Webrtc(error.to_string())) |
| 633 | } |
| 634 | |
| 635 | pub(crate) fn set_sender_active(sender: &RtpSender, active: bool) -> Result<()> { |
| 636 | let mut parameters = sender.parameters(); |
| 637 | for encoding in &mut parameters.encodings { |
| 638 | encoding.active = active; |
| 639 | } |
| 640 | sender |
| 641 | .set_parameters(parameters) |
| 642 | .map_err(|error| Error::Webrtc(error.to_string())) |
| 643 | } |
| 644 | |
| 645 | fn set_active(sender: &RtpSender, active: bool) -> Result<()> { |
| 646 | Self::set_sender_active(sender, active) |
| 647 | } |
| 648 | |
| 649 | fn camera_sink(&self) -> LocalSink { |
| 650 | LocalSink::new( |
| 651 | self.camera.source.clone(), |
| 652 | Some((self.hub.clone(), VideoKey::LocalCamera)), |
| 653 | ) |
| 654 | .mirrored_by(self.blur.clone()) |
| 655 | .reporting_size(self.camera.frame_size.clone()) |
| 656 | } |
| 657 | |
| 658 | /// Local share frames go to the encoder and to the window in the chat. |
| 659 | fn screen_sink(&self) -> LocalSink { |
| 660 | LocalSink::new( |
| 661 | self.screen.source.clone(), |
| 662 | Some((self.hub.clone(), VideoKey::LocalScreen)), |
| 663 | ) |
| 664 | .with_standout(self.blur.clone()) |
| 665 | .reporting_size(self.screen.frame_size.clone()) |
| 666 | } |
| 667 | |
| 668 | /// A capture thread that was replaced meanwhile must not switch off its successor. |
| 669 | fn report_failure( |
| 670 | &self, |
| 671 | notice_key: &'static str, |
| 672 | generation: &Arc<AtomicU64>, |
| 673 | switch_off: CallCommand, |
| 674 | ) -> impl FnOnce(String) + Send + 'static { |
| 675 | let updates = self.updates.clone(); |
| 676 | let commands = self.commands.clone(); |
| 677 | let started = generation.fetch_add(1, Ordering::SeqCst) + 1; |
| 678 | let generation = generation.clone(); |
| 679 | move |reason| { |
| 680 | let _ = updates.send(CallUpdate::Notice(notice_with_detail(notice_key, reason))); |
| 681 | if generation.load(Ordering::SeqCst) == started |
| 682 | && let Some(commands) = commands |
| 683 | { |
| 684 | let _ = commands.send(switch_off); |
| 685 | } |
| 686 | } |
| 687 | } |
| 688 | |
| 689 | pub fn preview_camera(&mut self, choice: &DeviceChoice) -> Result<()> { |
| 690 | if !self.is_available() { |
| 691 | return Err(Error::Webrtc("video is switched off".into())); |
| 692 | } |
| 693 | self.camera.capture = None; |
| 694 | self.camera.capture = Some(self.capture_camera(choice)?); |
| 695 | self.camera_preview = true; |
| 696 | Ok(()) |
| 697 | } |
| 698 | |
| 699 | pub fn start_camera(&mut self, choice: &DeviceChoice) -> Result<()> { |
| 700 | let lines = self |
| 701 | .lines |
| 702 | .as_ref() |
| 703 | .ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?; |
| 704 | if !self.is_available() { |
| 705 | return Err(Error::Webrtc("video is switched off".into())); |
| 706 | } |
| 707 | if !self.camera_previewing() { |
| 708 | self.camera.capture = None; |
| 709 | self.camera.capture = Some(self.capture_camera(choice)?); |
| 710 | } |
| 711 | Self::begin_sending_on(&lines.camera, &self.camera.track)?; |
| 712 | self.camera_preview = false; |
| 713 | Ok(()) |
| 714 | } |
| 715 | |
| 716 | pub fn camera_capture_summary(&self) -> Option<String> { |
| 717 | self.camera_stats.summary() |
| 718 | } |
| 719 | |
| 720 | fn capture_camera(&self, choice: &DeviceChoice) -> Result<Capture> { |
| 721 | let mut sink = self.camera_sink(); |
| 722 | Ok(match self.mode { |
| 723 | VideoMode::Pattern => Capture::Task(spawn_pattern( |
| 724 | sink, |
| 725 | PatternKind::Camera, |
| 726 | Some(self.blur.clone()), |
| 727 | )), |
| 728 | _ => { |
| 729 | let timeline = self.timeline.clone(); |
| 730 | start_camera( |
| 731 | choice, |
| 732 | self.quality, |
| 733 | self.blur.clone(), |
| 734 | self.camera_stats.clone(), |
| 735 | move |label| { |
| 736 | if let Some(timeline) = timeline { |
| 737 | timeline.record("camera capture", label); |
| 738 | } else { |
| 739 | eprintln!("calls: camera capture {label}"); |
| 740 | } |
| 741 | }, |
| 742 | move |buffer| sink.push(buffer), |
| 743 | self.report_failure( |
| 744 | CAMERA_STOPPED_NOTICE, |
| 745 | &self.camera_generation, |
| 746 | CallCommand::SetCamera(false), |
| 747 | ), |
| 748 | )? |
| 749 | } |
| 750 | }) |
| 751 | } |
| 752 | |
| 753 | /// Restart capture with the current quality if the camera is already running. |
| 754 | pub fn refresh_camera_capture(&mut self, choice: &DeviceChoice) -> Result<()> { |
| 755 | if self.camera.capture.is_none() { |
| 756 | return Ok(()); |
| 757 | } |
| 758 | let preview = self.camera_preview; |
| 759 | self.camera.capture = None; |
| 760 | self.camera.capture = Some(self.capture_camera(choice)?); |
| 761 | self.camera_preview = preview; |
| 762 | if !preview { |
| 763 | if let Some(lines) = self.lines.as_ref() { |
| 764 | Self::begin_sending_on(&lines.camera, &self.camera.track)?; |
| 765 | } |
| 766 | } |
| 767 | Ok(()) |
| 768 | } |
| 769 | |
| 770 | pub fn stop_camera(&mut self) { |
| 771 | self.camera_generation.fetch_add(1, Ordering::SeqCst); |
| 772 | self.camera_preview = false; |
| 773 | self.camera.capture = None; |
| 774 | self.blur.set_cutout(None); |
| 775 | if let Some(lines) = &self.lines { |
| 776 | let _ = Self::set_active(&lines.camera.sender(), false); |
| 777 | } |
| 778 | self.hub.forget(&VideoKey::LocalCamera); |
| 779 | } |
| 780 | |
| 781 | pub fn accept_portal(&mut self, generation: u64) -> bool { |
| 782 | if self.portal_armed && self.portal_generation == generation { |
| 783 | self.portal_armed = false; |
| 784 | self.portal_keep = true; |
| 785 | self.portal_bound = true; |
| 786 | true |
| 787 | } else { |
| 788 | false |
| 789 | } |
| 790 | } |
| 791 | |
| 792 | pub fn open_portal( |
| 793 | &mut self, |
| 794 | kind: ShareKind, |
| 795 | commands: UnboundedSender<CallCommand>, |
| 796 | ) -> Result<()> { |
| 797 | if !self.is_available() { |
| 798 | return Err(Error::Webrtc("video is switched off".into())); |
| 799 | } |
| 800 | if self.mode == VideoMode::Pattern { |
| 801 | let source = ShareSource { |
| 802 | id: if kind == ShareKind::Screen { 1 } else { 2 }, |
| 803 | kind, |
| 804 | title: if kind == ShareKind::Screen { |
| 805 | "Test screen" |
| 806 | } else { |
| 807 | "Test window" |
| 808 | } |
| 809 | .into(), |
| 810 | }; |
| 811 | let _ = commands.send(CallCommand::StartShare(source)); |
| 812 | return Ok(()); |
| 813 | } |
| 814 | self.portal_generation = self.portal_generation.wrapping_add(1); |
| 815 | let generation = self.portal_generation; |
| 816 | self.portal_armed = false; |
| 817 | self.portal_keep = false; |
| 818 | self.portal_bound = false; |
| 819 | self.screen.capture = None; |
| 820 | let mut sink = self.screen_sink(); |
| 821 | let updates = self.updates.clone(); |
| 822 | let capture = start_portal_capture( |
| 823 | kind, |
| 824 | self.share_fps.clone(), |
| 825 | move |buffer| sink.push(buffer), |
| 826 | move |follow| match follow { |
| 827 | PortalFollowUp::Share(source) => { |
| 828 | let _ = commands.send(CallCommand::FinishPortalShare { source, generation }); |
| 829 | } |
| 830 | PortalFollowUp::Quiet => { |
| 831 | let _ = commands.send(CallCommand::AbandonPortalShare); |
| 832 | } |
| 833 | PortalFollowUp::Notice(text) => { |
| 834 | let _ = updates.send(CallUpdate::Notice(text.to_owned())); |
| 835 | let _ = commands.send(CallCommand::AbandonPortalShare); |
| 836 | } |
| 837 | }, |
| 838 | )?; |
| 839 | self.portal_armed = true; |
| 840 | self.screen.capture = Some(capture); |
| 841 | Ok(()) |
| 842 | } |
| 843 | |
| 844 | pub fn start_share(&mut self, source: &ShareSource) -> Result<()> { |
| 845 | let lines = self |
| 846 | .lines |
| 847 | .as_ref() |
| 848 | .ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?; |
| 849 | let share = lines |
| 850 | .share |
| 851 | .as_ref() |
| 852 | .ok_or_else(|| Error::Webrtc("sharing needs a meeting".into()))?; |
| 853 | if !self.is_available() { |
| 854 | return Err(Error::Webrtc("video is switched off".into())); |
| 855 | } |
| 856 | let keep = std::mem::take(&mut self.portal_keep) || self.portal_bound; |
| 857 | if !keep { |
| 858 | self.portal_armed = false; |
| 859 | self.portal_generation = self.portal_generation.wrapping_add(1); |
| 860 | self.screen.capture = None; |
| 861 | let mut sink = self.screen_sink(); |
| 862 | let capture = match self.mode { |
| 863 | VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Screen, None)), |
| 864 | _ => start_screen_capture( |
| 865 | source.clone(), |
| 866 | self.share_fps.clone(), |
| 867 | move |buffer| sink.push(buffer), |
| 868 | self.report_failure( |
| 869 | SCREEN_SHARE_STOPPED_NOTICE, |
| 870 | &self.share_generation, |
| 871 | CallCommand::StopShare, |
| 872 | ), |
| 873 | )?, |
| 874 | }; |
| 875 | self.screen.capture = Some(capture); |
| 876 | } |
| 877 | Self::begin_sending_on(&share, &self.screen.track)?; |
| 878 | let _ = self.tune_share(&share.sender()); |
| 879 | Ok(()) |
| 880 | } |
| 881 | |
| 882 | pub fn stop_share(&mut self) { |
| 883 | self.share_generation.fetch_add(1, Ordering::SeqCst); |
| 884 | self.portal_generation = self.portal_generation.wrapping_add(1); |
| 885 | self.portal_armed = false; |
| 886 | self.portal_keep = false; |
| 887 | self.portal_bound = false; |
| 888 | self.screen.capture = None; |
| 889 | self.hub.forget(&VideoKey::LocalScreen); |
| 890 | if let Some(share) = self.lines.as_ref().and_then(|lines| lines.share.as_ref()) { |
| 891 | let _ = Self::set_active(&share.sender(), false); |
| 892 | } |
| 893 | } |
| 894 | |
| 895 | pub fn stop_all(&mut self) { |
| 896 | self.stop_camera(); |
| 897 | self.stop_share(); |
| 898 | } |
| 899 | } |
| 900 | |
| 901 | #[cfg(test)] |
| 902 | mod tests { |
| 903 | use super::*; |
| 904 | use libwebrtc::MediaType; |
| 905 | use libwebrtc::peer_connection_factory::RtcConfiguration; |
| 906 | use libwebrtc::rtp_transceiver::{RtpTransceiverDirection, RtpTransceiverInit}; |
| 907 | |
| 908 | #[tokio::test] |
| 909 | async fn a_camera_preview_runs_without_a_line_and_stops_cleanly() { |
| 910 | let (sender, _receiver) = tokio::sync::mpsc::unbounded_channel(); |
| 911 | let factory = crate::devices::shared_factory(); |
| 912 | let mut video = LocalVideo::new( |
| 913 | &factory, |
| 914 | VideoMode::Pattern, |
| 915 | VideoHub::new(sender.clone()), |
| 916 | sender, |
| 917 | ); |
| 918 | video.preview_camera(&DeviceChoice::SystemDefault).unwrap(); |
| 919 | assert!(video.camera_previewing() && !video.camera_on()); |
| 920 | assert!( |
| 921 | video.start_camera(&DeviceChoice::SystemDefault).is_err(), |
| 922 | "sending needs a negotiated line" |
| 923 | ); |
| 924 | assert!(video.camera_previewing()); |
| 925 | video.stop_camera(); |
| 926 | assert!(!video.camera_previewing() && !video.camera_on()); |
| 927 | } |
| 928 | |
| 929 | #[tokio::test] |
| 930 | async fn clearing_a_sender_track_does_not_crash() { |
| 931 | let factory = crate::devices::shared_factory(); |
| 932 | let peer = factory |
| 933 | .create_peer_connection(RtcConfiguration::default()) |
| 934 | .expect("peer"); |
| 935 | let transceiver = peer |
| 936 | .add_transceiver_for_media( |
| 937 | MediaType::Video, |
| 938 | RtpTransceiverInit { |
| 939 | direction: RtpTransceiverDirection::SendRecv, |
| 940 | stream_ids: vec!["camera".into()], |
| 941 | send_encodings: Vec::new(), |
| 942 | }, |
| 943 | ) |
| 944 | .expect("transceiver"); |
| 945 | let (updates, _) = tokio::sync::mpsc::unbounded_channel(); |
| 946 | let video = LocalVideo::new( |
| 947 | &factory, |
| 948 | VideoMode::Pattern, |
| 949 | VideoHub::new(updates.clone()), |
| 950 | updates, |
| 951 | ); |
| 952 | let sender = transceiver.sender(); |
| 953 | sender |
| 954 | .set_track(Some( |
| 955 | libwebrtc::media_stream_track::MediaStreamTrack::Video(video.camera_track()), |
| 956 | )) |
| 957 | .expect("attach"); |
| 958 | // Do not call sender.track() afterwards: the FFI track() wrapper crashes on a null |
| 959 | // webrtc track (get_or_create_media_stream_track). |
| 960 | sender.set_track(None).expect("detach must accept nullptr"); |
| 961 | peer.close(); |
| 962 | } |
| 963 | |
| 964 | #[test] |
| 965 | fn frame_sizes_survive_packing() { |
| 966 | assert_eq!(unpack_size(pack_size(1280, 720)), Some((1280, 720))); |
| 967 | assert_eq!(unpack_size(0), None); |
| 968 | } |
| 969 | |
| 970 | #[test] |
| 971 | fn the_video_mode_follows_the_environment_value() { |
| 972 | assert_eq!(VideoMode::parse(None), VideoMode::Platform); |
| 973 | assert_eq!(VideoMode::parse(Some("Pattern")), VideoMode::Pattern); |
| 974 | assert_eq!(VideoMode::parse(Some("off")), VideoMode::Off); |
| 975 | assert_eq!(VideoMode::parse(Some("whatever")), VideoMode::Platform); |
| 976 | } |
| 977 | } |