BlueGit

ict rusty-teams

feat(calls): 9 video slots in meetings

- offer 9 receive-only video lines (mids 2-10), the share line moves to mid 11
- the app sends the visible tiles (SetVideoWants), "+N" and hidden people get no slot
- stage tile asks for max-fs 3600, filmstrip and small tiles for 920
- a tile that changes size keeps its slot and picture
- offer layout, slot plan and request tests cover 9 slots

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-10-13 · 7 weeks ago

Hash
b608e9a149a5b8e88376d0abde6941aa6155a5ee
Parent
1136fb3e
11 files changed +353 −50
crates/app/src/call/demo.rs +1 −1
@@ -596,7 +596,7 @@ async fn speak_until_hangup(
596 596 people.iter().for_each(|(mri, _)| control.video.forget(&VideoKey::Person(mri.clone())));
597 597 control.send(CallUpdate::IncomingVideo(enabled));
598 598 }
599 Some(CallCommand::SetCameraEffects(_)) => {}
599 Some(CallCommand::SetCameraEffects(_) | CallCommand::SetVideoWants(_)) => {}
600 600 Some(CallCommand::SetRecording { on, .. }) => control.send(CallUpdate::Recording(on)),
601 601 Some(CallCommand::ConsentToRecording) => control.send(CallUpdate::ConsentRequired(false)),
602 602 Some(CallCommand::Hold(hold)) => control.send(CallUpdate::Hold(if hold { HoldState::Local } else { HoldState::Active })),
@@ -596,7 +596,7 @@ async fn speak_until_hangup(
596 people.iter().for_each(|(mri, _)| control.video.forget(&VideoKey::Person(mri.clone())));
596 people.iter().for_each(|(mri, _)| control.video.forget(&VideoKey::Person(mri.clone())));
597 control.send(CallUpdate::IncomingVideo(enabled));
597 control.send(CallUpdate::IncomingVideo(enabled));
598 }
598 }
599 Some(CallCommand::SetCameraEffects(_)) => {}
599 Some(CallCommand::SetCameraEffects(_) | CallCommand::SetVideoWants(_)) => {}
600 Some(CallCommand::SetRecording { on, .. }) => control.send(CallUpdate::Recording(on)),
600 Some(CallCommand::SetRecording { on, .. }) => control.send(CallUpdate::Recording(on)),
601 Some(CallCommand::ConsentToRecording) => control.send(CallUpdate::ConsentRequired(false)),
601 Some(CallCommand::ConsentToRecording) => control.send(CallUpdate::ConsentRequired(false)),
602 Some(CallCommand::Hold(hold)) => control.send(CallUpdate::Hold(if hold { HoldState::Local } else { HoldState::Active })),
602 Some(CallCommand::Hold(hold)) => control.send(CallUpdate::Hold(if hold { HoldState::Local } else { HoldState::Active })),
crates/app/src/call/mod.rs +1 −1
@@ -51,6 +51,6 @@ pub use model::{
51 51 pub use overlay::CallWindows;
52 52 pub use preview::{CameraPreview, preview_backgrounds};
53 53 pub use ring::{MissedCall, RingEntry, Rings};
54 pub use stage_layout::{FILMSTRIP_MAX, GALLERY_MAX, filmstrip, gallery_grid, split_overflow};
54 pub use stage_layout::{FILMSTRIP_MAX, Filmstrip, GALLERY_MAX, Overflow, filmstrip, gallery_grid, split_overflow};
55 55 pub use target::plan_for_chat;
56 56 pub use view_settings::{CallLayout, ViewSettings};
@@ -51,6 +51,6 @@ pub use model::{
51pub use overlay::CallWindows;
51pub use overlay::CallWindows;
52pub use preview::{CameraPreview, preview_backgrounds};
52pub use preview::{CameraPreview, preview_backgrounds};
53pub use ring::{MissedCall, RingEntry, Rings};
53pub use ring::{MissedCall, RingEntry, Rings};
54pub use stage_layout::{FILMSTRIP_MAX, GALLERY_MAX, filmstrip, gallery_grid, split_overflow};
54pub use stage_layout::{FILMSTRIP_MAX, Filmstrip, GALLERY_MAX, Overflow, filmstrip, gallery_grid, split_overflow};
55pub use target::plan_for_chat;
55pub use target::plan_for_chat;
56pub use view_settings::{CallLayout, ViewSettings};
56pub use view_settings::{CallLayout, ViewSettings};
crates/app/src/call/model.rs +3 −1
@@ -6,7 +6,7 @@ use std::time::{Duration, Instant};
6 6 use calling::{
7 7 CallCommand, CallState, CallUpdate, CameraDevice, CaptionEntry, CaptionState, ContentShare,
8 8 DeviceChoice, DeviceLists, EndKind, EndReason, HoldState, MeetingTarget, Progress, Reaction,
9 RosterEntry, ShareKind, ShareSource, SpeakingDetector, VideoHub,
9 RosterEntry, ShareKind, ShareSource, SpeakingDetector, VideoHub, VideoWant,
10 10 };
11 11 use tokio::sync::mpsc::UnboundedSender;
12 12
@@ -42,6 +42,7 @@ pub struct ActiveCall {
42 42 pub stage_fullscreen: bool,
43 43 pub fullscreen: Option<FullscreenState>,
44 44 pub stage_size: Rc<Cell<(f32, f32)>>,
45 pub sent_wants: Vec<VideoWant>,
45 46 pub bubbles: Vec<ChatBubble>,
46 47 pub share_menu_open: bool,
47 48 pub lobby_list_open: bool,
@@ -105,6 +106,7 @@ impl ActiveCall {
105 106 stage_fullscreen: false,
106 107 fullscreen: None,
107 108 stage_size: Rc::default(),
109 sent_wants: Vec::new(),
108 110 bubbles: Vec::new(),
109 111 share_menu_open: false,
110 112 lobby_list_open: false,
@@ -6,7 +6,7 @@ use std::time::{Duration, Instant};
6use calling::{
6use calling::{
7 CallCommand, CallState, CallUpdate, CameraDevice, CaptionEntry, CaptionState, ContentShare,
7 CallCommand, CallState, CallUpdate, CameraDevice, CaptionEntry, CaptionState, ContentShare,
8 DeviceChoice, DeviceLists, EndKind, EndReason, HoldState, MeetingTarget, Progress, Reaction,
8 DeviceChoice, DeviceLists, EndKind, EndReason, HoldState, MeetingTarget, Progress, Reaction,
9 RosterEntry, ShareKind, ShareSource, SpeakingDetector, VideoHub,
9 RosterEntry, ShareKind, ShareSource, SpeakingDetector, VideoHub, VideoWant,
10};
10};
11use tokio::sync::mpsc::UnboundedSender;
11use tokio::sync::mpsc::UnboundedSender;
12
12
@@ -42,6 +42,7 @@ pub struct ActiveCall {
42 pub stage_fullscreen: bool,
42 pub stage_fullscreen: bool,
43 pub fullscreen: Option<FullscreenState>,
43 pub fullscreen: Option<FullscreenState>,
44 pub stage_size: Rc<Cell<(f32, f32)>>,
44 pub stage_size: Rc<Cell<(f32, f32)>>,
45 pub sent_wants: Vec<VideoWant>,
45 pub bubbles: Vec<ChatBubble>,
46 pub bubbles: Vec<ChatBubble>,
46 pub share_menu_open: bool,
47 pub share_menu_open: bool,
47 pub lobby_list_open: bool,
48 pub lobby_list_open: bool,
@@ -105,6 +106,7 @@ impl ActiveCall {
105 stage_fullscreen: false,
106 stage_fullscreen: false,
106 fullscreen: None,
107 fullscreen: None,
107 stage_size: Rc::default(),
108 stage_size: Rc::default(),
109 sent_wants: Vec::new(),
108 bubbles: Vec::new(),
110 bubbles: Vec::new(),
109 share_menu_open: false,
111 share_menu_open: false,
110 lobby_list_open: false,
112 lobby_list_open: false,
crates/app/src/call/view_actions.rs +14 −0
@@ -1,11 +1,13 @@
1 1 use std::time::{Duration, Instant};
2 2
3 use calling::CallCommand;
3 4 use gpui_kit::*;
4 5
5 6 use super::bubbles::{BUBBLE_SHOWN, ChatBubble, push_bubble};
6 7 use super::fullscreen::{FullscreenState, HINT_SHOWN};
7 8 use super::view_settings::{CallLayout, ViewSettings};
8 9 use crate::app_state::{AppEvent, AppState};
10 use crate::views::call_layouts::{measured_stage, video_wants};
9 11
10 12 const CHROME_TOUCH_THROTTLE: Duration = Duration::from_millis(250);
11 13 const DEMO_BUBBLE_START: Duration = Duration::from_secs(8);
@@ -60,11 +62,23 @@ impl AppState {
60 62 .call
61 63 .as_mut()
62 64 .is_some_and(|call| call.model.refresh_layout(Instant::now()));
65 self.sync_video_wants();
63 66 if changed {
64 67 cx.notify();
65 68 }
66 69 }
67 70
71 fn sync_video_wants(&mut self) {
72 let Some(call) = self.call.as_mut() else {
73 return;
74 };
75 let wants = video_wants(&call.model, measured_stage(call));
76 if wants != call.sent_wants {
77 let _ = call.commands.send(CallCommand::SetVideoWants(wants.clone()));
78 call.sent_wants = wants;
79 }
80 }
81
68 82 pub fn toggle_call_fullscreen(&mut self, cx: &mut Context<Self>) {
69 83 let Some(call) = self.call.as_mut().filter(|call| call.viewing) else {
70 84 return;
@@ -1,11 +1,13 @@
1use std::time::{Duration, Instant};
1use std::time::{Duration, Instant};
2
2
3use calling::CallCommand;
3use gpui_kit::*;
4use gpui_kit::*;
4
5
5use super::bubbles::{BUBBLE_SHOWN, ChatBubble, push_bubble};
6use super::bubbles::{BUBBLE_SHOWN, ChatBubble, push_bubble};
6use super::fullscreen::{FullscreenState, HINT_SHOWN};
7use super::fullscreen::{FullscreenState, HINT_SHOWN};
7use super::view_settings::{CallLayout, ViewSettings};
8use super::view_settings::{CallLayout, ViewSettings};
8use crate::app_state::{AppEvent, AppState};
9use crate::app_state::{AppEvent, AppState};
10use crate::views::call_layouts::{measured_stage, video_wants};
9
11
10const CHROME_TOUCH_THROTTLE: Duration = Duration::from_millis(250);
12const CHROME_TOUCH_THROTTLE: Duration = Duration::from_millis(250);
11const DEMO_BUBBLE_START: Duration = Duration::from_secs(8);
13const DEMO_BUBBLE_START: Duration = Duration::from_secs(8);
@@ -60,11 +62,23 @@ impl AppState {
60 .call
62 .call
61 .as_mut()
63 .as_mut()
62 .is_some_and(|call| call.model.refresh_layout(Instant::now()));
64 .is_some_and(|call| call.model.refresh_layout(Instant::now()));
65 self.sync_video_wants();
63 if changed {
66 if changed {
64 cx.notify();
67 cx.notify();
65 }
68 }
66 }
69 }
67
70
71 fn sync_video_wants(&mut self) {
72 let Some(call) = self.call.as_mut() else {
73 return;
74 };
75 let wants = video_wants(&call.model, measured_stage(call));
76 if wants != call.sent_wants {
77 let _ = call.commands.send(CallCommand::SetVideoWants(wants.clone()));
78 call.sent_wants = wants;
79 }
80 }
81
68 pub fn toggle_call_fullscreen(&mut self, cx: &mut Context<Self>) {
82 pub fn toggle_call_fullscreen(&mut self, cx: &mut Context<Self>) {
69 let Some(call) = self.call.as_mut().filter(|call| call.viewing) else {
83 let Some(call) = self.call.as_mut().filter(|call| call.viewing) else {
70 return;
84 return;
crates/app/src/views/call_layouts.rs +168 −15
@@ -19,9 +19,10 @@ use super::call_view::{
19 19 use super::widgets::icon;
20 20 use crate::app_state::AppState;
21 21 use crate::call::{
22 ActiveCall, CallLayout, CallModel, FILMSTRIP_MAX, GALLERY_MAX, Tile, TileSize, filmstrip, gallery_grid,
23 shown_bubbles, split_overflow,
22 ActiveCall, CallLayout, CallModel, FILMSTRIP_MAX, Filmstrip, Focus, GALLERY_MAX, Overflow, Tile, TileSize,
23 filmstrip, gallery_grid, shown_bubbles, split_overflow,
24 24 };
25 use calling::{TileDetail, VideoWant};
25 26 use crate::theme;
26 27
27 28 const FALLBACK_STAGE: (f32, f32) = (900., 560.);
@@ -43,7 +44,7 @@ const BUBBLE_BACKGROUND: f32 = 0.72;
43 44 const CHIP_BACKGROUND: f32 = 0.6;
44 45 pub const FULLSCREEN_HINT: &str = "Press Esc to exit full screen";
45 46
46 fn measured_stage(call: &ActiveCall) -> (f32, f32) {
47 pub fn measured_stage(call: &ActiveCall) -> (f32, f32) {
47 48 let (width, height) = call.stage_size.get();
48 49 if width < 1. || height < 1. {
49 50 return FALLBACK_STAGE;
@@ -357,6 +358,12 @@ fn rows_of(cells: Vec<AnyElement>, columns: usize) -> Vec<Div> {
357 358 }
358 359 }
359 360
361 fn gallery_split(model: &CallModel) -> (Vec<&Tile>, Overflow) {
362 let others = model.layout_tiles();
363 let overflow = split_overflow(others.len(), model.own_cells(), GALLERY_MAX);
364 (others, overflow)
365 }
366
360 367 fn gallery_body(
361 368 app: &Entity<AppState>,
362 369 state: &AppState,
@@ -364,9 +371,8 @@ fn gallery_body(
364 371 now: Instant,
365 372 stage: (f32, f32),
366 373 ) -> AnyElement {
367 let others = model.layout_tiles();
374 let (others, overflow) = gallery_split(model);
368 375 let own_cells = model.own_cells();
369 let overflow = split_overflow(others.len(), own_cells, GALLERY_MAX);
370 376 let cells = overflow.shown + own_cells + usize::from(overflow.hidden > 0);
371 377 let grid = gallery_grid(
372 378 cells,
@@ -399,18 +405,16 @@ fn gallery_body(
399 405 .into_any_element()
400 406 }
401 407
402 fn speaker_body(
403 app: &Entity<AppState>,
404 state: &AppState,
405 model: &CallModel,
406 now: Instant,
407 stage: (f32, f32),
408 ) -> AnyElement {
408 struct SpeakerSplit<'a> {
409 focus: Option<Focus>,
410 others: Vec<&'a Tile>,
411 own_cells: usize,
412 plan: Filmstrip,
413 }
414
415 fn speaker_split(model: &CallModel, stage: (f32, f32)) -> SpeakerSplit<'_> {
409 416 let focus = model.speaker_focus();
410 417 let focus_mri = focus.as_ref().map(|focus| focus.mri.as_str());
411 let main = focus
412 .as_ref()
413 .and_then(|focus| render_focus_stage(app, state, focus, now));
414 418 let mut others: Vec<&Tile> = model
415 419 .layout_tiles()
416 420 .into_iter()
@@ -427,6 +431,20 @@ fn speaker_body(
427 431 if plan.overflow.shown < FILMSTRIP_MAX.min(others.len()) {
428 432 others.sort_by_key(|tile| !model.is_recent_speaker(&tile.mri));
429 433 }
434 SpeakerSplit { focus, others, own_cells, plan }
435 }
436
437 fn speaker_body(
438 app: &Entity<AppState>,
439 state: &AppState,
440 model: &CallModel,
441 now: Instant,
442 stage: (f32, f32),
443 ) -> AnyElement {
444 let SpeakerSplit { focus, others, own_cells, plan } = speaker_split(model, stage);
445 let main = focus
446 .as_ref()
447 .and_then(|focus| render_focus_stage(app, state, focus, now));
430 448 let size = TileSize::sixteen_by_nine(plan.tile_width.floor());
431 449 let shown = &others[..plan.overflow.shown];
432 450 let mut tiles: Vec<AnyElement> = shown
@@ -523,6 +541,39 @@ fn share_body(
523 541 .into_any_element()
524 542 }
525 543
544 const LARGE_GALLERY_TILES: usize = 4;
545
546 fn want(tile: &Tile, detail: TileDetail) -> VideoWant {
547 VideoWant { mri: tile.mri.clone(), detail }
548 }
549
550 pub fn video_wants(model: &CallModel, stage: (f32, f32)) -> Vec<VideoWant> {
551 if model.has_content() {
552 if model.effective_layout() == CallLayout::Content {
553 return Vec::new();
554 }
555 return model
556 .strip_tiles()
557 .into_iter()
558 .filter(|tile| !model.hidden_for_no_video(tile))
559 .map(|tile| want(tile, TileDetail::Small))
560 .collect();
561 }
562 if model.effective_layout() == CallLayout::Speaker {
563 let split = speaker_split(model, stage);
564 let stage_person = split.focus.iter().filter(|focus| !focus.own).map(|focus| VideoWant {
565 mri: focus.mri.clone(),
566 detail: TileDetail::Stage,
567 });
568 return stage_person
569 .chain(split.others[..split.plan.overflow.shown].iter().map(|tile| want(tile, TileDetail::Small)))
570 .collect();
571 }
572 let (others, overflow) = gallery_split(model);
573 let detail = if overflow.shown <= LARGE_GALLERY_TILES { TileDetail::Stage } else { TileDetail::Small };
574 others[..overflow.shown].iter().map(|tile| want(tile, detail)).collect()
575 }
576
526 577 pub(super) fn stage_region(
527 578 app: &Entity<AppState>,
528 579 state: &AppState,
@@ -561,3 +612,105 @@ pub(super) fn stage_region(
561 612 )
562 613 .into_any_element()
563 614 }
615
616 #[cfg(test)]
617 mod tests {
618 use std::time::Instant;
619
620 use calling::{CallUpdate, RosterEntry, TileDetail, VideoWant};
621
622 use super::{
623 CallLayout, CallModel, FILMSTRIP_TILE_MAX, GALLERY_MAX, GRID_PADDING, TILE_GAP, filmstrip, split_overflow,
624 video_wants,
625 };
626
627 const STAGE: (f32, f32) = (1400., 800.);
628
629 fn person(index: usize, has_video: bool) -> RosterEntry {
630 RosterEntry {
631 mri: format!("8:orgid:p{index}"),
632 display_name: format!("P{index}"),
633 muted: false,
634 in_lobby: false,
635 has_video,
636 sharing: false,
637 hand: None,
638 spotlight: None,
639 organizer: false,
640 }
641 }
642
643 fn meeting(people: Vec<RosterEntry>) -> CallModel {
644 let mut model = CallModel::meeting("Standup", false);
645 model.apply(CallUpdate::OwnIdentity { mri: "8:orgid:me".into() });
646 model.apply(CallUpdate::Roster(people));
647 model
648 }
649
650 fn crowd(count: usize) -> CallModel {
651 meeting((0..count).map(|index| person(index, true)).collect())
652 }
653
654 fn details(wants: &[VideoWant]) -> Vec<TileDetail> {
655 wants.iter().map(|want| want.detail).collect()
656 }
657
658 #[test]
659 fn a_small_gallery_asks_for_large_pictures() {
660 let wants = video_wants(&crowd(3), STAGE);
661 assert_eq!(wants.len(), 3);
662 assert!(details(&wants).iter().all(|detail| *detail == TileDetail::Stage));
663 }
664
665 #[test]
666 fn a_big_gallery_asks_for_small_pictures_and_skips_the_plus_n_people() {
667 let model = crowd(14);
668 let wants = video_wants(&model, STAGE);
669 assert_eq!(wants.len(), split_overflow(14, 1, GALLERY_MAX).shown);
670 assert!(details(&wants).iter().all(|detail| *detail == TileDetail::Small));
671 let hidden: Vec<&str> = model.layout_tiles()[wants.len()..].iter().map(|tile| tile.mri.as_str()).collect();
672 assert!(wants.iter().all(|want| !hidden.contains(&want.mri.as_str())));
673 }
674
675 #[test]
676 fn people_hidden_for_having_no_video_get_no_picture_request() {
677 let mut model = meeting(vec![person(0, true), person(1, false), person(2, false)]);
678 model.view.hide_no_video = true;
679 let wants = video_wants(&model, STAGE);
680 assert_eq!(wants.iter().map(|want| want.mri.as_str()).collect::<Vec<_>>(), vec!["8:orgid:p0"]);
681 }
682
683 #[test]
684 fn the_speaker_stage_is_large_and_the_filmstrip_small() {
685 let mut model = crowd(5);
686 model.view.choose(CallLayout::Speaker);
687 model.refresh_layout(Instant::now());
688 let focus = model.speaker_focus().expect("a stage person").mri;
689 let wants = video_wants(&model, STAGE);
690 assert_eq!(wants[0], VideoWant { mri: focus.clone(), detail: TileDetail::Stage });
691 assert_eq!(wants.len(), 5);
692 assert!(wants[1..].iter().all(|want| want.detail == TileDetail::Small && want.mri != focus));
693 }
694
695 #[test]
696 fn the_speaker_filmstrip_drops_people_that_do_not_fit() {
697 let mut model = crowd(12);
698 model.view.choose(CallLayout::Speaker);
699 model.refresh_layout(Instant::now());
700 let wants = video_wants(&model, (500., 800.));
701 let fitting = filmstrip(11, 1, 500. - 2. * GRID_PADDING, TILE_GAP, FILMSTRIP_TILE_MAX).overflow.shown;
702 assert!(fitting < 11);
703 assert_eq!(wants.len(), 1 + fitting);
704 }
705
706 #[test]
707 fn next_to_shared_content_everybody_in_the_strip_is_small_and_content_focus_wants_nobody() {
708 let mut model = crowd(3);
709 model.apply(CallUpdate::ScreenShare(Some("8:orgid:p1".into())));
710 let wants = video_wants(&model, STAGE);
711 assert_eq!(wants.len(), 3);
712 assert!(details(&wants).iter().all(|detail| *detail == TileDetail::Small));
713 model.view.choose(CallLayout::Content);
714 assert!(video_wants(&model, STAGE).is_empty());
715 }
716 }
@@ -19,9 +19,10 @@ use super::call_view::{
19use super::widgets::icon;
19use super::widgets::icon;
20use crate::app_state::AppState;
20use crate::app_state::AppState;
21use crate::call::{
21use crate::call::{
22 ActiveCall, CallLayout, CallModel, FILMSTRIP_MAX, GALLERY_MAX, Tile, TileSize, filmstrip, gallery_grid,
22 ActiveCall, CallLayout, CallModel, FILMSTRIP_MAX, Filmstrip, Focus, GALLERY_MAX, Overflow, Tile, TileSize,
23 shown_bubbles, split_overflow,
23 filmstrip, gallery_grid, shown_bubbles, split_overflow,
24};
24};
25use calling::{TileDetail, VideoWant};
25use crate::theme;
26use crate::theme;
26
27
27const FALLBACK_STAGE: (f32, f32) = (900., 560.);
28const FALLBACK_STAGE: (f32, f32) = (900., 560.);
@@ -43,7 +44,7 @@ const BUBBLE_BACKGROUND: f32 = 0.72;
43const CHIP_BACKGROUND: f32 = 0.6;
44const CHIP_BACKGROUND: f32 = 0.6;
44pub const FULLSCREEN_HINT: &str = "Press Esc to exit full screen";
45pub const FULLSCREEN_HINT: &str = "Press Esc to exit full screen";
45
46
46fn measured_stage(call: &ActiveCall) -> (f32, f32) {
47pub fn measured_stage(call: &ActiveCall) -> (f32, f32) {
47 let (width, height) = call.stage_size.get();
48 let (width, height) = call.stage_size.get();
48 if width < 1. || height < 1. {
49 if width < 1. || height < 1. {
49 return FALLBACK_STAGE;
50 return FALLBACK_STAGE;
@@ -357,6 +358,12 @@ fn rows_of(cells: Vec<AnyElement>, columns: usize) -> Vec<Div> {
357 }
358 }
358}
359}
359
360
361fn gallery_split(model: &CallModel) -> (Vec<&Tile>, Overflow) {
362 let others = model.layout_tiles();
363 let overflow = split_overflow(others.len(), model.own_cells(), GALLERY_MAX);
364 (others, overflow)
365}
366
360fn gallery_body(
367fn gallery_body(
361 app: &Entity<AppState>,
368 app: &Entity<AppState>,
362 state: &AppState,
369 state: &AppState,
@@ -364,9 +371,8 @@ fn gallery_body(
364 now: Instant,
371 now: Instant,
365 stage: (f32, f32),
372 stage: (f32, f32),
366) -> AnyElement {
373) -> AnyElement {
367 let others = model.layout_tiles();
374 let (others, overflow) = gallery_split(model);
368 let own_cells = model.own_cells();
375 let own_cells = model.own_cells();
369 let overflow = split_overflow(others.len(), own_cells, GALLERY_MAX);
370 let cells = overflow.shown + own_cells + usize::from(overflow.hidden > 0);
376 let cells = overflow.shown + own_cells + usize::from(overflow.hidden > 0);
371 let grid = gallery_grid(
377 let grid = gallery_grid(
372 cells,
378 cells,
@@ -399,18 +405,16 @@ fn gallery_body(
399 .into_any_element()
405 .into_any_element()
400}
406}
401
407
402fn speaker_body(
408struct SpeakerSplit<'a> {
403 app: &Entity<AppState>,
409 focus: Option<Focus>,
404 state: &AppState,
410 others: Vec<&'a Tile>,
405 model: &CallModel,
411 own_cells: usize,
406 now: Instant,
412 plan: Filmstrip,
407 stage: (f32, f32),
413}
408) -> AnyElement {
414
415fn speaker_split(model: &CallModel, stage: (f32, f32)) -> SpeakerSplit<'_> {
409 let focus = model.speaker_focus();
416 let focus = model.speaker_focus();
410 let focus_mri = focus.as_ref().map(|focus| focus.mri.as_str());
417 let focus_mri = focus.as_ref().map(|focus| focus.mri.as_str());
411 let main = focus
412 .as_ref()
413 .and_then(|focus| render_focus_stage(app, state, focus, now));
414 let mut others: Vec<&Tile> = model
418 let mut others: Vec<&Tile> = model
415 .layout_tiles()
419 .layout_tiles()
416 .into_iter()
420 .into_iter()
@@ -427,6 +431,20 @@ fn speaker_body(
427 if plan.overflow.shown < FILMSTRIP_MAX.min(others.len()) {
431 if plan.overflow.shown < FILMSTRIP_MAX.min(others.len()) {
428 others.sort_by_key(|tile| !model.is_recent_speaker(&tile.mri));
432 others.sort_by_key(|tile| !model.is_recent_speaker(&tile.mri));
429 }
433 }
434 SpeakerSplit { focus, others, own_cells, plan }
435}
436
437fn speaker_body(
438 app: &Entity<AppState>,
439 state: &AppState,
440 model: &CallModel,
441 now: Instant,
442 stage: (f32, f32),
443) -> AnyElement {
444 let SpeakerSplit { focus, others, own_cells, plan } = speaker_split(model, stage);
445 let main = focus
446 .as_ref()
447 .and_then(|focus| render_focus_stage(app, state, focus, now));
430 let size = TileSize::sixteen_by_nine(plan.tile_width.floor());
448 let size = TileSize::sixteen_by_nine(plan.tile_width.floor());
431 let shown = &others[..plan.overflow.shown];
449 let shown = &others[..plan.overflow.shown];
432 let mut tiles: Vec<AnyElement> = shown
450 let mut tiles: Vec<AnyElement> = shown
@@ -523,6 +541,39 @@ fn share_body(
523 .into_any_element()
541 .into_any_element()
524}
542}
525
543
544const LARGE_GALLERY_TILES: usize = 4;
545
546fn want(tile: &Tile, detail: TileDetail) -> VideoWant {
547 VideoWant { mri: tile.mri.clone(), detail }
548}
549
550pub fn video_wants(model: &CallModel, stage: (f32, f32)) -> Vec<VideoWant> {
551 if model.has_content() {
552 if model.effective_layout() == CallLayout::Content {
553 return Vec::new();
554 }
555 return model
556 .strip_tiles()
557 .into_iter()
558 .filter(|tile| !model.hidden_for_no_video(tile))
559 .map(|tile| want(tile, TileDetail::Small))
560 .collect();
561 }
562 if model.effective_layout() == CallLayout::Speaker {
563 let split = speaker_split(model, stage);
564 let stage_person = split.focus.iter().filter(|focus| !focus.own).map(|focus| VideoWant {
565 mri: focus.mri.clone(),
566 detail: TileDetail::Stage,
567 });
568 return stage_person
569 .chain(split.others[..split.plan.overflow.shown].iter().map(|tile| want(tile, TileDetail::Small)))
570 .collect();
571 }
572 let (others, overflow) = gallery_split(model);
573 let detail = if overflow.shown <= LARGE_GALLERY_TILES { TileDetail::Stage } else { TileDetail::Small };
574 others[..overflow.shown].iter().map(|tile| want(tile, detail)).collect()
575}
576
526pub(super) fn stage_region(
577pub(super) fn stage_region(
527 app: &Entity<AppState>,
578 app: &Entity<AppState>,
528 state: &AppState,
579 state: &AppState,
@@ -561,3 +612,105 @@ pub(super) fn stage_region(
561 )
612 )
562 .into_any_element()
613 .into_any_element()
563}
614}
615
616#[cfg(test)]
617mod tests {
618 use std::time::Instant;
619
620 use calling::{CallUpdate, RosterEntry, TileDetail, VideoWant};
621
622 use super::{
623 CallLayout, CallModel, FILMSTRIP_TILE_MAX, GALLERY_MAX, GRID_PADDING, TILE_GAP, filmstrip, split_overflow,
624 video_wants,
625 };
626
627 const STAGE: (f32, f32) = (1400., 800.);
628
629 fn person(index: usize, has_video: bool) -> RosterEntry {
630 RosterEntry {
631 mri: format!("8:orgid:p{index}"),
632 display_name: format!("P{index}"),
633 muted: false,
634 in_lobby: false,
635 has_video,
636 sharing: false,
637 hand: None,
638 spotlight: None,
639 organizer: false,
640 }
641 }
642
643 fn meeting(people: Vec<RosterEntry>) -> CallModel {
644 let mut model = CallModel::meeting("Standup", false);
645 model.apply(CallUpdate::OwnIdentity { mri: "8:orgid:me".into() });
646 model.apply(CallUpdate::Roster(people));
647 model
648 }
649
650 fn crowd(count: usize) -> CallModel {
651 meeting((0..count).map(|index| person(index, true)).collect())
652 }
653
654 fn details(wants: &[VideoWant]) -> Vec<TileDetail> {
655 wants.iter().map(|want| want.detail).collect()
656 }
657
658 #[test]
659 fn a_small_gallery_asks_for_large_pictures() {
660 let wants = video_wants(&crowd(3), STAGE);
661 assert_eq!(wants.len(), 3);
662 assert!(details(&wants).iter().all(|detail| *detail == TileDetail::Stage));
663 }
664
665 #[test]
666 fn a_big_gallery_asks_for_small_pictures_and_skips_the_plus_n_people() {
667 let model = crowd(14);
668 let wants = video_wants(&model, STAGE);
669 assert_eq!(wants.len(), split_overflow(14, 1, GALLERY_MAX).shown);
670 assert!(details(&wants).iter().all(|detail| *detail == TileDetail::Small));
671 let hidden: Vec<&str> = model.layout_tiles()[wants.len()..].iter().map(|tile| tile.mri.as_str()).collect();
672 assert!(wants.iter().all(|want| !hidden.contains(&want.mri.as_str())));
673 }
674
675 #[test]
676 fn people_hidden_for_having_no_video_get_no_picture_request() {
677 let mut model = meeting(vec![person(0, true), person(1, false), person(2, false)]);
678 model.view.hide_no_video = true;
679 let wants = video_wants(&model, STAGE);
680 assert_eq!(wants.iter().map(|want| want.mri.as_str()).collect::<Vec<_>>(), vec!["8:orgid:p0"]);
681 }
682
683 #[test]
684 fn the_speaker_stage_is_large_and_the_filmstrip_small() {
685 let mut model = crowd(5);
686 model.view.choose(CallLayout::Speaker);
687 model.refresh_layout(Instant::now());
688 let focus = model.speaker_focus().expect("a stage person").mri;
689 let wants = video_wants(&model, STAGE);
690 assert_eq!(wants[0], VideoWant { mri: focus.clone(), detail: TileDetail::Stage });
691 assert_eq!(wants.len(), 5);
692 assert!(wants[1..].iter().all(|want| want.detail == TileDetail::Small && want.mri != focus));
693 }
694
695 #[test]
696 fn the_speaker_filmstrip_drops_people_that_do_not_fit() {
697 let mut model = crowd(12);
698 model.view.choose(CallLayout::Speaker);
699 model.refresh_layout(Instant::now());
700 let wants = video_wants(&model, (500., 800.));
701 let fitting = filmstrip(11, 1, 500. - 2. * GRID_PADDING, TILE_GAP, FILMSTRIP_TILE_MAX).overflow.shown;
702 assert!(fitting < 11);
703 assert_eq!(wants.len(), 1 + fitting);
704 }
705
706 #[test]
707 fn next_to_shared_content_everybody_in_the_strip_is_small_and_content_focus_wants_nobody() {
708 let mut model = crowd(3);
709 model.apply(CallUpdate::ScreenShare(Some("8:orgid:p1".into())));
710 let wants = video_wants(&model, STAGE);
711 assert_eq!(wants.len(), 3);
712 assert!(details(&wants).iter().all(|detail| *detail == TileDetail::Small));
713 model.view.choose(CallLayout::Content);
714 assert!(video_wants(&model, STAGE).is_empty());
715 }
716}
crates/calling/src/call.rs +5 −0
@@ -1535,6 +1535,11 @@ async fn drive(
1535 1535 send_receive_change(control, video.reselect(&roster));
1536 1536 control.send(CallUpdate::IncomingVideo(enabled));
1537 1537 }
1538 Some(CallCommand::SetVideoWants(wants)) => {
1539 if video.set_wants(wants) {
1540 send_receive_change(control, video.reselect(&roster));
1541 }
1542 }
1538 1543 Some(CallCommand::SetCameraEffects(effects)) => local_video.set_effects(effects),
1539 1544 Some(CallCommand::SendReaction(reaction)) => {
1540 1545 if let Err(error) = remote.signaling.send_reaction(&remote.conversation, &remote.participant, reaction).await {
@@ -1535,6 +1535,11 @@ async fn drive(
1535 send_receive_change(control, video.reselect(&roster));
1535 send_receive_change(control, video.reselect(&roster));
1536 control.send(CallUpdate::IncomingVideo(enabled));
1536 control.send(CallUpdate::IncomingVideo(enabled));
1537 }
1537 }
1538 Some(CallCommand::SetVideoWants(wants)) => {
1539 if video.set_wants(wants) {
1540 send_receive_change(control, video.reselect(&roster));
1541 }
1542 }
1538 Some(CallCommand::SetCameraEffects(effects)) => local_video.set_effects(effects),
1543 Some(CallCommand::SetCameraEffects(effects)) => local_video.set_effects(effects),
1539 Some(CallCommand::SendReaction(reaction)) => {
1544 Some(CallCommand::SendReaction(reaction)) => {
1540 if let Err(error) = remote.signaling.send_reaction(&remote.conversation, &remote.participant, reaction).await {
1545 if let Err(error) = remote.signaling.send_reaction(&remote.conversation, &remote.participant, reaction).await {
crates/calling/src/control.rs +2 −0
@@ -19,6 +19,7 @@ use crate::camera::CameraDevice;
19 19 use crate::screen::ShareSource;
20 20 use crate::signaling::{Callee, MeetingTarget};
21 21 use crate::state::CallState;
22 use crate::video_layout::VideoWant;
22 23 use crate::video_frame::VideoHub;
23 24 use crate::whiteboard::ContentShare;
24 25
@@ -49,6 +50,7 @@ pub enum CallCommand {
49 50 SetCaptions(bool),
50 51 SetBackground(BackgroundChoice),
51 52 SetIncomingVideo(bool),
53 SetVideoWants(Vec<VideoWant>),
52 54 SetCameraEffects(CameraEffects),
53 55 SendReaction(Reaction),
54 56 SetRecording { on: bool, title: String },
@@ -19,6 +19,7 @@ use crate::camera::CameraDevice;
19use crate::screen::ShareSource;
19use crate::screen::ShareSource;
20use crate::signaling::{Callee, MeetingTarget};
20use crate::signaling::{Callee, MeetingTarget};
21use crate::state::CallState;
21use crate::state::CallState;
22use crate::video_layout::VideoWant;
22use crate::video_frame::VideoHub;
23use crate::video_frame::VideoHub;
23use crate::whiteboard::ContentShare;
24use crate::whiteboard::ContentShare;
24
25
@@ -49,6 +50,7 @@ pub enum CallCommand {
49 SetCaptions(bool),
50 SetCaptions(bool),
50 SetBackground(BackgroundChoice),
51 SetBackground(BackgroundChoice),
51 SetIncomingVideo(bool),
52 SetIncomingVideo(bool),
53 SetVideoWants(Vec<VideoWant>),
52 SetCameraEffects(CameraEffects),
54 SetCameraEffects(CameraEffects),
53 SendReaction(Reaction),
55 SendReaction(Reaction),
54 SetRecording { on: bool, title: String },
56 SetRecording { on: bool, title: String },
crates/calling/src/lib.rs +1 −0
@@ -76,6 +76,7 @@ pub use error::{Error, Result};
76 76 pub use level::SpeakingDetector;
77 77 pub use mic_processing::{ApmConfig, MicSettings, NoiseSuppression};
78 78 pub use mute::MuteCommand;
79 pub use video_layout::{TileDetail, VideoWant};
79 80 pub use state::{CallSignal, CallState, EndReason};
80 81 pub use camera::{CameraDevice, camera_entries};
81 82 pub use screen::{ShareKind, ShareSource};
@@ -76,6 +76,7 @@ pub use error::{Error, Result};
76pub use level::SpeakingDetector;
76pub use level::SpeakingDetector;
77pub use mic_processing::{ApmConfig, MicSettings, NoiseSuppression};
77pub use mic_processing::{ApmConfig, MicSettings, NoiseSuppression};
78pub use mute::MuteCommand;
78pub use mute::MuteCommand;
79pub use video_layout::{TileDetail, VideoWant};
79pub use state::{CallSignal, CallState, EndReason};
80pub use state::{CallSignal, CallState, EndReason};
80pub use camera::{CameraDevice, camera_entries};
81pub use camera::{CameraDevice, camera_entries};
81pub use screen::{ShareKind, ShareSource};
82pub use screen::{ShareKind, ShareSource};
crates/calling/src/video_layout.rs +121 −16
@@ -12,9 +12,9 @@ use crate::error::{Error, Result};
12 12 use crate::sdp::{LineRole, OfferPlan, StreamLine};
13 13 use crate::video_frame::VideoKey;
14 14
15 pub const RECEIVE_SLOTS: usize = 4;
15 pub const RECEIVE_SLOTS: usize = 9;
16 16 pub const CAMERA_MID: &str = "1";
17 pub const SHARE_MID: &str = "6";
17 pub const SHARE_MID: &str = "11";
18 18 pub const ONE_TO_ONE_SHARE_MID: &str = "2";
19 19 const CAMERA_LINE_LABEL: &str = "main-video";
20 20 const SHARE_LINE_LABEL: &str = "applicationsharing-video";
@@ -23,10 +23,33 @@ const SCREEN_STREAM: &str = "screen";
23 23 const H264: &str = "video/h264";
24 24 const RTX: &str = "video/rtx";
25 25 const NO_SOURCE: i64 = -1;
26 const PERSON_REQUEST: ReceiveLimits = ReceiveLimits { max_fs: 3600, max_fps: 3000, max_mbps: 108_000 };
26 const STAGE_REQUEST: ReceiveLimits = ReceiveLimits { max_fs: 3600, max_fps: 3000, max_mbps: 108_000 };
27 const SMALL_REQUEST: ReceiveLimits = ReceiveLimits { max_fs: 920, max_fps: 3000, max_mbps: 27_600 };
27 28 const SCREEN_REQUEST: ReceiveLimits = ReceiveLimits { max_fs: 8160, max_fps: 1500, max_mbps: 135_000 };
28 29 const SUBSCRIBE_PROFILE: &str = "64001f";
29 30
31 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
32 pub enum TileDetail {
33 #[default]
34 Stage,
35 Small,
36 }
37
38 impl TileDetail {
39 fn limits(self) -> ReceiveLimits {
40 match self {
41 TileDetail::Stage => STAGE_REQUEST,
42 TileDetail::Small => SMALL_REQUEST,
43 }
44 }
45 }
46
47 #[derive(Debug, Clone, PartialEq, Eq)]
48 pub struct VideoWant {
49 pub mri: String,
50 pub detail: TileDetail,
51 }
52
30 53 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
31 54 struct ReceiveLimits {
32 55 max_fs: u32,
@@ -48,7 +71,7 @@ pub fn one_to_one_plan() -> OfferPlan {
48 71 }
49 72 }
50 73
51 /// Offered after the audio line: camera, `RECEIVE_SLOTS` receive-only slots, screen share (mids 1, 2-5, 6).
74 /// Offered after the audio line: camera, `RECEIVE_SLOTS` receive-only slots, screen share (mids 1, 2-10, 11).
52 75 #[derive(Clone)]
53 76 pub struct VideoLines {
54 77 pub camera: RtpTransceiver,
@@ -178,16 +201,26 @@ impl SlotTable {
178 201 pub struct Assignment {
179 202 pub mri: String,
180 203 pub source: u32,
204 pub detail: TileDetail,
205 }
206
207 impl Assignment {
208 fn same_source(&self, other: &Assignment) -> bool {
209 self.mri == other.mri && self.source == other.source
210 }
181 211 }
182 212
183 213 pub fn plan_receive(current: &[Option<Assignment>], candidates: &[Assignment]) -> Vec<Option<Assignment>> {
184 214 let wanted: Vec<&Assignment> = candidates.iter().take(current.len()).collect();
185 215 let mut next: Vec<Option<Assignment>> = current
186 216 .iter()
187 .map(|slot| slot.clone().filter(|held| wanted.contains(&held)))
217 .map(|slot| {
218 let held = slot.as_ref()?;
219 wanted.iter().find(|assignment| assignment.same_source(held)).map(|assignment| (*assignment).clone())
220 })
188 221 .collect();
189 222 for assignment in wanted {
190 if next.iter().flatten().any(|held| held == assignment) {
223 if next.iter().flatten().any(|held| held.same_source(assignment)) {
191 224 continue;
192 225 }
193 226 if let Some(free) = next.iter_mut().find(|slot| slot.is_none()) {
@@ -197,11 +230,20 @@ pub fn plan_receive(current: &[Option<Assignment>], candidates: &[Assignment]) -
197 230 next
198 231 }
199 232
200 pub fn prioritize(candidates: Vec<(String, u32)>, speaker_history: &[String]) -> Vec<Assignment> {
233 pub fn prioritize(candidates: Vec<(String, u32)>, speaker_history: &[String], wants: Option<&[VideoWant]>) -> Vec<Assignment> {
234 if let Some(wants) = wants {
235 return wants
236 .iter()
237 .filter_map(|want| {
238 let (mri, source) = candidates.iter().find(|(mri, _)| *mri == want.mri)?;
239 Some(Assignment { mri: mri.clone(), source: *source, detail: want.detail })
240 })
241 .collect();
242 }
201 243 let rank = |mri: &str| speaker_history.iter().position(|speaker| speaker == mri).unwrap_or(usize::MAX);
202 244 let mut ordered: Vec<Assignment> = candidates
203 245 .into_iter()
204 .map(|(mri, source)| Assignment { mri, source })
246 .map(|(mri, source)| Assignment { mri, source, detail: TileDetail::Stage })
205 247 .collect();
206 248 ordered.sort_by_key(|assignment| rank(&assignment.mri));
207 249 ordered
@@ -213,6 +255,7 @@ pub struct SourceRequest {
213 255 pub stream_id: u32,
214 256 pub source: Option<u32>,
215 257 pub screen: bool,
258 pub detail: TileDetail,
216 259 }
217 260
218 261 pub fn requests_for(
@@ -229,6 +272,7 @@ pub fn requests_for(
229 272 stream_id: slot.stream_id,
230 273 source: after.as_ref().map(|assignment| assignment.source),
231 274 screen: false,
275 detail: after.as_ref().map(|assignment| assignment.detail).unwrap_or_default(),
232 276 })
233 277 .collect()
234 278 }
@@ -236,7 +280,7 @@ pub fn requests_for(
236 280 impl SourceRequest {
237 281 /// Body of the `applyChannelParameters` link, the signaling twin of the data-channel `sr` message.
238 282 pub fn body(&self, sequence_number: u64) -> Value {
239 let limits = if self.screen { SCREEN_REQUEST } else { PERSON_REQUEST };
283 let limits = if self.screen { SCREEN_REQUEST } else { self.detail.limits() };
240 284 let control = json!({
241 285 "controlVideoStreaming": {
242 286 "sequenceNumber": sequence_number,
@@ -287,7 +331,7 @@ mod tests {
287 331 use super::*;
288 332
289 333 fn assignment(name: &str, source: u32) -> Assignment {
290 Assignment { mri: format!("8:orgid:{name}"), source }
334 Assignment { mri: format!("8:orgid:{name}"), source, detail: TileDetail::Stage }
291 335 }
292 336
293 337 fn stream(mid: &str, role: LineRole, id: Option<u32>) -> StreamLine {
@@ -303,12 +347,12 @@ mod tests {
303 347 stream("3", LineRole::MainVideo, Some(204)),
304 348 stream("4", LineRole::MainVideo, None),
305 349 stream("5", LineRole::MainVideo, Some(206)),
306 stream("6", LineRole::ScreenShare, Some(207)),
350 stream("11", LineRole::ScreenShare, Some(207)),
307 351 ];
308 352 let table = SlotTable::from_streams(&streams);
309 353 let mids: Vec<&str> = table.people.iter().map(|slot| slot.mid.as_str()).collect();
310 354 assert_eq!(mids, vec!["2", "3", "5"]);
311 assert_eq!(table.screen, Some(ReceiveSlot { mid: "6".into(), stream_id: 207 }));
355 assert_eq!(table.screen, Some(ReceiveSlot { mid: "11".into(), stream_id: 207 }));
312 356 }
313 357
314 358 #[test]
@@ -327,7 +371,7 @@ mod tests {
327 371 let held: Vec<Option<Assignment>> = (1..=4).map(|index| Some(assignment(&format!("p{index}"), index))).collect();
328 372 let history = vec!["8:orgid:p5".to_owned(), "8:orgid:p1".to_owned(), "8:orgid:p2".to_owned(), "8:orgid:p3".to_owned()];
329 373 let roster = (1..=5).map(|index| (format!("8:orgid:p{index}"), index)).collect();
330 let next = plan_receive(&held, &prioritize(roster, &history));
374 let next = plan_receive(&held, &prioritize(roster, &history, None));
331 375 let names: Vec<&str> = next.iter().flatten().map(|held| held.mri.as_str()).collect();
332 376 assert_eq!(names, vec!["8:orgid:p1", "8:orgid:p2", "8:orgid:p3", "8:orgid:p5"]);
333 377 }
@@ -342,12 +386,12 @@ mod tests {
342 386 ReceiveSlot { mid: "3".into(), stream_id: 204 },
343 387 ];
344 388 let requests = requests_for(&held, &next, &slots);
345 assert_eq!(requests, vec![SourceRequest { mid: "2".into(), stream_id: 203, source: None, screen: false }]);
389 assert_eq!(requests, vec![SourceRequest { mid: "2".into(), stream_id: 203, source: None, screen: false, detail: TileDetail::Stage }]);
346 390 }
347 391
348 392 #[test]
349 393 fn a_source_request_wraps_the_control_message_like_the_web_client() {
350 let request = SourceRequest { mid: "3".into(), stream_id: 204, source: Some(302), screen: false };
394 let request = SourceRequest { mid: "3".into(), stream_id: 204, source: Some(302), screen: false, detail: TileDetail::Stage };
351 395 let body = request.body(7);
352 396 let channel = &body["applyChannelParameters"]["multiChannelParameter"];
353 397 assert_eq!(channel["mids"], json!(["3"]));
@@ -369,6 +413,67 @@ mod tests {
369 413 assert_eq!(parameter["controlVideoStreaming"]["controlInfo"]["fmtParams"][0]["max-fs"], 8160);
370 414 }
371 415
416 fn want(name: &str, detail: TileDetail) -> VideoWant {
417 VideoWant { mri: format!("8:orgid:{name}"), detail }
418 }
419
420 fn roster_of(count: u32) -> Vec<(String, u32)> {
421 (1..=count).map(|index| (format!("8:orgid:p{index}"), index)).collect()
422 }
423
424 #[test]
425 fn nine_slots_hold_nine_visible_people_and_the_tenth_waits() {
426 let wants: Vec<VideoWant> = (1..=10).map(|index| want(&format!("p{index}"), TileDetail::Small)).collect();
427 let candidates = prioritize(roster_of(10), &[], Some(&wants));
428 let next = plan_receive(&vec![None; RECEIVE_SLOTS], &candidates);
429 assert_eq!(next.iter().flatten().count(), 9);
430 assert!(next.iter().flatten().all(|held| held.mri != "8:orgid:p10"));
431 }
432
433 #[test]
434 fn people_outside_the_visible_tiles_get_no_slot() {
435 let wants = vec![want("p2", TileDetail::Small), want("p4", TileDetail::Small)];
436 let candidates = prioritize(roster_of(5), &["8:orgid:p5".to_owned()], Some(&wants));
437 let mris: Vec<&str> = candidates.iter().map(|assignment| assignment.mri.as_str()).collect();
438 assert_eq!(mris, vec!["8:orgid:p2", "8:orgid:p4"]);
439 let held = vec![Some(assignment("p5", 5)), None, None];
440 let next = plan_receive(&held, &candidates);
441 assert_eq!(next.iter().flatten().map(|held| held.mri.as_str()).collect::<Vec<_>>(), vec!["8:orgid:p2", "8:orgid:p4"]);
442 }
443
444 #[test]
445 fn nobody_visible_means_no_subscription() {
446 assert!(prioritize(roster_of(3), &[], Some(&[])).is_empty());
447 }
448
449 #[test]
450 fn a_person_who_moves_to_the_stage_keeps_the_slot_and_gets_the_large_request() {
451 let small = Assignment { detail: TileDetail::Small, ..assignment("a", 1) };
452 let held = vec![None, Some(small), None];
453 let wants = vec![want("a", TileDetail::Stage)];
454 let next = plan_receive(&held, &prioritize(vec![("8:orgid:a".to_owned(), 1)], &[], Some(&wants)));
455 assert_eq!(next, vec![None, Some(assignment("a", 1)), None]);
456 let slots: Vec<ReceiveSlot> = (0..3).map(|index| ReceiveSlot { mid: format!("{}", index + 2), stream_id: 203 + index }).collect();
457 let requests = requests_for(&held, &next, &slots);
458 assert_eq!(requests.len(), 1);
459 assert_eq!(requests[0].mid, "3");
460 assert_eq!(requests[0].detail, TileDetail::Stage);
461 }
462
463 #[test]
464 fn stage_and_small_tiles_ask_for_different_resolutions() {
465 let fmt_for = |detail| {
466 let request = SourceRequest { mid: "2".into(), stream_id: 203, source: Some(1), screen: false, detail };
467 let body = request.body(1);
468 let parameter: Value =
469 serde_json::from_str(body["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"].as_str().unwrap()).unwrap();
470 parameter["controlVideoStreaming"]["controlInfo"]["fmtParams"][0].clone()
471 };
472 assert_eq!(fmt_for(TileDetail::Stage)["max-fs"], 3600);
473 assert_eq!(fmt_for(TileDetail::Small)["max-fs"], 920);
474 assert_eq!(fmt_for(TileDetail::Small)["max-mbps"], 27_600);
475 }
476
372 477 #[test]
373 478 fn media_descriptions_tell_the_mixer_what_a_line_does() {
374 479 assert_eq!(
@@ -378,7 +483,7 @@ mod tests {
378 483 assert_eq!(MediaDescription::camera(false).wire(), json!({"mid": "1", "direction": "recvonly"}));
379 484 assert_eq!(
380 485 MediaDescription::share(true).wire(),
381 json!({"mid": "6", "direction": "sendrecv", "label": "applicationsharing-video"})
486 json!({"mid": "11", "direction": "sendrecv", "label": "applicationsharing-video"})
382 487 );
383 488 }
384 489
@@ -12,9 +12,9 @@ use crate::error::{Error, Result};
12use crate::sdp::{LineRole, OfferPlan, StreamLine};
12use crate::sdp::{LineRole, OfferPlan, StreamLine};
13use crate::video_frame::VideoKey;
13use crate::video_frame::VideoKey;
14
14
15pub const RECEIVE_SLOTS: usize = 4;
15pub const RECEIVE_SLOTS: usize = 9;
16pub const CAMERA_MID: &str = "1";
16pub const CAMERA_MID: &str = "1";
17pub const SHARE_MID: &str = "6";
17pub const SHARE_MID: &str = "11";
18pub const ONE_TO_ONE_SHARE_MID: &str = "2";
18pub const ONE_TO_ONE_SHARE_MID: &str = "2";
19const CAMERA_LINE_LABEL: &str = "main-video";
19const CAMERA_LINE_LABEL: &str = "main-video";
20const SHARE_LINE_LABEL: &str = "applicationsharing-video";
20const SHARE_LINE_LABEL: &str = "applicationsharing-video";
@@ -23,10 +23,33 @@ const SCREEN_STREAM: &str = "screen";
23const H264: &str = "video/h264";
23const H264: &str = "video/h264";
24const RTX: &str = "video/rtx";
24const RTX: &str = "video/rtx";
25const NO_SOURCE: i64 = -1;
25const NO_SOURCE: i64 = -1;
26const PERSON_REQUEST: ReceiveLimits = ReceiveLimits { max_fs: 3600, max_fps: 3000, max_mbps: 108_000 };
26const STAGE_REQUEST: ReceiveLimits = ReceiveLimits { max_fs: 3600, max_fps: 3000, max_mbps: 108_000 };
27const SMALL_REQUEST: ReceiveLimits = ReceiveLimits { max_fs: 920, max_fps: 3000, max_mbps: 27_600 };
27const SCREEN_REQUEST: ReceiveLimits = ReceiveLimits { max_fs: 8160, max_fps: 1500, max_mbps: 135_000 };
28const SCREEN_REQUEST: ReceiveLimits = ReceiveLimits { max_fs: 8160, max_fps: 1500, max_mbps: 135_000 };
28const SUBSCRIBE_PROFILE: &str = "64001f";
29const SUBSCRIBE_PROFILE: &str = "64001f";
29
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
32pub enum TileDetail {
33 #[default]
34 Stage,
35 Small,
36}
37
38impl TileDetail {
39 fn limits(self) -> ReceiveLimits {
40 match self {
41 TileDetail::Stage => STAGE_REQUEST,
42 TileDetail::Small => SMALL_REQUEST,
43 }
44 }
45}
46
47#[derive(Debug, Clone, PartialEq, Eq)]
48pub struct VideoWant {
49 pub mri: String,
50 pub detail: TileDetail,
51}
52
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31struct ReceiveLimits {
54struct ReceiveLimits {
32 max_fs: u32,
55 max_fs: u32,
@@ -48,7 +71,7 @@ pub fn one_to_one_plan() -> OfferPlan {
48 }
71 }
49}
72}
50
73
51/// Offered after the audio line: camera, `RECEIVE_SLOTS` receive-only slots, screen share (mids 1, 2-5, 6).
74/// Offered after the audio line: camera, `RECEIVE_SLOTS` receive-only slots, screen share (mids 1, 2-10, 11).
52#[derive(Clone)]
75#[derive(Clone)]
53pub struct VideoLines {
76pub struct VideoLines {
54 pub camera: RtpTransceiver,
77 pub camera: RtpTransceiver,
@@ -178,16 +201,26 @@ impl SlotTable {
178pub struct Assignment {
201pub struct Assignment {
179 pub mri: String,
202 pub mri: String,
180 pub source: u32,
203 pub source: u32,
204 pub detail: TileDetail,
205}
206
207impl Assignment {
208 fn same_source(&self, other: &Assignment) -> bool {
209 self.mri == other.mri && self.source == other.source
210 }
181}
211}
182
212
183pub fn plan_receive(current: &[Option<Assignment>], candidates: &[Assignment]) -> Vec<Option<Assignment>> {
213pub fn plan_receive(current: &[Option<Assignment>], candidates: &[Assignment]) -> Vec<Option<Assignment>> {
184 let wanted: Vec<&Assignment> = candidates.iter().take(current.len()).collect();
214 let wanted: Vec<&Assignment> = candidates.iter().take(current.len()).collect();
185 let mut next: Vec<Option<Assignment>> = current
215 let mut next: Vec<Option<Assignment>> = current
186 .iter()
216 .iter()
187 .map(|slot| slot.clone().filter(|held| wanted.contains(&held)))
217 .map(|slot| {
218 let held = slot.as_ref()?;
219 wanted.iter().find(|assignment| assignment.same_source(held)).map(|assignment| (*assignment).clone())
220 })
188 .collect();
221 .collect();
189 for assignment in wanted {
222 for assignment in wanted {
190 if next.iter().flatten().any(|held| held == assignment) {
223 if next.iter().flatten().any(|held| held.same_source(assignment)) {
191 continue;
224 continue;
192 }
225 }
193 if let Some(free) = next.iter_mut().find(|slot| slot.is_none()) {
226 if let Some(free) = next.iter_mut().find(|slot| slot.is_none()) {
@@ -197,11 +230,20 @@ pub fn plan_receive(current: &[Option<Assignment>], candidates: &[Assignment]) -
197 next
230 next
198}
231}
199
232
200pub fn prioritize(candidates: Vec<(String, u32)>, speaker_history: &[String]) -> Vec<Assignment> {
233pub fn prioritize(candidates: Vec<(String, u32)>, speaker_history: &[String], wants: Option<&[VideoWant]>) -> Vec<Assignment> {
234 if let Some(wants) = wants {
235 return wants
236 .iter()
237 .filter_map(|want| {
238 let (mri, source) = candidates.iter().find(|(mri, _)| *mri == want.mri)?;
239 Some(Assignment { mri: mri.clone(), source: *source, detail: want.detail })
240 })
241 .collect();
242 }
201 let rank = |mri: &str| speaker_history.iter().position(|speaker| speaker == mri).unwrap_or(usize::MAX);
243 let rank = |mri: &str| speaker_history.iter().position(|speaker| speaker == mri).unwrap_or(usize::MAX);
202 let mut ordered: Vec<Assignment> = candidates
244 let mut ordered: Vec<Assignment> = candidates
203 .into_iter()
245 .into_iter()
204 .map(|(mri, source)| Assignment { mri, source })
246 .map(|(mri, source)| Assignment { mri, source, detail: TileDetail::Stage })
205 .collect();
247 .collect();
206 ordered.sort_by_key(|assignment| rank(&assignment.mri));
248 ordered.sort_by_key(|assignment| rank(&assignment.mri));
207 ordered
249 ordered
@@ -213,6 +255,7 @@ pub struct SourceRequest {
213 pub stream_id: u32,
255 pub stream_id: u32,
214 pub source: Option<u32>,
256 pub source: Option<u32>,
215 pub screen: bool,
257 pub screen: bool,
258 pub detail: TileDetail,
216}
259}
217
260
218pub fn requests_for(
261pub fn requests_for(
@@ -229,6 +272,7 @@ pub fn requests_for(
229 stream_id: slot.stream_id,
272 stream_id: slot.stream_id,
230 source: after.as_ref().map(|assignment| assignment.source),
273 source: after.as_ref().map(|assignment| assignment.source),
231 screen: false,
274 screen: false,
275 detail: after.as_ref().map(|assignment| assignment.detail).unwrap_or_default(),
232 })
276 })
233 .collect()
277 .collect()
234}
278}
@@ -236,7 +280,7 @@ pub fn requests_for(
236impl SourceRequest {
280impl SourceRequest {
237 /// Body of the `applyChannelParameters` link, the signaling twin of the data-channel `sr` message.
281 /// Body of the `applyChannelParameters` link, the signaling twin of the data-channel `sr` message.
238 pub fn body(&self, sequence_number: u64) -> Value {
282 pub fn body(&self, sequence_number: u64) -> Value {
239 let limits = if self.screen { SCREEN_REQUEST } else { PERSON_REQUEST };
283 let limits = if self.screen { SCREEN_REQUEST } else { self.detail.limits() };
240 let control = json!({
284 let control = json!({
241 "controlVideoStreaming": {
285 "controlVideoStreaming": {
242 "sequenceNumber": sequence_number,
286 "sequenceNumber": sequence_number,
@@ -287,7 +331,7 @@ mod tests {
287 use super::*;
331 use super::*;
288
332
289 fn assignment(name: &str, source: u32) -> Assignment {
333 fn assignment(name: &str, source: u32) -> Assignment {
290 Assignment { mri: format!("8:orgid:{name}"), source }
334 Assignment { mri: format!("8:orgid:{name}"), source, detail: TileDetail::Stage }
291 }
335 }
292
336
293 fn stream(mid: &str, role: LineRole, id: Option<u32>) -> StreamLine {
337 fn stream(mid: &str, role: LineRole, id: Option<u32>) -> StreamLine {
@@ -303,12 +347,12 @@ mod tests {
303 stream("3", LineRole::MainVideo, Some(204)),
347 stream("3", LineRole::MainVideo, Some(204)),
304 stream("4", LineRole::MainVideo, None),
348 stream("4", LineRole::MainVideo, None),
305 stream("5", LineRole::MainVideo, Some(206)),
349 stream("5", LineRole::MainVideo, Some(206)),
306 stream("6", LineRole::ScreenShare, Some(207)),
350 stream("11", LineRole::ScreenShare, Some(207)),
307 ];
351 ];
308 let table = SlotTable::from_streams(&streams);
352 let table = SlotTable::from_streams(&streams);
309 let mids: Vec<&str> = table.people.iter().map(|slot| slot.mid.as_str()).collect();
353 let mids: Vec<&str> = table.people.iter().map(|slot| slot.mid.as_str()).collect();
310 assert_eq!(mids, vec!["2", "3", "5"]);
354 assert_eq!(mids, vec!["2", "3", "5"]);
311 assert_eq!(table.screen, Some(ReceiveSlot { mid: "6".into(), stream_id: 207 }));
355 assert_eq!(table.screen, Some(ReceiveSlot { mid: "11".into(), stream_id: 207 }));
312 }
356 }
313
357
314 #[test]
358 #[test]
@@ -327,7 +371,7 @@ mod tests {
327 let held: Vec<Option<Assignment>> = (1..=4).map(|index| Some(assignment(&format!("p{index}"), index))).collect();
371 let held: Vec<Option<Assignment>> = (1..=4).map(|index| Some(assignment(&format!("p{index}"), index))).collect();
328 let history = vec!["8:orgid:p5".to_owned(), "8:orgid:p1".to_owned(), "8:orgid:p2".to_owned(), "8:orgid:p3".to_owned()];
372 let history = vec!["8:orgid:p5".to_owned(), "8:orgid:p1".to_owned(), "8:orgid:p2".to_owned(), "8:orgid:p3".to_owned()];
329 let roster = (1..=5).map(|index| (format!("8:orgid:p{index}"), index)).collect();
373 let roster = (1..=5).map(|index| (format!("8:orgid:p{index}"), index)).collect();
330 let next = plan_receive(&held, &prioritize(roster, &history));
374 let next = plan_receive(&held, &prioritize(roster, &history, None));
331 let names: Vec<&str> = next.iter().flatten().map(|held| held.mri.as_str()).collect();
375 let names: Vec<&str> = next.iter().flatten().map(|held| held.mri.as_str()).collect();
332 assert_eq!(names, vec!["8:orgid:p1", "8:orgid:p2", "8:orgid:p3", "8:orgid:p5"]);
376 assert_eq!(names, vec!["8:orgid:p1", "8:orgid:p2", "8:orgid:p3", "8:orgid:p5"]);
333 }
377 }
@@ -342,12 +386,12 @@ mod tests {
342 ReceiveSlot { mid: "3".into(), stream_id: 204 },
386 ReceiveSlot { mid: "3".into(), stream_id: 204 },
343 ];
387 ];
344 let requests = requests_for(&held, &next, &slots);
388 let requests = requests_for(&held, &next, &slots);
345 assert_eq!(requests, vec![SourceRequest { mid: "2".into(), stream_id: 203, source: None, screen: false }]);
389 assert_eq!(requests, vec![SourceRequest { mid: "2".into(), stream_id: 203, source: None, screen: false, detail: TileDetail::Stage }]);
346 }
390 }
347
391
348 #[test]
392 #[test]
349 fn a_source_request_wraps_the_control_message_like_the_web_client() {
393 fn a_source_request_wraps_the_control_message_like_the_web_client() {
350 let request = SourceRequest { mid: "3".into(), stream_id: 204, source: Some(302), screen: false };
394 let request = SourceRequest { mid: "3".into(), stream_id: 204, source: Some(302), screen: false, detail: TileDetail::Stage };
351 let body = request.body(7);
395 let body = request.body(7);
352 let channel = &body["applyChannelParameters"]["multiChannelParameter"];
396 let channel = &body["applyChannelParameters"]["multiChannelParameter"];
353 assert_eq!(channel["mids"], json!(["3"]));
397 assert_eq!(channel["mids"], json!(["3"]));
@@ -369,6 +413,67 @@ mod tests {
369 assert_eq!(parameter["controlVideoStreaming"]["controlInfo"]["fmtParams"][0]["max-fs"], 8160);
413 assert_eq!(parameter["controlVideoStreaming"]["controlInfo"]["fmtParams"][0]["max-fs"], 8160);
370 }
414 }
371
415
416 fn want(name: &str, detail: TileDetail) -> VideoWant {
417 VideoWant { mri: format!("8:orgid:{name}"), detail }
418 }
419
420 fn roster_of(count: u32) -> Vec<(String, u32)> {
421 (1..=count).map(|index| (format!("8:orgid:p{index}"), index)).collect()
422 }
423
424 #[test]
425 fn nine_slots_hold_nine_visible_people_and_the_tenth_waits() {
426 let wants: Vec<VideoWant> = (1..=10).map(|index| want(&format!("p{index}"), TileDetail::Small)).collect();
427 let candidates = prioritize(roster_of(10), &[], Some(&wants));
428 let next = plan_receive(&vec![None; RECEIVE_SLOTS], &candidates);
429 assert_eq!(next.iter().flatten().count(), 9);
430 assert!(next.iter().flatten().all(|held| held.mri != "8:orgid:p10"));
431 }
432
433 #[test]
434 fn people_outside_the_visible_tiles_get_no_slot() {
435 let wants = vec![want("p2", TileDetail::Small), want("p4", TileDetail::Small)];
436 let candidates = prioritize(roster_of(5), &["8:orgid:p5".to_owned()], Some(&wants));
437 let mris: Vec<&str> = candidates.iter().map(|assignment| assignment.mri.as_str()).collect();
438 assert_eq!(mris, vec!["8:orgid:p2", "8:orgid:p4"]);
439 let held = vec![Some(assignment("p5", 5)), None, None];
440 let next = plan_receive(&held, &candidates);
441 assert_eq!(next.iter().flatten().map(|held| held.mri.as_str()).collect::<Vec<_>>(), vec!["8:orgid:p2", "8:orgid:p4"]);
442 }
443
444 #[test]
445 fn nobody_visible_means_no_subscription() {
446 assert!(prioritize(roster_of(3), &[], Some(&[])).is_empty());
447 }
448
449 #[test]
450 fn a_person_who_moves_to_the_stage_keeps_the_slot_and_gets_the_large_request() {
451 let small = Assignment { detail: TileDetail::Small, ..assignment("a", 1) };
452 let held = vec![None, Some(small), None];
453 let wants = vec![want("a", TileDetail::Stage)];
454 let next = plan_receive(&held, &prioritize(vec![("8:orgid:a".to_owned(), 1)], &[], Some(&wants)));
455 assert_eq!(next, vec![None, Some(assignment("a", 1)), None]);
456 let slots: Vec<ReceiveSlot> = (0..3).map(|index| ReceiveSlot { mid: format!("{}", index + 2), stream_id: 203 + index }).collect();
457 let requests = requests_for(&held, &next, &slots);
458 assert_eq!(requests.len(), 1);
459 assert_eq!(requests[0].mid, "3");
460 assert_eq!(requests[0].detail, TileDetail::Stage);
461 }
462
463 #[test]
464 fn stage_and_small_tiles_ask_for_different_resolutions() {
465 let fmt_for = |detail| {
466 let request = SourceRequest { mid: "2".into(), stream_id: 203, source: Some(1), screen: false, detail };
467 let body = request.body(1);
468 let parameter: Value =
469 serde_json::from_str(body["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"].as_str().unwrap()).unwrap();
470 parameter["controlVideoStreaming"]["controlInfo"]["fmtParams"][0].clone()
471 };
472 assert_eq!(fmt_for(TileDetail::Stage)["max-fs"], 3600);
473 assert_eq!(fmt_for(TileDetail::Small)["max-fs"], 920);
474 assert_eq!(fmt_for(TileDetail::Small)["max-mbps"], 27_600);
475 }
476
372 #[test]
477 #[test]
373 fn media_descriptions_tell_the_mixer_what_a_line_does() {
478 fn media_descriptions_tell_the_mixer_what_a_line_does() {
374 assert_eq!(
479 assert_eq!(
@@ -378,7 +483,7 @@ mod tests {
378 assert_eq!(MediaDescription::camera(false).wire(), json!({"mid": "1", "direction": "recvonly"}));
483 assert_eq!(MediaDescription::camera(false).wire(), json!({"mid": "1", "direction": "recvonly"}));
379 assert_eq!(
484 assert_eq!(
380 MediaDescription::share(true).wire(),
485 MediaDescription::share(true).wire(),
381 json!({"mid": "6", "direction": "sendrecv", "label": "applicationsharing-video"})
486 json!({"mid": "11", "direction": "sendrecv", "label": "applicationsharing-video"})
382 );
487 );
383 }
488 }
384
489
crates/calling/src/video_receive.rs +19 −5
@@ -14,7 +14,7 @@ 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, VideoRouter, plan_receive, prioritize, requests_for,
17 Assignment, SlotTable, SourceRequest, TileDetail, VideoRouter, VideoWant, plan_receive, prioritize, requests_for,
18 18 };
19 19
20 20 const HISTORY_LIMIT: usize = 16;
@@ -76,7 +76,7 @@ impl SourceRequester {
76 76 ),
77 77 Err(error) => timeline.record("video source failed", error.to_string()),
78 78 }
79 if let Some(key) = &queued.route_after {
79 if let Some(key) = queued.route_after.as_ref().filter(|key| router.key_for(&queued.request.mid).as_ref() != Some(key)) {
80 80 hub.forget(key);
81 81 }
82 82 router.set(&queued.request.mid, queued.route_after);
@@ -109,6 +109,7 @@ pub struct VideoReceive {
109 109 held: Vec<Option<Assignment>>,
110 110 screen_held: Option<Assignment>,
111 111 history: Vec<String>,
112 wants: Option<Vec<VideoWant>>,
112 113 requester: Option<SourceRequester>,
113 114 incoming_enabled: bool,
114 115 }
@@ -122,6 +123,7 @@ impl VideoReceive {
122 123 held: Vec::new(),
123 124 screen_held: None,
124 125 history: Vec::new(),
126 wants: None,
125 127 requester: None,
126 128 incoming_enabled: true,
127 129 }
@@ -131,6 +133,12 @@ impl VideoReceive {
131 133 self.incoming_enabled = enabled;
132 134 }
133 135
136 pub fn set_wants(&mut self, wants: Vec<VideoWant>) -> bool {
137 let changed = self.wants.as_ref() != Some(&wants);
138 self.wants = Some(wants);
139 changed
140 }
141
134 142 pub fn router(&self) -> &VideoRouter {
135 143 &self.router
136 144 }
@@ -163,7 +171,7 @@ impl VideoReceive {
163 171 let mut change = ReceiveChange::default();
164 172 let Some(requester) = &self.requester else { return change };
165 173 let candidates = if self.incoming_enabled {
166 prioritize(roster.video_candidates(&self.own_mri), &self.history)
174 prioritize(roster.video_candidates(&self.own_mri), &self.history, self.wants.as_deref())
167 175 } else {
168 176 Vec::new()
169 177 };
@@ -173,14 +181,19 @@ impl VideoReceive {
173 181 let route_after = slot
174 182 .and_then(|index| next[index].as_ref())
175 183 .map(|assignment| VideoKey::Person(assignment.mri.clone()));
176 self.router.set(&request.mid, None);
184 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)
186 });
187 if !same_person {
188 self.router.set(&request.mid, None);
189 }
177 190 requester.send(request, route_after);
178 191 }
179 192 self.held = next;
180 193 if let Some(slot) = &self.table.screen {
181 194 let wanted = roster
182 195 .screen_share(&self.own_mri)
183 .map(|(mri, source)| Assignment { mri, source });
196 .map(|(mri, source)| Assignment { mri, source, detail: TileDetail::Stage });
184 197 if wanted != self.screen_held {
185 198 let route_after = wanted.as_ref().map(|_| VideoKey::Screen);
186 199 self.router.set(&slot.mid, None);
@@ -190,6 +203,7 @@ impl VideoReceive {
190 203 stream_id: slot.stream_id,
191 204 source: wanted.as_ref().map(|assignment| assignment.source),
192 205 screen: true,
206 detail: TileDetail::Stage,
193 207 },
194 208 route_after,
195 209 );
@@ -14,7 +14,7 @@ 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, VideoRouter, plan_receive, prioritize, requests_for,
17 Assignment, SlotTable, SourceRequest, TileDetail, VideoRouter, VideoWant, plan_receive, prioritize, requests_for,
18};
18};
19
19
20const HISTORY_LIMIT: usize = 16;
20const HISTORY_LIMIT: usize = 16;
@@ -76,7 +76,7 @@ impl SourceRequester {
76 ),
76 ),
77 Err(error) => timeline.record("video source failed", error.to_string()),
77 Err(error) => timeline.record("video source failed", error.to_string()),
78 }
78 }
79 if let Some(key) = &queued.route_after {
79 if let Some(key) = queued.route_after.as_ref().filter(|key| router.key_for(&queued.request.mid).as_ref() != Some(key)) {
80 hub.forget(key);
80 hub.forget(key);
81 }
81 }
82 router.set(&queued.request.mid, queued.route_after);
82 router.set(&queued.request.mid, queued.route_after);
@@ -109,6 +109,7 @@ pub struct VideoReceive {
109 held: Vec<Option<Assignment>>,
109 held: Vec<Option<Assignment>>,
110 screen_held: Option<Assignment>,
110 screen_held: Option<Assignment>,
111 history: Vec<String>,
111 history: Vec<String>,
112 wants: Option<Vec<VideoWant>>,
112 requester: Option<SourceRequester>,
113 requester: Option<SourceRequester>,
113 incoming_enabled: bool,
114 incoming_enabled: bool,
114}
115}
@@ -122,6 +123,7 @@ impl VideoReceive {
122 held: Vec::new(),
123 held: Vec::new(),
123 screen_held: None,
124 screen_held: None,
124 history: Vec::new(),
125 history: Vec::new(),
126 wants: None,
125 requester: None,
127 requester: None,
126 incoming_enabled: true,
128 incoming_enabled: true,
127 }
129 }
@@ -131,6 +133,12 @@ impl VideoReceive {
131 self.incoming_enabled = enabled;
133 self.incoming_enabled = enabled;
132 }
134 }
133
135
136 pub fn set_wants(&mut self, wants: Vec<VideoWant>) -> bool {
137 let changed = self.wants.as_ref() != Some(&wants);
138 self.wants = Some(wants);
139 changed
140 }
141
134 pub fn router(&self) -> &VideoRouter {
142 pub fn router(&self) -> &VideoRouter {
135 &self.router
143 &self.router
136 }
144 }
@@ -163,7 +171,7 @@ impl VideoReceive {
163 let mut change = ReceiveChange::default();
171 let mut change = ReceiveChange::default();
164 let Some(requester) = &self.requester else { return change };
172 let Some(requester) = &self.requester else { return change };
165 let candidates = if self.incoming_enabled {
173 let candidates = if self.incoming_enabled {
166 prioritize(roster.video_candidates(&self.own_mri), &self.history)
174 prioritize(roster.video_candidates(&self.own_mri), &self.history, self.wants.as_deref())
167 } else {
175 } else {
168 Vec::new()
176 Vec::new()
169 };
177 };
@@ -173,14 +181,19 @@ impl VideoReceive {
173 let route_after = slot
181 let route_after = slot
174 .and_then(|index| next[index].as_ref())
182 .and_then(|index| next[index].as_ref())
175 .map(|assignment| VideoKey::Person(assignment.mri.clone()));
183 .map(|assignment| VideoKey::Person(assignment.mri.clone()));
176 self.router.set(&request.mid, None);
184 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)
186 });
187 if !same_person {
188 self.router.set(&request.mid, None);
189 }
177 requester.send(request, route_after);
190 requester.send(request, route_after);
178 }
191 }
179 self.held = next;
192 self.held = next;
180 if let Some(slot) = &self.table.screen {
193 if let Some(slot) = &self.table.screen {
181 let wanted = roster
194 let wanted = roster
182 .screen_share(&self.own_mri)
195 .screen_share(&self.own_mri)
183 .map(|(mri, source)| Assignment { mri, source });
196 .map(|(mri, source)| Assignment { mri, source, detail: TileDetail::Stage });
184 if wanted != self.screen_held {
197 if wanted != self.screen_held {
185 let route_after = wanted.as_ref().map(|_| VideoKey::Screen);
198 let route_after = wanted.as_ref().map(|_| VideoKey::Screen);
186 self.router.set(&slot.mid, None);
199 self.router.set(&slot.mid, None);
@@ -190,6 +203,7 @@ impl VideoReceive {
190 stream_id: slot.stream_id,
203 stream_id: slot.stream_id,
191 source: wanted.as_ref().map(|assignment| assignment.source),
204 source: wanted.as_ref().map(|assignment| assignment.source),
192 screen: true,
205 screen: true,
206 detail: TileDetail::Stage,
193 },
207 },
194 route_after,
208 route_after,
195 );
209 );
crates/calling/tests/video_offer.rs +18 −11
@@ -50,13 +50,13 @@ async fn the_caption_data_channel_adds_one_x_data_line_after_the_video_lines() {
50 50 let offer = to_teams_offer(&offer_with(true).await, &offer_plan(), &mut counter()).unwrap();
51 51 let parsed = parse(&offer.sdp).unwrap();
52 52 let kinds: Vec<(&str, &str)> = parsed.media.iter().map(|media| (media.kind.as_str(), media.mid().unwrap_or_default())).collect();
53 assert_eq!(kinds.len(), 8);
54 assert_eq!(kinds[7], ("x-data", "7"));
55 assert_eq!(&kinds[..7].iter().map(|(_, mid)| *mid).collect::<Vec<_>>(), &["0", "1", "2", "3", "4", "5", "6"]);
56 assert_eq!(parsed.media[7].value("x-data-protocol"), Some("sctp"));
53 assert_eq!(kinds.len(), 13);
54 assert_eq!(kinds[12], ("x-data", "12"));
55 assert_eq!(&kinds[..12].iter().map(|(_, mid)| *mid).collect::<Vec<_>>(), &["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"]);
56 assert_eq!(parsed.media[12].value("x-data-protocol"), Some("sctp"));
57 57 assert_eq!(offer.lines.iter().filter(|line| line.role == LineRole::Data).count(), 1);
58 58 let group = parsed.session.attributes.iter().find(|attribute| attribute.name == "group").and_then(|attribute| attribute.value.clone());
59 assert_eq!(group.as_deref(), Some("BUNDLE 0 1 2 3 4 5 6 7"));
59 assert_eq!(group.as_deref(), Some("BUNDLE 0 1 2 3 4 5 6 7 8 9 10 11 12"));
60 60 }
61 61
62 62 #[tokio::test]
@@ -82,18 +82,23 @@ async fn the_meeting_layout_is_signaled_like_the_web_client_offers_it() {
82 82 ("3", "main-video", "recvonly"),
83 83 ("4", "main-video", "recvonly"),
84 84 ("5", "main-video", "recvonly"),
85 ("6", "applicationsharing-video", "sendrecv"),
85 ("6", "main-video", "recvonly"),
86 ("7", "main-video", "recvonly"),
87 ("8", "main-video", "recvonly"),
88 ("9", "main-video", "recvonly"),
89 ("10", "main-video", "recvonly"),
90 ("11", "applicationsharing-video", "sendrecv"),
86 91 ];
87 92 let actual: Vec<(&str, &str, &str)> = summary.iter().map(|(a, b, c)| (a.as_str(), b.as_str(), c.as_str())).collect();
88 93 assert_eq!(actual, expected);
89 for receive in &parsed.media[2..6] {
94 for receive in &parsed.media[2..11] {
90 95 assert_eq!(receive.value("x-ssrc-range"), Some("1-1"));
91 96 assert_eq!(receive.value("x-signaling-fb"), Some("* x-message app send:src recv:src,vc"));
92 97 assert!(receive.values("rtpmap").all(|mapping| mapping.contains("H264") || mapping.contains("rtx")), "{:?}", receive.values("rtpmap").collect::<Vec<_>>());
93 98 }
94 99 assert!(parsed.media[1].value("x-ssrc-range").is_some());
95 100 let group = parsed.session.attributes.iter().find(|attribute| attribute.name == "group").and_then(|attribute| attribute.value.clone());
96 assert_eq!(group.as_deref(), Some("BUNDLE 0 1 2 3 4 5 6"));
101 assert_eq!(group.as_deref(), Some("BUNDLE 0 1 2 3 4 5 6 7 8 9 10 11"));
97 102 assert_eq!(offer.lines.iter().filter(|line| line.role == LineRole::ScreenShare).count(), 1);
98 103 }
99 104
@@ -102,13 +107,15 @@ async fn the_slots_come_from_the_source_stream_ids_of_an_answer() {
102 107 let browser = browser_offer().await;
103 108 let offer = to_teams_offer(&browser, &offer_plan(), &mut counter()).unwrap();
104 109 let mut answer = String::from("v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n");
105 for (index, role) in ["main-audio", "main-video", "main-video", "main-video", "main-video", "main-video", "applicationsharing-video"].iter().enumerate() {
110 let roles: Vec<&str> = ["main-audio"].into_iter().chain(["main-video"; 10]).chain(["applicationsharing-video"]).collect();
111 for (index, role) in roles.iter().enumerate() {
106 112 let kind = if index == 0 { "audio" } else { "video" };
107 113 answer.push_str(&format!("m={kind} 3478 RTP/SAVP 107\r\na=x-source-streamid:{}\r\na=label:{role}\r\na=mid:{index}\r\n", 201 + index));
108 114 }
109 115 let streams = stream_lines(&answer, &offer.lines).unwrap();
110 116 let table = SlotTable::from_streams(&streams);
111 117 let slots: Vec<(String, u32)> = table.people.iter().map(|slot| (slot.mid.clone(), slot.stream_id)).collect();
112 assert_eq!(slots, vec![("2".to_owned(), 203), ("3".to_owned(), 204), ("4".to_owned(), 205), ("5".to_owned(), 206)]);
113 assert_eq!(table.screen.map(|slot| (slot.mid, slot.stream_id)), Some(("6".to_owned(), 207)));
118 let expected: Vec<(String, u32)> = (2..=10).map(|mid| (mid.to_string(), 201 + mid)).collect();
119 assert_eq!(slots, expected);
120 assert_eq!(table.screen.map(|slot| (slot.mid, slot.stream_id)), Some(("11".to_owned(), 212)));
114 121 }
@@ -50,13 +50,13 @@ async fn the_caption_data_channel_adds_one_x_data_line_after_the_video_lines() {
50 let offer = to_teams_offer(&offer_with(true).await, &offer_plan(), &mut counter()).unwrap();
50 let offer = to_teams_offer(&offer_with(true).await, &offer_plan(), &mut counter()).unwrap();
51 let parsed = parse(&offer.sdp).unwrap();
51 let parsed = parse(&offer.sdp).unwrap();
52 let kinds: Vec<(&str, &str)> = parsed.media.iter().map(|media| (media.kind.as_str(), media.mid().unwrap_or_default())).collect();
52 let kinds: Vec<(&str, &str)> = parsed.media.iter().map(|media| (media.kind.as_str(), media.mid().unwrap_or_default())).collect();
53 assert_eq!(kinds.len(), 8);
53 assert_eq!(kinds.len(), 13);
54 assert_eq!(kinds[7], ("x-data", "7"));
54 assert_eq!(kinds[12], ("x-data", "12"));
55 assert_eq!(&kinds[..7].iter().map(|(_, mid)| *mid).collect::<Vec<_>>(), &["0", "1", "2", "3", "4", "5", "6"]);
55 assert_eq!(&kinds[..12].iter().map(|(_, mid)| *mid).collect::<Vec<_>>(), &["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"]);
56 assert_eq!(parsed.media[7].value("x-data-protocol"), Some("sctp"));
56 assert_eq!(parsed.media[12].value("x-data-protocol"), Some("sctp"));
57 assert_eq!(offer.lines.iter().filter(|line| line.role == LineRole::Data).count(), 1);
57 assert_eq!(offer.lines.iter().filter(|line| line.role == LineRole::Data).count(), 1);
58 let group = parsed.session.attributes.iter().find(|attribute| attribute.name == "group").and_then(|attribute| attribute.value.clone());
58 let group = parsed.session.attributes.iter().find(|attribute| attribute.name == "group").and_then(|attribute| attribute.value.clone());
59 assert_eq!(group.as_deref(), Some("BUNDLE 0 1 2 3 4 5 6 7"));
59 assert_eq!(group.as_deref(), Some("BUNDLE 0 1 2 3 4 5 6 7 8 9 10 11 12"));
60}
60}
61
61
62#[tokio::test]
62#[tokio::test]
@@ -82,18 +82,23 @@ async fn the_meeting_layout_is_signaled_like_the_web_client_offers_it() {
82 ("3", "main-video", "recvonly"),
82 ("3", "main-video", "recvonly"),
83 ("4", "main-video", "recvonly"),
83 ("4", "main-video", "recvonly"),
84 ("5", "main-video", "recvonly"),
84 ("5", "main-video", "recvonly"),
85 ("6", "applicationsharing-video", "sendrecv"),
85 ("6", "main-video", "recvonly"),
86 ("7", "main-video", "recvonly"),
87 ("8", "main-video", "recvonly"),
88 ("9", "main-video", "recvonly"),
89 ("10", "main-video", "recvonly"),
90 ("11", "applicationsharing-video", "sendrecv"),
86 ];
91 ];
87 let actual: Vec<(&str, &str, &str)> = summary.iter().map(|(a, b, c)| (a.as_str(), b.as_str(), c.as_str())).collect();
92 let actual: Vec<(&str, &str, &str)> = summary.iter().map(|(a, b, c)| (a.as_str(), b.as_str(), c.as_str())).collect();
88 assert_eq!(actual, expected);
93 assert_eq!(actual, expected);
89 for receive in &parsed.media[2..6] {
94 for receive in &parsed.media[2..11] {
90 assert_eq!(receive.value("x-ssrc-range"), Some("1-1"));
95 assert_eq!(receive.value("x-ssrc-range"), Some("1-1"));
91 assert_eq!(receive.value("x-signaling-fb"), Some("* x-message app send:src recv:src,vc"));
96 assert_eq!(receive.value("x-signaling-fb"), Some("* x-message app send:src recv:src,vc"));
92 assert!(receive.values("rtpmap").all(|mapping| mapping.contains("H264") || mapping.contains("rtx")), "{:?}", receive.values("rtpmap").collect::<Vec<_>>());
97 assert!(receive.values("rtpmap").all(|mapping| mapping.contains("H264") || mapping.contains("rtx")), "{:?}", receive.values("rtpmap").collect::<Vec<_>>());
93 }
98 }
94 assert!(parsed.media[1].value("x-ssrc-range").is_some());
99 assert!(parsed.media[1].value("x-ssrc-range").is_some());
95 let group = parsed.session.attributes.iter().find(|attribute| attribute.name == "group").and_then(|attribute| attribute.value.clone());
100 let group = parsed.session.attributes.iter().find(|attribute| attribute.name == "group").and_then(|attribute| attribute.value.clone());
96 assert_eq!(group.as_deref(), Some("BUNDLE 0 1 2 3 4 5 6"));
101 assert_eq!(group.as_deref(), Some("BUNDLE 0 1 2 3 4 5 6 7 8 9 10 11"));
97 assert_eq!(offer.lines.iter().filter(|line| line.role == LineRole::ScreenShare).count(), 1);
102 assert_eq!(offer.lines.iter().filter(|line| line.role == LineRole::ScreenShare).count(), 1);
98}
103}
99
104
@@ -102,13 +107,15 @@ async fn the_slots_come_from_the_source_stream_ids_of_an_answer() {
102 let browser = browser_offer().await;
107 let browser = browser_offer().await;
103 let offer = to_teams_offer(&browser, &offer_plan(), &mut counter()).unwrap();
108 let offer = to_teams_offer(&browser, &offer_plan(), &mut counter()).unwrap();
104 let mut answer = String::from("v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n");
109 let mut answer = String::from("v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n");
105 for (index, role) in ["main-audio", "main-video", "main-video", "main-video", "main-video", "main-video", "applicationsharing-video"].iter().enumerate() {
110 let roles: Vec<&str> = ["main-audio"].into_iter().chain(["main-video"; 10]).chain(["applicationsharing-video"]).collect();
111 for (index, role) in roles.iter().enumerate() {
106 let kind = if index == 0 { "audio" } else { "video" };
112 let kind = if index == 0 { "audio" } else { "video" };
107 answer.push_str(&format!("m={kind} 3478 RTP/SAVP 107\r\na=x-source-streamid:{}\r\na=label:{role}\r\na=mid:{index}\r\n", 201 + index));
113 answer.push_str(&format!("m={kind} 3478 RTP/SAVP 107\r\na=x-source-streamid:{}\r\na=label:{role}\r\na=mid:{index}\r\n", 201 + index));
108 }
114 }
109 let streams = stream_lines(&answer, &offer.lines).unwrap();
115 let streams = stream_lines(&answer, &offer.lines).unwrap();
110 let table = SlotTable::from_streams(&streams);
116 let table = SlotTable::from_streams(&streams);
111 let slots: Vec<(String, u32)> = table.people.iter().map(|slot| (slot.mid.clone(), slot.stream_id)).collect();
117 let slots: Vec<(String, u32)> = table.people.iter().map(|slot| (slot.mid.clone(), slot.stream_id)).collect();
112 assert_eq!(slots, vec![("2".to_owned(), 203), ("3".to_owned(), 204), ("4".to_owned(), 205), ("5".to_owned(), 206)]);
118 let expected: Vec<(String, u32)> = (2..=10).map(|mid| (mid.to_string(), 201 + mid)).collect();
113 assert_eq!(table.screen.map(|slot| (slot.mid, slot.stream_id)), Some(("6".to_owned(), 207)));
119 assert_eq!(slots, expected);
120 assert_eq!(table.screen.map(|slot| (slot.mid, slot.stream_id)), Some(("11".to_owned(), 212)));
114}
121}