Skip to main content

srt_runtime/
livecc.rs

1//! SRT Live Congestion Control — packet pacing (`draft-sharabayko-srt-01` §5.1,
2//! curated at `private/specs-verified/rules/srt-livecc.md`).
3//!
4//! A sans-IO, `no_std` sender-side pacing controller that computes the minimum
5//! inter-packet send period (`PKT_SND_PERIOD`) from a configured maximum
6//! bandwidth (`MAX_BW`) and a running EWMA of the average payload size
7//! (`AvgPayloadSize`).
8//!
9//! ## Usage
10//!
11//! ```rust
12//! use srt_runtime::livecc::{LiveCC, MaxBwConfig};
13//! use core::time::Duration;
14//!
15//! let mut cc = LiveCC::new(Default::default());
16//! // Application sends a data packet with 1316 bytes of payload:
17//! cc.on_data_packet(1316);
18//! // On ACK reception, recompute the send period:
19//! let period = cc.on_ack_received();
20//! assert!(period > Duration::ZERO);
21//! ```
22//!
23//! ## Spec grounding
24//!
25//! - `private/specs-verified/rules/srt-livecc.md` §5.1.1 — MAX_BW configuration modes (§5.1.1,
26//!   lines L3116-L3202).
27//! - `private/specs-verified/rules/srt-livecc.md` §5.1.2 — LiveCC algorithm (lines L3203-L3238):
28//!   - EWMA formula: L3219 (`AvgPayloadSize = 7/8 * AvgPayloadSize + 1/8 * PacketPayloadSize`)
29//!   - Initial value cap: L3222-3223 (max 1456 bytes).
30//!   - PktSize formula: L3227-3229 (`PktSize = AvgPayloadSize + SRT header size`).
31//!   - PKT_SND_PERIOD formula: L3234 (`PktSize * 1000000 / MAX_BW`).
32//! - `private/specs-verified/rules/srt-livecc.md` — SYN = 0.01 s (imported from §5.2.1,
33//!   L3421-3423, restated at L197-L199 of the curated doc).
34
35use core::time::Duration;
36
37/// The fixed SRT header size (16 bytes), defined in `draft-sharabayko-srt-01` §3,
38/// Figure 2. Used by the PktSize formula (`private/specs-verified/rules/srt-livecc.md` §5.1.2
39/// step 2, L3227-3229).
40const SRT_HEADER_SIZE: u64 = 16;
41
42/// Initial cap for `AvgPayloadSize`: the maximum allowed packet payload size,
43/// which cannot be larger than 1456 bytes (`private/specs-verified/rules/srt-livecc.md` §5.1.2,
44/// L3222-3223).
45const INITIAL_AVG_PAYLOAD_SIZE_CAP: u64 = 1456;
46
47/// Default MAX_BW for MAXBW_SET mode — 1 Gbps (`private/specs-verified/rules/srt-livecc.md`
48/// §5.1.1, L3122-3123). Stored in bytes per second (L3156-3157): 1 Gbps =
49/// 125_000_000 bytes/s.
50const DEFAULT_MAX_BW_BYTES_PER_SEC: u64 = 125_000_000;
51
52/// Maximum bandwidth configuration mode (`private/specs-verified/rules/srt-livecc.md` §5.1.1,
53/// lines L3116-L3202).
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55#[non_exhaustive]
56pub enum MaxBwConfig {
57    /// **MAXBW_SET** (§5.1.1, L3120-3128): MAX_BW set explicitly (bytes/sec).
58    /// Default: 1 Gbps = 125_000_000 bytes/sec.
59    Set(u64),
60    /// **INPUTBW_SET** (§5.1.1, L3130-3146): input rate (bytes/sec) + overhead
61    /// percentage. MAX_BW = `input_bw * (1 + overhead / 100)` (L3143).
62    InputBased {
63        /// The sender's input rate, in bytes per second.
64        input_bw: u64,
65        /// Overhead percentage (e.g. 25 means 25%).
66        overhead: u64,
67    },
68    /// **INPUTBW_ESTIMATED** (§5.1.1, L3148-3184): measured input rate +
69    /// overhead. MAX_BW = `est_input_bw * (1 + overhead / 100)` (L3154).
70    ///
71    /// Unlike [`MaxBwConfig::InputBased`], `est_input_bw` is updated
72    /// externally (e.g. the encoder's measured bitrate). The formula is
73    /// identical.
74    Estimated {
75        /// The estimated sender input rate, in bytes per second.
76        est_input_bw: u64,
77        /// Overhead percentage (e.g. 25 means 25%).
78        overhead: u64,
79    },
80    /// Unbounded — infinite bandwidth. No packet pacing is applied.
81    ///
82    /// Not a named mode in §5.1.1's table (L3197-3201), but is the implicit
83    /// effect when MAX_BW is not set or is unlimited. Represented by a
84    /// PKT_SND_PERIOD of 0 (send as fast as possible).
85    Infinite,
86}
87
88impl Default for MaxBwConfig {
89    /// Default: [`MaxBwConfig::Set`] at 1 Gbps (`private/specs-verified/rules/srt-livecc.md`
90    /// §5.1.1, L3122-3123).
91    fn default() -> Self {
92        MaxBwConfig::Set(DEFAULT_MAX_BW_BYTES_PER_SEC)
93    }
94}
95
96impl MaxBwConfig {
97    /// The §5.1.1 mode name.
98    pub fn name(&self) -> &'static str {
99        match self {
100            MaxBwConfig::Set(_) => "MAXBW_SET",
101            MaxBwConfig::InputBased { .. } => "INPUTBW_SET",
102            MaxBwConfig::Estimated { .. } => "INPUTBW_ESTIMATED",
103            MaxBwConfig::Infinite => "Infinite",
104        }
105    }
106
107    /// Resolve the current `MAX_BW` value in bytes per second, or `None` for
108    /// unbounded (infinite bandwidth).
109    ///
110    /// Per `private/specs-verified/rules/srt-livecc.md` §5.1.1:
111    /// - MAXBW_SET: returns the explicit value (L3120-3128).
112    /// - INPUTBW_SET: returns `input_bw * (1 + overhead / 100)` (L3143).
113    /// - INPUTBW_ESTIMATED: returns `est_input_bw * (1 + overhead / 100)` (L3154).
114    /// - Infinite: returns `None`.
115    pub fn max_bw_bytes_per_sec(&self) -> Option<u64> {
116        match *self {
117            MaxBwConfig::Set(bw) => Some(bw),
118            MaxBwConfig::InputBased { input_bw, overhead } => {
119                // L3143: MAX_BW = INPUT_BW * (1 + OVERHEAD / 100)
120                Some(apply_overhead(input_bw, overhead))
121            }
122            MaxBwConfig::Estimated {
123                est_input_bw,
124                overhead,
125            } => {
126                // L3154: MAX_BW = EST_INPUT_BW * (1 + OVERHEAD / 100)
127                Some(apply_overhead(est_input_bw, overhead))
128            }
129            MaxBwConfig::Infinite => None,
130        }
131    }
132}
133
134broadcast_common::impl_spec_display!(MaxBwConfig);
135
136/// Apply `'MAX_BW = bw * (1 + overhead / 100)'` (`private/specs-verified/rules/srt-livecc.md`
137/// L3143/L3154, verbatim).
138fn apply_overhead(bw: u64, overhead: u64) -> u64 {
139    // `overhead / 100` is truncated integer division, but the spec formula
140    // `(1 + OVERHEAD / 100)` is a real multiplier — we lose precision with
141    // integer arithmetic. Compute as `bw + bw * overhead / 100` instead, in
142    // 128 bits and saturating at `u64::MAX`.
143    let scaled = u128::from(bw) + u128::from(bw) * u128::from(overhead) / 100;
144    u64::try_from(scaled).unwrap_or(u64::MAX)
145}
146
147/// SRT Live Congestion Control — sender-side pacing state
148/// (`draft-sharabayko-srt-01` §5.1.2).
149///
150/// Tracks the EWMA average payload size and recomputes the inter-packet send
151/// period on each ACK.
152///
153/// Sans-IO: all timing is caller-driven — [`LiveCC::on_data_packet`],
154/// [`LiveCC::on_ack_received`], and [`LiveCC::tick`] take explicit inputs and
155/// return computed values; the controller never reads a wall clock internally.
156#[derive(Debug, Clone)]
157pub struct LiveCC {
158    /// Average payload size (EWMA), in bytes — `AvgPayloadSize` from §5.1.2
159    /// (L3219).
160    avg_payload_size: u64,
161    /// Maximum bandwidth configuration (§5.1.1).
162    max_bw_config: MaxBwConfig,
163}
164
165impl LiveCC {
166    /// Create a new LiveCC pacing controller.
167    ///
168    /// `max_bw_config` — the MAX_BW mode (§5.1.1). Use `Default::default()`
169    /// for the default 1 Gbps fixed MAXBW_SET mode.
170    ///
171    /// Initial `AvgPayloadSize` is set to the initial cap (1456 bytes),
172    /// per `private/specs-verified/rules/srt-livecc.md` §5.1.2 (L3222-3223).
173    pub fn new(max_bw_config: MaxBwConfig) -> Self {
174        LiveCC {
175            avg_payload_size: INITIAL_AVG_PAYLOAD_SIZE_CAP,
176            max_bw_config,
177        }
178    }
179
180    /// Update the EWMA average payload size on sending a data packet
181    /// (`private/specs-verified/rules/srt-livecc.md` §5.1.2, L3216-3223).
182    ///
183    /// `packet_payload_size` — the payload size (bytes) of the just-sent data
184    /// packet (original or retransmitted, L3216-3217).
185    ///
186    /// Formula (L3219, verbatim):
187    ///
188    /// ```text
189    /// AvgPayloadSize = 7/8 * AvgPayloadSize + 1/8 * PacketPayloadSize
190    /// ```
191    pub fn on_data_packet(&mut self, packet_payload_size: u64) {
192        // L3219: AvgPayloadSize = 7/8 * AvgPayloadSize + 1/8 * PacketPayloadSize
193        let old = self.avg_payload_size;
194        self.avg_payload_size = (7 * old + packet_payload_size) / 8;
195    }
196
197    /// The current average payload size estimate, in bytes.
198    pub fn avg_payload_size(&self) -> u64 {
199        self.avg_payload_size
200    }
201
202    /// The current MAX_BW configuration.
203    pub fn max_bw_config(&self) -> &MaxBwConfig {
204        &self.max_bw_config
205    }
206
207    /// Reconfigure the MAX_BW mode at runtime.
208    pub fn set_max_bw_config(&mut self, config: MaxBwConfig) {
209        self.max_bw_config = config;
210    }
211
212    /// Compute the current inter-packet send period in microseconds
213    /// (`private/specs-verified/rules/srt-livecc.md` §5.1.2, L3225-3238).
214    ///
215    /// Call this on ACK reception (method (2), L3225). The period is also
216    /// used after any state change (e.g. reconfiguration).
217    ///
218    /// Returns `Duration::ZERO` when bandwidth is unbounded (infinite mode),
219    /// meaning "send as fast as possible".
220    ///
221    /// Step 1 — PktSize (L3227-3229, paraphrased):
222    ///
223    /// ```text
224    /// PktSize = AvgPayloadSize + SRT header size
225    /// ```
226    ///
227    /// Step 2 — PKT_SND_PERIOD (L3234, verbatim):
228    ///
229    /// ```text
230    /// PKT_SND_PERIOD = PktSize * 1000000 / MAX_BW
231    /// ```
232    pub fn on_ack_received(&self) -> Duration {
233        let Some(max_bw) = self.max_bw_config.max_bw_bytes_per_sec() else {
234            // Infinite: no pacing.
235            return Duration::ZERO;
236        };
237        if max_bw == 0 {
238            return Duration::ZERO;
239        }
240
241        // L3227-3229: PktSize = AvgPayloadSize + SRT header size (16 bytes).
242        let pkt_size = self.avg_payload_size + SRT_HEADER_SIZE;
243
244        // L3234: PKT_SND_PERIOD = PktSize * 1000000 / MAX_BW
245        //
246        // pkt_size is in bytes, MAX_BW in bytes/sec. The factor 1_000_000
247        // converts seconds to microseconds (L3237-3238).
248        let period_us = pkt_size * 1_000_000 / max_bw;
249        Duration::from_micros(period_us)
250    }
251
252    /// Time-driven tick — currently a no-op for LiveCC (the `§5.1.2` algorithm
253    /// is driven by packet/ACK events only; an RTO timeout also triggers
254    /// `on_data_packet`, per L3240-3241).
255    ///
256    /// Provided for forward compatibility: the sender loop should call this
257    /// every cycle. Returns `None`.
258    pub fn tick(&mut self) -> Option<Duration> {
259        // Per spec, LiveCC reacts to events (data send, ACK, RTO — L3211-3214);
260        // the RTO timeout also calls on_data_packet (L3240-3241). No periodic
261        // internal computation needed.
262        None
263    }
264}
265
266impl Default for LiveCC {
267    fn default() -> Self {
268        LiveCC::new(Default::default())
269    }
270}
271
272#[cfg(test)]
273mod tests {
274    use super::*;
275
276    #[test]
277    fn initial_avg_payload_size_is_1456_cap() {
278        // L3222-3223: initial AvgPayloadSize is the max allowed payload, max 1456.
279        let cc = LiveCC::new(Default::default());
280        assert_eq!(cc.avg_payload_size(), 1456);
281    }
282
283    #[test]
284    fn default_bw_is_1_gbps() {
285        // L3122-3123: recommended default is 1 Gbps.
286        let cfg = MaxBwConfig::default();
287        assert_eq!(cfg.max_bw_bytes_per_sec(), Some(125_000_000));
288    }
289
290    #[test]
291    fn ewma_update_matches_hand_computed_formula() {
292        // L3219: AvgPayloadSize = 7/8 * old + 1/8 * payload.
293        // Initial: 1456. Feed a 100-byte payload.
294        // new = (7 * 1456 + 100) / 8 = (10192 + 100) / 8 = 10292 / 8 = 1286
295        let mut cc = LiveCC::new(Default::default());
296        cc.on_data_packet(100);
297        assert_eq!(cc.avg_payload_size(), 1286);
298    }
299
300    #[test]
301    fn ewma_converges_toward_constant_payload() {
302        // Feed a constant 1000-byte payload many times; the EWMA should
303        // converge toward 1000.
304        let mut cc = LiveCC::new(Default::default());
305        for _ in 0..64 {
306            cc.on_data_packet(1000);
307        }
308        let avg = cc.avg_payload_size();
309        // Converged within 1 of 1000.
310        assert!(avg.abs_diff(1000) <= 1, "expected ~1000, got {avg}");
311    }
312
313    #[test]
314    fn ewma_respects_initial_cap_regardless_of_first_feed() {
315        // The initial cap (1456) is separate from the first update.
316        // Even if we feed a tiny payload, the init was 1456, not the fed value.
317        let mut cc = LiveCC::new(Default::default());
318        cc.on_data_packet(50);
319        // new = (7 * 1456 + 50) / 8 = (10192 + 50) / 8 = 10242 / 8 = 1280
320        assert_eq!(cc.avg_payload_size(), 1280);
321    }
322
323    #[test]
324    fn pkt_snd_period_formula_matches_hand_computed() {
325        // L3234: PKT_SND_PERIOD = PktSize * 1000000 / MAX_BW.
326        //
327        // With default MAX_BW = 125_000_000 bytes/sec and init AvgPayloadSize
328        // = 1456:
329        //   PktSize = 1456 + 16 = 1472
330        //   period = 1472 * 1_000_000 / 125_000_000 = 1_472_000_000 / 125_000_000
331        //          = 11 (integer division; 11.776 truncated to 11)
332        let cc = LiveCC::new(Default::default());
333        let period = cc.on_ack_received();
334        assert_eq!(period, Duration::from_micros(11));
335    }
336
337    #[test]
338    fn pkt_snd_period_with_different_payload_size() {
339        // After feeding a 1316-byte payload seven times (to get close to
340        // converged), compute the period.
341        //
342        // EWMA after 7 steps: we don't hand-compute the exact 8-step weight
343        // here; instead we use a simpler scenario:
344        //   initial: 1456
345        //   feed 1316: avg = (7*1456 + 1316)/8 = 1438
346        //   feed 1316: avg = (7*1438 + 1316)/8 = 1422
347        //   PktSize = 1422 + 16 = 1438
348        //   period = 1438 * 1_000_000 / 125_000_000 = 11
349        let mut cc = LiveCC::new(Default::default());
350        cc.on_data_packet(1316);
351        cc.on_data_packet(1316);
352        let period = cc.on_ack_received();
353        assert_eq!(period, Duration::from_micros(11));
354    }
355
356    #[test]
357    fn input_bw_mode_formula() {
358        // L3143: MAX_BW = INPUT_BW * (1 + OVERHEAD / 100).
359        // input_bw = 10_000_000 (10 MB/s), overhead = 25%.
360        // MAX_BW = 10_000_000 + 10_000_000 * 25 / 100 = 12_500_000 bytes/sec.
361        let cfg = MaxBwConfig::InputBased {
362            input_bw: 10_000_000,
363            overhead: 25,
364        };
365        assert_eq!(cfg.max_bw_bytes_per_sec(), Some(12_500_000));
366    }
367
368    #[test]
369    fn estimated_mode_formula() {
370        // L3154: same formula as INPUTBW_SET but with EST_INPUT_BW.
371        let cfg = MaxBwConfig::Estimated {
372            est_input_bw: 5_000_000,
373            overhead: 10,
374        };
375        // MAX_BW = 5_000_000 + 5_000_000 * 10 / 100 = 5_500_000
376        assert_eq!(cfg.max_bw_bytes_per_sec(), Some(5_500_000));
377    }
378
379    #[test]
380    fn infinite_mode_returns_zero_period() {
381        let cc = LiveCC::new(MaxBwConfig::Infinite);
382        assert_eq!(cc.on_ack_received(), Duration::ZERO);
383    }
384
385    #[test]
386    fn set_mode_period_scales_with_bw() {
387        // MAXBW_SET at 62_500_000 bytes/sec (500 Mbps); init PktSize = 1472.
388        // period = 1472 * 1_000_000 / 62_500_000 = 23 (23.552 truncated).
389        let cc = LiveCC::new(MaxBwConfig::Set(62_500_000));
390        assert_eq!(cc.on_ack_received(), Duration::from_micros(23));
391    }
392
393    #[test]
394    fn runtime_reconfiguration_affects_period() {
395        let mut cc = LiveCC::new(MaxBwConfig::Infinite);
396        assert_eq!(cc.on_ack_received(), Duration::ZERO);
397
398        cc.set_max_bw_config(MaxBwConfig::Set(125_000_000));
399        assert_eq!(cc.on_ack_received(), Duration::from_micros(11));
400    }
401
402    #[test]
403    fn zero_bw_returns_zero_period() {
404        // Guard: if MAX_BW is 0, we'd divide by zero. Return ZERO instead.
405        let cc = LiveCC::new(MaxBwConfig::Set(0));
406        assert_eq!(cc.on_ack_received(), Duration::ZERO);
407    }
408
409    #[test]
410    fn tick_is_noop() {
411        let mut cc = LiveCC::new(Default::default());
412        assert_eq!(cc.tick(), None);
413        // Calling tick must not mutate state.
414        assert_eq!(cc.avg_payload_size(), 1456);
415    }
416
417    #[test]
418    fn overhead_formula_edge_cases() {
419        // overhead = 0: MAX_BW = bw + bw*0/100 = bw
420        assert_eq!(
421            MaxBwConfig::InputBased {
422                input_bw: 10_000,
423                overhead: 0,
424            }
425            .max_bw_bytes_per_sec(),
426            Some(10_000)
427        );
428        // overhead = 100: MAX_BW = bw + bw*100/100 = 2*bw
429        assert_eq!(
430            MaxBwConfig::InputBased {
431                input_bw: 10_000,
432                overhead: 100,
433            }
434            .max_bw_bytes_per_sec(),
435            Some(20_000)
436        );
437    }
438}