1use 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
65pub(crate) const FRAME_MS: u64 = 20;
67pub(crate) const WINDOWS_KEPT: usize = 256;
69const POLL_EVERY: Duration = Duration::from_secs(1);
71const MISSING_KEPT: usize = 128;
73const MISSING_MAX_RUN: u64 = 64;
75
76#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
79#[non_exhaustive]
80pub struct PlayoutTotals {
81 pub decoded: u64,
83 pub fec: u64,
85 pub concealed: u64,
87}
88
89impl PlayoutTotals {
90 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
104pub trait PlayoutStats: Send + Sync + 'static {
108 fn playout_totals(&self) -> Vec<(u64, PlayoutTotals)>;
111}
112
113#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
115#[serde(rename_all = "snake_case")]
116#[non_exhaustive]
117pub enum PlayoutSource {
118 Pipeline,
121 Engine,
123}
124
125#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
127#[serde(tag = "status", rename_all = "snake_case")]
128#[non_exhaustive]
129pub enum BeaconOutcome {
130 Off,
133 Stopped,
135 NoCredential,
137 Accepted {
139 http_status: u16,
141 },
142 Refused {
144 http_status: u16,
146 code: Option<String>,
148 reason: Option<String>,
150 },
151 Failed {
153 error: String,
155 },
156}
157
158#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
160#[non_exhaustive]
161pub struct StatsWindow {
162 pub index: u32,
164 pub interval_ms: u32,
166 pub last: bool,
168 pub audio_played_ms: u32,
170 pub audio_concealed_ms: u32,
172 pub audio_packets_expected: u32,
174 pub audio_packets_received: u32,
176 pub audio_packets_lost: u32,
178 pub audio_jitter_ms: u32,
180 pub audio_longest_gap_ms: u32,
184 pub playout_source: PlayoutSource,
186 pub decrypt_failures: u32,
188 pub frames_before_key: u64,
191 pub refused_frames: u64,
193 pub frames_sent: u64,
195 pub frames_received: u64,
197 pub candidate: Option<String>,
199 pub relay_protocol: Option<String>,
201 pub rtt_ms: Option<u32>,
203 pub noise_removal: Option<crate::NoiseRemovalState>,
207 pub sample: Option<CallStatsSample>,
209 pub beacon: BeaconOutcome,
211}
212
213#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
216#[non_exhaustive]
217pub struct BeforeFirstWindow {
218 pub decrypt_failures: u64,
220 pub frames_before_key: u64,
222 pub refused_frames: u64,
224 pub frames_received: u64,
226 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#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
244#[non_exhaustive]
245pub struct CallStatsReport {
246 pub terms: Option<CallStatsBeacon>,
248 pub before_first_window: Option<BeforeFirstWindow>,
250 pub windows: Vec<StatsWindow>,
252 pub samples_sent: u64,
254 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
273pub(crate) type Path = (CallStatsCandidate, Option<CallStatsRelayProtocol>);
275
276#[derive(Debug, Default)]
277struct Stream {
278 highest: Option<u64>,
279 first_expected: u64,
282 received: u64,
284 last_arrival: Option<Instant>,
285 last_ts: u32,
286 jitter_s: f64,
287 missing: VecDeque<u64>,
288}
289
290#[derive(Debug)]
292pub(crate) struct Meter {
293 interval: Duration,
294 started: Option<Instant>,
296 index: u32,
297 streams: HashMap<u64, Stream>,
298 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 pub(crate) fn set_terms(&mut self, terms: Option<&CallStatsBeacon>) {
341 self.interval = interval_of(terms);
342 }
343
344 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 pub(crate) fn deadline(&self) -> Option<Instant> {
366 let s = self.started?;
367 Some((s + self.interval).min(self.next_poll))
368 }
369
370 pub(crate) fn due(&self, now: Instant) -> bool {
372 self.started.is_some_and(|s| now >= s + self.interval)
373 }
374
375 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 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 let ts_adv_s = f64::from(ts.wrapping_sub(st.last_ts) as i32) / 48_000.0;
409 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 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 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 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 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
583pub(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 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 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 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 #[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 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}