Skip to main content

srt_runtime/arq/
receiver.rs

1//! ARQ receiver-side reliability state — `draft-sharabayko-srt-01` §4.8.1
2//! (Full/Light ACK generation), §4.8.2 (loss detection + NAK), §4.10 (RTT
3//! measurement via the ACK/ACKACK round trip). Curated rules:
4//! `private/specs-verified/rules/srt-arq.md`.
5//!
6//! Sans-IO: [`Receiver`] never reads a wall clock — [`Receiver::feed_data`]
7//! and [`Receiver::tick`] take a caller-supplied
8//! `now: broadcast_common::stage::Timestamp` (monotonic time since a fixed
9//! epoch the caller owns).
10//!
11//! # Delivery model
12//! [`FeedOutcome::delivered`] lists the sequence numbers that became
13//! cumulatively in-order-deliverable as a result of one `feed_data` call —
14//! i.e. the ARQ engine's view of "no longer missing" (rule 8's ack point),
15//! not a TSBPD-timed playout (that delay is `srt-tsbpd.md` scope, a
16//! separate follow-up).
17//!
18//! # TLPKTDROP fake ACK
19//! The receiver advances its ack point past packets the delivery side gave up
20//! on only when told to (the crate-internal skip the tokio adapter calls when
21//! the TSBPD scheduler reports a drop, rule 13); it never skips a gap on its
22//! own, so without that call it keeps NAKing and never acknowledges what it
23//! has not received.
24
25use alloc::collections::{BTreeMap, BTreeSet};
26use alloc::vec::Vec;
27use broadcast_common::stage::Timestamp;
28use core::time::Duration;
29
30use crate::packet::number::{AckNumber, SeqNo, SocketId, SrtTimestamp};
31use crate::packet::{AckAckPacket, AckCif, AckPacket, ControlPacket, LossListEntry, NakPacket};
32
33use super::rtt::RttEstimator;
34use super::{FULL_ACK_PERIOD, LIGHT_ACK_THRESHOLD, nak_interval, seq, timestamp_to_wire_us};
35
36/// The most sequence numbers ahead of the cumulative ack point this receiver
37/// will ever track (a bound on `loss_list` + `out_of_order`, which together
38/// can never name more sequence numbers than the window spans). The
39/// effective bound is the negotiated Maximum Flow Window Size
40/// (`draft-sharabayko-srt-01` §3.2.1 — a packet further ahead than the window
41/// cannot be buffered by the peer's own flow control either), clamped to this
42/// value so a hostile or misconfigured window cannot turn one packet into
43/// unbounded work. Not a `private/specs-verified/rules/srt-arq.md` rule — an implementation
44/// bound (about ten times libsrt's default 25 600-packet flow window).
45const MAX_TRACKED_WINDOW: u32 = 1 << 18;
46
47/// Most DROPREQ ranges held ahead of the ack point at once.
48const MAX_PENDING_SKIPS: usize = 1024;
49
50/// IPv4 (20 B) + UDP (8 B) header bytes inside one MTU-sized datagram — what
51/// the handshake's `MTU` field (§3.2.1, "Maximum Transmission Unit Size")
52/// counts but a NAK's Control Information Field cannot use.
53const IP_UDP_HEADER_LEN: usize = 28;
54
55/// Encoded size of one loss-list entry: a single sequence number is one
56/// 32-bit word, a range is two (Appendix A, Figures 21/22).
57const LOSS_ENTRY_SINGLE_LEN: usize = 4;
58const LOSS_ENTRY_RANGE_LEN: usize = 8;
59
60/// Default MTU assumed for NAK sizing until [`Receiver::with_mtu`] sets the
61/// negotiated value (the handshake's default `MTU`, 1500 B).
62const DEFAULT_MTU: u32 = 1500;
63
64/// How many multiples of the round-trip time a Full ACK waits for its ACKACK
65/// before the entry is forgotten (the ACKACK was lost, or the peer never
66/// sends one). Implementation-defined — `srt-arq.md` rules 26-28 do not say
67/// when to give up.
68const ACK_RETENTION_RTTS: u32 = 4;
69
70/// Floor on the time an outstanding Full ACK is retained, so a very low RTT
71/// estimate cannot expire an ACKACK that is merely queued.
72const ACK_RETENTION_FLOOR: Duration = Duration::from_secs(1);
73
74/// Hard cap on outstanding Full ACKs awaiting an ACKACK, however long the
75/// retention (at one Full ACK per 10 ms this is ten seconds' worth).
76const MAX_OUTSTANDING_ACKS: usize = 1024;
77
78/// Outcome of one [`Receiver::feed_data`] call.
79#[derive(Debug, Clone, PartialEq, Eq, Default)]
80#[non_exhaustive]
81pub struct FeedOutcome {
82    /// Sequence numbers that became cumulatively in-order-deliverable as a
83    /// result of this packet's arrival — includes `seq` itself when it was
84    /// the next-expected packet, plus any previously-buffered out-of-order
85    /// packets it consequently unblocked.
86    pub delivered: Vec<u32>,
87    /// An immediate NAK to send, if this packet's arrival revealed a new
88    /// gap (`private/specs-verified/rules/srt-arq.md` rules 4, 14).
89    pub nak: Option<Vec<u8>>,
90    /// The packet was not a 31-bit sequence number (§3.1), or was further
91    /// ahead of the cumulative ack point than the flow window allows, and was
92    /// ignored entirely (not recorded, not
93    /// NAKed): accepting it would let one crafted datagram inflate the loss
94    /// list. The caller must not stage or deliver it.
95    pub out_of_window: bool,
96}
97
98/// ARQ receiver-side state (`draft-sharabayko-srt-01` §4.8.1/§4.8.2/§4.10).
99#[derive(Debug)]
100pub struct Receiver {
101    dest_socket_id: u32,
102    /// Cumulative ack point: every seq strictly before this has been
103    /// delivered in order (rule 8).
104    next_expected: u32,
105    /// Received but not yet in-order-deliverable (a gap remains below it).
106    out_of_order: BTreeSet<u32>,
107    /// Sequence numbers currently believed lost (rules 4, 14, 21).
108    loss_list: BTreeSet<u32>,
109    /// DROPREQ ranges (§3.2.9) still ahead of the ack point, as inclusive
110    /// `(first, last)` pairs; the ack point jumps each one on arrival.
111    pending_skips: Vec<(u32, u32)>,
112    /// The highest sequence number ever received, to detect newly-opened
113    /// gaps (bookkeeping, not itself a spec-named field).
114    highest_received: Option<u32>,
115    /// Packets received since the last ACK of either kind (rule 12).
116    packets_since_ack: u32,
117    /// Absolute time the last Full ACK was sent (rule 11).
118    last_full_ack_at: Timestamp,
119    /// Absolute time the last periodic NAK was sent (rule 22).
120    last_nak_at: Timestamp,
121    /// Next Full ACK's Acknowledgement Number ("starting from 1", §3.2.4).
122    next_ack_number: u32,
123    /// Outstanding Full ACKs awaiting their ACKACK, send-time keyed by
124    /// Acknowledgement Number (rules 24, 26-28).
125    outstanding_acks: BTreeMap<u32, Timestamp>,
126    rtt: RttEstimator,
127    /// The Full ACK's "Available Buffer Size" (packets) — the negotiated
128    /// Maximum Flow Window Size (§3.2.1), the most this receiver will ever
129    /// have staged ahead of its delivery cursor (`Driver::ingress`'s flow-
130    /// window overflow guard enforces that cap independently, so this is
131    /// never an overstatement). A real libsrt sender's own flow control
132    /// treats this field as "room for N more packets": reporting `0` here
133    /// (this crate's old default, chosen to avoid fabricating a real
134    /// buffer-occupancy estimate) reads as "no room at all" and a real
135    /// libsrt Caller then withholds every DATA packet forever, connected but
136    /// silent — a real, previously undetected interop stall found live
137    /// against `srt-live-transmit`, independent of the caller-side
138    /// CONCLUSION `dest_socket_id` bug `libsrt_interop.rs` was originally
139    /// written to catch (libsrt interop; no tracked issue number for this
140    /// one).
141    avail_buf_size: u32,
142    /// The MTU the periodic NAK is sized against (`IP_UDP_HEADER_LEN` and the
143    /// SRT header come off it, see [`Self::with_mtu`]).
144    mtu: u32,
145}
146
147impl Receiver {
148    /// A fresh receiver expecting `initial_seq` first (the peer's ISN),
149    /// addressing `dest_socket_id` (the peer's SRT Socket ID, §3), advertising
150    /// `max_flow_window` (§3.2.1) as its Full ACK's Available Buffer Size.
151    pub fn new(dest_socket_id: u32, initial_seq: u32, max_flow_window: u32) -> Self {
152        Receiver {
153            dest_socket_id,
154            next_expected: initial_seq,
155            out_of_order: BTreeSet::new(),
156            loss_list: BTreeSet::new(),
157            pending_skips: Vec::new(),
158            highest_received: None,
159            packets_since_ack: 0,
160            last_full_ack_at: Timestamp::ZERO,
161            last_nak_at: Timestamp::ZERO,
162            next_ack_number: 1,
163            outstanding_acks: BTreeMap::new(),
164            rtt: RttEstimator::new(),
165            avail_buf_size: max_flow_window,
166            mtu: DEFAULT_MTU,
167        }
168    }
169
170    /// Size periodic NAK datagrams against `mtu` (the handshake's negotiated
171    /// Maximum Transmission Unit Size, §3.2.1) instead of the 1500-byte
172    /// default: a loss list too long for one datagram is split across several
173    /// NAK packets rather than emitted as one the socket cannot send.
174    pub fn with_mtu(mut self, mtu: u32) -> Self {
175        self.mtu = mtu;
176        self
177    }
178
179    /// How far ahead of the ack point a packet may be and still be tracked.
180    fn window(&self) -> u32 {
181        self.avail_buf_size.min(MAX_TRACKED_WINDOW)
182    }
183
184    /// Most NAK Control Information Field bytes one datagram may carry:
185    /// the MTU less the IP/UDP and SRT headers, never less than one range
186    /// entry (so a pathological MTU still makes progress).
187    fn max_nak_cif_len(&self) -> usize {
188        usize::try_from(self.mtu)
189            .unwrap_or(usize::MAX)
190            .saturating_sub(IP_UDP_HEADER_LEN + crate::packet::SRT_HEADER_LEN)
191            .max(LOSS_ENTRY_RANGE_LEN)
192    }
193
194    /// The cumulative ack point — every seq strictly before this has been
195    /// delivered in order (rule 8's ACK `n + 1` semantics).
196    pub fn ack_point(&self) -> u32 {
197        self.next_expected
198    }
199
200    /// The current RTT estimate (rules 26-31).
201    pub fn rtt(&self) -> Duration {
202        self.rtt.rtt()
203    }
204
205    /// The current RTTVar estimate.
206    pub fn rtt_var(&self) -> Duration {
207        self.rtt.rtt_var()
208    }
209
210    /// Number of sequence numbers currently believed lost.
211    pub fn loss_list_len(&self) -> usize {
212        self.loss_list.len()
213    }
214
215    /// Process one arriving data packet's sequence number.
216    ///
217    /// A packet more than the flow window ahead of the ack point is ignored
218    /// ([`FeedOutcome::out_of_window`]): a crafted sequence jump therefore
219    /// never grows the loss list or the out-of-order set past the window.
220    pub fn feed_data(&mut self, seq_number: u32, now: Timestamp) -> FeedOutcome {
221        // Not a 31-bit sequence number at all (§3.1): never a real packet.
222        if seq_number > crate::packet::SEQ_NUMBER_MASK {
223            return FeedOutcome {
224                out_of_window: true,
225                ..FeedOutcome::default()
226            };
227        }
228        if seq::seq_gt(seq_number, self.next_expected)
229            && !u32::try_from(seq::seq_diff(seq_number, self.next_expected))
230                .is_ok_and(|ahead| ahead <= self.window())
231        {
232            return FeedOutcome {
233                out_of_window: true,
234                ..FeedOutcome::default()
235            };
236        }
237
238        self.packets_since_ack = self.packets_since_ack.saturating_add(1);
239
240        let mut nak_entries = Vec::new();
241        // Before any packet has arrived the "highest received" is the one
242        // just below the peer's ISN (the ack point), so a first packet
243        // ahead of the ISN reveals a gap like any other.
244        let highest = self
245            .highest_received
246            .unwrap_or_else(|| seq::seq_add(self.next_expected, crate::packet::SEQ_NUMBER_MASK));
247        if seq::seq_gt(seq_number, highest) {
248            // The newly opened gap, `highest + 1 ..= seq_number - 1` —
249            // clipped to the ack point (a DROPREQ may have moved it past
250            // a `highest` that never saw those packets).
251            let mut first_lost = seq::seq_next(highest);
252            if seq::seq_lt(first_lost, self.next_expected) {
253                first_lost = self.next_expected;
254            }
255            if first_lost != seq_number && seq::seq_lt(first_lost, seq_number) {
256                // `+ (2^31 - 1)` is `- 1` in the 31-bit sequence space.
257                let last_lost = seq::seq_add(seq_number, crate::packet::SEQ_NUMBER_MASK);
258                let mut s = first_lost;
259                loop {
260                    self.loss_list.insert(s);
261                    if s == last_lost {
262                        break;
263                    }
264                    s = seq::seq_next(s);
265                }
266                let (first_lost, last_lost) = (
267                    SeqNo::from_wire_masked(first_lost),
268                    SeqNo::from_wire_masked(last_lost),
269                );
270                nak_entries.push(if first_lost == last_lost {
271                    LossListEntry::Single(first_lost)
272                } else {
273                    LossListEntry::Range(first_lost, last_lost)
274                });
275            }
276            self.highest_received = Some(seq_number);
277            let pending = &self.pending_skips;
278            self.loss_list.retain(|&s| {
279                !pending
280                    .iter()
281                    .any(|&(f, l)| seq::seq_in_closed_range(s, f, l))
282            });
283        }
284
285        self.loss_list.remove(&seq_number);
286
287        let mut delivered = Vec::new();
288        if seq_number == self.next_expected {
289            delivered.push(seq_number);
290            self.next_expected = seq::seq_next(seq_number);
291            while self.out_of_order.remove(&self.next_expected) {
292                delivered.push(self.next_expected);
293                self.next_expected = seq::seq_next(self.next_expected);
294            }
295            self.cross_pending_skips(&mut delivered);
296        } else if seq::seq_gt(seq_number, self.next_expected) {
297            self.out_of_order.insert(seq_number);
298        }
299        // seq_number before next_expected: a duplicate of an
300        // already-delivered packet (e.g. a redundant retransmission) —
301        // nothing to do.
302
303        let nak = if nak_entries.is_empty() {
304            None
305        } else {
306            self.build_naks(&nak_entries, now).into_iter().next()
307        };
308
309        FeedOutcome {
310            delivered,
311            nak,
312            out_of_window: false,
313        }
314    }
315
316    /// Serialize `entries` into one or more NAK datagrams, none larger than
317    /// the MTU allows (a periodic NAK of a bursty-loss list otherwise grows
318    /// past one datagram, which the socket refuses with `EMSGSIZE`).
319    fn build_naks(&self, entries: &[LossListEntry], now: Timestamp) -> Vec<Vec<u8>> {
320        let budget = self.max_nak_cif_len();
321        let mut out = Vec::new();
322        let mut chunk: Vec<LossListEntry> = Vec::new();
323        let mut used = 0usize;
324        for &entry in entries {
325            let len = match entry {
326                LossListEntry::Range(..) => LOSS_ENTRY_RANGE_LEN,
327                _ => LOSS_ENTRY_SINGLE_LEN,
328            };
329            if used + len > budget && !chunk.is_empty() {
330                out.extend(self.nak_datagram(&chunk, now));
331                chunk.clear();
332                used = 0;
333            }
334            chunk.push(entry);
335            used += len;
336        }
337        if !chunk.is_empty() {
338            out.extend(self.nak_datagram(&chunk, now));
339        }
340        out
341    }
342
343    /// One NAK datagram for `entries`, or `None` if it cannot be serialized.
344    fn nak_datagram(&self, entries: &[LossListEntry], now: Timestamp) -> Option<Vec<u8>> {
345        let pkt = ControlPacket::Nak(NakPacket {
346            timestamp: timestamp_to_wire_us(now),
347            dest_socket_id: SocketId::from_wire(self.dest_socket_id),
348            entries: entries.to_vec(),
349        });
350        let mut buf = alloc::vec![0u8; pkt.serialized_len()];
351        pkt.serialize_into(&mut buf).ok()?;
352        Some(buf)
353    }
354
355    /// Advance to absolute time `now` and emit any periodic control packets
356    /// now due: a Full ACK every [`super::FULL_ACK_PERIOD`] (rule 11), a
357    /// Light ACK once [`super::LIGHT_ACK_THRESHOLD`] packets have arrived
358    /// since the last ACK (rule 12), and a periodic NAK once `NAKInterval`
359    /// has elapsed *and* the loss list is non-empty (rules 21, 22) — never a
360    /// NAK when nothing is believed lost.
361    pub fn tick(&mut self, now: Timestamp) -> Vec<Vec<u8>> {
362        let mut out = Vec::new();
363
364        if elapsed(now, self.last_full_ack_at) >= FULL_ACK_PERIOD {
365            out.extend(self.build_full_ack(now));
366            self.last_full_ack_at = now;
367            self.packets_since_ack = 0;
368        } else if self.packets_since_ack >= LIGHT_ACK_THRESHOLD {
369            out.extend(self.build_light_ack());
370            self.packets_since_ack = 0;
371        }
372
373        let interval = nak_interval(self.rtt.rtt(), self.rtt.rtt_var());
374        if !self.loss_list.is_empty() && elapsed(now, self.last_nak_at) >= interval {
375            // Circular order from the ack point, so a run that straddles the
376            // 31-bit wrap coalesces into one range.
377            let base = self.next_expected;
378            let mut seqs: Vec<u32> = self.loss_list.iter().copied().collect();
379            seqs.sort_unstable_by_key(|&s| seq::seq_diff(s, base));
380            out.extend(self.build_naks(&coalesce(&seqs), now));
381            self.last_nak_at = now;
382        }
383
384        self.expire_outstanding_acks(now);
385
386        out
387    }
388
389    /// Absolute (since the connection epoch) time of the next periodic Full
390    /// ACK or, while the loss list is non-empty, the next periodic NAK —
391    /// whichever is earlier and still representable. The 10 ms Full ACK is
392    /// unconditional (rule 11), so an idle connection still has a deadline;
393    /// `None` means a deadline past the end of the clock, which never fires
394    /// (a deadline is [`Timestamp::checked_add`], never a saturated instant
395    /// that reads as "due now" forever).
396    pub fn next_timeout(&self) -> Option<Timestamp> {
397        let ack = self.last_full_ack_at.checked_add(FULL_ACK_PERIOD);
398        if self.loss_list.is_empty() {
399            return ack;
400        }
401        let nak = self
402            .last_nak_at
403            .checked_add(nak_interval(self.rtt.rtt(), self.rtt.rtt_var()));
404        match (ack, nak) {
405            (Some(a), Some(n)) => Some(a.min(n)),
406            (a, n) => a.or(n),
407        }
408    }
409
410    /// Forget Full ACKs whose ACKACK never came (W3): a lost ACKACK, or a
411    /// peer that never sends one, would otherwise leave one entry per Full
412    /// ACK (100/s) forever.
413    fn expire_outstanding_acks(&mut self, now: Timestamp) {
414        let retention = (self.rtt.rtt() * ACK_RETENTION_RTTS).max(ACK_RETENTION_FLOOR);
415        self.outstanding_acks
416            .retain(|_, sent_at| elapsed(now, *sent_at) <= retention);
417    }
418
419    fn build_full_ack(&mut self, now: Timestamp) -> Option<Vec<u8>> {
420        let ack_number = self.next_ack_number;
421        self.next_ack_number = self.next_ack_number.wrapping_add(1);
422        if self.outstanding_acks.len() >= MAX_OUTSTANDING_ACKS {
423            // Oldest first: Acknowledgement Numbers only ever increase (the
424            // 32-bit `AckNumber` counter wraps only after ~2^32 Full ACKs at
425            // 100/s).
426            self.outstanding_acks.pop_first();
427        }
428        self.outstanding_acks.insert(ack_number, now);
429        let pkt = ControlPacket::Ack(AckPacket {
430            ack_number: AckNumber::from_wire(ack_number),
431            timestamp: timestamp_to_wire_us(now),
432            dest_socket_id: SocketId::from_wire(self.dest_socket_id),
433            cif: AckCif::Full {
434                last_ack_seq: SeqNo::from_wire_masked(self.next_expected),
435                rtt_us: self.rtt.rtt_us(),
436                rtt_var_us: self.rtt.rtt_var_us(),
437                avail_buf_size: self.avail_buf_size,
438                // Bandwidth/rate estimation (§4.7) is out of ARQ scope — not
439                // curated in srt-arq.md, so left at 0 rather than fabricated.
440                pkt_recv_rate: 0,
441                est_link_capacity: 0,
442                recv_rate_bps: 0,
443            },
444        });
445        let mut buf = alloc::vec![0u8; pkt.serialized_len()];
446        pkt.serialize_into(&mut buf).ok()?;
447        Some(buf)
448    }
449
450    fn build_light_ack(&self) -> Option<Vec<u8>> {
451        // §3.2.4: a Light ACK's Acknowledgement Number "should be set to
452        // 0"; it carries no RTT/CIF payload beyond the sequence number
453        // (rule 24).
454        let pkt = ControlPacket::Ack(AckPacket {
455            ack_number: AckNumber::ZERO,
456            timestamp: SrtTimestamp::ZERO,
457            dest_socket_id: SocketId::from_wire(self.dest_socket_id),
458            cif: AckCif::Light {
459                last_ack_seq: SeqNo::from_wire_masked(self.next_expected),
460            },
461        });
462        let mut buf = alloc::vec![0u8; pkt.serialized_len()];
463        pkt.serialize_into(&mut buf).ok()?;
464        Some(buf)
465    }
466
467    /// Process an incoming ACKACK: match it against the outstanding Full ACK
468    /// it acknowledges and update RTT/RTTVar from the round-trip sample
469    /// (rules 26-30). An ACKACK for an unknown/already-matched
470    /// Acknowledgement Number is ignored.
471    pub fn on_ackack(&mut self, ackack: &AckAckPacket, now: Timestamp) {
472        if let Some(sent_at) = self.outstanding_acks.remove(&ackack.ack_number.value()) {
473            self.rtt.update(elapsed(now, sent_at));
474        }
475    }
476
477    /// Handle a peer's DROPREQ (`draft-sharabayko-srt-01` §3.2.9): the sender
478    /// has given up on delivering the inclusive sequence range
479    /// `first..=last`, so they will never arrive.
480    ///
481    /// Without this, loss detection would NAK those numbers forever and the
482    /// cumulative ack point (`next_expected`) would stall below the gap for
483    /// the life of the connection. The range is removed from the loss list
484    /// (stop asking) and the out-of-order set (the sender has given up on
485    /// them, so anything they unblocked can no longer be delivered in order),
486    /// and when the range covers `next_expected` the ack point jumps to the
487    /// sequence after `last`. A `last` preceding `first` is a malformed
488    /// (empty) range and ignored.
489    //
490    // Public so a sans-IO driver other than the tokio adapter (`crate::io`) can apply a DROPREQ
491    // and the Too-Late Packet Drop fake ACK.
492    pub fn skip_range(&mut self, first: u32, last: u32) {
493        if seq::seq_diff(last, first) < 0 {
494            return;
495        }
496        let reach = seq::seq_diff(last, self.next_expected);
497        if reach < 0 || !u32::try_from(reach).is_ok_and(|ahead| ahead <= self.window()) {
498            return;
499        }
500        self.loss_list
501            .retain(|s| !seq::seq_in_closed_range(*s, first, last));
502        self.out_of_order
503            .retain(|s| !seq::seq_in_closed_range(*s, first, last));
504        if seq::seq_lt(self.next_expected, first) {
505            if self.pending_skips.len() < MAX_PENDING_SKIPS {
506                self.pending_skips.push((first, last));
507            }
508        } else {
509            self.next_expected = seq::seq_next(last);
510        }
511        self.cross_pending_skips(&mut Vec::new());
512    }
513
514    /// Advance the ack point over every packet already received and every
515    /// DROPREQ range it has reached, pushing the received ones onto
516    /// `delivered`.
517    fn cross_pending_skips(&mut self, delivered: &mut Vec<u32>) {
518        loop {
519            while self.out_of_order.remove(&self.next_expected) {
520                delivered.push(self.next_expected);
521                self.next_expected = seq::seq_next(self.next_expected);
522            }
523            let next = self.next_expected;
524            self.pending_skips.retain(|&(_, l)| !seq::seq_lt(l, next));
525            let Some(pos) = self
526                .pending_skips
527                .iter()
528                .position(|&(f, l)| seq::seq_in_closed_range(next, f, l))
529            else {
530                return;
531            };
532            let (_, last) = self.pending_skips.swap_remove(pos);
533            self.next_expected = seq::seq_next(last);
534        }
535    }
536}
537
538/// `now - since`, clamped to zero rather than panicking on a non-monotonic
539/// `now` (a caller bug, not a protocol condition this module needs to
540/// reject).
541fn elapsed(now: Timestamp, since: Timestamp) -> Duration {
542    now.saturating_sub(since)
543}
544
545/// Coalesce a run of sequence numbers (already circularly increasing) into
546/// [`LossListEntry`] Single/Range entries (Appendix A) — a compact NAK
547/// encoding; the coalescing itself is not a spec rule.
548fn coalesce(seqs: &[u32]) -> Vec<LossListEntry> {
549    let mut out = Vec::new();
550    let mut i = 0;
551    while i < seqs.len() {
552        let start = seqs[i];
553        let mut end = start;
554        let mut j = i + 1;
555        while j < seqs.len() && seqs[j] == seq::seq_next(end) {
556            end = seqs[j];
557            j += 1;
558        }
559        let (start, end) = (SeqNo::from_wire_masked(start), SeqNo::from_wire_masked(end));
560        if start == end {
561            out.push(LossListEntry::Single(start));
562        } else {
563            out.push(LossListEntry::Range(start, end));
564        }
565        i = j;
566    }
567    out
568}
569
570#[cfg(test)]
571mod tests {
572    use super::*;
573
574    const PEER: u32 = 0xBBBB;
575    const MAX_FLOW_WINDOW: u32 = 8192;
576
577    /// A `Timestamp` at `d` microseconds since the test epoch.
578    fn ts(d: Duration) -> Timestamp {
579        Timestamp::from_micros(u64::try_from(d.as_micros()).expect("in range"))
580    }
581
582    #[test]
583    fn next_timeout_is_the_full_ack_period_then_tracks_the_nak_interval() {
584        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW);
585        assert_eq!(
586            r.next_timeout(),
587            Some(ts(FULL_ACK_PERIOD)),
588            "fresh receiver: first Full ACK at 10 ms"
589        );
590        let _ = r.tick(ts(FULL_ACK_PERIOD));
591        assert_eq!(r.next_timeout(), Some(ts(FULL_ACK_PERIOD * 2)));
592        // a gap puts a NAK deadline on the table; it can only make the deadline earlier or equal
593        let _ = r.feed_data(5, Timestamp::from_millis(11)); // 1..=4 now lost
594        assert!(
595            r.next_timeout()
596                .is_some_and(|t| t <= ts(FULL_ACK_PERIOD * 2))
597        );
598    }
599
600    /// A deadline past the end of the clock never fires: at the last
601    /// representable `Timestamp` the next Full ACK (and, with a loss, the next
602    /// NAK) cannot be scheduled, so `next_timeout` reports `None` — not a
603    /// saturated instant equal to "now" that would re-fire forever.
604    #[test]
605    fn next_timeout_at_the_end_of_the_clock_is_none() {
606        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW);
607        r.last_full_ack_at = Timestamp::from_micros(u64::MAX);
608        assert_eq!(r.next_timeout(), None, "Full ACK deadline past the clock");
609
610        // A loss adds a NAK deadline too; it is equally unrepresentable.
611        r.last_nak_at = Timestamp::from_micros(u64::MAX);
612        r.loss_list.insert(0);
613        assert_eq!(r.next_timeout(), None, "NAK deadline past the clock");
614    }
615
616    #[test]
617    fn in_order_arrivals_deliver_immediately_without_nak() {
618        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW);
619        for seq_number in 0..5u32 {
620            let outcome = r.feed_data(seq_number, Timestamp::ZERO);
621            assert_eq!(outcome.delivered, alloc::vec![seq_number]);
622            assert!(outcome.nak.is_none());
623        }
624        assert_eq!(r.ack_point(), 5);
625        assert_eq!(r.loss_list_len(), 0);
626    }
627
628    #[test]
629    fn a_gap_triggers_an_immediate_nak_and_stalls_delivery() {
630        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW);
631        r.feed_data(0, Timestamp::ZERO);
632        r.feed_data(1, Timestamp::ZERO);
633        let outcome = r.feed_data(3, Timestamp::ZERO); // seq 2 missing
634        assert!(outcome.delivered.is_empty());
635        let nak = outcome.nak.expect("gap must trigger an immediate NAK");
636        let ControlPacket::Nak(n) = ControlPacket::parse(&nak).unwrap() else {
637            panic!("expected NAK");
638        };
639        assert_eq!(n.entries, alloc::vec![LossListEntry::Single(sn(2))]);
640        assert_eq!(r.ack_point(), 2); // stalled at the gap
641        assert_eq!(r.loss_list_len(), 1);
642
643        // Filling the gap unblocks the buffered seq 3 too.
644        let fill = r.feed_data(2, Timestamp::ZERO);
645        assert_eq!(fill.delivered, alloc::vec![2, 3]);
646        assert!(fill.nak.is_none());
647        assert_eq!(r.ack_point(), 4);
648        assert_eq!(r.loss_list_len(), 0);
649    }
650
651    #[test]
652    fn zero_loss_tick_never_emits_a_nak() {
653        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW);
654        for seq_number in 0..5u32 {
655            r.feed_data(seq_number, Timestamp::ZERO);
656        }
657        for ms in 1..200u64 {
658            let out = r.tick(Timestamp::from_millis(ms));
659            for bytes in &out {
660                assert!(!matches!(
661                    ControlPacket::parse(bytes).unwrap(),
662                    ControlPacket::Nak(_)
663                ));
664            }
665        }
666    }
667
668    #[test]
669    fn full_ack_fires_on_the_10ms_timer_and_light_ack_on_the_64_packet_threshold() {
670        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW);
671        let out = r.tick(ts(FULL_ACK_PERIOD));
672        assert_eq!(out.len(), 1);
673        let ControlPacket::Ack(ack) = ControlPacket::parse(&out[0]).unwrap() else {
674            panic!("expected ACK");
675        };
676        assert!(matches!(ack.cif, AckCif::Full { .. }));
677        assert_eq!(ack.ack_number.value(), 1);
678
679        // Under the Full ACK period, but past the light-ack packet count.
680        for seq_number in 0..LIGHT_ACK_THRESHOLD {
681            r.feed_data(seq_number, Timestamp::ZERO);
682        }
683        let out = r.tick(ts(FULL_ACK_PERIOD + Duration::from_millis(1)));
684        // Immediately after a Full ACK, the next tick 1ms later is still
685        // under the 10ms period, so a Light ACK fires instead.
686        let out2 = r.tick(ts(FULL_ACK_PERIOD + Duration::from_millis(2)));
687        let light =
688            out.into_iter()
689                .chain(out2)
690                .find_map(|b| match ControlPacket::parse(&b).unwrap() {
691                    ControlPacket::Ack(a) if matches!(a.cif, AckCif::Light { .. }) => Some(a),
692                    _ => None,
693                });
694        assert!(
695            light.is_some(),
696            "expected a Light ACK from the 64-packet threshold"
697        );
698    }
699
700    #[test]
701    fn ackack_updates_rtt_from_the_measured_round_trip() {
702        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW);
703        let out = r.tick(ts(FULL_ACK_PERIOD));
704        let ControlPacket::Ack(ack) = ControlPacket::parse(&out[0]).unwrap() else {
705            panic!("expected ACK");
706        };
707        let ackack = AckAckPacket {
708            ack_number: ack.ack_number,
709            timestamp: SrtTimestamp::ZERO,
710            dest_socket_id: SocketId::from_wire(PEER),
711            libsrt_pad: false,
712        };
713        let sample = Duration::from_millis(20);
714        r.on_ackack(&ackack, ts(FULL_ACK_PERIOD + sample));
715        // moved from the 100ms initial value toward the 20ms sample.
716        assert!(r.rtt() < Duration::from_millis(100));
717        assert!(r.rtt() > sample);
718    }
719
720    fn nak_entries(bytes: &[u8]) -> Vec<LossListEntry> {
721        let ControlPacket::Nak(n) = ControlPacket::parse(bytes).unwrap() else {
722            panic!("expected NAK");
723        };
724        n.entries
725    }
726
727    fn sn(v: u32) -> SeqNo {
728        SeqNo::try_new(v).expect("fits 31 bits")
729    }
730
731    /// r08-SRT-W2: a sequence number past the flow window is ignored, so one
732    /// crafted datagram cannot inflate the loss list. 2^30 - 1 is the farthest
733    /// "ahead" the 31-bit circular order allows (the old code enumerated
734    /// 65 536 losses for it and then jumped `highest_received`, so the next
735    /// spoofed packet added another 65 536).
736    #[test]
737    fn a_sequence_number_wider_than_31_bits_is_refused() {
738        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW);
739        for seq in [0x8000_0000u32, 0x8000_0001, u32::MAX] {
740            let out = r.feed_data(seq, Timestamp::ZERO);
741            assert!(out.out_of_window, "{seq:#x}");
742            assert!(out.delivered.is_empty() && out.nak.is_none());
743        }
744        assert_eq!(r.loss_list_len(), 0);
745        assert_eq!(r.highest_received, None);
746        assert_eq!(r.ack_point(), 0);
747    }
748
749    #[test]
750    fn a_hostile_sequence_jump_is_ignored_not_enumerated() {
751        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW);
752        r.feed_data(0, Timestamp::ZERO);
753        for jump in [(1u32 << 30) - 1, 1 << 20, 1 << 18, 5 << 16] {
754            let out = r.feed_data(jump, Timestamp::ZERO);
755            assert!(out.out_of_window, "jump to {jump} must be refused");
756            assert!(out.nak.is_none());
757            assert!(out.delivered.is_empty());
758        }
759        assert_eq!(r.loss_list_len(), 0);
760        assert_eq!(r.out_of_order.len(), 0);
761        assert_eq!(r.ack_point(), 1);
762        // The ack point is where the window is measured from: repeating the
763        // attack does not move `highest_received` either.
764        assert_eq!(r.highest_received, Some(0));
765    }
766
767    /// The window boundary is exact: `next_expected + window` is accepted
768    /// (and its whole gap NAKed as one range), one more is refused.
769    #[test]
770    fn the_flow_window_boundary_is_exact() {
771        const WINDOW: u32 = 1000;
772        let mut r = Receiver::new(PEER, 0, WINDOW);
773        let beyond = r.feed_data(WINDOW + 1, Timestamp::ZERO);
774        assert!(beyond.out_of_window);
775        assert_eq!(r.loss_list_len(), 0);
776
777        let edge = r.feed_data(WINDOW, Timestamp::ZERO);
778        assert!(!edge.out_of_window);
779        assert_eq!(r.loss_list_len(), (WINDOW - 1) as usize + 1); // 0..WINDOW-1
780        let nak = edge.nak.expect("the gap is NAKed immediately");
781        // One Range entry, not 1000 singles.
782        assert_eq!(
783            nak_entries(&nak),
784            alloc::vec![LossListEntry::Range(sn(0), sn(WINDOW - 1))]
785        );
786        assert!(r.out_of_order.len() <= WINDOW as usize);
787    }
788
789    /// A window larger than the receiver is willing to track is clamped, so
790    /// a hostile `max_flow_window_size` cannot re-open the flood.
791    #[test]
792    fn an_oversized_negotiated_window_is_clamped() {
793        let mut r = Receiver::new(PEER, 0, u32::MAX);
794        let out = r.feed_data((1 << 30) - 1, Timestamp::ZERO);
795        assert!(out.out_of_window);
796        assert_eq!(r.loss_list_len(), 0);
797    }
798
799    /// r08-SRT-W3: Full ACKs whose ACKACK never arrives are forgotten. 5 000
800    /// ticks (50 s) with no ACKACK at all used to leave 5 000 entries.
801    #[test]
802    fn unanswered_full_acks_age_out() {
803        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW);
804        for tick in 1..=5_000u64 {
805            r.tick(Timestamp::from_millis(10 * tick));
806        }
807        // Retention is max(4 x RTT, 1 s) = 1 s of 10 ms ACKs.
808        let retention_acks =
809            (ACK_RETENTION_FLOOR.as_millis() / FULL_ACK_PERIOD.as_millis()) as usize;
810        assert!(
811            r.outstanding_acks.len() <= retention_acks + 1,
812            "{} outstanding ACKs retained",
813            r.outstanding_acks.len()
814        );
815        assert!(!r.outstanding_acks.is_empty(), "recent ACKs are kept");
816    }
817
818    /// An ACKACK arriving inside the retention window still measures RTT; one
819    /// that arrives after its entry aged out is ignored.
820    #[test]
821    fn ackack_after_expiry_is_ignored() {
822        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW);
823        let out = r.tick(ts(FULL_ACK_PERIOD));
824        let ControlPacket::Ack(ack) = ControlPacket::parse(&out[0]).unwrap() else {
825            panic!("expected ACK");
826        };
827        let ackack = AckAckPacket {
828            ack_number: ack.ack_number,
829            timestamp: SrtTimestamp::ZERO,
830            dest_socket_id: SocketId::from_wire(PEER),
831            libsrt_pad: false,
832        };
833        let rtt_before = r.rtt();
834        // Age the entry out (no ACKACK for 10 s), then deliver the ACKACK.
835        for tick in 2..=1_000u64 {
836            r.tick(Timestamp::from_millis(10 * tick));
837        }
838        r.on_ackack(&ackack, ts(Duration::from_secs(10)));
839        assert_eq!(r.rtt(), rtt_before, "an expired ACK must not move the RTT");
840    }
841
842    /// The hard cap: more Full ACKs than `MAX_OUTSTANDING_ACKS` inside one
843    /// retention window evict the oldest rather than growing.
844    #[test]
845    fn outstanding_acks_are_capped() {
846        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW);
847        for _ in 0..(MAX_OUTSTANDING_ACKS * 5) {
848            r.build_full_ack(Timestamp::ZERO);
849        }
850        assert_eq!(r.outstanding_acks.len(), MAX_OUTSTANDING_ACKS);
851        // The survivors are the newest.
852        let oldest = *r.outstanding_acks.keys().next().unwrap();
853        assert_eq!(oldest as usize, MAX_OUTSTANDING_ACKS * 4 + 1);
854    }
855
856    /// r08-SRT-W4: a bursty (non-contiguous) loss list no longer becomes one
857    /// datagram larger than the MTU — it is split, every datagram fits, and
858    /// together they name every lost packet exactly once.
859    #[test]
860    fn periodic_nak_is_split_to_fit_the_mtu() {
861        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW);
862        r.feed_data(0, Timestamp::ZERO);
863        // Receive every other packet: 2, 4, ..., 2000 → 1000 isolated losses.
864        let mut lost = Vec::new();
865        for q in (2..=2000u32).step_by(2) {
866            r.feed_data(q, Timestamp::ZERO);
867            lost.push(q - 1);
868        }
869        assert_eq!(r.loss_list_len(), 1000);
870
871        let naks: Vec<Vec<u8>> = r
872            .tick(ts(Duration::from_secs(1)))
873            .into_iter()
874            .filter(|b| matches!(ControlPacket::parse(b), Ok(ControlPacket::Nak(_))))
875            .collect();
876        assert!(naks.len() > 1, "1000 singles cannot fit one datagram");
877        let mut named = Vec::new();
878        for nak in &naks {
879            assert!(
880                nak.len() + IP_UDP_HEADER_LEN <= DEFAULT_MTU as usize,
881                "NAK of {} B exceeds the {} B MTU",
882                nak.len() + IP_UDP_HEADER_LEN,
883                DEFAULT_MTU
884            );
885            for e in nak_entries(nak) {
886                match e {
887                    LossListEntry::Single(s) => named.push(s.value()),
888                    other => panic!("unexpected entry {other:?}"),
889                }
890            }
891        }
892        named.sort_unstable();
893        assert_eq!(named, lost);
894    }
895
896    /// The MTU is configurable: 576 gives smaller datagrams.
897    #[test]
898    fn nak_chunking_follows_the_configured_mtu() {
899        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW).with_mtu(576);
900        r.feed_data(0, Timestamp::ZERO);
901        for q in (2..=400u32).step_by(2) {
902            r.feed_data(q, Timestamp::ZERO);
903        }
904        let naks: Vec<Vec<u8>> = r
905            .tick(ts(Duration::from_secs(1)))
906            .into_iter()
907            .filter(|b| matches!(ControlPacket::parse(b), Ok(ControlPacket::Nak(_))))
908            .collect();
909        assert!(naks.len() >= 2);
910        for nak in &naks {
911            assert!(nak.len() + IP_UDP_HEADER_LEN <= 576);
912        }
913    }
914
915    /// A loss run that straddles the 31-bit wrap is one range in the periodic
916    /// NAK (the loss list is ordered by raw value, which would split it at
917    /// the wrap).
918    #[test]
919    fn periodic_nak_coalesces_a_loss_run_across_the_wrap() {
920        const MAX: u32 = crate::packet::SEQ_NUMBER_MASK;
921        let mut r = Receiver::new(PEER, MAX - 2, MAX_FLOW_WINDOW);
922        r.feed_data(MAX - 2, Timestamp::ZERO);
923        let imm = r.feed_data(2, Timestamp::ZERO); // MAX-1, MAX, 0, 1 lost
924        assert_eq!(
925            nak_entries(&imm.nak.expect("gap NAK")),
926            alloc::vec![LossListEntry::Range(sn(MAX - 1), sn(1))]
927        );
928        let naks: Vec<Vec<u8>> = r
929            .tick(ts(Duration::from_secs(1)))
930            .into_iter()
931            .filter(|b| matches!(ControlPacket::parse(b), Ok(ControlPacket::Nak(_))))
932            .collect();
933        assert_eq!(naks.len(), 1);
934        assert_eq!(
935            nak_entries(&naks[0]),
936            alloc::vec![LossListEntry::Range(sn(MAX - 1), sn(1))]
937        );
938    }
939
940    /// After a DROPREQ moves the ack point past packets this receiver never
941    /// saw, the next gap is measured from the ack point, not from a stale
942    /// `highest_received` (which would NAK sequence numbers the sender gave
943    /// up on).
944    #[cfg(feature = "tokio")]
945    #[test]
946    fn gap_after_a_dropreq_starts_at_the_ack_point() {
947        let mut r = Receiver::new(PEER, 0, MAX_FLOW_WINDOW);
948        r.feed_data(0, Timestamp::ZERO);
949        r.skip_range(1, 99); // sender gave up on 1..=99
950        assert_eq!(r.ack_point(), 100);
951        let out = r.feed_data(105, Timestamp::ZERO);
952        assert_eq!(
953            nak_entries(&out.nak.expect("gap NAK")),
954            alloc::vec![LossListEntry::Range(sn(100), sn(104))]
955        );
956        assert_eq!(r.loss_list_len(), 5);
957    }
958}