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