Skip to main content

rtci_interceptor/report/
sender.rs

1//! Sender Report Interceptor - Filters hop-by-hop RTCP feedback.
2
3use super::sender_stream::SenderStream;
4use crate::Interceptor;
5use crate::stream_info::StreamInfo;
6use crate::{AttributedPacket, Packet, TaggedPacket};
7use rtcp::header::PacketType;
8use sansio::Protocol;
9use shared::TransportContext;
10use shared::error::Error;
11use shared::time::SystemInstant;
12use std::collections::{HashMap, VecDeque};
13use std::time::{Duration, Instant};
14
15/// Builder for the SenderReportInterceptor.
16///
17/// # Example
18///
19/// ```
20/// use rtci_interceptor::{Slot, Registry, SenderReportBuilder};
21/// use std::time::Duration;
22///
23/// // With default interval (1 second)
24/// let chain = Registry::new()
25///     .with(Slot::SenderReport, SenderReportBuilder::new().build())
26///     .build();
27///
28/// // With custom interval
29/// let chain = Registry::new()
30///     .with(Slot::SenderReport, SenderReportBuilder::new().with_interval(Duration::from_millis(500)).build())
31///     .build();
32///
33/// // With use_latest_packet enabled
34/// let chain = Registry::new()
35///     .with(Slot::SenderReport, SenderReportBuilder::new().with_use_latest_packet().build())
36///     .build();
37/// ```
38pub struct SenderReportBuilder {
39    /// Interval between sender reports.
40    interval: Duration,
41    /// Whether to always use the latest packet, even if out-of-order.
42    use_latest_packet: bool,
43    /// The wall-clock anchor NTP times derive from (`None`: the process-wide one).
44    wall_clock: Option<SystemInstant>,
45}
46
47impl Default for SenderReportBuilder {
48    fn default() -> Self {
49        Self {
50            interval: Duration::from_secs(1),
51            use_latest_packet: false,
52            wall_clock: None,
53        }
54    }
55}
56
57impl SenderReportBuilder {
58    /// Create a new builder with default settings.
59    ///
60    /// Default interval is 1 second.
61    pub fn new() -> Self {
62        Self::default()
63    }
64
65    /// Set a custom interval between sender reports.
66    ///
67    /// # Example
68    ///
69    /// ```
70    /// use rtci_interceptor::{Registry, SenderReportBuilder, Slot};
71    /// use std::time::Duration;
72    ///
73    /// let registry = Registry::new().with(
74    ///     Slot::SenderReport,
75    ///     SenderReportBuilder::new()
76    ///         .with_interval(Duration::from_millis(500))
77    ///         .build(),
78    /// );
79    /// ```
80    pub fn with_interval(mut self, interval: Duration) -> Self {
81        self.interval = interval;
82        self
83    }
84
85    /// Enable always using the latest packet for timestamp tracking,
86    /// even if it appears to be out-of-order based on sequence numbers.
87    ///
88    /// By default (disabled), only in-order packets update the RTP↔NTP
89    /// timestamp correlation. This prevents out-of-order packets from
90    /// corrupting the timestamp mapping.
91    ///
92    /// Enable this option when:
93    /// - Packets are guaranteed to arrive in order
94    /// - The application reorders packets before the interceptor
95    /// - You want the sender report to always reflect the most recent packet
96    ///
97    /// # Example
98    ///
99    /// ```
100    /// use rtci_interceptor::{Slot, Registry, SenderReportBuilder};
101    ///
102    /// let registry =
103    ///     Registry::new().with(Slot::SenderReport, SenderReportBuilder::new().with_use_latest_packet().build());
104    /// ```
105    pub fn with_use_latest_packet(mut self) -> Self {
106        self.use_latest_packet = true;
107        self
108    }
109
110    /// The wall-clock anchor the sender reports' NTP times derive from. Default: the
111    /// process-wide [`SystemInstant::shared`]. Give one per peer connection for reproducible
112    /// virtual-time runs: two runs in one process otherwise map the same instants to NTP times
113    /// as far apart as the real time between them.
114    pub fn with_wall_clock(mut self, anchor: SystemInstant) -> Self {
115        self.wall_clock = Some(anchor);
116        self
117    }
118
119    /// Create a builder function for use with Registry.
120    ///
121    /// This returns a closure that can be passed to `Registry::with()`.
122    ///
123    /// # Example
124    ///
125    /// ```
126    /// use rtci_interceptor::{Slot, Registry, SenderReportBuilder};
127    ///
128    /// let registry = Registry::new()
129    ///     .with(Slot::SenderReport, SenderReportBuilder::new().build());
130    /// ```
131    pub fn build(self) -> SenderReportInterceptor {
132        let mut interceptor = SenderReportInterceptor::new(self.interval, self.use_latest_packet);
133        interceptor.wall_clock = self.wall_clock;
134        interceptor
135    }
136}
137
138/// The most receiver reference times held for answering at once.
139const MAX_REFERENCE_TIMES: usize = 64;
140
141/// A stream unbound since the chain was last polled.
142struct Departing {
143    ssrc: u32,
144    stream: SenderStream,
145    /// Its final sender report and BYE, if it ever sent.
146    goodbye: Option<TaggedPacket>,
147}
148
149/// Interceptor that filters hop-by-hop RTCP reports.
150///
151/// This interceptor filters out RTCP Receiver Reports and Transport-Specific
152/// Feedback, which are hop-by-hop reports that should not be forwarded
153/// end-to-end.
154///
155/// # Type Parameters
156///
157/// - `P`: The inner protocol being wrapped
158///
159/// # Example
160///
161/// ```
162/// use rtci_interceptor::{Slot, Registry, SenderReportBuilder};
163///
164/// let chain = Registry::new()
165///     .with(Slot::SenderReport, SenderReportBuilder::new().build())
166///     .build();
167/// ```
168pub struct SenderReportInterceptor {
169    interval: Duration,
170    next_timeout: Option<Instant>,
171
172    /// Whether to always use the latest packet, even if out-of-order.
173    use_latest_packet: bool,
174
175    /// [`SenderReportBuilder::with_wall_clock`].
176    wall_clock: Option<SystemInstant>,
177
178    streams: HashMap<u32, SenderStream>,
179
180    /// The latest instant handed in, for stamping the goodbye of a stream unbound without one.
181    last_now: Option<Instant>,
182
183    /// The receiver reference times (RFC 3611 section 4.4) received since the last sender
184    /// reports went out, by the SSRC they came from: the compact NTP timestamp and when it
185    /// arrived. Answered with a DLRR block (section 4.5) in the next sender report's compound
186    /// packet, as libwebrtc does whether or not anything was negotiated.
187    reference_times: HashMap<u32, (u32, Instant)>,
188
189    /// Streams unbound since the chain was last polled, with the goodbye each says. A stream
190    /// bound again with the same SSRC before then (a renegotiation re-binding it with a new
191    /// codec) takes its state back and says no goodbye: it goes on.
192    departing: Vec<Departing>,
193
194    read_queue: VecDeque<TaggedPacket>,
195    write_queue: VecDeque<TaggedPacket>,
196}
197
198impl SenderReportInterceptor {
199    /// Create a new SenderReportInterceptor.
200    fn new(interval: Duration, use_latest_packet: bool) -> Self {
201        Self {
202            interval,
203            next_timeout: None,
204
205            use_latest_packet,
206
207            wall_clock: None,
208
209            streams: HashMap::new(),
210
211            last_now: None,
212
213            departing: Vec::new(),
214
215            reference_times: HashMap::new(),
216
217            read_queue: VecDeque::new(),
218            write_queue: VecDeque::new(),
219        }
220    }
221
222    /// Queues the goodbye of every stream that was unbound and not bound again.
223    fn flush_departing(&mut self) {
224        for departing in self.departing.drain(..) {
225            if let Some(goodbye) = departing.goodbye {
226                self.write_queue.push_back(goodbye);
227            }
228        }
229    }
230
231    /// Check if an RTCP packet type should be filtered.
232    ///
233    /// Returns `true` for hop-by-hop report types that should not be forwarded:
234    /// - Receiver Report (201)
235    /// - Transport-Specific Feedback (205)
236    fn should_filter(packet_type: PacketType) -> bool {
237        packet_type == PacketType::ReceiverReport
238            || (packet_type == PacketType::TransportSpecificFeedback)
239    }
240}
241
242impl Protocol<TaggedPacket, TaggedPacket, ()> for SenderReportInterceptor {
243    type Rout = TaggedPacket;
244    type Wout = TaggedPacket;
245    type Eout = ();
246    type Error = Error;
247    type Time = Instant;
248
249    fn handle_read(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
250        if let Packet::Rtcp(rtcp_packets) = &msg.message.packet {
251            for packet in rtcp_packets {
252                let Some(xr) = packet
253                    .as_any()
254                    .downcast_ref::<rtcp::extended_report::ExtendedReport>()
255                else {
256                    continue;
257                };
258                for block in &xr.reports {
259                    if let Some(rrtr) = block
260                        .as_any()
261                        .downcast_ref::<rtcp::extended_report::ReceiverReferenceTimeReportBlock>(
262                    ) {
263                        // A remote that sends from many SSRCs is held to a bounded table.
264                        if self.reference_times.len() < MAX_REFERENCE_TIMES
265                            || self.reference_times.contains_key(&xr.sender_ssrc)
266                        {
267                            self.reference_times.insert(
268                                xr.sender_ssrc,
269                                ((rrtr.ntp_timestamp >> 16) as u32, msg.now),
270                            );
271                        }
272                    }
273                }
274            }
275        }
276        self.read_queue.push_back(msg);
277        Ok(())
278    }
279
280    fn poll_read(&mut self) -> Option<Self::Rout> {
281        self.read_queue.pop_front()
282    }
283
284    fn handle_write(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
285        self.flush_departing();
286        self.last_now = Some(self.last_now.map_or(msg.now, |last| last.max(msg.now)));
287        if let Packet::Rtp(rtp_packet) = &msg.message.packet
288            && let Some(stream) = self.streams.get_mut(&rtp_packet.header.ssrc)
289        {
290            stream.process_rtp(msg.now, rtp_packet);
291
292            // Arm the report timer from the first packet's instant (see nack::generator).
293            if self.next_timeout.is_none() {
294                self.next_timeout = Some(msg.now + self.interval);
295            }
296        }
297
298        self.write_queue.push_back(msg);
299
300        Ok(())
301    }
302
303    fn poll_write(&mut self) -> Option<TaggedPacket> {
304        self.flush_departing();
305        // First drain generated RTCP reports
306        if let Some(pkt) = self.write_queue.pop_front() {
307            return Some(pkt);
308        }
309        None
310    }
311
312    fn handle_timeout(&mut self, now: Instant) -> Result<(), Error> {
313        self.flush_departing();
314        self.last_now = Some(self.last_now.map_or(now, |last| last.max(now)));
315        if let Some(next_timeout) = self.next_timeout
316            && now >= next_timeout
317        {
318            self.next_timeout = Some(now + self.interval);
319
320            for stream in self.streams.values_mut() {
321                // RFC 3550 6.4: only a stream that sent during the last two reporting intervals
322                // issues a sender report; a silent one reports nothing from here.
323                if let Some(sr) = stream.generate_regular_report(now) {
324                    let mut compound: Vec<Box<dyn rtcp::Packet>> = vec![Box::new(sr)];
325                    // The DLRR block answers every reference time received since the last
326                    // reports, once, from the first stream that reports (RFC 3611 section 4.5).
327                    if !self.reference_times.is_empty() {
328                        let reports = self
329                            .reference_times
330                            .drain()
331                            .map(
332                                |(ssrc, (last_rr, arrived))| rtcp::extended_report::DLRRReport {
333                                    ssrc,
334                                    last_rr,
335                                    dlrr: (now.saturating_duration_since(arrived).as_secs_f64()
336                                        * 65536.0) as u32,
337                                },
338                            )
339                            .collect();
340                        compound.push(Box::new(rtcp::extended_report::ExtendedReport {
341                            sender_ssrc: stream.ssrc(),
342                            reports: vec![Box::new(rtcp::extended_report::DLRRReportBlock {
343                                reports,
344                            })],
345                        }));
346                    }
347                    self.write_queue.push_back(TaggedPacket {
348                        now,
349                        transport: TransportContext::default(),
350                        message: AttributedPacket::new(Packet::Rtcp(compound)),
351                    });
352                }
353            }
354        }
355        Ok(())
356    }
357
358    fn poll_timeout(&mut self) -> Option<Instant> {
359        self.next_timeout
360    }
361}
362
363impl Interceptor for SenderReportInterceptor {
364    /// A stream unbound a moment ago (since the chain was last polled) and bound again with the
365    /// same SSRC is the same stream re-bound by a renegotiation: it keeps its packet and octet
366    /// counts and RTP / NTP timing, takes the new clock rate, and its goodbye is withdrawn.
367    fn bind_local_stream(&mut self, info: &StreamInfo) {
368        let stream = match self.departing.iter().position(|d| d.ssrc == info.ssrc) {
369            Some(i) => {
370                let mut stream = self.departing.remove(i).stream;
371                stream.set_clock_rate(info.clock_rate);
372                stream
373            }
374            None => SenderStream::new(info.ssrc, info.clock_rate, self.use_latest_packet)
375                .with_wall_clock(self.wall_clock),
376        };
377        self.streams.insert(info.ssrc, stream);
378    }
379
380    /// A stream that sent and is now unbound (its sender stopped) says goodbye: a final sender
381    /// report and an RTCP BYE for its SSRC and its repair flows, in one compound packet
382    /// (RFC 3550 6.6: a BYE follows a report in a compound packet). The goodbye goes out when
383    /// the chain is next polled, unless the stream is bound again first.
384    fn unbind_local_stream(&mut self, info: &StreamInfo) {
385        let Some(mut stream) = self.streams.remove(&info.ssrc) else {
386            return;
387        };
388        let goodbye = match self.last_now {
389            Some(now) if stream.has_sent() => {
390                // RFC 3550 6.4: a sender report only from a stream that sent lately; one that
391                // fell silent leads its goodbye with an empty receiver report instead.
392                let report: Option<Box<dyn rtcp::Packet>> = if stream.is_sender() {
393                    stream
394                        .generate_report(now)
395                        .map(|report| Box::new(report) as Box<dyn rtcp::Packet>)
396                } else {
397                    Some(Box::new(rtcp::receiver_report::ReceiverReport {
398                        ssrc: info.ssrc,
399                        ..Default::default()
400                    }))
401                };
402                report.map(|report| {
403                    let sources = std::iter::once(info.ssrc)
404                        .chain(info.ssrc_rtx)
405                        .chain(info.ssrc_fec)
406                        .collect();
407                    TaggedPacket {
408                        now,
409                        transport: TransportContext::default(),
410                        message: AttributedPacket::new(Packet::Rtcp(vec![
411                            report,
412                            Box::new(rtcp::goodbye::Goodbye {
413                                sources,
414                                reason: Default::default(),
415                            }),
416                        ])),
417                    }
418                })
419            }
420            _ => None,
421        };
422        self.departing.retain(|d| d.ssrc != info.ssrc);
423        self.departing.push(Departing {
424            ssrc: info.ssrc,
425            stream,
426            goodbye,
427        });
428    }
429
430    fn bind_remote_stream(&mut self, _info: &StreamInfo) {}
431
432    fn unbind_remote_stream(&mut self, _info: &StreamInfo) {}
433}