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