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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
//! SRT data packet — `draft-sharabayko-srt-01` §3.1, Figure 3.
//!
//! ```text
//! word0  0|                Packet Sequence Number (31)                 |
//! word1  PP|O|KK|R|                Message Number (26)                 |
//! word2                          Timestamp (32)
//! word3                    Destination Socket ID (32)
//! rest                              Data
//! ```

pub(crate) use super::number::{MESSAGE_NUMBER_BITS, MESSAGE_NUMBER_MASK};
use super::number::{SocketId, SrtTimestamp};
use super::{Error, Result, SEQ_NUMBER_MASK, SRT_HEADER_LEN, put_be32};
use broadcast_core::len::{need_in, need_out};
use broadcast_core::reserved::FieldValue;

/// The next Message Number after `n`, wrapping at the 26-bit boundary
/// (`draft-sharabayko-srt-01` §3.1) back to `0` — analogous to
/// `crate::arq::seq::seq_next` for the 31-bit Packet Sequence Number.
///
/// A plain `u32::wrapping_add(1)` (which this replaces, issue #1062) only
/// wraps at 2^32: once a long-lived sender's message counter passed
/// `MESSAGE_NUMBER_MASK` (after ~67 million messages), [`DataPacket::serialize_into`]
/// started returning `Error::FieldOverflow` for every packet, and every caller
/// that assumed that could only fail on a too-small buffer (`.expect("buffer
/// sized from serialized_len")` in `arq::sender`) panicked.
///
/// `cfg`-gated on `tokio`: its only caller, `io::Driver::send_one`, lives
/// entirely behind that feature (unlike `arq::seq::seq_next`'s equivalent
/// for the sequence number, which `arq::sender` also uses unconditionally) —
/// gated rather than left to warn as dead code under `--no-default-features`.
///
/// Wraps to `1`, not `0`: libsrt's own public header reserves message number
/// `0` — `SRT_MSGNO_CONTROL` in `srt.h` ("0: control (used by packet filter
/// control messages)") — so `0` on a DATA packet is not "message number
/// zero", it is libsrt's own filter-control sentinel. A plain wrap to `0`
/// (this function's behavior until this fix) would, once every 2^26
/// messages, emit a genuine data packet a real libsrt receiver reads as a
/// filter-control message instead.
#[cfg(feature = "link")]
pub(crate) fn next_message_number(n: u32) -> u32 {
    // Mask `n` down first: it is always already in range in practice (every
    // caller only ever feeds back a value this function returned), but doing
    // so here too means a stray out-of-range input can't push `n + 1` out of
    // range either.
    match ((n & MESSAGE_NUMBER_MASK) + 1) & MESSAGE_NUMBER_MASK {
        0 => 1,
        next => next,
    }
}

/// `PP` (Packet Position Flag) wire values (§3.1).
/// Mask of the 2-bit `PP`/`KK` fields of the second header word (§3.1).
const FIELD_MASK: u8 = 0b11;
/// Bit width of the `KK` field.
const KK_BITS: u32 = 2;

/// Bit width of a data packet's 31-bit Packet Sequence Number (§3.1).
const SEQ_NUMBER_BITS: u32 = 31;

const PP_MIDDLE: u8 = 0b00;
const PP_LAST: u8 = 0b01;
const PP_FIRST: u8 = 0b10;
const PP_SOLO: u8 = 0b11;

/// `KK` (Key-based Encryption Flag) wire values (§3.1).
const KK_NOT_ENCRYPTED: u8 = 0b00;
const KK_EVEN: u8 = 0b01;
const KK_ODD: u8 = 0b10;
/// `11b` — reserved; only meaningful on control packets (Key Material `KK`).
#[cfg(test)]
const KK_CONTROL_ONLY: u8 = 0b11;

/// `PP`: Packet Position Flag — position of the data packet in its message
/// (`draft-sharabayko-srt-01` §3.1).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum PacketPosition {
    /// `10b`: first packet of the message.
    First,
    /// `00b`: a packet in the middle of the message.
    Middle,
    /// `01b`: last packet of the message.
    Last,
    /// `11b`: the whole message fits in a single data packet.
    Solo,
}

impl PacketPosition {
    /// Decode the 2-bit `PP` field.
    pub fn from_bits(v: u8) -> Self {
        match v & FIELD_MASK {
            PP_FIRST => PacketPosition::First,
            PP_LAST => PacketPosition::Last,
            PP_SOLO => PacketPosition::Solo,
            _ => PacketPosition::Middle, // PP_MIDDLE, and unreachable otherwise (v & 0b11 <= 3)
        }
    }

    /// The 2-bit wire value.
    pub fn to_bits(self) -> u8 {
        match self {
            PacketPosition::First => PP_FIRST,
            PacketPosition::Middle => PP_MIDDLE,
            PacketPosition::Last => PP_LAST,
            PacketPosition::Solo => PP_SOLO,
        }
    }

    /// Spec label.
    pub fn name(&self) -> &'static str {
        match self {
            PacketPosition::First => "first",
            PacketPosition::Middle => "middle",
            PacketPosition::Last => "last",
            PacketPosition::Solo => "solo",
        }
    }
}

broadcast_core::impl_spec_display!(PacketPosition);

/// `KK`: Key-based Encryption Flag — whether/how the `Data` field is
/// encrypted (`draft-sharabayko-srt-01` §3.1, §6). `11b` is reserved for
/// control packets (Key Material's own `KK` field, §3.2.2) and should not
/// appear on a data packet, but is decoded rather than rejected.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum EncryptionKeyField {
    /// `00b`: the payload is not encrypted.
    NotEncrypted,
    /// `01b`: encrypted with the even key.
    Even,
    /// `10b`: encrypted with the odd key.
    Odd,
    /// `11b`: reserved — only meaningful on control packets.
    Reserved(FieldValue<KK_BITS>),
}

impl EncryptionKeyField {
    /// Decode the 2-bit `KK` field.
    pub fn from_bits(v: u8) -> Self {
        let field = FieldValue::<KK_BITS>::from_bits(v);
        match field.get() {
            KK_NOT_ENCRYPTED => EncryptionKeyField::NotEncrypted,
            KK_EVEN => EncryptionKeyField::Even,
            KK_ODD => EncryptionKeyField::Odd,
            _ => EncryptionKeyField::Reserved(field),
        }
    }

    /// The 2-bit wire value.
    pub fn to_bits(self) -> u8 {
        match self {
            EncryptionKeyField::NotEncrypted => KK_NOT_ENCRYPTED,
            EncryptionKeyField::Even => KK_EVEN,
            EncryptionKeyField::Odd => KK_ODD,
            EncryptionKeyField::Reserved(v) => v.get(),
        }
    }

    /// Spec label.
    pub fn name(&self) -> &'static str {
        match self {
            EncryptionKeyField::NotEncrypted => "not encrypted",
            EncryptionKeyField::Even => "even key",
            EncryptionKeyField::Odd => "odd key",
            EncryptionKeyField::Reserved(_) => "reserved",
        }
    }
}

broadcast_core::impl_spec_display!(EncryptionKeyField, Reserved);

/// An SRT data packet (`draft-sharabayko-srt-01` §3.1, Figure 3).
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct DataPacket<'a> {
    /// Packet Sequence Number — 31 bits.
    pub seq_number: u32,
    /// `PP`: Packet Position Flag.
    pub position: PacketPosition,
    /// `O`: Order Flag — deliver in order (`true`) or not (`false`).
    pub in_order: bool,
    /// `KK`: Key-based Encryption Flag.
    pub key_flag: EncryptionKeyField,
    /// `R`: Retransmitted Packet Flag.
    pub retransmitted: bool,
    /// Message Number — 26 bits.
    pub message_number: u32,
    /// Timestamp, in microseconds relative to connection establishment (§3).
    pub timestamp: SrtTimestamp,
    /// Destination Socket ID (§3).
    pub dest_socket_id: SocketId,
    /// The payload. Length is whatever remains of the UDP datagram.
    pub data: &'a [u8],
}

const KK_SHIFT: u32 = 27;
const PP_SHIFT: u32 = 30;
const O_SHIFT: u32 = 29;
const R_SHIFT: u32 = 26;

impl<'a> DataPacket<'a> {
    /// Parse a data packet from `bytes` (the full SRT packet, header + data).
    ///
    /// # Errors
    /// [`Error::BufferTooShort`] if shorter than the 16-byte header;
    /// [`Error::WrongPacketKind`] if the `F` bit is set (this is a control
    /// packet).
    pub fn parse(bytes: &'a [u8]) -> Result<Self> {
        need_in(bytes, SRT_HEADER_LEN, "SRT data packet header")?;
        let word0 = broadcast_core::wire::Reader::at(bytes, 0).u32("word0")?;
        if word0 & super::F_BIT != 0 {
            return Err(Error::WrongPacketKind {
                expected: "data packet (F=0)",
            });
        }
        let word1 =
            broadcast_core::wire::Reader::at(bytes, super::TYPE_FIELD_OFFSET).u32("word1")?;
        let seq_number = word0 & SEQ_NUMBER_MASK;
        let position = PacketPosition::from_bits((word1 >> PP_SHIFT) as u8);
        let in_order = (word1 >> O_SHIFT) & 1 != 0;
        let key_flag = EncryptionKeyField::from_bits((word1 >> KK_SHIFT) as u8);
        let retransmitted = (word1 >> R_SHIFT) & 1 != 0;
        let message_number = word1 & MESSAGE_NUMBER_MASK;
        let timestamp = SrtTimestamp::from_wire(
            broadcast_core::wire::Reader::at(bytes, super::TIMESTAMP_OFFSET).u32("timestamp")?,
        );
        let dest_socket_id = SocketId::from_wire(
            broadcast_core::wire::Reader::at(bytes, super::DEST_SOCKET_ID_OFFSET)
                .u32("SocketId")?,
        );
        let data = &bytes[SRT_HEADER_LEN..];
        Ok(DataPacket {
            seq_number,
            position,
            in_order,
            key_flag,
            retransmitted,
            message_number,
            timestamp,
            dest_socket_id,
            data,
        })
    }

    /// Number of bytes [`Self::serialize_into`] will write.
    pub fn serialized_len(&self) -> usize {
        SRT_HEADER_LEN + self.data.len()
    }

    /// Serialize this data packet into `buf`.
    pub fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        let len = self.serialized_len();
        need_out(buf, len, "DataPacket")?;
        broadcast_core::len::fit_bits(
            u64::from(self.seq_number),
            SEQ_NUMBER_BITS,
            "Packet Sequence Number",
        )?;
        broadcast_core::len::fit_bits(
            u64::from(self.message_number),
            MESSAGE_NUMBER_BITS,
            "Message Number",
        )?;
        let word0 = self.seq_number; // F bit (bit 31) stays clear.
        let word1 = (u32::from(self.position.to_bits()) << PP_SHIFT)
            | (u32::from(self.in_order) << O_SHIFT)
            | (u32::from(self.key_flag.to_bits()) << KK_SHIFT)
            | (u32::from(self.retransmitted) << R_SHIFT)
            | self.message_number;
        put_be32(buf, 0, word0);
        put_be32(buf, super::TYPE_FIELD_OFFSET, word1);
        put_be32(buf, super::TIMESTAMP_OFFSET, self.timestamp.value());
        put_be32(
            buf,
            super::DEST_SOCKET_ID_OFFSET,
            self.dest_socket_id.value(),
        );
        buf[SRT_HEADER_LEN..len].copy_from_slice(self.data);
        Ok(len)
    }
}

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

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

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

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

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

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

    #[test]
    #[cfg(feature = "link")]
    fn next_message_number_wraps_at_26_bits() {
        assert_eq!(next_message_number(0), 1);
        assert_eq!(
            next_message_number(MESSAGE_NUMBER_MASK - 1),
            MESSAGE_NUMBER_MASK
        );
        // The actual boundary (issue #1062): one past the max 26-bit value
        // must wrap back into range, not silently produce an out-of-range
        // value that later fails `DataPacket::serialize_into`'s
        // `FieldOverflow` check — and specifically to `1`, not `0`: libsrt's
        // `srt.h` reserves message number `0` (`SRT_MSGNO_CONTROL`) for its
        // own packet-filter control messages, never a real data message.
        assert_eq!(next_message_number(MESSAGE_NUMBER_MASK), 1);
        assert_eq!(next_message_number(0), 1);
    }

    #[test]
    #[cfg(feature = "link")]
    fn next_message_number_result_always_serializes() {
        // Every value this function can ever produce must fit the 26-bit
        // field — this is the actual invariant the panic bug violated.
        for start in [0, 1, MESSAGE_NUMBER_MASK - 2, MESSAGE_NUMBER_MASK] {
            let n = next_message_number(start);
            assert!(n <= MESSAGE_NUMBER_MASK, "start={start:#x} -> {n:#x}");
        }
    }

    fn sample() -> DataPacket<'static> {
        DataPacket {
            seq_number: 0x0123_4567,
            position: PacketPosition::Solo,
            in_order: true,
            key_flag: EncryptionKeyField::Even,
            retransmitted: false,
            message_number: 0x0155_5555, // fits 26 bits
            timestamp: SrtTimestamp::from_wire(0xAABB_CCDD),
            dest_socket_id: SocketId::from_wire(0x1122_3344),
            data: &[0x47, 0x00, 0x01, 0x02],
        }
    }

    #[test]
    fn round_trip_bytes_are_hand_computed() {
        let pkt = sample();
        let mut buf = [0u8; 20];
        let n = pkt.serialize_into(&mut buf).unwrap();
        assert_eq!(n, 20);

        // word0: F=0, seq=0x01234567 -> top bit clear already.
        assert_eq!(&buf[0..4], &0x0123_4567u32.to_be_bytes());
        // word1: PP=11 (Solo), O=1, KK=01 (Even), R=0 (omitted: 0<<26 is a
        // no-op), msg=0x01555555.
        let expected_word1 = (0b11u32 << 30) | (1u32 << 29) | (0b01u32 << 27) | 0x0155_5555;
        assert_eq!(&buf[4..8], &expected_word1.to_be_bytes());
        assert_eq!(&buf[8..12], &0xAABB_CCDDu32.to_be_bytes());
        assert_eq!(&buf[12..16], &0x1122_3344u32.to_be_bytes());
        assert_eq!(&buf[16..20], &[0x47, 0x00, 0x01, 0x02]);

        let parsed = DataPacket::parse(&buf).unwrap();
        assert_eq!(parsed, pkt);
    }

    /// The header words are typed values that serialize to exactly their own
    /// wire value: the old `u32` fields let a socket id be read as a
    /// timestamp (or passed where the other belonged).
    #[test]
    fn the_header_words_serialize_as_their_own_values() {
        assert_eq!(SrtTimestamp::from_wire(0xAABB_CCDD).value(), 0xAABB_CCDDu32);
        assert_eq!(SocketId::from_wire(0x1122_3344).value(), 0x1122_3344u32);
        let mut buf = [0u8; 20];
        sample().serialize_into(&mut buf).unwrap();
        let pkt = DataPacket::parse(&buf).unwrap();
        assert_eq!(pkt.timestamp, SrtTimestamp::from_wire(0xAABB_CCDD));
        assert_eq!(pkt.dest_socket_id, SocketId::from_wire(0x1122_3344));
    }

    #[test]
    fn mutate_field_changes_bytes() {
        let mut pkt = sample();
        let mut buf1 = [0u8; 20];
        pkt.serialize_into(&mut buf1).unwrap();
        pkt.retransmitted = true;
        let mut buf2 = [0u8; 20];
        pkt.serialize_into(&mut buf2).unwrap();
        assert_ne!(buf1, buf2);
    }

    #[test]
    fn rejects_control_packet_bytes() {
        let mut buf = [0u8; 16];
        buf[0] = 0x80; // F=1
        assert_eq!(
            DataPacket::parse(&buf).unwrap_err(),
            Error::WrongPacketKind {
                expected: "data packet (F=0)"
            }
        );
    }

    #[test]
    fn all_packet_positions_round_trip() {
        for p in [
            PacketPosition::First,
            PacketPosition::Middle,
            PacketPosition::Last,
            PacketPosition::Solo,
        ] {
            assert_eq!(PacketPosition::from_bits(p.to_bits()), p);
        }
    }

    #[test]
    fn all_key_flags_round_trip() {
        for k in [
            EncryptionKeyField::NotEncrypted,
            EncryptionKeyField::Even,
            EncryptionKeyField::Odd,
        ] {
            assert_eq!(EncryptionKeyField::from_bits(k.to_bits()), k);
        }
        assert_eq!(
            EncryptionKeyField::from_bits(KK_CONTROL_ONLY),
            EncryptionKeyField::from_bits(KK_CONTROL_ONLY)
        );
    }

    #[test]
    fn overwide_seq_number_errs() {
        let mut pkt = sample();
        pkt.seq_number = 0x8000_0000;
        let mut buf = [0u8; 20];
        assert!(matches!(
            pkt.serialize_into(&mut buf),
            Err(Error::FieldOverflow(_))
        ));
    }
}