BlueGit

ict rusty-teams

feat(calls): save a pseudonymized test report after each call

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

metis Daniel Däschle · pushed by metis

Authored 2026-10-13 · 7 weeks ago

Hash
88ecaa13008a91641a7b0d6e3cbd6a346f67380e
Parent
5e8bccf0
21 files changed +1918 −9
README.md +1 −0
@@ -64,6 +64,7 @@
64 64 - Video and screen sharing: H264 tiles, shared screen on a stage (double click for full window, Esc back), camera and screen share buttons with a "You are sharing" banner. Linux needs glib at run time
65 65 - Incoming calls: topmost ring toast with Decline and Accept, ring tone, missed calls in Activity
66 66 - Join a running meeting from its chat (audio): roster tiles, speaking ring, lobby state, Leave or End meeting for the organizer
67 - After every call a pseudonymized test report (JSON and Markdown, newest 30) is saved to the app data folder `call-reports`; toast "Test report saved" with Open folder, Settings > Devices switch
67 68 - Organizer controls: lobby banner with Admit and Deny, tile menu (pin, spotlight, mute, remove), Mute all, live captions overlay, camera background blur
68 69
69 70 **Agents (MCP)**
@@ -64,6 +64,7 @@
64- Video and screen sharing: H264 tiles, shared screen on a stage (double click for full window, Esc back), camera and screen share buttons with a "You are sharing" banner. Linux needs glib at run time
64- Video and screen sharing: H264 tiles, shared screen on a stage (double click for full window, Esc back), camera and screen share buttons with a "You are sharing" banner. Linux needs glib at run time
65- Incoming calls: topmost ring toast with Decline and Accept, ring tone, missed calls in Activity
65- Incoming calls: topmost ring toast with Decline and Accept, ring tone, missed calls in Activity
66- Join a running meeting from its chat (audio): roster tiles, speaking ring, lobby state, Leave or End meeting for the organizer
66- Join a running meeting from its chat (audio): roster tiles, speaking ring, lobby state, Leave or End meeting for the organizer
67- After every call a pseudonymized test report (JSON and Markdown, newest 30) is saved to the app data folder `call-reports`; toast "Test report saved" with Open folder, Settings > Devices switch
67- Organizer controls: lobby banner with Admit and Deny, tile menu (pin, spotlight, mute, remove), Mute all, live captions overlay, camera background blur
68- Organizer controls: lobby banner with Admit and Deny, tile menu (pin, spotlight, mute, remove), Mute all, live captions overlay, camera background blur
68
69
69**Agents (MCP)**
70**Agents (MCP)**
ROADMAP.md +3 −2
@@ -2,7 +2,7 @@
2 2
3 3 Feature parity with the Microsoft Teams desktop client.
4 4
5 **Parity: 80 %** (83 done, 28 partial, 10 missing of 121). Partial counts half.
5 **Parity: 80 %** (84 done, 28 partial, 10 missing of 122). Partial counts half.
6 6
7 7 ## By area
8 8
@@ -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) | 49 % | 5 | 27 | 6 |
21 | [Calls and meetings](#calls-and-meetings) | 50 % | 6 | 27 | 6 |
22 22
23 23 ## Next
24 24
@@ -164,6 +164,7 @@ Feature parity with the Microsoft Teams desktop client.
164 164 | Feature | State | Note |
165 165 |---|---|---|
166 166 | Test call (Echo bot) | Done | Native libwebrtc audio, call view, mini window, mute, devices |
167 | Call test report | Done | After every call a pseudonymized JSON and Markdown report lands in the app data folder `call-reports` (newest 30): timeline, SDP summary, stats every 2 s as min / max / last, features used with result, notices, end reason. People, e-mails, phone numbers, ids, URL queries, IPs, ICE credentials, fingerprints and chat text never reach the file. Toast "Test report saved" with Open folder; Settings > Devices switch, default on. Demo calls write one too |
167 168 | Incoming call: ring, accept, decline | Partial | Ring toast, ring tone, missed call in Activity, registrar endpoint, attach + accept. Built from the Teams code, not yet rung by a second person |
168 169 | 1:1 and group calls | Partial | Phone button, Calling and Ringing tiles, end notices, direct to mixer renegotiation. Not yet tried with a second person |
169 170 | Join a meeting from a chat | Partial | Join button from the live meeting state, joins muted, roster tiles, lobby, Leave and End meeting. Audio only. Verified with a meeting of one; not yet with other participants |
@@ -2,7 +2,7 @@
2
2
3Feature parity with the Microsoft Teams desktop client.
3Feature parity with the Microsoft Teams desktop client.
4
4
5**Parity: 80 %** (83 done, 28 partial, 10 missing of 121). Partial counts half.
5**Parity: 80 %** (84 done, 28 partial, 10 missing of 122). Partial counts half.
6
6
7## By area
7## By area
8
8
@@ -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) | 49 % | 5 | 27 | 6 |
21| [Calls and meetings](#calls-and-meetings) | 50 % | 6 | 27 | 6 |
22
22
23## Next
23## Next
24
24
@@ -164,6 +164,7 @@ Feature parity with the Microsoft Teams desktop client.
164| Feature | State | Note |
164| Feature | State | Note |
165|---|---|---|
165|---|---|---|
166| Test call (Echo bot) | Done | Native libwebrtc audio, call view, mini window, mute, devices |
166| Test call (Echo bot) | Done | Native libwebrtc audio, call view, mini window, mute, devices |
167| Call test report | Done | After every call a pseudonymized JSON and Markdown report lands in the app data folder `call-reports` (newest 30): timeline, SDP summary, stats every 2 s as min / max / last, features used with result, notices, end reason. People, e-mails, phone numbers, ids, URL queries, IPs, ICE credentials, fingerprints and chat text never reach the file. Toast "Test report saved" with Open folder; Settings > Devices switch, default on. Demo calls write one too |
167| Incoming call: ring, accept, decline | Partial | Ring toast, ring tone, missed call in Activity, registrar endpoint, attach + accept. Built from the Teams code, not yet rung by a second person |
168| Incoming call: ring, accept, decline | Partial | Ring toast, ring tone, missed call in Activity, registrar endpoint, attach + accept. Built from the Teams code, not yet rung by a second person |
168| 1:1 and group calls | Partial | Phone button, Calling and Ringing tiles, end notices, direct to mixer renegotiation. Not yet tried with a second person |
169| 1:1 and group calls | Partial | Phone button, Calling and Ringing tiles, end notices, direct to mixer renegotiation. Not yet tried with a second person |
169| Join a meeting from a chat | Partial | Join button from the live meeting state, joins muted, roster tiles, lobby, Leave and End meeting. Audio only. Verified with a meeting of one; not yet with other participants |
170| Join a meeting from a chat | Partial | Join button from the live meeting state, joins muted, roster tiles, lobby, Leave and End meeting. Audio only. Verified with a meeting of one; not yet with other participants |
crates/app/src/app_state.rs +3 −0
@@ -129,6 +129,7 @@ pub struct AppState {
129 129 pub call_share_sound: bool,
130 130 pub call_share_motion: bool,
131 131 pub call_share_standout: bool,
132 pub call_report_enabled: bool,
132 133 pub call_strip_width: f32,
133 134 pub call_view: crate::call::ViewSettings,
134 135 pub call_background: crate::call::BackgroundPick,
@@ -241,6 +242,7 @@ impl AppState {
241 242 call_share_sound: false,
242 243 call_share_motion: false,
243 244 call_share_standout: false,
245 call_report_enabled: true,
244 246 call_strip_width: crate::call::STRIP_DEFAULT_WIDTH,
245 247 call_view: crate::call::ViewSettings::default(),
246 248 call_background: crate::call::BackgroundPick::None,
@@ -272,6 +274,7 @@ impl AppState {
272 274 state.call_share_sound = crate::call::load_share_sound(&state.store);
273 275 state.call_share_motion = crate::call::load_flag(&state.store, crate::call::SHARE_MOTION_META_KEY);
274 276 state.call_share_standout = crate::call::load_flag(&state.store, crate::call::SHARE_STANDOUT_META_KEY);
277 state.call_report_enabled = crate::call::load_report_enabled(&state.store);
275 278 state.call_strip_width = crate::call::load_strip_width(&state.store);
276 279 state.call_view = crate::call::ViewSettings::load(&state.store);
277 280 state.call_background = crate::call::load_background(&state.store);
@@ -129,6 +129,7 @@ pub struct AppState {
129 pub call_share_sound: bool,
129 pub call_share_sound: bool,
130 pub call_share_motion: bool,
130 pub call_share_motion: bool,
131 pub call_share_standout: bool,
131 pub call_share_standout: bool,
132 pub call_report_enabled: bool,
132 pub call_strip_width: f32,
133 pub call_strip_width: f32,
133 pub call_view: crate::call::ViewSettings,
134 pub call_view: crate::call::ViewSettings,
134 pub call_background: crate::call::BackgroundPick,
135 pub call_background: crate::call::BackgroundPick,
@@ -241,6 +242,7 @@ impl AppState {
241 call_share_sound: false,
242 call_share_sound: false,
242 call_share_motion: false,
243 call_share_motion: false,
243 call_share_standout: false,
244 call_share_standout: false,
245 call_report_enabled: true,
244 call_strip_width: crate::call::STRIP_DEFAULT_WIDTH,
246 call_strip_width: crate::call::STRIP_DEFAULT_WIDTH,
245 call_view: crate::call::ViewSettings::default(),
247 call_view: crate::call::ViewSettings::default(),
246 call_background: crate::call::BackgroundPick::None,
248 call_background: crate::call::BackgroundPick::None,
@@ -272,6 +274,7 @@ impl AppState {
272 state.call_share_sound = crate::call::load_share_sound(&state.store);
274 state.call_share_sound = crate::call::load_share_sound(&state.store);
273 state.call_share_motion = crate::call::load_flag(&state.store, crate::call::SHARE_MOTION_META_KEY);
275 state.call_share_motion = crate::call::load_flag(&state.store, crate::call::SHARE_MOTION_META_KEY);
274 state.call_share_standout = crate::call::load_flag(&state.store, crate::call::SHARE_STANDOUT_META_KEY);
276 state.call_share_standout = crate::call::load_flag(&state.store, crate::call::SHARE_STANDOUT_META_KEY);
277 state.call_report_enabled = crate::call::load_report_enabled(&state.store);
275 state.call_strip_width = crate::call::load_strip_width(&state.store);
278 state.call_strip_width = crate::call::load_strip_width(&state.store);
276 state.call_view = crate::call::ViewSettings::load(&state.store);
279 state.call_view = crate::call::ViewSettings::load(&state.store);
277 state.call_background = crate::call::load_background(&state.store);
280 state.call_background = crate::call::load_background(&state.store);
crates/app/src/call/actions.rs +81 −1
@@ -19,9 +19,13 @@ use super::media::CallMedia;
19 19 use super::mic::save_mic;
20 20 use super::model::{ActiveCall, CallKind, CallModel, ended_notice};
21 21 use super::prejoin::{DemoMeeting, MeetingJoin};
22 use super::report::{
23 CallRecorder, OwnIdentity, SETTING_META_KEY, SharedRecorder, report_directory, save_report, shared,
24 };
22 25 use super::ring::{MissedCall, RingOutcome};
23 26 use super::target::{is_organizer, plan_for_chat};
24 27 use crate::app_state::{AppEvent, AppState, Selection, chat_title};
28 use crate::notice::NoticeAction;
25 29 use crate::notify::selection_for;
26 30
27 31 const TIMER_REFRESH: Duration = Duration::from_millis(500);
@@ -41,6 +45,7 @@ pub const SHARE_SOUND_META_KEY: &str = "call_share_sound";
41 45 const CAMERA_META_KEY: &str = "call_camera";
42 46 const EFFECTS_META_KEY: &str = "call_camera_effects";
43 47 const DEFAULT_CAMERA_META: &str = "default";
48 const REPORT_SAVED_NOTICE: &str = "Test report saved";
44 49
45 50 pub fn load_share_sound(store: &store::Store) -> bool {
46 51 store.meta(SHARE_SOUND_META_KEY).ok().flatten().as_deref() == Some("1")
@@ -250,19 +255,73 @@ impl AppState {
250 255 self.send_call_command(CallCommand::SetCameraEffects(self.call_effects));
251 256 self.refresh_call_backgrounds(cx);
252 257 self.new_chat = false;
253 self.follow_call(call_id, updates, cx);
258 let report = self.start_call_report();
259 if let Some(call) = self.call.as_mut() {
260 call.report.clone_from(&report);
261 }
262 self.follow_call(call_id, updates, report, cx);
254 263 cx.emit(AppEvent::Call);
255 264 cx.notify();
256 265 }
257 266
267 fn start_call_report(&self) -> Option<SharedRecorder> {
268 let call = self.call.as_ref().filter(|_| self.call_report_enabled)?;
269 let me = self.directory.me.as_ref();
270 let own = OwnIdentity {
271 mri: me.map_or_else(String::new, |me| format!("{ORGID_PREFIX}{}", me.user_id)),
272 display_name: me.map_or_else(String::new, |me| me.display_name.clone()),
273 email: self.own_email.clone(),
274 };
275 let mut people: Vec<(String, String)> = call
276 .model
277 .tiles
278 .iter()
279 .map(|tile| (tile.mri.clone(), tile.name.clone()))
280 .collect();
281 if people.is_empty() {
282 people.push((String::new(), call.model.peer_name.clone()));
283 }
284 let recorder = CallRecorder::begin(
285 call.model.kind,
286 call.model.incoming,
287 self.mode.demo,
288 own,
289 people,
290 );
291 Some(shared(recorder))
292 }
293
294 pub(super) fn note_call_feature(&self, feature: &'static str, detail: String) {
295 if let Some(report) = self.call.as_ref().and_then(|call| call.report.as_ref()) {
296 report.borrow_mut().local_feature(feature, detail);
297 }
298 }
299
300 fn report_saved(&mut self, path: std::path::PathBuf, cx: &mut Context<Self>) {
301 let action = NoticeAction::new("Open folder", move |_, _| {
302 crate::downloads::reveal_in_file_manager(&path)
303 });
304 self.raise_notice(REPORT_SAVED_NOTICE.to_owned(), Some(action), cx);
305 }
306
307 pub fn set_call_report_enabled(&mut self, on: bool, cx: &mut Context<Self>) {
308 self.call_report_enabled = on;
309 let _ = self.store.set_meta(SETTING_META_KEY, if on { "1" } else { "0" });
310 cx.notify();
311 }
312
258 313 fn follow_call(
259 314 &mut self,
260 315 call_id: u64,
261 316 mut updates: tokio::sync::mpsc::UnboundedReceiver<CallUpdate>,
317 report: Option<SharedRecorder>,
262 318 cx: &mut Context<Self>,
263 319 ) {
264 320 cx.spawn(async move |this, cx| {
265 321 while let Some(update) = updates.recv().await {
322 if let Some(report) = &report {
323 report.borrow_mut().observe(&update);
324 }
266 325 let alive =
267 326 this.update(cx, |state, cx| state.apply_call_update(call_id, update, cx));
268 327 if alive.is_err() {
@@ -270,6 +329,22 @@ impl AppState {
270 329 }
271 330 }
272 331 let _ = this.update(cx, |state, cx| state.end_orphaned_call(call_id, cx));
332 let Some(report) = report else {
333 return;
334 };
335 let reason = EndReason::Failed("The call stopped unexpectedly".to_owned());
336 report.borrow_mut().observe(&CallUpdate::State(CallState::Ended { reason }));
337 let recorder = report.borrow().clone();
338 let saved = cx
339 .background_executor()
340 .spawn(async move { save_report(&report_directory(), &recorder.document()) })
341 .await;
342 match saved {
343 Ok(saved) => {
344 let _ = this.update(cx, |state, cx| state.report_saved(saved.json, cx));
345 }
346 Err(error) => log::warn!("call test report not saved: {error}"),
347 }
273 348 })
274 349 .detach();
275 350 cx.spawn(async move |this, cx| {
@@ -412,6 +487,9 @@ impl AppState {
412 487
413 488 pub(super) fn send_call_command(&self, command: CallCommand) {
414 489 if let Some(call) = &self.call {
490 if let Some(report) = &call.report {
491 report.borrow_mut().command(&command);
492 }
415 493 let _ = call.commands.send(command);
416 494 }
417 495 }
@@ -540,11 +618,13 @@ impl AppState {
540 618 return;
541 619 };
542 620 call.chat_open = !call.chat_open;
621 let chat_state = if call.chat_open { "open" } else { "close" };
543 622 if call.chat_open {
544 623 call.transcript_open = false;
545 624 self.transcript_panel = None;
546 625 call.people_open = false;
547 626 }
627 self.note_call_feature("chat", chat_state.to_owned());
548 628 cx.emit(AppEvent::Call);
549 629 cx.notify();
550 630 }
@@ -19,9 +19,13 @@ use super::media::CallMedia;
19use super::mic::save_mic;
19use super::mic::save_mic;
20use super::model::{ActiveCall, CallKind, CallModel, ended_notice};
20use super::model::{ActiveCall, CallKind, CallModel, ended_notice};
21use super::prejoin::{DemoMeeting, MeetingJoin};
21use super::prejoin::{DemoMeeting, MeetingJoin};
22use super::report::{
23 CallRecorder, OwnIdentity, SETTING_META_KEY, SharedRecorder, report_directory, save_report, shared,
24};
22use super::ring::{MissedCall, RingOutcome};
25use super::ring::{MissedCall, RingOutcome};
23use super::target::{is_organizer, plan_for_chat};
26use super::target::{is_organizer, plan_for_chat};
24use crate::app_state::{AppEvent, AppState, Selection, chat_title};
27use crate::app_state::{AppEvent, AppState, Selection, chat_title};
28use crate::notice::NoticeAction;
25use crate::notify::selection_for;
29use crate::notify::selection_for;
26
30
27const TIMER_REFRESH: Duration = Duration::from_millis(500);
31const TIMER_REFRESH: Duration = Duration::from_millis(500);
@@ -41,6 +45,7 @@ pub const SHARE_SOUND_META_KEY: &str = "call_share_sound";
41const CAMERA_META_KEY: &str = "call_camera";
45const CAMERA_META_KEY: &str = "call_camera";
42const EFFECTS_META_KEY: &str = "call_camera_effects";
46const EFFECTS_META_KEY: &str = "call_camera_effects";
43const DEFAULT_CAMERA_META: &str = "default";
47const DEFAULT_CAMERA_META: &str = "default";
48const REPORT_SAVED_NOTICE: &str = "Test report saved";
44
49
45pub fn load_share_sound(store: &store::Store) -> bool {
50pub fn load_share_sound(store: &store::Store) -> bool {
46 store.meta(SHARE_SOUND_META_KEY).ok().flatten().as_deref() == Some("1")
51 store.meta(SHARE_SOUND_META_KEY).ok().flatten().as_deref() == Some("1")
@@ -250,19 +255,73 @@ impl AppState {
250 self.send_call_command(CallCommand::SetCameraEffects(self.call_effects));
255 self.send_call_command(CallCommand::SetCameraEffects(self.call_effects));
251 self.refresh_call_backgrounds(cx);
256 self.refresh_call_backgrounds(cx);
252 self.new_chat = false;
257 self.new_chat = false;
253 self.follow_call(call_id, updates, cx);
258 let report = self.start_call_report();
259 if let Some(call) = self.call.as_mut() {
260 call.report.clone_from(&report);
261 }
262 self.follow_call(call_id, updates, report, cx);
254 cx.emit(AppEvent::Call);
263 cx.emit(AppEvent::Call);
255 cx.notify();
264 cx.notify();
256 }
265 }
257
266
267 fn start_call_report(&self) -> Option<SharedRecorder> {
268 let call = self.call.as_ref().filter(|_| self.call_report_enabled)?;
269 let me = self.directory.me.as_ref();
270 let own = OwnIdentity {
271 mri: me.map_or_else(String::new, |me| format!("{ORGID_PREFIX}{}", me.user_id)),
272 display_name: me.map_or_else(String::new, |me| me.display_name.clone()),
273 email: self.own_email.clone(),
274 };
275 let mut people: Vec<(String, String)> = call
276 .model
277 .tiles
278 .iter()
279 .map(|tile| (tile.mri.clone(), tile.name.clone()))
280 .collect();
281 if people.is_empty() {
282 people.push((String::new(), call.model.peer_name.clone()));
283 }
284 let recorder = CallRecorder::begin(
285 call.model.kind,
286 call.model.incoming,
287 self.mode.demo,
288 own,
289 people,
290 );
291 Some(shared(recorder))
292 }
293
294 pub(super) fn note_call_feature(&self, feature: &'static str, detail: String) {
295 if let Some(report) = self.call.as_ref().and_then(|call| call.report.as_ref()) {
296 report.borrow_mut().local_feature(feature, detail);
297 }
298 }
299
300 fn report_saved(&mut self, path: std::path::PathBuf, cx: &mut Context<Self>) {
301 let action = NoticeAction::new("Open folder", move |_, _| {
302 crate::downloads::reveal_in_file_manager(&path)
303 });
304 self.raise_notice(REPORT_SAVED_NOTICE.to_owned(), Some(action), cx);
305 }
306
307 pub fn set_call_report_enabled(&mut self, on: bool, cx: &mut Context<Self>) {
308 self.call_report_enabled = on;
309 let _ = self.store.set_meta(SETTING_META_KEY, if on { "1" } else { "0" });
310 cx.notify();
311 }
312
258 fn follow_call(
313 fn follow_call(
259 &mut self,
314 &mut self,
260 call_id: u64,
315 call_id: u64,
261 mut updates: tokio::sync::mpsc::UnboundedReceiver<CallUpdate>,
316 mut updates: tokio::sync::mpsc::UnboundedReceiver<CallUpdate>,
317 report: Option<SharedRecorder>,
262 cx: &mut Context<Self>,
318 cx: &mut Context<Self>,
263 ) {
319 ) {
264 cx.spawn(async move |this, cx| {
320 cx.spawn(async move |this, cx| {
265 while let Some(update) = updates.recv().await {
321 while let Some(update) = updates.recv().await {
322 if let Some(report) = &report {
323 report.borrow_mut().observe(&update);
324 }
266 let alive =
325 let alive =
267 this.update(cx, |state, cx| state.apply_call_update(call_id, update, cx));
326 this.update(cx, |state, cx| state.apply_call_update(call_id, update, cx));
268 if alive.is_err() {
327 if alive.is_err() {
@@ -270,6 +329,22 @@ impl AppState {
270 }
329 }
271 }
330 }
272 let _ = this.update(cx, |state, cx| state.end_orphaned_call(call_id, cx));
331 let _ = this.update(cx, |state, cx| state.end_orphaned_call(call_id, cx));
332 let Some(report) = report else {
333 return;
334 };
335 let reason = EndReason::Failed("The call stopped unexpectedly".to_owned());
336 report.borrow_mut().observe(&CallUpdate::State(CallState::Ended { reason }));
337 let recorder = report.borrow().clone();
338 let saved = cx
339 .background_executor()
340 .spawn(async move { save_report(&report_directory(), &recorder.document()) })
341 .await;
342 match saved {
343 Ok(saved) => {
344 let _ = this.update(cx, |state, cx| state.report_saved(saved.json, cx));
345 }
346 Err(error) => log::warn!("call test report not saved: {error}"),
347 }
273 })
348 })
274 .detach();
349 .detach();
275 cx.spawn(async move |this, cx| {
350 cx.spawn(async move |this, cx| {
@@ -412,6 +487,9 @@ impl AppState {
412
487
413 pub(super) fn send_call_command(&self, command: CallCommand) {
488 pub(super) fn send_call_command(&self, command: CallCommand) {
414 if let Some(call) = &self.call {
489 if let Some(call) = &self.call {
490 if let Some(report) = &call.report {
491 report.borrow_mut().command(&command);
492 }
415 let _ = call.commands.send(command);
493 let _ = call.commands.send(command);
416 }
494 }
417 }
495 }
@@ -540,11 +618,13 @@ impl AppState {
540 return;
618 return;
541 };
619 };
542 call.chat_open = !call.chat_open;
620 call.chat_open = !call.chat_open;
621 let chat_state = if call.chat_open { "open" } else { "close" };
543 if call.chat_open {
622 if call.chat_open {
544 call.transcript_open = false;
623 call.transcript_open = false;
545 self.transcript_panel = None;
624 self.transcript_panel = None;
546 call.people_open = false;
625 call.people_open = false;
547 }
626 }
627 self.note_call_feature("chat", chat_state.to_owned());
548 cx.emit(AppEvent::Call);
628 cx.emit(AppEvent::Call);
549 cx.notify();
629 cx.notify();
550 }
630 }
crates/app/src/call/demo.rs +71 −3
@@ -11,6 +11,9 @@ use calling::{
11 11 PublishedState, RaisedHand, Reaction, RecordingKind, RosterEntry, ShareKind, ShareSource, StopScope,
12 12 TransportDetails, VideoKey, call_channel,
13 13 };
14 use calling::call::VideoReport;
15 use calling::timeline::TimelineEntry;
16 use calling::{CallDiagnostics, SdpLine, SdpSummary, StatsSample};
14 17
15 18 use super::demo_scene::self_view;
16 19 use tokio::time::{interval, sleep};
@@ -23,6 +26,8 @@ const ANSWER_DELAY: Duration = Duration::from_millis(3200);
23 26 const INCOMING_CONNECT_DELAY: Duration = Duration::from_millis(600);
24 27 const LOBBY_WAIT: Duration = Duration::from_secs(6);
25 28 const LEVEL_PERIOD: Duration = Duration::from_millis(200);
29 const SAMPLE_EVERY_TICKS: u32 = 10;
30 const SAMPLE_PACKETS_PER_TICK: u64 = 10;
26 31 const CYCLE_TICKS: u32 = 40;
27 32 const REMOTE_SPEAKS: std::ops::Range<u32> = 0..18;
28 33 const LOCAL_SPEAKS: std::ops::Range<u32> = 24..32;
@@ -281,9 +286,7 @@ async fn run_demo_call(mut control: CallControl, script: DemoCall, scene: DemoSc
281 286 DemoCall::Incoming(caller) => (vec![caller.clone()], false),
282 287 };
283 288 if !ring_until_answered(&mut control, &script).await {
284 control.send(CallUpdate::State(CallState::Ended {
285 reason: EndReason::Cancelled,
286 }));
289 end(&control, EndReason::Cancelled);
287 290 return;
288 291 }
289 292 control.send(CallUpdate::ListenOnly(false));
@@ -527,6 +530,9 @@ async fn speak_until_hangup(
527 530 }
528 531 caption_ticks += 1;
529 532 }
533 if ticks.is_multiple_of(SAMPLE_EVERY_TICKS) {
534 control.send(CallUpdate::Sample(demo_sample(ticks, video)));
535 }
530 536 scene_tick(&control, scene, ticks, &people);
531 537 ticks += 1;
532 538 }
@@ -812,6 +818,68 @@ fn set_demo_hand(roster: &mut Vec<RosterEntry>, mri: &str, raised: bool) {
812 818
813 819 fn end(control: &CallControl, reason: EndReason) {
814 820 control.send(CallUpdate::State(CallState::Ended { reason }));
821 control.send(CallUpdate::Diagnostics(Box::new(demo_diagnostics())));
822 }
823
824 fn demo_sample(ticks: u32, video: bool) -> StatsSample {
825 let packets = u64::from(ticks) * SAMPLE_PACKETS_PER_TICK;
826 StatsSample {
827 audio_in_packets: packets,
828 audio_out_packets: packets,
829 audio_in_level: 0.05,
830 audio_out_level: 0.04,
831 video: if video {
832 VideoReport {
833 inbound_packets: packets * 4,
834 inbound_frames_decoded: packets,
835 inbound_width: 1280,
836 inbound_height: 720,
837 outbound_packets: packets * 3,
838 outbound_frames_encoded: packets,
839 outbound_width: 640,
840 outbound_height: 360,
841 ..VideoReport::default()
842 }
843 } else {
844 VideoReport::default()
845 },
846 ..StatsSample::default()
847 }
848 }
849
850 fn demo_diagnostics() -> CallDiagnostics {
851 let entry = |elapsed_ms: u128, label: &str, detail: &str| TimelineEntry {
852 elapsed_ms,
853 label: label.to_owned(),
854 detail: detail.to_owned(),
855 };
856 let line = |kind: &str, mid: &str, codecs: &[&str]| SdpLine {
857 kind: kind.to_owned(),
858 mid: mid.to_owned(),
859 direction: "sendrecv".to_owned(),
860 codecs: codecs.iter().map(|codec| (*codec).to_owned()).collect(),
861 payload_count: codecs.len(),
862 ssrc_count: 1,
863 rejected: false,
864 };
865 CallDiagnostics {
866 timeline: vec![
867 entry(5, "Trouter connected", "callback socket ready"),
868 entry(40, "setLocalDescription", "2 m-line(s) signaled"),
869 entry(900, "ICE state", "Connected"),
870 entry(950, "PeerConnection state", "Connected"),
871 ],
872 sdp: vec![
873 SdpSummary { at_ms: 40, role: "local offer".to_owned(), lines: vec![line("audio", "0", &["opus"]), line("video", "1", &["H264"])] },
874 SdpSummary { at_ms: 800, role: "remote answer".to_owned(), lines: vec![line("audio", "0", &["opus"]), line("video", "1", &["H264"])] },
875 ],
876 ice_connected_ms: Some(900),
877 peer_connected_ms: Some(950),
878 selected_pair: Some("local Host/udp <-> remote Host/udp".to_owned()),
879 tls_version: "1.2".to_owned(),
880 dtls_cipher: "demo".to_owned(),
881 srtp_cipher: "demo".to_owned(),
882 }
815 883 }
816 884
817 885 #[cfg(test)]
@@ -11,6 +11,9 @@ use calling::{
11 PublishedState, RaisedHand, Reaction, RecordingKind, RosterEntry, ShareKind, ShareSource, StopScope,
11 PublishedState, RaisedHand, Reaction, RecordingKind, RosterEntry, ShareKind, ShareSource, StopScope,
12 TransportDetails, VideoKey, call_channel,
12 TransportDetails, VideoKey, call_channel,
13};
13};
14use calling::call::VideoReport;
15use calling::timeline::TimelineEntry;
16use calling::{CallDiagnostics, SdpLine, SdpSummary, StatsSample};
14
17
15use super::demo_scene::self_view;
18use super::demo_scene::self_view;
16use tokio::time::{interval, sleep};
19use tokio::time::{interval, sleep};
@@ -23,6 +26,8 @@ const ANSWER_DELAY: Duration = Duration::from_millis(3200);
23const INCOMING_CONNECT_DELAY: Duration = Duration::from_millis(600);
26const INCOMING_CONNECT_DELAY: Duration = Duration::from_millis(600);
24const LOBBY_WAIT: Duration = Duration::from_secs(6);
27const LOBBY_WAIT: Duration = Duration::from_secs(6);
25const LEVEL_PERIOD: Duration = Duration::from_millis(200);
28const LEVEL_PERIOD: Duration = Duration::from_millis(200);
29const SAMPLE_EVERY_TICKS: u32 = 10;
30const SAMPLE_PACKETS_PER_TICK: u64 = 10;
26const CYCLE_TICKS: u32 = 40;
31const CYCLE_TICKS: u32 = 40;
27const REMOTE_SPEAKS: std::ops::Range<u32> = 0..18;
32const REMOTE_SPEAKS: std::ops::Range<u32> = 0..18;
28const LOCAL_SPEAKS: std::ops::Range<u32> = 24..32;
33const LOCAL_SPEAKS: std::ops::Range<u32> = 24..32;
@@ -281,9 +286,7 @@ async fn run_demo_call(mut control: CallControl, script: DemoCall, scene: DemoSc
281 DemoCall::Incoming(caller) => (vec![caller.clone()], false),
286 DemoCall::Incoming(caller) => (vec![caller.clone()], false),
282 };
287 };
283 if !ring_until_answered(&mut control, &script).await {
288 if !ring_until_answered(&mut control, &script).await {
284 control.send(CallUpdate::State(CallState::Ended {
289 end(&control, EndReason::Cancelled);
285 reason: EndReason::Cancelled,
286 }));
287 return;
290 return;
288 }
291 }
289 control.send(CallUpdate::ListenOnly(false));
292 control.send(CallUpdate::ListenOnly(false));
@@ -527,6 +530,9 @@ async fn speak_until_hangup(
527 }
530 }
528 caption_ticks += 1;
531 caption_ticks += 1;
529 }
532 }
533 if ticks.is_multiple_of(SAMPLE_EVERY_TICKS) {
534 control.send(CallUpdate::Sample(demo_sample(ticks, video)));
535 }
530 scene_tick(&control, scene, ticks, &people);
536 scene_tick(&control, scene, ticks, &people);
531 ticks += 1;
537 ticks += 1;
532 }
538 }
@@ -812,6 +818,68 @@ fn set_demo_hand(roster: &mut Vec<RosterEntry>, mri: &str, raised: bool) {
812
818
813fn end(control: &CallControl, reason: EndReason) {
819fn end(control: &CallControl, reason: EndReason) {
814 control.send(CallUpdate::State(CallState::Ended { reason }));
820 control.send(CallUpdate::State(CallState::Ended { reason }));
821 control.send(CallUpdate::Diagnostics(Box::new(demo_diagnostics())));
822}
823
824fn demo_sample(ticks: u32, video: bool) -> StatsSample {
825 let packets = u64::from(ticks) * SAMPLE_PACKETS_PER_TICK;
826 StatsSample {
827 audio_in_packets: packets,
828 audio_out_packets: packets,
829 audio_in_level: 0.05,
830 audio_out_level: 0.04,
831 video: if video {
832 VideoReport {
833 inbound_packets: packets * 4,
834 inbound_frames_decoded: packets,
835 inbound_width: 1280,
836 inbound_height: 720,
837 outbound_packets: packets * 3,
838 outbound_frames_encoded: packets,
839 outbound_width: 640,
840 outbound_height: 360,
841 ..VideoReport::default()
842 }
843 } else {
844 VideoReport::default()
845 },
846 ..StatsSample::default()
847 }
848}
849
850fn demo_diagnostics() -> CallDiagnostics {
851 let entry = |elapsed_ms: u128, label: &str, detail: &str| TimelineEntry {
852 elapsed_ms,
853 label: label.to_owned(),
854 detail: detail.to_owned(),
855 };
856 let line = |kind: &str, mid: &str, codecs: &[&str]| SdpLine {
857 kind: kind.to_owned(),
858 mid: mid.to_owned(),
859 direction: "sendrecv".to_owned(),
860 codecs: codecs.iter().map(|codec| (*codec).to_owned()).collect(),
861 payload_count: codecs.len(),
862 ssrc_count: 1,
863 rejected: false,
864 };
865 CallDiagnostics {
866 timeline: vec![
867 entry(5, "Trouter connected", "callback socket ready"),
868 entry(40, "setLocalDescription", "2 m-line(s) signaled"),
869 entry(900, "ICE state", "Connected"),
870 entry(950, "PeerConnection state", "Connected"),
871 ],
872 sdp: vec![
873 SdpSummary { at_ms: 40, role: "local offer".to_owned(), lines: vec![line("audio", "0", &["opus"]), line("video", "1", &["H264"])] },
874 SdpSummary { at_ms: 800, role: "remote answer".to_owned(), lines: vec![line("audio", "0", &["opus"]), line("video", "1", &["H264"])] },
875 ],
876 ice_connected_ms: Some(900),
877 peer_connected_ms: Some(950),
878 selected_pair: Some("local Host/udp <-> remote Host/udp".to_owned()),
879 tls_version: "1.2".to_owned(),
880 dtls_cipher: "demo".to_owned(),
881 srtp_cipher: "demo".to_owned(),
882 }
815}
883}
816
884
817#[cfg(test)]
885#[cfg(test)]
crates/app/src/call/features.rs +2 −0
@@ -269,6 +269,7 @@ impl AppState {
269 269 self.raise_notice("Not connected to Teams yet".to_owned(), None, cx);
270 270 return;
271 271 };
272 self.note_call_feature("consult", format!("start with {}", target.mri));
272 273 self.send_call_command(CallCommand::Hold(true));
273 274 self.call_count += 1;
274 275 let consult_id = self.call_count;
@@ -337,6 +338,7 @@ impl AppState {
337 338 let transferring = consult.transferring;
338 339 call.consult = None;
339 340 if !transferring {
341 self.note_call_feature("consult", "ended without a transfer".to_owned());
340 342 self.raise_notice("The consultation ended".to_owned(), None, cx);
341 343 self.send_call_command(CallCommand::Hold(false));
342 344 }
@@ -269,6 +269,7 @@ impl AppState {
269 self.raise_notice("Not connected to Teams yet".to_owned(), None, cx);
269 self.raise_notice("Not connected to Teams yet".to_owned(), None, cx);
270 return;
270 return;
271 };
271 };
272 self.note_call_feature("consult", format!("start with {}", target.mri));
272 self.send_call_command(CallCommand::Hold(true));
273 self.send_call_command(CallCommand::Hold(true));
273 self.call_count += 1;
274 self.call_count += 1;
274 let consult_id = self.call_count;
275 let consult_id = self.call_count;
@@ -337,6 +338,7 @@ impl AppState {
337 let transferring = consult.transferring;
338 let transferring = consult.transferring;
338 call.consult = None;
339 call.consult = None;
339 if !transferring {
340 if !transferring {
341 self.note_call_feature("consult", "ended without a transfer".to_owned());
340 self.raise_notice("The consultation ended".to_owned(), None, cx);
342 self.raise_notice("The consultation ended".to_owned(), None, cx);
341 self.send_call_command(CallCommand::Hold(false));
343 self.send_call_command(CallCommand::Hold(false));
342 }
344 }
crates/app/src/call/mod.rs +2 −0
@@ -26,6 +26,7 @@ mod prejoin;
26 26 mod preview;
27 27 mod push_to_talk;
28 28 mod recording_menu;
29 mod report;
29 30 mod reminder;
30 31 mod share_actions;
31 32 mod share_view;
@@ -72,6 +73,7 @@ pub use ring::{MissedCall, RingEntry, Rings};
72 73 pub use stage_layout::{FILMSTRIP_MAX, Filmstrip, GALLERY_MAX, Overflow, filmstrip, gallery_grid, split_overflow};
73 74 pub use schedule::{FormValues, Invitee, default_window, draft_from_form};
74 75 pub use recording_menu::{RecordAction, RecordingChip, record_actions, recording_chip};
76 pub use report::load_enabled as load_report_enabled;
75 77 pub use target::plan_for_chat;
76 78 pub use transcript::clock_label;
77 79 pub use view_settings::{CallLayout, ViewSettings};
@@ -26,6 +26,7 @@ mod prejoin;
26mod preview;
26mod preview;
27mod push_to_talk;
27mod push_to_talk;
28mod recording_menu;
28mod recording_menu;
29mod report;
29mod reminder;
30mod reminder;
30mod share_actions;
31mod share_actions;
31mod share_view;
32mod share_view;
@@ -72,6 +73,7 @@ pub use ring::{MissedCall, RingEntry, Rings};
72pub use stage_layout::{FILMSTRIP_MAX, Filmstrip, GALLERY_MAX, Overflow, filmstrip, gallery_grid, split_overflow};
73pub use stage_layout::{FILMSTRIP_MAX, Filmstrip, GALLERY_MAX, Overflow, filmstrip, gallery_grid, split_overflow};
73pub use schedule::{FormValues, Invitee, default_window, draft_from_form};
74pub use schedule::{FormValues, Invitee, default_window, draft_from_form};
74pub use recording_menu::{RecordAction, RecordingChip, record_actions, recording_chip};
75pub use recording_menu::{RecordAction, RecordingChip, record_actions, recording_chip};
76pub use report::load_enabled as load_report_enabled;
75pub use target::plan_for_chat;
77pub use target::plan_for_chat;
76pub use transcript::clock_label;
78pub use transcript::clock_label;
77pub use view_settings::{CallLayout, ViewSettings};
79pub use view_settings::{CallLayout, ViewSettings};
crates/app/src/call/model.rs +5 −0
@@ -21,6 +21,7 @@ use super::transcript::{Transcript, TranscriptEntry};
21 21 use super::view_settings::{CallLayout, ViewSettings};
22 22 use super::options_dialog::OptionsDialog;
23 23 use super::push_to_talk::PushToTalk;
24 use super::report::SharedRecorder;
24 25 use super::share_view::ShareStage;
25 26
26 27 pub const TEST_CALL_TITLE: &str = "Test call";
@@ -59,6 +60,7 @@ pub struct ActiveCall {
59 60 pub pending_move: Option<PendingMove>,
60 61 pub consult: Option<ConsultCall>,
61 62 pub push_to_talk: PushToTalk,
63 pub report: Option<SharedRecorder>,
62 64 }
63 65
64 66 #[derive(Debug, Clone, PartialEq)]
@@ -127,6 +129,7 @@ impl ActiveCall {
127 129 pending_move: None,
128 130 consult: None,
129 131 push_to_talk: PushToTalk::default(),
132 report: None,
130 133 }
131 134 }
132 135
@@ -493,6 +496,8 @@ impl CallModel {
493 496 CallUpdate::Capability(capability) => self.capability = capability,
494 497 CallUpdate::BreakoutRoom { main } => self.main_meeting = Some(main),
495 498 CallUpdate::BlurTiming(_)
499 | CallUpdate::Sample(_)
500 | CallUpdate::Diagnostics(_)
496 501 | CallUpdate::Organizer { .. }
497 502 | CallUpdate::MeetingOptions(_)
498 503 | CallUpdate::MeetingOptionsSaved(_)
@@ -21,6 +21,7 @@ use super::transcript::{Transcript, TranscriptEntry};
21use super::view_settings::{CallLayout, ViewSettings};
21use super::view_settings::{CallLayout, ViewSettings};
22use super::options_dialog::OptionsDialog;
22use super::options_dialog::OptionsDialog;
23use super::push_to_talk::PushToTalk;
23use super::push_to_talk::PushToTalk;
24use super::report::SharedRecorder;
24use super::share_view::ShareStage;
25use super::share_view::ShareStage;
25
26
26pub const TEST_CALL_TITLE: &str = "Test call";
27pub const TEST_CALL_TITLE: &str = "Test call";
@@ -59,6 +60,7 @@ pub struct ActiveCall {
59 pub pending_move: Option<PendingMove>,
60 pub pending_move: Option<PendingMove>,
60 pub consult: Option<ConsultCall>,
61 pub consult: Option<ConsultCall>,
61 pub push_to_talk: PushToTalk,
62 pub push_to_talk: PushToTalk,
63 pub report: Option<SharedRecorder>,
62}
64}
63
65
64#[derive(Debug, Clone, PartialEq)]
66#[derive(Debug, Clone, PartialEq)]
@@ -127,6 +129,7 @@ impl ActiveCall {
127 pending_move: None,
129 pending_move: None,
128 consult: None,
130 consult: None,
129 push_to_talk: PushToTalk::default(),
131 push_to_talk: PushToTalk::default(),
132 report: None,
130 }
133 }
131 }
134 }
132
135
@@ -493,6 +496,8 @@ impl CallModel {
493 CallUpdate::Capability(capability) => self.capability = capability,
496 CallUpdate::Capability(capability) => self.capability = capability,
494 CallUpdate::BreakoutRoom { main } => self.main_meeting = Some(main),
497 CallUpdate::BreakoutRoom { main } => self.main_meeting = Some(main),
495 CallUpdate::BlurTiming(_)
498 CallUpdate::BlurTiming(_)
499 | CallUpdate::Sample(_)
500 | CallUpdate::Diagnostics(_)
496 | CallUpdate::Organizer { .. }
501 | CallUpdate::Organizer { .. }
497 | CallUpdate::MeetingOptions(_)
502 | CallUpdate::MeetingOptions(_)
498 | CallUpdate::MeetingOptionsSaved(_)
503 | CallUpdate::MeetingOptionsSaved(_)
crates/app/src/call/report/document.rs added +429 −0
@@ -0,0 +1,429 @@
1 use std::collections::BTreeMap;
2
3 use calling::{EndKind, EndReason, MediaPath};
4 use serde::Serialize;
5
6 use super::markdown;
7 use super::scrub::Scrubber;
8 use super::series::{level_name, limitation_name};
9 use super::{CallRecorder, FeatureRecord, Outcome};
10 use crate::call::model::CallKind;
11
12 const SCHEMA: u32 = 1;
13 const FILE_STAMP: &str = "%Y%m%dT%H%M%SZ";
14 const READABLE_STAMP: &str = "%Y-%m-%d %H:%M:%S";
15 const MIN_SAMPLES_FOR_STALLS: u32 = 3;
16 const ESCALATION_LABEL: &str = "escalation";
17 const TRANSFER_LABEL: &str = "transfer";
18 const FAILURE_WORDS: [&str; 3] = ["failed", "rejected", "not understood"];
19 const FEATURE_FAILURE_LABELS: [(&str, &str); 11] = [
20 ("raise hand failed", "hand"),
21 ("lower hand failed", "hand"),
22 ("lower all hands failed", "hand"),
23 ("hold failed", "hold"),
24 ("transfer failed", "transfer"),
25 ("reaction failed", "reaction"),
26 ("camera offer failed", "camera"),
27 ("recording consent failed", "recording"),
28 ("caption language failed", "captions"),
29 ("caption start failed", "captions"),
30 ("end meeting failed", "people action"),
31 ];
32
33 pub struct Document {
34 pub stem: String,
35 pub json: String,
36 pub markdown: String,
37 }
38
39 #[derive(Debug, Serialize)]
40 pub struct Report {
41 pub schema: u32,
42 pub app: AppInfo,
43 pub call: CallInfo,
44 pub media: MediaInfo,
45 pub participants: ParticipantInfo,
46 pub problems: Vec<String>,
47 pub stats: StatsInfo,
48 pub features: Vec<FeatureInfo>,
49 pub notices: Vec<NoticeInfo>,
50 pub states: Vec<StateInfo>,
51 pub sdp: Vec<SdpInfo>,
52 pub timeline: Vec<TimelineInfo>,
53 }
54
55 #[derive(Debug, Serialize)]
56 pub struct AppInfo {
57 pub version: &'static str,
58 pub build: &'static str,
59 pub os: &'static str,
60 pub arch: &'static str,
61 pub demo: bool,
62 }
63
64 #[derive(Debug, Serialize)]
65 pub struct CallInfo {
66 pub kind: &'static str,
67 pub direction: &'static str,
68 pub started_utc: String,
69 pub connect_ms: Option<u128>,
70 pub total_ms: Option<u128>,
71 pub connected_ms: Option<u128>,
72 pub end_reason: String,
73 pub engine_ice_connected_ms: Option<u128>,
74 pub engine_peer_connected_ms: Option<u128>,
75 }
76
77 #[derive(Debug, Serialize)]
78 pub struct MediaInfo {
79 pub path: &'static str,
80 pub path_changes: Vec<PathChange>,
81 pub escalations: usize,
82 pub escalation_failures: usize,
83 pub selected_pair: Option<String>,
84 pub tls_version: String,
85 pub dtls_cipher: String,
86 pub srtp_cipher: String,
87 }
88
89 #[derive(Debug, Serialize)]
90 pub struct PathChange {
91 pub at_ms: u128,
92 pub path: &'static str,
93 }
94
95 #[derive(Debug, Serialize)]
96 pub struct ParticipantInfo {
97 pub peak_present: usize,
98 pub known: Vec<String>,
99 pub captions_received: u32,
100 }
101
102 #[derive(Debug, Serialize)]
103 pub struct StatsInfo {
104 pub samples: u32,
105 pub metrics: BTreeMap<&'static str, Range>,
106 pub audio_in_stalled_samples: u32,
107 pub audio_out_stalled_samples: u32,
108 pub health_samples: BTreeMap<&'static str, u32>,
109 pub health_level_changes: Vec<PathChange>,
110 pub quality_limitation_samples: BTreeMap<&'static str, u32>,
111 pub cpu_limited_samples: u32,
112 }
113
114 #[derive(Debug, Serialize)]
115 pub struct Range {
116 pub min: f64,
117 pub max: f64,
118 pub last: f64,
119 }
120
121 #[derive(Debug, Serialize)]
122 pub struct FeatureInfo {
123 pub at_ms: u128,
124 pub feature: &'static str,
125 pub detail: String,
126 pub result: &'static str,
127 pub confirmed_at_ms: Option<u128>,
128 pub error: Option<String>,
129 }
130
131 #[derive(Debug, Serialize)]
132 pub struct NoticeInfo {
133 pub at_ms: u128,
134 pub text: String,
135 }
136
137 #[derive(Debug, Serialize)]
138 pub struct StateInfo {
139 pub at_ms: u128,
140 pub state: String,
141 }
142
143 #[derive(Debug, Serialize)]
144 pub struct SdpInfo {
145 pub engine_ms: u128,
146 pub role: String,
147 pub lines: Vec<SdpLineInfo>,
148 }
149
150 #[derive(Debug, Serialize)]
151 pub struct SdpLineInfo {
152 pub kind: String,
153 pub mid: String,
154 pub direction: String,
155 pub codecs: Vec<String>,
156 pub payloads: usize,
157 pub ssrcs: usize,
158 pub rejected: bool,
159 }
160
161 #[derive(Debug, Serialize)]
162 pub struct TimelineInfo {
163 pub engine_ms: u128,
164 pub label: String,
165 pub detail: String,
166 }
167
168 fn kind_label(kind: CallKind) -> &'static str {
169 match kind {
170 CallKind::Test => "echo",
171 CallKind::Direct => "1:1",
172 CallKind::Group => "group",
173 CallKind::Meeting => "meeting",
174 }
175 }
176
177 fn kind_slug(kind: CallKind) -> &'static str {
178 match kind {
179 CallKind::Test => "echo",
180 CallKind::Direct => "1to1",
181 CallKind::Group => "group",
182 CallKind::Meeting => "meeting",
183 }
184 }
185
186 fn path_name(path: MediaPath) -> &'static str {
187 match path {
188 MediaPath::Pending => "pending",
189 MediaPath::Direct => "direct",
190 MediaPath::Mixer => "mixer",
191 }
192 }
193
194 fn end_text(reason: &EndReason) -> String {
195 match reason {
196 EndReason::LocalHangup => "local hangup".to_owned(),
197 EndReason::Cancelled => "cancelled before the call connected".to_owned(),
198 EndReason::Dropped => "connection dropped".to_owned(),
199 EndReason::Failed(message) => format!("failed: {message}"),
200 EndReason::Remote(EndKind::Declined) => "remote declined".to_owned(),
201 EndReason::Remote(EndKind::NoAnswer) => "no answer".to_owned(),
202 EndReason::Remote(EndKind::Unavailable) => "remote unavailable".to_owned(),
203 EndReason::Remote(kind) => format!("remote ended ({kind:?})"),
204 }
205 }
206
207 impl CallRecorder {
208 pub fn document(&self) -> Document {
209 let report = self.report();
210 Document {
211 stem: format!("{}-{}", self.started_at.format(FILE_STAMP), kind_slug(self.kind)),
212 json: serde_json::to_string_pretty(&report).unwrap_or_else(|error| format!("{{\"error\":\"{error}\"}}")),
213 markdown: markdown::render(&report),
214 }
215 }
216
217 fn scrubber(&self) -> Scrubber {
218 let mut scrubber = Scrubber::new();
219 scrubber.register_self(&self.me.mri, &self.me.display_name, &self.me.email);
220 for (mri, name) in &self.people {
221 scrubber.register_person(mri, name);
222 }
223 scrubber
224 }
225
226 fn report(&self) -> Report {
227 let mut scrubber = self.scrubber();
228 let diagnostics = self.diagnostics.clone().unwrap_or_default();
229 let timeline: Vec<TimelineInfo> = diagnostics
230 .timeline
231 .iter()
232 .map(|entry| TimelineInfo {
233 engine_ms: entry.elapsed_ms,
234 label: scrubber.scrub(&entry.label),
235 detail: scrubber.scrub(&entry.detail),
236 })
237 .collect();
238 let features = self.feature_infos(&mut scrubber, &diagnostics.timeline);
239 let notices = self
240 .notices
241 .iter()
242 .map(|(at_ms, text)| NoticeInfo { at_ms: *at_ms, text: scrubber.scrub(text) })
243 .collect();
244 let total_ms = self.ended.as_ref().map(|(at_ms, _)| *at_ms);
245 let end_reason = self.ended.as_ref().map_or_else(|| "still running when saved".to_owned(), |(_, reason)| scrubber.scrub(&end_text(reason)));
246 let escalations = timeline.iter().filter(|entry| entry.label == ESCALATION_LABEL && entry.detail.contains("new offer sent")).count();
247 let escalation_failures = timeline.iter().filter(|entry| entry.label == "escalation failed").count();
248 let path = self.paths.last().map_or("unknown", |(_, path)| path_name(*path));
249 let stats = self.stats_info();
250 let sdp = diagnostics
251 .sdp
252 .iter()
253 .map(|summary| SdpInfo {
254 engine_ms: summary.at_ms,
255 role: summary.role.clone(),
256 lines: summary
257 .lines
258 .iter()
259 .map(|line| SdpLineInfo {
260 kind: line.kind.clone(),
261 mid: line.mid.clone(),
262 direction: line.direction.clone(),
263 codecs: line.codecs.clone(),
264 payloads: line.payload_count,
265 ssrcs: line.ssrc_count,
266 rejected: line.rejected,
267 })
268 .collect(),
269 })
270 .collect();
271 let mut report = Report {
272 schema: SCHEMA,
273 app: AppInfo {
274 version: env!("CARGO_PKG_VERSION"),
275 build: env!("TEAMS_BUILD_VERSION"),
276 os: std::env::consts::OS,
277 arch: std::env::consts::ARCH,
278 demo: self.demo,
279 },
280 call: CallInfo {
281 kind: kind_label(self.kind),
282 direction: if self.incoming { "incoming" } else { "outgoing" },
283 started_utc: self.started_at.format(READABLE_STAMP).to_string(),
284 connect_ms: self.connected_ms,
285 total_ms,
286 connected_ms: self.connected_ms.zip(total_ms).map(|(connected, total)| total.saturating_sub(connected)),
287 end_reason,
288 engine_ice_connected_ms: diagnostics.ice_connected_ms,
289 engine_peer_connected_ms: diagnostics.peer_connected_ms,
290 },
291 media: MediaInfo {
292 path,
293 path_changes: self.paths.iter().map(|(at_ms, path)| PathChange { at_ms: *at_ms, path: path_name(*path) }).collect(),
294 escalations,
295 escalation_failures,
296 selected_pair: diagnostics.selected_pair.as_deref().map(|pair| scrubber.scrub(pair)),
297 tls_version: diagnostics.tls_version.clone(),
298 dtls_cipher: diagnostics.dtls_cipher.clone(),
299 srtp_cipher: diagnostics.srtp_cipher.clone(),
300 },
301 participants: ParticipantInfo {
302 peak_present: self.peak_participants,
303 known: placeholders(&mut scrubber, &self.people),
304 captions_received: self.captions,
305 },
306 problems: Vec::new(),
307 stats,
308 features,
309 notices,
310 states: self.states.iter().map(|(at_ms, state)| StateInfo { at_ms: *at_ms, state: state.clone() }).collect(),
311 sdp,
312 timeline,
313 };
314 let abnormal = matches!(self.ended, Some((_, EndReason::Failed(_) | EndReason::Dropped)));
315 report.problems = problems(&report, abnormal);
316 report
317 }
318
319 fn stats_info(&self) -> StatsInfo {
320 let series = &self.series;
321 let metrics: BTreeMap<&'static str, Range> = series
322 .values()
323 .iter()
324 .map(|(name, value)| (*name, Range { min: value.min, max: value.max, last: value.last }))
325 .collect();
326 let samples = series.values().get("audio_in_packets").map_or(0, |value| value.samples);
327 let health_names = [calling::NetworkLevel::Good, calling::NetworkLevel::Poor, calling::NetworkLevel::Bad];
328 let limitation_names = [calling::Limitation::None, calling::Limitation::Cpu, calling::Limitation::Bandwidth];
329 StatsInfo {
330 samples,
331 metrics,
332 audio_in_stalled_samples: series.stalled_audio_in,
333 audio_out_stalled_samples: series.stalled_audio_out,
334 health_samples: health_names.iter().map(|level| (level_name(*level), series.level_samples[*level as usize])).collect(),
335 health_level_changes: series.level_changes.iter().map(|(at_ms, level)| PathChange { at_ms: *at_ms, path: level }).collect(),
336 quality_limitation_samples: limitation_names
337 .iter()
338 .map(|limitation| (limitation_name(*limitation), series.limitation_samples[*limitation as usize]))
339 .collect(),
340 cpu_limited_samples: series.cpu_limited_samples,
341 }
342 }
343
344 fn feature_infos(&self, scrubber: &mut Scrubber, timeline: &[calling::timeline::TimelineEntry]) -> Vec<FeatureInfo> {
345 let mut records: Vec<FeatureRecord> = self.features.clone();
346 for entry in timeline {
347 if entry.label == TRANSFER_LABEL
348 && let Some(record) = records.iter_mut().rev().find(|record| record.feature == "transfer" && record.outcome == Outcome::Requested)
349 {
350 record.outcome = Outcome::Confirmed(entry.elapsed_ms);
351 }
352 let Some((_, feature)) = FEATURE_FAILURE_LABELS.iter().find(|(label, _)| entry.label == *label) else {
353 continue;
354 };
355 if let Some(record) = records.iter_mut().rev().find(|record| record.feature == *feature && record.outcome == Outcome::Requested) {
356 record.outcome = Outcome::Failed(entry.detail.clone());
357 }
358 }
359 records
360 .into_iter()
361 .map(|record| {
362 let (result, confirmed_at_ms, error) = match record.outcome {
363 Outcome::Requested => ("no confirmation", None, None),
364 Outcome::Confirmed(at_ms) => ("ok", Some(at_ms), None),
365 Outcome::Failed(message) => ("failed", None, Some(scrubber.scrub(&message))),
366 };
367 FeatureInfo {
368 at_ms: record.at_ms,
369 feature: record.feature,
370 detail: scrubber.scrub(&record.detail),
371 result,
372 confirmed_at_ms,
373 error,
374 }
375 })
376 .collect()
377 }
378 }
379
380 fn placeholders(scrubber: &mut Scrubber, people: &[(String, String)]) -> Vec<String> {
381 let mut known = vec![super::scrub::SELF_PLACEHOLDER.to_owned()];
382 for (mri, _) in people {
383 let placeholder = scrubber.person(mri);
384 if !known.contains(&placeholder) {
385 known.push(placeholder);
386 }
387 }
388 known
389 }
390
391 fn problems(report: &Report, abnormal_end: bool) -> Vec<String> {
392 let mut found = Vec::new();
393 if report.call.connect_ms.is_none() {
394 found.push(format!("Never connected ({}).", report.call.end_reason));
395 } else if abnormal_end {
396 found.push(format!("Ended abnormally: {}.", report.call.end_reason));
397 }
398 let metrics = &report.stats.metrics;
399 let samples = report.stats.samples;
400 if samples > 0 && metrics.get("audio_in_packets").is_some_and(|range| range.max == 0.) {
401 found.push("No inbound audio packets arrived.".to_owned());
402 }
403 if samples > 0 && metrics.get("audio_out_packets").is_some_and(|range| range.max == 0.) {
404 found.push("No outbound audio packets were sent.".to_owned());
405 }
406 if samples >= MIN_SAMPLES_FOR_STALLS && report.stats.audio_in_stalled_samples > 0 {
407 found.push(format!("Inbound audio stalled in {} of {samples} samples.", report.stats.audio_in_stalled_samples));
408 }
409 if samples >= MIN_SAMPLES_FOR_STALLS && report.stats.audio_out_stalled_samples > 0 {
410 found.push(format!("Outbound audio stalled in {} of {samples} samples.", report.stats.audio_out_stalled_samples));
411 }
412 let degraded: u32 = ["poor", "bad"].iter().filter_map(|name| report.stats.health_samples.get(*name)).sum();
413 if degraded > 0 {
414 found.push(format!("Network health was poor or bad in {degraded} samples."));
415 }
416 if report.media.escalation_failures > 0 {
417 found.push(format!("{} escalation(s) failed.", report.media.escalation_failures));
418 }
419 let failures: Vec<&TimelineInfo> =
420 report.timeline.iter().filter(|entry| FAILURE_WORDS.iter().any(|word| entry.label.contains(word))).collect();
421 if !failures.is_empty() {
422 let labels: Vec<&str> = failures.iter().take(5).map(|entry| entry.label.as_str()).collect();
423 found.push(format!("{} failure entries in the timeline: {}.", failures.len(), labels.join(", ")));
424 }
425 for feature in report.features.iter().filter(|feature| feature.result == "failed") {
426 found.push(format!("Feature {} ({}) failed at {} ms.", feature.feature, feature.detail, feature.at_ms));
427 }
428 found
429 }
@@ -0,0 +1,429 @@
1use std::collections::BTreeMap;
2
3use calling::{EndKind, EndReason, MediaPath};
4use serde::Serialize;
5
6use super::markdown;
7use super::scrub::Scrubber;
8use super::series::{level_name, limitation_name};
9use super::{CallRecorder, FeatureRecord, Outcome};
10use crate::call::model::CallKind;
11
12const SCHEMA: u32 = 1;
13const FILE_STAMP: &str = "%Y%m%dT%H%M%SZ";
14const READABLE_STAMP: &str = "%Y-%m-%d %H:%M:%S";
15const MIN_SAMPLES_FOR_STALLS: u32 = 3;
16const ESCALATION_LABEL: &str = "escalation";
17const TRANSFER_LABEL: &str = "transfer";
18const FAILURE_WORDS: [&str; 3] = ["failed", "rejected", "not understood"];
19const FEATURE_FAILURE_LABELS: [(&str, &str); 11] = [
20 ("raise hand failed", "hand"),
21 ("lower hand failed", "hand"),
22 ("lower all hands failed", "hand"),
23 ("hold failed", "hold"),
24 ("transfer failed", "transfer"),
25 ("reaction failed", "reaction"),
26 ("camera offer failed", "camera"),
27 ("recording consent failed", "recording"),
28 ("caption language failed", "captions"),
29 ("caption start failed", "captions"),
30 ("end meeting failed", "people action"),
31];
32
33pub struct Document {
34 pub stem: String,
35 pub json: String,
36 pub markdown: String,
37}
38
39#[derive(Debug, Serialize)]
40pub struct Report {
41 pub schema: u32,
42 pub app: AppInfo,
43 pub call: CallInfo,
44 pub media: MediaInfo,
45 pub participants: ParticipantInfo,
46 pub problems: Vec<String>,
47 pub stats: StatsInfo,
48 pub features: Vec<FeatureInfo>,
49 pub notices: Vec<NoticeInfo>,
50 pub states: Vec<StateInfo>,
51 pub sdp: Vec<SdpInfo>,
52 pub timeline: Vec<TimelineInfo>,
53}
54
55#[derive(Debug, Serialize)]
56pub struct AppInfo {
57 pub version: &'static str,
58 pub build: &'static str,
59 pub os: &'static str,
60 pub arch: &'static str,
61 pub demo: bool,
62}
63
64#[derive(Debug, Serialize)]
65pub struct CallInfo {
66 pub kind: &'static str,
67 pub direction: &'static str,
68 pub started_utc: String,
69 pub connect_ms: Option<u128>,
70 pub total_ms: Option<u128>,
71 pub connected_ms: Option<u128>,
72 pub end_reason: String,
73 pub engine_ice_connected_ms: Option<u128>,
74 pub engine_peer_connected_ms: Option<u128>,
75}
76
77#[derive(Debug, Serialize)]
78pub struct MediaInfo {
79 pub path: &'static str,
80 pub path_changes: Vec<PathChange>,
81 pub escalations: usize,
82 pub escalation_failures: usize,
83 pub selected_pair: Option<String>,
84 pub tls_version: String,
85 pub dtls_cipher: String,
86 pub srtp_cipher: String,
87}
88
89#[derive(Debug, Serialize)]
90pub struct PathChange {
91 pub at_ms: u128,
92 pub path: &'static str,
93}
94
95#[derive(Debug, Serialize)]
96pub struct ParticipantInfo {
97 pub peak_present: usize,
98 pub known: Vec<String>,
99 pub captions_received: u32,
100}
101
102#[derive(Debug, Serialize)]
103pub struct StatsInfo {
104 pub samples: u32,
105 pub metrics: BTreeMap<&'static str, Range>,
106 pub audio_in_stalled_samples: u32,
107 pub audio_out_stalled_samples: u32,
108 pub health_samples: BTreeMap<&'static str, u32>,
109 pub health_level_changes: Vec<PathChange>,
110 pub quality_limitation_samples: BTreeMap<&'static str, u32>,
111 pub cpu_limited_samples: u32,
112}
113
114#[derive(Debug, Serialize)]
115pub struct Range {
116 pub min: f64,
117 pub max: f64,
118 pub last: f64,
119}
120
121#[derive(Debug, Serialize)]
122pub struct FeatureInfo {
123 pub at_ms: u128,
124 pub feature: &'static str,
125 pub detail: String,
126 pub result: &'static str,
127 pub confirmed_at_ms: Option<u128>,
128 pub error: Option<String>,
129}
130
131#[derive(Debug, Serialize)]
132pub struct NoticeInfo {
133 pub at_ms: u128,
134 pub text: String,
135}
136
137#[derive(Debug, Serialize)]
138pub struct StateInfo {
139 pub at_ms: u128,
140 pub state: String,
141}
142
143#[derive(Debug, Serialize)]
144pub struct SdpInfo {
145 pub engine_ms: u128,
146 pub role: String,
147 pub lines: Vec<SdpLineInfo>,
148}
149
150#[derive(Debug, Serialize)]
151pub struct SdpLineInfo {
152 pub kind: String,
153 pub mid: String,
154 pub direction: String,
155 pub codecs: Vec<String>,
156 pub payloads: usize,
157 pub ssrcs: usize,
158 pub rejected: bool,
159}
160
161#[derive(Debug, Serialize)]
162pub struct TimelineInfo {
163 pub engine_ms: u128,
164 pub label: String,
165 pub detail: String,
166}
167
168fn kind_label(kind: CallKind) -> &'static str {
169 match kind {
170 CallKind::Test => "echo",
171 CallKind::Direct => "1:1",
172 CallKind::Group => "group",
173 CallKind::Meeting => "meeting",
174 }
175}
176
177fn kind_slug(kind: CallKind) -> &'static str {
178 match kind {
179 CallKind::Test => "echo",
180 CallKind::Direct => "1to1",
181 CallKind::Group => "group",
182 CallKind::Meeting => "meeting",
183 }
184}
185
186fn path_name(path: MediaPath) -> &'static str {
187 match path {
188 MediaPath::Pending => "pending",
189 MediaPath::Direct => "direct",
190 MediaPath::Mixer => "mixer",
191 }
192}
193
194fn end_text(reason: &EndReason) -> String {
195 match reason {
196 EndReason::LocalHangup => "local hangup".to_owned(),
197 EndReason::Cancelled => "cancelled before the call connected".to_owned(),
198 EndReason::Dropped => "connection dropped".to_owned(),
199 EndReason::Failed(message) => format!("failed: {message}"),
200 EndReason::Remote(EndKind::Declined) => "remote declined".to_owned(),
201 EndReason::Remote(EndKind::NoAnswer) => "no answer".to_owned(),
202 EndReason::Remote(EndKind::Unavailable) => "remote unavailable".to_owned(),
203 EndReason::Remote(kind) => format!("remote ended ({kind:?})"),
204 }
205}
206
207impl CallRecorder {
208 pub fn document(&self) -> Document {
209 let report = self.report();
210 Document {
211 stem: format!("{}-{}", self.started_at.format(FILE_STAMP), kind_slug(self.kind)),
212 json: serde_json::to_string_pretty(&report).unwrap_or_else(|error| format!("{{\"error\":\"{error}\"}}")),
213 markdown: markdown::render(&report),
214 }
215 }
216
217 fn scrubber(&self) -> Scrubber {
218 let mut scrubber = Scrubber::new();
219 scrubber.register_self(&self.me.mri, &self.me.display_name, &self.me.email);
220 for (mri, name) in &self.people {
221 scrubber.register_person(mri, name);
222 }
223 scrubber
224 }
225
226 fn report(&self) -> Report {
227 let mut scrubber = self.scrubber();
228 let diagnostics = self.diagnostics.clone().unwrap_or_default();
229 let timeline: Vec<TimelineInfo> = diagnostics
230 .timeline
231 .iter()
232 .map(|entry| TimelineInfo {
233 engine_ms: entry.elapsed_ms,
234 label: scrubber.scrub(&entry.label),
235 detail: scrubber.scrub(&entry.detail),
236 })
237 .collect();
238 let features = self.feature_infos(&mut scrubber, &diagnostics.timeline);
239 let notices = self
240 .notices
241 .iter()
242 .map(|(at_ms, text)| NoticeInfo { at_ms: *at_ms, text: scrubber.scrub(text) })
243 .collect();
244 let total_ms = self.ended.as_ref().map(|(at_ms, _)| *at_ms);
245 let end_reason = self.ended.as_ref().map_or_else(|| "still running when saved".to_owned(), |(_, reason)| scrubber.scrub(&end_text(reason)));
246 let escalations = timeline.iter().filter(|entry| entry.label == ESCALATION_LABEL && entry.detail.contains("new offer sent")).count();
247 let escalation_failures = timeline.iter().filter(|entry| entry.label == "escalation failed").count();
248 let path = self.paths.last().map_or("unknown", |(_, path)| path_name(*path));
249 let stats = self.stats_info();
250 let sdp = diagnostics
251 .sdp
252 .iter()
253 .map(|summary| SdpInfo {
254 engine_ms: summary.at_ms,
255 role: summary.role.clone(),
256 lines: summary
257 .lines
258 .iter()
259 .map(|line| SdpLineInfo {
260 kind: line.kind.clone(),
261 mid: line.mid.clone(),
262 direction: line.direction.clone(),
263 codecs: line.codecs.clone(),
264 payloads: line.payload_count,
265 ssrcs: line.ssrc_count,
266 rejected: line.rejected,
267 })
268 .collect(),
269 })
270 .collect();
271 let mut report = Report {
272 schema: SCHEMA,
273 app: AppInfo {
274 version: env!("CARGO_PKG_VERSION"),
275 build: env!("TEAMS_BUILD_VERSION"),
276 os: std::env::consts::OS,
277 arch: std::env::consts::ARCH,
278 demo: self.demo,
279 },
280 call: CallInfo {
281 kind: kind_label(self.kind),
282 direction: if self.incoming { "incoming" } else { "outgoing" },
283 started_utc: self.started_at.format(READABLE_STAMP).to_string(),
284 connect_ms: self.connected_ms,
285 total_ms,
286 connected_ms: self.connected_ms.zip(total_ms).map(|(connected, total)| total.saturating_sub(connected)),
287 end_reason,
288 engine_ice_connected_ms: diagnostics.ice_connected_ms,
289 engine_peer_connected_ms: diagnostics.peer_connected_ms,
290 },
291 media: MediaInfo {
292 path,
293 path_changes: self.paths.iter().map(|(at_ms, path)| PathChange { at_ms: *at_ms, path: path_name(*path) }).collect(),
294 escalations,
295 escalation_failures,
296 selected_pair: diagnostics.selected_pair.as_deref().map(|pair| scrubber.scrub(pair)),
297 tls_version: diagnostics.tls_version.clone(),
298 dtls_cipher: diagnostics.dtls_cipher.clone(),
299 srtp_cipher: diagnostics.srtp_cipher.clone(),
300 },
301 participants: ParticipantInfo {
302 peak_present: self.peak_participants,
303 known: placeholders(&mut scrubber, &self.people),
304 captions_received: self.captions,
305 },
306 problems: Vec::new(),
307 stats,
308 features,
309 notices,
310 states: self.states.iter().map(|(at_ms, state)| StateInfo { at_ms: *at_ms, state: state.clone() }).collect(),
311 sdp,
312 timeline,
313 };
314 let abnormal = matches!(self.ended, Some((_, EndReason::Failed(_) | EndReason::Dropped)));
315 report.problems = problems(&report, abnormal);
316 report
317 }
318
319 fn stats_info(&self) -> StatsInfo {
320 let series = &self.series;
321 let metrics: BTreeMap<&'static str, Range> = series
322 .values()
323 .iter()
324 .map(|(name, value)| (*name, Range { min: value.min, max: value.max, last: value.last }))
325 .collect();
326 let samples = series.values().get("audio_in_packets").map_or(0, |value| value.samples);
327 let health_names = [calling::NetworkLevel::Good, calling::NetworkLevel::Poor, calling::NetworkLevel::Bad];
328 let limitation_names = [calling::Limitation::None, calling::Limitation::Cpu, calling::Limitation::Bandwidth];
329 StatsInfo {
330 samples,
331 metrics,
332 audio_in_stalled_samples: series.stalled_audio_in,
333 audio_out_stalled_samples: series.stalled_audio_out,
334 health_samples: health_names.iter().map(|level| (level_name(*level), series.level_samples[*level as usize])).collect(),
335 health_level_changes: series.level_changes.iter().map(|(at_ms, level)| PathChange { at_ms: *at_ms, path: level }).collect(),
336 quality_limitation_samples: limitation_names
337 .iter()
338 .map(|limitation| (limitation_name(*limitation), series.limitation_samples[*limitation as usize]))
339 .collect(),
340 cpu_limited_samples: series.cpu_limited_samples,
341 }
342 }
343
344 fn feature_infos(&self, scrubber: &mut Scrubber, timeline: &[calling::timeline::TimelineEntry]) -> Vec<FeatureInfo> {
345 let mut records: Vec<FeatureRecord> = self.features.clone();
346 for entry in timeline {
347 if entry.label == TRANSFER_LABEL
348 && let Some(record) = records.iter_mut().rev().find(|record| record.feature == "transfer" && record.outcome == Outcome::Requested)
349 {
350 record.outcome = Outcome::Confirmed(entry.elapsed_ms);
351 }
352 let Some((_, feature)) = FEATURE_FAILURE_LABELS.iter().find(|(label, _)| entry.label == *label) else {
353 continue;
354 };
355 if let Some(record) = records.iter_mut().rev().find(|record| record.feature == *feature && record.outcome == Outcome::Requested) {
356 record.outcome = Outcome::Failed(entry.detail.clone());
357 }
358 }
359 records
360 .into_iter()
361 .map(|record| {
362 let (result, confirmed_at_ms, error) = match record.outcome {
363 Outcome::Requested => ("no confirmation", None, None),
364 Outcome::Confirmed(at_ms) => ("ok", Some(at_ms), None),
365 Outcome::Failed(message) => ("failed", None, Some(scrubber.scrub(&message))),
366 };
367 FeatureInfo {
368 at_ms: record.at_ms,
369 feature: record.feature,
370 detail: scrubber.scrub(&record.detail),
371 result,
372 confirmed_at_ms,
373 error,
374 }
375 })
376 .collect()
377 }
378}
379
380fn placeholders(scrubber: &mut Scrubber, people: &[(String, String)]) -> Vec<String> {
381 let mut known = vec![super::scrub::SELF_PLACEHOLDER.to_owned()];
382 for (mri, _) in people {
383 let placeholder = scrubber.person(mri);
384 if !known.contains(&placeholder) {
385 known.push(placeholder);
386 }
387 }
388 known
389}
390
391fn problems(report: &Report, abnormal_end: bool) -> Vec<String> {
392 let mut found = Vec::new();
393 if report.call.connect_ms.is_none() {
394 found.push(format!("Never connected ({}).", report.call.end_reason));
395 } else if abnormal_end {
396 found.push(format!("Ended abnormally: {}.", report.call.end_reason));
397 }
398 let metrics = &report.stats.metrics;
399 let samples = report.stats.samples;
400 if samples > 0 && metrics.get("audio_in_packets").is_some_and(|range| range.max == 0.) {
401 found.push("No inbound audio packets arrived.".to_owned());
402 }
403 if samples > 0 && metrics.get("audio_out_packets").is_some_and(|range| range.max == 0.) {
404 found.push("No outbound audio packets were sent.".to_owned());
405 }
406 if samples >= MIN_SAMPLES_FOR_STALLS && report.stats.audio_in_stalled_samples > 0 {
407 found.push(format!("Inbound audio stalled in {} of {samples} samples.", report.stats.audio_in_stalled_samples));
408 }
409 if samples >= MIN_SAMPLES_FOR_STALLS && report.stats.audio_out_stalled_samples > 0 {
410 found.push(format!("Outbound audio stalled in {} of {samples} samples.", report.stats.audio_out_stalled_samples));
411 }
412 let degraded: u32 = ["poor", "bad"].iter().filter_map(|name| report.stats.health_samples.get(*name)).sum();
413 if degraded > 0 {
414 found.push(format!("Network health was poor or bad in {degraded} samples."));
415 }
416 if report.media.escalation_failures > 0 {
417 found.push(format!("{} escalation(s) failed.", report.media.escalation_failures));
418 }
419 let failures: Vec<&TimelineInfo> =
420 report.timeline.iter().filter(|entry| FAILURE_WORDS.iter().any(|word| entry.label.contains(word))).collect();
421 if !failures.is_empty() {
422 let labels: Vec<&str> = failures.iter().take(5).map(|entry| entry.label.as_str()).collect();
423 found.push(format!("{} failure entries in the timeline: {}.", failures.len(), labels.join(", ")));
424 }
425 for feature in report.features.iter().filter(|feature| feature.result == "failed") {
426 found.push(format!("Feature {} ({}) failed at {} ms.", feature.feature, feature.detail, feature.at_ms));
427 }
428 found
429}
crates/app/src/call/report/markdown.rs added +138 −0
@@ -0,0 +1,138 @@
1 use std::fmt::Write;
2
3 use super::document::{FeatureInfo, Range, Report, SdpInfo};
4
5 const SUMMARY_METRICS: [(&str, &str); 14] = [
6 ("audio_in_packets", "Audio in, packets"),
7 ("audio_out_packets", "Audio out, packets"),
8 ("audio_in_level", "Audio in, level"),
9 ("audio_out_level", "Audio out, level"),
10 ("video_in_packets", "Video in, packets"),
11 ("video_in_frames_decoded", "Video in, frames decoded"),
12 ("video_out_packets", "Video out, packets"),
13 ("video_out_frames_encoded", "Video out, frames encoded"),
14 ("share_in_packets", "Share in, packets"),
15 ("share_out_packets", "Share out, packets"),
16 ("loss_percent", "Loss, %"),
17 ("round_trip_ms", "Round trip, ms"),
18 ("jitter_ms", "Jitter, ms"),
19 ("received_kbps", "Received, kbit/s"),
20 ];
21
22 fn seconds(milliseconds: Option<u128>) -> String {
23 milliseconds.map_or("n/a".to_owned(), |value| format!("{:.1} s", value as f64 / 1000.))
24 }
25
26 fn number(value: f64) -> String {
27 if value.fract() == 0. { format!("{value:.0}") } else { format!("{value:.3}") }
28 }
29
30 fn resolution(report: &Report, width: &str, height: &str) -> String {
31 let side = |name: &str| report.stats.metrics.get(name).map_or(0., |range| range.last);
32 let (width, height) = (side(width), side(height));
33 if width == 0. { "none".to_owned() } else { format!("{width:.0}x{height:.0}") }
34 }
35
36 pub fn render(report: &Report) -> String {
37 let mut text = String::new();
38 let call = &report.call;
39 let _ = writeln!(text, "# Call test report\n");
40 let _ = writeln!(text, "| | |\n|---|---|");
41 let _ = writeln!(text, "| Kind | {} |", call.kind);
42 let _ = writeln!(text, "| Direction | {} |", call.direction);
43 let _ = writeln!(text, "| Started (UTC) | {} |", call.started_utc);
44 let _ = writeln!(text, "| Connect time | {} |", seconds(call.connect_ms));
45 let _ = writeln!(text, "| Connected for | {} |", seconds(call.connected_ms));
46 let _ = writeln!(text, "| Total | {} |", seconds(call.total_ms));
47 let _ = writeln!(text, "| End reason | {} |", call.end_reason);
48 let _ = writeln!(
49 text,
50 "| Media path | {} ({} escalation(s), {} failed) |",
51 report.media.path, report.media.escalations, report.media.escalation_failures
52 );
53 let _ = writeln!(text, "| Participants | {} present at peak, {} known |", report.participants.peak_present, report.participants.known.len());
54 let _ = writeln!(text, "| Video | in {}, out {} |", resolution(report, "video_in_width", "video_in_height"), resolution(report, "video_out_width", "video_out_height"));
55 let _ = writeln!(
56 text,
57 "| App | {} ({}), {} {}{} |",
58 report.app.version,
59 report.app.build,
60 report.app.os,
61 report.app.arch,
62 if report.app.demo { ", demo mode" } else { "" }
63 );
64 write_problems(&mut text, report);
65 write_stats(&mut text, report);
66 write_features(&mut text, &report.features);
67 write_notices(&mut text, report);
68 write_sdp(&mut text, &report.sdp);
69 let _ = writeln!(text, "\nThe JSON file next to this one holds the full timeline ({} entries).", report.timeline.len());
70 text
71 }
72
73 fn write_problems(text: &mut String, report: &Report) {
74 let _ = writeln!(text, "\n## Findings\n");
75 if report.problems.is_empty() {
76 let _ = writeln!(text, "- Nothing suspicious found.");
77 }
78 for problem in &report.problems {
79 let _ = writeln!(text, "- {problem}");
80 }
81 }
82
83 fn write_stats(text: &mut String, report: &Report) {
84 let _ = writeln!(text, "\n## Stats ({} samples, every 2 s)\n", report.stats.samples);
85 let _ = writeln!(text, "| Metric | Min | Max | Last |\n|---|---|---|---|");
86 for (name, label) in SUMMARY_METRICS {
87 if let Some(Range { min, max, last }) = report.stats.metrics.get(name) {
88 let _ = writeln!(text, "| {label} | {} | {} | {} |", number(*min), number(*max), number(*last));
89 }
90 }
91 let health: Vec<String> = report.stats.health_samples.iter().map(|(level, count)| format!("{level} {count}")).collect();
92 let limits: Vec<String> = report.stats.quality_limitation_samples.iter().map(|(limit, count)| format!("{limit} {count}")).collect();
93 let _ = writeln!(text, "\nHealth samples: {}. Quality limitation samples: {}.", health.join(", "), limits.join(", "));
94 }
95
96 fn write_features(text: &mut String, features: &[FeatureInfo]) {
97 let _ = writeln!(text, "\n## Features used\n");
98 if features.is_empty() {
99 let _ = writeln!(text, "None.");
100 return;
101 }
102 let _ = writeln!(text, "| At | Feature | Detail | Result |\n|---|---|---|---|");
103 for feature in features {
104 let result = match &feature.error {
105 Some(error) => format!("failed: {error}"),
106 None => feature.result.to_owned(),
107 };
108 let _ = writeln!(text, "| {} | {} | {} | {} |", seconds(Some(feature.at_ms)), feature.feature, feature.detail, result);
109 }
110 }
111
112 fn write_notices(text: &mut String, report: &Report) {
113 let _ = writeln!(text, "\n## Notices shown\n");
114 if report.notices.is_empty() {
115 let _ = writeln!(text, "None.");
116 }
117 for notice in &report.notices {
118 let _ = writeln!(text, "- {}: {}", seconds(Some(notice.at_ms)), notice.text);
119 }
120 }
121
122 fn write_sdp(text: &mut String, sdp: &[SdpInfo]) {
123 let _ = writeln!(text, "\n## SDP (summary only)\n");
124 if sdp.is_empty() {
125 let _ = writeln!(text, "None recorded.");
126 }
127 for summary in sdp {
128 let lines: Vec<String> = summary
129 .lines
130 .iter()
131 .map(|line| {
132 let state = if line.rejected { "rejected".to_owned() } else { line.direction.clone() };
133 format!("{} mid {} {} [{}]", line.kind, line.mid, state, line.codecs.join(","))
134 })
135 .collect();
136 let _ = writeln!(text, "- {} at {} ms: {}", summary.role, summary.engine_ms, lines.join("; "));
137 }
138 }
@@ -0,0 +1,138 @@
1use std::fmt::Write;
2
3use super::document::{FeatureInfo, Range, Report, SdpInfo};
4
5const SUMMARY_METRICS: [(&str, &str); 14] = [
6 ("audio_in_packets", "Audio in, packets"),
7 ("audio_out_packets", "Audio out, packets"),
8 ("audio_in_level", "Audio in, level"),
9 ("audio_out_level", "Audio out, level"),
10 ("video_in_packets", "Video in, packets"),
11 ("video_in_frames_decoded", "Video in, frames decoded"),
12 ("video_out_packets", "Video out, packets"),
13 ("video_out_frames_encoded", "Video out, frames encoded"),
14 ("share_in_packets", "Share in, packets"),
15 ("share_out_packets", "Share out, packets"),
16 ("loss_percent", "Loss, %"),
17 ("round_trip_ms", "Round trip, ms"),
18 ("jitter_ms", "Jitter, ms"),
19 ("received_kbps", "Received, kbit/s"),
20];
21
22fn seconds(milliseconds: Option<u128>) -> String {
23 milliseconds.map_or("n/a".to_owned(), |value| format!("{:.1} s", value as f64 / 1000.))
24}
25
26fn number(value: f64) -> String {
27 if value.fract() == 0. { format!("{value:.0}") } else { format!("{value:.3}") }
28}
29
30fn resolution(report: &Report, width: &str, height: &str) -> String {
31 let side = |name: &str| report.stats.metrics.get(name).map_or(0., |range| range.last);
32 let (width, height) = (side(width), side(height));
33 if width == 0. { "none".to_owned() } else { format!("{width:.0}x{height:.0}") }
34}
35
36pub fn render(report: &Report) -> String {
37 let mut text = String::new();
38 let call = &report.call;
39 let _ = writeln!(text, "# Call test report\n");
40 let _ = writeln!(text, "| | |\n|---|---|");
41 let _ = writeln!(text, "| Kind | {} |", call.kind);
42 let _ = writeln!(text, "| Direction | {} |", call.direction);
43 let _ = writeln!(text, "| Started (UTC) | {} |", call.started_utc);
44 let _ = writeln!(text, "| Connect time | {} |", seconds(call.connect_ms));
45 let _ = writeln!(text, "| Connected for | {} |", seconds(call.connected_ms));
46 let _ = writeln!(text, "| Total | {} |", seconds(call.total_ms));
47 let _ = writeln!(text, "| End reason | {} |", call.end_reason);
48 let _ = writeln!(
49 text,
50 "| Media path | {} ({} escalation(s), {} failed) |",
51 report.media.path, report.media.escalations, report.media.escalation_failures
52 );
53 let _ = writeln!(text, "| Participants | {} present at peak, {} known |", report.participants.peak_present, report.participants.known.len());
54 let _ = writeln!(text, "| Video | in {}, out {} |", resolution(report, "video_in_width", "video_in_height"), resolution(report, "video_out_width", "video_out_height"));
55 let _ = writeln!(
56 text,
57 "| App | {} ({}), {} {}{} |",
58 report.app.version,
59 report.app.build,
60 report.app.os,
61 report.app.arch,
62 if report.app.demo { ", demo mode" } else { "" }
63 );
64 write_problems(&mut text, report);
65 write_stats(&mut text, report);
66 write_features(&mut text, &report.features);
67 write_notices(&mut text, report);
68 write_sdp(&mut text, &report.sdp);
69 let _ = writeln!(text, "\nThe JSON file next to this one holds the full timeline ({} entries).", report.timeline.len());
70 text
71}
72
73fn write_problems(text: &mut String, report: &Report) {
74 let _ = writeln!(text, "\n## Findings\n");
75 if report.problems.is_empty() {
76 let _ = writeln!(text, "- Nothing suspicious found.");
77 }
78 for problem in &report.problems {
79 let _ = writeln!(text, "- {problem}");
80 }
81}
82
83fn write_stats(text: &mut String, report: &Report) {
84 let _ = writeln!(text, "\n## Stats ({} samples, every 2 s)\n", report.stats.samples);
85 let _ = writeln!(text, "| Metric | Min | Max | Last |\n|---|---|---|---|");
86 for (name, label) in SUMMARY_METRICS {
87 if let Some(Range { min, max, last }) = report.stats.metrics.get(name) {
88 let _ = writeln!(text, "| {label} | {} | {} | {} |", number(*min), number(*max), number(*last));
89 }
90 }
91 let health: Vec<String> = report.stats.health_samples.iter().map(|(level, count)| format!("{level} {count}")).collect();
92 let limits: Vec<String> = report.stats.quality_limitation_samples.iter().map(|(limit, count)| format!("{limit} {count}")).collect();
93 let _ = writeln!(text, "\nHealth samples: {}. Quality limitation samples: {}.", health.join(", "), limits.join(", "));
94}
95
96fn write_features(text: &mut String, features: &[FeatureInfo]) {
97 let _ = writeln!(text, "\n## Features used\n");
98 if features.is_empty() {
99 let _ = writeln!(text, "None.");
100 return;
101 }
102 let _ = writeln!(text, "| At | Feature | Detail | Result |\n|---|---|---|---|");
103 for feature in features {
104 let result = match &feature.error {
105 Some(error) => format!("failed: {error}"),
106 None => feature.result.to_owned(),
107 };
108 let _ = writeln!(text, "| {} | {} | {} | {} |", seconds(Some(feature.at_ms)), feature.feature, feature.detail, result);
109 }
110}
111
112fn write_notices(text: &mut String, report: &Report) {
113 let _ = writeln!(text, "\n## Notices shown\n");
114 if report.notices.is_empty() {
115 let _ = writeln!(text, "None.");
116 }
117 for notice in &report.notices {
118 let _ = writeln!(text, "- {}: {}", seconds(Some(notice.at_ms)), notice.text);
119 }
120}
121
122fn write_sdp(text: &mut String, sdp: &[SdpInfo]) {
123 let _ = writeln!(text, "\n## SDP (summary only)\n");
124 if sdp.is_empty() {
125 let _ = writeln!(text, "None recorded.");
126 }
127 for summary in sdp {
128 let lines: Vec<String> = summary
129 .lines
130 .iter()
131 .map(|line| {
132 let state = if line.rejected { "rejected".to_owned() } else { line.direction.clone() };
133 format!("{} mid {} {} [{}]", line.kind, line.mid, state, line.codecs.join(","))
134 })
135 .collect();
136 let _ = writeln!(text, "- {} at {} ms: {}", summary.role, summary.engine_ms, lines.join("; "));
137 }
138}
crates/app/src/call/report/mod.rs added +409 −0
@@ -0,0 +1,409 @@
1 mod document;
2 mod markdown;
3 mod scrub;
4 mod series;
5 mod storage;
6
7 use std::cell::RefCell;
8 use std::rc::Rc;
9 use std::time::Instant;
10
11 use calling::{CallCommand, CallDiagnostics, CallState, CallUpdate, CaptionState, EndReason, HoldState, MediaPath};
12 use chrono::{DateTime, Utc};
13
14 pub use document::Document;
15 pub use storage::{report_directory, save_report};
16
17 use super::model::CallKind;
18 use series::StatsSeries;
19
20 pub const SETTING_META_KEY: &str = "call_test_report";
21
22 pub type SharedRecorder = Rc<RefCell<CallRecorder>>;
23
24 #[derive(Debug, Clone, PartialEq)]
25 enum Outcome {
26 Requested,
27 Confirmed(u128),
28 Failed(String),
29 }
30
31 #[derive(Debug, Clone)]
32 struct FeatureRecord {
33 at_ms: u128,
34 feature: &'static str,
35 detail: String,
36 outcome: Outcome,
37 }
38
39 #[derive(Debug, Clone)]
40 pub struct OwnIdentity {
41 pub mri: String,
42 pub display_name: String,
43 pub email: String,
44 }
45
46 #[derive(Debug, Clone)]
47 pub struct CallRecorder {
48 started_at: DateTime<Utc>,
49 started: Instant,
50 kind: CallKind,
51 incoming: bool,
52 demo: bool,
53 me: OwnIdentity,
54 people: Vec<(String, String)>,
55 peak_participants: usize,
56 states: Vec<(u128, String)>,
57 connected_ms: Option<u128>,
58 ended: Option<(u128, EndReason)>,
59 features: Vec<FeatureRecord>,
60 notices: Vec<(u128, String)>,
61 captions: u32,
62 series: StatsSeries,
63 paths: Vec<(u128, MediaPath)>,
64 diagnostics: Option<CallDiagnostics>,
65 }
66
67 pub fn load_enabled(store: &store::Store) -> bool {
68 store.meta(SETTING_META_KEY).ok().flatten().as_deref() != Some("0")
69 }
70
71 pub fn shared(recorder: CallRecorder) -> SharedRecorder {
72 Rc::new(RefCell::new(recorder))
73 }
74
75 fn on_off(on: bool) -> &'static str {
76 if on { "on" } else { "off" }
77 }
78
79 impl CallRecorder {
80 pub fn begin(kind: CallKind, incoming: bool, demo: bool, me: OwnIdentity, people: Vec<(String, String)>) -> Self {
81 CallRecorder {
82 started_at: Utc::now(),
83 started: Instant::now(),
84 kind,
85 incoming,
86 demo,
87 me,
88 people,
89 peak_participants: 0,
90 states: Vec::new(),
91 connected_ms: None,
92 ended: None,
93 features: Vec::new(),
94 notices: Vec::new(),
95 captions: 0,
96 series: StatsSeries::default(),
97 paths: Vec::new(),
98 diagnostics: None,
99 }
100 }
101
102 fn elapsed_ms(&self) -> u128 {
103 self.started.elapsed().as_millis()
104 }
105
106 pub fn feature(&mut self, feature: &'static str, detail: impl Into<String>) {
107 let at_ms = self.elapsed_ms();
108 self.features.push(FeatureRecord { at_ms, feature, detail: detail.into(), outcome: Outcome::Requested });
109 }
110
111 pub fn local_feature(&mut self, feature: &'static str, detail: impl Into<String>) {
112 self.feature(feature, detail);
113 self.confirm(feature);
114 }
115
116 pub fn command(&mut self, command: &CallCommand) {
117 if let Some((feature, detail)) = describe(command) {
118 self.feature(feature, detail);
119 }
120 }
121
122 fn settle(&mut self, feature: &str, outcome: Outcome) {
123 if let Some(record) = self
124 .features
125 .iter_mut()
126 .rev()
127 .find(|record| record.feature == feature && record.outcome == Outcome::Requested)
128 {
129 record.outcome = outcome;
130 }
131 }
132
133 fn confirm(&mut self, feature: &str) {
134 let at_ms = self.elapsed_ms();
135 self.settle(feature, Outcome::Confirmed(at_ms));
136 }
137
138 fn remember_person(&mut self, mri: &str, display_name: &str) {
139 if !self.people.iter().any(|(known, _)| known == mri) {
140 self.people.push((mri.to_owned(), display_name.to_owned()));
141 }
142 }
143
144 pub fn observe(&mut self, update: &CallUpdate) {
145 let at_ms = self.elapsed_ms();
146 match update {
147 CallUpdate::State(state) => self.note_state(state, at_ms),
148 CallUpdate::OwnIdentity { mri } => self.me.mri.clone_from(mri),
149 CallUpdate::Muted(_) => self.confirm("mute"),
150 CallUpdate::Camera(_) => self.confirm("camera"),
151 CallUpdate::LocalShare(_) | CallUpdate::ShareSound(_) => self.confirm("share"),
152 CallUpdate::Hold(state) => {
153 self.states.push((at_ms, format!("hold {}", hold_name(*state))));
154 self.confirm("hold");
155 }
156 CallUpdate::Recording(_) => self.confirm("recording"),
157 CallUpdate::OwnHand(_) => self.confirm("hand"),
158 CallUpdate::Reaction { mri, .. } if *mri == self.me.mri => self.confirm("reaction"),
159 CallUpdate::Captions(CaptionState::Failed(message)) => {
160 self.settle("captions", Outcome::Failed(message.clone()));
161 }
162 CallUpdate::Captions(CaptionState::On) => self.confirm("captions"),
163 CallUpdate::Caption(_) => self.captions += 1,
164 CallUpdate::Organizer { outcome: Ok(_), .. } => self.confirm("people action"),
165 CallUpdate::Organizer { outcome: Err(message), .. } => {
166 self.settle("people action", Outcome::Failed(message.clone()));
167 }
168 CallUpdate::Roster(entries) => {
169 for entry in entries {
170 self.remember_person(&entry.mri, &entry.display_name);
171 }
172 let present = entries.iter().filter(|entry| !entry.in_lobby).count();
173 self.peak_participants = self.peak_participants.max(present);
174 }
175 CallUpdate::Notice(text) => self.notices.push((at_ms, text.clone())),
176 CallUpdate::Health(health) => {
177 self.series.observe_health(health, at_ms);
178 if self.paths.last().map(|(_, path)| *path) != Some(health.path) {
179 self.paths.push((at_ms, health.path));
180 }
181 }
182 CallUpdate::Sample(sample) => self.series.observe_sample(sample),
183 CallUpdate::Diagnostics(diagnostics) => self.diagnostics = Some((**diagnostics).clone()),
184 _ => {}
185 }
186 }
187
188 fn note_state(&mut self, state: &CallState, at_ms: u128) {
189 let name = match state {
190 CallState::Idle => "idle",
191 CallState::Connecting => "connecting",
192 CallState::Connected { .. } => "connected",
193 CallState::Reconnecting { .. } => "reconnecting",
194 CallState::Ended { .. } => "ended",
195 };
196 if self.states.last().is_none_or(|(_, last)| last != name) {
197 self.states.push((at_ms, name.to_owned()));
198 }
199 match state {
200 CallState::Connected { .. } if self.connected_ms.is_none() => self.connected_ms = Some(at_ms),
201 CallState::Ended { reason } if self.ended.is_none() => {
202 self.ended = Some((at_ms, reason.clone()));
203 self.confirm("hangup");
204 }
205 _ => {}
206 }
207 }
208 }
209
210 fn hold_name(state: HoldState) -> &'static str {
211 match state {
212 HoldState::Active => "active",
213 HoldState::Local => "local",
214 HoldState::Remote => "remote",
215 }
216 }
217
218 fn describe(command: &CallCommand) -> Option<(&'static str, String)> {
219 use CallCommand::*;
220 Some(match command {
221 Mute(mute) => ("mute", format!("{mute:?}").to_lowercase()),
222 SetCamera(on) => ("camera", on_off(*on).to_owned()),
223 StartShare(source) => ("share", format!("start {}", format!("{:?}", source.kind).to_lowercase())),
224 StopShare => ("share", "stop".to_owned()),
225 SetShareSound(on) => ("share", format!("sound {}", on_off(*on))),
226 SetShareMotion(on) => ("share", format!("motion {}", on_off(*on))),
227 SetShareStandout(on) => ("share", format!("standout {}", on_off(*on))),
228 Hold(on) => ("hold", (if *on { "hold" } else { "resume" }).to_owned()),
229 Transfer { target, replaces } => {
230 let way = if replaces.is_some() { "consulted" } else { "blind" };
231 ("transfer", format!("{way} to {}", target.mri))
232 }
233 Invite { callees, group_thread } => {
234 let group = if group_thread.is_some() { ", into a group chat" } else { "" };
235 ("add people", format!("{} invited{group}", callees.len()))
236 }
237 StartRecording { kind, .. } => ("recording", format!("start {kind:?}")),
238 StopRecording { scope } => ("recording", format!("stop {scope:?}")),
239 ConsentToRecording => ("recording", "consent".to_owned()),
240 SetCaptions(on) => ("captions", on_off(*on).to_owned()),
241 SetCaptionLanguage(tag) => ("captions", format!("language {tag}")),
242 SetHand(on) => ("hand", on_off(*on).to_owned()),
243 LowerHand { mri } => ("hand", format!("lower {mri}")),
244 LowerAllHands => ("hand", "lower all".to_owned()),
245 SendReaction(reaction) => ("reaction", format!("{reaction:?}")),
246 Admit { mri } => ("people action", format!("admit {mri}")),
247 AdmitAll => ("people action", "admit all".to_owned()),
248 Deny { mri } => ("people action", format!("deny {mri}")),
249 MuteParticipant { mri } => ("people action", format!("mute {mri}")),
250 MuteAll => ("people action", "mute all".to_owned()),
251 Spotlight { mri } => ("people action", format!("spotlight {mri}")),
252 StopSpotlight { mri } => ("people action", format!("stop spotlight {mri}")),
253 RemoveParticipant { mri } => ("people action", format!("remove {mri}")),
254 SetLock(on) => ("people action", format!("lock {}", on_off(*on))),
255 SetRole { mri, role } => ("people action", format!("role {role:?} for {mri}")),
256 SetAttendeeModality { mri, modality, allowed } => {
257 ("people action", format!("{modality:?} {} for {mri}", if *allowed { "allowed" } else { "blocked" }))
258 }
259 SetAttendeeRestrictions { mic_off, camera_off } => {
260 ("people action", format!("attendee restrictions mic_off={mic_off} camera_off={camera_off}"))
261 }
262 EndMeeting => ("people action", "end meeting for all".to_owned()),
263 OpenWhiteboard { .. } => ("whiteboard", "open".to_owned()),
264 Hangup => ("hangup", "local".to_owned()),
265 _ => return None,
266 })
267 }
268
269 #[cfg(test)]
270 mod tests {
271 use calling::call::VideoReport;
272 use calling::timeline::TimelineEntry;
273 use calling::{
274 Callee, HealthSample, MuteCommand, NetworkLevel, RosterEntry, SdpLine, SdpSummary, StatsSample, TransportDetails,
275 };
276
277 use super::*;
278
279 const PEER_MRI: &str = "8:orgid:aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee";
280
281 fn recorder() -> CallRecorder {
282 let me = OwnIdentity {
283 mri: "8:orgid:11111111-2222-3333-4444-555555555555".to_owned(),
284 display_name: "Daniel Daeschle".to_owned(),
285 email: "daniel@example.com".to_owned(),
286 };
287 CallRecorder::begin(CallKind::Direct, false, true, me, vec![(PEER_MRI.to_owned(), "Mara Lindqvist".to_owned())])
288 }
289
290 fn sample(packets: u64) -> CallUpdate {
291 CallUpdate::Sample(StatsSample {
292 audio_in_packets: packets,
293 audio_out_packets: packets,
294 video: VideoReport { inbound_width: 1280, inbound_height: 720, ..VideoReport::default() },
295 ..StatsSample::default()
296 })
297 }
298
299 fn diagnostics() -> CallUpdate {
300 let entry = |elapsed_ms, label: &str, detail: &str| TimelineEntry {
301 elapsed_ms,
302 label: label.to_owned(),
303 detail: detail.to_owned(),
304 };
305 CallUpdate::Diagnostics(Box::new(CallDiagnostics {
306 timeline: vec![
307 entry(10, "roster", "Mara Lindqvist 8:orgid:aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee from 203.0.113.9"),
308 entry(20, "raise hand failed", "HTTP 500 for https://emea.msg.teams.microsoft.com/v1/users/ME/conversations/19%3Aabc%40thread.v2?token=secret"),
309 entry(30, "escalation", "new peer connection, new offer sent"),
310 ],
311 sdp: vec![SdpSummary {
312 at_ms: 5,
313 role: "local offer".to_owned(),
314 lines: vec![SdpLine {
315 kind: "audio".to_owned(),
316 mid: "0".to_owned(),
317 direction: "sendrecv".to_owned(),
318 codecs: vec!["opus".to_owned()],
319 payload_count: 1,
320 ssrc_count: 1,
321 rejected: false,
322 }],
323 }],
324 ..CallDiagnostics::default()
325 }))
326 }
327
328 fn finished_call() -> CallRecorder {
329 let mut recorder = recorder();
330 recorder.observe(&CallUpdate::State(CallState::Connecting));
331 recorder.observe(&CallUpdate::State(CallState::Connected { since: Instant::now() }));
332 recorder.observe(&CallUpdate::Roster(vec![RosterEntry {
333 mri: PEER_MRI.to_owned(),
334 display_name: "Mara Lindqvist".to_owned(),
335 ..RosterEntry::default()
336 }]));
337 for packets in [100, 200, 200, 300] {
338 recorder.observe(&sample(packets));
339 }
340 recorder.observe(&CallUpdate::Health(calling::CallHealth {
341 level: NetworkLevel::Poor,
342 cpu_limited: false,
343 sample: HealthSample { loss_percent: 6., ..HealthSample::default() },
344 transport: TransportDetails::default(),
345 path: MediaPath::Direct,
346 }));
347 recorder.observe(&CallUpdate::Notice("Mara Lindqvist declined the transfer".to_owned()));
348 recorder.command(&CallCommand::Mute(MuteCommand::Toggle));
349 recorder.observe(&CallUpdate::Muted(true));
350 recorder.command(&CallCommand::SetHand(true));
351 recorder.command(&CallCommand::Transfer {
352 target: Callee { mri: PEER_MRI.to_owned(), display_name: "Mara Lindqvist".to_owned() },
353 replaces: None,
354 });
355 recorder.command(&CallCommand::Hangup);
356 recorder.observe(&CallUpdate::State(CallState::Ended { reason: EndReason::LocalHangup }));
357 recorder.observe(&diagnostics());
358 recorder
359 }
360
361 #[test]
362 fn the_report_names_the_call_its_features_and_findings() {
363 let document = finished_call().document();
364 let json: serde_json::Value = serde_json::from_str(&document.json).expect("valid json");
365 assert_eq!(json["call"]["kind"], "1:1");
366 assert_eq!(json["call"]["direction"], "outgoing");
367 assert_eq!(json["call"]["end_reason"], "local hangup");
368 assert_eq!(json["media"]["path"], "direct");
369 assert_eq!(json["media"]["escalations"], 1);
370 assert_eq!(json["stats"]["samples"], 4);
371 assert_eq!(json["stats"]["audio_in_stalled_samples"], 1);
372 let results: Vec<(&str, &str)> = json["features"]
373 .as_array()
374 .unwrap()
375 .iter()
376 .map(|feature| (feature["feature"].as_str().unwrap(), feature["result"].as_str().unwrap()))
377 .collect();
378 assert_eq!(results, [("mute", "ok"), ("hand", "failed"), ("transfer", "no confirmation"), ("hangup", "ok")]);
379 assert_eq!(json["timeline"].as_array().unwrap().len(), 3);
380 assert_eq!(json["sdp"][0]["lines"][0]["codecs"][0], "opus");
381 assert!(document.markdown.starts_with("# Call test report"));
382 assert!(document.markdown.contains("## Findings"));
383 assert!(document.markdown.contains("Inbound audio stalled in 1 of 4 samples."));
384 assert!(document.stem.ends_with("-1to1"));
385 }
386
387 #[test]
388 fn neither_file_holds_anything_personal() {
389 let document = finished_call().document();
390 for text in [&document.json, &document.markdown] {
391 for leaked in [
392 "Mara", "Lindqvist", "Daniel", "Daeschle", "aaaaaaaa", "11111111", "example.com", "203.0.113.9", "token=secret", "abc%40thread",
393 ] {
394 assert!(!text.contains(leaked), "{leaked} leaked into: {text}");
395 }
396 assert!(text.contains("person-1"));
397 }
398 }
399
400 #[test]
401 fn a_call_that_never_ended_still_gives_a_report() {
402 let mut recorder = recorder();
403 recorder.observe(&CallUpdate::State(CallState::Connecting));
404 let document = recorder.document();
405 let json: serde_json::Value = serde_json::from_str(&document.json).unwrap();
406 assert_eq!(json["call"]["end_reason"], "still running when saved");
407 assert!(document.markdown.contains("Never connected"));
408 }
409 }
@@ -0,0 +1,409 @@
1mod document;
2mod markdown;
3mod scrub;
4mod series;
5mod storage;
6
7use std::cell::RefCell;
8use std::rc::Rc;
9use std::time::Instant;
10
11use calling::{CallCommand, CallDiagnostics, CallState, CallUpdate, CaptionState, EndReason, HoldState, MediaPath};
12use chrono::{DateTime, Utc};
13
14pub use document::Document;
15pub use storage::{report_directory, save_report};
16
17use super::model::CallKind;
18use series::StatsSeries;
19
20pub const SETTING_META_KEY: &str = "call_test_report";
21
22pub type SharedRecorder = Rc<RefCell<CallRecorder>>;
23
24#[derive(Debug, Clone, PartialEq)]
25enum Outcome {
26 Requested,
27 Confirmed(u128),
28 Failed(String),
29}
30
31#[derive(Debug, Clone)]
32struct FeatureRecord {
33 at_ms: u128,
34 feature: &'static str,
35 detail: String,
36 outcome: Outcome,
37}
38
39#[derive(Debug, Clone)]
40pub struct OwnIdentity {
41 pub mri: String,
42 pub display_name: String,
43 pub email: String,
44}
45
46#[derive(Debug, Clone)]
47pub struct CallRecorder {
48 started_at: DateTime<Utc>,
49 started: Instant,
50 kind: CallKind,
51 incoming: bool,
52 demo: bool,
53 me: OwnIdentity,
54 people: Vec<(String, String)>,
55 peak_participants: usize,
56 states: Vec<(u128, String)>,
57 connected_ms: Option<u128>,
58 ended: Option<(u128, EndReason)>,
59 features: Vec<FeatureRecord>,
60 notices: Vec<(u128, String)>,
61 captions: u32,
62 series: StatsSeries,
63 paths: Vec<(u128, MediaPath)>,
64 diagnostics: Option<CallDiagnostics>,
65}
66
67pub fn load_enabled(store: &store::Store) -> bool {
68 store.meta(SETTING_META_KEY).ok().flatten().as_deref() != Some("0")
69}
70
71pub fn shared(recorder: CallRecorder) -> SharedRecorder {
72 Rc::new(RefCell::new(recorder))
73}
74
75fn on_off(on: bool) -> &'static str {
76 if on { "on" } else { "off" }
77}
78
79impl CallRecorder {
80 pub fn begin(kind: CallKind, incoming: bool, demo: bool, me: OwnIdentity, people: Vec<(String, String)>) -> Self {
81 CallRecorder {
82 started_at: Utc::now(),
83 started: Instant::now(),
84 kind,
85 incoming,
86 demo,
87 me,
88 people,
89 peak_participants: 0,
90 states: Vec::new(),
91 connected_ms: None,
92 ended: None,
93 features: Vec::new(),
94 notices: Vec::new(),
95 captions: 0,
96 series: StatsSeries::default(),
97 paths: Vec::new(),
98 diagnostics: None,
99 }
100 }
101
102 fn elapsed_ms(&self) -> u128 {
103 self.started.elapsed().as_millis()
104 }
105
106 pub fn feature(&mut self, feature: &'static str, detail: impl Into<String>) {
107 let at_ms = self.elapsed_ms();
108 self.features.push(FeatureRecord { at_ms, feature, detail: detail.into(), outcome: Outcome::Requested });
109 }
110
111 pub fn local_feature(&mut self, feature: &'static str, detail: impl Into<String>) {
112 self.feature(feature, detail);
113 self.confirm(feature);
114 }
115
116 pub fn command(&mut self, command: &CallCommand) {
117 if let Some((feature, detail)) = describe(command) {
118 self.feature(feature, detail);
119 }
120 }
121
122 fn settle(&mut self, feature: &str, outcome: Outcome) {
123 if let Some(record) = self
124 .features
125 .iter_mut()
126 .rev()
127 .find(|record| record.feature == feature && record.outcome == Outcome::Requested)
128 {
129 record.outcome = outcome;
130 }
131 }
132
133 fn confirm(&mut self, feature: &str) {
134 let at_ms = self.elapsed_ms();
135 self.settle(feature, Outcome::Confirmed(at_ms));
136 }
137
138 fn remember_person(&mut self, mri: &str, display_name: &str) {
139 if !self.people.iter().any(|(known, _)| known == mri) {
140 self.people.push((mri.to_owned(), display_name.to_owned()));
141 }
142 }
143
144 pub fn observe(&mut self, update: &CallUpdate) {
145 let at_ms = self.elapsed_ms();
146 match update {
147 CallUpdate::State(state) => self.note_state(state, at_ms),
148 CallUpdate::OwnIdentity { mri } => self.me.mri.clone_from(mri),
149 CallUpdate::Muted(_) => self.confirm("mute"),
150 CallUpdate::Camera(_) => self.confirm("camera"),
151 CallUpdate::LocalShare(_) | CallUpdate::ShareSound(_) => self.confirm("share"),
152 CallUpdate::Hold(state) => {
153 self.states.push((at_ms, format!("hold {}", hold_name(*state))));
154 self.confirm("hold");
155 }
156 CallUpdate::Recording(_) => self.confirm("recording"),
157 CallUpdate::OwnHand(_) => self.confirm("hand"),
158 CallUpdate::Reaction { mri, .. } if *mri == self.me.mri => self.confirm("reaction"),
159 CallUpdate::Captions(CaptionState::Failed(message)) => {
160 self.settle("captions", Outcome::Failed(message.clone()));
161 }
162 CallUpdate::Captions(CaptionState::On) => self.confirm("captions"),
163 CallUpdate::Caption(_) => self.captions += 1,
164 CallUpdate::Organizer { outcome: Ok(_), .. } => self.confirm("people action"),
165 CallUpdate::Organizer { outcome: Err(message), .. } => {
166 self.settle("people action", Outcome::Failed(message.clone()));
167 }
168 CallUpdate::Roster(entries) => {
169 for entry in entries {
170 self.remember_person(&entry.mri, &entry.display_name);
171 }
172 let present = entries.iter().filter(|entry| !entry.in_lobby).count();
173 self.peak_participants = self.peak_participants.max(present);
174 }
175 CallUpdate::Notice(text) => self.notices.push((at_ms, text.clone())),
176 CallUpdate::Health(health) => {
177 self.series.observe_health(health, at_ms);
178 if self.paths.last().map(|(_, path)| *path) != Some(health.path) {
179 self.paths.push((at_ms, health.path));
180 }
181 }
182 CallUpdate::Sample(sample) => self.series.observe_sample(sample),
183 CallUpdate::Diagnostics(diagnostics) => self.diagnostics = Some((**diagnostics).clone()),
184 _ => {}
185 }
186 }
187
188 fn note_state(&mut self, state: &CallState, at_ms: u128) {
189 let name = match state {
190 CallState::Idle => "idle",
191 CallState::Connecting => "connecting",
192 CallState::Connected { .. } => "connected",
193 CallState::Reconnecting { .. } => "reconnecting",
194 CallState::Ended { .. } => "ended",
195 };
196 if self.states.last().is_none_or(|(_, last)| last != name) {
197 self.states.push((at_ms, name.to_owned()));
198 }
199 match state {
200 CallState::Connected { .. } if self.connected_ms.is_none() => self.connected_ms = Some(at_ms),
201 CallState::Ended { reason } if self.ended.is_none() => {
202 self.ended = Some((at_ms, reason.clone()));
203 self.confirm("hangup");
204 }
205 _ => {}
206 }
207 }
208}
209
210fn hold_name(state: HoldState) -> &'static str {
211 match state {
212 HoldState::Active => "active",
213 HoldState::Local => "local",
214 HoldState::Remote => "remote",
215 }
216}
217
218fn describe(command: &CallCommand) -> Option<(&'static str, String)> {
219 use CallCommand::*;
220 Some(match command {
221 Mute(mute) => ("mute", format!("{mute:?}").to_lowercase()),
222 SetCamera(on) => ("camera", on_off(*on).to_owned()),
223 StartShare(source) => ("share", format!("start {}", format!("{:?}", source.kind).to_lowercase())),
224 StopShare => ("share", "stop".to_owned()),
225 SetShareSound(on) => ("share", format!("sound {}", on_off(*on))),
226 SetShareMotion(on) => ("share", format!("motion {}", on_off(*on))),
227 SetShareStandout(on) => ("share", format!("standout {}", on_off(*on))),
228 Hold(on) => ("hold", (if *on { "hold" } else { "resume" }).to_owned()),
229 Transfer { target, replaces } => {
230 let way = if replaces.is_some() { "consulted" } else { "blind" };
231 ("transfer", format!("{way} to {}", target.mri))
232 }
233 Invite { callees, group_thread } => {
234 let group = if group_thread.is_some() { ", into a group chat" } else { "" };
235 ("add people", format!("{} invited{group}", callees.len()))
236 }
237 StartRecording { kind, .. } => ("recording", format!("start {kind:?}")),
238 StopRecording { scope } => ("recording", format!("stop {scope:?}")),
239 ConsentToRecording => ("recording", "consent".to_owned()),
240 SetCaptions(on) => ("captions", on_off(*on).to_owned()),
241 SetCaptionLanguage(tag) => ("captions", format!("language {tag}")),
242 SetHand(on) => ("hand", on_off(*on).to_owned()),
243 LowerHand { mri } => ("hand", format!("lower {mri}")),
244 LowerAllHands => ("hand", "lower all".to_owned()),
245 SendReaction(reaction) => ("reaction", format!("{reaction:?}")),
246 Admit { mri } => ("people action", format!("admit {mri}")),
247 AdmitAll => ("people action", "admit all".to_owned()),
248 Deny { mri } => ("people action", format!("deny {mri}")),
249 MuteParticipant { mri } => ("people action", format!("mute {mri}")),
250 MuteAll => ("people action", "mute all".to_owned()),
251 Spotlight { mri } => ("people action", format!("spotlight {mri}")),
252 StopSpotlight { mri } => ("people action", format!("stop spotlight {mri}")),
253 RemoveParticipant { mri } => ("people action", format!("remove {mri}")),
254 SetLock(on) => ("people action", format!("lock {}", on_off(*on))),
255 SetRole { mri, role } => ("people action", format!("role {role:?} for {mri}")),
256 SetAttendeeModality { mri, modality, allowed } => {
257 ("people action", format!("{modality:?} {} for {mri}", if *allowed { "allowed" } else { "blocked" }))
258 }
259 SetAttendeeRestrictions { mic_off, camera_off } => {
260 ("people action", format!("attendee restrictions mic_off={mic_off} camera_off={camera_off}"))
261 }
262 EndMeeting => ("people action", "end meeting for all".to_owned()),
263 OpenWhiteboard { .. } => ("whiteboard", "open".to_owned()),
264 Hangup => ("hangup", "local".to_owned()),
265 _ => return None,
266 })
267}
268
269#[cfg(test)]
270mod tests {
271 use calling::call::VideoReport;
272 use calling::timeline::TimelineEntry;
273 use calling::{
274 Callee, HealthSample, MuteCommand, NetworkLevel, RosterEntry, SdpLine, SdpSummary, StatsSample, TransportDetails,
275 };
276
277 use super::*;
278
279 const PEER_MRI: &str = "8:orgid:aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee";
280
281 fn recorder() -> CallRecorder {
282 let me = OwnIdentity {
283 mri: "8:orgid:11111111-2222-3333-4444-555555555555".to_owned(),
284 display_name: "Daniel Daeschle".to_owned(),
285 email: "daniel@example.com".to_owned(),
286 };
287 CallRecorder::begin(CallKind::Direct, false, true, me, vec![(PEER_MRI.to_owned(), "Mara Lindqvist".to_owned())])
288 }
289
290 fn sample(packets: u64) -> CallUpdate {
291 CallUpdate::Sample(StatsSample {
292 audio_in_packets: packets,
293 audio_out_packets: packets,
294 video: VideoReport { inbound_width: 1280, inbound_height: 720, ..VideoReport::default() },
295 ..StatsSample::default()
296 })
297 }
298
299 fn diagnostics() -> CallUpdate {
300 let entry = |elapsed_ms, label: &str, detail: &str| TimelineEntry {
301 elapsed_ms,
302 label: label.to_owned(),
303 detail: detail.to_owned(),
304 };
305 CallUpdate::Diagnostics(Box::new(CallDiagnostics {
306 timeline: vec![
307 entry(10, "roster", "Mara Lindqvist 8:orgid:aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee from 203.0.113.9"),
308 entry(20, "raise hand failed", "HTTP 500 for https://emea.msg.teams.microsoft.com/v1/users/ME/conversations/19%3Aabc%40thread.v2?token=secret"),
309 entry(30, "escalation", "new peer connection, new offer sent"),
310 ],
311 sdp: vec![SdpSummary {
312 at_ms: 5,
313 role: "local offer".to_owned(),
314 lines: vec![SdpLine {
315 kind: "audio".to_owned(),
316 mid: "0".to_owned(),
317 direction: "sendrecv".to_owned(),
318 codecs: vec!["opus".to_owned()],
319 payload_count: 1,
320 ssrc_count: 1,
321 rejected: false,
322 }],
323 }],
324 ..CallDiagnostics::default()
325 }))
326 }
327
328 fn finished_call() -> CallRecorder {
329 let mut recorder = recorder();
330 recorder.observe(&CallUpdate::State(CallState::Connecting));
331 recorder.observe(&CallUpdate::State(CallState::Connected { since: Instant::now() }));
332 recorder.observe(&CallUpdate::Roster(vec![RosterEntry {
333 mri: PEER_MRI.to_owned(),
334 display_name: "Mara Lindqvist".to_owned(),
335 ..RosterEntry::default()
336 }]));
337 for packets in [100, 200, 200, 300] {
338 recorder.observe(&sample(packets));
339 }
340 recorder.observe(&CallUpdate::Health(calling::CallHealth {
341 level: NetworkLevel::Poor,
342 cpu_limited: false,
343 sample: HealthSample { loss_percent: 6., ..HealthSample::default() },
344 transport: TransportDetails::default(),
345 path: MediaPath::Direct,
346 }));
347 recorder.observe(&CallUpdate::Notice("Mara Lindqvist declined the transfer".to_owned()));
348 recorder.command(&CallCommand::Mute(MuteCommand::Toggle));
349 recorder.observe(&CallUpdate::Muted(true));
350 recorder.command(&CallCommand::SetHand(true));
351 recorder.command(&CallCommand::Transfer {
352 target: Callee { mri: PEER_MRI.to_owned(), display_name: "Mara Lindqvist".to_owned() },
353 replaces: None,
354 });
355 recorder.command(&CallCommand::Hangup);
356 recorder.observe(&CallUpdate::State(CallState::Ended { reason: EndReason::LocalHangup }));
357 recorder.observe(&diagnostics());
358 recorder
359 }
360
361 #[test]
362 fn the_report_names_the_call_its_features_and_findings() {
363 let document = finished_call().document();
364 let json: serde_json::Value = serde_json::from_str(&document.json).expect("valid json");
365 assert_eq!(json["call"]["kind"], "1:1");
366 assert_eq!(json["call"]["direction"], "outgoing");
367 assert_eq!(json["call"]["end_reason"], "local hangup");
368 assert_eq!(json["media"]["path"], "direct");
369 assert_eq!(json["media"]["escalations"], 1);
370 assert_eq!(json["stats"]["samples"], 4);
371 assert_eq!(json["stats"]["audio_in_stalled_samples"], 1);
372 let results: Vec<(&str, &str)> = json["features"]
373 .as_array()
374 .unwrap()
375 .iter()
376 .map(|feature| (feature["feature"].as_str().unwrap(), feature["result"].as_str().unwrap()))
377 .collect();
378 assert_eq!(results, [("mute", "ok"), ("hand", "failed"), ("transfer", "no confirmation"), ("hangup", "ok")]);
379 assert_eq!(json["timeline"].as_array().unwrap().len(), 3);
380 assert_eq!(json["sdp"][0]["lines"][0]["codecs"][0], "opus");
381 assert!(document.markdown.starts_with("# Call test report"));
382 assert!(document.markdown.contains("## Findings"));
383 assert!(document.markdown.contains("Inbound audio stalled in 1 of 4 samples."));
384 assert!(document.stem.ends_with("-1to1"));
385 }
386
387 #[test]
388 fn neither_file_holds_anything_personal() {
389 let document = finished_call().document();
390 for text in [&document.json, &document.markdown] {
391 for leaked in [
392 "Mara", "Lindqvist", "Daniel", "Daeschle", "aaaaaaaa", "11111111", "example.com", "203.0.113.9", "token=secret", "abc%40thread",
393 ] {
394 assert!(!text.contains(leaked), "{leaked} leaked into: {text}");
395 }
396 assert!(text.contains("person-1"));
397 }
398 }
399
400 #[test]
401 fn a_call_that_never_ended_still_gives_a_report() {
402 let mut recorder = recorder();
403 recorder.observe(&CallUpdate::State(CallState::Connecting));
404 let document = recorder.document();
405 let json: serde_json::Value = serde_json::from_str(&document.json).unwrap();
406 assert_eq!(json["call"]["end_reason"], "still running when saved");
407 assert!(document.markdown.contains("Never connected"));
408 }
409}
crates/app/src/call/report/scrub.rs added +287 −0
@@ -0,0 +1,287 @@
1 use std::collections::HashMap;
2 use std::sync::LazyLock;
3
4 use regex::{Captures, Regex, escape};
5
6 pub const SELF_PLACEHOLDER: &str = "self";
7 pub const ECHO_PLACEHOLDER: &str = "echo-bot";
8 const ORGID_PREFIX: &str = "8:orgid:";
9 const MIN_NAME_PART: usize = 3;
10 const ID_SEGMENT_MIN: usize = 8;
11 const REMOVED: &str = "[removed]";
12
13 fn compiled(pattern: &str) -> Regex {
14 Regex::new(pattern).expect("scrub pattern compiles")
15 }
16
17 static URL: LazyLock<Regex> = LazyLock::new(|| compiled(r#"(?i)\b[a-z][a-z0-9+.-]*://[^\s"'<>)\]]+"#));
18 static JWT: LazyLock<Regex> = LazyLock::new(|| compiled(r"\beyJ[\w-]+\.[\w-]+\.[\w-]*"));
19 static COOKIE: LazyLock<Regex> = LazyLock::new(|| compiled(r"(?i)\b(set-cookie|cookie)\s*[:=][^\n]*"));
20 static BEARER: LazyLock<Regex> = LazyLock::new(|| compiled(r"(?i)\b(bearer|basic)\s+[\w\-.~+/=]+"));
21 static CREDENTIAL: LazyLock<Regex> = LazyLock::new(|| {
22 compiled(
23 r"(?i)\b(access_token|refresh_token|id_token|skypetoken|authtoken|token|authorization|password|passwd|secret|signature|sig)\b\s*[:=]\s*[^\s&;,]+",
24 )
25 });
26 static ICE_CREDENTIAL: LazyLock<Regex> =
27 LazyLock::new(|| compiled(r"(?i)\b(ice-ufrag|ice-pwd|ufrag|pwd)\b[:=\s]+\S+"));
28 static FINGERPRINT: LazyLock<Regex> = LazyLock::new(|| compiled(r"(?i)\b(?:[0-9a-f]{2}:){15,}[0-9a-f]{2}\b"));
29 static THREAD: LazyLock<Regex> = LazyLock::new(|| compiled(r#"\b19:[^\s,;"'<>()]+@[A-Za-z0-9.\-]+"#));
30 static ENCODED_THREAD: LazyLock<Regex> = LazyLock::new(|| compiled(r"(?i)\b19%3a\S+?%40[A-Za-z0-9.\-]+"));
31 static MRI: LazyLock<Regex> = LazyLock::new(|| {
32 compiled(r#"\b(?:8:(?:orgid|live|acs|teamsvisitor|spo|gid):[A-Za-z0-9_.+\-=]+|28:[A-Za-z0-9_.\-]{8,}|4:\+?\d{5,})"#)
33 });
34 static EMAIL: LazyLock<Regex> = LazyLock::new(|| compiled(r"[A-Za-z0-9._%+'\-]+@[A-Za-z0-9\-]+(?:\.[A-Za-z0-9\-]+)+"));
35 static UUID: LazyLock<Regex> = LazyLock::new(|| {
36 compiled(r"(?i)\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b")
37 });
38 static IPV4: LazyLock<Regex> = LazyLock::new(|| compiled(r"\b(?:\d{1,3}\.){3}\d{1,3}\b"));
39 static IPV6: LazyLock<Regex> = LazyLock::new(|| {
40 compiled(
41 r"(?i)\b(?:[0-9a-f]{1,4}:){7}[0-9a-f]{1,4}\b|(?:\b[0-9a-f]{1,4}:){1,7}:(?:[0-9a-f]{1,4}(?::[0-9a-f]{1,4}){0,6})?|::(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4}\b",
42 )
43 });
44 static PHONE: LazyLock<Regex> = LazyLock::new(|| compiled(r"\+\d[\d ()\-/]{6,}\d"));
45 static OPAQUE: LazyLock<Regex> = LazyLock::new(|| compiled(r"[A-Za-z0-9+/_\-]{40,}={0,2}"));
46
47 #[derive(Debug, Clone, Default)]
48 pub struct Scrubber {
49 people: HashMap<String, String>,
50 names: Vec<(String, String)>,
51 meetings: HashMap<String, String>,
52 identifiers: HashMap<String, String>,
53 person_count: usize,
54 }
55
56 impl Scrubber {
57 pub fn new() -> Self {
58 Scrubber::default()
59 }
60
61 pub fn register_self(&mut self, mri: &str, display_name: &str, email: &str) {
62 for key in [mri, email].into_iter().filter(|key| !key.trim().is_empty()) {
63 self.alias(key, SELF_PLACEHOLDER);
64 }
65 self.add_name(display_name, SELF_PLACEHOLDER);
66 }
67
68 pub fn register_person(&mut self, mri: &str, display_name: &str) {
69 let placeholder = if mri == calling::signaling::ECHO_BOT_MRI {
70 self.alias(mri, ECHO_PLACEHOLDER);
71 if !display_name.trim().is_empty() {
72 self.names.push((display_name.to_owned(), ECHO_PLACEHOLDER.to_owned()));
73 }
74 return;
75 } else if mri.is_empty() {
76 self.person(display_name)
77 } else {
78 self.person(mri)
79 };
80 self.add_name(display_name, &placeholder);
81 }
82
83 pub fn person(&mut self, key: &str) -> String {
84 let normalized = normalize(key);
85 if let Some(found) = self.people.get(&normalized) {
86 return found.clone();
87 }
88 self.person_count += 1;
89 let placeholder = format!("person-{}", self.person_count);
90 self.alias(key, &placeholder);
91 placeholder
92 }
93
94 fn alias(&mut self, key: &str, placeholder: &str) {
95 let normalized = normalize(key);
96 if let Some(user_id) = normalized.strip_prefix(ORGID_PREFIX) {
97 self.people.insert(user_id.to_owned(), placeholder.to_owned());
98 }
99 self.people.insert(normalized, placeholder.to_owned());
100 }
101
102 fn add_name(&mut self, name: &str, placeholder: &str) {
103 if name.trim().is_empty() {
104 return;
105 }
106 let mut candidates = vec![name.to_owned()];
107 candidates.extend(
108 name.split(|character: char| !character.is_alphanumeric())
109 .filter(|part| part.chars().count() >= MIN_NAME_PART)
110 .map(str::to_owned),
111 );
112 for candidate in candidates {
113 if !self.names.iter().any(|(known, _)| known.eq_ignore_ascii_case(&candidate)) {
114 self.names.push((candidate, placeholder.to_owned()));
115 }
116 }
117 }
118
119 pub fn scrub(&mut self, text: &str) -> String {
120 let mut text = URL.replace_all(text, |captures: &Captures| scrub_url(&captures[0])).into_owned();
121 text = JWT.replace_all(&text, REMOVED).into_owned();
122 text = COOKIE.replace_all(&text, "$1: [removed]").into_owned();
123 text = BEARER.replace_all(&text, "$1 [removed]").into_owned();
124 text = CREDENTIAL.replace_all(&text, "$1 [removed]").into_owned();
125 text = ICE_CREDENTIAL.replace_all(&text, "$1 [removed]").into_owned();
126 text = FINGERPRINT.replace_all(&text, "[fingerprint]").into_owned();
127 text = THREAD.replace_all(&text, |captures: &Captures| self.meeting(&captures[0])).into_owned();
128 text = ENCODED_THREAD.replace_all(&text, |captures: &Captures| self.meeting(&captures[0])).into_owned();
129 text = MRI.replace_all(&text, |captures: &Captures| self.person(&captures[0])).into_owned();
130 text = EMAIL.replace_all(&text, |captures: &Captures| self.person(&captures[0])).into_owned();
131 text = PHONE.replace_all(&text, |captures: &Captures| self.person(&captures[0])).into_owned();
132 text = UUID.replace_all(&text, |captures: &Captures| self.identifier(&captures[0])).into_owned();
133 text = IPV6.replace_all(&text, "[ip]").into_owned();
134 text = IPV4.replace_all(&text, "[ip]").into_owned();
135 text = self.replace_names(&text);
136 OPAQUE.replace_all(&text, REMOVED).into_owned()
137 }
138
139 fn meeting(&mut self, key: &str) -> String {
140 let next = self.meetings.len() + 1;
141 self.meetings.entry(normalize(key)).or_insert_with(|| format!("meeting-{next}")).clone()
142 }
143
144 fn identifier(&mut self, key: &str) -> String {
145 let normalized = normalize(key);
146 if let Some(found) = self.people.get(&normalized) {
147 return found.clone();
148 }
149 let next = self.identifiers.len() + 1;
150 self.identifiers.entry(normalized).or_insert_with(|| format!("id-{next}")).clone()
151 }
152
153 fn replace_names(&self, text: &str) -> String {
154 if self.names.is_empty() {
155 return text.to_owned();
156 }
157 let mut ordered: Vec<&(String, String)> = self.names.iter().collect();
158 ordered.sort_by_key(|(name, _)| std::cmp::Reverse(name.chars().count()));
159 let alternatives: Vec<String> = ordered.iter().map(|(name, _)| escape(name)).collect();
160 let pattern = format!(r"(?i)\b(?:{})\b", alternatives.join("|"));
161 let Ok(names) = Regex::new(&pattern) else {
162 return text.to_owned();
163 };
164 names
165 .replace_all(text, |captures: &Captures| {
166 let matched = captures[0].to_lowercase();
167 ordered
168 .iter()
169 .find(|(name, _)| name.to_lowercase() == matched)
170 .map_or_else(|| REMOVED.to_owned(), |(_, placeholder)| placeholder.clone())
171 })
172 .into_owned()
173 }
174 }
175
176 fn normalize(key: &str) -> String {
177 key.trim().to_lowercase()
178 }
179
180 pub fn scrub_url(url: &str) -> String {
181 let (scheme, rest) = url.split_once("://").unwrap_or(("", url));
182 let (authority_and_path, has_query) = match rest.find(['?', '#']) {
183 Some(position) => (&rest[..position], true),
184 None => (rest, false),
185 };
186 let (authority, path) = match authority_and_path.find('/') {
187 Some(position) => authority_and_path.split_at(position),
188 None => (authority_and_path, ""),
189 };
190 let host = authority.rsplit('@').next().unwrap_or(authority);
191 let host_name = host.split(':').next().unwrap_or(host);
192 let host = if IPV4.is_match(host_name) || host.starts_with('[') {
193 "[ip]".to_owned()
194 } else {
195 host.to_lowercase()
196 };
197 let path: Vec<String> = path
198 .split('/')
199 .map(|segment| if is_identifier_segment(segment) { "{id}".to_owned() } else { segment.to_owned() })
200 .collect();
201 let query = if has_query { "?..." } else { "" };
202 format!("{scheme}://{host}{}{query}", path.join("/"))
203 }
204
205 fn is_identifier_segment(segment: &str) -> bool {
206 let has_digit = segment.chars().any(|character| character.is_ascii_digit());
207 let encoded = segment.contains(['@', ':', '%', '=']);
208 encoded || (segment.chars().count() >= ID_SEGMENT_MIN && has_digit) || UUID.is_match(segment)
209 }
210
211 #[cfg(test)]
212 mod tests {
213 use super::*;
214
215 fn scrubber() -> Scrubber {
216 let mut scrubber = Scrubber::new();
217 scrubber.register_self("8:orgid:11111111-2222-3333-4444-555555555555", "Daniel Daeschle", "daniel@example.com");
218 scrubber.register_person("8:orgid:aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", "Mara Lindqvist");
219 scrubber
220 }
221
222 const FIXTURE: &str = "\
223 Mara Lindqvist called 8:orgid:aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee from daniel@example.com; \
224 Daniel Daeschle answered. Colleague jonas.ortega@contoso.com and +49 170 1234567 joined, also 8:orgid:99999999-8888-7777-6666-555555555555 and 4:+4917012345678. \
225 Thread 19:meeting_ZmFrZWlkMTIzNDU2Nzg5@thread.v2 and 19:abc123_def456@unq.gbl.spaces. \
226 GET https://emea.ng.msg.teams.microsoft.com/v1/users/ME/conversations/19%3Aabc%40thread.v2/messages?token=abc123&skypetoken=zzz#frag \
227 Authorization: Bearer abcdef.ghijkl.mnopqr and eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiIxMjM0In0.c2lnbmF0dXJl. \
228 Cookie: session=abc; other=def\n\
229 Retry with access_token=hunter2 failed. \
230 a=ice-ufrag:Xy12 a=ice-pwd:supersecretpasswordvalue12 candidate 1 UDP 2122 203.0.113.9 50000 typ host ufrag Xy12 and 2001:db8:85a3::8a2e:370:7334 \
231 a=fingerprint:sha-256 AB:CD:EF:01:23:45:67:89:AB:CD:EF:01:23:45:67:89:AB:CD:EF:01:23:45:67:89:AB:CD:EF:01:23:45:67:89 \
232 opaque QWxhZGRpbjpvcGVuIHNlc2FtZVF1ZXJ5U3RyaW5nVGhhdElzTG9uZ0Vub3VnaEZvckFUb2tlbg \
233 meeting id 12345678-aaaa-bbbb-cccc-1234567890ab at 12:30:45.";
234
235 #[test]
236 fn nothing_personal_survives_the_fixture() {
237 let scrubbed = scrubber().scrub(FIXTURE);
238 for leaked in [
239 "Mara", "Lindqvist", "Daniel", "Daeschle", "daniel@", "example.com", "jonas", "contoso", "+49", "1234567",
240 "aaaaaaaa", "99999999", "11111111", "ZmFrZW", "abc123", "def456", "skypetoken=zzz", "token=abc", "abcdef.ghijkl",
241 "eyJ", "session=abc", "access_token=hunter2", "Xy12", "supersecret", "203.0.113.9", "2001:db8", "AB:CD:EF", "QWxhZGRp", "12345678-aaaa",
242 ] {
243 assert!(!scrubbed.contains(leaked), "{leaked} leaked in: {scrubbed}");
244 }
245 }
246
247 #[test]
248 fn people_get_stable_placeholders_across_forms() {
249 let mut scrubber = scrubber();
250 let scrubbed = scrubber.scrub("Mara Lindqvist 8:orgid:AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee mara");
251 assert_eq!(scrubbed, "person-1 person-1 person-1 person-1");
252 assert_eq!(scrubber.scrub("daniel@example.com Daniel"), "self self");
253 assert_eq!(scrubber.scrub("8:orgid:99999999-8888-7777-6666-555555555555"), "person-2");
254 assert_eq!(scrubber.scrub("jonas.ortega@contoso.com 8:orgid:99999999-8888-7777-6666-555555555555"), "person-3 person-2");
255 }
256
257 #[test]
258 fn threads_become_numbered_meetings() {
259 let mut scrubber = Scrubber::new();
260 let scrubbed = scrubber.scrub("19:abc@thread.v2 then 19:def@thread.v2 then 19:abc@thread.v2");
261 assert_eq!(scrubbed, "meeting-1 then meeting-2 then meeting-1");
262 }
263
264 #[test]
265 fn urls_keep_host_and_path_shape() {
266 assert_eq!(
267 scrub_url("https://Host.Example.com/v1/users/ME/conversations/19%3Aabc%40thread.v2/messages/1699999999999?x=1"),
268 "https://host.example.com/v1/users/ME/conversations/{id}/messages/{id}?..."
269 );
270 assert_eq!(scrub_url("https://203.0.113.9:3478/turn"), "https://[ip]/turn");
271 assert_eq!(scrub_url("https://user:pass@host.example.com/a"), "https://host.example.com/a");
272 }
273
274 #[test]
275 fn plain_diagnostics_stay_readable() {
276 let mut scrubber = scrubber();
277 let text = "ICE state Connected at 12:30:45, in packets=1200 level=0.031 mixer reports 4 (rtt 31 ms)";
278 assert_eq!(scrubber.scrub(text), text);
279 }
280
281 #[test]
282 fn the_echo_bot_is_named_not_numbered() {
283 let mut scrubber = Scrubber::new();
284 scrubber.register_person(calling::signaling::ECHO_BOT_MRI, "Teams echo");
285 assert_eq!(scrubber.scrub(&format!("{} Teams echo", calling::signaling::ECHO_BOT_MRI)), "echo-bot echo-bot");
286 }
287 }
@@ -0,0 +1,287 @@
1use std::collections::HashMap;
2use std::sync::LazyLock;
3
4use regex::{Captures, Regex, escape};
5
6pub const SELF_PLACEHOLDER: &str = "self";
7pub const ECHO_PLACEHOLDER: &str = "echo-bot";
8const ORGID_PREFIX: &str = "8:orgid:";
9const MIN_NAME_PART: usize = 3;
10const ID_SEGMENT_MIN: usize = 8;
11const REMOVED: &str = "[removed]";
12
13fn compiled(pattern: &str) -> Regex {
14 Regex::new(pattern).expect("scrub pattern compiles")
15}
16
17static URL: LazyLock<Regex> = LazyLock::new(|| compiled(r#"(?i)\b[a-z][a-z0-9+.-]*://[^\s"'<>)\]]+"#));
18static JWT: LazyLock<Regex> = LazyLock::new(|| compiled(r"\beyJ[\w-]+\.[\w-]+\.[\w-]*"));
19static COOKIE: LazyLock<Regex> = LazyLock::new(|| compiled(r"(?i)\b(set-cookie|cookie)\s*[:=][^\n]*"));
20static BEARER: LazyLock<Regex> = LazyLock::new(|| compiled(r"(?i)\b(bearer|basic)\s+[\w\-.~+/=]+"));
21static CREDENTIAL: LazyLock<Regex> = LazyLock::new(|| {
22 compiled(
23 r"(?i)\b(access_token|refresh_token|id_token|skypetoken|authtoken|token|authorization|password|passwd|secret|signature|sig)\b\s*[:=]\s*[^\s&;,]+",
24 )
25});
26static ICE_CREDENTIAL: LazyLock<Regex> =
27 LazyLock::new(|| compiled(r"(?i)\b(ice-ufrag|ice-pwd|ufrag|pwd)\b[:=\s]+\S+"));
28static FINGERPRINT: LazyLock<Regex> = LazyLock::new(|| compiled(r"(?i)\b(?:[0-9a-f]{2}:){15,}[0-9a-f]{2}\b"));
29static THREAD: LazyLock<Regex> = LazyLock::new(|| compiled(r#"\b19:[^\s,;"'<>()]+@[A-Za-z0-9.\-]+"#));
30static ENCODED_THREAD: LazyLock<Regex> = LazyLock::new(|| compiled(r"(?i)\b19%3a\S+?%40[A-Za-z0-9.\-]+"));
31static MRI: LazyLock<Regex> = LazyLock::new(|| {
32 compiled(r#"\b(?:8:(?:orgid|live|acs|teamsvisitor|spo|gid):[A-Za-z0-9_.+\-=]+|28:[A-Za-z0-9_.\-]{8,}|4:\+?\d{5,})"#)
33});
34static EMAIL: LazyLock<Regex> = LazyLock::new(|| compiled(r"[A-Za-z0-9._%+'\-]+@[A-Za-z0-9\-]+(?:\.[A-Za-z0-9\-]+)+"));
35static UUID: LazyLock<Regex> = LazyLock::new(|| {
36 compiled(r"(?i)\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b")
37});
38static IPV4: LazyLock<Regex> = LazyLock::new(|| compiled(r"\b(?:\d{1,3}\.){3}\d{1,3}\b"));
39static IPV6: LazyLock<Regex> = LazyLock::new(|| {
40 compiled(
41 r"(?i)\b(?:[0-9a-f]{1,4}:){7}[0-9a-f]{1,4}\b|(?:\b[0-9a-f]{1,4}:){1,7}:(?:[0-9a-f]{1,4}(?::[0-9a-f]{1,4}){0,6})?|::(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4}\b",
42 )
43});
44static PHONE: LazyLock<Regex> = LazyLock::new(|| compiled(r"\+\d[\d ()\-/]{6,}\d"));
45static OPAQUE: LazyLock<Regex> = LazyLock::new(|| compiled(r"[A-Za-z0-9+/_\-]{40,}={0,2}"));
46
47#[derive(Debug, Clone, Default)]
48pub struct Scrubber {
49 people: HashMap<String, String>,
50 names: Vec<(String, String)>,
51 meetings: HashMap<String, String>,
52 identifiers: HashMap<String, String>,
53 person_count: usize,
54}
55
56impl Scrubber {
57 pub fn new() -> Self {
58 Scrubber::default()
59 }
60
61 pub fn register_self(&mut self, mri: &str, display_name: &str, email: &str) {
62 for key in [mri, email].into_iter().filter(|key| !key.trim().is_empty()) {
63 self.alias(key, SELF_PLACEHOLDER);
64 }
65 self.add_name(display_name, SELF_PLACEHOLDER);
66 }
67
68 pub fn register_person(&mut self, mri: &str, display_name: &str) {
69 let placeholder = if mri == calling::signaling::ECHO_BOT_MRI {
70 self.alias(mri, ECHO_PLACEHOLDER);
71 if !display_name.trim().is_empty() {
72 self.names.push((display_name.to_owned(), ECHO_PLACEHOLDER.to_owned()));
73 }
74 return;
75 } else if mri.is_empty() {
76 self.person(display_name)
77 } else {
78 self.person(mri)
79 };
80 self.add_name(display_name, &placeholder);
81 }
82
83 pub fn person(&mut self, key: &str) -> String {
84 let normalized = normalize(key);
85 if let Some(found) = self.people.get(&normalized) {
86 return found.clone();
87 }
88 self.person_count += 1;
89 let placeholder = format!("person-{}", self.person_count);
90 self.alias(key, &placeholder);
91 placeholder
92 }
93
94 fn alias(&mut self, key: &str, placeholder: &str) {
95 let normalized = normalize(key);
96 if let Some(user_id) = normalized.strip_prefix(ORGID_PREFIX) {
97 self.people.insert(user_id.to_owned(), placeholder.to_owned());
98 }
99 self.people.insert(normalized, placeholder.to_owned());
100 }
101
102 fn add_name(&mut self, name: &str, placeholder: &str) {
103 if name.trim().is_empty() {
104 return;
105 }
106 let mut candidates = vec![name.to_owned()];
107 candidates.extend(
108 name.split(|character: char| !character.is_alphanumeric())
109 .filter(|part| part.chars().count() >= MIN_NAME_PART)
110 .map(str::to_owned),
111 );
112 for candidate in candidates {
113 if !self.names.iter().any(|(known, _)| known.eq_ignore_ascii_case(&candidate)) {
114 self.names.push((candidate, placeholder.to_owned()));
115 }
116 }
117 }
118
119 pub fn scrub(&mut self, text: &str) -> String {
120 let mut text = URL.replace_all(text, |captures: &Captures| scrub_url(&captures[0])).into_owned();
121 text = JWT.replace_all(&text, REMOVED).into_owned();
122 text = COOKIE.replace_all(&text, "$1: [removed]").into_owned();
123 text = BEARER.replace_all(&text, "$1 [removed]").into_owned();
124 text = CREDENTIAL.replace_all(&text, "$1 [removed]").into_owned();
125 text = ICE_CREDENTIAL.replace_all(&text, "$1 [removed]").into_owned();
126 text = FINGERPRINT.replace_all(&text, "[fingerprint]").into_owned();
127 text = THREAD.replace_all(&text, |captures: &Captures| self.meeting(&captures[0])).into_owned();
128 text = ENCODED_THREAD.replace_all(&text, |captures: &Captures| self.meeting(&captures[0])).into_owned();
129 text = MRI.replace_all(&text, |captures: &Captures| self.person(&captures[0])).into_owned();
130 text = EMAIL.replace_all(&text, |captures: &Captures| self.person(&captures[0])).into_owned();
131 text = PHONE.replace_all(&text, |captures: &Captures| self.person(&captures[0])).into_owned();
132 text = UUID.replace_all(&text, |captures: &Captures| self.identifier(&captures[0])).into_owned();
133 text = IPV6.replace_all(&text, "[ip]").into_owned();
134 text = IPV4.replace_all(&text, "[ip]").into_owned();
135 text = self.replace_names(&text);
136 OPAQUE.replace_all(&text, REMOVED).into_owned()
137 }
138
139 fn meeting(&mut self, key: &str) -> String {
140 let next = self.meetings.len() + 1;
141 self.meetings.entry(normalize(key)).or_insert_with(|| format!("meeting-{next}")).clone()
142 }
143
144 fn identifier(&mut self, key: &str) -> String {
145 let normalized = normalize(key);
146 if let Some(found) = self.people.get(&normalized) {
147 return found.clone();
148 }
149 let next = self.identifiers.len() + 1;
150 self.identifiers.entry(normalized).or_insert_with(|| format!("id-{next}")).clone()
151 }
152
153 fn replace_names(&self, text: &str) -> String {
154 if self.names.is_empty() {
155 return text.to_owned();
156 }
157 let mut ordered: Vec<&(String, String)> = self.names.iter().collect();
158 ordered.sort_by_key(|(name, _)| std::cmp::Reverse(name.chars().count()));
159 let alternatives: Vec<String> = ordered.iter().map(|(name, _)| escape(name)).collect();
160 let pattern = format!(r"(?i)\b(?:{})\b", alternatives.join("|"));
161 let Ok(names) = Regex::new(&pattern) else {
162 return text.to_owned();
163 };
164 names
165 .replace_all(text, |captures: &Captures| {
166 let matched = captures[0].to_lowercase();
167 ordered
168 .iter()
169 .find(|(name, _)| name.to_lowercase() == matched)
170 .map_or_else(|| REMOVED.to_owned(), |(_, placeholder)| placeholder.clone())
171 })
172 .into_owned()
173 }
174}
175
176fn normalize(key: &str) -> String {
177 key.trim().to_lowercase()
178}
179
180pub fn scrub_url(url: &str) -> String {
181 let (scheme, rest) = url.split_once("://").unwrap_or(("", url));
182 let (authority_and_path, has_query) = match rest.find(['?', '#']) {
183 Some(position) => (&rest[..position], true),
184 None => (rest, false),
185 };
186 let (authority, path) = match authority_and_path.find('/') {
187 Some(position) => authority_and_path.split_at(position),
188 None => (authority_and_path, ""),
189 };
190 let host = authority.rsplit('@').next().unwrap_or(authority);
191 let host_name = host.split(':').next().unwrap_or(host);
192 let host = if IPV4.is_match(host_name) || host.starts_with('[') {
193 "[ip]".to_owned()
194 } else {
195 host.to_lowercase()
196 };
197 let path: Vec<String> = path
198 .split('/')
199 .map(|segment| if is_identifier_segment(segment) { "{id}".to_owned() } else { segment.to_owned() })
200 .collect();
201 let query = if has_query { "?..." } else { "" };
202 format!("{scheme}://{host}{}{query}", path.join("/"))
203}
204
205fn is_identifier_segment(segment: &str) -> bool {
206 let has_digit = segment.chars().any(|character| character.is_ascii_digit());
207 let encoded = segment.contains(['@', ':', '%', '=']);
208 encoded || (segment.chars().count() >= ID_SEGMENT_MIN && has_digit) || UUID.is_match(segment)
209}
210
211#[cfg(test)]
212mod tests {
213 use super::*;
214
215 fn scrubber() -> Scrubber {
216 let mut scrubber = Scrubber::new();
217 scrubber.register_self("8:orgid:11111111-2222-3333-4444-555555555555", "Daniel Daeschle", "daniel@example.com");
218 scrubber.register_person("8:orgid:aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", "Mara Lindqvist");
219 scrubber
220 }
221
222 const FIXTURE: &str = "\
223Mara Lindqvist called 8:orgid:aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee from daniel@example.com; \
224Daniel Daeschle answered. Colleague jonas.ortega@contoso.com and +49 170 1234567 joined, also 8:orgid:99999999-8888-7777-6666-555555555555 and 4:+4917012345678. \
225Thread 19:meeting_ZmFrZWlkMTIzNDU2Nzg5@thread.v2 and 19:abc123_def456@unq.gbl.spaces. \
226GET https://emea.ng.msg.teams.microsoft.com/v1/users/ME/conversations/19%3Aabc%40thread.v2/messages?token=abc123&skypetoken=zzz#frag \
227Authorization: Bearer abcdef.ghijkl.mnopqr and eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiIxMjM0In0.c2lnbmF0dXJl. \
228Cookie: session=abc; other=def\n\
229Retry with access_token=hunter2 failed. \
230a=ice-ufrag:Xy12 a=ice-pwd:supersecretpasswordvalue12 candidate 1 UDP 2122 203.0.113.9 50000 typ host ufrag Xy12 and 2001:db8:85a3::8a2e:370:7334 \
231a=fingerprint:sha-256 AB:CD:EF:01:23:45:67:89:AB:CD:EF:01:23:45:67:89:AB:CD:EF:01:23:45:67:89:AB:CD:EF:01:23:45:67:89 \
232opaque QWxhZGRpbjpvcGVuIHNlc2FtZVF1ZXJ5U3RyaW5nVGhhdElzTG9uZ0Vub3VnaEZvckFUb2tlbg \
233meeting id 12345678-aaaa-bbbb-cccc-1234567890ab at 12:30:45.";
234
235 #[test]
236 fn nothing_personal_survives_the_fixture() {
237 let scrubbed = scrubber().scrub(FIXTURE);
238 for leaked in [
239 "Mara", "Lindqvist", "Daniel", "Daeschle", "daniel@", "example.com", "jonas", "contoso", "+49", "1234567",
240 "aaaaaaaa", "99999999", "11111111", "ZmFrZW", "abc123", "def456", "skypetoken=zzz", "token=abc", "abcdef.ghijkl",
241 "eyJ", "session=abc", "access_token=hunter2", "Xy12", "supersecret", "203.0.113.9", "2001:db8", "AB:CD:EF", "QWxhZGRp", "12345678-aaaa",
242 ] {
243 assert!(!scrubbed.contains(leaked), "{leaked} leaked in: {scrubbed}");
244 }
245 }
246
247 #[test]
248 fn people_get_stable_placeholders_across_forms() {
249 let mut scrubber = scrubber();
250 let scrubbed = scrubber.scrub("Mara Lindqvist 8:orgid:AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee mara");
251 assert_eq!(scrubbed, "person-1 person-1 person-1 person-1");
252 assert_eq!(scrubber.scrub("daniel@example.com Daniel"), "self self");
253 assert_eq!(scrubber.scrub("8:orgid:99999999-8888-7777-6666-555555555555"), "person-2");
254 assert_eq!(scrubber.scrub("jonas.ortega@contoso.com 8:orgid:99999999-8888-7777-6666-555555555555"), "person-3 person-2");
255 }
256
257 #[test]
258 fn threads_become_numbered_meetings() {
259 let mut scrubber = Scrubber::new();
260 let scrubbed = scrubber.scrub("19:abc@thread.v2 then 19:def@thread.v2 then 19:abc@thread.v2");
261 assert_eq!(scrubbed, "meeting-1 then meeting-2 then meeting-1");
262 }
263
264 #[test]
265 fn urls_keep_host_and_path_shape() {
266 assert_eq!(
267 scrub_url("https://Host.Example.com/v1/users/ME/conversations/19%3Aabc%40thread.v2/messages/1699999999999?x=1"),
268 "https://host.example.com/v1/users/ME/conversations/{id}/messages/{id}?..."
269 );
270 assert_eq!(scrub_url("https://203.0.113.9:3478/turn"), "https://[ip]/turn");
271 assert_eq!(scrub_url("https://user:pass@host.example.com/a"), "https://host.example.com/a");
272 }
273
274 #[test]
275 fn plain_diagnostics_stay_readable() {
276 let mut scrubber = scrubber();
277 let text = "ICE state Connected at 12:30:45, in packets=1200 level=0.031 mixer reports 4 (rtt 31 ms)";
278 assert_eq!(scrubber.scrub(text), text);
279 }
280
281 #[test]
282 fn the_echo_bot_is_named_not_numbered() {
283 let mut scrubber = Scrubber::new();
284 scrubber.register_person(calling::signaling::ECHO_BOT_MRI, "Teams echo");
285 assert_eq!(scrubber.scrub(&format!("{} Teams echo", calling::signaling::ECHO_BOT_MRI)), "echo-bot echo-bot");
286 }
287}
crates/app/src/call/report/series.rs added +173 −0
@@ -0,0 +1,173 @@
1 use std::collections::BTreeMap;
2
3 use calling::{CallHealth, Limitation, NetworkLevel, StatsSample};
4
5 #[derive(Debug, Clone, Copy, PartialEq)]
6 pub struct Series {
7 pub min: f64,
8 pub max: f64,
9 pub last: f64,
10 pub samples: u32,
11 }
12
13 impl Series {
14 fn new(value: f64) -> Self {
15 Series { min: value, max: value, last: value, samples: 1 }
16 }
17
18 fn observe(&mut self, value: f64) {
19 self.min = self.min.min(value);
20 self.max = self.max.max(value);
21 self.last = value;
22 self.samples += 1;
23 }
24 }
25
26 #[derive(Debug, Clone, Default, PartialEq)]
27 pub struct StatsSeries {
28 values: BTreeMap<&'static str, Series>,
29 pub stalled_audio_in: u32,
30 pub stalled_audio_out: u32,
31 pub level_samples: [u32; 3],
32 pub limitation_samples: [u32; 3],
33 pub cpu_limited_samples: u32,
34 pub level_changes: Vec<(u128, &'static str)>,
35 pub last_level: Option<NetworkLevel>,
36 }
37
38 pub fn level_name(level: NetworkLevel) -> &'static str {
39 match level {
40 NetworkLevel::Good => "good",
41 NetworkLevel::Poor => "poor",
42 NetworkLevel::Bad => "bad",
43 }
44 }
45
46 pub fn limitation_name(limitation: Limitation) -> &'static str {
47 match limitation {
48 Limitation::None => "none",
49 Limitation::Cpu => "cpu",
50 Limitation::Bandwidth => "bandwidth",
51 }
52 }
53
54 impl StatsSeries {
55 pub fn values(&self) -> &BTreeMap<&'static str, Series> {
56 &self.values
57 }
58
59 fn observe(&mut self, name: &'static str, value: f64) {
60 match self.values.get_mut(name) {
61 Some(series) => series.observe(value),
62 None => {
63 self.values.insert(name, Series::new(value));
64 }
65 }
66 }
67
68 pub fn observe_sample(&mut self, sample: &StatsSample) {
69 let video = &sample.video;
70 if let Some(before) = self.values.get("audio_in_packets")
71 && sample.audio_in_packets <= before.last as u64
72 {
73 self.stalled_audio_in += 1;
74 }
75 if let Some(before) = self.values.get("audio_out_packets")
76 && sample.audio_out_packets <= before.last as u64
77 {
78 self.stalled_audio_out += 1;
79 }
80 let readings: [(&'static str, f64); 16] = [
81 ("audio_in_packets", sample.audio_in_packets as f64),
82 ("audio_out_packets", sample.audio_out_packets as f64),
83 ("audio_in_level", sample.audio_in_level),
84 ("audio_out_level", sample.audio_out_level),
85 ("video_in_packets", video.inbound_packets as f64),
86 ("video_in_frames_decoded", video.inbound_frames_decoded as f64),
87 ("video_in_width", f64::from(video.inbound_width)),
88 ("video_in_height", f64::from(video.inbound_height)),
89 ("video_out_packets", video.outbound_packets as f64),
90 ("video_out_frames_encoded", video.outbound_frames_encoded as f64),
91 ("video_out_width", f64::from(video.outbound_width)),
92 ("video_out_height", f64::from(video.outbound_height)),
93 ("video_remote_round_trip_ms", video.remote_round_trip_ms),
94 ("share_in_packets", sample.share_in_packets as f64),
95 ("share_out_packets", sample.share_out_packets as f64),
96 ("video_frames_published", video.frames_published as f64),
97 ];
98 for (name, value) in readings {
99 self.observe(name, value);
100 }
101 }
102
103 pub fn observe_health(&mut self, health: &CallHealth, at_ms: u128) {
104 let sample = &health.sample;
105 for (name, value) in [
106 ("loss_percent", sample.loss_percent),
107 ("round_trip_ms", sample.round_trip_ms),
108 ("jitter_ms", sample.jitter_ms),
109 ("sent_kbps", sample.sent_kbps),
110 ("received_kbps", sample.received_kbps),
111 ] {
112 self.observe(name, value);
113 }
114 self.level_samples[health.level as usize] += 1;
115 self.limitation_samples[sample.limitation as usize] += 1;
116 if health.cpu_limited {
117 self.cpu_limited_samples += 1;
118 }
119 if self.last_level != Some(health.level) {
120 self.level_changes.push((at_ms, level_name(health.level)));
121 self.last_level = Some(health.level);
122 }
123 }
124 }
125
126 #[cfg(test)]
127 mod tests {
128 use calling::{HealthSample, MediaPath, TransportDetails, call::VideoReport};
129
130 use super::*;
131
132 fn sample(audio_in: u64) -> StatsSample {
133 StatsSample {
134 audio_in_packets: audio_in,
135 audio_out_packets: audio_in * 2,
136 video: VideoReport { inbound_width: 1280, inbound_height: 720, ..VideoReport::default() },
137 ..StatsSample::default()
138 }
139 }
140
141 fn health(level: NetworkLevel, loss_percent: f64) -> CallHealth {
142 CallHealth {
143 level,
144 cpu_limited: false,
145 sample: HealthSample { loss_percent, ..HealthSample::default() },
146 transport: TransportDetails::default(),
147 path: MediaPath::Direct,
148 }
149 }
150
151 #[test]
152 fn samples_keep_min_max_last_and_count_stalls() {
153 let mut series = StatsSeries::default();
154 for packets in [10, 20, 20, 35] {
155 series.observe_sample(&sample(packets));
156 }
157 let audio_in = series.values()["audio_in_packets"];
158 assert_eq!((audio_in.min, audio_in.max, audio_in.last, audio_in.samples), (10., 35., 35., 4));
159 assert_eq!(series.stalled_audio_in, 1);
160 assert_eq!(series.values()["video_in_width"].last, 1280.);
161 }
162
163 #[test]
164 fn health_keeps_ranges_and_level_changes() {
165 let mut series = StatsSeries::default();
166 series.observe_health(&health(NetworkLevel::Good, 0.), 2000);
167 series.observe_health(&health(NetworkLevel::Poor, 7.), 4000);
168 series.observe_health(&health(NetworkLevel::Poor, 6.), 6000);
169 assert_eq!(series.values()["loss_percent"].max, 7.);
170 assert_eq!(series.level_samples, [1, 2, 0]);
171 assert_eq!(series.level_changes, [(2000, "good"), (4000, "poor")]);
172 }
173 }
@@ -0,0 +1,173 @@
1use std::collections::BTreeMap;
2
3use calling::{CallHealth, Limitation, NetworkLevel, StatsSample};
4
5#[derive(Debug, Clone, Copy, PartialEq)]
6pub struct Series {
7 pub min: f64,
8 pub max: f64,
9 pub last: f64,
10 pub samples: u32,
11}
12
13impl Series {
14 fn new(value: f64) -> Self {
15 Series { min: value, max: value, last: value, samples: 1 }
16 }
17
18 fn observe(&mut self, value: f64) {
19 self.min = self.min.min(value);
20 self.max = self.max.max(value);
21 self.last = value;
22 self.samples += 1;
23 }
24}
25
26#[derive(Debug, Clone, Default, PartialEq)]
27pub struct StatsSeries {
28 values: BTreeMap<&'static str, Series>,
29 pub stalled_audio_in: u32,
30 pub stalled_audio_out: u32,
31 pub level_samples: [u32; 3],
32 pub limitation_samples: [u32; 3],
33 pub cpu_limited_samples: u32,
34 pub level_changes: Vec<(u128, &'static str)>,
35 pub last_level: Option<NetworkLevel>,
36}
37
38pub fn level_name(level: NetworkLevel) -> &'static str {
39 match level {
40 NetworkLevel::Good => "good",
41 NetworkLevel::Poor => "poor",
42 NetworkLevel::Bad => "bad",
43 }
44}
45
46pub fn limitation_name(limitation: Limitation) -> &'static str {
47 match limitation {
48 Limitation::None => "none",
49 Limitation::Cpu => "cpu",
50 Limitation::Bandwidth => "bandwidth",
51 }
52}
53
54impl StatsSeries {
55 pub fn values(&self) -> &BTreeMap<&'static str, Series> {
56 &self.values
57 }
58
59 fn observe(&mut self, name: &'static str, value: f64) {
60 match self.values.get_mut(name) {
61 Some(series) => series.observe(value),
62 None => {
63 self.values.insert(name, Series::new(value));
64 }
65 }
66 }
67
68 pub fn observe_sample(&mut self, sample: &StatsSample) {
69 let video = &sample.video;
70 if let Some(before) = self.values.get("audio_in_packets")
71 && sample.audio_in_packets <= before.last as u64
72 {
73 self.stalled_audio_in += 1;
74 }
75 if let Some(before) = self.values.get("audio_out_packets")
76 && sample.audio_out_packets <= before.last as u64
77 {
78 self.stalled_audio_out += 1;
79 }
80 let readings: [(&'static str, f64); 16] = [
81 ("audio_in_packets", sample.audio_in_packets as f64),
82 ("audio_out_packets", sample.audio_out_packets as f64),
83 ("audio_in_level", sample.audio_in_level),
84 ("audio_out_level", sample.audio_out_level),
85 ("video_in_packets", video.inbound_packets as f64),
86 ("video_in_frames_decoded", video.inbound_frames_decoded as f64),
87 ("video_in_width", f64::from(video.inbound_width)),
88 ("video_in_height", f64::from(video.inbound_height)),
89 ("video_out_packets", video.outbound_packets as f64),
90 ("video_out_frames_encoded", video.outbound_frames_encoded as f64),
91 ("video_out_width", f64::from(video.outbound_width)),
92 ("video_out_height", f64::from(video.outbound_height)),
93 ("video_remote_round_trip_ms", video.remote_round_trip_ms),
94 ("share_in_packets", sample.share_in_packets as f64),
95 ("share_out_packets", sample.share_out_packets as f64),
96 ("video_frames_published", video.frames_published as f64),
97 ];
98 for (name, value) in readings {
99 self.observe(name, value);
100 }
101 }
102
103 pub fn observe_health(&mut self, health: &CallHealth, at_ms: u128) {
104 let sample = &health.sample;
105 for (name, value) in [
106 ("loss_percent", sample.loss_percent),
107 ("round_trip_ms", sample.round_trip_ms),
108 ("jitter_ms", sample.jitter_ms),
109 ("sent_kbps", sample.sent_kbps),
110 ("received_kbps", sample.received_kbps),
111 ] {
112 self.observe(name, value);
113 }
114 self.level_samples[health.level as usize] += 1;
115 self.limitation_samples[sample.limitation as usize] += 1;
116 if health.cpu_limited {
117 self.cpu_limited_samples += 1;
118 }
119 if self.last_level != Some(health.level) {
120 self.level_changes.push((at_ms, level_name(health.level)));
121 self.last_level = Some(health.level);
122 }
123 }
124}
125
126#[cfg(test)]
127mod tests {
128 use calling::{HealthSample, MediaPath, TransportDetails, call::VideoReport};
129
130 use super::*;
131
132 fn sample(audio_in: u64) -> StatsSample {
133 StatsSample {
134 audio_in_packets: audio_in,
135 audio_out_packets: audio_in * 2,
136 video: VideoReport { inbound_width: 1280, inbound_height: 720, ..VideoReport::default() },
137 ..StatsSample::default()
138 }
139 }
140
141 fn health(level: NetworkLevel, loss_percent: f64) -> CallHealth {
142 CallHealth {
143 level,
144 cpu_limited: false,
145 sample: HealthSample { loss_percent, ..HealthSample::default() },
146 transport: TransportDetails::default(),
147 path: MediaPath::Direct,
148 }
149 }
150
151 #[test]
152 fn samples_keep_min_max_last_and_count_stalls() {
153 let mut series = StatsSeries::default();
154 for packets in [10, 20, 20, 35] {
155 series.observe_sample(&sample(packets));
156 }
157 let audio_in = series.values()["audio_in_packets"];
158 assert_eq!((audio_in.min, audio_in.max, audio_in.last, audio_in.samples), (10., 35., 35., 4));
159 assert_eq!(series.stalled_audio_in, 1);
160 assert_eq!(series.values()["video_in_width"].last, 1280.);
161 }
162
163 #[test]
164 fn health_keeps_ranges_and_level_changes() {
165 let mut series = StatsSeries::default();
166 series.observe_health(&health(NetworkLevel::Good, 0.), 2000);
167 series.observe_health(&health(NetworkLevel::Poor, 7.), 4000);
168 series.observe_health(&health(NetworkLevel::Poor, 6.), 6000);
169 assert_eq!(series.values()["loss_percent"].max, 7.);
170 assert_eq!(series.level_samples, [1, 2, 0]);
171 assert_eq!(series.level_changes, [(2000, "good"), (4000, "poor")]);
172 }
173}
crates/app/src/call/report/storage.rs added +103 −0
@@ -0,0 +1,103 @@
1 use std::fs;
2 use std::io;
3 use std::path::{Path, PathBuf};
4
5 use super::Document;
6
7 const REPORT_DIRECTORY: &str = "call-reports";
8 const KEEP_REPORTS: usize = 30;
9 const JSON_EXTENSION: &str = "json";
10 const MARKDOWN_EXTENSION: &str = "md";
11
12 #[derive(Debug, Clone, PartialEq, Eq)]
13 pub struct SavedReport {
14 pub json: PathBuf,
15 pub markdown: PathBuf,
16 }
17
18 #[cfg(test)]
19 pub fn report_directory() -> PathBuf {
20 std::env::temp_dir().join("rusty-teams-test-call-reports")
21 }
22
23 #[cfg(not(test))]
24 pub fn report_directory() -> PathBuf {
25 directories::ProjectDirs::from("", "", store::DATA_DIR_NAME)
26 .map(|directories| directories.data_local_dir().join(REPORT_DIRECTORY))
27 .unwrap_or_else(|| PathBuf::from(REPORT_DIRECTORY))
28 }
29
30 pub fn save_report(directory: &Path, document: &Document) -> io::Result<SavedReport> {
31 fs::create_dir_all(directory)?;
32 let stem = free_stem(directory, &document.stem);
33 let saved = SavedReport {
34 json: directory.join(format!("{stem}.{JSON_EXTENSION}")),
35 markdown: directory.join(format!("{stem}.{MARKDOWN_EXTENSION}")),
36 };
37 fs::write(&saved.json, &document.json)?;
38 fs::write(&saved.markdown, &document.markdown)?;
39 prune(directory, KEEP_REPORTS);
40 Ok(saved)
41 }
42
43 fn free_stem(directory: &Path, stem: &str) -> String {
44 let taken = |candidate: &str| directory.join(format!("{candidate}.{JSON_EXTENSION}")).exists();
45 if !taken(stem) {
46 return stem.to_owned();
47 }
48 (2..)
49 .map(|counter| format!("{stem}-{counter}"))
50 .find(|candidate| !taken(candidate))
51 .expect("an unbounded counter finds a free name")
52 }
53
54 fn prune(directory: &Path, keep: usize) {
55 let Ok(entries) = fs::read_dir(directory) else {
56 return;
57 };
58 let mut stems: Vec<String> = entries
59 .filter_map(Result::ok)
60 .map(|entry| entry.path())
61 .filter(|path| path.extension().is_some_and(|extension| extension == JSON_EXTENSION))
62 .filter_map(|path| path.file_stem().map(|stem| stem.to_string_lossy().into_owned()))
63 .collect();
64 stems.sort();
65 let surplus = stems.len().saturating_sub(keep);
66 for stem in &stems[..surplus] {
67 for extension in [JSON_EXTENSION, MARKDOWN_EXTENSION] {
68 let _ = fs::remove_file(directory.join(format!("{stem}.{extension}")));
69 }
70 }
71 }
72
73 #[cfg(test)]
74 mod tests {
75 use super::*;
76
77 fn document(stem: &str) -> Document {
78 Document { stem: stem.to_owned(), json: "{}".to_owned(), markdown: "# x".to_owned() }
79 }
80
81 #[test]
82 fn the_newest_thirty_reports_are_kept_with_both_files() {
83 let directory = tempfile::tempdir().unwrap();
84 for index in 0..33 {
85 save_report(directory.path(), &document(&format!("20260101T0000{index:02}Z-1to1"))).unwrap();
86 }
87 let mut names: Vec<String> =
88 fs::read_dir(directory.path()).unwrap().map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()).collect();
89 names.sort();
90 assert_eq!(names.len(), 60);
91 assert_eq!(names[0], "20260101T000003Z-1to1.json");
92 assert_eq!(names[59], "20260101T000032Z-1to1.md");
93 }
94
95 #[test]
96 fn a_report_in_the_same_second_gets_a_counter() {
97 let directory = tempfile::tempdir().unwrap();
98 let first = save_report(directory.path(), &document("20260101T000000Z-echo")).unwrap();
99 let second = save_report(directory.path(), &document("20260101T000000Z-echo")).unwrap();
100 assert_ne!(first.json, second.json);
101 assert!(second.json.to_string_lossy().ends_with("20260101T000000Z-echo-2.json"));
102 }
103 }
@@ -0,0 +1,103 @@
1use std::fs;
2use std::io;
3use std::path::{Path, PathBuf};
4
5use super::Document;
6
7const REPORT_DIRECTORY: &str = "call-reports";
8const KEEP_REPORTS: usize = 30;
9const JSON_EXTENSION: &str = "json";
10const MARKDOWN_EXTENSION: &str = "md";
11
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct SavedReport {
14 pub json: PathBuf,
15 pub markdown: PathBuf,
16}
17
18#[cfg(test)]
19pub fn report_directory() -> PathBuf {
20 std::env::temp_dir().join("rusty-teams-test-call-reports")
21}
22
23#[cfg(not(test))]
24pub fn report_directory() -> PathBuf {
25 directories::ProjectDirs::from("", "", store::DATA_DIR_NAME)
26 .map(|directories| directories.data_local_dir().join(REPORT_DIRECTORY))
27 .unwrap_or_else(|| PathBuf::from(REPORT_DIRECTORY))
28}
29
30pub fn save_report(directory: &Path, document: &Document) -> io::Result<SavedReport> {
31 fs::create_dir_all(directory)?;
32 let stem = free_stem(directory, &document.stem);
33 let saved = SavedReport {
34 json: directory.join(format!("{stem}.{JSON_EXTENSION}")),
35 markdown: directory.join(format!("{stem}.{MARKDOWN_EXTENSION}")),
36 };
37 fs::write(&saved.json, &document.json)?;
38 fs::write(&saved.markdown, &document.markdown)?;
39 prune(directory, KEEP_REPORTS);
40 Ok(saved)
41}
42
43fn free_stem(directory: &Path, stem: &str) -> String {
44 let taken = |candidate: &str| directory.join(format!("{candidate}.{JSON_EXTENSION}")).exists();
45 if !taken(stem) {
46 return stem.to_owned();
47 }
48 (2..)
49 .map(|counter| format!("{stem}-{counter}"))
50 .find(|candidate| !taken(candidate))
51 .expect("an unbounded counter finds a free name")
52}
53
54fn prune(directory: &Path, keep: usize) {
55 let Ok(entries) = fs::read_dir(directory) else {
56 return;
57 };
58 let mut stems: Vec<String> = entries
59 .filter_map(Result::ok)
60 .map(|entry| entry.path())
61 .filter(|path| path.extension().is_some_and(|extension| extension == JSON_EXTENSION))
62 .filter_map(|path| path.file_stem().map(|stem| stem.to_string_lossy().into_owned()))
63 .collect();
64 stems.sort();
65 let surplus = stems.len().saturating_sub(keep);
66 for stem in &stems[..surplus] {
67 for extension in [JSON_EXTENSION, MARKDOWN_EXTENSION] {
68 let _ = fs::remove_file(directory.join(format!("{stem}.{extension}")));
69 }
70 }
71}
72
73#[cfg(test)]
74mod tests {
75 use super::*;
76
77 fn document(stem: &str) -> Document {
78 Document { stem: stem.to_owned(), json: "{}".to_owned(), markdown: "# x".to_owned() }
79 }
80
81 #[test]
82 fn the_newest_thirty_reports_are_kept_with_both_files() {
83 let directory = tempfile::tempdir().unwrap();
84 for index in 0..33 {
85 save_report(directory.path(), &document(&format!("20260101T0000{index:02}Z-1to1"))).unwrap();
86 }
87 let mut names: Vec<String> =
88 fs::read_dir(directory.path()).unwrap().map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()).collect();
89 names.sort();
90 assert_eq!(names.len(), 60);
91 assert_eq!(names[0], "20260101T000003Z-1to1.json");
92 assert_eq!(names[59], "20260101T000032Z-1to1.md");
93 }
94
95 #[test]
96 fn a_report_in_the_same_second_gets_a_counter() {
97 let directory = tempfile::tempdir().unwrap();
98 let first = save_report(directory.path(), &document("20260101T000000Z-echo")).unwrap();
99 let second = save_report(directory.path(), &document("20260101T000000Z-echo")).unwrap();
100 assert_ne!(first.json, second.json);
101 assert!(second.json.to_string_lossy().ends_with("20260101T000000Z-echo-2.json"));
102 }
103}
crates/app/src/notify/settings_view.rs +21 −0
@@ -264,6 +264,12 @@ impl SettingsView {
264 264 cx.notify();
265 265 }
266 266
267 fn set_report_enabled(&mut self, on: bool, cx: &mut Context<Self>) {
268 let app = self.center.read(cx).app().clone();
269 app.update(cx, |state, cx| state.set_call_report_enabled(on, cx));
270 cx.notify();
271 }
272
267 273 fn change_effects(&mut self, change: fn(&mut CameraEffects), cx: &mut Context<Self>) {
268 274 let app = self.center.read(cx).app().clone();
269 275 let mut effects = app.read(cx).call_effects;
@@ -519,6 +525,8 @@ impl SettingsView {
519 525 let mic = self.center.read(cx).app().read(cx).call_mic;
520 526 let noise_view = view.clone();
521 527 let music_view = view.clone();
528 let report_view = view.clone();
529 let report_on = self.center.read(cx).app().read(cx).call_report_enabled;
522 530 let effects = self.center.read(cx).app().read(cx).call_effects;
523 531 let image = self.preview.image(Instant::now());
524 532 let status = if self.preview_blocked {
@@ -638,6 +646,19 @@ impl SettingsView {
638 646 })
639 647 }),
640 648 )
649 .child(
650 control_row(
651 "Save a test report after each call",
652 "Pseudonymized, stays on this computer",
653 switch(report_on),
654 )
655 .id("call-report-row")
656 .cursor_pointer()
657 .hover(|row| row.bg(theme::row_hover()))
658 .on_click(move |_, _, cx| {
659 report_view.update(cx, |view, cx| view.set_report_enabled(!report_on, cx))
660 }),
661 )
641 662 .child(
642 663 v_flex()
643 664 .w_full()
@@ -264,6 +264,12 @@ impl SettingsView {
264 cx.notify();
264 cx.notify();
265 }
265 }
266
266
267 fn set_report_enabled(&mut self, on: bool, cx: &mut Context<Self>) {
268 let app = self.center.read(cx).app().clone();
269 app.update(cx, |state, cx| state.set_call_report_enabled(on, cx));
270 cx.notify();
271 }
272
267 fn change_effects(&mut self, change: fn(&mut CameraEffects), cx: &mut Context<Self>) {
273 fn change_effects(&mut self, change: fn(&mut CameraEffects), cx: &mut Context<Self>) {
268 let app = self.center.read(cx).app().clone();
274 let app = self.center.read(cx).app().clone();
269 let mut effects = app.read(cx).call_effects;
275 let mut effects = app.read(cx).call_effects;
@@ -519,6 +525,8 @@ impl SettingsView {
519 let mic = self.center.read(cx).app().read(cx).call_mic;
525 let mic = self.center.read(cx).app().read(cx).call_mic;
520 let noise_view = view.clone();
526 let noise_view = view.clone();
521 let music_view = view.clone();
527 let music_view = view.clone();
528 let report_view = view.clone();
529 let report_on = self.center.read(cx).app().read(cx).call_report_enabled;
522 let effects = self.center.read(cx).app().read(cx).call_effects;
530 let effects = self.center.read(cx).app().read(cx).call_effects;
523 let image = self.preview.image(Instant::now());
531 let image = self.preview.image(Instant::now());
524 let status = if self.preview_blocked {
532 let status = if self.preview_blocked {
@@ -638,6 +646,19 @@ impl SettingsView {
638 })
646 })
639 }),
647 }),
640 )
648 )
649 .child(
650 control_row(
651 "Save a test report after each call",
652 "Pseudonymized, stays on this computer",
653 switch(report_on),
654 )
655 .id("call-report-row")
656 .cursor_pointer()
657 .hover(|row| row.bg(theme::row_hover()))
658 .on_click(move |_, _, cx| {
659 report_view.update(cx, |view, cx| view.set_report_enabled(!report_on, cx))
660 }),
661 )
641 .child(
662 .child(
642 v_flex()
663 v_flex()
643 .w_full()
664 .w_full()
crates/calling/src/call.rs +40 −2
@@ -28,6 +28,7 @@ use crate::captions::{
28 28 parse_caption_message,
29 29 };
30 30 use crate::control::{CallCommand, CallControl, CallUpdate, Progress};
31 use crate::diagnostics::{CallDiagnostics, StatsSample};
31 32 use crate::data_channel::Depacketizer;
32 33 use crate::devices::{self, DeviceChoice};
33 34 use crate::end::EndKind;
@@ -55,7 +56,7 @@ use crate::timeline::{Timeline, TimelineEntry};
55 56 use crate::transfer::{TransferEvent, TransferTarget};
56 57 use crate::video_frame::VideoKey;
57 58 use crate::video_layout::{
58 CAMERA_MID, MediaDescription, ONE_TO_ONE_SHARE_MID, SlotTable, VideoLines, VideoRouter, add_one_to_one_lines, add_video_lines, offer_plan, one_to_one_plan,
59 CAMERA_MID, MediaDescription, ONE_TO_ONE_SHARE_MID, SlotTable, VideoLines, VideoRouter, add_one_to_one_lines, add_video_lines, is_share_mid, offer_plan, one_to_one_plan,
59 60 };
60 61 use crate::video_send::{LocalVideo, VideoMode};
61 62 use crate::screen::{ShareKind, ShareSource, list_share_sources};
@@ -396,10 +397,11 @@ impl CallEngine {
396 397 tear_down(live, inner, &timeline, &mut report, cancelled).await;
397 398 let recording = recording.lock().await;
398 399 report.recorded_samples = recording.samples.len();
400 report.timeline = timeline.entries();
401 control.send(CallUpdate::Diagnostics(Box::new(CallDiagnostics::new(&report, timeline.sdp_summaries()))));
399 402 if let Some(path) = &options.wav_path {
400 403 write_wav(path, &recording.samples).map_err(|error| Error::Webrtc(format!("wav: {error}")))?;
401 404 }
402 report.timeline = timeline.entries();
403 405 match failure {
404 406 Some(error) => Err(error),
405 407 None => Ok(report),
@@ -673,6 +675,7 @@ async fn drive(
673 675 direct_video_mid = Some(CAMERA_MID.to_owned());
674 676 }
675 677 timeline.record("setLocalDescription", format!("{} m-line(s) signaled", media.signaled.lines.len()));
678 timeline.record_sdp("local offer", &media.signaled.sdp);
676 679 dump_sdp(options, "1-browser-offer.sdp", &media.browser_offer);
677 680 dump_sdp(options, "2-teams-offer.sdp", &media.signaled.sdp);
678 681 let target = spec.target();
@@ -735,6 +738,8 @@ async fn drive(
735 738 layout_plan = answered.remote.plan();
736 739 direct_video_mid = answered.camera_mid.clone();
737 740 timeline.record("setRemoteDescription", format!("offer applied, {} signaled line(s)", answered.remote.lines.len()));
741 timeline.record_sdp("remote offer", &teams_offer);
742 timeline.record_sdp("local answer", &answered.answer_sdp);
738 743 dump_sdp(options, "4-teams-answer.sdp", &answered.answer_sdp);
739 744 let acceptance_url = attached
740 745 .links
@@ -968,6 +973,7 @@ async fn drive(
968 973 MediaAction::AnswerOnNewPeer => {
969 974 match answer_on_new_peer(&factory, &grant, options, &track, &renegotiation.sdp).await {
970 975 Ok((session, answered)) => {
976 timeline.record_sdp("local answer", &answered.answer_sdp);
971 977 live.peers.push(session.peer.clone());
972 978 let sent = send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await;
973 979 next = Some(NextPeer { session, offered: None });
@@ -980,6 +986,7 @@ async fn drive(
980 986 let video_answer = if layout == Layout::OneToOne { AnswerVideo::Receive } else { AnswerVideo::Reject };
981 987 match answer_offer(&current.peer, None, &renegotiation.sdp, video_answer).await {
982 988 Ok(answered) => {
989 timeline.record_sdp("local answer", &answered.answer_sdp);
983 990 let sent = send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await;
984 991 let held = is_hold(&renegotiation.sdp).unwrap_or(false);
985 992 if held != remote_hold {
@@ -1326,6 +1333,7 @@ async fn drive(
1326 1333 Ok(()) if direct => {
1327 1334 match offer_same_peer(&current.peer, &layout_plan, layout, false, true, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
1328 1335 Ok((browser_offer, signaled)) => {
1336 timeline.record_sdp("local offer", &signaled.sdp);
1329 1337 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(true) });
1330 1338 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
1331 1339 }
@@ -1345,6 +1353,7 @@ async fn drive(
1345 1353 local_video.stop_camera();
1346 1354 match offer_same_peer(&current.peer, &layout_plan, layout, false, false, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
1347 1355 Ok((browser_offer, signaled)) => {
1356 timeline.record_sdp("local offer", &signaled.sdp);
1348 1357 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(false) });
1349 1358 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
1350 1359 }
@@ -1597,6 +1606,7 @@ async fn drive(
1597 1606 let camera = !hold && local_video.camera_on();
1598 1607 match offer_same_peer(&current.peer, &layout_plan, layout, hold, camera, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
1599 1608 Ok((browser_offer, signaled)) => {
1609 timeline.record_sdp("local offer", &signaled.sdp);
1600 1610 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Hold(hold) });
1601 1611 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
1602 1612 }
@@ -1698,6 +1708,17 @@ async fn drive(
1698 1708 {
1699 1709 control.send(CallUpdate::BlurTiming(average_ms));
1700 1710 }
1711 if ticks.is_multiple_of(HEALTH_EVERY_TICKS) {
1712 control.send(CallUpdate::Sample(StatsSample {
1713 audio_in_packets: snapshot.inbound_packets,
1714 audio_out_packets: snapshot.outbound_packets,
1715 audio_in_level: snapshot.audio_level,
1716 audio_out_level: snapshot.local_level,
1717 video: snapshot.video.clone(),
1718 share_in_packets: snapshot.share_inbound_packets,
1719 share_out_packets: snapshot.share_outbound_packets,
1720 }));
1721 }
1701 1722 if ticks.is_multiple_of(HEALTH_EVERY_TICKS)
1702 1723 && snapshot.selected_pair.is_some()
1703 1724 && let Some(sample) = health_sampler.sample(std::time::Instant::now(), snapshot.health)
@@ -1854,6 +1875,9 @@ async fn escalate(
1854 1875 {
1855 1876 Ok(pending) => {
1856 1877 timeline.record("escalation", "new peer connection, new offer sent");
1878 if let Some(media) = &pending.offered {
1879 timeline.record_sdp("local offer", &media.signaled.sdp);
1880 }
1857 1881 live.peers.push(pending.session.peer.clone());
1858 1882 Some(pending)
1859 1883 }
@@ -2408,6 +2432,12 @@ fn handle_callback(callback: &TrouterCallback, timeline: &Timeline) -> Result<Ca
2408 2432 _ => String::new(),
2409 2433 };
2410 2434 timeline.record(format!("Trouter {}", event.name()), detail);
2435 match &event {
2436 CallEvent::Acceptance(acceptance) => timeline.record_sdp("remote answer", &acceptance.sdp),
2437 CallEvent::MediaAnswer(answer) => timeline.record_sdp("remote answer", &answer.sdp),
2438 CallEvent::MediaRenegotiation(renegotiation) => timeline.record_sdp("remote offer", &renegotiation.sdp),
2439 _ => {}
2440 }
2411 2441 Ok(event)
2412 2442 }
2413 2443
@@ -2501,6 +2531,8 @@ struct StatsSnapshot {
2501 2531 local_level: f64,
2502 2532 echo_return_loss_enhancement: f64,
2503 2533 video: VideoReport,
2534 share_inbound_packets: u64,
2535 share_outbound_packets: u64,
2504 2536 dtls_state: String,
2505 2537 tls_version: String,
2506 2538 dtls_cipher: String,
@@ -2533,6 +2565,9 @@ async fn collect_stats(peer: &PeerConnection) -> StatsSnapshot {
2533 2565 }
2534 2566 RtcStats::InboundRtp(inbound) if inbound.stream.kind == "video" => {
2535 2567 snapshot.video.inbound_packets += inbound.received.packets_received;
2568 if is_share_mid(&inbound.inbound.mid) {
2569 snapshot.share_inbound_packets += inbound.received.packets_received;
2570 }
2536 2571 snapshot.video.inbound_frames_decoded += u64::from(inbound.inbound.frames_decoded);
2537 2572 snapshot.video.inbound_width = snapshot.video.inbound_width.max(inbound.inbound.frame_width);
2538 2573 snapshot.video.inbound_height = snapshot.video.inbound_height.max(inbound.inbound.frame_height);
@@ -2543,6 +2578,9 @@ async fn collect_stats(peer: &PeerConnection) -> StatsSnapshot {
2543 2578 }
2544 2579 RtcStats::OutboundRtp(outbound) if outbound.stream.kind == "video" => {
2545 2580 snapshot.video.outbound_packets += outbound.sent.packets_sent;
2581 if is_share_mid(&outbound.outbound.mid) {
2582 snapshot.share_outbound_packets += outbound.sent.packets_sent;
2583 }
2546 2584 snapshot.video.outbound_frames_encoded += u64::from(outbound.outbound.frames_encoded);
2547 2585 snapshot.video.outbound_width = snapshot.video.outbound_width.max(outbound.outbound.frame_width);
2548 2586 snapshot.video.outbound_height = snapshot.video.outbound_height.max(outbound.outbound.frame_height);
@@ -28,6 +28,7 @@ use crate::captions::{
28 parse_caption_message,
28 parse_caption_message,
29};
29};
30use crate::control::{CallCommand, CallControl, CallUpdate, Progress};
30use crate::control::{CallCommand, CallControl, CallUpdate, Progress};
31use crate::diagnostics::{CallDiagnostics, StatsSample};
31use crate::data_channel::Depacketizer;
32use crate::data_channel::Depacketizer;
32use crate::devices::{self, DeviceChoice};
33use crate::devices::{self, DeviceChoice};
33use crate::end::EndKind;
34use crate::end::EndKind;
@@ -55,7 +56,7 @@ use crate::timeline::{Timeline, TimelineEntry};
55use crate::transfer::{TransferEvent, TransferTarget};
56use crate::transfer::{TransferEvent, TransferTarget};
56use crate::video_frame::VideoKey;
57use crate::video_frame::VideoKey;
57use crate::video_layout::{
58use crate::video_layout::{
58 CAMERA_MID, MediaDescription, ONE_TO_ONE_SHARE_MID, SlotTable, VideoLines, VideoRouter, add_one_to_one_lines, add_video_lines, offer_plan, one_to_one_plan,
59 CAMERA_MID, MediaDescription, ONE_TO_ONE_SHARE_MID, SlotTable, VideoLines, VideoRouter, add_one_to_one_lines, add_video_lines, is_share_mid, offer_plan, one_to_one_plan,
59};
60};
60use crate::video_send::{LocalVideo, VideoMode};
61use crate::video_send::{LocalVideo, VideoMode};
61use crate::screen::{ShareKind, ShareSource, list_share_sources};
62use crate::screen::{ShareKind, ShareSource, list_share_sources};
@@ -396,10 +397,11 @@ impl CallEngine {
396 tear_down(live, inner, &timeline, &mut report, cancelled).await;
397 tear_down(live, inner, &timeline, &mut report, cancelled).await;
397 let recording = recording.lock().await;
398 let recording = recording.lock().await;
398 report.recorded_samples = recording.samples.len();
399 report.recorded_samples = recording.samples.len();
400 report.timeline = timeline.entries();
401 control.send(CallUpdate::Diagnostics(Box::new(CallDiagnostics::new(&report, timeline.sdp_summaries()))));
399 if let Some(path) = &options.wav_path {
402 if let Some(path) = &options.wav_path {
400 write_wav(path, &recording.samples).map_err(|error| Error::Webrtc(format!("wav: {error}")))?;
403 write_wav(path, &recording.samples).map_err(|error| Error::Webrtc(format!("wav: {error}")))?;
401 }
404 }
402 report.timeline = timeline.entries();
403 match failure {
405 match failure {
404 Some(error) => Err(error),
406 Some(error) => Err(error),
405 None => Ok(report),
407 None => Ok(report),
@@ -673,6 +675,7 @@ async fn drive(
673 direct_video_mid = Some(CAMERA_MID.to_owned());
675 direct_video_mid = Some(CAMERA_MID.to_owned());
674 }
676 }
675 timeline.record("setLocalDescription", format!("{} m-line(s) signaled", media.signaled.lines.len()));
677 timeline.record("setLocalDescription", format!("{} m-line(s) signaled", media.signaled.lines.len()));
678 timeline.record_sdp("local offer", &media.signaled.sdp);
676 dump_sdp(options, "1-browser-offer.sdp", &media.browser_offer);
679 dump_sdp(options, "1-browser-offer.sdp", &media.browser_offer);
677 dump_sdp(options, "2-teams-offer.sdp", &media.signaled.sdp);
680 dump_sdp(options, "2-teams-offer.sdp", &media.signaled.sdp);
678 let target = spec.target();
681 let target = spec.target();
@@ -735,6 +738,8 @@ async fn drive(
735 layout_plan = answered.remote.plan();
738 layout_plan = answered.remote.plan();
736 direct_video_mid = answered.camera_mid.clone();
739 direct_video_mid = answered.camera_mid.clone();
737 timeline.record("setRemoteDescription", format!("offer applied, {} signaled line(s)", answered.remote.lines.len()));
740 timeline.record("setRemoteDescription", format!("offer applied, {} signaled line(s)", answered.remote.lines.len()));
741 timeline.record_sdp("remote offer", &teams_offer);
742 timeline.record_sdp("local answer", &answered.answer_sdp);
738 dump_sdp(options, "4-teams-answer.sdp", &answered.answer_sdp);
743 dump_sdp(options, "4-teams-answer.sdp", &answered.answer_sdp);
739 let acceptance_url = attached
744 let acceptance_url = attached
740 .links
745 .links
@@ -968,6 +973,7 @@ async fn drive(
968 MediaAction::AnswerOnNewPeer => {
973 MediaAction::AnswerOnNewPeer => {
969 match answer_on_new_peer(&factory, &grant, options, &track, &renegotiation.sdp).await {
974 match answer_on_new_peer(&factory, &grant, options, &track, &renegotiation.sdp).await {
970 Ok((session, answered)) => {
975 Ok((session, answered)) => {
976 timeline.record_sdp("local answer", &answered.answer_sdp);
971 live.peers.push(session.peer.clone());
977 live.peers.push(session.peer.clone());
972 let sent = send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await;
978 let sent = send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await;
973 next = Some(NextPeer { session, offered: None });
979 next = Some(NextPeer { session, offered: None });
@@ -980,6 +986,7 @@ async fn drive(
980 let video_answer = if layout == Layout::OneToOne { AnswerVideo::Receive } else { AnswerVideo::Reject };
986 let video_answer = if layout == Layout::OneToOne { AnswerVideo::Receive } else { AnswerVideo::Reject };
981 match answer_offer(&current.peer, None, &renegotiation.sdp, video_answer).await {
987 match answer_offer(&current.peer, None, &renegotiation.sdp, video_answer).await {
982 Ok(answered) => {
988 Ok(answered) => {
989 timeline.record_sdp("local answer", &answered.answer_sdp);
983 let sent = send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await;
990 let sent = send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await;
984 let held = is_hold(&renegotiation.sdp).unwrap_or(false);
991 let held = is_hold(&renegotiation.sdp).unwrap_or(false);
985 if held != remote_hold {
992 if held != remote_hold {
@@ -1326,6 +1333,7 @@ async fn drive(
1326 Ok(()) if direct => {
1333 Ok(()) if direct => {
1327 match offer_same_peer(&current.peer, &layout_plan, layout, false, true, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
1334 match offer_same_peer(&current.peer, &layout_plan, layout, false, true, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
1328 Ok((browser_offer, signaled)) => {
1335 Ok((browser_offer, signaled)) => {
1336 timeline.record_sdp("local offer", &signaled.sdp);
1329 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(true) });
1337 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(true) });
1330 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
1338 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
1331 }
1339 }
@@ -1345,6 +1353,7 @@ async fn drive(
1345 local_video.stop_camera();
1353 local_video.stop_camera();
1346 match offer_same_peer(&current.peer, &layout_plan, layout, false, false, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
1354 match offer_same_peer(&current.peer, &layout_plan, layout, false, false, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
1347 Ok((browser_offer, signaled)) => {
1355 Ok((browser_offer, signaled)) => {
1356 timeline.record_sdp("local offer", &signaled.sdp);
1348 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(false) });
1357 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(false) });
1349 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
1358 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
1350 }
1359 }
@@ -1597,6 +1606,7 @@ async fn drive(
1597 let camera = !hold && local_video.camera_on();
1606 let camera = !hold && local_video.camera_on();
1598 match offer_same_peer(&current.peer, &layout_plan, layout, hold, camera, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
1607 match offer_same_peer(&current.peer, &layout_plan, layout, hold, camera, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
1599 Ok((browser_offer, signaled)) => {
1608 Ok((browser_offer, signaled)) => {
1609 timeline.record_sdp("local offer", &signaled.sdp);
1600 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Hold(hold) });
1610 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Hold(hold) });
1601 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
1611 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
1602 }
1612 }
@@ -1698,6 +1708,17 @@ async fn drive(
1698 {
1708 {
1699 control.send(CallUpdate::BlurTiming(average_ms));
1709 control.send(CallUpdate::BlurTiming(average_ms));
1700 }
1710 }
1711 if ticks.is_multiple_of(HEALTH_EVERY_TICKS) {
1712 control.send(CallUpdate::Sample(StatsSample {
1713 audio_in_packets: snapshot.inbound_packets,
1714 audio_out_packets: snapshot.outbound_packets,
1715 audio_in_level: snapshot.audio_level,
1716 audio_out_level: snapshot.local_level,
1717 video: snapshot.video.clone(),
1718 share_in_packets: snapshot.share_inbound_packets,
1719 share_out_packets: snapshot.share_outbound_packets,
1720 }));
1721 }
1701 if ticks.is_multiple_of(HEALTH_EVERY_TICKS)
1722 if ticks.is_multiple_of(HEALTH_EVERY_TICKS)
1702 && snapshot.selected_pair.is_some()
1723 && snapshot.selected_pair.is_some()
1703 && let Some(sample) = health_sampler.sample(std::time::Instant::now(), snapshot.health)
1724 && let Some(sample) = health_sampler.sample(std::time::Instant::now(), snapshot.health)
@@ -1854,6 +1875,9 @@ async fn escalate(
1854 {
1875 {
1855 Ok(pending) => {
1876 Ok(pending) => {
1856 timeline.record("escalation", "new peer connection, new offer sent");
1877 timeline.record("escalation", "new peer connection, new offer sent");
1878 if let Some(media) = &pending.offered {
1879 timeline.record_sdp("local offer", &media.signaled.sdp);
1880 }
1857 live.peers.push(pending.session.peer.clone());
1881 live.peers.push(pending.session.peer.clone());
1858 Some(pending)
1882 Some(pending)
1859 }
1883 }
@@ -2408,6 +2432,12 @@ fn handle_callback(callback: &TrouterCallback, timeline: &Timeline) -> Result<Ca
2408 _ => String::new(),
2432 _ => String::new(),
2409 };
2433 };
2410 timeline.record(format!("Trouter {}", event.name()), detail);
2434 timeline.record(format!("Trouter {}", event.name()), detail);
2435 match &event {
2436 CallEvent::Acceptance(acceptance) => timeline.record_sdp("remote answer", &acceptance.sdp),
2437 CallEvent::MediaAnswer(answer) => timeline.record_sdp("remote answer", &answer.sdp),
2438 CallEvent::MediaRenegotiation(renegotiation) => timeline.record_sdp("remote offer", &renegotiation.sdp),
2439 _ => {}
2440 }
2411 Ok(event)
2441 Ok(event)
2412}
2442}
2413
2443
@@ -2501,6 +2531,8 @@ struct StatsSnapshot {
2501 local_level: f64,
2531 local_level: f64,
2502 echo_return_loss_enhancement: f64,
2532 echo_return_loss_enhancement: f64,
2503 video: VideoReport,
2533 video: VideoReport,
2534 share_inbound_packets: u64,
2535 share_outbound_packets: u64,
2504 dtls_state: String,
2536 dtls_state: String,
2505 tls_version: String,
2537 tls_version: String,
2506 dtls_cipher: String,
2538 dtls_cipher: String,
@@ -2533,6 +2565,9 @@ async fn collect_stats(peer: &PeerConnection) -> StatsSnapshot {
2533 }
2565 }
2534 RtcStats::InboundRtp(inbound) if inbound.stream.kind == "video" => {
2566 RtcStats::InboundRtp(inbound) if inbound.stream.kind == "video" => {
2535 snapshot.video.inbound_packets += inbound.received.packets_received;
2567 snapshot.video.inbound_packets += inbound.received.packets_received;
2568 if is_share_mid(&inbound.inbound.mid) {
2569 snapshot.share_inbound_packets += inbound.received.packets_received;
2570 }
2536 snapshot.video.inbound_frames_decoded += u64::from(inbound.inbound.frames_decoded);
2571 snapshot.video.inbound_frames_decoded += u64::from(inbound.inbound.frames_decoded);
2537 snapshot.video.inbound_width = snapshot.video.inbound_width.max(inbound.inbound.frame_width);
2572 snapshot.video.inbound_width = snapshot.video.inbound_width.max(inbound.inbound.frame_width);
2538 snapshot.video.inbound_height = snapshot.video.inbound_height.max(inbound.inbound.frame_height);
2573 snapshot.video.inbound_height = snapshot.video.inbound_height.max(inbound.inbound.frame_height);
@@ -2543,6 +2578,9 @@ async fn collect_stats(peer: &PeerConnection) -> StatsSnapshot {
2543 }
2578 }
2544 RtcStats::OutboundRtp(outbound) if outbound.stream.kind == "video" => {
2579 RtcStats::OutboundRtp(outbound) if outbound.stream.kind == "video" => {
2545 snapshot.video.outbound_packets += outbound.sent.packets_sent;
2580 snapshot.video.outbound_packets += outbound.sent.packets_sent;
2581 if is_share_mid(&outbound.outbound.mid) {
2582 snapshot.share_outbound_packets += outbound.sent.packets_sent;
2583 }
2546 snapshot.video.outbound_frames_encoded += u64::from(outbound.outbound.frames_encoded);
2584 snapshot.video.outbound_frames_encoded += u64::from(outbound.outbound.frames_encoded);
2547 snapshot.video.outbound_width = snapshot.video.outbound_width.max(outbound.outbound.frame_width);
2585 snapshot.video.outbound_width = snapshot.video.outbound_width.max(outbound.outbound.frame_width);
2548 snapshot.video.outbound_height = snapshot.video.outbound_height.max(outbound.outbound.frame_height);
2586 snapshot.video.outbound_height = snapshot.video.outbound_height.max(outbound.outbound.frame_height);
crates/calling/src/control.rs +3 −0
@@ -9,6 +9,7 @@ use crate::breakout::BreakoutMove;
9 9 use crate::captions::{CaptionEntry, CaptionState};
10 10 use crate::recording::{RecordingKind, StopScope};
11 11 use crate::devices::{DeviceChoice, DeviceLists};
12 use crate::diagnostics::{CallDiagnostics, StatsSample};
12 13 use crate::error::{Error, Result};
13 14 use crate::health::CallHealth;
14 15 use crate::hold::HoldState;
@@ -92,6 +93,8 @@ pub enum CallUpdate {
92 93 Selected { input: DeviceChoice, output: DeviceChoice },
93 94 ListenOnly(bool),
94 95 Stats { inbound_packets: u64, outbound_packets: u64 },
96 Sample(StatsSample),
97 Diagnostics(Box<CallDiagnostics>),
95 98 Progress(Progress),
96 99 Roster(Vec<RosterEntry>),
97 100 Speakers(Vec<String>),
@@ -9,6 +9,7 @@ use crate::breakout::BreakoutMove;
9use crate::captions::{CaptionEntry, CaptionState};
9use crate::captions::{CaptionEntry, CaptionState};
10use crate::recording::{RecordingKind, StopScope};
10use crate::recording::{RecordingKind, StopScope};
11use crate::devices::{DeviceChoice, DeviceLists};
11use crate::devices::{DeviceChoice, DeviceLists};
12use crate::diagnostics::{CallDiagnostics, StatsSample};
12use crate::error::{Error, Result};
13use crate::error::{Error, Result};
13use crate::health::CallHealth;
14use crate::health::CallHealth;
14use crate::hold::HoldState;
15use crate::hold::HoldState;
@@ -92,6 +93,8 @@ pub enum CallUpdate {
92 Selected { input: DeviceChoice, output: DeviceChoice },
93 Selected { input: DeviceChoice, output: DeviceChoice },
93 ListenOnly(bool),
94 ListenOnly(bool),
94 Stats { inbound_packets: u64, outbound_packets: u64 },
95 Stats { inbound_packets: u64, outbound_packets: u64 },
96 Sample(StatsSample),
97 Diagnostics(Box<CallDiagnostics>),
95 Progress(Progress),
98 Progress(Progress),
96 Roster(Vec<RosterEntry>),
99 Roster(Vec<RosterEntry>),
97 Speakers(Vec<String>),
100 Speakers(Vec<String>),
crates/calling/src/diagnostics.rs added +126 −0
@@ -0,0 +1,126 @@
1 use crate::call::{CallReport, VideoReport};
2 use crate::sdp;
3 use crate::timeline::TimelineEntry;
4
5 const RTX_CODEC: &str = "rtx";
6
7 #[derive(Debug, Clone, PartialEq)]
8 pub struct SdpLine {
9 pub kind: String,
10 pub mid: String,
11 pub direction: String,
12 pub codecs: Vec<String>,
13 pub payload_count: usize,
14 pub ssrc_count: usize,
15 pub rejected: bool,
16 }
17
18 #[derive(Debug, Clone, PartialEq)]
19 pub struct SdpSummary {
20 pub at_ms: u128,
21 pub role: String,
22 pub lines: Vec<SdpLine>,
23 }
24
25 #[derive(Debug, Clone, Default, PartialEq)]
26 pub struct StatsSample {
27 pub audio_in_packets: u64,
28 pub audio_out_packets: u64,
29 pub audio_in_level: f64,
30 pub audio_out_level: f64,
31 pub video: VideoReport,
32 pub share_in_packets: u64,
33 pub share_out_packets: u64,
34 }
35
36 #[derive(Debug, Clone, Default, PartialEq)]
37 pub struct CallDiagnostics {
38 pub timeline: Vec<TimelineEntry>,
39 pub sdp: Vec<SdpSummary>,
40 pub ice_connected_ms: Option<u128>,
41 pub peer_connected_ms: Option<u128>,
42 pub selected_pair: Option<String>,
43 pub tls_version: String,
44 pub dtls_cipher: String,
45 pub srtp_cipher: String,
46 }
47
48 impl CallDiagnostics {
49 pub fn new(report: &CallReport, sdp: Vec<SdpSummary>) -> Self {
50 CallDiagnostics {
51 timeline: report.timeline.clone(),
52 sdp,
53 ice_connected_ms: report.ice_connected_ms,
54 peer_connected_ms: report.peer_connected_ms,
55 selected_pair: report.selected_pair.clone(),
56 tls_version: report.tls_version.clone(),
57 dtls_cipher: report.dtls_cipher.clone(),
58 srtp_cipher: report.srtp_cipher.clone(),
59 }
60 }
61 }
62
63 pub fn summarize_sdp(at_ms: u128, role: &str, text: &str) -> Option<SdpSummary> {
64 let description = sdp::parse(text).ok()?;
65 let lines = description
66 .media
67 .iter()
68 .map(|media| {
69 let named: Vec<String> = media
70 .values("rtpmap")
71 .filter_map(|value| value.split_once(' '))
72 .filter_map(|(_, encoding)| encoding.split('/').next())
73 .filter(|name| !name.eq_ignore_ascii_case(RTX_CODEC))
74 .map(str::to_owned)
75 .collect();
76 let mut codecs: Vec<String> = Vec::new();
77 for codec in named {
78 if !codecs.contains(&codec) {
79 codecs.push(codec);
80 }
81 }
82 SdpLine {
83 kind: media.kind.clone(),
84 mid: media.mid().unwrap_or_default().to_owned(),
85 direction: media.direction().unwrap_or("sendrecv").to_owned(),
86 codecs,
87 payload_count: media.formats.len(),
88 ssrc_count: media.values("ssrc").filter(|value| value.contains(" cname:")).count(),
89 rejected: media.port == "0",
90 }
91 })
92 .collect();
93 Some(SdpSummary { at_ms, role: role.to_owned(), lines })
94 }
95
96 #[cfg(test)]
97 mod tests {
98 use super::*;
99
100 const OFFER: &str = "v=0\r\no=- 1 2 IN IP4 203.0.113.9\r\ns=-\r\nt=0 0\r\n\
101 m=audio 9 UDP/TLS/RTP/SAVPF 111 9\r\nc=IN IP4 203.0.113.9\r\na=mid:0\r\na=sendrecv\r\na=ice-ufrag:abcd\r\na=ice-pwd:secretsecretsecret\r\n\
102 a=rtpmap:111 opus/48000/2\r\na=rtpmap:9 G722/8000\r\na=ssrc:111 cname:xyz\r\n\
103 m=video 0 UDP/TLS/RTP/SAVPF 96 97\r\na=mid:1\r\na=inactive\r\na=rtpmap:96 H264/90000\r\na=rtpmap:97 rtx/90000\r\n";
104
105 #[test]
106 fn a_summary_keeps_kinds_mids_directions_codecs_and_counts_only() {
107 let summary = summarize_sdp(40, "local offer", OFFER).expect("parses");
108 assert_eq!(summary.lines.len(), 2);
109 assert_eq!(summary.lines[0].kind, "audio");
110 assert_eq!(summary.lines[0].mid, "0");
111 assert_eq!(summary.lines[0].direction, "sendrecv");
112 assert_eq!(summary.lines[0].codecs, ["opus", "G722"]);
113 assert_eq!(summary.lines[0].payload_count, 2);
114 assert_eq!(summary.lines[0].ssrc_count, 1);
115 assert_eq!(summary.lines[1].direction, "inactive");
116 assert_eq!(summary.lines[1].codecs, ["H264"]);
117 assert!(summary.lines[1].rejected);
118 let rendered = format!("{summary:?}");
119 assert!(!rendered.contains("203.0.113.9") && !rendered.contains("secretsecret") && !rendered.contains("abcd"));
120 }
121
122 #[test]
123 fn text_that_is_no_sdp_gives_no_summary() {
124 assert!(summarize_sdp(0, "remote offer", "not sdp").is_none());
125 }
126 }
@@ -0,0 +1,126 @@
1use crate::call::{CallReport, VideoReport};
2use crate::sdp;
3use crate::timeline::TimelineEntry;
4
5const RTX_CODEC: &str = "rtx";
6
7#[derive(Debug, Clone, PartialEq)]
8pub struct SdpLine {
9 pub kind: String,
10 pub mid: String,
11 pub direction: String,
12 pub codecs: Vec<String>,
13 pub payload_count: usize,
14 pub ssrc_count: usize,
15 pub rejected: bool,
16}
17
18#[derive(Debug, Clone, PartialEq)]
19pub struct SdpSummary {
20 pub at_ms: u128,
21 pub role: String,
22 pub lines: Vec<SdpLine>,
23}
24
25#[derive(Debug, Clone, Default, PartialEq)]
26pub struct StatsSample {
27 pub audio_in_packets: u64,
28 pub audio_out_packets: u64,
29 pub audio_in_level: f64,
30 pub audio_out_level: f64,
31 pub video: VideoReport,
32 pub share_in_packets: u64,
33 pub share_out_packets: u64,
34}
35
36#[derive(Debug, Clone, Default, PartialEq)]
37pub struct CallDiagnostics {
38 pub timeline: Vec<TimelineEntry>,
39 pub sdp: Vec<SdpSummary>,
40 pub ice_connected_ms: Option<u128>,
41 pub peer_connected_ms: Option<u128>,
42 pub selected_pair: Option<String>,
43 pub tls_version: String,
44 pub dtls_cipher: String,
45 pub srtp_cipher: String,
46}
47
48impl CallDiagnostics {
49 pub fn new(report: &CallReport, sdp: Vec<SdpSummary>) -> Self {
50 CallDiagnostics {
51 timeline: report.timeline.clone(),
52 sdp,
53 ice_connected_ms: report.ice_connected_ms,
54 peer_connected_ms: report.peer_connected_ms,
55 selected_pair: report.selected_pair.clone(),
56 tls_version: report.tls_version.clone(),
57 dtls_cipher: report.dtls_cipher.clone(),
58 srtp_cipher: report.srtp_cipher.clone(),
59 }
60 }
61}
62
63pub fn summarize_sdp(at_ms: u128, role: &str, text: &str) -> Option<SdpSummary> {
64 let description = sdp::parse(text).ok()?;
65 let lines = description
66 .media
67 .iter()
68 .map(|media| {
69 let named: Vec<String> = media
70 .values("rtpmap")
71 .filter_map(|value| value.split_once(' '))
72 .filter_map(|(_, encoding)| encoding.split('/').next())
73 .filter(|name| !name.eq_ignore_ascii_case(RTX_CODEC))
74 .map(str::to_owned)
75 .collect();
76 let mut codecs: Vec<String> = Vec::new();
77 for codec in named {
78 if !codecs.contains(&codec) {
79 codecs.push(codec);
80 }
81 }
82 SdpLine {
83 kind: media.kind.clone(),
84 mid: media.mid().unwrap_or_default().to_owned(),
85 direction: media.direction().unwrap_or("sendrecv").to_owned(),
86 codecs,
87 payload_count: media.formats.len(),
88 ssrc_count: media.values("ssrc").filter(|value| value.contains(" cname:")).count(),
89 rejected: media.port == "0",
90 }
91 })
92 .collect();
93 Some(SdpSummary { at_ms, role: role.to_owned(), lines })
94}
95
96#[cfg(test)]
97mod tests {
98 use super::*;
99
100 const OFFER: &str = "v=0\r\no=- 1 2 IN IP4 203.0.113.9\r\ns=-\r\nt=0 0\r\n\
101m=audio 9 UDP/TLS/RTP/SAVPF 111 9\r\nc=IN IP4 203.0.113.9\r\na=mid:0\r\na=sendrecv\r\na=ice-ufrag:abcd\r\na=ice-pwd:secretsecretsecret\r\n\
102a=rtpmap:111 opus/48000/2\r\na=rtpmap:9 G722/8000\r\na=ssrc:111 cname:xyz\r\n\
103m=video 0 UDP/TLS/RTP/SAVPF 96 97\r\na=mid:1\r\na=inactive\r\na=rtpmap:96 H264/90000\r\na=rtpmap:97 rtx/90000\r\n";
104
105 #[test]
106 fn a_summary_keeps_kinds_mids_directions_codecs_and_counts_only() {
107 let summary = summarize_sdp(40, "local offer", OFFER).expect("parses");
108 assert_eq!(summary.lines.len(), 2);
109 assert_eq!(summary.lines[0].kind, "audio");
110 assert_eq!(summary.lines[0].mid, "0");
111 assert_eq!(summary.lines[0].direction, "sendrecv");
112 assert_eq!(summary.lines[0].codecs, ["opus", "G722"]);
113 assert_eq!(summary.lines[0].payload_count, 2);
114 assert_eq!(summary.lines[0].ssrc_count, 1);
115 assert_eq!(summary.lines[1].direction, "inactive");
116 assert_eq!(summary.lines[1].codecs, ["H264"]);
117 assert!(summary.lines[1].rejected);
118 let rendered = format!("{summary:?}");
119 assert!(!rendered.contains("203.0.113.9") && !rendered.contains("secretsecret") && !rendered.contains("abcd"));
120 }
121
122 #[test]
123 fn text_that_is_no_sdp_gives_no_summary() {
124 assert!(summarize_sdp(0, "remote offer", "not sdp").is_none());
125 }
126}
crates/calling/src/lib.rs +2 −0
@@ -11,6 +11,7 @@ pub mod capture;
11 11 pub mod control;
12 12 pub mod data_channel;
13 13 pub mod devices;
14 pub mod diagnostics;
14 15 pub mod engine;
15 16 pub mod effects;
16 17 pub mod end;
@@ -76,6 +77,7 @@ pub use roster::{AttendeeLimits, MeetingRole, PublishedState, RaisedHand, Roster
76 77 pub use sound_capture::LoopbackKind;
77 78 pub use renegotiation::MediaPath;
78 79 pub use signaling::{Callee, MeetingTarget};
80 pub use diagnostics::{CallDiagnostics, SdpLine, SdpSummary, StatsSample};
79 81 pub use devices::{AudioDevice, DeviceChoice, DeviceEntry, DeviceLists};
80 82 pub use error::{Error, Result};
81 83 pub use level::SpeakingDetector;
@@ -11,6 +11,7 @@ pub mod capture;
11pub mod control;
11pub mod control;
12pub mod data_channel;
12pub mod data_channel;
13pub mod devices;
13pub mod devices;
14pub mod diagnostics;
14pub mod engine;
15pub mod engine;
15pub mod effects;
16pub mod effects;
16pub mod end;
17pub mod end;
@@ -76,6 +77,7 @@ pub use roster::{AttendeeLimits, MeetingRole, PublishedState, RaisedHand, Roster
76pub use sound_capture::LoopbackKind;
77pub use sound_capture::LoopbackKind;
77pub use renegotiation::MediaPath;
78pub use renegotiation::MediaPath;
78pub use signaling::{Callee, MeetingTarget};
79pub use signaling::{Callee, MeetingTarget};
80pub use diagnostics::{CallDiagnostics, SdpLine, SdpSummary, StatsSample};
79pub use devices::{AudioDevice, DeviceChoice, DeviceEntry, DeviceLists};
81pub use devices::{AudioDevice, DeviceChoice, DeviceEntry, DeviceLists};
80pub use error::{Error, Result};
82pub use error::{Error, Result};
81pub use level::SpeakingDetector;
83pub use level::SpeakingDetector;
crates/calling/src/timeline.rs +15 −1
@@ -1,7 +1,9 @@
1 1 use std::sync::{Arc, Mutex};
2 2 use std::time::Instant;
3 3
4 #[derive(Debug, Clone)]
4 use crate::diagnostics::{SdpSummary, summarize_sdp};
5
6 #[derive(Debug, Clone, PartialEq)]
5 7 pub struct TimelineEntry {
6 8 pub elapsed_ms: u128,
7 9 pub label: String,
@@ -12,6 +14,7 @@ pub struct TimelineEntry {
12 14 pub struct Timeline {
13 15 started: Instant,
14 16 entries: Arc<Mutex<Vec<TimelineEntry>>>,
17 sdp: Arc<Mutex<Vec<SdpSummary>>>,
15 18 echo: bool,
16 19 }
17 20
@@ -20,6 +23,7 @@ impl Timeline {
20 23 Timeline {
21 24 started: Instant::now(),
22 25 entries: Arc::default(),
26 sdp: Arc::default(),
23 27 echo,
24 28 }
25 29 }
@@ -40,6 +44,16 @@ impl Timeline {
40 44 self.entries.lock().expect("timeline lock").push(entry);
41 45 }
42 46
47 pub fn record_sdp(&self, role: &str, sdp: &str) {
48 if let Some(summary) = summarize_sdp(self.elapsed_ms(), role, sdp) {
49 self.sdp.lock().expect("timeline lock").push(summary);
50 }
51 }
52
53 pub fn sdp_summaries(&self) -> Vec<SdpSummary> {
54 self.sdp.lock().expect("timeline lock").clone()
55 }
56
43 57 pub fn entries(&self) -> Vec<TimelineEntry> {
44 58 self.entries.lock().expect("timeline lock").clone()
45 59 }
@@ -1,7 +1,9 @@
1use std::sync::{Arc, Mutex};
1use std::sync::{Arc, Mutex};
2use std::time::Instant;
2use std::time::Instant;
3
3
4#[derive(Debug, Clone)]
4use crate::diagnostics::{SdpSummary, summarize_sdp};
5
6#[derive(Debug, Clone, PartialEq)]
5pub struct TimelineEntry {
7pub struct TimelineEntry {
6 pub elapsed_ms: u128,
8 pub elapsed_ms: u128,
7 pub label: String,
9 pub label: String,
@@ -12,6 +14,7 @@ pub struct TimelineEntry {
12pub struct Timeline {
14pub struct Timeline {
13 started: Instant,
15 started: Instant,
14 entries: Arc<Mutex<Vec<TimelineEntry>>>,
16 entries: Arc<Mutex<Vec<TimelineEntry>>>,
17 sdp: Arc<Mutex<Vec<SdpSummary>>>,
15 echo: bool,
18 echo: bool,
16}
19}
17
20
@@ -20,6 +23,7 @@ impl Timeline {
20 Timeline {
23 Timeline {
21 started: Instant::now(),
24 started: Instant::now(),
22 entries: Arc::default(),
25 entries: Arc::default(),
26 sdp: Arc::default(),
23 echo,
27 echo,
24 }
28 }
25 }
29 }
@@ -40,6 +44,16 @@ impl Timeline {
40 self.entries.lock().expect("timeline lock").push(entry);
44 self.entries.lock().expect("timeline lock").push(entry);
41 }
45 }
42
46
47 pub fn record_sdp(&self, role: &str, sdp: &str) {
48 if let Some(summary) = summarize_sdp(self.elapsed_ms(), role, sdp) {
49 self.sdp.lock().expect("timeline lock").push(summary);
50 }
51 }
52
53 pub fn sdp_summaries(&self) -> Vec<SdpSummary> {
54 self.sdp.lock().expect("timeline lock").clone()
55 }
56
43 pub fn entries(&self) -> Vec<TimelineEntry> {
57 pub fn entries(&self) -> Vec<TimelineEntry> {
44 self.entries.lock().expect("timeline lock").clone()
58 self.entries.lock().expect("timeline lock").clone()
45 }
59 }
crates/calling/src/video_layout.rs +4 −0
@@ -16,6 +16,10 @@ pub const RECEIVE_SLOTS: usize = 9;
16 16 pub const CAMERA_MID: &str = "1";
17 17 pub const SHARE_MID: &str = "11";
18 18 pub const ONE_TO_ONE_SHARE_MID: &str = "2";
19
20 pub fn is_share_mid(mid: &str) -> bool {
21 mid == SHARE_MID || mid == ONE_TO_ONE_SHARE_MID
22 }
19 23 const CAMERA_LINE_LABEL: &str = "main-video";
20 24 const SHARE_LINE_LABEL: &str = "applicationsharing-video";
21 25 const CAMERA_STREAM: &str = "camera";
@@ -16,6 +16,10 @@ pub const RECEIVE_SLOTS: usize = 9;
16pub const CAMERA_MID: &str = "1";
16pub const CAMERA_MID: &str = "1";
17pub const SHARE_MID: &str = "11";
17pub const SHARE_MID: &str = "11";
18pub const ONE_TO_ONE_SHARE_MID: &str = "2";
18pub const ONE_TO_ONE_SHARE_MID: &str = "2";
19
20pub fn is_share_mid(mid: &str) -> bool {
21 mid == SHARE_MID || mid == ONE_TO_ONE_SHARE_MID
22}
19const CAMERA_LINE_LABEL: &str = "main-video";
23const CAMERA_LINE_LABEL: &str = "main-video";
20const SHARE_LINE_LABEL: &str = "applicationsharing-video";
24const SHARE_LINE_LABEL: &str = "applicationsharing-video";
21const CAMERA_STREAM: &str = "camera";
25const CAMERA_STREAM: &str = "camera";