Skip to main content

srt_runtime/
filecc.rs

1//! SRT File Transfer Congestion Control (FileCC) — window-based congestion
2//! control, `draft-sharabayko-srt-01` §5.2 (curated at
3//! `private/specs-verified/rules/srt-congestion.md`).
4//!
5//! This is the **file/bulk-transfer mode** sibling of [`crate::livecc::LiveCC`]
6//! (§5.1, the **live/streaming mode**'s pacing-only model). Unlike LiveCC,
7//! which only paces `PKT_SND_PERIOD` from a configured `MAX_BW`, FileCC is "a
8//! hybrid Additive Increase Multiplicative Decrease (AIMD) algorithm"
9//! (`private/specs-verified/rules/srt-congestion.md` L3294-3295) that also grows/shrinks a
10//! congestion window (`CWND_SIZE`), in two strictly-sequential phases: Slow
11//! Start (§5.2.1.1), then Congestion Avoidance (§5.2.1.2) — see [`Phase`].
12//! `PKT_SND_PERIOD` and `CWND_SIZE` are computed independently of and do not
13//! touch LiveCC's state — the two controllers are additive alternatives, not
14//! layered.
15//!
16//! ## Usage
17//!
18//! ```rust
19//! use srt_runtime::filecc::{FileCc, Phase};
20//! use broadcast_common::stage::Timestamp;
21//! use core::time::Duration;
22//!
23//! let mut cc = FileCc::new(0);
24//! assert_eq!(cc.phase(), Phase::SlowStart);
25//!
26//! // On each full ACK, feed the receiver-reported rate/RTT samples:
27//! cc.on_ack(Timestamp::from_millis(10), 16, 5_000, 1_000, Duration::from_millis(50));
28//!
29//! // A NAK (loss report) ends slow start on the first loss (rule 4/9):
30//! cc.on_loss(8, 16, 0.5);
31//! assert_eq!(cc.phase(), Phase::CongestionAvoidance);
32//! ```
33//!
34//! ## Sans-IO contract
35//!
36//! Like every other engine in this crate, [`FileCc`] never reads a wall
37//! clock: [`FileCc::on_ack`] takes an explicit `now: Timestamp`; [`FileCc::on_loss`]
38//! and [`FileCc::on_timeout`] are driven purely by caller-reported events.
39//!
40//! ## Shared state, not redefined here
41//!
42//! Per `private/specs-verified/rules/srt-congestion.md`'s header note, the following are
43//! cross-referenced, not redefined by this module:
44//! - `RC_INTERVAL` / `SYN` = 10 ms — reused from [`crate::arq::FULL_ACK_PERIOD`]
45//!   (`private/specs-verified/rules/srt-arq.md` rule 11), which is the same 10 ms value
46//!   (L3421-3425).
47//! - The initial `RTT` estimate (100 ms) — reused from
48//!   [`crate::arq::rtt::INITIAL_RTT`] (`private/specs-verified/rules/srt-arq.md` rule 31)
49//!   before the first ACK sample is fed.
50//!
51//! ## Two implementation-defined gaps, flagged (not fabricated)
52//!
53//! `private/specs-verified/rules/srt-congestion.md` explicitly flags two points the draft
54//! text leaves unspecified. Both are resolved here with a documented choice:
55//!
56//! 1. **EWMA weight for `RECEIVING_RATE`/`EST_LINK_CAPACITY` smoothing**
57//!    (gap, L3678-3681 / doc's "Gaps" section). Chosen: **this engine does
58//!    not smooth them itself** — [`FileCc::on_ack`] takes `receiving_rate_pps`
59//!    and `est_link_capacity_pps` as already-current values and stores them
60//!    verbatim, exactly the same treatment this section already gives `RTT`
61//!    (cross-ref rule/L3409-3411: "receiver-reported and sender-smoothed",
62//!    with the smoothing defined *elsewhere*, not here). This keeps the
63//!    engine's formulas directly hand-computable from fed inputs (no hidden
64//!    internal averaging to reverse-engineer), and leaves the actual
65//!    smoothing decision to the caller/sender loop — consistent with how RTT
66//!    is already layered in this crate ([`crate::arq::rtt::RttEstimator`] is
67//!    a separate, explicit component, not folded into the ARQ sender).
68//! 2. **Packet-pairs probing mechanics** (gap, L3686-3689). Out of scope:
69//!    this module consumes `RECEIVING_RATE`/`EST_LINK_CAPACITY` as inputs: it
70//!    does not implement the receiver-side inter-arrival-time measurement or
71//!    packet-pairs probing described in §5.2.1.3 (rules 30-37) that would
72//!    *produce* those inputs on a real receiver. That measurement pipeline is
73//!    receiver-side and is not part of this sender-side congestion-control
74//!    state machine.
75//!
76//! A third, smaller implementation choice not flagged as a spec gap: the
77//! `DecRandom` *distribution* (uniform in `[1, AvgNAKNum]`, clamped to 1) is
78//! given (rule 23), but no source of randomness is specified. This module
79//! uses a small internal, deterministic xorshift PRNG instead of pulling in
80//! a `rand` dependency for a `no_std` crate — true entropy is not required
81//! for correctness here, `DecRandom` only staggers repeat-decrease timing
82//! across congestion periods (rule 24). `DecRandom` is rounded to the
83//! nearest whole number (`FileCc::next_dec_random`, internal): Step 4's gate
84//! (`NAKCount == DecCount * DecRandom`) compares two integer counters, so a
85//! fractional draw makes that equality unsatisfiable after the first check.
86//!
87//! ## A quirk of the draft's own Step 4 pseudocode (verified, not a bug)
88//!
89//! `NAKCount`/`DecCount` reset to 1 at the start of a congestion period and
90//! are ONLY incremented again *inside* Step 4's own conditional (rule 28) —
91//! never unconditionally per NAK. So once the immediate post-reset check
92//! (`1 == 1*DecRandom`) fails — i.e. whenever the drawn `DecRandom != 1` —
93//! neither counter ever moves again for the rest of the period, and Step 4
94//! goes silent until the next congestion period redraws `DecRandom`. This is
95//! a property of the draft text as transcribed (`private/specs-verified/rules/srt-congestion.md`,
96//! confirmed against the actual reference implementation, `libsrt`
97//! `congctl.cpp`, which uses a different formulation — `NAKCount % DecRandom
98//! == 0` with both counters incrementing on every same-period NAK
99//! regardless of outcome — that does not share this one-shot property).
100//! Adopting libsrt's formulation would be a spec-posture departure this
101//! crate is not designated for; this implementation stays literal to the
102//! curated draft text. See `filecc::tests::repeat_decrease_is_a_one_shot_per_period_once_dec_random_exceeds_one`.
103
104use broadcast_common::stage::Timestamp;
105use core::time::Duration;
106
107use crate::arq::FULL_ACK_PERIOD;
108use crate::arq::rtt::INITIAL_RTT;
109use crate::arq::seq::{seq_diff, seq_gt};
110
111/// `RC_INTERVAL` = `SYN` = 10 ms (`private/specs-verified/rules/srt-congestion.md` L3421-3425),
112/// reused from [`crate::arq::FULL_ACK_PERIOD`] (same value, `srt-arq.md` rule
113/// 11) rather than redefined here.
114const RC_INTERVAL: Duration = FULL_ACK_PERIOD;
115
116/// `S` — "the SRT packet size (in terms of IP payload) in bytes. SRT treats
117/// 1500 bytes as a standard packet size." (`private/specs-verified/rules/srt-congestion.md`
118/// L3539-3540, verbatim). A different quantity from LiveCC's EWMA-derived
119/// `PktSize` — see the module doc's header note.
120const S_BYTES: f64 = 1500.0;
121
122/// Slow start's fixed `PKT_SND_PERIOD` — "1 microsecond ... in order to send
123/// packets as fast as possible, but not at an infinite rate"
124/// (`private/specs-verified/rules/srt-congestion.md` L3338-3340, verbatim; rule 6).
125const SLOW_START_PKT_SND_PERIOD_US: f64 = 1.0;
126
127/// Slow start's initial `CWND_SIZE` — 16 packets (`private/specs-verified/rules/srt-congestion.md`
128/// L3340-3341, rule 7).
129const INITIAL_CWND_SIZE: f64 = 16.0;
130
131/// `LastDecPeriod`'s initial value — 1 microsecond (`private/specs-verified/rules/srt-congestion.md`
132/// L3521-3524).
133const INITIAL_LAST_DEC_PERIOD_US: f64 = 1.0;
134
135/// Default `MAX_CWND_SIZE` — the spec suggests "the maximum receiver buffer
136/// size (12 MB)" as the threshold (`private/specs-verified/rules/srt-congestion.md` L3344-3345,
137/// rule 8), worded as settable/recommended, not a hardwired constant.
138/// Expressed here in packets at the standard packet size `S` (1500 bytes):
139/// `12_000_000 / 1500 = 8000` packets. Override with [`FileCc::set_max_cwnd_size`].
140const DEFAULT_MAX_CWND_SIZE: f64 = 8_000.0;
141
142/// The NAK-tolerance loss-ratio threshold — "less than 2%"
143/// (`private/specs-verified/rules/srt-congestion.md` L3572-3579, rule 16).
144const LOSS_RATIO_TOLERANCE: f64 = 0.02;
145
146/// The repeat-decrease rate-backoff multiplier — `1.03`
147/// (`private/specs-verified/rules/srt-congestion.md` L3602-3604 / L3652-3654, rules 19 & 27).
148const RATE_BACKOFF_FACTOR: f64 = 1.03;
149
150/// The `AvgNAKNum` EWMA weights — `0.97`/`0.03`
151/// (`private/specs-verified/rules/srt-congestion.md` L3606-3608, rule 20, verbatim).
152const AVG_NAK_NUM_OLD_WEIGHT: f64 = 0.97;
153const AVG_NAK_NUM_NEW_WEIGHT: f64 = 0.03;
154
155/// The repeat-decrease `DecCount` ceiling — decreases stop once `DecCount`
156/// exceeds 5 within a congestion period (`private/specs-verified/rules/srt-congestion.md`
157/// L3652-3658, rule "Step 4").
158const MAX_DEC_COUNT: u32 = 5;
159
160/// `inc`'s multiplier in the Step 5 rate-increase formula (`private/specs-verified/rules/srt-congestion.md`
161/// L3498-3517, verbatim: `0.0000015`).
162const INC_SCALE: f64 = 0.0000015;
163
164/// Microseconds per second — the units conversion every `PKT_SND_PERIOD`/rate
165/// formula in this module divides or multiplies by (`private/specs-verified/rules/srt-congestion.md`,
166/// recurring throughout §5.2.1.2's Steps 3/5/6, sourced from the same
167/// L3498-3517 code block as [`INC_SCALE`]).
168const US_PER_SEC: f64 = 1_000_000.0;
169
170/// `lossBandwidth`'s doubling factor in the Step 5 rate-increase formula
171/// (`private/specs-verified/rules/srt-congestion.md` L3498-3517 code block, verbatim:
172/// `lossBandwidth = 2 * (1000000 / LastDecPeriod)`).
173const LOSS_BANDWIDTH_FACTOR: f64 = 2.0;
174
175/// The `linkCapacity / 9` clamp divisor in the Step 5 rate-increase formula
176/// (`private/specs-verified/rules/srt-congestion.md` L3498-3517 code block, verbatim:
177/// `if (... && (linkCapacity / 9) < B) B = linkCapacity / 9;`) — a
178/// spec-mandated tuning constant, not independently derived.
179const LINK_CAPACITY_CLAMP_DIVISOR: f64 = 9.0;
180
181/// Bits per byte, used to convert `S` (packet size in bytes) to bits in the
182/// Step 5 rate-increase formula (`private/specs-verified/rules/srt-congestion.md` L3498-3517
183/// code block, verbatim: `inc = pow(10.0, ceil(log10(B * S * 8))) * 0.0000015 / S`).
184const BITS_PER_BYTE: f64 = 8.0;
185
186/// FileCC algorithm phase (`private/specs-verified/rules/srt-congestion.md` rules 4-5). Slow
187/// Start (§5.2.1.1) runs exactly once at the start of a connection; it
188/// transitions to Congestion Avoidance (§5.2.1.2) on the first loss,
189/// `CWND_SIZE` exceeding its maximum, or a timeout — and never transitions
190/// back (L3323-3326).
191#[derive(Debug, Clone, Copy, PartialEq, Eq)]
192#[non_exhaustive]
193pub enum Phase {
194    /// §5.2.1.1 — probes for available bandwidth; runs exactly once.
195    SlowStart,
196    /// §5.2.1.2 — entered once slow start ends; the steady-state AIMD phase.
197    CongestionAvoidance,
198}
199
200impl Phase {
201    /// The §5.2 phase name.
202    pub fn name(&self) -> &'static str {
203        match self {
204            Phase::SlowStart => "SlowStart",
205            Phase::CongestionAvoidance => "CongestionAvoidance",
206        }
207    }
208}
209
210broadcast_common::impl_spec_display!(Phase);
211
212/// A minimal, seedable xorshift64* PRNG — see the module doc's third
213/// implementation-choice note (`DecRandom`'s source of randomness is
214/// unspecified by the draft; only its distribution is given, rule 23).
215#[derive(Debug, Clone, Copy)]
216struct XorShift64(u64);
217
218impl XorShift64 {
219    /// A fixed, non-zero default seed. Deterministic on purpose: reproducible
220    /// test/debug behavior, and true entropy is not required for correctness
221    /// (see the module doc).
222    const DEFAULT_SEED: u64 = 0x9E37_79B9_7F4A_7C15;
223
224    fn new(seed: u64) -> Self {
225        XorShift64(if seed == 0 { Self::DEFAULT_SEED } else { seed })
226    }
227
228    /// Next pseudo-random value, uniform in `[0.0, 1.0)`.
229    fn next_unit(&mut self) -> f64 {
230        let mut x = self.0;
231        x ^= x << 13;
232        x ^= x >> 7;
233        x ^= x << 17;
234        self.0 = x;
235        let r = x.wrapping_mul(0x2545_F491_4F6C_DD1D);
236        // Top 53 bits as a double in [0, 1).
237        (r >> 11) as f64 * (1.0 / (1u64 << 53) as f64)
238    }
239}
240
241/// `min(a, b)` for `f64`, without relying on `f64::min` (kept as a plain
242/// comparison so this module has no dependency on any transcendental-math
243/// support — see [`next_power_of_10`]'s doc for why that matters for the
244/// `no_std` build).
245fn fmin(a: f64, b: f64) -> f64 {
246    if a < b { a } else { b }
247}
248
249/// `max(a, b)` for `f64` — see [`fmin`].
250fn fmax(a: f64, b: f64) -> f64 {
251    if a > b { a } else { b }
252}
253
254/// Round-half-away-from-zero for `f64`, matching `f64::round`'s semantics —
255/// without calling it, since `f64::round` is a `std`-only method (`core`
256/// float types don't expose it; see [`fmin`]'s doc for why this module avoids
257/// any transcendental/libm dependency). `as i64` float-to-int casts are
258/// saturating in Rust, so this is safe for any finite input in `i64` range —
259/// `DecRandom` values are always small and positive.
260fn fround(x: f64) -> f64 {
261    let truncated = x as i64 as f64;
262    let diff = x - truncated;
263    if diff >= 0.5 {
264        truncated + 1.0
265    } else if diff <= -0.5 {
266        truncated - 1.0
267    } else {
268        truncated
269    }
270}
271
272/// `pow(10.0, ceil(log10(x)))` for `x > 0` — the smallest power of 10 that is
273/// `>= x` (`private/specs-verified/rules/srt-congestion.md` Step 5, L3506, verbatim source:
274/// `pow(10.0, ceil(log10(B * S * 8))) * 0.0000015 / S`).
275///
276/// Implemented via repeated multiplication/division instead of calling
277/// `log10`/`powf` directly: those are `libm` functions not available in
278/// `core` (this crate builds `no_std`, including on `thumbv7em-none-eabi`
279/// with no libm), whereas this loop only uses basic arithmetic and
280/// comparisons. Algebraically identical to the spec's formula for `x > 0`.
281fn next_power_of_10(x: f64) -> f64 {
282    debug_assert!(x > 0.0, "next_power_of_10 is only defined for x > 0");
283    let mut p = 1.0_f64;
284    while p < x {
285        p *= 10.0;
286    }
287    while p / 10.0 >= x {
288        p /= 10.0;
289    }
290    p
291}
292
293/// SRT File Transfer Congestion Control — sender-side window + pacing state
294/// (`draft-sharabayko-srt-01` §5.2). See the module doc for the full formula
295/// mapping, the sans-IO contract, and the two flagged spec gaps.
296#[derive(Debug, Clone)]
297pub struct FileCc {
298    phase: Phase,
299    /// `CWND_SIZE`, in packets (rule 7; Step 3 of both phases).
300    cwnd_size: f64,
301    /// `MAX_CWND_SIZE` (rule 8) — slow start ends once `cwnd_size` exceeds
302    /// this.
303    max_cwnd_size: f64,
304    /// `PKT_SND_PERIOD`, in microseconds.
305    pkt_snd_period_us: f64,
306    /// `LastRCTime` — `None` until the first ACK (rate-control gate always
307    /// passes on the very first call; the draft does not give an initial
308    /// value, this is the implementation-defined resolution).
309    last_rc_time: Option<Timestamp>,
310    /// `LAST_ACK_SEQNO` — initialized to the caller-supplied `initial_seqno`
311    /// (representing "no data packet acknowledged yet"; the draft does not
312    /// give LAST_ACK_SEQNO's initial value either).
313    last_ack_seqno: u32,
314    /// `bLoss` — initial value `False` (rule 12).
315    b_loss: bool,
316    /// `LastDecPeriod`, in microseconds — initial value 1 microsecond
317    /// (item under Step 5).
318    last_dec_period_us: f64,
319    /// `LastDecSeq` — `None` until the first Congestion-Avoidance-phase NAK
320    /// (so the very first CA-phase loss always starts a new congestion
321    /// period, rule 25).
322    last_dec_seq: Option<u32>,
323    /// `AvgNAKNum` — initial value 0 (rule "State variables", verbatim def).
324    avg_nak_num: f64,
325    /// `NAKCount` — initial value 0.
326    nak_count: u32,
327    /// `DecCount` — initial value 0.
328    dec_count: u32,
329    /// `DecRandom` — computed per congestion period (rule 23).
330    dec_random: f64,
331    /// `RECEIVING_RATE`, packets/sec — see the module doc's gap-1 resolution
332    /// (stored verbatim from [`FileCc::on_ack`], not smoothed here).
333    receiving_rate_pps: u64,
334    /// `EST_LINK_CAPACITY`, packets/sec — see the module doc's gap-1
335    /// resolution.
336    est_link_capacity_pps: u64,
337    /// `RTT`, sender-smoothed elsewhere (`crate::arq::rtt::RttEstimator`) and
338    /// fed in via [`FileCc::on_ack`]. Initialized to
339    /// [`crate::arq::rtt::INITIAL_RTT`] before the first ACK.
340    rtt: Duration,
341    /// `MAX_BW`, bytes/sec — Step 6 clamp (rule 15: file transfer only uses
342    /// `MAXBW_SET`; `None` means unbounded, the default for file transfer).
343    max_bw_bytes_per_sec: Option<u64>,
344    rng: XorShift64,
345}
346
347impl FileCc {
348    /// A fresh FileCC engine in Slow Start (rule 4: "runs exactly once at
349    /// the beginning of a connection").
350    ///
351    /// `initial_seqno` seeds `LAST_ACK_SEQNO` (see the field doc) — pass the
352    /// connection's initial sequence number (ISN) minus one, or the ISN
353    /// itself if no data has been sent yet; either way the first ACK's
354    /// `CWND_SIZE` growth (Step 3) reflects exactly the packets actually
355    /// acknowledged since then.
356    pub fn new(initial_seqno: u32) -> Self {
357        FileCc {
358            phase: Phase::SlowStart,
359            cwnd_size: INITIAL_CWND_SIZE,
360            max_cwnd_size: DEFAULT_MAX_CWND_SIZE,
361            pkt_snd_period_us: SLOW_START_PKT_SND_PERIOD_US,
362            last_rc_time: None,
363            last_ack_seqno: initial_seqno,
364            b_loss: false,
365            last_dec_period_us: INITIAL_LAST_DEC_PERIOD_US,
366            last_dec_seq: None,
367            avg_nak_num: 0.0,
368            nak_count: 0,
369            dec_count: 0,
370            dec_random: 1.0,
371            receiving_rate_pps: 0,
372            est_link_capacity_pps: 0,
373            rtt: INITIAL_RTT,
374            max_bw_bytes_per_sec: None,
375            rng: XorShift64::new(XorShift64::DEFAULT_SEED),
376        }
377    }
378
379    /// The current algorithm phase.
380    pub fn phase(&self) -> Phase {
381        self.phase
382    }
383
384    /// The current `CWND_SIZE`, in packets.
385    pub fn cwnd_size(&self) -> f64 {
386        self.cwnd_size
387    }
388
389    /// The current `PKT_SND_PERIOD`, in microseconds (as an `f64` — the
390    /// Congestion Avoidance formulas are inherently fractional).
391    pub fn pkt_snd_period_us(&self) -> f64 {
392        self.pkt_snd_period_us
393    }
394
395    /// The current `MAX_CWND_SIZE` (rule 8), in packets.
396    pub fn max_cwnd_size(&self) -> f64 {
397        self.max_cwnd_size
398    }
399
400    /// Reconfigure `MAX_CWND_SIZE` — rule 8 calls the 12 MB-derived default
401    /// a settable/recommended value, not a hardwired constant.
402    pub fn set_max_cwnd_size(&mut self, packets: f64) {
403        self.max_cwnd_size = packets;
404    }
405
406    /// The current `MAX_BW` clamp, in bytes/sec (`None` = unbounded).
407    pub fn max_bw_bytes_per_sec(&self) -> Option<u64> {
408        self.max_bw_bytes_per_sec
409    }
410
411    /// Reconfigure `MAX_BW` (rule 15: `MAXBW_SET` mode only applies to file
412    /// transfer; there is no default, `None` is unbounded). `Some(0)` would
413    /// make the minimum send period infinite, so it is treated as unbounded.
414    #[cfg(test)]
415    pub(crate) fn set_max_bw_bytes_per_sec(&mut self, max_bw: Option<u64>) {
416        self.max_bw_bytes_per_sec = max_bw.filter(|&bw| bw > 0);
417    }
418
419    /// The last `RECEIVING_RATE` fed via [`FileCc::on_ack`], packets/sec.
420    pub fn receiving_rate_pps(&self) -> u64 {
421        self.receiving_rate_pps
422    }
423
424    /// The last `EST_LINK_CAPACITY` fed via [`FileCc::on_ack`], packets/sec.
425    pub fn est_link_capacity_pps(&self) -> u64 {
426        self.est_link_capacity_pps
427    }
428
429    /// The last `RTT` fed via [`FileCc::on_ack`] (or the initial 100 ms
430    /// default before the first ACK).
431    pub fn rtt(&self) -> Duration {
432        self.rtt
433    }
434
435    /// `bLoss` — `true` if a loss has been reported since the last rate
436    /// increase (rule 11-12).
437    pub fn b_loss(&self) -> bool {
438        self.b_loss
439    }
440
441    /// `AvgNAKNum` — the average number of NAKs per congestion period
442    /// (rule 20's EWMA).
443    pub fn avg_nak_num(&self) -> f64 {
444        self.avg_nak_num
445    }
446
447    /// `NAKCount` — NAKs received so far in the current congestion period.
448    pub fn nak_count(&self) -> u32 {
449        self.nak_count
450    }
451
452    /// `DecCount` — rate decreases applied so far in the current congestion
453    /// period.
454    pub fn dec_count(&self) -> u32 {
455        self.dec_count
456    }
457
458    /// `LastDecSeq` — the largest sent sequence number at the last rate
459    /// decrease / congestion-period boundary, or `None` if no
460    /// Congestion-Avoidance-phase loss has occurred yet.
461    pub fn last_dec_seq(&self) -> Option<u32> {
462        self.last_dec_seq
463    }
464
465    /// `LastDecPeriod`, in microseconds (item under Step 5; initial value 1
466    /// microsecond).
467    pub fn last_dec_period_us(&self) -> f64 {
468        self.last_dec_period_us
469    }
470
471    /// On full-ACK packet reception (`private/specs-verified/rules/srt-congestion.md`,
472    /// §5.2.1.1 "(1) On ACK packet reception" / §5.2.1.2 "(1) On ACK packet
473    /// reception"). Only full ACKs trigger a rate increase (rule 3,
474    /// L3313-3314) — a light ACK must not be passed to this method.
475    ///
476    /// `now` — the current time (Step 1's `currTime`).
477    /// `ack_seqno` — the ACK's acknowledged sequence number (`ACK_SEQNO`).
478    /// `receiving_rate_pps` / `est_link_capacity_pps` — the ACK-carried,
479    /// receiver-reported rate estimates (§5.2.1.3); see the module doc's
480    /// gap-1 resolution for why these are stored verbatim, not smoothed
481    /// here.
482    /// `rtt` — the current (already-smoothed elsewhere) RTT estimate.
483    pub fn on_ack(
484        &mut self,
485        now: Timestamp,
486        ack_seqno: u32,
487        receiving_rate_pps: u64,
488        est_link_capacity_pps: u64,
489        rtt: Duration,
490    ) {
491        self.receiving_rate_pps = receiving_rate_pps;
492        self.est_link_capacity_pps = est_link_capacity_pps;
493        self.rtt = rtt;
494
495        // Step 1 (identical gate in both phases, L3365-3371 / L3455-3461):
496        // if (currTime - LastRCTime < RC_INTERVAL) { keep; stop; }
497        if let Some(last) = self.last_rc_time
498            && now.saturating_sub(last) < RC_INTERVAL
499        {
500            return;
501        }
502        // Step 2: LastRCTime = currTime.
503        self.last_rc_time = Some(now);
504
505        match self.phase {
506            Phase::SlowStart => self.on_ack_slow_start(ack_seqno),
507            Phase::CongestionAvoidance => self.on_ack_congestion_avoidance(),
508        }
509    }
510
511    /// Slow start's ACK handling, Steps 3-5 (L3381-3401).
512    fn on_ack_slow_start(&mut self, ack_seqno: u32) {
513        // Step 3: CWND_SIZE += ACK_SEQNO - LAST_ACK_SEQNO (wrap-safe delta —
514        // reusing arq::seq, not redefined here, per the crate's existing
515        // sequence-arithmetic convention).
516        let delta = seq_diff(ack_seqno, self.last_ack_seqno);
517        self.cwnd_size += f64::from(delta);
518        // Step 4: LAST_ACK_SEQNO = ACK_SEQNO.
519        self.last_ack_seqno = ack_seqno;
520
521        // Step 5: CWND_SIZE exceeding MAX_CWND_SIZE ends slow start.
522        if self.cwnd_size > self.max_cwnd_size {
523            self.end_slow_start();
524        }
525    }
526
527    /// Congestion Avoidance's ACK handling, Steps 3-6 (L3479-3559).
528    fn on_ack_congestion_avoidance(&mut self) {
529        // Step 3: CWND_SIZE = RECEIVING_RATE*(RTT+RC_INTERVAL)/1000000 + 16
530        // (recomputed directly, not incrementally, unlike slow start).
531        self.cwnd_size = self.receiving_rate_pps as f64 * self.rtt_plus_rc_interval_us()
532            / US_PER_SEC
533            + INITIAL_CWND_SIZE;
534
535        // Step 4: loss-in-flight guard.
536        if self.b_loss {
537            self.b_loss = false;
538            return;
539        }
540
541        // Step 5: rate-increase formula (L3498-3517, verbatim).
542        let loss_bandwidth = LOSS_BANDWIDTH_FACTOR * (US_PER_SEC / self.last_dec_period_us);
543        let link_capacity = fmin(loss_bandwidth, self.est_link_capacity_pps as f64);
544        let mut b = link_capacity - US_PER_SEC / self.pkt_snd_period_us;
545        if self.pkt_snd_period_us > self.last_dec_period_us
546            && (link_capacity / LINK_CAPACITY_CLAMP_DIVISOR) < b
547        {
548            b = link_capacity / LINK_CAPACITY_CLAMP_DIVISOR;
549        }
550        let inc = if b <= 0.0 {
551            1.0 / S_BYTES
552        } else {
553            let raw = next_power_of_10(b * S_BYTES * BITS_PER_BYTE) * INC_SCALE / S_BYTES;
554            fmax(raw, 1.0 / S_BYTES)
555        };
556        let rc_interval_us = RC_INTERVAL.as_micros() as f64;
557        self.pkt_snd_period_us = (self.pkt_snd_period_us * rc_interval_us)
558            / (self.pkt_snd_period_us * inc + rc_interval_us);
559
560        // Step 6: MAX_BW clamp, if configured (rule 15).
561        if let Some(max_bw) = self.max_bw_bytes_per_sec {
562            let min_period_us = US_PER_SEC / (max_bw as f64 / S_BYTES);
563            if self.pkt_snd_period_us < min_period_us {
564                self.pkt_snd_period_us = min_period_us;
565            }
566        }
567    }
568
569    /// `RTT + RC_INTERVAL`, in microseconds — shared by the CWND_SIZE
570    /// formula (Step 3, both event handlers that use it).
571    fn rtt_plus_rc_interval_us(&self) -> f64 {
572        self.rtt.as_micros() as f64 + RC_INTERVAL.as_micros() as f64
573    }
574
575    /// Ends slow start, computing `PKT_SND_PERIOD` per the shared Step 5
576    /// formula (L3392-3401, reused verbatim by rules 9 and 10 — NAK and RTO
577    /// during slow start).
578    fn end_slow_start(&mut self) {
579        self.phase = Phase::CongestionAvoidance;
580        self.pkt_snd_period_us = if self.receiving_rate_pps > 0 {
581            US_PER_SEC / self.receiving_rate_pps as f64
582        } else {
583            self.cwnd_size / self.rtt_plus_rc_interval_us()
584        };
585    }
586
587    /// On a loss report (NAK) packet reception.
588    ///
589    /// - During Slow Start (rule 9): ends slow start; `PKT_SND_PERIOD` is
590    ///   set exactly as in the ACK Step 5 formula. `lost_seqno`,
591    ///   `largest_sent_seqno`, and `loss_ratio` are not consulted by this
592    ///   phase's handling (the draft's rule 9 gives no further formula).
593    /// - During Congestion Avoidance (§5.2.1.2 "(2)", L3568-3658): runs the
594    ///   full bLoss/loss-ratio-tolerance/congestion-period/repeat-decrease
595    ///   state machine.
596    ///
597    /// `lost_seqno` — the sequence number reported lost by this NAK.
598    /// `largest_sent_seqno` — the largest sequence number sent so far
599    /// (recorded as the new `LastDecSeq` on a decrease, rules 22/29).
600    /// `loss_ratio` — the sender's current estimated loss ratio (rule 16's
601    /// "less than 2%" tolerance check), e.g. lost/sent over a recent window.
602    pub fn on_loss(&mut self, lost_seqno: u32, largest_sent_seqno: u32, loss_ratio: f64) {
603        match self.phase {
604            Phase::SlowStart => self.end_slow_start(),
605            Phase::CongestionAvoidance => {
606                self.on_loss_congestion_avoidance(lost_seqno, largest_sent_seqno, loss_ratio)
607            }
608        }
609    }
610
611    /// Congestion Avoidance's NAK handling (L3568-3658).
612    fn on_loss_congestion_avoidance(
613        &mut self,
614        lost_seqno: u32,
615        largest_sent_seqno: u32,
616        loss_ratio: f64,
617    ) {
618        // Step 1: bLoss = True.
619        self.b_loss = true;
620
621        // Step 2: loss-ratio tolerance (rule 16-17).
622        if loss_ratio < LOSS_RATIO_TOLERANCE {
623            self.last_dec_period_us = self.pkt_snd_period_us;
624            return;
625        }
626
627        // Step 3: new congestion period? (rule 25: the lost seq is greater
628        // than LastDecSeq).
629        let is_new_period = match self.last_dec_seq {
630            None => true,
631            Some(last) => seq_gt(lost_seqno, last),
632        };
633
634        if is_new_period {
635            self.last_dec_period_us = self.pkt_snd_period_us;
636            self.pkt_snd_period_us *= RATE_BACKOFF_FACTOR;
637            // rule 20: AvgNAKNum = 0.97*AvgNAKNum + 0.03*NAKCount (using the
638            // just-finished period's NAKCount, before it is reset below).
639            self.avg_nak_num = AVG_NAK_NUM_OLD_WEIGHT * self.avg_nak_num
640                + AVG_NAK_NUM_NEW_WEIGHT * self.nak_count as f64;
641            self.nak_count = 1;
642            self.dec_count = 1;
643            self.last_dec_seq = Some(largest_sent_seqno);
644            self.dec_random = self.next_dec_random();
645            return;
646        }
647
648        // Step 4: repeat decrease within the same congestion period
649        // (rule "Step 4": DecCount<=5 && NAKCount==DecCount*DecRandom).
650        if self.dec_count <= MAX_DEC_COUNT
651            && self.nak_count as f64 == self.dec_count as f64 * self.dec_random
652        {
653            self.pkt_snd_period_us *= RATE_BACKOFF_FACTOR;
654            self.dec_count += 1;
655            self.nak_count += 1;
656            self.last_dec_seq = Some(largest_sent_seqno);
657        }
658    }
659
660    /// `DecRandom` — "a random number between 1 and the average number of
661    /// NAKs per congestion period (AvgNAKNum)", clamped to 1 if the draw is
662    /// below 1 (rule 23). See the module doc for the PRNG source note.
663    ///
664    /// Rounded to the nearest whole number: Step 4's repeat-decrease gate
665    /// (`NAKCount == DecCount * DecRandom`) compares against the integer
666    /// counters `NAKCount`/`DecCount`, so it only means "every `DecRandom`-th
667    /// NAK" — and is satisfiable — when `DecRandom` is itself integer-valued.
668    /// A raw fractional draw (`AvgNAKNum > 1`) makes that equality a
669    /// measure-zero float comparison that (almost) never holds again after
670    /// the congestion period's first decrease, silently disabling repeat
671    /// decrease for the rest of the period.
672    fn next_dec_random(&mut self) -> f64 {
673        let hi = fmax(self.avg_nak_num, 1.0);
674        let r = self.rng.next_unit();
675        let val = fround(1.0 + r * (hi - 1.0));
676        fmax(val, 1.0)
677    }
678
679    /// On a retransmission timeout (RTO) event.
680    ///
681    /// During Slow Start (rule 10): ends slow start, `PKT_SND_PERIOD` set
682    /// exactly as in the ACK Step 5 formula (same as [`FileCc::on_loss`]'s
683    /// slow-start handling). Once in Congestion Avoidance, this section does
684    /// not describe an RTO-specific FileCC reaction (RTO-driven
685    /// retransmission itself is the ARQ engine's concern, `srt-arq.md`) —
686    /// calling this while already in Congestion Avoidance is a no-op.
687    pub fn on_timeout(&mut self) {
688        if self.phase == Phase::SlowStart {
689            self.end_slow_start();
690        }
691    }
692}
693
694impl Default for FileCc {
695    /// A fresh engine with `initial_seqno = 0` (see [`FileCc::new`]).
696    fn default() -> Self {
697        FileCc::new(0)
698    }
699}
700
701#[cfg(test)]
702mod tests {
703    use super::*;
704
705    #[test]
706    fn starts_in_slow_start_with_spec_initial_values() {
707        let cc = FileCc::new(0);
708        assert_eq!(cc.phase(), Phase::SlowStart);
709        assert_eq!(cc.cwnd_size(), 16.0);
710        assert_eq!(cc.pkt_snd_period_us(), 1.0);
711        assert_eq!(cc.max_cwnd_size(), 8_000.0);
712        assert!(!cc.b_loss());
713        assert_eq!(cc.avg_nak_num(), 0.0);
714        assert_eq!(cc.nak_count(), 0);
715        assert_eq!(cc.dec_count(), 0);
716        assert_eq!(cc.last_dec_seq(), None);
717        assert_eq!(cc.last_dec_period_us(), 1.0);
718        assert_eq!(cc.rtt(), Duration::from_millis(100));
719        assert_eq!(cc.max_bw_bytes_per_sec(), None);
720    }
721
722    #[test]
723    fn slow_start_cwnd_grows_by_ack_seqno_delta() {
724        let mut cc = FileCc::new(0);
725        cc.on_ack(
726            Timestamp::from_millis(10),
727            5,
728            0,
729            0,
730            Duration::from_millis(100),
731        );
732        assert_eq!(cc.cwnd_size(), 21.0); // 16 + (5 - 0)
733        assert_eq!(
734            cc.pkt_snd_period_us(),
735            1.0,
736            "fixed at 1us during slow start"
737        );
738    }
739
740    #[test]
741    fn rate_control_gate_blocks_updates_within_rc_interval() {
742        let mut cc = FileCc::new(0);
743        cc.on_ack(
744            Timestamp::from_millis(10),
745            5,
746            0,
747            0,
748            Duration::from_millis(100),
749        );
750        assert_eq!(cc.cwnd_size(), 21.0);
751        // Only 1ms later (< RC_INTERVAL = 10ms): must be a no-op.
752        cc.on_ack(
753            Timestamp::from_millis(11),
754            999,
755            0,
756            0,
757            Duration::from_millis(100),
758        );
759        assert_eq!(
760            cc.cwnd_size(),
761            21.0,
762            "gate must block an ACK inside RC_INTERVAL"
763        );
764    }
765
766    #[test]
767    fn loss_during_slow_start_transitions_to_congestion_avoidance() {
768        let mut cc = FileCc::new(0);
769        assert_eq!(cc.phase(), Phase::SlowStart);
770        cc.on_loss(10, 10, 0.9);
771        assert_eq!(cc.phase(), Phase::CongestionAvoidance);
772    }
773
774    #[test]
775    fn timeout_during_slow_start_transitions_to_congestion_avoidance() {
776        let mut cc = FileCc::new(0);
777        cc.on_timeout();
778        assert_eq!(cc.phase(), Phase::CongestionAvoidance);
779    }
780
781    #[test]
782    fn timeout_during_congestion_avoidance_is_a_no_op() {
783        let mut cc = FileCc::new(0);
784        cc.on_loss(10, 10, 0.9);
785        assert_eq!(cc.phase(), Phase::CongestionAvoidance);
786        let period = cc.pkt_snd_period_us();
787        cc.on_timeout();
788        assert_eq!(cc.pkt_snd_period_us(), period);
789    }
790
791    #[test]
792    fn cwnd_exceeding_max_ends_slow_start() {
793        let mut cc = FileCc::new(0);
794        cc.set_max_cwnd_size(20.0);
795        cc.on_ack(
796            Timestamp::from_millis(10),
797            10,
798            0,
799            0,
800            Duration::from_millis(100),
801        );
802        // CWND = 16 + 10 = 26 > 20 -> slow start ends.
803        assert_eq!(cc.phase(), Phase::CongestionAvoidance);
804    }
805
806    #[test]
807    fn max_bw_clamp_floors_pkt_snd_period() {
808        let mut cc = FileCc::new(0);
809        cc.on_loss(1, 1, 0.9); // -> Congestion Avoidance
810        cc.set_max_bw_bytes_per_sec(Some(1)); // absurdly low MAX_BW
811        cc.on_ack(
812            Timestamp::from_millis(10),
813            1,
814            1_000,
815            1_000,
816            Duration::from_millis(50),
817        );
818        // MIN_PERIOD = 1_000_000 / (1 / 1500) = 1_500_000_000 us.
819        assert!(cc.pkt_snd_period_us() >= 1_500_000_000.0);
820    }
821
822    #[test]
823    fn zero_max_bw_is_unbounded_not_an_infinite_send_period() {
824        let mut cc = FileCc::new(0);
825        cc.on_loss(1, 1, 0.9);
826        cc.set_max_bw_bytes_per_sec(Some(0));
827        assert_eq!(cc.max_bw_bytes_per_sec(), None);
828        cc.on_ack(
829            Timestamp::from_millis(10),
830            1,
831            1_000,
832            1_000,
833            Duration::from_millis(50),
834        );
835        assert!(cc.pkt_snd_period_us().is_finite());
836    }
837
838    #[test]
839    fn next_power_of_10_matches_known_values() {
840        assert_eq!(next_power_of_10(1.0), 1.0);
841        assert_eq!(next_power_of_10(9.9), 10.0);
842        assert_eq!(next_power_of_10(10.0), 10.0);
843        assert_eq!(next_power_of_10(10.1), 100.0);
844        assert_eq!(next_power_of_10(100.0), 100.0);
845        assert_eq!(next_power_of_10(0.05), 0.1);
846    }
847
848    #[test]
849    fn xorshift_produces_values_in_unit_range() {
850        let mut rng = XorShift64::new(1);
851        for _ in 0..100 {
852            let v = rng.next_unit();
853            assert!((0.0..1.0).contains(&v), "value out of range: {v}");
854        }
855    }
856
857    #[test]
858    fn dec_random_is_one_when_avg_nak_num_is_zero() {
859        let mut cc = FileCc::new(0);
860        assert_eq!(cc.avg_nak_num(), 0.0);
861        assert_eq!(cc.next_dec_random(), 1.0);
862    }
863
864    /// `DecRandom` must be integer-valued once `AvgNAKNum > 1` (a fractional
865    /// draw makes Step 4's `NAKCount == DecCount * DecRandom` gate a
866    /// measure-zero float comparison that — after the congestion period's
867    /// first decrease — essentially never holds again, silently disabling
868    /// repeat decrease for the rest of the period). This is the bug a
869    /// pre-tag audit found: the un-rounded draw only ever produced an
870    /// integer in the degenerate `AvgNAKNum <= 1` case, which is the only
871    /// case the pre-existing test suite exercised.
872    #[test]
873    fn dec_random_is_integer_valued_once_avg_nak_num_exceeds_one() {
874        let mut cc = FileCc::new(0);
875        cc.avg_nak_num = 6.0;
876        for _ in 0..200 {
877            let v = cc.next_dec_random();
878            assert_eq!(
879                v,
880                v.round(),
881                "DecRandom must be a whole number (got {v}) so Step 4's \
882                 NAKCount == DecCount * DecRandom gate is actually satisfiable"
883            );
884            assert!((1.0..=6.0).contains(&v), "DecRandom out of range: {v}");
885        }
886    }
887
888    /// Documents a genuine quirk of the draft's own literal Step 4
889    /// pseudocode (verified against `private/specs-verified/rules/srt-congestion.md`, not
890    /// assumed): `NAKCount`/`DecCount` are reset to 1 on a new congestion
891    /// period and are ONLY ever touched again *inside* Step 4's own
892    /// `NAKCount == DecCount * DecRandom` conditional (rule 28: "Increase
893    /// DecCount and NAKCount each by 1" — inside the `if`, not unconditional
894    /// per-NAK). So the very next same-period NAK checks `1 == 1*DecRandom`;
895    /// if `DecRandom != 1` that fails, and since neither counter has moved,
896    /// the SAME false check repeats for every subsequent NAK in the period —
897    /// Step 4 cannot fire again until the next congestion period redraws
898    /// `DecRandom`. This is a property of the literal spec text as
899    /// transcribed, not a Rust-side bug: the reference implementation
900    /// (libsrt `congctl.cpp`) uses a different formulation (`NAKCount %
901    /// DecRandom == 0`, incrementing both counters on every same-period NAK
902    /// regardless of the check's outcome) that does NOT have this one-shot
903    /// property — but adopting that would be a spec-posture departure this
904    /// crate isn't designated for (see `CLAUDE.md`), so this implementation
905    /// stays literal to the curated draft text. Confirmed here with a fixed
906    /// `dec_random` (bypassing the RNG) so the assertion is deterministic.
907    #[test]
908    fn repeat_decrease_is_a_one_shot_per_period_once_dec_random_exceeds_one() {
909        let mut cc = FileCc::new(0);
910        cc.on_loss(10, 10, 0.9); // end slow start
911        cc.on_loss(20, 20, 0.9); // new congestion period, big decrease
912        assert_eq!(cc.dec_count(), 1);
913
914        // Force a specific integer DecRandom > 1 for this period (bypassing
915        // the RNG so the check below is deterministic, not seed-dependent).
916        cc.dec_random = 3.0;
917        let after_first = cc.pkt_snd_period_us();
918
919        // Many same-period NAKs: per the literal spec pseudocode, NONE of
920        // them can fire Step 4 again, because NAKCount/DecCount are frozen
921        // at (1, 1) and 1 == 1*3 is false — and stays false forever, since
922        // nothing outside Step 4's own conditional advances either counter.
923        for sent in 21..=60u32 {
924            cc.on_loss(15, sent, 0.9);
925        }
926
927        assert_eq!(
928            cc.dec_count(),
929            1,
930            "with the literal spec's Step 4 pseudocode, DecCount must stay \
931             frozen at 1 for the rest of the period once the immediate \
932             post-reset check (NAKCount==DecCount*DecRandom, i.e. 1==1*3) \
933             fails — this is the draft's own one-shot property, not a bug"
934        );
935        assert_eq!(
936            cc.pkt_snd_period_us(),
937            after_first,
938            "PKT_SND_PERIOD must not change further once Step 4 has gone \
939             silent for the rest of the period"
940        );
941    }
942
943    /// The complementary, working case: when the drawn integer `DecRandom`
944    /// rounds to exactly `1`, the immediate post-reset check `1 == 1*1`
945    /// holds, so Step 4 fires on every subsequent same-period NAK (this is
946    /// the case the pre-existing integration test
947    /// `repeated_decrease_backs_off_by_1_03_bounded_by_dec_count` already
948    /// covers end-to-end with `AvgNAKNum == 0`; this unit test additionally
949    /// proves it holds even when `AvgNAKNum` is nonzero but rounds to 1).
950    #[test]
951    fn repeat_decrease_fires_repeatedly_when_dec_random_rounds_to_one() {
952        let mut cc = FileCc::new(0);
953        cc.avg_nak_num = 1.2; // rounds to 1 via next_dec_random's `.round()`
954        cc.on_loss(10, 10, 0.9);
955        cc.on_loss(20, 20, 0.9);
956        assert_eq!(cc.dec_random, 1.0);
957        assert_eq!(cc.dec_count(), 1);
958
959        for sent in 21..=25u32 {
960            cc.on_loss(15, sent, 0.9);
961        }
962        assert_eq!(
963            cc.dec_count(),
964            6,
965            "DecRandom==1 must let Step 4 fire on every same-period NAK"
966        );
967    }
968
969    #[test]
970    fn default_matches_new_zero() {
971        let a = FileCc::default();
972        let b = FileCc::new(0);
973        assert_eq!(a.cwnd_size(), b.cwnd_size());
974        assert_eq!(a.phase(), b.phase());
975    }
976}