Skip to main content

srt_runtime/packet/
data.rs

1//! SRT data packet — `draft-sharabayko-srt-01` §3.1, Figure 3.
2//!
3//! ```text
4//! word0  0|                Packet Sequence Number (31)                 |
5//! word1  PP|O|KK|R|                Message Number (26)                 |
6//! word2                          Timestamp (32)
7//! word3                    Destination Socket ID (32)
8//! rest                              Data
9//! ```
10
11use super::number::{SocketId, SrtTimestamp};
12use super::{Error, Result, SEQ_NUMBER_MASK, SRT_HEADER_LEN, be32, put_be32};
13use broadcast_common::len::{need_in, need_out};
14
15/// Bit width of the Message Number field (§3.1).
16pub(crate) const MESSAGE_NUMBER_BITS: u32 = 26;
17/// Mask for the 26-bit Message Number field (§3.1). `pub(crate)` so
18/// `io::Driver` can wrap its own message-number counter at the same
19/// boundary [`next_message_number`] uses (issue #1062).
20pub(crate) const MESSAGE_NUMBER_MASK: u32 = (1 << MESSAGE_NUMBER_BITS) - 1;
21
22/// The next Message Number after `n`, wrapping at the 26-bit boundary
23/// (`draft-sharabayko-srt-01` §3.1) back to `0` — analogous to
24/// `crate::arq::seq::seq_next` for the 31-bit Packet Sequence Number.
25///
26/// A plain `u32::wrapping_add(1)` (which this replaces, issue #1062) only
27/// wraps at 2^32: once a long-lived sender's message counter passed
28/// `MESSAGE_NUMBER_MASK` (after ~67 million messages), [`DataPacket::serialize_into`]
29/// started returning `Error::FieldOverflow` for every packet, and every caller
30/// that assumed that could only fail on a too-small buffer (`.expect("buffer
31/// sized from serialized_len")` in `arq::sender`) panicked.
32///
33/// `cfg`-gated on `tokio`: its only caller, `io::Driver::send_one`, lives
34/// entirely behind that feature (unlike `arq::seq::seq_next`'s equivalent
35/// for the sequence number, which `arq::sender` also uses unconditionally) —
36/// gated rather than left to warn as dead code under `--no-default-features`.
37///
38/// Wraps to `1`, not `0`: libsrt's own public header reserves message number
39/// `0` — `SRT_MSGNO_CONTROL` in `srt.h` ("0: control (used by packet filter
40/// control messages)") — so `0` on a DATA packet is not "message number
41/// zero", it is libsrt's own filter-control sentinel. A plain wrap to `0`
42/// (this function's behavior until this fix) would, once every 2^26
43/// messages, emit a genuine data packet a real libsrt receiver reads as a
44/// filter-control message instead.
45#[cfg(feature = "tokio")]
46pub(crate) fn next_message_number(n: u32) -> u32 {
47    // Mask `n` down first: it is always already in range in practice (every
48    // caller only ever feeds back a value this function returned), but doing
49    // so here too means a stray out-of-range input can't push `n + 1` out of
50    // range either.
51    match ((n & MESSAGE_NUMBER_MASK) + 1) & MESSAGE_NUMBER_MASK {
52        0 => 1,
53        next => next,
54    }
55}
56
57/// `PP` (Packet Position Flag) wire values (§3.1).
58const PP_MIDDLE: u8 = 0b00;
59const PP_LAST: u8 = 0b01;
60const PP_FIRST: u8 = 0b10;
61const PP_SOLO: u8 = 0b11;
62
63/// `KK` (Key-based Encryption Flag) wire values (§3.1).
64const KK_NOT_ENCRYPTED: u8 = 0b00;
65const KK_EVEN: u8 = 0b01;
66const KK_ODD: u8 = 0b10;
67/// `11b` — reserved; only meaningful on control packets (Key Material `KK`).
68#[cfg(test)]
69const KK_CONTROL_ONLY: u8 = 0b11;
70
71/// `PP`: Packet Position Flag — position of the data packet in its message
72/// (`draft-sharabayko-srt-01` §3.1).
73#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
74#[cfg_attr(feature = "serde", derive(serde::Serialize))]
75#[non_exhaustive]
76pub enum PacketPosition {
77    /// `10b`: first packet of the message.
78    First,
79    /// `00b`: a packet in the middle of the message.
80    Middle,
81    /// `01b`: last packet of the message.
82    Last,
83    /// `11b`: the whole message fits in a single data packet.
84    Solo,
85}
86
87impl PacketPosition {
88    /// Decode the 2-bit `PP` field.
89    pub fn from_bits(v: u8) -> Self {
90        match v & 0b11 {
91            PP_FIRST => PacketPosition::First,
92            PP_LAST => PacketPosition::Last,
93            PP_SOLO => PacketPosition::Solo,
94            _ => PacketPosition::Middle, // PP_MIDDLE, and unreachable otherwise (v & 0b11 <= 3)
95        }
96    }
97
98    /// The 2-bit wire value.
99    pub fn to_bits(self) -> u8 {
100        match self {
101            PacketPosition::First => PP_FIRST,
102            PacketPosition::Middle => PP_MIDDLE,
103            PacketPosition::Last => PP_LAST,
104            PacketPosition::Solo => PP_SOLO,
105        }
106    }
107
108    /// Spec label.
109    pub fn name(&self) -> &'static str {
110        match self {
111            PacketPosition::First => "first",
112            PacketPosition::Middle => "middle",
113            PacketPosition::Last => "last",
114            PacketPosition::Solo => "solo",
115        }
116    }
117}
118
119broadcast_common::impl_spec_display!(PacketPosition);
120
121/// `KK`: Key-based Encryption Flag — whether/how the `Data` field is
122/// encrypted (`draft-sharabayko-srt-01` §3.1, §6). `11b` is reserved for
123/// control packets (Key Material's own `KK` field, §3.2.2) and should not
124/// appear on a data packet, but is decoded rather than rejected.
125#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
126#[cfg_attr(feature = "serde", derive(serde::Serialize))]
127#[non_exhaustive]
128pub enum EncryptionKeyField {
129    /// `00b`: the payload is not encrypted.
130    NotEncrypted,
131    /// `01b`: encrypted with the even key.
132    Even,
133    /// `10b`: encrypted with the odd key.
134    Odd,
135    /// `11b`: reserved — only meaningful on control packets.
136    Reserved(u8),
137}
138
139impl EncryptionKeyField {
140    /// Decode the 2-bit `KK` field.
141    pub fn from_bits(v: u8) -> Self {
142        match v & 0b11 {
143            KK_NOT_ENCRYPTED => EncryptionKeyField::NotEncrypted,
144            KK_EVEN => EncryptionKeyField::Even,
145            KK_ODD => EncryptionKeyField::Odd,
146            other => EncryptionKeyField::Reserved(other),
147        }
148    }
149
150    /// The 2-bit wire value.
151    pub fn to_bits(self) -> u8 {
152        match self {
153            EncryptionKeyField::NotEncrypted => KK_NOT_ENCRYPTED,
154            EncryptionKeyField::Even => KK_EVEN,
155            EncryptionKeyField::Odd => KK_ODD,
156            EncryptionKeyField::Reserved(v) => v & 0b11,
157        }
158    }
159
160    /// Spec label.
161    pub fn name(&self) -> &'static str {
162        match self {
163            EncryptionKeyField::NotEncrypted => "not encrypted",
164            EncryptionKeyField::Even => "even key",
165            EncryptionKeyField::Odd => "odd key",
166            EncryptionKeyField::Reserved(_) => "reserved",
167        }
168    }
169}
170
171broadcast_common::impl_spec_display!(EncryptionKeyField, Reserved);
172
173/// An SRT data packet (`draft-sharabayko-srt-01` §3.1, Figure 3).
174#[derive(Debug, Clone, PartialEq)]
175#[cfg_attr(feature = "serde", derive(serde::Serialize))]
176pub struct DataPacket<'a> {
177    /// Packet Sequence Number — 31 bits.
178    pub seq_number: u32,
179    /// `PP`: Packet Position Flag.
180    pub position: PacketPosition,
181    /// `O`: Order Flag — deliver in order (`true`) or not (`false`).
182    pub in_order: bool,
183    /// `KK`: Key-based Encryption Flag.
184    pub key_flag: EncryptionKeyField,
185    /// `R`: Retransmitted Packet Flag.
186    pub retransmitted: bool,
187    /// Message Number — 26 bits.
188    pub message_number: u32,
189    /// Timestamp, in microseconds relative to connection establishment (§3).
190    pub timestamp: SrtTimestamp,
191    /// Destination Socket ID (§3).
192    pub dest_socket_id: SocketId,
193    /// The payload. Length is whatever remains of the UDP datagram.
194    pub data: &'a [u8],
195}
196
197const KK_SHIFT: u32 = 27;
198const PP_SHIFT: u32 = 30;
199const O_SHIFT: u32 = 29;
200const R_SHIFT: u32 = 26;
201
202impl<'a> DataPacket<'a> {
203    /// Parse a data packet from `bytes` (the full SRT packet, header + data).
204    ///
205    /// # Errors
206    /// [`Error::BufferTooShort`] if shorter than the 16-byte header;
207    /// [`Error::WrongPacketKind`] if the `F` bit is set (this is a control
208    /// packet).
209    pub fn parse(bytes: &'a [u8]) -> Result<Self> {
210        need_in(bytes, SRT_HEADER_LEN, "SRT data packet header")?;
211        let word0 = be32(bytes, 0);
212        if word0 & super::F_BIT != 0 {
213            return Err(Error::WrongPacketKind {
214                expected: "data packet (F=0)",
215            });
216        }
217        let word1 = be32(bytes, 4);
218        let seq_number = word0 & SEQ_NUMBER_MASK;
219        let position = PacketPosition::from_bits((word1 >> PP_SHIFT) as u8);
220        let in_order = (word1 >> O_SHIFT) & 1 != 0;
221        let key_flag = EncryptionKeyField::from_bits((word1 >> KK_SHIFT) as u8);
222        let retransmitted = (word1 >> R_SHIFT) & 1 != 0;
223        let message_number = word1 & MESSAGE_NUMBER_MASK;
224        let timestamp = SrtTimestamp::from_wire(be32(bytes, 8));
225        let dest_socket_id = SocketId::from_wire(be32(bytes, 12));
226        let data = &bytes[SRT_HEADER_LEN..];
227        Ok(DataPacket {
228            seq_number,
229            position,
230            in_order,
231            key_flag,
232            retransmitted,
233            message_number,
234            timestamp,
235            dest_socket_id,
236            data,
237        })
238    }
239
240    /// Number of bytes [`Self::serialize_into`] will write.
241    pub fn serialized_len(&self) -> usize {
242        SRT_HEADER_LEN + self.data.len()
243    }
244
245    /// Serialize this data packet into `buf`.
246    pub fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
247        let len = self.serialized_len();
248        need_out(buf, len)?;
249        broadcast_common::len::fit_bits(u64::from(self.seq_number), 31, "Packet Sequence Number")?;
250        broadcast_common::len::fit_bits(
251            u64::from(self.message_number),
252            MESSAGE_NUMBER_BITS,
253            "Message Number",
254        )?;
255        let word0 = self.seq_number; // F bit (bit 31) stays clear.
256        let word1 = (u32::from(self.position.to_bits()) << PP_SHIFT)
257            | (u32::from(self.in_order) << O_SHIFT)
258            | (u32::from(self.key_flag.to_bits()) << KK_SHIFT)
259            | (u32::from(self.retransmitted) << R_SHIFT)
260            | self.message_number;
261        put_be32(buf, 0, word0);
262        put_be32(buf, 4, word1);
263        put_be32(buf, 8, self.timestamp.value());
264        put_be32(buf, 12, self.dest_socket_id.value());
265        buf[SRT_HEADER_LEN..len].copy_from_slice(self.data);
266        Ok(len)
267    }
268}
269
270impl<'a> broadcast_common::Parse<'a> for DataPacket<'a> {
271    type Error = crate::Error;
272
273    fn parse(bytes: &'a [u8]) -> core::result::Result<Self, Self::Error> {
274        DataPacket::parse(bytes)
275    }
276}
277
278impl broadcast_common::Serialize for DataPacket<'_> {
279    type Error = crate::Error;
280
281    fn serialized_len(&self) -> usize {
282        DataPacket::serialized_len(self)
283    }
284
285    fn serialize_into(&self, buf: &mut [u8]) -> core::result::Result<usize, Self::Error> {
286        DataPacket::serialize_into(self, buf)
287    }
288}
289
290#[cfg(test)]
291mod tests {
292    use super::*;
293
294    #[test]
295    #[cfg(feature = "tokio")]
296    fn next_message_number_wraps_at_26_bits() {
297        assert_eq!(next_message_number(0), 1);
298        assert_eq!(
299            next_message_number(MESSAGE_NUMBER_MASK - 1),
300            MESSAGE_NUMBER_MASK
301        );
302        // The actual boundary (issue #1062): one past the max 26-bit value
303        // must wrap back into range, not silently produce an out-of-range
304        // value that later fails `DataPacket::serialize_into`'s
305        // `FieldOverflow` check — and specifically to `1`, not `0`: libsrt's
306        // `srt.h` reserves message number `0` (`SRT_MSGNO_CONTROL`) for its
307        // own packet-filter control messages, never a real data message.
308        assert_eq!(next_message_number(MESSAGE_NUMBER_MASK), 1);
309        assert_eq!(next_message_number(0), 1);
310    }
311
312    #[test]
313    #[cfg(feature = "tokio")]
314    fn next_message_number_result_always_serializes() {
315        // Every value this function can ever produce must fit the 26-bit
316        // field — this is the actual invariant the panic bug violated.
317        for start in [0, 1, MESSAGE_NUMBER_MASK - 2, MESSAGE_NUMBER_MASK] {
318            let n = next_message_number(start);
319            assert!(n <= MESSAGE_NUMBER_MASK, "start={start:#x} -> {n:#x}");
320        }
321    }
322
323    fn sample() -> DataPacket<'static> {
324        DataPacket {
325            seq_number: 0x0123_4567,
326            position: PacketPosition::Solo,
327            in_order: true,
328            key_flag: EncryptionKeyField::Even,
329            retransmitted: false,
330            message_number: 0x0155_5555, // fits 26 bits
331            timestamp: SrtTimestamp::from_wire(0xAABB_CCDD),
332            dest_socket_id: SocketId::from_wire(0x1122_3344),
333            data: &[0x47, 0x00, 0x01, 0x02],
334        }
335    }
336
337    #[test]
338    fn round_trip_bytes_are_hand_computed() {
339        let pkt = sample();
340        let mut buf = [0u8; 20];
341        let n = pkt.serialize_into(&mut buf).unwrap();
342        assert_eq!(n, 20);
343
344        // word0: F=0, seq=0x01234567 -> top bit clear already.
345        assert_eq!(&buf[0..4], &0x0123_4567u32.to_be_bytes());
346        // word1: PP=11 (Solo), O=1, KK=01 (Even), R=0 (omitted: 0<<26 is a
347        // no-op), msg=0x01555555.
348        let expected_word1 = (0b11u32 << 30) | (1u32 << 29) | (0b01u32 << 27) | 0x0155_5555;
349        assert_eq!(&buf[4..8], &expected_word1.to_be_bytes());
350        assert_eq!(&buf[8..12], &0xAABB_CCDDu32.to_be_bytes());
351        assert_eq!(&buf[12..16], &0x1122_3344u32.to_be_bytes());
352        assert_eq!(&buf[16..20], &[0x47, 0x00, 0x01, 0x02]);
353
354        let parsed = DataPacket::parse(&buf).unwrap();
355        assert_eq!(parsed, pkt);
356    }
357
358    /// The header words are typed values that serialize to exactly their own
359    /// wire value: the old `u32` fields let a socket id be read as a
360    /// timestamp (or passed where the other belonged).
361    #[test]
362    fn the_header_words_serialize_as_their_own_values() {
363        assert_eq!(SrtTimestamp::from_wire(0xAABB_CCDD).value(), 0xAABB_CCDDu32);
364        assert_eq!(SocketId::from_wire(0x1122_3344).value(), 0x1122_3344u32);
365        let mut buf = [0u8; 20];
366        sample().serialize_into(&mut buf).unwrap();
367        let pkt = DataPacket::parse(&buf).unwrap();
368        assert_eq!(pkt.timestamp, SrtTimestamp::from_wire(0xAABB_CCDD));
369        assert_eq!(pkt.dest_socket_id, SocketId::from_wire(0x1122_3344));
370    }
371
372    #[test]
373    fn mutate_field_changes_bytes() {
374        let mut pkt = sample();
375        let mut buf1 = [0u8; 20];
376        pkt.serialize_into(&mut buf1).unwrap();
377        pkt.retransmitted = true;
378        let mut buf2 = [0u8; 20];
379        pkt.serialize_into(&mut buf2).unwrap();
380        assert_ne!(buf1, buf2);
381    }
382
383    #[test]
384    fn rejects_control_packet_bytes() {
385        let mut buf = [0u8; 16];
386        buf[0] = 0x80; // F=1
387        assert_eq!(
388            DataPacket::parse(&buf).unwrap_err(),
389            Error::WrongPacketKind {
390                expected: "data packet (F=0)"
391            }
392        );
393    }
394
395    #[test]
396    fn all_packet_positions_round_trip() {
397        for p in [
398            PacketPosition::First,
399            PacketPosition::Middle,
400            PacketPosition::Last,
401            PacketPosition::Solo,
402        ] {
403            assert_eq!(PacketPosition::from_bits(p.to_bits()), p);
404        }
405    }
406
407    #[test]
408    fn all_key_flags_round_trip() {
409        for k in [
410            EncryptionKeyField::NotEncrypted,
411            EncryptionKeyField::Even,
412            EncryptionKeyField::Odd,
413        ] {
414            assert_eq!(EncryptionKeyField::from_bits(k.to_bits()), k);
415        }
416        assert_eq!(
417            EncryptionKeyField::from_bits(KK_CONTROL_ONLY),
418            EncryptionKeyField::Reserved(KK_CONTROL_ONLY)
419        );
420    }
421
422    #[test]
423    fn overwide_seq_number_errs() {
424        let mut pkt = sample();
425        pkt.seq_number = 0x8000_0000;
426        let mut buf = [0u8; 20];
427        assert!(matches!(
428            pkt.serialize_into(&mut buf),
429            Err(Error::FieldOverflow(_))
430        ));
431    }
432}