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