Skip to main content

rtci_interceptor/cc/
estimator.rs

1//! The seam a congestion control algorithm plugs into.
2
3use crate::Usage;
4use crate::rtpfb::acknowledgement::PacketReport;
5use std::time::Instant;
6
7/// A congestion control algorithm: acknowledged packets in, a target bitrate out.
8///
9/// # Why this is not an `Interceptor`
10///
11/// An estimator does not transform packets, it observes them. Making it an interceptor would give
12/// it a position in the chain ordering it does not need, four bind methods it has no use for, and —
13/// fatally — bury it inside a `Box<dyn Interceptor>` the application cannot reach.
14/// `CongestionControlInterceptor` is the interceptor; this is the algorithm it drives.
15///
16/// # Why the seam is here rather than at the RTCP packet
17///
18/// Upstream's equivalent interface has six methods, of which one returns a writer, one takes raw
19/// RTCP, and one takes a callback. A custom estimator there must parse feedback, own a history of
20/// sent packets, own a pacer, and correctly wrap a writer — four responsibilities that have nothing
21/// to do with the algorithm, reimplemented per algorithm.
22///
23/// Here [`PacketReport`] is already resolved by [`History`](crate::History): departure joined with
24/// arrival, per packet, in send order. What is left is a function from acknowledgements to a number,
25/// which is what a congestion control algorithm actually is.
26///
27/// # Clocks
28///
29/// There are none. Every instant arrives as a parameter, so a test can pin an exact bitrate
30/// trajectory for a given feedback sequence rather than asserting that something eventually
31/// happens.
32pub trait BandwidthEstimator: Send + Sync {
33    /// Packets whose fate the remote has now reported, in send order.
34    ///
35    /// Each report carries the instant it *left* this endpoint — the pacer's release instant, not
36    /// the instant the application enqueued it — the instant it arrived on the receiver's clock,
37    /// its size, and whether it arrived at all. That is everything a delay-based or loss-based
38    /// estimator needs.
39    ///
40    /// May be called with an empty slice; an implementation should treat that as "no news".
41    fn on_reports(&mut self, now: Instant, reports: &[PacketReport]);
42
43    /// The current estimate, in bits per second.
44    ///
45    /// Read after every [`on_reports`](Self::on_reports) and after every
46    /// [`handle_timeout`](Self::handle_timeout); a change is what reaches the pacer.
47    fn target_bitrate(&self) -> f64;
48
49    /// Periodic work, for an estimator that has any. Most do not.
50    fn handle_timeout(&mut self, _now: Instant) {}
51
52    /// When this estimator next wants waking, or `None` if it does not.
53    ///
54    /// `None` when idle, and the instant must advance — a deadline at or before the `now` just
55    /// handed to [`handle_timeout`](Self::handle_timeout) is a busy-loop that wakes the whole chain.
56    fn poll_timeout(&self) -> Option<Instant> {
57        None
58    }
59
60    /// A packet left for the network. With [`on_reports`](Self::on_reports) this is what lets
61    /// an estimator tell "nothing was sent" from "something was sent and nothing came back".
62    fn on_packet_sent(&mut self, _now: Instant, _size: usize) {}
63
64    /// A packet left for the network on a stream that negotiated no per-packet feedback (no
65    /// transport-wide sequence numbers, no RFC 8888): nothing will ever report it, so an
66    /// estimator that counts on feedback for what it sent ([`on_packet_sent`](Self::on_packet_sent))
67    /// must not wait for this packet's.
68    fn on_unreported_packet_sent(&mut self, _now: Instant, _size: usize) {}
69
70    /// A round trip time measured from feedback: the instant a packet left to the instant the
71    /// feedback naming it was read, less nothing, so it includes the receiver's reporting delay.
72    fn on_round_trip_time(&mut self, _now: Instant, _round_trip_time: std::time::Duration) {}
73
74    /// Limits from outside the algorithm, in bits per second: what was negotiated (`b=AS`,
75    /// `b=TIAS`), what the receiver asked for (TMMBR, REMB), what the circuit breaker allows.
76    /// The interceptor combines them and hands over the tightest; `None` lifts the limit. An
77    /// estimator that honours them keeps its target at or below `max` whatever it measures.
78    fn set_external_bounds(&mut self, _min: Option<f64>, _max: Option<f64>) {}
79
80    /// The floor the target never goes under, in bits per second, when the estimator has one.
81    /// It rides with the target as [`MinimumTarget`](crate::MinimumTarget), so the NACK
82    /// responder knows where the original media cannot be lowered for retransmissions
83    /// (RFC 4588 section 7).
84    fn min_bitrate(&self) -> Option<f64> {
85        None
86    }
87
88    /// The ceiling of the estimate, when the estimator has one: probing asks for nothing
89    /// above it (a cluster above what the estimate can ever be measures nothing of use).
90    fn max_bitrate(&self) -> Option<f64> {
91        None
92    }
93
94    /// The estimator's reading of the path at the last feedback: over-used (more is sent than
95    /// it carries: a growing queue, or loss out of a full one), under-used (the queue is
96    /// draining) or normal. The probe controller reads it
97    /// ([`ProbeController::set_usage`](crate::ProbeController::set_usage)). `Normal` for an
98    /// estimator that has no such state.
99    fn usage(&self) -> Usage {
100        Usage::Normal
101    }
102
103    /// The fraction lost a receiver report gave for a stream this endpoint sends, handed over
104    /// only while the receiver sends no per-packet feedback (no TWCC, no RFC 8888): the
105    /// loss-based half of an estimator can still run on it
106    /// (draft-ietf-rmcat-gcc-02 section 7).
107    fn on_receiver_report(&mut self, _now: Instant, _fraction_lost: f64) {}
108
109    /// The network path changed (a new selected candidate pair, a new interface): what was
110    /// learnt about the old path says nothing about this one (RFC 8836 section 2, 1d).
111    fn on_path_change(&mut self, _now: Instant) {}
112
113    /// Of `packets` RTP packets the receiver counted since its last ECN report, `marked`
114    /// arrived ECN-CE (RFC 6679 section 5: the cumulative counters of its RTCP ECN Feedback
115    /// packets and XR ECN Summary Reports, for a stream whose per-packet feedback is not RFC
116    /// 8888, which carries the marks itself). Section 7.3.3: "The default reaction on the
117    /// reception of these ECN-CE-marked packets MUST be to provide the congestion control
118    /// algorithm with a congestion notification that triggers the algorithm to react as if
119    /// packet loss had occurred."
120    fn on_congestion_marks(&mut self, _now: Instant, _marked: u64, _packets: u64) {}
121
122    /// A probe cluster showed the path carries `bits_per_second`
123    /// ([`probe_estimate`](crate::probe_estimate)). Called only when bandwidth probing is on
124    /// ([`CongestionControlBuilder::with_bandwidth_probing`](crate::CongestionControlBuilder::with_bandwidth_probing)).
125    /// An estimator that ignores it loses nothing but the faster start.
126    fn on_probe_result(&mut self, _now: Instant, _bits_per_second: f64) {}
127
128    /// The DSCP each sent stream's packets are marked with, by SSRC (RFC 8837 Table 1; the
129    /// peer connection's [`FlowCodepoints`]), replacing what was said before. RFC 8836 section
130    /// 2, requirement 9: flows "may have different Differentiated Services Code Point (DSCP)
131    /// markings ... A particular bottleneck ... may or may not honor DSCP markings. The
132    /// algorithm SHOULD attempt to leverage DSCP markings when they're available." An estimator
133    /// that keeps one delay signal for every flow ignores it.
134    fn on_flow_codepoints(&mut self, _codepoints: &[(u32, u8)]) {}
135
136    /// Whatever the algorithm wants to expose. Never load-bearing.
137    fn stats(&self) -> EstimatorStats {
138        EstimatorStats::default()
139    }
140}
141
142/// The DSCP each stream the connection sends is marked with (RFC 8837 Table 1: by the flow's
143/// type and the encoding's `networkPriority` / `priority`; RTX and FEC streams with their
144/// encoding's codepoint; 0 for a flow the DSCP fallback turned back, RFC 8835 section 4.2), as
145/// (SSRC, DSCP). The congestion control interceptor hands it to its estimator
146/// ([`BandwidthEstimator::on_flow_codepoints`]); a stream not named counts as DSCP 0.
147///
148/// The peer connection writes it into the chain, as an [`Attribute::Custom`](crate::Attribute::Custom)
149/// on an empty RTCP packet ([`FlowCodepoints::into_packet`]), each time a description is
150/// applied, after `setParameters`, and when the DSCP fallback turns a flow back. Read with
151/// [`AttributedPacket::custom`](crate::AttributedPacket::custom).
152#[derive(Debug, Clone, PartialEq, Eq, Default)]
153#[non_exhaustive]
154pub struct FlowCodepoints {
155    /// (SSRC, DSCP).
156    pub codepoints: Vec<(u32, u8)>,
157}
158
159impl FlowCodepoints {
160    /// The codepoints `codepoints`, as (SSRC, DSCP).
161    pub fn new(codepoints: Vec<(u32, u8)>) -> Self {
162        Self { codepoints }
163    }
164
165    /// The packet that carries this into the chain when written at `now`.
166    pub fn into_packet(self, now: Instant) -> crate::TaggedPacket {
167        crate::TaggedPacket {
168            now,
169            transport: shared::TransportContext::default(),
170            message: crate::AttributedPacket::new(crate::Packet::Rtcp(vec![]))
171                .with(crate::Attribute::Custom(std::sync::Arc::new(self))),
172        }
173    }
174}
175
176/// What an estimator is willing to say about itself.
177///
178/// Deliberately a struct rather than upstream's `map[string]any`: a stringly-typed bag cannot be
179/// read without knowing what the implementation happened to put in it. Fields are optional because
180/// an estimator that does not compute one should say so rather than report a zero that reads like a
181/// measurement.
182#[derive(Debug, Clone, Copy, Default, PartialEq)]
183#[non_exhaustive]
184pub struct EstimatorStats {
185    /// The delay-based half of the estimate, in bits per second.
186    pub delay_based_bitrate: Option<f64>,
187    /// The loss-based half of the estimate, in bits per second.
188    pub loss_based_bitrate: Option<f64>,
189    /// Fraction of packets the remote reported lost, over whatever window the estimator uses.
190    pub packet_loss: Option<f64>,
191    /// Round trip time implied by the most recent feedback.
192    pub round_trip_time: Option<std::time::Duration>,
193}
194
195/// An estimator that always says the same number.
196///
197/// Not a placeholder. It is the proof that [`BandwidthEstimator`] is usable with two methods, and
198/// it is what the interceptor's own tests drive so that the interceptor's behaviour — recording
199/// departures, resolving feedback, attaching the attribute — is separable from any algorithm's.
200///
201/// It is also a legitimate configuration: a fixed rate with a pacer in front of it is what an
202/// application wants when the path is known and it would rather not have an algorithm second-guess
203/// it.
204#[derive(Debug, Clone, Copy)]
205pub struct ConstantBitrate {
206    bits_per_second: f64,
207}
208
209impl ConstantBitrate {
210    /// An estimator fixed at `bits_per_second`.
211    pub fn new(bits_per_second: f64) -> Self {
212        Self { bits_per_second }
213    }
214}
215
216impl BandwidthEstimator for ConstantBitrate {
217    /// Nothing to learn from: the answer does not depend on the question.
218    fn on_reports(&mut self, _now: Instant, _reports: &[PacketReport]) {}
219
220    fn target_bitrate(&self) -> f64 {
221        self.bits_per_second
222    }
223}
224
225#[cfg(test)]
226mod tests {
227    use super::*;
228    use rtcp::transport_feedbacks::cc_feedback_report::Ecn;
229    use std::time::Duration;
230
231    fn report(id: u64, arrived: bool, departure: Instant) -> PacketReport {
232        PacketReport {
233            ssrc: 1,
234            id,
235            rtp_sequence_number: id as u16,
236            is_twcc: true,
237            twcc_sequence_number: id as u16,
238            size: 1200,
239            arrived,
240            departure,
241            arrival: arrived.then(|| Duration::from_millis(10)),
242            ecn: Ecn::default(),
243        }
244    }
245
246    /// The seam is two methods. If this ever needs a third to compile, the defaults have stopped
247    /// carrying their weight and the trait has grown.
248    #[test]
249    fn an_estimator_needs_only_two_methods() {
250        struct Minimal(f64);
251        impl BandwidthEstimator for Minimal {
252            fn on_reports(&mut self, _now: Instant, reports: &[PacketReport]) {
253                // Something an algorithm plausibly does, so this is not vacuously minimal.
254                let arrived = reports.iter().filter(|report| report.arrived).count();
255                self.0 = 100_000.0 * arrived as f64;
256            }
257            fn target_bitrate(&self) -> f64 {
258                self.0
259            }
260        }
261
262        let epoch = Instant::now();
263        let mut estimator = Minimal(0.0);
264        estimator.on_reports(epoch, &[report(1, true, epoch), report(2, false, epoch)]);
265
266        assert_eq!(100_000.0, estimator.target_bitrate());
267        assert_eq!(None, estimator.poll_timeout(), "the default is idle");
268        assert_eq!(EstimatorStats::default(), estimator.stats());
269        estimator.handle_timeout(epoch + Duration::from_secs(1));
270    }
271
272    #[test]
273    fn a_constant_estimator_ignores_what_it_is_told() {
274        let epoch = Instant::now();
275        let mut estimator = ConstantBitrate::new(750_000.0);
276
277        assert_eq!(750_000.0, estimator.target_bitrate());
278        estimator.on_reports(epoch, &[report(1, false, epoch)]);
279        estimator.handle_timeout(epoch + Duration::from_secs(10));
280        assert_eq!(
281            750_000.0,
282            estimator.target_bitrate(),
283            "loss and time must not move a rate the application fixed"
284        );
285    }
286
287    /// `Send + Sync` is a supertrait because the chain is, and a `Box<dyn BandwidthEstimator>`
288    /// has to be storable in one.
289    #[test]
290    fn an_estimator_is_send_and_sync() {
291        fn assert_send_sync<T: Send + Sync>() {}
292        assert_send_sync::<ConstantBitrate>();
293        assert_send_sync::<Box<dyn BandwidthEstimator>>();
294    }
295}