BlueGit

ict rusty-teams

feat: camera video quality Auto/720p/1080p

Persist the ceiling, prefer 1080 capture for Auto, raise stage receive
budgets when allowed, and ship as v0.3.0-joe.2.

metis Joachim Mild · pushed by metis

Authored 2026-11-12 · 2 weeks ago

Hash
039de50cce218d567ebe5d64bc8e0b0dd4e715c8
Parent
c853e8fb
21 files changed +1099 −617
CHANGELOG.md +0 −22
@@ -1,27 +1,5 @@
1 1 # Changelog
2 2
3 ## [0.3.0-joe.4] - 2026-11-12
4
5 ### Fixed
6
7 - Camera capture prefers MJPEG 1080p/720p at 30 fps on USB 2.0 webcams (e.g. C930e)
8 instead of falling back to YUYV 1080p at 5 fps; opens under 30 fps are rejected
9 when a faster format exists.
10 - MJPEG frames decode locally (zune-jpeg → I420) with reusable buffers.
11 - UVC best-effort: disable exposure dynamic framerate and set 50 Hz power-line
12 frequency; call reports log the chosen format plus capture fps / decode time.
13
14 ## [0.3.0-joe.3] - 2026-11-12
15
16 ### Fixed
17
18 - 1:1 escalation answers no longer emit an extra folded gallery m-line (`mid 3-0`),
19 which triggered Teams `InvalidNumberOfMedia` / «Incorrect number of media».
20 - Same-peer renegotiation keeps a short grace after the answer timeout so a late
21 camera answer (`recvonly`) can still be applied instead of rolling back send.
22 - Camera open survives UVC `CameraFormat` property failures (Closest NV12 first;
23 AbsoluteHighest only as last resort).
24
25 3 ## [0.3.0-joe.2] - 2026-11-12
26 4
27 5 ### Added
@@ -1,27 +1,5 @@
1# Changelog
1# Changelog
2
2
3## [0.3.0-joe.4] - 2026-11-12
4
5### Fixed
6
7- Camera capture prefers MJPEG 1080p/720p at 30 fps on USB 2.0 webcams (e.g. C930e)
8 instead of falling back to YUYV 1080p at 5 fps; opens under 30 fps are rejected
9 when a faster format exists.
10- MJPEG frames decode locally (zune-jpeg → I420) with reusable buffers.
11- UVC best-effort: disable exposure dynamic framerate and set 50 Hz power-line
12 frequency; call reports log the chosen format plus capture fps / decode time.
13
14## [0.3.0-joe.3] - 2026-11-12
15
16### Fixed
17
18- 1:1 escalation answers no longer emit an extra folded gallery m-line (`mid 3-0`),
19 which triggered Teams `InvalidNumberOfMedia` / «Incorrect number of media».
20- Same-peer renegotiation keeps a short grace after the answer timeout so a late
21 camera answer (`recvonly`) can still be applied instead of rolling back send.
22- Camera open survives UVC `CameraFormat` property failures (Closest NV12 first;
23 AbsoluteHighest only as last resort).
24
25## [0.3.0-joe.2] - 2026-11-12
3## [0.3.0-joe.2] - 2026-11-12
26
4
27### Added
5### Added
crates/app-call-model/src/demo.rs +1 −1
@@ -744,7 +744,7 @@ async fn speak_until_hangup(
744 744 people.iter().for_each(|(mri, _)| control.video.forget(&VideoKey::Person(mri.clone())));
745 745 control.send(CallUpdate::IncomingVideo(enabled));
746 746 }
747 Some(CallCommand::SetCameraEffects(_) | CallCommand::SetVideoWants(_) | CallCommand::SetShareMotion(_) | CallCommand::SetShareStandout(_)) => {}
747 Some(CallCommand::SetCameraEffects(_) | CallCommand::SetVideoQuality(_) | CallCommand::SetVideoWants(_) | CallCommand::SetShareMotion(_) | CallCommand::SetShareStandout(_)) => {}
748 748 Some(CallCommand::StartRecording { kind, .. }) => {
749 749 recording_on = kind != RecordingKind::TranscriptOnly;
750 750 transcribing_on = true;
@@ -744,7 +744,7 @@ async fn speak_until_hangup(
744 people.iter().for_each(|(mri, _)| control.video.forget(&VideoKey::Person(mri.clone())));
744 people.iter().for_each(|(mri, _)| control.video.forget(&VideoKey::Person(mri.clone())));
745 control.send(CallUpdate::IncomingVideo(enabled));
745 control.send(CallUpdate::IncomingVideo(enabled));
746 }
746 }
747 Some(CallCommand::SetCameraEffects(_) | CallCommand::SetVideoWants(_) | CallCommand::SetShareMotion(_) | CallCommand::SetShareStandout(_)) => {}
747 Some(CallCommand::SetCameraEffects(_) | CallCommand::SetVideoQuality(_) | CallCommand::SetVideoWants(_) | CallCommand::SetShareMotion(_) | CallCommand::SetShareStandout(_)) => {}
748 Some(CallCommand::StartRecording { kind, .. }) => {
748 Some(CallCommand::StartRecording { kind, .. }) => {
749 recording_on = kind != RecordingKind::TranscriptOnly;
749 recording_on = kind != RecordingKind::TranscriptOnly;
750 transcribing_on = true;
750 transcribing_on = true;
crates/app-call-model/src/preview.rs +2 −1
@@ -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,6 +59,7 @@ 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(),
63 64 CameraCaptureStats::new(),
64 65 |_label| {},
@@ -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,6 +59,7 @@ 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(),
63 CameraCaptureStats::new(),
64 CameraCaptureStats::new(),
64 |_label| {},
65 |_label| {},
crates/app-state/src/app_state.rs +3 −0
@@ -200,6 +200,7 @@ pub struct AppState {
200 200 pub call_input: calling::DeviceChoice,
201 201 pub call_output: calling::DeviceChoice,
202 202 pub call_mic: calling::MicSettings,
203 pub call_video_quality: calling::VideoQuality,
203 204 pub call_effects: calling::CameraEffects,
204 205 pub meet_now_pending: bool,
205 206 pub prejoin: Option<crate::call::PendingJoin>,
@@ -360,6 +361,7 @@ impl AppState {
360 361 call_input: calling::DeviceChoice::SystemDefault,
361 362 call_output: calling::DeviceChoice::SystemDefault,
362 363 call_mic: calling::MicSettings::default(),
364 call_video_quality: calling::VideoQuality::default(),
363 365 call_effects: calling::CameraEffects::default(),
364 366 meet_now_pending: false,
365 367 prejoin: None,
@@ -396,6 +398,7 @@ impl AppState {
396 398 state.call_output = crate::call::load_output(&state.store);
397 399 crate::call::apply_sound_output(&state.call_output);
398 400 state.call_mic = crate::call::load_mic(&state.store);
401 state.call_video_quality = crate::call::load_video_quality(&state.store);
399 402 state.call_effects = crate::call::load_camera_effects(&state.store);
400 403 state.join_options = crate::call::load_join_options(&state.store);
401 404 state.call_backgrounds.customs = crate::call::load_custom_backgrounds(&state.store);
@@ -200,6 +200,7 @@ pub struct AppState {
200 pub call_input: calling::DeviceChoice,
200 pub call_input: calling::DeviceChoice,
201 pub call_output: calling::DeviceChoice,
201 pub call_output: calling::DeviceChoice,
202 pub call_mic: calling::MicSettings,
202 pub call_mic: calling::MicSettings,
203 pub call_video_quality: calling::VideoQuality,
203 pub call_effects: calling::CameraEffects,
204 pub call_effects: calling::CameraEffects,
204 pub meet_now_pending: bool,
205 pub meet_now_pending: bool,
205 pub prejoin: Option<crate::call::PendingJoin>,
206 pub prejoin: Option<crate::call::PendingJoin>,
@@ -360,6 +361,7 @@ impl AppState {
360 call_input: calling::DeviceChoice::SystemDefault,
361 call_input: calling::DeviceChoice::SystemDefault,
361 call_output: calling::DeviceChoice::SystemDefault,
362 call_output: calling::DeviceChoice::SystemDefault,
362 call_mic: calling::MicSettings::default(),
363 call_mic: calling::MicSettings::default(),
364 call_video_quality: calling::VideoQuality::default(),
363 call_effects: calling::CameraEffects::default(),
365 call_effects: calling::CameraEffects::default(),
364 meet_now_pending: false,
366 meet_now_pending: false,
365 prejoin: None,
367 prejoin: None,
@@ -396,6 +398,7 @@ impl AppState {
396 state.call_output = crate::call::load_output(&state.store);
398 state.call_output = crate::call::load_output(&state.store);
397 crate::call::apply_sound_output(&state.call_output);
399 crate::call::apply_sound_output(&state.call_output);
398 state.call_mic = crate::call::load_mic(&state.store);
400 state.call_mic = crate::call::load_mic(&state.store);
401 state.call_video_quality = crate::call::load_video_quality(&state.store);
399 state.call_effects = crate::call::load_camera_effects(&state.store);
402 state.call_effects = crate::call::load_camera_effects(&state.store);
400 state.join_options = crate::call::load_join_options(&state.store);
403 state.join_options = crate::call::load_join_options(&state.store);
401 state.call_backgrounds.customs = crate::call::load_custom_backgrounds(&state.store);
404 state.call_backgrounds.customs = crate::call::load_custom_backgrounds(&state.store);
crates/app-state/src/call/actions.rs +237 −50
@@ -3,7 +3,8 @@ use std::time::{Duration, Instant};
3 3 use calling::meeting::LiveMeeting;
4 4 use calling::{
5 5 AcceptMode, CallCommand, CallHandle, CallSpec, CallState, CallUpdate, Callee, CameraEffects,
6 DeviceChoice, EndReason, EngineEvent, MicSettings, MuteCommand, Reaction, RingSignal, ShareSource, VideoKey,
6 DeviceChoice, EndReason, EngineEvent, MicSettings, MuteCommand, Reaction, RingSignal,
7 ShareKind, ShareSource, VideoKey,
7 8 };
8 9 use gpui_kit::*;
9 10
@@ -14,14 +15,15 @@ use super::demo::{
14 15 DemoCall, DemoScene, demo_caller, demo_guests, demo_ring, demo_video_ring, start_demo_call,
15 16 start_demo_scene_call,
16 17 };
18 use super::end_screen::{CallEndScreen, end_tone};
17 19 use super::features::{TransferCandidate, room_closed_move};
18 20 use super::media::CallMedia;
19 21 use super::mic::save_mic;
20 use super::end_screen::{CallEndScreen, end_tone};
21 22 use super::model::{ActiveCall, CallKind, CallModel, ConsultTransfer, ended_notice};
22 23 use super::prejoin::{DemoMeeting, MeetingJoin};
23 24 use super::report::{
24 CallRecorder, OwnIdentity, SETTING_META_KEY, SharedRecorder, report_directory, save_report, shared,
25 CallRecorder, OwnIdentity, SETTING_META_KEY, SharedRecorder, report_directory, save_report,
26 shared,
25 27 };
26 28 use super::ring::{MissedCall, RingOutcome};
27 29 use super::target::{is_echo_chat, is_organizer, plan_for_chat};
@@ -46,6 +48,7 @@ const DEMO_LIVE_MINUTES: i64 = 60;
46 48 const ORGID_PREFIX: &str = "8:orgid:";
47 49 pub const SHARE_SOUND_META_KEY: &str = "call_share_sound";
48 50 const CAMERA_META_KEY: &str = "call_camera";
51 const VIDEO_QUALITY_META_KEY: &str = "call_video_quality";
49 52 const INPUT_META_KEY: &str = "call_input";
50 53 pub fn apply_sound_output(choice: &DeviceChoice) {
51 54 let device_key = match choice {
@@ -93,6 +96,19 @@ pub fn load_camera_effects(store: &store::Store) -> CameraEffects {
93 96 })
94 97 }
95 98
99 pub fn load_video_quality(store: &store::Store) -> calling::VideoQuality {
100 store
101 .meta(VIDEO_QUALITY_META_KEY)
102 .ok()
103 .flatten()
104 .as_deref()
105 .map_or_else(calling::VideoQuality::default, calling::VideoQuality::from_meta)
106 }
107
108 pub fn save_video_quality(store: &store::Store, quality: calling::VideoQuality) {
109 let _ = store.set_meta(VIDEO_QUALITY_META_KEY, quality.to_meta());
110 }
111
96 112 fn device_meta(choice: &DeviceChoice) -> &str {
97 113 match choice {
98 114 DeviceChoice::SystemDefault => DEFAULT_DEVICE_META,
@@ -143,12 +159,20 @@ impl AppState {
143 159 self.show_call(true, cx);
144 160 return;
145 161 }
146 let chat = self.sidebar.chats.iter().find(|chat| chat.id == conversation_id);
162 let chat = self
163 .sidebar
164 .chats
165 .iter()
166 .find(|chat| chat.id == conversation_id);
147 167 if chat.is_some_and(is_echo_chat) {
148 168 self.start_test_call(cx);
149 169 return;
150 170 }
151 let chat = self.sidebar.chats.iter().find(|chat| chat.id == conversation_id);
171 let chat = self
172 .sidebar
173 .chats
174 .iter()
175 .find(|chat| chat.id == conversation_id);
152 176 let plan = chat.and_then(|chat| plan_for_chat(chat, self.directory.me.as_ref()));
153 177 let Some(plan) = plan else {
154 178 self.raise_notice(NOT_CALLABLE_NOTICE.to_owned(), None, cx);
@@ -276,6 +300,7 @@ impl AppState {
276 300 if self.call_mic != MicSettings::default() {
277 301 self.send_call_command(CallCommand::SetMicSettings(self.call_mic));
278 302 }
303 self.send_call_command(CallCommand::SetVideoQuality(self.call_video_quality));
279 304 if let Some(call) = self.call.as_mut() {
280 305 call.model.background = self.call_background.clone();
281 306 call.model.camera = self.call_camera.clone();
@@ -301,7 +326,10 @@ impl AppState {
301 326 if let Some(call) = self.call.as_mut() {
302 327 call.report.clone_from(&report);
303 328 }
304 let rights_conversation = self.call.as_ref().and_then(|call| call.conversation_id.clone());
329 let rights_conversation = self
330 .call
331 .as_ref()
332 .and_then(|call| call.conversation_id.clone());
305 333 self.apply_recording_rights(rights_conversation.as_deref(), cx);
306 334 self.follow_call(call_id, updates, report, cx);
307 335 cx.emit(AppEvent::Call);
@@ -345,8 +373,15 @@ impl AppState {
345 373 let action = NoticeAction::new("Open folder", move |_, _| {
346 374 crate::downloads::reveal_in_file_manager(&path)
347 375 });
348 let text = match self.notice.as_ref().filter(|notice| notice.action.is_none()) {
349 Some(ended) => format!("{}. {REPORT_SAVED_NOTICE}", ended.text.trim_end_matches('.')),
376 let text = match self
377 .notice
378 .as_ref()
379 .filter(|notice| notice.action.is_none())
380 {
381 Some(ended) => format!(
382 "{}. {REPORT_SAVED_NOTICE}",
383 ended.text.trim_end_matches('.')
384 ),
350 385 None => REPORT_SAVED_NOTICE.to_owned(),
351 386 };
352 387 self.raise_notice(text, Some(action), cx);
@@ -354,7 +389,9 @@ impl AppState {
354 389
355 390 pub fn set_call_report_enabled(&mut self, on: bool, cx: &mut Context<Self>) {
356 391 self.call_report_enabled = on;
357 let _ = self.store.set_meta(SETTING_META_KEY, if on { "1" } else { "0" });
392 let _ = self
393 .store
394 .set_meta(SETTING_META_KEY, if on { "1" } else { "0" });
358 395 cx.notify();
359 396 }
360 397
@@ -381,7 +418,9 @@ impl AppState {
381 418 return;
382 419 };
383 420 let reason = EndReason::Failed("The call stopped unexpectedly".to_owned());
384 report.borrow_mut().observe(&CallUpdate::State(CallState::Ended { reason }));
421 report
422 .borrow_mut()
423 .observe(&CallUpdate::State(CallState::Ended { reason }));
385 424 let recorder = report.borrow().clone();
386 425 let saved = cx
387 426 .background_executor()
@@ -436,7 +475,8 @@ impl AppState {
436 475 CallUpdate::Roster(entries) => entries,
437 476 other => return other,
438 477 };
439 let user_id = |entry: &calling::RosterEntry| entry.mri.strip_prefix(ORGID_PREFIX).map(str::to_owned);
478 let user_id =
479 |entry: &calling::RosterEntry| entry.mri.strip_prefix(ORGID_PREFIX).map(str::to_owned);
440 480 let missing: Vec<String> = entries
441 481 .iter()
442 482 .filter(|entry| entry.display_name.is_empty())
@@ -444,7 +484,10 @@ impl AppState {
444 484 .collect();
445 485 if !missing.is_empty() {
446 486 let names = crate::people::resolve_names(self, &missing);
447 for entry in entries.iter_mut().filter(|entry| entry.display_name.is_empty()) {
487 for entry in entries
488 .iter_mut()
489 .filter(|entry| entry.display_name.is_empty())
490 {
448 491 if let Some(name) = user_id(entry).and_then(|id| names.get(&id)) {
449 492 entry.display_name = name.clone();
450 493 }
@@ -515,7 +558,11 @@ impl AppState {
515 558 return;
516 559 }
517 560 CallUpdate::MeetingOptionsSaved(result) => {
518 if call.options_dialog.as_mut().is_some_and(|dialog| dialog.saved(result)) {
561 if call
562 .options_dialog
563 .as_mut()
564 .is_some_and(|dialog| dialog.saved(result))
565 {
519 566 call.options_dialog = None;
520 567 }
521 568 cx.notify();
@@ -532,6 +579,7 @@ impl AppState {
532 579 crate::agent_api::note_caption(thread, &entry.id, speaker, &entry.text, cx);
533 580 }
534 581 let sharer_before = call.model.screen_sharer.clone();
582 let local_share_before = call.model.local_share.is_some();
535 583 let lobby_before = call.model.lobby_mris();
536 584 call.model.apply(update);
537 585 if call.model.someone_entered_the_lobby(&lobby_before)
@@ -540,13 +588,27 @@ impl AppState {
540 588 .is_none_or(|played_at| played_at.elapsed() >= LOBBY_TONE_THROTTLE)
541 589 {
542 590 call.lobby_tone_at = Some(Instant::now());
543 cx.emit(AppEvent::CallTone(chatsvc::sounds::CallTone::MeetingReminder));
591 cx.emit(AppEvent::CallTone(
592 chatsvc::sounds::CallTone::MeetingReminder,
593 ));
594 }
595 if !local_share_before && call.model.local_share.is_some() && call.chat_thread().is_some()
596 {
597 call.chat_open = true;
598 call.transcript_open = false;
599 call.people_open = false;
600 self.transcript_panel = None;
601 }
602 if call.model.local_share.is_none() {
603 call.pictures.forget(&VideoKey::LocalScreen, cx);
544 604 }
545 605 if call.model.screen_sharer != sharer_before {
546 606 call.pictures.forget(&VideoKey::Screen, cx);
547 607 }
548 608 if let Some(language) = call.model.take_ready_caption_language() {
549 let _ = call.commands.send(CallCommand::SetCaptionLanguage(language));
609 let _ = call
610 .commands
611 .send(CallCommand::SetCaptionLanguage(language));
550 612 }
551 613 if call.model.screen_sharer.is_none() {
552 614 call.stage_fullscreen = false;
@@ -640,6 +702,17 @@ impl AppState {
640 702 cx.notify();
641 703 }
642 704
705 pub fn set_call_video_quality(
706 &mut self,
707 quality: calling::VideoQuality,
708 cx: &mut Context<Self>,
709 ) {
710 self.call_video_quality = quality;
711 save_video_quality(&self.store, quality);
712 self.send_call_command(CallCommand::SetVideoQuality(quality));
713 cx.notify();
714 }
715
643 716 pub fn press_push_to_talk(&mut self, _cx: &mut Context<Self>) {
644 717 let Some(call) = self.call.as_mut() else {
645 718 return;
@@ -678,6 +751,10 @@ impl AppState {
678 751 self.send_call_command(CallCommand::StartShare(source));
679 752 }
680 753
754 pub fn start_portal_share(&mut self, kind: ShareKind, _cx: &mut Context<Self>) {
755 self.send_call_command(CallCommand::StartPortalShare(kind));
756 }
757
681 758 pub fn stop_call_share(&mut self, _cx: &mut Context<Self>) {
682 759 self.send_call_command(CallCommand::StopShare);
683 760 }
@@ -823,7 +900,8 @@ impl AppState {
823 900 return;
824 901 };
825 902 if let Some(own_mri) = call.model.own_mri.clone() {
826 call.model.note_reaction(own_mri, reaction.clone(), Instant::now());
903 call.model
904 .note_reaction(own_mri, reaction.clone(), Instant::now());
827 905 }
828 906 self.send_call_command(CallCommand::SendReaction(reaction));
829 907 cx.emit(AppEvent::Call);
@@ -1405,21 +1483,24 @@ mod tests {
1405 1483 use calling::{
1406 1484 BackgroundChoice, CallCommand, CallControl, CallState, CallUpdate, CameraEffects,
1407 1485 DeviceChoice, EndKind, EndReason, EngineEvent, HoldState, Reaction, RecordingKind,
1408 StopScope, call_channel,
1486 StopScope, VideoQuality, call_channel,
1409 1487 };
1410 1488 use gpui_kit::{AppContext as _, Entity, TestAppContext};
1411 1489 use store::{ChatRecord, MemberRecord, Store};
1412 1490
1413 use super::{ActiveCall, CallModel, load_camera, load_camera_effects, load_input, load_output};
1491 use super::{
1492 ActiveCall, CallModel, load_camera, load_camera_effects, load_input, load_output,
1493 load_video_quality,
1494 };
1414 1495 use crate::app_state::{AppEvent, AppState, Mode, Selection};
1415 1496 use crate::call::TransferCandidate;
1416 1497 use crate::call::background::BackgroundPick;
1417 use crate::call::{CaptionPosition, CaptionSize, RecordAction, ViewSettings};
1418 1498 use crate::call::demo::demo_ring;
1419 use chatsvc::sounds::CallTone;
1420 1499 use crate::call::features::room_closed_move;
1421 1500 use crate::call::model::BreakoutState;
1501 use crate::call::{CaptionPosition, CaptionSize, RecordAction, ViewSettings};
1422 1502 use crate::data::Person;
1503 use chatsvc::sounds::CallTone;
1423 1504
1424 1505 fn app_with_call(cx: &mut TestAppContext) -> Entity<AppState> {
1425 1506 cx.update(gpui_kit::init);
@@ -1522,7 +1603,15 @@ mod tests {
1522 1603 let app = app_with_call(cx);
1523 1604 let key = calling::VideoKey::Person("8:orgid:peer".into());
1524 1605 let shown = |app: &Entity<AppState>, cx: &mut TestAppContext| {
1525 cx.update(|cx| app.read(cx).call.as_ref().unwrap().pictures.live(&key, Instant::now()).is_some())
1606 cx.update(|cx| {
1607 app.read(cx)
1608 .call
1609 .as_ref()
1610 .unwrap()
1611 .pictures
1612 .live(&key, Instant::now())
1613 .is_some()
1614 })
1526 1615 };
1527 1616 cx.update(|cx| {
1528 1617 app.update(cx, |state, cx| {
@@ -1568,11 +1657,16 @@ mod tests {
1568 1657 state.select_call_output(DeviceChoice::Device("headset".into()), cx);
1569 1658 })
1570 1659 });
1571 assert_eq!(load_input(&store), DeviceChoice::Device("headset-mic".into()));
1660 assert_eq!(
1661 load_input(&store),
1662 DeviceChoice::Device("headset-mic".into())
1663 );
1572 1664 assert_eq!(load_output(&store), DeviceChoice::Device("headset".into()));
1573 1665 assert_eq!(
1574 1666 control.try_recv_command(),
1575 Some(CallCommand::SelectInput(DeviceChoice::Device("headset-mic".into())))
1667 Some(CallCommand::SelectInput(DeviceChoice::Device(
1668 "headset-mic".into()
1669 )))
1576 1670 );
1577 1671 cx.update(|cx| {
1578 1672 app.update(cx, |state, cx| {
@@ -1610,12 +1704,17 @@ mod tests {
1610 1704 while let Some(command) = control.try_recv_command() {
1611 1705 commands.push(command);
1612 1706 }
1613 assert!(commands.contains(&CallCommand::SelectInput(DeviceChoice::Device(
1614 "unplugged-mic".into()
1615 ))));
1616 assert!(commands.contains(&CallCommand::SelectOutput(DeviceChoice::Device(
1617 "headset".into()
1618 ))));
1707 assert!(
1708 commands.contains(&CallCommand::SelectInput(DeviceChoice::Device(
1709 "unplugged-mic".into()
1710 )))
1711 );
1712 assert!(
1713 commands.contains(&CallCommand::SelectOutput(DeviceChoice::Device(
1714 "headset".into()
1715 )))
1716 );
1717 assert!(commands.contains(&CallCommand::SetVideoQuality(VideoQuality::Auto)));
1619 1718 assert_eq!(
1620 1719 load_input(&store),
1621 1720 DeviceChoice::Device("unplugged-mic".into())
@@ -1668,6 +1767,28 @@ mod tests {
1668 1767 assert_eq!(cx.update(|cx| reopened.read(cx).call_effects), effects);
1669 1768 }
1670 1769
1770 #[gpui_kit::test]
1771 fn the_video_quality_is_remembered_and_sent_to_the_call(cx: &mut TestAppContext) {
1772 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
1773 let store = cx.update(|cx| app.read(cx).store.clone());
1774 assert_eq!(load_video_quality(&store), VideoQuality::Auto);
1775 cx.update(|cx| {
1776 app.update(cx, |state, cx| {
1777 state.set_call_video_quality(VideoQuality::P1080, cx)
1778 })
1779 });
1780 assert_eq!(
1781 control.try_recv_command(),
1782 Some(CallCommand::SetVideoQuality(VideoQuality::P1080))
1783 );
1784 assert_eq!(load_video_quality(&store), VideoQuality::P1080);
1785 let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
1786 assert_eq!(
1787 cx.update(|cx| reopened.read(cx).call_video_quality),
1788 VideoQuality::P1080
1789 );
1790 }
1791
1671 1792 #[gpui_kit::test]
1672 1793 fn hands_and_reactions_become_call_commands_and_lowering_needs_the_organizer(
1673 1794 cx: &mut TestAppContext,
@@ -1981,16 +2102,39 @@ mod tests {
1981 2102 cx.update(|cx| {
1982 2103 organizer.update(cx, |state, cx| {
1983 2104 state.run_call_record_action(RecordAction::Start(RecordingKind::AudioOnly), cx);
1984 state.run_call_record_action(RecordAction::Start(RecordingKind::TranscriptOnly), cx);
2105 state
2106 .run_call_record_action(RecordAction::Start(RecordingKind::TranscriptOnly), cx);
1985 2107 state.run_call_record_action(RecordAction::Stop(StopScope::RecordingOnly), cx);
1986 2108 state.run_call_record_action(RecordAction::Stop(StopScope::TranscriptionOnly), cx);
1987 2109 })
1988 2110 });
1989 2111 let title = "Standup".to_owned();
1990 assert_eq!(control.try_recv_command(), Some(CallCommand::StartRecording { kind: RecordingKind::AudioOnly, title: title.clone() }));
1991 assert_eq!(control.try_recv_command(), Some(CallCommand::StartRecording { kind: RecordingKind::TranscriptOnly, title }));
1992 assert_eq!(control.try_recv_command(), Some(CallCommand::StopRecording { scope: StopScope::RecordingOnly }));
1993 assert_eq!(control.try_recv_command(), Some(CallCommand::StopRecording { scope: StopScope::TranscriptionOnly }));
2112 assert_eq!(
2113 control.try_recv_command(),
2114 Some(CallCommand::StartRecording {
2115 kind: RecordingKind::AudioOnly,
2116 title: title.clone()
2117 })
2118 );
2119 assert_eq!(
2120 control.try_recv_command(),
2121 Some(CallCommand::StartRecording {
2122 kind: RecordingKind::TranscriptOnly,
2123 title
2124 })
2125 );
2126 assert_eq!(
2127 control.try_recv_command(),
2128 Some(CallCommand::StopRecording {
2129 scope: StopScope::RecordingOnly
2130 })
2131 );
2132 assert_eq!(
2133 control.try_recv_command(),
2134 Some(CallCommand::StopRecording {
2135 scope: StopScope::TranscriptionOnly
2136 })
2137 );
1994 2138 assert_eq!(control.try_recv_command(), None);
1995 2139 }
1996 2140
@@ -1999,7 +2143,11 @@ mod tests {
1999 2143 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
2000 2144 cx.update(|cx| {
2001 2145 app.update(cx, |state, cx| {
2002 state.apply_call_update(7, CallUpdate::MeetingChat("19:meeting_x@thread.v2".into()), cx);
2146 state.apply_call_update(
2147 7,
2148 CallUpdate::MeetingChat("19:meeting_x@thread.v2".into()),
2149 cx,
2150 );
2003 2151 state.toggle_call_chat(cx);
2004 2152 state.show_call_transcript(cx);
2005 2153 })
@@ -2009,7 +2157,10 @@ mod tests {
2009 2157 (call.chat_open, call.transcript_open)
2010 2158 });
2011 2159 assert!(!chat_open && transcript_open);
2012 assert_eq!(control.try_recv_command(), Some(CallCommand::SetCaptions(true)));
2160 assert_eq!(
2161 control.try_recv_command(),
2162 Some(CallCommand::SetCaptions(true))
2163 );
2013 2164 cx.update(|cx| {
2014 2165 app.update(cx, |state, cx| {
2015 2166 state.apply_call_update(7, CallUpdate::Captions(calling::CaptionState::On), cx);
@@ -2026,15 +2177,24 @@ mod tests {
2026 2177 }
2027 2178
2028 2179 #[gpui_kit::test]
2029 fn a_spoken_language_picked_while_captions_are_off_is_sent_once_they_are_on(cx: &mut TestAppContext) {
2180 fn a_spoken_language_picked_while_captions_are_off_is_sent_once_they_are_on(
2181 cx: &mut TestAppContext,
2182 ) {
2030 2183 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
2031 2184 cx.update(|cx| {
2032 2185 app.update(cx, |state, cx| {
2033 2186 state.choose_call_caption_language("de-DE", cx);
2034 state.apply_call_update(7, CallUpdate::Captions(calling::CaptionState::Starting), cx);
2187 state.apply_call_update(
2188 7,
2189 CallUpdate::Captions(calling::CaptionState::Starting),
2190 cx,
2191 );
2035 2192 })
2036 2193 });
2037 assert_eq!(control.try_recv_command(), Some(CallCommand::SetCaptions(true)));
2194 assert_eq!(
2195 control.try_recv_command(),
2196 Some(CallCommand::SetCaptions(true))
2197 );
2038 2198 assert_eq!(control.try_recv_command(), None);
2039 2199 cx.update(|cx| {
2040 2200 app.update(cx, |state, cx| {
@@ -2042,8 +2202,14 @@ mod tests {
2042 2202 state.choose_call_caption_language("fr-FR", cx);
2043 2203 })
2044 2204 });
2045 assert_eq!(control.try_recv_command(), Some(CallCommand::SetCaptionLanguage("de-DE".into())));
2046 assert_eq!(control.try_recv_command(), Some(CallCommand::SetCaptionLanguage("fr-FR".into())));
2205 assert_eq!(
2206 control.try_recv_command(),
2207 Some(CallCommand::SetCaptionLanguage("de-DE".into()))
2208 );
2209 assert_eq!(
2210 control.try_recv_command(),
2211 Some(CallCommand::SetCaptionLanguage("fr-FR".into()))
2212 );
2047 2213 assert_eq!(control.try_recv_command(), None);
2048 2214 }
2049 2215
@@ -2058,10 +2224,19 @@ mod tests {
2058 2224 });
2059 2225 let (view, stored) = cx.update(|cx| {
2060 2226 let state = app.read(cx);
2061 (state.call.as_ref().unwrap().model.view, ViewSettings::load(&state.store))
2227 (
2228 state.call.as_ref().unwrap().model.view,
2229 ViewSettings::load(&state.store),
2230 )
2062 2231 });
2063 assert_eq!((view.caption_size, view.caption_position), (CaptionSize::Large, CaptionPosition::Top));
2064 assert_eq!((stored.caption_size, stored.caption_position), (CaptionSize::Large, CaptionPosition::Top));
2232 assert_eq!(
2233 (view.caption_size, view.caption_position),
2234 (CaptionSize::Large, CaptionPosition::Top)
2235 );
2236 assert_eq!(
2237 (stored.caption_size, stored.caption_position),
2238 (CaptionSize::Large, CaptionPosition::Top)
2239 );
2065 2240 }
2066 2241
2067 2242 fn live_one_to_one() -> CallModel {
@@ -2102,9 +2277,7 @@ mod tests {
2102 2277 }
2103 2278
2104 2279 #[gpui_kit::test]
2105 fn a_blind_transfer_names_the_target(
2106 cx: &mut TestAppContext,
2107 ) {
2280 fn a_blind_transfer_names_the_target(cx: &mut TestAppContext) {
2108 2281 let (app, mut control) = app_with_commands(cx, live_one_to_one(), None);
2109 2282 cx.update(|cx| {
2110 2283 app.update(cx, |state, cx| {
@@ -2389,12 +2562,14 @@ mod tests {
2389 2562 }
2390 2563
2391 2564 #[gpui_kit::test]
2392 fn picking_another_chat_keeps_the_call_window_showing_the_call(cx: &mut TestAppContext) {
2565 fn picking_another_chat_moves_the_call_to_the_mini_window(cx: &mut TestAppContext) {
2393 2566 let app = app_with_call(cx);
2394 2567 cx.update(|cx| {
2395 2568 app.update(cx, |state, cx| {
2396 2569 assert!(state.viewing_call());
2397 2570 state.select(Selection::Chat("c1".into()), cx);
2571 assert!(!state.viewing_call());
2572 state.show_call(true, cx);
2398 2573 assert!(state.viewing_call());
2399 2574 })
2400 2575 });
@@ -2435,7 +2610,13 @@ mod tests {
2435 2610 })
2436 2611 .detach();
2437 2612 app.update(cx, |state, cx| {
2438 state.apply_call_update(7, CallUpdate::State(CallState::Ended { reason: EndReason::Dropped }), cx);
2613 state.apply_call_update(
2614 7,
2615 CallUpdate::State(CallState::Ended {
2616 reason: EndReason::Dropped,
2617 }),
2618 cx,
2619 );
2439 2620 assert!(state.call.is_none());
2440 2621 assert!(state.notice.is_none());
2441 2622 let screen = state.call_end.as_ref().expect("end screen");
@@ -2453,7 +2634,13 @@ mod tests {
2453 2634 let app = app_with_call(cx);
2454 2635 cx.update(|cx| {
2455 2636 app.update(cx, |state, cx| {
2456 state.apply_call_update(7, CallUpdate::State(CallState::Ended { reason: EndReason::Remote(EndKind::Removed) }), cx);
2637 state.apply_call_update(
2638 7,
2639 CallUpdate::State(CallState::Ended {
2640 reason: EndReason::Remote(EndKind::Removed),
2641 }),
2642 cx,
2643 );
2457 2644 assert!(state.call_end.is_none());
2458 2645 assert!(state.notice.is_some());
2459 2646 })
@@ -3,7 +3,8 @@ use std::time::{Duration, Instant};
3use calling::meeting::LiveMeeting;
3use calling::meeting::LiveMeeting;
4use calling::{
4use calling::{
5 AcceptMode, CallCommand, CallHandle, CallSpec, CallState, CallUpdate, Callee, CameraEffects,
5 AcceptMode, CallCommand, CallHandle, CallSpec, CallState, CallUpdate, Callee, CameraEffects,
6 DeviceChoice, EndReason, EngineEvent, MicSettings, MuteCommand, Reaction, RingSignal, ShareSource, VideoKey,
6 DeviceChoice, EndReason, EngineEvent, MicSettings, MuteCommand, Reaction, RingSignal,
7 ShareKind, ShareSource, VideoKey,
7};
8};
8use gpui_kit::*;
9use gpui_kit::*;
9
10
@@ -14,14 +15,15 @@ use super::demo::{
14 DemoCall, DemoScene, demo_caller, demo_guests, demo_ring, demo_video_ring, start_demo_call,
15 DemoCall, DemoScene, demo_caller, demo_guests, demo_ring, demo_video_ring, start_demo_call,
15 start_demo_scene_call,
16 start_demo_scene_call,
16};
17};
18use super::end_screen::{CallEndScreen, end_tone};
17use super::features::{TransferCandidate, room_closed_move};
19use super::features::{TransferCandidate, room_closed_move};
18use super::media::CallMedia;
20use super::media::CallMedia;
19use super::mic::save_mic;
21use super::mic::save_mic;
20use super::end_screen::{CallEndScreen, end_tone};
21use super::model::{ActiveCall, CallKind, CallModel, ConsultTransfer, ended_notice};
22use super::model::{ActiveCall, CallKind, CallModel, ConsultTransfer, ended_notice};
22use super::prejoin::{DemoMeeting, MeetingJoin};
23use super::prejoin::{DemoMeeting, MeetingJoin};
23use super::report::{
24use super::report::{
24 CallRecorder, OwnIdentity, SETTING_META_KEY, SharedRecorder, report_directory, save_report, shared,
25 CallRecorder, OwnIdentity, SETTING_META_KEY, SharedRecorder, report_directory, save_report,
26 shared,
25};
27};
26use super::ring::{MissedCall, RingOutcome};
28use super::ring::{MissedCall, RingOutcome};
27use super::target::{is_echo_chat, is_organizer, plan_for_chat};
29use super::target::{is_echo_chat, is_organizer, plan_for_chat};
@@ -46,6 +48,7 @@ const DEMO_LIVE_MINUTES: i64 = 60;
46const ORGID_PREFIX: &str = "8:orgid:";
48const ORGID_PREFIX: &str = "8:orgid:";
47pub const SHARE_SOUND_META_KEY: &str = "call_share_sound";
49pub const SHARE_SOUND_META_KEY: &str = "call_share_sound";
48const CAMERA_META_KEY: &str = "call_camera";
50const CAMERA_META_KEY: &str = "call_camera";
51const VIDEO_QUALITY_META_KEY: &str = "call_video_quality";
49const INPUT_META_KEY: &str = "call_input";
52const INPUT_META_KEY: &str = "call_input";
50pub fn apply_sound_output(choice: &DeviceChoice) {
53pub fn apply_sound_output(choice: &DeviceChoice) {
51 let device_key = match choice {
54 let device_key = match choice {
@@ -93,6 +96,19 @@ pub fn load_camera_effects(store: &store::Store) -> CameraEffects {
93 })
96 })
94}
97}
95
98
99pub fn load_video_quality(store: &store::Store) -> calling::VideoQuality {
100 store
101 .meta(VIDEO_QUALITY_META_KEY)
102 .ok()
103 .flatten()
104 .as_deref()
105 .map_or_else(calling::VideoQuality::default, calling::VideoQuality::from_meta)
106}
107
108pub fn save_video_quality(store: &store::Store, quality: calling::VideoQuality) {
109 let _ = store.set_meta(VIDEO_QUALITY_META_KEY, quality.to_meta());
110}
111
96fn device_meta(choice: &DeviceChoice) -> &str {
112fn device_meta(choice: &DeviceChoice) -> &str {
97 match choice {
113 match choice {
98 DeviceChoice::SystemDefault => DEFAULT_DEVICE_META,
114 DeviceChoice::SystemDefault => DEFAULT_DEVICE_META,
@@ -143,12 +159,20 @@ impl AppState {
143 self.show_call(true, cx);
159 self.show_call(true, cx);
144 return;
160 return;
145 }
161 }
146 let chat = self.sidebar.chats.iter().find(|chat| chat.id == conversation_id);
162 let chat = self
163 .sidebar
164 .chats
165 .iter()
166 .find(|chat| chat.id == conversation_id);
147 if chat.is_some_and(is_echo_chat) {
167 if chat.is_some_and(is_echo_chat) {
148 self.start_test_call(cx);
168 self.start_test_call(cx);
149 return;
169 return;
150 }
170 }
151 let chat = self.sidebar.chats.iter().find(|chat| chat.id == conversation_id);
171 let chat = self
172 .sidebar
173 .chats
174 .iter()
175 .find(|chat| chat.id == conversation_id);
152 let plan = chat.and_then(|chat| plan_for_chat(chat, self.directory.me.as_ref()));
176 let plan = chat.and_then(|chat| plan_for_chat(chat, self.directory.me.as_ref()));
153 let Some(plan) = plan else {
177 let Some(plan) = plan else {
154 self.raise_notice(NOT_CALLABLE_NOTICE.to_owned(), None, cx);
178 self.raise_notice(NOT_CALLABLE_NOTICE.to_owned(), None, cx);
@@ -276,6 +300,7 @@ impl AppState {
276 if self.call_mic != MicSettings::default() {
300 if self.call_mic != MicSettings::default() {
277 self.send_call_command(CallCommand::SetMicSettings(self.call_mic));
301 self.send_call_command(CallCommand::SetMicSettings(self.call_mic));
278 }
302 }
303 self.send_call_command(CallCommand::SetVideoQuality(self.call_video_quality));
279 if let Some(call) = self.call.as_mut() {
304 if let Some(call) = self.call.as_mut() {
280 call.model.background = self.call_background.clone();
305 call.model.background = self.call_background.clone();
281 call.model.camera = self.call_camera.clone();
306 call.model.camera = self.call_camera.clone();
@@ -301,7 +326,10 @@ impl AppState {
301 if let Some(call) = self.call.as_mut() {
326 if let Some(call) = self.call.as_mut() {
302 call.report.clone_from(&report);
327 call.report.clone_from(&report);
303 }
328 }
304 let rights_conversation = self.call.as_ref().and_then(|call| call.conversation_id.clone());
329 let rights_conversation = self
330 .call
331 .as_ref()
332 .and_then(|call| call.conversation_id.clone());
305 self.apply_recording_rights(rights_conversation.as_deref(), cx);
333 self.apply_recording_rights(rights_conversation.as_deref(), cx);
306 self.follow_call(call_id, updates, report, cx);
334 self.follow_call(call_id, updates, report, cx);
307 cx.emit(AppEvent::Call);
335 cx.emit(AppEvent::Call);
@@ -345,8 +373,15 @@ impl AppState {
345 let action = NoticeAction::new("Open folder", move |_, _| {
373 let action = NoticeAction::new("Open folder", move |_, _| {
346 crate::downloads::reveal_in_file_manager(&path)
374 crate::downloads::reveal_in_file_manager(&path)
347 });
375 });
348 let text = match self.notice.as_ref().filter(|notice| notice.action.is_none()) {
376 let text = match self
349 Some(ended) => format!("{}. {REPORT_SAVED_NOTICE}", ended.text.trim_end_matches('.')),
377 .notice
378 .as_ref()
379 .filter(|notice| notice.action.is_none())
380 {
381 Some(ended) => format!(
382 "{}. {REPORT_SAVED_NOTICE}",
383 ended.text.trim_end_matches('.')
384 ),
350 None => REPORT_SAVED_NOTICE.to_owned(),
385 None => REPORT_SAVED_NOTICE.to_owned(),
351 };
386 };
352 self.raise_notice(text, Some(action), cx);
387 self.raise_notice(text, Some(action), cx);
@@ -354,7 +389,9 @@ impl AppState {
354
389
355 pub fn set_call_report_enabled(&mut self, on: bool, cx: &mut Context<Self>) {
390 pub fn set_call_report_enabled(&mut self, on: bool, cx: &mut Context<Self>) {
356 self.call_report_enabled = on;
391 self.call_report_enabled = on;
357 let _ = self.store.set_meta(SETTING_META_KEY, if on { "1" } else { "0" });
392 let _ = self
393 .store
394 .set_meta(SETTING_META_KEY, if on { "1" } else { "0" });
358 cx.notify();
395 cx.notify();
359 }
396 }
360
397
@@ -381,7 +418,9 @@ impl AppState {
381 return;
418 return;
382 };
419 };
383 let reason = EndReason::Failed("The call stopped unexpectedly".to_owned());
420 let reason = EndReason::Failed("The call stopped unexpectedly".to_owned());
384 report.borrow_mut().observe(&CallUpdate::State(CallState::Ended { reason }));
421 report
422 .borrow_mut()
423 .observe(&CallUpdate::State(CallState::Ended { reason }));
385 let recorder = report.borrow().clone();
424 let recorder = report.borrow().clone();
386 let saved = cx
425 let saved = cx
387 .background_executor()
426 .background_executor()
@@ -436,7 +475,8 @@ impl AppState {
436 CallUpdate::Roster(entries) => entries,
475 CallUpdate::Roster(entries) => entries,
437 other => return other,
476 other => return other,
438 };
477 };
439 let user_id = |entry: &calling::RosterEntry| entry.mri.strip_prefix(ORGID_PREFIX).map(str::to_owned);
478 let user_id =
479 |entry: &calling::RosterEntry| entry.mri.strip_prefix(ORGID_PREFIX).map(str::to_owned);
440 let missing: Vec<String> = entries
480 let missing: Vec<String> = entries
441 .iter()
481 .iter()
442 .filter(|entry| entry.display_name.is_empty())
482 .filter(|entry| entry.display_name.is_empty())
@@ -444,7 +484,10 @@ impl AppState {
444 .collect();
484 .collect();
445 if !missing.is_empty() {
485 if !missing.is_empty() {
446 let names = crate::people::resolve_names(self, &missing);
486 let names = crate::people::resolve_names(self, &missing);
447 for entry in entries.iter_mut().filter(|entry| entry.display_name.is_empty()) {
487 for entry in entries
488 .iter_mut()
489 .filter(|entry| entry.display_name.is_empty())
490 {
448 if let Some(name) = user_id(entry).and_then(|id| names.get(&id)) {
491 if let Some(name) = user_id(entry).and_then(|id| names.get(&id)) {
449 entry.display_name = name.clone();
492 entry.display_name = name.clone();
450 }
493 }
@@ -515,7 +558,11 @@ impl AppState {
515 return;
558 return;
516 }
559 }
517 CallUpdate::MeetingOptionsSaved(result) => {
560 CallUpdate::MeetingOptionsSaved(result) => {
518 if call.options_dialog.as_mut().is_some_and(|dialog| dialog.saved(result)) {
561 if call
562 .options_dialog
563 .as_mut()
564 .is_some_and(|dialog| dialog.saved(result))
565 {
519 call.options_dialog = None;
566 call.options_dialog = None;
520 }
567 }
521 cx.notify();
568 cx.notify();
@@ -532,6 +579,7 @@ impl AppState {
532 crate::agent_api::note_caption(thread, &entry.id, speaker, &entry.text, cx);
579 crate::agent_api::note_caption(thread, &entry.id, speaker, &entry.text, cx);
533 }
580 }
534 let sharer_before = call.model.screen_sharer.clone();
581 let sharer_before = call.model.screen_sharer.clone();
582 let local_share_before = call.model.local_share.is_some();
535 let lobby_before = call.model.lobby_mris();
583 let lobby_before = call.model.lobby_mris();
536 call.model.apply(update);
584 call.model.apply(update);
537 if call.model.someone_entered_the_lobby(&lobby_before)
585 if call.model.someone_entered_the_lobby(&lobby_before)
@@ -540,13 +588,27 @@ impl AppState {
540 .is_none_or(|played_at| played_at.elapsed() >= LOBBY_TONE_THROTTLE)
588 .is_none_or(|played_at| played_at.elapsed() >= LOBBY_TONE_THROTTLE)
541 {
589 {
542 call.lobby_tone_at = Some(Instant::now());
590 call.lobby_tone_at = Some(Instant::now());
543 cx.emit(AppEvent::CallTone(chatsvc::sounds::CallTone::MeetingReminder));
591 cx.emit(AppEvent::CallTone(
592 chatsvc::sounds::CallTone::MeetingReminder,
593 ));
594 }
595 if !local_share_before && call.model.local_share.is_some() && call.chat_thread().is_some()
596 {
597 call.chat_open = true;
598 call.transcript_open = false;
599 call.people_open = false;
600 self.transcript_panel = None;
601 }
602 if call.model.local_share.is_none() {
603 call.pictures.forget(&VideoKey::LocalScreen, cx);
544 }
604 }
545 if call.model.screen_sharer != sharer_before {
605 if call.model.screen_sharer != sharer_before {
546 call.pictures.forget(&VideoKey::Screen, cx);
606 call.pictures.forget(&VideoKey::Screen, cx);
547 }
607 }
548 if let Some(language) = call.model.take_ready_caption_language() {
608 if let Some(language) = call.model.take_ready_caption_language() {
549 let _ = call.commands.send(CallCommand::SetCaptionLanguage(language));
609 let _ = call
610 .commands
611 .send(CallCommand::SetCaptionLanguage(language));
550 }
612 }
551 if call.model.screen_sharer.is_none() {
613 if call.model.screen_sharer.is_none() {
552 call.stage_fullscreen = false;
614 call.stage_fullscreen = false;
@@ -640,6 +702,17 @@ impl AppState {
640 cx.notify();
702 cx.notify();
641 }
703 }
642
704
705 pub fn set_call_video_quality(
706 &mut self,
707 quality: calling::VideoQuality,
708 cx: &mut Context<Self>,
709 ) {
710 self.call_video_quality = quality;
711 save_video_quality(&self.store, quality);
712 self.send_call_command(CallCommand::SetVideoQuality(quality));
713 cx.notify();
714 }
715
643 pub fn press_push_to_talk(&mut self, _cx: &mut Context<Self>) {
716 pub fn press_push_to_talk(&mut self, _cx: &mut Context<Self>) {
644 let Some(call) = self.call.as_mut() else {
717 let Some(call) = self.call.as_mut() else {
645 return;
718 return;
@@ -678,6 +751,10 @@ impl AppState {
678 self.send_call_command(CallCommand::StartShare(source));
751 self.send_call_command(CallCommand::StartShare(source));
679 }
752 }
680
753
754 pub fn start_portal_share(&mut self, kind: ShareKind, _cx: &mut Context<Self>) {
755 self.send_call_command(CallCommand::StartPortalShare(kind));
756 }
757
681 pub fn stop_call_share(&mut self, _cx: &mut Context<Self>) {
758 pub fn stop_call_share(&mut self, _cx: &mut Context<Self>) {
682 self.send_call_command(CallCommand::StopShare);
759 self.send_call_command(CallCommand::StopShare);
683 }
760 }
@@ -823,7 +900,8 @@ impl AppState {
823 return;
900 return;
824 };
901 };
825 if let Some(own_mri) = call.model.own_mri.clone() {
902 if let Some(own_mri) = call.model.own_mri.clone() {
826 call.model.note_reaction(own_mri, reaction.clone(), Instant::now());
903 call.model
904 .note_reaction(own_mri, reaction.clone(), Instant::now());
827 }
905 }
828 self.send_call_command(CallCommand::SendReaction(reaction));
906 self.send_call_command(CallCommand::SendReaction(reaction));
829 cx.emit(AppEvent::Call);
907 cx.emit(AppEvent::Call);
@@ -1405,21 +1483,24 @@ mod tests {
1405 use calling::{
1483 use calling::{
1406 BackgroundChoice, CallCommand, CallControl, CallState, CallUpdate, CameraEffects,
1484 BackgroundChoice, CallCommand, CallControl, CallState, CallUpdate, CameraEffects,
1407 DeviceChoice, EndKind, EndReason, EngineEvent, HoldState, Reaction, RecordingKind,
1485 DeviceChoice, EndKind, EndReason, EngineEvent, HoldState, Reaction, RecordingKind,
1408 StopScope, call_channel,
1486 StopScope, VideoQuality, call_channel,
1409 };
1487 };
1410 use gpui_kit::{AppContext as _, Entity, TestAppContext};
1488 use gpui_kit::{AppContext as _, Entity, TestAppContext};
1411 use store::{ChatRecord, MemberRecord, Store};
1489 use store::{ChatRecord, MemberRecord, Store};
1412
1490
1413 use super::{ActiveCall, CallModel, load_camera, load_camera_effects, load_input, load_output};
1491 use super::{
1492 ActiveCall, CallModel, load_camera, load_camera_effects, load_input, load_output,
1493 load_video_quality,
1494 };
1414 use crate::app_state::{AppEvent, AppState, Mode, Selection};
1495 use crate::app_state::{AppEvent, AppState, Mode, Selection};
1415 use crate::call::TransferCandidate;
1496 use crate::call::TransferCandidate;
1416 use crate::call::background::BackgroundPick;
1497 use crate::call::background::BackgroundPick;
1417 use crate::call::{CaptionPosition, CaptionSize, RecordAction, ViewSettings};
1418 use crate::call::demo::demo_ring;
1498 use crate::call::demo::demo_ring;
1419 use chatsvc::sounds::CallTone;
1420 use crate::call::features::room_closed_move;
1499 use crate::call::features::room_closed_move;
1421 use crate::call::model::BreakoutState;
1500 use crate::call::model::BreakoutState;
1501 use crate::call::{CaptionPosition, CaptionSize, RecordAction, ViewSettings};
1422 use crate::data::Person;
1502 use crate::data::Person;
1503 use chatsvc::sounds::CallTone;
1423
1504
1424 fn app_with_call(cx: &mut TestAppContext) -> Entity<AppState> {
1505 fn app_with_call(cx: &mut TestAppContext) -> Entity<AppState> {
1425 cx.update(gpui_kit::init);
1506 cx.update(gpui_kit::init);
@@ -1522,7 +1603,15 @@ mod tests {
1522 let app = app_with_call(cx);
1603 let app = app_with_call(cx);
1523 let key = calling::VideoKey::Person("8:orgid:peer".into());
1604 let key = calling::VideoKey::Person("8:orgid:peer".into());
1524 let shown = |app: &Entity<AppState>, cx: &mut TestAppContext| {
1605 let shown = |app: &Entity<AppState>, cx: &mut TestAppContext| {
1525 cx.update(|cx| app.read(cx).call.as_ref().unwrap().pictures.live(&key, Instant::now()).is_some())
1606 cx.update(|cx| {
1607 app.read(cx)
1608 .call
1609 .as_ref()
1610 .unwrap()
1611 .pictures
1612 .live(&key, Instant::now())
1613 .is_some()
1614 })
1526 };
1615 };
1527 cx.update(|cx| {
1616 cx.update(|cx| {
1528 app.update(cx, |state, cx| {
1617 app.update(cx, |state, cx| {
@@ -1568,11 +1657,16 @@ mod tests {
1568 state.select_call_output(DeviceChoice::Device("headset".into()), cx);
1657 state.select_call_output(DeviceChoice::Device("headset".into()), cx);
1569 })
1658 })
1570 });
1659 });
1571 assert_eq!(load_input(&store), DeviceChoice::Device("headset-mic".into()));
1660 assert_eq!(
1661 load_input(&store),
1662 DeviceChoice::Device("headset-mic".into())
1663 );
1572 assert_eq!(load_output(&store), DeviceChoice::Device("headset".into()));
1664 assert_eq!(load_output(&store), DeviceChoice::Device("headset".into()));
1573 assert_eq!(
1665 assert_eq!(
1574 control.try_recv_command(),
1666 control.try_recv_command(),
1575 Some(CallCommand::SelectInput(DeviceChoice::Device("headset-mic".into())))
1667 Some(CallCommand::SelectInput(DeviceChoice::Device(
1668 "headset-mic".into()
1669 )))
1576 );
1670 );
1577 cx.update(|cx| {
1671 cx.update(|cx| {
1578 app.update(cx, |state, cx| {
1672 app.update(cx, |state, cx| {
@@ -1610,12 +1704,17 @@ mod tests {
1610 while let Some(command) = control.try_recv_command() {
1704 while let Some(command) = control.try_recv_command() {
1611 commands.push(command);
1705 commands.push(command);
1612 }
1706 }
1613 assert!(commands.contains(&CallCommand::SelectInput(DeviceChoice::Device(
1707 assert!(
1614 "unplugged-mic".into()
1708 commands.contains(&CallCommand::SelectInput(DeviceChoice::Device(
1615 ))));
1709 "unplugged-mic".into()
1616 assert!(commands.contains(&CallCommand::SelectOutput(DeviceChoice::Device(
1710 )))
1617 "headset".into()
1711 );
1618 ))));
1712 assert!(
1713 commands.contains(&CallCommand::SelectOutput(DeviceChoice::Device(
1714 "headset".into()
1715 )))
1716 );
1717 assert!(commands.contains(&CallCommand::SetVideoQuality(VideoQuality::Auto)));
1619 assert_eq!(
1718 assert_eq!(
1620 load_input(&store),
1719 load_input(&store),
1621 DeviceChoice::Device("unplugged-mic".into())
1720 DeviceChoice::Device("unplugged-mic".into())
@@ -1668,6 +1767,28 @@ mod tests {
1668 assert_eq!(cx.update(|cx| reopened.read(cx).call_effects), effects);
1767 assert_eq!(cx.update(|cx| reopened.read(cx).call_effects), effects);
1669 }
1768 }
1670
1769
1770 #[gpui_kit::test]
1771 fn the_video_quality_is_remembered_and_sent_to_the_call(cx: &mut TestAppContext) {
1772 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
1773 let store = cx.update(|cx| app.read(cx).store.clone());
1774 assert_eq!(load_video_quality(&store), VideoQuality::Auto);
1775 cx.update(|cx| {
1776 app.update(cx, |state, cx| {
1777 state.set_call_video_quality(VideoQuality::P1080, cx)
1778 })
1779 });
1780 assert_eq!(
1781 control.try_recv_command(),
1782 Some(CallCommand::SetVideoQuality(VideoQuality::P1080))
1783 );
1784 assert_eq!(load_video_quality(&store), VideoQuality::P1080);
1785 let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
1786 assert_eq!(
1787 cx.update(|cx| reopened.read(cx).call_video_quality),
1788 VideoQuality::P1080
1789 );
1790 }
1791
1671 #[gpui_kit::test]
1792 #[gpui_kit::test]
1672 fn hands_and_reactions_become_call_commands_and_lowering_needs_the_organizer(
1793 fn hands_and_reactions_become_call_commands_and_lowering_needs_the_organizer(
1673 cx: &mut TestAppContext,
1794 cx: &mut TestAppContext,
@@ -1981,16 +2102,39 @@ mod tests {
1981 cx.update(|cx| {
2102 cx.update(|cx| {
1982 organizer.update(cx, |state, cx| {
2103 organizer.update(cx, |state, cx| {
1983 state.run_call_record_action(RecordAction::Start(RecordingKind::AudioOnly), cx);
2104 state.run_call_record_action(RecordAction::Start(RecordingKind::AudioOnly), cx);
1984 state.run_call_record_action(RecordAction::Start(RecordingKind::TranscriptOnly), cx);
2105 state
2106 .run_call_record_action(RecordAction::Start(RecordingKind::TranscriptOnly), cx);
1985 state.run_call_record_action(RecordAction::Stop(StopScope::RecordingOnly), cx);
2107 state.run_call_record_action(RecordAction::Stop(StopScope::RecordingOnly), cx);
1986 state.run_call_record_action(RecordAction::Stop(StopScope::TranscriptionOnly), cx);
2108 state.run_call_record_action(RecordAction::Stop(StopScope::TranscriptionOnly), cx);
1987 })
2109 })
1988 });
2110 });
1989 let title = "Standup".to_owned();
2111 let title = "Standup".to_owned();
1990 assert_eq!(control.try_recv_command(), Some(CallCommand::StartRecording { kind: RecordingKind::AudioOnly, title: title.clone() }));
2112 assert_eq!(
1991 assert_eq!(control.try_recv_command(), Some(CallCommand::StartRecording { kind: RecordingKind::TranscriptOnly, title }));
2113 control.try_recv_command(),
1992 assert_eq!(control.try_recv_command(), Some(CallCommand::StopRecording { scope: StopScope::RecordingOnly }));
2114 Some(CallCommand::StartRecording {
1993 assert_eq!(control.try_recv_command(), Some(CallCommand::StopRecording { scope: StopScope::TranscriptionOnly }));
2115 kind: RecordingKind::AudioOnly,
2116 title: title.clone()
2117 })
2118 );
2119 assert_eq!(
2120 control.try_recv_command(),
2121 Some(CallCommand::StartRecording {
2122 kind: RecordingKind::TranscriptOnly,
2123 title
2124 })
2125 );
2126 assert_eq!(
2127 control.try_recv_command(),
2128 Some(CallCommand::StopRecording {
2129 scope: StopScope::RecordingOnly
2130 })
2131 );
2132 assert_eq!(
2133 control.try_recv_command(),
2134 Some(CallCommand::StopRecording {
2135 scope: StopScope::TranscriptionOnly
2136 })
2137 );
1994 assert_eq!(control.try_recv_command(), None);
2138 assert_eq!(control.try_recv_command(), None);
1995 }
2139 }
1996
2140
@@ -1999,7 +2143,11 @@ mod tests {
1999 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
2143 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
2000 cx.update(|cx| {
2144 cx.update(|cx| {
2001 app.update(cx, |state, cx| {
2145 app.update(cx, |state, cx| {
2002 state.apply_call_update(7, CallUpdate::MeetingChat("19:meeting_x@thread.v2".into()), cx);
2146 state.apply_call_update(
2147 7,
2148 CallUpdate::MeetingChat("19:meeting_x@thread.v2".into()),
2149 cx,
2150 );
2003 state.toggle_call_chat(cx);
2151 state.toggle_call_chat(cx);
2004 state.show_call_transcript(cx);
2152 state.show_call_transcript(cx);
2005 })
2153 })
@@ -2009,7 +2157,10 @@ mod tests {
2009 (call.chat_open, call.transcript_open)
2157 (call.chat_open, call.transcript_open)
2010 });
2158 });
2011 assert!(!chat_open && transcript_open);
2159 assert!(!chat_open && transcript_open);
2012 assert_eq!(control.try_recv_command(), Some(CallCommand::SetCaptions(true)));
2160 assert_eq!(
2161 control.try_recv_command(),
2162 Some(CallCommand::SetCaptions(true))
2163 );
2013 cx.update(|cx| {
2164 cx.update(|cx| {
2014 app.update(cx, |state, cx| {
2165 app.update(cx, |state, cx| {
2015 state.apply_call_update(7, CallUpdate::Captions(calling::CaptionState::On), cx);
2166 state.apply_call_update(7, CallUpdate::Captions(calling::CaptionState::On), cx);
@@ -2026,15 +2177,24 @@ mod tests {
2026 }
2177 }
2027
2178
2028 #[gpui_kit::test]
2179 #[gpui_kit::test]
2029 fn a_spoken_language_picked_while_captions_are_off_is_sent_once_they_are_on(cx: &mut TestAppContext) {
2180 fn a_spoken_language_picked_while_captions_are_off_is_sent_once_they_are_on(
2181 cx: &mut TestAppContext,
2182 ) {
2030 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
2183 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
2031 cx.update(|cx| {
2184 cx.update(|cx| {
2032 app.update(cx, |state, cx| {
2185 app.update(cx, |state, cx| {
2033 state.choose_call_caption_language("de-DE", cx);
2186 state.choose_call_caption_language("de-DE", cx);
2034 state.apply_call_update(7, CallUpdate::Captions(calling::CaptionState::Starting), cx);
2187 state.apply_call_update(
2188 7,
2189 CallUpdate::Captions(calling::CaptionState::Starting),
2190 cx,
2191 );
2035 })
2192 })
2036 });
2193 });
2037 assert_eq!(control.try_recv_command(), Some(CallCommand::SetCaptions(true)));
2194 assert_eq!(
2195 control.try_recv_command(),
2196 Some(CallCommand::SetCaptions(true))
2197 );
2038 assert_eq!(control.try_recv_command(), None);
2198 assert_eq!(control.try_recv_command(), None);
2039 cx.update(|cx| {
2199 cx.update(|cx| {
2040 app.update(cx, |state, cx| {
2200 app.update(cx, |state, cx| {
@@ -2042,8 +2202,14 @@ mod tests {
2042 state.choose_call_caption_language("fr-FR", cx);
2202 state.choose_call_caption_language("fr-FR", cx);
2043 })
2203 })
2044 });
2204 });
2045 assert_eq!(control.try_recv_command(), Some(CallCommand::SetCaptionLanguage("de-DE".into())));
2205 assert_eq!(
2046 assert_eq!(control.try_recv_command(), Some(CallCommand::SetCaptionLanguage("fr-FR".into())));
2206 control.try_recv_command(),
2207 Some(CallCommand::SetCaptionLanguage("de-DE".into()))
2208 );
2209 assert_eq!(
2210 control.try_recv_command(),
2211 Some(CallCommand::SetCaptionLanguage("fr-FR".into()))
2212 );
2047 assert_eq!(control.try_recv_command(), None);
2213 assert_eq!(control.try_recv_command(), None);
2048 }
2214 }
2049
2215
@@ -2058,10 +2224,19 @@ mod tests {
2058 });
2224 });
2059 let (view, stored) = cx.update(|cx| {
2225 let (view, stored) = cx.update(|cx| {
2060 let state = app.read(cx);
2226 let state = app.read(cx);
2061 (state.call.as_ref().unwrap().model.view, ViewSettings::load(&state.store))
2227 (
2228 state.call.as_ref().unwrap().model.view,
2229 ViewSettings::load(&state.store),
2230 )
2062 });
2231 });
2063 assert_eq!((view.caption_size, view.caption_position), (CaptionSize::Large, CaptionPosition::Top));
2232 assert_eq!(
2064 assert_eq!((stored.caption_size, stored.caption_position), (CaptionSize::Large, CaptionPosition::Top));
2233 (view.caption_size, view.caption_position),
2234 (CaptionSize::Large, CaptionPosition::Top)
2235 );
2236 assert_eq!(
2237 (stored.caption_size, stored.caption_position),
2238 (CaptionSize::Large, CaptionPosition::Top)
2239 );
2065 }
2240 }
2066
2241
2067 fn live_one_to_one() -> CallModel {
2242 fn live_one_to_one() -> CallModel {
@@ -2102,9 +2277,7 @@ mod tests {
2102 }
2277 }
2103
2278
2104 #[gpui_kit::test]
2279 #[gpui_kit::test]
2105 fn a_blind_transfer_names_the_target(
2280 fn a_blind_transfer_names_the_target(cx: &mut TestAppContext) {
2106 cx: &mut TestAppContext,
2107 ) {
2108 let (app, mut control) = app_with_commands(cx, live_one_to_one(), None);
2281 let (app, mut control) = app_with_commands(cx, live_one_to_one(), None);
2109 cx.update(|cx| {
2282 cx.update(|cx| {
2110 app.update(cx, |state, cx| {
2283 app.update(cx, |state, cx| {
@@ -2389,12 +2562,14 @@ mod tests {
2389 }
2562 }
2390
2563
2391 #[gpui_kit::test]
2564 #[gpui_kit::test]
2392 fn picking_another_chat_keeps_the_call_window_showing_the_call(cx: &mut TestAppContext) {
2565 fn picking_another_chat_moves_the_call_to_the_mini_window(cx: &mut TestAppContext) {
2393 let app = app_with_call(cx);
2566 let app = app_with_call(cx);
2394 cx.update(|cx| {
2567 cx.update(|cx| {
2395 app.update(cx, |state, cx| {
2568 app.update(cx, |state, cx| {
2396 assert!(state.viewing_call());
2569 assert!(state.viewing_call());
2397 state.select(Selection::Chat("c1".into()), cx);
2570 state.select(Selection::Chat("c1".into()), cx);
2571 assert!(!state.viewing_call());
2572 state.show_call(true, cx);
2398 assert!(state.viewing_call());
2573 assert!(state.viewing_call());
2399 })
2574 })
2400 });
2575 });
@@ -2435,7 +2610,13 @@ mod tests {
2435 })
2610 })
2436 .detach();
2611 .detach();
2437 app.update(cx, |state, cx| {
2612 app.update(cx, |state, cx| {
2438 state.apply_call_update(7, CallUpdate::State(CallState::Ended { reason: EndReason::Dropped }), cx);
2613 state.apply_call_update(
2614 7,
2615 CallUpdate::State(CallState::Ended {
2616 reason: EndReason::Dropped,
2617 }),
2618 cx,
2619 );
2439 assert!(state.call.is_none());
2620 assert!(state.call.is_none());
2440 assert!(state.notice.is_none());
2621 assert!(state.notice.is_none());
2441 let screen = state.call_end.as_ref().expect("end screen");
2622 let screen = state.call_end.as_ref().expect("end screen");
@@ -2453,7 +2634,13 @@ mod tests {
2453 let app = app_with_call(cx);
2634 let app = app_with_call(cx);
2454 cx.update(|cx| {
2635 cx.update(|cx| {
2455 app.update(cx, |state, cx| {
2636 app.update(cx, |state, cx| {
2456 state.apply_call_update(7, CallUpdate::State(CallState::Ended { reason: EndReason::Remote(EndKind::Removed) }), cx);
2637 state.apply_call_update(
2638 7,
2639 CallUpdate::State(CallState::Ended {
2640 reason: EndReason::Remote(EndKind::Removed),
2641 }),
2642 cx,
2643 );
2457 assert!(state.call_end.is_none());
2644 assert!(state.call_end.is_none());
2458 assert!(state.notice.is_some());
2645 assert!(state.notice.is_some());
2459 })
2646 })
crates/app-state/src/call/mod.rs +1 −0
@@ -31,6 +31,7 @@ pub use app_call_model::{
31 31
32 32 pub use actions::{
33 33 apply_sound_output, load_camera, load_camera_effects, load_input, load_output, load_share_sound,
34 load_video_quality,
34 35 };
35 36 pub use mic::load_mic;
36 37 pub use agenda::{AgendaRow, fetch_window, join_available, response_label};
@@ -31,6 +31,7 @@ pub use app_call_model::{
31
31
32pub use actions::{
32pub use actions::{
33 apply_sound_output, load_camera, load_camera_effects, load_input, load_output, load_share_sound,
33 apply_sound_output, load_camera, load_camera_effects, load_input, load_output, load_share_sound,
34 load_video_quality,
34};
35};
35pub use mic::load_mic;
36pub use mic::load_mic;
36pub use agenda::{AgendaRow, fetch_window, join_available, response_label};
37pub use agenda::{AgendaRow, fetch_window, join_available, response_label};
crates/app/src/settings/devices.rs +6 −5
@@ -135,7 +135,7 @@ impl DevicesView {
135 135 };
136 136 view.load_devices(demo, cx);
137 137 view.apply_background(cx);
138 view.start_preview();
138 view.start_preview(cx);
139 139 view
140 140 }
141 141
@@ -165,9 +165,10 @@ impl DevicesView {
165 165 .detach();
166 166 }
167 167
168 fn start_preview(&mut self) {
168 fn start_preview(&mut self, cx: &Context<Self>) {
169 169 if !self.preview_blocked {
170 self.preview.start(&self.camera);
170 let quality = self.app.read(cx).call_video_quality;
171 self.preview.start(&self.camera, quality);
171 172 }
172 173 }
173 174
@@ -180,7 +181,7 @@ impl DevicesView {
180 181 if blocked {
181 182 self.preview.stop(cx);
182 183 } else {
183 self.start_preview();
184 self.start_preview(cx);
184 185 }
185 186 cx.notify();
186 187 }
@@ -189,7 +190,7 @@ impl DevicesView {
189 190 self.camera = camera.clone();
190 191 self.app
191 192 .update(cx, |state, cx| state.select_call_camera(camera, cx));
192 self.start_preview();
193 self.start_preview(cx);
193 194 cx.notify();
194 195 }
195 196
@@ -135,7 +135,7 @@ impl DevicesView {
135 };
135 };
136 view.load_devices(demo, cx);
136 view.load_devices(demo, cx);
137 view.apply_background(cx);
137 view.apply_background(cx);
138 view.start_preview();
138 view.start_preview(cx);
139 view
139 view
140 }
140 }
141
141
@@ -165,9 +165,10 @@ impl DevicesView {
165 .detach();
165 .detach();
166 }
166 }
167
167
168 fn start_preview(&mut self) {
168 fn start_preview(&mut self, cx: &Context<Self>) {
169 if !self.preview_blocked {
169 if !self.preview_blocked {
170 self.preview.start(&self.camera);
170 let quality = self.app.read(cx).call_video_quality;
171 self.preview.start(&self.camera, quality);
171 }
172 }
172 }
173 }
173
174
@@ -180,7 +181,7 @@ impl DevicesView {
180 if blocked {
181 if blocked {
181 self.preview.stop(cx);
182 self.preview.stop(cx);
182 } else {
183 } else {
183 self.start_preview();
184 self.start_preview(cx);
184 }
185 }
185 cx.notify();
186 cx.notify();
186 }
187 }
@@ -189,7 +190,7 @@ impl DevicesView {
189 self.camera = camera.clone();
190 self.camera = camera.clone();
190 self.app
191 self.app
191 .update(cx, |state, cx| state.select_call_camera(camera, cx));
192 .update(cx, |state, cx| state.select_call_camera(camera, cx));
192 self.start_preview();
193 self.start_preview(cx);
193 cx.notify();
194 cx.notify();
194 }
195 }
195
196
crates/app/src/views/call_extras.rs +26 −0
@@ -319,6 +319,7 @@ pub struct CameraMenu {
319 319 pub images: Vec<(String, String, Option<PathBuf>)>,
320 320 pub customs: Vec<PathBuf>,
321 321 pub effects: CameraEffects,
322 pub quality: calling::VideoQuality,
322 323 }
323 324
324 325 impl CameraMenu {
@@ -339,10 +340,35 @@ impl CameraMenu {
339 340 .collect(),
340 341 customs: library.customs.clone(),
341 342 effects: state.call_effects,
343 quality: state.call_video_quality,
342 344 }
343 345 }
344 346 }
345 347
348 pub fn quality_items(
349 popup: PopupMenu,
350 app: &Entity<AppState>,
351 current: calling::VideoQuality,
352 ) -> PopupMenu {
353 let choices = [
354 (calling::VideoQuality::Auto, "Auto"),
355 (calling::VideoQuality::P720, "720p"),
356 (calling::VideoQuality::P1080, "1080p"),
357 ];
358 let mut popup = popup.separator().item(PopupMenuItem::label("Video quality"));
359 for (quality, label) in choices {
360 let app = app.clone();
361 popup = popup.item(
362 PopupMenuItem::new(label)
363 .checked(current == quality)
364 .on_click(move |_, _, cx| {
365 app.update(cx, |state, cx| state.set_call_video_quality(quality, cx))
366 }),
367 );
368 }
369 popup
370 }
371
346 372 fn thumbnail(
347 373 app: &Entity<AppState>,
348 374 index: usize,
@@ -319,6 +319,7 @@ pub struct CameraMenu {
319 pub images: Vec<(String, String, Option<PathBuf>)>,
319 pub images: Vec<(String, String, Option<PathBuf>)>,
320 pub customs: Vec<PathBuf>,
320 pub customs: Vec<PathBuf>,
321 pub effects: CameraEffects,
321 pub effects: CameraEffects,
322 pub quality: calling::VideoQuality,
322}
323}
323
324
324impl CameraMenu {
325impl CameraMenu {
@@ -339,10 +340,35 @@ impl CameraMenu {
339 .collect(),
340 .collect(),
340 customs: library.customs.clone(),
341 customs: library.customs.clone(),
341 effects: state.call_effects,
342 effects: state.call_effects,
343 quality: state.call_video_quality,
342 }
344 }
343 }
345 }
344}
346}
345
347
348pub fn quality_items(
349 popup: PopupMenu,
350 app: &Entity<AppState>,
351 current: calling::VideoQuality,
352) -> PopupMenu {
353 let choices = [
354 (calling::VideoQuality::Auto, "Auto"),
355 (calling::VideoQuality::P720, "720p"),
356 (calling::VideoQuality::P1080, "1080p"),
357 ];
358 let mut popup = popup.separator().item(PopupMenuItem::label("Video quality"));
359 for (quality, label) in choices {
360 let app = app.clone();
361 popup = popup.item(
362 PopupMenuItem::new(label)
363 .checked(current == quality)
364 .on_click(move |_, _, cx| {
365 app.update(cx, |state, cx| state.set_call_video_quality(quality, cx))
366 }),
367 );
368 }
369 popup
370}
371
346fn thumbnail(
372fn thumbnail(
347 app: &Entity<AppState>,
373 app: &Entity<AppState>,
348 index: usize,
374 index: usize,
crates/app/src/views/call_organizer.rs +5 −1
@@ -604,7 +604,11 @@ fn camera_menu(
604 604 popup = popup.item(item);
605 605 }
606 606 background_items(
607 effect_items(popup, app, backgrounds.effects),
607 effect_items(
608 super::call_extras::quality_items(popup, app, backgrounds.quality),
609 app,
610 backgrounds.effects,
611 ),
608 612 app,
609 613 backgrounds,
610 614 )
@@ -604,7 +604,11 @@ fn camera_menu(
604 popup = popup.item(item);
604 popup = popup.item(item);
605 }
605 }
606 background_items(
606 background_items(
607 effect_items(popup, app, backgrounds.effects),
607 effect_items(
608 super::call_extras::quality_items(popup, app, backgrounds.quality),
609 app,
610 backgrounds.effects,
611 ),
608 app,
612 app,
609 backgrounds,
613 backgrounds,
610 )
614 )
crates/app/src/views/prejoin_view.rs +29 −8
@@ -12,7 +12,7 @@ use gpui_kit::prelude::FluentBuilder as _;
12 12 use gpui_kit::*;
13 13
14 14 use super::avatar::person_avatar;
15 use super::call_extras::{CameraMenu, background_items};
15 use super::call_extras::{CameraMenu, background_items, quality_items};
16 16 use super::call_view::{device_items, round_control};
17 17 use crate::app_state::AppState;
18 18 use crate::call::{AudioChoice, CameraPreview, JoinOptions, PendingJoin};
@@ -45,6 +45,7 @@ pub struct PrejoinView {
45 45 input: DeviceChoice,
46 46 output: DeviceChoice,
47 47 applied_background: crate::call::BackgroundPick,
48 applied_quality: calling::VideoQuality,
48 49 tick: u32,
49 50 _subscription: Subscription,
50 51 _release: Subscription,
@@ -92,7 +93,10 @@ impl PrejoinView {
92 93 _window: &mut Window,
93 94 cx: &mut Context<Self>,
94 95 ) -> Self {
95 let subscription = cx.observe(&app, |view, _, cx| view.sync_background(cx));
96 let subscription = cx.observe(&app, |view, _, cx| {
97 view.sync_background(cx);
98 view.sync_quality(cx);
99 });
96 100 let release = cx.on_release(|view, cx| view.preview.stop(cx));
97 101 let (preview, mut updates) = CameraPreview::new();
98 102 let state = app.read(cx);
@@ -102,6 +106,7 @@ impl PrejoinView {
102 106 options.camera_on = options.camera_on && !state.mode.read_only;
103 107 let camera = state.call_camera.clone();
104 108 let (input, output) = (state.call_input.clone(), state.call_output.clone());
109 let applied_quality = state.call_video_quality;
105 110 let mut view = PrejoinView {
106 111 pending_id: pending.id,
107 112 demo,
@@ -117,6 +122,7 @@ impl PrejoinView {
117 122 input,
118 123 output,
119 124 applied_background: crate::call::BackgroundPick::None,
125 applied_quality,
120 126 tick: 0,
121 127 _subscription: subscription,
122 128 _release: release,
@@ -159,7 +165,7 @@ impl PrejoinView {
159 165 view.load_devices(cx);
160 166 }
161 167 view.sync_background(cx);
162 view.restart_preview();
168 view.restart_preview(cx);
163 169 view
164 170 }
165 171
@@ -196,9 +202,10 @@ impl PrejoinView {
196 202 .detach();
197 203 }
198 204
199 fn restart_preview(&mut self) {
205 fn restart_preview(&mut self, cx: &Context<Self>) {
200 206 if self.options.camera_on && !self.demo {
201 self.preview.start(&self.camera);
207 let quality = self.app.read(cx).call_video_quality;
208 self.preview.start(&self.camera, quality);
202 209 }
203 210 }
204 211
@@ -215,10 +222,20 @@ impl PrejoinView {
215 222 cx.notify();
216 223 }
217 224
225 fn sync_quality(&mut self, cx: &mut Context<Self>) {
226 let quality = self.app.read(cx).call_video_quality;
227 if quality == self.applied_quality {
228 return;
229 }
230 self.applied_quality = quality;
231 self.restart_preview(cx);
232 cx.notify();
233 }
234
218 235 fn toggle_camera(&mut self, cx: &mut Context<Self>) {
219 236 self.options.camera_on = !self.options.camera_on;
220 237 if self.options.camera_on {
221 self.restart_preview();
238 self.restart_preview(cx);
222 239 } else {
223 240 self.preview.stop(cx);
224 241 }
@@ -239,7 +256,7 @@ impl PrejoinView {
239 256 self.camera = choice.clone();
240 257 self.app
241 258 .update(cx, |state, cx| state.select_call_camera(choice, cx));
242 self.restart_preview();
259 self.restart_preview(cx);
243 260 cx.notify();
244 261 }
245 262
@@ -365,7 +382,11 @@ impl PrejoinView {
365 382 .label("Background")
366 383 .icon(IconName::ChevronDown)
367 384 .dropdown_menu(move |menu: PopupMenu, _, _| {
368 background_items(menu, &background_app, &backgrounds)
385 background_items(
386 quality_items(menu, &background_app, backgrounds.quality),
387 &background_app,
388 &backgrounds,
389 )
369 390 }),
370 391 )
371 392 }
@@ -12,7 +12,7 @@ use gpui_kit::prelude::FluentBuilder as _;
12use gpui_kit::*;
12use gpui_kit::*;
13
13
14use super::avatar::person_avatar;
14use super::avatar::person_avatar;
15use super::call_extras::{CameraMenu, background_items};
15use super::call_extras::{CameraMenu, background_items, quality_items};
16use super::call_view::{device_items, round_control};
16use super::call_view::{device_items, round_control};
17use crate::app_state::AppState;
17use crate::app_state::AppState;
18use crate::call::{AudioChoice, CameraPreview, JoinOptions, PendingJoin};
18use crate::call::{AudioChoice, CameraPreview, JoinOptions, PendingJoin};
@@ -45,6 +45,7 @@ pub struct PrejoinView {
45 input: DeviceChoice,
45 input: DeviceChoice,
46 output: DeviceChoice,
46 output: DeviceChoice,
47 applied_background: crate::call::BackgroundPick,
47 applied_background: crate::call::BackgroundPick,
48 applied_quality: calling::VideoQuality,
48 tick: u32,
49 tick: u32,
49 _subscription: Subscription,
50 _subscription: Subscription,
50 _release: Subscription,
51 _release: Subscription,
@@ -92,7 +93,10 @@ impl PrejoinView {
92 _window: &mut Window,
93 _window: &mut Window,
93 cx: &mut Context<Self>,
94 cx: &mut Context<Self>,
94 ) -> Self {
95 ) -> Self {
95 let subscription = cx.observe(&app, |view, _, cx| view.sync_background(cx));
96 let subscription = cx.observe(&app, |view, _, cx| {
97 view.sync_background(cx);
98 view.sync_quality(cx);
99 });
96 let release = cx.on_release(|view, cx| view.preview.stop(cx));
100 let release = cx.on_release(|view, cx| view.preview.stop(cx));
97 let (preview, mut updates) = CameraPreview::new();
101 let (preview, mut updates) = CameraPreview::new();
98 let state = app.read(cx);
102 let state = app.read(cx);
@@ -102,6 +106,7 @@ impl PrejoinView {
102 options.camera_on = options.camera_on && !state.mode.read_only;
106 options.camera_on = options.camera_on && !state.mode.read_only;
103 let camera = state.call_camera.clone();
107 let camera = state.call_camera.clone();
104 let (input, output) = (state.call_input.clone(), state.call_output.clone());
108 let (input, output) = (state.call_input.clone(), state.call_output.clone());
109 let applied_quality = state.call_video_quality;
105 let mut view = PrejoinView {
110 let mut view = PrejoinView {
106 pending_id: pending.id,
111 pending_id: pending.id,
107 demo,
112 demo,
@@ -117,6 +122,7 @@ impl PrejoinView {
117 input,
122 input,
118 output,
123 output,
119 applied_background: crate::call::BackgroundPick::None,
124 applied_background: crate::call::BackgroundPick::None,
125 applied_quality,
120 tick: 0,
126 tick: 0,
121 _subscription: subscription,
127 _subscription: subscription,
122 _release: release,
128 _release: release,
@@ -159,7 +165,7 @@ impl PrejoinView {
159 view.load_devices(cx);
165 view.load_devices(cx);
160 }
166 }
161 view.sync_background(cx);
167 view.sync_background(cx);
162 view.restart_preview();
168 view.restart_preview(cx);
163 view
169 view
164 }
170 }
165
171
@@ -196,9 +202,10 @@ impl PrejoinView {
196 .detach();
202 .detach();
197 }
203 }
198
204
199 fn restart_preview(&mut self) {
205 fn restart_preview(&mut self, cx: &Context<Self>) {
200 if self.options.camera_on && !self.demo {
206 if self.options.camera_on && !self.demo {
201 self.preview.start(&self.camera);
207 let quality = self.app.read(cx).call_video_quality;
208 self.preview.start(&self.camera, quality);
202 }
209 }
203 }
210 }
204
211
@@ -215,10 +222,20 @@ impl PrejoinView {
215 cx.notify();
222 cx.notify();
216 }
223 }
217
224
225 fn sync_quality(&mut self, cx: &mut Context<Self>) {
226 let quality = self.app.read(cx).call_video_quality;
227 if quality == self.applied_quality {
228 return;
229 }
230 self.applied_quality = quality;
231 self.restart_preview(cx);
232 cx.notify();
233 }
234
218 fn toggle_camera(&mut self, cx: &mut Context<Self>) {
235 fn toggle_camera(&mut self, cx: &mut Context<Self>) {
219 self.options.camera_on = !self.options.camera_on;
236 self.options.camera_on = !self.options.camera_on;
220 if self.options.camera_on {
237 if self.options.camera_on {
221 self.restart_preview();
238 self.restart_preview(cx);
222 } else {
239 } else {
223 self.preview.stop(cx);
240 self.preview.stop(cx);
224 }
241 }
@@ -239,7 +256,7 @@ impl PrejoinView {
239 self.camera = choice.clone();
256 self.camera = choice.clone();
240 self.app
257 self.app
241 .update(cx, |state, cx| state.select_call_camera(choice, cx));
258 .update(cx, |state, cx| state.select_call_camera(choice, cx));
242 self.restart_preview();
259 self.restart_preview(cx);
243 cx.notify();
260 cx.notify();
244 }
261 }
245
262
@@ -365,7 +382,11 @@ impl PrejoinView {
365 .label("Background")
382 .label("Background")
366 .icon(IconName::ChevronDown)
383 .icon(IconName::ChevronDown)
367 .dropdown_menu(move |menu: PopupMenu, _, _| {
384 .dropdown_menu(move |menu: PopupMenu, _, _| {
368 background_items(menu, &background_app, &backgrounds)
385 background_items(
386 quality_items(menu, &background_app, backgrounds.quality),
387 &background_app,
388 &backgrounds,
389 )
369 }),
390 }),
370 )
391 )
371 }
392 }
crates/calling/src/camera.rs +56 −392
@@ -1,7 +1,5 @@
1 use std::process::Command;
2 1 use std::sync::Arc;
3 use std::sync::atomic::{AtomicU64, Ordering};
4 use std::time::{Duration, Instant};
2 use std::time::Duration;
5 3
6 4 use libwebrtc::native::yuv_helper::{abgr_to_i420, nv12_to_i420};
7 5 use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};
@@ -11,10 +9,7 @@ use nokhwa::utils::{
11 9 Resolution,
12 10 };
13 11 use nokhwa::{Camera, query};
14 use zune_core::bytestream::ZCursor;
15 use zune_core::colorspace::ColorSpace;
16 use zune_core::options::DecoderOptions;
17 use zune_jpeg::JpegDecoder;
12 use std::sync::atomic::Ordering;
18 13
19 14 use crate::blur::BlurSettings;
20 15 use crate::capture::Capture;
@@ -29,8 +24,6 @@ const CAPTURE_FPS: u32 = 30;
29 24 const ASPECT_WIDTH: u32 = 16;
30 25 const ASPECT_HEIGHT: u32 = 9;
31 26 const DIRECT_FORMATS: [FrameFormat; 2] = [FrameFormat::NV12, FrameFormat::YUYV];
32 const USABLE_FORMATS: [FrameFormat; 3] =
33 [FrameFormat::NV12, FrameFormat::YUYV, FrameFormat::MJPEG];
34 27
35 28 #[derive(Debug, Clone, PartialEq, Eq)]
36 29 pub struct CameraDevice {
@@ -38,72 +31,6 @@ pub struct CameraDevice {
38 31 pub name: String,
39 32 }
40 33
41 /// Shared capture counters for call-report stats (format + fps + decode time).
42 #[derive(Debug, Default)]
43 pub struct CameraCaptureStats {
44 format: std::sync::Mutex<String>,
45 started: std::sync::Mutex<Option<Instant>>,
46 frames: AtomicU64,
47 decode_ns: AtomicU64,
48 }
49
50 impl CameraCaptureStats {
51 pub fn new() -> Arc<Self> {
52 Arc::new(Self::default())
53 }
54
55 fn set_format(&self, label: impl Into<String>) {
56 if let Ok(mut slot) = self.format.lock() {
57 *slot = label.into();
58 }
59 if let Ok(mut started) = self.started.lock() {
60 *started = Some(Instant::now());
61 }
62 self.frames.store(0, Ordering::Relaxed);
63 self.decode_ns.store(0, Ordering::Relaxed);
64 }
65
66 fn note_frame(&self, decode: Duration) {
67 self.frames.fetch_add(1, Ordering::Relaxed);
68 self.decode_ns
69 .fetch_add(decode.as_nanos() as u64, Ordering::Relaxed);
70 }
71
72 pub fn format_label(&self) -> String {
73 self.format
74 .lock()
75 .map(|label| label.clone())
76 .unwrap_or_default()
77 }
78
79 pub fn summary(&self) -> Option<String> {
80 let label = self.format_label();
81 if label.is_empty() {
82 return None;
83 }
84 let frames = self.frames.load(Ordering::Relaxed);
85 let decode_ns = self.decode_ns.load(Ordering::Relaxed);
86 let decode_ms = if frames == 0 {
87 0.0
88 } else {
89 (decode_ns as f64 / frames as f64) / 1_000_000.0
90 };
91 let fps = self
92 .started
93 .lock()
94 .ok()
95 .and_then(|started| *started)
96 .map(|started| {
97 let seconds = started.elapsed().as_secs_f64().max(0.001);
98 frames as f64 / seconds
99 })
100 .unwrap_or(0.0);
101 Some(format!(
102 " camera={label} capture={fps:.1}fps decode={decode_ms:.1}ms"
103 ))
104 }
105 }
106
107 34 pub fn list_cameras() -> Vec<CameraDevice> {
108 35 query(ApiBackend::Auto)
109 36 .unwrap_or_default()
@@ -148,32 +75,11 @@ pub fn i420_from_rgba(rgba: &[u8], width: u32, height: u32) -> I420Buffer {
148 75
149 76 fn format_rank(frame_format: FrameFormat) -> u8 {
150 77 match frame_format {
151 FrameFormat::NV12 => 3,
152 FrameFormat::YUYV => 2,
153 FrameFormat::MJPEG => 1,
78 FrameFormat::NV12 => 1,
154 79 _ => 0,
155 80 }
156 81 }
157 82
158 fn format_short_name(frame_format: FrameFormat) -> String {
159 match frame_format {
160 FrameFormat::MJPEG => "MJPG".into(),
161 FrameFormat::NV12 => "NV12".into(),
162 FrameFormat::YUYV => "YUYV".into(),
163 other => other.to_string(),
164 }
165 }
166
167 fn format_label(format: &CameraFormat) -> String {
168 format!(
169 "{} {}x{} @{}",
170 format_short_name(format.format()),
171 format.width(),
172 format.height(),
173 format.frame_rate()
174 )
175 }
176
177 83 fn is_widescreen(width: u32, height: u32) -> bool {
178 84 width * ASPECT_HEIGHT == height * ASPECT_WIDTH
179 85 }
@@ -196,7 +102,7 @@ fn pick_format(formats: &[CameraFormat], quality: VideoQuality) -> Option<Camera
196 102 formats
197 103 .iter()
198 104 .copied()
199 .filter(|format| USABLE_FORMATS.contains(&format.format()))
105 .filter(|format| DIRECT_FORMATS.contains(&format.format()))
200 106 .filter(|format| format.frame_rate() >= CAPTURE_FPS)
201 107 .filter(|format| {
202 108 format.height() <= capture_height
@@ -212,33 +118,6 @@ fn pick_format(formats: &[CameraFormat], quality: VideoQuality) -> Option<Camera
212 118 })
213 119 }
214 120
215 fn candidate_heights(quality: VideoQuality) -> Vec<u32> {
216 match quality {
217 VideoQuality::P720 => vec![720, 540, 360],
218 VideoQuality::Auto | VideoQuality::P1080 => vec![1080, 720, 540, 360],
219 }
220 }
221
222 fn preferred_candidates(quality: VideoQuality) -> Vec<CameraFormat> {
223 let mut candidates = Vec::new();
224 for height in candidate_heights(quality) {
225 let width = height * ASPECT_WIDTH / ASPECT_HEIGHT;
226 candidates.push(CameraFormat::new(
227 Resolution::new(width, height),
228 FrameFormat::MJPEG,
229 CAPTURE_FPS,
230 ));
231 for frame_format in DIRECT_FORMATS {
232 candidates.push(CameraFormat::new(
233 Resolution::new(width, height),
234 frame_format,
235 CAPTURE_FPS,
236 ));
237 }
238 }
239 candidates
240 }
241
242 121 fn even(value: u32) -> u32 {
243 122 value & !1
244 123 }
@@ -310,119 +189,51 @@ pub(crate) fn fit_widescreen(mut buffer: I420Buffer, quality: VideoQuality) -> I
310 189 buffer
311 190 }
312 191
313 fn open_with_request(
192 fn open_picked_format(
314 193 index: CameraIndex,
315 request: RequestedFormatType,
194 quality: VideoQuality,
316 195 ) -> std::result::Result<Camera, nokhwa::NokhwaError> {
317 let format = RequestedFormat::new::<RgbAFormat>(request);
318 let mut camera = Camera::new(index, format)?;
196 let mut camera = Camera::new(
197 index,
198 RequestedFormat::new::<RgbAFormat>(RequestedFormatType::AbsoluteHighestFrameRate),
199 )?;
200 let formats = camera.compatible_camera_formats()?;
201 let format = pick_format(&formats, quality).ok_or_else(|| {
202 nokhwa::NokhwaError::GeneralError("no raw camera format at 30 fps".to_owned())
203 })?;
204 camera.set_camera_requset(RequestedFormat::new::<RgbAFormat>(
205 RequestedFormatType::Exact(format),
206 ))?;
319 207 camera.open_stream()?;
320 208 Ok(camera)
321 209 }
322 210
323 fn device_path(index: &CameraIndex) -> Option<String> {
324 match index {
325 CameraIndex::Index(number) => Some(format!("/dev/video{number}")),
326 CameraIndex::String(text) if text.starts_with("/dev/") => Some(text.clone()),
327 CameraIndex::String(text) if text.chars().all(|c| c.is_ascii_digit()) => {
328 Some(format!("/dev/video{text}"))
329 }
330 CameraIndex::String(text) if text.starts_with("video") => Some(format!("/dev/{text}")),
331 _ => None,
332 }
333 }
334
335 fn tune_uvc_controls(index: &CameraIndex) {
336 let Some(device) = device_path(index) else {
337 return;
338 };
339 // Best effort: fixed frame rate (no auto-drop in low light) and 50 Hz mains (CH).
340 let _ = Command::new("v4l2-ctl")
341 .args([
342 "-d",
343 &device,
344 "-c",
345 "exposure_dynamic_framerate=0,power_line_frequency=1",
346 ])
347 .stdout(std::process::Stdio::null())
348 .stderr(std::process::Stdio::null())
349 .status();
350 }
351
352 fn accept_opened(index: &CameraIndex, mut camera: Camera) -> Option<(Camera, String)> {
353 let got = camera.camera_format();
354 if got.frame_rate() < CAPTURE_FPS {
355 let _ = camera.stop_stream();
356 return None;
357 }
358 tune_uvc_controls(index);
359 let label = format_label(&got);
360 Some((camera, label))
361 }
362
363 fn try_exact_or_closest(
364 index: CameraIndex,
365 format: CameraFormat,
366 ) -> std::result::Result<Camera, nokhwa::NokhwaError> {
367 match open_with_request(index.clone(), RequestedFormatType::Exact(format)) {
368 Ok(camera) => Ok(camera),
369 Err(_) => open_with_request(index, RequestedFormatType::Closest(format)),
370 }
371 }
372
373 fn open_from_list(
374 index: CameraIndex,
375 quality: VideoQuality,
376 formats: &[CameraFormat],
377 ) -> Option<(Camera, String)> {
378 let Some(wanted) = pick_format(formats, quality) else {
379 return None;
380 };
381 let camera = try_exact_or_closest(index.clone(), wanted).ok()?;
382 accept_opened(&index, camera)
383 }
384
385 211 fn open_camera(
386 212 index: CameraIndex,
387 213 quality: VideoQuality,
388 ) -> std::result::Result<(Camera, String), nokhwa::NokhwaError> {
389 // Probe the device list without committing to a slow Closest(NV12) open.
390 for probe in preferred_candidates(quality) {
391 let Ok(mut camera) = try_exact_or_closest(index.clone(), probe) else {
392 continue;
393 };
394 if let Ok(formats) = camera.compatible_camera_formats() {
395 let _ = camera.stop_stream();
396 drop(camera);
397 if let Some(opened) = open_from_list(index.clone(), quality, &formats) {
398 return Ok(opened);
399 }
400 } else if let Some(opened) = accept_opened(&index, camera) {
401 return Ok(opened);
402 }
214 ) -> std::result::Result<Camera, nokhwa::NokhwaError> {
215 if let Ok(camera) = open_picked_format(index.clone(), quality) {
216 return Ok(camera);
403 217 }
404
218 let wanted = Resolution::new(quality.capture_width(), quality.capture_height());
219 let mut requests: Vec<RequestedFormatType> = DIRECT_FORMATS
220 .into_iter()
221 .map(|frame_format| {
222 RequestedFormatType::Closest(CameraFormat::new(wanted, frame_format, CAPTURE_FPS))
223 })
224 .collect();
225 requests.push(RequestedFormatType::AbsoluteHighestFrameRate);
405 226 let mut last_error = None;
406 for candidate in preferred_candidates(quality) {
407 match try_exact_or_closest(index.clone(), candidate) {
408 Ok(camera) => {
409 if let Some(opened) = accept_opened(&index, camera) {
410 return Ok(opened);
411 }
412 }
227 for request in requests {
228 let format = RequestedFormat::new::<RgbAFormat>(request);
229 match Camera::new(index.clone(), format)
230 .and_then(|mut camera| camera.open_stream().map(|()| camera))
231 {
232 Ok(camera) => return Ok(camera),
413 233 Err(error) => last_error = Some(error),
414 234 }
415 235 }
416
417 // Last resort: AbsoluteHighest may still yield a usable stream on odd backends.
418 match open_with_request(index.clone(), RequestedFormatType::AbsoluteHighestFrameRate) {
419 Ok(camera) => {
420 tune_uvc_controls(&index);
421 let label = format_label(&camera.camera_format());
422 Ok((camera, label))
423 }
424 Err(error) => Err(last_error.unwrap_or(error)),
425 }
236 Err(last_error.expect("at least one request"))
426 237 }
427 238
428 239 pub(crate) fn i420_from_nv12(data: &[u8], width: u32, height: u32) -> Option<I420Buffer> {
@@ -482,42 +293,15 @@ pub(crate) fn i420_from_yuyv(data: &[u8], width: u32, height: u32) -> Option<I42
482 293 Some(buffer)
483 294 }
484 295
485 fn i420_from_mjpeg(data: &[u8], rgba_scratch: &mut Vec<u8>) -> Option<(I420Buffer, u32, u32)> {
486 let options = DecoderOptions::default().jpeg_set_out_colorspace(ColorSpace::RGBA);
487 let mut decoder = JpegDecoder::new_with_options(ZCursor::new(data), options);
488 let pixels = decoder.decode().ok()?;
489 let info = decoder.info()?;
490 let (width, height) = (u32::from(info.width), u32::from(info.height));
491 if width < 2 || height < 2 || width % 2 != 0 || height % 2 != 0 {
492 return None;
493 }
494 let rgba_len = (width * height * BYTES_PER_PIXEL) as usize;
495 let rgba = if pixels.len() == rgba_len {
496 pixels.as_slice()
497 } else if pixels.len() == (width * height * 3) as usize {
498 rgba_scratch.clear();
499 rgba_scratch.reserve(rgba_len);
500 for chunk in pixels.chunks_exact(3) {
501 rgba_scratch.extend_from_slice(&[chunk[0], chunk[1], chunk[2], 255]);
502 }
503 rgba_scratch.as_slice()
504 } else {
505 return None;
506 };
507 Some((i420_from_rgba(rgba, width, height), width, height))
508 }
509
510 296 fn direct_i420(
511 297 frame_format: FrameFormat,
512 298 data: &[u8],
513 299 width: u32,
514 300 height: u32,
515 rgba_scratch: &mut Vec<u8>,
516 301 ) -> Option<I420Buffer> {
517 302 match frame_format {
518 303 FrameFormat::NV12 => i420_from_nv12(data, width, height),
519 304 FrameFormat::YUYV => i420_from_yuyv(data, width, height),
520 FrameFormat::MJPEG => i420_from_mjpeg(data, rgba_scratch).map(|(buffer, _, _)| buffer),
521 305 _ => None,
522 306 }
523 307 }
@@ -526,25 +310,20 @@ pub fn start_camera(
526 310 choice: &DeviceChoice,
527 311 quality: VideoQuality,
528 312 blur: Arc<BlurSettings>,
529 stats: Arc<CameraCaptureStats>,
530 on_opened: impl FnOnce(String) + Send + 'static,
531 313 deliver: impl FnMut(I420Buffer) + Send + 'static,
532 314 failed: impl FnOnce(String) + Send + 'static,
533 315 ) -> Result<Capture> {
534 316 let index = camera_index(choice);
535 317 Capture::spawn_thread("camera", move |stop| {
536 let (mut camera, label) = match open_camera(index, quality) {
537 Ok(opened) => opened,
318 let mut camera = match open_camera(index, quality) {
319 Ok(camera) => camera,
538 320 Err(error) => return failed(error.to_string()),
539 321 };
540 stats.set_format(&label);
541 on_opened(label);
542 322 let effects = match EffectsThread::spawn(blur, deliver) {
543 323 Ok(effects) => effects,
544 324 Err(error) => return failed(format!("effects thread: {error}")),
545 325 };
546 326 let mut warned_undecodable = false;
547 let mut rgba_scratch = Vec::new();
548 327 while !stop.load(Ordering::SeqCst) {
549 328 let Ok(frame) = camera.frame() else {
550 329 std::thread::sleep(RETRY_PAUSE);
@@ -555,29 +334,22 @@ pub fn start_camera(
555 334 if width < 2 || height < 2 || width % 2 != 0 || height % 2 != 0 {
556 335 continue;
557 336 }
558 let started = Instant::now();
559 let buffer = match direct_i420(
560 frame.source_frame_format(),
561 frame.buffer(),
562 width,
563 height,
564 &mut rgba_scratch,
565 ) {
566 Some(buffer) => buffer,
567 None => {
568 let Ok(decoded) = frame.decode_image::<RgbAFormat>() else {
569 if !std::mem::replace(&mut warned_undecodable, true) {
570 eprintln!(
571 "calls: camera delivers {} and no decoder is available",
572 frame.source_frame_format()
573 );
574 }
575 continue;
576 };
577 i420_from_rgba(&decoded.into_raw(), width, height)
578 }
579 };
580 stats.note_frame(started.elapsed());
337 let buffer =
338 match direct_i420(frame.source_frame_format(), frame.buffer(), width, height) {
339 Some(buffer) => buffer,
340 None => {
341 let Ok(decoded) = frame.decode_image::<RgbAFormat>() else {
342 if !std::mem::replace(&mut warned_undecodable, true) {
343 eprintln!(
344 "calls: camera delivers {} and no decoder is available",
345 frame.source_frame_format()
346 );
347 }
348 continue;
349 };
350 i420_from_rgba(&decoded.into_raw(), width, height)
351 }
352 };
581 353 effects.submit(fit_widescreen(buffer, quality));
582 354 }
583 355 let _ = camera.stop_stream();
@@ -649,7 +421,7 @@ mod tests {
649 421 }
650 422
651 423 #[test]
652 fn a_c920_like_list_picks_hd_mjpeg_at_30_fps_over_slow_raw() {
424 fn a_c920_like_list_picks_the_raw_format_that_runs_at_30_fps() {
653 425 let formats = [
654 426 format(1280, 720, FrameFormat::YUYV, 10),
655 427 format(640, 480, FrameFormat::YUYV, 30),
@@ -657,39 +429,7 @@ mod tests {
657 429 ];
658 430 assert_eq!(
659 431 pick_format(&formats, VideoQuality::P720),
660 Some(format(1280, 720, FrameFormat::MJPEG, 30))
661 );
662 }
663
664 #[test]
665 fn raw_at_the_same_height_beats_mjpeg() {
666 let formats = [
667 format(1280, 720, FrameFormat::MJPEG, 30),
668 format(1280, 720, FrameFormat::NV12, 30),
669 ];
670 assert_eq!(
671 pick_format(&formats, VideoQuality::P720),
672 Some(format(1280, 720, FrameFormat::NV12, 30))
673 );
674 }
675
676 #[test]
677 fn a_c930e_like_list_picks_mjpeg_1080_for_auto() {
678 let formats = [
679 format(1920, 1080, FrameFormat::YUYV, 5),
680 format(1280, 720, FrameFormat::YUYV, 10),
681 format(640, 360, FrameFormat::YUYV, 30),
682 format(1920, 1080, FrameFormat::MJPEG, 30),
683 format(1280, 720, FrameFormat::MJPEG, 30),
684 format(960, 540, FrameFormat::MJPEG, 30),
685 ];
686 assert_eq!(
687 pick_format(&formats, VideoQuality::Auto),
688 Some(format(1920, 1080, FrameFormat::MJPEG, 30))
689 );
690 assert_eq!(
691 pick_format(&formats, VideoQuality::P720),
692 Some(format(1280, 720, FrameFormat::MJPEG, 30))
432 Some(format(640, 480, FrameFormat::YUYV, 30))
693 433 );
694 434 }
695 435
@@ -791,7 +531,7 @@ mod tests {
791 531 #[test]
792 532 fn no_usable_format_picks_nothing() {
793 533 let formats = [
794 format(1280, 720, FrameFormat::MJPEG, 15),
534 format(1280, 720, FrameFormat::MJPEG, 30),
795 535 format(1280, 720, FrameFormat::YUYV, 15),
796 536 ];
797 537 assert_eq!(pick_format(&formats, VideoQuality::Auto), None);
@@ -813,80 +553,4 @@ mod tests {
813 553 CameraIndex::String(_)
814 554 ));
815 555 }
816
817 #[test]
818 fn mjpeg_decodes_to_i420() {
819 // Minimal valid grayscale JPEG is awkward; encode via `image` crate.
820 let mut rgb = image::RgbImage::new(16, 16);
821 for pixel in rgb.pixels_mut() {
822 *pixel = image::Rgb([40, 80, 120]);
823 }
824 let mut jpeg = Vec::new();
825 image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, 90)
826 .encode(rgb.as_raw(), 16, 16, image::ExtendedColorType::Rgb8)
827 .expect("encode");
828 let mut scratch = Vec::new();
829 let (buffer, width, height) =
830 i420_from_mjpeg(&jpeg, &mut scratch).expect("mjpeg decodes");
831 assert_eq!((width, height), (16, 16));
832 assert_eq!((buffer.width(), buffer.height()), (16, 16));
833 }
834
835 #[test]
836 #[ignore = "timing; run with --release --ignored"]
837 fn mjpeg_1080p_decode_stays_under_fifteen_ms() {
838 let mut rgb = image::RgbImage::new(1920, 1080);
839 for (index, pixel) in rgb.pixels_mut().enumerate() {
840 let value = (index % 255) as u8;
841 *pixel = image::Rgb([value, value.wrapping_add(40), value.wrapping_add(80)]);
842 }
843 let mut jpeg = Vec::new();
844 image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, 85)
845 .encode(rgb.as_raw(), 1920, 1080, image::ExtendedColorType::Rgb8)
846 .expect("encode");
847 let mut scratch = Vec::new();
848 // Warm caches / CPU, then time a steady batch (30 fps allows ~33 ms/frame).
849 for _ in 0..3 {
850 let _ = i420_from_mjpeg(&jpeg, &mut scratch).expect("decode");
851 }
852 let started = Instant::now();
853 for _ in 0..10 {
854 let _ = i420_from_mjpeg(&jpeg, &mut scratch).expect("decode");
855 }
856 let average = started.elapsed() / 10;
857 assert!(
858 average < Duration::from_millis(20),
859 "average decode {average:?} exceeds 20 ms"
860 );
861 }
862
863 #[test]
864 #[ignore = "needs a connected camera"]
865 fn open_picks_at_least_thirty_fps_when_available() {
866 if list_cameras().is_empty() {
867 return;
868 }
869 let (mut camera, label) = open_camera(CameraIndex::Index(0), VideoQuality::Auto)
870 .expect("camera opens");
871 assert!(
872 camera.camera_format().frame_rate() >= CAPTURE_FPS,
873 "opened {label} under 30 fps"
874 );
875 // Warm up buffers, then count for one second.
876 for _ in 0..10 {
877 let _ = camera.frame();
878 }
879 let deadline = Instant::now() + Duration::from_secs(1);
880 let mut frames = 0u32;
881 while Instant::now() < deadline {
882 if camera.frame().is_ok() {
883 frames += 1;
884 }
885 }
886 let _ = camera.stop_stream();
887 assert!(
888 frames >= 20,
889 "expected >= 20 frames in 1 s from {label}, got {frames}"
890 );
891 }
892 556 }
@@ -1,7 +1,5 @@
1use std::process::Command;
2use std::sync::Arc;
1use std::sync::Arc;
3use std::sync::atomic::{AtomicU64, Ordering};
2use std::time::Duration;
4use std::time::{Duration, Instant};
5
3
6use libwebrtc::native::yuv_helper::{abgr_to_i420, nv12_to_i420};
4use libwebrtc::native::yuv_helper::{abgr_to_i420, nv12_to_i420};
7use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};
5use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};
@@ -11,10 +9,7 @@ use nokhwa::utils::{
11 Resolution,
9 Resolution,
12};
10};
13use nokhwa::{Camera, query};
11use nokhwa::{Camera, query};
14use zune_core::bytestream::ZCursor;
12use std::sync::atomic::Ordering;
15use zune_core::colorspace::ColorSpace;
16use zune_core::options::DecoderOptions;
17use zune_jpeg::JpegDecoder;
18
13
19use crate::blur::BlurSettings;
14use crate::blur::BlurSettings;
20use crate::capture::Capture;
15use crate::capture::Capture;
@@ -29,8 +24,6 @@ const CAPTURE_FPS: u32 = 30;
29const ASPECT_WIDTH: u32 = 16;
24const ASPECT_WIDTH: u32 = 16;
30const ASPECT_HEIGHT: u32 = 9;
25const ASPECT_HEIGHT: u32 = 9;
31const DIRECT_FORMATS: [FrameFormat; 2] = [FrameFormat::NV12, FrameFormat::YUYV];
26const DIRECT_FORMATS: [FrameFormat; 2] = [FrameFormat::NV12, FrameFormat::YUYV];
32const USABLE_FORMATS: [FrameFormat; 3] =
33 [FrameFormat::NV12, FrameFormat::YUYV, FrameFormat::MJPEG];
34
27
35#[derive(Debug, Clone, PartialEq, Eq)]
28#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct CameraDevice {
29pub struct CameraDevice {
@@ -38,72 +31,6 @@ pub struct CameraDevice {
38 pub name: String,
31 pub name: String,
39}
32}
40
33
41/// Shared capture counters for call-report stats (format + fps + decode time).
42#[derive(Debug, Default)]
43pub struct CameraCaptureStats {
44 format: std::sync::Mutex<String>,
45 started: std::sync::Mutex<Option<Instant>>,
46 frames: AtomicU64,
47 decode_ns: AtomicU64,
48}
49
50impl CameraCaptureStats {
51 pub fn new() -> Arc<Self> {
52 Arc::new(Self::default())
53 }
54
55 fn set_format(&self, label: impl Into<String>) {
56 if let Ok(mut slot) = self.format.lock() {
57 *slot = label.into();
58 }
59 if let Ok(mut started) = self.started.lock() {
60 *started = Some(Instant::now());
61 }
62 self.frames.store(0, Ordering::Relaxed);
63 self.decode_ns.store(0, Ordering::Relaxed);
64 }
65
66 fn note_frame(&self, decode: Duration) {
67 self.frames.fetch_add(1, Ordering::Relaxed);
68 self.decode_ns
69 .fetch_add(decode.as_nanos() as u64, Ordering::Relaxed);
70 }
71
72 pub fn format_label(&self) -> String {
73 self.format
74 .lock()
75 .map(|label| label.clone())
76 .unwrap_or_default()
77 }
78
79 pub fn summary(&self) -> Option<String> {
80 let label = self.format_label();
81 if label.is_empty() {
82 return None;
83 }
84 let frames = self.frames.load(Ordering::Relaxed);
85 let decode_ns = self.decode_ns.load(Ordering::Relaxed);
86 let decode_ms = if frames == 0 {
87 0.0
88 } else {
89 (decode_ns as f64 / frames as f64) / 1_000_000.0
90 };
91 let fps = self
92 .started
93 .lock()
94 .ok()
95 .and_then(|started| *started)
96 .map(|started| {
97 let seconds = started.elapsed().as_secs_f64().max(0.001);
98 frames as f64 / seconds
99 })
100 .unwrap_or(0.0);
101 Some(format!(
102 " camera={label} capture={fps:.1}fps decode={decode_ms:.1}ms"
103 ))
104 }
105}
106
107pub fn list_cameras() -> Vec<CameraDevice> {
34pub fn list_cameras() -> Vec<CameraDevice> {
108 query(ApiBackend::Auto)
35 query(ApiBackend::Auto)
109 .unwrap_or_default()
36 .unwrap_or_default()
@@ -148,32 +75,11 @@ pub fn i420_from_rgba(rgba: &[u8], width: u32, height: u32) -> I420Buffer {
148
75
149fn format_rank(frame_format: FrameFormat) -> u8 {
76fn format_rank(frame_format: FrameFormat) -> u8 {
150 match frame_format {
77 match frame_format {
151 FrameFormat::NV12 => 3,
78 FrameFormat::NV12 => 1,
152 FrameFormat::YUYV => 2,
153 FrameFormat::MJPEG => 1,
154 _ => 0,
79 _ => 0,
155 }
80 }
156}
81}
157
82
158fn format_short_name(frame_format: FrameFormat) -> String {
159 match frame_format {
160 FrameFormat::MJPEG => "MJPG".into(),
161 FrameFormat::NV12 => "NV12".into(),
162 FrameFormat::YUYV => "YUYV".into(),
163 other => other.to_string(),
164 }
165}
166
167fn format_label(format: &CameraFormat) -> String {
168 format!(
169 "{} {}x{} @{}",
170 format_short_name(format.format()),
171 format.width(),
172 format.height(),
173 format.frame_rate()
174 )
175}
176
177fn is_widescreen(width: u32, height: u32) -> bool {
83fn is_widescreen(width: u32, height: u32) -> bool {
178 width * ASPECT_HEIGHT == height * ASPECT_WIDTH
84 width * ASPECT_HEIGHT == height * ASPECT_WIDTH
179}
85}
@@ -196,7 +102,7 @@ fn pick_format(formats: &[CameraFormat], quality: VideoQuality) -> Option<Camera
196 formats
102 formats
197 .iter()
103 .iter()
198 .copied()
104 .copied()
199 .filter(|format| USABLE_FORMATS.contains(&format.format()))
105 .filter(|format| DIRECT_FORMATS.contains(&format.format()))
200 .filter(|format| format.frame_rate() >= CAPTURE_FPS)
106 .filter(|format| format.frame_rate() >= CAPTURE_FPS)
201 .filter(|format| {
107 .filter(|format| {
202 format.height() <= capture_height
108 format.height() <= capture_height
@@ -212,33 +118,6 @@ fn pick_format(formats: &[CameraFormat], quality: VideoQuality) -> Option<Camera
212 })
118 })
213}
119}
214
120
215fn candidate_heights(quality: VideoQuality) -> Vec<u32> {
216 match quality {
217 VideoQuality::P720 => vec![720, 540, 360],
218 VideoQuality::Auto | VideoQuality::P1080 => vec![1080, 720, 540, 360],
219 }
220}
221
222fn preferred_candidates(quality: VideoQuality) -> Vec<CameraFormat> {
223 let mut candidates = Vec::new();
224 for height in candidate_heights(quality) {
225 let width = height * ASPECT_WIDTH / ASPECT_HEIGHT;
226 candidates.push(CameraFormat::new(
227 Resolution::new(width, height),
228 FrameFormat::MJPEG,
229 CAPTURE_FPS,
230 ));
231 for frame_format in DIRECT_FORMATS {
232 candidates.push(CameraFormat::new(
233 Resolution::new(width, height),
234 frame_format,
235 CAPTURE_FPS,
236 ));
237 }
238 }
239 candidates
240}
241
242fn even(value: u32) -> u32 {
121fn even(value: u32) -> u32 {
243 value & !1
122 value & !1
244}
123}
@@ -310,119 +189,51 @@ pub(crate) fn fit_widescreen(mut buffer: I420Buffer, quality: VideoQuality) -> I
310 buffer
189 buffer
311}
190}
312
191
313fn open_with_request(
192fn open_picked_format(
314 index: CameraIndex,
193 index: CameraIndex,
315 request: RequestedFormatType,
194 quality: VideoQuality,
316) -> std::result::Result<Camera, nokhwa::NokhwaError> {
195) -> std::result::Result<Camera, nokhwa::NokhwaError> {
317 let format = RequestedFormat::new::<RgbAFormat>(request);
196 let mut camera = Camera::new(
318 let mut camera = Camera::new(index, format)?;
197 index,
198 RequestedFormat::new::<RgbAFormat>(RequestedFormatType::AbsoluteHighestFrameRate),
199 )?;
200 let formats = camera.compatible_camera_formats()?;
201 let format = pick_format(&formats, quality).ok_or_else(|| {
202 nokhwa::NokhwaError::GeneralError("no raw camera format at 30 fps".to_owned())
203 })?;
204 camera.set_camera_requset(RequestedFormat::new::<RgbAFormat>(
205 RequestedFormatType::Exact(format),
206 ))?;
319 camera.open_stream()?;
207 camera.open_stream()?;
320 Ok(camera)
208 Ok(camera)
321}
209}
322
210
323fn device_path(index: &CameraIndex) -> Option<String> {
324 match index {
325 CameraIndex::Index(number) => Some(format!("/dev/video{number}")),
326 CameraIndex::String(text) if text.starts_with("/dev/") => Some(text.clone()),
327 CameraIndex::String(text) if text.chars().all(|c| c.is_ascii_digit()) => {
328 Some(format!("/dev/video{text}"))
329 }
330 CameraIndex::String(text) if text.starts_with("video") => Some(format!("/dev/{text}")),
331 _ => None,
332 }
333}
334
335fn tune_uvc_controls(index: &CameraIndex) {
336 let Some(device) = device_path(index) else {
337 return;
338 };
339 // Best effort: fixed frame rate (no auto-drop in low light) and 50 Hz mains (CH).
340 let _ = Command::new("v4l2-ctl")
341 .args([
342 "-d",
343 &device,
344 "-c",
345 "exposure_dynamic_framerate=0,power_line_frequency=1",
346 ])
347 .stdout(std::process::Stdio::null())
348 .stderr(std::process::Stdio::null())
349 .status();
350}
351
352fn accept_opened(index: &CameraIndex, mut camera: Camera) -> Option<(Camera, String)> {
353 let got = camera.camera_format();
354 if got.frame_rate() < CAPTURE_FPS {
355 let _ = camera.stop_stream();
356 return None;
357 }
358 tune_uvc_controls(index);
359 let label = format_label(&got);
360 Some((camera, label))
361}
362
363fn try_exact_or_closest(
364 index: CameraIndex,
365 format: CameraFormat,
366) -> std::result::Result<Camera, nokhwa::NokhwaError> {
367 match open_with_request(index.clone(), RequestedFormatType::Exact(format)) {
368 Ok(camera) => Ok(camera),
369 Err(_) => open_with_request(index, RequestedFormatType::Closest(format)),
370 }
371}
372
373fn open_from_list(
374 index: CameraIndex,
375 quality: VideoQuality,
376 formats: &[CameraFormat],
377) -> Option<(Camera, String)> {
378 let Some(wanted) = pick_format(formats, quality) else {
379 return None;
380 };
381 let camera = try_exact_or_closest(index.clone(), wanted).ok()?;
382 accept_opened(&index, camera)
383}
384
385fn open_camera(
211fn open_camera(
386 index: CameraIndex,
212 index: CameraIndex,
387 quality: VideoQuality,
213 quality: VideoQuality,
388) -> std::result::Result<(Camera, String), nokhwa::NokhwaError> {
214) -> std::result::Result<Camera, nokhwa::NokhwaError> {
389 // Probe the device list without committing to a slow Closest(NV12) open.
215 if let Ok(camera) = open_picked_format(index.clone(), quality) {
390 for probe in preferred_candidates(quality) {
216 return Ok(camera);
391 let Ok(mut camera) = try_exact_or_closest(index.clone(), probe) else {
392 continue;
393 };
394 if let Ok(formats) = camera.compatible_camera_formats() {
395 let _ = camera.stop_stream();
396 drop(camera);
397 if let Some(opened) = open_from_list(index.clone(), quality, &formats) {
398 return Ok(opened);
399 }
400 } else if let Some(opened) = accept_opened(&index, camera) {
401 return Ok(opened);
402 }
403 }
217 }
404
218 let wanted = Resolution::new(quality.capture_width(), quality.capture_height());
219 let mut requests: Vec<RequestedFormatType> = DIRECT_FORMATS
220 .into_iter()
221 .map(|frame_format| {
222 RequestedFormatType::Closest(CameraFormat::new(wanted, frame_format, CAPTURE_FPS))
223 })
224 .collect();
225 requests.push(RequestedFormatType::AbsoluteHighestFrameRate);
405 let mut last_error = None;
226 let mut last_error = None;
406 for candidate in preferred_candidates(quality) {
227 for request in requests {
407 match try_exact_or_closest(index.clone(), candidate) {
228 let format = RequestedFormat::new::<RgbAFormat>(request);
408 Ok(camera) => {
229 match Camera::new(index.clone(), format)
409 if let Some(opened) = accept_opened(&index, camera) {
230 .and_then(|mut camera| camera.open_stream().map(|()| camera))
410 return Ok(opened);
231 {
411 }
232 Ok(camera) => return Ok(camera),
412 }
413 Err(error) => last_error = Some(error),
233 Err(error) => last_error = Some(error),
414 }
234 }
415 }
235 }
416
236 Err(last_error.expect("at least one request"))
417 // Last resort: AbsoluteHighest may still yield a usable stream on odd backends.
418 match open_with_request(index.clone(), RequestedFormatType::AbsoluteHighestFrameRate) {
419 Ok(camera) => {
420 tune_uvc_controls(&index);
421 let label = format_label(&camera.camera_format());
422 Ok((camera, label))
423 }
424 Err(error) => Err(last_error.unwrap_or(error)),
425 }
426}
237}
427
238
428pub(crate) fn i420_from_nv12(data: &[u8], width: u32, height: u32) -> Option<I420Buffer> {
239pub(crate) fn i420_from_nv12(data: &[u8], width: u32, height: u32) -> Option<I420Buffer> {
@@ -482,42 +293,15 @@ pub(crate) fn i420_from_yuyv(data: &[u8], width: u32, height: u32) -> Option<I42
482 Some(buffer)
293 Some(buffer)
483}
294}
484
295
485fn i420_from_mjpeg(data: &[u8], rgba_scratch: &mut Vec<u8>) -> Option<(I420Buffer, u32, u32)> {
486 let options = DecoderOptions::default().jpeg_set_out_colorspace(ColorSpace::RGBA);
487 let mut decoder = JpegDecoder::new_with_options(ZCursor::new(data), options);
488 let pixels = decoder.decode().ok()?;
489 let info = decoder.info()?;
490 let (width, height) = (u32::from(info.width), u32::from(info.height));
491 if width < 2 || height < 2 || width % 2 != 0 || height % 2 != 0 {
492 return None;
493 }
494 let rgba_len = (width * height * BYTES_PER_PIXEL) as usize;
495 let rgba = if pixels.len() == rgba_len {
496 pixels.as_slice()
497 } else if pixels.len() == (width * height * 3) as usize {
498 rgba_scratch.clear();
499 rgba_scratch.reserve(rgba_len);
500 for chunk in pixels.chunks_exact(3) {
501 rgba_scratch.extend_from_slice(&[chunk[0], chunk[1], chunk[2], 255]);
502 }
503 rgba_scratch.as_slice()
504 } else {
505 return None;
506 };
507 Some((i420_from_rgba(rgba, width, height), width, height))
508}
509
510fn direct_i420(
296fn direct_i420(
511 frame_format: FrameFormat,
297 frame_format: FrameFormat,
512 data: &[u8],
298 data: &[u8],
513 width: u32,
299 width: u32,
514 height: u32,
300 height: u32,
515 rgba_scratch: &mut Vec<u8>,
516) -> Option<I420Buffer> {
301) -> Option<I420Buffer> {
517 match frame_format {
302 match frame_format {
518 FrameFormat::NV12 => i420_from_nv12(data, width, height),
303 FrameFormat::NV12 => i420_from_nv12(data, width, height),
519 FrameFormat::YUYV => i420_from_yuyv(data, width, height),
304 FrameFormat::YUYV => i420_from_yuyv(data, width, height),
520 FrameFormat::MJPEG => i420_from_mjpeg(data, rgba_scratch).map(|(buffer, _, _)| buffer),
521 _ => None,
305 _ => None,
522 }
306 }
523}
307}
@@ -526,25 +310,20 @@ pub fn start_camera(
526 choice: &DeviceChoice,
310 choice: &DeviceChoice,
527 quality: VideoQuality,
311 quality: VideoQuality,
528 blur: Arc<BlurSettings>,
312 blur: Arc<BlurSettings>,
529 stats: Arc<CameraCaptureStats>,
530 on_opened: impl FnOnce(String) + Send + 'static,
531 deliver: impl FnMut(I420Buffer) + Send + 'static,
313 deliver: impl FnMut(I420Buffer) + Send + 'static,
532 failed: impl FnOnce(String) + Send + 'static,
314 failed: impl FnOnce(String) + Send + 'static,
533) -> Result<Capture> {
315) -> Result<Capture> {
534 let index = camera_index(choice);
316 let index = camera_index(choice);
535 Capture::spawn_thread("camera", move |stop| {
317 Capture::spawn_thread("camera", move |stop| {
536 let (mut camera, label) = match open_camera(index, quality) {
318 let mut camera = match open_camera(index, quality) {
537 Ok(opened) => opened,
319 Ok(camera) => camera,
538 Err(error) => return failed(error.to_string()),
320 Err(error) => return failed(error.to_string()),
539 };
321 };
540 stats.set_format(&label);
541 on_opened(label);
542 let effects = match EffectsThread::spawn(blur, deliver) {
322 let effects = match EffectsThread::spawn(blur, deliver) {
543 Ok(effects) => effects,
323 Ok(effects) => effects,
544 Err(error) => return failed(format!("effects thread: {error}")),
324 Err(error) => return failed(format!("effects thread: {error}")),
545 };
325 };
546 let mut warned_undecodable = false;
326 let mut warned_undecodable = false;
547 let mut rgba_scratch = Vec::new();
548 while !stop.load(Ordering::SeqCst) {
327 while !stop.load(Ordering::SeqCst) {
549 let Ok(frame) = camera.frame() else {
328 let Ok(frame) = camera.frame() else {
550 std::thread::sleep(RETRY_PAUSE);
329 std::thread::sleep(RETRY_PAUSE);
@@ -555,29 +334,22 @@ pub fn start_camera(
555 if width < 2 || height < 2 || width % 2 != 0 || height % 2 != 0 {
334 if width < 2 || height < 2 || width % 2 != 0 || height % 2 != 0 {
556 continue;
335 continue;
557 }
336 }
558 let started = Instant::now();
337 let buffer =
559 let buffer = match direct_i420(
338 match direct_i420(frame.source_frame_format(), frame.buffer(), width, height) {
560 frame.source_frame_format(),
339 Some(buffer) => buffer,
561 frame.buffer(),
340 None => {
562 width,
341 let Ok(decoded) = frame.decode_image::<RgbAFormat>() else {
563 height,
342 if !std::mem::replace(&mut warned_undecodable, true) {
564 &mut rgba_scratch,
343 eprintln!(
565 ) {
344 "calls: camera delivers {} and no decoder is available",
566 Some(buffer) => buffer,
345 frame.source_frame_format()
567 None => {
346 );
568 let Ok(decoded) = frame.decode_image::<RgbAFormat>() else {
347 }
569 if !std::mem::replace(&mut warned_undecodable, true) {
348 continue;
570 eprintln!(
349 };
571 "calls: camera delivers {} and no decoder is available",
350 i420_from_rgba(&decoded.into_raw(), width, height)
572 frame.source_frame_format()
351 }
573 );
352 };
574 }
575 continue;
576 };
577 i420_from_rgba(&decoded.into_raw(), width, height)
578 }
579 };
580 stats.note_frame(started.elapsed());
581 effects.submit(fit_widescreen(buffer, quality));
353 effects.submit(fit_widescreen(buffer, quality));
582 }
354 }
583 let _ = camera.stop_stream();
355 let _ = camera.stop_stream();
@@ -649,7 +421,7 @@ mod tests {
649 }
421 }
650
422
651 #[test]
423 #[test]
652 fn a_c920_like_list_picks_hd_mjpeg_at_30_fps_over_slow_raw() {
424 fn a_c920_like_list_picks_the_raw_format_that_runs_at_30_fps() {
653 let formats = [
425 let formats = [
654 format(1280, 720, FrameFormat::YUYV, 10),
426 format(1280, 720, FrameFormat::YUYV, 10),
655 format(640, 480, FrameFormat::YUYV, 30),
427 format(640, 480, FrameFormat::YUYV, 30),
@@ -657,39 +429,7 @@ mod tests {
657 ];
429 ];
658 assert_eq!(
430 assert_eq!(
659 pick_format(&formats, VideoQuality::P720),
431 pick_format(&formats, VideoQuality::P720),
660 Some(format(1280, 720, FrameFormat::MJPEG, 30))
432 Some(format(640, 480, FrameFormat::YUYV, 30))
661 );
662 }
663
664 #[test]
665 fn raw_at_the_same_height_beats_mjpeg() {
666 let formats = [
667 format(1280, 720, FrameFormat::MJPEG, 30),
668 format(1280, 720, FrameFormat::NV12, 30),
669 ];
670 assert_eq!(
671 pick_format(&formats, VideoQuality::P720),
672 Some(format(1280, 720, FrameFormat::NV12, 30))
673 );
674 }
675
676 #[test]
677 fn a_c930e_like_list_picks_mjpeg_1080_for_auto() {
678 let formats = [
679 format(1920, 1080, FrameFormat::YUYV, 5),
680 format(1280, 720, FrameFormat::YUYV, 10),
681 format(640, 360, FrameFormat::YUYV, 30),
682 format(1920, 1080, FrameFormat::MJPEG, 30),
683 format(1280, 720, FrameFormat::MJPEG, 30),
684 format(960, 540, FrameFormat::MJPEG, 30),
685 ];
686 assert_eq!(
687 pick_format(&formats, VideoQuality::Auto),
688 Some(format(1920, 1080, FrameFormat::MJPEG, 30))
689 );
690 assert_eq!(
691 pick_format(&formats, VideoQuality::P720),
692 Some(format(1280, 720, FrameFormat::MJPEG, 30))
693 );
433 );
694 }
434 }
695
435
@@ -791,7 +531,7 @@ mod tests {
791 #[test]
531 #[test]
792 fn no_usable_format_picks_nothing() {
532 fn no_usable_format_picks_nothing() {
793 let formats = [
533 let formats = [
794 format(1280, 720, FrameFormat::MJPEG, 15),
534 format(1280, 720, FrameFormat::MJPEG, 30),
795 format(1280, 720, FrameFormat::YUYV, 15),
535 format(1280, 720, FrameFormat::YUYV, 15),
796 ];
536 ];
797 assert_eq!(pick_format(&formats, VideoQuality::Auto), None);
537 assert_eq!(pick_format(&formats, VideoQuality::Auto), None);
@@ -813,80 +553,4 @@ mod tests {
813 CameraIndex::String(_)
553 CameraIndex::String(_)
814 ));
554 ));
815 }
555 }
816
817 #[test]
818 fn mjpeg_decodes_to_i420() {
819 // Minimal valid grayscale JPEG is awkward; encode via `image` crate.
820 let mut rgb = image::RgbImage::new(16, 16);
821 for pixel in rgb.pixels_mut() {
822 *pixel = image::Rgb([40, 80, 120]);
823 }
824 let mut jpeg = Vec::new();
825 image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, 90)
826 .encode(rgb.as_raw(), 16, 16, image::ExtendedColorType::Rgb8)
827 .expect("encode");
828 let mut scratch = Vec::new();
829 let (buffer, width, height) =
830 i420_from_mjpeg(&jpeg, &mut scratch).expect("mjpeg decodes");
831 assert_eq!((width, height), (16, 16));
832 assert_eq!((buffer.width(), buffer.height()), (16, 16));
833 }
834
835 #[test]
836 #[ignore = "timing; run with --release --ignored"]
837 fn mjpeg_1080p_decode_stays_under_fifteen_ms() {
838 let mut rgb = image::RgbImage::new(1920, 1080);
839 for (index, pixel) in rgb.pixels_mut().enumerate() {
840 let value = (index % 255) as u8;
841 *pixel = image::Rgb([value, value.wrapping_add(40), value.wrapping_add(80)]);
842 }
843 let mut jpeg = Vec::new();
844 image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, 85)
845 .encode(rgb.as_raw(), 1920, 1080, image::ExtendedColorType::Rgb8)
846 .expect("encode");
847 let mut scratch = Vec::new();
848 // Warm caches / CPU, then time a steady batch (30 fps allows ~33 ms/frame).
849 for _ in 0..3 {
850 let _ = i420_from_mjpeg(&jpeg, &mut scratch).expect("decode");
851 }
852 let started = Instant::now();
853 for _ in 0..10 {
854 let _ = i420_from_mjpeg(&jpeg, &mut scratch).expect("decode");
855 }
856 let average = started.elapsed() / 10;
857 assert!(
858 average < Duration::from_millis(20),
859 "average decode {average:?} exceeds 20 ms"
860 );
861 }
862
863 #[test]
864 #[ignore = "needs a connected camera"]
865 fn open_picks_at_least_thirty_fps_when_available() {
866 if list_cameras().is_empty() {
867 return;
868 }
869 let (mut camera, label) = open_camera(CameraIndex::Index(0), VideoQuality::Auto)
870 .expect("camera opens");
871 assert!(
872 camera.camera_format().frame_rate() >= CAPTURE_FPS,
873 "opened {label} under 30 fps"
874 );
875 // Warm up buffers, then count for one second.
876 for _ in 0..10 {
877 let _ = camera.frame();
878 }
879 let deadline = Instant::now() + Duration::from_secs(1);
880 let mut frames = 0u32;
881 while Instant::now() < deadline {
882 if camera.frame().is_ok() {
883 frames += 1;
884 }
885 }
886 let _ = camera.stop_stream();
887 assert!(
888 frames >= 20,
889 "expected >= 20 frames in 1 s from {label}, got {frames}"
890 );
891 }
892}
556}
crates/calling/src/control.rs +1 −0
@@ -35,6 +35,7 @@ pub enum CallCommand {
35 35 SelectInput(DeviceChoice),
36 36 SelectOutput(DeviceChoice),
37 37 SetMicSettings(MicSettings),
38 SetVideoQuality(crate::video_quality::VideoQuality),
38 39 RefreshDevices,
39 40 SetCamera(bool),
40 41 SelectCamera(DeviceChoice),
@@ -35,6 +35,7 @@ pub enum CallCommand {
35 SelectInput(DeviceChoice),
35 SelectInput(DeviceChoice),
36 SelectOutput(DeviceChoice),
36 SelectOutput(DeviceChoice),
37 SetMicSettings(MicSettings),
37 SetMicSettings(MicSettings),
38 SetVideoQuality(crate::video_quality::VideoQuality),
38 RefreshDevices,
39 RefreshDevices,
39 SetCamera(bool),
40 SetCamera(bool),
40 SelectCamera(DeviceChoice),
41 SelectCamera(DeviceChoice),
crates/calling/src/video_layout.rs +397 −89
@@ -1,17 +1,18 @@
1 1 use std::collections::HashMap;
2 2 use std::sync::{Arc, Mutex};
3 3
4 use libwebrtc::MediaType;
4 5 use libwebrtc::peer_connection::PeerConnection;
5 6 use libwebrtc::peer_connection_factory::PeerConnectionFactory;
6 7 use libwebrtc::rtp_parameters::{RtpCodecCapability, RtpEncodingParameters};
7 8 use libwebrtc::rtp_transceiver::{RtpTransceiver, RtpTransceiverDirection, RtpTransceiverInit};
8 use libwebrtc::MediaType;
9 9 use serde_json::{Value, json};
10 10
11 11 use crate::error::{Error, Result};
12 use crate::send_control::capture_macroblocks;
13 12 use crate::sdp::{LineRole, OfferPlan, StreamLine};
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,9 +26,27 @@ 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 { max_fs: 3600, max_fps: 3000, max_mbps: 108_000 };
29 const SMALL_REQUEST: ReceiveLimits = ReceiveLimits { max_fs: 920, max_fps: 3000, max_mbps: 27_600 };
30 const SCREEN_REQUEST: ReceiveLimits = ReceiveLimits { max_fs: 8160, max_fps: 1500, max_mbps: 135_000 };
29 const STAGE_720_REQUEST: ReceiveLimits = ReceiveLimits {
30 max_fs: 3600,
31 max_fps: 3000,
32 max_mbps: 108_000,
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 };
40 const SMALL_REQUEST: ReceiveLimits = ReceiveLimits {
41 max_fs: 920,
42 max_fps: 3000,
43 max_mbps: 27_600,
44 };
45 const SCREEN_REQUEST: ReceiveLimits = ReceiveLimits {
46 max_fs: 8160,
47 max_fps: 1500,
48 max_mbps: 135_000,
49 };
31 50 const SUBSCRIBE_PROFILE: &str = "64001f";
32 51 const SIMULCAST_RIDS: [&str; 3] = ["1", "2", "3"];
33 52 const SIMULCAST_START_SCALES: [f64; 3] = [4.0, 2.0, 1.0];
@@ -43,9 +62,12 @@ pub enum TileDetail {
43 62 }
44 63
45 64 impl TileDetail {
46 fn limits(self) -> ReceiveLimits {
65 fn limits(self, quality: VideoQuality) -> ReceiveLimits {
47 66 match self {
48 TileDetail::Stage => STAGE_REQUEST,
67 TileDetail::Stage => match quality {
68 VideoQuality::P720 => STAGE_720_REQUEST,
69 VideoQuality::Auto | VideoQuality::P1080 => STAGE_1080_REQUEST,
70 },
49 71 TileDetail::Small => SMALL_REQUEST,
50 72 }
51 73 }
@@ -68,7 +90,6 @@ pub fn offer_plan() -> OfferPlan {
68 90 OfferPlan {
69 91 screen_share_mids: vec![SHARE_MID.to_owned()],
70 92 gallery_mids: Vec::new(),
71 fold_groups: Vec::new(),
72 93 }
73 94 }
74 95
@@ -76,7 +97,6 @@ pub fn one_to_one_plan() -> OfferPlan {
76 97 OfferPlan {
77 98 screen_share_mids: vec![ONE_TO_ONE_SHARE_MID.to_owned()],
78 99 gallery_mids: Vec::new(),
79 fold_groups: Vec::new(),
80 100 }
81 101 }
82 102
@@ -131,28 +151,83 @@ fn simulcast_encodings() -> Vec<RtpEncodingParameters> {
131 151 .collect()
132 152 }
133 153
134 pub fn add_video_lines(peer: &PeerConnection, factory: &PeerConnectionFactory) -> Result<VideoLines> {
154 pub fn add_video_lines(
155 peer: &PeerConnection,
156 factory: &PeerConnectionFactory,
157 ) -> Result<VideoLines> {
135 158 let sending = h264_only(factory.get_rtp_sender_capabilities(MediaType::Video).codecs);
136 let receiving = h264_only(factory.get_rtp_receiver_capabilities(MediaType::Video).codecs);
137 let camera = add_line(peer, RtpTransceiverDirection::SendRecv, Some(CAMERA_STREAM), sending.clone(), simulcast_encodings())?;
159 let receiving = h264_only(
160 factory
161 .get_rtp_receiver_capabilities(MediaType::Video)
162 .codecs,
163 );
164 let camera = add_line(
165 peer,
166 RtpTransceiverDirection::SendRecv,
167 Some(CAMERA_STREAM),
168 sending.clone(),
169 simulcast_encodings(),
170 )?;
138 171 for _ in 0..RECEIVE_SLOTS {
139 add_line(peer, RtpTransceiverDirection::RecvOnly, None, receiving.clone(), Vec::new())?;
140 }
141 let share = add_line(peer, RtpTransceiverDirection::SendRecv, Some(SCREEN_STREAM), sending, Vec::new())?;
142 Ok(VideoLines { camera, share: Some(share) })
172 add_line(
173 peer,
174 RtpTransceiverDirection::RecvOnly,
175 None,
176 receiving.clone(),
177 Vec::new(),
178 )?;
179 }
180 let share = add_line(
181 peer,
182 RtpTransceiverDirection::SendRecv,
183 Some(SCREEN_STREAM),
184 sending,
185 Vec::new(),
186 )?;
187 Ok(VideoLines {
188 camera,
189 share: Some(share),
190 })
143 191 }
144 192
145 193 /// A sharing line added to a running direct call, the way Teams adds it before its share offer.
146 pub fn add_share_line(peer: &PeerConnection, factory: &PeerConnectionFactory) -> Result<RtpTransceiver> {
194 pub fn add_share_line(
195 peer: &PeerConnection,
196 factory: &PeerConnectionFactory,
197 ) -> Result<RtpTransceiver> {
147 198 let sending = h264_only(factory.get_rtp_sender_capabilities(MediaType::Video).codecs);
148 add_line(peer, RtpTransceiverDirection::SendRecv, Some(SCREEN_STREAM), sending, Vec::new())
199 add_line(
200 peer,
201 RtpTransceiverDirection::SendRecv,
202 Some(SCREEN_STREAM),
203 sending,
204 Vec::new(),
205 )
149 206 }
150 207
151 pub fn add_one_to_one_lines(peer: &PeerConnection, factory: &PeerConnectionFactory) -> Result<VideoLines> {
208 pub fn add_one_to_one_lines(
209 peer: &PeerConnection,
210 factory: &PeerConnectionFactory,
211 ) -> Result<VideoLines> {
152 212 let sending = h264_only(factory.get_rtp_sender_capabilities(MediaType::Video).codecs);
153 let camera = add_line(peer, RtpTransceiverDirection::SendRecv, Some(CAMERA_STREAM), sending.clone(), Vec::new())?;
154 let share = add_line(peer, RtpTransceiverDirection::SendRecv, Some(SCREEN_STREAM), sending, Vec::new())?;
155 Ok(VideoLines { camera, share: Some(share) })
213 let camera = add_line(
214 peer,
215 RtpTransceiverDirection::SendRecv,
216 Some(CAMERA_STREAM),
217 sending.clone(),
218 Vec::new(),
219 )?;
220 let share = add_line(
221 peer,
222 RtpTransceiverDirection::SendRecv,
223 Some(SCREEN_STREAM),
224 sending,
225 Vec::new(),
226 )?;
227 Ok(VideoLines {
228 camera,
229 share: Some(share),
230 })
156 231 }
157 232
158 233 /// Per-line direction told to the mixer through `updateMediaDescriptions`; no SDP renegotiation.
@@ -174,9 +249,17 @@ impl MediaDescription {
174 249
175 250 fn line(mid: &'static str, sending: bool, label: &'static str) -> Self {
176 251 if sending {
177 MediaDescription { mid, direction: "sendrecv", label: Some(label) }
252 MediaDescription {
253 mid,
254 direction: "sendrecv",
255 label: Some(label),
256 }
178 257 } else {
179 MediaDescription { mid, direction: "recvonly", label: None }
258 MediaDescription {
259 mid,
260 direction: "recvonly",
261 label: None,
262 }
180 263 }
181 264 }
182 265
@@ -216,7 +299,10 @@ impl SlotTable {
216 299 .filter_map(slot)
217 300 .take(RECEIVE_SLOTS)
218 301 .collect();
219 let screen = streams.iter().find(|stream| stream.role == LineRole::ScreenShare).and_then(slot);
302 let screen = streams
303 .iter()
304 .find(|stream| stream.role == LineRole::ScreenShare)
305 .and_then(slot);
220 306 SlotTable { people, screen }
221 307 }
222 308
@@ -238,17 +324,27 @@ impl Assignment {
238 324 }
239 325 }
240 326
241 pub fn plan_receive(current: &[Option<Assignment>], candidates: &[Assignment]) -> Vec<Option<Assignment>> {
327 pub fn plan_receive(
328 current: &[Option<Assignment>],
329 candidates: &[Assignment],
330 ) -> Vec<Option<Assignment>> {
242 331 let wanted: Vec<&Assignment> = candidates.iter().take(current.len()).collect();
243 332 let mut next: Vec<Option<Assignment>> = current
244 333 .iter()
245 334 .map(|slot| {
246 335 let held = slot.as_ref()?;
247 wanted.iter().find(|assignment| assignment.same_source(held)).map(|assignment| (*assignment).clone())
336 wanted
337 .iter()
338 .find(|assignment| assignment.same_source(held))
339 .map(|assignment| (*assignment).clone())
248 340 })
249 341 .collect();
250 342 for assignment in wanted {
251 if next.iter().flatten().any(|held| held.same_source(assignment)) {
343 if next
344 .iter()
345 .flatten()
346 .any(|held| held.same_source(assignment))
347 {
252 348 continue;
253 349 }
254 350 if let Some(free) = next.iter_mut().find(|slot| slot.is_none()) {
@@ -258,20 +354,37 @@ pub fn plan_receive(current: &[Option<Assignment>], candidates: &[Assignment]) -
258 354 next
259 355 }
260 356
261 pub fn prioritize(candidates: Vec<(String, u32)>, speaker_history: &[String], wants: Option<&[VideoWant]>) -> Vec<Assignment> {
357 pub fn prioritize(
358 candidates: Vec<(String, u32)>,
359 speaker_history: &[String],
360 wants: Option<&[VideoWant]>,
361 ) -> Vec<Assignment> {
262 362 if let Some(wants) = wants {
263 363 return wants
264 364 .iter()
265 365 .filter_map(|want| {
266 366 let (mri, source) = candidates.iter().find(|(mri, _)| *mri == want.mri)?;
267 Some(Assignment { mri: mri.clone(), source: *source, detail: want.detail })
367 Some(Assignment {
368 mri: mri.clone(),
369 source: *source,
370 detail: want.detail,
371 })
268 372 })
269 373 .collect();
270 374 }
271 let rank = |mri: &str| speaker_history.iter().position(|speaker| speaker == mri).unwrap_or(usize::MAX);
375 let rank = |mri: &str| {
376 speaker_history
377 .iter()
378 .position(|speaker| speaker == mri)
379 .unwrap_or(usize::MAX)
380 };
272 381 let mut ordered: Vec<Assignment> = candidates
273 382 .into_iter()
274 .map(|(mri, source)| Assignment { mri, source, detail: TileDetail::Stage })
383 .map(|(mri, source)| Assignment {
384 mri,
385 source,
386 detail: TileDetail::Stage,
387 })
275 388 .collect();
276 389 ordered.sort_by_key(|assignment| rank(&assignment.mri));
277 390 ordered
@@ -284,12 +397,14 @@ pub struct SourceRequest {
284 397 pub source: Option<u32>,
285 398 pub screen: bool,
286 399 pub detail: TileDetail,
400 pub quality: VideoQuality,
287 401 }
288 402
289 403 pub fn requests_for(
290 404 current: &[Option<Assignment>],
291 405 next: &[Option<Assignment>],
292 406 slots: &[ReceiveSlot],
407 quality: VideoQuality,
293 408 ) -> Vec<SourceRequest> {
294 409 slots
295 410 .iter()
@@ -300,7 +415,11 @@ pub fn requests_for(
300 415 stream_id: slot.stream_id,
301 416 source: after.as_ref().map(|assignment| assignment.source),
302 417 screen: false,
303 detail: after.as_ref().map(|assignment| assignment.detail).unwrap_or_default(),
418 detail: after
419 .as_ref()
420 .map(|assignment| assignment.detail)
421 .unwrap_or_default(),
422 quality,
304 423 })
305 424 .collect()
306 425 }
@@ -308,7 +427,11 @@ pub fn requests_for(
308 427 impl SourceRequest {
309 428 /// Body of the `applyChannelParameters` link, the signaling twin of the data-channel `sr` message.
310 429 pub fn body(&self, sequence_number: u64) -> Value {
311 let limits = if self.screen { SCREEN_REQUEST } else { self.detail.limits() };
430 let limits = if self.screen {
431 SCREEN_REQUEST
432 } else {
433 self.detail.limits(self.quality)
434 };
312 435 let control = json!({
313 436 "controlVideoStreaming": {
314 437 "sequenceNumber": sequence_number,
@@ -335,9 +458,21 @@ impl SourceRequest {
335 458 }
336 459 }
337 460
338 pub fn send_capabilities_body(width: u32, height: u32, sequence_number: u64) -> Value {
461 pub fn send_capabilities_body(
462 width: u32,
463 height: u32,
464 sequence_number: u64,
465 quality: VideoQuality,
466 ) -> Value {
467 let ceiling = quality.capture_height().max(quality.capture_width());
468 let width = width.min(ceiling);
469 let height = height.min(ceiling);
339 470 let largest_side = width.max(height);
340 let layers = if capture_macroblocks(width, height) < THREE_LAYER_MIN_FS { 2 } else { SIMULCAST_RIDS.len() };
471 let layers = if capture_macroblocks(width, height) < THREE_LAYER_MIN_FS {
472 2
473 } else {
474 SIMULCAST_RIDS.len()
475 };
341 476 let capabilities = json!({
342 477 "maxVideoSendCapabilities": {
343 478 "max-width": largest_side,
@@ -362,17 +497,24 @@ pub fn send_capabilities_body(width: u32, height: u32, sequence_number: u64) ->
362 497 #[derive(Debug, Default)]
363 498 pub struct SendCapabilityReporter {
364 499 last_size: Option<(u32, u32)>,
500 last_quality: Option<VideoQuality>,
365 501 sequence_number: u64,
366 502 }
367 503
368 504 impl SendCapabilityReporter {
369 pub fn body_for(&mut self, size: (u32, u32)) -> Option<Value> {
370 if self.last_size == Some(size) {
505 pub fn body_for(&mut self, size: (u32, u32), quality: VideoQuality) -> Option<Value> {
506 if self.last_size == Some(size) && self.last_quality == Some(quality) {
371 507 return None;
372 508 }
373 self.last_size = Some(size);
509 self.last_size.replace(size);
510 self.last_quality.replace(quality);
374 511 self.sequence_number += 1;
375 Some(send_capabilities_body(size.0, size.1, self.sequence_number))
512 Some(send_capabilities_body(
513 size.0,
514 size.1,
515 self.sequence_number,
516 quality,
517 ))
376 518 }
377 519 }
378 520
@@ -400,11 +542,20 @@ mod tests {
400 542 use super::*;
401 543
402 544 fn assignment(name: &str, source: u32) -> Assignment {
403 Assignment { mri: format!("8:orgid:{name}"), source, detail: TileDetail::Stage }
545 Assignment {
546 mri: format!("8:orgid:{name}"),
547 source,
548 detail: TileDetail::Stage,
549 }
404 550 }
405 551
406 552 fn stream(mid: &str, role: LineRole, id: Option<u32>) -> StreamLine {
407 StreamLine { mid: mid.into(), browser_mid: mid.into(), role, source_stream_id: id }
553 StreamLine {
554 mid: mid.into(),
555 browser_mid: mid.into(),
556 role,
557 source_stream_id: id,
558 }
408 559 }
409 560
410 561 #[test]
@@ -421,12 +572,23 @@ mod tests {
421 572 let table = SlotTable::from_streams(&streams);
422 573 let mids: Vec<&str> = table.people.iter().map(|slot| slot.mid.as_str()).collect();
423 574 assert_eq!(mids, vec!["2", "3", "5"]);
424 assert_eq!(table.screen, Some(ReceiveSlot { mid: "11".into(), stream_id: 207 }));
575 assert_eq!(
576 table.screen,
577 Some(ReceiveSlot {
578 mid: "11".into(),
579 stream_id: 207
580 })
581 );
425 582 }
426 583
427 584 #[test]
428 585 fn nobody_is_dropped_while_they_are_still_wanted() {
429 let held = vec![Some(assignment("a", 1)), Some(assignment("b", 2)), None, None];
586 let held = vec![
587 Some(assignment("a", 1)),
588 Some(assignment("b", 2)),
589 None,
590 None,
591 ];
430 592 let candidates = vec![assignment("c", 3), assignment("a", 1), assignment("b", 2)];
431 593 let next = plan_receive(&held, &candidates);
432 594 assert_eq!(next[0], Some(assignment("a", 1)));
@@ -437,12 +599,28 @@ mod tests {
437 599
438 600 #[test]
439 601 fn a_new_speaker_replaces_the_least_recent_person() {
440 let held: Vec<Option<Assignment>> = (1..=4).map(|index| Some(assignment(&format!("p{index}"), index))).collect();
441 let history = vec!["8:orgid:p5".to_owned(), "8:orgid:p1".to_owned(), "8:orgid:p2".to_owned(), "8:orgid:p3".to_owned()];
442 let roster = (1..=5).map(|index| (format!("8:orgid:p{index}"), index)).collect();
602 let held: Vec<Option<Assignment>> = (1..=4)
603 .map(|index| Some(assignment(&format!("p{index}"), index)))
604 .collect();
605 let history = vec![
606 "8:orgid:p5".to_owned(),
607 "8:orgid:p1".to_owned(),
608 "8:orgid:p2".to_owned(),
609 "8:orgid:p3".to_owned(),
610 ];
611 let roster = (1..=5)
612 .map(|index| (format!("8:orgid:p{index}"), index))
613 .collect();
443 614 let next = plan_receive(&held, &prioritize(roster, &history, None));
444 let names: Vec<&str> = next.iter().flatten().map(|held| held.mri.as_str()).collect();
445 assert_eq!(names, vec!["8:orgid:p1", "8:orgid:p2", "8:orgid:p3", "8:orgid:p5"]);
615 let names: Vec<&str> = next
616 .iter()
617 .flatten()
618 .map(|held| held.mri.as_str())
619 .collect();
620 assert_eq!(
621 names,
622 vec!["8:orgid:p1", "8:orgid:p2", "8:orgid:p3", "8:orgid:p5"]
623 );
446 624 }
447 625
448 626 #[test]
@@ -451,48 +629,102 @@ mod tests {
451 629 let next = plan_receive(&held, &[assignment("b", 2)]);
452 630 assert_eq!(next, vec![None, Some(assignment("b", 2))]);
453 631 let slots = vec![
454 ReceiveSlot { mid: "2".into(), stream_id: 203 },
455 ReceiveSlot { mid: "3".into(), stream_id: 204 },
632 ReceiveSlot {
633 mid: "2".into(),
634 stream_id: 203,
635 },
636 ReceiveSlot {
637 mid: "3".into(),
638 stream_id: 204,
639 },
456 640 ];
457 let requests = requests_for(&held, &next, &slots);
458 assert_eq!(requests, vec![SourceRequest { mid: "2".into(), stream_id: 203, source: None, screen: false, detail: TileDetail::Stage }]);
641 let requests = requests_for(&held, &next, &slots, VideoQuality::Auto);
642 assert_eq!(
643 requests,
644 vec![SourceRequest {
645 mid: "2".into(),
646 stream_id: 203,
647 source: None,
648 screen: false,
649 detail: TileDetail::Stage,
650 quality: VideoQuality::Auto,
651 }]
652 );
459 653 }
460 654
461 655 #[test]
462 656 fn a_source_request_wraps_the_control_message_like_the_web_client() {
463 let request = SourceRequest { mid: "3".into(), stream_id: 204, source: Some(302), screen: false, detail: TileDetail::Stage };
657 let request = SourceRequest {
658 mid: "3".into(),
659 stream_id: 204,
660 source: Some(302),
661 screen: false,
662 detail: TileDetail::Stage,
663 quality: VideoQuality::Auto,
664 };
464 665 let body = request.body(7);
465 666 let channel = &body["applyChannelParameters"]["multiChannelParameter"];
466 667 assert_eq!(channel["mids"], json!(["3"]));
467 let parameter: Value = serde_json::from_str(channel["mediaParameter"].as_str().unwrap()).unwrap();
668 let parameter: Value =
669 serde_json::from_str(channel["mediaParameter"].as_str().unwrap()).unwrap();
468 670 let info = &parameter["controlVideoStreaming"]["controlInfo"];
469 671 assert_eq!(parameter["controlVideoStreaming"]["sequenceNumber"], 7);
470 672 assert_eq!(info["sourceId"], 302);
471 673 assert_eq!(info["streamMsid"], 204);
472 assert_eq!(info["fmtParams"][0]["max-fs"], 3600);
674 assert_eq!(info["fmtParams"][0]["max-fs"], 8160);
473 675 assert_eq!(info["fmtParams"][0]["max-fps"], 3000);
676 assert_eq!(info["fmtParams"][0]["max-mbps"], 244_800);
474 677 assert_eq!(info["fmtParams"][0]["profile-level-id"], "64001f");
475 let cleared = SourceRequest { source: None, ..request.clone() }.body(8);
476 let parameter: Value =
477 serde_json::from_str(cleared["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"].as_str().unwrap()).unwrap();
478 assert_eq!(parameter["controlVideoStreaming"]["controlInfo"]["sourceId"], -1);
479 let screen = SourceRequest { screen: true, ..request }.body(9);
480 let parameter: Value =
481 serde_json::from_str(screen["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"].as_str().unwrap()).unwrap();
482 assert_eq!(parameter["controlVideoStreaming"]["controlInfo"]["fmtParams"][0]["max-fs"], 8160);
678 let cleared = SourceRequest {
679 source: None,
680 ..request.clone()
681 }
682 .body(8);
683 let parameter: Value = serde_json::from_str(
684 cleared["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"]
685 .as_str()
686 .unwrap(),
687 )
688 .unwrap();
689 assert_eq!(
690 parameter["controlVideoStreaming"]["controlInfo"]["sourceId"],
691 -1
692 );
693 let screen = SourceRequest {
694 screen: true,
695 ..request
696 }
697 .body(9);
698 let parameter: Value = serde_json::from_str(
699 screen["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"]
700 .as_str()
701 .unwrap(),
702 )
703 .unwrap();
704 assert_eq!(
705 parameter["controlVideoStreaming"]["controlInfo"]["fmtParams"][0]["max-fs"],
706 8160
707 );
483 708 }
484 709
485 710 fn want(name: &str, detail: TileDetail) -> VideoWant {
486 VideoWant { mri: format!("8:orgid:{name}"), detail }
711 VideoWant {
712 mri: format!("8:orgid:{name}"),
713 detail,
714 }
487 715 }
488 716
489 717 fn roster_of(count: u32) -> Vec<(String, u32)> {
490 (1..=count).map(|index| (format!("8:orgid:p{index}"), index)).collect()
718 (1..=count)
719 .map(|index| (format!("8:orgid:p{index}"), index))
720 .collect()
491 721 }
492 722
493 723 #[test]
494 724 fn nine_slots_hold_nine_visible_people_and_the_tenth_waits() {
495 let wants: Vec<VideoWant> = (1..=10).map(|index| want(&format!("p{index}"), TileDetail::Small)).collect();
725 let wants: Vec<VideoWant> = (1..=10)
726 .map(|index| want(&format!("p{index}"), TileDetail::Small))
727 .collect();
496 728 let candidates = prioritize(roster_of(10), &[], Some(&wants));
497 729 let next = plan_receive(&vec![None; RECEIVE_SLOTS], &candidates);
498 730 assert_eq!(next.iter().flatten().count(), 9);
@@ -503,11 +735,20 @@ mod tests {
503 735 fn people_outside_the_visible_tiles_get_no_slot() {
504 736 let wants = vec![want("p2", TileDetail::Small), want("p4", TileDetail::Small)];
505 737 let candidates = prioritize(roster_of(5), &["8:orgid:p5".to_owned()], Some(&wants));
506 let mris: Vec<&str> = candidates.iter().map(|assignment| assignment.mri.as_str()).collect();
738 let mris: Vec<&str> = candidates
739 .iter()
740 .map(|assignment| assignment.mri.as_str())
741 .collect();
507 742 assert_eq!(mris, vec!["8:orgid:p2", "8:orgid:p4"]);
508 743 let held = vec![Some(assignment("p5", 5)), None, None];
509 744 let next = plan_receive(&held, &candidates);
510 assert_eq!(next.iter().flatten().map(|held| held.mri.as_str()).collect::<Vec<_>>(), vec!["8:orgid:p2", "8:orgid:p4"]);
745 assert_eq!(
746 next.iter()
747 .flatten()
748 .map(|held| held.mri.as_str())
749 .collect::<Vec<_>>(),
750 vec!["8:orgid:p2", "8:orgid:p4"]
751 );
511 752 }
512 753
513 754 #[test]
@@ -517,13 +758,24 @@ mod tests {
517 758
518 759 #[test]
519 760 fn a_person_who_moves_to_the_stage_keeps_the_slot_and_gets_the_large_request() {
520 let small = Assignment { detail: TileDetail::Small, ..assignment("a", 1) };
761 let small = Assignment {
762 detail: TileDetail::Small,
763 ..assignment("a", 1)
764 };
521 765 let held = vec![None, Some(small), None];
522 766 let wants = vec![want("a", TileDetail::Stage)];
523 let next = plan_receive(&held, &prioritize(vec![("8:orgid:a".to_owned(), 1)], &[], Some(&wants)));
767 let next = plan_receive(
768 &held,
769 &prioritize(vec![("8:orgid:a".to_owned(), 1)], &[], Some(&wants)),
770 );
524 771 assert_eq!(next, vec![None, Some(assignment("a", 1)), None]);
525 let slots: Vec<ReceiveSlot> = (0..3).map(|index| ReceiveSlot { mid: format!("{}", index + 2), stream_id: 203 + index }).collect();
526 let requests = requests_for(&held, &next, &slots);
772 let slots: Vec<ReceiveSlot> = (0..3)
773 .map(|index| ReceiveSlot {
774 mid: format!("{}", index + 2),
775 stream_id: 203 + index,
776 })
777 .collect();
778 let requests = requests_for(&held, &next, &slots, VideoQuality::Auto);
527 779 assert_eq!(requests.len(), 1);
528 780 assert_eq!(requests[0].mid, "3");
529 781 assert_eq!(requests[0].detail, TileDetail::Stage);
@@ -532,15 +784,46 @@ mod tests {
532 784 #[test]
533 785 fn stage_and_small_tiles_ask_for_different_resolutions() {
534 786 let fmt_for = |detail| {
535 let request = SourceRequest { mid: "2".into(), stream_id: 203, source: Some(1), screen: false, detail };
787 let request = SourceRequest {
788 mid: "2".into(),
789 stream_id: 203,
790 source: Some(1),
791 screen: false,
792 detail,
793 quality: VideoQuality::Auto,
794 };
536 795 let body = request.body(1);
537 let parameter: Value =
538 serde_json::from_str(body["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"].as_str().unwrap()).unwrap();
796 let parameter: Value = serde_json::from_str(
797 body["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"]
798 .as_str()
799 .unwrap(),
800 )
801 .unwrap();
539 802 parameter["controlVideoStreaming"]["controlInfo"]["fmtParams"][0].clone()
540 803 };
541 assert_eq!(fmt_for(TileDetail::Stage)["max-fs"], 3600);
804 assert_eq!(fmt_for(TileDetail::Stage)["max-fs"], 8160);
805 assert_eq!(fmt_for(TileDetail::Stage)["max-mbps"], 244_800);
542 806 assert_eq!(fmt_for(TileDetail::Small)["max-fs"], 920);
543 807 assert_eq!(fmt_for(TileDetail::Small)["max-mbps"], 27_600);
808 let locked = SourceRequest {
809 mid: "2".into(),
810 stream_id: 203,
811 source: Some(1),
812 screen: false,
813 detail: TileDetail::Stage,
814 quality: VideoQuality::P720,
815 }
816 .body(1);
817 let parameter: Value = serde_json::from_str(
818 locked["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"]
819 .as_str()
820 .unwrap(),
821 )
822 .unwrap();
823 assert_eq!(
824 parameter["controlVideoStreaming"]["controlInfo"]["fmtParams"][0]["max-fs"],
825 3600
826 );
544 827 }
545 828
546 829 #[test]
@@ -549,7 +832,10 @@ mod tests {
549 832 MediaDescription::camera(true).wire(),
550 833 json!({"mid": "1", "direction": "sendrecv", "label": "main-video"})
551 834 );
552 assert_eq!(MediaDescription::camera(false).wire(), json!({"mid": "1", "direction": "recvonly"}));
835 assert_eq!(
836 MediaDescription::camera(false).wire(),
837 json!({"mid": "1", "direction": "recvonly"})
838 );
553 839 assert_eq!(
554 840 MediaDescription::share(true).wire(),
555 841 json!({"mid": "11", "direction": "sendrecv", "label": "applicationsharing-video"})
@@ -561,37 +847,59 @@ mod tests {
561 847 let router = VideoRouter::default();
562 848 assert_eq!(router.key_for("2"), None);
563 849 router.set("2", Some(VideoKey::Person("8:orgid:a".into())));
564 assert_eq!(router.key_for("2"), Some(VideoKey::Person("8:orgid:a".into())));
850 assert_eq!(
851 router.key_for("2"),
852 Some(VideoKey::Person("8:orgid:a".into()))
853 );
565 854 router.set("2", None);
566 855 assert_eq!(router.key_for("2"), None);
567 856 }
568 857
569 858 #[test]
570 859 fn send_capabilities_name_the_camera_mid_and_the_largest_side() {
571 let body = send_capabilities_body(1280, 720, 4);
860 let body = send_capabilities_body(1280, 720, 4, VideoQuality::Auto);
572 861 let channel = &body["applyChannelParameters"]["multiChannelParameter"];
573 862 assert_eq!(channel["mids"], json!(["1"]));
574 let parameter: Value = serde_json::from_str(channel["mediaParameter"].as_str().unwrap()).unwrap();
863 let parameter: Value =
864 serde_json::from_str(channel["mediaParameter"].as_str().unwrap()).unwrap();
575 865 assert_eq!(
576 866 parameter,
577 867 json!({"maxVideoSendCapabilities": {
578 868 "max-width": 1280, "max-height": 1280, "max-fps": 30, "max-streams": 3, "max-layers": 3, "sequence-number": 4
579 869 }})
580 870 );
581 let small: Value =
582 serde_json::from_str(send_capabilities_body(480, 270, 1)["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"].as_str().unwrap())
583 .unwrap();
871 let small: Value = serde_json::from_str(
872 send_capabilities_body(480, 270, 1, VideoQuality::Auto)
873 ["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"]
874 .as_str()
875 .unwrap(),
876 )
877 .unwrap();
584 878 assert_eq!(small["maxVideoSendCapabilities"]["max-layers"], 2);
879 let clamped: Value = serde_json::from_str(
880 send_capabilities_body(3840, 2160, 1, VideoQuality::P720)
881 ["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"]
882 .as_str()
883 .unwrap(),
884 )
885 .unwrap();
886 assert_eq!(clamped["maxVideoSendCapabilities"]["max-width"], 1280);
887 assert_eq!(clamped["maxVideoSendCapabilities"]["max-height"], 1280);
585 888 }
586 889
587 890 #[test]
588 891 fn the_reporter_skips_a_repeated_size_and_counts_sequences() {
589 892 let mut reporter = SendCapabilityReporter::default();
590 assert!(reporter.body_for((1280, 720)).is_some());
591 assert!(reporter.body_for((1280, 720)).is_none());
592 let body = reporter.body_for((640, 480)).unwrap();
593 let parameter: Value =
594 serde_json::from_str(body["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"].as_str().unwrap()).unwrap();
893 assert!(reporter.body_for((1280, 720), VideoQuality::Auto).is_some());
894 assert!(reporter.body_for((1280, 720), VideoQuality::Auto).is_none());
895 let body = reporter.body_for((640, 480), VideoQuality::Auto).unwrap();
896 let parameter: Value = serde_json::from_str(
897 body["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"]
898 .as_str()
899 .unwrap(),
900 )
901 .unwrap();
595 902 assert_eq!(parameter["maxVideoSendCapabilities"]["sequence-number"], 2);
903 assert!(reporter.body_for((640, 480), VideoQuality::P720).is_some());
596 904 }
597 905 }
@@ -1,17 +1,18 @@
1use std::collections::HashMap;
1use std::collections::HashMap;
2use std::sync::{Arc, Mutex};
2use std::sync::{Arc, Mutex};
3
3
4use libwebrtc::MediaType;
4use libwebrtc::peer_connection::PeerConnection;
5use libwebrtc::peer_connection::PeerConnection;
5use libwebrtc::peer_connection_factory::PeerConnectionFactory;
6use libwebrtc::peer_connection_factory::PeerConnectionFactory;
6use libwebrtc::rtp_parameters::{RtpCodecCapability, RtpEncodingParameters};
7use libwebrtc::rtp_parameters::{RtpCodecCapability, RtpEncodingParameters};
7use libwebrtc::rtp_transceiver::{RtpTransceiver, RtpTransceiverDirection, RtpTransceiverInit};
8use libwebrtc::rtp_transceiver::{RtpTransceiver, RtpTransceiverDirection, RtpTransceiverInit};
8use libwebrtc::MediaType;
9use serde_json::{Value, json};
9use serde_json::{Value, json};
10
10
11use crate::error::{Error, Result};
11use crate::error::{Error, Result};
12use crate::send_control::capture_macroblocks;
13use crate::sdp::{LineRole, OfferPlan, StreamLine};
12use crate::sdp::{LineRole, OfferPlan, StreamLine};
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,9 +26,27 @@ 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 { max_fs: 3600, max_fps: 3000, max_mbps: 108_000 };
29const STAGE_720_REQUEST: ReceiveLimits = ReceiveLimits {
29const SMALL_REQUEST: ReceiveLimits = ReceiveLimits { max_fs: 920, max_fps: 3000, max_mbps: 27_600 };
30 max_fs: 3600,
30const SCREEN_REQUEST: ReceiveLimits = ReceiveLimits { max_fs: 8160, max_fps: 1500, max_mbps: 135_000 };
31 max_fps: 3000,
32 max_mbps: 108_000,
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};
40const SMALL_REQUEST: ReceiveLimits = ReceiveLimits {
41 max_fs: 920,
42 max_fps: 3000,
43 max_mbps: 27_600,
44};
45const SCREEN_REQUEST: ReceiveLimits = ReceiveLimits {
46 max_fs: 8160,
47 max_fps: 1500,
48 max_mbps: 135_000,
49};
31const SUBSCRIBE_PROFILE: &str = "64001f";
50const SUBSCRIBE_PROFILE: &str = "64001f";
32const SIMULCAST_RIDS: [&str; 3] = ["1", "2", "3"];
51const SIMULCAST_RIDS: [&str; 3] = ["1", "2", "3"];
33const SIMULCAST_START_SCALES: [f64; 3] = [4.0, 2.0, 1.0];
52const SIMULCAST_START_SCALES: [f64; 3] = [4.0, 2.0, 1.0];
@@ -43,9 +62,12 @@ pub enum TileDetail {
43}
62}
44
63
45impl TileDetail {
64impl TileDetail {
46 fn limits(self) -> ReceiveLimits {
65 fn limits(self, quality: VideoQuality) -> ReceiveLimits {
47 match self {
66 match self {
48 TileDetail::Stage => STAGE_REQUEST,
67 TileDetail::Stage => match quality {
68 VideoQuality::P720 => STAGE_720_REQUEST,
69 VideoQuality::Auto | VideoQuality::P1080 => STAGE_1080_REQUEST,
70 },
49 TileDetail::Small => SMALL_REQUEST,
71 TileDetail::Small => SMALL_REQUEST,
50 }
72 }
51 }
73 }
@@ -68,7 +90,6 @@ pub fn offer_plan() -> OfferPlan {
68 OfferPlan {
90 OfferPlan {
69 screen_share_mids: vec![SHARE_MID.to_owned()],
91 screen_share_mids: vec![SHARE_MID.to_owned()],
70 gallery_mids: Vec::new(),
92 gallery_mids: Vec::new(),
71 fold_groups: Vec::new(),
72 }
93 }
73}
94}
74
95
@@ -76,7 +97,6 @@ pub fn one_to_one_plan() -> OfferPlan {
76 OfferPlan {
97 OfferPlan {
77 screen_share_mids: vec![ONE_TO_ONE_SHARE_MID.to_owned()],
98 screen_share_mids: vec![ONE_TO_ONE_SHARE_MID.to_owned()],
78 gallery_mids: Vec::new(),
99 gallery_mids: Vec::new(),
79 fold_groups: Vec::new(),
80 }
100 }
81}
101}
82
102
@@ -131,28 +151,83 @@ fn simulcast_encodings() -> Vec<RtpEncodingParameters> {
131 .collect()
151 .collect()
132}
152}
133
153
134pub fn add_video_lines(peer: &PeerConnection, factory: &PeerConnectionFactory) -> Result<VideoLines> {
154pub fn add_video_lines(
155 peer: &PeerConnection,
156 factory: &PeerConnectionFactory,
157) -> Result<VideoLines> {
135 let sending = h264_only(factory.get_rtp_sender_capabilities(MediaType::Video).codecs);
158 let sending = h264_only(factory.get_rtp_sender_capabilities(MediaType::Video).codecs);
136 let receiving = h264_only(factory.get_rtp_receiver_capabilities(MediaType::Video).codecs);
159 let receiving = h264_only(
137 let camera = add_line(peer, RtpTransceiverDirection::SendRecv, Some(CAMERA_STREAM), sending.clone(), simulcast_encodings())?;
160 factory
161 .get_rtp_receiver_capabilities(MediaType::Video)
162 .codecs,
163 );
164 let camera = add_line(
165 peer,
166 RtpTransceiverDirection::SendRecv,
167 Some(CAMERA_STREAM),
168 sending.clone(),
169 simulcast_encodings(),
170 )?;
138 for _ in 0..RECEIVE_SLOTS {
171 for _ in 0..RECEIVE_SLOTS {
139 add_line(peer, RtpTransceiverDirection::RecvOnly, None, receiving.clone(), Vec::new())?;
172 add_line(
140 }
173 peer,
141 let share = add_line(peer, RtpTransceiverDirection::SendRecv, Some(SCREEN_STREAM), sending, Vec::new())?;
174 RtpTransceiverDirection::RecvOnly,
142 Ok(VideoLines { camera, share: Some(share) })
175 None,
176 receiving.clone(),
177 Vec::new(),
178 )?;
179 }
180 let share = add_line(
181 peer,
182 RtpTransceiverDirection::SendRecv,
183 Some(SCREEN_STREAM),
184 sending,
185 Vec::new(),
186 )?;
187 Ok(VideoLines {
188 camera,
189 share: Some(share),
190 })
143}
191}
144
192
145/// A sharing line added to a running direct call, the way Teams adds it before its share offer.
193/// A sharing line added to a running direct call, the way Teams adds it before its share offer.
146pub fn add_share_line(peer: &PeerConnection, factory: &PeerConnectionFactory) -> Result<RtpTransceiver> {
194pub fn add_share_line(
195 peer: &PeerConnection,
196 factory: &PeerConnectionFactory,
197) -> Result<RtpTransceiver> {
147 let sending = h264_only(factory.get_rtp_sender_capabilities(MediaType::Video).codecs);
198 let sending = h264_only(factory.get_rtp_sender_capabilities(MediaType::Video).codecs);
148 add_line(peer, RtpTransceiverDirection::SendRecv, Some(SCREEN_STREAM), sending, Vec::new())
199 add_line(
200 peer,
201 RtpTransceiverDirection::SendRecv,
202 Some(SCREEN_STREAM),
203 sending,
204 Vec::new(),
205 )
149}
206}
150
207
151pub fn add_one_to_one_lines(peer: &PeerConnection, factory: &PeerConnectionFactory) -> Result<VideoLines> {
208pub fn add_one_to_one_lines(
209 peer: &PeerConnection,
210 factory: &PeerConnectionFactory,
211) -> Result<VideoLines> {
152 let sending = h264_only(factory.get_rtp_sender_capabilities(MediaType::Video).codecs);
212 let sending = h264_only(factory.get_rtp_sender_capabilities(MediaType::Video).codecs);
153 let camera = add_line(peer, RtpTransceiverDirection::SendRecv, Some(CAMERA_STREAM), sending.clone(), Vec::new())?;
213 let camera = add_line(
154 let share = add_line(peer, RtpTransceiverDirection::SendRecv, Some(SCREEN_STREAM), sending, Vec::new())?;
214 peer,
155 Ok(VideoLines { camera, share: Some(share) })
215 RtpTransceiverDirection::SendRecv,
216 Some(CAMERA_STREAM),
217 sending.clone(),
218 Vec::new(),
219 )?;
220 let share = add_line(
221 peer,
222 RtpTransceiverDirection::SendRecv,
223 Some(SCREEN_STREAM),
224 sending,
225 Vec::new(),
226 )?;
227 Ok(VideoLines {
228 camera,
229 share: Some(share),
230 })
156}
231}
157
232
158/// Per-line direction told to the mixer through `updateMediaDescriptions`; no SDP renegotiation.
233/// Per-line direction told to the mixer through `updateMediaDescriptions`; no SDP renegotiation.
@@ -174,9 +249,17 @@ impl MediaDescription {
174
249
175 fn line(mid: &'static str, sending: bool, label: &'static str) -> Self {
250 fn line(mid: &'static str, sending: bool, label: &'static str) -> Self {
176 if sending {
251 if sending {
177 MediaDescription { mid, direction: "sendrecv", label: Some(label) }
252 MediaDescription {
253 mid,
254 direction: "sendrecv",
255 label: Some(label),
256 }
178 } else {
257 } else {
179 MediaDescription { mid, direction: "recvonly", label: None }
258 MediaDescription {
259 mid,
260 direction: "recvonly",
261 label: None,
262 }
180 }
263 }
181 }
264 }
182
265
@@ -216,7 +299,10 @@ impl SlotTable {
216 .filter_map(slot)
299 .filter_map(slot)
217 .take(RECEIVE_SLOTS)
300 .take(RECEIVE_SLOTS)
218 .collect();
301 .collect();
219 let screen = streams.iter().find(|stream| stream.role == LineRole::ScreenShare).and_then(slot);
302 let screen = streams
303 .iter()
304 .find(|stream| stream.role == LineRole::ScreenShare)
305 .and_then(slot);
220 SlotTable { people, screen }
306 SlotTable { people, screen }
221 }
307 }
222
308
@@ -238,17 +324,27 @@ impl Assignment {
238 }
324 }
239}
325}
240
326
241pub fn plan_receive(current: &[Option<Assignment>], candidates: &[Assignment]) -> Vec<Option<Assignment>> {
327pub fn plan_receive(
328 current: &[Option<Assignment>],
329 candidates: &[Assignment],
330) -> Vec<Option<Assignment>> {
242 let wanted: Vec<&Assignment> = candidates.iter().take(current.len()).collect();
331 let wanted: Vec<&Assignment> = candidates.iter().take(current.len()).collect();
243 let mut next: Vec<Option<Assignment>> = current
332 let mut next: Vec<Option<Assignment>> = current
244 .iter()
333 .iter()
245 .map(|slot| {
334 .map(|slot| {
246 let held = slot.as_ref()?;
335 let held = slot.as_ref()?;
247 wanted.iter().find(|assignment| assignment.same_source(held)).map(|assignment| (*assignment).clone())
336 wanted
337 .iter()
338 .find(|assignment| assignment.same_source(held))
339 .map(|assignment| (*assignment).clone())
248 })
340 })
249 .collect();
341 .collect();
250 for assignment in wanted {
342 for assignment in wanted {
251 if next.iter().flatten().any(|held| held.same_source(assignment)) {
343 if next
344 .iter()
345 .flatten()
346 .any(|held| held.same_source(assignment))
347 {
252 continue;
348 continue;
253 }
349 }
254 if let Some(free) = next.iter_mut().find(|slot| slot.is_none()) {
350 if let Some(free) = next.iter_mut().find(|slot| slot.is_none()) {
@@ -258,20 +354,37 @@ pub fn plan_receive(current: &[Option<Assignment>], candidates: &[Assignment]) -
258 next
354 next
259}
355}
260
356
261pub fn prioritize(candidates: Vec<(String, u32)>, speaker_history: &[String], wants: Option<&[VideoWant]>) -> Vec<Assignment> {
357pub fn prioritize(
358 candidates: Vec<(String, u32)>,
359 speaker_history: &[String],
360 wants: Option<&[VideoWant]>,
361) -> Vec<Assignment> {
262 if let Some(wants) = wants {
362 if let Some(wants) = wants {
263 return wants
363 return wants
264 .iter()
364 .iter()
265 .filter_map(|want| {
365 .filter_map(|want| {
266 let (mri, source) = candidates.iter().find(|(mri, _)| *mri == want.mri)?;
366 let (mri, source) = candidates.iter().find(|(mri, _)| *mri == want.mri)?;
267 Some(Assignment { mri: mri.clone(), source: *source, detail: want.detail })
367 Some(Assignment {
368 mri: mri.clone(),
369 source: *source,
370 detail: want.detail,
371 })
268 })
372 })
269 .collect();
373 .collect();
270 }
374 }
271 let rank = |mri: &str| speaker_history.iter().position(|speaker| speaker == mri).unwrap_or(usize::MAX);
375 let rank = |mri: &str| {
376 speaker_history
377 .iter()
378 .position(|speaker| speaker == mri)
379 .unwrap_or(usize::MAX)
380 };
272 let mut ordered: Vec<Assignment> = candidates
381 let mut ordered: Vec<Assignment> = candidates
273 .into_iter()
382 .into_iter()
274 .map(|(mri, source)| Assignment { mri, source, detail: TileDetail::Stage })
383 .map(|(mri, source)| Assignment {
384 mri,
385 source,
386 detail: TileDetail::Stage,
387 })
275 .collect();
388 .collect();
276 ordered.sort_by_key(|assignment| rank(&assignment.mri));
389 ordered.sort_by_key(|assignment| rank(&assignment.mri));
277 ordered
390 ordered
@@ -284,12 +397,14 @@ pub struct SourceRequest {
284 pub source: Option<u32>,
397 pub source: Option<u32>,
285 pub screen: bool,
398 pub screen: bool,
286 pub detail: TileDetail,
399 pub detail: TileDetail,
400 pub quality: VideoQuality,
287}
401}
288
402
289pub fn requests_for(
403pub fn requests_for(
290 current: &[Option<Assignment>],
404 current: &[Option<Assignment>],
291 next: &[Option<Assignment>],
405 next: &[Option<Assignment>],
292 slots: &[ReceiveSlot],
406 slots: &[ReceiveSlot],
407 quality: VideoQuality,
293) -> Vec<SourceRequest> {
408) -> Vec<SourceRequest> {
294 slots
409 slots
295 .iter()
410 .iter()
@@ -300,7 +415,11 @@ pub fn requests_for(
300 stream_id: slot.stream_id,
415 stream_id: slot.stream_id,
301 source: after.as_ref().map(|assignment| assignment.source),
416 source: after.as_ref().map(|assignment| assignment.source),
302 screen: false,
417 screen: false,
303 detail: after.as_ref().map(|assignment| assignment.detail).unwrap_or_default(),
418 detail: after
419 .as_ref()
420 .map(|assignment| assignment.detail)
421 .unwrap_or_default(),
422 quality,
304 })
423 })
305 .collect()
424 .collect()
306}
425}
@@ -308,7 +427,11 @@ pub fn requests_for(
308impl SourceRequest {
427impl SourceRequest {
309 /// Body of the `applyChannelParameters` link, the signaling twin of the data-channel `sr` message.
428 /// Body of the `applyChannelParameters` link, the signaling twin of the data-channel `sr` message.
310 pub fn body(&self, sequence_number: u64) -> Value {
429 pub fn body(&self, sequence_number: u64) -> Value {
311 let limits = if self.screen { SCREEN_REQUEST } else { self.detail.limits() };
430 let limits = if self.screen {
431 SCREEN_REQUEST
432 } else {
433 self.detail.limits(self.quality)
434 };
312 let control = json!({
435 let control = json!({
313 "controlVideoStreaming": {
436 "controlVideoStreaming": {
314 "sequenceNumber": sequence_number,
437 "sequenceNumber": sequence_number,
@@ -335,9 +458,21 @@ impl SourceRequest {
335 }
458 }
336}
459}
337
460
338pub fn send_capabilities_body(width: u32, height: u32, sequence_number: u64) -> Value {
461pub fn send_capabilities_body(
462 width: u32,
463 height: u32,
464 sequence_number: u64,
465 quality: VideoQuality,
466) -> Value {
467 let ceiling = quality.capture_height().max(quality.capture_width());
468 let width = width.min(ceiling);
469 let height = height.min(ceiling);
339 let largest_side = width.max(height);
470 let largest_side = width.max(height);
340 let layers = if capture_macroblocks(width, height) < THREE_LAYER_MIN_FS { 2 } else { SIMULCAST_RIDS.len() };
471 let layers = if capture_macroblocks(width, height) < THREE_LAYER_MIN_FS {
472 2
473 } else {
474 SIMULCAST_RIDS.len()
475 };
341 let capabilities = json!({
476 let capabilities = json!({
342 "maxVideoSendCapabilities": {
477 "maxVideoSendCapabilities": {
343 "max-width": largest_side,
478 "max-width": largest_side,
@@ -362,17 +497,24 @@ pub fn send_capabilities_body(width: u32, height: u32, sequence_number: u64) ->
362#[derive(Debug, Default)]
497#[derive(Debug, Default)]
363pub struct SendCapabilityReporter {
498pub struct SendCapabilityReporter {
364 last_size: Option<(u32, u32)>,
499 last_size: Option<(u32, u32)>,
500 last_quality: Option<VideoQuality>,
365 sequence_number: u64,
501 sequence_number: u64,
366}
502}
367
503
368impl SendCapabilityReporter {
504impl SendCapabilityReporter {
369 pub fn body_for(&mut self, size: (u32, u32)) -> Option<Value> {
505 pub fn body_for(&mut self, size: (u32, u32), quality: VideoQuality) -> Option<Value> {
370 if self.last_size == Some(size) {
506 if self.last_size == Some(size) && self.last_quality == Some(quality) {
371 return None;
507 return None;
372 }
508 }
373 self.last_size = Some(size);
509 self.last_size.replace(size);
510 self.last_quality.replace(quality);
374 self.sequence_number += 1;
511 self.sequence_number += 1;
375 Some(send_capabilities_body(size.0, size.1, self.sequence_number))
512 Some(send_capabilities_body(
513 size.0,
514 size.1,
515 self.sequence_number,
516 quality,
517 ))
376 }
518 }
377}
519}
378
520
@@ -400,11 +542,20 @@ mod tests {
400 use super::*;
542 use super::*;
401
543
402 fn assignment(name: &str, source: u32) -> Assignment {
544 fn assignment(name: &str, source: u32) -> Assignment {
403 Assignment { mri: format!("8:orgid:{name}"), source, detail: TileDetail::Stage }
545 Assignment {
546 mri: format!("8:orgid:{name}"),
547 source,
548 detail: TileDetail::Stage,
549 }
404 }
550 }
405
551
406 fn stream(mid: &str, role: LineRole, id: Option<u32>) -> StreamLine {
552 fn stream(mid: &str, role: LineRole, id: Option<u32>) -> StreamLine {
407 StreamLine { mid: mid.into(), browser_mid: mid.into(), role, source_stream_id: id }
553 StreamLine {
554 mid: mid.into(),
555 browser_mid: mid.into(),
556 role,
557 source_stream_id: id,
558 }
408 }
559 }
409
560
410 #[test]
561 #[test]
@@ -421,12 +572,23 @@ mod tests {
421 let table = SlotTable::from_streams(&streams);
572 let table = SlotTable::from_streams(&streams);
422 let mids: Vec<&str> = table.people.iter().map(|slot| slot.mid.as_str()).collect();
573 let mids: Vec<&str> = table.people.iter().map(|slot| slot.mid.as_str()).collect();
423 assert_eq!(mids, vec!["2", "3", "5"]);
574 assert_eq!(mids, vec!["2", "3", "5"]);
424 assert_eq!(table.screen, Some(ReceiveSlot { mid: "11".into(), stream_id: 207 }));
575 assert_eq!(
576 table.screen,
577 Some(ReceiveSlot {
578 mid: "11".into(),
579 stream_id: 207
580 })
581 );
425 }
582 }
426
583
427 #[test]
584 #[test]
428 fn nobody_is_dropped_while_they_are_still_wanted() {
585 fn nobody_is_dropped_while_they_are_still_wanted() {
429 let held = vec![Some(assignment("a", 1)), Some(assignment("b", 2)), None, None];
586 let held = vec![
587 Some(assignment("a", 1)),
588 Some(assignment("b", 2)),
589 None,
590 None,
591 ];
430 let candidates = vec![assignment("c", 3), assignment("a", 1), assignment("b", 2)];
592 let candidates = vec![assignment("c", 3), assignment("a", 1), assignment("b", 2)];
431 let next = plan_receive(&held, &candidates);
593 let next = plan_receive(&held, &candidates);
432 assert_eq!(next[0], Some(assignment("a", 1)));
594 assert_eq!(next[0], Some(assignment("a", 1)));
@@ -437,12 +599,28 @@ mod tests {
437
599
438 #[test]
600 #[test]
439 fn a_new_speaker_replaces_the_least_recent_person() {
601 fn a_new_speaker_replaces_the_least_recent_person() {
440 let held: Vec<Option<Assignment>> = (1..=4).map(|index| Some(assignment(&format!("p{index}"), index))).collect();
602 let held: Vec<Option<Assignment>> = (1..=4)
441 let history = vec!["8:orgid:p5".to_owned(), "8:orgid:p1".to_owned(), "8:orgid:p2".to_owned(), "8:orgid:p3".to_owned()];
603 .map(|index| Some(assignment(&format!("p{index}"), index)))
442 let roster = (1..=5).map(|index| (format!("8:orgid:p{index}"), index)).collect();
604 .collect();
605 let history = vec![
606 "8:orgid:p5".to_owned(),
607 "8:orgid:p1".to_owned(),
608 "8:orgid:p2".to_owned(),
609 "8:orgid:p3".to_owned(),
610 ];
611 let roster = (1..=5)
612 .map(|index| (format!("8:orgid:p{index}"), index))
613 .collect();
443 let next = plan_receive(&held, &prioritize(roster, &history, None));
614 let next = plan_receive(&held, &prioritize(roster, &history, None));
444 let names: Vec<&str> = next.iter().flatten().map(|held| held.mri.as_str()).collect();
615 let names: Vec<&str> = next
445 assert_eq!(names, vec!["8:orgid:p1", "8:orgid:p2", "8:orgid:p3", "8:orgid:p5"]);
616 .iter()
617 .flatten()
618 .map(|held| held.mri.as_str())
619 .collect();
620 assert_eq!(
621 names,
622 vec!["8:orgid:p1", "8:orgid:p2", "8:orgid:p3", "8:orgid:p5"]
623 );
446 }
624 }
447
625
448 #[test]
626 #[test]
@@ -451,48 +629,102 @@ mod tests {
451 let next = plan_receive(&held, &[assignment("b", 2)]);
629 let next = plan_receive(&held, &[assignment("b", 2)]);
452 assert_eq!(next, vec![None, Some(assignment("b", 2))]);
630 assert_eq!(next, vec![None, Some(assignment("b", 2))]);
453 let slots = vec![
631 let slots = vec![
454 ReceiveSlot { mid: "2".into(), stream_id: 203 },
632 ReceiveSlot {
455 ReceiveSlot { mid: "3".into(), stream_id: 204 },
633 mid: "2".into(),
634 stream_id: 203,
635 },
636 ReceiveSlot {
637 mid: "3".into(),
638 stream_id: 204,
639 },
456 ];
640 ];
457 let requests = requests_for(&held, &next, &slots);
641 let requests = requests_for(&held, &next, &slots, VideoQuality::Auto);
458 assert_eq!(requests, vec![SourceRequest { mid: "2".into(), stream_id: 203, source: None, screen: false, detail: TileDetail::Stage }]);
642 assert_eq!(
643 requests,
644 vec![SourceRequest {
645 mid: "2".into(),
646 stream_id: 203,
647 source: None,
648 screen: false,
649 detail: TileDetail::Stage,
650 quality: VideoQuality::Auto,
651 }]
652 );
459 }
653 }
460
654
461 #[test]
655 #[test]
462 fn a_source_request_wraps_the_control_message_like_the_web_client() {
656 fn a_source_request_wraps_the_control_message_like_the_web_client() {
463 let request = SourceRequest { mid: "3".into(), stream_id: 204, source: Some(302), screen: false, detail: TileDetail::Stage };
657 let request = SourceRequest {
658 mid: "3".into(),
659 stream_id: 204,
660 source: Some(302),
661 screen: false,
662 detail: TileDetail::Stage,
663 quality: VideoQuality::Auto,
664 };
464 let body = request.body(7);
665 let body = request.body(7);
465 let channel = &body["applyChannelParameters"]["multiChannelParameter"];
666 let channel = &body["applyChannelParameters"]["multiChannelParameter"];
466 assert_eq!(channel["mids"], json!(["3"]));
667 assert_eq!(channel["mids"], json!(["3"]));
467 let parameter: Value = serde_json::from_str(channel["mediaParameter"].as_str().unwrap()).unwrap();
668 let parameter: Value =
669 serde_json::from_str(channel["mediaParameter"].as_str().unwrap()).unwrap();
468 let info = &parameter["controlVideoStreaming"]["controlInfo"];
670 let info = &parameter["controlVideoStreaming"]["controlInfo"];
469 assert_eq!(parameter["controlVideoStreaming"]["sequenceNumber"], 7);
671 assert_eq!(parameter["controlVideoStreaming"]["sequenceNumber"], 7);
470 assert_eq!(info["sourceId"], 302);
672 assert_eq!(info["sourceId"], 302);
471 assert_eq!(info["streamMsid"], 204);
673 assert_eq!(info["streamMsid"], 204);
472 assert_eq!(info["fmtParams"][0]["max-fs"], 3600);
674 assert_eq!(info["fmtParams"][0]["max-fs"], 8160);
473 assert_eq!(info["fmtParams"][0]["max-fps"], 3000);
675 assert_eq!(info["fmtParams"][0]["max-fps"], 3000);
676 assert_eq!(info["fmtParams"][0]["max-mbps"], 244_800);
474 assert_eq!(info["fmtParams"][0]["profile-level-id"], "64001f");
677 assert_eq!(info["fmtParams"][0]["profile-level-id"], "64001f");
475 let cleared = SourceRequest { source: None, ..request.clone() }.body(8);
678 let cleared = SourceRequest {
476 let parameter: Value =
679 source: None,
477 serde_json::from_str(cleared["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"].as_str().unwrap()).unwrap();
680 ..request.clone()
478 assert_eq!(parameter["controlVideoStreaming"]["controlInfo"]["sourceId"], -1);
681 }
479 let screen = SourceRequest { screen: true, ..request }.body(9);
682 .body(8);
480 let parameter: Value =
683 let parameter: Value = serde_json::from_str(
481 serde_json::from_str(screen["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"].as_str().unwrap()).unwrap();
684 cleared["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"]
482 assert_eq!(parameter["controlVideoStreaming"]["controlInfo"]["fmtParams"][0]["max-fs"], 8160);
685 .as_str()
686 .unwrap(),
687 )
688 .unwrap();
689 assert_eq!(
690 parameter["controlVideoStreaming"]["controlInfo"]["sourceId"],
691 -1
692 );
693 let screen = SourceRequest {
694 screen: true,
695 ..request
696 }
697 .body(9);
698 let parameter: Value = serde_json::from_str(
699 screen["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"]
700 .as_str()
701 .unwrap(),
702 )
703 .unwrap();
704 assert_eq!(
705 parameter["controlVideoStreaming"]["controlInfo"]["fmtParams"][0]["max-fs"],
706 8160
707 );
483 }
708 }
484
709
485 fn want(name: &str, detail: TileDetail) -> VideoWant {
710 fn want(name: &str, detail: TileDetail) -> VideoWant {
486 VideoWant { mri: format!("8:orgid:{name}"), detail }
711 VideoWant {
712 mri: format!("8:orgid:{name}"),
713 detail,
714 }
487 }
715 }
488
716
489 fn roster_of(count: u32) -> Vec<(String, u32)> {
717 fn roster_of(count: u32) -> Vec<(String, u32)> {
490 (1..=count).map(|index| (format!("8:orgid:p{index}"), index)).collect()
718 (1..=count)
719 .map(|index| (format!("8:orgid:p{index}"), index))
720 .collect()
491 }
721 }
492
722
493 #[test]
723 #[test]
494 fn nine_slots_hold_nine_visible_people_and_the_tenth_waits() {
724 fn nine_slots_hold_nine_visible_people_and_the_tenth_waits() {
495 let wants: Vec<VideoWant> = (1..=10).map(|index| want(&format!("p{index}"), TileDetail::Small)).collect();
725 let wants: Vec<VideoWant> = (1..=10)
726 .map(|index| want(&format!("p{index}"), TileDetail::Small))
727 .collect();
496 let candidates = prioritize(roster_of(10), &[], Some(&wants));
728 let candidates = prioritize(roster_of(10), &[], Some(&wants));
497 let next = plan_receive(&vec![None; RECEIVE_SLOTS], &candidates);
729 let next = plan_receive(&vec![None; RECEIVE_SLOTS], &candidates);
498 assert_eq!(next.iter().flatten().count(), 9);
730 assert_eq!(next.iter().flatten().count(), 9);
@@ -503,11 +735,20 @@ mod tests {
503 fn people_outside_the_visible_tiles_get_no_slot() {
735 fn people_outside_the_visible_tiles_get_no_slot() {
504 let wants = vec![want("p2", TileDetail::Small), want("p4", TileDetail::Small)];
736 let wants = vec![want("p2", TileDetail::Small), want("p4", TileDetail::Small)];
505 let candidates = prioritize(roster_of(5), &["8:orgid:p5".to_owned()], Some(&wants));
737 let candidates = prioritize(roster_of(5), &["8:orgid:p5".to_owned()], Some(&wants));
506 let mris: Vec<&str> = candidates.iter().map(|assignment| assignment.mri.as_str()).collect();
738 let mris: Vec<&str> = candidates
739 .iter()
740 .map(|assignment| assignment.mri.as_str())
741 .collect();
507 assert_eq!(mris, vec!["8:orgid:p2", "8:orgid:p4"]);
742 assert_eq!(mris, vec!["8:orgid:p2", "8:orgid:p4"]);
508 let held = vec![Some(assignment("p5", 5)), None, None];
743 let held = vec![Some(assignment("p5", 5)), None, None];
509 let next = plan_receive(&held, &candidates);
744 let next = plan_receive(&held, &candidates);
510 assert_eq!(next.iter().flatten().map(|held| held.mri.as_str()).collect::<Vec<_>>(), vec!["8:orgid:p2", "8:orgid:p4"]);
745 assert_eq!(
746 next.iter()
747 .flatten()
748 .map(|held| held.mri.as_str())
749 .collect::<Vec<_>>(),
750 vec!["8:orgid:p2", "8:orgid:p4"]
751 );
511 }
752 }
512
753
513 #[test]
754 #[test]
@@ -517,13 +758,24 @@ mod tests {
517
758
518 #[test]
759 #[test]
519 fn a_person_who_moves_to_the_stage_keeps_the_slot_and_gets_the_large_request() {
760 fn a_person_who_moves_to_the_stage_keeps_the_slot_and_gets_the_large_request() {
520 let small = Assignment { detail: TileDetail::Small, ..assignment("a", 1) };
761 let small = Assignment {
762 detail: TileDetail::Small,
763 ..assignment("a", 1)
764 };
521 let held = vec![None, Some(small), None];
765 let held = vec![None, Some(small), None];
522 let wants = vec![want("a", TileDetail::Stage)];
766 let wants = vec![want("a", TileDetail::Stage)];
523 let next = plan_receive(&held, &prioritize(vec![("8:orgid:a".to_owned(), 1)], &[], Some(&wants)));
767 let next = plan_receive(
768 &held,
769 &prioritize(vec![("8:orgid:a".to_owned(), 1)], &[], Some(&wants)),
770 );
524 assert_eq!(next, vec![None, Some(assignment("a", 1)), None]);
771 assert_eq!(next, vec![None, Some(assignment("a", 1)), None]);
525 let slots: Vec<ReceiveSlot> = (0..3).map(|index| ReceiveSlot { mid: format!("{}", index + 2), stream_id: 203 + index }).collect();
772 let slots: Vec<ReceiveSlot> = (0..3)
526 let requests = requests_for(&held, &next, &slots);
773 .map(|index| ReceiveSlot {
774 mid: format!("{}", index + 2),
775 stream_id: 203 + index,
776 })
777 .collect();
778 let requests = requests_for(&held, &next, &slots, VideoQuality::Auto);
527 assert_eq!(requests.len(), 1);
779 assert_eq!(requests.len(), 1);
528 assert_eq!(requests[0].mid, "3");
780 assert_eq!(requests[0].mid, "3");
529 assert_eq!(requests[0].detail, TileDetail::Stage);
781 assert_eq!(requests[0].detail, TileDetail::Stage);
@@ -532,15 +784,46 @@ mod tests {
532 #[test]
784 #[test]
533 fn stage_and_small_tiles_ask_for_different_resolutions() {
785 fn stage_and_small_tiles_ask_for_different_resolutions() {
534 let fmt_for = |detail| {
786 let fmt_for = |detail| {
535 let request = SourceRequest { mid: "2".into(), stream_id: 203, source: Some(1), screen: false, detail };
787 let request = SourceRequest {
788 mid: "2".into(),
789 stream_id: 203,
790 source: Some(1),
791 screen: false,
792 detail,
793 quality: VideoQuality::Auto,
794 };
536 let body = request.body(1);
795 let body = request.body(1);
537 let parameter: Value =
796 let parameter: Value = serde_json::from_str(
538 serde_json::from_str(body["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"].as_str().unwrap()).unwrap();
797 body["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"]
798 .as_str()
799 .unwrap(),
800 )
801 .unwrap();
539 parameter["controlVideoStreaming"]["controlInfo"]["fmtParams"][0].clone()
802 parameter["controlVideoStreaming"]["controlInfo"]["fmtParams"][0].clone()
540 };
803 };
541 assert_eq!(fmt_for(TileDetail::Stage)["max-fs"], 3600);
804 assert_eq!(fmt_for(TileDetail::Stage)["max-fs"], 8160);
805 assert_eq!(fmt_for(TileDetail::Stage)["max-mbps"], 244_800);
542 assert_eq!(fmt_for(TileDetail::Small)["max-fs"], 920);
806 assert_eq!(fmt_for(TileDetail::Small)["max-fs"], 920);
543 assert_eq!(fmt_for(TileDetail::Small)["max-mbps"], 27_600);
807 assert_eq!(fmt_for(TileDetail::Small)["max-mbps"], 27_600);
808 let locked = SourceRequest {
809 mid: "2".into(),
810 stream_id: 203,
811 source: Some(1),
812 screen: false,
813 detail: TileDetail::Stage,
814 quality: VideoQuality::P720,
815 }
816 .body(1);
817 let parameter: Value = serde_json::from_str(
818 locked["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"]
819 .as_str()
820 .unwrap(),
821 )
822 .unwrap();
823 assert_eq!(
824 parameter["controlVideoStreaming"]["controlInfo"]["fmtParams"][0]["max-fs"],
825 3600
826 );
544 }
827 }
545
828
546 #[test]
829 #[test]
@@ -549,7 +832,10 @@ mod tests {
549 MediaDescription::camera(true).wire(),
832 MediaDescription::camera(true).wire(),
550 json!({"mid": "1", "direction": "sendrecv", "label": "main-video"})
833 json!({"mid": "1", "direction": "sendrecv", "label": "main-video"})
551 );
834 );
552 assert_eq!(MediaDescription::camera(false).wire(), json!({"mid": "1", "direction": "recvonly"}));
835 assert_eq!(
836 MediaDescription::camera(false).wire(),
837 json!({"mid": "1", "direction": "recvonly"})
838 );
553 assert_eq!(
839 assert_eq!(
554 MediaDescription::share(true).wire(),
840 MediaDescription::share(true).wire(),
555 json!({"mid": "11", "direction": "sendrecv", "label": "applicationsharing-video"})
841 json!({"mid": "11", "direction": "sendrecv", "label": "applicationsharing-video"})
@@ -561,37 +847,59 @@ mod tests {
561 let router = VideoRouter::default();
847 let router = VideoRouter::default();
562 assert_eq!(router.key_for("2"), None);
848 assert_eq!(router.key_for("2"), None);
563 router.set("2", Some(VideoKey::Person("8:orgid:a".into())));
849 router.set("2", Some(VideoKey::Person("8:orgid:a".into())));
564 assert_eq!(router.key_for("2"), Some(VideoKey::Person("8:orgid:a".into())));
850 assert_eq!(
851 router.key_for("2"),
852 Some(VideoKey::Person("8:orgid:a".into()))
853 );
565 router.set("2", None);
854 router.set("2", None);
566 assert_eq!(router.key_for("2"), None);
855 assert_eq!(router.key_for("2"), None);
567 }
856 }
568
857
569 #[test]
858 #[test]
570 fn send_capabilities_name_the_camera_mid_and_the_largest_side() {
859 fn send_capabilities_name_the_camera_mid_and_the_largest_side() {
571 let body = send_capabilities_body(1280, 720, 4);
860 let body = send_capabilities_body(1280, 720, 4, VideoQuality::Auto);
572 let channel = &body["applyChannelParameters"]["multiChannelParameter"];
861 let channel = &body["applyChannelParameters"]["multiChannelParameter"];
573 assert_eq!(channel["mids"], json!(["1"]));
862 assert_eq!(channel["mids"], json!(["1"]));
574 let parameter: Value = serde_json::from_str(channel["mediaParameter"].as_str().unwrap()).unwrap();
863 let parameter: Value =
864 serde_json::from_str(channel["mediaParameter"].as_str().unwrap()).unwrap();
575 assert_eq!(
865 assert_eq!(
576 parameter,
866 parameter,
577 json!({"maxVideoSendCapabilities": {
867 json!({"maxVideoSendCapabilities": {
578 "max-width": 1280, "max-height": 1280, "max-fps": 30, "max-streams": 3, "max-layers": 3, "sequence-number": 4
868 "max-width": 1280, "max-height": 1280, "max-fps": 30, "max-streams": 3, "max-layers": 3, "sequence-number": 4
579 }})
869 }})
580 );
870 );
581 let small: Value =
871 let small: Value = serde_json::from_str(
582 serde_json::from_str(send_capabilities_body(480, 270, 1)["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"].as_str().unwrap())
872 send_capabilities_body(480, 270, 1, VideoQuality::Auto)
583 .unwrap();
873 ["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"]
874 .as_str()
875 .unwrap(),
876 )
877 .unwrap();
584 assert_eq!(small["maxVideoSendCapabilities"]["max-layers"], 2);
878 assert_eq!(small["maxVideoSendCapabilities"]["max-layers"], 2);
879 let clamped: Value = serde_json::from_str(
880 send_capabilities_body(3840, 2160, 1, VideoQuality::P720)
881 ["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"]
882 .as_str()
883 .unwrap(),
884 )
885 .unwrap();
886 assert_eq!(clamped["maxVideoSendCapabilities"]["max-width"], 1280);
887 assert_eq!(clamped["maxVideoSendCapabilities"]["max-height"], 1280);
585 }
888 }
586
889
587 #[test]
890 #[test]
588 fn the_reporter_skips_a_repeated_size_and_counts_sequences() {
891 fn the_reporter_skips_a_repeated_size_and_counts_sequences() {
589 let mut reporter = SendCapabilityReporter::default();
892 let mut reporter = SendCapabilityReporter::default();
590 assert!(reporter.body_for((1280, 720)).is_some());
893 assert!(reporter.body_for((1280, 720), VideoQuality::Auto).is_some());
591 assert!(reporter.body_for((1280, 720)).is_none());
894 assert!(reporter.body_for((1280, 720), VideoQuality::Auto).is_none());
592 let body = reporter.body_for((640, 480)).unwrap();
895 let body = reporter.body_for((640, 480), VideoQuality::Auto).unwrap();
593 let parameter: Value =
896 let parameter: Value = serde_json::from_str(
594 serde_json::from_str(body["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"].as_str().unwrap()).unwrap();
897 body["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"]
898 .as_str()
899 .unwrap(),
900 )
901 .unwrap();
595 assert_eq!(parameter["maxVideoSendCapabilities"]["sequence-number"], 2);
902 assert_eq!(parameter["maxVideoSendCapabilities"]["sequence-number"], 2);
903 assert!(reporter.body_for((640, 480), VideoQuality::P720).is_some());
596 }
904 }
597}
905}
crates/calling/src/video_quality.rs added +69 −0
@@ -0,0 +1,69 @@
1 /// User-facing camera / stage video quality ceiling. No 4K mode.
2 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
3 pub enum VideoQuality {
4 #[default]
5 Auto,
6 P720,
7 P1080,
8 }
9
10 impl VideoQuality {
11 /// Preferred capture height for this choice (Auto prefers 1080).
12 pub fn capture_height(self) -> u32 {
13 match self {
14 Self::P720 => 720,
15 Self::Auto | Self::P1080 => 1080,
16 }
17 }
18
19 pub fn capture_width(self) -> u32 {
20 self.capture_height() * 16 / 9
21 }
22
23 /// Highest sensor height we may open before downscaling to the capture ceiling.
24 pub fn largest_sensor_height(self) -> u32 {
25 match self {
26 Self::P720 => 1080,
27 Self::Auto | Self::P1080 => 1440,
28 }
29 }
30
31 pub fn from_meta(value: &str) -> Self {
32 match value {
33 "720" => Self::P720,
34 "1080" => Self::P1080,
35 _ => Self::Auto,
36 }
37 }
38
39 pub fn to_meta(self) -> &'static str {
40 match self {
41 Self::Auto => "auto",
42 Self::P720 => "720",
43 Self::P1080 => "1080",
44 }
45 }
46 }
47
48 #[cfg(test)]
49 mod tests {
50 use super::*;
51
52 #[test]
53 fn auto_and_1080_share_a_1080_capture_ceiling() {
54 assert_eq!(VideoQuality::Auto.capture_height(), 1080);
55 assert_eq!(VideoQuality::P1080.capture_height(), 1080);
56 assert_eq!(VideoQuality::P720.capture_height(), 720);
57 assert_eq!(VideoQuality::Auto.capture_width(), 1920);
58 assert_eq!(VideoQuality::P720.capture_width(), 1280);
59 }
60
61 #[test]
62 fn meta_round_trips() {
63 for quality in [VideoQuality::Auto, VideoQuality::P720, VideoQuality::P1080] {
64 assert_eq!(VideoQuality::from_meta(quality.to_meta()), quality);
65 }
66 assert_eq!(VideoQuality::from_meta(""), VideoQuality::Auto);
67 assert_eq!(VideoQuality::from_meta("garbage"), VideoQuality::Auto);
68 }
69 }
@@ -0,0 +1,69 @@
1/// User-facing camera / stage video quality ceiling. No 4K mode.
2#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
3pub enum VideoQuality {
4 #[default]
5 Auto,
6 P720,
7 P1080,
8}
9
10impl VideoQuality {
11 /// Preferred capture height for this choice (Auto prefers 1080).
12 pub fn capture_height(self) -> u32 {
13 match self {
14 Self::P720 => 720,
15 Self::Auto | Self::P1080 => 1080,
16 }
17 }
18
19 pub fn capture_width(self) -> u32 {
20 self.capture_height() * 16 / 9
21 }
22
23 /// Highest sensor height we may open before downscaling to the capture ceiling.
24 pub fn largest_sensor_height(self) -> u32 {
25 match self {
26 Self::P720 => 1080,
27 Self::Auto | Self::P1080 => 1440,
28 }
29 }
30
31 pub fn from_meta(value: &str) -> Self {
32 match value {
33 "720" => Self::P720,
34 "1080" => Self::P1080,
35 _ => Self::Auto,
36 }
37 }
38
39 pub fn to_meta(self) -> &'static str {
40 match self {
41 Self::Auto => "auto",
42 Self::P720 => "720",
43 Self::P1080 => "1080",
44 }
45 }
46}
47
48#[cfg(test)]
49mod tests {
50 use super::*;
51
52 #[test]
53 fn auto_and_1080_share_a_1080_capture_ceiling() {
54 assert_eq!(VideoQuality::Auto.capture_height(), 1080);
55 assert_eq!(VideoQuality::P1080.capture_height(), 1080);
56 assert_eq!(VideoQuality::P720.capture_height(), 720);
57 assert_eq!(VideoQuality::Auto.capture_width(), 1920);
58 assert_eq!(VideoQuality::P720.capture_width(), 1280);
59 }
60
61 #[test]
62 fn meta_round_trips() {
63 for quality in [VideoQuality::Auto, VideoQuality::P720, VideoQuality::P1080] {
64 assert_eq!(VideoQuality::from_meta(quality.to_meta()), quality);
65 }
66 assert_eq!(VideoQuality::from_meta(""), VideoQuality::Auto);
67 assert_eq!(VideoQuality::from_meta("garbage"), VideoQuality::Auto);
68 }
69}
crates/calling/src/video_receive.rs +77 −16
@@ -14,8 +14,10 @@ use crate::signaling::Signaling;
14 14 use crate::timeline::Timeline;
15 15 use crate::video_frame::{FrameGate, VideoHub, VideoKey, picture_from_frame};
16 16 use crate::video_layout::{
17 Assignment, SlotTable, SourceRequest, TileDetail, VideoRouter, VideoWant, plan_receive, prioritize, requests_for,
17 Assignment, SlotTable, SourceRequest, TileDetail, VideoRouter, VideoWant, plan_receive,
18 prioritize, requests_for,
18 19 };
20 use crate::video_quality::VideoQuality;
19 21
20 22 const HISTORY_LIMIT: usize = 16;
21 23 const REQUEST_LABEL: &str = "POST applyChannelParameters";
@@ -38,12 +40,18 @@ pub fn spawn_video_pump(
38 40 let mut gates: HashMap<VideoKey, FrameGate> = HashMap::new();
39 41 while let Some(frame) = stream.next().await {
40 42 counters.received.fetch_add(1, Ordering::Relaxed);
41 let Some(key) = router.key_for(&mid) else { continue };
42 let gate = gates.entry(key.clone()).or_insert_with(|| FrameGate::new(key.max_fps()));
43 let Some(key) = router.key_for(&mid) else {
44 continue;
45 };
46 let gate = gates
47 .entry(key.clone())
48 .or_insert_with(|| FrameGate::new(key.max_fps()));
43 49 if !gate.admit(Instant::now()) {
44 50 continue;
45 51 }
46 let Some(picture) = picture_from_frame(frame, key.max_width()) else { continue };
52 let Some(picture) = picture_from_frame(frame, key.max_width()) else {
53 continue;
54 };
47 55 counters.published.fetch_add(1, Ordering::Relaxed);
48 56 hub.publish(key, picture);
49 57 }
@@ -62,7 +70,13 @@ pub struct SourceRequester {
62 70 }
63 71
64 72 impl SourceRequester {
65 pub fn start(signaling: Arc<Signaling>, url: String, router: VideoRouter, hub: Arc<VideoHub>, timeline: Timeline) -> Self {
73 pub fn start(
74 signaling: Arc<Signaling>,
75 url: String,
76 router: VideoRouter,
77 hub: Arc<VideoHub>,
78 timeline: Timeline,
79 ) -> Self {
66 80 let (queue, mut requests) = mpsc::unbounded_channel::<QueuedRequest>();
67 81 let task = tokio::spawn(async move {
68 82 let mut sequence_number = 0u64;
@@ -72,11 +86,18 @@ impl SourceRequester {
72 86 match signaling.post_json(REQUEST_LABEL, &url, body).await {
73 87 Ok(()) => timeline.record(
74 88 "video source",
75 format!("mid {} source {:?} accepted", queued.request.mid, queued.request.source),
89 format!(
90 "mid {} source {:?} accepted",
91 queued.request.mid, queued.request.source
92 ),
76 93 ),
77 94 Err(error) => timeline.record("video source failed", error.to_string()),
78 95 }
79 if let Some(key) = queued.route_after.as_ref().filter(|key| router.key_for(&queued.request.mid).as_ref() != Some(key)) {
96 if let Some(key) = queued
97 .route_after
98 .as_ref()
99 .filter(|key| router.key_for(&queued.request.mid).as_ref() != Some(key))
100 {
80 101 hub.forget(key);
81 102 }
82 103 router.set(&queued.request.mid, queued.route_after);
@@ -86,9 +107,11 @@ impl SourceRequester {
86 107 }
87 108
88 109 fn send(&self, request: SourceRequest, route_after: Option<VideoKey>) {
89 let _ = self.queue.send(QueuedRequest { request, route_after });
110 let _ = self.queue.send(QueuedRequest {
111 request,
112 route_after,
113 });
90 114 }
91
92 115 }
93 116
94 117 impl Drop for SourceRequester {
@@ -112,6 +135,8 @@ pub struct VideoReceive {
112 135 wants: Option<Vec<VideoWant>>,
113 136 requester: Option<SourceRequester>,
114 137 incoming_enabled: bool,
138 quality: VideoQuality,
139 refresh_limits: bool,
115 140 }
116 141
117 142 impl VideoReceive {
@@ -126,6 +151,8 @@ impl VideoReceive {
126 151 wants: None,
127 152 requester: None,
128 153 incoming_enabled: true,
154 quality: VideoQuality::default(),
155 refresh_limits: false,
129 156 }
130 157 }
131 158
@@ -133,6 +160,15 @@ impl VideoReceive {
133 160 self.incoming_enabled = enabled;
134 161 }
135 162
163 pub fn set_video_quality(&mut self, quality: VideoQuality) -> bool {
164 if self.quality == quality {
165 return false;
166 }
167 self.quality = quality;
168 self.refresh_limits = true;
169 true
170 }
171
136 172 pub fn set_wants(&mut self, wants: Vec<VideoWant>) -> bool {
137 173 let changed = self.wants.as_ref() != Some(&wants);
138 174 self.wants = Some(wants);
@@ -169,20 +205,38 @@ impl VideoReceive {
169 205
170 206 pub fn reselect(&mut self, roster: &Roster) -> ReceiveChange {
171 207 let mut change = ReceiveChange::default();
172 let Some(requester) = &self.requester else { return change };
208 let Some(requester) = &self.requester else {
209 return change;
210 };
173 211 let candidates = if self.incoming_enabled {
174 prioritize(roster.video_candidates(&self.own_mri), &self.history, self.wants.as_deref())
212 prioritize(
213 roster.video_candidates(&self.own_mri),
214 &self.history,
215 self.wants.as_deref(),
216 )
175 217 } else {
176 218 Vec::new()
177 219 };
178 220 let next = plan_receive(&self.held, &candidates);
179 for request in requests_for(&self.held, &next, &self.table.people) {
180 let slot = self.table.people.iter().position(|slot| slot.mid == request.mid);
221 let current = if self.refresh_limits {
222 vec![None; self.held.len()]
223 } else {
224 self.held.clone()
225 };
226 for request in requests_for(&current, &next, &self.table.people, self.quality) {
227 let slot = self
228 .table
229 .people
230 .iter()
231 .position(|slot| slot.mid == request.mid);
181 232 let route_after = slot
182 233 .and_then(|index| next[index].as_ref())
183 234 .map(|assignment| VideoKey::Person(assignment.mri.clone()));
184 235 let same_person = slot.is_some_and(|index| {
185 self.held[index].as_ref().zip(next[index].as_ref()).is_some_and(|(before, after)| before.mri == after.mri)
236 self.held[index]
237 .as_ref()
238 .zip(next[index].as_ref())
239 .is_some_and(|(before, after)| before.mri == after.mri)
186 240 });
187 241 if !same_person {
188 242 self.router.set(&request.mid, None);
@@ -190,10 +244,15 @@ impl VideoReceive {
190 244 requester.send(request, route_after);
191 245 }
192 246 self.held = next;
247 self.refresh_limits = false;
193 248 if let Some(slot) = &self.table.screen {
194 249 let wanted = roster
195 250 .screen_share(&self.own_mri)
196 .map(|(mri, source)| Assignment { mri, source, detail: TileDetail::Stage });
251 .map(|(mri, source)| Assignment {
252 mri,
253 source,
254 detail: TileDetail::Stage,
255 });
197 256 if wanted != self.screen_held {
198 257 let route_after = wanted.as_ref().map(|_| VideoKey::Screen);
199 258 self.router.set(&slot.mid, route_after.clone());
@@ -204,10 +263,12 @@ impl VideoReceive {
204 263 source: wanted.as_ref().map(|assignment| assignment.source),
205 264 screen: true,
206 265 detail: TileDetail::Stage,
266 quality: self.quality,
207 267 },
208 268 route_after,
209 269 );
210 change.screen_sharer = Some(wanted.as_ref().map(|assignment| assignment.mri.clone()));
270 change.screen_sharer =
271 Some(wanted.as_ref().map(|assignment| assignment.mri.clone()));
211 272 self.screen_held = wanted;
212 273 }
213 274 }
@@ -14,8 +14,10 @@ use crate::signaling::Signaling;
14use crate::timeline::Timeline;
14use crate::timeline::Timeline;
15use crate::video_frame::{FrameGate, VideoHub, VideoKey, picture_from_frame};
15use crate::video_frame::{FrameGate, VideoHub, VideoKey, picture_from_frame};
16use crate::video_layout::{
16use crate::video_layout::{
17 Assignment, SlotTable, SourceRequest, TileDetail, VideoRouter, VideoWant, plan_receive, prioritize, requests_for,
17 Assignment, SlotTable, SourceRequest, TileDetail, VideoRouter, VideoWant, plan_receive,
18 prioritize, requests_for,
18};
19};
20use crate::video_quality::VideoQuality;
19
21
20const HISTORY_LIMIT: usize = 16;
22const HISTORY_LIMIT: usize = 16;
21const REQUEST_LABEL: &str = "POST applyChannelParameters";
23const REQUEST_LABEL: &str = "POST applyChannelParameters";
@@ -38,12 +40,18 @@ pub fn spawn_video_pump(
38 let mut gates: HashMap<VideoKey, FrameGate> = HashMap::new();
40 let mut gates: HashMap<VideoKey, FrameGate> = HashMap::new();
39 while let Some(frame) = stream.next().await {
41 while let Some(frame) = stream.next().await {
40 counters.received.fetch_add(1, Ordering::Relaxed);
42 counters.received.fetch_add(1, Ordering::Relaxed);
41 let Some(key) = router.key_for(&mid) else { continue };
43 let Some(key) = router.key_for(&mid) else {
42 let gate = gates.entry(key.clone()).or_insert_with(|| FrameGate::new(key.max_fps()));
44 continue;
45 };
46 let gate = gates
47 .entry(key.clone())
48 .or_insert_with(|| FrameGate::new(key.max_fps()));
43 if !gate.admit(Instant::now()) {
49 if !gate.admit(Instant::now()) {
44 continue;
50 continue;
45 }
51 }
46 let Some(picture) = picture_from_frame(frame, key.max_width()) else { continue };
52 let Some(picture) = picture_from_frame(frame, key.max_width()) else {
53 continue;
54 };
47 counters.published.fetch_add(1, Ordering::Relaxed);
55 counters.published.fetch_add(1, Ordering::Relaxed);
48 hub.publish(key, picture);
56 hub.publish(key, picture);
49 }
57 }
@@ -62,7 +70,13 @@ pub struct SourceRequester {
62}
70}
63
71
64impl SourceRequester {
72impl SourceRequester {
65 pub fn start(signaling: Arc<Signaling>, url: String, router: VideoRouter, hub: Arc<VideoHub>, timeline: Timeline) -> Self {
73 pub fn start(
74 signaling: Arc<Signaling>,
75 url: String,
76 router: VideoRouter,
77 hub: Arc<VideoHub>,
78 timeline: Timeline,
79 ) -> Self {
66 let (queue, mut requests) = mpsc::unbounded_channel::<QueuedRequest>();
80 let (queue, mut requests) = mpsc::unbounded_channel::<QueuedRequest>();
67 let task = tokio::spawn(async move {
81 let task = tokio::spawn(async move {
68 let mut sequence_number = 0u64;
82 let mut sequence_number = 0u64;
@@ -72,11 +86,18 @@ impl SourceRequester {
72 match signaling.post_json(REQUEST_LABEL, &url, body).await {
86 match signaling.post_json(REQUEST_LABEL, &url, body).await {
73 Ok(()) => timeline.record(
87 Ok(()) => timeline.record(
74 "video source",
88 "video source",
75 format!("mid {} source {:?} accepted", queued.request.mid, queued.request.source),
89 format!(
90 "mid {} source {:?} accepted",
91 queued.request.mid, queued.request.source
92 ),
76 ),
93 ),
77 Err(error) => timeline.record("video source failed", error.to_string()),
94 Err(error) => timeline.record("video source failed", error.to_string()),
78 }
95 }
79 if let Some(key) = queued.route_after.as_ref().filter(|key| router.key_for(&queued.request.mid).as_ref() != Some(key)) {
96 if let Some(key) = queued
97 .route_after
98 .as_ref()
99 .filter(|key| router.key_for(&queued.request.mid).as_ref() != Some(key))
100 {
80 hub.forget(key);
101 hub.forget(key);
81 }
102 }
82 router.set(&queued.request.mid, queued.route_after);
103 router.set(&queued.request.mid, queued.route_after);
@@ -86,9 +107,11 @@ impl SourceRequester {
86 }
107 }
87
108
88 fn send(&self, request: SourceRequest, route_after: Option<VideoKey>) {
109 fn send(&self, request: SourceRequest, route_after: Option<VideoKey>) {
89 let _ = self.queue.send(QueuedRequest { request, route_after });
110 let _ = self.queue.send(QueuedRequest {
111 request,
112 route_after,
113 });
90 }
114 }
91
92}
115}
93
116
94impl Drop for SourceRequester {
117impl Drop for SourceRequester {
@@ -112,6 +135,8 @@ pub struct VideoReceive {
112 wants: Option<Vec<VideoWant>>,
135 wants: Option<Vec<VideoWant>>,
113 requester: Option<SourceRequester>,
136 requester: Option<SourceRequester>,
114 incoming_enabled: bool,
137 incoming_enabled: bool,
138 quality: VideoQuality,
139 refresh_limits: bool,
115}
140}
116
141
117impl VideoReceive {
142impl VideoReceive {
@@ -126,6 +151,8 @@ impl VideoReceive {
126 wants: None,
151 wants: None,
127 requester: None,
152 requester: None,
128 incoming_enabled: true,
153 incoming_enabled: true,
154 quality: VideoQuality::default(),
155 refresh_limits: false,
129 }
156 }
130 }
157 }
131
158
@@ -133,6 +160,15 @@ impl VideoReceive {
133 self.incoming_enabled = enabled;
160 self.incoming_enabled = enabled;
134 }
161 }
135
162
163 pub fn set_video_quality(&mut self, quality: VideoQuality) -> bool {
164 if self.quality == quality {
165 return false;
166 }
167 self.quality = quality;
168 self.refresh_limits = true;
169 true
170 }
171
136 pub fn set_wants(&mut self, wants: Vec<VideoWant>) -> bool {
172 pub fn set_wants(&mut self, wants: Vec<VideoWant>) -> bool {
137 let changed = self.wants.as_ref() != Some(&wants);
173 let changed = self.wants.as_ref() != Some(&wants);
138 self.wants = Some(wants);
174 self.wants = Some(wants);
@@ -169,20 +205,38 @@ impl VideoReceive {
169
205
170 pub fn reselect(&mut self, roster: &Roster) -> ReceiveChange {
206 pub fn reselect(&mut self, roster: &Roster) -> ReceiveChange {
171 let mut change = ReceiveChange::default();
207 let mut change = ReceiveChange::default();
172 let Some(requester) = &self.requester else { return change };
208 let Some(requester) = &self.requester else {
209 return change;
210 };
173 let candidates = if self.incoming_enabled {
211 let candidates = if self.incoming_enabled {
174 prioritize(roster.video_candidates(&self.own_mri), &self.history, self.wants.as_deref())
212 prioritize(
213 roster.video_candidates(&self.own_mri),
214 &self.history,
215 self.wants.as_deref(),
216 )
175 } else {
217 } else {
176 Vec::new()
218 Vec::new()
177 };
219 };
178 let next = plan_receive(&self.held, &candidates);
220 let next = plan_receive(&self.held, &candidates);
179 for request in requests_for(&self.held, &next, &self.table.people) {
221 let current = if self.refresh_limits {
180 let slot = self.table.people.iter().position(|slot| slot.mid == request.mid);
222 vec![None; self.held.len()]
223 } else {
224 self.held.clone()
225 };
226 for request in requests_for(&current, &next, &self.table.people, self.quality) {
227 let slot = self
228 .table
229 .people
230 .iter()
231 .position(|slot| slot.mid == request.mid);
181 let route_after = slot
232 let route_after = slot
182 .and_then(|index| next[index].as_ref())
233 .and_then(|index| next[index].as_ref())
183 .map(|assignment| VideoKey::Person(assignment.mri.clone()));
234 .map(|assignment| VideoKey::Person(assignment.mri.clone()));
184 let same_person = slot.is_some_and(|index| {
235 let same_person = slot.is_some_and(|index| {
185 self.held[index].as_ref().zip(next[index].as_ref()).is_some_and(|(before, after)| before.mri == after.mri)
236 self.held[index]
237 .as_ref()
238 .zip(next[index].as_ref())
239 .is_some_and(|(before, after)| before.mri == after.mri)
186 });
240 });
187 if !same_person {
241 if !same_person {
188 self.router.set(&request.mid, None);
242 self.router.set(&request.mid, None);
@@ -190,10 +244,15 @@ impl VideoReceive {
190 requester.send(request, route_after);
244 requester.send(request, route_after);
191 }
245 }
192 self.held = next;
246 self.held = next;
247 self.refresh_limits = false;
193 if let Some(slot) = &self.table.screen {
248 if let Some(slot) = &self.table.screen {
194 let wanted = roster
249 let wanted = roster
195 .screen_share(&self.own_mri)
250 .screen_share(&self.own_mri)
196 .map(|(mri, source)| Assignment { mri, source, detail: TileDetail::Stage });
251 .map(|(mri, source)| Assignment {
252 mri,
253 source,
254 detail: TileDetail::Stage,
255 });
197 if wanted != self.screen_held {
256 if wanted != self.screen_held {
198 let route_after = wanted.as_ref().map(|_| VideoKey::Screen);
257 let route_after = wanted.as_ref().map(|_| VideoKey::Screen);
199 self.router.set(&slot.mid, route_after.clone());
258 self.router.set(&slot.mid, route_after.clone());
@@ -204,10 +263,12 @@ impl VideoReceive {
204 source: wanted.as_ref().map(|assignment| assignment.source),
263 source: wanted.as_ref().map(|assignment| assignment.source),
205 screen: true,
264 screen: true,
206 detail: TileDetail::Stage,
265 detail: TileDetail::Stage,
266 quality: self.quality,
207 },
267 },
208 route_after,
268 route_after,
209 );
269 );
210 change.screen_sharer = Some(wanted.as_ref().map(|assignment| assignment.mri.clone()));
270 change.screen_sharer =
271 Some(wanted.as_ref().map(|assignment| assignment.mri.clone()));
211 self.screen_held = wanted;
272 self.screen_held = wanted;
212 }
273 }
213 }
274 }
crates/calling/src/video_send.rs +8 −32
@@ -16,14 +16,13 @@ use tokio::sync::mpsc::UnboundedSender;
16 16
17 17 use crate::background::BackgroundPicture;
18 18 use crate::blur::BlurSettings;
19 use crate::camera::{CameraCaptureStats, start_camera};
19 use crate::camera::start_camera;
20 20 use crate::video_quality::VideoQuality;
21 21 use crate::capture::Capture;
22 22 use crate::control::{CallCommand, CallUpdate};
23 23 use crate::devices::DeviceChoice;
24 24 use crate::effects::CameraEffects;
25 25 use crate::error::{Error, Result};
26 use crate::timeline::Timeline;
27 26 use crate::screen::{
28 27 PortalFollowUp, ShareKind, ShareSource, start_portal_capture, start_screen_capture,
29 28 };
@@ -203,8 +202,6 @@ pub struct LocalVideo {
203 202 share_fps: Arc<AtomicU32>,
204 203 camera_preview: bool,
205 204 quality: VideoQuality,
206 camera_stats: Arc<CameraCaptureStats>,
207 timeline: Option<Timeline>,
208 205 portal_generation: u64,
209 206 portal_armed: bool,
210 207 portal_keep: bool,
@@ -232,8 +229,6 @@ impl LocalVideo {
232 229 share_fps: Arc::new(AtomicU32::new(SCREEN_SHARE_FPS)),
233 230 camera_preview: false,
234 231 quality: VideoQuality::default(),
235 camera_stats: CameraCaptureStats::new(),
236 timeline: None,
237 232 portal_generation: 0,
238 233 portal_armed: false,
239 234 portal_keep: false,
@@ -241,10 +236,6 @@ impl LocalVideo {
241 236 }
242 237 }
243 238
244 pub fn attach_timeline(&mut self, timeline: Timeline) {
245 self.timeline = Some(timeline);
246 }
247
248 239 pub fn video_quality(&self) -> VideoQuality {
249 240 self.quality
250 241 }
@@ -588,10 +579,6 @@ impl LocalVideo {
588 579 Ok(())
589 580 }
590 581
591 pub fn camera_capture_summary(&self) -> Option<String> {
592 self.camera_stats.summary()
593 }
594
595 582 fn capture_camera(&self, choice: &DeviceChoice) -> Result<Capture> {
596 583 let mut sink = self.camera_sink();
597 584 Ok(match self.mode {
@@ -600,24 +587,13 @@ impl LocalVideo {
600 587 PatternKind::Camera,
601 588 Some(self.blur.clone()),
602 589 )),
603 _ => {
604 let timeline = self.timeline.clone();
605 start_camera(
606 choice,
607 self.quality,
608 self.blur.clone(),
609 self.camera_stats.clone(),
610 move |label| {
611 if let Some(timeline) = timeline {
612 timeline.record("camera capture", label);
613 } else {
614 eprintln!("calls: camera capture {label}");
615 }
616 },
617 move |buffer| sink.push(buffer),
618 self.report_failure("Camera"),
619 )?
620 }
590 _ => start_camera(
591 choice,
592 self.quality,
593 self.blur.clone(),
594 move |buffer| sink.push(buffer),
595 self.report_failure("Camera"),
596 )?,
621 597 })
622 598 }
623 599
@@ -16,14 +16,13 @@ use tokio::sync::mpsc::UnboundedSender;
16
16
17use crate::background::BackgroundPicture;
17use crate::background::BackgroundPicture;
18use crate::blur::BlurSettings;
18use crate::blur::BlurSettings;
19use crate::camera::{CameraCaptureStats, start_camera};
19use crate::camera::start_camera;
20use crate::video_quality::VideoQuality;
20use crate::video_quality::VideoQuality;
21use crate::capture::Capture;
21use crate::capture::Capture;
22use crate::control::{CallCommand, CallUpdate};
22use crate::control::{CallCommand, CallUpdate};
23use crate::devices::DeviceChoice;
23use crate::devices::DeviceChoice;
24use crate::effects::CameraEffects;
24use crate::effects::CameraEffects;
25use crate::error::{Error, Result};
25use crate::error::{Error, Result};
26use crate::timeline::Timeline;
27use crate::screen::{
26use crate::screen::{
28 PortalFollowUp, ShareKind, ShareSource, start_portal_capture, start_screen_capture,
27 PortalFollowUp, ShareKind, ShareSource, start_portal_capture, start_screen_capture,
29};
28};
@@ -203,8 +202,6 @@ pub struct LocalVideo {
203 share_fps: Arc<AtomicU32>,
202 share_fps: Arc<AtomicU32>,
204 camera_preview: bool,
203 camera_preview: bool,
205 quality: VideoQuality,
204 quality: VideoQuality,
206 camera_stats: Arc<CameraCaptureStats>,
207 timeline: Option<Timeline>,
208 portal_generation: u64,
205 portal_generation: u64,
209 portal_armed: bool,
206 portal_armed: bool,
210 portal_keep: bool,
207 portal_keep: bool,
@@ -232,8 +229,6 @@ impl LocalVideo {
232 share_fps: Arc::new(AtomicU32::new(SCREEN_SHARE_FPS)),
229 share_fps: Arc::new(AtomicU32::new(SCREEN_SHARE_FPS)),
233 camera_preview: false,
230 camera_preview: false,
234 quality: VideoQuality::default(),
231 quality: VideoQuality::default(),
235 camera_stats: CameraCaptureStats::new(),
236 timeline: None,
237 portal_generation: 0,
232 portal_generation: 0,
238 portal_armed: false,
233 portal_armed: false,
239 portal_keep: false,
234 portal_keep: false,
@@ -241,10 +236,6 @@ impl LocalVideo {
241 }
236 }
242 }
237 }
243
238
244 pub fn attach_timeline(&mut self, timeline: Timeline) {
245 self.timeline = Some(timeline);
246 }
247
248 pub fn video_quality(&self) -> VideoQuality {
239 pub fn video_quality(&self) -> VideoQuality {
249 self.quality
240 self.quality
250 }
241 }
@@ -588,10 +579,6 @@ impl LocalVideo {
588 Ok(())
579 Ok(())
589 }
580 }
590
581
591 pub fn camera_capture_summary(&self) -> Option<String> {
592 self.camera_stats.summary()
593 }
594
595 fn capture_camera(&self, choice: &DeviceChoice) -> Result<Capture> {
582 fn capture_camera(&self, choice: &DeviceChoice) -> Result<Capture> {
596 let mut sink = self.camera_sink();
583 let mut sink = self.camera_sink();
597 Ok(match self.mode {
584 Ok(match self.mode {
@@ -600,24 +587,13 @@ impl LocalVideo {
600 PatternKind::Camera,
587 PatternKind::Camera,
601 Some(self.blur.clone()),
588 Some(self.blur.clone()),
602 )),
589 )),
603 _ => {
590 _ => start_camera(
604 let timeline = self.timeline.clone();
591 choice,
605 start_camera(
592 self.quality,
606 choice,
593 self.blur.clone(),
607 self.quality,
594 move |buffer| sink.push(buffer),
608 self.blur.clone(),
595 self.report_failure("Camera"),
609 self.camera_stats.clone(),
596 )?,
610 move |label| {
611 if let Some(timeline) = timeline {
612 timeline.record("camera capture", label);
613 } else {
614 eprintln!("calls: camera capture {label}");
615 }
616 },
617 move |buffer| sink.push(buffer),
618 self.report_failure("Camera"),
619 )?
620 }
621 })
597 })
622 }
598 }
623
599
openspec/changes/camera-video-quality/.openspec.yaml added +2 −0
@@ -0,0 +1,2 @@
1 schema: spec-driven
2 created: 2026-11-12
@@ -0,0 +1,2 @@
1schema: spec-driven
2created: 2026-11-12
openspec/changes/camera-video-quality/design.md added +64 −0
@@ -0,0 +1,64 @@
1 # Design
2
3 ## Context
4
5 Siehe `proposal.md` — Why. Heute: `CAPTURE_HEIGHT = 720`, Preferenz exakt 720, Downscale-Decke 1080 aber `fit_widescreen` kürzt wieder auf 720; Stage-Receive `max-fs=3600` (~720p); Screen schon `8160` (~1080p). Codec-Filter bleibt H.264 (`h264_only`).
6
7 ## Goals / Non-Goals
8
9 **Goals:**
10
11 - Eine Qualitaetsstufe steuert Capture-Decke, Send-Advertise und Stage-Receive gemeinsam.
12 - 1080p als praktisches Maximum; Auto faellt sauber auf 720p zurueck.
13 - Bestehende Small-Tile- und Screen-Share-Limits unangetastet.
14
15 **Non-Goals:**
16
17 - 4K-UI oder 4K-Advertise.
18 - H.265 / AV1.
19 - Mixer-Bitrate erzwingen jenseits der Teams-`controlVideoStreaming`-Antworten.
20 - Aenderung am Screen-Share-Capture-Pfad.
21
22 ## Decisions
23
24 ### 1. Eine Einstellung fuer Capture + Advertise + Stage
25
26 **Wahl:** `VideoQuality { Auto, P720, P1080 }` wirkt auf alle drei.
27
28 **Warum:** Getrennte «Senden»/«Empfangen»-Regler verdoppeln UI und erklaeren selten den wahrgenommenen Weichzeichner. Stage und Eigenbild sollen dieselbe Erwartung teilen.
29
30 **Alternative:** Nur Capture aendern — abgelehnt, weil Stage weiter 720p anfordert.
31
32 ### 2. Konstanten an Macroblock-Budgets koppeln
33
34 **Wahl:** 720p-Stage bleibt `max-fs=3600` / heutige `max-mbps`/`max-fps`; 1080p-Stage uebernimmt die heutigen Screen-`ReceiveLimits` (`8160` / `135_000` / `1500` fps-Einheiten) oder eine bewusst dokumentierte 1080p-Kamera-Variante mit gleichem `max-fs`, falls Screen-FPS zu niedrig fuer Kamera wirkt — dann `max-fps` bei 1080p-Stage auf Kameraniveau (~3000) halten und `max-mbps` proportional anheben.
35
36 **Empfehlung im Apply:** `max-fs=8160`, `max-fps=3000`, `max-mbps` so skalieren, dass 1080p@30 in Macroblock·FPS passt (≈ `8160 * 30` = 244800), nicht blind Screen-1500-FPS kopieren.
37
38 ### 3. Capture-API parametrisieren
39
40 **Wahl:** Preferenz-Hoehe und Downscale-Decke aus der aktiven Qualitaet ableiten statt hartem `CAPTURE_HEIGHT`. `pick_format` / `fit_widescreen` / Fallback-`Resolution` lesen dieselbe Decke. `LARGEST_DOWNSCALED_HEIGHT` fuer 1080-Ceiling darf hoehere Sensorformate bis z. B. 1440 zulassen, solange das Ergebnis auf ≤1080 skaliert — kein 4K-Modus in der UI.
41
42 ### 4. Persistenz und UI-Ort
43
44 **Wahl:** Persistenz neben bestehenden Geraete-/Call-Settings; Auswahl im Kamera-Menue (Call + Prejoin), Labels «Auto», «720p», «1080p». Default `Auto`. Wechsel im Call: Kamera-Track neu oeffnen wenn noetig; Stage-Subscriptions die Limits neu posten (`applyChannelParameters`).
45
46 ### 5. Codec unveraendert
47
48 H.264-only bleibt. Qualitaet ≠ Codec-Wechsel.
49
50 ## Risks / Trade-offs
51
52 - [Blur/Effects bei 1080p teurer] → Mitigation: Auto trotzdem 1080; bei messbaren Drops spaeter optional «Performance» — nicht in diesem Change.
53 - [Mixer ignoriert hoehere Advertise] → Mitigation: lokales Self-View und Capture trotzdem schaerfer; Stage-Request erhoehen unabhaengig.
54 - [Kamera ohne 30fps-1080] → Mitigation: Fallback 720; Start nicht hart failen.
55 - [Screen-Limits fuer Stage falsch uebernehmen (niedriges max-fps)] → Mitigation: Decision 2 mit kameratauglichem `max-fps`/`max-mbps`.
56
57 ## Migration Plan
58
59 - Default Auto → Nutzer ohne Setting bekommen 1080 wo moeglich (Verhalten aendert sich spuerbar).
60 - Rollback: Setting auf 720p oder Code-Revert der Capture-Konstanten.
61
62 ## Open Questions
63
64 - Ob Prejoin-Preview dieselbe Qualitaetsstufe sofort nutzt oder erst nach Join (bevorzugt: sofort, konsistent mit Call).
@@ -0,0 +1,64 @@
1# Design
2
3## Context
4
5Siehe `proposal.md` — Why. Heute: `CAPTURE_HEIGHT = 720`, Preferenz exakt 720, Downscale-Decke 1080 aber `fit_widescreen` kürzt wieder auf 720; Stage-Receive `max-fs=3600` (~720p); Screen schon `8160` (~1080p). Codec-Filter bleibt H.264 (`h264_only`).
6
7## Goals / Non-Goals
8
9**Goals:**
10
11- Eine Qualitaetsstufe steuert Capture-Decke, Send-Advertise und Stage-Receive gemeinsam.
12- 1080p als praktisches Maximum; Auto faellt sauber auf 720p zurueck.
13- Bestehende Small-Tile- und Screen-Share-Limits unangetastet.
14
15**Non-Goals:**
16
17- 4K-UI oder 4K-Advertise.
18- H.265 / AV1.
19- Mixer-Bitrate erzwingen jenseits der Teams-`controlVideoStreaming`-Antworten.
20- Aenderung am Screen-Share-Capture-Pfad.
21
22## Decisions
23
24### 1. Eine Einstellung fuer Capture + Advertise + Stage
25
26**Wahl:** `VideoQuality { Auto, P720, P1080 }` wirkt auf alle drei.
27
28**Warum:** Getrennte «Senden»/«Empfangen»-Regler verdoppeln UI und erklaeren selten den wahrgenommenen Weichzeichner. Stage und Eigenbild sollen dieselbe Erwartung teilen.
29
30**Alternative:** Nur Capture aendern — abgelehnt, weil Stage weiter 720p anfordert.
31
32### 2. Konstanten an Macroblock-Budgets koppeln
33
34**Wahl:** 720p-Stage bleibt `max-fs=3600` / heutige `max-mbps`/`max-fps`; 1080p-Stage uebernimmt die heutigen Screen-`ReceiveLimits` (`8160` / `135_000` / `1500` fps-Einheiten) oder eine bewusst dokumentierte 1080p-Kamera-Variante mit gleichem `max-fs`, falls Screen-FPS zu niedrig fuer Kamera wirkt — dann `max-fps` bei 1080p-Stage auf Kameraniveau (~3000) halten und `max-mbps` proportional anheben.
35
36**Empfehlung im Apply:** `max-fs=8160`, `max-fps=3000`, `max-mbps` so skalieren, dass 1080p@30 in Macroblock·FPS passt (≈ `8160 * 30` = 244800), nicht blind Screen-1500-FPS kopieren.
37
38### 3. Capture-API parametrisieren
39
40**Wahl:** Preferenz-Hoehe und Downscale-Decke aus der aktiven Qualitaet ableiten statt hartem `CAPTURE_HEIGHT`. `pick_format` / `fit_widescreen` / Fallback-`Resolution` lesen dieselbe Decke. `LARGEST_DOWNSCALED_HEIGHT` fuer 1080-Ceiling darf hoehere Sensorformate bis z. B. 1440 zulassen, solange das Ergebnis auf ≤1080 skaliert — kein 4K-Modus in der UI.
41
42### 4. Persistenz und UI-Ort
43
44**Wahl:** Persistenz neben bestehenden Geraete-/Call-Settings; Auswahl im Kamera-Menue (Call + Prejoin), Labels «Auto», «720p», «1080p». Default `Auto`. Wechsel im Call: Kamera-Track neu oeffnen wenn noetig; Stage-Subscriptions die Limits neu posten (`applyChannelParameters`).
45
46### 5. Codec unveraendert
47
48H.264-only bleibt. Qualitaet ≠ Codec-Wechsel.
49
50## Risks / Trade-offs
51
52- [Blur/Effects bei 1080p teurer] → Mitigation: Auto trotzdem 1080; bei messbaren Drops spaeter optional «Performance» — nicht in diesem Change.
53- [Mixer ignoriert hoehere Advertise] → Mitigation: lokales Self-View und Capture trotzdem schaerfer; Stage-Request erhoehen unabhaengig.
54- [Kamera ohne 30fps-1080] → Mitigation: Fallback 720; Start nicht hart failen.
55- [Screen-Limits fuer Stage falsch uebernehmen (niedriges max-fps)] → Mitigation: Decision 2 mit kameratauglichem `max-fps`/`max-mbps`.
56
57## Migration Plan
58
59- Default Auto → Nutzer ohne Setting bekommen 1080 wo moeglich (Verhalten aendert sich spuerbar).
60- Rollback: Setting auf 720p oder Code-Revert der Capture-Konstanten.
61
62## Open Questions
63
64- Ob Prejoin-Preview dieselbe Qualitaetsstufe sofort nutzt oder erst nach Join (bevorzugt: sofort, konsistent mit Call).
openspec/changes/camera-video-quality/proposal.md added +32 −0
@@ -0,0 +1,32 @@
1 # Proposal
2
3 ## Why
4
5 Die Kamera wirkt weich, weil Capture und Stage-Empfang auf ~720p festgenagelt sind, obwohl viele Kameras und der Teams-Mixer 1080p koennen. Nutzer sollen die Sende-/Empfangsqualitaet bewusst steuern koennen, ohne 4K-Komplexitaet.
6
7 ## What Changes
8
9 - Kamera-Capture bevorzugt **1080p @ 30 fps** (Widescreen), mit Fallback auf 720p wenn die Kamera das nicht liefert.
10 - Stage-Empfangs-Limits steigen auf **1080p-Niveau** (analog heutiger Screen-Share-`max-fs`/`max-mbps`-Groessenordnung).
11 - Neue persistente Einstellung **Videoqualitaet**: `Auto` | `720p` | `1080p` (kein 4K).
12 - Steuert Capture-Decke, `maxVideoSendCapabilities` und Stage-Request-Limits zusammen.
13 - `Auto` = hoechste unterstuetzte Stufe bis 1080p.
14 - Small-Tile-Limits und Screen-Share-Limits bleiben unveraendert.
15 - Codec bleibt H.264; kein H.265.
16
17 ## Capabilities
18
19 ### New Capabilities
20
21 - `camera-video-quality`: Capture-Preferenz, Sende-Faehigkeiten und Stage-Empfangs-Limits fuer Kameravideo, inkl. Nutzerwahl Auto/720/1080.
22
23 ### Modified Capabilities
24
25 - (keine)
26
27 ## Impact
28
29 - Capture/Formatwahl und Downscale in `crates/calling` (Kamera-Pfad).
30 - Stage-`applyChannelParameters` / Receive-Limits und Send-Capabilities in `crates/calling`.
31 - UI: Kamera-Menue bzw. Call-/Geraete-Einstellungen in `crates/app`; Persistenz analog bestehender Call-Settings.
32 - Tests: Formatwahl, Limit-Konstanten, Setting-Persistenz; Verify mit `cargo test -p calling --lib` und gezielten App-Tests.
@@ -0,0 +1,32 @@
1# Proposal
2
3## Why
4
5Die Kamera wirkt weich, weil Capture und Stage-Empfang auf ~720p festgenagelt sind, obwohl viele Kameras und der Teams-Mixer 1080p koennen. Nutzer sollen die Sende-/Empfangsqualitaet bewusst steuern koennen, ohne 4K-Komplexitaet.
6
7## What Changes
8
9- Kamera-Capture bevorzugt **1080p @ 30 fps** (Widescreen), mit Fallback auf 720p wenn die Kamera das nicht liefert.
10- Stage-Empfangs-Limits steigen auf **1080p-Niveau** (analog heutiger Screen-Share-`max-fs`/`max-mbps`-Groessenordnung).
11- Neue persistente Einstellung **Videoqualitaet**: `Auto` | `720p` | `1080p` (kein 4K).
12 - Steuert Capture-Decke, `maxVideoSendCapabilities` und Stage-Request-Limits zusammen.
13 - `Auto` = hoechste unterstuetzte Stufe bis 1080p.
14- Small-Tile-Limits und Screen-Share-Limits bleiben unveraendert.
15- Codec bleibt H.264; kein H.265.
16
17## Capabilities
18
19### New Capabilities
20
21- `camera-video-quality`: Capture-Preferenz, Sende-Faehigkeiten und Stage-Empfangs-Limits fuer Kameravideo, inkl. Nutzerwahl Auto/720/1080.
22
23### Modified Capabilities
24
25- (keine)
26
27## Impact
28
29- Capture/Formatwahl und Downscale in `crates/calling` (Kamera-Pfad).
30- Stage-`applyChannelParameters` / Receive-Limits und Send-Capabilities in `crates/calling`.
31- UI: Kamera-Menue bzw. Call-/Geraete-Einstellungen in `crates/app`; Persistenz analog bestehender Call-Settings.
32- Tests: Formatwahl, Limit-Konstanten, Setting-Persistenz; Verify mit `cargo test -p calling --lib` und gezielten App-Tests.
openspec/changes/camera-video-quality/specs/camera-video-quality/spec.md added +63 −0
@@ -0,0 +1,63 @@
1 # Spec Delta
2
3 ## Purpose
4
5 Steuert, in welcher Aufloesung die eigene Kamera erfasst und dem Call angeboten wird, und welche Qualitaet fuer Stage-Kamera-Empfang angefordert wird — waehlbar als Auto, 720p oder 1080p.
6
7 ## ADDED Requirements
8
9 ### Requirement: Camera capture prefers the selected quality ceiling
10
11 The client SHALL capture the local camera at the highest supported widescreen format at least 30 fps that does not exceed the active quality ceiling (720p or 1080p). Auto SHALL use a 1080p ceiling when the camera can deliver it, otherwise 720p. The client SHALL NOT offer or use a 4K camera quality mode.
12
13 #### Scenario: Camera supports 1080p with Auto
14
15 - **WHEN** video quality is Auto and the selected camera exposes a suitable 1920×1080 (or equivalent 16:9) format at ≥30 fps
16 - **THEN** capture uses that 1080p-class format (not forced down to 720p before encoding)
17
18 #### Scenario: Camera only supports 720p
19
20 - **WHEN** video quality is Auto or 1080p and the camera cannot provide a suitable 1080p format
21 - **THEN** capture falls back to a suitable 720p format without failing camera start solely for that reason
22
23 #### Scenario: User locks 720p
24
25 - **WHEN** video quality is set to 720p and a higher camera format is available
26 - **THEN** capture stays at or below 720p
27
28 ### Requirement: Send capabilities match capture ceiling
29
30 After the local camera size for sending is known, the client SHALL advertise max video send capabilities whose width and height reflect that capture size (up to the active quality ceiling), so the meeting media path can request layers up to that size.
31
32 #### Scenario: 1080p capture is advertised
33
34 - **WHEN** the outbound camera frame size is 1920×1080
35 - **THEN** the send-capabilities update reports max width and height of at least 1920 on the largest side consistent with that frame
36
37 ### Requirement: Stage receive requests use 1080p-class limits when allowed
38
39 For non-screen camera tiles shown as stage detail, the client SHALL request receive limits at 1080p-class macroblock and throughput budgets when the active quality ceiling is Auto or 1080p. When the ceiling is 720p, stage requests SHALL remain at 720p-class budgets. Small gallery tiles and screen-share receive limits SHALL keep their existing budgets.
40
41 #### Scenario: Stage at Auto or 1080p
42
43 - **WHEN** the user is subscribed to a participant camera on the stage and video quality is Auto or 1080p
44 - **THEN** the stage receive request uses 1080p-class `max-fs` / `max-mbps` budgets (same order of magnitude as today’s screen-share camera request, not the previous 720p stage budget)
45
46 #### Scenario: Stage locked to 720p
47
48 - **WHEN** video quality is 720p and the user is subscribed to a stage camera tile
49 - **THEN** the stage receive request uses 720p-class budgets
50
51 ### Requirement: Video quality setting is user-visible and persistent
52
53 The product SHALL expose a video quality choice of Auto, 720p, and 1080p in the call/device camera controls, persist the choice across app restarts, and apply it to new captures and new stage subscriptions. Changing the setting while a call is active SHALL take effect for subsequent capture restarts and subsequent stage request updates without requiring an app relaunch.
54
55 #### Scenario: Persist across restart
56
57 - **WHEN** the user selects 1080p and later restarts the app
58 - **THEN** video quality remains 1080p
59
60 #### Scenario: Default is Auto
61
62 - **WHEN** no prior video quality choice exists
63 - **THEN** the effective choice is Auto
@@ -0,0 +1,63 @@
1# Spec Delta
2
3## Purpose
4
5Steuert, in welcher Aufloesung die eigene Kamera erfasst und dem Call angeboten wird, und welche Qualitaet fuer Stage-Kamera-Empfang angefordert wird — waehlbar als Auto, 720p oder 1080p.
6
7## ADDED Requirements
8
9### Requirement: Camera capture prefers the selected quality ceiling
10
11The client SHALL capture the local camera at the highest supported widescreen format at least 30 fps that does not exceed the active quality ceiling (720p or 1080p). Auto SHALL use a 1080p ceiling when the camera can deliver it, otherwise 720p. The client SHALL NOT offer or use a 4K camera quality mode.
12
13#### Scenario: Camera supports 1080p with Auto
14
15- **WHEN** video quality is Auto and the selected camera exposes a suitable 1920×1080 (or equivalent 16:9) format at ≥30 fps
16- **THEN** capture uses that 1080p-class format (not forced down to 720p before encoding)
17
18#### Scenario: Camera only supports 720p
19
20- **WHEN** video quality is Auto or 1080p and the camera cannot provide a suitable 1080p format
21- **THEN** capture falls back to a suitable 720p format without failing camera start solely for that reason
22
23#### Scenario: User locks 720p
24
25- **WHEN** video quality is set to 720p and a higher camera format is available
26- **THEN** capture stays at or below 720p
27
28### Requirement: Send capabilities match capture ceiling
29
30After the local camera size for sending is known, the client SHALL advertise max video send capabilities whose width and height reflect that capture size (up to the active quality ceiling), so the meeting media path can request layers up to that size.
31
32#### Scenario: 1080p capture is advertised
33
34- **WHEN** the outbound camera frame size is 1920×1080
35- **THEN** the send-capabilities update reports max width and height of at least 1920 on the largest side consistent with that frame
36
37### Requirement: Stage receive requests use 1080p-class limits when allowed
38
39For non-screen camera tiles shown as stage detail, the client SHALL request receive limits at 1080p-class macroblock and throughput budgets when the active quality ceiling is Auto or 1080p. When the ceiling is 720p, stage requests SHALL remain at 720p-class budgets. Small gallery tiles and screen-share receive limits SHALL keep their existing budgets.
40
41#### Scenario: Stage at Auto or 1080p
42
43- **WHEN** the user is subscribed to a participant camera on the stage and video quality is Auto or 1080p
44- **THEN** the stage receive request uses 1080p-class `max-fs` / `max-mbps` budgets (same order of magnitude as today’s screen-share camera request, not the previous 720p stage budget)
45
46#### Scenario: Stage locked to 720p
47
48- **WHEN** video quality is 720p and the user is subscribed to a stage camera tile
49- **THEN** the stage receive request uses 720p-class budgets
50
51### Requirement: Video quality setting is user-visible and persistent
52
53The product SHALL expose a video quality choice of Auto, 720p, and 1080p in the call/device camera controls, persist the choice across app restarts, and apply it to new captures and new stage subscriptions. Changing the setting while a call is active SHALL take effect for subsequent capture restarts and subsequent stage request updates without requiring an app relaunch.
54
55#### Scenario: Persist across restart
56
57- **WHEN** the user selects 1080p and later restarts the app
58- **THEN** video quality remains 1080p
59
60#### Scenario: Default is Auto
61
62- **WHEN** no prior video quality choice exists
63- **THEN** the effective choice is Auto
openspec/changes/camera-video-quality/tasks.md added +20 −0
@@ -0,0 +1,20 @@
1 # Tasks
2
3 ## 1. Qualitaetsmodell und Capture
4
5 - [x] 1.1 `VideoQuality` (Auto / 720 / 1080) und Ableitung der Capture-Decke in `calling` einfuehren; Verify: Unit-Test fuer Ceiling-Mapping
6 - [x] 1.2 `pick_format` / `fit_widescreen` / Open-Fallback auf die Decke umstellen (Preferenz 1080 bei Auto/1080); Verify: `cargo test -p calling --lib` Filter Formatwahl / widescreen
7 - [x] 1.3 Bestehende Capture-Tests an neue Preferenz anpassen; Verify: `cargo test -p calling --lib camera` (oder engerer Filter) gruen
8
9 ## 2. Send- und Stage-Limits
10
11 - [x] 2.1 Stage-Receive-Limits fuer Auto/1080 auf 1080p-Klasse setzen (`max-fs` 8160, kamerataugliches `max-fps`/`max-mbps`); 720 belaesst alte Stage-Budgets; Verify: Tests in `video_layout` fuer Stage-Body
12 - [x] 2.2 Send-Capabilities weiter an tatsaechliche Capture-Groesse koppeln und gegen Ceiling absichern; Verify: `send_capabilities_body`-Tests / Reporter
13 - [x] 2.3 Small-Tile- und Screen-Share-Limits unveraendert lassen; Verify: bestehende Assertions fuer Small/Screen weiterhin gruen
14
15 ## 3. Setting, UI, Apply im Call
16
17 - [x] 3.1 Videoqualitaet persistieren (Default Auto) analog Geraete-/Call-Settings; Verify: Roundtrip-Test oder Settings-Serialisierung
18 - [x] 3.2 Auswahl Auto/720p/1080p im Kamera-Menue (Call + Prejoin); Verify: manueller UI-Smoke oder View-Test falls vorhanden
19 - [x] 3.3 Wechsel der Stufe startet Capture neu und aktualisiert Stage-Requests ohne App-Neustart; Verify: gezielter calling/app-Test oder dokumentierter Smoke-Schritt
20 - [x] 3.4 Integration: `cargo test -p calling --lib` und relevante `cargo test -p app …`-Filter gruen
@@ -0,0 +1,20 @@
1# Tasks
2
3## 1. Qualitaetsmodell und Capture
4
5- [x] 1.1 `VideoQuality` (Auto / 720 / 1080) und Ableitung der Capture-Decke in `calling` einfuehren; Verify: Unit-Test fuer Ceiling-Mapping
6- [x] 1.2 `pick_format` / `fit_widescreen` / Open-Fallback auf die Decke umstellen (Preferenz 1080 bei Auto/1080); Verify: `cargo test -p calling --lib` Filter Formatwahl / widescreen
7- [x] 1.3 Bestehende Capture-Tests an neue Preferenz anpassen; Verify: `cargo test -p calling --lib camera` (oder engerer Filter) gruen
8
9## 2. Send- und Stage-Limits
10
11- [x] 2.1 Stage-Receive-Limits fuer Auto/1080 auf 1080p-Klasse setzen (`max-fs` 8160, kamerataugliches `max-fps`/`max-mbps`); 720 belaesst alte Stage-Budgets; Verify: Tests in `video_layout` fuer Stage-Body
12- [x] 2.2 Send-Capabilities weiter an tatsaechliche Capture-Groesse koppeln und gegen Ceiling absichern; Verify: `send_capabilities_body`-Tests / Reporter
13- [x] 2.3 Small-Tile- und Screen-Share-Limits unveraendert lassen; Verify: bestehende Assertions fuer Small/Screen weiterhin gruen
14
15## 3. Setting, UI, Apply im Call
16
17- [x] 3.1 Videoqualitaet persistieren (Default Auto) analog Geraete-/Call-Settings; Verify: Roundtrip-Test oder Settings-Serialisierung
18- [x] 3.2 Auswahl Auto/720p/1080p im Kamera-Menue (Call + Prejoin); Verify: manueller UI-Smoke oder View-Test falls vorhanden
19- [x] 3.3 Wechsel der Stufe startet Capture neu und aktualisiert Stage-Requests ohne App-Neustart; Verify: gezielter calling/app-Test oder dokumentierter Smoke-Schritt
20- [x] 3.4 Integration: `cargo test -p calling --lib` und relevante `cargo test -p app …`-Filter gruen