Skip to main content

PacerInterceptor

Struct PacerInterceptor 

Source
pub struct PacerInterceptor { /* private fields */ }
Expand description

Releases queued packets at a target rate rather than as fast as they arrive.

§Where this belongs in the chain

Close to the wire, with every generator on the application side of it. Everything after it on the write path observes the release instant, so a send history goes there and records what actually left; placed the other way round it would record the enqueue instant and charge this queueing delay to the network.

Retransmissions, FEC repair packets and generated RTCP are all produced further out and reach the pacer on the belt, so they are metered along with everything else. Under the nested chain they bypassed it entirely.

§Differences from upstream

  • No ticker and no goroutine. Upstream runs a loop on a 5 ms time.Ticker; here the budget is a pure function of the instants handed in, so a release schedule is reproducible rather than merely eventually-correct.
  • Idle means idle. poll_timeout returns None with nothing queued, so an idle connection does not wake the whole chain at the pacing interval.
  • The deadline is when the head can afford to go, not now + interval, so it always advances — a deadline at or before the now just handed to handle_timeout is the webrtc#862 busy-loop.

§Order of service

  1. Audio (the packets of a stream bound with an audio/ codec) leaves the moment it is written, charged to the budget, which the packets behind it then wait out. A voice that waits behind a video backlog is the call breaking up.
  2. Audio retransmissions leave the same way: an audio stream’s repair flows (its RTX and FEC SSRCs, from Interceptor::bind_local_stream) count as audio, so an audio retransmission never waits behind video either.
  3. Video retransmissions (Attribute::Retransmission on any other stream) wait in the media queue ahead of all new media (libwebrtc’s prioritized_packet_queue.cc: “Send retransmissions before new media”), a stream’s oldest packet first (by the sequence number repaired, whenever each was written: a receiver that plays in order waits for its oldest gap). One whose packet already has a retransmission waiting is not queued again (PacerInterceptor::duplicate_retransmissions), and each that leaves or is dropped is reported application-ward (RetransmissionsLeft), so the NACK responder does not make another while one waits.
  4. Video and FEC (every other RTP packet that is not padding) wait behind them, in the order written. The queue time bound (2 s by default, PacerBuilder::with_queue_time_limit) and the queue limit are this queue’s (3 and 4): by default (QueueOverflow::Drop) what has waited the bound, or the oldest packet when the queue is full, is discarded, so nothing leaves above the target (a retransmission one packet at a time, new media whole frames at a time: see “Discarding media” below); QueueOverflow::Drain raises the pacing rate above the target instead (libwebrtc’s MaybeUpdateMediaRateDueToLongQueue) and releases those packets over the budget.
  5. Padding (padding-only packets, RFC 3550 section 5.1: the padding bit and no payload, which the NACK responder fills a probe cluster with) waits in a queue of its own and leaves only when no media waits. A probe cluster is written as a burst of padding the moment it is asked for; queued in line with the media it would hold every packet the application writes during the cluster behind all of it (140 to 180 ms for a 6000-octet cluster at 200 kbit/s in early_media_rtc2rtc). Media written during a cluster leaves first, at the cluster’s rate and with its mark, so it fills the cluster in place of padding, as in libwebrtc’s pacer (padding has the lowest priority of its packet queue).

Padding is outside the queue time bound: it never counts toward raising the pacing rate (with QueueOverflow::Drain), is never dropped as overdue nor released over the budget, and so never goes ahead of media or past the rate the congestion controller set.

A cluster’s padding belongs to the cluster. The pacer tells the responder how much padding a cluster needs beyond the media already queued (ProbeFill), so a cluster asked while a backlog waits (the pause) is made of that backlog and no padding is written for it. Padding written for a cluster that could not leave in it (media written meanwhile took its place, or the cluster timed out) is discarded when the cluster ends, counted by PacerInterceptor::padding_discarded: outside its cluster it measures nothing, and sent later it is worse than nothing. Each padding packet holds the sequence number of the RTX stream it was given when it was made; kept until budget was spare (seconds, while media waited) it left far behind the stream’s newest number, where a receiver’s replay protection (RFC 3711 section 3.3.2) and its feedback window no longer take it, inside whatever cluster was being sent then: that cluster’s packets were never all reported and the probe gave no result (every cluster after a capacity drop in tests/capacity_cap_video_rtc2rtc.rs, 191 stale padding packets queued, and an estimate that stayed at its floor for want of a probe result). Discarding leaves a hole in the RTX stream’s sequence numbers, which the receiver’s reports count as lost (RFC 3550 appendix A.3); the sender’s own readers of those reports take the numbers that never left out of the count (NeverSent, in the circuit breaker and the receiver-report fallback of the congestion controller), as for media the pacer discards.

Padding written while no cluster is being sent (an application’s own) keeps its place until budget is spare, however long that takes: it is sent late, not dropped. A padding queue that reaches the queue limit (4096 packets) discards the padding that arrives.

§Pausing the source

When the media queued would take half the queue time bound or more to leave at the target (PacerInterceptor::expected_queue_time; 1 s of the default 2 s), the pacer tells the application to stop producing: every Attribute::TargetBitrateChanged it passes application-ward carries zero (so RTCRtpSender::target_bitrates and the stats read zero), with PacerPause carrying the congestion controller’s target for the interceptors that need the path’s rate, and it announces the change at once on a carrier of its own. When the queue is back under a twentieth of the bound (100 ms), it announces the real target again. libwebrtc does the same: its control handler gives the encoder a target of zero while the pacer’s expected queue time exceeds 2 s (modules/congestion_controller/rtp/control_handler.cc, pacing_controller.h: “the packet producers should wait (eg drop frames rather than encoding them)”). Pausing at half the bound, not at the bound, leaves a source that stops when told the time to notice (a frame interval, a read of its target) and room for the target to fall once more.

What a source that follows the pause wrote is never discarded for its age: the media written before the pause began (and within 250 ms of it, the time to notice) stays queued until it leaves, however long that takes. At a sudden drop of the path’s capacity that can be seconds: the target may fall to a tenth of what the queued media was written for, and the retransmissions of what the path lost at the drop leave ahead of it (order of service 3), which is also the order a receiver needs them in. Nothing new joins the queue meanwhile, so it is bounded by what was there when the pause began; discarding it would leave a gap in the stream that costs the receiver more than the wait (a receiver that waits for missing packets by count, as rtci-media’s SampleBuilder does, sat 9 s on such a gap in tests/capacity_cap_video_rtc2rtc.rs). The queue time bound and the discard below are for media written into a pause: a source that does not follow it.

What that costs, and why it is not the default at a collapse. This paragraph and the one before describe a queue kept through a sudden drop: Backlog::Keep, and by default a long queue whose target did not collapse. By default a collapse flushes the queue instead (next section; docs/capacity-collapse.md). After a sudden drop the picture a receiver shows can be seconds old while those retransmissions leave: in that test, which runs Backlog::Keep (2.5 Mbit/s into a path that drops to 300 kbit/s) the receiver never went 2 s without a usable frame (0.75 to 1.13 s), but the oldest picture it showed was 4.14 to 6.58 s old, against 2.90 to 3.20 s in a chain without a pacer. The 55 to 62 video packets the path dropped are repaired inside an estimate of 100 to 250 kbit/s of which the audio takes 76, under every retransmission rule (59 to 80 retransmissions; a request for a packet whose retransmission the feedback reports received is not answered, see the NACK responder). Dropping the repairs and asking for a key frame instead is worse for a receiver that plays in order and waits for a gap by packet count (measured: frozen for 8 s, as it holds the gap for its whole packet window): such a receiver is what Backlog::Keep is for.

A target of zero means: produce nothing until the next target. An encoder skips (does not encode) the frames captured meanwhile; it does not need a key frame to resume, because nothing it encoded was lost: the next frame it encodes refers to the last one it sent, which is still queued here and reaches the receiver. libwebrtc resumes the same way: it encodes the last frame captured during the pause, or asks the capturer for a fresh one (video_stream_encoder.cc, OnBitrateUpdated: “A pending stored frame can be processed”, else RequestRefreshFrame), and forces no key frame. Audio is not queued here and can carry on; the target is the transport’s. Media the application writes anyway is queued and, past the bound, discarded as below, with a key-frame request: that, not the resume, is when a key frame is needed.

§A capacity collapse

By default (Backlog::Flush) the pause above is for a queue that is long at a steady target: a key frame larger than a second of the target, a source that is slow to follow. When the queue is long because the target collapsed (a pause would begin or is in force, and the target is now half or less of the highest target in force since the oldest queued new media was written or in the last queue time bound, two seconds by default, whichever reaches further back), the pacer does not pause, or ends the pause. The queue may hold new media, retransmissions or both: the repairs asked for a second after a drop, behind a deep queue on the path, are of media written for the old rate as well. It flushes: every queued packet is discarded (new media and FEC through PacerDiscard, whole frames, as below; queued retransmissions through RetransmissionsLeft), a PacerFlush tells the NACK responder to forget everything sent before on the video streams, so that later NACKs for it are answered by nothing, and the application is asked for a key frame of every video stream (the Picture Loss Indication described below). The source is not paused: the next frame it writes, at the target it now reads, is the key frame. Audio is never queued and is not touched; padding stays.

What was queued was sized for a rate the path no longer carries: 0.4 s of 2.5 Mbit/s video and the retransmissions of what the path dropped take 8 s to leave at 100 to 250 kbit/s (tests/capacity_instrument.rs: the picture on the screen was 9 s old in the median), against a key frame of a few packets. RFC 8834 section 6.1 asks a sender to consider “the likelihood of [retransmissions] arriving in time to be useful”; RFC 8836 section 2 gives interactive media “no more delay than hundreds of milliseconds end-to-end”; RFC 8298 section 3 lets a sender whose queues grow rapidly discard encoded frames “to ensure that the RTP queues are drained quickly”. A decoder refresh point “completely resets the decoder” (RFC 5104 section 2.2): nothing sent before it is needed after it.

A flush is not repeated for what was written after it: no target from before a flush counts again, and the key frame the application writes in answer was written at the fallen target, so a queue it fills is a pause, not a collapse, and is delivered. The target has to halve again, from what it was at the flush, for another one: at most log2(highest / lowest target) flushes in a row, four from 2.5 Mbit/s to a 100 kbit/s floor. The receiver sees a gap in the sequence numbers (the application numbered the discarded packets) and its NACKs for it go unanswered; one that waits for missing packets has to bound that wait in time or resume at the key frame (docs/capacity-collapse.md). Backlog::Keep restores the pause for every long queue.

§Discarding media

With QueueOverflow::Drop, new media the target has no room for is discarded whole frames at a time. A frame is the packets of one stream (SSRC) with one RTP timestamp (RFC 3550 section 5.1: the packets of one frame share it; the marker bit ends it). A frame with a packet missing is worth nothing to a decoder, and so is every later frame that refers to it, up to the next key frame; a frame that waited two seconds is stale anyway. So when the oldest new-media packet has waited the bound (or is the oldest of a full queue), the pacer discards every queued packet of its stream that is not a retransmission, oldest frame first, and the packets of the newest discarded frame the application writes after that. Nothing marks a key frame on this path (the application writes RTP packets, and only the codec’s payload says which frame is a key frame), so no queued frame of the stream is kept as one: the key frame the application writes in answer to the request below is the next frame the stream sends, not one that waits behind the stale ones. Audio, retransmissions and padding are never discarded this way (audio is never queued, a retransmission is dropped alone, padding is sent late).

For every discard the pacer emits on its read leg (the application-ward direction, the only one that reaches the NACK responder application-ward of it) an empty RTCP carrier with PacerDiscard: the NACK responder removes those packets from its retransmission buffer, so a NACK for them is answered by nothing (RFC 4588 section 7: the sender “MAY selectively retransmit only the packets that it deems important”), and the peer connection hands the discard to the application (RTCPeerConnectionEvent::OnPacerDiscard). For a media stream (not a repair flow) it also emits a Picture Loss Indication (RFC 4585 section 6.3.1) for the stream, sender SSRC 0, marked Attribute::DeliverToApplication: the request a receiver that lost its picture sends, so an application that answers PLI with a key frame (RTCMessage::RtcpPacket, RTCPeerConnectionEvent::OnKeyFrameRequest) answers this too, at the target the frames it writes now are sized for.

libwebrtc does not discard in its pacer: when the expected queue time passes 2 s it pauses the encoder (target zero to the encoder, modules/congestion_controller/rtp/control_handler.cc) and drains the queue above the target (QueueOverflow::Drain); its frames are dropped before they are numbered. Here the application numbers its packets, so a discarded frame leaves a gap in the stream’s sequence numbers that the receiver sees as loss.

Implementations§

Source§

impl PacerInterceptor

Source

pub fn pacer(&self) -> &LeakyBucket

The pacing bucket, for a bandwidth estimator to drive.

Source

pub fn pacer_mut(&mut self) -> &mut LeakyBucket

The pacing bucket, mutably — this is where set_target_bitrate is reached.

Source

pub fn queued(&self) -> usize

How many packets are waiting to be released, padding included.

Source

pub fn padding_discarded(&self) -> u64

How many padding-only packets were discarded: left over when the probe cluster they were written for ended (see “A cluster’s padding belongs to the cluster” on PacerInterceptor), or refused because the padding queue was full.

Source

pub fn forced(&self) -> u64

How many packets left over the budget, overdue or to make room in a full queue (QueueOverflow::Drain).

Source

pub fn dropped(&self) -> u64

How many media packets were dropped, overdue or to make room in a full queue (QueueOverflow::Drop): the packets of the discarded frames and the retransmissions dropped.

Source

pub fn discarded_frames(&self) -> u64

How many frames of new media were discarded whole (QueueOverflow::Drop, see “Discarding media” on PacerInterceptor).

Source

pub fn pauses(&self) -> u64

How many times the application was told to pause (see “Pausing the source” on PacerInterceptor).

Source

pub fn flushes(&self) -> u64

How many times the queue was flushed at a collapse of the target (see “A capacity collapse” on PacerInterceptor).

Source

pub fn paused(&self) -> bool

Whether the application is told to pause now.

Source

pub fn duplicate_retransmissions(&self) -> u64

How many retransmissions were not queued because a retransmission of the same packet already waited in the queue.

Source

pub fn expected_queue_time(&self) -> Duration

How long the media queued now takes to leave at the target: queued bits over the target (libwebrtc’s ExpectedQueueTime). Padding is not counted.

Source

pub fn queue_time(&self, now: Instant) -> Duration

How long the oldest queued media packet has waited at now, zero with none queued (padding is not counted: the queue time bound is the media’s).

Trait Implementations§

Source§

impl Interceptor for PacerInterceptor

Source§

fn bind_local_stream(&mut self, info: &StreamInfo)

Audio streams (and their repair flows) are not queued behind others. The repair flows of the other streams are remembered: a discard on one asks for no key frame.

Source§

fn unbind_local_stream(&mut self, info: &StreamInfo)

unbind_local_stream is called when the Stream is removed. It can be used to clean up any data related to that track.
Source§

fn bind_remote_stream(&mut self, _info: &StreamInfo)

bind_remote_stream lets you modify any incoming RTP packets. It is called once for per RemoteStream. The returned method will be called once per rtp packet.
Source§

fn unbind_remote_stream(&mut self, _info: &StreamInfo)

unbind_remote_stream is called when the Stream is removed. It can be used to clean up any data related to that track.
Source§

fn with<O, F>(self, f: F) -> O
where Self: Sized, F: FnOnce(Self) -> O, O: Interceptor,

Wraps this interceptor in an outer one built by f, for nested (#[next]-field) interceptors written with the Interceptor derive. The result is an ordinary interceptor and can be placed in a Registry slot. Read more
Source§

fn move_local_stream_out(&mut self, info: &StreamInfo)

The local stream info moves to another RTP session (its m= section moved to another transport, as a bundling answer does): it leaves this one without ending, so nothing says it left (no RTCP BYE, RFC 3550 section 6.6). Unbinds it by default.
Source§

impl Protocol<TransportMessage<AttributedPacket>, TransportMessage<AttributedPacket>, ()> for PacerInterceptor

Source§

type Rout = TransportMessage<AttributedPacket>

Output read message type Read more
Source§

type Wout = TransportMessage<AttributedPacket>

Output write message type Read more
Source§

type Eout = ()

Output event type Read more
Source§

type Error = Error

Error type for protocol operations
Source§

type Time = Instant

Time/Instant type for timeout handling Read more
Source§

fn handle_read(&mut self, msg: TaggedPacket) -> Result<(), Self::Error>

Handle an incoming read message. Read more
Source§

fn poll_read(&mut self) -> Option<Self::Rout>

Poll for a processed read message. Read more
Source§

fn handle_write(&mut self, msg: TaggedPacket) -> Result<(), Self::Error>

Handle an outgoing write message. Read more
Source§

fn poll_write(&mut self) -> Option<TaggedPacket>

Poll for a processed write message. Read more
Source§

fn handle_timeout(&mut self, now: Instant) -> Result<(), Error>

Handle a timeout event. Read more
Source§

fn poll_timeout(&mut self) -> Option<Instant>

Poll for the next timeout deadline. Read more
Source§

fn handle_event(&mut self, _evt: Ein) -> Result<(), Self::Error>

Handle a custom event. Read more
Source§

fn poll_event(&mut self) -> Option<Self::Eout>

Poll for a generated event. Read more
Source§

fn close(&mut self) -> Result<(), Self::Error>

Close the protocol. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.