Skip to main content

srt_runtime/packet/
number.rs

1//! The typed SRT wire numbers — `draft-sharabayko-srt-01` §3 (header words)
2//! and Appendix A (loss-list coding).
3//!
4//! Three quantities name a packet or a socket on the wire and were all bare
5//! `u32` before: the 31-bit Packet Sequence Number (§3.1, Figure 3), the
6//! 26-bit Message Number (§3.1), and the 32-bit Destination/Source Socket ID
7//! (§3, Figure 2). Each now has its own type, so the units and the wrap
8//! behaviour travel with the value instead of living in a comment, and the
9//! node-budget/parse sites convert once at the wire edge.
10//!
11//! [`SeqNo`] is the one sequence-number type in the crate: the ACK's Last
12//! Acknowledged Packet Sequence Number and the NAK/DROPREQ loss-list endpoints
13//! are the same 31-bit sequence space, so all of them are a [`SeqNo`]. The wrap
14//! arithmetic is [`broadcast_common::modular`] (31 bits), never `wrapping_add` or
15//! `abs_diff` on a raw integer.
16//!
17//! [`AckNumber`] is deliberately *not* a [`SeqNo`]: the ACK/ACKACK
18//! Acknowledgement Number lives in a whole 32-bit header word (§3.2.4,
19//! §3.2.8), so every `u32` value is a legal acknowledgement number.
20
21use broadcast_common::modular::Modulus;
22
23/// The SRT packet sequence-number space: 31 bits (`draft-sharabayko-srt-01`
24/// §3.1, Figure 3 — `Packet Sequence Number (31)`; the top bit is the header
25/// `F` packet-type flag, reused as the NAK loss-list range marker, Appendix A).
26const SEQ_SPACE_BITS: u32 = 31;
27/// The 31-bit space, proven in range at compile time.
28const SEQ_SPACE: Modulus = Modulus::new::<SEQ_SPACE_BITS>();
29
30/// Bit width of the Message Number field (`draft-sharabayko-srt-01` §3.1,
31/// Figure 3: `Message Number (26)`).
32pub const MESSAGE_NUMBER_BITS: u32 = 26;
33/// The 26-bit Message Number mask (§3.1).
34pub const MESSAGE_NUMBER_MASK: u32 = (1 << MESSAGE_NUMBER_BITS) - 1;
35
36/// A 31-bit SRT packet sequence number (`draft-sharabayko-srt-01` §3.1,
37/// Figure 3).
38///
39/// The value always fits the 31-bit field. Construction never masks a
40/// caller-supplied value: [`SeqNo::try_new`] rejects an out-of-range one and
41/// [`SeqNo::from_wire_masked`] is the explicit parse-site constructor. It is
42/// *not* `Ord`: the sequence space is circular, so ordering is
43/// [`SeqNo::lt`]/[`SeqNo::gt`]/... (shorter-direction, RFC 1982-style), never a
44/// plain numeric compare that breaks at the wrap.
45#[derive(Clone, Copy, PartialEq, Eq, Hash)]
46#[cfg_attr(feature = "serde", derive(serde::Serialize))]
47#[cfg_attr(feature = "serde", serde(transparent))]
48pub struct SeqNo(u32);
49
50impl SeqNo {
51    /// The largest sequence number in the 31-bit space (`0x7FFF_FFFF`).
52    pub const MAX: SeqNo = SeqNo(SEQ_SPACE.mask() as u32);
53
54    /// Construct a `SeqNo`, rejecting a value that does not fit the 31-bit
55    /// field.
56    ///
57    /// # Errors
58    /// [`SeqOutOfRange`] when `value > 0x7FFF_FFFF`.
59    pub const fn try_new(value: u32) -> Result<Self, SeqOutOfRange> {
60        if value as u64 > SEQ_SPACE.mask() {
61            Err(SeqOutOfRange { value })
62        } else {
63            Ok(Self(value))
64        }
65    }
66
67    /// Construct a `SeqNo` from the low 31 bits of `value`, **deliberately**
68    /// discarding the rest: the explicit name for extracting the sequence
69    /// field out of a wider wire word (e.g. the header word whose bit 31 is
70    /// the `F` flag), where masking is the specified behaviour. Use this only
71    /// at parse sites; use [`SeqNo::try_new`] for a caller-supplied value.
72    #[must_use]
73    pub const fn from_wire_masked(value: u32) -> Self {
74        Self(value & SEQ_SPACE.mask() as u32)
75    }
76
77    /// The raw 31-bit value.
78    #[must_use]
79    pub const fn value(self) -> u32 {
80        self.0
81    }
82
83    /// `self + n`, wrapping at the 31-bit boundary.
84    #[must_use]
85    pub const fn add(self, n: u32) -> Self {
86        Self(SEQ_SPACE.add(self.0 as u64, n as u64) as u32)
87    }
88
89    /// The next sequence number after `self` (wraps `0x7FFF_FFFF` -> `0`).
90    #[must_use]
91    pub const fn next(self) -> Self {
92        self.add(1)
93    }
94
95    /// Signed circular distance `self - other`, in `(-2^30, 2^30]`. Positive
96    /// means `self` is ahead of `other`.
97    #[must_use]
98    pub const fn diff(self, other: Self) -> i32 {
99        SEQ_SPACE.signed(other.0 as u64, self.0 as u64) as i32
100    }
101
102    /// `self` precedes `other` in circular sequence order.
103    #[must_use]
104    pub const fn lt(self, other: Self) -> bool {
105        SEQ_SPACE.lt(self.0 as u64, other.0 as u64)
106    }
107
108    /// `self` precedes or equals `other`.
109    #[must_use]
110    pub const fn leq(self, other: Self) -> bool {
111        SEQ_SPACE.leq(self.0 as u64, other.0 as u64)
112    }
113
114    /// `self` follows `other` in circular sequence order.
115    #[must_use]
116    pub const fn gt(self, other: Self) -> bool {
117        SEQ_SPACE.gt(self.0 as u64, other.0 as u64)
118    }
119
120    /// `self` follows or equals `other`.
121    #[must_use]
122    pub const fn geq(self, other: Self) -> bool {
123        SEQ_SPACE.geq(self.0 as u64, other.0 as u64)
124    }
125
126    /// Whether `self` lies within the inclusive circular range `first..=last`,
127    /// walking forward from `first`. A `last` that precedes `first` in circular
128    /// order is an empty (malformed) range and never matches.
129    #[must_use]
130    pub const fn in_closed_range(self, first: Self, last: Self) -> bool {
131        SEQ_SPACE.in_closed_range(self.0 as u64, first.0 as u64, last.0 as u64)
132    }
133}
134
135/// A sequence number that does not fit the 31-bit field
136/// (`draft-sharabayko-srt-01` §3.1).
137#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
138#[error("sequence number {value:#010X} exceeds the 31-bit range")]
139#[non_exhaustive]
140pub struct SeqOutOfRange {
141    /// The rejected value.
142    pub value: u32,
143}
144
145impl TryFrom<u32> for SeqNo {
146    type Error = SeqOutOfRange;
147    fn try_from(value: u32) -> Result<Self, Self::Error> {
148        Self::try_new(value)
149    }
150}
151
152impl From<SeqNo> for u32 {
153    fn from(seq: SeqNo) -> Self {
154        seq.0
155    }
156}
157
158impl core::fmt::Debug for SeqNo {
159    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
160        write!(f, "SeqNo({:#010X})", self.0)
161    }
162}
163
164impl core::fmt::Display for SeqNo {
165    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
166        write!(f, "{}", self.0)
167    }
168}
169
170/// An SRT Socket ID — the 32-bit Destination Socket ID / Source Socket ID of
171/// `draft-sharabayko-srt-01` §3, Figure 2.
172///
173/// Every value fits the 32-bit wire field, so there is no range rejection;
174/// the type exists so a socket id cannot be confused with a sequence number, a
175/// timestamp or an arbitrary count. `0` is meaningful — on a handshake induction
176/// packet it is the connection request sentinel (§4.3.1.1).
177#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
178#[cfg_attr(feature = "serde", derive(serde::Serialize))]
179#[cfg_attr(feature = "serde", serde(transparent))]
180pub struct SocketId(u32);
181
182impl SocketId {
183    /// The connection-request sentinel: a Destination Socket ID of `0` on a
184    /// handshake induction packet (§4.3.1.1).
185    pub const CONNECTION_REQUEST: SocketId = SocketId(0);
186
187    /// Construct a `SocketId` from its 32-bit wire value.
188    #[must_use]
189    pub const fn from_wire(value: u32) -> Self {
190        Self(value)
191    }
192
193    /// The raw 32-bit wire value.
194    #[must_use]
195    pub const fn value(self) -> u32 {
196        self.0
197    }
198
199    /// Whether this is the connection-request sentinel ([`Self::CONNECTION_REQUEST`]).
200    #[must_use]
201    pub const fn is_connection_request(self) -> bool {
202        self.0 == 0
203    }
204}
205
206impl From<u32> for SocketId {
207    fn from(value: u32) -> Self {
208        SocketId(value)
209    }
210}
211
212impl From<SocketId> for u32 {
213    fn from(id: SocketId) -> Self {
214        id.0
215    }
216}
217
218impl core::fmt::Debug for SocketId {
219    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
220        write!(f, "SocketId({})", self.0)
221    }
222}
223
224impl core::fmt::Display for SocketId {
225    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
226        write!(f, "{}", self.0)
227    }
228}
229
230/// The sequential number of a Full ACK control packet — the
231/// `draft-sharabayko-srt-01` §3.2.4 (Figure 13) `Acknowledgement Number`,
232/// carried in the control header's `Type-specific Information` word, and
233/// echoed back by the ACKACK that acknowledges it (§3.2.8, Figure 17).
234///
235/// Unlike [`SeqNo`], whose 31-bit space exists because the top bit of a *data*
236/// packet's first header word is the `F` flag, this field occupies a whole
237/// 32-bit word: no bit in it is reserved and no value is unrepresentable, so
238/// there is no range rejection. The type keeps an ACK's numbering (an
239/// incrementing counter, §4.8.1) from being confused with a sequence number, a
240/// socket id, a timestamp or a plain count.
241#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
242#[cfg_attr(feature = "serde", derive(serde::Serialize))]
243#[cfg_attr(feature = "serde", serde(transparent))]
244pub struct AckNumber(u32);
245
246impl AckNumber {
247    /// The zero acknowledgement number — what a Small/Light ACK carries
248    /// (§3.2.4: their `Type-specific Information` "should be set to 0").
249    pub const ZERO: AckNumber = AckNumber(0);
250
251    /// Construct an `AckNumber` from its 32-bit wire value.
252    #[must_use]
253    pub const fn from_wire(value: u32) -> Self {
254        Self(value)
255    }
256
257    /// The raw 32-bit wire value.
258    #[must_use]
259    pub const fn value(self) -> u32 {
260        self.0
261    }
262}
263
264impl From<u32> for AckNumber {
265    fn from(value: u32) -> Self {
266        AckNumber(value)
267    }
268}
269
270impl From<AckNumber> for u32 {
271    fn from(n: AckNumber) -> Self {
272        n.0
273    }
274}
275
276impl core::fmt::Debug for AckNumber {
277    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
278        write!(f, "AckNumber({})", self.0)
279    }
280}
281
282impl core::fmt::Display for AckNumber {
283    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
284        write!(f, "{}", self.0)
285    }
286}
287
288/// A 26-bit SRT Message Number (`draft-sharabayko-srt-01` §3.1, Figure 3:
289/// `Message Number (26)`).
290///
291/// The value always fits the 26-bit field. [`MessageNumber::next`] wraps at
292/// the 26-bit boundary back to `1`, not `0`: libsrt's public header reserves
293/// message number `0` (`SRT_MSGNO_CONTROL`) as a packet-filter control
294/// sentinel, so a data packet must never carry it (issue #1062).
295#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
296#[cfg_attr(feature = "serde", derive(serde::Serialize))]
297#[cfg_attr(feature = "serde", serde(transparent))]
298pub struct MessageNumber(u32);
299
300impl MessageNumber {
301    /// Construct a `MessageNumber`, rejecting a value that does not fit the
302    /// 26-bit field.
303    ///
304    /// # Errors
305    /// [`MessageNumberOutOfRange`] when `value` exceeds [`MESSAGE_NUMBER_MASK`].
306    pub const fn try_new(value: u32) -> Result<Self, MessageNumberOutOfRange> {
307        if value > MESSAGE_NUMBER_MASK {
308            Err(MessageNumberOutOfRange { value })
309        } else {
310            Ok(Self(value))
311        }
312    }
313
314    /// Construct a `MessageNumber` from the low 26 bits of `value`,
315    /// **deliberately** discarding the rest — the parse-site constructor for
316    /// the `word1` Message Number field (§3.1).
317    #[must_use]
318    pub const fn from_wire_masked(value: u32) -> Self {
319        Self(value & MESSAGE_NUMBER_MASK)
320    }
321
322    /// The raw 26-bit value.
323    #[must_use]
324    pub const fn value(self) -> u32 {
325        self.0
326    }
327
328    /// The next Message Number after `self`, wrapping at the 26-bit boundary
329    /// to `1` (never `0` — see the type doc).
330    #[must_use]
331    pub const fn next(self) -> Self {
332        match ((self.0 & MESSAGE_NUMBER_MASK) + 1) & MESSAGE_NUMBER_MASK {
333            0 => Self(1),
334            next => Self(next),
335        }
336    }
337}
338
339/// A message number that does not fit the 26-bit field
340/// (`draft-sharabayko-srt-01` §3.1).
341#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
342#[error("message number {value:#010X} exceeds the 26-bit range")]
343#[non_exhaustive]
344pub struct MessageNumberOutOfRange {
345    /// The rejected value.
346    pub value: u32,
347}
348
349impl TryFrom<u32> for MessageNumber {
350    type Error = MessageNumberOutOfRange;
351    fn try_from(value: u32) -> Result<Self, Self::Error> {
352        Self::try_new(value)
353    }
354}
355
356impl From<MessageNumber> for u32 {
357    fn from(n: MessageNumber) -> Self {
358        n.0
359    }
360}
361
362impl core::fmt::Debug for MessageNumber {
363    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
364        write!(f, "MessageNumber({})", self.0)
365    }
366}
367
368impl core::fmt::Display for MessageNumber {
369    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
370        write!(f, "{}", self.0)
371    }
372}
373
374/// An SRT header Timestamp — the 32-bit field of `draft-sharabayko-srt-01` §3
375/// (Figure 2), carried by every data and control packet.
376///
377/// On a data packet it is a media timestamp in microseconds relative to
378/// connection establishment (§3.1), wrapping every `2^32` µs (~71.58 min,
379/// rule 15 of `private/specs-verified/rules/srt-tsbpd.md`); on a control packet
380/// it is the sender's current time for the packet's purpose (§3.2). It always
381/// fits the 32-bit field, so there is no range rejection — the type keeps a
382/// header timestamp from being confused with a sequence number, a socket id or
383/// a plain count.
384#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
385#[cfg_attr(feature = "serde", derive(serde::Serialize))]
386#[cfg_attr(feature = "serde", serde(transparent))]
387pub struct SrtTimestamp(u32);
388
389impl SrtTimestamp {
390    /// The zero timestamp.
391    pub const ZERO: SrtTimestamp = SrtTimestamp(0);
392
393    /// Construct an `SrtTimestamp` from its 32-bit wire value.
394    #[must_use]
395    pub const fn from_wire(value: u32) -> Self {
396        Self(value)
397    }
398
399    /// The raw 32-bit wire value.
400    #[must_use]
401    pub const fn value(self) -> u32 {
402        self.0
403    }
404}
405
406impl From<u32> for SrtTimestamp {
407    fn from(value: u32) -> Self {
408        SrtTimestamp(value)
409    }
410}
411
412impl From<SrtTimestamp> for u32 {
413    fn from(ts: SrtTimestamp) -> Self {
414        ts.0
415    }
416}
417
418impl core::fmt::Debug for SrtTimestamp {
419    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
420        write!(f, "SrtTimestamp({})", self.0)
421    }
422}
423
424impl core::fmt::Display for SrtTimestamp {
425    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
426        write!(f, "{}", self.0)
427    }
428}
429
430#[cfg(test)]
431mod tests {
432    use super::*;
433
434    /// An ACK/ACKACK Acknowledgement Number is a whole 32-bit word
435    /// (§3.2.4/§3.2.8): no value is out of range, unlike the 31-bit
436    /// [`SeqNo`], so the type never rejects or masks one.
437    #[test]
438    fn ack_number_keeps_every_32_bit_value() {
439        for v in [0, 1, 0x7FFF_FFFF, 0x8000_0000, 0xFFFF_FFFF] {
440            let n = AckNumber::from_wire(v);
441            assert_eq!(n.value(), v);
442            assert_eq!(u32::from(AckNumber::from(v)), v);
443            assert_eq!(alloc::format!("{n:?}"), alloc::format!("AckNumber({v})"));
444            assert_eq!(alloc::format!("{n}"), alloc::format!("{v}"));
445        }
446        assert_eq!(AckNumber::ZERO.value(), 0);
447    }
448
449    #[test]
450    fn seq_space_matches_the_wire_mask() {
451        assert_eq!(SEQ_SPACE.mask().count_ones(), SEQ_SPACE_BITS);
452        assert_eq!(SeqNo::MAX.value().count_ones(), 31);
453        assert_eq!(SeqNo::from_wire_masked(0x8000_0005).value(), 5);
454    }
455
456    #[test]
457    fn seq_try_new_rejects_an_out_of_range_value() {
458        assert_eq!(
459            SeqNo::try_new(0x8000_0000),
460            Err(SeqOutOfRange { value: 0x8000_0000 })
461        );
462        assert_eq!(
463            SeqNo::try_new(SeqNo::MAX.value()).map(SeqNo::value),
464            Ok(0x7FFF_FFFF)
465        );
466    }
467
468    #[test]
469    fn seq_wraps_and_orders_circularly() {
470        assert_eq!(SeqNo::MAX.next(), SeqNo::from_wire_masked(0));
471        assert!(SeqNo::MAX.lt(SeqNo::from_wire_masked(0)));
472        assert_eq!(SeqNo::from_wire_masked(0).diff(SeqNo::MAX), 1);
473        assert!(SeqNo::from_wire_masked(10).lt(SeqNo::from_wire_masked(20)));
474        assert!(SeqNo::from_wire_masked(20).gt(SeqNo::from_wire_masked(10)));
475    }
476
477    #[test]
478    fn seq_closed_range_walks_across_the_wrap() {
479        let lo = SeqNo::MAX.add(SEQ_SPACE.mask() as u32); // (MAX + MAX) mod 2^31 = MAX - 1
480        assert_eq!(lo.value(), constant_max_minus_one());
481        assert!(SeqNo::from_wire_masked(0).in_closed_range(lo, SeqNo::from_wire_masked(1)));
482        assert!(
483            SeqNo::from_wire_masked(SeqNo::MAX.value())
484                .in_closed_range(lo, SeqNo::from_wire_masked(1))
485        );
486        assert!(!SeqNo::from_wire_masked(2).in_closed_range(lo, SeqNo::from_wire_masked(1)));
487    }
488
489    fn constant_max_minus_one() -> u32 {
490        SeqNo::MAX.value() - 1
491    }
492
493    #[test]
494    fn socket_id_round_trips_and_names_the_connection_request() {
495        assert!(SocketId::CONNECTION_REQUEST.is_connection_request());
496        assert!(!SocketId::from_wire(7).is_connection_request());
497        assert_eq!(u32::from(SocketId::from_wire(42)), 42);
498    }
499
500    #[test]
501    fn message_number_wraps_to_one_and_rejects_overwide() {
502        assert_eq!(MessageNumber::from_wire_masked(0).next().value(), 1);
503        assert_eq!(
504            MessageNumber::from_wire_masked(MESSAGE_NUMBER_MASK)
505                .next()
506                .value(),
507            1
508        );
509        assert_eq!(
510            MessageNumber::try_new(1 << MESSAGE_NUMBER_BITS),
511            Err(MessageNumberOutOfRange {
512                value: 1 << MESSAGE_NUMBER_BITS
513            })
514        );
515    }
516
517    #[test]
518    fn message_number_masks_the_wire_word() {
519        assert_eq!(MessageNumber::from_wire_masked(0xFC00_0005).value(), 5);
520    }
521}