srt-runtime 0.13.1

SRT (Secure Reliable Transport, draft-sharabayko-srt-01) packet codecs, sans-IO HSv5 handshakes, a one-connection link engine, ARQ, TSBPD, LiveCC/FileCC congestion control, optional payload crypto and an optional tokio UDP adapter; no_std core.
Documentation
//! SRT ARQ (Automatic Repeat reQuest) reliability engine —
//! `draft-sharabayko-srt-01` §4.8 (Acknowledgement and Lost Packet
//! Handling), §4.8.1 (Packet Acknowledgement — ACKs, ACKACKs), §4.8.2
//! (Packet Retransmission — NAKs), §4.10 (Round-Trip Time Estimation).
//! Curated behavioural rules: `private/specs-verified/rules/srt-arq.md`. The wire field
//! layouts this module drives (ACK/NAK/ACKACK) are the existing
//! [`crate::packet`] codecs — this module never re-encodes them, it only
//! decides *when* to build one and *what* to do with one received.
//!
//! Sans-IO, like the rest of this crate: [`Sender`] and [`Receiver`] never
//! read a wall clock. All timing is driven by a caller-supplied
//! `now: broadcast_core::stage::Instant` (monotonic time since a fixed
//! epoch the caller owns) passed to `tick`/`feed_data`/`on_data`/`on_ack`/`on_ackack`.
//!
//! # Module map
//! - [`seq`] — wrap-safe 31-bit sequence-number arithmetic (not itself a
//!   `srt-arq.md` rule — the draft does not specify a comparison algorithm;
//!   see the module doc there for the resolution).
//! - [`rtt::RttEstimator`] — the rule 29-31 RTT/RTTVar EWMA, shared by both
//!   roles (rule 34: a socket's RTT state is really one estimator usable by
//!   both a sender and a receiver path).
//! - [`Sender`] — send buffer, NAK-driven retransmit queue, ACK/ACKACK
//!   handling (rules 1, 3, 5, 7-10, 15-18, 23-24, 33).
//! - [`Receiver`] — loss detection, Full/Light ACK generation, periodic NAK,
//!   ACKACK-driven RTT measurement (rules 4, 8, 11-14, 21-22, 26-30, 32).
//!
//! # Non-goals (explicit follow-ups, not curated as ARQ rules here)
//! - Deciding *when* to apply the TLPKTDROP fake-ACK skip (rule 13) is
//!   `srt-tsbpd.md` scope: the receiver can skip a range, the integration layer
//!   (the tokio adapter) decides when, and only if TLPKTDROP was negotiated.
//! - RTO-based periodic retransmission without a NAK / congestion control
//!   (§5, FileCC) — srt-arq.md is explicit that the RTO formula is
//!   congestion-control scope, not curated there.
//! - Send-queue overflow / unsent-packet drop sizing (rules 19-20) — the
//!   latency-window math is §4.4/§4.5 scope.

mod receiver;
pub mod rtt;
mod sender;
pub mod seq;

pub use receiver::{FeedOutcome, Receiver, ReceiverBounds};
pub use rtt::RttEstimator;
pub use sender::{Sender, SenderBounds};

/// Both ARQ halves' bounds, as a link takes them.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ArqBounds {
    /// The receiving half's bounds.
    pub receiver: ReceiverBounds,
    /// The sending half's bounds.
    pub sender: SenderBounds,
}

impl ArqBounds {
    /// Refuse a bound that cannot work: a window, skip list or ACK table of zero
    /// tracks nothing, a NAK that may mark no packet disables retransmission, and a
    /// pacing burst of zero never sends. A zero
    /// [`SenderBounds::min_retransmit_interval`] is allowed and means no floor.
    ///
    /// # Errors
    ///
    /// [`crate::Error::InvalidConfig`] naming the field.
    pub fn validate(&self) -> crate::Result<()> {
        let rule = "must be at least 1";
        if self.receiver.max_tracked_window == 0 {
            return Err(crate::Error::invalid_config(
                "receiver.max_tracked_window",
                rule,
            ));
        }
        if self.receiver.max_pending_skips == 0 {
            return Err(crate::Error::invalid_config(
                "receiver.max_pending_skips",
                rule,
            ));
        }
        if self.receiver.max_outstanding_acks == 0 {
            return Err(crate::Error::invalid_config(
                "receiver.max_outstanding_acks",
                rule,
            ));
        }
        if self.sender.max_nak_seqs_per_packet == 0 {
            return Err(crate::Error::invalid_config(
                "sender.max_nak_seqs_per_packet",
                rule,
            ));
        }
        if self.sender.pacing_burst_packets == 0 {
            return Err(crate::Error::invalid_config(
                "sender.pacing_burst_packets",
                rule,
            ));
        }
        Ok(())
    }
}

use crate::packet::number::SrtTimestamp;
use broadcast_core::stage::Instant;
use core::time::Duration;

/// Full ACK timer period — 10 milliseconds (`private/specs-verified/rules/srt-arq.md` rule
/// 11, quoting `draft-sharabayko-srt-01` L2874-2876: "the ACK period or
/// synchronization time interval SYN").
pub const FULL_ACK_PERIOD: Duration = Duration::from_millis(10);

/// Light-ACK packet-count threshold — 64 packets (`private/specs-verified/rules/srt-arq.md`
/// rule 12, L2877-2883): if this many packets have been sent/received
/// within the Full ACK period, the receiver sends a Light ACK early.
pub const LIGHT_ACK_THRESHOLD: u32 = 64;

/// `NAKInterval` floor — 20 milliseconds (`private/specs-verified/rules/srt-arq.md` rule 22,
/// L2953-2960 / L3276): `NAKInterval = max((RTT + 4*RTTVar) / 2, 20ms)`.
pub const NAK_INTERVAL_FLOOR: Duration = Duration::from_millis(20);

/// Convert a [`Duration`] to the wire `Instant` field's microsecond
/// `u32` (`draft-sharabayko-srt-01` §3: "microseconds elapsed since the SRT
/// connection was established"), **wrapping** modulo `2^32` once `d` exceeds
/// `u32::MAX` microseconds (about 71.58 minutes) since the caller's epoch —
/// not clamping to `u32::MAX`.
///
/// A clamp (this function's pre-#1063 behavior) makes every packet sent
/// after that point carry the *same* fixed timestamp forever, instead of one
/// that keeps counting up (mod 2^32) the way the field is defined. A real
/// peer's `PktTsbpdTime` formula (`TsbpdTimeBase + PKT_TIMESTAMP + ...`,
/// `private/specs-verified/rules/srt-tsbpd.md` rule 9) would then compute the same constant
/// play time for every such packet — which the peer's receiver clock keeps
/// advancing past, so every packet after the clamp point looks
/// arbitrarily-far too late and gets Too-Late-Packet-Dropped. The receiving
/// side of the same problem — correctly *un*wrapping a peer's wrapped
/// timestamp back into an always-increasing value for `PktTsbpdTime`
/// purposes — is `crate::tsbpd::TsbpdScheduler`'s `unwrap_timestamp`, not
/// this function (this one only ever produces an in-range wire value; it
/// does not need to remember any wrap-count itself, so plain truncation of
/// the microsecond count into 32 bits is exactly "mod 2^32").
pub(crate) fn duration_to_wire_us(d: Duration) -> u32 {
    // Keep exactly the low 32 bits: the wire field is "microseconds mod 2^32".
    u32::try_from(d.as_micros() & u128::from(u32::MAX)).unwrap_or(0)
}

/// Convert a [`Instant`] to the wire `Instant` field's microsecond `u32`
/// (`draft-sharabayko-srt-01` §3), wrapping modulo `2^32` once the
/// microsecond count exceeds `u32::MAX` (about 71.58 minutes) since the
/// caller's epoch — not clamping to `u32::MAX`. See
/// [`duration_to_wire_us`] for why a clamp (instead of a wrap) stalls a real
/// peer's Too-Late-Packet-Drop.
pub(crate) fn timestamp_to_wire_us(ts: Instant) -> SrtTimestamp {
    // Keep exactly the low 32 bits: the wire field is "microseconds mod 2^32".
    SrtTimestamp::from_wire(u32::try_from(ts.as_micros() & u64::from(u32::MAX)).unwrap_or(0))
}

/// `NAKInterval = max((RTT + 4 * RTTVar) / 2, 20 ms)` (`private/specs-verified/rules/srt-arq.md`
/// rule 22, verbatim from `draft-sharabayko-srt-01` L2953-2960, unit
/// resolution cross-referenced from §5.2's L3276 restatement).
/// Weight of `RTTVar` in the NAK interval, and the divisor of the sum.
const RTT_VAR_WEIGHT: u32 = 4;
const NAK_INTERVAL_DIVISOR: u32 = 2;

pub(crate) fn nak_interval(rtt: Duration, rtt_var: Duration) -> Duration {
    let sum = rtt + rtt_var * RTT_VAR_WEIGHT;
    let half = sum / NAK_INTERVAL_DIVISOR;
    if half < NAK_INTERVAL_FLOOR {
        NAK_INTERVAL_FLOOR
    } else {
        half
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// `timestamp_to_wire_us` keeps exactly the low 32 bits, so a `Instant`
    /// past `u32::MAX` microseconds (about 71.58 minutes) wraps the way the
    /// §3 wire field defines — it never clamps (a clamp would freeze every
    /// later packet's timestamp and Too-Late-Packet-Drop a real peer).
    #[test]
    fn timestamp_to_wire_us_wraps_mod_2_32() {
        assert_eq!(
            timestamp_to_wire_us(Instant::from_micros(0)),
            SrtTimestamp::ZERO
        );
        assert_eq!(
            timestamp_to_wire_us(Instant::from_micros(1_000)),
            SrtTimestamp::from_wire(1_000)
        );
        assert_eq!(
            timestamp_to_wire_us(Instant::from_micros(u64::from(u32::MAX))),
            SrtTimestamp::from_wire(u32::MAX)
        );
        assert_eq!(
            timestamp_to_wire_us(Instant::from_micros(u64::from(u32::MAX) + 1)),
            SrtTimestamp::ZERO,
            "the wrap is modulo 2^32, not a clamp"
        );
    }

    /// `NAKInterval = max((RTT + 4*RTTVar) / 2, 20 ms)` (rule 22, L2953-2960).
    #[test]
    fn nak_interval_follows_the_rule_22_formula() {
        assert_eq!(
            nak_interval(Duration::from_millis(100), Duration::from_millis(25)),
            Duration::from_millis(100),
            "(100 + 4*25) / 2 = 100"
        );
        assert_eq!(
            nak_interval(Duration::from_millis(10), Duration::from_millis(2)),
            Duration::from_millis(20),
            "(10 + 4*2) / 2 = 9 is below the 20 ms floor"
        );
        assert_eq!(
            nak_interval(Duration::from_millis(40), Duration::ZERO),
            Duration::from_millis(20),
            "40 / 2 = 20 is exactly the floor"
        );
        assert_eq!(
            nak_interval(Duration::from_millis(50), Duration::ZERO),
            Duration::from_millis(25),
            "above the floor the halved sum is used as-is"
        );
    }
}