Skip to main content

rtci_interceptor/pacing/
sender.rs

1//! Smooths outgoing packets to a target rate.
2
3use super::pacer::Pacer as LeakyBucket;
4use crate::Interceptor;
5use crate::StreamInfo;
6use crate::cc::probe::{ProbeFill, ProbePacket, ProbeRequest};
7use crate::keyframe::LocalKeyFrameRequest;
8use crate::{Attribute, AttributedPacket, Packet, TaggedPacket};
9use rtcp::payload_feedbacks::picture_loss_indication::PictureLossIndication;
10use sansio::Protocol;
11use shared::TransportContext;
12use shared::error::Error;
13use shared::marshal::MarshalSize;
14use std::collections::{HashMap, HashSet, VecDeque};
15use std::sync::Arc;
16use std::time::{Duration, Instant};
17
18/// Rate used when none is configured: 1 Mb/s.
19pub const DEFAULT_BITRATE: f64 = 1_000_000.0;
20
21/// Packets held before the queue overflows (see [`QueueOverflow`]).
22pub const DEFAULT_QUEUE_LIMIT: usize = 4096;
23
24/// How long a packet may wait in the queue by default (libwebrtc's
25/// `kMaxExpectedQueueLength`, 2 s); what happens to one that would wait longer is
26/// [`QueueOverflow`]'s.
27pub const DEFAULT_QUEUE_TIME_LIMIT: Duration = Duration::from_secs(2);
28
29/// What the pacer does with media the target has no room for: a packet that has waited the
30/// queue time limit, or the oldest one when a packet arrives at a full queue. It happens only
31/// when the application writes faster than the congestion controller's target for longer
32/// than the limit.
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
34#[non_exhaustive]
35pub enum QueueOverflow {
36    /// The media is discarded here, whole frames at a time (see [`PacerDiscard`]; counted by
37    /// [`PacerInterceptor::dropped`] and [`PacerInterceptor::discarded_frames`]): nothing
38    /// leaves above the target. The congestion controller's target is what the path carries (RFC
39    /// 8836 section 2; RFC 8083 section 4 stops a flow that does not keep to it), so a sender
40    /// that put the excess on the path anyway would fill the bottleneck's queue, lose there
41    /// and drive the estimate to its floor: a 2.4 Mbit/s source on a 600 kbit/s link
42    /// (`tests/gcc_rate_limited_link_rtc2rtc.rs`, and netem in
43    /// `testenv_impairment::gcc_follows_a_rate_limited_link`) held a target of 500 to 590
44    /// kbit/s this way, and fell to 100 kbit/s with [`QueueOverflow::Drain`]. The receiver
45    /// counts the dropped packets as lost, which they are; the NACK responder does not resend
46    /// them, and the application is asked for a key frame (see [`PacerDiscard`]).
47    #[default]
48    Drop,
49    /// libwebrtc's pacer (`drain_large_queues`, `MaybeUpdateMediaRateDueToLongQueue`): the
50    /// pacing rate is raised above the target as far as it takes to drain the queue before
51    /// its oldest packet has waited the limit, a packet that has waited it leaves whatever the
52    /// budget says, and a full queue releases its oldest over the budget (counted by
53    /// [`PacerInterceptor::forced`]). Nothing the application wrote is lost here, and a
54    /// source that keeps above the target puts all of it on the path. For an encoder that
55    /// follows the target, as libwebrtc's does.
56    Drain,
57}
58
59/// What the pacer does with what it holds when the path's capacity collapses: the target has
60/// fallen to half or less of what it was when the queued media was written or within the
61/// queue time bound, and the queue would now take half the queue time bound or more to leave (see "A capacity collapse" on
62/// [`PacerInterceptor`]). It applies with [`QueueOverflow::Drop`]; [`QueueOverflow::Drain`]
63/// never discards.
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
65#[non_exhaustive]
66pub enum Backlog {
67    /// The queue is given up: the media and retransmissions waiting are discarded
68    /// ([`PacerDiscard`], [`RetransmissionsLeft`]), the NACK responder is told to forget what
69    /// was sent before ([`PacerFlush`]) and the application is asked for a key frame of every
70    /// video stream. The receiver's next picture is a current one, a key frame sized for the
71    /// new rate, in place of seconds of frames sized for the old one delivered in order.
72    /// RFC 8834 section 6.1: "It is not appropriate to blindly retransmit RTP packets in
73    /// response to a NACK. The importance of lost packets and the likelihood of them arriving
74    /// in time to be useful need to be considered"; RFC 4588 section 7: the sender "MAY
75    /// selectively retransmit only the packets that it deems important".
76    #[default]
77    Flush,
78    /// The source is paused and everything queued is delivered in order, with every
79    /// retransmission asked for ("Pausing the source" on [`PacerInterceptor`]): for a receiver
80    /// that plays strictly in order and cannot resume at a key frame. After a sharp drop the
81    /// picture such a receiver shows is seconds old.
82    ///
83    /// "Keep and repair everything" is one choice for a whole chain: the default interceptor
84    /// set (`DefaultInterceptorOptions::pacer_backlog`) also switches off the NACK
85    /// responder's own rules that give repairs up
86    /// ([`NackResponderBuilder::with_max_repair_age`](crate::NackResponderBuilder::with_max_repair_age),
87    /// [`with_repair_backlog_bound`](crate::NackResponderBuilder::with_repair_backlog_bound)).
88    /// A chain built by hand sets both to `None` on its responder.
89    Keep,
90}
91
92/// Builder for [`PacerInterceptor`].
93///
94/// # Example
95///
96/// ```
97/// use rtci_interceptor::{Slot, PacerBuilder, Registry};
98///
99/// let chain = Registry::new()
100///     .with(Slot::Pacer, PacerBuilder::new().with_target_bitrate(2_000_000.0).build())
101///     .build();
102/// ```
103pub struct PacerBuilder {
104    bitrate: f64,
105    burst_bits: Option<f64>,
106    queue_limit: usize,
107    queue_time_limit: Option<Duration>,
108    queue_overflow: QueueOverflow,
109    backlog: Backlog,
110    immediate_release: bool,
111}
112
113impl Default for PacerBuilder {
114    fn default() -> Self {
115        Self {
116            bitrate: DEFAULT_BITRATE,
117            burst_bits: None,
118            queue_limit: DEFAULT_QUEUE_LIMIT,
119            queue_time_limit: Some(DEFAULT_QUEUE_TIME_LIMIT),
120            queue_overflow: QueueOverflow::default(),
121            backlog: Backlog::default(),
122            immediate_release: true,
123        }
124    }
125}
126
127impl PacerBuilder {
128    /// Create a builder with the default rate and queue limit.
129    pub fn new() -> Self {
130        Self::default()
131    }
132
133    /// The rate to pace at, in bits per second.
134    pub fn with_target_bitrate(mut self, bits_per_second: f64) -> Self {
135        self.bitrate = bits_per_second;
136        self
137    }
138
139    /// How much may be released at once, in bits.
140    ///
141    /// Larger bursts smooth less but cost fewer wake-ups.
142    pub fn with_burst_bits(mut self, burst_bits: f64) -> Self {
143        self.burst_bits = Some(burst_bits);
144        self
145    }
146
147    /// How many packets may be queued. When a packet arrives at a full queue, the oldest one
148    /// is dropped or leaves over the budget, as [`Self::with_queue_overflow`] says.
149    pub fn with_queue_limit(mut self, queue_limit: usize) -> Self {
150        self.queue_limit = queue_limit;
151        self
152    }
153
154    /// How long a packet may wait in the queue ([`DEFAULT_QUEUE_TIME_LIMIT`] by default,
155    /// `None` for no bound). When the application writes faster than the congestion
156    /// controller's target, the queue grows; a packet that would wait longer than this is
157    /// dropped or drained above the target, as [`Self::with_queue_overflow`] says. The
158    /// application learns that its source is above the target from the target itself
159    /// (`TargetBitrateChanged`, `RTCRtpSender::target_bitrates`), from
160    /// [`PacerInterceptor::queue_time`], and, once media had to be discarded, from
161    /// [`PacerDiscard`] (`RTCPeerConnectionEvent::OnPacerDiscard` in the peer connection) and
162    /// the key-frame request that goes with it.
163    pub fn with_queue_time_limit(mut self, limit: Option<Duration>) -> Self {
164        self.queue_time_limit = limit;
165        self
166    }
167
168    /// What happens to media the target has no room for ([`QueueOverflow::Drop`] by default).
169    pub fn with_queue_overflow(mut self, overflow: QueueOverflow) -> Self {
170        self.queue_overflow = overflow;
171        self
172    }
173
174    /// What happens to the queue when the path's capacity collapses ([`Backlog::Flush`] by
175    /// default).
176    pub fn with_backlog(mut self, backlog: Backlog) -> Self {
177        self.backlog = backlog;
178        self
179    }
180
181    /// Whether a packet the budget already covers leaves when it is written, with nothing
182    /// queued ahead of it. On by default.
183    ///
184    /// The pacer exists to keep a sender from putting more than its target rate times the
185    /// burst time on the path at once (draft-ietf-rmcat-gcc-02 section 4: a group of packets
186    /// of that size every `burst_time`, 5 ms recommended). The budget is that bound: it never
187    /// holds more than one burst and refills at the target rate. A packet inside it adds
188    /// nothing to what the bound allows, and holding it until the next wake-up only adds
189    /// delay the sender caused itself, which RFC 8836 section 2 (requirement 1) asks a
190    /// congestion controller for interactive media to keep as low as possible; no RFC asks
191    /// for the wait. `false` restores it: every packet is queued and leaves from the next
192    /// timeout, so departures happen only on the driver's clock.
193    pub fn with_immediate_release(mut self, immediate_release: bool) -> Self {
194        self.immediate_release = immediate_release;
195        self
196    }
197
198    /// Build the interceptor.
199    pub fn build(self) -> PacerInterceptor {
200        let bucket = match self.burst_bits {
201            Some(burst_bits) => LeakyBucket::new(self.bitrate).with_burst_bits(burst_bits),
202            None => LeakyBucket::new(self.bitrate),
203        };
204        let mut pacer = PacerInterceptor::new(bucket, self.queue_limit);
205        pacer.immediate_release = self.immediate_release;
206        pacer.queue_time_limit = self.queue_time_limit;
207        pacer.queue_overflow = self.queue_overflow;
208        pacer.backlog = self.backlog;
209        pacer
210    }
211}
212
213/// Releases queued packets at a target rate rather than as fast as they arrive.
214///
215/// # Where this belongs in the chain
216///
217/// **Close to the wire, with every generator on the application side of it.** Everything after it
218/// on the write path observes the *release* instant, so a send history goes there and records what
219/// actually left; placed the other way round it would record the enqueue instant and charge this
220/// queueing delay to the network.
221///
222/// Retransmissions, FEC repair packets and generated RTCP are all produced further out and reach
223/// the pacer on the belt, so they are metered along with everything else. Under the nested chain
224/// they bypassed it entirely.
225///
226/// # Differences from upstream
227///
228/// - **No ticker and no goroutine.** Upstream runs a loop on a 5 ms `time.Ticker`; here the
229///   budget is a pure function of the instants handed in, so a release schedule is reproducible
230///   rather than merely eventually-correct.
231/// - **Idle means idle.** `poll_timeout` returns `None` with nothing queued, so an idle
232///   connection does not wake the whole chain at the pacing interval.
233/// - **The deadline is when the head can afford to go**, not `now + interval`, so it always
234///   advances — a deadline at or before the `now` just handed to `handle_timeout` is the
235///   webrtc#862 busy-loop.
236///
237/// # Order of service
238///
239/// 1. **Audio** (the packets of a stream bound with an `audio/` codec) leaves the moment it is
240///    written, charged to the budget, which the packets behind it then wait out. A voice that
241///    waits behind a video backlog is the call breaking up.
242/// 2. **Audio retransmissions** leave the same way: an audio stream's repair flows (its RTX
243///    and FEC SSRCs, from [`Interceptor::bind_local_stream`]) count as audio, so an audio
244///    retransmission never waits behind video either.
245/// 3. **Video retransmissions** (`Attribute::Retransmission` on any other stream) wait in the
246///    media queue ahead of all new media (libwebrtc's `prioritized_packet_queue.cc`: "Send
247///    retransmissions before new media"), a stream's oldest packet first (by the sequence
248///    number repaired, whenever each was written: a receiver that plays in order waits for
249///    its oldest gap). One whose packet
250///    already has a retransmission waiting is not queued again
251///    ([`PacerInterceptor::duplicate_retransmissions`]), and each that leaves or is dropped is
252///    reported application-ward ([`RetransmissionsLeft`]), so the NACK responder does not make
253///    another while one waits.
254/// 4. **Video and FEC** (every other RTP packet that is not padding) wait behind them. Each
255///    stream's packets leave in the order written; **among the streams with packets waiting the
256///    payload octets are shared by priority** (RFC 8835 section 4.1: "each stream at each level
257///    of priority is being given approximately twice the transmission capacity (measured in
258///    payload bytes) of the level below"), by start-time fair queuing: each stream weighs what
259///    [`PacerPriorities`] gives it (very-low 1, low 2, medium 4, high 8; a stream it does not
260///    name weighs as `low`, the W3C default), and a bound stream's FEC and RTX streams are one
261///    flow with it. A retransmission keeps its place ahead of new media (3), and its payload is
262///    charged to its stream's share, so the repairs of a stream change the order, not the
263///    shares. Streams of one priority share equally; with one stream waiting, its packets leave
264///    in the order written, as before. Only packets that wait are shared out: what leaves the
265///    moment it is written (nothing waiting, budget to spare) is not counted, and the shares
266///    start afresh each time the queue holds no new media. Audio (1, 2) is not in the share.
267///    The **queue time bound** (2 s by default,
268///    [`PacerBuilder::with_queue_time_limit`]) and the queue limit are this queue's (3 and 4):
269///    by default ([`QueueOverflow::Drop`]) what has waited the bound, or the oldest packet when
270///    the queue is full, is discarded, so nothing leaves above the target (a retransmission
271///    one packet at a time, new media whole frames at a time: see "Discarding media" below);
272///    [`QueueOverflow::Drain`] raises the pacing rate above the target instead (libwebrtc's
273///    `MaybeUpdateMediaRateDueToLongQueue`) and releases those packets over the budget.
274/// 5. **Padding** (padding-only packets, RFC 3550 section 5.1: the padding bit and no payload,
275///    which the NACK responder fills a probe cluster with) waits in a queue of its own and leaves
276///    only when no media waits. A probe cluster is written as a burst of padding the moment it is
277///    asked for; queued in line with the media it would hold every packet the application writes
278///    during the cluster behind all of it (140 to 180 ms for a 6000-octet cluster at 200 kbit/s
279///    in `early_media_rtc2rtc`). Media written during a cluster leaves first, at the cluster's
280///    rate and with its mark, so it fills the cluster in place of padding, as in libwebrtc's
281///    pacer (padding has the lowest priority of its packet queue).
282///
283/// Padding is outside the queue time bound: it never counts toward raising the pacing rate
284/// (with [`QueueOverflow::Drain`]), is never dropped as overdue nor released over the budget,
285/// and so never goes ahead of media or past the rate the congestion controller set.
286///
287/// **A cluster's padding belongs to the cluster.** The pacer tells the responder how much
288/// padding a cluster needs beyond the media already queued ([`ProbeFill`]), so a cluster asked
289/// while a backlog waits (the pause) is made of that backlog and no padding is written for
290/// it. Padding written for a cluster that could not leave in it (media written meanwhile took
291/// its place, or the cluster timed out) is **discarded when the cluster ends**, counted by
292/// [`PacerInterceptor::padding_discarded`]: outside its cluster it measures nothing, and sent
293/// later it is worse than nothing. Each padding packet holds the sequence number of the RTX
294/// stream it was given when it was made; kept until budget was spare (seconds, while media
295/// waited) it left far behind the stream's newest number, where a receiver's replay
296/// protection (RFC 3711 section 3.3.2) and its feedback window no longer take it, inside
297/// whatever cluster was being sent then: that cluster's packets were never all reported and
298/// the probe gave no result (every cluster after a capacity drop in
299/// `tests/capacity_cap_video_rtc2rtc.rs`, 191 stale padding packets queued, and an estimate
300/// that stayed at its floor for want of a probe result). Discarding leaves a hole in the RTX
301/// stream's sequence numbers, which the receiver's reports count as lost (RFC 3550 appendix
302/// A.3); the sender's own readers of those reports take the numbers that never left out of
303/// the count (`NeverSent`, in the circuit breaker and the receiver-report fallback of the
304/// congestion controller), as for media the pacer discards.
305///
306/// Padding written while no cluster is being sent (an application's own) keeps its place
307/// until budget is spare, however long that takes: it is sent late, not dropped. A padding
308/// queue that reaches the queue limit (4096 packets) discards the padding that arrives.
309///
310/// # Pausing the source
311///
312/// When the media queued would take half the queue time bound or more to leave at the target
313/// ([`PacerInterceptor::expected_queue_time`]; 1 s of the default 2 s), the pacer tells the
314/// application to **stop producing**: every [`Attribute::TargetBitrateChanged`] it passes
315/// application-ward carries **zero** (so `RTCRtpSender::target_bitrates` and the stats read
316/// zero), with [`PacerPause`] carrying the congestion controller's target for the interceptors
317/// that need the path's rate, and it announces the change at once on a carrier of its own. When
318/// the queue is back under a twentieth of the bound (100 ms), it announces the real target
319/// again. libwebrtc does the same: its control handler gives the encoder a target of zero while
320/// the pacer's expected queue time exceeds 2 s
321/// (`modules/congestion_controller/rtp/control_handler.cc`, `pacing_controller.h`: "the packet
322/// producers should wait (eg drop frames rather than encoding them)"). Pausing at half the
323/// bound, not at the bound, leaves a source that stops when told the time to notice (a frame
324/// interval, a read of its target) and room for the target to fall once more.
325///
326/// **What a source that follows the pause wrote is never discarded for its age**: the media
327/// written before the pause began (and within 250 ms of it, the time to notice) stays queued
328/// until it leaves, however long that takes. At a sudden drop of the path's capacity that can be
329/// seconds: the target may fall to a tenth of what the queued media was written for, and the
330/// retransmissions of what the path lost at the drop leave ahead of it (order of service 3),
331/// which is also the order a receiver needs them in. Nothing new joins the queue meanwhile, so
332/// it is bounded by what was there when the pause began; discarding it would leave a gap in the
333/// stream that costs the receiver more than the wait (a receiver that waits for missing packets
334/// by count, as `rtci-media`'s `SampleBuilder` does, sat 9 s on such a gap in
335/// `tests/capacity_cap_video_rtc2rtc.rs`). The queue time bound and the discard below are for
336/// media written into a pause: a source that does not follow it.
337///
338/// **What that costs, and why it is not the default at a collapse.** This paragraph and the
339/// one before describe a queue kept through a sudden drop: [`Backlog::Keep`], and by default
340/// a long queue whose target did not collapse. By default a collapse flushes the queue
341/// instead (next section; `docs/capacity-collapse.md`). After a sudden drop the picture a
342/// receiver shows can be seconds old while those retransmissions leave: in that test, which
343/// runs [`Backlog::Keep`] (2.5 Mbit/s into a path that drops to
344/// 300 kbit/s) the receiver never went 2 s without a usable frame (0.75 to 1.13 s), but the
345/// oldest picture it showed was 4.14 to 6.58 s old, against 2.90 to 3.20 s in a chain without
346/// a pacer. The 55 to 62 video packets the path dropped are repaired inside an estimate of 100
347/// to 250 kbit/s of which the audio takes 76, under every retransmission rule (59 to 80
348/// retransmissions; a request for a packet whose retransmission the feedback reports received
349/// is not answered, see the NACK responder). Dropping the repairs and asking for a key frame
350/// instead is worse for a receiver that plays in order and waits for a gap by packet count
351/// (measured: frozen for 8 s, as it holds the gap for its whole packet window): such a
352/// receiver is what [`Backlog::Keep`] is for.
353///
354/// **A target of zero means: produce nothing until the next target.** An encoder skips (does
355/// not encode) the frames captured meanwhile; it does not need a key frame to resume, because
356/// nothing it encoded was lost: the next frame it encodes refers to the last one it sent, which
357/// is still queued here and reaches the receiver. libwebrtc resumes the same way: it encodes the
358/// last frame captured during the pause, or asks the capturer for a fresh one
359/// (`video_stream_encoder.cc`, `OnBitrateUpdated`: "A pending stored frame can be processed",
360/// else `RequestRefreshFrame`), and forces no key frame. Audio is not queued here and can carry
361/// on; the target is the transport's. Media the application writes anyway is queued and, past
362/// the bound, discarded as below, with a key-frame request: that, not the resume, is when a key
363/// frame is needed.
364///
365/// # A capacity collapse
366///
367/// By default ([`Backlog::Flush`]) the pause above is for a queue that is long at a steady
368/// target: a key frame larger than a second of the target, a source that is slow to follow.
369/// When the queue is long because **the target collapsed** (a pause would begin or is in
370/// force, and the target is now half or less of the highest target in force since the oldest
371/// queued new media was written or in the last queue time bound, two seconds by default,
372/// whichever reaches further back), the pacer does not pause, or ends the pause. The queue
373/// may hold new media, retransmissions or both: the repairs asked for a second after a drop,
374/// behind a deep queue on the path, are of media written for the old rate as well. It
375/// **flushes**: every queued packet is
376/// discarded (new media and FEC through [`PacerDiscard`], whole frames, as below; queued
377/// retransmissions through [`RetransmissionsLeft`]), a [`PacerFlush`] tells the NACK responder
378/// to forget everything sent before on the video streams, so that later NACKs for it are
379/// answered by nothing, and the application is asked for a key frame of every video stream
380/// (the Picture Loss Indication described below). The source is not paused: the next frame it
381/// writes, at the target it now reads, is the key frame. Audio is never queued and is not
382/// touched; padding stays.
383///
384/// What was queued was sized for a rate the path no longer carries: 0.4 s of 2.5 Mbit/s video
385/// and the retransmissions of what the path dropped take 8 s to leave at 100 to 250 kbit/s
386/// (`tests/capacity_instrument.rs`: the picture on the screen was 9 s old in the median),
387/// against a key frame of a few packets. RFC 8834 section 6.1 asks a sender to consider "the
388/// likelihood of [retransmissions] arriving in time to be useful"; RFC 8836 section 2 gives
389/// interactive media "no more delay than hundreds of milliseconds end-to-end"; RFC 8298
390/// section 3 lets a sender whose queues grow rapidly discard encoded frames "to ensure that
391/// the RTP queues are drained quickly". A decoder refresh point "completely resets the
392/// decoder" (RFC 5104 section 2.2): nothing sent before it is needed after it.
393///
394/// A flush is not repeated for what was written after it: no target from before a flush
395/// counts again, and the key frame the application writes in answer was written at the fallen
396/// target, so a queue it fills is a pause, not a collapse, and is delivered. The target has to
397/// halve again, from what it was at the flush, for another one: at most log2(highest /
398/// lowest target) flushes in a row, four from 2.5 Mbit/s to a 100 kbit/s floor. The receiver
399/// sees a gap in the sequence numbers (the application numbered the discarded packets) and
400/// its NACKs for it go unanswered; one that waits for missing packets has to bound that wait
401/// in time or resume at the key frame (`docs/capacity-collapse.md`).
402/// [`Backlog::Keep`] restores the pause for every long queue.
403///
404/// # Discarding media
405///
406/// With [`QueueOverflow::Drop`], new media the target has no room for is discarded **whole
407/// frames at a time**. A frame is the packets of one stream (SSRC) with one RTP timestamp (RFC
408/// 3550 section 5.1: the packets of one frame share it; the marker bit ends it). A frame with a
409/// packet missing is worth nothing to a decoder, and so is every later frame that refers to it,
410/// up to the next key frame; a frame that waited two seconds is stale anyway. So when the
411/// oldest new-media packet has waited the bound (or is the oldest of a full queue), the pacer
412/// discards every queued packet of its stream that is not a retransmission, oldest frame first,
413/// and the packets of the newest discarded frame the application writes after that. Nothing
414/// marks a key frame on this path (the application writes RTP packets, and only the codec's
415/// payload says which frame is a key frame), so no queued frame of the stream is kept as one:
416/// the key frame the application writes in answer to the request below is the next frame the
417/// stream sends, not one that waits behind the stale ones. Audio, retransmissions and padding
418/// are never discarded this way (audio is never queued, a retransmission is dropped alone,
419/// padding is sent late).
420///
421/// For every discard the pacer emits on its **read** leg (the application-ward direction, the
422/// only one that reaches the NACK responder application-ward of it) an empty RTCP carrier with
423/// [`PacerDiscard`]: the NACK responder removes those packets from its retransmission buffer, so
424/// a NACK for them is answered by nothing (RFC 4588 section 7: the sender "MAY selectively
425/// retransmit only the packets that it deems important"), and the peer connection hands the
426/// discard to the application (`RTCPeerConnectionEvent::OnPacerDiscard`). For a media stream
427/// (not a repair flow) it also emits a Picture Loss Indication (RFC 4585 section 6.3.1) for the
428/// stream, sender SSRC 0, marked [`Attribute::DeliverToApplication`]: the request a receiver
429/// that lost its picture sends, so an application that answers PLI with a key frame
430/// (`RTCMessage::RtcpPacket`, `RTCPeerConnectionEvent::OnKeyFrameRequest`) answers this too, at
431/// the target the frames it writes now are sized for. The request carries
432/// [`LocalKeyFrameRequest`] (`PacerDiscard`, or `PacerFlush` for the requests of a flush), so it
433/// can be told from a remote one (`RTCPeerConnectionEvent::OnKeyFrameRequestOrigin`).
434///
435/// libwebrtc does not discard in its pacer: when the expected queue time passes 2 s it pauses
436/// the encoder (target zero to the encoder, `modules/congestion_controller/rtp/control_handler.cc`)
437/// and drains the queue above the target ([`QueueOverflow::Drain`]); its frames are dropped
438/// before they are numbered. Here the application numbers its packets, so a discarded frame
439/// leaves a gap in the stream's sequence numbers that the receiver sees as loss.
440pub struct PacerInterceptor {
441    pacer: LeakyBucket,
442    /// The rate the bucket was set to before the queue time limit raised it, while it is
443    /// raised: the target to come back to (the congestion controller's, or one set through
444    /// [`Self::pacer_mut`]).
445    raised_from: Option<f64>,
446    /// The congestion controller's minimum that rode with its last target
447    /// ([`MinimumTarget`](crate::MinimumTarget)), to ride with the target this pacer announces
448    /// itself when a pause begins or ends.
449    minimum: Option<crate::MinimumTarget>,
450    queue: VecDeque<TaggedPacket>,
451    /// Padding-only packets, released only while `queue` is empty (see the order of service),
452    /// each with the probe cluster it was written for (the one being sent when it arrived).
453    padding: VecDeque<(Option<u32>, TaggedPacket)>,
454    /// Padding discarded: left over when its cluster ended, or refused by a full queue.
455    padding_discarded: u64,
456    /// When the cluster that ended last was asked for: its padding is written at that instant
457    /// and, arriving after the cluster ended, is not queued.
458    ended_cluster_asked: Option<Instant>,
459    /// The bits waiting in `queue` (padding not counted).
460    queued_bits: f64,
461    queue_limit: usize,
462    queue_time_limit: Option<Duration>,
463    queue_overflow: QueueOverflow,
464    backlog: Backlog,
465    /// The targets set and when, oldest first, back to the one in force when the oldest queued
466    /// new media was written: what that media was written for (see "A capacity collapse").
467    targets: VecDeque<(Instant, f64)>,
468    /// How many times the queue was flushed at a collapse.
469    flushes: u64,
470    /// The media SSRCs of the bound streams other than audio.
471    video: HashSet<u32>,
472    /// The SSRCs of the audio streams: their packets are not queued behind others.
473    audio: HashSet<u32>,
474    /// The flows the circuit breaker has ceased ([`CircuitBreakerNotice`]): their packets do
475    /// not leave, and are not charged to the budget.
476    ceased: HashSet<u32>,
477    /// The streams that may not send ([`StreamsNotSending`]): their packets are dropped.
478    not_sending: HashSet<u32>,
479    /// Packets dropped because their stream may not send.
480    not_sending_dropped: u64,
481    /// Whether a packet inside the budget leaves at once when nothing is queued ahead of it.
482    immediate_release: bool,
483    /// The probe cluster being sent, if one is (see [`ProbeRequest`]).
484    probe: Option<ActiveProbe>,
485    /// Packets released over the budget ([`QueueOverflow::Drain`]).
486    forced: u64,
487    /// Media packets dropped for want of room in the target ([`QueueOverflow::Drop`]).
488    dropped: u64,
489    /// Frames of new media discarded whole ([`QueueOverflow::Drop`]).
490    discarded_frames: u64,
491    /// The repair flows (RTX, FEC SSRCs) of the bound streams other than audio: a discard on
492    /// one asks for no key frame.
493    repair_flows: HashSet<u32>,
494    /// (repair SSRC, media SSRC) of the bound streams other than audio: a repair flow is one
495    /// flow with its stream in the share by priority. A few entries, searched in order.
496    repaired_by: Vec<(u32, u32)>,
497    /// The streams' weights ([`PacerPriorities`]), by media SSRC.
498    priorities: Vec<(u32, f64)>,
499    /// The flows of the share by priority since the queue last held no new media (see the
500    /// order of service): one entry per stream that has waited or been repaired since. Cleared,
501    /// not freed, when a new share starts, so a steady run allocates nothing.
502    flows: Vec<FairFlow>,
503    /// Start-time fair queuing's virtual time: the start tag of the new media served last.
504    virtual_time: f64,
505    /// The RTP timestamp of the newest frame discarded on each stream: its packets written
506    /// later are discarded too.
507    discarded_frame: HashMap<u32, u32>,
508    /// Whether the application is told to pause (see "Pausing the source").
509    paused: bool,
510    /// When the pause in force, or the last one, began.
511    pause_began: Option<Instant>,
512    /// How many times a pause began.
513    pauses: u64,
514    /// Retransmissions not queued because the same packet's retransmission already waited.
515    duplicate_retransmissions: u64,
516    /// The retransmissions released and dropped since the last [`RetransmissionsLeft`].
517    departed: Vec<(u32, u16)>,
518    retransmissions_dropped: Vec<(u32, u16)>,
519    /// Packets the budget has released, waiting to join the belt.
520    released: VecDeque<TaggedPacket>,
521    /// Inbound packets ready for the next interceptor.
522    read_queue: VecDeque<TaggedPacket>,
523    /// Outbound packets ready for the next interceptor: what passed through, plus
524    /// anything this one generated.
525    write_queue: VecDeque<TaggedPacket>,
526}
527
528impl PacerInterceptor {
529    fn new(pacer: LeakyBucket, queue_limit: usize) -> Self {
530        Self {
531            read_queue: VecDeque::new(),
532            write_queue: VecDeque::new(),
533            released: VecDeque::new(),
534            raised_from: None,
535            minimum: None,
536            pacer,
537            queue: VecDeque::new(),
538            padding: VecDeque::new(),
539            padding_discarded: 0,
540            ended_cluster_asked: None,
541            queued_bits: 0.0,
542            queue_limit: queue_limit.max(1),
543            queue_time_limit: Some(DEFAULT_QUEUE_TIME_LIMIT),
544            queue_overflow: QueueOverflow::default(),
545            backlog: Backlog::default(),
546            targets: VecDeque::new(),
547            flushes: 0,
548            video: HashSet::new(),
549            audio: HashSet::new(),
550            ceased: HashSet::new(),
551            not_sending: HashSet::new(),
552            not_sending_dropped: 0,
553            immediate_release: true,
554            probe: None,
555            forced: 0,
556            dropped: 0,
557            discarded_frames: 0,
558            repair_flows: HashSet::new(),
559            repaired_by: Vec::new(),
560            priorities: Vec::new(),
561            flows: Vec::new(),
562            virtual_time: 0.0,
563            discarded_frame: HashMap::new(),
564            paused: false,
565            pause_began: None,
566            pauses: 0,
567            duplicate_retransmissions: 0,
568            departed: Vec::new(),
569            retransmissions_dropped: Vec::new(),
570        }
571    }
572
573    /// The pacing bucket, for a bandwidth estimator to drive.
574    pub fn pacer(&self) -> &LeakyBucket {
575        &self.pacer
576    }
577
578    /// The pacing bucket, mutably — this is where `set_target_bitrate` is reached.
579    pub fn pacer_mut(&mut self) -> &mut LeakyBucket {
580        &mut self.pacer
581    }
582
583    /// How many packets are waiting to be released, padding included.
584    pub fn queued(&self) -> usize {
585        self.queue.len() + self.padding.len()
586    }
587
588    /// How many padding-only packets were discarded: left over when the probe cluster they
589    /// were written for ended (see "A cluster's padding belongs to the cluster" on
590    /// [`PacerInterceptor`]), or refused because the padding queue was full.
591    pub fn padding_discarded(&self) -> u64 {
592        self.padding_discarded
593    }
594
595    /// How many packets were dropped because their stream may not send
596    /// ([`StreamsNotSending`]): held when its direction changed, or written after.
597    pub fn not_sending_dropped(&self) -> u64 {
598        self.not_sending_dropped
599    }
600
601    /// How many packets left over the budget, overdue or to make room in a full queue
602    /// ([`QueueOverflow::Drain`]).
603    pub fn forced(&self) -> u64 {
604        self.forced
605    }
606
607    /// How many media packets were dropped, overdue or to make room in a full queue
608    /// ([`QueueOverflow::Drop`]): the packets of the discarded frames and the retransmissions
609    /// dropped.
610    pub fn dropped(&self) -> u64 {
611        self.dropped
612    }
613
614    /// How many frames of new media were discarded whole ([`QueueOverflow::Drop`], see
615    /// "Discarding media" on [`PacerInterceptor`]).
616    pub fn discarded_frames(&self) -> u64 {
617        self.discarded_frames
618    }
619
620    /// How many times the application was told to pause (see "Pausing the source" on
621    /// [`PacerInterceptor`]).
622    pub fn pauses(&self) -> u64 {
623        self.pauses
624    }
625
626    /// How many times the queue was flushed at a collapse of the target (see "A capacity
627    /// collapse" on [`PacerInterceptor`]).
628    pub fn flushes(&self) -> u64 {
629        self.flushes
630    }
631
632    /// Whether the application is told to pause now.
633    pub fn paused(&self) -> bool {
634        self.paused
635    }
636
637    /// How many retransmissions were not queued because a retransmission of the same packet
638    /// already waited in the queue.
639    pub fn duplicate_retransmissions(&self) -> u64 {
640        self.duplicate_retransmissions
641    }
642
643    /// How long the media queued now takes to leave at the target: queued bits over the
644    /// target (libwebrtc's `ExpectedQueueTime`). Padding is not counted.
645    pub fn expected_queue_time(&self) -> Duration {
646        if self.queued_bits <= 0.0 {
647            return Duration::ZERO;
648        }
649        let target = self.target();
650        if target <= 0.0 {
651            return Duration::MAX;
652        }
653        Duration::try_from_secs_f64(self.queued_bits / target).unwrap_or(Duration::MAX)
654    }
655
656    /// How long the oldest queued media packet has waited at `now`, zero with none queued
657    /// (padding is not counted: the queue time bound is the media's).
658    pub fn queue_time(&self, now: Instant) -> Duration {
659        self.queue.front().map_or(Duration::ZERO, |head| {
660            now.saturating_duration_since(head.now)
661        })
662    }
663
664    /// When the oldest queued new media (not a retransmission) was written.
665    fn oldest_new_media(&self) -> Option<Instant> {
666        self.queue
667            .iter()
668            .find(|queued| !queued.message.has(&Attribute::Retransmission))
669            .map(|oldest| oldest.now)
670    }
671
672    /// The rate to pace at now: the target, or more when the queue would otherwise not drain
673    /// before its oldest packet has waited the queue time limit. With `q` bits queued and the
674    /// oldest packet having waited `w`, the rate is max(target, q / (limit - w)); once `w`
675    /// reaches the limit, everything queued may leave.
676    fn pacing_rate(&self, now: Instant) -> f64 {
677        let target = self.target();
678        if self.queue_overflow != QueueOverflow::Drain {
679            return target;
680        }
681        let Some(limit) = self.queue_time_limit else {
682            return target;
683        };
684        if self.queue.is_empty() {
685            return target;
686        }
687        let remaining = limit.saturating_sub(self.queue_time(now)).as_secs_f64();
688        let needed = if remaining > 0.001 {
689            self.queued_bits / remaining
690        } else {
691            // Overdue: everything may leave (`handle_timeout` releases it).
692            1e12
693        };
694        target.max(needed)
695    }
696
697    /// The target rate: what the bucket paces at when the queue is short.
698    fn target(&self) -> f64 {
699        self.raised_from
700            .unwrap_or_else(|| self.pacer.target_bitrate())
701    }
702
703    /// Paces at [`Self::pacing_rate`] from `now`: above the target while the queue needs it,
704    /// back at the target once it does not.
705    fn follow_queue(&mut self, now: Instant) {
706        let target = self.target();
707        let rate = self.pacing_rate(now);
708        if rate > target {
709            self.raised_from = Some(target);
710            if rate != self.pacer.target_bitrate() {
711                self.pacer.set_target_bitrate(rate);
712            }
713        } else if let Some(target) = self.raised_from.take() {
714            self.pacer.set_target_bitrate(target);
715        }
716    }
717
718    /// Whether `packet` is padding only: an RTP packet with the padding bit and no payload.
719    fn is_padding(packet: &TaggedPacket) -> bool {
720        matches!(&packet.message.packet, Packet::Rtp(rtp) if rtp.header.padding && rtp.payload.is_empty())
721    }
722
723    fn is_audio(&self, packet: &TaggedPacket) -> bool {
724        matches!(&packet.message.packet, Packet::Rtp(rtp) if self.audio.contains(&rtp.header.ssrc))
725    }
726
727    /// The size of a packet on the wire, in bits — the unit the budget is kept in.
728    fn bits_of(packet: &TaggedPacket) -> f64 {
729        match &packet.message.packet {
730            Packet::Rtp(rtp) => (rtp.marshal_size() * 8) as f64,
731            Packet::Rtcp(_) => 0.0,
732        }
733    }
734
735    /// The flow of the stream `ssrc` in the share by priority: the media stream a bound repair
736    /// flow belongs to, otherwise the stream itself.
737    fn flow_key(&self, ssrc: u32) -> u32 {
738        self.repaired_by
739            .iter()
740            .find(|(repair, _)| *repair == ssrc)
741            .map_or(ssrc, |(_, media)| *media)
742    }
743
744    /// The index in `flows` of the RTP packet's flow, if it has one yet.
745    fn flow_of(&self, packet: &TaggedPacket) -> Option<usize> {
746        let Packet::Rtp(rtp) = &packet.message.packet else {
747            return None;
748        };
749        let key = self.flow_key(rtp.header.ssrc);
750        self.flows.iter().position(|flow| flow.ssrc == key)
751    }
752
753    /// The index in `flows` of the flow `key`, entered (with no share used) if it was not.
754    fn flow_index(&mut self, key: u32) -> usize {
755        if let Some(index) = self.flows.iter().position(|flow| flow.ssrc == key) {
756            return index;
757        }
758        let weight = self.weight_for(key);
759        self.flows.push(FairFlow {
760            ssrc: key,
761            queued: 0,
762            weight,
763            finish: 0.0,
764        });
765        self.flows.len() - 1
766    }
767
768    /// The weight of the stream `key` in the share ([`PacerPriorities`]; `low`'s when it is
769    /// not named, or named with a weight that is not a positive number).
770    fn weight_for(&self, key: u32) -> f64 {
771        self.priorities
772            .iter()
773            .find(|(ssrc, _)| *ssrc == key)
774            .map(|(_, weight)| *weight)
775            .filter(|weight| weight.is_finite() && *weight > 0.0)
776            .unwrap_or(DEFAULT_STREAM_WEIGHT)
777    }
778
779    /// New media joins the queue: counted to its flow. With no new media waiting before it, a
780    /// new share starts (nothing that left before counts in it).
781    fn count_queued(&mut self, packet: &TaggedPacket) {
782        let Packet::Rtp(rtp) = &packet.message.packet else {
783            return;
784        };
785        if self.queue.is_empty() || self.flows.iter().all(|flow| flow.queued == 0) {
786            self.flows.clear();
787            self.virtual_time = 0.0;
788        }
789        let key = self.flow_key(rtp.header.ssrc);
790        let index = self.flow_index(key);
791        self.flows[index].queued += 1;
792    }
793
794    /// Queued new media leaves the queue without being sent (discarded or dropped).
795    fn uncount(&mut self, packet: &TaggedPacket) {
796        if packet.message.has(&Attribute::Retransmission) {
797            return;
798        }
799        if let Some(index) = self.flow_of(packet) {
800            let flow = &mut self.flows[index];
801            flow.queued = flow.queued.saturating_sub(1);
802        }
803    }
804
805    /// A queued packet leaves: its payload octets are charged to its flow's share (start-time
806    /// fair queuing: its start tag is the later of the flow's finish tag and the virtual time,
807    /// its finish tag the start plus the octets over the weight). New media also moves the
808    /// virtual time to its start tag; a retransmission does not (it went ahead of its turn,
809    /// and the other streams are not to lose theirs for it).
810    fn charge(&mut self, packet: &TaggedPacket) {
811        let Packet::Rtp(rtp) = &packet.message.packet else {
812            return;
813        };
814        let octets = rtp.payload.len() as f64;
815        let repair = packet.message.has(&Attribute::Retransmission);
816        let key = self.flow_key(rtp.header.ssrc);
817        let index = self.flow_index(key);
818        let virtual_time = self.virtual_time;
819        let flow = &mut self.flows[index];
820        let start = flow.finish.max(virtual_time);
821        flow.finish = start + octets / flow.weight;
822        if !repair {
823            flow.queued = flow.queued.saturating_sub(1);
824            self.virtual_time = start;
825        }
826    }
827
828    /// The index in the queue of the packet to leave next when the budget allows (see the
829    /// order of service): the front while it is a retransmission (they wait at the front) or
830    /// while one stream has new media waiting; otherwise the oldest packet of the stream
831    /// whose start tag is lowest, the older stream's on a tie. Allocates nothing: the flows
832    /// are a few entries, and the queue is searched only as far as that stream's oldest
833    /// packet.
834    fn next_index(&self) -> usize {
835        if self.flows.len() < 2 {
836            return 0;
837        }
838        let Some(front) = self.queue.front() else {
839            return 0;
840        };
841        if front.message.has(&Attribute::Retransmission) {
842            return 0;
843        }
844        let mut waiting = 0;
845        let mut lowest = f64::INFINITY;
846        for flow in &self.flows {
847            if flow.queued > 0 {
848                waiting += 1;
849                lowest = lowest.min(flow.start(self.virtual_time));
850            }
851        }
852        if waiting < 2 {
853            return 0;
854        }
855        self.queue
856            .iter()
857            .position(|packet| {
858                self.flow_of(packet).is_some_and(|index| {
859                    let flow = &self.flows[index];
860                    flow.queued > 0 && flow.start(self.virtual_time) == lowest
861                })
862            })
863            .unwrap_or(0)
864    }
865
866    /// The bucket releases are metered through now: the probe cluster's while one is being
867    /// sent, the target rate's otherwise.
868    fn bucket(&self) -> &LeakyBucket {
869        self.probe
870            .as_ref()
871            .map_or(&self.pacer, |probe| &probe.bucket)
872    }
873
874    /// The instant the next packet can be released: the head of the media queue, or of the
875    /// padding while no media waits (padding has no queue time bound to wake for).
876    fn next_release(&self) -> Option<Instant> {
877        let Some(head) = self.queue.front() else {
878            let (_, head) = self.padding.front()?;
879            return self.bucket().releasable_at(Self::bits_of(head));
880        };
881        // The budget is waited for by the packet whose turn it is (the share by priority), the
882        // queue time bound by the oldest.
883        let next = self.queue.get(self.next_index()).unwrap_or(head);
884        let by_budget = self.bucket().releasable_at(Self::bits_of(next)).map(|at| {
885            // While the rate is raised it moves with every call, and the instant computed at
886            // one rate can come out a hair short of the budget at the next: a microsecond
887            // later it is not, and the deadline advances (webrtc#862).
888            if self.raised_from.is_some() {
889                at + Duration::from_micros(1)
890            } else {
891                at
892            }
893        });
894        // The rate rises as the oldest packet ages: wake by the time it reaches the limit
895        // (never for a packet the bound does not apply to: that deadline would stay in the
896        // past and a driver would spin on it).
897        let by_limit = self
898            .queue_time_limit
899            .filter(|_| self.queue_overflow == QueueOverflow::Drain || self.ages_out(head))
900            .map(|limit| head.now + limit);
901        match (by_budget, by_limit) {
902            (Some(a), Some(b)) => Some(a.min(b)),
903            (a, b) => a.or(b),
904        }
905    }
906
907    /// Whether `bits` may leave now, and if so, spends them.
908    fn try_spend(&mut self, bits: f64) -> bool {
909        match self.probe.as_mut() {
910            Some(probe) => {
911                if !probe.bucket.can_release(bits) {
912                    return false;
913                }
914                probe.bucket.consume(bits);
915                true
916            }
917            None => {
918                if !self.pacer.can_release(bits) {
919                    return false;
920                }
921                self.pacer.consume(bits);
922                true
923            }
924        }
925    }
926
927    /// Brings the budgets up to `now`, and ends a probe cluster that could not be filled.
928    fn refill(&mut self, now: Instant) {
929        self.pacer.refill(now);
930        if let Some(probe) = self.probe.as_mut() {
931            probe.bucket.refill(now);
932            if now.saturating_duration_since(probe.started) > PROBE_CLUSTER_TIMEOUT {
933                self.end_probe();
934            }
935        }
936    }
937
938    /// The probe cluster being sent is over (sent in full, timed out, or replaced by the next
939    /// one): the padding written for it that did not leave in it is discarded (see "A
940    /// cluster's padding belongs to the cluster").
941    fn end_probe(&mut self) {
942        let Some(probe) = self.probe.take() else {
943            return;
944        };
945        self.ended_cluster_asked = Some(probe.started);
946        let before = self.padding.len();
947        self.padding
948            .retain(|(cluster, _)| *cluster != Some(probe.cluster));
949        self.padding_discarded += (before - self.padding.len()) as u64;
950    }
951
952    /// A packet leaves at `now`: marked as part of the probe cluster while one is being sent.
953    fn release(&mut self, mut packet: TaggedPacket, bits: f64) {
954        if packet.message.has(&Attribute::Retransmission)
955            && !Self::is_padding(&packet)
956            && let Some(key) = self.retransmission_key(&packet)
957        {
958            self.departed.push(key);
959        }
960        if let Some(probe) = self.probe.as_mut() {
961            packet.message.add(Attribute::Custom(Arc::new(ProbePacket {
962                cluster: probe.cluster,
963            })));
964            probe.remaining_bits -= bits;
965            if probe.remaining_bits <= 0.0 {
966                self.end_probe();
967            }
968        }
969        self.released.push_back(packet);
970    }
971
972    /// The packet a retransmission repairs, as (SSRC on the wire, sequence number repaired): on
973    /// an RTX stream the original sequence number ahead of the payload (RFC 4588 section 4),
974    /// otherwise (a retransmission under the media SSRC) its own sequence number.
975    fn retransmission_key(&self, packet: &TaggedPacket) -> Option<(u32, u16)> {
976        let Packet::Rtp(rtp) = &packet.message.packet else {
977            return None;
978        };
979        let ssrc = rtp.header.ssrc;
980        if self.repair_flows.contains(&ssrc) {
981            let osn = rtp.payload.get(..2)?;
982            return Some((ssrc, u16::from_be_bytes([osn[0], osn[1]])));
983        }
984        Some((ssrc, rtp.header.sequence_number))
985    }
986
987    /// Whether a retransmission of the packet `packet` repairs already waits in the queue
988    /// (retransmissions wait at its front).
989    fn retransmission_waits(&self, packet: &TaggedPacket) -> bool {
990        let Some(key) = self.retransmission_key(packet) else {
991            return false;
992        };
993        self.queue
994            .iter()
995            .take_while(|queued| queued.message.has(&Attribute::Retransmission))
996            .any(|queued| self.retransmission_key(queued) == Some(key))
997    }
998
999    /// Records a retransmission dropped from the queue, for [`RetransmissionsLeft`].
1000    fn retransmission_dropped(&mut self, packet: &TaggedPacket) {
1001        if let Some(key) = self.retransmission_key(packet) {
1002            self.retransmissions_dropped.push(key);
1003        }
1004    }
1005
1006    /// Whether the pause should begin or end now (see "Pausing the source"); `true` when it
1007    /// changed.
1008    fn update_pause(&mut self, now: Instant) -> bool {
1009        if self.collapsed(now) {
1010            // Not a queue to wait out: the rate it was written for is gone. Also when the
1011            // target goes on falling during a pause that began before it had halved.
1012            self.flush(now);
1013            // A pause in force ends with its queue.
1014            return std::mem::replace(&mut self.paused, false);
1015        }
1016        let expected = self.expected_queue_time();
1017        let change = match self.queue_time_limit {
1018            Some(limit) if !self.paused => expected >= limit.mul_f64(PAUSE_AT),
1019            Some(limit) => expected <= limit.mul_f64(RESUME_AT),
1020            None => self.paused,
1021        };
1022        if change {
1023            self.paused = !self.paused;
1024            if self.paused {
1025                self.pauses += 1;
1026                self.pause_began = Some(now);
1027            }
1028        }
1029        change
1030    }
1031
1032    /// Records the target set at `now`, and drops the targets too old to count.
1033    fn note_target(&mut self, now: Instant, bits_per_second: f64) {
1034        if self.targets.back().map(|(_, target)| *target) != Some(bits_per_second) {
1035            self.targets.push_back((now, bits_per_second));
1036        }
1037        self.forget_targets(now);
1038    }
1039
1040    /// The instant from which the targets count toward a collapse at `now`: when the oldest
1041    /// queued new media was written, or the queue time bound ago, whichever is earlier. What
1042    /// waits here was written since, and so was what a retransmission queued now repairs,
1043    /// as far as it is still worth sending (media that waited the bound is discarded as
1044    /// stale). No target set before the last flush is kept ([`Self::flush`]), so the
1045    /// horizon never reaches behind one.
1046    fn collapse_horizon(&self, now: Instant) -> Option<Instant> {
1047        let oldest = self.oldest_new_media();
1048        let look_back = self
1049            .queue_time_limit
1050            .and_then(|limit| now.checked_sub(limit));
1051        match (oldest, look_back) {
1052            (Some(oldest), Some(look_back)) => Some(oldest.min(look_back)),
1053            (oldest, look_back) => oldest.or(look_back),
1054        }
1055    }
1056
1057    /// Drops the targets replaced before [`Self::collapse_horizon`]; all but the last when
1058    /// none counts.
1059    fn forget_targets(&mut self, now: Instant) {
1060        let horizon = self.collapse_horizon(now);
1061        while self.targets.len() > 1 && horizon.is_none_or(|from| self.targets[1].0 <= from) {
1062            self.targets.pop_front();
1063        }
1064        // Far more changes than a queue's lifetime holds: the oldest are let go (the collapse
1065        // is then judged against a later, lower target, which errs towards the pause).
1066        while self.targets.len() > MAX_TARGETS_KEPT {
1067            self.targets.pop_front();
1068        }
1069    }
1070
1071    /// Whether the queue is long because the target collapsed: what waits (new media or
1072    /// retransmissions) would take the pause mark or more to leave, whether a pause is in
1073    /// force or about to begin, and the target is at most [`COLLAPSE_AT`] of the highest in force since
1074    /// [`Self::collapse_horizon`] (see "A capacity collapse").
1075    fn collapsed(&self, now: Instant) -> bool {
1076        if self.backlog != Backlog::Flush || self.queue_overflow != QueueOverflow::Drop {
1077            return false;
1078        }
1079        let Some(limit) = self.queue_time_limit else {
1080            return false;
1081        };
1082        if self.queue.is_empty() || self.expected_queue_time() < limit.mul_f64(PAUSE_AT) {
1083            return false;
1084        }
1085        let Some(horizon) = self.collapse_horizon(now) else {
1086            return false;
1087        };
1088        let mut written_for: f64 = 0.0;
1089        for (index, (_, target)) in self.targets.iter().enumerate() {
1090            // In force at the horizon (the last set at or before it), or since.
1091            let superseded = self
1092                .targets
1093                .get(index + 1)
1094                .is_some_and(|(next, _)| *next <= horizon);
1095            if !superseded {
1096                written_for = written_for.max(*target);
1097            }
1098        }
1099        written_for > 0.0 && self.target() <= COLLAPSE_AT * written_for
1100    }
1101
1102    /// Gives the queue up at a collapse: retransmissions dropped, media discarded stream by
1103    /// stream, the NACK responder told to forget what was sent before ([`PacerFlush`]), and
1104    /// a key frame asked of every video stream.
1105    fn flush(&mut self, now: Instant) {
1106        let mut streams: Vec<(u32, Vec<TaggedPacket>)> = Vec::new();
1107        for packet in std::mem::take(&mut self.queue) {
1108            if packet.message.has(&Attribute::Retransmission) {
1109                self.retransmission_dropped(&packet);
1110                self.dropped += 1;
1111            } else if let Packet::Rtp(rtp) = &packet.message.packet {
1112                let ssrc = rtp.header.ssrc;
1113                match streams.iter_mut().find(|(stream, _)| *stream == ssrc) {
1114                    Some((_, packets)) => packets.push(packet),
1115                    None => streams.push((ssrc, vec![packet])),
1116                }
1117            }
1118        }
1119        self.queued_bits = 0.0;
1120        self.flows.clear();
1121        self.virtual_time = 0.0;
1122        self.flushes += 1;
1123        let mut asked: HashSet<u32> = HashSet::new();
1124        for (ssrc, packets) in &streams {
1125            // `PacerDiscard`, and for a media stream the key-frame request.
1126            self.discard(now, *ssrc, packets, LocalKeyFrameRequest::PacerFlush);
1127            asked.insert(*ssrc);
1128        }
1129        let mut ssrcs: Vec<u32> = self.video.iter().copied().collect();
1130        ssrcs.sort_unstable();
1131        // A video stream with nothing queued lost its repairs all the same.
1132        for ssrc in ssrcs.iter().filter(|ssrc| !asked.contains(ssrc)) {
1133            self.read_queue.push_back(TaggedPacket {
1134                now,
1135                transport: TransportContext::default(),
1136                message: AttributedPacket::new(Packet::Rtcp(vec![Box::new(
1137                    PictureLossIndication {
1138                        sender_ssrc: 0,
1139                        media_ssrc: *ssrc,
1140                    },
1141                )]))
1142                .with(Attribute::DeliverToApplication)
1143                .with(Attribute::Custom(Arc::new(
1144                    LocalKeyFrameRequest::PacerFlush,
1145                ))),
1146            });
1147        }
1148        self.read_queue.push_back(TaggedPacket {
1149            now,
1150            transport: TransportContext::default(),
1151            message: AttributedPacket::new(Packet::Rtcp(vec![]))
1152                .with(Attribute::Custom(Arc::new(PacerFlush { ssrcs }))),
1153        });
1154        // What is written from here on is written for the target now: no earlier target
1155        // counts again, so the key frame that answers this flush, however long it takes to
1156        // leave, is a pause and not another collapse.
1157        let target = self.target();
1158        self.targets.clear();
1159        self.targets.push_back((now, target));
1160    }
1161
1162    /// Whether new media written at `written` is what a source that follows the pause left
1163    /// behind: written before the pause in force (or the last one) began, or within
1164    /// [`PAUSE_GRACE`] of that. It is never discarded for its age (see "Pausing the source").
1165    fn written_before_pause(&self, written: Instant) -> bool {
1166        self.pause_began
1167            .is_some_and(|began| written <= began + PAUSE_GRACE)
1168    }
1169
1170    /// Whether the queued `packet` is discarded once it has waited the queue time bound
1171    /// ([`QueueOverflow::Drop`]): a retransmission, and new media a pausing source would not
1172    /// have written.
1173    fn ages_out(&self, packet: &TaggedPacket) -> bool {
1174        packet.message.has(&Attribute::Retransmission) || !self.written_before_pause(packet.now)
1175    }
1176
1177    /// The target as the application is to read it: zero while paused, with [`PacerPause`]
1178    /// carrying the congestion controller's.
1179    fn tag_target(&self, message: &mut AttributedPacket) {
1180        if !self.paused {
1181            return;
1182        }
1183        let mut target = None;
1184        for attribute in &mut message.attributes {
1185            if let Attribute::TargetBitrateChanged { bits_per_second } = attribute {
1186                target = Some(*bits_per_second);
1187                *bits_per_second = 0.0;
1188            }
1189        }
1190        if let Some(target_bits_per_second) = target {
1191            message.add(Attribute::Custom(Arc::new(PacerPause {
1192                target_bits_per_second,
1193            })));
1194        }
1195    }
1196
1197    /// After a write or a timeout: a pause that began or ended goes application-ward as the
1198    /// target, and the retransmissions that left or were dropped as [`RetransmissionsLeft`].
1199    fn tell_application_ward(&mut self, now: Instant) {
1200        if self.update_pause(now) {
1201            let mut message =
1202                AttributedPacket::new(Packet::Rtcp(vec![])).with(Attribute::TargetBitrateChanged {
1203                    bits_per_second: self.target(),
1204                });
1205            // The controller's target said again, so with the minimum the controller gave it:
1206            // a reader that takes the minimum from each target (the NACK responder, which never
1207            // tells the original media less than it) would otherwise read "no minimum" here,
1208            // and lower the target by its whole retransmission reserve when a pause ends.
1209            if let Some(minimum) = self.minimum {
1210                message.add(Attribute::Custom(Arc::new(minimum)));
1211            }
1212            self.tag_target(&mut message);
1213            self.read_queue.push_back(TaggedPacket {
1214                now,
1215                transport: TransportContext::default(),
1216                message,
1217            });
1218        }
1219        if !self.departed.is_empty() || !self.retransmissions_dropped.is_empty() {
1220            let notice = RetransmissionsLeft {
1221                departed: std::mem::take(&mut self.departed),
1222                dropped: std::mem::take(&mut self.retransmissions_dropped),
1223            };
1224            self.read_queue.push_back(TaggedPacket {
1225                now,
1226                transport: TransportContext::default(),
1227                message: AttributedPacket::new(Packet::Rtcp(vec![]))
1228                    .with(Attribute::Custom(Arc::new(notice))),
1229            });
1230        }
1231    }
1232
1233    /// Applies the [`StreamsNotSending`] notice `packet` carries, if any (see
1234    /// [`Self::stop_streams`]); whether it did. Out of line: the search calls through each
1235    /// custom attribute's vtable, and inlined in `enqueue` it kept registers spilled on the
1236    /// path of every packet.
1237    #[cold]
1238    #[inline(never)]
1239    fn apply_notice(&mut self, packet: &TaggedPacket) -> bool {
1240        // The streams' priorities (the peer connection's, on an RTCP carrier: an RTP packet
1241        // with attributes is not searched for them): they weigh in the shares from now on.
1242        if matches!(packet.message.packet, Packet::Rtcp(_))
1243            && let Some(priorities) = packet.message.custom::<PacerPriorities>()
1244        {
1245            self.set_priorities(&priorities.weights);
1246        }
1247        match packet.message.custom::<StreamsNotSending>() {
1248            Some(notice) => {
1249                self.stop_streams(packet.now, &notice.ssrcs);
1250                true
1251            }
1252            None => false,
1253        }
1254    }
1255
1256    /// The streams' weights in the share by priority from now on ([`PacerPriorities`]),
1257    /// replacing those given before; a flow already in the share takes its new weight for what
1258    /// it sends from now on.
1259    #[cold]
1260    #[inline(never)]
1261    fn set_priorities(&mut self, weights: &[(u32, f64)]) {
1262        self.priorities.clear();
1263        self.priorities.extend_from_slice(weights);
1264        for index in 0..self.flows.len() {
1265            self.flows[index].weight = self.weight_for(self.flows[index].ssrc);
1266        }
1267    }
1268
1269    /// Whether `packet` is RTP of a stream that may not send ([`StreamsNotSending`]).
1270    fn is_not_sending(&self, packet: &TaggedPacket) -> bool {
1271        matches!(&packet.message.packet, Packet::Rtp(rtp) if self.not_sending.contains(&rtp.header.ssrc))
1272    }
1273
1274    /// Counts a packet of a stream that may not send as dropped (a retransmission for
1275    /// [`RetransmissionsLeft`] too).
1276    #[cold]
1277    #[inline(never)]
1278    fn drop_not_sending(&mut self, packet: &TaggedPacket) {
1279        if packet.message.has(&Attribute::Retransmission) && !Self::is_padding(packet) {
1280            self.retransmission_dropped(packet);
1281        }
1282        self.not_sending_dropped += 1;
1283    }
1284
1285    /// The streams `ssrcs` may not send from `now` on (replacing those that could not
1286    /// before): everything of them that waits here (queued media and retransmissions,
1287    /// padding, and what was released for the next interceptor but has not gone to it) is
1288    /// dropped, without a key-frame request or a [`PacerDiscard`]: nothing is asked of a
1289    /// source that is not to send.
1290    ///
1291    /// Out of line and cold on purpose: `enqueue` looks for the notice on every packet written
1292    /// and finds it once per applied answer. Inlined there, this body made `handle_write`'s
1293    /// frame twice the size and the `Interceptor/Pacer/write+poll` benchmark slower
1294    /// (docs/performance.md, "pacer-4").
1295    #[cold]
1296    #[inline(never)]
1297    fn stop_streams(&mut self, now: Instant, ssrcs: &[u32]) {
1298        self.not_sending = ssrcs.iter().copied().collect();
1299        if self.not_sending.is_empty() {
1300            return;
1301        }
1302        let mut kept = VecDeque::with_capacity(self.queue.len());
1303        for packet in std::mem::take(&mut self.queue) {
1304            if self.is_not_sending(&packet) {
1305                self.queued_bits = (self.queued_bits - Self::bits_of(&packet)).max(0.0);
1306                self.uncount(&packet);
1307                self.drop_not_sending(&packet);
1308            } else {
1309                kept.push_back(packet);
1310            }
1311        }
1312        self.queue = kept;
1313        if self.queue.is_empty() {
1314            self.queued_bits = 0.0;
1315        }
1316        let mut padding = VecDeque::with_capacity(self.padding.len());
1317        for (cluster, packet) in std::mem::take(&mut self.padding) {
1318            if self.is_not_sending(&packet) {
1319                self.padding_discarded += 1;
1320                self.not_sending_dropped += 1;
1321            } else {
1322                padding.push_back((cluster, packet));
1323            }
1324        }
1325        self.padding = padding;
1326        let mut released = VecDeque::with_capacity(self.released.len());
1327        for packet in std::mem::take(&mut self.released) {
1328            if self.is_not_sending(&packet) {
1329                self.drop_not_sending(&packet);
1330            } else {
1331                released.push_back(packet);
1332            }
1333        }
1334        self.released = released;
1335        for ssrc in ssrcs {
1336            self.discarded_frame.remove(ssrc);
1337        }
1338        self.follow_queue(now);
1339    }
1340
1341    /// Whether `packet` is new media (not a retransmission) of the stream `ssrc`.
1342    fn is_new_media_of(packet: &TaggedPacket, ssrc: u32) -> bool {
1343        matches!(&packet.message.packet, Packet::Rtp(rtp) if rtp.header.ssrc == ssrc)
1344            && !packet.message.has(&Attribute::Retransmission)
1345    }
1346
1347    /// The stream of `packet` when it belongs to the frame discarded last on that stream; a
1348    /// packet of a later frame ends that frame's discard.
1349    fn continues_discard(&mut self, packet: &TaggedPacket) -> Option<u32> {
1350        let Packet::Rtp(rtp) = &packet.message.packet else {
1351            return None;
1352        };
1353        let ssrc = rtp.header.ssrc;
1354        let discarded = *self.discarded_frame.get(&ssrc)?;
1355        if discarded == rtp.header.timestamp {
1356            return Some(ssrc);
1357        }
1358        self.discarded_frame.remove(&ssrc);
1359        None
1360    }
1361
1362    /// Discards the frame of the queued new-media packet at `index` and every other queued
1363    /// frame of its stream (see "Discarding media" on [`PacerInterceptor`]).
1364    fn discard_stream_of(&mut self, now: Instant, index: usize) {
1365        let Some(Packet::Rtp(rtp)) = self.queue.get(index).map(|packet| &packet.message.packet)
1366        else {
1367            return;
1368        };
1369        let ssrc = rtp.header.ssrc;
1370        let mut discarded = Vec::new();
1371        let mut kept = VecDeque::with_capacity(self.queue.len());
1372        for packet in self.queue.drain(..) {
1373            if Self::is_new_media_of(&packet, ssrc) {
1374                discarded.push(packet);
1375            } else {
1376                kept.push_back(packet);
1377            }
1378        }
1379        self.queue = kept;
1380        for packet in &discarded {
1381            self.uncount(packet);
1382        }
1383        let bits: f64 = discarded.iter().map(Self::bits_of).sum();
1384        self.queued_bits = (self.queued_bits - bits).max(0.0);
1385        self.discard(now, ssrc, &discarded, LocalKeyFrameRequest::PacerDiscard);
1386    }
1387
1388    /// Counts the discard of `packets` (new media of the stream `ssrc`, oldest first) and tells
1389    /// the chain application-ward: the NACK responder and the application through
1390    /// [`PacerDiscard`], and the application a key frame is needed (the request carrying
1391    /// `why`, [`LocalKeyFrameRequest`]).
1392    fn discard(
1393        &mut self,
1394        now: Instant,
1395        ssrc: u32,
1396        packets: &[TaggedPacket],
1397        why: LocalKeyFrameRequest,
1398    ) {
1399        let mut sequence_numbers = Vec::with_capacity(packets.len());
1400        let mut octets = 0usize;
1401        let mut frames = 0u32;
1402        let mut newest = self.discarded_frame.get(&ssrc).copied();
1403        for packet in packets {
1404            if let Packet::Rtp(rtp) = &packet.message.packet {
1405                sequence_numbers.push(rtp.header.sequence_number);
1406                octets += rtp.marshal_size();
1407                if newest != Some(rtp.header.timestamp) {
1408                    frames += 1;
1409                    newest = Some(rtp.header.timestamp);
1410                }
1411            }
1412        }
1413        if sequence_numbers.is_empty() {
1414            return;
1415        }
1416        if let Some(timestamp) = newest {
1417            self.discarded_frame.insert(ssrc, timestamp);
1418        }
1419        self.dropped += sequence_numbers.len() as u64;
1420        self.discarded_frames += u64::from(frames);
1421        let target_bitrate = self.target();
1422        self.read_queue.push_back(TaggedPacket {
1423            now,
1424            transport: TransportContext::default(),
1425            message: AttributedPacket::new(Packet::Rtcp(vec![])).with(Attribute::Custom(Arc::new(
1426                PacerDiscard {
1427                    ssrc,
1428                    sequence_numbers,
1429                    frames,
1430                    octets,
1431                    target_bitrate,
1432                },
1433            ))),
1434        });
1435        // A new frame lost (not only the rest of one already discarded): the stream needs a
1436        // key frame, asked for the way a receiver asks, so the application's PLI handling
1437        // answers it.
1438        if frames > 0 && !self.repair_flows.contains(&ssrc) {
1439            self.read_queue.push_back(TaggedPacket {
1440                now,
1441                transport: TransportContext::default(),
1442                message: AttributedPacket::new(Packet::Rtcp(vec![Box::new(
1443                    PictureLossIndication {
1444                        sender_ssrc: 0,
1445                        media_ssrc: ssrc,
1446                    },
1447                )]))
1448                .with(Attribute::DeliverToApplication)
1449                .with(Attribute::Custom(Arc::new(why))),
1450            });
1451        }
1452    }
1453}
1454
1455/// Media the pacer discarded for want of room in the target ([`QueueOverflow::Drop`]): whole
1456/// frames of one stream (see "Discarding media" on [`PacerInterceptor`]).
1457///
1458/// The pacer sends it application-ward, on an empty RTCP carrier on its read leg, at the
1459/// instant of the discard. The NACK responder removes the packets named here from its
1460/// retransmission buffer (a NACK for them is answered by nothing) and from the original
1461/// packets it counts against the target (they never used the link); the peer connection
1462/// hands it to the application as `RTCPeerConnectionEvent::OnPacerDiscard`. It means **the
1463/// source is above the target**: what the application writes has to come down to the target
1464/// it is given (`Attribute::TargetBitrateChanged`, `RTCRtpSender::target_bitrates`). Read with
1465/// [`AttributedPacket::custom`](crate::AttributedPacket::custom).
1466#[derive(Debug, Clone, PartialEq)]
1467pub struct PacerDiscard {
1468    /// The stream the packets were of.
1469    pub ssrc: u32,
1470    /// The sequence numbers of the packets discarded, oldest first.
1471    pub sequence_numbers: Vec<u16>,
1472    /// How many frames were discarded (0 when these packets are the rest of a frame already
1473    /// discarded).
1474    pub frames: u32,
1475    /// The octets of the packets discarded (RTP header and payload).
1476    pub octets: usize,
1477    /// The pacer's target at the discard, bits per second.
1478    pub target_bitrate: f64,
1479}
1480
1481/// The pacer gave its queue up at a collapse of the target ([`Backlog::Flush`], see "A capacity
1482/// collapse" on [`PacerInterceptor`]): sent application-ward on an empty RTCP carrier, after
1483/// the [`PacerDiscard`] of each stream that had media queued. The NACK responder forgets
1484/// everything sent before it on the streams named (their retransmission buffers, the requests
1485/// waiting): a NACK for any of it is answered by nothing, and the stream goes on from the key
1486/// frame the application is asked for. Read with
1487/// [`AttributedPacket::custom`](crate::AttributedPacket::custom).
1488#[derive(Debug, Clone, PartialEq, Eq)]
1489pub struct PacerFlush {
1490    /// The media SSRCs of the video streams flushed (every bound stream that is not audio).
1491    pub ssrcs: Vec<u32>,
1492}
1493
1494/// The local streams that may not send media now: the SSRCs (media, RTX and FEC) of the
1495/// senders whose negotiated direction does not send (`recvonly`, `inactive`). RFC 8866
1496/// section 6.7.4: "No media is sent over an inactive media stream", and section 6.7.1: a
1497/// receive-only stream is in "receive-only mode"; RFC 3264 section 5.1. W3C webrtc-pc 4.4.1.6:
1498/// an answer sets `[[CurrentDirection]]`, and a sender sends only while it is "sendrecv" or
1499/// "sendonly". RTCP is not affected (RFC 8866 section 6.7: it "MUST still" be sent).
1500///
1501/// The peer connection writes it into the chain each time an answer is applied, as an
1502/// [`Attribute::Custom`] on an empty RTCP packet ([`StreamsNotSending::into_packet`]); each
1503/// replaces the one before. The [`PacerInterceptor`] drops what it holds of those streams at
1504/// that instant (media, retransmissions, padding) and every packet of them written later; the
1505/// [`NackResponderInterceptor`](crate::NackResponderInterceptor) forgets what it sent of them,
1506/// answers no NACK for them and pads no probe on their RTX streams. Read with
1507/// [`AttributedPacket::custom`](crate::AttributedPacket::custom).
1508#[derive(Debug, Clone, PartialEq, Eq, Default)]
1509pub struct StreamsNotSending {
1510    /// The SSRCs of the streams, their RTX and FEC streams included.
1511    pub ssrcs: Vec<u32>,
1512}
1513
1514impl StreamsNotSending {
1515    /// The packet that carries this into the chain when written at `now`.
1516    pub fn into_packet(self, now: Instant) -> TaggedPacket {
1517        TaggedPacket {
1518            now,
1519            transport: TransportContext::default(),
1520            message: AttributedPacket::new(Packet::Rtcp(vec![]))
1521                .with(Attribute::Custom(Arc::new(self))),
1522        }
1523    }
1524}
1525
1526/// A collapse is a target at most this share of the highest in force since the queued media
1527/// was written (or within the queue time bound, for what its retransmissions repair): half.
1528/// One decrease of the delay-based controller is 0.85 and the loss-based controller cuts by
1529/// at most half a report, so a target that halved within the life of the queue (two seconds
1530/// at most) is a path that lost its capacity, not a controller adapting; and a queue a
1531/// flush's own key frame fills was written at the fallen target and is never a collapse.
1532const COLLAPSE_AT: f64 = 0.5;
1533
1534/// How many target changes are kept to say what queued media was written for.
1535const MAX_TARGETS_KEPT: usize = 1024;
1536
1537/// The pause begins when the expected queue time reaches this share of the queue time bound:
1538/// half, so a source that stops when told (within a frame or a read of its target) never lets
1539/// its packets wait the bound, even when the target falls by half once more meanwhile.
1540const PAUSE_AT: f64 = 0.5;
1541
1542/// The pause ends when the expected queue time is back under this share of the bound (100 ms
1543/// of the default 2 s): what then waits is the delay the call carries on with, so it is kept
1544/// short; the gap between the two shares keeps one frame from switching it on and off.
1545const RESUME_AT: f64 = 0.05;
1546
1547/// How long after a pause began media still counts as written by a source that follows it:
1548/// the time such a source takes to notice (a read of its target, the frame being encoded).
1549const PAUSE_GRACE: Duration = Duration::from_millis(250);
1550
1551/// Rides a target of zero ([`Attribute::TargetBitrateChanged`]) that the pacer hands
1552/// application-ward while it tells the source to pause (see "Pausing the source" on
1553/// [`PacerInterceptor`]): the congestion controller's target, for what application-ward of the
1554/// pacer needs the rate the path carries (the NACK responder's retransmission rate limit). Read
1555/// with [`AttributedPacket::custom`](crate::AttributedPacket::custom).
1556#[derive(Debug, Clone, Copy, PartialEq)]
1557pub struct PacerPause {
1558    /// The congestion controller's target, bits per second.
1559    pub target_bits_per_second: f64,
1560}
1561
1562/// The weight of a stream no [`PacerPriorities`] names: `low`'s (2), the W3C default priority.
1563const DEFAULT_STREAM_WEIGHT: f64 = 2.0;
1564
1565/// One flow (a stream with its repair flows) in the pacer's share by priority.
1566#[derive(Debug, Clone, Copy)]
1567struct FairFlow {
1568    /// The media SSRC.
1569    ssrc: u32,
1570    /// Its new-media packets waiting in the queue.
1571    queued: u32,
1572    weight: f64,
1573    /// The finish tag of the last of its packets served: payload octets over the weight, in
1574    /// the share's virtual time.
1575    finish: f64,
1576}
1577
1578impl FairFlow {
1579    /// The start tag of its next packet at the virtual time `virtual_time`.
1580    fn start(&self, virtual_time: f64) -> f64 {
1581        self.finish.max(virtual_time)
1582    }
1583}
1584
1585/// The streams' weights in the pacer's share by priority (see "Order of service" on
1586/// [`PacerInterceptor`]): each media SSRC with the weight of its encoding's priority, each
1587/// level twice the level below (RFC 8835 section 4.1; the peer connection gives very-low 1,
1588/// low 2, medium 4, high 8). A bound stream's RTX and FEC streams weigh with it; a stream not
1589/// named weighs 2 (`low`, the W3C default). Each replaces the weights given before.
1590///
1591/// The peer connection writes it into the chain, as an [`Attribute::Custom`] on an empty RTCP
1592/// packet ([`PacerPriorities::into_packet`]), each time a description is applied and after
1593/// `setParameters`. The pacer takes the weights and passes the carrier on, which reaches the
1594/// end of the chain and is dropped there. Read with
1595/// [`AttributedPacket::custom`](crate::AttributedPacket::custom).
1596#[derive(Debug, Clone, PartialEq, Default)]
1597#[non_exhaustive]
1598pub struct PacerPriorities {
1599    /// (media SSRC, weight); a weight that is not a positive number counts as 2.
1600    pub weights: Vec<(u32, f64)>,
1601}
1602
1603impl PacerPriorities {
1604    /// The weights `weights`, as (media SSRC, weight).
1605    pub fn new(weights: Vec<(u32, f64)>) -> Self {
1606        Self { weights }
1607    }
1608
1609    /// The packet that carries this into the chain when written at `now`.
1610    pub fn into_packet(self, now: Instant) -> TaggedPacket {
1611        TaggedPacket {
1612            now,
1613            transport: TransportContext::default(),
1614            message: AttributedPacket::new(Packet::Rtcp(vec![]))
1615                .with(Attribute::Custom(Arc::new(self))),
1616        }
1617    }
1618}
1619
1620/// The retransmissions that left the pacer, or were dropped there, since the last notice: each
1621/// as (SSRC on the wire, sequence number of the packet it repairs; the original sequence
1622/// number on an RTX stream). The pacer sends it application-ward on an empty RTCP carrier; the
1623/// NACK responder treats a packet as on its way while its retransmission waits in the pacer
1624/// and counts the resend interval from when it left, as libwebrtc's packet history does
1625/// (`modules/rtp_rtcp/source/rtp_packet_history.cc`: a request for a packet "already in pacer
1626/// queue" is ignored; the send time is set when it is sent). Read with
1627/// [`AttributedPacket::custom`](crate::AttributedPacket::custom).
1628#[derive(Debug, Clone, PartialEq, Default)]
1629pub struct RetransmissionsLeft {
1630    /// Released toward the wire.
1631    pub departed: Vec<(u32, u16)>,
1632    /// Dropped (waited the queue time bound, or the oldest of a full queue).
1633    pub dropped: Vec<(u32, u16)>,
1634}
1635
1636/// How long a probe cluster is held open for packets to fill it. A cluster that takes longer
1637/// than this to leave is not a burst any more and measures nothing.
1638const PROBE_CLUSTER_TIMEOUT: Duration = Duration::from_millis(250);
1639
1640/// A probe cluster on its way out.
1641struct ActiveProbe {
1642    cluster: u32,
1643    /// Meters the cluster's packets at the probe rate, one packet at a time.
1644    bucket: LeakyBucket,
1645    remaining_bits: f64,
1646    started: Instant,
1647}
1648
1649impl Protocol<TaggedPacket, TaggedPacket, ()> for PacerInterceptor {
1650    type Rout = TaggedPacket;
1651    type Wout = TaggedPacket;
1652    type Eout = ();
1653    type Error = Error;
1654    type Time = Instant;
1655
1656    fn handle_read(&mut self, mut msg: TaggedPacket) -> Result<(), Self::Error> {
1657        // Follow the congestion controller's estimate.
1658        //
1659        // It arrives on the **read** leg because that is the only one it can cross on. The
1660        // controller is wire-most, so on the write leg it is the last interceptor to see a packet
1661        // and anything it attached would already have gone past here. On the read leg it is the
1662        // first, and this is downstream of it — so the feedback packet that produced the estimate
1663        // carries it here on its way to the application.
1664        //
1665        // Observed, not consumed: the packet carries on with the attribute attached, so anything
1666        // further along reads the same number.
1667        if let Some(Attribute::TargetBitrateChanged { bits_per_second }) =
1668            msg.message.get(&Attribute::TargetBitrateChanged {
1669                bits_per_second: 0.0,
1670            })
1671        {
1672            match self.raised_from.as_mut() {
1673                // Raised to drain the queue: the new target is what it comes back to.
1674                Some(target) => *target = *bits_per_second,
1675                None => self.pacer.set_target_bitrate(*bits_per_second),
1676            }
1677            self.minimum = msg.message.custom::<crate::MinimumTarget>().copied();
1678            let target = *bits_per_second;
1679            self.note_target(msg.now, target);
1680            // A new rate changes how long the queue takes to leave: the pause may begin or
1681            // end, and the application reads it on this packet.
1682            self.update_pause(msg.now);
1683            self.tag_target(&mut msg.message);
1684        }
1685
1686        // A flow the circuit breaker ceased or restarted (it sits wire-ward of here).
1687        if let Some(notice) = msg.message.custom::<crate::CircuitBreakerNotice>() {
1688            if notice.ceased.is_some() {
1689                self.ceased.insert(notice.ssrc);
1690            } else {
1691                self.ceased.remove(&notice.ssrc);
1692            }
1693        }
1694
1695        // A probe cluster the congestion controller asks for: the next packets leave at its
1696        // rate, on top of the target's budget, and carry its mark. Observed, not consumed:
1697        // the NACK responder above reads the same request and fills the cluster.
1698        if let Some(request) = msg.message.custom::<ProbeRequest>().copied() {
1699            // A cluster still being sent is over: the new one takes its place.
1700            self.end_probe();
1701            let mut bucket = LeakyBucket::new(request.bits_per_second)
1702                .with_burst_bits(crate::pacing::pacer::MIN_BURST_BITS);
1703            bucket.refill(msg.now);
1704            self.probe = Some(ActiveProbe {
1705                cluster: request.cluster,
1706                bucket,
1707                remaining_bits: request.octets as f64 * 8.0,
1708                started: msg.now,
1709            });
1710            // What waits in the media queue leaves first and fills the cluster: the
1711            // responder is asked for the rest only.
1712            let queued_octets = (self.queued_bits.max(0.0) / 8.0) as usize;
1713            msg.message.add(Attribute::Custom(Arc::new(ProbeFill {
1714                cluster: request.cluster,
1715                octets: request.octets.saturating_sub(queued_octets),
1716            })));
1717        }
1718
1719        self.read_queue.push_back(msg);
1720        Ok(())
1721    }
1722
1723    fn poll_read(&mut self) -> Option<Self::Rout> {
1724        self.read_queue.pop_front()
1725    }
1726
1727    fn handle_write(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
1728        let now = msg.now;
1729        let rtp = matches!(msg.message.packet, Packet::Rtp(_));
1730        // Nothing here borrows `msg` before it moves into `enqueue`: a borrow (the search for
1731        // the `StreamsNotSending` notice was one) makes the move a copy of every packet
1732        // written (224 bytes on x86-64). `enqueue` looks for the notice and says whether it
1733        // applied one.
1734        let not_sending = self.enqueue(msg)?;
1735        if rtp || not_sending {
1736            self.tell_application_ward(now);
1737        }
1738        Ok(())
1739    }
1740
1741    fn poll_write(&mut self) -> Option<TaggedPacket> {
1742        // Unpaced traffic goes first — RTCP is only useful while it is fresh, and holding it
1743        // behind the budget would be pacing it after all.
1744        self.write_queue
1745            .pop_front()
1746            .or_else(|| self.released.pop_front())
1747    }
1748
1749    fn handle_timeout(&mut self, now: Instant) -> Result<(), Error> {
1750        self.release_due(now);
1751        self.tell_application_ward(now);
1752        Ok(())
1753    }
1754
1755    fn poll_timeout(&mut self) -> Option<Instant> {
1756        self.next_release()
1757    }
1758}
1759
1760impl PacerInterceptor {
1761    /// A packet written: released, queued, or discarded; whether it carried a
1762    /// [`StreamsNotSending`] notice (applied first, see [`Self::stop_streams`]).
1763    fn enqueue(&mut self, msg: TaggedPacket) -> Result<bool, Error> {
1764        // No estimate is read here. It was, once — but the congestion controller sits wire-*ward*
1765        // of the pacer, so on the write leg it never sees a packet before this interceptor does and
1766        // the branch had no possible producer. If an application-set target is ever wanted it comes
1767        // back with its own `RTCEvent` variant, and a test.
1768
1769        // The streams that may not send from now on: what waits of them goes.
1770        let not_sending = !msg.message.attributes.is_empty() && self.apply_notice(&msg);
1771
1772        // RTCP is control traffic and mostly time-sensitive — feedback is only useful while it is
1773        // fresh — so it is not paced.
1774        if matches!(msg.message.packet, Packet::Rtcp(_)) {
1775            self.write_queue.push_back(msg);
1776            return Ok(not_sending);
1777        }
1778
1779        // A stream that may not send (`StreamsNotSending`): written after its direction
1780        // changed (a retransmission, padding, FEC), it does not leave.
1781        if self.is_not_sending(&msg) {
1782            self.drop_not_sending(&msg);
1783            return Ok(not_sending);
1784        }
1785
1786        // A flow the circuit breaker ceased (RFC 8083 section 4.5): its packets are dropped
1787        // at the breaker, below. They pass here unmetered: charged to the budget, a voice the
1788        // application keeps writing took 76 of a 100 kbit/s target that the video then
1789        // could not use (`tests/capacity_cap_video_rtc2rtc.rs`'s path), for packets that
1790        // never left.
1791        if matches!(&msg.message.packet, Packet::Rtp(rtp) if self.ceased.contains(&rtp.header.ssrc))
1792        {
1793            self.released.push_back(msg);
1794            return Ok(not_sending);
1795        }
1796
1797        // Keeping the budget current at enqueue time is what lets `poll_timeout` compute a
1798        // deadline that is never in the past, even before the first `handle_timeout`.
1799        self.refill(msg.now);
1800        self.follow_queue(msg.now);
1801
1802        // Audio is never queued behind video: its packets are small and few, and a voice that
1803        // waits behind a video backlog is the call breaking up. It leaves at once and is
1804        // charged to the budget, which the packets behind it then wait out.
1805        if self.is_audio(&msg) {
1806            let bits = Self::bits_of(&msg);
1807            if !self.try_spend(bits) {
1808                self.pacer.consume(bits);
1809            }
1810            self.release(msg, bits);
1811            return Ok(not_sending);
1812        }
1813
1814        // Padding waits behind every other packet, and nothing waits behind it.
1815        let padding = Self::is_padding(&msg);
1816        // Written for a cluster that has ended already (filled by media in the instant it
1817        // was asked for): it would only leave late.
1818        if padding && self.probe.is_none() && self.ended_cluster_asked == Some(msg.now) {
1819            self.padding_discarded += 1;
1820            return Ok(not_sending);
1821        }
1822
1823        // The rest of a frame already discarded is worth nothing either.
1824        let new_media = !padding && !msg.message.has(&Attribute::Retransmission);
1825        if new_media && let Some(ssrc) = self.continues_discard(&msg) {
1826            self.discard(
1827                msg.now,
1828                ssrc,
1829                std::slice::from_ref(&msg),
1830                LocalKeyFrameRequest::PacerDiscard,
1831            );
1832            return Ok(not_sending);
1833        }
1834
1835        // Inside the budget and first in line: it leaves now. The budget is the bound on what
1836        // may enter the path at once, so nothing is gained by holding the packet for a timer.
1837        // Queued padding is not in line ahead of media.
1838        if self.immediate_release && self.queue.is_empty() && (!padding || self.padding.is_empty())
1839        {
1840            let bits = Self::bits_of(&msg);
1841            if self.try_spend(bits) {
1842                self.release(msg, bits);
1843                return Ok(not_sending);
1844            }
1845        }
1846
1847        if padding {
1848            // Never over the budget and never counted toward the queue time bound (see the
1849            // order of service); at the limit the arrival is discarded.
1850            if self.padding.len() >= self.queue_limit {
1851                self.padding_discarded += 1;
1852            } else {
1853                let cluster = self.probe.as_ref().map(|probe| probe.cluster);
1854                self.padding.push_back((cluster, msg));
1855            }
1856            return Ok(not_sending);
1857        }
1858
1859        // A retransmission of a packet whose retransmission already waits adds nothing but a
1860        // second copy (libwebrtc's packet history ignores a request for a packet "already in
1861        // pacer queue", `rtp_packet_history.cc`).
1862        if !new_media && self.retransmission_waits(&msg) {
1863            self.duplicate_retransmissions += 1;
1864            return Ok(not_sending);
1865        }
1866
1867        if self.queue.len() >= self.queue_limit {
1868            // Room for the arrival: the oldest goes (the newest is the one still worth
1869            // sending). Discarded by default, a retransmission alone, new media with its
1870            // stream's queued frames; with `Drain` it leaves now, over the budget.
1871            let retransmission = self
1872                .queue
1873                .front()
1874                .is_some_and(|oldest| oldest.message.has(&Attribute::Retransmission));
1875            match self.queue_overflow {
1876                QueueOverflow::Drop if !retransmission => {
1877                    self.discard_stream_of(msg.now, 0);
1878                    if new_media && let Some(ssrc) = self.continues_discard(&msg) {
1879                        self.discard(
1880                            msg.now,
1881                            ssrc,
1882                            std::slice::from_ref(&msg),
1883                            LocalKeyFrameRequest::PacerDiscard,
1884                        );
1885                        return Ok(not_sending);
1886                    }
1887                }
1888                _ => {
1889                    if let Some(mut oldest) = self.queue.pop_front() {
1890                        let bits = Self::bits_of(&oldest);
1891                        self.queued_bits -= bits;
1892                        if self.queue_overflow == QueueOverflow::Drain {
1893                            self.charge(&oldest);
1894                            self.pacer.consume(bits);
1895                            oldest.now = msg.now;
1896                            self.forced += 1;
1897                            self.release(oldest, bits);
1898                        } else {
1899                            self.retransmission_dropped(&oldest);
1900                            self.dropped += 1;
1901                        }
1902                    }
1903                }
1904            }
1905        }
1906
1907        // Held: it leaves later, from `poll_write`, when the budget allows. A retransmission
1908        // goes ahead of the new media waiting, behind the retransmissions before it: a repair
1909        // the NACK responder has already held to the congestion controller's target is worth
1910        // most early, and waiting behind seconds of new video it may outlive its use or be
1911        // dropped as overdue. libwebrtc's pacer orders its queue the same way
1912        // (`modules/pacing/prioritized_packet_queue.cc`, `GetPriorityForType`: "Send
1913        // retransmissions before new media").
1914        let now = msg.now;
1915        self.queued_bits += Self::bits_of(&msg);
1916        if msg.message.has(&Attribute::Retransmission) {
1917            let end = self
1918                .queue
1919                .iter()
1920                .position(|queued| !queued.message.has(&Attribute::Retransmission))
1921                .unwrap_or(self.queue.len());
1922            // Among the retransmissions of one stream the oldest packet goes first, whenever
1923            // it was asked for: a receiver that plays in order waits for the oldest gap, and
1924            // a repair that was itself lost and is made again would otherwise wait behind
1925            // every newer one.
1926            let at = self
1927                .retransmission_key(&msg)
1928                .map_or(end, |(ssrc, repaired)| {
1929                    self.queue
1930                        .iter()
1931                        .take(end)
1932                        .position(|queued| {
1933                            self.retransmission_key(queued)
1934                                .is_some_and(|(other, waiting)| {
1935                                    other == ssrc
1936                                        && waiting != repaired
1937                                        && waiting.wrapping_sub(repaired) < 0x8000
1938                                })
1939                        })
1940                        .unwrap_or(end)
1941                });
1942            self.queue.insert(at, msg);
1943            if at == 0 {
1944                // First in line now: it may leave at once if the budget allows.
1945                self.release_due(now);
1946            }
1947            self.follow_queue(now);
1948            return Ok(not_sending);
1949        }
1950        self.count_queued(&msg);
1951        self.queue.push_back(msg);
1952        self.follow_queue(now);
1953        Ok(not_sending)
1954    }
1955
1956    /// Releases what the budget allows at `now`, and drops what waited the bound.
1957    fn release_due(&mut self, now: Instant) {
1958        self.refill(now);
1959        self.follow_queue(now);
1960
1961        while let Some(head) = self.queue.front() {
1962            let mut bits = Self::bits_of(head);
1963            // Past the queue time limit the head is dropped (`Drop`) or leaves whatever the
1964            // budget says (`Drain`).
1965            let overdue = self
1966                .queue_time_limit
1967                .is_some_and(|limit| now.saturating_duration_since(head.now) >= limit)
1968                && (self.queue_overflow == QueueOverflow::Drain || self.ages_out(head));
1969            // The packet that leaves: the overdue head, or the one whose turn it is in the
1970            // share by priority (the head unless several streams wait).
1971            let mut index = 0;
1972            if overdue {
1973                if self.queue_overflow == QueueOverflow::Drop {
1974                    // A retransmission is dropped alone; new media with every queued frame
1975                    // of its stream (see "Discarding media").
1976                    if head.message.has(&Attribute::Retransmission) {
1977                        if let Some(dropped) = self.queue.pop_front() {
1978                            self.retransmission_dropped(&dropped);
1979                        }
1980                        self.queued_bits = (self.queued_bits - bits).max(0.0);
1981                        self.dropped += 1;
1982                    } else {
1983                        self.discard_stream_of(now, 0);
1984                    }
1985                    continue;
1986                }
1987                self.pacer.consume(bits);
1988                self.forced += 1;
1989            } else {
1990                index = self.next_index();
1991                if index != 0 {
1992                    bits = self.queue.get(index).map_or(bits, Self::bits_of);
1993                }
1994                if !self.try_spend(bits) {
1995                    break;
1996                }
1997            }
1998
1999            let mut packet = self.queue.remove(index).expect("index within the queue");
2000            self.charge(&packet);
2001            self.queued_bits = (self.queued_bits - bits).max(0.0);
2002            // Rule 3: the packet departs now. Anything below recording departure — the send
2003            // history congestion control reads — must see the release instant, not the enqueue
2004            // instant, or this queueing delay is charged to the network.
2005            packet.now = now;
2006            // Queued for `poll_write`, which puts it back on the belt so it traverses every
2007            // interceptor ahead — numbering, and the send history reading the release instant just set.
2008            self.release(packet, bits);
2009        }
2010        if self.queue.is_empty() {
2011            self.queued_bits = 0.0;
2012            // No media waits: padding leaves from what the budget has left, never over it.
2013            while let Some((_, head)) = self.padding.front() {
2014                let bits = Self::bits_of(head);
2015                if !self.try_spend(bits) {
2016                    break;
2017                }
2018                let (_, mut packet) = self.padding.pop_front().expect("front just checked");
2019                packet.now = now;
2020                self.release(packet, bits);
2021            }
2022        }
2023        self.follow_queue(now);
2024    }
2025}
2026
2027impl Interceptor for PacerInterceptor {
2028    /// Audio streams (and their repair flows) are not queued behind others. The repair flows of
2029    /// the other streams are remembered: a discard on one asks for no key frame.
2030    fn bind_local_stream(&mut self, info: &StreamInfo) {
2031        if info.mime_type.to_ascii_lowercase().starts_with("audio/") {
2032            self.audio.extend(crate::twcc::flow_ssrcs(info));
2033        } else {
2034            self.video.insert(info.ssrc);
2035            self.repair_flows
2036                .extend(info.ssrc_rtx.into_iter().chain(info.ssrc_fec));
2037            for repair in info.ssrc_rtx.into_iter().chain(info.ssrc_fec) {
2038                self.repaired_by.retain(|(ssrc, _)| *ssrc != repair);
2039                self.repaired_by.push((repair, info.ssrc));
2040            }
2041        }
2042    }
2043
2044    fn unbind_local_stream(&mut self, info: &StreamInfo) {
2045        self.video.remove(&info.ssrc);
2046        for ssrc in crate::twcc::flow_ssrcs(info) {
2047            self.audio.remove(&ssrc);
2048            self.discarded_frame.remove(&ssrc);
2049            self.ceased.remove(&ssrc);
2050        }
2051        for ssrc in info.ssrc_rtx.into_iter().chain(info.ssrc_fec) {
2052            self.repair_flows.remove(&ssrc);
2053            self.repaired_by.retain(|(repair, _)| *repair != ssrc);
2054        }
2055    }
2056
2057    fn bind_remote_stream(&mut self, _info: &StreamInfo) {}
2058
2059    fn unbind_remote_stream(&mut self, _info: &StreamInfo) {}
2060}