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