Skip to main content

srt_runtime/
tsbpd.rs

1//! Timestamp-Based Packet Delivery (TSBPD) + Too-Late Packet Drop — SRT
2//! receiver-side delivery scheduling.
3//!
4//! Spec grounding: [`draft-sharabayko-srt-01`](https://datatracker.ietf.org/doc/html/draft-sharabayko-srt-01)
5//! §4.5 "Timestamp-Based Packet Delivery", §4.5.1 "Packet Delivery Time",
6//! §4.5.1.1 "TSBPD Time Base Calculation", §4.6 "Too-Late Packet Drop", and
7//! §4.7 "Drift Management" (for the `Drift` term in the `PktTsbpdTime`
8//! formula). Curated behavioral rules: `private/specs-verified/rules/srt-tsbpd.md`.
9//!
10//! # Sans-IO contract
11//!
12//! [`TsbpdScheduler`] never reads a wall clock. All timing is driven by:
13//! - [`TsbpdScheduler::feed_data`] — submit a received data packet's sequence
14//!   number + 32-bit timestamp (from the SRT header). The scheduler computes
15//!   the packet's `PktTsbpdTime` (rule 9) and stores it for timed delivery.
16//! - [`TsbpdScheduler::tick`] — advance the virtual clock to `now` and release
17//!   any packets whose play time has arrived, in sequence order. Also drops
18//!   packets whose play time has already passed the too-late threshold
19//!   (rule 17-19, if enabled).
20//!
21//! # Delivery model
22//!
23//! `tick` returns a [`TickOutcome`] containing:
24//! - `delivered` — sequence numbers released to the application in order.
25//! - `dropped` — sequence numbers dropped because they arrived after their
26//!   play time (too-late drop, rules 17-18).
27//!
28//! Packets are always released in monotonically increasing sequence order.
29//! A packet whose `PktTsbpdTime` has not yet arrived is withheld.
30//!
31//! # Time base, wrap and drift
32//!
33//! - `TsbpdTimeBase` (rule 12) is a *signed* microsecond offset: it is seeded
34//!   as `T_NOW - HSREQ_TIMESTAMP`, which is negative whenever the peer's
35//!   handshake timestamp exceeds the local time since the caller's epoch.
36//! - The 32-bit wire timestamp wraps every ~71.58 minutes (rule 15). The
37//!   scheduler unwraps it into an always-increasing value with a maintained
38//!   reference point and a signed circular delta
39//!   (`TsbpdScheduler::unwrap_timestamp`, mirroring `arq::seq::seq_diff` one
40//!   bit wider), which is equivalent to adding `MAX_TIMESTAMP + 1` to the
41//!   base at each wrap (rule 16) without a separate wrap-window state machine.
42//!   (An earlier version used plain modular arithmetic, dropping `PktTsbpdTime`
43//!   back near zero on every wrap — issue #1063.)
44//! - Drift (§4.7, rules 26-27) is estimated internally from fresh in-sequence
45//!   packets, in a packet-count-based window ([`DRIFT_SAMPLE_COUNT`]); the
46//!   window average is applied as `Drift`, with any part beyond
47//!   [`DRIFT_MAX_US`] moved into the time base, mirroring libsrt's tracer.
48//!
49//! # Fake ACK on skip
50//! When this scheduler skips or drops packets under TLPKTDROP it reports them
51//! in [`TickOutcome::dropped`]; moving the ARQ receiver's ack point past them
52//! (the "fake ACK" of rule 22 / `srt-arq.md` rule 13) is the integration
53//! layer's job, and [`crate::io`] does it (only when TLPKTDROP was
54//! negotiated — with it off the scheduler never drops, and the ack point waits
55//! for the retransmission).
56//!
57//! # Non-goals (explicit follow-ups)
58//! - Sender-side TLPKTDROP (rule 18-20): out of scope for the receiver.
59
60use alloc::collections::BTreeMap;
61use alloc::vec::Vec;
62use broadcast_common::stage::Timestamp;
63use core::time::Duration;
64
65use crate::arq::seq;
66
67/// How many fresh in-sequence packets make up one drift-sampling window
68/// (`private/specs-verified/rules/srt-tsbpd.md` rules 26-27: "based on packet count, not time
69/// duration"). The draft gives no number (the srt-tsbpd.md "Ambiguous" list
70/// says so); this matches the 1000-sample window of libsrt's drift tracer
71/// (`srtcore/tsbpd_time.h`), so both ends of a link correct at the same pace.
72pub const DRIFT_SAMPLE_COUNT: u32 = 1000;
73
74/// The most a drift correction may move `Drift` itself, in microseconds; any
75/// excess of the window average is folded into `TsbpdTimeBase` instead
76/// (libsrt's tracer bound, 5 ms — implementation-defined, see
77/// [`DRIFT_SAMPLE_COUNT`]).
78pub const DRIFT_MAX_US: i64 = 5_000;
79
80/// Minimum negotiated `TsbpdDelay` — 120 milliseconds
81/// (`private/specs-verified/rules/srt-tsbpd.md` rule 10, verbatim L2601-2603:
82/// "The value of minimum TsbpdDelay is negotiated during the SRT handshake
83/// exchange and is equal to 120 milliseconds.").
84const TSBPD_DELAY_MIN_MS: u64 = 120;
85
86/// A bound on how many sequence numbers one too-late skip may walk past a
87/// gap. Not a spec rule — a safety cap against an adversarial or corrupt
88/// sequence-number layout causing unbounded work in `release_ready`
89/// (the receiver bounds its own gap tracking by the flow window instead).
90const MAX_TLPKT_SKIP_SPAN: u32 = 1 << 16;
91
92/// A bound on how many not-yet-reached DROPREQ ranges are remembered.
93/// Not a spec rule — memory back-pressure against a peer flooding DROPREQs;
94/// once reached, further gaps are cleared by the too-late skip instead.
95const MAX_SKIPS: usize = 1024;
96
97/// `now` as whole microseconds, saturating (a `Duration` past ~584 000 years).
98/// Outcome of one [`TsbpdScheduler::tick`] call.
99#[derive(Debug, Clone, PartialEq, Eq, Default)]
100#[non_exhaustive]
101pub struct TickOutcome {
102    /// Sequence numbers released to the application in monotonically
103    /// increasing order — each at or after its `PktTsbpdTime`.
104    pub delivered: Vec<u32>,
105    /// Sequence numbers dropped because their play time was already past the
106    /// too-late threshold upon arrival (or before `tick` could release them),
107    /// or skipped as unrecoverable when a gap's earliest buffered successor
108    /// went too late (§4.6, rule 21).
109    pub dropped: Vec<u32>,
110}
111
112/// SRT receiver-side TSBPD delivery scheduler + Too-Late Packet Drop
113/// (`draft-sharabayko-srt-01` §4.5/§4.6).
114///
115/// Sans-IO: never reads a wall clock. All timing is driven by caller-supplied
116/// `now: core::time::Duration` in [`feed_data`](Self::feed_data) and
117/// [`tick`](Self::tick).
118///
119/// # State variables (per `private/specs-verified/rules/srt-tsbpd.md`)
120///
121/// - `TsbpdTimeBase` (µs, rule 12) — seeded at construction (signed), reflects
122///   the clock difference between receiver-local time and the sender's
123///   timestamp clock; moved by the drift tracer past [`DRIFT_MAX_US`].
124/// - `TsbpdDelay` (ms, rule 10) — receiver latency buffer, floor 120 ms.
125/// - `Drift` (µs, rules 24-27) — current drift correction; seeded at
126///   construction and re-estimated every [`DRIFT_SAMPLE_COUNT`] fresh packets.
127/// - `TLPKTDROP_THRESHOLD` (rule 19) — threshold beyond which a packet whose
128///   play time has passed is dropped; enabled by default.
129/// - `next_release` — the next sequence number to release (cumulative delivery
130///   point).
131#[derive(Debug)]
132pub struct TsbpdScheduler {
133    /// `TsbpdTimeBase` — time base reflecting the clock difference between
134    /// receiver-local time and the sender's packet-timestamping clock
135    /// (µs, `private/specs-verified/rules/srt-tsbpd.md` rule 12, §4.5.1.1 L2612-2618).
136    tsbpd_time_base: i64,
137    /// `TsbpdDelay` — receiver's buffer delay, in milliseconds
138    /// (rule 9-10, §4.5.1 L2588-2592).
139    tsbpd_delay_ms: u64,
140    /// `Drift` — time drift correction between sender/receiver clocks, in
141    /// microseconds, signed (rule 9, §4.7 L2757-2765).
142    drift_us: i64,
143    /// Running sum of the current drift window's samples (µs).
144    drift_sample_sum: i64,
145    /// Samples in the current drift window.
146    drift_sample_count: u32,
147    /// `TLPKTDROP_THRESHOLD` — threshold for too-late packet drop, in
148    /// microseconds (rule 19, §4.6 L2664-2670). Computed as
149    /// `1.25 * TsbpdDelay_ms * 1000` when constructed; exposed as a field
150    /// so the caller can customize.
151    tlpktdrop_threshold_us: u64,
152    /// Whether too-late packet drop is enabled (rule 23, §4.6 L2729-2733).
153    tlpktdrop_enabled: bool,
154    /// The next sequence number to release — cumulative delivery point.
155    next_release: u32,
156    /// Out-of-order packets buffered for timed delivery, keyed by sequence
157    /// number. Each entry holds the computed `PktTsbpdTime` in microseconds.
158    /// Unordered delivery (notably `BTreeMap`) — out-of-order packets are
159    /// inserted here until their predecessors arrive.
160    buffer: BTreeMap<u32, u64>,
161    /// The highest sequence number ever fed — used to detect monotonically
162    /// increasing deliveries when no gaps remain.
163    highest_fed: Option<u32>,
164    /// DROPREQ ranges (§3.2.9) the delivery cursor has not reached yet, as
165    /// inclusive `(first, last)` pairs. `release_ready` jumps the cursor past
166    /// them on arrival; pruned once passed.
167    pending_skips: Vec<(u32, u32)>,
168    /// The current reference point for unwrapping the 32-bit wire timestamp
169    /// into an always-increasing microsecond value (issue #1063): the most
170    /// recently *advanced-to* raw timestamp and the absolute value it was
171    /// unwrapped to. `None` until the first packet.
172    ts_unwrap_reference: Option<(u32, i64)>,
173}
174
175impl TsbpdScheduler {
176    /// Create a new TSBPD scheduler.
177    ///
178    /// # Parameters
179    ///
180    /// * `initial_seq` — the first expected sequence number (the peer's ISN).
181    /// * `tsbpd_time_base` — `TsbpdTimeBase` in microseconds (signed), seeded
182    ///   per rule 12 (`T_NOW - HSREQ_TIMESTAMP`).
183    /// * `tsbpd_delay` — `TsbpdDelay` (rule 10). A value below the minimum
184    ///   120 ms is silently raised to 120 ms.
185    /// * `drift_us` — initial `Drift` correction in microseconds, signed
186    ///   (rule 9); supply `0` when no drift estimate is available.
187    /// * `tlpktdrop_enabled` — whether too-late packet drop is enabled
188    ///   (rule 23).
189    /// * `tlpktdrop_threshold_us` — custom too-late threshold in microseconds.
190    ///   If `None`, the recommended default `1.25 × TsbpdDelay` is used
191    ///   (rule 19).
192    pub fn new(
193        initial_seq: u32,
194        tsbpd_time_base: i64,
195        tsbpd_delay: Duration,
196        drift_us: i64,
197        tlpktdrop_enabled: bool,
198        tlpktdrop_threshold_us: Option<u64>,
199    ) -> Self {
200        let tsbpd_delay_ms = u64::try_from(tsbpd_delay.as_millis())
201            .unwrap_or(u64::MAX)
202            .max(TSBPD_DELAY_MIN_MS);
203        let tlpktdrop_threshold_us = tlpktdrop_threshold_us.unwrap_or_else(|| {
204            // Recommended threshold: `1.25 × SRT_latency` (rule 19).
205            // TsbpdDelay is in ms, convert to µs. Use integer arithmetic:
206            // tsbpd_delay_ms * 1250 / 1000 = tsbpd_delay_ms * 5 / 4 * 1000
207            // Rounded up via (a * 5 + 3) / 4 to match ceil(1.25 * delay).
208            tsbpd_delay_ms
209                .saturating_mul(5)
210                .div_ceil(4)
211                .saturating_mul(1000)
212        });
213        TsbpdScheduler {
214            tsbpd_time_base,
215            tsbpd_delay_ms,
216            drift_us,
217            drift_sample_sum: 0,
218            drift_sample_count: 0,
219            tlpktdrop_threshold_us,
220            tlpktdrop_enabled,
221            next_release: initial_seq,
222            buffer: BTreeMap::new(),
223            highest_fed: None,
224            pending_skips: Vec::new(),
225            ts_unwrap_reference: None,
226        }
227    }
228
229    /// Computed PktTsbpdTime for a packet.
230    ///
231    /// Per `private/specs-verified/rules/srt-tsbpd.md` rule 9 (verbatim from
232    /// `draft-sharabayko-srt-01` L2581):
233    ///
234    /// > PktTsbpdTime = TsbpdTimeBase + PKT_TIMESTAMP + TsbpdDelay + Drift
235    ///
236    /// where:
237    /// - `TsbpdTimeBase` is in µs (rule 12).
238    /// - `PKT_TIMESTAMP` is in µs (§3.1).
239    /// - `TsbpdDelay` is in ms (rule 10), converted to µs by ×1000.
240    /// - `Drift` is in µs (rule 9).
241    ///
242    /// Computed in signed saturating arithmetic (the time base and drift are
243    /// signed); a play time before the epoch is clamped to `0` ("already due").
244    fn pkt_tsbpd_time(&self, unwrapped_pkt_timestamp_us: i64) -> u64 {
245        let sum = self
246            .tsbpd_time_base
247            .saturating_add(unwrapped_pkt_timestamp_us)
248            .saturating_add(
249                i64::try_from(self.tsbpd_delay_ms.saturating_mul(1000)).unwrap_or(i64::MAX),
250            )
251            .saturating_add(self.drift_us);
252        u64::try_from(sum).unwrap_or(0)
253    }
254
255    /// The current `TsbpdTimeBase` in microseconds (rule 12; moved by the
256    /// drift tracer past [`DRIFT_MAX_US`]).
257    #[cfg(test)]
258    pub(crate) fn time_base_us(&self) -> i64 {
259        self.tsbpd_time_base
260    }
261
262    /// The current `Drift` correction in microseconds (rule 9, §4.7).
263    pub fn drift_us(&self) -> i64 {
264        self.drift_us
265    }
266
267    /// Add one drift sample for a fresh packet that arrived at `now_us` with
268    /// (unwrapped) timestamp `unwrapped_ts`: how far its arrival is past the
269    /// `TsbpdTimeBase + PKT_TIMESTAMP` the receiver expected (§4.7). After
270    /// [`DRIFT_SAMPLE_COUNT`] samples the window average becomes the new
271    /// `Drift`; the part beyond [`DRIFT_MAX_US`] is folded into the time base
272    /// so `Drift` stays small (the same split libsrt's tracer makes). The
273    /// window is packet-count based, not time based (rule 27).
274    fn add_drift_sample(&mut self, now_us: u64, unwrapped_ts: i64) {
275        let arrival = i64::try_from(now_us).unwrap_or(i64::MAX);
276        let expected = self.tsbpd_time_base.saturating_add(unwrapped_ts);
277        self.drift_sample_sum = self
278            .drift_sample_sum
279            .saturating_add(arrival.saturating_sub(expected));
280        self.drift_sample_count += 1;
281        if self.drift_sample_count < DRIFT_SAMPLE_COUNT {
282            return;
283        }
284        let average = self.drift_sample_sum / i64::from(DRIFT_SAMPLE_COUNT);
285        self.drift_sample_sum = 0;
286        self.drift_sample_count = 0;
287        let overdrift = if average > DRIFT_MAX_US {
288            average - DRIFT_MAX_US
289        } else if average < -DRIFT_MAX_US {
290            average + DRIFT_MAX_US
291        } else {
292            0
293        };
294        self.tsbpd_time_base = self.tsbpd_time_base.saturating_add(overdrift);
295        self.drift_us = average - overdrift;
296    }
297
298    /// Extend a packet's raw 32-bit wire timestamp into an always-increasing
299    /// microsecond value, correctly spanning a real wraparound past `2^32`
300    /// microseconds (~71.58 minutes, `private/specs-verified/rules/srt-tsbpd.md` rule 15) —
301    /// without this, `pkt_tsbpd_time` fed the raw value straight through, so
302    /// every packet after a wrap computed a `PktTsbpdTime` far in the past
303    /// (the field dropped back near 0) and got Too-Late-Packet-Dropped
304    /// forever (issue #1063).
305    ///
306    /// Mirrors `arq::seq::seq_diff` (signed circular distance) one bit wider:
307    /// the shortest signed delta from the current reference's raw value to
308    /// `raw`, added to the reference's absolute value. Correct as long as
309    /// consecutive *reference advances* stay within +/-2^31 us (~35.79 min)
310    /// of each other — true for any stream whose packets keep arriving more
311    /// often than that. The reference only ever advances forward (to the
312    /// highest absolute value produced so far); an out-of-order/retransmitted
313    /// packet earlier than the current reference is still unwrapped
314    /// correctly against it, it just doesn't move the reference.
315    fn unwrap_timestamp(&mut self, raw: u32) -> i64 {
316        let Some((ref_raw, ref_abs)) = self.ts_unwrap_reference else {
317            self.ts_unwrap_reference = Some((raw, i64::from(raw)));
318            return i64::from(raw);
319        };
320        let mut delta = i64::from(raw) - i64::from(ref_raw);
321        if delta < -(1i64 << 31) {
322            delta += 1i64 << 32;
323        } else if delta >= (1i64 << 31) {
324            delta -= 1i64 << 32;
325        }
326        let abs = ref_abs.saturating_add(delta);
327        if abs > ref_abs {
328            self.ts_unwrap_reference = Some((raw, abs));
329        }
330        abs
331    }
332
333    /// Feed a received data packet's sequence number and timestamp.
334    ///
335    /// Returns [`TickOutcome`] with any packets that can be immediately
336    /// delivered (when the packet fills the next-released sequence gap and
337    /// its play time is at or before `now`), plus any packets that are
338    /// already too late on arrival.
339    ///
340    /// # Parameters
341    ///
342    /// * `seq_number` — the data packet's 31-bit sequence number.
343    /// * `pkt_timestamp` — the data packet's 32-bit timestamp (§3.1).
344    /// * `now` — current receiver time since the fixed epoch (the `T_NOW`
345    ///   used to decide whether `PktTsbpdTime ≤ now`).
346    pub fn feed_data(
347        &mut self,
348        seq_number: u32,
349        pkt_timestamp: u32,
350        now: Timestamp,
351    ) -> TickOutcome {
352        let now_us = now.as_micros();
353        let unwrapped_ts = self.unwrap_timestamp(pkt_timestamp);
354
355        // Track highest fed (monotonic, for detecting when delivery advances
356        // with no gap). A *fresh* packet — the very next sequence number, not
357        // a retransmission or a gap-jumper — is a clean drift sample: its
358        // arrival is not delayed by a NAK round trip.
359        match self.highest_fed {
360            None => {
361                self.highest_fed = Some(seq_number);
362                self.add_drift_sample(now_us, unwrapped_ts);
363            }
364            Some(h) if seq::seq_gt(seq_number, h) => {
365                if seq_number == seq::seq_next(h) {
366                    self.add_drift_sample(now_us, unwrapped_ts);
367                }
368                self.highest_fed = Some(seq_number);
369            }
370            _ => {}
371        }
372        // After the drift sample: it may have just moved the time base.
373        let pkt_tsbpd_time = self.pkt_tsbpd_time(unwrapped_ts);
374
375        // Rule 17-18/21: drop a packet whose PktTsbpdTime is before
376        // (now - TLPKTDROP_THRESHOLD).
377        if self.tlpktdrop_enabled {
378            let drop_before = now_us.saturating_sub(self.tlpktdrop_threshold_us);
379            if pkt_tsbpd_time < drop_before {
380                // Packet is too late — drop it immediately.
381                let mut dropped = alloc::vec![seq_number];
382                // Advance past the dropped sequence if it's the next
383                // expected, so the queue doesn't stall.
384                if seq_number == self.next_release {
385                    self.next_release = seq::seq_next(seq_number);
386                }
387                self.buffer.remove(&seq_number);
388                // Try to release any now-unblocked packets that are also
389                // too-late (the receiver-buffer read pseudocode, rule 21:
390                // "Drop packets which buffer position number is less than
391                // i").
392                let (delivered, mut later_dropped) = self.release_ready(now_us);
393                dropped.append(&mut later_dropped);
394                return TickOutcome { delivered, dropped };
395            }
396        }
397
398        // Ignore duplicate of an already-delivered sequence.
399        if !seq::seq_lt(seq_number, self.next_release) {
400            // Insert into the buffer (or replace — a retransmission arriving
401            // after the original is fine; the PktTsbpdTime is the same per
402            // rule 4 L2496-2502).
403            self.buffer.insert(seq_number, pkt_tsbpd_time);
404        }
405
406        let (delivered, dropped) = self.release_ready(now_us);
407        TickOutcome { delivered, dropped }
408    }
409
410    /// Advance the virtual clock and release/drop packets whose time has
411    /// come.
412    ///
413    /// Call this periodically (e.g. every millisecond) to drain the buffer.
414    /// Packets whose `PktTsbpdTime ≤ now` are released in sequence order.
415    /// If too-late drop is enabled, packets whose play time has already
416    /// passed the threshold are dropped instead.
417    pub fn tick(&mut self, now: Timestamp) -> TickOutcome {
418        let now_us = now.as_micros();
419        let (delivered, dropped) = self.release_ready(now_us);
420        TickOutcome { delivered, dropped }
421    }
422
423    /// Earliest buffered packet play time strictly after `now`, if any.
424    ///
425    /// A buffered packet whose time has passed but that cannot be released
426    /// (waiting for a gap with TLPKTDROP off) yields no wake-up: it is
427    /// re-examined on the next event, never by a busy timer.
428    pub fn next_release_after(&self, now: Timestamp) -> Option<Duration> {
429        let now_us = now.as_micros();
430        self.buffer
431            .values()
432            .copied()
433            .filter(|&t| t > now_us)
434            .min()
435            .map(Duration::from_micros)
436    }
437
438    /// Release all packets that are ready for delivery in sequence order.
439    ///
440    /// Walks forward from `self.next_release` while the next packet is
441    /// present in the buffer AND its `PktTsbpdTime ≤ now_us`. Returns the
442    /// released sequence numbers plus those dropped as too late. If too-late
443    /// drop is enabled, packets whose scheduled play time is already past
444    /// `(now_us - TLPKTDROP_THRESHOLD)` are dropped instead of delivered
445    /// (matching the receiver-buffer read pseudocode, rule 21: "if
446    /// T_NOW < PktTsbpdTime: continue;" / "Drop packets which buffer
447    /// position number is less than i;" / "Deliver packet ...").
448    ///
449    /// With too-late drop enabled, a *missing* head-of-line packet is also
450    /// skipped as soon as the earliest buffered successor's play time has
451    /// arrived: that successor is then delivered (or dropped only if it is in
452    /// turn past its own too-late threshold), while the missing positions
453    /// before it are reported dropped (§4.6; rule 21's "Drop packets which
454    /// buffer position number is less than i" / "Deliver packet with the
455    /// buffer position i"). With too-late drop disabled the scheduler keeps
456    /// waiting for the gap indefinitely, preserving reliable in-order
457    /// delivery.
458    ///
459    /// The logic here follows the pseudocode from
460    /// `private/specs-verified/rules/srt-tsbpd.md` rule 21 (L2693-2715):
461    ///
462    /// ```text
463    /// while(True) {
464    ///     i = next_avail();
465    ///     PktTsbpdTime = delivery_time(i);
466    ///     if T_NOW < PktTsbpdTime:
467    ///         continue;
468    ///     Drop packets which buffer position number is less than i;
469    ///     Deliver packet with the buffer position i;
470    ///     pos = i + 1;
471    /// }
472    /// ```
473    fn release_ready(&mut self, now_us: u64) -> (Vec<u32>, Vec<u32>) {
474        let mut delivered = Vec::new();
475        let mut dropped = Vec::new();
476
477        loop {
478            if let Some(&tsbpd_time) = self.buffer.get(&self.next_release) {
479                if now_us < tsbpd_time {
480                    break; // not yet time
481                }
482
483                // Too-late drop check: if PktTsbpdTime is so far in the past
484                // that it's past the drop threshold, drop instead of deliver.
485                if self.tlpktdrop_enabled {
486                    let drop_before = now_us.saturating_sub(self.tlpktdrop_threshold_us);
487                    if tsbpd_time < drop_before {
488                        // Drop this packet and any others before the skip
489                        // point. The receiver-buffer pseudocode says "Drop
490                        // packets which buffer position number is less than
491                        // i" — i.e. we drop the packet at position i and
492                        // advance past it. (rule 21, L2693-2715)
493                        self.buffer.remove(&self.next_release);
494                        dropped.push(self.next_release);
495                        self.next_release = seq::seq_next(self.next_release);
496                        continue;
497                    }
498                }
499
500                // Deliver.
501                self.buffer.remove(&self.next_release);
502                delivered.push(self.next_release);
503                self.next_release = seq::seq_next(self.next_release);
504                continue;
505            }
506
507            // Gap at `next_release`. A DROPREQ (§3.2.9) the sender already
508            // announced for this range: those packets are gone by its own
509            // admission — jump past them immediately, in any delivery mode.
510            if let Some(pos) = self
511                .pending_skips
512                .iter()
513                .position(|&(f, l)| seq::seq_in_closed_range(self.next_release, f, l))
514            {
515                let (_, last) = self.pending_skips.remove(pos);
516                self.next_release = seq::seq_next(last);
517                continue;
518            }
519
520            // Too-late drop disabled → wait for the missing packet
521            // (reliable delivery).
522            if !self.tlpktdrop_enabled {
523                break;
524            }
525
526            // §4.6 / rule 21 pseudocode: `i = next_avail()` — the first
527            // buffered packet at or after the cursor. If its play time has
528            // not arrived, keep waiting (a retransmission of the missing one
529            // could still make it). Once it HAS arrived, drop the missing
530            // positions before `i` and let the loop deliver `i` itself — it
531            // is dropped only if it is in turn past its own too-late
532            // threshold, via the branch above.
533            let Some((&skip_to, &skip_time)) = self
534                .buffer
535                .range(self.next_release..)
536                .chain(self.buffer.range(..self.next_release))
537                .next()
538            else {
539                break;
540            };
541            if now_us < skip_time {
542                break; // T_NOW < PktTsbpdTime(i) — keep waiting
543            }
544            // Defensive bound against an adversarial sequence-number layout
545            // (the ARQ receiver bounds its tracking by the flow window): a skip span
546            // this large means the buffered timestamps cannot be trusted to
547            // describe one contiguous live stream — wait rather than walk.
548            if !u32::try_from(seq::seq_diff(skip_to, self.next_release))
549                .is_ok_and(|span| span <= MAX_TLPKT_SKIP_SPAN)
550            {
551                break;
552            }
553            // Drop everything before the skip point (rule 21: "Drop packets
554            // which buffer position number is less than i") — including any
555            // buffered entries whose play time has already been overtaken.
556            let mut s = self.next_release;
557            while s != skip_to {
558                self.buffer.remove(&s);
559                dropped.push(s);
560                s = seq::seq_next(s);
561            }
562            self.next_release = skip_to;
563        }
564
565        (delivered, dropped)
566    }
567
568    /// Whether Too-Late Packet Drop is enabled (§4.6): `false` makes the
569    /// scheduler wait for a missing packet indefinitely.
570    pub fn tlpktdrop_enabled(&self) -> bool {
571        self.tlpktdrop_enabled
572    }
573
574    /// The next sequence number expected for release.
575    pub fn next_release(&self) -> u32 {
576        self.next_release
577    }
578
579    /// Mark the inclusive circular range `first..=last` as permanently
580    /// unavailable — the peer sent a DROPREQ (§3.2.9) announcing it will
581    /// never deliver those packets.
582    ///
583    /// Any buffered entries inside the range are discarded (the sender has
584    /// given up on them; delivering them late would break message integrity),
585    /// and when the delivery cursor reaches the range it jumps past it: if
586    /// `next_release` is already inside, immediately; otherwise the range is
587    /// recorded so [`Self::tick`]/[`Self::feed_data`] skip it the moment the
588    /// cursor arrives — unblocking everything behind the gap without waiting
589    /// for the too-late threshold. A `last` preceding `first` is a malformed
590    /// (empty) range and ignored.
591    //
592    // Public so a sans-IO driver other than the tokio adapter (`crate::io`) can apply a DROPREQ
593    // and the Too-Late Packet Drop fake ACK.
594    pub fn skip_range(&mut self, first: u32, last: u32) {
595        if seq::seq_diff(last, first) < 0 {
596            // `last` precedes `first` — a malformed DROPREQ range; ignoring
597            // it is safer than treating every sequence as skipped.
598            return;
599        }
600        self.buffer
601            .retain(|&s, _| !seq::seq_in_closed_range(s, first, last));
602        // Ranges the cursor has already passed are dead weight — prune them.
603        self.pending_skips
604            .retain(|&(_, l)| !seq::seq_lt(l, self.next_release));
605        if seq::seq_in_closed_range(self.next_release, first, last) {
606            self.next_release = seq::seq_next(last);
607        } else if seq::seq_lt(self.next_release, first) && self.pending_skips.len() < MAX_SKIPS {
608            // Ahead of the cursor: remember it so `release_ready` jumps the
609            // gap when it gets there. Bounded by `MAX_SKIPS`; a peer that
610            // floods DROPREQs beyond that is served by the too-late skip.
611            self.pending_skips.push((first, last));
612        }
613    }
614
615    /// Number of packets currently buffered and awaiting their play time.
616    pub fn buffered_count(&self) -> usize {
617        self.buffer.len()
618    }
619
620    /// Whether the buffer has a gap (the next expected sequence number is
621    /// not present).
622    pub fn has_gap(&self) -> bool {
623        !self.buffer.contains_key(&self.next_release)
624    }
625}
626
627#[cfg(test)]
628mod tests {
629    use super::*;
630    use alloc::vec;
631    use core::time::Duration;
632
633    /// A `Timestamp` at `d` microseconds since the test epoch.
634    fn ts(d: Duration) -> Timestamp {
635        Timestamp::from_micros(u64::try_from(d.as_micros()).expect("in range"))
636    }
637
638    const TIME_BASE: u64 = 1_000_000; // arbitrary TsbpdTimeBase
639    const TIME_BASE_I64: i64 = 1_000_000; // the same, as the scheduler's signed seed
640    const DELAY_MS: u64 = 120; // minimum
641    const ISN: u32 = 0;
642
643    /// Helper: default scheduler for tests.
644    fn sched() -> TsbpdScheduler {
645        TsbpdScheduler::new(
646            ISN,
647            TIME_BASE_I64,
648            Duration::from_millis(DELAY_MS),
649            0,
650            true,
651            None,
652        )
653    }
654
655    #[test]
656    fn next_release_after_is_the_earliest_future_play_time() {
657        let mut s = TsbpdScheduler::new(0, 0, Duration::from_millis(DELAY_MS), 0, true, None);
658        assert_eq!(
659            s.next_release_after(Timestamp::ZERO),
660            None,
661            "nothing buffered"
662        );
663        let _ = s.feed_data(0, 0, Timestamp::ZERO);
664        let t = s
665            .next_release_after(Timestamp::ZERO)
666            .expect("one packet buffered");
667        assert_eq!(t, Duration::from_millis(DELAY_MS));
668        assert_eq!(s.next_release_after(ts(t)), None, "strictly after");
669        let _ = s.tick(ts(t));
670        assert_eq!(
671            s.next_release_after(Timestamp::ZERO),
672            None,
673            "released packets leave the buffer"
674        );
675    }
676
677    #[test]
678    fn a_stuck_gap_without_tlpktdrop_produces_no_busy_wakeup() {
679        let mut s = TsbpdScheduler::new(0, 0, Duration::from_millis(DELAY_MS), 0, false, None);
680        let _ = s.feed_data(2, 0, Timestamp::ZERO); // 0 and 1 missing, drop disabled
681        let late = Timestamp::from_millis(DELAY_MS * 10);
682        let _ = s.tick(late);
683        assert_eq!(
684            s.next_release_after(late),
685            None,
686            "past-due but blocked: wait for events, not for time"
687        );
688    }
689
690    #[test]
691    fn pkt_tsbpd_time_formula() {
692        let s = sched();
693        // PktTsbpdTime = TsbpdTimeBase + PKT_TIMESTAMP + TsbpdDelay_us + Drift
694        let ts = 5000u32;
695        let expected = TIME_BASE + u64::from(ts) + DELAY_MS * 1000;
696        assert_eq!(s.pkt_tsbpd_time(i64::from(ts)), expected);
697    }
698
699    #[test]
700    fn in_order_after_delay() {
701        let mut s = sched();
702        let ts_a = 0u32;
703        let ts_b = 10_000u32; // 10 ms later
704
705        // Feed at now=0 — neither is deliverable yet (PktTsbpdTime is
706        // in the future).
707        let outcome = s.feed_data(0, ts_a, Timestamp::ZERO);
708        assert!(outcome.delivered.is_empty());
709        assert!(outcome.dropped.is_empty());
710        assert_eq!(s.buffered_count(), 1);
711
712        let outcome = s.feed_data(1, ts_b, Timestamp::ZERO);
713        assert!(outcome.delivered.is_empty());
714        assert!(outcome.dropped.is_empty());
715        assert_eq!(s.buffered_count(), 2);
716
717        // Advance clock past packet 1's PktTsbpdTime but not packet 2's.
718        let pkt1_tsbpd = TIME_BASE + u64::from(ts_a) + DELAY_MS * 1000;
719        let outcome = s.tick(Timestamp::from_micros(pkt1_tsbpd));
720        assert_eq!(outcome.delivered, vec![0]);
721
722        let pkt2_tsbpd = TIME_BASE + u64::from(ts_b) + DELAY_MS * 1000;
723        let outcome = s.tick(Timestamp::from_micros(pkt2_tsbpd));
724        assert_eq!(outcome.delivered, vec![1]);
725        assert!(s.buffer.is_empty());
726    }
727
728    #[test]
729    fn out_of_order_arrival() {
730        let mut s = sched();
731        // Packet 1 arrives out of order before packet 0 — fed well before its
732        // play time, so it buffers waiting for the gap (at the play time
733        // itself rule 21 would skip the gap; see
734        // `gap_skip_delivers_successor_at_its_play_time`).
735        let ts = 10_000u32;
736        let pkt1_tsbpd = TIME_BASE + 10_000 + DELAY_MS * 1000;
737        let outcome = s.feed_data(1, ts, Timestamp::ZERO);
738        assert!(outcome.delivered.is_empty());
739        assert_eq!(s.buffered_count(), 1);
740
741        // Now packet 0 arrives — tick at the same time so that both are
742        // past their play time and can be delivered together.
743        let outcome = s.feed_data(0, 0, Timestamp::from_micros(pkt1_tsbpd));
744        // Both should be delivered in order.
745        assert_eq!(outcome.delivered, vec![0, 1]);
746        assert!(s.buffer.is_empty());
747    }
748
749    #[test]
750    fn too_late_drop_on_arrival() {
751        let mut s = sched();
752        // The drop threshold is 1.25 × 120ms = 150ms.
753        // Feed a packet whose PktTsbpdTime is deep in the past — well past
754        // the drop threshold.
755        let pkt_tsbpd = TIME_BASE + DELAY_MS * 1000;
756        // Arrive now at PktTsbpdTime + threshold + 1 µs — just past the
757        // drop window.
758        let threshold_us = (DELAY_MS * 5).div_ceil(4) * 1000;
759        let very_late_now = Timestamp::from_micros(pkt_tsbpd + threshold_us + 1);
760        let outcome = s.feed_data(0, 0, very_late_now);
761        assert!(
762            outcome.delivered.is_empty(),
763            "should not deliver late packet"
764        );
765        assert_eq!(outcome.dropped, vec![0]);
766    }
767
768    #[test]
769    fn too_late_drop_buffered() {
770        // Packets 1 and 2 arrive while packet 0 is missing. At packet 1's
771        // play time the gap is skipped and packet 1 delivered (§4.6 / rule
772        // 21); a buffered packet that itself goes past its too-late threshold
773        // — here packet 2, starved of ticks between the two clock jumps — is
774        // dropped instead.
775        let mut s = TsbpdScheduler::new(
776            0,
777            TIME_BASE_I64,
778            Duration::from_millis(DELAY_MS),
779            0,
780            true,
781            None,
782        );
783
784        // Feed packets 1 and 2 well before their play times — they buffer.
785        s.feed_data(1, 10_000, Timestamp::ZERO);
786        s.feed_data(2, 20_000, Timestamp::ZERO);
787        assert_eq!(s.buffered_count(), 2);
788
789        // At packet 1's play time the missing packet 0 is reported dropped
790        // and packet 1 delivered — not thrown away with the gap.
791        let pkt1_tsbpd = TIME_BASE + 10_000 + DELAY_MS * 1000;
792        let outcome = s.tick(Timestamp::from_micros(pkt1_tsbpd));
793        assert_eq!(outcome.delivered, vec![1]);
794        assert_eq!(outcome.dropped, vec![0]);
795
796        // Packet 2 is now left sitting past its too-late threshold.
797        let pkt2_tsbpd = TIME_BASE + 20_000 + DELAY_MS * 1000;
798        let threshold = (DELAY_MS * 5).div_ceil(4) * 1000;
799        let outcome = s.tick(Timestamp::from_micros(pkt2_tsbpd + threshold + 1));
800        assert!(outcome.delivered.is_empty());
801        assert_eq!(outcome.dropped, vec![2]);
802
803        // A late duplicate of the skipped packet 0 is a no-op — the cursor
804        // has already advanced past it.
805        let outcome = s.feed_data(0, 0, Timestamp::from_micros(pkt2_tsbpd + threshold * 10));
806        assert!(outcome.delivered.is_empty());
807        assert_eq!(s.next_release(), 3);
808        assert_eq!(s.buffered_count(), 0);
809    }
810
811    #[test]
812    fn sequence_order_preserved() {
813        let mut s = sched();
814        // Deliver several packets in order.
815        let ts_step = 10_000u32;
816        let num_packets = 5;
817        for i in 0..num_packets {
818            s.feed_data(i, ts_step * i, Timestamp::ZERO);
819        }
820        // All are buffered.
821        assert_eq!(s.buffered_count(), num_packets as usize);
822
823        // Tick past the last packet's play time.
824        let last_tsbpd =
825            TIME_BASE + u64::from(ts_step) * (num_packets - 1) as u64 + DELAY_MS * 1000;
826        let outcome = s.tick(Timestamp::from_micros(last_tsbpd));
827        assert_eq!(outcome.delivered, (0..num_packets).collect::<Vec<_>>());
828    }
829
830    #[test]
831    fn timestamp_wrap_smoke() {
832        // Issue #1063: a real wraparound of the 32-bit wire timestamp
833        // (`past_wrap` arriving after `near_wrap`, having actually wrapped
834        // past `2^32` microseconds) must unwrap to an ever-*increasing*
835        // absolute time — not the raw numeric value, which drops back near
836        // 0 and would make `past_wrap`'s `PktTsbpdTime` look far in the
837        // *past* relative to `near_wrap`'s (the pre-fix bug: every packet
838        // after a real wrap computed a play time the receiver's clock had
839        // already passed, so Too-Late-Packet-Drop discarded it forever).
840        let mut s = TsbpdScheduler::new(
841            0,
842            TIME_BASE_I64,
843            Duration::from_millis(DELAY_MS),
844            0,
845            false,
846            None,
847        );
848        // A timestamp near the 32-bit max value.
849        let near_wrap: u32 = 0xFFFF_FF00u32;
850        // The same clock, 756 us later, having wrapped past 0
851        // (`0x1_0000_0000 - 0xFFFF_FF00 + 500 = 256 + 500 = 756`).
852        let past_wrap: u32 = 500;
853
854        let outcome = s.feed_data(0, near_wrap, Timestamp::ZERO);
855        assert!(outcome.delivered.is_empty());
856
857        let outcome = s.feed_data(1, past_wrap, Timestamp::ZERO);
858        assert!(outcome.delivered.is_empty());
859        assert_eq!(s.buffered_count(), 2);
860
861        // Correctly unwrapped, pkt1 (the later, post-wrap packet) plays
862        // 756 µs AFTER pkt0. Naively widening the raw u32 would give pkt1 a
863        // play time ~71 minutes BEFORE pkt0's, so it would be released the
864        // instant pkt0 is — that is what the checkpoints below pin down.
865        let pkt0_tsbpd = TIME_BASE + u64::from(near_wrap) + DELAY_MS * 1000;
866        let outcome = s.tick(Timestamp::from_micros(pkt0_tsbpd));
867        assert_eq!(
868            outcome.delivered,
869            vec![0],
870            "at pkt0's play time only pkt0 is due"
871        );
872        let outcome = s.tick(Timestamp::from_micros(pkt0_tsbpd + 755));
873        assert!(outcome.delivered.is_empty(), "pkt1 is 756 µs later");
874        let outcome = s.tick(Timestamp::from_micros(pkt0_tsbpd + 756));
875        assert_eq!(outcome.delivered, vec![1]);
876    }
877
878    #[test]
879    fn unwrap_timestamp_stays_monotonic_across_many_wraps() {
880        // A longer-lived connection wraps the 32-bit timestamp every
881        // ~71.58 min. Simulate one by walking the raw wire value forward in
882        // realistic, sub-half-range steps (1 real second each, `wrapping_add`
883        // so it genuinely rolls over at `u32::MAX` the way the wire field
884        // does) through more than two full wraps, and confirm the unwrapped
885        // absolute value strictly increases by exactly one step every time
886        // — never resetting or going backward at either wrap boundary.
887        let mut s = TsbpdScheduler::new(
888            0,
889            TIME_BASE_I64,
890            Duration::from_millis(DELAY_MS),
891            0,
892            false,
893            None,
894        );
895        const STEP: u32 = 1_000_000; // 1 second in microseconds
896        let iterations = (u64::from(u32::MAX) / u64::from(STEP)) * 2 + 10; // > 2 wraps
897
898        let mut raw: u32 = 0;
899        let mut expected_abs = i64::from(raw);
900        let mut prev_abs = s.unwrap_timestamp(raw);
901        assert_eq!(prev_abs, expected_abs);
902
903        for _ in 0..iterations {
904            raw = raw.wrapping_add(STEP);
905            expected_abs += i64::from(STEP);
906            let abs = s.unwrap_timestamp(raw);
907            assert_eq!(abs, expected_abs, "raw={raw:#x}");
908            assert!(abs > prev_abs, "prev={prev_abs} abs={abs}");
909            prev_abs = abs;
910        }
911    }
912
913    #[test]
914    fn unwrap_timestamp_handles_reordered_packet_without_moving_reference() {
915        // An out-of-order/retransmitted packet earlier than the current
916        // reference must still unwrap correctly against it, and must not
917        // itself move the reference backward.
918        let mut s = TsbpdScheduler::new(
919            0,
920            TIME_BASE_I64,
921            Duration::from_millis(DELAY_MS),
922            0,
923            false,
924            None,
925        );
926        let a = s.unwrap_timestamp(10_000);
927        let b = s.unwrap_timestamp(20_000); // reference advances to here
928        let reordered = s.unwrap_timestamp(15_000); // arrives late, between a and b
929        assert_eq!(a, 10_000);
930        assert_eq!(b, 20_000);
931        assert_eq!(reordered, 15_000);
932        // Reference must still be at `b` (20_000), not `reordered`: the next
933        // packet close to `b` unwraps relative to `b`, not `reordered`.
934        let next = s.unwrap_timestamp(20_500);
935        assert_eq!(next, 20_500);
936    }
937
938    #[test]
939    fn a_reordered_pre_wrap_packet_keeps_its_play_time_before_the_first_post_wrap_one() {
940        let mut s = TsbpdScheduler::new(0, 0, Duration::from_millis(DELAY_MS), 0, false, None);
941        let _ = s.feed_data(1, 5, Timestamp::ZERO);
942        let _ = s.feed_data(0, u32::MAX - 15, Timestamp::ZERO);
943        assert_eq!(
944            s.next_release_after(Timestamp::ZERO),
945            Some(Duration::from_micros(DELAY_MS * 1000 - 16)),
946            "16 us before the wrap point, so before the epoch the post-wrap packet seeded"
947        );
948    }
949
950    #[test]
951    fn minimum_delay_floor_applied() {
952        // A delay below 120 ms should be silently raised.
953        let s = TsbpdScheduler::new(0, TIME_BASE_I64, Duration::from_millis(10), 0, false, None);
954        let ts = 0u32;
955        // The computed PktTsbpdTime should use 120 ms, not 10 ms.
956        let expected = TIME_BASE + u64::from(ts) + TSBPD_DELAY_MIN_MS * 1000;
957        assert_eq!(s.pkt_tsbpd_time(i64::from(ts)), expected);
958    }
959
960    #[test]
961    fn tlpktdrop_disabled_never_drops() {
962        let mut s = TsbpdScheduler::new(
963            0,
964            TIME_BASE_I64,
965            Duration::from_millis(DELAY_MS),
966            0,
967            false,
968            None,
969        );
970        // Feed a packet very late but with tlpktdrop disabled.
971        let ts = 0u32;
972        let very_late_now =
973            Timestamp::from_micros(TIME_BASE + u64::from(ts) + DELAY_MS * 1000 + 1_000_000);
974        let outcome = s.feed_data(0, ts, very_late_now);
975        // Should be delivered (not dropped) because tlpktdrop is disabled.
976        assert_eq!(outcome.delivered, vec![0]);
977        assert!(outcome.dropped.is_empty());
978    }
979
980    #[test]
981    fn gap_blocks_delivery() {
982        // Reliable mode (too-late drop disabled): a gap blocks delivery no
983        // matter how far the clock advances — every payload must arrive.
984        // With too-late drop enabled the gap is instead skipped at the
985        // successor's play time (§4.6 / rule 21); see
986        // `gap_skip_delivers_successor_at_its_play_time`.
987        let mut s = TsbpdScheduler::new(
988            0,
989            TIME_BASE_I64,
990            Duration::from_millis(DELAY_MS),
991            0,
992            false,
993            None,
994        );
995        // Feed packets 1 and 2 but not 0.
996        s.feed_data(
997            1,
998            10_000,
999            Timestamp::from_micros(TIME_BASE + 10_000 + DELAY_MS * 1000),
1000        );
1001        s.feed_data(
1002            2,
1003            20_000,
1004            Timestamp::from_micros(TIME_BASE + 20_000 + DELAY_MS * 1000),
1005        );
1006        assert!(s.has_gap());
1007        assert_eq!(s.buffered_count(), 2);
1008
1009        // Even ticking far in the future should not deliver without packet 0.
1010        let outcome = s.tick(Timestamp::from_micros(
1011            TIME_BASE + 100_000 + DELAY_MS * 1000,
1012        ));
1013        assert!(outcome.delivered.is_empty());
1014        assert!(s.has_gap());
1015    }
1016
1017    #[test]
1018    fn gap_skip_delivers_successor_at_its_play_time() {
1019        // §4.6 / rule 21: when the first buffered packet after a gap reaches
1020        // its play time, the missing positions before it are dropped and IT
1021        // is delivered — not thrown away with the gap.
1022        let mut s = sched(); // too-late drop enabled
1023        s.feed_data(1, 10_000, Timestamp::ZERO);
1024        s.feed_data(2, 20_000, Timestamp::ZERO);
1025        assert_eq!(s.buffered_count(), 2);
1026
1027        let pkt1_tsbpd = TIME_BASE + 10_000 + DELAY_MS * 1000;
1028        let outcome = s.tick(Timestamp::from_micros(pkt1_tsbpd));
1029        assert_eq!(
1030            outcome.delivered,
1031            vec![1],
1032            "the successor must be delivered at its play time"
1033        );
1034        assert_eq!(
1035            outcome.dropped,
1036            vec![0],
1037            "the missing packet must be reported as dropped"
1038        );
1039
1040        let pkt2_tsbpd = TIME_BASE + 20_000 + DELAY_MS * 1000;
1041        let outcome = s.tick(Timestamp::from_micros(pkt2_tsbpd));
1042        assert_eq!(outcome.delivered, vec![2]);
1043    }
1044
1045    #[test]
1046    fn duplicate_arrival_does_not_advance_clock() {
1047        let mut s = sched();
1048        let ts = 0u32;
1049        let now = Timestamp::from_micros(TIME_BASE + DELAY_MS * 1000);
1050        s.feed_data(0, ts, now);
1051        assert_eq!(s.buffered_count(), 0); // delivered immediately
1052
1053        // Same seq number again (duplicate retransmission) — should be a
1054        // no-op (already advanced past it).
1055        s.feed_data(0, ts, now);
1056        assert_eq!(s.buffered_count(), 0, "duplicate must not re-buffer");
1057        assert_eq!(s.next_release(), 1);
1058    }
1059
1060    /// Feed `n` fresh in-sequence packets starting at `first_seq`: packet `i`
1061    /// (timestamp `i * 1000` µs) arrives `i * skew_us` after the instant its
1062    /// `TsbpdTimeBase + PKT_TIMESTAMP` predicts — a clock that runs
1063    /// `skew_us` per millisecond fast (positive) or slow (negative).
1064    fn feed_skewed_window(s: &mut TsbpdScheduler, first_seq: u32, n: u32, skew_us: i64) {
1065        for i in 0..n {
1066            let predicted = s.time_base_us() + i64::from(i) * 1000;
1067            let arrival = predicted + i64::from(i) * skew_us;
1068            s.feed_data(
1069                first_seq + i,
1070                i * 1000,
1071                Timestamp::from_micros(u64::try_from(arrival).unwrap()),
1072            );
1073        }
1074    }
1075
1076    /// r08-SRT-W9, §4.7 rules 26-27: after one packet-count window of samples
1077    /// the average arrival error becomes `Drift`; the part beyond
1078    /// `DRIFT_MAX_US` moves the time base so `Drift` stays small. Window
1079    /// average here: `20 µs * (0 + 1 + ... + 999) / 1000` = 9990 µs.
1080    #[test]
1081    fn a_fast_sender_clock_is_corrected_after_one_window() {
1082        let mut s = TsbpdScheduler::new(
1083            0,
1084            TIME_BASE_I64,
1085            Duration::from_millis(DELAY_MS),
1086            0,
1087            false,
1088            None,
1089        );
1090        feed_skewed_window(&mut s, 0, DRIFT_SAMPLE_COUNT, 20);
1091        assert_eq!(s.drift_us(), 5_000, "drift saturates at DRIFT_MAX_US");
1092        assert_eq!(
1093            s.time_base_us(),
1094            TIME_BASE_I64 + 4_990,
1095            "the 4 990 µs beyond the bound move the time base"
1096        );
1097        // The correction is applied to later packets' play time (rule 9).
1098        assert_eq!(
1099            s.pkt_tsbpd_time(0),
1100            u64::try_from(TIME_BASE_I64 + 4_990 + 5_000).unwrap() + DELAY_MS * 1000
1101        );
1102    }
1103
1104    /// The same, for a slow clock: negative drift, negative base correction.
1105    #[test]
1106    fn a_slow_sender_clock_is_corrected_after_one_window() {
1107        let mut s = TsbpdScheduler::new(
1108            0,
1109            TIME_BASE_I64,
1110            Duration::from_millis(DELAY_MS),
1111            0,
1112            false,
1113            None,
1114        );
1115        feed_skewed_window(&mut s, 0, DRIFT_SAMPLE_COUNT, -20);
1116        assert_eq!(s.drift_us(), -5_000);
1117        assert_eq!(s.time_base_us(), TIME_BASE_I64 - 4_990);
1118    }
1119
1120    /// A small error (average 999 µs, within `DRIFT_MAX_US`) is all `Drift`,
1121    /// and nothing happens before the window is full.
1122    #[test]
1123    fn a_small_drift_is_applied_as_drift_only_and_only_at_the_window_boundary() {
1124        let mut s = TsbpdScheduler::new(
1125            0,
1126            TIME_BASE_I64,
1127            Duration::from_millis(DELAY_MS),
1128            0,
1129            false,
1130            None,
1131        );
1132        feed_skewed_window(&mut s, 0, DRIFT_SAMPLE_COUNT - 1, 2);
1133        assert_eq!(s.drift_us(), 0, "999 samples is not a window yet");
1134        assert_eq!(s.time_base_us(), TIME_BASE_I64);
1135        // The 1000th sample (error 999 * 2 = 1998 µs) closes the window:
1136        // sum = 2 * (0 + ... + 999) = 999 000 → average 999.
1137        let predicted = s.time_base_us() + 999 * 1000;
1138        s.feed_data(
1139            DRIFT_SAMPLE_COUNT - 1,
1140            999 * 1000,
1141            Timestamp::from_micros(u64::try_from(predicted + 999 * 2).unwrap()),
1142        );
1143        assert_eq!(s.drift_us(), 999);
1144        assert_eq!(
1145            s.time_base_us(),
1146            TIME_BASE_I64,
1147            "within the bound: base untouched"
1148        );
1149    }
1150
1151    /// Only a *fresh* packet (the very next sequence number) is a drift
1152    /// sample: a retransmission or a packet that jumped a gap arrives late for
1153    /// reasons that say nothing about the clocks.
1154    #[test]
1155    fn only_fresh_in_sequence_packets_are_drift_samples() {
1156        let mut s = TsbpdScheduler::new(
1157            0,
1158            TIME_BASE_I64,
1159            Duration::from_millis(DELAY_MS),
1160            0,
1161            false,
1162            None,
1163        );
1164        let t = Timestamp::from_micros(u64::try_from(TIME_BASE_I64).unwrap());
1165        s.feed_data(0, 0, t);
1166        assert_eq!(s.drift_sample_count, 1, "the first packet is a sample");
1167        s.feed_data(5, 5_000, t); // jumps a gap
1168        assert_eq!(s.drift_sample_count, 1, "a gap-jumper is not a sample");
1169        s.feed_data(1, 1_000, t); // a late recovery of the gap
1170        assert_eq!(
1171            s.drift_sample_count, 1,
1172            "a recovered packet is not a sample"
1173        );
1174        s.feed_data(6, 6_000, t); // the next after the highest
1175        assert_eq!(s.drift_sample_count, 2);
1176    }
1177
1178    /// The time base is signed (rule 12: `T_NOW - HSREQ_TIMESTAMP` is negative
1179    /// when the peer's clock is ahead): a negative base places the first
1180    /// packet's play time correctly, and saturates at "already due" rather
1181    /// than wrapping.
1182    #[test]
1183    fn a_negative_time_base_is_supported() {
1184        let s = TsbpdScheduler::new(
1185            0,
1186            -3_000_000,
1187            Duration::from_millis(DELAY_MS),
1188            0,
1189            false,
1190            None,
1191        );
1192        assert_eq!(s.pkt_tsbpd_time(3_000_000), DELAY_MS * 1000);
1193        assert_eq!(
1194            s.pkt_tsbpd_time(0),
1195            0,
1196            "a play time before the epoch is `now`"
1197        );
1198    }
1199
1200    /// r08-SRT-W8: the receiver's TLPKTDROP-enabled path across the 32-bit
1201    /// timestamp wrap. A packet stream whose raw timestamp wraps from near
1202    /// `u32::MAX` to near 0 arrives at a steady 10 ms network delay; every
1203    /// packet must be delivered. Without unwrapping, each post-wrap packet's
1204    /// play time lands ~71 minutes in the past and Too-Late Packet Drop
1205    /// discards it — the stream dies at the first wrap.
1206    #[test]
1207    fn a_stream_crossing_the_timestamp_wrap_is_delivered_not_dropped() {
1208        const PACKETS: u32 = 100;
1209        const START: u64 = 0xFFFF_F000; // 4096 µs before the wrap
1210        let mut s = TsbpdScheduler::new(0, 0, Duration::from_millis(DELAY_MS), 0, true, None);
1211        let mut dropped = Vec::new();
1212        let mut last_now = 0;
1213        for i in 0..PACKETS {
1214            let true_ts = START + u64::from(i) * 1000;
1215            // The wire field is the true value modulo 2^32.
1216            let raw = u32::try_from(true_ts & 0xFFFF_FFFF).unwrap();
1217            last_now = true_ts + 10_000;
1218            let out = s.feed_data(i, raw, Timestamp::from_micros(last_now));
1219            dropped.extend(out.dropped);
1220        }
1221        let out = s.tick(Timestamp::from_micros(last_now + DELAY_MS * 1000));
1222        dropped.extend(out.dropped);
1223        assert!(dropped.is_empty(), "dropped across the wrap: {dropped:?}");
1224        assert_eq!(s.next_release(), PACKETS, "every packet was released");
1225        assert_eq!(s.buffered_count(), 0);
1226        // (Packets already due on arrival are delivered by `feed_data`; the
1227        // rest by the final tick. `next_release` and an empty buffer prove
1228        // all 100 went out in order.)
1229    }
1230
1231    /// #2860: a DROPREQ flood ahead of the delivery cursor cannot grow the
1232    /// remembered-skip set past `MAX_SKIPS`.
1233    #[test]
1234    fn a_dropreq_flood_stops_at_the_skip_cap() {
1235        let mut s = sched();
1236        let flood = u32::try_from(MAX_SKIPS).unwrap() + 48;
1237        for i in 0..flood {
1238            let seq_number = 1000 + 2 * i;
1239            s.skip_range(seq_number, seq_number);
1240        }
1241        assert_eq!(s.pending_skips.len(), MAX_SKIPS);
1242    }
1243}