BlueGit

ict rusty-teams

Files

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

video_send.rs

video_send.rs 33.6 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 /// Optional uplink cap from the bitrate governor (never above mixer max-br).
219 camera_bitrate_cap: Option<u64>,
220}
221
222impl LocalVideo {
223 pub fn new(
224 factory: &PeerConnectionFactory,
225 mode: VideoMode,
226 hub: Arc<VideoHub>,
227 updates: UnboundedSender<CallUpdate>,
228 ) -> Self {
229 LocalVideo {
230 mode,
231 hub,
232 updates,
233 commands: None,
234 camera_generation: Arc::new(AtomicU64::new(0)),
235 share_generation: Arc::new(AtomicU64::new(0)),
236 camera: Outgoing::new(factory, CAMERA_LABEL, PatternKind::Camera, false),
237 screen: Outgoing::new(factory, SCREEN_LABEL, PatternKind::Screen, true),
238 lines: None,
239 blur: Arc::new(BlurSettings::default()),
240 motion: false,
241 share_fps: Arc::new(AtomicU32::new(SCREEN_SHARE_FPS)),
242 camera_preview: false,
243 quality: VideoQuality::default(),
244 camera_stats: CameraCaptureStats::new(),
245 timeline: None,
246 portal_generation: 0,
247 portal_armed: false,
248 portal_keep: false,
249 portal_bound: false,
250 camera_bitrate_cap: None,
251 }
252 }
253
254 pub fn attach_commands(&mut self, commands: UnboundedSender<CallCommand>) {
255 self.commands = Some(commands);
256 }
257
258 pub fn attach_timeline(&mut self, timeline: Timeline) {
259 self.timeline = Some(timeline);
260 }
261
262 pub fn video_quality(&self) -> VideoQuality {
263 self.quality
264 }
265
266 pub fn set_video_quality(&mut self, quality: VideoQuality) {
267 self.quality = quality;
268 }
269
270 pub fn set_motion(&mut self, motion: bool) {
271 self.motion = motion;
272 self.share_fps.store(
273 if motion {
274 MOTION_SHARE_FPS
275 } else {
276 SCREEN_SHARE_FPS
277 },
278 Ordering::Relaxed,
279 );
280 if let Some(share) = self
281 .lines
282 .as_ref()
283 .and_then(|lines| lines.share.as_ref())
284 .filter(|_| self.sharing())
285 {
286 let _ = self.tune_share(&share.sender());
287 }
288 }
289
290 pub fn set_standout(&self, standout: bool) {
291 self.blur.set_standout(standout);
292 }
293
294 fn tune_share(&self, sender: &RtpSender) -> Result<()> {
295 let mut parameters = sender.parameters();
296 parameters.set_degradation_preference(if self.motion {
297 DegradationPreference::MaintainFramerate
298 } else {
299 DegradationPreference::MaintainResolution
300 });
301 let fps = f64::from(self.share_fps.load(Ordering::Relaxed));
302 for encoding in &mut parameters.encodings {
303 encoding.max_framerate = Some(fps);
304 }
305 sender
306 .set_parameters(parameters)
307 .map_err(|error| Error::Webrtc(error.to_string()))
308 }
309
310 fn sender_of(&self, source: SendSource) -> Option<RtpSender> {
311 let lines = self.lines.as_ref()?;
312 match source {
313 SendSource::Camera => Some(lines.camera.sender()),
314 SendSource::Screen => lines.share.as_ref().map(|share| share.sender()),
315 }
316 }
317
318 pub fn apply_send_limit(
319 &mut self,
320 source: SendSource,
321 limits: &[SendLimit],
322 ) -> Result<Option<Vec<LayerPlan>>> {
323 let sending = match source {
324 SendSource::Camera => self.camera_on(),
325 SendSource::Screen => self.sharing(),
326 };
327 let Some(sender) = self.sender_of(source).filter(|_| sending) else {
328 return Ok(None);
329 };
330 let outgoing = match source {
331 SendSource::Camera => &mut self.camera,
332 SendSource::Screen => &mut self.screen,
333 };
334 let frame = unpack_size(outgoing.frame_size.load(Ordering::Relaxed));
335 outgoing.requested = Some(RequestedLimits {
336 limits: limits.to_vec(),
337 applied_for: frame,
338 });
339 let rids: Vec<String> = sender
340 .parameters()
341 .encodings
342 .into_iter()
343 .map(|encoding| encoding.rid)
344 .collect();
345 if rids.len() > 1 {
346 let mut plans = plan_layers(limits, frame, &rids);
347 if source == SendSource::Camera {
348 Self::apply_bitrate_cap_to_plans(&mut plans, self.camera_bitrate_cap);
349 }
350 if plans.iter().any(|plan| plan.keyframe) {
351 Self::set_layers(&sender, &plans, KEYFRAME_NUDGE)?;
352 }
353 Self::set_layers(&sender, &plans, 1.0)?;
354 return Ok(Some(plans));
355 }
356 let Some(limit) = limits.first() else {
357 return Ok(None);
358 };
359 let mut encoder = encoder_limits(limit, frame);
360 if source == SendSource::Camera
361 && let Some(cap) = self.camera_bitrate_cap
362 {
363 encoder.max_bitrate = Some(encoder.max_bitrate.map_or(cap, |max| max.min(cap)));
364 }
365 if limit.keyframe {
366 Self::set_limits(&sender, &encoder, KEYFRAME_NUDGE)?;
367 }
368 Self::set_limits(&sender, &encoder, 1.0)?;
369 Ok(Some(vec![LayerPlan {
370 rid: rids.into_iter().next().unwrap_or_default(),
371 active: true,
372 limits: Some(encoder),
373 keyframe: limit.keyframe,
374 }]))
375 }
376
377 fn apply_bitrate_cap_to_plans(plans: &mut [LayerPlan], cap: Option<u64>) {
378 let Some(cap) = cap else { return };
379 for plan in plans {
380 if let Some(limits) = plan.limits.as_mut() {
381 limits.max_bitrate = Some(limits.max_bitrate.map_or(cap, |max| max.min(cap)));
382 }
383 }
384 }
385
386 /// The mixer sends its limits once, often before the first frame tells the size to scale from.
387 pub fn refresh_send_limits(&mut self) -> Vec<(SendSource, Result<Option<Vec<LayerPlan>>>)> {
388 let mut refreshed = Vec::new();
389 for source in [SendSource::Camera, SendSource::Screen] {
390 let outgoing = match source {
391 SendSource::Camera => &self.camera,
392 SendSource::Screen => &self.screen,
393 };
394 let frame = unpack_size(outgoing.frame_size.load(Ordering::Relaxed));
395 let Some(requested) = outgoing
396 .requested
397 .as_ref()
398 .filter(|requested| frame.is_some() && requested.applied_for != frame)
399 else {
400 continue;
401 };
402 let limits = requested.limits.clone();
403 refreshed.push((source, self.apply_send_limit(source, &limits)));
404 }
405 refreshed
406 }
407
408 fn set_layers(sender: &RtpSender, plans: &[LayerPlan], nudge: f64) -> Result<()> {
409 let mut parameters = sender.parameters();
410 for encoding in &mut parameters.encodings {
411 let Some(plan) = plans.iter().find(|plan| plan.rid == encoding.rid) else {
412 continue;
413 };
414 let nudged = nudge != 1.0 && plan.keyframe;
415 encoding.active = plan.active;
416 let Some(limits) = &plan.limits else { continue };
417 encoding.scale_resolution_down_by =
418 Some(limits.scale_down_by * if nudged { nudge } else { 1.0 });
419 if let Some(framerate) = limits.max_framerate {
420 encoding.max_framerate = Some(framerate);
421 }
422 encoding.max_bitrate = limits.max_bitrate;
423 }
424 sender
425 .set_parameters(parameters)
426 .map_err(|error| Error::Webrtc(error.to_string()))
427 }
428
429 fn set_limits(sender: &RtpSender, limits: &EncoderLimits, nudge: f64) -> Result<()> {
430 let mut parameters = sender.parameters();
431 for encoding in &mut parameters.encodings {
432 encoding.scale_resolution_down_by = Some(limits.scale_down_by * nudge);
433 if let Some(framerate) = limits.max_framerate {
434 encoding.max_framerate = Some(framerate);
435 }
436 encoding.max_bitrate = limits.max_bitrate;
437 }
438 sender
439 .set_parameters(parameters)
440 .map_err(|error| Error::Webrtc(error.to_string()))
441 }
442
443 pub fn camera_size(&self) -> Option<(u32, u32)> {
444 unpack_size(self.camera.frame_size.load(Ordering::Relaxed)).filter(|_| self.camera_on())
445 }
446
447 pub fn set_background(&self, enabled: bool, picture: Option<Arc<BackgroundPicture>>) {
448 self.blur.set_picture(picture);
449 self.blur.set_enabled(enabled);
450 }
451
452 pub fn set_effects(&self, effects: CameraEffects) {
453 self.blur.set_effects(effects);
454 }
455
456 pub fn camera_track(&self) -> RtcVideoTrack {
457 self.camera.track.clone()
458 }
459
460 pub fn share_track(&self) -> RtcVideoTrack {
461 self.screen.track.clone()
462 }
463
464 pub fn take_effects_failure(&self) -> bool {
465 self.blur.take_unavailable()
466 }
467
468 pub fn blur_average_ms(&self) -> Option<f32> {
469 (self.camera_on() && self.blur.active()).then(|| self.blur.average_ms())
470 }
471
472 pub fn blur_model(&self) -> Option<&'static str> {
473 (self.camera_on() && self.blur.active())
474 .then(|| self.blur.model())
475 .filter(|model| !model.is_empty())
476 }
477
478 pub fn has_lines(&self) -> bool {
479 self.lines.is_some()
480 }
481
482 /// Drop senders that belonged to a peer connection that was replaced.
483 /// Detach tracks first — closing a peer while a live camera/share track is
484 /// still attached can block the call task indefinitely (UI hang → kill).
485 pub fn clear_lines(&mut self) {
486 if let Some(lines) = self.lines.take() {
487 let _ = lines.camera.sender().set_track(None);
488 let _ = Self::set_active(&lines.camera.sender(), false);
489 if let Some(share) = lines.share {
490 let _ = share.sender().set_track(None);
491 let _ = Self::set_active(&share.sender(), false);
492 }
493 }
494 }
495
496 pub fn camera_mid(&self) -> Option<String> {
497 self.lines.as_ref().and_then(|lines| lines.camera.mid())
498 }
499
500 pub fn share_mid(&self) -> Option<String> {
501 self.lines
502 .as_ref()
503 .and_then(|lines| lines.share.as_ref())
504 .and_then(|share| share.mid())
505 }
506
507 pub fn has_share_line(&self) -> bool {
508 self.lines
509 .as_ref()
510 .is_some_and(|lines| lines.share.is_some())
511 }
512
513 pub fn add_share_line(
514 &mut self,
515 share: RtpTransceiver,
516 camera: Option<RtpTransceiver>,
517 ) -> Result<()> {
518 match (self.lines.as_mut(), camera) {
519 (Some(lines), _) => lines.share = Some(share),
520 (None, Some(camera)) => {
521 self.lines = Some(VideoLines {
522 camera,
523 share: Some(share),
524 })
525 }
526 (None, None) => return Err(Error::Webrtc("no video line negotiated".into())),
527 }
528 Ok(())
529 }
530
531 pub fn share_sending(&self) -> bool {
532 self.lines
533 .as_ref()
534 .and_then(|lines| lines.share.as_ref())
535 .and_then(|share| share.current_direction())
536 .is_some_and(|direction| {
537 matches!(
538 direction,
539 RtpTransceiverDirection::SendOnly | RtpTransceiverDirection::SendRecv
540 )
541 })
542 }
543
544 pub fn is_available(&self) -> bool {
545 self.mode != VideoMode::Off
546 }
547
548 pub fn camera_on(&self) -> bool {
549 self.camera.capture.is_some() && !self.camera_preview
550 }
551
552 pub fn camera_previewing(&self) -> bool {
553 self.camera.capture.is_some() && self.camera_preview
554 }
555
556 pub fn sharing(&self) -> bool {
557 self.screen.capture.is_some()
558 }
559
560 pub fn portal_is_open(&self) -> bool {
561 self.portal_armed
562 }
563
564 pub fn set_lines(&mut self, lines: VideoLines) -> Result<()> {
565 self.clear_lines();
566 if self.camera_on() {
567 Self::begin_sending_on(&lines.camera, &self.camera.track)?;
568 }
569 if self.sharing()
570 && let Some(share) = &lines.share
571 {
572 Self::begin_sending_on(share, &self.screen.track)?;
573 }
574 self.lines = Some(lines);
575 Ok(())
576 }
577
578 fn ensure_send_direction(transceiver: &RtpTransceiver) -> Result<()> {
579 match transceiver.direction() {
580 RtpTransceiverDirection::SendRecv | RtpTransceiverDirection::SendOnly => Ok(()),
581 RtpTransceiverDirection::RecvOnly | RtpTransceiverDirection::Inactive => transceiver
582 .set_direction(RtpTransceiverDirection::SendRecv)
583 .map_err(|error| Error::Webrtc(error.to_string())),
584 RtpTransceiverDirection::Stopped => Err(Error::Webrtc("video line is stopped".into())),
585 }
586 }
587
588 fn begin_sending_on(transceiver: &RtpTransceiver, track: &RtcVideoTrack) -> Result<()> {
589 Self::ensure_send_direction(transceiver)?;
590 Self::begin_sending(&transceiver.sender(), track)
591 }
592
593 fn begin_sending(sender: &RtpSender, track: &RtcVideoTrack) -> Result<()> {
594 sender
595 .set_track(Some(MediaStreamTrack::Video(track.clone())))
596 .map_err(|error| Error::Webrtc(error.to_string()))?;
597 // Prefer dropping resolution over framerate when the uplink is tight.
598 let mut parameters = sender.parameters();
599 parameters.set_degradation_preference(DegradationPreference::MaintainFramerate);
600 sender
601 .set_parameters(parameters)
602 .map_err(|error| Error::Webrtc(error.to_string()))?;
603 Self::set_active(sender, true)
604 }
605
606 /// Apply or clear a governor cap on the camera encodings; mixer limits stay the ceiling.
607 pub fn cap_camera_bitrate(&mut self, cap: Option<u64>) -> Result<()> {
608 if self.camera_bitrate_cap == cap {
609 return Ok(());
610 }
611 self.camera_bitrate_cap = cap;
612 if let Some(limits) = self
613 .camera
614 .requested
615 .as_ref()
616 .map(|requested| requested.limits.clone())
617 {
618 let _ = self.apply_send_limit(SendSource::Camera, &limits)?;
619 return Ok(());
620 }
621 let Some(sender) = self
622 .sender_of(SendSource::Camera)
623 .filter(|_| self.camera_on())
624 else {
625 return Ok(());
626 };
627 let mut parameters = sender.parameters();
628 for encoding in &mut parameters.encodings {
629 encoding.max_bitrate = match (encoding.max_bitrate, cap) {
630 (Some(max), Some(cap)) => Some(max.min(cap)),
631 (None, Some(cap)) => Some(cap),
632 (max, None) => max,
633 };
634 }
635 sender
636 .set_parameters(parameters)
637 .map_err(|error| Error::Webrtc(error.to_string()))
638 }
639
640 pub(crate) fn set_sender_active(sender: &RtpSender, active: bool) -> Result<()> {
641 let mut parameters = sender.parameters();
642 for encoding in &mut parameters.encodings {
643 encoding.active = active;
644 }
645 sender
646 .set_parameters(parameters)
647 .map_err(|error| Error::Webrtc(error.to_string()))
648 }
649
650 fn set_active(sender: &RtpSender, active: bool) -> Result<()> {
651 Self::set_sender_active(sender, active)
652 }
653
654 fn camera_sink(&self) -> LocalSink {
655 LocalSink::new(
656 self.camera.source.clone(),
657 Some((self.hub.clone(), VideoKey::LocalCamera)),
658 )
659 .mirrored_by(self.blur.clone())
660 .reporting_size(self.camera.frame_size.clone())
661 }
662
663 /// Local share frames go to the encoder and to the window in the chat.
664 fn screen_sink(&self) -> LocalSink {
665 LocalSink::new(
666 self.screen.source.clone(),
667 Some((self.hub.clone(), VideoKey::LocalScreen)),
668 )
669 .with_standout(self.blur.clone())
670 .reporting_size(self.screen.frame_size.clone())
671 }
672
673 /// A capture thread that was replaced meanwhile must not switch off its successor.
674 fn report_failure(
675 &self,
676 notice_key: &'static str,
677 generation: &Arc<AtomicU64>,
678 switch_off: CallCommand,
679 ) -> impl FnOnce(String) + Send + 'static {
680 let updates = self.updates.clone();
681 let commands = self.commands.clone();
682 let started = generation.fetch_add(1, Ordering::SeqCst) + 1;
683 let generation = generation.clone();
684 move |reason| {
685 let _ = updates.send(CallUpdate::Notice(notice_with_detail(notice_key, reason)));
686 if generation.load(Ordering::SeqCst) == started
687 && let Some(commands) = commands
688 {
689 let _ = commands.send(switch_off);
690 }
691 }
692 }
693
694 pub fn preview_camera(&mut self, choice: &DeviceChoice) -> Result<()> {
695 if !self.is_available() {
696 return Err(Error::Webrtc("video is switched off".into()));
697 }
698 self.camera.capture = None;
699 self.camera.capture = Some(self.capture_camera(choice)?);
700 self.camera_preview = true;
701 Ok(())
702 }
703
704 pub fn start_camera(&mut self, choice: &DeviceChoice) -> Result<()> {
705 let lines = self
706 .lines
707 .as_ref()
708 .ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?;
709 if !self.is_available() {
710 return Err(Error::Webrtc("video is switched off".into()));
711 }
712 if !self.camera_previewing() {
713 self.camera.capture = None;
714 self.camera.capture = Some(self.capture_camera(choice)?);
715 }
716 Self::begin_sending_on(&lines.camera, &self.camera.track)?;
717 self.camera_preview = false;
718 Ok(())
719 }
720
721 pub fn camera_capture_summary(&self) -> Option<String> {
722 self.camera_stats.summary()
723 }
724
725 fn capture_camera(&self, choice: &DeviceChoice) -> Result<Capture> {
726 let mut sink = self.camera_sink();
727 Ok(match self.mode {
728 VideoMode::Pattern => Capture::Task(spawn_pattern(
729 sink,
730 PatternKind::Camera,
731 Some(self.blur.clone()),
732 )),
733 _ => {
734 let timeline = self.timeline.clone();
735 start_camera(
736 choice,
737 self.quality,
738 self.blur.clone(),
739 self.camera_stats.clone(),
740 move |label| {
741 if let Some(timeline) = timeline {
742 timeline.record("camera capture", label);
743 } else {
744 eprintln!("calls: camera capture {label}");
745 }
746 },
747 move |buffer| sink.push(buffer),
748 self.report_failure(
749 CAMERA_STOPPED_NOTICE,
750 &self.camera_generation,
751 CallCommand::SetCamera(false),
752 ),
753 )?
754 }
755 })
756 }
757
758 /// Restart capture with the current quality if the camera is already running.
759 pub fn refresh_camera_capture(&mut self, choice: &DeviceChoice) -> Result<()> {
760 if self.camera.capture.is_none() {
761 return Ok(());
762 }
763 let preview = self.camera_preview;
764 self.camera.capture = None;
765 self.camera.capture = Some(self.capture_camera(choice)?);
766 self.camera_preview = preview;
767 if !preview {
768 if let Some(lines) = self.lines.as_ref() {
769 Self::begin_sending_on(&lines.camera, &self.camera.track)?;
770 }
771 }
772 Ok(())
773 }
774
775 pub fn stop_camera(&mut self) {
776 self.camera_generation.fetch_add(1, Ordering::SeqCst);
777 self.camera_preview = false;
778 self.camera.capture = None;
779 self.blur.set_cutout(None);
780 if let Some(lines) = &self.lines {
781 let _ = Self::set_active(&lines.camera.sender(), false);
782 }
783 self.hub.forget(&VideoKey::LocalCamera);
784 }
785
786 pub fn accept_portal(&mut self, generation: u64) -> bool {
787 if self.portal_armed && self.portal_generation == generation {
788 self.portal_armed = false;
789 self.portal_keep = true;
790 self.portal_bound = true;
791 true
792 } else {
793 false
794 }
795 }
796
797 pub fn open_portal(
798 &mut self,
799 kind: ShareKind,
800 commands: UnboundedSender<CallCommand>,
801 ) -> Result<()> {
802 if !self.is_available() {
803 return Err(Error::Webrtc("video is switched off".into()));
804 }
805 if self.mode == VideoMode::Pattern {
806 let source = ShareSource {
807 id: if kind == ShareKind::Screen { 1 } else { 2 },
808 kind,
809 title: if kind == ShareKind::Screen {
810 "Test screen"
811 } else {
812 "Test window"
813 }
814 .into(),
815 };
816 let _ = commands.send(CallCommand::StartShare(source));
817 return Ok(());
818 }
819 self.portal_generation = self.portal_generation.wrapping_add(1);
820 let generation = self.portal_generation;
821 self.portal_armed = false;
822 self.portal_keep = false;
823 self.portal_bound = false;
824 self.screen.capture = None;
825 let mut sink = self.screen_sink();
826 let updates = self.updates.clone();
827 let capture = start_portal_capture(
828 kind,
829 self.share_fps.clone(),
830 move |buffer| sink.push(buffer),
831 move |follow| match follow {
832 PortalFollowUp::Share(source) => {
833 let _ = commands.send(CallCommand::FinishPortalShare { source, generation });
834 }
835 PortalFollowUp::Quiet => {
836 let _ = commands.send(CallCommand::AbandonPortalShare);
837 }
838 PortalFollowUp::Notice(text) => {
839 let _ = updates.send(CallUpdate::Notice(text.to_owned()));
840 let _ = commands.send(CallCommand::AbandonPortalShare);
841 }
842 },
843 )?;
844 self.portal_armed = true;
845 self.screen.capture = Some(capture);
846 Ok(())
847 }
848
849 pub fn start_share(&mut self, source: &ShareSource) -> Result<()> {
850 let lines = self
851 .lines
852 .as_ref()
853 .ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?;
854 let share = lines
855 .share
856 .as_ref()
857 .ok_or_else(|| Error::Webrtc("sharing needs a meeting".into()))?;
858 if !self.is_available() {
859 return Err(Error::Webrtc("video is switched off".into()));
860 }
861 let keep = std::mem::take(&mut self.portal_keep) || self.portal_bound;
862 if !keep {
863 self.portal_armed = false;
864 self.portal_generation = self.portal_generation.wrapping_add(1);
865 self.screen.capture = None;
866 let mut sink = self.screen_sink();
867 let capture = match self.mode {
868 VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Screen, None)),
869 _ => start_screen_capture(
870 source.clone(),
871 self.share_fps.clone(),
872 move |buffer| sink.push(buffer),
873 self.report_failure(
874 SCREEN_SHARE_STOPPED_NOTICE,
875 &self.share_generation,
876 CallCommand::StopShare,
877 ),
878 )?,
879 };
880 self.screen.capture = Some(capture);
881 }
882 Self::begin_sending_on(&share, &self.screen.track)?;
883 let _ = self.tune_share(&share.sender());
884 Ok(())
885 }
886
887 pub fn stop_share(&mut self) {
888 self.share_generation.fetch_add(1, Ordering::SeqCst);
889 self.portal_generation = self.portal_generation.wrapping_add(1);
890 self.portal_armed = false;
891 self.portal_keep = false;
892 self.portal_bound = false;
893 self.screen.capture = None;
894 self.hub.forget(&VideoKey::LocalScreen);
895 if let Some(share) = self.lines.as_ref().and_then(|lines| lines.share.as_ref()) {
896 let _ = Self::set_active(&share.sender(), false);
897 }
898 }
899
900 pub fn stop_all(&mut self) {
901 self.stop_camera();
902 self.stop_share();
903 }
904}
905
906#[cfg(test)]
907mod tests {
908 use super::*;
909 use libwebrtc::MediaType;
910 use libwebrtc::peer_connection_factory::RtcConfiguration;
911 use libwebrtc::rtp_transceiver::{RtpTransceiverDirection, RtpTransceiverInit};
912
913 #[tokio::test]
914 async fn a_camera_preview_runs_without_a_line_and_stops_cleanly() {
915 let (sender, _receiver) = tokio::sync::mpsc::unbounded_channel();
916 let factory = crate::devices::shared_factory();
917 let mut video = LocalVideo::new(
918 &factory,
919 VideoMode::Pattern,
920 VideoHub::new(sender.clone()),
921 sender,
922 );
923 video.preview_camera(&DeviceChoice::SystemDefault).unwrap();
924 assert!(video.camera_previewing() && !video.camera_on());
925 assert!(
926 video.start_camera(&DeviceChoice::SystemDefault).is_err(),
927 "sending needs a negotiated line"
928 );
929 assert!(video.camera_previewing());
930 video.stop_camera();
931 assert!(!video.camera_previewing() && !video.camera_on());
932 }
933
934 #[tokio::test]
935 async fn clearing_a_sender_track_does_not_crash() {
936 let factory = crate::devices::shared_factory();
937 let peer = factory
938 .create_peer_connection(RtcConfiguration::default())
939 .expect("peer");
940 let transceiver = peer
941 .add_transceiver_for_media(
942 MediaType::Video,
943 RtpTransceiverInit {
944 direction: RtpTransceiverDirection::SendRecv,
945 stream_ids: vec!["camera".into()],
946 send_encodings: Vec::new(),
947 },
948 )
949 .expect("transceiver");
950 let (updates, _) = tokio::sync::mpsc::unbounded_channel();
951 let video = LocalVideo::new(
952 &factory,
953 VideoMode::Pattern,
954 VideoHub::new(updates.clone()),
955 updates,
956 );
957 let sender = transceiver.sender();
958 sender
959 .set_track(Some(
960 libwebrtc::media_stream_track::MediaStreamTrack::Video(video.camera_track()),
961 ))
962 .expect("attach");
963 // Must not SIGSEGV on nullptr (peer switch calls clear_lines → set_track(None)).
964 // Do not call sender.track() afterwards: the FFI track() wrapper crashes on a null
965 // webrtc track (get_or_create_media_stream_track).
966 sender.set_track(None).expect("detach must accept nullptr");
967 peer.close();
968 }
969
970 #[test]
971 fn frame_sizes_survive_packing() {
972 assert_eq!(unpack_size(pack_size(1280, 720)), Some((1280, 720)));
973 assert_eq!(unpack_size(0), None);
974 }
975
976 #[test]
977 fn the_video_mode_follows_the_environment_value() {
978 assert_eq!(VideoMode::parse(None), VideoMode::Platform);
979 assert_eq!(VideoMode::parse(Some("Pattern")), VideoMode::Pattern);
980 assert_eq!(VideoMode::parse(Some("off")), VideoMode::Off);
981 assert_eq!(VideoMode::parse(Some("whatever")), VideoMode::Platform);
982 }
983}