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. Padding older than the bound is sent late, not dropped. Each padding packet already holds the next sequence number of its RTX stream (the responder numbers it when it fills the cluster), so dropping it would leave a hole in that stream which a receiver counts as lost (RFC 3550 appendix A.3, expected minus received) and the RTCP reports carry back as loss nobody had on the path. Sent late it costs nothing: it leaves only from budget no media wants. A padding queue that reaches the queue limit (4096 packets, far beyond what probing writes while media waits) discards the padding that arrives, counted by PacerInterceptor::padding_discarded: the one place padding can leave a hole, preferred to letting it go over the budget.

§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.

Known limit. After a sudden drop the picture a receiver shows can be seconds old while those retransmissions leave: in that test (2.5 Mbit/s into a path that drops to 300 kbit/s) the receiver never went 2 s without a usable frame (1.38 to 1.90 s), but the oldest picture it showed was 5.95 to 8.56 s old, against 2.26 to 3.21 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, and 35 to 41 of the 90 to 103 retransmissions repeat a packet whose first repair was still in flight when the receiver asked again (they arrive after it). Dropping the repairs and asking for a key frame instead is worse for a receiver that plays in order (measured: frozen for 8 s, as it holds the gap for its whole packet window); what is planned is no repeat repair of a packet whose first repair transport-wide feedback reports received.

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.

§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 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 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.