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