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