BlueGit

ict rusty-teams

merge: 9 video slots and screen sharing tools

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

metis Daniel Däschle · pushed by metis

Authored 2026-10-13 · 7 weeks ago

Hash
084d8c4357ce3aaaf9da85ce1a3c39c5a27d3cb4
35 files changed +1702 −118
Cargo.lock +1 −0
@@ -301,6 +301,7 @@ dependencies = [
301 301 "uuid",
302 302 "webview",
303 303 "windows 0.62.2",
304 "x11rb",
304 305 ]
305 306
306 307 [[package]]
@@ -301,6 +301,7 @@ dependencies = [
301 "uuid",
301 "uuid",
302 "webview",
302 "webview",
303 "windows 0.62.2",
303 "windows 0.62.2",
304 "x11rb",
304]
305]
305
306
306[[package]]
307[[package]]
ROADMAP.md +2 −0
@@ -184,6 +184,8 @@ Feature parity with the Microsoft Teams desktop client.
184 184 | Breakout rooms (participant) | Partial | Move message from the participant update or the replacement invite: notice "Moving you to <room>", leave and join the room, "Return to main meeting" in the header, a closed room goes back to the main meeting. Parsing unit tested; needs an organizer who moves people |
185 185 | Call health and encryption | Partial | Header shows signal bars and a shield; click opens "Call health" with loss, round trip, jitter, bitrate, "Secured by Teams encryption", DTLS-SRTP cipher and media path (direct or via Microsoft media server). Unstable network banner with "Turn off incoming video", overloaded computer banner with "Turn off effects". Thresholds unit tested; not yet seen on a bad live network |
186 186 | View and layout | Partial | "View" button between share and "...": Gallery (up to 3x3 of 16:9 tiles, "+N" tile with a pin list; visible tiles only swap after 2 s of speech, one swap per 5 s), Speaker (stage plus filmstrip of up to 6), Focus on content (only while someone shares), Hide people without video with a count chip, Hide me / Show me, Chat bubbles, Full screen (F11, controls hide after 3 s). Choice, Hide people without video and Chat bubbles are remembered. Checked with the demo gallery scene only; not yet in a large live meeting |
187 | Gallery video slots | Partial | Meetings offer 9 receive lines (mids 2-10, share on 11), so a 3x3 gallery shows up to 9 live videos. Only visible tiles get a slot: "+N" people and people hidden by "Hide people without video" are not requested. Speaker stage asks for 3600 macroblocks (max-fs), filmstrip, strip and big-gallery tiles for 920. 1:1 calls unchanged. Slot plan and offer layout unit tested; not yet seen with nine people on a live mixer |
188 | Sharing tools | Partial | Received share: Ctrl+wheel zoom 1x-4x around the pointer, drag to pan, Alt+Shift+Plus / Minus / 0, "250%" chip resets; draggable divider (strip 160-400 px, remembered); "Pop out" opens the content in its own window, closing it returns it. Share menu: "Optimize for motion" (maintain framerate, 30 fps; off = maintain resolution, 15 fps) and "Show me over my content" (camera cut-out bottom right, 22 % wide, rounded; skipped without a mask). Linux: red border windows ignore the mouse on X11. Checked in the demo and unit tests; not yet live with a second person |
187 189 | Whiteboard | Partial | Stage shows "<name> is sharing a whiteboard" with Open in browser, "..." > Whiteboard opens the meeting's board. State parsing unit tested; the share callback link is registered on join but not yet seen live |
188 190 | Call history | Done | Calls tab (Ctrl+5) from the Teams call log: avatar, name, Missed call in red, Outgoing / Incoming / Meeting with duration, time like the chat list. Click calls back or opens the meeting chat; right-click Call back and Open chat. Refreshes on tab open and after a call ends. Read live (counts and shapes); no realtime update |
189 191 | Join by link or meeting ID | Done | "Join with ID" dialog, "Paste a meeting link", Join chip next to Teams meeting links in the composer and messages. IDs and /meet/ links resolve through a roster-only conversation like Teams web; verified live with a self-created scheduled meeting (same meeting chat found) |
@@ -184,6 +184,8 @@ Feature parity with the Microsoft Teams desktop client.
184| Breakout rooms (participant) | Partial | Move message from the participant update or the replacement invite: notice "Moving you to <room>", leave and join the room, "Return to main meeting" in the header, a closed room goes back to the main meeting. Parsing unit tested; needs an organizer who moves people |
184| Breakout rooms (participant) | Partial | Move message from the participant update or the replacement invite: notice "Moving you to <room>", leave and join the room, "Return to main meeting" in the header, a closed room goes back to the main meeting. Parsing unit tested; needs an organizer who moves people |
185| Call health and encryption | Partial | Header shows signal bars and a shield; click opens "Call health" with loss, round trip, jitter, bitrate, "Secured by Teams encryption", DTLS-SRTP cipher and media path (direct or via Microsoft media server). Unstable network banner with "Turn off incoming video", overloaded computer banner with "Turn off effects". Thresholds unit tested; not yet seen on a bad live network |
185| Call health and encryption | Partial | Header shows signal bars and a shield; click opens "Call health" with loss, round trip, jitter, bitrate, "Secured by Teams encryption", DTLS-SRTP cipher and media path (direct or via Microsoft media server). Unstable network banner with "Turn off incoming video", overloaded computer banner with "Turn off effects". Thresholds unit tested; not yet seen on a bad live network |
186| View and layout | Partial | "View" button between share and "...": Gallery (up to 3x3 of 16:9 tiles, "+N" tile with a pin list; visible tiles only swap after 2 s of speech, one swap per 5 s), Speaker (stage plus filmstrip of up to 6), Focus on content (only while someone shares), Hide people without video with a count chip, Hide me / Show me, Chat bubbles, Full screen (F11, controls hide after 3 s). Choice, Hide people without video and Chat bubbles are remembered. Checked with the demo gallery scene only; not yet in a large live meeting |
186| View and layout | Partial | "View" button between share and "...": Gallery (up to 3x3 of 16:9 tiles, "+N" tile with a pin list; visible tiles only swap after 2 s of speech, one swap per 5 s), Speaker (stage plus filmstrip of up to 6), Focus on content (only while someone shares), Hide people without video with a count chip, Hide me / Show me, Chat bubbles, Full screen (F11, controls hide after 3 s). Choice, Hide people without video and Chat bubbles are remembered. Checked with the demo gallery scene only; not yet in a large live meeting |
187| Gallery video slots | Partial | Meetings offer 9 receive lines (mids 2-10, share on 11), so a 3x3 gallery shows up to 9 live videos. Only visible tiles get a slot: "+N" people and people hidden by "Hide people without video" are not requested. Speaker stage asks for 3600 macroblocks (max-fs), filmstrip, strip and big-gallery tiles for 920. 1:1 calls unchanged. Slot plan and offer layout unit tested; not yet seen with nine people on a live mixer |
188| Sharing tools | Partial | Received share: Ctrl+wheel zoom 1x-4x around the pointer, drag to pan, Alt+Shift+Plus / Minus / 0, "250%" chip resets; draggable divider (strip 160-400 px, remembered); "Pop out" opens the content in its own window, closing it returns it. Share menu: "Optimize for motion" (maintain framerate, 30 fps; off = maintain resolution, 15 fps) and "Show me over my content" (camera cut-out bottom right, 22 % wide, rounded; skipped without a mask). Linux: red border windows ignore the mouse on X11. Checked in the demo and unit tests; not yet live with a second person |
187| Whiteboard | Partial | Stage shows "<name> is sharing a whiteboard" with Open in browser, "..." > Whiteboard opens the meeting's board. State parsing unit tested; the share callback link is registered on join but not yet seen live |
189| Whiteboard | Partial | Stage shows "<name> is sharing a whiteboard" with Open in browser, "..." > Whiteboard opens the meeting's board. State parsing unit tested; the share callback link is registered on join but not yet seen live |
188| Call history | Done | Calls tab (Ctrl+5) from the Teams call log: avatar, name, Missed call in red, Outgoing / Incoming / Meeting with duration, time like the chat list. Click calls back or opens the meeting chat; right-click Call back and Open chat. Refreshes on tab open and after a call ends. Read live (counts and shapes); no realtime update |
190| Call history | Done | Calls tab (Ctrl+5) from the Teams call log: avatar, name, Missed call in red, Outgoing / Incoming / Meeting with duration, time like the chat list. Click calls back or opens the meeting chat; right-click Call back and Open chat. Refreshes on tab open and after a call ends. Read live (counts and shapes); no realtime update |
189| Join by link or meeting ID | Done | "Join with ID" dialog, "Paste a meeting link", Join chip next to Teams meeting links in the composer and messages. IDs and /meet/ links resolve through a roster-only conversation like Teams web; verified live with a self-created scheduled meeting (same meeting chat found) |
191| Join by link or meeting ID | Done | "Join with ID" dialog, "Paste a meeting link", Join chip next to Teams meeting links in the composer and messages. IDs and /meet/ links resolve through a roster-only conversation like Teams web; verified live with a self-created scheduled meeting (same meeting chat found) |
crates/app/Cargo.toml +4 −0
@@ -38,6 +38,10 @@ tokio.workspace = true
38 38 uuid.workspace = true
39 39 image = { version = "0.25", default-features = false, features = ["bmp", "gif", "jpeg", "png", "webp"] }
40 40
41 [target.'cfg(target_os = "linux")'.dependencies]
42 raw-window-handle = "0.6"
43 x11rb = { version = "0.13", features = ["shape"] }
44
41 45 [target.'cfg(windows)'.dependencies]
42 46 webview.workspace = true
43 47 raw-window-handle = "0.6"
@@ -38,6 +38,10 @@ tokio.workspace = true
38uuid.workspace = true
38uuid.workspace = true
39image = { version = "0.25", default-features = false, features = ["bmp", "gif", "jpeg", "png", "webp"] }
39image = { version = "0.25", default-features = false, features = ["bmp", "gif", "jpeg", "png", "webp"] }
40
40
41[target.'cfg(target_os = "linux")'.dependencies]
42raw-window-handle = "0.6"
43x11rb = { version = "0.13", features = ["shape"] }
44
41[target.'cfg(windows)'.dependencies]
45[target.'cfg(windows)'.dependencies]
42webview.workspace = true
46webview.workspace = true
43raw-window-handle = "0.6"
47raw-window-handle = "0.6"
crates/app/src/app_state.rs +9 −0
@@ -125,6 +125,9 @@ pub struct AppState {
125 125 pub call_launcher: Option<Arc<CallLauncher>>,
126 126 pub call_count: u64,
127 127 pub call_share_sound: bool,
128 pub call_share_motion: bool,
129 pub call_share_standout: bool,
130 pub call_strip_width: f32,
128 131 pub call_view: crate::call::ViewSettings,
129 132 pub call_background: crate::call::BackgroundPick,
130 133 pub call_camera: calling::DeviceChoice,
@@ -232,6 +235,9 @@ impl AppState {
232 235 call_launcher: None,
233 236 call_count: 0,
234 237 call_share_sound: false,
238 call_share_motion: false,
239 call_share_standout: false,
240 call_strip_width: crate::call::STRIP_DEFAULT_WIDTH,
235 241 call_view: crate::call::ViewSettings::default(),
236 242 call_background: crate::call::BackgroundPick::None,
237 243 call_camera: calling::DeviceChoice::SystemDefault,
@@ -260,6 +266,9 @@ impl AppState {
260 266 state.local_previews = load_local_previews(&state.store);
261 267 state.collapsed = state.load_collapsed();
262 268 state.call_share_sound = crate::call::load_share_sound(&state.store);
269 state.call_share_motion = crate::call::load_flag(&state.store, crate::call::SHARE_MOTION_META_KEY);
270 state.call_share_standout = crate::call::load_flag(&state.store, crate::call::SHARE_STANDOUT_META_KEY);
271 state.call_strip_width = crate::call::load_strip_width(&state.store);
263 272 state.call_view = crate::call::ViewSettings::load(&state.store);
264 273 state.call_background = crate::call::load_background(&state.store);
265 274 state.call_camera = crate::call::load_camera(&state.store);
@@ -125,6 +125,9 @@ pub struct AppState {
125 pub call_launcher: Option<Arc<CallLauncher>>,
125 pub call_launcher: Option<Arc<CallLauncher>>,
126 pub call_count: u64,
126 pub call_count: u64,
127 pub call_share_sound: bool,
127 pub call_share_sound: bool,
128 pub call_share_motion: bool,
129 pub call_share_standout: bool,
130 pub call_strip_width: f32,
128 pub call_view: crate::call::ViewSettings,
131 pub call_view: crate::call::ViewSettings,
129 pub call_background: crate::call::BackgroundPick,
132 pub call_background: crate::call::BackgroundPick,
130 pub call_camera: calling::DeviceChoice,
133 pub call_camera: calling::DeviceChoice,
@@ -232,6 +235,9 @@ impl AppState {
232 call_launcher: None,
235 call_launcher: None,
233 call_count: 0,
236 call_count: 0,
234 call_share_sound: false,
237 call_share_sound: false,
238 call_share_motion: false,
239 call_share_standout: false,
240 call_strip_width: crate::call::STRIP_DEFAULT_WIDTH,
235 call_view: crate::call::ViewSettings::default(),
241 call_view: crate::call::ViewSettings::default(),
236 call_background: crate::call::BackgroundPick::None,
242 call_background: crate::call::BackgroundPick::None,
237 call_camera: calling::DeviceChoice::SystemDefault,
243 call_camera: calling::DeviceChoice::SystemDefault,
@@ -260,6 +266,9 @@ impl AppState {
260 state.local_previews = load_local_previews(&state.store);
266 state.local_previews = load_local_previews(&state.store);
261 state.collapsed = state.load_collapsed();
267 state.collapsed = state.load_collapsed();
262 state.call_share_sound = crate::call::load_share_sound(&state.store);
268 state.call_share_sound = crate::call::load_share_sound(&state.store);
269 state.call_share_motion = crate::call::load_flag(&state.store, crate::call::SHARE_MOTION_META_KEY);
270 state.call_share_standout = crate::call::load_flag(&state.store, crate::call::SHARE_STANDOUT_META_KEY);
271 state.call_strip_width = crate::call::load_strip_width(&state.store);
263 state.call_view = crate::call::ViewSettings::load(&state.store);
272 state.call_view = crate::call::ViewSettings::load(&state.store);
264 state.call_background = crate::call::load_background(&state.store);
273 state.call_background = crate::call::load_background(&state.store);
265 state.call_camera = crate::call::load_camera(&state.store);
274 state.call_camera = crate::call::load_camera(&state.store);
crates/app/src/call/actions.rs +7 −0
@@ -226,6 +226,12 @@ impl AppState {
226 226 if self.call_share_sound {
227 227 self.send_call_command(CallCommand::SetShareSound(true));
228 228 }
229 if self.call_share_motion {
230 self.send_call_command(CallCommand::SetShareMotion(true));
231 }
232 if self.call_share_standout {
233 self.send_call_command(CallCommand::SetShareStandout(true));
234 }
229 235 if self.call_mic != MicSettings::default() {
230 236 self.send_call_command(CallCommand::SetMicSettings(self.call_mic));
231 237 }
@@ -368,6 +374,7 @@ impl AppState {
368 374 }
369 375 if call.model.screen_sharer.is_none() {
370 376 call.stage_fullscreen = false;
377 call.share_stage.end();
371 378 call.pictures.forget(&VideoKey::Screen, cx);
372 379 }
373 380 if !call.model.camera_on {
@@ -226,6 +226,12 @@ impl AppState {
226 if self.call_share_sound {
226 if self.call_share_sound {
227 self.send_call_command(CallCommand::SetShareSound(true));
227 self.send_call_command(CallCommand::SetShareSound(true));
228 }
228 }
229 if self.call_share_motion {
230 self.send_call_command(CallCommand::SetShareMotion(true));
231 }
232 if self.call_share_standout {
233 self.send_call_command(CallCommand::SetShareStandout(true));
234 }
229 if self.call_mic != MicSettings::default() {
235 if self.call_mic != MicSettings::default() {
230 self.send_call_command(CallCommand::SetMicSettings(self.call_mic));
236 self.send_call_command(CallCommand::SetMicSettings(self.call_mic));
231 }
237 }
@@ -368,6 +374,7 @@ impl AppState {
368 }
374 }
369 if call.model.screen_sharer.is_none() {
375 if call.model.screen_sharer.is_none() {
370 call.stage_fullscreen = false;
376 call.stage_fullscreen = false;
377 call.share_stage.end();
371 call.pictures.forget(&VideoKey::Screen, cx);
378 call.pictures.forget(&VideoKey::Screen, cx);
372 }
379 }
373 if !call.model.camera_on {
380 if !call.model.camera_on {
crates/app/src/call/demo.rs +11 −3
@@ -93,6 +93,7 @@ pub enum DemoScene {
93 93 Whiteboard,
94 94 Network,
95 95 Gallery,
96 Sharing,
96 97 }
97 98
98 99 impl DemoScene {
@@ -107,6 +108,7 @@ impl DemoScene {
107 108 "whiteboard" => DemoScene::Whiteboard,
108 109 "network" => DemoScene::Network,
109 110 "gallery" => DemoScene::Gallery,
111 "sharing" => DemoScene::Sharing,
110 112 _ => return None,
111 113 })
112 114 }
@@ -116,7 +118,11 @@ impl DemoScene {
116 118 }
117 119
118 120 pub fn guests(self) -> Option<usize> {
119 (self == DemoScene::Gallery).then_some(DEMO_GALLERY_GUESTS)
121 match self {
122 DemoScene::Gallery => Some(DEMO_GALLERY_GUESTS),
123 DemoScene::Sharing => Some(DEMO_SHARING_GUESTS),
124 _ => None,
125 }
120 126 }
121 127
122 128 fn cameras(self) -> usize {
@@ -135,6 +141,7 @@ impl DemoScene {
135 141 }
136 142
137 143 pub const DEMO_GALLERY_GUESTS: usize = 12;
144 const DEMO_SHARING_GUESTS: usize = 6;
138 145 const BREAKOUT_AT_TICKS: u32 = 20;
139 146 const WHITEBOARD_AT_TICKS: u32 = 5;
140 147 const DEMO_BOARD_URL: &str = "https://app.whiteboard.microsoft.com/me/whiteboards/demo";
@@ -403,6 +410,7 @@ fn start_scene(control: &CallControl, scene: DemoScene) {
403 410 | DemoScene::Breakout
404 411 | DemoScene::Whiteboard
405 412 | DemoScene::Gallery
413 | DemoScene::Sharing
406 414 | DemoScene::Plain => {}
407 415 }
408 416 }
@@ -488,7 +496,7 @@ async fn speak_until_hangup(
488 496 tokio::select! {
489 497 _ = video_tick.tick(), if video || camera_on => {
490 498 let elapsed = started.elapsed();
491 let share_now = sharer.is_some() && (SHARE_START..SHARE_END).contains(&elapsed);
499 let share_now = sharer.is_some() && (scene == DemoScene::Sharing || (SHARE_START..SHARE_END).contains(&elapsed));
492 500 if share_now != sharing {
493 501 sharing = share_now;
494 502 control.send(CallUpdate::ScreenShare(sharer.clone().filter(|_| sharing)));
@@ -642,7 +650,7 @@ async fn speak_until_hangup(
642 650 people.iter().for_each(|(mri, _)| control.video.forget(&VideoKey::Person(mri.clone())));
643 651 control.send(CallUpdate::IncomingVideo(enabled));
644 652 }
645 Some(CallCommand::SetCameraEffects(_)) => {}
653 Some(CallCommand::SetCameraEffects(_) | CallCommand::SetVideoWants(_) | CallCommand::SetShareMotion(_) | CallCommand::SetShareStandout(_)) => {}
646 654 Some(CallCommand::StartRecording { kind, .. }) => {
647 655 recording_on = kind != RecordingKind::TranscriptOnly;
648 656 transcribing_on = true;
@@ -93,6 +93,7 @@ pub enum DemoScene {
93 Whiteboard,
93 Whiteboard,
94 Network,
94 Network,
95 Gallery,
95 Gallery,
96 Sharing,
96}
97}
97
98
98impl DemoScene {
99impl DemoScene {
@@ -107,6 +108,7 @@ impl DemoScene {
107 "whiteboard" => DemoScene::Whiteboard,
108 "whiteboard" => DemoScene::Whiteboard,
108 "network" => DemoScene::Network,
109 "network" => DemoScene::Network,
109 "gallery" => DemoScene::Gallery,
110 "gallery" => DemoScene::Gallery,
111 "sharing" => DemoScene::Sharing,
110 _ => return None,
112 _ => return None,
111 })
113 })
112 }
114 }
@@ -116,7 +118,11 @@ impl DemoScene {
116 }
118 }
117
119
118 pub fn guests(self) -> Option<usize> {
120 pub fn guests(self) -> Option<usize> {
119 (self == DemoScene::Gallery).then_some(DEMO_GALLERY_GUESTS)
121 match self {
122 DemoScene::Gallery => Some(DEMO_GALLERY_GUESTS),
123 DemoScene::Sharing => Some(DEMO_SHARING_GUESTS),
124 _ => None,
125 }
120 }
126 }
121
127
122 fn cameras(self) -> usize {
128 fn cameras(self) -> usize {
@@ -135,6 +141,7 @@ impl DemoScene {
135}
141}
136
142
137pub const DEMO_GALLERY_GUESTS: usize = 12;
143pub const DEMO_GALLERY_GUESTS: usize = 12;
144const DEMO_SHARING_GUESTS: usize = 6;
138const BREAKOUT_AT_TICKS: u32 = 20;
145const BREAKOUT_AT_TICKS: u32 = 20;
139const WHITEBOARD_AT_TICKS: u32 = 5;
146const WHITEBOARD_AT_TICKS: u32 = 5;
140const DEMO_BOARD_URL: &str = "https://app.whiteboard.microsoft.com/me/whiteboards/demo";
147const DEMO_BOARD_URL: &str = "https://app.whiteboard.microsoft.com/me/whiteboards/demo";
@@ -403,6 +410,7 @@ fn start_scene(control: &CallControl, scene: DemoScene) {
403 | DemoScene::Breakout
410 | DemoScene::Breakout
404 | DemoScene::Whiteboard
411 | DemoScene::Whiteboard
405 | DemoScene::Gallery
412 | DemoScene::Gallery
413 | DemoScene::Sharing
406 | DemoScene::Plain => {}
414 | DemoScene::Plain => {}
407 }
415 }
408}
416}
@@ -488,7 +496,7 @@ async fn speak_until_hangup(
488 tokio::select! {
496 tokio::select! {
489 _ = video_tick.tick(), if video || camera_on => {
497 _ = video_tick.tick(), if video || camera_on => {
490 let elapsed = started.elapsed();
498 let elapsed = started.elapsed();
491 let share_now = sharer.is_some() && (SHARE_START..SHARE_END).contains(&elapsed);
499 let share_now = sharer.is_some() && (scene == DemoScene::Sharing || (SHARE_START..SHARE_END).contains(&elapsed));
492 if share_now != sharing {
500 if share_now != sharing {
493 sharing = share_now;
501 sharing = share_now;
494 control.send(CallUpdate::ScreenShare(sharer.clone().filter(|_| sharing)));
502 control.send(CallUpdate::ScreenShare(sharer.clone().filter(|_| sharing)));
@@ -642,7 +650,7 @@ async fn speak_until_hangup(
642 people.iter().for_each(|(mri, _)| control.video.forget(&VideoKey::Person(mri.clone())));
650 people.iter().for_each(|(mri, _)| control.video.forget(&VideoKey::Person(mri.clone())));
643 control.send(CallUpdate::IncomingVideo(enabled));
651 control.send(CallUpdate::IncomingVideo(enabled));
644 }
652 }
645 Some(CallCommand::SetCameraEffects(_)) => {}
653 Some(CallCommand::SetCameraEffects(_) | CallCommand::SetVideoWants(_) | CallCommand::SetShareMotion(_) | CallCommand::SetShareStandout(_)) => {}
646 Some(CallCommand::StartRecording { kind, .. }) => {
654 Some(CallCommand::StartRecording { kind, .. }) => {
647 recording_on = kind != RecordingKind::TranscriptOnly;
655 recording_on = kind != RecordingKind::TranscriptOnly;
648 transcribing_on = true;
656 transcribing_on = true;
crates/app/src/call/mod.rs +5 −1
@@ -27,6 +27,8 @@ mod preview;
27 27 mod push_to_talk;
28 28 mod recording_menu;
29 29 mod reminder;
30 mod share_actions;
31 mod share_view;
30 32 mod ring;
31 33 mod schedule;
32 34 mod stage_layout;
@@ -62,10 +64,12 @@ pub use options_dialog::OptionsDialog;
62 64 pub use overlay::CallWindows;
63 65 pub use prejoin::{AudioChoice, JoinOptions, PendingJoin, load_join_options};
64 66 pub use people::{PeopleSections, PersonRow, people_sections};
67 pub use share_actions::ZoomStep;
68 pub use share_view::{SHARE_MOTION_META_KEY, SHARE_STANDOUT_META_KEY, STRIP_DEFAULT_WIDTH, ShareStage, load_flag, load_strip_width};
65 69 pub use preview::{CameraPreview, preview_backgrounds};
66 70 pub use reminder::{MeetingToasts, subtitle as meeting_subtitle};
67 71 pub use ring::{MissedCall, RingEntry, Rings};
68 pub use stage_layout::{FILMSTRIP_MAX, GALLERY_MAX, filmstrip, gallery_grid, split_overflow};
72 pub use stage_layout::{FILMSTRIP_MAX, Filmstrip, GALLERY_MAX, Overflow, filmstrip, gallery_grid, split_overflow};
69 73 pub use schedule::{FormValues, Invitee, default_window, draft_from_form};
70 74 pub use recording_menu::{RecordAction, RecordingChip, record_actions, recording_chip};
71 75 pub use target::plan_for_chat;
@@ -27,6 +27,8 @@ mod preview;
27mod push_to_talk;
27mod push_to_talk;
28mod recording_menu;
28mod recording_menu;
29mod reminder;
29mod reminder;
30mod share_actions;
31mod share_view;
30mod ring;
32mod ring;
31mod schedule;
33mod schedule;
32mod stage_layout;
34mod stage_layout;
@@ -62,10 +64,12 @@ pub use options_dialog::OptionsDialog;
62pub use overlay::CallWindows;
64pub use overlay::CallWindows;
63pub use prejoin::{AudioChoice, JoinOptions, PendingJoin, load_join_options};
65pub use prejoin::{AudioChoice, JoinOptions, PendingJoin, load_join_options};
64pub use people::{PeopleSections, PersonRow, people_sections};
66pub use people::{PeopleSections, PersonRow, people_sections};
67pub use share_actions::ZoomStep;
68pub use share_view::{SHARE_MOTION_META_KEY, SHARE_STANDOUT_META_KEY, STRIP_DEFAULT_WIDTH, ShareStage, load_flag, load_strip_width};
65pub use preview::{CameraPreview, preview_backgrounds};
69pub use preview::{CameraPreview, preview_backgrounds};
66pub use reminder::{MeetingToasts, subtitle as meeting_subtitle};
70pub use reminder::{MeetingToasts, subtitle as meeting_subtitle};
67pub use ring::{MissedCall, RingEntry, Rings};
71pub use ring::{MissedCall, RingEntry, Rings};
68pub use stage_layout::{FILMSTRIP_MAX, GALLERY_MAX, filmstrip, gallery_grid, split_overflow};
72pub use stage_layout::{FILMSTRIP_MAX, Filmstrip, GALLERY_MAX, Overflow, filmstrip, gallery_grid, split_overflow};
69pub use schedule::{FormValues, Invitee, default_window, draft_from_form};
73pub use schedule::{FormValues, Invitee, default_window, draft_from_form};
70pub use recording_menu::{RecordAction, RecordingChip, record_actions, recording_chip};
74pub use recording_menu::{RecordAction, RecordingChip, record_actions, recording_chip};
71pub use target::plan_for_chat;
75pub use target::plan_for_chat;
crates/app/src/call/model.rs +6 −0
@@ -7,6 +7,7 @@ use calling::{
7 7 AttendeeLimits, CallCommand, CallState, CallUpdate, CameraDevice, CaptionEntry, CaptionState, ContentShare,
8 8 DeviceChoice, DeviceLists, EndKind, EndReason, HoldState, MeetingCapability, MeetingRole,
9 9 MeetingTarget, Progress, Reaction, RosterEntry, ShareKind, ShareSource, SpeakingDetector, VideoHub,
10 VideoWant,
10 11 };
11 12 use tokio::sync::mpsc::UnboundedSender;
12 13
@@ -20,6 +21,7 @@ use super::transcript::{Transcript, TranscriptEntry};
20 21 use super::view_settings::{CallLayout, ViewSettings};
21 22 use super::options_dialog::OptionsDialog;
22 23 use super::push_to_talk::PushToTalk;
24 use super::share_view::ShareStage;
23 25
24 26 pub const TEST_CALL_TITLE: &str = "Test call";
25 27 pub const ECHO_NAME: &str = "Teams echo";
@@ -44,6 +46,8 @@ pub struct ActiveCall {
44 46 pub stage_fullscreen: bool,
45 47 pub fullscreen: Option<FullscreenState>,
46 48 pub stage_size: Rc<Cell<(f32, f32)>>,
49 pub sent_wants: Vec<VideoWant>,
50 pub share_stage: ShareStage,
47 51 pub bubbles: Vec<ChatBubble>,
48 52 pub share_menu_open: bool,
49 53 pub lobby_list_open: bool,
@@ -110,6 +114,8 @@ impl ActiveCall {
110 114 stage_fullscreen: false,
111 115 fullscreen: None,
112 116 stage_size: Rc::default(),
117 sent_wants: Vec::new(),
118 share_stage: ShareStage::default(),
113 119 bubbles: Vec::new(),
114 120 share_menu_open: false,
115 121 lobby_list_open: false,
@@ -7,6 +7,7 @@ use calling::{
7 AttendeeLimits, CallCommand, CallState, CallUpdate, CameraDevice, CaptionEntry, CaptionState, ContentShare,
7 AttendeeLimits, CallCommand, CallState, CallUpdate, CameraDevice, CaptionEntry, CaptionState, ContentShare,
8 DeviceChoice, DeviceLists, EndKind, EndReason, HoldState, MeetingCapability, MeetingRole,
8 DeviceChoice, DeviceLists, EndKind, EndReason, HoldState, MeetingCapability, MeetingRole,
9 MeetingTarget, Progress, Reaction, RosterEntry, ShareKind, ShareSource, SpeakingDetector, VideoHub,
9 MeetingTarget, Progress, Reaction, RosterEntry, ShareKind, ShareSource, SpeakingDetector, VideoHub,
10 VideoWant,
10};
11};
11use tokio::sync::mpsc::UnboundedSender;
12use tokio::sync::mpsc::UnboundedSender;
12
13
@@ -20,6 +21,7 @@ use super::transcript::{Transcript, TranscriptEntry};
20use super::view_settings::{CallLayout, ViewSettings};
21use super::view_settings::{CallLayout, ViewSettings};
21use super::options_dialog::OptionsDialog;
22use super::options_dialog::OptionsDialog;
22use super::push_to_talk::PushToTalk;
23use super::push_to_talk::PushToTalk;
24use super::share_view::ShareStage;
23
25
24pub const TEST_CALL_TITLE: &str = "Test call";
26pub const TEST_CALL_TITLE: &str = "Test call";
25pub const ECHO_NAME: &str = "Teams echo";
27pub const ECHO_NAME: &str = "Teams echo";
@@ -44,6 +46,8 @@ pub struct ActiveCall {
44 pub stage_fullscreen: bool,
46 pub stage_fullscreen: bool,
45 pub fullscreen: Option<FullscreenState>,
47 pub fullscreen: Option<FullscreenState>,
46 pub stage_size: Rc<Cell<(f32, f32)>>,
48 pub stage_size: Rc<Cell<(f32, f32)>>,
49 pub sent_wants: Vec<VideoWant>,
50 pub share_stage: ShareStage,
47 pub bubbles: Vec<ChatBubble>,
51 pub bubbles: Vec<ChatBubble>,
48 pub share_menu_open: bool,
52 pub share_menu_open: bool,
49 pub lobby_list_open: bool,
53 pub lobby_list_open: bool,
@@ -110,6 +114,8 @@ impl ActiveCall {
110 stage_fullscreen: false,
114 stage_fullscreen: false,
111 fullscreen: None,
115 fullscreen: None,
112 stage_size: Rc::default(),
116 stage_size: Rc::default(),
117 sent_wants: Vec::new(),
118 share_stage: ShareStage::default(),
113 bubbles: Vec::new(),
119 bubbles: Vec::new(),
114 share_menu_open: false,
120 share_menu_open: false,
115 lobby_list_open: false,
121 lobby_list_open: false,
crates/app/src/call/overlay.rs +65 −3
@@ -12,6 +12,7 @@ use super::overlay_layout::{
12 12 use crate::app_state::AppState;
13 13 use crate::notify::platform::{self, NativeHandle, ScreenRect, ShareGeometry, WorkArea};
14 14 use crate::views::call_mini_window::MiniWindowView;
15 use crate::views::call_pop_out::{POP_OUT_SIZE, POP_OUT_TITLE, SharePopOutView};
15 16 use crate::views::share_bar::{ShareBarView, ShareBorderView};
16 17
17 18 const TICK: Duration = Duration::from_millis(100);
@@ -61,6 +62,8 @@ pub struct CallWindows {
61 62 windows: HashMap<Role, Placed>,
62 63 opening: HashSet<Role>,
63 64 share: Option<ShareSession>,
65 pop_out: Option<AnyWindowHandle>,
66 pop_out_opening: bool,
64 67 pinned: bool,
65 68 bar_idle_since: Instant,
66 69 bar_collapsed: bool,
@@ -126,6 +129,8 @@ impl CallWindows {
126 129 windows: HashMap::new(),
127 130 opening: HashSet::new(),
128 131 share: None,
132 pop_out: None,
133 pop_out_opening: false,
129 134 pinned: false,
130 135 bar_idle_since: Instant::now(),
131 136 bar_collapsed: false,
@@ -213,6 +218,7 @@ impl CallWindows {
213 218 let slow = self.ticks % SLOW_TICK_EVERY == 0;
214 219 self.refresh_main_window();
215 220 self.sync_share(slow, cx);
221 self.sync_pop_out(cx);
216 222 self.sync_mini(cx);
217 223 if slow {
218 224 self.track_mini_position(cx);
@@ -316,6 +322,60 @@ impl CallWindows {
316 322 }
317 323 }
318 324
325 fn sync_pop_out(&mut self, cx: &mut Context<Self>) {
326 let wanted = self
327 .app
328 .read(cx)
329 .call
330 .as_ref()
331 .is_some_and(|call| call.share_stage.popped && call.model.screen_sharer.is_some());
332 match (wanted, self.pop_out) {
333 (true, None) => self.open_pop_out(cx),
334 (false, Some(handle)) => {
335 self.pop_out = None;
336 handle.update(cx, |_, window, _| window.remove_window()).ok();
337 }
338 (true, Some(handle)) => {
339 if handle.update(cx, |_, _, _| ()).is_err() {
340 self.pop_out = None;
341 self.app.update(cx, |state, cx| state.return_stage_from_pop_out(cx));
342 }
343 }
344 (false, None) => {}
345 }
346 }
347
348 fn open_pop_out(&mut self, cx: &mut Context<Self>) {
349 if self.pop_out_opening {
350 return;
351 }
352 self.pop_out_opening = true;
353 let controller = cx.entity();
354 let app = self.app.clone();
355 let options = WindowOptions {
356 window_bounds: Some(WindowBounds::Windowed(Bounds::centered(
357 None,
358 size(px(POP_OUT_SIZE.0), px(POP_OUT_SIZE.1)),
359 cx,
360 ))),
361 titlebar: Some(TitlebarOptions {
362 title: Some(POP_OUT_TITLE.into()),
363 ..Default::default()
364 }),
365 ..Default::default()
366 };
367 // open_window draws right away, and the view reads the app entity while rendering.
368 cx.defer(move |cx| {
369 let opened = gpui_kit::open_window(options, cx, move |window, cx| {
370 cx.new(|cx| SharePopOutView::new(app, window, cx))
371 });
372 controller.update(cx, |this, _| {
373 this.pop_out_opening = false;
374 this.pop_out = opened.ok().map(|(handle, _)| handle);
375 });
376 });
377 }
378
319 379 fn sync_mini(&mut self, cx: &mut Context<Self>) {
320 380 let in_call = self.app.read(cx).call.is_some();
321 381 let work = self.work_area.or_else(|| display_work_area(cx));
@@ -406,9 +466,11 @@ impl CallWindows {
406 466 if let Some(native) = native {
407 467 platform::prepare_toast_window(native);
408 468 platform::exclude_from_capture(native);
409 if matches!(role, Role::Border(_)) {
410 platform::make_click_through(native);
411 }
469 }
470 if matches!(role, Role::Border(_)) {
471 handle
472 .update(cx, |_, window, _| platform::make_window_click_through(window))
473 .ok();
412 474 }
413 475 Placed {
414 476 handle,
@@ -12,6 +12,7 @@ use super::overlay_layout::{
12use crate::app_state::AppState;
12use crate::app_state::AppState;
13use crate::notify::platform::{self, NativeHandle, ScreenRect, ShareGeometry, WorkArea};
13use crate::notify::platform::{self, NativeHandle, ScreenRect, ShareGeometry, WorkArea};
14use crate::views::call_mini_window::MiniWindowView;
14use crate::views::call_mini_window::MiniWindowView;
15use crate::views::call_pop_out::{POP_OUT_SIZE, POP_OUT_TITLE, SharePopOutView};
15use crate::views::share_bar::{ShareBarView, ShareBorderView};
16use crate::views::share_bar::{ShareBarView, ShareBorderView};
16
17
17const TICK: Duration = Duration::from_millis(100);
18const TICK: Duration = Duration::from_millis(100);
@@ -61,6 +62,8 @@ pub struct CallWindows {
61 windows: HashMap<Role, Placed>,
62 windows: HashMap<Role, Placed>,
62 opening: HashSet<Role>,
63 opening: HashSet<Role>,
63 share: Option<ShareSession>,
64 share: Option<ShareSession>,
65 pop_out: Option<AnyWindowHandle>,
66 pop_out_opening: bool,
64 pinned: bool,
67 pinned: bool,
65 bar_idle_since: Instant,
68 bar_idle_since: Instant,
66 bar_collapsed: bool,
69 bar_collapsed: bool,
@@ -126,6 +129,8 @@ impl CallWindows {
126 windows: HashMap::new(),
129 windows: HashMap::new(),
127 opening: HashSet::new(),
130 opening: HashSet::new(),
128 share: None,
131 share: None,
132 pop_out: None,
133 pop_out_opening: false,
129 pinned: false,
134 pinned: false,
130 bar_idle_since: Instant::now(),
135 bar_idle_since: Instant::now(),
131 bar_collapsed: false,
136 bar_collapsed: false,
@@ -213,6 +218,7 @@ impl CallWindows {
213 let slow = self.ticks % SLOW_TICK_EVERY == 0;
218 let slow = self.ticks % SLOW_TICK_EVERY == 0;
214 self.refresh_main_window();
219 self.refresh_main_window();
215 self.sync_share(slow, cx);
220 self.sync_share(slow, cx);
221 self.sync_pop_out(cx);
216 self.sync_mini(cx);
222 self.sync_mini(cx);
217 if slow {
223 if slow {
218 self.track_mini_position(cx);
224 self.track_mini_position(cx);
@@ -316,6 +322,60 @@ impl CallWindows {
316 }
322 }
317 }
323 }
318
324
325 fn sync_pop_out(&mut self, cx: &mut Context<Self>) {
326 let wanted = self
327 .app
328 .read(cx)
329 .call
330 .as_ref()
331 .is_some_and(|call| call.share_stage.popped && call.model.screen_sharer.is_some());
332 match (wanted, self.pop_out) {
333 (true, None) => self.open_pop_out(cx),
334 (false, Some(handle)) => {
335 self.pop_out = None;
336 handle.update(cx, |_, window, _| window.remove_window()).ok();
337 }
338 (true, Some(handle)) => {
339 if handle.update(cx, |_, _, _| ()).is_err() {
340 self.pop_out = None;
341 self.app.update(cx, |state, cx| state.return_stage_from_pop_out(cx));
342 }
343 }
344 (false, None) => {}
345 }
346 }
347
348 fn open_pop_out(&mut self, cx: &mut Context<Self>) {
349 if self.pop_out_opening {
350 return;
351 }
352 self.pop_out_opening = true;
353 let controller = cx.entity();
354 let app = self.app.clone();
355 let options = WindowOptions {
356 window_bounds: Some(WindowBounds::Windowed(Bounds::centered(
357 None,
358 size(px(POP_OUT_SIZE.0), px(POP_OUT_SIZE.1)),
359 cx,
360 ))),
361 titlebar: Some(TitlebarOptions {
362 title: Some(POP_OUT_TITLE.into()),
363 ..Default::default()
364 }),
365 ..Default::default()
366 };
367 // open_window draws right away, and the view reads the app entity while rendering.
368 cx.defer(move |cx| {
369 let opened = gpui_kit::open_window(options, cx, move |window, cx| {
370 cx.new(|cx| SharePopOutView::new(app, window, cx))
371 });
372 controller.update(cx, |this, _| {
373 this.pop_out_opening = false;
374 this.pop_out = opened.ok().map(|(handle, _)| handle);
375 });
376 });
377 }
378
319 fn sync_mini(&mut self, cx: &mut Context<Self>) {
379 fn sync_mini(&mut self, cx: &mut Context<Self>) {
320 let in_call = self.app.read(cx).call.is_some();
380 let in_call = self.app.read(cx).call.is_some();
321 let work = self.work_area.or_else(|| display_work_area(cx));
381 let work = self.work_area.or_else(|| display_work_area(cx));
@@ -406,9 +466,11 @@ impl CallWindows {
406 if let Some(native) = native {
466 if let Some(native) = native {
407 platform::prepare_toast_window(native);
467 platform::prepare_toast_window(native);
408 platform::exclude_from_capture(native);
468 platform::exclude_from_capture(native);
409 if matches!(role, Role::Border(_)) {
469 }
410 platform::make_click_through(native);
470 if matches!(role, Role::Border(_)) {
411 }
471 handle
472 .update(cx, |_, window, _| platform::make_window_click_through(window))
473 .ok();
412 }
474 }
413 Placed {
475 Placed {
414 handle,
476 handle,
crates/app/src/call/share_actions.rs added +110 −0
@@ -0,0 +1,110 @@
1 use calling::CallCommand;
2 use gpui_kit::*;
3
4 use super::share_view::{
5 SHARE_MOTION_META_KEY, SHARE_STANDOUT_META_KEY, STRIP_WIDTH_META_KEY, StripDrag, clamp_strip_width,
6 };
7 use crate::app_state::{AppEvent, AppState};
8
9 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
10 pub enum ZoomStep {
11 In,
12 Out,
13 Reset,
14 }
15
16 fn flag_text(on: bool) -> &'static str {
17 if on { "1" } else { "0" }
18 }
19
20 impl AppState {
21 fn change_share_stage(&mut self, cx: &mut Context<Self>, change: impl FnOnce(&mut super::share_view::ShareStage)) {
22 let Some(call) = self.call.as_mut().filter(|call| call.model.screen_sharer.is_some()) else {
23 return;
24 };
25 change(&mut call.share_stage);
26 cx.emit(AppEvent::Call);
27 cx.notify();
28 }
29
30 pub fn zoom_share_wheel(&mut self, scroll_pixels: f32, position: (f32, f32), cx: &mut Context<Self>) {
31 self.change_share_stage(cx, |stage| {
32 let (pointer, size) = (stage.pointer(position), stage.size());
33 stage.view.zoom_wheel(scroll_pixels, pointer, size);
34 });
35 }
36
37 pub fn zoom_share(&mut self, step: ZoomStep, cx: &mut Context<Self>) {
38 self.change_share_stage(cx, |stage| {
39 let size = stage.size();
40 match step {
41 ZoomStep::In => stage.view.step_in(size),
42 ZoomStep::Out => stage.view.step_out(size),
43 ZoomStep::Reset => stage.view.reset(),
44 }
45 });
46 }
47
48 pub fn begin_share_pan(&mut self, position: (f32, f32), cx: &mut Context<Self>) {
49 self.change_share_stage(cx, |stage| stage.pan_from = Some(position));
50 }
51
52 pub fn pan_share_to(&mut self, position: (f32, f32), cx: &mut Context<Self>) {
53 self.change_share_stage(cx, |stage| {
54 let Some(from) = stage.pan_from.replace(position) else {
55 return;
56 };
57 let size = stage.size();
58 stage.view.pan_by((position.0 - from.0, position.1 - from.1), size);
59 });
60 }
61
62 pub fn end_share_pan(&mut self, cx: &mut Context<Self>) {
63 self.change_share_stage(cx, |stage| stage.pan_from = None);
64 }
65
66 pub fn begin_strip_drag(&mut self, pointer_x: f32, cx: &mut Context<Self>) {
67 let start_width = self.call_strip_width;
68 self.change_share_stage(cx, |stage| stage.strip_drag = Some(StripDrag { start_pointer: pointer_x, start_width }));
69 }
70
71 pub fn drag_strip_to(&mut self, pointer_x: f32, cx: &mut Context<Self>) {
72 let Some(drag) = self.call.as_ref().and_then(|call| call.share_stage.strip_drag) else {
73 return;
74 };
75 self.call_strip_width = drag.width_at(pointer_x);
76 cx.notify();
77 }
78
79 pub fn end_strip_drag(&mut self, cx: &mut Context<Self>) {
80 if self.call.as_ref().is_none_or(|call| call.share_stage.strip_drag.is_none()) {
81 return;
82 }
83 let width = clamp_strip_width(self.call_strip_width);
84 self.call_strip_width = width;
85 let _ = self.store.set_meta(STRIP_WIDTH_META_KEY, &width.to_string());
86 self.change_share_stage(cx, |stage| stage.strip_drag = None);
87 }
88
89 pub fn pop_out_stage(&mut self, cx: &mut Context<Self>) {
90 self.change_share_stage(cx, |stage| stage.popped = true);
91 }
92
93 pub fn return_stage_from_pop_out(&mut self, cx: &mut Context<Self>) {
94 self.change_share_stage(cx, |stage| stage.popped = false);
95 }
96
97 pub fn set_call_share_motion(&mut self, on: bool, cx: &mut Context<Self>) {
98 self.call_share_motion = on;
99 let _ = self.store.set_meta(SHARE_MOTION_META_KEY, flag_text(on));
100 self.send_call_command(CallCommand::SetShareMotion(on));
101 cx.notify();
102 }
103
104 pub fn set_call_share_standout(&mut self, on: bool, cx: &mut Context<Self>) {
105 self.call_share_standout = on;
106 let _ = self.store.set_meta(SHARE_STANDOUT_META_KEY, flag_text(on));
107 self.send_call_command(CallCommand::SetShareStandout(on));
108 cx.notify();
109 }
110 }
@@ -0,0 +1,110 @@
1use calling::CallCommand;
2use gpui_kit::*;
3
4use super::share_view::{
5 SHARE_MOTION_META_KEY, SHARE_STANDOUT_META_KEY, STRIP_WIDTH_META_KEY, StripDrag, clamp_strip_width,
6};
7use crate::app_state::{AppEvent, AppState};
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum ZoomStep {
11 In,
12 Out,
13 Reset,
14}
15
16fn flag_text(on: bool) -> &'static str {
17 if on { "1" } else { "0" }
18}
19
20impl AppState {
21 fn change_share_stage(&mut self, cx: &mut Context<Self>, change: impl FnOnce(&mut super::share_view::ShareStage)) {
22 let Some(call) = self.call.as_mut().filter(|call| call.model.screen_sharer.is_some()) else {
23 return;
24 };
25 change(&mut call.share_stage);
26 cx.emit(AppEvent::Call);
27 cx.notify();
28 }
29
30 pub fn zoom_share_wheel(&mut self, scroll_pixels: f32, position: (f32, f32), cx: &mut Context<Self>) {
31 self.change_share_stage(cx, |stage| {
32 let (pointer, size) = (stage.pointer(position), stage.size());
33 stage.view.zoom_wheel(scroll_pixels, pointer, size);
34 });
35 }
36
37 pub fn zoom_share(&mut self, step: ZoomStep, cx: &mut Context<Self>) {
38 self.change_share_stage(cx, |stage| {
39 let size = stage.size();
40 match step {
41 ZoomStep::In => stage.view.step_in(size),
42 ZoomStep::Out => stage.view.step_out(size),
43 ZoomStep::Reset => stage.view.reset(),
44 }
45 });
46 }
47
48 pub fn begin_share_pan(&mut self, position: (f32, f32), cx: &mut Context<Self>) {
49 self.change_share_stage(cx, |stage| stage.pan_from = Some(position));
50 }
51
52 pub fn pan_share_to(&mut self, position: (f32, f32), cx: &mut Context<Self>) {
53 self.change_share_stage(cx, |stage| {
54 let Some(from) = stage.pan_from.replace(position) else {
55 return;
56 };
57 let size = stage.size();
58 stage.view.pan_by((position.0 - from.0, position.1 - from.1), size);
59 });
60 }
61
62 pub fn end_share_pan(&mut self, cx: &mut Context<Self>) {
63 self.change_share_stage(cx, |stage| stage.pan_from = None);
64 }
65
66 pub fn begin_strip_drag(&mut self, pointer_x: f32, cx: &mut Context<Self>) {
67 let start_width = self.call_strip_width;
68 self.change_share_stage(cx, |stage| stage.strip_drag = Some(StripDrag { start_pointer: pointer_x, start_width }));
69 }
70
71 pub fn drag_strip_to(&mut self, pointer_x: f32, cx: &mut Context<Self>) {
72 let Some(drag) = self.call.as_ref().and_then(|call| call.share_stage.strip_drag) else {
73 return;
74 };
75 self.call_strip_width = drag.width_at(pointer_x);
76 cx.notify();
77 }
78
79 pub fn end_strip_drag(&mut self, cx: &mut Context<Self>) {
80 if self.call.as_ref().is_none_or(|call| call.share_stage.strip_drag.is_none()) {
81 return;
82 }
83 let width = clamp_strip_width(self.call_strip_width);
84 self.call_strip_width = width;
85 let _ = self.store.set_meta(STRIP_WIDTH_META_KEY, &width.to_string());
86 self.change_share_stage(cx, |stage| stage.strip_drag = None);
87 }
88
89 pub fn pop_out_stage(&mut self, cx: &mut Context<Self>) {
90 self.change_share_stage(cx, |stage| stage.popped = true);
91 }
92
93 pub fn return_stage_from_pop_out(&mut self, cx: &mut Context<Self>) {
94 self.change_share_stage(cx, |stage| stage.popped = false);
95 }
96
97 pub fn set_call_share_motion(&mut self, on: bool, cx: &mut Context<Self>) {
98 self.call_share_motion = on;
99 let _ = self.store.set_meta(SHARE_MOTION_META_KEY, flag_text(on));
100 self.send_call_command(CallCommand::SetShareMotion(on));
101 cx.notify();
102 }
103
104 pub fn set_call_share_standout(&mut self, on: bool, cx: &mut Context<Self>) {
105 self.call_share_standout = on;
106 let _ = self.store.set_meta(SHARE_STANDOUT_META_KEY, flag_text(on));
107 self.send_call_command(CallCommand::SetShareStandout(on));
108 cx.notify();
109 }
110}
crates/app/src/call/share_view.rs added +211 −0
@@ -0,0 +1,211 @@
1 use std::cell::Cell;
2 use std::rc::Rc;
3
4 pub const ZOOM_MIN: f32 = 1.;
5 pub const ZOOM_MAX: f32 = 4.;
6 const ZOOM_STEP: f32 = 1.25;
7 const WHEEL_ZOOM_PER_PIXEL: f32 = 0.0015;
8 pub const STRIP_MIN_WIDTH: f32 = 160.;
9 pub const STRIP_MAX_WIDTH: f32 = 400.;
10 pub const STRIP_DEFAULT_WIDTH: f32 = 232.;
11 pub const STRIP_WIDTH_META_KEY: &str = "call_strip_width";
12 pub const SHARE_MOTION_META_KEY: &str = "call_share_motion";
13 pub const SHARE_STANDOUT_META_KEY: &str = "call_share_standout";
14
15 #[derive(Debug, Clone, Copy, PartialEq)]
16 pub struct ShareView {
17 zoom: f32,
18 offset: (f32, f32),
19 }
20
21 impl Default for ShareView {
22 fn default() -> Self {
23 ShareView { zoom: ZOOM_MIN, offset: (0., 0.) }
24 }
25 }
26
27 fn clamp_axis(offset: f32, extent: f32, zoom: f32) -> f32 {
28 offset.clamp(extent - extent * zoom, 0.)
29 }
30
31 impl ShareView {
32 pub fn zoom(&self) -> f32 {
33 self.zoom
34 }
35
36 pub fn is_zoomed(&self) -> bool {
37 self.zoom > ZOOM_MIN
38 }
39
40 pub fn percent(&self) -> u32 {
41 (self.zoom * 100.).round() as u32
42 }
43
44 pub fn offset(&self, stage: (f32, f32)) -> (f32, f32) {
45 (clamp_axis(self.offset.0, stage.0, self.zoom), clamp_axis(self.offset.1, stage.1, self.zoom))
46 }
47
48 pub fn reset(&mut self) {
49 *self = ShareView::default();
50 }
51
52 pub fn zoom_around(&mut self, factor: f32, pointer: (f32, f32), stage: (f32, f32)) {
53 let target = (self.zoom * factor).clamp(ZOOM_MIN, ZOOM_MAX);
54 if target <= ZOOM_MIN {
55 self.reset();
56 return;
57 }
58 let (offset_x, offset_y) = self.offset(stage);
59 let ratio = target / self.zoom;
60 self.zoom = target;
61 self.offset = (pointer.0 - (pointer.0 - offset_x) * ratio, pointer.1 - (pointer.1 - offset_y) * ratio);
62 self.offset = self.offset(stage);
63 }
64
65 pub fn zoom_wheel(&mut self, scroll_pixels: f32, pointer: (f32, f32), stage: (f32, f32)) {
66 self.zoom_around((scroll_pixels * WHEEL_ZOOM_PER_PIXEL).exp(), pointer, stage);
67 }
68
69 pub fn step_in(&mut self, stage: (f32, f32)) {
70 self.zoom_around(ZOOM_STEP, (stage.0 / 2., stage.1 / 2.), stage);
71 }
72
73 pub fn step_out(&mut self, stage: (f32, f32)) {
74 self.zoom_around(1. / ZOOM_STEP, (stage.0 / 2., stage.1 / 2.), stage);
75 }
76
77 pub fn pan_by(&mut self, delta: (f32, f32), stage: (f32, f32)) {
78 if !self.is_zoomed() {
79 return;
80 }
81 let (offset_x, offset_y) = self.offset(stage);
82 self.offset = (offset_x + delta.0, offset_y + delta.1);
83 self.offset = self.offset(stage);
84 }
85 }
86
87 pub fn clamp_strip_width(width: f32) -> f32 {
88 width.clamp(STRIP_MIN_WIDTH, STRIP_MAX_WIDTH)
89 }
90
91 pub fn load_strip_width(store: &store::Store) -> f32 {
92 store
93 .meta(STRIP_WIDTH_META_KEY)
94 .ok()
95 .flatten()
96 .and_then(|text| text.parse().ok())
97 .map_or(STRIP_DEFAULT_WIDTH, clamp_strip_width)
98 }
99
100 pub fn load_flag(store: &store::Store, key: &str) -> bool {
101 store.meta(key).ok().flatten().as_deref() == Some("1")
102 }
103
104 #[derive(Debug, Clone, Copy, PartialEq)]
105 pub struct StripDrag {
106 pub start_pointer: f32,
107 pub start_width: f32,
108 }
109
110 impl StripDrag {
111 pub fn width_at(&self, pointer: f32) -> f32 {
112 clamp_strip_width(self.start_width + self.start_pointer - pointer)
113 }
114 }
115
116 #[derive(Default)]
117 pub struct ShareStage {
118 pub view: ShareView,
119 pub pan_from: Option<(f32, f32)>,
120 pub strip_drag: Option<StripDrag>,
121 pub popped: bool,
122 pub bounds: Rc<Cell<(f32, f32, f32, f32)>>,
123 }
124
125 impl ShareStage {
126 pub fn size(&self) -> (f32, f32) {
127 let (_, _, width, height) = self.bounds.get();
128 (width, height)
129 }
130
131 pub fn pointer(&self, position: (f32, f32)) -> (f32, f32) {
132 let (left, top, _, _) = self.bounds.get();
133 (position.0 - left, position.1 - top)
134 }
135
136 pub fn end(&mut self) {
137 self.view.reset();
138 self.pan_from = None;
139 self.popped = false;
140 }
141 }
142
143 #[cfg(test)]
144 mod tests {
145 use super::*;
146
147 const STAGE: (f32, f32) = (800., 450.);
148
149 #[test]
150 fn zooming_keeps_the_point_under_the_pointer_still() {
151 let mut view = ShareView::default();
152 let pointer = (600., 100.);
153 view.zoom_around(2., pointer, STAGE);
154 let (offset_x, offset_y) = view.offset(STAGE);
155 let content = ((pointer.0 - offset_x) / view.zoom(), (pointer.1 - offset_y) / view.zoom());
156 assert!((content.0 - 600.).abs() < 0.01 && (content.1 - 100.).abs() < 0.01);
157 }
158
159 #[test]
160 fn zoom_stays_between_one_and_four_times() {
161 let mut view = ShareView::default();
162 view.zoom_around(100., (400., 225.), STAGE);
163 assert_eq!(view.zoom(), ZOOM_MAX);
164 view.zoom_around(0.0001, (400., 225.), STAGE);
165 assert!(!view.is_zoomed());
166 assert_eq!(view.offset(STAGE), (0., 0.));
167 }
168
169 #[test]
170 fn panning_never_leaves_the_content() {
171 let mut view = ShareView::default();
172 view.pan_by((50., 50.), STAGE);
173 assert_eq!(view.offset(STAGE), (0., 0.));
174 view.zoom_around(2., (0., 0.), STAGE);
175 view.pan_by((-5000., -5000.), STAGE);
176 assert_eq!(view.offset(STAGE), (-800., -450.));
177 view.pan_by((5000., 5000.), STAGE);
178 assert_eq!(view.offset(STAGE), (0., 0.));
179 }
180
181 #[test]
182 fn keyboard_steps_zoom_around_the_center_and_zero_resets() {
183 let mut view = ShareView::default();
184 view.step_in(STAGE);
185 view.step_in(STAGE);
186 assert_eq!(view.percent(), 156);
187 view.step_out(STAGE);
188 assert_eq!(view.percent(), 125);
189 view.reset();
190 assert_eq!(view.percent(), 100);
191 }
192
193 #[test]
194 fn wheel_up_zooms_in_and_down_zooms_out() {
195 let mut view = ShareView::default();
196 view.zoom_wheel(120., (400., 225.), STAGE);
197 assert!(view.zoom() > 1.);
198 let zoomed = view.zoom();
199 view.zoom_wheel(-60., (400., 225.), STAGE);
200 assert!(view.zoom() < zoomed);
201 }
202
203 #[test]
204 fn the_strip_width_stays_between_160_and_400_and_follows_the_pointer() {
205 let drag = StripDrag { start_pointer: 900., start_width: 232. };
206 assert_eq!(drag.width_at(880.), 252.);
207 assert_eq!(drag.width_at(0.), STRIP_MAX_WIDTH);
208 assert_eq!(drag.width_at(2000.), STRIP_MIN_WIDTH);
209 assert_eq!(clamp_strip_width(10.), STRIP_MIN_WIDTH);
210 }
211 }
@@ -0,0 +1,211 @@
1use std::cell::Cell;
2use std::rc::Rc;
3
4pub const ZOOM_MIN: f32 = 1.;
5pub const ZOOM_MAX: f32 = 4.;
6const ZOOM_STEP: f32 = 1.25;
7const WHEEL_ZOOM_PER_PIXEL: f32 = 0.0015;
8pub const STRIP_MIN_WIDTH: f32 = 160.;
9pub const STRIP_MAX_WIDTH: f32 = 400.;
10pub const STRIP_DEFAULT_WIDTH: f32 = 232.;
11pub const STRIP_WIDTH_META_KEY: &str = "call_strip_width";
12pub const SHARE_MOTION_META_KEY: &str = "call_share_motion";
13pub const SHARE_STANDOUT_META_KEY: &str = "call_share_standout";
14
15#[derive(Debug, Clone, Copy, PartialEq)]
16pub struct ShareView {
17 zoom: f32,
18 offset: (f32, f32),
19}
20
21impl Default for ShareView {
22 fn default() -> Self {
23 ShareView { zoom: ZOOM_MIN, offset: (0., 0.) }
24 }
25}
26
27fn clamp_axis(offset: f32, extent: f32, zoom: f32) -> f32 {
28 offset.clamp(extent - extent * zoom, 0.)
29}
30
31impl ShareView {
32 pub fn zoom(&self) -> f32 {
33 self.zoom
34 }
35
36 pub fn is_zoomed(&self) -> bool {
37 self.zoom > ZOOM_MIN
38 }
39
40 pub fn percent(&self) -> u32 {
41 (self.zoom * 100.).round() as u32
42 }
43
44 pub fn offset(&self, stage: (f32, f32)) -> (f32, f32) {
45 (clamp_axis(self.offset.0, stage.0, self.zoom), clamp_axis(self.offset.1, stage.1, self.zoom))
46 }
47
48 pub fn reset(&mut self) {
49 *self = ShareView::default();
50 }
51
52 pub fn zoom_around(&mut self, factor: f32, pointer: (f32, f32), stage: (f32, f32)) {
53 let target = (self.zoom * factor).clamp(ZOOM_MIN, ZOOM_MAX);
54 if target <= ZOOM_MIN {
55 self.reset();
56 return;
57 }
58 let (offset_x, offset_y) = self.offset(stage);
59 let ratio = target / self.zoom;
60 self.zoom = target;
61 self.offset = (pointer.0 - (pointer.0 - offset_x) * ratio, pointer.1 - (pointer.1 - offset_y) * ratio);
62 self.offset = self.offset(stage);
63 }
64
65 pub fn zoom_wheel(&mut self, scroll_pixels: f32, pointer: (f32, f32), stage: (f32, f32)) {
66 self.zoom_around((scroll_pixels * WHEEL_ZOOM_PER_PIXEL).exp(), pointer, stage);
67 }
68
69 pub fn step_in(&mut self, stage: (f32, f32)) {
70 self.zoom_around(ZOOM_STEP, (stage.0 / 2., stage.1 / 2.), stage);
71 }
72
73 pub fn step_out(&mut self, stage: (f32, f32)) {
74 self.zoom_around(1. / ZOOM_STEP, (stage.0 / 2., stage.1 / 2.), stage);
75 }
76
77 pub fn pan_by(&mut self, delta: (f32, f32), stage: (f32, f32)) {
78 if !self.is_zoomed() {
79 return;
80 }
81 let (offset_x, offset_y) = self.offset(stage);
82 self.offset = (offset_x + delta.0, offset_y + delta.1);
83 self.offset = self.offset(stage);
84 }
85}
86
87pub fn clamp_strip_width(width: f32) -> f32 {
88 width.clamp(STRIP_MIN_WIDTH, STRIP_MAX_WIDTH)
89}
90
91pub fn load_strip_width(store: &store::Store) -> f32 {
92 store
93 .meta(STRIP_WIDTH_META_KEY)
94 .ok()
95 .flatten()
96 .and_then(|text| text.parse().ok())
97 .map_or(STRIP_DEFAULT_WIDTH, clamp_strip_width)
98}
99
100pub fn load_flag(store: &store::Store, key: &str) -> bool {
101 store.meta(key).ok().flatten().as_deref() == Some("1")
102}
103
104#[derive(Debug, Clone, Copy, PartialEq)]
105pub struct StripDrag {
106 pub start_pointer: f32,
107 pub start_width: f32,
108}
109
110impl StripDrag {
111 pub fn width_at(&self, pointer: f32) -> f32 {
112 clamp_strip_width(self.start_width + self.start_pointer - pointer)
113 }
114}
115
116#[derive(Default)]
117pub struct ShareStage {
118 pub view: ShareView,
119 pub pan_from: Option<(f32, f32)>,
120 pub strip_drag: Option<StripDrag>,
121 pub popped: bool,
122 pub bounds: Rc<Cell<(f32, f32, f32, f32)>>,
123}
124
125impl ShareStage {
126 pub fn size(&self) -> (f32, f32) {
127 let (_, _, width, height) = self.bounds.get();
128 (width, height)
129 }
130
131 pub fn pointer(&self, position: (f32, f32)) -> (f32, f32) {
132 let (left, top, _, _) = self.bounds.get();
133 (position.0 - left, position.1 - top)
134 }
135
136 pub fn end(&mut self) {
137 self.view.reset();
138 self.pan_from = None;
139 self.popped = false;
140 }
141}
142
143#[cfg(test)]
144mod tests {
145 use super::*;
146
147 const STAGE: (f32, f32) = (800., 450.);
148
149 #[test]
150 fn zooming_keeps_the_point_under_the_pointer_still() {
151 let mut view = ShareView::default();
152 let pointer = (600., 100.);
153 view.zoom_around(2., pointer, STAGE);
154 let (offset_x, offset_y) = view.offset(STAGE);
155 let content = ((pointer.0 - offset_x) / view.zoom(), (pointer.1 - offset_y) / view.zoom());
156 assert!((content.0 - 600.).abs() < 0.01 && (content.1 - 100.).abs() < 0.01);
157 }
158
159 #[test]
160 fn zoom_stays_between_one_and_four_times() {
161 let mut view = ShareView::default();
162 view.zoom_around(100., (400., 225.), STAGE);
163 assert_eq!(view.zoom(), ZOOM_MAX);
164 view.zoom_around(0.0001, (400., 225.), STAGE);
165 assert!(!view.is_zoomed());
166 assert_eq!(view.offset(STAGE), (0., 0.));
167 }
168
169 #[test]
170 fn panning_never_leaves_the_content() {
171 let mut view = ShareView::default();
172 view.pan_by((50., 50.), STAGE);
173 assert_eq!(view.offset(STAGE), (0., 0.));
174 view.zoom_around(2., (0., 0.), STAGE);
175 view.pan_by((-5000., -5000.), STAGE);
176 assert_eq!(view.offset(STAGE), (-800., -450.));
177 view.pan_by((5000., 5000.), STAGE);
178 assert_eq!(view.offset(STAGE), (0., 0.));
179 }
180
181 #[test]
182 fn keyboard_steps_zoom_around_the_center_and_zero_resets() {
183 let mut view = ShareView::default();
184 view.step_in(STAGE);
185 view.step_in(STAGE);
186 assert_eq!(view.percent(), 156);
187 view.step_out(STAGE);
188 assert_eq!(view.percent(), 125);
189 view.reset();
190 assert_eq!(view.percent(), 100);
191 }
192
193 #[test]
194 fn wheel_up_zooms_in_and_down_zooms_out() {
195 let mut view = ShareView::default();
196 view.zoom_wheel(120., (400., 225.), STAGE);
197 assert!(view.zoom() > 1.);
198 let zoomed = view.zoom();
199 view.zoom_wheel(-60., (400., 225.), STAGE);
200 assert!(view.zoom() < zoomed);
201 }
202
203 #[test]
204 fn the_strip_width_stays_between_160_and_400_and_follows_the_pointer() {
205 let drag = StripDrag { start_pointer: 900., start_width: 232. };
206 assert_eq!(drag.width_at(880.), 252.);
207 assert_eq!(drag.width_at(0.), STRIP_MAX_WIDTH);
208 assert_eq!(drag.width_at(2000.), STRIP_MIN_WIDTH);
209 assert_eq!(clamp_strip_width(10.), STRIP_MIN_WIDTH);
210 }
211}
crates/app/src/call/view_actions.rs +14 −0
@@ -1,5 +1,6 @@
1 1 use std::time::{Duration, Instant};
2 2
3 use calling::CallCommand;
3 4 use gpui_kit::*;
4 5
5 6 use super::caption_style::{CaptionPosition, CaptionSize};
@@ -7,6 +8,7 @@ use super::bubbles::{BUBBLE_SHOWN, ChatBubble, push_bubble};
7 8 use super::fullscreen::{FullscreenState, HINT_SHOWN};
8 9 use super::view_settings::{CallLayout, ViewSettings};
9 10 use crate::app_state::{AppEvent, AppState};
11 use crate::views::call_layouts::{measured_stage, video_wants};
10 12
11 13 const CHROME_TOUCH_THROTTLE: Duration = Duration::from_millis(250);
12 14 const DEMO_BUBBLE_START: Duration = Duration::from_secs(8);
@@ -69,11 +71,23 @@ impl AppState {
69 71 .call
70 72 .as_mut()
71 73 .is_some_and(|call| call.model.refresh_layout(Instant::now()));
74 self.sync_video_wants();
72 75 if changed {
73 76 cx.notify();
74 77 }
75 78 }
76 79
80 fn sync_video_wants(&mut self) {
81 let Some(call) = self.call.as_mut() else {
82 return;
83 };
84 let wants = video_wants(&call.model, measured_stage(call));
85 if wants != call.sent_wants {
86 let _ = call.commands.send(CallCommand::SetVideoWants(wants.clone()));
87 call.sent_wants = wants;
88 }
89 }
90
77 91 pub fn toggle_call_fullscreen(&mut self, cx: &mut Context<Self>) {
78 92 let Some(call) = self.call.as_mut().filter(|call| call.viewing) else {
79 93 return;
@@ -1,5 +1,6 @@
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::caption_style::{CaptionPosition, CaptionSize};
6use super::caption_style::{CaptionPosition, CaptionSize};
@@ -7,6 +8,7 @@ use super::bubbles::{BUBBLE_SHOWN, ChatBubble, push_bubble};
7use super::fullscreen::{FullscreenState, HINT_SHOWN};
8use super::fullscreen::{FullscreenState, HINT_SHOWN};
8use super::view_settings::{CallLayout, ViewSettings};
9use super::view_settings::{CallLayout, ViewSettings};
9use crate::app_state::{AppEvent, AppState};
10use crate::app_state::{AppEvent, AppState};
11use crate::views::call_layouts::{measured_stage, video_wants};
10
12
11const CHROME_TOUCH_THROTTLE: Duration = Duration::from_millis(250);
13const CHROME_TOUCH_THROTTLE: Duration = Duration::from_millis(250);
12const DEMO_BUBBLE_START: Duration = Duration::from_secs(8);
14const DEMO_BUBBLE_START: Duration = Duration::from_secs(8);
@@ -69,11 +71,23 @@ impl AppState {
69 .call
71 .call
70 .as_mut()
72 .as_mut()
71 .is_some_and(|call| call.model.refresh_layout(Instant::now()));
73 .is_some_and(|call| call.model.refresh_layout(Instant::now()));
74 self.sync_video_wants();
72 if changed {
75 if changed {
73 cx.notify();
76 cx.notify();
74 }
77 }
75 }
78 }
76
79
80 fn sync_video_wants(&mut self) {
81 let Some(call) = self.call.as_mut() else {
82 return;
83 };
84 let wants = video_wants(&call.model, measured_stage(call));
85 if wants != call.sent_wants {
86 let _ = call.commands.send(CallCommand::SetVideoWants(wants.clone()));
87 call.sent_wants = wants;
88 }
89 }
90
77 pub fn toggle_call_fullscreen(&mut self, cx: &mut Context<Self>) {
91 pub fn toggle_call_fullscreen(&mut self, cx: &mut Context<Self>) {
78 let Some(call) = self.call.as_mut().filter(|call| call.viewing) else {
92 let Some(call) = self.call.as_mut().filter(|call| call.viewing) else {
79 return;
93 return;
crates/app/src/layout_guard.rs +29 −1
@@ -167,6 +167,12 @@ mod frames {
167 167 const PREJOIN_LINK: &str = "https://teams.microsoft.com/l/meetup-join/19%3ameeting_guard%40thread.v2/0?context=%7b%22Tid%22%3a%22t%22%2c%22Oid%22%3a%22o%22%7d";
168 168 const CALL_TRANSCRIPT: &str = "shell/islands/main/call-transcript";
169 169 const PEOPLE_PANEL: &str = "shell/islands/main/call-people";
170 const SHARE_GUARDED: &[&str] = &[
171 "shell/islands/main/call-stage/share-content",
172 "shell/islands/main/call-stage/share-content/zoom-chip",
173 "shell/islands/main/call-stage/share-divider",
174 "shell/islands/main/call-stage/share-strip",
175 ];
170 176 const MENU: &str = "popup-menu";
171 177 const OWN_STATUS: &str = "shell/title-bar/own-status";
172 178 const RECAP_TAB: &str = "shell/islands/main/recap-tab";
@@ -184,6 +190,7 @@ mod frames {
184 190 Prejoin,
185 191 CallTranscript,
186 192 CallPeople,
193 CallShare,
187 194 }
188 195
189 196 fn parent_of(path: &str) -> Option<&str> {
@@ -301,11 +308,19 @@ mod frames {
301 308 .chain(CALL_GUARDED)
302 309 .chain(CALLS_TAGS)
303 310 .chain(PREJOIN_TAGS)
311 .chain(SHARE_GUARDED)
304 312 .chain([&CALL_TRANSCRIPT, &MENU, &RECAP_TAB, &RECAP_REGION, &PEOPLE_PANEL])
305 313 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
306 314 .collect()
307 315 }
308 316
317 fn sharing_call() -> ActiveCall {
318 let mut call = gallery_call();
319 call.model.apply(CallUpdate::ScreenShare(Some("8:orgid:guard-1".to_owned())));
320 call.share_stage.view.step_in((800., 450.));
321 call
322 }
323
309 324 fn gallery_call() -> ActiveCall {
310 325 let (handle, _control) = call_channel();
311 326 let mut model = CallModel::meeting("Standup", false);
@@ -421,6 +436,7 @@ mod frames {
421 436 Screen::Call,
422 437 Screen::CallTranscript,
423 438 Screen::CallPeople,
439 Screen::CallShare,
424 440 ];
425 441 for screen in screens {
426 442 let (screen_name, status_menu) = match screen {
@@ -475,6 +491,15 @@ mod frames {
475 491 });
476 492 ("call-transcript", false)
477 493 }
494 Screen::CallShare => {
495 visual.update(|_, cx| {
496 app.update(cx, |state, cx| {
497 state.call = Some(sharing_call());
498 cx.notify();
499 })
500 });
501 ("call-share", false)
502 }
478 503 Screen::StatusMenu => {
479 504 let tags = collect(&mut visual, None);
480 505 let button = tags
@@ -486,7 +511,7 @@ mod frames {
486 511 ("status-menu", true)
487 512 }
488 513 };
489 let is_call = matches!(screen_name, "call" | "call-people" | "call-transcript");
514 let is_call = matches!(screen_name, "call" | "call-people" | "call-transcript" | "call-share");
490 515 let tags = collect(&mut visual, status_menu.then_some(MENU));
491 516 let mut expected = GUARDED.to_vec();
492 517 if is_call {
@@ -498,6 +523,9 @@ mod frames {
498 523 if screen_name == "call-people" {
499 524 expected.push(PEOPLE_PANEL);
500 525 }
526 if screen_name == "call-share" {
527 expected.extend(SHARE_GUARDED);
528 }
501 529 if status_menu {
502 530 expected.push(MENU);
503 531 }
@@ -167,6 +167,12 @@ mod frames {
167 const PREJOIN_LINK: &str = "https://teams.microsoft.com/l/meetup-join/19%3ameeting_guard%40thread.v2/0?context=%7b%22Tid%22%3a%22t%22%2c%22Oid%22%3a%22o%22%7d";
167 const PREJOIN_LINK: &str = "https://teams.microsoft.com/l/meetup-join/19%3ameeting_guard%40thread.v2/0?context=%7b%22Tid%22%3a%22t%22%2c%22Oid%22%3a%22o%22%7d";
168 const CALL_TRANSCRIPT: &str = "shell/islands/main/call-transcript";
168 const CALL_TRANSCRIPT: &str = "shell/islands/main/call-transcript";
169 const PEOPLE_PANEL: &str = "shell/islands/main/call-people";
169 const PEOPLE_PANEL: &str = "shell/islands/main/call-people";
170 const SHARE_GUARDED: &[&str] = &[
171 "shell/islands/main/call-stage/share-content",
172 "shell/islands/main/call-stage/share-content/zoom-chip",
173 "shell/islands/main/call-stage/share-divider",
174 "shell/islands/main/call-stage/share-strip",
175 ];
170 const MENU: &str = "popup-menu";
176 const MENU: &str = "popup-menu";
171 const OWN_STATUS: &str = "shell/title-bar/own-status";
177 const OWN_STATUS: &str = "shell/title-bar/own-status";
172 const RECAP_TAB: &str = "shell/islands/main/recap-tab";
178 const RECAP_TAB: &str = "shell/islands/main/recap-tab";
@@ -184,6 +190,7 @@ mod frames {
184 Prejoin,
190 Prejoin,
185 CallTranscript,
191 CallTranscript,
186 CallPeople,
192 CallPeople,
193 CallShare,
187 }
194 }
188
195
189 fn parent_of(path: &str) -> Option<&str> {
196 fn parent_of(path: &str) -> Option<&str> {
@@ -301,11 +308,19 @@ mod frames {
301 .chain(CALL_GUARDED)
308 .chain(CALL_GUARDED)
302 .chain(CALLS_TAGS)
309 .chain(CALLS_TAGS)
303 .chain(PREJOIN_TAGS)
310 .chain(PREJOIN_TAGS)
311 .chain(SHARE_GUARDED)
304 .chain([&CALL_TRANSCRIPT, &MENU, &RECAP_TAB, &RECAP_REGION, &PEOPLE_PANEL])
312 .chain([&CALL_TRANSCRIPT, &MENU, &RECAP_TAB, &RECAP_REGION, &PEOPLE_PANEL])
305 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
313 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
306 .collect()
314 .collect()
307 }
315 }
308
316
317 fn sharing_call() -> ActiveCall {
318 let mut call = gallery_call();
319 call.model.apply(CallUpdate::ScreenShare(Some("8:orgid:guard-1".to_owned())));
320 call.share_stage.view.step_in((800., 450.));
321 call
322 }
323
309 fn gallery_call() -> ActiveCall {
324 fn gallery_call() -> ActiveCall {
310 let (handle, _control) = call_channel();
325 let (handle, _control) = call_channel();
311 let mut model = CallModel::meeting("Standup", false);
326 let mut model = CallModel::meeting("Standup", false);
@@ -421,6 +436,7 @@ mod frames {
421 Screen::Call,
436 Screen::Call,
422 Screen::CallTranscript,
437 Screen::CallTranscript,
423 Screen::CallPeople,
438 Screen::CallPeople,
439 Screen::CallShare,
424 ];
440 ];
425 for screen in screens {
441 for screen in screens {
426 let (screen_name, status_menu) = match screen {
442 let (screen_name, status_menu) = match screen {
@@ -475,6 +491,15 @@ mod frames {
475 });
491 });
476 ("call-transcript", false)
492 ("call-transcript", false)
477 }
493 }
494 Screen::CallShare => {
495 visual.update(|_, cx| {
496 app.update(cx, |state, cx| {
497 state.call = Some(sharing_call());
498 cx.notify();
499 })
500 });
501 ("call-share", false)
502 }
478 Screen::StatusMenu => {
503 Screen::StatusMenu => {
479 let tags = collect(&mut visual, None);
504 let tags = collect(&mut visual, None);
480 let button = tags
505 let button = tags
@@ -486,7 +511,7 @@ mod frames {
486 ("status-menu", true)
511 ("status-menu", true)
487 }
512 }
488 };
513 };
489 let is_call = matches!(screen_name, "call" | "call-people" | "call-transcript");
514 let is_call = matches!(screen_name, "call" | "call-people" | "call-transcript" | "call-share");
490 let tags = collect(&mut visual, status_menu.then_some(MENU));
515 let tags = collect(&mut visual, status_menu.then_some(MENU));
491 let mut expected = GUARDED.to_vec();
516 let mut expected = GUARDED.to_vec();
492 if is_call {
517 if is_call {
@@ -498,6 +523,9 @@ mod frames {
498 if screen_name == "call-people" {
523 if screen_name == "call-people" {
499 expected.push(PEOPLE_PANEL);
524 expected.push(PEOPLE_PANEL);
500 }
525 }
526 if screen_name == "call-share" {
527 expected.extend(SHARE_GUARDED);
528 }
501 if status_menu {
529 if status_menu {
502 expected.push(MENU);
530 expected.push(MENU);
503 }
531 }
crates/app/src/notify/platform/mod.rs +2 −0
@@ -3,6 +3,8 @@ mod windows_impl;
3 3 #[cfg(windows)]
4 4 pub use windows_impl::*;
5 5
6 #[cfg(target_os = "linux")]
7 mod x11_input;
6 8 #[cfg(not(windows))]
7 9 mod stub;
8 10 #[cfg(not(windows))]
@@ -3,6 +3,8 @@ mod windows_impl;
3#[cfg(windows)]
3#[cfg(windows)]
4pub use windows_impl::*;
4pub use windows_impl::*;
5
5
6#[cfg(target_os = "linux")]
7mod x11_input;
6#[cfg(not(windows))]
8#[cfg(not(windows))]
7mod stub;
9mod stub;
8#[cfg(not(windows))]
10#[cfg(not(windows))]
crates/app/src/notify/platform/stub.rs +7 −1
@@ -26,7 +26,13 @@ pub fn place(_handle: NativeHandle, _x: i32, _y: i32, _width: i32, _height: i32)
26 26
27 27 pub fn exclude_from_capture(_handle: NativeHandle) {}
28 28
29 pub fn make_click_through(_handle: NativeHandle) {}
29 #[cfg(target_os = "linux")]
30 pub fn make_window_click_through(window: &Window) {
31 super::x11_input::make_input_transparent(window);
32 }
33
34 #[cfg(not(target_os = "linux"))]
35 pub fn make_window_click_through(_window: &Window) {}
30 36
31 37 pub fn window_minimized(_handle: NativeHandle) -> bool {
32 38 false
@@ -26,7 +26,13 @@ pub fn place(_handle: NativeHandle, _x: i32, _y: i32, _width: i32, _height: i32)
26
26
27pub fn exclude_from_capture(_handle: NativeHandle) {}
27pub fn exclude_from_capture(_handle: NativeHandle) {}
28
28
29pub fn make_click_through(_handle: NativeHandle) {}
29#[cfg(target_os = "linux")]
30pub fn make_window_click_through(window: &Window) {
31 super::x11_input::make_input_transparent(window);
32}
33
34#[cfg(not(target_os = "linux"))]
35pub fn make_window_click_through(_window: &Window) {}
30
36
31pub fn window_minimized(_handle: NativeHandle) -> bool {
37pub fn window_minimized(_handle: NativeHandle) -> bool {
32 false
38 false
crates/app/src/notify/platform/windows_impl.rs +7 −1
@@ -197,7 +197,13 @@ pub fn exclude_from_capture(handle: NativeHandle) {
197 197 }
198 198 }
199 199
200 pub fn make_click_through(handle: NativeHandle) {
200 pub fn make_window_click_through(window: &Window) {
201 if let Some(handle) = native_handle(window) {
202 make_click_through(handle);
203 }
204 }
205
206 fn make_click_through(handle: NativeHandle) {
201 207 unsafe {
202 208 let style = GetWindowLongPtrW(hwnd(handle), GWL_EXSTYLE);
203 209 let added = (WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_NOACTIVATE).0 as isize;
@@ -197,7 +197,13 @@ pub fn exclude_from_capture(handle: NativeHandle) {
197 }
197 }
198}
198}
199
199
200pub fn make_click_through(handle: NativeHandle) {
200pub fn make_window_click_through(window: &Window) {
201 if let Some(handle) = native_handle(window) {
202 make_click_through(handle);
203 }
204}
205
206fn make_click_through(handle: NativeHandle) {
201 unsafe {
207 unsafe {
202 let style = GetWindowLongPtrW(hwnd(handle), GWL_EXSTYLE);
208 let style = GetWindowLongPtrW(hwnd(handle), GWL_EXSTYLE);
203 let added = (WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_NOACTIVATE).0 as isize;
209 let added = (WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_NOACTIVATE).0 as isize;
crates/app/src/notify/platform/x11_input.rs added +84 −0
@@ -0,0 +1,84 @@
1 use gpui_kit::Window;
2 use raw_window_handle::{HasWindowHandle, RawWindowHandle};
3 use x11rb::protocol::shape::{ConnectionExt as _, SK, SO};
4 use x11rb::protocol::xproto::ClipOrdering;
5 use x11rb::rust_connection::RustConnection;
6
7 fn x11_window_id(window: &Window) -> Option<u32> {
8 match HasWindowHandle::window_handle(window).ok()?.as_raw() {
9 RawWindowHandle::Xcb(handle) => Some(handle.window.get()),
10 RawWindowHandle::Xlib(handle) => u32::try_from(handle.window).ok(),
11 _ => None,
12 }
13 }
14
15 pub fn empty_input_region(display: Option<&str>, window: u32) -> Result<(), Box<dyn std::error::Error>> {
16 let (connection, _) = RustConnection::connect(display)?;
17 connection
18 .shape_rectangles(SO::SET, SK::INPUT, ClipOrdering::UNSORTED, window, 0, 0, &[])?
19 .check()?;
20 Ok(())
21 }
22
23 pub fn make_input_transparent(window: &Window) {
24 if let Some(id) = x11_window_id(window) {
25 let _ = empty_input_region(None, id);
26 }
27 }
28
29 #[cfg(test)]
30 mod tests {
31 use std::process::{Child, Command, Stdio};
32 use std::time::Duration;
33
34 use x11rb::connection::Connection;
35 use x11rb::protocol::xproto::{ConnectionExt as _, CreateWindowAux, WindowClass};
36 use x11rb::COPY_DEPTH_FROM_PARENT;
37
38 use super::*;
39
40 struct Server(Child);
41
42 impl Drop for Server {
43 fn drop(&mut self) {
44 let _ = self.0.kill();
45 }
46 }
47
48 fn start_server(display: &str) -> Option<Server> {
49 let child = Command::new("Xvfb")
50 .args([display, "-screen", "0", "320x200x24", "-nolisten", "tcp", "-noreset"])
51 .stdout(Stdio::null())
52 .stderr(Stdio::null())
53 .spawn()
54 .ok()?;
55 let server = Server(child);
56 for _ in 0..50 {
57 if RustConnection::connect(Some(display)).is_ok() {
58 return Some(server);
59 }
60 std::thread::sleep(Duration::from_millis(100));
61 }
62 None
63 }
64
65 #[test]
66 fn the_border_window_gets_an_empty_input_region() {
67 let display = ":87";
68 let Some(_server) = start_server(display) else {
69 return;
70 };
71 let (connection, screen_number) = RustConnection::connect(Some(display)).unwrap();
72 let root = connection.setup().roots[screen_number].root;
73 let window = connection.generate_id().unwrap();
74 connection
75 .create_window(COPY_DEPTH_FROM_PARENT, window, root, 0, 0, 100, 100, 0, WindowClass::INPUT_OUTPUT, 0, &CreateWindowAux::new())
76 .unwrap();
77 connection.flush().unwrap();
78 let before = connection.shape_get_rectangles(window, SK::INPUT).unwrap().reply().unwrap();
79 assert_eq!(before.rectangles.len(), 1);
80 empty_input_region(Some(display), window).unwrap();
81 let after = connection.shape_get_rectangles(window, SK::INPUT).unwrap().reply().unwrap();
82 assert!(after.rectangles.is_empty());
83 }
84 }
@@ -0,0 +1,84 @@
1use gpui_kit::Window;
2use raw_window_handle::{HasWindowHandle, RawWindowHandle};
3use x11rb::protocol::shape::{ConnectionExt as _, SK, SO};
4use x11rb::protocol::xproto::ClipOrdering;
5use x11rb::rust_connection::RustConnection;
6
7fn x11_window_id(window: &Window) -> Option<u32> {
8 match HasWindowHandle::window_handle(window).ok()?.as_raw() {
9 RawWindowHandle::Xcb(handle) => Some(handle.window.get()),
10 RawWindowHandle::Xlib(handle) => u32::try_from(handle.window).ok(),
11 _ => None,
12 }
13}
14
15pub fn empty_input_region(display: Option<&str>, window: u32) -> Result<(), Box<dyn std::error::Error>> {
16 let (connection, _) = RustConnection::connect(display)?;
17 connection
18 .shape_rectangles(SO::SET, SK::INPUT, ClipOrdering::UNSORTED, window, 0, 0, &[])?
19 .check()?;
20 Ok(())
21}
22
23pub fn make_input_transparent(window: &Window) {
24 if let Some(id) = x11_window_id(window) {
25 let _ = empty_input_region(None, id);
26 }
27}
28
29#[cfg(test)]
30mod tests {
31 use std::process::{Child, Command, Stdio};
32 use std::time::Duration;
33
34 use x11rb::connection::Connection;
35 use x11rb::protocol::xproto::{ConnectionExt as _, CreateWindowAux, WindowClass};
36 use x11rb::COPY_DEPTH_FROM_PARENT;
37
38 use super::*;
39
40 struct Server(Child);
41
42 impl Drop for Server {
43 fn drop(&mut self) {
44 let _ = self.0.kill();
45 }
46 }
47
48 fn start_server(display: &str) -> Option<Server> {
49 let child = Command::new("Xvfb")
50 .args([display, "-screen", "0", "320x200x24", "-nolisten", "tcp", "-noreset"])
51 .stdout(Stdio::null())
52 .stderr(Stdio::null())
53 .spawn()
54 .ok()?;
55 let server = Server(child);
56 for _ in 0..50 {
57 if RustConnection::connect(Some(display)).is_ok() {
58 return Some(server);
59 }
60 std::thread::sleep(Duration::from_millis(100));
61 }
62 None
63 }
64
65 #[test]
66 fn the_border_window_gets_an_empty_input_region() {
67 let display = ":87";
68 let Some(_server) = start_server(display) else {
69 return;
70 };
71 let (connection, screen_number) = RustConnection::connect(Some(display)).unwrap();
72 let root = connection.setup().roots[screen_number].root;
73 let window = connection.generate_id().unwrap();
74 connection
75 .create_window(COPY_DEPTH_FROM_PARENT, window, root, 0, 0, 100, 100, 0, WindowClass::INPUT_OUTPUT, 0, &CreateWindowAux::new())
76 .unwrap();
77 connection.flush().unwrap();
78 let before = connection.shape_get_rectangles(window, SK::INPUT).unwrap().reply().unwrap();
79 assert_eq!(before.rectangles.len(), 1);
80 empty_input_region(Some(display), window).unwrap();
81 let after = connection.shape_get_rectangles(window, SK::INPUT).unwrap().reply().unwrap();
82 assert!(after.rectangles.is_empty());
83 }
84}
crates/app/src/views/call_layouts.rs +232 −28
@@ -14,19 +14,22 @@ use gpui_kit::*;
14 14 use super::avatar::person_avatar;
15 15 use super::call_organizer::render_focus_stage;
16 16 use super::call_view::{
17 GRID_PADDING, STRIP_GAP, STRIP_TILE, STRIP_VISIBLE, TILE_GAP, own_tile, person_tile,
17 GRID_PADDING, STRIP_GAP, STRIP_VISIBLE, TILE_GAP, own_tile, person_tile,
18 18 };
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.);
28 29 const MEASURE_TOLERANCE: f32 = 0.5;
29 30 const OVERLAY_INSET: f32 = 16.;
31 const DIVIDER_LINE: f32 = 4.;
32 const DIVIDER_LENGTH: f32 = 48.;
30 33 const CHIP_TOP: f32 = 12.;
31 34 const FILMSTRIP_TILE_MAX: f32 = 220.;
32 35 const TILE_RADIUS: f32 = 12.;
@@ -43,7 +46,7 @@ const BUBBLE_BACKGROUND: f32 = 0.72;
43 46 const CHIP_BACKGROUND: f32 = 0.6;
44 47 pub const FULLSCREEN_HINT: &str = "Press Esc to exit full screen";
45 48
46 fn measured_stage(call: &ActiveCall) -> (f32, f32) {
49 pub fn measured_stage(call: &ActiveCall) -> (f32, f32) {
47 50 let (width, height) = call.stage_size.get();
48 51 if width < 1. || height < 1. {
49 52 return FALLBACK_STAGE;
@@ -357,6 +360,12 @@ fn rows_of(cells: Vec<AnyElement>, columns: usize) -> Vec<Div> {
357 360 }
358 361 }
359 362
363 fn gallery_split(model: &CallModel) -> (Vec<&Tile>, Overflow) {
364 let others = model.layout_tiles();
365 let overflow = split_overflow(others.len(), model.own_cells(), GALLERY_MAX);
366 (others, overflow)
367 }
368
360 369 fn gallery_body(
361 370 app: &Entity<AppState>,
362 371 state: &AppState,
@@ -364,9 +373,8 @@ fn gallery_body(
364 373 now: Instant,
365 374 stage: (f32, f32),
366 375 ) -> AnyElement {
367 let others = model.layout_tiles();
376 let (others, overflow) = gallery_split(model);
368 377 let own_cells = model.own_cells();
369 let overflow = split_overflow(others.len(), own_cells, GALLERY_MAX);
370 378 let cells = overflow.shown + own_cells + usize::from(overflow.hidden > 0);
371 379 let grid = gallery_grid(
372 380 cells,
@@ -399,18 +407,16 @@ fn gallery_body(
399 407 .into_any_element()
400 408 }
401 409
402 fn speaker_body(
403 app: &Entity<AppState>,
404 state: &AppState,
405 model: &CallModel,
406 now: Instant,
407 stage: (f32, f32),
408 ) -> AnyElement {
410 struct SpeakerSplit<'a> {
411 focus: Option<Focus>,
412 others: Vec<&'a Tile>,
413 own_cells: usize,
414 plan: Filmstrip,
415 }
416
417 fn speaker_split(model: &CallModel, stage: (f32, f32)) -> SpeakerSplit<'_> {
409 418 let focus = model.speaker_focus();
410 419 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 420 let mut others: Vec<&Tile> = model
415 421 .layout_tiles()
416 422 .into_iter()
@@ -427,6 +433,20 @@ fn speaker_body(
427 433 if plan.overflow.shown < FILMSTRIP_MAX.min(others.len()) {
428 434 others.sort_by_key(|tile| !model.is_recent_speaker(&tile.mri));
429 435 }
436 SpeakerSplit { focus, others, own_cells, plan }
437 }
438
439 fn speaker_body(
440 app: &Entity<AppState>,
441 state: &AppState,
442 model: &CallModel,
443 now: Instant,
444 stage: (f32, f32),
445 ) -> AnyElement {
446 let SpeakerSplit { focus, others, own_cells, plan } = speaker_split(model, stage);
447 let main = focus
448 .as_ref()
449 .and_then(|focus| render_focus_stage(app, state, focus, now));
430 450 let size = TileSize::sixteen_by_nine(plan.tile_width.floor());
431 451 let shown = &others[..plan.overflow.shown];
432 452 let mut tiles: Vec<AnyElement> = shown
@@ -479,50 +499,130 @@ fn people_strip(
479 499 state: &AppState,
480 500 model: &CallModel,
481 501 now: Instant,
502 available: (f32, f32),
482 503 ) -> Stateful<Div> {
504 let strip_width = state.call_strip_width.min(((available.0 - TILE_GAP) / 2.).max(0.));
505 let tile = TileSize::sixteen_by_nine(strip_width);
483 506 let mut cells: Vec<AnyElement> = model
484 507 .strip_tiles()
485 508 .into_iter()
486 .filter(|tile| !model.hidden_for_no_video(tile))
487 .map(|remote| person_tile(app, state, model, remote, STRIP_TILE, now))
509 .filter(|tile_model| !model.hidden_for_no_video(tile_model))
510 .map(|remote| person_tile(app, state, model, remote, tile, now))
488 511 .collect();
489 512 if model.own_cells() > 0 {
490 513 let own_index = model.own_cell_index(cells.len());
491 cells.insert(own_index, own_tile(app, state, model, STRIP_TILE, now));
514 cells.insert(own_index, own_tile(app, state, model, tile, now));
492 515 }
493 516 v_flex()
494 517 .id("call-strip")
518 .debug_selector(|| "shell/islands/main/call-stage/share-strip".into())
495 519 .flex_none()
496 .w(px(STRIP_TILE.width))
497 .max_h(px(
498 STRIP_VISIBLE * (STRIP_TILE.height + STRIP_GAP) - STRIP_GAP
499 ))
520 .w(px(tile.width))
521 .max_h(px((STRIP_VISIBLE * (tile.height + STRIP_GAP) - STRIP_GAP).min(available.1)))
500 522 .gap(px(STRIP_GAP))
501 523 .overflow_y_scroll()
502 524 .children(cells)
503 525 }
504 526
527 fn strip_divider(app: &Entity<AppState>, dragging: bool) -> Stateful<Div> {
528 let app = app.clone();
529 h_flex()
530 .id("call-strip-divider")
531 .debug_selector(|| "shell/islands/main/call-stage/share-divider".into())
532 .flex_none()
533 .w(px(TILE_GAP))
534 .h_full()
535 .items_center()
536 .justify_center()
537 .cursor_col_resize()
538 .child(
539 div()
540 .w(px(DIVIDER_LINE))
541 .h(px(DIVIDER_LENGTH))
542 .rounded_full()
543 .bg(if dragging { theme::accent() } else { theme::border() }),
544 )
545 .on_mouse_down(MouseButton::Left, move |event, _, cx| {
546 let pointer_x = f32::from(event.position.x);
547 app.update(cx, |state, cx| state.begin_strip_drag(pointer_x, cx));
548 })
549 }
550
505 551 fn share_body(
506 552 app: &Entity<AppState>,
507 553 state: &AppState,
508 554 model: &CallModel,
509 555 now: Instant,
510 stage: AnyElement,
556 share: AnyElement,
511 557 layout: CallLayout,
558 stage: (f32, f32),
512 559 ) -> AnyElement {
560 let move_app = app.clone();
561 let up_app = app.clone();
562 let up_out_app = app.clone();
563 let dragging = state.call.as_ref().is_some_and(|call| call.share_stage.strip_drag.is_some());
513 564 h_flex()
565 .id("call-share-body")
514 566 .absolute()
515 567 .inset_0()
516 568 .p(px(GRID_PADDING))
517 .gap(px(TILE_GAP))
518 569 .items_center()
519 .child(stage)
570 .on_mouse_move(move |event, _, cx| {
571 let pointer_x = f32::from(event.position.x);
572 move_app.update(cx, |state, cx| state.drag_strip_to(pointer_x, cx));
573 })
574 .on_mouse_up(MouseButton::Left, move |_, _, cx| {
575 up_app.update(cx, |state, cx| state.end_strip_drag(cx));
576 })
577 .on_mouse_up_out(MouseButton::Left, move |_, _, cx| {
578 up_out_app.update(cx, |state, cx| state.end_strip_drag(cx));
579 })
580 .child(share)
520 581 .when(layout != CallLayout::Content, |row| {
521 row.child(people_strip(app, state, model, now))
582 row.child(strip_divider(app, dragging)).child(people_strip(
583 app,
584 state,
585 model,
586 now,
587 (stage.0 - 2. * GRID_PADDING, stage.1 - 2. * GRID_PADDING),
588 ))
522 589 })
523 590 .into_any_element()
524 591 }
525 592
593 const LARGE_GALLERY_TILES: usize = 4;
594
595 fn want(tile: &Tile, detail: TileDetail) -> VideoWant {
596 VideoWant { mri: tile.mri.clone(), detail }
597 }
598
599 pub fn video_wants(model: &CallModel, stage: (f32, f32)) -> Vec<VideoWant> {
600 if model.has_content() {
601 if model.effective_layout() == CallLayout::Content {
602 return Vec::new();
603 }
604 return model
605 .strip_tiles()
606 .into_iter()
607 .filter(|tile| !model.hidden_for_no_video(tile))
608 .map(|tile| want(tile, TileDetail::Small))
609 .collect();
610 }
611 if model.effective_layout() == CallLayout::Speaker {
612 let split = speaker_split(model, stage);
613 let stage_person = split.focus.iter().filter(|focus| !focus.own).map(|focus| VideoWant {
614 mri: focus.mri.clone(),
615 detail: TileDetail::Stage,
616 });
617 return stage_person
618 .chain(split.others[..split.plan.overflow.shown].iter().map(|tile| want(tile, TileDetail::Small)))
619 .collect();
620 }
621 let (others, overflow) = gallery_split(model);
622 let detail = if overflow.shown <= LARGE_GALLERY_TILES { TileDetail::Stage } else { TileDetail::Small };
623 others[..overflow.shown].iter().map(|tile| want(tile, detail)).collect()
624 }
625
526 626 pub(super) fn stage_region(
527 627 app: &Entity<AppState>,
528 628 state: &AppState,
@@ -537,7 +637,7 @@ pub(super) fn stage_region(
537 637 let shows_people = hold.is_none() && !(share_stage.is_some() && layout == CallLayout::Content);
538 638 let body = match (hold, share_stage) {
539 639 (Some(hold), _) => v_flex().absolute().inset_0().child(hold).into_any_element(),
540 (None, Some(share)) => share_body(app, state, model, now, share, layout),
640 (None, Some(share)) => share_body(app, state, model, now, share, layout, stage),
541 641 (None, None) if layout == CallLayout::Speaker => {
542 642 speaker_body(app, state, model, now, stage)
543 643 }
@@ -561,3 +661,107 @@ pub(super) fn stage_region(
561 661 )
562 662 .into_any_element()
563 663 }
664
665 #[cfg(test)]
666 mod tests {
667 use std::time::Instant;
668
669 use calling::{CallUpdate, RosterEntry, TileDetail, VideoWant};
670
671 use super::{
672 CallLayout, CallModel, FILMSTRIP_TILE_MAX, GALLERY_MAX, GRID_PADDING, TILE_GAP, filmstrip, split_overflow,
673 video_wants,
674 };
675
676 const STAGE: (f32, f32) = (1400., 800.);
677
678 fn person(index: usize, has_video: bool) -> RosterEntry {
679 RosterEntry {
680 mri: format!("8:orgid:p{index}"),
681 display_name: format!("P{index}"),
682 muted: false,
683 in_lobby: false,
684 has_video,
685 sharing: false,
686 hand: None,
687 spotlight: None,
688 organizer: false,
689 role: None,
690 limits: Default::default(),
691 }
692 }
693
694 fn meeting(people: Vec<RosterEntry>) -> CallModel {
695 let mut model = CallModel::meeting("Standup", false);
696 model.apply(CallUpdate::OwnIdentity { mri: "8:orgid:me".into() });
697 model.apply(CallUpdate::Roster(people));
698 model
699 }
700
701 fn crowd(count: usize) -> CallModel {
702 meeting((0..count).map(|index| person(index, true)).collect())
703 }
704
705 fn details(wants: &[VideoWant]) -> Vec<TileDetail> {
706 wants.iter().map(|want| want.detail).collect()
707 }
708
709 #[test]
710 fn a_small_gallery_asks_for_large_pictures() {
711 let wants = video_wants(&crowd(3), STAGE);
712 assert_eq!(wants.len(), 3);
713 assert!(details(&wants).iter().all(|detail| *detail == TileDetail::Stage));
714 }
715
716 #[test]
717 fn a_big_gallery_asks_for_small_pictures_and_skips_the_plus_n_people() {
718 let model = crowd(14);
719 let wants = video_wants(&model, STAGE);
720 assert_eq!(wants.len(), split_overflow(14, 1, GALLERY_MAX).shown);
721 assert!(details(&wants).iter().all(|detail| *detail == TileDetail::Small));
722 let hidden: Vec<&str> = model.layout_tiles()[wants.len()..].iter().map(|tile| tile.mri.as_str()).collect();
723 assert!(wants.iter().all(|want| !hidden.contains(&want.mri.as_str())));
724 }
725
726 #[test]
727 fn people_hidden_for_having_no_video_get_no_picture_request() {
728 let mut model = meeting(vec![person(0, true), person(1, false), person(2, false)]);
729 model.view.hide_no_video = true;
730 let wants = video_wants(&model, STAGE);
731 assert_eq!(wants.iter().map(|want| want.mri.as_str()).collect::<Vec<_>>(), vec!["8:orgid:p0"]);
732 }
733
734 #[test]
735 fn the_speaker_stage_is_large_and_the_filmstrip_small() {
736 let mut model = crowd(5);
737 model.view.choose(CallLayout::Speaker);
738 model.refresh_layout(Instant::now());
739 let focus = model.speaker_focus().expect("a stage person").mri;
740 let wants = video_wants(&model, STAGE);
741 assert_eq!(wants[0], VideoWant { mri: focus.clone(), detail: TileDetail::Stage });
742 assert_eq!(wants.len(), 5);
743 assert!(wants[1..].iter().all(|want| want.detail == TileDetail::Small && want.mri != focus));
744 }
745
746 #[test]
747 fn the_speaker_filmstrip_drops_people_that_do_not_fit() {
748 let mut model = crowd(12);
749 model.view.choose(CallLayout::Speaker);
750 model.refresh_layout(Instant::now());
751 let wants = video_wants(&model, (500., 800.));
752 let fitting = filmstrip(11, 1, 500. - 2. * GRID_PADDING, TILE_GAP, FILMSTRIP_TILE_MAX).overflow.shown;
753 assert!(fitting < 11);
754 assert_eq!(wants.len(), 1 + fitting);
755 }
756
757 #[test]
758 fn next_to_shared_content_everybody_in_the_strip_is_small_and_content_focus_wants_nobody() {
759 let mut model = crowd(3);
760 model.apply(CallUpdate::ScreenShare(Some("8:orgid:p1".into())));
761 let wants = video_wants(&model, STAGE);
762 assert_eq!(wants.len(), 3);
763 assert!(details(&wants).iter().all(|detail| *detail == TileDetail::Small));
764 model.view.choose(CallLayout::Content);
765 assert!(video_wants(&model, STAGE).is_empty());
766 }
767 }
@@ -14,19 +14,22 @@ use gpui_kit::*;
14use super::avatar::person_avatar;
14use super::avatar::person_avatar;
15use super::call_organizer::render_focus_stage;
15use super::call_organizer::render_focus_stage;
16use super::call_view::{
16use super::call_view::{
17 GRID_PADDING, STRIP_GAP, STRIP_TILE, STRIP_VISIBLE, TILE_GAP, own_tile, person_tile,
17 GRID_PADDING, STRIP_GAP, STRIP_VISIBLE, TILE_GAP, own_tile, person_tile,
18};
18};
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.);
28const MEASURE_TOLERANCE: f32 = 0.5;
29const MEASURE_TOLERANCE: f32 = 0.5;
29const OVERLAY_INSET: f32 = 16.;
30const OVERLAY_INSET: f32 = 16.;
31const DIVIDER_LINE: f32 = 4.;
32const DIVIDER_LENGTH: f32 = 48.;
30const CHIP_TOP: f32 = 12.;
33const CHIP_TOP: f32 = 12.;
31const FILMSTRIP_TILE_MAX: f32 = 220.;
34const FILMSTRIP_TILE_MAX: f32 = 220.;
32const TILE_RADIUS: f32 = 12.;
35const TILE_RADIUS: f32 = 12.;
@@ -43,7 +46,7 @@ const BUBBLE_BACKGROUND: f32 = 0.72;
43const CHIP_BACKGROUND: f32 = 0.6;
46const CHIP_BACKGROUND: f32 = 0.6;
44pub const FULLSCREEN_HINT: &str = "Press Esc to exit full screen";
47pub const FULLSCREEN_HINT: &str = "Press Esc to exit full screen";
45
48
46fn measured_stage(call: &ActiveCall) -> (f32, f32) {
49pub fn measured_stage(call: &ActiveCall) -> (f32, f32) {
47 let (width, height) = call.stage_size.get();
50 let (width, height) = call.stage_size.get();
48 if width < 1. || height < 1. {
51 if width < 1. || height < 1. {
49 return FALLBACK_STAGE;
52 return FALLBACK_STAGE;
@@ -357,6 +360,12 @@ fn rows_of(cells: Vec<AnyElement>, columns: usize) -> Vec<Div> {
357 }
360 }
358}
361}
359
362
363fn gallery_split(model: &CallModel) -> (Vec<&Tile>, Overflow) {
364 let others = model.layout_tiles();
365 let overflow = split_overflow(others.len(), model.own_cells(), GALLERY_MAX);
366 (others, overflow)
367}
368
360fn gallery_body(
369fn gallery_body(
361 app: &Entity<AppState>,
370 app: &Entity<AppState>,
362 state: &AppState,
371 state: &AppState,
@@ -364,9 +373,8 @@ fn gallery_body(
364 now: Instant,
373 now: Instant,
365 stage: (f32, f32),
374 stage: (f32, f32),
366) -> AnyElement {
375) -> AnyElement {
367 let others = model.layout_tiles();
376 let (others, overflow) = gallery_split(model);
368 let own_cells = model.own_cells();
377 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);
378 let cells = overflow.shown + own_cells + usize::from(overflow.hidden > 0);
371 let grid = gallery_grid(
379 let grid = gallery_grid(
372 cells,
380 cells,
@@ -399,18 +407,16 @@ fn gallery_body(
399 .into_any_element()
407 .into_any_element()
400}
408}
401
409
402fn speaker_body(
410struct SpeakerSplit<'a> {
403 app: &Entity<AppState>,
411 focus: Option<Focus>,
404 state: &AppState,
412 others: Vec<&'a Tile>,
405 model: &CallModel,
413 own_cells: usize,
406 now: Instant,
414 plan: Filmstrip,
407 stage: (f32, f32),
415}
408) -> AnyElement {
416
417fn speaker_split(model: &CallModel, stage: (f32, f32)) -> SpeakerSplit<'_> {
409 let focus = model.speaker_focus();
418 let focus = model.speaker_focus();
410 let focus_mri = focus.as_ref().map(|focus| focus.mri.as_str());
419 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
420 let mut others: Vec<&Tile> = model
415 .layout_tiles()
421 .layout_tiles()
416 .into_iter()
422 .into_iter()
@@ -427,6 +433,20 @@ fn speaker_body(
427 if plan.overflow.shown < FILMSTRIP_MAX.min(others.len()) {
433 if plan.overflow.shown < FILMSTRIP_MAX.min(others.len()) {
428 others.sort_by_key(|tile| !model.is_recent_speaker(&tile.mri));
434 others.sort_by_key(|tile| !model.is_recent_speaker(&tile.mri));
429 }
435 }
436 SpeakerSplit { focus, others, own_cells, plan }
437}
438
439fn speaker_body(
440 app: &Entity<AppState>,
441 state: &AppState,
442 model: &CallModel,
443 now: Instant,
444 stage: (f32, f32),
445) -> AnyElement {
446 let SpeakerSplit { focus, others, own_cells, plan } = speaker_split(model, stage);
447 let main = focus
448 .as_ref()
449 .and_then(|focus| render_focus_stage(app, state, focus, now));
430 let size = TileSize::sixteen_by_nine(plan.tile_width.floor());
450 let size = TileSize::sixteen_by_nine(plan.tile_width.floor());
431 let shown = &others[..plan.overflow.shown];
451 let shown = &others[..plan.overflow.shown];
432 let mut tiles: Vec<AnyElement> = shown
452 let mut tiles: Vec<AnyElement> = shown
@@ -479,50 +499,130 @@ fn people_strip(
479 state: &AppState,
499 state: &AppState,
480 model: &CallModel,
500 model: &CallModel,
481 now: Instant,
501 now: Instant,
502 available: (f32, f32),
482) -> Stateful<Div> {
503) -> Stateful<Div> {
504 let strip_width = state.call_strip_width.min(((available.0 - TILE_GAP) / 2.).max(0.));
505 let tile = TileSize::sixteen_by_nine(strip_width);
483 let mut cells: Vec<AnyElement> = model
506 let mut cells: Vec<AnyElement> = model
484 .strip_tiles()
507 .strip_tiles()
485 .into_iter()
508 .into_iter()
486 .filter(|tile| !model.hidden_for_no_video(tile))
509 .filter(|tile_model| !model.hidden_for_no_video(tile_model))
487 .map(|remote| person_tile(app, state, model, remote, STRIP_TILE, now))
510 .map(|remote| person_tile(app, state, model, remote, tile, now))
488 .collect();
511 .collect();
489 if model.own_cells() > 0 {
512 if model.own_cells() > 0 {
490 let own_index = model.own_cell_index(cells.len());
513 let own_index = model.own_cell_index(cells.len());
491 cells.insert(own_index, own_tile(app, state, model, STRIP_TILE, now));
514 cells.insert(own_index, own_tile(app, state, model, tile, now));
492 }
515 }
493 v_flex()
516 v_flex()
494 .id("call-strip")
517 .id("call-strip")
518 .debug_selector(|| "shell/islands/main/call-stage/share-strip".into())
495 .flex_none()
519 .flex_none()
496 .w(px(STRIP_TILE.width))
520 .w(px(tile.width))
497 .max_h(px(
521 .max_h(px((STRIP_VISIBLE * (tile.height + STRIP_GAP) - STRIP_GAP).min(available.1)))
498 STRIP_VISIBLE * (STRIP_TILE.height + STRIP_GAP) - STRIP_GAP
499 ))
500 .gap(px(STRIP_GAP))
522 .gap(px(STRIP_GAP))
501 .overflow_y_scroll()
523 .overflow_y_scroll()
502 .children(cells)
524 .children(cells)
503}
525}
504
526
527fn strip_divider(app: &Entity<AppState>, dragging: bool) -> Stateful<Div> {
528 let app = app.clone();
529 h_flex()
530 .id("call-strip-divider")
531 .debug_selector(|| "shell/islands/main/call-stage/share-divider".into())
532 .flex_none()
533 .w(px(TILE_GAP))
534 .h_full()
535 .items_center()
536 .justify_center()
537 .cursor_col_resize()
538 .child(
539 div()
540 .w(px(DIVIDER_LINE))
541 .h(px(DIVIDER_LENGTH))
542 .rounded_full()
543 .bg(if dragging { theme::accent() } else { theme::border() }),
544 )
545 .on_mouse_down(MouseButton::Left, move |event, _, cx| {
546 let pointer_x = f32::from(event.position.x);
547 app.update(cx, |state, cx| state.begin_strip_drag(pointer_x, cx));
548 })
549}
550
505fn share_body(
551fn share_body(
506 app: &Entity<AppState>,
552 app: &Entity<AppState>,
507 state: &AppState,
553 state: &AppState,
508 model: &CallModel,
554 model: &CallModel,
509 now: Instant,
555 now: Instant,
510 stage: AnyElement,
556 share: AnyElement,
511 layout: CallLayout,
557 layout: CallLayout,
558 stage: (f32, f32),
512) -> AnyElement {
559) -> AnyElement {
560 let move_app = app.clone();
561 let up_app = app.clone();
562 let up_out_app = app.clone();
563 let dragging = state.call.as_ref().is_some_and(|call| call.share_stage.strip_drag.is_some());
513 h_flex()
564 h_flex()
565 .id("call-share-body")
514 .absolute()
566 .absolute()
515 .inset_0()
567 .inset_0()
516 .p(px(GRID_PADDING))
568 .p(px(GRID_PADDING))
517 .gap(px(TILE_GAP))
518 .items_center()
569 .items_center()
519 .child(stage)
570 .on_mouse_move(move |event, _, cx| {
571 let pointer_x = f32::from(event.position.x);
572 move_app.update(cx, |state, cx| state.drag_strip_to(pointer_x, cx));
573 })
574 .on_mouse_up(MouseButton::Left, move |_, _, cx| {
575 up_app.update(cx, |state, cx| state.end_strip_drag(cx));
576 })
577 .on_mouse_up_out(MouseButton::Left, move |_, _, cx| {
578 up_out_app.update(cx, |state, cx| state.end_strip_drag(cx));
579 })
580 .child(share)
520 .when(layout != CallLayout::Content, |row| {
581 .when(layout != CallLayout::Content, |row| {
521 row.child(people_strip(app, state, model, now))
582 row.child(strip_divider(app, dragging)).child(people_strip(
583 app,
584 state,
585 model,
586 now,
587 (stage.0 - 2. * GRID_PADDING, stage.1 - 2. * GRID_PADDING),
588 ))
522 })
589 })
523 .into_any_element()
590 .into_any_element()
524}
591}
525
592
593const LARGE_GALLERY_TILES: usize = 4;
594
595fn want(tile: &Tile, detail: TileDetail) -> VideoWant {
596 VideoWant { mri: tile.mri.clone(), detail }
597}
598
599pub fn video_wants(model: &CallModel, stage: (f32, f32)) -> Vec<VideoWant> {
600 if model.has_content() {
601 if model.effective_layout() == CallLayout::Content {
602 return Vec::new();
603 }
604 return model
605 .strip_tiles()
606 .into_iter()
607 .filter(|tile| !model.hidden_for_no_video(tile))
608 .map(|tile| want(tile, TileDetail::Small))
609 .collect();
610 }
611 if model.effective_layout() == CallLayout::Speaker {
612 let split = speaker_split(model, stage);
613 let stage_person = split.focus.iter().filter(|focus| !focus.own).map(|focus| VideoWant {
614 mri: focus.mri.clone(),
615 detail: TileDetail::Stage,
616 });
617 return stage_person
618 .chain(split.others[..split.plan.overflow.shown].iter().map(|tile| want(tile, TileDetail::Small)))
619 .collect();
620 }
621 let (others, overflow) = gallery_split(model);
622 let detail = if overflow.shown <= LARGE_GALLERY_TILES { TileDetail::Stage } else { TileDetail::Small };
623 others[..overflow.shown].iter().map(|tile| want(tile, detail)).collect()
624}
625
526pub(super) fn stage_region(
626pub(super) fn stage_region(
527 app: &Entity<AppState>,
627 app: &Entity<AppState>,
528 state: &AppState,
628 state: &AppState,
@@ -537,7 +637,7 @@ pub(super) fn stage_region(
537 let shows_people = hold.is_none() && !(share_stage.is_some() && layout == CallLayout::Content);
637 let shows_people = hold.is_none() && !(share_stage.is_some() && layout == CallLayout::Content);
538 let body = match (hold, share_stage) {
638 let body = match (hold, share_stage) {
539 (Some(hold), _) => v_flex().absolute().inset_0().child(hold).into_any_element(),
639 (Some(hold), _) => v_flex().absolute().inset_0().child(hold).into_any_element(),
540 (None, Some(share)) => share_body(app, state, model, now, share, layout),
640 (None, Some(share)) => share_body(app, state, model, now, share, layout, stage),
541 (None, None) if layout == CallLayout::Speaker => {
641 (None, None) if layout == CallLayout::Speaker => {
542 speaker_body(app, state, model, now, stage)
642 speaker_body(app, state, model, now, stage)
543 }
643 }
@@ -561,3 +661,107 @@ pub(super) fn stage_region(
561 )
661 )
562 .into_any_element()
662 .into_any_element()
563}
663}
664
665#[cfg(test)]
666mod tests {
667 use std::time::Instant;
668
669 use calling::{CallUpdate, RosterEntry, TileDetail, VideoWant};
670
671 use super::{
672 CallLayout, CallModel, FILMSTRIP_TILE_MAX, GALLERY_MAX, GRID_PADDING, TILE_GAP, filmstrip, split_overflow,
673 video_wants,
674 };
675
676 const STAGE: (f32, f32) = (1400., 800.);
677
678 fn person(index: usize, has_video: bool) -> RosterEntry {
679 RosterEntry {
680 mri: format!("8:orgid:p{index}"),
681 display_name: format!("P{index}"),
682 muted: false,
683 in_lobby: false,
684 has_video,
685 sharing: false,
686 hand: None,
687 spotlight: None,
688 organizer: false,
689 role: None,
690 limits: Default::default(),
691 }
692 }
693
694 fn meeting(people: Vec<RosterEntry>) -> CallModel {
695 let mut model = CallModel::meeting("Standup", false);
696 model.apply(CallUpdate::OwnIdentity { mri: "8:orgid:me".into() });
697 model.apply(CallUpdate::Roster(people));
698 model
699 }
700
701 fn crowd(count: usize) -> CallModel {
702 meeting((0..count).map(|index| person(index, true)).collect())
703 }
704
705 fn details(wants: &[VideoWant]) -> Vec<TileDetail> {
706 wants.iter().map(|want| want.detail).collect()
707 }
708
709 #[test]
710 fn a_small_gallery_asks_for_large_pictures() {
711 let wants = video_wants(&crowd(3), STAGE);
712 assert_eq!(wants.len(), 3);
713 assert!(details(&wants).iter().all(|detail| *detail == TileDetail::Stage));
714 }
715
716 #[test]
717 fn a_big_gallery_asks_for_small_pictures_and_skips_the_plus_n_people() {
718 let model = crowd(14);
719 let wants = video_wants(&model, STAGE);
720 assert_eq!(wants.len(), split_overflow(14, 1, GALLERY_MAX).shown);
721 assert!(details(&wants).iter().all(|detail| *detail == TileDetail::Small));
722 let hidden: Vec<&str> = model.layout_tiles()[wants.len()..].iter().map(|tile| tile.mri.as_str()).collect();
723 assert!(wants.iter().all(|want| !hidden.contains(&want.mri.as_str())));
724 }
725
726 #[test]
727 fn people_hidden_for_having_no_video_get_no_picture_request() {
728 let mut model = meeting(vec![person(0, true), person(1, false), person(2, false)]);
729 model.view.hide_no_video = true;
730 let wants = video_wants(&model, STAGE);
731 assert_eq!(wants.iter().map(|want| want.mri.as_str()).collect::<Vec<_>>(), vec!["8:orgid:p0"]);
732 }
733
734 #[test]
735 fn the_speaker_stage_is_large_and_the_filmstrip_small() {
736 let mut model = crowd(5);
737 model.view.choose(CallLayout::Speaker);
738 model.refresh_layout(Instant::now());
739 let focus = model.speaker_focus().expect("a stage person").mri;
740 let wants = video_wants(&model, STAGE);
741 assert_eq!(wants[0], VideoWant { mri: focus.clone(), detail: TileDetail::Stage });
742 assert_eq!(wants.len(), 5);
743 assert!(wants[1..].iter().all(|want| want.detail == TileDetail::Small && want.mri != focus));
744 }
745
746 #[test]
747 fn the_speaker_filmstrip_drops_people_that_do_not_fit() {
748 let mut model = crowd(12);
749 model.view.choose(CallLayout::Speaker);
750 model.refresh_layout(Instant::now());
751 let wants = video_wants(&model, (500., 800.));
752 let fitting = filmstrip(11, 1, 500. - 2. * GRID_PADDING, TILE_GAP, FILMSTRIP_TILE_MAX).overflow.shown;
753 assert!(fitting < 11);
754 assert_eq!(wants.len(), 1 + fitting);
755 }
756
757 #[test]
758 fn next_to_shared_content_everybody_in_the_strip_is_small_and_content_focus_wants_nobody() {
759 let mut model = crowd(3);
760 model.apply(CallUpdate::ScreenShare(Some("8:orgid:p1".into())));
761 let wants = video_wants(&model, STAGE);
762 assert_eq!(wants.len(), 3);
763 assert!(details(&wants).iter().all(|detail| *detail == TileDetail::Small));
764 model.view.choose(CallLayout::Content);
765 assert!(video_wants(&model, STAGE).is_empty());
766 }
767}
crates/app/src/views/call_pop_out.rs added +67 −0
@@ -0,0 +1,67 @@
1 use gpui_kit::component::v_flex;
2 use gpui_kit::*;
3
4 use super::call_stage::{StageMode, render_stage};
5 use super::shortcuts::{ZoomShareIn, ZoomShareOut, ZoomShareReset};
6 use crate::app_state::AppState;
7 use crate::call::ZoomStep;
8 use crate::theme;
9
10 pub const POP_OUT_TITLE: &str = "Shared content";
11 pub const POP_OUT_SIZE: (f32, f32) = (960., 600.);
12 const KEY_CONTEXT: &str = "SharePopOut";
13
14 pub struct SharePopOutView {
15 app: Entity<AppState>,
16 focus: FocusHandle,
17 _app_subscription: Subscription,
18 _media_subscription: Option<Subscription>,
19 }
20
21 impl SharePopOutView {
22 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
23 let app_subscription = cx.observe(&app, |_, _, cx| cx.notify());
24 let media_subscription = app
25 .read(cx)
26 .call_media
27 .clone()
28 .map(|media| cx.observe(&media, |_, _, cx| cx.notify()));
29 let closing_app = app.clone();
30 window.on_window_should_close(cx, move |_, cx| {
31 closing_app.update(cx, |state, cx| state.return_stage_from_pop_out(cx));
32 true
33 });
34 let focus = cx.focus_handle();
35 window.focus(&focus, cx);
36 SharePopOutView {
37 app,
38 focus,
39 _app_subscription: app_subscription,
40 _media_subscription: media_subscription,
41 }
42 }
43 }
44
45 pub fn zoom_listener<A: Action>(
46 app: &Entity<AppState>,
47 step: ZoomStep,
48 ) -> impl Fn(&A, &mut Window, &mut App) + 'static {
49 let app = app.clone();
50 move |_, _, cx| app.update(cx, |state, cx| state.zoom_share(step, cx))
51 }
52
53 impl Render for SharePopOutView {
54 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
55 let state = self.app.read(cx);
56 v_flex()
57 .id("share-pop-out")
58 .key_context(KEY_CONTEXT)
59 .track_focus(&self.focus)
60 .size_full()
61 .bg(theme::background())
62 .on_action(zoom_listener::<ZoomShareIn>(&self.app, ZoomStep::In))
63 .on_action(zoom_listener::<ZoomShareOut>(&self.app, ZoomStep::Out))
64 .on_action(zoom_listener::<ZoomShareReset>(&self.app, ZoomStep::Reset))
65 .children(render_stage(&self.app, state, StageMode::PopOut))
66 }
67 }
@@ -0,0 +1,67 @@
1use gpui_kit::component::v_flex;
2use gpui_kit::*;
3
4use super::call_stage::{StageMode, render_stage};
5use super::shortcuts::{ZoomShareIn, ZoomShareOut, ZoomShareReset};
6use crate::app_state::AppState;
7use crate::call::ZoomStep;
8use crate::theme;
9
10pub const POP_OUT_TITLE: &str = "Shared content";
11pub const POP_OUT_SIZE: (f32, f32) = (960., 600.);
12const KEY_CONTEXT: &str = "SharePopOut";
13
14pub struct SharePopOutView {
15 app: Entity<AppState>,
16 focus: FocusHandle,
17 _app_subscription: Subscription,
18 _media_subscription: Option<Subscription>,
19}
20
21impl SharePopOutView {
22 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
23 let app_subscription = cx.observe(&app, |_, _, cx| cx.notify());
24 let media_subscription = app
25 .read(cx)
26 .call_media
27 .clone()
28 .map(|media| cx.observe(&media, |_, _, cx| cx.notify()));
29 let closing_app = app.clone();
30 window.on_window_should_close(cx, move |_, cx| {
31 closing_app.update(cx, |state, cx| state.return_stage_from_pop_out(cx));
32 true
33 });
34 let focus = cx.focus_handle();
35 window.focus(&focus, cx);
36 SharePopOutView {
37 app,
38 focus,
39 _app_subscription: app_subscription,
40 _media_subscription: media_subscription,
41 }
42 }
43}
44
45pub fn zoom_listener<A: Action>(
46 app: &Entity<AppState>,
47 step: ZoomStep,
48) -> impl Fn(&A, &mut Window, &mut App) + 'static {
49 let app = app.clone();
50 move |_, _, cx| app.update(cx, |state, cx| state.zoom_share(step, cx))
51}
52
53impl Render for SharePopOutView {
54 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
55 let state = self.app.read(cx);
56 v_flex()
57 .id("share-pop-out")
58 .key_context(KEY_CONTEXT)
59 .track_focus(&self.focus)
60 .size_full()
61 .bg(theme::background())
62 .on_action(zoom_listener::<ZoomShareIn>(&self.app, ZoomStep::In))
63 .on_action(zoom_listener::<ZoomShareOut>(&self.app, ZoomStep::Out))
64 .on_action(zoom_listener::<ZoomShareReset>(&self.app, ZoomStep::Reset))
65 .children(render_stage(&self.app, state, StageMode::PopOut))
66 }
67}
crates/app/src/views/call_stage.rs +211 −19
@@ -7,8 +7,11 @@ use gpui_kit::component::{h_flex, v_flex};
7 7 use gpui_kit::prelude::FluentBuilder as _;
8 8 use gpui_kit::*;
9 9
10 use gpui_kit::component::tooltip::Tooltip;
11
10 12 use super::widgets::icon;
11 13 use crate::app_state::AppState;
14 use crate::call::{ShareStage, ZoomStep};
12 15 use crate::theme;
13 16
14 17 const STAGE_RADIUS: f32 = 12.;
@@ -17,6 +20,17 @@ const STAGE_BACKGROUND: f32 = 0.04;
17 20 const LABEL_BACKGROUND: f32 = 0.6;
18 21 pub const WAITING_TEXT: &str = "Loading the shared screen...";
19 22 pub const FULL_WINDOW_HINT: &str = "Double-click or press Esc to leave full window";
23 pub const POP_OUT_TOOLTIP: &str = "Pop out";
24 pub const POPPED_TEXT: &str = "Shared content is open in its own window";
25 const LINE_HEIGHT: f32 = 20.;
26 const CHIP_HEIGHT: f32 = 30.;
27
28 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
29 pub enum StageMode {
30 Docked,
31 Fullscreen,
32 PopOut,
33 }
20 34
21 35 fn stage_black() -> Hsla {
22 36 hsla(0., 0., STAGE_BACKGROUND, 1.)
@@ -40,13 +54,9 @@ fn label_chip(text: String) -> Div {
40 54 .child(text)
41 55 }
42 56
43 fn picture(image: Option<Arc<RenderImage>>) -> AnyElement {
44 match image {
45 Some(image) => img(ImageSource::Render(image))
46 .size_full()
47 .object_fit(ObjectFit::Contain)
48 .into_any_element(),
49 None => div()
57 fn picture(image: Option<Arc<RenderImage>>, stage: &ShareStage) -> AnyElement {
58 let Some(image) = image else {
59 return div()
50 60 .size_full()
51 61 .flex()
52 62 .items_center()
@@ -54,25 +64,170 @@ fn picture(image: Option<Arc<RenderImage>>) -> AnyElement {
54 64 .text_size(px(14.))
55 65 .text_color(theme::text_muted())
56 66 .child(WAITING_TEXT)
57 .into_any_element(),
67 .into_any_element();
68 };
69 let size = stage.size();
70 let (offset_x, offset_y) = stage.view.offset(size);
71 let zoom = stage.view.zoom();
72 div()
73 .absolute()
74 .left(px(offset_x))
75 .top(px(offset_y))
76 .w(px(size.0 * zoom))
77 .h(px(size.1 * zoom))
78 .child(
79 img(ImageSource::Render(image))
80 .size_full()
81 .object_fit(ObjectFit::Contain),
82 )
83 .into_any_element()
84 }
85
86 fn measure(stage: &ShareStage) -> impl IntoElement {
87 let bounds = stage.bounds.clone();
88 canvas(
89 |_, _, _| {},
90 move |area, _, window, _| {
91 let measured = (
92 f32::from(area.origin.x),
93 f32::from(area.origin.y),
94 f32::from(area.size.width),
95 f32::from(area.size.height),
96 );
97 if bounds.get() != measured {
98 bounds.set(measured);
99 window.refresh();
100 }
101 },
102 )
103 .absolute()
104 .size_full()
105 }
106
107 fn zoom_chip(app: &Entity<AppState>, stage: &ShareStage) -> Option<AnyElement> {
108 if !stage.view.is_zoomed() {
109 return None;
58 110 }
111 let app = app.clone();
112 Some(
113 div()
114 .absolute()
115 .top(px(LABEL_OFFSET))
116 .right(px(LABEL_OFFSET))
117 .debug_selector(|| "shell/islands/main/call-stage/share-content/zoom-chip".into())
118 .child(
119 h_flex()
120 .id("call-stage-zoom")
121 .h(px(CHIP_HEIGHT))
122 .px(px(12.))
123 .gap(px(8.))
124 .items_center()
125 .rounded_full()
126 .bg(hsla(0., 0., 0., LABEL_BACKGROUND))
127 .text_color(theme::white())
128 .text_size(px(13.))
129 .font_weight(FontWeight::SEMIBOLD)
130 .cursor_pointer()
131 .hover(|chip| chip.opacity(0.85))
132 .tooltip(|window, cx| Tooltip::new("Reset zoom").build(window, cx))
133 .child(icon(IconName::Search, 15., theme::white()))
134 .child(format!("{}%", stage.view.percent()))
135 .on_click(move |_, _, cx| {
136 cx.stop_propagation();
137 app.update(cx, |state, cx| state.zoom_share(ZoomStep::Reset, cx));
138 }),
139 )
140 .into_any_element(),
141 )
142 }
143
144 fn pop_out_button(app: &Entity<AppState>) -> AnyElement {
145 let app = app.clone();
146 div()
147 .absolute()
148 .bottom(px(LABEL_OFFSET))
149 .right(px(LABEL_OFFSET))
150 .child(
151 h_flex()
152 .id("call-stage-pop-out")
153 .h(px(CHIP_HEIGHT))
154 .px(px(12.))
155 .gap(px(8.))
156 .items_center()
157 .rounded_full()
158 .bg(hsla(0., 0., 0., LABEL_BACKGROUND))
159 .text_color(theme::white())
160 .text_size(px(13.))
161 .font_weight(FontWeight::SEMIBOLD)
162 .cursor_pointer()
163 .hover(|chip| chip.opacity(0.85))
164 .child(icon(IconName::ExternalLink, 15., theme::white()))
165 .child(POP_OUT_TOOLTIP)
166 .on_click(move |_, _, cx| {
167 cx.stop_propagation();
168 app.update(cx, |state, cx| state.pop_out_stage(cx));
169 }),
170 )
171 .into_any_element()
172 }
173
174 pub fn popped_placeholder(app: &Entity<AppState>) -> AnyElement {
175 let app = app.clone();
176 v_flex()
177 .id("call-stage-popped")
178 .flex_1()
179 .min_w_0()
180 .h_full()
181 .items_center()
182 .justify_center()
183 .gap(px(12.))
184 .rounded(px(STAGE_RADIUS))
185 .bg(stage_black())
186 .text_size(px(14.))
187 .text_color(theme::text_muted())
188 .child(POPPED_TEXT)
189 .child(
190 h_flex()
191 .id("call-stage-bring-back")
192 .h(px(CHIP_HEIGHT))
193 .px(px(14.))
194 .items_center()
195 .rounded_full()
196 .bg(theme::accent())
197 .text_color(theme::on_accent())
198 .font_weight(FontWeight::SEMIBOLD)
199 .cursor_pointer()
200 .hover(|button| button.opacity(0.9))
201 .child("Bring back")
202 .on_click(move |_, _, cx| {
203 app.update(cx, |state, cx| state.return_stage_from_pop_out(cx))
204 }),
205 )
206 .into_any_element()
59 207 }
60 208
61 209 pub fn render_stage(
62 210 app: &Entity<AppState>,
63 211 state: &AppState,
64 fullscreen: bool,
212 mode: StageMode,
65 213 ) -> Option<AnyElement> {
66 214 let call = state.call.as_ref()?;
67 215 let label = call.model.sharing_label()?;
68 216 let image = call.pictures.live(&VideoKey::Screen, Instant::now());
217 let share_stage = &call.share_stage;
69 218 let toggle_app = app.clone();
219 let wheel_app = app.clone();
220 let down_app = app.clone();
221 let move_app = app.clone();
222 let up_app = app.clone();
223 let up_out_app = app.clone();
224 let position = |point: Point<Pixels>| (f32::from(point.x), f32::from(point.y));
70 225 Some(
71 226 div()
72 .id(if fullscreen {
73 "call-stage-full"
74 } else {
75 "call-stage"
227 .id(match mode {
228 StageMode::Docked => "call-stage",
229 StageMode::Fullscreen => "call-stage-full",
230 StageMode::PopOut => "call-stage-pop-out-window",
76 231 })
77 232 .relative()
78 233 .flex_1()
@@ -80,16 +235,53 @@ pub fn render_stage(
80 235 .h_full()
81 236 .overflow_hidden()
82 237 .bg(stage_black())
83 .when(!fullscreen, |stage| stage.rounded(px(STAGE_RADIUS)))
84 .cursor_pointer()
238 .when(mode == StageMode::Docked, |stage| {
239 stage
240 .rounded(px(STAGE_RADIUS))
241 .debug_selector(|| "shell/islands/main/call-stage/share-content".into())
242 })
243 .map(|stage| {
244 if share_stage.view.is_zoomed() {
245 stage.cursor_grab()
246 } else {
247 stage.cursor_pointer()
248 }
249 })
250 .on_scroll_wheel(move |event, _, cx| {
251 if !event.modifiers.control {
252 return;
253 }
254 let scroll = f32::from(event.delta.pixel_delta(px(LINE_HEIGHT)).y);
255 wheel_app.update(cx, |state, cx| {
256 state.zoom_share_wheel(scroll, position(event.position), cx)
257 });
258 cx.stop_propagation();
259 })
260 .on_mouse_down(MouseButton::Left, move |event, _, cx| {
261 down_app.update(cx, |state, cx| state.begin_share_pan(position(event.position), cx));
262 })
263 .on_mouse_move(move |event, _, cx| {
264 if event.pressed_button == Some(MouseButton::Left) {
265 move_app.update(cx, |state, cx| state.pan_share_to(position(event.position), cx));
266 }
267 })
268 .on_mouse_up(MouseButton::Left, move |_, _, cx| {
269 up_app.update(cx, |state, cx| state.end_share_pan(cx));
270 })
271 .on_mouse_up_out(MouseButton::Left, move |_, _, cx| {
272 up_out_app.update(cx, |state, cx| state.end_share_pan(cx));
273 })
85 274 .on_click(move |event, _, cx| {
86 if event.click_count() >= 2 {
275 if mode != StageMode::PopOut && event.click_count() >= 2 {
87 276 toggle_app.update(cx, |state, cx| state.toggle_stage_fullscreen(cx));
88 277 }
89 278 })
90 .child(picture(image))
279 .child(measure(share_stage))
280 .child(picture(image, share_stage))
91 281 .child(label_chip(label))
92 .when(fullscreen, |stage| {
282 .children(zoom_chip(app, share_stage))
283 .when(mode == StageMode::Docked, |stage| stage.child(pop_out_button(app)))
284 .when(mode == StageMode::Fullscreen, |stage| {
93 285 stage.child(
94 286 div()
95 287 .absolute()
@@ -118,7 +310,7 @@ pub fn render_stage_overlay(app: &Entity<AppState>, state: &AppState) -> Option<
118 310 if !state.stage_fullscreen() {
119 311 return None;
120 312 }
121 let stage = render_stage(app, state, true)?;
313 let stage = render_stage(app, state, StageMode::Fullscreen)?;
122 314 Some(
123 315 v_flex()
124 316 .id("call-stage-overlay")
@@ -7,8 +7,11 @@ use gpui_kit::component::{h_flex, v_flex};
7use gpui_kit::prelude::FluentBuilder as _;
7use gpui_kit::prelude::FluentBuilder as _;
8use gpui_kit::*;
8use gpui_kit::*;
9
9
10use gpui_kit::component::tooltip::Tooltip;
11
10use super::widgets::icon;
12use super::widgets::icon;
11use crate::app_state::AppState;
13use crate::app_state::AppState;
14use crate::call::{ShareStage, ZoomStep};
12use crate::theme;
15use crate::theme;
13
16
14const STAGE_RADIUS: f32 = 12.;
17const STAGE_RADIUS: f32 = 12.;
@@ -17,6 +20,17 @@ const STAGE_BACKGROUND: f32 = 0.04;
17const LABEL_BACKGROUND: f32 = 0.6;
20const LABEL_BACKGROUND: f32 = 0.6;
18pub const WAITING_TEXT: &str = "Loading the shared screen...";
21pub const WAITING_TEXT: &str = "Loading the shared screen...";
19pub const FULL_WINDOW_HINT: &str = "Double-click or press Esc to leave full window";
22pub const FULL_WINDOW_HINT: &str = "Double-click or press Esc to leave full window";
23pub const POP_OUT_TOOLTIP: &str = "Pop out";
24pub const POPPED_TEXT: &str = "Shared content is open in its own window";
25const LINE_HEIGHT: f32 = 20.;
26const CHIP_HEIGHT: f32 = 30.;
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum StageMode {
30 Docked,
31 Fullscreen,
32 PopOut,
33}
20
34
21fn stage_black() -> Hsla {
35fn stage_black() -> Hsla {
22 hsla(0., 0., STAGE_BACKGROUND, 1.)
36 hsla(0., 0., STAGE_BACKGROUND, 1.)
@@ -40,13 +54,9 @@ fn label_chip(text: String) -> Div {
40 .child(text)
54 .child(text)
41}
55}
42
56
43fn picture(image: Option<Arc<RenderImage>>) -> AnyElement {
57fn picture(image: Option<Arc<RenderImage>>, stage: &ShareStage) -> AnyElement {
44 match image {
58 let Some(image) = image else {
45 Some(image) => img(ImageSource::Render(image))
59 return div()
46 .size_full()
47 .object_fit(ObjectFit::Contain)
48 .into_any_element(),
49 None => div()
50 .size_full()
60 .size_full()
51 .flex()
61 .flex()
52 .items_center()
62 .items_center()
@@ -54,25 +64,170 @@ fn picture(image: Option<Arc<RenderImage>>) -> AnyElement {
54 .text_size(px(14.))
64 .text_size(px(14.))
55 .text_color(theme::text_muted())
65 .text_color(theme::text_muted())
56 .child(WAITING_TEXT)
66 .child(WAITING_TEXT)
57 .into_any_element(),
67 .into_any_element();
68 };
69 let size = stage.size();
70 let (offset_x, offset_y) = stage.view.offset(size);
71 let zoom = stage.view.zoom();
72 div()
73 .absolute()
74 .left(px(offset_x))
75 .top(px(offset_y))
76 .w(px(size.0 * zoom))
77 .h(px(size.1 * zoom))
78 .child(
79 img(ImageSource::Render(image))
80 .size_full()
81 .object_fit(ObjectFit::Contain),
82 )
83 .into_any_element()
84}
85
86fn measure(stage: &ShareStage) -> impl IntoElement {
87 let bounds = stage.bounds.clone();
88 canvas(
89 |_, _, _| {},
90 move |area, _, window, _| {
91 let measured = (
92 f32::from(area.origin.x),
93 f32::from(area.origin.y),
94 f32::from(area.size.width),
95 f32::from(area.size.height),
96 );
97 if bounds.get() != measured {
98 bounds.set(measured);
99 window.refresh();
100 }
101 },
102 )
103 .absolute()
104 .size_full()
105}
106
107fn zoom_chip(app: &Entity<AppState>, stage: &ShareStage) -> Option<AnyElement> {
108 if !stage.view.is_zoomed() {
109 return None;
58 }
110 }
111 let app = app.clone();
112 Some(
113 div()
114 .absolute()
115 .top(px(LABEL_OFFSET))
116 .right(px(LABEL_OFFSET))
117 .debug_selector(|| "shell/islands/main/call-stage/share-content/zoom-chip".into())
118 .child(
119 h_flex()
120 .id("call-stage-zoom")
121 .h(px(CHIP_HEIGHT))
122 .px(px(12.))
123 .gap(px(8.))
124 .items_center()
125 .rounded_full()
126 .bg(hsla(0., 0., 0., LABEL_BACKGROUND))
127 .text_color(theme::white())
128 .text_size(px(13.))
129 .font_weight(FontWeight::SEMIBOLD)
130 .cursor_pointer()
131 .hover(|chip| chip.opacity(0.85))
132 .tooltip(|window, cx| Tooltip::new("Reset zoom").build(window, cx))
133 .child(icon(IconName::Search, 15., theme::white()))
134 .child(format!("{}%", stage.view.percent()))
135 .on_click(move |_, _, cx| {
136 cx.stop_propagation();
137 app.update(cx, |state, cx| state.zoom_share(ZoomStep::Reset, cx));
138 }),
139 )
140 .into_any_element(),
141 )
142}
143
144fn pop_out_button(app: &Entity<AppState>) -> AnyElement {
145 let app = app.clone();
146 div()
147 .absolute()
148 .bottom(px(LABEL_OFFSET))
149 .right(px(LABEL_OFFSET))
150 .child(
151 h_flex()
152 .id("call-stage-pop-out")
153 .h(px(CHIP_HEIGHT))
154 .px(px(12.))
155 .gap(px(8.))
156 .items_center()
157 .rounded_full()
158 .bg(hsla(0., 0., 0., LABEL_BACKGROUND))
159 .text_color(theme::white())
160 .text_size(px(13.))
161 .font_weight(FontWeight::SEMIBOLD)
162 .cursor_pointer()
163 .hover(|chip| chip.opacity(0.85))
164 .child(icon(IconName::ExternalLink, 15., theme::white()))
165 .child(POP_OUT_TOOLTIP)
166 .on_click(move |_, _, cx| {
167 cx.stop_propagation();
168 app.update(cx, |state, cx| state.pop_out_stage(cx));
169 }),
170 )
171 .into_any_element()
172}
173
174pub fn popped_placeholder(app: &Entity<AppState>) -> AnyElement {
175 let app = app.clone();
176 v_flex()
177 .id("call-stage-popped")
178 .flex_1()
179 .min_w_0()
180 .h_full()
181 .items_center()
182 .justify_center()
183 .gap(px(12.))
184 .rounded(px(STAGE_RADIUS))
185 .bg(stage_black())
186 .text_size(px(14.))
187 .text_color(theme::text_muted())
188 .child(POPPED_TEXT)
189 .child(
190 h_flex()
191 .id("call-stage-bring-back")
192 .h(px(CHIP_HEIGHT))
193 .px(px(14.))
194 .items_center()
195 .rounded_full()
196 .bg(theme::accent())
197 .text_color(theme::on_accent())
198 .font_weight(FontWeight::SEMIBOLD)
199 .cursor_pointer()
200 .hover(|button| button.opacity(0.9))
201 .child("Bring back")
202 .on_click(move |_, _, cx| {
203 app.update(cx, |state, cx| state.return_stage_from_pop_out(cx))
204 }),
205 )
206 .into_any_element()
59}
207}
60
208
61pub fn render_stage(
209pub fn render_stage(
62 app: &Entity<AppState>,
210 app: &Entity<AppState>,
63 state: &AppState,
211 state: &AppState,
64 fullscreen: bool,
212 mode: StageMode,
65) -> Option<AnyElement> {
213) -> Option<AnyElement> {
66 let call = state.call.as_ref()?;
214 let call = state.call.as_ref()?;
67 let label = call.model.sharing_label()?;
215 let label = call.model.sharing_label()?;
68 let image = call.pictures.live(&VideoKey::Screen, Instant::now());
216 let image = call.pictures.live(&VideoKey::Screen, Instant::now());
217 let share_stage = &call.share_stage;
69 let toggle_app = app.clone();
218 let toggle_app = app.clone();
219 let wheel_app = app.clone();
220 let down_app = app.clone();
221 let move_app = app.clone();
222 let up_app = app.clone();
223 let up_out_app = app.clone();
224 let position = |point: Point<Pixels>| (f32::from(point.x), f32::from(point.y));
70 Some(
225 Some(
71 div()
226 div()
72 .id(if fullscreen {
227 .id(match mode {
73 "call-stage-full"
228 StageMode::Docked => "call-stage",
74 } else {
229 StageMode::Fullscreen => "call-stage-full",
75 "call-stage"
230 StageMode::PopOut => "call-stage-pop-out-window",
76 })
231 })
77 .relative()
232 .relative()
78 .flex_1()
233 .flex_1()
@@ -80,16 +235,53 @@ pub fn render_stage(
80 .h_full()
235 .h_full()
81 .overflow_hidden()
236 .overflow_hidden()
82 .bg(stage_black())
237 .bg(stage_black())
83 .when(!fullscreen, |stage| stage.rounded(px(STAGE_RADIUS)))
238 .when(mode == StageMode::Docked, |stage| {
84 .cursor_pointer()
239 stage
240 .rounded(px(STAGE_RADIUS))
241 .debug_selector(|| "shell/islands/main/call-stage/share-content".into())
242 })
243 .map(|stage| {
244 if share_stage.view.is_zoomed() {
245 stage.cursor_grab()
246 } else {
247 stage.cursor_pointer()
248 }
249 })
250 .on_scroll_wheel(move |event, _, cx| {
251 if !event.modifiers.control {
252 return;
253 }
254 let scroll = f32::from(event.delta.pixel_delta(px(LINE_HEIGHT)).y);
255 wheel_app.update(cx, |state, cx| {
256 state.zoom_share_wheel(scroll, position(event.position), cx)
257 });
258 cx.stop_propagation();
259 })
260 .on_mouse_down(MouseButton::Left, move |event, _, cx| {
261 down_app.update(cx, |state, cx| state.begin_share_pan(position(event.position), cx));
262 })
263 .on_mouse_move(move |event, _, cx| {
264 if event.pressed_button == Some(MouseButton::Left) {
265 move_app.update(cx, |state, cx| state.pan_share_to(position(event.position), cx));
266 }
267 })
268 .on_mouse_up(MouseButton::Left, move |_, _, cx| {
269 up_app.update(cx, |state, cx| state.end_share_pan(cx));
270 })
271 .on_mouse_up_out(MouseButton::Left, move |_, _, cx| {
272 up_out_app.update(cx, |state, cx| state.end_share_pan(cx));
273 })
85 .on_click(move |event, _, cx| {
274 .on_click(move |event, _, cx| {
86 if event.click_count() >= 2 {
275 if mode != StageMode::PopOut && event.click_count() >= 2 {
87 toggle_app.update(cx, |state, cx| state.toggle_stage_fullscreen(cx));
276 toggle_app.update(cx, |state, cx| state.toggle_stage_fullscreen(cx));
88 }
277 }
89 })
278 })
90 .child(picture(image))
279 .child(measure(share_stage))
280 .child(picture(image, share_stage))
91 .child(label_chip(label))
281 .child(label_chip(label))
92 .when(fullscreen, |stage| {
282 .children(zoom_chip(app, share_stage))
283 .when(mode == StageMode::Docked, |stage| stage.child(pop_out_button(app)))
284 .when(mode == StageMode::Fullscreen, |stage| {
93 stage.child(
285 stage.child(
94 div()
286 div()
95 .absolute()
287 .absolute()
@@ -118,7 +310,7 @@ pub fn render_stage_overlay(app: &Entity<AppState>, state: &AppState) -> Option<
118 if !state.stage_fullscreen() {
310 if !state.stage_fullscreen() {
119 return None;
311 return None;
120 }
312 }
121 let stage = render_stage(app, state, true)?;
313 let stage = render_stage(app, state, StageMode::Fullscreen)?;
122 Some(
314 Some(
123 v_flex()
315 v_flex()
124 .id("call-stage-overlay")
316 .id("call-stage-overlay")
crates/app/src/views/call_view.rs +80 −12
@@ -27,7 +27,7 @@ use super::call_organizer::{
27 27 more_button, pin_chip, spotlight_chip, with_tile_menu,
28 28 };
29 29 use super::call_people::{lock_banner, lock_chip, options_dialog, people_button, people_panel};
30 use super::call_stage::render_stage;
30 use super::call_stage::{StageMode, popped_placeholder, render_stage};
31 31 use super::call_view_menu::view_button;
32 32 use super::conversation::ConversationView;
33 33 use super::shell::ISLAND_GAP;
@@ -51,11 +51,6 @@ const BLINK_DIMMED_OPACITY: f32 = 0.45;
51 51 pub(super) const DISABLED_OPACITY: f32 = 0.4;
52 52 pub(super) const TILE_GAP: f32 = 20.;
53 53 pub(super) const GRID_PADDING: f32 = 24.;
54 pub(super) const STRIP_TILE: TileSize = TileSize {
55 width: 232.,
56 height: 131.,
57 avatar: 56.,
58 };
59 54 pub(super) const STRIP_GAP: f32 = 12.;
60 55 pub(super) const STRIP_VISIBLE: f32 = 4.;
61 56 const TILE_RADIUS: f32 = 12.;
@@ -74,6 +69,9 @@ const REACTION_RISE: f32 = 24.;
74 69 const REACTION_FADE_FROM: f32 = 0.75;
75 70 const REACTION_CELL: f32 = 40.;
76 71 const SHARE_SOUND_LABEL: &str = "Include computer sound";
72 const SHARE_MOTION_LABEL: &str = "Optimize for motion";
73 const SHARE_STANDOUT_LABEL: &str = "Show me over my content";
74 const SHARE_STANDOUT_NEEDS_CAMERA: &str = "Turn your camera on first";
77 75 const NOISE_SUPPRESSION_LABEL: &str = "Noise suppression";
78 76 const MUSIC_MODE_LABEL: &str = "Music mode";
79 77 const PUSH_TO_TALK_HINT: &str = "Unmuted - release Ctrl+Space to mute";
@@ -408,6 +406,13 @@ pub fn leave_button(
408 406 })
409 407 }
410 408
409 fn share_stage_element(app: &Entity<AppState>, state: &AppState, call: &ActiveCall) -> Option<AnyElement> {
410 if call.share_stage.popped && call.model.screen_sharer.is_some() {
411 return Some(popped_placeholder(app));
412 }
413 render_stage(app, state, StageMode::Docked).or_else(|| whiteboard_stage(app, &call.model))
414 }
415
411 416 pub(super) fn camera_button(app: &Entity<AppState>, model: &CallModel) -> Stateful<Div> {
412 417 let (glyph, background, foreground) = if model.camera_on {
413 418 (IconName::Video, theme::accent(), theme::on_accent())
@@ -443,6 +448,50 @@ fn sound_switch_item(app: &Entity<AppState>, sound: bool) -> PopupMenuItem {
443 448 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.set_call_share_sound(!sound, cx)))
444 449 }
445 450
451 fn motion_switch_item(app: &Entity<AppState>, motion: bool) -> PopupMenuItem {
452 let app = app.clone();
453 PopupMenuItem::element(move |_, _| {
454 h_flex()
455 .id("call-share-motion-row")
456 .w_full()
457 .gap(px(16.))
458 .items_center()
459 .justify_between()
460 .child(SHARE_MOTION_LABEL)
461 .child(Switch::new("call-share-motion").checked(motion))
462 })
463 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.set_call_share_motion(!motion, cx)))
464 }
465
466 fn standout_switch_item(app: &Entity<AppState>, standout: bool, camera_on: bool) -> PopupMenuItem {
467 let app = app.clone();
468 PopupMenuItem::element(move |_, _| {
469 v_flex()
470 .id("call-share-standout-row")
471 .w_full()
472 .when(!camera_on, |row| row.opacity(DISABLED_OPACITY))
473 .child(
474 h_flex()
475 .w_full()
476 .gap(px(16.))
477 .items_center()
478 .justify_between()
479 .child(SHARE_STANDOUT_LABEL)
480 .child(Switch::new("call-share-standout").checked(standout && camera_on)),
481 )
482 .when(!camera_on, |row| {
483 row.child(
484 div()
485 .text_size(px(11.))
486 .text_color(theme::text_muted())
487 .child(SHARE_STANDOUT_NEEDS_CAMERA),
488 )
489 })
490 })
491 .disabled(!camera_on)
492 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.set_call_share_standout(!standout, cx)))
493 }
494
446 495 fn music_mode_item(app: &Entity<AppState>, mic: MicSettings) -> PopupMenuItem {
447 496 let app = app.clone();
448 497 PopupMenuItem::element(move |_, _| {
@@ -491,17 +540,36 @@ fn push_to_talk_chip(call: &ActiveCall) -> Option<AnyElement> {
491 540 })
492 541 }
493 542
543 #[derive(Debug, Clone, Copy)]
544 pub(super) struct ShareOptions {
545 pub sound: bool,
546 pub motion: bool,
547 pub standout: bool,
548 }
549
550 impl ShareOptions {
551 pub(super) fn of(state: &AppState) -> Self {
552 ShareOptions {
553 sound: state.call_share_sound,
554 motion: state.call_share_motion,
555 standout: state.call_share_standout,
556 }
557 }
558 }
559
494 560 fn share_items(
495 561 popup: PopupMenu,
496 562 app: &Entity<AppState>,
497 563 model: &CallModel,
498 sound: bool,
564 options: ShareOptions,
499 565 ) -> PopupMenu {
500 566 let screens = model.screens();
501 567 let single_screen = screens.len() == 1;
502 568 let mut popup = popup
503 569 .min_w(px(MENU_WIDTH))
504 .item(sound_switch_item(app, sound))
570 .item(sound_switch_item(app, options.sound))
571 .item(motion_switch_item(app, options.motion))
572 .item(standout_switch_item(app, options.standout, model.camera_on))
505 573 .separator();
506 574 for (index, source) in screens.into_iter().enumerate() {
507 575 let label = if single_screen {
@@ -540,7 +608,7 @@ fn share_items(
540 608 fn share_button(
541 609 app: &Entity<AppState>,
542 610 model: &CallModel,
543 sound: bool,
611 options: ShareOptions,
544 612 menu_open: bool,
545 613 ) -> AnyElement {
546 614 if model.local_share.is_some() {
@@ -581,7 +649,7 @@ fn share_button(
581 649 .rounded_full()
582 650 .child(face)
583 651 .dropdown_menu_with_anchor(Anchor::BottomLeft, move |popup, _, _| {
584 share_items(popup, &app, &model, sound)
652 share_items(popup, &app, &model, options)
585 653 })
586 654 .open(menu_open)
587 655 .on_open_change(move |open, _, cx| {
@@ -1081,7 +1149,7 @@ pub fn render_call_view(
1081 1149 .children(return_button(app, model));
1082 1150
1083 1151 let hold = hold_panel(app, model);
1084 let share_stage = render_stage(app, state, false).or_else(|| whiteboard_stage(app, model));
1152 let share_stage = share_stage_element(app, state, call);
1085 1153 let region = stage_region(app, state, call, now, hold, share_stage);
1086 1154
1087 1155 let controls = h_flex()
@@ -1112,7 +1180,7 @@ pub fn render_call_view(
1112 1180 .child(share_button(
1113 1181 app,
1114 1182 model,
1115 state.call_share_sound,
1183 ShareOptions::of(state),
1116 1184 call.share_menu_open,
1117 1185 ))
1118 1186 .when(model.has_reaction_controls(), |row| {
@@ -27,7 +27,7 @@ use super::call_organizer::{
27 more_button, pin_chip, spotlight_chip, with_tile_menu,
27 more_button, pin_chip, spotlight_chip, with_tile_menu,
28};
28};
29use super::call_people::{lock_banner, lock_chip, options_dialog, people_button, people_panel};
29use super::call_people::{lock_banner, lock_chip, options_dialog, people_button, people_panel};
30use super::call_stage::render_stage;
30use super::call_stage::{StageMode, popped_placeholder, render_stage};
31use super::call_view_menu::view_button;
31use super::call_view_menu::view_button;
32use super::conversation::ConversationView;
32use super::conversation::ConversationView;
33use super::shell::ISLAND_GAP;
33use super::shell::ISLAND_GAP;
@@ -51,11 +51,6 @@ const BLINK_DIMMED_OPACITY: f32 = 0.45;
51pub(super) const DISABLED_OPACITY: f32 = 0.4;
51pub(super) const DISABLED_OPACITY: f32 = 0.4;
52pub(super) const TILE_GAP: f32 = 20.;
52pub(super) const TILE_GAP: f32 = 20.;
53pub(super) const GRID_PADDING: f32 = 24.;
53pub(super) const GRID_PADDING: f32 = 24.;
54pub(super) const STRIP_TILE: TileSize = TileSize {
55 width: 232.,
56 height: 131.,
57 avatar: 56.,
58};
59pub(super) const STRIP_GAP: f32 = 12.;
54pub(super) const STRIP_GAP: f32 = 12.;
60pub(super) const STRIP_VISIBLE: f32 = 4.;
55pub(super) const STRIP_VISIBLE: f32 = 4.;
61const TILE_RADIUS: f32 = 12.;
56const TILE_RADIUS: f32 = 12.;
@@ -74,6 +69,9 @@ const REACTION_RISE: f32 = 24.;
74const REACTION_FADE_FROM: f32 = 0.75;
69const REACTION_FADE_FROM: f32 = 0.75;
75const REACTION_CELL: f32 = 40.;
70const REACTION_CELL: f32 = 40.;
76const SHARE_SOUND_LABEL: &str = "Include computer sound";
71const SHARE_SOUND_LABEL: &str = "Include computer sound";
72const SHARE_MOTION_LABEL: &str = "Optimize for motion";
73const SHARE_STANDOUT_LABEL: &str = "Show me over my content";
74const SHARE_STANDOUT_NEEDS_CAMERA: &str = "Turn your camera on first";
77const NOISE_SUPPRESSION_LABEL: &str = "Noise suppression";
75const NOISE_SUPPRESSION_LABEL: &str = "Noise suppression";
78const MUSIC_MODE_LABEL: &str = "Music mode";
76const MUSIC_MODE_LABEL: &str = "Music mode";
79const PUSH_TO_TALK_HINT: &str = "Unmuted - release Ctrl+Space to mute";
77const PUSH_TO_TALK_HINT: &str = "Unmuted - release Ctrl+Space to mute";
@@ -408,6 +406,13 @@ pub fn leave_button(
408 })
406 })
409}
407}
410
408
409fn share_stage_element(app: &Entity<AppState>, state: &AppState, call: &ActiveCall) -> Option<AnyElement> {
410 if call.share_stage.popped && call.model.screen_sharer.is_some() {
411 return Some(popped_placeholder(app));
412 }
413 render_stage(app, state, StageMode::Docked).or_else(|| whiteboard_stage(app, &call.model))
414}
415
411pub(super) fn camera_button(app: &Entity<AppState>, model: &CallModel) -> Stateful<Div> {
416pub(super) fn camera_button(app: &Entity<AppState>, model: &CallModel) -> Stateful<Div> {
412 let (glyph, background, foreground) = if model.camera_on {
417 let (glyph, background, foreground) = if model.camera_on {
413 (IconName::Video, theme::accent(), theme::on_accent())
418 (IconName::Video, theme::accent(), theme::on_accent())
@@ -443,6 +448,50 @@ fn sound_switch_item(app: &Entity<AppState>, sound: bool) -> PopupMenuItem {
443 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.set_call_share_sound(!sound, cx)))
448 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.set_call_share_sound(!sound, cx)))
444}
449}
445
450
451fn motion_switch_item(app: &Entity<AppState>, motion: bool) -> PopupMenuItem {
452 let app = app.clone();
453 PopupMenuItem::element(move |_, _| {
454 h_flex()
455 .id("call-share-motion-row")
456 .w_full()
457 .gap(px(16.))
458 .items_center()
459 .justify_between()
460 .child(SHARE_MOTION_LABEL)
461 .child(Switch::new("call-share-motion").checked(motion))
462 })
463 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.set_call_share_motion(!motion, cx)))
464}
465
466fn standout_switch_item(app: &Entity<AppState>, standout: bool, camera_on: bool) -> PopupMenuItem {
467 let app = app.clone();
468 PopupMenuItem::element(move |_, _| {
469 v_flex()
470 .id("call-share-standout-row")
471 .w_full()
472 .when(!camera_on, |row| row.opacity(DISABLED_OPACITY))
473 .child(
474 h_flex()
475 .w_full()
476 .gap(px(16.))
477 .items_center()
478 .justify_between()
479 .child(SHARE_STANDOUT_LABEL)
480 .child(Switch::new("call-share-standout").checked(standout && camera_on)),
481 )
482 .when(!camera_on, |row| {
483 row.child(
484 div()
485 .text_size(px(11.))
486 .text_color(theme::text_muted())
487 .child(SHARE_STANDOUT_NEEDS_CAMERA),
488 )
489 })
490 })
491 .disabled(!camera_on)
492 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.set_call_share_standout(!standout, cx)))
493}
494
446fn music_mode_item(app: &Entity<AppState>, mic: MicSettings) -> PopupMenuItem {
495fn music_mode_item(app: &Entity<AppState>, mic: MicSettings) -> PopupMenuItem {
447 let app = app.clone();
496 let app = app.clone();
448 PopupMenuItem::element(move |_, _| {
497 PopupMenuItem::element(move |_, _| {
@@ -491,17 +540,36 @@ fn push_to_talk_chip(call: &ActiveCall) -> Option<AnyElement> {
491 })
540 })
492}
541}
493
542
543#[derive(Debug, Clone, Copy)]
544pub(super) struct ShareOptions {
545 pub sound: bool,
546 pub motion: bool,
547 pub standout: bool,
548}
549
550impl ShareOptions {
551 pub(super) fn of(state: &AppState) -> Self {
552 ShareOptions {
553 sound: state.call_share_sound,
554 motion: state.call_share_motion,
555 standout: state.call_share_standout,
556 }
557 }
558}
559
494fn share_items(
560fn share_items(
495 popup: PopupMenu,
561 popup: PopupMenu,
496 app: &Entity<AppState>,
562 app: &Entity<AppState>,
497 model: &CallModel,
563 model: &CallModel,
498 sound: bool,
564 options: ShareOptions,
499) -> PopupMenu {
565) -> PopupMenu {
500 let screens = model.screens();
566 let screens = model.screens();
501 let single_screen = screens.len() == 1;
567 let single_screen = screens.len() == 1;
502 let mut popup = popup
568 let mut popup = popup
503 .min_w(px(MENU_WIDTH))
569 .min_w(px(MENU_WIDTH))
504 .item(sound_switch_item(app, sound))
570 .item(sound_switch_item(app, options.sound))
571 .item(motion_switch_item(app, options.motion))
572 .item(standout_switch_item(app, options.standout, model.camera_on))
505 .separator();
573 .separator();
506 for (index, source) in screens.into_iter().enumerate() {
574 for (index, source) in screens.into_iter().enumerate() {
507 let label = if single_screen {
575 let label = if single_screen {
@@ -540,7 +608,7 @@ fn share_items(
540fn share_button(
608fn share_button(
541 app: &Entity<AppState>,
609 app: &Entity<AppState>,
542 model: &CallModel,
610 model: &CallModel,
543 sound: bool,
611 options: ShareOptions,
544 menu_open: bool,
612 menu_open: bool,
545) -> AnyElement {
613) -> AnyElement {
546 if model.local_share.is_some() {
614 if model.local_share.is_some() {
@@ -581,7 +649,7 @@ fn share_button(
581 .rounded_full()
649 .rounded_full()
582 .child(face)
650 .child(face)
583 .dropdown_menu_with_anchor(Anchor::BottomLeft, move |popup, _, _| {
651 .dropdown_menu_with_anchor(Anchor::BottomLeft, move |popup, _, _| {
584 share_items(popup, &app, &model, sound)
652 share_items(popup, &app, &model, options)
585 })
653 })
586 .open(menu_open)
654 .open(menu_open)
587 .on_open_change(move |open, _, cx| {
655 .on_open_change(move |open, _, cx| {
@@ -1081,7 +1149,7 @@ pub fn render_call_view(
1081 .children(return_button(app, model));
1149 .children(return_button(app, model));
1082
1150
1083 let hold = hold_panel(app, model);
1151 let hold = hold_panel(app, model);
1084 let share_stage = render_stage(app, state, false).or_else(|| whiteboard_stage(app, model));
1152 let share_stage = share_stage_element(app, state, call);
1085 let region = stage_region(app, state, call, now, hold, share_stage);
1153 let region = stage_region(app, state, call, now, hold, share_stage);
1086
1154
1087 let controls = h_flex()
1155 let controls = h_flex()
@@ -1112,7 +1180,7 @@ pub fn render_call_view(
1112 .child(share_button(
1180 .child(share_button(
1113 app,
1181 app,
1114 model,
1182 model,
1115 state.call_share_sound,
1183 ShareOptions::of(state),
1116 call.share_menu_open,
1184 call.share_menu_open,
1117 ))
1185 ))
1118 .when(model.has_reaction_controls(), |row| {
1186 .when(model.has_reaction_controls(), |row| {
crates/app/src/views/mod.rs +1 −0
@@ -11,6 +11,7 @@ pub mod call_mini;
11 11 pub mod call_mini_window;
12 12 pub mod call_organizer;
13 13 pub mod call_people;
14 pub mod call_pop_out;
14 15 pub mod call_record;
15 16 pub mod call_stage;
16 17 pub mod call_transcript;
@@ -11,6 +11,7 @@ pub mod call_mini;
11pub mod call_mini_window;
11pub mod call_mini_window;
12pub mod call_organizer;
12pub mod call_organizer;
13pub mod call_people;
13pub mod call_people;
14pub mod call_pop_out;
14pub mod call_record;
15pub mod call_record;
15pub mod call_stage;
16pub mod call_stage;
16pub mod call_transcript;
17pub mod call_transcript;
crates/app/src/views/shell.rs +6 −2
@@ -19,8 +19,9 @@ use super::shortcuts::{
19 19 AcceptCall, DeclineCall, HangUpCall, JoinMeetingFromToast, NextConversation, OpenActivity,
20 20 OpenCallsTab, OpenChannelsTab, OpenChatsTab, OpenLobbyList, OpenSaved, PreviousConversation, PushToTalk,
21 21 Scope, ShowShortcuts, StartAudioCall, StartVideoCall, ToggleCallCamera, ToggleCallFullscreen,
22 ToggleCallHand, ToggleCallShare,
22 ToggleCallHand, ToggleCallShare, ZoomShareIn, ZoomShareOut, ZoomShareReset,
23 23 };
24 use super::call_pop_out::zoom_listener;
24 25 use super::shortcuts_dialog::{ShortcutsDialog, ShortcutsDialogEvent};
25 26 use super::sidebar::{SIDEBAR_WIDTH, SidebarView};
26 27 use super::status_bar::render_status_bar;
@@ -31,7 +32,7 @@ use super::title_bar::render_title_bar;
31 32 use crate::activity::ActivityCenter;
32 33 use crate::agents::{AgentRunsEvent, StartDialog, StartDialogEvent, StartRequest};
33 34 use crate::app_state::{AppEvent, AppState, Selection};
34 use crate::call::{CallMedia, CallWindows};
35 use crate::call::{CallMedia, CallWindows, ZoomStep};
35 36 use crate::notice::NoticeAction;
36 37 use crate::notify::{NotificationCenter, selection_for};
37 38 use crate::sidebar_model::Step;
@@ -875,6 +876,9 @@ impl Render for AppShell {
875 876 this.state
876 877 .update(cx, |state, cx| state.toggle_call_fullscreen(cx));
877 878 }))
879 .on_action(zoom_listener::<ZoomShareIn>(&self.state, ZoomStep::In))
880 .on_action(zoom_listener::<ZoomShareOut>(&self.state, ZoomStep::Out))
881 .on_action(zoom_listener::<ZoomShareReset>(&self.state, ZoomStep::Reset))
878 882 .on_action(cx.listener(|this, _: &ReplyToHovered, window, cx| {
879 883 this.close_image_viewer(window, cx);
880 884 this.conversation.update(cx, |conversation, cx| {
@@ -19,8 +19,9 @@ use super::shortcuts::{
19 AcceptCall, DeclineCall, HangUpCall, JoinMeetingFromToast, NextConversation, OpenActivity,
19 AcceptCall, DeclineCall, HangUpCall, JoinMeetingFromToast, NextConversation, OpenActivity,
20 OpenCallsTab, OpenChannelsTab, OpenChatsTab, OpenLobbyList, OpenSaved, PreviousConversation, PushToTalk,
20 OpenCallsTab, OpenChannelsTab, OpenChatsTab, OpenLobbyList, OpenSaved, PreviousConversation, PushToTalk,
21 Scope, ShowShortcuts, StartAudioCall, StartVideoCall, ToggleCallCamera, ToggleCallFullscreen,
21 Scope, ShowShortcuts, StartAudioCall, StartVideoCall, ToggleCallCamera, ToggleCallFullscreen,
22 ToggleCallHand, ToggleCallShare,
22 ToggleCallHand, ToggleCallShare, ZoomShareIn, ZoomShareOut, ZoomShareReset,
23};
23};
24use super::call_pop_out::zoom_listener;
24use super::shortcuts_dialog::{ShortcutsDialog, ShortcutsDialogEvent};
25use super::shortcuts_dialog::{ShortcutsDialog, ShortcutsDialogEvent};
25use super::sidebar::{SIDEBAR_WIDTH, SidebarView};
26use super::sidebar::{SIDEBAR_WIDTH, SidebarView};
26use super::status_bar::render_status_bar;
27use super::status_bar::render_status_bar;
@@ -31,7 +32,7 @@ use super::title_bar::render_title_bar;
31use crate::activity::ActivityCenter;
32use crate::activity::ActivityCenter;
32use crate::agents::{AgentRunsEvent, StartDialog, StartDialogEvent, StartRequest};
33use crate::agents::{AgentRunsEvent, StartDialog, StartDialogEvent, StartRequest};
33use crate::app_state::{AppEvent, AppState, Selection};
34use crate::app_state::{AppEvent, AppState, Selection};
34use crate::call::{CallMedia, CallWindows};
35use crate::call::{CallMedia, CallWindows, ZoomStep};
35use crate::notice::NoticeAction;
36use crate::notice::NoticeAction;
36use crate::notify::{NotificationCenter, selection_for};
37use crate::notify::{NotificationCenter, selection_for};
37use crate::sidebar_model::Step;
38use crate::sidebar_model::Step;
@@ -875,6 +876,9 @@ impl Render for AppShell {
875 this.state
876 this.state
876 .update(cx, |state, cx| state.toggle_call_fullscreen(cx));
877 .update(cx, |state, cx| state.toggle_call_fullscreen(cx));
877 }))
878 }))
879 .on_action(zoom_listener::<ZoomShareIn>(&self.state, ZoomStep::In))
880 .on_action(zoom_listener::<ZoomShareOut>(&self.state, ZoomStep::Out))
881 .on_action(zoom_listener::<ZoomShareReset>(&self.state, ZoomStep::Reset))
878 .on_action(cx.listener(|this, _: &ReplyToHovered, window, cx| {
882 .on_action(cx.listener(|this, _: &ReplyToHovered, window, cx| {
879 this.close_image_viewer(window, cx);
883 this.close_image_viewer(window, cx);
880 this.conversation.update(cx, |conversation, cx| {
884 this.conversation.update(cx, |conversation, cx| {
crates/app/src/views/shortcuts.rs +21 −1
@@ -10,6 +10,7 @@ use super::shell::{NewChat, OpenSwitcher, ToggleCallMute};
10 10 const TEXT_FIELD_CONTEXT: &str = "Input";
11 11 const OUTSIDE_COMPOSER_CONTEXT: &str = "!Composer";
12 12 const OUTSIDE_TEXT_FIELD_CONTEXT: &str = "!Input";
13 const ALTERNATE_KEYS: &[(&str, &str)] = &[("alt-shift-=", "alt-shift-+")];
13 14
14 15 actions!(
15 16 teams,
@@ -33,6 +34,9 @@ actions!(
33 34 StartVideoCall,
34 35 ToggleCallFullscreen,
35 36 PushToTalk,
37 ZoomShareIn,
38 ZoomShareOut,
39 ZoomShareReset,
36 40 ShowShortcuts
37 41 ]
38 42 );
@@ -128,6 +132,9 @@ pub const SHORTCUTS: &[Shortcut] = &[
128 132 shortcut!(Calls, GlobalOverTextFields, "Start an audio call in this chat", "alt-shift-a", None, StartAudioCall),
129 133 shortcut!(Calls, GlobalOverTextFields, "Start a video call in this chat", "alt-shift-v", None, StartVideoCall),
130 134 shortcut!(Calls, GlobalOverTextFields, "Full screen", "f11", None, ToggleCallFullscreen),
135 shortcut!(Calls, GlobalOverTextFields, "Zoom in on shared content", "alt-shift-=", None, ZoomShareIn),
136 shortcut!(Calls, GlobalOverTextFields, "Zoom out on shared content", "alt-shift--", None, ZoomShareOut),
137 shortcut!(Calls, GlobalOverTextFields, "Reset zoom on shared content", "alt-shift-0", None, ZoomShareReset),
131 138 shortcut!(Calls, OutsideTextFields, "Hold to talk while muted", "ctrl-space", None, PushToTalk),
132 139 ];
133 140
@@ -152,6 +159,7 @@ impl Shortcut {
152 159 Scope::Composer => &[Some(COMPOSER_CONTEXT)],
153 160 };
154 161 let mut keys = vec![self.keys];
162 keys.extend(ALTERNATE_KEYS.iter().filter(|(primary, _)| *primary == self.keys).map(|(_, alternate)| *alternate));
155 163 keys.extend(self.mac_keys.filter(|_| cfg!(target_os = "macos")));
156 164 keys.iter()
157 165 .flat_map(|keys| contexts.iter().map(|context| (self.bind)(keys, *context)))
@@ -167,7 +175,14 @@ pub fn keys_for_label(label: &str) -> Option<String> {
167 175 }
168 176
169 177 pub fn display_keys(keys: &str) -> String {
170 keys.split('-')
178 let (modifiers, key) = match keys.strip_suffix("--") {
179 Some(modifiers) => (modifiers, "-"),
180 None => keys.rsplit_once('-').unwrap_or(("", keys)),
181 };
182 modifiers
183 .split('-')
184 .filter(|part| !part.is_empty())
185 .chain([key])
171 186 .map(|part| match part {
172 187 "ctrl" => "Ctrl".to_owned(),
173 188 "cmd" => "Cmd".to_owned(),
@@ -177,6 +192,8 @@ pub fn display_keys(keys: &str) -> String {
177 192 "down" => "Down".to_owned(),
178 193 "enter" => "Enter".to_owned(),
179 194 "space" => "Space".to_owned(),
195 "=" => "Plus".to_owned(),
196 "-" => "Minus".to_owned(),
180 197 other => other.to_uppercase(),
181 198 })
182 199 .collect::<Vec<_>>()
@@ -319,5 +336,8 @@ mod tests {
319 336 assert_eq!(display_keys("alt-up"), "Alt+Up");
320 337 assert_eq!(display_keys("ctrl-."), "Ctrl+.");
321 338 assert_eq!(display_keys("ctrl-space"), "Ctrl+Space");
339 assert_eq!(display_keys("alt-shift-="), "Alt+Shift+Plus");
340 assert_eq!(display_keys("alt-shift--"), "Alt+Shift+Minus");
341 assert_eq!(display_keys("alt-shift-0"), "Alt+Shift+0");
322 342 }
323 343 }
@@ -10,6 +10,7 @@ use super::shell::{NewChat, OpenSwitcher, ToggleCallMute};
10const TEXT_FIELD_CONTEXT: &str = "Input";
10const TEXT_FIELD_CONTEXT: &str = "Input";
11const OUTSIDE_COMPOSER_CONTEXT: &str = "!Composer";
11const OUTSIDE_COMPOSER_CONTEXT: &str = "!Composer";
12const OUTSIDE_TEXT_FIELD_CONTEXT: &str = "!Input";
12const OUTSIDE_TEXT_FIELD_CONTEXT: &str = "!Input";
13const ALTERNATE_KEYS: &[(&str, &str)] = &[("alt-shift-=", "alt-shift-+")];
13
14
14actions!(
15actions!(
15 teams,
16 teams,
@@ -33,6 +34,9 @@ actions!(
33 StartVideoCall,
34 StartVideoCall,
34 ToggleCallFullscreen,
35 ToggleCallFullscreen,
35 PushToTalk,
36 PushToTalk,
37 ZoomShareIn,
38 ZoomShareOut,
39 ZoomShareReset,
36 ShowShortcuts
40 ShowShortcuts
37 ]
41 ]
38);
42);
@@ -128,6 +132,9 @@ pub const SHORTCUTS: &[Shortcut] = &[
128 shortcut!(Calls, GlobalOverTextFields, "Start an audio call in this chat", "alt-shift-a", None, StartAudioCall),
132 shortcut!(Calls, GlobalOverTextFields, "Start an audio call in this chat", "alt-shift-a", None, StartAudioCall),
129 shortcut!(Calls, GlobalOverTextFields, "Start a video call in this chat", "alt-shift-v", None, StartVideoCall),
133 shortcut!(Calls, GlobalOverTextFields, "Start a video call in this chat", "alt-shift-v", None, StartVideoCall),
130 shortcut!(Calls, GlobalOverTextFields, "Full screen", "f11", None, ToggleCallFullscreen),
134 shortcut!(Calls, GlobalOverTextFields, "Full screen", "f11", None, ToggleCallFullscreen),
135 shortcut!(Calls, GlobalOverTextFields, "Zoom in on shared content", "alt-shift-=", None, ZoomShareIn),
136 shortcut!(Calls, GlobalOverTextFields, "Zoom out on shared content", "alt-shift--", None, ZoomShareOut),
137 shortcut!(Calls, GlobalOverTextFields, "Reset zoom on shared content", "alt-shift-0", None, ZoomShareReset),
131 shortcut!(Calls, OutsideTextFields, "Hold to talk while muted", "ctrl-space", None, PushToTalk),
138 shortcut!(Calls, OutsideTextFields, "Hold to talk while muted", "ctrl-space", None, PushToTalk),
132];
139];
133
140
@@ -152,6 +159,7 @@ impl Shortcut {
152 Scope::Composer => &[Some(COMPOSER_CONTEXT)],
159 Scope::Composer => &[Some(COMPOSER_CONTEXT)],
153 };
160 };
154 let mut keys = vec![self.keys];
161 let mut keys = vec![self.keys];
162 keys.extend(ALTERNATE_KEYS.iter().filter(|(primary, _)| *primary == self.keys).map(|(_, alternate)| *alternate));
155 keys.extend(self.mac_keys.filter(|_| cfg!(target_os = "macos")));
163 keys.extend(self.mac_keys.filter(|_| cfg!(target_os = "macos")));
156 keys.iter()
164 keys.iter()
157 .flat_map(|keys| contexts.iter().map(|context| (self.bind)(keys, *context)))
165 .flat_map(|keys| contexts.iter().map(|context| (self.bind)(keys, *context)))
@@ -167,7 +175,14 @@ pub fn keys_for_label(label: &str) -> Option<String> {
167}
175}
168
176
169pub fn display_keys(keys: &str) -> String {
177pub fn display_keys(keys: &str) -> String {
170 keys.split('-')
178 let (modifiers, key) = match keys.strip_suffix("--") {
179 Some(modifiers) => (modifiers, "-"),
180 None => keys.rsplit_once('-').unwrap_or(("", keys)),
181 };
182 modifiers
183 .split('-')
184 .filter(|part| !part.is_empty())
185 .chain([key])
171 .map(|part| match part {
186 .map(|part| match part {
172 "ctrl" => "Ctrl".to_owned(),
187 "ctrl" => "Ctrl".to_owned(),
173 "cmd" => "Cmd".to_owned(),
188 "cmd" => "Cmd".to_owned(),
@@ -177,6 +192,8 @@ pub fn display_keys(keys: &str) -> String {
177 "down" => "Down".to_owned(),
192 "down" => "Down".to_owned(),
178 "enter" => "Enter".to_owned(),
193 "enter" => "Enter".to_owned(),
179 "space" => "Space".to_owned(),
194 "space" => "Space".to_owned(),
195 "=" => "Plus".to_owned(),
196 "-" => "Minus".to_owned(),
180 other => other.to_uppercase(),
197 other => other.to_uppercase(),
181 })
198 })
182 .collect::<Vec<_>>()
199 .collect::<Vec<_>>()
@@ -319,5 +336,8 @@ mod tests {
319 assert_eq!(display_keys("alt-up"), "Alt+Up");
336 assert_eq!(display_keys("alt-up"), "Alt+Up");
320 assert_eq!(display_keys("ctrl-."), "Ctrl+.");
337 assert_eq!(display_keys("ctrl-."), "Ctrl+.");
321 assert_eq!(display_keys("ctrl-space"), "Ctrl+Space");
338 assert_eq!(display_keys("ctrl-space"), "Ctrl+Space");
339 assert_eq!(display_keys("alt-shift-="), "Alt+Shift+Plus");
340 assert_eq!(display_keys("alt-shift--"), "Alt+Shift+Minus");
341 assert_eq!(display_keys("alt-shift-0"), "Alt+Shift+0");
322 }
342 }
323}
343}
crates/calling/src/blur.rs +24 −2
@@ -8,6 +8,7 @@ use tract_onnx::prelude::*;
8 8 use crate::background::BackgroundPicture;
9 9 use crate::effects::CameraEffects;
10 10 use crate::error::{Error, Result};
11 use crate::standout::Cutout;
11 12
12 13 const MODEL: &[u8] = include_bytes!("../assets/selfie_segmentation_landscape.onnx");
13 14 pub const MASK_WIDTH: usize = 256;
@@ -76,7 +77,7 @@ fn model_input(rgba: &[u8], width: usize, height: usize) -> Tensor {
76 77 Tensor::from_shape(&[1, 3, MASK_HEIGHT, MASK_WIDTH], &data).expect("shape matches data")
77 78 }
78 79
79 fn smoothstep(value: f32) -> f32 {
80 pub(crate) fn smoothstep(value: f32) -> f32 {
80 81 let t = ((value - EDGE_LOW) / (EDGE_HIGH - EDGE_LOW)).clamp(0., 1.);
81 82 t * t * (3. - 2. * t)
82 83 }
@@ -229,9 +230,11 @@ pub fn compose_image(rgba: &mut [u8], width: usize, height: usize, mask: &[f32],
229 230 #[derive(Default)]
230 231 pub struct BlurSettings {
231 232 enabled: AtomicBool,
233 standout: AtomicBool,
232 234 average_micros: AtomicU32,
233 235 picture: Mutex<Option<Arc<BackgroundPicture>>>,
234 236 effects: Mutex<CameraEffects>,
237 cutout: Mutex<Option<Arc<Cutout>>>,
235 238 }
236 239
237 240 impl BlurSettings {
@@ -243,6 +246,25 @@ impl BlurSettings {
243 246 self.enabled.load(Ordering::Relaxed)
244 247 }
245 248
249 pub fn set_standout(&self, standout: bool) {
250 self.standout.store(standout, Ordering::Relaxed);
251 if !standout {
252 self.set_cutout(None);
253 }
254 }
255
256 pub fn standout(&self) -> bool {
257 self.standout.load(Ordering::Relaxed)
258 }
259
260 pub fn set_cutout(&self, cutout: Option<Arc<Cutout>>) {
261 *self.cutout.lock().expect("cutout lock") = cutout;
262 }
263
264 pub fn cutout(&self) -> Option<Arc<Cutout>> {
265 self.cutout.lock().expect("cutout lock").clone()
266 }
267
246 268 pub fn set_picture(&self, picture: Option<Arc<BackgroundPicture>>) {
247 269 *self.picture.lock().expect("picture lock") = picture;
248 270 }
@@ -260,7 +282,7 @@ impl BlurSettings {
260 282 }
261 283
262 284 pub fn active(&self) -> bool {
263 self.enabled() || self.effects().alters_frame()
285 self.enabled() || self.standout() || self.effects().alters_frame()
264 286 }
265 287
266 288 pub fn average_ms(&self) -> f32 {
@@ -8,6 +8,7 @@ use tract_onnx::prelude::*;
8use crate::background::BackgroundPicture;
8use crate::background::BackgroundPicture;
9use crate::effects::CameraEffects;
9use crate::effects::CameraEffects;
10use crate::error::{Error, Result};
10use crate::error::{Error, Result};
11use crate::standout::Cutout;
11
12
12const MODEL: &[u8] = include_bytes!("../assets/selfie_segmentation_landscape.onnx");
13const MODEL: &[u8] = include_bytes!("../assets/selfie_segmentation_landscape.onnx");
13pub const MASK_WIDTH: usize = 256;
14pub const MASK_WIDTH: usize = 256;
@@ -76,7 +77,7 @@ fn model_input(rgba: &[u8], width: usize, height: usize) -> Tensor {
76 Tensor::from_shape(&[1, 3, MASK_HEIGHT, MASK_WIDTH], &data).expect("shape matches data")
77 Tensor::from_shape(&[1, 3, MASK_HEIGHT, MASK_WIDTH], &data).expect("shape matches data")
77}
78}
78
79
79fn smoothstep(value: f32) -> f32 {
80pub(crate) fn smoothstep(value: f32) -> f32 {
80 let t = ((value - EDGE_LOW) / (EDGE_HIGH - EDGE_LOW)).clamp(0., 1.);
81 let t = ((value - EDGE_LOW) / (EDGE_HIGH - EDGE_LOW)).clamp(0., 1.);
81 t * t * (3. - 2. * t)
82 t * t * (3. - 2. * t)
82}
83}
@@ -229,9 +230,11 @@ pub fn compose_image(rgba: &mut [u8], width: usize, height: usize, mask: &[f32],
229#[derive(Default)]
230#[derive(Default)]
230pub struct BlurSettings {
231pub struct BlurSettings {
231 enabled: AtomicBool,
232 enabled: AtomicBool,
233 standout: AtomicBool,
232 average_micros: AtomicU32,
234 average_micros: AtomicU32,
233 picture: Mutex<Option<Arc<BackgroundPicture>>>,
235 picture: Mutex<Option<Arc<BackgroundPicture>>>,
234 effects: Mutex<CameraEffects>,
236 effects: Mutex<CameraEffects>,
237 cutout: Mutex<Option<Arc<Cutout>>>,
235}
238}
236
239
237impl BlurSettings {
240impl BlurSettings {
@@ -243,6 +246,25 @@ impl BlurSettings {
243 self.enabled.load(Ordering::Relaxed)
246 self.enabled.load(Ordering::Relaxed)
244 }
247 }
245
248
249 pub fn set_standout(&self, standout: bool) {
250 self.standout.store(standout, Ordering::Relaxed);
251 if !standout {
252 self.set_cutout(None);
253 }
254 }
255
256 pub fn standout(&self) -> bool {
257 self.standout.load(Ordering::Relaxed)
258 }
259
260 pub fn set_cutout(&self, cutout: Option<Arc<Cutout>>) {
261 *self.cutout.lock().expect("cutout lock") = cutout;
262 }
263
264 pub fn cutout(&self) -> Option<Arc<Cutout>> {
265 self.cutout.lock().expect("cutout lock").clone()
266 }
267
246 pub fn set_picture(&self, picture: Option<Arc<BackgroundPicture>>) {
268 pub fn set_picture(&self, picture: Option<Arc<BackgroundPicture>>) {
247 *self.picture.lock().expect("picture lock") = picture;
269 *self.picture.lock().expect("picture lock") = picture;
248 }
270 }
@@ -260,7 +282,7 @@ impl BlurSettings {
260 }
282 }
261
283
262 pub fn active(&self) -> bool {
284 pub fn active(&self) -> bool {
263 self.enabled() || self.effects().alters_frame()
285 self.enabled() || self.standout() || self.effects().alters_frame()
264 }
286 }
265
287
266 pub fn average_ms(&self) -> f32 {
288 pub fn average_ms(&self) -> f32 {
crates/calling/src/call.rs +7 −0
@@ -1646,6 +1646,13 @@ async fn drive(
1646 1646 send_receive_change(control, video.reselect(&roster));
1647 1647 control.send(CallUpdate::IncomingVideo(enabled));
1648 1648 }
1649 Some(CallCommand::SetVideoWants(wants)) => {
1650 if video.set_wants(wants) {
1651 send_receive_change(control, video.reselect(&roster));
1652 }
1653 }
1654 Some(CallCommand::SetShareMotion(on)) => local_video.set_motion(on),
1655 Some(CallCommand::SetShareStandout(on)) => local_video.set_standout(on),
1649 1656 Some(CallCommand::SetCameraEffects(effects)) => local_video.set_effects(effects),
1650 1657 Some(CallCommand::SendReaction(reaction)) => {
1651 1658 if let Err(error) = remote.signaling.send_reaction(&remote.conversation, &remote.participant, reaction).await {
@@ -1646,6 +1646,13 @@ async fn drive(
1646 send_receive_change(control, video.reselect(&roster));
1646 send_receive_change(control, video.reselect(&roster));
1647 control.send(CallUpdate::IncomingVideo(enabled));
1647 control.send(CallUpdate::IncomingVideo(enabled));
1648 }
1648 }
1649 Some(CallCommand::SetVideoWants(wants)) => {
1650 if video.set_wants(wants) {
1651 send_receive_change(control, video.reselect(&roster));
1652 }
1653 }
1654 Some(CallCommand::SetShareMotion(on)) => local_video.set_motion(on),
1655 Some(CallCommand::SetShareStandout(on)) => local_video.set_standout(on),
1649 Some(CallCommand::SetCameraEffects(effects)) => local_video.set_effects(effects),
1656 Some(CallCommand::SetCameraEffects(effects)) => local_video.set_effects(effects),
1650 Some(CallCommand::SendReaction(reaction)) => {
1657 Some(CallCommand::SendReaction(reaction)) => {
1651 if let Err(error) = remote.signaling.send_reaction(&remote.conversation, &remote.participant, reaction).await {
1658 if let Err(error) = remote.signaling.send_reaction(&remote.conversation, &remote.participant, reaction).await {
crates/calling/src/control.rs +4 −0
@@ -22,6 +22,7 @@ use crate::camera::CameraDevice;
22 22 use crate::screen::ShareSource;
23 23 use crate::signaling::{Callee, MeetingTarget};
24 24 use crate::state::CallState;
25 use crate::video_layout::VideoWant;
25 26 use crate::video_frame::VideoHub;
26 27 use crate::whiteboard::ContentShare;
27 28
@@ -38,6 +39,8 @@ pub enum CallCommand {
38 39 StartShare(ShareSource),
39 40 StopShare,
40 41 SetShareSound(bool),
42 SetShareMotion(bool),
43 SetShareStandout(bool),
41 44 RefreshShareSources,
42 45 SetHand(bool),
43 46 LowerHand { mri: String },
@@ -60,6 +63,7 @@ pub enum CallCommand {
60 63 SetCaptions(bool),
61 64 SetBackground(BackgroundChoice),
62 65 SetIncomingVideo(bool),
66 SetVideoWants(Vec<VideoWant>),
63 67 SetCameraEffects(CameraEffects),
64 68 SendReaction(Reaction),
65 69 StartRecording { kind: RecordingKind, title: String },
@@ -22,6 +22,7 @@ use crate::camera::CameraDevice;
22use crate::screen::ShareSource;
22use crate::screen::ShareSource;
23use crate::signaling::{Callee, MeetingTarget};
23use crate::signaling::{Callee, MeetingTarget};
24use crate::state::CallState;
24use crate::state::CallState;
25use crate::video_layout::VideoWant;
25use crate::video_frame::VideoHub;
26use crate::video_frame::VideoHub;
26use crate::whiteboard::ContentShare;
27use crate::whiteboard::ContentShare;
27
28
@@ -38,6 +39,8 @@ pub enum CallCommand {
38 StartShare(ShareSource),
39 StartShare(ShareSource),
39 StopShare,
40 StopShare,
40 SetShareSound(bool),
41 SetShareSound(bool),
42 SetShareMotion(bool),
43 SetShareStandout(bool),
41 RefreshShareSources,
44 RefreshShareSources,
42 SetHand(bool),
45 SetHand(bool),
43 LowerHand { mri: String },
46 LowerHand { mri: String },
@@ -60,6 +63,7 @@ pub enum CallCommand {
60 SetCaptions(bool),
63 SetCaptions(bool),
61 SetBackground(BackgroundChoice),
64 SetBackground(BackgroundChoice),
62 SetIncomingVideo(bool),
65 SetIncomingVideo(bool),
66 SetVideoWants(Vec<VideoWant>),
63 SetCameraEffects(CameraEffects),
67 SetCameraEffects(CameraEffects),
64 SendReaction(Reaction),
68 SendReaction(Reaction),
65 StartRecording { kind: RecordingKind, title: String },
69 StartRecording { kind: RecordingKind, title: String },
crates/calling/src/effects.rs +16 −5
@@ -6,6 +6,7 @@ use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};
6 6
7 7 use crate::blur::{BlurSettings, BlurStage, MASK_HEIGHT, MASK_WIDTH, MaskSource};
8 8 use crate::camera::i420_from_rgba;
9 use crate::standout::Cutout;
9 10 use crate::framing::{CropPlanner, Subject, crop_and_scale, find_subject, is_full_frame};
10 11 use crate::luma_effects::{apply_table, gamma_table, mean_luma, smooth_gamma, soften_luma, target_gamma};
11 12
@@ -94,7 +95,8 @@ impl EffectsStage {
94 95 pub fn apply_i420(&mut self, mut buffer: I420Buffer) -> I420Buffer {
95 96 let effects = self.settings.effects();
96 97 let blur = self.settings.enabled();
97 if !blur && !effects.alters_frame() {
98 let standout = self.settings.standout();
99 if !blur && !standout && !effects.alters_frame() {
98 100 self.previous_frame = None;
99 101 return buffer;
100 102 }
@@ -104,11 +106,14 @@ impl EffectsStage {
104 106 if effects.adjust_brightness {
105 107 self.adjust_brightness(&mut buffer, width, height, elapsed);
106 108 }
107 if (blur || effects.needs_mask()) && self.load_masks() {
108 self.refresh_mask(&mut buffer, effects.auto_framing);
109 if (blur || standout || effects.needs_mask()) && self.load_masks() {
110 let fresh = self.refresh_mask(&mut buffer, effects.auto_framing);
109 111 if effects.soft_focus {
110 112 self.soften(&mut buffer, width, height, effects.soft_focus_strength);
111 113 }
114 if standout && fresh {
115 self.publish_cutout(&mut buffer);
116 }
112 117 if blur {
113 118 buffer = self.compose_background(buffer, width, height);
114 119 }
@@ -138,12 +143,18 @@ impl EffectsStage {
138 143 !self.unavailable
139 144 }
140 145
141 fn refresh_mask(&mut self, buffer: &mut I420Buffer, track_subject: bool) {
142 let Some(masks) = self.masks.as_mut() else { return };
146 fn refresh_mask(&mut self, buffer: &mut I420Buffer, track_subject: bool) -> bool {
147 let Some(masks) = self.masks.as_mut() else { return false };
143 148 let fresh = masks.refresh(|| mask_input(buffer));
144 149 if track_subject && fresh {
145 150 self.subject = find_subject(masks.mask(), MASK_WIDTH, MASK_HEIGHT);
146 151 }
152 fresh
153 }
154
155 fn publish_cutout(&self, buffer: &mut I420Buffer) {
156 let Some(masks) = self.masks.as_ref() else { return };
157 self.settings.set_cutout(Cutout::from_camera(buffer, masks.mask()).map(Arc::new));
147 158 }
148 159
149 160 fn soften(&self, buffer: &mut I420Buffer, width: usize, height: usize, strength: u8) {
@@ -6,6 +6,7 @@ use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};
6
6
7use crate::blur::{BlurSettings, BlurStage, MASK_HEIGHT, MASK_WIDTH, MaskSource};
7use crate::blur::{BlurSettings, BlurStage, MASK_HEIGHT, MASK_WIDTH, MaskSource};
8use crate::camera::i420_from_rgba;
8use crate::camera::i420_from_rgba;
9use crate::standout::Cutout;
9use crate::framing::{CropPlanner, Subject, crop_and_scale, find_subject, is_full_frame};
10use crate::framing::{CropPlanner, Subject, crop_and_scale, find_subject, is_full_frame};
10use crate::luma_effects::{apply_table, gamma_table, mean_luma, smooth_gamma, soften_luma, target_gamma};
11use crate::luma_effects::{apply_table, gamma_table, mean_luma, smooth_gamma, soften_luma, target_gamma};
11
12
@@ -94,7 +95,8 @@ impl EffectsStage {
94 pub fn apply_i420(&mut self, mut buffer: I420Buffer) -> I420Buffer {
95 pub fn apply_i420(&mut self, mut buffer: I420Buffer) -> I420Buffer {
95 let effects = self.settings.effects();
96 let effects = self.settings.effects();
96 let blur = self.settings.enabled();
97 let blur = self.settings.enabled();
97 if !blur && !effects.alters_frame() {
98 let standout = self.settings.standout();
99 if !blur && !standout && !effects.alters_frame() {
98 self.previous_frame = None;
100 self.previous_frame = None;
99 return buffer;
101 return buffer;
100 }
102 }
@@ -104,11 +106,14 @@ impl EffectsStage {
104 if effects.adjust_brightness {
106 if effects.adjust_brightness {
105 self.adjust_brightness(&mut buffer, width, height, elapsed);
107 self.adjust_brightness(&mut buffer, width, height, elapsed);
106 }
108 }
107 if (blur || effects.needs_mask()) && self.load_masks() {
109 if (blur || standout || effects.needs_mask()) && self.load_masks() {
108 self.refresh_mask(&mut buffer, effects.auto_framing);
110 let fresh = self.refresh_mask(&mut buffer, effects.auto_framing);
109 if effects.soft_focus {
111 if effects.soft_focus {
110 self.soften(&mut buffer, width, height, effects.soft_focus_strength);
112 self.soften(&mut buffer, width, height, effects.soft_focus_strength);
111 }
113 }
114 if standout && fresh {
115 self.publish_cutout(&mut buffer);
116 }
112 if blur {
117 if blur {
113 buffer = self.compose_background(buffer, width, height);
118 buffer = self.compose_background(buffer, width, height);
114 }
119 }
@@ -138,12 +143,18 @@ impl EffectsStage {
138 !self.unavailable
143 !self.unavailable
139 }
144 }
140
145
141 fn refresh_mask(&mut self, buffer: &mut I420Buffer, track_subject: bool) {
146 fn refresh_mask(&mut self, buffer: &mut I420Buffer, track_subject: bool) -> bool {
142 let Some(masks) = self.masks.as_mut() else { return };
147 let Some(masks) = self.masks.as_mut() else { return false };
143 let fresh = masks.refresh(|| mask_input(buffer));
148 let fresh = masks.refresh(|| mask_input(buffer));
144 if track_subject && fresh {
149 if track_subject && fresh {
145 self.subject = find_subject(masks.mask(), MASK_WIDTH, MASK_HEIGHT);
150 self.subject = find_subject(masks.mask(), MASK_WIDTH, MASK_HEIGHT);
146 }
151 }
152 fresh
153 }
154
155 fn publish_cutout(&self, buffer: &mut I420Buffer) {
156 let Some(masks) = self.masks.as_ref() else { return };
157 self.settings.set_cutout(Cutout::from_camera(buffer, masks.mask()).map(Arc::new));
147 }
158 }
148
159
149 fn soften(&self, buffer: &mut I420Buffer, width: usize, height: usize, strength: u8) {
160 fn soften(&self, buffer: &mut I420Buffer, width: usize, height: usize, strength: u8) {
crates/calling/src/lib.rs +2 −0
@@ -42,6 +42,7 @@ pub mod sdp;
42 42 pub mod signaling;
43 43 pub mod software_audio;
44 44 pub mod sound_capture;
45 pub mod standout;
45 46 pub mod state;
46 47 pub mod timeline;
47 48 pub mod transfer;
@@ -80,6 +81,7 @@ pub use error::{Error, Result};
80 81 pub use level::SpeakingDetector;
81 82 pub use mic_processing::{ApmConfig, MicSettings, NoiseSuppression};
82 83 pub use mute::MuteCommand;
84 pub use video_layout::{TileDetail, VideoWant};
83 85 pub use state::{CallSignal, CallState, EndReason};
84 86 pub use camera::{CameraDevice, camera_entries};
85 87 pub use screen::{ShareKind, ShareSource};
@@ -42,6 +42,7 @@ pub mod sdp;
42pub mod signaling;
42pub mod signaling;
43pub mod software_audio;
43pub mod software_audio;
44pub mod sound_capture;
44pub mod sound_capture;
45pub mod standout;
45pub mod state;
46pub mod state;
46pub mod timeline;
47pub mod timeline;
47pub mod transfer;
48pub mod transfer;
@@ -80,6 +81,7 @@ pub use error::{Error, Result};
80pub use level::SpeakingDetector;
81pub use level::SpeakingDetector;
81pub use mic_processing::{ApmConfig, MicSettings, NoiseSuppression};
82pub use mic_processing::{ApmConfig, MicSettings, NoiseSuppression};
82pub use mute::MuteCommand;
83pub use mute::MuteCommand;
84pub use video_layout::{TileDetail, VideoWant};
83pub use state::{CallSignal, CallState, EndReason};
85pub use state::{CallSignal, CallState, EndReason};
84pub use camera::{CameraDevice, camera_entries};
86pub use camera::{CameraDevice, camera_entries};
85pub use screen::{ShareKind, ShareSource};
87pub use screen::{ShareKind, ShareSource};
crates/calling/src/screen.rs +4 −4
@@ -1,4 +1,5 @@
1 use std::sync::atomic::Ordering;
1 use std::sync::Arc;
2 use std::sync::atomic::{AtomicU32, Ordering};
2 3 use std::time::Duration;
3 4
4 5 use libwebrtc::desktop_capturer::{CaptureSource, DesktopCaptureSourceType, DesktopCapturer, DesktopCapturerOptions};
@@ -7,7 +8,6 @@ use libwebrtc::video_frame::I420Buffer;
7 8
8 9 use crate::capture::Capture;
9 10 use crate::error::{Error, Result};
10 use crate::video_pattern::PatternKind;
11 11
12 12
13 13 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -83,10 +83,10 @@ fn i420_from_bgra(bytes: &[u8], width: u32, height: u32, stride: u32) -> I420Buf
83 83
84 84 pub fn start_screen_capture(
85 85 wanted: ShareSource,
86 fps: Arc<AtomicU32>,
86 87 mut deliver: impl FnMut(I420Buffer) + Send + 'static,
87 88 failed: impl FnOnce(String) + Send + 'static,
88 89 ) -> Result<Capture> {
89 let period = Duration::from_secs(1) / PatternKind::Screen.fps();
90 90 Capture::spawn_thread("screen-capture", move |stop| {
91 91 let Some(source) = sources_of(wanted.kind).into_iter().find(|(source, _)| source.id == wanted.id).map(|(_, raw)| raw) else {
92 92 return failed("the shared source is gone".to_owned());
@@ -103,7 +103,7 @@ pub fn start_screen_capture(
103 103 });
104 104 while !stop.load(Ordering::SeqCst) {
105 105 capturer.capture_frame();
106 std::thread::sleep(period);
106 std::thread::sleep(Duration::from_secs(1) / fps.load(Ordering::Relaxed).max(1));
107 107 }
108 108 })
109 109 .map_err(|error| Error::Webrtc(format!("screen thread: {error}")))
@@ -1,4 +1,5 @@
1use std::sync::atomic::Ordering;
1use std::sync::Arc;
2use std::sync::atomic::{AtomicU32, Ordering};
2use std::time::Duration;
3use std::time::Duration;
3
4
4use libwebrtc::desktop_capturer::{CaptureSource, DesktopCaptureSourceType, DesktopCapturer, DesktopCapturerOptions};
5use libwebrtc::desktop_capturer::{CaptureSource, DesktopCaptureSourceType, DesktopCapturer, DesktopCapturerOptions};
@@ -7,7 +8,6 @@ use libwebrtc::video_frame::I420Buffer;
7
8
8use crate::capture::Capture;
9use crate::capture::Capture;
9use crate::error::{Error, Result};
10use crate::error::{Error, Result};
10use crate::video_pattern::PatternKind;
11
11
12
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -83,10 +83,10 @@ fn i420_from_bgra(bytes: &[u8], width: u32, height: u32, stride: u32) -> I420Buf
83
83
84pub fn start_screen_capture(
84pub fn start_screen_capture(
85 wanted: ShareSource,
85 wanted: ShareSource,
86 fps: Arc<AtomicU32>,
86 mut deliver: impl FnMut(I420Buffer) + Send + 'static,
87 mut deliver: impl FnMut(I420Buffer) + Send + 'static,
87 failed: impl FnOnce(String) + Send + 'static,
88 failed: impl FnOnce(String) + Send + 'static,
88) -> Result<Capture> {
89) -> Result<Capture> {
89 let period = Duration::from_secs(1) / PatternKind::Screen.fps();
90 Capture::spawn_thread("screen-capture", move |stop| {
90 Capture::spawn_thread("screen-capture", move |stop| {
91 let Some(source) = sources_of(wanted.kind).into_iter().find(|(source, _)| source.id == wanted.id).map(|(_, raw)| raw) else {
91 let Some(source) = sources_of(wanted.kind).into_iter().find(|(source, _)| source.id == wanted.id).map(|(_, raw)| raw) else {
92 return failed("the shared source is gone".to_owned());
92 return failed("the shared source is gone".to_owned());
@@ -103,7 +103,7 @@ pub fn start_screen_capture(
103 });
103 });
104 while !stop.load(Ordering::SeqCst) {
104 while !stop.load(Ordering::SeqCst) {
105 capturer.capture_frame();
105 capturer.capture_frame();
106 std::thread::sleep(period);
106 std::thread::sleep(Duration::from_secs(1) / fps.load(Ordering::Relaxed).max(1));
107 }
107 }
108 })
108 })
109 .map_err(|error| Error::Webrtc(format!("screen thread: {error}")))
109 .map_err(|error| Error::Webrtc(format!("screen thread: {error}")))
crates/calling/src/standout.rs added +245 −0
@@ -0,0 +1,245 @@
1 use std::sync::Arc;
2
3 use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};
4
5 use crate::blur::{MASK_HEIGHT, MASK_WIDTH, axis, smoothstep};
6 use crate::blur::BlurSettings;
7
8 const CUTOUT_WIDTH: u32 = 480;
9 const WIDTH_SHARE: f32 = 0.22;
10 const MARGIN_SHARE: f32 = 0.03;
11 const CORNER_SHARE: f32 = 0.1;
12 const MIN_TARGET_WIDTH: usize = 64;
13
14 pub struct Cutout {
15 width: usize,
16 height: usize,
17 luma: Vec<u8>,
18 chroma_blue: Vec<u8>,
19 chroma_red: Vec<u8>,
20 alpha: Vec<u8>,
21 }
22
23 fn corner_coverage(column: usize, row: usize, width: usize, height: usize, radius: f32) -> f32 {
24 let x = column as f32 + 0.5;
25 let y = row as f32 + 0.5;
26 let inner_x = x.clamp(radius, width as f32 - radius);
27 let inner_y = y.clamp(radius, height as f32 - radius);
28 let distance = ((x - inner_x).powi(2) + (y - inner_y).powi(2)).sqrt();
29 (radius - distance + 0.5).clamp(0., 1.)
30 }
31
32 impl Cutout {
33 pub fn from_camera(camera: &mut I420Buffer, mask: &[f32]) -> Option<Cutout> {
34 if mask.len() != MASK_WIDTH * MASK_HEIGHT || camera.width() < 2 || camera.height() < 2 {
35 return None;
36 }
37 let width = CUTOUT_WIDTH.min(camera.width()) & !1;
38 let height = (u64::from(camera.height()) * u64::from(width) / u64::from(camera.width())) as u32 & !1;
39 let scaled = camera.scale(width as i32, height as i32);
40 let (width, height) = (width as usize, height as usize);
41 let (stride_y, stride_u, stride_v) = scaled.strides();
42 let (plane_y, plane_u, plane_v) = scaled.data();
43 let mask_x = axis(width, MASK_WIDTH);
44 let mask_y = axis(height, MASK_HEIGHT);
45 let radius = width as f32 * CORNER_SHARE;
46 let mut cutout = Cutout {
47 width,
48 height,
49 luma: Vec::with_capacity(width * height),
50 chroma_blue: Vec::with_capacity(width * height),
51 chroma_red: Vec::with_capacity(width * height),
52 alpha: Vec::with_capacity(width * height),
53 };
54 for row in 0..height {
55 let (top, bottom, vertical) = (mask_y.first[row] * MASK_WIDTH, mask_y.second[row] * MASK_WIDTH, mask_y.weight[row]);
56 for column in 0..width {
57 let (left, right, across) = (mask_x.first[column], mask_x.second[column], mask_x.weight[column]);
58 let upper = mask[top + left] * (1. - across) + mask[top + right] * across;
59 let lower = mask[bottom + left] * (1. - across) + mask[bottom + right] * across;
60 let person = smoothstep(upper * (1. - vertical) + lower * vertical);
61 let coverage = person * corner_coverage(column, row, width, height, radius);
62 cutout.luma.push(plane_y[row * stride_y as usize + column]);
63 cutout.chroma_blue.push(plane_u[(row / 2) * stride_u as usize + column / 2]);
64 cutout.chroma_red.push(plane_v[(row / 2) * stride_v as usize + column / 2]);
65 cutout.alpha.push((coverage * 255. + 0.5) as u8);
66 }
67 }
68 Some(cutout)
69 }
70
71 fn scaled_to(&self, width: usize, height: usize) -> Cutout {
72 let across = axis(width, self.width);
73 let down = axis(height, self.height);
74 let resample = |plane: &[u8]| -> Vec<u8> {
75 let mut output = Vec::with_capacity(width * height);
76 for row in 0..height {
77 let (top, bottom, vertical) = (down.first[row] * self.width, down.second[row] * self.width, down.weight[row]);
78 for column in 0..width {
79 let (left, right, horizontal) = (across.first[column], across.second[column], across.weight[column]);
80 let sample = |index: usize| f32::from(plane[index]);
81 let upper = sample(top + left) * (1. - horizontal) + sample(top + right) * horizontal;
82 let lower = sample(bottom + left) * (1. - horizontal) + sample(bottom + right) * horizontal;
83 output.push((upper * (1. - vertical) + lower * vertical + 0.5) as u8);
84 }
85 }
86 output
87 };
88 Cutout {
89 width,
90 height,
91 luma: resample(&self.luma),
92 chroma_blue: resample(&self.chroma_blue),
93 chroma_red: resample(&self.chroma_red),
94 alpha: resample(&self.alpha),
95 }
96 }
97
98 fn blend_onto(&self, target: &mut I420Buffer, left: usize, top: usize) {
99 let (stride_y, stride_u, stride_v) = target.strides();
100 let (plane_y, plane_u, plane_v) = target.data_mut();
101 let mix = |below: u8, above: u8, alpha: u8| {
102 let weight = u32::from(alpha);
103 ((u32::from(below) * (255 - weight) + u32::from(above) * weight + 127) / 255) as u8
104 };
105 for row in 0..self.height {
106 for column in 0..self.width {
107 let alpha = self.alpha[row * self.width + column];
108 if alpha == 0 {
109 continue;
110 }
111 let (x, y) = (left + column, top + row);
112 let source = row * self.width + column;
113 let luma = &mut plane_y[y * stride_y as usize + x];
114 *luma = mix(*luma, self.luma[source], alpha);
115 if x % 2 == 0 && y % 2 == 0 {
116 let chroma_index = (y / 2) * stride_u as usize + x / 2;
117 plane_u[chroma_index] = mix(plane_u[chroma_index], self.chroma_blue[source], alpha);
118 let chroma_index = (y / 2) * stride_v as usize + x / 2;
119 plane_v[chroma_index] = mix(plane_v[chroma_index], self.chroma_red[source], alpha);
120 }
121 }
122 }
123 }
124 }
125
126 pub struct StandoutOverlay {
127 settings: Arc<BlurSettings>,
128 scaled: Option<ScaledCutout>,
129 }
130
131 struct ScaledCutout {
132 source: Arc<Cutout>,
133 frame: (usize, usize),
134 cutout: Cutout,
135 }
136
137 impl StandoutOverlay {
138 pub fn new(settings: Arc<BlurSettings>) -> Self {
139 StandoutOverlay { settings, scaled: None }
140 }
141
142 pub fn apply(&mut self, mut frame: I420Buffer) -> I420Buffer {
143 if !self.settings.standout() {
144 return frame;
145 }
146 let Some(source) = self.settings.cutout() else { return frame };
147 let (frame_width, frame_height) = (frame.width() as usize, frame.height() as usize);
148 let width = (frame_width as f32 * WIDTH_SHARE) as usize & !1;
149 if width < MIN_TARGET_WIDTH {
150 return frame;
151 }
152 let height = (width * source.height / source.width) & !1;
153 let margin = (frame_width as f32 * MARGIN_SHARE) as usize;
154 if height + margin >= frame_height || width + margin >= frame_width {
155 return frame;
156 }
157 let fresh = self.scaled.as_ref().is_some_and(|scaled| Arc::ptr_eq(&scaled.source, &source) && scaled.frame == (frame_width, frame_height));
158 if !fresh {
159 self.scaled = Some(ScaledCutout { cutout: source.scaled_to(width, height), source, frame: (frame_width, frame_height) });
160 }
161 if let Some(scaled) = &self.scaled {
162 let left = (frame_width - width - margin) & !1;
163 let top = (frame_height - height - margin) & !1;
164 scaled.cutout.blend_onto(&mut frame, left, top);
165 }
166 frame
167 }
168 }
169
170 #[cfg(test)]
171 mod tests {
172 use super::*;
173
174 fn gray_frame(width: u32, height: u32, luma: u8) -> I420Buffer {
175 let mut buffer = I420Buffer::new(width, height);
176 let (stride_y, stride_u, stride_v) = buffer.strides();
177 let (plane_y, plane_u, plane_v) = buffer.data_mut();
178 for row in 0..height as usize {
179 plane_y[row * stride_y as usize..][..width as usize].fill(luma);
180 }
181 for row in 0..height as usize / 2 {
182 plane_u[row * stride_u as usize..][..width as usize / 2].fill(128);
183 plane_v[row * stride_v as usize..][..width as usize / 2].fill(128);
184 }
185 buffer
186 }
187
188 fn full_mask(value: f32) -> Vec<f32> {
189 vec![value; MASK_WIDTH * MASK_HEIGHT]
190 }
191
192 fn luma_at(buffer: &I420Buffer, x: usize, y: usize) -> u8 {
193 buffer.data().0[y * buffer.strides().0 as usize + x]
194 }
195
196 fn overlay_with(person: f32) -> (StandoutOverlay, Arc<BlurSettings>) {
197 let settings = Arc::new(BlurSettings::default());
198 settings.set_standout(true);
199 let mut camera = gray_frame(640, 360, 235);
200 settings.set_cutout(Cutout::from_camera(&mut camera, &full_mask(person)).map(Arc::new));
201 (StandoutOverlay::new(settings.clone()), settings)
202 }
203
204 #[test]
205 fn the_person_lands_bottom_right_and_the_rest_of_the_screen_stays() {
206 let (mut overlay, _) = overlay_with(1.);
207 let frame = overlay.apply(gray_frame(1280, 720, 16));
208 assert_eq!(luma_at(&frame, 100, 100), 16);
209 assert!(luma_at(&frame, 1280 - 100, 720 - 100) > 200);
210 }
211
212 #[test]
213 fn corners_are_rounded() {
214 let (mut overlay, _) = overlay_with(1.);
215 let frame = overlay.apply(gray_frame(1280, 720, 16));
216 let width = (1280. * WIDTH_SHARE) as usize & !1;
217 let left = (1280 - width - (1280. * MARGIN_SHARE) as usize) & !1;
218 let top = (720 - ((width * 9 / 16) & !1) - (1280. * MARGIN_SHARE) as usize) & !1;
219 assert_eq!(luma_at(&frame, left, top), 16);
220 assert!(luma_at(&frame, left + width / 2, top + 20) > 200);
221 }
222
223 #[test]
224 fn no_person_in_the_mask_changes_nothing() {
225 let (mut overlay, _) = overlay_with(0.);
226 let frame = overlay.apply(gray_frame(1280, 720, 16));
227 assert_eq!(luma_at(&frame, 1280 - 100, 720 - 100), 16);
228 }
229
230 #[test]
231 fn switched_off_or_without_a_cutout_the_frame_passes_through() {
232 let (mut overlay, settings) = overlay_with(1.);
233 settings.set_standout(false);
234 assert_eq!(luma_at(&overlay.apply(gray_frame(1280, 720, 16)), 1280 - 100, 720 - 100), 16);
235 settings.set_standout(true);
236 settings.set_cutout(None);
237 assert_eq!(luma_at(&overlay.apply(gray_frame(1280, 720, 16)), 1280 - 100, 720 - 100), 16);
238 }
239
240 #[test]
241 fn a_missing_mask_gives_no_cutout() {
242 let mut camera = gray_frame(640, 360, 100);
243 assert!(Cutout::from_camera(&mut camera, &[]).is_none());
244 }
245 }
@@ -0,0 +1,245 @@
1use std::sync::Arc;
2
3use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};
4
5use crate::blur::{MASK_HEIGHT, MASK_WIDTH, axis, smoothstep};
6use crate::blur::BlurSettings;
7
8const CUTOUT_WIDTH: u32 = 480;
9const WIDTH_SHARE: f32 = 0.22;
10const MARGIN_SHARE: f32 = 0.03;
11const CORNER_SHARE: f32 = 0.1;
12const MIN_TARGET_WIDTH: usize = 64;
13
14pub struct Cutout {
15 width: usize,
16 height: usize,
17 luma: Vec<u8>,
18 chroma_blue: Vec<u8>,
19 chroma_red: Vec<u8>,
20 alpha: Vec<u8>,
21}
22
23fn corner_coverage(column: usize, row: usize, width: usize, height: usize, radius: f32) -> f32 {
24 let x = column as f32 + 0.5;
25 let y = row as f32 + 0.5;
26 let inner_x = x.clamp(radius, width as f32 - radius);
27 let inner_y = y.clamp(radius, height as f32 - radius);
28 let distance = ((x - inner_x).powi(2) + (y - inner_y).powi(2)).sqrt();
29 (radius - distance + 0.5).clamp(0., 1.)
30}
31
32impl Cutout {
33 pub fn from_camera(camera: &mut I420Buffer, mask: &[f32]) -> Option<Cutout> {
34 if mask.len() != MASK_WIDTH * MASK_HEIGHT || camera.width() < 2 || camera.height() < 2 {
35 return None;
36 }
37 let width = CUTOUT_WIDTH.min(camera.width()) & !1;
38 let height = (u64::from(camera.height()) * u64::from(width) / u64::from(camera.width())) as u32 & !1;
39 let scaled = camera.scale(width as i32, height as i32);
40 let (width, height) = (width as usize, height as usize);
41 let (stride_y, stride_u, stride_v) = scaled.strides();
42 let (plane_y, plane_u, plane_v) = scaled.data();
43 let mask_x = axis(width, MASK_WIDTH);
44 let mask_y = axis(height, MASK_HEIGHT);
45 let radius = width as f32 * CORNER_SHARE;
46 let mut cutout = Cutout {
47 width,
48 height,
49 luma: Vec::with_capacity(width * height),
50 chroma_blue: Vec::with_capacity(width * height),
51 chroma_red: Vec::with_capacity(width * height),
52 alpha: Vec::with_capacity(width * height),
53 };
54 for row in 0..height {
55 let (top, bottom, vertical) = (mask_y.first[row] * MASK_WIDTH, mask_y.second[row] * MASK_WIDTH, mask_y.weight[row]);
56 for column in 0..width {
57 let (left, right, across) = (mask_x.first[column], mask_x.second[column], mask_x.weight[column]);
58 let upper = mask[top + left] * (1. - across) + mask[top + right] * across;
59 let lower = mask[bottom + left] * (1. - across) + mask[bottom + right] * across;
60 let person = smoothstep(upper * (1. - vertical) + lower * vertical);
61 let coverage = person * corner_coverage(column, row, width, height, radius);
62 cutout.luma.push(plane_y[row * stride_y as usize + column]);
63 cutout.chroma_blue.push(plane_u[(row / 2) * stride_u as usize + column / 2]);
64 cutout.chroma_red.push(plane_v[(row / 2) * stride_v as usize + column / 2]);
65 cutout.alpha.push((coverage * 255. + 0.5) as u8);
66 }
67 }
68 Some(cutout)
69 }
70
71 fn scaled_to(&self, width: usize, height: usize) -> Cutout {
72 let across = axis(width, self.width);
73 let down = axis(height, self.height);
74 let resample = |plane: &[u8]| -> Vec<u8> {
75 let mut output = Vec::with_capacity(width * height);
76 for row in 0..height {
77 let (top, bottom, vertical) = (down.first[row] * self.width, down.second[row] * self.width, down.weight[row]);
78 for column in 0..width {
79 let (left, right, horizontal) = (across.first[column], across.second[column], across.weight[column]);
80 let sample = |index: usize| f32::from(plane[index]);
81 let upper = sample(top + left) * (1. - horizontal) + sample(top + right) * horizontal;
82 let lower = sample(bottom + left) * (1. - horizontal) + sample(bottom + right) * horizontal;
83 output.push((upper * (1. - vertical) + lower * vertical + 0.5) as u8);
84 }
85 }
86 output
87 };
88 Cutout {
89 width,
90 height,
91 luma: resample(&self.luma),
92 chroma_blue: resample(&self.chroma_blue),
93 chroma_red: resample(&self.chroma_red),
94 alpha: resample(&self.alpha),
95 }
96 }
97
98 fn blend_onto(&self, target: &mut I420Buffer, left: usize, top: usize) {
99 let (stride_y, stride_u, stride_v) = target.strides();
100 let (plane_y, plane_u, plane_v) = target.data_mut();
101 let mix = |below: u8, above: u8, alpha: u8| {
102 let weight = u32::from(alpha);
103 ((u32::from(below) * (255 - weight) + u32::from(above) * weight + 127) / 255) as u8
104 };
105 for row in 0..self.height {
106 for column in 0..self.width {
107 let alpha = self.alpha[row * self.width + column];
108 if alpha == 0 {
109 continue;
110 }
111 let (x, y) = (left + column, top + row);
112 let source = row * self.width + column;
113 let luma = &mut plane_y[y * stride_y as usize + x];
114 *luma = mix(*luma, self.luma[source], alpha);
115 if x % 2 == 0 && y % 2 == 0 {
116 let chroma_index = (y / 2) * stride_u as usize + x / 2;
117 plane_u[chroma_index] = mix(plane_u[chroma_index], self.chroma_blue[source], alpha);
118 let chroma_index = (y / 2) * stride_v as usize + x / 2;
119 plane_v[chroma_index] = mix(plane_v[chroma_index], self.chroma_red[source], alpha);
120 }
121 }
122 }
123 }
124}
125
126pub struct StandoutOverlay {
127 settings: Arc<BlurSettings>,
128 scaled: Option<ScaledCutout>,
129}
130
131struct ScaledCutout {
132 source: Arc<Cutout>,
133 frame: (usize, usize),
134 cutout: Cutout,
135}
136
137impl StandoutOverlay {
138 pub fn new(settings: Arc<BlurSettings>) -> Self {
139 StandoutOverlay { settings, scaled: None }
140 }
141
142 pub fn apply(&mut self, mut frame: I420Buffer) -> I420Buffer {
143 if !self.settings.standout() {
144 return frame;
145 }
146 let Some(source) = self.settings.cutout() else { return frame };
147 let (frame_width, frame_height) = (frame.width() as usize, frame.height() as usize);
148 let width = (frame_width as f32 * WIDTH_SHARE) as usize & !1;
149 if width < MIN_TARGET_WIDTH {
150 return frame;
151 }
152 let height = (width * source.height / source.width) & !1;
153 let margin = (frame_width as f32 * MARGIN_SHARE) as usize;
154 if height + margin >= frame_height || width + margin >= frame_width {
155 return frame;
156 }
157 let fresh = self.scaled.as_ref().is_some_and(|scaled| Arc::ptr_eq(&scaled.source, &source) && scaled.frame == (frame_width, frame_height));
158 if !fresh {
159 self.scaled = Some(ScaledCutout { cutout: source.scaled_to(width, height), source, frame: (frame_width, frame_height) });
160 }
161 if let Some(scaled) = &self.scaled {
162 let left = (frame_width - width - margin) & !1;
163 let top = (frame_height - height - margin) & !1;
164 scaled.cutout.blend_onto(&mut frame, left, top);
165 }
166 frame
167 }
168}
169
170#[cfg(test)]
171mod tests {
172 use super::*;
173
174 fn gray_frame(width: u32, height: u32, luma: u8) -> I420Buffer {
175 let mut buffer = I420Buffer::new(width, height);
176 let (stride_y, stride_u, stride_v) = buffer.strides();
177 let (plane_y, plane_u, plane_v) = buffer.data_mut();
178 for row in 0..height as usize {
179 plane_y[row * stride_y as usize..][..width as usize].fill(luma);
180 }
181 for row in 0..height as usize / 2 {
182 plane_u[row * stride_u as usize..][..width as usize / 2].fill(128);
183 plane_v[row * stride_v as usize..][..width as usize / 2].fill(128);
184 }
185 buffer
186 }
187
188 fn full_mask(value: f32) -> Vec<f32> {
189 vec![value; MASK_WIDTH * MASK_HEIGHT]
190 }
191
192 fn luma_at(buffer: &I420Buffer, x: usize, y: usize) -> u8 {
193 buffer.data().0[y * buffer.strides().0 as usize + x]
194 }
195
196 fn overlay_with(person: f32) -> (StandoutOverlay, Arc<BlurSettings>) {
197 let settings = Arc::new(BlurSettings::default());
198 settings.set_standout(true);
199 let mut camera = gray_frame(640, 360, 235);
200 settings.set_cutout(Cutout::from_camera(&mut camera, &full_mask(person)).map(Arc::new));
201 (StandoutOverlay::new(settings.clone()), settings)
202 }
203
204 #[test]
205 fn the_person_lands_bottom_right_and_the_rest_of_the_screen_stays() {
206 let (mut overlay, _) = overlay_with(1.);
207 let frame = overlay.apply(gray_frame(1280, 720, 16));
208 assert_eq!(luma_at(&frame, 100, 100), 16);
209 assert!(luma_at(&frame, 1280 - 100, 720 - 100) > 200);
210 }
211
212 #[test]
213 fn corners_are_rounded() {
214 let (mut overlay, _) = overlay_with(1.);
215 let frame = overlay.apply(gray_frame(1280, 720, 16));
216 let width = (1280. * WIDTH_SHARE) as usize & !1;
217 let left = (1280 - width - (1280. * MARGIN_SHARE) as usize) & !1;
218 let top = (720 - ((width * 9 / 16) & !1) - (1280. * MARGIN_SHARE) as usize) & !1;
219 assert_eq!(luma_at(&frame, left, top), 16);
220 assert!(luma_at(&frame, left + width / 2, top + 20) > 200);
221 }
222
223 #[test]
224 fn no_person_in_the_mask_changes_nothing() {
225 let (mut overlay, _) = overlay_with(0.);
226 let frame = overlay.apply(gray_frame(1280, 720, 16));
227 assert_eq!(luma_at(&frame, 1280 - 100, 720 - 100), 16);
228 }
229
230 #[test]
231 fn switched_off_or_without_a_cutout_the_frame_passes_through() {
232 let (mut overlay, settings) = overlay_with(1.);
233 settings.set_standout(false);
234 assert_eq!(luma_at(&overlay.apply(gray_frame(1280, 720, 16)), 1280 - 100, 720 - 100), 16);
235 settings.set_standout(true);
236 settings.set_cutout(None);
237 assert_eq!(luma_at(&overlay.apply(gray_frame(1280, 720, 16)), 1280 - 100, 720 - 100), 16);
238 }
239
240 #[test]
241 fn a_missing_mask_gives_no_cutout() {
242 let mut camera = gray_frame(640, 360, 100);
243 assert!(Cutout::from_camera(&mut camera, &[]).is_none());
244 }
245}
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/src/video_send.rs +50 −3
@@ -1,8 +1,10 @@
1 1 use std::sync::Arc;
2 use std::sync::atomic::{AtomicU32, Ordering};
2 3 use std::time::{Instant, SystemTime, UNIX_EPOCH};
3 4
4 5 use libwebrtc::media_stream_track::MediaStreamTrack;
5 6 use libwebrtc::peer_connection_factory::PeerConnectionFactory;
7 use libwebrtc::rtp_parameters::DegradationPreference;
6 8 use libwebrtc::rtp_sender::RtpSender;
7 9 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
8 10 use libwebrtc::video_frame::{I420Buffer, VideoFrame, VideoRotation};
@@ -20,6 +22,7 @@ use crate::control::CallUpdate;
20 22 use crate::devices::DeviceChoice;
21 23 use crate::error::{Error, Result};
22 24 use crate::screen::{ShareSource, start_screen_capture};
25 use crate::standout::StandoutOverlay;
23 26 use crate::video_frame::{FrameGate, PERSON_FPS, SCREEN_FPS, VideoHub, VideoKey, picture_from_i420};
24 27 use crate::video_layout::VideoLines;
25 28 use crate::video_pattern::{PatternKind, spawn_pattern};
@@ -27,6 +30,8 @@ use crate::video_pattern::{PatternKind, spawn_pattern};
27 30 pub const VIDEO_MODE_ENV: &str = "CALLING_VIDEO";
28 31 const CAMERA_LABEL: &str = "camera";
29 32 const SCREEN_LABEL: &str = "screen";
33 pub const SCREEN_SHARE_FPS: u32 = 15;
34 pub const MOTION_SHARE_FPS: u32 = 30;
30 35
31 36 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
32 37 pub enum VideoMode {
@@ -55,6 +60,7 @@ pub struct LocalSink {
55 60 source: NativeVideoSource,
56 61 self_view: Option<(Arc<VideoHub>, VideoKey, FrameGate)>,
57 62 mirror: Option<Arc<BlurSettings>>,
63 standout: Option<StandoutOverlay>,
58 64 }
59 65
60 66 impl LocalSink {
@@ -63,7 +69,7 @@ impl LocalSink {
63 69 let fps = if matches!(key, VideoKey::LocalScreen) { SCREEN_FPS } else { PERSON_FPS };
64 70 (hub, key, FrameGate::new(fps))
65 71 });
66 LocalSink { source, self_view, mirror: None }
72 LocalSink { source, self_view, mirror: None, standout: None }
67 73 }
68 74
69 75 pub fn mirrored_by(mut self, settings: Arc<BlurSettings>) -> Self {
@@ -71,7 +77,16 @@ impl LocalSink {
71 77 self
72 78 }
73 79
80 pub fn with_standout(mut self, settings: Arc<BlurSettings>) -> Self {
81 self.standout = Some(StandoutOverlay::new(settings));
82 self
83 }
84
74 85 pub fn push(&mut self, buffer: I420Buffer) {
86 let buffer = match &mut self.standout {
87 Some(overlay) => overlay.apply(buffer),
88 None => buffer,
89 };
75 90 let mut frame = VideoFrame::new(VideoRotation::VideoRotation0, buffer);
76 91 frame.timestamp_us = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |elapsed| elapsed.as_micros() as i64);
77 92 self.source.capture_frame(&frame);
@@ -111,6 +126,8 @@ pub struct LocalVideo {
111 126 screen: Outgoing,
112 127 lines: Option<VideoLines>,
113 128 blur: Arc<BlurSettings>,
129 motion: bool,
130 share_fps: Arc<AtomicU32>,
114 131 }
115 132
116 133 impl LocalVideo {
@@ -123,7 +140,35 @@ impl LocalVideo {
123 140 screen: Outgoing::new(factory, SCREEN_LABEL, PatternKind::Screen, true),
124 141 lines: None,
125 142 blur: Arc::new(BlurSettings::default()),
143 motion: false,
144 share_fps: Arc::new(AtomicU32::new(SCREEN_SHARE_FPS)),
145 }
146 }
147
148 pub fn set_motion(&mut self, motion: bool) {
149 self.motion = motion;
150 self.share_fps.store(if motion { MOTION_SHARE_FPS } else { SCREEN_SHARE_FPS }, Ordering::Relaxed);
151 if let Some(share) = self.lines.as_ref().and_then(|lines| lines.share.as_ref()).filter(|_| self.sharing()) {
152 let _ = self.tune_share(&share.sender());
153 }
154 }
155
156 pub fn set_standout(&self, standout: bool) {
157 self.blur.set_standout(standout);
158 }
159
160 fn tune_share(&self, sender: &RtpSender) -> Result<()> {
161 let mut parameters = sender.parameters();
162 parameters.set_degradation_preference(if self.motion {
163 DegradationPreference::MaintainFramerate
164 } else {
165 DegradationPreference::MaintainResolution
166 });
167 let fps = f64::from(self.share_fps.load(Ordering::Relaxed));
168 for encoding in &mut parameters.encodings {
169 encoding.max_framerate = Some(fps);
126 170 }
171 sender.set_parameters(parameters).map_err(|error| Error::Webrtc(error.to_string()))
127 172 }
128 173
129 174 pub fn set_background(&self, enabled: bool, picture: Option<Arc<BackgroundPicture>>) {
@@ -216,6 +261,7 @@ impl LocalVideo {
216 261
217 262 pub fn stop_camera(&mut self) {
218 263 self.camera.capture = None;
264 self.blur.set_cutout(None);
219 265 if let Some(lines) = &self.lines {
220 266 let _ = Self::set_active(&lines.camera.sender(), false);
221 267 }
@@ -229,12 +275,13 @@ impl LocalVideo {
229 275 return Err(Error::Webrtc("video is switched off".into()));
230 276 }
231 277 self.screen.capture = None;
232 let mut sink = LocalSink::new(self.screen.source.clone(), None);
278 let mut sink = LocalSink::new(self.screen.source.clone(), None).with_standout(self.blur.clone());
233 279 let capture = match self.mode {
234 280 VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Screen, None)),
235 _ => start_screen_capture(source.clone(), move |buffer| sink.push(buffer), self.report_failure("Screen share"))?,
281 _ => start_screen_capture(source.clone(), self.share_fps.clone(), move |buffer| sink.push(buffer), self.report_failure("Screen share"))?,
236 282 };
237 283 Self::begin_sending(&share.sender(), &self.screen.track)?;
284 let _ = self.tune_share(&share.sender());
238 285 self.screen.capture = Some(capture);
239 286 Ok(())
240 287 }
@@ -1,8 +1,10 @@
1use std::sync::Arc;
1use std::sync::Arc;
2use std::sync::atomic::{AtomicU32, Ordering};
2use std::time::{Instant, SystemTime, UNIX_EPOCH};
3use std::time::{Instant, SystemTime, UNIX_EPOCH};
3
4
4use libwebrtc::media_stream_track::MediaStreamTrack;
5use libwebrtc::media_stream_track::MediaStreamTrack;
5use libwebrtc::peer_connection_factory::PeerConnectionFactory;
6use libwebrtc::peer_connection_factory::PeerConnectionFactory;
7use libwebrtc::rtp_parameters::DegradationPreference;
6use libwebrtc::rtp_sender::RtpSender;
8use libwebrtc::rtp_sender::RtpSender;
7use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
9use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
8use libwebrtc::video_frame::{I420Buffer, VideoFrame, VideoRotation};
10use libwebrtc::video_frame::{I420Buffer, VideoFrame, VideoRotation};
@@ -20,6 +22,7 @@ use crate::control::CallUpdate;
20use crate::devices::DeviceChoice;
22use crate::devices::DeviceChoice;
21use crate::error::{Error, Result};
23use crate::error::{Error, Result};
22use crate::screen::{ShareSource, start_screen_capture};
24use crate::screen::{ShareSource, start_screen_capture};
25use crate::standout::StandoutOverlay;
23use crate::video_frame::{FrameGate, PERSON_FPS, SCREEN_FPS, VideoHub, VideoKey, picture_from_i420};
26use crate::video_frame::{FrameGate, PERSON_FPS, SCREEN_FPS, VideoHub, VideoKey, picture_from_i420};
24use crate::video_layout::VideoLines;
27use crate::video_layout::VideoLines;
25use crate::video_pattern::{PatternKind, spawn_pattern};
28use crate::video_pattern::{PatternKind, spawn_pattern};
@@ -27,6 +30,8 @@ use crate::video_pattern::{PatternKind, spawn_pattern};
27pub const VIDEO_MODE_ENV: &str = "CALLING_VIDEO";
30pub const VIDEO_MODE_ENV: &str = "CALLING_VIDEO";
28const CAMERA_LABEL: &str = "camera";
31const CAMERA_LABEL: &str = "camera";
29const SCREEN_LABEL: &str = "screen";
32const SCREEN_LABEL: &str = "screen";
33pub const SCREEN_SHARE_FPS: u32 = 15;
34pub const MOTION_SHARE_FPS: u32 = 30;
30
35
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
32pub enum VideoMode {
37pub enum VideoMode {
@@ -55,6 +60,7 @@ pub struct LocalSink {
55 source: NativeVideoSource,
60 source: NativeVideoSource,
56 self_view: Option<(Arc<VideoHub>, VideoKey, FrameGate)>,
61 self_view: Option<(Arc<VideoHub>, VideoKey, FrameGate)>,
57 mirror: Option<Arc<BlurSettings>>,
62 mirror: Option<Arc<BlurSettings>>,
63 standout: Option<StandoutOverlay>,
58}
64}
59
65
60impl LocalSink {
66impl LocalSink {
@@ -63,7 +69,7 @@ impl LocalSink {
63 let fps = if matches!(key, VideoKey::LocalScreen) { SCREEN_FPS } else { PERSON_FPS };
69 let fps = if matches!(key, VideoKey::LocalScreen) { SCREEN_FPS } else { PERSON_FPS };
64 (hub, key, FrameGate::new(fps))
70 (hub, key, FrameGate::new(fps))
65 });
71 });
66 LocalSink { source, self_view, mirror: None }
72 LocalSink { source, self_view, mirror: None, standout: None }
67 }
73 }
68
74
69 pub fn mirrored_by(mut self, settings: Arc<BlurSettings>) -> Self {
75 pub fn mirrored_by(mut self, settings: Arc<BlurSettings>) -> Self {
@@ -71,7 +77,16 @@ impl LocalSink {
71 self
77 self
72 }
78 }
73
79
80 pub fn with_standout(mut self, settings: Arc<BlurSettings>) -> Self {
81 self.standout = Some(StandoutOverlay::new(settings));
82 self
83 }
84
74 pub fn push(&mut self, buffer: I420Buffer) {
85 pub fn push(&mut self, buffer: I420Buffer) {
86 let buffer = match &mut self.standout {
87 Some(overlay) => overlay.apply(buffer),
88 None => buffer,
89 };
75 let mut frame = VideoFrame::new(VideoRotation::VideoRotation0, buffer);
90 let mut frame = VideoFrame::new(VideoRotation::VideoRotation0, buffer);
76 frame.timestamp_us = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |elapsed| elapsed.as_micros() as i64);
91 frame.timestamp_us = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |elapsed| elapsed.as_micros() as i64);
77 self.source.capture_frame(&frame);
92 self.source.capture_frame(&frame);
@@ -111,6 +126,8 @@ pub struct LocalVideo {
111 screen: Outgoing,
126 screen: Outgoing,
112 lines: Option<VideoLines>,
127 lines: Option<VideoLines>,
113 blur: Arc<BlurSettings>,
128 blur: Arc<BlurSettings>,
129 motion: bool,
130 share_fps: Arc<AtomicU32>,
114}
131}
115
132
116impl LocalVideo {
133impl LocalVideo {
@@ -123,7 +140,35 @@ impl LocalVideo {
123 screen: Outgoing::new(factory, SCREEN_LABEL, PatternKind::Screen, true),
140 screen: Outgoing::new(factory, SCREEN_LABEL, PatternKind::Screen, true),
124 lines: None,
141 lines: None,
125 blur: Arc::new(BlurSettings::default()),
142 blur: Arc::new(BlurSettings::default()),
143 motion: false,
144 share_fps: Arc::new(AtomicU32::new(SCREEN_SHARE_FPS)),
145 }
146 }
147
148 pub fn set_motion(&mut self, motion: bool) {
149 self.motion = motion;
150 self.share_fps.store(if motion { MOTION_SHARE_FPS } else { SCREEN_SHARE_FPS }, Ordering::Relaxed);
151 if let Some(share) = self.lines.as_ref().and_then(|lines| lines.share.as_ref()).filter(|_| self.sharing()) {
152 let _ = self.tune_share(&share.sender());
153 }
154 }
155
156 pub fn set_standout(&self, standout: bool) {
157 self.blur.set_standout(standout);
158 }
159
160 fn tune_share(&self, sender: &RtpSender) -> Result<()> {
161 let mut parameters = sender.parameters();
162 parameters.set_degradation_preference(if self.motion {
163 DegradationPreference::MaintainFramerate
164 } else {
165 DegradationPreference::MaintainResolution
166 });
167 let fps = f64::from(self.share_fps.load(Ordering::Relaxed));
168 for encoding in &mut parameters.encodings {
169 encoding.max_framerate = Some(fps);
126 }
170 }
171 sender.set_parameters(parameters).map_err(|error| Error::Webrtc(error.to_string()))
127 }
172 }
128
173
129 pub fn set_background(&self, enabled: bool, picture: Option<Arc<BackgroundPicture>>) {
174 pub fn set_background(&self, enabled: bool, picture: Option<Arc<BackgroundPicture>>) {
@@ -216,6 +261,7 @@ impl LocalVideo {
216
261
217 pub fn stop_camera(&mut self) {
262 pub fn stop_camera(&mut self) {
218 self.camera.capture = None;
263 self.camera.capture = None;
264 self.blur.set_cutout(None);
219 if let Some(lines) = &self.lines {
265 if let Some(lines) = &self.lines {
220 let _ = Self::set_active(&lines.camera.sender(), false);
266 let _ = Self::set_active(&lines.camera.sender(), false);
221 }
267 }
@@ -229,12 +275,13 @@ impl LocalVideo {
229 return Err(Error::Webrtc("video is switched off".into()));
275 return Err(Error::Webrtc("video is switched off".into()));
230 }
276 }
231 self.screen.capture = None;
277 self.screen.capture = None;
232 let mut sink = LocalSink::new(self.screen.source.clone(), None);
278 let mut sink = LocalSink::new(self.screen.source.clone(), None).with_standout(self.blur.clone());
233 let capture = match self.mode {
279 let capture = match self.mode {
234 VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Screen, None)),
280 VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Screen, None)),
235 _ => start_screen_capture(source.clone(), move |buffer| sink.push(buffer), self.report_failure("Screen share"))?,
281 _ => start_screen_capture(source.clone(), self.share_fps.clone(), move |buffer| sink.push(buffer), self.report_failure("Screen share"))?,
236 };
282 };
237 Self::begin_sending(&share.sender(), &self.screen.track)?;
283 Self::begin_sending(&share.sender(), &self.screen.track)?;
284 let _ = self.tune_share(&share.sender());
238 self.screen.capture = Some(capture);
285 self.screen.capture = Some(capture);
239 Ok(())
286 Ok(())
240 }
287 }
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}