Skip to main content

srt_runtime/arq/
mod.rs

1//! SRT ARQ (Automatic Repeat reQuest) reliability engine —
2//! `draft-sharabayko-srt-01` §4.8 (Acknowledgement and Lost Packet
3//! Handling), §4.8.1 (Packet Acknowledgement — ACKs, ACKACKs), §4.8.2
4//! (Packet Retransmission — NAKs), §4.10 (Round-Trip Time Estimation).
5//! Curated behavioural rules: `private/specs-verified/rules/srt-arq.md`. The wire field
6//! layouts this module drives (ACK/NAK/ACKACK) are the existing
7//! [`crate::packet`] codecs — this module never re-encodes them, it only
8//! decides *when* to build one and *what* to do with one received.
9//!
10//! Sans-IO, like the rest of this crate: [`Sender`] and [`Receiver`] never
11//! read a wall clock. All timing is driven by a caller-supplied
12//! `now: broadcast_core::stage::Instant` (monotonic time since a fixed
13//! epoch the caller owns) passed to `tick`/`feed_data`/`on_data`/`on_ack`/`on_ackack`.
14//!
15//! # Module map
16//! - [`seq`] — wrap-safe 31-bit sequence-number arithmetic (not itself a
17//!   `srt-arq.md` rule — the draft does not specify a comparison algorithm;
18//!   see the module doc there for the resolution).
19//! - [`rtt::RttEstimator`] — the rule 29-31 RTT/RTTVar EWMA, shared by both
20//!   roles (rule 34: a socket's RTT state is really one estimator usable by
21//!   both a sender and a receiver path).
22//! - [`Sender`] — send buffer, NAK-driven retransmit queue, ACK/ACKACK
23//!   handling (rules 1, 3, 5, 7-10, 15-18, 23-24, 33).
24//! - [`Receiver`] — loss detection, Full/Light ACK generation, periodic NAK,
25//!   ACKACK-driven RTT measurement (rules 4, 8, 11-14, 21-22, 26-30, 32).
26//!
27//! # Non-goals (explicit follow-ups, not curated as ARQ rules here)
28//! - Deciding *when* to apply the TLPKTDROP fake-ACK skip (rule 13) is
29//!   `srt-tsbpd.md` scope: the receiver can skip a range, the integration layer
30//!   (the tokio adapter) decides when, and only if TLPKTDROP was negotiated.
31//! - RTO-based periodic retransmission without a NAK / congestion control
32//!   (§5, FileCC) — srt-arq.md is explicit that the RTO formula is
33//!   congestion-control scope, not curated there.
34//! - Send-queue overflow / unsent-packet drop sizing (rules 19-20) — the
35//!   latency-window math is §4.4/§4.5 scope.
36
37mod receiver;
38pub mod rtt;
39mod sender;
40pub mod seq;
41
42pub use receiver::{FeedOutcome, Receiver, ReceiverBounds};
43pub use rtt::RttEstimator;
44pub use sender::{Sender, SenderBounds};
45
46/// Both ARQ halves' bounds, as a link takes them.
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub struct ArqBounds {
49    /// The receiving half's bounds.
50    pub receiver: ReceiverBounds,
51    /// The sending half's bounds.
52    pub sender: SenderBounds,
53}
54
55impl ArqBounds {
56    /// Refuse a bound that cannot work: a window, skip list or ACK table of zero
57    /// tracks nothing, a NAK that may mark no packet disables retransmission, and a
58    /// pacing burst of zero never sends. A zero
59    /// [`SenderBounds::min_retransmit_interval`] is allowed and means no floor.
60    ///
61    /// # Errors
62    ///
63    /// [`crate::Error::InvalidConfig`] naming the field.
64    pub fn validate(&self) -> crate::Result<()> {
65        let rule = "must be at least 1";
66        if self.receiver.max_tracked_window == 0 {
67            return Err(crate::Error::invalid_config(
68                "receiver.max_tracked_window",
69                rule,
70            ));
71        }
72        if self.receiver.max_pending_skips == 0 {
73            return Err(crate::Error::invalid_config(
74                "receiver.max_pending_skips",
75                rule,
76            ));
77        }
78        if self.receiver.max_outstanding_acks == 0 {
79            return Err(crate::Error::invalid_config(
80                "receiver.max_outstanding_acks",
81                rule,
82            ));
83        }
84        if self.sender.max_nak_seqs_per_packet == 0 {
85            return Err(crate::Error::invalid_config(
86                "sender.max_nak_seqs_per_packet",
87                rule,
88            ));
89        }
90        if self.sender.pacing_burst_packets == 0 {
91            return Err(crate::Error::invalid_config(
92                "sender.pacing_burst_packets",
93                rule,
94            ));
95        }
96        Ok(())
97    }
98}
99
100use crate::packet::number::SrtTimestamp;
101use broadcast_core::stage::Instant;
102use core::time::Duration;
103
104/// Full ACK timer period — 10 milliseconds (`private/specs-verified/rules/srt-arq.md` rule
105/// 11, quoting `draft-sharabayko-srt-01` L2874-2876: "the ACK period or
106/// synchronization time interval SYN").
107pub const FULL_ACK_PERIOD: Duration = Duration::from_millis(10);
108
109/// Light-ACK packet-count threshold — 64 packets (`private/specs-verified/rules/srt-arq.md`
110/// rule 12, L2877-2883): if this many packets have been sent/received
111/// within the Full ACK period, the receiver sends a Light ACK early.
112pub const LIGHT_ACK_THRESHOLD: u32 = 64;
113
114/// `NAKInterval` floor — 20 milliseconds (`private/specs-verified/rules/srt-arq.md` rule 22,
115/// L2953-2960 / L3276): `NAKInterval = max((RTT + 4*RTTVar) / 2, 20ms)`.
116pub const NAK_INTERVAL_FLOOR: Duration = Duration::from_millis(20);
117
118/// Convert a [`Duration`] to the wire `Instant` field's microsecond
119/// `u32` (`draft-sharabayko-srt-01` §3: "microseconds elapsed since the SRT
120/// connection was established"), **wrapping** modulo `2^32` once `d` exceeds
121/// `u32::MAX` microseconds (about 71.58 minutes) since the caller's epoch —
122/// not clamping to `u32::MAX`.
123///
124/// A clamp (this function's pre-#1063 behavior) makes every packet sent
125/// after that point carry the *same* fixed timestamp forever, instead of one
126/// that keeps counting up (mod 2^32) the way the field is defined. A real
127/// peer's `PktTsbpdTime` formula (`TsbpdTimeBase + PKT_TIMESTAMP + ...`,
128/// `private/specs-verified/rules/srt-tsbpd.md` rule 9) would then compute the same constant
129/// play time for every such packet — which the peer's receiver clock keeps
130/// advancing past, so every packet after the clamp point looks
131/// arbitrarily-far too late and gets Too-Late-Packet-Dropped. The receiving
132/// side of the same problem — correctly *un*wrapping a peer's wrapped
133/// timestamp back into an always-increasing value for `PktTsbpdTime`
134/// purposes — is `crate::tsbpd::TsbpdScheduler`'s `unwrap_timestamp`, not
135/// this function (this one only ever produces an in-range wire value; it
136/// does not need to remember any wrap-count itself, so plain truncation of
137/// the microsecond count into 32 bits is exactly "mod 2^32").
138pub(crate) fn duration_to_wire_us(d: Duration) -> u32 {
139    // Keep exactly the low 32 bits: the wire field is "microseconds mod 2^32".
140    u32::try_from(d.as_micros() & u128::from(u32::MAX)).unwrap_or(0)
141}
142
143/// Convert a [`Instant`] to the wire `Instant` field's microsecond `u32`
144/// (`draft-sharabayko-srt-01` §3), wrapping modulo `2^32` once the
145/// microsecond count exceeds `u32::MAX` (about 71.58 minutes) since the
146/// caller's epoch — not clamping to `u32::MAX`. See
147/// [`duration_to_wire_us`] for why a clamp (instead of a wrap) stalls a real
148/// peer's Too-Late-Packet-Drop.
149pub(crate) fn timestamp_to_wire_us(ts: Instant) -> SrtTimestamp {
150    // Keep exactly the low 32 bits: the wire field is "microseconds mod 2^32".
151    SrtTimestamp::from_wire(u32::try_from(ts.as_micros() & u64::from(u32::MAX)).unwrap_or(0))
152}
153
154/// `NAKInterval = max((RTT + 4 * RTTVar) / 2, 20 ms)` (`private/specs-verified/rules/srt-arq.md`
155/// rule 22, verbatim from `draft-sharabayko-srt-01` L2953-2960, unit
156/// resolution cross-referenced from §5.2's L3276 restatement).
157/// Weight of `RTTVar` in the NAK interval, and the divisor of the sum.
158const RTT_VAR_WEIGHT: u32 = 4;
159const NAK_INTERVAL_DIVISOR: u32 = 2;
160
161pub(crate) fn nak_interval(rtt: Duration, rtt_var: Duration) -> Duration {
162    let sum = rtt + rtt_var * RTT_VAR_WEIGHT;
163    let half = sum / NAK_INTERVAL_DIVISOR;
164    if half < NAK_INTERVAL_FLOOR {
165        NAK_INTERVAL_FLOOR
166    } else {
167        half
168    }
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174
175    /// `timestamp_to_wire_us` keeps exactly the low 32 bits, so a `Instant`
176    /// past `u32::MAX` microseconds (about 71.58 minutes) wraps the way the
177    /// §3 wire field defines — it never clamps (a clamp would freeze every
178    /// later packet's timestamp and Too-Late-Packet-Drop a real peer).
179    #[test]
180    fn timestamp_to_wire_us_wraps_mod_2_32() {
181        assert_eq!(
182            timestamp_to_wire_us(Instant::from_micros(0)),
183            SrtTimestamp::ZERO
184        );
185        assert_eq!(
186            timestamp_to_wire_us(Instant::from_micros(1_000)),
187            SrtTimestamp::from_wire(1_000)
188        );
189        assert_eq!(
190            timestamp_to_wire_us(Instant::from_micros(u64::from(u32::MAX))),
191            SrtTimestamp::from_wire(u32::MAX)
192        );
193        assert_eq!(
194            timestamp_to_wire_us(Instant::from_micros(u64::from(u32::MAX) + 1)),
195            SrtTimestamp::ZERO,
196            "the wrap is modulo 2^32, not a clamp"
197        );
198    }
199
200    /// `NAKInterval = max((RTT + 4*RTTVar) / 2, 20 ms)` (rule 22, L2953-2960).
201    #[test]
202    fn nak_interval_follows_the_rule_22_formula() {
203        assert_eq!(
204            nak_interval(Duration::from_millis(100), Duration::from_millis(25)),
205            Duration::from_millis(100),
206            "(100 + 4*25) / 2 = 100"
207        );
208        assert_eq!(
209            nak_interval(Duration::from_millis(10), Duration::from_millis(2)),
210            Duration::from_millis(20),
211            "(10 + 4*2) / 2 = 9 is below the 20 ms floor"
212        );
213        assert_eq!(
214            nak_interval(Duration::from_millis(40), Duration::ZERO),
215            Duration::from_millis(20),
216            "40 / 2 = 20 is exactly the floor"
217        );
218        assert_eq!(
219            nak_interval(Duration::from_millis(50), Duration::ZERO),
220            Duration::from_millis(25),
221            "above the floor the halved sum is used as-is"
222        );
223    }
224}