fix(calling): an early send limit still applies when the camera starts (#139)
Co-authored-by: Matteo Lombardi <93079933+matteolomba@users.noreply.github.com>
@@ -1224,6 +1224,8 @@ dependencies = [
1224
1224
"libwebrtc",
1225
1225
"ndarray",
1226
1226
"nokhwa",
1227
"objc2 0.6.5",
1228
"objc2-foundation 0.3.2",
1227
1229
"ort",
1228
1230
"serde",
1229
1231
"serde_json",
@@ -1224,6 +1224,8 @@ dependencies = [1224
"libwebrtc",1224
"libwebrtc",1225
"ndarray",1225
"ndarray",1226
"nokhwa",1226
"nokhwa",1227
"objc2 0.6.5",1228
"objc2-foundation 0.3.2",1227
"ort",1229
"ort",1228
"serde",1230
"serde",1229
"serde_json",1231
"serde_json",@@ -31,6 +31,11 @@ uuid.workspace = true
31
31
[target.'cfg(target_os = "linux")'.dependencies]
32
32
libc = "0.2"
33
33
34
[target.'cfg(target_os = "macos")'.dependencies]
35
libc = "0.2"
36
objc2 = "0.6"
37
objc2-foundation = { version = "0.3", features = ["NSProcessInfo"] }
38
34
39
[target.'cfg(not(windows))'.dependencies]
35
40
ort = { version = "=2.0.0-rc.14", default-features = false, features = ["std", "ndarray", "load-dynamic", "api-31"] }
36
41
@@ -31,6 +31,11 @@ uuid.workspace = true31
[target.'cfg(target_os = "linux")'.dependencies]31
[target.'cfg(target_os = "linux")'.dependencies]32
libc = "0.2"32
libc = "0.2"33
33
34
[target.'cfg(target_os = "macos")'.dependencies]35
libc = "0.2"36
objc2 = "0.6"37
objc2-foundation = { version = "0.3", features = ["NSProcessInfo"] }38
34
[target.'cfg(not(windows))'.dependencies]39
[target.'cfg(not(windows))'.dependencies]35
ort = { version = "=2.0.0-rc.14", default-features = false, features = ["std", "ndarray", "load-dynamic", "api-31"] }40
ort = { version = "=2.0.0-rc.14", default-features = false, features = ["std", "ndarray", "load-dynamic", "api-31"] }36
41
@@ -921,6 +921,7 @@ async fn drive(
921
921
let mut capability = MeetingCapability::default();
922
922
let mut previous_packets = 0u64;
923
923
let mut ticks = 0u32;
924
let mut host_cpu = std::collections::HashMap::new();
924
925
let mut segmentation_model: Option<&'static str> = None;
925
926
let mut health_sampler = HealthSampler::default();
926
927
let mut quality_tracker = QualityTracker::default();
@@ -2804,6 +2805,20 @@ async fn drive(
2804
2805
segmentation_model = Some(model);
2805
2806
}
2806
2807
}
2808
if crate::host_load::recorded_on_this_platform()
2809
&& ticks.is_multiple_of(HEALTH_EVERY_TICKS)
2810
{
2811
let current = crate::host_load::thread_cpu();
2812
let deltas = crate::host_load::cpu_deltas(¤t, &mut host_cpu);
2813
timeline.record(
2814
"host load",
2815
crate::host_load::host_load_line(
2816
&deltas,
2817
&local_video.effects_label(),
2818
crate::host_load::thermal_state(),
2819
),
2820
);
2821
}
2807
2822
if ticks.is_multiple_of(HEALTH_EVERY_TICKS) {
2808
2823
control.send(CallUpdate::Sample(StatsSample {
2809
2824
audio_in_packets: snapshot.inbound_packets,
@@ -921,6 +921,7 @@ async fn drive(921
let mut capability = MeetingCapability::default();921
let mut capability = MeetingCapability::default();922
let mut previous_packets = 0u64;922
let mut previous_packets = 0u64;923
let mut ticks = 0u32;923
let mut ticks = 0u32;924
let mut host_cpu = std::collections::HashMap::new();924
let mut segmentation_model: Option<&'static str> = None;925
let mut segmentation_model: Option<&'static str> = None;925
let mut health_sampler = HealthSampler::default();926
let mut health_sampler = HealthSampler::default();926
let mut quality_tracker = QualityTracker::default();927
let mut quality_tracker = QualityTracker::default();@@ -2804,6 +2805,20 @@ async fn drive(2804
segmentation_model = Some(model);2805
segmentation_model = Some(model);2805
}2806
}2806
}2807
}2808
if crate::host_load::recorded_on_this_platform()2809
&& ticks.is_multiple_of(HEALTH_EVERY_TICKS)2810
{2811
let current = crate::host_load::thread_cpu();2812
let deltas = crate::host_load::cpu_deltas(¤t, &mut host_cpu);2813
timeline.record(2814
"host load",2815
crate::host_load::host_load_line(2816
&deltas,2817
&local_video.effects_label(),2818
crate::host_load::thermal_state(),2819
),2820
);2821
}2807
if ticks.is_multiple_of(HEALTH_EVERY_TICKS) {2822
if ticks.is_multiple_of(HEALTH_EVERY_TICKS) {2808
control.send(CallUpdate::Sample(StatsSample {2823
control.send(CallUpdate::Sample(StatsSample {2809
audio_in_packets: snapshot.inbound_packets,2824
audio_in_packets: snapshot.inbound_packets,@@ -0,0 +1,305 @@
1
use std::collections::HashMap;
2
3
/// One thread and the CPU time it has used since the process started, in milliseconds.
4
/// `id` is the kernel thread id, not the Mach port and not the pthread name.
5
#[derive(Debug, Clone, PartialEq, Eq)]
6
pub struct ThreadCpu {
7
pub id: u64,
8
pub name: String,
9
pub cpu_ms: u64,
10
}
11
12
pub fn recorded_on_this_platform() -> bool {
13
cfg!(target_os = "macos")
14
}
15
16
/// CPU used since the previous sample, summed by thread name. The first sample reports the
17
/// time already used. Threads that share a name (tokio workers) stay separate in `previous`
18
/// and add up on the line.
19
pub fn cpu_deltas(current: &[ThreadCpu], previous: &mut HashMap<u64, u64>) -> Vec<(String, u64)> {
20
let mut seen = Vec::with_capacity(current.len());
21
let mut totals: HashMap<String, u64> = HashMap::new();
22
for thread in current {
23
let before = previous.get(&thread.id).copied().unwrap_or(0);
24
*totals.entry(thread.name.clone()).or_default() += thread.cpu_ms.saturating_sub(before);
25
previous.insert(thread.id, thread.cpu_ms);
26
seen.push(thread.id);
27
}
28
previous.retain(|id, _| seen.contains(id));
29
let mut deltas: Vec<(String, u64)> = totals.into_iter().collect();
30
deltas.sort_by(|left, right| right.1.cmp(&left.1).then_with(|| left.0.cmp(&right.0)));
31
deltas
32
}
33
34
const SHOWN_THREADS: usize = 8;
35
36
pub fn host_load_line(deltas: &[(String, u64)], effects: &str, thermal: &str) -> String {
37
let active: Vec<_> = deltas.iter().filter(|(_, cpu_ms)| *cpu_ms > 0).collect();
38
let threads = if active.is_empty() {
39
"no thread cpu".to_owned()
40
} else {
41
let shown = active.len().min(SHOWN_THREADS);
42
let mut parts: Vec<String> = active[..shown]
43
.iter()
44
.map(|(name, cpu_ms)| format!("{name} {cpu_ms}ms"))
45
.collect();
46
if active.len() > SHOWN_THREADS {
47
let rest: u64 = active[SHOWN_THREADS..]
48
.iter()
49
.map(|(_, cpu_ms)| *cpu_ms)
50
.sum();
51
parts.push(format!("others {rest}ms"));
52
}
53
parts.join(", ")
54
};
55
format!("{threads}; {effects}; thermal {thermal}")
56
}
57
58
/// Cumulative CPU time per thread. Empty off macOS, and empty when the kernel call fails.
59
pub fn thread_cpu() -> Vec<ThreadCpu> {
60
#[cfg(target_os = "macos")]
61
{
62
macos::thread_cpu()
63
}
64
#[cfg(not(target_os = "macos"))]
65
{
66
Vec::new()
67
}
68
}
69
70
pub fn thermal_state() -> &'static str {
71
#[cfg(target_os = "macos")]
72
{
73
macos::thermal_state()
74
}
75
#[cfg(not(target_os = "macos"))]
76
{
77
"unavailable"
78
}
79
}
80
81
#[cfg(target_os = "macos")]
82
mod macos {
83
use super::ThreadCpu;
84
85
unsafe extern "C" {
86
fn mach_port_deallocate(
87
task: libc::mach_port_t,
88
name: libc::mach_port_t,
89
) -> libc::kern_return_t;
90
}
91
92
pub fn thermal_state() -> &'static str {
93
let state = objc2_foundation::NSProcessInfo::processInfo().thermalState();
94
match state {
95
objc2_foundation::NSProcessInfoThermalState::Nominal => "nominal",
96
objc2_foundation::NSProcessInfoThermalState::Fair => "fair",
97
objc2_foundation::NSProcessInfoThermalState::Serious => "serious",
98
objc2_foundation::NSProcessInfoThermalState::Critical => "critical",
99
_ => "unknown",
100
}
101
}
102
103
pub fn thread_cpu() -> Vec<ThreadCpu> {
104
unsafe {
105
let task = libc::mach_task_self();
106
let mut threads: libc::thread_act_array_t = std::ptr::null_mut();
107
let mut count: libc::mach_msg_type_number_t = 0;
108
if libc::task_threads(task, &mut threads, &mut count) != libc::KERN_SUCCESS {
109
return Vec::new();
110
}
111
let mut found = Vec::with_capacity(count as usize);
112
for index in 0..count {
113
let thread = *threads.add(index as usize);
114
let mut info: libc::thread_basic_info = std::mem::zeroed();
115
let mut info_count = libc::THREAD_BASIC_INFO_COUNT;
116
let status = libc::thread_info(
117
thread,
118
libc::THREAD_BASIC_INFO,
119
&mut info as *mut libc::thread_basic_info as libc::thread_info_t,
120
&mut info_count,
121
);
122
if status == libc::KERN_SUCCESS
123
&& let Some(id) = thread_id(thread)
124
{
125
found.push(ThreadCpu {
126
id,
127
name: thread_name(thread),
128
cpu_ms: cpu_ms(&info),
129
});
130
}
131
// task_threads hands back a send right per thread. Freeing the array does not release those.
132
let _ = mach_port_deallocate(task, thread);
133
}
134
let bytes = count as libc::vm_size_t
135
* std::mem::size_of::<libc::thread_act_t>() as libc::vm_size_t;
136
let _ = libc::vm_deallocate(task, threads as libc::vm_address_t, bytes);
137
found
138
}
139
}
140
141
fn cpu_ms(info: &libc::thread_basic_info) -> u64 {
142
let part = |time: libc::time_value_t| {
143
let seconds = i64::from(time.seconds).max(0);
144
let micros = i64::from(time.microseconds).max(0);
145
seconds.saturating_mul(1000) + micros / 1000
146
};
147
part(info.user_time).saturating_add(part(info.system_time)) as u64
148
}
149
150
/// Stable across samples. The Mach port from `task_threads` is reused after
151
/// `mach_port_deallocate`, so it cannot key the previous sample.
152
fn thread_id(thread: libc::thread_act_t) -> Option<u64> {
153
unsafe {
154
let mut info: libc::thread_identifier_info = std::mem::zeroed();
155
let mut count = libc::THREAD_IDENTIFIER_INFO_COUNT;
156
let status = libc::thread_info(
157
thread,
158
libc::THREAD_IDENTIFIER_INFO,
159
&mut info as *mut libc::thread_identifier_info as libc::thread_info_t,
160
&mut count,
161
);
162
if status == libc::KERN_SUCCESS && info.thread_id != 0 {
163
Some(info.thread_id)
164
} else {
165
None
166
}
167
}
168
}
169
170
fn thread_name(thread: libc::thread_act_t) -> String {
171
unsafe {
172
let pthread = libc::pthread_from_mach_thread_np(thread);
173
if !pthread.is_null() {
174
let mut buffer = [0u8; 64];
175
if libc::pthread_getname_np(pthread, buffer.as_mut_ptr().cast(), buffer.len()) == 0
176
{
177
let end = buffer
178
.iter()
179
.position(|byte| *byte == 0)
180
.unwrap_or(buffer.len());
181
if let Ok(name) = std::str::from_utf8(&buffer[..end]) {
182
let name = name.trim();
183
if !name.is_empty() {
184
return name.to_owned();
185
}
186
}
187
}
188
}
189
format!("tid-{thread}")
190
}
191
}
192
}
193
194
#[cfg(test)]
195
mod tests {
196
use super::*;
197
198
#[test]
199
fn a_host_load_line_names_the_hot_thread_the_effects_and_the_thermal_state() {
200
let mut previous = HashMap::new();
201
let first = cpu_deltas(
202
&[
203
ThreadCpu {
204
id: 1,
205
name: "camera".into(),
206
cpu_ms: 40,
207
},
208
ThreadCpu {
209
id: 2,
210
name: "camera effects".into(),
211
cpu_ms: 5,
212
},
213
],
214
&mut previous,
215
);
216
let line = host_load_line(
217
&first,
218
"blur=off standout=off framing=off brightness=off soft_focus=off",
219
"nominal",
220
);
221
assert_eq!(
222
line,
223
"camera 40ms, camera effects 5ms; blur=off standout=off framing=off brightness=off soft_focus=off; thermal nominal"
224
);
225
let second = cpu_deltas(
226
&[
227
ThreadCpu {
228
id: 1,
229
name: "camera".into(),
230
cpu_ms: 90,
231
},
232
ThreadCpu {
233
id: 2,
234
name: "camera effects".into(),
235
cpu_ms: 5,
236
},
237
],
238
&mut previous,
239
);
240
assert_eq!(
241
second,
242
vec![("camera".into(), 50), ("camera effects".into(), 0)]
243
);
244
}
245
246
#[test]
247
fn shared_thread_names_sum_and_idle_threads_fold_out_of_the_line() {
248
let mut previous = HashMap::new();
249
let first = cpu_deltas(
250
&[
251
ThreadCpu {
252
id: 10,
253
name: "teams-net".into(),
254
cpu_ms: 5_000,
255
},
256
ThreadCpu {
257
id: 11,
258
name: "teams-net".into(),
259
cpu_ms: 300,
260
},
261
],
262
&mut previous,
263
);
264
assert_eq!(first, vec![("teams-net".into(), 5_300)]);
265
let second = cpu_deltas(
266
&[
267
ThreadCpu {
268
id: 10,
269
name: "teams-net".into(),
270
cpu_ms: 5_300,
271
},
272
ThreadCpu {
273
id: 11,
274
name: "teams-net".into(),
275
cpu_ms: 800,
276
},
277
],
278
&mut previous,
279
);
280
assert_eq!(second, vec![("teams-net".into(), 800)]);
281
let mut busy = Vec::new();
282
for index in 0..10 {
283
busy.push((format!("t{index}"), 10 - index));
284
}
285
busy.push(("idle".into(), 0));
286
let line = host_load_line(
287
&busy,
288
"blur=off standout=off framing=off brightness=off soft_focus=off",
289
"unknown",
290
);
291
assert_eq!(
292
line,
293
"t0 10ms, t1 9ms, t2 8ms, t3 7ms, t4 6ms, t5 5ms, t6 4ms, t7 3ms, others 3ms; blur=off standout=off framing=off brightness=off soft_focus=off; thermal unknown"
294
);
295
}
296
297
#[test]
298
fn host_load_is_recorded_only_on_macos() {
299
assert_eq!(recorded_on_this_platform(), cfg!(target_os = "macos"));
300
if !recorded_on_this_platform() {
301
assert!(thread_cpu().is_empty());
302
assert_eq!(thermal_state(), "unavailable");
303
}
304
}
305
}
@@ -0,0 +1,305 @@1
use std::collections::HashMap;2
3
/// One thread and the CPU time it has used since the process started, in milliseconds.4
/// `id` is the kernel thread id, not the Mach port and not the pthread name.5
#[derive(Debug, Clone, PartialEq, Eq)]6
pub struct ThreadCpu {7
pub id: u64,8
pub name: String,9
pub cpu_ms: u64,10
}11
12
pub fn recorded_on_this_platform() -> bool {13
cfg!(target_os = "macos")14
}15
16
/// CPU used since the previous sample, summed by thread name. The first sample reports the17
/// time already used. Threads that share a name (tokio workers) stay separate in `previous`18
/// and add up on the line.19
pub fn cpu_deltas(current: &[ThreadCpu], previous: &mut HashMap<u64, u64>) -> Vec<(String, u64)> {20
let mut seen = Vec::with_capacity(current.len());21
let mut totals: HashMap<String, u64> = HashMap::new();22
for thread in current {23
let before = previous.get(&thread.id).copied().unwrap_or(0);24
*totals.entry(thread.name.clone()).or_default() += thread.cpu_ms.saturating_sub(before);25
previous.insert(thread.id, thread.cpu_ms);26
seen.push(thread.id);27
}28
previous.retain(|id, _| seen.contains(id));29
let mut deltas: Vec<(String, u64)> = totals.into_iter().collect();30
deltas.sort_by(|left, right| right.1.cmp(&left.1).then_with(|| left.0.cmp(&right.0)));31
deltas32
}33
34
const SHOWN_THREADS: usize = 8;35
36
pub fn host_load_line(deltas: &[(String, u64)], effects: &str, thermal: &str) -> String {37
let active: Vec<_> = deltas.iter().filter(|(_, cpu_ms)| *cpu_ms > 0).collect();38
let threads = if active.is_empty() {39
"no thread cpu".to_owned()40
} else {41
let shown = active.len().min(SHOWN_THREADS);42
let mut parts: Vec<String> = active[..shown]43
.iter()44
.map(|(name, cpu_ms)| format!("{name} {cpu_ms}ms"))45
.collect();46
if active.len() > SHOWN_THREADS {47
let rest: u64 = active[SHOWN_THREADS..]48
.iter()49
.map(|(_, cpu_ms)| *cpu_ms)50
.sum();51
parts.push(format!("others {rest}ms"));52
}53
parts.join(", ")54
};55
format!("{threads}; {effects}; thermal {thermal}")56
}57
58
/// Cumulative CPU time per thread. Empty off macOS, and empty when the kernel call fails.59
pub fn thread_cpu() -> Vec<ThreadCpu> {60
#[cfg(target_os = "macos")]61
{62
macos::thread_cpu()63
}64
#[cfg(not(target_os = "macos"))]65
{66
Vec::new()67
}68
}69
70
pub fn thermal_state() -> &'static str {71
#[cfg(target_os = "macos")]72
{73
macos::thermal_state()74
}75
#[cfg(not(target_os = "macos"))]76
{77
"unavailable"78
}79
}80
81
#[cfg(target_os = "macos")]82
mod macos {83
use super::ThreadCpu;84
85
unsafe extern "C" {86
fn mach_port_deallocate(87
task: libc::mach_port_t,88
name: libc::mach_port_t,89
) -> libc::kern_return_t;90
}91
92
pub fn thermal_state() -> &'static str {93
let state = objc2_foundation::NSProcessInfo::processInfo().thermalState();94
match state {95
objc2_foundation::NSProcessInfoThermalState::Nominal => "nominal",96
objc2_foundation::NSProcessInfoThermalState::Fair => "fair",97
objc2_foundation::NSProcessInfoThermalState::Serious => "serious",98
objc2_foundation::NSProcessInfoThermalState::Critical => "critical",99
_ => "unknown",100
}101
}102
103
pub fn thread_cpu() -> Vec<ThreadCpu> {104
unsafe {105
let task = libc::mach_task_self();106
let mut threads: libc::thread_act_array_t = std::ptr::null_mut();107
let mut count: libc::mach_msg_type_number_t = 0;108
if libc::task_threads(task, &mut threads, &mut count) != libc::KERN_SUCCESS {109
return Vec::new();110
}111
let mut found = Vec::with_capacity(count as usize);112
for index in 0..count {113
let thread = *threads.add(index as usize);114
let mut info: libc::thread_basic_info = std::mem::zeroed();115
let mut info_count = libc::THREAD_BASIC_INFO_COUNT;116
let status = libc::thread_info(117
thread,118
libc::THREAD_BASIC_INFO,119
&mut info as *mut libc::thread_basic_info as libc::thread_info_t,120
&mut info_count,121
);122
if status == libc::KERN_SUCCESS123
&& let Some(id) = thread_id(thread)124
{125
found.push(ThreadCpu {126
id,127
name: thread_name(thread),128
cpu_ms: cpu_ms(&info),129
});130
}131
// task_threads hands back a send right per thread. Freeing the array does not release those.132
let _ = mach_port_deallocate(task, thread);133
}134
let bytes = count as libc::vm_size_t135
* std::mem::size_of::<libc::thread_act_t>() as libc::vm_size_t;136
let _ = libc::vm_deallocate(task, threads as libc::vm_address_t, bytes);137
found138
}139
}140
141
fn cpu_ms(info: &libc::thread_basic_info) -> u64 {142
let part = |time: libc::time_value_t| {143
let seconds = i64::from(time.seconds).max(0);144
let micros = i64::from(time.microseconds).max(0);145
seconds.saturating_mul(1000) + micros / 1000146
};147
part(info.user_time).saturating_add(part(info.system_time)) as u64148
}149
150
/// Stable across samples. The Mach port from `task_threads` is reused after151
/// `mach_port_deallocate`, so it cannot key the previous sample.152
fn thread_id(thread: libc::thread_act_t) -> Option<u64> {153
unsafe {154
let mut info: libc::thread_identifier_info = std::mem::zeroed();155
let mut count = libc::THREAD_IDENTIFIER_INFO_COUNT;156
let status = libc::thread_info(157
thread,158
libc::THREAD_IDENTIFIER_INFO,159
&mut info as *mut libc::thread_identifier_info as libc::thread_info_t,160
&mut count,161
);162
if status == libc::KERN_SUCCESS && info.thread_id != 0 {163
Some(info.thread_id)164
} else {165
None166
}167
}168
}169
170
fn thread_name(thread: libc::thread_act_t) -> String {171
unsafe {172
let pthread = libc::pthread_from_mach_thread_np(thread);173
if !pthread.is_null() {174
let mut buffer = [0u8; 64];175
if libc::pthread_getname_np(pthread, buffer.as_mut_ptr().cast(), buffer.len()) == 0176
{177
let end = buffer178
.iter()179
.position(|byte| *byte == 0)180
.unwrap_or(buffer.len());181
if let Ok(name) = std::str::from_utf8(&buffer[..end]) {182
let name = name.trim();183
if !name.is_empty() {184
return name.to_owned();185
}186
}187
}188
}189
format!("tid-{thread}")190
}191
}192
}193
194
#[cfg(test)]195
mod tests {196
use super::*;197
198
#[test]199
fn a_host_load_line_names_the_hot_thread_the_effects_and_the_thermal_state() {200
let mut previous = HashMap::new();201
let first = cpu_deltas(202
&[203
ThreadCpu {204
id: 1,205
name: "camera".into(),206
cpu_ms: 40,207
},208
ThreadCpu {209
id: 2,210
name: "camera effects".into(),211
cpu_ms: 5,212
},213
],214
&mut previous,215
);216
let line = host_load_line(217
&first,218
"blur=off standout=off framing=off brightness=off soft_focus=off",219
"nominal",220
);221
assert_eq!(222
line,223
"camera 40ms, camera effects 5ms; blur=off standout=off framing=off brightness=off soft_focus=off; thermal nominal"224
);225
let second = cpu_deltas(226
&[227
ThreadCpu {228
id: 1,229
name: "camera".into(),230
cpu_ms: 90,231
},232
ThreadCpu {233
id: 2,234
name: "camera effects".into(),235
cpu_ms: 5,236
},237
],238
&mut previous,239
);240
assert_eq!(241
second,242
vec![("camera".into(), 50), ("camera effects".into(), 0)]243
);244
}245
246
#[test]247
fn shared_thread_names_sum_and_idle_threads_fold_out_of_the_line() {248
let mut previous = HashMap::new();249
let first = cpu_deltas(250
&[251
ThreadCpu {252
id: 10,253
name: "teams-net".into(),254
cpu_ms: 5_000,255
},256
ThreadCpu {257
id: 11,258
name: "teams-net".into(),259
cpu_ms: 300,260
},261
],262
&mut previous,263
);264
assert_eq!(first, vec![("teams-net".into(), 5_300)]);265
let second = cpu_deltas(266
&[267
ThreadCpu {268
id: 10,269
name: "teams-net".into(),270
cpu_ms: 5_300,271
},272
ThreadCpu {273
id: 11,274
name: "teams-net".into(),275
cpu_ms: 800,276
},277
],278
&mut previous,279
);280
assert_eq!(second, vec![("teams-net".into(), 800)]);281
let mut busy = Vec::new();282
for index in 0..10 {283
busy.push((format!("t{index}"), 10 - index));284
}285
busy.push(("idle".into(), 0));286
let line = host_load_line(287
&busy,288
"blur=off standout=off framing=off brightness=off soft_focus=off",289
"unknown",290
);291
assert_eq!(292
line,293
"t0 10ms, t1 9ms, t2 8ms, t3 7ms, t4 6ms, t5 5ms, t6 4ms, t7 3ms, others 3ms; blur=off standout=off framing=off brightness=off soft_focus=off; thermal unknown"294
);295
}296
297
#[test]298
fn host_load_is_recorded_only_on_macos() {299
assert_eq!(recorded_on_this_platform(), cfg!(target_os = "macos"));300
if !recorded_on_this_platform() {301
assert!(thread_cpu().is_empty());302
assert_eq!(thermal_state(), "unavailable");303
}304
}305
}@@ -25,6 +25,7 @@ pub mod error;
25
25
pub mod framing;
26
26
pub mod health;
27
27
pub mod hold;
28
pub mod host_load;
28
29
pub mod join;
29
30
pub mod latest;
30
31
pub mod level;
@@ -25,6 +25,7 @@ pub mod error;25
pub mod framing;25
pub mod framing;26
pub mod health;26
pub mod health;27
pub mod hold;27
pub mod hold;28
pub mod host_load;28
pub mod join;29
pub mod join;29
pub mod latest;30
pub mod latest;30
pub mod level;31
pub mod level;@@ -306,6 +306,13 @@ impl LocalVideo {
306
306
.map_err(|error| Error::Webrtc(error.to_string()))
307
307
}
308
308
309
fn outgoing_mut(&mut self, source: SendSource) -> &mut Outgoing {
310
match source {
311
SendSource::Camera => &mut self.camera,
312
SendSource::Screen => &mut self.screen,
313
}
314
}
315
309
316
fn sender_of(&self, source: SendSource) -> Option<RtpSender> {
310
317
let lines = self.lines.as_ref()?;
311
318
match source {
@@ -324,6 +331,13 @@ impl LocalVideo {
324
331
SendSource::Screen => self.sharing(),
325
332
};
326
333
let Some(sender) = self.sender_of(source).filter(|_| sending) else {
334
// The controller often sends the limit before the source exists.
335
// Keep it. A repeat of the same limit is dropped by the filter,
336
// and refresh applies this copy once sending and a frame size exist.
337
self.outgoing_mut(source).requested = Some(RequestedLimits {
338
limits: limits.to_vec(),
339
applied_for: None,
340
});
327
341
return Ok(None);
328
342
};
329
343
let outgoing = match source {
@@ -404,6 +418,24 @@ impl LocalVideo {
404
418
refreshed
405
419
}
406
420
421
/// Applies a limit that was waiting for this source and writes it on the call report.
422
/// The drive loop only records a refresh it performs itself.
423
fn record_refreshed_send_limits(&mut self) {
424
let Some(timeline) = self.timeline.clone() else {
425
self.refresh_send_limits();
426
return;
427
};
428
for (source, refreshed) in self.refresh_send_limits() {
429
match refreshed {
430
Ok(Some(plans)) => {
431
timeline.record("send limits", format!("{source:?} {plans:?}"));
432
}
433
Ok(None) => {}
434
Err(error) => timeline.record("send limits failed", error.to_string()),
435
}
436
}
437
}
438
407
439
fn set_layers(sender: &RtpSender, plans: &[LayerPlan], nudge: f64) -> Result<()> {
408
440
let mut parameters = sender.parameters();
409
441
for encoding in &mut parameters.encodings {
@@ -474,6 +506,19 @@ impl LocalVideo {
474
506
.filter(|model| !model.is_empty())
475
507
}
476
508
509
pub fn effects_label(&self) -> String {
510
let effects = self.blur.effects();
511
let flag = |on: bool| if on { "on" } else { "off" };
512
format!(
513
"blur={} standout={} framing={} brightness={} soft_focus={}",
514
flag(self.blur.enabled()),
515
flag(self.blur.standout()),
516
flag(effects.auto_framing),
517
flag(effects.adjust_brightness),
518
flag(effects.soft_focus)
519
)
520
}
521
477
522
pub fn has_lines(&self) -> bool {
478
523
self.lines.is_some()
479
524
}
@@ -724,6 +769,7 @@ impl LocalVideo {
724
769
}
725
770
Self::begin_sending_on(&lines.camera, &self.camera.track)?;
726
771
self.camera_preview = false;
772
self.record_refreshed_send_limits();
727
773
Ok(())
728
774
}
729
775
@@ -898,6 +944,7 @@ impl LocalVideo {
898
944
}
899
945
Self::begin_sending_on(&share, &self.screen.track)?;
900
946
let _ = self.tune_share(&share.sender());
947
self.record_refreshed_send_limits();
901
948
Ok(())
902
949
}
903
950
@@ -948,6 +995,77 @@ mod tests {
948
995
assert!(!video.camera_previewing() && !video.camera_on());
949
996
}
950
997
998
#[tokio::test]
999
async fn a_camera_limit_that_arrived_while_off_is_applied_when_the_camera_starts() {
1000
let factory = crate::devices::shared_factory();
1001
let peer = factory
1002
.create_peer_connection(RtcConfiguration::default())
1003
.expect("peer");
1004
let camera = peer
1005
.add_transceiver_for_media(
1006
MediaType::Video,
1007
RtpTransceiverInit {
1008
direction: RtpTransceiverDirection::SendRecv,
1009
stream_ids: vec!["camera".into()],
1010
send_encodings: Vec::new(),
1011
},
1012
)
1013
.expect("transceiver");
1014
let (updates, _) = tokio::sync::mpsc::unbounded_channel();
1015
let mut video = LocalVideo::new(
1016
&factory,
1017
VideoMode::Pattern,
1018
VideoHub::new(updates.clone()),
1019
updates,
1020
);
1021
video
1022
.set_lines(VideoLines {
1023
camera,
1024
share: None,
1025
})
1026
.expect("lines");
1027
let limit = |bitrate: u64| SendLimit {
1028
max_fs: Some(920),
1029
max_mbps: Some(13_800),
1030
max_fps: Some(15.0),
1031
max_bitrate: Some(bitrate),
1032
keyframe: false,
1033
rid: None,
1034
ssrc: None,
1035
};
1036
assert!(
1037
video
1038
.apply_send_limit(SendSource::Camera, &[limit(600_000)])
1039
.unwrap()
1040
.is_none()
1041
);
1042
assert!(
1043
video
1044
.apply_send_limit(SendSource::Camera, &[limit(100_000)])
1045
.unwrap()
1046
.is_none()
1047
);
1048
video
1049
.start_camera(&DeviceChoice::SystemDefault)
1050
.expect("camera");
1051
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
1052
let refreshed = video.refresh_send_limits();
1053
let bitrate = refreshed.iter().find_map(|(source, applied)| {
1054
(*source == SendSource::Camera)
1055
.then_some(applied)
1056
.and_then(|applied| {
1057
applied.as_ref().ok().and_then(|plans| {
1058
plans.as_ref().and_then(|plans| {
1059
plans.first().and_then(|plan| {
1060
plan.limits.as_ref().and_then(|limits| limits.max_bitrate)
1061
})
1062
})
1063
})
1064
})
1065
});
1066
assert_eq!(bitrate, Some(100_000));
1067
}
1068
951
1069
#[tokio::test]
952
1070
async fn clearing_a_sender_track_does_not_crash() {
953
1071
let factory = crate::devices::shared_factory();
@@ -306,6 +306,13 @@ impl LocalVideo {306
.map_err(|error| Error::Webrtc(error.to_string()))306
.map_err(|error| Error::Webrtc(error.to_string()))307
}307
}308
308
309
fn outgoing_mut(&mut self, source: SendSource) -> &mut Outgoing {310
match source {311
SendSource::Camera => &mut self.camera,312
SendSource::Screen => &mut self.screen,313
}314
}315
309
fn sender_of(&self, source: SendSource) -> Option<RtpSender> {316
fn sender_of(&self, source: SendSource) -> Option<RtpSender> {310
let lines = self.lines.as_ref()?;317
let lines = self.lines.as_ref()?;311
match source {318
match source {@@ -324,6 +331,13 @@ impl LocalVideo {324
SendSource::Screen => self.sharing(),331
SendSource::Screen => self.sharing(),325
};332
};326
let Some(sender) = self.sender_of(source).filter(|_| sending) else {333
let Some(sender) = self.sender_of(source).filter(|_| sending) else {334
// The controller often sends the limit before the source exists.335
// Keep it. A repeat of the same limit is dropped by the filter,336
// and refresh applies this copy once sending and a frame size exist.337
self.outgoing_mut(source).requested = Some(RequestedLimits {338
limits: limits.to_vec(),339
applied_for: None,340
});327
return Ok(None);341
return Ok(None);328
};342
};329
let outgoing = match source {343
let outgoing = match source {@@ -404,6 +418,24 @@ impl LocalVideo {404
refreshed418
refreshed405
}419
}406
420
421
/// Applies a limit that was waiting for this source and writes it on the call report.422
/// The drive loop only records a refresh it performs itself.423
fn record_refreshed_send_limits(&mut self) {424
let Some(timeline) = self.timeline.clone() else {425
self.refresh_send_limits();426
return;427
};428
for (source, refreshed) in self.refresh_send_limits() {429
match refreshed {430
Ok(Some(plans)) => {431
timeline.record("send limits", format!("{source:?} {plans:?}"));432
}433
Ok(None) => {}434
Err(error) => timeline.record("send limits failed", error.to_string()),435
}436
}437
}438
407
fn set_layers(sender: &RtpSender, plans: &[LayerPlan], nudge: f64) -> Result<()> {439
fn set_layers(sender: &RtpSender, plans: &[LayerPlan], nudge: f64) -> Result<()> {408
let mut parameters = sender.parameters();440
let mut parameters = sender.parameters();409
for encoding in &mut parameters.encodings {441
for encoding in &mut parameters.encodings {@@ -474,6 +506,19 @@ impl LocalVideo {474
.filter(|model| !model.is_empty())506
.filter(|model| !model.is_empty())475
}507
}476
508
509
pub fn effects_label(&self) -> String {510
let effects = self.blur.effects();511
let flag = |on: bool| if on { "on" } else { "off" };512
format!(513
"blur={} standout={} framing={} brightness={} soft_focus={}",514
flag(self.blur.enabled()),515
flag(self.blur.standout()),516
flag(effects.auto_framing),517
flag(effects.adjust_brightness),518
flag(effects.soft_focus)519
)520
}521
477
pub fn has_lines(&self) -> bool {522
pub fn has_lines(&self) -> bool {478
self.lines.is_some()523
self.lines.is_some()479
}524
}@@ -724,6 +769,7 @@ impl LocalVideo {724
}769
}725
Self::begin_sending_on(&lines.camera, &self.camera.track)?;770
Self::begin_sending_on(&lines.camera, &self.camera.track)?;726
self.camera_preview = false;771
self.camera_preview = false;772
self.record_refreshed_send_limits();727
Ok(())773
Ok(())728
}774
}729
775
@@ -898,6 +944,7 @@ impl LocalVideo {898
}944
}899
Self::begin_sending_on(&share, &self.screen.track)?;945
Self::begin_sending_on(&share, &self.screen.track)?;900
let _ = self.tune_share(&share.sender());946
let _ = self.tune_share(&share.sender());947
self.record_refreshed_send_limits();901
Ok(())948
Ok(())902
}949
}903
950
@@ -948,6 +995,77 @@ mod tests {948
assert!(!video.camera_previewing() && !video.camera_on());995
assert!(!video.camera_previewing() && !video.camera_on());949
}996
}950
997
998
#[tokio::test]999
async fn a_camera_limit_that_arrived_while_off_is_applied_when_the_camera_starts() {1000
let factory = crate::devices::shared_factory();1001
let peer = factory1002
.create_peer_connection(RtcConfiguration::default())1003
.expect("peer");1004
let camera = peer1005
.add_transceiver_for_media(1006
MediaType::Video,1007
RtpTransceiverInit {1008
direction: RtpTransceiverDirection::SendRecv,1009
stream_ids: vec!["camera".into()],1010
send_encodings: Vec::new(),1011
},1012
)1013
.expect("transceiver");1014
let (updates, _) = tokio::sync::mpsc::unbounded_channel();1015
let mut video = LocalVideo::new(1016
&factory,1017
VideoMode::Pattern,1018
VideoHub::new(updates.clone()),1019
updates,1020
);1021
video1022
.set_lines(VideoLines {1023
camera,1024
share: None,1025
})1026
.expect("lines");1027
let limit = |bitrate: u64| SendLimit {1028
max_fs: Some(920),1029
max_mbps: Some(13_800),1030
max_fps: Some(15.0),1031
max_bitrate: Some(bitrate),1032
keyframe: false,1033
rid: None,1034
ssrc: None,1035
};1036
assert!(1037
video1038
.apply_send_limit(SendSource::Camera, &[limit(600_000)])1039
.unwrap()1040
.is_none()1041
);1042
assert!(1043
video1044
.apply_send_limit(SendSource::Camera, &[limit(100_000)])1045
.unwrap()1046
.is_none()1047
);1048
video1049
.start_camera(&DeviceChoice::SystemDefault)1050
.expect("camera");1051
tokio::time::sleep(std::time::Duration::from_millis(200)).await;1052
let refreshed = video.refresh_send_limits();1053
let bitrate = refreshed.iter().find_map(|(source, applied)| {1054
(*source == SendSource::Camera)1055
.then_some(applied)1056
.and_then(|applied| {1057
applied.as_ref().ok().and_then(|plans| {1058
plans.as_ref().and_then(|plans| {1059
plans.first().and_then(|plan| {1060
plan.limits.as_ref().and_then(|limits| limits.max_bitrate)1061
})1062
})1063
})1064
})1065
});1066
assert_eq!(bitrate, Some(100_000));1067
}1068
951
#[tokio::test]1069
#[tokio::test]952
async fn clearing_a_sender_track_does_not_crash() {1070
async fn clearing_a_sender_track_does_not_crash() {953
let factory = crate::devices::shared_factory();1071
let factory = crate::devices::shared_factory();@@ -16,6 +16,7 @@ Run on a real Mac (`.app` from `scripts/build-macos.sh` or a release zip). Unit
16
16
3. Pick a display or window: share banner shows; stop share leaves the call up.
17
17
4. Cancel the picker: no share, call stays connected, no error toast.
18
18
5. Prefer a second person for 1:1 ring / accept when available (ROADMAP still Partial without that).
19
6. Camera on, no blur, standout, auto framing, brightness, or soft focus, and no share, for one minute. The call report (`host load`, every two seconds) names the threads that used CPU, says those effects are off, and states thermal state `nominal`, `fair`, `serious`, or `critical`. The next capture change follows the hottest thread in that report. This minute is the gate; it is not a substitute for guessing a GPU path.
19
20
20
21
## Desktop integration
21
22
@@ -16,6 +16,7 @@ Run on a real Mac (`.app` from `scripts/build-macos.sh` or a release zip). Unit16
3. Pick a display or window: share banner shows; stop share leaves the call up.16
3. Pick a display or window: share banner shows; stop share leaves the call up.17
4. Cancel the picker: no share, call stays connected, no error toast.17
4. Cancel the picker: no share, call stays connected, no error toast.18
5. Prefer a second person for 1:1 ring / accept when available (ROADMAP still Partial without that).18
5. Prefer a second person for 1:1 ring / accept when available (ROADMAP still Partial without that).19
6. Camera on, no blur, standout, auto framing, brightness, or soft focus, and no share, for one minute. The call report (`host load`, every two seconds) names the threads that used CPU, says those effects are off, and states thermal state `nominal`, `fair`, `serious`, or `critical`. The next capture change follows the hottest thread in that report. This minute is the gate; it is not a substitute for guessing a GPU path.19
20
20
## Desktop integration21
## Desktop integration21
22