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, in the
255///    order written. The **queue time bound** (2 s by default,
256///    [`PacerBuilder::with_queue_time_limit`]) and the queue limit are this queue's (3 and 4):
257///    by default ([`QueueOverflow::Drop`]) what has waited the bound, or the oldest packet when
258///    the queue is full, is discarded, so nothing leaves above the target (a retransmission
259///    one packet at a time, new media whole frames at a time: see "Discarding media" below);
260///    [`QueueOverflow::Drain`] raises the pacing rate above the target instead (libwebrtc's
261///    `MaybeUpdateMediaRateDueToLongQueue`) and releases those packets over the budget.
262/// 5. **Padding** (padding-only packets, RFC 3550 section 5.1: the padding bit and no payload,
263///    which the NACK responder fills a probe cluster with) waits in a queue of its own and leaves
264///    only when no media waits. A probe cluster is written as a burst of padding the moment it is
265///    asked for; queued in line with the media it would hold every packet the application writes
266///    during the cluster behind all of it (140 to 180 ms for a 6000-octet cluster at 200 kbit/s
267///    in `early_media_rtc2rtc`). Media written during a cluster leaves first, at the cluster's
268///    rate and with its mark, so it fills the cluster in place of padding, as in libwebrtc's
269///    pacer (padding has the lowest priority of its packet queue).
270///
271/// Padding is outside the queue time bound: it never counts toward raising the pacing rate
272/// (with [`QueueOverflow::Drain`]), is never dropped as overdue nor released over the budget,
273/// and so never goes ahead of media or past the rate the congestion controller set.
274///
275/// **A cluster's padding belongs to the cluster.** The pacer tells the responder how much
276/// padding a cluster needs beyond the media already queued ([`ProbeFill`]), so a cluster asked
277/// while a backlog waits (the pause) is made of that backlog and no padding is written for
278/// it. Padding written for a cluster that could not leave in it (media written meanwhile took
279/// its place, or the cluster timed out) is **discarded when the cluster ends**, counted by
280/// [`PacerInterceptor::padding_discarded`]: outside its cluster it measures nothing, and sent
281/// later it is worse than nothing. Each padding packet holds the sequence number of the RTX
282/// stream it was given when it was made; kept until budget was spare (seconds, while media
283/// waited) it left far behind the stream's newest number, where a receiver's replay
284/// protection (RFC 3711 section 3.3.2) and its feedback window no longer take it, inside
285/// whatever cluster was being sent then: that cluster's packets were never all reported and
286/// the probe gave no result (every cluster after a capacity drop in
287/// `tests/capacity_cap_video_rtc2rtc.rs`, 191 stale padding packets queued, and an estimate
288/// that stayed at its floor for want of a probe result). Discarding leaves a hole in the RTX
289/// stream's sequence numbers, which the receiver's reports count as lost (RFC 3550 appendix
290/// A.3); the sender's own readers of those reports take the numbers that never left out of
291/// the count (`NeverSent`, in the circuit breaker and the receiver-report fallback of the
292/// congestion controller), as for media the pacer discards.
293///
294/// Padding written while no cluster is being sent (an application's own) keeps its place
295/// until budget is spare, however long that takes: it is sent late, not dropped. A padding
296/// queue that reaches the queue limit (4096 packets) discards the padding that arrives.
297///
298/// # Pausing the source
299///
300/// When the media queued would take half the queue time bound or more to leave at the target
301/// ([`PacerInterceptor::expected_queue_time`]; 1 s of the default 2 s), the pacer tells the
302/// application to **stop producing**: every [`Attribute::TargetBitrateChanged`] it passes
303/// application-ward carries **zero** (so `RTCRtpSender::target_bitrates` and the stats read
304/// zero), with [`PacerPause`] carrying the congestion controller's target for the interceptors
305/// that need the path's rate, and it announces the change at once on a carrier of its own. When
306/// the queue is back under a twentieth of the bound (100 ms), it announces the real target
307/// again. libwebrtc does the same: its control handler gives the encoder a target of zero while
308/// the pacer's expected queue time exceeds 2 s
309/// (`modules/congestion_controller/rtp/control_handler.cc`, `pacing_controller.h`: "the packet
310/// producers should wait (eg drop frames rather than encoding them)"). Pausing at half the
311/// bound, not at the bound, leaves a source that stops when told the time to notice (a frame
312/// interval, a read of its target) and room for the target to fall once more.
313///
314/// **What a source that follows the pause wrote is never discarded for its age**: the media
315/// written before the pause began (and within 250 ms of it, the time to notice) stays queued
316/// until it leaves, however long that takes. At a sudden drop of the path's capacity that can be
317/// seconds: the target may fall to a tenth of what the queued media was written for, and the
318/// retransmissions of what the path lost at the drop leave ahead of it (order of service 3),
319/// which is also the order a receiver needs them in. Nothing new joins the queue meanwhile, so
320/// it is bounded by what was there when the pause began; discarding it would leave a gap in the
321/// stream that costs the receiver more than the wait (a receiver that waits for missing packets
322/// by count, as `rtci-media`'s `SampleBuilder` does, sat 9 s on such a gap in
323/// `tests/capacity_cap_video_rtc2rtc.rs`). The queue time bound and the discard below are for
324/// media written into a pause: a source that does not follow it.
325///
326/// **What that costs, and why it is not the default at a collapse.** This paragraph and the
327/// one before describe a queue kept through a sudden drop: [`Backlog::Keep`], and by default
328/// a long queue whose target did not collapse. By default a collapse flushes the queue
329/// instead (next section; `docs/capacity-collapse.md`). After a sudden drop the picture a
330/// receiver shows can be seconds old while those retransmissions leave: in that test, which
331/// runs [`Backlog::Keep`] (2.5 Mbit/s into a path that drops to
332/// 300 kbit/s) the receiver never went 2 s without a usable frame (0.75 to 1.13 s), but the
333/// oldest picture it showed was 4.14 to 6.58 s old, against 2.90 to 3.20 s in a chain without
334/// a pacer. The 55 to 62 video packets the path dropped are repaired inside an estimate of 100
335/// to 250 kbit/s of which the audio takes 76, under every retransmission rule (59 to 80
336/// retransmissions; a request for a packet whose retransmission the feedback reports received
337/// is not answered, see the NACK responder). Dropping the repairs and asking for a key frame
338/// instead is worse for a receiver that plays in order and waits for a gap by packet count
339/// (measured: frozen for 8 s, as it holds the gap for its whole packet window): such a
340/// receiver is what [`Backlog::Keep`] is for.
341///
342/// **A target of zero means: produce nothing until the next target.** An encoder skips (does
343/// not encode) the frames captured meanwhile; it does not need a key frame to resume, because
344/// nothing it encoded was lost: the next frame it encodes refers to the last one it sent, which
345/// is still queued here and reaches the receiver. libwebrtc resumes the same way: it encodes the
346/// last frame captured during the pause, or asks the capturer for a fresh one
347/// (`video_stream_encoder.cc`, `OnBitrateUpdated`: "A pending stored frame can be processed",
348/// else `RequestRefreshFrame`), and forces no key frame. Audio is not queued here and can carry
349/// on; the target is the transport's. Media the application writes anyway is queued and, past
350/// the bound, discarded as below, with a key-frame request: that, not the resume, is when a key
351/// frame is needed.
352///
353/// # A capacity collapse
354///
355/// By default ([`Backlog::Flush`]) the pause above is for a queue that is long at a steady
356/// target: a key frame larger than a second of the target, a source that is slow to follow.
357/// When the queue is long because **the target collapsed** (a pause would begin or is in
358/// force, and the target is now half or less of the highest target in force since the oldest
359/// queued new media was written or in the last queue time bound, two seconds by default,
360/// whichever reaches further back), the pacer does not pause, or ends the pause. The queue
361/// may hold new media, retransmissions or both: the repairs asked for a second after a drop,
362/// behind a deep queue on the path, are of media written for the old rate as well. It
363/// **flushes**: every queued packet is
364/// discarded (new media and FEC through [`PacerDiscard`], whole frames, as below; queued
365/// retransmissions through [`RetransmissionsLeft`]), a [`PacerFlush`] tells the NACK responder
366/// to forget everything sent before on the video streams, so that later NACKs for it are
367/// answered by nothing, and the application is asked for a key frame of every video stream
368/// (the Picture Loss Indication described below). The source is not paused: the next frame it
369/// writes, at the target it now reads, is the key frame. Audio is never queued and is not
370/// touched; padding stays.
371///
372/// What was queued was sized for a rate the path no longer carries: 0.4 s of 2.5 Mbit/s video
373/// and the retransmissions of what the path dropped take 8 s to leave at 100 to 250 kbit/s
374/// (`tests/capacity_instrument.rs`: the picture on the screen was 9 s old in the median),
375/// against a key frame of a few packets. RFC 8834 section 6.1 asks a sender to consider "the
376/// likelihood of [retransmissions] arriving in time to be useful"; RFC 8836 section 2 gives
377/// interactive media "no more delay than hundreds of milliseconds end-to-end"; RFC 8298
378/// section 3 lets a sender whose queues grow rapidly discard encoded frames "to ensure that
379/// the RTP queues are drained quickly". A decoder refresh point "completely resets the
380/// decoder" (RFC 5104 section 2.2): nothing sent before it is needed after it.
381///
382/// A flush is not repeated for what was written after it: no target from before a flush
383/// counts again, and the key frame the application writes in answer was written at the fallen
384/// target, so a queue it fills is a pause, not a collapse, and is delivered. The target has to
385/// halve again, from what it was at the flush, for another one: at most log2(highest /
386/// lowest target) flushes in a row, four from 2.5 Mbit/s to a 100 kbit/s floor. The receiver
387/// sees a gap in the sequence numbers (the application numbered the discarded packets) and
388/// its NACKs for it go unanswered; one that waits for missing packets has to bound that wait
389/// in time or resume at the key frame (`docs/capacity-collapse.md`).
390/// [`Backlog::Keep`] restores the pause for every long queue.
391///
392/// # Discarding media
393///
394/// With [`QueueOverflow::Drop`], new media the target has no room for is discarded **whole
395/// frames at a time**. A frame is the packets of one stream (SSRC) with one RTP timestamp (RFC
396/// 3550 section 5.1: the packets of one frame share it; the marker bit ends it). A frame with a
397/// packet missing is worth nothing to a decoder, and so is every later frame that refers to it,
398/// up to the next key frame; a frame that waited two seconds is stale anyway. So when the
399/// oldest new-media packet has waited the bound (or is the oldest of a full queue), the pacer
400/// discards every queued packet of its stream that is not a retransmission, oldest frame first,
401/// and the packets of the newest discarded frame the application writes after that. Nothing
402/// marks a key frame on this path (the application writes RTP packets, and only the codec's
403/// payload says which frame is a key frame), so no queued frame of the stream is kept as one:
404/// the key frame the application writes in answer to the request below is the next frame the
405/// stream sends, not one that waits behind the stale ones. Audio, retransmissions and padding
406/// are never discarded this way (audio is never queued, a retransmission is dropped alone,
407/// padding is sent late).
408///
409/// For every discard the pacer emits on its **read** leg (the application-ward direction, the
410/// only one that reaches the NACK responder application-ward of it) an empty RTCP carrier with
411/// [`PacerDiscard`]: the NACK responder removes those packets from its retransmission buffer, so
412/// a NACK for them is answered by nothing (RFC 4588 section 7: the sender "MAY selectively
413/// retransmit only the packets that it deems important"), and the peer connection hands the
414/// discard to the application (`RTCPeerConnectionEvent::OnPacerDiscard`). For a media stream
415/// (not a repair flow) it also emits a Picture Loss Indication (RFC 4585 section 6.3.1) for the
416/// stream, sender SSRC 0, marked [`Attribute::DeliverToApplication`]: the request a receiver
417/// that lost its picture sends, so an application that answers PLI with a key frame
418/// (`RTCMessage::RtcpPacket`, `RTCPeerConnectionEvent::OnKeyFrameRequest`) answers this too, at
419/// the target the frames it writes now are sized for. The request carries
420/// [`LocalKeyFrameRequest`] (`PacerDiscard`, or `PacerFlush` for the requests of a flush), so it
421/// can be told from a remote one (`RTCPeerConnectionEvent::OnKeyFrameRequestOrigin`).
422///
423/// libwebrtc does not discard in its pacer: when the expected queue time passes 2 s it pauses
424/// the encoder (target zero to the encoder, `modules/congestion_controller/rtp/control_handler.cc`)
425/// and drains the queue above the target ([`QueueOverflow::Drain`]); its frames are dropped
426/// before they are numbered. Here the application numbers its packets, so a discarded frame
427/// leaves a gap in the stream's sequence numbers that the receiver sees as loss.
428pub struct PacerInterceptor {
429    pacer: LeakyBucket,
430    /// The rate the bucket was set to before the queue time limit raised it, while it is
431    /// raised: the target to come back to (the congestion controller's, or one set through
432    /// [`Self::pacer_mut`]).
433    raised_from: Option<f64>,
434    /// The congestion controller's minimum that rode with its last target
435    /// ([`MinimumTarget`](crate::MinimumTarget)), to ride with the target this pacer announces
436    /// itself when a pause begins or ends.
437    minimum: Option<crate::MinimumTarget>,
438    queue: VecDeque<TaggedPacket>,
439    /// Padding-only packets, released only while `queue` is empty (see the order of service),
440    /// each with the probe cluster it was written for (the one being sent when it arrived).
441    padding: VecDeque<(Option<u32>, TaggedPacket)>,
442    /// Padding discarded: left over when its cluster ended, or refused by a full queue.
443    padding_discarded: u64,
444    /// When the cluster that ended last was asked for: its padding is written at that instant
445    /// and, arriving after the cluster ended, is not queued.
446    ended_cluster_asked: Option<Instant>,
447    /// The bits waiting in `queue` (padding not counted).
448    queued_bits: f64,
449    queue_limit: usize,
450    queue_time_limit: Option<Duration>,
451    queue_overflow: QueueOverflow,
452    backlog: Backlog,
453    /// The targets set and when, oldest first, back to the one in force when the oldest queued
454    /// new media was written: what that media was written for (see "A capacity collapse").
455    targets: VecDeque<(Instant, f64)>,
456    /// How many times the queue was flushed at a collapse.
457    flushes: u64,
458    /// The media SSRCs of the bound streams other than audio.
459    video: HashSet<u32>,
460    /// The SSRCs of the audio streams: their packets are not queued behind others.
461    audio: HashSet<u32>,
462    /// The flows the circuit breaker has ceased ([`CircuitBreakerNotice`]): their packets do
463    /// not leave, and are not charged to the budget.
464    ceased: HashSet<u32>,
465    /// The streams that may not send ([`StreamsNotSending`]): their packets are dropped.
466    not_sending: HashSet<u32>,
467    /// Packets dropped because their stream may not send.
468    not_sending_dropped: u64,
469    /// Whether a packet inside the budget leaves at once when nothing is queued ahead of it.
470    immediate_release: bool,
471    /// The probe cluster being sent, if one is (see [`ProbeRequest`]).
472    probe: Option<ActiveProbe>,
473    /// Packets released over the budget ([`QueueOverflow::Drain`]).
474    forced: u64,
475    /// Media packets dropped for want of room in the target ([`QueueOverflow::Drop`]).
476    dropped: u64,
477    /// Frames of new media discarded whole ([`QueueOverflow::Drop`]).
478    discarded_frames: u64,
479    /// The repair flows (RTX, FEC SSRCs) of the bound streams other than audio: a discard on
480    /// one asks for no key frame.
481    repair_flows: HashSet<u32>,
482    /// The RTP timestamp of the newest frame discarded on each stream: its packets written
483    /// later are discarded too.
484    discarded_frame: HashMap<u32, u32>,
485    /// Whether the application is told to pause (see "Pausing the source").
486    paused: bool,
487    /// When the pause in force, or the last one, began.
488    pause_began: Option<Instant>,
489    /// How many times a pause began.
490    pauses: u64,
491    /// Retransmissions not queued because the same packet's retransmission already waited.
492    duplicate_retransmissions: u64,
493    /// The retransmissions released and dropped since the last [`RetransmissionsLeft`].
494    departed: Vec<(u32, u16)>,
495    retransmissions_dropped: Vec<(u32, u16)>,
496    /// Packets the budget has released, waiting to join the belt.
497    released: VecDeque<TaggedPacket>,
498    /// Inbound packets ready for the next interceptor.
499    read_queue: VecDeque<TaggedPacket>,
500    /// Outbound packets ready for the next interceptor: what passed through, plus
501    /// anything this one generated.
502    write_queue: VecDeque<TaggedPacket>,
503}
504
505impl PacerInterceptor {
506    fn new(pacer: LeakyBucket, queue_limit: usize) -> Self {
507        Self {
508            read_queue: VecDeque::new(),
509            write_queue: VecDeque::new(),
510            released: VecDeque::new(),
511            raised_from: None,
512            minimum: None,
513            pacer,
514            queue: VecDeque::new(),
515            padding: VecDeque::new(),
516            padding_discarded: 0,
517            ended_cluster_asked: None,
518            queued_bits: 0.0,
519            queue_limit: queue_limit.max(1),
520            queue_time_limit: Some(DEFAULT_QUEUE_TIME_LIMIT),
521            queue_overflow: QueueOverflow::default(),
522            backlog: Backlog::default(),
523            targets: VecDeque::new(),
524            flushes: 0,
525            video: HashSet::new(),
526            audio: HashSet::new(),
527            ceased: HashSet::new(),
528            not_sending: HashSet::new(),
529            not_sending_dropped: 0,
530            immediate_release: true,
531            probe: None,
532            forced: 0,
533            dropped: 0,
534            discarded_frames: 0,
535            repair_flows: HashSet::new(),
536            discarded_frame: HashMap::new(),
537            paused: false,
538            pause_began: None,
539            pauses: 0,
540            duplicate_retransmissions: 0,
541            departed: Vec::new(),
542            retransmissions_dropped: Vec::new(),
543        }
544    }
545
546    /// The pacing bucket, for a bandwidth estimator to drive.
547    pub fn pacer(&self) -> &LeakyBucket {
548        &self.pacer
549    }
550
551    /// The pacing bucket, mutably — this is where `set_target_bitrate` is reached.
552    pub fn pacer_mut(&mut self) -> &mut LeakyBucket {
553        &mut self.pacer
554    }
555
556    /// How many packets are waiting to be released, padding included.
557    pub fn queued(&self) -> usize {
558        self.queue.len() + self.padding.len()
559    }
560
561    /// How many padding-only packets were discarded: left over when the probe cluster they
562    /// were written for ended (see "A cluster's padding belongs to the cluster" on
563    /// [`PacerInterceptor`]), or refused because the padding queue was full.
564    pub fn padding_discarded(&self) -> u64 {
565        self.padding_discarded
566    }
567
568    /// How many packets were dropped because their stream may not send
569    /// ([`StreamsNotSending`]): held when its direction changed, or written after.
570    pub fn not_sending_dropped(&self) -> u64 {
571        self.not_sending_dropped
572    }
573
574    /// How many packets left over the budget, overdue or to make room in a full queue
575    /// ([`QueueOverflow::Drain`]).
576    pub fn forced(&self) -> u64 {
577        self.forced
578    }
579
580    /// How many media packets were dropped, overdue or to make room in a full queue
581    /// ([`QueueOverflow::Drop`]): the packets of the discarded frames and the retransmissions
582    /// dropped.
583    pub fn dropped(&self) -> u64 {
584        self.dropped
585    }
586
587    /// How many frames of new media were discarded whole ([`QueueOverflow::Drop`], see
588    /// "Discarding media" on [`PacerInterceptor`]).
589    pub fn discarded_frames(&self) -> u64 {
590        self.discarded_frames
591    }
592
593    /// How many times the application was told to pause (see "Pausing the source" on
594    /// [`PacerInterceptor`]).
595    pub fn pauses(&self) -> u64 {
596        self.pauses
597    }
598
599    /// How many times the queue was flushed at a collapse of the target (see "A capacity
600    /// collapse" on [`PacerInterceptor`]).
601    pub fn flushes(&self) -> u64 {
602        self.flushes
603    }
604
605    /// Whether the application is told to pause now.
606    pub fn paused(&self) -> bool {
607        self.paused
608    }
609
610    /// How many retransmissions were not queued because a retransmission of the same packet
611    /// already waited in the queue.
612    pub fn duplicate_retransmissions(&self) -> u64 {
613        self.duplicate_retransmissions
614    }
615
616    /// How long the media queued now takes to leave at the target: queued bits over the
617    /// target (libwebrtc's `ExpectedQueueTime`). Padding is not counted.
618    pub fn expected_queue_time(&self) -> Duration {
619        if self.queued_bits <= 0.0 {
620            return Duration::ZERO;
621        }
622        let target = self.target();
623        if target <= 0.0 {
624            return Duration::MAX;
625        }
626        Duration::try_from_secs_f64(self.queued_bits / target).unwrap_or(Duration::MAX)
627    }
628
629    /// How long the oldest queued media packet has waited at `now`, zero with none queued
630    /// (padding is not counted: the queue time bound is the media's).
631    pub fn queue_time(&self, now: Instant) -> Duration {
632        self.queue.front().map_or(Duration::ZERO, |head| {
633            now.saturating_duration_since(head.now)
634        })
635    }
636
637    /// When the oldest queued new media (not a retransmission) was written.
638    fn oldest_new_media(&self) -> Option<Instant> {
639        self.queue
640            .iter()
641            .find(|queued| !queued.message.has(&Attribute::Retransmission))
642            .map(|oldest| oldest.now)
643    }
644
645    /// The rate to pace at now: the target, or more when the queue would otherwise not drain
646    /// before its oldest packet has waited the queue time limit. With `q` bits queued and the
647    /// oldest packet having waited `w`, the rate is max(target, q / (limit - w)); once `w`
648    /// reaches the limit, everything queued may leave.
649    fn pacing_rate(&self, now: Instant) -> f64 {
650        let target = self.target();
651        if self.queue_overflow != QueueOverflow::Drain {
652            return target;
653        }
654        let Some(limit) = self.queue_time_limit else {
655            return target;
656        };
657        if self.queue.is_empty() {
658            return target;
659        }
660        let remaining = limit.saturating_sub(self.queue_time(now)).as_secs_f64();
661        let needed = if remaining > 0.001 {
662            self.queued_bits / remaining
663        } else {
664            // Overdue: everything may leave (`handle_timeout` releases it).
665            1e12
666        };
667        target.max(needed)
668    }
669
670    /// The target rate: what the bucket paces at when the queue is short.
671    fn target(&self) -> f64 {
672        self.raised_from
673            .unwrap_or_else(|| self.pacer.target_bitrate())
674    }
675
676    /// Paces at [`Self::pacing_rate`] from `now`: above the target while the queue needs it,
677    /// back at the target once it does not.
678    fn follow_queue(&mut self, now: Instant) {
679        let target = self.target();
680        let rate = self.pacing_rate(now);
681        if rate > target {
682            self.raised_from = Some(target);
683            if rate != self.pacer.target_bitrate() {
684                self.pacer.set_target_bitrate(rate);
685            }
686        } else if let Some(target) = self.raised_from.take() {
687            self.pacer.set_target_bitrate(target);
688        }
689    }
690
691    /// Whether `packet` is padding only: an RTP packet with the padding bit and no payload.
692    fn is_padding(packet: &TaggedPacket) -> bool {
693        matches!(&packet.message.packet, Packet::Rtp(rtp) if rtp.header.padding && rtp.payload.is_empty())
694    }
695
696    fn is_audio(&self, packet: &TaggedPacket) -> bool {
697        matches!(&packet.message.packet, Packet::Rtp(rtp) if self.audio.contains(&rtp.header.ssrc))
698    }
699
700    /// The size of a packet on the wire, in bits — the unit the budget is kept in.
701    fn bits_of(packet: &TaggedPacket) -> f64 {
702        match &packet.message.packet {
703            Packet::Rtp(rtp) => (rtp.marshal_size() * 8) as f64,
704            Packet::Rtcp(_) => 0.0,
705        }
706    }
707
708    /// The bucket releases are metered through now: the probe cluster's while one is being
709    /// sent, the target rate's otherwise.
710    fn bucket(&self) -> &LeakyBucket {
711        self.probe
712            .as_ref()
713            .map_or(&self.pacer, |probe| &probe.bucket)
714    }
715
716    /// The instant the next packet can be released: the head of the media queue, or of the
717    /// padding while no media waits (padding has no queue time bound to wake for).
718    fn next_release(&self) -> Option<Instant> {
719        let Some(head) = self.queue.front() else {
720            let (_, head) = self.padding.front()?;
721            return self.bucket().releasable_at(Self::bits_of(head));
722        };
723        let by_budget = self.bucket().releasable_at(Self::bits_of(head)).map(|at| {
724            // While the rate is raised it moves with every call, and the instant computed at
725            // one rate can come out a hair short of the budget at the next: a microsecond
726            // later it is not, and the deadline advances (webrtc#862).
727            if self.raised_from.is_some() {
728                at + Duration::from_micros(1)
729            } else {
730                at
731            }
732        });
733        // The rate rises as the oldest packet ages: wake by the time it reaches the limit
734        // (never for a packet the bound does not apply to: that deadline would stay in the
735        // past and a driver would spin on it).
736        let by_limit = self
737            .queue_time_limit
738            .filter(|_| self.queue_overflow == QueueOverflow::Drain || self.ages_out(head))
739            .map(|limit| head.now + limit);
740        match (by_budget, by_limit) {
741            (Some(a), Some(b)) => Some(a.min(b)),
742            (a, b) => a.or(b),
743        }
744    }
745
746    /// Whether `bits` may leave now, and if so, spends them.
747    fn try_spend(&mut self, bits: f64) -> bool {
748        match self.probe.as_mut() {
749            Some(probe) => {
750                if !probe.bucket.can_release(bits) {
751                    return false;
752                }
753                probe.bucket.consume(bits);
754                true
755            }
756            None => {
757                if !self.pacer.can_release(bits) {
758                    return false;
759                }
760                self.pacer.consume(bits);
761                true
762            }
763        }
764    }
765
766    /// Brings the budgets up to `now`, and ends a probe cluster that could not be filled.
767    fn refill(&mut self, now: Instant) {
768        self.pacer.refill(now);
769        if let Some(probe) = self.probe.as_mut() {
770            probe.bucket.refill(now);
771            if now.saturating_duration_since(probe.started) > PROBE_CLUSTER_TIMEOUT {
772                self.end_probe();
773            }
774        }
775    }
776
777    /// The probe cluster being sent is over (sent in full, timed out, or replaced by the next
778    /// one): the padding written for it that did not leave in it is discarded (see "A
779    /// cluster's padding belongs to the cluster").
780    fn end_probe(&mut self) {
781        let Some(probe) = self.probe.take() else {
782            return;
783        };
784        self.ended_cluster_asked = Some(probe.started);
785        let before = self.padding.len();
786        self.padding
787            .retain(|(cluster, _)| *cluster != Some(probe.cluster));
788        self.padding_discarded += (before - self.padding.len()) as u64;
789    }
790
791    /// A packet leaves at `now`: marked as part of the probe cluster while one is being sent.
792    fn release(&mut self, mut packet: TaggedPacket, bits: f64) {
793        if packet.message.has(&Attribute::Retransmission)
794            && !Self::is_padding(&packet)
795            && let Some(key) = self.retransmission_key(&packet)
796        {
797            self.departed.push(key);
798        }
799        if let Some(probe) = self.probe.as_mut() {
800            packet.message.add(Attribute::Custom(Arc::new(ProbePacket {
801                cluster: probe.cluster,
802            })));
803            probe.remaining_bits -= bits;
804            if probe.remaining_bits <= 0.0 {
805                self.end_probe();
806            }
807        }
808        self.released.push_back(packet);
809    }
810
811    /// The packet a retransmission repairs, as (SSRC on the wire, sequence number repaired): on
812    /// an RTX stream the original sequence number ahead of the payload (RFC 4588 section 4),
813    /// otherwise (a retransmission under the media SSRC) its own sequence number.
814    fn retransmission_key(&self, packet: &TaggedPacket) -> Option<(u32, u16)> {
815        let Packet::Rtp(rtp) = &packet.message.packet else {
816            return None;
817        };
818        let ssrc = rtp.header.ssrc;
819        if self.repair_flows.contains(&ssrc) {
820            let osn = rtp.payload.get(..2)?;
821            return Some((ssrc, u16::from_be_bytes([osn[0], osn[1]])));
822        }
823        Some((ssrc, rtp.header.sequence_number))
824    }
825
826    /// Whether a retransmission of the packet `packet` repairs already waits in the queue
827    /// (retransmissions wait at its front).
828    fn retransmission_waits(&self, packet: &TaggedPacket) -> bool {
829        let Some(key) = self.retransmission_key(packet) else {
830            return false;
831        };
832        self.queue
833            .iter()
834            .take_while(|queued| queued.message.has(&Attribute::Retransmission))
835            .any(|queued| self.retransmission_key(queued) == Some(key))
836    }
837
838    /// Records a retransmission dropped from the queue, for [`RetransmissionsLeft`].
839    fn retransmission_dropped(&mut self, packet: &TaggedPacket) {
840        if let Some(key) = self.retransmission_key(packet) {
841            self.retransmissions_dropped.push(key);
842        }
843    }
844
845    /// Whether the pause should begin or end now (see "Pausing the source"); `true` when it
846    /// changed.
847    fn update_pause(&mut self, now: Instant) -> bool {
848        if self.collapsed(now) {
849            // Not a queue to wait out: the rate it was written for is gone. Also when the
850            // target goes on falling during a pause that began before it had halved.
851            self.flush(now);
852            // A pause in force ends with its queue.
853            return std::mem::replace(&mut self.paused, false);
854        }
855        let expected = self.expected_queue_time();
856        let change = match self.queue_time_limit {
857            Some(limit) if !self.paused => expected >= limit.mul_f64(PAUSE_AT),
858            Some(limit) => expected <= limit.mul_f64(RESUME_AT),
859            None => self.paused,
860        };
861        if change {
862            self.paused = !self.paused;
863            if self.paused {
864                self.pauses += 1;
865                self.pause_began = Some(now);
866            }
867        }
868        change
869    }
870
871    /// Records the target set at `now`, and drops the targets too old to count.
872    fn note_target(&mut self, now: Instant, bits_per_second: f64) {
873        if self.targets.back().map(|(_, target)| *target) != Some(bits_per_second) {
874            self.targets.push_back((now, bits_per_second));
875        }
876        self.forget_targets(now);
877    }
878
879    /// The instant from which the targets count toward a collapse at `now`: when the oldest
880    /// queued new media was written, or the queue time bound ago, whichever is earlier. What
881    /// waits here was written since, and so was what a retransmission queued now repairs,
882    /// as far as it is still worth sending (media that waited the bound is discarded as
883    /// stale). No target set before the last flush is kept ([`Self::flush`]), so the
884    /// horizon never reaches behind one.
885    fn collapse_horizon(&self, now: Instant) -> Option<Instant> {
886        let oldest = self.oldest_new_media();
887        let look_back = self
888            .queue_time_limit
889            .and_then(|limit| now.checked_sub(limit));
890        match (oldest, look_back) {
891            (Some(oldest), Some(look_back)) => Some(oldest.min(look_back)),
892            (oldest, look_back) => oldest.or(look_back),
893        }
894    }
895
896    /// Drops the targets replaced before [`Self::collapse_horizon`]; all but the last when
897    /// none counts.
898    fn forget_targets(&mut self, now: Instant) {
899        let horizon = self.collapse_horizon(now);
900        while self.targets.len() > 1 && horizon.is_none_or(|from| self.targets[1].0 <= from) {
901            self.targets.pop_front();
902        }
903        // Far more changes than a queue's lifetime holds: the oldest are let go (the collapse
904        // is then judged against a later, lower target, which errs towards the pause).
905        while self.targets.len() > MAX_TARGETS_KEPT {
906            self.targets.pop_front();
907        }
908    }
909
910    /// Whether the queue is long because the target collapsed: what waits (new media or
911    /// retransmissions) would take the pause mark or more to leave, whether a pause is in
912    /// force or about to begin, and the target is at most [`COLLAPSE_AT`] of the highest in force since
913    /// [`Self::collapse_horizon`] (see "A capacity collapse").
914    fn collapsed(&self, now: Instant) -> bool {
915        if self.backlog != Backlog::Flush || self.queue_overflow != QueueOverflow::Drop {
916            return false;
917        }
918        let Some(limit) = self.queue_time_limit else {
919            return false;
920        };
921        if self.queue.is_empty() || self.expected_queue_time() < limit.mul_f64(PAUSE_AT) {
922            return false;
923        }
924        let Some(horizon) = self.collapse_horizon(now) else {
925            return false;
926        };
927        let mut written_for: f64 = 0.0;
928        for (index, (_, target)) in self.targets.iter().enumerate() {
929            // In force at the horizon (the last set at or before it), or since.
930            let superseded = self
931                .targets
932                .get(index + 1)
933                .is_some_and(|(next, _)| *next <= horizon);
934            if !superseded {
935                written_for = written_for.max(*target);
936            }
937        }
938        written_for > 0.0 && self.target() <= COLLAPSE_AT * written_for
939    }
940
941    /// Gives the queue up at a collapse: retransmissions dropped, media discarded stream by
942    /// stream, the NACK responder told to forget what was sent before ([`PacerFlush`]), and
943    /// a key frame asked of every video stream.
944    fn flush(&mut self, now: Instant) {
945        let mut streams: Vec<(u32, Vec<TaggedPacket>)> = Vec::new();
946        for packet in std::mem::take(&mut self.queue) {
947            if packet.message.has(&Attribute::Retransmission) {
948                self.retransmission_dropped(&packet);
949                self.dropped += 1;
950            } else if let Packet::Rtp(rtp) = &packet.message.packet {
951                let ssrc = rtp.header.ssrc;
952                match streams.iter_mut().find(|(stream, _)| *stream == ssrc) {
953                    Some((_, packets)) => packets.push(packet),
954                    None => streams.push((ssrc, vec![packet])),
955                }
956            }
957        }
958        self.queued_bits = 0.0;
959        self.flushes += 1;
960        let mut asked: HashSet<u32> = HashSet::new();
961        for (ssrc, packets) in &streams {
962            // `PacerDiscard`, and for a media stream the key-frame request.
963            self.discard(now, *ssrc, packets, LocalKeyFrameRequest::PacerFlush);
964            asked.insert(*ssrc);
965        }
966        let mut ssrcs: Vec<u32> = self.video.iter().copied().collect();
967        ssrcs.sort_unstable();
968        // A video stream with nothing queued lost its repairs all the same.
969        for ssrc in ssrcs.iter().filter(|ssrc| !asked.contains(ssrc)) {
970            self.read_queue.push_back(TaggedPacket {
971                now,
972                transport: TransportContext::default(),
973                message: AttributedPacket::new(Packet::Rtcp(vec![Box::new(
974                    PictureLossIndication {
975                        sender_ssrc: 0,
976                        media_ssrc: *ssrc,
977                    },
978                )]))
979                .with(Attribute::DeliverToApplication)
980                .with(Attribute::Custom(Arc::new(
981                    LocalKeyFrameRequest::PacerFlush,
982                ))),
983            });
984        }
985        self.read_queue.push_back(TaggedPacket {
986            now,
987            transport: TransportContext::default(),
988            message: AttributedPacket::new(Packet::Rtcp(vec![]))
989                .with(Attribute::Custom(Arc::new(PacerFlush { ssrcs }))),
990        });
991        // What is written from here on is written for the target now: no earlier target
992        // counts again, so the key frame that answers this flush, however long it takes to
993        // leave, is a pause and not another collapse.
994        let target = self.target();
995        self.targets.clear();
996        self.targets.push_back((now, target));
997    }
998
999    /// Whether new media written at `written` is what a source that follows the pause left
1000    /// behind: written before the pause in force (or the last one) began, or within
1001    /// [`PAUSE_GRACE`] of that. It is never discarded for its age (see "Pausing the source").
1002    fn written_before_pause(&self, written: Instant) -> bool {
1003        self.pause_began
1004            .is_some_and(|began| written <= began + PAUSE_GRACE)
1005    }
1006
1007    /// Whether the queued `packet` is discarded once it has waited the queue time bound
1008    /// ([`QueueOverflow::Drop`]): a retransmission, and new media a pausing source would not
1009    /// have written.
1010    fn ages_out(&self, packet: &TaggedPacket) -> bool {
1011        packet.message.has(&Attribute::Retransmission) || !self.written_before_pause(packet.now)
1012    }
1013
1014    /// The target as the application is to read it: zero while paused, with [`PacerPause`]
1015    /// carrying the congestion controller's.
1016    fn tag_target(&self, message: &mut AttributedPacket) {
1017        if !self.paused {
1018            return;
1019        }
1020        let mut target = None;
1021        for attribute in &mut message.attributes {
1022            if let Attribute::TargetBitrateChanged { bits_per_second } = attribute {
1023                target = Some(*bits_per_second);
1024                *bits_per_second = 0.0;
1025            }
1026        }
1027        if let Some(target_bits_per_second) = target {
1028            message.add(Attribute::Custom(Arc::new(PacerPause {
1029                target_bits_per_second,
1030            })));
1031        }
1032    }
1033
1034    /// After a write or a timeout: a pause that began or ended goes application-ward as the
1035    /// target, and the retransmissions that left or were dropped as [`RetransmissionsLeft`].
1036    fn tell_application_ward(&mut self, now: Instant) {
1037        if self.update_pause(now) {
1038            let mut message =
1039                AttributedPacket::new(Packet::Rtcp(vec![])).with(Attribute::TargetBitrateChanged {
1040                    bits_per_second: self.target(),
1041                });
1042            // The controller's target said again, so with the minimum the controller gave it:
1043            // a reader that takes the minimum from each target (the NACK responder, which never
1044            // tells the original media less than it) would otherwise read "no minimum" here,
1045            // and lower the target by its whole retransmission reserve when a pause ends.
1046            if let Some(minimum) = self.minimum {
1047                message.add(Attribute::Custom(Arc::new(minimum)));
1048            }
1049            self.tag_target(&mut message);
1050            self.read_queue.push_back(TaggedPacket {
1051                now,
1052                transport: TransportContext::default(),
1053                message,
1054            });
1055        }
1056        if !self.departed.is_empty() || !self.retransmissions_dropped.is_empty() {
1057            let notice = RetransmissionsLeft {
1058                departed: std::mem::take(&mut self.departed),
1059                dropped: std::mem::take(&mut self.retransmissions_dropped),
1060            };
1061            self.read_queue.push_back(TaggedPacket {
1062                now,
1063                transport: TransportContext::default(),
1064                message: AttributedPacket::new(Packet::Rtcp(vec![]))
1065                    .with(Attribute::Custom(Arc::new(notice))),
1066            });
1067        }
1068    }
1069
1070    /// Applies the [`StreamsNotSending`] notice `packet` carries, if any (see
1071    /// [`Self::stop_streams`]); whether it did. Out of line: the search calls through each
1072    /// custom attribute's vtable, and inlined in `enqueue` it kept registers spilled on the
1073    /// path of every packet.
1074    #[cold]
1075    #[inline(never)]
1076    fn apply_notice(&mut self, packet: &TaggedPacket) -> bool {
1077        match packet.message.custom::<StreamsNotSending>() {
1078            Some(notice) => {
1079                self.stop_streams(packet.now, &notice.ssrcs);
1080                true
1081            }
1082            None => false,
1083        }
1084    }
1085
1086    /// Whether `packet` is RTP of a stream that may not send ([`StreamsNotSending`]).
1087    fn is_not_sending(&self, packet: &TaggedPacket) -> bool {
1088        matches!(&packet.message.packet, Packet::Rtp(rtp) if self.not_sending.contains(&rtp.header.ssrc))
1089    }
1090
1091    /// Counts a packet of a stream that may not send as dropped (a retransmission for
1092    /// [`RetransmissionsLeft`] too).
1093    #[cold]
1094    #[inline(never)]
1095    fn drop_not_sending(&mut self, packet: &TaggedPacket) {
1096        if packet.message.has(&Attribute::Retransmission) && !Self::is_padding(packet) {
1097            self.retransmission_dropped(packet);
1098        }
1099        self.not_sending_dropped += 1;
1100    }
1101
1102    /// The streams `ssrcs` may not send from `now` on (replacing those that could not
1103    /// before): everything of them that waits here (queued media and retransmissions,
1104    /// padding, and what was released for the next interceptor but has not gone to it) is
1105    /// dropped, without a key-frame request or a [`PacerDiscard`]: nothing is asked of a
1106    /// source that is not to send.
1107    ///
1108    /// Out of line and cold on purpose: `enqueue` looks for the notice on every packet written
1109    /// and finds it once per applied answer. Inlined there, this body made `handle_write`'s
1110    /// frame twice the size and the `Interceptor/Pacer/write+poll` benchmark slower
1111    /// (docs/performance.md, "pacer-4").
1112    #[cold]
1113    #[inline(never)]
1114    fn stop_streams(&mut self, now: Instant, ssrcs: &[u32]) {
1115        self.not_sending = ssrcs.iter().copied().collect();
1116        if self.not_sending.is_empty() {
1117            return;
1118        }
1119        let mut kept = VecDeque::with_capacity(self.queue.len());
1120        for packet in std::mem::take(&mut self.queue) {
1121            if self.is_not_sending(&packet) {
1122                self.queued_bits = (self.queued_bits - Self::bits_of(&packet)).max(0.0);
1123                self.drop_not_sending(&packet);
1124            } else {
1125                kept.push_back(packet);
1126            }
1127        }
1128        self.queue = kept;
1129        if self.queue.is_empty() {
1130            self.queued_bits = 0.0;
1131        }
1132        let mut padding = VecDeque::with_capacity(self.padding.len());
1133        for (cluster, packet) in std::mem::take(&mut self.padding) {
1134            if self.is_not_sending(&packet) {
1135                self.padding_discarded += 1;
1136                self.not_sending_dropped += 1;
1137            } else {
1138                padding.push_back((cluster, packet));
1139            }
1140        }
1141        self.padding = padding;
1142        let mut released = VecDeque::with_capacity(self.released.len());
1143        for packet in std::mem::take(&mut self.released) {
1144            if self.is_not_sending(&packet) {
1145                self.drop_not_sending(&packet);
1146            } else {
1147                released.push_back(packet);
1148            }
1149        }
1150        self.released = released;
1151        for ssrc in ssrcs {
1152            self.discarded_frame.remove(ssrc);
1153        }
1154        self.follow_queue(now);
1155    }
1156
1157    /// Whether `packet` is new media (not a retransmission) of the stream `ssrc`.
1158    fn is_new_media_of(packet: &TaggedPacket, ssrc: u32) -> bool {
1159        matches!(&packet.message.packet, Packet::Rtp(rtp) if rtp.header.ssrc == ssrc)
1160            && !packet.message.has(&Attribute::Retransmission)
1161    }
1162
1163    /// The stream of `packet` when it belongs to the frame discarded last on that stream; a
1164    /// packet of a later frame ends that frame's discard.
1165    fn continues_discard(&mut self, packet: &TaggedPacket) -> Option<u32> {
1166        let Packet::Rtp(rtp) = &packet.message.packet else {
1167            return None;
1168        };
1169        let ssrc = rtp.header.ssrc;
1170        let discarded = *self.discarded_frame.get(&ssrc)?;
1171        if discarded == rtp.header.timestamp {
1172            return Some(ssrc);
1173        }
1174        self.discarded_frame.remove(&ssrc);
1175        None
1176    }
1177
1178    /// Discards the frame of the queued new-media packet at `index` and every other queued
1179    /// frame of its stream (see "Discarding media" on [`PacerInterceptor`]).
1180    fn discard_stream_of(&mut self, now: Instant, index: usize) {
1181        let Some(Packet::Rtp(rtp)) = self.queue.get(index).map(|packet| &packet.message.packet)
1182        else {
1183            return;
1184        };
1185        let ssrc = rtp.header.ssrc;
1186        let mut discarded = Vec::new();
1187        let mut kept = VecDeque::with_capacity(self.queue.len());
1188        for packet in self.queue.drain(..) {
1189            if Self::is_new_media_of(&packet, ssrc) {
1190                discarded.push(packet);
1191            } else {
1192                kept.push_back(packet);
1193            }
1194        }
1195        self.queue = kept;
1196        let bits: f64 = discarded.iter().map(Self::bits_of).sum();
1197        self.queued_bits = (self.queued_bits - bits).max(0.0);
1198        self.discard(now, ssrc, &discarded, LocalKeyFrameRequest::PacerDiscard);
1199    }
1200
1201    /// Counts the discard of `packets` (new media of the stream `ssrc`, oldest first) and tells
1202    /// the chain application-ward: the NACK responder and the application through
1203    /// [`PacerDiscard`], and the application a key frame is needed (the request carrying
1204    /// `why`, [`LocalKeyFrameRequest`]).
1205    fn discard(
1206        &mut self,
1207        now: Instant,
1208        ssrc: u32,
1209        packets: &[TaggedPacket],
1210        why: LocalKeyFrameRequest,
1211    ) {
1212        let mut sequence_numbers = Vec::with_capacity(packets.len());
1213        let mut octets = 0usize;
1214        let mut frames = 0u32;
1215        let mut newest = self.discarded_frame.get(&ssrc).copied();
1216        for packet in packets {
1217            if let Packet::Rtp(rtp) = &packet.message.packet {
1218                sequence_numbers.push(rtp.header.sequence_number);
1219                octets += rtp.marshal_size();
1220                if newest != Some(rtp.header.timestamp) {
1221                    frames += 1;
1222                    newest = Some(rtp.header.timestamp);
1223                }
1224            }
1225        }
1226        if sequence_numbers.is_empty() {
1227            return;
1228        }
1229        if let Some(timestamp) = newest {
1230            self.discarded_frame.insert(ssrc, timestamp);
1231        }
1232        self.dropped += sequence_numbers.len() as u64;
1233        self.discarded_frames += u64::from(frames);
1234        let target_bitrate = self.target();
1235        self.read_queue.push_back(TaggedPacket {
1236            now,
1237            transport: TransportContext::default(),
1238            message: AttributedPacket::new(Packet::Rtcp(vec![])).with(Attribute::Custom(Arc::new(
1239                PacerDiscard {
1240                    ssrc,
1241                    sequence_numbers,
1242                    frames,
1243                    octets,
1244                    target_bitrate,
1245                },
1246            ))),
1247        });
1248        // A new frame lost (not only the rest of one already discarded): the stream needs a
1249        // key frame, asked for the way a receiver asks, so the application's PLI handling
1250        // answers it.
1251        if frames > 0 && !self.repair_flows.contains(&ssrc) {
1252            self.read_queue.push_back(TaggedPacket {
1253                now,
1254                transport: TransportContext::default(),
1255                message: AttributedPacket::new(Packet::Rtcp(vec![Box::new(
1256                    PictureLossIndication {
1257                        sender_ssrc: 0,
1258                        media_ssrc: ssrc,
1259                    },
1260                )]))
1261                .with(Attribute::DeliverToApplication)
1262                .with(Attribute::Custom(Arc::new(why))),
1263            });
1264        }
1265    }
1266}
1267
1268/// Media the pacer discarded for want of room in the target ([`QueueOverflow::Drop`]): whole
1269/// frames of one stream (see "Discarding media" on [`PacerInterceptor`]).
1270///
1271/// The pacer sends it application-ward, on an empty RTCP carrier on its read leg, at the
1272/// instant of the discard. The NACK responder removes the packets named here from its
1273/// retransmission buffer (a NACK for them is answered by nothing) and from the original
1274/// packets it counts against the target (they never used the link); the peer connection
1275/// hands it to the application as `RTCPeerConnectionEvent::OnPacerDiscard`. It means **the
1276/// source is above the target**: what the application writes has to come down to the target
1277/// it is given (`Attribute::TargetBitrateChanged`, `RTCRtpSender::target_bitrates`). Read with
1278/// [`AttributedPacket::custom`](crate::AttributedPacket::custom).
1279#[derive(Debug, Clone, PartialEq)]
1280pub struct PacerDiscard {
1281    /// The stream the packets were of.
1282    pub ssrc: u32,
1283    /// The sequence numbers of the packets discarded, oldest first.
1284    pub sequence_numbers: Vec<u16>,
1285    /// How many frames were discarded (0 when these packets are the rest of a frame already
1286    /// discarded).
1287    pub frames: u32,
1288    /// The octets of the packets discarded (RTP header and payload).
1289    pub octets: usize,
1290    /// The pacer's target at the discard, bits per second.
1291    pub target_bitrate: f64,
1292}
1293
1294/// The pacer gave its queue up at a collapse of the target ([`Backlog::Flush`], see "A capacity
1295/// collapse" on [`PacerInterceptor`]): sent application-ward on an empty RTCP carrier, after
1296/// the [`PacerDiscard`] of each stream that had media queued. The NACK responder forgets
1297/// everything sent before it on the streams named (their retransmission buffers, the requests
1298/// waiting): a NACK for any of it is answered by nothing, and the stream goes on from the key
1299/// frame the application is asked for. Read with
1300/// [`AttributedPacket::custom`](crate::AttributedPacket::custom).
1301#[derive(Debug, Clone, PartialEq, Eq)]
1302pub struct PacerFlush {
1303    /// The media SSRCs of the video streams flushed (every bound stream that is not audio).
1304    pub ssrcs: Vec<u32>,
1305}
1306
1307/// The local streams that may not send media now: the SSRCs (media, RTX and FEC) of the
1308/// senders whose negotiated direction does not send (`recvonly`, `inactive`). RFC 8866
1309/// section 6.7.4: "No media is sent over an inactive media stream", and section 6.7.1: a
1310/// receive-only stream is in "receive-only mode"; RFC 3264 section 5.1. W3C webrtc-pc 4.4.1.6:
1311/// an answer sets `[[CurrentDirection]]`, and a sender sends only while it is "sendrecv" or
1312/// "sendonly". RTCP is not affected (RFC 8866 section 6.7: it "MUST still" be sent).
1313///
1314/// The peer connection writes it into the chain each time an answer is applied, as an
1315/// [`Attribute::Custom`] on an empty RTCP packet ([`StreamsNotSending::into_packet`]); each
1316/// replaces the one before. The [`PacerInterceptor`] drops what it holds of those streams at
1317/// that instant (media, retransmissions, padding) and every packet of them written later; the
1318/// [`NackResponderInterceptor`](crate::NackResponderInterceptor) forgets what it sent of them,
1319/// answers no NACK for them and pads no probe on their RTX streams. Read with
1320/// [`AttributedPacket::custom`](crate::AttributedPacket::custom).
1321#[derive(Debug, Clone, PartialEq, Eq, Default)]
1322pub struct StreamsNotSending {
1323    /// The SSRCs of the streams, their RTX and FEC streams included.
1324    pub ssrcs: Vec<u32>,
1325}
1326
1327impl StreamsNotSending {
1328    /// The packet that carries this into the chain when written at `now`.
1329    pub fn into_packet(self, now: Instant) -> TaggedPacket {
1330        TaggedPacket {
1331            now,
1332            transport: TransportContext::default(),
1333            message: AttributedPacket::new(Packet::Rtcp(vec![]))
1334                .with(Attribute::Custom(Arc::new(self))),
1335        }
1336    }
1337}
1338
1339/// A collapse is a target at most this share of the highest in force since the queued media
1340/// was written (or within the queue time bound, for what its retransmissions repair): half.
1341/// One decrease of the delay-based controller is 0.85 and the loss-based controller cuts by
1342/// at most half a report, so a target that halved within the life of the queue (two seconds
1343/// at most) is a path that lost its capacity, not a controller adapting; and a queue a
1344/// flush's own key frame fills was written at the fallen target and is never a collapse.
1345const COLLAPSE_AT: f64 = 0.5;
1346
1347/// How many target changes are kept to say what queued media was written for.
1348const MAX_TARGETS_KEPT: usize = 1024;
1349
1350/// The pause begins when the expected queue time reaches this share of the queue time bound:
1351/// half, so a source that stops when told (within a frame or a read of its target) never lets
1352/// its packets wait the bound, even when the target falls by half once more meanwhile.
1353const PAUSE_AT: f64 = 0.5;
1354
1355/// The pause ends when the expected queue time is back under this share of the bound (100 ms
1356/// of the default 2 s): what then waits is the delay the call carries on with, so it is kept
1357/// short; the gap between the two shares keeps one frame from switching it on and off.
1358const RESUME_AT: f64 = 0.05;
1359
1360/// How long after a pause began media still counts as written by a source that follows it:
1361/// the time such a source takes to notice (a read of its target, the frame being encoded).
1362const PAUSE_GRACE: Duration = Duration::from_millis(250);
1363
1364/// Rides a target of zero ([`Attribute::TargetBitrateChanged`]) that the pacer hands
1365/// application-ward while it tells the source to pause (see "Pausing the source" on
1366/// [`PacerInterceptor`]): the congestion controller's target, for what application-ward of the
1367/// pacer needs the rate the path carries (the NACK responder's retransmission rate limit). Read
1368/// with [`AttributedPacket::custom`](crate::AttributedPacket::custom).
1369#[derive(Debug, Clone, Copy, PartialEq)]
1370pub struct PacerPause {
1371    /// The congestion controller's target, bits per second.
1372    pub target_bits_per_second: f64,
1373}
1374
1375/// The retransmissions that left the pacer, or were dropped there, since the last notice: each
1376/// as (SSRC on the wire, sequence number of the packet it repairs; the original sequence
1377/// number on an RTX stream). The pacer sends it application-ward on an empty RTCP carrier; the
1378/// NACK responder treats a packet as on its way while its retransmission waits in the pacer
1379/// and counts the resend interval from when it left, as libwebrtc's packet history does
1380/// (`modules/rtp_rtcp/source/rtp_packet_history.cc`: a request for a packet "already in pacer
1381/// queue" is ignored; the send time is set when it is sent). Read with
1382/// [`AttributedPacket::custom`](crate::AttributedPacket::custom).
1383#[derive(Debug, Clone, PartialEq, Default)]
1384pub struct RetransmissionsLeft {
1385    /// Released toward the wire.
1386    pub departed: Vec<(u32, u16)>,
1387    /// Dropped (waited the queue time bound, or the oldest of a full queue).
1388    pub dropped: Vec<(u32, u16)>,
1389}
1390
1391/// How long a probe cluster is held open for packets to fill it. A cluster that takes longer
1392/// than this to leave is not a burst any more and measures nothing.
1393const PROBE_CLUSTER_TIMEOUT: Duration = Duration::from_millis(250);
1394
1395/// A probe cluster on its way out.
1396struct ActiveProbe {
1397    cluster: u32,
1398    /// Meters the cluster's packets at the probe rate, one packet at a time.
1399    bucket: LeakyBucket,
1400    remaining_bits: f64,
1401    started: Instant,
1402}
1403
1404impl Protocol<TaggedPacket, TaggedPacket, ()> for PacerInterceptor {
1405    type Rout = TaggedPacket;
1406    type Wout = TaggedPacket;
1407    type Eout = ();
1408    type Error = Error;
1409    type Time = Instant;
1410
1411    fn handle_read(&mut self, mut msg: TaggedPacket) -> Result<(), Self::Error> {
1412        // Follow the congestion controller's estimate.
1413        //
1414        // It arrives on the **read** leg because that is the only one it can cross on. The
1415        // controller is wire-most, so on the write leg it is the last interceptor to see a packet
1416        // and anything it attached would already have gone past here. On the read leg it is the
1417        // first, and this is downstream of it — so the feedback packet that produced the estimate
1418        // carries it here on its way to the application.
1419        //
1420        // Observed, not consumed: the packet carries on with the attribute attached, so anything
1421        // further along reads the same number.
1422        if let Some(Attribute::TargetBitrateChanged { bits_per_second }) =
1423            msg.message.get(&Attribute::TargetBitrateChanged {
1424                bits_per_second: 0.0,
1425            })
1426        {
1427            match self.raised_from.as_mut() {
1428                // Raised to drain the queue: the new target is what it comes back to.
1429                Some(target) => *target = *bits_per_second,
1430                None => self.pacer.set_target_bitrate(*bits_per_second),
1431            }
1432            self.minimum = msg.message.custom::<crate::MinimumTarget>().copied();
1433            let target = *bits_per_second;
1434            self.note_target(msg.now, target);
1435            // A new rate changes how long the queue takes to leave: the pause may begin or
1436            // end, and the application reads it on this packet.
1437            self.update_pause(msg.now);
1438            self.tag_target(&mut msg.message);
1439        }
1440
1441        // A flow the circuit breaker ceased or restarted (it sits wire-ward of here).
1442        if let Some(notice) = msg.message.custom::<crate::CircuitBreakerNotice>() {
1443            if notice.ceased.is_some() {
1444                self.ceased.insert(notice.ssrc);
1445            } else {
1446                self.ceased.remove(&notice.ssrc);
1447            }
1448        }
1449
1450        // A probe cluster the congestion controller asks for: the next packets leave at its
1451        // rate, on top of the target's budget, and carry its mark. Observed, not consumed:
1452        // the NACK responder above reads the same request and fills the cluster.
1453        if let Some(request) = msg.message.custom::<ProbeRequest>().copied() {
1454            // A cluster still being sent is over: the new one takes its place.
1455            self.end_probe();
1456            let mut bucket = LeakyBucket::new(request.bits_per_second)
1457                .with_burst_bits(crate::pacing::pacer::MIN_BURST_BITS);
1458            bucket.refill(msg.now);
1459            self.probe = Some(ActiveProbe {
1460                cluster: request.cluster,
1461                bucket,
1462                remaining_bits: request.octets as f64 * 8.0,
1463                started: msg.now,
1464            });
1465            // What waits in the media queue leaves first and fills the cluster: the
1466            // responder is asked for the rest only.
1467            let queued_octets = (self.queued_bits.max(0.0) / 8.0) as usize;
1468            msg.message.add(Attribute::Custom(Arc::new(ProbeFill {
1469                cluster: request.cluster,
1470                octets: request.octets.saturating_sub(queued_octets),
1471            })));
1472        }
1473
1474        self.read_queue.push_back(msg);
1475        Ok(())
1476    }
1477
1478    fn poll_read(&mut self) -> Option<Self::Rout> {
1479        self.read_queue.pop_front()
1480    }
1481
1482    fn handle_write(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
1483        let now = msg.now;
1484        let rtp = matches!(msg.message.packet, Packet::Rtp(_));
1485        // Nothing here borrows `msg` before it moves into `enqueue`: a borrow (the search for
1486        // the `StreamsNotSending` notice was one) makes the move a copy of every packet
1487        // written (224 bytes on x86-64). `enqueue` looks for the notice and says whether it
1488        // applied one.
1489        let not_sending = self.enqueue(msg)?;
1490        if rtp || not_sending {
1491            self.tell_application_ward(now);
1492        }
1493        Ok(())
1494    }
1495
1496    fn poll_write(&mut self) -> Option<TaggedPacket> {
1497        // Unpaced traffic goes first — RTCP is only useful while it is fresh, and holding it
1498        // behind the budget would be pacing it after all.
1499        self.write_queue
1500            .pop_front()
1501            .or_else(|| self.released.pop_front())
1502    }
1503
1504    fn handle_timeout(&mut self, now: Instant) -> Result<(), Error> {
1505        self.release_due(now);
1506        self.tell_application_ward(now);
1507        Ok(())
1508    }
1509
1510    fn poll_timeout(&mut self) -> Option<Instant> {
1511        self.next_release()
1512    }
1513}
1514
1515impl PacerInterceptor {
1516    /// A packet written: released, queued, or discarded; whether it carried a
1517    /// [`StreamsNotSending`] notice (applied first, see [`Self::stop_streams`]).
1518    fn enqueue(&mut self, msg: TaggedPacket) -> Result<bool, Error> {
1519        // No estimate is read here. It was, once — but the congestion controller sits wire-*ward*
1520        // of the pacer, so on the write leg it never sees a packet before this interceptor does and
1521        // the branch had no possible producer. If an application-set target is ever wanted it comes
1522        // back with its own `RTCEvent` variant, and a test.
1523
1524        // The streams that may not send from now on: what waits of them goes.
1525        let not_sending = !msg.message.attributes.is_empty() && self.apply_notice(&msg);
1526
1527        // RTCP is control traffic and mostly time-sensitive — feedback is only useful while it is
1528        // fresh — so it is not paced.
1529        if matches!(msg.message.packet, Packet::Rtcp(_)) {
1530            self.write_queue.push_back(msg);
1531            return Ok(not_sending);
1532        }
1533
1534        // A stream that may not send (`StreamsNotSending`): written after its direction
1535        // changed (a retransmission, padding, FEC), it does not leave.
1536        if self.is_not_sending(&msg) {
1537            self.drop_not_sending(&msg);
1538            return Ok(not_sending);
1539        }
1540
1541        // A flow the circuit breaker ceased (RFC 8083 section 4.5): its packets are dropped
1542        // at the breaker, below. They pass here unmetered: charged to the budget, a voice the
1543        // application keeps writing took 76 of a 100 kbit/s target that the video then
1544        // could not use (`tests/capacity_cap_video_rtc2rtc.rs`'s path), for packets that
1545        // never left.
1546        if matches!(&msg.message.packet, Packet::Rtp(rtp) if self.ceased.contains(&rtp.header.ssrc))
1547        {
1548            self.released.push_back(msg);
1549            return Ok(not_sending);
1550        }
1551
1552        // Keeping the budget current at enqueue time is what lets `poll_timeout` compute a
1553        // deadline that is never in the past, even before the first `handle_timeout`.
1554        self.refill(msg.now);
1555        self.follow_queue(msg.now);
1556
1557        // Audio is never queued behind video: its packets are small and few, and a voice that
1558        // waits behind a video backlog is the call breaking up. It leaves at once and is
1559        // charged to the budget, which the packets behind it then wait out.
1560        if self.is_audio(&msg) {
1561            let bits = Self::bits_of(&msg);
1562            if !self.try_spend(bits) {
1563                self.pacer.consume(bits);
1564            }
1565            self.release(msg, bits);
1566            return Ok(not_sending);
1567        }
1568
1569        // Padding waits behind every other packet, and nothing waits behind it.
1570        let padding = Self::is_padding(&msg);
1571        // Written for a cluster that has ended already (filled by media in the instant it
1572        // was asked for): it would only leave late.
1573        if padding && self.probe.is_none() && self.ended_cluster_asked == Some(msg.now) {
1574            self.padding_discarded += 1;
1575            return Ok(not_sending);
1576        }
1577
1578        // The rest of a frame already discarded is worth nothing either.
1579        let new_media = !padding && !msg.message.has(&Attribute::Retransmission);
1580        if new_media && let Some(ssrc) = self.continues_discard(&msg) {
1581            self.discard(
1582                msg.now,
1583                ssrc,
1584                std::slice::from_ref(&msg),
1585                LocalKeyFrameRequest::PacerDiscard,
1586            );
1587            return Ok(not_sending);
1588        }
1589
1590        // Inside the budget and first in line: it leaves now. The budget is the bound on what
1591        // may enter the path at once, so nothing is gained by holding the packet for a timer.
1592        // Queued padding is not in line ahead of media.
1593        if self.immediate_release && self.queue.is_empty() && (!padding || self.padding.is_empty())
1594        {
1595            let bits = Self::bits_of(&msg);
1596            if self.try_spend(bits) {
1597                self.release(msg, bits);
1598                return Ok(not_sending);
1599            }
1600        }
1601
1602        if padding {
1603            // Never over the budget and never counted toward the queue time bound (see the
1604            // order of service); at the limit the arrival is discarded.
1605            if self.padding.len() >= self.queue_limit {
1606                self.padding_discarded += 1;
1607            } else {
1608                let cluster = self.probe.as_ref().map(|probe| probe.cluster);
1609                self.padding.push_back((cluster, msg));
1610            }
1611            return Ok(not_sending);
1612        }
1613
1614        // A retransmission of a packet whose retransmission already waits adds nothing but a
1615        // second copy (libwebrtc's packet history ignores a request for a packet "already in
1616        // pacer queue", `rtp_packet_history.cc`).
1617        if !new_media && self.retransmission_waits(&msg) {
1618            self.duplicate_retransmissions += 1;
1619            return Ok(not_sending);
1620        }
1621
1622        if self.queue.len() >= self.queue_limit {
1623            // Room for the arrival: the oldest goes (the newest is the one still worth
1624            // sending). Discarded by default, a retransmission alone, new media with its
1625            // stream's queued frames; with `Drain` it leaves now, over the budget.
1626            let retransmission = self
1627                .queue
1628                .front()
1629                .is_some_and(|oldest| oldest.message.has(&Attribute::Retransmission));
1630            match self.queue_overflow {
1631                QueueOverflow::Drop if !retransmission => {
1632                    self.discard_stream_of(msg.now, 0);
1633                    if new_media && let Some(ssrc) = self.continues_discard(&msg) {
1634                        self.discard(
1635                            msg.now,
1636                            ssrc,
1637                            std::slice::from_ref(&msg),
1638                            LocalKeyFrameRequest::PacerDiscard,
1639                        );
1640                        return Ok(not_sending);
1641                    }
1642                }
1643                _ => {
1644                    if let Some(mut oldest) = self.queue.pop_front() {
1645                        let bits = Self::bits_of(&oldest);
1646                        self.queued_bits -= bits;
1647                        if self.queue_overflow == QueueOverflow::Drain {
1648                            self.pacer.consume(bits);
1649                            oldest.now = msg.now;
1650                            self.forced += 1;
1651                            self.release(oldest, bits);
1652                        } else {
1653                            self.retransmission_dropped(&oldest);
1654                            self.dropped += 1;
1655                        }
1656                    }
1657                }
1658            }
1659        }
1660
1661        // Held: it leaves later, from `poll_write`, when the budget allows. A retransmission
1662        // goes ahead of the new media waiting, behind the retransmissions before it: a repair
1663        // the NACK responder has already held to the congestion controller's target is worth
1664        // most early, and waiting behind seconds of new video it may outlive its use or be
1665        // dropped as overdue. libwebrtc's pacer orders its queue the same way
1666        // (`modules/pacing/prioritized_packet_queue.cc`, `GetPriorityForType`: "Send
1667        // retransmissions before new media").
1668        let now = msg.now;
1669        self.queued_bits += Self::bits_of(&msg);
1670        if msg.message.has(&Attribute::Retransmission) {
1671            let end = self
1672                .queue
1673                .iter()
1674                .position(|queued| !queued.message.has(&Attribute::Retransmission))
1675                .unwrap_or(self.queue.len());
1676            // Among the retransmissions of one stream the oldest packet goes first, whenever
1677            // it was asked for: a receiver that plays in order waits for the oldest gap, and
1678            // a repair that was itself lost and is made again would otherwise wait behind
1679            // every newer one.
1680            let at = self
1681                .retransmission_key(&msg)
1682                .map_or(end, |(ssrc, repaired)| {
1683                    self.queue
1684                        .iter()
1685                        .take(end)
1686                        .position(|queued| {
1687                            self.retransmission_key(queued)
1688                                .is_some_and(|(other, waiting)| {
1689                                    other == ssrc
1690                                        && waiting != repaired
1691                                        && waiting.wrapping_sub(repaired) < 0x8000
1692                                })
1693                        })
1694                        .unwrap_or(end)
1695                });
1696            self.queue.insert(at, msg);
1697            if at == 0 {
1698                // First in line now: it may leave at once if the budget allows.
1699                self.release_due(now);
1700            }
1701            self.follow_queue(now);
1702            return Ok(not_sending);
1703        }
1704        self.queue.push_back(msg);
1705        self.follow_queue(now);
1706        Ok(not_sending)
1707    }
1708
1709    /// Releases what the budget allows at `now`, and drops what waited the bound.
1710    fn release_due(&mut self, now: Instant) {
1711        self.refill(now);
1712        self.follow_queue(now);
1713
1714        while let Some(head) = self.queue.front() {
1715            let bits = Self::bits_of(head);
1716            // Past the queue time limit the head is dropped (`Drop`) or leaves whatever the
1717            // budget says (`Drain`).
1718            let overdue = self
1719                .queue_time_limit
1720                .is_some_and(|limit| now.saturating_duration_since(head.now) >= limit)
1721                && (self.queue_overflow == QueueOverflow::Drain || self.ages_out(head));
1722            if overdue {
1723                if self.queue_overflow == QueueOverflow::Drop {
1724                    // A retransmission is dropped alone; new media with every queued frame
1725                    // of its stream (see "Discarding media").
1726                    if head.message.has(&Attribute::Retransmission) {
1727                        if let Some(dropped) = self.queue.pop_front() {
1728                            self.retransmission_dropped(&dropped);
1729                        }
1730                        self.queued_bits = (self.queued_bits - bits).max(0.0);
1731                        self.dropped += 1;
1732                    } else {
1733                        self.discard_stream_of(now, 0);
1734                    }
1735                    continue;
1736                }
1737                self.pacer.consume(bits);
1738                self.forced += 1;
1739            } else if !self.try_spend(bits) {
1740                break;
1741            }
1742
1743            let mut packet = self.queue.pop_front().expect("front just checked");
1744            self.queued_bits = (self.queued_bits - bits).max(0.0);
1745            // Rule 3: the packet departs now. Anything below recording departure — the send
1746            // history congestion control reads — must see the release instant, not the enqueue
1747            // instant, or this queueing delay is charged to the network.
1748            packet.now = now;
1749            // Queued for `poll_write`, which puts it back on the belt so it traverses every
1750            // interceptor ahead — numbering, and the send history reading the release instant just set.
1751            self.release(packet, bits);
1752        }
1753        if self.queue.is_empty() {
1754            self.queued_bits = 0.0;
1755            // No media waits: padding leaves from what the budget has left, never over it.
1756            while let Some((_, head)) = self.padding.front() {
1757                let bits = Self::bits_of(head);
1758                if !self.try_spend(bits) {
1759                    break;
1760                }
1761                let (_, mut packet) = self.padding.pop_front().expect("front just checked");
1762                packet.now = now;
1763                self.release(packet, bits);
1764            }
1765        }
1766        self.follow_queue(now);
1767    }
1768}
1769
1770impl Interceptor for PacerInterceptor {
1771    /// Audio streams (and their repair flows) are not queued behind others. The repair flows of
1772    /// the other streams are remembered: a discard on one asks for no key frame.
1773    fn bind_local_stream(&mut self, info: &StreamInfo) {
1774        if info.mime_type.to_ascii_lowercase().starts_with("audio/") {
1775            self.audio.extend(crate::twcc::flow_ssrcs(info));
1776        } else {
1777            self.video.insert(info.ssrc);
1778            self.repair_flows
1779                .extend(info.ssrc_rtx.into_iter().chain(info.ssrc_fec));
1780        }
1781    }
1782
1783    fn unbind_local_stream(&mut self, info: &StreamInfo) {
1784        self.video.remove(&info.ssrc);
1785        for ssrc in crate::twcc::flow_ssrcs(info) {
1786            self.audio.remove(&ssrc);
1787            self.discarded_frame.remove(&ssrc);
1788            self.ceased.remove(&ssrc);
1789        }
1790        for ssrc in info.ssrc_rtx.into_iter().chain(info.ssrc_fec) {
1791            self.repair_flows.remove(&ssrc);
1792        }
1793    }
1794
1795    fn bind_remote_stream(&mut self, _info: &StreamInfo) {}
1796
1797    fn unbind_remote_stream(&mut self, _info: &StreamInfo) {}
1798}