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