Skip to main content

sew_call_client/
stats.rs

1//! The call-stats beacon: one aggregate, anonymous [`CallStatsSample`] per window to Sew's
2//! `POST /api/v1/me/voice/stats` with the call credential, and the same per-window numbers for
3//! the host ([`crate::Call::stats`], [`crate::CallEvent::Stats`]).
4//!
5//! **When.** The join answer's `stats` terms (`calls.stats_beacon` on) set the window
6//! (`interval_ms`, 15 s from Sew). The first window starts when the call first reaches
7//! `connected`; a sample goes out at the end of every window and once more when the host
8//! leaves (the partial window, before Sew's leave, so the caller is still in voice). A join
9//! with no terms sends nothing, but the windows are still measured (at 15 s) for the host. A
10//! re-join takes the new answer's terms. Sew's `403 call_stats_off` (the policy turned off)
11//! stops the beacon for the rest of the call; any other refusal is recorded on that window
12//! and the next window is sent as usual.
13//!
14//! **What.** `client` is `native` and the six `audio_*` fields are sent **only** when the terms
15//! say `audio_fields: true` (an older Sew refuses both: `deny_unknown_fields`); otherwise the
16//! sample is the browsers' shape with `client: other`. The video fields (`frames_decoded`,
17//! `frames_dropped`, `freezes`, `freeze_ms`) are 0: the engine carries audio only. Every value
18//! is clamped to Sew's caps (`sew_proto::voice::CALL_STATS_*`) and the sample is validated
19//! before it is sent.
20//!
21//! How each value is derived (a "stream" is one remote audio track; packets are counted on
22//! RTP arrival in the engine, before decryption, for tracks the keys allow):
23//!
24//! | Field | From |
25//! |---|---|
26//! | `interval_ms` | the window's wall length (the leave sample: the partial window, at least 1 ms) |
27//! | `decrypt_failures` | remote frames that failed to decrypt in the window ([`crate::CallCounters::decrypt_failures`]): not the frames whose key was not installed yet, around a join or a key switch ([`crate::CallCounters::frames_before_key`], in the host's window only) |
28//! | `candidate`, `relay_protocol` | the local candidate of str0m's selected pair (its latest `PeerStats`, once a second), matched to the transport's candidates: a TURN relay is `relay` with its `udp`/`tcp`/`tls`, else `host` |
29//! | `rtt_ms` | the selected pair's latest ICE (STUN consent) round-trip time from the same `PeerStats` |
30//! | `audio_played_ms` | 20 ms × the frames the audio pipeline played in the window, summed over streams: kessel-audio's `frames_decoded + frames_fec + frames_concealed` (DTX silence not counted, as kessel-audio's `concealed_pct`), read once a second and differenced; a host with its own pipeline reports them through [`crate::Call::set_playout_stats`]; with neither, the engine's view: 20 ms × (frames handed to the pipeline + loss marks) |
31//! | `audio_concealed_ms` | 20 ms × kessel-audio's `frames_concealed` in the window (loss concealment; FEC recovery is not concealment); the engine's fallback: 20 ms × loss marks |
32//! | `audio_packets_expected` | per stream, the highest RTP sequence number at the window's end minus the highest at its start (a new stream: from its first packet), summed |
33//! | `audio_packets_lost` | expected minus the unique packets that arrived in the window (a late packet still counts as received), at least 0 |
34//! | `audio_jitter_ms` | the worst stream's RFC 3550 interarrival jitter (arrival time against the 48 kHz RTP timestamp, smoothed 1/16), the highest value it reached in the window |
35//! | `audio_longest_gap_ms` | the longest stretch with no audio arriving on one stream, counted when the stream's next packet arrives: the arrival interval beyond what the RTP timestamps advanced (a network stall) plus 20 ms per packet missing in between (loss), at most the arrival interval; sender silence (DTX, or a pause the timestamps cover) is not a gap. A gap is counted in the window where audio resumes, clipped to that window |
36//!
37//! **Before the first window.** Frames counted before the call first reached `connected` (the
38//! keys still settling: refused before the subscription, or crossing the join's key switch) are
39//! in no window; [`CallStatsReport::before_first_window`] holds them, so a counter of
40//! [`crate::CallCounters`] is that bucket plus the sum of the windows (while every window is
41//! kept).
42//!
43//! Known limits: `audio_longest_gap_ms` is an inter-packet measure on one stream. A stream
44//! that stops and never resumes adds no gap (and no loss) for that stretch, and a reconnect
45//! that replaces a track (a full reconnect, a re-join or a move: new PC, new streams) starts a
46//! new stream, so the silence of the reconnect itself is never a gap: a call with reconnects
47//! of 1 to 3 s of silence can read gaps of a few ms. Silence at the speaker across reconnects
48//! is the host's to measure (the playout side). A track removed mid-window keeps the counts up
49//! to its removal; a host that never plays audio (no pipeline attached) gets the engine's
50//! fallback for played and concealed.
51
52use std::collections::{HashMap, VecDeque};
53use std::time::{Duration, Instant};
54
55use serde::Serialize;
56use sew_proto::error::Validate as _;
57use sew_proto::voice::{
58    CALL_STATS_AUDIO_JITTER_MAX_MS, CALL_STATS_AUDIO_PACKETS_MAX, CALL_STATS_AUDIO_STREAMS_MAX,
59    CALL_STATS_EVENTS_MAX, CALL_STATS_INTERVAL_MS, CALL_STATS_RTT_MAX_MS, CALL_STATS_WINDOW_MAX_MS,
60    CallStatsBeacon, CallStatsCandidate, CallStatsClient, CallStatsRelayProtocol, CallStatsSample,
61};
62
63use crate::call::CallCounters;
64
65/// One Opus frame's duration (the engine and kessel-audio send and play 20 ms frames).
66pub(crate) const FRAME_MS: u64 = 20;
67/// Windows [`CallStatsReport::windows`] keeps (the latest).
68pub(crate) const WINDOWS_KEPT: usize = 256;
69/// How often the playout counters and the selected pair are read.
70const POLL_EVERY: Duration = Duration::from_secs(1);
71/// Missing sequence numbers remembered per stream (a later arrival still counts as received).
72const MISSING_KEPT: usize = 128;
73/// Gaps in the sequence longer than this are not remembered packet by packet.
74const MISSING_MAX_RUN: u64 = 64;
75
76/// Cumulative playout counters of one remote track since the pipeline added it, in 20 ms
77/// frames (kessel-audio's `ParticipantStats` fields of the same names).
78#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
79#[non_exhaustive]
80pub struct PlayoutTotals {
81    /// Frames decoded from packets.
82    pub decoded: u64,
83    /// Frames rebuilt from the next packet's in-band FEC.
84    pub fec: u64,
85    /// Frames synthesised by loss concealment.
86    pub concealed: u64,
87}
88
89impl PlayoutTotals {
90    /// Counters from a host's own pipeline.
91    pub fn new(decoded: u64, fec: u64, concealed: u64) -> PlayoutTotals {
92        PlayoutTotals {
93            decoded,
94            fec,
95            concealed,
96        }
97    }
98
99    fn played(self) -> u64 {
100        self.decoded + self.fec + self.concealed
101    }
102}
103
104/// The audio pipeline's playout counters, which the beacon's `audio_played_ms` and
105/// `audio_concealed_ms` come from. [`crate::AudioBridge`] reports kessel-audio's; a host with
106/// its own pipeline passes one to [`crate::Call::set_playout_stats`].
107pub trait PlayoutStats: Send + Sync + 'static {
108    /// Every remote track the pipeline plays, by the id of [`crate::RecvItem::Added`], with its
109    /// cumulative counters (read about once a second; cheap).
110    fn playout_totals(&self) -> Vec<(u64, PlayoutTotals)>;
111}
112
113/// Where a window's played and concealed audio came from.
114#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
115#[serde(rename_all = "snake_case")]
116#[non_exhaustive]
117pub enum PlayoutSource {
118    /// The audio pipeline's own counters (kessel-audio through [`crate::AudioBridge`], or the
119    /// host's [`PlayoutStats`]).
120    Pipeline,
121    /// No pipeline reported: the engine's frames and loss marks.
122    Engine,
123}
124
125/// What became of a window's sample.
126#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
127#[serde(tag = "status", rename_all = "snake_case")]
128#[non_exhaustive]
129pub enum BeaconOutcome {
130    /// The join answer carried no stats terms (`calls.stats_beacon` off at the join): nothing
131    /// was sent.
132    Off,
133    /// Sew refused an earlier sample with `call_stats_off`: the beacon stopped.
134    Stopped,
135    /// The join has no call credential to send it with.
136    NoCredential,
137    /// Sew took it.
138    Accepted {
139        /// The HTTP status (200).
140        http_status: u16,
141    },
142    /// Sew (or the door in front of it) refused it.
143    Refused {
144        /// The HTTP status.
145        http_status: u16,
146        /// `error.code` of the answer, when it had one.
147        code: Option<String>,
148        /// `error.details.reason`, when it had one.
149        reason: Option<String>,
150    },
151    /// It could not be sent (the network, a timeout, or a sample that failed its own checks).
152    Failed {
153        /// Why.
154        error: String,
155    },
156}
157
158/// One stats window: the numbers measured, the sample sent (if any) and Sew's answer.
159#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
160#[non_exhaustive]
161pub struct StatsWindow {
162    /// The window's number in this call, from 1.
163    pub index: u32,
164    /// Its length, ms.
165    pub interval_ms: u32,
166    /// The leave sample (the partial last window).
167    pub last: bool,
168    /// Audio played, ms, summed over streams.
169    pub audio_played_ms: u32,
170    /// Of that, concealed, ms.
171    pub audio_concealed_ms: u32,
172    /// Audio packets expected, summed over streams.
173    pub audio_packets_expected: u32,
174    /// Audio packets that arrived (unique).
175    pub audio_packets_received: u32,
176    /// Of the expected, lost.
177    pub audio_packets_lost: u32,
178    /// The worst stream's jitter, ms.
179    pub audio_jitter_ms: u32,
180    /// The longest gap between two packets of one stream, ms (counted when the next packet
181    /// arrives; a reconnect starts new streams, so its silence is not counted: see the module
182    /// docs).
183    pub audio_longest_gap_ms: u32,
184    /// Where played and concealed came from.
185    pub playout_source: PlayoutSource,
186    /// Remote frames that failed to decrypt.
187    pub decrypt_failures: u32,
188    /// Remote frames dropped because the sender's key was not installed yet (a join or a key
189    /// switch; the host's view only, not sent to Sew).
190    pub frames_before_key: u64,
191    /// Remote frames of tracks the keys did not allow (the host's view only).
192    pub refused_frames: u64,
193    /// Frames encrypted and sent in the window.
194    pub frames_sent: u64,
195    /// Remote frames decrypted in the window.
196    pub frames_received: u64,
197    /// The selected pair's local candidate type (`host`, `relay`), when known.
198    pub candidate: Option<String>,
199    /// For `relay`: `udp`, `tcp` or `tls`.
200    pub relay_protocol: Option<String>,
201    /// The selected pair's round-trip time, ms, when known.
202    pub rtt_ms: Option<u32>,
203    /// The microphone's noise removal at the window's end: `{mode, active, reason}` (the
204    /// host's view only, not sent to Sew; `None` when the call's audio reports none:
205    /// [`crate::AudioBridge::start_with_noise`]).
206    pub noise_removal: Option<crate::NoiseRemovalState>,
207    /// The body sent to Sew (absent when nothing was sent).
208    pub sample: Option<CallStatsSample>,
209    /// What became of it.
210    pub beacon: BeaconOutcome,
211}
212
213/// What the counters held when the first window started (the call first `connected`): the
214/// frames no window covers.
215#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
216#[non_exhaustive]
217pub struct BeforeFirstWindow {
218    /// Remote frames that failed to decrypt.
219    pub decrypt_failures: u64,
220    /// Remote frames dropped because the sender's key was not installed yet.
221    pub frames_before_key: u64,
222    /// Remote frames of tracks the keys did not allow yet.
223    pub refused_frames: u64,
224    /// Remote frames decrypted.
225    pub frames_received: u64,
226    /// Frames encrypted and sent.
227    pub frames_sent: u64,
228}
229
230impl BeforeFirstWindow {
231    fn of(c: &CallCounters) -> BeforeFirstWindow {
232        BeforeFirstWindow {
233            decrypt_failures: c.decrypt_failures,
234            frames_before_key: c.frames_before_key,
235            refused_frames: c.refused_frames,
236            frames_received: c.frames_received,
237            frames_sent: c.frames_sent,
238        }
239    }
240}
241
242/// The call's stats so far ([`crate::Call::stats`]).
243#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
244#[non_exhaustive]
245pub struct CallStatsReport {
246    /// The beacon's terms of the current join (`None`: the beacon is off).
247    pub terms: Option<CallStatsBeacon>,
248    /// The counts from before the first window (`None` until the call first connected).
249    pub before_first_window: Option<BeforeFirstWindow>,
250    /// The latest windows (at most 256), oldest first.
251    pub windows: Vec<StatsWindow>,
252    /// Samples sent.
253    pub samples_sent: u64,
254    /// Samples Sew accepted.
255    pub samples_accepted: u64,
256}
257
258impl CallStatsReport {
259    pub(crate) fn push(&mut self, w: StatsWindow) {
260        if w.sample.is_some() {
261            self.samples_sent += 1;
262        }
263        if matches!(w.beacon, BeaconOutcome::Accepted { .. }) {
264            self.samples_accepted += 1;
265        }
266        if self.windows.len() >= WINDOWS_KEPT {
267            self.windows.remove(0);
268        }
269        self.windows.push(w);
270    }
271}
272
273/// The selected pair's path, as the beacon names it.
274pub(crate) type Path = (CallStatsCandidate, Option<CallStatsRelayProtocol>);
275
276#[derive(Debug, Default)]
277struct Stream {
278    highest: Option<u64>,
279    /// The first sequence number this window expects (a new stream: its first packet's; then
280    /// one past the highest before the window): expected = highest + 1 − this.
281    first_expected: u64,
282    /// Unique packets that arrived in this window.
283    received: u64,
284    last_arrival: Option<Instant>,
285    last_ts: u32,
286    jitter_s: f64,
287    missing: VecDeque<u64>,
288}
289
290/// The engine's per-window accounting (owned by the engine task).
291#[derive(Debug)]
292pub(crate) struct Meter {
293    interval: Duration,
294    /// The current window's start (`None` until the call first connected).
295    started: Option<Instant>,
296    index: u32,
297    streams: HashMap<u64, Stream>,
298    /// Expected and received of the streams removed during this window.
299    expected_gone: u64,
300    received_gone: u64,
301    jitter_peak_s: f64,
302    gap_ms: u64,
303    played_frames: u64,
304    concealed_frames: u64,
305    pipeline_seen: bool,
306    playout_prev: HashMap<u64, PlayoutTotals>,
307    next_poll: Instant,
308    counters_at_start: CallCounters,
309    rtt: Option<Duration>,
310    path: Option<Path>,
311}
312
313fn sat_u32(v: u64) -> u32 {
314    u32::try_from(v).unwrap_or(u32::MAX)
315}
316
317impl Meter {
318    pub(crate) fn new(now: Instant, terms: Option<&CallStatsBeacon>) -> Meter {
319        Meter {
320            interval: interval_of(terms),
321            started: None,
322            index: 0,
323            streams: HashMap::new(),
324            expected_gone: 0,
325            received_gone: 0,
326            jitter_peak_s: 0.0,
327            gap_ms: 0,
328            played_frames: 0,
329            concealed_frames: 0,
330            pipeline_seen: false,
331            playout_prev: HashMap::new(),
332            next_poll: now,
333            counters_at_start: CallCounters::default(),
334            rtt: None,
335            path: None,
336        }
337    }
338
339    /// New terms (a re-join's answer): the next windows take its interval.
340    pub(crate) fn set_terms(&mut self, terms: Option<&CallStatsBeacon>) {
341        self.interval = interval_of(terms);
342    }
343
344    /// The call is connected: the first window starts (once). Returns what the counters held
345    /// before it (`None` when the window had already started).
346    pub(crate) fn start(
347        &mut self,
348        now: Instant,
349        counters: &CallCounters,
350    ) -> Option<BeforeFirstWindow> {
351        if self.started.is_some() {
352            return None;
353        }
354        self.started = Some(now);
355        self.next_poll = now;
356        self.reset_window(counters);
357        Some(BeforeFirstWindow::of(counters))
358    }
359
360    pub(crate) fn started(&self) -> bool {
361        self.started.is_some()
362    }
363
364    /// When the engine must wake for the meter.
365    pub(crate) fn deadline(&self) -> Option<Instant> {
366        let s = self.started?;
367        Some((s + self.interval).min(self.next_poll))
368    }
369
370    /// The current window is over.
371    pub(crate) fn due(&self, now: Instant) -> bool {
372        self.started.is_some_and(|s| now >= s + self.interval)
373    }
374
375    /// One RTP packet of remote track `slot` (extended sequence number, 48 kHz timestamp).
376    pub(crate) fn on_packet(&mut self, slot: u64, seq: u64, ts: u32, now: Instant) {
377        let window_start = self.started;
378        let st = self.streams.entry(slot).or_default();
379        let Some(h) = st.highest else {
380            st.highest = Some(seq);
381            st.first_expected = seq;
382            st.received = 1;
383            st.last_arrival = Some(now);
384            st.last_ts = ts;
385            return;
386        };
387        if seq <= h {
388            // Reordered (or a duplicate): counts only when it was missing.
389            if let Some(i) = st.missing.iter().position(|m| *m == seq) {
390                st.missing.remove(i);
391                st.received += 1;
392            }
393            return;
394        }
395        let delta = seq - h;
396        if delta <= MISSING_MAX_RUN {
397            for m in (h + 1)..seq {
398                if st.missing.len() >= MISSING_KEPT {
399                    st.missing.pop_front();
400                }
401                st.missing.push_back(m);
402            }
403        }
404        st.received += 1;
405        if let Some(prev) = st.last_arrival {
406            let interval_s = now.saturating_duration_since(prev).as_secs_f64();
407            // The media time the timestamps say passed (wrapping, as RTP timestamps do).
408            let ts_adv_s = f64::from(ts.wrapping_sub(st.last_ts) as i32) / 48_000.0;
409            // RFC 3550 §6.4.1: D = (Rj − Ri) − (Sj − Si); J += (|D| − J) / 16.
410            let d = interval_s - ts_adv_s;
411            st.jitter_s += (d.abs() - st.jitter_s) / 16.0;
412            if st.jitter_s > self.jitter_peak_s {
413                self.jitter_peak_s = st.jitter_s;
414            }
415            let interval_ms = (interval_s * 1_000.0).round() as u64;
416            let stall_ms = ((interval_s - ts_adv_s.max(0.0)).max(0.0) * 1_000.0).round() as u64;
417            let missing_ms = (delta - 1).saturating_mul(FRAME_MS);
418            let mut gap = stall_ms.saturating_add(missing_ms).min(interval_ms);
419            if let Some(ws) = window_start {
420                let in_window = now.saturating_duration_since(ws).as_millis();
421                gap = gap.min(u64::try_from(in_window).unwrap_or(u64::MAX));
422            }
423            if gap > self.gap_ms {
424                self.gap_ms = gap;
425            }
426        }
427        st.highest = Some(seq);
428        st.last_arrival = Some(now);
429        st.last_ts = ts;
430    }
431
432    /// Remote track `slot` ended: its counts so far stay in this window.
433    pub(crate) fn on_removed(&mut self, slot: u64) {
434        if let Some(st) = self.streams.remove(&slot) {
435            self.expected_gone += st
436                .highest
437                .map_or(0, |h| (h + 1).saturating_sub(st.first_expected));
438            self.received_gone += st.received;
439        }
440    }
441
442    /// str0m's `PeerStats`: the selected pair's path and round-trip time.
443    pub(crate) fn on_peer(&mut self, path: Option<Path>, rtt: Option<Duration>) {
444        if path.is_some() {
445            self.path = path;
446        }
447        if rtt.is_some() {
448            self.rtt = rtt;
449        }
450    }
451
452    /// Reads the playout counters when a second has passed (or `force`).
453    pub(crate) fn poll(&mut self, now: Instant, source: Option<&dyn PlayoutStats>, force: bool) {
454        if self.started.is_none() || (!force && now < self.next_poll) {
455            return;
456        }
457        self.next_poll = now + POLL_EVERY;
458        let Some(src) = source else { return };
459        self.pipeline_seen = true;
460        let now_totals: HashMap<u64, PlayoutTotals> = src.playout_totals().into_iter().collect();
461        for (id, t) in &now_totals {
462            let prev = self.playout_prev.get(id).copied().unwrap_or_default();
463            self.played_frames += t.played().saturating_sub(prev.played());
464            self.concealed_frames += t.concealed.saturating_sub(prev.concealed);
465        }
466        self.playout_prev = now_totals;
467    }
468
469    /// Ends the current window at `now` and starts the next one.
470    pub(crate) fn close(
471        &mut self,
472        now: Instant,
473        counters: &CallCounters,
474        source: Option<&dyn PlayoutStats>,
475        last: bool,
476    ) -> StatsWindow {
477        self.poll(now, source, true);
478        let start = self.started.unwrap_or(now);
479        let interval_ms = u64::try_from(now.saturating_duration_since(start).as_millis())
480            .unwrap_or(u64::MAX)
481            .clamp(1, u64::from(CALL_STATS_WINDOW_MAX_MS));
482        let mut expected = self.expected_gone;
483        let mut received = self.received_gone;
484        for st in self.streams.values() {
485            expected += st
486                .highest
487                .map_or(0, |h| (h + 1).saturating_sub(st.first_expected));
488            received += st.received;
489        }
490        let c0 = &self.counters_at_start;
491        let lost_marks = counters.lost_marks.saturating_sub(c0.lost_marks);
492        let (played_frames, concealed_frames, playout_source) = if self.pipeline_seen {
493            (
494                self.played_frames,
495                self.concealed_frames,
496                PlayoutSource::Pipeline,
497            )
498        } else {
499            let handed = counters.frames_received.saturating_sub(c0.frames_received);
500            (handed + lost_marks, lost_marks, PlayoutSource::Engine)
501        };
502        let played_max = interval_ms * u64::from(CALL_STATS_AUDIO_STREAMS_MAX);
503        let played = (played_frames * FRAME_MS).min(played_max);
504        let concealed = (concealed_frames * FRAME_MS).min(played);
505        let packets_max = u64::from(CALL_STATS_AUDIO_PACKETS_MAX);
506        let expected_c = expected.min(packets_max);
507        let lost = expected.saturating_sub(received).min(expected_c);
508        let jitter_ms = ((self.jitter_peak_s * 1_000.0).round() as u64)
509            .min(u64::from(CALL_STATS_AUDIO_JITTER_MAX_MS));
510        let (candidate, relay_protocol) = match self.path {
511            Some((c, p)) => (
512                Some(c.as_str().to_owned()),
513                p.map(|p| p.as_str().to_owned()),
514            ),
515            None => (None, None),
516        };
517        let w = StatsWindow {
518            index: self.index + 1,
519            interval_ms: sat_u32(interval_ms),
520            last,
521            audio_played_ms: sat_u32(played),
522            audio_concealed_ms: sat_u32(concealed),
523            audio_packets_expected: sat_u32(expected_c),
524            audio_packets_received: sat_u32(received.min(packets_max)),
525            audio_packets_lost: sat_u32(lost),
526            audio_jitter_ms: sat_u32(jitter_ms),
527            audio_longest_gap_ms: sat_u32(self.gap_ms.min(interval_ms)),
528            playout_source,
529            decrypt_failures: sat_u32(
530                counters
531                    .decrypt_failures
532                    .saturating_sub(c0.decrypt_failures)
533                    .min(u64::from(CALL_STATS_EVENTS_MAX)),
534            ),
535            frames_before_key: counters
536                .frames_before_key
537                .saturating_sub(c0.frames_before_key),
538            refused_frames: counters.refused_frames.saturating_sub(c0.refused_frames),
539            frames_sent: counters.frames_sent.saturating_sub(c0.frames_sent),
540            frames_received: counters.frames_received.saturating_sub(c0.frames_received),
541            candidate,
542            relay_protocol,
543            rtt_ms: self.rtt.map(|r| {
544                sat_u32(
545                    u64::try_from(r.as_millis())
546                        .unwrap_or(u64::MAX)
547                        .min(u64::from(CALL_STATS_RTT_MAX_MS)),
548                )
549            }),
550            noise_removal: None,
551            sample: None,
552            beacon: BeaconOutcome::Off,
553        };
554        self.index += 1;
555        self.started = Some(now);
556        self.reset_window(counters);
557        w
558    }
559
560    fn reset_window(&mut self, counters: &CallCounters) {
561        for st in self.streams.values_mut() {
562            if let Some(h) = st.highest {
563                st.first_expected = h + 1;
564            }
565            st.received = 0;
566        }
567        self.expected_gone = 0;
568        self.received_gone = 0;
569        self.jitter_peak_s = 0.0;
570        self.gap_ms = 0;
571        self.played_frames = 0;
572        self.concealed_frames = 0;
573        self.pipeline_seen = false;
574        self.counters_at_start = counters.clone();
575    }
576}
577
578fn interval_of(terms: Option<&CallStatsBeacon>) -> Duration {
579    let ms = terms.map_or(CALL_STATS_INTERVAL_MS, |t| t.interval_ms);
580    Duration::from_millis(u64::from(ms.clamp(1_000, CALL_STATS_WINDOW_MAX_MS)))
581}
582
583/// The sample of window `w` under `terms`: `native` and the audio fields only when the terms
584/// offer them. `Err` when it fails Sew's own checks (never sent).
585pub(crate) fn sample(w: &StatsWindow, terms: &CallStatsBeacon) -> Result<CallStatsSample, String> {
586    let audio = terms.audio_fields;
587    let candidate = w
588        .candidate
589        .as_deref()
590        .and_then(CallStatsCandidate::from_wire);
591    let relay_protocol = match candidate {
592        Some(CallStatsCandidate::Relay) => w
593            .relay_protocol
594            .as_deref()
595            .and_then(CallStatsRelayProtocol::from_wire),
596        _ => None,
597    };
598    let mut s = CallStatsSample::new(if audio {
599        CallStatsClient::Native
600    } else {
601        CallStatsClient::Other
602    });
603    s.interval_ms = w.interval_ms;
604    s.decrypt_failures = w.decrypt_failures;
605    s.candidate = candidate;
606    s.relay_protocol = relay_protocol;
607    s.rtt_ms = w.rtt_ms;
608    s.audio_played_ms = audio.then_some(w.audio_played_ms);
609    s.audio_concealed_ms = audio.then_some(w.audio_concealed_ms);
610    s.audio_packets_expected = audio.then_some(w.audio_packets_expected);
611    s.audio_packets_lost = audio.then_some(w.audio_packets_lost);
612    s.audio_jitter_ms = audio.then_some(w.audio_jitter_ms);
613    s.audio_longest_gap_ms = audio.then_some(w.audio_longest_gap_ms);
614    s.validate().map_err(|e| format!("invalid sample: {e}"))?;
615    Ok(s)
616}
617
618#[cfg(test)]
619mod tests {
620    #![allow(clippy::unwrap_used, clippy::expect_used)]
621    use super::*;
622
623    const TERMS: CallStatsBeacon = CallStatsBeacon {
624        interval_ms: 15_000,
625        audio_fields: true,
626    };
627
628    fn ms(n: u64) -> Duration {
629        Duration::from_millis(n)
630    }
631
632    struct Fixed(Vec<(u64, PlayoutTotals)>);
633    impl PlayoutStats for Fixed {
634        fn playout_totals(&self) -> Vec<(u64, PlayoutTotals)> {
635            self.0.clone()
636        }
637    }
638
639    #[test]
640    fn a_clean_stream_has_no_loss_no_gap_and_little_jitter() {
641        let t0 = Instant::now();
642        let mut m = Meter::new(t0, Some(&TERMS));
643        m.start(t0, &CallCounters::default());
644        for i in 0..750u64 {
645            m.on_packet(1, 1_000 + i, (i as u32) * 960, t0 + ms(20 * i));
646        }
647        let w = m.close(t0 + ms(15_000), &CallCounters::default(), None, false);
648        assert_eq!(w.interval_ms, 15_000);
649        // From the first packet: 750.
650        assert_eq!(w.audio_packets_expected, 750);
651        assert_eq!(w.audio_packets_lost, 0);
652        assert_eq!(w.audio_longest_gap_ms, 0);
653        assert_eq!(w.audio_jitter_ms, 0);
654        assert_eq!(w.playout_source, PlayoutSource::Engine);
655        let s = sample(&w, &TERMS).unwrap();
656        assert_eq!(s.client, CallStatsClient::Native);
657        assert_eq!(s.audio_packets_lost, Some(0));
658    }
659
660    #[test]
661    fn loss_and_a_stall_are_gaps_but_dtx_is_not() {
662        let t0 = Instant::now();
663        let mut m = Meter::new(t0, Some(&TERMS));
664        m.start(t0, &CallCounters::default());
665        // 0..10 clean, then 5 lost (seq 10..15 missing): the next arrives 120 ms later.
666        let mut at = 0u64;
667        for i in 0..10u64 {
668            m.on_packet(1, i, (i as u32) * 960, t0 + ms(at));
669            at += 20;
670        }
671        at += 100;
672        m.on_packet(1, 15, 15 * 960, t0 + ms(at));
673        let w = m.close(t0 + ms(1_000), &CallCounters::default(), None, false);
674        assert_eq!(w.audio_packets_expected, 16);
675        assert_eq!(w.audio_packets_lost, 5);
676        assert_eq!(w.audio_longest_gap_ms, 100, "{w:?}");
677        // On time, then a stall (seq + 1, timestamp + 960, 300 ms later), then DTX (seq + 1,
678        // the timestamps cover 400 ms, 400 ms later).
679        let t1 = t0 + ms(1_000);
680        m.on_packet(1, 16, 16 * 960, t1 + ms(20));
681        m.on_packet(1, 17, 17 * 960, t1 + ms(320));
682        m.on_packet(1, 18, 17 * 960 + 400 * 48, t1 + ms(720));
683        let w = m.close(t1 + ms(1_000), &CallCounters::default(), None, false);
684        assert_eq!(w.audio_packets_expected, 3);
685        assert_eq!(w.audio_packets_lost, 0);
686        assert_eq!(w.audio_longest_gap_ms, 280, "the stall, not the DTX: {w:?}");
687        assert!(w.audio_jitter_ms > 0);
688    }
689
690    #[test]
691    fn a_late_packet_counts_as_received() {
692        let t0 = Instant::now();
693        let mut m = Meter::new(t0, Some(&TERMS));
694        m.start(t0, &CallCounters::default());
695        m.on_packet(1, 0, 0, t0);
696        m.on_packet(1, 2, 2 * 960, t0 + ms(40));
697        m.on_packet(1, 1, 960, t0 + ms(45));
698        m.on_packet(1, 1, 960, t0 + ms(46));
699        let w = m.close(t0 + ms(1_000), &CallCounters::default(), None, false);
700        assert_eq!(w.audio_packets_expected, 3);
701        assert_eq!(w.audio_packets_lost, 0);
702    }
703
704    #[test]
705    fn the_pipeline_counters_are_differenced_per_window() {
706        let t0 = Instant::now();
707        let mut m = Meter::new(t0, Some(&TERMS));
708        m.start(t0, &CallCounters::default());
709        let a = Fixed(vec![(1, PlayoutTotals::new(700, 10, 40))]);
710        let w = m.close(t0 + ms(15_000), &CallCounters::default(), Some(&a), false);
711        assert_eq!(w.playout_source, PlayoutSource::Pipeline);
712        assert_eq!(w.audio_played_ms, 750 * 20);
713        assert_eq!(w.audio_concealed_ms, 40 * 20);
714        let b = Fixed(vec![(1, PlayoutTotals::new(1_440, 10, 50))]);
715        let w = m.close(t0 + ms(30_000), &CallCounters::default(), Some(&b), true);
716        assert_eq!(w.audio_played_ms, 750 * 20);
717        assert_eq!(w.audio_concealed_ms, 10 * 20);
718        assert!(w.last);
719    }
720
721    #[test]
722    fn the_engine_fallback_uses_frames_and_loss_marks() {
723        let t0 = Instant::now();
724        let mut m = Meter::new(t0, None);
725        m.start(t0, &CallCounters::default());
726        let c = CallCounters {
727            frames_received: 740,
728            lost_marks: 10,
729            decrypt_failures: 2,
730            frames_sent: 750,
731            ..CallCounters::default()
732        };
733        let w = m.close(t0 + ms(15_000), &c, None, false);
734        assert_eq!(w.audio_played_ms, 750 * 20);
735        assert_eq!(w.audio_concealed_ms, 200);
736        assert_eq!(w.decrypt_failures, 2);
737        assert_eq!(w.frames_sent, 750);
738    }
739
740    /// Every counted frame is in the bucket before the first window or in exactly one window:
741    /// the call's counter is their sum (the harness summary's `counters.decrypt_failures` once
742    /// disagreed with the windows' sum by the failures before `connected`). Frames whose key was
743    /// not installed yet are never in the sample's `decrypt_failures`.
744    #[test]
745    fn counters_are_the_bucket_before_the_first_window_plus_the_windows() {
746        let t0 = Instant::now();
747        let mut m = Meter::new(t0, Some(&TERMS));
748        // Before `connected`: the join's key switch.
749        let pre = CallCounters {
750            decrypt_failures: 1,
751            frames_before_key: 15,
752            refused_frames: 6,
753            frames_received: 20,
754            frames_sent: 30,
755            ..CallCounters::default()
756        };
757        let b = m.start(t0, &pre).expect("the first start");
758        assert_eq!(
759            b,
760            BeforeFirstWindow {
761                decrypt_failures: 1,
762                frames_before_key: 15,
763                refused_frames: 6,
764                frames_received: 20,
765                frames_sent: 30,
766            }
767        );
768        assert_eq!(m.start(t0 + ms(5), &pre), None, "once");
769        let mut c = pre.clone();
770        c.frames_before_key += 3;
771        c.decrypt_failures += 2;
772        c.frames_received += 700;
773        let w1 = m.close(t0 + ms(15_000), &c, None, false);
774        c.refused_frames += 1;
775        c.frames_received += 750;
776        let w2 = m.close(t0 + ms(30_000), &c, None, true);
777        assert_eq!((w1.frames_before_key, w1.decrypt_failures), (3, 2));
778        assert_eq!((w2.frames_before_key, w2.decrypt_failures), (0, 0));
779        assert_eq!(sample(&w1, &TERMS).unwrap().decrypt_failures, 2);
780        let sum = |f: fn(&StatsWindow) -> u64| [&w1, &w2].iter().map(|w| f(w)).sum::<u64>();
781        assert_eq!(
782            b.decrypt_failures + sum(|w| u64::from(w.decrypt_failures)),
783            c.decrypt_failures
784        );
785        assert_eq!(
786            b.frames_before_key + sum(|w| w.frames_before_key),
787            c.frames_before_key
788        );
789        assert_eq!(
790            b.refused_frames + sum(|w| w.refused_frames),
791            c.refused_frames
792        );
793        assert_eq!(
794            b.frames_received + sum(|w| w.frames_received),
795            c.frames_received
796        );
797    }
798
799    #[test]
800    fn without_audio_fields_the_sample_is_the_browsers_shape() {
801        let t0 = Instant::now();
802        let mut m = Meter::new(t0, None);
803        m.start(t0, &CallCounters::default());
804        m.on_peer(
805            Some((CallStatsCandidate::Relay, Some(CallStatsRelayProtocol::Tls))),
806            Some(ms(41)),
807        );
808        let w = m.close(t0 + ms(15_000), &CallCounters::default(), None, false);
809        let old = CallStatsBeacon {
810            interval_ms: 15_000,
811            audio_fields: false,
812        };
813        let s = sample(&w, &old).unwrap();
814        assert_eq!(s.client, CallStatsClient::Other);
815        assert!(!s.has_audio_fields());
816        let v = serde_json::to_value(&s).unwrap();
817        let keys: Vec<&String> = v.as_object().unwrap().keys().collect();
818        assert!(keys.iter().all(|k| !k.starts_with("audio_")), "{v}");
819        assert_eq!(v["candidate"], "relay");
820        assert_eq!(v["relay_protocol"], "tls");
821        assert_eq!(v["rtt_ms"], 41);
822    }
823
824    #[test]
825    fn values_are_clamped_to_the_caps() {
826        let t0 = Instant::now();
827        let mut m = Meter::new(t0, Some(&TERMS));
828        m.start(t0, &CallCounters::default());
829        m.on_peer(None, Some(Duration::from_secs(120)));
830        let w = m.close(t0, &CallCounters::default(), None, true);
831        assert_eq!(w.interval_ms, 1, "a window is at least 1 ms");
832        assert_eq!(w.rtt_ms, Some(CALL_STATS_RTT_MAX_MS));
833        assert!(sample(&w, &TERMS).is_ok());
834    }
835}