srt-runtime 0.13.0

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 packet structure — `draft-sharabayko-srt-01` §3 (Packet Structure).
//!
//! Every SRT packet is the payload of one UDP datagram (§3, Figure 1). It
//! starts with a 16-byte SRT header (Figure 2): a leading `F` bit
//! distinguishes data packets (`F=0`, §3.1) from control packets (`F=1`,
//! §3.2); the following two header words carry packet-type-specific fields,
//! and the header always closes with a 32-bit Timestamp and a 32-bit
//! Destination Socket ID.
//!
//! This module is packet **structure** only — parse/serialize of the wire
//! format. The handshake *state machine* (caller/listener/rendezvous
//! exchange, §4.3), loss/ARQ handling, TSBPD, congestion control, and the
//! actual AES key-wrap/unwrap crypto (§6) are explicit follow-ups; see the
//! crate root docs.

pub mod ack;
pub mod control;
pub mod data;
pub mod handshake;
pub mod key_material;
pub mod misc;
pub mod nak;
pub mod number;

pub use ack::{AckCif, AckPacket};
pub use control::{ControlPacket, ControlType, UserDefinedPacket};
pub use data::{DataPacket, EncryptionKeyField, PacketPosition};
pub use handshake::{
    EncryptionField, ExtensionType, GroupFlags, GroupMembershipExtension, GroupType,
    HandshakeExtensionBlock, HandshakeExtensionFlags, HandshakeExtensionMessageFlags,
    HandshakeExtensions, HandshakePacket, HandshakeType, HsExtMessage,
};
pub use key_material::{Cipher, KeyMaterial, KmAuth, KmKeyFlag, StreamEncapsulation};
pub use misc::{
    AckAckPacket, CongestionWarningPacket, DropReqPacket, KeepAlivePacket, PeerErrorPacket,
    ShutdownPacket,
};
pub use nak::{LossListEntry, NakPacket};
pub use number::{AckNumber, MessageNumber, SeqNo, SocketId, SrtTimestamp};

use crate::error::{Error, Result};
use broadcast_core::len::need_in;

/// Length in bytes of the fixed SRT header shared by data and control packets
/// (`draft-sharabayko-srt-01` §3, Figure 2): 4 header words = 16 bytes, before
/// any packet-type-specific payload (data) or Control Information Field
/// (control).
pub const SRT_HEADER_LEN: usize = 16;

/// The `F` (Packet Type Flag) bit — bit 31 of the first header word. Clear for
/// a data packet, set for a control packet (§3, Figure 2). Also reused,
/// bit-for-bit, as the range marker in the NAK loss-list coding (Appendix A).
pub(crate) const F_BIT: u32 = 0x8000_0000;

/// Mask for a 31-bit packet sequence number (data packet §3.1, NAK loss list
/// Appendix A): all bits below the `F`/range-marker bit.
pub(crate) const SEQ_NUMBER_MASK: u32 = SeqNo::MAX.value();

/// Byte offset of the second header word — the packet-type-specific field —
/// shared by every data and control packet (§3, Figure 2).
pub(crate) const TYPE_FIELD_OFFSET: usize = 4;

/// Byte offset of the Timestamp, shared by every data and control packet
/// (§3, Figure 2).
pub(crate) const TIMESTAMP_OFFSET: usize = 8;

/// Byte offset of the Destination Socket ID — the last of the four fixed
/// header words shared by every data and control packet (§3, Figure 2).
pub(crate) const DEST_SOCKET_ID_OFFSET: usize = 12;

/// Byte width of a big-endian `u32` field, and of a big-endian `u16` field.
const U32_FIELD_LEN: usize = core::mem::size_of::<u32>();
const U16_FIELD_LEN: usize = core::mem::size_of::<u16>();

/// Reads the Destination Socket ID straight off the wire header, without a
/// full [`SrtPacket::parse`] — it sits at the same fixed offset for every
/// data and control packet (§3, Figure 2), so a demultiplexer can route on it
/// even for a packet type it doesn't otherwise understand. `None` if `bytes`
/// is too short to contain a full header. `cfg`-gated on `tokio`: its only
/// caller is `io`'s listener routing pump.
#[cfg(feature = "tokio")]
pub(crate) fn peek_dest_socket_id(bytes: &[u8]) -> Option<u32> {
    if bytes.len() < SRT_HEADER_LEN {
        return None;
    }
    broadcast_core::wire::Reader::at(bytes, DEST_SOCKET_ID_OFFSET)
        .u32("dest_socket_id")
        .ok()
}

/// A parsed SRT packet — the payload of one UDP datagram carrying SRT traffic
/// (`draft-sharabayko-srt-01` §3, Figure 1 / Figure 2).
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum SrtPacket<'a> {
    /// `F=0`: a data packet (§3.1).
    Data(DataPacket<'a>),
    /// `F=1`: a control packet (§3.2).
    Control(ControlPacket<'a>),
}

impl<'a> SrtPacket<'a> {
    /// Parse one SRT packet from `bytes` — the full payload of one UDP
    /// datagram carrying SRT traffic. Dispatches on the `F` bit of the first
    /// header word (§3, Figure 2).
    pub fn parse(bytes: &'a [u8]) -> Result<Self> {
        need_in(bytes, SRT_HEADER_LEN, "SRT header")?;
        let word0 = broadcast_core::wire::Reader::at(bytes, 0).u32("word0")?;
        if word0 & F_BIT != 0 {
            Ok(SrtPacket::Control(ControlPacket::parse(bytes)?))
        } else {
            Ok(SrtPacket::Data(DataPacket::parse(bytes)?))
        }
    }

    /// Number of bytes [`Self::serialize_into`] will write.
    pub fn serialized_len(&self) -> usize {
        match self {
            SrtPacket::Data(d) => d.serialized_len(),
            SrtPacket::Control(c) => c.serialized_len(),
        }
    }

    /// Serialize this packet into `buf`. Returns the number of bytes written.
    pub fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        match self {
            SrtPacket::Data(d) => d.serialize_into(buf),
            SrtPacket::Control(c) => c.serialize_into(buf),
        }
    }
}

impl<'a> broadcast_core::Parse<'a> for SrtPacket<'a> {
    type Error = crate::Error;

    fn parse(bytes: &'a [u8]) -> core::result::Result<Self, Self::Error> {
        SrtPacket::parse(bytes)
    }
}

impl broadcast_core::Serialize for SrtPacket<'_> {
    type Error = crate::Error;

    fn serialized_len(&self) -> usize {
        SrtPacket::serialized_len(self)
    }

    fn serialize_into(&self, buf: &mut [u8]) -> core::result::Result<usize, Self::Error> {
        SrtPacket::serialize_into(self, buf)
    }
}

/// Write a big-endian `u32` at byte offset `off`.
///
/// # Panics
/// Panics if `buf.len() < off + 4`.
pub(crate) fn put_be32(buf: &mut [u8], off: usize, value: u32) {
    buf[off..off + U32_FIELD_LEN].copy_from_slice(&value.to_be_bytes());
}

/// Write a big-endian `u16` at byte offset `off`. See [`put_be32`] on panics.
pub(crate) fn put_be16(buf: &mut [u8], off: usize, value: u16) {
    buf[off..off + U16_FIELD_LEN].copy_from_slice(&value.to_be_bytes());
}

#[cfg(all(test, feature = "tokio"))]
mod tests {
    use super::*;

    /// The listener's demultiplexing peek needs a whole header: exactly
    /// [`SRT_HEADER_LEN`] bytes yields the id, one byte fewer yields `None`
    /// (never a partial read).
    #[test]
    fn peek_dest_socket_id_needs_a_whole_header() {
        let mut bytes = [0u8; SRT_HEADER_LEN];
        put_be32(&mut bytes, DEST_SOCKET_ID_OFFSET, 0x1234_5678);
        assert_eq!(peek_dest_socket_id(&bytes), Some(0x1234_5678));
        assert_eq!(
            peek_dest_socket_id(&bytes[..SRT_HEADER_LEN - 1]),
            None,
            "a 15-byte datagram has no complete header"
        );
        assert_eq!(peek_dest_socket_id(&[]), None);
    }
}