BlueGit

ict rusty-teams

Merge pull request #18: fix(calling): 1:1 media negotiation and 30 fps camera capture

metis Daniel Däschle · pushed by metis

Authored 2026-11-13 · 2 weeks ago

Hash
76a97dccf30ad47d695219130951ca1e697c2fd1
7 files changed +862 −209
crates/app-call-model/src/preview.rs +5 −2
@@ -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};
@@ -47,7 +47,7 @@ impl CameraPreview {
47 47 (preview, receiver)
48 48 }
49 49
50 pub fn start(&mut self, choice: &DeviceChoice) {
50 pub fn start(&mut self, choice: &DeviceChoice, quality: calling::VideoQuality) {
51 51 self.release_capture();
52 52 *self.failure.lock().expect("preview failure lock") = None;
53 53 self.frames.store(0, Ordering::Relaxed);
@@ -59,7 +59,10 @@ impl CameraPreview {
59 59 let mirror = self.blur.clone();
60 60 let started = start_camera(
61 61 choice,
62 quality,
62 63 self.blur.clone(),
64 CameraCaptureStats::new(),
65 |_label| {},
63 66 move |buffer| {
64 67 frames.fetch_add(1, Ordering::Relaxed);
65 68 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};
@@ -47,7 +47,7 @@ impl CameraPreview {
47 (preview, receiver)
47 (preview, receiver)
48 }
48 }
49
49
50 pub fn start(&mut self, choice: &DeviceChoice) {
50 pub fn start(&mut self, choice: &DeviceChoice, quality: calling::VideoQuality) {
51 self.release_capture();
51 self.release_capture();
52 *self.failure.lock().expect("preview failure lock") = None;
52 *self.failure.lock().expect("preview failure lock") = None;
53 self.frames.store(0, Ordering::Relaxed);
53 self.frames.store(0, Ordering::Relaxed);
@@ -59,7 +59,10 @@ impl CameraPreview {
59 let mirror = self.blur.clone();
59 let mirror = self.blur.clone();
60 let started = start_camera(
60 let started = start_camera(
61 choice,
61 choice,
62 quality,
62 self.blur.clone(),
63 self.blur.clone(),
64 CameraCaptureStats::new(),
65 |_label| {},
63 move |buffer| {
66 move |buffer| {
64 frames.fetch_add(1, Ordering::Relaxed);
67 frames.fetch_add(1, Ordering::Relaxed);
65 if let Some(mut picture) = picture_from_i420(buffer, PREVIEW_MAX_WIDTH) {
68 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 +200 −81
@@ -47,6 +47,24 @@ use crate::hold::{
47 47 use crate::meeting_options::{self, OptionWrite};
48 48 use crate::mic_processing::MicSettings;
49 49 use crate::mute::{MuteCommand, MuteEffect};
50 use crate::notices::{
51 ADMIT_ALL_FAILED_NOTICE, ADMIT_FAILED_NOTICE, ATTENDEE_SETTINGS_FAILED_NOTICE,
52 BACKGROUND_IMAGE_FAILED_NOTICE, CALL_TRANSFERRED_NOTICE, CAMERA_RESTART_NOTICE,
53 CAMERA_SETTING_FAILED_NOTICE, CAMERA_START_NOTICE, CAPTION_LANGUAGE_FAILED_NOTICE,
54 CAPTIONS_JOIN_FAILED_NOTICE, CAPTIONS_START_FAILED_NOTICE, CHANGE_ROLE_FAILED_NOTICE,
55 CHANGE_RUNNING_NOTICE, CONFIRM_RECORDING_FAILED_NOTICE, CONSENT_FIRST_NOTICE,
56 DENY_FAILED_NOTICE, HOLD_CHANGE_FAILED_NOTICE, HOLD_FAILED_NOTICE, INVITE_PERSON_FAILED_NOTICE,
57 LOWER_ALL_HANDS_FAILED_NOTICE, LOWER_HAND_FAILED_NOTICE, LOWER_THAT_HAND_FAILED_NOTICE,
58 MEETING_LOCK_FAILED_NOTICE, MIC_SETTING_FAILED_NOTICE, MUTE_ALL_FAILED_NOTICE,
59 MUTE_PARTICIPANT_FAILED_NOTICE, NOT_CONNECTED_FOR_VIDEO, ON_HOLD_NOTICE,
60 RAISE_HAND_FAILED_NOTICE, REACTION_FAILED_NOTICE, RECORDING_JOIN_FAILED_NOTICE,
61 RECORDING_NOT_STARTED_NOTICE, RECORDING_START_FAILED_NOTICE, RECORDING_STOP_FAILED_NOTICE,
62 REMOVE_PARTICIPANT_FAILED_NOTICE, RESUME_FAILED_NOTICE, SHARE_QUEUED_NOTICE,
63 SHARE_REFUSED_NOTICE, SHARING_START_NOTICE, SPOTLIGHT_FAILED_NOTICE,
64 STOP_SPOTLIGHT_FAILED_NOTICE, TRANSFER_CALL_FAILED_NOTICE, TRANSFER_FAILED_NOTICE,
65 TRANSFER_NOT_ALLOWED_NOTICE, TRANSFERRING_NOTICE, VIDEO_FAILED_NOTICE,
66 WHITEBOARD_OPEN_FAILED_NOTICE, WHITEBOARDS_MEETINGS_ONLY_NOTICE, notice_with_detail,
67 };
50 68 use crate::organizer::{MeetingCapability, Modality, StateStep, Target, modality_steps};
51 69 use crate::outcome::{embedded_end, failed_participant_count, outcome_summary};
52 70 use crate::push::CallNotification;
@@ -54,7 +72,10 @@ use crate::recording::{Consent, RecordingPlan, RecordingStatus};
54 72 use crate::relay::{DEFAULT_RELAY_HOST, RelayGrant};
55 73 use crate::renegotiation::{MediaAction, MediaNegotiator, MediaPath, RejectedOffer};
56 74 use crate::roster::{Roster, direct_roster};
57 use crate::screen::{ShareKind, ShareSource, list_share_sources, share_thumbnail};
75 use crate::screen::{
76 ShareKind, SharePicker, ShareSource, current_share_picker, list_share_sources,
77 share_sources_for_menu, share_thumbnail,
78 };
58 79 use crate::sdp::{
59 80 LineRole, OfferPlan, RemoteOffer, SignaledOffer, from_teams_offer, stream_lines,
60 81 to_browser_answer, to_teams_answer, to_teams_offer,
@@ -105,6 +126,8 @@ const HEALTH_EVERY_TICKS: u32 = TICKS_PER_SECOND * 2;
105 126 const BOT_PREFIX: &str = "28:";
106 127 const RECORDING_START_LIMIT: Duration = Duration::from_secs(40);
107 128 const SAME_PEER_ANSWER_LIMIT: Duration = Duration::from_secs(40);
129 /// Teams sometimes answers a few seconds after the soft limit; keep the local offer until this grace ends.
130 const SAME_PEER_LATE_GRACE: Duration = Duration::from_secs(15);
108 131 const GATHERING_LIMIT: Duration = Duration::from_secs(5);
109 132 const RELAY_SETTLE: Duration = Duration::from_millis(200);
110 133 const GATHERING_POLL: Duration = Duration::from_millis(50);
@@ -113,7 +136,6 @@ const GLARE_RESEND_LIMIT: Duration = Duration::from_secs(3);
113 136 const GLARE_CODE: i64 = 491;
114 137 const RETARGET_WAIT: Duration = Duration::from_secs(20);
115 138 const CAMERA_STREAM: &str = "camera";
116 const CONSENT_FIRST_NOTICE: &str = "Accept the recording notice first";
117 139
118 140 #[derive(Debug, Clone)]
119 141 pub struct CallOptions {
@@ -1009,6 +1031,7 @@ async fn drive(
1009 1031 control.video.clone(),
1010 1032 control.updates(),
1011 1033 );
1034 local_video.attach_timeline(timeline.clone());
1012 1035 let mut camera_choice = options.camera.clone();
1013 1036 if options.start_camera {
1014 1037 match local_video.preview_camera(&camera_choice) {
@@ -1018,6 +1041,7 @@ async fn drive(
1018 1041 }
1019 1042 let mut media_description_request = 1u32;
1020 1043 refresh_cameras(control.updates(), options.video, timeline.clone());
1044 control.send(CallUpdate::SharePicker(current_share_picker()));
1021 1045 refresh_share_sources(control.updates(), options.video, false);
1022 1046
1023 1047 let wants_data_channel =
@@ -1230,8 +1254,9 @@ async fn drive(
1230 1254 }) {
1231 1255 Some(Ok(())) => match local_video.start_camera(&camera_choice) {
1232 1256 Ok(()) => sending_camera = true,
1233 Err(error) => control.send(CallUpdate::Notice(format!(
1234 "Camera could not start: {error}"
1257 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(
1258 CAMERA_START_NOTICE,
1259 error,
1235 1260 ))),
1236 1261 },
1237 1262 Some(Err(error)) => {
@@ -1363,6 +1388,7 @@ async fn drive(
1363 1388 let mut send_requests = RequestFilter::default();
1364 1389 let mut send_capabilities = SendCapabilityReporter::default();
1365 1390 let mut same_peer_deadline: Option<Instant> = None;
1391 let mut same_peer_grace_until: Option<Instant> = None;
1366 1392 let mut meeting_chat = conversation.chat_thread.clone();
1367 1393 if let Some(thread) = &meeting_chat {
1368 1394 control.send(CallUpdate::MeetingChat(thread.clone()));
@@ -1375,6 +1401,7 @@ async fn drive(
1375 1401 }
1376 1402 let mut start_camera_pending = options.start_camera;
1377 1403 let mut share_pending: Option<ShareSource> = None;
1404 let mut portal_pending: Option<ShareKind> = None;
1378 1405 let mut glare_resend: Option<GlareResend> = None;
1379 1406 let mut deferred_changes: Vec<Change> = Vec::new();
1380 1407 let mut remote_direct_share: Option<String> = None;
@@ -1389,6 +1416,11 @@ async fn drive(
1389 1416 {
1390 1417 control.defer(CallCommand::StartShare(source));
1391 1418 }
1419 if video_possible(remote_set, layout, negotiator.path())
1420 && let Some(kind) = portal_pending.take()
1421 {
1422 control.defer(CallCommand::StartPortalShare(kind));
1423 }
1392 1424 if next.as_ref().is_some_and(|pending| {
1393 1425 pending.connected && (pending.offered.is_some() || pending.retargeted)
1394 1426 }) && let Some(pending) = next.take()
@@ -1577,6 +1609,7 @@ async fn drive(
1577 1609 && let Some(pending) = same_peer.take()
1578 1610 {
1579 1611 same_peer_deadline = None;
1612 same_peer_grace_until = None;
1580 1613 let applied = match pending.change {
1581 1614 Change::Hold(_) => apply_hold_answer(&current.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await,
1582 1615 Change::Camera(_) | Change::Share(_) => apply_answer(&current.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await,
@@ -1596,7 +1629,7 @@ async fn drive(
1596 1629 Change::Share(true) if !answer.from_mixer && !local_video.share_sending() => {
1597 1630 local_video.stop_share();
1598 1631 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);
1599 control.send(CallUpdate::LocalShare(None));
1632 clear_share(control);
1600 1633 control.send(CallUpdate::Notice(SHARE_REFUSED_NOTICE.into()));
1601 1634 }
1602 1635 Change::Share(_) => {}
@@ -1657,6 +1690,7 @@ async fn drive(
1657 1690 && let Some(pending) = same_peer.take()
1658 1691 {
1659 1692 same_peer_deadline = None;
1693 same_peer_grace_until = None;
1660 1694 negotiator.same_peer_offer_failed();
1661 1695 rollback_offer(&current.peer).await;
1662 1696 timeline.record("glare", "the remote offer is answered first, ours goes out again after");
@@ -1668,6 +1702,7 @@ async fn drive(
1668 1702 MediaAction::AnswerOnNewPeer => {
1669 1703 if let Some(pending) = same_peer.take() {
1670 1704 same_peer_deadline = None;
1705 same_peer_grace_until = None;
1671 1706 timeline.record("same-peer offer", "superseded by the escalation offer");
1672 1707 rollback_offer(&current.peer).await;
1673 1708 defer_to_new_peer(pending.change, &mut deferred_changes, &mut local_video, control);
@@ -1826,13 +1861,15 @@ async fn drive(
1826 1861 recording_flow.failed();
1827 1862 recording_deadline = None;
1828 1863 control.send(CallUpdate::RecordingPending(false));
1829 control.send(CallUpdate::Notice("The recording service could not join".into()));
1864 control.send(CallUpdate::Notice(RECORDING_JOIN_FAILED_NOTICE.into()));
1830 1865 }
1831 1866 if caption_flow.wanted() && roster.caption_bot().is_none() {
1832 1867 timeline.record("caption bot failed", "addParticipantFailure");
1833 1868 caption_flow.failed();
1834 1869 caption_deadline = None;
1835 control.send(CallUpdate::Captions(CaptionState::Failed("The captions service could not join".into())));
1870 control.send(CallUpdate::Captions(CaptionState::Failed(
1871 CAPTIONS_JOIN_FAILED_NOTICE.into(),
1872 )));
1836 1873 }
1837 1874 }
1838 1875 Ok(CallEvent::ConversationUpdate(body)) => {
@@ -1902,14 +1939,14 @@ async fn drive(
1902 1939 completed if completed.succeeded() => {
1903 1940 timeline.record("transfer", "completed");
1904 1941 control.send(CallUpdate::TransferResult { succeeded: true });
1905 control.send(CallUpdate::Notice("Call transferred".into()));
1942 control.send(CallUpdate::Notice(CALL_TRANSFERRED_NOTICE.into()));
1906 1943 advance(state, CallSignal::LocalLeave, control);
1907 1944 break;
1908 1945 }
1909 1946 TransferEvent::Completed { code, sub_code } => {
1910 1947 timeline.record("transfer failed", format!("code {code} subCode {sub_code}"));
1911 1948 control.send(CallUpdate::TransferResult { succeeded: false });
1912 control.send(CallUpdate::Notice("The transfer did not go through".into()));
1949 control.send(CallUpdate::Notice(TRANSFER_FAILED_NOTICE.into()));
1913 1950 }
1914 1951 }
1915 1952 }
@@ -1968,6 +2005,7 @@ async fn drive(
1968 2005 Ok(CallEvent::Rejection(body)) => match negotiator.on_rejection() {
1969 2006 RejectedOffer::SamePeer => {
1970 2007 same_peer_deadline = None;
2008 same_peer_grace_until = None;
1971 2009 if let Some(pending) = same_peer.take() {
1972 2010 rollback_offer(&current.peer).await;
1973 2011 if is_glare_rejection(&body) {
@@ -2187,6 +2225,7 @@ async fn drive(
2187 2225 timeline.record_sdp("local offer", &signaled.sdp);
2188 2226 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(true), reply_tags });
2189 2227 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2228 same_peer_grace_until = None;
2190 2229 }
2191 2230 Err(error) => {
2192 2231 timeline.record("camera offer failed", error.to_string());
@@ -2198,7 +2237,7 @@ async fn drive(
2198 2237 control.send(CallUpdate::Camera(true));
2199 2238 tell_media_descriptions(&remote, &media_links, MediaDescription::camera(true), &mut media_description_request, timeline);
2200 2239 }
2201 Err(error) => control.send(CallUpdate::Notice(format!("Camera could not start: {error}"))),
2240 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(CAMERA_START_NOTICE, error))),
2202 2241 }
2203 2242 } else if direct && (same_peer.is_some() || glare_resend.is_some()) {
2204 2243 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
@@ -2209,6 +2248,7 @@ async fn drive(
2209 2248 timeline.record_sdp("local offer", &signaled.sdp);
2210 2249 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(false), reply_tags });
2211 2250 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2251 same_peer_grace_until = None;
2212 2252 }
2213 2253 Err(error) => {
2214 2254 timeline.record("camera offer failed", error.to_string());
@@ -2226,11 +2266,59 @@ async fn drive(
2226 2266 if local_video.camera_previewing()
2227 2267 && let Err(error) = local_video.preview_camera(&camera_choice)
2228 2268 {
2229 control.send(CallUpdate::Notice(format!("Camera could not start: {error}")));
2269 control.send(CallUpdate::Notice(notice_with_detail(CAMERA_START_NOTICE, error)));
2230 2270 } else if local_video.camera_on()
2231 2271 && let Err(error) = local_video.start_camera(&camera_choice)
2232 2272 {
2233 control.send(CallUpdate::Notice(format!("Camera could not start: {error}")));
2273 control.send(CallUpdate::Notice(notice_with_detail(CAMERA_START_NOTICE, error)));
2274 }
2275 }
2276 Some(CallCommand::SetVideoQuality(quality)) => {
2277 local_video.set_video_quality(quality);
2278 if let Err(error) = local_video.refresh_camera_capture(&camera_choice) {
2279 control.send(CallUpdate::Notice(notice_with_detail(CAMERA_RESTART_NOTICE, error)));
2280 }
2281 if video.set_video_quality(quality) {
2282 send_receive_change(control, video.reselect(&roster));
2283 }
2284 }
2285 Some(CallCommand::StartPortalShare(kind)) => {
2286 let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;
2287 if !remote_set {
2288 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
2289 } else if local_hold {
2290 control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into()));
2291 } else if direct && !local_video.sharing() && (same_peer.is_some() || glare_resend.is_some()) {
2292 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
2293 } else if direct
2294 && !local_video.sharing()
2295 && !local_video.has_share_line()
2296 && let Err(error) = attach_share_line(&current.peer, &factory, &mut local_video, direct_video_mid.as_deref())
2297 {
2298 control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error)));
2299 } else if !local_video.sharing() && !video_possible(remote_set, layout, negotiator.path()) {
2300 if next.is_none() && negotiator.begin_conference_upgrade() {
2301 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;
2302 next = pending.or(next);
2303 }
2304 if next.is_some() {
2305 portal_pending = Some(kind);
2306 control.send(CallUpdate::Notice(SHARE_QUEUED_NOTICE.into()));
2307 } else {
2308 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
2309 }
2310 } else if let Err(error) = local_video.open_portal(kind, control.command_sender()) {
2311 control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error)));
2312 }
2313 }
2314 Some(CallCommand::FinishPortalShare { source, generation }) => {
2315 if local_video.accept_portal(generation) {
2316 control.defer(CallCommand::StartShare(source));
2317 }
2318 }
2319 Some(CallCommand::AbandonPortalShare) => {
2320 if local_video.portal_is_open() {
2321 local_video.stop_share();
2234 2322 }
2235 2323 }
2236 2324 Some(CallCommand::StartShare(source)) => {
@@ -2239,10 +2327,10 @@ async fn drive(
2239 2327 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
2240 2328 } else if local_hold {
2241 2329 control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into()));
2242 } else if direct && local_video.sharing() {
2330 } else if direct && local_video.share_sending() {
2243 2331 match local_video.start_share(&source) {
2244 Ok(()) => control.send(CallUpdate::LocalShare(Some(source.label()))),
2245 Err(error) => control.send(CallUpdate::Notice(format!("Sharing could not start: {error}"))),
2332 Ok(()) => announce_share(control, &source),
2333 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))),
2246 2334 }
2247 2335 } else if direct && (same_peer.is_some() || glare_resend.is_some()) {
2248 2336 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
@@ -2250,17 +2338,18 @@ async fn drive(
2250 2338 && !local_video.has_share_line()
2251 2339 && let Err(error) = attach_share_line(&current.peer, &factory, &mut local_video, direct_video_mid.as_deref())
2252 2340 {
2253 control.send(CallUpdate::Notice(format!("Sharing could not start: {error}")));
2341 control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error)));
2254 2342 } else if direct {
2255 2343 match local_video.start_share(&source) {
2256 2344 Ok(()) => {
2257 control.send(CallUpdate::LocalShare(Some(source.label())));
2345 announce_share(control, &source);
2258 2346 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);
2259 2347 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 {
2260 2348 Ok((browser_offer, signaled, reply_tags)) => {
2261 2349 timeline.record_sdp("local offer", &signaled.sdp);
2262 2350 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(true), reply_tags });
2263 2351 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2352 same_peer_grace_until = None;
2264 2353 }
2265 2354 Err(error) => {
2266 2355 timeline.record("share offer failed", error.to_string());
@@ -2268,7 +2357,7 @@ async fn drive(
2268 2357 }
2269 2358 }
2270 2359 }
2271 Err(error) => control.send(CallUpdate::Notice(format!("Sharing could not start: {error}"))),
2360 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))),
2272 2361 }
2273 2362 } else if !video_possible(remote_set, layout, negotiator.path()) {
2274 2363 if next.is_none() && negotiator.begin_conference_upgrade() {
@@ -2284,35 +2373,39 @@ async fn drive(
2284 2373 } else {
2285 2374 match local_video.start_share(&source) {
2286 2375 Ok(()) => {
2287 control.send(CallUpdate::LocalShare(Some(source.label())));
2376 announce_share(control, &source);
2288 2377 tell_media_descriptions(&remote, &media_links, MediaDescription::share(true), &mut media_description_request, timeline);
2289 2378 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);
2290 2379 }
2291 Err(error) => control.send(CallUpdate::Notice(format!("Sharing could not start: {error}"))),
2380 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))),
2292 2381 }
2293 2382 }
2294 2383 }
2295 2384 Some(CallCommand::StopShare) => {
2296 2385 let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;
2297 2386 share_pending = None;
2298 if direct && local_video.sharing() && (same_peer.is_some() || glare_resend.is_some()) {
2387 portal_pending = None;
2388 if local_video.portal_is_open() {
2389 local_video.stop_share();
2390 } else if direct && local_video.sharing() && (same_peer.is_some() || glare_resend.is_some()) {
2299 2391 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
2300 2392 } else if direct && local_video.sharing() {
2301 2393 local_video.stop_share();
2302 control.send(CallUpdate::LocalShare(None));
2394 clear_share(control);
2303 2395 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);
2304 2396 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 {
2305 2397 Ok((browser_offer, signaled, reply_tags)) => {
2306 2398 timeline.record_sdp("local offer", &signaled.sdp);
2307 2399 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(false), reply_tags });
2308 2400 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2401 same_peer_grace_until = None;
2309 2402 }
2310 2403 Err(error) => timeline.record("share offer failed", error.to_string()),
2311 2404 }
2312 2405 } else if local_video.sharing() {
2313 2406 local_video.stop_share();
2314 2407 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);
2315 control.send(CallUpdate::LocalShare(None));
2408 clear_share(control);
2316 2409 tell_media_descriptions(&remote, &media_links, MediaDescription::share(false), &mut media_description_request, timeline);
2317 2410 }
2318 2411 }
@@ -2329,7 +2422,7 @@ async fn drive(
2329 2422 Err(error) => {
2330 2423 timeline.record("raise hand failed", error.to_string());
2331 2424 control.send(CallUpdate::OwnHand(None));
2332 control.send(CallUpdate::Notice("Could not raise your hand".into()));
2425 control.send(CallUpdate::Notice(RAISE_HAND_FAILED_NOTICE.into()));
2333 2426 }
2334 2427 },
2335 2428 Some(CallCommand::SetHand(false)) => {
@@ -2340,7 +2433,7 @@ async fn drive(
2340 2433 && let Err(error) = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await
2341 2434 {
2342 2435 timeline.record("lower hand failed", error.to_string());
2343 control.send(CallUpdate::Notice("Could not lower your hand".into()));
2436 control.send(CallUpdate::Notice(LOWER_HAND_FAILED_NOTICE.into()));
2344 2437 }
2345 2438 }
2346 2439 Some(CallCommand::LowerHand { mri }) => {
@@ -2349,18 +2442,18 @@ async fn drive(
2349 2442 && let Err(error) = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await
2350 2443 {
2351 2444 timeline.record("lower hand failed", error.to_string());
2352 control.send(CallUpdate::Notice("Could not lower that hand".into()));
2445 control.send(CallUpdate::Notice(LOWER_THAT_HAND_FAILED_NOTICE.into()));
2353 2446 }
2354 2447 }
2355 2448 Some(CallCommand::LowerAllHands) => {
2356 2449 if let Err(error) = remote.signaling.lower_all_hands(&remote.conversation, &remote.participant).await {
2357 2450 timeline.record("lower all hands failed", error.to_string());
2358 control.send(CallUpdate::Notice("Could not lower all hands".into()));
2451 control.send(CallUpdate::Notice(LOWER_ALL_HANDS_FAILED_NOTICE.into()));
2359 2452 }
2360 2453 }
2361 2454 Some(CallCommand::Admit { mri }) => {
2362 2455 let result = remote.signaling.admit(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await;
2363 report_organizer_result(result, "admit", "Could not admit that person", control, timeline);
2456 report_organizer_result(result, "admit", ADMIT_FAILED_NOTICE, control, timeline);
2364 2457 }
2365 2458 Some(CallCommand::AdmitAll) => {
2366 2459 let mut result = Ok(202);
@@ -2370,19 +2463,19 @@ async fn drive(
2370 2463 break;
2371 2464 }
2372 2465 }
2373 report_organizer_result(result, "admit all", "Could not admit everyone", control, timeline);
2466 report_organizer_result(result, "admit all", ADMIT_ALL_FAILED_NOTICE, control, timeline);
2374 2467 }
2375 2468 Some(CallCommand::Deny { mri }) => {
2376 2469 let result = remote.signaling.remove_participant(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await;
2377 report_organizer_result(result, "deny", "Could not deny that person", control, timeline);
2470 report_organizer_result(result, "deny", DENY_FAILED_NOTICE, control, timeline);
2378 2471 }
2379 2472 Some(CallCommand::RemoveParticipant { mri }) => {
2380 2473 let result = remote.signaling.remove_participant(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await;
2381 report_organizer_result(result, "remove participant", "Could not remove that person", control, timeline);
2474 report_organizer_result(result, "remove participant", REMOVE_PARTICIPANT_FAILED_NOTICE, control, timeline);
2382 2475 }
2383 2476 Some(CallCommand::MuteParticipant { mri }) => {
2384 2477 let result = remote.signaling.mute_participant(&remote.conversation, &remote.participant, &mri).await;
2385 report_organizer_result(result, "mute participant", "Could not mute that person", control, timeline);
2478 report_organizer_result(result, "mute participant", MUTE_PARTICIPANT_FAILED_NOTICE, control, timeline);
2386 2479 }
2387 2480 Some(CallCommand::MuteAll) => {
2388 2481 let others: Vec<String> = roster
@@ -2392,7 +2485,7 @@ async fn drive(
2392 2485 .map(|member| member.mri.clone())
2393 2486 .collect();
2394 2487 let result = remote.signaling.mute_everyone(&remote.conversation, &remote.participant, &others).await;
2395 report_organizer_result(result, "mute all", "Could not mute everyone", control, timeline);
2488 report_organizer_result(result, "mute all", MUTE_ALL_FAILED_NOTICE, control, timeline);
2396 2489 }
2397 2490 Some(CallCommand::SetLock(locked)) => {
2398 2491 let result = remote.signaling.set_lock(&remote.conversation, &remote.participant, locked).await;
@@ -2400,11 +2493,11 @@ async fn drive(
2400 2493 capability.locked = locked;
2401 2494 control.send(CallUpdate::Capability(capability));
2402 2495 }
2403 report_organizer_result(result, "lock meeting", "Could not change the meeting lock", control, timeline);
2496 report_organizer_result(result, "lock meeting", MEETING_LOCK_FAILED_NOTICE, control, timeline);
2404 2497 }
2405 2498 Some(CallCommand::SetRole { mri, role }) => {
2406 2499 let result = remote.signaling.change_role(&remote.conversation, &remote.participant, &mri, role).await;
2407 report_organizer_result(result, "change role", "Could not change that role", control, timeline);
2500 report_organizer_result(result, "change role", CHANGE_ROLE_FAILED_NOTICE, control, timeline);
2408 2501 }
2409 2502 Some(CallCommand::SetAttendeeModality { mri, modality, allowed }) => {
2410 2503 let limits = roster.entries().into_iter().find(|entry| entry.mri == mri).map(|entry| entry.limits).unwrap_or_default();
@@ -2418,7 +2511,11 @@ async fn drive(
2418 2511 break;
2419 2512 }
2420 2513 }
2421 let notice = if modality == Modality::Mic { "Could not change that microphone setting" } else { "Could not change that camera setting" };
2514 let notice = if modality == Modality::Mic {
2515 MIC_SETTING_FAILED_NOTICE
2516 } else {
2517 CAMERA_SETTING_FAILED_NOTICE
2518 };
2422 2519 report_organizer_result(result, "attendee modality", notice, control, timeline);
2423 2520 }
2424 2521 Some(CallCommand::SetAttendeeRestrictions { mic_off, camera_off }) => {
@@ -2431,12 +2528,12 @@ async fn drive(
2431 2528 capability.attendee_camera_off = camera_off;
2432 2529 control.send(CallUpdate::Capability(capability));
2433 2530 }
2434 report_organizer_result(result, "attendee restrictions", "Could not change the attendee settings", control, timeline);
2531 report_organizer_result(result, "attendee restrictions", ATTENDEE_SETTINGS_FAILED_NOTICE, control, timeline);
2435 2532 }
2436 2533 Some(CallCommand::Invite { callees, group_thread }) => {
2437 2534 let thread = group_thread.or_else(|| meeting_chat.clone());
2438 2535 let result = remote.signaling.add_participants(&remote.conversation, &remote.participant, &callees, thread.as_deref(), meeting_target.as_ref(), &links).await;
2439 report_organizer_result(result, "invite", "Could not invite that person", control, timeline);
2536 report_organizer_result(result, "invite", INVITE_PERSON_FAILED_NOTICE, control, timeline);
2440 2537 }
2441 2538 Some(CallCommand::LoadMeetingOptions) => {
2442 2539 let update = match &meeting_target {
@@ -2460,13 +2557,13 @@ async fn drive(
2460 2557 }
2461 2558 Some(CallCommand::Spotlight { mri }) => {
2462 2559 let result = remote.signaling.spotlight(&remote.conversation, &remote.participant, &mri).await;
2463 report_organizer_result(result, "spotlight", "Could not spotlight that person", control, timeline);
2560 report_organizer_result(result, "spotlight", SPOTLIGHT_FAILED_NOTICE, control, timeline);
2464 2561 }
2465 2562 Some(CallCommand::StopSpotlight { mri }) => {
2466 2563 let state_ids: Vec<String> = roster.spotlight_of(&mri).map(|spotlight| spotlight.state_id.clone()).into_iter().collect();
2467 2564 if !state_ids.is_empty() {
2468 2565 let result = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await.map(|()| 200);
2469 report_organizer_result(result, "stop spotlight", "Could not stop the spotlight", control, timeline);
2566 report_organizer_result(result, "stop spotlight", STOP_SPOTLIGHT_FAILED_NOTICE, control, timeline);
2470 2567 }
2471 2568 }
2472 2569 Some(CallCommand::SetCaptions(on)) => {
@@ -2505,7 +2602,7 @@ async fn drive(
2505 2602 && let Err(error) = remote.signaling.caption_language_command(&url, &remote.participant, &language).await
2506 2603 {
2507 2604 timeline.record("caption language failed", error.to_string());
2508 control.send(CallUpdate::Notice("Could not change the spoken language".into()));
2605 control.send(CallUpdate::Notice(CAPTION_LANGUAGE_FAILED_NOTICE.into()));
2509 2606 }
2510 2607 }
2511 2608 Some(CallCommand::ConsentToRecording) => {
@@ -2516,7 +2613,7 @@ async fn drive(
2516 2613 }
2517 2614 Err(error) => {
2518 2615 timeline.record("recording consent failed", error.to_string());
2519 control.send(CallUpdate::Notice("Could not confirm the recording notice".into()));
2616 control.send(CallUpdate::Notice(CONFIRM_RECORDING_FAILED_NOTICE.into()));
2520 2617 }
2521 2618 }
2522 2619 }
@@ -2534,32 +2631,40 @@ async fn drive(
2534 2631 timeline.record_sdp("local offer", &signaled.sdp);
2535 2632 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Hold(hold), reply_tags });
2536 2633 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2634 same_peer_grace_until = None;
2537 2635 }
2538 2636 Err(error) => {
2539 2637 timeline.record("hold failed", error.to_string());
2540 control.send(CallUpdate::Notice(if hold { "Could not put the call on hold".into() } else { "Could not resume the call".into() }));
2638 control.send(CallUpdate::Notice(if hold {
2639 HOLD_FAILED_NOTICE.into()
2640 } else {
2641 RESUME_FAILED_NOTICE.into()
2642 }));
2541 2643 }
2542 2644 }
2543 2645 }
2544 2646 Some(CallCommand::Transfer { target, replaces }) => {
2545 2647 let Some(url) = media_links.get("transfer").cloned() else {
2546 2648 control.send(CallUpdate::TransferResult { succeeded: false });
2547 control.send(CallUpdate::Notice("This call cannot be transferred".into()));
2649 control.send(CallUpdate::Notice(TRANSFER_NOT_ALLOWED_NOTICE.into()));
2548 2650 continue;
2549 2651 };
2550 2652 let transfer_target = TransferTarget { mri: &target.mri, replaces: replaces.as_ref() };
2551 2653 match remote.signaling.transfer(&url, &remote.participant, transfer_target, &links).await {
2552 Ok(()) => control.send(CallUpdate::Notice(format!("Transferring to {}...", target.display_name))),
2654 Ok(()) => control.send(CallUpdate::Notice(notice_with_detail(
2655 TRANSFERRING_NOTICE,
2656 target.display_name,
2657 ))),
2553 2658 Err(error) => {
2554 2659 timeline.record("transfer failed", error.to_string());
2555 2660 control.send(CallUpdate::TransferResult { succeeded: false });
2556 control.send(CallUpdate::Notice("Could not transfer the call".into()));
2661 control.send(CallUpdate::Notice(TRANSFER_CALL_FAILED_NOTICE.into()));
2557 2662 }
2558 2663 }
2559 2664 }
2560 2665 Some(CallCommand::OpenWhiteboard { title }) => {
2561 2666 let Some(target) = meeting_target.clone() else {
2562 control.send(CallUpdate::Notice("Whiteboards belong to meetings".into()));
2667 control.send(CallUpdate::Notice(WHITEBOARDS_MEETINGS_ONLY_NOTICE.into()));
2563 2668 continue;
2564 2669 };
2565 2670 let session = inner.session.clone();
@@ -2567,7 +2672,7 @@ async fn drive(
2567 2672 tokio::spawn(async move {
2568 2673 let update = match whiteboard::fetch_board(&session, &target, &title).await {
2569 2674 Ok(url) => CallUpdate::WhiteboardUrl(url),
2570 Err(_) => CallUpdate::Notice("The whiteboard could not be opened".into()),
2675 Err(_) => CallUpdate::Notice(WHITEBOARD_OPEN_FAILED_NOTICE.into()),
2571 2676 };
2572 2677 let _ = updates.send(update);
2573 2678 });
@@ -2594,7 +2699,7 @@ async fn drive(
2594 2699 Some(CallCommand::SendReaction(reaction)) => {
2595 2700 if let Err(error) = remote.signaling.send_reaction(&remote.conversation, &remote.participant, reaction).await {
2596 2701 timeline.record("reaction failed", error.to_string());
2597 control.send(CallUpdate::Notice("Could not send the reaction".into()));
2702 control.send(CallUpdate::Notice(REACTION_FAILED_NOTICE.into()));
2598 2703 }
2599 2704 }
2600 2705 Some(CallCommand::EndMeeting) => {
@@ -2645,12 +2750,13 @@ async fn drive(
2645 2750 recording_flow.failed();
2646 2751 timeline.record("recording", "did not start in time");
2647 2752 control.send(CallUpdate::RecordingPending(false));
2648 control.send(CallUpdate::Notice("The recording did not start".into()));
2753 control.send(CallUpdate::Notice(RECORDING_NOT_STARTED_NOTICE.into()));
2649 2754 }
2650 2755 if layout == Layout::Conference
2651 2756 && let Some(size) = local_video.camera_size()
2652 2757 && let Some(url) = media_links.get("applyChannelParameters").cloned()
2653 && let Some(body) = send_capabilities.body_for(size)
2758 && let Some(body) =
2759 send_capabilities.body_for(size, local_video.video_quality())
2654 2760 {
2655 2761 let signaling = signaling.clone();
2656 2762 let timeline = timeline.clone();
@@ -2746,12 +2852,13 @@ async fn drive(
2746 2852 timeline.record(
2747 2853 "stats",
2748 2854 format!(
2749 "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={:?}{}",
2855 "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={:?}{}{}",
2750 2856 snapshot.inbound_packets, snapshot.inbound_bytes, snapshot.audio_level, snapshot.outbound_packets, snapshot.local_level, snapshot.echo_return_loss_enhancement, snapshot.dtls_state,
2751 2857 snapshot.video.inbound_packets, snapshot.video.inbound_frames_decoded, snapshot.video.inbound_width, snapshot.video.inbound_height,
2752 2858 snapshot.video.outbound_packets, snapshot.video.outbound_frames_encoded, snapshot.video.outbound_width, snapshot.video.outbound_height,
2753 2859 snapshot.video.remote_reports, snapshot.video.remote_round_trip_ms, snapshot.outbound_bytes, snapshot.source_levels, snapshot.video_senders,
2754 snapshot.share_receive.as_ref().filter(|_| snapshot.share_inbound_packets > 0).map(ShareReceive::summary).unwrap_or_default()
2860 snapshot.share_receive.as_ref().filter(|_| snapshot.share_inbound_packets > 0).map(ShareReceive::summary).unwrap_or_default(),
2861 local_video.camera_capture_summary().unwrap_or_default()
2755 2862 ),
2756 2863 );
2757 2864 }
@@ -2796,6 +2903,7 @@ async fn drive(
2796 2903 control.send(CallUpdate::Camera(false));
2797 2904 }
2798 2905 share_pending = None;
2906 portal_pending = None;
2799 2907 settle_failed_escalation(pending.offered.is_none(), layout, &mut negotiator, &mut deferred_changes, &mut local_video, control);
2800 2908 timeline.record("escalation failed", "no answer for the new peer connection in time");
2801 2909 control.send(CallUpdate::Notice(VIDEO_FAILED_NOTICE.into()));
@@ -2826,6 +2934,7 @@ async fn drive(
2826 2934 timeline.record_sdp("local offer", &signaled.sdp);
2827 2935 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: resend.change, reply_tags });
2828 2936 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2937 same_peer_grace_until = None;
2829 2938 }
2830 2939 Err(error) => {
2831 2940 timeline.record("offer after glare failed", error.to_string());
@@ -2836,6 +2945,16 @@ async fn drive(
2836 2945 }
2837 2946 _ = sleep_until(same_peer_deadline.unwrap_or_else(far_future)), if same_peer_deadline.is_some() => {
2838 2947 same_peer_deadline = None;
2948 if same_peer.is_some() {
2949 same_peer_grace_until = Some(Instant::now() + SAME_PEER_LATE_GRACE);
2950 timeline.record(
2951 "same-peer offer",
2952 "no answer yet, waiting a little longer",
2953 );
2954 }
2955 }
2956 _ = sleep_until(same_peer_grace_until.unwrap_or_else(far_future)), if same_peer_grace_until.is_some() => {
2957 same_peer_grace_until = None;
2839 2958 if let Some(pending) = same_peer.take() {
2840 2959 timeline.record("same-peer offer", "no answer in time");
2841 2960 negotiator.same_peer_offer_failed();
@@ -3041,13 +3160,6 @@ fn negotiate_video(
3041 3160 send_receive_change(control, video.reselect(roster));
3042 3161 }
3043 3162
3044 const NOT_CONNECTED_FOR_VIDEO: &str = "Video starts once the call is connected";
3045 const ON_HOLD_NOTICE: &str = "Resume the call first";
3046 const CHANGE_RUNNING_NOTICE: &str = "Another change is still running, try again in a moment";
3047 const VIDEO_FAILED_NOTICE: &str = "Video could not start, the call stays audio only";
3048 const SHARE_QUEUED_NOTICE: &str = "Sharing starts in a moment";
3049 const SHARE_REFUSED_NOTICE: &str = "The other side did not accept the screen share";
3050
3051 3163 async fn camera_devices(mode: VideoMode) -> Vec<CameraDevice> {
3052 3164 match mode {
3053 3165 VideoMode::Pattern => vec![CameraDevice {
@@ -3085,12 +3197,23 @@ const SHARE_THUMBNAIL_WINDOWS: usize = 12;
3085 3197 const SHARE_THUMBNAIL_WIDTH: u32 = 320;
3086 3198 const SHARE_THUMBNAIL_HEIGHT: u32 = 180;
3087 3199
3200 fn announce_share(control: &CallControl, source: &ShareSource) {
3201 control.send(CallUpdate::ShareKind(Some(source.kind)));
3202 control.send(CallUpdate::LocalShare(Some(source.label())));
3203 }
3204
3205 fn clear_share(control: &CallControl) {
3206 control.send(CallUpdate::ShareKind(None));
3207 control.send(CallUpdate::LocalShare(None));
3208 }
3209
3088 3210 fn refresh_share_sources(
3089 3211 updates: mpsc::UnboundedSender<CallUpdate>,
3090 3212 mode: VideoMode,
3091 3213 with_thumbnails: bool,
3092 3214 ) {
3093 3215 tokio::spawn(async move {
3216 let picker = current_share_picker();
3094 3217 let sources = match mode {
3095 3218 VideoMode::Pattern => vec![
3096 3219 ShareSource {
@@ -3105,12 +3228,14 @@ fn refresh_share_sources(
3105 3228 },
3106 3229 ],
3107 3230 VideoMode::Off => Vec::new(),
3231 VideoMode::Platform if picker == SharePicker::Portal => Vec::new(),
3108 3232 VideoMode::Platform => tokio::task::spawn_blocking(list_share_sources)
3109 3233 .await
3110 3234 .unwrap_or_default(),
3111 3235 };
3236 let sources = share_sources_for_menu(picker, sources);
3112 3237 let _ = updates.send(CallUpdate::ShareSources(sources.clone()));
3113 if !with_thumbnails {
3238 if picker == SharePicker::Portal || !with_thumbnails {
3114 3239 return;
3115 3240 }
3116 3241 let wanted: Vec<ShareSource> = sources
@@ -3503,7 +3628,7 @@ fn settle_failed_escalation(
3503 3628 fn drop_local_media(local_video: &mut LocalVideo, control: &CallControl) {
3504 3629 if local_video.sharing() {
3505 3630 local_video.stop_share();
3506 control.send(CallUpdate::LocalShare(None));
3631 clear_share(control);
3507 3632 }
3508 3633 if local_video.camera_on() {
3509 3634 local_video.stop_camera();
@@ -3520,11 +3645,14 @@ fn undo_change(change: Change, local_video: &mut LocalVideo, control: &CallContr
3520 3645 Change::Camera(false) => control.send(CallUpdate::Camera(false)),
3521 3646 Change::Share(true) => {
3522 3647 local_video.stop_share();
3523 control.send(CallUpdate::LocalShare(None));
3524 control.send(CallUpdate::Notice("Sharing could not start".into()));
3648 clear_share(control);
3649 control.send(CallUpdate::Notice(notice_with_detail(
3650 SHARING_START_NOTICE,
3651 "",
3652 )));
3525 3653 }
3526 3654 Change::Share(false) => {}
3527 Change::Hold(_) => control.send(CallUpdate::Notice("The hold did not go through".into())),
3655 Change::Hold(_) => control.send(CallUpdate::Notice(HOLD_CHANGE_FAILED_NOTICE.into())),
3528 3656 }
3529 3657 }
3530 3658
@@ -3564,9 +3692,7 @@ async fn apply_background(
3564 3692 Ok(Ok(picture)) => local_video.set_background(true, Some(Arc::new(picture))),
3565 3693 Ok(Err(error)) => {
3566 3694 timeline.record("background image failed", error.to_string());
3567 control.send(CallUpdate::Notice(
3568 "That background image could not be used".into(),
3569 ));
3695 control.send(CallUpdate::Notice(BACKGROUND_IMAGE_FAILED_NOTICE.into()));
3570 3696 }
3571 3697 Err(_) => {}
3572 3698 }
@@ -3609,13 +3735,13 @@ fn recorder_busy(error: &Error) -> bool {
3609 3735 fn report_organizer_result(
3610 3736 result: Result<u16>,
3611 3737 label: &str,
3612 notice: &str,
3738 notice: &'static str,
3613 3739 control: &CallControl,
3614 3740 timeline: &Timeline,
3615 3741 ) {
3616 3742 if let Err(error) = &result {
3617 3743 timeline.record(format!("{label} failed"), error.to_string());
3618 control.send(CallUpdate::Notice(notice.into()));
3744 control.send(CallUpdate::Notice(notice.to_owned()));
3619 3745 }
3620 3746 control.send(CallUpdate::Organizer {
3621 3747 action: label.to_owned(),
@@ -3667,14 +3793,8 @@ async fn run_bot_steps(
3667 3793 }
3668 3794 };
3669 3795 let (join_failure, start_failure) = match job {
3670 BotJob::Captions => (
3671 "The captions service could not join",
3672 "Captions could not start",
3673 ),
3674 BotJob::Recording => (
3675 "The recording service could not join",
3676 "The recording could not start",
3677 ),
3796 BotJob::Captions => (CAPTIONS_JOIN_FAILED_NOTICE, CAPTIONS_START_FAILED_NOTICE),
3797 BotJob::Recording => (RECORDING_JOIN_FAILED_NOTICE, RECORDING_START_FAILED_NOTICE),
3678 3798 };
3679 3799 loop {
3680 3800 match flow.next_for(roster.caption_bot(), is_active) {
@@ -3804,9 +3924,8 @@ async fn run_bot_steps(
3804 3924 .await;
3805 3925 }
3806 3926 if stopped.is_err() {
3807 let _ = updates.send(CallUpdate::Notice(
3808 "The recording could not be stopped".into(),
3809 ));
3927 let _ = updates
3928 .send(CallUpdate::Notice(RECORDING_STOP_FAILED_NOTICE.into()));
3810 3929 }
3811 3930 let _ = updates.send(CallUpdate::Organizer {
3812 3931 action: "recording stop".into(),
@@ -47,6 +47,24 @@ use crate::hold::{
47use crate::meeting_options::{self, OptionWrite};
47use crate::meeting_options::{self, OptionWrite};
48use crate::mic_processing::MicSettings;
48use crate::mic_processing::MicSettings;
49use crate::mute::{MuteCommand, MuteEffect};
49use crate::mute::{MuteCommand, MuteEffect};
50use crate::notices::{
51 ADMIT_ALL_FAILED_NOTICE, ADMIT_FAILED_NOTICE, ATTENDEE_SETTINGS_FAILED_NOTICE,
52 BACKGROUND_IMAGE_FAILED_NOTICE, CALL_TRANSFERRED_NOTICE, CAMERA_RESTART_NOTICE,
53 CAMERA_SETTING_FAILED_NOTICE, CAMERA_START_NOTICE, CAPTION_LANGUAGE_FAILED_NOTICE,
54 CAPTIONS_JOIN_FAILED_NOTICE, CAPTIONS_START_FAILED_NOTICE, CHANGE_ROLE_FAILED_NOTICE,
55 CHANGE_RUNNING_NOTICE, CONFIRM_RECORDING_FAILED_NOTICE, CONSENT_FIRST_NOTICE,
56 DENY_FAILED_NOTICE, HOLD_CHANGE_FAILED_NOTICE, HOLD_FAILED_NOTICE, INVITE_PERSON_FAILED_NOTICE,
57 LOWER_ALL_HANDS_FAILED_NOTICE, LOWER_HAND_FAILED_NOTICE, LOWER_THAT_HAND_FAILED_NOTICE,
58 MEETING_LOCK_FAILED_NOTICE, MIC_SETTING_FAILED_NOTICE, MUTE_ALL_FAILED_NOTICE,
59 MUTE_PARTICIPANT_FAILED_NOTICE, NOT_CONNECTED_FOR_VIDEO, ON_HOLD_NOTICE,
60 RAISE_HAND_FAILED_NOTICE, REACTION_FAILED_NOTICE, RECORDING_JOIN_FAILED_NOTICE,
61 RECORDING_NOT_STARTED_NOTICE, RECORDING_START_FAILED_NOTICE, RECORDING_STOP_FAILED_NOTICE,
62 REMOVE_PARTICIPANT_FAILED_NOTICE, RESUME_FAILED_NOTICE, SHARE_QUEUED_NOTICE,
63 SHARE_REFUSED_NOTICE, SHARING_START_NOTICE, SPOTLIGHT_FAILED_NOTICE,
64 STOP_SPOTLIGHT_FAILED_NOTICE, TRANSFER_CALL_FAILED_NOTICE, TRANSFER_FAILED_NOTICE,
65 TRANSFER_NOT_ALLOWED_NOTICE, TRANSFERRING_NOTICE, VIDEO_FAILED_NOTICE,
66 WHITEBOARD_OPEN_FAILED_NOTICE, WHITEBOARDS_MEETINGS_ONLY_NOTICE, notice_with_detail,
67};
50use crate::organizer::{MeetingCapability, Modality, StateStep, Target, modality_steps};
68use crate::organizer::{MeetingCapability, Modality, StateStep, Target, modality_steps};
51use crate::outcome::{embedded_end, failed_participant_count, outcome_summary};
69use crate::outcome::{embedded_end, failed_participant_count, outcome_summary};
52use crate::push::CallNotification;
70use crate::push::CallNotification;
@@ -54,7 +72,10 @@ use crate::recording::{Consent, RecordingPlan, RecordingStatus};
54use crate::relay::{DEFAULT_RELAY_HOST, RelayGrant};
72use crate::relay::{DEFAULT_RELAY_HOST, RelayGrant};
55use crate::renegotiation::{MediaAction, MediaNegotiator, MediaPath, RejectedOffer};
73use crate::renegotiation::{MediaAction, MediaNegotiator, MediaPath, RejectedOffer};
56use crate::roster::{Roster, direct_roster};
74use crate::roster::{Roster, direct_roster};
57use crate::screen::{ShareKind, ShareSource, list_share_sources, share_thumbnail};
75use crate::screen::{
76 ShareKind, SharePicker, ShareSource, current_share_picker, list_share_sources,
77 share_sources_for_menu, share_thumbnail,
78};
58use crate::sdp::{
79use crate::sdp::{
59 LineRole, OfferPlan, RemoteOffer, SignaledOffer, from_teams_offer, stream_lines,
80 LineRole, OfferPlan, RemoteOffer, SignaledOffer, from_teams_offer, stream_lines,
60 to_browser_answer, to_teams_answer, to_teams_offer,
81 to_browser_answer, to_teams_answer, to_teams_offer,
@@ -105,6 +126,8 @@ const HEALTH_EVERY_TICKS: u32 = TICKS_PER_SECOND * 2;
105const BOT_PREFIX: &str = "28:";
126const BOT_PREFIX: &str = "28:";
106const RECORDING_START_LIMIT: Duration = Duration::from_secs(40);
127const RECORDING_START_LIMIT: Duration = Duration::from_secs(40);
107const SAME_PEER_ANSWER_LIMIT: Duration = Duration::from_secs(40);
128const SAME_PEER_ANSWER_LIMIT: Duration = Duration::from_secs(40);
129/// Teams sometimes answers a few seconds after the soft limit; keep the local offer until this grace ends.
130const SAME_PEER_LATE_GRACE: Duration = Duration::from_secs(15);
108const GATHERING_LIMIT: Duration = Duration::from_secs(5);
131const GATHERING_LIMIT: Duration = Duration::from_secs(5);
109const RELAY_SETTLE: Duration = Duration::from_millis(200);
132const RELAY_SETTLE: Duration = Duration::from_millis(200);
110const GATHERING_POLL: Duration = Duration::from_millis(50);
133const GATHERING_POLL: Duration = Duration::from_millis(50);
@@ -113,7 +136,6 @@ const GLARE_RESEND_LIMIT: Duration = Duration::from_secs(3);
113const GLARE_CODE: i64 = 491;
136const GLARE_CODE: i64 = 491;
114const RETARGET_WAIT: Duration = Duration::from_secs(20);
137const RETARGET_WAIT: Duration = Duration::from_secs(20);
115const CAMERA_STREAM: &str = "camera";
138const CAMERA_STREAM: &str = "camera";
116const CONSENT_FIRST_NOTICE: &str = "Accept the recording notice first";
117
139
118#[derive(Debug, Clone)]
140#[derive(Debug, Clone)]
119pub struct CallOptions {
141pub struct CallOptions {
@@ -1009,6 +1031,7 @@ async fn drive(
1009 control.video.clone(),
1031 control.video.clone(),
1010 control.updates(),
1032 control.updates(),
1011 );
1033 );
1034 local_video.attach_timeline(timeline.clone());
1012 let mut camera_choice = options.camera.clone();
1035 let mut camera_choice = options.camera.clone();
1013 if options.start_camera {
1036 if options.start_camera {
1014 match local_video.preview_camera(&camera_choice) {
1037 match local_video.preview_camera(&camera_choice) {
@@ -1018,6 +1041,7 @@ async fn drive(
1018 }
1041 }
1019 let mut media_description_request = 1u32;
1042 let mut media_description_request = 1u32;
1020 refresh_cameras(control.updates(), options.video, timeline.clone());
1043 refresh_cameras(control.updates(), options.video, timeline.clone());
1044 control.send(CallUpdate::SharePicker(current_share_picker()));
1021 refresh_share_sources(control.updates(), options.video, false);
1045 refresh_share_sources(control.updates(), options.video, false);
1022
1046
1023 let wants_data_channel =
1047 let wants_data_channel =
@@ -1230,8 +1254,9 @@ async fn drive(
1230 }) {
1254 }) {
1231 Some(Ok(())) => match local_video.start_camera(&camera_choice) {
1255 Some(Ok(())) => match local_video.start_camera(&camera_choice) {
1232 Ok(()) => sending_camera = true,
1256 Ok(()) => sending_camera = true,
1233 Err(error) => control.send(CallUpdate::Notice(format!(
1257 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(
1234 "Camera could not start: {error}"
1258 CAMERA_START_NOTICE,
1259 error,
1235 ))),
1260 ))),
1236 },
1261 },
1237 Some(Err(error)) => {
1262 Some(Err(error)) => {
@@ -1363,6 +1388,7 @@ async fn drive(
1363 let mut send_requests = RequestFilter::default();
1388 let mut send_requests = RequestFilter::default();
1364 let mut send_capabilities = SendCapabilityReporter::default();
1389 let mut send_capabilities = SendCapabilityReporter::default();
1365 let mut same_peer_deadline: Option<Instant> = None;
1390 let mut same_peer_deadline: Option<Instant> = None;
1391 let mut same_peer_grace_until: Option<Instant> = None;
1366 let mut meeting_chat = conversation.chat_thread.clone();
1392 let mut meeting_chat = conversation.chat_thread.clone();
1367 if let Some(thread) = &meeting_chat {
1393 if let Some(thread) = &meeting_chat {
1368 control.send(CallUpdate::MeetingChat(thread.clone()));
1394 control.send(CallUpdate::MeetingChat(thread.clone()));
@@ -1375,6 +1401,7 @@ async fn drive(
1375 }
1401 }
1376 let mut start_camera_pending = options.start_camera;
1402 let mut start_camera_pending = options.start_camera;
1377 let mut share_pending: Option<ShareSource> = None;
1403 let mut share_pending: Option<ShareSource> = None;
1404 let mut portal_pending: Option<ShareKind> = None;
1378 let mut glare_resend: Option<GlareResend> = None;
1405 let mut glare_resend: Option<GlareResend> = None;
1379 let mut deferred_changes: Vec<Change> = Vec::new();
1406 let mut deferred_changes: Vec<Change> = Vec::new();
1380 let mut remote_direct_share: Option<String> = None;
1407 let mut remote_direct_share: Option<String> = None;
@@ -1389,6 +1416,11 @@ async fn drive(
1389 {
1416 {
1390 control.defer(CallCommand::StartShare(source));
1417 control.defer(CallCommand::StartShare(source));
1391 }
1418 }
1419 if video_possible(remote_set, layout, negotiator.path())
1420 && let Some(kind) = portal_pending.take()
1421 {
1422 control.defer(CallCommand::StartPortalShare(kind));
1423 }
1392 if next.as_ref().is_some_and(|pending| {
1424 if next.as_ref().is_some_and(|pending| {
1393 pending.connected && (pending.offered.is_some() || pending.retargeted)
1425 pending.connected && (pending.offered.is_some() || pending.retargeted)
1394 }) && let Some(pending) = next.take()
1426 }) && let Some(pending) = next.take()
@@ -1577,6 +1609,7 @@ async fn drive(
1577 && let Some(pending) = same_peer.take()
1609 && let Some(pending) = same_peer.take()
1578 {
1610 {
1579 same_peer_deadline = None;
1611 same_peer_deadline = None;
1612 same_peer_grace_until = None;
1580 let applied = match pending.change {
1613 let applied = match pending.change {
1581 Change::Hold(_) => apply_hold_answer(&current.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await,
1614 Change::Hold(_) => apply_hold_answer(&current.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await,
1582 Change::Camera(_) | Change::Share(_) => apply_answer(&current.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await,
1615 Change::Camera(_) | Change::Share(_) => apply_answer(&current.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await,
@@ -1596,7 +1629,7 @@ async fn drive(
1596 Change::Share(true) if !answer.from_mixer && !local_video.share_sending() => {
1629 Change::Share(true) if !answer.from_mixer && !local_video.share_sending() => {
1597 local_video.stop_share();
1630 local_video.stop_share();
1598 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);
1631 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);
1599 control.send(CallUpdate::LocalShare(None));
1632 clear_share(control);
1600 control.send(CallUpdate::Notice(SHARE_REFUSED_NOTICE.into()));
1633 control.send(CallUpdate::Notice(SHARE_REFUSED_NOTICE.into()));
1601 }
1634 }
1602 Change::Share(_) => {}
1635 Change::Share(_) => {}
@@ -1657,6 +1690,7 @@ async fn drive(
1657 && let Some(pending) = same_peer.take()
1690 && let Some(pending) = same_peer.take()
1658 {
1691 {
1659 same_peer_deadline = None;
1692 same_peer_deadline = None;
1693 same_peer_grace_until = None;
1660 negotiator.same_peer_offer_failed();
1694 negotiator.same_peer_offer_failed();
1661 rollback_offer(&current.peer).await;
1695 rollback_offer(&current.peer).await;
1662 timeline.record("glare", "the remote offer is answered first, ours goes out again after");
1696 timeline.record("glare", "the remote offer is answered first, ours goes out again after");
@@ -1668,6 +1702,7 @@ async fn drive(
1668 MediaAction::AnswerOnNewPeer => {
1702 MediaAction::AnswerOnNewPeer => {
1669 if let Some(pending) = same_peer.take() {
1703 if let Some(pending) = same_peer.take() {
1670 same_peer_deadline = None;
1704 same_peer_deadline = None;
1705 same_peer_grace_until = None;
1671 timeline.record("same-peer offer", "superseded by the escalation offer");
1706 timeline.record("same-peer offer", "superseded by the escalation offer");
1672 rollback_offer(&current.peer).await;
1707 rollback_offer(&current.peer).await;
1673 defer_to_new_peer(pending.change, &mut deferred_changes, &mut local_video, control);
1708 defer_to_new_peer(pending.change, &mut deferred_changes, &mut local_video, control);
@@ -1826,13 +1861,15 @@ async fn drive(
1826 recording_flow.failed();
1861 recording_flow.failed();
1827 recording_deadline = None;
1862 recording_deadline = None;
1828 control.send(CallUpdate::RecordingPending(false));
1863 control.send(CallUpdate::RecordingPending(false));
1829 control.send(CallUpdate::Notice("The recording service could not join".into()));
1864 control.send(CallUpdate::Notice(RECORDING_JOIN_FAILED_NOTICE.into()));
1830 }
1865 }
1831 if caption_flow.wanted() && roster.caption_bot().is_none() {
1866 if caption_flow.wanted() && roster.caption_bot().is_none() {
1832 timeline.record("caption bot failed", "addParticipantFailure");
1867 timeline.record("caption bot failed", "addParticipantFailure");
1833 caption_flow.failed();
1868 caption_flow.failed();
1834 caption_deadline = None;
1869 caption_deadline = None;
1835 control.send(CallUpdate::Captions(CaptionState::Failed("The captions service could not join".into())));
1870 control.send(CallUpdate::Captions(CaptionState::Failed(
1871 CAPTIONS_JOIN_FAILED_NOTICE.into(),
1872 )));
1836 }
1873 }
1837 }
1874 }
1838 Ok(CallEvent::ConversationUpdate(body)) => {
1875 Ok(CallEvent::ConversationUpdate(body)) => {
@@ -1902,14 +1939,14 @@ async fn drive(
1902 completed if completed.succeeded() => {
1939 completed if completed.succeeded() => {
1903 timeline.record("transfer", "completed");
1940 timeline.record("transfer", "completed");
1904 control.send(CallUpdate::TransferResult { succeeded: true });
1941 control.send(CallUpdate::TransferResult { succeeded: true });
1905 control.send(CallUpdate::Notice("Call transferred".into()));
1942 control.send(CallUpdate::Notice(CALL_TRANSFERRED_NOTICE.into()));
1906 advance(state, CallSignal::LocalLeave, control);
1943 advance(state, CallSignal::LocalLeave, control);
1907 break;
1944 break;
1908 }
1945 }
1909 TransferEvent::Completed { code, sub_code } => {
1946 TransferEvent::Completed { code, sub_code } => {
1910 timeline.record("transfer failed", format!("code {code} subCode {sub_code}"));
1947 timeline.record("transfer failed", format!("code {code} subCode {sub_code}"));
1911 control.send(CallUpdate::TransferResult { succeeded: false });
1948 control.send(CallUpdate::TransferResult { succeeded: false });
1912 control.send(CallUpdate::Notice("The transfer did not go through".into()));
1949 control.send(CallUpdate::Notice(TRANSFER_FAILED_NOTICE.into()));
1913 }
1950 }
1914 }
1951 }
1915 }
1952 }
@@ -1968,6 +2005,7 @@ async fn drive(
1968 Ok(CallEvent::Rejection(body)) => match negotiator.on_rejection() {
2005 Ok(CallEvent::Rejection(body)) => match negotiator.on_rejection() {
1969 RejectedOffer::SamePeer => {
2006 RejectedOffer::SamePeer => {
1970 same_peer_deadline = None;
2007 same_peer_deadline = None;
2008 same_peer_grace_until = None;
1971 if let Some(pending) = same_peer.take() {
2009 if let Some(pending) = same_peer.take() {
1972 rollback_offer(&current.peer).await;
2010 rollback_offer(&current.peer).await;
1973 if is_glare_rejection(&body) {
2011 if is_glare_rejection(&body) {
@@ -2187,6 +2225,7 @@ async fn drive(
2187 timeline.record_sdp("local offer", &signaled.sdp);
2225 timeline.record_sdp("local offer", &signaled.sdp);
2188 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(true), reply_tags });
2226 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(true), reply_tags });
2189 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2227 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2228 same_peer_grace_until = None;
2190 }
2229 }
2191 Err(error) => {
2230 Err(error) => {
2192 timeline.record("camera offer failed", error.to_string());
2231 timeline.record("camera offer failed", error.to_string());
@@ -2198,7 +2237,7 @@ async fn drive(
2198 control.send(CallUpdate::Camera(true));
2237 control.send(CallUpdate::Camera(true));
2199 tell_media_descriptions(&remote, &media_links, MediaDescription::camera(true), &mut media_description_request, timeline);
2238 tell_media_descriptions(&remote, &media_links, MediaDescription::camera(true), &mut media_description_request, timeline);
2200 }
2239 }
2201 Err(error) => control.send(CallUpdate::Notice(format!("Camera could not start: {error}"))),
2240 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(CAMERA_START_NOTICE, error))),
2202 }
2241 }
2203 } else if direct && (same_peer.is_some() || glare_resend.is_some()) {
2242 } else if direct && (same_peer.is_some() || glare_resend.is_some()) {
2204 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
2243 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
@@ -2209,6 +2248,7 @@ async fn drive(
2209 timeline.record_sdp("local offer", &signaled.sdp);
2248 timeline.record_sdp("local offer", &signaled.sdp);
2210 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(false), reply_tags });
2249 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(false), reply_tags });
2211 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2250 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2251 same_peer_grace_until = None;
2212 }
2252 }
2213 Err(error) => {
2253 Err(error) => {
2214 timeline.record("camera offer failed", error.to_string());
2254 timeline.record("camera offer failed", error.to_string());
@@ -2226,11 +2266,59 @@ async fn drive(
2226 if local_video.camera_previewing()
2266 if local_video.camera_previewing()
2227 && let Err(error) = local_video.preview_camera(&camera_choice)
2267 && let Err(error) = local_video.preview_camera(&camera_choice)
2228 {
2268 {
2229 control.send(CallUpdate::Notice(format!("Camera could not start: {error}")));
2269 control.send(CallUpdate::Notice(notice_with_detail(CAMERA_START_NOTICE, error)));
2230 } else if local_video.camera_on()
2270 } else if local_video.camera_on()
2231 && let Err(error) = local_video.start_camera(&camera_choice)
2271 && let Err(error) = local_video.start_camera(&camera_choice)
2232 {
2272 {
2233 control.send(CallUpdate::Notice(format!("Camera could not start: {error}")));
2273 control.send(CallUpdate::Notice(notice_with_detail(CAMERA_START_NOTICE, error)));
2274 }
2275 }
2276 Some(CallCommand::SetVideoQuality(quality)) => {
2277 local_video.set_video_quality(quality);
2278 if let Err(error) = local_video.refresh_camera_capture(&camera_choice) {
2279 control.send(CallUpdate::Notice(notice_with_detail(CAMERA_RESTART_NOTICE, error)));
2280 }
2281 if video.set_video_quality(quality) {
2282 send_receive_change(control, video.reselect(&roster));
2283 }
2284 }
2285 Some(CallCommand::StartPortalShare(kind)) => {
2286 let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;
2287 if !remote_set {
2288 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
2289 } else if local_hold {
2290 control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into()));
2291 } else if direct && !local_video.sharing() && (same_peer.is_some() || glare_resend.is_some()) {
2292 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
2293 } else if direct
2294 && !local_video.sharing()
2295 && !local_video.has_share_line()
2296 && let Err(error) = attach_share_line(&current.peer, &factory, &mut local_video, direct_video_mid.as_deref())
2297 {
2298 control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error)));
2299 } else if !local_video.sharing() && !video_possible(remote_set, layout, negotiator.path()) {
2300 if next.is_none() && negotiator.begin_conference_upgrade() {
2301 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;
2302 next = pending.or(next);
2303 }
2304 if next.is_some() {
2305 portal_pending = Some(kind);
2306 control.send(CallUpdate::Notice(SHARE_QUEUED_NOTICE.into()));
2307 } else {
2308 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
2309 }
2310 } else if let Err(error) = local_video.open_portal(kind, control.command_sender()) {
2311 control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error)));
2312 }
2313 }
2314 Some(CallCommand::FinishPortalShare { source, generation }) => {
2315 if local_video.accept_portal(generation) {
2316 control.defer(CallCommand::StartShare(source));
2317 }
2318 }
2319 Some(CallCommand::AbandonPortalShare) => {
2320 if local_video.portal_is_open() {
2321 local_video.stop_share();
2234 }
2322 }
2235 }
2323 }
2236 Some(CallCommand::StartShare(source)) => {
2324 Some(CallCommand::StartShare(source)) => {
@@ -2239,10 +2327,10 @@ async fn drive(
2239 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
2327 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
2240 } else if local_hold {
2328 } else if local_hold {
2241 control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into()));
2329 control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into()));
2242 } else if direct && local_video.sharing() {
2330 } else if direct && local_video.share_sending() {
2243 match local_video.start_share(&source) {
2331 match local_video.start_share(&source) {
2244 Ok(()) => control.send(CallUpdate::LocalShare(Some(source.label()))),
2332 Ok(()) => announce_share(control, &source),
2245 Err(error) => control.send(CallUpdate::Notice(format!("Sharing could not start: {error}"))),
2333 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))),
2246 }
2334 }
2247 } else if direct && (same_peer.is_some() || glare_resend.is_some()) {
2335 } else if direct && (same_peer.is_some() || glare_resend.is_some()) {
2248 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
2336 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
@@ -2250,17 +2338,18 @@ async fn drive(
2250 && !local_video.has_share_line()
2338 && !local_video.has_share_line()
2251 && let Err(error) = attach_share_line(&current.peer, &factory, &mut local_video, direct_video_mid.as_deref())
2339 && let Err(error) = attach_share_line(&current.peer, &factory, &mut local_video, direct_video_mid.as_deref())
2252 {
2340 {
2253 control.send(CallUpdate::Notice(format!("Sharing could not start: {error}")));
2341 control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error)));
2254 } else if direct {
2342 } else if direct {
2255 match local_video.start_share(&source) {
2343 match local_video.start_share(&source) {
2256 Ok(()) => {
2344 Ok(()) => {
2257 control.send(CallUpdate::LocalShare(Some(source.label())));
2345 announce_share(control, &source);
2258 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);
2346 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);
2259 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 {
2347 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 {
2260 Ok((browser_offer, signaled, reply_tags)) => {
2348 Ok((browser_offer, signaled, reply_tags)) => {
2261 timeline.record_sdp("local offer", &signaled.sdp);
2349 timeline.record_sdp("local offer", &signaled.sdp);
2262 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(true), reply_tags });
2350 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(true), reply_tags });
2263 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2351 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2352 same_peer_grace_until = None;
2264 }
2353 }
2265 Err(error) => {
2354 Err(error) => {
2266 timeline.record("share offer failed", error.to_string());
2355 timeline.record("share offer failed", error.to_string());
@@ -2268,7 +2357,7 @@ async fn drive(
2268 }
2357 }
2269 }
2358 }
2270 }
2359 }
2271 Err(error) => control.send(CallUpdate::Notice(format!("Sharing could not start: {error}"))),
2360 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))),
2272 }
2361 }
2273 } else if !video_possible(remote_set, layout, negotiator.path()) {
2362 } else if !video_possible(remote_set, layout, negotiator.path()) {
2274 if next.is_none() && negotiator.begin_conference_upgrade() {
2363 if next.is_none() && negotiator.begin_conference_upgrade() {
@@ -2284,35 +2373,39 @@ async fn drive(
2284 } else {
2373 } else {
2285 match local_video.start_share(&source) {
2374 match local_video.start_share(&source) {
2286 Ok(()) => {
2375 Ok(()) => {
2287 control.send(CallUpdate::LocalShare(Some(source.label())));
2376 announce_share(control, &source);
2288 tell_media_descriptions(&remote, &media_links, MediaDescription::share(true), &mut media_description_request, timeline);
2377 tell_media_descriptions(&remote, &media_links, MediaDescription::share(true), &mut media_description_request, timeline);
2289 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);
2378 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);
2290 }
2379 }
2291 Err(error) => control.send(CallUpdate::Notice(format!("Sharing could not start: {error}"))),
2380 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))),
2292 }
2381 }
2293 }
2382 }
2294 }
2383 }
2295 Some(CallCommand::StopShare) => {
2384 Some(CallCommand::StopShare) => {
2296 let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;
2385 let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;
2297 share_pending = None;
2386 share_pending = None;
2298 if direct && local_video.sharing() && (same_peer.is_some() || glare_resend.is_some()) {
2387 portal_pending = None;
2388 if local_video.portal_is_open() {
2389 local_video.stop_share();
2390 } else if direct && local_video.sharing() && (same_peer.is_some() || glare_resend.is_some()) {
2299 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
2391 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
2300 } else if direct && local_video.sharing() {
2392 } else if direct && local_video.sharing() {
2301 local_video.stop_share();
2393 local_video.stop_share();
2302 control.send(CallUpdate::LocalShare(None));
2394 clear_share(control);
2303 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);
2395 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);
2304 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 {
2396 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 {
2305 Ok((browser_offer, signaled, reply_tags)) => {
2397 Ok((browser_offer, signaled, reply_tags)) => {
2306 timeline.record_sdp("local offer", &signaled.sdp);
2398 timeline.record_sdp("local offer", &signaled.sdp);
2307 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(false), reply_tags });
2399 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(false), reply_tags });
2308 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2400 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2401 same_peer_grace_until = None;
2309 }
2402 }
2310 Err(error) => timeline.record("share offer failed", error.to_string()),
2403 Err(error) => timeline.record("share offer failed", error.to_string()),
2311 }
2404 }
2312 } else if local_video.sharing() {
2405 } else if local_video.sharing() {
2313 local_video.stop_share();
2406 local_video.stop_share();
2314 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);
2407 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);
2315 control.send(CallUpdate::LocalShare(None));
2408 clear_share(control);
2316 tell_media_descriptions(&remote, &media_links, MediaDescription::share(false), &mut media_description_request, timeline);
2409 tell_media_descriptions(&remote, &media_links, MediaDescription::share(false), &mut media_description_request, timeline);
2317 }
2410 }
2318 }
2411 }
@@ -2329,7 +2422,7 @@ async fn drive(
2329 Err(error) => {
2422 Err(error) => {
2330 timeline.record("raise hand failed", error.to_string());
2423 timeline.record("raise hand failed", error.to_string());
2331 control.send(CallUpdate::OwnHand(None));
2424 control.send(CallUpdate::OwnHand(None));
2332 control.send(CallUpdate::Notice("Could not raise your hand".into()));
2425 control.send(CallUpdate::Notice(RAISE_HAND_FAILED_NOTICE.into()));
2333 }
2426 }
2334 },
2427 },
2335 Some(CallCommand::SetHand(false)) => {
2428 Some(CallCommand::SetHand(false)) => {
@@ -2340,7 +2433,7 @@ async fn drive(
2340 && let Err(error) = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await
2433 && let Err(error) = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await
2341 {
2434 {
2342 timeline.record("lower hand failed", error.to_string());
2435 timeline.record("lower hand failed", error.to_string());
2343 control.send(CallUpdate::Notice("Could not lower your hand".into()));
2436 control.send(CallUpdate::Notice(LOWER_HAND_FAILED_NOTICE.into()));
2344 }
2437 }
2345 }
2438 }
2346 Some(CallCommand::LowerHand { mri }) => {
2439 Some(CallCommand::LowerHand { mri }) => {
@@ -2349,18 +2442,18 @@ async fn drive(
2349 && let Err(error) = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await
2442 && let Err(error) = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await
2350 {
2443 {
2351 timeline.record("lower hand failed", error.to_string());
2444 timeline.record("lower hand failed", error.to_string());
2352 control.send(CallUpdate::Notice("Could not lower that hand".into()));
2445 control.send(CallUpdate::Notice(LOWER_THAT_HAND_FAILED_NOTICE.into()));
2353 }
2446 }
2354 }
2447 }
2355 Some(CallCommand::LowerAllHands) => {
2448 Some(CallCommand::LowerAllHands) => {
2356 if let Err(error) = remote.signaling.lower_all_hands(&remote.conversation, &remote.participant).await {
2449 if let Err(error) = remote.signaling.lower_all_hands(&remote.conversation, &remote.participant).await {
2357 timeline.record("lower all hands failed", error.to_string());
2450 timeline.record("lower all hands failed", error.to_string());
2358 control.send(CallUpdate::Notice("Could not lower all hands".into()));
2451 control.send(CallUpdate::Notice(LOWER_ALL_HANDS_FAILED_NOTICE.into()));
2359 }
2452 }
2360 }
2453 }
2361 Some(CallCommand::Admit { mri }) => {
2454 Some(CallCommand::Admit { mri }) => {
2362 let result = remote.signaling.admit(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await;
2455 let result = remote.signaling.admit(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await;
2363 report_organizer_result(result, "admit", "Could not admit that person", control, timeline);
2456 report_organizer_result(result, "admit", ADMIT_FAILED_NOTICE, control, timeline);
2364 }
2457 }
2365 Some(CallCommand::AdmitAll) => {
2458 Some(CallCommand::AdmitAll) => {
2366 let mut result = Ok(202);
2459 let mut result = Ok(202);
@@ -2370,19 +2463,19 @@ async fn drive(
2370 break;
2463 break;
2371 }
2464 }
2372 }
2465 }
2373 report_organizer_result(result, "admit all", "Could not admit everyone", control, timeline);
2466 report_organizer_result(result, "admit all", ADMIT_ALL_FAILED_NOTICE, control, timeline);
2374 }
2467 }
2375 Some(CallCommand::Deny { mri }) => {
2468 Some(CallCommand::Deny { mri }) => {
2376 let result = remote.signaling.remove_participant(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await;
2469 let result = remote.signaling.remove_participant(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await;
2377 report_organizer_result(result, "deny", "Could not deny that person", control, timeline);
2470 report_organizer_result(result, "deny", DENY_FAILED_NOTICE, control, timeline);
2378 }
2471 }
2379 Some(CallCommand::RemoveParticipant { mri }) => {
2472 Some(CallCommand::RemoveParticipant { mri }) => {
2380 let result = remote.signaling.remove_participant(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await;
2473 let result = remote.signaling.remove_participant(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await;
2381 report_organizer_result(result, "remove participant", "Could not remove that person", control, timeline);
2474 report_organizer_result(result, "remove participant", REMOVE_PARTICIPANT_FAILED_NOTICE, control, timeline);
2382 }
2475 }
2383 Some(CallCommand::MuteParticipant { mri }) => {
2476 Some(CallCommand::MuteParticipant { mri }) => {
2384 let result = remote.signaling.mute_participant(&remote.conversation, &remote.participant, &mri).await;
2477 let result = remote.signaling.mute_participant(&remote.conversation, &remote.participant, &mri).await;
2385 report_organizer_result(result, "mute participant", "Could not mute that person", control, timeline);
2478 report_organizer_result(result, "mute participant", MUTE_PARTICIPANT_FAILED_NOTICE, control, timeline);
2386 }
2479 }
2387 Some(CallCommand::MuteAll) => {
2480 Some(CallCommand::MuteAll) => {
2388 let others: Vec<String> = roster
2481 let others: Vec<String> = roster
@@ -2392,7 +2485,7 @@ async fn drive(
2392 .map(|member| member.mri.clone())
2485 .map(|member| member.mri.clone())
2393 .collect();
2486 .collect();
2394 let result = remote.signaling.mute_everyone(&remote.conversation, &remote.participant, &others).await;
2487 let result = remote.signaling.mute_everyone(&remote.conversation, &remote.participant, &others).await;
2395 report_organizer_result(result, "mute all", "Could not mute everyone", control, timeline);
2488 report_organizer_result(result, "mute all", MUTE_ALL_FAILED_NOTICE, control, timeline);
2396 }
2489 }
2397 Some(CallCommand::SetLock(locked)) => {
2490 Some(CallCommand::SetLock(locked)) => {
2398 let result = remote.signaling.set_lock(&remote.conversation, &remote.participant, locked).await;
2491 let result = remote.signaling.set_lock(&remote.conversation, &remote.participant, locked).await;
@@ -2400,11 +2493,11 @@ async fn drive(
2400 capability.locked = locked;
2493 capability.locked = locked;
2401 control.send(CallUpdate::Capability(capability));
2494 control.send(CallUpdate::Capability(capability));
2402 }
2495 }
2403 report_organizer_result(result, "lock meeting", "Could not change the meeting lock", control, timeline);
2496 report_organizer_result(result, "lock meeting", MEETING_LOCK_FAILED_NOTICE, control, timeline);
2404 }
2497 }
2405 Some(CallCommand::SetRole { mri, role }) => {
2498 Some(CallCommand::SetRole { mri, role }) => {
2406 let result = remote.signaling.change_role(&remote.conversation, &remote.participant, &mri, role).await;
2499 let result = remote.signaling.change_role(&remote.conversation, &remote.participant, &mri, role).await;
2407 report_organizer_result(result, "change role", "Could not change that role", control, timeline);
2500 report_organizer_result(result, "change role", CHANGE_ROLE_FAILED_NOTICE, control, timeline);
2408 }
2501 }
2409 Some(CallCommand::SetAttendeeModality { mri, modality, allowed }) => {
2502 Some(CallCommand::SetAttendeeModality { mri, modality, allowed }) => {
2410 let limits = roster.entries().into_iter().find(|entry| entry.mri == mri).map(|entry| entry.limits).unwrap_or_default();
2503 let limits = roster.entries().into_iter().find(|entry| entry.mri == mri).map(|entry| entry.limits).unwrap_or_default();
@@ -2418,7 +2511,11 @@ async fn drive(
2418 break;
2511 break;
2419 }
2512 }
2420 }
2513 }
2421 let notice = if modality == Modality::Mic { "Could not change that microphone setting" } else { "Could not change that camera setting" };
2514 let notice = if modality == Modality::Mic {
2515 MIC_SETTING_FAILED_NOTICE
2516 } else {
2517 CAMERA_SETTING_FAILED_NOTICE
2518 };
2422 report_organizer_result(result, "attendee modality", notice, control, timeline);
2519 report_organizer_result(result, "attendee modality", notice, control, timeline);
2423 }
2520 }
2424 Some(CallCommand::SetAttendeeRestrictions { mic_off, camera_off }) => {
2521 Some(CallCommand::SetAttendeeRestrictions { mic_off, camera_off }) => {
@@ -2431,12 +2528,12 @@ async fn drive(
2431 capability.attendee_camera_off = camera_off;
2528 capability.attendee_camera_off = camera_off;
2432 control.send(CallUpdate::Capability(capability));
2529 control.send(CallUpdate::Capability(capability));
2433 }
2530 }
2434 report_organizer_result(result, "attendee restrictions", "Could not change the attendee settings", control, timeline);
2531 report_organizer_result(result, "attendee restrictions", ATTENDEE_SETTINGS_FAILED_NOTICE, control, timeline);
2435 }
2532 }
2436 Some(CallCommand::Invite { callees, group_thread }) => {
2533 Some(CallCommand::Invite { callees, group_thread }) => {
2437 let thread = group_thread.or_else(|| meeting_chat.clone());
2534 let thread = group_thread.or_else(|| meeting_chat.clone());
2438 let result = remote.signaling.add_participants(&remote.conversation, &remote.participant, &callees, thread.as_deref(), meeting_target.as_ref(), &links).await;
2535 let result = remote.signaling.add_participants(&remote.conversation, &remote.participant, &callees, thread.as_deref(), meeting_target.as_ref(), &links).await;
2439 report_organizer_result(result, "invite", "Could not invite that person", control, timeline);
2536 report_organizer_result(result, "invite", INVITE_PERSON_FAILED_NOTICE, control, timeline);
2440 }
2537 }
2441 Some(CallCommand::LoadMeetingOptions) => {
2538 Some(CallCommand::LoadMeetingOptions) => {
2442 let update = match &meeting_target {
2539 let update = match &meeting_target {
@@ -2460,13 +2557,13 @@ async fn drive(
2460 }
2557 }
2461 Some(CallCommand::Spotlight { mri }) => {
2558 Some(CallCommand::Spotlight { mri }) => {
2462 let result = remote.signaling.spotlight(&remote.conversation, &remote.participant, &mri).await;
2559 let result = remote.signaling.spotlight(&remote.conversation, &remote.participant, &mri).await;
2463 report_organizer_result(result, "spotlight", "Could not spotlight that person", control, timeline);
2560 report_organizer_result(result, "spotlight", SPOTLIGHT_FAILED_NOTICE, control, timeline);
2464 }
2561 }
2465 Some(CallCommand::StopSpotlight { mri }) => {
2562 Some(CallCommand::StopSpotlight { mri }) => {
2466 let state_ids: Vec<String> = roster.spotlight_of(&mri).map(|spotlight| spotlight.state_id.clone()).into_iter().collect();
2563 let state_ids: Vec<String> = roster.spotlight_of(&mri).map(|spotlight| spotlight.state_id.clone()).into_iter().collect();
2467 if !state_ids.is_empty() {
2564 if !state_ids.is_empty() {
2468 let result = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await.map(|()| 200);
2565 let result = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await.map(|()| 200);
2469 report_organizer_result(result, "stop spotlight", "Could not stop the spotlight", control, timeline);
2566 report_organizer_result(result, "stop spotlight", STOP_SPOTLIGHT_FAILED_NOTICE, control, timeline);
2470 }
2567 }
2471 }
2568 }
2472 Some(CallCommand::SetCaptions(on)) => {
2569 Some(CallCommand::SetCaptions(on)) => {
@@ -2505,7 +2602,7 @@ async fn drive(
2505 && let Err(error) = remote.signaling.caption_language_command(&url, &remote.participant, &language).await
2602 && let Err(error) = remote.signaling.caption_language_command(&url, &remote.participant, &language).await
2506 {
2603 {
2507 timeline.record("caption language failed", error.to_string());
2604 timeline.record("caption language failed", error.to_string());
2508 control.send(CallUpdate::Notice("Could not change the spoken language".into()));
2605 control.send(CallUpdate::Notice(CAPTION_LANGUAGE_FAILED_NOTICE.into()));
2509 }
2606 }
2510 }
2607 }
2511 Some(CallCommand::ConsentToRecording) => {
2608 Some(CallCommand::ConsentToRecording) => {
@@ -2516,7 +2613,7 @@ async fn drive(
2516 }
2613 }
2517 Err(error) => {
2614 Err(error) => {
2518 timeline.record("recording consent failed", error.to_string());
2615 timeline.record("recording consent failed", error.to_string());
2519 control.send(CallUpdate::Notice("Could not confirm the recording notice".into()));
2616 control.send(CallUpdate::Notice(CONFIRM_RECORDING_FAILED_NOTICE.into()));
2520 }
2617 }
2521 }
2618 }
2522 }
2619 }
@@ -2534,32 +2631,40 @@ async fn drive(
2534 timeline.record_sdp("local offer", &signaled.sdp);
2631 timeline.record_sdp("local offer", &signaled.sdp);
2535 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Hold(hold), reply_tags });
2632 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Hold(hold), reply_tags });
2536 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2633 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2634 same_peer_grace_until = None;
2537 }
2635 }
2538 Err(error) => {
2636 Err(error) => {
2539 timeline.record("hold failed", error.to_string());
2637 timeline.record("hold failed", error.to_string());
2540 control.send(CallUpdate::Notice(if hold { "Could not put the call on hold".into() } else { "Could not resume the call".into() }));
2638 control.send(CallUpdate::Notice(if hold {
2639 HOLD_FAILED_NOTICE.into()
2640 } else {
2641 RESUME_FAILED_NOTICE.into()
2642 }));
2541 }
2643 }
2542 }
2644 }
2543 }
2645 }
2544 Some(CallCommand::Transfer { target, replaces }) => {
2646 Some(CallCommand::Transfer { target, replaces }) => {
2545 let Some(url) = media_links.get("transfer").cloned() else {
2647 let Some(url) = media_links.get("transfer").cloned() else {
2546 control.send(CallUpdate::TransferResult { succeeded: false });
2648 control.send(CallUpdate::TransferResult { succeeded: false });
2547 control.send(CallUpdate::Notice("This call cannot be transferred".into()));
2649 control.send(CallUpdate::Notice(TRANSFER_NOT_ALLOWED_NOTICE.into()));
2548 continue;
2650 continue;
2549 };
2651 };
2550 let transfer_target = TransferTarget { mri: &target.mri, replaces: replaces.as_ref() };
2652 let transfer_target = TransferTarget { mri: &target.mri, replaces: replaces.as_ref() };
2551 match remote.signaling.transfer(&url, &remote.participant, transfer_target, &links).await {
2653 match remote.signaling.transfer(&url, &remote.participant, transfer_target, &links).await {
2552 Ok(()) => control.send(CallUpdate::Notice(format!("Transferring to {}...", target.display_name))),
2654 Ok(()) => control.send(CallUpdate::Notice(notice_with_detail(
2655 TRANSFERRING_NOTICE,
2656 target.display_name,
2657 ))),
2553 Err(error) => {
2658 Err(error) => {
2554 timeline.record("transfer failed", error.to_string());
2659 timeline.record("transfer failed", error.to_string());
2555 control.send(CallUpdate::TransferResult { succeeded: false });
2660 control.send(CallUpdate::TransferResult { succeeded: false });
2556 control.send(CallUpdate::Notice("Could not transfer the call".into()));
2661 control.send(CallUpdate::Notice(TRANSFER_CALL_FAILED_NOTICE.into()));
2557 }
2662 }
2558 }
2663 }
2559 }
2664 }
2560 Some(CallCommand::OpenWhiteboard { title }) => {
2665 Some(CallCommand::OpenWhiteboard { title }) => {
2561 let Some(target) = meeting_target.clone() else {
2666 let Some(target) = meeting_target.clone() else {
2562 control.send(CallUpdate::Notice("Whiteboards belong to meetings".into()));
2667 control.send(CallUpdate::Notice(WHITEBOARDS_MEETINGS_ONLY_NOTICE.into()));
2563 continue;
2668 continue;
2564 };
2669 };
2565 let session = inner.session.clone();
2670 let session = inner.session.clone();
@@ -2567,7 +2672,7 @@ async fn drive(
2567 tokio::spawn(async move {
2672 tokio::spawn(async move {
2568 let update = match whiteboard::fetch_board(&session, &target, &title).await {
2673 let update = match whiteboard::fetch_board(&session, &target, &title).await {
2569 Ok(url) => CallUpdate::WhiteboardUrl(url),
2674 Ok(url) => CallUpdate::WhiteboardUrl(url),
2570 Err(_) => CallUpdate::Notice("The whiteboard could not be opened".into()),
2675 Err(_) => CallUpdate::Notice(WHITEBOARD_OPEN_FAILED_NOTICE.into()),
2571 };
2676 };
2572 let _ = updates.send(update);
2677 let _ = updates.send(update);
2573 });
2678 });
@@ -2594,7 +2699,7 @@ async fn drive(
2594 Some(CallCommand::SendReaction(reaction)) => {
2699 Some(CallCommand::SendReaction(reaction)) => {
2595 if let Err(error) = remote.signaling.send_reaction(&remote.conversation, &remote.participant, reaction).await {
2700 if let Err(error) = remote.signaling.send_reaction(&remote.conversation, &remote.participant, reaction).await {
2596 timeline.record("reaction failed", error.to_string());
2701 timeline.record("reaction failed", error.to_string());
2597 control.send(CallUpdate::Notice("Could not send the reaction".into()));
2702 control.send(CallUpdate::Notice(REACTION_FAILED_NOTICE.into()));
2598 }
2703 }
2599 }
2704 }
2600 Some(CallCommand::EndMeeting) => {
2705 Some(CallCommand::EndMeeting) => {
@@ -2645,12 +2750,13 @@ async fn drive(
2645 recording_flow.failed();
2750 recording_flow.failed();
2646 timeline.record("recording", "did not start in time");
2751 timeline.record("recording", "did not start in time");
2647 control.send(CallUpdate::RecordingPending(false));
2752 control.send(CallUpdate::RecordingPending(false));
2648 control.send(CallUpdate::Notice("The recording did not start".into()));
2753 control.send(CallUpdate::Notice(RECORDING_NOT_STARTED_NOTICE.into()));
2649 }
2754 }
2650 if layout == Layout::Conference
2755 if layout == Layout::Conference
2651 && let Some(size) = local_video.camera_size()
2756 && let Some(size) = local_video.camera_size()
2652 && let Some(url) = media_links.get("applyChannelParameters").cloned()
2757 && let Some(url) = media_links.get("applyChannelParameters").cloned()
2653 && let Some(body) = send_capabilities.body_for(size)
2758 && let Some(body) =
2759 send_capabilities.body_for(size, local_video.video_quality())
2654 {
2760 {
2655 let signaling = signaling.clone();
2761 let signaling = signaling.clone();
2656 let timeline = timeline.clone();
2762 let timeline = timeline.clone();
@@ -2746,12 +2852,13 @@ async fn drive(
2746 timeline.record(
2852 timeline.record(
2747 "stats",
2853 "stats",
2748 format!(
2854 format!(
2749 "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={:?}{}",
2855 "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={:?}{}{}",
2750 snapshot.inbound_packets, snapshot.inbound_bytes, snapshot.audio_level, snapshot.outbound_packets, snapshot.local_level, snapshot.echo_return_loss_enhancement, snapshot.dtls_state,
2856 snapshot.inbound_packets, snapshot.inbound_bytes, snapshot.audio_level, snapshot.outbound_packets, snapshot.local_level, snapshot.echo_return_loss_enhancement, snapshot.dtls_state,
2751 snapshot.video.inbound_packets, snapshot.video.inbound_frames_decoded, snapshot.video.inbound_width, snapshot.video.inbound_height,
2857 snapshot.video.inbound_packets, snapshot.video.inbound_frames_decoded, snapshot.video.inbound_width, snapshot.video.inbound_height,
2752 snapshot.video.outbound_packets, snapshot.video.outbound_frames_encoded, snapshot.video.outbound_width, snapshot.video.outbound_height,
2858 snapshot.video.outbound_packets, snapshot.video.outbound_frames_encoded, snapshot.video.outbound_width, snapshot.video.outbound_height,
2753 snapshot.video.remote_reports, snapshot.video.remote_round_trip_ms, snapshot.outbound_bytes, snapshot.source_levels, snapshot.video_senders,
2859 snapshot.video.remote_reports, snapshot.video.remote_round_trip_ms, snapshot.outbound_bytes, snapshot.source_levels, snapshot.video_senders,
2754 snapshot.share_receive.as_ref().filter(|_| snapshot.share_inbound_packets > 0).map(ShareReceive::summary).unwrap_or_default()
2860 snapshot.share_receive.as_ref().filter(|_| snapshot.share_inbound_packets > 0).map(ShareReceive::summary).unwrap_or_default(),
2861 local_video.camera_capture_summary().unwrap_or_default()
2755 ),
2862 ),
2756 );
2863 );
2757 }
2864 }
@@ -2796,6 +2903,7 @@ async fn drive(
2796 control.send(CallUpdate::Camera(false));
2903 control.send(CallUpdate::Camera(false));
2797 }
2904 }
2798 share_pending = None;
2905 share_pending = None;
2906 portal_pending = None;
2799 settle_failed_escalation(pending.offered.is_none(), layout, &mut negotiator, &mut deferred_changes, &mut local_video, control);
2907 settle_failed_escalation(pending.offered.is_none(), layout, &mut negotiator, &mut deferred_changes, &mut local_video, control);
2800 timeline.record("escalation failed", "no answer for the new peer connection in time");
2908 timeline.record("escalation failed", "no answer for the new peer connection in time");
2801 control.send(CallUpdate::Notice(VIDEO_FAILED_NOTICE.into()));
2909 control.send(CallUpdate::Notice(VIDEO_FAILED_NOTICE.into()));
@@ -2826,6 +2934,7 @@ async fn drive(
2826 timeline.record_sdp("local offer", &signaled.sdp);
2934 timeline.record_sdp("local offer", &signaled.sdp);
2827 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: resend.change, reply_tags });
2935 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: resend.change, reply_tags });
2828 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2936 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2937 same_peer_grace_until = None;
2829 }
2938 }
2830 Err(error) => {
2939 Err(error) => {
2831 timeline.record("offer after glare failed", error.to_string());
2940 timeline.record("offer after glare failed", error.to_string());
@@ -2836,6 +2945,16 @@ async fn drive(
2836 }
2945 }
2837 _ = sleep_until(same_peer_deadline.unwrap_or_else(far_future)), if same_peer_deadline.is_some() => {
2946 _ = sleep_until(same_peer_deadline.unwrap_or_else(far_future)), if same_peer_deadline.is_some() => {
2838 same_peer_deadline = None;
2947 same_peer_deadline = None;
2948 if same_peer.is_some() {
2949 same_peer_grace_until = Some(Instant::now() + SAME_PEER_LATE_GRACE);
2950 timeline.record(
2951 "same-peer offer",
2952 "no answer yet, waiting a little longer",
2953 );
2954 }
2955 }
2956 _ = sleep_until(same_peer_grace_until.unwrap_or_else(far_future)), if same_peer_grace_until.is_some() => {
2957 same_peer_grace_until = None;
2839 if let Some(pending) = same_peer.take() {
2958 if let Some(pending) = same_peer.take() {
2840 timeline.record("same-peer offer", "no answer in time");
2959 timeline.record("same-peer offer", "no answer in time");
2841 negotiator.same_peer_offer_failed();
2960 negotiator.same_peer_offer_failed();
@@ -3041,13 +3160,6 @@ fn negotiate_video(
3041 send_receive_change(control, video.reselect(roster));
3160 send_receive_change(control, video.reselect(roster));
3042}
3161}
3043
3162
3044const NOT_CONNECTED_FOR_VIDEO: &str = "Video starts once the call is connected";
3045const ON_HOLD_NOTICE: &str = "Resume the call first";
3046const CHANGE_RUNNING_NOTICE: &str = "Another change is still running, try again in a moment";
3047const VIDEO_FAILED_NOTICE: &str = "Video could not start, the call stays audio only";
3048const SHARE_QUEUED_NOTICE: &str = "Sharing starts in a moment";
3049const SHARE_REFUSED_NOTICE: &str = "The other side did not accept the screen share";
3050
3051async fn camera_devices(mode: VideoMode) -> Vec<CameraDevice> {
3163async fn camera_devices(mode: VideoMode) -> Vec<CameraDevice> {
3052 match mode {
3164 match mode {
3053 VideoMode::Pattern => vec![CameraDevice {
3165 VideoMode::Pattern => vec![CameraDevice {
@@ -3085,12 +3197,23 @@ const SHARE_THUMBNAIL_WINDOWS: usize = 12;
3085const SHARE_THUMBNAIL_WIDTH: u32 = 320;
3197const SHARE_THUMBNAIL_WIDTH: u32 = 320;
3086const SHARE_THUMBNAIL_HEIGHT: u32 = 180;
3198const SHARE_THUMBNAIL_HEIGHT: u32 = 180;
3087
3199
3200fn announce_share(control: &CallControl, source: &ShareSource) {
3201 control.send(CallUpdate::ShareKind(Some(source.kind)));
3202 control.send(CallUpdate::LocalShare(Some(source.label())));
3203}
3204
3205fn clear_share(control: &CallControl) {
3206 control.send(CallUpdate::ShareKind(None));
3207 control.send(CallUpdate::LocalShare(None));
3208}
3209
3088fn refresh_share_sources(
3210fn refresh_share_sources(
3089 updates: mpsc::UnboundedSender<CallUpdate>,
3211 updates: mpsc::UnboundedSender<CallUpdate>,
3090 mode: VideoMode,
3212 mode: VideoMode,
3091 with_thumbnails: bool,
3213 with_thumbnails: bool,
3092) {
3214) {
3093 tokio::spawn(async move {
3215 tokio::spawn(async move {
3216 let picker = current_share_picker();
3094 let sources = match mode {
3217 let sources = match mode {
3095 VideoMode::Pattern => vec![
3218 VideoMode::Pattern => vec![
3096 ShareSource {
3219 ShareSource {
@@ -3105,12 +3228,14 @@ fn refresh_share_sources(
3105 },
3228 },
3106 ],
3229 ],
3107 VideoMode::Off => Vec::new(),
3230 VideoMode::Off => Vec::new(),
3231 VideoMode::Platform if picker == SharePicker::Portal => Vec::new(),
3108 VideoMode::Platform => tokio::task::spawn_blocking(list_share_sources)
3232 VideoMode::Platform => tokio::task::spawn_blocking(list_share_sources)
3109 .await
3233 .await
3110 .unwrap_or_default(),
3234 .unwrap_or_default(),
3111 };
3235 };
3236 let sources = share_sources_for_menu(picker, sources);
3112 let _ = updates.send(CallUpdate::ShareSources(sources.clone()));
3237 let _ = updates.send(CallUpdate::ShareSources(sources.clone()));
3113 if !with_thumbnails {
3238 if picker == SharePicker::Portal || !with_thumbnails {
3114 return;
3239 return;
3115 }
3240 }
3116 let wanted: Vec<ShareSource> = sources
3241 let wanted: Vec<ShareSource> = sources
@@ -3503,7 +3628,7 @@ fn settle_failed_escalation(
3503fn drop_local_media(local_video: &mut LocalVideo, control: &CallControl) {
3628fn drop_local_media(local_video: &mut LocalVideo, control: &CallControl) {
3504 if local_video.sharing() {
3629 if local_video.sharing() {
3505 local_video.stop_share();
3630 local_video.stop_share();
3506 control.send(CallUpdate::LocalShare(None));
3631 clear_share(control);
3507 }
3632 }
3508 if local_video.camera_on() {
3633 if local_video.camera_on() {
3509 local_video.stop_camera();
3634 local_video.stop_camera();
@@ -3520,11 +3645,14 @@ fn undo_change(change: Change, local_video: &mut LocalVideo, control: &CallContr
3520 Change::Camera(false) => control.send(CallUpdate::Camera(false)),
3645 Change::Camera(false) => control.send(CallUpdate::Camera(false)),
3521 Change::Share(true) => {
3646 Change::Share(true) => {
3522 local_video.stop_share();
3647 local_video.stop_share();
3523 control.send(CallUpdate::LocalShare(None));
3648 clear_share(control);
3524 control.send(CallUpdate::Notice("Sharing could not start".into()));
3649 control.send(CallUpdate::Notice(notice_with_detail(
3650 SHARING_START_NOTICE,
3651 "",
3652 )));
3525 }
3653 }
3526 Change::Share(false) => {}
3654 Change::Share(false) => {}
3527 Change::Hold(_) => control.send(CallUpdate::Notice("The hold did not go through".into())),
3655 Change::Hold(_) => control.send(CallUpdate::Notice(HOLD_CHANGE_FAILED_NOTICE.into())),
3528 }
3656 }
3529}
3657}
3530
3658
@@ -3564,9 +3692,7 @@ async fn apply_background(
3564 Ok(Ok(picture)) => local_video.set_background(true, Some(Arc::new(picture))),
3692 Ok(Ok(picture)) => local_video.set_background(true, Some(Arc::new(picture))),
3565 Ok(Err(error)) => {
3693 Ok(Err(error)) => {
3566 timeline.record("background image failed", error.to_string());
3694 timeline.record("background image failed", error.to_string());
3567 control.send(CallUpdate::Notice(
3695 control.send(CallUpdate::Notice(BACKGROUND_IMAGE_FAILED_NOTICE.into()));
3568 "That background image could not be used".into(),
3569 ));
3570 }
3696 }
3571 Err(_) => {}
3697 Err(_) => {}
3572 }
3698 }
@@ -3609,13 +3735,13 @@ fn recorder_busy(error: &Error) -> bool {
3609fn report_organizer_result(
3735fn report_organizer_result(
3610 result: Result<u16>,
3736 result: Result<u16>,
3611 label: &str,
3737 label: &str,
3612 notice: &str,
3738 notice: &'static str,
3613 control: &CallControl,
3739 control: &CallControl,
3614 timeline: &Timeline,
3740 timeline: &Timeline,
3615) {
3741) {
3616 if let Err(error) = &result {
3742 if let Err(error) = &result {
3617 timeline.record(format!("{label} failed"), error.to_string());
3743 timeline.record(format!("{label} failed"), error.to_string());
3618 control.send(CallUpdate::Notice(notice.into()));
3744 control.send(CallUpdate::Notice(notice.to_owned()));
3619 }
3745 }
3620 control.send(CallUpdate::Organizer {
3746 control.send(CallUpdate::Organizer {
3621 action: label.to_owned(),
3747 action: label.to_owned(),
@@ -3667,14 +3793,8 @@ async fn run_bot_steps(
3667 }
3793 }
3668 };
3794 };
3669 let (join_failure, start_failure) = match job {
3795 let (join_failure, start_failure) = match job {
3670 BotJob::Captions => (
3796 BotJob::Captions => (CAPTIONS_JOIN_FAILED_NOTICE, CAPTIONS_START_FAILED_NOTICE),
3671 "The captions service could not join",
3797 BotJob::Recording => (RECORDING_JOIN_FAILED_NOTICE, RECORDING_START_FAILED_NOTICE),
3672 "Captions could not start",
3673 ),
3674 BotJob::Recording => (
3675 "The recording service could not join",
3676 "The recording could not start",
3677 ),
3678 };
3798 };
3679 loop {
3799 loop {
3680 match flow.next_for(roster.caption_bot(), is_active) {
3800 match flow.next_for(roster.caption_bot(), is_active) {
@@ -3804,9 +3924,8 @@ async fn run_bot_steps(
3804 .await;
3924 .await;
3805 }
3925 }
3806 if stopped.is_err() {
3926 if stopped.is_err() {
3807 let _ = updates.send(CallUpdate::Notice(
3927 let _ = updates
3808 "The recording could not be stopped".into(),
3928 .send(CallUpdate::Notice(RECORDING_STOP_FAILED_NOTICE.into()));
3809 ));
3810 }
3929 }
3811 let _ = updates.send(CallUpdate::Organizer {
3930 let _ = updates.send(CallUpdate::Organizer {
3812 action: "recording stop".into(),
3931 action: "recording stop".into(),
crates/calling/src/camera.rs +449 −89
@@ -1,5 +1,7 @@
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 _};
@@ -9,23 +11,25 @@ use nokhwa::utils::{
9 11 Resolution,
10 12 };
11 13 use nokhwa::{Camera, query};
12 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;
13 18
14 19 use crate::blur::BlurSettings;
15 20 use crate::capture::Capture;
16 21 use crate::devices::{DeviceChoice, DeviceEntry};
17 22 use crate::effects::EffectsThread;
18 23 use crate::error::{Error, Result};
24 use crate::video_quality::VideoQuality;
19 25
20 26 const RETRY_PAUSE: Duration = Duration::from_millis(20);
21 27 const BYTES_PER_PIXEL: u32 = 4;
22 const CAPTURE_WIDTH: u32 = 1280;
23 const CAPTURE_HEIGHT: u32 = 720;
24 28 const CAPTURE_FPS: u32 = 30;
25 const LARGEST_DOWNSCALED_HEIGHT: u32 = 1080;
26 29 const ASPECT_WIDTH: u32 = 16;
27 30 const ASPECT_HEIGHT: u32 = 9;
28 31 const DIRECT_FORMATS: [FrameFormat; 2] = [FrameFormat::NV12, FrameFormat::YUYV];
32 const USABLE_FORMATS: [FrameFormat; 3] = [FrameFormat::NV12, FrameFormat::YUYV, FrameFormat::MJPEG];
29 33
30 34 #[derive(Debug, Clone, PartialEq, Eq)]
31 35 pub struct CameraDevice {
@@ -33,6 +37,72 @@ pub struct CameraDevice {
33 37 pub name: String,
34 38 }
35 39
40 /// Shared capture counters for call-report stats (format + fps + decode time).
41 #[derive(Debug, Default)]
42 pub struct CameraCaptureStats {
43 format: std::sync::Mutex<String>,
44 started: std::sync::Mutex<Option<Instant>>,
45 frames: AtomicU64,
46 decode_ns: AtomicU64,
47 }
48
49 impl CameraCaptureStats {
50 pub fn new() -> Arc<Self> {
51 Arc::new(Self::default())
52 }
53
54 fn set_format(&self, label: impl Into<String>) {
55 if let Ok(mut slot) = self.format.lock() {
56 *slot = label.into();
57 }
58 if let Ok(mut started) = self.started.lock() {
59 *started = Some(Instant::now());
60 }
61 self.frames.store(0, Ordering::Relaxed);
62 self.decode_ns.store(0, Ordering::Relaxed);
63 }
64
65 fn note_frame(&self, decode: Duration) {
66 self.frames.fetch_add(1, Ordering::Relaxed);
67 self.decode_ns
68 .fetch_add(decode.as_nanos() as u64, Ordering::Relaxed);
69 }
70
71 pub fn format_label(&self) -> String {
72 self.format
73 .lock()
74 .map(|label| label.clone())
75 .unwrap_or_default()
76 }
77
78 pub fn summary(&self) -> Option<String> {
79 let label = self.format_label();
80 if label.is_empty() {
81 return None;
82 }
83 let frames = self.frames.load(Ordering::Relaxed);
84 let decode_ns = self.decode_ns.load(Ordering::Relaxed);
85 let decode_ms = if frames == 0 {
86 0.0
87 } else {
88 (decode_ns as f64 / frames as f64) / 1_000_000.0
89 };
90 let fps = self
91 .started
92 .lock()
93 .ok()
94 .and_then(|started| *started)
95 .map(|started| {
96 let seconds = started.elapsed().as_secs_f64().max(0.001);
97 frames as f64 / seconds
98 })
99 .unwrap_or(0.0);
100 Some(format!(
101 " camera={label} capture={fps:.1}fps decode={decode_ms:.1}ms"
102 ))
103 }
104 }
105
36 106 pub fn list_cameras() -> Vec<CameraDevice> {
37 107 query(ApiBackend::Auto)
38 108 .unwrap_or_default()
@@ -77,48 +147,97 @@ pub fn i420_from_rgba(rgba: &[u8], width: u32, height: u32) -> I420Buffer {
77 147
78 148 fn format_rank(frame_format: FrameFormat) -> u8 {
79 149 match frame_format {
80 FrameFormat::NV12 => 1,
150 FrameFormat::NV12 => 3,
151 FrameFormat::YUYV => 2,
152 FrameFormat::MJPEG => 1,
81 153 _ => 0,
82 154 }
83 155 }
84 156
157 fn format_short_name(frame_format: FrameFormat) -> String {
158 match frame_format {
159 FrameFormat::MJPEG => "MJPG".into(),
160 FrameFormat::NV12 => "NV12".into(),
161 FrameFormat::YUYV => "YUYV".into(),
162 other => other.to_string(),
163 }
164 }
165
166 fn format_label(format: &CameraFormat) -> String {
167 format!(
168 "{} {}x{} @{}",
169 format_short_name(format.format()),
170 format.width(),
171 format.height(),
172 format.frame_rate()
173 )
174 }
175
85 176 fn is_widescreen(width: u32, height: u32) -> bool {
86 177 width * ASPECT_HEIGHT == height * ASPECT_WIDTH
87 178 }
88 179
89 fn widescreen_tier(format: &CameraFormat) -> u8 {
180 fn widescreen_tier(format: &CameraFormat, capture_height: u32) -> u8 {
90 181 match (
91 182 is_widescreen(format.width(), format.height()),
92 183 format.height(),
93 184 ) {
94 (true, CAPTURE_HEIGHT) => 3,
95 (true, height) if height > CAPTURE_HEIGHT => 2,
185 (true, height) if height == capture_height => 3,
186 (true, height) if height > capture_height => 2,
96 187 (true, _) => 1,
97 188 (false, _) => 0,
98 189 }
99 190 }
100 191
101 fn pick_format(formats: &[CameraFormat]) -> Option<CameraFormat> {
192 fn pick_format(formats: &[CameraFormat], quality: VideoQuality) -> Option<CameraFormat> {
193 let capture_height = quality.capture_height();
194 let largest = quality.largest_sensor_height();
102 195 formats
103 196 .iter()
104 197 .copied()
105 .filter(|format| DIRECT_FORMATS.contains(&format.format()))
198 .filter(|format| USABLE_FORMATS.contains(&format.format()))
106 199 .filter(|format| format.frame_rate() >= CAPTURE_FPS)
107 200 .filter(|format| {
108 format.height() <= CAPTURE_HEIGHT
109 || (is_widescreen(format.width(), format.height())
110 && format.height() <= LARGEST_DOWNSCALED_HEIGHT)
201 format.height() <= capture_height
202 || (is_widescreen(format.width(), format.height()) && format.height() <= largest)
111 203 })
112 204 .max_by_key(|format| {
113 205 (
114 widescreen_tier(format),
115 std::cmp::Reverse(format.height().abs_diff(CAPTURE_HEIGHT)),
206 widescreen_tier(format, capture_height),
207 std::cmp::Reverse(format.height().abs_diff(capture_height)),
116 208 format_rank(format.format()),
117 209 std::cmp::Reverse(format.frame_rate()),
118 210 )
119 211 })
120 212 }
121 213
214 fn candidate_heights(quality: VideoQuality) -> Vec<u32> {
215 match quality {
216 VideoQuality::P720 => vec![720, 540, 360],
217 VideoQuality::Auto | VideoQuality::P1080 => vec![1080, 720, 540, 360],
218 }
219 }
220
221 fn preferred_candidates(quality: VideoQuality) -> Vec<CameraFormat> {
222 let mut candidates = Vec::new();
223 for height in candidate_heights(quality) {
224 let width = height * ASPECT_WIDTH / ASPECT_HEIGHT;
225 candidates.push(CameraFormat::new(
226 Resolution::new(width, height),
227 FrameFormat::MJPEG,
228 CAPTURE_FPS,
229 ));
230 for frame_format in DIRECT_FORMATS {
231 candidates.push(CameraFormat::new(
232 Resolution::new(width, height),
233 frame_format,
234 CAPTURE_FPS,
235 ));
236 }
237 }
238 candidates
239 }
240
122 241 fn even(value: u32) -> u32 {
123 242 value & !1
124 243 }
@@ -165,7 +284,8 @@ fn crop_i420(buffer: &I420Buffer, left: u32, top: u32, width: u32, height: u32)
165 284 cropped
166 285 }
167 286
168 pub(crate) fn fit_widescreen(mut buffer: I420Buffer) -> I420Buffer {
287 pub(crate) fn fit_widescreen(mut buffer: I420Buffer, quality: VideoQuality) -> I420Buffer {
288 let capture_height = quality.capture_height();
169 289 let (width, height) = (buffer.width(), buffer.height());
170 290 let (crop_width, crop_height) = if width * ASPECT_HEIGHT > height * ASPECT_WIDTH {
171 291 (even(height * ASPECT_WIDTH / ASPECT_HEIGHT), height)
@@ -182,52 +302,126 @@ pub(crate) fn fit_widescreen(mut buffer: I420Buffer) -> I420Buffer {
182 302 );
183 303 }
184 304 let (width, height) = (buffer.width(), buffer.height());
185 if height > CAPTURE_HEIGHT {
186 let scaled_width = even(width * CAPTURE_HEIGHT / height);
187 return buffer.scale(scaled_width as i32, CAPTURE_HEIGHT as i32);
305 if height > capture_height {
306 let scaled_width = even(width * capture_height / height);
307 return buffer.scale(scaled_width as i32, capture_height as i32);
188 308 }
189 309 buffer
190 310 }
191 311
192 fn open_picked_format(index: CameraIndex) -> std::result::Result<Camera, nokhwa::NokhwaError> {
193 let mut camera = Camera::new(
194 index,
195 RequestedFormat::new::<RgbAFormat>(RequestedFormatType::AbsoluteHighestFrameRate),
196 )?;
197 let formats = camera.compatible_camera_formats()?;
198 let format = pick_format(&formats).ok_or_else(|| {
199 nokhwa::NokhwaError::GeneralError("no raw camera format at 30 fps".to_owned())
200 })?;
201 camera.set_camera_requset(RequestedFormat::new::<RgbAFormat>(
202 RequestedFormatType::Exact(format),
203 ))?;
312 fn open_with_request(
313 index: CameraIndex,
314 request: RequestedFormatType,
315 ) -> std::result::Result<Camera, nokhwa::NokhwaError> {
316 let format = RequestedFormat::new::<RgbAFormat>(request);
317 let mut camera = Camera::new(index, format)?;
204 318 camera.open_stream()?;
205 319 Ok(camera)
206 320 }
207 321
208 fn open_camera(index: CameraIndex) -> std::result::Result<Camera, nokhwa::NokhwaError> {
209 if let Ok(camera) = open_picked_format(index.clone()) {
210 return Ok(camera);
322 fn device_path(index: &CameraIndex) -> Option<String> {
323 match index {
324 CameraIndex::Index(number) => Some(format!("/dev/video{number}")),
325 CameraIndex::String(text) if text.starts_with("/dev/") => Some(text.clone()),
326 CameraIndex::String(text) if text.chars().all(|c| c.is_ascii_digit()) => {
327 Some(format!("/dev/video{text}"))
328 }
329 CameraIndex::String(text) if text.starts_with("video") => Some(format!("/dev/{text}")),
330 _ => None,
211 331 }
212 let wanted = Resolution::new(CAPTURE_WIDTH, CAPTURE_HEIGHT);
213 let mut requests: Vec<RequestedFormatType> = DIRECT_FORMATS
214 .into_iter()
215 .map(|frame_format| {
216 RequestedFormatType::Closest(CameraFormat::new(wanted, frame_format, CAPTURE_FPS))
217 })
218 .collect();
219 requests.push(RequestedFormatType::AbsoluteHighestFrameRate);
332 }
333
334 fn tune_uvc_controls(index: &CameraIndex) {
335 let Some(device) = device_path(index) else {
336 return;
337 };
338 // Best effort: fixed frame rate (no auto-drop in low light) and 50 Hz mains (CH).
339 let _ = Command::new("v4l2-ctl")
340 .args([
341 "-d",
342 &device,
343 "-c",
344 "exposure_dynamic_framerate=0,power_line_frequency=1",
345 ])
346 .stdout(std::process::Stdio::null())
347 .stderr(std::process::Stdio::null())
348 .status();
349 }
350
351 fn accept_opened(index: &CameraIndex, mut camera: Camera) -> Option<(Camera, String)> {
352 let got = camera.camera_format();
353 if got.frame_rate() < CAPTURE_FPS {
354 let _ = camera.stop_stream();
355 return None;
356 }
357 tune_uvc_controls(index);
358 let label = format_label(&got);
359 Some((camera, label))
360 }
361
362 fn try_exact_or_closest(
363 index: CameraIndex,
364 format: CameraFormat,
365 ) -> std::result::Result<Camera, nokhwa::NokhwaError> {
366 match open_with_request(index.clone(), RequestedFormatType::Exact(format)) {
367 Ok(camera) => Ok(camera),
368 Err(_) => open_with_request(index, RequestedFormatType::Closest(format)),
369 }
370 }
371
372 fn open_from_list(
373 index: CameraIndex,
374 quality: VideoQuality,
375 formats: &[CameraFormat],
376 ) -> Option<(Camera, String)> {
377 let Some(wanted) = pick_format(formats, quality) else {
378 return None;
379 };
380 let camera = try_exact_or_closest(index.clone(), wanted).ok()?;
381 accept_opened(&index, camera)
382 }
383
384 fn open_camera(
385 index: CameraIndex,
386 quality: VideoQuality,
387 ) -> std::result::Result<(Camera, String), nokhwa::NokhwaError> {
388 // Probe the device list without committing to a slow Closest(NV12) open.
389 for probe in preferred_candidates(quality) {
390 let Ok(mut camera) = try_exact_or_closest(index.clone(), probe) else {
391 continue;
392 };
393 if let Ok(formats) = camera.compatible_camera_formats() {
394 let _ = camera.stop_stream();
395 drop(camera);
396 if let Some(opened) = open_from_list(index.clone(), quality, &formats) {
397 return Ok(opened);
398 }
399 } else if let Some(opened) = accept_opened(&index, camera) {
400 return Ok(opened);
401 }
402 }
403
220 404 let mut last_error = None;
221 for request in requests {
222 let format = RequestedFormat::new::<RgbAFormat>(request);
223 match Camera::new(index.clone(), format)
224 .and_then(|mut camera| camera.open_stream().map(|()| camera))
225 {
226 Ok(camera) => return Ok(camera),
405 for candidate in preferred_candidates(quality) {
406 match try_exact_or_closest(index.clone(), candidate) {
407 Ok(camera) => {
408 if let Some(opened) = accept_opened(&index, camera) {
409 return Ok(opened);
410 }
411 }
227 412 Err(error) => last_error = Some(error),
228 413 }
229 414 }
230 Err(last_error.expect("at least one request"))
415
416 // Last resort: AbsoluteHighest may still yield a usable stream on odd backends.
417 match open_with_request(index.clone(), RequestedFormatType::AbsoluteHighestFrameRate) {
418 Ok(camera) => {
419 tune_uvc_controls(&index);
420 let label = format_label(&camera.camera_format());
421 Ok((camera, label))
422 }
423 Err(error) => Err(last_error.unwrap_or(error)),
424 }
231 425 }
232 426
233 427 pub(crate) fn i420_from_nv12(data: &[u8], width: u32, height: u32) -> Option<I420Buffer> {
@@ -287,36 +481,69 @@ pub(crate) fn i420_from_yuyv(data: &[u8], width: u32, height: u32) -> Option<I42
287 481 Some(buffer)
288 482 }
289 483
484 fn i420_from_mjpeg(data: &[u8], rgba_scratch: &mut Vec<u8>) -> Option<(I420Buffer, u32, u32)> {
485 let options = DecoderOptions::default().jpeg_set_out_colorspace(ColorSpace::RGBA);
486 let mut decoder = JpegDecoder::new_with_options(ZCursor::new(data), options);
487 let pixels = decoder.decode().ok()?;
488 let info = decoder.info()?;
489 let (width, height) = (u32::from(info.width), u32::from(info.height));
490 if width < 2 || height < 2 || width % 2 != 0 || height % 2 != 0 {
491 return None;
492 }
493 let rgba_len = (width * height * BYTES_PER_PIXEL) as usize;
494 let rgba = if pixels.len() == rgba_len {
495 pixels.as_slice()
496 } else if pixels.len() == (width * height * 3) as usize {
497 rgba_scratch.clear();
498 rgba_scratch.reserve(rgba_len);
499 for chunk in pixels.chunks_exact(3) {
500 rgba_scratch.extend_from_slice(&[chunk[0], chunk[1], chunk[2], 255]);
501 }
502 rgba_scratch.as_slice()
503 } else {
504 return None;
505 };
506 Some((i420_from_rgba(rgba, width, height), width, height))
507 }
508
290 509 fn direct_i420(
291 510 frame_format: FrameFormat,
292 511 data: &[u8],
293 512 width: u32,
294 513 height: u32,
514 rgba_scratch: &mut Vec<u8>,
295 515 ) -> Option<I420Buffer> {
296 516 match frame_format {
297 517 FrameFormat::NV12 => i420_from_nv12(data, width, height),
298 518 FrameFormat::YUYV => i420_from_yuyv(data, width, height),
519 FrameFormat::MJPEG => i420_from_mjpeg(data, rgba_scratch).map(|(buffer, _, _)| buffer),
299 520 _ => None,
300 521 }
301 522 }
302 523
303 524 pub fn start_camera(
304 525 choice: &DeviceChoice,
526 quality: VideoQuality,
305 527 blur: Arc<BlurSettings>,
528 stats: Arc<CameraCaptureStats>,
529 on_opened: impl FnOnce(String) + Send + 'static,
306 530 deliver: impl FnMut(I420Buffer) + Send + 'static,
307 531 failed: impl FnOnce(String) + Send + 'static,
308 532 ) -> Result<Capture> {
309 533 let index = camera_index(choice);
310 534 Capture::spawn_thread("camera", move |stop| {
311 let mut camera = match open_camera(index) {
312 Ok(camera) => camera,
535 let (mut camera, label) = match open_camera(index, quality) {
536 Ok(opened) => opened,
313 537 Err(error) => return failed(error.to_string()),
314 538 };
539 stats.set_format(&label);
540 on_opened(label);
315 541 let effects = match EffectsThread::spawn(blur, deliver) {
316 542 Ok(effects) => effects,
317 543 Err(error) => return failed(format!("effects thread: {error}")),
318 544 };
319 545 let mut warned_undecodable = false;
546 let mut rgba_scratch = Vec::new();
320 547 while !stop.load(Ordering::SeqCst) {
321 548 let Ok(frame) = camera.frame() else {
322 549 std::thread::sleep(RETRY_PAUSE);
@@ -327,23 +554,30 @@ pub fn start_camera(
327 554 if width < 2 || height < 2 || width % 2 != 0 || height % 2 != 0 {
328 555 continue;
329 556 }
330 let buffer =
331 match direct_i420(frame.source_frame_format(), frame.buffer(), width, height) {
332 Some(buffer) => buffer,
333 None => {
334 let Ok(decoded) = frame.decode_image::<RgbAFormat>() else {
335 if !std::mem::replace(&mut warned_undecodable, true) {
336 eprintln!(
337 "calls: camera delivers {} and no decoder is available",
338 frame.source_frame_format()
339 );
340 }
341 continue;
342 };
343 i420_from_rgba(&decoded.into_raw(), width, height)
344 }
345 };
346 effects.submit(fit_widescreen(buffer));
557 let started = Instant::now();
558 let buffer = match direct_i420(
559 frame.source_frame_format(),
560 frame.buffer(),
561 width,
562 height,
563 &mut rgba_scratch,
564 ) {
565 Some(buffer) => buffer,
566 None => {
567 let Ok(decoded) = frame.decode_image::<RgbAFormat>() else {
568 if !std::mem::replace(&mut warned_undecodable, true) {
569 eprintln!(
570 "calls: camera delivers {} and no decoder is available",
571 frame.source_frame_format()
572 );
573 }
574 continue;
575 };
576 i420_from_rgba(&decoded.into_raw(), width, height)
577 }
578 };
579 stats.note_frame(started.elapsed());
580 effects.submit(fit_widescreen(buffer, quality));
347 581 }
348 582 let _ = camera.stop_stream();
349 583 })
@@ -414,20 +648,52 @@ mod tests {
414 648 }
415 649
416 650 #[test]
417 fn a_c920_like_list_picks_the_raw_format_that_runs_at_30_fps() {
651 fn a_c920_like_list_picks_hd_mjpeg_at_30_fps_over_slow_raw() {
418 652 let formats = [
419 653 format(1280, 720, FrameFormat::YUYV, 10),
420 654 format(640, 480, FrameFormat::YUYV, 30),
421 655 format(1280, 720, FrameFormat::MJPEG, 30),
422 656 ];
423 657 assert_eq!(
424 pick_format(&formats),
425 Some(format(640, 480, FrameFormat::YUYV, 30))
658 pick_format(&formats, VideoQuality::P720),
659 Some(format(1280, 720, FrameFormat::MJPEG, 30))
660 );
661 }
662
663 #[test]
664 fn raw_at_the_same_height_beats_mjpeg() {
665 let formats = [
666 format(1280, 720, FrameFormat::MJPEG, 30),
667 format(1280, 720, FrameFormat::NV12, 30),
668 ];
669 assert_eq!(
670 pick_format(&formats, VideoQuality::P720),
671 Some(format(1280, 720, FrameFormat::NV12, 30))
672 );
673 }
674
675 #[test]
676 fn a_c930e_like_list_picks_mjpeg_1080_for_auto() {
677 let formats = [
678 format(1920, 1080, FrameFormat::YUYV, 5),
679 format(1280, 720, FrameFormat::YUYV, 10),
680 format(640, 360, FrameFormat::YUYV, 30),
681 format(1920, 1080, FrameFormat::MJPEG, 30),
682 format(1280, 720, FrameFormat::MJPEG, 30),
683 format(960, 540, FrameFormat::MJPEG, 30),
684 ];
685 assert_eq!(
686 pick_format(&formats, VideoQuality::Auto),
687 Some(format(1920, 1080, FrameFormat::MJPEG, 30))
688 );
689 assert_eq!(
690 pick_format(&formats, VideoQuality::P720),
691 Some(format(1280, 720, FrameFormat::MJPEG, 30))
426 692 );
427 693 }
428 694
429 695 #[test]
430 fn the_largest_height_up_to_720_wins_then_nv12() {
696 fn auto_prefers_1080p_nv12_over_720p() {
431 697 let formats = [
432 698 format(1920, 1080, FrameFormat::NV12, 30),
433 699 format(640, 480, FrameFormat::NV12, 30),
@@ -435,7 +701,11 @@ mod tests {
435 701 format(1280, 720, FrameFormat::NV12, 30),
436 702 ];
437 703 assert_eq!(
438 pick_format(&formats),
704 pick_format(&formats, VideoQuality::Auto),
705 Some(format(1920, 1080, FrameFormat::NV12, 30))
706 );
707 assert_eq!(
708 pick_format(&formats, VideoQuality::P720),
439 709 Some(format(1280, 720, FrameFormat::NV12, 30))
440 710 );
441 711 }
@@ -448,20 +718,30 @@ mod tests {
448 718 format(640, 480, FrameFormat::NV12, 30),
449 719 ];
450 720 assert_eq!(
451 pick_format(&formats),
721 pick_format(&formats, VideoQuality::P720),
452 722 Some(format(1280, 720, FrameFormat::YUYV, 30))
453 723 );
454 724 }
455 725
456 726 #[test]
457 fn without_720p_the_order_is_1080p_then_360p_then_4_3() {
727 fn locked_720_keeps_1080_as_downscale_candidate_but_prefers_exact_720() {
458 728 let full_hd = format(1920, 1080, FrameFormat::NV12, 30);
729 let hd = format(1280, 720, FrameFormat::NV12, 30);
459 730 let small = format(640, 360, FrameFormat::NV12, 30);
460 731 let classic = format(960, 720, FrameFormat::NV12, 30);
461 assert_eq!(pick_format(&[classic, small, full_hd]), Some(full_hd));
462 assert_eq!(pick_format(&[classic, small]), Some(small));
463 732 assert_eq!(
464 pick_format(&[classic, format(2560, 1440, FrameFormat::NV12, 30)]),
733 pick_format(&[classic, small, full_hd], VideoQuality::Auto),
734 Some(full_hd)
735 );
736 assert_eq!(
737 pick_format(&[classic, small, full_hd, hd], VideoQuality::P720),
738 Some(hd)
739 );
740 assert_eq!(
741 pick_format(
742 &[classic, format(2560, 1440, FrameFormat::NV12, 30)],
743 VideoQuality::P720
744 ),
465 745 Some(classic)
466 746 );
467 747 }
@@ -481,7 +761,7 @@ mod tests {
481 761
482 762 #[test]
483 763 fn a_4_3_frame_is_centre_cropped_to_16_9() {
484 let cropped = fit_widescreen(gradient(960, 720));
764 let cropped = fit_widescreen(gradient(960, 720), VideoQuality::P720);
485 765 assert_eq!((cropped.width(), cropped.height()), (960, 540));
486 766 let (stride_y, stride_u, _) = cropped.strides();
487 767 let (plane_y, plane_u, _) = cropped.data();
@@ -492,24 +772,29 @@ mod tests {
492 772 }
493 773
494 774 #[test]
495 fn a_widescreen_frame_passes_and_1080p_is_scaled_to_720p() {
496 assert_eq!(fit_widescreen(gradient(1280, 720)).width(), 1280);
497 let scaled = fit_widescreen(gradient(1920, 1080));
775 fn auto_keeps_1080p_and_720_lock_scales_it_down() {
776 assert_eq!(
777 fit_widescreen(gradient(1280, 720), VideoQuality::Auto).width(),
778 1280
779 );
780 let kept = fit_widescreen(gradient(1920, 1080), VideoQuality::Auto);
781 assert_eq!((kept.width(), kept.height()), (1920, 1080));
782 let scaled = fit_widescreen(gradient(1920, 1080), VideoQuality::P720);
498 783 assert_eq!((scaled.width(), scaled.height()), (1280, 720));
499 let wide = fit_widescreen(gradient(2560, 1080));
500 assert_eq!((wide.width(), wide.height()), (1280, 720));
501 let classic = fit_widescreen(gradient(640, 480));
784 let wide = fit_widescreen(gradient(2560, 1440), VideoQuality::Auto);
785 assert_eq!((wide.width(), wide.height()), (1920, 1080));
786 let classic = fit_widescreen(gradient(640, 480), VideoQuality::Auto);
502 787 assert_eq!((classic.width(), classic.height()), (640, 360));
503 788 }
504 789
505 790 #[test]
506 791 fn no_usable_format_picks_nothing() {
507 792 let formats = [
508 format(1280, 720, FrameFormat::MJPEG, 30),
793 format(1280, 720, FrameFormat::MJPEG, 15),
509 794 format(1280, 720, FrameFormat::YUYV, 15),
510 795 ];
511 assert_eq!(pick_format(&formats), None);
512 assert_eq!(pick_format(&[]), None);
796 assert_eq!(pick_format(&formats, VideoQuality::Auto), None);
797 assert_eq!(pick_format(&[], VideoQuality::Auto), None);
513 798 }
514 799
515 800 #[test]
@@ -527,4 +812,79 @@ mod tests {
527 812 CameraIndex::String(_)
528 813 ));
529 814 }
815
816 #[test]
817 fn mjpeg_decodes_to_i420() {
818 // Minimal valid grayscale JPEG is awkward; encode via `image` crate.
819 let mut rgb = image::RgbImage::new(16, 16);
820 for pixel in rgb.pixels_mut() {
821 *pixel = image::Rgb([40, 80, 120]);
822 }
823 let mut jpeg = Vec::new();
824 image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, 90)
825 .encode(rgb.as_raw(), 16, 16, image::ExtendedColorType::Rgb8)
826 .expect("encode");
827 let mut scratch = Vec::new();
828 let (buffer, width, height) = i420_from_mjpeg(&jpeg, &mut scratch).expect("mjpeg decodes");
829 assert_eq!((width, height), (16, 16));
830 assert_eq!((buffer.width(), buffer.height()), (16, 16));
831 }
832
833 #[test]
834 #[ignore = "timing; run with --release --ignored"]
835 fn mjpeg_1080p_decode_stays_under_fifteen_ms() {
836 let mut rgb = image::RgbImage::new(1920, 1080);
837 for (index, pixel) in rgb.pixels_mut().enumerate() {
838 let value = (index % 255) as u8;
839 *pixel = image::Rgb([value, value.wrapping_add(40), value.wrapping_add(80)]);
840 }
841 let mut jpeg = Vec::new();
842 image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, 85)
843 .encode(rgb.as_raw(), 1920, 1080, image::ExtendedColorType::Rgb8)
844 .expect("encode");
845 let mut scratch = Vec::new();
846 // Warm caches / CPU, then time a steady batch (30 fps allows ~33 ms/frame).
847 for _ in 0..3 {
848 let _ = i420_from_mjpeg(&jpeg, &mut scratch).expect("decode");
849 }
850 let started = Instant::now();
851 for _ in 0..10 {
852 let _ = i420_from_mjpeg(&jpeg, &mut scratch).expect("decode");
853 }
854 let average = started.elapsed() / 10;
855 assert!(
856 average < Duration::from_millis(20),
857 "average decode {average:?} exceeds 20 ms"
858 );
859 }
860
861 #[test]
862 #[ignore = "needs a connected camera"]
863 fn open_picks_at_least_thirty_fps_when_available() {
864 if list_cameras().is_empty() {
865 return;
866 }
867 let (mut camera, label) =
868 open_camera(CameraIndex::Index(0), VideoQuality::Auto).expect("camera opens");
869 assert!(
870 camera.camera_format().frame_rate() >= CAPTURE_FPS,
871 "opened {label} under 30 fps"
872 );
873 // Warm up buffers, then count for one second.
874 for _ in 0..10 {
875 let _ = camera.frame();
876 }
877 let deadline = Instant::now() + Duration::from_secs(1);
878 let mut frames = 0u32;
879 while Instant::now() < deadline {
880 if camera.frame().is_ok() {
881 frames += 1;
882 }
883 }
884 let _ = camera.stop_stream();
885 assert!(
886 frames >= 20,
887 "expected >= 20 frames in 1 s from {label}, got {frames}"
888 );
889 }
530 890 }
@@ -1,5 +1,7 @@
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 _};
@@ -9,23 +11,25 @@ use nokhwa::utils::{
9 Resolution,
11 Resolution,
10};
12};
11use nokhwa::{Camera, query};
13use nokhwa::{Camera, query};
12use std::sync::atomic::Ordering;
14use zune_core::bytestream::ZCursor;
15use zune_core::colorspace::ColorSpace;
16use zune_core::options::DecoderOptions;
17use zune_jpeg::JpegDecoder;
13
18
14use crate::blur::BlurSettings;
19use crate::blur::BlurSettings;
15use crate::capture::Capture;
20use crate::capture::Capture;
16use crate::devices::{DeviceChoice, DeviceEntry};
21use crate::devices::{DeviceChoice, DeviceEntry};
17use crate::effects::EffectsThread;
22use crate::effects::EffectsThread;
18use crate::error::{Error, Result};
23use crate::error::{Error, Result};
24use crate::video_quality::VideoQuality;
19
25
20const RETRY_PAUSE: Duration = Duration::from_millis(20);
26const RETRY_PAUSE: Duration = Duration::from_millis(20);
21const BYTES_PER_PIXEL: u32 = 4;
27const BYTES_PER_PIXEL: u32 = 4;
22const CAPTURE_WIDTH: u32 = 1280;
23const CAPTURE_HEIGHT: u32 = 720;
24const CAPTURE_FPS: u32 = 30;
28const CAPTURE_FPS: u32 = 30;
25const LARGEST_DOWNSCALED_HEIGHT: u32 = 1080;
26const ASPECT_WIDTH: u32 = 16;
29const ASPECT_WIDTH: u32 = 16;
27const ASPECT_HEIGHT: u32 = 9;
30const ASPECT_HEIGHT: u32 = 9;
28const DIRECT_FORMATS: [FrameFormat; 2] = [FrameFormat::NV12, FrameFormat::YUYV];
31const DIRECT_FORMATS: [FrameFormat; 2] = [FrameFormat::NV12, FrameFormat::YUYV];
32const USABLE_FORMATS: [FrameFormat; 3] = [FrameFormat::NV12, FrameFormat::YUYV, FrameFormat::MJPEG];
29
33
30#[derive(Debug, Clone, PartialEq, Eq)]
34#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct CameraDevice {
35pub struct CameraDevice {
@@ -33,6 +37,72 @@ pub struct CameraDevice {
33 pub name: String,
37 pub name: String,
34}
38}
35
39
40/// Shared capture counters for call-report stats (format + fps + decode time).
41#[derive(Debug, Default)]
42pub struct CameraCaptureStats {
43 format: std::sync::Mutex<String>,
44 started: std::sync::Mutex<Option<Instant>>,
45 frames: AtomicU64,
46 decode_ns: AtomicU64,
47}
48
49impl CameraCaptureStats {
50 pub fn new() -> Arc<Self> {
51 Arc::new(Self::default())
52 }
53
54 fn set_format(&self, label: impl Into<String>) {
55 if let Ok(mut slot) = self.format.lock() {
56 *slot = label.into();
57 }
58 if let Ok(mut started) = self.started.lock() {
59 *started = Some(Instant::now());
60 }
61 self.frames.store(0, Ordering::Relaxed);
62 self.decode_ns.store(0, Ordering::Relaxed);
63 }
64
65 fn note_frame(&self, decode: Duration) {
66 self.frames.fetch_add(1, Ordering::Relaxed);
67 self.decode_ns
68 .fetch_add(decode.as_nanos() as u64, Ordering::Relaxed);
69 }
70
71 pub fn format_label(&self) -> String {
72 self.format
73 .lock()
74 .map(|label| label.clone())
75 .unwrap_or_default()
76 }
77
78 pub fn summary(&self) -> Option<String> {
79 let label = self.format_label();
80 if label.is_empty() {
81 return None;
82 }
83 let frames = self.frames.load(Ordering::Relaxed);
84 let decode_ns = self.decode_ns.load(Ordering::Relaxed);
85 let decode_ms = if frames == 0 {
86 0.0
87 } else {
88 (decode_ns as f64 / frames as f64) / 1_000_000.0
89 };
90 let fps = self
91 .started
92 .lock()
93 .ok()
94 .and_then(|started| *started)
95 .map(|started| {
96 let seconds = started.elapsed().as_secs_f64().max(0.001);
97 frames as f64 / seconds
98 })
99 .unwrap_or(0.0);
100 Some(format!(
101 " camera={label} capture={fps:.1}fps decode={decode_ms:.1}ms"
102 ))
103 }
104}
105
36pub fn list_cameras() -> Vec<CameraDevice> {
106pub fn list_cameras() -> Vec<CameraDevice> {
37 query(ApiBackend::Auto)
107 query(ApiBackend::Auto)
38 .unwrap_or_default()
108 .unwrap_or_default()
@@ -77,48 +147,97 @@ pub fn i420_from_rgba(rgba: &[u8], width: u32, height: u32) -> I420Buffer {
77
147
78fn format_rank(frame_format: FrameFormat) -> u8 {
148fn format_rank(frame_format: FrameFormat) -> u8 {
79 match frame_format {
149 match frame_format {
80 FrameFormat::NV12 => 1,
150 FrameFormat::NV12 => 3,
151 FrameFormat::YUYV => 2,
152 FrameFormat::MJPEG => 1,
81 _ => 0,
153 _ => 0,
82 }
154 }
83}
155}
84
156
157fn format_short_name(frame_format: FrameFormat) -> String {
158 match frame_format {
159 FrameFormat::MJPEG => "MJPG".into(),
160 FrameFormat::NV12 => "NV12".into(),
161 FrameFormat::YUYV => "YUYV".into(),
162 other => other.to_string(),
163 }
164}
165
166fn format_label(format: &CameraFormat) -> String {
167 format!(
168 "{} {}x{} @{}",
169 format_short_name(format.format()),
170 format.width(),
171 format.height(),
172 format.frame_rate()
173 )
174}
175
85fn is_widescreen(width: u32, height: u32) -> bool {
176fn is_widescreen(width: u32, height: u32) -> bool {
86 width * ASPECT_HEIGHT == height * ASPECT_WIDTH
177 width * ASPECT_HEIGHT == height * ASPECT_WIDTH
87}
178}
88
179
89fn widescreen_tier(format: &CameraFormat) -> u8 {
180fn widescreen_tier(format: &CameraFormat, capture_height: u32) -> u8 {
90 match (
181 match (
91 is_widescreen(format.width(), format.height()),
182 is_widescreen(format.width(), format.height()),
92 format.height(),
183 format.height(),
93 ) {
184 ) {
94 (true, CAPTURE_HEIGHT) => 3,
185 (true, height) if height == capture_height => 3,
95 (true, height) if height > CAPTURE_HEIGHT => 2,
186 (true, height) if height > capture_height => 2,
96 (true, _) => 1,
187 (true, _) => 1,
97 (false, _) => 0,
188 (false, _) => 0,
98 }
189 }
99}
190}
100
191
101fn pick_format(formats: &[CameraFormat]) -> Option<CameraFormat> {
192fn pick_format(formats: &[CameraFormat], quality: VideoQuality) -> Option<CameraFormat> {
193 let capture_height = quality.capture_height();
194 let largest = quality.largest_sensor_height();
102 formats
195 formats
103 .iter()
196 .iter()
104 .copied()
197 .copied()
105 .filter(|format| DIRECT_FORMATS.contains(&format.format()))
198 .filter(|format| USABLE_FORMATS.contains(&format.format()))
106 .filter(|format| format.frame_rate() >= CAPTURE_FPS)
199 .filter(|format| format.frame_rate() >= CAPTURE_FPS)
107 .filter(|format| {
200 .filter(|format| {
108 format.height() <= CAPTURE_HEIGHT
201 format.height() <= capture_height
109 || (is_widescreen(format.width(), format.height())
202 || (is_widescreen(format.width(), format.height()) && format.height() <= largest)
110 && format.height() <= LARGEST_DOWNSCALED_HEIGHT)
111 })
203 })
112 .max_by_key(|format| {
204 .max_by_key(|format| {
113 (
205 (
114 widescreen_tier(format),
206 widescreen_tier(format, capture_height),
115 std::cmp::Reverse(format.height().abs_diff(CAPTURE_HEIGHT)),
207 std::cmp::Reverse(format.height().abs_diff(capture_height)),
116 format_rank(format.format()),
208 format_rank(format.format()),
117 std::cmp::Reverse(format.frame_rate()),
209 std::cmp::Reverse(format.frame_rate()),
118 )
210 )
119 })
211 })
120}
212}
121
213
214fn candidate_heights(quality: VideoQuality) -> Vec<u32> {
215 match quality {
216 VideoQuality::P720 => vec![720, 540, 360],
217 VideoQuality::Auto | VideoQuality::P1080 => vec![1080, 720, 540, 360],
218 }
219}
220
221fn preferred_candidates(quality: VideoQuality) -> Vec<CameraFormat> {
222 let mut candidates = Vec::new();
223 for height in candidate_heights(quality) {
224 let width = height * ASPECT_WIDTH / ASPECT_HEIGHT;
225 candidates.push(CameraFormat::new(
226 Resolution::new(width, height),
227 FrameFormat::MJPEG,
228 CAPTURE_FPS,
229 ));
230 for frame_format in DIRECT_FORMATS {
231 candidates.push(CameraFormat::new(
232 Resolution::new(width, height),
233 frame_format,
234 CAPTURE_FPS,
235 ));
236 }
237 }
238 candidates
239}
240
122fn even(value: u32) -> u32 {
241fn even(value: u32) -> u32 {
123 value & !1
242 value & !1
124}
243}
@@ -165,7 +284,8 @@ fn crop_i420(buffer: &I420Buffer, left: u32, top: u32, width: u32, height: u32)
165 cropped
284 cropped
166}
285}
167
286
168pub(crate) fn fit_widescreen(mut buffer: I420Buffer) -> I420Buffer {
287pub(crate) fn fit_widescreen(mut buffer: I420Buffer, quality: VideoQuality) -> I420Buffer {
288 let capture_height = quality.capture_height();
169 let (width, height) = (buffer.width(), buffer.height());
289 let (width, height) = (buffer.width(), buffer.height());
170 let (crop_width, crop_height) = if width * ASPECT_HEIGHT > height * ASPECT_WIDTH {
290 let (crop_width, crop_height) = if width * ASPECT_HEIGHT > height * ASPECT_WIDTH {
171 (even(height * ASPECT_WIDTH / ASPECT_HEIGHT), height)
291 (even(height * ASPECT_WIDTH / ASPECT_HEIGHT), height)
@@ -182,52 +302,126 @@ pub(crate) fn fit_widescreen(mut buffer: I420Buffer) -> I420Buffer {
182 );
302 );
183 }
303 }
184 let (width, height) = (buffer.width(), buffer.height());
304 let (width, height) = (buffer.width(), buffer.height());
185 if height > CAPTURE_HEIGHT {
305 if height > capture_height {
186 let scaled_width = even(width * CAPTURE_HEIGHT / height);
306 let scaled_width = even(width * capture_height / height);
187 return buffer.scale(scaled_width as i32, CAPTURE_HEIGHT as i32);
307 return buffer.scale(scaled_width as i32, capture_height as i32);
188 }
308 }
189 buffer
309 buffer
190}
310}
191
311
192fn open_picked_format(index: CameraIndex) -> std::result::Result<Camera, nokhwa::NokhwaError> {
312fn open_with_request(
193 let mut camera = Camera::new(
313 index: CameraIndex,
194 index,
314 request: RequestedFormatType,
195 RequestedFormat::new::<RgbAFormat>(RequestedFormatType::AbsoluteHighestFrameRate),
315) -> std::result::Result<Camera, nokhwa::NokhwaError> {
196 )?;
316 let format = RequestedFormat::new::<RgbAFormat>(request);
197 let formats = camera.compatible_camera_formats()?;
317 let mut camera = Camera::new(index, format)?;
198 let format = pick_format(&formats).ok_or_else(|| {
199 nokhwa::NokhwaError::GeneralError("no raw camera format at 30 fps".to_owned())
200 })?;
201 camera.set_camera_requset(RequestedFormat::new::<RgbAFormat>(
202 RequestedFormatType::Exact(format),
203 ))?;
204 camera.open_stream()?;
318 camera.open_stream()?;
205 Ok(camera)
319 Ok(camera)
206}
320}
207
321
208fn open_camera(index: CameraIndex) -> std::result::Result<Camera, nokhwa::NokhwaError> {
322fn device_path(index: &CameraIndex) -> Option<String> {
209 if let Ok(camera) = open_picked_format(index.clone()) {
323 match index {
210 return Ok(camera);
324 CameraIndex::Index(number) => Some(format!("/dev/video{number}")),
325 CameraIndex::String(text) if text.starts_with("/dev/") => Some(text.clone()),
326 CameraIndex::String(text) if text.chars().all(|c| c.is_ascii_digit()) => {
327 Some(format!("/dev/video{text}"))
328 }
329 CameraIndex::String(text) if text.starts_with("video") => Some(format!("/dev/{text}")),
330 _ => None,
211 }
331 }
212 let wanted = Resolution::new(CAPTURE_WIDTH, CAPTURE_HEIGHT);
332}
213 let mut requests: Vec<RequestedFormatType> = DIRECT_FORMATS
333
214 .into_iter()
334fn tune_uvc_controls(index: &CameraIndex) {
215 .map(|frame_format| {
335 let Some(device) = device_path(index) else {
216 RequestedFormatType::Closest(CameraFormat::new(wanted, frame_format, CAPTURE_FPS))
336 return;
217 })
337 };
218 .collect();
338 // Best effort: fixed frame rate (no auto-drop in low light) and 50 Hz mains (CH).
219 requests.push(RequestedFormatType::AbsoluteHighestFrameRate);
339 let _ = Command::new("v4l2-ctl")
340 .args([
341 "-d",
342 &device,
343 "-c",
344 "exposure_dynamic_framerate=0,power_line_frequency=1",
345 ])
346 .stdout(std::process::Stdio::null())
347 .stderr(std::process::Stdio::null())
348 .status();
349}
350
351fn accept_opened(index: &CameraIndex, mut camera: Camera) -> Option<(Camera, String)> {
352 let got = camera.camera_format();
353 if got.frame_rate() < CAPTURE_FPS {
354 let _ = camera.stop_stream();
355 return None;
356 }
357 tune_uvc_controls(index);
358 let label = format_label(&got);
359 Some((camera, label))
360}
361
362fn try_exact_or_closest(
363 index: CameraIndex,
364 format: CameraFormat,
365) -> std::result::Result<Camera, nokhwa::NokhwaError> {
366 match open_with_request(index.clone(), RequestedFormatType::Exact(format)) {
367 Ok(camera) => Ok(camera),
368 Err(_) => open_with_request(index, RequestedFormatType::Closest(format)),
369 }
370}
371
372fn open_from_list(
373 index: CameraIndex,
374 quality: VideoQuality,
375 formats: &[CameraFormat],
376) -> Option<(Camera, String)> {
377 let Some(wanted) = pick_format(formats, quality) else {
378 return None;
379 };
380 let camera = try_exact_or_closest(index.clone(), wanted).ok()?;
381 accept_opened(&index, camera)
382}
383
384fn open_camera(
385 index: CameraIndex,
386 quality: VideoQuality,
387) -> std::result::Result<(Camera, String), nokhwa::NokhwaError> {
388 // Probe the device list without committing to a slow Closest(NV12) open.
389 for probe in preferred_candidates(quality) {
390 let Ok(mut camera) = try_exact_or_closest(index.clone(), probe) else {
391 continue;
392 };
393 if let Ok(formats) = camera.compatible_camera_formats() {
394 let _ = camera.stop_stream();
395 drop(camera);
396 if let Some(opened) = open_from_list(index.clone(), quality, &formats) {
397 return Ok(opened);
398 }
399 } else if let Some(opened) = accept_opened(&index, camera) {
400 return Ok(opened);
401 }
402 }
403
220 let mut last_error = None;
404 let mut last_error = None;
221 for request in requests {
405 for candidate in preferred_candidates(quality) {
222 let format = RequestedFormat::new::<RgbAFormat>(request);
406 match try_exact_or_closest(index.clone(), candidate) {
223 match Camera::new(index.clone(), format)
407 Ok(camera) => {
224 .and_then(|mut camera| camera.open_stream().map(|()| camera))
408 if let Some(opened) = accept_opened(&index, camera) {
225 {
409 return Ok(opened);
226 Ok(camera) => return Ok(camera),
410 }
411 }
227 Err(error) => last_error = Some(error),
412 Err(error) => last_error = Some(error),
228 }
413 }
229 }
414 }
230 Err(last_error.expect("at least one request"))
415
416 // Last resort: AbsoluteHighest may still yield a usable stream on odd backends.
417 match open_with_request(index.clone(), RequestedFormatType::AbsoluteHighestFrameRate) {
418 Ok(camera) => {
419 tune_uvc_controls(&index);
420 let label = format_label(&camera.camera_format());
421 Ok((camera, label))
422 }
423 Err(error) => Err(last_error.unwrap_or(error)),
424 }
231}
425}
232
426
233pub(crate) fn i420_from_nv12(data: &[u8], width: u32, height: u32) -> Option<I420Buffer> {
427pub(crate) fn i420_from_nv12(data: &[u8], width: u32, height: u32) -> Option<I420Buffer> {
@@ -287,36 +481,69 @@ pub(crate) fn i420_from_yuyv(data: &[u8], width: u32, height: u32) -> Option<I42
287 Some(buffer)
481 Some(buffer)
288}
482}
289
483
484fn i420_from_mjpeg(data: &[u8], rgba_scratch: &mut Vec<u8>) -> Option<(I420Buffer, u32, u32)> {
485 let options = DecoderOptions::default().jpeg_set_out_colorspace(ColorSpace::RGBA);
486 let mut decoder = JpegDecoder::new_with_options(ZCursor::new(data), options);
487 let pixels = decoder.decode().ok()?;
488 let info = decoder.info()?;
489 let (width, height) = (u32::from(info.width), u32::from(info.height));
490 if width < 2 || height < 2 || width % 2 != 0 || height % 2 != 0 {
491 return None;
492 }
493 let rgba_len = (width * height * BYTES_PER_PIXEL) as usize;
494 let rgba = if pixels.len() == rgba_len {
495 pixels.as_slice()
496 } else if pixels.len() == (width * height * 3) as usize {
497 rgba_scratch.clear();
498 rgba_scratch.reserve(rgba_len);
499 for chunk in pixels.chunks_exact(3) {
500 rgba_scratch.extend_from_slice(&[chunk[0], chunk[1], chunk[2], 255]);
501 }
502 rgba_scratch.as_slice()
503 } else {
504 return None;
505 };
506 Some((i420_from_rgba(rgba, width, height), width, height))
507}
508
290fn direct_i420(
509fn direct_i420(
291 frame_format: FrameFormat,
510 frame_format: FrameFormat,
292 data: &[u8],
511 data: &[u8],
293 width: u32,
512 width: u32,
294 height: u32,
513 height: u32,
514 rgba_scratch: &mut Vec<u8>,
295) -> Option<I420Buffer> {
515) -> Option<I420Buffer> {
296 match frame_format {
516 match frame_format {
297 FrameFormat::NV12 => i420_from_nv12(data, width, height),
517 FrameFormat::NV12 => i420_from_nv12(data, width, height),
298 FrameFormat::YUYV => i420_from_yuyv(data, width, height),
518 FrameFormat::YUYV => i420_from_yuyv(data, width, height),
519 FrameFormat::MJPEG => i420_from_mjpeg(data, rgba_scratch).map(|(buffer, _, _)| buffer),
299 _ => None,
520 _ => None,
300 }
521 }
301}
522}
302
523
303pub fn start_camera(
524pub fn start_camera(
304 choice: &DeviceChoice,
525 choice: &DeviceChoice,
526 quality: VideoQuality,
305 blur: Arc<BlurSettings>,
527 blur: Arc<BlurSettings>,
528 stats: Arc<CameraCaptureStats>,
529 on_opened: impl FnOnce(String) + Send + 'static,
306 deliver: impl FnMut(I420Buffer) + Send + 'static,
530 deliver: impl FnMut(I420Buffer) + Send + 'static,
307 failed: impl FnOnce(String) + Send + 'static,
531 failed: impl FnOnce(String) + Send + 'static,
308) -> Result<Capture> {
532) -> Result<Capture> {
309 let index = camera_index(choice);
533 let index = camera_index(choice);
310 Capture::spawn_thread("camera", move |stop| {
534 Capture::spawn_thread("camera", move |stop| {
311 let mut camera = match open_camera(index) {
535 let (mut camera, label) = match open_camera(index, quality) {
312 Ok(camera) => camera,
536 Ok(opened) => opened,
313 Err(error) => return failed(error.to_string()),
537 Err(error) => return failed(error.to_string()),
314 };
538 };
539 stats.set_format(&label);
540 on_opened(label);
315 let effects = match EffectsThread::spawn(blur, deliver) {
541 let effects = match EffectsThread::spawn(blur, deliver) {
316 Ok(effects) => effects,
542 Ok(effects) => effects,
317 Err(error) => return failed(format!("effects thread: {error}")),
543 Err(error) => return failed(format!("effects thread: {error}")),
318 };
544 };
319 let mut warned_undecodable = false;
545 let mut warned_undecodable = false;
546 let mut rgba_scratch = Vec::new();
320 while !stop.load(Ordering::SeqCst) {
547 while !stop.load(Ordering::SeqCst) {
321 let Ok(frame) = camera.frame() else {
548 let Ok(frame) = camera.frame() else {
322 std::thread::sleep(RETRY_PAUSE);
549 std::thread::sleep(RETRY_PAUSE);
@@ -327,23 +554,30 @@ pub fn start_camera(
327 if width < 2 || height < 2 || width % 2 != 0 || height % 2 != 0 {
554 if width < 2 || height < 2 || width % 2 != 0 || height % 2 != 0 {
328 continue;
555 continue;
329 }
556 }
330 let buffer =
557 let started = Instant::now();
331 match direct_i420(frame.source_frame_format(), frame.buffer(), width, height) {
558 let buffer = match direct_i420(
332 Some(buffer) => buffer,
559 frame.source_frame_format(),
333 None => {
560 frame.buffer(),
334 let Ok(decoded) = frame.decode_image::<RgbAFormat>() else {
561 width,
335 if !std::mem::replace(&mut warned_undecodable, true) {
562 height,
336 eprintln!(
563 &mut rgba_scratch,
337 "calls: camera delivers {} and no decoder is available",
564 ) {
338 frame.source_frame_format()
565 Some(buffer) => buffer,
339 );
566 None => {
340 }
567 let Ok(decoded) = frame.decode_image::<RgbAFormat>() else {
341 continue;
568 if !std::mem::replace(&mut warned_undecodable, true) {
342 };
569 eprintln!(
343 i420_from_rgba(&decoded.into_raw(), width, height)
570 "calls: camera delivers {} and no decoder is available",
344 }
571 frame.source_frame_format()
345 };
572 );
346 effects.submit(fit_widescreen(buffer));
573 }
574 continue;
575 };
576 i420_from_rgba(&decoded.into_raw(), width, height)
577 }
578 };
579 stats.note_frame(started.elapsed());
580 effects.submit(fit_widescreen(buffer, quality));
347 }
581 }
348 let _ = camera.stop_stream();
582 let _ = camera.stop_stream();
349 })
583 })
@@ -414,20 +648,52 @@ mod tests {
414 }
648 }
415
649
416 #[test]
650 #[test]
417 fn a_c920_like_list_picks_the_raw_format_that_runs_at_30_fps() {
651 fn a_c920_like_list_picks_hd_mjpeg_at_30_fps_over_slow_raw() {
418 let formats = [
652 let formats = [
419 format(1280, 720, FrameFormat::YUYV, 10),
653 format(1280, 720, FrameFormat::YUYV, 10),
420 format(640, 480, FrameFormat::YUYV, 30),
654 format(640, 480, FrameFormat::YUYV, 30),
421 format(1280, 720, FrameFormat::MJPEG, 30),
655 format(1280, 720, FrameFormat::MJPEG, 30),
422 ];
656 ];
423 assert_eq!(
657 assert_eq!(
424 pick_format(&formats),
658 pick_format(&formats, VideoQuality::P720),
425 Some(format(640, 480, FrameFormat::YUYV, 30))
659 Some(format(1280, 720, FrameFormat::MJPEG, 30))
660 );
661 }
662
663 #[test]
664 fn raw_at_the_same_height_beats_mjpeg() {
665 let formats = [
666 format(1280, 720, FrameFormat::MJPEG, 30),
667 format(1280, 720, FrameFormat::NV12, 30),
668 ];
669 assert_eq!(
670 pick_format(&formats, VideoQuality::P720),
671 Some(format(1280, 720, FrameFormat::NV12, 30))
672 );
673 }
674
675 #[test]
676 fn a_c930e_like_list_picks_mjpeg_1080_for_auto() {
677 let formats = [
678 format(1920, 1080, FrameFormat::YUYV, 5),
679 format(1280, 720, FrameFormat::YUYV, 10),
680 format(640, 360, FrameFormat::YUYV, 30),
681 format(1920, 1080, FrameFormat::MJPEG, 30),
682 format(1280, 720, FrameFormat::MJPEG, 30),
683 format(960, 540, FrameFormat::MJPEG, 30),
684 ];
685 assert_eq!(
686 pick_format(&formats, VideoQuality::Auto),
687 Some(format(1920, 1080, FrameFormat::MJPEG, 30))
688 );
689 assert_eq!(
690 pick_format(&formats, VideoQuality::P720),
691 Some(format(1280, 720, FrameFormat::MJPEG, 30))
426 );
692 );
427 }
693 }
428
694
429 #[test]
695 #[test]
430 fn the_largest_height_up_to_720_wins_then_nv12() {
696 fn auto_prefers_1080p_nv12_over_720p() {
431 let formats = [
697 let formats = [
432 format(1920, 1080, FrameFormat::NV12, 30),
698 format(1920, 1080, FrameFormat::NV12, 30),
433 format(640, 480, FrameFormat::NV12, 30),
699 format(640, 480, FrameFormat::NV12, 30),
@@ -435,7 +701,11 @@ mod tests {
435 format(1280, 720, FrameFormat::NV12, 30),
701 format(1280, 720, FrameFormat::NV12, 30),
436 ];
702 ];
437 assert_eq!(
703 assert_eq!(
438 pick_format(&formats),
704 pick_format(&formats, VideoQuality::Auto),
705 Some(format(1920, 1080, FrameFormat::NV12, 30))
706 );
707 assert_eq!(
708 pick_format(&formats, VideoQuality::P720),
439 Some(format(1280, 720, FrameFormat::NV12, 30))
709 Some(format(1280, 720, FrameFormat::NV12, 30))
440 );
710 );
441 }
711 }
@@ -448,20 +718,30 @@ mod tests {
448 format(640, 480, FrameFormat::NV12, 30),
718 format(640, 480, FrameFormat::NV12, 30),
449 ];
719 ];
450 assert_eq!(
720 assert_eq!(
451 pick_format(&formats),
721 pick_format(&formats, VideoQuality::P720),
452 Some(format(1280, 720, FrameFormat::YUYV, 30))
722 Some(format(1280, 720, FrameFormat::YUYV, 30))
453 );
723 );
454 }
724 }
455
725
456 #[test]
726 #[test]
457 fn without_720p_the_order_is_1080p_then_360p_then_4_3() {
727 fn locked_720_keeps_1080_as_downscale_candidate_but_prefers_exact_720() {
458 let full_hd = format(1920, 1080, FrameFormat::NV12, 30);
728 let full_hd = format(1920, 1080, FrameFormat::NV12, 30);
729 let hd = format(1280, 720, FrameFormat::NV12, 30);
459 let small = format(640, 360, FrameFormat::NV12, 30);
730 let small = format(640, 360, FrameFormat::NV12, 30);
460 let classic = format(960, 720, FrameFormat::NV12, 30);
731 let classic = format(960, 720, FrameFormat::NV12, 30);
461 assert_eq!(pick_format(&[classic, small, full_hd]), Some(full_hd));
462 assert_eq!(pick_format(&[classic, small]), Some(small));
463 assert_eq!(
732 assert_eq!(
464 pick_format(&[classic, format(2560, 1440, FrameFormat::NV12, 30)]),
733 pick_format(&[classic, small, full_hd], VideoQuality::Auto),
734 Some(full_hd)
735 );
736 assert_eq!(
737 pick_format(&[classic, small, full_hd, hd], VideoQuality::P720),
738 Some(hd)
739 );
740 assert_eq!(
741 pick_format(
742 &[classic, format(2560, 1440, FrameFormat::NV12, 30)],
743 VideoQuality::P720
744 ),
465 Some(classic)
745 Some(classic)
466 );
746 );
467 }
747 }
@@ -481,7 +761,7 @@ mod tests {
481
761
482 #[test]
762 #[test]
483 fn a_4_3_frame_is_centre_cropped_to_16_9() {
763 fn a_4_3_frame_is_centre_cropped_to_16_9() {
484 let cropped = fit_widescreen(gradient(960, 720));
764 let cropped = fit_widescreen(gradient(960, 720), VideoQuality::P720);
485 assert_eq!((cropped.width(), cropped.height()), (960, 540));
765 assert_eq!((cropped.width(), cropped.height()), (960, 540));
486 let (stride_y, stride_u, _) = cropped.strides();
766 let (stride_y, stride_u, _) = cropped.strides();
487 let (plane_y, plane_u, _) = cropped.data();
767 let (plane_y, plane_u, _) = cropped.data();
@@ -492,24 +772,29 @@ mod tests {
492 }
772 }
493
773
494 #[test]
774 #[test]
495 fn a_widescreen_frame_passes_and_1080p_is_scaled_to_720p() {
775 fn auto_keeps_1080p_and_720_lock_scales_it_down() {
496 assert_eq!(fit_widescreen(gradient(1280, 720)).width(), 1280);
776 assert_eq!(
497 let scaled = fit_widescreen(gradient(1920, 1080));
777 fit_widescreen(gradient(1280, 720), VideoQuality::Auto).width(),
778 1280
779 );
780 let kept = fit_widescreen(gradient(1920, 1080), VideoQuality::Auto);
781 assert_eq!((kept.width(), kept.height()), (1920, 1080));
782 let scaled = fit_widescreen(gradient(1920, 1080), VideoQuality::P720);
498 assert_eq!((scaled.width(), scaled.height()), (1280, 720));
783 assert_eq!((scaled.width(), scaled.height()), (1280, 720));
499 let wide = fit_widescreen(gradient(2560, 1080));
784 let wide = fit_widescreen(gradient(2560, 1440), VideoQuality::Auto);
500 assert_eq!((wide.width(), wide.height()), (1280, 720));
785 assert_eq!((wide.width(), wide.height()), (1920, 1080));
501 let classic = fit_widescreen(gradient(640, 480));
786 let classic = fit_widescreen(gradient(640, 480), VideoQuality::Auto);
502 assert_eq!((classic.width(), classic.height()), (640, 360));
787 assert_eq!((classic.width(), classic.height()), (640, 360));
503 }
788 }
504
789
505 #[test]
790 #[test]
506 fn no_usable_format_picks_nothing() {
791 fn no_usable_format_picks_nothing() {
507 let formats = [
792 let formats = [
508 format(1280, 720, FrameFormat::MJPEG, 30),
793 format(1280, 720, FrameFormat::MJPEG, 15),
509 format(1280, 720, FrameFormat::YUYV, 15),
794 format(1280, 720, FrameFormat::YUYV, 15),
510 ];
795 ];
511 assert_eq!(pick_format(&formats), None);
796 assert_eq!(pick_format(&formats, VideoQuality::Auto), None);
512 assert_eq!(pick_format(&[]), None);
797 assert_eq!(pick_format(&[], VideoQuality::Auto), None);
513 }
798 }
514
799
515 #[test]
800 #[test]
@@ -527,4 +812,79 @@ mod tests {
527 CameraIndex::String(_)
812 CameraIndex::String(_)
528 ));
813 ));
529 }
814 }
815
816 #[test]
817 fn mjpeg_decodes_to_i420() {
818 // Minimal valid grayscale JPEG is awkward; encode via `image` crate.
819 let mut rgb = image::RgbImage::new(16, 16);
820 for pixel in rgb.pixels_mut() {
821 *pixel = image::Rgb([40, 80, 120]);
822 }
823 let mut jpeg = Vec::new();
824 image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, 90)
825 .encode(rgb.as_raw(), 16, 16, image::ExtendedColorType::Rgb8)
826 .expect("encode");
827 let mut scratch = Vec::new();
828 let (buffer, width, height) = i420_from_mjpeg(&jpeg, &mut scratch).expect("mjpeg decodes");
829 assert_eq!((width, height), (16, 16));
830 assert_eq!((buffer.width(), buffer.height()), (16, 16));
831 }
832
833 #[test]
834 #[ignore = "timing; run with --release --ignored"]
835 fn mjpeg_1080p_decode_stays_under_fifteen_ms() {
836 let mut rgb = image::RgbImage::new(1920, 1080);
837 for (index, pixel) in rgb.pixels_mut().enumerate() {
838 let value = (index % 255) as u8;
839 *pixel = image::Rgb([value, value.wrapping_add(40), value.wrapping_add(80)]);
840 }
841 let mut jpeg = Vec::new();
842 image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, 85)
843 .encode(rgb.as_raw(), 1920, 1080, image::ExtendedColorType::Rgb8)
844 .expect("encode");
845 let mut scratch = Vec::new();
846 // Warm caches / CPU, then time a steady batch (30 fps allows ~33 ms/frame).
847 for _ in 0..3 {
848 let _ = i420_from_mjpeg(&jpeg, &mut scratch).expect("decode");
849 }
850 let started = Instant::now();
851 for _ in 0..10 {
852 let _ = i420_from_mjpeg(&jpeg, &mut scratch).expect("decode");
853 }
854 let average = started.elapsed() / 10;
855 assert!(
856 average < Duration::from_millis(20),
857 "average decode {average:?} exceeds 20 ms"
858 );
859 }
860
861 #[test]
862 #[ignore = "needs a connected camera"]
863 fn open_picks_at_least_thirty_fps_when_available() {
864 if list_cameras().is_empty() {
865 return;
866 }
867 let (mut camera, label) =
868 open_camera(CameraIndex::Index(0), VideoQuality::Auto).expect("camera opens");
869 assert!(
870 camera.camera_format().frame_rate() >= CAPTURE_FPS,
871 "opened {label} under 30 fps"
872 );
873 // Warm up buffers, then count for one second.
874 for _ in 0..10 {
875 let _ = camera.frame();
876 }
877 let deadline = Instant::now() + Duration::from_secs(1);
878 let mut frames = 0u32;
879 while Instant::now() < deadline {
880 if camera.frame().is_ok() {
881 frames += 1;
882 }
883 }
884 let _ = camera.stop_stream();
885 assert!(
886 frames >= 20,
887 "expected >= 20 frames in 1 s from {label}, got {frames}"
888 );
889 }
530}
890}
crates/calling/src/sdp.rs +120 −17
@@ -298,11 +298,14 @@ impl LineRole {
298 298 }
299 299 }
300 300
301 /// 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.
302 303 #[derive(Debug, Clone, Default)]
303 304 pub struct OfferPlan {
304 305 pub screen_share_mids: Vec<String>,
305 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>>,
306 309 }
307 310
308 311 #[derive(Debug, Clone, PartialEq, Eq)]
@@ -344,12 +347,16 @@ pub fn to_teams_offer(
344 347 .map(|(_, cname)| cname.to_owned())
345 348 })
346 349 .unwrap_or_else(|| format!("{:08x}{:08x}", numbers.next_u32(), numbers.next_u32()));
347 let gallery_carrier = plan.gallery_mids.last().cloned();
350 let fold_groups = effective_fold_groups(plan);
348 351 let mut lines = Vec::new();
349 352 let mut media = Vec::new();
350 353 for source in &browser.media {
351 354 let mid = source.mid().unwrap_or_default().to_owned();
352 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 {
353 360 continue;
354 361 }
355 362 let role = match source.kind.as_str() {
@@ -358,11 +365,10 @@ pub fn to_teams_offer(
358 365 _ if plan.screen_share_mids.contains(&mid) => LineRole::ScreenShare,
359 366 _ => LineRole::MainVideo,
360 367 };
361 let multi_stream =
362 (Some(&mid) == gallery_carrier.as_ref()).then_some(plan.gallery_mids.len());
368 let multi_stream = fold_group.map(|group| group.len());
363 369 let is_first = media.is_empty();
364 370 let signaled = if source.port == "0" {
365 signal_rejected_line(source, role)
371 signal_rejected_line(source, role, multi_stream)
366 372 } else if role == LineRole::Data {
367 373 signal_data_line(source, numbers)
368 374 } else {
@@ -370,8 +376,8 @@ pub fn to_teams_offer(
370 376 };
371 377 media.push(signaled);
372 378 lines.push(SignaledLine {
373 browser_mids: match multi_stream {
374 Some(_) => plan.gallery_mids.clone(),
379 browser_mids: match fold_group {
380 Some(group) => group.clone(),
375 381 None => vec![mid],
376 382 },
377 383 role,
@@ -405,12 +411,14 @@ pub fn to_teams_offer(
405 411 })
406 412 }
407 413
408 fn signal_rejected_line(source: &Media, role: LineRole) -> Media {
409 let attributes = vec![
410 Attribute::new("mid", source.mid().unwrap_or_default()),
411 Attribute::flag("inactive"),
412 Attribute::new("label", role.label()),
413 ];
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()));
414 422 Media {
415 423 kind: if role == LineRole::Data {
416 424 "x-data".to_owned()
@@ -1117,16 +1125,28 @@ impl RemoteOffer {
1117 1125 LineRole::ScreenShare => plan
1118 1126 .screen_share_mids
1119 1127 .extend(line.browser_mids.iter().cloned()),
1120 _ if line.browser_mids.len() > 1 => {
1121 plan.gallery_mids.extend(line.browser_mids.iter().cloned())
1122 }
1123 1128 _ => {}
1124 1129 }
1130 if line.browser_mids.len() > 1 {
1131 plan.gallery_mids.extend(line.browser_mids.iter().cloned());
1132 plan.fold_groups.push(line.browser_mids.clone());
1133 }
1125 1134 }
1126 1135 plan
1127 1136 }
1128 1137 }
1129 1138
1139 fn effective_fold_groups(plan: &OfferPlan) -> Vec<Vec<String>> {
1140 if !plan.fold_groups.is_empty() {
1141 return plan.fold_groups.clone();
1142 }
1143 if plan.gallery_mids.len() > 1 {
1144 vec![plan.gallery_mids.clone()]
1145 } else {
1146 Vec::new()
1147 }
1148 }
1149
1130 1150 fn role_of_teams_line(line: &Media) -> LineRole {
1131 1151 match line.value("label") {
1132 1152 Some("main-audio") => LineRole::MainAudio,
@@ -1660,6 +1680,89 @@ mod tests {
1660 1680 );
1661 1681 }
1662 1682
1683 /// 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).
1684 fn folded_carrier_neighbor_taken(label: &str) -> String {
1685 format!(
1686 "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"
1687 )
1688 }
1689
1690 #[test]
1691 fn a_folded_answer_keeps_one_teams_line_when_carrier_neighbors_are_taken() {
1692 for label in ["main-video", "applicationsharing-video"] {
1693 let offer = folded_carrier_neighbor_taken(label);
1694 let remote = from_teams_offer(&offer).unwrap();
1695 let folded = remote
1696 .lines
1697 .iter()
1698 .find(|line| line.browser_mids.len() > 1)
1699 .expect("folded line");
1700 assert_eq!(folded.browser_mids, vec!["3-0".to_owned(), "3".to_owned()]);
1701 assert_eq!(
1702 remote.plan().fold_groups,
1703 vec![vec!["3-0".to_owned(), "3".to_owned()]]
1704 );
1705 let offer_lines = parse(&offer).unwrap().media.len();
1706 let browser = parse(&remote.browser_sdp).unwrap();
1707 assert_eq!(browser.media.len(), offer_lines + 1);
1708 for port in ["0", "9"] {
1709 let answer_browser = write(&SessionDescription {
1710 session: browser.session.clone(),
1711 media: browser
1712 .media
1713 .iter()
1714 .map(|line| {
1715 let mut line = line.clone();
1716 line.port = if line.kind == "audio" || line.kind == "application" {
1717 "9".to_owned()
1718 } else {
1719 port.to_owned()
1720 };
1721 line.attributes.retain(|attribute| {
1722 !matches!(
1723 attribute.name.as_str(),
1724 "sendrecv" | "recvonly" | "sendonly" | "inactive"
1725 )
1726 });
1727 if line.kind == "audio" || line.kind == "application" {
1728 line.attributes.push(Attribute::flag("sendrecv"));
1729 } else {
1730 line.attributes.push(Attribute::flag("inactive"));
1731 }
1732 line
1733 })
1734 .collect(),
1735 });
1736 let answer = to_teams_answer(&answer_browser, &remote, &mut counter()).unwrap();
1737 let parsed = parse(&answer.sdp).unwrap();
1738 let mids: Vec<_> = parsed.media.iter().filter_map(|line| line.mid()).collect();
1739 assert_eq!(
1740 parsed.media.len(),
1741 offer_lines,
1742 "{label} port {port}: answer mids {mids:?} must match the offer line count"
1743 );
1744 assert!(
1745 !mids.iter().any(|mid| *mid == "3-0"),
1746 "{label} port {port}: signaled answer must not expose the internal fold mid: {mids:?}"
1747 );
1748 assert!(mids.iter().any(|mid| *mid == "3"), "{label} port {port}");
1749 let carrier = parsed
1750 .media
1751 .iter()
1752 .find(|line| line.mid() == Some("3"))
1753 .unwrap();
1754 assert_eq!(
1755 carrier
1756 .value("x-multi-stream")
1757 .and_then(|value| value.split(' ').next().map(str::to_owned)),
1758 Some("2".to_owned()),
1759 "{label} port {port}: carrier must keep x-multi-stream"
1760 );
1761 assert_eq!(carrier.value("label"), Some(label));
1762 }
1763 }
1764 }
1765
1663 1766 #[test]
1664 1767 fn opus_fmtp_gets_the_send_quality_without_overriding_teams() {
1665 1768 assert_eq!(
@@ -298,11 +298,14 @@ impl LineRole {
298 }
298 }
299}
299}
300
300
301/// 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.
302#[derive(Debug, Clone, Default)]
303#[derive(Debug, Clone, Default)]
303pub struct OfferPlan {
304pub struct OfferPlan {
304 pub screen_share_mids: Vec<String>,
305 pub screen_share_mids: Vec<String>,
305 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>>,
306}
309}
307
310
308#[derive(Debug, Clone, PartialEq, Eq)]
311#[derive(Debug, Clone, PartialEq, Eq)]
@@ -344,12 +347,16 @@ pub fn to_teams_offer(
344 .map(|(_, cname)| cname.to_owned())
347 .map(|(_, cname)| cname.to_owned())
345 })
348 })
346 .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()));
347 let gallery_carrier = plan.gallery_mids.last().cloned();
350 let fold_groups = effective_fold_groups(plan);
348 let mut lines = Vec::new();
351 let mut lines = Vec::new();
349 let mut media = Vec::new();
352 let mut media = Vec::new();
350 for source in &browser.media {
353 for source in &browser.media {
351 let mid = source.mid().unwrap_or_default().to_owned();
354 let mid = source.mid().unwrap_or_default().to_owned();
352 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 {
353 continue;
360 continue;
354 }
361 }
355 let role = match source.kind.as_str() {
362 let role = match source.kind.as_str() {
@@ -358,11 +365,10 @@ pub fn to_teams_offer(
358 _ if plan.screen_share_mids.contains(&mid) => LineRole::ScreenShare,
365 _ if plan.screen_share_mids.contains(&mid) => LineRole::ScreenShare,
359 _ => LineRole::MainVideo,
366 _ => LineRole::MainVideo,
360 };
367 };
361 let multi_stream =
368 let multi_stream = fold_group.map(|group| group.len());
362 (Some(&mid) == gallery_carrier.as_ref()).then_some(plan.gallery_mids.len());
363 let is_first = media.is_empty();
369 let is_first = media.is_empty();
364 let signaled = if source.port == "0" {
370 let signaled = if source.port == "0" {
365 signal_rejected_line(source, role)
371 signal_rejected_line(source, role, multi_stream)
366 } else if role == LineRole::Data {
372 } else if role == LineRole::Data {
367 signal_data_line(source, numbers)
373 signal_data_line(source, numbers)
368 } else {
374 } else {
@@ -370,8 +376,8 @@ pub fn to_teams_offer(
370 };
376 };
371 media.push(signaled);
377 media.push(signaled);
372 lines.push(SignaledLine {
378 lines.push(SignaledLine {
373 browser_mids: match multi_stream {
379 browser_mids: match fold_group {
374 Some(_) => plan.gallery_mids.clone(),
380 Some(group) => group.clone(),
375 None => vec![mid],
381 None => vec![mid],
376 },
382 },
377 role,
383 role,
@@ -405,12 +411,14 @@ pub fn to_teams_offer(
405 })
411 })
406}
412}
407
413
408fn signal_rejected_line(source: &Media, role: LineRole) -> Media {
414fn signal_rejected_line(source: &Media, role: LineRole, multi_stream: Option<usize>) -> Media {
409 let attributes = vec![
415 let mut attributes = Vec::new();
410 Attribute::new("mid", source.mid().unwrap_or_default()),
416 if let Some(count) = multi_stream {
411 Attribute::flag("inactive"),
417 attributes.push(Attribute::new("x-multi-stream", format!("{count} 1 1 1")));
412 Attribute::new("label", role.label()),
418 }
413 ];
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()));
414 Media {
422 Media {
415 kind: if role == LineRole::Data {
423 kind: if role == LineRole::Data {
416 "x-data".to_owned()
424 "x-data".to_owned()
@@ -1117,16 +1125,28 @@ impl RemoteOffer {
1117 LineRole::ScreenShare => plan
1125 LineRole::ScreenShare => plan
1118 .screen_share_mids
1126 .screen_share_mids
1119 .extend(line.browser_mids.iter().cloned()),
1127 .extend(line.browser_mids.iter().cloned()),
1120 _ if line.browser_mids.len() > 1 => {
1121 plan.gallery_mids.extend(line.browser_mids.iter().cloned())
1122 }
1123 _ => {}
1128 _ => {}
1124 }
1129 }
1130 if line.browser_mids.len() > 1 {
1131 plan.gallery_mids.extend(line.browser_mids.iter().cloned());
1132 plan.fold_groups.push(line.browser_mids.clone());
1133 }
1125 }
1134 }
1126 plan
1135 plan
1127 }
1136 }
1128}
1137}
1129
1138
1139fn effective_fold_groups(plan: &OfferPlan) -> Vec<Vec<String>> {
1140 if !plan.fold_groups.is_empty() {
1141 return plan.fold_groups.clone();
1142 }
1143 if plan.gallery_mids.len() > 1 {
1144 vec![plan.gallery_mids.clone()]
1145 } else {
1146 Vec::new()
1147 }
1148}
1149
1130fn role_of_teams_line(line: &Media) -> LineRole {
1150fn role_of_teams_line(line: &Media) -> LineRole {
1131 match line.value("label") {
1151 match line.value("label") {
1132 Some("main-audio") => LineRole::MainAudio,
1152 Some("main-audio") => LineRole::MainAudio,
@@ -1660,6 +1680,89 @@ mod tests {
1660 );
1680 );
1661 }
1681 }
1662
1682
1683 /// 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).
1684 fn folded_carrier_neighbor_taken(label: &str) -> String {
1685 format!(
1686 "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"
1687 )
1688 }
1689
1690 #[test]
1691 fn a_folded_answer_keeps_one_teams_line_when_carrier_neighbors_are_taken() {
1692 for label in ["main-video", "applicationsharing-video"] {
1693 let offer = folded_carrier_neighbor_taken(label);
1694 let remote = from_teams_offer(&offer).unwrap();
1695 let folded = remote
1696 .lines
1697 .iter()
1698 .find(|line| line.browser_mids.len() > 1)
1699 .expect("folded line");
1700 assert_eq!(folded.browser_mids, vec!["3-0".to_owned(), "3".to_owned()]);
1701 assert_eq!(
1702 remote.plan().fold_groups,
1703 vec![vec!["3-0".to_owned(), "3".to_owned()]]
1704 );
1705 let offer_lines = parse(&offer).unwrap().media.len();
1706 let browser = parse(&remote.browser_sdp).unwrap();
1707 assert_eq!(browser.media.len(), offer_lines + 1);
1708 for port in ["0", "9"] {
1709 let answer_browser = write(&SessionDescription {
1710 session: browser.session.clone(),
1711 media: browser
1712 .media
1713 .iter()
1714 .map(|line| {
1715 let mut line = line.clone();
1716 line.port = if line.kind == "audio" || line.kind == "application" {
1717 "9".to_owned()
1718 } else {
1719 port.to_owned()
1720 };
1721 line.attributes.retain(|attribute| {
1722 !matches!(
1723 attribute.name.as_str(),
1724 "sendrecv" | "recvonly" | "sendonly" | "inactive"
1725 )
1726 });
1727 if line.kind == "audio" || line.kind == "application" {
1728 line.attributes.push(Attribute::flag("sendrecv"));
1729 } else {
1730 line.attributes.push(Attribute::flag("inactive"));
1731 }
1732 line
1733 })
1734 .collect(),
1735 });
1736 let answer = to_teams_answer(&answer_browser, &remote, &mut counter()).unwrap();
1737 let parsed = parse(&answer.sdp).unwrap();
1738 let mids: Vec<_> = parsed.media.iter().filter_map(|line| line.mid()).collect();
1739 assert_eq!(
1740 parsed.media.len(),
1741 offer_lines,
1742 "{label} port {port}: answer mids {mids:?} must match the offer line count"
1743 );
1744 assert!(
1745 !mids.iter().any(|mid| *mid == "3-0"),
1746 "{label} port {port}: signaled answer must not expose the internal fold mid: {mids:?}"
1747 );
1748 assert!(mids.iter().any(|mid| *mid == "3"), "{label} port {port}");
1749 let carrier = parsed
1750 .media
1751 .iter()
1752 .find(|line| line.mid() == Some("3"))
1753 .unwrap();
1754 assert_eq!(
1755 carrier
1756 .value("x-multi-stream")
1757 .and_then(|value| value.split(' ').next().map(str::to_owned)),
1758 Some("2".to_owned()),
1759 "{label} port {port}: carrier must keep x-multi-stream"
1760 );
1761 assert_eq!(carrier.value("label"), Some(label));
1762 }
1763 }
1764 }
1765
1663 #[test]
1766 #[test]
1664 fn opus_fmtp_gets_the_send_quality_without_overriding_teams() {
1767 fn opus_fmtp_gets_the_send_quality_without_overriding_teams() {
1665 assert_eq!(
1768 assert_eq!(
crates/calling/src/video_layout.rs +85 −20
@@ -12,6 +12,7 @@ use crate::error::{Error, Result};
12 12 use crate::sdp::{LineRole, OfferPlan, StreamLine};
13 13 use crate::send_control::capture_macroblocks;
14 14 use crate::video_frame::VideoKey;
15 use crate::video_quality::VideoQuality;
15 16
16 17 pub const RECEIVE_SLOTS: usize = 9;
17 18 pub const CAMERA_MID: &str = "1";
@@ -25,11 +26,17 @@ pub const SCREEN_STREAM: &str = "screen";
25 26 const H264: &str = "video/h264";
26 27 const RTX: &str = "video/rtx";
27 28 const NO_SOURCE: i64 = -1;
28 const STAGE_REQUEST: ReceiveLimits = ReceiveLimits {
29 const STAGE_720_REQUEST: ReceiveLimits = ReceiveLimits {
29 30 max_fs: 3600,
30 31 max_fps: 3000,
31 32 max_mbps: 108_000,
32 33 };
34 /// 1080p @ 30: max-fs 8160 macroblocks, mbps ≈ 8160 * 30.
35 const STAGE_1080_REQUEST: ReceiveLimits = ReceiveLimits {
36 max_fs: 8160,
37 max_fps: 3000,
38 max_mbps: 244_800,
39 };
33 40 const SMALL_REQUEST: ReceiveLimits = ReceiveLimits {
34 41 max_fs: 920,
35 42 max_fps: 3000,
@@ -55,9 +62,12 @@ pub enum TileDetail {
55 62 }
56 63
57 64 impl TileDetail {
58 fn limits(self) -> ReceiveLimits {
65 fn limits(self, quality: VideoQuality) -> ReceiveLimits {
59 66 match self {
60 TileDetail::Stage => STAGE_REQUEST,
67 TileDetail::Stage => match quality {
68 VideoQuality::P720 => STAGE_720_REQUEST,
69 VideoQuality::Auto | VideoQuality::P1080 => STAGE_1080_REQUEST,
70 },
61 71 TileDetail::Small => SMALL_REQUEST,
62 72 }
63 73 }
@@ -80,6 +90,7 @@ pub fn offer_plan() -> OfferPlan {
80 90 OfferPlan {
81 91 screen_share_mids: vec![SHARE_MID.to_owned()],
82 92 gallery_mids: Vec::new(),
93 fold_groups: Vec::new(),
83 94 }
84 95 }
85 96
@@ -87,6 +98,7 @@ pub fn one_to_one_plan() -> OfferPlan {
87 98 OfferPlan {
88 99 screen_share_mids: vec![ONE_TO_ONE_SHARE_MID.to_owned()],
89 100 gallery_mids: Vec::new(),
101 fold_groups: Vec::new(),
90 102 }
91 103 }
92 104
@@ -387,12 +399,14 @@ pub struct SourceRequest {
387 399 pub source: Option<u32>,
388 400 pub screen: bool,
389 401 pub detail: TileDetail,
402 pub quality: VideoQuality,
390 403 }
391 404
392 405 pub fn requests_for(
393 406 current: &[Option<Assignment>],
394 407 next: &[Option<Assignment>],
395 408 slots: &[ReceiveSlot],
409 quality: VideoQuality,
396 410 ) -> Vec<SourceRequest> {
397 411 slots
398 412 .iter()
@@ -407,6 +421,7 @@ pub fn requests_for(
407 421 .as_ref()
408 422 .map(|assignment| assignment.detail)
409 423 .unwrap_or_default(),
424 quality,
410 425 })
411 426 .collect()
412 427 }
@@ -417,7 +432,7 @@ impl SourceRequest {
417 432 let limits = if self.screen {
418 433 SCREEN_REQUEST
419 434 } else {
420 self.detail.limits()
435 self.detail.limits(self.quality)
421 436 };
422 437 let control = json!({
423 438 "controlVideoStreaming": {
@@ -445,7 +460,15 @@ impl SourceRequest {
445 460 }
446 461 }
447 462
448 pub fn send_capabilities_body(width: u32, height: u32, sequence_number: u64) -> Value {
463 pub fn send_capabilities_body(
464 width: u32,
465 height: u32,
466 sequence_number: u64,
467 quality: VideoQuality,
468 ) -> Value {
469 let ceiling = quality.capture_height().max(quality.capture_width());
470 let width = width.min(ceiling);
471 let height = height.min(ceiling);
449 472 let largest_side = width.max(height);
450 473 let layers = if capture_macroblocks(width, height) < THREE_LAYER_MIN_FS {
451 474 2
@@ -476,17 +499,24 @@ pub fn send_capabilities_body(width: u32, height: u32, sequence_number: u64) ->
476 499 #[derive(Debug, Default)]
477 500 pub struct SendCapabilityReporter {
478 501 last_size: Option<(u32, u32)>,
502 last_quality: Option<VideoQuality>,
479 503 sequence_number: u64,
480 504 }
481 505
482 506 impl SendCapabilityReporter {
483 pub fn body_for(&mut self, size: (u32, u32)) -> Option<Value> {
484 if self.last_size == Some(size) {
507 pub fn body_for(&mut self, size: (u32, u32), quality: VideoQuality) -> Option<Value> {
508 if self.last_size == Some(size) && self.last_quality == Some(quality) {
485 509 return None;
486 510 }
487 self.last_size = Some(size);
511 self.last_size.replace(size);
512 self.last_quality.replace(quality);
488 513 self.sequence_number += 1;
489 Some(send_capabilities_body(size.0, size.1, self.sequence_number))
514 Some(send_capabilities_body(
515 size.0,
516 size.1,
517 self.sequence_number,
518 quality,
519 ))
490 520 }
491 521 }
492 522
@@ -610,7 +640,7 @@ mod tests {
610 640 stream_id: 204,
611 641 },
612 642 ];
613 let requests = requests_for(&held, &next, &slots);
643 let requests = requests_for(&held, &next, &slots, VideoQuality::Auto);
614 644 assert_eq!(
615 645 requests,
616 646 vec![SourceRequest {
@@ -618,7 +648,8 @@ mod tests {
618 648 stream_id: 203,
619 649 source: None,
620 650 screen: false,
621 detail: TileDetail::Stage
651 detail: TileDetail::Stage,
652 quality: VideoQuality::Auto,
622 653 }]
623 654 );
624 655 }
@@ -631,6 +662,7 @@ mod tests {
631 662 source: Some(302),
632 663 screen: false,
633 664 detail: TileDetail::Stage,
665 quality: VideoQuality::Auto,
634 666 };
635 667 let body = request.body(7);
636 668 let channel = &body["applyChannelParameters"]["multiChannelParameter"];
@@ -641,8 +673,9 @@ mod tests {
641 673 assert_eq!(parameter["controlVideoStreaming"]["sequenceNumber"], 7);
642 674 assert_eq!(info["sourceId"], 302);
643 675 assert_eq!(info["streamMsid"], 204);
644 assert_eq!(info["fmtParams"][0]["max-fs"], 3600);
676 assert_eq!(info["fmtParams"][0]["max-fs"], 8160);
645 677 assert_eq!(info["fmtParams"][0]["max-fps"], 3000);
678 assert_eq!(info["fmtParams"][0]["max-mbps"], 244_800);
646 679 assert_eq!(info["fmtParams"][0]["profile-level-id"], "64001f");
647 680 let cleared = SourceRequest {
648 681 source: None,
@@ -744,7 +777,7 @@ mod tests {
744 777 stream_id: 203 + index,
745 778 })
746 779 .collect();
747 let requests = requests_for(&held, &next, &slots);
780 let requests = requests_for(&held, &next, &slots, VideoQuality::Auto);
748 781 assert_eq!(requests.len(), 1);
749 782 assert_eq!(requests[0].mid, "3");
750 783 assert_eq!(requests[0].detail, TileDetail::Stage);
@@ -759,6 +792,7 @@ mod tests {
759 792 source: Some(1),
760 793 screen: false,
761 794 detail,
795 quality: VideoQuality::Auto,
762 796 };
763 797 let body = request.body(1);
764 798 let parameter: Value = serde_json::from_str(
@@ -769,9 +803,29 @@ mod tests {
769 803 .unwrap();
770 804 parameter["controlVideoStreaming"]["controlInfo"]["fmtParams"][0].clone()
771 805 };
772 assert_eq!(fmt_for(TileDetail::Stage)["max-fs"], 3600);
806 assert_eq!(fmt_for(TileDetail::Stage)["max-fs"], 8160);
807 assert_eq!(fmt_for(TileDetail::Stage)["max-mbps"], 244_800);
773 808 assert_eq!(fmt_for(TileDetail::Small)["max-fs"], 920);
774 809 assert_eq!(fmt_for(TileDetail::Small)["max-mbps"], 27_600);
810 let locked = SourceRequest {
811 mid: "2".into(),
812 stream_id: 203,
813 source: Some(1),
814 screen: false,
815 detail: TileDetail::Stage,
816 quality: VideoQuality::P720,
817 }
818 .body(1);
819 let parameter: Value = serde_json::from_str(
820 locked["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"]
821 .as_str()
822 .unwrap(),
823 )
824 .unwrap();
825 assert_eq!(
826 parameter["controlVideoStreaming"]["controlInfo"]["fmtParams"][0]["max-fs"],
827 3600
828 );
775 829 }
776 830
777 831 #[test]
@@ -805,7 +859,7 @@ mod tests {
805 859
806 860 #[test]
807 861 fn send_capabilities_name_the_camera_mid_and_the_largest_side() {
808 let body = send_capabilities_body(1280, 720, 4);
862 let body = send_capabilities_body(1280, 720, 4, VideoQuality::Auto);
809 863 let channel = &body["applyChannelParameters"]["multiChannelParameter"];
810 864 assert_eq!(channel["mids"], json!(["1"]));
811 865 let parameter: Value =
@@ -817,21 +871,31 @@ mod tests {
817 871 }})
818 872 );
819 873 let small: Value = serde_json::from_str(
820 send_capabilities_body(480, 270, 1)["applyChannelParameters"]["multiChannelParameter"]
821 ["mediaParameter"]
874 send_capabilities_body(480, 270, 1, VideoQuality::Auto)
875 ["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"]
822 876 .as_str()
823 877 .unwrap(),
824 878 )
825 879 .unwrap();
826 880 assert_eq!(small["maxVideoSendCapabilities"]["max-layers"], 2);
881 let clamped: Value =
882 serde_json::from_str(
883 send_capabilities_body(3840, 2160, 1, VideoQuality::P720)["applyChannelParameters"]
884 ["multiChannelParameter"]["mediaParameter"]
885 .as_str()
886 .unwrap(),
887 )
888 .unwrap();
889 assert_eq!(clamped["maxVideoSendCapabilities"]["max-width"], 1280);
890 assert_eq!(clamped["maxVideoSendCapabilities"]["max-height"], 1280);
827 891 }
828 892
829 893 #[test]
830 894 fn the_reporter_skips_a_repeated_size_and_counts_sequences() {
831 895 let mut reporter = SendCapabilityReporter::default();
832 assert!(reporter.body_for((1280, 720)).is_some());
833 assert!(reporter.body_for((1280, 720)).is_none());
834 let body = reporter.body_for((640, 480)).unwrap();
896 assert!(reporter.body_for((1280, 720), VideoQuality::Auto).is_some());
897 assert!(reporter.body_for((1280, 720), VideoQuality::Auto).is_none());
898 let body = reporter.body_for((640, 480), VideoQuality::Auto).unwrap();
835 899 let parameter: Value = serde_json::from_str(
836 900 body["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"]
837 901 .as_str()
@@ -839,5 +903,6 @@ mod tests {
839 903 )
840 904 .unwrap();
841 905 assert_eq!(parameter["maxVideoSendCapabilities"]["sequence-number"], 2);
906 assert!(reporter.body_for((640, 480), VideoQuality::P720).is_some());
842 907 }
843 908 }
@@ -12,6 +12,7 @@ use crate::error::{Error, Result};
12use crate::sdp::{LineRole, OfferPlan, StreamLine};
12use crate::sdp::{LineRole, OfferPlan, StreamLine};
13use crate::send_control::capture_macroblocks;
13use crate::send_control::capture_macroblocks;
14use crate::video_frame::VideoKey;
14use crate::video_frame::VideoKey;
15use crate::video_quality::VideoQuality;
15
16
16pub const RECEIVE_SLOTS: usize = 9;
17pub const RECEIVE_SLOTS: usize = 9;
17pub const CAMERA_MID: &str = "1";
18pub const CAMERA_MID: &str = "1";
@@ -25,11 +26,17 @@ pub const SCREEN_STREAM: &str = "screen";
25const H264: &str = "video/h264";
26const H264: &str = "video/h264";
26const RTX: &str = "video/rtx";
27const RTX: &str = "video/rtx";
27const NO_SOURCE: i64 = -1;
28const NO_SOURCE: i64 = -1;
28const STAGE_REQUEST: ReceiveLimits = ReceiveLimits {
29const STAGE_720_REQUEST: ReceiveLimits = ReceiveLimits {
29 max_fs: 3600,
30 max_fs: 3600,
30 max_fps: 3000,
31 max_fps: 3000,
31 max_mbps: 108_000,
32 max_mbps: 108_000,
32};
33};
34/// 1080p @ 30: max-fs 8160 macroblocks, mbps ≈ 8160 * 30.
35const STAGE_1080_REQUEST: ReceiveLimits = ReceiveLimits {
36 max_fs: 8160,
37 max_fps: 3000,
38 max_mbps: 244_800,
39};
33const SMALL_REQUEST: ReceiveLimits = ReceiveLimits {
40const SMALL_REQUEST: ReceiveLimits = ReceiveLimits {
34 max_fs: 920,
41 max_fs: 920,
35 max_fps: 3000,
42 max_fps: 3000,
@@ -55,9 +62,12 @@ pub enum TileDetail {
55}
62}
56
63
57impl TileDetail {
64impl TileDetail {
58 fn limits(self) -> ReceiveLimits {
65 fn limits(self, quality: VideoQuality) -> ReceiveLimits {
59 match self {
66 match self {
60 TileDetail::Stage => STAGE_REQUEST,
67 TileDetail::Stage => match quality {
68 VideoQuality::P720 => STAGE_720_REQUEST,
69 VideoQuality::Auto | VideoQuality::P1080 => STAGE_1080_REQUEST,
70 },
61 TileDetail::Small => SMALL_REQUEST,
71 TileDetail::Small => SMALL_REQUEST,
62 }
72 }
63 }
73 }
@@ -80,6 +90,7 @@ pub fn offer_plan() -> OfferPlan {
80 OfferPlan {
90 OfferPlan {
81 screen_share_mids: vec![SHARE_MID.to_owned()],
91 screen_share_mids: vec![SHARE_MID.to_owned()],
82 gallery_mids: Vec::new(),
92 gallery_mids: Vec::new(),
93 fold_groups: Vec::new(),
83 }
94 }
84}
95}
85
96
@@ -87,6 +98,7 @@ pub fn one_to_one_plan() -> OfferPlan {
87 OfferPlan {
98 OfferPlan {
88 screen_share_mids: vec![ONE_TO_ONE_SHARE_MID.to_owned()],
99 screen_share_mids: vec![ONE_TO_ONE_SHARE_MID.to_owned()],
89 gallery_mids: Vec::new(),
100 gallery_mids: Vec::new(),
101 fold_groups: Vec::new(),
90 }
102 }
91}
103}
92
104
@@ -387,12 +399,14 @@ pub struct SourceRequest {
387 pub source: Option<u32>,
399 pub source: Option<u32>,
388 pub screen: bool,
400 pub screen: bool,
389 pub detail: TileDetail,
401 pub detail: TileDetail,
402 pub quality: VideoQuality,
390}
403}
391
404
392pub fn requests_for(
405pub fn requests_for(
393 current: &[Option<Assignment>],
406 current: &[Option<Assignment>],
394 next: &[Option<Assignment>],
407 next: &[Option<Assignment>],
395 slots: &[ReceiveSlot],
408 slots: &[ReceiveSlot],
409 quality: VideoQuality,
396) -> Vec<SourceRequest> {
410) -> Vec<SourceRequest> {
397 slots
411 slots
398 .iter()
412 .iter()
@@ -407,6 +421,7 @@ pub fn requests_for(
407 .as_ref()
421 .as_ref()
408 .map(|assignment| assignment.detail)
422 .map(|assignment| assignment.detail)
409 .unwrap_or_default(),
423 .unwrap_or_default(),
424 quality,
410 })
425 })
411 .collect()
426 .collect()
412}
427}
@@ -417,7 +432,7 @@ impl SourceRequest {
417 let limits = if self.screen {
432 let limits = if self.screen {
418 SCREEN_REQUEST
433 SCREEN_REQUEST
419 } else {
434 } else {
420 self.detail.limits()
435 self.detail.limits(self.quality)
421 };
436 };
422 let control = json!({
437 let control = json!({
423 "controlVideoStreaming": {
438 "controlVideoStreaming": {
@@ -445,7 +460,15 @@ impl SourceRequest {
445 }
460 }
446}
461}
447
462
448pub fn send_capabilities_body(width: u32, height: u32, sequence_number: u64) -> Value {
463pub fn send_capabilities_body(
464 width: u32,
465 height: u32,
466 sequence_number: u64,
467 quality: VideoQuality,
468) -> Value {
469 let ceiling = quality.capture_height().max(quality.capture_width());
470 let width = width.min(ceiling);
471 let height = height.min(ceiling);
449 let largest_side = width.max(height);
472 let largest_side = width.max(height);
450 let layers = if capture_macroblocks(width, height) < THREE_LAYER_MIN_FS {
473 let layers = if capture_macroblocks(width, height) < THREE_LAYER_MIN_FS {
451 2
474 2
@@ -476,17 +499,24 @@ pub fn send_capabilities_body(width: u32, height: u32, sequence_number: u64) ->
476#[derive(Debug, Default)]
499#[derive(Debug, Default)]
477pub struct SendCapabilityReporter {
500pub struct SendCapabilityReporter {
478 last_size: Option<(u32, u32)>,
501 last_size: Option<(u32, u32)>,
502 last_quality: Option<VideoQuality>,
479 sequence_number: u64,
503 sequence_number: u64,
480}
504}
481
505
482impl SendCapabilityReporter {
506impl SendCapabilityReporter {
483 pub fn body_for(&mut self, size: (u32, u32)) -> Option<Value> {
507 pub fn body_for(&mut self, size: (u32, u32), quality: VideoQuality) -> Option<Value> {
484 if self.last_size == Some(size) {
508 if self.last_size == Some(size) && self.last_quality == Some(quality) {
485 return None;
509 return None;
486 }
510 }
487 self.last_size = Some(size);
511 self.last_size.replace(size);
512 self.last_quality.replace(quality);
488 self.sequence_number += 1;
513 self.sequence_number += 1;
489 Some(send_capabilities_body(size.0, size.1, self.sequence_number))
514 Some(send_capabilities_body(
515 size.0,
516 size.1,
517 self.sequence_number,
518 quality,
519 ))
490 }
520 }
491}
521}
492
522
@@ -610,7 +640,7 @@ mod tests {
610 stream_id: 204,
640 stream_id: 204,
611 },
641 },
612 ];
642 ];
613 let requests = requests_for(&held, &next, &slots);
643 let requests = requests_for(&held, &next, &slots, VideoQuality::Auto);
614 assert_eq!(
644 assert_eq!(
615 requests,
645 requests,
616 vec![SourceRequest {
646 vec![SourceRequest {
@@ -618,7 +648,8 @@ mod tests {
618 stream_id: 203,
648 stream_id: 203,
619 source: None,
649 source: None,
620 screen: false,
650 screen: false,
621 detail: TileDetail::Stage
651 detail: TileDetail::Stage,
652 quality: VideoQuality::Auto,
622 }]
653 }]
623 );
654 );
624 }
655 }
@@ -631,6 +662,7 @@ mod tests {
631 source: Some(302),
662 source: Some(302),
632 screen: false,
663 screen: false,
633 detail: TileDetail::Stage,
664 detail: TileDetail::Stage,
665 quality: VideoQuality::Auto,
634 };
666 };
635 let body = request.body(7);
667 let body = request.body(7);
636 let channel = &body["applyChannelParameters"]["multiChannelParameter"];
668 let channel = &body["applyChannelParameters"]["multiChannelParameter"];
@@ -641,8 +673,9 @@ mod tests {
641 assert_eq!(parameter["controlVideoStreaming"]["sequenceNumber"], 7);
673 assert_eq!(parameter["controlVideoStreaming"]["sequenceNumber"], 7);
642 assert_eq!(info["sourceId"], 302);
674 assert_eq!(info["sourceId"], 302);
643 assert_eq!(info["streamMsid"], 204);
675 assert_eq!(info["streamMsid"], 204);
644 assert_eq!(info["fmtParams"][0]["max-fs"], 3600);
676 assert_eq!(info["fmtParams"][0]["max-fs"], 8160);
645 assert_eq!(info["fmtParams"][0]["max-fps"], 3000);
677 assert_eq!(info["fmtParams"][0]["max-fps"], 3000);
678 assert_eq!(info["fmtParams"][0]["max-mbps"], 244_800);
646 assert_eq!(info["fmtParams"][0]["profile-level-id"], "64001f");
679 assert_eq!(info["fmtParams"][0]["profile-level-id"], "64001f");
647 let cleared = SourceRequest {
680 let cleared = SourceRequest {
648 source: None,
681 source: None,
@@ -744,7 +777,7 @@ mod tests {
744 stream_id: 203 + index,
777 stream_id: 203 + index,
745 })
778 })
746 .collect();
779 .collect();
747 let requests = requests_for(&held, &next, &slots);
780 let requests = requests_for(&held, &next, &slots, VideoQuality::Auto);
748 assert_eq!(requests.len(), 1);
781 assert_eq!(requests.len(), 1);
749 assert_eq!(requests[0].mid, "3");
782 assert_eq!(requests[0].mid, "3");
750 assert_eq!(requests[0].detail, TileDetail::Stage);
783 assert_eq!(requests[0].detail, TileDetail::Stage);
@@ -759,6 +792,7 @@ mod tests {
759 source: Some(1),
792 source: Some(1),
760 screen: false,
793 screen: false,
761 detail,
794 detail,
795 quality: VideoQuality::Auto,
762 };
796 };
763 let body = request.body(1);
797 let body = request.body(1);
764 let parameter: Value = serde_json::from_str(
798 let parameter: Value = serde_json::from_str(
@@ -769,9 +803,29 @@ mod tests {
769 .unwrap();
803 .unwrap();
770 parameter["controlVideoStreaming"]["controlInfo"]["fmtParams"][0].clone()
804 parameter["controlVideoStreaming"]["controlInfo"]["fmtParams"][0].clone()
771 };
805 };
772 assert_eq!(fmt_for(TileDetail::Stage)["max-fs"], 3600);
806 assert_eq!(fmt_for(TileDetail::Stage)["max-fs"], 8160);
807 assert_eq!(fmt_for(TileDetail::Stage)["max-mbps"], 244_800);
773 assert_eq!(fmt_for(TileDetail::Small)["max-fs"], 920);
808 assert_eq!(fmt_for(TileDetail::Small)["max-fs"], 920);
774 assert_eq!(fmt_for(TileDetail::Small)["max-mbps"], 27_600);
809 assert_eq!(fmt_for(TileDetail::Small)["max-mbps"], 27_600);
810 let locked = SourceRequest {
811 mid: "2".into(),
812 stream_id: 203,
813 source: Some(1),
814 screen: false,
815 detail: TileDetail::Stage,
816 quality: VideoQuality::P720,
817 }
818 .body(1);
819 let parameter: Value = serde_json::from_str(
820 locked["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"]
821 .as_str()
822 .unwrap(),
823 )
824 .unwrap();
825 assert_eq!(
826 parameter["controlVideoStreaming"]["controlInfo"]["fmtParams"][0]["max-fs"],
827 3600
828 );
775 }
829 }
776
830
777 #[test]
831 #[test]
@@ -805,7 +859,7 @@ mod tests {
805
859
806 #[test]
860 #[test]
807 fn send_capabilities_name_the_camera_mid_and_the_largest_side() {
861 fn send_capabilities_name_the_camera_mid_and_the_largest_side() {
808 let body = send_capabilities_body(1280, 720, 4);
862 let body = send_capabilities_body(1280, 720, 4, VideoQuality::Auto);
809 let channel = &body["applyChannelParameters"]["multiChannelParameter"];
863 let channel = &body["applyChannelParameters"]["multiChannelParameter"];
810 assert_eq!(channel["mids"], json!(["1"]));
864 assert_eq!(channel["mids"], json!(["1"]));
811 let parameter: Value =
865 let parameter: Value =
@@ -817,21 +871,31 @@ mod tests {
817 }})
871 }})
818 );
872 );
819 let small: Value = serde_json::from_str(
873 let small: Value = serde_json::from_str(
820 send_capabilities_body(480, 270, 1)["applyChannelParameters"]["multiChannelParameter"]
874 send_capabilities_body(480, 270, 1, VideoQuality::Auto)
821 ["mediaParameter"]
875 ["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"]
822 .as_str()
876 .as_str()
823 .unwrap(),
877 .unwrap(),
824 )
878 )
825 .unwrap();
879 .unwrap();
826 assert_eq!(small["maxVideoSendCapabilities"]["max-layers"], 2);
880 assert_eq!(small["maxVideoSendCapabilities"]["max-layers"], 2);
881 let clamped: Value =
882 serde_json::from_str(
883 send_capabilities_body(3840, 2160, 1, VideoQuality::P720)["applyChannelParameters"]
884 ["multiChannelParameter"]["mediaParameter"]
885 .as_str()
886 .unwrap(),
887 )
888 .unwrap();
889 assert_eq!(clamped["maxVideoSendCapabilities"]["max-width"], 1280);
890 assert_eq!(clamped["maxVideoSendCapabilities"]["max-height"], 1280);
827 }
891 }
828
892
829 #[test]
893 #[test]
830 fn the_reporter_skips_a_repeated_size_and_counts_sequences() {
894 fn the_reporter_skips_a_repeated_size_and_counts_sequences() {
831 let mut reporter = SendCapabilityReporter::default();
895 let mut reporter = SendCapabilityReporter::default();
832 assert!(reporter.body_for((1280, 720)).is_some());
896 assert!(reporter.body_for((1280, 720), VideoQuality::Auto).is_some());
833 assert!(reporter.body_for((1280, 720)).is_none());
897 assert!(reporter.body_for((1280, 720), VideoQuality::Auto).is_none());
834 let body = reporter.body_for((640, 480)).unwrap();
898 let body = reporter.body_for((640, 480), VideoQuality::Auto).unwrap();
835 let parameter: Value = serde_json::from_str(
899 let parameter: Value = serde_json::from_str(
836 body["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"]
900 body["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"]
837 .as_str()
901 .as_str()
@@ -839,5 +903,6 @@ mod tests {
839 )
903 )
840 .unwrap();
904 .unwrap();
841 assert_eq!(parameter["maxVideoSendCapabilities"]["sequence-number"], 2);
905 assert_eq!(parameter["maxVideoSendCapabilities"]["sequence-number"], 2);
906 assert!(reporter.body_for((640, 480), VideoQuality::P720).is_some());
842 }
907 }
843}
908}
crates/calling/tests/sdp_golden.rs +1 −0
@@ -12,6 +12,7 @@ fn captured_plan() -> OfferPlan {
12 12 OfferPlan {
13 13 screen_share_mids: vec!["18".into()],
14 14 gallery_mids: (10..=17).map(|mid| mid.to_string()).collect(),
15 fold_groups: Vec::new(),
15 16 }
16 17 }
17 18
@@ -12,6 +12,7 @@ fn captured_plan() -> OfferPlan {
12 OfferPlan {
12 OfferPlan {
13 screen_share_mids: vec!["18".into()],
13 screen_share_mids: vec!["18".into()],
14 gallery_mids: (10..=17).map(|mid| mid.to_string()).collect(),
14 gallery_mids: (10..=17).map(|mid| mid.to_string()).collect(),
15 fold_groups: Vec::new(),
15 }
16 }
16}
17}
17
18