diff --git a/crates/call-protocol/AGENTS.md b/crates/call-protocol/AGENTS.md index e270e70f..76ace3e7 100644 --- a/crates/call-protocol/AGENTS.md +++ b/crates/call-protocol/AGENTS.md @@ -16,6 +16,7 @@ This crate defines the bounded binary messages between the key-holding core and - Devices and levels (ADR-0059): wire version 10 added `ToWorker::TestDevice { test, device }` (a first message only, like `ListDevices`; `DeviceTest` is a closed set), `ToWorker::SetDevices { recording, playout, camera }` (the camera choice applies from the next camera start; `DevicesSet` answers for the microphone and speaker only), `FromWorker::ParticipantLevel { connection, identity, level }`, `FromWorker::ParticipantMuted { connection, identity, muted }` and `FromWorker::DevicesSet { failure }` (0 for none, else a `FailureCode`). `SoundLevel` is now the own microphone's level. - Microphone settings (ADR-0062): wire version 11 added `ToWorker::SetMicrophone { auto_level, mic_gain }` (tag 16, no answer), and `Join` ends with `auto_level` and `mic_gain` (two bytes). `Reader::mic_gain` refuses a gain over `MAX_MIC_GAIN_PERCENT` (400) or off the step of `MIC_GAIN_STEP_PERCENT` (5); use `valid_mic_gain` wherever a gain is used. - Screen targets (ADR-0053 amendment of 25 November 2026, ADR-0064): wire version 12 changed `SetScreen`'s `ScreenTarget::Monitor` (tag 2) from a list index to the Windows GDI device name (`MonitorName`: a length byte, then 1 to `MAX_MONITOR_NAME` (32) printable ASCII bytes other than space: 0x21 to 0x7E, `u8::is_ascii_graphic`; a name with a space is an invalid value), the width and height, and the monitor's rectangle (`DesktopRect`: four big-endian `i32` edges, each side 1 to `MAX_MONITOR_SIDE`, each edge within `MAX_DESKTOP_COORDINATE` of 0), and added `ScreenTarget::Display { id, width, height }` (tag 3, the macOS CoreGraphics display ID, never 0). `Reader::monitor_size` refuses a side outside 1 to `MAX_MONITOR_SIDE`. Tag 1 (`Portal { node }`) is unchanged. +- Call statistics (ADR-0066): wire version 13 added `ToWorker::SetStats { on }` (tag 17) and `FromWorker::Stats(CallStats)` (`src/stats.rs`). The message is closed and numeric: integers with a unit and a bound that the reader checks (`MAX_STATS_*`), `Option` for a value that is not known yet, at most `MAX_PARTICIPANTS` remote entries and `MAX_STATS_CONNECTIONS` connection entries, each participant (connection and identity) and each connection at most once. It carries no address, port, candidate type, SSRC, codec or other text beyond the already validated identities. The writer cuts each list to its limit and writes every entry as given; the caller (`mapping::stats` in the worker) leaves out an entry that the reader would refuse and clamps the numbers, because the reader refuses the whole message for one such entry. Tag 16 and wire version 11 are the microphone settings above (ADR-0062). The next wire change takes tag 18 and the next free version. The `MAX_STATS_*` bounds are repeated as `CALL_STATS_*` in `crates/contracts`; `crates/core/src/calls/stats.rs` checks at compile time that they match. - Coordinate wire changes with `crates/core` and `crates/call-worker` (planned), and bump the version byte. ## Checks diff --git a/crates/call-protocol/src/lib.rs b/crates/call-protocol/src/lib.rs index 1c74c123..28e703c6 100644 --- a/crates/call-protocol/src/lib.rs +++ b/crates/call-protocol/src/lib.rs @@ -12,7 +12,14 @@ use persephone_media_protocol::{ }; use zeroize::Zeroizing; -pub const VERSION: u8 = 12; +mod stats; +pub use stats::{ + AudioReceiveStats, AudioSendStats, CallStats, ConnectionStats, MAX_STATS_CONNECTIONS, + MAX_STATS_FPS, MAX_STATS_KBPS, MAX_STATS_MS, MAX_STATS_SIDE, QualityLimit, RemoteStats, + VideoReceiveStats, VideoSendStats, +}; + +pub const VERSION: u8 = 13; pub const MAX_MESSAGE_BYTES: usize = 64 * 1024; /// Longest diagnostic record target (ADR-0058). pub const MAX_DIAGNOSTIC_TARGET_BYTES: usize = 64; @@ -392,6 +399,11 @@ pub enum ToWorker { playout: Option, camera: Option, }, + /// Start or stop sending [`FromWorker::Stats`], at most one a second + /// (ADR-0066). Off when the worker starts. No answer. + SetStats { + on: bool, + }, } /// The device that [`ToWorker::TestDevice`] tests. A closed set. @@ -512,6 +524,7 @@ impl std::fmt::Debug for ToWorker { .field("recording", recording) .field("playout", playout) .finish(), + Self::SetStats { on } => f.debug_struct("SetStats").field("on", on).finish(), } } } @@ -872,6 +885,11 @@ pub enum FromWorker { target: String, message: String, }, + /// The call's statistics, as numbers with units (ADR-0066). Sent at + /// most once a second, and only while [`ToWorker::SetStats`] is on. The + /// off drops a reading that waits; one that the worker was already + /// writing can still follow the off, and the core drops it. + Stats(CallStats), } // Tags of core to worker messages. @@ -891,6 +909,7 @@ const TO_SET_DIAGNOSTICS: u8 = 13; const TO_TEST_DEVICE: u8 = 14; const TO_SET_DEVICES: u8 = 15; const TO_SET_MICROPHONE: u8 = 16; +const TO_SET_STATS: u8 = 17; // Tags of worker to core messages. const FROM_READY: u8 = 1; @@ -915,6 +934,7 @@ const FROM_SOUND_LEVEL: u8 = 19; const FROM_PARTICIPANT_LEVEL: u8 = 20; const FROM_PARTICIPANT_MUTED: u8 = 21; const FROM_DEVICES_SET: u8 = 22; +const FROM_STATS: u8 = 23; #[derive(Clone, Copy)] enum CharRule { @@ -1317,6 +1337,10 @@ impl ToWorker { put_str(&mut out, playout.as_deref().unwrap_or("")); put_str(&mut out, camera.as_deref().unwrap_or("")); } + Self::SetStats { on } => { + out.push(TO_SET_STATS); + out.push(u8::from(*on)); + } } out } @@ -1450,6 +1474,7 @@ impl ToWorker { playout: reader.device_choice()?, camera: reader.device_choice()?, }, + TO_SET_STATS => Self::SetStats { on: reader.bool()? }, _ => return Err(DecodeError::UnknownTag), }; reader.finish()?; @@ -1623,6 +1648,10 @@ impl FromWorker { put_str(&mut out, target); put_str(&mut out, message); } + Self::Stats(stats) => { + out.push(FROM_STATS); + stats::put_stats(&mut out, stats); + } Self::VideoStopped { tile } => { out.push(FROM_VIDEO_STOPPED); out.push(*tile); @@ -1737,6 +1766,7 @@ impl FromWorker { } Self::VideoFrame { tile, rotation } } + FROM_STATS => Self::Stats(stats::read_stats(&mut reader)?), _ => return Err(DecodeError::UnknownTag), }; reader.finish()?; @@ -1954,6 +1984,7 @@ pub fn write_video_frame( #[cfg(test)] mod tests { + use super::stats::tests::full_stats; use super::*; use std::io::Cursor; @@ -2157,6 +2188,8 @@ mod tests { }, ToWorker::SetDiagnostics { on: true }, ToWorker::SetDiagnostics { on: false }, + ToWorker::SetStats { on: true }, + ToWorker::SetStats { on: false }, ToWorker::TestDevice { test: DeviceTest::Microphone, device: None, @@ -2326,6 +2359,8 @@ mod tests { target: "t".to_owned(), message: String::new(), }, + FromWorker::Stats(CallStats::default()), + FromWorker::Stats(full_stats()), FromWorker::VideoStopped { tile: 0 }, FromWorker::VideoStopped { tile: 4 }, FromWorker::VideoStopped { tile: SCREEN_TILE }, @@ -2406,7 +2441,7 @@ mod tests { width: 0, height: 0, }; - write_frame(&mut wire, header, &[99, 1]).unwrap(); + write_frame(&mut wire, header, &[VERSION + 1, 1]).unwrap(); let result: Result = read_message(&mut Cursor::new(wire), &ResourceBudgets::default()); assert_eq!(result, Err(ReadError::Decode(DecodeError::UnknownVersion))); @@ -2545,11 +2580,11 @@ mod tests { Err(DecodeError::UnknownTag) ); assert_eq!( - ToWorker::decode(&[VERSION, 17]), + ToWorker::decode(&[VERSION, 18]), Err(DecodeError::UnknownTag) ); assert_eq!( - FromWorker::decode(&[VERSION, 23]), + FromWorker::decode(&[VERSION, 24]), Err(DecodeError::UnknownTag) ); assert_eq!(FromWorker::decode(&[]), Err(DecodeError::Truncated)); @@ -3167,7 +3202,7 @@ mod tests { /// 640x360 at 15 per second. #[test] fn given_tiles_when_limits_asked_then_screen_differs_from_camera() { - assert_eq!((VIDEO_TILES, SCREEN_TILE, VERSION), (6, 5, 12)); + assert_eq!((VIDEO_TILES, SCREEN_TILE, VERSION), (6, 5, 13)); assert_eq!(MAX_SCREEN_BYTES, 3_686_400); assert_eq!(MAX_SCREEN_PIXELS, 921_600); for tile in 0..SCREEN_TILE { @@ -3645,13 +3680,13 @@ mod tests { ); } - /// GIVEN a message of the previous wire versions (6 to 11) + /// GIVEN a message of the previous wire versions (6 to 12) /// WHEN it is decoded in either direction /// THEN the version is refused. #[test] fn given_older_wire_versions_when_decoded_then_they_are_refused() { - assert_eq!(VERSION, 12); - for old in [6, 7, 8, 9, 10, 11] { + assert_eq!(VERSION, 13); + for old in [6, 7, 8, 9, 10, 11, 12] { assert_eq!( ToWorker::decode(&[old, TO_LEAVE]), Err(DecodeError::UnknownVersion) diff --git a/crates/call-protocol/src/stats.rs b/crates/call-protocol/src/stats.rs new file mode 100644 index 00000000..2140bec3 --- /dev/null +++ b/crates/call-protocol/src/stats.rs @@ -0,0 +1,457 @@ +//! The call statistics message (ADR-0066): closed numeric values only. +//! +//! Every field is an integer with a unit and an upper bound that the reader +//! checks. There is no text except the participants' identities, which the +//! worker has already validated for other messages. There is no address, +//! port, candidate type, SSRC or codec name. +//! +//! The page's contract repeats the `MAX_STATS_*` bounds as `CALL_STATS_*` +//! in `persephone-contracts`. The core checks at compile time that they +//! match. Change them together. + +use super::{DecodeError, MAX_OTHER_CONNECTIONS, MAX_PARTICIPANTS, Reader, put_str}; + +/// The highest bitrate or bandwidth a statistic holds, in kbit/s (1 Gbit/s). +pub const MAX_STATS_KBPS: u32 = 1_000_000; +/// The longest time a statistic holds, in milliseconds (one minute). +pub const MAX_STATS_MS: u16 = 60_000; +/// The highest frame rate a statistic holds, in frames per second. +pub const MAX_STATS_FPS: u8 = 120; +/// The longest picture side a statistic holds, in pixels. +pub const MAX_STATS_SIDE: u16 = 16_384; +/// The most connections one message describes: the own SFU and the other +/// SFUs of ADR-0054. +pub const MAX_STATS_CONNECTIONS: usize = 1 + MAX_OTHER_CONNECTIONS as usize; + +/// Why a sent video track runs below what was asked, as WebRTC reports it. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[repr(u8)] +pub enum QualityLimit { + None = 0, + Cpu = 1, + Bandwidth = 2, + Other = 3, +} + +impl TryFrom for QualityLimit { + type Error = DecodeError; + + fn try_from(value: u8) -> Result { + Ok(match value { + 0 => Self::None, + 1 => Self::Cpu, + 2 => Self::Bandwidth, + 3 => Self::Other, + _ => return Err(DecodeError::InvalidValue), + }) + } +} + +/// The own microphone track. `None` fields are not known yet: a rate needs +/// two samples, and the far end reports loss, jitter and round-trip time +/// only after its first report. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct AudioSendStats { + /// 0 to `MAX_SOUND_LEVEL` (100), as the meter shows it. + pub level: u8, + /// Kbit/s, at most [`MAX_STATS_KBPS`]. + pub bitrate_kbps: Option, + /// Packets sent since the track began (saturates at `u32::MAX`). + pub packets_sent: u32, + /// Packets the far end reports lost. + pub packets_lost: Option, + /// Milliseconds, at most [`MAX_STATS_MS`]. + pub jitter_ms: Option, + /// Milliseconds, at most [`MAX_STATS_MS`]. + pub rtt_ms: Option, +} + +/// The own camera or screen share track. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct VideoSendStats { + /// At most [`MAX_STATS_FPS`]. + pub fps: u8, + /// At most [`MAX_STATS_SIDE`] each. + pub width: u16, + pub height: u16, + /// Kbit/s, at most [`MAX_STATS_KBPS`]. + pub bitrate_kbps: Option, + pub limit: QualityLimit, + /// Packets the far end reports lost. + pub packets_lost: Option, +} + +/// The audio of one remote participant. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct AudioReceiveStats { + /// 0 to `MAX_SOUND_LEVEL` (100). + pub level: u8, + pub bitrate_kbps: Option, + pub packets_received: u32, + pub packets_lost: u32, + /// Milliseconds, at most [`MAX_STATS_MS`]. + pub jitter_ms: u16, + /// Share of the samples of the last second that WebRTC made up, 0 to + /// 100. + pub concealed_percent: Option, +} + +/// The video of one remote participant. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct VideoReceiveStats { + pub fps: u8, + pub width: u16, + pub height: u16, + pub bitrate_kbps: Option, + /// Frames dropped each second, over the last interval, at most + /// [`MAX_STATS_FPS`]. Not known until the second sample. + pub dropped_fps: Option, + pub packets_lost: u32, +} + +/// One remote participant, named by the identity and connection that the +/// worker already validated for its other messages. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct RemoteStats { + pub connection: u8, + pub identity: String, + pub audio: Option, + pub video: Option, +} + +/// One connection to an SFU: 0 is the own one. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct ConnectionStats { + pub connection: u8, + /// The bandwidth that WebRTC estimates for sending, kbit/s. + pub outgoing_kbps: Option, + /// Everything sent and everything received on the connection, kbit/s. + pub send_kbps: Option, + pub receive_kbps: Option, + pub rtt_ms: Option, +} + +/// One reading of the call's statistics. +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct CallStats { + pub microphone: Option, + pub camera: Option, + pub screen: Option, + /// At most [`MAX_PARTICIPANTS`], at most one for each participant. + pub remotes: Vec, + /// At most [`MAX_STATS_CONNECTIONS`], at most one for each connection. + pub connections: Vec, +} + +// Writing. The caller keeps every value inside its bound; the reader refuses +// anything else. + +fn put_flag(out: &mut Vec, present: bool) { + out.push(u8::from(present)); +} + +fn put_u32(out: &mut Vec, value: Option) { + put_flag(out, value.is_some()); + if let Some(value) = value { + out.extend_from_slice(&value.to_be_bytes()); + } +} + +fn put_u16(out: &mut Vec, value: Option) { + put_flag(out, value.is_some()); + if let Some(value) = value { + out.extend_from_slice(&value.to_be_bytes()); + } +} + +fn put_u8(out: &mut Vec, value: Option) { + put_flag(out, value.is_some()); + if let Some(value) = value { + out.push(value); + } +} + +fn put_audio_send(out: &mut Vec, audio: &AudioSendStats) { + out.push(audio.level); + put_u32(out, audio.bitrate_kbps); + out.extend_from_slice(&audio.packets_sent.to_be_bytes()); + put_u32(out, audio.packets_lost); + put_u16(out, audio.jitter_ms); + put_u16(out, audio.rtt_ms); +} + +fn put_video_send(out: &mut Vec, video: &VideoSendStats) { + out.push(video.fps); + out.extend_from_slice(&video.width.to_be_bytes()); + out.extend_from_slice(&video.height.to_be_bytes()); + put_u32(out, video.bitrate_kbps); + out.push(video.limit as u8); + put_u32(out, video.packets_lost); +} + +fn put_audio_receive(out: &mut Vec, audio: &AudioReceiveStats) { + out.push(audio.level); + put_u32(out, audio.bitrate_kbps); + out.extend_from_slice(&audio.packets_received.to_be_bytes()); + out.extend_from_slice(&audio.packets_lost.to_be_bytes()); + out.extend_from_slice(&audio.jitter_ms.to_be_bytes()); + put_u8(out, audio.concealed_percent); +} + +fn put_video_receive(out: &mut Vec, video: &VideoReceiveStats) { + out.push(video.fps); + out.extend_from_slice(&video.width.to_be_bytes()); + out.extend_from_slice(&video.height.to_be_bytes()); + put_u32(out, video.bitrate_kbps); + put_u8(out, video.dropped_fps); + out.extend_from_slice(&video.packets_lost.to_be_bytes()); +} + +/// Writes `stats` after the message tag. The lists are cut to their limits, +/// so each count fits its byte. Like the other writers of this protocol, it +/// writes every entry as given: the reader refuses the whole message for an +/// entry out of bounds (an identity that is too long or has a control +/// character, a connection past `MAX_OTHER_CONNECTIONS`, a repeated entry, a +/// number past its maximum). The caller (`mapping::stats` in the worker) +/// leaves such entries out and clamps the numbers first. +pub(super) fn put_stats(out: &mut Vec, stats: &CallStats) { + let present = u8::from(stats.microphone.is_some()) + | u8::from(stats.camera.is_some()) << 1 + | u8::from(stats.screen.is_some()) << 2; + out.push(present); + if let Some(audio) = &stats.microphone { + put_audio_send(out, audio); + } + for video in [&stats.camera, &stats.screen].into_iter().flatten() { + put_video_send(out, video); + } + let remotes = &stats.remotes[..stats.remotes.len().min(MAX_PARTICIPANTS)]; + out.push(remotes.len() as u8); + for remote in remotes { + out.push(remote.connection); + put_str(out, &remote.identity); + out.push(u8::from(remote.audio.is_some()) | u8::from(remote.video.is_some()) << 1); + if let Some(audio) = &remote.audio { + put_audio_receive(out, audio); + } + if let Some(video) = &remote.video { + put_video_receive(out, video); + } + } + let connections = &stats.connections[..stats.connections.len().min(MAX_STATS_CONNECTIONS)]; + out.push(connections.len() as u8); + for connection in connections { + out.push(connection.connection); + put_u32(out, connection.outgoing_kbps); + put_u32(out, connection.send_kbps); + put_u32(out, connection.receive_kbps); + put_u16(out, connection.rtt_ms); + } +} + +// Reading. + +impl Reader<'_> { + fn flag(&mut self) -> Result { + self.bool() + } + + fn kbps(&mut self) -> Result, DecodeError> { + if !self.flag()? { + return Ok(None); + } + let value = self.u32()?; + if value > MAX_STATS_KBPS { + return Err(DecodeError::InvalidValue); + } + Ok(Some(value)) + } + + fn millis(&mut self) -> Result { + let value = self.u16()?; + if value > MAX_STATS_MS { + return Err(DecodeError::InvalidValue); + } + Ok(value) + } + + fn optional_millis(&mut self) -> Result, DecodeError> { + if self.flag()? { + Ok(Some(self.millis()?)) + } else { + Ok(None) + } + } + + fn optional_count(&mut self) -> Result, DecodeError> { + if self.flag()? { + Ok(Some(self.u32()?)) + } else { + Ok(None) + } + } + + fn fps(&mut self) -> Result { + let value = self.u8()?; + if value > MAX_STATS_FPS { + return Err(DecodeError::InvalidValue); + } + Ok(value) + } + + fn side(&mut self) -> Result { + let value = self.u16()?; + if value > MAX_STATS_SIDE { + return Err(DecodeError::InvalidValue); + } + Ok(value) + } + + fn percent(&mut self) -> Result { + let value = self.u8()?; + if value > 100 { + return Err(DecodeError::InvalidValue); + } + Ok(value) + } + + fn audio_send(&mut self) -> Result { + Ok(AudioSendStats { + level: self.sound_level()?, + bitrate_kbps: self.kbps()?, + packets_sent: self.u32()?, + packets_lost: self.optional_count()?, + jitter_ms: self.optional_millis()?, + rtt_ms: self.optional_millis()?, + }) + } + + fn video_send(&mut self) -> Result { + Ok(VideoSendStats { + fps: self.fps()?, + width: self.side()?, + height: self.side()?, + bitrate_kbps: self.kbps()?, + limit: QualityLimit::try_from(self.u8()?)?, + packets_lost: self.optional_count()?, + }) + } + + fn audio_receive(&mut self) -> Result { + Ok(AudioReceiveStats { + level: self.sound_level()?, + bitrate_kbps: self.kbps()?, + packets_received: self.u32()?, + packets_lost: self.u32()?, + jitter_ms: self.millis()?, + concealed_percent: if self.flag()? { + Some(self.percent()?) + } else { + None + }, + }) + } + + fn video_receive(&mut self) -> Result { + Ok(VideoReceiveStats { + fps: self.fps()?, + width: self.side()?, + height: self.side()?, + bitrate_kbps: self.kbps()?, + dropped_fps: if self.flag()? { + Some(self.fps()?) + } else { + None + }, + packets_lost: self.u32()?, + }) + } +} + +/// Reads the statistics after the message tag. The counts are checked +/// before anything is allocated, and a participant or a connection that +/// appears twice is refused. +pub(super) fn read_stats(reader: &mut Reader<'_>) -> Result { + let present = reader.u8()?; + if present > 0b111 { + return Err(DecodeError::InvalidValue); + } + let microphone = if present & 1 != 0 { + Some(reader.audio_send()?) + } else { + None + }; + let camera = if present & 2 != 0 { + Some(reader.video_send()?) + } else { + None + }; + let screen = if present & 4 != 0 { + Some(reader.video_send()?) + } else { + None + }; + let count = usize::from(reader.u8()?); + if count > MAX_PARTICIPANTS { + return Err(DecodeError::TooLarge); + } + let mut remotes: Vec = Vec::with_capacity(count); + for _ in 0..count { + let connection = reader.connection()?; + let identity = reader.identity()?; + if remotes + .iter() + .any(|seen| seen.connection == connection && seen.identity == identity) + { + return Err(DecodeError::InvalidValue); + } + let kinds = reader.u8()?; + if kinds > 0b11 { + return Err(DecodeError::InvalidValue); + } + let audio = if kinds & 1 != 0 { + Some(reader.audio_receive()?) + } else { + None + }; + let video = if kinds & 2 != 0 { + Some(reader.video_receive()?) + } else { + None + }; + remotes.push(RemoteStats { + connection, + identity, + audio, + video, + }); + } + let count = usize::from(reader.u8()?); + if count > MAX_STATS_CONNECTIONS { + return Err(DecodeError::TooLarge); + } + let mut connections: Vec = Vec::with_capacity(count); + for _ in 0..count { + let connection = reader.connection()?; + if connections.iter().any(|seen| seen.connection == connection) { + return Err(DecodeError::InvalidValue); + } + connections.push(ConnectionStats { + connection, + outgoing_kbps: reader.kbps()?, + send_kbps: reader.kbps()?, + receive_kbps: reader.kbps()?, + rtt_ms: reader.optional_millis()?, + }); + } + Ok(CallStats { + microphone, + camera, + screen, + remotes, + connections, + }) +} + +#[cfg(test)] +pub(crate) mod tests; diff --git a/crates/call-protocol/src/stats/tests.rs b/crates/call-protocol/src/stats/tests.rs new file mode 100644 index 00000000..85ad15ff --- /dev/null +++ b/crates/call-protocol/src/stats/tests.rs @@ -0,0 +1,298 @@ +use super::*; +use crate::{ + FROM_STATS, FromWorker, MAX_IDENTITY_BYTES, MAX_MESSAGE_BYTES, TO_SET_STATS, ToWorker, VERSION, +}; + +pub(crate) fn full_stats() -> CallStats { + let audio = AudioReceiveStats { + level: 100, + bitrate_kbps: Some(MAX_STATS_KBPS), + packets_received: u32::MAX, + packets_lost: 7, + jitter_ms: MAX_STATS_MS, + concealed_percent: Some(100), + }; + let video = VideoReceiveStats { + fps: MAX_STATS_FPS, + width: MAX_STATS_SIDE, + height: 1, + bitrate_kbps: None, + dropped_fps: Some(3), + packets_lost: u32::MAX, + }; + let sent = VideoSendStats { + fps: 30, + width: 1280, + height: 720, + bitrate_kbps: Some(1500), + limit: QualityLimit::Bandwidth, + packets_lost: Some(2), + }; + CallStats { + microphone: Some(AudioSendStats { + level: 42, + bitrate_kbps: Some(32), + packets_sent: 1000, + packets_lost: Some(1), + jitter_ms: Some(3), + rtt_ms: Some(40), + }), + camera: Some(sent), + screen: Some(VideoSendStats { + limit: QualityLimit::None, + packets_lost: None, + ..sent + }), + remotes: vec![ + RemoteStats { + connection: 0, + identity: "@bob:example.org:D".to_owned(), + audio: Some(audio), + video: Some(video), + }, + RemoteStats { + connection: 2, + identity: "@bob:example.org:D".to_owned(), + audio: None, + video: Some(video), + }, + ], + connections: vec![ + ConnectionStats { + connection: 0, + outgoing_kbps: Some(2500), + send_kbps: Some(40), + receive_kbps: None, + rtt_ms: Some(20), + }, + ConnectionStats { + connection: 3, + outgoing_kbps: None, + send_kbps: None, + receive_kbps: Some(MAX_STATS_KBPS), + rtt_ms: None, + }, + ], + } +} + +/// A message body with the version, the tag and `fields`. +fn body(fields: &[u8]) -> Vec { + let mut out = vec![VERSION, FROM_STATS]; + out.extend_from_slice(fields); + out +} + +fn decode(fields: &[u8]) -> Result { + FromWorker::decode(&body(fields)) +} + +/// The fields of a message with an own microphone record and nothing else. +fn audio_send_fields(level: u8) -> Vec { + // present: microphone; level; no bitrate; 4 bytes of packets; no loss, + // jitter or round-trip time; then no remotes and no connections. + vec![0b001, level, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] +} + +/// GIVEN every kind of statistic WHEN encoded and decoded THEN it is the +/// same. +#[test] +fn given_full_stats_when_round_tripped_then_unchanged() { + for stats in [CallStats::default(), full_stats()] { + let message = FromWorker::Stats(stats); + assert_eq!(FromWorker::decode(&message.encode()), Ok(message)); + } +} + +/// GIVEN statistics for every participant, with the longest identities WHEN +/// encoded THEN the message fits `MAX_MESSAGE_BYTES`. +#[test] +fn given_the_most_participants_with_long_identities_then_the_message_fits() { + let mut stats = full_stats(); + let audio = stats.remotes[0].audio; + let video = stats.remotes[0].video; + stats.remotes = (0..MAX_PARTICIPANTS) + .map(|index| RemoteStats { + connection: 0, + identity: format!("{index:0>width$}", width = MAX_IDENTITY_BYTES), + audio, + video, + }) + .collect(); + let wire = FromWorker::Stats(stats.clone()).encode(); + assert!(wire.len() < MAX_MESSAGE_BYTES, "{}", wire.len()); + assert_eq!(FromWorker::decode(&wire), Ok(FromWorker::Stats(stats))); +} + +/// GIVEN more entries than the limits WHEN encoded THEN the extra entries +/// are left out and the message decodes. +#[test] +fn given_too_many_entries_when_encoded_then_the_extras_are_left_out() { + let stats = CallStats { + remotes: (0..MAX_PARTICIPANTS + 5) + .map(|index| RemoteStats { + connection: 0, + identity: format!("id{index}"), + audio: None, + video: None, + }) + .collect(), + connections: (0..8) + .map(|connection| ConnectionStats { + connection, + outgoing_kbps: None, + send_kbps: None, + receive_kbps: None, + rtt_ms: None, + }) + .collect(), + ..CallStats::default() + }; + let Ok(FromWorker::Stats(read)) = FromWorker::decode(&FromWorker::Stats(stats).encode()) else { + panic!("the message must decode"); + }; + assert_eq!(read.remotes.len(), MAX_PARTICIPANTS); + assert_eq!(read.connections.len(), MAX_STATS_CONNECTIONS); +} + +/// GIVEN a count of participants or connections over its limit WHEN decoded +/// THEN it is refused before any entry is read. +#[test] +fn given_counts_over_the_limits_when_decoded_then_they_are_refused() { + assert_eq!( + decode(&[0, (MAX_PARTICIPANTS + 1) as u8]), + Err(DecodeError::TooLarge) + ); + assert_eq!( + decode(&[0, 0, (MAX_STATS_CONNECTIONS + 1) as u8]), + Err(DecodeError::TooLarge) + ); + assert_eq!( + decode(&[0, 0, 0]), + Ok(FromWorker::Stats(CallStats::default())) + ); +} + +/// GIVEN a field over its bound WHEN decoded THEN it is refused, and the +/// bound itself is accepted. +#[test] +fn given_a_value_over_its_bound_when_decoded_then_it_is_refused() { + assert_eq!( + decode(&audio_send_fields(101)), + Err(DecodeError::InvalidValue) + ); + assert!(decode(&audio_send_fields(100)).is_ok()); + // A bitrate over 1 Gbit/s. + for (kbps, ok) in [(MAX_STATS_KBPS, true), (MAX_STATS_KBPS + 1, false)] { + let mut fields = vec![0b001, 0, 1]; + fields.extend_from_slice(&kbps.to_be_bytes()); + fields.extend_from_slice(&[0; 9]); + assert_eq!(decode(&fields).is_ok(), ok, "{kbps}"); + } + // A round-trip time over a minute. + for (millis, ok) in [(MAX_STATS_MS, true), (MAX_STATS_MS + 1, false)] { + let mut fields = vec![0b001, 0, 0, 0, 0, 0, 0, 0, 0, 1]; + fields.extend_from_slice(&millis.to_be_bytes()); + fields.extend_from_slice(&[0, 0]); + assert_eq!(decode(&fields).is_ok(), ok, "{millis}"); + } + // A frame rate, a side and a limit code of a camera. + for (fps, side, limit, ok) in [ + (MAX_STATS_FPS, MAX_STATS_SIDE, 3u8, true), + (MAX_STATS_FPS + 1, 1u16, 0u8, false), + (1, MAX_STATS_SIDE + 1, 0, false), + (1, 1, 4, false), + ] { + let mut fields = vec![0b010, fps]; + fields.extend_from_slice(&side.to_be_bytes()); + fields.extend_from_slice(&1u16.to_be_bytes()); + fields.extend_from_slice(&[0, limit, 0, 0, 0]); + assert_eq!(decode(&fields).is_ok(), ok, "{fps} {side} {limit}"); + } +} + +/// GIVEN flag bytes that are not 0 or 1, or unknown presence bits WHEN +/// decoded THEN they are refused. +#[test] +fn given_bad_flags_when_decoded_then_they_are_refused() { + assert_eq!(decode(&[0b1000]), Err(DecodeError::InvalidValue)); + let mut fields = audio_send_fields(1); + fields[2] = 2; + assert_eq!(decode(&fields), Err(DecodeError::InvalidValue)); + // A remote with unknown kind bits. + assert_eq!( + decode(&[0, 1, 0, 0, 1, b'a', 0b100]), + Err(DecodeError::InvalidValue) + ); +} + +/// GIVEN a participant or a connection listed twice, an unknown connection +/// number, or a bad identity WHEN decoded THEN it is refused. +#[test] +fn given_duplicate_or_bad_entries_when_decoded_then_they_are_refused() { + let remote = [0u8, 0, 1, b'a', 0]; + let mut twice = vec![0, 2]; + twice.extend_from_slice(&remote); + twice.extend_from_slice(&remote); + twice.push(0); + assert_eq!(decode(&twice), Err(DecodeError::InvalidValue)); + // The same identity on two connections is two participants. + let mut other = remote; + other[0] = 1; + let mut two = vec![0, 2]; + two.extend_from_slice(&remote); + two.extend_from_slice(&other); + two.push(0); + assert!(decode(&two).is_ok()); + // Connection 4 does not exist. + assert_eq!( + decode(&[0, 1, 4, 0, 1, b'a', 0, 0]), + Err(DecodeError::InvalidValue) + ); + // An empty identity and a control character. + assert_eq!(decode(&[0, 1, 0, 0, 0, 0]), Err(DecodeError::TooShort)); + assert_eq!( + decode(&[0, 1, 0, 0, 1, 0x07, 0, 0]), + Err(DecodeError::InvalidCharacter) + ); + // A connection twice. + let connection = [0u8, 0, 0, 0, 0]; + let mut dup = vec![0, 0, 2]; + dup.extend_from_slice(&connection); + dup.extend_from_slice(&connection); + assert_eq!(decode(&dup), Err(DecodeError::InvalidValue)); +} + +/// GIVEN a message cut at every byte, with a trailing byte, or over the +/// message limit WHEN decoded THEN it is refused. +#[test] +fn given_truncated_trailing_or_oversize_stats_when_decoded_then_refused() { + let wire = FromWorker::Stats(full_stats()).encode(); + for length in 0..wire.len() { + assert!(FromWorker::decode(&wire[..length]).is_err(), "{length}"); + } + let mut longer = wire.clone(); + longer.push(0); + assert_eq!(FromWorker::decode(&longer), Err(DecodeError::TrailingBytes)); + let mut huge = wire; + huge.resize(MAX_MESSAGE_BYTES + 1, 0); + assert_eq!(FromWorker::decode(&huge), Err(DecodeError::TooLarge)); +} + +/// GIVEN the core's switch WHEN it is anything but 0 or 1 THEN it is +/// refused. +#[test] +fn given_the_stats_switch_when_decoded_then_only_a_bool_is_accepted() { + for on in [true, false] { + let message = ToWorker::SetStats { on }; + assert_eq!(ToWorker::decode(&message.encode()), Ok(message)); + } + assert_eq!( + ToWorker::decode(&[VERSION, TO_SET_STATS, 2]), + Err(DecodeError::InvalidValue) + ); + assert_eq!( + ToWorker::decode(&[VERSION, TO_SET_STATS]), + Err(DecodeError::Truncated) + ); +} diff --git a/crates/call-worker/AGENTS.md b/crates/call-worker/AGENTS.md index a5816f05..5fe7d5df 100644 --- a/crates/call-worker/AGENTS.md +++ b/crates/call-worker/AGENTS.md @@ -30,6 +30,7 @@ The contained process that runs one call (ADR-0043). It joins one LiveKit room w - Device tests (ADR-0059): `TestDevice` is a first message, like `ListDevices`; it connects to no server. `session::test_device` opens a sound test's device first (`sound_test::open`, off the runtime threads), then applies stage 2, then runs it (`Opened::run`, on its own thread). `sound_test.rs` listens (15 s, own level) or plays a 440 Hz tone (1.5 s). Windows: WASAPI in shared mode; `E_ACCESSDENIED` is `DeviceDenied`. Linux: one PulseAudio stream through the `libpulse.so.0` handle of `pulse.rs`, the default stream with no device name and `PA_STREAM_DONT_MOVE`; a `pulse:` choice is checked with `sound_paths` as for a `Join` and reaches the stream through `PULSE_SOURCE` or `PULSE_SINK`; any other chosen ID is `DeviceNotFound`; it must open before stage 2 (new socket); `PA_ERR_ACCESS` is `DeviceDenied`. macOS: a Core Audio HAL I/O procedure (32-bit float only) on the default device or the chosen UID; the device is found before the microphone permission is checked, so a missing device never prompts; a refused permission is `DeviceDenied`. Never request a permission in a default-run test on macOS: outside an app bundle it ends the process. The camera test takes the portal remote that the core sends before `TestDevice` (`Grant::take`), opens the camera as a call does and sends pictures on tile 0 for at most 30 s. `Leave` ends any test, which ends with `Left` or `Failed`. - Microphone settings (ADR-0062): `Join` carries `auto_level` and `mic_gain`, and `SetMicrophone` changes them in a running call. `mapping::Microphone::new` is the worker's own check (a gain over 400 percent or off the step of 5 is `Protocol`; the protocol reader refuses it first). The gain goes to the voice engine's audio processing module through `native::capture_processing::set_capture_gain_percent` (a process-wide value that every live factory applies); the automatic level goes to the published microphone track through `RtcAudioTrack::set_auto_gain_control`. Both apply at once, and `apply_microphone` applies both again after each `SetDevices`. The device tests (`sound_test.rs`) do not use them. A refusal is noted, never fatal. - Audio notes (ADR-0058 amendment of 2026-11-25): `note_audio` in `session.rs` writes `Note` records of the target `persephone::call_worker::audio` while the log is on: the devices at the join (counts and how each was chosen, never an ID or name), the microphone settings with what the audio processing module reports, and every 5 seconds the own level, the playout state and each remote audio track's packets, samples and level (`measure_levels`). Keep them to counts, flags and levels. Never add an identity, a device ID or name, a key or a token. +- Call statistics (ADR-0066): `session/stats_probe.rs` reads `get_stats` of the own microphone, camera and screen tracks and of one audio and one video track of each remote participant (at most `MAX_PARTICIPANTS`), only while the core has sent `SetStats { on: true }`, at most once a second, on its own task with a deadline (`StatsProbe`; one read at a time, aborted at shutdown, a report of an older series is dropped by its number). It reads transports through those tracks, not through the room, because a `Room` is not clonable into the task. It never reads an address, port, candidate type, SSRC or codec. `mapping/stats.rs` is pure: `StatsBook` turns raw counters into rates from the change since each counter's sample before, over the time between the two reads, keyed by track ID or transport (a reset, a new track, a missing earlier value, a zero interval or a connection with an unread transport gives no rate, never a wrong one) and clamps every number to the protocol bound. Turning the statistics off and on keeps the one-second spacing of reads. The message goes to `Output::offer_stats`, which keeps at most one waiting reading (newest wins) and writes it after the control messages and the waiting picture of a round. Statistics never use the control queue. - Pictures never use the control queue. `output.rs` keeps at most one waiting picture per tile (newest wins), and control messages always go out first. Pictures are RGBA in byte order R, G, B, A, at most 640x360 and 15 per second per camera tile, and at most 1280x720 and 5 per second on the screen tile (5), checked by tile index before allocation. ## Build diff --git a/crates/call-worker/src/mapping.rs b/crates/call-worker/src/mapping.rs index bf9add86..4911fbee 100644 --- a/crates/call-worker/src/mapping.rs +++ b/crates/call-worker/src/mapping.rs @@ -1,5 +1,7 @@ //! The pure parts of the worker: no LiveKit types, no I/O, no clock reads. +pub mod stats; + use std::collections::{BTreeSet, HashMap, VecDeque}; use std::time::{Duration, Instant}; diff --git a/crates/call-worker/src/mapping/stats.rs b/crates/call-worker/src/mapping/stats.rs new file mode 100644 index 00000000..1a34f039 --- /dev/null +++ b/crates/call-worker/src/mapping/stats.rs @@ -0,0 +1,533 @@ +//! Turns raw WebRTC counters into the call statistics message (ADR-0066). +//! +//! Pure: no LiveKit types, no I/O and no clock. The caller gives each +//! track's and each transport's numbers the time they were read, in +//! milliseconds, and the book makes each rate from the change of a counter +//! since its sample before, over the time between the two samples. A +//! track's counters are kept under its track ID, so a new track never +//! compares with an older one. + +use std::collections::HashMap; + +use persephone_call_protocol::{ + AudioReceiveStats, AudioSendStats, CallStats, ConnectionStats, MAX_OTHER_CONNECTIONS, + MAX_PARTICIPANTS, MAX_STATS_CONNECTIONS, MAX_STATS_FPS, MAX_STATS_KBPS, MAX_STATS_MS, + MAX_STATS_SIDE, QualityLimit, RemoteStats, VideoReceiveStats, VideoSendStats, +}; + +use super::{sound_level, valid_identity}; + +/// How many bits a counter has in WebRTC. A 32-bit counter that falls from +/// near its top to near zero has wrapped. Any other fall is a reset. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Width { + Bits32, + Bits64, +} + +/// How much `current` is above `previous`, or `None` when there is no +/// previous value or the counter was reset. +pub fn counter_delta(previous: Option, current: u64, width: Width) -> Option { + let previous = previous?; + if current >= previous { + return Some(current - previous); + } + let top = u64::from(u32::MAX); + // A 32-bit counter wraps from near its top to near zero. A fall by less + // than half the range is a reset or a counter that went back. + if width == Width::Bits32 && previous <= top && current <= top && previous - current > top / 2 { + return Some(current + (top - previous) + 1); + } + None +} + +/// `delta` each second over `interval_ms`. `None` for no interval. +pub fn per_second(delta: u64, interval_ms: u64) -> Option { + if interval_ms == 0 { + return None; + } + u64::try_from(u128::from(delta) * 1000 / u128::from(interval_ms)).ok() +} + +/// The bitrate in kbit/s of `delta` bytes over `interval_ms`, at most +/// [`MAX_STATS_KBPS`]. `None` for no interval. +pub fn kbps(delta_bytes: u64, interval_ms: u64) -> Option { + if interval_ms == 0 { + return None; + } + // Bits per millisecond are kbit/s. + let rate = u128::from(delta_bytes) * 8 / u128::from(interval_ms); + Some(u32::try_from(rate.min(u128::from(MAX_STATS_KBPS))).unwrap_or(MAX_STATS_KBPS)) +} + +/// Seconds as WebRTC reports them to milliseconds, at most +/// [`MAX_STATS_MS`]. A value that is not a number or is negative is `None`. +pub fn millis(seconds: f64) -> Option { + if !seconds.is_finite() || seconds < 0.0 { + return None; + } + // Clamped first, so the cast cannot truncate. + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + let millis = (seconds * 1000.0).round().min(f64::from(MAX_STATS_MS)) as u16; + Some(millis) +} + +/// A count that WebRTC reports signed (lost packets can fall below zero when +/// duplicates arrive): never below 0 and at most `u32::MAX`. +pub fn count(value: i64) -> u32 { + u32::try_from(value.max(0)).unwrap_or(u32::MAX) +} + +fn unsigned(value: u64) -> u32 { + u32::try_from(value).unwrap_or(u32::MAX) +} + +fn frames_per_second(value: f64) -> u8 { + if !value.is_finite() || value <= 0.0 { + return 0; + } + // Clamped first, so the cast cannot truncate. + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + let fps = value.round().min(f64::from(MAX_STATS_FPS)) as u8; + fps +} + +fn side(value: u32) -> u16 { + u16::try_from(value.min(u32::from(MAX_STATS_SIDE))).unwrap_or(MAX_STATS_SIDE) +} + +fn kbps_from_bits(bits_per_second: f64) -> Option { + if !bits_per_second.is_finite() || bits_per_second < 0.0 { + return None; + } + // Clamped first, so the cast cannot truncate. + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + let rate = (bits_per_second / 1000.0) + .round() + .min(f64::from(MAX_STATS_KBPS)) as u32; + Some(rate) +} + +// The raw readings: plain numbers in the units of WebRTC's statistics +// (seconds, bytes, 0.0 to 1.0 levels). + +/// The own microphone track. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct RawOwnAudio { + /// The track ID, which keys its counters, and the time of its read. + pub track: String, + pub at_ms: u64, + /// Linear, 0.0 to 1.0. + pub level: f64, + pub bytes_sent: u64, + pub packets_sent: u64, + /// What the far end reports; `None` before its first report. + pub packets_lost: Option, + pub jitter_seconds: Option, + pub rtt_seconds: Option, +} + +/// The own camera or screen share track. A track with several layers gives +/// the sum of their bytes and the largest layer's size and frame rate. +#[derive(Clone, Debug, PartialEq)] +pub struct RawOwnVideo { + pub track: String, + pub at_ms: u64, + pub fps: f64, + pub width: u32, + pub height: u32, + pub bytes_sent: u64, + pub limit: QualityLimit, + pub packets_lost: Option, +} + +/// The audio of one remote participant: its microphone track (one per +/// participant; the smallest track id when it has more). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct RawRemoteAudio { + pub track: String, + pub at_ms: u64, + /// Linear, 0.0 to 1.0. + pub level: f64, + pub bytes_received: u64, + pub packets_received: u64, + pub packets_lost: i64, + pub jitter_seconds: f64, + pub total_samples: u64, + pub concealed_samples: u64, +} + +/// The video of one remote participant. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct RawRemoteVideo { + pub track: String, + pub at_ms: u64, + pub fps: f64, + pub width: u32, + pub height: u32, + pub bytes_received: u64, + pub frames_dropped: u64, + pub packets_lost: i64, +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct RawRemote { + pub connection: u8, + pub identity: String, + pub audio: Option, + pub video: Option, +} + +/// Which transport of a connection a link is. +#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] +pub enum LinkRole { + /// The own room's single peer connection, which sends and receives. + Single, + Publisher, + Subscriber, +} + +/// The byte counters of one transport, read at `at_ms`. +#[derive(Clone, Debug, PartialEq)] +pub struct RawLink { + pub role: LinkRole, + pub at_ms: u64, + pub bytes_sent: u64, + pub bytes_received: u64, +} + +/// One connection to an SFU. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct RawConnection { + pub connection: u8, + /// WebRTC's estimate of the bandwidth for sending, in bit/s. + pub outgoing_bits_per_second: Option, + pub rtt_seconds: Option, + /// The transports whose bytes add up to the connection's totals, each + /// role once. + pub links: Vec, + /// Whether every transport that the connection uses was read. When one + /// was not, the totals would be short, so the byte rates are unknown. + pub complete: bool, +} + +/// One reading of everything. Each part carries the time it was read, on a +/// clock that only goes forward. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct RawStats { + pub microphone: Option, + pub camera: Option, + pub screen: Option, + pub remotes: Vec, + pub connections: Vec, +} + +/// What a counter belongs to: an own track by its track ID, a remote track +/// by connection, identity and track ID, or one transport of a connection. +/// A new track starts with no earlier value, so a switch (a camera after a +/// screen share, a new microphone) never gives a wrong rate. +#[derive(Clone, Debug, Eq, Hash, PartialEq)] +enum Source { + Microphone(String), + Camera(String), + Screen(String), + Remote(u8, String, String), + Link(u8, LinkRole), +} + +#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] +enum Counter { + BytesSent, + BytesReceived, + AudioBytes, + VideoBytes, + FramesDropped, + TotalSamples, + ConcealedSamples, +} + +type Key = (Source, Counter); + +/// A counter's value and the time it was read. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +struct Sample { + value: u64, + at_ms: u64, +} + +/// Remembers the last sample of each counter, so a reading gives rates. +#[derive(Debug, Default)] +pub struct StatsBook { + counters: HashMap, +} + +/// The counters of one reading while it is made. +struct Reading<'a> { + before: &'a HashMap, + now: HashMap, +} + +impl Reading<'_> { + /// The change of a counter since its sample before, and the time + /// between the two. `None` for a counter with no sample before, one that + /// was reset, and a sample at the time of the one before or earlier. A + /// sample at the same time keeps the one before, so the next sample + /// still has a rate; any other sample is kept for the next reading. + fn delta( + &mut self, + source: &Source, + counter: Counter, + sample: Sample, + width: Width, + ) -> Option<(u64, u64)> { + let key = (source.clone(), counter); + let before = self.before.get(&key).copied(); + if let Some(before) = before + && before.at_ms == sample.at_ms + { + self.now.insert(key, before); + return None; + } + self.now.insert(key, sample); + let before = before?; + let interval = sample + .at_ms + .checked_sub(before.at_ms) + .filter(|interval| *interval > 0)?; + Some(( + counter_delta(Some(before.value), sample.value, width)?, + interval, + )) + } + + fn kbps(&mut self, source: &Source, counter: Counter, bytes: u64, at_ms: u64) -> Option { + let sample = Sample { + value: bytes, + at_ms, + }; + let (delta, interval) = self.delta(source, counter, sample, Width::Bits64)?; + kbps(delta, interval) + } +} + +impl StatsBook { + /// Forgets every counter, so the next reading has no rates. Call it when + /// the statistics are turned on, so a pause is not a long interval. + pub fn reset(&mut self) { + self.counters.clear(); + } + + /// The statistics message for `raw`. A rate is `None` for a counter with + /// no sample before (the first reading, a new track), one that was + /// reset, and one read at the time of its sample before or earlier. + /// Entries past the limits and entries the protocol would refuse are + /// left out. Counters that the reading does not show are forgotten. + pub fn next(&mut self, raw: &RawStats) -> CallStats { + let before = std::mem::take(&mut self.counters); + let mut reading = Reading { + before: &before, + now: HashMap::new(), + }; + let stats = + CallStats { + microphone: raw + .microphone + .as_ref() + .map(|audio| own_audio(&mut reading, audio)), + camera: raw.camera.as_ref().map(|video| { + own_video(&mut reading, &Source::Camera(video.track.clone()), video) + }), + screen: raw.screen.as_ref().map(|video| { + own_video(&mut reading, &Source::Screen(video.track.clone()), video) + }), + remotes: remotes(&mut reading, &raw.remotes), + connections: connections(&mut reading, &raw.connections), + }; + self.counters = reading.now; + stats + } +} + +fn own_audio(reading: &mut Reading<'_>, audio: &RawOwnAudio) -> AudioSendStats { + AudioSendStats { + level: sound_level(audio.level), + bitrate_kbps: reading.kbps( + &Source::Microphone(audio.track.clone()), + Counter::BytesSent, + audio.bytes_sent, + audio.at_ms, + ), + packets_sent: unsigned(audio.packets_sent), + packets_lost: audio.packets_lost.map(count), + jitter_ms: audio.jitter_seconds.and_then(millis), + rtt_ms: audio.rtt_seconds.and_then(millis), + } +} + +fn own_video(reading: &mut Reading<'_>, source: &Source, video: &RawOwnVideo) -> VideoSendStats { + VideoSendStats { + fps: frames_per_second(video.fps), + width: side(video.width), + height: side(video.height), + bitrate_kbps: reading.kbps(source, Counter::BytesSent, video.bytes_sent, video.at_ms), + limit: video.limit, + packets_lost: video.packets_lost.map(count), + } +} + +fn remotes(reading: &mut Reading<'_>, raw: &[RawRemote]) -> Vec { + let mut out: Vec = Vec::new(); + for remote in raw { + if out.len() >= MAX_PARTICIPANTS { + break; + } + if !valid_identity(&remote.identity) + || remote.connection > MAX_OTHER_CONNECTIONS + || out.iter().any(|seen| { + seen.connection == remote.connection && seen.identity == remote.identity + }) + { + continue; + } + let track = |track: &str| { + Source::Remote(remote.connection, remote.identity.clone(), track.to_owned()) + }; + let audio = remote.audio.as_ref().map(|audio| { + let source = track(&audio.track); + let sample = |value| Sample { + value, + at_ms: audio.at_ms, + }; + let total = reading + .delta( + &source, + Counter::TotalSamples, + sample(audio.total_samples), + Width::Bits64, + ) + .map(|(delta, _)| delta); + let concealed = reading + .delta( + &source, + Counter::ConcealedSamples, + sample(audio.concealed_samples), + Width::Bits64, + ) + .map(|(delta, _)| delta); + AudioReceiveStats { + level: sound_level(audio.level), + bitrate_kbps: reading.kbps( + &source, + Counter::AudioBytes, + audio.bytes_received, + audio.at_ms, + ), + packets_received: unsigned(audio.packets_received), + packets_lost: count(audio.packets_lost), + jitter_ms: millis(audio.jitter_seconds).unwrap_or(0), + concealed_percent: concealed_percent(total, concealed), + } + }); + let video = remote.video.as_ref().map(|video| { + let source = track(&video.track); + let dropped = reading.delta( + &source, + Counter::FramesDropped, + Sample { + value: video.frames_dropped, + at_ms: video.at_ms, + }, + Width::Bits32, + ); + VideoReceiveStats { + fps: frames_per_second(video.fps), + width: side(video.width), + height: side(video.height), + bitrate_kbps: reading.kbps( + &source, + Counter::VideoBytes, + video.bytes_received, + video.at_ms, + ), + dropped_fps: dropped + .and_then(|(delta, interval)| per_second(delta, interval)) + .map(|rate| u8::try_from(rate.min(u64::from(MAX_STATS_FPS))).unwrap_or(0)), + packets_lost: count(video.packets_lost), + } + }); + out.push(RemoteStats { + connection: remote.connection, + identity: remote.identity.clone(), + audio, + video, + }); + } + out +} + +/// The share of the samples of one interval that WebRTC made up. `None` +/// when there was no interval or no sample. +fn concealed_percent(total: Option, concealed: Option) -> Option { + let (total, concealed) = (total?, concealed?); + if total == 0 { + return None; + } + let percent = (u128::from(concealed) * 100 / u128::from(total)).min(100); + u8::try_from(percent).ok() +} + +fn connections(reading: &mut Reading<'_>, raw: &[RawConnection]) -> Vec { + let mut out: Vec = Vec::new(); + for connection in raw { + if out.len() >= MAX_STATS_CONNECTIONS + || connection.connection > MAX_OTHER_CONNECTIONS + || out + .iter() + .any(|seen| seen.connection == connection.connection) + { + continue; + } + out.push(ConnectionStats { + connection: connection.connection, + outgoing_kbps: connection.outgoing_bits_per_second.and_then(kbps_from_bits), + send_kbps: link_kbps(reading, connection, Counter::BytesSent, |link| { + link.bytes_sent + }), + receive_kbps: link_kbps(reading, connection, Counter::BytesReceived, |link| { + link.bytes_received + }), + rtt_ms: connection.rtt_seconds.and_then(millis), + }); + } + out +} + +/// A connection's rate of one counter: the sum of its transports' rates, +/// each from that transport's own samples. Unknown when a transport that +/// the connection uses was not read, or when one has no rate yet, so a +/// missing transport never makes a total that is short or one that jumps. +/// Each transport's sample is kept for the next reading either way. +fn link_kbps( + reading: &mut Reading<'_>, + connection: &RawConnection, + counter: Counter, + bytes: fn(&RawLink) -> u64, +) -> Option { + let mut total = Some(0_u32); + let mut roles: Vec = Vec::new(); + for link in &connection.links { + if roles.contains(&link.role) { + continue; + } + roles.push(link.role); + let source = Source::Link(connection.connection, link.role); + let rate = reading.kbps(&source, counter, bytes(link), link.at_ms); + total = total + .zip(rate) + .map(|(sum, rate)| sum.saturating_add(rate).min(MAX_STATS_KBPS)); + } + total.filter(|_| connection.complete && !roles.is_empty()) +} + +#[cfg(test)] +mod tests; diff --git a/crates/call-worker/src/mapping/stats/tests.rs b/crates/call-worker/src/mapping/stats/tests.rs new file mode 100644 index 00000000..c3b69bb5 --- /dev/null +++ b/crates/call-worker/src/mapping/stats/tests.rs @@ -0,0 +1,481 @@ +use super::*; +use persephone_call_protocol::MAX_IDENTITY_BYTES; + +fn audio_in(bytes: u64) -> RawRemoteAudio { + RawRemoteAudio { + track: "TR_audio".to_owned(), + at_ms: 0, + level: 0.5, + bytes_received: bytes, + packets_received: 100, + packets_lost: 2, + jitter_seconds: 0.012, + total_samples: 0, + concealed_samples: 0, + } +} + +fn remote(identity: &str, audio: Option) -> RawRemote { + RawRemote { + connection: 0, + identity: identity.to_owned(), + audio, + video: None, + } +} + +fn mic(bytes: u64) -> RawOwnAudio { + RawOwnAudio { + track: "TR_mic".to_owned(), + at_ms: 0, + level: 1.0, + bytes_sent: bytes, + packets_sent: 5, + packets_lost: Some(-3), + jitter_seconds: Some(0.0004), + rtt_seconds: Some(0.0415), + } +} + +fn reading(at_ms: u64, bytes: u64) -> RawStats { + RawStats { + microphone: Some(RawOwnAudio { + at_ms, + ..mic(bytes) + }), + ..RawStats::default() + } +} + +fn bitrate(stats: &CallStats) -> Option { + stats + .microphone + .as_ref() + .and_then(|audio| audio.bitrate_kbps) +} + +/// GIVEN a counter that grows WHEN the delta is taken THEN it is the +/// growth; GIVEN no previous value THEN there is none. +#[test] +fn given_a_growing_counter_when_the_delta_is_taken_then_it_is_the_growth() { + assert_eq!(counter_delta(Some(10), 25, Width::Bits64), Some(15)); + assert_eq!(counter_delta(Some(10), 10, Width::Bits64), Some(0)); + assert_eq!(counter_delta(None, 25, Width::Bits64), None); +} + +/// GIVEN a counter that falls WHEN the delta is taken THEN it is a reset +/// and has no delta. +#[test] +fn given_a_counter_that_falls_when_the_delta_is_taken_then_it_is_a_reset() { + assert_eq!(counter_delta(Some(1000), 5, Width::Bits64), None); + // A small fall of a 32-bit counter is no wrap. + assert_eq!(counter_delta(Some(1000), 5, Width::Bits32), None); + // A fall from a 64-bit value beyond 32 bits is never a wrap. + assert_eq!(counter_delta(Some(1 << 40), 5, Width::Bits32), None); +} + +/// GIVEN a 32-bit counter near its top that comes back near zero WHEN the +/// delta is taken THEN it is the growth across the wrap, but a 64-bit +/// counter is not wrapped. +#[test] +fn given_a_32_bit_counter_wraps_when_the_delta_is_taken_then_it_counts_across() { + let top = u64::from(u32::MAX); + assert_eq!(counter_delta(Some(top - 4), 5, Width::Bits32), Some(10)); + assert_eq!(counter_delta(Some(top), 0, Width::Bits32), Some(1)); + assert_eq!(counter_delta(Some(top - 4), 5, Width::Bits64), None); +} + +/// GIVEN a zero interval WHEN a rate is made THEN there is none. +#[test] +fn given_a_zero_interval_when_a_rate_is_made_then_there_is_none() { + assert_eq!(per_second(10, 0), None); + assert_eq!(kbps(10, 0), None); + assert_eq!(per_second(10, 500), Some(20)); +} + +/// GIVEN bytes over an interval WHEN the bitrate is made THEN it is in +/// kbit/s, and a huge value stops at the bound. +#[test] +fn given_bytes_over_an_interval_when_the_bitrate_is_made_then_it_is_in_kbps() { + // 125 000 bytes in a second are 1000 kbit/s. + assert_eq!(kbps(125_000, 1000), Some(1000)); + assert_eq!(kbps(125_000, 2000), Some(500)); + assert_eq!(kbps(u64::MAX, 1), Some(MAX_STATS_KBPS)); +} + +/// GIVEN odd WebRTC numbers WHEN they are converted THEN each stays inside +/// its bound and a number that is not a number is unknown. +#[test] +fn given_odd_numbers_when_converted_then_they_stay_inside_their_bounds() { + assert_eq!(millis(0.0415), Some(42)); + assert_eq!(millis(1e9), Some(MAX_STATS_MS)); + assert_eq!(millis(-1.0), None); + assert_eq!(millis(f64::NAN), None); + assert_eq!(millis(f64::INFINITY), None); + assert_eq!(count(-5), 0); + assert_eq!(count(i64::MAX), u32::MAX); + assert_eq!(frames_per_second(29.6), 30); + assert_eq!(frames_per_second(1e9), MAX_STATS_FPS); + assert_eq!(frames_per_second(f64::NAN), 0); + assert_eq!(side(u32::MAX), MAX_STATS_SIDE); + assert_eq!(kbps_from_bits(2_500_000.0), Some(2500)); + assert_eq!(kbps_from_bits(1e300), Some(MAX_STATS_KBPS)); + assert_eq!(kbps_from_bits(f64::NAN), None); +} + +/// GIVEN the first reading WHEN it is made THEN no rate is known; GIVEN the +/// second a second later THEN the rate follows from the change. +#[test] +fn given_two_readings_when_made_then_the_second_has_the_rate() { + let mut book = StatsBook::default(); + let first = book.next(&reading(1000, 10_000)); + assert_eq!(bitrate(&first), None); + // Own values that need no earlier reading are there at once. + let audio = first.microphone.unwrap(); + assert_eq!(audio.level, 100); + assert_eq!(audio.packets_lost, Some(0), "a negative loss counts as 0"); + assert_eq!(audio.jitter_ms, Some(0)); + assert_eq!(audio.rtt_ms, Some(42)); + let second = book.next(&reading(2000, 10_000 + 4000)); + assert_eq!(bitrate(&second), Some(32)); + // Half a second later with the same growth doubles the rate. + let third = book.next(&reading(2500, 10_000 + 8000)); + assert_eq!(bitrate(&third), Some(64)); +} + +/// GIVEN a counter that was reset WHEN the next reading is made THEN that +/// reading has no rate and the one after has it again. +#[test] +fn given_a_reset_counter_when_read_then_one_reading_has_no_rate() { + let mut book = StatsBook::default(); + book.next(&reading(1000, 50_000)); + let after_reset = book.next(&reading(2000, 100)); + assert_eq!(bitrate(&after_reset), None); + let next = book.next(&reading(3000, 100 + 12_500)); + assert_eq!(bitrate(&next), Some(100)); +} + +/// GIVEN two readings at the same time WHEN the second is made THEN it has +/// no rate and the third still compares with the first. +#[test] +fn given_a_zero_interval_when_read_then_no_rate_and_the_baseline_stays() { + let mut book = StatsBook::default(); + book.next(&reading(1000, 0)); + let same = book.next(&reading(1000, 5000)); + assert_eq!(bitrate(&same), None); + let later = book.next(&reading(2000, 12_500)); + assert_eq!(bitrate(&later), Some(100)); +} + +/// GIVEN a reading with an earlier time WHEN it is made THEN it has no rate +/// and becomes the new baseline. +#[test] +fn given_time_going_back_when_read_then_no_rate_and_a_new_baseline() { + let mut book = StatsBook::default(); + book.next(&reading(5000, 1_000_000)); + let back = book.next(&reading(1000, 0)); + assert_eq!(bitrate(&back), None); + let next = book.next(&reading(2000, 12_500)); + assert_eq!(bitrate(&next), Some(100)); +} + +/// GIVEN the statistics were turned off and on WHEN the book is reset THEN +/// the first reading has no rate, however long the pause. +#[test] +fn given_a_reset_book_when_read_then_the_first_reading_has_no_rate() { + let mut book = StatsBook::default(); + book.next(&reading(1000, 0)); + book.reset(); + assert_eq!(bitrate(&book.next(&reading(60_000, 1_000_000))), None); +} + +/// GIVEN a track that stops and starts WHEN readings are made THEN the new +/// track has no rate until its second reading. +#[test] +fn given_a_track_that_goes_and_returns_when_read_then_its_rate_starts_again() { + let mut book = StatsBook::default(); + book.next(&reading(1000, 0)); + book.next(&RawStats::default()); + assert_eq!(bitrate(&book.next(&reading(3000, 99_000))), None); + assert_eq!( + bitrate(&book.next(&reading(4000, 99_000 + 125_000))), + Some(1000) + ); +} + +/// GIVEN remote audio that conceals samples WHEN read twice THEN the share +/// is of the samples of the last interval only. +#[test] +fn given_concealed_samples_when_read_then_the_share_is_of_the_last_interval() { + let mut book = StatsBook::default(); + let with = |at_ms, total, concealed| RawStats { + remotes: vec![remote( + "@a:example.org:D", + Some(RawRemoteAudio { + at_ms, + total_samples: total, + concealed_samples: concealed, + ..audio_in(0) + }), + )], + ..RawStats::default() + }; + let share = |stats: &CallStats| stats.remotes[0].audio.unwrap().concealed_percent; + assert_eq!(share(&book.next(&with(1000, 48_000, 40_000))), None); + assert_eq!(share(&book.next(&with(2000, 96_000, 40_000))), Some(0)); + assert_eq!(share(&book.next(&with(3000, 144_000, 52_000))), Some(25)); + // No samples in the interval: no share. + assert_eq!(share(&book.next(&with(4000, 144_000, 52_000))), None); + // More concealed than total is stopped at 100. + assert_eq!(share(&book.next(&with(5000, 144_100, 99_000))), Some(100)); +} + +/// GIVEN remote video that drops frames WHEN read twice THEN the drop rate +/// is per second. +#[test] +fn given_dropped_frames_when_read_then_the_rate_is_per_second() { + let mut book = StatsBook::default(); + let with = |at_ms, dropped| RawStats { + remotes: vec![RawRemote { + video: Some(RawRemoteVideo { + at_ms, + fps: 29.97, + width: 1280, + height: 720, + frames_dropped: dropped, + ..RawRemoteVideo::default() + }), + ..remote("@a:example.org:D", None) + }], + ..RawStats::default() + }; + let rate = |stats: &CallStats| stats.remotes[0].video.unwrap().dropped_fps; + assert_eq!(rate(&book.next(&with(1000, 7))), None); + assert_eq!(rate(&book.next(&with(3000, 17))), Some(5)); + let last = book.next(&with(4000, 1_000_000)); + assert_eq!(rate(&last), Some(MAX_STATS_FPS)); + assert_eq!(last.remotes[0].video.unwrap().fps, 30); +} + +/// GIVEN too many, repeated and invalid participants WHEN read THEN the +/// message holds only valid ones, each once, and at most the limit. +#[test] +fn given_bad_participants_when_read_then_only_valid_distinct_ones_stay() { + let mut raw = RawStats::default(); + raw.remotes.push(remote("", None)); + raw.remotes.push(remote("bad\nname", None)); + raw.remotes + .push(remote(&"x".repeat(MAX_IDENTITY_BYTES + 1), None)); + raw.remotes.push(RawRemote { + connection: MAX_OTHER_CONNECTIONS + 1, + ..remote("@far:example.org:D", None) + }); + raw.remotes.push(remote("@a:example.org:D", None)); + raw.remotes + .push(remote("@a:example.org:D", Some(audio_in(1)))); + raw.remotes.push(RawRemote { + connection: 2, + ..remote("@a:example.org:D", None) + }); + raw.remotes + .extend((0..MAX_PARTICIPANTS * 2).map(|i| remote(&format!("@u{i}:example.org:D"), None))); + let stats = StatsBook::default().next(&raw); + assert_eq!(stats.remotes.len(), MAX_PARTICIPANTS); + assert_eq!(stats.remotes[0].identity, "@a:example.org:D"); + assert!(stats.remotes[0].audio.is_none(), "the first entry wins"); + assert_eq!(stats.remotes[1].connection, 2); + // The message encodes and decodes: nothing the protocol refuses is left. + let message = persephone_call_protocol::FromWorker::Stats(stats); + assert_eq!( + persephone_call_protocol::FromWorker::decode(&message.encode()), + Ok(message) + ); +} + +fn link(role: LinkRole, at_ms: u64, sent: u64, received: u64) -> RawLink { + RawLink { + role, + at_ms, + bytes_sent: sent, + bytes_received: received, + } +} + +fn connection(number: u8, links: Vec, complete: bool) -> RawConnection { + RawConnection { + connection: number, + outgoing_bits_per_second: Some(3_000_000.0), + rtt_seconds: Some(0.02), + links, + complete, + } +} + +/// GIVEN connections that repeat or do not exist WHEN read THEN each real +/// one is there once and the rates follow the transport bytes. +#[test] +fn given_connections_when_read_then_rates_follow_the_transport_bytes() { + let one = |number, at_ms, sent, received| { + connection( + number, + vec![link(LinkRole::Single, at_ms, sent, received)], + true, + ) + }; + let raw = |at_ms, sent, received| RawStats { + connections: vec![ + one(0, at_ms, sent, received), + one(0, at_ms, 0, 0), + one(1, at_ms, sent, received), + one(MAX_OTHER_CONNECTIONS + 1, at_ms, 0, 0), + ], + ..RawStats::default() + }; + let mut book = StatsBook::default(); + let first = book.next(&raw(1000, 0, 0)); + assert_eq!(first.connections.len(), 2); + assert_eq!(first.connections[0].send_kbps, None); + assert_eq!(first.connections[0].outgoing_kbps, Some(3000)); + assert_eq!(first.connections[0].rtt_ms, Some(20)); + let second = book.next(&raw(2000, 250_000, 125_000)); + assert_eq!(second.connections[0].send_kbps, Some(2000)); + assert_eq!(second.connections[0].receive_kbps, Some(1000)); + assert_eq!(second.connections[1].connection, 1); +} + +/// GIVEN a participant that left WHEN readings go on THEN its counters are +/// forgotten, so the book holds no more than the reading shows. +#[test] +fn given_a_participant_that_left_when_read_then_its_counters_are_forgotten() { + let mut book = StatsBook::default(); + let both = RawStats { + remotes: vec![ + remote("@a:example.org:D", Some(audio_in(1))), + remote("@b:example.org:D", Some(audio_in(1))), + ], + ..RawStats::default() + }; + book.next(&both); + let held = book.counters.len(); + book.next(&RawStats { + remotes: vec![remote( + "@a:example.org:D", + Some(RawRemoteAudio { + at_ms: 1000, + ..audio_in(1) + }), + )], + ..RawStats::default() + }); + assert!(book.counters.len() < held); + assert!(book.counters.keys().all(|(source, _)| matches!( + source, + Source::Remote(0, identity, _) if identity == "@a:example.org:D" + ))); +} + +/// GIVEN a participant whose video moves from one track to another (the +/// camera after a screen share) WHEN read THEN the new track has no rate +/// until its second reading, however its counters compare with the old +/// track's. +#[test] +fn given_a_new_track_for_a_participant_when_read_then_no_rate_crosses_tracks() { + let mut book = StatsBook::default(); + let with = |track: &str, at_ms, bytes, dropped| RawStats { + remotes: vec![RawRemote { + video: Some(RawRemoteVideo { + track: track.to_owned(), + at_ms, + bytes_received: bytes, + frames_dropped: dropped, + ..RawRemoteVideo::default() + }), + ..remote("@a:example.org:D", None) + }], + ..RawStats::default() + }; + let video = |stats: CallStats| stats.remotes[0].video.unwrap(); + book.next(&with("TR_screen", 1000, 100_000, 3)); + let switched = video(book.next(&with("TR_camera", 2000, 250_000, 9))); + assert_eq!(switched.bitrate_kbps, None, "never compared with the share"); + assert_eq!(switched.dropped_fps, None); + let next = video(book.next(&with("TR_camera", 3000, 250_000 + 125_000, 10))); + assert_eq!(next.bitrate_kbps, Some(1000)); + assert_eq!(next.dropped_fps, Some(1)); + // The own microphone after a device change is a new track too. + book.next(&reading(4000, 10_000)); + let new_mic = book.next(&RawStats { + microphone: Some(RawOwnAudio { + track: "TR_mic_2".to_owned(), + at_ms: 5000, + ..mic(500_000) + }), + ..RawStats::default() + }); + assert_eq!(bitrate(&new_mic), None); +} + +/// GIVEN two tracks read at different times in one reading WHEN the rates +/// are made THEN each uses the time between its own two reads, so a slow +/// read of another track never changes them. +#[test] +fn given_tracks_read_at_different_times_when_rated_then_each_uses_its_own_interval() { + let mut book = StatsBook::default(); + let with = |mic_at, remote_at, bytes| RawStats { + microphone: Some(RawOwnAudio { + at_ms: mic_at, + ..mic(bytes) + }), + remotes: vec![remote( + "@a:example.org:D", + Some(RawRemoteAudio { + at_ms: remote_at, + ..audio_in(bytes) + }), + )], + ..RawStats::default() + }; + book.next(&with(1000, 1000, 0)); + let stats = book.next(&with(2000, 2700, 125_000)); + assert_eq!(bitrate(&stats), Some(1000), "one second for the microphone"); + assert_eq!( + stats.remotes[0].audio.unwrap().bitrate_kbps, + Some(588), + "1.7 seconds for the remote track" + ); +} + +/// GIVEN a connection with a publisher and a subscriber transport WHEN one +/// transport was not read THEN the totals are unknown in that reading and +/// in the next one, and never jump; the reading after has the true rate. +#[test] +fn given_a_transport_that_was_not_read_when_rated_then_the_totals_are_unknown() { + let mut book = StatsBook::default(); + let both = |at_ms, published, subscribed| RawStats { + connections: vec![connection( + 0, + vec![ + link(LinkRole::Publisher, at_ms, published, 0), + link(LinkRole::Subscriber, at_ms, subscribed, 0), + ], + true, + )], + ..RawStats::default() + }; + let send = |stats: CallStats| stats.connections[0].send_kbps; + assert_eq!(send(book.next(&both(1000, 100_000, 50_000))), None); + assert_eq!(send(book.next(&both(2000, 200_000, 60_000))), Some(880)); + // The publisher's read missed its deadline. + let short = RawStats { + connections: vec![connection( + 0, + vec![link(LinkRole::Subscriber, 3000, 70_000, 0)], + false, + )], + ..RawStats::default() + }; + assert_eq!(send(book.next(&short)), None, "a short total is unknown"); + // The publisher has no sample before, so no jump on its return. + assert_eq!(send(book.next(&both(4000, 400_000, 80_000))), None); + assert_eq!(send(book.next(&both(5000, 420_000, 90_000))), Some(240)); +} diff --git a/crates/call-worker/src/output.rs b/crates/call-worker/src/output.rs index 4f761339..f674427f 100644 --- a/crates/call-worker/src/output.rs +++ b/crates/call-worker/src/output.rs @@ -6,8 +6,13 @@ //! that still waits, so at most one picture per tile is held, and a picture //! never waits in front of a control message. The slot write never blocks. //! +//! - The call statistics (ADR-0066) go into one slot, apart from both. A +//! newer reading replaces the one that still waits. The writer writes it +//! after the control messages and a waiting picture of its round, so it +//! never delays them, and the slot write never blocks. +//! //! A small wake item in the control queue tells the writer that a picture -//! waits. If the queue is full, the writer is busy and looks at the slots +//! or a reading waits. If the queue is full, the writer is busy and looks at the slots //! anyway before it sleeps. use std::io::{self, Write}; @@ -15,7 +20,9 @@ use std::sync::{Arc, Mutex, PoisonError}; #[cfg(test)] use persephone_call_protocol::SCREEN_TILE; -use persephone_call_protocol::{FromWorker, VIDEO_TILES, write_message, write_video_frame}; +use persephone_call_protocol::{ + CallStats, FromWorker, VIDEO_TILES, write_message, write_video_frame, +}; use tokio::sync::mpsc::{self, WeakSender, error::TryRecvError}; use crate::video::rgba_len; @@ -84,10 +91,12 @@ impl Default for Slots { /// The own camera's tile. const OWN_TILE: u8 = 0; -/// The newest waiting picture of each tile. +/// The newest waiting picture of each tile, and the newest waiting +/// statistics reading. #[derive(Default)] pub struct VideoSlots { slots: Mutex, + stats: Mutex>, } impl VideoSlots { @@ -112,6 +121,19 @@ impl VideoSlots { valid } + /// Stores a statistics reading and replaces the one that waits. + fn put_stats(&self, stats: CallStats) { + *self.stats.lock().unwrap_or_else(PoisonError::into_inner) = Some(stats); + } + + /// Takes the waiting statistics reading. + fn take_stats(&self) -> Option { + self.stats + .lock() + .unwrap_or_else(PoisonError::into_inner) + .take() + } + /// Drops the picture that waits for a tile. A remote tile stays closed /// until the writer writes a `VideoStarted` queued after this clear. pub fn clear(&self, tile: u8) { @@ -219,6 +241,22 @@ impl Output { } } + /// Offers a statistics reading (ADR-0066). It never waits, and it + /// replaces a reading that has not gone out, so at most one waits and + /// no control message is held up by it. + pub fn offer_stats(&self, stats: CallStats) { + self.slots.put_stats(stats); + // A full queue means the writer is busy and will look at the slot. + let _ = self.queue.try_send(Item::Wake); + } + + /// Drops the statistics reading that waits, when the core turns the + /// statistics off (ADR-0066). A reading that the writer took before + /// this call can still go out; the core drops a reading while off. + pub fn clear_stats(&self) { + drop(self.slots.take_stats()); + } + /// Drops the picture that waits for a tile. Call it after the tile's /// producer has stopped and before `VideoStopped`. pub fn clear_picture(&self, tile: u8) { @@ -294,6 +332,13 @@ fn write_loop_with( } wrote_picture = true; } + // The newest statistics reading, after the control messages and the + // picture of this round. + if let Some(stats) = input.slots.take_stats() + && write_message(&mut out, &FromWorker::Stats(stats)).is_err() + { + return false; + } // Diagnostic records only after every waiting control message and // picture, a few at a time, so neither waits long behind them, and // a steady stream of pictures does not stop them (ADR-0058). @@ -578,6 +623,107 @@ mod tests { )); } + fn stats_with_level(level: u8) -> CallStats { + CallStats { + microphone: Some(persephone_call_protocol::AudioSendStats { + level, + bitrate_kbps: None, + packets_sent: 0, + packets_lost: None, + jitter_ms: None, + rtt_ms: None, + }), + ..CallStats::default() + } + } + + /// GIVEN several statistics readings before the writer runs WHEN it runs + /// THEN only the newest goes out, after the control messages and the + /// waiting picture. + #[test] + fn given_stats_pile_up_when_written_then_only_the_newest_goes_after_the_rest() { + let (output, receiver) = Output::new(); + let sink = output.pictures(); + for level in 1..=5 { + output.offer_stats(stats_with_level(level)); + } + sink.put(0, 0, 1, 1, picture(1, 1, 3)); + output + .queue + .try_send(output.slots.queued(FromWorker::Left)) + .unwrap(); + drop(sink); + drop(output); + let mut wire = Vec::new(); + assert!(write_loop(&mut wire, receiver)); + let items = read_all(wire); + assert_eq!(items.len(), 3); + assert_eq!(items[0], WorkerItem::Message(FromWorker::Left)); + assert!(matches!(items[1], WorkerItem::Video { tile: 0, .. })); + assert_eq!( + items[2], + WorkerItem::Message(FromWorker::Stats(stats_with_level(5))) + ); + } + + /// GIVEN a reading that waits WHEN the statistics go off before the + /// writer runs THEN the reading is not written, and a reading offered + /// after that goes out. + #[test] + fn given_a_waiting_reading_when_stats_go_off_then_it_is_not_written() { + let (output, receiver) = Output::new(); + output.offer_stats(stats_with_level(3)); + output.clear_stats(); + output + .queue + .try_send(output.slots.queued(FromWorker::Left)) + .unwrap(); + drop(output); + let mut wire = Vec::new(); + assert!(write_loop(&mut wire, receiver)); + assert_eq!(read_all(wire), vec![WorkerItem::Message(FromWorker::Left)]); + + let (output, receiver) = Output::new(); + output.offer_stats(stats_with_level(3)); + output.clear_stats(); + output.offer_stats(stats_with_level(4)); + drop(output); + let mut wire = Vec::new(); + assert!(write_loop(&mut wire, receiver)); + assert_eq!( + read_all(wire), + vec![WorkerItem::Message(FromWorker::Stats(stats_with_level(4)))] + ); + } + + /// GIVEN a full control queue WHEN a reading is offered THEN the offer + /// does not block and takes no place in the queue, and the reading goes + /// out after the queue drains. + #[test] + fn given_full_queue_when_stats_offered_then_it_does_not_block_or_queue() { + let (output, receiver) = Output::new(); + for _ in 0..OUTPUT_CAPACITY { + output + .queue + .try_send(output.slots.queued(FromWorker::Left)) + .unwrap(); + } + output.offer_stats(stats_with_level(9)); + assert_eq!( + output.queue.max_capacity() - output.queue.capacity(), + OUTPUT_CAPACITY + ); + drop(output); + let mut wire = Vec::new(); + assert!(write_loop(&mut wire, receiver)); + let items = read_all(wire); + assert_eq!(items.len(), OUTPUT_CAPACITY + 1); + assert_eq!( + items.last(), + Some(&WorkerItem::Message(FromWorker::Stats(stats_with_level(9)))) + ); + } + /// GIVEN pictures for several tiles WHEN the writer runs THEN the tiles take /// turns, starting after the one served last. #[test] diff --git a/crates/call-worker/src/session.rs b/crates/call-worker/src/session.rs index e4ab59b7..5fcd4609 100644 --- a/crates/call-worker/src/session.rs +++ b/crates/call-worker/src/session.rs @@ -20,8 +20,8 @@ use livekit::{ prelude::{ AudioProcessingOptions, LocalAudioTrack, LocalTrack, LocalTrackPublication, LocalVideoTrack, Participant, PlatformAudio, PlayoutDeviceId, RecordingDeviceId, - RemoteAudioTrack, RemoteParticipant, RemoteTrack, RemoteTrackPublication, TrackKind, - TrackSid, TrackSource, + RemoteAudioTrack, RemoteParticipant, RemoteTrack, RemoteTrackPublication, RemoteVideoTrack, + TrackKind, TrackSid, TrackSource, }, rtc_engine::EngineError, webrtc::{ @@ -49,6 +49,8 @@ use tokio::time::{Instant, MissedTickBehavior, interval}; use tokio_stream::StreamExt; use zeroize::Zeroizing; +mod stats_probe; + use crate::camera::{self, CapturedFrame, Format}; use crate::containment; use crate::mapping::{ @@ -67,6 +69,7 @@ use crate::video::{ fit_within_box, quarter_turns, rgba_len, }; use crate::{EXIT_DONE, EXIT_FAILED, Input}; +use stats_probe::{Sources, StatsProbe}; /// Element Call's key ring size (livekit-client keyringSize). const KEY_RING_SIZE: i32 = 256; @@ -259,6 +262,8 @@ pub async fn run(first: ToWorker, input: &mut Receiver, output: &Output) let (connect_tx, connect_done) = mpsc::channel::(usize::from(MAX_OTHER_CONNECTIONS)); // At most one sound level measurement runs, so one result can wait. let (sound_tx, mut sound_done) = mpsc::channel::>(1); + // The same for the statistics read (ADR-0066). + let (stats_tx, mut stats_done) = mpsc::channel(1); let mut others_inbox = OtherInbox { events: OtherEvents::default(), connected: connect_done, @@ -295,6 +300,7 @@ pub async fn run(first: ToWorker, input: &mut Receiver, output: &Output) playout: Playout::new(volume), microphone, sound: SoundProbe::new(sound_tx), + stats: StatsProbe::new(stats_tx), }; // Tracks subscribed during the connect get the volume now; later ones // when their subscription is handled. @@ -320,6 +326,7 @@ pub async fn run(first: ToWorker, input: &mut Receiver, output: &Output) &mut others_inbox, &mut tracker, &mut sound_done, + &mut stats_done, ) .await } @@ -1066,6 +1073,8 @@ struct Call<'a> { /// The level meters' measurement of the own and received sound /// (ADR-0055, ADR-0059). sound: SoundProbe, + /// The statistics read while the core asks for them (ADR-0066). + stats: StatsProbe, } /// Measures the own and the received sound for the level meters (ADR-0055, @@ -2012,6 +2021,7 @@ impl Call<'_> { if let Some(task) = self.sound.task.take() { task.abort(); } + self.stats.shutdown(); open_done.close(); while let Ok(done) = open_done.try_recv() { if let Ok(opened) = done.result { @@ -2587,6 +2597,88 @@ impl Call<'_> { ); } + /// Starts a read of the statistics when they are on and one is due. + fn measure_stats(&mut self) { + let Self { + stats, + room, + others, + publication, + .. + } = self; + stats.tick(Instant::now(), || { + let mut sources = Sources { + one_connection: room.is_single_peer_connection_active(), + microphone: match publication.track() { + Some(LocalTrack::Audio(track)) => Some(track), + _ => None, + }, + ..Sources::default() + }; + for local in room.local_participant().track_publications().values() { + let Some(LocalTrack::Video(track)) = local.track() else { + continue; + }; + match local.source() { + TrackSource::Camera => sources.camera = Some(track), + TrackSource::Screenshare => sources.screen = Some(track), + _ => {} + } + } + let rooms = std::iter::once((0, &**room)).chain(others.open_indexed()); + let mut participants = 0; + for (connection, remote_room) in rooms { + for (identity, participant) in remote_room.remote_participants() { + if participants >= MAX_PARTICIPANTS { + return sources; + } + let identity = identity.to_string(); + if !valid_identity(&identity) { + continue; + } + participants += 1; + // One microphone, and the camera before a screen share. + // The smallest track id breaks a tie, so the reads + // follow one track while it stays. When the choice + // moves to another track, the book keys counters by + // track ID, so the new track starts without a rate. + let mut audio: Option<(TrackSid, RemoteAudioTrack)> = None; + let mut video: Option<(bool, TrackSid, RemoteVideoTrack)> = None; + for publication in participant.track_publications().values() { + let sid = publication.sid(); + match (publication.track(), publication.source()) { + (Some(RemoteTrack::Audio(track)), TrackSource::Microphone) => { + if audio.as_ref().is_none_or(|(have, _)| sid < *have) { + audio = Some((sid, track)); + } + } + (Some(RemoteTrack::Video(track)), source) => { + let camera = source == TrackSource::Camera; + let better = video.as_ref().is_none_or(|(have_camera, have, _)| { + (camera, std::cmp::Reverse(&sid)) + > (*have_camera, std::cmp::Reverse(have)) + }); + if better { + video = Some((camera, sid, track)); + } + } + _ => {} + } + } + if let Some((_, track)) = audio { + sources + .remote_audio + .push((connection, identity.clone(), track)); + } + if let Some((_, _, track)) = video { + sources.remote_video.push((connection, identity, track)); + } + } + } + sources + }); + } + /// Tells the core whether a remote participant's microphone is muted. async fn send_muted( &self, @@ -2845,6 +2937,10 @@ impl Call<'_> { crate::diagnostics::global().set_on(on); Ok(Vec::new()) } + ToWorker::SetStats { on } => { + self.stats.set(on); + Ok(Vec::new()) + } ToWorker::SetCamera { on: true, remote } => { // The remote that came with this command, taken now so it // cannot go to another one: the camera channel gives them @@ -3124,6 +3220,7 @@ async fn event_loop( others: &mut OtherInbox, tracker: &mut SpeakingTracker, sound_done: &mut Receiver>, + stats_done: &mut Receiver<(u64, Option)>, ) -> End { let mut tick = interval(SPEAKING_TICK); tick.set_missed_tick_behavior(MissedTickBehavior::Delay); @@ -3178,10 +3275,18 @@ async fn event_loop( return End::Left; } Some(Input::Message(message)) => { + // The off also drops a reading that waits in the output + // slot. A reading that the writer took already can still + // be written after the off; the core drops it, because + // its switch is off then (ADR-0066). + let stats_off = matches!(message, ToWorker::SetStats { on: false }); match call.handle_command(message).await { Ok(reply) => outgoing.extend(reply), Err(code) => return End::Failed(code), } + if stats_off { + output.clear_stats(); + } } Some(Input::Bad) => return End::Failed(FailureCode::Protocol), }, @@ -3208,7 +3313,17 @@ async fn event_loop( Some(levels) = sound_done.recv() => { outgoing.extend(call.sound.end(levels)); } - _ = tick.tick() => call.measure_sound(), + Some((generation, raw)) = stats_done.recv() => { + // Never queued: the newest reading waits in a slot, and the + // control messages go out before it. + if let Some(FromWorker::Stats(stats)) = call.stats.end(generation, raw) { + output.offer_stats(stats); + } + } + _ = tick.tick() => { + call.measure_sound(); + call.measure_stats(); + } } outgoing.extend(tracker.poll(Instant::now().into_std())); let disconnected = outgoing.iter().any(|message| { diff --git a/crates/call-worker/src/session/stats_probe.rs b/crates/call-worker/src/session/stats_probe.rs new file mode 100644 index 00000000..84993839 --- /dev/null +++ b/crates/call-worker/src/session/stats_probe.rs @@ -0,0 +1,902 @@ +//! Reads the call's WebRTC statistics for the "technical details" panel +//! (ADR-0066). +//! +//! Like [`super::SoundProbe`] it runs one read at a time, on its own task and +//! under a deadline, so the event loop never waits for it. It reads only +//! while the core has turned the statistics on, and at most once a second. +//! The task gives back plain numbers (`RawStats`); `mapping::stats` makes +//! the message from them. Nothing here keeps a track handle, an address or a +//! name: only the numbers that the message carries, and each track's ID with +//! the time of its read, leave the parse functions. The ID keys the track's +//! counters in the worker and never leaves it. + +use std::collections::{BTreeSet, HashMap}; +use std::future::Future; +use std::pin::Pin; +use std::time::Duration; + +use livekit::{ + prelude::{LocalAudioTrack, LocalVideoTrack, RemoteAudioTrack, RemoteVideoTrack}, + webrtc::stats::{QualityLimitationReason, RtcStats}, +}; +use persephone_call_protocol::{FromWorker, MAX_OTHER_CONNECTIONS, QualityLimit}; +use tokio::sync::mpsc; +use tokio::task::JoinHandle; +use tokio::time::Instant; + +use super::read_all; +use crate::mapping::stats::{ + LinkRole, RawConnection, RawLink, RawOwnAudio, RawOwnVideo, RawRemote, RawRemoteAudio, + RawRemoteVideo, RawStats, StatsBook, +}; + +/// The shortest time between two reads. +pub const STATS_INTERVAL: Duration = Duration::from_secs(1); +/// The time one read has for all its statistics. It is shorter than +/// [`STATS_TIMEOUT`], so the task reports what it has. +const STATS_READ_BUDGET: Duration = Duration::from_millis(700); +/// The longest one read may take altogether. +const STATS_TIMEOUT: Duration = Duration::from_millis(900); +const _: () = assert!(STATS_READ_BUDGET.as_millis() < STATS_TIMEOUT.as_millis()); +const _: () = assert!(STATS_TIMEOUT.as_millis() < STATS_INTERVAL.as_millis()); + +/// What one read looks at. The tracks are cheap handles; at most one audio +/// and one video track of each remote participant, so at most +/// `2 * MAX_PARTICIPANTS` remote reads and three own ones. +#[derive(Default)] +pub struct Sources { + /// The own room sends and receives on one peer connection (LiveKit's + /// single peer connection), so its own and remote tracks read the same + /// transport, which is counted once. + pub one_connection: bool, + pub microphone: Option, + pub camera: Option, + pub screen: Option, + pub remote_audio: Vec<(u8, String, RemoteAudioTrack)>, + pub remote_video: Vec<(u8, String, RemoteVideoTrack)>, +} + +/// Which track a read is of. +enum ReadKind { + Microphone, + Camera, + Screen, + RemoteAudio(u8, String), + RemoteVideo(u8, String), +} + +/// The reading of one track: its statistics (none when they could not be +/// read), its track ID, and the time the read finished on the probe's +/// monotonic clock, which is the time of its counters. libwebrtc may answer +/// from a report it made up to 50 ms before, and its answer reaches the +/// probe a little later, so a rate is off by those delays' change between +/// two reads: a few percent of a one-second interval, which the next +/// interval gives back. The records' own `timestamp` is not used: by default +/// it comes from the system clock, which can step (`media_config.h`), and a +/// step would give a wrong rate of any size. +struct Read { + kind: ReadKind, + track: String, + at_ms: u64, + stats: Vec, +} + +impl Read { + fn new(kind: ReadKind, track: String, base: std::time::Instant, stats: Vec) -> Self { + Self { + kind, + track, + at_ms: since(base), + stats, + } + } +} + +/// Milliseconds since `base`. +fn since(base: std::time::Instant) -> u64 { + u64::try_from(base.elapsed().as_millis()).unwrap_or(u64::MAX) +} + +/// The transports a read needs: the own room's publisher when an own track +/// is read, and each connection's subscriber when one of its remote tracks +/// is read. +#[derive(Default)] +struct Asked { + own: bool, + remote: BTreeSet, +} + +type Job = Pin + Send>>; + +/// One read's report. Dropping it sends the numbers, or `None`, so the task +/// reports once however it ends. Only one read runs and the slot is freed +/// only by its report, so the channel has room. +struct Report { + done: mpsc::Sender<(u64, Option)>, + generation: u64, + stats: Option, +} + +impl Drop for Report { + fn drop(&mut self) { + let _ = self.done.try_send((self.generation, self.stats.take())); + } +} + +/// Reads the statistics while they are on. +pub struct StatsProbe { + done: mpsc::Sender<(u64, Option)>, + on: bool, + /// Numbers the reads, so the report of a read that was stopped never + /// frees the slot of a newer one. + generation: u64, + task: Option>, + started: Option, + /// The clock of the readings: they count from here. + base: std::time::Instant, + book: StatsBook, +} + +impl StatsProbe { + pub fn new(done: mpsc::Sender<(u64, Option)>) -> Self { + Self { + done, + on: false, + generation: 0, + task: None, + started: None, + base: std::time::Instant::now(), + book: StatsBook::default(), + } + } + + /// Turns the reads on or off (`SetStats`). Turning them on starts a new + /// series: the first reading has no rates. The time of the last start is + /// kept, so turning them off and on never reads more than once a second. + pub fn set(&mut self, on: bool) { + if on == self.on { + return; + } + self.on = on; + self.generation += 1; + self.book.reset(); + // A read that runs ends by its deadline and reports; its report is + // dropped by its number. The slot is freed only by that report. + } + + /// Stops a read that runs, for the end of the call. + pub fn shutdown(&mut self) { + self.on = false; + self.generation += 1; + if let Some(task) = self.task.take() { + task.abort(); + } + } + + /// Starts a read when they are on, none runs and a second has gone since + /// the last start. `sources` is only called then. + pub fn tick(&mut self, now: Instant, sources: impl FnOnce() -> Sources) { + if !self.on || self.task.is_some() { + return; + } + if self + .started + .is_some_and(|at| now.saturating_duration_since(at) < STATS_INTERVAL) + { + return; + } + self.started = Some(now); + let done = self.done.clone(); + let generation = self.generation; + let base = self.base; + let sources = sources(); + self.task = Some(tokio::spawn(async move { + let mut report = Report { + done, + generation, + stats: None, + }; + report.stats = tokio::time::timeout(STATS_TIMEOUT, read(sources, base)) + .await + .ok(); + })); + } + + /// A read reported, so the slot is free. The message to send, when the + /// read belongs to the current series and finished. + pub fn end(&mut self, generation: u64, stats: Option) -> Option { + self.task = None; + if generation != self.generation { + return None; + } + stats.map(|raw| FromWorker::Stats(self.book.next(&raw))) + } +} + +/// Reads every track at once, each under one deadline. +async fn read(sources: Sources, base: std::time::Instant) -> RawStats { + let deadline = Instant::now() + STATS_READ_BUDGET; + let one_connection = sources.one_connection; + let mut asked = Asked::default(); + let mut jobs: Vec = Vec::new(); + if let Some(track) = sources.microphone { + asked.own = true; + let sid = track.sid().to_string(); + jobs.push(Box::pin(async move { + let stats = track.get_stats().await.unwrap_or_default(); + Read::new(ReadKind::Microphone, sid, base, stats) + })); + } + for (kind, track) in [ + (ReadKind::Camera, sources.camera), + (ReadKind::Screen, sources.screen), + ] { + let Some(track) = track else { + continue; + }; + asked.own = true; + let sid = track.sid().to_string(); + jobs.push(Box::pin(async move { + let stats = track.get_stats().await.unwrap_or_default(); + Read::new(kind, sid, base, stats) + })); + } + for (connection, identity, track) in sources.remote_audio { + asked.remote.insert(connection); + let sid = track.sid().to_string(); + jobs.push(Box::pin(async move { + let stats = track.get_stats().await.unwrap_or_default(); + Read::new( + ReadKind::RemoteAudio(connection, identity), + sid, + base, + stats, + ) + })); + } + for (connection, identity, track) in sources.remote_video { + asked.remote.insert(connection); + let sid = track.sid().to_string(); + jobs.push(Box::pin(async move { + let stats = track.get_stats().await.unwrap_or_default(); + Read::new( + ReadKind::RemoteVideo(connection, identity), + sid, + base, + stats, + ) + })); + } + let reads = read_all(deadline, jobs).await.into_iter().flatten(); + assemble(&asked, one_connection, reads) +} + +/// Makes the raw reading from what the reads gave. A track whose read did +/// not finish is left out. `one_connection` says that the own room's tracks +/// all use one transport (see [`Sources::one_connection`]). A connection +/// whose needed transport (see [`Asked`]) no read gave is not complete. +fn assemble(asked: &Asked, one_connection: bool, reads: impl Iterator) -> RawStats { + let mut raw = RawStats::default(); + // The first transport of the own tracks (the publisher) and of the + // remote tracks of each connection (the subscriber). Each track's + // statistics hold only its own streams and the transport they use. + let mut publisher: Option = None; + let mut subscribers: HashMap = HashMap::new(); + let mut remotes: HashMap<(u8, String), RawRemote> = HashMap::new(); + for read in reads { + let found = link(&read); + match &read.kind { + ReadKind::Microphone => { + raw.microphone = own_audio(&read); + publisher = publisher.or(found); + } + ReadKind::Camera => { + raw.camera = own_video(&read); + publisher = publisher.or(found); + } + ReadKind::Screen => { + raw.screen = own_video(&read); + publisher = publisher.or(found); + } + ReadKind::RemoteAudio(connection, identity) => { + if let Some(found) = found { + subscribers.entry(*connection).or_insert(found); + } + remote(&mut remotes, *connection, identity).audio = remote_audio(&read); + } + ReadKind::RemoteVideo(connection, identity) => { + if let Some(found) = found { + subscribers.entry(*connection).or_insert(found); + } + remote(&mut remotes, *connection, identity).video = remote_video(&read); + } + } + } + raw.remotes = remotes.into_values().collect(); + raw.remotes + .sort_by(|a, b| (a.connection, &a.identity).cmp(&(b.connection, &b.identity))); + raw.connections = (0..=MAX_OTHER_CONNECTIONS) + .filter_map(|connection| { + let subscriber = subscribers.get(&connection); + let remote_asked = asked.remote.contains(&connection); + let links: Vec<(LinkRole, Option<&Link>, bool)> = match connection { + // One peer connection: every read of the room saw the same + // transport, so any one of them gives it. + 0 if one_connection => vec![( + LinkRole::Single, + publisher.as_ref().or(subscriber), + asked.own || remote_asked, + )], + 0 => vec![ + (LinkRole::Publisher, publisher.as_ref(), asked.own), + (LinkRole::Subscriber, subscriber, remote_asked), + ], + _ => vec![(LinkRole::Subscriber, subscriber, remote_asked)], + }; + connection_stats(connection, &links) + }) + .collect(); + raw +} + +fn remote<'a>( + remotes: &'a mut HashMap<(u8, String), RawRemote>, + connection: u8, + identity: &str, +) -> &'a mut RawRemote { + remotes + .entry((connection, identity.to_owned())) + .or_insert_with(|| RawRemote { + connection, + identity: identity.to_owned(), + audio: None, + video: None, + }) +} + +/// The numbers of one peer connection's transport and its selected pair of +/// addresses, and the time of the read that gave them. The addresses +/// themselves are never read. +#[derive(Clone, Debug, Default, PartialEq)] +struct Link { + at_ms: u64, + bytes_sent: u64, + bytes_received: u64, + outgoing_bits_per_second: Option, + rtt_seconds: Option, +} + +fn link(read: &Read) -> Option { + let stats = &read.stats; + let mut transports = stats.iter().filter_map(|stat| match stat { + RtcStats::Transport(transport) => Some(transport), + _ => None, + }); + let transport = transports.next()?; + let selected = stats.iter().find_map(|stat| match stat { + RtcStats::CandidatePair(pair) + if pair.rtc.id == transport.transport.selected_candidate_pair_id => + { + Some(&pair.candidate_pair) + } + _ => None, + }); + Some(Link { + at_ms: read.at_ms, + bytes_sent: transport.transport.bytes_sent, + bytes_received: transport.transport.bytes_received, + outgoing_bits_per_second: selected + .map(|pair| pair.available_outgoing_bitrate) + .filter(|rate| *rate > 0.0), + rtt_seconds: selected + .map(|pair| pair.current_round_trip_time) + .filter(|rtt| *rtt > 0.0), + }) +} + +/// The connection's numbers from its transports (`role`, the link a read +/// gave, whether a read needed it): each transport's bytes, the estimate of +/// the outgoing bandwidth, and the round-trip time. `None` when no +/// transport was read. Not complete when a needed transport is missing. +fn connection_stats( + connection: u8, + transports: &[(LinkRole, Option<&Link>, bool)], +) -> Option { + let read: Vec<(LinkRole, &Link)> = transports + .iter() + .filter_map(|(role, link, _)| link.map(|link| (*role, link))) + .collect(); + if read.is_empty() { + return None; + } + Some(RawConnection { + connection, + outgoing_bits_per_second: read + .iter() + .find_map(|(_, link)| link.outgoing_bits_per_second), + rtt_seconds: read.iter().find_map(|(_, link)| link.rtt_seconds), + links: read + .iter() + .map(|(role, link)| RawLink { + role: *role, + at_ms: link.at_ms, + bytes_sent: link.bytes_sent, + bytes_received: link.bytes_received, + }) + .collect(), + complete: transports + .iter() + .all(|(_, link, needed)| link.is_some() || !needed), + }) +} + +fn own_audio(read: &Read) -> Option { + let stats = &read.stats; + let mut audio: Option = None; + for stat in stats { + if let RtcStats::OutboundRtp(outbound) = stat + && outbound.stream.kind == "audio" + { + let audio = audio.get_or_insert_with(|| RawOwnAudio { + track: read.track.clone(), + at_ms: read.at_ms, + ..RawOwnAudio::default() + }); + audio.bytes_sent = audio.bytes_sent.saturating_add(outbound.sent.bytes_sent); + audio.packets_sent = audio + .packets_sent + .saturating_add(outbound.sent.packets_sent); + } + } + let audio = audio.as_mut()?; + for stat in stats { + match stat { + RtcStats::MediaSource(source) if source.source.kind == "audio" => { + audio.level = audio.level.max(source.audio.audio_level); + } + // What the far end reports of our stream. + RtcStats::RemoteInboundRtp(far) if far.stream.kind == "audio" => { + audio.packets_lost = Some(far.received.packets_lost); + audio.jitter_seconds = Some(far.received.jitter); + audio.rtt_seconds = Some(far.remote_inbound.round_trip_time); + } + _ => {} + } + } + Some(audio.clone()) +} + +fn limit(reason: QualityLimitationReason) -> QualityLimit { + match reason { + QualityLimitationReason::None => QualityLimit::None, + QualityLimitationReason::Cpu => QualityLimit::Cpu, + QualityLimitationReason::Bandwidth => QualityLimit::Bandwidth, + QualityLimitationReason::Other => QualityLimit::Other, + } +} + +/// The own video track: the bytes of every layer, and the size, frame rate +/// and limit of the largest one. +fn own_video(read: &Read) -> Option { + let stats = &read.stats; + let mut video: Option = None; + let mut largest = 0_u64; + for stat in stats { + let RtcStats::OutboundRtp(outbound) = stat else { + continue; + }; + if outbound.stream.kind != "video" { + continue; + } + let size = + u64::from(outbound.outbound.frame_width) * u64::from(outbound.outbound.frame_height); + match video.as_mut() { + None => { + largest = size; + video = Some(RawOwnVideo { + track: read.track.clone(), + at_ms: read.at_ms, + fps: outbound.outbound.frames_per_second, + width: outbound.outbound.frame_width, + height: outbound.outbound.frame_height, + bytes_sent: outbound.sent.bytes_sent, + limit: limit(outbound.outbound.quality_limitation_reason), + packets_lost: None, + }); + } + Some(video) => { + video.bytes_sent = video.bytes_sent.saturating_add(outbound.sent.bytes_sent); + if size > largest { + largest = size; + video.fps = outbound.outbound.frames_per_second; + video.width = outbound.outbound.frame_width; + video.height = outbound.outbound.frame_height; + video.limit = limit(outbound.outbound.quality_limitation_reason); + } + } + } + } + let video = video.as_mut()?; + for stat in stats { + if let RtcStats::RemoteInboundRtp(far) = stat + && far.stream.kind == "video" + { + video.packets_lost = Some( + video + .packets_lost + .unwrap_or(0) + .saturating_add(far.received.packets_lost.max(0)), + ); + } + } + Some(video.clone()) +} + +fn remote_audio(read: &Read) -> Option { + let mut audio: Option = None; + for stat in &read.stats { + let RtcStats::InboundRtp(inbound) = stat else { + continue; + }; + if inbound.stream.kind != "audio" { + continue; + } + let audio = audio.get_or_insert_with(|| RawRemoteAudio { + track: read.track.clone(), + at_ms: read.at_ms, + ..RawRemoteAudio::default() + }); + audio.level = audio.level.max(inbound.inbound.audio_level); + audio.bytes_received = audio + .bytes_received + .saturating_add(inbound.inbound.bytes_received); + audio.packets_received = audio + .packets_received + .saturating_add(inbound.received.packets_received); + audio.packets_lost = audio + .packets_lost + .saturating_add(inbound.received.packets_lost); + audio.jitter_seconds = audio.jitter_seconds.max(inbound.received.jitter); + audio.total_samples = audio + .total_samples + .saturating_add(inbound.inbound.total_samples_received); + audio.concealed_samples = audio + .concealed_samples + .saturating_add(inbound.inbound.concealed_samples); + } + audio +} + +fn remote_video(read: &Read) -> Option { + let mut video: Option = None; + for stat in &read.stats { + let RtcStats::InboundRtp(inbound) = stat else { + continue; + }; + if inbound.stream.kind != "video" { + continue; + } + let video = video.get_or_insert_with(|| RawRemoteVideo { + track: read.track.clone(), + at_ms: read.at_ms, + ..RawRemoteVideo::default() + }); + video.fps = video.fps.max(inbound.inbound.frames_per_second); + video.width = video.width.max(inbound.inbound.frame_width); + video.height = video.height.max(inbound.inbound.frame_height); + video.bytes_received = video + .bytes_received + .saturating_add(inbound.inbound.bytes_received); + video.frames_dropped = video + .frames_dropped + .saturating_add(u64::from(inbound.inbound.frames_dropped)); + video.packets_lost = video + .packets_lost + .saturating_add(inbound.received.packets_lost); + } + video +} + +#[cfg(test)] +mod tests { + use super::*; + + fn probe() -> (StatsProbe, mpsc::Receiver<(u64, Option)>) { + let (tx, rx) = mpsc::channel(1); + (StatsProbe::new(tx), rx) + } + + /// Starts a read at `now` and counts the calls of the source builder. + fn tick(probe: &mut StatsProbe, now: Instant) -> usize { + let mut built = 0; + probe.tick(now, || { + built += 1; + Sources::default() + }); + built + } + + /// GIVEN the statistics are off WHEN a tick comes THEN nothing is built + /// or read. + #[tokio::test] + async fn given_statistics_off_when_ticked_then_nothing_is_read() { + let (mut probe, mut reports) = probe(); + assert_eq!(tick(&mut probe, Instant::now()), 0); + assert!(reports.try_recv().is_err()); + } + + /// GIVEN the statistics are on WHEN ticks come THEN one read starts, no + /// other starts while it runs or within a second, and the report frees + /// the slot and gives one message. + #[tokio::test] + async fn given_statistics_on_when_ticked_then_one_read_runs_at_most_once_a_second() { + let (mut probe, mut reports) = probe(); + probe.set(true); + let start = Instant::now(); + assert_eq!(tick(&mut probe, start), 1); + assert_eq!(tick(&mut probe, start), 0, "one read at a time"); + let (generation, raw) = reports.recv().await.unwrap(); + let message = probe.end(generation, raw); + assert!(matches!(message, Some(FromWorker::Stats(_)))); + assert_eq!( + tick(&mut probe, start + Duration::from_millis(900)), + 0, + "less than a second since the last start" + ); + assert_eq!(tick(&mut probe, start + STATS_INTERVAL), 1); + probe.shutdown(); + } + + /// GIVEN a read that finished WHEN the statistics go off and on again + /// within a second THEN no read starts before a second since the last + /// start, and the next one has no rates. + #[tokio::test] + async fn given_a_quick_off_and_on_when_ticked_then_reads_stay_a_second_apart() { + let (mut probe, mut reports) = probe(); + probe.set(true); + let start = Instant::now(); + assert_eq!(tick(&mut probe, start), 1); + let (generation, raw) = reports.recv().await.unwrap(); + assert!(probe.end(generation, raw).is_some()); + probe.set(false); + probe.set(true); + assert_eq!( + tick(&mut probe, start + Duration::from_millis(100)), + 0, + "the toggle keeps the time of the last start" + ); + assert_eq!(tick(&mut probe, start + STATS_INTERVAL), 1); + probe.shutdown(); + } + + /// GIVEN a read that runs WHEN the statistics go off and on again THEN + /// the old read's report gives no message and the slot stays taken until + /// it reports, so two reads never run together. + #[tokio::test] + async fn given_a_switch_during_a_read_when_it_reports_then_the_old_report_is_dropped() { + let (mut probe, mut reports) = probe(); + probe.set(true); + let start = Instant::now(); + assert_eq!(tick(&mut probe, start), 1); + probe.set(false); + probe.set(true); + assert_eq!(tick(&mut probe, start + STATS_INTERVAL), 0, "still reading"); + let (generation, raw) = reports.recv().await.unwrap(); + assert!(probe.end(generation, raw).is_none(), "an old series"); + assert_eq!( + tick(&mut probe, start + STATS_INTERVAL), + 1, + "a new one starts" + ); + probe.shutdown(); + } + + /// GIVEN a read that did not finish WHEN it reports nothing THEN no + /// message goes and the next read can start. + #[tokio::test] + async fn given_a_read_that_did_not_finish_then_no_message_and_the_slot_is_free() { + let (mut probe, _reports) = probe(); + probe.set(true); + let start = Instant::now(); + assert_eq!(tick(&mut probe, start), 1); + assert!(probe.end(probe.generation, None).is_none()); + assert_eq!(tick(&mut probe, start + STATS_INTERVAL), 1); + probe.shutdown(); + } + + /// GIVEN the call ends WHEN the probe shuts down THEN no read starts + /// again, even when a tick comes. + #[tokio::test] + async fn given_shutdown_when_ticked_then_no_read_starts() { + let (mut probe, _reports) = probe(); + probe.set(true); + probe.shutdown(); + assert_eq!(tick(&mut probe, Instant::now()), 0); + } + + /// GIVEN reads that hold no statistics WHEN the reading is assembled THEN + /// a track with nothing to show has no entry and no connection is made + /// up. + #[test] + fn given_a_connection_without_transports_when_assembled_then_it_has_no_entry() { + let raw = assemble(&Asked::default(), false, std::iter::empty()); + assert!(raw.connections.is_empty() && raw.remotes.is_empty()); + let raw = assemble( + &asked(true, &[1]), + false, + [ + read(ReadKind::Microphone, 6, Vec::new()), + read(ReadKind::RemoteAudio(1, "x".into()), 6, Vec::new()), + ] + .into_iter(), + ); + assert!(raw.microphone.is_none(), "no outbound statistic, no entry"); + assert_eq!(raw.remotes.len(), 1); + assert!(raw.remotes[0].audio.is_none()); + assert!(raw.connections.is_empty()); + } + + /// The statistics of a track whose transport sent and received the + /// given bytes. + fn on_transport(bytes_sent: u64, bytes_received: u64) -> Vec { + let mut transport = livekit::webrtc::stats::TransportStats::default(); + transport.transport.bytes_sent = bytes_sent; + transport.transport.bytes_received = bytes_received; + vec![RtcStats::Transport(transport)] + } + + fn read(kind: ReadKind, at_ms: u64, stats: Vec) -> Read { + Read { + kind, + track: "TR".to_owned(), + at_ms, + stats, + } + } + + fn asked(own: bool, remote: &[u8]) -> Asked { + Asked { + own, + remote: remote.iter().copied().collect(), + } + } + + fn reads() -> impl Iterator { + [ + read(ReadKind::Microphone, 10, on_transport(100, 40)), + read( + ReadKind::RemoteAudio(0, "a".into()), + 11, + on_transport(101, 41), + ), + read(ReadKind::RemoteVideo(1, "b".into()), 12, on_transport(7, 9)), + ] + .into_iter() + } + + /// A link as its role, time, bytes sent and bytes received. + type LinkRow = (LinkRole, u64, u64, u64); + + /// Each connection's number, links, and whether it is complete. + fn links(raw: &RawStats) -> Vec<(u8, Vec, bool)> { + raw.connections + .iter() + .map(|c| { + let links = c + .links + .iter() + .map(|l| (l.role, l.at_ms, l.bytes_sent, l.bytes_received)) + .collect(); + (c.connection, links, c.complete) + }) + .collect() + } + + /// GIVEN the own room uses one peer connection WHEN the reading is + /// assembled THEN its transport is counted once, from the own tracks, + /// and another connection keeps its own numbers. + #[test] + fn given_one_peer_connection_when_assembled_then_its_transport_counts_once() { + let raw = assemble(&asked(true, &[0, 1]), true, reads()); + assert_eq!( + links(&raw), + [ + (0, vec![(LinkRole::Single, 10, 100, 40)], true), + (1, vec![(LinkRole::Subscriber, 12, 7, 9)], true), + ] + ); + } + + /// GIVEN the own room uses a publisher and a subscriber connection WHEN + /// the reading is assembled THEN both transports are there, each with + /// the time of its own read. + #[test] + fn given_two_peer_connections_when_assembled_then_both_transports_are_there() { + let raw = assemble(&asked(true, &[0, 1]), false, reads()); + assert_eq!( + links(&raw)[0], + ( + 0, + vec![ + (LinkRole::Publisher, 10, 100, 40), + (LinkRole::Subscriber, 11, 101, 41) + ], + true + ) + ); + } + + /// GIVEN one peer connection and no own track WHEN the reading is + /// assembled THEN the remote tracks' transport still gives the numbers. + #[test] + fn given_one_peer_connection_without_own_tracks_then_the_remote_transport_counts() { + let raw = assemble( + &asked(false, &[0]), + true, + [read( + ReadKind::RemoteAudio(0, "a".into()), + 3, + on_transport(3, 5), + )] + .into_iter(), + ); + assert_eq!(links(&raw), [(0, vec![(LinkRole::Single, 3, 3, 5)], true)]); + } + + /// GIVEN two peer connections and an own track whose read did not finish + /// WHEN the reading is assembled THEN the connection has the subscriber + /// only and is not complete, so its totals are unknown, never short. + #[test] + fn given_a_missing_publisher_read_when_assembled_then_the_connection_is_not_complete() { + let raw = assemble( + &asked(true, &[0]), + false, + [read( + ReadKind::RemoteAudio(0, "a".into()), + 3, + on_transport(3, 5), + )] + .into_iter(), + ); + assert_eq!( + links(&raw), + [(0, vec![(LinkRole::Subscriber, 3, 3, 5)], false)] + ); + } + + /// GIVEN reads of tracks WHEN the reading is assembled THEN each track's + /// numbers carry its track ID and the time of its own read. + #[test] + fn given_reads_when_assembled_then_each_track_has_its_id_and_time() { + let mut outbound = livekit::webrtc::stats::OutboundRtpStats::default(); + outbound.stream.kind = "audio".to_owned(); + let mut inbound = livekit::webrtc::stats::InboundRtpStats::default(); + inbound.stream.kind = "video".to_owned(); + let raw = assemble( + &asked(true, &[0]), + true, + [ + Read { + kind: ReadKind::Microphone, + track: "TR_mic".to_owned(), + at_ms: 20, + stats: vec![RtcStats::OutboundRtp(outbound)], + }, + Read { + kind: ReadKind::RemoteVideo(0, "a".into()), + track: "TR_cam".to_owned(), + at_ms: 27, + stats: vec![RtcStats::InboundRtp(inbound)], + }, + ] + .into_iter(), + ); + let microphone = raw.microphone.unwrap(); + assert_eq!( + (microphone.track.as_str(), microphone.at_ms), + ("TR_mic", 20) + ); + let video = raw.remotes[0].video.as_ref().unwrap(); + assert_eq!((video.track.as_str(), video.at_ms), ("TR_cam", 27)); + } +} diff --git a/crates/contracts/AGENTS.md b/crates/contracts/AGENTS.md index 488396f6..eb9c4fc0 100644 --- a/crates/contracts/AGENTS.md +++ b/crates/contracts/AGENTS.md @@ -7,6 +7,9 @@ This crate defines small Rust view types and exports their TypeScript representa - Update JSON fixtures in `fixtures/`, Rust tests, and `tests/type-contracts.ts` when the intended wire contract changes. The exporter writes TypeScript only; it does not update the JSON fixtures. - Inspect `frontend/src/bridge/index.ts`, core view production, and Tauri consumers for compatibility. Static TypeScript types do not validate untrusted runtime data. - Keep sample data synthetic, including hostile text that must remain inert when rendered. +- Sonar's rule `rust:S9334` is off for `src/lib.rs` (`sonar-project.properties`), so review does its check: an `Option` field with its own `deserialize_with` is required-nullable (`Option::deserialize`), or it has `#[serde(default)]` so that a missing key reads as `None`. + +- Call statistics (ADR-0066): `CallStats` and its parts hold integers with bounds (`CALL_STATS_*`). `CallStats::within_limits` is the check that the core, the UI host and the page's `parseCallStats` all repeat; change them together. The `CALL_STATS_*` bounds repeat `MAX_STATS_*` in `crates/call-protocol/src/stats.rs`, and `crates/core/src/calls/stats.rs` checks at compile time that they match. Each `Option` field is required-nullable (`Option::deserialize`): the key must be there, and only its value may be null. ## Checks diff --git a/crates/contracts/generated/contracts.ts b/crates/contracts/generated/contracts.ts index 47569945..d8d17907 100644 --- a/crates/contracts/generated/contracts.ts +++ b/crates/contracts/generated/contracts.ts @@ -117,6 +117,74 @@ muted: boolean, }; export type CallParticipantLevel = { userId: string, deviceId: string, level: number, }; +export type CallStatsLimit = "none" | "cpu" | "bandwidth" | "other"; + +export type CallStatsAudioSent = { +/** + * 0 to [`CALL_SOUND_LEVEL_MAX`]. + */ +level: number, +/** + * Kbit/s, at most [`CALL_STATS_KBPS_MAX`]. + */ +bitrateKbps: number | null, packetsSent: number, +/** + * Packets the far end reports lost. + */ +packetsLost: number | null, +/** + * Milliseconds, at most [`CALL_STATS_MS_MAX`]. + */ +jitterMs: number | null, rttMs: number | null, }; + +export type CallStatsVideoSent = { +/** + * At most [`CALL_STATS_FPS_MAX`]. + */ +fps: number, +/** + * At most [`CALL_STATS_SIDE_MAX`] each. + */ +width: number, height: number, bitrateKbps: number | null, limit: CallStatsLimit, packetsLost: number | null, }; + +export type CallStatsAudioReceived = { +/** + * 0 to [`CALL_SOUND_LEVEL_MAX`]. + */ +level: number, bitrateKbps: number | null, packetsReceived: number, packetsLost: number, jitterMs: number, +/** + * The share of the last second's samples that WebRTC made up, 0 to 100. + */ +concealedPercent: number | null, }; + +export type CallStatsVideoReceived = { fps: number, width: number, height: number, bitrateKbps: number | null, +/** + * Frames dropped each second, at most [`CALL_STATS_FPS_MAX`]. + */ +droppedFps: number | null, packetsLost: number, }; + +export type CallStatsParticipant = { userId: string, deviceId: string, audio: CallStatsAudioReceived | null, video: CallStatsVideoReceived | null, }; + +export type CallStatsConnection = { connection: number, +/** + * The bandwidth that WebRTC estimates for sending, kbit/s. + */ +outgoingKbps: number | null, +/** + * Everything sent and received on the connection, kbit/s. + */ +sendKbps: number | null, receiveKbps: number | null, rttMs: number | null, }; + +export type CallStats = { microphone: CallStatsAudioSent | null, camera: CallStatsVideoSent | null, screen: CallStatsVideoSent | null, +/** + * At most [`CALL_PARTICIPANTS_MAX`], each device once. + */ +participants: Array, +/** + * At most [`CALL_STATS_CONNECTIONS_MAX`], each connection once. + */ +connections: Array, }; + export type CallDeviceTestKind = "microphone" | "speaker" | "camera"; export type CallDeviceTestState = "idle" | "starting" | "running" | "done" | "not_found" | "denied" | "unsupported" | "unavailable" | "in_call" | "failed"; @@ -946,3 +1014,18 @@ export const CALL_DEVICE_ID_BYTES_MAX = 255; /** The top of a call sound level meter. */ export const CALL_SOUND_LEVEL_MAX = 100; + +/** The highest call statistic bitrate, in kbit/s. */ +export const CALL_STATS_KBPS_MAX = 1000000; + +/** The longest call statistic time, in milliseconds. */ +export const CALL_STATS_MS_MAX = 60000; + +/** The highest call statistic frame rate. */ +export const CALL_STATS_FPS_MAX = 120; + +/** The longest call statistic picture side, in pixels. */ +export const CALL_STATS_SIDE_MAX = 16384; + +/** The most connections in one call statistics reading. */ +export const CALL_STATS_CONNECTIONS_MAX = 4; diff --git a/crates/contracts/src/lib.rs b/crates/contracts/src/lib.rs index 3dc54336..45c8a195 100644 --- a/crates/contracts/src/lib.rs +++ b/crates/contracts/src/lib.rs @@ -2455,6 +2455,213 @@ pub struct CallParticipantLevel { pub level: u8, } +// The `CALL_STATS_*` bounds repeat `MAX_STATS_*` of the call protocol, which +// the worker clamps each number to. A number over a bound here drops the +// whole reading, so the core checks at compile time that both sets match +// (`crates/core/src/calls/stats.rs`). Change them together. + +/// The highest bitrate or bandwidth a call statistic shows, in kbit/s. +pub const CALL_STATS_KBPS_MAX: u32 = 1_000_000; +/// The longest time a call statistic shows, in milliseconds. +pub const CALL_STATS_MS_MAX: u16 = 60_000; +/// The highest frame rate a call statistic shows. +pub const CALL_STATS_FPS_MAX: u8 = 120; +/// The longest picture side a call statistic shows, in pixels. +pub const CALL_STATS_SIDE_MAX: u16 = 16_384; +/// The most connections one reading describes: the own call server and the +/// other call servers of ADR-0054. +pub const CALL_STATS_CONNECTIONS_MAX: usize = 4; + +/// Why a sent video runs below what was asked, as WebRTC reports it. +#[derive(Clone, Copy, Debug, Deserialize, Serialize, TS, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum CallStatsLimit { + None, + Cpu, + Bandwidth, + Other, +} + +/// The own microphone. An unknown value is null: a rate needs two readings, +/// and the far end reports loss, jitter and round-trip time later. Each +/// value that may be null is still a required key, here and in the other +/// statistics types. +#[derive(Clone, Debug, Deserialize, Serialize, TS, PartialEq, Eq)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +pub struct CallStatsAudioSent { + /// 0 to [`CALL_SOUND_LEVEL_MAX`]. + pub level: u8, + /// Kbit/s, at most [`CALL_STATS_KBPS_MAX`]. + #[serde(deserialize_with = "Option::deserialize")] + pub bitrate_kbps: Option, + pub packets_sent: u32, + /// Packets the far end reports lost. + #[serde(deserialize_with = "Option::deserialize")] + pub packets_lost: Option, + /// Milliseconds, at most [`CALL_STATS_MS_MAX`]. + #[serde(deserialize_with = "Option::deserialize")] + pub jitter_ms: Option, + #[serde(deserialize_with = "Option::deserialize")] + pub rtt_ms: Option, +} + +/// The own camera or screen share. +#[derive(Clone, Debug, Deserialize, Serialize, TS, PartialEq, Eq)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +pub struct CallStatsVideoSent { + /// At most [`CALL_STATS_FPS_MAX`]. + pub fps: u8, + /// At most [`CALL_STATS_SIDE_MAX`] each. + pub width: u16, + pub height: u16, + #[serde(deserialize_with = "Option::deserialize")] + pub bitrate_kbps: Option, + pub limit: CallStatsLimit, + #[serde(deserialize_with = "Option::deserialize")] + pub packets_lost: Option, +} + +/// The audio of another device in the call. +#[derive(Clone, Debug, Deserialize, Serialize, TS, PartialEq, Eq)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +pub struct CallStatsAudioReceived { + /// 0 to [`CALL_SOUND_LEVEL_MAX`]. + pub level: u8, + #[serde(deserialize_with = "Option::deserialize")] + pub bitrate_kbps: Option, + pub packets_received: u32, + pub packets_lost: u32, + pub jitter_ms: u16, + /// The share of the last second's samples that WebRTC made up, 0 to 100. + #[serde(deserialize_with = "Option::deserialize")] + pub concealed_percent: Option, +} + +/// The video of another device in the call. +#[derive(Clone, Debug, Deserialize, Serialize, TS, PartialEq, Eq)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +pub struct CallStatsVideoReceived { + pub fps: u8, + pub width: u16, + pub height: u16, + #[serde(deserialize_with = "Option::deserialize")] + pub bitrate_kbps: Option, + /// Frames dropped each second, at most [`CALL_STATS_FPS_MAX`]. + #[serde(deserialize_with = "Option::deserialize")] + pub dropped_fps: Option, + pub packets_lost: u32, +} + +/// One other device in the call, by the IDs of the call status. The IDs are +/// validated Matrix IDs (untrusted, shown as text). +#[derive(Clone, Debug, Deserialize, Serialize, TS, PartialEq, Eq)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +pub struct CallStatsParticipant { + pub user_id: String, + pub device_id: String, + #[serde(deserialize_with = "Option::deserialize")] + pub audio: Option, + #[serde(deserialize_with = "Option::deserialize")] + pub video: Option, +} + +/// One connection to a call server: 0 is the own one, 1 to 3 are other ones +/// (ADR-0054). +#[derive(Clone, Debug, Deserialize, Serialize, TS, PartialEq, Eq)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +pub struct CallStatsConnection { + pub connection: u8, + /// The bandwidth that WebRTC estimates for sending, kbit/s. + #[serde(deserialize_with = "Option::deserialize")] + pub outgoing_kbps: Option, + /// Everything sent and received on the connection, kbit/s. + #[serde(deserialize_with = "Option::deserialize")] + pub send_kbps: Option, + #[serde(deserialize_with = "Option::deserialize")] + pub receive_kbps: Option, + #[serde(deserialize_with = "Option::deserialize")] + pub rtt_ms: Option, +} + +/// The call's technical details, read about once a second while the call +/// window shows them (ADR-0066). Numbers with units only: no address, port, +/// codec or other text but the IDs of the devices. +#[derive(Clone, Debug, Default, Deserialize, Serialize, TS, PartialEq, Eq)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +pub struct CallStats { + #[serde(deserialize_with = "Option::deserialize")] + pub microphone: Option, + #[serde(deserialize_with = "Option::deserialize")] + pub camera: Option, + #[serde(deserialize_with = "Option::deserialize")] + pub screen: Option, + /// At most [`CALL_PARTICIPANTS_MAX`], each device once. + pub participants: Vec, + /// At most [`CALL_STATS_CONNECTIONS_MAX`], each connection once. + pub connections: Vec, +} + +impl CallStats { + /// Whether every number is inside its bound, the lists are inside their + /// limits, no device or connection comes twice and the IDs fit. A reading + /// that fails is dropped whole, never cut. + pub fn within_limits(&self) -> bool { + let kbps = |value: Option| value.is_none_or(|value| value <= CALL_STATS_KBPS_MAX); + let millis = |value: Option| value.is_none_or(|value| value <= CALL_STATS_MS_MAX); + let sent_audio = |audio: &CallStatsAudioSent| { + audio.level <= CALL_SOUND_LEVEL_MAX + && kbps(audio.bitrate_kbps) + && millis(audio.jitter_ms) + && millis(audio.rtt_ms) + }; + let sent_video = |video: &CallStatsVideoSent| { + video.fps <= CALL_STATS_FPS_MAX + && video.width <= CALL_STATS_SIDE_MAX + && video.height <= CALL_STATS_SIDE_MAX + && kbps(video.bitrate_kbps) + }; + let audio = |audio: &CallStatsAudioReceived| { + audio.level <= CALL_SOUND_LEVEL_MAX + && kbps(audio.bitrate_kbps) + && audio.jitter_ms <= CALL_STATS_MS_MAX + && audio.concealed_percent.is_none_or(|percent| percent <= 100) + }; + let video = |video: &CallStatsVideoReceived| { + video.fps <= CALL_STATS_FPS_MAX + && video.width <= CALL_STATS_SIDE_MAX + && video.height <= CALL_STATS_SIDE_MAX + && kbps(video.bitrate_kbps) + && video + .dropped_fps + .is_none_or(|fps| fps <= CALL_STATS_FPS_MAX) + }; + self.microphone.as_ref().is_none_or(sent_audio) + && self.camera.as_ref().is_none_or(sent_video) + && self.screen.as_ref().is_none_or(sent_video) + && self.participants.len() <= CALL_PARTICIPANTS_MAX + && self.participants.iter().enumerate().all(|(index, person)| { + person.user_id.len() <= CALL_USER_ID_BYTES_MAX + && person.device_id.len() <= CALL_DEVICE_ID_BYTES_MAX + && person.audio.as_ref().is_none_or(audio) + && person.video.as_ref().is_none_or(video) + && !self.participants[..index].iter().any(|seen| { + seen.user_id == person.user_id && seen.device_id == person.device_id + }) + }) + && self.connections.len() <= CALL_STATS_CONNECTIONS_MAX + && self.connections.iter().enumerate().all(|(index, link)| { + usize::from(link.connection) < CALL_STATS_CONNECTIONS_MAX + && kbps(link.outgoing_kbps) + && kbps(link.send_kbps) + && kbps(link.receive_kbps) + && millis(link.rtt_ms) + && !self.connections[..index] + .iter() + .any(|seen| seen.connection == link.connection) + }) + } +} + /// What a device test checks (ADR-0059). #[derive(Clone, Copy, Debug, Deserialize, Serialize, TS, PartialEq, Eq)] #[serde(rename_all = "snake_case")] @@ -2918,6 +3125,14 @@ pub fn generated_typescript() -> String { format!("export {}", CallPhase::decl(&config)), format!("export {}", CallParticipant::decl(&config)), format!("export {}", CallParticipantLevel::decl(&config)), + format!("export {}", CallStatsLimit::decl(&config)), + format!("export {}", CallStatsAudioSent::decl(&config)), + format!("export {}", CallStatsVideoSent::decl(&config)), + format!("export {}", CallStatsAudioReceived::decl(&config)), + format!("export {}", CallStatsVideoReceived::decl(&config)), + format!("export {}", CallStatsParticipant::decl(&config)), + format!("export {}", CallStatsConnection::decl(&config)), + format!("export {}", CallStats::decl(&config)), format!("export {}", CallDeviceTestKind::decl(&config)), format!("export {}", CallDeviceTestState::decl(&config)), format!("export {}", CallDeviceTestStatus::decl(&config)), @@ -3047,6 +3262,35 @@ pub fn generated_typescript() -> String { output.push_str(&format!( "\n/** The top of a call sound level meter. */\nexport const CALL_SOUND_LEVEL_MAX = {CALL_SOUND_LEVEL_MAX};\n" )); + for (doc, name, value) in [ + ( + "The highest call statistic bitrate, in kbit/s.", + "CALL_STATS_KBPS_MAX", + u64::from(CALL_STATS_KBPS_MAX), + ), + ( + "The longest call statistic time, in milliseconds.", + "CALL_STATS_MS_MAX", + u64::from(CALL_STATS_MS_MAX), + ), + ( + "The highest call statistic frame rate.", + "CALL_STATS_FPS_MAX", + u64::from(CALL_STATS_FPS_MAX), + ), + ( + "The longest call statistic picture side, in pixels.", + "CALL_STATS_SIDE_MAX", + u64::from(CALL_STATS_SIDE_MAX), + ), + ( + "The most connections in one call statistics reading.", + "CALL_STATS_CONNECTIONS_MAX", + CALL_STATS_CONNECTIONS_MAX as u64, + ), + ] { + output.push_str(&format!("\n/** {doc} */\nexport const {name} = {value};\n")); + } output } diff --git a/crates/contracts/tests/contracts.rs b/crates/contracts/tests/contracts.rs index d876b1e4..a3186369 100644 --- a/crates/contracts/tests/contracts.rs +++ b/crates/contracts/tests/contracts.rs @@ -1004,3 +1004,218 @@ fn linux_vault_reasons_are_fixed_store_codes() { } assert!(serde_json::from_value::(serde_json::json!("no_keyring")).is_err()); } + +fn sample_call_stats() -> persephone_contracts::CallStats { + use persephone_contracts::{ + CallStats, CallStatsAudioReceived, CallStatsAudioSent, CallStatsConnection, CallStatsLimit, + CallStatsParticipant, CallStatsVideoReceived, CallStatsVideoSent, + }; + CallStats { + microphone: Some(CallStatsAudioSent { + level: 100, + bitrate_kbps: Some(32), + packets_sent: u32::MAX, + packets_lost: None, + jitter_ms: Some(60_000), + rtt_ms: Some(40), + }), + camera: Some(CallStatsVideoSent { + fps: 120, + width: 16_384, + height: 1, + bitrate_kbps: Some(1_000_000), + limit: CallStatsLimit::Bandwidth, + packets_lost: Some(3), + }), + screen: None, + participants: vec![CallStatsParticipant { + user_id: "@bob:example.invalid".into(), + device_id: "BOBDEV".into(), + audio: Some(CallStatsAudioReceived { + level: 5, + bitrate_kbps: None, + packets_received: 10, + packets_lost: 0, + jitter_ms: 4, + concealed_percent: Some(100), + }), + video: Some(CallStatsVideoReceived { + fps: 30, + width: 1280, + height: 720, + bitrate_kbps: Some(900), + dropped_fps: Some(120), + packets_lost: 1, + }), + }], + connections: vec![CallStatsConnection { + connection: 3, + outgoing_kbps: None, + send_kbps: Some(1), + receive_kbps: None, + rtt_ms: Some(60_000), + }], + } +} + +/// GIVEN a statistics reading at every bound WHEN it crosses the wire THEN +/// it round-trips with camelCase names, unknown fields are refused, and the +/// bound itself passes `within_limits`. +#[test] +fn call_stats_cross_with_camel_case_names_and_refuse_unknown_fields() { + let stats = sample_call_stats(); + assert!(stats.within_limits()); + let json = serde_json::to_value(&stats).unwrap(); + assert_eq!(json["microphone"]["packetsSent"], u32::MAX); + assert_eq!(json["camera"]["limit"], "bandwidth"); + assert_eq!(json["participants"][0]["video"]["droppedFps"], 120); + assert!(json["screen"].is_null()); + assert_eq!( + serde_json::from_value::(json.clone()).unwrap(), + stats + ); + for path in [ + "/microphone", + "/participants/0", + "/participants/0/audio", + "/connections/0", + ] { + let mut extra = json.clone(); + extra.pointer_mut(path).unwrap()["address"] = "10.0.0.1".into(); + assert!( + serde_json::from_value::(extra).is_err(), + "{path}" + ); + } +} + +/// GIVEN a statistics reading WHEN a value that may be null is null THEN it +/// reads as unknown, and WHEN its key is left out THEN the reading is +/// refused: the key is required, as the TypeScript contract declares. +#[test] +fn call_stats_need_each_nullable_key() { + let json = serde_json::to_value(sample_call_stats()).unwrap(); + for (path, keys) in [ + ("", &["microphone", "camera", "screen"][..]), + ( + "/microphone", + &["bitrateKbps", "packetsLost", "jitterMs", "rttMs"], + ), + ("/camera", &["bitrateKbps", "packetsLost"]), + ("/participants/0", &["audio", "video"]), + ( + "/participants/0/audio", + &["bitrateKbps", "concealedPercent"], + ), + ("/participants/0/video", &["bitrateKbps", "droppedFps"]), + ( + "/connections/0", + &["outgoingKbps", "sendKbps", "receiveKbps", "rttMs"], + ), + ] { + for key in keys { + let mut null = json.clone(); + null.pointer_mut(path).unwrap()[*key] = serde_json::Value::Null; + assert!( + serde_json::from_value::(null).is_ok(), + "{path}/{key} may be null" + ); + let mut missing = json.clone(); + let object = missing.pointer_mut(path).unwrap().as_object_mut().unwrap(); + assert!( + object.remove(*key).is_some(), + "{path}/{key} is in the sample" + ); + assert!( + serde_json::from_value::(missing).is_err(), + "{path}/{key} may not be left out" + ); + } + } +} + +/// GIVEN a statistics reading with one value over its bound, too many or +/// repeated entries, or an overlong ID WHEN it is checked THEN it is +/// refused whole. +#[test] +fn call_stats_over_their_bounds_are_refused_whole() { + use persephone_contracts::{ + CALL_DEVICE_ID_BYTES_MAX, CALL_PARTICIPANTS_MAX, CALL_STATS_CONNECTIONS_MAX, + CALL_USER_ID_BYTES_MAX, CallStats, + }; + type Edit = Box; + let edits: [(&str, Edit); 12] = [ + ( + "level", + Box::new(|s| s.microphone.as_mut().unwrap().level = 101), + ), + ( + "bitrate", + Box::new(|s| s.camera.as_mut().unwrap().bitrate_kbps = Some(1_000_001)), + ), + ("fps", Box::new(|s| s.camera.as_mut().unwrap().fps = 121)), + ( + "side", + Box::new(|s| s.camera.as_mut().unwrap().height = 16_385), + ), + ( + "jitter", + Box::new(|s| s.microphone.as_mut().unwrap().jitter_ms = Some(60_001)), + ), + ( + "concealed", + Box::new(|s| { + s.participants[0].audio.as_mut().unwrap().concealed_percent = Some(101); + }), + ), + ( + "dropped", + Box::new(|s| s.participants[0].video.as_mut().unwrap().dropped_fps = Some(121)), + ), + ("rtt", Box::new(|s| s.connections[0].rtt_ms = Some(60_001))), + ( + "connection number", + Box::new(|s| s.connections[0].connection = 4), + ), + ( + "user id", + Box::new(|s| s.participants[0].user_id = "u".repeat(CALL_USER_ID_BYTES_MAX + 1)), + ), + ( + "device id", + Box::new(|s| s.participants[0].device_id = "d".repeat(CALL_DEVICE_ID_BYTES_MAX + 1)), + ), + ( + "same device twice", + Box::new(|s| { + let again = s.participants[0].clone(); + s.participants.push(again); + }), + ), + ]; + for (name, edit) in edits { + let mut stats = sample_call_stats(); + edit(&mut stats); + assert!(!stats.within_limits(), "{name}"); + } + let mut many = sample_call_stats(); + let one = many.participants[0].clone(); + many.participants = (0..=CALL_PARTICIPANTS_MAX) + .map(|index| persephone_contracts::CallStatsParticipant { + device_id: format!("D{index}"), + ..one.clone() + }) + .collect(); + assert!(!many.within_limits(), "too many devices"); + many.participants.truncate(CALL_PARTICIPANTS_MAX); + assert!(many.within_limits()); + let mut links = sample_call_stats(); + let first = links.connections[0].clone(); + links.connections = (0..=CALL_STATS_CONNECTIONS_MAX) + .map(|index| persephone_contracts::CallStatsConnection { + connection: u8::try_from(index).unwrap(), + ..first.clone() + }) + .collect(); + assert!(!links.within_limits(), "too many connections"); +} diff --git a/crates/contracts/tests/type-contracts.ts b/crates/contracts/tests/type-contracts.ts index 0042832c..a1afc563 100644 --- a/crates/contracts/tests/type-contracts.ts +++ b/crates/contracts/tests/type-contracts.ts @@ -11,6 +11,7 @@ import type { CallReadiness, CallStatus, CallParticipantLevel, + CallStats, CallDeviceTestKind, CallDeviceTestState, CallDeviceTestStatus, @@ -299,6 +300,17 @@ const unknownDeviceChange: CallStatus = { ...idleCall, deviceChange: "unplugged" const levelList: CallParticipantLevel[] = [{ userId: "@a:s", deviceId: "D", level: 40 }]; // @ts-expect-error a level carries the device and a number, nothing else const levelWithName: CallParticipantLevel = { ...levelList[0], name: "x" }; +const detailsTable: CallStats = { + microphone: { level: 40, bitrateKbps: null, packetsSent: 3, packetsLost: null, jitterMs: null, rttMs: null }, + camera: null, + screen: null, + participants: [{ userId: "@a:s", deviceId: "D", audio: null, video: null }], + connections: [{ connection: 0, outgoingKbps: null, sendKbps: 40, receiveKbps: null, rttMs: 20 }], +}; +// @ts-expect-error statistics carry numbers and IDs, never an address or a codec name +const detailsWithAddress: CallStats = { ...detailsTable, connections: [{ ...detailsTable.connections[0], address: "10.0.0.1" }] }; +// @ts-expect-error an unknown value is null, not missing +const detailsMissingValue: CallStats = { ...detailsTable, microphone: { level: 1, packetsSent: 3, packetsLost: null, jitterMs: null, rttMs: null } }; const testStatus: CallDeviceTestStatus = { id: 4, test: "camera", state: "running", stream: 2 }; // @ts-expect-error the test ID is required const noTestId: CallDeviceTestStatus = { test: "camera", state: "running", stream: 2 }; diff --git a/crates/core-protocol/AGENTS.md b/crates/core-protocol/AGENTS.md index b499857b..b69f29e9 100644 --- a/crates/core-protocol/AGENTS.md +++ b/crates/core-protocol/AGENTS.md @@ -5,6 +5,7 @@ This crate defines bounded commands, replies, and change events between the keyl - Use `persephone-media-protocol` framing and resource budgets. Reject invalid headers before allocating a body. - Keep command and payload schemas strict. Preserve unknown-command and unknown-field rejection, including empty command objects. Serde unit variants do not provide the same field rejection as struct variants. - Distinguish a required nullable field from a missing field. Test the actual Serde wire representation. +- Sonar's rule `rust:S9334` is off for `src/lib.rs` (`sonar-project.properties`), so review does its check: an `Option` field with its own `deserialize_with` is required-nullable (`Option::deserialize`), or it has `#[serde(default)]` so that a missing key reads as `None`. - Preserve request/reply correlation and distinguish pushed events from replies. Keep events small; message content belongs in bounded view calls. - Keep IDs, cursors, subscription counts, and error codes bounded and explicit. Coordinate any limit change with the receiving core, Tauri relay, and frontend consumers. - Test malformed frames, unexpected kinds, truncated input, extra fields, invalid variants, and oversized messages. Preserve fail-closed behavior. diff --git a/crates/core-protocol/src/lib.rs b/crates/core-protocol/src/lib.rs index c16b439d..615b1453 100644 --- a/crates/core-protocol/src/lib.rs +++ b/crates/core-protocol/src/lib.rs @@ -768,6 +768,13 @@ pub enum Call { auto_level: bool, gain: u16, }, + /// Start or stop the call statistics (ADR-0066). While on, the core + /// asks the worker to read them and sends [`Event::CallStats`], at most + /// about once a second. Only the call window may send it. Off at every + /// call start, and off again when the call ends. Replies `null`. + CallStats { + on: bool, + }, /// Turn the camera on or off during a call. Replies `CallStatus`, with the /// camera `starting` when turned on; the worker's answer arrives as /// [`Event::CallChanged`]. Refused when no call is connected. @@ -1117,6 +1124,14 @@ pub enum Event { #[serde(deserialize_with = "bounded_levels")] levels: Vec, }, + /// The call's technical details (ADR-0066), sent only while + /// [`Call::CallStats`] is on: numbers with units, and the validated IDs + /// of the devices. Coalesced: only the newest waits. A reading that is + /// out of bounds is refused whole. + #[serde(deserialize_with = "call_stats_content")] + CallStats { + stats: persephone_contracts::CallStats, + }, /// A device test started, changed or ended (ADR-0059): ask for /// `call_device_test_status`. Content-free and coalesced. CallDeviceTestChanged {}, @@ -1161,48 +1176,322 @@ pub fn levels_within_limits(levels: &[persephone_contracts::CallParticipantLevel }) } -/// Reads a level list and refuses an entry past [`MAX_CALL_LEVELS`], an -/// overlong ID or a level out of range before it keeps it, so a hostile list -/// allocates at most the limits. -fn bounded_levels<'de, D: serde::Deserializer<'de>>( +/// Reads the content of [`Event::CallStats`]. Only a JSON object with the one +/// key `stats` is read: the derived reader would also take a positional +/// array. A repeated or unknown key is an error. +fn call_stats_content<'de, D: serde::Deserializer<'de>>( deserializer: D, -) -> Result, D::Error> { - struct Levels; - impl<'de> serde::de::Visitor<'de> for Levels { - type Value = Vec; +) -> Result { + struct Content; + impl<'de> serde::de::Visitor<'de> for Content { + type Value = persephone_contracts::CallStats; fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "at most {MAX_CALL_LEVELS} call levels") + f.write_str("an object with the key `stats`") } - fn visit_seq>( + fn visit_map>( self, - mut seq: A, + mut map: A, ) -> Result { - let mut levels = Vec::new(); - loop { - // A full list only checks for one more entry, unbuilt. - if levels.len() == MAX_CALL_LEVELS { - if seq.next_element::()?.is_some() { - return Err(serde::de::Error::custom("call levels out of bounds")); + use serde::de::Error; + #[derive(Deserialize)] + #[serde(rename_all = "camelCase")] + enum Field { + Stats, + } + let mut stats = None; + while let Some(Field::Stats) = map.next_key::()? { + // The key alone refuses a repeat: its value is not read. + if stats.is_some() { + return Err(A::Error::duplicate_field("stats")); + } + stats = Some(map.next_value::()?); + } + stats + .map(|stats| stats.0) + .ok_or_else(|| A::Error::missing_field("stats")) + } + } + deserializer.deserialize_map(Content) +} + +/// A statistics reading, read by [`bounded_stats`]. +struct WireStatsValue(persephone_contracts::CallStats); + +impl<'de> Deserialize<'de> for WireStatsValue { + fn deserialize>(deserializer: D) -> Result { + bounded_stats(deserializer).map(WireStatsValue) + } +} + +/// Wraps a deserializer so that a struct reads only from a JSON object. A +/// derived struct reader also takes a positional array, which is not the +/// contract. +struct MapOnlyDeserializer(D); + +impl<'de, D: serde::Deserializer<'de>> serde::Deserializer<'de> for MapOnlyDeserializer { + type Error = D::Error; + + fn deserialize_any>( + self, + visitor: V, + ) -> Result { + self.0.deserialize_map(visitor) + } + + serde::forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string + bytes byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct enum identifier ignored_any + } +} + +/// A value read through [`MapOnlyDeserializer`]. +struct MapOnly(T); + +impl<'de, T: Deserialize<'de>> Deserialize<'de> for MapOnly { + fn deserialize>(deserializer: D) -> Result { + T::deserialize(MapOnlyDeserializer(deserializer)).map(MapOnly) + } +} + +/// Reads a statistics reading. Only a JSON object is read, each list stops +/// at its limit before it builds one more entry, and each ID is bounded +/// before it is copied. `CallStats::within_limits` then checks the numbers +/// and repeats: a reading that fails is refused whole. +fn bounded_stats<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result { + let stats = deserializer.deserialize_map(WireStats)?; + if stats.within_limits() { + Ok(stats) + } else { + Err(serde::de::Error::custom("call statistics out of bounds")) + } +} + +/// The map-only reader of a statistics reading. Every key is required, and +/// the keys of the parts that may be null take `null`. +struct WireStats; + +impl<'de> serde::de::Visitor<'de> for WireStats { + type Value = persephone_contracts::CallStats; + + fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("a call statistics object") + } + + fn visit_map>(self, mut map: A) -> Result { + use serde::de::Error; + #[derive(Deserialize)] + #[serde(rename_all = "camelCase")] + enum Field { + Microphone, + Camera, + Screen, + Participants, + Connections, + } + let (mut microphone, mut camera, mut screen) = (None, None, None); + let (mut participants, mut connections) = (None, None); + // A repeated key is refused before its value is read. A key seen with + // the value `null` still counts as seen, so `Option>`. + while let Some(field) = map.next_key::()? { + let seen = match field { + Field::Microphone => microphone.is_some(), + Field::Camera => camera.is_some(), + Field::Screen => screen.is_some(), + Field::Participants => participants.is_some(), + Field::Connections => connections.is_some(), + }; + if seen { + return Err(A::Error::custom("duplicate call statistics field")); + } + match field { + Field::Microphone => { + microphone = Some( + map.next_value::>>()?, + ); + } + Field::Camera => { + camera = Some( + map.next_value::>>()?, + ); + } + Field::Screen => { + screen = Some( + map.next_value::>>()?, + ); + } + Field::Participants => { + participants = Some(map.next_value::>()?); + } + Field::Connections => { + connections = Some(map.next_value::, + { persephone_contracts::CALL_STATS_CONNECTIONS_MAX }, + >>()?); + } + } + } + let participants = participants.ok_or_else(|| A::Error::missing_field("participants"))?; + Ok(persephone_contracts::CallStats { + microphone: microphone + .ok_or_else(|| A::Error::missing_field("microphone"))? + .map(|audio| audio.0), + camera: camera + .ok_or_else(|| A::Error::missing_field("camera"))? + .map(|video| video.0), + screen: screen + .ok_or_else(|| A::Error::missing_field("screen"))? + .map(|video| video.0), + participants: participants + .0 + .into_iter() + .map(|participant| persephone_contracts::CallStatsParticipant { + user_id: participant.user_id.0, + device_id: participant.device_id.0, + audio: participant.audio.map(|audio| audio.0), + video: participant.video.map(|video| video.0), + }) + .collect(), + connections: connections + .ok_or_else(|| A::Error::missing_field("connections"))? + .0 + .into_iter() + .map(|connection| connection.0) + .collect(), + }) + } +} + +/// One device of a statistics reading as it crosses, with its IDs bounded. +/// Only a JSON object is read, and every key is required. +struct WireParticipant { + user_id: BoundedText, + device_id: BoundedText, + audio: Option>, + video: Option>, +} + +impl<'de> Deserialize<'de> for WireParticipant { + fn deserialize>(deserializer: D) -> Result { + #[derive(Deserialize)] + #[serde(rename_all = "camelCase")] + enum Field { + UserId, + DeviceId, + Audio, + Video, + } + struct Entry; + impl<'de> serde::de::Visitor<'de> for Entry { + type Value = WireParticipant; + + fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("a call statistics participant object") + } + + fn visit_map>( + self, + mut map: A, + ) -> Result { + use serde::de::Error; + let (mut user_id, mut device_id, mut audio, mut video) = (None, None, None, None); + while let Some(field) = map.next_key::()? { + // A repeated key is refused before its value is read. + let seen = match field { + Field::UserId => user_id.is_some(), + Field::DeviceId => device_id.is_some(), + Field::Audio => audio.is_some(), + Field::Video => video.is_some(), + }; + if seen { + return Err(A::Error::custom("duplicate call statistics field")); + } + match field { + Field::UserId => user_id = Some(map.next_value()?), + Field::DeviceId => device_id = Some(map.next_value()?), + Field::Audio => audio = Some(map.next_value()?), + Field::Video => video = Some(map.next_value()?), } - return Ok(levels); } - let Some(level) = seq.next_element::()? else { - return Ok(levels); - }; - if level.level > MAX_CALL_SOUND_LEVEL { - return Err(serde::de::Error::custom("call levels out of bounds")); + Ok(WireParticipant { + user_id: user_id.ok_or_else(|| A::Error::missing_field("userId"))?, + device_id: device_id.ok_or_else(|| A::Error::missing_field("deviceId"))?, + audio: audio.ok_or_else(|| A::Error::missing_field("audio"))?, + video: video.ok_or_else(|| A::Error::missing_field("video"))?, + }) + } + } + deserializer.deserialize_map(Entry) + } +} + +/// Reads a level list and refuses an entry past [`MAX_CALL_LEVELS`] or an +/// overlong ID before it keeps it, so a hostile list allocates at most the +/// limits, and then a level out of range. +fn bounded_levels<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result, D::Error> { + let BoundedList(levels) = BoundedList::::deserialize(deserializer)?; + if levels + .iter() + .any(|level| level.level > MAX_CALL_SOUND_LEVEL) + { + return Err(serde::de::Error::custom("call levels out of bounds")); + } + Ok(levels + .into_iter() + .map(|level| persephone_contracts::CallParticipantLevel { + user_id: level.user_id.0, + device_id: level.device_id.0, + level: level.level, + }) + .collect()) +} + +/// A list of at most `N` entries. The entry past the limit is refused +/// before it is built: a full list only checks for one more, unbuilt. +struct BoundedList(Vec); + +impl<'de, T: Deserialize<'de>, const N: usize> Deserialize<'de> for BoundedList { + fn deserialize>(deserializer: D) -> Result { + struct List(std::marker::PhantomData); + impl<'de, T: Deserialize<'de>, const N: usize> serde::de::Visitor<'de> for List { + type Value = BoundedList; + + fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "a list of at most {N} entries") + } + + fn visit_seq>( + self, + mut seq: A, + ) -> Result { + let mut entries = Vec::new(); + loop { + if entries.len() == N { + if seq.next_element::()?.is_some() { + return Err(serde::de::Error::custom(format_args!( + "list over its limit of {N} entries" + ))); + } + return Ok(BoundedList(entries)); + } + let Some(entry) = seq.next_element()? else { + return Ok(BoundedList(entries)); + }; + entries.push(entry); } - levels.push(persephone_contracts::CallParticipantLevel { - user_id: level.user_id.0, - device_id: level.device_id.0, - level: level.level, - }); } } + deserializer.deserialize_seq(List(std::marker::PhantomData)) } - deserializer.deserialize_seq(Levels) } /// One entry of a level list as it crosses, with its IDs bounded. Only a @@ -2349,6 +2638,10 @@ mod tests { Call::CallScreen { on: true }, r#"{"id":1,"call":{"command":"call_screen","on":true}}"#, ), + ( + Call::CallStats { on: true }, + r#"{"id":1,"call":{"command":"call_stats","on":true}}"#, + ), ( Call::CallVideoFrame { tile: 4, @@ -4151,6 +4444,247 @@ mod timeline_events_wire_tests { ); } + /// GIVEN the statistics command WHEN it is decoded THEN it carries only + /// the flag. + #[test] + fn given_the_stats_command_then_it_carries_only_the_flag() { + let decoded = |json: &[u8]| serde_json::from_slice::(json); + assert!(decoded(br#"{"id":1,"call":{"command":"call_stats","on":true}}"#).is_ok()); + assert!(decoded(br#"{"id":1,"call":{"command":"call_stats","on":false}}"#).is_ok()); + for json in [ + &br#"{"id":1,"call":{"command":"call_stats"}}"#[..], + br#"{"id":1,"call":{"command":"call_stats","on":1}}"#, + br#"{"id":1,"call":{"command":"call_stats","on":true,"interval":1}}"#, + ] { + assert!(decoded(json).is_err(), "{}", String::from_utf8_lossy(json)); + } + } + + /// GIVEN statistics events WHEN read THEN a reading inside its bounds + /// is kept, and one with a number over its bound, an overlong ID, a + /// repeated device or an unknown field is refused whole. + #[test] + fn given_call_stats_events_then_only_bounded_readings_are_read() { + let event = |stats: serde_json::Value| { + serde_json::from_value::( + serde_json::json!({"event": {"call_stats": {"stats": stats}}}), + ) + }; + let reading = |fps: u32, user: &str| { + serde_json::json!({ + "microphone": null, + "camera": {"fps": fps, "width": 640, "height": 360, "bitrateKbps": null, + "limit": "none", "packetsLost": null}, + "screen": null, + "participants": [{"userId": user, "deviceId": "D", "audio": null, "video": null}], + "connections": [], + }) + }; + assert!(event(reading(120, "@a:example.org")).is_ok()); + assert!(event(reading(121, "@a:example.org")).is_err()); + assert!(event(reading(1, &"a".repeat(MAX_USER_ID_BYTES + 1))).is_err()); + let mut twice = reading(1, "@a:example.org"); + let again = twice["participants"][0].clone(); + twice["participants"].as_array_mut().unwrap().push(again); + assert!(event(twice).is_err()); + let mut extra = reading(1, "@a:example.org"); + extra["address"] = "10.0.0.1".into(); + assert!(event(extra).is_err()); + for key in ["microphone", "screen", "participants", "connections"] { + let mut missing = reading(1, "@a:example.org"); + missing.as_object_mut().unwrap().remove(key); + assert!(event(missing).is_err(), "{key}"); + } + for key in ["audio", "deviceId"] { + let mut missing = reading(1, "@a:example.org"); + missing["participants"][0] + .as_object_mut() + .unwrap() + .remove(key); + assert!(event(missing).is_err(), "{key}"); + } + let mut no_rate = reading(1, "@a:example.org"); + no_rate["camera"] + .as_object_mut() + .unwrap() + .remove("bitrateKbps"); + assert!(event(no_rate).is_err()); + let wire = serde_json::to_string(&CoreMessage::Event(Event::CallStats { + stats: persephone_contracts::CallStats::default(), + })) + .unwrap(); + assert!(wire.starts_with(r#"{"event":{"call_stats":{"stats":{"microphone":null"#)); + assert!(serde_json::from_str::(&wire).is_ok()); + } + + /// GIVEN statistics events with a list past its limit, a positional + /// array or a repeated key WHEN read THEN each is refused: the reader + /// takes objects only and stops a list at its limit as it reads. + #[test] + fn given_call_stats_past_their_limits_or_in_arrays_then_they_are_refused() { + let event = |stats: serde_json::Value| { + serde_json::from_value::( + serde_json::json!({"event": {"call_stats": {"stats": stats}}}), + ) + }; + let participant = |index: usize| { + serde_json::json!({"userId": format!("@u{index}:example.org"), "deviceId": "D", + "audio": null, "video": null}) + }; + let connection = |index: usize| { + serde_json::json!({"connection": index, "outgoingKbps": null, "sendKbps": null, + "receiveKbps": null, "rttMs": null}) + }; + let reading = |participants: usize, connections: usize| { + serde_json::json!({ + "microphone": null, "camera": null, "screen": null, + "participants": (0..participants).map(participant).collect::>(), + "connections": (0..connections).map(connection).collect::>(), + }) + }; + let full = persephone_contracts::CALL_STATS_CONNECTIONS_MAX; + let people = persephone_contracts::CALL_PARTICIPANTS_MAX; + assert!(event(reading(people, full)).is_ok()); + assert!(event(reading(people + 1, 0)).is_err()); + // An entry past the limit is refused unbuilt, whatever it holds. + let mut over = reading(people, 0); + over["participants"] + .as_array_mut() + .unwrap() + .push(serde_json::json!({"anything": [1, 2, 3]})); + let error = event(over).unwrap_err(); + assert!(error.to_string().contains("over its limit"), "{error}"); + // The entry past the limit cannot be a connection, so only the early + // limit can refuse it. + let mut too_many = reading(0, full); + too_many["connections"] + .as_array_mut() + .unwrap() + .push(serde_json::json!("x")); + let error = event(too_many).unwrap_err(); + assert!(error.to_string().contains("over its limit"), "{error}"); + assert!(event(serde_json::json!([null, null, null, [], []])).is_err()); + let mut positional = reading(0, 0); + positional["participants"] = serde_json::json!([["@a:example.org", "D", null, null]]); + assert!(event(positional).is_err()); + let twice = r#"{"event":{"call_stats":{"stats":{"microphone":null,"microphone":null, + "camera":null,"screen":null,"participants":[],"connections":[]}}}}"#; + assert!(serde_json::from_str::(twice).is_err()); + } + + /// GIVEN statistics events on the byte path WHEN the content or a part is + /// positional THEN it is refused, and an object with null parts is kept. + #[test] + fn given_call_stats_bytes_with_positional_parts_then_they_are_refused() { + let read = |json: &str| serde_json::from_slice::(json.as_bytes()); + let content = |stats: &str| format!(r#"{{"event":{{"call_stats":{stats}}}}}"#); + let reading = |microphone: &str, participants: &str, connections: &str| { + format!( + r#"{{"microphone":{microphone},"camera":null,"screen":null,"participants":{participants},"connections":{connections}}}"# + ) + }; + let valid = reading("null", "[]", "[]"); + assert!(read(&content(&format!(r#"{{"stats":{valid}}}"#))).is_ok()); + // The content is an object with the key `stats`, and no other key. + assert!(read(&content(&format!("[{valid}]"))).is_err()); + assert!(read(&content("{}")).is_err()); + assert!(read(&content(&format!(r#"{{"stats":{valid},"stats":{valid}}}"#))).is_err()); + assert!(read(&content(&format!(r#"{{"stats":{valid},"extra":1}}"#))).is_err()); + // Each nested record is an object too. + let with = |microphone: &str, participants: &str, connections: &str| { + content(&format!( + r#"{{"stats":{}}}"#, + reading(microphone, participants, connections) + )) + }; + // Each array is a complete record that the derived reader of the + // contract type takes, so only the map-only reader refuses it here. + let microphone = "[1,null,0,null,null,null]"; + let heard = "[1,null,0,0,0,null]"; + let connection = "[0,null,null,null,null]"; + assert!( + serde_json::from_str::(microphone).is_ok() + ); + assert!( + serde_json::from_str::(heard).is_ok() + ); + assert!( + serde_json::from_str::(connection).is_ok() + ); + assert!(read(&with(microphone, "[]", "[]")).is_err()); + assert!(read(&with("null", "[]", &format!("[{connection}]"))).is_err()); + assert!( + read(&with( + "null", + &format!( + r#"[{{"userId":"@a:example.org","deviceId":"D","audio":{heard},"video":null}}]"# + ), + "[]" + )) + .is_err() + ); + // GIVEN objects with null parts THEN they are kept. + assert!( + read(&with( + r#"{"level":1,"bitrateKbps":null,"packetsSent":0,"packetsLost":null,"jitterMs":null,"rttMs":null}"#, + r#"[{"userId":"@a:example.org","deviceId":"D","audio":null,"video":null}]"#, + r#"[{"connection":0,"outgoingKbps":null,"sendKbps":null,"receiveKbps":null,"rttMs":null}]"# + )) + .is_ok() + ); + } + + /// GIVEN a repeated key whose second value is invalid WHEN read THEN the + /// repeat is refused by the key, not by the value: the error names the + /// duplicate, so the second value was never decoded. + #[test] + fn given_a_repeated_call_stats_key_with_a_bad_second_value_then_the_key_is_refused() { + let read = |json: &str| { + serde_json::from_str::(json) + .unwrap_err() + .to_string() + }; + let content = |stats: &str| format!(r#"{{"event":{{"call_stats":{stats}}}}}"#); + let valid = + r#"{"microphone":null,"camera":null,"screen":null,"participants":[],"connections":[]}"#; + // The content key `stats`. + let error = read(&content(&format!(r#"{{"stats":{valid},"stats":"bad"}}"#))); + assert!(error.contains("duplicate field `stats`"), "{error}"); + // An aggregate key. + let error = read(&content( + r#"{"stats":{"microphone":null,"microphone":"bad","camera":null,"screen":null,"participants":[],"connections":[]}}"#, + )); + assert!(error.contains("duplicate call statistics field"), "{error}"); + // A participant key. + let error = read(&content( + r#"{"stats":{"microphone":null,"camera":null,"screen":null,"connections":[], + "participants":[{"userId":"@a:example.org","userId":5,"deviceId":"D","audio":null,"video":null}]}}"#, + )); + assert!(error.contains("duplicate call statistics field"), "{error}"); + } + + /// GIVEN a key first read as `null` and then repeated WHEN read THEN it is + /// refused as a repeat: `null` is a value, not an unseen key. + #[test] + fn given_a_repeated_call_stats_key_after_null_then_it_is_refused_as_a_repeat() { + let read = |json: &str| { + serde_json::from_str::(json) + .unwrap_err() + .to_string() + }; + let error = read( + r#"{"event":{"call_stats":{"stats":{"microphone":null,"microphone":null,"camera":null, + "screen":null,"participants":[],"connections":[]}}}}"#, + ); + assert!(error.contains("duplicate call statistics field"), "{error}"); + let error = read( + r#"{"event":{"call_stats":{"stats":{"microphone":null,"camera":null,"screen":null, + "connections":[],"participants":[{"userId":"@a:example.org","deviceId":"D", + "audio":null,"audio":null,"video":null}]}}}}"#, + ); + assert!(error.contains("duplicate call statistics field"), "{error}"); + } + /// GIVEN call level events WHEN read THEN bounded ones are kept, and a /// level over the top, too many devices or an overlong ID is refused. #[test] @@ -4195,10 +4729,7 @@ mod timeline_events_wire_tests { let missing = br#"{"event":{"call_levels":{"levels":[{"userId":"@a:example.org","deviceId":"D"}]}}}"#; assert!(serde_json::from_slice::(missing).is_err()); - assert!( - error.to_string().contains("call levels out of bounds"), - "{error}" - ); + assert!(error.to_string().contains("over its limit"), "{error}"); let longest = "a".repeat(MAX_USER_ID_BYTES); assert!(event(serde_json::json!([one(1, &longest)])).is_ok()); let device = "D".repeat(MAX_DEVICE_ID_BYTES + 1); diff --git a/crates/core/AGENTS.md b/crates/core/AGENTS.md index 027fbdb5..083ad594 100644 --- a/crates/core/AGENTS.md +++ b/crates/core/AGENTS.md @@ -19,6 +19,7 @@ This crate is the application entry process. ADR-0004 assigns sessions, SDK work - Join refusal and the alone rule (ADR-0063, proposed): `CallController::prepare` reads the room's power levels from the local store and answers `CallError::NotPermitted` (`join_error` `not_permitted`) with `can_send_member_state`, the function `readiness` uses, before the SFU discovery, the worker launch, the delayed event and the membership send. A 403 `M_FORBIDDEN` answer to the membership send is the same error (`membership_error`); any other refusal stays `Membership`. `LevelKey::JoinCalls` maps to the call membership event type in `room_settings::state_type`, so the one closed level change sets it. `calls/alone.rs` keeps the remote participants by connection from `ParticipantJoined` and `ParticipantLeft`, and drops a connection's participants on `Connection { up: false }`; the call loop ends the call with `EndReason::Alone` 30 s after `Connected` with nobody else, or after the last one left. At the deadline it first applies the worker's waiting messages (`alone_still_due`), so a join that waits unread keeps the call. The end uses the normal leave path. Keep the set bounded, and keep a call whose set overflowed. Its tests need tokio's `test-util` (dev-dependency only). - Presence (ADR-0057, proposed): `presence.rs` holds the `Writer`, which picks every sync request's `set_presence` and the `PUT` of a changed setting, at most one write a second and a carried sync value at most every 15 seconds, the bounded `Book` of contacts' presence, and `Members`, the bounded book of the members the member panel last listed (`room_settings::readers` sets it). The contacts' two and the members' four lookups a round all run at once, so a round stays within one timeout. Never let a sync request use the SDK's default `online`: pass the writer's value to `account::sync_round`. - Devices and levels (ADR-0059, proposed): `calls/device_test.rs` holds the pure test rules; `CallController::start_device_test` runs one test at a time on its own thread, refuses it while a call runs or joins (`in_call`), stops it when a join starts and ends it after `TEST_LIMIT`. The test worker starts with the `pulse:` name of the tested device only (`device_test::worker_audio`), and on the Linux portal path a camera test sends one portal remote before `TestDevice` (`devices::send_portal_remote`, cancelled by the user's stop). A stop recorded while the test worker starts ends the test before `TestDevice`, so no device opens; a later stop reaches the worker as `Leave`, which closes a device that opened. The test worker gets the diagnostic switch before `TestDevice` and on each change, and its records go to the log (`worker_record`, ADR-0058). A camera test's picture store is the controller's store only while no call runs. `Core::set_call_devices` also sends the microphone, speaker and camera choice to a running or joining call (`CallController::set_devices`, which sends `ToWorker::SetDevices`); the camera applies from the next camera start, and a failed microphone or speaker change is the status's `deviceChange`. Other devices' levels go to the hub as `SoundUpdate::Participants` and leave with the own level under its gap. +- Call statistics (ADR-0066, proposed): `calls/stats.rs` makes the page's `CallStats` from the worker's message, naming each remote entry by the member that `View::level_member` says its identity stands for (a current member on a connection that speaks for it) and dropping the whole reading when it fails `CallStats::within_limits`. `CallController::set_stats` is the one switch: on needs a running call or a joining call that the end of the session has not stopped. `Inner::release` and `stop_for_session_end` turn it off under the slot lock, for a running and a joining call alike, and the end of the session drops the waiting reading before it publishes `Ended`. `Core::close` and the host's window reset turn it off too, and `Call::run` sends `SetStats` on each change (`apply_stats`, retry when the queue is full). A reading is dropped unless the switch is on. The hub keeps only the newest and sends `Event::CallStats` at once; it is dropped when the switch goes off. Never send statistics to a page that did not turn them on. - Linux keyring (ADR-0061, proposed): `platform/linux/vault.rs` asks `confirm_keyring_creation` (default "no") only when `ReadAlias("default")` is `/` while a new secret is stored, at most once per open attempt, and only after a yes calls `CreateCollection` ("Login", alias `default`) reads the alias again after the answer (a default made meanwhile is used without `CreateCollection`, which would return it and could relabel it), and uses the collection it created (`created_collection`: the reply's path, or the prompt's result) only if that path was not in the provider's `Collections` list just before and the alias now names it. `store_new` owns the session-bus name `CREATION_NAME` (`CreationLock`) from its first search to its read-back, so no other core on that bus creates an item during the waits; do not move this lock to a file under a per-process directory. A core waits at most `CREATION_WAIT` (5 s) for the name, plus one `CREATION_CALL_TIMEOUT` (1 s) request that started before the end (the lock asks on its own connection with that reply timeout), because `main.rs` opens the profile before any window shows. Another core that still owns the name then is `VaultError::Busy` (`keyring_busy`); no session bus for the lock's connection is `VaultError::Missing(Missing::SessionBus)` (`no_session_bus`); any other lock failure, also a bus that exists but does not answer in time, is `VaultError::Failed` (`key_unreadable`). Never add `SetAlias`. A missing bus, provider, default keyring or display is `VaultError::Missing`, which `store.rs` maps to its own `StoreState`; never fall back to another collection, the kernel keyring, a file or the passphrase alone. - Diagnostic log (ADR-0058, proposed): `diagnostics.rs` is the only writer. It is off at every start; `main.rs` erases the old file (overwrite, sync, truncate, delete) before the profile opens. Every string passes `diagnostics/redact.rs` before the writer thread gets it. `diagnostics/events.rs` writes event metadata only; content is always `[content]`. Request records use `Call::command()`, which reads only the command tag, never arguments. Never format a secret into a record, and keep the queue, line and file limits. Turning it on goes through `confirm_diagnostics` (default "no"). diff --git a/crates/core/src/calls/controller.rs b/crates/core/src/calls/controller.rs index 9622a681..40dce185 100644 --- a/crates/core/src/calls/controller.rs +++ b/crates/core/src/calls/controller.rs @@ -29,6 +29,7 @@ use super::readiness::{Discovery, Flow, TurnServers, sfu_transport, turn_servers use super::rings::{self, Plan as RingPlan, Watch}; use super::screen::{ScreenGrant, ScreenRefusal, ScreenSource}; use super::sfu::{self, OpenIdToken, SfuError, SfuGrant}; +use super::stats; use super::status::can_send_member_state; use super::video::{Notifier, Picture, VideoStore}; use super::worker::{ @@ -54,7 +55,8 @@ use persephone_call_protocol::{ }; use persephone_contracts::{ CALL_PARTICIPANTS_MAX, CallCamera, CallDeviceChange, CallDeviceTestKind, CallDeviceTestState, - CallDeviceTestStatus, CallParticipantLevel, CallParticipantRef, CallScreen, CallVideoTile, + CallDeviceTestStatus, CallParticipantLevel, CallParticipantRef, CallScreen, CallStats, + CallVideoTile, }; use std::{ collections::{BTreeMap, BTreeSet, HashSet, VecDeque}, @@ -663,12 +665,14 @@ impl View { fn apply(&mut self, event: &FromWorker) -> Applied { match event { // A record goes to the diagnostic log, never to the view. - // A sound level goes to the level meters, never to the view. + // A sound level goes to the level meters, never to the view; the + // statistics go to their own listener (ADR-0066). FromWorker::Ready { .. } | FromWorker::ParticipantJoined { .. } | FromWorker::Diagnostic { .. } | FromWorker::SoundLevel { .. } - | FromWorker::ParticipantLevel { .. } => Applied::Same, + | FromWorker::ParticipantLevel { .. } + | FromWorker::Stats(_) => Applied::Same, FromWorker::ParticipantMuted { connection, identity, @@ -1175,6 +1179,10 @@ enum Command { type Listener = Arc; /// Takes the call's sound levels (ADR-0055, ADR-0059). pub type SoundListener = Arc; +/// Takes the call's technical details (ADR-0066): the newest reading, or +/// `None` when there is none any more (the statistics went off, or the call +/// ended). It must not block and must not call the controller. +pub type StatsListener = Arc) + Send + Sync>; /// A member as the page names it: user ID and device ID. type CallParticipantLevelKey = (String, String); @@ -1203,6 +1211,13 @@ struct Inner { /// Takes each sound level of the running call; see /// [`CallController::set_sound_listener`]. sound_listener: Mutex>, + /// Whether the page shows the technical details (ADR-0066). Only a + /// running or joining call can have it on, and the end of the call turns + /// it off under the slot lock. + stats_on: watch::Sender, + /// Takes each statistics reading of the running call; see + /// [`CallController::set_stats_listener`]. + stats_listener: Mutex>, /// The picture store of the running worker, from its start to the end of /// the call or join, or of a camera test while no call runs (ADR-0059). video: Mutex>, @@ -1347,6 +1362,12 @@ impl Inner { *slot = Slot::Idle; // Under the slot lock, so a later join cannot meet this close. self.close_video(); + // The details never carry over to another call (ADR-0066). + self.stats_on.send_replace(false); + } + drop(slot); + if mine && let Some(listener) = plain(&self.stats_listener).clone() { + listener(None); } mine } @@ -1408,6 +1429,8 @@ impl CallController { listener: Mutex::new(None), video_listener: Mutex::new(None), sound_listener: Mutex::new(None), + stats_on: watch::channel(false).0, + stats_listener: Mutex::new(None), video: Mutex::new(None), next_id: AtomicU64::new(0), device_test: Mutex::new(DeviceTestSlot::default()), @@ -1442,6 +1465,42 @@ impl CallController { *plain(&self.inner.sound_listener) = Some(listener); } + /// Sets what takes the call's statistics readings (ADR-0066). It is + /// called from the call task with the newest reading while they are on, + /// and with `None` when they stop. + pub fn set_stats_listener(&self, listener: StatsListener) { + *plain(&self.inner.stats_listener) = Some(listener); + } + + /// Turns the call's technical details on or off (ADR-0066): the worker + /// reads its statistics only while they are on. Turning them on needs a + /// running call, or a joining call that the end of the session has not + /// stopped (`NotInCall` otherwise); off always works. They are off again + /// when the call or the session ends. + pub fn set_stats(&self, on: bool) -> Result<(), CallError> { + let slot = self.inner.slot(); + let no_call = match &*slot { + Slot::Idle => true, + // A join that the end of the session stopped keeps its slot + // until its guard drops, but it is no call to read. + Slot::Joining(join) => join.flags.ended(), + Slot::Running(_) => false, + }; + if on && no_call { + return Err(CallError::NotInCall); + } + // Under the slot lock, so the end of a call cannot meet a late `on`. + let was = self.inner.stats_on.send_replace(on); + drop(slot); + if was + && !on + && let Some(listener) = plain(&self.inner.stats_listener).clone() + { + listener(None); + } + Ok(()) + } + /// Calls `listener` after each change of the device test's status, on /// the test's thread. It must not block and must not call the controller. pub fn set_test_listener(&self, listener: Listener) { @@ -2250,7 +2309,7 @@ impl CallController { self.stop_device_test(); let (room_id, kill) = { let mut slot = self.inner.slot(); - match std::mem::replace(&mut *slot, Slot::Idle) { + let stopped = match std::mem::replace(&mut *slot, Slot::Idle) { Slot::Idle => return, Slot::Joining(join) => { // The flag is set under the lock a join takes to start @@ -2268,8 +2327,22 @@ impl CallController { } (run.room_id, Some(run.kill)) } - } + }; + // The details stop here, under the slot lock, for a joining call + // too (ADR-0066): a running call's slot is free now, so its + // task's own `release` finds nothing to reset, and a join's + // guard frees its slot only when the join unwinds. So they never + // carry over to the next call, and a stopped join cannot turn + // them on again. + self.inner.stats_on.send_replace(false); + stopped }; + // The waiting reading goes before the end is published, so no + // reading reaches the page after the call ended. A join's `release` + // tells the listener again later, which drops nothing more. + if let Some(listener) = plain(&self.inner.stats_listener).clone() { + listener(None); + } if let Some(kill) = kill { kill.kill(); } @@ -2928,6 +3001,14 @@ fn take_newer_choice( } } +/// Replaces a kept statistics switch with a newer one that waits unread in +/// `switch`, so a retry never sends an older value. +fn take_newer_switch(switch: &mut watch::Receiver, pending: &mut Option<(Instant, bool)>) { + if switch.has_changed().unwrap_or(false) { + *pending = Some((Instant::now(), *switch.borrow_and_update())); + } +} + /// Gives the call a microphone and speaker choice. The same choice as the /// last one changes nothing, so saving only the camera does not restart the /// sound of a running call; with `again` (the last change failed) it is @@ -3639,6 +3720,19 @@ impl Call { self.participant_level(inner, *connection, identity, *level); return Ok(()); } + // The technical details go to the page only while it asks for them + // (ADR-0066); a reading that comes after they went off is dropped. + if let FromWorker::Stats(stats) = event { + if *inner.stats_on.borrow() + && let Some(listener) = plain(&inner.stats_listener).clone() + && let Some(view) = stats::view(stats, |connection, identity| { + self.view.level_member(connection, identity) + }) + { + listener(Some(view)); + } + return Ok(()); + } // A camera that is not on has no capture left: its remote is used up. // An `On` after a remote went (and no off since) is a capture over it. if let FromWorker::Camera { state } = event { @@ -3950,6 +4044,28 @@ impl Call { Ok(()) } + /// Gives the worker the statistics switch in `pending` (ADR-0066). A + /// value that the worker already has is not sent again. When the queue + /// is full, the switch waits for the next retry instead of ending the + /// call; a newer value replaces a waiting one. + fn apply_stats( + &self, + pending: &mut Option<(Instant, bool)>, + sent: &mut bool, + ) -> Result<(), EndReason> { + if let Some((_, on)) = pending.take() { + if on == *sent { + return Ok(()); + } + if self.queue_worker(ToWorker::SetStats { on })? { + *sent = on; + } else { + *pending = Some((Instant::now() + UNSENT_RETRY, on)); + } + } + Ok(()) + } + /// Sends the pending device choice (ADR-0059). A full queue keeps it for /// a retry, so a busy worker does not end the call; a newer choice /// replaces it. @@ -4138,6 +4254,12 @@ impl Call { let mut diagnostics = crate::diagnostics::global().watch(); diagnostics.mark_changed(); let mut pending_diagnostics: Option<(Instant, bool)> = None; + // The statistics switch (ADR-0066), sent on each change. The worker + // starts with it off, so `stats_sent` starts off too. + let mut stats_switch = inner.stats_on.subscribe(); + stats_switch.mark_changed(); + let mut pending_stats: Option<(Instant, bool)> = None; + let mut stats_sent = false; // The newest device choice while the worker's queue is full. let mut pending_devices: Option<(Instant, DeviceChoice)> = None; self.start_keys(inner).await?; @@ -4151,6 +4273,7 @@ impl Call { let due = pending_own.as_ref().map(|(at, _)| *at); let retry = self.unsent_retry; let diagnostics_due = pending_diagnostics.map(|(at, _)| at); + let stats_due = pending_stats.map(|(at, _)| at); let devices_due = pending_devices.as_ref().map(|(at, _)| *at); tokio::select! { _ = &mut *stop => return Ok(()), @@ -4212,6 +4335,23 @@ impl Call { None => std::future::pending().await, } } => self.apply_diagnostics(&mut pending_diagnostics)?, + Ok(()) = stats_switch.changed() => { + let on = *stats_switch.borrow_and_update(); + pending_stats = Some((Instant::now(), on)); + self.apply_stats(&mut pending_stats, &mut stats_sent)?; + } + () = async { + match stats_due { + Some(at) => time::sleep_until(at.into()).await, + None => std::future::pending().await, + } + } => { + // `select!` picks a ready arm at random: a newer switch + // that waits unread replaces the kept one first, so the + // worker never gets an older value. + take_newer_switch(&mut stats_switch, &mut pending_stats); + self.apply_stats(&mut pending_stats, &mut stats_sent)?; + } remote = portal_done(&mut self.portal) => self.portal_finished(inner, remote)?, (picked, cancelled) = screen_pick_done(&mut self.screen_pick) => { if cancelled { @@ -6518,6 +6658,22 @@ mod tests { assert!(!devices.has_changed().unwrap(), "the newer choice is read"); } + /// GIVEN a statistics switch kept for a retry and a newer value not read + /// yet WHEN the retry is due THEN the newer value replaces the kept one; + /// with no newer value the kept one stays. + #[test] + fn given_the_statistics_switch_with_a_newer_value_then_a_retry_sends_the_newer() { + let sender = watch::channel(false).0; + let mut switch = sender.subscribe(); + let mut pending = Some((Instant::now(), true)); + take_newer_switch(&mut switch, &mut pending); + assert_eq!(pending.map(|(_, on)| on), Some(true), "nothing newer"); + sender.send_replace(false); + take_newer_switch(&mut switch, &mut pending); + assert_eq!(pending.map(|(_, on)| on), Some(false), "the newer wins"); + assert!(!switch.has_changed().unwrap(), "the newer value is read"); + } + /// GIVEN two members with a sound level WHEN one leaves the call THEN /// its level goes from the meters at once, and the member that stays /// keeps its level; a prune with no change sends nothing. @@ -6807,6 +6963,252 @@ mod tests { assert_eq!(changes.load(Ordering::SeqCst), before); } + /// A slot with a running call, for the statistics switch. + fn run_slot(calls: &CallController, id: u64) { + let (commands, _rx) = mpsc::channel(1); + *calls.inner.slot() = Slot::Running(RunHandle { + id, + room_id: room_id!("!r:example.org").to_owned(), + flags: Arc::new(Flags::default()), + kill: killer().1, + stop: None, + commands, + camera_wanted: Arc::new(AtomicBool::new(false)), + screen_control: Arc::default(), + volume: watch::channel(MAX_VOLUME_PERCENT).0, + devices: watch::channel(None).0, + microphone: watch::channel(None).0, + task: None, + }); + } + + fn join_slot(calls: &CallController, id: u64) { + *calls.inner.slot() = Slot::Joining(Joining { + id, + room_id: room_id!("!r:example.org").to_owned(), + flags: Arc::new(Flags::default()), + kill: Arc::default(), + devices: watch::channel(None).0, + microphone: watch::channel(None).0, + }); + } + + fn stats_reading(identity: &str) -> persephone_call_protocol::CallStats { + persephone_call_protocol::CallStats { + remotes: vec![persephone_call_protocol::RemoteStats { + connection: 0, + identity: identity.to_owned(), + audio: None, + video: None, + }], + ..persephone_call_protocol::CallStats::default() + } + } + + /// GIVEN a call WHEN the worker reports statistics THEN they reach the + /// listener only while the page has them on, named by member, and never + /// change the call state; a reading after they went off is dropped. + #[test] + fn given_statistics_then_only_a_page_that_asked_for_them_gets_them() { + let fixture = test_call( + no_admission(), + Arc::new(Flags::default()), + Arc::new(AtomicBool::new(false)), + ); + let calls = controller(FakeHost::new(true, None)); + let changes = Arc::new(AtomicUsize::new(0)); + let seen = changes.clone(); + calls.set_listener(Arc::new(move || { + seen.fetch_add(1, Ordering::SeqCst); + })); + let heard = Arc::new(Mutex::new(Vec::new())); + let taken = heard.clone(); + calls.set_stats_listener(Arc::new(move |stats| plain(&taken).push(stats))); + let inner = calls.inner.clone(); + let mut call = fixture.call; + call.view = view(); + call.view.set_members(vec![member( + "@a:example.org", + "A", + "https://sfu.example.org", + )]); + let backend = call.view.members[0].backend_identities[0].clone(); + let reading = FromWorker::Stats(stats_reading(&backend)); + let state = call.view.state(); + let before = changes.load(Ordering::SeqCst); + + // Off: nothing leaves. + assert_eq!(call.worker_event(&inner, &reading), Ok(())); + assert!(plain(&heard).is_empty()); + + // On: the reading leaves, named by the member the identity stands for. + inner.stats_on.send_replace(true); + assert_eq!(call.worker_event(&inner, &reading), Ok(())); + let sent = plain(&heard).clone(); + assert_eq!(sent.len(), 1); + let stats = sent[0].as_ref().expect("a reading"); + assert_eq!(stats.participants.len(), 1); + assert_eq!(stats.participants[0].user_id, "@a:example.org"); + assert_eq!(stats.participants[0].device_id, "A"); + + // A participant that is no member is left out; the rest goes. + let stranger = FromWorker::Stats(stats_reading("stranger")); + assert_eq!(call.worker_event(&inner, &stranger), Ok(())); + assert!( + plain(&heard)[1] + .as_ref() + .is_some_and(|stats| stats.participants.is_empty()) + ); + + // Off again: a reading that was already on its way is dropped. + inner.stats_on.send_replace(false); + assert_eq!(call.worker_event(&inner, &reading), Ok(())); + assert_eq!(plain(&heard).len(), 2); + assert_eq!(call.view.state(), state); + assert_eq!(changes.load(Ordering::SeqCst), before); + } + + /// GIVEN no call WHEN the page turns the statistics on THEN it is refused + /// and nothing is on; GIVEN a call WHEN it turns them on and off THEN the + /// switch follows, and turning them off tells the listener once. + #[test] + fn given_no_call_then_statistics_cannot_be_turned_on() { + let calls = controller(FakeHost::new(true, None)); + let heard = Arc::new(Mutex::new(Vec::new())); + let taken = heard.clone(); + calls.set_stats_listener(Arc::new(move |stats| plain(&taken).push(stats))); + assert!(matches!(calls.set_stats(true), Err(CallError::NotInCall))); + assert!(!*calls.inner.stats_on.borrow()); + assert!(calls.set_stats(false).is_ok(), "off always works"); + assert!(plain(&heard).is_empty(), "off while off tells nobody"); + run_slot(&calls, 3); + assert!(calls.set_stats(true).is_ok()); + assert!(*calls.inner.stats_on.borrow()); + assert!(calls.set_stats(false).is_ok()); + assert!(!*calls.inner.stats_on.borrow()); + assert_eq!(*plain(&heard), [None]); + } + + /// GIVEN statistics on WHEN the call ends THEN they are off in the same + /// step, so the next call starts with them off, and the listener drops + /// the last reading. + #[test] + fn given_statistics_on_when_the_call_ends_then_they_are_off() { + let calls = controller(FakeHost::new(true, None)); + let heard = Arc::new(Mutex::new(Vec::new())); + let taken = heard.clone(); + calls.set_stats_listener(Arc::new(move |stats| plain(&taken).push(stats))); + run_slot(&calls, 5); + assert!(calls.set_stats(true).is_ok()); + assert!( + !calls.inner.release(4), + "another call's end changes nothing" + ); + assert!(*calls.inner.stats_on.borrow()); + assert!(calls.inner.release(5)); + assert!(!*calls.inner.stats_on.borrow()); + assert_eq!(*plain(&heard), [None]); + assert!(matches!(calls.set_stats(true), Err(CallError::NotInCall))); + } + + /// GIVEN statistics on in a running call WHEN the session ends (lock, + /// sign-out) THEN they are off in the same step and the listener drops + /// the last reading, although the task's own release then finds nothing, + /// so the next call starts with them off. + #[test] + fn given_statistics_on_when_the_session_ends_then_they_are_off() { + let calls = controller(FakeHost::new(true, None)); + let heard = Arc::new(Mutex::new(Vec::new())); + let taken = heard.clone(); + calls.set_stats_listener(Arc::new(move |stats| plain(&taken).push(stats))); + run_slot(&calls, 6); + assert!(calls.set_stats(true).is_ok()); + calls.stop_for_session_end(); + assert!(!*calls.inner.stats_on.borrow()); + assert_eq!(*plain(&heard), [None]); + assert!(!calls.inner.release(6), "the task's release finds nothing"); + assert_eq!(*plain(&heard), [None], "told once"); + run_slot(&calls, 7); + assert!(!*calls.inner.stats_on.borrow(), "the next call starts off"); + } + + /// GIVEN statistics on while a call joins WHEN the session ends (lock, + /// sign-out) THEN they are off in the same step and the waiting reading + /// is dropped before the end is published; the stopped join takes no new + /// start; and the join's own release later frees the slot with them off. + #[test] + fn given_statistics_on_while_joining_when_the_session_ends_then_they_are_off() { + let calls = controller(FakeHost::new(true, None)); + let order = Arc::new(Mutex::new(Vec::new())); + let taken = order.clone(); + calls.set_stats_listener(Arc::new(move |stats| { + plain(&taken).push(if stats.is_none() { + "reading dropped" + } else { + "reading" + }); + })); + let taken = order.clone(); + calls.set_listener(Arc::new(move || plain(&taken).push("state"))); + join_slot(&calls, 8); + assert!( + calls.set_stats(true).is_ok(), + "a joining call may turn them on" + ); + plain(&order).clear(); + calls.stop_for_session_end(); + assert!(!*calls.inner.stats_on.borrow()); + assert!(matches!(calls.state(), CallState::Ended { .. })); + assert_eq!(*plain(&order), ["reading dropped", "state"]); + assert!( + matches!(calls.set_stats(true), Err(CallError::NotInCall)), + "a stopped join takes no new start" + ); + assert!(!*calls.inner.stats_on.borrow()); + assert!(calls.set_stats(false).is_ok(), "off always works"); + assert!(calls.inner.release(8), "the join's guard frees its slot"); + assert!(!*calls.inner.stats_on.borrow()); + run_slot(&calls, 9); + assert!(!*calls.inner.stats_on.borrow(), "the next call starts off"); + } + + /// GIVEN a running call WHEN its task runs THEN a switch of the statistics + /// reaches the worker once, and the same value is not sent again. The + /// test reads what the worker gets, not only the `sent` flag. + #[test] + fn given_the_statistics_switch_when_applied_then_the_worker_gets_each_change_once() { + let mut fixture = test_call( + no_admission(), + Arc::new(Flags::default()), + Arc::new(AtomicBool::new(false)), + ); + let (call, to_worker) = (&mut fixture.call, &mut fixture.to_worker); + let mut sent = false; + let mut pending = Some((Instant::now(), false)); + assert_eq!(call.apply_stats(&mut pending, &mut sent), Ok(())); + assert!(pending.is_none() && !sent); + assert!(to_worker.try_recv().is_err(), "off to off is not sent"); + pending = Some((Instant::now(), true)); + assert_eq!(call.apply_stats(&mut pending, &mut sent), Ok(())); + assert!(pending.is_none() && sent); + assert!(matches!( + to_worker.try_recv(), + Ok(ToWorker::SetStats { on: true }) + )); + pending = Some((Instant::now(), true)); + assert_eq!(call.apply_stats(&mut pending, &mut sent), Ok(())); + assert!(pending.is_none() && sent); + assert!(to_worker.try_recv().is_err(), "on to on is not sent again"); + pending = Some((Instant::now(), false)); + assert_eq!(call.apply_stats(&mut pending, &mut sent), Ok(())); + assert!(pending.is_none() && !sent); + assert!(matches!( + to_worker.try_recv(), + Ok(ToWorker::SetStats { on: false }) + )); + assert!(to_worker.try_recv().is_err(), "the off goes once"); + } + /// GIVEN a call alone for 30 seconds with a join that waits unread /// WHEN the alone deadline fires THEN the join is applied first and the /// call stays; with nothing waiting after another 30 seconds alone it diff --git a/crates/core/src/calls/mod.rs b/crates/core/src/calls/mod.rs index 2a106b0f..037e10b2 100644 --- a/crates/core/src/calls/mod.rs +++ b/crates/core/src/calls/mod.rs @@ -58,6 +58,7 @@ pub mod ring_events; pub mod rings; pub mod screen; pub mod sfu; +pub mod stats; pub mod status; pub mod video; pub mod worker; diff --git a/crates/core/src/calls/stats.rs b/crates/core/src/calls/stats.rs new file mode 100644 index 00000000..5a0cc80a --- /dev/null +++ b/crates/core/src/calls/stats.rs @@ -0,0 +1,231 @@ +//! The call statistics that the page may see (ADR-0066). +//! +//! The worker's message is already bounded by the call protocol reader. This +//! module names each remote entry by the member it stands for, leaves out an +//! entry that no member stands for, and checks the result once more against +//! the limits the UI host enforces. + +use persephone_call_protocol as worker; +use persephone_contracts::{ + CallStats, CallStatsAudioReceived, CallStatsAudioSent, CallStatsConnection, CallStatsLimit, + CallStatsParticipant, CallStatsVideoReceived, CallStatsVideoSent, +}; + +// The page's bounds repeat the worker protocol's. The worker clamps each +// number to its protocol bound, and `CallStats::within_limits` drops a +// reading whole on a number over the page's bound, so the two must match. +const _: () = { + assert!(persephone_contracts::CALL_STATS_KBPS_MAX == worker::MAX_STATS_KBPS); + assert!(persephone_contracts::CALL_STATS_MS_MAX == worker::MAX_STATS_MS); + assert!(persephone_contracts::CALL_STATS_FPS_MAX == worker::MAX_STATS_FPS); + assert!(persephone_contracts::CALL_STATS_SIDE_MAX == worker::MAX_STATS_SIDE); + assert!(persephone_contracts::CALL_STATS_CONNECTIONS_MAX == worker::MAX_STATS_CONNECTIONS); + assert!(persephone_contracts::CALL_PARTICIPANTS_MAX == worker::MAX_PARTICIPANTS); + assert!(persephone_contracts::CALL_SOUND_LEVEL_MAX == worker::MAX_SOUND_LEVEL); +}; + +fn limit(limit: worker::QualityLimit) -> CallStatsLimit { + match limit { + worker::QualityLimit::None => CallStatsLimit::None, + worker::QualityLimit::Cpu => CallStatsLimit::Cpu, + worker::QualityLimit::Bandwidth => CallStatsLimit::Bandwidth, + worker::QualityLimit::Other => CallStatsLimit::Other, + } +} + +fn audio_sent(audio: &worker::AudioSendStats) -> CallStatsAudioSent { + CallStatsAudioSent { + level: audio.level, + bitrate_kbps: audio.bitrate_kbps, + packets_sent: audio.packets_sent, + packets_lost: audio.packets_lost, + jitter_ms: audio.jitter_ms, + rtt_ms: audio.rtt_ms, + } +} + +fn video_sent(video: &worker::VideoSendStats) -> CallStatsVideoSent { + CallStatsVideoSent { + fps: video.fps, + width: video.width, + height: video.height, + bitrate_kbps: video.bitrate_kbps, + limit: limit(video.limit), + packets_lost: video.packets_lost, + } +} + +fn audio_received(audio: &worker::AudioReceiveStats) -> CallStatsAudioReceived { + CallStatsAudioReceived { + level: audio.level, + bitrate_kbps: audio.bitrate_kbps, + packets_received: audio.packets_received, + packets_lost: audio.packets_lost, + jitter_ms: audio.jitter_ms, + concealed_percent: audio.concealed_percent, + } +} + +fn video_received(video: &worker::VideoReceiveStats) -> CallStatsVideoReceived { + CallStatsVideoReceived { + fps: video.fps, + width: video.width, + height: video.height, + bitrate_kbps: video.bitrate_kbps, + dropped_fps: video.dropped_fps, + packets_lost: video.packets_lost, + } +} + +/// The page's view of `stats`. `member` gives the user ID and device ID of +/// the member that a worker participant (its connection and identity) +/// stands for, or `None` when the participant is no current member or its +/// connection does not speak for it. A device that more than one entry +/// stands for is listed once. `None` when the result is out of its limits. +pub fn view( + stats: &worker::CallStats, + member: impl Fn(u8, &str) -> Option<(String, String)>, +) -> Option { + let mut participants: Vec = Vec::new(); + for remote in &stats.remotes { + let Some((user_id, device_id)) = member(remote.connection, &remote.identity) else { + continue; + }; + if participants + .iter() + .any(|seen| seen.user_id == user_id && seen.device_id == device_id) + { + continue; + } + participants.push(CallStatsParticipant { + user_id, + device_id, + audio: remote.audio.as_ref().map(audio_received), + video: remote.video.as_ref().map(video_received), + }); + } + let view = CallStats { + microphone: stats.microphone.as_ref().map(audio_sent), + camera: stats.camera.as_ref().map(video_sent), + screen: stats.screen.as_ref().map(video_sent), + participants, + connections: stats + .connections + .iter() + .map(|link| CallStatsConnection { + connection: link.connection, + outgoing_kbps: link.outgoing_kbps, + send_kbps: link.send_kbps, + receive_kbps: link.receive_kbps, + rtt_ms: link.rtt_ms, + }) + .collect(), + }; + view.within_limits().then_some(view) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn remote(connection: u8, identity: &str) -> worker::RemoteStats { + worker::RemoteStats { + connection, + identity: identity.to_owned(), + audio: Some(worker::AudioReceiveStats { + level: 7, + bitrate_kbps: Some(30), + packets_received: 5, + packets_lost: 1, + jitter_ms: 2, + concealed_percent: None, + }), + video: None, + } + } + + fn members(connection: u8, identity: &str) -> Option<(String, String)> { + match (connection, identity) { + (0, "bob-backend") | (1, "bob-other") => { + Some(("@bob:example.org".into(), "BOB".into())) + } + (0, "eve-backend") => Some(("@eve:example.org".into(), "EVE".into())), + _ => None, + } + } + + /// GIVEN a reading with members, strangers and a repeated device WHEN it + /// is made for the page THEN only members are named, each device once, + /// and the numbers carry over. + #[test] + fn given_a_reading_when_viewed_then_only_current_members_are_named_once() { + let stats = worker::CallStats { + microphone: Some(worker::AudioSendStats { + level: 40, + bitrate_kbps: Some(32), + packets_sent: 9, + packets_lost: Some(1), + jitter_ms: Some(3), + rtt_ms: Some(20), + }), + remotes: vec![ + remote(0, "bob-backend"), + remote(0, "stranger"), + remote(1, "bob-other"), + remote(2, "bob-backend"), + remote(0, "eve-backend"), + ], + connections: vec![worker::ConnectionStats { + connection: 0, + outgoing_kbps: Some(2500), + send_kbps: None, + receive_kbps: Some(40), + rtt_ms: Some(18), + }], + ..worker::CallStats::default() + }; + let view = view(&stats, members).expect("within limits"); + let names: Vec<_> = view + .participants + .iter() + .map(|person| person.device_id.as_str()) + .collect(); + assert_eq!(names, ["BOB", "EVE"]); + assert_eq!(view.participants[0].audio.as_ref().unwrap().level, 7); + assert_eq!(view.microphone.as_ref().unwrap().rtt_ms, Some(20)); + assert_eq!(view.connections[0].outgoing_kbps, Some(2500)); + assert_eq!(view.connections[0].send_kbps, None); + assert!(view.camera.is_none() && view.screen.is_none()); + } + + /// GIVEN a member with an ID that the page would refuse WHEN the reading + /// is made THEN the whole reading is dropped. + #[test] + fn given_an_id_over_the_limit_when_viewed_then_the_reading_is_dropped() { + let stats = worker::CallStats { + remotes: vec![remote(0, "bob-backend")], + ..worker::CallStats::default() + }; + let long = |_: u8, _: &str| { + Some(( + "u".repeat(persephone_contracts::CALL_USER_ID_BYTES_MAX + 1), + "D".to_owned(), + )) + }; + assert!(view(&stats, long).is_none()); + } + + /// GIVEN a limit reason WHEN it is viewed THEN each worker value has its + /// page value. + #[test] + fn given_each_quality_limit_when_viewed_then_it_maps_one_to_one() { + for (from, to) in [ + (worker::QualityLimit::None, CallStatsLimit::None), + (worker::QualityLimit::Cpu, CallStatsLimit::Cpu), + (worker::QualityLimit::Bandwidth, CallStatsLimit::Bandwidth), + (worker::QualityLimit::Other, CallStatsLimit::Other), + ] { + assert_eq!(limit(from), to); + } + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 42d2d9ec..2ebc28c9 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -179,6 +179,9 @@ struct Notifications { /// The newest levels of the other devices in the call, not yet sent /// (ADR-0059). They leave with the sound level, under its gap. participant_levels: Option>, + /// The newest call statistics reading, not yet sent (ADR-0066). A newer + /// one replaces it; it is dropped when the statistics go off. + call_stats: Option, /// The device test changed since the last notification (ADR-0059). device_test_changed: bool, /// The report of third-party modules changed since the last notification. @@ -338,6 +341,17 @@ impl Hub { self.changed.notify_all(); } + /// Keeps `stats` as the call statistics to send, or drops the waiting + /// reading for `None`. Only the newest waits. + fn call_stats_changed(&self, stats: Option) { + let mut notifications = lock(&self.notifications); + let wake = stats.is_some(); + notifications.call_stats = stats; + if wake { + self.changed.notify_all(); + } + } + /// The device test changed: one `call_device_test_changed` event waits. fn device_test_changed(&self) { let mut notifications = lock(&self.notifications); @@ -776,6 +790,12 @@ impl Core { } })); let tell = Arc::downgrade(&hub); + calls.set_stats_listener(Arc::new(move |stats| { + if let Some(hub) = tell.upgrade() { + hub.call_stats_changed(stats); + } + })); + let tell = Arc::downgrade(&hub); calls.set_test_listener(Arc::new(move || { if let Some(hub) = tell.upgrade() { hub.device_test_changed(); @@ -1537,6 +1557,7 @@ impl Core { } self.call_microphone(*auto_level, *gain) } + Call::CallStats { on } => self.call_stats(*on), Call::CallCamera { on } => self.call_camera(*on), Call::CallScreen { on } => self.call_screen(*on), // Its picture reaches only `serve`. @@ -2751,6 +2772,26 @@ impl Core { ok(&calls::status::status(&self.calls.state())) } + /// Turns the call's technical details on or off (ADR-0066). They are + /// read and sent only while on, which needs a call; turning them off + /// also drops a reading that waits. + fn call_stats(&self, on: bool) -> Outcome { + // Turning them off always works (ADR-0066), also while the session + // is locked or busy, so a closed panel never leaves them reading. + if on && let Err(code) = self.calls_open() { + return Outcome::Error(code); + } + match self.calls.set_stats(on) { + Ok(()) => { + if !on { + self.hub.call_stats_changed(None); + } + Outcome::Ok(serde_json::Value::Null) + } + Err(_) => Outcome::Error(ErrorCode::Unavailable), + } + } + /// Turns the camera on or off. Unlike mute, no call is an error: there is /// nothing to turn on. fn call_camera(&self, on: bool) -> Outcome { @@ -3875,6 +3916,7 @@ impl Core { && !notifications.modules_changed && !notifications.diagnostics_changed && !notifications.device_test_changed + && notifications.call_stats.is_none() && notifications.toast.is_none() && !video_due && !sound_due @@ -3939,6 +3981,10 @@ impl Core { }; let device_test = std::mem::take(&mut notifications.device_test_changed) .then_some(Event::CallDeviceTestChanged {}); + let call_stats = notifications + .call_stats + .take() + .map(|stats| Event::CallStats { stats }); let session = std::mem::take(&mut notifications.session_changed).then_some(Event::SessionChanged {}); let list = std::mem::take(&mut notifications.room_list_changed) @@ -3979,6 +4025,7 @@ impl Core { .chain(video) .chain(sound) .chain(levels) + .chain(call_stats) .chain(device_test) .chain(modules) .chain(diagnostics) @@ -4021,6 +4068,8 @@ impl Core { } fn close(&self) { + // The page that asked for the call statistics is gone (ADR-0066). + let _ = self.calls.set_stats(false); self.hub.closing.store(true, Ordering::SeqCst); lock(&self.hub.notifications).closed = true; self.hub.changed.notify_all(); @@ -4664,6 +4713,53 @@ mod tests { ); } + /// GIVEN several statistics readings before the event writer runs WHEN + /// the events are taken THEN only the newest leaves, at once, and a + /// reading dropped by the switch never does. + #[test] + fn given_statistics_readings_then_only_the_newest_leaves() { + let core = Core::default(); + let reading = |level: u8| persephone_contracts::CallStats { + microphone: Some(persephone_contracts::CallStatsAudioSent { + level, + bitrate_kbps: None, + packets_sent: 0, + packets_lost: None, + jitter_ms: None, + rtt_ms: None, + }), + ..persephone_contracts::CallStats::default() + }; + core.hub.call_stats_changed(Some(reading(1))); + core.hub.call_stats_changed(Some(reading(2))); + assert_eq!( + core.take_events(), + Some(vec![Event::CallStats { stats: reading(2) }]) + ); + // Dropped while it waits: nothing leaves, and the writer does not + // wake for it. + core.hub.call_stats_changed(Some(reading(3))); + core.hub.call_stats_changed(None); + core.hub.calls_changed(); + assert_eq!(core.take_events(), Some(vec![Event::CallChanged {}])); + } + + /// GIVEN the statistics command WHEN there is no call THEN turning them + /// on is `unavailable` and turning them off works, also after the UI + /// connection closed. + #[test] + fn given_the_statistics_command_then_it_needs_a_call() { + let core = Core::default(); + let stats = |on| core.call_stats(on); + assert!(matches!( + stats(true), + Outcome::Error(ErrorCode::Unavailable) + )); + assert!(matches!(stats(false), Outcome::Ok(serde_json::Value::Null))); + core.close(); + assert!(core.calls.set_stats(false).is_ok()); + } + /// GIVEN a waiting video event WHEN the connection closes THEN the writer /// stops instead of waiting for the gap. #[test] diff --git a/crates/core/tests/serve.rs b/crates/core/tests/serve.rs index d88964ec..1585d8b0 100644 --- a/crates/core/tests/serve.rs +++ b/crates/core/tests/serve.rs @@ -713,8 +713,9 @@ fn given_call_commands_then_room_ids_are_checked_and_synthetic_data_has_no_call( } /// GIVEN a profile WHEN it is locked THEN every call command is refused as -/// `locked`; WHEN it is open and has no account THEN status, leave and mute -/// answer idle, and readiness has no homeserver to ask. +/// `locked`, but turning the statistics off still works; WHEN it is open and +/// has no account THEN status, leave and mute answer idle, and readiness has +/// no homeserver to ask. #[test] fn given_a_profile_then_call_commands_follow_the_session() { use persephone_contracts::{CallReadiness, CallStatus}; @@ -776,6 +777,7 @@ fn given_a_profile_then_call_commands_follow_the_session() { video: false, }, Call::CallCamera { on: true }, + Call::CallStats { on: true }, ] { assert_eq!( answer::(&core, call.clone()), @@ -783,6 +785,12 @@ fn given_a_profile_then_call_commands_follow_the_session() { "{call:?}" ); } + // Turning the statistics off always works, so a closed panel or window + // never leaves them reading. + assert_eq!( + answer::(&core, Call::CallStats { on: false }), + Ok(serde_json::Value::Null) + ); } /// GIVEN no call WHEN the page turns the camera on or off THEN the core diff --git a/docs/adr/0065-choose-the-large-video-and-change-devices-in-the-call-window.md b/docs/adr/0065-choose-the-large-video-and-change-devices-in-the-call-window.md new file mode 100644 index 00000000..ce9eac57 --- /dev/null +++ b/docs/adr/0065-choose-the-large-video-and-change-devices-in-the-call-window.md @@ -0,0 +1,113 @@ +# Choose the large video and change devices in the call window + +* Status: proposed +* Deciders: project owner +* Date: 2026-11-25 + +Technical Story: the call window of ADR-0060 shows every feed at the same +size. A viewer who wants to read a shared screen, or to watch one person, has +no way to enlarge it. A viewer who plugs in a headset must leave the call +window and use the main window's settings. + +## Context and Problem Statement + +The call window shows a grid with one cell for you, one for each other device +and one for a shared screen. The worker sends one picture for each tile at a +fixed size: at most 640 by 360 pixels for a camera and 1280 by 720 for the +screen (ADR-0048, ADR-0053). The window may call only the commands in its +capability (ADR-0060). How does the viewer choose a large feed and change +devices, without asking the core for larger pictures and without giving the +call window more commands than it needs? + +## Decision Drivers + +* Keep the pictures and the worker as they are: the page scales with CSS. +* Keep the call window's commands to the fewest that the feature needs. +* Keep the choice logic testable without a web view. +* Keep the controls usable by keyboard and by screen reader. + +## Considered Options + +* Selectable feeds with a large view and a row of small tiles; a device panel + inside the call window +* A fixed layout that always enlarges the screen share; devices only in the + main window +* Ask the core for a larger picture for the large feed + +## Decision Outcome + +Chosen option: "Selectable feeds with a large view and a row of small tiles; +a device panel inside the call window", because it needs no change to the +worker or the core and adds two read and write commands that the main window +already has. + +### Large video + +* Each feed (your camera, each other camera, the shared screen) is one + button with `aria-pressed` and a visible focus ring. +* With no pick the window shows the grid of ADR-0060. Selecting a feed shows + it large. The other feeds become small tiles in one row along the bottom; + the row scrolls sideways when the tiles do not fit. Selecting another small + feed makes it large and puts the one that was large back in the row. + Selecting the large feed again, or "Show all", shows the grid. +* When a screen is shared and the viewer has picked nothing, the screen is + large. A pick by the viewer always wins, including "Show all": the grid + stays while that share runs, and the next share is shown large again. +* A feed that goes away (the person leaves, the camera goes off, the share + ends) drops its pick. The window then shows the grid, or the screen by the + rule above. The pick is also dropped when the call ends. +* The rules are pure functions in `frontend/src/callView.ts`, with Node tests. +* The picture sizes do not change. A large feed is the same picture scaled + by CSS with its aspect ratio kept, so a camera is enlarged beyond its + 640 by 360 pixels and looks soft. A feed that moves between the grid, the + large view and the row gets a new canvas; the page draws the newest picture + again at once from a copy it keeps for each tile. The copy is kept with the + feed (the device and stream) it belongs to, and is drawn only while that + feed is still on the tile, so a tile that another person takes next never + shows the last picture of the one before. + +### Devices in the call window + +* A "Device settings" button in the call window's controls opens a panel with + the microphone, speaker and camera. The panel lists the devices each time it + opens. The button, or Escape, closes it and the focus returns to the button. +* A choice is saved with `set_call_devices` and applies to the running call + through the switch of ADR-0059. The core checks the IDs again. +* Saves go one at a time, in the order the menus changed, and each sends all + three menus as they were then. A menu changed while a save runs is + therefore sent after it and never dropped, and only the newest save sets + the line under the menus. The menus stay usable while a save runs; they + wait only while the lists load. The order rules are in + `frontend/src/callDevicePanel.ts`, with Node tests. +* The capability `call` gets two more commands: `call_devices` and + `set_call_devices`. It still has no device tests, no call start, no rooms + and no files. The host test of the call window's command set checks this. +* The panel shows what happened: saved; the chosen device is not connected + (`not_found`); the microphone could not be opened and the old one is kept + (`kept`); this system cannot switch during a call (`unsupported`, Linux + today); or the sound may have stopped and a lost speaker needs a rejoin + (`failed`). A call that ends because of its audio device shows its end + reason as before (`AudioDevice`). +* The call status has no mark for a change that worked. The panel therefore + says only "saved" when it saved the choice and the status shows no + failure, and adds that a failure shows on the same line. It cannot tell + "worked" from "not answered yet", so it never says "switched". + A failure that the status shows is shown whether or not the panel saved + anything, so a failure from before the panel opened (or from the main + window's settings) is in view when the panel opens to fix it. + The worker's answer can arrive after the save, and a failure from an earlier + change stays until the worker answers the new one. A camera change applies + at the next camera start (ADR-0059). + +### Positive Consequences + +* A viewer can read a shared screen or watch one person at a larger size. +* Devices change without leaving the call window. + +### Negative Consequences + +* Two more commands in the call window's capability. +* A camera picture is not sharper when it is large. +* "Switched" is a reading of the absence of a failure, not an + acknowledgement. A later change to the status can add one. +* The page keeps the newest picture of each tile, up to about 8 MB. diff --git a/docs/adr/0066-show-call-statistics-on-request.md b/docs/adr/0066-show-call-statistics-on-request.md new file mode 100644 index 00000000..a4dcc5b6 --- /dev/null +++ b/docs/adr/0066-show-call-statistics-on-request.md @@ -0,0 +1,256 @@ +# Show call statistics on request + +* Status: proposed +* Deciders: project owner +* Date: 2026-11-25 + +Technical Story: on 25 November 2026 the owner asked for a "Technical +details" button in the call window. It shows the numbers behind a call: for +the own microphone, camera and screen share, for each other participant, and +for the connection to each call server. The owner wants to see why a call is +silent, choppy or slow. + +## Context and Problem Statement + +The call worker runs the call inside its containment (ADR-0043). Only the +worker can read WebRTC's statistics, and the web view has no connection to +the call at all. ADR-0059 already reads the sound levels of each track from +`get_stats` every 100 ms for the meters. The new details need many more +numbers from more tracks. How does Persephone show them without a new way for +the worker's or the SFU's data to reach the page, and without any cost while +nobody looks? + +Facts from the source on 25 November 2026: + +* LiveKit 0.11.0 gives `get_stats` for each local and remote track, as typed + values (`RtcStats`). The report of a track includes its transport and the + selected candidate pair. `Room::get_stats` also exists, but a `Room` is + not clonable into a task. +* The statistics hold addresses, ports, candidate types, SSRCs and codec + names. The details need none of them. +* Counters (bytes, packets) only grow. A rate is the change between two + readings. A counter falls when WebRTC restarts a stream. + +## Decision Drivers + +* No work, and no new message, while the panel is closed. +* The worker sends numbers only, with bounds that the receiver checks + (ADR-0043). No free text, address or identifier beyond those that other + messages already carry. +* In each round of the worker's writer, statistics go after the control + messages and the waiting picture, and they never run in the worker's event + loop. A control message that comes while a reading is being written waits + for that one bounded write. +* The call window gets two new commands and nothing else (ADR-0060): + `call_stats`, the switch that reaches the core, and `call_stats_read`, + which only tells the host that the page handled a reading. + +## Considered Options + +* On request: the page turns the details on and off, and the worker reads + once a second only while they are on +* Always on: the worker reads every second during every call and the core + keeps the newest reading +* The page asks for each reading (a pull command) + +## Decision Outcome + +Chosen option: "On request", because it costs nothing while closed, and only +one of its two commands, the switch, reaches the core. The other, +`call_stats_read`, stays in the UI host and only paces the page. With a pull +command, each reading is a request that reaches the core and the worker, and +the worker must read for each request or keep the newest reading always. + +### Switch + +* The call window sends `call_stats { on, page }` with a channel. The core + command is `Call::CallStats { on }`. Turning the details on needs a running + or joining call (`unavailable` otherwise); turning them off always works, + also while the session is locked or busy, so a closed panel or window never + leaves them reading. +* The core turns them off when the call ends (in the same step that frees the + call slot, so a late "on" cannot reach the next call), when the UI + connection closes, and when the call window that asked reloads or closes. + The host keeps the channel only while they are on, and tells the core to + stop when it drops one. +* The core sends `ToWorker::SetStats { on }` to the worker on each change. + The worker starts with them off. A full worker queue keeps the newest value + for a retry, like the diagnostic switch (ADR-0058). +* The core sends a change only. When the page turns the details off and on + again while the call task is busy, the task can see only the newest value, + "on", and sends nothing: the worker never stopped, so its series and its + rates go on. When both changes reach the worker, it starts a new series, + whose first reading has no rates. Readings taken before the off can still + arrive after the on: the one that the worker's writer holds, and those that + wait in the core's queue of worker messages (`EVENT_QUEUE`, 64 messages of + every kind) while the call task is busy. The worker reads at most once a + second, so at most one reading waits for each second that the task is + busy. The core passes them on. The core and the UI host keep only the + newest waiting reading, but the page can still show more than one of them, + one after the other. Each is a reading of the same call, taken before the + off, and the next new reading replaces it. A series number in `SetStats` + and `Stats` would let the core drop them; this record does not add one. + +### Worker + +* `StatsProbe` (`session/stats_probe.rs`) reads while the switch is on, at + most once a second, one read at a time, on its own task with a deadline of + 900 ms. It is the same design as `SoundProbe` (ADR-0055, ADR-0059): the + event loop only starts it and takes its report. It is aborted when the + call ends. A report of an older on-off series is dropped by its number. +* A read asks for the statistics of the own microphone, camera and screen + tracks, and of one audio and one video track of each remote participant + (at most 32 participants, so at most 64 remote reads): the microphone, and + the camera before a screen share, with the smallest track ID when there + are more, so the reads follow one track while it stays. Each read keeps + its track ID and the time it finished. + libwebrtc gives each track only its own streams and the transport they + use. The own room uses LiveKit's single peer connection when the server + offers it; its own and remote tracks then read one transport, which counts + once. With a publisher and a subscriber connection, both add, each from its + own counters. The connection numbers come from the transport and the + selected candidate pair that those reports already include. A connection + with no track has no entry. When a transport that a connection uses was + not read (its read missed the deadline), the connection's send and + receive rates are unknown for that reading, never short. +* `mapping/stats.rs` is pure. `StatsBook` keeps the last sample of each + counter, with the time of the read that gave it, under the track's ID (or + the connection's transport). Each rate is the change since that sample, + over the time between the two reads, so a slow read of another track + never changes it, and a new track never compares with an old one. A + counter with no earlier value, and a zero or negative interval, give no + rate (`null`), never a wrong one. A counter that fell was restarted and + gives no rate, with one exception: a 32-bit counter that fell by more than + half its range wrapped, and counts across the wrap (`counter_delta`). A + 64-bit counter (bytes) never wraps. A restart of a 32-bit counter from + above half its range reads as a wrap; its rate is still clamped. Every + number is clamped to its bound, and an entry whose identity + or connection the protocol would refuse is left out. +* The reading goes to `Output::offer_stats`. It never waits, it replaces a + reading that has not gone out, and the writer writes it after the control + messages and the waiting picture of its round. So at most one reading + waits. A control message that comes while the reading is being written + waits for that write, which the message limits bound. + +### Message + +`FromWorker::Stats` (tag 23, protocol version 13) holds integers only: + +| Part | Content | Bound | +| --- | --- | --- | +| Own microphone | level, bitrate, packets sent, packets lost by the far end, jitter, round-trip time | level 0 to 100, bitrate 0 to 1,000,000 kbit/s, times 0 to 60,000 ms | +| Own camera and screen share | frame rate, size, bitrate, quality limit (none, processor, bandwidth, other), packets lost by the far end | 0 to 120 fps, sides 0 to 16,384 | +| Each remote participant | audio: level, bitrate, packets received and lost, jitter, concealed share. Video: frame rate, size, bitrate, frames dropped each second, packets lost | at most 32; each (connection, identity) once; concealed 0 to 100 | +| Each connection | estimated upload bandwidth, total send rate, total receive rate, round-trip time | at most 4; numbers 0 to 3, each once | + +A value that is not known yet (a rate before the second reading, a +round-trip time before the first report) is absent, not zero. The message is +about 18 KiB at most and the protocol limit is 64 KiB. The reader checks every +count before it allocates, refuses a repeated participant or connection, and +the writer leaves out entries past the limits. There is no address, port, +candidate type, SSRC, codec or other text. + +### Core and host + +* While the details are on, the core names each remote entry by the member + that the worker identity stands for (`View::level_member`: a current member + whose connection speaks for it), leaves out any other, and checks the + result against `CallStats::within_limits`. While they are off, a reading + is dropped. +* The core keeps only the newest reading and sends it as `Event::CallStats`. + The UI host reads the event with the same limits and sends it only to the + channel of a window that turned the details on. The UI host sends each + page one reading at a time: the next waits until the page says, with + `call_stats_read`, that it handled the last one, and only the newest waits. +* The UI host keeps a window's channel only after the core accepted the + start. Its own stop on a reload or close is a request too, so the host + lets one change of the core's switch run at a time, and each ends with the + switch as the kept channels want. A start that a reload or close overtook + keeps no channel and turns the switch off again; a late stop does not + undo the start of the page that came next. Tauri reads a command's + arguments only in its task, which may start after the reload or close, so + the host cannot tell from the time which page sent it. So each window + counts its pages: the page load and `watch_session` (a page's first + request) each count a new page, and `watch_session` gives the page its + count. The page sends the count with each `call_stats`, and the host takes + a start or stop only with the count of the page the window shows now. A + request of a page that is gone fails and changes nothing. +* The capability `call` gains `allow-call-stats` (the switch, which reaches + the core) and `allow-call-stats-read` (the page's acknowledgment, which + stays in the host and reaches no core), and nothing else. The main + window has neither. + +### Page + +* A button "Technical details" (an icon button) in the call window controls + opens a panel. The panel turns the details on when it opens and off when + it closes, so closing, a closed window and an ended call all stop them. + The window closes the panel when the call ends and when a call in another + room replaces it (`statsStayOpen`), so the panel never shows a reading of + an earlier call. The call status has no call ID, so a new call in the + same room is told apart only by the end status between the two. + Escape closes it. The bridge keeps the page's count from `watch_session` + and sends it with each start and stop; with none, a start fails and a stop + asks nothing. It sends the starts and stops one at a time, in the order + asked: the host keeps one channel per window, so the late stop of + a closed panel must never reach it after the start of the panel opened + next. The button is a disclosure (`aria-expanded`, `aria-controls`), like + the device button. +* The panel shows a table per source with units: kbit/s, fps, ms, %, + packets. Participants show as in the call window. All text is inert. The + page checks each reading against the contract again and drops a bad one. + +### Positive Consequences + +* No cost while the panel is closed: no read, no message, no timer work. +* The numbers cannot carry anything but numbers, and the page never sees an + address. +* A reading goes after the control messages and the waiting picture of each + writer round, so it delays a control message by at most one bounded write. + +### Negative Consequences + +* The reading takes up to a second to appear, and rates show as unknown + until the second reading. +* Each read starts from LiveKit's copy of each room's participant map + (`Room::remote_participants`, one identity and two shared handles per + participant), and the limit of 32 applies after that copy. The level + meters take the same copy ten times a second. A bounded participant index + kept from room events would bound both; it is not part of this record. +* An entry whose track has no statistics (a slow or failed read) is missing + for that second. +* A connection that has no track shows no numbers, because the worker reads + transports through tracks. +* The numbers are WebRTC's own and were not compared with another tool. They + were tested with synthetic readings only; no live call was measured for + this record. + +## Pros and Cons of the Options + +### On request + +* Good, because it costs nothing while closed. +* Good, because it adds one event and two commands, and only one of the + commands (the switch) reaches the core. +* Bad, because the first reading takes a second. + +### Always on + +* Good, because the first view is immediate. +* Bad, because every call pays for reads that nobody looks at, on up to + 70 tracks a second. + +### Pull command + +* Good, because the page paces itself. +* Bad, because each reading is a request that reaches the core and the + worker, and the worker has to read for each request or keep the newest + reading always. + +## Links + +* Refines [ADR-0060](0060-show-calls-in-a-separate-call-window.md): the call + window's capability gains `call_stats`. +* Follows the probe design of [ADR-0055](0055-add-deafen-and-a-call-volume-to-calls.md) + and [ADR-0059](0059-test-call-devices-show-each-participants-level-and-switch-devices-during-a-call.md). +* Follows the switch design of [ADR-0058](0058-write-a-diagnostic-log-only-when-the-user-turns-it-on.md). diff --git a/docs/adr/index.md b/docs/adr/index.md index b6482041..53a74016 100644 --- a/docs/adr/index.md +++ b/docs/adr/index.md @@ -71,6 +71,8 @@ * [0062 - Set the microphone gain and the automatic level in calls](0062-set-the-microphone-gain-and-automatic-level-in-calls.md) * [0063 - Explain a refused call join, let moderators allow it, and leave a call after 30 seconds alone](0063-explain-a-refused-call-join-and-leave-a-call-after-30-seconds-alone.md) * [0064 - Share the screen in calls on macOS](0064-share-the-screen-in-calls-on-macos.md) +* [0065 - Choose the large video and change devices in the call window](0065-choose-the-large-video-and-change-devices-in-the-call-window.md) +* [0066 - Show call statistics on request](0066-show-call-statistics-on-request.md) ## Superseded Records diff --git a/frontend/AGENTS.md b/frontend/AGENTS.md index c7a938eb..720af3dc 100644 --- a/frontend/AGENTS.md +++ b/frontend/AGENTS.md @@ -3,7 +3,8 @@ This area inherits `../AGENTS.md`. - Build a locally bundled Svelte UI. Keep `vite.config.js` output in `../.local/build/frontend`, relative asset URLs, no inline assets, and no production source maps unless a reviewed requirement changes them. -- There are two pages: `index.html` (`src/main.ts`, the main window) and `call.html` (`src/call.ts`, the call window of ADR-0060). The call window may call only the commands in `src-tauri/capabilities/call.json`; do not use other bridge calls in `CallWindow.svelte`. +- There are two pages: `index.html` (`src/main.ts`, the main window) and `call.html` (`src/call.ts`, the call window of ADR-0060). The call window may call only the commands in `src-tauri/capabilities/call.json`; do not use other bridge calls in `CallWindow.svelte`. That includes `call_devices` and `set_call_devices` (ADR-0065) for `CallWindowDevices.svelte`, but no device tests. Its load and save order (saves one at a time, none dropped, the newest sets the result) is in `src/callDevicePanel.ts`, which takes the bridge calls as arguments. The choice of the large video is pure logic in `src/callView.ts`: a pick of the viewer wins, a shared screen is large only when nothing is picked, and a feed that goes away drops its pick. Scale pictures with CSS only; never ask the core for a larger one. +- The technical details (ADR-0066) are `CallStats.svelte` (the panel, opened by one icon button in `CallWindow.svelte`) and the pure `src/callStats.ts` (contract check, units, table rows). The panel turns the readings on when it mounts and off when it is destroyed, through `startCallStats` and `stopCallStats` in the bridge, which send them one at a time in the order asked. After each reading, handled or dropped, the bridge calls `call_stats_read` with the page count, so the host sends the next (it holds one in flight per page). The bridge drops a reading that `parseCallStats` refuses. Show every number with its unit from the reading only, and show user IDs and device IDs as escaped text. A table's caption is `CallStatsCaption.svelte`, which puts the user ID and the device ID each in its own ``. The details and the device panel are open one at a time (`openDevices`, `openStats`). The call window closes the details when the call ends or a call in another room replaces it (`statsStayOpen` in `callWindow.ts`); keep that rule, because the panel starts its readings only when it mounts. - Put all Tauri API access in `src/bridge/index.ts` or another module under `src/bridge/`. Components use the typed bridge. Do not call `invoke`, Tauri globals, or host APIs directly from components. - Import public DTOs from `../crates/contracts/generated/contracts.ts`. Change Rust definitions and run the exporter when the DTO contract changes. TypeScript types do not validate runtime input or authorize commands. - Render names and message bodies as escaped text. Preserve bidirectional isolation in `src/Message.svelte`, `src/RoomList.svelte`, and `src/Timeline.svelte`. Do not use `{@html}`, HTML insertion APIs, automatic previews, or arbitrary remote images. diff --git a/frontend/src/CallDevices.svelte b/frontend/src/CallDevices.svelte index 69ef0911..094a1bb5 100644 --- a/frontend/src/CallDevices.svelte +++ b/frontend/src/CallDevices.svelte @@ -16,6 +16,7 @@ } from './bridge'; import CallVideo from './CallVideo.svelte'; import { + DEVICE_FAILURE_TEXT, DEVICE_TEST_LABEL, DEVICE_TEST_STOP_LABEL, deviceTestActive, @@ -118,12 +119,7 @@ let failure = $state(null); let generation = 0; - const failures: Record = { - locked: 'The profile is locked.', - limit_exceeded: 'Persephone is busy. Try again in a moment.', - core_unavailable: 'The call devices could not be listed.', - invalid_argument: 'That device cannot be saved.' - }; + const failures = DEVICE_FAILURE_TEXT; async function load() { if (busy) return; diff --git a/frontend/src/CallStats.svelte b/frontend/src/CallStats.svelte new file mode 100644 index 00000000..6c23fd84 --- /dev/null +++ b/frontend/src/CallStats.svelte @@ -0,0 +1,65 @@ + + + { + if (event.key === 'Escape') onclose(); + }} +/> + + diff --git a/frontend/src/CallStatsCaption.svelte b/frontend/src/CallStatsCaption.svelte new file mode 100644 index 00000000..9e037ef0 --- /dev/null +++ b/frontend/src/CallStatsCaption.svelte @@ -0,0 +1,14 @@ + + +{#if section.userId !== null}{#if section.deviceId !== null} + ({'device '}{section.deviceId}){/if}{:else}{section.title}{/if} diff --git a/frontend/src/CallWindow.svelte b/frontend/src/CallWindow.svelte index b06b68a6..fef3ea87 100644 --- a/frontend/src/CallWindow.svelte +++ b/frontend/src/CallWindow.svelte @@ -7,8 +7,8 @@ - selfClose.shown()} /> +{#snippet feed(cell: CallCell, isLarge: boolean)} + {@const shape = cell.tile === null ? undefined : shapes[cell.tile]} + {@const layout = shape && cell.tile !== null ? tileLayout(shape.width, shape.height, shape.rotation, cell.own) : null} +
+ +
+{/snippet} + + selfClose.shown()} onkeydown={onKeydown} />
@@ -232,41 +375,30 @@ {rosterOpen ? `Hide ${ROSTER_LABEL.toLowerCase()}` : `Show ${ROSTER_LABEL.toLowerCase()}`} + {#if joined && view.large} + + {/if}
{#if joined} -
- {#each grid as cell (cell.key)} - {@const shape = cell.tile === null ? undefined : shapes[cell.tile]} - {@const layout = shape && cell.tile !== null ? tileLayout(shape.width, shape.height, shape.rotation, cell.own) : null} -
-
- {#if cell.tile !== null} - - {/if} - {#if layout === null} - - {/if} -
-
- {#if cell.own} - {OWN_TILE_LABEL} - {:else if cell.userId !== null} - - {/if} - {#if cell.screen}{SCREEN_TILE_LABEL}{/if} - {#if cell.muted}{/if} -
-
- {/each} +
+ {#if view.large} +
{@render feed(view.large, true)}
+
+ {#each view.rest as cell (cell.key)} + {@render feed(cell, false)} + {/each} +
+ {:else} +
+ {#each view.rest as cell (cell.key)} + {@render feed(cell, false)} + {/each} +
+ {/if}
{:else}
@@ -324,6 +456,9 @@
{#if joined} + {#if devicesOpen} + + {/if}
+
{#if CAMERA_TEXT[status.camera] !== ''} @@ -363,11 +522,19 @@ {#if screenNote(status.screen, platform) !== ''}

{screenNote(status.screen, platform)}

{/if} - {#if status.deviceChange} + {#if status.deviceChange && !devicesOpen}

{DEVICE_CHANGE_TEXT[status.deviceChange]}

{/if} {/if} {#if failure} {/if} + {#if joined && statsOpen} + { + statsOpen = false; + void tick().then(() => statsButton?.focus()); + }} + /> + {/if}
diff --git a/frontend/src/CallWindowDevices.svelte b/frontend/src/CallWindowDevices.svelte new file mode 100644 index 00000000..3caede21 --- /dev/null +++ b/frontend/src/CallWindowDevices.svelte @@ -0,0 +1,82 @@ + + +
+

{DEVICES_PANEL_LABEL}

+ {#if devices && !devices.supported} +

{devicesNote(devices)}

+ {:else} + + + + + + + + {/if} + {#if result !== ''} +

{result}

+ {/if} + {#if view.failure} + + {/if} +
diff --git a/frontend/src/Icon.svelte b/frontend/src/Icon.svelte index 82d5616b..cf8e2e98 100644 --- a/frontend/src/Icon.svelte +++ b/frontend/src/Icon.svelte @@ -36,7 +36,8 @@ | 'volume' | 'video' | 'video-off' - | 'screen'; + | 'screen' + | 'activity';