Skip to main content

srt_runtime/packet/
mod.rs

1//! SRT packet structure — `draft-sharabayko-srt-01` §3 (Packet Structure).
2//!
3//! Every SRT packet is the payload of one UDP datagram (§3, Figure 1). It
4//! starts with a 16-byte SRT header (Figure 2): a leading `F` bit
5//! distinguishes data packets (`F=0`, §3.1) from control packets (`F=1`,
6//! §3.2); the following two header words carry packet-type-specific fields,
7//! and the header always closes with a 32-bit Timestamp and a 32-bit
8//! Destination Socket ID.
9//!
10//! This module is packet **structure** only — parse/serialize of the wire
11//! format. The handshake *state machine* (caller/listener/rendezvous
12//! exchange, §4.3), loss/ARQ handling, TSBPD, congestion control, and the
13//! actual AES key-wrap/unwrap crypto (§6) are explicit follow-ups; see the
14//! crate root docs.
15
16pub mod ack;
17pub mod control;
18pub mod data;
19pub mod handshake;
20pub mod key_material;
21pub mod misc;
22pub mod nak;
23pub mod number;
24
25pub use ack::{AckCif, AckPacket};
26pub use control::{ControlPacket, ControlType, UserDefinedPacket};
27pub use data::{DataPacket, EncryptionKeyField, PacketPosition};
28pub use handshake::{
29    EncryptionField, ExtensionType, GroupFlags, GroupMembershipExtension, GroupType,
30    HandshakeExtensionBlock, HandshakeExtensionFlags, HandshakeExtensionMessageFlags,
31    HandshakeExtensions, HandshakePacket, HandshakeType, HsExtMessage,
32};
33pub use key_material::{Cipher, KeyMaterial, KmAuth, KmKeyFlag, StreamEncapsulation};
34pub use misc::{
35    AckAckPacket, CongestionWarningPacket, DropReqPacket, KeepAlivePacket, PeerErrorPacket,
36    ShutdownPacket,
37};
38pub use nak::{LossListEntry, NakPacket};
39pub use number::{AckNumber, MessageNumber, SeqNo, SocketId, SrtTimestamp};
40
41use crate::error::{Error, Result};
42use broadcast_core::len::need_in;
43
44/// Length in bytes of the fixed SRT header shared by data and control packets
45/// (`draft-sharabayko-srt-01` §3, Figure 2): 4 header words = 16 bytes, before
46/// any packet-type-specific payload (data) or Control Information Field
47/// (control).
48pub const SRT_HEADER_LEN: usize = 16;
49
50/// The `F` (Packet Type Flag) bit — bit 31 of the first header word. Clear for
51/// a data packet, set for a control packet (§3, Figure 2). Also reused,
52/// bit-for-bit, as the range marker in the NAK loss-list coding (Appendix A).
53pub(crate) const F_BIT: u32 = 0x8000_0000;
54
55/// Mask for a 31-bit packet sequence number (data packet §3.1, NAK loss list
56/// Appendix A): all bits below the `F`/range-marker bit.
57pub(crate) const SEQ_NUMBER_MASK: u32 = SeqNo::MAX.value();
58
59/// Byte offset of the second header word — the packet-type-specific field —
60/// shared by every data and control packet (§3, Figure 2).
61pub(crate) const TYPE_FIELD_OFFSET: usize = 4;
62
63/// Byte offset of the Timestamp, shared by every data and control packet
64/// (§3, Figure 2).
65pub(crate) const TIMESTAMP_OFFSET: usize = 8;
66
67/// Byte offset of the Destination Socket ID — the last of the four fixed
68/// header words shared by every data and control packet (§3, Figure 2).
69pub(crate) const DEST_SOCKET_ID_OFFSET: usize = 12;
70
71/// Byte width of a big-endian `u32` field, and of a big-endian `u16` field.
72const U32_FIELD_LEN: usize = core::mem::size_of::<u32>();
73const U16_FIELD_LEN: usize = core::mem::size_of::<u16>();
74
75/// Reads the Destination Socket ID straight off the wire header, without a
76/// full [`SrtPacket::parse`] — it sits at the same fixed offset for every
77/// data and control packet (§3, Figure 2), so a demultiplexer can route on it
78/// even for a packet type it doesn't otherwise understand. `None` if `bytes`
79/// is too short to contain a full header. `cfg`-gated on `tokio`: its only
80/// caller is `io`'s listener routing pump.
81#[cfg(feature = "tokio")]
82pub(crate) fn peek_dest_socket_id(bytes: &[u8]) -> Option<u32> {
83    if bytes.len() < SRT_HEADER_LEN {
84        return None;
85    }
86    broadcast_core::wire::Reader::at(bytes, DEST_SOCKET_ID_OFFSET)
87        .u32("dest_socket_id")
88        .ok()
89}
90
91/// A parsed SRT packet — the payload of one UDP datagram carrying SRT traffic
92/// (`draft-sharabayko-srt-01` §3, Figure 1 / Figure 2).
93#[derive(Debug, Clone, PartialEq)]
94#[cfg_attr(feature = "serde", derive(serde::Serialize))]
95#[non_exhaustive]
96pub enum SrtPacket<'a> {
97    /// `F=0`: a data packet (§3.1).
98    Data(DataPacket<'a>),
99    /// `F=1`: a control packet (§3.2).
100    Control(ControlPacket<'a>),
101}
102
103impl<'a> SrtPacket<'a> {
104    /// Parse one SRT packet from `bytes` — the full payload of one UDP
105    /// datagram carrying SRT traffic. Dispatches on the `F` bit of the first
106    /// header word (§3, Figure 2).
107    pub fn parse(bytes: &'a [u8]) -> Result<Self> {
108        need_in(bytes, SRT_HEADER_LEN, "SRT header")?;
109        let word0 = broadcast_core::wire::Reader::at(bytes, 0).u32("word0")?;
110        if word0 & F_BIT != 0 {
111            Ok(SrtPacket::Control(ControlPacket::parse(bytes)?))
112        } else {
113            Ok(SrtPacket::Data(DataPacket::parse(bytes)?))
114        }
115    }
116
117    /// Number of bytes [`Self::serialize_into`] will write.
118    pub fn serialized_len(&self) -> usize {
119        match self {
120            SrtPacket::Data(d) => d.serialized_len(),
121            SrtPacket::Control(c) => c.serialized_len(),
122        }
123    }
124
125    /// Serialize this packet into `buf`. Returns the number of bytes written.
126    pub fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
127        match self {
128            SrtPacket::Data(d) => d.serialize_into(buf),
129            SrtPacket::Control(c) => c.serialize_into(buf),
130        }
131    }
132}
133
134impl<'a> broadcast_core::Parse<'a> for SrtPacket<'a> {
135    type Error = crate::Error;
136
137    fn parse(bytes: &'a [u8]) -> core::result::Result<Self, Self::Error> {
138        SrtPacket::parse(bytes)
139    }
140}
141
142impl broadcast_core::Serialize for SrtPacket<'_> {
143    type Error = crate::Error;
144
145    fn serialized_len(&self) -> usize {
146        SrtPacket::serialized_len(self)
147    }
148
149    fn serialize_into(&self, buf: &mut [u8]) -> core::result::Result<usize, Self::Error> {
150        SrtPacket::serialize_into(self, buf)
151    }
152}
153
154/// Write a big-endian `u32` at byte offset `off`.
155///
156/// # Panics
157/// Panics if `buf.len() < off + 4`.
158pub(crate) fn put_be32(buf: &mut [u8], off: usize, value: u32) {
159    buf[off..off + U32_FIELD_LEN].copy_from_slice(&value.to_be_bytes());
160}
161
162/// Write a big-endian `u16` at byte offset `off`. See [`put_be32`] on panics.
163pub(crate) fn put_be16(buf: &mut [u8], off: usize, value: u16) {
164    buf[off..off + U16_FIELD_LEN].copy_from_slice(&value.to_be_bytes());
165}
166
167#[cfg(all(test, feature = "tokio"))]
168mod tests {
169    use super::*;
170
171    /// The listener's demultiplexing peek needs a whole header: exactly
172    /// [`SRT_HEADER_LEN`] bytes yields the id, one byte fewer yields `None`
173    /// (never a partial read).
174    #[test]
175    fn peek_dest_socket_id_needs_a_whole_header() {
176        let mut bytes = [0u8; SRT_HEADER_LEN];
177        put_be32(&mut bytes, DEST_SOCKET_ID_OFFSET, 0x1234_5678);
178        assert_eq!(peek_dest_socket_id(&bytes), Some(0x1234_5678));
179        assert_eq!(
180            peek_dest_socket_id(&bytes[..SRT_HEADER_LEN - 1]),
181            None,
182            "a 15-byte datagram has no complete header"
183        );
184        assert_eq!(peek_dest_socket_id(&[]), None);
185    }
186}