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 max_bw_mode_labels_match_the_spec_table() {
285 assert_eq!(MaxBwConfig::Set(1).name(), "MAXBW_SET");
286 assert_eq!(
287 MaxBwConfig::InputBased {
288 input_bw: 1,
289 overhead: 0
290 }
291 .name(),
292 "INPUTBW_SET"
293 );
294 assert_eq!(
295 MaxBwConfig::Estimated {
296 est_input_bw: 1,
297 overhead: 0,
298 }
299 .name(),
300 "INPUTBW_ESTIMATED"
301 );
302 assert_eq!(MaxBwConfig::Infinite.name(), "Infinite");
303 }
304
305 #[test]
306 fn max_bw_config_returns_the_configured_mode() {
307 let cc = LiveCC::new(MaxBwConfig::Set(1_234_567));
308 assert_eq!(cc.max_bw_config(), &MaxBwConfig::Set(1_234_567));
309 let mut cc = LiveCC::new(MaxBwConfig::Infinite);
310 cc.set_max_bw_config(MaxBwConfig::Estimated {
311 est_input_bw: 900_000,
312 overhead: 10,
313 });
314 assert_eq!(
315 cc.max_bw_config(),
316 &MaxBwConfig::Estimated {
317 est_input_bw: 900_000,
318 overhead: 10,
319 }
320 );
321 }
322
323 #[test]
324 fn default_bw_is_1_gbps() {
325 // L3122-3123: recommended default is 1 Gbps.
326 let cfg = MaxBwConfig::default();
327 assert_eq!(cfg.max_bw_bytes_per_sec(), Some(125_000_000));
328 }
329
330 #[test]
331 fn ewma_update_matches_hand_computed_formula() {
332 // L3219: AvgPayloadSize = 7/8 * old + 1/8 * payload.
333 // Initial: 1456. Feed a 100-byte payload.
334 // new = (7 * 1456 + 100) / 8 = (10192 + 100) / 8 = 10292 / 8 = 1286
335 let mut cc = LiveCC::new(Default::default());
336 cc.on_data_packet(100);
337 assert_eq!(cc.avg_payload_size(), 1286);
338 }
339
340 #[test]
341 fn ewma_converges_toward_constant_payload() {
342 // Feed a constant 1000-byte payload many times; the EWMA should
343 // converge toward 1000.
344 let mut cc = LiveCC::new(Default::default());
345 for _ in 0..64 {
346 cc.on_data_packet(1000);
347 }
348 let avg = cc.avg_payload_size();
349 // Converged within 1 of 1000.
350 assert!(avg.abs_diff(1000) <= 1, "expected ~1000, got {avg}");
351 }
352
353 #[test]
354 fn ewma_respects_initial_cap_regardless_of_first_feed() {
355 // The initial cap (1456) is separate from the first update.
356 // Even if we feed a tiny payload, the init was 1456, not the fed value.
357 let mut cc = LiveCC::new(Default::default());
358 cc.on_data_packet(50);
359 // new = (7 * 1456 + 50) / 8 = (10192 + 50) / 8 = 10242 / 8 = 1280
360 assert_eq!(cc.avg_payload_size(), 1280);
361 }
362
363 #[test]
364 fn pkt_snd_period_formula_matches_hand_computed() {
365 // L3234: PKT_SND_PERIOD = PktSize * 1000000 / MAX_BW.
366 //
367 // With default MAX_BW = 125_000_000 bytes/sec and init AvgPayloadSize
368 // = 1456:
369 // PktSize = 1456 + 16 = 1472
370 // period = 1472 * 1_000_000 / 125_000_000 = 1_472_000_000 / 125_000_000
371 // = 11 (integer division; 11.776 truncated to 11)
372 let cc = LiveCC::new(Default::default());
373 let period = cc.on_ack_received();
374 assert_eq!(period, Duration::from_micros(11));
375 }
376
377 #[test]
378 fn pkt_snd_period_with_different_payload_size() {
379 // After feeding a 1316-byte payload seven times (to get close to
380 // converged), compute the period.
381 //
382 // EWMA after 7 steps: we don't hand-compute the exact 8-step weight
383 // here; instead we use a simpler scenario:
384 // initial: 1456
385 // feed 1316: avg = (7*1456 + 1316)/8 = 1438
386 // feed 1316: avg = (7*1438 + 1316)/8 = 1422
387 // PktSize = 1422 + 16 = 1438
388 // period = 1438 * 1_000_000 / 125_000_000 = 11
389 let mut cc = LiveCC::new(Default::default());
390 cc.on_data_packet(1316);
391 cc.on_data_packet(1316);
392 let period = cc.on_ack_received();
393 assert_eq!(period, Duration::from_micros(11));
394 }
395
396 #[test]
397 fn input_bw_mode_formula() {
398 // L3143: MAX_BW = INPUT_BW * (1 + OVERHEAD / 100).
399 // input_bw = 10_000_000 (10 MB/s), overhead = 25%.
400 // MAX_BW = 10_000_000 + 10_000_000 * 25 / 100 = 12_500_000 bytes/sec.
401 let cfg = MaxBwConfig::InputBased {
402 input_bw: 10_000_000,
403 overhead: 25,
404 };
405 assert_eq!(cfg.max_bw_bytes_per_sec(), Some(12_500_000));
406 }
407
408 #[test]
409 fn estimated_mode_formula() {
410 // L3154: same formula as INPUTBW_SET but with EST_INPUT_BW.
411 let cfg = MaxBwConfig::Estimated {
412 est_input_bw: 5_000_000,
413 overhead: 10,
414 };
415 // MAX_BW = 5_000_000 + 5_000_000 * 10 / 100 = 5_500_000
416 assert_eq!(cfg.max_bw_bytes_per_sec(), Some(5_500_000));
417 }
418
419 #[test]
420 fn infinite_mode_returns_zero_period() {
421 let cc = LiveCC::new(MaxBwConfig::Infinite);
422 assert_eq!(cc.on_ack_received(), Duration::ZERO);
423 }
424
425 #[test]
426 fn set_mode_period_scales_with_bw() {
427 // MAXBW_SET at 62_500_000 bytes/sec (500 Mbps); init PktSize = 1472.
428 // period = 1472 * 1_000_000 / 62_500_000 = 23 (23.552 truncated).
429 let cc = LiveCC::new(MaxBwConfig::Set(62_500_000));
430 assert_eq!(cc.on_ack_received(), Duration::from_micros(23));
431 }
432
433 #[test]
434 fn runtime_reconfiguration_affects_period() {
435 let mut cc = LiveCC::new(MaxBwConfig::Infinite);
436 assert_eq!(cc.on_ack_received(), Duration::ZERO);
437
438 cc.set_max_bw_config(MaxBwConfig::Set(125_000_000));
439 assert_eq!(cc.on_ack_received(), Duration::from_micros(11));
440 }
441
442 #[test]
443 fn zero_bw_returns_zero_period() {
444 // Guard: if MAX_BW is 0, we'd divide by zero. Return ZERO instead.
445 let cc = LiveCC::new(MaxBwConfig::Set(0));
446 assert_eq!(cc.on_ack_received(), Duration::ZERO);
447 }
448
449 #[test]
450 fn tick_is_noop() {
451 let mut cc = LiveCC::new(Default::default());
452 assert_eq!(cc.tick(), None);
453 // Calling tick must not mutate state.
454 assert_eq!(cc.avg_payload_size(), 1456);
455 }
456
457 #[test]
458 fn overhead_formula_edge_cases() {
459 // overhead = 0: MAX_BW = bw + bw*0/100 = bw
460 assert_eq!(
461 MaxBwConfig::InputBased {
462 input_bw: 10_000,
463 overhead: 0,
464 }
465 .max_bw_bytes_per_sec(),
466 Some(10_000)
467 );
468 // overhead = 100: MAX_BW = bw + bw*100/100 = 2*bw
469 assert_eq!(
470 MaxBwConfig::InputBased {
471 input_bw: 10_000,
472 overhead: 100,
473 }
474 .max_bw_bytes_per_sec(),
475 Some(20_000)
476 );
477 }
478}