Skip to main content

rtci_interceptor/rtcp_session/
mod.rs

1//! The RTCP session of an endpoint: who it is, when it speaks and what a packet looks like.
2//!
3//! See [`RtcpSessionInterceptor`].
4
5mod ecn;
6pub(crate) mod identity;
7pub(crate) mod scheduler;
8
9use crate::report::receiver_stream::ReceiverStream;
10use crate::report::sender_stream::SenderStream;
11use crate::stream_info::StreamInfo;
12use crate::{Attribute, AttributedPacket, Interceptor, Packet, TaggedPacket};
13use identity::{RtcpRandom, SharedRandom, ThreadRandom, choose_ssrc, generate_cname};
14use rtcp::extended_report::{
15    DLRRReport, DLRRReportBlock, EcnSummaryReport, EcnSummaryReportBlock, ExtendedReport,
16    ReceiverReferenceTimeReportBlock,
17};
18use rtcp::goodbye::Goodbye;
19use rtcp::payload_feedbacks::full_intra_request::FullIntraRequest;
20use rtcp::payload_feedbacks::picture_loss_indication::PictureLossIndication;
21use rtcp::payload_feedbacks::receiver_estimated_maximum_bitrate::ReceiverEstimatedMaximumBitrate;
22use rtcp::payload_feedbacks::slice_loss_indication::SliceLossIndication;
23use rtcp::payload_feedbacks::temporal_spatial_tradeoff::{
24    TemporalSpatialTradeoffNotification, TemporalSpatialTradeoffRequest,
25};
26use rtcp::receiver_report::ReceiverReport;
27use rtcp::reception_report::ReceptionReport;
28use rtcp::sender_report::SenderReport;
29use rtcp::source_description::{
30    SdesType, SourceDescription, SourceDescriptionChunk, SourceDescriptionItem,
31};
32use rtcp::transport_feedbacks::cc_feedback_report::CcFeedbackReport;
33use rtcp::transport_feedbacks::ecn_feedback::EcnFeedback;
34use rtcp::transport_feedbacks::rapid_resynchronization_request::RapidResynchronizationRequest;
35use rtcp::transport_feedbacks::transport_layer_cc::TransportLayerCc;
36use rtcp::transport_feedbacks::transport_layer_nack::{
37    TransportLayerNack, nack_pairs_from_sequence_numbers,
38};
39use sansio::Protocol;
40use scheduler::{
41    BYE_BACKOFF_MEMBERS, IntervalInput, LOWER_LAYER_OVERHEAD, RTCP_BW_FRACTION, RTCP_MIN_TIME,
42    RTCP_SENDER_BW_FRACTION, RegularDecision, TIMEOUT_MULTIPLIER, Timing, after,
43    deterministic_interval, randomized_interval, reduced_minimum, regular_decision,
44    seconds_between, update_avg_rtcp_size,
45};
46use shared::TransportContext;
47use shared::error::Error;
48use shared::marshal::MarshalSize;
49use shared::time::SystemInstant;
50use std::collections::{HashMap, HashSet, VecDeque};
51use std::sync::Arc;
52use std::time::{Duration, Instant};
53
54/// The session bandwidth assumed while none is configured and no media has been measured:
55/// one audio stream.
56pub const RTCP_SESSION_MIN_BANDWIDTH: u64 = 64_000;
57/// The session bandwidth assumed for video at the start, while no `b=` line gave one and the
58/// media has not yet had its two seconds to be measured: 1 Mbit/s, a camera stream at
59/// standard definition.
60///
61/// RFC 3550 section 6.2 takes the RTCP bandwidth as a share of the session bandwidth, which
62/// it lets "a session management application" supply; without one the session measures the
63/// media, both ways, over the last two seconds (64 kbit/s at least). Before there is anything
64/// to measure, this start-up value (with [`RTCP_SESSION_NOMINAL_AUDIO_BANDWIDTH`] for audio)
65/// stands in, so the first reports are not held to an idle session's share. Congestion
66/// control feedback does not depend on it: it follows the media it reports on
67/// ([`RtcpSessionBuilder::with_immediate_congestion_feedback`]).
68pub const RTCP_SESSION_NOMINAL_VIDEO_BANDWIDTH: u64 = 1_000_000;
69/// The session bandwidth assumed for audio while none was signalled: 64 kbit/s, an Opus
70/// stream at its high end for speech and the floor the session has always had.
71pub const RTCP_SESSION_NOMINAL_AUDIO_BANDWIDTH: u64 = RTCP_SESSION_MIN_BANDWIDTH;
72
73/// The nominal session bandwidth of a session that carries video and / or audio, bits per
74/// second (see [`RTCP_SESSION_NOMINAL_VIDEO_BANDWIDTH`]).
75pub(crate) fn nominal_session_bandwidth(video: bool, audio: bool) -> f64 {
76    let mut nominal = 0;
77    if video {
78        nominal += RTCP_SESSION_NOMINAL_VIDEO_BANDWIDTH;
79    }
80    if audio {
81        nominal += RTCP_SESSION_NOMINAL_AUDIO_BANDWIDTH;
82    }
83    nominal.max(RTCP_SESSION_MIN_BANDWIDTH) as f64
84}
85
86/// The default of [`RtcpSessionBuilder::with_t_rr_interval`].
87pub const RTCP_SESSION_DEFAULT_T_RR_INTERVAL: Duration = Duration::from_secs(1);
88/// The default of [`RtcpSessionBuilder::with_mtu`]: the size a compound RTCP packet is kept
89/// under, SRTCP and lower layers not counted.
90pub const RTCP_SESSION_DEFAULT_MTU: usize = 1200;
91
92/// The most sources the member table holds; RTCP from further unknown SSRCs is not counted.
93const MAX_MEMBERS: usize = 1024;
94/// The most feedback and other packets held for the next compound packet.
95const MAX_PENDING: usize = 64;
96/// The most receiver reference times held for answering at once.
97const MAX_REFERENCE_TIMES: usize = 64;
98/// The most timer expiries worked through in one call: a session left alone for long catches
99/// up to here and starts over from the present.
100const MAX_CATCH_UP: usize = 4096;
101/// The window the media bitrate is measured over when no session bandwidth is configured.
102const RATE_WINDOW: Duration = Duration::from_secs(2);
103/// The size of one bucket of that window.
104const RATE_BUCKET: Duration = Duration::from_millis(250);
105/// RFC 5506 4.2.2: a feedback packet larger than this goes out compound, not reduced-size.
106const REDUCED_SIZE_MAX: usize = 400;
107/// RFC 5506 4.2.1: this many reduced-size NACK packets in a row with none of the packets
108/// they asked for arriving, and the session falls back to compound packets.
109const REDUCED_SIZE_UNANSWERED_LIMIT: u32 = 8;
110/// The most report blocks one SR or RR carries (RFC 3550 6.4.1: RC is five bits).
111const MAX_REPORT_BLOCKS: usize = 31;
112
113/// The fraction lost (in 1/256: about 10%) from which a stream's report goes before the round
114/// robin when not every report fits (RFC 8083 section 4.3).
115const HIGH_LOSS_FRACTION: u8 = 26;
116/// The longest `T_rr_interval` the RTCP bandwidth left over by congestion control feedback
117/// stretches the regular reports to ([`RtcpSessionBuilder::with_congestion_feedback_in_budget`]),
118/// seconds: RFC 4585 section 5 (interworking with AVP) has `T_rr_interval` "SHOULD NOT be larger
119/// than five seconds" where RTP/AVP entities may take part.
120const MAX_BUDGET_T_RR_INTERVAL: f64 = 5.0;
121
122/// The least interval the session computes, in seconds. RTP/AVPF has no minimum for a
123/// point-to-point session (RFC 4585 3.5.1), so with enough bandwidth the calculated interval
124/// tends to nothing; a timer cannot.
125const MIN_INTERVAL: f64 = 0.005;
126
127/// The RTP profile whose RTCP timing rules apply.
128#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
129pub enum RtcpProfile {
130    /// RTP/AVP and RTP/SAVP (RFC 3551): a five second minimum interval, no early feedback.
131    Avp,
132    /// RTP/AVPF and RTP/SAVPF (RFC 4585): early feedback, `T_rr_interval`. What WebRTC uses.
133    #[default]
134    Avpf,
135}
136
137/// The bandwidth figures a session description gives for RTCP, all in bits per second.
138#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
139pub struct RtcpBandwidth {
140    /// The session bandwidth (`b=TIAS`, or `b=AS` times 1000). RTCP gets 5% of it unless
141    /// `rs` and `rr` say otherwise. `None`: the media bitrate measured over the last two
142    /// seconds, with a start-up value before that ([`RTCP_SESSION_NOMINAL_VIDEO_BANDWIDTH`]).
143    pub session: Option<u64>,
144    /// `b=RS` (RFC 3556): the RTCP bandwidth of the senders.
145    pub rs: Option<u64>,
146    /// `b=RR` (RFC 3556): the RTCP bandwidth of the receivers.
147    pub rr: Option<u64>,
148}
149
150/// What an application (or the peer connection) tells the session while it runs.
151///
152/// It travels as an [`Attribute::Custom`] on an empty RTCP packet written into the chain
153/// ([`RtcpSessionControl::into_packet`]); the session takes it off the belt.
154#[derive(Debug, Clone, PartialEq, Eq)]
155#[non_exhaustive]
156pub enum RtcpSessionControl {
157    /// The transport is up: the session joins now, without waiting for a first packet.
158    Start,
159    /// The CNAME of this endpoint, the one its session description announces.
160    Cname(String),
161    /// The negotiated bandwidth (`b=` lines).
162    Bandwidth(RtcpBandwidth),
163    /// Whether reduced-size RTCP (`a=rtcp-rsize`, RFC 5506) was negotiated.
164    ReducedSize(bool),
165    /// The octets SRTCP adds to every compound packet: the E flag and SRTCP index, the
166    /// authentication tag and the MKI. RFC 3711 section 3.4: they are part of the packet size
167    /// avg_rtcp_size is computed from, the initial estimate included. Give it before
168    /// [`Self::Start`]; 0 (the default) for plain RTCP.
169    SrtcpOverhead(usize),
170    /// The negotiated `trr-int` (RFC 4585 4.2), the minimum interval between regular reports.
171    TrrInt(Duration),
172    /// The negotiation has no `trr-int` (any more): the interval the session was built with
173    /// ([`RtcpSessionBuilder::with_t_rr_interval`]) applies again.
174    TrrIntCleared,
175    /// The endpoint leaves the session: every local SSRC says BYE.
176    Leave,
177    /// What identifies the local stream `ssrc` beyond the CNAME: the identification-tag of
178    /// its m= section (RFC 9143 section 15.1, SDES `MID`), its RtpStreamId (RFC 8852 section
179    /// 3.1) and, for a redundancy stream (RTX, FEC), the RepairedRtpStreamId of the stream it
180    /// repairs (section 3.2). Each given value is an item of the SSRC's SDES chunk in every
181    /// compound packet: RFC 9143 section 15 wants the MID "in the first few RTCP packets after
182    /// joining the session and ... regularly thereafter". All `None` forgets the SSRC's items;
183    /// the items of an SSRC that is no longer bound go when the next ones are given.
184    StreamIdentifiers {
185        /// The local SSRC.
186        ssrc: u32,
187        /// The m= section's `a=mid`.
188        mid: Option<String>,
189        /// The RtpStreamId (the encoding's rid).
190        rid: Option<String>,
191        /// The RepairedRtpStreamId (the rid of the stream a redundancy stream repairs).
192        repaired_rid: Option<String>,
193    },
194    /// RFC 7160 section 4.1: the local stream `current` took over from the streams `previous`
195    /// because the sender switched to another clock rate (each clock rate has an SSRC of its
196    /// own). The next compound packet "MUST contain multiple SR packets, the first one
197    /// containing the mapping for the current clock rate and the subsequent SR packet(s)
198    /// containing the mapping for the other clock rates seen during the last period": it
199    /// leads with `current`'s report, followed by those of the `previous` streams that sent
200    /// lately.
201    ClockRateSwitch {
202        /// The SSRC of the clock rate now in use.
203        current: u32,
204        /// The SSRCs of the other clock rates the stream was sent with, still in the session.
205        previous: Vec<u32>,
206    },
207    /// Stops the repetitions of the packets written with the [`RepeatInRegularReports`] of
208    /// this `key` that are still owed (RFC 7728 section 6.4: "stopping such repetition
209    /// whenever leaving the state").
210    StopRepeating {
211        /// The key the packets were written with.
212        key: u32,
213    },
214}
215
216/// Attached as an [`Attribute::Custom`] to RTCP packets written into the chain: besides
217/// sending them as it sends any feedback (in an Early packet when RFC 4585 3.5.2 allows one,
218/// in the next Regular packet otherwise), the RTCP session puts a copy of them into each of
219/// the next `count` **Regular** compound packets after the one that carried them.
220///
221/// RFC 7728 section 6.3 has a paused sender "repeat PAUSED in the next two regular RTCP
222/// reports" (section 8.2: "PAUSED MUST also be included in (at least) the next two regular
223/// RTCP reports"); the session is what knows when a regular report leaves. Packets written
224/// again with the same `key` replace the repetitions still owed for it, and
225/// [`RtcpSessionControl::StopRepeating`] ends them.
226#[derive(Debug, Clone, Copy, PartialEq, Eq)]
227pub struct RepeatInRegularReports {
228    /// Groups the repetitions, for replacing or stopping them (e.g. the media SSRC the
229    /// packets are about).
230    pub key: u32,
231    /// In how many Regular compound packets after the first one they ride again.
232    pub count: u8,
233}
234
235/// Packets the RTCP session repeats in its Regular compound packets.
236struct Repeat {
237    key: u32,
238    packets: Vec<Box<dyn rtcp::Packet>>,
239    left: u8,
240    /// Whether the compound packet that carried the original has left: only Regular packets
241    /// after it carry a copy.
242    armed: bool,
243}
244
245impl RtcpSessionControl {
246    /// The packet that carries this to the session when written into the chain at `now`.
247    pub fn into_packet(self, now: Instant) -> TaggedPacket {
248        TaggedPacket {
249            now,
250            transport: TransportContext::default(),
251            message: AttributedPacket::new(Packet::Rtcp(vec![]))
252                .with(Attribute::Custom(Arc::new(self))),
253        }
254    }
255}
256
257/// What the session tells the rest of the chain and the peer connection.
258///
259/// It travels application-ward as an [`Attribute::Custom`] on an empty RTCP packet; read it
260/// with [`AttributedPacket::custom`].
261#[derive(Debug, Clone, PartialEq, Eq)]
262#[non_exhaustive]
263pub enum RtcpSessionEvent {
264    /// RFC 3550 8.2: a packet arrived from another source that uses `ssrc`, one of this
265    /// endpoint's own. `replacement` is an SSRC no known source uses, for the stream to move
266    /// to; a reporting SSRC the session chose itself has already moved.
267    SsrcCollision {
268        /// The local SSRC another source uses too.
269        ssrc: u32,
270        /// An unused SSRC to replace it with.
271        replacement: u32,
272    },
273    /// RFC 3550 6.5.1: the remote source `ssrc` named its CNAME (or changed it).
274    RemoteCname {
275        /// The remote SSRC.
276        ssrc: u32,
277        /// Its canonical name.
278        cname: String,
279    },
280    /// RFC 3550 6.3.5: nothing was heard from the remote source for five report intervals.
281    SourceTimedOut {
282        /// The remote SSRC.
283        ssrc: u32,
284    },
285    /// RFC 3550 6.4.1: the round-trip time to the receiver that reported on the local `ssrc`.
286    RoundTripTime {
287        /// The local SSRC the report block was about.
288        ssrc: u32,
289        /// The round trip.
290        rtt: Duration,
291    },
292}
293
294/// Builder for [`RtcpSessionInterceptor`].
295///
296/// ```
297/// use rtci_interceptor::{Registry, RtcpSessionBuilder, Slot};
298///
299/// let chain = Registry::new()
300///     .with(Slot::RtcpSession, RtcpSessionBuilder::new().build())
301///     .build();
302/// # let _ = chain;
303/// ```
304pub struct RtcpSessionBuilder {
305    profile: RtcpProfile,
306    t_rr_interval: Duration,
307    bandwidth: RtcpBandwidth,
308    rtcp_fraction: f64,
309    reduced_minimum: bool,
310    reduced_size: bool,
311    mtu: usize,
312    cname: Option<String>,
313    point_to_point: Option<bool>,
314    report_from_every_ssrc: bool,
315    immediate_congestion_feedback: bool,
316    congestion_feedback_in_budget: bool,
317    minimum_session_bandwidth: u64,
318    joins_on_start: bool,
319    first_report_at_join: bool,
320    random: Box<dyn RtcpRandom>,
321    wall_clock: Option<SystemInstant>,
322}
323
324impl Default for RtcpSessionBuilder {
325    fn default() -> Self {
326        Self {
327            profile: RtcpProfile::default(),
328            t_rr_interval: RTCP_SESSION_DEFAULT_T_RR_INTERVAL,
329            bandwidth: RtcpBandwidth::default(),
330            rtcp_fraction: RTCP_BW_FRACTION,
331            reduced_minimum: false,
332            reduced_size: false,
333            mtu: RTCP_SESSION_DEFAULT_MTU,
334            cname: None,
335            point_to_point: None,
336            report_from_every_ssrc: false,
337            immediate_congestion_feedback: true,
338            congestion_feedback_in_budget: false,
339            minimum_session_bandwidth: RTCP_SESSION_MIN_BANDWIDTH,
340            joins_on_start: false,
341            first_report_at_join: false,
342            random: Box::new(ThreadRandom),
343            wall_clock: None,
344        }
345    }
346}
347
348impl RtcpSessionBuilder {
349    /// A builder with the defaults: RTP/AVPF timing, a `T_rr_interval` of one second, RTCP at
350    /// 5% of the measured media bitrate (a start-up value before it is measured), compound
351    /// packets only, congestion control feedback sent as it is built.
352    pub fn new() -> Self {
353        Self::default()
354    }
355
356    /// The profile whose timing rules apply. Default: [`RtcpProfile::Avpf`].
357    pub fn with_profile(mut self, profile: RtcpProfile) -> Self {
358        self.profile = profile;
359        self
360    }
361
362    /// `T_rr_interval` (RFC 4585 3.4): the minimum interval between regular (full compound)
363    /// reports under RTP/AVPF. Feedback is not held by it.
364    ///
365    /// RFC 4585 4.2 makes the value zero when `trr-int` is not negotiated, which lets regular
366    /// reports use the whole RTCP bandwidth: a report every few tens of milliseconds beside a
367    /// video stream. The default here is one second (what this engine sent before, and what
368    /// browsers send); a negotiated `trr-int` ([`RtcpSessionControl::TrrInt`]) replaces it,
369    /// and zero gives the RFC's default.
370    pub fn with_t_rr_interval(mut self, t_rr_interval: Duration) -> Self {
371        self.t_rr_interval = t_rr_interval;
372        self
373    }
374
375    /// The bandwidth the session description gives (`b=AS` / `b=TIAS`, `b=RS`, `b=RR`).
376    /// Default: none, so the media bitrate is measured and RTCP gets 5% of it.
377    pub fn with_bandwidth(mut self, bandwidth: RtcpBandwidth) -> Self {
378        self.bandwidth = bandwidth;
379        self
380    }
381
382    /// The share of the session bandwidth RTCP uses when `b=RS` / `b=RR` do not say. Default:
383    /// 0.05, the value RFC 3550 6.2 recommends.
384    pub fn with_rtcp_fraction(mut self, fraction: f64) -> Self {
385        self.rtcp_fraction = fraction.clamp(0.0, 1.0);
386        self
387    }
388
389    /// Under RTP/AVP, use the reduced minimum interval of RFC 3550 6.2 (360 divided by the
390    /// session bandwidth in kbit/s) instead of five seconds.
391    pub fn with_reduced_minimum(mut self, reduced_minimum: bool) -> Self {
392        self.reduced_minimum = reduced_minimum;
393        self
394    }
395
396    /// Whether reduced-size RTCP (RFC 5506) was negotiated. Default: no, every packet is a
397    /// compound packet.
398    pub fn with_reduced_size(mut self, reduced_size: bool) -> Self {
399        self.reduced_size = reduced_size;
400        self
401    }
402
403    /// The size compound packets are kept under (RFC 3550 6.1). Default:
404    /// [`RTCP_SESSION_DEFAULT_MTU`].
405    pub fn with_mtu(mut self, mtu: usize) -> Self {
406        self.mtu = mtu.max(128);
407        self
408    }
409
410    /// The CNAME to use. Default: one generated as RFC 7022 section 4.2 describes.
411    pub fn with_cname(mut self, cname: impl Into<String>) -> Self {
412        self.cname = Some(cname.into());
413        self
414    }
415
416    /// Says whether the session is point to point instead of leaving it to the count of
417    /// remote CNAMEs (RFC 8108 5.4.2: "unless signaling indicates").
418    pub fn with_point_to_point(mut self, point_to_point: bool) -> Self {
419        self.point_to_point = Some(point_to_point);
420        self
421    }
422
423    /// RFC 8108 5.1 to the letter: every local SSRC carries a report block for every remote
424    /// SSRC. Default: off, the blocks are carried once, by the first local media SSRC (what
425    /// browsers do, and what RFC 8861 reporting groups exist to allow).
426    pub fn with_report_from_every_ssrc(mut self, every: bool) -> Self {
427        self.report_from_every_ssrc = every;
428        self
429    }
430
431    /// Whether congestion control feedback (transport-wide feedback, RFC 8888 reports) leaves
432    /// as soon as its generator writes it (the default), or waits its turn under RFC 4585
433    /// section 3.5.2 like other feedback: at most one Early packet per regular interval.
434    ///
435    /// The generators size their own cadence to 5% of the media they report on, between 50
436    /// and 250 ms (`TwccReceiverBuilder::with_adaptive_interval`): congestion control feedback
437    /// is the sender's congestion signal and is not held to the RTCP bandwidth the regular
438    /// reports share, as libwebrtc and the browsers send it. It goes as a reduced-size packet
439    /// where `a=rtcp-rsize` was negotiated, else in a minimal compound packet, and does not
440    /// move the regular reports' timing. `false` is RFC 4585 as written: at low media rates
441    /// the session then sends feedback a few times a second, with gaps a sender's estimator
442    /// does not climb through.
443    pub fn with_immediate_congestion_feedback(mut self, immediate: bool) -> Self {
444        self.immediate_congestion_feedback = immediate;
445        self
446    }
447
448    /// Whether the congestion control feedback that leaves at once
449    /// ([`Self::with_immediate_congestion_feedback`]) counts against the RTCP bandwidth the
450    /// regular reports share (`true`), or comes on top of it (`false`, the default).
451    ///
452    /// With `true` the session measures the congestion control feedback it sends and receives
453    /// over the last two seconds, and spaces its regular reports so that they and the
454    /// feedback together stay inside the RTCP bandwidth (RFC 3550 section 6.2: 5% of the
455    /// session bandwidth): the regular interval computed with what the feedback leaves becomes
456    /// a `T_rr_interval` (RFC 4585 section 3.5.3, which suppresses regular reports inside it
457    /// and lets feedback through), no longer than five seconds. Regular reports become rarer
458    /// at low media rates and nothing else changes. Part of the `Performance` behaviour
459    /// profile.
460    pub fn with_congestion_feedback_in_budget(mut self, in_budget: bool) -> Self {
461        self.congestion_feedback_in_budget = in_budget;
462        self
463    }
464
465    /// The least session bandwidth the RTCP bandwidth is computed from when no `b=` line gives
466    /// one and the media is measured, bits per second. Default
467    /// [`RTCP_SESSION_MIN_BANDWIDTH`] (64 kbit/s). Below it the measured media rate is not
468    /// used, so a 24 kbit/s audio call reports as a 64 kbit/s one would (RFC 3550 section 6.2
469    /// lets the session bandwidth be the expected one). The `Performance` behaviour profile
470    /// takes 16 kbit/s, so the RTCP bandwidth follows the media down to there. Held to at
471    /// least 8 kbit/s, so a session with no media still reports.
472    pub fn with_minimum_session_bandwidth(mut self, bits_per_second: u64) -> Self {
473        self.minimum_session_bandwidth = bits_per_second.max(8_000);
474        self
475    }
476
477    /// Whether the session joins only when told [`RtcpSessionControl::Start`] (`true`), or at
478    /// the first control, packet or stream it is given (`false`, the default).
479    ///
480    /// RFC 3550 section 6: RTCP is the control protocol of an RTP session, and there is none
481    /// until an RTP m= section is negotiated (RFC 8834 section 4.1). A peer connection knows
482    /// when that is, per transport, and joins the session then; with `true` nothing else makes
483    /// it join: until `Start` it sends nothing (no report, no SDES, no SSRC of its own), and
484    /// what is written to it as RTCP is dropped. After [`RtcpSessionControl::Leave`], a
485    /// `Start` joins it again (RTCP resumes from a new reporting SSRC).
486    pub fn with_joins_on_start(mut self, joins_on_start: bool) -> Self {
487        self.joins_on_start = joins_on_start;
488        self
489    }
490
491    /// Whether the first compound packet goes out when the session joins (`true`), or after
492    /// the initial interval of RFC 3550 section 6.2 (`false`, the default).
493    ///
494    /// RFC 8834 section 4.1, with RFC 3550 section 6.2 as RFC 8108 updates it: "The delay
495    /// before sending the initial compound RTCP packet can be set to zero." A peer connection
496    /// joins a transport's session when its keys exist, and reporting then tells the peer the
497    /// endpoint's SSRCs at once (RFC 3550 section 8.2: an SSRC collision is found from the
498    /// first packet that shows it) and starts the round-trip and loss reports congestion
499    /// control reads.
500    pub fn with_first_report_at_join(mut self, at_join: bool) -> Self {
501        self.first_report_at_join = at_join;
502        self
503    }
504
505    /// The source of the session's random numbers; a test supplies one that repeats.
506    pub fn with_random(mut self, random: impl RtcpRandom + 'static) -> Self {
507        self.random = Box::new(random);
508        self
509    }
510
511    /// The wall-clock anchor the session's NTP times (sender reports, XR receiver reference
512    /// times) derive from. Default: the process-wide [`SystemInstant::shared`]. Give one per
513    /// peer connection for reproducible virtual-time runs: two runs in one process otherwise
514    /// map the same instants to NTP times as far apart as the real time between them.
515    pub fn with_wall_clock(mut self, anchor: SystemInstant) -> Self {
516        self.wall_clock = Some(anchor);
517        self
518    }
519
520    /// Builds an RTCP session per RTP session ([`crate::PerRtpSession`]): a peer connection
521    /// with sections on several transports runs an RTCP session on each (RFC 3550 section 6,
522    /// RFC 8834 section 4.4), every one with these settings, the same CNAME (RFC 7022
523    /// section 4.2: one per endpoint) and its own members, bandwidth and timers.
524    pub fn build_per_rtp_session(mut self) -> crate::PerRtpSession<RtcpSessionInterceptor> {
525        let cname = self
526            .cname
527            .take()
528            .unwrap_or_else(|| generate_cname(self.random.as_mut()));
529        let random = SharedRandom(Arc::new(std::sync::Mutex::new(std::mem::replace(
530            &mut self.random,
531            Box::new(ThreadRandom),
532        ))));
533        let template = RtcpSessionBuilder {
534            cname: Some(cname),
535            random: Box::new(random.clone()),
536            ..self
537        };
538        let make = move |template: &RtcpSessionBuilder| RtcpSessionBuilder {
539            profile: template.profile,
540            t_rr_interval: template.t_rr_interval,
541            bandwidth: template.bandwidth,
542            rtcp_fraction: template.rtcp_fraction,
543            reduced_minimum: template.reduced_minimum,
544            reduced_size: template.reduced_size,
545            mtu: template.mtu,
546            cname: template.cname.clone(),
547            point_to_point: template.point_to_point,
548            report_from_every_ssrc: template.report_from_every_ssrc,
549            immediate_congestion_feedback: template.immediate_congestion_feedback,
550            congestion_feedback_in_budget: template.congestion_feedback_in_budget,
551            minimum_session_bandwidth: template.minimum_session_bandwidth,
552            joins_on_start: template.joins_on_start,
553            first_report_at_join: template.first_report_at_join,
554            random: Box::new(random.clone()),
555            wall_clock: template.wall_clock,
556        };
557        let first = make(&template).build();
558        crate::PerRtpSession::with_first(first, move || make(&template).build())
559    }
560
561    /// Builds the interceptor.
562    pub fn build(mut self) -> RtcpSessionInterceptor {
563        let cname = self
564            .cname
565            .take()
566            .unwrap_or_else(|| generate_cname(self.random.as_mut()));
567        RtcpSessionInterceptor {
568            profile: self.profile,
569            t_rr_interval: self.t_rr_interval.as_secs_f64(),
570            configured_t_rr_interval: self.t_rr_interval.as_secs_f64(),
571            bandwidth: self.bandwidth,
572            rtcp_fraction: self.rtcp_fraction,
573            reduced_minimum: self.reduced_minimum,
574            reduced_size: self.reduced_size,
575            mtu: self.mtu,
576            cname,
577            point_to_point: self.point_to_point,
578            report_from_every_ssrc: self.report_from_every_ssrc,
579            random: self.random,
580
581            joins_on_start: self.joins_on_start,
582            first_report_at_join: self.first_report_at_join,
583            start_given: false,
584            started: false,
585            left: false,
586            locals: Vec::new(),
587            departing: Vec::new(),
588            remotes: HashMap::new(),
589            remote_order: Vec::new(),
590            ecn_summary_next: 0,
591            report_cursor: 0,
592            members: HashMap::new(),
593            pmembers: 0,
594            avg_rtcp_size: 0.0,
595            srtcp_overhead: 0,
596            rate: RateWindow::default(),
597            immediate_congestion_feedback: self.immediate_congestion_feedback,
598            congestion_feedback_in_budget: self.congestion_feedback_in_budget,
599            minimum_session_bandwidth: self.minimum_session_bandwidth,
600            congestion_feedback_rate: RateWindow::default(),
601            regular_size: 0.0,
602            sending_regular: false,
603            outside_budget: false,
604            pending: Vec::new(),
605            repeats: Vec::new(),
606            early_at: None,
607            sender_report_requested: None,
608            clock_rate_switch: None,
609            compound_sent: false,
610            reference_times: HashMap::new(),
611            dlrr_limits: HashMap::new(),
612            wall_clock: self.wall_clock,
613            reduced_size_failed: false,
614            unanswered_reduced_nacks: 0,
615            awaited: None,
616            collided: HashSet::new(),
617            said_bye: HashMap::new(),
618            identifiers: HashMap::new(),
619            bye: None,
620            read_queue: VecDeque::new(),
621            write_queue: VecDeque::new(),
622        }
623    }
624}
625
626#[derive(Debug, Clone, Copy, PartialEq, Eq)]
627enum Kind {
628    Audio,
629    Video,
630    Other,
631}
632
633impl Kind {
634    fn of(mime_type: &str) -> Self {
635        let mime_type = mime_type.to_ascii_lowercase();
636        if mime_type.starts_with("audio/") {
637            Kind::Audio
638        } else if mime_type.starts_with("video/") {
639            Kind::Video
640        } else {
641            Kind::Other
642        }
643    }
644}
645
646#[derive(Debug, Clone, Copy, PartialEq, Eq)]
647enum Role {
648    /// The SSRC of a media stream this endpoint is set up to send.
649    Media,
650    /// An RTX or FEC SSRC: a participant once it has sent.
651    Repair,
652    /// The SSRC the session chose to report from while the endpoint has no media SSRC.
653    Reporter,
654}
655
656/// One of this endpoint's SSRCs.
657struct Local {
658    ssrc: u32,
659    kind: Kind,
660    role: Role,
661    stream: SenderStream,
662    /// `None` until the SSRC takes part and the session has started.
663    timing: Option<Timing>,
664    last_rtp: Option<Instant>,
665    rtp_sent: bool,
666    rtcp_sent: bool,
667    /// The compact NTP timestamps of the last sender reports and when each was sent, for the
668    /// round-trip time (RFC 3550 6.4.1).
669    sent_reports: VecDeque<(u32, Instant)>,
670}
671
672impl Local {
673    fn new(
674        ssrc: u32,
675        kind: Kind,
676        role: Role,
677        clock_rate: u32,
678        wall_clock: Option<SystemInstant>,
679    ) -> Self {
680        Self {
681            ssrc,
682            kind,
683            role,
684            stream: SenderStream::new(ssrc, clock_rate, false).with_wall_clock(wall_clock),
685            timing: None,
686            last_rtp: None,
687            rtp_sent: false,
688            rtcp_sent: false,
689            sent_reports: VecDeque::new(),
690        }
691    }
692
693    /// Whether the SSRC is a participant of the session: a repair SSRC is one from its first
694    /// packet on.
695    fn participates(&self) -> bool {
696        self.role != Role::Repair || self.rtp_sent
697    }
698}
699
700/// A remote stream bound for reception.
701struct Remote {
702    stream: ReceiverStream,
703    kind: Kind,
704    /// Whether receiver reference times (RFC 3611 4.4) were negotiated for it.
705    rrtr: bool,
706    /// The RTCP ECN Feedback packet (`nack ecn`, RFC 6679 6.2) was negotiated for it.
707    ecn_feedback: bool,
708    /// The XR ECN Summary Report (`xr ecn-sum`, RFC 6679 6.3) was negotiated for it.
709    ecn_summary: bool,
710    /// Its ECN counts (RFC 6679 5.1), kept while either is negotiated.
711    ecn: Option<Box<ecn::EcnTally>>,
712    /// The source said BYE or timed out: it is not reported on until it is heard again.
713    gone: bool,
714}
715
716/// A source in the member table (RFC 3550 6.2.1).
717struct Member {
718    last_heard: Instant,
719    last_rtp: Option<Instant>,
720    cname: Option<String>,
721}
722
723/// RFC 3550 6.3.7: a BYE waiting its turn in a session of more than fifty members.
724struct ByeBackoff {
725    packets: Vec<Box<dyn rtcp::Packet>>,
726    size: f64,
727    tp: Instant,
728    tn: Instant,
729    /// The BYE packets counted so far, this one included.
730    members: usize,
731}
732
733/// The media bitrate of the last seconds, for a session whose bandwidth nobody stated.
734#[derive(Default)]
735struct RateWindow {
736    buckets: VecDeque<(Instant, u64)>,
737    first: Option<Instant>,
738}
739
740impl RateWindow {
741    fn add(&mut self, now: Instant, octets: usize) {
742        self.first.get_or_insert(now);
743        match self.buckets.back_mut() {
744            Some((start, sum)) if now.saturating_duration_since(*start) < RATE_BUCKET => {
745                *sum += octets as u64;
746            }
747            _ => self.buckets.push_back((now, octets as u64)),
748        }
749        while self
750            .buckets
751            .front()
752            .is_some_and(|(start, _)| now.saturating_duration_since(*start) > RATE_WINDOW)
753        {
754            self.buckets.pop_front();
755        }
756    }
757
758    fn bits_per_second(&self, now: Instant) -> f64 {
759        let Some(first) = self.first else {
760            return 0.0;
761        };
762        let octets: u64 = self
763            .buckets
764            .iter()
765            .filter(|(start, _)| now.saturating_duration_since(*start) <= RATE_WINDOW)
766            .map(|(_, sum)| *sum)
767            .sum();
768        let span = now
769            .saturating_duration_since(first)
770            .clamp(RATE_BUCKET, RATE_WINDOW);
771        octets as f64 * 8.0 / span.as_secs_f64()
772    }
773}
774
775/// How a compound packet is put together.
776#[derive(Debug, Clone, Copy, PartialEq, Eq)]
777enum Shape {
778    /// A regular report: every due SSRC's SR or RR with the report blocks, SDES, XR.
779    Full,
780    /// RFC 4585 3.1: the minimal compound packet that carries feedback: one SR or RR without
781    /// report blocks, SDES, the feedback.
782    Minimal,
783}
784
785/// The RTCP session of an endpoint (RFC 3550 section 6, RFC 4585 section 3, RFC 8108).
786///
787/// One interceptor, closest to the wire, is the endpoint's whole RTCP voice:
788///
789/// - **Identity.** One CNAME for every local SSRC (RFC 7022: 96 random bits, Base64), given
790///   or generated. Reports and feedback come from the local media SSRCs; an endpoint with
791///   none reports from one SSRC the session chooses (never zero, never one in use). Every
792///   feedback packet the interceptors above or the application write leaves with the packet
793///   sender SSRC of this endpoint (RFC 8108 5.4.1), whatever they filled in.
794/// - **Reports.** A sender report for every SSRC that sent RTP in the last two intervals, RTX
795///   and FEC SSRCs included; a receiver report otherwise (RFC 3550 6.4). Reception report
796///   blocks for the remote streams (RFC 3550 Appendix A.3), an SDES CNAME for every reporting
797///   SSRC, XR receiver reference time and DLRR blocks (RFC 3611).
798/// - **Timing.** The interval of RFC 3550 6.3 from the member and sender counts, the average
799///   packet size and the RTCP bandwidth, randomised, with timer reconsideration and reverse
800///   reconsideration; the early feedback rules of RFC 4585 3.5 and `T_rr_interval`; one timer
801///   per local SSRC, aggregated into one compound packet (RFC 8108 5.3).
802/// - **Packets.** Everything leaves as a compound packet (SR or RR first, then SDES) unless
803///   reduced-size RTCP was negotiated (RFC 5506), kept under the MTU.
804/// - **Membership.** Sources heard in RTP and RTCP, their CNAMEs, BYE, the timeout after five
805///   intervals, sender status over two; BYE for a local SSRC that stops and for all of them
806///   when the endpoint leaves; a collision with one of the endpoint's own SSRCs.
807///
808/// It replaces [`SenderReportInterceptor`](crate::SenderReportInterceptor) and
809/// [`ReceiverReportInterceptor`](crate::ReceiverReportInterceptor), which report on fixed
810/// timers: a sender or receiver report those (or the application) write is dropped here, the
811/// session's own stand for it.
812///
813/// # Where it goes
814///
815/// [`Slot::RtcpSession`](crate::Slot::RtcpSession), wire-ward of everything: it counts what
816/// leaves (retransmissions and FEC included) and what arrives, and every RTCP packet the
817/// chain writes passes it last.
818///
819/// # Inputs and outputs
820///
821/// What a session description negotiates is handed in with the builder or, while running,
822/// as an [`RtcpSessionControl`]. What the session learns leaves as an [`RtcpSessionEvent`].
823pub struct RtcpSessionInterceptor {
824    profile: RtcpProfile,
825    /// Seconds.
826    t_rr_interval: f64,
827    /// Seconds: the builder's, which [`RtcpSessionControl::TrrIntCleared`] goes back to.
828    configured_t_rr_interval: f64,
829    bandwidth: RtcpBandwidth,
830    rtcp_fraction: f64,
831    reduced_minimum: bool,
832    reduced_size: bool,
833    mtu: usize,
834    cname: String,
835    point_to_point: Option<bool>,
836    report_from_every_ssrc: bool,
837    random: Box<dyn RtcpRandom>,
838
839    /// [`RtcpSessionBuilder::with_joins_on_start`].
840    joins_on_start: bool,
841    /// [`RtcpSessionBuilder::with_first_report_at_join`].
842    first_report_at_join: bool,
843    /// [`RtcpSessionControl::Start`] was given since the session was built or last left.
844    start_given: bool,
845    started: bool,
846    left: bool,
847    /// In the order they were bound.
848    locals: Vec<Local>,
849    /// Local SSRCs unbound since the chain was last driven: each says BYE unless bound again.
850    departing: Vec<Local>,
851    /// The SDES items of a local SSRC after its CNAME ([`RtcpSessionControl::StreamIdentifiers`]).
852    identifiers: HashMap<u32, Vec<SourceDescriptionItem>>,
853    remotes: HashMap<u32, Remote>,
854    /// The bound remote SSRCs in the order they were bound, for the round robin of report
855    /// blocks.
856    remote_order: Vec<u32>,
857    /// Where the next ECN summary starts in `remote_order` when not every sender fits (RFC
858    /// 6679 section 5.2: a subset, round-robin).
859    ecn_summary_next: usize,
860    report_cursor: usize,
861    /// The remote members of the session.
862    members: HashMap<u32, Member>,
863    pmembers: usize,
864    avg_rtcp_size: f64,
865    /// What SRTCP adds to each compound packet ([`RtcpSessionControl::SrtcpOverhead`]).
866    srtcp_overhead: usize,
867    rate: RateWindow,
868    /// Whether congestion control feedback leaves as soon as it is written.
869    immediate_congestion_feedback: bool,
870    /// [`RtcpSessionBuilder::with_congestion_feedback_in_budget`].
871    congestion_feedback_in_budget: bool,
872    /// [`RtcpSessionBuilder::with_minimum_session_bandwidth`], bits per second.
873    minimum_session_bandwidth: u64,
874    /// The congestion control feedback sent and received, with SRTCP, over the last seconds.
875    congestion_feedback_rate: RateWindow,
876    /// The average size of this endpoint's regular compound packets per reporting SSRC.
877    regular_size: f64,
878    /// Set while a regular packet is sent.
879    sending_regular: bool,
880    /// Set while a packet is sent outside the RTCP bandwidth's timing (immediate congestion
881    /// feedback): it does not move the average packet size the regular interval rests on.
882    outside_budget: bool,
883    /// Feedback and other packets waiting for a compound packet.
884    pending: Vec<Box<dyn rtcp::Packet>>,
885    /// Packets each of the next Regular compound packets carries again
886    /// ([`RepeatInRegularReports`]).
887    repeats: Vec<Repeat>,
888    /// RFC 4585 3.5.2: when the scheduled Early packet goes.
889    early_at: Option<Instant>,
890    /// RFC 6051 section 3.2: the local SSRC an RTCP-SR-REQ asked for an SR of, until an
891    /// Early packet carries it.
892    sender_report_requested: Option<usize>,
893    /// RFC 7160 section 4.1: the clock rate switch the next compound packet reports
894    /// ([`RtcpSessionControl::ClockRateSwitch`]): the current SSRC, then the previous ones.
895    clock_rate_switch: Option<(u32, Vec<u32>)>,
896    /// Whether a compound packet has been sent (RFC 5506 4: none reduced-size before).
897    compound_sent: bool,
898    /// The receiver reference times received and not yet answered, by sender SSRC.
899    reference_times: HashMap<u32, (u32, Instant)>,
900    /// The largest DLRR block each bound stream's `rcvr-rtt=<mode>:<max>` allows, in octets
901    /// (RFC 3611 section 5.1), by SSRC.
902    dlrr_limits: HashMap<u32, usize>,
903    wall_clock: Option<SystemInstant>,
904    reduced_size_failed: bool,
905    unanswered_reduced_nacks: u32,
906    /// The packets the last reduced-size NACK asked for.
907    awaited: Option<(u32, Vec<u16>)>,
908    /// Local media SSRCs a collision was reported for.
909    collided: HashSet<u32>,
910    /// Sources that said BYE and when (RFC 3550 6.2.1: the entry is kept, marked, for a
911    /// while, so that a packet that was overtaken by the BYE does not bring the source back).
912    said_bye: HashMap<u32, Instant>,
913    bye: Option<ByeBackoff>,
914
915    read_queue: VecDeque<TaggedPacket>,
916    write_queue: VecDeque<TaggedPacket>,
917}
918
919fn boxed<P: rtcp::Packet + 'static>(packet: P) -> Box<dyn rtcp::Packet> {
920    Box::new(packet)
921}
922
923/// The size of `packets` on the wire, lower layers included.
924fn wire_size(packets: &[Box<dyn rtcp::Packet>]) -> usize {
925    LOWER_LAYER_OVERHEAD + packets.iter().map(|p| p.marshal_size()).sum::<usize>()
926}
927
928/// The number of SSRCs reporting in a compound packet (RFC 8108 5.3.1): the distinct sources
929/// of its SR and RR packets, one for a packet without any.
930fn reporting_ssrcs(packets: &[Box<dyn rtcp::Packet>]) -> usize {
931    let mut sources: Vec<u32> = packets
932        .iter()
933        .filter_map(|packet| {
934            let any = packet.as_any();
935            any.downcast_ref::<SenderReport>()
936                .map(|sr| sr.ssrc)
937                .or_else(|| any.downcast_ref::<ReceiverReport>().map(|rr| rr.ssrc))
938        })
939        .collect();
940    sources.sort_unstable();
941    sources.dedup();
942    sources.len().max(1)
943}
944
945/// The packet sender SSRC of a feedback or report packet, and the media SSRC a feedback
946/// message is about.
947fn sender_and_media(packet: &dyn rtcp::Packet) -> (Option<u32>, Option<u32>) {
948    let any = packet.as_any();
949    if let Some(p) = any.downcast_ref::<TransportLayerNack>() {
950        (Some(p.sender_ssrc), Some(p.media_ssrc))
951    } else if let Some(p) = any.downcast_ref::<PictureLossIndication>() {
952        (Some(p.sender_ssrc), Some(p.media_ssrc))
953    } else if let Some(p) = any.downcast_ref::<FullIntraRequest>() {
954        (Some(p.sender_ssrc), p.fir.first().map(|entry| entry.ssrc))
955    } else if let Some(p) = any.downcast_ref::<SliceLossIndication>() {
956        (Some(p.sender_ssrc), Some(p.media_ssrc))
957    } else if let Some(p) = any.downcast_ref::<ReceiverEstimatedMaximumBitrate>() {
958        (Some(p.sender_ssrc), p.ssrcs.first().copied())
959    } else if let Some(p) = any.downcast_ref::<TransportLayerCc>() {
960        (Some(p.sender_ssrc), Some(p.media_ssrc))
961    } else if let Some(p) = any.downcast_ref::<CcFeedbackReport>() {
962        (Some(p.sender_ssrc), None)
963    } else if let Some(p) = any.downcast_ref::<RapidResynchronizationRequest>() {
964        (Some(p.sender_ssrc), Some(p.media_ssrc))
965    } else if let Some(p) = any.downcast_ref::<EcnFeedback>() {
966        (Some(p.sender_ssrc), Some(p.media_ssrc))
967    } else if let Some(p) = any.downcast_ref::<ExtendedReport>() {
968        (Some(p.sender_ssrc), None)
969    } else if let Some(p) = any.downcast_ref::<SenderReport>() {
970        (Some(p.ssrc), None)
971    } else if let Some(p) = any.downcast_ref::<ReceiverReport>() {
972        (Some(p.ssrc), None)
973    } else {
974        (None, None)
975    }
976}
977
978/// Whether a remote stream negotiated the RFC 6679 ECN Feedback packet (`a=rtcp-fb:<pt> nack
979/// ecn`, section 6.2) and the XR ECN Summary Report (`a=rtcp-xr:ecn-sum`, section 6.3, which
980/// reaches a stream as an `xr` feedback entry).
981fn negotiated_ecn_feedback(info: &StreamInfo) -> (bool, bool) {
982    let feedback = info
983        .rtcp_feedback
984        .iter()
985        .any(|f| f.typ == "nack" && f.parameter == crate::RTCP_FB_NACK_ECN);
986    let summary = info
987        .rtcp_feedback
988        .iter()
989        .any(|f| f.typ == crate::RTCP_FB_XR && f.parameter == crate::RTCP_XR_ECN_SUMMARY);
990    (feedback, summary)
991}
992
993/// `packet` with `ssrc` as its packet sender, for the types that name one.
994fn with_sender(packet: Box<dyn rtcp::Packet>, ssrc: u32) -> Box<dyn rtcp::Packet> {
995    macro_rules! rewrite {
996        ($($ty:ty),*) => {
997            $(if let Some(p) = packet.as_any().downcast_ref::<$ty>() {
998                let mut p = p.clone();
999                p.sender_ssrc = ssrc;
1000                return Box::new(p);
1001            })*
1002        };
1003    }
1004    rewrite!(
1005        TransportLayerNack,
1006        PictureLossIndication,
1007        FullIntraRequest,
1008        SliceLossIndication,
1009        ReceiverEstimatedMaximumBitrate,
1010        TransportLayerCc,
1011        CcFeedbackReport,
1012        RapidResynchronizationRequest,
1013        EcnFeedback,
1014        ExtendedReport
1015    );
1016    packet
1017}
1018
1019/// RFC 5506 4.2.1: whether the delivery of `packet` shows in what the peer does next (a
1020/// retransmission, a key frame, a sender that goes on raising its rate), so it may travel
1021/// reduced-size on its own.
1022///
1023/// Congestion control feedback is of that kind: RFC 8888 section 3.1 has it sent "in a
1024/// non-compound RTCP packet if supported by the session participants", and a sender whose
1025/// feedback does not arrive cuts its rate (RFC 8888 section 5), which the receiver sees.
1026/// Without the report and SDES around it the feedback is half the size, and at low media
1027/// rates twice as many fit the RTCP bandwidth.
1028fn delivery_shows(packet: &dyn rtcp::Packet) -> bool {
1029    let any = packet.as_any();
1030    any.is::<TransportLayerNack>()
1031        || any.is::<PictureLossIndication>()
1032        || any.is::<FullIntraRequest>()
1033        || any.is::<TransportLayerCc>()
1034        || any.is::<CcFeedbackReport>()
1035        || any.is::<EcnFeedback>()
1036}
1037
1038/// The maximum DLRR size in `rcvr-rtt=<mode>:<max>` (RFC 3611 section 5.1), `None` without
1039/// one.
1040fn dlrr_limit(format: &str) -> Option<usize> {
1041    let (name, value) = format.split_once('=')?;
1042    if name != "rcvr-rtt" {
1043        return None;
1044    }
1045    value.split_once(':')?.1.parse().ok()
1046}
1047
1048impl RtcpSessionInterceptor {
1049    /// The CNAME this endpoint's SSRCs are described with.
1050    pub fn cname(&self) -> &str {
1051        &self.cname
1052    }
1053
1054    fn unit(&mut self) -> f64 {
1055        self.random.unit()
1056    }
1057
1058    fn emit(&mut self, now: Instant, event: RtcpSessionEvent) {
1059        self.read_queue.push_back(TaggedPacket {
1060            now,
1061            transport: TransportContext::default(),
1062            message: AttributedPacket::new(Packet::Rtcp(vec![]))
1063                .with(Attribute::Custom(Arc::new(event))),
1064        });
1065    }
1066
1067    fn send(&mut self, now: Instant, packets: Vec<Box<dyn rtcp::Packet>>) {
1068        if packets.is_empty() {
1069            return;
1070        }
1071        if self.outside_budget {
1072            self.congestion_feedback_rate
1073                .add(now, wire_size(&packets) + self.srtcp_overhead);
1074        }
1075        if self.sending_regular {
1076            let size = (wire_size(&packets) + self.srtcp_overhead) as f64
1077                / reporting_ssrcs(&packets) as f64;
1078            self.regular_size = if self.regular_size > 0.0 {
1079                update_avg_rtcp_size(self.regular_size, size)
1080            } else {
1081                size
1082            };
1083        }
1084        // RFC 3550 6.3.6 with RFC 8108 5.3.1: the average takes the size per reporting SSRC.
1085        if !self.outside_budget {
1086            let size = (wire_size(&packets) + self.srtcp_overhead) as f64
1087                / reporting_ssrcs(&packets) as f64;
1088            self.avg_rtcp_size = update_avg_rtcp_size(self.avg_rtcp_size, size);
1089        }
1090        self.write_queue.push_back(TaggedPacket {
1091            now,
1092            transport: TransportContext::default(),
1093            message: AttributedPacket::new(Packet::Rtcp(packets)),
1094        });
1095    }
1096
1097    // ---- who is in the session -------------------------------------------------------
1098
1099    fn local_index(&self, ssrc: u32) -> Option<usize> {
1100        self.locals.iter().position(|local| local.ssrc == ssrc)
1101    }
1102
1103    fn ssrc_in_use(&self, ssrc: u32) -> bool {
1104        self.local_index(ssrc).is_some()
1105            || self.departing.iter().any(|local| local.ssrc == ssrc)
1106            || self.members.contains_key(&ssrc)
1107            || self.remotes.contains_key(&ssrc)
1108    }
1109
1110    /// The local SSRC that carries the reception report blocks: the first media SSRC, or the
1111    /// session's own reporting SSRC.
1112    fn reporter(&self) -> Option<usize> {
1113        self.locals
1114            .iter()
1115            .position(|local| local.role == Role::Media)
1116            .or_else(|| {
1117                self.locals
1118                    .iter()
1119                    .position(|local| local.role == Role::Reporter)
1120            })
1121    }
1122
1123    /// The local SSRC feedback about `media_ssrc` is sent from (RFC 8108 5.4.1): a media SSRC
1124    /// of the same kind as the stream when there is one, the reporter otherwise.
1125    fn feedback_source(&self, media_ssrc: Option<u32>) -> Option<usize> {
1126        let kind = media_ssrc
1127            .and_then(|ssrc| self.remotes.get(&ssrc))
1128            .map(|remote| remote.kind);
1129        kind.and_then(|kind| {
1130            self.locals
1131                .iter()
1132                .position(|local| local.role == Role::Media && local.kind == kind)
1133        })
1134        .or_else(|| self.reporter())
1135    }
1136
1137    /// Keeps the session's own reporting SSRC while the endpoint has no media SSRC, and
1138    /// retires it when it has one (RFC 8108 6.2: with a BYE).
1139    fn sync_reporter(&mut self) {
1140        let has_media = self.locals.iter().any(|local| local.role == Role::Media);
1141        let reporter = self
1142            .locals
1143            .iter()
1144            .position(|local| local.role == Role::Reporter);
1145        match (has_media, reporter) {
1146            (true, Some(index)) => {
1147                let local = self.locals.remove(index);
1148                self.departing.push(local);
1149            }
1150            (false, None) if !self.left => {
1151                let mut random = std::mem::replace(&mut self.random, Box::new(ThreadRandom));
1152                let ssrc = choose_ssrc(random.as_mut(), |ssrc| self.ssrc_in_use(ssrc));
1153                self.random = random;
1154                self.locals.push(Local::new(
1155                    ssrc,
1156                    Kind::Other,
1157                    Role::Reporter,
1158                    90_000,
1159                    self.wall_clock,
1160                ));
1161            }
1162            _ => {}
1163        }
1164    }
1165
1166    fn member_count(&self) -> usize {
1167        self.members.len() + self.locals.iter().filter(|l| l.participates()).count()
1168    }
1169
1170    /// RFC 8108 5.4.2: point to point unless the remote sources name more than one CNAME.
1171    fn is_point_to_point(&self) -> bool {
1172        if let Some(point_to_point) = self.point_to_point {
1173            return point_to_point;
1174        }
1175        let mut cnames = self.members.values().filter_map(|m| m.cname.as_deref());
1176        match cnames.next() {
1177            Some(first) => cnames.all(|cname| cname == first),
1178            None => true,
1179        }
1180    }
1181
1182    // ---- bandwidth and intervals -----------------------------------------------------
1183
1184    fn session_bandwidth(&self, now: Instant) -> f64 {
1185        match self.bandwidth.session {
1186            Some(session) => session as f64,
1187            None => {
1188                // RFC 3550 6.2 lets the session bandwidth be "supplied by a session
1189                // management application"; without one it is the media measured both ways
1190                // over the last seconds. (A congestion controller's target is not used: an
1191                // application-limited sender's target is many times what it sends.)
1192                let measured = self.rate.bits_per_second(now);
1193                // The nominal figure stands only until the media has had its window to be
1194                // measured: a start-up value, not the session bandwidth.
1195                let starting = self
1196                    .rate
1197                    .first
1198                    .is_none_or(|first| now.saturating_duration_since(first) < RATE_WINDOW);
1199                let measured = if starting {
1200                    measured.max(self.nominal_bandwidth())
1201                } else {
1202                    measured
1203                };
1204                measured.max(self.minimum_session_bandwidth as f64)
1205            }
1206        }
1207    }
1208
1209    /// The nominal session bandwidth of the media bound, when no `b=` line gave one.
1210    fn nominal_bandwidth(&self) -> f64 {
1211        let kinds = self
1212            .locals
1213            .iter()
1214            .filter(|local| local.role == Role::Media)
1215            .map(|local| local.kind)
1216            .chain(self.remotes.values().map(|remote| remote.kind));
1217        let (mut video, mut audio) = (false, false);
1218        for kind in kinds {
1219            match kind {
1220                Kind::Video => video = true,
1221                Kind::Audio => audio = true,
1222                Kind::Other => {}
1223            }
1224        }
1225        nominal_session_bandwidth(video, audio)
1226    }
1227
1228    /// The RTCP bandwidth in octets per second and the senders' share of it.
1229    fn rtcp_bandwidth(&self, now: Instant) -> (f64, f64) {
1230        let session = self.session_bandwidth(now);
1231        // RFC 3556: a modifier that is absent keeps its default share of the 5%.
1232        let default_rs = session * self.rtcp_fraction * RTCP_SENDER_BW_FRACTION;
1233        let default_rr = session * self.rtcp_fraction * (1.0 - RTCP_SENDER_BW_FRACTION);
1234        match (self.bandwidth.rs, self.bandwidth.rr) {
1235            (None, None) => (session * self.rtcp_fraction / 8.0, RTCP_SENDER_BW_FRACTION),
1236            (rs, rr) => {
1237                let rs = rs.map_or(default_rs, |rs| rs as f64);
1238                let rr = rr.map_or(default_rr, |rr| rr as f64);
1239                let total = rs + rr;
1240                if total <= 0.0 {
1241                    (0.0, RTCP_SENDER_BW_FRACTION)
1242                } else {
1243                    (total / 8.0, rs / total)
1244                }
1245            }
1246        }
1247    }
1248
1249    /// The minimum interval in force for a local SSRC.
1250    fn t_min(&self, now: Instant, initial: bool) -> f64 {
1251        match self.profile {
1252            RtcpProfile::Avp => {
1253                if self.reduced_minimum {
1254                    reduced_minimum(self.session_bandwidth(now))
1255                } else {
1256                    RTCP_MIN_TIME
1257                }
1258            }
1259            // RFC 4585 3.5.1 and 3.5.3: zero for a point-to-point session, one second for the
1260            // first packet of a multiparty one, zero after it.
1261            RtcpProfile::Avpf => {
1262                if initial && !self.is_point_to_point() {
1263                    1.0
1264                } else {
1265                    0.0
1266                }
1267            }
1268        }
1269    }
1270
1271    /// RFC 3550 6.3.8: whether the local SSRC sent RTP within the last two report intervals.
1272    fn we_sent(&self, index: usize, now: Instant) -> bool {
1273        let horizon = 2.0 * self.report_interval(now);
1274        self.locals[index]
1275            .last_rtp
1276            .is_some_and(|last| now.saturating_duration_since(last).as_secs_f64() <= horizon)
1277    }
1278
1279    /// The interval reports are made at, for the sender status of RFC 3550 6.3.5 and 6.3.8
1280    /// ("within the last two RTCP report intervals"): the interval at which the members
1281    /// share the RTCP bandwidth, no less than the profile's minimum, and under RTP/AVPF no
1282    /// less than `T_rr_interval`, inside which regular reports are suppressed.
1283    fn report_interval(&self, now: Instant) -> f64 {
1284        let (rtcp_bw, _) = self.rtcp_bandwidth(now);
1285        let shared = if rtcp_bw > 0.0 {
1286            self.avg_rtcp_size * self.member_count().max(1) as f64 / rtcp_bw
1287        } else {
1288            RTCP_MIN_TIME
1289        };
1290        let floor = match self.profile {
1291            RtcpProfile::Avp => self.t_min(now, false),
1292            RtcpProfile::Avpf => self.t_rr_interval,
1293        };
1294        shared.max(floor).max(MIN_INTERVAL)
1295    }
1296
1297    fn sender_count(&self, now: Instant) -> usize {
1298        let horizon = 2.0 * self.report_interval(now);
1299        let sent_lately = |last_rtp: Option<Instant>| {
1300            last_rtp
1301                .is_some_and(|last| now.saturating_duration_since(last).as_secs_f64() <= horizon)
1302        };
1303        self.members
1304            .values()
1305            .filter(|member| sent_lately(member.last_rtp))
1306            .count()
1307            + self
1308                .locals
1309                .iter()
1310                .filter(|local| local.participates() && sent_lately(local.last_rtp))
1311                .count()
1312    }
1313
1314    /// The input of the interval computation of RFC 3550 6.3.1.
1315    fn interval_input(
1316        &self,
1317        now: Instant,
1318        we_sent: bool,
1319        initial: bool,
1320        senders: usize,
1321    ) -> IntervalInput {
1322        let (rtcp_bw, sender_fraction) = self.rtcp_bandwidth(now);
1323        IntervalInput {
1324            members: self.member_count().max(1),
1325            senders,
1326            rtcp_bw,
1327            sender_fraction,
1328            we_sent,
1329            avg_rtcp_size: self.avg_rtcp_size,
1330            t_min: self.t_min(now, initial),
1331            initial,
1332        }
1333    }
1334
1335    /// The calculated interval T of a local SSRC, randomised (RFC 3550 6.3.1).
1336    fn interval(&mut self, index: usize, now: Instant) -> f64 {
1337        let we_sent = self.we_sent(index, now);
1338        let initial = self.locals[index]
1339            .timing
1340            .is_none_or(|timing| timing.initial);
1341        let senders = self.sender_count(now);
1342        let td = deterministic_interval(&self.interval_input(now, we_sent, initial, senders));
1343        let random = self.unit();
1344        randomized_interval(td, random).max(MIN_INTERVAL)
1345    }
1346
1347    /// The `T_rr_interval` regular reports keep (RFC 4585 3.5.3), seconds: the configured or
1348    /// negotiated one, or with [`RtcpSessionBuilder::with_congestion_feedback_in_budget`] the
1349    /// regular interval in what the RTCP bandwidth leaves after the congestion control
1350    /// feedback, whichever is longer (at most [`MAX_BUDGET_T_RR_INTERVAL`]).
1351    fn effective_t_rr_interval(&self, index: usize, now: Instant) -> f64 {
1352        if !self.congestion_feedback_in_budget {
1353            return self.t_rr_interval;
1354        }
1355        let (rtcp_bw, sender_fraction) = self.rtcp_bandwidth(now);
1356        let feedback = self.congestion_feedback_rate.bits_per_second(now) / 8.0;
1357        let left = rtcp_bw - feedback;
1358        let size = if self.regular_size > 0.0 {
1359            self.regular_size
1360        } else {
1361            self.avg_rtcp_size
1362        };
1363        let budget = if left <= 0.0 {
1364            MAX_BUDGET_T_RR_INTERVAL
1365        } else {
1366            let input = IntervalInput {
1367                members: self.member_count().max(1),
1368                senders: self.sender_count(now),
1369                rtcp_bw: left,
1370                sender_fraction,
1371                we_sent: self.we_sent(index, now),
1372                avg_rtcp_size: size,
1373                t_min: 0.0,
1374                initial: false,
1375            };
1376            deterministic_interval(&input).min(MAX_BUDGET_T_RR_INTERVAL)
1377        };
1378        self.t_rr_interval.max(budget)
1379    }
1380
1381    // ---- joining ---------------------------------------------------------------------
1382
1383    /// Whether anything may make the session join: always, unless it joins on
1384    /// [`RtcpSessionControl::Start`] only and has not been given it.
1385    fn may_join(&self) -> bool {
1386        !self.joins_on_start || self.start_given
1387    }
1388
1389    /// [`RtcpSessionControl::Start`] after [`RtcpSessionControl::Leave`]: the session is
1390    /// joined afresh (RFC 3550 section 6.3.2's initial state), with no members, nothing
1391    /// pending and the next local SSRC it reports from a new one.
1392    fn rejoin(&mut self) {
1393        self.left = false;
1394        self.started = false;
1395        self.departing.clear();
1396        self.pending.clear();
1397        self.early_at = None;
1398        self.bye = None;
1399        self.members.clear();
1400        self.pmembers = 0;
1401        self.avg_rtcp_size = 0.0;
1402        self.compound_sent = false;
1403        self.reference_times.clear();
1404        self.awaited = None;
1405        self.unanswered_reduced_nacks = 0;
1406    }
1407
1408    /// Joins the session if it has not, and gives every participating SSRC its timer.
1409    fn sync(&mut self, now: Instant) {
1410        if self.left || !self.may_join() {
1411            return;
1412        }
1413        self.sync_reporter();
1414        let joining = !self.started;
1415        if !self.started {
1416            self.started = true;
1417            // RFC 3550 6.3.2: avg_rtcp_size starts at the probable size of the first packet:
1418            // a report, an SDES with the CNAME, and a block for each stream bound so far.
1419            // RFC 3711 section 3.4: with the SRTCP fields.
1420            self.avg_rtcp_size = (LOWER_LAYER_OVERHEAD
1421                + 8
1422                + 12
1423                + self.cname.len()
1424                + 24 * self.remotes.len().min(MAX_REPORT_BLOCKS)
1425                + self.srtcp_overhead) as f64;
1426            self.pmembers = self.member_count().max(1);
1427        }
1428        for index in 0..self.locals.len() {
1429            if self.locals[index].timing.is_none() && self.locals[index].participates() {
1430                self.locals[index].timing = Some(if joining && self.first_report_at_join {
1431                    Timing::immediate(now)
1432                } else {
1433                    let t = self.interval(index, now);
1434                    Timing::new(now, t)
1435                });
1436            }
1437        }
1438        self.flush_departing(now);
1439    }
1440
1441    // ---- the member table ------------------------------------------------------------
1442
1443    fn heard(&mut self, now: Instant, ssrc: u32, rtp: bool) {
1444        if let Some(&left_at) = self.said_bye.get(&ssrc) {
1445            // RFC 3550 6.2.1: a straggler behind the BYE; the source stays gone for two
1446            // report intervals.
1447            if now.saturating_duration_since(left_at).as_secs_f64()
1448                <= 2.0 * self.report_interval(now)
1449            {
1450                return;
1451            }
1452            self.said_bye.remove(&ssrc);
1453        }
1454        if let Some(member) = self.members.get_mut(&ssrc) {
1455            member.last_heard = now;
1456            if rtp {
1457                member.last_rtp = Some(now);
1458            }
1459        } else if self.members.len() < MAX_MEMBERS {
1460            self.members.insert(
1461                ssrc,
1462                Member {
1463                    last_heard: now,
1464                    last_rtp: rtp.then_some(now),
1465                    cname: None,
1466                },
1467            );
1468        }
1469        if let Some(remote) = self.remotes.get_mut(&ssrc) {
1470            remote.gone = false;
1471        }
1472    }
1473
1474    /// RFC 3550 6.3.4: the membership fell; the timers shrink with it.
1475    fn reverse_reconsider(&mut self, now: Instant) {
1476        let members = self.member_count().max(1);
1477        if members < self.pmembers {
1478            let pmembers = self.pmembers;
1479            for local in &mut self.locals {
1480                if let Some(timing) = local.timing.as_mut() {
1481                    timing.reverse_reconsider(now, members, pmembers);
1482                }
1483            }
1484            self.pmembers = members;
1485        }
1486    }
1487
1488    fn remove_member(&mut self, ssrc: u32) -> bool {
1489        if let Some(remote) = self.remotes.get_mut(&ssrc) {
1490            remote.gone = true;
1491        }
1492        self.reference_times.remove(&ssrc);
1493        self.members.remove(&ssrc).is_some()
1494    }
1495
1496    /// RFC 3550 6.3.5 with RFC 8108 7.1.4: a member not heard for five deterministic
1497    /// intervals (computed for a receiver, with a minimum of five seconds) is timed out.
1498    fn time_out_members(&mut self, now: Instant) {
1499        let mut input = self.interval_input(now, false, false, self.sender_count(now));
1500        input.t_min = RTCP_MIN_TIME;
1501        let timeout = TIMEOUT_MULTIPLIER * deterministic_interval(&input);
1502        if !timeout.is_finite() {
1503            return;
1504        }
1505        let silent: Vec<u32> = self
1506            .members
1507            .iter()
1508            .filter(|(_, member)| {
1509                now.saturating_duration_since(member.last_heard)
1510                    .as_secs_f64()
1511                    > timeout
1512            })
1513            .map(|(ssrc, _)| *ssrc)
1514            .collect();
1515        let linger = 2.0 * self.report_interval(now);
1516        self.said_bye
1517            .retain(|_, left_at| now.saturating_duration_since(*left_at).as_secs_f64() <= linger);
1518        if silent.is_empty() {
1519            return;
1520        }
1521        for ssrc in silent {
1522            self.remove_member(ssrc);
1523            self.emit(now, RtcpSessionEvent::SourceTimedOut { ssrc });
1524        }
1525        self.reverse_reconsider(now);
1526    }
1527
1528    /// RFC 3550 8.2: a packet from another source carries one of this endpoint's SSRCs.
1529    fn collision(&mut self, now: Instant, ssrc: u32) {
1530        let Some(index) = self.local_index(ssrc) else {
1531            return;
1532        };
1533        let mut random = std::mem::replace(&mut self.random, Box::new(ThreadRandom));
1534        let replacement = choose_ssrc(random.as_mut(), |candidate| self.ssrc_in_use(candidate));
1535        self.random = random;
1536
1537        if self.locals[index].role == Role::Reporter {
1538            // The session's own SSRC: say BYE with the old identifier and take the new one.
1539            let old = self.locals.remove(index);
1540            self.departing.push(old);
1541            self.locals.push(Local::new(
1542                replacement,
1543                Kind::Other,
1544                Role::Reporter,
1545                90_000,
1546                self.wall_clock,
1547            ));
1548            self.emit(now, RtcpSessionEvent::SsrcCollision { ssrc, replacement });
1549            self.sync(now);
1550        } else if self.collided.insert(ssrc) {
1551            // A stream's SSRC is the sender's to change: it is told, and the BYE for the old
1552            // SSRC leaves when the stream is unbound.
1553            self.emit(now, RtcpSessionEvent::SsrcCollision { ssrc, replacement });
1554        }
1555    }
1556
1557    // ---- what arrives ----------------------------------------------------------------
1558
1559    /// Whether the packet goes on to the rest of the chain.
1560    fn observe_rtp(
1561        &mut self,
1562        now: Instant,
1563        message: &AttributedPacket,
1564        ecn: Option<shared::EcnCodepoint>,
1565    ) -> bool {
1566        let Packet::Rtp(packet) = &message.packet else {
1567            return true;
1568        };
1569        let header = &packet.header;
1570        // The stream the packet arrived on: the RTX stream for a retransmission that was
1571        // de-encapsulated before the chain.
1572        let (arrival_ssrc, arrival_sequence_number) = message
1573            .attributes
1574            .iter()
1575            .find_map(|attribute| match attribute {
1576                Attribute::Retransmitted {
1577                    ssrc,
1578                    sequence_number,
1579                } => Some((*ssrc, *sequence_number)),
1580                _ => None,
1581            })
1582            .unwrap_or((header.ssrc, header.sequence_number));
1583
1584        // RFC 3550 8.2: our own SSRC from the network is a collision, or our own packet
1585        // looped back; either way it is not a remote stream's.
1586        if self.local_index(arrival_ssrc).is_some() {
1587            self.collision(now, arrival_ssrc);
1588            return false;
1589        }
1590
1591        self.rate
1592            .add(now, header.marshal_size() + packet.payload.len());
1593        self.heard(now, arrival_ssrc, true);
1594        for &csrc in &header.csrc {
1595            self.heard(now, csrc, false);
1596        }
1597
1598        self.observe_ecn(now, arrival_ssrc, arrival_sequence_number, ecn);
1599        if let Some(remote) = self.remotes.get_mut(&arrival_ssrc) {
1600            if arrival_ssrc == header.ssrc {
1601                remote.stream.process_rtp(now, packet);
1602            } else {
1603                let mut arrived = rtp::Packet {
1604                    header: rtp::header::Header {
1605                        ssrc: arrival_ssrc,
1606                        sequence_number: arrival_sequence_number,
1607                        timestamp: header.timestamp,
1608                        ..Default::default()
1609                    },
1610                    ..Default::default()
1611                };
1612                arrived.header.version = 2;
1613                remote.stream.process_rtp(now, &arrived);
1614            }
1615        } else if arrival_ssrc != header.ssrc
1616            && let Some(remote) = self.remotes.get_mut(&header.ssrc)
1617        {
1618            // A retransmission whose RTX stream is not bound counts where it is delivered.
1619            remote.stream.process_rtp(now, packet);
1620        }
1621
1622        // RFC 5506 4.2.1: a packet a reduced-size NACK asked for arrived, so they get through.
1623        if let Some((ssrc, sequence_numbers)) = &self.awaited
1624            && *ssrc == header.ssrc
1625            && sequence_numbers.contains(&header.sequence_number)
1626        {
1627            self.awaited = None;
1628            self.unanswered_reduced_nacks = 0;
1629        }
1630        true
1631    }
1632
1633    /// RFC 6679 5.1, 7.2.1 and 7.3.2: counts the ECN field of an RTP packet from a source
1634    /// that negotiated ECN feedback, and asks for an early ECN Feedback packet on the first
1635    /// ECT or CE packet of the source, on every CE mark and on a detected loss, where the
1636    /// feedback packet (`nack ecn`) was negotiated.
1637    fn observe_ecn(
1638        &mut self,
1639        now: Instant,
1640        ssrc: u32,
1641        sequence_number: u16,
1642        ecn: Option<shared::EcnCodepoint>,
1643    ) {
1644        let Some(remote) = self.remotes.get_mut(&ssrc) else {
1645            return;
1646        };
1647        let Some(tally) = remote.ecn.as_deref_mut() else {
1648            return;
1649        };
1650        let events = tally.on_packet(sequence_number, ecn);
1651        if !(events.any() && remote.ecn_feedback) {
1652            return;
1653        }
1654        let feedback = EcnFeedback {
1655            sender_ssrc: 0,
1656            media_ssrc: ssrc,
1657            extended_highest_sequence_number: tally.extended_highest(),
1658            counters: tally.counters(),
1659        };
1660        self.adopt(boxed(feedback));
1661        self.schedule_feedback(now);
1662    }
1663
1664    fn observe_report_blocks(&mut self, now: Instant, reports: &[ReceptionReport]) {
1665        for report in reports {
1666            if report.last_sender_report == 0 {
1667                continue;
1668            }
1669            let Some(index) = self.local_index(report.ssrc) else {
1670                continue;
1671            };
1672            let Some(&(_, sent)) = self.locals[index]
1673                .sent_reports
1674                .iter()
1675                .find(|(compact_ntp, _)| *compact_ntp == report.last_sender_report)
1676            else {
1677                continue;
1678            };
1679            // RFC 3550 6.4.1: the round trip is the time since the report was sent less the
1680            // delay the receiver held it for (DLSR, in 1/65536 s).
1681            let elapsed = now.saturating_duration_since(sent).as_secs_f64();
1682            let rtt = (elapsed - f64::from(report.delay) / 65536.0).max(0.0);
1683            self.emit(
1684                now,
1685                RtcpSessionEvent::RoundTripTime {
1686                    ssrc: report.ssrc,
1687                    rtt: Duration::from_secs_f64(rtt),
1688                },
1689            );
1690        }
1691    }
1692
1693    fn observe_rtcp(&mut self, now: Instant, packets: &[Box<dyn rtcp::Packet>]) {
1694        if packets.is_empty() {
1695            return;
1696        }
1697        // RFC 3711 section 3.4: the SRTCP fields count, though they are gone by now.
1698        let size =
1699            (wire_size(packets) + self.srtcp_overhead) as f64 / reporting_ssrcs(packets) as f64;
1700        let mut goodbyes = 0;
1701        let feedback: usize = packets
1702            .iter()
1703            .filter(|packet| {
1704                let any = packet.as_any();
1705                any.is::<TransportLayerCc>() || any.is::<CcFeedbackReport>()
1706            })
1707            .map(|packet| packet.marshal_size())
1708            .sum();
1709        if feedback > 0 {
1710            // A reduced-size packet's SRTCP fields are the feedback's own.
1711            let reduced = !packets.iter().any(|packet| {
1712                let any = packet.as_any();
1713                any.is::<SenderReport>() || any.is::<ReceiverReport>()
1714            });
1715            let overhead = if reduced { self.srtcp_overhead } else { 0 };
1716            self.congestion_feedback_rate.add(now, feedback + overhead);
1717        }
1718
1719        for packet in packets {
1720            let any = packet.as_any();
1721            if let Some(goodbye) = any.downcast_ref::<Goodbye>() {
1722                goodbyes += 1;
1723                for &source in &goodbye.sources {
1724                    self.remove_member(source);
1725                    if self.said_bye.len() < MAX_MEMBERS {
1726                        self.said_bye.insert(source, now);
1727                    }
1728                }
1729                continue;
1730            }
1731            if let Some(sdes) = any.downcast_ref::<SourceDescription>() {
1732                for chunk in &sdes.chunks {
1733                    if self.local_index(chunk.source).is_some() {
1734                        continue;
1735                    }
1736                    self.heard(now, chunk.source, false);
1737                    let cname = chunk
1738                        .items
1739                        .iter()
1740                        .find(|item| item.sdes_type == SdesType::SdesCname)
1741                        .map(|item| String::from_utf8_lossy(&item.text).into_owned());
1742                    if let Some(cname) = cname
1743                        && let Some(member) = self.members.get_mut(&chunk.source)
1744                        && member.cname.as_deref() != Some(cname.as_str())
1745                    {
1746                        member.cname = Some(cname.clone());
1747                        self.emit(
1748                            now,
1749                            RtcpSessionEvent::RemoteCname {
1750                                ssrc: chunk.source,
1751                                cname,
1752                            },
1753                        );
1754                    }
1755                }
1756                continue;
1757            }
1758
1759            let (sender, _) = sender_and_media(packet.as_ref());
1760            if let Some(sender) = sender {
1761                if self.local_index(sender).is_some() {
1762                    // RFC 3550 8.2: RTCP from another source under one of our SSRCs.
1763                    self.collision(now, sender);
1764                    continue;
1765                }
1766                self.heard(now, sender, false);
1767            }
1768
1769            // RFC 6051 section 3.2: "a media source that understands the RTCP-SR-REQ packet
1770            // SHOULD generate an RTCP SR packet as soon as possible while complying with the
1771            // RTCP early feedback rules".
1772            if let Some(request) = any.downcast_ref::<RapidResynchronizationRequest>()
1773                && let Some(index) = self.local_index(request.media_ssrc)
1774            {
1775                self.request_sender_report(now, index);
1776            }
1777
1778            if let Some(sr) = any.downcast_ref::<SenderReport>() {
1779                if let Some(remote) = self.remotes.get_mut(&sr.ssrc) {
1780                    remote.stream.process_sender_report(now, sr);
1781                }
1782                self.observe_report_blocks(now, &sr.reports);
1783            } else if let Some(rr) = any.downcast_ref::<ReceiverReport>() {
1784                self.observe_report_blocks(now, &rr.reports);
1785            } else if let Some(xr) = any.downcast_ref::<ExtendedReport>() {
1786                for block in &xr.reports {
1787                    if let Some(rrtr) = block
1788                        .as_any()
1789                        .downcast_ref::<ReceiverReferenceTimeReportBlock>()
1790                        && (self.reference_times.len() < MAX_REFERENCE_TIMES
1791                            || self.reference_times.contains_key(&xr.sender_ssrc))
1792                    {
1793                        self.reference_times
1794                            .insert(xr.sender_ssrc, ((rrtr.ntp_timestamp >> 16) as u32, now));
1795                    }
1796                }
1797            }
1798        }
1799
1800        if let Some(bye) = self.bye.as_mut() {
1801            // RFC 3550 6.3.7: while a BYE waits, only BYE packets are counted and sized.
1802            if goodbyes > 0 {
1803                bye.members += goodbyes;
1804                bye.size = update_avg_rtcp_size(bye.size, size);
1805            }
1806        } else {
1807            self.avg_rtcp_size = update_avg_rtcp_size(self.avg_rtcp_size, size);
1808            if goodbyes > 0 {
1809                self.reverse_reconsider(now);
1810            }
1811        }
1812    }
1813
1814    // ---- what the chain and the application write ------------------------------------
1815
1816    /// Takes an RTCP packet written from above into the session's hands.
1817    fn adopt(&mut self, packet: Box<dyn rtcp::Packet>) {
1818        let any = packet.as_any();
1819        // The session's own reports and CNAME stand for these.
1820        if any.is::<SenderReport>() || any.is::<ReceiverReport>() || any.is::<SourceDescription>() {
1821            return;
1822        }
1823        let (sender, media) = sender_and_media(packet.as_ref());
1824        let packet = match (sender, self.feedback_source(media)) {
1825            (Some(_), Some(index)) => with_sender(packet, self.locals[index].ssrc),
1826            _ => packet,
1827        };
1828
1829        // RFC 4585 3.5.2: feedback for one compound packet is merged into as few messages
1830        // as possible.
1831        let any = packet.as_any();
1832        if let Some(nack) = any.downcast_ref::<TransportLayerNack>() {
1833            for held in &mut self.pending {
1834                if let Some(other) = held.as_any().downcast_ref::<TransportLayerNack>()
1835                    && other.media_ssrc == nack.media_ssrc
1836                {
1837                    let mut sequence_numbers: Vec<u16> = other
1838                        .nacks
1839                        .iter()
1840                        .chain(&nack.nacks)
1841                        .flat_map(|pair| pair.packet_list())
1842                        .collect();
1843                    sequence_numbers.sort_unstable();
1844                    sequence_numbers.dedup();
1845                    *held = boxed(TransportLayerNack {
1846                        sender_ssrc: nack.sender_ssrc,
1847                        media_ssrc: nack.media_ssrc,
1848                        nacks: nack_pairs_from_sequence_numbers(&sequence_numbers),
1849                    });
1850                    return;
1851                }
1852            }
1853        } else if let Some(feedback) = any.downcast_ref::<EcnFeedback>() {
1854            // RFC 6679 5.1: the counters are cumulative, so the newest report says all an
1855            // older one waiting beside it would.
1856            let media = feedback.media_ssrc;
1857            self.pending.retain(|held| {
1858                held.as_any()
1859                    .downcast_ref::<EcnFeedback>()
1860                    .is_none_or(|other| other.media_ssrc != media)
1861            });
1862        } else if let Some(pli) = any.downcast_ref::<PictureLossIndication>()
1863            && self.pending.iter().any(|held| {
1864                held.as_any()
1865                    .downcast_ref::<PictureLossIndication>()
1866                    .is_some_and(|other| other.media_ssrc == pli.media_ssrc)
1867            })
1868        {
1869            return;
1870        }
1871
1872        if self.pending.len() >= MAX_PENDING {
1873            self.pending.remove(0);
1874        }
1875        self.pending.push(packet);
1876    }
1877
1878    fn has_feedback(&self) -> bool {
1879        self.pending.iter().any(|packet| {
1880            let any = packet.as_any();
1881            // RFC 5104 sections 4.3.2.3 and 4.3.3.3: a TSTR "is not time critical and SHOULD
1882            // be sent using regular RTCP timing", and so is the TSTN that answers it. They
1883            // wait for the next regular packet and ask for no Early one (another feedback
1884            // message that does takes them along).
1885            !any.is::<ExtendedReport>()
1886                && !any.is::<Goodbye>()
1887                && !any.is::<TemporalSpatialTradeoffRequest>()
1888                && !any.is::<TemporalSpatialTradeoffNotification>()
1889        })
1890    }
1891
1892    /// RFC 4585 3.5.2: feedback was detected at `now`.
1893    fn schedule_feedback(&mut self, now: Instant) {
1894        if !self.has_feedback() || self.profile == RtcpProfile::Avp {
1895            // Without AVPF, feedback rides the next regular packet.
1896            return;
1897        }
1898        // Step 2: a packet with feedback is already scheduled; this joins it.
1899        if self.early_at.is_some() {
1900            return;
1901        }
1902        let media = self
1903            .pending
1904            .iter()
1905            .find_map(|packet| sender_and_media(packet.as_ref()).1);
1906        let Some(index) = self.feedback_source(media) else {
1907            return;
1908        };
1909        let Some(timing) = self.locals[index].timing else {
1910            return;
1911        };
1912        // Step 2b: no dither between two parties, half the regular interval among more.
1913        let t_dither_max = if self.is_point_to_point() {
1914            0.0
1915        } else {
1916            0.5 * seconds_between(timing.tp, timing.tn).max(0.0)
1917        };
1918        // Step 3: the regular packet is due within the dither; step 4a: no early packet is
1919        // allowed. Either way the feedback is stored for the regular packet at tn.
1920        if after(now, t_dither_max) > timing.tn || !timing.allow_early {
1921            return;
1922        }
1923        // Step 4b.
1924        let te = after(now, self.unit() * t_dither_max);
1925        if te <= now {
1926            self.send_early(now, index);
1927        } else {
1928            self.early_at = Some(te);
1929        }
1930    }
1931
1932    /// RFC 6051 section 3.2: an SR from the local SSRC `index` as soon as RFC 4585 3.5.2
1933    /// allows, in an Early packet (a regular one due within the dither carries it anyway,
1934    /// as does the next regular one when no Early packet is allowed now). Under RTP/AVP
1935    /// there is no Early packet; nor is there an SR to give for an SSRC that has not sent.
1936    fn request_sender_report(&mut self, now: Instant, index: usize) {
1937        if self.profile == RtcpProfile::Avp || !self.we_sent(index, now) {
1938            return;
1939        }
1940        let Some(timing) = self.locals[index].timing else {
1941            return;
1942        };
1943        self.sender_report_requested = Some(index);
1944        if self.early_at.is_some() {
1945            return;
1946        }
1947        let t_dither_max = if self.is_point_to_point() {
1948            0.0
1949        } else {
1950            0.5 * seconds_between(timing.tp, timing.tn).max(0.0)
1951        };
1952        if after(now, t_dither_max) > timing.tn || !timing.allow_early {
1953            self.sender_report_requested = None;
1954            return;
1955        }
1956        let te = after(now, self.unit() * t_dither_max);
1957        if te <= now {
1958            self.sender_report_requested = None;
1959            self.send_early(now, index);
1960        } else {
1961            self.early_at = Some(te);
1962        }
1963    }
1964
1965    // ---- building packets ------------------------------------------------------------
1966
1967    fn sdes_chunk(&self, ssrc: u32) -> SourceDescriptionChunk {
1968        let mut items = vec![SourceDescriptionItem {
1969            sdes_type: SdesType::SdesCname,
1970            text: self.cname.clone().into(),
1971        }];
1972        if let Some(identifiers) = self.identifiers.get(&ssrc) {
1973            items.extend(identifiers.iter().cloned());
1974        }
1975        SourceDescriptionChunk {
1976            source: ssrc,
1977            items,
1978        }
1979    }
1980
1981    /// The SR of a local SSRC that sent lately, its RR otherwise (RFC 3550 6.4).
1982    fn report(
1983        &mut self,
1984        index: usize,
1985        now: Instant,
1986        blocks: Vec<ReceptionReport>,
1987    ) -> Box<dyn rtcp::Packet> {
1988        let we_sent = self.we_sent(index, now);
1989        let local = &mut self.locals[index];
1990        local.rtcp_sent = true;
1991        if we_sent && let Some(mut report) = local.stream.generate_report(now) {
1992            local
1993                .sent_reports
1994                .push_back(((report.ntp_time >> 16) as u32, now));
1995            while local.sent_reports.len() > 8 {
1996                local.sent_reports.pop_front();
1997            }
1998            report.reports = blocks;
1999            boxed(report)
2000        } else {
2001            boxed(ReceiverReport {
2002                ssrc: local.ssrc,
2003                reports: blocks,
2004                ..Default::default()
2005            })
2006        }
2007    }
2008
2009    /// The report blocks of this interval: up to `max` remote streams, taken round robin so
2010    /// that each is reported in turn when they do not all fit (RFC 3550 6.1).
2011    ///
2012    /// When they do not all fit, streams losing [`HIGH_LOSS_FRACTION`] or more since their
2013    /// last report go first, the worst first, in up to half of the blocks (RFC 8083 section
2014    /// 4.3: "priority SHOULD be given to reports on sources that have high packet loss
2015    /// rates"); the other half stays round robin, so every stream is still reported in turn.
2016    fn report_blocks(&mut self, now: Instant, max: usize) -> Vec<ReceptionReport> {
2017        let candidates: Vec<u32> = self
2018            .remote_order
2019            .iter()
2020            .copied()
2021            .filter(|ssrc| {
2022                self.remotes
2023                    .get(ssrc)
2024                    .is_some_and(|remote| !remote.gone && remote.stream.has_received())
2025            })
2026            .collect();
2027        if candidates.is_empty() || max == 0 {
2028            return vec![];
2029        }
2030        let mut chosen: Vec<u32> = Vec::new();
2031        if candidates.len() > max {
2032            let mut lossy: Vec<(u8, u32)> = candidates
2033                .iter()
2034                .filter_map(|ssrc| {
2035                    let loss = self.remotes.get(ssrc)?.stream.pending_fraction_lost();
2036                    (loss >= HIGH_LOSS_FRACTION).then_some((loss, *ssrc))
2037                })
2038                .collect();
2039            lossy.sort_by_key(|(loss, _)| std::cmp::Reverse(*loss));
2040            chosen.extend(lossy.iter().take(max / 2).map(|(_, ssrc)| *ssrc));
2041        }
2042        let rest: Vec<u32> = candidates
2043            .iter()
2044            .copied()
2045            .filter(|ssrc| !chosen.contains(ssrc))
2046            .collect();
2047        if !rest.is_empty() {
2048            let count = rest.len().min(max - chosen.len());
2049            let start = self.report_cursor % rest.len();
2050            self.report_cursor = (start + count) % rest.len();
2051            chosen.extend((0..count).map(|offset| rest[(start + offset) % rest.len()]));
2052        }
2053        chosen
2054            .into_iter()
2055            .filter_map(|ssrc| {
2056                self.remotes
2057                    .get_mut(&ssrc)
2058                    .map(|remote| remote.stream.generate_reception_report(now))
2059            })
2060            .collect()
2061    }
2062
2063    /// RFC 3611 section 5.1: the maximum DLRR size a stream's `rcvr-rtt=<mode>:<max>` names
2064    /// (an `rrtr` feedback whose parameter is the `xr-format` as signalled).
2065    fn record_dlrr_limit(&mut self, info: &StreamInfo) {
2066        let limit = info
2067            .rtcp_feedback
2068            .iter()
2069            .filter(|feedback| feedback.typ == crate::RTCP_FB_RRTR)
2070            .filter_map(|feedback| dlrr_limit(&feedback.parameter))
2071            .min();
2072        match limit {
2073            Some(limit) => self.dlrr_limits.insert(info.ssrc, limit),
2074            None => self.dlrr_limits.remove(&info.ssrc),
2075        };
2076    }
2077
2078    /// The XR packet of a regular report: a receiver reference time when a bound stream
2079    /// negotiated it, and a DLRR block answering the reference times received (RFC 3611 4.4,
2080    /// 4.5) when a local SSRC sends.
2081    fn extended_report(
2082        &mut self,
2083        now: Instant,
2084        ssrc: u32,
2085        any_sender: bool,
2086        budget: usize,
2087    ) -> Option<ExtendedReport> {
2088        let mut blocks: Vec<Box<dyn rtcp::Packet>> = vec![];
2089        if self
2090            .remotes
2091            .values()
2092            .any(|remote| remote.rrtr && !remote.gone)
2093        {
2094            let wall_clock = *self
2095                .wall_clock
2096                .get_or_insert_with(|| SystemInstant::shared(now));
2097            blocks.push(Box::new(ReceiverReferenceTimeReportBlock {
2098                ntp_timestamp: wall_clock.ntp(now),
2099            }));
2100        }
2101        // RFC 3611 section 5.1: "non RTP senders SHALL NOT send DLRR blocks" under
2102        // `rcvr-rtt=sender`; under `all` they MAY, and this endpoint does not. A DLRR block is
2103        // no larger than the signalled maximum: the reference times that do not fit wait for
2104        // the next report, oldest first ("in a round robin fashion across several report
2105        // intervals").
2106        if any_sender && !self.reference_times.is_empty() {
2107            let fit = self
2108                .dlrr_limits
2109                .values()
2110                .min()
2111                .map_or(usize::MAX, |octets| octets.saturating_sub(4) / 12)
2112                .max(1);
2113            let mut waiting: Vec<(u32, (u32, Instant))> =
2114                self.reference_times.iter().map(|(k, v)| (*k, *v)).collect();
2115            waiting.sort_by_key(|(ssrc, (_, arrived))| (*arrived, *ssrc));
2116            let reports = waiting
2117                .into_iter()
2118                .take(fit)
2119                .map(|(ssrc, (last_rr, arrived))| {
2120                    self.reference_times.remove(&ssrc);
2121                    DLRRReport {
2122                        ssrc,
2123                        last_rr,
2124                        dlrr: (now.saturating_duration_since(arrived).as_secs_f64() * 65536.0)
2125                            as u64 as u32,
2126                    }
2127                })
2128                .collect();
2129            blocks.push(Box::new(DLRRReportBlock { reports }));
2130        }
2131        // RFC 6679 7.3.2: "Every time a regular compound RTCP packet is to be transmitted, an
2132        // ECN-capable RTP receiver MUST include an RTCP XR ECN Summary Report"; section 5.2:
2133        // the SSRCs reported as senders are in it, and with none the block "SHALL still be
2134        // sent with no report block entry and a zero report block length".
2135        if self
2136            .remotes
2137            .values()
2138            .any(|remote| remote.ecn_summary && !remote.gone)
2139        {
2140            let mut reports: Vec<EcnSummaryReport> = self
2141                .remote_order
2142                .iter()
2143                .filter_map(|ssrc| {
2144                    let remote = self.remotes.get(ssrc)?;
2145                    let tally = remote.ecn.as_deref()?;
2146                    (remote.ecn_summary && !remote.gone && tally.heard()).then(|| {
2147                        EcnSummaryReport {
2148                            ssrc: *ssrc,
2149                            counters: tally.counters(),
2150                        }
2151                    })
2152                })
2153                .collect();
2154            // RFC 6679 section 5.2: "If the RTCP SR or RR packet and the XR ECN summary
2155            // report together exceed the MTU, a subset of the senders is reported, chosen in a
2156            // round-robin fashion" across the compound packets. Room is what the compound
2157            // packet has left after the XR header and the blocks before this one; one entry
2158            // goes at least. One XR block's length field counts at most 65535 words.
2159            let used = 8 + blocks.iter().map(|b| b.marshal_size()).sum::<usize>() + 4;
2160            let fit = (budget.saturating_sub(used) / 20)
2161                .max(1)
2162                .min(usize::from(u16::MAX) / 5);
2163            if reports.len() > fit {
2164                let start = self.ecn_summary_next % reports.len();
2165                reports.rotate_left(start);
2166                reports.truncate(fit);
2167                self.ecn_summary_next = start + fit;
2168            } else {
2169                self.ecn_summary_next = 0;
2170            }
2171            blocks.push(Box::new(EcnSummaryReportBlock { reports }));
2172        }
2173        (!blocks.is_empty()).then_some(ExtendedReport {
2174            sender_ssrc: ssrc,
2175            reports: blocks,
2176        })
2177    }
2178
2179    /// The octets an XR ECN Summary Report about the senders heard takes, at most `limit`
2180    /// (one entry at least): 0 when no remote negotiated the summary.
2181    fn ecn_summary_reserve(&self, limit: usize) -> usize {
2182        let wanted = self
2183            .remotes
2184            .values()
2185            .any(|remote| remote.ecn_summary && !remote.gone);
2186        if !wanted {
2187            return 0;
2188        }
2189        let senders = self
2190            .remotes
2191            .values()
2192            .filter(|remote| {
2193                remote.ecn_summary
2194                    && !remote.gone
2195                    && remote.ecn.as_deref().is_some_and(|t| t.heard())
2196            })
2197            .count();
2198        // XR header, block header, 20 octets an entry.
2199        let entries = senders.min(limit.saturating_sub(12) / 20).max(1);
2200        12 + 20 * entries
2201    }
2202
2203    /// RFC 7728 sections 6.3, 8.2 ([`RepeatInRegularReports`]): a copy of each armed
2204    /// repetition into this Regular compound packet, as far as `budget` goes; a repetition
2205    /// that does not fit waits for the next Regular packet.
2206    fn take_repeats(&mut self, packets: &mut Vec<Box<dyn rtcp::Packet>>, budget: &mut usize) {
2207        for repeat in self.repeats.iter_mut().filter(|repeat| repeat.armed) {
2208            let size: usize = repeat.packets.iter().map(|p| p.marshal_size()).sum();
2209            if size > *budget {
2210                continue;
2211            }
2212            *budget -= size;
2213            packets.extend(repeat.packets.iter().map(|p| p.cloned()));
2214            repeat.left = repeat.left.saturating_sub(1);
2215        }
2216        self.repeats.retain(|repeat| repeat.left > 0);
2217    }
2218
2219    /// Moves what is waiting into `packets`, as far as `budget` octets go. What does not fit
2220    /// waits for the next packet; a packet too large for any compound packet goes anyway.
2221    fn take_pending(&mut self, packets: &mut Vec<Box<dyn rtcp::Packet>>, budget: &mut usize) {
2222        /// A report without blocks and an SDES with one CNAME: what a minimal compound
2223        /// packet spends before its feedback.
2224        const MINIMAL_OVERHEAD: usize = 64;
2225        let mut kept = vec![];
2226        for packet in std::mem::take(&mut self.pending) {
2227            let size = packet.marshal_size();
2228            if size <= *budget || size + MINIMAL_OVERHEAD > self.mtu {
2229                *budget = budget.saturating_sub(size);
2230                packets.push(packet);
2231            } else {
2232                kept.push(packet);
2233            }
2234        }
2235        self.pending = kept;
2236    }
2237
2238    /// Builds and sends a compound packet led by the local SSRC `first`.
2239    ///
2240    /// `Shape::Full` aggregates the other local SSRCs (RFC 8108 5.3.2) and returns the
2241    /// indices of those that reported; `Shape::Minimal` carries the leading report alone.
2242    fn send_compound(&mut self, now: Instant, first: usize, shape: Shape) -> Vec<usize> {
2243        let mut budget = self.mtu;
2244        // RFC 7160 section 4.1: after a clock rate switch the packet leads with the report of
2245        // the SSRC now in use, and the SRs of the other clock rates' SSRCs follow it. The SSRC
2246        // whose timer brought the packet is in it as well.
2247        let switch = self
2248            .clock_rate_switch
2249            .take()
2250            .and_then(|(current, previous)| {
2251                let lead = self.local_index(current)?;
2252                let previous: Vec<usize> = previous
2253                    .iter()
2254                    .filter_map(|ssrc| self.local_index(*ssrc))
2255                    .filter(|&index| index != lead && self.we_sent(index, now))
2256                    .collect();
2257                Some((lead, previous))
2258            });
2259        let (first, switched): (usize, Vec<usize>) = match switch {
2260            Some((lead, mut previous)) => {
2261                if first != lead && !previous.contains(&first) {
2262                    previous.push(first);
2263                }
2264                (lead, previous)
2265            }
2266            None => (first, vec![]),
2267        };
2268        let mut included = vec![first];
2269        let mut reports: Vec<Box<dyn rtcp::Packet>> = vec![];
2270
2271        // The SDES chunk of an SSRC is 12 octets and its CNAME, padded, and its stream
2272        // identifiers: the largest one is counted for each.
2273        let chunk = self
2274            .locals
2275            .iter()
2276            .map(|local| self.sdes_chunk(local.ssrc).marshal_size())
2277            .max()
2278            .unwrap_or_else(|| self.sdes_chunk(0).marshal_size());
2279        let block = 24;
2280
2281        let reporter = self.reporter();
2282        let mut blocks = vec![];
2283        if shape == Shape::Full {
2284            // What is left for report blocks once every participant's report and CNAME are
2285            // in: the streams that do not fit are reported next time (RFC 3550 6.1).
2286            let participants = self.locals.iter().filter(|l| l.participates()).count();
2287            // RFC 6679 section 5.2: the reports and the ECN summary share the MTU; the summary
2288            // is given room for its senders, up to half the packet, before the blocks are sized.
2289            let summary_reserve = self.ecn_summary_reserve(budget / 2);
2290            let room =
2291                budget.saturating_sub(participants * (28 + chunk) + 4 + summary_reserve) / block;
2292            blocks = self.report_blocks(now, room.max(1));
2293        }
2294        // RFC 3550 6.1: a report carries 31 blocks; further ones follow in additional RR
2295        // packets from the same SSRC.
2296        let overflow: Vec<ReceptionReport> = if blocks.len() > MAX_REPORT_BLOCKS {
2297            blocks.split_off(MAX_REPORT_BLOCKS)
2298        } else {
2299            vec![]
2300        };
2301        let every = self.report_from_every_ssrc;
2302        let carries_blocks =
2303            move |index: usize| every || Some(index) == reporter || reporter.is_none();
2304        let first_blocks = if carries_blocks(first) {
2305            blocks.clone()
2306        } else {
2307            vec![]
2308        };
2309        let report = self.report(first, now, first_blocks);
2310        budget = budget.saturating_sub(report.marshal_size() + 4 + chunk);
2311        reports.push(report);
2312        // The other clock rates' reports (and the SSRC whose timer this is) right behind the
2313        // leader, whatever the shape.
2314        for &index in &switched {
2315            let own_blocks = if carries_blocks(index) {
2316                blocks.clone()
2317            } else {
2318                vec![]
2319            };
2320            let report = self.report(index, now, own_blocks);
2321            budget = budget.saturating_sub(report.marshal_size() + chunk);
2322            reports.push(report);
2323            included.push(index);
2324        }
2325
2326        if shape == Shape::Full {
2327            // RFC 8108 5.3.2: the other SSRCs, in the order their timers would expire, as
2328            // long as their reports fit.
2329            let mut others: Vec<usize> = (0..self.locals.len())
2330                .filter(|&index| {
2331                    !included.contains(&index)
2332                        && self.locals[index].participates()
2333                        && self.locals[index].timing.is_some()
2334                })
2335                .collect();
2336            others.sort_by_key(|&index| self.locals[index].timing.map(|timing| timing.tn));
2337            // The SSRC that carries the blocks reports right behind the leader.
2338            if let Some(reporter) = reporter
2339                && let Some(position) = others.iter().position(|&index| index == reporter)
2340            {
2341                let reporter = others.remove(position);
2342                others.insert(0, reporter);
2343            }
2344            for index in others {
2345                let own_blocks = if carries_blocks(index) {
2346                    blocks.clone()
2347                } else {
2348                    vec![]
2349                };
2350                let size = 28 + block * own_blocks.len() + chunk;
2351                if size > budget && Some(index) != reporter {
2352                    // It keeps its own timer and reports when that expires.
2353                    continue;
2354                }
2355                let report = self.report(index, now, own_blocks);
2356                budget = budget.saturating_sub(report.marshal_size() + chunk);
2357                reports.push(report);
2358                included.push(index);
2359            }
2360        }
2361
2362        let mut packets = reports;
2363        if !overflow.is_empty() {
2364            let ssrc = self.locals[reporter.filter(|r| included.contains(r)).unwrap_or(first)].ssrc;
2365            // Behind the report of the SSRC they continue.
2366            let position = packets
2367                .iter()
2368                .position(|packet| sender_and_media(packet.as_ref()).0 == Some(ssrc))
2369                .map_or(packets.len(), |position| position + 1);
2370            for (offset, chunk) in overflow.chunks(MAX_REPORT_BLOCKS).enumerate() {
2371                let more = boxed(ReceiverReport {
2372                    ssrc,
2373                    reports: chunk.to_vec(),
2374                    ..Default::default()
2375                });
2376                budget = budget.saturating_sub(more.marshal_size());
2377                packets.insert(position + offset, more);
2378            }
2379        }
2380        packets.push(boxed(SourceDescription {
2381            chunks: included
2382                .iter()
2383                .map(|&index| self.sdes_chunk(self.locals[index].ssrc))
2384                .collect(),
2385        }));
2386
2387        if shape == Shape::Full {
2388            let any_sender = included.iter().any(|&index| self.we_sent(index, now));
2389            let ssrc = self.locals[reporter.filter(|r| included.contains(r)).unwrap_or(first)].ssrc;
2390            if let Some(xr) = self.extended_report(now, ssrc, any_sender, budget) {
2391                budget = budget.saturating_sub(xr.marshal_size());
2392                packets.push(boxed(xr));
2393            }
2394        }
2395
2396        if shape == Shape::Full {
2397            self.take_repeats(&mut packets, &mut budget);
2398        }
2399        self.take_pending(&mut packets, &mut budget);
2400        // The originals of the repetitions not yet armed left with this packet (everything
2401        // pending is taken): the Regular packets after it carry the copies.
2402        for repeat in &mut self.repeats {
2403            repeat.armed = true;
2404        }
2405        self.early_at = None;
2406        self.compound_sent = true;
2407        self.send(now, packets);
2408        included
2409    }
2410
2411    /// Congestion control feedback leaves now, outside RFC 4585's Early allowance and the
2412    /// regular timing (see [`RtcpSessionBuilder::with_immediate_congestion_feedback`]):
2413    /// reduced-size where negotiated, else in a minimal compound packet; whatever other
2414    /// feedback is waiting goes with it.
2415    fn send_congestion_feedback(&mut self, now: Instant) {
2416        let media = self
2417            .pending
2418            .iter()
2419            .find_map(|packet| sender_and_media(packet.as_ref()).1);
2420        let Some(index) = self.feedback_source(media) else {
2421            return;
2422        };
2423        if self.locals[index].timing.is_none() {
2424            return;
2425        }
2426        let reduced = self.reduced_size
2427            && self.compound_sent
2428            && !self.reduced_size_failed
2429            && self
2430                .pending
2431                .iter()
2432                .all(|packet| delivery_shows(packet.as_ref()))
2433            && self.pending.iter().map(|p| p.marshal_size()).sum::<usize>() <= REDUCED_SIZE_MAX;
2434        self.outside_budget = true;
2435        if reduced {
2436            self.note_reduced_nack();
2437            let packets = std::mem::take(&mut self.pending);
2438            self.send(now, packets);
2439        } else {
2440            self.send_compound(now, index, Shape::Minimal);
2441        }
2442        self.outside_budget = false;
2443        if self.pending.is_empty() {
2444            self.early_at = None;
2445        }
2446    }
2447
2448    /// RFC 4585 3.5.2 step 6: the Early packet goes, from the local SSRC `index`.
2449    fn send_early(&mut self, now: Instant, index: usize) {
2450        let reduced = self.reduced_size
2451            && self.compound_sent
2452            && !self.reduced_size_failed
2453            && self
2454                .pending
2455                .iter()
2456                .all(|packet| delivery_shows(packet.as_ref()))
2457            && self.pending.iter().map(|p| p.marshal_size()).sum::<usize>() <= REDUCED_SIZE_MAX;
2458
2459        if reduced {
2460            self.note_reduced_nack();
2461            let packets = std::mem::take(&mut self.pending);
2462            self.early_at = None;
2463            self.send(now, packets);
2464        } else {
2465            self.send_compound(now, index, Shape::Minimal);
2466        }
2467        if let Some(timing) = self.locals[index].timing.as_mut() {
2468            timing.early_sent();
2469        }
2470    }
2471
2472    /// RFC 5506 4.2.1: watches whether reduced-size NACKs get an answer. A run of them with
2473    /// none of the requested packets arriving means they do not get through, and the session
2474    /// goes back to compound packets.
2475    fn note_reduced_nack(&mut self) {
2476        let Some(nack) = self
2477            .pending
2478            .iter()
2479            .find_map(|packet| packet.as_any().downcast_ref::<TransportLayerNack>())
2480        else {
2481            return;
2482        };
2483        if self.awaited.is_some() {
2484            self.unanswered_reduced_nacks += 1;
2485            if self.unanswered_reduced_nacks >= REDUCED_SIZE_UNANSWERED_LIMIT {
2486                self.reduced_size_failed = true;
2487            }
2488        }
2489        self.awaited = Some((
2490            nack.media_ssrc,
2491            nack.nacks
2492                .iter()
2493                .flat_map(|pair| pair.packet_list())
2494                .collect(),
2495        ));
2496    }
2497
2498    /// RFC 3550 6.6 and 6.3.7: the local SSRCs that were unbound say BYE, each behind its
2499    /// last report, unless they never sent anything.
2500    fn flush_departing(&mut self, now: Instant) {
2501        if self.departing.is_empty() {
2502            return;
2503        }
2504        let departing = std::mem::take(&mut self.departing);
2505        let mut reports: Vec<Box<dyn rtcp::Packet>> = vec![];
2506        let mut chunks = vec![];
2507        let mut sources = vec![];
2508        for mut local in departing {
2509            self.collided.remove(&local.ssrc);
2510            // "A participant which never sent an RTP or RTCP packet MUST NOT send a BYE."
2511            if !local.rtp_sent && !local.rtcp_sent {
2512                continue;
2513            }
2514            let horizon = 2.0 * self.report_interval(now);
2515            let was_sender = local
2516                .last_rtp
2517                .is_some_and(|last| now.saturating_duration_since(last).as_secs_f64() <= horizon);
2518            match local.stream.generate_report(now).filter(|_| was_sender) {
2519                Some(report) => reports.push(boxed(report)),
2520                None => reports.push(boxed(ReceiverReport {
2521                    ssrc: local.ssrc,
2522                    ..Default::default()
2523                })),
2524            }
2525            chunks.push(self.sdes_chunk(local.ssrc));
2526            sources.push(local.ssrc);
2527        }
2528        if sources.is_empty() {
2529            return;
2530        }
2531        let mut packets = reports;
2532        packets.push(boxed(SourceDescription { chunks }));
2533        packets.push(boxed(Goodbye {
2534            sources,
2535            reason: Default::default(),
2536        }));
2537
2538        if self.member_count() >= BYE_BACKOFF_MEMBERS && !self.left {
2539            // RFC 3550 6.3.7: in a large session the BYE takes its turn.
2540            let size = (wire_size(&packets) + self.srtcp_overhead) as f64;
2541            let mut input = self.interval_input(now, false, true, 0);
2542            input.members = 1;
2543            input.avg_rtcp_size = size;
2544            let t = randomized_interval(deterministic_interval(&input), self.unit());
2545            self.bye = Some(ByeBackoff {
2546                packets,
2547                size,
2548                tp: now,
2549                tn: after(now, t),
2550                members: 1,
2551            });
2552        } else if self.member_count() < BYE_BACKOFF_MEMBERS {
2553            self.compound_sent = true;
2554            self.send(now, packets);
2555        }
2556        // Leaving a session of more than fifty members at once: without a BYE (6.3.7 allows
2557        // it), since the transport does not outlive the back-off.
2558    }
2559
2560    // ---- the timers ------------------------------------------------------------------
2561
2562    /// RFC 3550 6.3.6 (with RFC 4585 3.5.3 and RFC 8108 5.3.2): works through every timer
2563    /// that expired by `now`.
2564    fn run_timers(&mut self, now: Instant) {
2565        if !self.started {
2566            return;
2567        }
2568        self.time_out_members(now);
2569
2570        if let Some(te) = self.early_at
2571            && te <= now
2572        {
2573            let media = self
2574                .pending
2575                .iter()
2576                .find_map(|packet| sender_and_media(packet.as_ref()).1);
2577            match (
2578                self.feedback_source(media),
2579                self.sender_report_requested.take(),
2580            ) {
2581                (Some(index), _) if self.has_feedback() => self.send_early(now, index),
2582                (_, Some(index)) if index < self.locals.len() => self.send_early(now, index),
2583                _ => self.early_at = None,
2584            }
2585        }
2586
2587        self.run_bye_timer(now);
2588
2589        for _ in 0..MAX_CATCH_UP {
2590            let Some(index) = (0..self.locals.len())
2591                .filter(|&index| {
2592                    self.locals[index]
2593                        .timing
2594                        .is_some_and(|timing| timing.tn <= now)
2595                })
2596                .min_by_key(|&index| self.locals[index].timing.map(|timing| timing.tn))
2597            else {
2598                return;
2599            };
2600            let Some(mut timing) = self.locals[index].timing else {
2601                return;
2602            };
2603            // The timer expired at tn, which may be a while ago: a session nobody woke
2604            // catches up with the expiries it would have suppressed.
2605            let tc = timing.tn;
2606            let t = self.interval(index, tc);
2607            if !timing.immediate && !timing.reconsider(tc, t) {
2608                self.locals[index].timing = Some(timing);
2609                self.pmembers = self.member_count().max(1);
2610                continue;
2611            }
2612
2613            let decision = match self.profile {
2614                RtcpProfile::Avp => RegularDecision::Send,
2615                RtcpProfile::Avpf => {
2616                    let random = self.unit();
2617                    let t_rr_interval = self.effective_t_rr_interval(index, tc);
2618                    regular_decision(
2619                        t_rr_interval,
2620                        timing.t_rr_last,
2621                        tc,
2622                        random,
2623                        !self.pending.is_empty(),
2624                    )
2625                }
2626            };
2627            match decision {
2628                RegularDecision::Send => self.send_regular(now, index),
2629                RegularDecision::SendFeedbackOnly => {
2630                    self.send_compound(now, index, Shape::Minimal);
2631                    let t = self.interval(index, now);
2632                    if let Some(timing) = self.locals[index].timing.as_mut() {
2633                        timing.rescheduled(now, t);
2634                    }
2635                }
2636                RegularDecision::Suppress => {
2637                    // RFC 8108 5.3.2: "tp is updated to tc as aggregation has not taken place".
2638                    let t = self.interval(index, tc);
2639                    if let Some(timing) = self.locals[index].timing.as_mut() {
2640                        timing.rescheduled(tc, t);
2641                    }
2642                }
2643            }
2644            self.pmembers = self.member_count().max(1);
2645        }
2646
2647        // Too far behind to replay: every timer starts over from now.
2648        for index in 0..self.locals.len() {
2649            if self.locals[index].timing.is_some() {
2650                let t = self.interval(index, now);
2651                if let Some(timing) = self.locals[index].timing.as_mut() {
2652                    timing.rescheduled(now, t);
2653                }
2654            }
2655        }
2656    }
2657
2658    /// A Regular RTCP packet led by the local SSRC `first`, and the timers of every SSRC it
2659    /// carried (RFC 8108 5.3.2, steps a to d).
2660    fn send_regular(&mut self, now: Instant, first: usize) {
2661        self.sending_regular = true;
2662        let included = self.send_compound(now, first, Shape::Full);
2663        self.sending_regular = false;
2664
2665        // a. The SSRC whose timer expired transmitted at tc. b. Each SSRC aggregated with it
2666        // would have transmitted when its own timer passed reconsideration.
2667        let mut offsets = vec![0.0];
2668        for &index in included.iter().skip(1) {
2669            let Some(mut timing) = self.locals[index].timing else {
2670                continue;
2671            };
2672            for _ in 0..64 {
2673                let t = self.interval(index, now);
2674                if after(timing.tp, t) <= timing.tn {
2675                    break;
2676                }
2677                timing.tn = after(timing.tp, t);
2678            }
2679            offsets.push(seconds_between(now, timing.tn).max(0.0));
2680        }
2681        // c. tp (and T_rr_last) of all of them is the average of those times.
2682        let tt_avg = after(now, offsets.iter().sum::<f64>() / offsets.len() as f64);
2683        // d. New timers from there.
2684        for &index in &included {
2685            if let Some(timing) = self.locals[index].timing.as_mut() {
2686                timing.initial = false;
2687                timing.t_rr_last = Some(tt_avg);
2688            }
2689            let t = self.interval(index, now);
2690            if let Some(timing) = self.locals[index].timing.as_mut() {
2691                timing.rescheduled(tt_avg, t);
2692            }
2693        }
2694    }
2695
2696    /// RFC 3550 6.3.7: the BYE of a large session, sent when its own timer passes
2697    /// reconsideration against the number of BYE packets seen.
2698    fn run_bye_timer(&mut self, now: Instant) {
2699        let Some(bye) = self.bye.as_ref() else {
2700            return;
2701        };
2702        if bye.tn > now {
2703            return;
2704        }
2705        let mut input = self.interval_input(now, false, true, 0);
2706        input.members = bye.members;
2707        input.avg_rtcp_size = bye.size;
2708        let t = randomized_interval(deterministic_interval(&input), self.unit());
2709        let Some(bye) = self.bye.as_mut() else {
2710            return;
2711        };
2712        if after(bye.tp, t) <= now {
2713            let packets = std::mem::take(&mut bye.packets);
2714            self.bye = None;
2715            self.send(now, packets);
2716        } else {
2717            bye.tn = after(bye.tp, t);
2718        }
2719    }
2720
2721    fn next_timeout(&self) -> Option<Instant> {
2722        if !self.started {
2723            return None;
2724        }
2725        let feedback_waits = !self.pending.is_empty();
2726        let regular = self.locals.iter().filter_map(|local| {
2727            let timing = local.timing?;
2728            // Until T_rr_interval has passed since the last regular packet, an expiring
2729            // timer only suppresses it; there is nothing to wake up for before half of it
2730            // (the least its dither allows) unless feedback is waiting.
2731            match (self.profile, timing.t_rr_last) {
2732                (RtcpProfile::Avpf, Some(t_rr_last))
2733                    if self.t_rr_interval > 0.0 && !feedback_waits =>
2734                {
2735                    Some(timing.tn.max(after(t_rr_last, 0.5 * self.t_rr_interval)))
2736                }
2737                _ => Some(timing.tn),
2738            }
2739        });
2740        regular
2741            .chain(self.early_at)
2742            .chain(self.bye.as_ref().map(|bye| bye.tn))
2743            .min()
2744    }
2745
2746    fn control(&mut self, now: Instant, control: &RtcpSessionControl) {
2747        match control {
2748            RtcpSessionControl::Start => {
2749                if self.left {
2750                    self.rejoin();
2751                }
2752                self.start_given = true;
2753            }
2754            RtcpSessionControl::Cname(cname) => self.cname = cname.clone(),
2755            RtcpSessionControl::Bandwidth(bandwidth) => self.bandwidth = *bandwidth,
2756            RtcpSessionControl::ReducedSize(reduced_size) => self.reduced_size = *reduced_size,
2757            RtcpSessionControl::SrtcpOverhead(overhead) => {
2758                // Given after the session started (any control starts it), the average moves
2759                // by the difference: an average of sizes that each carry the overhead is the
2760                // average of the sizes plus the overhead.
2761                if self.started {
2762                    self.avg_rtcp_size += *overhead as f64 - self.srtcp_overhead as f64;
2763                }
2764                self.srtcp_overhead = *overhead;
2765            }
2766            RtcpSessionControl::TrrInt(t_rr_interval) => {
2767                self.t_rr_interval = t_rr_interval.as_secs_f64();
2768            }
2769            RtcpSessionControl::TrrIntCleared => {
2770                self.t_rr_interval = self.configured_t_rr_interval;
2771            }
2772            RtcpSessionControl::StreamIdentifiers {
2773                ssrc,
2774                mid,
2775                rid,
2776                repaired_rid,
2777            } => {
2778                let items: Vec<SourceDescriptionItem> = [
2779                    (SdesType::SdesMid, mid),
2780                    (SdesType::SdesRtpStreamId, rid),
2781                    (SdesType::SdesRepairedRtpStreamId, repaired_rid),
2782                ]
2783                .into_iter()
2784                // An SDES item holds at most 255 octets (RFC 3550 section 6.5).
2785                .filter_map(|(sdes_type, value)| {
2786                    value
2787                        .as_ref()
2788                        .filter(|value| !value.is_empty() && value.len() <= 255)
2789                        .map(|value| SourceDescriptionItem {
2790                            sdes_type,
2791                            text: value.clone().into(),
2792                        })
2793                })
2794                .collect();
2795                // Only the streams the session still has keep theirs.
2796                let (locals, departing) = (&self.locals, &self.departing);
2797                self.identifiers.retain(|kept, _| {
2798                    locals
2799                        .iter()
2800                        .chain(departing)
2801                        .any(|local| local.ssrc == *kept)
2802                });
2803                if items.is_empty() {
2804                    self.identifiers.remove(ssrc);
2805                } else {
2806                    self.identifiers.insert(*ssrc, items);
2807                }
2808            }
2809            RtcpSessionControl::ClockRateSwitch { current, previous } => {
2810                self.clock_rate_switch = Some((*current, previous.clone()));
2811            }
2812            RtcpSessionControl::StopRepeating { key } => {
2813                self.repeats.retain(|repeat| repeat.key != *key);
2814            }
2815            RtcpSessionControl::Leave => {
2816                // A session that joins on `Start` and was not given it has not joined: there
2817                // is nothing to leave.
2818                if !self.may_join() || self.left {
2819                    return;
2820                }
2821                self.start_given = false;
2822                // RFC 3550 6.6: every SSRC of an endpoint that leaves says BYE.
2823                self.sync(now);
2824                self.left = true;
2825                self.departing.append(&mut self.locals);
2826                self.pending.clear();
2827                self.repeats.clear();
2828                self.early_at = None;
2829                self.flush_departing(now);
2830                return;
2831            }
2832        }
2833        self.sync(now);
2834    }
2835}
2836
2837impl Protocol<TaggedPacket, TaggedPacket, ()> for RtcpSessionInterceptor {
2838    type Rout = TaggedPacket;
2839    type Wout = TaggedPacket;
2840    type Eout = ();
2841    type Error = Error;
2842    type Time = Instant;
2843
2844    fn handle_read(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
2845        let now = msg.now;
2846        self.sync(now);
2847        let pass = match &msg.message.packet {
2848            Packet::Rtp(_) => self.observe_rtp(now, &msg.message, msg.transport.ecn),
2849            Packet::Rtcp(packets) => {
2850                self.observe_rtcp(now, packets);
2851                true
2852            }
2853        };
2854        if pass {
2855            self.read_queue.push_back(msg);
2856        }
2857        Ok(())
2858    }
2859
2860    fn poll_read(&mut self) -> Option<Self::Rout> {
2861        self.read_queue.pop_front()
2862    }
2863
2864    fn handle_write(&mut self, mut msg: TaggedPacket) -> Result<(), Self::Error> {
2865        let now = msg.now;
2866
2867        if let Some(control) = msg.message.custom::<RtcpSessionControl>().cloned() {
2868            self.control(now, &control);
2869            msg.message.attributes.retain(|attribute| {
2870                !matches!(attribute, Attribute::Custom(value) if value.is::<RtcpSessionControl>())
2871            });
2872            if msg.message.attributes.is_empty()
2873                && matches!(&msg.message.packet, Packet::Rtcp(packets) if packets.is_empty())
2874            {
2875                return Ok(());
2876            }
2877        }
2878        if self.left || !self.may_join() {
2879            // After the BYE nothing more is said (RFC 3550 6.1: BYE is the last packet), and
2880            // before the session joins there is no RTP session to say it in.
2881            if matches!(msg.message.packet, Packet::Rtp(_)) {
2882                self.write_queue.push_back(msg);
2883            }
2884            return Ok(());
2885        }
2886        self.sync(now);
2887
2888        let repeat = msg.message.custom::<RepeatInRegularReports>().copied();
2889        match msg.message.packet {
2890            Packet::Rtp(ref packet) => {
2891                if let Some(index) = self.local_index(packet.header.ssrc) {
2892                    let local = &mut self.locals[index];
2893                    local.stream.process_rtp(now, packet);
2894                    local.last_rtp = Some(now);
2895                    local.rtp_sent = true;
2896                    self.rate
2897                        .add(now, packet.header.marshal_size() + packet.payload.len());
2898                    // A repair SSRC joins with its first packet.
2899                    self.sync(now);
2900                }
2901                self.write_queue.push_back(msg);
2902            }
2903            // An attribute carrier (see `Packet::Rtcp`): not the session's.
2904            Packet::Rtcp(ref packets) if packets.is_empty() => {
2905                self.write_queue.push_back(msg);
2906            }
2907            Packet::Rtcp(packets) => {
2908                let congestion_feedback = !packets.is_empty()
2909                    && packets.iter().all(|packet| {
2910                        let any = packet.as_any();
2911                        any.is::<TransportLayerCc>() || any.is::<CcFeedbackReport>()
2912                    });
2913                if let Some(repeat) = repeat {
2914                    self.repeats.retain(|held| held.key != repeat.key);
2915                    if repeat.count > 0 {
2916                        self.repeats.push(Repeat {
2917                            key: repeat.key,
2918                            packets: packets.iter().map(|packet| packet.cloned()).collect(),
2919                            left: repeat.count,
2920                            armed: false,
2921                        });
2922                    }
2923                }
2924                for packet in packets {
2925                    self.adopt(packet);
2926                }
2927                self.run_timers(now);
2928                if congestion_feedback && self.immediate_congestion_feedback {
2929                    self.send_congestion_feedback(now);
2930                }
2931                self.schedule_feedback(now);
2932            }
2933        }
2934        Ok(())
2935    }
2936
2937    fn poll_write(&mut self) -> Option<Self::Wout> {
2938        self.write_queue.pop_front()
2939    }
2940
2941    fn handle_timeout(&mut self, now: Self::Time) -> Result<(), Self::Error> {
2942        if !self.started || self.left {
2943            return Ok(());
2944        }
2945        self.sync(now);
2946        self.run_timers(now);
2947        Ok(())
2948    }
2949
2950    fn poll_timeout(&mut self) -> Option<Self::Time> {
2951        self.next_timeout()
2952    }
2953}
2954
2955impl Interceptor for RtcpSessionInterceptor {
2956    /// A stream this endpoint sends: its SSRC reports from now on, and its RTX and FEC SSRCs
2957    /// from their first packet. A stream unbound a moment ago and bound again with the same
2958    /// SSRC (a renegotiation) carries on: no BYE, and its counts are kept.
2959    fn bind_local_stream(&mut self, info: &StreamInfo) {
2960        self.record_dlrr_limit(info);
2961        let kind = Kind::of(&info.mime_type);
2962        let sources = std::iter::once((info.ssrc, Role::Media))
2963            .chain(info.ssrc_rtx.map(|ssrc| (ssrc, Role::Repair)))
2964            .chain(info.ssrc_fec.map(|ssrc| (ssrc, Role::Repair)));
2965        for (ssrc, role) in sources {
2966            // The media SSRC may carry the section's other formats (RFC 7160, one SSRC).
2967            let rates: &[(u8, u32)] = if role == Role::Media {
2968                &info.payload_clock_rates
2969            } else {
2970                &[]
2971            };
2972            if let Some(index) = self.local_index(ssrc) {
2973                self.locals[index].stream.set_clock_rate(info.clock_rate);
2974                self.locals[index].stream.set_payload_clock_rates(rates);
2975                continue;
2976            }
2977            let mut local = match self.departing.iter().position(|local| local.ssrc == ssrc) {
2978                Some(position) => {
2979                    let mut local = self.departing.remove(position);
2980                    local.stream.set_clock_rate(info.clock_rate);
2981                    local.kind = kind;
2982                    local.role = role;
2983                    local
2984                }
2985                None => Local::new(ssrc, kind, role, info.clock_rate, self.wall_clock),
2986            };
2987            local.stream.set_payload_clock_rates(rates);
2988            self.locals.push(local);
2989        }
2990        self.sync_reporter();
2991    }
2992
2993    /// The stream stopped: its SSRCs say BYE the next time the chain is driven, unless they
2994    /// are bound again first.
2995    fn unbind_local_stream(&mut self, info: &StreamInfo) {
2996        self.dlrr_limits.remove(&info.ssrc);
2997        for ssrc in std::iter::once(info.ssrc)
2998            .chain(info.ssrc_rtx)
2999            .chain(info.ssrc_fec)
3000        {
3001            if let Some(index) = self.local_index(ssrc) {
3002                let local = self.locals.remove(index);
3003                self.departing.push(local);
3004            }
3005        }
3006    }
3007
3008    /// A stream moving to another RTP session is not leaving: its SSRCs go from this
3009    /// session's members without the BYE `unbind_local_stream` sends (RFC 3550 6.6 is for a
3010    /// source that leaves the session; this one carries on in the other session, and this
3011    /// session's transport is going away or no longer carries it).
3012    fn move_local_stream_out(&mut self, info: &StreamInfo) {
3013        self.dlrr_limits.remove(&info.ssrc);
3014        for ssrc in std::iter::once(info.ssrc)
3015            .chain(info.ssrc_rtx)
3016            .chain(info.ssrc_fec)
3017        {
3018            if let Some(index) = self.local_index(ssrc) {
3019                self.locals.remove(index);
3020            }
3021        }
3022    }
3023
3024    fn bind_remote_stream(&mut self, info: &StreamInfo) {
3025        self.record_dlrr_limit(info);
3026        let rrtr = info
3027            .rtcp_feedback
3028            .iter()
3029            .any(|feedback| feedback.typ == crate::RTCP_FB_RRTR);
3030        let (ecn_feedback, ecn_summary) = negotiated_ecn_feedback(info);
3031        match self.remotes.get_mut(&info.ssrc) {
3032            Some(remote) => {
3033                remote.ecn_feedback = ecn_feedback;
3034                remote.ecn_summary = ecn_summary;
3035                if !(ecn_feedback || ecn_summary) {
3036                    remote.ecn = None;
3037                } else if remote.ecn.is_none() {
3038                    remote.ecn = Some(Box::default());
3039                }
3040                remote.stream.set_clock_rate(info.clock_rate);
3041                remote
3042                    .stream
3043                    .set_payload_clock_rates(&info.payload_clock_rates);
3044                remote.rrtr = rrtr;
3045                remote.kind = Kind::of(&info.mime_type);
3046            }
3047            None => {
3048                self.remotes.insert(
3049                    info.ssrc,
3050                    Remote {
3051                        stream: {
3052                            let mut stream = ReceiverStream::new(info.ssrc, info.clock_rate);
3053                            stream.set_payload_clock_rates(&info.payload_clock_rates);
3054                            stream
3055                        },
3056                        kind: Kind::of(&info.mime_type),
3057                        rrtr,
3058                        ecn_feedback,
3059                        ecn_summary,
3060                        ecn: (ecn_feedback || ecn_summary).then(Box::default),
3061                        gone: false,
3062                    },
3063                );
3064                self.remote_order.push(info.ssrc);
3065            }
3066        }
3067    }
3068
3069    fn unbind_remote_stream(&mut self, info: &StreamInfo) {
3070        self.dlrr_limits.remove(&info.ssrc);
3071        self.remotes.remove(&info.ssrc);
3072        self.remote_order.retain(|ssrc| *ssrc != info.ssrc);
3073    }
3074}
3075
3076#[cfg(test)]
3077mod tests {
3078    use super::*;
3079
3080    fn rr(ssrc: u32) -> Box<dyn rtcp::Packet> {
3081        boxed(ReceiverReport {
3082            ssrc,
3083            ..Default::default()
3084        })
3085    }
3086
3087    /// RFC 8108 5.3.1: the size that goes into avg_rtcp_size is the packet's divided by "the
3088    /// number of different SSRCs that are the source of SR or RR RTCP packets" in it; a
3089    /// packet without any reports for one.
3090    #[test]
3091    fn a_compound_packet_counts_per_reporting_ssrc() {
3092        let sr = boxed(SenderReport {
3093            ssrc: 3,
3094            ..Default::default()
3095        });
3096        assert_eq!(3, reporting_ssrcs(&[rr(1), rr(2), sr]));
3097        // A second RR from the same SSRC (more than 31 report blocks) is the same reporter.
3098        assert_eq!(1, reporting_ssrcs(&[rr(1), rr(1)]));
3099        let pli = boxed(PictureLossIndication {
3100            sender_ssrc: 1,
3101            media_ssrc: 2,
3102        });
3103        assert_eq!(1, reporting_ssrcs(&[pli]));
3104
3105        // An empty RR is 8 octets; with UDP and IPv4 under it, 36.
3106        assert_eq!(36, wire_size(&[rr(1)]));
3107        let mut session = RtcpSessionBuilder::new().build();
3108        session.avg_rtcp_size = 100.0;
3109        session.send(Instant::now(), vec![rr(1), rr(2)]);
3110        // (28 + 16) / 2 = 22: 100 * 15/16 + 22 / 16.
3111        assert!((session.avg_rtcp_size - (93.75 + 1.375)).abs() < 1e-9);
3112    }
3113
3114    /// RFC 3711 section 3.4: the SRTCP index, E flag and authentication tag are part of the
3115    /// packet size: in the initial avg_rtcp_size and in every packet sent or received.
3116    #[test]
3117    fn the_srtcp_fields_count_in_the_average_packet_size() {
3118        let now = Instant::now();
3119        let started = |overhead: Option<usize>| {
3120            let mut session = RtcpSessionBuilder::new().build();
3121            session.control(now, &RtcpSessionControl::Cname("cname".to_owned()));
3122            if let Some(overhead) = overhead {
3123                session.control(now, &RtcpSessionControl::SrtcpOverhead(overhead));
3124            }
3125            session
3126        };
3127        let (plain, mut protected) = (started(None), started(Some(14)));
3128        assert!(plain.started && protected.started);
3129        assert!((protected.avg_rtcp_size - plain.avg_rtcp_size - 14.0).abs() < 1e-9);
3130        // Given before the session starts, the initial estimate has it.
3131        let mut early = RtcpSessionBuilder::new().build();
3132        early.srtcp_overhead = 14;
3133        early.cname = "cname".to_owned();
3134        early.sync(now);
3135        assert!((early.avg_rtcp_size - plain.avg_rtcp_size - 14.0).abs() < 1e-9);
3136
3137        // A packet sent: 36 octets of RR, UDP and IPv4, and 14 of SRTCP.
3138        protected.avg_rtcp_size = 100.0;
3139        protected.send(now, vec![rr(1)]);
3140        assert!((protected.avg_rtcp_size - (93.75 + 50.0 / 16.0)).abs() < 1e-9);
3141        // One received: the same.
3142        protected.avg_rtcp_size = 100.0;
3143        protected.observe_rtcp(now, &[rr(2)]);
3144        assert!((protected.avg_rtcp_size - (93.75 + 50.0 / 16.0)).abs() < 1e-9);
3145    }
3146
3147    /// RFC 4585 6.1: the packet sender of a feedback message is rewritten, whatever its type.
3148    #[test]
3149    fn every_feedback_type_takes_the_endpoints_ssrc() {
3150        let packets: Vec<Box<dyn rtcp::Packet>> = vec![
3151            boxed(TransportLayerNack::default()),
3152            boxed(PictureLossIndication::default()),
3153            boxed(FullIntraRequest::default()),
3154            boxed(SliceLossIndication::default()),
3155            boxed(ReceiverEstimatedMaximumBitrate::default()),
3156            boxed(TransportLayerCc::default()),
3157            boxed(RapidResynchronizationRequest::default()),
3158        ];
3159        for packet in packets {
3160            let rewritten = with_sender(packet, 0xABCD);
3161            assert_eq!(
3162                Some(0xABCD),
3163                sender_and_media(rewritten.as_ref()).0,
3164                "{rewritten:?}"
3165            );
3166        }
3167    }
3168
3169    /// RFC 8834 section 13 (with RFC 8108): the effect of RTCP from SSRCs this endpoint does
3170    /// not know is bounded. Reports and reference times from 5000 different unknown sources
3171    /// leave the member table at its bound, so the RTCP interval (which grows with the
3172    /// membership, RFC 3550 6.3.1) stays that of 1024 members, and the reference times kept
3173    /// for DLRR answers at 64.
3174    #[test]
3175    fn rtcp_from_many_unknown_ssrcs_has_a_bounded_effect() {
3176        let now = Instant::now();
3177        let mut session = RtcpSessionBuilder::new().build();
3178        session.control(now, &RtcpSessionControl::Cname("cname".to_owned()));
3179        let before = session.report_interval(now);
3180        for ssrc in 1..=5000u32 {
3181            let xr = boxed(ExtendedReport {
3182                sender_ssrc: ssrc,
3183                reports: vec![Box::new(ReceiverReferenceTimeReportBlock {
3184                    ntp_timestamp: u64::from(ssrc) << 16,
3185                })],
3186            });
3187            session.observe_rtcp(now, &[rr(ssrc), xr]);
3188        }
3189        assert_eq!(MAX_MEMBERS, session.members.len());
3190        assert_eq!(MAX_REFERENCE_TIMES, session.reference_times.len());
3191        let flooded = session.report_interval(now);
3192        assert!(flooded >= before, "{flooded} {before}");
3193        // One more member's worth of interval per member at most: what 1024 members give.
3194        let mut bounded = RtcpSessionBuilder::new().build();
3195        bounded.control(now, &RtcpSessionControl::Cname("cname".to_owned()));
3196        for ssrc in 1..=MAX_MEMBERS as u32 {
3197            bounded.observe_rtcp(now, &[rr(ssrc)]);
3198        }
3199        bounded.avg_rtcp_size = session.avg_rtcp_size;
3200        assert!(
3201            (flooded - bounded.report_interval(now)).abs() < 1e-6,
3202            "{flooded} against {}",
3203            bounded.report_interval(now)
3204        );
3205    }
3206
3207    #[test]
3208    fn the_media_bitrate_is_measured_over_the_last_seconds() {
3209        let mut rate = RateWindow::default();
3210        let base = Instant::now();
3211        assert_eq!(0.0, rate.bits_per_second(base));
3212        // 50 packets a second of 1250 octets for three seconds: 500 kbit/s.
3213        for n in 0..150u32 {
3214            rate.add(base + Duration::from_millis(20) * n, 1250);
3215        }
3216        let measured = rate.bits_per_second(base + Duration::from_secs(3));
3217        assert!((measured - 500_000.0).abs() < 75_000.0, "{measured}");
3218        // Long after the last packet: nothing.
3219        assert_eq!(0.0, rate.bits_per_second(base + Duration::from_secs(30)));
3220    }
3221}