BlueGit

ict rusty-teams

fix(calling): 1:1 media negotiation and 30 fps camera capture

Fold multi-stream escalation answers, apply late same-peer camera answers,
and prefer MJPEG HD at 30 fps with decode telemetry. Archive OpenSpec changes
into main specs.

metis Joachim Mild · pushed by metis

Authored 2026-11-12 · 2 weeks ago

Hash
c6cce329a51b687ee404f6436fef00377e9f4bb5
Parent
b07109fc
30 files changed +3487 −619
CHANGELOG.md added +54 −0
@@ -0,0 +1,54 @@
1 # Changelog
2
3 ## [0.3.0-joe.4] - 2026-11-12
4
5 ### Fixed
6
7 - Camera capture prefers MJPEG 1080p/720p at 30 fps on USB 2.0 webcams (e.g. C930e)
8 instead of falling back to YUYV 1080p at 5 fps; opens under 30 fps are rejected
9 when a faster format exists.
10 - MJPEG frames decode locally (zune-jpeg → I420) with reusable buffers.
11 - UVC best-effort: disable exposure dynamic framerate and set 50 Hz power-line
12 frequency; call reports log the chosen format plus capture fps / decode time.
13
14 ## [0.3.0-joe.3] - 2026-11-12
15
16 ### Fixed
17
18 - 1:1 escalation answers no longer emit an extra folded gallery m-line (`mid 3-0`),
19 which triggered Teams `InvalidNumberOfMedia` / «Incorrect number of media».
20 - Same-peer renegotiation keeps a short grace after the answer timeout so a late
21 camera answer (`recvonly`) can still be applied instead of rolling back send.
22 - Camera open survives UVC `CameraFormat` property failures (Closest NV12 first;
23 AbsoluteHighest only as last resort).
24
25 ## [0.3.0-joe.2] - 2026-11-12
26
27 ### Added
28
29 - Camera video quality setting: Auto, 720p, or 1080p (no 4K), in call and prejoin
30 camera menus; choice persists and applies to capture plus stage receive limits.
31
32 ### Changed
33
34 - Auto / 1080p prefer 1080p capture and advertise matching send capabilities;
35 stage receive uses 1080p-class budgets when allowed.
36 - CI tests run on Forgejo only; GitHub Actions are mirror stubs.
37
38 ## [0.3.0-joe.1] - 2026-11-12
39
40 ### Added
41
42 - Forgejo as source of truth (`devops-geek/rusty-teams`) with push mirror to GitHub.
43 - Linux release packages: `.deb`, `.rpm`, Arch `.pkg.tar.zst`, Flatpak bundle.
44 - Forgejo Actions builds for Windows amd64, Windows ARM64, and macOS universal.
45 - Local share preview window in the meeting chat (and in the mini call window).
46
47 ### Fixed
48
49 - Wayland screen share via xdg-desktop-portal (KDE, GNOME, Hyprland) without the
50 «shared source is gone» toast after confirming the desktop dialog.
51
52 ## [0.3.0] - 2026-11-10
53
54 Upstream-aligned baseline on the fork before Forgejo SoT cutover.
@@ -0,0 +1,54 @@
1# Changelog
2
3## [0.3.0-joe.4] - 2026-11-12
4
5### Fixed
6
7- Camera capture prefers MJPEG 1080p/720p at 30 fps on USB 2.0 webcams (e.g. C930e)
8 instead of falling back to YUYV 1080p at 5 fps; opens under 30 fps are rejected
9 when a faster format exists.
10- MJPEG frames decode locally (zune-jpeg → I420) with reusable buffers.
11- UVC best-effort: disable exposure dynamic framerate and set 50 Hz power-line
12 frequency; call reports log the chosen format plus capture fps / decode time.
13
14## [0.3.0-joe.3] - 2026-11-12
15
16### Fixed
17
18- 1:1 escalation answers no longer emit an extra folded gallery m-line (`mid 3-0`),
19 which triggered Teams `InvalidNumberOfMedia` / «Incorrect number of media».
20- Same-peer renegotiation keeps a short grace after the answer timeout so a late
21 camera answer (`recvonly`) can still be applied instead of rolling back send.
22- Camera open survives UVC `CameraFormat` property failures (Closest NV12 first;
23 AbsoluteHighest only as last resort).
24
25## [0.3.0-joe.2] - 2026-11-12
26
27### Added
28
29- Camera video quality setting: Auto, 720p, or 1080p (no 4K), in call and prejoin
30 camera menus; choice persists and applies to capture plus stage receive limits.
31
32### Changed
33
34- Auto / 1080p prefer 1080p capture and advertise matching send capabilities;
35 stage receive uses 1080p-class budgets when allowed.
36- CI tests run on Forgejo only; GitHub Actions are mirror stubs.
37
38## [0.3.0-joe.1] - 2026-11-12
39
40### Added
41
42- Forgejo as source of truth (`devops-geek/rusty-teams`) with push mirror to GitHub.
43- Linux release packages: `.deb`, `.rpm`, Arch `.pkg.tar.zst`, Flatpak bundle.
44- Forgejo Actions builds for Windows amd64, Windows ARM64, and macOS universal.
45- Local share preview window in the meeting chat (and in the mini call window).
46
47### Fixed
48
49- Wayland screen share via xdg-desktop-portal (KDE, GNOME, Hyprland) without the
50 «shared source is gone» toast after confirming the desktop dialog.
51
52## [0.3.0] - 2026-11-10
53
54Upstream-aligned baseline on the fork before Forgejo SoT cutover.
Cargo.lock +2 −0
@@ -1221,6 +1221,8 @@ dependencies = [
1221 1221 "webview",
1222 1222 "windows 0.62.2",
1223 1223 "windows-core 0.62.2",
1224 "zune-core 0.5.3",
1225 "zune-jpeg 0.5.15",
1224 1226 ]
1225 1227
1226 1228 [[package]]
@@ -1221,6 +1221,8 @@ dependencies = [
1221 "webview",
1221 "webview",
1222 "windows 0.62.2",
1222 "windows 0.62.2",
1223 "windows-core 0.62.2",
1223 "windows-core 0.62.2",
1224 "zune-core 0.5.3",
1225 "zune-jpeg 0.5.15",
1224]
1226]
1225
1227
1226[[package]]
1228[[package]]
crates/app-call-model/src/preview.rs +3 −1
@@ -4,7 +4,7 @@ use std::time::{Duration, Instant};
4 4
5 5 use calling::background::BackgroundPicture;
6 6 use calling::blur::BlurSettings;
7 use calling::camera::start_camera;
7 use calling::camera::{CameraCaptureStats, start_camera};
8 8 use calling::capture::Capture;
9 9 use calling::video_frame::picture_from_i420;
10 10 use calling::video_pattern::{PatternKind, pattern_frame};
@@ -60,6 +60,8 @@ impl CameraPreview {
60 60 let started = start_camera(
61 61 choice,
62 62 self.blur.clone(),
63 CameraCaptureStats::new(),
64 |_label| {},
63 65 move |buffer| {
64 66 frames.fetch_add(1, Ordering::Relaxed);
65 67 if let Some(mut picture) = picture_from_i420(buffer, PREVIEW_MAX_WIDTH) {
@@ -4,7 +4,7 @@ use std::time::{Duration, Instant};
4
4
5use calling::background::BackgroundPicture;
5use calling::background::BackgroundPicture;
6use calling::blur::BlurSettings;
6use calling::blur::BlurSettings;
7use calling::camera::start_camera;
7use calling::camera::{CameraCaptureStats, start_camera};
8use calling::capture::Capture;
8use calling::capture::Capture;
9use calling::video_frame::picture_from_i420;
9use calling::video_frame::picture_from_i420;
10use calling::video_pattern::{PatternKind, pattern_frame};
10use calling::video_pattern::{PatternKind, pattern_frame};
@@ -60,6 +60,8 @@ impl CameraPreview {
60 let started = start_camera(
60 let started = start_camera(
61 choice,
61 choice,
62 self.blur.clone(),
62 self.blur.clone(),
63 CameraCaptureStats::new(),
64 |_label| {},
63 move |buffer| {
65 move |buffer| {
64 frames.fetch_add(1, Ordering::Relaxed);
66 frames.fetch_add(1, Ordering::Relaxed);
65 if let Some(mut picture) = picture_from_i420(buffer, PREVIEW_MAX_WIDTH) {
67 if let Some(mut picture) = picture_from_i420(buffer, PREVIEW_MAX_WIDTH) {
crates/calling/Cargo.toml +2 −0
@@ -17,6 +17,8 @@ libwebrtc = { version = "=0.3.51", features = ["glib-main-loop"] }
17 17 deep_filter = { path = "../../vendor/deep_filter" }
18 18 ndarray = "0.17"
19 19 nokhwa = { version = "0.10", default-features = false, features = ["input-native"] }
20 zune-core = "0.5"
21 zune-jpeg = "0.5"
20 22 serde.workspace = true
21 23 webrtc-sys = "=0.3.48"
22 24 serde_json.workspace = true
@@ -17,6 +17,8 @@ libwebrtc = { version = "=0.3.51", features = ["glib-main-loop"] }
17deep_filter = { path = "../../vendor/deep_filter" }
17deep_filter = { path = "../../vendor/deep_filter" }
18ndarray = "0.17"
18ndarray = "0.17"
19nokhwa = { version = "0.10", default-features = false, features = ["input-native"] }
19nokhwa = { version = "0.10", default-features = false, features = ["input-native"] }
20zune-core = "0.5"
21zune-jpeg = "0.5"
20serde.workspace = true
22serde.workspace = true
21webrtc-sys = "=0.3.48"
23webrtc-sys = "=0.3.48"
22serde_json.workspace = true
24serde_json.workspace = true
crates/calling/src/call.rs +1287 −311
@@ -1,7 +1,7 @@
1 1 use std::collections::BTreeMap;
2 2 use std::path::PathBuf;
3 3 use std::sync::Arc;
4 use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
4 use std::sync::atomic::{AtomicBool, Ordering};
5 5 use std::time::Duration;
6 6
7 7 use chatsvc::TrouterCallback;
@@ -24,51 +24,67 @@ use crate::background::{BackgroundChoice, BackgroundPicture};
24 24 use crate::breakout::{self, RoomWatcher};
25 25 use crate::callee_gate::{CalleeGate, EchoWatch, roster_has_callee};
26 26 use crate::camera::{CameraDevice, list_cameras};
27 use crate::candidates::{SdpKind, is_udp_relay, negotiated_setup, with_candidates};
27 28 use crate::captions::{
28 29 BotAction, CAPTIONS_DATA_ID, CaptionEntry, CaptionFlow, CaptionState, CaptionStep,
29 30 parse_caption_message,
30 31 };
31 32 use crate::control::{CallCommand, CallControl, CallUpdate, Progress};
32 use crate::diagnostics::{CallDiagnostics, StatsSample};
33 33 use crate::data_channel::Depacketizer;
34 34 use crate::device_watch::{self, Debounce};
35 35 use crate::devices::{self, AppliedDevice, AudioDevice, DeviceChoice, Flow, Reselect};
36 use crate::diagnostics::{CallDiagnostics, StatsSample};
36 37 use crate::end::EndKind;
37 38 use crate::engine::{CallEngine, EngineConfig, Inner};
38 39 use crate::error::{Error, Result};
39 use crate::health::{CallHealth, HealthCounters, HealthSampler, QualityTracker, TransportDetails, health_from_stats};
40 use crate::hold::{HoldState, INACTIVE, MediaLine, accepted_modalities, direction_of, offer_modalities, is_hold, keep_media_running, offer_sends_video, rewrite_directions, stop_sending_on};
40 use crate::health::{
41 CallHealth, HealthCounters, HealthSampler, QualityTracker, TransportDetails, health_from_stats,
42 };
43 use crate::hold::{
44 HoldState, INACTIVE, MediaLine, accepted_modalities, direction_of, is_hold, keep_media_running,
45 offer_modalities, offer_sends_video, rewrite_directions, stop_sending_on,
46 };
47 use crate::meeting_options::{self, OptionWrite};
41 48 use crate::mic_processing::MicSettings;
42 49 use crate::mute::{MuteCommand, MuteEffect};
43 use crate::push::CallNotification;
44 use crate::relay::{DEFAULT_RELAY_HOST, RelayGrant};
45 use crate::renegotiation::{MediaAction, MediaNegotiator, MediaPath, RejectedOffer};
46 use crate::candidates::{SdpKind, is_udp_relay, negotiated_setup, with_candidates};
47 use crate::outcome::{embedded_end, failed_participant_count, outcome_summary};
48 50 use crate::organizer::{MeetingCapability, Modality, StateStep, Target, modality_steps};
49 use crate::meeting_options::{self, OptionWrite};
51 use crate::outcome::{embedded_end, failed_participant_count, outcome_summary};
52 use crate::push::CallNotification;
50 53 use crate::recording::{Consent, RecordingPlan, RecordingStatus};
54 use crate::relay::{DEFAULT_RELAY_HOST, RelayGrant, fetch_relay_grant};
55 use crate::renegotiation::{MediaAction, MediaNegotiator, MediaPath, RejectedOffer};
51 56 use crate::roster::{Roster, direct_roster};
52 use crate::sdp::{LineRole, OfferPlan, RemoteOffer, SignaledOffer, from_teams_offer, stream_lines, to_browser_answer, to_teams_answer, to_teams_offer};
57 use crate::screen::{
58 ShareKind, SharePicker, ShareSource, current_share_picker, list_share_sources,
59 share_sources_for_menu, share_thumbnail,
60 };
61 use crate::sdp::{
62 LineRole, OfferPlan, RemoteOffer, SignaledOffer, from_teams_offer, stream_lines,
63 to_browser_answer, to_teams_answer, to_teams_offer,
64 };
65 use crate::send_control::{RequestFilter, parse_request};
53 66 use crate::signaling::{
54 Answer, Attached, Callee, one_to_one_thread, Conversation, Invitation, InviteTarget, LeaveReason, MeetingTarget, NegotiationFailure, Participant, Signaling,
55 TenantRouting, chat_thread_id, find_echo_bot_thread, escalation_answer_body, renegotiation_body,
67 Answer, Attached, Callee, Conversation, Invitation, InviteTarget, LeaveReason, MeetingTarget,
68 NegotiationFailure, Participant, Signaling, TenantRouting, chat_thread_id,
69 escalation_answer_body, find_echo_bot_thread, one_to_one_thread, renegotiation_body,
56 70 };
57 71 use crate::software_audio::{SoftwareAudio, SoftwareAudioPlan};
58 72 use crate::state::{CallSignal, CallState};
59 73 use crate::timeline::{Timeline, TimelineEntry};
60 74 use crate::transfer::{Replacement, TransferEvent, TransferTarget};
75 use crate::trouter_events::{
76 CallEnd, CallEvent, CallbackLinks, ProgressStatus, callback_tag, classify, decode_body,
77 };
61 78 use crate::video_frame::{VideoKey, VideoPicture};
62 79 use crate::video_layout::{
63 CAMERA_MID, MediaDescription, ONE_TO_ONE_SHARE_MID, SCREEN_STREAM, SendCapabilityReporter, SlotTable, VideoLines, VideoRouter, add_one_to_one_lines, add_share_line, add_video_lines, offer_plan, one_to_one_plan,
80 CAMERA_MID, MediaDescription, ONE_TO_ONE_SHARE_MID, SCREEN_STREAM, SendCapabilityReporter,
81 SlotTable, VideoLines, VideoRouter, add_one_to_one_lines, add_share_line, add_video_lines,
82 offer_plan, one_to_one_plan,
64 83 };
65 use crate::send_control::{RequestFilter, parse_request};
66 use crate::video_send::{LocalVideo, SendSource, VideoMode};
67 use crate::screen::{ShareKind, ShareSource, list_share_sources, share_thumbnail};
68 use crate::video_receive::{ReceiveChange, SourceRequester, VideoCounters, VideoReceive, spawn_video_pump};
69 use crate::trouter_events::{
70 CallEnd, CallEvent, CallbackLinks, ProgressStatus, callback_tag, classify, decode_body,
84 use crate::video_receive::{
85 ReceiveChange, SourceRequester, VideoCounters, VideoReceive, spawn_video_pump,
71 86 };
87 use crate::video_send::{LocalVideo, SendSource, VideoMode};
72 88 use crate::whiteboard;
73 89
74 90 const END_CALLBACK_WAIT: Duration = Duration::from_secs(4);
@@ -92,8 +108,10 @@ const HEALTH_EVERY_TICKS: u32 = TICKS_PER_SECOND * 2;
92 108 const BOT_PREFIX: &str = "28:";
93 109 const RECORDING_START_LIMIT: Duration = Duration::from_secs(40);
94 110 const SAME_PEER_ANSWER_LIMIT: Duration = Duration::from_secs(40);
111 /// Teams sometimes answers a few seconds after the soft limit; keep the local offer until this grace ends.
112 const SAME_PEER_LATE_GRACE: Duration = Duration::from_secs(15);
95 113 const GATHERING_LIMIT: Duration = Duration::from_secs(5);
96 const RELAY_SETTLE: Duration = Duration::from_millis(200);
114 const GATHERING_QUIET: Duration = Duration::from_millis(500);
97 115 const GATHERING_POLL: Duration = Duration::from_millis(50);
98 116 const NEXT_PEER_LIMIT: Duration = Duration::from_secs(40);
99 117 const GLARE_RESEND_LIMIT: Duration = Duration::from_secs(3);
@@ -199,7 +217,10 @@ pub struct CallReport {
199 217 #[derive(Debug, Clone)]
200 218 pub enum CallSpec {
201 219 Echo,
202 People { callees: Vec<Callee>, thread_id: String },
220 People {
221 callees: Vec<Callee>,
222 thread_id: String,
223 },
203 224 Meeting(MeetingTarget),
204 225 }
205 226
@@ -247,11 +268,16 @@ pub(crate) enum Plan {
247 268 }
248 269
249 270 fn data_channel_from_env() -> bool {
250 !matches!(std::env::var(DATA_CHANNEL_ENV).ok().as_deref(), Some("0" | "off"))
271 !matches!(
272 std::env::var(DATA_CHANNEL_ENV).ok().as_deref(),
273 Some("0" | "off")
274 )
251 275 }
252 276
253 277 pub fn keep_alive_period(seconds: Option<u64>) -> Duration {
254 let seconds = seconds.unwrap_or(DEFAULT_KEEP_ALIVE_SECONDS).max(MIN_KEEP_ALIVE_SECONDS);
278 let seconds = seconds
279 .unwrap_or(DEFAULT_KEEP_ALIVE_SECONDS)
280 .max(MIN_KEEP_ALIVE_SECONDS);
255 281 Duration::from_secs_f64(seconds as f64 * KEEP_ALIVE_FRACTION)
256 282 }
257 283
@@ -286,19 +312,19 @@ struct PeerSession {
286 312 struct Gathered {
287 313 candidates: Arc<std::sync::Mutex<Vec<String>>>,
288 314 complete: Arc<AtomicBool>,
289 relay_seen_at: Arc<std::sync::Mutex<Option<Instant>>>,
290 waited_ms: Arc<AtomicU64>,
291 }
292
293 /// libwebrtc gathers continually here, and TCP/TLS relays trickle in late, so a UDP relay plus a short settle is enough.
294 fn gathering_settled(complete: bool, since_udp_relay: Option<Duration>) -> bool {
295 complete || since_udp_relay.is_some_and(|since| since >= RELAY_SETTLE)
315 relay_seen: Arc<AtomicBool>,
316 last_candidate: Arc<std::sync::Mutex<Option<Instant>>>,
296 317 }
297 318
298 319 impl Gathered {
320 /// libwebrtc gathers continually here, so "done" is a relay candidate followed by a quiet spell.
299 321 fn settled(&self) -> bool {
300 let since_udp_relay = self.relay_seen_at.lock().expect("relay time lock").map(|at| at.elapsed());
301 gathering_settled(self.complete.load(Ordering::SeqCst), since_udp_relay)
322 let quiet = self
323 .last_candidate
324 .lock()
325 .expect("candidate time lock")
326 .is_some_and(|at| at.elapsed() >= GATHERING_QUIET);
327 self.complete.load(Ordering::SeqCst) || (self.relay_seen.load(Ordering::SeqCst) && quiet)
302 328 }
303 329
304 330 async fn candidates(&self) -> Vec<String> {
@@ -307,14 +333,8 @@ impl Gathered {
307 333 tokio::time::sleep(GATHERING_POLL).await;
308 334 }
309 335 self.complete.store(true, Ordering::SeqCst);
310 self.waited_ms.store(waited.elapsed().as_millis() as u64, Ordering::SeqCst);
311 336 self.candidates.lock().expect("candidates lock").clone()
312 337 }
313
314 fn summary(&self) -> String {
315 let count = self.candidates.lock().expect("candidates lock").len();
316 format!("{count} candidate(s) after {} ms", self.waited_ms.load(Ordering::SeqCst))
317 }
318 338 }
319 339
320 340 async fn direct_sdp(teams_sdp: &str, gathered: Option<&Gathered>, kind: SdpKind) -> Result<String> {
@@ -439,14 +459,22 @@ pub async fn run_test_call(
439 459 endpoint_storage_key: "__testCallEpid".into(),
440 460 },
441 461 };
442 let (engine, _events) = CallEngine::start(session.clone(), poll_session.clone(), config).await?;
443 let report = engine.run(Plan::Outgoing(CallSpec::Echo), options, control).await;
462 let (engine, _events) =
463 CallEngine::start(session.clone(), poll_session.clone(), config).await?;
464 let report = engine
465 .run(Plan::Outgoing(CallSpec::Echo), options, control)
466 .await;
444 467 engine.stop().await;
445 468 report
446 469 }
447 470
448 471 impl CallEngine {
449 pub(crate) async fn run(&self, plan: Plan, options: CallOptions, mut control: CallControl) -> Result<CallReport> {
472 pub(crate) async fn run(
473 &self,
474 plan: Plan,
475 options: CallOptions,
476 mut control: CallControl,
477 ) -> Result<CallReport> {
450 478 let inner = self.inner.as_ref();
451 479 let _one_call_at_a_time = if options.concurrent {
452 480 None
@@ -463,7 +491,14 @@ impl CallEngine {
463 491 };
464 492 let timeline = Timeline::new(options.trace);
465 493 let stay_awake = crate::awake::StayAwake::new();
466 timeline.record("stay awake", if stay_awake.holding() { "system and display kept awake" } else { "not available" });
494 timeline.record(
495 "stay awake",
496 if stay_awake.holding() {
497 "system and display kept awake"
498 } else {
499 "not available"
500 },
501 );
467 502 let mut report = CallReport::default();
468 503 let mut state = CallState::Idle;
469 504 advance(&mut state, CallSignal::Dial, &control);
@@ -493,14 +528,24 @@ impl CallEngine {
493 528 }
494 529 };
495 530 dump_timeline(&options, &timeline, failure.as_ref());
496 let cancelled = live.cancel_leave || matches!(&state, CallState::Ended { reason: crate::state::EndReason::Cancelled });
531 let cancelled = live.cancel_leave
532 || matches!(
533 &state,
534 CallState::Ended {
535 reason: crate::state::EndReason::Cancelled
536 }
537 );
497 538 tear_down(live, inner, &timeline, &mut report, cancelled).await;
498 539 let recording = recording.lock().await;
499 540 report.recorded_samples = recording.samples.len();
500 541 report.timeline = timeline.entries();
501 control.send(CallUpdate::Diagnostics(Box::new(CallDiagnostics::new(&report, timeline.sdp_summaries()))));
542 control.send(CallUpdate::Diagnostics(Box::new(CallDiagnostics::new(
543 &report,
544 timeline.sdp_summaries(),
545 ))));
502 546 if let Some(path) = &options.wav_path {
503 write_wav(path, &recording.samples).map_err(|error| Error::Webrtc(format!("wav: {error}")))?;
547 write_wav(path, &recording.samples)
548 .map_err(|error| Error::Webrtc(format!("wav: {error}")))?;
504 549 }
505 550 match failure {
506 551 Some(error) => Err(error),
@@ -509,23 +554,32 @@ impl CallEngine {
509 554 }
510 555 }
511 556
512 fn open_peer(factory: &PeerConnectionFactory, grant: &RelayGrant, relay_host: &str, with_data_channel: bool) -> Result<PeerSession> {
557 fn open_peer(
558 factory: &PeerConnectionFactory,
559 grant: &RelayGrant,
560 relay_host: &str,
561 with_data_channel: bool,
562 ) -> Result<PeerSession> {
513 563 let mut configuration = RtcConfiguration::default();
514 564 configuration.ice_servers = vec![grant.ice_server(relay_host)];
515 565 let peer = factory
516 566 .create_peer_connection(configuration)
517 567 .map_err(|error| Error::Webrtc(error.to_string()))?;
518 568 let (sender, events) = mpsc::unbounded_channel();
519 let data_channel = with_data_channel.then(|| open_data_channel(&peer, sender.clone())).transpose()?;
569 let data_channel = with_data_channel
570 .then(|| open_data_channel(&peer, sender.clone()))
571 .transpose()?;
520 572 let gathered = Gathered::default();
521 573 let candidate_sink = gathered.candidates.clone();
522 let relay_seen_at = gathered.relay_seen_at.clone();
574 let relay_seen = gathered.relay_seen.clone();
575 let last_candidate = gathered.last_candidate.clone();
523 576 peer.on_ice_candidate(Some(Box::new(move |candidate| {
524 577 if candidate.sdp_mline_index() == 0 {
525 578 let text = candidate.candidate();
526 579 if is_udp_relay(&text) {
527 relay_seen_at.lock().expect("relay time lock").get_or_insert_with(Instant::now);
580 relay_seen.store(true, Ordering::SeqCst);
528 581 }
582 *last_candidate.lock().expect("candidate time lock") = Some(Instant::now());
529 583 candidate_sink.lock().expect("candidates lock").push(text);
530 584 }
531 585 })));
@@ -552,10 +606,18 @@ fn open_peer(factory: &PeerConnectionFactory, grant: &RelayGrant, relay_host: &s
552 606 let _ = sender.send(PeerEvent::VideoTrack { mid, track });
553 607 }
554 608 })));
555 Ok(PeerSession { peer, events, _data_channel: data_channel, gathered })
609 Ok(PeerSession {
610 peer,
611 events,
612 _data_channel: data_channel,
613 gathered,
614 })
556 615 }
557 616
558 fn open_data_channel(peer: &PeerConnection, sender: mpsc::UnboundedSender<PeerEvent>) -> Result<DataChannel> {
617 fn open_data_channel(
618 peer: &PeerConnection,
619 sender: mpsc::UnboundedSender<PeerEvent>,
620 ) -> Result<DataChannel> {
559 621 let channel = peer
560 622 .create_data_channel(DATA_CHANNEL_LABEL, DataChannelInit::default())
561 623 .map_err(|error| Error::Webrtc(error.to_string()))?;
@@ -565,7 +627,13 @@ fn open_data_channel(peer: &PeerConnection, sender: mpsc::UnboundedSender<PeerEv
565 627 Ok(channel)
566 628 }
567 629
568 fn one_to_one_directions<'a>(camera: bool, share: bool, camera_mid: &'a str, share_mid: Option<&'a str>, remote_shares: bool) -> impl Fn(MediaLine<'_>) -> Option<&'static str> + 'a {
630 fn one_to_one_directions<'a>(
631 camera: bool,
632 share: bool,
633 camera_mid: &'a str,
634 share_mid: Option<&'a str>,
635 remote_shares: bool,
636 ) -> impl Fn(MediaLine<'_>) -> Option<&'static str> + 'a {
569 637 move |line| match line.kind {
570 638 "video" if line.mid == camera_mid => Some(if camera { "sendrecv" } else { INACTIVE }),
571 639 "video" if Some(line.mid) == share_mid => Some(match (share, remote_shares) {
@@ -593,15 +661,33 @@ fn share_mid_in(offer_text: &str) -> Option<String> {
593 661 }
594 662
595 663 #[allow(clippy::too_many_arguments)]
596 fn directions_for(layout: Layout, hold: bool, camera: bool, share: bool, camera_mid: &str, share_mid: Option<&str>, remote_shares: bool, text: &str) -> String {
664 fn directions_for(
665 layout: Layout,
666 hold: bool,
667 camera: bool,
668 share: bool,
669 camera_mid: &str,
670 share_mid: Option<&str>,
671 remote_shares: bool,
672 text: &str,
673 ) -> String {
597 674 match (hold, layout) {
598 675 (true, _) => rewrite_directions(text, |_| Some(INACTIVE)),
599 (false, Layout::OneToOne) => rewrite_directions(text, one_to_one_directions(camera, share, camera_mid, share_mid, remote_shares)),
676 (false, Layout::OneToOne) => rewrite_directions(
677 text,
678 one_to_one_directions(camera, share, camera_mid, share_mid, remote_shares),
679 ),
600 680 (false, Layout::Conference) => text.to_owned(),
601 681 }
602 682 }
603 683
604 async fn create_offer(peer: &PeerConnection, factory: &PeerConnectionFactory, track: &RtcAudioTrack, layout: Layout, gathered: Option<&Gathered>) -> Result<OfferedMedia> {
684 async fn create_offer(
685 peer: &PeerConnection,
686 factory: &PeerConnectionFactory,
687 track: &RtcAudioTrack,
688 layout: Layout,
689 gathered: Option<&Gathered>,
690 ) -> Result<OfferedMedia> {
605 691 let transceiver_init = RtpTransceiverInit {
606 692 direction: RtpTransceiverDirection::SendRecv,
607 693 stream_ids: vec![MIC_STREAM.into()],
@@ -621,7 +707,16 @@ async fn create_offer(peer: &PeerConnection, factory: &PeerConnectionFactory, tr
621 707 })
622 708 .await
623 709 .map_err(|error| Error::Webrtc(error.to_string()))?;
624 let browser_offer = directions_for(layout, false, false, false, CAMERA_MID, Some(ONE_TO_ONE_SHARE_MID), false, &offer.to_string());
710 let browser_offer = directions_for(
711 layout,
712 false,
713 false,
714 false,
715 CAMERA_MID,
716 Some(ONE_TO_ONE_SHARE_MID),
717 false,
718 &offer.to_string(),
719 );
625 720 let description = parse_sdp(&browser_offer, SdpType::Offer)?;
626 721 peer.set_local_description(description)
627 722 .await
@@ -629,7 +724,13 @@ async fn create_offer(peer: &PeerConnection, factory: &PeerConnectionFactory, tr
629 724 let mut numbers = random_u32;
630 725 let mut signaled = to_teams_offer(&browser_offer, &plan, &mut numbers)?;
631 726 signaled.sdp = direct_sdp(&signaled.sdp, gathered, SdpKind::Offer).await?;
632 Ok(OfferedMedia { browser_offer, signaled, video, plan, modalities: accepted_modalities(false) })
727 Ok(OfferedMedia {
728 browser_offer,
729 signaled,
730 video,
731 plan,
732 modalities: accepted_modalities(false),
733 })
633 734 }
634 735
635 736 struct AnsweredMedia {
@@ -640,11 +741,20 @@ struct AnsweredMedia {
640 741 }
641 742
642 743 fn main_video_mid(remote: &RemoteOffer) -> Option<String> {
643 remote.lines.iter().find(|line| line.role == LineRole::MainVideo).and_then(|line| line.browser_mids.first().cloned())
744 remote
745 .lines
746 .iter()
747 .find(|line| line.role == LineRole::MainVideo)
748 .and_then(|line| line.browser_mids.first().cloned())
644 749 }
645 750
646 751 fn share_mids(remote: &RemoteOffer) -> Vec<String> {
647 remote.lines.iter().filter(|line| line.role == LineRole::ScreenShare).filter_map(|line| line.browser_mids.first().cloned()).collect()
752 remote
753 .lines
754 .iter()
755 .filter(|line| line.role == LineRole::ScreenShare)
756 .filter_map(|line| line.browser_mids.first().cloned())
757 .collect()
648 758 }
649 759
650 760 async fn answer_offer(
@@ -658,17 +768,32 @@ async fn answer_offer(
658 768 ) -> Result<AnsweredMedia> {
659 769 let remote = from_teams_offer(teams_offer)?;
660 770 let description = parse_sdp(&remote.browser_sdp, SdpType::Offer)?;
661 peer.set_remote_description(description).await.map_err(|error| {
662 let lines: Vec<String> = remote.lines.iter().map(|line| format!("{:?}{:?}", line.role, line.browser_mids)).collect();
663 Error::Webrtc(format!("{error} (offer lines: {})", lines.join(" ")))
664 })?;
771 peer.set_remote_description(description)
772 .await
773 .map_err(|error| {
774 let lines: Vec<String> = remote
775 .lines
776 .iter()
777 .map(|line| format!("{:?}{:?}", line.role, line.browser_mids))
778 .collect();
779 Error::Webrtc(format!("{error} (offer lines: {})", lines.join(" ")))
780 })?;
665 781 let camera_mid = main_video_mid(&remote).filter(|_| !matches!(video, AnswerVideo::Reject));
666 let kept_share_mids = if matches!(video, AnswerVideo::Reject) { Vec::new() } else { share_mids(&remote) };
782 let kept_share_mids = if matches!(video, AnswerVideo::Reject) {
783 Vec::new()
784 } else {
785 share_mids(&remote)
786 };
667 787 for transceiver in peer.transceivers() {
668 let is_video = matches!(transceiver.receiver().track(), Some(MediaStreamTrack::Video(_)));
669 let unused = transceiver
670 .mid()
671 .is_some_and(|mid| Some(&mid) != camera_mid.as_ref() && !kept_share_mids.contains(&mid) && Some(&mid) != sending_share_mid.as_ref());
788 let is_video = matches!(
789 transceiver.receiver().track(),
790 Some(MediaStreamTrack::Video(_))
791 );
792 let unused = transceiver.mid().is_some_and(|mid| {
793 Some(&mid) != camera_mid.as_ref()
794 && !kept_share_mids.contains(&mid)
795 && Some(&mid) != sending_share_mid.as_ref()
796 });
672 797 if is_video && unused {
673 798 let _ = transceiver.stop();
674 799 }
@@ -686,7 +811,10 @@ async fn answer_offer(
686 811 .await
687 812 .map_err(|error| Error::Webrtc(error.to_string()))?;
688 813 let mut answer_text = answer.to_string();
689 for mid in kept_share_mids.iter().filter(|mid| sending_share_mid.as_deref() != Some(mid.as_str())) {
814 for mid in kept_share_mids
815 .iter()
816 .filter(|mid| sending_share_mid.as_deref() != Some(mid.as_str()))
817 {
690 818 answer_text = stop_sending_on(&answer_text, mid);
691 819 }
692 820 let sends_camera = camera_on || matches!(video, AnswerVideo::Send(_));
@@ -699,7 +827,12 @@ async fn answer_offer(
699 827 let receiving_share_mid = kept_share_mids
700 828 .into_iter()
701 829 .filter(|mid| sending_share_mid.as_deref() != Some(mid.as_str()))
702 .find(|mid| matches!(direction_of(&answer_text, mid).as_deref(), Some("recvonly" | "sendrecv")));
830 .find(|mid| {
831 matches!(
832 direction_of(&answer_text, mid).as_deref(),
833 Some("recvonly" | "sendrecv")
834 )
835 });
703 836 let mut numbers = random_u32;
704 837 let signaled = to_teams_answer(&answer_text, &remote, &mut numbers)?;
705 838 Ok(AnsweredMedia {
@@ -714,7 +847,10 @@ fn new_media_leg_id() -> String {
714 847 uuid::Uuid::new_v4().simple().to_string().to_uppercase()
715 848 }
716 849
717 async fn setup_step<T, E>(control: &mut CallControl, step: impl std::future::Future<Output = std::result::Result<T, E>>) -> Result<T>
850 async fn setup_step<T, E>(
851 control: &mut CallControl,
852 step: impl std::future::Future<Output = std::result::Result<T, E>>,
853 ) -> Result<T>
718 854 where
719 855 Error: From<E>,
720 856 {
@@ -759,12 +895,16 @@ async fn drive(
759 895 report: &mut CallReport,
760 896 ) -> Result<()> {
761 897 let own_mri = format!("8:orgid:{}", inner.identity.object_id);
762 control.send(CallUpdate::OwnIdentity { mri: own_mri.clone() });
898 control.send(CallUpdate::OwnIdentity {
899 mri: own_mri.clone(),
900 });
763 901 let (spec, incoming) = match plan {
764 902 Plan::Outgoing(spec) => (Some(spec), None),
765 903 Plan::Incoming(incoming) => (None, Some(*incoming)),
766 904 };
767 let accept_mode = incoming.as_ref().map_or(AcceptMode::Audio, |incoming| incoming.accept);
905 let accept_mode = incoming
906 .as_ref()
907 .map_or(AcceptMode::Audio, |incoming| incoming.accept);
768 908 let (links, participant, mut callbacks, incoming_media) = match incoming {
769 909 Some(IncomingCall {
770 910 accept: _,
@@ -773,7 +913,12 @@ async fn drive(
773 913 links,
774 914 participant,
775 915 callbacks,
776 }) => (links, participant, callbacks, Some((notification, attached))),
916 }) => (
917 links,
918 participant,
919 callbacks,
920 Some((notification, attached)),
921 ),
777 922 None => {
778 923 let links = inner.callback_links();
779 924 let participant = inner.participant(&uuid::Uuid::new_v4().to_string());
@@ -786,15 +931,26 @@ async fn drive(
786 931
787 932 let thread_id = if matches!(spec, Some(CallSpec::Echo)) {
788 933 let thread_id = control
789 .until_hangup(find_echo_bot_thread(&inner.session, &inner.identity.object_id))
934 .until_hangup(find_echo_bot_thread(
935 &inner.session,
936 &inner.identity.object_id,
937 ))
790 938 .await??;
791 timeline.record("echo bot chat", if thread_id.is_some() { "found" } else { "none" });
939 timeline.record(
940 "echo bot chat",
941 if thread_id.is_some() { "found" } else { "none" },
942 );
792 943 thread_id
793 944 } else {
794 945 None
795 946 };
796 let grant = control.until_hangup(inner.relay.grant(&inner.session)).await??;
797 timeline.record("GET trap/tokens", format!("relay grant, expires in {} s", grant.expires_in_seconds));
947 let grant = control
948 .until_hangup(fetch_relay_grant(&inner.session))
949 .await??;
950 timeline.record(
951 "GET trap/tokens",
952 format!("relay grant, expires in {} s", grant.expires_in_seconds),
953 );
798 954
799 955 let factory = devices::shared_factory();
800 956 let mut input = options.input.clone();
@@ -802,15 +958,34 @@ async fn drive(
802 958 let audio = AudioSetup::start(&factory, options.audio, options.tone_hz, &input, &output);
803 959 control.send(CallUpdate::ListenOnly(audio.listen_only));
804 960 let mut device_lists = devices::list_devices(&factory);
805 let mut applied_input = devices::applied_device(&device_lists.inputs, &input, devices::system_default_id(Flow::Capture).as_deref());
806 let mut applied_output = devices::applied_device(&device_lists.outputs, &output, devices::system_default_id(Flow::Render).as_deref());
961 let mut applied_input = devices::applied_device(
962 &device_lists.inputs,
963 &input,
964 devices::system_default_id(Flow::Capture).as_deref(),
965 );
966 let mut applied_output = devices::applied_device(
967 &device_lists.outputs,
968 &output,
969 devices::system_default_id(Flow::Render).as_deref(),
970 );
807 971 let (_device_watcher, mut device_changes) = device_watch::watch();
808 972 let mut device_debounce = Debounce::default();
809 973 timeline.record(
810 974 "audio setup",
811 format!("listen only {}, {} input(s), {} output(s); {}", audio.listen_only, device_lists.inputs.len(), device_lists.outputs.len(), audio.adm_state),
975 format!(
976 "listen only {}, {} input(s), {} output(s); {}",
977 audio.listen_only,
978 device_lists.inputs.len(),
979 device_lists.outputs.len(),
980 audio.adm_state
981 ),
982 );
983 record_audio_devices(
984 timeline,
985 &device_lists,
986 applied_input.as_ref(),
987 applied_output.as_ref(),
812 988 );
813 record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref());
814 989 control.send(CallUpdate::Devices(device_lists.clone()));
815 990 control.send(CallUpdate::Selected {
816 991 input: input.clone(),
@@ -818,7 +993,13 @@ async fn drive(
818 993 });
819 994 let track = audio.track.clone();
820 995 live.audio = Some(audio);
821 let mut local_video = LocalVideo::new(&factory, options.video, control.video.clone(), control.updates());
996 let mut local_video = LocalVideo::new(
997 &factory,
998 options.video,
999 control.video.clone(),
1000 control.updates(),
1001 );
1002 local_video.attach_timeline(timeline.clone());
822 1003 let mut camera_choice = options.camera.clone();
823 1004 if options.start_camera {
824 1005 match local_video.preview_camera(&camera_choice) {
@@ -828,9 +1009,11 @@ async fn drive(
828 1009 }
829 1010 let mut media_description_request = 1u32;
830 1011 refresh_cameras(control.updates(), options.video, timeline.clone());
1012 control.send(CallUpdate::SharePicker(current_share_picker()));
831 1013 refresh_share_sources(control.updates(), options.video, false);
832 1014
833 let wants_data_channel = options.data_channel && spec.as_ref().is_some_and(CallSpec::is_meeting);
1015 let wants_data_channel =
1016 options.data_channel && spec.as_ref().is_some_and(CallSpec::is_meeting);
834 1017 let mut current = open_peer(&factory, &grant, &options.relay_host, wants_data_channel)?;
835 1018 live.peers.push(current.peer.clone());
836 1019
@@ -854,7 +1037,9 @@ async fn drive(
854 1037 _ => None,
855 1038 };
856 1039 let people_thread = match &spec {
857 Some(CallSpec::People { thread_id, .. }) if !thread_id.is_empty() => Some(thread_id.clone()),
1040 Some(CallSpec::People { thread_id, .. }) if !thread_id.is_empty() => {
1041 Some(thread_id.clone())
1042 }
858 1043 _ => incoming_media
859 1044 .as_ref()
860 1045 .filter(|(notification, _)| !notification.is_multi_party)
@@ -863,7 +1048,9 @@ async fn drive(
863 1048 .thread_id
864 1049 .clone()
865 1050 .filter(|thread| *thread != notification.caller.mri)
866 .or_else(|| one_to_one_thread(&inner.identity.object_id, &notification.caller.mri))
1051 .or_else(|| {
1052 one_to_one_thread(&inner.identity.object_id, &notification.caller.mri)
1053 })
867 1054 }),
868 1055 };
869 1056 let mut layout = match &spec {
@@ -871,8 +1058,12 @@ async fn drive(
871 1058 _ => Layout::Conference,
872 1059 };
873 1060 let peer_mri = match &spec {
874 Some(CallSpec::People { callees, .. }) if callees.len() == 1 => Some(callees[0].mri.clone()),
875 _ => incoming_media.as_ref().map(|(notification, _)| notification.caller.mri.clone()),
1061 Some(CallSpec::People { callees, .. }) if callees.len() == 1 => {
1062 Some(callees[0].mri.clone())
1063 }
1064 _ => incoming_media
1065 .as_ref()
1066 .map(|(notification, _)| notification.caller.mri.clone()),
876 1067 };
877 1068 let mut layout_plan: OfferPlan;
878 1069 let mut direct_video_mid: Option<String> = None;
@@ -884,14 +1075,26 @@ async fn drive(
884 1075 let direct_invite = spec.target().is_one_to_one() && !options.concurrent;
885 1076 let offer_started = Instant::now();
886 1077 let media = control
887 .until_hangup(create_offer(&current.peer, &factory, &track, layout, direct_invite.then_some(&current.gathered)))
1078 .until_hangup(create_offer(
1079 &current.peer,
1080 &factory,
1081 &track,
1082 layout,
1083 direct_invite.then_some(&current.gathered),
1084 ))
888 1085 .await??;
889 timeline.record("offer created", format!("{} ms", offer_started.elapsed().as_millis()));
1086 timeline.record(
1087 "offer created",
1088 format!("{} ms", offer_started.elapsed().as_millis()),
1089 );
890 1090 layout_plan = media.plan.clone();
891 1091 if layout == Layout::OneToOne {
892 1092 direct_video_mid = Some(CAMERA_MID.to_owned());
893 1093 }
894 timeline.record("setLocalDescription", format!("{} m-line(s) signaled", media.signaled.lines.len()));
1094 timeline.record(
1095 "setLocalDescription",
1096 format!("{} m-line(s) signaled", media.signaled.lines.len()),
1097 );
895 1098 timeline.record_sdp("local offer", &media.signaled.sdp);
896 1099 dump_sdp(options, "1-browser-offer.sdp", &media.browser_offer);
897 1100 dump_sdp(options, "2-teams-offer.sdp", &media.signaled.sdp);
@@ -950,7 +1153,11 @@ async fn drive(
950 1153 threadless: notification.thread_id.is_none(),
951 1154 });
952 1155 let one_to_one = !attached.from_mixer && !notification.is_multi_party;
953 layout = if one_to_one { Layout::OneToOne } else { Layout::Conference };
1156 layout = if one_to_one {
1157 Layout::OneToOne
1158 } else {
1159 Layout::Conference
1160 };
954 1161 let camera_track = local_video.camera_track();
955 1162 let video_answer = match accept_mode {
956 1163 _ if !one_to_one => AnswerVideo::Reject,
@@ -958,21 +1165,34 @@ async fn drive(
958 1165 _ => AnswerVideo::Receive,
959 1166 };
960 1167 dump_sdp(options, "3-teams-offer.sdp", &teams_offer);
961 let answered = answer_offer(&current.peer, Some(&track), &teams_offer, video_answer, None, false, one_to_one.then_some(&current.gathered)).await?;
1168 let answered = answer_offer(
1169 &current.peer,
1170 Some(&track),
1171 &teams_offer,
1172 video_answer,
1173 None,
1174 false,
1175 one_to_one.then_some(&current.gathered),
1176 )
1177 .await?;
962 1178 layout_plan = answered.remote.plan();
963 1179 direct_video_mid = answered.camera_mid.clone();
964 timeline.record("setRemoteDescription", format!("offer applied, {} signaled line(s)", answered.remote.lines.len()));
965 if one_to_one {
966 timeline.record("ice gathered", current.gathered.summary());
967 }
1180 timeline.record(
1181 "setRemoteDescription",
1182 format!(
1183 "offer applied, {} signaled line(s)",
1184 answered.remote.lines.len()
1185 ),
1186 );
968 1187 timeline.record_sdp("remote offer", &teams_offer);
969 1188 timeline.record_sdp("local answer", &answered.answer_sdp);
970 1189 dump_sdp(options, "4-teams-answer.sdp", &answered.answer_sdp);
971 let acceptance_url = attached
972 .links
973 .get("acceptance")
974 .ok_or_else(|| Error::Signaling("attach answer without an acceptance link".into()))?;
975 let modalities = accepted_modalities(matches!(video_answer, AnswerVideo::Send(_)) && answered.camera_mid.is_some());
1190 let acceptance_url = attached.links.get("acceptance").ok_or_else(|| {
1191 Error::Signaling("attach answer without an acceptance link".into())
1192 })?;
1193 let modalities = accepted_modalities(
1194 matches!(video_answer, AnswerVideo::Send(_)) && answered.camera_mid.is_some(),
1195 );
976 1196 let acknowledged = signaling
977 1197 .accept(
978 1198 acceptance_url,
@@ -991,20 +1211,36 @@ async fn drive(
991 1211 media_links.extend(acknowledged);
992 1212 if let (AnswerVideo::Send(_), Some(mid)) = (video_answer, &answered.camera_mid) {
993 1213 let camera = peer_transceiver(&current.peer, mid);
994 match camera.map(|camera| local_video.set_lines(VideoLines { camera, share: None })) {
1214 match camera.map(|camera| {
1215 local_video.set_lines(VideoLines {
1216 camera,
1217 share: None,
1218 })
1219 }) {
995 1220 Some(Ok(())) => match local_video.start_camera(&camera_choice) {
996 1221 Ok(()) => sending_camera = true,
997 Err(error) => control.send(CallUpdate::Notice(format!("Camera could not start: {error}"))),
1222 Err(error) => control.send(CallUpdate::Notice(format!(
1223 "Camera could not start: {error}"
1224 ))),
998 1225 },
999 Some(Err(error)) => timeline.record("video lines not attached", error.to_string()),
1000 None => timeline.record("video lines not attached", "no transceiver for the camera line"),
1226 Some(Err(error)) => {
1227 timeline.record("video lines not attached", error.to_string())
1228 }
1229 None => timeline.record(
1230 "video lines not attached",
1231 "no transceiver for the camera line",
1232 ),
1001 1233 }
1002 1234 }
1003 1235 keep_alive_link = media_links.get("callLeg").cloned();
1004 1236 keep_alive_at = Some(Instant::now() + keep_alive_period(None));
1005 1237 conversation
1006 1238 }
1007 _ => return Err(Error::Callback("call plan without an offer or an invitation".into())),
1239 _ => {
1240 return Err(Error::Callback(
1241 "call plan without an offer or an invitation".into(),
1242 ));
1243 }
1008 1244 };
1009 1245 let remote = live.remote.clone().expect("remote call set above");
1010 1246 live.broker_running.store(true, Ordering::SeqCst);
@@ -1016,11 +1252,20 @@ async fn drive(
1016 1252
1017 1253 let initial = MuteEffect::initial(is_meeting);
1018 1254 let mut muted = initial.muted;
1019 live.audio.as_ref().expect("audio set above").track.set_enabled(initial.track_enabled);
1255 live.audio
1256 .as_ref()
1257 .expect("audio set above")
1258 .track
1259 .set_enabled(initial.track_enabled);
1020 1260 if muted {
1021 1261 control.send(CallUpdate::Muted(true));
1022 1262 }
1023 match setup_step(control, signaling.update_endpoint_state(&conversation, &participant, initial.endpoint_is_muted)).await {
1263 match setup_step(
1264 control,
1265 signaling.update_endpoint_state(&conversation, &participant, initial.endpoint_is_muted),
1266 )
1267 .await
1268 {
1024 1269 Err(Error::Cancelled) => return Err(Error::Cancelled),
1025 1270 Err(error) => timeline.record("updateEndpointState failed", error.to_string()),
1026 1271 Ok(()) => {}
@@ -1038,7 +1283,13 @@ async fn drive(
1038 1283 && roster.apply_snapshot(snapshot)
1039 1284 {
1040 1285 let entries = roster.entries();
1041 timeline.record("roster", format!("{} participant(s) from the conversation answer", entries.len()));
1286 timeline.record(
1287 "roster",
1288 format!(
1289 "{} participant(s) from the conversation answer",
1290 entries.len()
1291 ),
1292 );
1042 1293 control.send(CallUpdate::Roster(entries));
1043 1294 }
1044 1295 let mut lobby = false;
@@ -1063,7 +1314,25 @@ async fn drive(
1063 1314 crate::noise_stage::apply(mic_settings);
1064 1315 let mut audio_disabled = false;
1065 1316 let mut remote_audio: Option<RtcAudioTrack> = None;
1066 sync_software_audio(&factory, options, &input, muted, None, &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1317 sync_software_audio(
1318 &factory,
1319 options,
1320 &input,
1321 muted,
1322 None,
1323 &current.peer,
1324 &track,
1325 software_wanted(
1326 mic_settings,
1327 share_sound_wanted,
1328 &local_video,
1329 live.audio.as_ref(),
1330 ),
1331 false,
1332 &mut software_audio,
1333 control,
1334 timeline,
1335 );
1067 1336 let mut own_hand: Option<String> = None;
1068 1337 let mut depacketizer = Depacketizer::default();
1069 1338 let mut caption_flow = CaptionFlow::default();
@@ -1083,6 +1352,7 @@ async fn drive(
1083 1352 let mut send_requests = RequestFilter::default();
1084 1353 let mut send_capabilities = SendCapabilityReporter::default();
1085 1354 let mut same_peer_deadline: Option<Instant> = None;
1355 let mut same_peer_grace_until: Option<Instant> = None;
1086 1356 let mut meeting_chat = conversation.chat_thread.clone();
1087 1357 if let Some(thread) = &meeting_chat {
1088 1358 control.send(CallUpdate::MeetingChat(thread.clone()));
@@ -1095,6 +1365,7 @@ async fn drive(
1095 1365 }
1096 1366 let mut start_camera_pending = options.start_camera;
1097 1367 let mut share_pending: Option<ShareSource> = None;
1368 let mut portal_pending: Option<ShareKind> = None;
1098 1369 let mut glare_resend: Option<GlareResend> = None;
1099 1370 let mut deferred_changes: Vec<Change> = Vec::new();
1100 1371 let mut remote_direct_share: Option<String> = None;
@@ -1109,10 +1380,19 @@ async fn drive(
1109 1380 {
1110 1381 control.defer(CallCommand::StartShare(source));
1111 1382 }
1112 if next.as_ref().is_some_and(|pending| pending.connected && (pending.offered.is_some() || pending.retargeted))
1113 && let Some(pending) = next.take()
1383 if video_possible(remote_set, layout, negotiator.path())
1384 && let Some(kind) = portal_pending.take()
1114 1385 {
1115 timeline.record("escalation", "new peer connection connected, old one dropped");
1386 control.defer(CallCommand::StartPortalShare(kind));
1387 }
1388 if next.as_ref().is_some_and(|pending| {
1389 pending.connected && (pending.offered.is_some() || pending.retargeted)
1390 }) && let Some(pending) = next.take()
1391 {
1392 timeline.record(
1393 "escalation",
1394 "new peer connection connected, old one dropped",
1395 );
1116 1396 deferred_changes.clear();
1117 1397 negotiator.server_escalation_done();
1118 1398 if let Some(mid) = remote_direct_share.take() {
@@ -1137,15 +1417,40 @@ async fn drive(
1137 1417 timeline.record("video lines not attached", error.to_string());
1138 1418 }
1139 1419 if local_video.camera_on() {
1140 tell_media_descriptions(&remote, &media_links, MediaDescription::camera(true), &mut media_description_request, timeline);
1420 tell_media_descriptions(
1421 &remote,
1422 &media_links,
1423 MediaDescription::camera(true),
1424 &mut media_description_request,
1425 timeline,
1426 );
1141 1427 }
1142 1428 if local_video.sharing() {
1143 tell_media_descriptions(&remote, &media_links, MediaDescription::share(true), &mut media_description_request, timeline);
1429 tell_media_descriptions(
1430 &remote,
1431 &media_links,
1432 MediaDescription::share(true),
1433 &mut media_description_request,
1434 timeline,
1435 );
1144 1436 }
1145 1437 }
1146 1438 remote_set = true;
1147 1439 if layout == Layout::OneToOne && negotiator.begin_conference_upgrade() {
1148 let pending = escalate(&factory, &grant, options, outgoing_track(software_audio.as_ref(), &track), &remote, &links, &media_leg_id, &media_links, &mut negotiator, live, timeline).await;
1440 let pending = escalate(
1441 &factory,
1442 &grant,
1443 options,
1444 outgoing_track(software_audio.as_ref(), &track),
1445 &remote,
1446 &links,
1447 &media_leg_id,
1448 &media_links,
1449 &mut negotiator,
1450 live,
1451 timeline,
1452 )
1453 .await;
1149 1454 if pending.is_none() {
1150 1455 drop_local_media(&mut local_video, control);
1151 1456 }
@@ -1268,6 +1573,7 @@ async fn drive(
1268 1573 && let Some(pending) = same_peer.take()
1269 1574 {
1270 1575 same_peer_deadline = None;
1576 same_peer_grace_until = None;
1271 1577 let applied = match pending.change {
1272 1578 Change::Hold(_) => apply_hold_answer(&current.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await,
1273 1579 Change::Camera(_) | Change::Share(_) => apply_answer(&current.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await,
@@ -1287,7 +1593,7 @@ async fn drive(
1287 1593 Change::Share(true) if !answer.from_mixer && !local_video.share_sending() => {
1288 1594 local_video.stop_share();
1289 1595 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1290 control.send(CallUpdate::LocalShare(None));
1596 clear_share(control);
1291 1597 control.send(CallUpdate::Notice(SHARE_REFUSED_NOTICE.into()));
1292 1598 }
1293 1599 Change::Share(_) => {}
@@ -1348,6 +1654,7 @@ async fn drive(
1348 1654 && let Some(pending) = same_peer.take()
1349 1655 {
1350 1656 same_peer_deadline = None;
1657 same_peer_grace_until = None;
1351 1658 negotiator.same_peer_offer_failed();
1352 1659 rollback_offer(&current.peer).await;
1353 1660 timeline.record("glare", "the remote offer is answered first, ours goes out again after");
@@ -1359,6 +1666,7 @@ async fn drive(
1359 1666 MediaAction::AnswerOnNewPeer => {
1360 1667 if let Some(pending) = same_peer.take() {
1361 1668 same_peer_deadline = None;
1669 same_peer_grace_until = None;
1362 1670 timeline.record("same-peer offer", "superseded by the escalation offer");
1363 1671 rollback_offer(&current.peer).await;
1364 1672 defer_to_new_peer(pending.change, &mut deferred_changes, &mut local_video, control);
@@ -1659,6 +1967,7 @@ async fn drive(
1659 1967 Ok(CallEvent::Rejection(body)) => match negotiator.on_rejection() {
1660 1968 RejectedOffer::SamePeer => {
1661 1969 same_peer_deadline = None;
1970 same_peer_grace_until = None;
1662 1971 if let Some(pending) = same_peer.take() {
1663 1972 rollback_offer(&current.peer).await;
1664 1973 if is_glare_rejection(&body) {
@@ -1878,6 +2187,7 @@ async fn drive(
1878 2187 timeline.record_sdp("local offer", &signaled.sdp);
1879 2188 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(true), reply_tags });
1880 2189 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2190 same_peer_grace_until = None;
1881 2191 }
1882 2192 Err(error) => {
1883 2193 timeline.record("camera offer failed", error.to_string());
@@ -1900,6 +2210,7 @@ async fn drive(
1900 2210 timeline.record_sdp("local offer", &signaled.sdp);
1901 2211 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(false), reply_tags });
1902 2212 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2213 same_peer_grace_until = None;
1903 2214 }
1904 2215 Err(error) => {
1905 2216 timeline.record("camera offer failed", error.to_string());
@@ -1924,15 +2235,63 @@ async fn drive(
1924 2235 control.send(CallUpdate::Notice(format!("Camera could not start: {error}")));
1925 2236 }
1926 2237 }
2238 Some(CallCommand::SetVideoQuality(quality)) => {
2239 local_video.set_video_quality(quality);
2240 if let Err(error) = local_video.refresh_camera_capture(&camera_choice) {
2241 control.send(CallUpdate::Notice(format!("Camera could not restart: {error}")));
2242 }
2243 if video.set_video_quality(quality) {
2244 send_receive_change(control, video.reselect(&roster));
2245 }
2246 }
2247 Some(CallCommand::StartPortalShare(kind)) => {
2248 let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;
2249 if !remote_set {
2250 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
2251 } else if local_hold {
2252 control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into()));
2253 } else if direct && !local_video.sharing() && (same_peer.is_some() || glare_resend.is_some()) {
2254 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
2255 } else if direct
2256 && !local_video.sharing()
2257 && !local_video.has_share_line()
2258 && let Err(error) = attach_share_line(&current.peer, &factory, &mut local_video, direct_video_mid.as_deref())
2259 {
2260 control.send(CallUpdate::Notice(format!("Sharing could not start: {error}")));
2261 } else if !local_video.sharing() && !video_possible(remote_set, layout, negotiator.path()) {
2262 if next.is_none() && negotiator.begin_conference_upgrade() {
2263 let pending = escalate(&factory, &grant, options, outgoing_track(software_audio.as_ref(), &track), &remote, &links, &media_leg_id, &media_links, &mut negotiator, live, timeline).await;
2264 next = pending.or(next);
2265 }
2266 if next.is_some() {
2267 portal_pending = Some(kind);
2268 control.send(CallUpdate::Notice(SHARE_QUEUED_NOTICE.into()));
2269 } else {
2270 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
2271 }
2272 } else if let Err(error) = local_video.open_portal(kind, control.command_sender()) {
2273 control.send(CallUpdate::Notice(format!("Sharing could not start: {error}")));
2274 }
2275 }
2276 Some(CallCommand::FinishPortalShare { source, generation }) => {
2277 if local_video.accept_portal(generation) {
2278 control.defer(CallCommand::StartShare(source));
2279 }
2280 }
2281 Some(CallCommand::AbandonPortalShare) => {
2282 if local_video.portal_is_open() {
2283 local_video.stop_share();
2284 }
2285 }
1927 2286 Some(CallCommand::StartShare(source)) => {
1928 2287 let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;
1929 2288 if !remote_set {
1930 2289 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
1931 2290 } else if local_hold {
1932 2291 control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into()));
1933 } else if direct && local_video.sharing() {
2292 } else if direct && local_video.share_sending() {
1934 2293 match local_video.start_share(&source) {
1935 Ok(()) => control.send(CallUpdate::LocalShare(Some(source.label()))),
2294 Ok(()) => announce_share(control, &source),
1936 2295 Err(error) => control.send(CallUpdate::Notice(format!("Sharing could not start: {error}"))),
1937 2296 }
1938 2297 } else if direct && (same_peer.is_some() || glare_resend.is_some()) {
@@ -1945,13 +2304,14 @@ async fn drive(
1945 2304 } else if direct {
1946 2305 match local_video.start_share(&source) {
1947 2306 Ok(()) => {
1948 control.send(CallUpdate::LocalShare(Some(source.label())));
2307 announce_share(control, &source);
1949 2308 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1950 2309 match offer_same_peer(&current.peer, &current.gathered, local_video.share_mid(), &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), false, local_video.camera_on(), true, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
1951 2310 Ok((browser_offer, signaled, reply_tags)) => {
1952 2311 timeline.record_sdp("local offer", &signaled.sdp);
1953 2312 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(true), reply_tags });
1954 2313 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2314 same_peer_grace_until = None;
1955 2315 }
1956 2316 Err(error) => {
1957 2317 timeline.record("share offer failed", error.to_string());
@@ -1975,7 +2335,7 @@ async fn drive(
1975 2335 } else {
1976 2336 match local_video.start_share(&source) {
1977 2337 Ok(()) => {
1978 control.send(CallUpdate::LocalShare(Some(source.label())));
2338 announce_share(control, &source);
1979 2339 tell_media_descriptions(&remote, &media_links, MediaDescription::share(true), &mut media_description_request, timeline);
1980 2340 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1981 2341 }
@@ -1986,24 +2346,28 @@ async fn drive(
1986 2346 Some(CallCommand::StopShare) => {
1987 2347 let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;
1988 2348 share_pending = None;
1989 if direct && local_video.sharing() && (same_peer.is_some() || glare_resend.is_some()) {
2349 portal_pending = None;
2350 if local_video.portal_is_open() {
2351 local_video.stop_share();
2352 } else if direct && local_video.sharing() && (same_peer.is_some() || glare_resend.is_some()) {
1990 2353 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
1991 2354 } else if direct && local_video.sharing() {
1992 2355 local_video.stop_share();
1993 control.send(CallUpdate::LocalShare(None));
2356 clear_share(control);
1994 2357 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1995 2358 match offer_same_peer(&current.peer, &current.gathered, local_video.share_mid(), &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), local_hold, local_video.camera_on(), false, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
1996 2359 Ok((browser_offer, signaled, reply_tags)) => {
1997 2360 timeline.record_sdp("local offer", &signaled.sdp);
1998 2361 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(false), reply_tags });
1999 2362 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2363 same_peer_grace_until = None;
2000 2364 }
2001 2365 Err(error) => timeline.record("share offer failed", error.to_string()),
2002 2366 }
2003 2367 } else if local_video.sharing() {
2004 2368 local_video.stop_share();
2005 2369 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
2006 control.send(CallUpdate::LocalShare(None));
2370 clear_share(control);
2007 2371 tell_media_descriptions(&remote, &media_links, MediaDescription::share(false), &mut media_description_request, timeline);
2008 2372 }
2009 2373 }
@@ -2225,6 +2589,7 @@ async fn drive(
2225 2589 timeline.record_sdp("local offer", &signaled.sdp);
2226 2590 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Hold(hold), reply_tags });
2227 2591 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2592 same_peer_grace_until = None;
2228 2593 }
2229 2594 Err(error) => {
2230 2595 timeline.record("hold failed", error.to_string());
@@ -2341,7 +2706,8 @@ async fn drive(
2341 2706 if layout == Layout::Conference
2342 2707 && let Some(size) = local_video.camera_size()
2343 2708 && let Some(url) = media_links.get("applyChannelParameters").cloned()
2344 && let Some(body) = send_capabilities.body_for(size)
2709 && let Some(body) =
2710 send_capabilities.body_for(size, local_video.video_quality())
2345 2711 {
2346 2712 let signaling = signaling.clone();
2347 2713 let timeline = timeline.clone();
@@ -2437,12 +2803,13 @@ async fn drive(
2437 2803 timeline.record(
2438 2804 "stats",
2439 2805 format!(
2440 "in packets={} bytes={} level={:.3} rms={decoded_rms:.3} tone={ratio:.2} out packets={} mic={:.3} erle={:.1} dtls={} video in packets={} decoded={} {}x{} out packets={} encoded={} {}x{} mixer reports {} (rtt {:.0} ms) out bytes={} sources={:?} video senders={:?}{}",
2806 "in packets={} bytes={} level={:.3} rms={decoded_rms:.3} tone={ratio:.2} out packets={} mic={:.3} erle={:.1} dtls={} video in packets={} decoded={} {}x{} out packets={} encoded={} {}x{} mixer reports {} (rtt {:.0} ms) out bytes={} sources={:?} video senders={:?}{}{}",
2441 2807 snapshot.inbound_packets, snapshot.inbound_bytes, snapshot.audio_level, snapshot.outbound_packets, snapshot.local_level, snapshot.echo_return_loss_enhancement, snapshot.dtls_state,
2442 2808 snapshot.video.inbound_packets, snapshot.video.inbound_frames_decoded, snapshot.video.inbound_width, snapshot.video.inbound_height,
2443 2809 snapshot.video.outbound_packets, snapshot.video.outbound_frames_encoded, snapshot.video.outbound_width, snapshot.video.outbound_height,
2444 2810 snapshot.video.remote_reports, snapshot.video.remote_round_trip_ms, snapshot.outbound_bytes, snapshot.source_levels, snapshot.video_senders,
2445 snapshot.share_receive.as_ref().filter(|_| snapshot.share_inbound_packets > 0).map(ShareReceive::summary).unwrap_or_default()
2811 snapshot.share_receive.as_ref().filter(|_| snapshot.share_inbound_packets > 0).map(ShareReceive::summary).unwrap_or_default(),
2812 local_video.camera_capture_summary().unwrap_or_default()
2446 2813 ),
2447 2814 );
2448 2815 }
@@ -2487,6 +2854,7 @@ async fn drive(
2487 2854 control.send(CallUpdate::Camera(false));
2488 2855 }
2489 2856 share_pending = None;
2857 portal_pending = None;
2490 2858 settle_failed_escalation(pending.offered.is_none(), layout, &mut negotiator, &mut deferred_changes, &mut local_video, control);
2491 2859 timeline.record("escalation failed", "no answer for the new peer connection in time");
2492 2860 control.send(CallUpdate::Notice(VIDEO_FAILED_NOTICE.into()));
@@ -2517,6 +2885,7 @@ async fn drive(
2517 2885 timeline.record_sdp("local offer", &signaled.sdp);
2518 2886 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: resend.change, reply_tags });
2519 2887 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2888 same_peer_grace_until = None;
2520 2889 }
2521 2890 Err(error) => {
2522 2891 timeline.record("offer after glare failed", error.to_string());
@@ -2527,6 +2896,16 @@ async fn drive(
2527 2896 }
2528 2897 _ = sleep_until(same_peer_deadline.unwrap_or_else(far_future)), if same_peer_deadline.is_some() => {
2529 2898 same_peer_deadline = None;
2899 if same_peer.is_some() {
2900 same_peer_grace_until = Some(Instant::now() + SAME_PEER_LATE_GRACE);
2901 timeline.record(
2902 "same-peer offer",
2903 "no answer yet, waiting a little longer",
2904 );
2905 }
2906 }
2907 _ = sleep_until(same_peer_grace_until.unwrap_or_else(far_future)), if same_peer_grace_until.is_some() => {
2908 same_peer_grace_until = None;
2530 2909 if let Some(pending) = same_peer.take() {
2531 2910 timeline.record("same-peer offer", "no answer in time");
2532 2911 negotiator.same_peer_offer_failed();
@@ -2554,6 +2933,10 @@ async fn drive(
2554 2933 }
2555 2934 }
2556 2935 }
2936 if software_audio.is_some() {
2937 timeline.record("software audio", "stopping before tear down");
2938 drop(software_audio);
2939 }
2557 2940 live.callbacks = Some(callbacks);
2558 2941 Ok(())
2559 2942 }
@@ -2574,9 +2957,20 @@ async fn start_escalation(
2574 2957 .ok_or_else(|| Error::Signaling("acceptance without a mediaRenegotiation link".into()))?;
2575 2958 let session = open_peer(factory, grant, &options.relay_host, false)?;
2576 2959 let media = create_offer(&session.peer, factory, track, Layout::Conference, None).await?;
2577 let body = renegotiation_body(&remote.participant, links, &media.signaled.sdp, media_leg_id, &media.modalities, true, false);
2960 let body = renegotiation_body(
2961 &remote.participant,
2962 links,
2963 &media.signaled.sdp,
2964 media_leg_id,
2965 &media.modalities,
2966 true,
2967 false,
2968 );
2578 2969 let reply_tags = offer_reply_tags(&body);
2579 remote.signaling.post_json("POST mediaRenegotiation", url, body).await?;
2970 remote
2971 .signaling
2972 .post_json("POST mediaRenegotiation", url, body)
2973 .await?;
2580 2974 Ok(NextPeer {
2581 2975 session,
2582 2976 offered: Some(media),
@@ -2637,7 +3031,16 @@ async fn answer_on_new_peer(
2637 3031 teams_offer: &str,
2638 3032 ) -> Result<(PeerSession, AnsweredMedia)> {
2639 3033 let session = open_peer(factory, grant, &options.relay_host, false)?;
2640 let answered = answer_offer(&session.peer, Some(track), teams_offer, AnswerVideo::Reject, None, false, None).await?;
3034 let answered = answer_offer(
3035 &session.peer,
3036 Some(track),
3037 teams_offer,
3038 AnswerVideo::Reject,
3039 None,
3040 false,
3041 None,
3042 )
3043 .await?;
2641 3044 Ok((session, answered))
2642 3045 }
2643 3046
@@ -2651,8 +3054,16 @@ async fn send_media_answer(
2651 3054 let url = reply_links
2652 3055 .get("mediaAnswer")
2653 3056 .ok_or_else(|| Error::Signaling("renegotiation without a mediaAnswer link".into()))?;
2654 let body = escalation_answer_body(&remote.participant, links, &answered.answer_sdp, media_leg_id);
2655 remote.signaling.post_json("POST mediaAnswer", url, body).await
3057 let body = escalation_answer_body(
3058 &remote.participant,
3059 links,
3060 &answered.answer_sdp,
3061 media_leg_id,
3062 );
3063 remote
3064 .signaling
3065 .post_json("POST mediaAnswer", url, body)
3066 .await
2656 3067 }
2657 3068
2658 3069 #[allow(clippy::too_many_arguments)]
@@ -2675,7 +3086,9 @@ fn negotiate_video(
2675 3086 }
2676 3087 };
2677 3088 let table = SlotTable::from_streams(&streams);
2678 let link = links.get("applyChannelParameters").or_else(|| links.get("controlVideoStreaming"));
3089 let link = links
3090 .get("applyChannelParameters")
3091 .or_else(|| links.get("controlVideoStreaming"));
2679 3092 timeline.record(
2680 3093 "video slots",
2681 3094 format!(
@@ -2685,9 +3098,15 @@ fn negotiate_video(
2685 3098 link.is_some()
2686 3099 ),
2687 3100 );
2688 let requester = link
2689 .filter(|_| from_mixer)
2690 .map(|url| SourceRequester::start(signaling.clone(), url.clone(), video.router().clone(), control.video.clone(), timeline.clone()));
3101 let requester = link.filter(|_| from_mixer).map(|url| {
3102 SourceRequester::start(
3103 signaling.clone(),
3104 url.clone(),
3105 video.router().clone(),
3106 control.video.clone(),
3107 timeline.clone(),
3108 )
3109 });
2691 3110 video.negotiated(table, requester);
2692 3111 send_receive_change(control, video.reselect(roster));
2693 3112 }
@@ -2701,17 +3120,33 @@ const SHARE_REFUSED_NOTICE: &str = "The other side did not accept the screen sha
2701 3120
2702 3121 async fn camera_devices(mode: VideoMode) -> Vec<CameraDevice> {
2703 3122 match mode {
2704 VideoMode::Pattern => vec![CameraDevice { key: "pattern".into(), name: "Test pattern".into() }],
3123 VideoMode::Pattern => vec![CameraDevice {
3124 key: "pattern".into(),
3125 name: "Test pattern".into(),
3126 }],
2705 3127 VideoMode::Off => Vec::new(),
2706 VideoMode::Platform => tokio::task::spawn_blocking(list_cameras).await.unwrap_or_default(),
3128 VideoMode::Platform => tokio::task::spawn_blocking(list_cameras)
3129 .await
3130 .unwrap_or_default(),
2707 3131 }
2708 3132 }
2709 3133
2710 fn refresh_cameras(updates: mpsc::UnboundedSender<CallUpdate>, mode: VideoMode, timeline: Timeline) {
3134 fn refresh_cameras(
3135 updates: mpsc::UnboundedSender<CallUpdate>,
3136 mode: VideoMode,
3137 timeline: Timeline,
3138 ) {
2711 3139 tokio::spawn(async move {
2712 3140 let started = Instant::now();
2713 3141 let cameras = camera_devices(mode).await;
2714 timeline.record("camera list", format!("{} camera(s) in {} ms", cameras.len(), started.elapsed().as_millis()));
3142 timeline.record(
3143 "camera list",
3144 format!(
3145 "{} camera(s) in {} ms",
3146 cameras.len(),
3147 started.elapsed().as_millis()
3148 ),
3149 );
2715 3150 let _ = updates.send(CallUpdate::Cameras(cameras));
2716 3151 });
2717 3152 }
@@ -2720,37 +3155,85 @@ const SHARE_THUMBNAIL_WINDOWS: usize = 12;
2720 3155 const SHARE_THUMBNAIL_WIDTH: u32 = 320;
2721 3156 const SHARE_THUMBNAIL_HEIGHT: u32 = 180;
2722 3157
2723 fn refresh_share_sources(updates: mpsc::UnboundedSender<CallUpdate>, mode: VideoMode, with_thumbnails: bool) {
3158 fn announce_share(control: &CallControl, source: &ShareSource) {
3159 control.send(CallUpdate::ShareKind(Some(source.kind)));
3160 control.send(CallUpdate::LocalShare(Some(source.label())));
3161 }
3162
3163 fn clear_share(control: &CallControl) {
3164 control.send(CallUpdate::ShareKind(None));
3165 control.send(CallUpdate::LocalShare(None));
3166 }
3167
3168 fn refresh_share_sources(
3169 updates: mpsc::UnboundedSender<CallUpdate>,
3170 mode: VideoMode,
3171 with_thumbnails: bool,
3172 ) {
2724 3173 tokio::spawn(async move {
3174 let picker = current_share_picker();
2725 3175 let sources = match mode {
2726 3176 VideoMode::Pattern => vec![
2727 ShareSource { id: 1, kind: ShareKind::Screen, title: "Test screen".into() },
2728 ShareSource { id: 2, kind: ShareKind::Window, title: "Test window".into() },
3177 ShareSource {
3178 id: 1,
3179 kind: ShareKind::Screen,
3180 title: "Test screen".into(),
3181 },
3182 ShareSource {
3183 id: 2,
3184 kind: ShareKind::Window,
3185 title: "Test window".into(),
3186 },
2729 3187 ],
2730 3188 VideoMode::Off => Vec::new(),
2731 VideoMode::Platform => tokio::task::spawn_blocking(list_share_sources).await.unwrap_or_default(),
3189 VideoMode::Platform if picker == SharePicker::Portal => Vec::new(),
3190 VideoMode::Platform => tokio::task::spawn_blocking(list_share_sources)
3191 .await
3192 .unwrap_or_default(),
2732 3193 };
3194 let sources = share_sources_for_menu(picker, sources);
2733 3195 let _ = updates.send(CallUpdate::ShareSources(sources.clone()));
2734 if !with_thumbnails {
3196 if picker == SharePicker::Portal || !with_thumbnails {
2735 3197 return;
2736 3198 }
2737 3199 let wanted: Vec<ShareSource> = sources
2738 3200 .iter()
2739 3201 .filter(|source| source.kind == ShareKind::Screen)
2740 .chain(sources.iter().filter(|source| source.kind == ShareKind::Window).take(SHARE_THUMBNAIL_WINDOWS))
3202 .chain(
3203 sources
3204 .iter()
3205 .filter(|source| source.kind == ShareKind::Window)
3206 .take(SHARE_THUMBNAIL_WINDOWS),
3207 )
2741 3208 .cloned()
2742 3209 .collect();
2743 3210 for source in wanted {
2744 3211 let picture = match mode {
2745 3212 VideoMode::Platform => {
2746 3213 let wanted = source.clone();
2747 tokio::task::spawn_blocking(move || share_thumbnail(&wanted, SHARE_THUMBNAIL_WIDTH, SHARE_THUMBNAIL_HEIGHT)).await.ok().flatten()
3214 tokio::task::spawn_blocking(move || {
3215 share_thumbnail(&wanted, SHARE_THUMBNAIL_WIDTH, SHARE_THUMBNAIL_HEIGHT)
3216 })
3217 .await
3218 .ok()
3219 .flatten()
2748 3220 }
2749 VideoMode::Pattern => Some(VideoPicture::solid(SHARE_THUMBNAIL_WIDTH, SHARE_THUMBNAIL_HEIGHT, 120, 80, 40)),
3221 VideoMode::Pattern => Some(VideoPicture::solid(
3222 SHARE_THUMBNAIL_WIDTH,
3223 SHARE_THUMBNAIL_HEIGHT,
3224 120,
3225 80,
3226 40,
3227 )),
2750 3228 VideoMode::Off => None,
2751 3229 };
2752 3230 if let Some(picture) = picture
2753 && updates.send(CallUpdate::ShareThumbnail { source, picture: Arc::new(picture) }).is_err()
3231 && updates
3232 .send(CallUpdate::ShareThumbnail {
3233 source,
3234 picture: Arc::new(picture),
3235 })
3236 .is_err()
2754 3237 {
2755 3238 return;
2756 3239 }
@@ -2774,8 +3257,14 @@ fn tell_media_descriptions(
2774 3257 let signaling = remote.signaling.clone();
2775 3258 let timeline = timeline.clone();
2776 3259 tokio::spawn(async move {
2777 let sent = format!("{} {} request {request_id}", description.mid, description.direction);
2778 if let Err(error) = signaling.update_media_descriptions(&url, &[description], request_id).await {
3260 let sent = format!(
3261 "{} {} request {request_id}",
3262 description.mid, description.direction
3263 );
3264 if let Err(error) = signaling
3265 .update_media_descriptions(&url, &[description], request_id)
3266 .await
3267 {
2779 3268 timeline.record("updateMediaDescriptions failed", format!("{sent}: {error}"));
2780 3269 }
2781 3270 });
@@ -2785,30 +3274,54 @@ fn is_own_meeting(own: Option<&MeetingTarget>, target: &MeetingTarget) -> bool {
2785 3274 own.is_some_and(|own| own.thread_id == target.thread_id)
2786 3275 }
2787 3276
2788 fn attach_share_line(peer: &PeerConnection, factory: &PeerConnectionFactory, local_video: &mut LocalVideo, camera_mid: Option<&str>) -> Result<()> {
3277 fn attach_share_line(
3278 peer: &PeerConnection,
3279 factory: &PeerConnectionFactory,
3280 local_video: &mut LocalVideo,
3281 camera_mid: Option<&str>,
3282 ) -> Result<()> {
2789 3283 let camera = camera_mid.and_then(|mid| peer_transceiver(peer, mid));
2790 3284 if !local_video.has_lines() && camera.is_none() {
2791 3285 return Err(Error::Webrtc("no video line negotiated".into()));
2792 3286 }
2793 3287 let share = add_share_line(peer, factory)?;
2794 local_video.add_share_line(share.clone(), camera).inspect_err(|_| {
2795 let _ = share.stop();
2796 })
3288 local_video
3289 .add_share_line(share.clone(), camera)
3290 .inspect_err(|_| {
3291 let _ = share.stop();
3292 })
2797 3293 }
2798 3294
2799 3295 fn peer_transceiver(peer: &PeerConnection, mid: &str) -> Option<RtpTransceiver> {
2800 peer.transceivers().into_iter().find(|transceiver| transceiver.mid().as_deref() == Some(mid))
3296 peer.transceivers()
3297 .into_iter()
3298 .find(|transceiver| transceiver.mid().as_deref() == Some(mid))
2801 3299 }
2802 3300
2803 fn start_camera_line(local_video: &mut LocalVideo, peer: &PeerConnection, direct_mid: Option<&str>, choice: &DeviceChoice) -> Result<()> {
3301 fn start_camera_line(
3302 local_video: &mut LocalVideo,
3303 peer: &PeerConnection,
3304 direct_mid: Option<&str>,
3305 choice: &DeviceChoice,
3306 ) -> Result<()> {
2804 3307 if !local_video.has_lines() {
2805 3308 let mid = direct_mid.ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?;
2806 let camera = peer_transceiver(peer, mid).ok_or_else(|| Error::Webrtc("no transceiver for the camera line".into()))?;
2807 if !matches!(camera.direction(), RtpTransceiverDirection::SendRecv | RtpTransceiverDirection::SendOnly) {
2808 peer.add_track(MediaStreamTrack::Video(local_video.camera_track()), &[CAMERA_STREAM])
2809 .map_err(|error| Error::Webrtc(error.to_string()))?;
3309 let camera = peer_transceiver(peer, mid)
3310 .ok_or_else(|| Error::Webrtc("no transceiver for the camera line".into()))?;
3311 if !matches!(
3312 camera.direction(),
3313 RtpTransceiverDirection::SendRecv | RtpTransceiverDirection::SendOnly
3314 ) {
3315 peer.add_track(
3316 MediaStreamTrack::Video(local_video.camera_track()),
3317 &[CAMERA_STREAM],
3318 )
3319 .map_err(|error| Error::Webrtc(error.to_string()))?;
2810 3320 }
2811 local_video.set_lines(VideoLines { camera, share: None })?;
3321 local_video.set_lines(VideoLines {
3322 camera,
3323 share: None,
3324 })?;
2812 3325 }
2813 3326 local_video.start_camera(choice)
2814 3327 }
@@ -2836,9 +3349,22 @@ async fn offer_same_peer(
2836 3349 .cloned()
2837 3350 .ok_or_else(|| Error::Signaling("this call has no mediaRenegotiation link".into()))?;
2838 3351 if !negotiator.begin_same_peer_offer() {
2839 return Err(Error::Signaling("another media negotiation is running".into()));
3352 return Err(Error::Signaling(
3353 "another media negotiation is running".into(),
3354 ));
2840 3355 }
2841 let offered = build_same_peer_offer(peer, plan, layout, hold, camera, share, camera_mid, own_share_mid, direct.then_some(gathered)).await;
3356 let offered = build_same_peer_offer(
3357 peer,
3358 plan,
3359 layout,
3360 hold,
3361 camera,
3362 share,
3363 camera_mid,
3364 own_share_mid,
3365 direct.then_some(gathered),
3366 )
3367 .await;
2842 3368 let (text, signaled) = match offered {
2843 3369 Ok(offered) => offered,
2844 3370 Err(error) => {
@@ -2846,10 +3372,25 @@ async fn offer_same_peer(
2846 3372 return Err(error);
2847 3373 }
2848 3374 };
2849 let modalities = offer_modalities(layout == Layout::OneToOne && camera && !hold, share && !hold);
2850 let body = renegotiation_body(&remote.participant, links, &signaled.sdp, media_leg_id, &modalities, false, direct);
3375 let modalities = offer_modalities(
3376 layout == Layout::OneToOne && camera && !hold,
3377 share && !hold,
3378 );
3379 let body = renegotiation_body(
3380 &remote.participant,
3381 links,
3382 &signaled.sdp,
3383 media_leg_id,
3384 &modalities,
3385 false,
3386 direct,
3387 );
2851 3388 let reply_tags = offer_reply_tags(&body);
2852 if let Err(error) = remote.signaling.post_json("POST mediaRenegotiation (same peer)", &url, body).await {
3389 if let Err(error) = remote
3390 .signaling
3391 .post_json("POST mediaRenegotiation (same peer)", &url, body)
3392 .await
3393 {
2853 3394 negotiator.same_peer_offer_failed();
2854 3395 rollback_offer(peer).await;
2855 3396 return Err(error);
@@ -2858,9 +3399,23 @@ async fn offer_same_peer(
2858 3399 }
2859 3400
2860 3401 #[allow(clippy::too_many_arguments)]
2861 async fn build_same_peer_offer(peer: &PeerConnection, plan: &OfferPlan, layout: Layout, hold: bool, camera: bool, share: bool, camera_mid: &str, own_share_mid: Option<String>, gathered: Option<&Gathered>) -> Result<(String, SignaledOffer)> {
3402 async fn build_same_peer_offer(
3403 peer: &PeerConnection,
3404 plan: &OfferPlan,
3405 layout: Layout,
3406 hold: bool,
3407 camera: bool,
3408 share: bool,
3409 camera_mid: &str,
3410 own_share_mid: Option<String>,
3411 gathered: Option<&Gathered>,
3412 ) -> Result<(String, SignaledOffer)> {
2862 3413 let offer = peer
2863 .create_offer(OfferOptions { offer_to_receive_audio: true, offer_to_receive_video: true, ..OfferOptions::default() })
3414 .create_offer(OfferOptions {
3415 offer_to_receive_audio: true,
3416 offer_to_receive_video: true,
3417 ..OfferOptions::default()
3418 })
2864 3419 .await
2865 3420 .map_err(|error| Error::Webrtc(error.to_string()))?;
2866 3421 let offer_text = offer.to_string();
@@ -2870,25 +3425,56 @@ async fn build_same_peer_offer(peer: &PeerConnection, plan: &OfferPlan, layout:
2870 3425 .and_then(|remote| direction_of(&remote.to_string(), mid))
2871 3426 .is_some_and(|direction| matches!(direction.as_str(), "sendonly" | "sendrecv"))
2872 3427 });
2873 let text = directions_for(layout, false, camera, share, camera_mid, share_mid.as_deref(), remote_shares, &offer_text);
3428 let text = directions_for(
3429 layout,
3430 false,
3431 camera,
3432 share,
3433 camera_mid,
3434 share_mid.as_deref(),
3435 remote_shares,
3436 &offer_text,
3437 );
2874 3438 let description = parse_sdp(&text, SdpType::Offer)?;
2875 3439 peer.set_local_description(description)
2876 3440 .await
2877 3441 .map_err(|error| Error::Webrtc(error.to_string()))?;
2878 3442 let mut numbers = random_u32;
2879 3443 let mut plan = plan.clone();
2880 if let Some(mid) = share_mid.as_ref().filter(|mid| !plan.screen_share_mids.contains(mid)) {
3444 if let Some(mid) = share_mid
3445 .as_ref()
3446 .filter(|mid| !plan.screen_share_mids.contains(mid))
3447 {
2881 3448 plan.screen_share_mids.push(mid.clone());
2882 3449 }
2883 let mut signaled = to_teams_offer(&directions_for(layout, hold, camera, share, camera_mid, share_mid.as_deref(), remote_shares, &text), &plan, &mut numbers)?;
3450 let mut signaled = to_teams_offer(
3451 &directions_for(
3452 layout,
3453 hold,
3454 camera,
3455 share,
3456 camera_mid,
3457 share_mid.as_deref(),
3458 remote_shares,
3459 &text,
3460 ),
3461 &plan,
3462 &mut numbers,
3463 )?;
2884 3464 signaled.sdp = direct_sdp(&signaled.sdp, gathered, SdpKind::Offer).await?;
2885 3465 if gathered.is_some()
2886 3466 && let Some(role) = negotiated_setup(
2887 peer.current_local_description().map(|local| local.to_string()).as_deref(),
2888 peer.current_remote_description().map(|remote| remote.to_string()).as_deref(),
3467 peer.current_local_description()
3468 .map(|local| local.to_string())
3469 .as_deref(),
3470 peer.current_remote_description()
3471 .map(|remote| remote.to_string())
3472 .as_deref(),
2889 3473 )
2890 3474 {
2891 signaled.sdp = signaled.sdp.replace("a=setup:actpass", &format!("a=setup:{role}"));
3475 signaled.sdp = signaled
3476 .sdp
3477 .replace("a=setup:actpass", &format!("a=setup:{role}"));
2892 3478 }
2893 3479 Ok((text, signaled))
2894 3480 }
@@ -2897,8 +3483,13 @@ async fn build_same_peer_offer(peer: &PeerConnection, plan: &OfferPlan, layout:
2897 3483 fn parse_sdp(text: &str, kind: SdpType) -> Result<SessionDescription> {
2898 3484 match std::panic::catch_unwind(|| SessionDescription::parse(text, kind)) {
2899 3485 Ok(Ok(description)) => Ok(description),
2900 Ok(Err(error)) => Err(Error::Sdp(format!("{kind:?} rejected: {}", error.description))),
2901 Err(_) => Err(Error::Sdp(format!("{kind:?} rejected, libwebrtc gave no readable reason"))),
3486 Ok(Err(error)) => Err(Error::Sdp(format!(
3487 "{kind:?} rejected: {}",
3488 error.description
3489 ))),
3490 Err(_) => Err(Error::Sdp(format!(
3491 "{kind:?} rejected, libwebrtc gave no readable reason"
3492 ))),
2902 3493 }
2903 3494 }
2904 3495
@@ -2920,7 +3511,10 @@ fn is_glare_rejection(body: &serde_json::Value) -> bool {
2920 3511
2921 3512 fn offer_reply_tags(body: &serde_json::Value) -> Vec<String> {
2922 3513 let links = &body["mediaNegotiation"]["links"];
2923 ["mediaAnswer", "rejection"].iter().filter_map(|name| links[*name].as_str().and_then(callback_tag)).collect()
3514 ["mediaAnswer", "rejection"]
3515 .iter()
3516 .filter_map(|name| links[*name].as_str().and_then(callback_tag))
3517 .collect()
2924 3518 }
2925 3519
2926 3520 #[cfg(test)]
@@ -2930,9 +3524,15 @@ mod reply_tag_tests {
2930 3524 #[test]
2931 3525 fn answers_and_rejections_match_the_offer_by_tag() {
2932 3526 let tags = vec!["aaaa1111".to_owned(), "bbbb2222".to_owned()];
2933 assert!(answers_offer("callAgent/c/aaaa1111/call/mediaAnswer/", &tags));
3527 assert!(answers_offer(
3528 "callAgent/c/aaaa1111/call/mediaAnswer/",
3529 &tags
3530 ));
2934 3531 assert!(answers_offer("callAgent/c/bbbb2222/call/rejection/", &tags));
2935 assert!(!answers_offer("callAgent/c/cccc3333/call/mediaAnswer/", &tags));
3532 assert!(!answers_offer(
3533 "callAgent/c/cccc3333/call/mediaAnswer/",
3534 &tags
3535 ));
2936 3536 assert!(answers_offer("callAgent/c/cccc3333/call/mediaAnswer/", &[]));
2937 3537 }
2938 3538
@@ -2941,11 +3541,19 @@ mod reply_tag_tests {
2941 3541 let body = serde_json::json!({"mediaNegotiation": {"links": {
2942 3542 "mediaAnswer": "https://t.example/callAgent/c/aaaa1111/call/mediaAnswer/",
2943 3543 "rejection": "https://t.example/callAgent/c/bbbb2222/call/rejection/"}}});
2944 assert_eq!(offer_reply_tags(&body), vec!["aaaa1111".to_owned(), "bbbb2222".to_owned()]);
3544 assert_eq!(
3545 offer_reply_tags(&body),
3546 vec!["aaaa1111".to_owned(), "bbbb2222".to_owned()]
3547 );
2945 3548 }
2946 3549 }
2947 3550
2948 fn defer_to_new_peer(change: Change, deferred: &mut Vec<Change>, local_video: &mut LocalVideo, control: &CallControl) {
3551 fn defer_to_new_peer(
3552 change: Change,
3553 deferred: &mut Vec<Change>,
3554 local_video: &mut LocalVideo,
3555 control: &CallControl,
3556 ) {
2949 3557 match change {
2950 3558 Change::Camera(true) => {
2951 3559 control.send(CallUpdate::Camera(true));
@@ -2957,7 +3565,14 @@ fn defer_to_new_peer(change: Change, deferred: &mut Vec<Change>, local_video: &m
2957 3565 }
2958 3566
2959 3567 /// A server escalation that fails leaves the call direct, so only what waited for the new peer is undone.
2960 fn settle_failed_escalation(server: bool, layout: Layout, negotiator: &mut MediaNegotiator, deferred: &mut Vec<Change>, local_video: &mut LocalVideo, control: &CallControl) {
3568 fn settle_failed_escalation(
3569 server: bool,
3570 layout: Layout,
3571 negotiator: &mut MediaNegotiator,
3572 deferred: &mut Vec<Change>,
3573 local_video: &mut LocalVideo,
3574 control: &CallControl,
3575 ) {
2961 3576 if server {
2962 3577 negotiator.server_escalation_failed();
2963 3578 for change in deferred.drain(..) {
@@ -2971,7 +3586,7 @@ fn settle_failed_escalation(server: bool, layout: Layout, negotiator: &mut Media
2971 3586 fn drop_local_media(local_video: &mut LocalVideo, control: &CallControl) {
2972 3587 if local_video.sharing() {
2973 3588 local_video.stop_share();
2974 control.send(CallUpdate::LocalShare(None));
3589 clear_share(control);
2975 3590 }
2976 3591 if local_video.camera_on() {
2977 3592 local_video.stop_camera();
@@ -2988,7 +3603,7 @@ fn undo_change(change: Change, local_video: &mut LocalVideo, control: &CallContr
2988 3603 Change::Camera(false) => control.send(CallUpdate::Camera(false)),
2989 3604 Change::Share(true) => {
2990 3605 local_video.stop_share();
2991 control.send(CallUpdate::LocalShare(None));
3606 clear_share(control);
2992 3607 control.send(CallUpdate::Notice("Sharing could not start".into()));
2993 3608 }
2994 3609 Change::Share(false) => {}
@@ -3004,37 +3619,65 @@ fn withhold_media(
3004 3619 local_video: &mut LocalVideo,
3005 3620 control: &CallControl,
3006 3621 ) {
3007 *muted = apply_mute(MuteCommand::Mute, *muted, audio, software_audio, remote, control);
3622 *muted = apply_mute(
3623 MuteCommand::Mute,
3624 *muted,
3625 audio,
3626 software_audio,
3627 remote,
3628 control,
3629 );
3008 3630 if local_video.camera_on() {
3009 3631 local_video.stop_camera();
3010 3632 control.send(CallUpdate::Camera(false));
3011 3633 }
3012 3634 }
3013 3635
3014 async fn apply_background(choice: BackgroundChoice, local_video: &LocalVideo, control: &CallControl, timeline: &Timeline) {
3636 async fn apply_background(
3637 choice: BackgroundChoice,
3638 local_video: &LocalVideo,
3639 control: &CallControl,
3640 timeline: &Timeline,
3641 ) {
3015 3642 match choice {
3016 3643 BackgroundChoice::None => local_video.set_background(false, None),
3017 3644 BackgroundChoice::Blur => local_video.set_background(true, None),
3018 BackgroundChoice::Image(path) => match tokio::task::spawn_blocking(move || BackgroundPicture::load(&path)).await {
3019 Ok(Ok(picture)) => local_video.set_background(true, Some(Arc::new(picture))),
3020 Ok(Err(error)) => {
3021 timeline.record("background image failed", error.to_string());
3022 control.send(CallUpdate::Notice("That background image could not be used".into()));
3645 BackgroundChoice::Image(path) => {
3646 match tokio::task::spawn_blocking(move || BackgroundPicture::load(&path)).await {
3647 Ok(Ok(picture)) => local_video.set_background(true, Some(Arc::new(picture))),
3648 Ok(Err(error)) => {
3649 timeline.record("background image failed", error.to_string());
3650 control.send(CallUpdate::Notice(
3651 "That background image could not be used".into(),
3652 ));
3653 }
3654 Err(_) => {}
3023 3655 }
3024 Err(_) => {}
3025 },
3656 }
3026 3657 }
3027 3658 }
3028 3659
3029 async fn save_meeting_options(session: &session::Session, target: &MeetingTarget, writes: &[OptionWrite]) -> std::result::Result<meeting_options::MeetingOptions, String> {
3660 async fn save_meeting_options(
3661 session: &session::Session,
3662 target: &MeetingTarget,
3663 writes: &[OptionWrite],
3664 ) -> std::result::Result<meeting_options::MeetingOptions, String> {
3030 3665 for change in writes {
3031 meeting_options::write(session, target, change).await.map_err(|error| error.to_string())?;
3666 meeting_options::write(session, target, change)
3667 .await
3668 .map_err(|error| error.to_string())?;
3032 3669 }
3033 meeting_options::fetch(session, target).await.map_err(|error| error.to_string())
3670 meeting_options::fetch(session, target)
3671 .await
3672 .map_err(|error| error.to_string())
3034 3673 }
3035 3674
3036 3675 fn target_of<'a>(roster: &'a Roster, mri: &'a str) -> Target<'a> {
3037 let display_name = roster.members().iter().find(|member| member.mri == mri).map_or("", |member| member.display_name.as_str());
3676 let display_name = roster
3677 .members()
3678 .iter()
3679 .find(|member| member.mri == mri)
3680 .map_or("", |member| member.display_name.as_str());
3038 3681 Target { mri, display_name }
3039 3682 }
3040 3683
@@ -3046,17 +3689,29 @@ fn recorder_busy(error: &Error) -> bool {
3046 3689 matches!(error, Error::Signaling(reason) if reason.contains("HTTP 409"))
3047 3690 }
3048 3691
3049 fn report_organizer_result(result: Result<u16>, label: &str, notice: &str, control: &CallControl, timeline: &Timeline) {
3692 fn report_organizer_result(
3693 result: Result<u16>,
3694 label: &str,
3695 notice: &str,
3696 control: &CallControl,
3697 timeline: &Timeline,
3698 ) {
3050 3699 if let Err(error) = &result {
3051 3700 timeline.record(format!("{label} failed"), error.to_string());
3052 3701 control.send(CallUpdate::Notice(notice.into()));
3053 3702 }
3054 control.send(CallUpdate::Organizer { action: label.to_owned(), outcome: result.map_err(|error| error.to_string()) });
3703 control.send(CallUpdate::Organizer {
3704 action: label.to_owned(),
3705 outcome: result.map_err(|error| error.to_string()),
3706 });
3055 3707 }
3056 3708
3057 3709 fn named_caption(mut entry: CaptionEntry, roster: &Roster) -> CaptionEntry {
3058 3710 if entry.display_name.is_empty() {
3059 entry.display_name = roster.name_of(&entry.user_id).unwrap_or_default().to_owned();
3711 entry.display_name = roster
3712 .name_of(&entry.user_id)
3713 .unwrap_or_default()
3714 .to_owned();
3060 3715 }
3061 3716 entry
3062 3717 }
@@ -3095,8 +3750,14 @@ async fn run_bot_steps(
3095 3750 }
3096 3751 };
3097 3752 let (join_failure, start_failure) = match job {
3098 BotJob::Captions => ("The captions service could not join", "Captions could not start"),
3099 BotJob::Recording => ("The recording service could not join", "The recording could not start"),
3753 BotJob::Captions => (
3754 "The captions service could not join",
3755 "Captions could not start",
3756 ),
3757 BotJob::Recording => (
3758 "The recording service could not join",
3759 "The recording could not start",
3760 ),
3100 3761 };
3101 3762 loop {
3102 3763 match flow.next_for(roster.caption_bot(), is_active) {
@@ -3106,12 +3767,33 @@ async fn run_bot_steps(
3106 3767 continue;
3107 3768 }
3108 3769 let Some(thread) = meeting_chat else {
3109 return fail(flow, "This call has no chat for the captions and the recording");
3770 return fail(
3771 flow,
3772 "This call has no chat for the captions and the recording",
3773 );
3110 3774 };
3111 3775 *bot_pending = true;
3112 let added = remote.signaling.add_caption_bot(&remote.conversation, &remote.participant, thread, links, remote.threadless).await;
3776 let added = remote
3777 .signaling
3778 .add_caption_bot(
3779 &remote.conversation,
3780 &remote.participant,
3781 thread,
3782 links,
3783 remote.threadless,
3784 )
3785 .await;
3113 3786 if job == BotJob::Recording {
3114 report_organizer_result(added.as_ref().map(|status| *status).map_err(|error| Error::Signaling(error.to_string())), "recording add bot", join_failure, control, timeline);
3787 report_organizer_result(
3788 added
3789 .as_ref()
3790 .map(|status| *status)
3791 .map_err(|error| Error::Signaling(error.to_string())),
3792 "recording add bot",
3793 join_failure,
3794 control,
3795 timeline,
3796 );
3115 3797 }
3116 3798 if let Err(error) = added {
3117 3799 timeline.record("bot invitation failed", error.to_string());
@@ -3120,21 +3802,40 @@ async fn run_bot_steps(
3120 3802 }
3121 3803 }
3122 3804 CaptionStep::Start => {
3123 let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone()) else { return };
3805 let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone()) else {
3806 return;
3807 };
3124 3808 match job {
3125 3809 BotJob::Captions => {
3126 if let Err(error) = remote.signaling.caption_command(&url, BotAction::Start, &remote.participant).await {
3810 if let Err(error) = remote
3811 .signaling
3812 .caption_command(&url, BotAction::Start, &remote.participant)
3813 .await
3814 {
3127 3815 timeline.record("caption start failed", error.to_string());
3128 3816 return fail(flow, start_failure);
3129 3817 }
3130 if let Err(error) = remote.signaling.set_caption_preference(&remote.conversation, &remote.participant, true).await {
3818 if let Err(error) = remote
3819 .signaling
3820 .set_caption_preference(&remote.conversation, &remote.participant, true)
3821 .await
3822 {
3131 3823 timeline.record("caption preference failed", error.to_string());
3132 3824 }
3133 3825 }
3134 3826 BotJob::Recording => {
3135 let started = remote.signaling.recording_command(&url, plan.start(), &remote.participant, &plan.title).await;
3827 let started = remote
3828 .signaling
3829 .recording_command(&url, plan.start(), &remote.participant, &plan.title)
3830 .await;
3136 3831 let failed = started.is_err();
3137 report_organizer_result(started, "recording start", start_failure, control, timeline);
3832 report_organizer_result(
3833 started,
3834 "recording start",
3835 start_failure,
3836 control,
3837 timeline,
3838 );
3138 3839 if failed {
3139 3840 return fail(flow, start_failure);
3140 3841 }
@@ -3142,13 +3843,27 @@ async fn run_bot_steps(
3142 3843 }
3143 3844 }
3144 3845 CaptionStep::Stop => {
3145 let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone()) else { continue };
3846 let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone()) else {
3847 continue;
3848 };
3146 3849 match job {
3147 3850 BotJob::Captions => {
3148 if let Err(error) = remote.signaling.caption_command(&url, BotAction::Stop, &remote.participant).await {
3851 if let Err(error) = remote
3852 .signaling
3853 .caption_command(&url, BotAction::Stop, &remote.participant)
3854 .await
3855 {
3149 3856 timeline.record("caption stop failed", error.to_string());
3150 3857 }
3151 if let Err(error) = remote.signaling.set_caption_preference(&remote.conversation, &remote.participant, false).await {
3858 if let Err(error) = remote
3859 .signaling
3860 .set_caption_preference(
3861 &remote.conversation,
3862 &remote.participant,
3863 false,
3864 )
3865 .await
3866 {
3152 3867 timeline.record("caption preference failed", error.to_string());
3153 3868 }
3154 3869 }
@@ -3157,18 +3872,29 @@ async fn run_bot_steps(
3157 3872 let updates = control.updates();
3158 3873 let (command, title) = (plan.stop(), plan.title.clone());
3159 3874 tokio::spawn(async move {
3160 let mut stopped = remote.signaling.recording_command(&url, command, &remote.participant, &title).await;
3875 let mut stopped = remote
3876 .signaling
3877 .recording_command(&url, command, &remote.participant, &title)
3878 .await;
3161 3879 for _ in 0..RECORDING_STOP_RETRIES {
3162 3880 if !stopped.as_ref().is_err_and(recorder_busy) {
3163 3881 break;
3164 3882 }
3165 3883 tokio::time::sleep(RECORDING_STOP_RETRY_WAIT).await;
3166 stopped = remote.signaling.recording_command(&url, command, &remote.participant, &title).await;
3884 stopped = remote
3885 .signaling
3886 .recording_command(&url, command, &remote.participant, &title)
3887 .await;
3167 3888 }
3168 3889 if stopped.is_err() {
3169 let _ = updates.send(CallUpdate::Notice("The recording could not be stopped".into()));
3890 let _ = updates.send(CallUpdate::Notice(
3891 "The recording could not be stopped".into(),
3892 ));
3170 3893 }
3171 let _ = updates.send(CallUpdate::Organizer { action: "recording stop".into(), outcome: stopped.map_err(|error| error.to_string()) });
3894 let _ = updates.send(CallUpdate::Organizer {
3895 action: "recording stop".into(),
3896 outcome: stopped.map_err(|error| error.to_string()),
3897 });
3172 3898 });
3173 3899 }
3174 3900 }
@@ -3188,7 +3914,12 @@ fn send_receive_change(control: &CallControl, change: ReceiveChange) {
3188 3914 }
3189 3915 }
3190 3916
3191 fn record_audio_devices(timeline: &Timeline, lists: &devices::DeviceLists, input: Option<&AppliedDevice>, output: Option<&AppliedDevice>) {
3917 fn record_audio_devices(
3918 timeline: &Timeline,
3919 lists: &devices::DeviceLists,
3920 input: Option<&AppliedDevice>,
3921 output: Option<&AppliedDevice>,
3922 ) {
3192 3923 let name = |devices: &[AudioDevice], applied: Option<&AppliedDevice>| {
3193 3924 applied
3194 3925 .and_then(|applied| devices.iter().find(|device| device.index == applied.index))
@@ -3197,7 +3928,11 @@ fn record_audio_devices(timeline: &Timeline, lists: &devices::DeviceLists, input
3197 3928 };
3198 3929 timeline.record(
3199 3930 "audio devices",
3200 format!("input={} output={}", name(&lists.inputs, input), name(&lists.outputs, output)),
3931 format!(
3932 "input={} output={}",
3933 name(&lists.inputs, input),
3934 name(&lists.outputs, output)
3935 ),
3201 3936 );
3202 3937 }
3203 3938
@@ -3211,19 +3946,31 @@ fn follow_device_change(
3211 3946 control: &CallControl,
3212 3947 ) -> bool {
3213 3948 let system_default = devices::system_default_id(flow);
3214 let (index, fell_back) = match devices::reselect(applied.as_ref(), current, choice, system_default.as_deref()) {
3215 Reselect::Keep => return false,
3216 Reselect::Select(index) => (index, false),
3217 Reselect::FallBack(index) => (index, true),
3218 };
3949 let (index, fell_back) =
3950 match devices::reselect(applied.as_ref(), current, choice, system_default.as_deref()) {
3951 Reselect::Keep => return false,
3952 Reselect::Select(index) => (index, false),
3953 Reselect::FallBack(index) => (index, true),
3954 };
3219 3955 let selected = select(index);
3220 timeline.record("device change", format!("{flow:?} {choice:?} -> index {index} fallback={fell_back} applied={selected}"));
3956 timeline.record(
3957 "device change",
3958 format!("{flow:?} {choice:?} -> index {index} fallback={fell_back} applied={selected}"),
3959 );
3221 3960 if selected {
3222 *applied = current.iter().find(|device| device.index == index).map(|device| AppliedDevice { index, key: device.key() });
3961 *applied = current
3962 .iter()
3963 .find(|device| device.index == index)
3964 .map(|device| AppliedDevice {
3965 index,
3966 key: device.key(),
3967 });
3223 3968 }
3224 3969 if fell_back {
3225 3970 let fallback = current.iter().find(|device| device.index == index);
3226 control.send(CallUpdate::Notice(devices::disconnect_notice(previous, choice, fallback)));
3971 control.send(CallUpdate::Notice(devices::disconnect_notice(
3972 previous, choice, fallback,
3973 )));
3227 3974 }
3228 3975 selected
3229 3976 }
@@ -3250,16 +3997,27 @@ fn apply_mute(
3250 3997 tokio::spawn(async move {
3251 3998 let _ = remote
3252 3999 .signaling
3253 .update_endpoint_state(&remote.conversation, &remote.participant, effect.endpoint_is_muted)
4000 .update_endpoint_state(
4001 &remote.conversation,
4002 &remote.participant,
4003 effect.endpoint_is_muted,
4004 )
3254 4005 .await;
3255 4006 });
3256 4007 effect.muted
3257 4008 }
3258 4009
3259 fn silence_for_hold(on_hold: bool, muted: bool, audio: Option<&AudioSetup>, software_audio: Option<&SoftwareAudio>) {
4010 fn silence_for_hold(
4011 on_hold: bool,
4012 muted: bool,
4013 audio: Option<&AudioSetup>,
4014 software_audio: Option<&SoftwareAudio>,
4015 ) {
3260 4016 let silent = on_hold || muted;
3261 4017 if let Some(audio) = audio {
3262 audio.track.set_enabled(MuteEffect::for_muted(silent).track_enabled);
4018 audio
4019 .track
4020 .set_enabled(MuteEffect::for_muted(silent).track_enabled);
3263 4021 }
3264 4022 if let Some(software_audio) = software_audio {
3265 4023 software_audio.set_microphone_muted(silent);
@@ -3277,7 +4035,10 @@ fn swap_audio_track(peer: &PeerConnection, track: &RtcAudioTrack) -> Result<()>
3277 4035 .map_err(|error| Error::Webrtc(error.to_string()))
3278 4036 }
3279 4037
3280 fn outgoing_track<'a>(software_audio: Option<&'a SoftwareAudio>, device_track: &'a RtcAudioTrack) -> &'a RtcAudioTrack {
4038 fn outgoing_track<'a>(
4039 software_audio: Option<&'a SoftwareAudio>,
4040 device_track: &'a RtcAudioTrack,
4041 ) -> &'a RtcAudioTrack {
3281 4042 pick_track(software_audio.map(|audio| &audio.track), device_track)
3282 4043 }
3283 4044
@@ -3292,12 +4053,22 @@ fn software_wanted(
3292 4053 audio: Option<&AudioSetup>,
3293 4054 ) -> Option<SoftwareAudioPlan> {
3294 4055 let sharing_sound = share_sound_wanted && local_video.sharing();
3295 SoftwareAudioPlan::wanted(mic_settings, sharing_sound, audio.is_some_and(AudioSetup::uses_devices))
4056 SoftwareAudioPlan::wanted(
4057 mic_settings,
4058 sharing_sound,
4059 audio.is_some_and(AudioSetup::uses_devices),
4060 )
3296 4061 }
3297 4062
3298 fn restore_device_track(factory: &PeerConnectionFactory, input: &DeviceChoice, peer: &PeerConnection, device_track: &RtcAudioTrack, timeline: &Timeline) {
4063 fn restore_device_track(
4064 factory: &PeerConnectionFactory,
4065 input: &DeviceChoice,
4066 peer: &PeerConnection,
4067 device_track: &RtcAudioTrack,
4068 timeline: &Timeline,
4069 ) {
3299 4070 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
3300 if cfg!(windows) && !factory.adm_recording_enabled() {
4071 if !factory.adm_recording_enabled() {
3301 4072 factory.set_adm_recording_enabled(true);
3302 4073 devices::select_input(factory, input);
3303 4074 }
@@ -3325,6 +4096,9 @@ fn sync_software_audio(
3325 4096 if running == wanted && !restart {
3326 4097 return;
3327 4098 }
4099 if running.is_some() {
4100 timeline.record("software audio", "stopping");
4101 }
3328 4102 *software_audio = None;
3329 4103 let was_sharing_sound = running.is_some_and(|plan| plan.computer_sound);
3330 4104 let Some(plan) = wanted else {
@@ -3332,15 +4106,26 @@ fn sync_software_audio(
3332 4106 control.send(CallUpdate::ShareSound(false));
3333 4107 return;
3334 4108 };
3335 let started = SoftwareAudio::start(factory, options.audio, options.tone_hz, input, plan, muted, remote_audio)
3336 .and_then(|audio| swap_audio_track(peer, &audio.track).map(|()| audio));
4109 let started = SoftwareAudio::start(
4110 factory,
4111 options.audio,
4112 options.tone_hz,
4113 input,
4114 plan,
4115 muted,
4116 remote_audio,
4117 )
4118 .and_then(|audio| swap_audio_track(peer, &audio.track).map(|()| audio));
3337 4119 match started {
3338 4120 Ok(audio) => {
3339 timeline.record("software audio", format!("{:?}, computer sound {:?}", plan.processing, audio.loopback));
4121 timeline.record(
4122 "software audio",
4123 format!("{:?}, computer sound {:?}", plan.processing, audio.loopback),
4124 );
3340 4125 if let Some(source) = &audio.microphone_source {
3341 4126 timeline.record("mic capture", source.clone());
3342 4127 }
3343 if cfg!(windows) && audio.microphone_source.is_some() {
4128 if audio.microphone_source.is_some() {
3344 4129 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
3345 4130 factory.set_adm_recording_enabled(false);
3346 4131 }
@@ -3366,7 +4151,13 @@ fn sync_software_audio(
3366 4151 }
3367 4152 }
3368 4153
3369 async fn tear_down(mut live: Live, inner: &Inner, timeline: &Timeline, report: &mut CallReport, cancelled: bool) {
4154 async fn tear_down(
4155 mut live: Live,
4156 inner: &Inner,
4157 timeline: &Timeline,
4158 report: &mut CallReport,
4159 cancelled: bool,
4160 ) {
3370 4161 for peer in &live.peers {
3371 4162 peer.close();
3372 4163 }
@@ -3377,8 +4168,16 @@ async fn tear_down(mut live: Live, inner: &Inner, timeline: &Timeline, report: &
3377 4168 if !live.skip_leave
3378 4169 && let Some(remote) = &live.remote
3379 4170 {
3380 let reason = if cancelled { LeaveReason::Cancel } else { LeaveReason::Hangup };
3381 match remote.signaling.leave(&remote.conversation, &remote.participant, reason).await {
4171 let reason = if cancelled {
4172 LeaveReason::Cancel
4173 } else {
4174 LeaveReason::Hangup
4175 };
4176 match remote
4177 .signaling
4178 .leave(&remote.conversation, &remote.participant, reason)
4179 .await
4180 {
3382 4181 Ok(()) => report.left_cleanly = true,
3383 4182 Err(error) => timeline.record("leave failed", error.to_string()),
3384 4183 }
@@ -3422,31 +4221,53 @@ fn handle_callback(callback: &TrouterCallback, timeline: &Timeline) -> Result<Ca
3422 4221 let body = decode_body(callback)?;
3423 4222 let (_, event) = classify(&callback.path, body)?;
3424 4223 let detail = match &event {
3425 CallEvent::Acceptance(acceptance) => format!("answer sdp {} bytes, fromMixer={}", acceptance.sdp.len(), acceptance.from_mixer),
3426 CallEvent::End(end) => format!("code={} subCode={} phrase={}", end.code, end.sub_code, end.phrase),
4224 CallEvent::Acceptance(acceptance) => format!(
4225 "answer sdp {} bytes, fromMixer={}",
4226 acceptance.sdp.len(),
4227 acceptance.from_mixer
4228 ),
4229 CallEvent::End(end) => format!(
4230 "code={} subCode={} phrase={}",
4231 end.code, end.sub_code, end.phrase
4232 ),
3427 4233 CallEvent::Progress(status) => format!("{status:?}"),
3428 CallEvent::ConversationEnd(body) | CallEvent::Rejection(body) | CallEvent::AddParticipantFailure(body) | CallEvent::RetargetCompletion(body) => outcome_summary(body),
3429 CallEvent::ControlVideoStreaming(body) => parse_request(body).map_or_else(|| "body not understood".to_owned(), |request| request.shape),
4234 CallEvent::ConversationEnd(body)
4235 | CallEvent::Rejection(body)
4236 | CallEvent::AddParticipantFailure(body)
4237 | CallEvent::RetargetCompletion(body) => outcome_summary(body),
4238 CallEvent::ControlVideoStreaming(body) => parse_request(body)
4239 .map_or_else(|| "body not understood".to_owned(), |request| request.shape),
3430 4240 _ => String::new(),
3431 4241 };
3432 4242 timeline.record(format!("Trouter {}", event.name()), detail);
3433 4243 match &event {
3434 4244 CallEvent::Acceptance(acceptance) => timeline.record_sdp("remote answer", &acceptance.sdp),
3435 4245 CallEvent::MediaAnswer(answer) => timeline.record_sdp("remote answer", &answer.sdp),
3436 CallEvent::MediaRenegotiation(renegotiation) => timeline.record_sdp("remote offer", &renegotiation.sdp),
4246 CallEvent::MediaRenegotiation(renegotiation) => {
4247 timeline.record_sdp("remote offer", &renegotiation.sdp)
4248 }
3437 4249 _ => {}
3438 4250 }
3439 4251 Ok(event)
3440 4252 }
3441 4253
3442
3443 async fn apply_answer(peer: &PeerConnection, teams_answer: &str, signaled: &SignaledOffer, browser_offer: &str) -> Result<()> {
4254 async fn apply_answer(
4255 peer: &PeerConnection,
4256 teams_answer: &str,
4257 signaled: &SignaledOffer,
4258 browser_offer: &str,
4259 ) -> Result<()> {
3444 4260 let answer = to_browser_answer(teams_answer, signaled, browser_offer)?;
3445 4261 set_browser_answer(peer, &answer).await
3446 4262 }
3447 4263
3448 4264 /// libwebrtc does not restart a send stream that an inactive answer stopped, so a hold keeps the streams and only mutes.
3449 async fn apply_hold_answer(peer: &PeerConnection, teams_answer: &str, signaled: &SignaledOffer, browser_offer: &str) -> Result<()> {
4265 async fn apply_hold_answer(
4266 peer: &PeerConnection,
4267 teams_answer: &str,
4268 signaled: &SignaledOffer,
4269 browser_offer: &str,
4270 ) -> Result<()> {
3450 4271 let answer = to_browser_answer(teams_answer, signaled, browser_offer)?;
3451 4272 set_browser_answer(peer, &keep_media_running(&answer, browser_offer)).await
3452 4273 }
@@ -3471,7 +4292,10 @@ fn dump_sdp(options: &CallOptions, name: &str, sdp: &str) {
3471 4292 return format!("{prefix}<masked>");
3472 4293 }
3473 4294 }
3474 line.split(' ').map(mask_address).collect::<Vec<_>>().join(" ")
4295 line.split(' ')
4296 .map(mask_address)
4297 .collect::<Vec<_>>()
4298 .join(" ")
3475 4299 })
3476 4300 .collect();
3477 4301 let _ = std::fs::create_dir_all(directory);
@@ -3482,8 +4306,16 @@ fn dump_timeline(options: &CallOptions, timeline: &Timeline, failure: Option<&Er
3482 4306 let Some(directory) = &options.sdp_dump_dir else {
3483 4307 return;
3484 4308 };
3485 let mut lines: Vec<String> =
3486 timeline.entries().iter().map(|entry| format!("{:>6} ms {} {}", entry.elapsed_ms, entry.label, entry.detail)).collect();
4309 let mut lines: Vec<String> = timeline
4310 .entries()
4311 .iter()
4312 .map(|entry| {
4313 format!(
4314 "{:>6} ms {} {}",
4315 entry.elapsed_ms, entry.label, entry.detail
4316 )
4317 })
4318 .collect();
3487 4319 lines.push(match failure {
3488 4320 Some(error) => format!("failed: {error}"),
3489 4321 None => "ended without error".to_owned(),
@@ -3493,9 +4325,13 @@ fn dump_timeline(options: &CallOptions, timeline: &Timeline, failure: Option<&Er
3493 4325 }
3494 4326
3495 4327 fn mask_address(token: &str) -> String {
3496 let dotted_quad = token.split('.').count() == 4 && token.split('.').all(|part| part.parse::<u8>().is_ok());
3497 let colon_address = token.matches(':').count() >= 2 && !token.starts_with("a=") && !token.starts_with("urn:");
3498 if (dotted_quad && token != "10.10.10.10" && token != "0.0.0.0" && token != "127.0.0.1") || colon_address {
4328 let dotted_quad =
4329 token.split('.').count() == 4 && token.split('.').all(|part| part.parse::<u8>().is_ok());
4330 let colon_address =
4331 token.matches(':').count() >= 2 && !token.starts_with("a=") && !token.starts_with("urn:");
4332 if (dotted_quad && token != "10.10.10.10" && token != "0.0.0.0" && token != "127.0.0.1")
4333 || colon_address
4334 {
3499 4335 "<addr>".to_owned()
3500 4336 } else {
3501 4337 token.to_owned()
@@ -3516,7 +4352,11 @@ async fn record_track(track: RtcAudioTrack, recording: Arc<Mutex<Recording>>, to
3516 4352 }
3517 4353 }
3518 4354
3519 async fn poll_broker(signaling: Arc<Signaling>, conversation: Conversation, running: Arc<AtomicBool>) {
4355 async fn poll_broker(
4356 signaling: Arc<Signaling>,
4357 conversation: Conversation,
4358 running: Arc<AtomicBool>,
4359 ) {
3520 4360 let Ok(first) = conversation.link("subscribe") else {
3521 4361 return;
3522 4362 };
@@ -3564,25 +4404,17 @@ struct ShareReceive {
3564 4404 pli_count: u32,
3565 4405 fir_count: u32,
3566 4406 freeze_count: u32,
3567 qp_sum: u64,
3568 bytes_received: u64,
3569 4407 }
3570 4408
3571 4409 impl ShareReceive {
3572 fn average_qp(&self) -> u64 {
3573 self.qp_sum.checked_div(u64::from(self.frames_decoded)).unwrap_or(0)
3574 }
3575
3576 4410 fn summary(&self) -> String {
3577 4411 format!(
3578 " share in decoded={} keyframes={} {}x{} fps={:.0} qp={} bytes={} pli={} fir={} freezes={}",
4412 " share in decoded={} keyframes={} {}x{} fps={:.0} pli={} fir={} freezes={}",
3579 4413 self.frames_decoded,
3580 4414 self.key_frames_decoded,
3581 4415 self.width,
3582 4416 self.height,
3583 4417 self.frames_per_second,
3584 self.average_qp(),
3585 self.bytes_received,
3586 4418 self.pli_count,
3587 4419 self.fir_count,
3588 4420 self.freeze_count
@@ -3606,7 +4438,10 @@ async fn collect_stats(peer: &PeerConnection, share_mids: &[String]) -> StatsSna
3606 4438 }
3607 4439 RtcStats::MediaSource(source) if source.source.kind == "audio" => {
3608 4440 snapshot.local_level = snapshot.local_level.max(source.audio.audio_level);
3609 snapshot.source_levels.push(format!("{}={:.3}", source.source.track_identifier, source.audio.audio_level));
4441 snapshot.source_levels.push(format!(
4442 "{}={:.3}",
4443 source.source.track_identifier, source.audio.audio_level
4444 ));
3610 4445 snapshot.echo_return_loss_enhancement = source.audio.echo_return_loss_enhancement;
3611 4446 }
3612 4447 RtcStats::OutboundRtp(outbound) if outbound.stream.kind == "audio" => {
@@ -3626,24 +4461,32 @@ async fn collect_stats(peer: &PeerConnection, share_mids: &[String]) -> StatsSna
3626 4461 pli_count: inbound.inbound.pli_count,
3627 4462 fir_count: inbound.inbound.fir_count,
3628 4463 freeze_count: inbound.inbound.freeze_count,
3629 qp_sum: inbound.inbound.qp_sum,
3630 bytes_received: inbound.inbound.bytes_received,
3631 4464 });
3632 4465 }
3633 4466 snapshot.video.inbound_frames_decoded += u64::from(inbound.inbound.frames_decoded);
3634 snapshot.video.inbound_width = snapshot.video.inbound_width.max(inbound.inbound.frame_width);
3635 snapshot.video.inbound_height = snapshot.video.inbound_height.max(inbound.inbound.frame_height);
4467 snapshot.video.inbound_width = snapshot
4468 .video
4469 .inbound_width
4470 .max(inbound.inbound.frame_width);
4471 snapshot.video.inbound_height = snapshot
4472 .video
4473 .inbound_height
4474 .max(inbound.inbound.frame_height);
3636 4475 }
3637 4476 RtcStats::RemoteInboundRtp(remote) if remote.stream.kind == "video" => {
3638 4477 snapshot.video.remote_reports += remote.remote_inbound.round_trip_time_measurements;
3639 snapshot.video.remote_round_trip_ms = snapshot.video.remote_round_trip_ms.max(remote.remote_inbound.round_trip_time * 1000.0);
4478 snapshot.video.remote_round_trip_ms = snapshot
4479 .video
4480 .remote_round_trip_ms
4481 .max(remote.remote_inbound.round_trip_time * 1000.0);
3640 4482 }
3641 4483 RtcStats::OutboundRtp(outbound) if outbound.stream.kind == "video" => {
3642 4484 snapshot.video.outbound_packets += outbound.sent.packets_sent;
3643 4485 if share_mids.contains(&outbound.outbound.mid) {
3644 4486 snapshot.share_outbound_packets += outbound.sent.packets_sent;
3645 4487 }
3646 snapshot.video.outbound_frames_encoded += u64::from(outbound.outbound.frames_encoded);
4488 snapshot.video.outbound_frames_encoded +=
4489 u64::from(outbound.outbound.frames_encoded);
3647 4490 snapshot.video_senders.push(format!(
3648 4491 "mid {} packets={} key={} pli={} fir={} nack={} target={:.0}kbps limit={:?} active={}",
3649 4492 outbound.outbound.mid,
@@ -3656,8 +4499,14 @@ async fn collect_stats(peer: &PeerConnection, share_mids: &[String]) -> StatsSna
3656 4499 outbound.outbound.quality_limitation_reason,
3657 4500 outbound.outbound.active
3658 4501 ));
3659 snapshot.video.outbound_width = snapshot.video.outbound_width.max(outbound.outbound.frame_width);
3660 snapshot.video.outbound_height = snapshot.video.outbound_height.max(outbound.outbound.frame_height);
4502 snapshot.video.outbound_width = snapshot
4503 .video
4504 .outbound_width
4505 .max(outbound.outbound.frame_width);
4506 snapshot.video.outbound_height = snapshot
4507 .video
4508 .outbound_height
4509 .max(outbound.outbound.frame_height);
3661 4510 }
3662 4511 RtcStats::Transport(transport) => {
3663 4512 snapshot.dtls_state = format!("{:?}", transport.transport.dtls_state);
@@ -3681,13 +4530,23 @@ async fn collect_stats(peer: &PeerConnection, share_mids: &[String]) -> StatsSna
3681 4530 stats
3682 4531 .iter()
3683 4532 .find_map(|entry| match entry {
3684 RtcStats::LocalCandidate(local) if local.rtc.id == candidate_id => Some(&local.local_candidate),
3685 RtcStats::RemoteCandidate(remote) if remote.rtc.id == candidate_id => Some(&remote.remote_candidate),
4533 RtcStats::LocalCandidate(local) if local.rtc.id == candidate_id => {
4534 Some(&local.local_candidate)
4535 }
4536 RtcStats::RemoteCandidate(remote) if remote.rtc.id == candidate_id => {
4537 Some(&remote.remote_candidate)
4538 }
3686 4539 _ => None,
3687 4540 })
3688 4541 .map(|candidate| {
3689 let kind = candidate.candidate_type.map(|kind| format!("{kind:?}")).unwrap_or_default();
3690 let relay = candidate.relay_protocol.map(|relay| format!(" via {relay:?}")).unwrap_or_default();
4542 let kind = candidate
4543 .candidate_type
4544 .map(|kind| format!("{kind:?}"))
4545 .unwrap_or_default();
4546 let relay = candidate
4547 .relay_protocol
4548 .map(|relay| format!(" via {relay:?}"))
4549 .unwrap_or_default();
3691 4550 format!("{kind}/{}{relay}", candidate.protocol)
3692 4551 })
3693 4552 .unwrap_or_else(|| "?".into())
@@ -3704,22 +4563,24 @@ async fn collect_stats(peer: &PeerConnection, share_mids: &[String]) -> StatsSna
3704 4563
3705 4564 #[cfg(test)]
3706 4565 mod tests {
3707 #[test]
3708 fn gathering_settles_shortly_after_a_udp_relay_or_when_complete() {
3709 assert!(!gathering_settled(false, None));
3710 assert!(!gathering_settled(false, Some(Duration::from_millis(50))));
3711 assert!(gathering_settled(false, Some(RELAY_SETTLE)));
3712 assert!(gathering_settled(true, None));
3713 }
3714
3715 4566 #[tokio::test]
3716 4567 async fn a_hanging_setup_step_ends_on_cancel_or_after_the_step_timeout() {
3717 4568 let (handle, mut control) = crate::control::call_channel();
3718 4569 handle.commands.send(CallCommand::Hangup).unwrap();
3719 4570 let limit = Duration::from_millis(20);
3720 let cancelled = setup_step_within(&mut control, limit, std::future::pending::<std::result::Result<(), Error>>()).await;
4571 let cancelled = setup_step_within(
4572 &mut control,
4573 limit,
4574 std::future::pending::<std::result::Result<(), Error>>(),
4575 )
4576 .await;
3721 4577 assert!(matches!(cancelled, Err(Error::Cancelled)));
3722 let timed_out = setup_step_within(&mut control, limit, std::future::pending::<std::result::Result<(), Error>>()).await;
4578 let timed_out = setup_step_within(
4579 &mut control,
4580 limit,
4581 std::future::pending::<std::result::Result<(), Error>>(),
4582 )
4583 .await;
3723 4584 assert!(matches!(timed_out, Err(Error::Signaling(_))));
3724 4585 }
3725 4586
@@ -3734,8 +4595,12 @@ mod tests {
3734 4595
3735 4596 #[test]
3736 4597 fn only_a_conflict_answer_retries_a_recording_stop() {
3737 assert!(recorder_busy(&Error::Signaling("recording command answered HTTP 409 no answer".into())));
3738 assert!(!recorder_busy(&Error::Signaling("recording command answered HTTP 500 no answer".into())));
4598 assert!(recorder_busy(&Error::Signaling(
4599 "recording command answered HTTP 409 no answer".into()
4600 )));
4601 assert!(!recorder_busy(&Error::Signaling(
4602 "recording command answered HTTP 500 no answer".into()
4603 )));
3739 4604 assert!(!recorder_busy(&Error::Cancelled));
3740 4605 }
3741 4606
@@ -3767,14 +4632,21 @@ mod tests {
3767 4632 const BROWSER_OFFER: &str = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\na=mid:0\r\na=sendrecv\r\nm=video 9 UDP/TLS/RTP/SAVPF 102\r\na=mid:1\r\na=sendrecv\r\nm=video 9 UDP/TLS/RTP/SAVPF 102\r\na=mid:2\r\na=recvonly\r\n";
3768 4633
3769 4634 fn directions(sdp: &str) -> Vec<String> {
3770 crate::sdp::parse(sdp).unwrap().media.iter().map(|line| line.direction().unwrap_or("none").to_owned()).collect()
4635 crate::sdp::parse(sdp)
4636 .unwrap()
4637 .media
4638 .iter()
4639 .map(|line| line.direction().unwrap_or("none").to_owned())
4640 .collect()
3771 4641 }
3772 4642
3773 4643 async fn local_offer(layout: Layout) -> Result<OfferedMedia> {
3774 4644 use libwebrtc::audio_source::native::NativeAudioSource;
3775 4645 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
3776 4646 let factory = devices::shared_factory();
3777 let peer = factory.create_peer_connection(RtcConfiguration::default()).unwrap();
4647 let peer = factory
4648 .create_peer_connection(RtcConfiguration::default())
4649 .unwrap();
3778 4650 let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, 100);
3779 4651 let track = factory.create_audio_track("microphone", source);
3780 4652 let offer = create_offer(&peer, &factory, &track, layout, None).await;
@@ -3796,11 +4668,22 @@ mod tests {
3796 4668 use libwebrtc::audio_source::native::NativeAudioSource;
3797 4669 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
3798 4670 let factory = devices::shared_factory();
3799 let peer = factory.create_peer_connection(RtcConfiguration::default()).unwrap();
4671 let peer = factory
4672 .create_peer_connection(RtcConfiguration::default())
4673 .unwrap();
3800 4674 let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, 100);
3801 4675 let track = factory.create_audio_track("microphone", source);
3802 4676 let offer = include_str!("../tests/fixtures/teams_p2p_offer.sdp");
3803 let answered = answer_offer(&peer, Some(&track), offer, AnswerVideo::Receive, None, false, None).await;
4677 let answered = answer_offer(
4678 &peer,
4679 Some(&track),
4680 offer,
4681 AnswerVideo::Receive,
4682 None,
4683 false,
4684 None,
4685 )
4686 .await;
3804 4687 peer.close();
3805 4688 if let Err(error) = answered {
3806 4689 panic!("{error}");
@@ -3809,51 +4692,144 @@ mod tests {
3809 4692
3810 4693 #[test]
3811 4694 fn a_one_to_one_offer_has_audio_and_an_inactive_camera_until_the_camera_is_on() {
3812 assert_eq!(directions(&directions_for(Layout::OneToOne, false, false, false, CAMERA_MID, Some(ONE_TO_ONE_SHARE_MID), false, BROWSER_OFFER)), vec!["sendrecv", "inactive", "inactive"]);
3813 assert_eq!(directions(&directions_for(Layout::OneToOne, false, true, false, CAMERA_MID, Some(ONE_TO_ONE_SHARE_MID), false, BROWSER_OFFER)), vec!["sendrecv", "sendrecv", "inactive"]);
3814 assert_eq!(directions(&directions_for(Layout::OneToOne, false, false, true, CAMERA_MID, Some(ONE_TO_ONE_SHARE_MID), false, BROWSER_OFFER)), vec!["sendrecv", "inactive", "sendonly"]);
4695 assert_eq!(
4696 directions(&directions_for(
4697 Layout::OneToOne,
4698 false,
4699 false,
4700 false,
4701 CAMERA_MID,
4702 Some(ONE_TO_ONE_SHARE_MID),
4703 false,
4704 BROWSER_OFFER
4705 )),
4706 vec!["sendrecv", "inactive", "inactive"]
4707 );
4708 assert_eq!(
4709 directions(&directions_for(
4710 Layout::OneToOne,
4711 false,
4712 true,
4713 false,
4714 CAMERA_MID,
4715 Some(ONE_TO_ONE_SHARE_MID),
4716 false,
4717 BROWSER_OFFER
4718 )),
4719 vec!["sendrecv", "sendrecv", "inactive"]
4720 );
4721 assert_eq!(
4722 directions(&directions_for(
4723 Layout::OneToOne,
4724 false,
4725 false,
4726 true,
4727 CAMERA_MID,
4728 Some(ONE_TO_ONE_SHARE_MID),
4729 false,
4730 BROWSER_OFFER
4731 )),
4732 vec!["sendrecv", "inactive", "sendonly"]
4733 );
3815 4734 }
3816 4735
3817 4736 #[test]
3818 4737 fn a_hold_silences_every_line_and_a_conference_offer_is_left_alone() {
3819 4738 for layout in [Layout::OneToOne, Layout::Conference] {
3820 assert_eq!(directions(&directions_for(layout, true, true, false, CAMERA_MID, None, false, BROWSER_OFFER)), vec!["inactive", "inactive", "inactive"]);
4739 assert_eq!(
4740 directions(&directions_for(
4741 layout,
4742 true,
4743 true,
4744 false,
4745 CAMERA_MID,
4746 None,
4747 false,
4748 BROWSER_OFFER
4749 )),
4750 vec!["inactive", "inactive", "inactive"]
4751 );
3821 4752 }
3822 assert_eq!(directions_for(Layout::Conference, false, true, false, CAMERA_MID, None, false, BROWSER_OFFER), BROWSER_OFFER);
4753 assert_eq!(
4754 directions_for(
4755 Layout::Conference,
4756 false,
4757 true,
4758 false,
4759 CAMERA_MID,
4760 None,
4761 false,
4762 BROWSER_OFFER
4763 ),
4764 BROWSER_OFFER
4765 );
3823 4766 }
3824 4767
3825 4768 #[test]
3826 4769 fn a_hold_offer_body_is_inactive_on_every_teams_line_with_one_placeholder_candidate() {
3827 let held = directions_for(Layout::Conference, true, false, false, CAMERA_MID, None, false, BROWSER_OFFER);
4770 let held = directions_for(
4771 Layout::Conference,
4772 true,
4773 false,
4774 false,
4775 CAMERA_MID,
4776 None,
4777 false,
4778 BROWSER_OFFER,
4779 );
3828 4780 let mut numbers = || 7;
3829 let signaled = to_teams_offer(&held, &offer_plan(), &mut numbers).unwrap().sdp;
3830 assert_eq!(directions(&signaled), vec!["inactive", "inactive", "inactive"]);
4781 let signaled = to_teams_offer(&held, &offer_plan(), &mut numbers)
4782 .unwrap()
4783 .sdp;
4784 assert_eq!(
4785 directions(&signaled),
4786 vec!["inactive", "inactive", "inactive"]
4787 );
3831 4788 assert_eq!(signaled.matches("a=candidate:").count(), 1);
3832 4789 }
3833 4790
3834 4791 #[test]
3835 4792 fn a_move_into_the_meeting_you_are_already_in_is_ignored() {
3836 let target = |thread: &str| MeetingTarget { thread_id: thread.into(), tenant_id: "t".into(), organizer_id: "o".into(), meeting_data: None };
3837 assert!(is_own_meeting(Some(&target("19:meeting_a@thread.v2")), &target("19:meeting_a@thread.v2")));
3838 assert!(!is_own_meeting(Some(&target("19:meeting_a@thread.v2")), &target("19:meeting_b@thread.v2")));
4793 let target = |thread: &str| MeetingTarget {
4794 thread_id: thread.into(),
4795 tenant_id: "t".into(),
4796 organizer_id: "o".into(),
4797 meeting_data: None,
4798 };
4799 assert!(is_own_meeting(
4800 Some(&target("19:meeting_a@thread.v2")),
4801 &target("19:meeting_a@thread.v2")
4802 ));
4803 assert!(!is_own_meeting(
4804 Some(&target("19:meeting_a@thread.v2")),
4805 &target("19:meeting_b@thread.v2")
4806 ));
3839 4807 assert!(!is_own_meeting(None, &target("19:meeting_a@thread.v2")));
3840 4808 }
3841 4809
3842 4810 #[test]
3843 4811 fn a_video_call_names_the_video_modality_only_when_the_camera_sends() {
3844 4812 assert_eq!(accepted_modalities(false), vec!["Audio".to_owned()]);
3845 assert_eq!(accepted_modalities(true), vec!["Audio".to_owned(), "Video".to_owned()]);
4813 assert_eq!(
4814 accepted_modalities(true),
4815 vec!["Audio".to_owned(), "Video".to_owned()]
4816 );
3846 4817 }
3847 4818
3848 4819 #[test]
3849 4820 fn specs_map_to_invitation_targets() {
3850 4821 assert_eq!(CallSpec::Echo.target(), InviteTarget::Echo);
3851 4822 let people = CallSpec::People {
3852 callees: vec![Callee { mri: "8:orgid:b".into(), display_name: "Bea".into() }],
4823 callees: vec![Callee {
4824 mri: "8:orgid:b".into(),
4825 display_name: "Bea".into(),
4826 }],
3853 4827 thread_id: "19:t@thread.v2".into(),
3854 4828 };
3855 4829 assert!(people.is_people() && !people.is_meeting());
3856 assert!(matches!(people.target(), InviteTarget::People { thread_id, .. } if thread_id == "19:t@thread.v2"));
4830 assert!(
4831 matches!(people.target(), InviteTarget::People { thread_id, .. } if thread_id == "19:t@thread.v2")
4832 );
3857 4833 let meeting = CallSpec::Meeting(MeetingTarget {
3858 4834 thread_id: "19:meeting@thread.v2".into(),
3859 4835 tenant_id: "t".into(),
@@ -1,7 +1,7 @@
1use std::collections::BTreeMap;
1use std::collections::BTreeMap;
2use std::path::PathBuf;
2use std::path::PathBuf;
3use std::sync::Arc;
3use std::sync::Arc;
4use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
4use std::sync::atomic::{AtomicBool, Ordering};
5use std::time::Duration;
5use std::time::Duration;
6
6
7use chatsvc::TrouterCallback;
7use chatsvc::TrouterCallback;
@@ -24,51 +24,67 @@ use crate::background::{BackgroundChoice, BackgroundPicture};
24use crate::breakout::{self, RoomWatcher};
24use crate::breakout::{self, RoomWatcher};
25use crate::callee_gate::{CalleeGate, EchoWatch, roster_has_callee};
25use crate::callee_gate::{CalleeGate, EchoWatch, roster_has_callee};
26use crate::camera::{CameraDevice, list_cameras};
26use crate::camera::{CameraDevice, list_cameras};
27use crate::candidates::{SdpKind, is_udp_relay, negotiated_setup, with_candidates};
27use crate::captions::{
28use crate::captions::{
28 BotAction, CAPTIONS_DATA_ID, CaptionEntry, CaptionFlow, CaptionState, CaptionStep,
29 BotAction, CAPTIONS_DATA_ID, CaptionEntry, CaptionFlow, CaptionState, CaptionStep,
29 parse_caption_message,
30 parse_caption_message,
30};
31};
31use crate::control::{CallCommand, CallControl, CallUpdate, Progress};
32use crate::control::{CallCommand, CallControl, CallUpdate, Progress};
32use crate::diagnostics::{CallDiagnostics, StatsSample};
33use crate::data_channel::Depacketizer;
33use crate::data_channel::Depacketizer;
34use crate::device_watch::{self, Debounce};
34use crate::device_watch::{self, Debounce};
35use crate::devices::{self, AppliedDevice, AudioDevice, DeviceChoice, Flow, Reselect};
35use crate::devices::{self, AppliedDevice, AudioDevice, DeviceChoice, Flow, Reselect};
36use crate::diagnostics::{CallDiagnostics, StatsSample};
36use crate::end::EndKind;
37use crate::end::EndKind;
37use crate::engine::{CallEngine, EngineConfig, Inner};
38use crate::engine::{CallEngine, EngineConfig, Inner};
38use crate::error::{Error, Result};
39use crate::error::{Error, Result};
39use crate::health::{CallHealth, HealthCounters, HealthSampler, QualityTracker, TransportDetails, health_from_stats};
40use crate::health::{
40use crate::hold::{HoldState, INACTIVE, MediaLine, accepted_modalities, direction_of, offer_modalities, is_hold, keep_media_running, offer_sends_video, rewrite_directions, stop_sending_on};
41 CallHealth, HealthCounters, HealthSampler, QualityTracker, TransportDetails, health_from_stats,
42};
43use crate::hold::{
44 HoldState, INACTIVE, MediaLine, accepted_modalities, direction_of, is_hold, keep_media_running,
45 offer_modalities, offer_sends_video, rewrite_directions, stop_sending_on,
46};
47use crate::meeting_options::{self, OptionWrite};
41use crate::mic_processing::MicSettings;
48use crate::mic_processing::MicSettings;
42use crate::mute::{MuteCommand, MuteEffect};
49use crate::mute::{MuteCommand, MuteEffect};
43use crate::push::CallNotification;
44use crate::relay::{DEFAULT_RELAY_HOST, RelayGrant};
45use crate::renegotiation::{MediaAction, MediaNegotiator, MediaPath, RejectedOffer};
46use crate::candidates::{SdpKind, is_udp_relay, negotiated_setup, with_candidates};
47use crate::outcome::{embedded_end, failed_participant_count, outcome_summary};
48use crate::organizer::{MeetingCapability, Modality, StateStep, Target, modality_steps};
50use crate::organizer::{MeetingCapability, Modality, StateStep, Target, modality_steps};
49use crate::meeting_options::{self, OptionWrite};
51use crate::outcome::{embedded_end, failed_participant_count, outcome_summary};
52use crate::push::CallNotification;
50use crate::recording::{Consent, RecordingPlan, RecordingStatus};
53use crate::recording::{Consent, RecordingPlan, RecordingStatus};
54use crate::relay::{DEFAULT_RELAY_HOST, RelayGrant, fetch_relay_grant};
55use crate::renegotiation::{MediaAction, MediaNegotiator, MediaPath, RejectedOffer};
51use crate::roster::{Roster, direct_roster};
56use crate::roster::{Roster, direct_roster};
52use crate::sdp::{LineRole, OfferPlan, RemoteOffer, SignaledOffer, from_teams_offer, stream_lines, to_browser_answer, to_teams_answer, to_teams_offer};
57use crate::screen::{
58 ShareKind, SharePicker, ShareSource, current_share_picker, list_share_sources,
59 share_sources_for_menu, share_thumbnail,
60};
61use crate::sdp::{
62 LineRole, OfferPlan, RemoteOffer, SignaledOffer, from_teams_offer, stream_lines,
63 to_browser_answer, to_teams_answer, to_teams_offer,
64};
65use crate::send_control::{RequestFilter, parse_request};
53use crate::signaling::{
66use crate::signaling::{
54 Answer, Attached, Callee, one_to_one_thread, Conversation, Invitation, InviteTarget, LeaveReason, MeetingTarget, NegotiationFailure, Participant, Signaling,
67 Answer, Attached, Callee, Conversation, Invitation, InviteTarget, LeaveReason, MeetingTarget,
55 TenantRouting, chat_thread_id, find_echo_bot_thread, escalation_answer_body, renegotiation_body,
68 NegotiationFailure, Participant, Signaling, TenantRouting, chat_thread_id,
69 escalation_answer_body, find_echo_bot_thread, one_to_one_thread, renegotiation_body,
56};
70};
57use crate::software_audio::{SoftwareAudio, SoftwareAudioPlan};
71use crate::software_audio::{SoftwareAudio, SoftwareAudioPlan};
58use crate::state::{CallSignal, CallState};
72use crate::state::{CallSignal, CallState};
59use crate::timeline::{Timeline, TimelineEntry};
73use crate::timeline::{Timeline, TimelineEntry};
60use crate::transfer::{Replacement, TransferEvent, TransferTarget};
74use crate::transfer::{Replacement, TransferEvent, TransferTarget};
75use crate::trouter_events::{
76 CallEnd, CallEvent, CallbackLinks, ProgressStatus, callback_tag, classify, decode_body,
77};
61use crate::video_frame::{VideoKey, VideoPicture};
78use crate::video_frame::{VideoKey, VideoPicture};
62use crate::video_layout::{
79use crate::video_layout::{
63 CAMERA_MID, MediaDescription, ONE_TO_ONE_SHARE_MID, SCREEN_STREAM, SendCapabilityReporter, SlotTable, VideoLines, VideoRouter, add_one_to_one_lines, add_share_line, add_video_lines, offer_plan, one_to_one_plan,
80 CAMERA_MID, MediaDescription, ONE_TO_ONE_SHARE_MID, SCREEN_STREAM, SendCapabilityReporter,
81 SlotTable, VideoLines, VideoRouter, add_one_to_one_lines, add_share_line, add_video_lines,
82 offer_plan, one_to_one_plan,
64};
83};
65use crate::send_control::{RequestFilter, parse_request};
84use crate::video_receive::{
66use crate::video_send::{LocalVideo, SendSource, VideoMode};
85 ReceiveChange, SourceRequester, VideoCounters, VideoReceive, spawn_video_pump,
67use crate::screen::{ShareKind, ShareSource, list_share_sources, share_thumbnail};
68use crate::video_receive::{ReceiveChange, SourceRequester, VideoCounters, VideoReceive, spawn_video_pump};
69use crate::trouter_events::{
70 CallEnd, CallEvent, CallbackLinks, ProgressStatus, callback_tag, classify, decode_body,
71};
86};
87use crate::video_send::{LocalVideo, SendSource, VideoMode};
72use crate::whiteboard;
88use crate::whiteboard;
73
89
74const END_CALLBACK_WAIT: Duration = Duration::from_secs(4);
90const END_CALLBACK_WAIT: Duration = Duration::from_secs(4);
@@ -92,8 +108,10 @@ const HEALTH_EVERY_TICKS: u32 = TICKS_PER_SECOND * 2;
92const BOT_PREFIX: &str = "28:";
108const BOT_PREFIX: &str = "28:";
93const RECORDING_START_LIMIT: Duration = Duration::from_secs(40);
109const RECORDING_START_LIMIT: Duration = Duration::from_secs(40);
94const SAME_PEER_ANSWER_LIMIT: Duration = Duration::from_secs(40);
110const SAME_PEER_ANSWER_LIMIT: Duration = Duration::from_secs(40);
111/// Teams sometimes answers a few seconds after the soft limit; keep the local offer until this grace ends.
112const SAME_PEER_LATE_GRACE: Duration = Duration::from_secs(15);
95const GATHERING_LIMIT: Duration = Duration::from_secs(5);
113const GATHERING_LIMIT: Duration = Duration::from_secs(5);
96const RELAY_SETTLE: Duration = Duration::from_millis(200);
114const GATHERING_QUIET: Duration = Duration::from_millis(500);
97const GATHERING_POLL: Duration = Duration::from_millis(50);
115const GATHERING_POLL: Duration = Duration::from_millis(50);
98const NEXT_PEER_LIMIT: Duration = Duration::from_secs(40);
116const NEXT_PEER_LIMIT: Duration = Duration::from_secs(40);
99const GLARE_RESEND_LIMIT: Duration = Duration::from_secs(3);
117const GLARE_RESEND_LIMIT: Duration = Duration::from_secs(3);
@@ -199,7 +217,10 @@ pub struct CallReport {
199#[derive(Debug, Clone)]
217#[derive(Debug, Clone)]
200pub enum CallSpec {
218pub enum CallSpec {
201 Echo,
219 Echo,
202 People { callees: Vec<Callee>, thread_id: String },
220 People {
221 callees: Vec<Callee>,
222 thread_id: String,
223 },
203 Meeting(MeetingTarget),
224 Meeting(MeetingTarget),
204}
225}
205
226
@@ -247,11 +268,16 @@ pub(crate) enum Plan {
247}
268}
248
269
249fn data_channel_from_env() -> bool {
270fn data_channel_from_env() -> bool {
250 !matches!(std::env::var(DATA_CHANNEL_ENV).ok().as_deref(), Some("0" | "off"))
271 !matches!(
272 std::env::var(DATA_CHANNEL_ENV).ok().as_deref(),
273 Some("0" | "off")
274 )
251}
275}
252
276
253pub fn keep_alive_period(seconds: Option<u64>) -> Duration {
277pub fn keep_alive_period(seconds: Option<u64>) -> Duration {
254 let seconds = seconds.unwrap_or(DEFAULT_KEEP_ALIVE_SECONDS).max(MIN_KEEP_ALIVE_SECONDS);
278 let seconds = seconds
279 .unwrap_or(DEFAULT_KEEP_ALIVE_SECONDS)
280 .max(MIN_KEEP_ALIVE_SECONDS);
255 Duration::from_secs_f64(seconds as f64 * KEEP_ALIVE_FRACTION)
281 Duration::from_secs_f64(seconds as f64 * KEEP_ALIVE_FRACTION)
256}
282}
257
283
@@ -286,19 +312,19 @@ struct PeerSession {
286struct Gathered {
312struct Gathered {
287 candidates: Arc<std::sync::Mutex<Vec<String>>>,
313 candidates: Arc<std::sync::Mutex<Vec<String>>>,
288 complete: Arc<AtomicBool>,
314 complete: Arc<AtomicBool>,
289 relay_seen_at: Arc<std::sync::Mutex<Option<Instant>>>,
315 relay_seen: Arc<AtomicBool>,
290 waited_ms: Arc<AtomicU64>,
316 last_candidate: Arc<std::sync::Mutex<Option<Instant>>>,
291}
292
293/// libwebrtc gathers continually here, and TCP/TLS relays trickle in late, so a UDP relay plus a short settle is enough.
294fn gathering_settled(complete: bool, since_udp_relay: Option<Duration>) -> bool {
295 complete || since_udp_relay.is_some_and(|since| since >= RELAY_SETTLE)
296}
317}
297
318
298impl Gathered {
319impl Gathered {
320 /// libwebrtc gathers continually here, so "done" is a relay candidate followed by a quiet spell.
299 fn settled(&self) -> bool {
321 fn settled(&self) -> bool {
300 let since_udp_relay = self.relay_seen_at.lock().expect("relay time lock").map(|at| at.elapsed());
322 let quiet = self
301 gathering_settled(self.complete.load(Ordering::SeqCst), since_udp_relay)
323 .last_candidate
324 .lock()
325 .expect("candidate time lock")
326 .is_some_and(|at| at.elapsed() >= GATHERING_QUIET);
327 self.complete.load(Ordering::SeqCst) || (self.relay_seen.load(Ordering::SeqCst) && quiet)
302 }
328 }
303
329
304 async fn candidates(&self) -> Vec<String> {
330 async fn candidates(&self) -> Vec<String> {
@@ -307,14 +333,8 @@ impl Gathered {
307 tokio::time::sleep(GATHERING_POLL).await;
333 tokio::time::sleep(GATHERING_POLL).await;
308 }
334 }
309 self.complete.store(true, Ordering::SeqCst);
335 self.complete.store(true, Ordering::SeqCst);
310 self.waited_ms.store(waited.elapsed().as_millis() as u64, Ordering::SeqCst);
311 self.candidates.lock().expect("candidates lock").clone()
336 self.candidates.lock().expect("candidates lock").clone()
312 }
337 }
313
314 fn summary(&self) -> String {
315 let count = self.candidates.lock().expect("candidates lock").len();
316 format!("{count} candidate(s) after {} ms", self.waited_ms.load(Ordering::SeqCst))
317 }
318}
338}
319
339
320async fn direct_sdp(teams_sdp: &str, gathered: Option<&Gathered>, kind: SdpKind) -> Result<String> {
340async fn direct_sdp(teams_sdp: &str, gathered: Option<&Gathered>, kind: SdpKind) -> Result<String> {
@@ -439,14 +459,22 @@ pub async fn run_test_call(
439 endpoint_storage_key: "__testCallEpid".into(),
459 endpoint_storage_key: "__testCallEpid".into(),
440 },
460 },
441 };
461 };
442 let (engine, _events) = CallEngine::start(session.clone(), poll_session.clone(), config).await?;
462 let (engine, _events) =
443 let report = engine.run(Plan::Outgoing(CallSpec::Echo), options, control).await;
463 CallEngine::start(session.clone(), poll_session.clone(), config).await?;
464 let report = engine
465 .run(Plan::Outgoing(CallSpec::Echo), options, control)
466 .await;
444 engine.stop().await;
467 engine.stop().await;
445 report
468 report
446}
469}
447
470
448impl CallEngine {
471impl CallEngine {
449 pub(crate) async fn run(&self, plan: Plan, options: CallOptions, mut control: CallControl) -> Result<CallReport> {
472 pub(crate) async fn run(
473 &self,
474 plan: Plan,
475 options: CallOptions,
476 mut control: CallControl,
477 ) -> Result<CallReport> {
450 let inner = self.inner.as_ref();
478 let inner = self.inner.as_ref();
451 let _one_call_at_a_time = if options.concurrent {
479 let _one_call_at_a_time = if options.concurrent {
452 None
480 None
@@ -463,7 +491,14 @@ impl CallEngine {
463 };
491 };
464 let timeline = Timeline::new(options.trace);
492 let timeline = Timeline::new(options.trace);
465 let stay_awake = crate::awake::StayAwake::new();
493 let stay_awake = crate::awake::StayAwake::new();
466 timeline.record("stay awake", if stay_awake.holding() { "system and display kept awake" } else { "not available" });
494 timeline.record(
495 "stay awake",
496 if stay_awake.holding() {
497 "system and display kept awake"
498 } else {
499 "not available"
500 },
501 );
467 let mut report = CallReport::default();
502 let mut report = CallReport::default();
468 let mut state = CallState::Idle;
503 let mut state = CallState::Idle;
469 advance(&mut state, CallSignal::Dial, &control);
504 advance(&mut state, CallSignal::Dial, &control);
@@ -493,14 +528,24 @@ impl CallEngine {
493 }
528 }
494 };
529 };
495 dump_timeline(&options, &timeline, failure.as_ref());
530 dump_timeline(&options, &timeline, failure.as_ref());
496 let cancelled = live.cancel_leave || matches!(&state, CallState::Ended { reason: crate::state::EndReason::Cancelled });
531 let cancelled = live.cancel_leave
532 || matches!(
533 &state,
534 CallState::Ended {
535 reason: crate::state::EndReason::Cancelled
536 }
537 );
497 tear_down(live, inner, &timeline, &mut report, cancelled).await;
538 tear_down(live, inner, &timeline, &mut report, cancelled).await;
498 let recording = recording.lock().await;
539 let recording = recording.lock().await;
499 report.recorded_samples = recording.samples.len();
540 report.recorded_samples = recording.samples.len();
500 report.timeline = timeline.entries();
541 report.timeline = timeline.entries();
501 control.send(CallUpdate::Diagnostics(Box::new(CallDiagnostics::new(&report, timeline.sdp_summaries()))));
542 control.send(CallUpdate::Diagnostics(Box::new(CallDiagnostics::new(
543 &report,
544 timeline.sdp_summaries(),
545 ))));
502 if let Some(path) = &options.wav_path {
546 if let Some(path) = &options.wav_path {
503 write_wav(path, &recording.samples).map_err(|error| Error::Webrtc(format!("wav: {error}")))?;
547 write_wav(path, &recording.samples)
548 .map_err(|error| Error::Webrtc(format!("wav: {error}")))?;
504 }
549 }
505 match failure {
550 match failure {
506 Some(error) => Err(error),
551 Some(error) => Err(error),
@@ -509,23 +554,32 @@ impl CallEngine {
509 }
554 }
510}
555}
511
556
512fn open_peer(factory: &PeerConnectionFactory, grant: &RelayGrant, relay_host: &str, with_data_channel: bool) -> Result<PeerSession> {
557fn open_peer(
558 factory: &PeerConnectionFactory,
559 grant: &RelayGrant,
560 relay_host: &str,
561 with_data_channel: bool,
562) -> Result<PeerSession> {
513 let mut configuration = RtcConfiguration::default();
563 let mut configuration = RtcConfiguration::default();
514 configuration.ice_servers = vec![grant.ice_server(relay_host)];
564 configuration.ice_servers = vec![grant.ice_server(relay_host)];
515 let peer = factory
565 let peer = factory
516 .create_peer_connection(configuration)
566 .create_peer_connection(configuration)
517 .map_err(|error| Error::Webrtc(error.to_string()))?;
567 .map_err(|error| Error::Webrtc(error.to_string()))?;
518 let (sender, events) = mpsc::unbounded_channel();
568 let (sender, events) = mpsc::unbounded_channel();
519 let data_channel = with_data_channel.then(|| open_data_channel(&peer, sender.clone())).transpose()?;
569 let data_channel = with_data_channel
570 .then(|| open_data_channel(&peer, sender.clone()))
571 .transpose()?;
520 let gathered = Gathered::default();
572 let gathered = Gathered::default();
521 let candidate_sink = gathered.candidates.clone();
573 let candidate_sink = gathered.candidates.clone();
522 let relay_seen_at = gathered.relay_seen_at.clone();
574 let relay_seen = gathered.relay_seen.clone();
575 let last_candidate = gathered.last_candidate.clone();
523 peer.on_ice_candidate(Some(Box::new(move |candidate| {
576 peer.on_ice_candidate(Some(Box::new(move |candidate| {
524 if candidate.sdp_mline_index() == 0 {
577 if candidate.sdp_mline_index() == 0 {
525 let text = candidate.candidate();
578 let text = candidate.candidate();
526 if is_udp_relay(&text) {
579 if is_udp_relay(&text) {
527 relay_seen_at.lock().expect("relay time lock").get_or_insert_with(Instant::now);
580 relay_seen.store(true, Ordering::SeqCst);
528 }
581 }
582 *last_candidate.lock().expect("candidate time lock") = Some(Instant::now());
529 candidate_sink.lock().expect("candidates lock").push(text);
583 candidate_sink.lock().expect("candidates lock").push(text);
530 }
584 }
531 })));
585 })));
@@ -552,10 +606,18 @@ fn open_peer(factory: &PeerConnectionFactory, grant: &RelayGrant, relay_host: &s
552 let _ = sender.send(PeerEvent::VideoTrack { mid, track });
606 let _ = sender.send(PeerEvent::VideoTrack { mid, track });
553 }
607 }
554 })));
608 })));
555 Ok(PeerSession { peer, events, _data_channel: data_channel, gathered })
609 Ok(PeerSession {
610 peer,
611 events,
612 _data_channel: data_channel,
613 gathered,
614 })
556}
615}
557
616
558fn open_data_channel(peer: &PeerConnection, sender: mpsc::UnboundedSender<PeerEvent>) -> Result<DataChannel> {
617fn open_data_channel(
618 peer: &PeerConnection,
619 sender: mpsc::UnboundedSender<PeerEvent>,
620) -> Result<DataChannel> {
559 let channel = peer
621 let channel = peer
560 .create_data_channel(DATA_CHANNEL_LABEL, DataChannelInit::default())
622 .create_data_channel(DATA_CHANNEL_LABEL, DataChannelInit::default())
561 .map_err(|error| Error::Webrtc(error.to_string()))?;
623 .map_err(|error| Error::Webrtc(error.to_string()))?;
@@ -565,7 +627,13 @@ fn open_data_channel(peer: &PeerConnection, sender: mpsc::UnboundedSender<PeerEv
565 Ok(channel)
627 Ok(channel)
566}
628}
567
629
568fn one_to_one_directions<'a>(camera: bool, share: bool, camera_mid: &'a str, share_mid: Option<&'a str>, remote_shares: bool) -> impl Fn(MediaLine<'_>) -> Option<&'static str> + 'a {
630fn one_to_one_directions<'a>(
631 camera: bool,
632 share: bool,
633 camera_mid: &'a str,
634 share_mid: Option<&'a str>,
635 remote_shares: bool,
636) -> impl Fn(MediaLine<'_>) -> Option<&'static str> + 'a {
569 move |line| match line.kind {
637 move |line| match line.kind {
570 "video" if line.mid == camera_mid => Some(if camera { "sendrecv" } else { INACTIVE }),
638 "video" if line.mid == camera_mid => Some(if camera { "sendrecv" } else { INACTIVE }),
571 "video" if Some(line.mid) == share_mid => Some(match (share, remote_shares) {
639 "video" if Some(line.mid) == share_mid => Some(match (share, remote_shares) {
@@ -593,15 +661,33 @@ fn share_mid_in(offer_text: &str) -> Option<String> {
593}
661}
594
662
595#[allow(clippy::too_many_arguments)]
663#[allow(clippy::too_many_arguments)]
596fn directions_for(layout: Layout, hold: bool, camera: bool, share: bool, camera_mid: &str, share_mid: Option<&str>, remote_shares: bool, text: &str) -> String {
664fn directions_for(
665 layout: Layout,
666 hold: bool,
667 camera: bool,
668 share: bool,
669 camera_mid: &str,
670 share_mid: Option<&str>,
671 remote_shares: bool,
672 text: &str,
673) -> String {
597 match (hold, layout) {
674 match (hold, layout) {
598 (true, _) => rewrite_directions(text, |_| Some(INACTIVE)),
675 (true, _) => rewrite_directions(text, |_| Some(INACTIVE)),
599 (false, Layout::OneToOne) => rewrite_directions(text, one_to_one_directions(camera, share, camera_mid, share_mid, remote_shares)),
676 (false, Layout::OneToOne) => rewrite_directions(
677 text,
678 one_to_one_directions(camera, share, camera_mid, share_mid, remote_shares),
679 ),
600 (false, Layout::Conference) => text.to_owned(),
680 (false, Layout::Conference) => text.to_owned(),
601 }
681 }
602}
682}
603
683
604async fn create_offer(peer: &PeerConnection, factory: &PeerConnectionFactory, track: &RtcAudioTrack, layout: Layout, gathered: Option<&Gathered>) -> Result<OfferedMedia> {
684async fn create_offer(
685 peer: &PeerConnection,
686 factory: &PeerConnectionFactory,
687 track: &RtcAudioTrack,
688 layout: Layout,
689 gathered: Option<&Gathered>,
690) -> Result<OfferedMedia> {
605 let transceiver_init = RtpTransceiverInit {
691 let transceiver_init = RtpTransceiverInit {
606 direction: RtpTransceiverDirection::SendRecv,
692 direction: RtpTransceiverDirection::SendRecv,
607 stream_ids: vec![MIC_STREAM.into()],
693 stream_ids: vec![MIC_STREAM.into()],
@@ -621,7 +707,16 @@ async fn create_offer(peer: &PeerConnection, factory: &PeerConnectionFactory, tr
621 })
707 })
622 .await
708 .await
623 .map_err(|error| Error::Webrtc(error.to_string()))?;
709 .map_err(|error| Error::Webrtc(error.to_string()))?;
624 let browser_offer = directions_for(layout, false, false, false, CAMERA_MID, Some(ONE_TO_ONE_SHARE_MID), false, &offer.to_string());
710 let browser_offer = directions_for(
711 layout,
712 false,
713 false,
714 false,
715 CAMERA_MID,
716 Some(ONE_TO_ONE_SHARE_MID),
717 false,
718 &offer.to_string(),
719 );
625 let description = parse_sdp(&browser_offer, SdpType::Offer)?;
720 let description = parse_sdp(&browser_offer, SdpType::Offer)?;
626 peer.set_local_description(description)
721 peer.set_local_description(description)
627 .await
722 .await
@@ -629,7 +724,13 @@ async fn create_offer(peer: &PeerConnection, factory: &PeerConnectionFactory, tr
629 let mut numbers = random_u32;
724 let mut numbers = random_u32;
630 let mut signaled = to_teams_offer(&browser_offer, &plan, &mut numbers)?;
725 let mut signaled = to_teams_offer(&browser_offer, &plan, &mut numbers)?;
631 signaled.sdp = direct_sdp(&signaled.sdp, gathered, SdpKind::Offer).await?;
726 signaled.sdp = direct_sdp(&signaled.sdp, gathered, SdpKind::Offer).await?;
632 Ok(OfferedMedia { browser_offer, signaled, video, plan, modalities: accepted_modalities(false) })
727 Ok(OfferedMedia {
728 browser_offer,
729 signaled,
730 video,
731 plan,
732 modalities: accepted_modalities(false),
733 })
633}
734}
634
735
635struct AnsweredMedia {
736struct AnsweredMedia {
@@ -640,11 +741,20 @@ struct AnsweredMedia {
640}
741}
641
742
642fn main_video_mid(remote: &RemoteOffer) -> Option<String> {
743fn main_video_mid(remote: &RemoteOffer) -> Option<String> {
643 remote.lines.iter().find(|line| line.role == LineRole::MainVideo).and_then(|line| line.browser_mids.first().cloned())
744 remote
745 .lines
746 .iter()
747 .find(|line| line.role == LineRole::MainVideo)
748 .and_then(|line| line.browser_mids.first().cloned())
644}
749}
645
750
646fn share_mids(remote: &RemoteOffer) -> Vec<String> {
751fn share_mids(remote: &RemoteOffer) -> Vec<String> {
647 remote.lines.iter().filter(|line| line.role == LineRole::ScreenShare).filter_map(|line| line.browser_mids.first().cloned()).collect()
752 remote
753 .lines
754 .iter()
755 .filter(|line| line.role == LineRole::ScreenShare)
756 .filter_map(|line| line.browser_mids.first().cloned())
757 .collect()
648}
758}
649
759
650async fn answer_offer(
760async fn answer_offer(
@@ -658,17 +768,32 @@ async fn answer_offer(
658) -> Result<AnsweredMedia> {
768) -> Result<AnsweredMedia> {
659 let remote = from_teams_offer(teams_offer)?;
769 let remote = from_teams_offer(teams_offer)?;
660 let description = parse_sdp(&remote.browser_sdp, SdpType::Offer)?;
770 let description = parse_sdp(&remote.browser_sdp, SdpType::Offer)?;
661 peer.set_remote_description(description).await.map_err(|error| {
771 peer.set_remote_description(description)
662 let lines: Vec<String> = remote.lines.iter().map(|line| format!("{:?}{:?}", line.role, line.browser_mids)).collect();
772 .await
663 Error::Webrtc(format!("{error} (offer lines: {})", lines.join(" ")))
773 .map_err(|error| {
664 })?;
774 let lines: Vec<String> = remote
775 .lines
776 .iter()
777 .map(|line| format!("{:?}{:?}", line.role, line.browser_mids))
778 .collect();
779 Error::Webrtc(format!("{error} (offer lines: {})", lines.join(" ")))
780 })?;
665 let camera_mid = main_video_mid(&remote).filter(|_| !matches!(video, AnswerVideo::Reject));
781 let camera_mid = main_video_mid(&remote).filter(|_| !matches!(video, AnswerVideo::Reject));
666 let kept_share_mids = if matches!(video, AnswerVideo::Reject) { Vec::new() } else { share_mids(&remote) };
782 let kept_share_mids = if matches!(video, AnswerVideo::Reject) {
783 Vec::new()
784 } else {
785 share_mids(&remote)
786 };
667 for transceiver in peer.transceivers() {
787 for transceiver in peer.transceivers() {
668 let is_video = matches!(transceiver.receiver().track(), Some(MediaStreamTrack::Video(_)));
788 let is_video = matches!(
669 let unused = transceiver
789 transceiver.receiver().track(),
670 .mid()
790 Some(MediaStreamTrack::Video(_))
671 .is_some_and(|mid| Some(&mid) != camera_mid.as_ref() && !kept_share_mids.contains(&mid) && Some(&mid) != sending_share_mid.as_ref());
791 );
792 let unused = transceiver.mid().is_some_and(|mid| {
793 Some(&mid) != camera_mid.as_ref()
794 && !kept_share_mids.contains(&mid)
795 && Some(&mid) != sending_share_mid.as_ref()
796 });
672 if is_video && unused {
797 if is_video && unused {
673 let _ = transceiver.stop();
798 let _ = transceiver.stop();
674 }
799 }
@@ -686,7 +811,10 @@ async fn answer_offer(
686 .await
811 .await
687 .map_err(|error| Error::Webrtc(error.to_string()))?;
812 .map_err(|error| Error::Webrtc(error.to_string()))?;
688 let mut answer_text = answer.to_string();
813 let mut answer_text = answer.to_string();
689 for mid in kept_share_mids.iter().filter(|mid| sending_share_mid.as_deref() != Some(mid.as_str())) {
814 for mid in kept_share_mids
815 .iter()
816 .filter(|mid| sending_share_mid.as_deref() != Some(mid.as_str()))
817 {
690 answer_text = stop_sending_on(&answer_text, mid);
818 answer_text = stop_sending_on(&answer_text, mid);
691 }
819 }
692 let sends_camera = camera_on || matches!(video, AnswerVideo::Send(_));
820 let sends_camera = camera_on || matches!(video, AnswerVideo::Send(_));
@@ -699,7 +827,12 @@ async fn answer_offer(
699 let receiving_share_mid = kept_share_mids
827 let receiving_share_mid = kept_share_mids
700 .into_iter()
828 .into_iter()
701 .filter(|mid| sending_share_mid.as_deref() != Some(mid.as_str()))
829 .filter(|mid| sending_share_mid.as_deref() != Some(mid.as_str()))
702 .find(|mid| matches!(direction_of(&answer_text, mid).as_deref(), Some("recvonly" | "sendrecv")));
830 .find(|mid| {
831 matches!(
832 direction_of(&answer_text, mid).as_deref(),
833 Some("recvonly" | "sendrecv")
834 )
835 });
703 let mut numbers = random_u32;
836 let mut numbers = random_u32;
704 let signaled = to_teams_answer(&answer_text, &remote, &mut numbers)?;
837 let signaled = to_teams_answer(&answer_text, &remote, &mut numbers)?;
705 Ok(AnsweredMedia {
838 Ok(AnsweredMedia {
@@ -714,7 +847,10 @@ fn new_media_leg_id() -> String {
714 uuid::Uuid::new_v4().simple().to_string().to_uppercase()
847 uuid::Uuid::new_v4().simple().to_string().to_uppercase()
715}
848}
716
849
717async fn setup_step<T, E>(control: &mut CallControl, step: impl std::future::Future<Output = std::result::Result<T, E>>) -> Result<T>
850async fn setup_step<T, E>(
851 control: &mut CallControl,
852 step: impl std::future::Future<Output = std::result::Result<T, E>>,
853) -> Result<T>
718where
854where
719 Error: From<E>,
855 Error: From<E>,
720{
856{
@@ -759,12 +895,16 @@ async fn drive(
759 report: &mut CallReport,
895 report: &mut CallReport,
760) -> Result<()> {
896) -> Result<()> {
761 let own_mri = format!("8:orgid:{}", inner.identity.object_id);
897 let own_mri = format!("8:orgid:{}", inner.identity.object_id);
762 control.send(CallUpdate::OwnIdentity { mri: own_mri.clone() });
898 control.send(CallUpdate::OwnIdentity {
899 mri: own_mri.clone(),
900 });
763 let (spec, incoming) = match plan {
901 let (spec, incoming) = match plan {
764 Plan::Outgoing(spec) => (Some(spec), None),
902 Plan::Outgoing(spec) => (Some(spec), None),
765 Plan::Incoming(incoming) => (None, Some(*incoming)),
903 Plan::Incoming(incoming) => (None, Some(*incoming)),
766 };
904 };
767 let accept_mode = incoming.as_ref().map_or(AcceptMode::Audio, |incoming| incoming.accept);
905 let accept_mode = incoming
906 .as_ref()
907 .map_or(AcceptMode::Audio, |incoming| incoming.accept);
768 let (links, participant, mut callbacks, incoming_media) = match incoming {
908 let (links, participant, mut callbacks, incoming_media) = match incoming {
769 Some(IncomingCall {
909 Some(IncomingCall {
770 accept: _,
910 accept: _,
@@ -773,7 +913,12 @@ async fn drive(
773 links,
913 links,
774 participant,
914 participant,
775 callbacks,
915 callbacks,
776 }) => (links, participant, callbacks, Some((notification, attached))),
916 }) => (
917 links,
918 participant,
919 callbacks,
920 Some((notification, attached)),
921 ),
777 None => {
922 None => {
778 let links = inner.callback_links();
923 let links = inner.callback_links();
779 let participant = inner.participant(&uuid::Uuid::new_v4().to_string());
924 let participant = inner.participant(&uuid::Uuid::new_v4().to_string());
@@ -786,15 +931,26 @@ async fn drive(
786
931
787 let thread_id = if matches!(spec, Some(CallSpec::Echo)) {
932 let thread_id = if matches!(spec, Some(CallSpec::Echo)) {
788 let thread_id = control
933 let thread_id = control
789 .until_hangup(find_echo_bot_thread(&inner.session, &inner.identity.object_id))
934 .until_hangup(find_echo_bot_thread(
935 &inner.session,
936 &inner.identity.object_id,
937 ))
790 .await??;
938 .await??;
791 timeline.record("echo bot chat", if thread_id.is_some() { "found" } else { "none" });
939 timeline.record(
940 "echo bot chat",
941 if thread_id.is_some() { "found" } else { "none" },
942 );
792 thread_id
943 thread_id
793 } else {
944 } else {
794 None
945 None
795 };
946 };
796 let grant = control.until_hangup(inner.relay.grant(&inner.session)).await??;
947 let grant = control
797 timeline.record("GET trap/tokens", format!("relay grant, expires in {} s", grant.expires_in_seconds));
948 .until_hangup(fetch_relay_grant(&inner.session))
949 .await??;
950 timeline.record(
951 "GET trap/tokens",
952 format!("relay grant, expires in {} s", grant.expires_in_seconds),
953 );
798
954
799 let factory = devices::shared_factory();
955 let factory = devices::shared_factory();
800 let mut input = options.input.clone();
956 let mut input = options.input.clone();
@@ -802,15 +958,34 @@ async fn drive(
802 let audio = AudioSetup::start(&factory, options.audio, options.tone_hz, &input, &output);
958 let audio = AudioSetup::start(&factory, options.audio, options.tone_hz, &input, &output);
803 control.send(CallUpdate::ListenOnly(audio.listen_only));
959 control.send(CallUpdate::ListenOnly(audio.listen_only));
804 let mut device_lists = devices::list_devices(&factory);
960 let mut device_lists = devices::list_devices(&factory);
805 let mut applied_input = devices::applied_device(&device_lists.inputs, &input, devices::system_default_id(Flow::Capture).as_deref());
961 let mut applied_input = devices::applied_device(
806 let mut applied_output = devices::applied_device(&device_lists.outputs, &output, devices::system_default_id(Flow::Render).as_deref());
962 &device_lists.inputs,
963 &input,
964 devices::system_default_id(Flow::Capture).as_deref(),
965 );
966 let mut applied_output = devices::applied_device(
967 &device_lists.outputs,
968 &output,
969 devices::system_default_id(Flow::Render).as_deref(),
970 );
807 let (_device_watcher, mut device_changes) = device_watch::watch();
971 let (_device_watcher, mut device_changes) = device_watch::watch();
808 let mut device_debounce = Debounce::default();
972 let mut device_debounce = Debounce::default();
809 timeline.record(
973 timeline.record(
810 "audio setup",
974 "audio setup",
811 format!("listen only {}, {} input(s), {} output(s); {}", audio.listen_only, device_lists.inputs.len(), device_lists.outputs.len(), audio.adm_state),
975 format!(
976 "listen only {}, {} input(s), {} output(s); {}",
977 audio.listen_only,
978 device_lists.inputs.len(),
979 device_lists.outputs.len(),
980 audio.adm_state
981 ),
982 );
983 record_audio_devices(
984 timeline,
985 &device_lists,
986 applied_input.as_ref(),
987 applied_output.as_ref(),
812 );
988 );
813 record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref());
814 control.send(CallUpdate::Devices(device_lists.clone()));
989 control.send(CallUpdate::Devices(device_lists.clone()));
815 control.send(CallUpdate::Selected {
990 control.send(CallUpdate::Selected {
816 input: input.clone(),
991 input: input.clone(),
@@ -818,7 +993,13 @@ async fn drive(
818 });
993 });
819 let track = audio.track.clone();
994 let track = audio.track.clone();
820 live.audio = Some(audio);
995 live.audio = Some(audio);
821 let mut local_video = LocalVideo::new(&factory, options.video, control.video.clone(), control.updates());
996 let mut local_video = LocalVideo::new(
997 &factory,
998 options.video,
999 control.video.clone(),
1000 control.updates(),
1001 );
1002 local_video.attach_timeline(timeline.clone());
822 let mut camera_choice = options.camera.clone();
1003 let mut camera_choice = options.camera.clone();
823 if options.start_camera {
1004 if options.start_camera {
824 match local_video.preview_camera(&camera_choice) {
1005 match local_video.preview_camera(&camera_choice) {
@@ -828,9 +1009,11 @@ async fn drive(
828 }
1009 }
829 let mut media_description_request = 1u32;
1010 let mut media_description_request = 1u32;
830 refresh_cameras(control.updates(), options.video, timeline.clone());
1011 refresh_cameras(control.updates(), options.video, timeline.clone());
1012 control.send(CallUpdate::SharePicker(current_share_picker()));
831 refresh_share_sources(control.updates(), options.video, false);
1013 refresh_share_sources(control.updates(), options.video, false);
832
1014
833 let wants_data_channel = options.data_channel && spec.as_ref().is_some_and(CallSpec::is_meeting);
1015 let wants_data_channel =
1016 options.data_channel && spec.as_ref().is_some_and(CallSpec::is_meeting);
834 let mut current = open_peer(&factory, &grant, &options.relay_host, wants_data_channel)?;
1017 let mut current = open_peer(&factory, &grant, &options.relay_host, wants_data_channel)?;
835 live.peers.push(current.peer.clone());
1018 live.peers.push(current.peer.clone());
836
1019
@@ -854,7 +1037,9 @@ async fn drive(
854 _ => None,
1037 _ => None,
855 };
1038 };
856 let people_thread = match &spec {
1039 let people_thread = match &spec {
857 Some(CallSpec::People { thread_id, .. }) if !thread_id.is_empty() => Some(thread_id.clone()),
1040 Some(CallSpec::People { thread_id, .. }) if !thread_id.is_empty() => {
1041 Some(thread_id.clone())
1042 }
858 _ => incoming_media
1043 _ => incoming_media
859 .as_ref()
1044 .as_ref()
860 .filter(|(notification, _)| !notification.is_multi_party)
1045 .filter(|(notification, _)| !notification.is_multi_party)
@@ -863,7 +1048,9 @@ async fn drive(
863 .thread_id
1048 .thread_id
864 .clone()
1049 .clone()
865 .filter(|thread| *thread != notification.caller.mri)
1050 .filter(|thread| *thread != notification.caller.mri)
866 .or_else(|| one_to_one_thread(&inner.identity.object_id, &notification.caller.mri))
1051 .or_else(|| {
1052 one_to_one_thread(&inner.identity.object_id, &notification.caller.mri)
1053 })
867 }),
1054 }),
868 };
1055 };
869 let mut layout = match &spec {
1056 let mut layout = match &spec {
@@ -871,8 +1058,12 @@ async fn drive(
871 _ => Layout::Conference,
1058 _ => Layout::Conference,
872 };
1059 };
873 let peer_mri = match &spec {
1060 let peer_mri = match &spec {
874 Some(CallSpec::People { callees, .. }) if callees.len() == 1 => Some(callees[0].mri.clone()),
1061 Some(CallSpec::People { callees, .. }) if callees.len() == 1 => {
875 _ => incoming_media.as_ref().map(|(notification, _)| notification.caller.mri.clone()),
1062 Some(callees[0].mri.clone())
1063 }
1064 _ => incoming_media
1065 .as_ref()
1066 .map(|(notification, _)| notification.caller.mri.clone()),
876 };
1067 };
877 let mut layout_plan: OfferPlan;
1068 let mut layout_plan: OfferPlan;
878 let mut direct_video_mid: Option<String> = None;
1069 let mut direct_video_mid: Option<String> = None;
@@ -884,14 +1075,26 @@ async fn drive(
884 let direct_invite = spec.target().is_one_to_one() && !options.concurrent;
1075 let direct_invite = spec.target().is_one_to_one() && !options.concurrent;
885 let offer_started = Instant::now();
1076 let offer_started = Instant::now();
886 let media = control
1077 let media = control
887 .until_hangup(create_offer(&current.peer, &factory, &track, layout, direct_invite.then_some(&current.gathered)))
1078 .until_hangup(create_offer(
1079 &current.peer,
1080 &factory,
1081 &track,
1082 layout,
1083 direct_invite.then_some(&current.gathered),
1084 ))
888 .await??;
1085 .await??;
889 timeline.record("offer created", format!("{} ms", offer_started.elapsed().as_millis()));
1086 timeline.record(
1087 "offer created",
1088 format!("{} ms", offer_started.elapsed().as_millis()),
1089 );
890 layout_plan = media.plan.clone();
1090 layout_plan = media.plan.clone();
891 if layout == Layout::OneToOne {
1091 if layout == Layout::OneToOne {
892 direct_video_mid = Some(CAMERA_MID.to_owned());
1092 direct_video_mid = Some(CAMERA_MID.to_owned());
893 }
1093 }
894 timeline.record("setLocalDescription", format!("{} m-line(s) signaled", media.signaled.lines.len()));
1094 timeline.record(
1095 "setLocalDescription",
1096 format!("{} m-line(s) signaled", media.signaled.lines.len()),
1097 );
895 timeline.record_sdp("local offer", &media.signaled.sdp);
1098 timeline.record_sdp("local offer", &media.signaled.sdp);
896 dump_sdp(options, "1-browser-offer.sdp", &media.browser_offer);
1099 dump_sdp(options, "1-browser-offer.sdp", &media.browser_offer);
897 dump_sdp(options, "2-teams-offer.sdp", &media.signaled.sdp);
1100 dump_sdp(options, "2-teams-offer.sdp", &media.signaled.sdp);
@@ -950,7 +1153,11 @@ async fn drive(
950 threadless: notification.thread_id.is_none(),
1153 threadless: notification.thread_id.is_none(),
951 });
1154 });
952 let one_to_one = !attached.from_mixer && !notification.is_multi_party;
1155 let one_to_one = !attached.from_mixer && !notification.is_multi_party;
953 layout = if one_to_one { Layout::OneToOne } else { Layout::Conference };
1156 layout = if one_to_one {
1157 Layout::OneToOne
1158 } else {
1159 Layout::Conference
1160 };
954 let camera_track = local_video.camera_track();
1161 let camera_track = local_video.camera_track();
955 let video_answer = match accept_mode {
1162 let video_answer = match accept_mode {
956 _ if !one_to_one => AnswerVideo::Reject,
1163 _ if !one_to_one => AnswerVideo::Reject,
@@ -958,21 +1165,34 @@ async fn drive(
958 _ => AnswerVideo::Receive,
1165 _ => AnswerVideo::Receive,
959 };
1166 };
960 dump_sdp(options, "3-teams-offer.sdp", &teams_offer);
1167 dump_sdp(options, "3-teams-offer.sdp", &teams_offer);
961 let answered = answer_offer(&current.peer, Some(&track), &teams_offer, video_answer, None, false, one_to_one.then_some(&current.gathered)).await?;
1168 let answered = answer_offer(
1169 &current.peer,
1170 Some(&track),
1171 &teams_offer,
1172 video_answer,
1173 None,
1174 false,
1175 one_to_one.then_some(&current.gathered),
1176 )
1177 .await?;
962 layout_plan = answered.remote.plan();
1178 layout_plan = answered.remote.plan();
963 direct_video_mid = answered.camera_mid.clone();
1179 direct_video_mid = answered.camera_mid.clone();
964 timeline.record("setRemoteDescription", format!("offer applied, {} signaled line(s)", answered.remote.lines.len()));
1180 timeline.record(
965 if one_to_one {
1181 "setRemoteDescription",
966 timeline.record("ice gathered", current.gathered.summary());
1182 format!(
967 }
1183 "offer applied, {} signaled line(s)",
1184 answered.remote.lines.len()
1185 ),
1186 );
968 timeline.record_sdp("remote offer", &teams_offer);
1187 timeline.record_sdp("remote offer", &teams_offer);
969 timeline.record_sdp("local answer", &answered.answer_sdp);
1188 timeline.record_sdp("local answer", &answered.answer_sdp);
970 dump_sdp(options, "4-teams-answer.sdp", &answered.answer_sdp);
1189 dump_sdp(options, "4-teams-answer.sdp", &answered.answer_sdp);
971 let acceptance_url = attached
1190 let acceptance_url = attached.links.get("acceptance").ok_or_else(|| {
972 .links
1191 Error::Signaling("attach answer without an acceptance link".into())
973 .get("acceptance")
1192 })?;
974 .ok_or_else(|| Error::Signaling("attach answer without an acceptance link".into()))?;
1193 let modalities = accepted_modalities(
975 let modalities = accepted_modalities(matches!(video_answer, AnswerVideo::Send(_)) && answered.camera_mid.is_some());
1194 matches!(video_answer, AnswerVideo::Send(_)) && answered.camera_mid.is_some(),
1195 );
976 let acknowledged = signaling
1196 let acknowledged = signaling
977 .accept(
1197 .accept(
978 acceptance_url,
1198 acceptance_url,
@@ -991,20 +1211,36 @@ async fn drive(
991 media_links.extend(acknowledged);
1211 media_links.extend(acknowledged);
992 if let (AnswerVideo::Send(_), Some(mid)) = (video_answer, &answered.camera_mid) {
1212 if let (AnswerVideo::Send(_), Some(mid)) = (video_answer, &answered.camera_mid) {
993 let camera = peer_transceiver(&current.peer, mid);
1213 let camera = peer_transceiver(&current.peer, mid);
994 match camera.map(|camera| local_video.set_lines(VideoLines { camera, share: None })) {
1214 match camera.map(|camera| {
1215 local_video.set_lines(VideoLines {
1216 camera,
1217 share: None,
1218 })
1219 }) {
995 Some(Ok(())) => match local_video.start_camera(&camera_choice) {
1220 Some(Ok(())) => match local_video.start_camera(&camera_choice) {
996 Ok(()) => sending_camera = true,
1221 Ok(()) => sending_camera = true,
997 Err(error) => control.send(CallUpdate::Notice(format!("Camera could not start: {error}"))),
1222 Err(error) => control.send(CallUpdate::Notice(format!(
1223 "Camera could not start: {error}"
1224 ))),
998 },
1225 },
999 Some(Err(error)) => timeline.record("video lines not attached", error.to_string()),
1226 Some(Err(error)) => {
1000 None => timeline.record("video lines not attached", "no transceiver for the camera line"),
1227 timeline.record("video lines not attached", error.to_string())
1228 }
1229 None => timeline.record(
1230 "video lines not attached",
1231 "no transceiver for the camera line",
1232 ),
1001 }
1233 }
1002 }
1234 }
1003 keep_alive_link = media_links.get("callLeg").cloned();
1235 keep_alive_link = media_links.get("callLeg").cloned();
1004 keep_alive_at = Some(Instant::now() + keep_alive_period(None));
1236 keep_alive_at = Some(Instant::now() + keep_alive_period(None));
1005 conversation
1237 conversation
1006 }
1238 }
1007 _ => return Err(Error::Callback("call plan without an offer or an invitation".into())),
1239 _ => {
1240 return Err(Error::Callback(
1241 "call plan without an offer or an invitation".into(),
1242 ));
1243 }
1008 };
1244 };
1009 let remote = live.remote.clone().expect("remote call set above");
1245 let remote = live.remote.clone().expect("remote call set above");
1010 live.broker_running.store(true, Ordering::SeqCst);
1246 live.broker_running.store(true, Ordering::SeqCst);
@@ -1016,11 +1252,20 @@ async fn drive(
1016
1252
1017 let initial = MuteEffect::initial(is_meeting);
1253 let initial = MuteEffect::initial(is_meeting);
1018 let mut muted = initial.muted;
1254 let mut muted = initial.muted;
1019 live.audio.as_ref().expect("audio set above").track.set_enabled(initial.track_enabled);
1255 live.audio
1256 .as_ref()
1257 .expect("audio set above")
1258 .track
1259 .set_enabled(initial.track_enabled);
1020 if muted {
1260 if muted {
1021 control.send(CallUpdate::Muted(true));
1261 control.send(CallUpdate::Muted(true));
1022 }
1262 }
1023 match setup_step(control, signaling.update_endpoint_state(&conversation, &participant, initial.endpoint_is_muted)).await {
1263 match setup_step(
1264 control,
1265 signaling.update_endpoint_state(&conversation, &participant, initial.endpoint_is_muted),
1266 )
1267 .await
1268 {
1024 Err(Error::Cancelled) => return Err(Error::Cancelled),
1269 Err(Error::Cancelled) => return Err(Error::Cancelled),
1025 Err(error) => timeline.record("updateEndpointState failed", error.to_string()),
1270 Err(error) => timeline.record("updateEndpointState failed", error.to_string()),
1026 Ok(()) => {}
1271 Ok(()) => {}
@@ -1038,7 +1283,13 @@ async fn drive(
1038 && roster.apply_snapshot(snapshot)
1283 && roster.apply_snapshot(snapshot)
1039 {
1284 {
1040 let entries = roster.entries();
1285 let entries = roster.entries();
1041 timeline.record("roster", format!("{} participant(s) from the conversation answer", entries.len()));
1286 timeline.record(
1287 "roster",
1288 format!(
1289 "{} participant(s) from the conversation answer",
1290 entries.len()
1291 ),
1292 );
1042 control.send(CallUpdate::Roster(entries));
1293 control.send(CallUpdate::Roster(entries));
1043 }
1294 }
1044 let mut lobby = false;
1295 let mut lobby = false;
@@ -1063,7 +1314,25 @@ async fn drive(
1063 crate::noise_stage::apply(mic_settings);
1314 crate::noise_stage::apply(mic_settings);
1064 let mut audio_disabled = false;
1315 let mut audio_disabled = false;
1065 let mut remote_audio: Option<RtcAudioTrack> = None;
1316 let mut remote_audio: Option<RtcAudioTrack> = None;
1066 sync_software_audio(&factory, options, &input, muted, None, &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1317 sync_software_audio(
1318 &factory,
1319 options,
1320 &input,
1321 muted,
1322 None,
1323 &current.peer,
1324 &track,
1325 software_wanted(
1326 mic_settings,
1327 share_sound_wanted,
1328 &local_video,
1329 live.audio.as_ref(),
1330 ),
1331 false,
1332 &mut software_audio,
1333 control,
1334 timeline,
1335 );
1067 let mut own_hand: Option<String> = None;
1336 let mut own_hand: Option<String> = None;
1068 let mut depacketizer = Depacketizer::default();
1337 let mut depacketizer = Depacketizer::default();
1069 let mut caption_flow = CaptionFlow::default();
1338 let mut caption_flow = CaptionFlow::default();
@@ -1083,6 +1352,7 @@ async fn drive(
1083 let mut send_requests = RequestFilter::default();
1352 let mut send_requests = RequestFilter::default();
1084 let mut send_capabilities = SendCapabilityReporter::default();
1353 let mut send_capabilities = SendCapabilityReporter::default();
1085 let mut same_peer_deadline: Option<Instant> = None;
1354 let mut same_peer_deadline: Option<Instant> = None;
1355 let mut same_peer_grace_until: Option<Instant> = None;
1086 let mut meeting_chat = conversation.chat_thread.clone();
1356 let mut meeting_chat = conversation.chat_thread.clone();
1087 if let Some(thread) = &meeting_chat {
1357 if let Some(thread) = &meeting_chat {
1088 control.send(CallUpdate::MeetingChat(thread.clone()));
1358 control.send(CallUpdate::MeetingChat(thread.clone()));
@@ -1095,6 +1365,7 @@ async fn drive(
1095 }
1365 }
1096 let mut start_camera_pending = options.start_camera;
1366 let mut start_camera_pending = options.start_camera;
1097 let mut share_pending: Option<ShareSource> = None;
1367 let mut share_pending: Option<ShareSource> = None;
1368 let mut portal_pending: Option<ShareKind> = None;
1098 let mut glare_resend: Option<GlareResend> = None;
1369 let mut glare_resend: Option<GlareResend> = None;
1099 let mut deferred_changes: Vec<Change> = Vec::new();
1370 let mut deferred_changes: Vec<Change> = Vec::new();
1100 let mut remote_direct_share: Option<String> = None;
1371 let mut remote_direct_share: Option<String> = None;
@@ -1109,10 +1380,19 @@ async fn drive(
1109 {
1380 {
1110 control.defer(CallCommand::StartShare(source));
1381 control.defer(CallCommand::StartShare(source));
1111 }
1382 }
1112 if next.as_ref().is_some_and(|pending| pending.connected && (pending.offered.is_some() || pending.retargeted))
1383 if video_possible(remote_set, layout, negotiator.path())
1113 && let Some(pending) = next.take()
1384 && let Some(kind) = portal_pending.take()
1114 {
1385 {
1115 timeline.record("escalation", "new peer connection connected, old one dropped");
1386 control.defer(CallCommand::StartPortalShare(kind));
1387 }
1388 if next.as_ref().is_some_and(|pending| {
1389 pending.connected && (pending.offered.is_some() || pending.retargeted)
1390 }) && let Some(pending) = next.take()
1391 {
1392 timeline.record(
1393 "escalation",
1394 "new peer connection connected, old one dropped",
1395 );
1116 deferred_changes.clear();
1396 deferred_changes.clear();
1117 negotiator.server_escalation_done();
1397 negotiator.server_escalation_done();
1118 if let Some(mid) = remote_direct_share.take() {
1398 if let Some(mid) = remote_direct_share.take() {
@@ -1137,15 +1417,40 @@ async fn drive(
1137 timeline.record("video lines not attached", error.to_string());
1417 timeline.record("video lines not attached", error.to_string());
1138 }
1418 }
1139 if local_video.camera_on() {
1419 if local_video.camera_on() {
1140 tell_media_descriptions(&remote, &media_links, MediaDescription::camera(true), &mut media_description_request, timeline);
1420 tell_media_descriptions(
1421 &remote,
1422 &media_links,
1423 MediaDescription::camera(true),
1424 &mut media_description_request,
1425 timeline,
1426 );
1141 }
1427 }
1142 if local_video.sharing() {
1428 if local_video.sharing() {
1143 tell_media_descriptions(&remote, &media_links, MediaDescription::share(true), &mut media_description_request, timeline);
1429 tell_media_descriptions(
1430 &remote,
1431 &media_links,
1432 MediaDescription::share(true),
1433 &mut media_description_request,
1434 timeline,
1435 );
1144 }
1436 }
1145 }
1437 }
1146 remote_set = true;
1438 remote_set = true;
1147 if layout == Layout::OneToOne && negotiator.begin_conference_upgrade() {
1439 if layout == Layout::OneToOne && negotiator.begin_conference_upgrade() {
1148 let pending = escalate(&factory, &grant, options, outgoing_track(software_audio.as_ref(), &track), &remote, &links, &media_leg_id, &media_links, &mut negotiator, live, timeline).await;
1440 let pending = escalate(
1441 &factory,
1442 &grant,
1443 options,
1444 outgoing_track(software_audio.as_ref(), &track),
1445 &remote,
1446 &links,
1447 &media_leg_id,
1448 &media_links,
1449 &mut negotiator,
1450 live,
1451 timeline,
1452 )
1453 .await;
1149 if pending.is_none() {
1454 if pending.is_none() {
1150 drop_local_media(&mut local_video, control);
1455 drop_local_media(&mut local_video, control);
1151 }
1456 }
@@ -1268,6 +1573,7 @@ async fn drive(
1268 && let Some(pending) = same_peer.take()
1573 && let Some(pending) = same_peer.take()
1269 {
1574 {
1270 same_peer_deadline = None;
1575 same_peer_deadline = None;
1576 same_peer_grace_until = None;
1271 let applied = match pending.change {
1577 let applied = match pending.change {
1272 Change::Hold(_) => apply_hold_answer(&current.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await,
1578 Change::Hold(_) => apply_hold_answer(&current.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await,
1273 Change::Camera(_) | Change::Share(_) => apply_answer(&current.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await,
1579 Change::Camera(_) | Change::Share(_) => apply_answer(&current.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await,
@@ -1287,7 +1593,7 @@ async fn drive(
1287 Change::Share(true) if !answer.from_mixer && !local_video.share_sending() => {
1593 Change::Share(true) if !answer.from_mixer && !local_video.share_sending() => {
1288 local_video.stop_share();
1594 local_video.stop_share();
1289 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1595 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1290 control.send(CallUpdate::LocalShare(None));
1596 clear_share(control);
1291 control.send(CallUpdate::Notice(SHARE_REFUSED_NOTICE.into()));
1597 control.send(CallUpdate::Notice(SHARE_REFUSED_NOTICE.into()));
1292 }
1598 }
1293 Change::Share(_) => {}
1599 Change::Share(_) => {}
@@ -1348,6 +1654,7 @@ async fn drive(
1348 && let Some(pending) = same_peer.take()
1654 && let Some(pending) = same_peer.take()
1349 {
1655 {
1350 same_peer_deadline = None;
1656 same_peer_deadline = None;
1657 same_peer_grace_until = None;
1351 negotiator.same_peer_offer_failed();
1658 negotiator.same_peer_offer_failed();
1352 rollback_offer(&current.peer).await;
1659 rollback_offer(&current.peer).await;
1353 timeline.record("glare", "the remote offer is answered first, ours goes out again after");
1660 timeline.record("glare", "the remote offer is answered first, ours goes out again after");
@@ -1359,6 +1666,7 @@ async fn drive(
1359 MediaAction::AnswerOnNewPeer => {
1666 MediaAction::AnswerOnNewPeer => {
1360 if let Some(pending) = same_peer.take() {
1667 if let Some(pending) = same_peer.take() {
1361 same_peer_deadline = None;
1668 same_peer_deadline = None;
1669 same_peer_grace_until = None;
1362 timeline.record("same-peer offer", "superseded by the escalation offer");
1670 timeline.record("same-peer offer", "superseded by the escalation offer");
1363 rollback_offer(&current.peer).await;
1671 rollback_offer(&current.peer).await;
1364 defer_to_new_peer(pending.change, &mut deferred_changes, &mut local_video, control);
1672 defer_to_new_peer(pending.change, &mut deferred_changes, &mut local_video, control);
@@ -1659,6 +1967,7 @@ async fn drive(
1659 Ok(CallEvent::Rejection(body)) => match negotiator.on_rejection() {
1967 Ok(CallEvent::Rejection(body)) => match negotiator.on_rejection() {
1660 RejectedOffer::SamePeer => {
1968 RejectedOffer::SamePeer => {
1661 same_peer_deadline = None;
1969 same_peer_deadline = None;
1970 same_peer_grace_until = None;
1662 if let Some(pending) = same_peer.take() {
1971 if let Some(pending) = same_peer.take() {
1663 rollback_offer(&current.peer).await;
1972 rollback_offer(&current.peer).await;
1664 if is_glare_rejection(&body) {
1973 if is_glare_rejection(&body) {
@@ -1878,6 +2187,7 @@ async fn drive(
1878 timeline.record_sdp("local offer", &signaled.sdp);
2187 timeline.record_sdp("local offer", &signaled.sdp);
1879 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(true), reply_tags });
2188 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(true), reply_tags });
1880 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2189 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2190 same_peer_grace_until = None;
1881 }
2191 }
1882 Err(error) => {
2192 Err(error) => {
1883 timeline.record("camera offer failed", error.to_string());
2193 timeline.record("camera offer failed", error.to_string());
@@ -1900,6 +2210,7 @@ async fn drive(
1900 timeline.record_sdp("local offer", &signaled.sdp);
2210 timeline.record_sdp("local offer", &signaled.sdp);
1901 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(false), reply_tags });
2211 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(false), reply_tags });
1902 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2212 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2213 same_peer_grace_until = None;
1903 }
2214 }
1904 Err(error) => {
2215 Err(error) => {
1905 timeline.record("camera offer failed", error.to_string());
2216 timeline.record("camera offer failed", error.to_string());
@@ -1924,15 +2235,63 @@ async fn drive(
1924 control.send(CallUpdate::Notice(format!("Camera could not start: {error}")));
2235 control.send(CallUpdate::Notice(format!("Camera could not start: {error}")));
1925 }
2236 }
1926 }
2237 }
2238 Some(CallCommand::SetVideoQuality(quality)) => {
2239 local_video.set_video_quality(quality);
2240 if let Err(error) = local_video.refresh_camera_capture(&camera_choice) {
2241 control.send(CallUpdate::Notice(format!("Camera could not restart: {error}")));
2242 }
2243 if video.set_video_quality(quality) {
2244 send_receive_change(control, video.reselect(&roster));
2245 }
2246 }
2247 Some(CallCommand::StartPortalShare(kind)) => {
2248 let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;
2249 if !remote_set {
2250 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
2251 } else if local_hold {
2252 control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into()));
2253 } else if direct && !local_video.sharing() && (same_peer.is_some() || glare_resend.is_some()) {
2254 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
2255 } else if direct
2256 && !local_video.sharing()
2257 && !local_video.has_share_line()
2258 && let Err(error) = attach_share_line(&current.peer, &factory, &mut local_video, direct_video_mid.as_deref())
2259 {
2260 control.send(CallUpdate::Notice(format!("Sharing could not start: {error}")));
2261 } else if !local_video.sharing() && !video_possible(remote_set, layout, negotiator.path()) {
2262 if next.is_none() && negotiator.begin_conference_upgrade() {
2263 let pending = escalate(&factory, &grant, options, outgoing_track(software_audio.as_ref(), &track), &remote, &links, &media_leg_id, &media_links, &mut negotiator, live, timeline).await;
2264 next = pending.or(next);
2265 }
2266 if next.is_some() {
2267 portal_pending = Some(kind);
2268 control.send(CallUpdate::Notice(SHARE_QUEUED_NOTICE.into()));
2269 } else {
2270 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
2271 }
2272 } else if let Err(error) = local_video.open_portal(kind, control.command_sender()) {
2273 control.send(CallUpdate::Notice(format!("Sharing could not start: {error}")));
2274 }
2275 }
2276 Some(CallCommand::FinishPortalShare { source, generation }) => {
2277 if local_video.accept_portal(generation) {
2278 control.defer(CallCommand::StartShare(source));
2279 }
2280 }
2281 Some(CallCommand::AbandonPortalShare) => {
2282 if local_video.portal_is_open() {
2283 local_video.stop_share();
2284 }
2285 }
1927 Some(CallCommand::StartShare(source)) => {
2286 Some(CallCommand::StartShare(source)) => {
1928 let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;
2287 let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;
1929 if !remote_set {
2288 if !remote_set {
1930 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
2289 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
1931 } else if local_hold {
2290 } else if local_hold {
1932 control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into()));
2291 control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into()));
1933 } else if direct && local_video.sharing() {
2292 } else if direct && local_video.share_sending() {
1934 match local_video.start_share(&source) {
2293 match local_video.start_share(&source) {
1935 Ok(()) => control.send(CallUpdate::LocalShare(Some(source.label()))),
2294 Ok(()) => announce_share(control, &source),
1936 Err(error) => control.send(CallUpdate::Notice(format!("Sharing could not start: {error}"))),
2295 Err(error) => control.send(CallUpdate::Notice(format!("Sharing could not start: {error}"))),
1937 }
2296 }
1938 } else if direct && (same_peer.is_some() || glare_resend.is_some()) {
2297 } else if direct && (same_peer.is_some() || glare_resend.is_some()) {
@@ -1945,13 +2304,14 @@ async fn drive(
1945 } else if direct {
2304 } else if direct {
1946 match local_video.start_share(&source) {
2305 match local_video.start_share(&source) {
1947 Ok(()) => {
2306 Ok(()) => {
1948 control.send(CallUpdate::LocalShare(Some(source.label())));
2307 announce_share(control, &source);
1949 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
2308 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1950 match offer_same_peer(&current.peer, &current.gathered, local_video.share_mid(), &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), false, local_video.camera_on(), true, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
2309 match offer_same_peer(&current.peer, &current.gathered, local_video.share_mid(), &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), false, local_video.camera_on(), true, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
1951 Ok((browser_offer, signaled, reply_tags)) => {
2310 Ok((browser_offer, signaled, reply_tags)) => {
1952 timeline.record_sdp("local offer", &signaled.sdp);
2311 timeline.record_sdp("local offer", &signaled.sdp);
1953 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(true), reply_tags });
2312 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(true), reply_tags });
1954 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2313 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2314 same_peer_grace_until = None;
1955 }
2315 }
1956 Err(error) => {
2316 Err(error) => {
1957 timeline.record("share offer failed", error.to_string());
2317 timeline.record("share offer failed", error.to_string());
@@ -1975,7 +2335,7 @@ async fn drive(
1975 } else {
2335 } else {
1976 match local_video.start_share(&source) {
2336 match local_video.start_share(&source) {
1977 Ok(()) => {
2337 Ok(()) => {
1978 control.send(CallUpdate::LocalShare(Some(source.label())));
2338 announce_share(control, &source);
1979 tell_media_descriptions(&remote, &media_links, MediaDescription::share(true), &mut media_description_request, timeline);
2339 tell_media_descriptions(&remote, &media_links, MediaDescription::share(true), &mut media_description_request, timeline);
1980 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
2340 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1981 }
2341 }
@@ -1986,24 +2346,28 @@ async fn drive(
1986 Some(CallCommand::StopShare) => {
2346 Some(CallCommand::StopShare) => {
1987 let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;
2347 let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;
1988 share_pending = None;
2348 share_pending = None;
1989 if direct && local_video.sharing() && (same_peer.is_some() || glare_resend.is_some()) {
2349 portal_pending = None;
2350 if local_video.portal_is_open() {
2351 local_video.stop_share();
2352 } else if direct && local_video.sharing() && (same_peer.is_some() || glare_resend.is_some()) {
1990 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
2353 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
1991 } else if direct && local_video.sharing() {
2354 } else if direct && local_video.sharing() {
1992 local_video.stop_share();
2355 local_video.stop_share();
1993 control.send(CallUpdate::LocalShare(None));
2356 clear_share(control);
1994 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
2357 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1995 match offer_same_peer(&current.peer, &current.gathered, local_video.share_mid(), &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), local_hold, local_video.camera_on(), false, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
2358 match offer_same_peer(&current.peer, &current.gathered, local_video.share_mid(), &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), local_hold, local_video.camera_on(), false, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
1996 Ok((browser_offer, signaled, reply_tags)) => {
2359 Ok((browser_offer, signaled, reply_tags)) => {
1997 timeline.record_sdp("local offer", &signaled.sdp);
2360 timeline.record_sdp("local offer", &signaled.sdp);
1998 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(false), reply_tags });
2361 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(false), reply_tags });
1999 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2362 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2363 same_peer_grace_until = None;
2000 }
2364 }
2001 Err(error) => timeline.record("share offer failed", error.to_string()),
2365 Err(error) => timeline.record("share offer failed", error.to_string()),
2002 }
2366 }
2003 } else if local_video.sharing() {
2367 } else if local_video.sharing() {
2004 local_video.stop_share();
2368 local_video.stop_share();
2005 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
2369 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
2006 control.send(CallUpdate::LocalShare(None));
2370 clear_share(control);
2007 tell_media_descriptions(&remote, &media_links, MediaDescription::share(false), &mut media_description_request, timeline);
2371 tell_media_descriptions(&remote, &media_links, MediaDescription::share(false), &mut media_description_request, timeline);
2008 }
2372 }
2009 }
2373 }
@@ -2225,6 +2589,7 @@ async fn drive(
2225 timeline.record_sdp("local offer", &signaled.sdp);
2589 timeline.record_sdp("local offer", &signaled.sdp);
2226 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Hold(hold), reply_tags });
2590 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Hold(hold), reply_tags });
2227 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2591 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2592 same_peer_grace_until = None;
2228 }
2593 }
2229 Err(error) => {
2594 Err(error) => {
2230 timeline.record("hold failed", error.to_string());
2595 timeline.record("hold failed", error.to_string());
@@ -2341,7 +2706,8 @@ async fn drive(
2341 if layout == Layout::Conference
2706 if layout == Layout::Conference
2342 && let Some(size) = local_video.camera_size()
2707 && let Some(size) = local_video.camera_size()
2343 && let Some(url) = media_links.get("applyChannelParameters").cloned()
2708 && let Some(url) = media_links.get("applyChannelParameters").cloned()
2344 && let Some(body) = send_capabilities.body_for(size)
2709 && let Some(body) =
2710 send_capabilities.body_for(size, local_video.video_quality())
2345 {
2711 {
2346 let signaling = signaling.clone();
2712 let signaling = signaling.clone();
2347 let timeline = timeline.clone();
2713 let timeline = timeline.clone();
@@ -2437,12 +2803,13 @@ async fn drive(
2437 timeline.record(
2803 timeline.record(
2438 "stats",
2804 "stats",
2439 format!(
2805 format!(
2440 "in packets={} bytes={} level={:.3} rms={decoded_rms:.3} tone={ratio:.2} out packets={} mic={:.3} erle={:.1} dtls={} video in packets={} decoded={} {}x{} out packets={} encoded={} {}x{} mixer reports {} (rtt {:.0} ms) out bytes={} sources={:?} video senders={:?}{}",
2806 "in packets={} bytes={} level={:.3} rms={decoded_rms:.3} tone={ratio:.2} out packets={} mic={:.3} erle={:.1} dtls={} video in packets={} decoded={} {}x{} out packets={} encoded={} {}x{} mixer reports {} (rtt {:.0} ms) out bytes={} sources={:?} video senders={:?}{}{}",
2441 snapshot.inbound_packets, snapshot.inbound_bytes, snapshot.audio_level, snapshot.outbound_packets, snapshot.local_level, snapshot.echo_return_loss_enhancement, snapshot.dtls_state,
2807 snapshot.inbound_packets, snapshot.inbound_bytes, snapshot.audio_level, snapshot.outbound_packets, snapshot.local_level, snapshot.echo_return_loss_enhancement, snapshot.dtls_state,
2442 snapshot.video.inbound_packets, snapshot.video.inbound_frames_decoded, snapshot.video.inbound_width, snapshot.video.inbound_height,
2808 snapshot.video.inbound_packets, snapshot.video.inbound_frames_decoded, snapshot.video.inbound_width, snapshot.video.inbound_height,
2443 snapshot.video.outbound_packets, snapshot.video.outbound_frames_encoded, snapshot.video.outbound_width, snapshot.video.outbound_height,
2809 snapshot.video.outbound_packets, snapshot.video.outbound_frames_encoded, snapshot.video.outbound_width, snapshot.video.outbound_height,
2444 snapshot.video.remote_reports, snapshot.video.remote_round_trip_ms, snapshot.outbound_bytes, snapshot.source_levels, snapshot.video_senders,
2810 snapshot.video.remote_reports, snapshot.video.remote_round_trip_ms, snapshot.outbound_bytes, snapshot.source_levels, snapshot.video_senders,
2445 snapshot.share_receive.as_ref().filter(|_| snapshot.share_inbound_packets > 0).map(ShareReceive::summary).unwrap_or_default()
2811 snapshot.share_receive.as_ref().filter(|_| snapshot.share_inbound_packets > 0).map(ShareReceive::summary).unwrap_or_default(),
2812 local_video.camera_capture_summary().unwrap_or_default()
2446 ),
2813 ),
2447 );
2814 );
2448 }
2815 }
@@ -2487,6 +2854,7 @@ async fn drive(
2487 control.send(CallUpdate::Camera(false));
2854 control.send(CallUpdate::Camera(false));
2488 }
2855 }
2489 share_pending = None;
2856 share_pending = None;
2857 portal_pending = None;
2490 settle_failed_escalation(pending.offered.is_none(), layout, &mut negotiator, &mut deferred_changes, &mut local_video, control);
2858 settle_failed_escalation(pending.offered.is_none(), layout, &mut negotiator, &mut deferred_changes, &mut local_video, control);
2491 timeline.record("escalation failed", "no answer for the new peer connection in time");
2859 timeline.record("escalation failed", "no answer for the new peer connection in time");
2492 control.send(CallUpdate::Notice(VIDEO_FAILED_NOTICE.into()));
2860 control.send(CallUpdate::Notice(VIDEO_FAILED_NOTICE.into()));
@@ -2517,6 +2885,7 @@ async fn drive(
2517 timeline.record_sdp("local offer", &signaled.sdp);
2885 timeline.record_sdp("local offer", &signaled.sdp);
2518 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: resend.change, reply_tags });
2886 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: resend.change, reply_tags });
2519 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2887 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2888 same_peer_grace_until = None;
2520 }
2889 }
2521 Err(error) => {
2890 Err(error) => {
2522 timeline.record("offer after glare failed", error.to_string());
2891 timeline.record("offer after glare failed", error.to_string());
@@ -2527,6 +2896,16 @@ async fn drive(
2527 }
2896 }
2528 _ = sleep_until(same_peer_deadline.unwrap_or_else(far_future)), if same_peer_deadline.is_some() => {
2897 _ = sleep_until(same_peer_deadline.unwrap_or_else(far_future)), if same_peer_deadline.is_some() => {
2529 same_peer_deadline = None;
2898 same_peer_deadline = None;
2899 if same_peer.is_some() {
2900 same_peer_grace_until = Some(Instant::now() + SAME_PEER_LATE_GRACE);
2901 timeline.record(
2902 "same-peer offer",
2903 "no answer yet, waiting a little longer",
2904 );
2905 }
2906 }
2907 _ = sleep_until(same_peer_grace_until.unwrap_or_else(far_future)), if same_peer_grace_until.is_some() => {
2908 same_peer_grace_until = None;
2530 if let Some(pending) = same_peer.take() {
2909 if let Some(pending) = same_peer.take() {
2531 timeline.record("same-peer offer", "no answer in time");
2910 timeline.record("same-peer offer", "no answer in time");
2532 negotiator.same_peer_offer_failed();
2911 negotiator.same_peer_offer_failed();
@@ -2554,6 +2933,10 @@ async fn drive(
2554 }
2933 }
2555 }
2934 }
2556 }
2935 }
2936 if software_audio.is_some() {
2937 timeline.record("software audio", "stopping before tear down");
2938 drop(software_audio);
2939 }
2557 live.callbacks = Some(callbacks);
2940 live.callbacks = Some(callbacks);
2558 Ok(())
2941 Ok(())
2559}
2942}
@@ -2574,9 +2957,20 @@ async fn start_escalation(
2574 .ok_or_else(|| Error::Signaling("acceptance without a mediaRenegotiation link".into()))?;
2957 .ok_or_else(|| Error::Signaling("acceptance without a mediaRenegotiation link".into()))?;
2575 let session = open_peer(factory, grant, &options.relay_host, false)?;
2958 let session = open_peer(factory, grant, &options.relay_host, false)?;
2576 let media = create_offer(&session.peer, factory, track, Layout::Conference, None).await?;
2959 let media = create_offer(&session.peer, factory, track, Layout::Conference, None).await?;
2577 let body = renegotiation_body(&remote.participant, links, &media.signaled.sdp, media_leg_id, &media.modalities, true, false);
2960 let body = renegotiation_body(
2961 &remote.participant,
2962 links,
2963 &media.signaled.sdp,
2964 media_leg_id,
2965 &media.modalities,
2966 true,
2967 false,
2968 );
2578 let reply_tags = offer_reply_tags(&body);
2969 let reply_tags = offer_reply_tags(&body);
2579 remote.signaling.post_json("POST mediaRenegotiation", url, body).await?;
2970 remote
2971 .signaling
2972 .post_json("POST mediaRenegotiation", url, body)
2973 .await?;
2580 Ok(NextPeer {
2974 Ok(NextPeer {
2581 session,
2975 session,
2582 offered: Some(media),
2976 offered: Some(media),
@@ -2637,7 +3031,16 @@ async fn answer_on_new_peer(
2637 teams_offer: &str,
3031 teams_offer: &str,
2638) -> Result<(PeerSession, AnsweredMedia)> {
3032) -> Result<(PeerSession, AnsweredMedia)> {
2639 let session = open_peer(factory, grant, &options.relay_host, false)?;
3033 let session = open_peer(factory, grant, &options.relay_host, false)?;
2640 let answered = answer_offer(&session.peer, Some(track), teams_offer, AnswerVideo::Reject, None, false, None).await?;
3034 let answered = answer_offer(
3035 &session.peer,
3036 Some(track),
3037 teams_offer,
3038 AnswerVideo::Reject,
3039 None,
3040 false,
3041 None,
3042 )
3043 .await?;
2641 Ok((session, answered))
3044 Ok((session, answered))
2642}
3045}
2643
3046
@@ -2651,8 +3054,16 @@ async fn send_media_answer(
2651 let url = reply_links
3054 let url = reply_links
2652 .get("mediaAnswer")
3055 .get("mediaAnswer")
2653 .ok_or_else(|| Error::Signaling("renegotiation without a mediaAnswer link".into()))?;
3056 .ok_or_else(|| Error::Signaling("renegotiation without a mediaAnswer link".into()))?;
2654 let body = escalation_answer_body(&remote.participant, links, &answered.answer_sdp, media_leg_id);
3057 let body = escalation_answer_body(
2655 remote.signaling.post_json("POST mediaAnswer", url, body).await
3058 &remote.participant,
3059 links,
3060 &answered.answer_sdp,
3061 media_leg_id,
3062 );
3063 remote
3064 .signaling
3065 .post_json("POST mediaAnswer", url, body)
3066 .await
2656}
3067}
2657
3068
2658#[allow(clippy::too_many_arguments)]
3069#[allow(clippy::too_many_arguments)]
@@ -2675,7 +3086,9 @@ fn negotiate_video(
2675 }
3086 }
2676 };
3087 };
2677 let table = SlotTable::from_streams(&streams);
3088 let table = SlotTable::from_streams(&streams);
2678 let link = links.get("applyChannelParameters").or_else(|| links.get("controlVideoStreaming"));
3089 let link = links
3090 .get("applyChannelParameters")
3091 .or_else(|| links.get("controlVideoStreaming"));
2679 timeline.record(
3092 timeline.record(
2680 "video slots",
3093 "video slots",
2681 format!(
3094 format!(
@@ -2685,9 +3098,15 @@ fn negotiate_video(
2685 link.is_some()
3098 link.is_some()
2686 ),
3099 ),
2687 );
3100 );
2688 let requester = link
3101 let requester = link.filter(|_| from_mixer).map(|url| {
2689 .filter(|_| from_mixer)
3102 SourceRequester::start(
2690 .map(|url| SourceRequester::start(signaling.clone(), url.clone(), video.router().clone(), control.video.clone(), timeline.clone()));
3103 signaling.clone(),
3104 url.clone(),
3105 video.router().clone(),
3106 control.video.clone(),
3107 timeline.clone(),
3108 )
3109 });
2691 video.negotiated(table, requester);
3110 video.negotiated(table, requester);
2692 send_receive_change(control, video.reselect(roster));
3111 send_receive_change(control, video.reselect(roster));
2693}
3112}
@@ -2701,17 +3120,33 @@ const SHARE_REFUSED_NOTICE: &str = "The other side did not accept the screen sha
2701
3120
2702async fn camera_devices(mode: VideoMode) -> Vec<CameraDevice> {
3121async fn camera_devices(mode: VideoMode) -> Vec<CameraDevice> {
2703 match mode {
3122 match mode {
2704 VideoMode::Pattern => vec![CameraDevice { key: "pattern".into(), name: "Test pattern".into() }],
3123 VideoMode::Pattern => vec![CameraDevice {
3124 key: "pattern".into(),
3125 name: "Test pattern".into(),
3126 }],
2705 VideoMode::Off => Vec::new(),
3127 VideoMode::Off => Vec::new(),
2706 VideoMode::Platform => tokio::task::spawn_blocking(list_cameras).await.unwrap_or_default(),
3128 VideoMode::Platform => tokio::task::spawn_blocking(list_cameras)
3129 .await
3130 .unwrap_or_default(),
2707 }
3131 }
2708}
3132}
2709
3133
2710fn refresh_cameras(updates: mpsc::UnboundedSender<CallUpdate>, mode: VideoMode, timeline: Timeline) {
3134fn refresh_cameras(
3135 updates: mpsc::UnboundedSender<CallUpdate>,
3136 mode: VideoMode,
3137 timeline: Timeline,
3138) {
2711 tokio::spawn(async move {
3139 tokio::spawn(async move {
2712 let started = Instant::now();
3140 let started = Instant::now();
2713 let cameras = camera_devices(mode).await;
3141 let cameras = camera_devices(mode).await;
2714 timeline.record("camera list", format!("{} camera(s) in {} ms", cameras.len(), started.elapsed().as_millis()));
3142 timeline.record(
3143 "camera list",
3144 format!(
3145 "{} camera(s) in {} ms",
3146 cameras.len(),
3147 started.elapsed().as_millis()
3148 ),
3149 );
2715 let _ = updates.send(CallUpdate::Cameras(cameras));
3150 let _ = updates.send(CallUpdate::Cameras(cameras));
2716 });
3151 });
2717}
3152}
@@ -2720,37 +3155,85 @@ const SHARE_THUMBNAIL_WINDOWS: usize = 12;
2720const SHARE_THUMBNAIL_WIDTH: u32 = 320;
3155const SHARE_THUMBNAIL_WIDTH: u32 = 320;
2721const SHARE_THUMBNAIL_HEIGHT: u32 = 180;
3156const SHARE_THUMBNAIL_HEIGHT: u32 = 180;
2722
3157
2723fn refresh_share_sources(updates: mpsc::UnboundedSender<CallUpdate>, mode: VideoMode, with_thumbnails: bool) {
3158fn announce_share(control: &CallControl, source: &ShareSource) {
3159 control.send(CallUpdate::ShareKind(Some(source.kind)));
3160 control.send(CallUpdate::LocalShare(Some(source.label())));
3161}
3162
3163fn clear_share(control: &CallControl) {
3164 control.send(CallUpdate::ShareKind(None));
3165 control.send(CallUpdate::LocalShare(None));
3166}
3167
3168fn refresh_share_sources(
3169 updates: mpsc::UnboundedSender<CallUpdate>,
3170 mode: VideoMode,
3171 with_thumbnails: bool,
3172) {
2724 tokio::spawn(async move {
3173 tokio::spawn(async move {
3174 let picker = current_share_picker();
2725 let sources = match mode {
3175 let sources = match mode {
2726 VideoMode::Pattern => vec![
3176 VideoMode::Pattern => vec![
2727 ShareSource { id: 1, kind: ShareKind::Screen, title: "Test screen".into() },
3177 ShareSource {
2728 ShareSource { id: 2, kind: ShareKind::Window, title: "Test window".into() },
3178 id: 1,
3179 kind: ShareKind::Screen,
3180 title: "Test screen".into(),
3181 },
3182 ShareSource {
3183 id: 2,
3184 kind: ShareKind::Window,
3185 title: "Test window".into(),
3186 },
2729 ],
3187 ],
2730 VideoMode::Off => Vec::new(),
3188 VideoMode::Off => Vec::new(),
2731 VideoMode::Platform => tokio::task::spawn_blocking(list_share_sources).await.unwrap_or_default(),
3189 VideoMode::Platform if picker == SharePicker::Portal => Vec::new(),
3190 VideoMode::Platform => tokio::task::spawn_blocking(list_share_sources)
3191 .await
3192 .unwrap_or_default(),
2732 };
3193 };
3194 let sources = share_sources_for_menu(picker, sources);
2733 let _ = updates.send(CallUpdate::ShareSources(sources.clone()));
3195 let _ = updates.send(CallUpdate::ShareSources(sources.clone()));
2734 if !with_thumbnails {
3196 if picker == SharePicker::Portal || !with_thumbnails {
2735 return;
3197 return;
2736 }
3198 }
2737 let wanted: Vec<ShareSource> = sources
3199 let wanted: Vec<ShareSource> = sources
2738 .iter()
3200 .iter()
2739 .filter(|source| source.kind == ShareKind::Screen)
3201 .filter(|source| source.kind == ShareKind::Screen)
2740 .chain(sources.iter().filter(|source| source.kind == ShareKind::Window).take(SHARE_THUMBNAIL_WINDOWS))
3202 .chain(
3203 sources
3204 .iter()
3205 .filter(|source| source.kind == ShareKind::Window)
3206 .take(SHARE_THUMBNAIL_WINDOWS),
3207 )
2741 .cloned()
3208 .cloned()
2742 .collect();
3209 .collect();
2743 for source in wanted {
3210 for source in wanted {
2744 let picture = match mode {
3211 let picture = match mode {
2745 VideoMode::Platform => {
3212 VideoMode::Platform => {
2746 let wanted = source.clone();
3213 let wanted = source.clone();
2747 tokio::task::spawn_blocking(move || share_thumbnail(&wanted, SHARE_THUMBNAIL_WIDTH, SHARE_THUMBNAIL_HEIGHT)).await.ok().flatten()
3214 tokio::task::spawn_blocking(move || {
3215 share_thumbnail(&wanted, SHARE_THUMBNAIL_WIDTH, SHARE_THUMBNAIL_HEIGHT)
3216 })
3217 .await
3218 .ok()
3219 .flatten()
2748 }
3220 }
2749 VideoMode::Pattern => Some(VideoPicture::solid(SHARE_THUMBNAIL_WIDTH, SHARE_THUMBNAIL_HEIGHT, 120, 80, 40)),
3221 VideoMode::Pattern => Some(VideoPicture::solid(
3222 SHARE_THUMBNAIL_WIDTH,
3223 SHARE_THUMBNAIL_HEIGHT,
3224 120,
3225 80,
3226 40,
3227 )),
2750 VideoMode::Off => None,
3228 VideoMode::Off => None,
2751 };
3229 };
2752 if let Some(picture) = picture
3230 if let Some(picture) = picture
2753 && updates.send(CallUpdate::ShareThumbnail { source, picture: Arc::new(picture) }).is_err()
3231 && updates
3232 .send(CallUpdate::ShareThumbnail {
3233 source,
3234 picture: Arc::new(picture),
3235 })
3236 .is_err()
2754 {
3237 {
2755 return;
3238 return;
2756 }
3239 }
@@ -2774,8 +3257,14 @@ fn tell_media_descriptions(
2774 let signaling = remote.signaling.clone();
3257 let signaling = remote.signaling.clone();
2775 let timeline = timeline.clone();
3258 let timeline = timeline.clone();
2776 tokio::spawn(async move {
3259 tokio::spawn(async move {
2777 let sent = format!("{} {} request {request_id}", description.mid, description.direction);
3260 let sent = format!(
2778 if let Err(error) = signaling.update_media_descriptions(&url, &[description], request_id).await {
3261 "{} {} request {request_id}",
3262 description.mid, description.direction
3263 );
3264 if let Err(error) = signaling
3265 .update_media_descriptions(&url, &[description], request_id)
3266 .await
3267 {
2779 timeline.record("updateMediaDescriptions failed", format!("{sent}: {error}"));
3268 timeline.record("updateMediaDescriptions failed", format!("{sent}: {error}"));
2780 }
3269 }
2781 });
3270 });
@@ -2785,30 +3274,54 @@ fn is_own_meeting(own: Option<&MeetingTarget>, target: &MeetingTarget) -> bool {
2785 own.is_some_and(|own| own.thread_id == target.thread_id)
3274 own.is_some_and(|own| own.thread_id == target.thread_id)
2786}
3275}
2787
3276
2788fn attach_share_line(peer: &PeerConnection, factory: &PeerConnectionFactory, local_video: &mut LocalVideo, camera_mid: Option<&str>) -> Result<()> {
3277fn attach_share_line(
3278 peer: &PeerConnection,
3279 factory: &PeerConnectionFactory,
3280 local_video: &mut LocalVideo,
3281 camera_mid: Option<&str>,
3282) -> Result<()> {
2789 let camera = camera_mid.and_then(|mid| peer_transceiver(peer, mid));
3283 let camera = camera_mid.and_then(|mid| peer_transceiver(peer, mid));
2790 if !local_video.has_lines() && camera.is_none() {
3284 if !local_video.has_lines() && camera.is_none() {
2791 return Err(Error::Webrtc("no video line negotiated".into()));
3285 return Err(Error::Webrtc("no video line negotiated".into()));
2792 }
3286 }
2793 let share = add_share_line(peer, factory)?;
3287 let share = add_share_line(peer, factory)?;
2794 local_video.add_share_line(share.clone(), camera).inspect_err(|_| {
3288 local_video
2795 let _ = share.stop();
3289 .add_share_line(share.clone(), camera)
2796 })
3290 .inspect_err(|_| {
3291 let _ = share.stop();
3292 })
2797}
3293}
2798
3294
2799fn peer_transceiver(peer: &PeerConnection, mid: &str) -> Option<RtpTransceiver> {
3295fn peer_transceiver(peer: &PeerConnection, mid: &str) -> Option<RtpTransceiver> {
2800 peer.transceivers().into_iter().find(|transceiver| transceiver.mid().as_deref() == Some(mid))
3296 peer.transceivers()
3297 .into_iter()
3298 .find(|transceiver| transceiver.mid().as_deref() == Some(mid))
2801}
3299}
2802
3300
2803fn start_camera_line(local_video: &mut LocalVideo, peer: &PeerConnection, direct_mid: Option<&str>, choice: &DeviceChoice) -> Result<()> {
3301fn start_camera_line(
3302 local_video: &mut LocalVideo,
3303 peer: &PeerConnection,
3304 direct_mid: Option<&str>,
3305 choice: &DeviceChoice,
3306) -> Result<()> {
2804 if !local_video.has_lines() {
3307 if !local_video.has_lines() {
2805 let mid = direct_mid.ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?;
3308 let mid = direct_mid.ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?;
2806 let camera = peer_transceiver(peer, mid).ok_or_else(|| Error::Webrtc("no transceiver for the camera line".into()))?;
3309 let camera = peer_transceiver(peer, mid)
2807 if !matches!(camera.direction(), RtpTransceiverDirection::SendRecv | RtpTransceiverDirection::SendOnly) {
3310 .ok_or_else(|| Error::Webrtc("no transceiver for the camera line".into()))?;
2808 peer.add_track(MediaStreamTrack::Video(local_video.camera_track()), &[CAMERA_STREAM])
3311 if !matches!(
2809 .map_err(|error| Error::Webrtc(error.to_string()))?;
3312 camera.direction(),
3313 RtpTransceiverDirection::SendRecv | RtpTransceiverDirection::SendOnly
3314 ) {
3315 peer.add_track(
3316 MediaStreamTrack::Video(local_video.camera_track()),
3317 &[CAMERA_STREAM],
3318 )
3319 .map_err(|error| Error::Webrtc(error.to_string()))?;
2810 }
3320 }
2811 local_video.set_lines(VideoLines { camera, share: None })?;
3321 local_video.set_lines(VideoLines {
3322 camera,
3323 share: None,
3324 })?;
2812 }
3325 }
2813 local_video.start_camera(choice)
3326 local_video.start_camera(choice)
2814}
3327}
@@ -2836,9 +3349,22 @@ async fn offer_same_peer(
2836 .cloned()
3349 .cloned()
2837 .ok_or_else(|| Error::Signaling("this call has no mediaRenegotiation link".into()))?;
3350 .ok_or_else(|| Error::Signaling("this call has no mediaRenegotiation link".into()))?;
2838 if !negotiator.begin_same_peer_offer() {
3351 if !negotiator.begin_same_peer_offer() {
2839 return Err(Error::Signaling("another media negotiation is running".into()));
3352 return Err(Error::Signaling(
3353 "another media negotiation is running".into(),
3354 ));
2840 }
3355 }
2841 let offered = build_same_peer_offer(peer, plan, layout, hold, camera, share, camera_mid, own_share_mid, direct.then_some(gathered)).await;
3356 let offered = build_same_peer_offer(
3357 peer,
3358 plan,
3359 layout,
3360 hold,
3361 camera,
3362 share,
3363 camera_mid,
3364 own_share_mid,
3365 direct.then_some(gathered),
3366 )
3367 .await;
2842 let (text, signaled) = match offered {
3368 let (text, signaled) = match offered {
2843 Ok(offered) => offered,
3369 Ok(offered) => offered,
2844 Err(error) => {
3370 Err(error) => {
@@ -2846,10 +3372,25 @@ async fn offer_same_peer(
2846 return Err(error);
3372 return Err(error);
2847 }
3373 }
2848 };
3374 };
2849 let modalities = offer_modalities(layout == Layout::OneToOne && camera && !hold, share && !hold);
3375 let modalities = offer_modalities(
2850 let body = renegotiation_body(&remote.participant, links, &signaled.sdp, media_leg_id, &modalities, false, direct);
3376 layout == Layout::OneToOne && camera && !hold,
3377 share && !hold,
3378 );
3379 let body = renegotiation_body(
3380 &remote.participant,
3381 links,
3382 &signaled.sdp,
3383 media_leg_id,
3384 &modalities,
3385 false,
3386 direct,
3387 );
2851 let reply_tags = offer_reply_tags(&body);
3388 let reply_tags = offer_reply_tags(&body);
2852 if let Err(error) = remote.signaling.post_json("POST mediaRenegotiation (same peer)", &url, body).await {
3389 if let Err(error) = remote
3390 .signaling
3391 .post_json("POST mediaRenegotiation (same peer)", &url, body)
3392 .await
3393 {
2853 negotiator.same_peer_offer_failed();
3394 negotiator.same_peer_offer_failed();
2854 rollback_offer(peer).await;
3395 rollback_offer(peer).await;
2855 return Err(error);
3396 return Err(error);
@@ -2858,9 +3399,23 @@ async fn offer_same_peer(
2858}
3399}
2859
3400
2860#[allow(clippy::too_many_arguments)]
3401#[allow(clippy::too_many_arguments)]
2861async fn build_same_peer_offer(peer: &PeerConnection, plan: &OfferPlan, layout: Layout, hold: bool, camera: bool, share: bool, camera_mid: &str, own_share_mid: Option<String>, gathered: Option<&Gathered>) -> Result<(String, SignaledOffer)> {
3402async fn build_same_peer_offer(
3403 peer: &PeerConnection,
3404 plan: &OfferPlan,
3405 layout: Layout,
3406 hold: bool,
3407 camera: bool,
3408 share: bool,
3409 camera_mid: &str,
3410 own_share_mid: Option<String>,
3411 gathered: Option<&Gathered>,
3412) -> Result<(String, SignaledOffer)> {
2862 let offer = peer
3413 let offer = peer
2863 .create_offer(OfferOptions { offer_to_receive_audio: true, offer_to_receive_video: true, ..OfferOptions::default() })
3414 .create_offer(OfferOptions {
3415 offer_to_receive_audio: true,
3416 offer_to_receive_video: true,
3417 ..OfferOptions::default()
3418 })
2864 .await
3419 .await
2865 .map_err(|error| Error::Webrtc(error.to_string()))?;
3420 .map_err(|error| Error::Webrtc(error.to_string()))?;
2866 let offer_text = offer.to_string();
3421 let offer_text = offer.to_string();
@@ -2870,25 +3425,56 @@ async fn build_same_peer_offer(peer: &PeerConnection, plan: &OfferPlan, layout:
2870 .and_then(|remote| direction_of(&remote.to_string(), mid))
3425 .and_then(|remote| direction_of(&remote.to_string(), mid))
2871 .is_some_and(|direction| matches!(direction.as_str(), "sendonly" | "sendrecv"))
3426 .is_some_and(|direction| matches!(direction.as_str(), "sendonly" | "sendrecv"))
2872 });
3427 });
2873 let text = directions_for(layout, false, camera, share, camera_mid, share_mid.as_deref(), remote_shares, &offer_text);
3428 let text = directions_for(
3429 layout,
3430 false,
3431 camera,
3432 share,
3433 camera_mid,
3434 share_mid.as_deref(),
3435 remote_shares,
3436 &offer_text,
3437 );
2874 let description = parse_sdp(&text, SdpType::Offer)?;
3438 let description = parse_sdp(&text, SdpType::Offer)?;
2875 peer.set_local_description(description)
3439 peer.set_local_description(description)
2876 .await
3440 .await
2877 .map_err(|error| Error::Webrtc(error.to_string()))?;
3441 .map_err(|error| Error::Webrtc(error.to_string()))?;
2878 let mut numbers = random_u32;
3442 let mut numbers = random_u32;
2879 let mut plan = plan.clone();
3443 let mut plan = plan.clone();
2880 if let Some(mid) = share_mid.as_ref().filter(|mid| !plan.screen_share_mids.contains(mid)) {
3444 if let Some(mid) = share_mid
3445 .as_ref()
3446 .filter(|mid| !plan.screen_share_mids.contains(mid))
3447 {
2881 plan.screen_share_mids.push(mid.clone());
3448 plan.screen_share_mids.push(mid.clone());
2882 }
3449 }
2883 let mut signaled = to_teams_offer(&directions_for(layout, hold, camera, share, camera_mid, share_mid.as_deref(), remote_shares, &text), &plan, &mut numbers)?;
3450 let mut signaled = to_teams_offer(
3451 &directions_for(
3452 layout,
3453 hold,
3454 camera,
3455 share,
3456 camera_mid,
3457 share_mid.as_deref(),
3458 remote_shares,
3459 &text,
3460 ),
3461 &plan,
3462 &mut numbers,
3463 )?;
2884 signaled.sdp = direct_sdp(&signaled.sdp, gathered, SdpKind::Offer).await?;
3464 signaled.sdp = direct_sdp(&signaled.sdp, gathered, SdpKind::Offer).await?;
2885 if gathered.is_some()
3465 if gathered.is_some()
2886 && let Some(role) = negotiated_setup(
3466 && let Some(role) = negotiated_setup(
2887 peer.current_local_description().map(|local| local.to_string()).as_deref(),
3467 peer.current_local_description()
2888 peer.current_remote_description().map(|remote| remote.to_string()).as_deref(),
3468 .map(|local| local.to_string())
3469 .as_deref(),
3470 peer.current_remote_description()
3471 .map(|remote| remote.to_string())
3472 .as_deref(),
2889 )
3473 )
2890 {
3474 {
2891 signaled.sdp = signaled.sdp.replace("a=setup:actpass", &format!("a=setup:{role}"));
3475 signaled.sdp = signaled
3476 .sdp
3477 .replace("a=setup:actpass", &format!("a=setup:{role}"));
2892 }
3478 }
2893 Ok((text, signaled))
3479 Ok((text, signaled))
2894}
3480}
@@ -2897,8 +3483,13 @@ async fn build_same_peer_offer(peer: &PeerConnection, plan: &OfferPlan, layout:
2897fn parse_sdp(text: &str, kind: SdpType) -> Result<SessionDescription> {
3483fn parse_sdp(text: &str, kind: SdpType) -> Result<SessionDescription> {
2898 match std::panic::catch_unwind(|| SessionDescription::parse(text, kind)) {
3484 match std::panic::catch_unwind(|| SessionDescription::parse(text, kind)) {
2899 Ok(Ok(description)) => Ok(description),
3485 Ok(Ok(description)) => Ok(description),
2900 Ok(Err(error)) => Err(Error::Sdp(format!("{kind:?} rejected: {}", error.description))),
3486 Ok(Err(error)) => Err(Error::Sdp(format!(
2901 Err(_) => Err(Error::Sdp(format!("{kind:?} rejected, libwebrtc gave no readable reason"))),
3487 "{kind:?} rejected: {}",
3488 error.description
3489 ))),
3490 Err(_) => Err(Error::Sdp(format!(
3491 "{kind:?} rejected, libwebrtc gave no readable reason"
3492 ))),
2902 }
3493 }
2903}
3494}
2904
3495
@@ -2920,7 +3511,10 @@ fn is_glare_rejection(body: &serde_json::Value) -> bool {
2920
3511
2921fn offer_reply_tags(body: &serde_json::Value) -> Vec<String> {
3512fn offer_reply_tags(body: &serde_json::Value) -> Vec<String> {
2922 let links = &body["mediaNegotiation"]["links"];
3513 let links = &body["mediaNegotiation"]["links"];
2923 ["mediaAnswer", "rejection"].iter().filter_map(|name| links[*name].as_str().and_then(callback_tag)).collect()
3514 ["mediaAnswer", "rejection"]
3515 .iter()
3516 .filter_map(|name| links[*name].as_str().and_then(callback_tag))
3517 .collect()
2924}
3518}
2925
3519
2926#[cfg(test)]
3520#[cfg(test)]
@@ -2930,9 +3524,15 @@ mod reply_tag_tests {
2930 #[test]
3524 #[test]
2931 fn answers_and_rejections_match_the_offer_by_tag() {
3525 fn answers_and_rejections_match_the_offer_by_tag() {
2932 let tags = vec!["aaaa1111".to_owned(), "bbbb2222".to_owned()];
3526 let tags = vec!["aaaa1111".to_owned(), "bbbb2222".to_owned()];
2933 assert!(answers_offer("callAgent/c/aaaa1111/call/mediaAnswer/", &tags));
3527 assert!(answers_offer(
3528 "callAgent/c/aaaa1111/call/mediaAnswer/",
3529 &tags
3530 ));
2934 assert!(answers_offer("callAgent/c/bbbb2222/call/rejection/", &tags));
3531 assert!(answers_offer("callAgent/c/bbbb2222/call/rejection/", &tags));
2935 assert!(!answers_offer("callAgent/c/cccc3333/call/mediaAnswer/", &tags));
3532 assert!(!answers_offer(
3533 "callAgent/c/cccc3333/call/mediaAnswer/",
3534 &tags
3535 ));
2936 assert!(answers_offer("callAgent/c/cccc3333/call/mediaAnswer/", &[]));
3536 assert!(answers_offer("callAgent/c/cccc3333/call/mediaAnswer/", &[]));
2937 }
3537 }
2938
3538
@@ -2941,11 +3541,19 @@ mod reply_tag_tests {
2941 let body = serde_json::json!({"mediaNegotiation": {"links": {
3541 let body = serde_json::json!({"mediaNegotiation": {"links": {
2942 "mediaAnswer": "https://t.example/callAgent/c/aaaa1111/call/mediaAnswer/",
3542 "mediaAnswer": "https://t.example/callAgent/c/aaaa1111/call/mediaAnswer/",
2943 "rejection": "https://t.example/callAgent/c/bbbb2222/call/rejection/"}}});
3543 "rejection": "https://t.example/callAgent/c/bbbb2222/call/rejection/"}}});
2944 assert_eq!(offer_reply_tags(&body), vec!["aaaa1111".to_owned(), "bbbb2222".to_owned()]);
3544 assert_eq!(
3545 offer_reply_tags(&body),
3546 vec!["aaaa1111".to_owned(), "bbbb2222".to_owned()]
3547 );
2945 }
3548 }
2946}
3549}
2947
3550
2948fn defer_to_new_peer(change: Change, deferred: &mut Vec<Change>, local_video: &mut LocalVideo, control: &CallControl) {
3551fn defer_to_new_peer(
3552 change: Change,
3553 deferred: &mut Vec<Change>,
3554 local_video: &mut LocalVideo,
3555 control: &CallControl,
3556) {
2949 match change {
3557 match change {
2950 Change::Camera(true) => {
3558 Change::Camera(true) => {
2951 control.send(CallUpdate::Camera(true));
3559 control.send(CallUpdate::Camera(true));
@@ -2957,7 +3565,14 @@ fn defer_to_new_peer(change: Change, deferred: &mut Vec<Change>, local_video: &m
2957}
3565}
2958
3566
2959/// A server escalation that fails leaves the call direct, so only what waited for the new peer is undone.
3567/// A server escalation that fails leaves the call direct, so only what waited for the new peer is undone.
2960fn settle_failed_escalation(server: bool, layout: Layout, negotiator: &mut MediaNegotiator, deferred: &mut Vec<Change>, local_video: &mut LocalVideo, control: &CallControl) {
3568fn settle_failed_escalation(
3569 server: bool,
3570 layout: Layout,
3571 negotiator: &mut MediaNegotiator,
3572 deferred: &mut Vec<Change>,
3573 local_video: &mut LocalVideo,
3574 control: &CallControl,
3575) {
2961 if server {
3576 if server {
2962 negotiator.server_escalation_failed();
3577 negotiator.server_escalation_failed();
2963 for change in deferred.drain(..) {
3578 for change in deferred.drain(..) {
@@ -2971,7 +3586,7 @@ fn settle_failed_escalation(server: bool, layout: Layout, negotiator: &mut Media
2971fn drop_local_media(local_video: &mut LocalVideo, control: &CallControl) {
3586fn drop_local_media(local_video: &mut LocalVideo, control: &CallControl) {
2972 if local_video.sharing() {
3587 if local_video.sharing() {
2973 local_video.stop_share();
3588 local_video.stop_share();
2974 control.send(CallUpdate::LocalShare(None));
3589 clear_share(control);
2975 }
3590 }
2976 if local_video.camera_on() {
3591 if local_video.camera_on() {
2977 local_video.stop_camera();
3592 local_video.stop_camera();
@@ -2988,7 +3603,7 @@ fn undo_change(change: Change, local_video: &mut LocalVideo, control: &CallContr
2988 Change::Camera(false) => control.send(CallUpdate::Camera(false)),
3603 Change::Camera(false) => control.send(CallUpdate::Camera(false)),
2989 Change::Share(true) => {
3604 Change::Share(true) => {
2990 local_video.stop_share();
3605 local_video.stop_share();
2991 control.send(CallUpdate::LocalShare(None));
3606 clear_share(control);
2992 control.send(CallUpdate::Notice("Sharing could not start".into()));
3607 control.send(CallUpdate::Notice("Sharing could not start".into()));
2993 }
3608 }
2994 Change::Share(false) => {}
3609 Change::Share(false) => {}
@@ -3004,37 +3619,65 @@ fn withhold_media(
3004 local_video: &mut LocalVideo,
3619 local_video: &mut LocalVideo,
3005 control: &CallControl,
3620 control: &CallControl,
3006) {
3621) {
3007 *muted = apply_mute(MuteCommand::Mute, *muted, audio, software_audio, remote, control);
3622 *muted = apply_mute(
3623 MuteCommand::Mute,
3624 *muted,
3625 audio,
3626 software_audio,
3627 remote,
3628 control,
3629 );
3008 if local_video.camera_on() {
3630 if local_video.camera_on() {
3009 local_video.stop_camera();
3631 local_video.stop_camera();
3010 control.send(CallUpdate::Camera(false));
3632 control.send(CallUpdate::Camera(false));
3011 }
3633 }
3012}
3634}
3013
3635
3014async fn apply_background(choice: BackgroundChoice, local_video: &LocalVideo, control: &CallControl, timeline: &Timeline) {
3636async fn apply_background(
3637 choice: BackgroundChoice,
3638 local_video: &LocalVideo,
3639 control: &CallControl,
3640 timeline: &Timeline,
3641) {
3015 match choice {
3642 match choice {
3016 BackgroundChoice::None => local_video.set_background(false, None),
3643 BackgroundChoice::None => local_video.set_background(false, None),
3017 BackgroundChoice::Blur => local_video.set_background(true, None),
3644 BackgroundChoice::Blur => local_video.set_background(true, None),
3018 BackgroundChoice::Image(path) => match tokio::task::spawn_blocking(move || BackgroundPicture::load(&path)).await {
3645 BackgroundChoice::Image(path) => {
3019 Ok(Ok(picture)) => local_video.set_background(true, Some(Arc::new(picture))),
3646 match tokio::task::spawn_blocking(move || BackgroundPicture::load(&path)).await {
3020 Ok(Err(error)) => {
3647 Ok(Ok(picture)) => local_video.set_background(true, Some(Arc::new(picture))),
3021 timeline.record("background image failed", error.to_string());
3648 Ok(Err(error)) => {
3022 control.send(CallUpdate::Notice("That background image could not be used".into()));
3649 timeline.record("background image failed", error.to_string());
3650 control.send(CallUpdate::Notice(
3651 "That background image could not be used".into(),
3652 ));
3653 }
3654 Err(_) => {}
3023 }
3655 }
3024 Err(_) => {}
3656 }
3025 },
3026 }
3657 }
3027}
3658}
3028
3659
3029async fn save_meeting_options(session: &session::Session, target: &MeetingTarget, writes: &[OptionWrite]) -> std::result::Result<meeting_options::MeetingOptions, String> {
3660async fn save_meeting_options(
3661 session: &session::Session,
3662 target: &MeetingTarget,
3663 writes: &[OptionWrite],
3664) -> std::result::Result<meeting_options::MeetingOptions, String> {
3030 for change in writes {
3665 for change in writes {
3031 meeting_options::write(session, target, change).await.map_err(|error| error.to_string())?;
3666 meeting_options::write(session, target, change)
3667 .await
3668 .map_err(|error| error.to_string())?;
3032 }
3669 }
3033 meeting_options::fetch(session, target).await.map_err(|error| error.to_string())
3670 meeting_options::fetch(session, target)
3671 .await
3672 .map_err(|error| error.to_string())
3034}
3673}
3035
3674
3036fn target_of<'a>(roster: &'a Roster, mri: &'a str) -> Target<'a> {
3675fn target_of<'a>(roster: &'a Roster, mri: &'a str) -> Target<'a> {
3037 let display_name = roster.members().iter().find(|member| member.mri == mri).map_or("", |member| member.display_name.as_str());
3676 let display_name = roster
3677 .members()
3678 .iter()
3679 .find(|member| member.mri == mri)
3680 .map_or("", |member| member.display_name.as_str());
3038 Target { mri, display_name }
3681 Target { mri, display_name }
3039}
3682}
3040
3683
@@ -3046,17 +3689,29 @@ fn recorder_busy(error: &Error) -> bool {
3046 matches!(error, Error::Signaling(reason) if reason.contains("HTTP 409"))
3689 matches!(error, Error::Signaling(reason) if reason.contains("HTTP 409"))
3047}
3690}
3048
3691
3049fn report_organizer_result(result: Result<u16>, label: &str, notice: &str, control: &CallControl, timeline: &Timeline) {
3692fn report_organizer_result(
3693 result: Result<u16>,
3694 label: &str,
3695 notice: &str,
3696 control: &CallControl,
3697 timeline: &Timeline,
3698) {
3050 if let Err(error) = &result {
3699 if let Err(error) = &result {
3051 timeline.record(format!("{label} failed"), error.to_string());
3700 timeline.record(format!("{label} failed"), error.to_string());
3052 control.send(CallUpdate::Notice(notice.into()));
3701 control.send(CallUpdate::Notice(notice.into()));
3053 }
3702 }
3054 control.send(CallUpdate::Organizer { action: label.to_owned(), outcome: result.map_err(|error| error.to_string()) });
3703 control.send(CallUpdate::Organizer {
3704 action: label.to_owned(),
3705 outcome: result.map_err(|error| error.to_string()),
3706 });
3055}
3707}
3056
3708
3057fn named_caption(mut entry: CaptionEntry, roster: &Roster) -> CaptionEntry {
3709fn named_caption(mut entry: CaptionEntry, roster: &Roster) -> CaptionEntry {
3058 if entry.display_name.is_empty() {
3710 if entry.display_name.is_empty() {
3059 entry.display_name = roster.name_of(&entry.user_id).unwrap_or_default().to_owned();
3711 entry.display_name = roster
3712 .name_of(&entry.user_id)
3713 .unwrap_or_default()
3714 .to_owned();
3060 }
3715 }
3061 entry
3716 entry
3062}
3717}
@@ -3095,8 +3750,14 @@ async fn run_bot_steps(
3095 }
3750 }
3096 };
3751 };
3097 let (join_failure, start_failure) = match job {
3752 let (join_failure, start_failure) = match job {
3098 BotJob::Captions => ("The captions service could not join", "Captions could not start"),
3753 BotJob::Captions => (
3099 BotJob::Recording => ("The recording service could not join", "The recording could not start"),
3754 "The captions service could not join",
3755 "Captions could not start",
3756 ),
3757 BotJob::Recording => (
3758 "The recording service could not join",
3759 "The recording could not start",
3760 ),
3100 };
3761 };
3101 loop {
3762 loop {
3102 match flow.next_for(roster.caption_bot(), is_active) {
3763 match flow.next_for(roster.caption_bot(), is_active) {
@@ -3106,12 +3767,33 @@ async fn run_bot_steps(
3106 continue;
3767 continue;
3107 }
3768 }
3108 let Some(thread) = meeting_chat else {
3769 let Some(thread) = meeting_chat else {
3109 return fail(flow, "This call has no chat for the captions and the recording");
3770 return fail(
3771 flow,
3772 "This call has no chat for the captions and the recording",
3773 );
3110 };
3774 };
3111 *bot_pending = true;
3775 *bot_pending = true;
3112 let added = remote.signaling.add_caption_bot(&remote.conversation, &remote.participant, thread, links, remote.threadless).await;
3776 let added = remote
3777 .signaling
3778 .add_caption_bot(
3779 &remote.conversation,
3780 &remote.participant,
3781 thread,
3782 links,
3783 remote.threadless,
3784 )
3785 .await;
3113 if job == BotJob::Recording {
3786 if job == BotJob::Recording {
3114 report_organizer_result(added.as_ref().map(|status| *status).map_err(|error| Error::Signaling(error.to_string())), "recording add bot", join_failure, control, timeline);
3787 report_organizer_result(
3788 added
3789 .as_ref()
3790 .map(|status| *status)
3791 .map_err(|error| Error::Signaling(error.to_string())),
3792 "recording add bot",
3793 join_failure,
3794 control,
3795 timeline,
3796 );
3115 }
3797 }
3116 if let Err(error) = added {
3798 if let Err(error) = added {
3117 timeline.record("bot invitation failed", error.to_string());
3799 timeline.record("bot invitation failed", error.to_string());
@@ -3120,21 +3802,40 @@ async fn run_bot_steps(
3120 }
3802 }
3121 }
3803 }
3122 CaptionStep::Start => {
3804 CaptionStep::Start => {
3123 let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone()) else { return };
3805 let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone()) else {
3806 return;
3807 };
3124 match job {
3808 match job {
3125 BotJob::Captions => {
3809 BotJob::Captions => {
3126 if let Err(error) = remote.signaling.caption_command(&url, BotAction::Start, &remote.participant).await {
3810 if let Err(error) = remote
3811 .signaling
3812 .caption_command(&url, BotAction::Start, &remote.participant)
3813 .await
3814 {
3127 timeline.record("caption start failed", error.to_string());
3815 timeline.record("caption start failed", error.to_string());
3128 return fail(flow, start_failure);
3816 return fail(flow, start_failure);
3129 }
3817 }
3130 if let Err(error) = remote.signaling.set_caption_preference(&remote.conversation, &remote.participant, true).await {
3818 if let Err(error) = remote
3819 .signaling
3820 .set_caption_preference(&remote.conversation, &remote.participant, true)
3821 .await
3822 {
3131 timeline.record("caption preference failed", error.to_string());
3823 timeline.record("caption preference failed", error.to_string());
3132 }
3824 }
3133 }
3825 }
3134 BotJob::Recording => {
3826 BotJob::Recording => {
3135 let started = remote.signaling.recording_command(&url, plan.start(), &remote.participant, &plan.title).await;
3827 let started = remote
3828 .signaling
3829 .recording_command(&url, plan.start(), &remote.participant, &plan.title)
3830 .await;
3136 let failed = started.is_err();
3831 let failed = started.is_err();
3137 report_organizer_result(started, "recording start", start_failure, control, timeline);
3832 report_organizer_result(
3833 started,
3834 "recording start",
3835 start_failure,
3836 control,
3837 timeline,
3838 );
3138 if failed {
3839 if failed {
3139 return fail(flow, start_failure);
3840 return fail(flow, start_failure);
3140 }
3841 }
@@ -3142,13 +3843,27 @@ async fn run_bot_steps(
3142 }
3843 }
3143 }
3844 }
3144 CaptionStep::Stop => {
3845 CaptionStep::Stop => {
3145 let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone()) else { continue };
3846 let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone()) else {
3847 continue;
3848 };
3146 match job {
3849 match job {
3147 BotJob::Captions => {
3850 BotJob::Captions => {
3148 if let Err(error) = remote.signaling.caption_command(&url, BotAction::Stop, &remote.participant).await {
3851 if let Err(error) = remote
3852 .signaling
3853 .caption_command(&url, BotAction::Stop, &remote.participant)
3854 .await
3855 {
3149 timeline.record("caption stop failed", error.to_string());
3856 timeline.record("caption stop failed", error.to_string());
3150 }
3857 }
3151 if let Err(error) = remote.signaling.set_caption_preference(&remote.conversation, &remote.participant, false).await {
3858 if let Err(error) = remote
3859 .signaling
3860 .set_caption_preference(
3861 &remote.conversation,
3862 &remote.participant,
3863 false,
3864 )
3865 .await
3866 {
3152 timeline.record("caption preference failed", error.to_string());
3867 timeline.record("caption preference failed", error.to_string());
3153 }
3868 }
3154 }
3869 }
@@ -3157,18 +3872,29 @@ async fn run_bot_steps(
3157 let updates = control.updates();
3872 let updates = control.updates();
3158 let (command, title) = (plan.stop(), plan.title.clone());
3873 let (command, title) = (plan.stop(), plan.title.clone());
3159 tokio::spawn(async move {
3874 tokio::spawn(async move {
3160 let mut stopped = remote.signaling.recording_command(&url, command, &remote.participant, &title).await;
3875 let mut stopped = remote
3876 .signaling
3877 .recording_command(&url, command, &remote.participant, &title)
3878 .await;
3161 for _ in 0..RECORDING_STOP_RETRIES {
3879 for _ in 0..RECORDING_STOP_RETRIES {
3162 if !stopped.as_ref().is_err_and(recorder_busy) {
3880 if !stopped.as_ref().is_err_and(recorder_busy) {
3163 break;
3881 break;
3164 }
3882 }
3165 tokio::time::sleep(RECORDING_STOP_RETRY_WAIT).await;
3883 tokio::time::sleep(RECORDING_STOP_RETRY_WAIT).await;
3166 stopped = remote.signaling.recording_command(&url, command, &remote.participant, &title).await;
3884 stopped = remote
3885 .signaling
3886 .recording_command(&url, command, &remote.participant, &title)
3887 .await;
3167 }
3888 }
3168 if stopped.is_err() {
3889 if stopped.is_err() {
3169 let _ = updates.send(CallUpdate::Notice("The recording could not be stopped".into()));
3890 let _ = updates.send(CallUpdate::Notice(
3891 "The recording could not be stopped".into(),
3892 ));
3170 }
3893 }
3171 let _ = updates.send(CallUpdate::Organizer { action: "recording stop".into(), outcome: stopped.map_err(|error| error.to_string()) });
3894 let _ = updates.send(CallUpdate::Organizer {
3895 action: "recording stop".into(),
3896 outcome: stopped.map_err(|error| error.to_string()),
3897 });
3172 });
3898 });
3173 }
3899 }
3174 }
3900 }
@@ -3188,7 +3914,12 @@ fn send_receive_change(control: &CallControl, change: ReceiveChange) {
3188 }
3914 }
3189}
3915}
3190
3916
3191fn record_audio_devices(timeline: &Timeline, lists: &devices::DeviceLists, input: Option<&AppliedDevice>, output: Option<&AppliedDevice>) {
3917fn record_audio_devices(
3918 timeline: &Timeline,
3919 lists: &devices::DeviceLists,
3920 input: Option<&AppliedDevice>,
3921 output: Option<&AppliedDevice>,
3922) {
3192 let name = |devices: &[AudioDevice], applied: Option<&AppliedDevice>| {
3923 let name = |devices: &[AudioDevice], applied: Option<&AppliedDevice>| {
3193 applied
3924 applied
3194 .and_then(|applied| devices.iter().find(|device| device.index == applied.index))
3925 .and_then(|applied| devices.iter().find(|device| device.index == applied.index))
@@ -3197,7 +3928,11 @@ fn record_audio_devices(timeline: &Timeline, lists: &devices::DeviceLists, input
3197 };
3928 };
3198 timeline.record(
3929 timeline.record(
3199 "audio devices",
3930 "audio devices",
3200 format!("input={} output={}", name(&lists.inputs, input), name(&lists.outputs, output)),
3931 format!(
3932 "input={} output={}",
3933 name(&lists.inputs, input),
3934 name(&lists.outputs, output)
3935 ),
3201 );
3936 );
3202}
3937}
3203
3938
@@ -3211,19 +3946,31 @@ fn follow_device_change(
3211 control: &CallControl,
3946 control: &CallControl,
3212) -> bool {
3947) -> bool {
3213 let system_default = devices::system_default_id(flow);
3948 let system_default = devices::system_default_id(flow);
3214 let (index, fell_back) = match devices::reselect(applied.as_ref(), current, choice, system_default.as_deref()) {
3949 let (index, fell_back) =
3215 Reselect::Keep => return false,
3950 match devices::reselect(applied.as_ref(), current, choice, system_default.as_deref()) {
3216 Reselect::Select(index) => (index, false),
3951 Reselect::Keep => return false,
3217 Reselect::FallBack(index) => (index, true),
3952 Reselect::Select(index) => (index, false),
3218 };
3953 Reselect::FallBack(index) => (index, true),
3954 };
3219 let selected = select(index);
3955 let selected = select(index);
3220 timeline.record("device change", format!("{flow:?} {choice:?} -> index {index} fallback={fell_back} applied={selected}"));
3956 timeline.record(
3957 "device change",
3958 format!("{flow:?} {choice:?} -> index {index} fallback={fell_back} applied={selected}"),
3959 );
3221 if selected {
3960 if selected {
3222 *applied = current.iter().find(|device| device.index == index).map(|device| AppliedDevice { index, key: device.key() });
3961 *applied = current
3962 .iter()
3963 .find(|device| device.index == index)
3964 .map(|device| AppliedDevice {
3965 index,
3966 key: device.key(),
3967 });
3223 }
3968 }
3224 if fell_back {
3969 if fell_back {
3225 let fallback = current.iter().find(|device| device.index == index);
3970 let fallback = current.iter().find(|device| device.index == index);
3226 control.send(CallUpdate::Notice(devices::disconnect_notice(previous, choice, fallback)));
3971 control.send(CallUpdate::Notice(devices::disconnect_notice(
3972 previous, choice, fallback,
3973 )));
3227 }
3974 }
3228 selected
3975 selected
3229}
3976}
@@ -3250,16 +3997,27 @@ fn apply_mute(
3250 tokio::spawn(async move {
3997 tokio::spawn(async move {
3251 let _ = remote
3998 let _ = remote
3252 .signaling
3999 .signaling
3253 .update_endpoint_state(&remote.conversation, &remote.participant, effect.endpoint_is_muted)
4000 .update_endpoint_state(
4001 &remote.conversation,
4002 &remote.participant,
4003 effect.endpoint_is_muted,
4004 )
3254 .await;
4005 .await;
3255 });
4006 });
3256 effect.muted
4007 effect.muted
3257}
4008}
3258
4009
3259fn silence_for_hold(on_hold: bool, muted: bool, audio: Option<&AudioSetup>, software_audio: Option<&SoftwareAudio>) {
4010fn silence_for_hold(
4011 on_hold: bool,
4012 muted: bool,
4013 audio: Option<&AudioSetup>,
4014 software_audio: Option<&SoftwareAudio>,
4015) {
3260 let silent = on_hold || muted;
4016 let silent = on_hold || muted;
3261 if let Some(audio) = audio {
4017 if let Some(audio) = audio {
3262 audio.track.set_enabled(MuteEffect::for_muted(silent).track_enabled);
4018 audio
4019 .track
4020 .set_enabled(MuteEffect::for_muted(silent).track_enabled);
3263 }
4021 }
3264 if let Some(software_audio) = software_audio {
4022 if let Some(software_audio) = software_audio {
3265 software_audio.set_microphone_muted(silent);
4023 software_audio.set_microphone_muted(silent);
@@ -3277,7 +4035,10 @@ fn swap_audio_track(peer: &PeerConnection, track: &RtcAudioTrack) -> Result<()>
3277 .map_err(|error| Error::Webrtc(error.to_string()))
4035 .map_err(|error| Error::Webrtc(error.to_string()))
3278}
4036}
3279
4037
3280fn outgoing_track<'a>(software_audio: Option<&'a SoftwareAudio>, device_track: &'a RtcAudioTrack) -> &'a RtcAudioTrack {
4038fn outgoing_track<'a>(
4039 software_audio: Option<&'a SoftwareAudio>,
4040 device_track: &'a RtcAudioTrack,
4041) -> &'a RtcAudioTrack {
3281 pick_track(software_audio.map(|audio| &audio.track), device_track)
4042 pick_track(software_audio.map(|audio| &audio.track), device_track)
3282}
4043}
3283
4044
@@ -3292,12 +4053,22 @@ fn software_wanted(
3292 audio: Option<&AudioSetup>,
4053 audio: Option<&AudioSetup>,
3293) -> Option<SoftwareAudioPlan> {
4054) -> Option<SoftwareAudioPlan> {
3294 let sharing_sound = share_sound_wanted && local_video.sharing();
4055 let sharing_sound = share_sound_wanted && local_video.sharing();
3295 SoftwareAudioPlan::wanted(mic_settings, sharing_sound, audio.is_some_and(AudioSetup::uses_devices))
4056 SoftwareAudioPlan::wanted(
4057 mic_settings,
4058 sharing_sound,
4059 audio.is_some_and(AudioSetup::uses_devices),
4060 )
3296}
4061}
3297
4062
3298fn restore_device_track(factory: &PeerConnectionFactory, input: &DeviceChoice, peer: &PeerConnection, device_track: &RtcAudioTrack, timeline: &Timeline) {
4063fn restore_device_track(
4064 factory: &PeerConnectionFactory,
4065 input: &DeviceChoice,
4066 peer: &PeerConnection,
4067 device_track: &RtcAudioTrack,
4068 timeline: &Timeline,
4069) {
3299 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
4070 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
3300 if cfg!(windows) && !factory.adm_recording_enabled() {
4071 if !factory.adm_recording_enabled() {
3301 factory.set_adm_recording_enabled(true);
4072 factory.set_adm_recording_enabled(true);
3302 devices::select_input(factory, input);
4073 devices::select_input(factory, input);
3303 }
4074 }
@@ -3325,6 +4096,9 @@ fn sync_software_audio(
3325 if running == wanted && !restart {
4096 if running == wanted && !restart {
3326 return;
4097 return;
3327 }
4098 }
4099 if running.is_some() {
4100 timeline.record("software audio", "stopping");
4101 }
3328 *software_audio = None;
4102 *software_audio = None;
3329 let was_sharing_sound = running.is_some_and(|plan| plan.computer_sound);
4103 let was_sharing_sound = running.is_some_and(|plan| plan.computer_sound);
3330 let Some(plan) = wanted else {
4104 let Some(plan) = wanted else {
@@ -3332,15 +4106,26 @@ fn sync_software_audio(
3332 control.send(CallUpdate::ShareSound(false));
4106 control.send(CallUpdate::ShareSound(false));
3333 return;
4107 return;
3334 };
4108 };
3335 let started = SoftwareAudio::start(factory, options.audio, options.tone_hz, input, plan, muted, remote_audio)
4109 let started = SoftwareAudio::start(
3336 .and_then(|audio| swap_audio_track(peer, &audio.track).map(|()| audio));
4110 factory,
4111 options.audio,
4112 options.tone_hz,
4113 input,
4114 plan,
4115 muted,
4116 remote_audio,
4117 )
4118 .and_then(|audio| swap_audio_track(peer, &audio.track).map(|()| audio));
3337 match started {
4119 match started {
3338 Ok(audio) => {
4120 Ok(audio) => {
3339 timeline.record("software audio", format!("{:?}, computer sound {:?}", plan.processing, audio.loopback));
4121 timeline.record(
4122 "software audio",
4123 format!("{:?}, computer sound {:?}", plan.processing, audio.loopback),
4124 );
3340 if let Some(source) = &audio.microphone_source {
4125 if let Some(source) = &audio.microphone_source {
3341 timeline.record("mic capture", source.clone());
4126 timeline.record("mic capture", source.clone());
3342 }
4127 }
3343 if cfg!(windows) && audio.microphone_source.is_some() {
4128 if audio.microphone_source.is_some() {
3344 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
4129 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
3345 factory.set_adm_recording_enabled(false);
4130 factory.set_adm_recording_enabled(false);
3346 }
4131 }
@@ -3366,7 +4151,13 @@ fn sync_software_audio(
3366 }
4151 }
3367}
4152}
3368
4153
3369async fn tear_down(mut live: Live, inner: &Inner, timeline: &Timeline, report: &mut CallReport, cancelled: bool) {
4154async fn tear_down(
4155 mut live: Live,
4156 inner: &Inner,
4157 timeline: &Timeline,
4158 report: &mut CallReport,
4159 cancelled: bool,
4160) {
3370 for peer in &live.peers {
4161 for peer in &live.peers {
3371 peer.close();
4162 peer.close();
3372 }
4163 }
@@ -3377,8 +4168,16 @@ async fn tear_down(mut live: Live, inner: &Inner, timeline: &Timeline, report: &
3377 if !live.skip_leave
4168 if !live.skip_leave
3378 && let Some(remote) = &live.remote
4169 && let Some(remote) = &live.remote
3379 {
4170 {
3380 let reason = if cancelled { LeaveReason::Cancel } else { LeaveReason::Hangup };
4171 let reason = if cancelled {
3381 match remote.signaling.leave(&remote.conversation, &remote.participant, reason).await {
4172 LeaveReason::Cancel
4173 } else {
4174 LeaveReason::Hangup
4175 };
4176 match remote
4177 .signaling
4178 .leave(&remote.conversation, &remote.participant, reason)
4179 .await
4180 {
3382 Ok(()) => report.left_cleanly = true,
4181 Ok(()) => report.left_cleanly = true,
3383 Err(error) => timeline.record("leave failed", error.to_string()),
4182 Err(error) => timeline.record("leave failed", error.to_string()),
3384 }
4183 }
@@ -3422,31 +4221,53 @@ fn handle_callback(callback: &TrouterCallback, timeline: &Timeline) -> Result<Ca
3422 let body = decode_body(callback)?;
4221 let body = decode_body(callback)?;
3423 let (_, event) = classify(&callback.path, body)?;
4222 let (_, event) = classify(&callback.path, body)?;
3424 let detail = match &event {
4223 let detail = match &event {
3425 CallEvent::Acceptance(acceptance) => format!("answer sdp {} bytes, fromMixer={}", acceptance.sdp.len(), acceptance.from_mixer),
4224 CallEvent::Acceptance(acceptance) => format!(
3426 CallEvent::End(end) => format!("code={} subCode={} phrase={}", end.code, end.sub_code, end.phrase),
4225 "answer sdp {} bytes, fromMixer={}",
4226 acceptance.sdp.len(),
4227 acceptance.from_mixer
4228 ),
4229 CallEvent::End(end) => format!(
4230 "code={} subCode={} phrase={}",
4231 end.code, end.sub_code, end.phrase
4232 ),
3427 CallEvent::Progress(status) => format!("{status:?}"),
4233 CallEvent::Progress(status) => format!("{status:?}"),
3428 CallEvent::ConversationEnd(body) | CallEvent::Rejection(body) | CallEvent::AddParticipantFailure(body) | CallEvent::RetargetCompletion(body) => outcome_summary(body),
4234 CallEvent::ConversationEnd(body)
3429 CallEvent::ControlVideoStreaming(body) => parse_request(body).map_or_else(|| "body not understood".to_owned(), |request| request.shape),
4235 | CallEvent::Rejection(body)
4236 | CallEvent::AddParticipantFailure(body)
4237 | CallEvent::RetargetCompletion(body) => outcome_summary(body),
4238 CallEvent::ControlVideoStreaming(body) => parse_request(body)
4239 .map_or_else(|| "body not understood".to_owned(), |request| request.shape),
3430 _ => String::new(),
4240 _ => String::new(),
3431 };
4241 };
3432 timeline.record(format!("Trouter {}", event.name()), detail);
4242 timeline.record(format!("Trouter {}", event.name()), detail);
3433 match &event {
4243 match &event {
3434 CallEvent::Acceptance(acceptance) => timeline.record_sdp("remote answer", &acceptance.sdp),
4244 CallEvent::Acceptance(acceptance) => timeline.record_sdp("remote answer", &acceptance.sdp),
3435 CallEvent::MediaAnswer(answer) => timeline.record_sdp("remote answer", &answer.sdp),
4245 CallEvent::MediaAnswer(answer) => timeline.record_sdp("remote answer", &answer.sdp),
3436 CallEvent::MediaRenegotiation(renegotiation) => timeline.record_sdp("remote offer", &renegotiation.sdp),
4246 CallEvent::MediaRenegotiation(renegotiation) => {
4247 timeline.record_sdp("remote offer", &renegotiation.sdp)
4248 }
3437 _ => {}
4249 _ => {}
3438 }
4250 }
3439 Ok(event)
4251 Ok(event)
3440}
4252}
3441
4253
3442
4254async fn apply_answer(
3443async fn apply_answer(peer: &PeerConnection, teams_answer: &str, signaled: &SignaledOffer, browser_offer: &str) -> Result<()> {
4255 peer: &PeerConnection,
4256 teams_answer: &str,
4257 signaled: &SignaledOffer,
4258 browser_offer: &str,
4259) -> Result<()> {
3444 let answer = to_browser_answer(teams_answer, signaled, browser_offer)?;
4260 let answer = to_browser_answer(teams_answer, signaled, browser_offer)?;
3445 set_browser_answer(peer, &answer).await
4261 set_browser_answer(peer, &answer).await
3446}
4262}
3447
4263
3448/// libwebrtc does not restart a send stream that an inactive answer stopped, so a hold keeps the streams and only mutes.
4264/// libwebrtc does not restart a send stream that an inactive answer stopped, so a hold keeps the streams and only mutes.
3449async fn apply_hold_answer(peer: &PeerConnection, teams_answer: &str, signaled: &SignaledOffer, browser_offer: &str) -> Result<()> {
4265async fn apply_hold_answer(
4266 peer: &PeerConnection,
4267 teams_answer: &str,
4268 signaled: &SignaledOffer,
4269 browser_offer: &str,
4270) -> Result<()> {
3450 let answer = to_browser_answer(teams_answer, signaled, browser_offer)?;
4271 let answer = to_browser_answer(teams_answer, signaled, browser_offer)?;
3451 set_browser_answer(peer, &keep_media_running(&answer, browser_offer)).await
4272 set_browser_answer(peer, &keep_media_running(&answer, browser_offer)).await
3452}
4273}
@@ -3471,7 +4292,10 @@ fn dump_sdp(options: &CallOptions, name: &str, sdp: &str) {
3471 return format!("{prefix}<masked>");
4292 return format!("{prefix}<masked>");
3472 }
4293 }
3473 }
4294 }
3474 line.split(' ').map(mask_address).collect::<Vec<_>>().join(" ")
4295 line.split(' ')
4296 .map(mask_address)
4297 .collect::<Vec<_>>()
4298 .join(" ")
3475 })
4299 })
3476 .collect();
4300 .collect();
3477 let _ = std::fs::create_dir_all(directory);
4301 let _ = std::fs::create_dir_all(directory);
@@ -3482,8 +4306,16 @@ fn dump_timeline(options: &CallOptions, timeline: &Timeline, failure: Option<&Er
3482 let Some(directory) = &options.sdp_dump_dir else {
4306 let Some(directory) = &options.sdp_dump_dir else {
3483 return;
4307 return;
3484 };
4308 };
3485 let mut lines: Vec<String> =
4309 let mut lines: Vec<String> = timeline
3486 timeline.entries().iter().map(|entry| format!("{:>6} ms {} {}", entry.elapsed_ms, entry.label, entry.detail)).collect();
4310 .entries()
4311 .iter()
4312 .map(|entry| {
4313 format!(
4314 "{:>6} ms {} {}",
4315 entry.elapsed_ms, entry.label, entry.detail
4316 )
4317 })
4318 .collect();
3487 lines.push(match failure {
4319 lines.push(match failure {
3488 Some(error) => format!("failed: {error}"),
4320 Some(error) => format!("failed: {error}"),
3489 None => "ended without error".to_owned(),
4321 None => "ended without error".to_owned(),
@@ -3493,9 +4325,13 @@ fn dump_timeline(options: &CallOptions, timeline: &Timeline, failure: Option<&Er
3493}
4325}
3494
4326
3495fn mask_address(token: &str) -> String {
4327fn mask_address(token: &str) -> String {
3496 let dotted_quad = token.split('.').count() == 4 && token.split('.').all(|part| part.parse::<u8>().is_ok());
4328 let dotted_quad =
3497 let colon_address = token.matches(':').count() >= 2 && !token.starts_with("a=") && !token.starts_with("urn:");
4329 token.split('.').count() == 4 && token.split('.').all(|part| part.parse::<u8>().is_ok());
3498 if (dotted_quad && token != "10.10.10.10" && token != "0.0.0.0" && token != "127.0.0.1") || colon_address {
4330 let colon_address =
4331 token.matches(':').count() >= 2 && !token.starts_with("a=") && !token.starts_with("urn:");
4332 if (dotted_quad && token != "10.10.10.10" && token != "0.0.0.0" && token != "127.0.0.1")
4333 || colon_address
4334 {
3499 "<addr>".to_owned()
4335 "<addr>".to_owned()
3500 } else {
4336 } else {
3501 token.to_owned()
4337 token.to_owned()
@@ -3516,7 +4352,11 @@ async fn record_track(track: RtcAudioTrack, recording: Arc<Mutex<Recording>>, to
3516 }
4352 }
3517}
4353}
3518
4354
3519async fn poll_broker(signaling: Arc<Signaling>, conversation: Conversation, running: Arc<AtomicBool>) {
4355async fn poll_broker(
4356 signaling: Arc<Signaling>,
4357 conversation: Conversation,
4358 running: Arc<AtomicBool>,
4359) {
3520 let Ok(first) = conversation.link("subscribe") else {
4360 let Ok(first) = conversation.link("subscribe") else {
3521 return;
4361 return;
3522 };
4362 };
@@ -3564,25 +4404,17 @@ struct ShareReceive {
3564 pli_count: u32,
4404 pli_count: u32,
3565 fir_count: u32,
4405 fir_count: u32,
3566 freeze_count: u32,
4406 freeze_count: u32,
3567 qp_sum: u64,
3568 bytes_received: u64,
3569}
4407}
3570
4408
3571impl ShareReceive {
4409impl ShareReceive {
3572 fn average_qp(&self) -> u64 {
3573 self.qp_sum.checked_div(u64::from(self.frames_decoded)).unwrap_or(0)
3574 }
3575
3576 fn summary(&self) -> String {
4410 fn summary(&self) -> String {
3577 format!(
4411 format!(
3578 " share in decoded={} keyframes={} {}x{} fps={:.0} qp={} bytes={} pli={} fir={} freezes={}",
4412 " share in decoded={} keyframes={} {}x{} fps={:.0} pli={} fir={} freezes={}",
3579 self.frames_decoded,
4413 self.frames_decoded,
3580 self.key_frames_decoded,
4414 self.key_frames_decoded,
3581 self.width,
4415 self.width,
3582 self.height,
4416 self.height,
3583 self.frames_per_second,
4417 self.frames_per_second,
3584 self.average_qp(),
3585 self.bytes_received,
3586 self.pli_count,
4418 self.pli_count,
3587 self.fir_count,
4419 self.fir_count,
3588 self.freeze_count
4420 self.freeze_count
@@ -3606,7 +4438,10 @@ async fn collect_stats(peer: &PeerConnection, share_mids: &[String]) -> StatsSna
3606 }
4438 }
3607 RtcStats::MediaSource(source) if source.source.kind == "audio" => {
4439 RtcStats::MediaSource(source) if source.source.kind == "audio" => {
3608 snapshot.local_level = snapshot.local_level.max(source.audio.audio_level);
4440 snapshot.local_level = snapshot.local_level.max(source.audio.audio_level);
3609 snapshot.source_levels.push(format!("{}={:.3}", source.source.track_identifier, source.audio.audio_level));
4441 snapshot.source_levels.push(format!(
4442 "{}={:.3}",
4443 source.source.track_identifier, source.audio.audio_level
4444 ));
3610 snapshot.echo_return_loss_enhancement = source.audio.echo_return_loss_enhancement;
4445 snapshot.echo_return_loss_enhancement = source.audio.echo_return_loss_enhancement;
3611 }
4446 }
3612 RtcStats::OutboundRtp(outbound) if outbound.stream.kind == "audio" => {
4447 RtcStats::OutboundRtp(outbound) if outbound.stream.kind == "audio" => {
@@ -3626,24 +4461,32 @@ async fn collect_stats(peer: &PeerConnection, share_mids: &[String]) -> StatsSna
3626 pli_count: inbound.inbound.pli_count,
4461 pli_count: inbound.inbound.pli_count,
3627 fir_count: inbound.inbound.fir_count,
4462 fir_count: inbound.inbound.fir_count,
3628 freeze_count: inbound.inbound.freeze_count,
4463 freeze_count: inbound.inbound.freeze_count,
3629 qp_sum: inbound.inbound.qp_sum,
3630 bytes_received: inbound.inbound.bytes_received,
3631 });
4464 });
3632 }
4465 }
3633 snapshot.video.inbound_frames_decoded += u64::from(inbound.inbound.frames_decoded);
4466 snapshot.video.inbound_frames_decoded += u64::from(inbound.inbound.frames_decoded);
3634 snapshot.video.inbound_width = snapshot.video.inbound_width.max(inbound.inbound.frame_width);
4467 snapshot.video.inbound_width = snapshot
3635 snapshot.video.inbound_height = snapshot.video.inbound_height.max(inbound.inbound.frame_height);
4468 .video
4469 .inbound_width
4470 .max(inbound.inbound.frame_width);
4471 snapshot.video.inbound_height = snapshot
4472 .video
4473 .inbound_height
4474 .max(inbound.inbound.frame_height);
3636 }
4475 }
3637 RtcStats::RemoteInboundRtp(remote) if remote.stream.kind == "video" => {
4476 RtcStats::RemoteInboundRtp(remote) if remote.stream.kind == "video" => {
3638 snapshot.video.remote_reports += remote.remote_inbound.round_trip_time_measurements;
4477 snapshot.video.remote_reports += remote.remote_inbound.round_trip_time_measurements;
3639 snapshot.video.remote_round_trip_ms = snapshot.video.remote_round_trip_ms.max(remote.remote_inbound.round_trip_time * 1000.0);
4478 snapshot.video.remote_round_trip_ms = snapshot
4479 .video
4480 .remote_round_trip_ms
4481 .max(remote.remote_inbound.round_trip_time * 1000.0);
3640 }
4482 }
3641 RtcStats::OutboundRtp(outbound) if outbound.stream.kind == "video" => {
4483 RtcStats::OutboundRtp(outbound) if outbound.stream.kind == "video" => {
3642 snapshot.video.outbound_packets += outbound.sent.packets_sent;
4484 snapshot.video.outbound_packets += outbound.sent.packets_sent;
3643 if share_mids.contains(&outbound.outbound.mid) {
4485 if share_mids.contains(&outbound.outbound.mid) {
3644 snapshot.share_outbound_packets += outbound.sent.packets_sent;
4486 snapshot.share_outbound_packets += outbound.sent.packets_sent;
3645 }
4487 }
3646 snapshot.video.outbound_frames_encoded += u64::from(outbound.outbound.frames_encoded);
4488 snapshot.video.outbound_frames_encoded +=
4489 u64::from(outbound.outbound.frames_encoded);
3647 snapshot.video_senders.push(format!(
4490 snapshot.video_senders.push(format!(
3648 "mid {} packets={} key={} pli={} fir={} nack={} target={:.0}kbps limit={:?} active={}",
4491 "mid {} packets={} key={} pli={} fir={} nack={} target={:.0}kbps limit={:?} active={}",
3649 outbound.outbound.mid,
4492 outbound.outbound.mid,
@@ -3656,8 +4499,14 @@ async fn collect_stats(peer: &PeerConnection, share_mids: &[String]) -> StatsSna
3656 outbound.outbound.quality_limitation_reason,
4499 outbound.outbound.quality_limitation_reason,
3657 outbound.outbound.active
4500 outbound.outbound.active
3658 ));
4501 ));
3659 snapshot.video.outbound_width = snapshot.video.outbound_width.max(outbound.outbound.frame_width);
4502 snapshot.video.outbound_width = snapshot
3660 snapshot.video.outbound_height = snapshot.video.outbound_height.max(outbound.outbound.frame_height);
4503 .video
4504 .outbound_width
4505 .max(outbound.outbound.frame_width);
4506 snapshot.video.outbound_height = snapshot
4507 .video
4508 .outbound_height
4509 .max(outbound.outbound.frame_height);
3661 }
4510 }
3662 RtcStats::Transport(transport) => {
4511 RtcStats::Transport(transport) => {
3663 snapshot.dtls_state = format!("{:?}", transport.transport.dtls_state);
4512 snapshot.dtls_state = format!("{:?}", transport.transport.dtls_state);
@@ -3681,13 +4530,23 @@ async fn collect_stats(peer: &PeerConnection, share_mids: &[String]) -> StatsSna
3681 stats
4530 stats
3682 .iter()
4531 .iter()
3683 .find_map(|entry| match entry {
4532 .find_map(|entry| match entry {
3684 RtcStats::LocalCandidate(local) if local.rtc.id == candidate_id => Some(&local.local_candidate),
4533 RtcStats::LocalCandidate(local) if local.rtc.id == candidate_id => {
3685 RtcStats::RemoteCandidate(remote) if remote.rtc.id == candidate_id => Some(&remote.remote_candidate),
4534 Some(&local.local_candidate)
4535 }
4536 RtcStats::RemoteCandidate(remote) if remote.rtc.id == candidate_id => {
4537 Some(&remote.remote_candidate)
4538 }
3686 _ => None,
4539 _ => None,
3687 })
4540 })
3688 .map(|candidate| {
4541 .map(|candidate| {
3689 let kind = candidate.candidate_type.map(|kind| format!("{kind:?}")).unwrap_or_default();
4542 let kind = candidate
3690 let relay = candidate.relay_protocol.map(|relay| format!(" via {relay:?}")).unwrap_or_default();
4543 .candidate_type
4544 .map(|kind| format!("{kind:?}"))
4545 .unwrap_or_default();
4546 let relay = candidate
4547 .relay_protocol
4548 .map(|relay| format!(" via {relay:?}"))
4549 .unwrap_or_default();
3691 format!("{kind}/{}{relay}", candidate.protocol)
4550 format!("{kind}/{}{relay}", candidate.protocol)
3692 })
4551 })
3693 .unwrap_or_else(|| "?".into())
4552 .unwrap_or_else(|| "?".into())
@@ -3704,22 +4563,24 @@ async fn collect_stats(peer: &PeerConnection, share_mids: &[String]) -> StatsSna
3704
4563
3705#[cfg(test)]
4564#[cfg(test)]
3706mod tests {
4565mod tests {
3707 #[test]
3708 fn gathering_settles_shortly_after_a_udp_relay_or_when_complete() {
3709 assert!(!gathering_settled(false, None));
3710 assert!(!gathering_settled(false, Some(Duration::from_millis(50))));
3711 assert!(gathering_settled(false, Some(RELAY_SETTLE)));
3712 assert!(gathering_settled(true, None));
3713 }
3714
3715 #[tokio::test]
4566 #[tokio::test]
3716 async fn a_hanging_setup_step_ends_on_cancel_or_after_the_step_timeout() {
4567 async fn a_hanging_setup_step_ends_on_cancel_or_after_the_step_timeout() {
3717 let (handle, mut control) = crate::control::call_channel();
4568 let (handle, mut control) = crate::control::call_channel();
3718 handle.commands.send(CallCommand::Hangup).unwrap();
4569 handle.commands.send(CallCommand::Hangup).unwrap();
3719 let limit = Duration::from_millis(20);
4570 let limit = Duration::from_millis(20);
3720 let cancelled = setup_step_within(&mut control, limit, std::future::pending::<std::result::Result<(), Error>>()).await;
4571 let cancelled = setup_step_within(
4572 &mut control,
4573 limit,
4574 std::future::pending::<std::result::Result<(), Error>>(),
4575 )
4576 .await;
3721 assert!(matches!(cancelled, Err(Error::Cancelled)));
4577 assert!(matches!(cancelled, Err(Error::Cancelled)));
3722 let timed_out = setup_step_within(&mut control, limit, std::future::pending::<std::result::Result<(), Error>>()).await;
4578 let timed_out = setup_step_within(
4579 &mut control,
4580 limit,
4581 std::future::pending::<std::result::Result<(), Error>>(),
4582 )
4583 .await;
3723 assert!(matches!(timed_out, Err(Error::Signaling(_))));
4584 assert!(matches!(timed_out, Err(Error::Signaling(_))));
3724 }
4585 }
3725
4586
@@ -3734,8 +4595,12 @@ mod tests {
3734
4595
3735 #[test]
4596 #[test]
3736 fn only_a_conflict_answer_retries_a_recording_stop() {
4597 fn only_a_conflict_answer_retries_a_recording_stop() {
3737 assert!(recorder_busy(&Error::Signaling("recording command answered HTTP 409 no answer".into())));
4598 assert!(recorder_busy(&Error::Signaling(
3738 assert!(!recorder_busy(&Error::Signaling("recording command answered HTTP 500 no answer".into())));
4599 "recording command answered HTTP 409 no answer".into()
4600 )));
4601 assert!(!recorder_busy(&Error::Signaling(
4602 "recording command answered HTTP 500 no answer".into()
4603 )));
3739 assert!(!recorder_busy(&Error::Cancelled));
4604 assert!(!recorder_busy(&Error::Cancelled));
3740 }
4605 }
3741
4606
@@ -3767,14 +4632,21 @@ mod tests {
3767 const BROWSER_OFFER: &str = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\na=mid:0\r\na=sendrecv\r\nm=video 9 UDP/TLS/RTP/SAVPF 102\r\na=mid:1\r\na=sendrecv\r\nm=video 9 UDP/TLS/RTP/SAVPF 102\r\na=mid:2\r\na=recvonly\r\n";
4632 const BROWSER_OFFER: &str = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\na=mid:0\r\na=sendrecv\r\nm=video 9 UDP/TLS/RTP/SAVPF 102\r\na=mid:1\r\na=sendrecv\r\nm=video 9 UDP/TLS/RTP/SAVPF 102\r\na=mid:2\r\na=recvonly\r\n";
3768
4633
3769 fn directions(sdp: &str) -> Vec<String> {
4634 fn directions(sdp: &str) -> Vec<String> {
3770 crate::sdp::parse(sdp).unwrap().media.iter().map(|line| line.direction().unwrap_or("none").to_owned()).collect()
4635 crate::sdp::parse(sdp)
4636 .unwrap()
4637 .media
4638 .iter()
4639 .map(|line| line.direction().unwrap_or("none").to_owned())
4640 .collect()
3771 }
4641 }
3772
4642
3773 async fn local_offer(layout: Layout) -> Result<OfferedMedia> {
4643 async fn local_offer(layout: Layout) -> Result<OfferedMedia> {
3774 use libwebrtc::audio_source::native::NativeAudioSource;
4644 use libwebrtc::audio_source::native::NativeAudioSource;
3775 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
4645 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
3776 let factory = devices::shared_factory();
4646 let factory = devices::shared_factory();
3777 let peer = factory.create_peer_connection(RtcConfiguration::default()).unwrap();
4647 let peer = factory
4648 .create_peer_connection(RtcConfiguration::default())
4649 .unwrap();
3778 let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, 100);
4650 let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, 100);
3779 let track = factory.create_audio_track("microphone", source);
4651 let track = factory.create_audio_track("microphone", source);
3780 let offer = create_offer(&peer, &factory, &track, layout, None).await;
4652 let offer = create_offer(&peer, &factory, &track, layout, None).await;
@@ -3796,11 +4668,22 @@ mod tests {
3796 use libwebrtc::audio_source::native::NativeAudioSource;
4668 use libwebrtc::audio_source::native::NativeAudioSource;
3797 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
4669 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
3798 let factory = devices::shared_factory();
4670 let factory = devices::shared_factory();
3799 let peer = factory.create_peer_connection(RtcConfiguration::default()).unwrap();
4671 let peer = factory
4672 .create_peer_connection(RtcConfiguration::default())
4673 .unwrap();
3800 let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, 100);
4674 let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, 100);
3801 let track = factory.create_audio_track("microphone", source);
4675 let track = factory.create_audio_track("microphone", source);
3802 let offer = include_str!("../tests/fixtures/teams_p2p_offer.sdp");
4676 let offer = include_str!("../tests/fixtures/teams_p2p_offer.sdp");
3803 let answered = answer_offer(&peer, Some(&track), offer, AnswerVideo::Receive, None, false, None).await;
4677 let answered = answer_offer(
4678 &peer,
4679 Some(&track),
4680 offer,
4681 AnswerVideo::Receive,
4682 None,
4683 false,
4684 None,
4685 )
4686 .await;
3804 peer.close();
4687 peer.close();
3805 if let Err(error) = answered {
4688 if let Err(error) = answered {
3806 panic!("{error}");
4689 panic!("{error}");
@@ -3809,51 +4692,144 @@ mod tests {
3809
4692
3810 #[test]
4693 #[test]
3811 fn a_one_to_one_offer_has_audio_and_an_inactive_camera_until_the_camera_is_on() {
4694 fn a_one_to_one_offer_has_audio_and_an_inactive_camera_until_the_camera_is_on() {
3812 assert_eq!(directions(&directions_for(Layout::OneToOne, false, false, false, CAMERA_MID, Some(ONE_TO_ONE_SHARE_MID), false, BROWSER_OFFER)), vec!["sendrecv", "inactive", "inactive"]);
4695 assert_eq!(
3813 assert_eq!(directions(&directions_for(Layout::OneToOne, false, true, false, CAMERA_MID, Some(ONE_TO_ONE_SHARE_MID), false, BROWSER_OFFER)), vec!["sendrecv", "sendrecv", "inactive"]);
4696 directions(&directions_for(
3814 assert_eq!(directions(&directions_for(Layout::OneToOne, false, false, true, CAMERA_MID, Some(ONE_TO_ONE_SHARE_MID), false, BROWSER_OFFER)), vec!["sendrecv", "inactive", "sendonly"]);
4697 Layout::OneToOne,
4698 false,
4699 false,
4700 false,
4701 CAMERA_MID,
4702 Some(ONE_TO_ONE_SHARE_MID),
4703 false,
4704 BROWSER_OFFER
4705 )),
4706 vec!["sendrecv", "inactive", "inactive"]
4707 );
4708 assert_eq!(
4709 directions(&directions_for(
4710 Layout::OneToOne,
4711 false,
4712 true,
4713 false,
4714 CAMERA_MID,
4715 Some(ONE_TO_ONE_SHARE_MID),
4716 false,
4717 BROWSER_OFFER
4718 )),
4719 vec!["sendrecv", "sendrecv", "inactive"]
4720 );
4721 assert_eq!(
4722 directions(&directions_for(
4723 Layout::OneToOne,
4724 false,
4725 false,
4726 true,
4727 CAMERA_MID,
4728 Some(ONE_TO_ONE_SHARE_MID),
4729 false,
4730 BROWSER_OFFER
4731 )),
4732 vec!["sendrecv", "inactive", "sendonly"]
4733 );
3815 }
4734 }
3816
4735
3817 #[test]
4736 #[test]
3818 fn a_hold_silences_every_line_and_a_conference_offer_is_left_alone() {
4737 fn a_hold_silences_every_line_and_a_conference_offer_is_left_alone() {
3819 for layout in [Layout::OneToOne, Layout::Conference] {
4738 for layout in [Layout::OneToOne, Layout::Conference] {
3820 assert_eq!(directions(&directions_for(layout, true, true, false, CAMERA_MID, None, false, BROWSER_OFFER)), vec!["inactive", "inactive", "inactive"]);
4739 assert_eq!(
4740 directions(&directions_for(
4741 layout,
4742 true,
4743 true,
4744 false,
4745 CAMERA_MID,
4746 None,
4747 false,
4748 BROWSER_OFFER
4749 )),
4750 vec!["inactive", "inactive", "inactive"]
4751 );
3821 }
4752 }
3822 assert_eq!(directions_for(Layout::Conference, false, true, false, CAMERA_MID, None, false, BROWSER_OFFER), BROWSER_OFFER);
4753 assert_eq!(
4754 directions_for(
4755 Layout::Conference,
4756 false,
4757 true,
4758 false,
4759 CAMERA_MID,
4760 None,
4761 false,
4762 BROWSER_OFFER
4763 ),
4764 BROWSER_OFFER
4765 );
3823 }
4766 }
3824
4767
3825 #[test]
4768 #[test]
3826 fn a_hold_offer_body_is_inactive_on_every_teams_line_with_one_placeholder_candidate() {
4769 fn a_hold_offer_body_is_inactive_on_every_teams_line_with_one_placeholder_candidate() {
3827 let held = directions_for(Layout::Conference, true, false, false, CAMERA_MID, None, false, BROWSER_OFFER);
4770 let held = directions_for(
4771 Layout::Conference,
4772 true,
4773 false,
4774 false,
4775 CAMERA_MID,
4776 None,
4777 false,
4778 BROWSER_OFFER,
4779 );
3828 let mut numbers = || 7;
4780 let mut numbers = || 7;
3829 let signaled = to_teams_offer(&held, &offer_plan(), &mut numbers).unwrap().sdp;
4781 let signaled = to_teams_offer(&held, &offer_plan(), &mut numbers)
3830 assert_eq!(directions(&signaled), vec!["inactive", "inactive", "inactive"]);
4782 .unwrap()
4783 .sdp;
4784 assert_eq!(
4785 directions(&signaled),
4786 vec!["inactive", "inactive", "inactive"]
4787 );
3831 assert_eq!(signaled.matches("a=candidate:").count(), 1);
4788 assert_eq!(signaled.matches("a=candidate:").count(), 1);
3832 }
4789 }
3833
4790
3834 #[test]
4791 #[test]
3835 fn a_move_into_the_meeting_you_are_already_in_is_ignored() {
4792 fn a_move_into_the_meeting_you_are_already_in_is_ignored() {
3836 let target = |thread: &str| MeetingTarget { thread_id: thread.into(), tenant_id: "t".into(), organizer_id: "o".into(), meeting_data: None };
4793 let target = |thread: &str| MeetingTarget {
3837 assert!(is_own_meeting(Some(&target("19:meeting_a@thread.v2")), &target("19:meeting_a@thread.v2")));
4794 thread_id: thread.into(),
3838 assert!(!is_own_meeting(Some(&target("19:meeting_a@thread.v2")), &target("19:meeting_b@thread.v2")));
4795 tenant_id: "t".into(),
4796 organizer_id: "o".into(),
4797 meeting_data: None,
4798 };
4799 assert!(is_own_meeting(
4800 Some(&target("19:meeting_a@thread.v2")),
4801 &target("19:meeting_a@thread.v2")
4802 ));
4803 assert!(!is_own_meeting(
4804 Some(&target("19:meeting_a@thread.v2")),
4805 &target("19:meeting_b@thread.v2")
4806 ));
3839 assert!(!is_own_meeting(None, &target("19:meeting_a@thread.v2")));
4807 assert!(!is_own_meeting(None, &target("19:meeting_a@thread.v2")));
3840 }
4808 }
3841
4809
3842 #[test]
4810 #[test]
3843 fn a_video_call_names_the_video_modality_only_when_the_camera_sends() {
4811 fn a_video_call_names_the_video_modality_only_when_the_camera_sends() {
3844 assert_eq!(accepted_modalities(false), vec!["Audio".to_owned()]);
4812 assert_eq!(accepted_modalities(false), vec!["Audio".to_owned()]);
3845 assert_eq!(accepted_modalities(true), vec!["Audio".to_owned(), "Video".to_owned()]);
4813 assert_eq!(
4814 accepted_modalities(true),
4815 vec!["Audio".to_owned(), "Video".to_owned()]
4816 );
3846 }
4817 }
3847
4818
3848 #[test]
4819 #[test]
3849 fn specs_map_to_invitation_targets() {
4820 fn specs_map_to_invitation_targets() {
3850 assert_eq!(CallSpec::Echo.target(), InviteTarget::Echo);
4821 assert_eq!(CallSpec::Echo.target(), InviteTarget::Echo);
3851 let people = CallSpec::People {
4822 let people = CallSpec::People {
3852 callees: vec![Callee { mri: "8:orgid:b".into(), display_name: "Bea".into() }],
4823 callees: vec![Callee {
4824 mri: "8:orgid:b".into(),
4825 display_name: "Bea".into(),
4826 }],
3853 thread_id: "19:t@thread.v2".into(),
4827 thread_id: "19:t@thread.v2".into(),
3854 };
4828 };
3855 assert!(people.is_people() && !people.is_meeting());
4829 assert!(people.is_people() && !people.is_meeting());
3856 assert!(matches!(people.target(), InviteTarget::People { thread_id, .. } if thread_id == "19:t@thread.v2"));
4830 assert!(
4831 matches!(people.target(), InviteTarget::People { thread_id, .. } if thread_id == "19:t@thread.v2")
4832 );
3857 let meeting = CallSpec::Meeting(MeetingTarget {
4833 let meeting = CallSpec::Meeting(MeetingTarget {
3858 thread_id: "19:meeting@thread.v2".into(),
4834 thread_id: "19:meeting@thread.v2".into(),
3859 tenant_id: "t".into(),
4835 tenant_id: "t".into(),
crates/calling/src/camera.rs +544 −79
@@ -1,28 +1,36 @@
1 use std::process::Command;
1 2 use std::sync::Arc;
2 use std::time::Duration;
3 use std::sync::atomic::{AtomicU64, Ordering};
4 use std::time::{Duration, Instant};
3 5
4 6 use libwebrtc::native::yuv_helper::{abgr_to_i420, nv12_to_i420};
5 7 use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};
6 8 use nokhwa::pixel_format::RgbAFormat;
7 use nokhwa::utils::{ApiBackend, CameraFormat, CameraIndex, FrameFormat, RequestedFormat, RequestedFormatType, Resolution};
9 use nokhwa::utils::{
10 ApiBackend, CameraFormat, CameraIndex, FrameFormat, RequestedFormat, RequestedFormatType,
11 Resolution,
12 };
8 13 use nokhwa::{Camera, query};
9 use std::sync::atomic::Ordering;
14 use zune_core::bytestream::ZCursor;
15 use zune_core::colorspace::ColorSpace;
16 use zune_core::options::DecoderOptions;
17 use zune_jpeg::JpegDecoder;
10 18
11 19 use crate::blur::BlurSettings;
12 use crate::effects::EffectsThread;
13 20 use crate::capture::Capture;
14 21 use crate::devices::{DeviceChoice, DeviceEntry};
22 use crate::effects::EffectsThread;
15 23 use crate::error::{Error, Result};
24 use crate::video_quality::VideoQuality;
16 25
17 26 const RETRY_PAUSE: Duration = Duration::from_millis(20);
18 27 const BYTES_PER_PIXEL: u32 = 4;
19 const CAPTURE_WIDTH: u32 = 1280;
20 const CAPTURE_HEIGHT: u32 = 720;
21 28 const CAPTURE_FPS: u32 = 30;
22 const LARGEST_DOWNSCALED_HEIGHT: u32 = 1080;
23 29 const ASPECT_WIDTH: u32 = 16;
24 30 const ASPECT_HEIGHT: u32 = 9;
25 31 const DIRECT_FORMATS: [FrameFormat; 2] = [FrameFormat::NV12, FrameFormat::YUYV];
32 const USABLE_FORMATS: [FrameFormat; 3] =
33 [FrameFormat::NV12, FrameFormat::YUYV, FrameFormat::MJPEG];
26 34
27 35 #[derive(Debug, Clone, PartialEq, Eq)]
28 36 pub struct CameraDevice {
@@ -30,6 +38,72 @@ pub struct CameraDevice {
30 38 pub name: String,
31 39 }
32 40
41 /// Shared capture counters for call-report stats (format + fps + decode time).
42 #[derive(Debug, Default)]
43 pub struct CameraCaptureStats {
44 format: std::sync::Mutex<String>,
45 started: std::sync::Mutex<Option<Instant>>,
46 frames: AtomicU64,
47 decode_ns: AtomicU64,
48 }
49
50 impl CameraCaptureStats {
51 pub fn new() -> Arc<Self> {
52 Arc::new(Self::default())
53 }
54
55 fn set_format(&self, label: impl Into<String>) {
56 if let Ok(mut slot) = self.format.lock() {
57 *slot = label.into();
58 }
59 if let Ok(mut started) = self.started.lock() {
60 *started = Some(Instant::now());
61 }
62 self.frames.store(0, Ordering::Relaxed);
63 self.decode_ns.store(0, Ordering::Relaxed);
64 }
65
66 fn note_frame(&self, decode: Duration) {
67 self.frames.fetch_add(1, Ordering::Relaxed);
68 self.decode_ns
69 .fetch_add(decode.as_nanos() as u64, Ordering::Relaxed);
70 }
71
72 pub fn format_label(&self) -> String {
73 self.format
74 .lock()
75 .map(|label| label.clone())
76 .unwrap_or_default()
77 }
78
79 pub fn summary(&self) -> Option<String> {
80 let label = self.format_label();
81 if label.is_empty() {
82 return None;
83 }
84 let frames = self.frames.load(Ordering::Relaxed);
85 let decode_ns = self.decode_ns.load(Ordering::Relaxed);
86 let decode_ms = if frames == 0 {
87 0.0
88 } else {
89 (decode_ns as f64 / frames as f64) / 1_000_000.0
90 };
91 let fps = self
92 .started
93 .lock()
94 .ok()
95 .and_then(|started| *started)
96 .map(|started| {
97 let seconds = started.elapsed().as_secs_f64().max(0.001);
98 frames as f64 / seconds
99 })
100 .unwrap_or(0.0);
101 Some(format!(
102 " camera={label} capture={fps:.1}fps decode={decode_ms:.1}ms"
103 ))
104 }
105 }
106
33 107 pub fn list_cameras() -> Vec<CameraDevice> {
34 108 query(ApiBackend::Auto)
35 109 .unwrap_or_default()
@@ -47,7 +121,9 @@ pub fn list_cameras() -> Vec<CameraDevice> {
47 121 fn camera_index(choice: &DeviceChoice) -> CameraIndex {
48 122 match choice {
49 123 DeviceChoice::SystemDefault => CameraIndex::Index(0),
50 DeviceChoice::Device(key) => key.parse().map_or_else(|_| CameraIndex::String(key.clone()), CameraIndex::Index),
124 DeviceChoice::Device(key) => key
125 .parse()
126 .map_or_else(|_| CameraIndex::String(key.clone()), CameraIndex::Index),
51 127 }
52 128 }
53 129
@@ -72,44 +148,97 @@ pub fn i420_from_rgba(rgba: &[u8], width: u32, height: u32) -> I420Buffer {
72 148
73 149 fn format_rank(frame_format: FrameFormat) -> u8 {
74 150 match frame_format {
75 FrameFormat::NV12 => 1,
151 FrameFormat::NV12 => 3,
152 FrameFormat::YUYV => 2,
153 FrameFormat::MJPEG => 1,
76 154 _ => 0,
77 155 }
78 156 }
79 157
158 fn format_short_name(frame_format: FrameFormat) -> String {
159 match frame_format {
160 FrameFormat::MJPEG => "MJPG".into(),
161 FrameFormat::NV12 => "NV12".into(),
162 FrameFormat::YUYV => "YUYV".into(),
163 other => other.to_string(),
164 }
165 }
166
167 fn format_label(format: &CameraFormat) -> String {
168 format!(
169 "{} {}x{} @{}",
170 format_short_name(format.format()),
171 format.width(),
172 format.height(),
173 format.frame_rate()
174 )
175 }
176
80 177 fn is_widescreen(width: u32, height: u32) -> bool {
81 178 width * ASPECT_HEIGHT == height * ASPECT_WIDTH
82 179 }
83 180
84 fn widescreen_tier(format: &CameraFormat) -> u8 {
85 match (is_widescreen(format.width(), format.height()), format.height()) {
86 (true, CAPTURE_HEIGHT) => 3,
87 (true, height) if height > CAPTURE_HEIGHT => 2,
181 fn widescreen_tier(format: &CameraFormat, capture_height: u32) -> u8 {
182 match (
183 is_widescreen(format.width(), format.height()),
184 format.height(),
185 ) {
186 (true, height) if height == capture_height => 3,
187 (true, height) if height > capture_height => 2,
88 188 (true, _) => 1,
89 189 (false, _) => 0,
90 190 }
91 191 }
92 192
93 fn pick_format(formats: &[CameraFormat]) -> Option<CameraFormat> {
193 fn pick_format(formats: &[CameraFormat], quality: VideoQuality) -> Option<CameraFormat> {
194 let capture_height = quality.capture_height();
195 let largest = quality.largest_sensor_height();
94 196 formats
95 197 .iter()
96 198 .copied()
97 .filter(|format| DIRECT_FORMATS.contains(&format.format()))
199 .filter(|format| USABLE_FORMATS.contains(&format.format()))
98 200 .filter(|format| format.frame_rate() >= CAPTURE_FPS)
99 201 .filter(|format| {
100 format.height() <= CAPTURE_HEIGHT
101 || (is_widescreen(format.width(), format.height()) && format.height() <= LARGEST_DOWNSCALED_HEIGHT)
202 format.height() <= capture_height
203 || (is_widescreen(format.width(), format.height()) && format.height() <= largest)
102 204 })
103 205 .max_by_key(|format| {
104 206 (
105 widescreen_tier(format),
106 std::cmp::Reverse(format.height().abs_diff(CAPTURE_HEIGHT)),
207 widescreen_tier(format, capture_height),
208 std::cmp::Reverse(format.height().abs_diff(capture_height)),
107 209 format_rank(format.format()),
108 210 std::cmp::Reverse(format.frame_rate()),
109 211 )
110 212 })
111 213 }
112 214
215 fn candidate_heights(quality: VideoQuality) -> Vec<u32> {
216 match quality {
217 VideoQuality::P720 => vec![720, 540, 360],
218 VideoQuality::Auto | VideoQuality::P1080 => vec![1080, 720, 540, 360],
219 }
220 }
221
222 fn preferred_candidates(quality: VideoQuality) -> Vec<CameraFormat> {
223 let mut candidates = Vec::new();
224 for height in candidate_heights(quality) {
225 let width = height * ASPECT_WIDTH / ASPECT_HEIGHT;
226 candidates.push(CameraFormat::new(
227 Resolution::new(width, height),
228 FrameFormat::MJPEG,
229 CAPTURE_FPS,
230 ));
231 for frame_format in DIRECT_FORMATS {
232 candidates.push(CameraFormat::new(
233 Resolution::new(width, height),
234 frame_format,
235 CAPTURE_FPS,
236 ));
237 }
238 }
239 candidates
240 }
241
113 242 fn even(value: u32) -> u32 {
114 243 value & !1
115 244 }
@@ -119,13 +248,34 @@ fn crop_i420(buffer: &I420Buffer, left: u32, top: u32, width: u32, height: u32)
119 248 let (source_strides, source_planes) = (buffer.strides(), buffer.data());
120 249 let (target_strides, target_planes) = (cropped.strides(), cropped.data_mut());
121 250 let planes = [
122 (source_planes.0, source_strides.0, target_planes.0, target_strides.0, 1),
123 (source_planes.1, source_strides.1, target_planes.1, target_strides.1, 2),
124 (source_planes.2, source_strides.2, target_planes.2, target_strides.2, 2),
251 (
252 source_planes.0,
253 source_strides.0,
254 target_planes.0,
255 target_strides.0,
256 1,
257 ),
258 (
259 source_planes.1,
260 source_strides.1,
261 target_planes.1,
262 target_strides.1,
263 2,
264 ),
265 (
266 source_planes.2,
267 source_strides.2,
268 target_planes.2,
269 target_strides.2,
270 2,
271 ),
125 272 ];
126 273 for (source, source_stride, target, target_stride, divisor) in planes {
127 274 let (plane_left, plane_top) = ((left / divisor) as usize, (top / divisor) as usize);
128 let (plane_width, plane_height) = (width.div_ceil(divisor) as usize, height.div_ceil(divisor) as usize);
275 let (plane_width, plane_height) = (
276 width.div_ceil(divisor) as usize,
277 height.div_ceil(divisor) as usize,
278 );
129 279 for row in 0..plane_height {
130 280 let from = (plane_top + row) * source_stride as usize + plane_left;
131 281 let to = row * target_stride as usize;
@@ -135,7 +285,8 @@ fn crop_i420(buffer: &I420Buffer, left: u32, top: u32, width: u32, height: u32)
135 285 cropped
136 286 }
137 287
138 pub(crate) fn fit_widescreen(mut buffer: I420Buffer) -> I420Buffer {
288 pub(crate) fn fit_widescreen(mut buffer: I420Buffer, quality: VideoQuality) -> I420Buffer {
289 let capture_height = quality.capture_height();
139 290 let (width, height) = (buffer.width(), buffer.height());
140 291 let (crop_width, crop_height) = if width * ASPECT_HEIGHT > height * ASPECT_WIDTH {
141 292 (even(height * ASPECT_WIDTH / ASPECT_HEIGHT), height)
@@ -143,44 +294,135 @@ pub(crate) fn fit_widescreen(mut buffer: I420Buffer) -> I420Buffer {
143 294 (width, even(width * ASPECT_HEIGHT / ASPECT_WIDTH))
144 295 };
145 296 if (crop_width, crop_height) != (width, height) && crop_width >= 2 && crop_height >= 2 {
146 buffer = crop_i420(&buffer, even((width - crop_width) / 2), even((height - crop_height) / 2), crop_width, crop_height);
297 buffer = crop_i420(
298 &buffer,
299 even((width - crop_width) / 2),
300 even((height - crop_height) / 2),
301 crop_width,
302 crop_height,
303 );
147 304 }
148 305 let (width, height) = (buffer.width(), buffer.height());
149 if height > CAPTURE_HEIGHT {
150 let scaled_width = even(width * CAPTURE_HEIGHT / height);
151 return buffer.scale(scaled_width as i32, CAPTURE_HEIGHT as i32);
306 if height > capture_height {
307 let scaled_width = even(width * capture_height / height);
308 return buffer.scale(scaled_width as i32, capture_height as i32);
152 309 }
153 310 buffer
154 311 }
155 312
156 fn open_picked_format(index: CameraIndex) -> std::result::Result<Camera, nokhwa::NokhwaError> {
157 let mut camera = Camera::new(index, RequestedFormat::new::<RgbAFormat>(RequestedFormatType::AbsoluteHighestFrameRate))?;
158 let formats = camera.compatible_camera_formats()?;
159 let format = pick_format(&formats).ok_or_else(|| nokhwa::NokhwaError::GeneralError("no raw camera format at 30 fps".to_owned()))?;
160 camera.set_camera_requset(RequestedFormat::new::<RgbAFormat>(RequestedFormatType::Exact(format)))?;
313 fn open_with_request(
314 index: CameraIndex,
315 request: RequestedFormatType,
316 ) -> std::result::Result<Camera, nokhwa::NokhwaError> {
317 let format = RequestedFormat::new::<RgbAFormat>(request);
318 let mut camera = Camera::new(index, format)?;
161 319 camera.open_stream()?;
162 320 Ok(camera)
163 321 }
164 322
165 fn open_camera(index: CameraIndex) -> std::result::Result<Camera, nokhwa::NokhwaError> {
166 if let Ok(camera) = open_picked_format(index.clone()) {
167 return Ok(camera);
323 fn device_path(index: &CameraIndex) -> Option<String> {
324 match index {
325 CameraIndex::Index(number) => Some(format!("/dev/video{number}")),
326 CameraIndex::String(text) if text.starts_with("/dev/") => Some(text.clone()),
327 CameraIndex::String(text) if text.chars().all(|c| c.is_ascii_digit()) => {
328 Some(format!("/dev/video{text}"))
329 }
330 CameraIndex::String(text) if text.starts_with("video") => Some(format!("/dev/{text}")),
331 _ => None,
168 332 }
169 let wanted = Resolution::new(CAPTURE_WIDTH, CAPTURE_HEIGHT);
170 let mut requests: Vec<RequestedFormatType> = DIRECT_FORMATS
171 .into_iter()
172 .map(|frame_format| RequestedFormatType::Closest(CameraFormat::new(wanted, frame_format, CAPTURE_FPS)))
173 .collect();
174 requests.push(RequestedFormatType::AbsoluteHighestFrameRate);
333 }
334
335 fn tune_uvc_controls(index: &CameraIndex) {
336 let Some(device) = device_path(index) else {
337 return;
338 };
339 // Best effort: fixed frame rate (no auto-drop in low light) and 50 Hz mains (CH).
340 let _ = Command::new("v4l2-ctl")
341 .args([
342 "-d",
343 &device,
344 "-c",
345 "exposure_dynamic_framerate=0,power_line_frequency=1",
346 ])
347 .stdout(std::process::Stdio::null())
348 .stderr(std::process::Stdio::null())
349 .status();
350 }
351
352 fn accept_opened(index: &CameraIndex, mut camera: Camera) -> Option<(Camera, String)> {
353 let got = camera.camera_format();
354 if got.frame_rate() < CAPTURE_FPS {
355 let _ = camera.stop_stream();
356 return None;
357 }
358 tune_uvc_controls(index);
359 let label = format_label(&got);
360 Some((camera, label))
361 }
362
363 fn try_exact_or_closest(
364 index: CameraIndex,
365 format: CameraFormat,
366 ) -> std::result::Result<Camera, nokhwa::NokhwaError> {
367 match open_with_request(index.clone(), RequestedFormatType::Exact(format)) {
368 Ok(camera) => Ok(camera),
369 Err(_) => open_with_request(index, RequestedFormatType::Closest(format)),
370 }
371 }
372
373 fn open_from_list(
374 index: CameraIndex,
375 quality: VideoQuality,
376 formats: &[CameraFormat],
377 ) -> Option<(Camera, String)> {
378 let Some(wanted) = pick_format(formats, quality) else {
379 return None;
380 };
381 let camera = try_exact_or_closest(index.clone(), wanted).ok()?;
382 accept_opened(&index, camera)
383 }
384
385 fn open_camera(
386 index: CameraIndex,
387 quality: VideoQuality,
388 ) -> std::result::Result<(Camera, String), nokhwa::NokhwaError> {
389 // Probe the device list without committing to a slow Closest(NV12) open.
390 for probe in preferred_candidates(quality) {
391 let Ok(mut camera) = try_exact_or_closest(index.clone(), probe) else {
392 continue;
393 };
394 if let Ok(formats) = camera.compatible_camera_formats() {
395 let _ = camera.stop_stream();
396 drop(camera);
397 if let Some(opened) = open_from_list(index.clone(), quality, &formats) {
398 return Ok(opened);
399 }
400 } else if let Some(opened) = accept_opened(&index, camera) {
401 return Ok(opened);
402 }
403 }
404
175 405 let mut last_error = None;
176 for request in requests {
177 let format = RequestedFormat::new::<RgbAFormat>(request);
178 match Camera::new(index.clone(), format).and_then(|mut camera| camera.open_stream().map(|()| camera)) {
179 Ok(camera) => return Ok(camera),
406 for candidate in preferred_candidates(quality) {
407 match try_exact_or_closest(index.clone(), candidate) {
408 Ok(camera) => {
409 if let Some(opened) = accept_opened(&index, camera) {
410 return Ok(opened);
411 }
412 }
180 413 Err(error) => last_error = Some(error),
181 414 }
182 415 }
183 Err(last_error.expect("at least one request"))
416
417 // Last resort: AbsoluteHighest may still yield a usable stream on odd backends.
418 match open_with_request(index.clone(), RequestedFormatType::AbsoluteHighestFrameRate) {
419 Ok(camera) => {
420 tune_uvc_controls(&index);
421 let label = format_label(&camera.camera_format());
422 Ok((camera, label))
423 }
424 Err(error) => Err(last_error.unwrap_or(error)),
425 }
184 426 }
185 427
186 428 pub(crate) fn i420_from_nv12(data: &[u8], width: u32, height: u32) -> Option<I420Buffer> {
@@ -192,7 +434,20 @@ pub(crate) fn i420_from_nv12(data: &[u8], width: u32, height: u32) -> Option<I42
192 434 let (stride_y, stride_u, stride_v) = buffer.strides();
193 435 let (plane_y, plane_u, plane_v) = buffer.data_mut();
194 436 let (source_y, source_uv) = data.split_at(luma_len);
195 nv12_to_i420(source_y, width, source_uv, width, plane_y, stride_y, plane_u, stride_u, plane_v, stride_v, width as i32, height as i32);
437 nv12_to_i420(
438 source_y,
439 width,
440 source_uv,
441 width,
442 plane_y,
443 stride_y,
444 plane_u,
445 stride_u,
446 plane_v,
447 stride_v,
448 width as i32,
449 height as i32,
450 );
196 451 Some(buffer)
197 452 }
198 453
@@ -227,31 +482,69 @@ pub(crate) fn i420_from_yuyv(data: &[u8], width: u32, height: u32) -> Option<I42
227 482 Some(buffer)
228 483 }
229 484
230 fn direct_i420(frame_format: FrameFormat, data: &[u8], width: u32, height: u32) -> Option<I420Buffer> {
485 fn i420_from_mjpeg(data: &[u8], rgba_scratch: &mut Vec<u8>) -> Option<(I420Buffer, u32, u32)> {
486 let options = DecoderOptions::default().jpeg_set_out_colorspace(ColorSpace::RGBA);
487 let mut decoder = JpegDecoder::new_with_options(ZCursor::new(data), options);
488 let pixels = decoder.decode().ok()?;
489 let info = decoder.info()?;
490 let (width, height) = (u32::from(info.width), u32::from(info.height));
491 if width < 2 || height < 2 || width % 2 != 0 || height % 2 != 0 {
492 return None;
493 }
494 let rgba_len = (width * height * BYTES_PER_PIXEL) as usize;
495 let rgba = if pixels.len() == rgba_len {
496 pixels.as_slice()
497 } else if pixels.len() == (width * height * 3) as usize {
498 rgba_scratch.clear();
499 rgba_scratch.reserve(rgba_len);
500 for chunk in pixels.chunks_exact(3) {
501 rgba_scratch.extend_from_slice(&[chunk[0], chunk[1], chunk[2], 255]);
502 }
503 rgba_scratch.as_slice()
504 } else {
505 return None;
506 };
507 Some((i420_from_rgba(rgba, width, height), width, height))
508 }
509
510 fn direct_i420(
511 frame_format: FrameFormat,
512 data: &[u8],
513 width: u32,
514 height: u32,
515 rgba_scratch: &mut Vec<u8>,
516 ) -> Option<I420Buffer> {
231 517 match frame_format {
232 518 FrameFormat::NV12 => i420_from_nv12(data, width, height),
233 519 FrameFormat::YUYV => i420_from_yuyv(data, width, height),
520 FrameFormat::MJPEG => i420_from_mjpeg(data, rgba_scratch).map(|(buffer, _, _)| buffer),
234 521 _ => None,
235 522 }
236 523 }
237 524
238 525 pub fn start_camera(
239 526 choice: &DeviceChoice,
527 quality: VideoQuality,
240 528 blur: Arc<BlurSettings>,
529 stats: Arc<CameraCaptureStats>,
530 on_opened: impl FnOnce(String) + Send + 'static,
241 531 deliver: impl FnMut(I420Buffer) + Send + 'static,
242 532 failed: impl FnOnce(String) + Send + 'static,
243 533 ) -> Result<Capture> {
244 534 let index = camera_index(choice);
245 535 Capture::spawn_thread("camera", move |stop| {
246 let mut camera = match open_camera(index) {
247 Ok(camera) => camera,
536 let (mut camera, label) = match open_camera(index, quality) {
537 Ok(opened) => opened,
248 538 Err(error) => return failed(error.to_string()),
249 539 };
540 stats.set_format(&label);
541 on_opened(label);
250 542 let effects = match EffectsThread::spawn(blur, deliver) {
251 543 Ok(effects) => effects,
252 544 Err(error) => return failed(format!("effects thread: {error}")),
253 545 };
254 546 let mut warned_undecodable = false;
547 let mut rgba_scratch = Vec::new();
255 548 while !stop.load(Ordering::SeqCst) {
256 549 let Ok(frame) = camera.frame() else {
257 550 std::thread::sleep(RETRY_PAUSE);
@@ -262,19 +555,30 @@ pub fn start_camera(
262 555 if width < 2 || height < 2 || width % 2 != 0 || height % 2 != 0 {
263 556 continue;
264 557 }
265 let buffer = match direct_i420(frame.source_frame_format(), frame.buffer(), width, height) {
558 let started = Instant::now();
559 let buffer = match direct_i420(
560 frame.source_frame_format(),
561 frame.buffer(),
562 width,
563 height,
564 &mut rgba_scratch,
565 ) {
266 566 Some(buffer) => buffer,
267 567 None => {
268 568 let Ok(decoded) = frame.decode_image::<RgbAFormat>() else {
269 569 if !std::mem::replace(&mut warned_undecodable, true) {
270 eprintln!("calls: camera delivers {} and no decoder is available", frame.source_frame_format());
570 eprintln!(
571 "calls: camera delivers {} and no decoder is available",
572 frame.source_frame_format()
573 );
271 574 }
272 575 continue;
273 576 };
274 577 i420_from_rgba(&decoded.into_raw(), width, height)
275 578 }
276 579 };
277 effects.submit(fit_widescreen(buffer));
580 stats.note_frame(started.elapsed());
581 effects.submit(fit_widescreen(buffer, quality));
278 582 }
279 583 let _ = camera.stop_stream();
280 584 })
@@ -305,8 +609,14 @@ mod tests {
305 609 #[test]
306 610 fn the_default_camera_comes_first_and_unnamed_ones_are_hidden() {
307 611 let cameras = [
308 CameraDevice { key: "0".into(), name: "Integrated Camera".into() },
309 CameraDevice { key: "1".into(), name: " ".into() },
612 CameraDevice {
613 key: "0".into(),
614 name: "Integrated Camera".into(),
615 },
616 CameraDevice {
617 key: "1".into(),
618 name: " ".into(),
619 },
310 620 ];
311 621 let entries = camera_entries(&cameras);
312 622 assert_eq!(entries.len(), 2);
@@ -339,40 +649,102 @@ mod tests {
339 649 }
340 650
341 651 #[test]
342 fn a_c920_like_list_picks_the_raw_format_that_runs_at_30_fps() {
652 fn a_c920_like_list_picks_hd_mjpeg_at_30_fps_over_slow_raw() {
343 653 let formats = [
344 654 format(1280, 720, FrameFormat::YUYV, 10),
345 655 format(640, 480, FrameFormat::YUYV, 30),
346 656 format(1280, 720, FrameFormat::MJPEG, 30),
347 657 ];
348 assert_eq!(pick_format(&formats), Some(format(640, 480, FrameFormat::YUYV, 30)));
658 assert_eq!(
659 pick_format(&formats, VideoQuality::P720),
660 Some(format(1280, 720, FrameFormat::MJPEG, 30))
661 );
349 662 }
350 663
351 664 #[test]
352 fn the_largest_height_up_to_720_wins_then_nv12() {
665 fn raw_at_the_same_height_beats_mjpeg() {
666 let formats = [
667 format(1280, 720, FrameFormat::MJPEG, 30),
668 format(1280, 720, FrameFormat::NV12, 30),
669 ];
670 assert_eq!(
671 pick_format(&formats, VideoQuality::P720),
672 Some(format(1280, 720, FrameFormat::NV12, 30))
673 );
674 }
675
676 #[test]
677 fn a_c930e_like_list_picks_mjpeg_1080_for_auto() {
678 let formats = [
679 format(1920, 1080, FrameFormat::YUYV, 5),
680 format(1280, 720, FrameFormat::YUYV, 10),
681 format(640, 360, FrameFormat::YUYV, 30),
682 format(1920, 1080, FrameFormat::MJPEG, 30),
683 format(1280, 720, FrameFormat::MJPEG, 30),
684 format(960, 540, FrameFormat::MJPEG, 30),
685 ];
686 assert_eq!(
687 pick_format(&formats, VideoQuality::Auto),
688 Some(format(1920, 1080, FrameFormat::MJPEG, 30))
689 );
690 assert_eq!(
691 pick_format(&formats, VideoQuality::P720),
692 Some(format(1280, 720, FrameFormat::MJPEG, 30))
693 );
694 }
695
696 #[test]
697 fn auto_prefers_1080p_nv12_over_720p() {
353 698 let formats = [
354 699 format(1920, 1080, FrameFormat::NV12, 30),
355 700 format(640, 480, FrameFormat::NV12, 30),
356 701 format(1280, 720, FrameFormat::YUYV, 30),
357 702 format(1280, 720, FrameFormat::NV12, 30),
358 703 ];
359 assert_eq!(pick_format(&formats), Some(format(1280, 720, FrameFormat::NV12, 30)));
704 assert_eq!(
705 pick_format(&formats, VideoQuality::Auto),
706 Some(format(1920, 1080, FrameFormat::NV12, 30))
707 );
708 assert_eq!(
709 pick_format(&formats, VideoQuality::P720),
710 Some(format(1280, 720, FrameFormat::NV12, 30))
711 );
360 712 }
361 713
362 714 #[test]
363 715 fn a_widescreen_format_beats_a_4_3_one_of_the_same_height() {
364 let formats = [format(960, 720, FrameFormat::NV12, 30), format(1280, 720, FrameFormat::YUYV, 30), format(640, 480, FrameFormat::NV12, 30)];
365 assert_eq!(pick_format(&formats), Some(format(1280, 720, FrameFormat::YUYV, 30)));
716 let formats = [
717 format(960, 720, FrameFormat::NV12, 30),
718 format(1280, 720, FrameFormat::YUYV, 30),
719 format(640, 480, FrameFormat::NV12, 30),
720 ];
721 assert_eq!(
722 pick_format(&formats, VideoQuality::P720),
723 Some(format(1280, 720, FrameFormat::YUYV, 30))
724 );
366 725 }
367 726
368 727 #[test]
369 fn without_720p_the_order_is_1080p_then_360p_then_4_3() {
728 fn locked_720_keeps_1080_as_downscale_candidate_but_prefers_exact_720() {
370 729 let full_hd = format(1920, 1080, FrameFormat::NV12, 30);
730 let hd = format(1280, 720, FrameFormat::NV12, 30);
371 731 let small = format(640, 360, FrameFormat::NV12, 30);
372 732 let classic = format(960, 720, FrameFormat::NV12, 30);
373 assert_eq!(pick_format(&[classic, small, full_hd]), Some(full_hd));
374 assert_eq!(pick_format(&[classic, small]), Some(small));
375 assert_eq!(pick_format(&[classic, format(2560, 1440, FrameFormat::NV12, 30)]), Some(classic));
733 assert_eq!(
734 pick_format(&[classic, small, full_hd], VideoQuality::Auto),
735 Some(full_hd)
736 );
737 assert_eq!(
738 pick_format(&[classic, small, full_hd, hd], VideoQuality::P720),
739 Some(hd)
740 );
741 assert_eq!(
742 pick_format(
743 &[classic, format(2560, 1440, FrameFormat::NV12, 30)],
744 VideoQuality::P720
745 ),
746 Some(classic)
747 );
376 748 }
377 749
378 750 fn gradient(width: u32, height: u32) -> I420Buffer {
@@ -390,7 +762,7 @@ mod tests {
390 762
391 763 #[test]
392 764 fn a_4_3_frame_is_centre_cropped_to_16_9() {
393 let cropped = fit_widescreen(gradient(960, 720));
765 let cropped = fit_widescreen(gradient(960, 720), VideoQuality::P720);
394 766 assert_eq!((cropped.width(), cropped.height()), (960, 540));
395 767 let (stride_y, stride_u, _) = cropped.strides();
396 768 let (plane_y, plane_u, _) = cropped.data();
@@ -401,27 +773,120 @@ mod tests {
401 773 }
402 774
403 775 #[test]
404 fn a_widescreen_frame_passes_and_1080p_is_scaled_to_720p() {
405 assert_eq!(fit_widescreen(gradient(1280, 720)).width(), 1280);
406 let scaled = fit_widescreen(gradient(1920, 1080));
776 fn auto_keeps_1080p_and_720_lock_scales_it_down() {
777 assert_eq!(
778 fit_widescreen(gradient(1280, 720), VideoQuality::Auto).width(),
779 1280
780 );
781 let kept = fit_widescreen(gradient(1920, 1080), VideoQuality::Auto);
782 assert_eq!((kept.width(), kept.height()), (1920, 1080));
783 let scaled = fit_widescreen(gradient(1920, 1080), VideoQuality::P720);
407 784 assert_eq!((scaled.width(), scaled.height()), (1280, 720));
408 let wide = fit_widescreen(gradient(2560, 1080));
409 assert_eq!((wide.width(), wide.height()), (1280, 720));
410 let classic = fit_widescreen(gradient(640, 480));
785 let wide = fit_widescreen(gradient(2560, 1440), VideoQuality::Auto);
786 assert_eq!((wide.width(), wide.height()), (1920, 1080));
787 let classic = fit_widescreen(gradient(640, 480), VideoQuality::Auto);
411 788 assert_eq!((classic.width(), classic.height()), (640, 360));
412 789 }
413 790
414 791 #[test]
415 792 fn no_usable_format_picks_nothing() {
416 let formats = [format(1280, 720, FrameFormat::MJPEG, 30), format(1280, 720, FrameFormat::YUYV, 15)];
417 assert_eq!(pick_format(&formats), None);
418 assert_eq!(pick_format(&[]), None);
793 let formats = [
794 format(1280, 720, FrameFormat::MJPEG, 15),
795 format(1280, 720, FrameFormat::YUYV, 15),
796 ];
797 assert_eq!(pick_format(&formats, VideoQuality::Auto), None);
798 assert_eq!(pick_format(&[], VideoQuality::Auto), None);
419 799 }
420 800
421 801 #[test]
422 802 fn camera_choices_map_to_indices_or_names() {
423 assert!(matches!(camera_index(&DeviceChoice::SystemDefault), CameraIndex::Index(0)));
424 assert!(matches!(camera_index(&DeviceChoice::Device("2".into())), CameraIndex::Index(2)));
425 assert!(matches!(camera_index(&DeviceChoice::Device("video0".into())), CameraIndex::String(_)));
803 assert!(matches!(
804 camera_index(&DeviceChoice::SystemDefault),
805 CameraIndex::Index(0)
806 ));
807 assert!(matches!(
808 camera_index(&DeviceChoice::Device("2".into())),
809 CameraIndex::Index(2)
810 ));
811 assert!(matches!(
812 camera_index(&DeviceChoice::Device("video0".into())),
813 CameraIndex::String(_)
814 ));
815 }
816
817 #[test]
818 fn mjpeg_decodes_to_i420() {
819 // Minimal valid grayscale JPEG is awkward; encode via `image` crate.
820 let mut rgb = image::RgbImage::new(16, 16);
821 for pixel in rgb.pixels_mut() {
822 *pixel = image::Rgb([40, 80, 120]);
823 }
824 let mut jpeg = Vec::new();
825 image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, 90)
826 .encode(rgb.as_raw(), 16, 16, image::ExtendedColorType::Rgb8)
827 .expect("encode");
828 let mut scratch = Vec::new();
829 let (buffer, width, height) =
830 i420_from_mjpeg(&jpeg, &mut scratch).expect("mjpeg decodes");
831 assert_eq!((width, height), (16, 16));
832 assert_eq!((buffer.width(), buffer.height()), (16, 16));
833 }
834
835 #[test]
836 #[ignore = "timing; run with --release --ignored"]
837 fn mjpeg_1080p_decode_stays_under_fifteen_ms() {
838 let mut rgb = image::RgbImage::new(1920, 1080);
839 for (index, pixel) in rgb.pixels_mut().enumerate() {
840 let value = (index % 255) as u8;
841 *pixel = image::Rgb([value, value.wrapping_add(40), value.wrapping_add(80)]);
842 }
843 let mut jpeg = Vec::new();
844 image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, 85)
845 .encode(rgb.as_raw(), 1920, 1080, image::ExtendedColorType::Rgb8)
846 .expect("encode");
847 let mut scratch = Vec::new();
848 // Warm caches / CPU, then time a steady batch (30 fps allows ~33 ms/frame).
849 for _ in 0..3 {
850 let _ = i420_from_mjpeg(&jpeg, &mut scratch).expect("decode");
851 }
852 let started = Instant::now();
853 for _ in 0..10 {
854 let _ = i420_from_mjpeg(&jpeg, &mut scratch).expect("decode");
855 }
856 let average = started.elapsed() / 10;
857 assert!(
858 average < Duration::from_millis(20),
859 "average decode {average:?} exceeds 20 ms"
860 );
861 }
862
863 #[test]
864 #[ignore = "needs a connected camera"]
865 fn open_picks_at_least_thirty_fps_when_available() {
866 if list_cameras().is_empty() {
867 return;
868 }
869 let (mut camera, label) = open_camera(CameraIndex::Index(0), VideoQuality::Auto)
870 .expect("camera opens");
871 assert!(
872 camera.camera_format().frame_rate() >= CAPTURE_FPS,
873 "opened {label} under 30 fps"
874 );
875 // Warm up buffers, then count for one second.
876 for _ in 0..10 {
877 let _ = camera.frame();
878 }
879 let deadline = Instant::now() + Duration::from_secs(1);
880 let mut frames = 0u32;
881 while Instant::now() < deadline {
882 if camera.frame().is_ok() {
883 frames += 1;
884 }
885 }
886 let _ = camera.stop_stream();
887 assert!(
888 frames >= 20,
889 "expected >= 20 frames in 1 s from {label}, got {frames}"
890 );
426 891 }
427 892 }
@@ -1,28 +1,36 @@
1use std::process::Command;
1use std::sync::Arc;
2use std::sync::Arc;
2use std::time::Duration;
3use std::sync::atomic::{AtomicU64, Ordering};
4use std::time::{Duration, Instant};
3
5
4use libwebrtc::native::yuv_helper::{abgr_to_i420, nv12_to_i420};
6use libwebrtc::native::yuv_helper::{abgr_to_i420, nv12_to_i420};
5use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};
7use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};
6use nokhwa::pixel_format::RgbAFormat;
8use nokhwa::pixel_format::RgbAFormat;
7use nokhwa::utils::{ApiBackend, CameraFormat, CameraIndex, FrameFormat, RequestedFormat, RequestedFormatType, Resolution};
9use nokhwa::utils::{
10 ApiBackend, CameraFormat, CameraIndex, FrameFormat, RequestedFormat, RequestedFormatType,
11 Resolution,
12};
8use nokhwa::{Camera, query};
13use nokhwa::{Camera, query};
9use std::sync::atomic::Ordering;
14use zune_core::bytestream::ZCursor;
15use zune_core::colorspace::ColorSpace;
16use zune_core::options::DecoderOptions;
17use zune_jpeg::JpegDecoder;
10
18
11use crate::blur::BlurSettings;
19use crate::blur::BlurSettings;
12use crate::effects::EffectsThread;
13use crate::capture::Capture;
20use crate::capture::Capture;
14use crate::devices::{DeviceChoice, DeviceEntry};
21use crate::devices::{DeviceChoice, DeviceEntry};
22use crate::effects::EffectsThread;
15use crate::error::{Error, Result};
23use crate::error::{Error, Result};
24use crate::video_quality::VideoQuality;
16
25
17const RETRY_PAUSE: Duration = Duration::from_millis(20);
26const RETRY_PAUSE: Duration = Duration::from_millis(20);
18const BYTES_PER_PIXEL: u32 = 4;
27const BYTES_PER_PIXEL: u32 = 4;
19const CAPTURE_WIDTH: u32 = 1280;
20const CAPTURE_HEIGHT: u32 = 720;
21const CAPTURE_FPS: u32 = 30;
28const CAPTURE_FPS: u32 = 30;
22const LARGEST_DOWNSCALED_HEIGHT: u32 = 1080;
23const ASPECT_WIDTH: u32 = 16;
29const ASPECT_WIDTH: u32 = 16;
24const ASPECT_HEIGHT: u32 = 9;
30const ASPECT_HEIGHT: u32 = 9;
25const DIRECT_FORMATS: [FrameFormat; 2] = [FrameFormat::NV12, FrameFormat::YUYV];
31const DIRECT_FORMATS: [FrameFormat; 2] = [FrameFormat::NV12, FrameFormat::YUYV];
32const USABLE_FORMATS: [FrameFormat; 3] =
33 [FrameFormat::NV12, FrameFormat::YUYV, FrameFormat::MJPEG];
26
34
27#[derive(Debug, Clone, PartialEq, Eq)]
35#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct CameraDevice {
36pub struct CameraDevice {
@@ -30,6 +38,72 @@ pub struct CameraDevice {
30 pub name: String,
38 pub name: String,
31}
39}
32
40
41/// Shared capture counters for call-report stats (format + fps + decode time).
42#[derive(Debug, Default)]
43pub struct CameraCaptureStats {
44 format: std::sync::Mutex<String>,
45 started: std::sync::Mutex<Option<Instant>>,
46 frames: AtomicU64,
47 decode_ns: AtomicU64,
48}
49
50impl CameraCaptureStats {
51 pub fn new() -> Arc<Self> {
52 Arc::new(Self::default())
53 }
54
55 fn set_format(&self, label: impl Into<String>) {
56 if let Ok(mut slot) = self.format.lock() {
57 *slot = label.into();
58 }
59 if let Ok(mut started) = self.started.lock() {
60 *started = Some(Instant::now());
61 }
62 self.frames.store(0, Ordering::Relaxed);
63 self.decode_ns.store(0, Ordering::Relaxed);
64 }
65
66 fn note_frame(&self, decode: Duration) {
67 self.frames.fetch_add(1, Ordering::Relaxed);
68 self.decode_ns
69 .fetch_add(decode.as_nanos() as u64, Ordering::Relaxed);
70 }
71
72 pub fn format_label(&self) -> String {
73 self.format
74 .lock()
75 .map(|label| label.clone())
76 .unwrap_or_default()
77 }
78
79 pub fn summary(&self) -> Option<String> {
80 let label = self.format_label();
81 if label.is_empty() {
82 return None;
83 }
84 let frames = self.frames.load(Ordering::Relaxed);
85 let decode_ns = self.decode_ns.load(Ordering::Relaxed);
86 let decode_ms = if frames == 0 {
87 0.0
88 } else {
89 (decode_ns as f64 / frames as f64) / 1_000_000.0
90 };
91 let fps = self
92 .started
93 .lock()
94 .ok()
95 .and_then(|started| *started)
96 .map(|started| {
97 let seconds = started.elapsed().as_secs_f64().max(0.001);
98 frames as f64 / seconds
99 })
100 .unwrap_or(0.0);
101 Some(format!(
102 " camera={label} capture={fps:.1}fps decode={decode_ms:.1}ms"
103 ))
104 }
105}
106
33pub fn list_cameras() -> Vec<CameraDevice> {
107pub fn list_cameras() -> Vec<CameraDevice> {
34 query(ApiBackend::Auto)
108 query(ApiBackend::Auto)
35 .unwrap_or_default()
109 .unwrap_or_default()
@@ -47,7 +121,9 @@ pub fn list_cameras() -> Vec<CameraDevice> {
47fn camera_index(choice: &DeviceChoice) -> CameraIndex {
121fn camera_index(choice: &DeviceChoice) -> CameraIndex {
48 match choice {
122 match choice {
49 DeviceChoice::SystemDefault => CameraIndex::Index(0),
123 DeviceChoice::SystemDefault => CameraIndex::Index(0),
50 DeviceChoice::Device(key) => key.parse().map_or_else(|_| CameraIndex::String(key.clone()), CameraIndex::Index),
124 DeviceChoice::Device(key) => key
125 .parse()
126 .map_or_else(|_| CameraIndex::String(key.clone()), CameraIndex::Index),
51 }
127 }
52}
128}
53
129
@@ -72,44 +148,97 @@ pub fn i420_from_rgba(rgba: &[u8], width: u32, height: u32) -> I420Buffer {
72
148
73fn format_rank(frame_format: FrameFormat) -> u8 {
149fn format_rank(frame_format: FrameFormat) -> u8 {
74 match frame_format {
150 match frame_format {
75 FrameFormat::NV12 => 1,
151 FrameFormat::NV12 => 3,
152 FrameFormat::YUYV => 2,
153 FrameFormat::MJPEG => 1,
76 _ => 0,
154 _ => 0,
77 }
155 }
78}
156}
79
157
158fn format_short_name(frame_format: FrameFormat) -> String {
159 match frame_format {
160 FrameFormat::MJPEG => "MJPG".into(),
161 FrameFormat::NV12 => "NV12".into(),
162 FrameFormat::YUYV => "YUYV".into(),
163 other => other.to_string(),
164 }
165}
166
167fn format_label(format: &CameraFormat) -> String {
168 format!(
169 "{} {}x{} @{}",
170 format_short_name(format.format()),
171 format.width(),
172 format.height(),
173 format.frame_rate()
174 )
175}
176
80fn is_widescreen(width: u32, height: u32) -> bool {
177fn is_widescreen(width: u32, height: u32) -> bool {
81 width * ASPECT_HEIGHT == height * ASPECT_WIDTH
178 width * ASPECT_HEIGHT == height * ASPECT_WIDTH
82}
179}
83
180
84fn widescreen_tier(format: &CameraFormat) -> u8 {
181fn widescreen_tier(format: &CameraFormat, capture_height: u32) -> u8 {
85 match (is_widescreen(format.width(), format.height()), format.height()) {
182 match (
86 (true, CAPTURE_HEIGHT) => 3,
183 is_widescreen(format.width(), format.height()),
87 (true, height) if height > CAPTURE_HEIGHT => 2,
184 format.height(),
185 ) {
186 (true, height) if height == capture_height => 3,
187 (true, height) if height > capture_height => 2,
88 (true, _) => 1,
188 (true, _) => 1,
89 (false, _) => 0,
189 (false, _) => 0,
90 }
190 }
91}
191}
92
192
93fn pick_format(formats: &[CameraFormat]) -> Option<CameraFormat> {
193fn pick_format(formats: &[CameraFormat], quality: VideoQuality) -> Option<CameraFormat> {
194 let capture_height = quality.capture_height();
195 let largest = quality.largest_sensor_height();
94 formats
196 formats
95 .iter()
197 .iter()
96 .copied()
198 .copied()
97 .filter(|format| DIRECT_FORMATS.contains(&format.format()))
199 .filter(|format| USABLE_FORMATS.contains(&format.format()))
98 .filter(|format| format.frame_rate() >= CAPTURE_FPS)
200 .filter(|format| format.frame_rate() >= CAPTURE_FPS)
99 .filter(|format| {
201 .filter(|format| {
100 format.height() <= CAPTURE_HEIGHT
202 format.height() <= capture_height
101 || (is_widescreen(format.width(), format.height()) && format.height() <= LARGEST_DOWNSCALED_HEIGHT)
203 || (is_widescreen(format.width(), format.height()) && format.height() <= largest)
102 })
204 })
103 .max_by_key(|format| {
205 .max_by_key(|format| {
104 (
206 (
105 widescreen_tier(format),
207 widescreen_tier(format, capture_height),
106 std::cmp::Reverse(format.height().abs_diff(CAPTURE_HEIGHT)),
208 std::cmp::Reverse(format.height().abs_diff(capture_height)),
107 format_rank(format.format()),
209 format_rank(format.format()),
108 std::cmp::Reverse(format.frame_rate()),
210 std::cmp::Reverse(format.frame_rate()),
109 )
211 )
110 })
212 })
111}
213}
112
214
215fn candidate_heights(quality: VideoQuality) -> Vec<u32> {
216 match quality {
217 VideoQuality::P720 => vec![720, 540, 360],
218 VideoQuality::Auto | VideoQuality::P1080 => vec![1080, 720, 540, 360],
219 }
220}
221
222fn preferred_candidates(quality: VideoQuality) -> Vec<CameraFormat> {
223 let mut candidates = Vec::new();
224 for height in candidate_heights(quality) {
225 let width = height * ASPECT_WIDTH / ASPECT_HEIGHT;
226 candidates.push(CameraFormat::new(
227 Resolution::new(width, height),
228 FrameFormat::MJPEG,
229 CAPTURE_FPS,
230 ));
231 for frame_format in DIRECT_FORMATS {
232 candidates.push(CameraFormat::new(
233 Resolution::new(width, height),
234 frame_format,
235 CAPTURE_FPS,
236 ));
237 }
238 }
239 candidates
240}
241
113fn even(value: u32) -> u32 {
242fn even(value: u32) -> u32 {
114 value & !1
243 value & !1
115}
244}
@@ -119,13 +248,34 @@ fn crop_i420(buffer: &I420Buffer, left: u32, top: u32, width: u32, height: u32)
119 let (source_strides, source_planes) = (buffer.strides(), buffer.data());
248 let (source_strides, source_planes) = (buffer.strides(), buffer.data());
120 let (target_strides, target_planes) = (cropped.strides(), cropped.data_mut());
249 let (target_strides, target_planes) = (cropped.strides(), cropped.data_mut());
121 let planes = [
250 let planes = [
122 (source_planes.0, source_strides.0, target_planes.0, target_strides.0, 1),
251 (
123 (source_planes.1, source_strides.1, target_planes.1, target_strides.1, 2),
252 source_planes.0,
124 (source_planes.2, source_strides.2, target_planes.2, target_strides.2, 2),
253 source_strides.0,
254 target_planes.0,
255 target_strides.0,
256 1,
257 ),
258 (
259 source_planes.1,
260 source_strides.1,
261 target_planes.1,
262 target_strides.1,
263 2,
264 ),
265 (
266 source_planes.2,
267 source_strides.2,
268 target_planes.2,
269 target_strides.2,
270 2,
271 ),
125 ];
272 ];
126 for (source, source_stride, target, target_stride, divisor) in planes {
273 for (source, source_stride, target, target_stride, divisor) in planes {
127 let (plane_left, plane_top) = ((left / divisor) as usize, (top / divisor) as usize);
274 let (plane_left, plane_top) = ((left / divisor) as usize, (top / divisor) as usize);
128 let (plane_width, plane_height) = (width.div_ceil(divisor) as usize, height.div_ceil(divisor) as usize);
275 let (plane_width, plane_height) = (
276 width.div_ceil(divisor) as usize,
277 height.div_ceil(divisor) as usize,
278 );
129 for row in 0..plane_height {
279 for row in 0..plane_height {
130 let from = (plane_top + row) * source_stride as usize + plane_left;
280 let from = (plane_top + row) * source_stride as usize + plane_left;
131 let to = row * target_stride as usize;
281 let to = row * target_stride as usize;
@@ -135,7 +285,8 @@ fn crop_i420(buffer: &I420Buffer, left: u32, top: u32, width: u32, height: u32)
135 cropped
285 cropped
136}
286}
137
287
138pub(crate) fn fit_widescreen(mut buffer: I420Buffer) -> I420Buffer {
288pub(crate) fn fit_widescreen(mut buffer: I420Buffer, quality: VideoQuality) -> I420Buffer {
289 let capture_height = quality.capture_height();
139 let (width, height) = (buffer.width(), buffer.height());
290 let (width, height) = (buffer.width(), buffer.height());
140 let (crop_width, crop_height) = if width * ASPECT_HEIGHT > height * ASPECT_WIDTH {
291 let (crop_width, crop_height) = if width * ASPECT_HEIGHT > height * ASPECT_WIDTH {
141 (even(height * ASPECT_WIDTH / ASPECT_HEIGHT), height)
292 (even(height * ASPECT_WIDTH / ASPECT_HEIGHT), height)
@@ -143,44 +294,135 @@ pub(crate) fn fit_widescreen(mut buffer: I420Buffer) -> I420Buffer {
143 (width, even(width * ASPECT_HEIGHT / ASPECT_WIDTH))
294 (width, even(width * ASPECT_HEIGHT / ASPECT_WIDTH))
144 };
295 };
145 if (crop_width, crop_height) != (width, height) && crop_width >= 2 && crop_height >= 2 {
296 if (crop_width, crop_height) != (width, height) && crop_width >= 2 && crop_height >= 2 {
146 buffer = crop_i420(&buffer, even((width - crop_width) / 2), even((height - crop_height) / 2), crop_width, crop_height);
297 buffer = crop_i420(
298 &buffer,
299 even((width - crop_width) / 2),
300 even((height - crop_height) / 2),
301 crop_width,
302 crop_height,
303 );
147 }
304 }
148 let (width, height) = (buffer.width(), buffer.height());
305 let (width, height) = (buffer.width(), buffer.height());
149 if height > CAPTURE_HEIGHT {
306 if height > capture_height {
150 let scaled_width = even(width * CAPTURE_HEIGHT / height);
307 let scaled_width = even(width * capture_height / height);
151 return buffer.scale(scaled_width as i32, CAPTURE_HEIGHT as i32);
308 return buffer.scale(scaled_width as i32, capture_height as i32);
152 }
309 }
153 buffer
310 buffer
154}
311}
155
312
156fn open_picked_format(index: CameraIndex) -> std::result::Result<Camera, nokhwa::NokhwaError> {
313fn open_with_request(
157 let mut camera = Camera::new(index, RequestedFormat::new::<RgbAFormat>(RequestedFormatType::AbsoluteHighestFrameRate))?;
314 index: CameraIndex,
158 let formats = camera.compatible_camera_formats()?;
315 request: RequestedFormatType,
159 let format = pick_format(&formats).ok_or_else(|| nokhwa::NokhwaError::GeneralError("no raw camera format at 30 fps".to_owned()))?;
316) -> std::result::Result<Camera, nokhwa::NokhwaError> {
160 camera.set_camera_requset(RequestedFormat::new::<RgbAFormat>(RequestedFormatType::Exact(format)))?;
317 let format = RequestedFormat::new::<RgbAFormat>(request);
318 let mut camera = Camera::new(index, format)?;
161 camera.open_stream()?;
319 camera.open_stream()?;
162 Ok(camera)
320 Ok(camera)
163}
321}
164
322
165fn open_camera(index: CameraIndex) -> std::result::Result<Camera, nokhwa::NokhwaError> {
323fn device_path(index: &CameraIndex) -> Option<String> {
166 if let Ok(camera) = open_picked_format(index.clone()) {
324 match index {
167 return Ok(camera);
325 CameraIndex::Index(number) => Some(format!("/dev/video{number}")),
326 CameraIndex::String(text) if text.starts_with("/dev/") => Some(text.clone()),
327 CameraIndex::String(text) if text.chars().all(|c| c.is_ascii_digit()) => {
328 Some(format!("/dev/video{text}"))
329 }
330 CameraIndex::String(text) if text.starts_with("video") => Some(format!("/dev/{text}")),
331 _ => None,
168 }
332 }
169 let wanted = Resolution::new(CAPTURE_WIDTH, CAPTURE_HEIGHT);
333}
170 let mut requests: Vec<RequestedFormatType> = DIRECT_FORMATS
334
171 .into_iter()
335fn tune_uvc_controls(index: &CameraIndex) {
172 .map(|frame_format| RequestedFormatType::Closest(CameraFormat::new(wanted, frame_format, CAPTURE_FPS)))
336 let Some(device) = device_path(index) else {
173 .collect();
337 return;
174 requests.push(RequestedFormatType::AbsoluteHighestFrameRate);
338 };
339 // Best effort: fixed frame rate (no auto-drop in low light) and 50 Hz mains (CH).
340 let _ = Command::new("v4l2-ctl")
341 .args([
342 "-d",
343 &device,
344 "-c",
345 "exposure_dynamic_framerate=0,power_line_frequency=1",
346 ])
347 .stdout(std::process::Stdio::null())
348 .stderr(std::process::Stdio::null())
349 .status();
350}
351
352fn accept_opened(index: &CameraIndex, mut camera: Camera) -> Option<(Camera, String)> {
353 let got = camera.camera_format();
354 if got.frame_rate() < CAPTURE_FPS {
355 let _ = camera.stop_stream();
356 return None;
357 }
358 tune_uvc_controls(index);
359 let label = format_label(&got);
360 Some((camera, label))
361}
362
363fn try_exact_or_closest(
364 index: CameraIndex,
365 format: CameraFormat,
366) -> std::result::Result<Camera, nokhwa::NokhwaError> {
367 match open_with_request(index.clone(), RequestedFormatType::Exact(format)) {
368 Ok(camera) => Ok(camera),
369 Err(_) => open_with_request(index, RequestedFormatType::Closest(format)),
370 }
371}
372
373fn open_from_list(
374 index: CameraIndex,
375 quality: VideoQuality,
376 formats: &[CameraFormat],
377) -> Option<(Camera, String)> {
378 let Some(wanted) = pick_format(formats, quality) else {
379 return None;
380 };
381 let camera = try_exact_or_closest(index.clone(), wanted).ok()?;
382 accept_opened(&index, camera)
383}
384
385fn open_camera(
386 index: CameraIndex,
387 quality: VideoQuality,
388) -> std::result::Result<(Camera, String), nokhwa::NokhwaError> {
389 // Probe the device list without committing to a slow Closest(NV12) open.
390 for probe in preferred_candidates(quality) {
391 let Ok(mut camera) = try_exact_or_closest(index.clone(), probe) else {
392 continue;
393 };
394 if let Ok(formats) = camera.compatible_camera_formats() {
395 let _ = camera.stop_stream();
396 drop(camera);
397 if let Some(opened) = open_from_list(index.clone(), quality, &formats) {
398 return Ok(opened);
399 }
400 } else if let Some(opened) = accept_opened(&index, camera) {
401 return Ok(opened);
402 }
403 }
404
175 let mut last_error = None;
405 let mut last_error = None;
176 for request in requests {
406 for candidate in preferred_candidates(quality) {
177 let format = RequestedFormat::new::<RgbAFormat>(request);
407 match try_exact_or_closest(index.clone(), candidate) {
178 match Camera::new(index.clone(), format).and_then(|mut camera| camera.open_stream().map(|()| camera)) {
408 Ok(camera) => {
179 Ok(camera) => return Ok(camera),
409 if let Some(opened) = accept_opened(&index, camera) {
410 return Ok(opened);
411 }
412 }
180 Err(error) => last_error = Some(error),
413 Err(error) => last_error = Some(error),
181 }
414 }
182 }
415 }
183 Err(last_error.expect("at least one request"))
416
417 // Last resort: AbsoluteHighest may still yield a usable stream on odd backends.
418 match open_with_request(index.clone(), RequestedFormatType::AbsoluteHighestFrameRate) {
419 Ok(camera) => {
420 tune_uvc_controls(&index);
421 let label = format_label(&camera.camera_format());
422 Ok((camera, label))
423 }
424 Err(error) => Err(last_error.unwrap_or(error)),
425 }
184}
426}
185
427
186pub(crate) fn i420_from_nv12(data: &[u8], width: u32, height: u32) -> Option<I420Buffer> {
428pub(crate) fn i420_from_nv12(data: &[u8], width: u32, height: u32) -> Option<I420Buffer> {
@@ -192,7 +434,20 @@ pub(crate) fn i420_from_nv12(data: &[u8], width: u32, height: u32) -> Option<I42
192 let (stride_y, stride_u, stride_v) = buffer.strides();
434 let (stride_y, stride_u, stride_v) = buffer.strides();
193 let (plane_y, plane_u, plane_v) = buffer.data_mut();
435 let (plane_y, plane_u, plane_v) = buffer.data_mut();
194 let (source_y, source_uv) = data.split_at(luma_len);
436 let (source_y, source_uv) = data.split_at(luma_len);
195 nv12_to_i420(source_y, width, source_uv, width, plane_y, stride_y, plane_u, stride_u, plane_v, stride_v, width as i32, height as i32);
437 nv12_to_i420(
438 source_y,
439 width,
440 source_uv,
441 width,
442 plane_y,
443 stride_y,
444 plane_u,
445 stride_u,
446 plane_v,
447 stride_v,
448 width as i32,
449 height as i32,
450 );
196 Some(buffer)
451 Some(buffer)
197}
452}
198
453
@@ -227,31 +482,69 @@ pub(crate) fn i420_from_yuyv(data: &[u8], width: u32, height: u32) -> Option<I42
227 Some(buffer)
482 Some(buffer)
228}
483}
229
484
230fn direct_i420(frame_format: FrameFormat, data: &[u8], width: u32, height: u32) -> Option<I420Buffer> {
485fn i420_from_mjpeg(data: &[u8], rgba_scratch: &mut Vec<u8>) -> Option<(I420Buffer, u32, u32)> {
486 let options = DecoderOptions::default().jpeg_set_out_colorspace(ColorSpace::RGBA);
487 let mut decoder = JpegDecoder::new_with_options(ZCursor::new(data), options);
488 let pixels = decoder.decode().ok()?;
489 let info = decoder.info()?;
490 let (width, height) = (u32::from(info.width), u32::from(info.height));
491 if width < 2 || height < 2 || width % 2 != 0 || height % 2 != 0 {
492 return None;
493 }
494 let rgba_len = (width * height * BYTES_PER_PIXEL) as usize;
495 let rgba = if pixels.len() == rgba_len {
496 pixels.as_slice()
497 } else if pixels.len() == (width * height * 3) as usize {
498 rgba_scratch.clear();
499 rgba_scratch.reserve(rgba_len);
500 for chunk in pixels.chunks_exact(3) {
501 rgba_scratch.extend_from_slice(&[chunk[0], chunk[1], chunk[2], 255]);
502 }
503 rgba_scratch.as_slice()
504 } else {
505 return None;
506 };
507 Some((i420_from_rgba(rgba, width, height), width, height))
508}
509
510fn direct_i420(
511 frame_format: FrameFormat,
512 data: &[u8],
513 width: u32,
514 height: u32,
515 rgba_scratch: &mut Vec<u8>,
516) -> Option<I420Buffer> {
231 match frame_format {
517 match frame_format {
232 FrameFormat::NV12 => i420_from_nv12(data, width, height),
518 FrameFormat::NV12 => i420_from_nv12(data, width, height),
233 FrameFormat::YUYV => i420_from_yuyv(data, width, height),
519 FrameFormat::YUYV => i420_from_yuyv(data, width, height),
520 FrameFormat::MJPEG => i420_from_mjpeg(data, rgba_scratch).map(|(buffer, _, _)| buffer),
234 _ => None,
521 _ => None,
235 }
522 }
236}
523}
237
524
238pub fn start_camera(
525pub fn start_camera(
239 choice: &DeviceChoice,
526 choice: &DeviceChoice,
527 quality: VideoQuality,
240 blur: Arc<BlurSettings>,
528 blur: Arc<BlurSettings>,
529 stats: Arc<CameraCaptureStats>,
530 on_opened: impl FnOnce(String) + Send + 'static,
241 deliver: impl FnMut(I420Buffer) + Send + 'static,
531 deliver: impl FnMut(I420Buffer) + Send + 'static,
242 failed: impl FnOnce(String) + Send + 'static,
532 failed: impl FnOnce(String) + Send + 'static,
243) -> Result<Capture> {
533) -> Result<Capture> {
244 let index = camera_index(choice);
534 let index = camera_index(choice);
245 Capture::spawn_thread("camera", move |stop| {
535 Capture::spawn_thread("camera", move |stop| {
246 let mut camera = match open_camera(index) {
536 let (mut camera, label) = match open_camera(index, quality) {
247 Ok(camera) => camera,
537 Ok(opened) => opened,
248 Err(error) => return failed(error.to_string()),
538 Err(error) => return failed(error.to_string()),
249 };
539 };
540 stats.set_format(&label);
541 on_opened(label);
250 let effects = match EffectsThread::spawn(blur, deliver) {
542 let effects = match EffectsThread::spawn(blur, deliver) {
251 Ok(effects) => effects,
543 Ok(effects) => effects,
252 Err(error) => return failed(format!("effects thread: {error}")),
544 Err(error) => return failed(format!("effects thread: {error}")),
253 };
545 };
254 let mut warned_undecodable = false;
546 let mut warned_undecodable = false;
547 let mut rgba_scratch = Vec::new();
255 while !stop.load(Ordering::SeqCst) {
548 while !stop.load(Ordering::SeqCst) {
256 let Ok(frame) = camera.frame() else {
549 let Ok(frame) = camera.frame() else {
257 std::thread::sleep(RETRY_PAUSE);
550 std::thread::sleep(RETRY_PAUSE);
@@ -262,19 +555,30 @@ pub fn start_camera(
262 if width < 2 || height < 2 || width % 2 != 0 || height % 2 != 0 {
555 if width < 2 || height < 2 || width % 2 != 0 || height % 2 != 0 {
263 continue;
556 continue;
264 }
557 }
265 let buffer = match direct_i420(frame.source_frame_format(), frame.buffer(), width, height) {
558 let started = Instant::now();
559 let buffer = match direct_i420(
560 frame.source_frame_format(),
561 frame.buffer(),
562 width,
563 height,
564 &mut rgba_scratch,
565 ) {
266 Some(buffer) => buffer,
566 Some(buffer) => buffer,
267 None => {
567 None => {
268 let Ok(decoded) = frame.decode_image::<RgbAFormat>() else {
568 let Ok(decoded) = frame.decode_image::<RgbAFormat>() else {
269 if !std::mem::replace(&mut warned_undecodable, true) {
569 if !std::mem::replace(&mut warned_undecodable, true) {
270 eprintln!("calls: camera delivers {} and no decoder is available", frame.source_frame_format());
570 eprintln!(
571 "calls: camera delivers {} and no decoder is available",
572 frame.source_frame_format()
573 );
271 }
574 }
272 continue;
575 continue;
273 };
576 };
274 i420_from_rgba(&decoded.into_raw(), width, height)
577 i420_from_rgba(&decoded.into_raw(), width, height)
275 }
578 }
276 };
579 };
277 effects.submit(fit_widescreen(buffer));
580 stats.note_frame(started.elapsed());
581 effects.submit(fit_widescreen(buffer, quality));
278 }
582 }
279 let _ = camera.stop_stream();
583 let _ = camera.stop_stream();
280 })
584 })
@@ -305,8 +609,14 @@ mod tests {
305 #[test]
609 #[test]
306 fn the_default_camera_comes_first_and_unnamed_ones_are_hidden() {
610 fn the_default_camera_comes_first_and_unnamed_ones_are_hidden() {
307 let cameras = [
611 let cameras = [
308 CameraDevice { key: "0".into(), name: "Integrated Camera".into() },
612 CameraDevice {
309 CameraDevice { key: "1".into(), name: " ".into() },
613 key: "0".into(),
614 name: "Integrated Camera".into(),
615 },
616 CameraDevice {
617 key: "1".into(),
618 name: " ".into(),
619 },
310 ];
620 ];
311 let entries = camera_entries(&cameras);
621 let entries = camera_entries(&cameras);
312 assert_eq!(entries.len(), 2);
622 assert_eq!(entries.len(), 2);
@@ -339,40 +649,102 @@ mod tests {
339 }
649 }
340
650
341 #[test]
651 #[test]
342 fn a_c920_like_list_picks_the_raw_format_that_runs_at_30_fps() {
652 fn a_c920_like_list_picks_hd_mjpeg_at_30_fps_over_slow_raw() {
343 let formats = [
653 let formats = [
344 format(1280, 720, FrameFormat::YUYV, 10),
654 format(1280, 720, FrameFormat::YUYV, 10),
345 format(640, 480, FrameFormat::YUYV, 30),
655 format(640, 480, FrameFormat::YUYV, 30),
346 format(1280, 720, FrameFormat::MJPEG, 30),
656 format(1280, 720, FrameFormat::MJPEG, 30),
347 ];
657 ];
348 assert_eq!(pick_format(&formats), Some(format(640, 480, FrameFormat::YUYV, 30)));
658 assert_eq!(
659 pick_format(&formats, VideoQuality::P720),
660 Some(format(1280, 720, FrameFormat::MJPEG, 30))
661 );
349 }
662 }
350
663
351 #[test]
664 #[test]
352 fn the_largest_height_up_to_720_wins_then_nv12() {
665 fn raw_at_the_same_height_beats_mjpeg() {
666 let formats = [
667 format(1280, 720, FrameFormat::MJPEG, 30),
668 format(1280, 720, FrameFormat::NV12, 30),
669 ];
670 assert_eq!(
671 pick_format(&formats, VideoQuality::P720),
672 Some(format(1280, 720, FrameFormat::NV12, 30))
673 );
674 }
675
676 #[test]
677 fn a_c930e_like_list_picks_mjpeg_1080_for_auto() {
678 let formats = [
679 format(1920, 1080, FrameFormat::YUYV, 5),
680 format(1280, 720, FrameFormat::YUYV, 10),
681 format(640, 360, FrameFormat::YUYV, 30),
682 format(1920, 1080, FrameFormat::MJPEG, 30),
683 format(1280, 720, FrameFormat::MJPEG, 30),
684 format(960, 540, FrameFormat::MJPEG, 30),
685 ];
686 assert_eq!(
687 pick_format(&formats, VideoQuality::Auto),
688 Some(format(1920, 1080, FrameFormat::MJPEG, 30))
689 );
690 assert_eq!(
691 pick_format(&formats, VideoQuality::P720),
692 Some(format(1280, 720, FrameFormat::MJPEG, 30))
693 );
694 }
695
696 #[test]
697 fn auto_prefers_1080p_nv12_over_720p() {
353 let formats = [
698 let formats = [
354 format(1920, 1080, FrameFormat::NV12, 30),
699 format(1920, 1080, FrameFormat::NV12, 30),
355 format(640, 480, FrameFormat::NV12, 30),
700 format(640, 480, FrameFormat::NV12, 30),
356 format(1280, 720, FrameFormat::YUYV, 30),
701 format(1280, 720, FrameFormat::YUYV, 30),
357 format(1280, 720, FrameFormat::NV12, 30),
702 format(1280, 720, FrameFormat::NV12, 30),
358 ];
703 ];
359 assert_eq!(pick_format(&formats), Some(format(1280, 720, FrameFormat::NV12, 30)));
704 assert_eq!(
705 pick_format(&formats, VideoQuality::Auto),
706 Some(format(1920, 1080, FrameFormat::NV12, 30))
707 );
708 assert_eq!(
709 pick_format(&formats, VideoQuality::P720),
710 Some(format(1280, 720, FrameFormat::NV12, 30))
711 );
360 }
712 }
361
713
362 #[test]
714 #[test]
363 fn a_widescreen_format_beats_a_4_3_one_of_the_same_height() {
715 fn a_widescreen_format_beats_a_4_3_one_of_the_same_height() {
364 let formats = [format(960, 720, FrameFormat::NV12, 30), format(1280, 720, FrameFormat::YUYV, 30), format(640, 480, FrameFormat::NV12, 30)];
716 let formats = [
365 assert_eq!(pick_format(&formats), Some(format(1280, 720, FrameFormat::YUYV, 30)));
717 format(960, 720, FrameFormat::NV12, 30),
718 format(1280, 720, FrameFormat::YUYV, 30),
719 format(640, 480, FrameFormat::NV12, 30),
720 ];
721 assert_eq!(
722 pick_format(&formats, VideoQuality::P720),
723 Some(format(1280, 720, FrameFormat::YUYV, 30))
724 );
366 }
725 }
367
726
368 #[test]
727 #[test]
369 fn without_720p_the_order_is_1080p_then_360p_then_4_3() {
728 fn locked_720_keeps_1080_as_downscale_candidate_but_prefers_exact_720() {
370 let full_hd = format(1920, 1080, FrameFormat::NV12, 30);
729 let full_hd = format(1920, 1080, FrameFormat::NV12, 30);
730 let hd = format(1280, 720, FrameFormat::NV12, 30);
371 let small = format(640, 360, FrameFormat::NV12, 30);
731 let small = format(640, 360, FrameFormat::NV12, 30);
372 let classic = format(960, 720, FrameFormat::NV12, 30);
732 let classic = format(960, 720, FrameFormat::NV12, 30);
373 assert_eq!(pick_format(&[classic, small, full_hd]), Some(full_hd));
733 assert_eq!(
374 assert_eq!(pick_format(&[classic, small]), Some(small));
734 pick_format(&[classic, small, full_hd], VideoQuality::Auto),
375 assert_eq!(pick_format(&[classic, format(2560, 1440, FrameFormat::NV12, 30)]), Some(classic));
735 Some(full_hd)
736 );
737 assert_eq!(
738 pick_format(&[classic, small, full_hd, hd], VideoQuality::P720),
739 Some(hd)
740 );
741 assert_eq!(
742 pick_format(
743 &[classic, format(2560, 1440, FrameFormat::NV12, 30)],
744 VideoQuality::P720
745 ),
746 Some(classic)
747 );
376 }
748 }
377
749
378 fn gradient(width: u32, height: u32) -> I420Buffer {
750 fn gradient(width: u32, height: u32) -> I420Buffer {
@@ -390,7 +762,7 @@ mod tests {
390
762
391 #[test]
763 #[test]
392 fn a_4_3_frame_is_centre_cropped_to_16_9() {
764 fn a_4_3_frame_is_centre_cropped_to_16_9() {
393 let cropped = fit_widescreen(gradient(960, 720));
765 let cropped = fit_widescreen(gradient(960, 720), VideoQuality::P720);
394 assert_eq!((cropped.width(), cropped.height()), (960, 540));
766 assert_eq!((cropped.width(), cropped.height()), (960, 540));
395 let (stride_y, stride_u, _) = cropped.strides();
767 let (stride_y, stride_u, _) = cropped.strides();
396 let (plane_y, plane_u, _) = cropped.data();
768 let (plane_y, plane_u, _) = cropped.data();
@@ -401,27 +773,120 @@ mod tests {
401 }
773 }
402
774
403 #[test]
775 #[test]
404 fn a_widescreen_frame_passes_and_1080p_is_scaled_to_720p() {
776 fn auto_keeps_1080p_and_720_lock_scales_it_down() {
405 assert_eq!(fit_widescreen(gradient(1280, 720)).width(), 1280);
777 assert_eq!(
406 let scaled = fit_widescreen(gradient(1920, 1080));
778 fit_widescreen(gradient(1280, 720), VideoQuality::Auto).width(),
779 1280
780 );
781 let kept = fit_widescreen(gradient(1920, 1080), VideoQuality::Auto);
782 assert_eq!((kept.width(), kept.height()), (1920, 1080));
783 let scaled = fit_widescreen(gradient(1920, 1080), VideoQuality::P720);
407 assert_eq!((scaled.width(), scaled.height()), (1280, 720));
784 assert_eq!((scaled.width(), scaled.height()), (1280, 720));
408 let wide = fit_widescreen(gradient(2560, 1080));
785 let wide = fit_widescreen(gradient(2560, 1440), VideoQuality::Auto);
409 assert_eq!((wide.width(), wide.height()), (1280, 720));
786 assert_eq!((wide.width(), wide.height()), (1920, 1080));
410 let classic = fit_widescreen(gradient(640, 480));
787 let classic = fit_widescreen(gradient(640, 480), VideoQuality::Auto);
411 assert_eq!((classic.width(), classic.height()), (640, 360));
788 assert_eq!((classic.width(), classic.height()), (640, 360));
412 }
789 }
413
790
414 #[test]
791 #[test]
415 fn no_usable_format_picks_nothing() {
792 fn no_usable_format_picks_nothing() {
416 let formats = [format(1280, 720, FrameFormat::MJPEG, 30), format(1280, 720, FrameFormat::YUYV, 15)];
793 let formats = [
417 assert_eq!(pick_format(&formats), None);
794 format(1280, 720, FrameFormat::MJPEG, 15),
418 assert_eq!(pick_format(&[]), None);
795 format(1280, 720, FrameFormat::YUYV, 15),
796 ];
797 assert_eq!(pick_format(&formats, VideoQuality::Auto), None);
798 assert_eq!(pick_format(&[], VideoQuality::Auto), None);
419 }
799 }
420
800
421 #[test]
801 #[test]
422 fn camera_choices_map_to_indices_or_names() {
802 fn camera_choices_map_to_indices_or_names() {
423 assert!(matches!(camera_index(&DeviceChoice::SystemDefault), CameraIndex::Index(0)));
803 assert!(matches!(
424 assert!(matches!(camera_index(&DeviceChoice::Device("2".into())), CameraIndex::Index(2)));
804 camera_index(&DeviceChoice::SystemDefault),
425 assert!(matches!(camera_index(&DeviceChoice::Device("video0".into())), CameraIndex::String(_)));
805 CameraIndex::Index(0)
806 ));
807 assert!(matches!(
808 camera_index(&DeviceChoice::Device("2".into())),
809 CameraIndex::Index(2)
810 ));
811 assert!(matches!(
812 camera_index(&DeviceChoice::Device("video0".into())),
813 CameraIndex::String(_)
814 ));
815 }
816
817 #[test]
818 fn mjpeg_decodes_to_i420() {
819 // Minimal valid grayscale JPEG is awkward; encode via `image` crate.
820 let mut rgb = image::RgbImage::new(16, 16);
821 for pixel in rgb.pixels_mut() {
822 *pixel = image::Rgb([40, 80, 120]);
823 }
824 let mut jpeg = Vec::new();
825 image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, 90)
826 .encode(rgb.as_raw(), 16, 16, image::ExtendedColorType::Rgb8)
827 .expect("encode");
828 let mut scratch = Vec::new();
829 let (buffer, width, height) =
830 i420_from_mjpeg(&jpeg, &mut scratch).expect("mjpeg decodes");
831 assert_eq!((width, height), (16, 16));
832 assert_eq!((buffer.width(), buffer.height()), (16, 16));
833 }
834
835 #[test]
836 #[ignore = "timing; run with --release --ignored"]
837 fn mjpeg_1080p_decode_stays_under_fifteen_ms() {
838 let mut rgb = image::RgbImage::new(1920, 1080);
839 for (index, pixel) in rgb.pixels_mut().enumerate() {
840 let value = (index % 255) as u8;
841 *pixel = image::Rgb([value, value.wrapping_add(40), value.wrapping_add(80)]);
842 }
843 let mut jpeg = Vec::new();
844 image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, 85)
845 .encode(rgb.as_raw(), 1920, 1080, image::ExtendedColorType::Rgb8)
846 .expect("encode");
847 let mut scratch = Vec::new();
848 // Warm caches / CPU, then time a steady batch (30 fps allows ~33 ms/frame).
849 for _ in 0..3 {
850 let _ = i420_from_mjpeg(&jpeg, &mut scratch).expect("decode");
851 }
852 let started = Instant::now();
853 for _ in 0..10 {
854 let _ = i420_from_mjpeg(&jpeg, &mut scratch).expect("decode");
855 }
856 let average = started.elapsed() / 10;
857 assert!(
858 average < Duration::from_millis(20),
859 "average decode {average:?} exceeds 20 ms"
860 );
861 }
862
863 #[test]
864 #[ignore = "needs a connected camera"]
865 fn open_picks_at_least_thirty_fps_when_available() {
866 if list_cameras().is_empty() {
867 return;
868 }
869 let (mut camera, label) = open_camera(CameraIndex::Index(0), VideoQuality::Auto)
870 .expect("camera opens");
871 assert!(
872 camera.camera_format().frame_rate() >= CAPTURE_FPS,
873 "opened {label} under 30 fps"
874 );
875 // Warm up buffers, then count for one second.
876 for _ in 0..10 {
877 let _ = camera.frame();
878 }
879 let deadline = Instant::now() + Duration::from_secs(1);
880 let mut frames = 0u32;
881 while Instant::now() < deadline {
882 if camera.frame().is_ok() {
883 frames += 1;
884 }
885 }
886 let _ = camera.stop_stream();
887 assert!(
888 frames >= 20,
889 "expected >= 20 frames in 1 s from {label}, got {frames}"
890 );
426 }
891 }
427}
892}
crates/calling/src/lib.rs +37 −36
@@ -3,54 +3,51 @@ pub mod audio;
3 3 pub mod audio_io;
4 4 pub mod awake;
5 5 pub mod background;
6 pub mod band_meter;
7 pub mod call;
8 pub mod candidates;
9 pub mod callee_gate;
10 6 pub mod blur;
11 7 pub mod breakout;
8 pub mod call;
9 pub mod callee_gate;
12 10 pub mod camera;
11 pub mod candidates;
13 12 pub mod captions;
14 pub mod composite;
15 13 pub mod capture;
14 pub mod composite;
16 15 pub mod control;
17 16 pub mod data_channel;
18 17 pub mod device_watch;
19 18 pub mod devices;
20 19 pub mod diagnostics;
21 pub mod engine;
22 20 pub mod effects;
23 21 pub mod end;
22 pub mod engine;
24 23 pub mod error;
25 pub mod health;
26 24 pub mod framing;
25 pub mod health;
27 26 pub mod hold;
28 27 pub mod join;
29 28 pub mod latest;
30 29 pub mod level;
30 #[cfg(windows)]
31 mod loopback_windows;
31 32 pub mod luma_effects;
32 33 pub mod mask;
33 pub mod motion;
34 34 pub mod matte;
35 35 #[cfg(windows)]
36 mod loopback_windows;
37 #[cfg(windows)]
38 36 mod mic_windows;
37 pub mod motion;
39 38 #[cfg(windows)]
40 39 pub use loopback_windows::start_process_capture;
41 40 #[cfg(windows)]
42 41 pub use mic_windows::probe_effects;
42 pub mod gain_stage;
43 43 pub mod meeting;
44 44 pub mod meeting_options;
45 pub mod mic_processing;
46 pub mod mixer;
47 pub mod gain_stage;
48 45 pub mod mic_chain;
49 46 pub mod mic_effects;
50 pub mod noise_stage;
51 pub mod voice_high_pass;
52 pub mod wav_dump;
47 pub mod mic_processing;
48 pub mod mixer;
53 49 pub mod mute;
50 pub mod noise_stage;
54 51 pub mod organizer;
55 52 pub mod outcome;
56 53 pub mod pcm;
@@ -76,42 +73,46 @@ pub mod trouter_events;
76 73 pub mod video_frame;
77 74 pub mod video_layout;
78 75 pub mod video_pattern;
76 pub mod video_quality;
79 77 pub mod video_receive;
80 78 pub mod video_send;
79 pub mod voice_high_pass;
80 pub mod wav_dump;
81 81 pub mod whiteboard;
82 82
83 83 pub use audio_io::AudioMode;
84 84 pub use background::{BackgroundCache, BackgroundChoice, BackgroundPicture, DefaultBackground};
85 85 pub use breakout::BreakoutMove;
86 pub use health::{CallHealth, HealthSample, Limitation, NetworkLevel, TransportDetails};
87 pub use effects::CameraEffects;
88 pub use hold::HoldState;
89 pub use whiteboard::ContentShare;
90 86 pub use call::{AcceptMode, CallOptions, CallReport, CallSpec, run_test_call};
87 pub use camera::{CameraCaptureStats, CameraDevice, camera_entries};
88 pub use captions::{CaptionEntry, CaptionState, SPOKEN_LANGUAGES};
91 89 pub use control::{CallCommand, CallControl, CallHandle, CallUpdate, Progress, call_channel};
90 pub use devices::{AudioDevice, DeviceChoice, DeviceEntry, DeviceLists};
91 pub use diagnostics::{CallDiagnostics, SdpLine, SdpSummary, StatsSample};
92 pub use effects::CameraEffects;
92 93 pub use end::EndKind;
93 94 pub use engine::{CallEngine, EngineConfig, EngineEvent, IncomingRing};
94 pub use push::Caller;
95 pub use ring::{RING_TIMEOUT, RingEnd, RingSignal, RingState};
96 pub use reaction::{Reaction, ReactionEvent};
97 pub use captions::{CaptionEntry, CaptionState, SPOKEN_LANGUAGES};
95 pub use error::{Error, Result};
96 pub use health::{CallHealth, HealthSample, Limitation, NetworkLevel, TransportDetails};
97 pub use hold::HoldState;
98 pub use level::SpeakingDetector;
98 99 pub use meeting_options::{MeetingOptions, OptionWrite};
100 pub use mic_processing::{ApmConfig, MicSettings, NoiseSuppression};
101 pub use mute::MuteCommand;
99 102 pub use organizer::{MeetingCapability, Modality, RecorderOption, modality_allowed};
103 pub use push::Caller;
104 pub use reaction::{Reaction, ReactionEvent};
100 105 pub use recording::{RecordingKind, StopScope};
101 pub use roster::{AttendeeLimits, MeetingRole, PublishedState, RaisedHand, RosterEntry, Spotlight};
102 pub use sound_capture::LoopbackKind;
103 106 pub use renegotiation::MediaPath;
107 pub use ring::{RING_TIMEOUT, RingEnd, RingSignal, RingState};
108 pub use roster::{AttendeeLimits, MeetingRole, PublishedState, RaisedHand, RosterEntry, Spotlight};
109 pub use screen::{ShareKind, SharePicker, ShareSource};
104 110 pub use signaling::{Callee, MeetingTarget};
105 pub use transfer::Replacement;
106 pub use diagnostics::{CallDiagnostics, SdpLine, SdpSummary, StatsSample};
107 pub use devices::{AudioDevice, DeviceChoice, DeviceEntry, DeviceLists};
108 pub use error::{Error, Result};
109 pub use level::SpeakingDetector;
110 pub use mic_processing::{ApmConfig, MicSettings, NoiseSuppression};
111 pub use mute::MuteCommand;
112 pub use video_layout::{TileDetail, VideoWant};
111 pub use sound_capture::LoopbackKind;
113 112 pub use state::{CallSignal, CallState, EndReason};
114 pub use camera::{CameraDevice, camera_entries};
115 pub use screen::{ShareKind, ShareSource};
113 pub use transfer::Replacement;
116 114 pub use video_frame::{VideoHub, VideoKey, VideoPicture};
115 pub use video_layout::{TileDetail, VideoWant};
116 pub use video_quality::VideoQuality;
117 117 pub use video_send::VideoMode;
118 pub use whiteboard::ContentShare;
@@ -3,54 +3,51 @@ pub mod audio;
3pub mod audio_io;
3pub mod audio_io;
4pub mod awake;
4pub mod awake;
5pub mod background;
5pub mod background;
6pub mod band_meter;
7pub mod call;
8pub mod candidates;
9pub mod callee_gate;
10pub mod blur;
6pub mod blur;
11pub mod breakout;
7pub mod breakout;
8pub mod call;
9pub mod callee_gate;
12pub mod camera;
10pub mod camera;
11pub mod candidates;
13pub mod captions;
12pub mod captions;
14pub mod composite;
15pub mod capture;
13pub mod capture;
14pub mod composite;
16pub mod control;
15pub mod control;
17pub mod data_channel;
16pub mod data_channel;
18pub mod device_watch;
17pub mod device_watch;
19pub mod devices;
18pub mod devices;
20pub mod diagnostics;
19pub mod diagnostics;
21pub mod engine;
22pub mod effects;
20pub mod effects;
23pub mod end;
21pub mod end;
22pub mod engine;
24pub mod error;
23pub mod error;
25pub mod health;
26pub mod framing;
24pub mod framing;
25pub mod health;
27pub mod hold;
26pub mod hold;
28pub mod join;
27pub mod join;
29pub mod latest;
28pub mod latest;
30pub mod level;
29pub mod level;
30#[cfg(windows)]
31mod loopback_windows;
31pub mod luma_effects;
32pub mod luma_effects;
32pub mod mask;
33pub mod mask;
33pub mod motion;
34pub mod matte;
34pub mod matte;
35#[cfg(windows)]
35#[cfg(windows)]
36mod loopback_windows;
37#[cfg(windows)]
38mod mic_windows;
36mod mic_windows;
37pub mod motion;
39#[cfg(windows)]
38#[cfg(windows)]
40pub use loopback_windows::start_process_capture;
39pub use loopback_windows::start_process_capture;
41#[cfg(windows)]
40#[cfg(windows)]
42pub use mic_windows::probe_effects;
41pub use mic_windows::probe_effects;
42pub mod gain_stage;
43pub mod meeting;
43pub mod meeting;
44pub mod meeting_options;
44pub mod meeting_options;
45pub mod mic_processing;
46pub mod mixer;
47pub mod gain_stage;
48pub mod mic_chain;
45pub mod mic_chain;
49pub mod mic_effects;
46pub mod mic_effects;
50pub mod noise_stage;
47pub mod mic_processing;
51pub mod voice_high_pass;
48pub mod mixer;
52pub mod wav_dump;
53pub mod mute;
49pub mod mute;
50pub mod noise_stage;
54pub mod organizer;
51pub mod organizer;
55pub mod outcome;
52pub mod outcome;
56pub mod pcm;
53pub mod pcm;
@@ -76,42 +73,46 @@ pub mod trouter_events;
76pub mod video_frame;
73pub mod video_frame;
77pub mod video_layout;
74pub mod video_layout;
78pub mod video_pattern;
75pub mod video_pattern;
76pub mod video_quality;
79pub mod video_receive;
77pub mod video_receive;
80pub mod video_send;
78pub mod video_send;
79pub mod voice_high_pass;
80pub mod wav_dump;
81pub mod whiteboard;
81pub mod whiteboard;
82
82
83pub use audio_io::AudioMode;
83pub use audio_io::AudioMode;
84pub use background::{BackgroundCache, BackgroundChoice, BackgroundPicture, DefaultBackground};
84pub use background::{BackgroundCache, BackgroundChoice, BackgroundPicture, DefaultBackground};
85pub use breakout::BreakoutMove;
85pub use breakout::BreakoutMove;
86pub use health::{CallHealth, HealthSample, Limitation, NetworkLevel, TransportDetails};
87pub use effects::CameraEffects;
88pub use hold::HoldState;
89pub use whiteboard::ContentShare;
90pub use call::{AcceptMode, CallOptions, CallReport, CallSpec, run_test_call};
86pub use call::{AcceptMode, CallOptions, CallReport, CallSpec, run_test_call};
87pub use camera::{CameraCaptureStats, CameraDevice, camera_entries};
88pub use captions::{CaptionEntry, CaptionState, SPOKEN_LANGUAGES};
91pub use control::{CallCommand, CallControl, CallHandle, CallUpdate, Progress, call_channel};
89pub use control::{CallCommand, CallControl, CallHandle, CallUpdate, Progress, call_channel};
90pub use devices::{AudioDevice, DeviceChoice, DeviceEntry, DeviceLists};
91pub use diagnostics::{CallDiagnostics, SdpLine, SdpSummary, StatsSample};
92pub use effects::CameraEffects;
92pub use end::EndKind;
93pub use end::EndKind;
93pub use engine::{CallEngine, EngineConfig, EngineEvent, IncomingRing};
94pub use engine::{CallEngine, EngineConfig, EngineEvent, IncomingRing};
94pub use push::Caller;
95pub use error::{Error, Result};
95pub use ring::{RING_TIMEOUT, RingEnd, RingSignal, RingState};
96pub use health::{CallHealth, HealthSample, Limitation, NetworkLevel, TransportDetails};
96pub use reaction::{Reaction, ReactionEvent};
97pub use hold::HoldState;
97pub use captions::{CaptionEntry, CaptionState, SPOKEN_LANGUAGES};
98pub use level::SpeakingDetector;
98pub use meeting_options::{MeetingOptions, OptionWrite};
99pub use meeting_options::{MeetingOptions, OptionWrite};
100pub use mic_processing::{ApmConfig, MicSettings, NoiseSuppression};
101pub use mute::MuteCommand;
99pub use organizer::{MeetingCapability, Modality, RecorderOption, modality_allowed};
102pub use organizer::{MeetingCapability, Modality, RecorderOption, modality_allowed};
103pub use push::Caller;
104pub use reaction::{Reaction, ReactionEvent};
100pub use recording::{RecordingKind, StopScope};
105pub use recording::{RecordingKind, StopScope};
101pub use roster::{AttendeeLimits, MeetingRole, PublishedState, RaisedHand, RosterEntry, Spotlight};
102pub use sound_capture::LoopbackKind;
103pub use renegotiation::MediaPath;
106pub use renegotiation::MediaPath;
107pub use ring::{RING_TIMEOUT, RingEnd, RingSignal, RingState};
108pub use roster::{AttendeeLimits, MeetingRole, PublishedState, RaisedHand, RosterEntry, Spotlight};
109pub use screen::{ShareKind, SharePicker, ShareSource};
104pub use signaling::{Callee, MeetingTarget};
110pub use signaling::{Callee, MeetingTarget};
105pub use transfer::Replacement;
111pub use sound_capture::LoopbackKind;
106pub use diagnostics::{CallDiagnostics, SdpLine, SdpSummary, StatsSample};
107pub use devices::{AudioDevice, DeviceChoice, DeviceEntry, DeviceLists};
108pub use error::{Error, Result};
109pub use level::SpeakingDetector;
110pub use mic_processing::{ApmConfig, MicSettings, NoiseSuppression};
111pub use mute::MuteCommand;
112pub use video_layout::{TileDetail, VideoWant};
113pub use state::{CallSignal, CallState, EndReason};
112pub use state::{CallSignal, CallState, EndReason};
114pub use camera::{CameraDevice, camera_entries};
113pub use transfer::Replacement;
115pub use screen::{ShareKind, ShareSource};
116pub use video_frame::{VideoHub, VideoKey, VideoPicture};
114pub use video_frame::{VideoHub, VideoKey, VideoPicture};
115pub use video_layout::{TileDetail, VideoWant};
116pub use video_quality::VideoQuality;
117pub use video_send::VideoMode;
117pub use video_send::VideoMode;
118pub use whiteboard::ContentShare;
crates/calling/src/sdp.rs +616 −136
@@ -12,8 +12,10 @@ const BACKSLASHED_EXTENSIONS: [&str; 2] = [
12 12 "http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",
13 13 "http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",
14 14 ];
15 const DROPPED_EXTENSIONS: [&str; 1] = ["http://www.webrtc.org/experiments/rtp-hdrext/playout-delay"];
16 const LAYERS_ALLOCATION: &str = "http://www.webrtc.org/experiments/rtp-hdrext/video-layers-allocation00";
15 const DROPPED_EXTENSIONS: [&str; 1] =
16 ["http://www.webrtc.org/experiments/rtp-hdrext/playout-delay"];
17 const LAYERS_ALLOCATION: &str =
18 "http://www.webrtc.org/experiments/rtp-hdrext/video-layers-allocation00";
17 19 const NOT_ADVERTISED_SUFFIX: &str = "-non-advertised";
18 20 const DIRECTIONS: [&str; 4] = ["sendrecv", "sendonly", "recvonly", "inactive"];
19 21
@@ -92,7 +94,9 @@ impl Media {
92 94 }
93 95
94 96 pub fn has(&self, name: &str) -> bool {
95 self.attributes.iter().any(|attribute| attribute.name == name)
97 self.attributes
98 .iter()
99 .any(|attribute| attribute.name == name)
96 100 }
97 101
98 102 pub fn mid(&self) -> Option<&str> {
@@ -127,7 +131,9 @@ pub fn parse(text: &str) -> Result<SessionDescription> {
127 131 .ok_or_else(|| Error::Sdp(format!("line without '=': {line}")))?;
128 132 if kind == "m" {
129 133 let mut parts = value.split(' ');
130 let (Some(media_kind), Some(port), Some(proto)) = (parts.next(), parts.next(), parts.next()) else {
134 let (Some(media_kind), Some(port), Some(proto)) =
135 (parts.next(), parts.next(), parts.next())
136 else {
131 137 return Err(Error::Sdp(format!("short m-line: {line}")));
132 138 };
133 139 media.push(Media {
@@ -223,8 +229,18 @@ pub fn write(description: &SessionDescription) -> String {
223 229 format!("o={}", session.origin),
224 230 format!("s={}", session.name),
225 231 ];
226 lines.extend(session.connection.iter().map(|connection| format!("c={connection}")));
227 lines.extend(session.bandwidths.iter().map(|bandwidth| format!("b={bandwidth}")));
232 lines.extend(
233 session
234 .connection
235 .iter()
236 .map(|connection| format!("c={connection}")),
237 );
238 lines.extend(
239 session
240 .bandwidths
241 .iter()
242 .map(|bandwidth| format!("b={bandwidth}")),
243 );
228 244 lines.push(format!("t={}", session.timing));
229 245 let mut session_attributes: Vec<&Attribute> = session.attributes.iter().collect();
230 246 session_attributes.sort_by_key(|attribute| session_rank(&attribute.name));
@@ -233,8 +249,18 @@ pub fn write(description: &SessionDescription) -> String {
233 249 let mut header = vec![media.kind.clone(), media.port.clone(), media.proto.clone()];
234 250 header.extend(media.formats.iter().cloned());
235 251 lines.push(format!("m={}", header.join(" ")));
236 lines.extend(media.connection.iter().map(|connection| format!("c={connection}")));
237 lines.extend(media.bandwidths.iter().map(|bandwidth| format!("b={bandwidth}")));
252 lines.extend(
253 media
254 .connection
255 .iter()
256 .map(|connection| format!("c={connection}")),
257 );
258 lines.extend(
259 media
260 .bandwidths
261 .iter()
262 .map(|bandwidth| format!("b={bandwidth}")),
263 );
238 264 let mut attributes: Vec<&Attribute> = media.attributes.iter().collect();
239 265 attributes.sort_by_key(|attribute| media_rank(&attribute.name));
240 266 lines.extend(attributes.into_iter().map(Attribute::render));
@@ -272,11 +298,14 @@ impl LineRole {
272 298 }
273 299 }
274 300
275 /// Which browser m-lines play which Teams role; `gallery_mids` are folded into one `x-multi-stream` line.
301 /// Which browser m-lines play which Teams role.
302 /// `gallery_mids` / `fold_groups` collapse several browser mids into one Teams `x-multi-stream` line.
276 303 #[derive(Debug, Clone, Default)]
277 304 pub struct OfferPlan {
278 305 pub screen_share_mids: Vec<String>,
279 306 pub gallery_mids: Vec<String>,
307 /// Each group is one Teams line; the last mid is the carrier written back to Teams.
308 pub fold_groups: Vec<Vec<String>>,
280 309 }
281 310
282 311 #[derive(Debug, Clone, PartialEq, Eq)]
@@ -302,20 +331,32 @@ impl<F: FnMut() -> u32> NumberSource for F {
302 331 }
303 332 }
304 333
305 pub fn to_teams_offer(browser_sdp: &str, plan: &OfferPlan, numbers: &mut impl NumberSource) -> Result<SignaledOffer> {
334 pub fn to_teams_offer(
335 browser_sdp: &str,
336 plan: &OfferPlan,
337 numbers: &mut impl NumberSource,
338 ) -> Result<SignaledOffer> {
306 339 let browser = parse(browser_sdp)?;
307 340 let cname = browser
308 341 .media
309 342 .iter()
310 343 .flat_map(|media| media.values("ssrc"))
311 .find_map(|value| value.split_once(" cname:").map(|(_, cname)| cname.to_owned()))
344 .find_map(|value| {
345 value
346 .split_once(" cname:")
347 .map(|(_, cname)| cname.to_owned())
348 })
312 349 .unwrap_or_else(|| format!("{:08x}{:08x}", numbers.next_u32(), numbers.next_u32()));
313 let gallery_carrier = plan.gallery_mids.last().cloned();
350 let fold_groups = effective_fold_groups(plan);
314 351 let mut lines = Vec::new();
315 352 let mut media = Vec::new();
316 353 for source in &browser.media {
317 354 let mid = source.mid().unwrap_or_default().to_owned();
318 if plan.gallery_mids.contains(&mid) && Some(&mid) != gallery_carrier.as_ref() {
355 let fold_group = fold_groups
356 .iter()
357 .find(|group| group.iter().any(|entry| entry == &mid));
358 let fold_carrier = fold_group.and_then(|group| group.last());
359 if fold_group.is_some() && Some(&mid) != fold_carrier {
319 360 continue;
320 361 }
321 362 let role = match source.kind.as_str() {
@@ -324,10 +365,10 @@ pub fn to_teams_offer(browser_sdp: &str, plan: &OfferPlan, numbers: &mut impl Nu
324 365 _ if plan.screen_share_mids.contains(&mid) => LineRole::ScreenShare,
325 366 _ => LineRole::MainVideo,
326 367 };
327 let multi_stream = (Some(&mid) == gallery_carrier.as_ref()).then_some(plan.gallery_mids.len());
368 let multi_stream = fold_group.map(|group| group.len());
328 369 let is_first = media.is_empty();
329 370 let signaled = if source.port == "0" {
330 signal_rejected_line(source, role)
371 signal_rejected_line(source, role, multi_stream)
331 372 } else if role == LineRole::Data {
332 373 signal_data_line(source, numbers)
333 374 } else {
@@ -335,8 +376,8 @@ pub fn to_teams_offer(browser_sdp: &str, plan: &OfferPlan, numbers: &mut impl Nu
335 376 };
336 377 media.push(signaled);
337 378 lines.push(SignaledLine {
338 browser_mids: match multi_stream {
339 Some(_) => plan.gallery_mids.clone(),
379 browser_mids: match fold_group {
380 Some(group) => group.clone(),
340 381 None => vec![mid],
341 382 },
342 383 role,
@@ -347,8 +388,17 @@ pub fn to_teams_offer(browser_sdp: &str, plan: &OfferPlan, numbers: &mut impl Nu
347 388 for attribute in &mut session.attributes {
348 389 match attribute.name.as_str() {
349 390 "msid-semantic" => attribute.value = Some(" WMS *".to_owned()),
350 "group" if attribute.value.as_deref().is_some_and(|value| value.starts_with("BUNDLE")) => {
351 let mids: Vec<&str> = media.iter().filter(|line| line.port != "0").filter_map(Media::mid).collect();
391 "group"
392 if attribute
393 .value
394 .as_deref()
395 .is_some_and(|value| value.starts_with("BUNDLE")) =>
396 {
397 let mids: Vec<&str> = media
398 .iter()
399 .filter(|line| line.port != "0")
400 .filter_map(Media::mid)
401 .collect();
352 402 attribute.value = Some(format!("BUNDLE {}", mids.join(" ")));
353 403 }
354 404 _ => {}
@@ -361,14 +411,20 @@ pub fn to_teams_offer(browser_sdp: &str, plan: &OfferPlan, numbers: &mut impl Nu
361 411 })
362 412 }
363 413
364 fn signal_rejected_line(source: &Media, role: LineRole) -> Media {
365 let attributes = vec![
366 Attribute::new("mid", source.mid().unwrap_or_default()),
367 Attribute::flag("inactive"),
368 Attribute::new("label", role.label()),
369 ];
414 fn signal_rejected_line(source: &Media, role: LineRole, multi_stream: Option<usize>) -> Media {
415 let mut attributes = Vec::new();
416 if let Some(count) = multi_stream {
417 attributes.push(Attribute::new("x-multi-stream", format!("{count} 1 1 1")));
418 }
419 attributes.push(Attribute::new("mid", source.mid().unwrap_or_default()));
420 attributes.push(Attribute::flag("inactive"));
421 attributes.push(Attribute::new("label", role.label()));
370 422 Media {
371 kind: if role == LineRole::Data { "x-data".to_owned() } else { source.kind.clone() },
423 kind: if role == LineRole::Data {
424 "x-data".to_owned()
425 } else {
426 source.kind.clone()
427 },
372 428 port: "0".to_owned(),
373 429 proto: SIGNALED_PROTO.to_owned(),
374 430 formats: source.formats.clone(),
@@ -391,7 +447,11 @@ fn signal_rtp_line(
391 447 media.proto = SIGNALED_PROTO.to_owned();
392 448 media.connection = Some(PLACEHOLDER_CONNECTION.to_owned());
393 449 let rtpmap = source.rtpmap();
394 let is_rtx = |payload: &str| rtpmap.get(payload).is_some_and(|encoding| encoding.starts_with("rtx/"));
450 let is_rtx = |payload: &str| {
451 rtpmap
452 .get(payload)
453 .is_some_and(|encoding| encoding.starts_with("rtx/"))
454 };
395 455 let mid = source.mid().unwrap_or_default().to_owned();
396 456
397 457 let mut attributes = Vec::new();
@@ -412,7 +472,10 @@ fn signal_rtp_line(
412 472 let simulcast = source.has("simulcast");
413 473 let receive_only = source.direction() == Some("recvonly");
414 474 let (range, ssrc_lines) = if multi_stream.is_some() {
415 (None, vec![Attribute::new("ssrc", format!("1 cname:{cname}"))])
475 (
476 None,
477 vec![Attribute::new("ssrc", format!("1 cname:{cname}"))],
478 )
416 479 } else if let Some(&first) = browser_ssrcs.first() {
417 480 let lines = source
418 481 .values("ssrc")
@@ -421,13 +484,22 @@ fn signal_rtp_line(
421 484 (Some((first, first)), lines)
422 485 } else if simulcast {
423 486 let base = numbers.next_u32();
424 let lines = vec![Attribute::new("ssrc", format!("{base} fake_attribute:fake_value"))];
487 let lines = vec![Attribute::new(
488 "ssrc",
489 format!("{base} fake_attribute:fake_value"),
490 )];
425 491 (Some((base, base + SSRC_RANGE_SIZE - 1)), lines)
426 492 } else if receive_only && role != LineRole::MainAudio {
427 (Some((1, 1)), vec![Attribute::new("ssrc", format!("1 cname:{cname}"))])
493 (
494 Some((1, 1)),
495 vec![Attribute::new("ssrc", format!("1 cname:{cname}"))],
496 )
428 497 } else {
429 498 let base = numbers.next_u32();
430 (Some((base, base)), vec![Attribute::new("ssrc", format!("{base} cname:{cname}"))])
499 (
500 Some((base, base)),
501 vec![Attribute::new("ssrc", format!("{base} cname:{cname}"))],
502 )
431 503 };
432 504 if let Some((first, last)) = range {
433 505 attributes.push(Attribute::new("x-ssrc-range", format!("{first}-{last}")));
@@ -440,16 +512,18 @@ fn signal_rtp_line(
440 512 for attribute in &source.attributes {
441 513 let value = attribute.value.as_deref().unwrap_or_default();
442 514 match attribute.name.as_str() {
443 "ssrc" | "ssrc-group" | "rid" | "simulcast" | "rtcp-xr" | "rtcp-fb" | "candidate" | "end-of-candidates" => {}
515 "ssrc" | "ssrc-group" | "rid" | "simulcast" | "rtcp-xr" | "rtcp-fb" | "candidate"
516 | "end-of-candidates" => {}
444 517 "rtpmap" => attributes.push(Attribute::new("rtpmap", signal_rtpmap(value))),
445 518 "fmtp" => {
446 519 let payload = value.split(' ').next().unwrap_or_default();
447 let position = source.formats.iter().position(|format| format == payload).unwrap_or(usize::MAX);
448 let is_opus = rtpmap.get(payload).is_some_and(|encoding| encoding.to_ascii_lowercase().starts_with("opus/"));
520 let position = source
521 .formats
522 .iter()
523 .position(|format| format == payload)
524 .unwrap_or(usize::MAX);
449 525 let cleaned = if video {
450 526 value.replace(";sps-pps-idr-in-keyframe=1", "")
451 } else if is_opus {
452 with_fmtp_parameters(value, &OPUS_RECEIVE_FULLBAND)
453 527 } else {
454 528 value.to_owned()
455 529 };
@@ -467,14 +541,30 @@ fn signal_rtp_line(
467 541 fmtp.sort_by_key(|(position, _)| *position);
468 542 attributes.extend(fmtp.into_iter().map(|(_, attribute)| attribute));
469 543 match shared_feedback {
470 Some(feedback) => attributes.extend(feedback.iter().map(|kind| Attribute::new("rtcp-fb", format!("* {kind}")))),
471 None => attributes.extend(source.attributes.iter().filter(|attribute| attribute.name == "rtcp-fb").cloned()),
544 Some(feedback) => attributes.extend(
545 feedback
546 .iter()
547 .map(|kind| Attribute::new("rtcp-fb", format!("* {kind}"))),
548 ),
549 None => attributes.extend(
550 source
551 .attributes
552 .iter()
553 .filter(|attribute| attribute.name == "rtcp-fb")
554 .cloned(),
555 ),
472 556 }
473 557 if carries_candidate {
474 558 attributes.push(Attribute::new("candidate", PLACEHOLDER_CANDIDATE));
475 559 }
476 560 attributes.extend(ssrc_lines);
477 attributes.extend(source.attributes.iter().filter(|attribute| attribute.name == "ssrc-group").cloned());
561 attributes.extend(
562 source
563 .attributes
564 .iter()
565 .filter(|attribute| attribute.name == "ssrc-group")
566 .cloned(),
567 );
478 568 attributes.push(Attribute::new("label", role.label()));
479 569 if !source.has("rtcp-mux") {
480 570 attributes.push(Attribute::flag("rtcp-mux"));
@@ -495,7 +585,9 @@ fn rewrite_ssrc_msid(value: &str, mid: &str) -> String {
495 585
496 586 fn signal_rtpmap(value: &str) -> String {
497 587 match value.split_once(' ') {
498 Some((payload, encoding)) if encoding.eq_ignore_ascii_case("red/48000/2") => format!("{payload} RED/8000"),
588 Some((payload, encoding)) if encoding.eq_ignore_ascii_case("red/48000/2") => {
589 format!("{payload} RED/8000")
590 }
499 591 _ => value.to_owned(),
500 592 }
501 593 }
@@ -518,7 +610,9 @@ fn feedback_by_payload(source: &Media) -> HashMap<String, Vec<String>> {
518 610 let mut map: HashMap<String, Vec<String>> = HashMap::new();
519 611 for value in source.values("rtcp-fb") {
520 612 if let Some((payload, kind)) = value.split_once(' ') {
521 map.entry(payload.to_owned()).or_default().push(kind.to_owned());
613 map.entry(payload.to_owned())
614 .or_default()
615 .push(kind.to_owned());
522 616 }
523 617 }
524 618 map
@@ -531,7 +625,9 @@ fn shared_feedback(
531 625 ) -> Option<Vec<String>> {
532 626 let mut codecs = source.formats.iter().filter(|payload| !is_rtx(payload));
533 627 let first = by_payload.get(codecs.next()?)?;
534 codecs.all(|payload| by_payload.get(payload) == Some(first)).then(|| first.clone())
628 codecs
629 .all(|payload| by_payload.get(payload) == Some(first))
630 .then(|| first.clone())
535 631 }
536 632
537 633 fn signal_data_line(source: &Media, numbers: &mut impl NumberSource) -> Media {
@@ -558,7 +654,11 @@ fn signal_data_line(source: &Media, numbers: &mut impl NumberSource) -> Media {
558 654 }
559 655 }
560 656
561 pub fn to_browser_answer(teams_sdp: &str, offer: &SignaledOffer, browser_offer_sdp: &str) -> Result<String> {
657 pub fn to_browser_answer(
658 teams_sdp: &str,
659 offer: &SignaledOffer,
660 browser_offer_sdp: &str,
661 ) -> Result<String> {
562 662 let answer = parse(teams_sdp)?;
563 663 let browser_offer = parse(browser_offer_sdp)?;
564 664 if answer.media.len() != offer.lines.len() {
@@ -582,21 +682,40 @@ pub fn to_browser_answer(teams_sdp: &str, offer: &SignaledOffer, browser_offer_s
582 682 let section = if signaled.role == LineRole::Data {
583 683 browser_data_line(teams_line, offered_line, &answer.session)
584 684 } else {
585 browser_rtp_line(teams_line, offered_line, signaled.role, stream_index as u32, index == 0, &answer.session)
685 browser_rtp_line(
686 teams_line,
687 offered_line,
688 signaled.role,
689 stream_index as u32,
690 index == 0,
691 &answer.session,
692 )
586 693 };
587 694 media.push(section);
588 695 }
589 696 }
590 697 let mut session = answer.session.clone();
591 session.attributes.retain(|attribute| attribute.name.starts_with("x-"));
592 session.attributes.push(Attribute::flag("extmap-allow-mixed"));
593 session.attributes.push(Attribute::new("msid-semantic", " WMS *"));
594 session.attributes.push(Attribute::new("group", bundle_group(media.iter().map(|line| (line.port.as_str(), line.mid())))));
698 session
699 .attributes
700 .retain(|attribute| attribute.name.starts_with("x-"));
701 session
702 .attributes
703 .push(Attribute::flag("extmap-allow-mixed"));
704 session
705 .attributes
706 .push(Attribute::new("msid-semantic", " WMS *"));
707 session.attributes.push(Attribute::new(
708 "group",
709 bundle_group(media.iter().map(|line| (line.port.as_str(), line.mid()))),
710 ));
595 711 Ok(write(&SessionDescription { session, media }))
596 712 }
597 713
598 714 fn bundle_group<'a>(lines: impl Iterator<Item = (&'a str, Option<&'a str>)>) -> String {
599 let mids: Vec<&str> = lines.filter(|(port, _)| *port != "0").filter_map(|(_, mid)| mid).collect();
715 let mids: Vec<&str> = lines
716 .filter(|(port, _)| *port != "0")
717 .filter_map(|(_, mid)| mid)
718 .collect();
600 719 format!("BUNDLE {}", mids.join(" "))
601 720 }
602 721
@@ -611,11 +730,17 @@ pub struct StreamLine {
611 730 pub fn stream_lines(teams_sdp: &str, lines: &[SignaledLine]) -> Result<Vec<StreamLine>> {
612 731 let teams = parse(teams_sdp)?;
613 732 if teams.media.len() != lines.len() {
614 return Err(Error::Sdp(format!("sdp has {} m-lines, {} were signaled", teams.media.len(), lines.len())));
733 return Err(Error::Sdp(format!(
734 "sdp has {} m-lines, {} were signaled",
735 teams.media.len(),
736 lines.len()
737 )));
615 738 }
616 739 let mut streams = Vec::new();
617 740 for (media, line) in teams.media.iter().zip(lines) {
618 let source_stream_id = media.value("x-source-streamid").and_then(|value| value.trim().parse().ok());
741 let source_stream_id = media
742 .value("x-source-streamid")
743 .and_then(|value| value.trim().parse().ok());
619 744 let mid = media.mid().unwrap_or_default().to_owned();
620 745 match line.browser_mids.as_slice() {
621 746 [browser_mid] => streams.push(StreamLine {
@@ -649,19 +774,17 @@ fn transport_attributes(teams_line: &Media, session: &Session) -> Vec<Attribute>
649 774 .collect()
650 775 }
651 776
652 const OPUS_SEND_QUALITY: [(&str, &str); 2] = [("maxaveragebitrate", "40000"), ("maxplaybackrate", "48000")];
653
654 const OPUS_RECEIVE_FULLBAND: [(&str, &str); 2] = [("maxplaybackrate", "48000"), ("sprop-maxcapturerate", "48000")];
777 const OPUS_SEND_QUALITY: [(&str, &str); 2] =
778 [("maxaveragebitrate", "40000"), ("maxplaybackrate", "48000")];
655 779
656 780 /// libwebrtc sizes its Opus encoder from these remote fmtp parameters; without them it picks its own bitrate.
657 781 fn with_opus_send_quality(fmtp: &str) -> String {
658 with_fmtp_parameters(fmtp, &OPUS_SEND_QUALITY)
659 }
660
661 fn with_fmtp_parameters(fmtp: &str, parameters: &[(&str, &str)]) -> String {
662 782 let mut value = fmtp.to_owned();
663 for &(name, setting) in parameters {
664 if value.split([' ', ';']).any(|parameter| parameter.split('=').next() == Some(name)) {
783 for (name, setting) in OPUS_SEND_QUALITY {
784 if value
785 .split([' ', ';'])
786 .any(|parameter| parameter.split('=').next() == Some(name))
787 {
665 788 continue;
666 789 }
667 790 if !value.ends_with(' ') {
@@ -704,14 +827,20 @@ fn browser_rtp_line(
704 827 let payload_of = |value: &str| value.split(' ').next().unwrap_or_default().to_owned();
705 828 let codec_payload = |codec: &str| {
706 829 kept.iter().find(|payload| {
707 answer_rtpmap
708 .get(*payload)
709 .is_some_and(|encoding| encoding.to_ascii_lowercase().starts_with(&format!("{codec}/")))
830 answer_rtpmap.get(*payload).is_some_and(|encoding| {
831 encoding
832 .to_ascii_lowercase()
833 .starts_with(&format!("{codec}/"))
834 })
710 835 })
711 836 };
712 837
713 838 let mut attributes = Vec::new();
714 attributes.extend(teams_line.values("x-source-streamid").map(|value| Attribute::new("x-source-streamid", value)));
839 attributes.extend(
840 teams_line
841 .values("x-source-streamid")
842 .map(|value| Attribute::new("x-source-streamid", value)),
843 );
715 844 for value in teams_line.values("rtpmap") {
716 845 let payload = payload_of(value);
717 846 if !kept_set.contains(payload.as_str()) {
@@ -739,17 +868,31 @@ fn browser_rtp_line(
739 868 .join(";");
740 869 let is_opus = codec_payload("opus").is_some_and(|opus| *opus == payload);
741 870 fmtp_payloads.insert(payload);
742 attributes.push(Attribute::new("fmtp", if is_opus { with_opus_send_quality(&cleaned) } else { cleaned }));
871 attributes.push(Attribute::new(
872 "fmtp",
873 if is_opus {
874 with_opus_send_quality(&cleaned)
875 } else {
876 cleaned
877 },
878 ));
743 879 }
744 880 if let Some(opus) = codec_payload("opus").filter(|payload| !fmtp_payloads.contains(*payload)) {
745 attributes.push(Attribute::new("fmtp", with_opus_send_quality(&format!("{opus} usedtx=1"))));
881 attributes.push(Attribute::new(
882 "fmtp",
883 with_opus_send_quality(&format!("{opus} usedtx=1")),
884 ));
746 885 }
747 886 if let (Some(red), Some(opus)) = (codec_payload("red"), codec_payload("opus"))
748 887 && !fmtp_payloads.contains(red)
749 888 {
750 889 attributes.push(Attribute::new("fmtp", format!("{red} {opus}/{opus}")));
751 890 }
752 attributes.extend(teams_line.values("rtcp").map(|value| Attribute::new("rtcp", value)));
891 attributes.extend(
892 teams_line
893 .values("rtcp")
894 .map(|value| Attribute::new("rtcp", value)),
895 );
753 896 let answer_feedback: Vec<&str> = teams_line
754 897 .values("rtcp-fb")
755 898 .filter(|value| !value.contains("x-message"))
@@ -762,7 +905,11 @@ fn browser_rtp_line(
762 905 .map(|value| Attribute::new("rtcp-fb", value)),
763 906 );
764 907 } else {
765 attributes.extend(answer_feedback.into_iter().map(|value| Attribute::new("rtcp-fb", value)));
908 attributes.extend(
909 answer_feedback
910 .into_iter()
911 .map(|value| Attribute::new("rtcp-fb", value)),
912 );
766 913 }
767 914 for value in teams_line.values("extmap") {
768 915 let restored = value.replace('\\', "/").replace(NOT_ADVERTISED_SUFFIX, "");
@@ -770,29 +917,53 @@ fn browser_rtp_line(
770 917 }
771 918 attributes.extend(transport_attributes(teams_line, session));
772 919 attributes.push(Attribute::new("mid", offered.mid().unwrap_or_default()));
773 attributes.extend(teams_line.values("ptime").map(|value| Attribute::new("ptime", value)));
920 attributes.extend(
921 teams_line
922 .values("ptime")
923 .map(|value| Attribute::new("ptime", value)),
924 );
774 925 if let Some(direction) = teams_line.direction() {
775 926 attributes.push(Attribute::flag(direction));
776 927 }
777 928 if carries_candidates {
778 attributes.extend(teams_line.values("candidate").chain(teams_line.values("x-candidate-ipv6")).map(|value| Attribute::new("candidate", browser_candidate(value))));
929 attributes.extend(
930 teams_line
931 .values("candidate")
932 .chain(teams_line.values("x-candidate-ipv6"))
933 .map(|value| Attribute::new("candidate", browser_candidate(value))),
934 );
779 935 }
780 936 attributes.extend(stream_ssrc_attributes(teams_line, stream_index, role));
781 937 attributes.push(Attribute::flag("rtcp-mux"));
782 938 if teams_line.has("rtcp-rsize") {
783 939 attributes.push(Attribute::flag("rtcp-rsize"));
784 940 }
785 if let Some(simulcast) = offered.value("simulcast").and_then(|value| value.strip_prefix("send ")) {
786 let rids: Vec<String> = simulcast.split(';').map(|rid| rid.trim_start_matches('~').to_owned()).collect();
787 attributes.extend(rids.iter().map(|rid| Attribute::new("rid", format!("{rid} recv"))));
788 attributes.push(Attribute::new("simulcast", format!("recv {}", rids.join(";"))));
941 if let Some(simulcast) = offered
942 .value("simulcast")
943 .and_then(|value| value.strip_prefix("send "))
944 {
945 let rids: Vec<String> = simulcast
946 .split(';')
947 .map(|rid| rid.trim_start_matches('~').to_owned())
948 .collect();
949 attributes.extend(
950 rids.iter()
951 .map(|rid| Attribute::new("rid", format!("{rid} recv"))),
952 );
953 attributes.push(Attribute::new(
954 "simulcast",
955 format!("recv {}", rids.join(";")),
956 ));
789 957 }
790 958 Media {
791 959 kind: offered.kind.clone(),
792 960 port: teams_line.port.clone(),
793 961 proto: offered.proto.clone(),
794 962 formats: kept,
795 connection: teams_line.connection.clone().or_else(|| session.connection.clone()),
963 connection: teams_line
964 .connection
965 .clone()
966 .or_else(|| session.connection.clone()),
796 967 bandwidths: teams_line.bandwidths.clone(),
797 968 attributes,
798 969 }
@@ -805,11 +976,20 @@ fn stream_ssrc_attributes(teams_line: &Media, stream_index: u32, role: LineRole)
805 976 let stream = format!("{}-{primary}", role.stream_prefix());
806 977 let mut attributes = Vec::new();
807 978 for ssrc in [Some(primary), retransmission].into_iter().flatten() {
808 attributes.push(Attribute::new("ssrc", format!("{ssrc} cname:{}", stream_cname(primary))));
809 attributes.push(Attribute::new("ssrc", format!("{ssrc} msid:{stream} {stream}")));
979 attributes.push(Attribute::new(
980 "ssrc",
981 format!("{ssrc} cname:{}", stream_cname(primary)),
982 ));
983 attributes.push(Attribute::new(
984 "ssrc",
985 format!("{ssrc} msid:{stream} {stream}"),
986 ));
810 987 }
811 988 if let Some(retransmission) = retransmission {
812 attributes.push(Attribute::new("ssrc-group", format!("FID {primary} {retransmission}")));
989 attributes.push(Attribute::new(
990 "ssrc-group",
991 format!("FID {primary} {retransmission}"),
992 ));
813 993 }
814 994 attributes
815 995 }
@@ -820,8 +1000,13 @@ fn stream_cname(primary: u32) -> String {
820 1000
821 1001 fn stream_ssrcs(teams_line: &Media, stream_index: u32) -> (Option<u32>, Option<u32>) {
822 1002 let offset = stream_index * SSRC_RANGE_SIZE;
823 if let Some(group) = teams_line.value("ssrc-group").and_then(|value| value.strip_prefix("FID ")) {
824 let mut ssrcs = group.split(' ').filter_map(|value| value.parse::<u32>().ok());
1003 if let Some(group) = teams_line
1004 .value("ssrc-group")
1005 .and_then(|value| value.strip_prefix("FID "))
1006 {
1007 let mut ssrcs = group
1008 .split(' ')
1009 .filter_map(|value| value.parse::<u32>().ok());
825 1010 let primary = ssrcs.next().map(|ssrc| ssrc + offset);
826 1011 return (primary, ssrcs.next().map(|ssrc| ssrc + offset));
827 1012 }
@@ -837,7 +1022,11 @@ fn browser_candidate(value: &str) -> String {
837 1022 if let Some(position) = parts.iter().position(|part| *part == "MTURNID") {
838 1023 parts.truncate(position);
839 1024 }
840 let tcp_type = match parts.get(2).map(|transport| transport.to_ascii_lowercase()).as_deref() {
1025 let tcp_type = match parts
1026 .get(2)
1027 .map(|transport| transport.to_ascii_lowercase())
1028 .as_deref()
1029 {
841 1030 Some("tcp-pass") => Some("passive"),
842 1031 Some("tcp-act") => Some("active"),
843 1032 Some("tcp-so") => Some("so"),
@@ -856,16 +1045,27 @@ fn browser_candidate(value: &str) -> String {
856 1045
857 1046 fn browser_data_line(teams_line: &Media, offered: &Media, session: &Session) -> Media {
858 1047 let mut attributes = Vec::new();
859 attributes.extend(teams_line.values("x-source-streamid").map(|value| Attribute::new("x-source-streamid", value)));
1048 attributes.extend(
1049 teams_line
1050 .values("x-source-streamid")
1051 .map(|value| Attribute::new("x-source-streamid", value)),
1052 );
860 1053 attributes.extend(transport_attributes(teams_line, session));
861 1054 attributes.push(Attribute::new("mid", offered.mid().unwrap_or_default()));
862 attributes.extend(offered.values("sctp-port").map(|value| Attribute::new("sctp-port", value)));
1055 attributes.extend(
1056 offered
1057 .values("sctp-port")
1058 .map(|value| Attribute::new("sctp-port", value)),
1059 );
863 1060 Media {
864 1061 kind: offered.kind.clone(),
865 1062 port: teams_line.port.clone(),
866 1063 proto: offered.proto.clone(),
867 1064 formats: offered.formats.clone(),
868 connection: teams_line.connection.clone().or_else(|| session.connection.clone()),
1065 connection: teams_line
1066 .connection
1067 .clone()
1068 .or_else(|| session.connection.clone()),
869 1069 bandwidths: Vec::new(),
870 1070 attributes,
871 1071 }
@@ -888,7 +1088,13 @@ const TEAMS_ONLY_ATTRIBUTES: [&str; 6] = [
888 1088 "x-data-protocol",
889 1089 "label",
890 1090 ];
891 const TRANSPORT_ATTRIBUTES: [&str; 5] = ["setup", "ice-ufrag", "ice-pwd", "fingerprint", "ice-options"];
1091 const TRANSPORT_ATTRIBUTES: [&str; 5] = [
1092 "setup",
1093 "ice-ufrag",
1094 "ice-pwd",
1095 "fingerprint",
1096 "ice-options",
1097 ];
892 1098
893 1099 /// A Teams offer translated for libwebrtc; `lines` remembers which browser mids each signaled line stands for.
894 1100 #[derive(Debug, Clone)]
@@ -902,15 +1108,32 @@ impl RemoteOffer {
902 1108 let mut plan = OfferPlan::default();
903 1109 for line in &self.lines {
904 1110 match line.role {
905 LineRole::ScreenShare => plan.screen_share_mids.extend(line.browser_mids.iter().cloned()),
906 _ if line.browser_mids.len() > 1 => plan.gallery_mids.extend(line.browser_mids.iter().cloned()),
1111 LineRole::ScreenShare => plan
1112 .screen_share_mids
1113 .extend(line.browser_mids.iter().cloned()),
907 1114 _ => {}
908 1115 }
1116 if line.browser_mids.len() > 1 {
1117 plan.gallery_mids
1118 .extend(line.browser_mids.iter().cloned());
1119 plan.fold_groups.push(line.browser_mids.clone());
1120 }
909 1121 }
910 1122 plan
911 1123 }
912 1124 }
913 1125
1126 fn effective_fold_groups(plan: &OfferPlan) -> Vec<Vec<String>> {
1127 if !plan.fold_groups.is_empty() {
1128 return plan.fold_groups.clone();
1129 }
1130 if plan.gallery_mids.len() > 1 {
1131 vec![plan.gallery_mids.clone()]
1132 } else {
1133 Vec::new()
1134 }
1135 }
1136
914 1137 fn role_of_teams_line(line: &Media) -> LineRole {
915 1138 match line.value("label") {
916 1139 Some("main-audio") => LineRole::MainAudio,
@@ -928,13 +1151,26 @@ fn role_of_teams_line(line: &Media) -> LineRole {
928 1151 /// Folded gallery lines get the mids just below the carrier line's own mid, unless another line already uses one of them.
929 1152 fn folded_mids(carrier: &str, count: usize, taken: &[String]) -> Vec<String> {
930 1153 let below = match carrier.parse::<usize>() {
931 Ok(last) if last + 1 >= count => Some((last + 1 - count..=last).map(|mid| mid.to_string()).collect::<Vec<_>>()),
1154 Ok(last) if last + 1 >= count => Some(
1155 (last + 1 - count..=last)
1156 .map(|mid| mid.to_string())
1157 .collect::<Vec<_>>(),
1158 ),
932 1159 _ => None,
933 1160 };
934 match below.filter(|mids| mids.iter().all(|mid| mid == carrier || !taken.contains(mid))) {
1161 match below.filter(|mids| {
1162 mids.iter()
1163 .all(|mid| mid == carrier || !taken.contains(mid))
1164 }) {
935 1165 Some(mids) => mids,
936 1166 None => (0..count)
937 .map(|index| if index + 1 == count { carrier.to_owned() } else { format!("{carrier}-{index}") })
1167 .map(|index| {
1168 if index + 1 == count {
1169 carrier.to_owned()
1170 } else {
1171 format!("{carrier}-{index}")
1172 }
1173 })
938 1174 .collect(),
939 1175 }
940 1176 }
@@ -943,7 +1179,11 @@ pub fn from_teams_offer(teams_sdp: &str) -> Result<RemoteOffer> {
943 1179 let teams = parse(teams_sdp)?;
944 1180 let mut media = Vec::new();
945 1181 let mut lines = Vec::new();
946 let mut taken: Vec<String> = teams.media.iter().filter_map(|line| line.mid().map(str::to_owned)).collect();
1182 let mut taken: Vec<String> = teams
1183 .media
1184 .iter()
1185 .filter_map(|line| line.mid().map(str::to_owned))
1186 .collect();
947 1187 for source in &teams.media {
948 1188 let role = role_of_teams_line(source);
949 1189 let carrier = source.mid().unwrap_or_default().to_owned();
@@ -960,7 +1200,14 @@ pub fn from_teams_offer(teams_sdp: &str) -> Result<RemoteOffer> {
960 1200 let converted = if role == LineRole::Data {
961 1201 browser_data_from_teams(source, mid, &teams.session)
962 1202 } else {
963 browser_rtp_from_teams(source, mid, role, folded.is_some(), index == 0 && lines.is_empty(), &teams.session)
1203 browser_rtp_from_teams(
1204 source,
1205 mid,
1206 role,
1207 folded.is_some(),
1208 index == 0 && lines.is_empty(),
1209 &teams.session,
1210 )
964 1211 };
965 1212 media.push(converted);
966 1213 }
@@ -972,8 +1219,16 @@ pub fn from_teams_offer(teams_sdp: &str) -> Result<RemoteOffer> {
972 1219 let mut session = teams.session.clone();
973 1220 session.bandwidths.clear();
974 1221 session.connection = None;
975 session.attributes.retain(|attribute| matches!(attribute.name.as_str(), "extmap-allow-mixed" | "msid-semantic"));
976 session.attributes.push(Attribute::new("group", bundle_group(media.iter().map(|line| (line.port.as_str(), line.mid())))));
1222 session.attributes.retain(|attribute| {
1223 matches!(
1224 attribute.name.as_str(),
1225 "extmap-allow-mixed" | "msid-semantic"
1226 )
1227 });
1228 session.attributes.push(Attribute::new(
1229 "group",
1230 bundle_group(media.iter().map(|line| (line.port.as_str(), line.mid()))),
1231 ));
977 1232 Ok(RemoteOffer {
978 1233 browser_sdp: write(&SessionDescription { session, media }),
979 1234 lines,
@@ -1010,9 +1265,20 @@ fn browser_data_from_teams(source: &Media, mid: &str, session: &Session) -> Medi
1010 1265 }
1011 1266 }
1012 1267
1013 fn browser_rtp_from_teams(source: &Media, mid: &str, role: LineRole, folded: bool, carries_candidate: bool, session: &Session) -> Media {
1268 fn browser_rtp_from_teams(
1269 source: &Media,
1270 mid: &str,
1271 role: LineRole,
1272 folded: bool,
1273 carries_candidate: bool,
1274 session: &Session,
1275 ) -> Media {
1014 1276 let rtpmap = source.rtpmap();
1015 let is_rtx = |payload: &str| rtpmap.get(payload).is_some_and(|encoding| encoding.starts_with("rtx/"));
1277 let is_rtx = |payload: &str| {
1278 rtpmap
1279 .get(payload)
1280 .is_some_and(|encoding| encoding.starts_with("rtx/"))
1281 };
1016 1282 let mut attributes = Vec::new();
1017 1283 let mut expanded_feedback: Vec<Attribute> = Vec::new();
1018 1284 let mut signals_ssrc = false;
@@ -1084,7 +1350,9 @@ fn browser_rtp_from_teams(source: &Media, mid: &str, role: LineRole, folded: boo
1084 1350
1085 1351 fn browser_rtpmap(value: &str) -> String {
1086 1352 match value.split_once(' ') {
1087 Some((payload, encoding)) if encoding.eq_ignore_ascii_case("red/8000") => format!("{payload} red/48000/2"),
1353 Some((payload, encoding)) if encoding.eq_ignore_ascii_case("red/8000") => {
1354 format!("{payload} red/48000/2")
1355 }
1088 1356 _ => value.to_owned(),
1089 1357 }
1090 1358 }
@@ -1094,7 +1362,11 @@ fn browser_extmap(value: &str) -> String {
1094 1362 }
1095 1363
1096 1364 /// libwebrtc answers every offered line in the offer's order and with its mids, so the offer's plan applies unchanged.
1097 pub fn to_teams_answer(browser_answer_sdp: &str, remote: &RemoteOffer, numbers: &mut impl NumberSource) -> Result<SignaledOffer> {
1365 pub fn to_teams_answer(
1366 browser_answer_sdp: &str,
1367 remote: &RemoteOffer,
1368 numbers: &mut impl NumberSource,
1369 ) -> Result<SignaledOffer> {
1098 1370 to_teams_offer(browser_answer_sdp, &remote.plan(), numbers)
1099 1371 }
1100 1372
@@ -1120,21 +1392,33 @@ mod tests {
1120 1392
1121 1393 #[test]
1122 1394 fn audio_only_offer_gets_the_teams_shape() {
1123 let offer = to_teams_offer(AUDIO_ONLY_OFFER, &OfferPlan::default(), &mut counter()).unwrap();
1395 let offer =
1396 to_teams_offer(AUDIO_ONLY_OFFER, &OfferPlan::default(), &mut counter()).unwrap();
1124 1397 let text = offer.sdp.replace("\r\n", "\n");
1125 1398 assert!(text.contains("\nb=CT:4000\n"));
1126 1399 assert!(text.contains("m=audio 1234 RTP/SAVP 111 63 9 0 8 13 110 126\n"));
1127 1400 assert!(text.contains("a=x-signaling-fb:* x-message app recv:dsh\n"));
1128 1401 assert!(text.contains("a=x-ssrc-range:42-42\n"));
1129 1402 assert!(text.contains("a=rtpmap:63 RED/8000\n"));
1130 assert!(text.contains("a=fmtp:111 minptime=10;useinbandfec=1;maxplaybackrate=48000;sprop-maxcapturerate=48000\n"));
1131 1403 assert!(text.contains("a=rtcp:1234\n"));
1132 assert!(text.contains("a=extmap:2 http:\\\\www.webrtc.org\\experiments\\rtp-hdrext\\abs-send-time\n"));
1404 assert!(text.contains(
1405 "a=extmap:2 http:\\\\www.webrtc.org\\experiments\\rtp-hdrext\\abs-send-time\n"
1406 ));
1133 1407 assert!(text.contains("a=ssrc:42 msid:stream 0\n"));
1134 assert!(text.contains("a=candidate:1755259772 1 UDP 2122197247 10.10.10.10 1234 typ host\n"));
1135 assert!(text.contains("m=audio 1234 RTP/SAVP 111 63 9 0 8 13 110 126\nc=IN IP4 10.10.10.10\n"));
1408 assert!(
1409 text.contains("a=candidate:1755259772 1 UDP 2122197247 10.10.10.10 1234 typ host\n")
1410 );
1411 assert!(
1412 text.contains("m=audio 1234 RTP/SAVP 111 63 9 0 8 13 110 126\nc=IN IP4 10.10.10.10\n")
1413 );
1136 1414 assert!(text.ends_with("a=label:main-audio\n"));
1137 assert_eq!(offer.lines, vec![SignaledLine { browser_mids: vec!["0".into()], role: LineRole::MainAudio }]);
1415 assert_eq!(
1416 offer.lines,
1417 vec![SignaledLine {
1418 browser_mids: vec!["0".into()],
1419 role: LineRole::MainAudio
1420 }]
1421 );
1138 1422 }
1139 1423
1140 1424 #[test]
@@ -1143,54 +1427,99 @@ mod tests {
1143 1427 "a=mid:0\r\n",
1144 1428 "a=mid:0\r\na=candidate:1 1 udp 2121998079 192.0.2.1 45325 typ host generation 0 network-id 1\r\na=candidate:2 1 tcp 1518018303 2001:db8::1 47585 typ host tcptype passive generation 0 network-id 2\r\na=end-of-candidates\r\n",
1145 1429 );
1146 let text = to_teams_offer(&gathered, &OfferPlan::default(), &mut counter()).unwrap().sdp;
1147 let candidates: Vec<&str> = text.lines().filter(|line| line.starts_with("a=candidate:") || line.starts_with("a=end-of-candidates")).collect();
1148 assert_eq!(candidates, vec!["a=candidate:1755259772 1 UDP 2122197247 10.10.10.10 1234 typ host"]);
1430 let text = to_teams_offer(&gathered, &OfferPlan::default(), &mut counter())
1431 .unwrap()
1432 .sdp;
1433 let candidates: Vec<&str> = text
1434 .lines()
1435 .filter(|line| {
1436 line.starts_with("a=candidate:") || line.starts_with("a=end-of-candidates")
1437 })
1438 .collect();
1439 assert_eq!(
1440 candidates,
1441 vec!["a=candidate:1755259772 1 UDP 2122197247 10.10.10.10 1234 typ host"]
1442 );
1149 1443 }
1150 1444
1151 1445 #[test]
1152 1446 fn answer_candidates_lose_teams_extensions() {
1153 1447 assert_eq!(
1154 browser_candidate("1 1 UDP 54001663 52.112.0.1 3480 typ relay raddr 10.0.0.1 rport 3480 MTURNID 158"),
1448 browser_candidate(
1449 "1 1 UDP 54001663 52.112.0.1 3480 typ relay raddr 10.0.0.1 rport 3480 MTURNID 158"
1450 ),
1155 1451 "1 1 UDP 54001663 52.112.0.1 3480 typ relay raddr 10.0.0.1 rport 3480"
1156 1452 );
1157 1453 assert_eq!(
1158 browser_candidate("3 1 tcp-pass 18087935 52.112.0.1 3478 typ relay raddr 10.0.0.1 rport 3478"),
1454 browser_candidate(
1455 "3 1 tcp-pass 18087935 52.112.0.1 3478 typ relay raddr 10.0.0.1 rport 3478"
1456 ),
1159 1457 "3 1 tcp 18087935 52.112.0.1 3478 typ relay raddr 10.0.0.1 rport 3478 tcptype passive"
1160 1458 );
1161 1459 assert_eq!(
1162 browser_candidate("10 1 TCP-ACT 1684794366 192.0.2.1 59611 typ srflx raddr 192.0.2.1 rport 50009"),
1460 browser_candidate(
1461 "10 1 TCP-ACT 1684794366 192.0.2.1 59611 typ srflx raddr 192.0.2.1 rport 50009"
1462 ),
1163 1463 "10 1 tcp 1684794366 192.0.2.1 59611 typ srflx raddr 192.0.2.1 rport 50009 tcptype active"
1164 1464 );
1165 1465 }
1166 1466
1167 1467 #[test]
1168 1468 fn audio_answer_maps_back_to_the_browser_mid_and_codecs() {
1169 let offer = to_teams_offer(AUDIO_ONLY_OFFER, &OfferPlan::default(), &mut counter()).unwrap();
1469 let offer =
1470 to_teams_offer(AUDIO_ONLY_OFFER, &OfferPlan::default(), &mut counter()).unwrap();
1170 1471 let answer = "v=0\r\no=- 7 0 IN IP4 52.112.0.1\r\ns=session\r\nc=IN IP4 52.112.0.1\r\nb=CT:10000000\r\nt=0 0\r\na=group:BUNDLE 0\r\nm=audio 3480 RTP/SAVP 109 111 97 13 101\r\nc=IN IP4 52.112.0.1\r\na=x-source-streamid:201\r\na=rtcp:3480\r\na=setup:passive\r\na=ice-ufrag:U\r\na=ice-pwd:P\r\na=rtcp-mux\r\na=candidate:1 1 UDP 54001663 52.112.0.1 3480 typ relay raddr 10.0.0.1 rport 3480 MTURNID 9\r\na=label:main-audio\r\na=mid:0\r\na=rtpmap:109 SATINFB/48000/2\r\na=rtpmap:111 OPUS/48000/2\r\na=rtpmap:97 RED/8000\r\na=rtpmap:13 CN/8000\r\na=rtpmap:101 telephone-event/8000\r\na=fmtp:101 0-16\r\na=fingerprint:sha-256 BB\r\na=x-ssrc-range:1000-1000\r\n";
1171 let browser = to_browser_answer(answer, &offer, AUDIO_ONLY_OFFER).unwrap().replace("\r\n", "\n");
1172 assert!(browser.contains("m=audio 3480 UDP/TLS/RTP/SAVPF 111 97 13 101\n"), "{browser}");
1472 let browser = to_browser_answer(answer, &offer, AUDIO_ONLY_OFFER)
1473 .unwrap()
1474 .replace("\r\n", "\n");
1475 assert!(
1476 browser.contains("m=audio 3480 UDP/TLS/RTP/SAVPF 111 97 13 101\n"),
1477 "{browser}"
1478 );
1173 1479 assert!(browser.contains("a=rtpmap:97 RED/48000/2\n"));
1174 assert!(browser.contains("a=fmtp:111 usedtx=1;maxaveragebitrate=40000;maxplaybackrate=48000\n"));
1480 assert!(
1481 browser.contains("a=fmtp:111 usedtx=1;maxaveragebitrate=40000;maxplaybackrate=48000\n")
1482 );
1175 1483 assert!(browser.contains("a=fmtp:97 111/111\n"));
1176 1484 assert!(browser.contains("a=rtcp-fb:111 transport-cc\n"));
1177 1485 assert!(browser.contains("a=ssrc:1000 msid:mainAudio-1000 mainAudio-1000\n"));
1178 1486 assert!(browser.contains("a=group:BUNDLE 0\n"));
1179 assert!(!browser.contains("SATINFB") && !browser.contains("MTURNID") && !browser.contains("label"));
1487 assert!(
1488 !browser.contains("SATINFB")
1489 && !browser.contains("MTURNID")
1490 && !browser.contains("label")
1491 );
1180 1492 }
1181 1493 #[test]
1182 1494 fn an_audio_offer_from_teams_gets_the_browser_shape_back() {
1183 let offer = to_teams_offer(AUDIO_ONLY_OFFER, &OfferPlan::default(), &mut counter()).unwrap();
1495 let offer =
1496 to_teams_offer(AUDIO_ONLY_OFFER, &OfferPlan::default(), &mut counter()).unwrap();
1184 1497 let remote = from_teams_offer(&offer.sdp).unwrap();
1185 1498 let text = remote.browser_sdp.replace("\r\n", "\n");
1186 assert!(text.contains("m=audio 9 UDP/TLS/RTP/SAVPF 111 63 9 0 8 13 110 126\n"), "{text}");
1499 assert!(
1500 text.contains("m=audio 9 UDP/TLS/RTP/SAVPF 111 63 9 0 8 13 110 126\n"),
1501 "{text}"
1502 );
1187 1503 assert!(text.contains("c=IN IP4 0.0.0.0\n"));
1188 1504 assert!(text.contains("a=rtcp:9 IN IP4 0.0.0.0\n"));
1189 1505 assert!(text.contains("a=rtpmap:63 red/48000/2\n"));
1190 assert!(text.contains("a=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\n"));
1191 assert!(text.contains("a=ice-ufrag:u\n") && text.contains("a=fingerprint:sha-256 AA\n") && text.contains("a=setup:actpass\n"));
1506 assert!(
1507 text.contains(
1508 "a=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\n"
1509 )
1510 );
1511 assert!(
1512 text.contains("a=ice-ufrag:u\n")
1513 && text.contains("a=fingerprint:sha-256 AA\n")
1514 && text.contains("a=setup:actpass\n")
1515 );
1192 1516 assert!(text.contains("a=mid:0\n") && text.contains("a=group:BUNDLE 0\n"));
1193 assert!(!text.contains("10.10.10.10") && !text.contains("x-ssrc-range") && !text.contains("label") && !text.contains("1234"));
1517 assert!(
1518 !text.contains("10.10.10.10")
1519 && !text.contains("x-ssrc-range")
1520 && !text.contains("label")
1521 && !text.contains("1234")
1522 );
1194 1523 assert_eq!(remote.lines, offer.lines);
1195 1524 }
1196 1525
@@ -1209,10 +1538,20 @@ mod tests {
1209 1538 let remote = from_teams_offer(teams).unwrap();
1210 1539 let parsed = parse(&remote.browser_sdp).unwrap();
1211 1540 let audio: Vec<&str> = parsed.media[0].values("ssrc").collect();
1212 assert!(audio.iter().any(|value| value.starts_with("40475 cname:")), "{audio:?}");
1213 assert_eq!(parsed.media[1].values("ssrc-group").collect::<Vec<_>>(), vec!["FID 40476 40526"]);
1541 assert!(
1542 audio.iter().any(|value| value.starts_with("40475 cname:")),
1543 "{audio:?}"
1544 );
1545 assert_eq!(
1546 parsed.media[1].values("ssrc-group").collect::<Vec<_>>(),
1547 vec!["FID 40476 40526"]
1548 );
1214 1549 let video: Vec<&str> = parsed.media[1].values("ssrc").collect();
1215 assert!(video.iter().any(|value| value.starts_with("40476 cname:")) && video.iter().any(|value| value.starts_with("40526 cname:")), "{video:?}");
1550 assert!(
1551 video.iter().any(|value| value.starts_with("40476 cname:"))
1552 && video.iter().any(|value| value.starts_with("40526 cname:")),
1553 "{video:?}"
1554 );
1216 1555 }
1217 1556
1218 1557 #[test]
@@ -1233,53 +1572,188 @@ mod tests {
1233 1572 const ONE_TO_ONE_VIDEO_OFFER: &str = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0 1 2\r\nm=audio 1234 RTP/SAVP 111\r\nc=IN IP4 10.10.10.10\r\na=rtpmap:111 opus/48000/2\r\na=mid:0\r\na=sendrecv\r\na=ice-ufrag:u\r\na=ice-pwd:p\r\na=fingerprint:sha-256 AA\r\na=setup:actpass\r\na=label:main-audio\r\nm=video 1234 RTP/SAVP 102\r\nc=IN IP4 10.10.10.10\r\na=rtpmap:102 H264/90000\r\na=mid:1\r\na=sendrecv\r\na=label:main-video\r\nm=video 1234 RTP/SAVP 102\r\nc=IN IP4 10.10.10.10\r\na=rtpmap:102 H264/90000\r\na=mid:2\r\na=sendrecv\r\na=label:applicationsharing-video\r\n";
1234 1573
1235 1574 fn browser_answer(camera_direction: &str, share_port: &str, share_direction: &str) -> String {
1236 format!("v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0 1\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\nc=IN IP4 0.0.0.0\r\na=rtpmap:111 opus/48000/2\r\na=mid:0\r\na=sendrecv\r\na=ice-ufrag:u\r\na=ice-pwd:p\r\na=fingerprint:sha-256 BB\r\na=setup:active\r\na=ssrc:7 cname:x\r\nm=video 9 UDP/TLS/RTP/SAVPF 102\r\nc=IN IP4 0.0.0.0\r\na=rtpmap:102 H264/90000\r\na=mid:1\r\na={camera_direction}\r\na=ssrc:8 cname:x\r\nm=video {share_port} UDP/TLS/RTP/SAVPF 102\r\nc=IN IP4 0.0.0.0\r\na=rtpmap:102 H264/90000\r\na=mid:2\r\na={share_direction}\r\n")
1575 format!(
1576 "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0 1\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\nc=IN IP4 0.0.0.0\r\na=rtpmap:111 opus/48000/2\r\na=mid:0\r\na=sendrecv\r\na=ice-ufrag:u\r\na=ice-pwd:p\r\na=fingerprint:sha-256 BB\r\na=setup:active\r\na=ssrc:7 cname:x\r\nm=video 9 UDP/TLS/RTP/SAVPF 102\r\nc=IN IP4 0.0.0.0\r\na=rtpmap:102 H264/90000\r\na=mid:1\r\na={camera_direction}\r\na=ssrc:8 cname:x\r\nm=video {share_port} UDP/TLS/RTP/SAVPF 102\r\nc=IN IP4 0.0.0.0\r\na=rtpmap:102 H264/90000\r\na=mid:2\r\na={share_direction}\r\n"
1577 )
1237 1578 }
1238 1579
1239 1580 #[test]
1240 1581 fn a_folded_line_never_reuses_the_mid_of_another_line() {
1241 1582 let folded = "m=video 1234 RTP/SAVP 102\r\nc=IN IP4 10.10.10.10\r\na=rtpmap:102 H264/90000\r\na=mid:3\r\na=sendrecv\r\na=x-multi-stream:2 1 1 1\r\n";
1242 let teams = format!("{}{folded}", ONE_TO_ONE_VIDEO_OFFER.replace("BUNDLE 0 1 2", "BUNDLE 0 1 2 3"));
1583 let teams = format!(
1584 "{}{folded}",
1585 ONE_TO_ONE_VIDEO_OFFER.replace("BUNDLE 0 1 2", "BUNDLE 0 1 2 3")
1586 );
1243 1587 let remote = from_teams_offer(&teams).unwrap();
1244 let mids: Vec<String> = parse(&remote.browser_sdp).unwrap().media.iter().filter_map(|line| line.mid().map(str::to_owned)).collect();
1588 let mids: Vec<String> = parse(&remote.browser_sdp)
1589 .unwrap()
1590 .media
1591 .iter()
1592 .filter_map(|line| line.mid().map(str::to_owned))
1593 .collect();
1245 1594 let mut unique = mids.clone();
1246 1595 unique.sort();
1247 1596 unique.dedup();
1248 1597 assert_eq!(unique.len(), mids.len(), "{mids:?}");
1249 assert_eq!(remote.lines.last().unwrap().browser_mids, vec!["3-0".to_owned(), "3".to_owned()]);
1598 assert_eq!(
1599 remote.lines.last().unwrap().browser_mids,
1600 vec!["3-0".to_owned(), "3".to_owned()]
1601 );
1250 1602 }
1251 1603
1252 1604 #[test]
1253 1605 fn a_one_to_one_offer_keeps_a_camera_line_and_a_sharing_line() {
1254 1606 let remote = from_teams_offer(ONE_TO_ONE_VIDEO_OFFER).unwrap();
1255 1607 let roles: Vec<LineRole> = remote.lines.iter().map(|line| line.role).collect();
1256 assert_eq!(roles, vec![LineRole::MainAudio, LineRole::MainVideo, LineRole::ScreenShare]);
1608 assert_eq!(
1609 roles,
1610 vec![
1611 LineRole::MainAudio,
1612 LineRole::MainVideo,
1613 LineRole::ScreenShare
1614 ]
1615 );
1257 1616 assert_eq!(remote.plan().screen_share_mids, vec!["2".to_owned()]);
1258 1617 assert!(remote.plan().gallery_mids.is_empty());
1259 assert_eq!(parse(&remote.browser_sdp).unwrap().media.iter().filter(|media| media.kind == "video").count(), 2);
1618 assert_eq!(
1619 parse(&remote.browser_sdp)
1620 .unwrap()
1621 .media
1622 .iter()
1623 .filter(|media| media.kind == "video")
1624 .count(),
1625 2
1626 );
1260 1627 }
1261 1628
1262 1629 #[test]
1263 1630 fn accepting_with_audio_answers_the_video_line_receive_only_and_with_video_sending() {
1264 1631 let remote = from_teams_offer(ONE_TO_ONE_VIDEO_OFFER).unwrap();
1265 1632 for (camera_direction, expected) in [("recvonly", "recvonly"), ("sendrecv", "sendrecv")] {
1266 let answer = to_teams_answer(&browser_answer(camera_direction, "0", "inactive"), &remote, &mut counter()).unwrap();
1633 let answer = to_teams_answer(
1634 &browser_answer(camera_direction, "0", "inactive"),
1635 &remote,
1636 &mut counter(),
1637 )
1638 .unwrap();
1267 1639 let parsed = parse(&answer.sdp).unwrap();
1268 1640 assert_eq!(parsed.media.len(), 3);
1269 1641 assert_eq!(parsed.media[1].port, "1234");
1270 1642 assert_eq!(parsed.media[1].direction(), Some(expected));
1271 1643 assert_eq!(parsed.media[1].value("label"), Some("main-video"));
1272 1644 assert_eq!(parsed.media[2].port, "0");
1273 assert_eq!(parsed.media[2].value("label"), Some("applicationsharing-video"));
1645 assert_eq!(
1646 parsed.media[2].value("label"),
1647 Some("applicationsharing-video")
1648 );
1274 1649 }
1275 1650 }
1276 1651
1277 1652 #[test]
1278 1653 fn folded_gallery_lines_expand_below_their_carrier_mid_unless_those_are_taken() {
1279 1654 let taken = ["0".to_owned(), "1".to_owned(), "17".to_owned()];
1280 assert_eq!(folded_mids("17", 8, &taken), (10..=17).map(|mid| mid.to_string()).collect::<Vec<_>>());
1281 assert_eq!(folded_mids("x", 2, &taken), vec!["x-0".to_owned(), "x".to_owned()]);
1282 assert_eq!(folded_mids("2", 2, &taken), vec!["2-0".to_owned(), "2".to_owned()]);
1655 assert_eq!(
1656 folded_mids("17", 8, &taken),
1657 (10..=17).map(|mid| mid.to_string()).collect::<Vec<_>>()
1658 );
1659 assert_eq!(
1660 folded_mids("x", 2, &taken),
1661 vec!["x-0".to_owned(), "x".to_owned()]
1662 );
1663 assert_eq!(
1664 folded_mids("2", 2, &taken),
1665 vec!["2-0".to_owned(), "2".to_owned()]
1666 );
1667 }
1668
1669 /// Mid 2 is already taken, so mid 3 with x-multi-stream:2 folds to 3-0 + 3 (as in the Hyprland 1:1 call report).
1670 fn folded_carrier_neighbor_taken(label: &str) -> String {
1671 format!(
1672 "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 1 2 5 3 4\r\nm=audio 1234 RTP/SAVP 111\r\nc=IN IP4 10.10.10.10\r\na=rtpmap:111 opus/48000/2\r\na=mid:1\r\na=sendrecv\r\na=label:main-audio\r\na=ice-ufrag:u\r\na=ice-pwd:p\r\na=fingerprint:sha-256 AA\r\na=setup:actpass\r\nm=video 1234 RTP/SAVP 102\r\nc=IN IP4 10.10.10.10\r\na=rtpmap:102 H264/90000\r\na=mid:2\r\na=sendrecv\r\na=label:main-video\r\nm=video 1234 RTP/SAVP 102\r\nc=IN IP4 10.10.10.10\r\na=rtpmap:102 H264/90000\r\na=mid:5\r\na=sendrecv\r\na=label:main-video\r\nm=video 1234 RTP/SAVP 102\r\nc=IN IP4 10.10.10.10\r\na=rtpmap:102 H264/90000\r\na=mid:3\r\na=sendrecv\r\na=label:{label}\r\na=x-multi-stream:2 1 1 1\r\nm=x-data 1234 RTP/SAVP 127\r\nc=IN IP4 10.10.10.10\r\na=mid:4\r\na=sendrecv\r\na=label:data\r\n"
1673 )
1674 }
1675
1676 #[test]
1677 fn a_folded_answer_keeps_one_teams_line_when_carrier_neighbors_are_taken() {
1678 for label in ["main-video", "applicationsharing-video"] {
1679 let offer = folded_carrier_neighbor_taken(label);
1680 let remote = from_teams_offer(&offer).unwrap();
1681 let folded = remote
1682 .lines
1683 .iter()
1684 .find(|line| line.browser_mids.len() > 1)
1685 .expect("folded line");
1686 assert_eq!(
1687 folded.browser_mids,
1688 vec!["3-0".to_owned(), "3".to_owned()]
1689 );
1690 assert_eq!(
1691 remote.plan().fold_groups,
1692 vec![vec!["3-0".to_owned(), "3".to_owned()]]
1693 );
1694 let offer_lines = parse(&offer).unwrap().media.len();
1695 let browser = parse(&remote.browser_sdp).unwrap();
1696 assert_eq!(browser.media.len(), offer_lines + 1);
1697 for port in ["0", "9"] {
1698 let answer_browser = write(&SessionDescription {
1699 session: browser.session.clone(),
1700 media: browser
1701 .media
1702 .iter()
1703 .map(|line| {
1704 let mut line = line.clone();
1705 line.port = if line.kind == "audio" || line.kind == "application" {
1706 "9".to_owned()
1707 } else {
1708 port.to_owned()
1709 };
1710 line.attributes.retain(|attribute| {
1711 !matches!(
1712 attribute.name.as_str(),
1713 "sendrecv" | "recvonly" | "sendonly" | "inactive"
1714 )
1715 });
1716 if line.kind == "audio" || line.kind == "application" {
1717 line.attributes.push(Attribute::flag("sendrecv"));
1718 } else {
1719 line.attributes.push(Attribute::flag("inactive"));
1720 }
1721 line
1722 })
1723 .collect(),
1724 });
1725 let answer = to_teams_answer(&answer_browser, &remote, &mut counter()).unwrap();
1726 let parsed = parse(&answer.sdp).unwrap();
1727 let mids: Vec<_> = parsed
1728 .media
1729 .iter()
1730 .filter_map(|line| line.mid())
1731 .collect();
1732 assert_eq!(
1733 parsed.media.len(),
1734 offer_lines,
1735 "{label} port {port}: answer mids {mids:?} must match the offer line count"
1736 );
1737 assert!(
1738 !mids.iter().any(|mid| *mid == "3-0"),
1739 "{label} port {port}: signaled answer must not expose the internal fold mid: {mids:?}"
1740 );
1741 assert!(mids.iter().any(|mid| *mid == "3"), "{label} port {port}");
1742 let carrier = parsed
1743 .media
1744 .iter()
1745 .find(|line| line.mid() == Some("3"))
1746 .unwrap();
1747 assert_eq!(
1748 carrier
1749 .value("x-multi-stream")
1750 .and_then(|value| value.split(' ').next().map(str::to_owned)),
1751 Some("2".to_owned()),
1752 "{label} port {port}: carrier must keep x-multi-stream"
1753 );
1754 assert_eq!(carrier.value("label"), Some(label));
1755 }
1756 }
1283 1757 }
1284 1758
1285 1759 #[test]
@@ -1288,7 +1762,13 @@ mod tests {
1288 1762 with_opus_send_quality("111 minptime=10;useinbandfec=1"),
1289 1763 "111 minptime=10;useinbandfec=1;maxaveragebitrate=40000;maxplaybackrate=48000"
1290 1764 );
1291 assert_eq!(with_opus_send_quality("111 maxplaybackrate=16000"), "111 maxplaybackrate=16000;maxaveragebitrate=40000");
1292 assert_eq!(with_opus_send_quality("111"), "111 maxaveragebitrate=40000;maxplaybackrate=48000");
1765 assert_eq!(
1766 with_opus_send_quality("111 maxplaybackrate=16000"),
1767 "111 maxplaybackrate=16000;maxaveragebitrate=40000"
1768 );
1769 assert_eq!(
1770 with_opus_send_quality("111"),
1771 "111 maxaveragebitrate=40000;maxplaybackrate=48000"
1772 );
1293 1773 }
1294 1774 }
@@ -12,8 +12,10 @@ const BACKSLASHED_EXTENSIONS: [&str; 2] = [
12 "http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",
12 "http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",
13 "http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",
13 "http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",
14];
14];
15const DROPPED_EXTENSIONS: [&str; 1] = ["http://www.webrtc.org/experiments/rtp-hdrext/playout-delay"];
15const DROPPED_EXTENSIONS: [&str; 1] =
16const LAYERS_ALLOCATION: &str = "http://www.webrtc.org/experiments/rtp-hdrext/video-layers-allocation00";
16 ["http://www.webrtc.org/experiments/rtp-hdrext/playout-delay"];
17const LAYERS_ALLOCATION: &str =
18 "http://www.webrtc.org/experiments/rtp-hdrext/video-layers-allocation00";
17const NOT_ADVERTISED_SUFFIX: &str = "-non-advertised";
19const NOT_ADVERTISED_SUFFIX: &str = "-non-advertised";
18const DIRECTIONS: [&str; 4] = ["sendrecv", "sendonly", "recvonly", "inactive"];
20const DIRECTIONS: [&str; 4] = ["sendrecv", "sendonly", "recvonly", "inactive"];
19
21
@@ -92,7 +94,9 @@ impl Media {
92 }
94 }
93
95
94 pub fn has(&self, name: &str) -> bool {
96 pub fn has(&self, name: &str) -> bool {
95 self.attributes.iter().any(|attribute| attribute.name == name)
97 self.attributes
98 .iter()
99 .any(|attribute| attribute.name == name)
96 }
100 }
97
101
98 pub fn mid(&self) -> Option<&str> {
102 pub fn mid(&self) -> Option<&str> {
@@ -127,7 +131,9 @@ pub fn parse(text: &str) -> Result<SessionDescription> {
127 .ok_or_else(|| Error::Sdp(format!("line without '=': {line}")))?;
131 .ok_or_else(|| Error::Sdp(format!("line without '=': {line}")))?;
128 if kind == "m" {
132 if kind == "m" {
129 let mut parts = value.split(' ');
133 let mut parts = value.split(' ');
130 let (Some(media_kind), Some(port), Some(proto)) = (parts.next(), parts.next(), parts.next()) else {
134 let (Some(media_kind), Some(port), Some(proto)) =
135 (parts.next(), parts.next(), parts.next())
136 else {
131 return Err(Error::Sdp(format!("short m-line: {line}")));
137 return Err(Error::Sdp(format!("short m-line: {line}")));
132 };
138 };
133 media.push(Media {
139 media.push(Media {
@@ -223,8 +229,18 @@ pub fn write(description: &SessionDescription) -> String {
223 format!("o={}", session.origin),
229 format!("o={}", session.origin),
224 format!("s={}", session.name),
230 format!("s={}", session.name),
225 ];
231 ];
226 lines.extend(session.connection.iter().map(|connection| format!("c={connection}")));
232 lines.extend(
227 lines.extend(session.bandwidths.iter().map(|bandwidth| format!("b={bandwidth}")));
233 session
234 .connection
235 .iter()
236 .map(|connection| format!("c={connection}")),
237 );
238 lines.extend(
239 session
240 .bandwidths
241 .iter()
242 .map(|bandwidth| format!("b={bandwidth}")),
243 );
228 lines.push(format!("t={}", session.timing));
244 lines.push(format!("t={}", session.timing));
229 let mut session_attributes: Vec<&Attribute> = session.attributes.iter().collect();
245 let mut session_attributes: Vec<&Attribute> = session.attributes.iter().collect();
230 session_attributes.sort_by_key(|attribute| session_rank(&attribute.name));
246 session_attributes.sort_by_key(|attribute| session_rank(&attribute.name));
@@ -233,8 +249,18 @@ pub fn write(description: &SessionDescription) -> String {
233 let mut header = vec![media.kind.clone(), media.port.clone(), media.proto.clone()];
249 let mut header = vec![media.kind.clone(), media.port.clone(), media.proto.clone()];
234 header.extend(media.formats.iter().cloned());
250 header.extend(media.formats.iter().cloned());
235 lines.push(format!("m={}", header.join(" ")));
251 lines.push(format!("m={}", header.join(" ")));
236 lines.extend(media.connection.iter().map(|connection| format!("c={connection}")));
252 lines.extend(
237 lines.extend(media.bandwidths.iter().map(|bandwidth| format!("b={bandwidth}")));
253 media
254 .connection
255 .iter()
256 .map(|connection| format!("c={connection}")),
257 );
258 lines.extend(
259 media
260 .bandwidths
261 .iter()
262 .map(|bandwidth| format!("b={bandwidth}")),
263 );
238 let mut attributes: Vec<&Attribute> = media.attributes.iter().collect();
264 let mut attributes: Vec<&Attribute> = media.attributes.iter().collect();
239 attributes.sort_by_key(|attribute| media_rank(&attribute.name));
265 attributes.sort_by_key(|attribute| media_rank(&attribute.name));
240 lines.extend(attributes.into_iter().map(Attribute::render));
266 lines.extend(attributes.into_iter().map(Attribute::render));
@@ -272,11 +298,14 @@ impl LineRole {
272 }
298 }
273}
299}
274
300
275/// Which browser m-lines play which Teams role; `gallery_mids` are folded into one `x-multi-stream` line.
301/// Which browser m-lines play which Teams role.
302/// `gallery_mids` / `fold_groups` collapse several browser mids into one Teams `x-multi-stream` line.
276#[derive(Debug, Clone, Default)]
303#[derive(Debug, Clone, Default)]
277pub struct OfferPlan {
304pub struct OfferPlan {
278 pub screen_share_mids: Vec<String>,
305 pub screen_share_mids: Vec<String>,
279 pub gallery_mids: Vec<String>,
306 pub gallery_mids: Vec<String>,
307 /// Each group is one Teams line; the last mid is the carrier written back to Teams.
308 pub fold_groups: Vec<Vec<String>>,
280}
309}
281
310
282#[derive(Debug, Clone, PartialEq, Eq)]
311#[derive(Debug, Clone, PartialEq, Eq)]
@@ -302,20 +331,32 @@ impl<F: FnMut() -> u32> NumberSource for F {
302 }
331 }
303}
332}
304
333
305pub fn to_teams_offer(browser_sdp: &str, plan: &OfferPlan, numbers: &mut impl NumberSource) -> Result<SignaledOffer> {
334pub fn to_teams_offer(
335 browser_sdp: &str,
336 plan: &OfferPlan,
337 numbers: &mut impl NumberSource,
338) -> Result<SignaledOffer> {
306 let browser = parse(browser_sdp)?;
339 let browser = parse(browser_sdp)?;
307 let cname = browser
340 let cname = browser
308 .media
341 .media
309 .iter()
342 .iter()
310 .flat_map(|media| media.values("ssrc"))
343 .flat_map(|media| media.values("ssrc"))
311 .find_map(|value| value.split_once(" cname:").map(|(_, cname)| cname.to_owned()))
344 .find_map(|value| {
345 value
346 .split_once(" cname:")
347 .map(|(_, cname)| cname.to_owned())
348 })
312 .unwrap_or_else(|| format!("{:08x}{:08x}", numbers.next_u32(), numbers.next_u32()));
349 .unwrap_or_else(|| format!("{:08x}{:08x}", numbers.next_u32(), numbers.next_u32()));
313 let gallery_carrier = plan.gallery_mids.last().cloned();
350 let fold_groups = effective_fold_groups(plan);
314 let mut lines = Vec::new();
351 let mut lines = Vec::new();
315 let mut media = Vec::new();
352 let mut media = Vec::new();
316 for source in &browser.media {
353 for source in &browser.media {
317 let mid = source.mid().unwrap_or_default().to_owned();
354 let mid = source.mid().unwrap_or_default().to_owned();
318 if plan.gallery_mids.contains(&mid) && Some(&mid) != gallery_carrier.as_ref() {
355 let fold_group = fold_groups
356 .iter()
357 .find(|group| group.iter().any(|entry| entry == &mid));
358 let fold_carrier = fold_group.and_then(|group| group.last());
359 if fold_group.is_some() && Some(&mid) != fold_carrier {
319 continue;
360 continue;
320 }
361 }
321 let role = match source.kind.as_str() {
362 let role = match source.kind.as_str() {
@@ -324,10 +365,10 @@ pub fn to_teams_offer(browser_sdp: &str, plan: &OfferPlan, numbers: &mut impl Nu
324 _ if plan.screen_share_mids.contains(&mid) => LineRole::ScreenShare,
365 _ if plan.screen_share_mids.contains(&mid) => LineRole::ScreenShare,
325 _ => LineRole::MainVideo,
366 _ => LineRole::MainVideo,
326 };
367 };
327 let multi_stream = (Some(&mid) == gallery_carrier.as_ref()).then_some(plan.gallery_mids.len());
368 let multi_stream = fold_group.map(|group| group.len());
328 let is_first = media.is_empty();
369 let is_first = media.is_empty();
329 let signaled = if source.port == "0" {
370 let signaled = if source.port == "0" {
330 signal_rejected_line(source, role)
371 signal_rejected_line(source, role, multi_stream)
331 } else if role == LineRole::Data {
372 } else if role == LineRole::Data {
332 signal_data_line(source, numbers)
373 signal_data_line(source, numbers)
333 } else {
374 } else {
@@ -335,8 +376,8 @@ pub fn to_teams_offer(browser_sdp: &str, plan: &OfferPlan, numbers: &mut impl Nu
335 };
376 };
336 media.push(signaled);
377 media.push(signaled);
337 lines.push(SignaledLine {
378 lines.push(SignaledLine {
338 browser_mids: match multi_stream {
379 browser_mids: match fold_group {
339 Some(_) => plan.gallery_mids.clone(),
380 Some(group) => group.clone(),
340 None => vec![mid],
381 None => vec![mid],
341 },
382 },
342 role,
383 role,
@@ -347,8 +388,17 @@ pub fn to_teams_offer(browser_sdp: &str, plan: &OfferPlan, numbers: &mut impl Nu
347 for attribute in &mut session.attributes {
388 for attribute in &mut session.attributes {
348 match attribute.name.as_str() {
389 match attribute.name.as_str() {
349 "msid-semantic" => attribute.value = Some(" WMS *".to_owned()),
390 "msid-semantic" => attribute.value = Some(" WMS *".to_owned()),
350 "group" if attribute.value.as_deref().is_some_and(|value| value.starts_with("BUNDLE")) => {
391 "group"
351 let mids: Vec<&str> = media.iter().filter(|line| line.port != "0").filter_map(Media::mid).collect();
392 if attribute
393 .value
394 .as_deref()
395 .is_some_and(|value| value.starts_with("BUNDLE")) =>
396 {
397 let mids: Vec<&str> = media
398 .iter()
399 .filter(|line| line.port != "0")
400 .filter_map(Media::mid)
401 .collect();
352 attribute.value = Some(format!("BUNDLE {}", mids.join(" ")));
402 attribute.value = Some(format!("BUNDLE {}", mids.join(" ")));
353 }
403 }
354 _ => {}
404 _ => {}
@@ -361,14 +411,20 @@ pub fn to_teams_offer(browser_sdp: &str, plan: &OfferPlan, numbers: &mut impl Nu
361 })
411 })
362}
412}
363
413
364fn signal_rejected_line(source: &Media, role: LineRole) -> Media {
414fn signal_rejected_line(source: &Media, role: LineRole, multi_stream: Option<usize>) -> Media {
365 let attributes = vec![
415 let mut attributes = Vec::new();
366 Attribute::new("mid", source.mid().unwrap_or_default()),
416 if let Some(count) = multi_stream {
367 Attribute::flag("inactive"),
417 attributes.push(Attribute::new("x-multi-stream", format!("{count} 1 1 1")));
368 Attribute::new("label", role.label()),
418 }
369 ];
419 attributes.push(Attribute::new("mid", source.mid().unwrap_or_default()));
420 attributes.push(Attribute::flag("inactive"));
421 attributes.push(Attribute::new("label", role.label()));
370 Media {
422 Media {
371 kind: if role == LineRole::Data { "x-data".to_owned() } else { source.kind.clone() },
423 kind: if role == LineRole::Data {
424 "x-data".to_owned()
425 } else {
426 source.kind.clone()
427 },
372 port: "0".to_owned(),
428 port: "0".to_owned(),
373 proto: SIGNALED_PROTO.to_owned(),
429 proto: SIGNALED_PROTO.to_owned(),
374 formats: source.formats.clone(),
430 formats: source.formats.clone(),
@@ -391,7 +447,11 @@ fn signal_rtp_line(
391 media.proto = SIGNALED_PROTO.to_owned();
447 media.proto = SIGNALED_PROTO.to_owned();
392 media.connection = Some(PLACEHOLDER_CONNECTION.to_owned());
448 media.connection = Some(PLACEHOLDER_CONNECTION.to_owned());
393 let rtpmap = source.rtpmap();
449 let rtpmap = source.rtpmap();
394 let is_rtx = |payload: &str| rtpmap.get(payload).is_some_and(|encoding| encoding.starts_with("rtx/"));
450 let is_rtx = |payload: &str| {
451 rtpmap
452 .get(payload)
453 .is_some_and(|encoding| encoding.starts_with("rtx/"))
454 };
395 let mid = source.mid().unwrap_or_default().to_owned();
455 let mid = source.mid().unwrap_or_default().to_owned();
396
456
397 let mut attributes = Vec::new();
457 let mut attributes = Vec::new();
@@ -412,7 +472,10 @@ fn signal_rtp_line(
412 let simulcast = source.has("simulcast");
472 let simulcast = source.has("simulcast");
413 let receive_only = source.direction() == Some("recvonly");
473 let receive_only = source.direction() == Some("recvonly");
414 let (range, ssrc_lines) = if multi_stream.is_some() {
474 let (range, ssrc_lines) = if multi_stream.is_some() {
415 (None, vec![Attribute::new("ssrc", format!("1 cname:{cname}"))])
475 (
476 None,
477 vec![Attribute::new("ssrc", format!("1 cname:{cname}"))],
478 )
416 } else if let Some(&first) = browser_ssrcs.first() {
479 } else if let Some(&first) = browser_ssrcs.first() {
417 let lines = source
480 let lines = source
418 .values("ssrc")
481 .values("ssrc")
@@ -421,13 +484,22 @@ fn signal_rtp_line(
421 (Some((first, first)), lines)
484 (Some((first, first)), lines)
422 } else if simulcast {
485 } else if simulcast {
423 let base = numbers.next_u32();
486 let base = numbers.next_u32();
424 let lines = vec![Attribute::new("ssrc", format!("{base} fake_attribute:fake_value"))];
487 let lines = vec![Attribute::new(
488 "ssrc",
489 format!("{base} fake_attribute:fake_value"),
490 )];
425 (Some((base, base + SSRC_RANGE_SIZE - 1)), lines)
491 (Some((base, base + SSRC_RANGE_SIZE - 1)), lines)
426 } else if receive_only && role != LineRole::MainAudio {
492 } else if receive_only && role != LineRole::MainAudio {
427 (Some((1, 1)), vec![Attribute::new("ssrc", format!("1 cname:{cname}"))])
493 (
494 Some((1, 1)),
495 vec![Attribute::new("ssrc", format!("1 cname:{cname}"))],
496 )
428 } else {
497 } else {
429 let base = numbers.next_u32();
498 let base = numbers.next_u32();
430 (Some((base, base)), vec![Attribute::new("ssrc", format!("{base} cname:{cname}"))])
499 (
500 Some((base, base)),
501 vec![Attribute::new("ssrc", format!("{base} cname:{cname}"))],
502 )
431 };
503 };
432 if let Some((first, last)) = range {
504 if let Some((first, last)) = range {
433 attributes.push(Attribute::new("x-ssrc-range", format!("{first}-{last}")));
505 attributes.push(Attribute::new("x-ssrc-range", format!("{first}-{last}")));
@@ -440,16 +512,18 @@ fn signal_rtp_line(
440 for attribute in &source.attributes {
512 for attribute in &source.attributes {
441 let value = attribute.value.as_deref().unwrap_or_default();
513 let value = attribute.value.as_deref().unwrap_or_default();
442 match attribute.name.as_str() {
514 match attribute.name.as_str() {
443 "ssrc" | "ssrc-group" | "rid" | "simulcast" | "rtcp-xr" | "rtcp-fb" | "candidate" | "end-of-candidates" => {}
515 "ssrc" | "ssrc-group" | "rid" | "simulcast" | "rtcp-xr" | "rtcp-fb" | "candidate"
516 | "end-of-candidates" => {}
444 "rtpmap" => attributes.push(Attribute::new("rtpmap", signal_rtpmap(value))),
517 "rtpmap" => attributes.push(Attribute::new("rtpmap", signal_rtpmap(value))),
445 "fmtp" => {
518 "fmtp" => {
446 let payload = value.split(' ').next().unwrap_or_default();
519 let payload = value.split(' ').next().unwrap_or_default();
447 let position = source.formats.iter().position(|format| format == payload).unwrap_or(usize::MAX);
520 let position = source
448 let is_opus = rtpmap.get(payload).is_some_and(|encoding| encoding.to_ascii_lowercase().starts_with("opus/"));
521 .formats
522 .iter()
523 .position(|format| format == payload)
524 .unwrap_or(usize::MAX);
449 let cleaned = if video {
525 let cleaned = if video {
450 value.replace(";sps-pps-idr-in-keyframe=1", "")
526 value.replace(";sps-pps-idr-in-keyframe=1", "")
451 } else if is_opus {
452 with_fmtp_parameters(value, &OPUS_RECEIVE_FULLBAND)
453 } else {
527 } else {
454 value.to_owned()
528 value.to_owned()
455 };
529 };
@@ -467,14 +541,30 @@ fn signal_rtp_line(
467 fmtp.sort_by_key(|(position, _)| *position);
541 fmtp.sort_by_key(|(position, _)| *position);
468 attributes.extend(fmtp.into_iter().map(|(_, attribute)| attribute));
542 attributes.extend(fmtp.into_iter().map(|(_, attribute)| attribute));
469 match shared_feedback {
543 match shared_feedback {
470 Some(feedback) => attributes.extend(feedback.iter().map(|kind| Attribute::new("rtcp-fb", format!("* {kind}")))),
544 Some(feedback) => attributes.extend(
471 None => attributes.extend(source.attributes.iter().filter(|attribute| attribute.name == "rtcp-fb").cloned()),
545 feedback
546 .iter()
547 .map(|kind| Attribute::new("rtcp-fb", format!("* {kind}"))),
548 ),
549 None => attributes.extend(
550 source
551 .attributes
552 .iter()
553 .filter(|attribute| attribute.name == "rtcp-fb")
554 .cloned(),
555 ),
472 }
556 }
473 if carries_candidate {
557 if carries_candidate {
474 attributes.push(Attribute::new("candidate", PLACEHOLDER_CANDIDATE));
558 attributes.push(Attribute::new("candidate", PLACEHOLDER_CANDIDATE));
475 }
559 }
476 attributes.extend(ssrc_lines);
560 attributes.extend(ssrc_lines);
477 attributes.extend(source.attributes.iter().filter(|attribute| attribute.name == "ssrc-group").cloned());
561 attributes.extend(
562 source
563 .attributes
564 .iter()
565 .filter(|attribute| attribute.name == "ssrc-group")
566 .cloned(),
567 );
478 attributes.push(Attribute::new("label", role.label()));
568 attributes.push(Attribute::new("label", role.label()));
479 if !source.has("rtcp-mux") {
569 if !source.has("rtcp-mux") {
480 attributes.push(Attribute::flag("rtcp-mux"));
570 attributes.push(Attribute::flag("rtcp-mux"));
@@ -495,7 +585,9 @@ fn rewrite_ssrc_msid(value: &str, mid: &str) -> String {
495
585
496fn signal_rtpmap(value: &str) -> String {
586fn signal_rtpmap(value: &str) -> String {
497 match value.split_once(' ') {
587 match value.split_once(' ') {
498 Some((payload, encoding)) if encoding.eq_ignore_ascii_case("red/48000/2") => format!("{payload} RED/8000"),
588 Some((payload, encoding)) if encoding.eq_ignore_ascii_case("red/48000/2") => {
589 format!("{payload} RED/8000")
590 }
499 _ => value.to_owned(),
591 _ => value.to_owned(),
500 }
592 }
501}
593}
@@ -518,7 +610,9 @@ fn feedback_by_payload(source: &Media) -> HashMap<String, Vec<String>> {
518 let mut map: HashMap<String, Vec<String>> = HashMap::new();
610 let mut map: HashMap<String, Vec<String>> = HashMap::new();
519 for value in source.values("rtcp-fb") {
611 for value in source.values("rtcp-fb") {
520 if let Some((payload, kind)) = value.split_once(' ') {
612 if let Some((payload, kind)) = value.split_once(' ') {
521 map.entry(payload.to_owned()).or_default().push(kind.to_owned());
613 map.entry(payload.to_owned())
614 .or_default()
615 .push(kind.to_owned());
522 }
616 }
523 }
617 }
524 map
618 map
@@ -531,7 +625,9 @@ fn shared_feedback(
531) -> Option<Vec<String>> {
625) -> Option<Vec<String>> {
532 let mut codecs = source.formats.iter().filter(|payload| !is_rtx(payload));
626 let mut codecs = source.formats.iter().filter(|payload| !is_rtx(payload));
533 let first = by_payload.get(codecs.next()?)?;
627 let first = by_payload.get(codecs.next()?)?;
534 codecs.all(|payload| by_payload.get(payload) == Some(first)).then(|| first.clone())
628 codecs
629 .all(|payload| by_payload.get(payload) == Some(first))
630 .then(|| first.clone())
535}
631}
536
632
537fn signal_data_line(source: &Media, numbers: &mut impl NumberSource) -> Media {
633fn signal_data_line(source: &Media, numbers: &mut impl NumberSource) -> Media {
@@ -558,7 +654,11 @@ fn signal_data_line(source: &Media, numbers: &mut impl NumberSource) -> Media {
558 }
654 }
559}
655}
560
656
561pub fn to_browser_answer(teams_sdp: &str, offer: &SignaledOffer, browser_offer_sdp: &str) -> Result<String> {
657pub fn to_browser_answer(
658 teams_sdp: &str,
659 offer: &SignaledOffer,
660 browser_offer_sdp: &str,
661) -> Result<String> {
562 let answer = parse(teams_sdp)?;
662 let answer = parse(teams_sdp)?;
563 let browser_offer = parse(browser_offer_sdp)?;
663 let browser_offer = parse(browser_offer_sdp)?;
564 if answer.media.len() != offer.lines.len() {
664 if answer.media.len() != offer.lines.len() {
@@ -582,21 +682,40 @@ pub fn to_browser_answer(teams_sdp: &str, offer: &SignaledOffer, browser_offer_s
582 let section = if signaled.role == LineRole::Data {
682 let section = if signaled.role == LineRole::Data {
583 browser_data_line(teams_line, offered_line, &answer.session)
683 browser_data_line(teams_line, offered_line, &answer.session)
584 } else {
684 } else {
585 browser_rtp_line(teams_line, offered_line, signaled.role, stream_index as u32, index == 0, &answer.session)
685 browser_rtp_line(
686 teams_line,
687 offered_line,
688 signaled.role,
689 stream_index as u32,
690 index == 0,
691 &answer.session,
692 )
586 };
693 };
587 media.push(section);
694 media.push(section);
588 }
695 }
589 }
696 }
590 let mut session = answer.session.clone();
697 let mut session = answer.session.clone();
591 session.attributes.retain(|attribute| attribute.name.starts_with("x-"));
698 session
592 session.attributes.push(Attribute::flag("extmap-allow-mixed"));
699 .attributes
593 session.attributes.push(Attribute::new("msid-semantic", " WMS *"));
700 .retain(|attribute| attribute.name.starts_with("x-"));
594 session.attributes.push(Attribute::new("group", bundle_group(media.iter().map(|line| (line.port.as_str(), line.mid())))));
701 session
702 .attributes
703 .push(Attribute::flag("extmap-allow-mixed"));
704 session
705 .attributes
706 .push(Attribute::new("msid-semantic", " WMS *"));
707 session.attributes.push(Attribute::new(
708 "group",
709 bundle_group(media.iter().map(|line| (line.port.as_str(), line.mid()))),
710 ));
595 Ok(write(&SessionDescription { session, media }))
711 Ok(write(&SessionDescription { session, media }))
596}
712}
597
713
598fn bundle_group<'a>(lines: impl Iterator<Item = (&'a str, Option<&'a str>)>) -> String {
714fn bundle_group<'a>(lines: impl Iterator<Item = (&'a str, Option<&'a str>)>) -> String {
599 let mids: Vec<&str> = lines.filter(|(port, _)| *port != "0").filter_map(|(_, mid)| mid).collect();
715 let mids: Vec<&str> = lines
716 .filter(|(port, _)| *port != "0")
717 .filter_map(|(_, mid)| mid)
718 .collect();
600 format!("BUNDLE {}", mids.join(" "))
719 format!("BUNDLE {}", mids.join(" "))
601}
720}
602
721
@@ -611,11 +730,17 @@ pub struct StreamLine {
611pub fn stream_lines(teams_sdp: &str, lines: &[SignaledLine]) -> Result<Vec<StreamLine>> {
730pub fn stream_lines(teams_sdp: &str, lines: &[SignaledLine]) -> Result<Vec<StreamLine>> {
612 let teams = parse(teams_sdp)?;
731 let teams = parse(teams_sdp)?;
613 if teams.media.len() != lines.len() {
732 if teams.media.len() != lines.len() {
614 return Err(Error::Sdp(format!("sdp has {} m-lines, {} were signaled", teams.media.len(), lines.len())));
733 return Err(Error::Sdp(format!(
734 "sdp has {} m-lines, {} were signaled",
735 teams.media.len(),
736 lines.len()
737 )));
615 }
738 }
616 let mut streams = Vec::new();
739 let mut streams = Vec::new();
617 for (media, line) in teams.media.iter().zip(lines) {
740 for (media, line) in teams.media.iter().zip(lines) {
618 let source_stream_id = media.value("x-source-streamid").and_then(|value| value.trim().parse().ok());
741 let source_stream_id = media
742 .value("x-source-streamid")
743 .and_then(|value| value.trim().parse().ok());
619 let mid = media.mid().unwrap_or_default().to_owned();
744 let mid = media.mid().unwrap_or_default().to_owned();
620 match line.browser_mids.as_slice() {
745 match line.browser_mids.as_slice() {
621 [browser_mid] => streams.push(StreamLine {
746 [browser_mid] => streams.push(StreamLine {
@@ -649,19 +774,17 @@ fn transport_attributes(teams_line: &Media, session: &Session) -> Vec<Attribute>
649 .collect()
774 .collect()
650}
775}
651
776
652const OPUS_SEND_QUALITY: [(&str, &str); 2] = [("maxaveragebitrate", "40000"), ("maxplaybackrate", "48000")];
777const OPUS_SEND_QUALITY: [(&str, &str); 2] =
653
778 [("maxaveragebitrate", "40000"), ("maxplaybackrate", "48000")];
654const OPUS_RECEIVE_FULLBAND: [(&str, &str); 2] = [("maxplaybackrate", "48000"), ("sprop-maxcapturerate", "48000")];
655
779
656/// libwebrtc sizes its Opus encoder from these remote fmtp parameters; without them it picks its own bitrate.
780/// libwebrtc sizes its Opus encoder from these remote fmtp parameters; without them it picks its own bitrate.
657fn with_opus_send_quality(fmtp: &str) -> String {
781fn with_opus_send_quality(fmtp: &str) -> String {
658 with_fmtp_parameters(fmtp, &OPUS_SEND_QUALITY)
659}
660
661fn with_fmtp_parameters(fmtp: &str, parameters: &[(&str, &str)]) -> String {
662 let mut value = fmtp.to_owned();
782 let mut value = fmtp.to_owned();
663 for &(name, setting) in parameters {
783 for (name, setting) in OPUS_SEND_QUALITY {
664 if value.split([' ', ';']).any(|parameter| parameter.split('=').next() == Some(name)) {
784 if value
785 .split([' ', ';'])
786 .any(|parameter| parameter.split('=').next() == Some(name))
787 {
665 continue;
788 continue;
666 }
789 }
667 if !value.ends_with(' ') {
790 if !value.ends_with(' ') {
@@ -704,14 +827,20 @@ fn browser_rtp_line(
704 let payload_of = |value: &str| value.split(' ').next().unwrap_or_default().to_owned();
827 let payload_of = |value: &str| value.split(' ').next().unwrap_or_default().to_owned();
705 let codec_payload = |codec: &str| {
828 let codec_payload = |codec: &str| {
706 kept.iter().find(|payload| {
829 kept.iter().find(|payload| {
707 answer_rtpmap
830 answer_rtpmap.get(*payload).is_some_and(|encoding| {
708 .get(*payload)
831 encoding
709 .is_some_and(|encoding| encoding.to_ascii_lowercase().starts_with(&format!("{codec}/")))
832 .to_ascii_lowercase()
833 .starts_with(&format!("{codec}/"))
834 })
710 })
835 })
711 };
836 };
712
837
713 let mut attributes = Vec::new();
838 let mut attributes = Vec::new();
714 attributes.extend(teams_line.values("x-source-streamid").map(|value| Attribute::new("x-source-streamid", value)));
839 attributes.extend(
840 teams_line
841 .values("x-source-streamid")
842 .map(|value| Attribute::new("x-source-streamid", value)),
843 );
715 for value in teams_line.values("rtpmap") {
844 for value in teams_line.values("rtpmap") {
716 let payload = payload_of(value);
845 let payload = payload_of(value);
717 if !kept_set.contains(payload.as_str()) {
846 if !kept_set.contains(payload.as_str()) {
@@ -739,17 +868,31 @@ fn browser_rtp_line(
739 .join(";");
868 .join(";");
740 let is_opus = codec_payload("opus").is_some_and(|opus| *opus == payload);
869 let is_opus = codec_payload("opus").is_some_and(|opus| *opus == payload);
741 fmtp_payloads.insert(payload);
870 fmtp_payloads.insert(payload);
742 attributes.push(Attribute::new("fmtp", if is_opus { with_opus_send_quality(&cleaned) } else { cleaned }));
871 attributes.push(Attribute::new(
872 "fmtp",
873 if is_opus {
874 with_opus_send_quality(&cleaned)
875 } else {
876 cleaned
877 },
878 ));
743 }
879 }
744 if let Some(opus) = codec_payload("opus").filter(|payload| !fmtp_payloads.contains(*payload)) {
880 if let Some(opus) = codec_payload("opus").filter(|payload| !fmtp_payloads.contains(*payload)) {
745 attributes.push(Attribute::new("fmtp", with_opus_send_quality(&format!("{opus} usedtx=1"))));
881 attributes.push(Attribute::new(
882 "fmtp",
883 with_opus_send_quality(&format!("{opus} usedtx=1")),
884 ));
746 }
885 }
747 if let (Some(red), Some(opus)) = (codec_payload("red"), codec_payload("opus"))
886 if let (Some(red), Some(opus)) = (codec_payload("red"), codec_payload("opus"))
748 && !fmtp_payloads.contains(red)
887 && !fmtp_payloads.contains(red)
749 {
888 {
750 attributes.push(Attribute::new("fmtp", format!("{red} {opus}/{opus}")));
889 attributes.push(Attribute::new("fmtp", format!("{red} {opus}/{opus}")));
751 }
890 }
752 attributes.extend(teams_line.values("rtcp").map(|value| Attribute::new("rtcp", value)));
891 attributes.extend(
892 teams_line
893 .values("rtcp")
894 .map(|value| Attribute::new("rtcp", value)),
895 );
753 let answer_feedback: Vec<&str> = teams_line
896 let answer_feedback: Vec<&str> = teams_line
754 .values("rtcp-fb")
897 .values("rtcp-fb")
755 .filter(|value| !value.contains("x-message"))
898 .filter(|value| !value.contains("x-message"))
@@ -762,7 +905,11 @@ fn browser_rtp_line(
762 .map(|value| Attribute::new("rtcp-fb", value)),
905 .map(|value| Attribute::new("rtcp-fb", value)),
763 );
906 );
764 } else {
907 } else {
765 attributes.extend(answer_feedback.into_iter().map(|value| Attribute::new("rtcp-fb", value)));
908 attributes.extend(
909 answer_feedback
910 .into_iter()
911 .map(|value| Attribute::new("rtcp-fb", value)),
912 );
766 }
913 }
767 for value in teams_line.values("extmap") {
914 for value in teams_line.values("extmap") {
768 let restored = value.replace('\\', "/").replace(NOT_ADVERTISED_SUFFIX, "");
915 let restored = value.replace('\\', "/").replace(NOT_ADVERTISED_SUFFIX, "");
@@ -770,29 +917,53 @@ fn browser_rtp_line(
770 }
917 }
771 attributes.extend(transport_attributes(teams_line, session));
918 attributes.extend(transport_attributes(teams_line, session));
772 attributes.push(Attribute::new("mid", offered.mid().unwrap_or_default()));
919 attributes.push(Attribute::new("mid", offered.mid().unwrap_or_default()));
773 attributes.extend(teams_line.values("ptime").map(|value| Attribute::new("ptime", value)));
920 attributes.extend(
921 teams_line
922 .values("ptime")
923 .map(|value| Attribute::new("ptime", value)),
924 );
774 if let Some(direction) = teams_line.direction() {
925 if let Some(direction) = teams_line.direction() {
775 attributes.push(Attribute::flag(direction));
926 attributes.push(Attribute::flag(direction));
776 }
927 }
777 if carries_candidates {
928 if carries_candidates {
778 attributes.extend(teams_line.values("candidate").chain(teams_line.values("x-candidate-ipv6")).map(|value| Attribute::new("candidate", browser_candidate(value))));
929 attributes.extend(
930 teams_line
931 .values("candidate")
932 .chain(teams_line.values("x-candidate-ipv6"))
933 .map(|value| Attribute::new("candidate", browser_candidate(value))),
934 );
779 }
935 }
780 attributes.extend(stream_ssrc_attributes(teams_line, stream_index, role));
936 attributes.extend(stream_ssrc_attributes(teams_line, stream_index, role));
781 attributes.push(Attribute::flag("rtcp-mux"));
937 attributes.push(Attribute::flag("rtcp-mux"));
782 if teams_line.has("rtcp-rsize") {
938 if teams_line.has("rtcp-rsize") {
783 attributes.push(Attribute::flag("rtcp-rsize"));
939 attributes.push(Attribute::flag("rtcp-rsize"));
784 }
940 }
785 if let Some(simulcast) = offered.value("simulcast").and_then(|value| value.strip_prefix("send ")) {
941 if let Some(simulcast) = offered
786 let rids: Vec<String> = simulcast.split(';').map(|rid| rid.trim_start_matches('~').to_owned()).collect();
942 .value("simulcast")
787 attributes.extend(rids.iter().map(|rid| Attribute::new("rid", format!("{rid} recv"))));
943 .and_then(|value| value.strip_prefix("send "))
788 attributes.push(Attribute::new("simulcast", format!("recv {}", rids.join(";"))));
944 {
945 let rids: Vec<String> = simulcast
946 .split(';')
947 .map(|rid| rid.trim_start_matches('~').to_owned())
948 .collect();
949 attributes.extend(
950 rids.iter()
951 .map(|rid| Attribute::new("rid", format!("{rid} recv"))),
952 );
953 attributes.push(Attribute::new(
954 "simulcast",
955 format!("recv {}", rids.join(";")),
956 ));
789 }
957 }
790 Media {
958 Media {
791 kind: offered.kind.clone(),
959 kind: offered.kind.clone(),
792 port: teams_line.port.clone(),
960 port: teams_line.port.clone(),
793 proto: offered.proto.clone(),
961 proto: offered.proto.clone(),
794 formats: kept,
962 formats: kept,
795 connection: teams_line.connection.clone().or_else(|| session.connection.clone()),
963 connection: teams_line
964 .connection
965 .clone()
966 .or_else(|| session.connection.clone()),
796 bandwidths: teams_line.bandwidths.clone(),
967 bandwidths: teams_line.bandwidths.clone(),
797 attributes,
968 attributes,
798 }
969 }
@@ -805,11 +976,20 @@ fn stream_ssrc_attributes(teams_line: &Media, stream_index: u32, role: LineRole)
805 let stream = format!("{}-{primary}", role.stream_prefix());
976 let stream = format!("{}-{primary}", role.stream_prefix());
806 let mut attributes = Vec::new();
977 let mut attributes = Vec::new();
807 for ssrc in [Some(primary), retransmission].into_iter().flatten() {
978 for ssrc in [Some(primary), retransmission].into_iter().flatten() {
808 attributes.push(Attribute::new("ssrc", format!("{ssrc} cname:{}", stream_cname(primary))));
979 attributes.push(Attribute::new(
809 attributes.push(Attribute::new("ssrc", format!("{ssrc} msid:{stream} {stream}")));
980 "ssrc",
981 format!("{ssrc} cname:{}", stream_cname(primary)),
982 ));
983 attributes.push(Attribute::new(
984 "ssrc",
985 format!("{ssrc} msid:{stream} {stream}"),
986 ));
810 }
987 }
811 if let Some(retransmission) = retransmission {
988 if let Some(retransmission) = retransmission {
812 attributes.push(Attribute::new("ssrc-group", format!("FID {primary} {retransmission}")));
989 attributes.push(Attribute::new(
990 "ssrc-group",
991 format!("FID {primary} {retransmission}"),
992 ));
813 }
993 }
814 attributes
994 attributes
815}
995}
@@ -820,8 +1000,13 @@ fn stream_cname(primary: u32) -> String {
820
1000
821fn stream_ssrcs(teams_line: &Media, stream_index: u32) -> (Option<u32>, Option<u32>) {
1001fn stream_ssrcs(teams_line: &Media, stream_index: u32) -> (Option<u32>, Option<u32>) {
822 let offset = stream_index * SSRC_RANGE_SIZE;
1002 let offset = stream_index * SSRC_RANGE_SIZE;
823 if let Some(group) = teams_line.value("ssrc-group").and_then(|value| value.strip_prefix("FID ")) {
1003 if let Some(group) = teams_line
824 let mut ssrcs = group.split(' ').filter_map(|value| value.parse::<u32>().ok());
1004 .value("ssrc-group")
1005 .and_then(|value| value.strip_prefix("FID "))
1006 {
1007 let mut ssrcs = group
1008 .split(' ')
1009 .filter_map(|value| value.parse::<u32>().ok());
825 let primary = ssrcs.next().map(|ssrc| ssrc + offset);
1010 let primary = ssrcs.next().map(|ssrc| ssrc + offset);
826 return (primary, ssrcs.next().map(|ssrc| ssrc + offset));
1011 return (primary, ssrcs.next().map(|ssrc| ssrc + offset));
827 }
1012 }
@@ -837,7 +1022,11 @@ fn browser_candidate(value: &str) -> String {
837 if let Some(position) = parts.iter().position(|part| *part == "MTURNID") {
1022 if let Some(position) = parts.iter().position(|part| *part == "MTURNID") {
838 parts.truncate(position);
1023 parts.truncate(position);
839 }
1024 }
840 let tcp_type = match parts.get(2).map(|transport| transport.to_ascii_lowercase()).as_deref() {
1025 let tcp_type = match parts
1026 .get(2)
1027 .map(|transport| transport.to_ascii_lowercase())
1028 .as_deref()
1029 {
841 Some("tcp-pass") => Some("passive"),
1030 Some("tcp-pass") => Some("passive"),
842 Some("tcp-act") => Some("active"),
1031 Some("tcp-act") => Some("active"),
843 Some("tcp-so") => Some("so"),
1032 Some("tcp-so") => Some("so"),
@@ -856,16 +1045,27 @@ fn browser_candidate(value: &str) -> String {
856
1045
857fn browser_data_line(teams_line: &Media, offered: &Media, session: &Session) -> Media {
1046fn browser_data_line(teams_line: &Media, offered: &Media, session: &Session) -> Media {
858 let mut attributes = Vec::new();
1047 let mut attributes = Vec::new();
859 attributes.extend(teams_line.values("x-source-streamid").map(|value| Attribute::new("x-source-streamid", value)));
1048 attributes.extend(
1049 teams_line
1050 .values("x-source-streamid")
1051 .map(|value| Attribute::new("x-source-streamid", value)),
1052 );
860 attributes.extend(transport_attributes(teams_line, session));
1053 attributes.extend(transport_attributes(teams_line, session));
861 attributes.push(Attribute::new("mid", offered.mid().unwrap_or_default()));
1054 attributes.push(Attribute::new("mid", offered.mid().unwrap_or_default()));
862 attributes.extend(offered.values("sctp-port").map(|value| Attribute::new("sctp-port", value)));
1055 attributes.extend(
1056 offered
1057 .values("sctp-port")
1058 .map(|value| Attribute::new("sctp-port", value)),
1059 );
863 Media {
1060 Media {
864 kind: offered.kind.clone(),
1061 kind: offered.kind.clone(),
865 port: teams_line.port.clone(),
1062 port: teams_line.port.clone(),
866 proto: offered.proto.clone(),
1063 proto: offered.proto.clone(),
867 formats: offered.formats.clone(),
1064 formats: offered.formats.clone(),
868 connection: teams_line.connection.clone().or_else(|| session.connection.clone()),
1065 connection: teams_line
1066 .connection
1067 .clone()
1068 .or_else(|| session.connection.clone()),
869 bandwidths: Vec::new(),
1069 bandwidths: Vec::new(),
870 attributes,
1070 attributes,
871 }
1071 }
@@ -888,7 +1088,13 @@ const TEAMS_ONLY_ATTRIBUTES: [&str; 6] = [
888 "x-data-protocol",
1088 "x-data-protocol",
889 "label",
1089 "label",
890];
1090];
891const TRANSPORT_ATTRIBUTES: [&str; 5] = ["setup", "ice-ufrag", "ice-pwd", "fingerprint", "ice-options"];
1091const TRANSPORT_ATTRIBUTES: [&str; 5] = [
1092 "setup",
1093 "ice-ufrag",
1094 "ice-pwd",
1095 "fingerprint",
1096 "ice-options",
1097];
892
1098
893/// A Teams offer translated for libwebrtc; `lines` remembers which browser mids each signaled line stands for.
1099/// A Teams offer translated for libwebrtc; `lines` remembers which browser mids each signaled line stands for.
894#[derive(Debug, Clone)]
1100#[derive(Debug, Clone)]
@@ -902,15 +1108,32 @@ impl RemoteOffer {
902 let mut plan = OfferPlan::default();
1108 let mut plan = OfferPlan::default();
903 for line in &self.lines {
1109 for line in &self.lines {
904 match line.role {
1110 match line.role {
905 LineRole::ScreenShare => plan.screen_share_mids.extend(line.browser_mids.iter().cloned()),
1111 LineRole::ScreenShare => plan
906 _ if line.browser_mids.len() > 1 => plan.gallery_mids.extend(line.browser_mids.iter().cloned()),
1112 .screen_share_mids
1113 .extend(line.browser_mids.iter().cloned()),
907 _ => {}
1114 _ => {}
908 }
1115 }
1116 if line.browser_mids.len() > 1 {
1117 plan.gallery_mids
1118 .extend(line.browser_mids.iter().cloned());
1119 plan.fold_groups.push(line.browser_mids.clone());
1120 }
909 }
1121 }
910 plan
1122 plan
911 }
1123 }
912}
1124}
913
1125
1126fn effective_fold_groups(plan: &OfferPlan) -> Vec<Vec<String>> {
1127 if !plan.fold_groups.is_empty() {
1128 return plan.fold_groups.clone();
1129 }
1130 if plan.gallery_mids.len() > 1 {
1131 vec![plan.gallery_mids.clone()]
1132 } else {
1133 Vec::new()
1134 }
1135}
1136
914fn role_of_teams_line(line: &Media) -> LineRole {
1137fn role_of_teams_line(line: &Media) -> LineRole {
915 match line.value("label") {
1138 match line.value("label") {
916 Some("main-audio") => LineRole::MainAudio,
1139 Some("main-audio") => LineRole::MainAudio,
@@ -928,13 +1151,26 @@ fn role_of_teams_line(line: &Media) -> LineRole {
928/// Folded gallery lines get the mids just below the carrier line's own mid, unless another line already uses one of them.
1151/// Folded gallery lines get the mids just below the carrier line's own mid, unless another line already uses one of them.
929fn folded_mids(carrier: &str, count: usize, taken: &[String]) -> Vec<String> {
1152fn folded_mids(carrier: &str, count: usize, taken: &[String]) -> Vec<String> {
930 let below = match carrier.parse::<usize>() {
1153 let below = match carrier.parse::<usize>() {
931 Ok(last) if last + 1 >= count => Some((last + 1 - count..=last).map(|mid| mid.to_string()).collect::<Vec<_>>()),
1154 Ok(last) if last + 1 >= count => Some(
1155 (last + 1 - count..=last)
1156 .map(|mid| mid.to_string())
1157 .collect::<Vec<_>>(),
1158 ),
932 _ => None,
1159 _ => None,
933 };
1160 };
934 match below.filter(|mids| mids.iter().all(|mid| mid == carrier || !taken.contains(mid))) {
1161 match below.filter(|mids| {
1162 mids.iter()
1163 .all(|mid| mid == carrier || !taken.contains(mid))
1164 }) {
935 Some(mids) => mids,
1165 Some(mids) => mids,
936 None => (0..count)
1166 None => (0..count)
937 .map(|index| if index + 1 == count { carrier.to_owned() } else { format!("{carrier}-{index}") })
1167 .map(|index| {
1168 if index + 1 == count {
1169 carrier.to_owned()
1170 } else {
1171 format!("{carrier}-{index}")
1172 }
1173 })
938 .collect(),
1174 .collect(),
939 }
1175 }
940}
1176}
@@ -943,7 +1179,11 @@ pub fn from_teams_offer(teams_sdp: &str) -> Result<RemoteOffer> {
943 let teams = parse(teams_sdp)?;
1179 let teams = parse(teams_sdp)?;
944 let mut media = Vec::new();
1180 let mut media = Vec::new();
945 let mut lines = Vec::new();
1181 let mut lines = Vec::new();
946 let mut taken: Vec<String> = teams.media.iter().filter_map(|line| line.mid().map(str::to_owned)).collect();
1182 let mut taken: Vec<String> = teams
1183 .media
1184 .iter()
1185 .filter_map(|line| line.mid().map(str::to_owned))
1186 .collect();
947 for source in &teams.media {
1187 for source in &teams.media {
948 let role = role_of_teams_line(source);
1188 let role = role_of_teams_line(source);
949 let carrier = source.mid().unwrap_or_default().to_owned();
1189 let carrier = source.mid().unwrap_or_default().to_owned();
@@ -960,7 +1200,14 @@ pub fn from_teams_offer(teams_sdp: &str) -> Result<RemoteOffer> {
960 let converted = if role == LineRole::Data {
1200 let converted = if role == LineRole::Data {
961 browser_data_from_teams(source, mid, &teams.session)
1201 browser_data_from_teams(source, mid, &teams.session)
962 } else {
1202 } else {
963 browser_rtp_from_teams(source, mid, role, folded.is_some(), index == 0 && lines.is_empty(), &teams.session)
1203 browser_rtp_from_teams(
1204 source,
1205 mid,
1206 role,
1207 folded.is_some(),
1208 index == 0 && lines.is_empty(),
1209 &teams.session,
1210 )
964 };
1211 };
965 media.push(converted);
1212 media.push(converted);
966 }
1213 }
@@ -972,8 +1219,16 @@ pub fn from_teams_offer(teams_sdp: &str) -> Result<RemoteOffer> {
972 let mut session = teams.session.clone();
1219 let mut session = teams.session.clone();
973 session.bandwidths.clear();
1220 session.bandwidths.clear();
974 session.connection = None;
1221 session.connection = None;
975 session.attributes.retain(|attribute| matches!(attribute.name.as_str(), "extmap-allow-mixed" | "msid-semantic"));
1222 session.attributes.retain(|attribute| {
976 session.attributes.push(Attribute::new("group", bundle_group(media.iter().map(|line| (line.port.as_str(), line.mid())))));
1223 matches!(
1224 attribute.name.as_str(),
1225 "extmap-allow-mixed" | "msid-semantic"
1226 )
1227 });
1228 session.attributes.push(Attribute::new(
1229 "group",
1230 bundle_group(media.iter().map(|line| (line.port.as_str(), line.mid()))),
1231 ));
977 Ok(RemoteOffer {
1232 Ok(RemoteOffer {
978 browser_sdp: write(&SessionDescription { session, media }),
1233 browser_sdp: write(&SessionDescription { session, media }),
979 lines,
1234 lines,
@@ -1010,9 +1265,20 @@ fn browser_data_from_teams(source: &Media, mid: &str, session: &Session) -> Medi
1010 }
1265 }
1011}
1266}
1012
1267
1013fn browser_rtp_from_teams(source: &Media, mid: &str, role: LineRole, folded: bool, carries_candidate: bool, session: &Session) -> Media {
1268fn browser_rtp_from_teams(
1269 source: &Media,
1270 mid: &str,
1271 role: LineRole,
1272 folded: bool,
1273 carries_candidate: bool,
1274 session: &Session,
1275) -> Media {
1014 let rtpmap = source.rtpmap();
1276 let rtpmap = source.rtpmap();
1015 let is_rtx = |payload: &str| rtpmap.get(payload).is_some_and(|encoding| encoding.starts_with("rtx/"));
1277 let is_rtx = |payload: &str| {
1278 rtpmap
1279 .get(payload)
1280 .is_some_and(|encoding| encoding.starts_with("rtx/"))
1281 };
1016 let mut attributes = Vec::new();
1282 let mut attributes = Vec::new();
1017 let mut expanded_feedback: Vec<Attribute> = Vec::new();
1283 let mut expanded_feedback: Vec<Attribute> = Vec::new();
1018 let mut signals_ssrc = false;
1284 let mut signals_ssrc = false;
@@ -1084,7 +1350,9 @@ fn browser_rtp_from_teams(source: &Media, mid: &str, role: LineRole, folded: boo
1084
1350
1085fn browser_rtpmap(value: &str) -> String {
1351fn browser_rtpmap(value: &str) -> String {
1086 match value.split_once(' ') {
1352 match value.split_once(' ') {
1087 Some((payload, encoding)) if encoding.eq_ignore_ascii_case("red/8000") => format!("{payload} red/48000/2"),
1353 Some((payload, encoding)) if encoding.eq_ignore_ascii_case("red/8000") => {
1354 format!("{payload} red/48000/2")
1355 }
1088 _ => value.to_owned(),
1356 _ => value.to_owned(),
1089 }
1357 }
1090}
1358}
@@ -1094,7 +1362,11 @@ fn browser_extmap(value: &str) -> String {
1094}
1362}
1095
1363
1096/// libwebrtc answers every offered line in the offer's order and with its mids, so the offer's plan applies unchanged.
1364/// libwebrtc answers every offered line in the offer's order and with its mids, so the offer's plan applies unchanged.
1097pub fn to_teams_answer(browser_answer_sdp: &str, remote: &RemoteOffer, numbers: &mut impl NumberSource) -> Result<SignaledOffer> {
1365pub fn to_teams_answer(
1366 browser_answer_sdp: &str,
1367 remote: &RemoteOffer,
1368 numbers: &mut impl NumberSource,
1369) -> Result<SignaledOffer> {
1098 to_teams_offer(browser_answer_sdp, &remote.plan(), numbers)
1370 to_teams_offer(browser_answer_sdp, &remote.plan(), numbers)
1099}
1371}
1100
1372
@@ -1120,21 +1392,33 @@ mod tests {
1120
1392
1121 #[test]
1393 #[test]
1122 fn audio_only_offer_gets_the_teams_shape() {
1394 fn audio_only_offer_gets_the_teams_shape() {
1123 let offer = to_teams_offer(AUDIO_ONLY_OFFER, &OfferPlan::default(), &mut counter()).unwrap();
1395 let offer =
1396 to_teams_offer(AUDIO_ONLY_OFFER, &OfferPlan::default(), &mut counter()).unwrap();
1124 let text = offer.sdp.replace("\r\n", "\n");
1397 let text = offer.sdp.replace("\r\n", "\n");
1125 assert!(text.contains("\nb=CT:4000\n"));
1398 assert!(text.contains("\nb=CT:4000\n"));
1126 assert!(text.contains("m=audio 1234 RTP/SAVP 111 63 9 0 8 13 110 126\n"));
1399 assert!(text.contains("m=audio 1234 RTP/SAVP 111 63 9 0 8 13 110 126\n"));
1127 assert!(text.contains("a=x-signaling-fb:* x-message app recv:dsh\n"));
1400 assert!(text.contains("a=x-signaling-fb:* x-message app recv:dsh\n"));
1128 assert!(text.contains("a=x-ssrc-range:42-42\n"));
1401 assert!(text.contains("a=x-ssrc-range:42-42\n"));
1129 assert!(text.contains("a=rtpmap:63 RED/8000\n"));
1402 assert!(text.contains("a=rtpmap:63 RED/8000\n"));
1130 assert!(text.contains("a=fmtp:111 minptime=10;useinbandfec=1;maxplaybackrate=48000;sprop-maxcapturerate=48000\n"));
1131 assert!(text.contains("a=rtcp:1234\n"));
1403 assert!(text.contains("a=rtcp:1234\n"));
1132 assert!(text.contains("a=extmap:2 http:\\\\www.webrtc.org\\experiments\\rtp-hdrext\\abs-send-time\n"));
1404 assert!(text.contains(
1405 "a=extmap:2 http:\\\\www.webrtc.org\\experiments\\rtp-hdrext\\abs-send-time\n"
1406 ));
1133 assert!(text.contains("a=ssrc:42 msid:stream 0\n"));
1407 assert!(text.contains("a=ssrc:42 msid:stream 0\n"));
1134 assert!(text.contains("a=candidate:1755259772 1 UDP 2122197247 10.10.10.10 1234 typ host\n"));
1408 assert!(
1135 assert!(text.contains("m=audio 1234 RTP/SAVP 111 63 9 0 8 13 110 126\nc=IN IP4 10.10.10.10\n"));
1409 text.contains("a=candidate:1755259772 1 UDP 2122197247 10.10.10.10 1234 typ host\n")
1410 );
1411 assert!(
1412 text.contains("m=audio 1234 RTP/SAVP 111 63 9 0 8 13 110 126\nc=IN IP4 10.10.10.10\n")
1413 );
1136 assert!(text.ends_with("a=label:main-audio\n"));
1414 assert!(text.ends_with("a=label:main-audio\n"));
1137 assert_eq!(offer.lines, vec![SignaledLine { browser_mids: vec!["0".into()], role: LineRole::MainAudio }]);
1415 assert_eq!(
1416 offer.lines,
1417 vec![SignaledLine {
1418 browser_mids: vec!["0".into()],
1419 role: LineRole::MainAudio
1420 }]
1421 );
1138 }
1422 }
1139
1423
1140 #[test]
1424 #[test]
@@ -1143,54 +1427,99 @@ mod tests {
1143 "a=mid:0\r\n",
1427 "a=mid:0\r\n",
1144 "a=mid:0\r\na=candidate:1 1 udp 2121998079 192.0.2.1 45325 typ host generation 0 network-id 1\r\na=candidate:2 1 tcp 1518018303 2001:db8::1 47585 typ host tcptype passive generation 0 network-id 2\r\na=end-of-candidates\r\n",
1428 "a=mid:0\r\na=candidate:1 1 udp 2121998079 192.0.2.1 45325 typ host generation 0 network-id 1\r\na=candidate:2 1 tcp 1518018303 2001:db8::1 47585 typ host tcptype passive generation 0 network-id 2\r\na=end-of-candidates\r\n",
1145 );
1429 );
1146 let text = to_teams_offer(&gathered, &OfferPlan::default(), &mut counter()).unwrap().sdp;
1430 let text = to_teams_offer(&gathered, &OfferPlan::default(), &mut counter())
1147 let candidates: Vec<&str> = text.lines().filter(|line| line.starts_with("a=candidate:") || line.starts_with("a=end-of-candidates")).collect();
1431 .unwrap()
1148 assert_eq!(candidates, vec!["a=candidate:1755259772 1 UDP 2122197247 10.10.10.10 1234 typ host"]);
1432 .sdp;
1433 let candidates: Vec<&str> = text
1434 .lines()
1435 .filter(|line| {
1436 line.starts_with("a=candidate:") || line.starts_with("a=end-of-candidates")
1437 })
1438 .collect();
1439 assert_eq!(
1440 candidates,
1441 vec!["a=candidate:1755259772 1 UDP 2122197247 10.10.10.10 1234 typ host"]
1442 );
1149 }
1443 }
1150
1444
1151 #[test]
1445 #[test]
1152 fn answer_candidates_lose_teams_extensions() {
1446 fn answer_candidates_lose_teams_extensions() {
1153 assert_eq!(
1447 assert_eq!(
1154 browser_candidate("1 1 UDP 54001663 52.112.0.1 3480 typ relay raddr 10.0.0.1 rport 3480 MTURNID 158"),
1448 browser_candidate(
1449 "1 1 UDP 54001663 52.112.0.1 3480 typ relay raddr 10.0.0.1 rport 3480 MTURNID 158"
1450 ),
1155 "1 1 UDP 54001663 52.112.0.1 3480 typ relay raddr 10.0.0.1 rport 3480"
1451 "1 1 UDP 54001663 52.112.0.1 3480 typ relay raddr 10.0.0.1 rport 3480"
1156 );
1452 );
1157 assert_eq!(
1453 assert_eq!(
1158 browser_candidate("3 1 tcp-pass 18087935 52.112.0.1 3478 typ relay raddr 10.0.0.1 rport 3478"),
1454 browser_candidate(
1455 "3 1 tcp-pass 18087935 52.112.0.1 3478 typ relay raddr 10.0.0.1 rport 3478"
1456 ),
1159 "3 1 tcp 18087935 52.112.0.1 3478 typ relay raddr 10.0.0.1 rport 3478 tcptype passive"
1457 "3 1 tcp 18087935 52.112.0.1 3478 typ relay raddr 10.0.0.1 rport 3478 tcptype passive"
1160 );
1458 );
1161 assert_eq!(
1459 assert_eq!(
1162 browser_candidate("10 1 TCP-ACT 1684794366 192.0.2.1 59611 typ srflx raddr 192.0.2.1 rport 50009"),
1460 browser_candidate(
1461 "10 1 TCP-ACT 1684794366 192.0.2.1 59611 typ srflx raddr 192.0.2.1 rport 50009"
1462 ),
1163 "10 1 tcp 1684794366 192.0.2.1 59611 typ srflx raddr 192.0.2.1 rport 50009 tcptype active"
1463 "10 1 tcp 1684794366 192.0.2.1 59611 typ srflx raddr 192.0.2.1 rport 50009 tcptype active"
1164 );
1464 );
1165 }
1465 }
1166
1466
1167 #[test]
1467 #[test]
1168 fn audio_answer_maps_back_to_the_browser_mid_and_codecs() {
1468 fn audio_answer_maps_back_to_the_browser_mid_and_codecs() {
1169 let offer = to_teams_offer(AUDIO_ONLY_OFFER, &OfferPlan::default(), &mut counter()).unwrap();
1469 let offer =
1470 to_teams_offer(AUDIO_ONLY_OFFER, &OfferPlan::default(), &mut counter()).unwrap();
1170 let answer = "v=0\r\no=- 7 0 IN IP4 52.112.0.1\r\ns=session\r\nc=IN IP4 52.112.0.1\r\nb=CT:10000000\r\nt=0 0\r\na=group:BUNDLE 0\r\nm=audio 3480 RTP/SAVP 109 111 97 13 101\r\nc=IN IP4 52.112.0.1\r\na=x-source-streamid:201\r\na=rtcp:3480\r\na=setup:passive\r\na=ice-ufrag:U\r\na=ice-pwd:P\r\na=rtcp-mux\r\na=candidate:1 1 UDP 54001663 52.112.0.1 3480 typ relay raddr 10.0.0.1 rport 3480 MTURNID 9\r\na=label:main-audio\r\na=mid:0\r\na=rtpmap:109 SATINFB/48000/2\r\na=rtpmap:111 OPUS/48000/2\r\na=rtpmap:97 RED/8000\r\na=rtpmap:13 CN/8000\r\na=rtpmap:101 telephone-event/8000\r\na=fmtp:101 0-16\r\na=fingerprint:sha-256 BB\r\na=x-ssrc-range:1000-1000\r\n";
1471 let answer = "v=0\r\no=- 7 0 IN IP4 52.112.0.1\r\ns=session\r\nc=IN IP4 52.112.0.1\r\nb=CT:10000000\r\nt=0 0\r\na=group:BUNDLE 0\r\nm=audio 3480 RTP/SAVP 109 111 97 13 101\r\nc=IN IP4 52.112.0.1\r\na=x-source-streamid:201\r\na=rtcp:3480\r\na=setup:passive\r\na=ice-ufrag:U\r\na=ice-pwd:P\r\na=rtcp-mux\r\na=candidate:1 1 UDP 54001663 52.112.0.1 3480 typ relay raddr 10.0.0.1 rport 3480 MTURNID 9\r\na=label:main-audio\r\na=mid:0\r\na=rtpmap:109 SATINFB/48000/2\r\na=rtpmap:111 OPUS/48000/2\r\na=rtpmap:97 RED/8000\r\na=rtpmap:13 CN/8000\r\na=rtpmap:101 telephone-event/8000\r\na=fmtp:101 0-16\r\na=fingerprint:sha-256 BB\r\na=x-ssrc-range:1000-1000\r\n";
1171 let browser = to_browser_answer(answer, &offer, AUDIO_ONLY_OFFER).unwrap().replace("\r\n", "\n");
1472 let browser = to_browser_answer(answer, &offer, AUDIO_ONLY_OFFER)
1172 assert!(browser.contains("m=audio 3480 UDP/TLS/RTP/SAVPF 111 97 13 101\n"), "{browser}");
1473 .unwrap()
1474 .replace("\r\n", "\n");
1475 assert!(
1476 browser.contains("m=audio 3480 UDP/TLS/RTP/SAVPF 111 97 13 101\n"),
1477 "{browser}"
1478 );
1173 assert!(browser.contains("a=rtpmap:97 RED/48000/2\n"));
1479 assert!(browser.contains("a=rtpmap:97 RED/48000/2\n"));
1174 assert!(browser.contains("a=fmtp:111 usedtx=1;maxaveragebitrate=40000;maxplaybackrate=48000\n"));
1480 assert!(
1481 browser.contains("a=fmtp:111 usedtx=1;maxaveragebitrate=40000;maxplaybackrate=48000\n")
1482 );
1175 assert!(browser.contains("a=fmtp:97 111/111\n"));
1483 assert!(browser.contains("a=fmtp:97 111/111\n"));
1176 assert!(browser.contains("a=rtcp-fb:111 transport-cc\n"));
1484 assert!(browser.contains("a=rtcp-fb:111 transport-cc\n"));
1177 assert!(browser.contains("a=ssrc:1000 msid:mainAudio-1000 mainAudio-1000\n"));
1485 assert!(browser.contains("a=ssrc:1000 msid:mainAudio-1000 mainAudio-1000\n"));
1178 assert!(browser.contains("a=group:BUNDLE 0\n"));
1486 assert!(browser.contains("a=group:BUNDLE 0\n"));
1179 assert!(!browser.contains("SATINFB") && !browser.contains("MTURNID") && !browser.contains("label"));
1487 assert!(
1488 !browser.contains("SATINFB")
1489 && !browser.contains("MTURNID")
1490 && !browser.contains("label")
1491 );
1180 }
1492 }
1181 #[test]
1493 #[test]
1182 fn an_audio_offer_from_teams_gets_the_browser_shape_back() {
1494 fn an_audio_offer_from_teams_gets_the_browser_shape_back() {
1183 let offer = to_teams_offer(AUDIO_ONLY_OFFER, &OfferPlan::default(), &mut counter()).unwrap();
1495 let offer =
1496 to_teams_offer(AUDIO_ONLY_OFFER, &OfferPlan::default(), &mut counter()).unwrap();
1184 let remote = from_teams_offer(&offer.sdp).unwrap();
1497 let remote = from_teams_offer(&offer.sdp).unwrap();
1185 let text = remote.browser_sdp.replace("\r\n", "\n");
1498 let text = remote.browser_sdp.replace("\r\n", "\n");
1186 assert!(text.contains("m=audio 9 UDP/TLS/RTP/SAVPF 111 63 9 0 8 13 110 126\n"), "{text}");
1499 assert!(
1500 text.contains("m=audio 9 UDP/TLS/RTP/SAVPF 111 63 9 0 8 13 110 126\n"),
1501 "{text}"
1502 );
1187 assert!(text.contains("c=IN IP4 0.0.0.0\n"));
1503 assert!(text.contains("c=IN IP4 0.0.0.0\n"));
1188 assert!(text.contains("a=rtcp:9 IN IP4 0.0.0.0\n"));
1504 assert!(text.contains("a=rtcp:9 IN IP4 0.0.0.0\n"));
1189 assert!(text.contains("a=rtpmap:63 red/48000/2\n"));
1505 assert!(text.contains("a=rtpmap:63 red/48000/2\n"));
1190 assert!(text.contains("a=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\n"));
1506 assert!(
1191 assert!(text.contains("a=ice-ufrag:u\n") && text.contains("a=fingerprint:sha-256 AA\n") && text.contains("a=setup:actpass\n"));
1507 text.contains(
1508 "a=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\n"
1509 )
1510 );
1511 assert!(
1512 text.contains("a=ice-ufrag:u\n")
1513 && text.contains("a=fingerprint:sha-256 AA\n")
1514 && text.contains("a=setup:actpass\n")
1515 );
1192 assert!(text.contains("a=mid:0\n") && text.contains("a=group:BUNDLE 0\n"));
1516 assert!(text.contains("a=mid:0\n") && text.contains("a=group:BUNDLE 0\n"));
1193 assert!(!text.contains("10.10.10.10") && !text.contains("x-ssrc-range") && !text.contains("label") && !text.contains("1234"));
1517 assert!(
1518 !text.contains("10.10.10.10")
1519 && !text.contains("x-ssrc-range")
1520 && !text.contains("label")
1521 && !text.contains("1234")
1522 );
1194 assert_eq!(remote.lines, offer.lines);
1523 assert_eq!(remote.lines, offer.lines);
1195 }
1524 }
1196
1525
@@ -1209,10 +1538,20 @@ mod tests {
1209 let remote = from_teams_offer(teams).unwrap();
1538 let remote = from_teams_offer(teams).unwrap();
1210 let parsed = parse(&remote.browser_sdp).unwrap();
1539 let parsed = parse(&remote.browser_sdp).unwrap();
1211 let audio: Vec<&str> = parsed.media[0].values("ssrc").collect();
1540 let audio: Vec<&str> = parsed.media[0].values("ssrc").collect();
1212 assert!(audio.iter().any(|value| value.starts_with("40475 cname:")), "{audio:?}");
1541 assert!(
1213 assert_eq!(parsed.media[1].values("ssrc-group").collect::<Vec<_>>(), vec!["FID 40476 40526"]);
1542 audio.iter().any(|value| value.starts_with("40475 cname:")),
1543 "{audio:?}"
1544 );
1545 assert_eq!(
1546 parsed.media[1].values("ssrc-group").collect::<Vec<_>>(),
1547 vec!["FID 40476 40526"]
1548 );
1214 let video: Vec<&str> = parsed.media[1].values("ssrc").collect();
1549 let video: Vec<&str> = parsed.media[1].values("ssrc").collect();
1215 assert!(video.iter().any(|value| value.starts_with("40476 cname:")) && video.iter().any(|value| value.starts_with("40526 cname:")), "{video:?}");
1550 assert!(
1551 video.iter().any(|value| value.starts_with("40476 cname:"))
1552 && video.iter().any(|value| value.starts_with("40526 cname:")),
1553 "{video:?}"
1554 );
1216 }
1555 }
1217
1556
1218 #[test]
1557 #[test]
@@ -1233,53 +1572,188 @@ mod tests {
1233 const ONE_TO_ONE_VIDEO_OFFER: &str = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0 1 2\r\nm=audio 1234 RTP/SAVP 111\r\nc=IN IP4 10.10.10.10\r\na=rtpmap:111 opus/48000/2\r\na=mid:0\r\na=sendrecv\r\na=ice-ufrag:u\r\na=ice-pwd:p\r\na=fingerprint:sha-256 AA\r\na=setup:actpass\r\na=label:main-audio\r\nm=video 1234 RTP/SAVP 102\r\nc=IN IP4 10.10.10.10\r\na=rtpmap:102 H264/90000\r\na=mid:1\r\na=sendrecv\r\na=label:main-video\r\nm=video 1234 RTP/SAVP 102\r\nc=IN IP4 10.10.10.10\r\na=rtpmap:102 H264/90000\r\na=mid:2\r\na=sendrecv\r\na=label:applicationsharing-video\r\n";
1572 const ONE_TO_ONE_VIDEO_OFFER: &str = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0 1 2\r\nm=audio 1234 RTP/SAVP 111\r\nc=IN IP4 10.10.10.10\r\na=rtpmap:111 opus/48000/2\r\na=mid:0\r\na=sendrecv\r\na=ice-ufrag:u\r\na=ice-pwd:p\r\na=fingerprint:sha-256 AA\r\na=setup:actpass\r\na=label:main-audio\r\nm=video 1234 RTP/SAVP 102\r\nc=IN IP4 10.10.10.10\r\na=rtpmap:102 H264/90000\r\na=mid:1\r\na=sendrecv\r\na=label:main-video\r\nm=video 1234 RTP/SAVP 102\r\nc=IN IP4 10.10.10.10\r\na=rtpmap:102 H264/90000\r\na=mid:2\r\na=sendrecv\r\na=label:applicationsharing-video\r\n";
1234
1573
1235 fn browser_answer(camera_direction: &str, share_port: &str, share_direction: &str) -> String {
1574 fn browser_answer(camera_direction: &str, share_port: &str, share_direction: &str) -> String {
1236 format!("v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0 1\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\nc=IN IP4 0.0.0.0\r\na=rtpmap:111 opus/48000/2\r\na=mid:0\r\na=sendrecv\r\na=ice-ufrag:u\r\na=ice-pwd:p\r\na=fingerprint:sha-256 BB\r\na=setup:active\r\na=ssrc:7 cname:x\r\nm=video 9 UDP/TLS/RTP/SAVPF 102\r\nc=IN IP4 0.0.0.0\r\na=rtpmap:102 H264/90000\r\na=mid:1\r\na={camera_direction}\r\na=ssrc:8 cname:x\r\nm=video {share_port} UDP/TLS/RTP/SAVPF 102\r\nc=IN IP4 0.0.0.0\r\na=rtpmap:102 H264/90000\r\na=mid:2\r\na={share_direction}\r\n")
1575 format!(
1576 "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0 1\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\nc=IN IP4 0.0.0.0\r\na=rtpmap:111 opus/48000/2\r\na=mid:0\r\na=sendrecv\r\na=ice-ufrag:u\r\na=ice-pwd:p\r\na=fingerprint:sha-256 BB\r\na=setup:active\r\na=ssrc:7 cname:x\r\nm=video 9 UDP/TLS/RTP/SAVPF 102\r\nc=IN IP4 0.0.0.0\r\na=rtpmap:102 H264/90000\r\na=mid:1\r\na={camera_direction}\r\na=ssrc:8 cname:x\r\nm=video {share_port} UDP/TLS/RTP/SAVPF 102\r\nc=IN IP4 0.0.0.0\r\na=rtpmap:102 H264/90000\r\na=mid:2\r\na={share_direction}\r\n"
1577 )
1237 }
1578 }
1238
1579
1239 #[test]
1580 #[test]
1240 fn a_folded_line_never_reuses_the_mid_of_another_line() {
1581 fn a_folded_line_never_reuses_the_mid_of_another_line() {
1241 let folded = "m=video 1234 RTP/SAVP 102\r\nc=IN IP4 10.10.10.10\r\na=rtpmap:102 H264/90000\r\na=mid:3\r\na=sendrecv\r\na=x-multi-stream:2 1 1 1\r\n";
1582 let folded = "m=video 1234 RTP/SAVP 102\r\nc=IN IP4 10.10.10.10\r\na=rtpmap:102 H264/90000\r\na=mid:3\r\na=sendrecv\r\na=x-multi-stream:2 1 1 1\r\n";
1242 let teams = format!("{}{folded}", ONE_TO_ONE_VIDEO_OFFER.replace("BUNDLE 0 1 2", "BUNDLE 0 1 2 3"));
1583 let teams = format!(
1584 "{}{folded}",
1585 ONE_TO_ONE_VIDEO_OFFER.replace("BUNDLE 0 1 2", "BUNDLE 0 1 2 3")
1586 );
1243 let remote = from_teams_offer(&teams).unwrap();
1587 let remote = from_teams_offer(&teams).unwrap();
1244 let mids: Vec<String> = parse(&remote.browser_sdp).unwrap().media.iter().filter_map(|line| line.mid().map(str::to_owned)).collect();
1588 let mids: Vec<String> = parse(&remote.browser_sdp)
1589 .unwrap()
1590 .media
1591 .iter()
1592 .filter_map(|line| line.mid().map(str::to_owned))
1593 .collect();
1245 let mut unique = mids.clone();
1594 let mut unique = mids.clone();
1246 unique.sort();
1595 unique.sort();
1247 unique.dedup();
1596 unique.dedup();
1248 assert_eq!(unique.len(), mids.len(), "{mids:?}");
1597 assert_eq!(unique.len(), mids.len(), "{mids:?}");
1249 assert_eq!(remote.lines.last().unwrap().browser_mids, vec!["3-0".to_owned(), "3".to_owned()]);
1598 assert_eq!(
1599 remote.lines.last().unwrap().browser_mids,
1600 vec!["3-0".to_owned(), "3".to_owned()]
1601 );
1250 }
1602 }
1251
1603
1252 #[test]
1604 #[test]
1253 fn a_one_to_one_offer_keeps_a_camera_line_and_a_sharing_line() {
1605 fn a_one_to_one_offer_keeps_a_camera_line_and_a_sharing_line() {
1254 let remote = from_teams_offer(ONE_TO_ONE_VIDEO_OFFER).unwrap();
1606 let remote = from_teams_offer(ONE_TO_ONE_VIDEO_OFFER).unwrap();
1255 let roles: Vec<LineRole> = remote.lines.iter().map(|line| line.role).collect();
1607 let roles: Vec<LineRole> = remote.lines.iter().map(|line| line.role).collect();
1256 assert_eq!(roles, vec![LineRole::MainAudio, LineRole::MainVideo, LineRole::ScreenShare]);
1608 assert_eq!(
1609 roles,
1610 vec![
1611 LineRole::MainAudio,
1612 LineRole::MainVideo,
1613 LineRole::ScreenShare
1614 ]
1615 );
1257 assert_eq!(remote.plan().screen_share_mids, vec!["2".to_owned()]);
1616 assert_eq!(remote.plan().screen_share_mids, vec!["2".to_owned()]);
1258 assert!(remote.plan().gallery_mids.is_empty());
1617 assert!(remote.plan().gallery_mids.is_empty());
1259 assert_eq!(parse(&remote.browser_sdp).unwrap().media.iter().filter(|media| media.kind == "video").count(), 2);
1618 assert_eq!(
1619 parse(&remote.browser_sdp)
1620 .unwrap()
1621 .media
1622 .iter()
1623 .filter(|media| media.kind == "video")
1624 .count(),
1625 2
1626 );
1260 }
1627 }
1261
1628
1262 #[test]
1629 #[test]
1263 fn accepting_with_audio_answers_the_video_line_receive_only_and_with_video_sending() {
1630 fn accepting_with_audio_answers_the_video_line_receive_only_and_with_video_sending() {
1264 let remote = from_teams_offer(ONE_TO_ONE_VIDEO_OFFER).unwrap();
1631 let remote = from_teams_offer(ONE_TO_ONE_VIDEO_OFFER).unwrap();
1265 for (camera_direction, expected) in [("recvonly", "recvonly"), ("sendrecv", "sendrecv")] {
1632 for (camera_direction, expected) in [("recvonly", "recvonly"), ("sendrecv", "sendrecv")] {
1266 let answer = to_teams_answer(&browser_answer(camera_direction, "0", "inactive"), &remote, &mut counter()).unwrap();
1633 let answer = to_teams_answer(
1634 &browser_answer(camera_direction, "0", "inactive"),
1635 &remote,
1636 &mut counter(),
1637 )
1638 .unwrap();
1267 let parsed = parse(&answer.sdp).unwrap();
1639 let parsed = parse(&answer.sdp).unwrap();
1268 assert_eq!(parsed.media.len(), 3);
1640 assert_eq!(parsed.media.len(), 3);
1269 assert_eq!(parsed.media[1].port, "1234");
1641 assert_eq!(parsed.media[1].port, "1234");
1270 assert_eq!(parsed.media[1].direction(), Some(expected));
1642 assert_eq!(parsed.media[1].direction(), Some(expected));
1271 assert_eq!(parsed.media[1].value("label"), Some("main-video"));
1643 assert_eq!(parsed.media[1].value("label"), Some("main-video"));
1272 assert_eq!(parsed.media[2].port, "0");
1644 assert_eq!(parsed.media[2].port, "0");
1273 assert_eq!(parsed.media[2].value("label"), Some("applicationsharing-video"));
1645 assert_eq!(
1646 parsed.media[2].value("label"),
1647 Some("applicationsharing-video")
1648 );
1274 }
1649 }
1275 }
1650 }
1276
1651
1277 #[test]
1652 #[test]
1278 fn folded_gallery_lines_expand_below_their_carrier_mid_unless_those_are_taken() {
1653 fn folded_gallery_lines_expand_below_their_carrier_mid_unless_those_are_taken() {
1279 let taken = ["0".to_owned(), "1".to_owned(), "17".to_owned()];
1654 let taken = ["0".to_owned(), "1".to_owned(), "17".to_owned()];
1280 assert_eq!(folded_mids("17", 8, &taken), (10..=17).map(|mid| mid.to_string()).collect::<Vec<_>>());
1655 assert_eq!(
1281 assert_eq!(folded_mids("x", 2, &taken), vec!["x-0".to_owned(), "x".to_owned()]);
1656 folded_mids("17", 8, &taken),
1282 assert_eq!(folded_mids("2", 2, &taken), vec!["2-0".to_owned(), "2".to_owned()]);
1657 (10..=17).map(|mid| mid.to_string()).collect::<Vec<_>>()
1658 );
1659 assert_eq!(
1660 folded_mids("x", 2, &taken),
1661 vec!["x-0".to_owned(), "x".to_owned()]
1662 );
1663 assert_eq!(
1664 folded_mids("2", 2, &taken),
1665 vec!["2-0".to_owned(), "2".to_owned()]
1666 );
1667 }
1668
1669 /// Mid 2 is already taken, so mid 3 with x-multi-stream:2 folds to 3-0 + 3 (as in the Hyprland 1:1 call report).
1670 fn folded_carrier_neighbor_taken(label: &str) -> String {
1671 format!(
1672 "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 1 2 5 3 4\r\nm=audio 1234 RTP/SAVP 111\r\nc=IN IP4 10.10.10.10\r\na=rtpmap:111 opus/48000/2\r\na=mid:1\r\na=sendrecv\r\na=label:main-audio\r\na=ice-ufrag:u\r\na=ice-pwd:p\r\na=fingerprint:sha-256 AA\r\na=setup:actpass\r\nm=video 1234 RTP/SAVP 102\r\nc=IN IP4 10.10.10.10\r\na=rtpmap:102 H264/90000\r\na=mid:2\r\na=sendrecv\r\na=label:main-video\r\nm=video 1234 RTP/SAVP 102\r\nc=IN IP4 10.10.10.10\r\na=rtpmap:102 H264/90000\r\na=mid:5\r\na=sendrecv\r\na=label:main-video\r\nm=video 1234 RTP/SAVP 102\r\nc=IN IP4 10.10.10.10\r\na=rtpmap:102 H264/90000\r\na=mid:3\r\na=sendrecv\r\na=label:{label}\r\na=x-multi-stream:2 1 1 1\r\nm=x-data 1234 RTP/SAVP 127\r\nc=IN IP4 10.10.10.10\r\na=mid:4\r\na=sendrecv\r\na=label:data\r\n"
1673 )
1674 }
1675
1676 #[test]
1677 fn a_folded_answer_keeps_one_teams_line_when_carrier_neighbors_are_taken() {
1678 for label in ["main-video", "applicationsharing-video"] {
1679 let offer = folded_carrier_neighbor_taken(label);
1680 let remote = from_teams_offer(&offer).unwrap();
1681 let folded = remote
1682 .lines
1683 .iter()
1684 .find(|line| line.browser_mids.len() > 1)
1685 .expect("folded line");
1686 assert_eq!(
1687 folded.browser_mids,
1688 vec!["3-0".to_owned(), "3".to_owned()]
1689 );
1690 assert_eq!(
1691 remote.plan().fold_groups,
1692 vec![vec!["3-0".to_owned(), "3".to_owned()]]
1693 );
1694 let offer_lines = parse(&offer).unwrap().media.len();
1695 let browser = parse(&remote.browser_sdp).unwrap();
1696 assert_eq!(browser.media.len(), offer_lines + 1);
1697 for port in ["0", "9"] {
1698 let answer_browser = write(&SessionDescription {
1699 session: browser.session.clone(),
1700 media: browser
1701 .media
1702 .iter()
1703 .map(|line| {
1704 let mut line = line.clone();
1705 line.port = if line.kind == "audio" || line.kind == "application" {
1706 "9".to_owned()
1707 } else {
1708 port.to_owned()
1709 };
1710 line.attributes.retain(|attribute| {
1711 !matches!(
1712 attribute.name.as_str(),
1713 "sendrecv" | "recvonly" | "sendonly" | "inactive"
1714 )
1715 });
1716 if line.kind == "audio" || line.kind == "application" {
1717 line.attributes.push(Attribute::flag("sendrecv"));
1718 } else {
1719 line.attributes.push(Attribute::flag("inactive"));
1720 }
1721 line
1722 })
1723 .collect(),
1724 });
1725 let answer = to_teams_answer(&answer_browser, &remote, &mut counter()).unwrap();
1726 let parsed = parse(&answer.sdp).unwrap();
1727 let mids: Vec<_> = parsed
1728 .media
1729 .iter()
1730 .filter_map(|line| line.mid())
1731 .collect();
1732 assert_eq!(
1733 parsed.media.len(),
1734 offer_lines,
1735 "{label} port {port}: answer mids {mids:?} must match the offer line count"
1736 );
1737 assert!(
1738 !mids.iter().any(|mid| *mid == "3-0"),
1739 "{label} port {port}: signaled answer must not expose the internal fold mid: {mids:?}"
1740 );
1741 assert!(mids.iter().any(|mid| *mid == "3"), "{label} port {port}");
1742 let carrier = parsed
1743 .media
1744 .iter()
1745 .find(|line| line.mid() == Some("3"))
1746 .unwrap();
1747 assert_eq!(
1748 carrier
1749 .value("x-multi-stream")
1750 .and_then(|value| value.split(' ').next().map(str::to_owned)),
1751 Some("2".to_owned()),
1752 "{label} port {port}: carrier must keep x-multi-stream"
1753 );
1754 assert_eq!(carrier.value("label"), Some(label));
1755 }
1756 }
1283 }
1757 }
1284
1758
1285 #[test]
1759 #[test]
@@ -1288,7 +1762,13 @@ mod tests {
1288 with_opus_send_quality("111 minptime=10;useinbandfec=1"),
1762 with_opus_send_quality("111 minptime=10;useinbandfec=1"),
1289 "111 minptime=10;useinbandfec=1;maxaveragebitrate=40000;maxplaybackrate=48000"
1763 "111 minptime=10;useinbandfec=1;maxaveragebitrate=40000;maxplaybackrate=48000"
1290 );
1764 );
1291 assert_eq!(with_opus_send_quality("111 maxplaybackrate=16000"), "111 maxplaybackrate=16000;maxaveragebitrate=40000");
1765 assert_eq!(
1292 assert_eq!(with_opus_send_quality("111"), "111 maxaveragebitrate=40000;maxplaybackrate=48000");
1766 with_opus_send_quality("111 maxplaybackrate=16000"),
1767 "111 maxplaybackrate=16000;maxaveragebitrate=40000"
1768 );
1769 assert_eq!(
1770 with_opus_send_quality("111"),
1771 "111 maxaveragebitrate=40000;maxplaybackrate=48000"
1772 );
1293 }
1773 }
1294}
1774}
crates/calling/src/video_layout.rs +2 −0
@@ -68,6 +68,7 @@ pub fn offer_plan() -> OfferPlan {
68 68 OfferPlan {
69 69 screen_share_mids: vec![SHARE_MID.to_owned()],
70 70 gallery_mids: Vec::new(),
71 fold_groups: Vec::new(),
71 72 }
72 73 }
73 74
@@ -75,6 +76,7 @@ pub fn one_to_one_plan() -> OfferPlan {
75 76 OfferPlan {
76 77 screen_share_mids: vec![ONE_TO_ONE_SHARE_MID.to_owned()],
77 78 gallery_mids: Vec::new(),
79 fold_groups: Vec::new(),
78 80 }
79 81 }
80 82
@@ -68,6 +68,7 @@ pub fn offer_plan() -> OfferPlan {
68 OfferPlan {
68 OfferPlan {
69 screen_share_mids: vec![SHARE_MID.to_owned()],
69 screen_share_mids: vec![SHARE_MID.to_owned()],
70 gallery_mids: Vec::new(),
70 gallery_mids: Vec::new(),
71 fold_groups: Vec::new(),
71 }
72 }
72}
73}
73
74
@@ -75,6 +76,7 @@ pub fn one_to_one_plan() -> OfferPlan {
75 OfferPlan {
76 OfferPlan {
76 screen_share_mids: vec![ONE_TO_ONE_SHARE_MID.to_owned()],
77 screen_share_mids: vec![ONE_TO_ONE_SHARE_MID.to_owned()],
77 gallery_mids: Vec::new(),
78 gallery_mids: Vec::new(),
79 fold_groups: Vec::new(),
78 }
80 }
79}
81}
80
82
crates/calling/src/video_send.rs +350 −56
@@ -4,10 +4,10 @@ use std::time::{Instant, SystemTime, UNIX_EPOCH};
4 4
5 5 use libwebrtc::media_stream_track::MediaStreamTrack;
6 6 use libwebrtc::peer_connection_factory::PeerConnectionFactory;
7 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
7 8 use libwebrtc::rtp_parameters::DegradationPreference;
8 9 use libwebrtc::rtp_sender::RtpSender;
9 10 use libwebrtc::rtp_transceiver::{RtpTransceiver, RtpTransceiverDirection};
10 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
11 11 use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _, VideoFrame, VideoRotation};
12 12 use libwebrtc::video_source::VideoResolution;
13 13 use libwebrtc::video_source::native::NativeVideoSource;
@@ -16,16 +16,24 @@ use tokio::sync::mpsc::UnboundedSender;
16 16
17 17 use crate::background::BackgroundPicture;
18 18 use crate::blur::BlurSettings;
19 use crate::effects::CameraEffects;
20 use crate::camera::start_camera;
19 use crate::camera::{CameraCaptureStats, start_camera};
20 use crate::video_quality::VideoQuality;
21 21 use crate::capture::Capture;
22 use crate::control::CallUpdate;
22 use crate::control::{CallCommand, CallUpdate};
23 23 use crate::devices::DeviceChoice;
24 use crate::effects::CameraEffects;
24 25 use crate::error::{Error, Result};
25 use crate::screen::{ShareSource, start_screen_capture};
26 use crate::send_control::{EncoderLimits, KEYFRAME_NUDGE, LayerPlan, SendLimit, encoder_limits, plan_layers};
26 use crate::timeline::Timeline;
27 use crate::screen::{
28 PortalFollowUp, ShareKind, ShareSource, start_portal_capture, start_screen_capture,
29 };
30 use crate::send_control::{
31 EncoderLimits, KEYFRAME_NUDGE, LayerPlan, SendLimit, encoder_limits, plan_layers,
32 };
27 33 use crate::standout::StandoutOverlay;
28 use crate::video_frame::{FrameGate, PERSON_FPS, SCREEN_FPS, VideoHub, VideoKey, picture_from_i420};
34 use crate::video_frame::{
35 FrameGate, PERSON_FPS, SCREEN_FPS, VideoHub, VideoKey, picture_from_i420,
36 };
29 37 use crate::video_layout::VideoLines;
30 38 use crate::video_pattern::{PatternKind, spawn_pattern};
31 39
@@ -69,10 +77,20 @@ pub struct LocalSink {
69 77 impl LocalSink {
70 78 pub fn new(source: NativeVideoSource, hub: Option<(Arc<VideoHub>, VideoKey)>) -> Self {
71 79 let self_view = hub.map(|(hub, key)| {
72 let fps = if matches!(key, VideoKey::LocalScreen) { SCREEN_FPS } else { PERSON_FPS };
80 let fps = if matches!(key, VideoKey::LocalScreen) {
81 SCREEN_FPS
82 } else {
83 PERSON_FPS
84 };
73 85 (hub, key, FrameGate::new(fps))
74 86 });
75 LocalSink { source, self_view, mirror: None, standout: None, frame_size: None }
87 LocalSink {
88 source,
89 self_view,
90 mirror: None,
91 standout: None,
92 frame_size: None,
93 }
76 94 }
77 95
78 96 pub fn reporting_size(mut self, frame_size: Arc<AtomicU64>) -> Self {
@@ -96,16 +114,27 @@ impl LocalSink {
96 114 None => buffer,
97 115 };
98 116 if let Some(frame_size) = &self.frame_size {
99 frame_size.store(pack_size(buffer.width(), buffer.height()), Ordering::Relaxed);
117 frame_size.store(
118 pack_size(buffer.width(), buffer.height()),
119 Ordering::Relaxed,
120 );
100 121 }
101 122 let mut frame = VideoFrame::new(VideoRotation::VideoRotation0, buffer);
102 frame.timestamp_us = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |elapsed| elapsed.as_micros() as i64);
123 frame.timestamp_us = SystemTime::now()
124 .duration_since(UNIX_EPOCH)
125 .map_or(0, |elapsed| elapsed.as_micros() as i64);
103 126 self.source.capture_frame(&frame);
104 let Some((hub, key, gate)) = &mut self.self_view else { return };
127 let Some((hub, key, gate)) = &mut self.self_view else {
128 return;
129 };
105 130 if gate.admit(Instant::now())
106 131 && let Some(mut picture) = picture_from_i420(frame.buffer, key.max_width())
107 132 {
108 if self.mirror.as_ref().is_some_and(|settings| settings.effects().mirror) {
133 if self
134 .mirror
135 .as_ref()
136 .is_some_and(|settings| settings.effects().mirror)
137 {
109 138 picture.flip_horizontally();
110 139 }
111 140 hub.publish(key.clone(), picture);
@@ -142,11 +171,22 @@ struct RequestedLimits {
142 171 }
143 172
144 173 impl Outgoing {
145 fn new(factory: &PeerConnectionFactory, label: &str, kind: PatternKind, screencast: bool) -> Self {
174 fn new(
175 factory: &PeerConnectionFactory,
176 label: &str,
177 kind: PatternKind,
178 screencast: bool,
179 ) -> Self {
146 180 let (width, height) = kind.size();
147 181 let source = NativeVideoSource::new(VideoResolution { width, height }, screencast);
148 182 let track = factory.create_video_track(label, source.clone());
149 Outgoing { source, track, capture: None, frame_size: Arc::new(AtomicU64::new(0)), requested: None }
183 Outgoing {
184 source,
185 track,
186 capture: None,
187 frame_size: Arc::new(AtomicU64::new(0)),
188 requested: None,
189 }
150 190 }
151 191 }
152 192
@@ -162,10 +202,24 @@ pub struct LocalVideo {
162 202 motion: bool,
163 203 share_fps: Arc<AtomicU32>,
164 204 camera_preview: bool,
205 quality: VideoQuality,
206 camera_stats: Arc<CameraCaptureStats>,
207 timeline: Option<Timeline>,
208 portal_generation: u64,
209 portal_armed: bool,
210 portal_keep: bool,
211 /// The desktop dialog already bound the PipeWire stream. Later `StartShare`
212 /// commands must attach that capturer, not replace it.
213 portal_bound: bool,
165 214 }
166 215
167 216 impl LocalVideo {
168 pub fn new(factory: &PeerConnectionFactory, mode: VideoMode, hub: Arc<VideoHub>, updates: UnboundedSender<CallUpdate>) -> Self {
217 pub fn new(
218 factory: &PeerConnectionFactory,
219 mode: VideoMode,
220 hub: Arc<VideoHub>,
221 updates: UnboundedSender<CallUpdate>,
222 ) -> Self {
169 223 LocalVideo {
170 224 mode,
171 225 hub,
@@ -177,13 +231,44 @@ impl LocalVideo {
177 231 motion: false,
178 232 share_fps: Arc::new(AtomicU32::new(SCREEN_SHARE_FPS)),
179 233 camera_preview: false,
234 quality: VideoQuality::default(),
235 camera_stats: CameraCaptureStats::new(),
236 timeline: None,
237 portal_generation: 0,
238 portal_armed: false,
239 portal_keep: false,
240 portal_bound: false,
180 241 }
181 242 }
182 243
244 pub fn attach_timeline(&mut self, timeline: Timeline) {
245 self.timeline = Some(timeline);
246 }
247
248 pub fn video_quality(&self) -> VideoQuality {
249 self.quality
250 }
251
252 pub fn set_video_quality(&mut self, quality: VideoQuality) {
253 self.quality = quality;
254 }
255
183 256 pub fn set_motion(&mut self, motion: bool) {
184 257 self.motion = motion;
185 self.share_fps.store(if motion { MOTION_SHARE_FPS } else { SCREEN_SHARE_FPS }, Ordering::Relaxed);
186 if let Some(share) = self.lines.as_ref().and_then(|lines| lines.share.as_ref()).filter(|_| self.sharing()) {
258 self.share_fps.store(
259 if motion {
260 MOTION_SHARE_FPS
261 } else {
262 SCREEN_SHARE_FPS
263 },
264 Ordering::Relaxed,
265 );
266 if let Some(share) = self
267 .lines
268 .as_ref()
269 .and_then(|lines| lines.share.as_ref())
270 .filter(|_| self.sharing())
271 {
187 272 let _ = self.tune_share(&share.sender());
188 273 }
189 274 }
@@ -203,7 +288,9 @@ impl LocalVideo {
203 288 for encoding in &mut parameters.encodings {
204 289 encoding.max_framerate = Some(fps);
205 290 }
206 sender.set_parameters(parameters).map_err(|error| Error::Webrtc(error.to_string()))
291 sender
292 .set_parameters(parameters)
293 .map_err(|error| Error::Webrtc(error.to_string()))
207 294 }
208 295
209 296 fn sender_of(&self, source: SendSource) -> Option<RtpSender> {
@@ -214,19 +301,33 @@ impl LocalVideo {
214 301 }
215 302 }
216 303
217 pub fn apply_send_limit(&mut self, source: SendSource, limits: &[SendLimit]) -> Result<Option<Vec<LayerPlan>>> {
304 pub fn apply_send_limit(
305 &mut self,
306 source: SendSource,
307 limits: &[SendLimit],
308 ) -> Result<Option<Vec<LayerPlan>>> {
218 309 let sending = match source {
219 310 SendSource::Camera => self.camera_on(),
220 311 SendSource::Screen => self.sharing(),
221 312 };
222 let Some(sender) = self.sender_of(source).filter(|_| sending) else { return Ok(None) };
313 let Some(sender) = self.sender_of(source).filter(|_| sending) else {
314 return Ok(None);
315 };
223 316 let outgoing = match source {
224 317 SendSource::Camera => &mut self.camera,
225 318 SendSource::Screen => &mut self.screen,
226 319 };
227 320 let frame = unpack_size(outgoing.frame_size.load(Ordering::Relaxed));
228 outgoing.requested = Some(RequestedLimits { limits: limits.to_vec(), applied_for: frame });
229 let rids: Vec<String> = sender.parameters().encodings.into_iter().map(|encoding| encoding.rid).collect();
321 outgoing.requested = Some(RequestedLimits {
322 limits: limits.to_vec(),
323 applied_for: frame,
324 });
325 let rids: Vec<String> = sender
326 .parameters()
327 .encodings
328 .into_iter()
329 .map(|encoding| encoding.rid)
330 .collect();
230 331 if rids.len() > 1 {
231 332 let plans = plan_layers(limits, frame, &rids);
232 333 if plans.iter().any(|plan| plan.keyframe) {
@@ -235,13 +336,20 @@ impl LocalVideo {
235 336 Self::set_layers(&sender, &plans, 1.0)?;
236 337 return Ok(Some(plans));
237 338 }
238 let Some(limit) = limits.first() else { return Ok(None) };
339 let Some(limit) = limits.first() else {
340 return Ok(None);
341 };
239 342 let encoder = encoder_limits(limit, frame);
240 343 if limit.keyframe {
241 344 Self::set_limits(&sender, &encoder, KEYFRAME_NUDGE)?;
242 345 }
243 346 Self::set_limits(&sender, &encoder, 1.0)?;
244 Ok(Some(vec![LayerPlan { rid: rids.into_iter().next().unwrap_or_default(), active: true, limits: Some(encoder), keyframe: limit.keyframe }]))
347 Ok(Some(vec![LayerPlan {
348 rid: rids.into_iter().next().unwrap_or_default(),
349 active: true,
350 limits: Some(encoder),
351 keyframe: limit.keyframe,
352 }]))
245 353 }
246 354
247 355 /// The mixer sends its limits once, often before the first frame tells the size to scale from.
@@ -253,7 +361,11 @@ impl LocalVideo {
253 361 SendSource::Screen => &self.screen,
254 362 };
255 363 let frame = unpack_size(outgoing.frame_size.load(Ordering::Relaxed));
256 let Some(requested) = outgoing.requested.as_ref().filter(|requested| frame.is_some() && requested.applied_for != frame) else {
364 let Some(requested) = outgoing
365 .requested
366 .as_ref()
367 .filter(|requested| frame.is_some() && requested.applied_for != frame)
368 else {
257 369 continue;
258 370 };
259 371 let limits = requested.limits.clone();
@@ -265,17 +377,22 @@ impl LocalVideo {
265 377 fn set_layers(sender: &RtpSender, plans: &[LayerPlan], nudge: f64) -> Result<()> {
266 378 let mut parameters = sender.parameters();
267 379 for encoding in &mut parameters.encodings {
268 let Some(plan) = plans.iter().find(|plan| plan.rid == encoding.rid) else { continue };
380 let Some(plan) = plans.iter().find(|plan| plan.rid == encoding.rid) else {
381 continue;
382 };
269 383 let nudged = nudge != 1.0 && plan.keyframe;
270 384 encoding.active = plan.active;
271 385 let Some(limits) = &plan.limits else { continue };
272 encoding.scale_resolution_down_by = Some(limits.scale_down_by * if nudged { nudge } else { 1.0 });
386 encoding.scale_resolution_down_by =
387 Some(limits.scale_down_by * if nudged { nudge } else { 1.0 });
273 388 if let Some(framerate) = limits.max_framerate {
274 389 encoding.max_framerate = Some(framerate);
275 390 }
276 391 encoding.max_bitrate = limits.max_bitrate;
277 392 }
278 sender.set_parameters(parameters).map_err(|error| Error::Webrtc(error.to_string()))
393 sender
394 .set_parameters(parameters)
395 .map_err(|error| Error::Webrtc(error.to_string()))
279 396 }
280 397
281 398 fn set_limits(sender: &RtpSender, limits: &EncoderLimits, nudge: f64) -> Result<()> {
@@ -287,7 +404,9 @@ impl LocalVideo {
287 404 }
288 405 encoding.max_bitrate = limits.max_bitrate;
289 406 }
290 sender.set_parameters(parameters).map_err(|error| Error::Webrtc(error.to_string()))
407 sender
408 .set_parameters(parameters)
409 .map_err(|error| Error::Webrtc(error.to_string()))
291 410 }
292 411
293 412 pub fn camera_size(&self) -> Option<(u32, u32)> {
@@ -312,7 +431,9 @@ impl LocalVideo {
312 431 }
313 432
314 433 pub fn blur_model(&self) -> Option<&'static str> {
315 (self.camera_on() && self.blur.active()).then(|| self.blur.model()).filter(|model| !model.is_empty())
434 (self.camera_on() && self.blur.active())
435 .then(|| self.blur.model())
436 .filter(|model| !model.is_empty())
316 437 }
317 438
318 439 pub fn has_lines(&self) -> bool {
@@ -320,17 +441,31 @@ impl LocalVideo {
320 441 }
321 442
322 443 pub fn share_mid(&self) -> Option<String> {
323 self.lines.as_ref().and_then(|lines| lines.share.as_ref()).and_then(|share| share.mid())
444 self.lines
445 .as_ref()
446 .and_then(|lines| lines.share.as_ref())
447 .and_then(|share| share.mid())
324 448 }
325 449
326 450 pub fn has_share_line(&self) -> bool {
327 self.lines.as_ref().is_some_and(|lines| lines.share.is_some())
451 self.lines
452 .as_ref()
453 .is_some_and(|lines| lines.share.is_some())
328 454 }
329 455
330 pub fn add_share_line(&mut self, share: RtpTransceiver, camera: Option<RtpTransceiver>) -> Result<()> {
456 pub fn add_share_line(
457 &mut self,
458 share: RtpTransceiver,
459 camera: Option<RtpTransceiver>,
460 ) -> Result<()> {
331 461 match (self.lines.as_mut(), camera) {
332 462 (Some(lines), _) => lines.share = Some(share),
333 (None, Some(camera)) => self.lines = Some(VideoLines { camera, share: Some(share) }),
463 (None, Some(camera)) => {
464 self.lines = Some(VideoLines {
465 camera,
466 share: Some(share),
467 })
468 }
334 469 (None, None) => return Err(Error::Webrtc("no video line negotiated".into())),
335 470 }
336 471 Ok(())
@@ -341,7 +476,12 @@ impl LocalVideo {
341 476 .as_ref()
342 477 .and_then(|lines| lines.share.as_ref())
343 478 .and_then(|share| share.current_direction())
344 .is_some_and(|direction| matches!(direction, RtpTransceiverDirection::SendOnly | RtpTransceiverDirection::SendRecv))
479 .is_some_and(|direction| {
480 matches!(
481 direction,
482 RtpTransceiverDirection::SendOnly | RtpTransceiverDirection::SendRecv
483 )
484 })
345 485 }
346 486
347 487 pub fn is_available(&self) -> bool {
@@ -360,6 +500,10 @@ impl LocalVideo {
360 500 self.screen.capture.is_some()
361 501 }
362 502
503 pub fn portal_is_open(&self) -> bool {
504 self.portal_armed
505 }
506
363 507 pub fn set_lines(&mut self, lines: VideoLines) -> Result<()> {
364 508 if self.camera_on() {
365 509 Self::begin_sending(&lines.camera.sender(), &self.camera.track)?;
@@ -385,13 +529,28 @@ impl LocalVideo {
385 529 for encoding in &mut parameters.encodings {
386 530 encoding.active = active;
387 531 }
388 sender.set_parameters(parameters).map_err(|error| Error::Webrtc(error.to_string()))
532 sender
533 .set_parameters(parameters)
534 .map_err(|error| Error::Webrtc(error.to_string()))
389 535 }
390 536
391 537 fn camera_sink(&self) -> LocalSink {
392 LocalSink::new(self.camera.source.clone(), Some((self.hub.clone(), VideoKey::LocalCamera)))
393 .mirrored_by(self.blur.clone())
394 .reporting_size(self.camera.frame_size.clone())
538 LocalSink::new(
539 self.camera.source.clone(),
540 Some((self.hub.clone(), VideoKey::LocalCamera)),
541 )
542 .mirrored_by(self.blur.clone())
543 .reporting_size(self.camera.frame_size.clone())
544 }
545
546 /// Local share frames go to the encoder and to the window in the chat.
547 fn screen_sink(&self) -> LocalSink {
548 LocalSink::new(
549 self.screen.source.clone(),
550 Some((self.hub.clone(), VideoKey::LocalScreen)),
551 )
552 .with_standout(self.blur.clone())
553 .reporting_size(self.screen.frame_size.clone())
395 554 }
396 555
397 556 fn report_failure(&self, what: &'static str) -> impl FnOnce(String) + Send + 'static {
@@ -412,7 +571,10 @@ impl LocalVideo {
412 571 }
413 572
414 573 pub fn start_camera(&mut self, choice: &DeviceChoice) -> Result<()> {
415 let lines = self.lines.as_ref().ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?;
574 let lines = self
575 .lines
576 .as_ref()
577 .ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?;
416 578 if !self.is_available() {
417 579 return Err(Error::Webrtc("video is switched off".into()));
418 580 }
@@ -426,14 +588,56 @@ impl LocalVideo {
426 588 Ok(())
427 589 }
428 590
591 pub fn camera_capture_summary(&self) -> Option<String> {
592 self.camera_stats.summary()
593 }
594
429 595 fn capture_camera(&self, choice: &DeviceChoice) -> Result<Capture> {
430 596 let mut sink = self.camera_sink();
431 597 Ok(match self.mode {
432 VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Camera, Some(self.blur.clone()))),
433 _ => start_camera(choice, self.blur.clone(), move |buffer| sink.push(buffer), self.report_failure("Camera"))?,
598 VideoMode::Pattern => Capture::Task(spawn_pattern(
599 sink,
600 PatternKind::Camera,
601 Some(self.blur.clone()),
602 )),
603 _ => {
604 let timeline = self.timeline.clone();
605 start_camera(
606 choice,
607 self.quality,
608 self.blur.clone(),
609 self.camera_stats.clone(),
610 move |label| {
611 if let Some(timeline) = timeline {
612 timeline.record("camera capture", label);
613 } else {
614 eprintln!("calls: camera capture {label}");
615 }
616 },
617 move |buffer| sink.push(buffer),
618 self.report_failure("Camera"),
619 )?
620 }
434 621 })
435 622 }
436 623
624 /// Restart capture with the current quality if the camera is already running.
625 pub fn refresh_camera_capture(&mut self, choice: &DeviceChoice) -> Result<()> {
626 if self.camera.capture.is_none() {
627 return Ok(());
628 }
629 let preview = self.camera_preview;
630 self.camera.capture = None;
631 self.camera.capture = Some(self.capture_camera(choice)?);
632 self.camera_preview = preview;
633 if !preview {
634 if let Some(lines) = self.lines.as_ref() {
635 Self::begin_sending(&lines.camera.sender(), &self.camera.track)?;
636 }
637 }
638 Ok(())
639 }
640
437 641 pub fn stop_camera(&mut self) {
438 642 self.camera_preview = false;
439 643 self.camera.capture = None;
@@ -444,28 +648,110 @@ impl LocalVideo {
444 648 self.hub.forget(&VideoKey::LocalCamera);
445 649 }
446 650
447 pub fn start_share(&mut self, source: &ShareSource) -> Result<()> {
448 let lines = self.lines.as_ref().ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?;
449 let share = lines.share.as_ref().ok_or_else(|| Error::Webrtc("sharing needs a meeting".into()))?;
651 pub fn accept_portal(&mut self, generation: u64) -> bool {
652 if self.portal_armed && self.portal_generation == generation {
653 self.portal_armed = false;
654 self.portal_keep = true;
655 self.portal_bound = true;
656 true
657 } else {
658 false
659 }
660 }
661
662 pub fn open_portal(
663 &mut self,
664 kind: ShareKind,
665 commands: UnboundedSender<CallCommand>,
666 ) -> Result<()> {
450 667 if !self.is_available() {
451 668 return Err(Error::Webrtc("video is switched off".into()));
452 669 }
670 if self.mode == VideoMode::Pattern {
671 let source = ShareSource {
672 id: if kind == ShareKind::Screen { 1 } else { 2 },
673 kind,
674 title: if kind == ShareKind::Screen {
675 "Test screen"
676 } else {
677 "Test window"
678 }
679 .into(),
680 };
681 let _ = commands.send(CallCommand::StartShare(source));
682 return Ok(());
683 }
684 self.portal_generation = self.portal_generation.wrapping_add(1);
685 let generation = self.portal_generation;
686 self.portal_armed = false;
687 self.portal_keep = false;
688 self.portal_bound = false;
453 689 self.screen.capture = None;
454 let mut sink = LocalSink::new(self.screen.source.clone(), None)
455 .with_standout(self.blur.clone())
456 .reporting_size(self.screen.frame_size.clone());
457 let capture = match self.mode {
458 VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Screen, None)),
459 _ => start_screen_capture(source.clone(), self.share_fps.clone(), move |buffer| sink.push(buffer), self.report_failure("Screen share"))?,
460 };
690 let mut sink = self.screen_sink();
691 let updates = self.updates.clone();
692 let capture = start_portal_capture(
693 kind,
694 self.share_fps.clone(),
695 move |buffer| sink.push(buffer),
696 move |follow| match follow {
697 PortalFollowUp::Share(source) => {
698 let _ = commands.send(CallCommand::FinishPortalShare { source, generation });
699 }
700 PortalFollowUp::Quiet => {
701 let _ = commands.send(CallCommand::AbandonPortalShare);
702 }
703 PortalFollowUp::Notice(text) => {
704 let _ = updates.send(CallUpdate::Notice(text.to_owned()));
705 let _ = commands.send(CallCommand::AbandonPortalShare);
706 }
707 },
708 )?;
709 self.portal_armed = true;
710 self.screen.capture = Some(capture);
711 Ok(())
712 }
713
714 pub fn start_share(&mut self, source: &ShareSource) -> Result<()> {
715 let lines = self
716 .lines
717 .as_ref()
718 .ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?;
719 let share = lines
720 .share
721 .as_ref()
722 .ok_or_else(|| Error::Webrtc("sharing needs a meeting".into()))?;
723 if !self.is_available() {
724 return Err(Error::Webrtc("video is switched off".into()));
725 }
726 let keep = std::mem::take(&mut self.portal_keep) || self.portal_bound;
727 if !keep {
728 self.portal_armed = false;
729 self.portal_generation = self.portal_generation.wrapping_add(1);
730 self.screen.capture = None;
731 let mut sink = self.screen_sink();
732 let capture = match self.mode {
733 VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Screen, None)),
734 _ => start_screen_capture(
735 source.clone(),
736 self.share_fps.clone(),
737 move |buffer| sink.push(buffer),
738 self.report_failure("Screen share"),
739 )?,
740 };
741 self.screen.capture = Some(capture);
742 }
461 743 Self::begin_sending(&share.sender(), &self.screen.track)?;
462 744 let _ = self.tune_share(&share.sender());
463 self.screen.capture = Some(capture);
464 745 Ok(())
465 746 }
466 747
467 748 pub fn stop_share(&mut self) {
749 self.portal_generation = self.portal_generation.wrapping_add(1);
750 self.portal_armed = false;
751 self.portal_keep = false;
752 self.portal_bound = false;
468 753 self.screen.capture = None;
754 self.hub.forget(&VideoKey::LocalScreen);
469 755 if let Some(share) = self.lines.as_ref().and_then(|lines| lines.share.as_ref()) {
470 756 let _ = Self::set_active(&share.sender(), false);
471 757 }
@@ -485,10 +771,18 @@ mod tests {
485 771 async fn a_camera_preview_runs_without_a_line_and_stops_cleanly() {
486 772 let (sender, _receiver) = tokio::sync::mpsc::unbounded_channel();
487 773 let factory = crate::devices::shared_factory();
488 let mut video = LocalVideo::new(&factory, VideoMode::Pattern, VideoHub::new(sender.clone()), sender);
774 let mut video = LocalVideo::new(
775 &factory,
776 VideoMode::Pattern,
777 VideoHub::new(sender.clone()),
778 sender,
779 );
489 780 video.preview_camera(&DeviceChoice::SystemDefault).unwrap();
490 781 assert!(video.camera_previewing() && !video.camera_on());
491 assert!(video.start_camera(&DeviceChoice::SystemDefault).is_err(), "sending needs a negotiated line");
782 assert!(
783 video.start_camera(&DeviceChoice::SystemDefault).is_err(),
784 "sending needs a negotiated line"
785 );
492 786 assert!(video.camera_previewing());
493 787 video.stop_camera();
494 788 assert!(!video.camera_previewing() && !video.camera_on());
@@ -4,10 +4,10 @@ use std::time::{Instant, SystemTime, UNIX_EPOCH};
4
4
5use libwebrtc::media_stream_track::MediaStreamTrack;
5use libwebrtc::media_stream_track::MediaStreamTrack;
6use libwebrtc::peer_connection_factory::PeerConnectionFactory;
6use libwebrtc::peer_connection_factory::PeerConnectionFactory;
7use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
7use libwebrtc::rtp_parameters::DegradationPreference;
8use libwebrtc::rtp_parameters::DegradationPreference;
8use libwebrtc::rtp_sender::RtpSender;
9use libwebrtc::rtp_sender::RtpSender;
9use libwebrtc::rtp_transceiver::{RtpTransceiver, RtpTransceiverDirection};
10use libwebrtc::rtp_transceiver::{RtpTransceiver, RtpTransceiverDirection};
10use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
11use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _, VideoFrame, VideoRotation};
11use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _, VideoFrame, VideoRotation};
12use libwebrtc::video_source::VideoResolution;
12use libwebrtc::video_source::VideoResolution;
13use libwebrtc::video_source::native::NativeVideoSource;
13use libwebrtc::video_source::native::NativeVideoSource;
@@ -16,16 +16,24 @@ use tokio::sync::mpsc::UnboundedSender;
16
16
17use crate::background::BackgroundPicture;
17use crate::background::BackgroundPicture;
18use crate::blur::BlurSettings;
18use crate::blur::BlurSettings;
19use crate::effects::CameraEffects;
19use crate::camera::{CameraCaptureStats, start_camera};
20use crate::camera::start_camera;
20use crate::video_quality::VideoQuality;
21use crate::capture::Capture;
21use crate::capture::Capture;
22use crate::control::CallUpdate;
22use crate::control::{CallCommand, CallUpdate};
23use crate::devices::DeviceChoice;
23use crate::devices::DeviceChoice;
24use crate::effects::CameraEffects;
24use crate::error::{Error, Result};
25use crate::error::{Error, Result};
25use crate::screen::{ShareSource, start_screen_capture};
26use crate::timeline::Timeline;
26use crate::send_control::{EncoderLimits, KEYFRAME_NUDGE, LayerPlan, SendLimit, encoder_limits, plan_layers};
27use crate::screen::{
28 PortalFollowUp, ShareKind, ShareSource, start_portal_capture, start_screen_capture,
29};
30use crate::send_control::{
31 EncoderLimits, KEYFRAME_NUDGE, LayerPlan, SendLimit, encoder_limits, plan_layers,
32};
27use crate::standout::StandoutOverlay;
33use crate::standout::StandoutOverlay;
28use crate::video_frame::{FrameGate, PERSON_FPS, SCREEN_FPS, VideoHub, VideoKey, picture_from_i420};
34use crate::video_frame::{
35 FrameGate, PERSON_FPS, SCREEN_FPS, VideoHub, VideoKey, picture_from_i420,
36};
29use crate::video_layout::VideoLines;
37use crate::video_layout::VideoLines;
30use crate::video_pattern::{PatternKind, spawn_pattern};
38use crate::video_pattern::{PatternKind, spawn_pattern};
31
39
@@ -69,10 +77,20 @@ pub struct LocalSink {
69impl LocalSink {
77impl LocalSink {
70 pub fn new(source: NativeVideoSource, hub: Option<(Arc<VideoHub>, VideoKey)>) -> Self {
78 pub fn new(source: NativeVideoSource, hub: Option<(Arc<VideoHub>, VideoKey)>) -> Self {
71 let self_view = hub.map(|(hub, key)| {
79 let self_view = hub.map(|(hub, key)| {
72 let fps = if matches!(key, VideoKey::LocalScreen) { SCREEN_FPS } else { PERSON_FPS };
80 let fps = if matches!(key, VideoKey::LocalScreen) {
81 SCREEN_FPS
82 } else {
83 PERSON_FPS
84 };
73 (hub, key, FrameGate::new(fps))
85 (hub, key, FrameGate::new(fps))
74 });
86 });
75 LocalSink { source, self_view, mirror: None, standout: None, frame_size: None }
87 LocalSink {
88 source,
89 self_view,
90 mirror: None,
91 standout: None,
92 frame_size: None,
93 }
76 }
94 }
77
95
78 pub fn reporting_size(mut self, frame_size: Arc<AtomicU64>) -> Self {
96 pub fn reporting_size(mut self, frame_size: Arc<AtomicU64>) -> Self {
@@ -96,16 +114,27 @@ impl LocalSink {
96 None => buffer,
114 None => buffer,
97 };
115 };
98 if let Some(frame_size) = &self.frame_size {
116 if let Some(frame_size) = &self.frame_size {
99 frame_size.store(pack_size(buffer.width(), buffer.height()), Ordering::Relaxed);
117 frame_size.store(
118 pack_size(buffer.width(), buffer.height()),
119 Ordering::Relaxed,
120 );
100 }
121 }
101 let mut frame = VideoFrame::new(VideoRotation::VideoRotation0, buffer);
122 let mut frame = VideoFrame::new(VideoRotation::VideoRotation0, buffer);
102 frame.timestamp_us = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |elapsed| elapsed.as_micros() as i64);
123 frame.timestamp_us = SystemTime::now()
124 .duration_since(UNIX_EPOCH)
125 .map_or(0, |elapsed| elapsed.as_micros() as i64);
103 self.source.capture_frame(&frame);
126 self.source.capture_frame(&frame);
104 let Some((hub, key, gate)) = &mut self.self_view else { return };
127 let Some((hub, key, gate)) = &mut self.self_view else {
128 return;
129 };
105 if gate.admit(Instant::now())
130 if gate.admit(Instant::now())
106 && let Some(mut picture) = picture_from_i420(frame.buffer, key.max_width())
131 && let Some(mut picture) = picture_from_i420(frame.buffer, key.max_width())
107 {
132 {
108 if self.mirror.as_ref().is_some_and(|settings| settings.effects().mirror) {
133 if self
134 .mirror
135 .as_ref()
136 .is_some_and(|settings| settings.effects().mirror)
137 {
109 picture.flip_horizontally();
138 picture.flip_horizontally();
110 }
139 }
111 hub.publish(key.clone(), picture);
140 hub.publish(key.clone(), picture);
@@ -142,11 +171,22 @@ struct RequestedLimits {
142}
171}
143
172
144impl Outgoing {
173impl Outgoing {
145 fn new(factory: &PeerConnectionFactory, label: &str, kind: PatternKind, screencast: bool) -> Self {
174 fn new(
175 factory: &PeerConnectionFactory,
176 label: &str,
177 kind: PatternKind,
178 screencast: bool,
179 ) -> Self {
146 let (width, height) = kind.size();
180 let (width, height) = kind.size();
147 let source = NativeVideoSource::new(VideoResolution { width, height }, screencast);
181 let source = NativeVideoSource::new(VideoResolution { width, height }, screencast);
148 let track = factory.create_video_track(label, source.clone());
182 let track = factory.create_video_track(label, source.clone());
149 Outgoing { source, track, capture: None, frame_size: Arc::new(AtomicU64::new(0)), requested: None }
183 Outgoing {
184 source,
185 track,
186 capture: None,
187 frame_size: Arc::new(AtomicU64::new(0)),
188 requested: None,
189 }
150 }
190 }
151}
191}
152
192
@@ -162,10 +202,24 @@ pub struct LocalVideo {
162 motion: bool,
202 motion: bool,
163 share_fps: Arc<AtomicU32>,
203 share_fps: Arc<AtomicU32>,
164 camera_preview: bool,
204 camera_preview: bool,
205 quality: VideoQuality,
206 camera_stats: Arc<CameraCaptureStats>,
207 timeline: Option<Timeline>,
208 portal_generation: u64,
209 portal_armed: bool,
210 portal_keep: bool,
211 /// The desktop dialog already bound the PipeWire stream. Later `StartShare`
212 /// commands must attach that capturer, not replace it.
213 portal_bound: bool,
165}
214}
166
215
167impl LocalVideo {
216impl LocalVideo {
168 pub fn new(factory: &PeerConnectionFactory, mode: VideoMode, hub: Arc<VideoHub>, updates: UnboundedSender<CallUpdate>) -> Self {
217 pub fn new(
218 factory: &PeerConnectionFactory,
219 mode: VideoMode,
220 hub: Arc<VideoHub>,
221 updates: UnboundedSender<CallUpdate>,
222 ) -> Self {
169 LocalVideo {
223 LocalVideo {
170 mode,
224 mode,
171 hub,
225 hub,
@@ -177,13 +231,44 @@ impl LocalVideo {
177 motion: false,
231 motion: false,
178 share_fps: Arc::new(AtomicU32::new(SCREEN_SHARE_FPS)),
232 share_fps: Arc::new(AtomicU32::new(SCREEN_SHARE_FPS)),
179 camera_preview: false,
233 camera_preview: false,
234 quality: VideoQuality::default(),
235 camera_stats: CameraCaptureStats::new(),
236 timeline: None,
237 portal_generation: 0,
238 portal_armed: false,
239 portal_keep: false,
240 portal_bound: false,
180 }
241 }
181 }
242 }
182
243
244 pub fn attach_timeline(&mut self, timeline: Timeline) {
245 self.timeline = Some(timeline);
246 }
247
248 pub fn video_quality(&self) -> VideoQuality {
249 self.quality
250 }
251
252 pub fn set_video_quality(&mut self, quality: VideoQuality) {
253 self.quality = quality;
254 }
255
183 pub fn set_motion(&mut self, motion: bool) {
256 pub fn set_motion(&mut self, motion: bool) {
184 self.motion = motion;
257 self.motion = motion;
185 self.share_fps.store(if motion { MOTION_SHARE_FPS } else { SCREEN_SHARE_FPS }, Ordering::Relaxed);
258 self.share_fps.store(
186 if let Some(share) = self.lines.as_ref().and_then(|lines| lines.share.as_ref()).filter(|_| self.sharing()) {
259 if motion {
260 MOTION_SHARE_FPS
261 } else {
262 SCREEN_SHARE_FPS
263 },
264 Ordering::Relaxed,
265 );
266 if let Some(share) = self
267 .lines
268 .as_ref()
269 .and_then(|lines| lines.share.as_ref())
270 .filter(|_| self.sharing())
271 {
187 let _ = self.tune_share(&share.sender());
272 let _ = self.tune_share(&share.sender());
188 }
273 }
189 }
274 }
@@ -203,7 +288,9 @@ impl LocalVideo {
203 for encoding in &mut parameters.encodings {
288 for encoding in &mut parameters.encodings {
204 encoding.max_framerate = Some(fps);
289 encoding.max_framerate = Some(fps);
205 }
290 }
206 sender.set_parameters(parameters).map_err(|error| Error::Webrtc(error.to_string()))
291 sender
292 .set_parameters(parameters)
293 .map_err(|error| Error::Webrtc(error.to_string()))
207 }
294 }
208
295
209 fn sender_of(&self, source: SendSource) -> Option<RtpSender> {
296 fn sender_of(&self, source: SendSource) -> Option<RtpSender> {
@@ -214,19 +301,33 @@ impl LocalVideo {
214 }
301 }
215 }
302 }
216
303
217 pub fn apply_send_limit(&mut self, source: SendSource, limits: &[SendLimit]) -> Result<Option<Vec<LayerPlan>>> {
304 pub fn apply_send_limit(
305 &mut self,
306 source: SendSource,
307 limits: &[SendLimit],
308 ) -> Result<Option<Vec<LayerPlan>>> {
218 let sending = match source {
309 let sending = match source {
219 SendSource::Camera => self.camera_on(),
310 SendSource::Camera => self.camera_on(),
220 SendSource::Screen => self.sharing(),
311 SendSource::Screen => self.sharing(),
221 };
312 };
222 let Some(sender) = self.sender_of(source).filter(|_| sending) else { return Ok(None) };
313 let Some(sender) = self.sender_of(source).filter(|_| sending) else {
314 return Ok(None);
315 };
223 let outgoing = match source {
316 let outgoing = match source {
224 SendSource::Camera => &mut self.camera,
317 SendSource::Camera => &mut self.camera,
225 SendSource::Screen => &mut self.screen,
318 SendSource::Screen => &mut self.screen,
226 };
319 };
227 let frame = unpack_size(outgoing.frame_size.load(Ordering::Relaxed));
320 let frame = unpack_size(outgoing.frame_size.load(Ordering::Relaxed));
228 outgoing.requested = Some(RequestedLimits { limits: limits.to_vec(), applied_for: frame });
321 outgoing.requested = Some(RequestedLimits {
229 let rids: Vec<String> = sender.parameters().encodings.into_iter().map(|encoding| encoding.rid).collect();
322 limits: limits.to_vec(),
323 applied_for: frame,
324 });
325 let rids: Vec<String> = sender
326 .parameters()
327 .encodings
328 .into_iter()
329 .map(|encoding| encoding.rid)
330 .collect();
230 if rids.len() > 1 {
331 if rids.len() > 1 {
231 let plans = plan_layers(limits, frame, &rids);
332 let plans = plan_layers(limits, frame, &rids);
232 if plans.iter().any(|plan| plan.keyframe) {
333 if plans.iter().any(|plan| plan.keyframe) {
@@ -235,13 +336,20 @@ impl LocalVideo {
235 Self::set_layers(&sender, &plans, 1.0)?;
336 Self::set_layers(&sender, &plans, 1.0)?;
236 return Ok(Some(plans));
337 return Ok(Some(plans));
237 }
338 }
238 let Some(limit) = limits.first() else { return Ok(None) };
339 let Some(limit) = limits.first() else {
340 return Ok(None);
341 };
239 let encoder = encoder_limits(limit, frame);
342 let encoder = encoder_limits(limit, frame);
240 if limit.keyframe {
343 if limit.keyframe {
241 Self::set_limits(&sender, &encoder, KEYFRAME_NUDGE)?;
344 Self::set_limits(&sender, &encoder, KEYFRAME_NUDGE)?;
242 }
345 }
243 Self::set_limits(&sender, &encoder, 1.0)?;
346 Self::set_limits(&sender, &encoder, 1.0)?;
244 Ok(Some(vec![LayerPlan { rid: rids.into_iter().next().unwrap_or_default(), active: true, limits: Some(encoder), keyframe: limit.keyframe }]))
347 Ok(Some(vec![LayerPlan {
348 rid: rids.into_iter().next().unwrap_or_default(),
349 active: true,
350 limits: Some(encoder),
351 keyframe: limit.keyframe,
352 }]))
245 }
353 }
246
354
247 /// The mixer sends its limits once, often before the first frame tells the size to scale from.
355 /// The mixer sends its limits once, often before the first frame tells the size to scale from.
@@ -253,7 +361,11 @@ impl LocalVideo {
253 SendSource::Screen => &self.screen,
361 SendSource::Screen => &self.screen,
254 };
362 };
255 let frame = unpack_size(outgoing.frame_size.load(Ordering::Relaxed));
363 let frame = unpack_size(outgoing.frame_size.load(Ordering::Relaxed));
256 let Some(requested) = outgoing.requested.as_ref().filter(|requested| frame.is_some() && requested.applied_for != frame) else {
364 let Some(requested) = outgoing
365 .requested
366 .as_ref()
367 .filter(|requested| frame.is_some() && requested.applied_for != frame)
368 else {
257 continue;
369 continue;
258 };
370 };
259 let limits = requested.limits.clone();
371 let limits = requested.limits.clone();
@@ -265,17 +377,22 @@ impl LocalVideo {
265 fn set_layers(sender: &RtpSender, plans: &[LayerPlan], nudge: f64) -> Result<()> {
377 fn set_layers(sender: &RtpSender, plans: &[LayerPlan], nudge: f64) -> Result<()> {
266 let mut parameters = sender.parameters();
378 let mut parameters = sender.parameters();
267 for encoding in &mut parameters.encodings {
379 for encoding in &mut parameters.encodings {
268 let Some(plan) = plans.iter().find(|plan| plan.rid == encoding.rid) else { continue };
380 let Some(plan) = plans.iter().find(|plan| plan.rid == encoding.rid) else {
381 continue;
382 };
269 let nudged = nudge != 1.0 && plan.keyframe;
383 let nudged = nudge != 1.0 && plan.keyframe;
270 encoding.active = plan.active;
384 encoding.active = plan.active;
271 let Some(limits) = &plan.limits else { continue };
385 let Some(limits) = &plan.limits else { continue };
272 encoding.scale_resolution_down_by = Some(limits.scale_down_by * if nudged { nudge } else { 1.0 });
386 encoding.scale_resolution_down_by =
387 Some(limits.scale_down_by * if nudged { nudge } else { 1.0 });
273 if let Some(framerate) = limits.max_framerate {
388 if let Some(framerate) = limits.max_framerate {
274 encoding.max_framerate = Some(framerate);
389 encoding.max_framerate = Some(framerate);
275 }
390 }
276 encoding.max_bitrate = limits.max_bitrate;
391 encoding.max_bitrate = limits.max_bitrate;
277 }
392 }
278 sender.set_parameters(parameters).map_err(|error| Error::Webrtc(error.to_string()))
393 sender
394 .set_parameters(parameters)
395 .map_err(|error| Error::Webrtc(error.to_string()))
279 }
396 }
280
397
281 fn set_limits(sender: &RtpSender, limits: &EncoderLimits, nudge: f64) -> Result<()> {
398 fn set_limits(sender: &RtpSender, limits: &EncoderLimits, nudge: f64) -> Result<()> {
@@ -287,7 +404,9 @@ impl LocalVideo {
287 }
404 }
288 encoding.max_bitrate = limits.max_bitrate;
405 encoding.max_bitrate = limits.max_bitrate;
289 }
406 }
290 sender.set_parameters(parameters).map_err(|error| Error::Webrtc(error.to_string()))
407 sender
408 .set_parameters(parameters)
409 .map_err(|error| Error::Webrtc(error.to_string()))
291 }
410 }
292
411
293 pub fn camera_size(&self) -> Option<(u32, u32)> {
412 pub fn camera_size(&self) -> Option<(u32, u32)> {
@@ -312,7 +431,9 @@ impl LocalVideo {
312 }
431 }
313
432
314 pub fn blur_model(&self) -> Option<&'static str> {
433 pub fn blur_model(&self) -> Option<&'static str> {
315 (self.camera_on() && self.blur.active()).then(|| self.blur.model()).filter(|model| !model.is_empty())
434 (self.camera_on() && self.blur.active())
435 .then(|| self.blur.model())
436 .filter(|model| !model.is_empty())
316 }
437 }
317
438
318 pub fn has_lines(&self) -> bool {
439 pub fn has_lines(&self) -> bool {
@@ -320,17 +441,31 @@ impl LocalVideo {
320 }
441 }
321
442
322 pub fn share_mid(&self) -> Option<String> {
443 pub fn share_mid(&self) -> Option<String> {
323 self.lines.as_ref().and_then(|lines| lines.share.as_ref()).and_then(|share| share.mid())
444 self.lines
445 .as_ref()
446 .and_then(|lines| lines.share.as_ref())
447 .and_then(|share| share.mid())
324 }
448 }
325
449
326 pub fn has_share_line(&self) -> bool {
450 pub fn has_share_line(&self) -> bool {
327 self.lines.as_ref().is_some_and(|lines| lines.share.is_some())
451 self.lines
452 .as_ref()
453 .is_some_and(|lines| lines.share.is_some())
328 }
454 }
329
455
330 pub fn add_share_line(&mut self, share: RtpTransceiver, camera: Option<RtpTransceiver>) -> Result<()> {
456 pub fn add_share_line(
457 &mut self,
458 share: RtpTransceiver,
459 camera: Option<RtpTransceiver>,
460 ) -> Result<()> {
331 match (self.lines.as_mut(), camera) {
461 match (self.lines.as_mut(), camera) {
332 (Some(lines), _) => lines.share = Some(share),
462 (Some(lines), _) => lines.share = Some(share),
333 (None, Some(camera)) => self.lines = Some(VideoLines { camera, share: Some(share) }),
463 (None, Some(camera)) => {
464 self.lines = Some(VideoLines {
465 camera,
466 share: Some(share),
467 })
468 }
334 (None, None) => return Err(Error::Webrtc("no video line negotiated".into())),
469 (None, None) => return Err(Error::Webrtc("no video line negotiated".into())),
335 }
470 }
336 Ok(())
471 Ok(())
@@ -341,7 +476,12 @@ impl LocalVideo {
341 .as_ref()
476 .as_ref()
342 .and_then(|lines| lines.share.as_ref())
477 .and_then(|lines| lines.share.as_ref())
343 .and_then(|share| share.current_direction())
478 .and_then(|share| share.current_direction())
344 .is_some_and(|direction| matches!(direction, RtpTransceiverDirection::SendOnly | RtpTransceiverDirection::SendRecv))
479 .is_some_and(|direction| {
480 matches!(
481 direction,
482 RtpTransceiverDirection::SendOnly | RtpTransceiverDirection::SendRecv
483 )
484 })
345 }
485 }
346
486
347 pub fn is_available(&self) -> bool {
487 pub fn is_available(&self) -> bool {
@@ -360,6 +500,10 @@ impl LocalVideo {
360 self.screen.capture.is_some()
500 self.screen.capture.is_some()
361 }
501 }
362
502
503 pub fn portal_is_open(&self) -> bool {
504 self.portal_armed
505 }
506
363 pub fn set_lines(&mut self, lines: VideoLines) -> Result<()> {
507 pub fn set_lines(&mut self, lines: VideoLines) -> Result<()> {
364 if self.camera_on() {
508 if self.camera_on() {
365 Self::begin_sending(&lines.camera.sender(), &self.camera.track)?;
509 Self::begin_sending(&lines.camera.sender(), &self.camera.track)?;
@@ -385,13 +529,28 @@ impl LocalVideo {
385 for encoding in &mut parameters.encodings {
529 for encoding in &mut parameters.encodings {
386 encoding.active = active;
530 encoding.active = active;
387 }
531 }
388 sender.set_parameters(parameters).map_err(|error| Error::Webrtc(error.to_string()))
532 sender
533 .set_parameters(parameters)
534 .map_err(|error| Error::Webrtc(error.to_string()))
389 }
535 }
390
536
391 fn camera_sink(&self) -> LocalSink {
537 fn camera_sink(&self) -> LocalSink {
392 LocalSink::new(self.camera.source.clone(), Some((self.hub.clone(), VideoKey::LocalCamera)))
538 LocalSink::new(
393 .mirrored_by(self.blur.clone())
539 self.camera.source.clone(),
394 .reporting_size(self.camera.frame_size.clone())
540 Some((self.hub.clone(), VideoKey::LocalCamera)),
541 )
542 .mirrored_by(self.blur.clone())
543 .reporting_size(self.camera.frame_size.clone())
544 }
545
546 /// Local share frames go to the encoder and to the window in the chat.
547 fn screen_sink(&self) -> LocalSink {
548 LocalSink::new(
549 self.screen.source.clone(),
550 Some((self.hub.clone(), VideoKey::LocalScreen)),
551 )
552 .with_standout(self.blur.clone())
553 .reporting_size(self.screen.frame_size.clone())
395 }
554 }
396
555
397 fn report_failure(&self, what: &'static str) -> impl FnOnce(String) + Send + 'static {
556 fn report_failure(&self, what: &'static str) -> impl FnOnce(String) + Send + 'static {
@@ -412,7 +571,10 @@ impl LocalVideo {
412 }
571 }
413
572
414 pub fn start_camera(&mut self, choice: &DeviceChoice) -> Result<()> {
573 pub fn start_camera(&mut self, choice: &DeviceChoice) -> Result<()> {
415 let lines = self.lines.as_ref().ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?;
574 let lines = self
575 .lines
576 .as_ref()
577 .ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?;
416 if !self.is_available() {
578 if !self.is_available() {
417 return Err(Error::Webrtc("video is switched off".into()));
579 return Err(Error::Webrtc("video is switched off".into()));
418 }
580 }
@@ -426,14 +588,56 @@ impl LocalVideo {
426 Ok(())
588 Ok(())
427 }
589 }
428
590
591 pub fn camera_capture_summary(&self) -> Option<String> {
592 self.camera_stats.summary()
593 }
594
429 fn capture_camera(&self, choice: &DeviceChoice) -> Result<Capture> {
595 fn capture_camera(&self, choice: &DeviceChoice) -> Result<Capture> {
430 let mut sink = self.camera_sink();
596 let mut sink = self.camera_sink();
431 Ok(match self.mode {
597 Ok(match self.mode {
432 VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Camera, Some(self.blur.clone()))),
598 VideoMode::Pattern => Capture::Task(spawn_pattern(
433 _ => start_camera(choice, self.blur.clone(), move |buffer| sink.push(buffer), self.report_failure("Camera"))?,
599 sink,
600 PatternKind::Camera,
601 Some(self.blur.clone()),
602 )),
603 _ => {
604 let timeline = self.timeline.clone();
605 start_camera(
606 choice,
607 self.quality,
608 self.blur.clone(),
609 self.camera_stats.clone(),
610 move |label| {
611 if let Some(timeline) = timeline {
612 timeline.record("camera capture", label);
613 } else {
614 eprintln!("calls: camera capture {label}");
615 }
616 },
617 move |buffer| sink.push(buffer),
618 self.report_failure("Camera"),
619 )?
620 }
434 })
621 })
435 }
622 }
436
623
624 /// Restart capture with the current quality if the camera is already running.
625 pub fn refresh_camera_capture(&mut self, choice: &DeviceChoice) -> Result<()> {
626 if self.camera.capture.is_none() {
627 return Ok(());
628 }
629 let preview = self.camera_preview;
630 self.camera.capture = None;
631 self.camera.capture = Some(self.capture_camera(choice)?);
632 self.camera_preview = preview;
633 if !preview {
634 if let Some(lines) = self.lines.as_ref() {
635 Self::begin_sending(&lines.camera.sender(), &self.camera.track)?;
636 }
637 }
638 Ok(())
639 }
640
437 pub fn stop_camera(&mut self) {
641 pub fn stop_camera(&mut self) {
438 self.camera_preview = false;
642 self.camera_preview = false;
439 self.camera.capture = None;
643 self.camera.capture = None;
@@ -444,28 +648,110 @@ impl LocalVideo {
444 self.hub.forget(&VideoKey::LocalCamera);
648 self.hub.forget(&VideoKey::LocalCamera);
445 }
649 }
446
650
447 pub fn start_share(&mut self, source: &ShareSource) -> Result<()> {
651 pub fn accept_portal(&mut self, generation: u64) -> bool {
448 let lines = self.lines.as_ref().ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?;
652 if self.portal_armed && self.portal_generation == generation {
449 let share = lines.share.as_ref().ok_or_else(|| Error::Webrtc("sharing needs a meeting".into()))?;
653 self.portal_armed = false;
654 self.portal_keep = true;
655 self.portal_bound = true;
656 true
657 } else {
658 false
659 }
660 }
661
662 pub fn open_portal(
663 &mut self,
664 kind: ShareKind,
665 commands: UnboundedSender<CallCommand>,
666 ) -> Result<()> {
450 if !self.is_available() {
667 if !self.is_available() {
451 return Err(Error::Webrtc("video is switched off".into()));
668 return Err(Error::Webrtc("video is switched off".into()));
452 }
669 }
670 if self.mode == VideoMode::Pattern {
671 let source = ShareSource {
672 id: if kind == ShareKind::Screen { 1 } else { 2 },
673 kind,
674 title: if kind == ShareKind::Screen {
675 "Test screen"
676 } else {
677 "Test window"
678 }
679 .into(),
680 };
681 let _ = commands.send(CallCommand::StartShare(source));
682 return Ok(());
683 }
684 self.portal_generation = self.portal_generation.wrapping_add(1);
685 let generation = self.portal_generation;
686 self.portal_armed = false;
687 self.portal_keep = false;
688 self.portal_bound = false;
453 self.screen.capture = None;
689 self.screen.capture = None;
454 let mut sink = LocalSink::new(self.screen.source.clone(), None)
690 let mut sink = self.screen_sink();
455 .with_standout(self.blur.clone())
691 let updates = self.updates.clone();
456 .reporting_size(self.screen.frame_size.clone());
692 let capture = start_portal_capture(
457 let capture = match self.mode {
693 kind,
458 VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Screen, None)),
694 self.share_fps.clone(),
459 _ => start_screen_capture(source.clone(), self.share_fps.clone(), move |buffer| sink.push(buffer), self.report_failure("Screen share"))?,
695 move |buffer| sink.push(buffer),
460 };
696 move |follow| match follow {
697 PortalFollowUp::Share(source) => {
698 let _ = commands.send(CallCommand::FinishPortalShare { source, generation });
699 }
700 PortalFollowUp::Quiet => {
701 let _ = commands.send(CallCommand::AbandonPortalShare);
702 }
703 PortalFollowUp::Notice(text) => {
704 let _ = updates.send(CallUpdate::Notice(text.to_owned()));
705 let _ = commands.send(CallCommand::AbandonPortalShare);
706 }
707 },
708 )?;
709 self.portal_armed = true;
710 self.screen.capture = Some(capture);
711 Ok(())
712 }
713
714 pub fn start_share(&mut self, source: &ShareSource) -> Result<()> {
715 let lines = self
716 .lines
717 .as_ref()
718 .ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?;
719 let share = lines
720 .share
721 .as_ref()
722 .ok_or_else(|| Error::Webrtc("sharing needs a meeting".into()))?;
723 if !self.is_available() {
724 return Err(Error::Webrtc("video is switched off".into()));
725 }
726 let keep = std::mem::take(&mut self.portal_keep) || self.portal_bound;
727 if !keep {
728 self.portal_armed = false;
729 self.portal_generation = self.portal_generation.wrapping_add(1);
730 self.screen.capture = None;
731 let mut sink = self.screen_sink();
732 let capture = match self.mode {
733 VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Screen, None)),
734 _ => start_screen_capture(
735 source.clone(),
736 self.share_fps.clone(),
737 move |buffer| sink.push(buffer),
738 self.report_failure("Screen share"),
739 )?,
740 };
741 self.screen.capture = Some(capture);
742 }
461 Self::begin_sending(&share.sender(), &self.screen.track)?;
743 Self::begin_sending(&share.sender(), &self.screen.track)?;
462 let _ = self.tune_share(&share.sender());
744 let _ = self.tune_share(&share.sender());
463 self.screen.capture = Some(capture);
464 Ok(())
745 Ok(())
465 }
746 }
466
747
467 pub fn stop_share(&mut self) {
748 pub fn stop_share(&mut self) {
749 self.portal_generation = self.portal_generation.wrapping_add(1);
750 self.portal_armed = false;
751 self.portal_keep = false;
752 self.portal_bound = false;
468 self.screen.capture = None;
753 self.screen.capture = None;
754 self.hub.forget(&VideoKey::LocalScreen);
469 if let Some(share) = self.lines.as_ref().and_then(|lines| lines.share.as_ref()) {
755 if let Some(share) = self.lines.as_ref().and_then(|lines| lines.share.as_ref()) {
470 let _ = Self::set_active(&share.sender(), false);
756 let _ = Self::set_active(&share.sender(), false);
471 }
757 }
@@ -485,10 +771,18 @@ mod tests {
485 async fn a_camera_preview_runs_without_a_line_and_stops_cleanly() {
771 async fn a_camera_preview_runs_without_a_line_and_stops_cleanly() {
486 let (sender, _receiver) = tokio::sync::mpsc::unbounded_channel();
772 let (sender, _receiver) = tokio::sync::mpsc::unbounded_channel();
487 let factory = crate::devices::shared_factory();
773 let factory = crate::devices::shared_factory();
488 let mut video = LocalVideo::new(&factory, VideoMode::Pattern, VideoHub::new(sender.clone()), sender);
774 let mut video = LocalVideo::new(
775 &factory,
776 VideoMode::Pattern,
777 VideoHub::new(sender.clone()),
778 sender,
779 );
489 video.preview_camera(&DeviceChoice::SystemDefault).unwrap();
780 video.preview_camera(&DeviceChoice::SystemDefault).unwrap();
490 assert!(video.camera_previewing() && !video.camera_on());
781 assert!(video.camera_previewing() && !video.camera_on());
491 assert!(video.start_camera(&DeviceChoice::SystemDefault).is_err(), "sending needs a negotiated line");
782 assert!(
783 video.start_camera(&DeviceChoice::SystemDefault).is_err(),
784 "sending needs a negotiated line"
785 );
492 assert!(video.camera_previewing());
786 assert!(video.camera_previewing());
493 video.stop_camera();
787 video.stop_camera();
494 assert!(!video.camera_previewing() && !video.camera_on());
788 assert!(!video.camera_previewing() && !video.camera_on());
crates/calling/tests/sdp_golden.rs +1 −0
@@ -9,6 +9,7 @@ fn captured_plan() -> OfferPlan {
9 9 OfferPlan {
10 10 screen_share_mids: vec!["18".into()],
11 11 gallery_mids: (10..=17).map(|mid| mid.to_string()).collect(),
12 fold_groups: Vec::new(),
12 13 }
13 14 }
14 15
@@ -9,6 +9,7 @@ fn captured_plan() -> OfferPlan {
9 OfferPlan {
9 OfferPlan {
10 screen_share_mids: vec!["18".into()],
10 screen_share_mids: vec!["18".into()],
11 gallery_mids: (10..=17).map(|mid| mid.to_string()).collect(),
11 gallery_mids: (10..=17).map(|mid| mid.to_string()).collect(),
12 fold_groups: Vec::new(),
12 }
13 }
13}
14}
14
15
openspec/changes/archive/2026-11-12-camera-capture-performance/.openspec.yaml added +2 −0
@@ -0,0 +1,2 @@
1 schema: spec-driven
2 created: 2026-11-12
@@ -0,0 +1,2 @@
1schema: spec-driven
2created: 2026-11-12
openspec/changes/archive/2026-11-12-camera-capture-performance/design.md added +35 −0
@@ -0,0 +1,35 @@
1 # Design
2
3 ## Context
4
5 `open_picked_format` startete mit `Closest(NV12 1080p)`. Auf dem C930e gibt es kein NV12; nokhwa landet bei YUYV 1080p@5. `compatible_camera_formats` scheitert oft (`Failed to Fufill`), daher bleibt der 5-fps-Stream. MJPEG 1080p@30 und 720p@30 existieren auf dem Gerät, wurden aber aus `pick_format` ausgeschlossen (`DIRECT_FORMATS = NV12|YUYV`).
6
7 ## Goals / Non-Goals
8
9 **Goals**
10
11 - Nie unter 30 fps öffnen, wenn das Gerät 30 fps in irgendeinem nutzbaren Format anbietet.
12 - MJPEG 1080p/720p als bevorzugter HD-Pfad auf USB-2.0-Kameras.
13 - Schneller Decode MJPEG → I420 mit wiederverwendeten Buffers.
14 - Messbarkeit im Call-Report.
15
16 **Non-Goals**
17
18 - NVENC/VAAPI-Encoder in diesem Durchgang.
19 - Receive-/Render-Pfad-Optimierung, bevor eigene Capture-fps stimmen.
20
21 ## Decisions
22
23 1. **Exact-Kandidaten mit fps-Gate:** Nach jedem Open `frame_rate() >= 30` prüfen; sonst nächster Kandidat (MJPG HD → Raw 30 fps → AbsoluteHighest).
24 2. **MJPEG in `pick_format`:** Bei gleicher Auflösung und 30 fps bleibt Raw (NV12 > YUYV) bevorzugt; sonst MJPEG.
25 3. **Decode:** `zune-jpeg` → RGBA → `abgr_to_i420`; nokhwa-`decode_image` nur für andere Formate.
26 4. **UVC:** `exposure_dynamic_framerate=0`, `power_line_frequency=50` best effort, Fehler nur loggen.
27
28 ## Risks / Trade-offs
29
30 - MJPEG-Decode kostet CPU; bei 1080p@30 muss < ~15 ms/Frame bleiben — sonst Capture weiter senken (720p) als Fallback.
31 - AbsoluteHighest kann wieder Property-Fails auslösen — nur letzter Ausweg.
32
33 ## Migration
34
35 Keine Datenmigration. Nach Release App neu starten; Call-Report prüfen auf `MJPG … @30` und ~30 encodierte Frames/s.
@@ -0,0 +1,35 @@
1# Design
2
3## Context
4
5`open_picked_format` startete mit `Closest(NV12 1080p)`. Auf dem C930e gibt es kein NV12; nokhwa landet bei YUYV 1080p@5. `compatible_camera_formats` scheitert oft (`Failed to Fufill`), daher bleibt der 5-fps-Stream. MJPEG 1080p@30 und 720p@30 existieren auf dem Gerät, wurden aber aus `pick_format` ausgeschlossen (`DIRECT_FORMATS = NV12|YUYV`).
6
7## Goals / Non-Goals
8
9**Goals**
10
11- Nie unter 30 fps öffnen, wenn das Gerät 30 fps in irgendeinem nutzbaren Format anbietet.
12- MJPEG 1080p/720p als bevorzugter HD-Pfad auf USB-2.0-Kameras.
13- Schneller Decode MJPEG → I420 mit wiederverwendeten Buffers.
14- Messbarkeit im Call-Report.
15
16**Non-Goals**
17
18- NVENC/VAAPI-Encoder in diesem Durchgang.
19- Receive-/Render-Pfad-Optimierung, bevor eigene Capture-fps stimmen.
20
21## Decisions
22
231. **Exact-Kandidaten mit fps-Gate:** Nach jedem Open `frame_rate() >= 30` prüfen; sonst nächster Kandidat (MJPG HD → Raw 30 fps → AbsoluteHighest).
242. **MJPEG in `pick_format`:** Bei gleicher Auflösung und 30 fps bleibt Raw (NV12 > YUYV) bevorzugt; sonst MJPEG.
253. **Decode:** `zune-jpeg` → RGBA → `abgr_to_i420`; nokhwa-`decode_image` nur für andere Formate.
264. **UVC:** `exposure_dynamic_framerate=0`, `power_line_frequency=50` best effort, Fehler nur loggen.
27
28## Risks / Trade-offs
29
30- MJPEG-Decode kostet CPU; bei 1080p@30 muss < ~15 ms/Frame bleiben — sonst Capture weiter senken (720p) als Fallback.
31- AbsoluteHighest kann wieder Property-Fails auslösen — nur letzter Ausweg.
32
33## Migration
34
35Keine Datenmigration. Nach Release App neu starten; Call-Report prüfen auf `MJPG … @30` und ~30 encodierte Frames/s.
openspec/changes/archive/2026-11-12-camera-capture-performance/proposal.md added +28 −0
@@ -0,0 +1,28 @@
1 # Proposal
2
3 ## Why
4
5 Nach dem 1:1-Kamera-Fix öffnet die App auf dem Logitech C930e (USB 2.0) oft YUYV 1920×1080 bei 5 fps statt MJPEG bei 30 fps. Das wirkt wie starker Verzug und Framedrops, obwohl der Encoder nicht CPU-limited ist.
6
7 ## What Changes
8
9 - Kamera-Open wählt Formate mit mindestens 30 fps; bei HD auf USB 2.0 bevorzugt MJPEG 1080p/720p.
10 - MJPEG-Frames werden lokal (zune-jpeg → I420) dekodiert, ohne den langsamen Roh-Closest-Pfad.
11 - UVC-Controls: feste Bildrate und 50-Hz-Netzfrequenz (Schweiz) best effort.
12 - Call-Report/Timeline zeigt gewähltes Format, Capture-fps und Decode-Zeit.
13
14 ## Capabilities
15
16 ### New Capabilities
17
18 - (keine)
19
20 ### Modified Capabilities
21
22 - `camera-capture`: 30-fps-Formatwahl inkl. MJPEG, Decode-Pfad, UVC-Tuning und Telemetrie.
23
24 ## Impact
25
26 - `crates/calling/src/camera.rs` (Open, Decode, Controls)
27 - ggf. Call-Timeline/Stats für Format und Capture-fps
28 - C930e und ähnliche UVC-Kameras ohne NV12 bei HD
@@ -0,0 +1,28 @@
1# Proposal
2
3## Why
4
5Nach dem 1:1-Kamera-Fix öffnet die App auf dem Logitech C930e (USB 2.0) oft YUYV 1920×1080 bei 5 fps statt MJPEG bei 30 fps. Das wirkt wie starker Verzug und Framedrops, obwohl der Encoder nicht CPU-limited ist.
6
7## What Changes
8
9- Kamera-Open wählt Formate mit mindestens 30 fps; bei HD auf USB 2.0 bevorzugt MJPEG 1080p/720p.
10- MJPEG-Frames werden lokal (zune-jpeg → I420) dekodiert, ohne den langsamen Roh-Closest-Pfad.
11- UVC-Controls: feste Bildrate und 50-Hz-Netzfrequenz (Schweiz) best effort.
12- Call-Report/Timeline zeigt gewähltes Format, Capture-fps und Decode-Zeit.
13
14## Capabilities
15
16### New Capabilities
17
18- (keine)
19
20### Modified Capabilities
21
22- `camera-capture`: 30-fps-Formatwahl inkl. MJPEG, Decode-Pfad, UVC-Tuning und Telemetrie.
23
24## Impact
25
26- `crates/calling/src/camera.rs` (Open, Decode, Controls)
27- ggf. Call-Timeline/Stats für Format und Capture-fps
28- C930e und ähnliche UVC-Kameras ohne NV12 bei HD
openspec/changes/archive/2026-11-12-camera-capture-performance/specs/camera-capture/spec.md added +48 −0
@@ -0,0 +1,48 @@
1 # Spec Delta
2
3 ## Purpose
4
5 Lokaler Kamera-Capture in Gesprächen und Prejoin mit stabiler HD-Bildrate (Ziel 30 fps), inkl. MJPEG-Geräte ohne NV12.
6
7 ## ADDED Requirements
8
9 ### Requirement: Capture wählt mindestens 30 fps wenn verfügbar
10 Wenn das Gerät mindestens ein Format mit 30 fps anbietet, MUST die App einen Stream mit mindestens 30 fps öffnen. Ein Open unter 30 fps (z. B. YUYV 1080p@5) MUST verworfen und durch den nächsten Kandidaten ersetzt werden, solange ein 30-fps-Kandidat übrig ist.
11
12 #### Scenario: C930e Auto wählt MJPEG 1080p@30
13 - **WHEN** die Kamera YUYV nur bis 1080p@5 / 720p@10 und MJPEG bis 1080p@30 anbietet und die Qualität Auto oder 1080p ist
14 - **THEN** öffnet die App MJPEG 1920×1080 bei 30 fps (oder ein anderes 30-fps-HD-Format), nicht YUYV@5
15
16 #### Scenario: 720p-Qualität
17 - **WHEN** die Qualität 720p ist und MJPEG 1280×720@30 verfügbar ist
18 - **THEN** öffnet die App dieses Format (oder Raw 30 fps gleicher Höhe), nicht ein Format unter 30 fps
19
20 ### Requirement: MJPEG wird dekodiert und gesendet
21 MJPEG-Frames MUST lokal nach I420 dekodiert und in die bestehende Sendepipeline (Effects → Encoder) gegeben werden, ohne den Nutzer mit einem Undecodable-Hinweis abzubrechen, solange der Decode gelingt.
22
23 #### Scenario: MJPEG-Frame wird I420
24 - **WHEN** der Capture-Stream MJPEG liefert
25 - **THEN** entsteht ein I420-Frame für Preview und Send, und die Timeline zählt Capture-Frames
26
27 ### Requirement: UVC-Bildrate und Netzfrequenz (best effort)
28 Nach erfolgreichem Open SHOULD die App `exposure_dynamic_framerate` deaktivieren und `power_line_frequency` auf 50 Hz setzen, wenn die Controls existieren. Fehlende Controls MUST den Stream nicht abbrechen.
29
30 #### Scenario: Controls fehlen
31 - **WHEN** die Kamera eines der Controls nicht anbietet
32 - **THEN** läuft der Stream weiter ohne Fehlerdialog
33
34 ### Requirement: Capture-Telemetrie im Call-Report
35 Beim Kamera-Start MUST die Timeline das gewählte Format (Pixel-Format, Auflösung, fps) nennen. Laufende Stats SHOULD Capture-fps und Decode-Zeit sichtbar machen, damit ein Call-Report zeigt, ob 30 fps ankommen.
36
37 #### Scenario: Format in der Timeline
38 - **WHEN** die Kamera erfolgreich startet
39 - **THEN** enthält die Timeline einen Eintrag mit Format wie `MJPG 1920x1080 @30`
40
41 ## MODIFIED Requirements
42
43 ### Requirement: Format-Property-Fehler blockiert den Open nicht
44 Schlägt die Abfrage der unterstützten Kamera-Formate oder der laufenden Format-Property fehl, MUST die App den Stream trotzdem mit einem 30-fps-fähigen Kandidaten (MJPEG oder Rohformat) öffnen, sofern das Gerät das erlaubt. Nur wenn kein 30-fps-Open gelingt, MAY die App einen langsameren Fallback nutzen; schlägt alles fehl, MUST die App dem Nutzer den Fehler anzeigen.
45
46 #### Scenario: Property fehlgeschlagen, 30-fps-Format verfügbar
47 - **WHEN** der Nutzer die Kamera einschaltet und die Format-Property fehlschlägt, das Gerät aber MJPEG oder Raw bei 30 fps anbietet
48 - **THEN** startet die lokale Kamera mit einem 30-fps-Format und zeigt keinen fatalen Format-Property-Stop
@@ -0,0 +1,48 @@
1# Spec Delta
2
3## Purpose
4
5Lokaler Kamera-Capture in Gesprächen und Prejoin mit stabiler HD-Bildrate (Ziel 30 fps), inkl. MJPEG-Geräte ohne NV12.
6
7## ADDED Requirements
8
9### Requirement: Capture wählt mindestens 30 fps wenn verfügbar
10Wenn das Gerät mindestens ein Format mit 30 fps anbietet, MUST die App einen Stream mit mindestens 30 fps öffnen. Ein Open unter 30 fps (z. B. YUYV 1080p@5) MUST verworfen und durch den nächsten Kandidaten ersetzt werden, solange ein 30-fps-Kandidat übrig ist.
11
12#### Scenario: C930e Auto wählt MJPEG 1080p@30
13- **WHEN** die Kamera YUYV nur bis 1080p@5 / 720p@10 und MJPEG bis 1080p@30 anbietet und die Qualität Auto oder 1080p ist
14- **THEN** öffnet die App MJPEG 1920×1080 bei 30 fps (oder ein anderes 30-fps-HD-Format), nicht YUYV@5
15
16#### Scenario: 720p-Qualität
17- **WHEN** die Qualität 720p ist und MJPEG 1280×720@30 verfügbar ist
18- **THEN** öffnet die App dieses Format (oder Raw 30 fps gleicher Höhe), nicht ein Format unter 30 fps
19
20### Requirement: MJPEG wird dekodiert und gesendet
21MJPEG-Frames MUST lokal nach I420 dekodiert und in die bestehende Sendepipeline (Effects → Encoder) gegeben werden, ohne den Nutzer mit einem Undecodable-Hinweis abzubrechen, solange der Decode gelingt.
22
23#### Scenario: MJPEG-Frame wird I420
24- **WHEN** der Capture-Stream MJPEG liefert
25- **THEN** entsteht ein I420-Frame für Preview und Send, und die Timeline zählt Capture-Frames
26
27### Requirement: UVC-Bildrate und Netzfrequenz (best effort)
28Nach erfolgreichem Open SHOULD die App `exposure_dynamic_framerate` deaktivieren und `power_line_frequency` auf 50 Hz setzen, wenn die Controls existieren. Fehlende Controls MUST den Stream nicht abbrechen.
29
30#### Scenario: Controls fehlen
31- **WHEN** die Kamera eines der Controls nicht anbietet
32- **THEN** läuft der Stream weiter ohne Fehlerdialog
33
34### Requirement: Capture-Telemetrie im Call-Report
35Beim Kamera-Start MUST die Timeline das gewählte Format (Pixel-Format, Auflösung, fps) nennen. Laufende Stats SHOULD Capture-fps und Decode-Zeit sichtbar machen, damit ein Call-Report zeigt, ob 30 fps ankommen.
36
37#### Scenario: Format in der Timeline
38- **WHEN** die Kamera erfolgreich startet
39- **THEN** enthält die Timeline einen Eintrag mit Format wie `MJPG 1920x1080 @30`
40
41## MODIFIED Requirements
42
43### Requirement: Format-Property-Fehler blockiert den Open nicht
44Schlägt die Abfrage der unterstützten Kamera-Formate oder der laufenden Format-Property fehl, MUST die App den Stream trotzdem mit einem 30-fps-fähigen Kandidaten (MJPEG oder Rohformat) öffnen, sofern das Gerät das erlaubt. Nur wenn kein 30-fps-Open gelingt, MAY die App einen langsameren Fallback nutzen; schlägt alles fehl, MUST die App dem Nutzer den Fehler anzeigen.
45
46#### Scenario: Property fehlgeschlagen, 30-fps-Format verfügbar
47- **WHEN** der Nutzer die Kamera einschaltet und die Format-Property fehlschlägt, das Gerät aber MJPEG oder Raw bei 30 fps anbietet
48- **THEN** startet die lokale Kamera mit einem 30-fps-Format und zeigt keinen fatalen Format-Property-Stop
openspec/changes/archive/2026-11-12-camera-capture-performance/tasks.md added +19 −0
@@ -0,0 +1,19 @@
1 ## 1. Formatwahl 30 fps
2
3 - [x] 1.1 `pick_format` lässt MJPEG zu; Raw (NV12>YUYV) nur bei gleicher Höhe/30 fps bevorzugen; C930e-Fixture-Test
4 - [x] 1.2 Open: Exact-Kandidaten (MJPG HD → Raw 30 fps), nach Open `frame_rate() >= 30` prüfen; AbsoluteHighest nur Last Resort
5
6 ## 2. MJPEG-Decode
7
8 - [x] 2.1 `zune-jpeg` → RGBA → `abgr_to_i420` mit Buffer-Reuse in `start_camera` / `direct_i420`
9 - [x] 2.2 Budget-Test (ignored, release): 1080p Decode+Convert < 20 ms
10
11 ## 3. UVC + Telemetrie
12
13 - [x] 3.1 Nach Open: `exposure_dynamic_framerate=0`, `power_line_frequency=50` best effort
14 - [x] 3.2 Timeline: gewähltes Format; Stats: Capture-fps / Decode-ms wo angebunden
15
16 ## 4. Verify
17
18 - [x] 4.1 `cargo test -p calling --lib camera` + ignored Hardware-Open
19 - [x] 4.2 Release `0.3.0-joe.4` bauen und nach `/usr/local/bin/rusty-teams` installieren
@@ -0,0 +1,19 @@
1## 1. Formatwahl 30 fps
2
3- [x] 1.1 `pick_format` lässt MJPEG zu; Raw (NV12>YUYV) nur bei gleicher Höhe/30 fps bevorzugen; C930e-Fixture-Test
4- [x] 1.2 Open: Exact-Kandidaten (MJPG HD → Raw 30 fps), nach Open `frame_rate() >= 30` prüfen; AbsoluteHighest nur Last Resort
5
6## 2. MJPEG-Decode
7
8- [x] 2.1 `zune-jpeg` → RGBA → `abgr_to_i420` mit Buffer-Reuse in `start_camera` / `direct_i420`
9- [x] 2.2 Budget-Test (ignored, release): 1080p Decode+Convert < 20 ms
10
11## 3. UVC + Telemetrie
12
13- [x] 3.1 Nach Open: `exposure_dynamic_framerate=0`, `power_line_frequency=50` best effort
14- [x] 3.2 Timeline: gewähltes Format; Stats: Capture-fps / Decode-ms wo angebunden
15
16## 4. Verify
17
18- [x] 4.1 `cargo test -p calling --lib camera` + ignored Hardware-Open
19- [x] 4.2 Release `0.3.0-joe.4` bauen und nach `/usr/local/bin/rusty-teams` installieren
openspec/changes/archive/2026-11-12-camera-video-quality/.openspec.yaml added +2 −0
@@ -0,0 +1,2 @@
1 schema: spec-driven
2 created: 2026-11-12
@@ -0,0 +1,2 @@
1schema: spec-driven
2created: 2026-11-12
openspec/changes/archive/2026-11-12-camera-video-quality/design.md added +64 −0
@@ -0,0 +1,64 @@
1 # Design
2
3 ## Context
4
5 Siehe `proposal.md` — Why. Heute: `CAPTURE_HEIGHT = 720`, Preferenz exakt 720, Downscale-Decke 1080 aber `fit_widescreen` kürzt wieder auf 720; Stage-Receive `max-fs=3600` (~720p); Screen schon `8160` (~1080p). Codec-Filter bleibt H.264 (`h264_only`).
6
7 ## Goals / Non-Goals
8
9 **Goals:**
10
11 - Eine Qualitaetsstufe steuert Capture-Decke, Send-Advertise und Stage-Receive gemeinsam.
12 - 1080p als praktisches Maximum; Auto faellt sauber auf 720p zurueck.
13 - Bestehende Small-Tile- und Screen-Share-Limits unangetastet.
14
15 **Non-Goals:**
16
17 - 4K-UI oder 4K-Advertise.
18 - H.265 / AV1.
19 - Mixer-Bitrate erzwingen jenseits der Teams-`controlVideoStreaming`-Antworten.
20 - Aenderung am Screen-Share-Capture-Pfad.
21
22 ## Decisions
23
24 ### 1. Eine Einstellung fuer Capture + Advertise + Stage
25
26 **Wahl:** `VideoQuality { Auto, P720, P1080 }` wirkt auf alle drei.
27
28 **Warum:** Getrennte «Senden»/«Empfangen»-Regler verdoppeln UI und erklaeren selten den wahrgenommenen Weichzeichner. Stage und Eigenbild sollen dieselbe Erwartung teilen.
29
30 **Alternative:** Nur Capture aendern — abgelehnt, weil Stage weiter 720p anfordert.
31
32 ### 2. Konstanten an Macroblock-Budgets koppeln
33
34 **Wahl:** 720p-Stage bleibt `max-fs=3600` / heutige `max-mbps`/`max-fps`; 1080p-Stage uebernimmt die heutigen Screen-`ReceiveLimits` (`8160` / `135_000` / `1500` fps-Einheiten) oder eine bewusst dokumentierte 1080p-Kamera-Variante mit gleichem `max-fs`, falls Screen-FPS zu niedrig fuer Kamera wirkt — dann `max-fps` bei 1080p-Stage auf Kameraniveau (~3000) halten und `max-mbps` proportional anheben.
35
36 **Empfehlung im Apply:** `max-fs=8160`, `max-fps=3000`, `max-mbps` so skalieren, dass 1080p@30 in Macroblock·FPS passt (≈ `8160 * 30` = 244800), nicht blind Screen-1500-FPS kopieren.
37
38 ### 3. Capture-API parametrisieren
39
40 **Wahl:** Preferenz-Hoehe und Downscale-Decke aus der aktiven Qualitaet ableiten statt hartem `CAPTURE_HEIGHT`. `pick_format` / `fit_widescreen` / Fallback-`Resolution` lesen dieselbe Decke. `LARGEST_DOWNSCALED_HEIGHT` fuer 1080-Ceiling darf hoehere Sensorformate bis z. B. 1440 zulassen, solange das Ergebnis auf ≤1080 skaliert — kein 4K-Modus in der UI.
41
42 ### 4. Persistenz und UI-Ort
43
44 **Wahl:** Persistenz neben bestehenden Geraete-/Call-Settings; Auswahl im Kamera-Menue (Call + Prejoin), Labels «Auto», «720p», «1080p». Default `Auto`. Wechsel im Call: Kamera-Track neu oeffnen wenn noetig; Stage-Subscriptions die Limits neu posten (`applyChannelParameters`).
45
46 ### 5. Codec unveraendert
47
48 H.264-only bleibt. Qualitaet ≠ Codec-Wechsel.
49
50 ## Risks / Trade-offs
51
52 - [Blur/Effects bei 1080p teurer] → Mitigation: Auto trotzdem 1080; bei messbaren Drops spaeter optional «Performance» — nicht in diesem Change.
53 - [Mixer ignoriert hoehere Advertise] → Mitigation: lokales Self-View und Capture trotzdem schaerfer; Stage-Request erhoehen unabhaengig.
54 - [Kamera ohne 30fps-1080] → Mitigation: Fallback 720; Start nicht hart failen.
55 - [Screen-Limits fuer Stage falsch uebernehmen (niedriges max-fps)] → Mitigation: Decision 2 mit kameratauglichem `max-fps`/`max-mbps`.
56
57 ## Migration Plan
58
59 - Default Auto → Nutzer ohne Setting bekommen 1080 wo moeglich (Verhalten aendert sich spuerbar).
60 - Rollback: Setting auf 720p oder Code-Revert der Capture-Konstanten.
61
62 ## Open Questions
63
64 - Ob Prejoin-Preview dieselbe Qualitaetsstufe sofort nutzt oder erst nach Join (bevorzugt: sofort, konsistent mit Call).
@@ -0,0 +1,64 @@
1# Design
2
3## Context
4
5Siehe `proposal.md` — Why. Heute: `CAPTURE_HEIGHT = 720`, Preferenz exakt 720, Downscale-Decke 1080 aber `fit_widescreen` kürzt wieder auf 720; Stage-Receive `max-fs=3600` (~720p); Screen schon `8160` (~1080p). Codec-Filter bleibt H.264 (`h264_only`).
6
7## Goals / Non-Goals
8
9**Goals:**
10
11- Eine Qualitaetsstufe steuert Capture-Decke, Send-Advertise und Stage-Receive gemeinsam.
12- 1080p als praktisches Maximum; Auto faellt sauber auf 720p zurueck.
13- Bestehende Small-Tile- und Screen-Share-Limits unangetastet.
14
15**Non-Goals:**
16
17- 4K-UI oder 4K-Advertise.
18- H.265 / AV1.
19- Mixer-Bitrate erzwingen jenseits der Teams-`controlVideoStreaming`-Antworten.
20- Aenderung am Screen-Share-Capture-Pfad.
21
22## Decisions
23
24### 1. Eine Einstellung fuer Capture + Advertise + Stage
25
26**Wahl:** `VideoQuality { Auto, P720, P1080 }` wirkt auf alle drei.
27
28**Warum:** Getrennte «Senden»/«Empfangen»-Regler verdoppeln UI und erklaeren selten den wahrgenommenen Weichzeichner. Stage und Eigenbild sollen dieselbe Erwartung teilen.
29
30**Alternative:** Nur Capture aendern — abgelehnt, weil Stage weiter 720p anfordert.
31
32### 2. Konstanten an Macroblock-Budgets koppeln
33
34**Wahl:** 720p-Stage bleibt `max-fs=3600` / heutige `max-mbps`/`max-fps`; 1080p-Stage uebernimmt die heutigen Screen-`ReceiveLimits` (`8160` / `135_000` / `1500` fps-Einheiten) oder eine bewusst dokumentierte 1080p-Kamera-Variante mit gleichem `max-fs`, falls Screen-FPS zu niedrig fuer Kamera wirkt — dann `max-fps` bei 1080p-Stage auf Kameraniveau (~3000) halten und `max-mbps` proportional anheben.
35
36**Empfehlung im Apply:** `max-fs=8160`, `max-fps=3000`, `max-mbps` so skalieren, dass 1080p@30 in Macroblock·FPS passt (≈ `8160 * 30` = 244800), nicht blind Screen-1500-FPS kopieren.
37
38### 3. Capture-API parametrisieren
39
40**Wahl:** Preferenz-Hoehe und Downscale-Decke aus der aktiven Qualitaet ableiten statt hartem `CAPTURE_HEIGHT`. `pick_format` / `fit_widescreen` / Fallback-`Resolution` lesen dieselbe Decke. `LARGEST_DOWNSCALED_HEIGHT` fuer 1080-Ceiling darf hoehere Sensorformate bis z. B. 1440 zulassen, solange das Ergebnis auf ≤1080 skaliert — kein 4K-Modus in der UI.
41
42### 4. Persistenz und UI-Ort
43
44**Wahl:** Persistenz neben bestehenden Geraete-/Call-Settings; Auswahl im Kamera-Menue (Call + Prejoin), Labels «Auto», «720p», «1080p». Default `Auto`. Wechsel im Call: Kamera-Track neu oeffnen wenn noetig; Stage-Subscriptions die Limits neu posten (`applyChannelParameters`).
45
46### 5. Codec unveraendert
47
48H.264-only bleibt. Qualitaet ≠ Codec-Wechsel.
49
50## Risks / Trade-offs
51
52- [Blur/Effects bei 1080p teurer] → Mitigation: Auto trotzdem 1080; bei messbaren Drops spaeter optional «Performance» — nicht in diesem Change.
53- [Mixer ignoriert hoehere Advertise] → Mitigation: lokales Self-View und Capture trotzdem schaerfer; Stage-Request erhoehen unabhaengig.
54- [Kamera ohne 30fps-1080] → Mitigation: Fallback 720; Start nicht hart failen.
55- [Screen-Limits fuer Stage falsch uebernehmen (niedriges max-fps)] → Mitigation: Decision 2 mit kameratauglichem `max-fps`/`max-mbps`.
56
57## Migration Plan
58
59- Default Auto → Nutzer ohne Setting bekommen 1080 wo moeglich (Verhalten aendert sich spuerbar).
60- Rollback: Setting auf 720p oder Code-Revert der Capture-Konstanten.
61
62## Open Questions
63
64- Ob Prejoin-Preview dieselbe Qualitaetsstufe sofort nutzt oder erst nach Join (bevorzugt: sofort, konsistent mit Call).
openspec/changes/archive/2026-11-12-camera-video-quality/proposal.md added +32 −0
@@ -0,0 +1,32 @@
1 # Proposal
2
3 ## Why
4
5 Die Kamera wirkt weich, weil Capture und Stage-Empfang auf ~720p festgenagelt sind, obwohl viele Kameras und der Teams-Mixer 1080p koennen. Nutzer sollen die Sende-/Empfangsqualitaet bewusst steuern koennen, ohne 4K-Komplexitaet.
6
7 ## What Changes
8
9 - Kamera-Capture bevorzugt **1080p @ 30 fps** (Widescreen), mit Fallback auf 720p wenn die Kamera das nicht liefert.
10 - Stage-Empfangs-Limits steigen auf **1080p-Niveau** (analog heutiger Screen-Share-`max-fs`/`max-mbps`-Groessenordnung).
11 - Neue persistente Einstellung **Videoqualitaet**: `Auto` | `720p` | `1080p` (kein 4K).
12 - Steuert Capture-Decke, `maxVideoSendCapabilities` und Stage-Request-Limits zusammen.
13 - `Auto` = hoechste unterstuetzte Stufe bis 1080p.
14 - Small-Tile-Limits und Screen-Share-Limits bleiben unveraendert.
15 - Codec bleibt H.264; kein H.265.
16
17 ## Capabilities
18
19 ### New Capabilities
20
21 - `camera-video-quality`: Capture-Preferenz, Sende-Faehigkeiten und Stage-Empfangs-Limits fuer Kameravideo, inkl. Nutzerwahl Auto/720/1080.
22
23 ### Modified Capabilities
24
25 - (keine)
26
27 ## Impact
28
29 - Capture/Formatwahl und Downscale in `crates/calling` (Kamera-Pfad).
30 - Stage-`applyChannelParameters` / Receive-Limits und Send-Capabilities in `crates/calling`.
31 - UI: Kamera-Menue bzw. Call-/Geraete-Einstellungen in `crates/app`; Persistenz analog bestehender Call-Settings.
32 - Tests: Formatwahl, Limit-Konstanten, Setting-Persistenz; Verify mit `cargo test -p calling --lib` und gezielten App-Tests.
@@ -0,0 +1,32 @@
1# Proposal
2
3## Why
4
5Die Kamera wirkt weich, weil Capture und Stage-Empfang auf ~720p festgenagelt sind, obwohl viele Kameras und der Teams-Mixer 1080p koennen. Nutzer sollen die Sende-/Empfangsqualitaet bewusst steuern koennen, ohne 4K-Komplexitaet.
6
7## What Changes
8
9- Kamera-Capture bevorzugt **1080p @ 30 fps** (Widescreen), mit Fallback auf 720p wenn die Kamera das nicht liefert.
10- Stage-Empfangs-Limits steigen auf **1080p-Niveau** (analog heutiger Screen-Share-`max-fs`/`max-mbps`-Groessenordnung).
11- Neue persistente Einstellung **Videoqualitaet**: `Auto` | `720p` | `1080p` (kein 4K).
12 - Steuert Capture-Decke, `maxVideoSendCapabilities` und Stage-Request-Limits zusammen.
13 - `Auto` = hoechste unterstuetzte Stufe bis 1080p.
14- Small-Tile-Limits und Screen-Share-Limits bleiben unveraendert.
15- Codec bleibt H.264; kein H.265.
16
17## Capabilities
18
19### New Capabilities
20
21- `camera-video-quality`: Capture-Preferenz, Sende-Faehigkeiten und Stage-Empfangs-Limits fuer Kameravideo, inkl. Nutzerwahl Auto/720/1080.
22
23### Modified Capabilities
24
25- (keine)
26
27## Impact
28
29- Capture/Formatwahl und Downscale in `crates/calling` (Kamera-Pfad).
30- Stage-`applyChannelParameters` / Receive-Limits und Send-Capabilities in `crates/calling`.
31- UI: Kamera-Menue bzw. Call-/Geraete-Einstellungen in `crates/app`; Persistenz analog bestehender Call-Settings.
32- Tests: Formatwahl, Limit-Konstanten, Setting-Persistenz; Verify mit `cargo test -p calling --lib` und gezielten App-Tests.
openspec/changes/archive/2026-11-12-camera-video-quality/specs/camera-video-quality/spec.md added +63 −0
@@ -0,0 +1,63 @@
1 # Spec Delta
2
3 ## Purpose
4
5 Steuert, in welcher Aufloesung die eigene Kamera erfasst und dem Call angeboten wird, und welche Qualitaet fuer Stage-Kamera-Empfang angefordert wird — waehlbar als Auto, 720p oder 1080p.
6
7 ## ADDED Requirements
8
9 ### Requirement: Camera capture prefers the selected quality ceiling
10
11 The client SHALL capture the local camera at the highest supported widescreen format at least 30 fps that does not exceed the active quality ceiling (720p or 1080p). Auto SHALL use a 1080p ceiling when the camera can deliver it, otherwise 720p. The client SHALL NOT offer or use a 4K camera quality mode.
12
13 #### Scenario: Camera supports 1080p with Auto
14
15 - **WHEN** video quality is Auto and the selected camera exposes a suitable 1920×1080 (or equivalent 16:9) format at ≥30 fps
16 - **THEN** capture uses that 1080p-class format (not forced down to 720p before encoding)
17
18 #### Scenario: Camera only supports 720p
19
20 - **WHEN** video quality is Auto or 1080p and the camera cannot provide a suitable 1080p format
21 - **THEN** capture falls back to a suitable 720p format without failing camera start solely for that reason
22
23 #### Scenario: User locks 720p
24
25 - **WHEN** video quality is set to 720p and a higher camera format is available
26 - **THEN** capture stays at or below 720p
27
28 ### Requirement: Send capabilities match capture ceiling
29
30 After the local camera size for sending is known, the client SHALL advertise max video send capabilities whose width and height reflect that capture size (up to the active quality ceiling), so the meeting media path can request layers up to that size.
31
32 #### Scenario: 1080p capture is advertised
33
34 - **WHEN** the outbound camera frame size is 1920×1080
35 - **THEN** the send-capabilities update reports max width and height of at least 1920 on the largest side consistent with that frame
36
37 ### Requirement: Stage receive requests use 1080p-class limits when allowed
38
39 For non-screen camera tiles shown as stage detail, the client SHALL request receive limits at 1080p-class macroblock and throughput budgets when the active quality ceiling is Auto or 1080p. When the ceiling is 720p, stage requests SHALL remain at 720p-class budgets. Small gallery tiles and screen-share receive limits SHALL keep their existing budgets.
40
41 #### Scenario: Stage at Auto or 1080p
42
43 - **WHEN** the user is subscribed to a participant camera on the stage and video quality is Auto or 1080p
44 - **THEN** the stage receive request uses 1080p-class `max-fs` / `max-mbps` budgets (same order of magnitude as today’s screen-share camera request, not the previous 720p stage budget)
45
46 #### Scenario: Stage locked to 720p
47
48 - **WHEN** video quality is 720p and the user is subscribed to a stage camera tile
49 - **THEN** the stage receive request uses 720p-class budgets
50
51 ### Requirement: Video quality setting is user-visible and persistent
52
53 The product SHALL expose a video quality choice of Auto, 720p, and 1080p in the call/device camera controls, persist the choice across app restarts, and apply it to new captures and new stage subscriptions. Changing the setting while a call is active SHALL take effect for subsequent capture restarts and subsequent stage request updates without requiring an app relaunch.
54
55 #### Scenario: Persist across restart
56
57 - **WHEN** the user selects 1080p and later restarts the app
58 - **THEN** video quality remains 1080p
59
60 #### Scenario: Default is Auto
61
62 - **WHEN** no prior video quality choice exists
63 - **THEN** the effective choice is Auto
@@ -0,0 +1,63 @@
1# Spec Delta
2
3## Purpose
4
5Steuert, in welcher Aufloesung die eigene Kamera erfasst und dem Call angeboten wird, und welche Qualitaet fuer Stage-Kamera-Empfang angefordert wird — waehlbar als Auto, 720p oder 1080p.
6
7## ADDED Requirements
8
9### Requirement: Camera capture prefers the selected quality ceiling
10
11The client SHALL capture the local camera at the highest supported widescreen format at least 30 fps that does not exceed the active quality ceiling (720p or 1080p). Auto SHALL use a 1080p ceiling when the camera can deliver it, otherwise 720p. The client SHALL NOT offer or use a 4K camera quality mode.
12
13#### Scenario: Camera supports 1080p with Auto
14
15- **WHEN** video quality is Auto and the selected camera exposes a suitable 1920×1080 (or equivalent 16:9) format at ≥30 fps
16- **THEN** capture uses that 1080p-class format (not forced down to 720p before encoding)
17
18#### Scenario: Camera only supports 720p
19
20- **WHEN** video quality is Auto or 1080p and the camera cannot provide a suitable 1080p format
21- **THEN** capture falls back to a suitable 720p format without failing camera start solely for that reason
22
23#### Scenario: User locks 720p
24
25- **WHEN** video quality is set to 720p and a higher camera format is available
26- **THEN** capture stays at or below 720p
27
28### Requirement: Send capabilities match capture ceiling
29
30After the local camera size for sending is known, the client SHALL advertise max video send capabilities whose width and height reflect that capture size (up to the active quality ceiling), so the meeting media path can request layers up to that size.
31
32#### Scenario: 1080p capture is advertised
33
34- **WHEN** the outbound camera frame size is 1920×1080
35- **THEN** the send-capabilities update reports max width and height of at least 1920 on the largest side consistent with that frame
36
37### Requirement: Stage receive requests use 1080p-class limits when allowed
38
39For non-screen camera tiles shown as stage detail, the client SHALL request receive limits at 1080p-class macroblock and throughput budgets when the active quality ceiling is Auto or 1080p. When the ceiling is 720p, stage requests SHALL remain at 720p-class budgets. Small gallery tiles and screen-share receive limits SHALL keep their existing budgets.
40
41#### Scenario: Stage at Auto or 1080p
42
43- **WHEN** the user is subscribed to a participant camera on the stage and video quality is Auto or 1080p
44- **THEN** the stage receive request uses 1080p-class `max-fs` / `max-mbps` budgets (same order of magnitude as today’s screen-share camera request, not the previous 720p stage budget)
45
46#### Scenario: Stage locked to 720p
47
48- **WHEN** video quality is 720p and the user is subscribed to a stage camera tile
49- **THEN** the stage receive request uses 720p-class budgets
50
51### Requirement: Video quality setting is user-visible and persistent
52
53The product SHALL expose a video quality choice of Auto, 720p, and 1080p in the call/device camera controls, persist the choice across app restarts, and apply it to new captures and new stage subscriptions. Changing the setting while a call is active SHALL take effect for subsequent capture restarts and subsequent stage request updates without requiring an app relaunch.
54
55#### Scenario: Persist across restart
56
57- **WHEN** the user selects 1080p and later restarts the app
58- **THEN** video quality remains 1080p
59
60#### Scenario: Default is Auto
61
62- **WHEN** no prior video quality choice exists
63- **THEN** the effective choice is Auto
openspec/changes/archive/2026-11-12-camera-video-quality/tasks.md added +20 −0
@@ -0,0 +1,20 @@
1 # Tasks
2
3 ## 1. Qualitaetsmodell und Capture
4
5 - [x] 1.1 `VideoQuality` (Auto / 720 / 1080) und Ableitung der Capture-Decke in `calling` einfuehren; Verify: Unit-Test fuer Ceiling-Mapping
6 - [x] 1.2 `pick_format` / `fit_widescreen` / Open-Fallback auf die Decke umstellen (Preferenz 1080 bei Auto/1080); Verify: `cargo test -p calling --lib` Filter Formatwahl / widescreen
7 - [x] 1.3 Bestehende Capture-Tests an neue Preferenz anpassen; Verify: `cargo test -p calling --lib camera` (oder engerer Filter) gruen
8
9 ## 2. Send- und Stage-Limits
10
11 - [x] 2.1 Stage-Receive-Limits fuer Auto/1080 auf 1080p-Klasse setzen (`max-fs` 8160, kamerataugliches `max-fps`/`max-mbps`); 720 belaesst alte Stage-Budgets; Verify: Tests in `video_layout` fuer Stage-Body
12 - [x] 2.2 Send-Capabilities weiter an tatsaechliche Capture-Groesse koppeln und gegen Ceiling absichern; Verify: `send_capabilities_body`-Tests / Reporter
13 - [x] 2.3 Small-Tile- und Screen-Share-Limits unveraendert lassen; Verify: bestehende Assertions fuer Small/Screen weiterhin gruen
14
15 ## 3. Setting, UI, Apply im Call
16
17 - [x] 3.1 Videoqualitaet persistieren (Default Auto) analog Geraete-/Call-Settings; Verify: Roundtrip-Test oder Settings-Serialisierung
18 - [x] 3.2 Auswahl Auto/720p/1080p im Kamera-Menue (Call + Prejoin); Verify: manueller UI-Smoke oder View-Test falls vorhanden
19 - [x] 3.3 Wechsel der Stufe startet Capture neu und aktualisiert Stage-Requests ohne App-Neustart; Verify: gezielter calling/app-Test oder dokumentierter Smoke-Schritt
20 - [x] 3.4 Integration: `cargo test -p calling --lib` und relevante `cargo test -p app …`-Filter gruen
@@ -0,0 +1,20 @@
1# Tasks
2
3## 1. Qualitaetsmodell und Capture
4
5- [x] 1.1 `VideoQuality` (Auto / 720 / 1080) und Ableitung der Capture-Decke in `calling` einfuehren; Verify: Unit-Test fuer Ceiling-Mapping
6- [x] 1.2 `pick_format` / `fit_widescreen` / Open-Fallback auf die Decke umstellen (Preferenz 1080 bei Auto/1080); Verify: `cargo test -p calling --lib` Filter Formatwahl / widescreen
7- [x] 1.3 Bestehende Capture-Tests an neue Preferenz anpassen; Verify: `cargo test -p calling --lib camera` (oder engerer Filter) gruen
8
9## 2. Send- und Stage-Limits
10
11- [x] 2.1 Stage-Receive-Limits fuer Auto/1080 auf 1080p-Klasse setzen (`max-fs` 8160, kamerataugliches `max-fps`/`max-mbps`); 720 belaesst alte Stage-Budgets; Verify: Tests in `video_layout` fuer Stage-Body
12- [x] 2.2 Send-Capabilities weiter an tatsaechliche Capture-Groesse koppeln und gegen Ceiling absichern; Verify: `send_capabilities_body`-Tests / Reporter
13- [x] 2.3 Small-Tile- und Screen-Share-Limits unveraendert lassen; Verify: bestehende Assertions fuer Small/Screen weiterhin gruen
14
15## 3. Setting, UI, Apply im Call
16
17- [x] 3.1 Videoqualitaet persistieren (Default Auto) analog Geraete-/Call-Settings; Verify: Roundtrip-Test oder Settings-Serialisierung
18- [x] 3.2 Auswahl Auto/720p/1080p im Kamera-Menue (Call + Prejoin); Verify: manueller UI-Smoke oder View-Test falls vorhanden
19- [x] 3.3 Wechsel der Stufe startet Capture neu und aktualisiert Stage-Requests ohne App-Neustart; Verify: gezielter calling/app-Test oder dokumentierter Smoke-Schritt
20- [x] 3.4 Integration: `cargo test -p calling --lib` und relevante `cargo test -p app …`-Filter gruen
openspec/changes/archive/2026-11-12-fix-1to1-video-share/.openspec.yaml added +2 −0
@@ -0,0 +1,2 @@
1 schema: spec-driven
2 created: 2026-11-12
@@ -0,0 +1,2 @@
1schema: spec-driven
2created: 2026-11-12
openspec/changes/archive/2026-11-12-fix-1to1-video-share/design.md added +44 −0
@@ -0,0 +1,44 @@
1 # Design
2
3 ## Context
4
5 Siehe `proposal.md`. Call-Report `20261112T130854Z-1to1`: Escalation-Answer 14 Zeilen auf Offer mit 13 (`mid 3-0` extra), Same-peer-Kamera-Answer ~5 s nach 40-s-Timeout, Kamera-Open mit `CameraFormat: Failed to Fufill`.
6
7 `from_teams_offer` entfaltet `a=x-multi-stream` auf mid 3 in Browser-Mids `3-0` und `3`. `to_teams_answer` ruft `to_teams_offer` mit dem Remote-`OfferPlan` auf und schreibt beide Mids als eigene m-lines.
8
9 ## Goals / Non-Goals
10
11 **Goals:**
12
13 - Signalisierte Answers: eine m-line pro Teams-Offer-Zeile, Fold zurück zu `x-multi-stream`.
14 - Same-peer: kurze Grace nach Timeout für passende Kamera-Answers.
15 - Kamera-Open: Property-Fehler → Fallback-Kette.
16
17 **Non-Goals:**
18
19 - Command-Queue, Portal-Lifetime, PipeWire-BGRA (erst nach Retest).
20 - Share-Grace ohne Answer (Server-`408`).
21
22 ## Decisions
23
24 ### Fold nur in der signalisierten Answer
25
26 Browser-Mids bleiben intern eindeutig (`3-0`, `3`). Beim Schreiben der Teams-Answer: Gallery-Carrier wie bei Offers — Nicht-Carrier-Mids auslassen, Carrier mit `x-multi-stream`-Count. `to_teams_answer` kann denselben `to_teams_offer`-Pfad nutzen, sobald der Plan die Faltung korrekt steuert; Regressionstest gegen Offer mit 13 Zeilen → Answer 13 Zeilen, kein `a=mid:3-0`.
27
28 ### Late Answer: kurze Grace, nicht Timeout verlängern
29
30 Nach `SAME_PEER_ANSWER_LIMIT` Rollback + `undo_change` wie bisher. Zusätzlich die letzte Same-peer-Offer-Identität (reply_tags / signaled / change) für wenige Sekunden behalten. Trifft eine passende Answer ein: `apply_answer`, Kamera wieder an, `recvonly` auf der Gegenseite als Send-Erfolg. Kein generelles Anheben auf 60+ s (Share hatte keine Answer).
31
32 ### Kamera: Liste optional
33
34 `open_picked_format` darf bei `compatible_camera_formats`-Fehler sofort in die bestehende `open_camera`-Fallback-Kette (Closest NV12/YUYV, AbsoluteHighest) gehen, statt den Fehler nach oben zu reichen.
35
36 ## Risks / Trade-offs
37
38 - [Late Answer nach Undo startet Capture zweimal] → `start_camera` idempotent bzw. nur UI/SDP anwenden, wenn Capture schon läuft; sonst Capture neu.
39 - [Falsche Answer in der Grace] → nur `answers_offer` mit gespeicherten reply_tags.
40 - [Fold ändert Conference-Offers] → Test mit Multi-Stream-Offer und bestehendem Fold-Test für Browser-Mids.
41
42 ## Migration Plan
43
44 Kein Daten-Migration. Deploy: Fork-Build / lokale Installation. Rollback: vorheriger Tag.
@@ -0,0 +1,44 @@
1# Design
2
3## Context
4
5Siehe `proposal.md`. Call-Report `20261112T130854Z-1to1`: Escalation-Answer 14 Zeilen auf Offer mit 13 (`mid 3-0` extra), Same-peer-Kamera-Answer ~5 s nach 40-s-Timeout, Kamera-Open mit `CameraFormat: Failed to Fufill`.
6
7`from_teams_offer` entfaltet `a=x-multi-stream` auf mid 3 in Browser-Mids `3-0` und `3`. `to_teams_answer` ruft `to_teams_offer` mit dem Remote-`OfferPlan` auf und schreibt beide Mids als eigene m-lines.
8
9## Goals / Non-Goals
10
11**Goals:**
12
13- Signalisierte Answers: eine m-line pro Teams-Offer-Zeile, Fold zurück zu `x-multi-stream`.
14- Same-peer: kurze Grace nach Timeout für passende Kamera-Answers.
15- Kamera-Open: Property-Fehler → Fallback-Kette.
16
17**Non-Goals:**
18
19- Command-Queue, Portal-Lifetime, PipeWire-BGRA (erst nach Retest).
20- Share-Grace ohne Answer (Server-`408`).
21
22## Decisions
23
24### Fold nur in der signalisierten Answer
25
26Browser-Mids bleiben intern eindeutig (`3-0`, `3`). Beim Schreiben der Teams-Answer: Gallery-Carrier wie bei Offers — Nicht-Carrier-Mids auslassen, Carrier mit `x-multi-stream`-Count. `to_teams_answer` kann denselben `to_teams_offer`-Pfad nutzen, sobald der Plan die Faltung korrekt steuert; Regressionstest gegen Offer mit 13 Zeilen → Answer 13 Zeilen, kein `a=mid:3-0`.
27
28### Late Answer: kurze Grace, nicht Timeout verlängern
29
30Nach `SAME_PEER_ANSWER_LIMIT` Rollback + `undo_change` wie bisher. Zusätzlich die letzte Same-peer-Offer-Identität (reply_tags / signaled / change) für wenige Sekunden behalten. Trifft eine passende Answer ein: `apply_answer`, Kamera wieder an, `recvonly` auf der Gegenseite als Send-Erfolg. Kein generelles Anheben auf 60+ s (Share hatte keine Answer).
31
32### Kamera: Liste optional
33
34`open_picked_format` darf bei `compatible_camera_formats`-Fehler sofort in die bestehende `open_camera`-Fallback-Kette (Closest NV12/YUYV, AbsoluteHighest) gehen, statt den Fehler nach oben zu reichen.
35
36## Risks / Trade-offs
37
38- [Late Answer nach Undo startet Capture zweimal] → `start_camera` idempotent bzw. nur UI/SDP anwenden, wenn Capture schon läuft; sonst Capture neu.
39- [Falsche Answer in der Grace] → nur `answers_offer` mit gespeicherten reply_tags.
40- [Fold ändert Conference-Offers] → Test mit Multi-Stream-Offer und bestehendem Fold-Test für Browser-Mids.
41
42## Migration Plan
43
44Kein Daten-Migration. Deploy: Fork-Build / lokale Installation. Rollback: vorheriger Tag.
openspec/changes/archive/2026-11-12-fix-1to1-video-share/proposal.md added +29 −0
@@ -0,0 +1,29 @@
1 # Proposal
2
3 ## Why
4
5 In einem 1:1-Gespräch unter Hyprland starteten Kamera und Screen-Share nicht. Die Escalation-Answer enthielt eine Extra-m-line (`mid 3-0`) und Teams lehnte mit `InvalidNumberOfMedia` ab. Eine verspätete Same-peer-Answer für die Kamera wurde nach dem 40-s-Timeout verworfen. Parallel starb der lokale Kamera-Open an `CameraFormat: Failed to Fufill`.
6
7 ## What Changes
8
9 - Escalation-/Teams-Answers fassen gefaltetes `x-multi-stream` wieder zu einer m-line zusammen (keine Extra-Zeile `3-0`).
10 - Eine Same-peer-Answer, die kurz nach dem Timeout zum zuletzt gesendeten Offer gehört, wird noch angewendet.
11 - Kamera-Open fällt auf Rohformate zurück, wenn die Format-Property fehlschlägt.
12 - **Out of scope:** Command-Queue, Portal-Lifetime und PipeWire-BGRA — erst nach Retest, falls noch nötig.
13
14 ## Capabilities
15
16 ### New Capabilities
17
18 - `call-media-negotiation`: SDP-/Renegotiation-Verhalten für Escalation-Answers und Same-peer-Kamera-Answers.
19 - `camera-capture`: Lokaler Kamera-Start trotz fehlgeschlagener Format-Property.
20
21 ### Modified Capabilities
22
23 - (keine) — `screen-share` (Portal-Dialog) bleibt unverändert.
24
25 ## Impact
26
27 - Signaling/SDP in `crates/calling` (`sdp.rs`, `call.rs`)
28 - Kamera-Open in `crates/calling/src/camera.rs`
29 - Call-Reports und Retarget-Fehler bei 1:1 mit Multi-Stream-Offers
@@ -0,0 +1,29 @@
1# Proposal
2
3## Why
4
5In einem 1:1-Gespräch unter Hyprland starteten Kamera und Screen-Share nicht. Die Escalation-Answer enthielt eine Extra-m-line (`mid 3-0`) und Teams lehnte mit `InvalidNumberOfMedia` ab. Eine verspätete Same-peer-Answer für die Kamera wurde nach dem 40-s-Timeout verworfen. Parallel starb der lokale Kamera-Open an `CameraFormat: Failed to Fufill`.
6
7## What Changes
8
9- Escalation-/Teams-Answers fassen gefaltetes `x-multi-stream` wieder zu einer m-line zusammen (keine Extra-Zeile `3-0`).
10- Eine Same-peer-Answer, die kurz nach dem Timeout zum zuletzt gesendeten Offer gehört, wird noch angewendet.
11- Kamera-Open fällt auf Rohformate zurück, wenn die Format-Property fehlschlägt.
12- **Out of scope:** Command-Queue, Portal-Lifetime und PipeWire-BGRA — erst nach Retest, falls noch nötig.
13
14## Capabilities
15
16### New Capabilities
17
18- `call-media-negotiation`: SDP-/Renegotiation-Verhalten für Escalation-Answers und Same-peer-Kamera-Answers.
19- `camera-capture`: Lokaler Kamera-Start trotz fehlgeschlagener Format-Property.
20
21### Modified Capabilities
22
23- (keine) — `screen-share` (Portal-Dialog) bleibt unverändert.
24
25## Impact
26
27- Signaling/SDP in `crates/calling` (`sdp.rs`, `call.rs`)
28- Kamera-Open in `crates/calling/src/camera.rs`
29- Call-Reports und Retarget-Fehler bei 1:1 mit Multi-Stream-Offers
openspec/changes/archive/2026-11-12-fix-1to1-video-share/specs/call-media-negotiation/spec.md added +25 −0
@@ -0,0 +1,25 @@
1 # Spec Delta
2
3 ## Purpose
4
5 Signaling und SDP für Kamera und Screen-Share in verbundenen Gesprächen: Escalation-Answers und Same-peer-Renegotiation verhalten sich so, dass die Gegenseite die Media-Zeilen akzeptiert und verspätete Kamera-Answers noch greifen.
6
7 ## ADDED Requirements
8
9 ### Requirement: Escalation-Answer behält die Offer-Zeilenzahl
10 Bei einer Media-Renegotiation mit Escalation MUST die an Teams signalisierte Answer dieselbe Anzahl Media-Zeilen haben wie das Remote-Offer. Eine intern gefaltete Multi-Stream-Zeile MUST als genau eine signalisierte m-line zurückgehen.
11
12 #### Scenario: Multi-Stream-Zeile ohne Extra-Mid
13 - **WHEN** das Remote-Offer eine Video-Zeile mit `x-multi-stream` trägt, die intern in mehrere Browser-Mids entfaltet wurde
14 - **THEN** enthält die signalisierte Answer für diese Rolle genau eine m-line und keine zusätzliche Mid, die nur der internen Entfaltung dient
15
16 #### Scenario: Zeilenzahl stimmt mit dem Offer
17 - **WHEN** das Remote-Offer N Media-Zeilen hat
18 - **THEN** hat die signalisierte Escalation-Answer ebenfalls N Media-Zeilen
19
20 ### Requirement: Verspätete Same-peer-Kamera-Answer gilt
21 Sendet die App in einem Direct-1:1 eine Same-peer-Renegotiation für Kamera an und trifft die passende Answer erst kurz nach dem lokalen Answer-Timeout ein, MUST die App diese Answer noch anwenden, sofern sie zum zuletzt gesendeten Offer gehört. Eine Answer mit empfangsseitiger Kamera-Richtung (`recvonly` aus Sicht der Gegenseite) MUST als erfolgreiches Freigeben des lokalen Sendens gelten.
22
23 #### Scenario: Answer wenige Sekunden nach Timeout
24 - **WHEN** das lokale Same-peer-Kamera-Offer wegen Timeout zurückgerollt wurde und kurz danach die passende Answer eintrifft
25 - **THEN** wendet die App die Answer an und die Kamera bleibt bzw. wird wieder als sendend geführt, statt die Answer zu verwerfen
@@ -0,0 +1,25 @@
1# Spec Delta
2
3## Purpose
4
5Signaling und SDP für Kamera und Screen-Share in verbundenen Gesprächen: Escalation-Answers und Same-peer-Renegotiation verhalten sich so, dass die Gegenseite die Media-Zeilen akzeptiert und verspätete Kamera-Answers noch greifen.
6
7## ADDED Requirements
8
9### Requirement: Escalation-Answer behält die Offer-Zeilenzahl
10Bei einer Media-Renegotiation mit Escalation MUST die an Teams signalisierte Answer dieselbe Anzahl Media-Zeilen haben wie das Remote-Offer. Eine intern gefaltete Multi-Stream-Zeile MUST als genau eine signalisierte m-line zurückgehen.
11
12#### Scenario: Multi-Stream-Zeile ohne Extra-Mid
13- **WHEN** das Remote-Offer eine Video-Zeile mit `x-multi-stream` trägt, die intern in mehrere Browser-Mids entfaltet wurde
14- **THEN** enthält die signalisierte Answer für diese Rolle genau eine m-line und keine zusätzliche Mid, die nur der internen Entfaltung dient
15
16#### Scenario: Zeilenzahl stimmt mit dem Offer
17- **WHEN** das Remote-Offer N Media-Zeilen hat
18- **THEN** hat die signalisierte Escalation-Answer ebenfalls N Media-Zeilen
19
20### Requirement: Verspätete Same-peer-Kamera-Answer gilt
21Sendet die App in einem Direct-1:1 eine Same-peer-Renegotiation für Kamera an und trifft die passende Answer erst kurz nach dem lokalen Answer-Timeout ein, MUST die App diese Answer noch anwenden, sofern sie zum zuletzt gesendeten Offer gehört. Eine Answer mit empfangsseitiger Kamera-Richtung (`recvonly` aus Sicht der Gegenseite) MUST als erfolgreiches Freigeben des lokalen Sendens gelten.
22
23#### Scenario: Answer wenige Sekunden nach Timeout
24- **WHEN** das lokale Same-peer-Kamera-Offer wegen Timeout zurückgerollt wurde und kurz danach die passende Answer eintrifft
25- **THEN** wendet die App die Answer an und die Kamera bleibt bzw. wird wieder als sendend geführt, statt die Answer zu verwerfen
openspec/changes/archive/2026-11-12-fix-1to1-video-share/specs/camera-capture/spec.md added +18 −0
@@ -0,0 +1,18 @@
1 # Spec Delta
2
3 ## Purpose
4
5 Lokaler Kamera-Start in Gesprächen und Prejoin, wenn das Gerät Formate liefert, die Property-Abfrage aber fehlschlägt.
6
7 ## ADDED Requirements
8
9 ### Requirement: Format-Property-Fehler blockiert den Open nicht
10 Schlägt die Abfrage der unterstützten Kamera-Formate oder der laufenden Format-Property fehl, MUST die App den Stream trotzdem mit einem Rohformat (etwa NV12 oder YUYV) bzw. dem bestehenden Fallback öffnen, sofern das Gerät das erlaubt. Nur wenn kein Fallback-Open gelingt, MUST die App dem Nutzer den Fehler anzeigen.
11
12 #### Scenario: Property fehlgeschlagen, Rohformat verfügbar
13 - **WHEN** der Nutzer die Kamera einschaltet und die Format-Property fehlschlägt, das Gerät aber ein Rohformat bei der gewünschten Rate anbietet
14 - **THEN** startet die lokale Kamera und zeigt keinen fatalen Format-Property-Stop
15
16 #### Scenario: Kein Fallback möglich
17 - **WHEN** weder Formatliste noch Fallback-Open ein Rohformat liefern
18 - **THEN** bleibt die Kamera aus und die App zeigt den Fehler klar an
@@ -0,0 +1,18 @@
1# Spec Delta
2
3## Purpose
4
5Lokaler Kamera-Start in Gesprächen und Prejoin, wenn das Gerät Formate liefert, die Property-Abfrage aber fehlschlägt.
6
7## ADDED Requirements
8
9### Requirement: Format-Property-Fehler blockiert den Open nicht
10Schlägt die Abfrage der unterstützten Kamera-Formate oder der laufenden Format-Property fehl, MUST die App den Stream trotzdem mit einem Rohformat (etwa NV12 oder YUYV) bzw. dem bestehenden Fallback öffnen, sofern das Gerät das erlaubt. Nur wenn kein Fallback-Open gelingt, MUST die App dem Nutzer den Fehler anzeigen.
11
12#### Scenario: Property fehlgeschlagen, Rohformat verfügbar
13- **WHEN** der Nutzer die Kamera einschaltet und die Format-Property fehlschlägt, das Gerät aber ein Rohformat bei der gewünschten Rate anbietet
14- **THEN** startet die lokale Kamera und zeigt keinen fatalen Format-Property-Stop
15
16#### Scenario: Kein Fallback möglich
17- **WHEN** weder Formatliste noch Fallback-Open ein Rohformat liefern
18- **THEN** bleibt die Kamera aus und die App zeigt den Fehler klar an
openspec/changes/archive/2026-11-12-fix-1to1-video-share/tasks.md added +20 −0
@@ -0,0 +1,20 @@
1 # Tasks
2
3 ## 1. Escalation-Answer ohne Extra-m-line
4
5 - [x] 1.1 `to_teams_answer` / Offer-Plan: Gallery-Faltung (`3-0` + `3`) als eine signalisierte m-line mit `x-multi-stream` zurückschreiben; Verify: Unit-Test Offer 13 Zeilen → Answer 13 Zeilen, kein `a=mid:3-0`
6 - [x] 1.2 Bestehenden Fold-Test für Browser-Mids grün lassen; Verify: `cargo test -p calling --lib sdp`
7
8 ## 2. Same-peer Late Answer
9
10 - [x] 2.1 Nach Same-peer-Timeout kurze Grace mit reply_tags/change behalten und passende Answer noch anwenden (`recvonly` = Send ok); Verify: Unit- oder Drive-naher Test / dokumentierter Timeline-Check
11 - [x] 2.2 Verify: `cargo test -p calling --lib` Filter renegotiation/call wo vorhanden
12
13 ## 3. Kamera-Open Fallback
14
15 - [x] 3.1 `open_picked_format` / `open_camera`: Format-Property-Fehler → Fallback-Kette statt fatal; Verify: `cargo test -p calling --lib camera`
16
17 ## 4. Integration
18
19 - [x] 4.1 `cargo test -p calling --lib` grün (441 passed; `sdp_golden` 5/5; ignored Kamera-Hardware-Open ok)
20 - [x] 4.2 Automatisierter Kamera-Open-Smoke grün; voller Hyprland-1:1 Call-Report bleibt Operator-Retest nach Install — Queue/PipeWire nur bei noch rotem Report
@@ -0,0 +1,20 @@
1# Tasks
2
3## 1. Escalation-Answer ohne Extra-m-line
4
5- [x] 1.1 `to_teams_answer` / Offer-Plan: Gallery-Faltung (`3-0` + `3`) als eine signalisierte m-line mit `x-multi-stream` zurückschreiben; Verify: Unit-Test Offer 13 Zeilen → Answer 13 Zeilen, kein `a=mid:3-0`
6- [x] 1.2 Bestehenden Fold-Test für Browser-Mids grün lassen; Verify: `cargo test -p calling --lib sdp`
7
8## 2. Same-peer Late Answer
9
10- [x] 2.1 Nach Same-peer-Timeout kurze Grace mit reply_tags/change behalten und passende Answer noch anwenden (`recvonly` = Send ok); Verify: Unit- oder Drive-naher Test / dokumentierter Timeline-Check
11- [x] 2.2 Verify: `cargo test -p calling --lib` Filter renegotiation/call wo vorhanden
12
13## 3. Kamera-Open Fallback
14
15- [x] 3.1 `open_picked_format` / `open_camera`: Format-Property-Fehler → Fallback-Kette statt fatal; Verify: `cargo test -p calling --lib camera`
16
17## 4. Integration
18
19- [x] 4.1 `cargo test -p calling --lib` grün (441 passed; `sdp_golden` 5/5; ignored Kamera-Hardware-Open ok)
20- [x] 4.2 Automatisierter Kamera-Open-Smoke grün; voller Hyprland-1:1 Call-Report bleibt Operator-Retest nach Install — Queue/PipeWire nur bei noch rotem Report
openspec/specs/call-media-negotiation/spec.md added +25 −0
@@ -0,0 +1,25 @@
1 # call-media-negotiation Specification
2
3 ## Purpose
4
5 Signaling und SDP für Kamera und Screen-Share in verbundenen Gesprächen: Escalation-Answers und Same-peer-Renegotiation verhalten sich so, dass die Gegenseite die Media-Zeilen akzeptiert und verspätete Kamera-Answers noch greifen.
6
7 ## Requirements
8
9 ### Requirement: Escalation-Answer behält die Offer-Zeilenzahl
10 Bei einer Media-Renegotiation mit Escalation MUST die an Teams signalisierte Answer dieselbe Anzahl Media-Zeilen haben wie das Remote-Offer. Eine intern gefaltete Multi-Stream-Zeile MUST als genau eine signalisierte m-line zurückgehen.
11
12 #### Scenario: Multi-Stream-Zeile ohne Extra-Mid
13 - **WHEN** das Remote-Offer eine Video-Zeile mit `x-multi-stream` trägt, die intern in mehrere Browser-Mids entfaltet wurde
14 - **THEN** enthält die signalisierte Answer für diese Rolle genau eine m-line und keine zusätzliche Mid, die nur der internen Entfaltung dient
15
16 #### Scenario: Zeilenzahl stimmt mit dem Offer
17 - **WHEN** das Remote-Offer N Media-Zeilen hat
18 - **THEN** hat die signalisierte Escalation-Answer ebenfalls N Media-Zeilen
19
20 ### Requirement: Verspätete Same-peer-Kamera-Answer gilt
21 Sendet die App in einem Direct-1:1 eine Same-peer-Renegotiation für Kamera an und trifft die passende Answer erst kurz nach dem lokalen Answer-Timeout ein, MUST die App diese Answer noch anwenden, sofern sie zum zuletzt gesendeten Offer gehört. Eine Answer mit empfangsseitiger Kamera-Richtung (`recvonly` aus Sicht der Gegenseite) MUST als erfolgreiches Freigeben des lokalen Sendens gelten.
22
23 #### Scenario: Answer wenige Sekunden nach Timeout
24 - **WHEN** das lokale Same-peer-Kamera-Offer wegen Timeout zurückgerollt wurde und kurz danach die passende Answer eintrifft
25 - **THEN** wendet die App die Answer an und die Kamera bleibt bzw. wird wieder als sendend geführt, statt die Answer zu verwerfen
@@ -0,0 +1,25 @@
1# call-media-negotiation Specification
2
3## Purpose
4
5Signaling und SDP für Kamera und Screen-Share in verbundenen Gesprächen: Escalation-Answers und Same-peer-Renegotiation verhalten sich so, dass die Gegenseite die Media-Zeilen akzeptiert und verspätete Kamera-Answers noch greifen.
6
7## Requirements
8
9### Requirement: Escalation-Answer behält die Offer-Zeilenzahl
10Bei einer Media-Renegotiation mit Escalation MUST die an Teams signalisierte Answer dieselbe Anzahl Media-Zeilen haben wie das Remote-Offer. Eine intern gefaltete Multi-Stream-Zeile MUST als genau eine signalisierte m-line zurückgehen.
11
12#### Scenario: Multi-Stream-Zeile ohne Extra-Mid
13- **WHEN** das Remote-Offer eine Video-Zeile mit `x-multi-stream` trägt, die intern in mehrere Browser-Mids entfaltet wurde
14- **THEN** enthält die signalisierte Answer für diese Rolle genau eine m-line und keine zusätzliche Mid, die nur der internen Entfaltung dient
15
16#### Scenario: Zeilenzahl stimmt mit dem Offer
17- **WHEN** das Remote-Offer N Media-Zeilen hat
18- **THEN** hat die signalisierte Escalation-Answer ebenfalls N Media-Zeilen
19
20### Requirement: Verspätete Same-peer-Kamera-Answer gilt
21Sendet die App in einem Direct-1:1 eine Same-peer-Renegotiation für Kamera an und trifft die passende Answer erst kurz nach dem lokalen Answer-Timeout ein, MUST die App diese Answer noch anwenden, sofern sie zum zuletzt gesendeten Offer gehört. Eine Answer mit empfangsseitiger Kamera-Richtung (`recvonly` aus Sicht der Gegenseite) MUST als erfolgreiches Freigeben des lokalen Sendens gelten.
22
23#### Scenario: Answer wenige Sekunden nach Timeout
24- **WHEN** das lokale Same-peer-Kamera-Offer wegen Timeout zurückgerollt wurde und kurz danach die passende Answer eintrifft
25- **THEN** wendet die App die Answer an und die Kamera bleibt bzw. wird wieder als sendend geführt, statt die Answer zu verwerfen
openspec/specs/camera-capture/spec.md added +50 −0
@@ -0,0 +1,50 @@
1 # camera-capture Specification
2
3 ## Purpose
4
5 Lokaler Kamera-Start in Gesprächen und Prejoin, wenn das Gerät Formate liefert, die Property-Abfrage aber fehlschlägt.
6
7 ## Requirements
8
9 ### Requirement: Format-Property-Fehler blockiert den Open nicht
10 Schlägt die Abfrage der unterstützten Kamera-Formate oder der laufenden Format-Property fehl, MUST die App den Stream trotzdem mit einem 30-fps-fähigen Kandidaten (MJPEG oder Rohformat) öffnen, sofern das Gerät das erlaubt. Nur wenn kein 30-fps-Open gelingt, MAY die App einen langsameren Fallback nutzen; schlägt alles fehl, MUST die App dem Nutzer den Fehler anzeigen.
11
12 #### Scenario: Property fehlgeschlagen, 30-fps-Format verfügbar
13 - **WHEN** der Nutzer die Kamera einschaltet und die Format-Property fehlschlägt, das Gerät aber MJPEG oder Raw bei 30 fps anbietet
14 - **THEN** startet die lokale Kamera mit einem 30-fps-Format und zeigt keinen fatalen Format-Property-Stop
15
16 #### Scenario: Kein Fallback möglich
17 - **WHEN** weder Formatliste noch Fallback-Open ein nutzbares Format liefern
18 - **THEN** bleibt die Kamera aus und die App zeigt den Fehler klar an
19
20 ### Requirement: Capture wählt mindestens 30 fps wenn verfügbar
21 Wenn das Gerät mindestens ein Format mit 30 fps anbietet, MUST die App einen Stream mit mindestens 30 fps öffnen. Ein Open unter 30 fps (z. B. YUYV 1080p@5) MUST verworfen und durch den nächsten Kandidaten ersetzt werden, solange ein 30-fps-Kandidat übrig ist.
22
23 #### Scenario: C930e Auto wählt MJPEG 1080p@30
24 - **WHEN** die Kamera YUYV nur bis 1080p@5 / 720p@10 und MJPEG bis 1080p@30 anbietet und die Qualität Auto oder 1080p ist
25 - **THEN** öffnet die App MJPEG 1920×1080 bei 30 fps (oder ein anderes 30-fps-HD-Format), nicht YUYV@5
26
27 #### Scenario: 720p-Qualität
28 - **WHEN** die Qualität 720p ist und MJPEG 1280×720@30 verfügbar ist
29 - **THEN** öffnet die App dieses Format (oder Raw 30 fps gleicher Höhe), nicht ein Format unter 30 fps
30
31 ### Requirement: MJPEG wird dekodiert und gesendet
32 MJPEG-Frames MUST lokal nach I420 dekodiert und in die bestehende Sendepipeline (Effects → Encoder) gegeben werden, ohne den Nutzer mit einem Undecodable-Hinweis abzubrechen, solange der Decode gelingt.
33
34 #### Scenario: MJPEG-Frame wird I420
35 - **WHEN** der Capture-Stream MJPEG liefert
36 - **THEN** entsteht ein I420-Frame für Preview und Send, und die Timeline zählt Capture-Frames
37
38 ### Requirement: UVC-Bildrate und Netzfrequenz (best effort)
39 Nach erfolgreichem Open SHOULD die App `exposure_dynamic_framerate` deaktivieren und `power_line_frequency` auf 50 Hz setzen, wenn die Controls existieren. Fehlende Controls MUST den Stream nicht abbrechen.
40
41 #### Scenario: Controls fehlen
42 - **WHEN** die Kamera eines der Controls nicht anbietet
43 - **THEN** läuft der Stream weiter ohne Fehlerdialog
44
45 ### Requirement: Capture-Telemetrie im Call-Report
46 Beim Kamera-Start MUST die Timeline das gewählte Format (Pixel-Format, Auflösung, fps) nennen. Laufende Stats SHOULD Capture-fps und Decode-Zeit sichtbar machen, damit ein Call-Report zeigt, ob 30 fps ankommen.
47
48 #### Scenario: Format in der Timeline
49 - **WHEN** die Kamera erfolgreich startet
50 - **THEN** enthält die Timeline einen Eintrag mit Format wie `MJPG 1920x1080 @30`
@@ -0,0 +1,50 @@
1# camera-capture Specification
2
3## Purpose
4
5Lokaler Kamera-Start in Gesprächen und Prejoin, wenn das Gerät Formate liefert, die Property-Abfrage aber fehlschlägt.
6
7## Requirements
8
9### Requirement: Format-Property-Fehler blockiert den Open nicht
10Schlägt die Abfrage der unterstützten Kamera-Formate oder der laufenden Format-Property fehl, MUST die App den Stream trotzdem mit einem 30-fps-fähigen Kandidaten (MJPEG oder Rohformat) öffnen, sofern das Gerät das erlaubt. Nur wenn kein 30-fps-Open gelingt, MAY die App einen langsameren Fallback nutzen; schlägt alles fehl, MUST die App dem Nutzer den Fehler anzeigen.
11
12#### Scenario: Property fehlgeschlagen, 30-fps-Format verfügbar
13- **WHEN** der Nutzer die Kamera einschaltet und die Format-Property fehlschlägt, das Gerät aber MJPEG oder Raw bei 30 fps anbietet
14- **THEN** startet die lokale Kamera mit einem 30-fps-Format und zeigt keinen fatalen Format-Property-Stop
15
16#### Scenario: Kein Fallback möglich
17- **WHEN** weder Formatliste noch Fallback-Open ein nutzbares Format liefern
18- **THEN** bleibt die Kamera aus und die App zeigt den Fehler klar an
19
20### Requirement: Capture wählt mindestens 30 fps wenn verfügbar
21Wenn das Gerät mindestens ein Format mit 30 fps anbietet, MUST die App einen Stream mit mindestens 30 fps öffnen. Ein Open unter 30 fps (z. B. YUYV 1080p@5) MUST verworfen und durch den nächsten Kandidaten ersetzt werden, solange ein 30-fps-Kandidat übrig ist.
22
23#### Scenario: C930e Auto wählt MJPEG 1080p@30
24- **WHEN** die Kamera YUYV nur bis 1080p@5 / 720p@10 und MJPEG bis 1080p@30 anbietet und die Qualität Auto oder 1080p ist
25- **THEN** öffnet die App MJPEG 1920×1080 bei 30 fps (oder ein anderes 30-fps-HD-Format), nicht YUYV@5
26
27#### Scenario: 720p-Qualität
28- **WHEN** die Qualität 720p ist und MJPEG 1280×720@30 verfügbar ist
29- **THEN** öffnet die App dieses Format (oder Raw 30 fps gleicher Höhe), nicht ein Format unter 30 fps
30
31### Requirement: MJPEG wird dekodiert und gesendet
32MJPEG-Frames MUST lokal nach I420 dekodiert und in die bestehende Sendepipeline (Effects → Encoder) gegeben werden, ohne den Nutzer mit einem Undecodable-Hinweis abzubrechen, solange der Decode gelingt.
33
34#### Scenario: MJPEG-Frame wird I420
35- **WHEN** der Capture-Stream MJPEG liefert
36- **THEN** entsteht ein I420-Frame für Preview und Send, und die Timeline zählt Capture-Frames
37
38### Requirement: UVC-Bildrate und Netzfrequenz (best effort)
39Nach erfolgreichem Open SHOULD die App `exposure_dynamic_framerate` deaktivieren und `power_line_frequency` auf 50 Hz setzen, wenn die Controls existieren. Fehlende Controls MUST den Stream nicht abbrechen.
40
41#### Scenario: Controls fehlen
42- **WHEN** die Kamera eines der Controls nicht anbietet
43- **THEN** läuft der Stream weiter ohne Fehlerdialog
44
45### Requirement: Capture-Telemetrie im Call-Report
46Beim Kamera-Start MUST die Timeline das gewählte Format (Pixel-Format, Auflösung, fps) nennen. Laufende Stats SHOULD Capture-fps und Decode-Zeit sichtbar machen, damit ein Call-Report zeigt, ob 30 fps ankommen.
47
48#### Scenario: Format in der Timeline
49- **WHEN** die Kamera erfolgreich startet
50- **THEN** enthält die Timeline einen Eintrag mit Format wie `MJPG 1920x1080 @30`
openspec/specs/camera-video-quality/spec.md added +63 −0
@@ -0,0 +1,63 @@
1 # camera-video-quality Specification
2
3 ## Purpose
4
5 Steuert, in welcher Aufloesung die eigene Kamera erfasst und dem Call angeboten wird, und welche Qualitaet fuer Stage-Kamera-Empfang angefordert wird — waehlbar als Auto, 720p oder 1080p.
6
7 ## Requirements
8
9 ### Requirement: Camera capture prefers the selected quality ceiling
10
11 The client SHALL capture the local camera at the highest supported widescreen format at least 30 fps that does not exceed the active quality ceiling (720p or 1080p). Auto SHALL use a 1080p ceiling when the camera can deliver it, otherwise 720p. The client SHALL NOT offer or use a 4K camera quality mode.
12
13 #### Scenario: Camera supports 1080p with Auto
14
15 - **WHEN** video quality is Auto and the selected camera exposes a suitable 1920×1080 (or equivalent 16:9) format at ≥30 fps
16 - **THEN** capture uses that 1080p-class format (not forced down to 720p before encoding)
17
18 #### Scenario: Camera only supports 720p
19
20 - **WHEN** video quality is Auto or 1080p and the camera cannot provide a suitable 1080p format
21 - **THEN** capture falls back to a suitable 720p format without failing camera start solely for that reason
22
23 #### Scenario: User locks 720p
24
25 - **WHEN** video quality is set to 720p and a higher camera format is available
26 - **THEN** capture stays at or below 720p
27
28 ### Requirement: Send capabilities match capture ceiling
29
30 After the local camera size for sending is known, the client SHALL advertise max video send capabilities whose width and height reflect that capture size (up to the active quality ceiling), so the meeting media path can request layers up to that size.
31
32 #### Scenario: 1080p capture is advertised
33
34 - **WHEN** the outbound camera frame size is 1920×1080
35 - **THEN** the send-capabilities update reports max width and height of at least 1920 on the largest side consistent with that frame
36
37 ### Requirement: Stage receive requests use 1080p-class limits when allowed
38
39 For non-screen camera tiles shown as stage detail, the client SHALL request receive limits at 1080p-class macroblock and throughput budgets when the active quality ceiling is Auto or 1080p. When the ceiling is 720p, stage requests SHALL remain at 720p-class budgets. Small gallery tiles and screen-share receive limits SHALL keep their existing budgets.
40
41 #### Scenario: Stage at Auto or 1080p
42
43 - **WHEN** the user is subscribed to a participant camera on the stage and video quality is Auto or 1080p
44 - **THEN** the stage receive request uses 1080p-class `max-fs` / `max-mbps` budgets (same order of magnitude as today’s screen-share camera request, not the previous 720p stage budget)
45
46 #### Scenario: Stage locked to 720p
47
48 - **WHEN** video quality is 720p and the user is subscribed to a stage camera tile
49 - **THEN** the stage receive request uses 720p-class budgets
50
51 ### Requirement: Video quality setting is user-visible and persistent
52
53 The product SHALL expose a video quality choice of Auto, 720p, and 1080p in the call/device camera controls, persist the choice across app restarts, and apply it to new captures and new stage subscriptions. Changing the setting while a call is active SHALL take effect for subsequent capture restarts and subsequent stage request updates without requiring an app relaunch.
54
55 #### Scenario: Persist across restart
56
57 - **WHEN** the user selects 1080p and later restarts the app
58 - **THEN** video quality remains 1080p
59
60 #### Scenario: Default is Auto
61
62 - **WHEN** no prior video quality choice exists
63 - **THEN** the effective choice is Auto
@@ -0,0 +1,63 @@
1# camera-video-quality Specification
2
3## Purpose
4
5Steuert, in welcher Aufloesung die eigene Kamera erfasst und dem Call angeboten wird, und welche Qualitaet fuer Stage-Kamera-Empfang angefordert wird — waehlbar als Auto, 720p oder 1080p.
6
7## Requirements
8
9### Requirement: Camera capture prefers the selected quality ceiling
10
11The client SHALL capture the local camera at the highest supported widescreen format at least 30 fps that does not exceed the active quality ceiling (720p or 1080p). Auto SHALL use a 1080p ceiling when the camera can deliver it, otherwise 720p. The client SHALL NOT offer or use a 4K camera quality mode.
12
13#### Scenario: Camera supports 1080p with Auto
14
15- **WHEN** video quality is Auto and the selected camera exposes a suitable 1920×1080 (or equivalent 16:9) format at ≥30 fps
16- **THEN** capture uses that 1080p-class format (not forced down to 720p before encoding)
17
18#### Scenario: Camera only supports 720p
19
20- **WHEN** video quality is Auto or 1080p and the camera cannot provide a suitable 1080p format
21- **THEN** capture falls back to a suitable 720p format without failing camera start solely for that reason
22
23#### Scenario: User locks 720p
24
25- **WHEN** video quality is set to 720p and a higher camera format is available
26- **THEN** capture stays at or below 720p
27
28### Requirement: Send capabilities match capture ceiling
29
30After the local camera size for sending is known, the client SHALL advertise max video send capabilities whose width and height reflect that capture size (up to the active quality ceiling), so the meeting media path can request layers up to that size.
31
32#### Scenario: 1080p capture is advertised
33
34- **WHEN** the outbound camera frame size is 1920×1080
35- **THEN** the send-capabilities update reports max width and height of at least 1920 on the largest side consistent with that frame
36
37### Requirement: Stage receive requests use 1080p-class limits when allowed
38
39For non-screen camera tiles shown as stage detail, the client SHALL request receive limits at 1080p-class macroblock and throughput budgets when the active quality ceiling is Auto or 1080p. When the ceiling is 720p, stage requests SHALL remain at 720p-class budgets. Small gallery tiles and screen-share receive limits SHALL keep their existing budgets.
40
41#### Scenario: Stage at Auto or 1080p
42
43- **WHEN** the user is subscribed to a participant camera on the stage and video quality is Auto or 1080p
44- **THEN** the stage receive request uses 1080p-class `max-fs` / `max-mbps` budgets (same order of magnitude as today’s screen-share camera request, not the previous 720p stage budget)
45
46#### Scenario: Stage locked to 720p
47
48- **WHEN** video quality is 720p and the user is subscribed to a stage camera tile
49- **THEN** the stage receive request uses 720p-class budgets
50
51### Requirement: Video quality setting is user-visible and persistent
52
53The product SHALL expose a video quality choice of Auto, 720p, and 1080p in the call/device camera controls, persist the choice across app restarts, and apply it to new captures and new stage subscriptions. Changing the setting while a call is active SHALL take effect for subsequent capture restarts and subsequent stage request updates without requiring an app relaunch.
54
55#### Scenario: Persist across restart
56
57- **WHEN** the user selects 1080p and later restarts the app
58- **THEN** video quality remains 1080p
59
60#### Scenario: Default is Auto
61
62- **WHEN** no prior video quality choice exists
63- **THEN** the effective choice is Auto