Skip to main content

rtci_interceptor/cc/
estimator.rs

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