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