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