Merge branch 'feat/calls-health' into integrate/calls-10
@@ -18,7 +18,7 @@ Feature parity with the Microsoft Teams desktop client.
18
18
| [Search and navigation](#search-and-navigation) | 100 % | 5 | 0 | 0 |
19
19
| [Presence and people](#presence-and-people) | 100 % | 4 | 0 | 0 |
20
20
| [Look and settings](#look-and-settings) | 50 % | 2 | 0 | 2 |
21
| [Calls and meetings](#calls-and-meetings) | 62 % | 4 | 13 | 0 |
21
| [Calls and meetings](#calls-and-meetings) | 61 % | 4 | 14 | 0 |
22
22
23
23
## Next
24
24
@@ -175,6 +175,7 @@ Feature parity with the Microsoft Teams desktop client.
175
175
| Recording | Partial | Organizer "..." > Start recording / Stop recording (confirm) through the recorder bot, red dot and "Recording" in the header for everyone from the meeting state, consent notice that keeps mic and camera off until OK. Bodies unit tested; start and stop run live through `meet_now --record`, consent needs a tenant with the policy on and a second person |
176
176
| Hold, resume, transfer | Partial | 1:1 "..." > Hold renegotiates every line inactive, "On hold" view with Resume, "You're on hold" when the other side holds, Transfer... person picker with Transfer now (blind) and Consult first (second call, first held, Transfer now). Needs a second person; redirect and park not built |
177
177
| 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 |
178
| 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 |
178
179
| 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 |
179
180
| 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 |
180
181
| 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) |
@@ -18,7 +18,7 @@ Feature parity with the Microsoft Teams desktop client.18
| [Search and navigation](#search-and-navigation) | 100 % | 5 | 0 | 0 |18
| [Search and navigation](#search-and-navigation) | 100 % | 5 | 0 | 0 |19
| [Presence and people](#presence-and-people) | 100 % | 4 | 0 | 0 |19
| [Presence and people](#presence-and-people) | 100 % | 4 | 0 | 0 |20
| [Look and settings](#look-and-settings) | 50 % | 2 | 0 | 2 |20
| [Look and settings](#look-and-settings) | 50 % | 2 | 0 | 2 |21
| [Calls and meetings](#calls-and-meetings) | 62 % | 4 | 13 | 0 |21
| [Calls and meetings](#calls-and-meetings) | 61 % | 4 | 14 | 0 |22
22
23
## Next23
## Next24
24
@@ -175,6 +175,7 @@ Feature parity with the Microsoft Teams desktop client.175
| Recording | Partial | Organizer "..." > Start recording / Stop recording (confirm) through the recorder bot, red dot and "Recording" in the header for everyone from the meeting state, consent notice that keeps mic and camera off until OK. Bodies unit tested; start and stop run live through `meet_now --record`, consent needs a tenant with the policy on and a second person |175
| Recording | Partial | Organizer "..." > Start recording / Stop recording (confirm) through the recorder bot, red dot and "Recording" in the header for everyone from the meeting state, consent notice that keeps mic and camera off until OK. Bodies unit tested; start and stop run live through `meet_now --record`, consent needs a tenant with the policy on and a second person |176
| Hold, resume, transfer | Partial | 1:1 "..." > Hold renegotiates every line inactive, "On hold" view with Resume, "You're on hold" when the other side holds, Transfer... person picker with Transfer now (blind) and Consult first (second call, first held, Transfer now). Needs a second person; redirect and park not built |176
| Hold, resume, transfer | Partial | 1:1 "..." > Hold renegotiates every line inactive, "On hold" view with Resume, "You're on hold" when the other side holds, Transfer... person picker with Transfer now (blind) and Consult first (second call, first held, Transfer now). Needs a second person; redirect and park not built |177
| 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 |177
| 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 |178
| 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 |178
| 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 |179
| 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 |179
| 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 |180
| 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 |180
| 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) |181
| 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) |@@ -0,0 +1 @@
1
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M480-80q-139-35-229.5-159.5T160-516v-244l320-120 320 120v244q0 152-90.5 276.5T480-80Zm0-84q104-33 172-132t68-220v-189l-240-90-240 90v189q0 121 68 220t172 132Zm0-316Z"/></svg>
@@ -0,0 +1 @@1
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M480-80q-139-35-229.5-159.5T160-516v-244l320-120 320 120v244q0 152-90.5 276.5T480-80Zm0-84q104-33 172-132t68-220v-189l-240-90-240 90v189q0 121 68 220t172 132Zm0-316Z"/></svg>@@ -8,7 +8,7 @@ macro_rules! symbols {
8
8
};
9
9
}
10
10
11
const SYMBOLS: [(&str, &[u8]); 42] = symbols![
11
const SYMBOLS: [(&str, &[u8]); 43] = symbols![
12
12
"done",
13
13
"done_all",
14
14
"keyboard_return",
@@ -51,6 +51,7 @@ const SYMBOLS: [(&str, &[u8]); 42] = symbols![
51
51
"fullscreen",
52
52
"spinner_track",
53
53
"spinner_arc",
54
"shield",
54
55
];
55
56
56
57
pub struct AppAssets;
@@ -8,7 +8,7 @@ macro_rules! symbols {8
};8
};9
}9
}10
10
11
const SYMBOLS: [(&str, &[u8]); 42] = symbols![11
const SYMBOLS: [(&str, &[u8]); 43] = symbols![12
"done",12
"done",13
"done_all",13
"done_all",14
"keyboard_return",14
"keyboard_return",@@ -51,6 +51,7 @@ const SYMBOLS: [(&str, &[u8]); 42] = symbols![51
"fullscreen",51
"fullscreen",52
"spinner_track",52
"spinner_track",53
"spinner_arc",53
"spinner_arc",54
"shield",54
];55
];55
56
56
pub struct AppAssets;57
pub struct AppAssets;@@ -4,10 +4,11 @@ use calling::CameraDevice;
4
4
use calling::video_frame::bgra_from_i420;
5
5
use calling::video_pattern::{PatternKind, pattern_frame};
6
6
use calling::{
7
AudioDevice, BackgroundChoice, BreakoutMove, CallCommand, CallControl, CallHandle, CallState,
8
CallUpdate, Caller, CaptionEntry, CaptionState, ContentShare, DeviceChoice, DeviceLists,
9
EndReason, HoldState, IncomingRing, MeetingTarget, Progress, PublishedState, RaisedHand,
10
Reaction, RosterEntry, ShareKind, ShareSource, VideoKey, call_channel,
7
AudioDevice, BackgroundChoice, BreakoutMove, CallCommand, CallControl, CallHandle, CallHealth,
8
CallState, CallUpdate, Caller, CaptionEntry, CaptionState, ContentShare, DeviceChoice,
9
DeviceLists, EndReason, HealthSample, HoldState, IncomingRing, Limitation, MediaPath,
10
MeetingTarget, NetworkLevel, Progress, PublishedState, RaisedHand, Reaction, RosterEntry,
11
ShareKind, ShareSource, TransportDetails, VideoKey, call_channel,
11
12
};
12
13
13
14
use super::demo_scene::self_view;
@@ -86,6 +87,7 @@ pub enum DemoScene {
86
87
Held,
87
88
Breakout,
88
89
Whiteboard,
90
Network,
89
91
}
90
92
91
93
impl DemoScene {
@@ -98,12 +100,13 @@ impl DemoScene {
98
100
"held" => DemoScene::Held,
99
101
"breakout" => DemoScene::Breakout,
100
102
"whiteboard" => DemoScene::Whiteboard,
103
"network" => DemoScene::Network,
101
104
_ => return None,
102
105
})
103
106
}
104
107
105
108
pub fn is_one_to_one(self) -> bool {
106
matches!(self, DemoScene::Call | DemoScene::Hold | DemoScene::Held)
109
matches!(self, DemoScene::Call | DemoScene::Hold | DemoScene::Held | DemoScene::Network)
107
110
}
108
111
}
109
112
@@ -362,10 +365,35 @@ fn start_scene(control: &CallControl, scene: DemoScene) {
362
365
}
363
366
DemoScene::Hold => control.send(CallUpdate::Hold(HoldState::Local)),
364
367
DemoScene::Held => control.send(CallUpdate::Hold(HoldState::Remote)),
368
DemoScene::Network => control.send(CallUpdate::Health(poor_network_health())),
365
369
DemoScene::Call | DemoScene::Breakout | DemoScene::Whiteboard | DemoScene::Plain => {}
366
370
}
367
371
}
368
372
373
fn poor_network_health() -> CallHealth {
374
CallHealth {
375
level: NetworkLevel::Poor,
376
cpu_limited: false,
377
sample: HealthSample {
378
loss_percent: 7.2,
379
round_trip_ms: 310.,
380
jitter_ms: 38.,
381
sent_kbps: 420.,
382
received_kbps: 1180.,
383
limitation: Limitation::Bandwidth,
384
},
385
transport: TransportDetails {
386
dtls_state: "Connected".to_owned(),
387
tls_version: "FEFD".to_owned(),
388
dtls_cipher: "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256".to_owned(),
389
srtp_cipher: "AEAD_AES_128_GCM".to_owned(),
390
local_fingerprint: String::new(),
391
remote_fingerprint: String::new(),
392
},
393
path: MediaPath::Direct,
394
}
395
}
396
369
397
fn scene_tick(control: &CallControl, scene: DemoScene, ticks: u32, people: &[Person]) {
370
398
match scene {
371
399
DemoScene::Breakout if ticks == BREAKOUT_AT_TICKS => {
@@ -405,6 +433,7 @@ async fn speak_until_hangup(
405
433
let mut video_ticks = 0u32;
406
434
let mut sharing = false;
407
435
let mut camera_on = false;
436
let mut incoming_video = true;
408
437
let mut blur = false;
409
438
let mut captions_on = false;
410
439
let mut caption_ticks = 0usize;
@@ -424,7 +453,7 @@ async fn speak_until_hangup(
424
453
sharing = share_now;
425
454
control.send(CallUpdate::ScreenShare(sharer.clone().filter(|_| sharing)));
426
455
}
427
publish_demo_video(&control, &people, video_ticks, sharing, sharer.as_deref(), camera_on.then_some(blur));
456
publish_demo_video(&control, if incoming_video { people.as_slice() } else { &[] }, video_ticks, sharing, sharer.as_deref(), camera_on.then_some(blur));
428
457
video_ticks += 1;
429
458
}
430
459
_ = tick.tick() => {
@@ -532,6 +561,11 @@ async fn speak_until_hangup(
532
561
control.send(CallUpdate::Captions(if on { CaptionState::On } else { CaptionState::Off }));
533
562
}
534
563
Some(CallCommand::SetBackground(choice)) => blur = choice != BackgroundChoice::None,
564
Some(CallCommand::SetIncomingVideo(enabled)) => {
565
incoming_video = enabled;
566
people.iter().for_each(|(mri, _)| control.video.forget(&VideoKey::Person(mri.clone())));
567
control.send(CallUpdate::IncomingVideo(enabled));
568
}
535
569
Some(CallCommand::SetRecording { on, .. }) => control.send(CallUpdate::Recording(on)),
536
570
Some(CallCommand::ConsentToRecording) => control.send(CallUpdate::ConsentRequired(false)),
537
571
Some(CallCommand::Hold(hold)) => control.send(CallUpdate::Hold(if hold { HoldState::Local } else { HoldState::Active })),
@@ -4,10 +4,11 @@ use calling::CameraDevice;4
use calling::video_frame::bgra_from_i420;4
use calling::video_frame::bgra_from_i420;5
use calling::video_pattern::{PatternKind, pattern_frame};5
use calling::video_pattern::{PatternKind, pattern_frame};6
use calling::{6
use calling::{7
AudioDevice, BackgroundChoice, BreakoutMove, CallCommand, CallControl, CallHandle, CallState,7
AudioDevice, BackgroundChoice, BreakoutMove, CallCommand, CallControl, CallHandle, CallHealth,8
CallUpdate, Caller, CaptionEntry, CaptionState, ContentShare, DeviceChoice, DeviceLists,8
CallState, CallUpdate, Caller, CaptionEntry, CaptionState, ContentShare, DeviceChoice,9
EndReason, HoldState, IncomingRing, MeetingTarget, Progress, PublishedState, RaisedHand,9
DeviceLists, EndReason, HealthSample, HoldState, IncomingRing, Limitation, MediaPath,10
Reaction, RosterEntry, ShareKind, ShareSource, VideoKey, call_channel,10
MeetingTarget, NetworkLevel, Progress, PublishedState, RaisedHand, Reaction, RosterEntry,11
ShareKind, ShareSource, TransportDetails, VideoKey, call_channel,11
};12
};12
13
13
use super::demo_scene::self_view;14
use super::demo_scene::self_view;@@ -86,6 +87,7 @@ pub enum DemoScene {86
Held,87
Held,87
Breakout,88
Breakout,88
Whiteboard,89
Whiteboard,90
Network,89
}91
}90
92
91
impl DemoScene {93
impl DemoScene {@@ -98,12 +100,13 @@ impl DemoScene {98
"held" => DemoScene::Held,100
"held" => DemoScene::Held,99
"breakout" => DemoScene::Breakout,101
"breakout" => DemoScene::Breakout,100
"whiteboard" => DemoScene::Whiteboard,102
"whiteboard" => DemoScene::Whiteboard,103
"network" => DemoScene::Network,101
_ => return None,104
_ => return None,102
})105
})103
}106
}104
107
105
pub fn is_one_to_one(self) -> bool {108
pub fn is_one_to_one(self) -> bool {106
matches!(self, DemoScene::Call | DemoScene::Hold | DemoScene::Held)109
matches!(self, DemoScene::Call | DemoScene::Hold | DemoScene::Held | DemoScene::Network)107
}110
}108
}111
}109
112
@@ -362,10 +365,35 @@ fn start_scene(control: &CallControl, scene: DemoScene) {362
}365
}363
DemoScene::Hold => control.send(CallUpdate::Hold(HoldState::Local)),366
DemoScene::Hold => control.send(CallUpdate::Hold(HoldState::Local)),364
DemoScene::Held => control.send(CallUpdate::Hold(HoldState::Remote)),367
DemoScene::Held => control.send(CallUpdate::Hold(HoldState::Remote)),368
DemoScene::Network => control.send(CallUpdate::Health(poor_network_health())),365
DemoScene::Call | DemoScene::Breakout | DemoScene::Whiteboard | DemoScene::Plain => {}369
DemoScene::Call | DemoScene::Breakout | DemoScene::Whiteboard | DemoScene::Plain => {}366
}370
}367
}371
}368
372
373
fn poor_network_health() -> CallHealth {374
CallHealth {375
level: NetworkLevel::Poor,376
cpu_limited: false,377
sample: HealthSample {378
loss_percent: 7.2,379
round_trip_ms: 310.,380
jitter_ms: 38.,381
sent_kbps: 420.,382
received_kbps: 1180.,383
limitation: Limitation::Bandwidth,384
},385
transport: TransportDetails {386
dtls_state: "Connected".to_owned(),387
tls_version: "FEFD".to_owned(),388
dtls_cipher: "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256".to_owned(),389
srtp_cipher: "AEAD_AES_128_GCM".to_owned(),390
local_fingerprint: String::new(),391
remote_fingerprint: String::new(),392
},393
path: MediaPath::Direct,394
}395
}396
369
fn scene_tick(control: &CallControl, scene: DemoScene, ticks: u32, people: &[Person]) {397
fn scene_tick(control: &CallControl, scene: DemoScene, ticks: u32, people: &[Person]) {370
match scene {398
match scene {371
DemoScene::Breakout if ticks == BREAKOUT_AT_TICKS => {399
DemoScene::Breakout if ticks == BREAKOUT_AT_TICKS => {@@ -405,6 +433,7 @@ async fn speak_until_hangup(405
let mut video_ticks = 0u32;433
let mut video_ticks = 0u32;406
let mut sharing = false;434
let mut sharing = false;407
let mut camera_on = false;435
let mut camera_on = false;436
let mut incoming_video = true;408
let mut blur = false;437
let mut blur = false;409
let mut captions_on = false;438
let mut captions_on = false;410
let mut caption_ticks = 0usize;439
let mut caption_ticks = 0usize;@@ -424,7 +453,7 @@ async fn speak_until_hangup(424
sharing = share_now;453
sharing = share_now;425
control.send(CallUpdate::ScreenShare(sharer.clone().filter(|_| sharing)));454
control.send(CallUpdate::ScreenShare(sharer.clone().filter(|_| sharing)));426
}455
}427
publish_demo_video(&control, &people, video_ticks, sharing, sharer.as_deref(), camera_on.then_some(blur));456
publish_demo_video(&control, if incoming_video { people.as_slice() } else { &[] }, video_ticks, sharing, sharer.as_deref(), camera_on.then_some(blur));428
video_ticks += 1;457
video_ticks += 1;429
}458
}430
_ = tick.tick() => {459
_ = tick.tick() => {@@ -532,6 +561,11 @@ async fn speak_until_hangup(532
control.send(CallUpdate::Captions(if on { CaptionState::On } else { CaptionState::Off }));561
control.send(CallUpdate::Captions(if on { CaptionState::On } else { CaptionState::Off }));533
}562
}534
Some(CallCommand::SetBackground(choice)) => blur = choice != BackgroundChoice::None,563
Some(CallCommand::SetBackground(choice)) => blur = choice != BackgroundChoice::None,564
Some(CallCommand::SetIncomingVideo(enabled)) => {565
incoming_video = enabled;566
people.iter().for_each(|(mri, _)| control.video.forget(&VideoKey::Person(mri.clone())));567
control.send(CallUpdate::IncomingVideo(enabled));568
}535
Some(CallCommand::SetRecording { on, .. }) => control.send(CallUpdate::Recording(on)),569
Some(CallCommand::SetRecording { on, .. }) => control.send(CallUpdate::Recording(on)),536
Some(CallCommand::ConsentToRecording) => control.send(CallUpdate::ConsentRequired(false)),570
Some(CallCommand::ConsentToRecording) => control.send(CallUpdate::ConsentRequired(false)),537
Some(CallCommand::Hold(hold)) => control.send(CallUpdate::Hold(if hold { HoldState::Local } else { HoldState::Active })),571
Some(CallCommand::Hold(hold)) => control.send(CallUpdate::Hold(if hold { HoldState::Local } else { HoldState::Active })),@@ -3,7 +3,9 @@ use calling::{
3
3
};
4
4
use gpui_kit::*;
5
5
6
use super::background::BackgroundPick;
6
7
use super::demo::{DemoCall, start_demo_call};
8
use super::health::HealthBanner;
7
9
use super::model::{ActiveCall, BreakoutState, CallModel, ConsultCall, PendingMove};
8
10
use super::target::plan_for_chat;
9
11
use crate::app_state::AppState;
@@ -66,6 +68,22 @@ impl AppState {
66
68
self.send_call_command(CallCommand::Hold(hold));
67
69
}
68
70
71
pub fn set_call_incoming_video(&mut self, enabled: bool, cx: &mut Context<Self>) {
72
self.send_call_command(CallCommand::SetIncomingVideo(enabled));
73
cx.notify();
74
}
75
76
pub fn close_call_health_banner(&mut self, banner: HealthBanner, cx: &mut Context<Self>) {
77
if let Some(call) = self.call.as_mut() {
78
call.model.health.close_banner(banner);
79
cx.notify();
80
}
81
}
82
83
pub fn turn_off_call_effects(&mut self, cx: &mut Context<Self>) {
84
self.set_call_background(BackgroundPick::None, cx);
85
}
86
69
87
pub fn open_call_whiteboard(&mut self, cx: &mut Context<Self>) {
70
88
let Some(call) = self
71
89
.call
@@ -3,7 +3,9 @@ use calling::{3
};3
};4
use gpui_kit::*;4
use gpui_kit::*;5
5
6
use super::background::BackgroundPick;6
use super::demo::{DemoCall, start_demo_call};7
use super::demo::{DemoCall, start_demo_call};8
use super::health::HealthBanner;7
use super::model::{ActiveCall, BreakoutState, CallModel, ConsultCall, PendingMove};9
use super::model::{ActiveCall, BreakoutState, CallModel, ConsultCall, PendingMove};8
use super::target::plan_for_chat;10
use super::target::plan_for_chat;9
use crate::app_state::AppState;11
use crate::app_state::AppState;@@ -66,6 +68,22 @@ impl AppState {66
self.send_call_command(CallCommand::Hold(hold));68
self.send_call_command(CallCommand::Hold(hold));67
}69
}68
70
71
pub fn set_call_incoming_video(&mut self, enabled: bool, cx: &mut Context<Self>) {72
self.send_call_command(CallCommand::SetIncomingVideo(enabled));73
cx.notify();74
}75
76
pub fn close_call_health_banner(&mut self, banner: HealthBanner, cx: &mut Context<Self>) {77
if let Some(call) = self.call.as_mut() {78
call.model.health.close_banner(banner);79
cx.notify();80
}81
}82
83
pub fn turn_off_call_effects(&mut self, cx: &mut Context<Self>) {84
self.set_call_background(BackgroundPick::None, cx);85
}86
69
pub fn open_call_whiteboard(&mut self, cx: &mut Context<Self>) {87
pub fn open_call_whiteboard(&mut self, cx: &mut Context<Self>) {70
let Some(call) = self88
let Some(call) = self71
.call89
.call@@ -0,0 +1,185 @@
1
use calling::{CallHealth, HealthSample, MediaPath, NetworkLevel};
2
3
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4
pub enum HealthBanner {
5
Network,
6
Cpu,
7
}
8
9
#[derive(Debug, Clone)]
10
pub struct HealthState {
11
pub latest: Option<CallHealth>,
12
pub incoming_video: bool,
13
network_closed: bool,
14
cpu_closed: bool,
15
}
16
17
impl Default for HealthState {
18
fn default() -> Self {
19
HealthState {
20
latest: None,
21
incoming_video: true,
22
network_closed: false,
23
cpu_closed: false,
24
}
25
}
26
}
27
28
impl HealthState {
29
pub fn apply(&mut self, health: CallHealth) {
30
if health.level == NetworkLevel::Good {
31
self.network_closed = false;
32
}
33
if !health.cpu_limited {
34
self.cpu_closed = false;
35
}
36
self.latest = Some(health);
37
}
38
39
pub fn level(&self) -> NetworkLevel {
40
self.latest
41
.as_ref()
42
.map_or(NetworkLevel::Good, |health| health.level)
43
}
44
45
pub fn banner(&self, effects_on: bool) -> Option<HealthBanner> {
46
let health = self.latest.as_ref()?;
47
if health.level != NetworkLevel::Good && self.incoming_video && !self.network_closed {
48
Some(HealthBanner::Network)
49
} else if health.cpu_limited && effects_on && !self.cpu_closed {
50
Some(HealthBanner::Cpu)
51
} else {
52
None
53
}
54
}
55
56
pub fn close_banner(&mut self, banner: HealthBanner) {
57
match banner {
58
HealthBanner::Network => self.network_closed = true,
59
HealthBanner::Cpu => self.cpu_closed = true,
60
}
61
}
62
}
63
64
pub fn level_text(level: NetworkLevel) -> &'static str {
65
match level {
66
NetworkLevel::Good => "Good",
67
NetworkLevel::Poor => "Poor",
68
NetworkLevel::Bad => "Bad",
69
}
70
}
71
72
fn rate_text(kilobits_per_second: f64) -> String {
73
if kilobits_per_second >= 1000. {
74
format!("{:.1} Mbps", kilobits_per_second / 1000.)
75
} else {
76
format!("{kilobits_per_second:.0} kbps")
77
}
78
}
79
80
pub fn network_rows(sample: &HealthSample) -> Vec<(&'static str, String)> {
81
vec![
82
("Packet loss", format!("{:.1}%", sample.loss_percent)),
83
("Round trip", format!("{:.0} ms", sample.round_trip_ms)),
84
("Jitter", format!("{:.0} ms", sample.jitter_ms)),
85
("Sent", rate_text(sample.sent_kbps)),
86
("Received", rate_text(sample.received_kbps)),
87
]
88
}
89
90
pub fn transport_text(health: &CallHealth) -> String {
91
match health.transport.srtp_cipher.as_str() {
92
"" => "Transport: DTLS-SRTP".to_owned(),
93
cipher => format!("Transport: DTLS-SRTP ({cipher})"),
94
}
95
}
96
97
pub fn media_text(health: &CallHealth, peer_name: &str) -> Option<String> {
98
match health.path {
99
MediaPath::Direct => Some(format!("Media: direct to {peer_name}")),
100
MediaPath::Mixer => Some("Media: via Microsoft media server".to_owned()),
101
MediaPath::Pending => None,
102
}
103
}
104
105
#[cfg(test)]
106
mod tests {
107
use calling::TransportDetails;
108
109
use super::*;
110
111
fn health(level: NetworkLevel, cpu_limited: bool) -> CallHealth {
112
CallHealth {
113
level,
114
cpu_limited,
115
sample: HealthSample::default(),
116
transport: TransportDetails {
117
srtp_cipher: "AEAD_AES_128_GCM".into(),
118
..TransportDetails::default()
119
},
120
path: MediaPath::Direct,
121
}
122
}
123
124
#[test]
125
fn the_network_banner_shows_while_unstable_and_stays_closed_until_the_level_recovers() {
126
let mut state = HealthState::default();
127
assert_eq!(state.banner(true), None);
128
state.apply(health(NetworkLevel::Poor, false));
129
assert_eq!(state.banner(true), Some(HealthBanner::Network));
130
state.close_banner(HealthBanner::Network);
131
state.apply(health(NetworkLevel::Bad, false));
132
assert_eq!(state.banner(true), None);
133
state.apply(health(NetworkLevel::Good, false));
134
state.apply(health(NetworkLevel::Poor, false));
135
assert_eq!(state.banner(true), Some(HealthBanner::Network));
136
}
137
138
#[test]
139
fn the_network_banner_is_pointless_once_incoming_video_is_off() {
140
let mut state = HealthState::default();
141
state.apply(health(NetworkLevel::Poor, false));
142
state.incoming_video = false;
143
assert_eq!(state.banner(true), None);
144
}
145
146
#[test]
147
fn the_cpu_banner_needs_effects_to_turn_off_and_has_its_own_close() {
148
let mut state = HealthState::default();
149
state.apply(health(NetworkLevel::Good, true));
150
assert_eq!(state.banner(false), None);
151
assert_eq!(state.banner(true), Some(HealthBanner::Cpu));
152
state.close_banner(HealthBanner::Cpu);
153
state.apply(health(NetworkLevel::Good, true));
154
assert_eq!(state.banner(true), None);
155
state.apply(health(NetworkLevel::Good, false));
156
state.apply(health(NetworkLevel::Good, true));
157
assert_eq!(state.banner(true), Some(HealthBanner::Cpu));
158
}
159
160
#[test]
161
fn the_popover_names_the_transport_and_the_media_path_without_claiming_end_to_end() {
162
let mut found = health(NetworkLevel::Good, false);
163
assert_eq!(transport_text(&found), "Transport: DTLS-SRTP (AEAD_AES_128_GCM)");
164
assert_eq!(media_text(&found, "Mara").as_deref(), Some("Media: direct to Mara"));
165
found.path = MediaPath::Mixer;
166
assert_eq!(
167
media_text(&found, "Mara").as_deref(),
168
Some("Media: via Microsoft media server")
169
);
170
found.path = MediaPath::Pending;
171
assert_eq!(media_text(&found, "Mara"), None);
172
}
173
174
#[test]
175
fn rates_switch_to_megabits_from_a_thousand() {
176
let sample = HealthSample {
177
sent_kbps: 420.4,
178
received_kbps: 1180.,
179
..HealthSample::default()
180
};
181
let rows = network_rows(&sample);
182
assert_eq!(rows[3].1, "420 kbps");
183
assert_eq!(rows[4].1, "1.2 Mbps");
184
}
185
}
@@ -0,0 +1,185 @@1
use calling::{CallHealth, HealthSample, MediaPath, NetworkLevel};2
3
#[derive(Debug, Clone, Copy, PartialEq, Eq)]4
pub enum HealthBanner {5
Network,6
Cpu,7
}8
9
#[derive(Debug, Clone)]10
pub struct HealthState {11
pub latest: Option<CallHealth>,12
pub incoming_video: bool,13
network_closed: bool,14
cpu_closed: bool,15
}16
17
impl Default for HealthState {18
fn default() -> Self {19
HealthState {20
latest: None,21
incoming_video: true,22
network_closed: false,23
cpu_closed: false,24
}25
}26
}27
28
impl HealthState {29
pub fn apply(&mut self, health: CallHealth) {30
if health.level == NetworkLevel::Good {31
self.network_closed = false;32
}33
if !health.cpu_limited {34
self.cpu_closed = false;35
}36
self.latest = Some(health);37
}38
39
pub fn level(&self) -> NetworkLevel {40
self.latest41
.as_ref()42
.map_or(NetworkLevel::Good, |health| health.level)43
}44
45
pub fn banner(&self, effects_on: bool) -> Option<HealthBanner> {46
let health = self.latest.as_ref()?;47
if health.level != NetworkLevel::Good && self.incoming_video && !self.network_closed {48
Some(HealthBanner::Network)49
} else if health.cpu_limited && effects_on && !self.cpu_closed {50
Some(HealthBanner::Cpu)51
} else {52
None53
}54
}55
56
pub fn close_banner(&mut self, banner: HealthBanner) {57
match banner {58
HealthBanner::Network => self.network_closed = true,59
HealthBanner::Cpu => self.cpu_closed = true,60
}61
}62
}63
64
pub fn level_text(level: NetworkLevel) -> &'static str {65
match level {66
NetworkLevel::Good => "Good",67
NetworkLevel::Poor => "Poor",68
NetworkLevel::Bad => "Bad",69
}70
}71
72
fn rate_text(kilobits_per_second: f64) -> String {73
if kilobits_per_second >= 1000. {74
format!("{:.1} Mbps", kilobits_per_second / 1000.)75
} else {76
format!("{kilobits_per_second:.0} kbps")77
}78
}79
80
pub fn network_rows(sample: &HealthSample) -> Vec<(&'static str, String)> {81
vec![82
("Packet loss", format!("{:.1}%", sample.loss_percent)),83
("Round trip", format!("{:.0} ms", sample.round_trip_ms)),84
("Jitter", format!("{:.0} ms", sample.jitter_ms)),85
("Sent", rate_text(sample.sent_kbps)),86
("Received", rate_text(sample.received_kbps)),87
]88
}89
90
pub fn transport_text(health: &CallHealth) -> String {91
match health.transport.srtp_cipher.as_str() {92
"" => "Transport: DTLS-SRTP".to_owned(),93
cipher => format!("Transport: DTLS-SRTP ({cipher})"),94
}95
}96
97
pub fn media_text(health: &CallHealth, peer_name: &str) -> Option<String> {98
match health.path {99
MediaPath::Direct => Some(format!("Media: direct to {peer_name}")),100
MediaPath::Mixer => Some("Media: via Microsoft media server".to_owned()),101
MediaPath::Pending => None,102
}103
}104
105
#[cfg(test)]106
mod tests {107
use calling::TransportDetails;108
109
use super::*;110
111
fn health(level: NetworkLevel, cpu_limited: bool) -> CallHealth {112
CallHealth {113
level,114
cpu_limited,115
sample: HealthSample::default(),116
transport: TransportDetails {117
srtp_cipher: "AEAD_AES_128_GCM".into(),118
..TransportDetails::default()119
},120
path: MediaPath::Direct,121
}122
}123
124
#[test]125
fn the_network_banner_shows_while_unstable_and_stays_closed_until_the_level_recovers() {126
let mut state = HealthState::default();127
assert_eq!(state.banner(true), None);128
state.apply(health(NetworkLevel::Poor, false));129
assert_eq!(state.banner(true), Some(HealthBanner::Network));130
state.close_banner(HealthBanner::Network);131
state.apply(health(NetworkLevel::Bad, false));132
assert_eq!(state.banner(true), None);133
state.apply(health(NetworkLevel::Good, false));134
state.apply(health(NetworkLevel::Poor, false));135
assert_eq!(state.banner(true), Some(HealthBanner::Network));136
}137
138
#[test]139
fn the_network_banner_is_pointless_once_incoming_video_is_off() {140
let mut state = HealthState::default();141
state.apply(health(NetworkLevel::Poor, false));142
state.incoming_video = false;143
assert_eq!(state.banner(true), None);144
}145
146
#[test]147
fn the_cpu_banner_needs_effects_to_turn_off_and_has_its_own_close() {148
let mut state = HealthState::default();149
state.apply(health(NetworkLevel::Good, true));150
assert_eq!(state.banner(false), None);151
assert_eq!(state.banner(true), Some(HealthBanner::Cpu));152
state.close_banner(HealthBanner::Cpu);153
state.apply(health(NetworkLevel::Good, true));154
assert_eq!(state.banner(true), None);155
state.apply(health(NetworkLevel::Good, false));156
state.apply(health(NetworkLevel::Good, true));157
assert_eq!(state.banner(true), Some(HealthBanner::Cpu));158
}159
160
#[test]161
fn the_popover_names_the_transport_and_the_media_path_without_claiming_end_to_end() {162
let mut found = health(NetworkLevel::Good, false);163
assert_eq!(transport_text(&found), "Transport: DTLS-SRTP (AEAD_AES_128_GCM)");164
assert_eq!(media_text(&found, "Mara").as_deref(), Some("Media: direct to Mara"));165
found.path = MediaPath::Mixer;166
assert_eq!(167
media_text(&found, "Mara").as_deref(),168
Some("Media: via Microsoft media server")169
);170
found.path = MediaPath::Pending;171
assert_eq!(media_text(&found, "Mara"), None);172
}173
174
#[test]175
fn rates_switch_to_megabits_from_a_thousand() {176
let sample = HealthSample {177
sent_kbps: 420.4,178
received_kbps: 1180.,179
..HealthSample::default()180
};181
let rows = network_rows(&sample);182
assert_eq!(rows[3].1, "420 kbps");183
assert_eq!(rows[4].1, "1.2 Mbps");184
}185
}@@ -5,6 +5,7 @@ mod calendar;
5
5
mod demo;
6
6
mod demo_scene;
7
7
mod features;
8
mod health;
8
9
mod history;
9
10
mod join;
10
11
mod launcher;
@@ -26,6 +27,7 @@ pub use background::{
26
27
};
27
28
pub use demo::DemoScene;
28
29
pub use features::TransferCandidate;
30
pub use health::{HealthBanner, level_text, media_text, network_rows, transport_text};
29
31
pub use history::CallRow;
30
32
pub use launcher::CallLauncher;
31
33
pub use list::{
@@ -5,6 +5,7 @@ mod calendar;5
mod demo;5
mod demo;6
mod demo_scene;6
mod demo_scene;7
mod features;7
mod features;8
mod health;8
mod history;9
mod history;9
mod join;10
mod join;10
mod launcher;11
mod launcher;@@ -26,6 +27,7 @@ pub use background::{26
};27
};27
pub use demo::DemoScene;28
pub use demo::DemoScene;28
pub use features::TransferCandidate;29
pub use features::TransferCandidate;30
pub use health::{HealthBanner, level_text, media_text, network_rows, transport_text};29
pub use history::CallRow;31
pub use history::CallRow;30
pub use launcher::CallLauncher;32
pub use launcher::CallLauncher;31
pub use list::{33
pub use list::{@@ -9,6 +9,7 @@ use calling::{
9
9
use tokio::sync::mpsc::UnboundedSender;
10
10
11
11
use super::background::BackgroundPick;
12
use super::health::{HealthBanner, HealthState};
12
13
use super::pictures::CallPictures;
13
14
14
15
pub const TEST_CALL_TITLE: &str = "Test call";
@@ -281,6 +282,7 @@ pub struct CallModel {
281
282
pub recording: bool,
282
283
pub consent_required: bool,
283
284
pub hold: HoldState,
285
pub health: HealthState,
284
286
pub whiteboard: Option<ContentShare>,
285
287
pub breakout: Option<BreakoutState>,
286
288
pub main_meeting: Option<MeetingTarget>,
@@ -330,6 +332,7 @@ impl CallModel {
330
332
recording: false,
331
333
consent_required: false,
332
334
hold: HoldState::Active,
335
health: HealthState::default(),
333
336
whiteboard: None,
334
337
breakout: None,
335
338
main_meeting: None,
@@ -448,6 +451,8 @@ impl CallModel {
448
451
CallUpdate::Recording(on) => self.recording = on,
449
452
CallUpdate::ConsentRequired(required) => self.consent_required = required,
450
453
CallUpdate::Hold(hold) => self.hold = hold,
454
CallUpdate::Health(health) => self.health.apply(health),
455
CallUpdate::IncomingVideo(enabled) => self.health.incoming_video = enabled,
451
456
CallUpdate::Whiteboard(share) => self.whiteboard = share,
452
457
CallUpdate::BreakoutRoom { main } => self.main_meeting = Some(main),
453
458
CallUpdate::BlurTiming(_)
@@ -765,6 +770,10 @@ impl CallModel {
765
770
self.whiteboard.as_ref()?.url.as_deref()
766
771
}
767
772
773
pub fn health_banner(&self) -> Option<HealthBanner> {
774
self.health.banner(self.background != BackgroundPick::None)
775
}
776
768
777
pub fn is_one_to_one(&self) -> bool {
769
778
self.kind == CallKind::Direct
770
779
}
@@ -9,6 +9,7 @@ use calling::{9
use tokio::sync::mpsc::UnboundedSender;9
use tokio::sync::mpsc::UnboundedSender;10
10
11
use super::background::BackgroundPick;11
use super::background::BackgroundPick;12
use super::health::{HealthBanner, HealthState};12
use super::pictures::CallPictures;13
use super::pictures::CallPictures;13
14
14
pub const TEST_CALL_TITLE: &str = "Test call";15
pub const TEST_CALL_TITLE: &str = "Test call";@@ -281,6 +282,7 @@ pub struct CallModel {281
pub recording: bool,282
pub recording: bool,282
pub consent_required: bool,283
pub consent_required: bool,283
pub hold: HoldState,284
pub hold: HoldState,285
pub health: HealthState,284
pub whiteboard: Option<ContentShare>,286
pub whiteboard: Option<ContentShare>,285
pub breakout: Option<BreakoutState>,287
pub breakout: Option<BreakoutState>,286
pub main_meeting: Option<MeetingTarget>,288
pub main_meeting: Option<MeetingTarget>,@@ -330,6 +332,7 @@ impl CallModel {330
recording: false,332
recording: false,331
consent_required: false,333
consent_required: false,332
hold: HoldState::Active,334
hold: HoldState::Active,335
health: HealthState::default(),333
whiteboard: None,336
whiteboard: None,334
breakout: None,337
breakout: None,335
main_meeting: None,338
main_meeting: None,@@ -448,6 +451,8 @@ impl CallModel {448
CallUpdate::Recording(on) => self.recording = on,451
CallUpdate::Recording(on) => self.recording = on,449
CallUpdate::ConsentRequired(required) => self.consent_required = required,452
CallUpdate::ConsentRequired(required) => self.consent_required = required,450
CallUpdate::Hold(hold) => self.hold = hold,453
CallUpdate::Hold(hold) => self.hold = hold,454
CallUpdate::Health(health) => self.health.apply(health),455
CallUpdate::IncomingVideo(enabled) => self.health.incoming_video = enabled,451
CallUpdate::Whiteboard(share) => self.whiteboard = share,456
CallUpdate::Whiteboard(share) => self.whiteboard = share,452
CallUpdate::BreakoutRoom { main } => self.main_meeting = Some(main),457
CallUpdate::BreakoutRoom { main } => self.main_meeting = Some(main),453
CallUpdate::BlurTiming(_)458
CallUpdate::BlurTiming(_)@@ -765,6 +770,10 @@ impl CallModel {765
self.whiteboard.as_ref()?.url.as_deref()770
self.whiteboard.as_ref()?.url.as_deref()766
}771
}767
772
773
pub fn health_banner(&self) -> Option<HealthBanner> {774
self.health.banner(self.background != BackgroundPick::None)775
}776
768
pub fn is_one_to_one(&self) -> bool {777
pub fn is_one_to_one(&self) -> bool {769
self.kind == CallKind::Direct778
self.kind == CallKind::Direct770
}779
}@@ -0,0 +1,209 @@
1
use calling::NetworkLevel;
2
use gpui_kit::component::button::{Button, ButtonVariants as _};
3
use gpui_kit::component::popover::Popover;
4
use gpui_kit::component::{h_flex, v_flex};
5
use gpui_kit::*;
6
7
use super::call_organizer::pill;
8
use super::call_view::{BANNER_HEIGHT, MENU_WIDTH};
9
use super::widgets::symbol;
10
use crate::app_state::AppState;
11
use crate::call::{CallModel, HealthBanner, level_text, media_text, network_rows, transport_text};
12
use crate::theme;
13
14
const BAR_WIDTH: f32 = 3.;
15
const BAR_HEIGHTS: [f32; 3] = [6., 10., 14.];
16
const BAR_GAP: f32 = 2.;
17
const INACTIVE_BAR: f32 = 0.3;
18
const INDICATOR_HEIGHT: f32 = 28.;
19
const POPOVER_PADDING: f32 = 12.;
20
const BANNER_TEXT: f32 = 13.;
21
const NETWORK_TEXT: &str = "Your network is unstable. Turning off incoming video may help.";
22
const CPU_TEXT: &str = "Your computer is overloaded. Turning off video effects may help.";
23
24
fn dark_text() -> Hsla {
25
hsla(0., 0., 0.08, 1.)
26
}
27
28
fn level_color(level: NetworkLevel) -> Hsla {
29
match level {
30
NetworkLevel::Good => theme::text_muted(),
31
NetworkLevel::Poor => theme::amber(),
32
NetworkLevel::Bad => theme::red(),
33
}
34
}
35
36
fn lit_bars(level: NetworkLevel) -> usize {
37
match level {
38
NetworkLevel::Good => BAR_HEIGHTS.len(),
39
NetworkLevel::Poor => 2,
40
NetworkLevel::Bad => 1,
41
}
42
}
43
44
fn signal_bars(level: NetworkLevel) -> Div {
45
let lit = lit_bars(level);
46
h_flex()
47
.h(px(BAR_HEIGHTS[2]))
48
.gap(px(BAR_GAP))
49
.items_end()
50
.children(BAR_HEIGHTS.iter().enumerate().map(|(index, height)| {
51
let color = level_color(level);
52
div()
53
.w(px(BAR_WIDTH))
54
.h(px(*height))
55
.rounded(px(1.))
56
.bg(if index < lit {
57
color
58
} else {
59
color.opacity(INACTIVE_BAR)
60
})
61
}))
62
}
63
64
fn section_title(title: &'static str) -> Div {
65
div()
66
.text_size(px(12.))
67
.font_weight(FontWeight::SEMIBOLD)
68
.text_color(theme::text_muted())
69
.child(title)
70
}
71
72
fn row(label: &'static str, value: String) -> Div {
73
h_flex()
74
.w_full()
75
.justify_between()
76
.text_size(px(13.))
77
.child(div().text_color(theme::text_muted()).child(label))
78
.child(value)
79
}
80
81
fn health_popover(model: &CallModel) -> Div {
82
let health = model.health.latest.clone();
83
let level = model.health.level();
84
let network = match &health {
85
Some(health) => v_flex()
86
.gap(px(4.))
87
.child(row("Quality", level_text(level).to_owned()))
88
.children(
89
network_rows(&health.sample)
90
.into_iter()
91
.map(|(label, value)| row(label, value)),
92
),
93
None => v_flex().child(row("Quality", "Measuring...".to_owned())),
94
};
95
let transport = health.iter().flat_map(|health| {
96
[Some(transport_text(health)), media_text(health, &model.peer_name)]
97
.into_iter()
98
.flatten()
99
});
100
v_flex()
101
.debug_selector(|| "shell/islands/main/call-health-popover".into())
102
.w(px(MENU_WIDTH))
103
.p(px(POPOVER_PADDING))
104
.gap(px(12.))
105
.child(
106
div()
107
.text_size(px(15.))
108
.font_weight(FontWeight::SEMIBOLD)
109
.child("Call health"),
110
)
111
.child(v_flex().gap(px(6.)).child(section_title("Network")).child(network))
112
.child(
113
v_flex()
114
.gap(px(6.))
115
.child(section_title("Encryption"))
116
.child(
117
div()
118
.text_size(px(13.))
119
.font_weight(FontWeight::SEMIBOLD)
120
.child("Secured by Teams encryption"),
121
)
122
.children(transport.map(|line| {
123
div()
124
.text_size(px(13.))
125
.text_color(theme::text_muted())
126
.child(line)
127
})),
128
)
129
}
130
131
pub fn health_indicator(model: &CallModel) -> Option<AnyElement> {
132
model.health.latest.as_ref()?;
133
let level = model.health.level();
134
let model = model.clone();
135
Some(
136
Popover::new("call-health-popover")
137
.anchor(Anchor::TopLeft)
138
.offset(px(8.))
139
.trigger(
140
Button::new("call-health")
141
.ghost()
142
.p_0()
143
.h(px(INDICATOR_HEIGHT))
144
.px(px(6.))
145
.child(
146
h_flex()
147
.debug_selector(|| "shell/islands/main/call-health".into())
148
.gap(px(8.))
149
.items_center()
150
.child(signal_bars(level))
151
.child(symbol("shield", 18., theme::text_muted())),
152
),
153
)
154
.content(move |_, _, _| health_popover(&model))
155
.into_any_element(),
156
)
157
}
158
159
pub fn health_banner(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElement> {
160
let banner = model.health_banner()?;
161
let (text, action_label) = match banner {
162
HealthBanner::Network => (NETWORK_TEXT, "Turn off incoming video"),
163
HealthBanner::Cpu => (CPU_TEXT, "Turn off effects"),
164
};
165
let (action_app, close_app) = (app.clone(), app.clone());
166
Some(
167
h_flex()
168
.id("call-health-banner")
169
.debug_selector(|| "shell/islands/main/call-health-banner".into())
170
.w_full()
171
.h(px(BANNER_HEIGHT))
172
.flex_none()
173
.px(px(20.))
174
.gap(px(12.))
175
.items_center()
176
.justify_center()
177
.bg(theme::amber())
178
.text_color(dark_text())
179
.text_size(px(BANNER_TEXT))
180
.font_weight(FontWeight::SEMIBOLD)
181
.child(text)
182
.child(
183
pill("call-health-action", action_label, true).on_click(move |_, _, cx| {
184
action_app.update(cx, |state, cx| match banner {
185
HealthBanner::Network => state.set_call_incoming_video(false, cx),
186
HealthBanner::Cpu => state.turn_off_call_effects(cx),
187
})
188
}),
189
)
190
.child(
191
div()
192
.id("call-health-close")
193
.size(px(24.))
194
.flex()
195
.flex_none()
196
.items_center()
197
.justify_center()
198
.rounded_full()
199
.cursor_pointer()
200
.hover(|button| button.bg(dark_text().opacity(0.12)))
201
.child(symbol("close", 16., dark_text()))
202
.on_click(move |_, _, cx| {
203
close_app
204
.update(cx, |state, cx| state.close_call_health_banner(banner, cx))
205
}),
206
)
207
.into_any_element(),
208
)
209
}
@@ -0,0 +1,209 @@1
use calling::NetworkLevel;2
use gpui_kit::component::button::{Button, ButtonVariants as _};3
use gpui_kit::component::popover::Popover;4
use gpui_kit::component::{h_flex, v_flex};5
use gpui_kit::*;6
7
use super::call_organizer::pill;8
use super::call_view::{BANNER_HEIGHT, MENU_WIDTH};9
use super::widgets::symbol;10
use crate::app_state::AppState;11
use crate::call::{CallModel, HealthBanner, level_text, media_text, network_rows, transport_text};12
use crate::theme;13
14
const BAR_WIDTH: f32 = 3.;15
const BAR_HEIGHTS: [f32; 3] = [6., 10., 14.];16
const BAR_GAP: f32 = 2.;17
const INACTIVE_BAR: f32 = 0.3;18
const INDICATOR_HEIGHT: f32 = 28.;19
const POPOVER_PADDING: f32 = 12.;20
const BANNER_TEXT: f32 = 13.;21
const NETWORK_TEXT: &str = "Your network is unstable. Turning off incoming video may help.";22
const CPU_TEXT: &str = "Your computer is overloaded. Turning off video effects may help.";23
24
fn dark_text() -> Hsla {25
hsla(0., 0., 0.08, 1.)26
}27
28
fn level_color(level: NetworkLevel) -> Hsla {29
match level {30
NetworkLevel::Good => theme::text_muted(),31
NetworkLevel::Poor => theme::amber(),32
NetworkLevel::Bad => theme::red(),33
}34
}35
36
fn lit_bars(level: NetworkLevel) -> usize {37
match level {38
NetworkLevel::Good => BAR_HEIGHTS.len(),39
NetworkLevel::Poor => 2,40
NetworkLevel::Bad => 1,41
}42
}43
44
fn signal_bars(level: NetworkLevel) -> Div {45
let lit = lit_bars(level);46
h_flex()47
.h(px(BAR_HEIGHTS[2]))48
.gap(px(BAR_GAP))49
.items_end()50
.children(BAR_HEIGHTS.iter().enumerate().map(|(index, height)| {51
let color = level_color(level);52
div()53
.w(px(BAR_WIDTH))54
.h(px(*height))55
.rounded(px(1.))56
.bg(if index < lit {57
color58
} else {59
color.opacity(INACTIVE_BAR)60
})61
}))62
}63
64
fn section_title(title: &'static str) -> Div {65
div()66
.text_size(px(12.))67
.font_weight(FontWeight::SEMIBOLD)68
.text_color(theme::text_muted())69
.child(title)70
}71
72
fn row(label: &'static str, value: String) -> Div {73
h_flex()74
.w_full()75
.justify_between()76
.text_size(px(13.))77
.child(div().text_color(theme::text_muted()).child(label))78
.child(value)79
}80
81
fn health_popover(model: &CallModel) -> Div {82
let health = model.health.latest.clone();83
let level = model.health.level();84
let network = match &health {85
Some(health) => v_flex()86
.gap(px(4.))87
.child(row("Quality", level_text(level).to_owned()))88
.children(89
network_rows(&health.sample)90
.into_iter()91
.map(|(label, value)| row(label, value)),92
),93
None => v_flex().child(row("Quality", "Measuring...".to_owned())),94
};95
let transport = health.iter().flat_map(|health| {96
[Some(transport_text(health)), media_text(health, &model.peer_name)]97
.into_iter()98
.flatten()99
});100
v_flex()101
.debug_selector(|| "shell/islands/main/call-health-popover".into())102
.w(px(MENU_WIDTH))103
.p(px(POPOVER_PADDING))104
.gap(px(12.))105
.child(106
div()107
.text_size(px(15.))108
.font_weight(FontWeight::SEMIBOLD)109
.child("Call health"),110
)111
.child(v_flex().gap(px(6.)).child(section_title("Network")).child(network))112
.child(113
v_flex()114
.gap(px(6.))115
.child(section_title("Encryption"))116
.child(117
div()118
.text_size(px(13.))119
.font_weight(FontWeight::SEMIBOLD)120
.child("Secured by Teams encryption"),121
)122
.children(transport.map(|line| {123
div()124
.text_size(px(13.))125
.text_color(theme::text_muted())126
.child(line)127
})),128
)129
}130
131
pub fn health_indicator(model: &CallModel) -> Option<AnyElement> {132
model.health.latest.as_ref()?;133
let level = model.health.level();134
let model = model.clone();135
Some(136
Popover::new("call-health-popover")137
.anchor(Anchor::TopLeft)138
.offset(px(8.))139
.trigger(140
Button::new("call-health")141
.ghost()142
.p_0()143
.h(px(INDICATOR_HEIGHT))144
.px(px(6.))145
.child(146
h_flex()147
.debug_selector(|| "shell/islands/main/call-health".into())148
.gap(px(8.))149
.items_center()150
.child(signal_bars(level))151
.child(symbol("shield", 18., theme::text_muted())),152
),153
)154
.content(move |_, _, _| health_popover(&model))155
.into_any_element(),156
)157
}158
159
pub fn health_banner(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElement> {160
let banner = model.health_banner()?;161
let (text, action_label) = match banner {162
HealthBanner::Network => (NETWORK_TEXT, "Turn off incoming video"),163
HealthBanner::Cpu => (CPU_TEXT, "Turn off effects"),164
};165
let (action_app, close_app) = (app.clone(), app.clone());166
Some(167
h_flex()168
.id("call-health-banner")169
.debug_selector(|| "shell/islands/main/call-health-banner".into())170
.w_full()171
.h(px(BANNER_HEIGHT))172
.flex_none()173
.px(px(20.))174
.gap(px(12.))175
.items_center()176
.justify_center()177
.bg(theme::amber())178
.text_color(dark_text())179
.text_size(px(BANNER_TEXT))180
.font_weight(FontWeight::SEMIBOLD)181
.child(text)182
.child(183
pill("call-health-action", action_label, true).on_click(move |_, _, cx| {184
action_app.update(cx, |state, cx| match banner {185
HealthBanner::Network => state.set_call_incoming_video(false, cx),186
HealthBanner::Cpu => state.turn_off_call_effects(cx),187
})188
}),189
)190
.child(191
div()192
.id("call-health-close")193
.size(px(24.))194
.flex()195
.flex_none()196
.items_center()197
.justify_center()198
.rounded_full()199
.cursor_pointer()200
.hover(|button| button.bg(dark_text().opacity(0.12)))201
.child(symbol("close", 16., dark_text()))202
.on_click(move |_, _, cx| {203
close_app204
.update(cx, |state, cx| state.close_call_health_banner(banner, cx))205
}),206
)207
.into_any_element(),208
)209
}@@ -374,10 +374,26 @@ pub fn more_button(app: &Entity<AppState>, model: &CallModel) -> Option<AnyEleme
374
374
375
375
fn more_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> PopupMenu {
376
376
let popup = popup.min_w(px(MENU_WIDTH));
377
if model.is_one_to_one() {
378
return one_to_one_items(popup, app, model);
377
let popup = if model.is_one_to_one() {
378
one_to_one_items(popup, app, model)
379
} else {
380
meeting_items(popup, app, model)
381
};
382
incoming_video_item(popup, app, model)
383
}
384
385
fn incoming_video_item(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> PopupMenu {
386
if model.health.incoming_video {
387
return popup;
379
388
}
380
meeting_items(popup, app, model)
389
let app = app.clone();
390
popup.item(
391
PopupMenuItem::new("Turn on incoming video")
392
.icon(IconName::Video)
393
.on_click(move |_, _, cx| {
394
app.update(cx, |state, cx| state.set_call_incoming_video(true, cx))
395
}),
396
)
381
397
}
382
398
383
399
fn one_to_one_items(mut popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> PopupMenu {
@@ -374,10 +374,26 @@ pub fn more_button(app: &Entity<AppState>, model: &CallModel) -> Option<AnyEleme374
374
375
fn more_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> PopupMenu {375
fn more_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> PopupMenu {376
let popup = popup.min_w(px(MENU_WIDTH));376
let popup = popup.min_w(px(MENU_WIDTH));377
if model.is_one_to_one() {377
let popup = if model.is_one_to_one() {378
return one_to_one_items(popup, app, model);378
one_to_one_items(popup, app, model)379
} else {380
meeting_items(popup, app, model)381
};382
incoming_video_item(popup, app, model)383
}384
385
fn incoming_video_item(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> PopupMenu {386
if model.health.incoming_video {387
return popup;379
}388
}380
meeting_items(popup, app, model)389
let app = app.clone();390
popup.item(391
PopupMenuItem::new("Turn on incoming video")392
.icon(IconName::Video)393
.on_click(move |_, _, cx| {394
app.update(cx, |state, cx| state.set_call_incoming_video(true, cx))395
}),396
)381
}397
}382
398
383
fn one_to_one_items(mut popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> PopupMenu {399
fn one_to_one_items(mut popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> PopupMenu {@@ -20,6 +20,7 @@ use super::call_extras::{
20
20
BackgroundMenu, consent_overlay, consult_banner, hold_panel, recording_chip, return_button,
21
21
room_chip, whiteboard_stage,
22
22
};
23
use super::call_health::{health_banner, health_indicator};
23
24
use super::call_organizer::{
24
25
camera_menu_button, captions_hint_chip, captions_overlay, chevron_button, lobby_banner,
25
26
more_button, pin_chip, render_focus_stage, spotlight_chip, with_tile_menu,
@@ -1038,6 +1039,7 @@ pub fn render_call_view(
1038
1039
.text_color(status_color)
1039
1040
.child(status),
1040
1041
)
1042
.children(health_indicator(model))
1041
1043
.children(recording_chip(model))
1042
1044
.children(room_chip(model))
1043
1045
.child(div().flex_1())
@@ -1118,6 +1120,7 @@ pub fn render_call_view(
1118
1120
.bg(theme::surface())
1119
1121
.child(header)
1120
1122
.children(lobby_banner(app, model))
1123
.children(health_banner(app, model))
1121
1124
.children(sharing_banner(app, model, state.call_share_sound))
1122
1125
.children(consult_banner(app, state))
1123
1126
.child(match stage {
@@ -20,6 +20,7 @@ use super::call_extras::{20
BackgroundMenu, consent_overlay, consult_banner, hold_panel, recording_chip, return_button,20
BackgroundMenu, consent_overlay, consult_banner, hold_panel, recording_chip, return_button,21
room_chip, whiteboard_stage,21
room_chip, whiteboard_stage,22
};22
};23
use super::call_health::{health_banner, health_indicator};23
use super::call_organizer::{24
use super::call_organizer::{24
camera_menu_button, captions_hint_chip, captions_overlay, chevron_button, lobby_banner,25
camera_menu_button, captions_hint_chip, captions_overlay, chevron_button, lobby_banner,25
more_button, pin_chip, render_focus_stage, spotlight_chip, with_tile_menu,26
more_button, pin_chip, render_focus_stage, spotlight_chip, with_tile_menu,@@ -1038,6 +1039,7 @@ pub fn render_call_view(1038
.text_color(status_color)1039
.text_color(status_color)1039
.child(status),1040
.child(status),1040
)1041
)1042
.children(health_indicator(model))1041
.children(recording_chip(model))1043
.children(recording_chip(model))1042
.children(room_chip(model))1044
.children(room_chip(model))1043
.child(div().flex_1())1045
.child(div().flex_1())@@ -1118,6 +1120,7 @@ pub fn render_call_view(1118
.bg(theme::surface())1120
.bg(theme::surface())1119
.child(header)1121
.child(header)1120
.children(lobby_banner(app, model))1122
.children(lobby_banner(app, model))1123
.children(health_banner(app, model))1121
.children(sharing_banner(app, model, state.call_share_sound))1124
.children(sharing_banner(app, model, state.call_share_sound))1122
.children(consult_banner(app, state))1125
.children(consult_banner(app, state))1123
.child(match stage {1126
.child(match stage {@@ -5,6 +5,7 @@ pub mod attachments;
5
5
pub mod avatar;
6
6
pub mod call_controls;
7
7
pub mod call_extras;
8
pub mod call_health;
8
9
pub mod call_mini;
9
10
pub mod call_mini_window;
10
11
pub mod call_organizer;
@@ -5,6 +5,7 @@ pub mod attachments;5
pub mod avatar;5
pub mod avatar;6
pub mod call_controls;6
pub mod call_controls;7
pub mod call_extras;7
pub mod call_extras;8
pub mod call_health;8
pub mod call_mini;9
pub mod call_mini;9
pub mod call_mini_window;10
pub mod call_mini_window;10
pub mod call_organizer;11
pub mod call_organizer;@@ -33,6 +33,7 @@ use crate::devices::{self, DeviceChoice};
33
33
use crate::end::EndKind;
34
34
use crate::engine::{CallEngine, EngineConfig, Inner};
35
35
use crate::error::{Error, Result};
36
use crate::health::{CallHealth, HealthCounters, HealthSampler, QualityTracker, TransportDetails, health_from_stats};
36
37
use crate::hold::{HoldState, INACTIVE, MediaLine, accepted_modalities, is_hold, rewrite_directions};
37
38
use crate::mute::{MuteCommand, MuteEffect};
38
39
use crate::push::CallNotification;
@@ -76,6 +77,7 @@ const DATA_CHANNEL_LABEL: &str = "main-channel";
76
77
pub const DATA_CHANNEL_ENV: &str = "CALLING_DATA_CHANNEL";
77
78
const CAPTION_START_LIMIT: Duration = Duration::from_secs(40);
78
79
const BLUR_TIMING_EVERY_TICKS: u32 = TICKS_PER_SECOND * 2;
80
const HEALTH_EVERY_TICKS: u32 = TICKS_PER_SECOND * 2;
79
81
const BOT_PREFIX: &str = "28:";
80
82
const RECORDING_START_LIMIT: Duration = Duration::from_secs(40);
81
83
const SAME_PEER_ANSWER_LIMIT: Duration = Duration::from_secs(15);
@@ -797,6 +799,8 @@ async fn drive(
797
799
let mut lobby = false;
798
800
let mut previous_packets = 0u64;
799
801
let mut ticks = 0u32;
802
let mut health_sampler = HealthSampler::default();
803
let mut quality_tracker = QualityTracker::default();
800
804
let mut second = 0u32;
801
805
let echo_thread = thread_id;
802
806
let mut video = VideoReceive::new(own_mri.clone(), VideoRouter::default());
@@ -1517,6 +1521,16 @@ async fn drive(
1517
1521
});
1518
1522
}
1519
1523
Some(CallCommand::SetBackground(choice)) => apply_background(choice, &local_video, control, timeline).await,
1524
Some(CallCommand::SetIncomingVideo(enabled)) => {
1525
video.set_incoming_enabled(enabled);
1526
if let (Some(mid), Some(mri)) = (&direct_video_mid, &peer_mri) {
1527
let key = VideoKey::Person(mri.clone());
1528
control.video.forget(&key);
1529
video.router().set(mid, enabled.then_some(key));
1530
}
1531
send_receive_change(control, video.reselect(&roster));
1532
control.send(CallUpdate::IncomingVideo(enabled));
1533
}
1520
1534
Some(CallCommand::SendReaction(reaction)) => {
1521
1535
if let Err(error) = remote.signaling.send_reaction(&remote.conversation, &remote.participant, reaction).await {
1522
1536
timeline.record("reaction failed", error.to_string());
@@ -1561,6 +1575,19 @@ async fn drive(
1561
1575
{
1562
1576
control.send(CallUpdate::BlurTiming(average_ms));
1563
1577
}
1578
if ticks.is_multiple_of(HEALTH_EVERY_TICKS)
1579
&& snapshot.selected_pair.is_some()
1580
&& let Some(sample) = health_sampler.sample(std::time::Instant::now(), snapshot.health)
1581
{
1582
let quality = quality_tracker.observe(std::time::Instant::now(), &sample);
1583
control.send(CallUpdate::Health(CallHealth {
1584
level: quality.level,
1585
cpu_limited: quality.cpu_limited,
1586
sample,
1587
transport: snapshot.transport.clone(),
1588
path: negotiator.path(),
1589
}));
1590
}
1564
1591
let local_level = if muted && share_audio.is_none() { 0.0 } else { snapshot.local_level as f32 };
1565
1592
control.send(CallUpdate::Levels { local: local_level, remote: snapshot.audio_level as f32 });
1566
1593
if snapshot.selected_pair.is_some() {
@@ -2328,6 +2355,8 @@ struct StatsSnapshot {
2328
2355
dtls_cipher: String,
2329
2356
srtp_cipher: String,
2330
2357
selected_pair: Option<String>,
2358
health: HealthCounters,
2359
transport: TransportDetails,
2331
2360
}
2332
2361
2333
2362
async fn collect_stats(peer: &PeerConnection) -> StatsSnapshot {
@@ -2335,6 +2364,7 @@ async fn collect_stats(peer: &PeerConnection) -> StatsSnapshot {
2335
2364
return StatsSnapshot::default();
2336
2365
};
2337
2366
let mut snapshot = StatsSnapshot::default();
2367
(snapshot.health, snapshot.transport) = health_from_stats(&stats);
2338
2368
let mut selected_pair_id = None;
2339
2369
for entry in &stats {
2340
2370
match entry {
@@ -33,6 +33,7 @@ use crate::devices::{self, DeviceChoice};33
use crate::end::EndKind;33
use crate::end::EndKind;34
use crate::engine::{CallEngine, EngineConfig, Inner};34
use crate::engine::{CallEngine, EngineConfig, Inner};35
use crate::error::{Error, Result};35
use crate::error::{Error, Result};36
use crate::health::{CallHealth, HealthCounters, HealthSampler, QualityTracker, TransportDetails, health_from_stats};36
use crate::hold::{HoldState, INACTIVE, MediaLine, accepted_modalities, is_hold, rewrite_directions};37
use crate::hold::{HoldState, INACTIVE, MediaLine, accepted_modalities, is_hold, rewrite_directions};37
use crate::mute::{MuteCommand, MuteEffect};38
use crate::mute::{MuteCommand, MuteEffect};38
use crate::push::CallNotification;39
use crate::push::CallNotification;@@ -76,6 +77,7 @@ const DATA_CHANNEL_LABEL: &str = "main-channel";76
pub const DATA_CHANNEL_ENV: &str = "CALLING_DATA_CHANNEL";77
pub const DATA_CHANNEL_ENV: &str = "CALLING_DATA_CHANNEL";77
const CAPTION_START_LIMIT: Duration = Duration::from_secs(40);78
const CAPTION_START_LIMIT: Duration = Duration::from_secs(40);78
const BLUR_TIMING_EVERY_TICKS: u32 = TICKS_PER_SECOND * 2;79
const BLUR_TIMING_EVERY_TICKS: u32 = TICKS_PER_SECOND * 2;80
const HEALTH_EVERY_TICKS: u32 = TICKS_PER_SECOND * 2;79
const BOT_PREFIX: &str = "28:";81
const BOT_PREFIX: &str = "28:";80
const RECORDING_START_LIMIT: Duration = Duration::from_secs(40);82
const RECORDING_START_LIMIT: Duration = Duration::from_secs(40);81
const SAME_PEER_ANSWER_LIMIT: Duration = Duration::from_secs(15);83
const SAME_PEER_ANSWER_LIMIT: Duration = Duration::from_secs(15);@@ -797,6 +799,8 @@ async fn drive(797
let mut lobby = false;799
let mut lobby = false;798
let mut previous_packets = 0u64;800
let mut previous_packets = 0u64;799
let mut ticks = 0u32;801
let mut ticks = 0u32;802
let mut health_sampler = HealthSampler::default();803
let mut quality_tracker = QualityTracker::default();800
let mut second = 0u32;804
let mut second = 0u32;801
let echo_thread = thread_id;805
let echo_thread = thread_id;802
let mut video = VideoReceive::new(own_mri.clone(), VideoRouter::default());806
let mut video = VideoReceive::new(own_mri.clone(), VideoRouter::default());@@ -1517,6 +1521,16 @@ async fn drive(1517
});1521
});1518
}1522
}1519
Some(CallCommand::SetBackground(choice)) => apply_background(choice, &local_video, control, timeline).await,1523
Some(CallCommand::SetBackground(choice)) => apply_background(choice, &local_video, control, timeline).await,1524
Some(CallCommand::SetIncomingVideo(enabled)) => {1525
video.set_incoming_enabled(enabled);1526
if let (Some(mid), Some(mri)) = (&direct_video_mid, &peer_mri) {1527
let key = VideoKey::Person(mri.clone());1528
control.video.forget(&key);1529
video.router().set(mid, enabled.then_some(key));1530
}1531
send_receive_change(control, video.reselect(&roster));1532
control.send(CallUpdate::IncomingVideo(enabled));1533
}1520
Some(CallCommand::SendReaction(reaction)) => {1534
Some(CallCommand::SendReaction(reaction)) => {1521
if let Err(error) = remote.signaling.send_reaction(&remote.conversation, &remote.participant, reaction).await {1535
if let Err(error) = remote.signaling.send_reaction(&remote.conversation, &remote.participant, reaction).await {1522
timeline.record("reaction failed", error.to_string());1536
timeline.record("reaction failed", error.to_string());@@ -1561,6 +1575,19 @@ async fn drive(1561
{1575
{1562
control.send(CallUpdate::BlurTiming(average_ms));1576
control.send(CallUpdate::BlurTiming(average_ms));1563
}1577
}1578
if ticks.is_multiple_of(HEALTH_EVERY_TICKS)1579
&& snapshot.selected_pair.is_some()1580
&& let Some(sample) = health_sampler.sample(std::time::Instant::now(), snapshot.health)1581
{1582
let quality = quality_tracker.observe(std::time::Instant::now(), &sample);1583
control.send(CallUpdate::Health(CallHealth {1584
level: quality.level,1585
cpu_limited: quality.cpu_limited,1586
sample,1587
transport: snapshot.transport.clone(),1588
path: negotiator.path(),1589
}));1590
}1564
let local_level = if muted && share_audio.is_none() { 0.0 } else { snapshot.local_level as f32 };1591
let local_level = if muted && share_audio.is_none() { 0.0 } else { snapshot.local_level as f32 };1565
control.send(CallUpdate::Levels { local: local_level, remote: snapshot.audio_level as f32 });1592
control.send(CallUpdate::Levels { local: local_level, remote: snapshot.audio_level as f32 });1566
if snapshot.selected_pair.is_some() {1593
if snapshot.selected_pair.is_some() {@@ -2328,6 +2355,8 @@ struct StatsSnapshot {2328
dtls_cipher: String,2355
dtls_cipher: String,2329
srtp_cipher: String,2356
srtp_cipher: String,2330
selected_pair: Option<String>,2357
selected_pair: Option<String>,2358
health: HealthCounters,2359
transport: TransportDetails,2331
}2360
}2332
2361
2333
async fn collect_stats(peer: &PeerConnection) -> StatsSnapshot {2362
async fn collect_stats(peer: &PeerConnection) -> StatsSnapshot {@@ -2335,6 +2364,7 @@ async fn collect_stats(peer: &PeerConnection) -> StatsSnapshot {2335
return StatsSnapshot::default();2364
return StatsSnapshot::default();2336
};2365
};2337
let mut snapshot = StatsSnapshot::default();2366
let mut snapshot = StatsSnapshot::default();2367
(snapshot.health, snapshot.transport) = health_from_stats(&stats);2338
let mut selected_pair_id = None;2368
let mut selected_pair_id = None;2339
for entry in &stats {2369
for entry in &stats {2340
match entry {2370
match entry {@@ -8,6 +8,7 @@ use crate::breakout::BreakoutMove;
8
8
use crate::captions::{CaptionEntry, CaptionState};
9
9
use crate::devices::{DeviceChoice, DeviceLists};
10
10
use crate::error::{Error, Result};
11
use crate::health::CallHealth;
11
12
use crate::hold::HoldState;
12
13
use crate::mute::MuteCommand;
13
14
use crate::reaction::Reaction;
@@ -44,6 +45,7 @@ pub enum CallCommand {
44
45
RemoveParticipant { mri: String },
45
46
SetCaptions(bool),
46
47
SetBackground(BackgroundChoice),
48
SetIncomingVideo(bool),
47
49
SendReaction(Reaction),
48
50
SetRecording { on: bool, title: String },
49
51
ConsentToRecording,
@@ -86,6 +88,8 @@ pub enum CallUpdate {
86
88
Captions(CaptionState),
87
89
Caption(CaptionEntry),
88
90
BlurTiming(f32),
91
Health(CallHealth),
92
IncomingVideo(bool),
89
93
Recording(bool),
90
94
ConsentRequired(bool),
91
95
Hold(HoldState),
@@ -8,6 +8,7 @@ use crate::breakout::BreakoutMove;8
use crate::captions::{CaptionEntry, CaptionState};8
use crate::captions::{CaptionEntry, CaptionState};9
use crate::devices::{DeviceChoice, DeviceLists};9
use crate::devices::{DeviceChoice, DeviceLists};10
use crate::error::{Error, Result};10
use crate::error::{Error, Result};11
use crate::health::CallHealth;11
use crate::hold::HoldState;12
use crate::hold::HoldState;12
use crate::mute::MuteCommand;13
use crate::mute::MuteCommand;13
use crate::reaction::Reaction;14
use crate::reaction::Reaction;@@ -44,6 +45,7 @@ pub enum CallCommand {44
RemoveParticipant { mri: String },45
RemoveParticipant { mri: String },45
SetCaptions(bool),46
SetCaptions(bool),46
SetBackground(BackgroundChoice),47
SetBackground(BackgroundChoice),48
SetIncomingVideo(bool),47
SendReaction(Reaction),49
SendReaction(Reaction),48
SetRecording { on: bool, title: String },50
SetRecording { on: bool, title: String },49
ConsentToRecording,51
ConsentToRecording,@@ -86,6 +88,8 @@ pub enum CallUpdate {86
Captions(CaptionState),88
Captions(CaptionState),87
Caption(CaptionEntry),89
Caption(CaptionEntry),88
BlurTiming(f32),90
BlurTiming(f32),91
Health(CallHealth),92
IncomingVideo(bool),89
Recording(bool),93
Recording(bool),90
ConsentRequired(bool),94
ConsentRequired(bool),91
Hold(HoldState),95
Hold(HoldState),@@ -0,0 +1,453 @@
1
use std::collections::VecDeque;
2
use std::time::{Duration, Instant};
3
4
use libwebrtc::stats::{QualityLimitationReason, RtcStats};
5
6
use crate::renegotiation::MediaPath;
7
8
const SUSTAIN: Duration = Duration::from_secs(5);
9
const RECOVERY: Duration = Duration::from_secs(10);
10
const LIMIT_WINDOW: Duration = Duration::from_secs(10);
11
const LIMIT_SHARE: f32 = 0.5;
12
const POOR_LOSS_PERCENT: f64 = 5.;
13
const POOR_ROUND_TRIP_MS: f64 = 400.;
14
const POOR_JITTER_MS: f64 = 30.;
15
const BAD_LOSS_PERCENT: f64 = 10.;
16
const BAD_ROUND_TRIP_MS: f64 = 500.;
17
18
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
19
pub enum NetworkLevel {
20
Good,
21
Poor,
22
Bad,
23
}
24
25
impl NetworkLevel {
26
fn better(self) -> Self {
27
match self {
28
NetworkLevel::Bad => NetworkLevel::Poor,
29
_ => NetworkLevel::Good,
30
}
31
}
32
}
33
34
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
35
pub enum Limitation {
36
#[default]
37
None,
38
Cpu,
39
Bandwidth,
40
}
41
42
#[derive(Debug, Clone, Copy, PartialEq, Default)]
43
pub struct HealthSample {
44
pub loss_percent: f64,
45
pub round_trip_ms: f64,
46
pub jitter_ms: f64,
47
pub sent_kbps: f64,
48
pub received_kbps: f64,
49
pub limitation: Limitation,
50
}
51
52
impl HealthSample {
53
fn is_bad(&self) -> bool {
54
self.loss_percent > BAD_LOSS_PERCENT || self.round_trip_ms > BAD_ROUND_TRIP_MS
55
}
56
57
fn is_poor(&self) -> bool {
58
self.is_bad()
59
|| self.loss_percent > POOR_LOSS_PERCENT
60
|| self.round_trip_ms > POOR_ROUND_TRIP_MS
61
|| self.jitter_ms > POOR_JITTER_MS
62
}
63
64
fn instant_level(&self) -> NetworkLevel {
65
if self.is_bad() {
66
NetworkLevel::Bad
67
} else if self.is_poor() || self.limitation == Limitation::Bandwidth {
68
NetworkLevel::Poor
69
} else {
70
NetworkLevel::Good
71
}
72
}
73
}
74
75
#[derive(Debug, Clone, PartialEq, Eq, Default)]
76
pub struct TransportDetails {
77
pub dtls_state: String,
78
pub tls_version: String,
79
pub dtls_cipher: String,
80
pub srtp_cipher: String,
81
pub local_fingerprint: String,
82
pub remote_fingerprint: String,
83
}
84
85
#[derive(Debug, Clone, PartialEq)]
86
pub struct CallHealth {
87
pub level: NetworkLevel,
88
pub cpu_limited: bool,
89
pub sample: HealthSample,
90
pub transport: TransportDetails,
91
pub path: MediaPath,
92
}
93
94
#[derive(Debug, Clone, Copy, PartialEq)]
95
pub struct Quality {
96
pub level: NetworkLevel,
97
pub cpu_limited: bool,
98
}
99
100
pub struct QualityTracker {
101
level: NetworkLevel,
102
poor_since: Option<Instant>,
103
bad_since: Option<Instant>,
104
recovering_since: Option<Instant>,
105
limits: VecDeque<(Instant, Limitation)>,
106
}
107
108
impl Default for QualityTracker {
109
fn default() -> Self {
110
QualityTracker {
111
level: NetworkLevel::Good,
112
poor_since: None,
113
bad_since: None,
114
recovering_since: None,
115
limits: VecDeque::new(),
116
}
117
}
118
}
119
120
fn run_since(since: &mut Option<Instant>, holds: bool, now: Instant) -> bool {
121
if !holds {
122
*since = None;
123
return false;
124
}
125
now.duration_since(*since.get_or_insert(now)) >= SUSTAIN
126
}
127
128
impl QualityTracker {
129
pub fn observe(&mut self, now: Instant, sample: &HealthSample) -> Quality {
130
self.limits.push_back((now, sample.limitation));
131
while self.limits.front().is_some_and(|(at, _)| now.duration_since(*at) > LIMIT_WINDOW) {
132
self.limits.pop_front();
133
}
134
let bad = run_since(&mut self.bad_since, sample.is_bad(), now);
135
let poor = run_since(&mut self.poor_since, sample.is_poor(), now);
136
let target = if bad {
137
NetworkLevel::Bad
138
} else if poor || self.share_of(Limitation::Bandwidth, now) > LIMIT_SHARE {
139
NetworkLevel::Poor
140
} else {
141
NetworkLevel::Good
142
};
143
if target > self.level {
144
self.level = target;
145
self.recovering_since = None;
146
} else if sample.instant_level() < self.level {
147
let since = *self.recovering_since.get_or_insert(now);
148
if now.duration_since(since) >= RECOVERY {
149
self.level = self.level.better();
150
self.recovering_since = None;
151
}
152
} else {
153
self.recovering_since = None;
154
}
155
Quality { level: self.level, cpu_limited: self.share_of(Limitation::Cpu, now) > LIMIT_SHARE }
156
}
157
158
fn share_of(&self, limitation: Limitation, now: Instant) -> f32 {
159
let spans_window = self.limits.front().is_some_and(|(at, _)| now.duration_since(*at) >= SUSTAIN);
160
if !spans_window {
161
return 0.;
162
}
163
let matching = self.limits.iter().filter(|(_, found)| *found == limitation).count();
164
matching as f32 / self.limits.len() as f32
165
}
166
}
167
168
#[derive(Debug, Clone, Copy, PartialEq, Default)]
169
pub struct HealthCounters {
170
pub packets_received: u64,
171
pub packets_lost: u64,
172
pub bytes_sent: u64,
173
pub bytes_received: u64,
174
pub jitter_ms: f64,
175
pub round_trip_ms: f64,
176
pub outbound_loss_percent: f64,
177
pub limitation: Limitation,
178
}
179
180
#[derive(Default)]
181
pub struct HealthSampler {
182
previous: Option<(Instant, HealthCounters)>,
183
}
184
185
impl HealthSampler {
186
pub fn sample(&mut self, now: Instant, counters: HealthCounters) -> Option<HealthSample> {
187
let (then, before) = self.previous.replace((now, counters))?;
188
let seconds = now.duration_since(then).as_secs_f64();
189
if seconds <= 0. {
190
return None;
191
}
192
let received = counters.packets_received.saturating_sub(before.packets_received);
193
let lost = counters.packets_lost.saturating_sub(before.packets_lost);
194
let inbound_loss_percent = if received + lost == 0 { 0. } else { lost as f64 * 100. / (received + lost) as f64 };
195
let kbps = |after: u64, before: u64| after.saturating_sub(before) as f64 * 8. / seconds / 1000.;
196
Some(HealthSample {
197
loss_percent: inbound_loss_percent.max(counters.outbound_loss_percent),
198
round_trip_ms: counters.round_trip_ms,
199
jitter_ms: counters.jitter_ms,
200
sent_kbps: kbps(counters.bytes_sent, before.bytes_sent),
201
received_kbps: kbps(counters.bytes_received, before.bytes_received),
202
limitation: counters.limitation,
203
})
204
}
205
}
206
207
fn limitation_of(reason: QualityLimitationReason) -> Limitation {
208
match reason {
209
QualityLimitationReason::Cpu => Limitation::Cpu,
210
QualityLimitationReason::Bandwidth => Limitation::Bandwidth,
211
_ => Limitation::None,
212
}
213
}
214
215
pub fn health_from_stats(stats: &[RtcStats]) -> (HealthCounters, TransportDetails) {
216
let mut counters = HealthCounters::default();
217
let mut transport = TransportDetails::default();
218
let mut certificate_ids = (String::new(), String::new());
219
let mut selected_pair_id = String::new();
220
let mut remote_round_trip_ms = 0f64;
221
for entry in stats {
222
match entry {
223
RtcStats::InboundRtp(inbound) => {
224
counters.packets_received += inbound.received.packets_received;
225
counters.packets_lost += inbound.received.packets_lost.max(0) as u64;
226
counters.bytes_received += inbound.inbound.bytes_received;
227
if inbound.stream.kind == "audio" {
228
counters.jitter_ms = counters.jitter_ms.max(inbound.received.jitter * 1000.);
229
}
230
}
231
RtcStats::OutboundRtp(outbound) => {
232
counters.bytes_sent += outbound.sent.bytes_sent;
233
if outbound.stream.kind == "video" && outbound.outbound.active {
234
let limitation = limitation_of(outbound.outbound.quality_limitation_reason);
235
counters.limitation = counters.limitation.max_with(limitation);
236
}
237
}
238
RtcStats::RemoteInboundRtp(remote) => {
239
counters.outbound_loss_percent = counters.outbound_loss_percent.max(remote.remote_inbound.fraction_lost * 100.);
240
remote_round_trip_ms = remote_round_trip_ms.max(remote.remote_inbound.round_trip_time * 1000.);
241
}
242
RtcStats::Transport(found) => {
243
transport.dtls_state = found.transport.dtls_state.map(|state| format!("{state:?}")).unwrap_or_default();
244
transport.tls_version = found.transport.tls_version.clone();
245
transport.dtls_cipher = found.transport.dtls_cipher.clone();
246
transport.srtp_cipher = found.transport.srtp_cipher.clone();
247
certificate_ids = (found.transport.local_certificate_id.clone(), found.transport.remote_certificate_id.clone());
248
selected_pair_id = found.transport.selected_candidate_pair_id.clone();
249
}
250
_ => {}
251
}
252
}
253
let fingerprint = |certificate_id: &str| {
254
stats
255
.iter()
256
.find_map(|entry| match entry {
257
RtcStats::Certificate(certificate) if certificate.rtc.id == certificate_id => {
258
Some(format!("{} {}", certificate.certificate.fingerprint_algorithm, certificate.certificate.fingerprint))
259
}
260
_ => None,
261
})
262
.unwrap_or_default()
263
};
264
transport.local_fingerprint = fingerprint(&certificate_ids.0);
265
transport.remote_fingerprint = fingerprint(&certificate_ids.1);
266
let pair_round_trip_ms = stats.iter().find_map(|entry| match entry {
267
RtcStats::CandidatePair(pair) if pair.rtc.id == selected_pair_id => Some(pair.candidate_pair.current_round_trip_time * 1000.),
268
_ => None,
269
});
270
counters.round_trip_ms = pair_round_trip_ms.filter(|milliseconds| *milliseconds > 0.).unwrap_or(remote_round_trip_ms);
271
(counters, transport)
272
}
273
274
impl Limitation {
275
fn max_with(self, other: Limitation) -> Limitation {
276
match (self, other) {
277
(Limitation::Cpu, _) | (_, Limitation::Cpu) => Limitation::Cpu,
278
(Limitation::Bandwidth, _) | (_, Limitation::Bandwidth) => Limitation::Bandwidth,
279
_ => Limitation::None,
280
}
281
}
282
}
283
284
#[cfg(test)]
285
mod tests {
286
use libwebrtc::stats::dictionaries::{CandidatePairStats, CertificateStats, InboundRtpStreamStats, OutboundRtpStreamStats, ReceivedRtpStreamStats, RtcStats as RtcStatsBase, RtpStreamStats, SentRtpStreamStats, TransportStats as TransportDictionary};
287
use libwebrtc::stats::{CandidatePairStats as PairEntry, CertificateStats as CertificateEntry, InboundRtpStats, OutboundRtpStats, TransportStats};
288
289
use super::*;
290
291
fn at(start: Instant, seconds: u64) -> Instant {
292
start + Duration::from_secs(seconds)
293
}
294
295
fn lossy(loss_percent: f64) -> HealthSample {
296
HealthSample { loss_percent, ..HealthSample::default() }
297
}
298
299
fn feed(tracker: &mut QualityTracker, start: Instant, from: u64, to: u64, sample: &HealthSample) -> Quality {
300
let mut quality = Quality { level: NetworkLevel::Good, cpu_limited: false };
301
for seconds in (from..=to).step_by(2) {
302
quality = tracker.observe(at(start, seconds), sample);
303
}
304
quality
305
}
306
307
#[test]
308
fn a_brief_spike_does_not_degrade_the_level() {
309
let (mut tracker, start) = (QualityTracker::default(), Instant::now());
310
assert_eq!(feed(&mut tracker, start, 0, 2, &lossy(8.)).level, NetworkLevel::Good);
311
assert_eq!(feed(&mut tracker, start, 4, 20, &lossy(0.)).level, NetworkLevel::Good);
312
}
313
314
#[test]
315
fn poor_needs_five_seconds_of_loss_over_five_percent() {
316
let (mut tracker, start) = (QualityTracker::default(), Instant::now());
317
assert_eq!(feed(&mut tracker, start, 0, 4, &lossy(6.)).level, NetworkLevel::Good);
318
assert_eq!(feed(&mut tracker, start, 6, 6, &lossy(6.)).level, NetworkLevel::Poor);
319
}
320
321
#[test]
322
fn round_trip_and_jitter_also_make_it_poor() {
323
for sample in [HealthSample { round_trip_ms: 450., ..Default::default() }, HealthSample { jitter_ms: 35., ..Default::default() }] {
324
let (mut tracker, start) = (QualityTracker::default(), Instant::now());
325
assert_eq!(feed(&mut tracker, start, 0, 6, &sample).level, NetworkLevel::Poor);
326
}
327
}
328
329
#[test]
330
fn bad_needs_five_seconds_over_ten_percent_loss_or_500_ms() {
331
let (mut tracker, start) = (QualityTracker::default(), Instant::now());
332
assert_eq!(feed(&mut tracker, start, 0, 6, &lossy(12.)).level, NetworkLevel::Bad);
333
let (mut tracker, start) = (QualityTracker::default(), Instant::now());
334
let slow = HealthSample { round_trip_ms: 600., ..Default::default() };
335
assert_eq!(feed(&mut tracker, start, 0, 6, &slow).level, NetworkLevel::Bad);
336
}
337
338
#[test]
339
fn the_level_drops_fast_and_recovers_one_step_per_ten_seconds() {
340
let (mut tracker, start) = (QualityTracker::default(), Instant::now());
341
assert_eq!(feed(&mut tracker, start, 0, 6, &lossy(12.)).level, NetworkLevel::Bad);
342
assert_eq!(feed(&mut tracker, start, 8, 16, &lossy(0.)).level, NetworkLevel::Bad);
343
assert_eq!(feed(&mut tracker, start, 18, 18, &lossy(0.)).level, NetworkLevel::Poor);
344
assert_eq!(feed(&mut tracker, start, 20, 28, &lossy(0.)).level, NetworkLevel::Poor);
345
assert_eq!(feed(&mut tracker, start, 30, 30, &lossy(0.)).level, NetworkLevel::Good);
346
}
347
348
#[test]
349
fn a_relapse_restarts_the_recovery_timer() {
350
let (mut tracker, start) = (QualityTracker::default(), Instant::now());
351
feed(&mut tracker, start, 0, 6, &lossy(7.));
352
feed(&mut tracker, start, 8, 16, &lossy(0.));
353
feed(&mut tracker, start, 18, 18, &lossy(7.));
354
assert_eq!(feed(&mut tracker, start, 20, 28, &lossy(0.)).level, NetworkLevel::Poor);
355
assert_eq!(feed(&mut tracker, start, 30, 30, &lossy(0.)).level, NetworkLevel::Good);
356
}
357
358
#[test]
359
fn bandwidth_limits_for_over_half_the_window_make_it_poor() {
360
let (mut tracker, start) = (QualityTracker::default(), Instant::now());
361
let limited = HealthSample { limitation: Limitation::Bandwidth, ..Default::default() };
362
assert_eq!(feed(&mut tracker, start, 0, 4, &limited).level, NetworkLevel::Good);
363
assert_eq!(feed(&mut tracker, start, 6, 6, &limited).level, NetworkLevel::Poor);
364
}
365
366
#[test]
367
fn cpu_limits_raise_their_own_flag_without_touching_the_level() {
368
let (mut tracker, start) = (QualityTracker::default(), Instant::now());
369
let limited = HealthSample { limitation: Limitation::Cpu, ..Default::default() };
370
let quality = feed(&mut tracker, start, 0, 6, &limited);
371
assert!(quality.cpu_limited);
372
assert_eq!(quality.level, NetworkLevel::Good);
373
assert!(!feed(&mut tracker, start, 8, 20, &HealthSample::default()).cpu_limited);
374
}
375
376
#[test]
377
fn the_sampler_turns_counter_deltas_into_loss_and_bitrate() {
378
let (mut sampler, start) = (HealthSampler::default(), Instant::now());
379
let first = HealthCounters { packets_received: 100, packets_lost: 0, bytes_sent: 1000, bytes_received: 2000, ..Default::default() };
380
assert_eq!(sampler.sample(start, first), None);
381
let second = HealthCounters { packets_received: 190, packets_lost: 10, bytes_sent: 51_000, bytes_received: 27_000, round_trip_ms: 80., jitter_ms: 4., ..first };
382
let sample = sampler.sample(at(start, 2), second).unwrap();
383
assert_eq!(sample.loss_percent, 10.);
384
assert_eq!(sample.sent_kbps, 200.);
385
assert_eq!(sample.received_kbps, 100.);
386
assert_eq!((sample.round_trip_ms, sample.jitter_ms), (80., 4.));
387
}
388
389
#[test]
390
fn the_sampler_reports_outbound_loss_from_the_remote_report() {
391
let (mut sampler, start) = (HealthSampler::default(), Instant::now());
392
sampler.sample(start, HealthCounters::default());
393
let counters = HealthCounters { outbound_loss_percent: 7., ..Default::default() };
394
assert_eq!(sampler.sample(at(start, 2), counters).unwrap().loss_percent, 7.);
395
}
396
397
#[test]
398
fn stats_parse_into_counters_and_transport_details() {
399
let stats = vec![
400
RtcStats::InboundRtp(InboundRtpStats {
401
stream: RtpStreamStats { kind: "audio".into(), ..Default::default() },
402
received: ReceivedRtpStreamStats { packets_received: 50, packets_lost: 5, jitter: 0.012 },
403
inbound: InboundRtpStreamStats { bytes_received: 4000, ..Default::default() },
404
..Default::default()
405
}),
406
RtcStats::OutboundRtp(OutboundRtpStats {
407
stream: RtpStreamStats { kind: "video".into(), ..Default::default() },
408
sent: SentRtpStreamStats { bytes_sent: 9000, ..Default::default() },
409
outbound: OutboundRtpStreamStats { active: true, quality_limitation_reason: QualityLimitationReason::Cpu, ..Default::default() },
410
..Default::default()
411
}),
412
RtcStats::Transport(TransportStats {
413
transport: TransportDictionary {
414
dtls_cipher: "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256".into(),
415
srtp_cipher: "AEAD_AES_128_GCM".into(),
416
tls_version: "FEFD".into(),
417
local_certificate_id: "CF1".into(),
418
remote_certificate_id: "CF2".into(),
419
selected_candidate_pair_id: "CP1".into(),
420
..Default::default()
421
},
422
..Default::default()
423
}),
424
RtcStats::CandidatePair(PairEntry {
425
rtc: RtcStatsBase { id: "CP1".into(), ..Default::default() },
426
candidate_pair: CandidatePairStats { current_round_trip_time: 0.045, ..Default::default() },
427
}),
428
RtcStats::Certificate(CertificateEntry {
429
rtc: RtcStatsBase { id: "CF1".into(), ..Default::default() },
430
certificate: CertificateStats { fingerprint: "AA:BB".into(), fingerprint_algorithm: "sha-256".into(), ..Default::default() },
431
}),
432
];
433
let (counters, transport) = health_from_stats(&stats);
434
assert_eq!((counters.packets_received, counters.packets_lost), (50, 5));
435
assert_eq!((counters.bytes_received, counters.bytes_sent), (4000, 9000));
436
assert_eq!(counters.jitter_ms, 12.);
437
assert_eq!(counters.round_trip_ms, 45.);
438
assert_eq!(counters.limitation, Limitation::Cpu);
439
assert_eq!(transport.srtp_cipher, "AEAD_AES_128_GCM");
440
assert_eq!(transport.local_fingerprint, "sha-256 AA:BB");
441
assert_eq!(transport.remote_fingerprint, "");
442
}
443
444
#[test]
445
fn inactive_video_streams_do_not_count_as_limited() {
446
let stats = vec![RtcStats::OutboundRtp(OutboundRtpStats {
447
stream: RtpStreamStats { kind: "video".into(), ..Default::default() },
448
outbound: OutboundRtpStreamStats { active: false, quality_limitation_reason: QualityLimitationReason::Bandwidth, ..Default::default() },
449
..Default::default()
450
})];
451
assert_eq!(health_from_stats(&stats).0.limitation, Limitation::None);
452
}
453
}
@@ -0,0 +1,453 @@1
use std::collections::VecDeque;2
use std::time::{Duration, Instant};3
4
use libwebrtc::stats::{QualityLimitationReason, RtcStats};5
6
use crate::renegotiation::MediaPath;7
8
const SUSTAIN: Duration = Duration::from_secs(5);9
const RECOVERY: Duration = Duration::from_secs(10);10
const LIMIT_WINDOW: Duration = Duration::from_secs(10);11
const LIMIT_SHARE: f32 = 0.5;12
const POOR_LOSS_PERCENT: f64 = 5.;13
const POOR_ROUND_TRIP_MS: f64 = 400.;14
const POOR_JITTER_MS: f64 = 30.;15
const BAD_LOSS_PERCENT: f64 = 10.;16
const BAD_ROUND_TRIP_MS: f64 = 500.;17
18
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]19
pub enum NetworkLevel {20
Good,21
Poor,22
Bad,23
}24
25
impl NetworkLevel {26
fn better(self) -> Self {27
match self {28
NetworkLevel::Bad => NetworkLevel::Poor,29
_ => NetworkLevel::Good,30
}31
}32
}33
34
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]35
pub enum Limitation {36
#[default]37
None,38
Cpu,39
Bandwidth,40
}41
42
#[derive(Debug, Clone, Copy, PartialEq, Default)]43
pub struct HealthSample {44
pub loss_percent: f64,45
pub round_trip_ms: f64,46
pub jitter_ms: f64,47
pub sent_kbps: f64,48
pub received_kbps: f64,49
pub limitation: Limitation,50
}51
52
impl HealthSample {53
fn is_bad(&self) -> bool {54
self.loss_percent > BAD_LOSS_PERCENT || self.round_trip_ms > BAD_ROUND_TRIP_MS55
}56
57
fn is_poor(&self) -> bool {58
self.is_bad()59
|| self.loss_percent > POOR_LOSS_PERCENT60
|| self.round_trip_ms > POOR_ROUND_TRIP_MS61
|| self.jitter_ms > POOR_JITTER_MS62
}63
64
fn instant_level(&self) -> NetworkLevel {65
if self.is_bad() {66
NetworkLevel::Bad67
} else if self.is_poor() || self.limitation == Limitation::Bandwidth {68
NetworkLevel::Poor69
} else {70
NetworkLevel::Good71
}72
}73
}74
75
#[derive(Debug, Clone, PartialEq, Eq, Default)]76
pub struct TransportDetails {77
pub dtls_state: String,78
pub tls_version: String,79
pub dtls_cipher: String,80
pub srtp_cipher: String,81
pub local_fingerprint: String,82
pub remote_fingerprint: String,83
}84
85
#[derive(Debug, Clone, PartialEq)]86
pub struct CallHealth {87
pub level: NetworkLevel,88
pub cpu_limited: bool,89
pub sample: HealthSample,90
pub transport: TransportDetails,91
pub path: MediaPath,92
}93
94
#[derive(Debug, Clone, Copy, PartialEq)]95
pub struct Quality {96
pub level: NetworkLevel,97
pub cpu_limited: bool,98
}99
100
pub struct QualityTracker {101
level: NetworkLevel,102
poor_since: Option<Instant>,103
bad_since: Option<Instant>,104
recovering_since: Option<Instant>,105
limits: VecDeque<(Instant, Limitation)>,106
}107
108
impl Default for QualityTracker {109
fn default() -> Self {110
QualityTracker {111
level: NetworkLevel::Good,112
poor_since: None,113
bad_since: None,114
recovering_since: None,115
limits: VecDeque::new(),116
}117
}118
}119
120
fn run_since(since: &mut Option<Instant>, holds: bool, now: Instant) -> bool {121
if !holds {122
*since = None;123
return false;124
}125
now.duration_since(*since.get_or_insert(now)) >= SUSTAIN126
}127
128
impl QualityTracker {129
pub fn observe(&mut self, now: Instant, sample: &HealthSample) -> Quality {130
self.limits.push_back((now, sample.limitation));131
while self.limits.front().is_some_and(|(at, _)| now.duration_since(*at) > LIMIT_WINDOW) {132
self.limits.pop_front();133
}134
let bad = run_since(&mut self.bad_since, sample.is_bad(), now);135
let poor = run_since(&mut self.poor_since, sample.is_poor(), now);136
let target = if bad {137
NetworkLevel::Bad138
} else if poor || self.share_of(Limitation::Bandwidth, now) > LIMIT_SHARE {139
NetworkLevel::Poor140
} else {141
NetworkLevel::Good142
};143
if target > self.level {144
self.level = target;145
self.recovering_since = None;146
} else if sample.instant_level() < self.level {147
let since = *self.recovering_since.get_or_insert(now);148
if now.duration_since(since) >= RECOVERY {149
self.level = self.level.better();150
self.recovering_since = None;151
}152
} else {153
self.recovering_since = None;154
}155
Quality { level: self.level, cpu_limited: self.share_of(Limitation::Cpu, now) > LIMIT_SHARE }156
}157
158
fn share_of(&self, limitation: Limitation, now: Instant) -> f32 {159
let spans_window = self.limits.front().is_some_and(|(at, _)| now.duration_since(*at) >= SUSTAIN);160
if !spans_window {161
return 0.;162
}163
let matching = self.limits.iter().filter(|(_, found)| *found == limitation).count();164
matching as f32 / self.limits.len() as f32165
}166
}167
168
#[derive(Debug, Clone, Copy, PartialEq, Default)]169
pub struct HealthCounters {170
pub packets_received: u64,171
pub packets_lost: u64,172
pub bytes_sent: u64,173
pub bytes_received: u64,174
pub jitter_ms: f64,175
pub round_trip_ms: f64,176
pub outbound_loss_percent: f64,177
pub limitation: Limitation,178
}179
180
#[derive(Default)]181
pub struct HealthSampler {182
previous: Option<(Instant, HealthCounters)>,183
}184
185
impl HealthSampler {186
pub fn sample(&mut self, now: Instant, counters: HealthCounters) -> Option<HealthSample> {187
let (then, before) = self.previous.replace((now, counters))?;188
let seconds = now.duration_since(then).as_secs_f64();189
if seconds <= 0. {190
return None;191
}192
let received = counters.packets_received.saturating_sub(before.packets_received);193
let lost = counters.packets_lost.saturating_sub(before.packets_lost);194
let inbound_loss_percent = if received + lost == 0 { 0. } else { lost as f64 * 100. / (received + lost) as f64 };195
let kbps = |after: u64, before: u64| after.saturating_sub(before) as f64 * 8. / seconds / 1000.;196
Some(HealthSample {197
loss_percent: inbound_loss_percent.max(counters.outbound_loss_percent),198
round_trip_ms: counters.round_trip_ms,199
jitter_ms: counters.jitter_ms,200
sent_kbps: kbps(counters.bytes_sent, before.bytes_sent),201
received_kbps: kbps(counters.bytes_received, before.bytes_received),202
limitation: counters.limitation,203
})204
}205
}206
207
fn limitation_of(reason: QualityLimitationReason) -> Limitation {208
match reason {209
QualityLimitationReason::Cpu => Limitation::Cpu,210
QualityLimitationReason::Bandwidth => Limitation::Bandwidth,211
_ => Limitation::None,212
}213
}214
215
pub fn health_from_stats(stats: &[RtcStats]) -> (HealthCounters, TransportDetails) {216
let mut counters = HealthCounters::default();217
let mut transport = TransportDetails::default();218
let mut certificate_ids = (String::new(), String::new());219
let mut selected_pair_id = String::new();220
let mut remote_round_trip_ms = 0f64;221
for entry in stats {222
match entry {223
RtcStats::InboundRtp(inbound) => {224
counters.packets_received += inbound.received.packets_received;225
counters.packets_lost += inbound.received.packets_lost.max(0) as u64;226
counters.bytes_received += inbound.inbound.bytes_received;227
if inbound.stream.kind == "audio" {228
counters.jitter_ms = counters.jitter_ms.max(inbound.received.jitter * 1000.);229
}230
}231
RtcStats::OutboundRtp(outbound) => {232
counters.bytes_sent += outbound.sent.bytes_sent;233
if outbound.stream.kind == "video" && outbound.outbound.active {234
let limitation = limitation_of(outbound.outbound.quality_limitation_reason);235
counters.limitation = counters.limitation.max_with(limitation);236
}237
}238
RtcStats::RemoteInboundRtp(remote) => {239
counters.outbound_loss_percent = counters.outbound_loss_percent.max(remote.remote_inbound.fraction_lost * 100.);240
remote_round_trip_ms = remote_round_trip_ms.max(remote.remote_inbound.round_trip_time * 1000.);241
}242
RtcStats::Transport(found) => {243
transport.dtls_state = found.transport.dtls_state.map(|state| format!("{state:?}")).unwrap_or_default();244
transport.tls_version = found.transport.tls_version.clone();245
transport.dtls_cipher = found.transport.dtls_cipher.clone();246
transport.srtp_cipher = found.transport.srtp_cipher.clone();247
certificate_ids = (found.transport.local_certificate_id.clone(), found.transport.remote_certificate_id.clone());248
selected_pair_id = found.transport.selected_candidate_pair_id.clone();249
}250
_ => {}251
}252
}253
let fingerprint = |certificate_id: &str| {254
stats255
.iter()256
.find_map(|entry| match entry {257
RtcStats::Certificate(certificate) if certificate.rtc.id == certificate_id => {258
Some(format!("{} {}", certificate.certificate.fingerprint_algorithm, certificate.certificate.fingerprint))259
}260
_ => None,261
})262
.unwrap_or_default()263
};264
transport.local_fingerprint = fingerprint(&certificate_ids.0);265
transport.remote_fingerprint = fingerprint(&certificate_ids.1);266
let pair_round_trip_ms = stats.iter().find_map(|entry| match entry {267
RtcStats::CandidatePair(pair) if pair.rtc.id == selected_pair_id => Some(pair.candidate_pair.current_round_trip_time * 1000.),268
_ => None,269
});270
counters.round_trip_ms = pair_round_trip_ms.filter(|milliseconds| *milliseconds > 0.).unwrap_or(remote_round_trip_ms);271
(counters, transport)272
}273
274
impl Limitation {275
fn max_with(self, other: Limitation) -> Limitation {276
match (self, other) {277
(Limitation::Cpu, _) | (_, Limitation::Cpu) => Limitation::Cpu,278
(Limitation::Bandwidth, _) | (_, Limitation::Bandwidth) => Limitation::Bandwidth,279
_ => Limitation::None,280
}281
}282
}283
284
#[cfg(test)]285
mod tests {286
use libwebrtc::stats::dictionaries::{CandidatePairStats, CertificateStats, InboundRtpStreamStats, OutboundRtpStreamStats, ReceivedRtpStreamStats, RtcStats as RtcStatsBase, RtpStreamStats, SentRtpStreamStats, TransportStats as TransportDictionary};287
use libwebrtc::stats::{CandidatePairStats as PairEntry, CertificateStats as CertificateEntry, InboundRtpStats, OutboundRtpStats, TransportStats};288
289
use super::*;290
291
fn at(start: Instant, seconds: u64) -> Instant {292
start + Duration::from_secs(seconds)293
}294
295
fn lossy(loss_percent: f64) -> HealthSample {296
HealthSample { loss_percent, ..HealthSample::default() }297
}298
299
fn feed(tracker: &mut QualityTracker, start: Instant, from: u64, to: u64, sample: &HealthSample) -> Quality {300
let mut quality = Quality { level: NetworkLevel::Good, cpu_limited: false };301
for seconds in (from..=to).step_by(2) {302
quality = tracker.observe(at(start, seconds), sample);303
}304
quality305
}306
307
#[test]308
fn a_brief_spike_does_not_degrade_the_level() {309
let (mut tracker, start) = (QualityTracker::default(), Instant::now());310
assert_eq!(feed(&mut tracker, start, 0, 2, &lossy(8.)).level, NetworkLevel::Good);311
assert_eq!(feed(&mut tracker, start, 4, 20, &lossy(0.)).level, NetworkLevel::Good);312
}313
314
#[test]315
fn poor_needs_five_seconds_of_loss_over_five_percent() {316
let (mut tracker, start) = (QualityTracker::default(), Instant::now());317
assert_eq!(feed(&mut tracker, start, 0, 4, &lossy(6.)).level, NetworkLevel::Good);318
assert_eq!(feed(&mut tracker, start, 6, 6, &lossy(6.)).level, NetworkLevel::Poor);319
}320
321
#[test]322
fn round_trip_and_jitter_also_make_it_poor() {323
for sample in [HealthSample { round_trip_ms: 450., ..Default::default() }, HealthSample { jitter_ms: 35., ..Default::default() }] {324
let (mut tracker, start) = (QualityTracker::default(), Instant::now());325
assert_eq!(feed(&mut tracker, start, 0, 6, &sample).level, NetworkLevel::Poor);326
}327
}328
329
#[test]330
fn bad_needs_five_seconds_over_ten_percent_loss_or_500_ms() {331
let (mut tracker, start) = (QualityTracker::default(), Instant::now());332
assert_eq!(feed(&mut tracker, start, 0, 6, &lossy(12.)).level, NetworkLevel::Bad);333
let (mut tracker, start) = (QualityTracker::default(), Instant::now());334
let slow = HealthSample { round_trip_ms: 600., ..Default::default() };335
assert_eq!(feed(&mut tracker, start, 0, 6, &slow).level, NetworkLevel::Bad);336
}337
338
#[test]339
fn the_level_drops_fast_and_recovers_one_step_per_ten_seconds() {340
let (mut tracker, start) = (QualityTracker::default(), Instant::now());341
assert_eq!(feed(&mut tracker, start, 0, 6, &lossy(12.)).level, NetworkLevel::Bad);342
assert_eq!(feed(&mut tracker, start, 8, 16, &lossy(0.)).level, NetworkLevel::Bad);343
assert_eq!(feed(&mut tracker, start, 18, 18, &lossy(0.)).level, NetworkLevel::Poor);344
assert_eq!(feed(&mut tracker, start, 20, 28, &lossy(0.)).level, NetworkLevel::Poor);345
assert_eq!(feed(&mut tracker, start, 30, 30, &lossy(0.)).level, NetworkLevel::Good);346
}347
348
#[test]349
fn a_relapse_restarts_the_recovery_timer() {350
let (mut tracker, start) = (QualityTracker::default(), Instant::now());351
feed(&mut tracker, start, 0, 6, &lossy(7.));352
feed(&mut tracker, start, 8, 16, &lossy(0.));353
feed(&mut tracker, start, 18, 18, &lossy(7.));354
assert_eq!(feed(&mut tracker, start, 20, 28, &lossy(0.)).level, NetworkLevel::Poor);355
assert_eq!(feed(&mut tracker, start, 30, 30, &lossy(0.)).level, NetworkLevel::Good);356
}357
358
#[test]359
fn bandwidth_limits_for_over_half_the_window_make_it_poor() {360
let (mut tracker, start) = (QualityTracker::default(), Instant::now());361
let limited = HealthSample { limitation: Limitation::Bandwidth, ..Default::default() };362
assert_eq!(feed(&mut tracker, start, 0, 4, &limited).level, NetworkLevel::Good);363
assert_eq!(feed(&mut tracker, start, 6, 6, &limited).level, NetworkLevel::Poor);364
}365
366
#[test]367
fn cpu_limits_raise_their_own_flag_without_touching_the_level() {368
let (mut tracker, start) = (QualityTracker::default(), Instant::now());369
let limited = HealthSample { limitation: Limitation::Cpu, ..Default::default() };370
let quality = feed(&mut tracker, start, 0, 6, &limited);371
assert!(quality.cpu_limited);372
assert_eq!(quality.level, NetworkLevel::Good);373
assert!(!feed(&mut tracker, start, 8, 20, &HealthSample::default()).cpu_limited);374
}375
376
#[test]377
fn the_sampler_turns_counter_deltas_into_loss_and_bitrate() {378
let (mut sampler, start) = (HealthSampler::default(), Instant::now());379
let first = HealthCounters { packets_received: 100, packets_lost: 0, bytes_sent: 1000, bytes_received: 2000, ..Default::default() };380
assert_eq!(sampler.sample(start, first), None);381
let second = HealthCounters { packets_received: 190, packets_lost: 10, bytes_sent: 51_000, bytes_received: 27_000, round_trip_ms: 80., jitter_ms: 4., ..first };382
let sample = sampler.sample(at(start, 2), second).unwrap();383
assert_eq!(sample.loss_percent, 10.);384
assert_eq!(sample.sent_kbps, 200.);385
assert_eq!(sample.received_kbps, 100.);386
assert_eq!((sample.round_trip_ms, sample.jitter_ms), (80., 4.));387
}388
389
#[test]390
fn the_sampler_reports_outbound_loss_from_the_remote_report() {391
let (mut sampler, start) = (HealthSampler::default(), Instant::now());392
sampler.sample(start, HealthCounters::default());393
let counters = HealthCounters { outbound_loss_percent: 7., ..Default::default() };394
assert_eq!(sampler.sample(at(start, 2), counters).unwrap().loss_percent, 7.);395
}396
397
#[test]398
fn stats_parse_into_counters_and_transport_details() {399
let stats = vec![400
RtcStats::InboundRtp(InboundRtpStats {401
stream: RtpStreamStats { kind: "audio".into(), ..Default::default() },402
received: ReceivedRtpStreamStats { packets_received: 50, packets_lost: 5, jitter: 0.012 },403
inbound: InboundRtpStreamStats { bytes_received: 4000, ..Default::default() },404
..Default::default()405
}),406
RtcStats::OutboundRtp(OutboundRtpStats {407
stream: RtpStreamStats { kind: "video".into(), ..Default::default() },408
sent: SentRtpStreamStats { bytes_sent: 9000, ..Default::default() },409
outbound: OutboundRtpStreamStats { active: true, quality_limitation_reason: QualityLimitationReason::Cpu, ..Default::default() },410
..Default::default()411
}),412
RtcStats::Transport(TransportStats {413
transport: TransportDictionary {414
dtls_cipher: "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256".into(),415
srtp_cipher: "AEAD_AES_128_GCM".into(),416
tls_version: "FEFD".into(),417
local_certificate_id: "CF1".into(),418
remote_certificate_id: "CF2".into(),419
selected_candidate_pair_id: "CP1".into(),420
..Default::default()421
},422
..Default::default()423
}),424
RtcStats::CandidatePair(PairEntry {425
rtc: RtcStatsBase { id: "CP1".into(), ..Default::default() },426
candidate_pair: CandidatePairStats { current_round_trip_time: 0.045, ..Default::default() },427
}),428
RtcStats::Certificate(CertificateEntry {429
rtc: RtcStatsBase { id: "CF1".into(), ..Default::default() },430
certificate: CertificateStats { fingerprint: "AA:BB".into(), fingerprint_algorithm: "sha-256".into(), ..Default::default() },431
}),432
];433
let (counters, transport) = health_from_stats(&stats);434
assert_eq!((counters.packets_received, counters.packets_lost), (50, 5));435
assert_eq!((counters.bytes_received, counters.bytes_sent), (4000, 9000));436
assert_eq!(counters.jitter_ms, 12.);437
assert_eq!(counters.round_trip_ms, 45.);438
assert_eq!(counters.limitation, Limitation::Cpu);439
assert_eq!(transport.srtp_cipher, "AEAD_AES_128_GCM");440
assert_eq!(transport.local_fingerprint, "sha-256 AA:BB");441
assert_eq!(transport.remote_fingerprint, "");442
}443
444
#[test]445
fn inactive_video_streams_do_not_count_as_limited() {446
let stats = vec![RtcStats::OutboundRtp(OutboundRtpStats {447
stream: RtpStreamStats { kind: "video".into(), ..Default::default() },448
outbound: OutboundRtpStreamStats { active: false, quality_limitation_reason: QualityLimitationReason::Bandwidth, ..Default::default() },449
..Default::default()450
})];451
assert_eq!(health_from_stats(&stats).0.limitation, Limitation::None);452
}453
}@@ -14,6 +14,7 @@ pub mod devices;
14
14
pub mod engine;
15
15
pub mod end;
16
16
pub mod error;
17
pub mod health;
17
18
pub mod hold;
18
19
pub mod join;
19
20
pub mod level;
@@ -50,6 +51,7 @@ pub mod whiteboard;
50
51
pub use audio_io::AudioMode;
51
52
pub use background::{BackgroundCache, BackgroundChoice, BackgroundPicture, DefaultBackground};
52
53
pub use breakout::BreakoutMove;
54
pub use health::{CallHealth, HealthSample, Limitation, NetworkLevel, TransportDetails};
53
55
pub use hold::HoldState;
54
56
pub use whiteboard::ContentShare;
55
57
pub use call::{AcceptMode, CallOptions, CallReport, CallSpec, run_test_call};
@@ -62,6 +64,7 @@ pub use reaction::{Reaction, ReactionEvent};
62
64
pub use captions::{CaptionEntry, CaptionState};
63
65
pub use roster::{PublishedState, RaisedHand, RosterEntry, Spotlight};
64
66
pub use sound_capture::LoopbackKind;
67
pub use renegotiation::MediaPath;
65
68
pub use signaling::{Callee, MeetingTarget};
66
69
pub use devices::{AudioDevice, DeviceChoice, DeviceEntry, DeviceLists};
67
70
pub use error::{Error, Result};
@@ -14,6 +14,7 @@ pub mod devices;14
pub mod engine;14
pub mod engine;15
pub mod end;15
pub mod end;16
pub mod error;16
pub mod error;17
pub mod health;17
pub mod hold;18
pub mod hold;18
pub mod join;19
pub mod join;19
pub mod level;20
pub mod level;@@ -50,6 +51,7 @@ pub mod whiteboard;50
pub use audio_io::AudioMode;51
pub use audio_io::AudioMode;51
pub use background::{BackgroundCache, BackgroundChoice, BackgroundPicture, DefaultBackground};52
pub use background::{BackgroundCache, BackgroundChoice, BackgroundPicture, DefaultBackground};52
pub use breakout::BreakoutMove;53
pub use breakout::BreakoutMove;54
pub use health::{CallHealth, HealthSample, Limitation, NetworkLevel, TransportDetails};53
pub use hold::HoldState;55
pub use hold::HoldState;54
pub use whiteboard::ContentShare;56
pub use whiteboard::ContentShare;55
pub use call::{AcceptMode, CallOptions, CallReport, CallSpec, run_test_call};57
pub use call::{AcceptMode, CallOptions, CallReport, CallSpec, run_test_call};@@ -62,6 +64,7 @@ pub use reaction::{Reaction, ReactionEvent};62
pub use captions::{CaptionEntry, CaptionState};64
pub use captions::{CaptionEntry, CaptionState};63
pub use roster::{PublishedState, RaisedHand, RosterEntry, Spotlight};65
pub use roster::{PublishedState, RaisedHand, RosterEntry, Spotlight};64
pub use sound_capture::LoopbackKind;66
pub use sound_capture::LoopbackKind;67
pub use renegotiation::MediaPath;65
pub use signaling::{Callee, MeetingTarget};68
pub use signaling::{Callee, MeetingTarget};66
pub use devices::{AudioDevice, DeviceChoice, DeviceEntry, DeviceLists};69
pub use devices::{AudioDevice, DeviceChoice, DeviceEntry, DeviceLists};67
pub use error::{Error, Result};70
pub use error::{Error, Result};@@ -110,6 +110,7 @@ pub struct VideoReceive {
110
110
screen_held: Option<Assignment>,
111
111
history: Vec<String>,
112
112
requester: Option<SourceRequester>,
113
incoming_enabled: bool,
113
114
}
114
115
115
116
impl VideoReceive {
@@ -122,9 +123,14 @@ impl VideoReceive {
122
123
screen_held: None,
123
124
history: Vec::new(),
124
125
requester: None,
126
incoming_enabled: true,
125
127
}
126
128
}
127
129
130
pub fn set_incoming_enabled(&mut self, enabled: bool) {
131
self.incoming_enabled = enabled;
132
}
133
128
134
pub fn router(&self) -> &VideoRouter {
129
135
&self.router
130
136
}
@@ -156,7 +162,11 @@ impl VideoReceive {
156
162
pub fn reselect(&mut self, roster: &Roster) -> ReceiveChange {
157
163
let mut change = ReceiveChange::default();
158
164
let Some(requester) = &self.requester else { return change };
159
let candidates = prioritize(roster.video_candidates(&self.own_mri), &self.history);
165
let candidates = if self.incoming_enabled {
166
prioritize(roster.video_candidates(&self.own_mri), &self.history)
167
} else {
168
Vec::new()
169
};
160
170
let next = plan_receive(&self.held, &candidates);
161
171
for request in requests_for(&self.held, &next, &self.table.people) {
162
172
let slot = self.table.people.iter().position(|slot| slot.mid == request.mid);
@@ -110,6 +110,7 @@ pub struct VideoReceive {110
screen_held: Option<Assignment>,110
screen_held: Option<Assignment>,111
history: Vec<String>,111
history: Vec<String>,112
requester: Option<SourceRequester>,112
requester: Option<SourceRequester>,113
incoming_enabled: bool,113
}114
}114
115
115
impl VideoReceive {116
impl VideoReceive {@@ -122,9 +123,14 @@ impl VideoReceive {122
screen_held: None,123
screen_held: None,123
history: Vec::new(),124
history: Vec::new(),124
requester: None,125
requester: None,126
incoming_enabled: true,125
}127
}126
}128
}127
129
130
pub fn set_incoming_enabled(&mut self, enabled: bool) {131
self.incoming_enabled = enabled;132
}133
128
pub fn router(&self) -> &VideoRouter {134
pub fn router(&self) -> &VideoRouter {129
&self.router135
&self.router130
}136
}@@ -156,7 +162,11 @@ impl VideoReceive {156
pub fn reselect(&mut self, roster: &Roster) -> ReceiveChange {162
pub fn reselect(&mut self, roster: &Roster) -> ReceiveChange {157
let mut change = ReceiveChange::default();163
let mut change = ReceiveChange::default();158
let Some(requester) = &self.requester else { return change };164
let Some(requester) = &self.requester else { return change };159
let candidates = prioritize(roster.video_candidates(&self.own_mri), &self.history);165
let candidates = if self.incoming_enabled {166
prioritize(roster.video_candidates(&self.own_mri), &self.history)167
} else {168
Vec::new()169
};160
let next = plan_receive(&self.held, &candidates);170
let next = plan_receive(&self.held, &candidates);161
for request in requests_for(&self.held, &next, &self.table.people) {171
for request in requests_for(&self.held, &next, &self.table.people) {162
let slot = self.table.people.iter().position(|slot| slot.mid == request.mid);172
let slot = self.table.people.iter().position(|slot| slot.mid == request.mid);