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