| 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 | camera: Outgoing, |
| 200 | screen: Outgoing, |
| 201 | lines: Option<VideoLines>, |
| 202 | blur: Arc<BlurSettings>, |
| 203 | motion: bool, |
| 204 | share_fps: Arc<AtomicU32>, |
| 205 | camera_preview: bool, |
| 206 | quality: VideoQuality, |
| 207 | camera_stats: Arc<CameraCaptureStats>, |
| 208 | timeline: Option<Timeline>, |
| 209 | portal_generation: u64, |
| 210 | portal_armed: bool, |
| 211 | portal_keep: bool, |
| 212 | /// The desktop dialog already bound the PipeWire stream. Later `StartShare` |
| 213 | /// commands must attach that capturer, not replace it. |
| 214 | portal_bound: bool, |
| 215 | } |
| 216 | |
| 217 | impl LocalVideo { |
| 218 | pub fn new( |
| 219 | factory: &PeerConnectionFactory, |
| 220 | mode: VideoMode, |
| 221 | hub: Arc<VideoHub>, |
| 222 | updates: UnboundedSender<CallUpdate>, |
| 223 | ) -> Self { |
| 224 | LocalVideo { |
| 225 | mode, |
| 226 | hub, |
| 227 | updates, |
| 228 | camera: Outgoing::new(factory, CAMERA_LABEL, PatternKind::Camera, false), |
| 229 | screen: Outgoing::new(factory, SCREEN_LABEL, PatternKind::Screen, true), |
| 230 | lines: None, |
| 231 | blur: Arc::new(BlurSettings::default()), |
| 232 | motion: false, |
| 233 | share_fps: Arc::new(AtomicU32::new(SCREEN_SHARE_FPS)), |
| 234 | camera_preview: false, |
| 235 | quality: VideoQuality::default(), |
| 236 | camera_stats: CameraCaptureStats::new(), |
| 237 | timeline: None, |
| 238 | portal_generation: 0, |
| 239 | portal_armed: false, |
| 240 | portal_keep: false, |
| 241 | portal_bound: false, |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | pub fn attach_timeline(&mut self, timeline: Timeline) { |
| 246 | self.timeline = Some(timeline); |
| 247 | } |
| 248 | |
| 249 | pub fn video_quality(&self) -> VideoQuality { |
| 250 | self.quality |
| 251 | } |
| 252 | |
| 253 | pub fn set_video_quality(&mut self, quality: VideoQuality) { |
| 254 | self.quality = quality; |
| 255 | } |
| 256 | |
| 257 | pub fn set_motion(&mut self, motion: bool) { |
| 258 | self.motion = motion; |
| 259 | self.share_fps.store( |
| 260 | if motion { |
| 261 | MOTION_SHARE_FPS |
| 262 | } else { |
| 263 | SCREEN_SHARE_FPS |
| 264 | }, |
| 265 | Ordering::Relaxed, |
| 266 | ); |
| 267 | if let Some(share) = self |
| 268 | .lines |
| 269 | .as_ref() |
| 270 | .and_then(|lines| lines.share.as_ref()) |
| 271 | .filter(|_| self.sharing()) |
| 272 | { |
| 273 | let _ = self.tune_share(&share.sender()); |
| 274 | } |
| 275 | } |
| 276 | |
| 277 | pub fn set_standout(&self, standout: bool) { |
| 278 | self.blur.set_standout(standout); |
| 279 | } |
| 280 | |
| 281 | fn tune_share(&self, sender: &RtpSender) -> Result<()> { |
| 282 | let mut parameters = sender.parameters(); |
| 283 | parameters.set_degradation_preference(if self.motion { |
| 284 | DegradationPreference::MaintainFramerate |
| 285 | } else { |
| 286 | DegradationPreference::MaintainResolution |
| 287 | }); |
| 288 | let fps = f64::from(self.share_fps.load(Ordering::Relaxed)); |
| 289 | for encoding in &mut parameters.encodings { |
| 290 | encoding.max_framerate = Some(fps); |
| 291 | } |
| 292 | sender |
| 293 | .set_parameters(parameters) |
| 294 | .map_err(|error| Error::Webrtc(error.to_string())) |
| 295 | } |
| 296 | |
| 297 | fn sender_of(&self, source: SendSource) -> Option<RtpSender> { |
| 298 | let lines = self.lines.as_ref()?; |
| 299 | match source { |
| 300 | SendSource::Camera => Some(lines.camera.sender()), |
| 301 | SendSource::Screen => lines.share.as_ref().map(|share| share.sender()), |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | pub fn apply_send_limit( |
| 306 | &mut self, |
| 307 | source: SendSource, |
| 308 | limits: &[SendLimit], |
| 309 | ) -> Result<Option<Vec<LayerPlan>>> { |
| 310 | let sending = match source { |
| 311 | SendSource::Camera => self.camera_on(), |
| 312 | SendSource::Screen => self.sharing(), |
| 313 | }; |
| 314 | let Some(sender) = self.sender_of(source).filter(|_| sending) else { |
| 315 | return Ok(None); |
| 316 | }; |
| 317 | let outgoing = match source { |
| 318 | SendSource::Camera => &mut self.camera, |
| 319 | SendSource::Screen => &mut self.screen, |
| 320 | }; |
| 321 | let frame = unpack_size(outgoing.frame_size.load(Ordering::Relaxed)); |
| 322 | outgoing.requested = Some(RequestedLimits { |
| 323 | limits: limits.to_vec(), |
| 324 | applied_for: frame, |
| 325 | }); |
| 326 | let rids: Vec<String> = sender |
| 327 | .parameters() |
| 328 | .encodings |
| 329 | .into_iter() |
| 330 | .map(|encoding| encoding.rid) |
| 331 | .collect(); |
| 332 | if rids.len() > 1 { |
| 333 | let plans = plan_layers(limits, frame, &rids); |
| 334 | if plans.iter().any(|plan| plan.keyframe) { |
| 335 | Self::set_layers(&sender, &plans, KEYFRAME_NUDGE)?; |
| 336 | } |
| 337 | Self::set_layers(&sender, &plans, 1.0)?; |
| 338 | return Ok(Some(plans)); |
| 339 | } |
| 340 | let Some(limit) = limits.first() else { |
| 341 | return Ok(None); |
| 342 | }; |
| 343 | let encoder = encoder_limits(limit, frame); |
| 344 | if limit.keyframe { |
| 345 | Self::set_limits(&sender, &encoder, KEYFRAME_NUDGE)?; |
| 346 | } |
| 347 | Self::set_limits(&sender, &encoder, 1.0)?; |
| 348 | Ok(Some(vec![LayerPlan { |
| 349 | rid: rids.into_iter().next().unwrap_or_default(), |
| 350 | active: true, |
| 351 | limits: Some(encoder), |
| 352 | keyframe: limit.keyframe, |
| 353 | }])) |
| 354 | } |
| 355 | |
| 356 | /// The mixer sends its limits once, often before the first frame tells the size to scale from. |
| 357 | pub fn refresh_send_limits(&mut self) -> Vec<(SendSource, Result<Option<Vec<LayerPlan>>>)> { |
| 358 | let mut refreshed = Vec::new(); |
| 359 | for source in [SendSource::Camera, SendSource::Screen] { |
| 360 | let outgoing = match source { |
| 361 | SendSource::Camera => &self.camera, |
| 362 | SendSource::Screen => &self.screen, |
| 363 | }; |
| 364 | let frame = unpack_size(outgoing.frame_size.load(Ordering::Relaxed)); |
| 365 | let Some(requested) = outgoing |
| 366 | .requested |
| 367 | .as_ref() |
| 368 | .filter(|requested| frame.is_some() && requested.applied_for != frame) |
| 369 | else { |
| 370 | continue; |
| 371 | }; |
| 372 | let limits = requested.limits.clone(); |
| 373 | refreshed.push((source, self.apply_send_limit(source, &limits))); |
| 374 | } |
| 375 | refreshed |
| 376 | } |
| 377 | |
| 378 | fn set_layers(sender: &RtpSender, plans: &[LayerPlan], nudge: f64) -> Result<()> { |
| 379 | let mut parameters = sender.parameters(); |
| 380 | for encoding in &mut parameters.encodings { |
| 381 | let Some(plan) = plans.iter().find(|plan| plan.rid == encoding.rid) else { |
| 382 | continue; |
| 383 | }; |
| 384 | let nudged = nudge != 1.0 && plan.keyframe; |
| 385 | encoding.active = plan.active; |
| 386 | let Some(limits) = &plan.limits else { continue }; |
| 387 | encoding.scale_resolution_down_by = |
| 388 | Some(limits.scale_down_by * if nudged { nudge } else { 1.0 }); |
| 389 | if let Some(framerate) = limits.max_framerate { |
| 390 | encoding.max_framerate = Some(framerate); |
| 391 | } |
| 392 | encoding.max_bitrate = limits.max_bitrate; |
| 393 | } |
| 394 | sender |
| 395 | .set_parameters(parameters) |
| 396 | .map_err(|error| Error::Webrtc(error.to_string())) |
| 397 | } |
| 398 | |
| 399 | fn set_limits(sender: &RtpSender, limits: &EncoderLimits, nudge: f64) -> Result<()> { |
| 400 | let mut parameters = sender.parameters(); |
| 401 | for encoding in &mut parameters.encodings { |
| 402 | encoding.scale_resolution_down_by = Some(limits.scale_down_by * nudge); |
| 403 | if let Some(framerate) = limits.max_framerate { |
| 404 | encoding.max_framerate = Some(framerate); |
| 405 | } |
| 406 | encoding.max_bitrate = limits.max_bitrate; |
| 407 | } |
| 408 | sender |
| 409 | .set_parameters(parameters) |
| 410 | .map_err(|error| Error::Webrtc(error.to_string())) |
| 411 | } |
| 412 | |
| 413 | pub fn camera_size(&self) -> Option<(u32, u32)> { |
| 414 | unpack_size(self.camera.frame_size.load(Ordering::Relaxed)).filter(|_| self.camera_on()) |
| 415 | } |
| 416 | |
| 417 | pub fn set_background(&self, enabled: bool, picture: Option<Arc<BackgroundPicture>>) { |
| 418 | self.blur.set_picture(picture); |
| 419 | self.blur.set_enabled(enabled); |
| 420 | } |
| 421 | |
| 422 | pub fn set_effects(&self, effects: CameraEffects) { |
| 423 | self.blur.set_effects(effects); |
| 424 | } |
| 425 | |
| 426 | pub fn camera_track(&self) -> RtcVideoTrack { |
| 427 | self.camera.track.clone() |
| 428 | } |
| 429 | |
| 430 | pub fn blur_average_ms(&self) -> Option<f32> { |
| 431 | (self.camera_on() && self.blur.active()).then(|| self.blur.average_ms()) |
| 432 | } |
| 433 | |
| 434 | pub fn blur_model(&self) -> Option<&'static str> { |
| 435 | (self.camera_on() && self.blur.active()) |
| 436 | .then(|| self.blur.model()) |
| 437 | .filter(|model| !model.is_empty()) |
| 438 | } |
| 439 | |
| 440 | pub fn has_lines(&self) -> bool { |
| 441 | self.lines.is_some() |
| 442 | } |
| 443 | |
| 444 | pub fn share_mid(&self) -> Option<String> { |
| 445 | self.lines |
| 446 | .as_ref() |
| 447 | .and_then(|lines| lines.share.as_ref()) |
| 448 | .and_then(|share| share.mid()) |
| 449 | } |
| 450 | |
| 451 | pub fn has_share_line(&self) -> bool { |
| 452 | self.lines |
| 453 | .as_ref() |
| 454 | .is_some_and(|lines| lines.share.is_some()) |
| 455 | } |
| 456 | |
| 457 | pub fn add_share_line( |
| 458 | &mut self, |
| 459 | share: RtpTransceiver, |
| 460 | camera: Option<RtpTransceiver>, |
| 461 | ) -> Result<()> { |
| 462 | match (self.lines.as_mut(), camera) { |
| 463 | (Some(lines), _) => lines.share = Some(share), |
| 464 | (None, Some(camera)) => { |
| 465 | self.lines = Some(VideoLines { |
| 466 | camera, |
| 467 | share: Some(share), |
| 468 | }) |
| 469 | } |
| 470 | (None, None) => return Err(Error::Webrtc("no video line negotiated".into())), |
| 471 | } |
| 472 | Ok(()) |
| 473 | } |
| 474 | |
| 475 | pub fn share_sending(&self) -> bool { |
| 476 | self.lines |
| 477 | .as_ref() |
| 478 | .and_then(|lines| lines.share.as_ref()) |
| 479 | .and_then(|share| share.current_direction()) |
| 480 | .is_some_and(|direction| { |
| 481 | matches!( |
| 482 | direction, |
| 483 | RtpTransceiverDirection::SendOnly | RtpTransceiverDirection::SendRecv |
| 484 | ) |
| 485 | }) |
| 486 | } |
| 487 | |
| 488 | pub fn is_available(&self) -> bool { |
| 489 | self.mode != VideoMode::Off |
| 490 | } |
| 491 | |
| 492 | pub fn camera_on(&self) -> bool { |
| 493 | self.camera.capture.is_some() && !self.camera_preview |
| 494 | } |
| 495 | |
| 496 | pub fn camera_previewing(&self) -> bool { |
| 497 | self.camera.capture.is_some() && self.camera_preview |
| 498 | } |
| 499 | |
| 500 | pub fn sharing(&self) -> bool { |
| 501 | self.screen.capture.is_some() |
| 502 | } |
| 503 | |
| 504 | pub fn portal_is_open(&self) -> bool { |
| 505 | self.portal_armed |
| 506 | } |
| 507 | |
| 508 | pub fn set_lines(&mut self, lines: VideoLines) -> Result<()> { |
| 509 | if self.camera_on() { |
| 510 | Self::begin_sending(&lines.camera.sender(), &self.camera.track)?; |
| 511 | } |
| 512 | if self.sharing() |
| 513 | && let Some(share) = &lines.share |
| 514 | { |
| 515 | Self::begin_sending(&share.sender(), &self.screen.track)?; |
| 516 | } |
| 517 | self.lines = Some(lines); |
| 518 | Ok(()) |
| 519 | } |
| 520 | |
| 521 | fn begin_sending(sender: &RtpSender, track: &RtcVideoTrack) -> Result<()> { |
| 522 | sender |
| 523 | .set_track(Some(MediaStreamTrack::Video(track.clone()))) |
| 524 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 525 | Self::set_active(sender, true) |
| 526 | } |
| 527 | |
| 528 | fn set_active(sender: &RtpSender, active: bool) -> Result<()> { |
| 529 | let mut parameters = sender.parameters(); |
| 530 | for encoding in &mut parameters.encodings { |
| 531 | encoding.active = active; |
| 532 | } |
| 533 | sender |
| 534 | .set_parameters(parameters) |
| 535 | .map_err(|error| Error::Webrtc(error.to_string())) |
| 536 | } |
| 537 | |
| 538 | fn camera_sink(&self) -> LocalSink { |
| 539 | LocalSink::new( |
| 540 | self.camera.source.clone(), |
| 541 | Some((self.hub.clone(), VideoKey::LocalCamera)), |
| 542 | ) |
| 543 | .mirrored_by(self.blur.clone()) |
| 544 | .reporting_size(self.camera.frame_size.clone()) |
| 545 | } |
| 546 | |
| 547 | /// Local share frames go to the encoder and to the window in the chat. |
| 548 | fn screen_sink(&self) -> LocalSink { |
| 549 | LocalSink::new( |
| 550 | self.screen.source.clone(), |
| 551 | Some((self.hub.clone(), VideoKey::LocalScreen)), |
| 552 | ) |
| 553 | .with_standout(self.blur.clone()) |
| 554 | .reporting_size(self.screen.frame_size.clone()) |
| 555 | } |
| 556 | |
| 557 | fn report_failure(&self, notice_key: &'static str) -> impl FnOnce(String) + Send + 'static { |
| 558 | let updates = self.updates.clone(); |
| 559 | move |reason| { |
| 560 | let _ = updates.send(CallUpdate::Notice(notice_with_detail(notice_key, reason))); |
| 561 | } |
| 562 | } |
| 563 | |
| 564 | pub fn preview_camera(&mut self, choice: &DeviceChoice) -> Result<()> { |
| 565 | if !self.is_available() { |
| 566 | return Err(Error::Webrtc("video is switched off".into())); |
| 567 | } |
| 568 | self.camera.capture = None; |
| 569 | self.camera.capture = Some(self.capture_camera(choice)?); |
| 570 | self.camera_preview = true; |
| 571 | Ok(()) |
| 572 | } |
| 573 | |
| 574 | pub fn start_camera(&mut self, choice: &DeviceChoice) -> Result<()> { |
| 575 | let lines = self |
| 576 | .lines |
| 577 | .as_ref() |
| 578 | .ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?; |
| 579 | if !self.is_available() { |
| 580 | return Err(Error::Webrtc("video is switched off".into())); |
| 581 | } |
| 582 | let sender = lines.camera.sender(); |
| 583 | if !self.camera_previewing() { |
| 584 | self.camera.capture = None; |
| 585 | self.camera.capture = Some(self.capture_camera(choice)?); |
| 586 | } |
| 587 | Self::begin_sending(&sender, &self.camera.track)?; |
| 588 | self.camera_preview = false; |
| 589 | Ok(()) |
| 590 | } |
| 591 | |
| 592 | pub fn camera_capture_summary(&self) -> Option<String> { |
| 593 | self.camera_stats.summary() |
| 594 | } |
| 595 | |
| 596 | fn capture_camera(&self, choice: &DeviceChoice) -> Result<Capture> { |
| 597 | let mut sink = self.camera_sink(); |
| 598 | Ok(match self.mode { |
| 599 | VideoMode::Pattern => Capture::Task(spawn_pattern( |
| 600 | sink, |
| 601 | PatternKind::Camera, |
| 602 | Some(self.blur.clone()), |
| 603 | )), |
| 604 | _ => { |
| 605 | let timeline = self.timeline.clone(); |
| 606 | start_camera( |
| 607 | choice, |
| 608 | self.quality, |
| 609 | self.blur.clone(), |
| 610 | self.camera_stats.clone(), |
| 611 | move |label| { |
| 612 | if let Some(timeline) = timeline { |
| 613 | timeline.record("camera capture", label); |
| 614 | } else { |
| 615 | eprintln!("calls: camera capture {label}"); |
| 616 | } |
| 617 | }, |
| 618 | move |buffer| sink.push(buffer), |
| 619 | self.report_failure(CAMERA_STOPPED_NOTICE), |
| 620 | )? |
| 621 | } |
| 622 | }) |
| 623 | } |
| 624 | |
| 625 | /// Restart capture with the current quality if the camera is already running. |
| 626 | pub fn refresh_camera_capture(&mut self, choice: &DeviceChoice) -> Result<()> { |
| 627 | if self.camera.capture.is_none() { |
| 628 | return Ok(()); |
| 629 | } |
| 630 | let preview = self.camera_preview; |
| 631 | self.camera.capture = None; |
| 632 | self.camera.capture = Some(self.capture_camera(choice)?); |
| 633 | self.camera_preview = preview; |
| 634 | if !preview { |
| 635 | if let Some(lines) = self.lines.as_ref() { |
| 636 | Self::begin_sending(&lines.camera.sender(), &self.camera.track)?; |
| 637 | } |
| 638 | } |
| 639 | Ok(()) |
| 640 | } |
| 641 | |
| 642 | pub fn stop_camera(&mut self) { |
| 643 | self.camera_preview = false; |
| 644 | self.camera.capture = None; |
| 645 | self.blur.set_cutout(None); |
| 646 | if let Some(lines) = &self.lines { |
| 647 | let _ = Self::set_active(&lines.camera.sender(), false); |
| 648 | } |
| 649 | self.hub.forget(&VideoKey::LocalCamera); |
| 650 | } |
| 651 | |
| 652 | pub fn accept_portal(&mut self, generation: u64) -> bool { |
| 653 | if self.portal_armed && self.portal_generation == generation { |
| 654 | self.portal_armed = false; |
| 655 | self.portal_keep = true; |
| 656 | self.portal_bound = true; |
| 657 | true |
| 658 | } else { |
| 659 | false |
| 660 | } |
| 661 | } |
| 662 | |
| 663 | pub fn open_portal( |
| 664 | &mut self, |
| 665 | kind: ShareKind, |
| 666 | commands: UnboundedSender<CallCommand>, |
| 667 | ) -> Result<()> { |
| 668 | if !self.is_available() { |
| 669 | return Err(Error::Webrtc("video is switched off".into())); |
| 670 | } |
| 671 | if self.mode == VideoMode::Pattern { |
| 672 | let source = ShareSource { |
| 673 | id: if kind == ShareKind::Screen { 1 } else { 2 }, |
| 674 | kind, |
| 675 | title: if kind == ShareKind::Screen { |
| 676 | "Test screen" |
| 677 | } else { |
| 678 | "Test window" |
| 679 | } |
| 680 | .into(), |
| 681 | }; |
| 682 | let _ = commands.send(CallCommand::StartShare(source)); |
| 683 | return Ok(()); |
| 684 | } |
| 685 | self.portal_generation = self.portal_generation.wrapping_add(1); |
| 686 | let generation = self.portal_generation; |
| 687 | self.portal_armed = false; |
| 688 | self.portal_keep = false; |
| 689 | self.portal_bound = false; |
| 690 | self.screen.capture = None; |
| 691 | let mut sink = self.screen_sink(); |
| 692 | let updates = self.updates.clone(); |
| 693 | let capture = start_portal_capture( |
| 694 | kind, |
| 695 | self.share_fps.clone(), |
| 696 | move |buffer| sink.push(buffer), |
| 697 | move |follow| match follow { |
| 698 | PortalFollowUp::Share(source) => { |
| 699 | let _ = commands.send(CallCommand::FinishPortalShare { source, generation }); |
| 700 | } |
| 701 | PortalFollowUp::Quiet => { |
| 702 | let _ = commands.send(CallCommand::AbandonPortalShare); |
| 703 | } |
| 704 | PortalFollowUp::Notice(text) => { |
| 705 | let _ = updates.send(CallUpdate::Notice(text.to_owned())); |
| 706 | let _ = commands.send(CallCommand::AbandonPortalShare); |
| 707 | } |
| 708 | }, |
| 709 | )?; |
| 710 | self.portal_armed = true; |
| 711 | self.screen.capture = Some(capture); |
| 712 | Ok(()) |
| 713 | } |
| 714 | |
| 715 | pub fn start_share(&mut self, source: &ShareSource) -> Result<()> { |
| 716 | let lines = self |
| 717 | .lines |
| 718 | .as_ref() |
| 719 | .ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?; |
| 720 | let share = lines |
| 721 | .share |
| 722 | .as_ref() |
| 723 | .ok_or_else(|| Error::Webrtc("sharing needs a meeting".into()))?; |
| 724 | if !self.is_available() { |
| 725 | return Err(Error::Webrtc("video is switched off".into())); |
| 726 | } |
| 727 | let keep = std::mem::take(&mut self.portal_keep) || self.portal_bound; |
| 728 | if !keep { |
| 729 | self.portal_armed = false; |
| 730 | self.portal_generation = self.portal_generation.wrapping_add(1); |
| 731 | self.screen.capture = None; |
| 732 | let mut sink = self.screen_sink(); |
| 733 | let capture = match self.mode { |
| 734 | VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Screen, None)), |
| 735 | _ => start_screen_capture( |
| 736 | source.clone(), |
| 737 | self.share_fps.clone(), |
| 738 | move |buffer| sink.push(buffer), |
| 739 | self.report_failure(SCREEN_SHARE_STOPPED_NOTICE), |
| 740 | )?, |
| 741 | }; |
| 742 | self.screen.capture = Some(capture); |
| 743 | } |
| 744 | Self::begin_sending(&share.sender(), &self.screen.track)?; |
| 745 | let _ = self.tune_share(&share.sender()); |
| 746 | Ok(()) |
| 747 | } |
| 748 | |
| 749 | pub fn stop_share(&mut self) { |
| 750 | self.portal_generation = self.portal_generation.wrapping_add(1); |
| 751 | self.portal_armed = false; |
| 752 | self.portal_keep = false; |
| 753 | self.portal_bound = false; |
| 754 | self.screen.capture = None; |
| 755 | self.hub.forget(&VideoKey::LocalScreen); |
| 756 | if let Some(share) = self.lines.as_ref().and_then(|lines| lines.share.as_ref()) { |
| 757 | let _ = Self::set_active(&share.sender(), false); |
| 758 | } |
| 759 | } |
| 760 | |
| 761 | pub fn stop_all(&mut self) { |
| 762 | self.stop_camera(); |
| 763 | self.stop_share(); |
| 764 | } |
| 765 | } |
| 766 | |
| 767 | #[cfg(test)] |
| 768 | mod tests { |
| 769 | use super::*; |
| 770 | |
| 771 | #[tokio::test] |
| 772 | async fn a_camera_preview_runs_without_a_line_and_stops_cleanly() { |
| 773 | let (sender, _receiver) = tokio::sync::mpsc::unbounded_channel(); |
| 774 | let factory = crate::devices::shared_factory(); |
| 775 | let mut video = LocalVideo::new( |
| 776 | &factory, |
| 777 | VideoMode::Pattern, |
| 778 | VideoHub::new(sender.clone()), |
| 779 | sender, |
| 780 | ); |
| 781 | video.preview_camera(&DeviceChoice::SystemDefault).unwrap(); |
| 782 | assert!(video.camera_previewing() && !video.camera_on()); |
| 783 | assert!( |
| 784 | video.start_camera(&DeviceChoice::SystemDefault).is_err(), |
| 785 | "sending needs a negotiated line" |
| 786 | ); |
| 787 | assert!(video.camera_previewing()); |
| 788 | video.stop_camera(); |
| 789 | assert!(!video.camera_previewing() && !video.camera_on()); |
| 790 | } |
| 791 | |
| 792 | #[test] |
| 793 | fn frame_sizes_survive_packing() { |
| 794 | assert_eq!(unpack_size(pack_size(1280, 720)), Some((1280, 720))); |
| 795 | assert_eq!(unpack_size(0), None); |
| 796 | } |
| 797 | |
| 798 | #[test] |
| 799 | fn the_video_mode_follows_the_environment_value() { |
| 800 | assert_eq!(VideoMode::parse(None), VideoMode::Platform); |
| 801 | assert_eq!(VideoMode::parse(Some("Pattern")), VideoMode::Pattern); |
| 802 | assert_eq!(VideoMode::parse(Some("off")), VideoMode::Off); |
| 803 | assert_eq!(VideoMode::parse(Some("whatever")), VideoMode::Platform); |
| 804 | } |
| 805 | } |