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