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