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_core::impl_spec_display!(MaxBwConfig);
135
136/// Apply `'MAX_BW = bw * (1 + overhead / 100)'` (`private/specs-verified/rules/srt-livecc.md`
137/// L3143/L3154, verbatim).
138/// Percent divisor of the overhead formula.
139const PERCENT: u128 = 100;
140
141/// Weights of the payload-size EWMA: 7/8 old, 1/8 new (§5.1.2).
142const EWMA_NUM: u64 = 7;
143const EWMA_DEN: u64 = 8;
144
145fn apply_overhead(bw: u64, overhead: u64) -> u64 {
146 // `overhead / 100` is truncated integer division, but the spec formula
147 // `(1 + OVERHEAD / 100)` is a real multiplier — we lose precision with
148 // integer arithmetic. Compute as `bw + bw * overhead / 100` instead, in
149 // 128 bits and saturating at `u64::MAX`.
150 let scaled = u128::from(bw) + u128::from(bw) * u128::from(overhead) / PERCENT;
151 u64::try_from(scaled).unwrap_or(u64::MAX)
152}
153
154/// SRT Live Congestion Control — sender-side pacing state
155/// (`draft-sharabayko-srt-01` §5.1.2).
156///
157/// Tracks the EWMA average payload size and recomputes the inter-packet send
158/// period on each ACK.
159///
160/// Sans-IO: all timing is caller-driven — [`LiveCC::on_data_packet`],
161/// [`LiveCC::on_ack_received`], and [`LiveCC::tick`] take explicit inputs and
162/// return computed values; the controller never reads a wall clock internally.
163#[derive(Debug, Clone)]
164pub struct LiveCC {
165 /// Average payload size (EWMA), in bytes — `AvgPayloadSize` from §5.1.2
166 /// (L3219).
167 avg_payload_size: u64,
168 /// Maximum bandwidth configuration (§5.1.1).
169 max_bw_config: MaxBwConfig,
170}
171
172impl LiveCC {
173 /// Create a new LiveCC pacing controller.
174 ///
175 /// `max_bw_config` — the MAX_BW mode (§5.1.1). Use `Default::default()`
176 /// for the default 1 Gbps fixed MAXBW_SET mode.
177 ///
178 /// Initial `AvgPayloadSize` is set to the initial cap (1456 bytes),
179 /// per `private/specs-verified/rules/srt-livecc.md` §5.1.2 (L3222-3223).
180 pub fn new(max_bw_config: MaxBwConfig) -> Self {
181 LiveCC {
182 avg_payload_size: INITIAL_AVG_PAYLOAD_SIZE_CAP,
183 max_bw_config,
184 }
185 }
186
187 /// Update the EWMA average payload size on sending a data packet
188 /// (`private/specs-verified/rules/srt-livecc.md` §5.1.2, L3216-3223).
189 ///
190 /// `packet_payload_size` — the payload size (bytes) of the just-sent data
191 /// packet (original or retransmitted, L3216-3217).
192 ///
193 /// Formula (L3219, verbatim):
194 ///
195 /// ```text
196 /// AvgPayloadSize = 7/8 * AvgPayloadSize + 1/8 * PacketPayloadSize
197 /// ```
198 pub fn on_data_packet(&mut self, packet_payload_size: u64) {
199 // L3219: AvgPayloadSize = 7/8 * AvgPayloadSize + 1/8 * PacketPayloadSize
200 let old = self.avg_payload_size;
201 self.avg_payload_size = (EWMA_NUM * old + packet_payload_size) / EWMA_DEN;
202 }
203
204 /// The current average payload size estimate, in bytes.
205 pub fn avg_payload_size(&self) -> u64 {
206 self.avg_payload_size
207 }
208
209 /// The current MAX_BW configuration.
210 pub fn max_bw_config(&self) -> &MaxBwConfig {
211 &self.max_bw_config
212 }
213
214 /// Reconfigure the MAX_BW mode at runtime.
215 pub fn set_max_bw_config(&mut self, config: MaxBwConfig) {
216 self.max_bw_config = config;
217 }
218
219 /// Compute the current inter-packet send period in microseconds
220 /// (`private/specs-verified/rules/srt-livecc.md` §5.1.2, L3225-3238).
221 ///
222 /// Call this on ACK reception (method (2), L3225). The period is also
223 /// used after any state change (e.g. reconfiguration).
224 ///
225 /// Returns `Duration::ZERO` when bandwidth is unbounded (infinite mode),
226 /// meaning "send as fast as possible".
227 ///
228 /// Step 1 — PktSize (L3227-3229, paraphrased):
229 ///
230 /// ```text
231 /// PktSize = AvgPayloadSize + SRT header size
232 /// ```
233 ///
234 /// Step 2 — PKT_SND_PERIOD (L3234, verbatim):
235 ///
236 /// ```text
237 /// PKT_SND_PERIOD = PktSize * 1000000 / MAX_BW
238 /// ```
239 pub fn on_ack_received(&self) -> Duration {
240 let Some(max_bw) = self.max_bw_config.max_bw_bytes_per_sec() else {
241 // Infinite: no pacing.
242 return Duration::ZERO;
243 };
244 if max_bw == 0 {
245 return Duration::ZERO;
246 }
247
248 // L3227-3229: PktSize = AvgPayloadSize + SRT header size (16 bytes).
249 let pkt_size = self.avg_payload_size + SRT_HEADER_SIZE;
250
251 // L3234: PKT_SND_PERIOD = PktSize * 1000000 / MAX_BW
252 //
253 // pkt_size is in bytes, MAX_BW in bytes/sec. The factor 1_000_000
254 // converts seconds to microseconds (L3237-3238).
255 let period_us = pkt_size * broadcast_core::units::MICROS_PER_SEC / max_bw;
256 Duration::from_micros(period_us)
257 }
258
259 /// Time-driven tick — currently a no-op for LiveCC (the `§5.1.2` algorithm
260 /// is driven by packet/ACK events only; an RTO timeout also triggers
261 /// `on_data_packet`, per L3240-3241).
262 ///
263 /// Provided for forward compatibility: the sender loop should call this
264 /// every cycle. Returns `None`.
265 pub fn tick(&mut self) -> Option<Duration> {
266 // Per spec, LiveCC reacts to events (data send, ACK, RTO — L3211-3214);
267 // the RTO timeout also calls on_data_packet (L3240-3241). No periodic
268 // internal computation needed.
269 None
270 }
271}
272
273impl Default for LiveCC {
274 fn default() -> Self {
275 LiveCC::new(Default::default())
276 }
277}
278
279#[cfg(test)]
280mod tests {
281 use super::*;
282
283 #[test]
284 fn initial_avg_payload_size_is_1456_cap() {
285 // L3222-3223: initial AvgPayloadSize is the max allowed payload, max 1456.
286 let cc = LiveCC::new(Default::default());
287 assert_eq!(cc.avg_payload_size(), 1456);
288 }
289
290 #[test]
291 fn max_bw_mode_labels_match_the_spec_table() {
292 assert_eq!(MaxBwConfig::Set(1).name(), "MAXBW_SET");
293 assert_eq!(
294 MaxBwConfig::InputBased {
295 input_bw: 1,
296 overhead: 0
297 }
298 .name(),
299 "INPUTBW_SET"
300 );
301 assert_eq!(
302 MaxBwConfig::Estimated {
303 est_input_bw: 1,
304 overhead: 0,
305 }
306 .name(),
307 "INPUTBW_ESTIMATED"
308 );
309 assert_eq!(MaxBwConfig::Infinite.name(), "Infinite");
310 }
311
312 #[test]
313 fn max_bw_config_returns_the_configured_mode() {
314 let cc = LiveCC::new(MaxBwConfig::Set(1_234_567));
315 assert_eq!(cc.max_bw_config(), &MaxBwConfig::Set(1_234_567));
316 let mut cc = LiveCC::new(MaxBwConfig::Infinite);
317 cc.set_max_bw_config(MaxBwConfig::Estimated {
318 est_input_bw: 900_000,
319 overhead: 10,
320 });
321 assert_eq!(
322 cc.max_bw_config(),
323 &MaxBwConfig::Estimated {
324 est_input_bw: 900_000,
325 overhead: 10,
326 }
327 );
328 }
329
330 #[test]
331 fn default_bw_is_1_gbps() {
332 // L3122-3123: recommended default is 1 Gbps.
333 let cfg = MaxBwConfig::default();
334 assert_eq!(cfg.max_bw_bytes_per_sec(), Some(125_000_000));
335 }
336
337 #[test]
338 fn ewma_update_matches_hand_computed_formula() {
339 // L3219: AvgPayloadSize = 7/8 * old + 1/8 * payload.
340 // Initial: 1456. Feed a 100-byte payload.
341 // new = (7 * 1456 + 100) / 8 = (10192 + 100) / 8 = 10292 / 8 = 1286
342 let mut cc = LiveCC::new(Default::default());
343 cc.on_data_packet(100);
344 assert_eq!(cc.avg_payload_size(), 1286);
345 }
346
347 #[test]
348 fn ewma_converges_toward_constant_payload() {
349 // Feed a constant 1000-byte payload many times; the EWMA should
350 // converge toward 1000.
351 let mut cc = LiveCC::new(Default::default());
352 for _ in 0..64 {
353 cc.on_data_packet(1000);
354 }
355 let avg = cc.avg_payload_size();
356 // Converged within 1 of 1000.
357 assert!(avg.abs_diff(1000) <= 1, "expected ~1000, got {avg}");
358 }
359
360 #[test]
361 fn ewma_respects_initial_cap_regardless_of_first_feed() {
362 // The initial cap (1456) is separate from the first update.
363 // Even if we feed a tiny payload, the init was 1456, not the fed value.
364 let mut cc = LiveCC::new(Default::default());
365 cc.on_data_packet(50);
366 // new = (7 * 1456 + 50) / 8 = (10192 + 50) / 8 = 10242 / 8 = 1280
367 assert_eq!(cc.avg_payload_size(), 1280);
368 }
369
370 #[test]
371 fn pkt_snd_period_formula_matches_hand_computed() {
372 // L3234: PKT_SND_PERIOD = PktSize * 1000000 / MAX_BW.
373 //
374 // With default MAX_BW = 125_000_000 bytes/sec and init AvgPayloadSize
375 // = 1456:
376 // PktSize = 1456 + 16 = 1472
377 // period = 1472 * 1_000_000 / 125_000_000 = 1_472_000_000 / 125_000_000
378 // = 11 (integer division; 11.776 truncated to 11)
379 let cc = LiveCC::new(Default::default());
380 let period = cc.on_ack_received();
381 assert_eq!(period, Duration::from_micros(11));
382 }
383
384 #[test]
385 fn pkt_snd_period_with_different_payload_size() {
386 // After feeding a 1316-byte payload seven times (to get close to
387 // converged), compute the period.
388 //
389 // EWMA after 7 steps: we don't hand-compute the exact 8-step weight
390 // here; instead we use a simpler scenario:
391 // initial: 1456
392 // feed 1316: avg = (7*1456 + 1316)/8 = 1438
393 // feed 1316: avg = (7*1438 + 1316)/8 = 1422
394 // PktSize = 1422 + 16 = 1438
395 // period = 1438 * 1_000_000 / 125_000_000 = 11
396 let mut cc = LiveCC::new(Default::default());
397 cc.on_data_packet(1316);
398 cc.on_data_packet(1316);
399 let period = cc.on_ack_received();
400 assert_eq!(period, Duration::from_micros(11));
401 }
402
403 #[test]
404 fn input_bw_mode_formula() {
405 // L3143: MAX_BW = INPUT_BW * (1 + OVERHEAD / 100).
406 // input_bw = 10_000_000 (10 MB/s), overhead = 25%.
407 // MAX_BW = 10_000_000 + 10_000_000 * 25 / 100 = 12_500_000 bytes/sec.
408 let cfg = MaxBwConfig::InputBased {
409 input_bw: 10_000_000,
410 overhead: 25,
411 };
412 assert_eq!(cfg.max_bw_bytes_per_sec(), Some(12_500_000));
413 }
414
415 #[test]
416 fn estimated_mode_formula() {
417 // L3154: same formula as INPUTBW_SET but with EST_INPUT_BW.
418 let cfg = MaxBwConfig::Estimated {
419 est_input_bw: 5_000_000,
420 overhead: 10,
421 };
422 // MAX_BW = 5_000_000 + 5_000_000 * 10 / 100 = 5_500_000
423 assert_eq!(cfg.max_bw_bytes_per_sec(), Some(5_500_000));
424 }
425
426 #[test]
427 fn infinite_mode_returns_zero_period() {
428 let cc = LiveCC::new(MaxBwConfig::Infinite);
429 assert_eq!(cc.on_ack_received(), Duration::ZERO);
430 }
431
432 #[test]
433 fn set_mode_period_scales_with_bw() {
434 // MAXBW_SET at 62_500_000 bytes/sec (500 Mbps); init PktSize = 1472.
435 // period = 1472 * 1_000_000 / 62_500_000 = 23 (23.552 truncated).
436 let cc = LiveCC::new(MaxBwConfig::Set(62_500_000));
437 assert_eq!(cc.on_ack_received(), Duration::from_micros(23));
438 }
439
440 #[test]
441 fn runtime_reconfiguration_affects_period() {
442 let mut cc = LiveCC::new(MaxBwConfig::Infinite);
443 assert_eq!(cc.on_ack_received(), Duration::ZERO);
444
445 cc.set_max_bw_config(MaxBwConfig::Set(125_000_000));
446 assert_eq!(cc.on_ack_received(), Duration::from_micros(11));
447 }
448
449 #[test]
450 fn zero_bw_returns_zero_period() {
451 // Guard: if MAX_BW is 0, we'd divide by zero. Return ZERO instead.
452 let cc = LiveCC::new(MaxBwConfig::Set(0));
453 assert_eq!(cc.on_ack_received(), Duration::ZERO);
454 }
455
456 #[test]
457 fn tick_is_noop() {
458 let mut cc = LiveCC::new(Default::default());
459 assert_eq!(cc.tick(), None);
460 // Calling tick must not mutate state.
461 assert_eq!(cc.avg_payload_size(), 1456);
462 }
463
464 #[test]
465 fn overhead_formula_edge_cases() {
466 // overhead = 0: MAX_BW = bw + bw*0/100 = bw
467 assert_eq!(
468 MaxBwConfig::InputBased {
469 input_bw: 10_000,
470 overhead: 0,
471 }
472 .max_bw_bytes_per_sec(),
473 Some(10_000)
474 );
475 // overhead = 100: MAX_BW = bw + bw*100/100 = 2*bw
476 assert_eq!(
477 MaxBwConfig::InputBased {
478 input_bw: 10_000,
479 overhead: 100,
480 }
481 .max_bw_bytes_per_sec(),
482 Some(20_000)
483 );
484 }
485}