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