BlueGit

ict rusty-teams

Files

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

video_send.rs

video_send.rs 33.8 KiB Download Raw
1use std::sync::Arc;
2use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
3use std::time::{Instant, SystemTime, UNIX_EPOCH};
4
5use libwebrtc::media_stream_track::MediaStreamTrack;
6use libwebrtc::peer_connection_factory::PeerConnectionFactory;
7use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
8use libwebrtc::rtp_parameters::DegradationPreference;
9use libwebrtc::rtp_sender::RtpSender;
10use libwebrtc::rtp_transceiver::{RtpTransceiver, RtpTransceiverDirection};
11use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _, VideoFrame, VideoRotation};
12use libwebrtc::video_source::VideoResolution;
13use libwebrtc::video_source::native::NativeVideoSource;
14use libwebrtc::video_track::RtcVideoTrack;
15use tokio::sync::mpsc::UnboundedSender;
16
17use crate::background::BackgroundPicture;
18use crate::blur::BlurSettings;
19use crate::camera::{CameraCaptureStats, start_camera};
20use crate::capture::Capture;
21use crate::control::{CallCommand, CallUpdate};
22use crate::devices::DeviceChoice;
23use crate::effects::CameraEffects;
24use crate::error::{Error, Result};
25use crate::notices::{CAMERA_STOPPED_NOTICE, SCREEN_SHARE_STOPPED_NOTICE, notice_with_detail};
26use crate::screen::{
27 PortalFollowUp, ShareKind, ShareSource, start_portal_capture, start_screen_capture,
28};
29use crate::send_control::{
30 EncoderLimits, KEYFRAME_NUDGE, LayerPlan, SendLimit, encoder_limits, plan_layers,
31};
32use crate::standout::StandoutOverlay;
33use crate::timeline::Timeline;
34use crate::video_frame::{
35 FrameGate, PERSON_FPS, SCREEN_FPS, VideoHub, VideoKey, picture_from_i420,
36};
37use crate::video_layout::VideoLines;
38use crate::video_pattern::{PatternKind, spawn_pattern};
39use crate::video_quality::VideoQuality;
40
41pub const VIDEO_MODE_ENV: &str = "CALLING_VIDEO";
42const CAMERA_LABEL: &str = "camera";
43const SCREEN_LABEL: &str = "screen";
44pub const SCREEN_SHARE_FPS: u32 = 15;
45pub const MOTION_SHARE_FPS: u32 = 30;
46
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
48pub enum VideoMode {
49 #[default]
50 Platform,
51 Pattern,
52 Off,
53}
54
55impl 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.
70pub 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
78impl 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
146fn pack_size(width: u32, height: u32) -> u64 {
147 (u64::from(width) << 32) | u64::from(height)
148}
149
150fn 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)]
156pub enum SendSource {
157 Camera,
158 Screen,
159}
160
161struct Outgoing {
162 source: NativeVideoSource,
163 track: RtcVideoTrack,
164 capture: Option<Capture>,
165 frame_size: Arc<AtomicU64>,
166 requested: Option<RequestedLimits>,
167}
168
169struct RequestedLimits {
170 limits: Vec<SendLimit>,
171 applied_for: Option<(u32, u32)>,
172}
173
174impl 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.
195pub 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
221impl 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 report = self.report_end(notice_key, generation, switch_off);
676 move |reason| report(Some(reason))
677 }
678
679 /// Like `report_failure`, but `None` switches off without a notice: the
680 /// user ended it outside the app.
681 fn report_end(
682 &self,
683 notice_key: &'static str,
684 generation: &Arc<AtomicU64>,
685 switch_off: CallCommand,
686 ) -> impl FnOnce(Option<String>) + Send + 'static {
687 let updates = self.updates.clone();
688 let commands = self.commands.clone();
689 let started = generation.fetch_add(1, Ordering::SeqCst) + 1;
690 let generation = generation.clone();
691 move |reason| {
692 if let Some(reason) = reason {
693 let _ = updates.send(CallUpdate::Notice(notice_with_detail(notice_key, reason)));
694 }
695 if generation.load(Ordering::SeqCst) == started
696 && let Some(commands) = commands
697 {
698 let _ = commands.send(switch_off);
699 }
700 }
701 }
702
703 pub fn preview_camera(&mut self, choice: &DeviceChoice) -> Result<()> {
704 if !self.is_available() {
705 return Err(Error::Webrtc("video is switched off".into()));
706 }
707 self.camera.capture = None;
708 self.camera.capture = Some(self.capture_camera(choice)?);
709 self.camera_preview = true;
710 Ok(())
711 }
712
713 pub fn start_camera(&mut self, choice: &DeviceChoice) -> Result<()> {
714 let lines = self
715 .lines
716 .as_ref()
717 .ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?;
718 if !self.is_available() {
719 return Err(Error::Webrtc("video is switched off".into()));
720 }
721 if !self.camera_previewing() {
722 self.camera.capture = None;
723 self.camera.capture = Some(self.capture_camera(choice)?);
724 }
725 Self::begin_sending_on(&lines.camera, &self.camera.track)?;
726 self.camera_preview = false;
727 Ok(())
728 }
729
730 pub fn camera_capture_summary(&self) -> Option<String> {
731 self.camera_stats.summary()
732 }
733
734 fn capture_camera(&self, choice: &DeviceChoice) -> Result<Capture> {
735 let mut sink = self.camera_sink();
736 Ok(match self.mode {
737 VideoMode::Pattern => Capture::Task(spawn_pattern(
738 sink,
739 PatternKind::Camera,
740 Some(self.blur.clone()),
741 )),
742 _ => {
743 let timeline = self.timeline.clone();
744 start_camera(
745 choice,
746 self.quality,
747 self.blur.clone(),
748 self.camera_stats.clone(),
749 move |label| {
750 if let Some(timeline) = timeline {
751 timeline.record("camera capture", label);
752 } else {
753 eprintln!("calls: camera capture {label}");
754 }
755 },
756 move |buffer| sink.push(buffer),
757 self.report_failure(
758 CAMERA_STOPPED_NOTICE,
759 &self.camera_generation,
760 CallCommand::SetCamera(false),
761 ),
762 )?
763 }
764 })
765 }
766
767 /// Restart capture with the current quality if the camera is already running.
768 pub fn refresh_camera_capture(&mut self, choice: &DeviceChoice) -> Result<()> {
769 if self.camera.capture.is_none() {
770 return Ok(());
771 }
772 let preview = self.camera_preview;
773 self.camera.capture = None;
774 self.camera.capture = Some(self.capture_camera(choice)?);
775 self.camera_preview = preview;
776 if !preview {
777 if let Some(lines) = self.lines.as_ref() {
778 Self::begin_sending_on(&lines.camera, &self.camera.track)?;
779 }
780 }
781 Ok(())
782 }
783
784 pub fn stop_camera(&mut self) {
785 self.camera_generation.fetch_add(1, Ordering::SeqCst);
786 self.camera_preview = false;
787 self.camera.capture = None;
788 self.blur.set_cutout(None);
789 if let Some(lines) = &self.lines {
790 let _ = Self::set_active(&lines.camera.sender(), false);
791 }
792 self.hub.forget(&VideoKey::LocalCamera);
793 }
794
795 pub fn accept_portal(&mut self, generation: u64) -> bool {
796 if self.portal_armed && self.portal_generation == generation {
797 self.portal_armed = false;
798 self.portal_keep = true;
799 self.portal_bound = true;
800 true
801 } else {
802 false
803 }
804 }
805
806 pub fn open_portal(
807 &mut self,
808 kind: ShareKind,
809 commands: UnboundedSender<CallCommand>,
810 ) -> Result<()> {
811 if !self.is_available() {
812 return Err(Error::Webrtc("video is switched off".into()));
813 }
814 if self.mode == VideoMode::Pattern {
815 let source = ShareSource {
816 id: if kind == ShareKind::Screen { 1 } else { 2 },
817 kind,
818 title: if kind == ShareKind::Screen {
819 "Test screen"
820 } else {
821 "Test window"
822 }
823 .into(),
824 };
825 let _ = commands.send(CallCommand::StartShare(source));
826 return Ok(());
827 }
828 self.portal_generation = self.portal_generation.wrapping_add(1);
829 let generation = self.portal_generation;
830 self.portal_armed = false;
831 self.portal_keep = false;
832 self.portal_bound = false;
833 self.screen.capture = None;
834 let mut sink = self.screen_sink();
835 let updates = self.updates.clone();
836 // `stop_share` moves the generation on, so only an end the app did not
837 // ask for switches the share off.
838 let ended = self.report_end(
839 SCREEN_SHARE_STOPPED_NOTICE,
840 &self.share_generation,
841 CallCommand::StopShare,
842 );
843 let capture = start_portal_capture(
844 kind,
845 self.share_fps.clone(),
846 move |buffer| sink.push(buffer),
847 move |follow| match follow {
848 PortalFollowUp::Share(source) => {
849 let _ = commands.send(CallCommand::FinishPortalShare { source, generation });
850 }
851 PortalFollowUp::Quiet => {
852 let _ = commands.send(CallCommand::AbandonPortalShare);
853 }
854 PortalFollowUp::Notice(text) => {
855 let _ = updates.send(CallUpdate::Notice(text.to_owned()));
856 let _ = commands.send(CallCommand::AbandonPortalShare);
857 }
858 },
859 ended,
860 )?;
861 self.portal_armed = true;
862 self.screen.capture = Some(capture);
863 Ok(())
864 }
865
866 pub fn start_share(&mut self, source: &ShareSource) -> Result<()> {
867 let lines = self
868 .lines
869 .as_ref()
870 .ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?;
871 let share = lines
872 .share
873 .as_ref()
874 .ok_or_else(|| Error::Webrtc("sharing needs a meeting".into()))?;
875 if !self.is_available() {
876 return Err(Error::Webrtc("video is switched off".into()));
877 }
878 let keep = std::mem::take(&mut self.portal_keep) || self.portal_bound;
879 if !keep {
880 self.portal_armed = false;
881 self.portal_generation = self.portal_generation.wrapping_add(1);
882 self.screen.capture = None;
883 let mut sink = self.screen_sink();
884 let capture = match self.mode {
885 VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Screen, None)),
886 _ => start_screen_capture(
887 source.clone(),
888 self.share_fps.clone(),
889 move |buffer| sink.push(buffer),
890 self.report_end(
891 SCREEN_SHARE_STOPPED_NOTICE,
892 &self.share_generation,
893 CallCommand::StopShare,
894 ),
895 )?,
896 };
897 self.screen.capture = Some(capture);
898 }
899 Self::begin_sending_on(&share, &self.screen.track)?;
900 let _ = self.tune_share(&share.sender());
901 Ok(())
902 }
903
904 pub fn stop_share(&mut self) {
905 self.share_generation.fetch_add(1, Ordering::SeqCst);
906 self.portal_generation = self.portal_generation.wrapping_add(1);
907 self.portal_armed = false;
908 self.portal_keep = false;
909 self.portal_bound = false;
910 self.screen.capture = None;
911 self.hub.forget(&VideoKey::LocalScreen);
912 if let Some(share) = self.lines.as_ref().and_then(|lines| lines.share.as_ref()) {
913 let _ = Self::set_active(&share.sender(), false);
914 }
915 }
916
917 pub fn stop_all(&mut self) {
918 self.stop_camera();
919 self.stop_share();
920 }
921}
922
923#[cfg(test)]
924mod tests {
925 use super::*;
926 use libwebrtc::MediaType;
927 use libwebrtc::peer_connection_factory::RtcConfiguration;
928 use libwebrtc::rtp_transceiver::{RtpTransceiverDirection, RtpTransceiverInit};
929
930 #[tokio::test]
931 async fn a_camera_preview_runs_without_a_line_and_stops_cleanly() {
932 let (sender, _receiver) = tokio::sync::mpsc::unbounded_channel();
933 let factory = crate::devices::shared_factory();
934 let mut video = LocalVideo::new(
935 &factory,
936 VideoMode::Pattern,
937 VideoHub::new(sender.clone()),
938 sender,
939 );
940 video.preview_camera(&DeviceChoice::SystemDefault).unwrap();
941 assert!(video.camera_previewing() && !video.camera_on());
942 assert!(
943 video.start_camera(&DeviceChoice::SystemDefault).is_err(),
944 "sending needs a negotiated line"
945 );
946 assert!(video.camera_previewing());
947 video.stop_camera();
948 assert!(!video.camera_previewing() && !video.camera_on());
949 }
950
951 #[tokio::test]
952 async fn clearing_a_sender_track_does_not_crash() {
953 let factory = crate::devices::shared_factory();
954 let peer = factory
955 .create_peer_connection(RtcConfiguration::default())
956 .expect("peer");
957 let transceiver = peer
958 .add_transceiver_for_media(
959 MediaType::Video,
960 RtpTransceiverInit {
961 direction: RtpTransceiverDirection::SendRecv,
962 stream_ids: vec!["camera".into()],
963 send_encodings: Vec::new(),
964 },
965 )
966 .expect("transceiver");
967 let (updates, _) = tokio::sync::mpsc::unbounded_channel();
968 let video = LocalVideo::new(
969 &factory,
970 VideoMode::Pattern,
971 VideoHub::new(updates.clone()),
972 updates,
973 );
974 let sender = transceiver.sender();
975 sender
976 .set_track(Some(
977 libwebrtc::media_stream_track::MediaStreamTrack::Video(video.camera_track()),
978 ))
979 .expect("attach");
980 // Do not call sender.track() afterwards: the FFI track() wrapper crashes on a null
981 // webrtc track (get_or_create_media_stream_track).
982 sender.set_track(None).expect("detach must accept nullptr");
983 peer.close();
984 }
985
986 #[test]
987 fn frame_sizes_survive_packing() {
988 assert_eq!(unpack_size(pack_size(1280, 720)), Some((1280, 720)));
989 assert_eq!(unpack_size(0), None);
990 }
991
992 #[test]
993 fn the_video_mode_follows_the_environment_value() {
994 assert_eq!(VideoMode::parse(None), VideoMode::Platform);
995 assert_eq!(VideoMode::parse(Some("Pattern")), VideoMode::Pattern);
996 assert_eq!(VideoMode::parse(Some("off")), VideoMode::Off);
997 assert_eq!(VideoMode::parse(Some("whatever")), VideoMode::Platform);
998 }
999}