Skip to main content

rtci_interceptor/xr/
mod.rs

1//! RTCP Extended Reports about received streams (RFC 3611 section 4): the unilateral report
2//! blocks a receiver sends about each source it hears.
3//!
4//! [`XrReportInterceptor`] watches the RTP that arrives on every bound remote stream and, on an
5//! interval, writes an XR packet with the blocks the stream asked for: Loss RLE (4.1),
6//! Duplicate RLE (4.2), Packet Receipt Times (4.3), Statistics Summary (4.6) and VoIP Metrics
7//! (4.7). The RTCP session puts it in its next compound packet.
8//!
9//! Which blocks a stream gets is what was negotiated for it with `a=rtcp-xr` (RFC 3611
10//! section 5.1): the stream's RTCP feedback carries each unilateral `xr-format` as an entry of
11//! type [`RTCP_FB_XR`] whose parameter is the format as signalled (`pkt-loss-rle`,
12//! `pkt-loss-rle=200`, `stat-summary=loss,dup,jitt`, `voip-metrics` ...). A stream with no such
13//! entry gets no block (section 5.1: "participants SHOULD NOT send XR blocks other than the
14//! ones indicated"). [`XrReportBuilder::with_formats`] sends blocks without negotiation, for an
15//! application that agreed on them some other way.
16//!
17//! The round-trip pair (receiver reference time and DLRR, sections 4.4 and 4.5) is the RTCP
18//! session's.
19
20pub(crate) mod burst;
21pub(crate) mod sequence;
22
23use crate::jitterbuffer::discards::JitterBufferDiscards;
24use crate::rfc8888::sender::random_ssrc;
25use crate::rtcp_session::RtcpSessionEvent;
26use crate::stream_info::StreamInfo;
27use crate::{AttributedPacket, Interceptor, Packet, TaggedPacket};
28use burst::BurstGapModel;
29use rtcp::extended_report::{
30    ExtendedReport, PacketReceiptTimesReportBlock, RLEReportBlock, StatisticsSummaryReportBlock,
31    TTLorHopLimitType, VoIPMetricsReportBlock, reported_sequence_numbers,
32};
33use sansio::Protocol;
34use sequence::SequenceExtender;
35use shared::TransportContext;
36use shared::error::Error;
37use shared::marshal::MarshalSize;
38use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
39use std::sync::{Arc, Mutex};
40use std::time::{Duration, Instant};
41
42/// The RTCP feedback type a stream's negotiated `a=rtcp-xr` unilateral formats arrive under
43/// (one entry per format, the format as its parameter).
44pub const RTCP_FB_XR: &str = "xr";
45
46/// The `xr-format` of the RFC 6679 ECN Summary Report block (`a=rtcp-xr:ecn-sum`, section 6.3).
47/// The RTCP session writes the block ([`RtcpSessionInterceptor`](crate::RtcpSessionInterceptor)).
48pub const RTCP_XR_ECN_SUMMARY: &str = "ecn-sum";
49
50/// The `nack` parameter of the RFC 6679 RTCP ECN Feedback packet (`a=rtcp-fb:<pt> nack ecn`,
51/// section 6.2). The RTCP session writes the packet.
52pub const RTCP_FB_NACK_ECN: &str = "ecn";
53
54/// How often the blocks are written when no interval is configured: about once per regular
55/// RTCP report of a video session.
56pub const DEFAULT_INTERVAL: Duration = Duration::from_secs(1);
57
58/// The Gmin of the VoIP Metrics burst model (RFC 3611 section 4.7.2 recommends 16).
59pub const DEFAULT_GMIN: u8 = 16;
60
61/// The largest size, in octets, of a Loss RLE, Duplicate RLE or Packet Receipt Times block
62/// when the stream's `xr-format` gives none, and the default of
63/// [`XrReportBuilder::with_max_block_size`]. RFC 3611 section 7: "applications SHOULD place
64/// an upper limit on the size of the XR report blocks they employ", and "the "thinning"
65/// techniques described in Section 4.1 permit the packet-by-packet report blocks to adhere
66/// to a predefined size limit". At 256 octets a stream's Loss RLE, Duplicate RLE and one
67/// Packet Receipt Times block, its Statistics Summary (40) and VoIP Metrics (36) blocks and a
68/// compound packet's report and SDES fit the RTCP session's default 1200-octet packet. Without
69/// it, a block could cover 65,533 sequence numbers (section 4.1): a Packet Receipt Times
70/// block of four octets each.
71pub const DEFAULT_MAX_BLOCK_SIZE: usize = 256;
72
73/// The largest sequence-number range one block reports on (RFC 3611 section 4.1: "MUST NOT
74/// report on a sequence number range of 65,534 or more").
75const MAX_RANGE: u64 = 65_533;
76
77/// How many of the packets reported lost are remembered, so that one arriving late is taken
78/// back from the loss count: a packet counts as lost only when it never comes (among the last
79/// this many reported lost), which is later than any jitter buffer's discard (RFC 3611 section
80/// 4.7.1: "The degree of lateness that triggers a loss SHOULD be significantly greater than
81/// that which triggers a discard").
82const REPORTED_LOSS_MEMORY: usize = 4096;
83
84/// The jitter buffer the application plays a stream out of, for the VoIP Metrics block (RFC
85/// 3611 section 4.7.7). The engine does not play media out, so it cannot know these itself.
86#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
87pub struct JitterBufferMetrics {
88    /// Adaptive (`Some(true)`), fixed (`Some(false)`) or not known (`None`).
89    pub adaptive: Option<bool>,
90    /// The jitter buffer rate, 0 to 15 (section 4.7.6, JB rate).
91    pub rate: u8,
92    /// Nominal delay in milliseconds.
93    pub nominal_ms: u16,
94    /// Maximum delay in milliseconds.
95    pub maximum_ms: u16,
96    /// Absolute maximum delay in milliseconds.
97    pub absolute_maximum_ms: u16,
98}
99
100/// The call quality figures of the VoIP Metrics block (RFC 3611 section 4.7.5), which come
101/// from a call quality model of the decoded media (ITU-T G.107 / ETSI TS 101 329-5): the
102/// application's to compute, as the engine does not decode. Given to
103/// [`XrReportHandle::set_call_quality`]. `None`, or a value outside the field's range, is
104/// sent as 127, "unavailable" (section 4.7.5: other values "MUST not be sent").
105#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
106pub struct CallQuality {
107    /// The R factor of the segment carried over this RTP session, 0 to 100.
108    pub r_factor: Option<u8>,
109    /// The external R factor (a network segment beyond the RTP one), 0 to 100.
110    pub external_r_factor: Option<u8>,
111    /// MOS-LQ, listening quality without the effects of delay, MOS x 10: 10 to 50.
112    pub mos_lq: Option<u8>,
113    /// MOS-CQ, conversational quality with the effects of delay, MOS x 10: 10 to 50.
114    pub mos_cq: Option<u8>,
115}
116
117impl CallQuality {
118    /// The four octets as the block carries them: each value in its range, 127 otherwise.
119    fn octets(&self) -> (u8, u8, u8, u8) {
120        let unavailable = rtcp::extended_report::vm::VOIP_METRIC_UNAVAILABLE;
121        let r = |value: Option<u8>| value.filter(|v| *v <= 100).unwrap_or(unavailable);
122        let mos = |value: Option<u8>| {
123            value
124                .filter(|v| (10..=50).contains(v))
125                .unwrap_or(unavailable)
126        };
127        (
128            r(self.r_factor),
129            r(self.external_r_factor),
130            mos(self.mos_lq),
131            mos(self.mos_cq),
132        )
133    }
134}
135
136/// The application's way to give the XR generator what only it knows, while the connection
137/// runs: the call quality figures of each received stream's VoIP Metrics block (RFC 3611
138/// section 4.7.5). Built with [`XrReportBuilder::build_with_handle`]; clones share the state.
139///
140/// ```
141/// use rtci_interceptor::{CallQuality, Registry, Slot, XrReportBuilder, XrReportHandle};
142///
143/// let handle = XrReportHandle::new();
144/// let chain = Registry::new()
145///     .with(Slot::ExtendedReports, XrReportBuilder::new().build_with_handle(&handle))
146///     .build();
147/// // From the application's own call quality model of the stream it plays out:
148/// handle.set_call_quality(
149///     0x1234_5678,
150///     CallQuality { r_factor: Some(88), mos_lq: Some(41), mos_cq: Some(40), ..Default::default() },
151/// );
152/// # let _ = chain;
153/// ```
154#[derive(Debug, Clone, Default)]
155pub struct XrReportHandle {
156    call_quality: Arc<Mutex<HashMap<u32, CallQuality>>>,
157}
158
159impl XrReportHandle {
160    /// A handle with no interceptor yet.
161    pub fn new() -> Self {
162        Self::default()
163    }
164
165    /// The call quality figures for the remote stream `ssrc`, sent in its next VoIP Metrics
166    /// blocks until replaced or cleared.
167    pub fn set_call_quality(&self, ssrc: u32, quality: CallQuality) {
168        self.lock().insert(ssrc, quality);
169    }
170
171    /// Forgets the figures for `ssrc`: its blocks say "unavailable" again.
172    pub fn clear_call_quality(&self, ssrc: u32) {
173        self.lock().remove(&ssrc);
174    }
175
176    /// The figures last given for `ssrc`.
177    pub fn call_quality(&self, ssrc: u32) -> Option<CallQuality> {
178        self.lock().get(&ssrc).copied()
179    }
180
181    fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<u32, CallQuality>> {
182        self.call_quality
183            .lock()
184            .unwrap_or_else(|poisoned| poisoned.into_inner())
185    }
186}
187
188/// What a stream's negotiated XR formats ask for.
189#[derive(Debug, Clone, Default, PartialEq, Eq)]
190pub(crate) struct XrFormats {
191    /// Loss RLE, with the largest size of the block in octets when one was given.
192    pub(crate) loss_rle: Option<Option<usize>>,
193    /// Duplicate RLE, with its largest size.
194    pub(crate) duplicate_rle: Option<Option<usize>>,
195    /// Packet Receipt Times, with its largest size.
196    pub(crate) receipt_times: Option<Option<usize>>,
197    /// Statistics Summary, with the fields asked for.
198    pub(crate) statistics: Option<StatisticsFields>,
199    /// VoIP Metrics.
200    pub(crate) voip_metrics: bool,
201}
202
203/// The fields `stat-summary=` lists (RFC 3611 section 5.1).
204#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
205pub(crate) struct StatisticsFields {
206    pub(crate) loss: bool,
207    pub(crate) duplicates: bool,
208    pub(crate) jitter: bool,
209    /// `TTL` or `HL` was listed. Neither can be measured here (the IP header is the
210    /// application's socket's), so the block says the fields are not reported.
211    pub(crate) ttl_or_hop_limit: bool,
212}
213
214impl XrFormats {
215    /// The formats named in `formats` (each an `xr-format` as signalled).
216    pub(crate) fn parse<'a>(formats: impl IntoIterator<Item = &'a str>) -> Self {
217        let mut out = XrFormats::default();
218        for format in formats {
219            let (name, value) = match format.split_once('=') {
220                Some((name, value)) => (name, Some(value)),
221                None => (format, None),
222            };
223            let size = || value.and_then(|v| v.parse::<usize>().ok());
224            match name {
225                "pkt-loss-rle" => out.loss_rle = Some(size()),
226                "pkt-dup-rle" => out.duplicate_rle = Some(size()),
227                "pkt-rcpt-times" => out.receipt_times = Some(size()),
228                "stat-summary" => {
229                    let mut fields = StatisticsFields::default();
230                    for field in value.unwrap_or_default().split(',') {
231                        match field {
232                            "loss" => fields.loss = true,
233                            "dup" => fields.duplicates = true,
234                            "jitt" => fields.jitter = true,
235                            "TTL" | "HL" => fields.ttl_or_hop_limit = true,
236                            _ => {}
237                        }
238                    }
239                    out.statistics = Some(fields);
240                }
241                "voip-metrics" => out.voip_metrics = true,
242                _ => {}
243            }
244        }
245        out
246    }
247
248    /// The formats a stream negotiated: its [`RTCP_FB_XR`] feedback entries.
249    pub(crate) fn of_stream(info: &StreamInfo) -> Self {
250        Self::parse(
251            info.rtcp_feedback
252                .iter()
253                .filter(|feedback| feedback.typ == RTCP_FB_XR)
254                .map(|feedback| feedback.parameter.as_str()),
255        )
256    }
257
258    fn any(&self) -> bool {
259        self.loss_rle.is_some()
260            || self.duplicate_rle.is_some()
261            || self.receipt_times.is_some()
262            || self.statistics.is_some()
263            || self.voip_metrics
264    }
265}
266
267/// Builder for [`XrReportInterceptor`].
268///
269/// ```
270/// use rtci_interceptor::{Registry, Slot, XrReportBuilder};
271///
272/// let chain = Registry::new()
273///     .with(Slot::ExtendedReports, XrReportBuilder::new().build())
274///     .build();
275/// # let _ = chain;
276/// ```
277#[derive(Debug, Clone)]
278pub struct XrReportBuilder {
279    interval: Duration,
280    formats: Option<Vec<String>>,
281    gmin: u8,
282    jitter_buffer: JitterBufferMetrics,
283    sender_ssrc: Option<u32>,
284    max_block_size: usize,
285    discards: Option<JitterBufferDiscards>,
286}
287
288impl Default for XrReportBuilder {
289    fn default() -> Self {
290        Self {
291            interval: DEFAULT_INTERVAL,
292            formats: None,
293            gmin: DEFAULT_GMIN,
294            jitter_buffer: JitterBufferMetrics::default(),
295            sender_ssrc: None,
296            max_block_size: DEFAULT_MAX_BLOCK_SIZE,
297            discards: None,
298        }
299    }
300}
301
302impl XrReportBuilder {
303    /// A builder with the defaults: one report a second, blocks as negotiated, Gmin 16.
304    pub fn new() -> Self {
305        Self::default()
306    }
307
308    /// How often the blocks are written.
309    pub fn with_interval(mut self, interval: Duration) -> Self {
310        self.interval = interval;
311        self
312    }
313
314    /// Send these `xr-format`s for every remote stream, whatever was negotiated (RFC 3611
315    /// section 5.1 allows blocks agreed on outside the signalling).
316    pub fn with_formats<S: Into<String>>(mut self, formats: impl IntoIterator<Item = S>) -> Self {
317        self.formats = Some(formats.into_iter().map(Into::into).collect());
318        self
319    }
320
321    /// The Gmin of the burst model (RFC 3611 section 4.7.2). 0 is taken as the default 16
322    /// (section 4.7.6: "Gmin MUST NOT be zero").
323    pub fn with_gmin(mut self, gmin: u8) -> Self {
324        self.gmin = if gmin == 0 { DEFAULT_GMIN } else { gmin };
325        self
326    }
327
328    /// The application's jitter buffer, reported in the VoIP Metrics block.
329    pub fn with_jitter_buffer(mut self, jitter_buffer: JitterBufferMetrics) -> Self {
330        self.jitter_buffer = jitter_buffer;
331        self
332    }
333
334    /// The SSRC the reports are sent from. Left unset: the first local stream's, or a random
335    /// one while there is none.
336    pub fn with_sender_ssrc(mut self, ssrc: u32) -> Self {
337        self.sender_ssrc = Some(ssrc);
338        self
339    }
340
341    /// The largest size, in octets, of a Loss RLE, Duplicate RLE or Packet Receipt Times
342    /// block (RFC 3611 section 7); a smaller size a stream's `xr-format` gives wins. Thinning
343    /// (section 4.1) brings a block under it. [`DEFAULT_MAX_BLOCK_SIZE`] unless set; at least
344    /// the 16 octets of a block with one entry.
345    pub fn with_max_block_size(mut self, octets: usize) -> Self {
346        self.max_block_size = octets.max(16);
347        self
348    }
349
350    /// The discards of the jitter buffer the streams are played out of, for the VoIP Metrics
351    /// block's discard rate (RFC 3611 section 4.7.1): the same handle given to the engine's
352    /// jitter buffer ([`JitterBufferBuilder::with_discard_count`](crate::JitterBufferBuilder::with_discard_count),
353    /// [`AdaptiveJitterBufferBuilder::with_discard_count`](crate::AdaptiveJitterBufferBuilder::with_discard_count)).
354    /// Without one the discard rate is 0: nothing in the chain discards.
355    pub fn with_jitter_buffer_discards(mut self, discards: &JitterBufferDiscards) -> Self {
356        self.discards = Some(discards.clone());
357        self
358    }
359
360    /// Build the interceptor.
361    pub fn build(self) -> XrReportInterceptor {
362        self.build_with_handle(&XrReportHandle::new())
363    }
364
365    /// Build the interceptor, taking what the application gives through `handle` (the call
366    /// quality figures, RFC 3611 section 4.7.5).
367    pub fn build_with_handle(self, handle: &XrReportHandle) -> XrReportInterceptor {
368        XrReportInterceptor {
369            interval: self.interval,
370            formats: self
371                .formats
372                .map(|f| XrFormats::parse(f.iter().map(String::as_str))),
373            gmin: self.gmin,
374            jitter_buffer: self.jitter_buffer,
375            max_block_size: self.max_block_size,
376            discards: self.discards,
377            handle: handle.clone(),
378            configured_ssrc: self.sender_ssrc,
379            receiver_ssrc: random_ssrc(),
380            local_ssrcs: vec![],
381            streams: HashMap::new(),
382            round_trip: None,
383            next_timeout: None,
384            read_queue: VecDeque::new(),
385            write_queue: VecDeque::new(),
386        }
387    }
388}
389
390/// One packet of an interval, by extended sequence number.
391#[derive(Debug, Clone, Copy)]
392struct Arrival {
393    /// When the first copy arrived (RFC 3611 4.3: "any time other than the earliest MUST NOT
394    /// be reported").
395    first: Instant,
396    /// Copies received.
397    copies: u32,
398}
399
400/// What is known about one remote stream.
401#[derive(Debug)]
402struct RemoteStream {
403    formats: XrFormats,
404    clock_rate: u32,
405    sequence: SequenceExtender,
406    /// The first extended sequence number the next blocks report on.
407    begin: Option<u64>,
408    /// The packets of the current interval.
409    arrivals: BTreeMap<u64, Arrival>,
410    /// Relative transit times between consecutive packets of the interval, in timestamp
411    /// units (RFC 3611 4.6).
412    transit_differences: Vec<u32>,
413    /// The previous packet's (arrival, RTP timestamp), for the transit difference.
414    previous: Option<(Instant, u32)>,
415    /// Where receipt times start: the first arrival and a random RTP-timestamp-unit offset
416    /// (RFC 3611 4.3: "the first receipt time value SHOULD also be chosen at random").
417    receipt_origin: Option<(Instant, u32)>,
418    /// Since the beginning of reception (RFC 3611 4.7.1, 4.7.2).
419    expected_total: u64,
420    lost_total: u64,
421    /// The sequence numbers reported lost most recently (at most [`REPORTED_LOSS_MEMORY`]):
422    /// one that arrives after all is taken back from `lost_total`.
423    reported_lost: BTreeSet<u64>,
424    burst: BurstGapModel,
425    /// Timestamp increments between consecutive packets, for the packet duration the burst
426    /// and gap durations are counted in.
427    timestamp_step_sum: u64,
428    timestamp_steps: u64,
429    previous_in_order: Option<(u64, u32)>,
430    /// The id of the stream's client-to-mixer audio level extension (RFC 6464), if it
431    /// negotiated one: the VoIP Metrics block's signal and noise levels come from it.
432    audio_level_id: Option<u8>,
433    /// RFC 3611 4.7.4: the levels the audio level extension gave since the beginning of
434    /// reception, in dBm0, summed over the packets with voice (signal) and without (noise).
435    signal_levels: (i64, u64),
436    noise_levels: (i64, u64),
437}
438
439impl RemoteStream {
440    fn new(formats: XrFormats, clock_rate: u32, gmin: u8) -> Self {
441        Self {
442            formats,
443            clock_rate: clock_rate.max(1),
444            sequence: SequenceExtender::default(),
445            begin: None,
446            arrivals: BTreeMap::new(),
447            transit_differences: vec![],
448            previous: None,
449            receipt_origin: None,
450            expected_total: 0,
451            lost_total: 0,
452            reported_lost: BTreeSet::new(),
453            burst: BurstGapModel::new(gmin),
454            timestamp_step_sum: 0,
455            timestamp_steps: 0,
456            previous_in_order: None,
457            audio_level_id: None,
458            signal_levels: (0, 0),
459            noise_levels: (0, 0),
460        }
461    }
462
463    /// RFC 3611 4.7.4 from RFC 6464: a packet's audio level (in -dBov) as dBm0 (0 dBov, a
464    /// full-scale sine, is +3 dBm0, ITU-T G.711), counted as signal when the sender marked
465    /// voice in it and as noise when it did not.
466    fn on_audio_level(&mut self, level: u8, voice: bool) {
467        let dbm0 = 3 - i64::from(level.min(127));
468        let sums = if voice {
469            &mut self.signal_levels
470        } else {
471            &mut self.noise_levels
472        };
473        sums.0 += dbm0;
474        sums.1 += 1;
475    }
476
477    /// The mean of `sums` as the block's signed octet, 127 (unavailable) when nothing was
478    /// measured.
479    fn mean_level((sum, count): (i64, u64)) -> u8 {
480        if count == 0 {
481            return rtcp::extended_report::vm::VOIP_METRIC_UNAVAILABLE;
482        }
483        let mean = (sum as f64 / count as f64).round() as i64;
484        (mean.clamp(-126, 126) as i8) as u8
485    }
486
487    fn ticks(&self, duration: Duration) -> u64 {
488        (duration.as_secs_f64() * f64::from(self.clock_rate)).round() as u64
489    }
490
491    fn on_packet(&mut self, now: Instant, sequence_number: u16, timestamp: u32) {
492        let extended = self.sequence.extend(sequence_number);
493        if self.receipt_origin.is_none() {
494            self.receipt_origin = Some((now, rand::random()));
495        }
496        match self.begin {
497            None => self.begin = Some(extended),
498            // Older than what the last blocks covered: already reported on, so a late copy
499            // counts for nothing new in the interval blocks. A packet they reported lost has
500            // arrived after all: the loss rate since the beginning of reception (RFC 3611
501            // section 4.7.1) no longer counts it.
502            Some(begin) if extended < begin => {
503                if self.reported_lost.remove(&extended) {
504                    self.lost_total = self.lost_total.saturating_sub(1);
505                }
506                return;
507            }
508            _ => {}
509        }
510        let arrival = self.arrivals.entry(extended).or_insert(Arrival {
511            first: now,
512            copies: 0,
513        });
514        arrival.copies += 1;
515        if arrival.copies > 1 {
516            return;
517        }
518        if let Some((at, previous_timestamp)) = self.previous {
519            // RFC 3550 6.4.1: D(i,j) = (Rj - Ri) - (Sj - Si), in timestamp units.
520            let arrival_ticks = self.ticks(now.saturating_duration_since(at)) as i64;
521            let sent_ticks = i64::from(timestamp.wrapping_sub(previous_timestamp) as i32);
522            let difference = (arrival_ticks - sent_ticks).unsigned_abs();
523            self.transit_differences
524                .push(difference.min(u64::from(u32::MAX)) as u32);
525        }
526        self.previous = Some((now, timestamp));
527        if let Some((previous_extended, previous_timestamp)) = self.previous_in_order
528            && extended == previous_extended + 1
529        {
530            self.timestamp_step_sum += u64::from(timestamp.wrapping_sub(previous_timestamp));
531            self.timestamp_steps += 1;
532        }
533        if self
534            .previous_in_order
535            .is_none_or(|(previous_extended, _)| extended > previous_extended)
536        {
537            self.previous_in_order = Some((extended, timestamp));
538        }
539    }
540
541    /// The duration of one packet in milliseconds, from the RTP timestamps (RFC 3611 4.7.2:
542    /// "if the actual values are not available, estimated values MUST be used").
543    fn packet_duration_ms(&self) -> f64 {
544        if self.timestamp_steps == 0 {
545            return 20.0;
546        }
547        let ticks = self.timestamp_step_sum as f64 / self.timestamp_steps as f64;
548        ticks * 1000.0 / f64::from(self.clock_rate)
549    }
550
551    fn receipt_time(&self, at: Instant) -> u32 {
552        let (origin, offset) = self.receipt_origin.expect("set with the first packet");
553        offset.wrapping_add(self.ticks(at.saturating_duration_since(origin)) as u32)
554    }
555}
556
557/// Writes RFC 3611 report blocks about the remote streams that asked for them.
558pub struct XrReportInterceptor {
559    interval: Duration,
560    formats: Option<XrFormats>,
561    gmin: u8,
562    jitter_buffer: JitterBufferMetrics,
563    max_block_size: usize,
564    /// The jitter buffer's discards, when the application shared them.
565    discards: Option<JitterBufferDiscards>,
566    handle: XrReportHandle,
567    configured_ssrc: Option<u32>,
568    receiver_ssrc: u32,
569    local_ssrcs: Vec<u32>,
570    streams: HashMap<u32, RemoteStream>,
571    /// The most recent round trip time the RTCP session measured.
572    round_trip: Option<Duration>,
573    next_timeout: Option<Instant>,
574    read_queue: VecDeque<TaggedPacket>,
575    write_queue: VecDeque<TaggedPacket>,
576}
577
578impl XrReportInterceptor {
579    /// The SSRC the reports are sent from.
580    pub fn sender_ssrc(&self) -> u32 {
581        self.configured_ssrc
582            .or_else(|| self.local_ssrcs.first().copied())
583            .unwrap_or(self.receiver_ssrc)
584    }
585
586    fn arm(&mut self, now: Instant) {
587        if self.next_timeout.is_none() && !self.streams.is_empty() {
588            self.next_timeout = Some(now + self.interval);
589        }
590    }
591
592    /// The blocks about `ssrc` for the interval that ends now.
593    fn blocks(&mut self, ssrc: u32) -> Vec<Box<dyn rtcp::Packet>> {
594        let jitter_buffer = self.jitter_buffer;
595        let round_trip = self.round_trip;
596        let gmin = self.gmin;
597        let max_block_size = self.max_block_size;
598        let call_quality = self.handle.call_quality(ssrc).unwrap_or_default();
599        let (discarded, discarded_now) = self.discards.as_ref().map_or((0, vec![]), |discards| {
600            (discards.discarded(ssrc), discards.take_pending(ssrc))
601        });
602        // RFC 3611 section 7: every per-packet block within a limit, the stream's own
603        // (section 5.1) when it is smaller.
604        let limit = |signalled: Option<usize>| -> usize {
605            signalled.map_or(max_block_size, |size| size.min(max_block_size))
606        };
607        let Some(stream) = self.streams.get_mut(&ssrc) else {
608            return vec![];
609        };
610        let (Some(begin), Some(&last)) = (stream.begin, stream.arrivals.keys().next_back()) else {
611            return vec![];
612        };
613        // RFC 3611 4.1: one block reports on fewer than 65,534 sequence numbers; what is
614        // older than that is left out.
615        let begin = begin.max((last + 1).saturating_sub(MAX_RANGE));
616        let end = last + 1;
617        let range: Vec<u64> = (begin..end).collect();
618        let begin_seq = begin as u16;
619        let end_seq = end as u16;
620        let received: Vec<bool> = range
621            .iter()
622            .map(|seq| stream.arrivals.contains_key(seq))
623            .collect();
624        let lost = received.iter().filter(|r| !**r).count() as u64;
625        let duplicates: u64 = stream
626            .arrivals
627            .range(begin..end)
628            .map(|(_, a)| u64::from(a.copies - 1))
629            .sum();
630
631        stream.expected_total += range.len() as u64;
632        stream.lost_total += lost;
633        stream.reported_lost.extend(
634            range
635                .iter()
636                .zip(&received)
637                .filter(|(_, received)| !**received)
638                .map(|(seq, _)| *seq),
639        );
640        while stream.reported_lost.len() > REPORTED_LOSS_MEMORY {
641            stream.reported_lost.pop_first();
642        }
643        // RFC 3611 4.7.2: the burst and gap metrics count packets "either lost or discarded".
644        // A packet of this interval the jitter buffer discarded (it learns the 16-bit number)
645        // is marked here; one it discards after this interval was reported is in the discard
646        // rate only, the interval's packets having gone through the model already.
647        let mut discarded_flags = vec![false; range.len()];
648        for seq in discarded_now {
649            let offset = usize::from(seq.wrapping_sub(begin_seq));
650            if let Some(flag) = discarded_flags.get_mut(offset) {
651                *flag = true;
652            }
653        }
654        for (flag, discarded) in received.iter().zip(&discarded_flags) {
655            stream.burst.observe(!*flag, *flag && *discarded);
656        }
657
658        let mut blocks: Vec<Box<dyn rtcp::Packet>> = vec![];
659        if let Some(signalled) = stream.formats.loss_rle {
660            let limit = limit(signalled);
661            blocks.push(Box::new(rle_block(true, ssrc, begin, end, limit, &|seq| {
662                stream.arrivals.contains_key(&seq)
663            })));
664        }
665        if let Some(signalled) = stream.formats.duplicate_rle {
666            let limit = limit(signalled);
667            blocks.push(Box::new(rle_block(
668                false,
669                ssrc,
670                begin,
671                end,
672                limit,
673                &|seq| stream.arrivals.get(&seq).is_some_and(|a| a.copies > 1),
674            )));
675        }
676        if let Some(signalled) = stream.formats.receipt_times {
677            let limit = limit(signalled);
678            // RFC 3611 4.3: "At least one packet MUST have been received for each sequence
679            // number reported upon in this block": one block per run of received packets.
680            let mut run: Vec<(u64, Instant)> = vec![];
681            let mut runs: Vec<Vec<(u64, Instant)>> = vec![];
682            for seq in begin..end {
683                match stream.arrivals.get(&seq) {
684                    Some(arrival) => run.push((seq, arrival.first)),
685                    None if !run.is_empty() => runs.push(std::mem::take(&mut run)),
686                    None => {}
687                }
688            }
689            if !run.is_empty() {
690                runs.push(run);
691            }
692            for run in runs {
693                blocks.push(Box::new(receipt_times_block(stream, ssrc, &run, limit)));
694            }
695        }
696        if let Some(fields) = stream.formats.statistics {
697            let differences = &stream.transit_differences;
698            let (min, max, mean, dev) = if differences.is_empty() {
699                (0, 0, 0, 0)
700            } else {
701                let n = differences.len() as f64;
702                let mean = differences.iter().map(|d| f64::from(*d)).sum::<f64>() / n;
703                let variance = differences
704                    .iter()
705                    .map(|d| (f64::from(*d) - mean).powi(2))
706                    .sum::<f64>()
707                    / n;
708                (
709                    *differences.iter().min().expect("not empty"),
710                    *differences.iter().max().expect("not empty"),
711                    mean.round() as u32,
712                    variance.sqrt().round() as u32,
713                )
714            };
715            blocks.push(Box::new(
716                StatisticsSummaryReportBlock {
717                    loss_reports: fields.loss,
718                    duplicate_reports: fields.duplicates,
719                    jitter_reports: fields.jitter,
720                    // The TTL / hop limit is in the IP header, which a sans-I/O engine
721                    // never sees: reported as not reported (ToH 0).
722                    ttl_or_hop_limit: TTLorHopLimitType::Missing,
723                    ssrc,
724                    begin_seq,
725                    end_seq,
726                    lost_packets: lost as u32,
727                    dup_packets: duplicates as u32,
728                    min_jitter: min,
729                    max_jitter: max,
730                    mean_jitter: mean,
731                    dev_jitter: dev,
732                    ..Default::default()
733                }
734                .reported(),
735            ));
736        }
737        if stream.formats.voip_metrics {
738            let metrics = stream.burst.metrics(stream.packet_duration_ms());
739            let rate = |part: u64, whole: u64| -> u8 {
740                (part * 256)
741                    .checked_div(whole)
742                    .map_or(0, |d| d.min(255) as u8)
743            };
744            // RFC 3611 4.7.6: PLC (unspecified here, the decoder is the application's), JBA
745            // (0 unknown, 2 non-adaptive, 3 adaptive) and the JB rate.
746            let jba: u8 = match jitter_buffer.adaptive {
747                None => 0,
748                Some(false) => 2,
749                Some(true) => 3,
750            };
751            let jitter_buffer_rx_config = (jba << 4) | (jitter_buffer.rate & 0x0F);
752            let (rfactor, ext_rfactor, mos_lq, mos_cq) = call_quality.octets();
753            blocks.push(Box::new(VoIPMetricsReportBlock {
754                ssrc,
755                loss_rate: rate(stream.lost_total, stream.expected_total),
756                // RFC 3611 4.7.1: the packets the jitter buffer discarded (late or early
757                // arrival, overflow; duplicates excluded) over those expected, since the
758                // beginning of reception. 0 when no jitter buffer shares its count: nothing
759                // else in the chain discards.
760                discard_rate: rate(discarded, stream.expected_total),
761                burst_density: metrics.burst_density,
762                gap_density: metrics.gap_density,
763                burst_duration: metrics.burst_duration_ms,
764                gap_duration: metrics.gap_duration_ms,
765                round_trip_delay: round_trip
766                    .map(|rtt| rtt.as_millis().min(u128::from(u16::MAX)) as u16)
767                    .unwrap_or(0),
768                // RFC 3611 4.7.3: "If an implementation is unable to provide the data, the
769                // value 0 MUST be used."
770                end_system_delay: 0,
771                gmin,
772                rx_config: jitter_buffer_rx_config,
773                jb_nominal: jitter_buffer.nominal_ms,
774                jb_maximum: jitter_buffer.maximum_ms,
775                jb_abs_max: jitter_buffer.absolute_maximum_ms,
776                // RFC 3611 4.7.4: the signal level during talkspurts and the noise level
777                // during silence, from the RFC 6464 audio levels the stream carried (127 when
778                // it carried none). RERL needs the application's echo canceller: 127.
779                signal_level: RemoteStream::mean_level(stream.signal_levels),
780                noise_level: RemoteStream::mean_level(stream.noise_levels),
781                // RFC 3611 4.7.5: R factor, external R factor, MOS-LQ and MOS-CQ come from a
782                // call quality model (ITU-T G.107) of the decoded media, which is the
783                // application's: what it gave through the handle, 127 ("unavailable")
784                // where it gave nothing.
785                rfactor,
786                ext_rfactor,
787                mos_lq,
788                mos_cq,
789                ..Default::default()
790            }));
791        }
792
793        // The next interval starts after this one.
794        stream.begin = Some(end);
795        stream.arrivals = stream.arrivals.split_off(&end);
796        stream.transit_differences.clear();
797        blocks
798    }
799}
800
801/// A Loss or Duplicate RLE block for `begin..end`, thinned until it fits `limit` octets (RFC
802/// 3611 5.1: "the largest size the whole report block SHOULD have"; section 7).
803fn rle_block(
804    is_loss_rle: bool,
805    ssrc: u32,
806    begin: u64,
807    end: u64,
808    limit: usize,
809    flag: &dyn Fn(u64) -> bool,
810) -> RLEReportBlock {
811    let mut t = 0u8;
812    loop {
813        let flags: Vec<bool> = reported(begin, end, t).into_iter().map(flag).collect();
814        let block =
815            RLEReportBlock::from_flags(is_loss_rle, ssrc, begin as u16, end as u16, t, &flags);
816        if block.marshal_size() <= limit || t == 15 {
817            return block;
818        }
819        t += 1;
820    }
821}
822
823/// The extended sequence numbers of `begin..end` a block with thinning `t` reports on.
824fn reported(begin: u64, end: u64, t: u8) -> Vec<u64> {
825    let seqs = reported_sequence_numbers(begin as u16, end as u16, t);
826    // Each reported 16-bit number is at its offset from `begin`.
827    seqs.into_iter()
828        .map(|seq| begin + u64::from(seq.wrapping_sub(begin as u16)))
829        .collect()
830}
831
832fn receipt_times_block(
833    stream: &RemoteStream,
834    ssrc: u32,
835    run: &[(u64, Instant)],
836    limit: usize,
837) -> PacketReceiptTimesReportBlock {
838    let begin = run[0].0;
839    let end = run[run.len() - 1].0 + 1;
840    let mut t = 0u8;
841    loop {
842        let wanted = reported(begin, end, t);
843        let receipt_time = run
844            .iter()
845            .filter(|(seq, _)| wanted.contains(seq))
846            .map(|(_, at)| stream.receipt_time(*at))
847            .collect();
848        let block = PacketReceiptTimesReportBlock {
849            t,
850            ssrc,
851            begin_seq: begin as u16,
852            end_seq: end as u16,
853            receipt_time,
854        };
855        if block.marshal_size() <= limit || t == 15 {
856            return block;
857        }
858        t += 1;
859    }
860}
861
862impl Protocol<TaggedPacket, TaggedPacket, ()> for XrReportInterceptor {
863    type Rout = TaggedPacket;
864    type Wout = TaggedPacket;
865    type Eout = ();
866    type Error = Error;
867    type Time = Instant;
868
869    fn handle_read(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
870        if let Some(RtcpSessionEvent::RoundTripTime { rtt, .. }) =
871            msg.message.custom::<RtcpSessionEvent>()
872        {
873            self.round_trip = Some(*rtt);
874        }
875        if let Packet::Rtp(packet) = &msg.message.packet
876            && let Some(stream) = self.streams.get_mut(&packet.header.ssrc)
877        {
878            if let Some(level) = stream
879                .audio_level_id
880                .and_then(|id| packet.header.get_extension(id))
881                .and_then(|value| {
882                    use shared::marshal::Unmarshal;
883                    rtp::extension::audio_level_extension::AudioLevelExtension::unmarshal(
884                        &mut value.as_ref(),
885                    )
886                    .ok()
887                })
888            {
889                stream.on_audio_level(level.level, level.voice);
890            }
891            stream.on_packet(
892                msg.now,
893                packet.header.sequence_number,
894                packet.header.timestamp,
895            );
896            self.arm(msg.now);
897        }
898        self.read_queue.push_back(msg);
899        Ok(())
900    }
901
902    fn poll_read(&mut self) -> Option<Self::Rout> {
903        self.read_queue.pop_front()
904    }
905
906    fn handle_write(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
907        self.write_queue.push_back(msg);
908        Ok(())
909    }
910
911    fn poll_write(&mut self) -> Option<Self::Wout> {
912        self.write_queue.pop_front()
913    }
914
915    fn handle_timeout(&mut self, now: Instant) -> Result<(), Self::Error> {
916        let Some(due) = self.next_timeout else {
917            return Ok(());
918        };
919        if now < due {
920            return Ok(());
921        }
922        self.next_timeout = Some(now + self.interval);
923        let mut ssrcs: Vec<u32> = self.streams.keys().copied().collect();
924        ssrcs.sort_unstable();
925        let mut reports: Vec<Box<dyn rtcp::Packet>> = vec![];
926        for ssrc in ssrcs {
927            reports.extend(self.blocks(ssrc));
928        }
929        if !reports.is_empty() {
930            let report = ExtendedReport {
931                sender_ssrc: self.sender_ssrc(),
932                reports,
933            };
934            self.write_queue.push_back(TaggedPacket {
935                now,
936                transport: TransportContext::default(),
937                message: AttributedPacket::new(Packet::Rtcp(vec![Box::new(report)])),
938            });
939        }
940        Ok(())
941    }
942
943    fn poll_timeout(&mut self) -> Option<Self::Time> {
944        self.next_timeout
945    }
946}
947
948impl Interceptor for XrReportInterceptor {
949    /// A remote stream is reported on when it negotiated at least one unilateral XR format
950    /// (or the builder named some for every stream).
951    fn bind_remote_stream(&mut self, info: &StreamInfo) {
952        let formats = self
953            .formats
954            .clone()
955            .unwrap_or_else(|| XrFormats::of_stream(info));
956        if formats.any() {
957            let mut stream = RemoteStream::new(formats, info.clock_rate, self.gmin);
958            stream.audio_level_id = info
959                .rtp_header_extensions
960                .iter()
961                .find(|ext| ext.uri == rtp::extension::AUDIO_LEVEL_URI)
962                .and_then(|ext| u8::try_from(ext.id).ok())
963                .filter(|id| *id != 0);
964            self.streams.insert(info.ssrc, stream);
965        }
966    }
967
968    fn unbind_remote_stream(&mut self, info: &StreamInfo) {
969        self.streams.remove(&info.ssrc);
970        if self.streams.is_empty() {
971            self.next_timeout = None;
972        }
973    }
974
975    fn bind_local_stream(&mut self, info: &StreamInfo) {
976        if !self.local_ssrcs.contains(&info.ssrc) {
977            self.local_ssrcs.push(info.ssrc);
978        }
979    }
980
981    fn unbind_local_stream(&mut self, info: &StreamInfo) {
982        self.local_ssrcs.retain(|ssrc| *ssrc != info.ssrc);
983    }
984}
985
986#[cfg(test)]
987mod xr_test;