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