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::{ProbePacket, ProbeRequest};
7use crate::{Attribute, AttributedPacket, Packet, TaggedPacket};
8use rtcp::payload_feedbacks::picture_loss_indication::PictureLossIndication;
9use sansio::Protocol;
10use shared::TransportContext;
11use shared::error::Error;
12use shared::marshal::MarshalSize;
13use std::collections::{HashMap, HashSet, VecDeque};
14use std::sync::Arc;
15use std::time::{Duration, Instant};
16
17/// Rate used when none is configured: 1 Mb/s.
18pub const DEFAULT_BITRATE: f64 = 1_000_000.0;
19
20/// Packets held before the queue overflows (see [`QueueOverflow`]).
21pub const DEFAULT_QUEUE_LIMIT: usize = 4096;
22
23/// How long a packet may wait in the queue by default (libwebrtc's
24/// `kMaxExpectedQueueLength`, 2 s); what happens to one that would wait longer is
25/// [`QueueOverflow`]'s.
26pub const DEFAULT_QUEUE_TIME_LIMIT: Duration = Duration::from_secs(2);
27
28/// What the pacer does with media the target has no room for: a packet that has waited the
29/// queue time limit, or the oldest one when a packet arrives at a full queue. It happens only
30/// when the application writes faster than the congestion controller's target for longer
31/// than the limit.
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
33#[non_exhaustive]
34pub enum QueueOverflow {
35    /// The media is discarded here, whole frames at a time (see [`PacerDiscard`]; counted by
36    /// [`PacerInterceptor::dropped`] and [`PacerInterceptor::discarded_frames`]): nothing
37    /// leaves above the target. The congestion controller's target is what the path carries (RFC
38    /// 8836 section 2; RFC 8083 section 4 stops a flow that does not keep to it), so a sender
39    /// that put the excess on the path anyway would fill the bottleneck's queue, lose there
40    /// and drive the estimate to its floor: a 2.4 Mbit/s source on a 600 kbit/s link
41    /// (`tests/gcc_rate_limited_link_rtc2rtc.rs`, and netem in
42    /// `testenv_impairment::gcc_follows_a_rate_limited_link`) held a target of 500 to 590
43    /// kbit/s this way, and fell to 100 kbit/s with [`QueueOverflow::Drain`]. The receiver
44    /// counts the dropped packets as lost, which they are; the NACK responder does not resend
45    /// them, and the application is asked for a key frame (see [`PacerDiscard`]).
46    #[default]
47    Drop,
48    /// libwebrtc's pacer (`drain_large_queues`, `MaybeUpdateMediaRateDueToLongQueue`): the
49    /// pacing rate is raised above the target as far as it takes to drain the queue before
50    /// its oldest packet has waited the limit, a packet that has waited it leaves whatever the
51    /// budget says, and a full queue releases its oldest over the budget (counted by
52    /// [`PacerInterceptor::forced`]). Nothing the application wrote is lost here, and a
53    /// source that keeps above the target puts all of it on the path. For an encoder that
54    /// follows the target, as libwebrtc's does.
55    Drain,
56}
57
58/// Builder for [`PacerInterceptor`].
59///
60/// # Example
61///
62/// ```
63/// use rtci_interceptor::{Slot, PacerBuilder, Registry};
64///
65/// let chain = Registry::new()
66///     .with(Slot::Pacer, PacerBuilder::new().with_target_bitrate(2_000_000.0).build())
67///     .build();
68/// ```
69pub struct PacerBuilder {
70    bitrate: f64,
71    burst_bits: Option<f64>,
72    queue_limit: usize,
73    queue_time_limit: Option<Duration>,
74    queue_overflow: QueueOverflow,
75    immediate_release: bool,
76}
77
78impl Default for PacerBuilder {
79    fn default() -> Self {
80        Self {
81            bitrate: DEFAULT_BITRATE,
82            burst_bits: None,
83            queue_limit: DEFAULT_QUEUE_LIMIT,
84            queue_time_limit: Some(DEFAULT_QUEUE_TIME_LIMIT),
85            queue_overflow: QueueOverflow::default(),
86            immediate_release: true,
87        }
88    }
89}
90
91impl PacerBuilder {
92    /// Create a builder with the default rate and queue limit.
93    pub fn new() -> Self {
94        Self::default()
95    }
96
97    /// The rate to pace at, in bits per second.
98    pub fn with_target_bitrate(mut self, bits_per_second: f64) -> Self {
99        self.bitrate = bits_per_second;
100        self
101    }
102
103    /// How much may be released at once, in bits.
104    ///
105    /// Larger bursts smooth less but cost fewer wake-ups.
106    pub fn with_burst_bits(mut self, burst_bits: f64) -> Self {
107        self.burst_bits = Some(burst_bits);
108        self
109    }
110
111    /// How many packets may be queued. When a packet arrives at a full queue, the oldest one
112    /// is dropped or leaves over the budget, as [`Self::with_queue_overflow`] says.
113    pub fn with_queue_limit(mut self, queue_limit: usize) -> Self {
114        self.queue_limit = queue_limit;
115        self
116    }
117
118    /// How long a packet may wait in the queue ([`DEFAULT_QUEUE_TIME_LIMIT`] by default,
119    /// `None` for no bound). When the application writes faster than the congestion
120    /// controller's target, the queue grows; a packet that would wait longer than this is
121    /// dropped or drained above the target, as [`Self::with_queue_overflow`] says. The
122    /// application learns that its source is above the target from the target itself
123    /// (`TargetBitrateChanged`, `RTCRtpSender::target_bitrates`), from
124    /// [`PacerInterceptor::queue_time`], and, once media had to be discarded, from
125    /// [`PacerDiscard`] (`RTCPeerConnectionEvent::OnPacerDiscard` in the peer connection) and
126    /// the key-frame request that goes with it.
127    pub fn with_queue_time_limit(mut self, limit: Option<Duration>) -> Self {
128        self.queue_time_limit = limit;
129        self
130    }
131
132    /// What happens to media the target has no room for ([`QueueOverflow::Drop`] by default).
133    pub fn with_queue_overflow(mut self, overflow: QueueOverflow) -> Self {
134        self.queue_overflow = overflow;
135        self
136    }
137
138    /// Whether a packet the budget already covers leaves when it is written, with nothing
139    /// queued ahead of it. On by default.
140    ///
141    /// The pacer exists to keep a sender from putting more than its target rate times the
142    /// burst time on the path at once (draft-ietf-rmcat-gcc-02 section 4: a group of packets
143    /// of that size every `burst_time`, 5 ms recommended). The budget is that bound: it never
144    /// holds more than one burst and refills at the target rate. A packet inside it adds
145    /// nothing to what the bound allows, and holding it until the next wake-up only adds
146    /// delay the sender caused itself, which RFC 8836 section 2 (requirement 1) asks a
147    /// congestion controller for interactive media to keep as low as possible; no RFC asks
148    /// for the wait. `false` restores it: every packet is queued and leaves from the next
149    /// timeout, so departures happen only on the driver's clock.
150    pub fn with_immediate_release(mut self, immediate_release: bool) -> Self {
151        self.immediate_release = immediate_release;
152        self
153    }
154
155    /// Build the interceptor.
156    pub fn build(self) -> PacerInterceptor {
157        let bucket = match self.burst_bits {
158            Some(burst_bits) => LeakyBucket::new(self.bitrate).with_burst_bits(burst_bits),
159            None => LeakyBucket::new(self.bitrate),
160        };
161        let mut pacer = PacerInterceptor::new(bucket, self.queue_limit);
162        pacer.immediate_release = self.immediate_release;
163        pacer.queue_time_limit = self.queue_time_limit;
164        pacer.queue_overflow = self.queue_overflow;
165        pacer
166    }
167}
168
169/// Releases queued packets at a target rate rather than as fast as they arrive.
170///
171/// # Where this belongs in the chain
172///
173/// **Close to the wire, with every generator on the application side of it.** Everything after it
174/// on the write path observes the *release* instant, so a send history goes there and records what
175/// actually left; placed the other way round it would record the enqueue instant and charge this
176/// queueing delay to the network.
177///
178/// Retransmissions, FEC repair packets and generated RTCP are all produced further out and reach
179/// the pacer on the belt, so they are metered along with everything else. Under the nested chain
180/// they bypassed it entirely.
181///
182/// # Differences from upstream
183///
184/// - **No ticker and no goroutine.** Upstream runs a loop on a 5 ms `time.Ticker`; here the
185///   budget is a pure function of the instants handed in, so a release schedule is reproducible
186///   rather than merely eventually-correct.
187/// - **Idle means idle.** `poll_timeout` returns `None` with nothing queued, so an idle
188///   connection does not wake the whole chain at the pacing interval.
189/// - **The deadline is when the head can afford to go**, not `now + interval`, so it always
190///   advances — a deadline at or before the `now` just handed to `handle_timeout` is the
191///   webrtc#862 busy-loop.
192///
193/// # Order of service
194///
195/// 1. **Audio** (the packets of a stream bound with an `audio/` codec) leaves the moment it is
196///    written, charged to the budget, which the packets behind it then wait out. A voice that
197///    waits behind a video backlog is the call breaking up.
198/// 2. **Audio retransmissions** leave the same way: an audio stream's repair flows (its RTX
199///    and FEC SSRCs, from [`Interceptor::bind_local_stream`]) count as audio, so an audio
200///    retransmission never waits behind video either.
201/// 3. **Video retransmissions** (`Attribute::Retransmission` on any other stream) wait in the
202///    media queue ahead of all new media (libwebrtc's `prioritized_packet_queue.cc`: "Send
203///    retransmissions before new media"), a stream's oldest packet first (by the sequence
204///    number repaired, whenever each was written: a receiver that plays in order waits for
205///    its oldest gap). One whose packet
206///    already has a retransmission waiting is not queued again
207///    ([`PacerInterceptor::duplicate_retransmissions`]), and each that leaves or is dropped is
208///    reported application-ward ([`RetransmissionsLeft`]), so the NACK responder does not make
209///    another while one waits.
210/// 4. **Video and FEC** (every other RTP packet that is not padding) wait behind them, in the
211///    order written. The **queue time bound** (2 s by default,
212///    [`PacerBuilder::with_queue_time_limit`]) and the queue limit are this queue's (3 and 4):
213///    by default ([`QueueOverflow::Drop`]) what has waited the bound, or the oldest packet when
214///    the queue is full, is discarded, so nothing leaves above the target (a retransmission
215///    one packet at a time, new media whole frames at a time: see "Discarding media" below);
216///    [`QueueOverflow::Drain`] raises the pacing rate above the target instead (libwebrtc's
217///    `MaybeUpdateMediaRateDueToLongQueue`) and releases those packets over the budget.
218/// 5. **Padding** (padding-only packets, RFC 3550 section 5.1: the padding bit and no payload,
219///    which the NACK responder fills a probe cluster with) waits in a queue of its own and leaves
220///    only when no media waits. A probe cluster is written as a burst of padding the moment it is
221///    asked for; queued in line with the media it would hold every packet the application writes
222///    during the cluster behind all of it (140 to 180 ms for a 6000-octet cluster at 200 kbit/s
223///    in `early_media_rtc2rtc`). Media written during a cluster leaves first, at the cluster's
224///    rate and with its mark, so it fills the cluster in place of padding, as in libwebrtc's
225///    pacer (padding has the lowest priority of its packet queue).
226///
227/// Padding is outside the queue time bound: it never counts toward raising the pacing rate
228/// (with [`QueueOverflow::Drain`]), is never dropped as overdue nor released over the budget,
229/// and so never goes ahead of media or past the rate the congestion controller set. Padding older than the bound
230/// is **sent late, not dropped**. Each padding packet already holds the next sequence number
231/// of its RTX stream (the responder numbers it when it fills the cluster), so dropping it
232/// would leave a hole in that stream which a receiver counts as lost (RFC 3550 appendix A.3,
233/// expected minus received) and the RTCP reports carry back as loss nobody had on the path.
234/// Sent late it costs nothing: it leaves only from budget no media wants. A padding queue
235/// that reaches the queue limit (4096 packets, far beyond what probing writes while media
236/// waits) discards the padding that arrives, counted by [`PacerInterceptor::padding_discarded`]:
237/// the one place padding can leave a hole, preferred to letting it go over the budget.
238///
239/// # Pausing the source
240///
241/// When the media queued would take half the queue time bound or more to leave at the target
242/// ([`PacerInterceptor::expected_queue_time`]; 1 s of the default 2 s), the pacer tells the
243/// application to **stop producing**: every [`Attribute::TargetBitrateChanged`] it passes
244/// application-ward carries **zero** (so `RTCRtpSender::target_bitrates` and the stats read
245/// zero), with [`PacerPause`] carrying the congestion controller's target for the interceptors
246/// that need the path's rate, and it announces the change at once on a carrier of its own. When
247/// the queue is back under a twentieth of the bound (100 ms), it announces the real target
248/// again. libwebrtc does the same: its control handler gives the encoder a target of zero while
249/// the pacer's expected queue time exceeds 2 s
250/// (`modules/congestion_controller/rtp/control_handler.cc`, `pacing_controller.h`: "the packet
251/// producers should wait (eg drop frames rather than encoding them)"). Pausing at half the
252/// bound, not at the bound, leaves a source that stops when told the time to notice (a frame
253/// interval, a read of its target) and room for the target to fall once more.
254///
255/// **What a source that follows the pause wrote is never discarded for its age**: the media
256/// written before the pause began (and within 250 ms of it, the time to notice) stays queued
257/// until it leaves, however long that takes. At a sudden drop of the path's capacity that can be
258/// seconds: the target may fall to a tenth of what the queued media was written for, and the
259/// retransmissions of what the path lost at the drop leave ahead of it (order of service 3),
260/// which is also the order a receiver needs them in. Nothing new joins the queue meanwhile, so
261/// it is bounded by what was there when the pause began; discarding it would leave a gap in the
262/// stream that costs the receiver more than the wait (a receiver that waits for missing packets
263/// by count, as `rtci-media`'s `SampleBuilder` does, sat 9 s on such a gap in
264/// `tests/capacity_cap_video_rtc2rtc.rs`). The queue time bound and the discard below are for
265/// media written into a pause: a source that does not follow it.
266///
267/// **Known limit.** After a sudden drop the picture a receiver shows can be seconds old while
268/// those retransmissions leave: in that test (2.5 Mbit/s into a path that drops to
269/// 300 kbit/s) the receiver never went 2 s without a usable frame (1.38 to 1.90 s), but the
270/// oldest picture it showed was 5.95 to 8.56 s old, against 2.26 to 3.21 s in a chain without
271/// a pacer. The 55 to 62 video packets the path dropped are repaired inside an estimate of 100
272/// to 250 kbit/s of which the audio takes 76, under every retransmission rule, and 35 to 41
273/// of the 90 to 103 retransmissions repeat a packet whose first repair was still in flight
274/// when the receiver asked again (they arrive after it). Dropping the repairs and asking for
275/// a key frame instead is worse for a receiver that plays in order (measured: frozen for 8 s,
276/// as it holds the gap for its whole packet window); what is planned is no repeat repair of a
277/// packet whose first repair transport-wide feedback reports received.
278///
279/// **A target of zero means: produce nothing until the next target.** An encoder skips (does
280/// not encode) the frames captured meanwhile; it does not need a key frame to resume, because
281/// nothing it encoded was lost: the next frame it encodes refers to the last one it sent, which
282/// is still queued here and reaches the receiver. libwebrtc resumes the same way: it encodes the
283/// last frame captured during the pause, or asks the capturer for a fresh one
284/// (`video_stream_encoder.cc`, `OnBitrateUpdated`: "A pending stored frame can be processed",
285/// else `RequestRefreshFrame`), and forces no key frame. Audio is not queued here and can carry
286/// on; the target is the transport's. Media the application writes anyway is queued and, past
287/// the bound, discarded as below, with a key-frame request: that, not the resume, is when a key
288/// frame is needed.
289///
290/// # Discarding media
291///
292/// With [`QueueOverflow::Drop`], new media the target has no room for is discarded **whole
293/// frames at a time**. A frame is the packets of one stream (SSRC) with one RTP timestamp (RFC
294/// 3550 section 5.1: the packets of one frame share it; the marker bit ends it). A frame with a
295/// packet missing is worth nothing to a decoder, and so is every later frame that refers to it,
296/// up to the next key frame; a frame that waited two seconds is stale anyway. So when the
297/// oldest new-media packet has waited the bound (or is the oldest of a full queue), the pacer
298/// discards every queued packet of its stream that is not a retransmission, oldest frame first,
299/// and the packets of the newest discarded frame the application writes after that. Nothing
300/// marks a key frame on this path (the application writes RTP packets, and only the codec's
301/// payload says which frame is a key frame), so no queued frame of the stream is kept as one:
302/// the key frame the application writes in answer to the request below is the next frame the
303/// stream sends, not one that waits behind the stale ones. Audio, retransmissions and padding
304/// are never discarded this way (audio is never queued, a retransmission is dropped alone,
305/// padding is sent late).
306///
307/// For every discard the pacer emits on its **read** leg (the application-ward direction, the
308/// only one that reaches the NACK responder application-ward of it) an empty RTCP carrier with
309/// [`PacerDiscard`]: the NACK responder removes those packets from its retransmission buffer, so
310/// a NACK for them is answered by nothing (RFC 4588 section 7: the sender "MAY selectively
311/// retransmit only the packets that it deems important"), and the peer connection hands the
312/// discard to the application (`RTCPeerConnectionEvent::OnPacerDiscard`). For a media stream
313/// (not a repair flow) it also emits a Picture Loss Indication (RFC 4585 section 6.3.1) for the
314/// stream, sender SSRC 0, marked [`Attribute::DeliverToApplication`]: the request a receiver
315/// that lost its picture sends, so an application that answers PLI with a key frame
316/// (`RTCMessage::RtcpPacket`, `RTCPeerConnectionEvent::OnKeyFrameRequest`) answers this too, at
317/// the target the frames it writes now are sized for.
318///
319/// libwebrtc does not discard in its pacer: when the expected queue time passes 2 s it pauses
320/// the encoder (target zero to the encoder, `modules/congestion_controller/rtp/control_handler.cc`)
321/// and drains the queue above the target ([`QueueOverflow::Drain`]); its frames are dropped
322/// before they are numbered. Here the application numbers its packets, so a discarded frame
323/// leaves a gap in the stream's sequence numbers that the receiver sees as loss.
324pub struct PacerInterceptor {
325    pacer: LeakyBucket,
326    /// The rate the bucket was set to before the queue time limit raised it, while it is
327    /// raised: the target to come back to (the congestion controller's, or one set through
328    /// [`Self::pacer_mut`]).
329    raised_from: Option<f64>,
330    queue: VecDeque<TaggedPacket>,
331    /// Padding-only packets, released only while `queue` is empty (see the order of service).
332    padding: VecDeque<TaggedPacket>,
333    /// Padding refused because the padding queue was full.
334    padding_discarded: u64,
335    /// The bits waiting in `queue` (padding not counted).
336    queued_bits: f64,
337    queue_limit: usize,
338    queue_time_limit: Option<Duration>,
339    queue_overflow: QueueOverflow,
340    /// The SSRCs of the audio streams: their packets are not queued behind others.
341    audio: HashSet<u32>,
342    /// Whether a packet inside the budget leaves at once when nothing is queued ahead of it.
343    immediate_release: bool,
344    /// The probe cluster being sent, if one is (see [`ProbeRequest`]).
345    probe: Option<ActiveProbe>,
346    /// Packets released over the budget ([`QueueOverflow::Drain`]).
347    forced: u64,
348    /// Media packets dropped for want of room in the target ([`QueueOverflow::Drop`]).
349    dropped: u64,
350    /// Frames of new media discarded whole ([`QueueOverflow::Drop`]).
351    discarded_frames: u64,
352    /// The repair flows (RTX, FEC SSRCs) of the bound streams other than audio: a discard on
353    /// one asks for no key frame.
354    repair_flows: HashSet<u32>,
355    /// The RTP timestamp of the newest frame discarded on each stream: its packets written
356    /// later are discarded too.
357    discarded_frame: HashMap<u32, u32>,
358    /// Whether the application is told to pause (see "Pausing the source").
359    paused: bool,
360    /// When the pause in force, or the last one, began.
361    pause_began: Option<Instant>,
362    /// How many times a pause began.
363    pauses: u64,
364    /// Retransmissions not queued because the same packet's retransmission already waited.
365    duplicate_retransmissions: u64,
366    /// The retransmissions released and dropped since the last [`RetransmissionsLeft`].
367    departed: Vec<(u32, u16)>,
368    retransmissions_dropped: Vec<(u32, u16)>,
369    /// Packets the budget has released, waiting to join the belt.
370    released: VecDeque<TaggedPacket>,
371    /// Inbound packets ready for the next interceptor.
372    read_queue: VecDeque<TaggedPacket>,
373    /// Outbound packets ready for the next interceptor: what passed through, plus
374    /// anything this one generated.
375    write_queue: VecDeque<TaggedPacket>,
376}
377
378impl PacerInterceptor {
379    fn new(pacer: LeakyBucket, queue_limit: usize) -> Self {
380        Self {
381            read_queue: VecDeque::new(),
382            write_queue: VecDeque::new(),
383            released: VecDeque::new(),
384            raised_from: None,
385            pacer,
386            queue: VecDeque::new(),
387            padding: VecDeque::new(),
388            padding_discarded: 0,
389            queued_bits: 0.0,
390            queue_limit: queue_limit.max(1),
391            queue_time_limit: Some(DEFAULT_QUEUE_TIME_LIMIT),
392            queue_overflow: QueueOverflow::default(),
393            audio: HashSet::new(),
394            immediate_release: true,
395            probe: None,
396            forced: 0,
397            dropped: 0,
398            discarded_frames: 0,
399            repair_flows: HashSet::new(),
400            discarded_frame: HashMap::new(),
401            paused: false,
402            pause_began: None,
403            pauses: 0,
404            duplicate_retransmissions: 0,
405            departed: Vec::new(),
406            retransmissions_dropped: Vec::new(),
407        }
408    }
409
410    /// The pacing bucket, for a bandwidth estimator to drive.
411    pub fn pacer(&self) -> &LeakyBucket {
412        &self.pacer
413    }
414
415    /// The pacing bucket, mutably — this is where `set_target_bitrate` is reached.
416    pub fn pacer_mut(&mut self) -> &mut LeakyBucket {
417        &mut self.pacer
418    }
419
420    /// How many packets are waiting to be released, padding included.
421    pub fn queued(&self) -> usize {
422        self.queue.len() + self.padding.len()
423    }
424
425    /// How many padding-only packets were discarded because the padding queue was full.
426    pub fn padding_discarded(&self) -> u64 {
427        self.padding_discarded
428    }
429
430    /// How many packets left over the budget, overdue or to make room in a full queue
431    /// ([`QueueOverflow::Drain`]).
432    pub fn forced(&self) -> u64 {
433        self.forced
434    }
435
436    /// How many media packets were dropped, overdue or to make room in a full queue
437    /// ([`QueueOverflow::Drop`]): the packets of the discarded frames and the retransmissions
438    /// dropped.
439    pub fn dropped(&self) -> u64 {
440        self.dropped
441    }
442
443    /// How many frames of new media were discarded whole ([`QueueOverflow::Drop`], see
444    /// "Discarding media" on [`PacerInterceptor`]).
445    pub fn discarded_frames(&self) -> u64 {
446        self.discarded_frames
447    }
448
449    /// How many times the application was told to pause (see "Pausing the source" on
450    /// [`PacerInterceptor`]).
451    pub fn pauses(&self) -> u64 {
452        self.pauses
453    }
454
455    /// Whether the application is told to pause now.
456    pub fn paused(&self) -> bool {
457        self.paused
458    }
459
460    /// How many retransmissions were not queued because a retransmission of the same packet
461    /// already waited in the queue.
462    pub fn duplicate_retransmissions(&self) -> u64 {
463        self.duplicate_retransmissions
464    }
465
466    /// How long the media queued now takes to leave at the target: queued bits over the
467    /// target (libwebrtc's `ExpectedQueueTime`). Padding is not counted.
468    pub fn expected_queue_time(&self) -> Duration {
469        if self.queued_bits <= 0.0 {
470            return Duration::ZERO;
471        }
472        let target = self.target();
473        if target <= 0.0 {
474            return Duration::MAX;
475        }
476        Duration::try_from_secs_f64(self.queued_bits / target).unwrap_or(Duration::MAX)
477    }
478
479    /// How long the oldest queued media packet has waited at `now`, zero with none queued
480    /// (padding is not counted: the queue time bound is the media's).
481    pub fn queue_time(&self, now: Instant) -> Duration {
482        self.queue.front().map_or(Duration::ZERO, |head| {
483            now.saturating_duration_since(head.now)
484        })
485    }
486
487    /// The rate to pace at now: the target, or more when the queue would otherwise not drain
488    /// before its oldest packet has waited the queue time limit. With `q` bits queued and the
489    /// oldest packet having waited `w`, the rate is max(target, q / (limit - w)); once `w`
490    /// reaches the limit, everything queued may leave.
491    fn pacing_rate(&self, now: Instant) -> f64 {
492        let target = self.target();
493        if self.queue_overflow != QueueOverflow::Drain {
494            return target;
495        }
496        let Some(limit) = self.queue_time_limit else {
497            return target;
498        };
499        if self.queue.is_empty() {
500            return target;
501        }
502        let remaining = limit.saturating_sub(self.queue_time(now)).as_secs_f64();
503        let needed = if remaining > 0.001 {
504            self.queued_bits / remaining
505        } else {
506            // Overdue: everything may leave (`handle_timeout` releases it).
507            1e12
508        };
509        target.max(needed)
510    }
511
512    /// The target rate: what the bucket paces at when the queue is short.
513    fn target(&self) -> f64 {
514        self.raised_from
515            .unwrap_or_else(|| self.pacer.target_bitrate())
516    }
517
518    /// Paces at [`Self::pacing_rate`] from `now`: above the target while the queue needs it,
519    /// back at the target once it does not.
520    fn follow_queue(&mut self, now: Instant) {
521        let target = self.target();
522        let rate = self.pacing_rate(now);
523        if rate > target {
524            self.raised_from = Some(target);
525            if rate != self.pacer.target_bitrate() {
526                self.pacer.set_target_bitrate(rate);
527            }
528        } else if let Some(target) = self.raised_from.take() {
529            self.pacer.set_target_bitrate(target);
530        }
531    }
532
533    /// Whether `packet` is padding only: an RTP packet with the padding bit and no payload.
534    fn is_padding(packet: &TaggedPacket) -> bool {
535        matches!(&packet.message.packet, Packet::Rtp(rtp) if rtp.header.padding && rtp.payload.is_empty())
536    }
537
538    fn is_audio(&self, packet: &TaggedPacket) -> bool {
539        matches!(&packet.message.packet, Packet::Rtp(rtp) if self.audio.contains(&rtp.header.ssrc))
540    }
541
542    /// The size of a packet on the wire, in bits — the unit the budget is kept in.
543    fn bits_of(packet: &TaggedPacket) -> f64 {
544        match &packet.message.packet {
545            Packet::Rtp(rtp) => (rtp.marshal_size() * 8) as f64,
546            Packet::Rtcp(_) => 0.0,
547        }
548    }
549
550    /// The bucket releases are metered through now: the probe cluster's while one is being
551    /// sent, the target rate's otherwise.
552    fn bucket(&self) -> &LeakyBucket {
553        self.probe
554            .as_ref()
555            .map_or(&self.pacer, |probe| &probe.bucket)
556    }
557
558    /// The instant the next packet can be released: the head of the media queue, or of the
559    /// padding while no media waits (padding has no queue time bound to wake for).
560    fn next_release(&self) -> Option<Instant> {
561        let Some(head) = self.queue.front() else {
562            let head = self.padding.front()?;
563            return self.bucket().releasable_at(Self::bits_of(head));
564        };
565        let by_budget = self.bucket().releasable_at(Self::bits_of(head)).map(|at| {
566            // While the rate is raised it moves with every call, and the instant computed at
567            // one rate can come out a hair short of the budget at the next: a microsecond
568            // later it is not, and the deadline advances (webrtc#862).
569            if self.raised_from.is_some() {
570                at + Duration::from_micros(1)
571            } else {
572                at
573            }
574        });
575        // The rate rises as the oldest packet ages: wake by the time it reaches the limit
576        // (never for a packet the bound does not apply to: that deadline would stay in the
577        // past and a driver would spin on it).
578        let by_limit = self
579            .queue_time_limit
580            .filter(|_| self.queue_overflow == QueueOverflow::Drain || self.ages_out(head))
581            .map(|limit| head.now + limit);
582        match (by_budget, by_limit) {
583            (Some(a), Some(b)) => Some(a.min(b)),
584            (a, b) => a.or(b),
585        }
586    }
587
588    /// Whether `bits` may leave now, and if so, spends them.
589    fn try_spend(&mut self, bits: f64) -> bool {
590        match self.probe.as_mut() {
591            Some(probe) => {
592                if !probe.bucket.can_release(bits) {
593                    return false;
594                }
595                probe.bucket.consume(bits);
596                true
597            }
598            None => {
599                if !self.pacer.can_release(bits) {
600                    return false;
601                }
602                self.pacer.consume(bits);
603                true
604            }
605        }
606    }
607
608    /// Brings the budgets up to `now`, and ends a probe cluster that could not be filled.
609    fn refill(&mut self, now: Instant) {
610        self.pacer.refill(now);
611        if let Some(probe) = self.probe.as_mut() {
612            probe.bucket.refill(now);
613            if now.saturating_duration_since(probe.started) > PROBE_CLUSTER_TIMEOUT {
614                self.probe = None;
615            }
616        }
617    }
618
619    /// A packet leaves at `now`: marked as part of the probe cluster while one is being sent.
620    fn release(&mut self, mut packet: TaggedPacket, bits: f64) {
621        if packet.message.has(&Attribute::Retransmission)
622            && !Self::is_padding(&packet)
623            && let Some(key) = self.retransmission_key(&packet)
624        {
625            self.departed.push(key);
626        }
627        if let Some(probe) = self.probe.as_mut() {
628            packet.message.add(Attribute::Custom(Arc::new(ProbePacket {
629                cluster: probe.cluster,
630            })));
631            probe.remaining_bits -= bits;
632            if probe.remaining_bits <= 0.0 {
633                self.probe = None;
634            }
635        }
636        self.released.push_back(packet);
637    }
638
639    /// The packet a retransmission repairs, as (SSRC on the wire, sequence number repaired): on
640    /// an RTX stream the original sequence number ahead of the payload (RFC 4588 section 4),
641    /// otherwise (a retransmission under the media SSRC) its own sequence number.
642    fn retransmission_key(&self, packet: &TaggedPacket) -> Option<(u32, u16)> {
643        let Packet::Rtp(rtp) = &packet.message.packet else {
644            return None;
645        };
646        let ssrc = rtp.header.ssrc;
647        if self.repair_flows.contains(&ssrc) {
648            let osn = rtp.payload.get(..2)?;
649            return Some((ssrc, u16::from_be_bytes([osn[0], osn[1]])));
650        }
651        Some((ssrc, rtp.header.sequence_number))
652    }
653
654    /// Whether a retransmission of the packet `packet` repairs already waits in the queue
655    /// (retransmissions wait at its front).
656    fn retransmission_waits(&self, packet: &TaggedPacket) -> bool {
657        let Some(key) = self.retransmission_key(packet) else {
658            return false;
659        };
660        self.queue
661            .iter()
662            .take_while(|queued| queued.message.has(&Attribute::Retransmission))
663            .any(|queued| self.retransmission_key(queued) == Some(key))
664    }
665
666    /// Records a retransmission dropped from the queue, for [`RetransmissionsLeft`].
667    fn retransmission_dropped(&mut self, packet: &TaggedPacket) {
668        if let Some(key) = self.retransmission_key(packet) {
669            self.retransmissions_dropped.push(key);
670        }
671    }
672
673    /// Whether the pause should begin or end now (see "Pausing the source"); `true` when it
674    /// changed.
675    fn update_pause(&mut self, now: Instant) -> bool {
676        let expected = self.expected_queue_time();
677        let change = match self.queue_time_limit {
678            Some(limit) if !self.paused => expected >= limit.mul_f64(PAUSE_AT),
679            Some(limit) => expected <= limit.mul_f64(RESUME_AT),
680            None => self.paused,
681        };
682        if change {
683            self.paused = !self.paused;
684            if self.paused {
685                self.pauses += 1;
686                self.pause_began = Some(now);
687            }
688        }
689        change
690    }
691
692    /// Whether new media written at `written` is what a source that follows the pause left
693    /// behind: written before the pause in force (or the last one) began, or within
694    /// [`PAUSE_GRACE`] of that. It is never discarded for its age (see "Pausing the source").
695    fn written_before_pause(&self, written: Instant) -> bool {
696        self.pause_began
697            .is_some_and(|began| written <= began + PAUSE_GRACE)
698    }
699
700    /// Whether the queued `packet` is discarded once it has waited the queue time bound
701    /// ([`QueueOverflow::Drop`]): a retransmission, and new media a pausing source would not
702    /// have written.
703    fn ages_out(&self, packet: &TaggedPacket) -> bool {
704        packet.message.has(&Attribute::Retransmission) || !self.written_before_pause(packet.now)
705    }
706
707    /// The target as the application is to read it: zero while paused, with [`PacerPause`]
708    /// carrying the congestion controller's.
709    fn tag_target(&self, message: &mut AttributedPacket) {
710        if !self.paused {
711            return;
712        }
713        let mut target = None;
714        for attribute in &mut message.attributes {
715            if let Attribute::TargetBitrateChanged { bits_per_second } = attribute {
716                target = Some(*bits_per_second);
717                *bits_per_second = 0.0;
718            }
719        }
720        if let Some(target_bits_per_second) = target {
721            message.add(Attribute::Custom(Arc::new(PacerPause {
722                target_bits_per_second,
723            })));
724        }
725    }
726
727    /// After a write or a timeout: a pause that began or ended goes application-ward as the
728    /// target, and the retransmissions that left or were dropped as [`RetransmissionsLeft`].
729    fn tell_application_ward(&mut self, now: Instant) {
730        if self.update_pause(now) {
731            let mut message =
732                AttributedPacket::new(Packet::Rtcp(vec![])).with(Attribute::TargetBitrateChanged {
733                    bits_per_second: self.target(),
734                });
735            self.tag_target(&mut message);
736            self.read_queue.push_back(TaggedPacket {
737                now,
738                transport: TransportContext::default(),
739                message,
740            });
741        }
742        if !self.departed.is_empty() || !self.retransmissions_dropped.is_empty() {
743            let notice = RetransmissionsLeft {
744                departed: std::mem::take(&mut self.departed),
745                dropped: std::mem::take(&mut self.retransmissions_dropped),
746            };
747            self.read_queue.push_back(TaggedPacket {
748                now,
749                transport: TransportContext::default(),
750                message: AttributedPacket::new(Packet::Rtcp(vec![]))
751                    .with(Attribute::Custom(Arc::new(notice))),
752            });
753        }
754    }
755
756    /// Whether `packet` is new media (not a retransmission) of the stream `ssrc`.
757    fn is_new_media_of(packet: &TaggedPacket, ssrc: u32) -> bool {
758        matches!(&packet.message.packet, Packet::Rtp(rtp) if rtp.header.ssrc == ssrc)
759            && !packet.message.has(&Attribute::Retransmission)
760    }
761
762    /// The stream of `packet` when it belongs to the frame discarded last on that stream; a
763    /// packet of a later frame ends that frame's discard.
764    fn continues_discard(&mut self, packet: &TaggedPacket) -> Option<u32> {
765        let Packet::Rtp(rtp) = &packet.message.packet else {
766            return None;
767        };
768        let ssrc = rtp.header.ssrc;
769        let discarded = *self.discarded_frame.get(&ssrc)?;
770        if discarded == rtp.header.timestamp {
771            return Some(ssrc);
772        }
773        self.discarded_frame.remove(&ssrc);
774        None
775    }
776
777    /// Discards the frame of the queued new-media packet at `index` and every other queued
778    /// frame of its stream (see "Discarding media" on [`PacerInterceptor`]).
779    fn discard_stream_of(&mut self, now: Instant, index: usize) {
780        let Some(Packet::Rtp(rtp)) = self.queue.get(index).map(|packet| &packet.message.packet)
781        else {
782            return;
783        };
784        let ssrc = rtp.header.ssrc;
785        let mut discarded = Vec::new();
786        let mut kept = VecDeque::with_capacity(self.queue.len());
787        for packet in self.queue.drain(..) {
788            if Self::is_new_media_of(&packet, ssrc) {
789                discarded.push(packet);
790            } else {
791                kept.push_back(packet);
792            }
793        }
794        self.queue = kept;
795        let bits: f64 = discarded.iter().map(Self::bits_of).sum();
796        self.queued_bits = (self.queued_bits - bits).max(0.0);
797        self.discard(now, ssrc, &discarded);
798    }
799
800    /// Counts the discard of `packets` (new media of the stream `ssrc`, oldest first) and tells
801    /// the chain application-ward: the NACK responder and the application through
802    /// [`PacerDiscard`], and the application a key frame is needed.
803    fn discard(&mut self, now: Instant, ssrc: u32, packets: &[TaggedPacket]) {
804        let mut sequence_numbers = Vec::with_capacity(packets.len());
805        let mut octets = 0usize;
806        let mut frames = 0u32;
807        let mut newest = self.discarded_frame.get(&ssrc).copied();
808        for packet in packets {
809            if let Packet::Rtp(rtp) = &packet.message.packet {
810                sequence_numbers.push(rtp.header.sequence_number);
811                octets += rtp.marshal_size();
812                if newest != Some(rtp.header.timestamp) {
813                    frames += 1;
814                    newest = Some(rtp.header.timestamp);
815                }
816            }
817        }
818        if sequence_numbers.is_empty() {
819            return;
820        }
821        if let Some(timestamp) = newest {
822            self.discarded_frame.insert(ssrc, timestamp);
823        }
824        self.dropped += sequence_numbers.len() as u64;
825        self.discarded_frames += u64::from(frames);
826        let target_bitrate = self.target();
827        self.read_queue.push_back(TaggedPacket {
828            now,
829            transport: TransportContext::default(),
830            message: AttributedPacket::new(Packet::Rtcp(vec![])).with(Attribute::Custom(Arc::new(
831                PacerDiscard {
832                    ssrc,
833                    sequence_numbers,
834                    frames,
835                    octets,
836                    target_bitrate,
837                },
838            ))),
839        });
840        // A new frame lost (not only the rest of one already discarded): the stream needs a
841        // key frame, asked for the way a receiver asks, so the application's PLI handling
842        // answers it.
843        if frames > 0 && !self.repair_flows.contains(&ssrc) {
844            self.read_queue.push_back(TaggedPacket {
845                now,
846                transport: TransportContext::default(),
847                message: AttributedPacket::new(Packet::Rtcp(vec![Box::new(
848                    PictureLossIndication {
849                        sender_ssrc: 0,
850                        media_ssrc: ssrc,
851                    },
852                )]))
853                .with(Attribute::DeliverToApplication),
854            });
855        }
856    }
857}
858
859/// Media the pacer discarded for want of room in the target ([`QueueOverflow::Drop`]): whole
860/// frames of one stream (see "Discarding media" on [`PacerInterceptor`]).
861///
862/// The pacer sends it application-ward, on an empty RTCP carrier on its read leg, at the
863/// instant of the discard. The NACK responder removes the packets named here from its
864/// retransmission buffer (a NACK for them is answered by nothing) and from the original
865/// packets it counts against the target (they never used the link); the peer connection
866/// hands it to the application as `RTCPeerConnectionEvent::OnPacerDiscard`. It means **the
867/// source is above the target**: what the application writes has to come down to the target
868/// it is given (`Attribute::TargetBitrateChanged`, `RTCRtpSender::target_bitrates`). Read with
869/// [`AttributedPacket::custom`](crate::AttributedPacket::custom).
870#[derive(Debug, Clone, PartialEq)]
871pub struct PacerDiscard {
872    /// The stream the packets were of.
873    pub ssrc: u32,
874    /// The sequence numbers of the packets discarded, oldest first.
875    pub sequence_numbers: Vec<u16>,
876    /// How many frames were discarded (0 when these packets are the rest of a frame already
877    /// discarded).
878    pub frames: u32,
879    /// The octets of the packets discarded (RTP header and payload).
880    pub octets: usize,
881    /// The pacer's target at the discard, bits per second.
882    pub target_bitrate: f64,
883}
884
885/// The pause begins when the expected queue time reaches this share of the queue time bound:
886/// half, so a source that stops when told (within a frame or a read of its target) never lets
887/// its packets wait the bound, even when the target falls by half once more meanwhile.
888const PAUSE_AT: f64 = 0.5;
889
890/// The pause ends when the expected queue time is back under this share of the bound (100 ms
891/// of the default 2 s): what then waits is the delay the call carries on with, so it is kept
892/// short; the gap between the two shares keeps one frame from switching it on and off.
893const RESUME_AT: f64 = 0.05;
894
895/// How long after a pause began media still counts as written by a source that follows it:
896/// the time such a source takes to notice (a read of its target, the frame being encoded).
897const PAUSE_GRACE: Duration = Duration::from_millis(250);
898
899/// Rides a target of zero ([`Attribute::TargetBitrateChanged`]) that the pacer hands
900/// application-ward while it tells the source to pause (see "Pausing the source" on
901/// [`PacerInterceptor`]): the congestion controller's target, for what application-ward of the
902/// pacer needs the rate the path carries (the NACK responder's retransmission rate limit). Read
903/// with [`AttributedPacket::custom`](crate::AttributedPacket::custom).
904#[derive(Debug, Clone, Copy, PartialEq)]
905pub struct PacerPause {
906    /// The congestion controller's target, bits per second.
907    pub target_bits_per_second: f64,
908}
909
910/// The retransmissions that left the pacer, or were dropped there, since the last notice: each
911/// as (SSRC on the wire, sequence number of the packet it repairs; the original sequence
912/// number on an RTX stream). The pacer sends it application-ward on an empty RTCP carrier; the
913/// NACK responder treats a packet as on its way while its retransmission waits in the pacer
914/// and counts the resend interval from when it left, as libwebrtc's packet history does
915/// (`modules/rtp_rtcp/source/rtp_packet_history.cc`: a request for a packet "already in pacer
916/// queue" is ignored; the send time is set when it is sent). Read with
917/// [`AttributedPacket::custom`](crate::AttributedPacket::custom).
918#[derive(Debug, Clone, PartialEq, Default)]
919pub struct RetransmissionsLeft {
920    /// Released toward the wire.
921    pub departed: Vec<(u32, u16)>,
922    /// Dropped (waited the queue time bound, or the oldest of a full queue).
923    pub dropped: Vec<(u32, u16)>,
924}
925
926/// How long a probe cluster is held open for packets to fill it. A cluster that takes longer
927/// than this to leave is not a burst any more and measures nothing.
928const PROBE_CLUSTER_TIMEOUT: Duration = Duration::from_millis(250);
929
930/// A probe cluster on its way out.
931struct ActiveProbe {
932    cluster: u32,
933    /// Meters the cluster's packets at the probe rate, one packet at a time.
934    bucket: LeakyBucket,
935    remaining_bits: f64,
936    started: Instant,
937}
938
939impl Protocol<TaggedPacket, TaggedPacket, ()> for PacerInterceptor {
940    type Rout = TaggedPacket;
941    type Wout = TaggedPacket;
942    type Eout = ();
943    type Error = Error;
944    type Time = Instant;
945
946    fn handle_read(&mut self, mut msg: TaggedPacket) -> Result<(), Self::Error> {
947        // Follow the congestion controller's estimate.
948        //
949        // It arrives on the **read** leg because that is the only one it can cross on. The
950        // controller is wire-most, so on the write leg it is the last interceptor to see a packet
951        // and anything it attached would already have gone past here. On the read leg it is the
952        // first, and this is downstream of it — so the feedback packet that produced the estimate
953        // carries it here on its way to the application.
954        //
955        // Observed, not consumed: the packet carries on with the attribute attached, so anything
956        // further along reads the same number.
957        if let Some(Attribute::TargetBitrateChanged { bits_per_second }) =
958            msg.message.get(&Attribute::TargetBitrateChanged {
959                bits_per_second: 0.0,
960            })
961        {
962            match self.raised_from.as_mut() {
963                // Raised to drain the queue: the new target is what it comes back to.
964                Some(target) => *target = *bits_per_second,
965                None => self.pacer.set_target_bitrate(*bits_per_second),
966            }
967            // A new rate changes how long the queue takes to leave: the pause may begin or
968            // end, and the application reads it on this packet.
969            self.update_pause(msg.now);
970            self.tag_target(&mut msg.message);
971        }
972
973        // A probe cluster the congestion controller asks for: the next packets leave at its
974        // rate, on top of the target's budget, and carry its mark. Observed, not consumed:
975        // the NACK responder above reads the same request and fills the cluster.
976        if let Some(request) = msg.message.custom::<ProbeRequest>() {
977            let mut bucket = LeakyBucket::new(request.bits_per_second)
978                .with_burst_bits(crate::pacing::pacer::MIN_BURST_BITS);
979            bucket.refill(msg.now);
980            self.probe = Some(ActiveProbe {
981                cluster: request.cluster,
982                bucket,
983                remaining_bits: request.octets as f64 * 8.0,
984                started: msg.now,
985            });
986        }
987
988        self.read_queue.push_back(msg);
989        Ok(())
990    }
991
992    fn poll_read(&mut self) -> Option<Self::Rout> {
993        self.read_queue.pop_front()
994    }
995
996    fn handle_write(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
997        let now = msg.now;
998        let rtp = matches!(msg.message.packet, Packet::Rtp(_));
999        self.enqueue(msg)?;
1000        if rtp {
1001            self.tell_application_ward(now);
1002        }
1003        Ok(())
1004    }
1005
1006    fn poll_write(&mut self) -> Option<TaggedPacket> {
1007        // Unpaced traffic goes first — RTCP is only useful while it is fresh, and holding it
1008        // behind the budget would be pacing it after all.
1009        self.write_queue
1010            .pop_front()
1011            .or_else(|| self.released.pop_front())
1012    }
1013
1014    fn handle_timeout(&mut self, now: Instant) -> Result<(), Error> {
1015        self.release_due(now);
1016        self.tell_application_ward(now);
1017        Ok(())
1018    }
1019
1020    fn poll_timeout(&mut self) -> Option<Instant> {
1021        self.next_release()
1022    }
1023}
1024
1025impl PacerInterceptor {
1026    /// A packet written: released, queued, or discarded.
1027    fn enqueue(&mut self, msg: TaggedPacket) -> Result<(), Error> {
1028        // No estimate is read here. It was, once — but the congestion controller sits wire-*ward*
1029        // of the pacer, so on the write leg it never sees a packet before this interceptor does and
1030        // the branch had no possible producer. If an application-set target is ever wanted it comes
1031        // back with its own `RTCEvent` variant, and a test.
1032
1033        // RTCP is control traffic and mostly time-sensitive — feedback is only useful while it is
1034        // fresh — so it is not paced.
1035        if matches!(msg.message.packet, Packet::Rtcp(_)) {
1036            self.write_queue.push_back(msg);
1037            return Ok(());
1038        }
1039
1040        // Keeping the budget current at enqueue time is what lets `poll_timeout` compute a
1041        // deadline that is never in the past, even before the first `handle_timeout`.
1042        self.refill(msg.now);
1043        self.follow_queue(msg.now);
1044
1045        // Audio is never queued behind video: its packets are small and few, and a voice that
1046        // waits behind a video backlog is the call breaking up. It leaves at once and is
1047        // charged to the budget, which the packets behind it then wait out.
1048        if self.is_audio(&msg) {
1049            let bits = Self::bits_of(&msg);
1050            if !self.try_spend(bits) {
1051                self.pacer.consume(bits);
1052            }
1053            self.release(msg, bits);
1054            return Ok(());
1055        }
1056
1057        // Padding waits behind every other packet, and nothing waits behind it.
1058        let padding = Self::is_padding(&msg);
1059
1060        // The rest of a frame already discarded is worth nothing either.
1061        let new_media = !padding && !msg.message.has(&Attribute::Retransmission);
1062        if new_media && let Some(ssrc) = self.continues_discard(&msg) {
1063            self.discard(msg.now, ssrc, std::slice::from_ref(&msg));
1064            return Ok(());
1065        }
1066
1067        // Inside the budget and first in line: it leaves now. The budget is the bound on what
1068        // may enter the path at once, so nothing is gained by holding the packet for a timer.
1069        // Queued padding is not in line ahead of media.
1070        if self.immediate_release && self.queue.is_empty() && (!padding || self.padding.is_empty())
1071        {
1072            let bits = Self::bits_of(&msg);
1073            if self.try_spend(bits) {
1074                self.release(msg, bits);
1075                return Ok(());
1076            }
1077        }
1078
1079        if padding {
1080            // Never over the budget and never counted toward the queue time bound (see the
1081            // order of service); at the limit the arrival is discarded.
1082            if self.padding.len() >= self.queue_limit {
1083                self.padding_discarded += 1;
1084            } else {
1085                self.padding.push_back(msg);
1086            }
1087            return Ok(());
1088        }
1089
1090        // A retransmission of a packet whose retransmission already waits adds nothing but a
1091        // second copy (libwebrtc's packet history ignores a request for a packet "already in
1092        // pacer queue", `rtp_packet_history.cc`).
1093        if !new_media && self.retransmission_waits(&msg) {
1094            self.duplicate_retransmissions += 1;
1095            return Ok(());
1096        }
1097
1098        if self.queue.len() >= self.queue_limit {
1099            // Room for the arrival: the oldest goes (the newest is the one still worth
1100            // sending). Discarded by default, a retransmission alone, new media with its
1101            // stream's queued frames; with `Drain` it leaves now, over the budget.
1102            let retransmission = self
1103                .queue
1104                .front()
1105                .is_some_and(|oldest| oldest.message.has(&Attribute::Retransmission));
1106            match self.queue_overflow {
1107                QueueOverflow::Drop if !retransmission => {
1108                    self.discard_stream_of(msg.now, 0);
1109                    if new_media && let Some(ssrc) = self.continues_discard(&msg) {
1110                        self.discard(msg.now, ssrc, std::slice::from_ref(&msg));
1111                        return Ok(());
1112                    }
1113                }
1114                _ => {
1115                    if let Some(mut oldest) = self.queue.pop_front() {
1116                        let bits = Self::bits_of(&oldest);
1117                        self.queued_bits -= bits;
1118                        if self.queue_overflow == QueueOverflow::Drain {
1119                            self.pacer.consume(bits);
1120                            oldest.now = msg.now;
1121                            self.forced += 1;
1122                            self.release(oldest, bits);
1123                        } else {
1124                            self.retransmission_dropped(&oldest);
1125                            self.dropped += 1;
1126                        }
1127                    }
1128                }
1129            }
1130        }
1131
1132        // Held: it leaves later, from `poll_write`, when the budget allows. A retransmission
1133        // goes ahead of the new media waiting, behind the retransmissions before it: a repair
1134        // the NACK responder has already held to the congestion controller's target is worth
1135        // most early, and waiting behind seconds of new video it may outlive its use or be
1136        // dropped as overdue. libwebrtc's pacer orders its queue the same way
1137        // (`modules/pacing/prioritized_packet_queue.cc`, `GetPriorityForType`: "Send
1138        // retransmissions before new media").
1139        let now = msg.now;
1140        self.queued_bits += Self::bits_of(&msg);
1141        if msg.message.has(&Attribute::Retransmission) {
1142            let end = self
1143                .queue
1144                .iter()
1145                .position(|queued| !queued.message.has(&Attribute::Retransmission))
1146                .unwrap_or(self.queue.len());
1147            // Among the retransmissions of one stream the oldest packet goes first, whenever
1148            // it was asked for: a receiver that plays in order waits for the oldest gap, and
1149            // a repair that was itself lost and is made again would otherwise wait behind
1150            // every newer one.
1151            let at = self
1152                .retransmission_key(&msg)
1153                .map_or(end, |(ssrc, repaired)| {
1154                    self.queue
1155                        .iter()
1156                        .take(end)
1157                        .position(|queued| {
1158                            self.retransmission_key(queued)
1159                                .is_some_and(|(other, waiting)| {
1160                                    other == ssrc
1161                                        && waiting != repaired
1162                                        && waiting.wrapping_sub(repaired) < 0x8000
1163                                })
1164                        })
1165                        .unwrap_or(end)
1166                });
1167            self.queue.insert(at, msg);
1168            if at == 0 {
1169                // First in line now: it may leave at once if the budget allows.
1170                self.release_due(now);
1171            }
1172            self.follow_queue(now);
1173            return Ok(());
1174        }
1175        self.queue.push_back(msg);
1176        self.follow_queue(now);
1177        Ok(())
1178    }
1179
1180    /// Releases what the budget allows at `now`, and drops what waited the bound.
1181    fn release_due(&mut self, now: Instant) {
1182        self.refill(now);
1183        self.follow_queue(now);
1184
1185        while let Some(head) = self.queue.front() {
1186            let bits = Self::bits_of(head);
1187            // Past the queue time limit the head is dropped (`Drop`) or leaves whatever the
1188            // budget says (`Drain`).
1189            let overdue = self
1190                .queue_time_limit
1191                .is_some_and(|limit| now.saturating_duration_since(head.now) >= limit)
1192                && (self.queue_overflow == QueueOverflow::Drain || self.ages_out(head));
1193            if overdue {
1194                if self.queue_overflow == QueueOverflow::Drop {
1195                    // A retransmission is dropped alone; new media with every queued frame
1196                    // of its stream (see "Discarding media").
1197                    if head.message.has(&Attribute::Retransmission) {
1198                        if let Some(dropped) = self.queue.pop_front() {
1199                            self.retransmission_dropped(&dropped);
1200                        }
1201                        self.queued_bits = (self.queued_bits - bits).max(0.0);
1202                        self.dropped += 1;
1203                    } else {
1204                        self.discard_stream_of(now, 0);
1205                    }
1206                    continue;
1207                }
1208                self.pacer.consume(bits);
1209                self.forced += 1;
1210            } else if !self.try_spend(bits) {
1211                break;
1212            }
1213
1214            let mut packet = self.queue.pop_front().expect("front just checked");
1215            self.queued_bits = (self.queued_bits - bits).max(0.0);
1216            // Rule 3: the packet departs now. Anything below recording departure — the send
1217            // history congestion control reads — must see the release instant, not the enqueue
1218            // instant, or this queueing delay is charged to the network.
1219            packet.now = now;
1220            // Queued for `poll_write`, which puts it back on the belt so it traverses every
1221            // interceptor ahead — numbering, and the send history reading the release instant just set.
1222            self.release(packet, bits);
1223        }
1224        if self.queue.is_empty() {
1225            self.queued_bits = 0.0;
1226            // No media waits: padding leaves from what the budget has left, never over it.
1227            while let Some(head) = self.padding.front() {
1228                let bits = Self::bits_of(head);
1229                if !self.try_spend(bits) {
1230                    break;
1231                }
1232                let mut packet = self.padding.pop_front().expect("front just checked");
1233                packet.now = now;
1234                self.release(packet, bits);
1235            }
1236        }
1237        self.follow_queue(now);
1238    }
1239}
1240
1241impl Interceptor for PacerInterceptor {
1242    /// Audio streams (and their repair flows) are not queued behind others. The repair flows of
1243    /// the other streams are remembered: a discard on one asks for no key frame.
1244    fn bind_local_stream(&mut self, info: &StreamInfo) {
1245        if info.mime_type.to_ascii_lowercase().starts_with("audio/") {
1246            self.audio.extend(crate::twcc::flow_ssrcs(info));
1247        } else {
1248            self.repair_flows
1249                .extend(info.ssrc_rtx.into_iter().chain(info.ssrc_fec));
1250        }
1251    }
1252
1253    fn unbind_local_stream(&mut self, info: &StreamInfo) {
1254        for ssrc in crate::twcc::flow_ssrcs(info) {
1255            self.audio.remove(&ssrc);
1256            self.discarded_frame.remove(&ssrc);
1257        }
1258        for ssrc in info.ssrc_rtx.into_iter().chain(info.ssrc_fec) {
1259            self.repair_flows.remove(&ssrc);
1260        }
1261    }
1262
1263    fn bind_remote_stream(&mut self, _info: &StreamInfo) {}
1264
1265    fn unbind_remote_stream(&mut self, _info: &StreamInfo) {}
1266}