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