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