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, thiserror::Error)]
140#[error("sequence number {value:#010X} exceeds the 31-bit range")]
141#[non_exhaustive]
142pub struct SeqOutOfRange {
143    /// The rejected value.
144    pub value: u32,
145}
146
147impl TryFrom<u32> for SeqNo {
148    type Error = SeqOutOfRange;
149    fn try_from(value: u32) -> Result<Self, Self::Error> {
150        Self::try_new(value)
151    }
152}
153
154impl From<SeqNo> for u32 {
155    fn from(seq: SeqNo) -> Self {
156        seq.0
157    }
158}
159
160impl core::fmt::Debug for SeqNo {
161    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
162        write!(f, "SeqNo({:#010X})", self.0)
163    }
164}
165
166impl core::fmt::Display for SeqNo {
167    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
168        write!(f, "{}", self.0)
169    }
170}
171
172/// An SRT Socket ID — the 32-bit Destination Socket ID / Source Socket ID of
173/// `draft-sharabayko-srt-01` §3, Figure 2.
174///
175/// Every value fits the 32-bit wire field, so there is no range rejection;
176/// the type exists so a socket id cannot be confused with a sequence number, a
177/// timestamp or an arbitrary count. `0` is meaningful — on a handshake induction
178/// packet it is the connection request sentinel (§4.3.1.1).
179#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
180#[cfg_attr(feature = "serde", derive(serde::Serialize))]
181#[cfg_attr(feature = "serde", serde(transparent))]
182pub struct SocketId(u32);
183
184impl SocketId {
185    /// The connection-request sentinel: a Destination Socket ID of `0` on a
186    /// handshake induction packet (§4.3.1.1).
187    pub const CONNECTION_REQUEST: SocketId = SocketId(0);
188
189    /// Construct a `SocketId` from its 32-bit wire value.
190    #[must_use]
191    pub const fn from_wire(value: u32) -> Self {
192        Self(value)
193    }
194
195    /// The raw 32-bit wire value.
196    #[must_use]
197    pub const fn value(self) -> u32 {
198        self.0
199    }
200
201    /// Whether this is the connection-request sentinel ([`Self::CONNECTION_REQUEST`]).
202    #[must_use]
203    pub const fn is_connection_request(self) -> bool {
204        self.0 == 0
205    }
206}
207
208impl From<u32> for SocketId {
209    fn from(value: u32) -> Self {
210        SocketId(value)
211    }
212}
213
214impl From<SocketId> for u32 {
215    fn from(id: SocketId) -> Self {
216        id.0
217    }
218}
219
220impl core::fmt::Debug for SocketId {
221    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
222        write!(f, "SocketId({})", self.0)
223    }
224}
225
226impl core::fmt::Display for SocketId {
227    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
228        write!(f, "{}", self.0)
229    }
230}
231
232/// The sequential number of a Full ACK control packet — the
233/// `draft-sharabayko-srt-01` §3.2.4 (Figure 13) `Acknowledgement Number`,
234/// carried in the control header's `Type-specific Information` word, and
235/// echoed back by the ACKACK that acknowledges it (§3.2.8, Figure 17).
236///
237/// Unlike [`SeqNo`], whose 31-bit space exists because the top bit of a *data*
238/// packet's first header word is the `F` flag, this field occupies a whole
239/// 32-bit word: no bit in it is reserved and no value is unrepresentable, so
240/// there is no range rejection. The type keeps an ACK's numbering (an
241/// incrementing counter, §4.8.1) from being confused with a sequence number, a
242/// socket id, a timestamp or a plain count.
243#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
244#[cfg_attr(feature = "serde", derive(serde::Serialize))]
245#[cfg_attr(feature = "serde", serde(transparent))]
246pub struct AckNumber(u32);
247
248impl AckNumber {
249    /// The zero acknowledgement number — what a Small/Light ACK carries
250    /// (§3.2.4: their `Type-specific Information` "should be set to 0").
251    pub const ZERO: AckNumber = AckNumber(0);
252
253    /// Construct an `AckNumber` from its 32-bit wire value.
254    #[must_use]
255    pub const fn from_wire(value: u32) -> Self {
256        Self(value)
257    }
258
259    /// The raw 32-bit wire value.
260    #[must_use]
261    pub const fn value(self) -> u32 {
262        self.0
263    }
264}
265
266impl From<u32> for AckNumber {
267    fn from(value: u32) -> Self {
268        AckNumber(value)
269    }
270}
271
272impl From<AckNumber> for u32 {
273    fn from(n: AckNumber) -> Self {
274        n.0
275    }
276}
277
278impl core::fmt::Debug for AckNumber {
279    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
280        write!(f, "AckNumber({})", self.0)
281    }
282}
283
284impl core::fmt::Display for AckNumber {
285    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
286        write!(f, "{}", self.0)
287    }
288}
289
290/// A 26-bit SRT Message Number (`draft-sharabayko-srt-01` §3.1, Figure 3:
291/// `Message Number (26)`).
292///
293/// The value always fits the 26-bit field. [`MessageNumber::next`] wraps at
294/// the 26-bit boundary back to `1`, not `0`: libsrt's public header reserves
295/// message number `0` (`SRT_MSGNO_CONTROL`) as a packet-filter control
296/// sentinel, so a data packet must never carry it (issue #1062).
297#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
298#[cfg_attr(feature = "serde", derive(serde::Serialize))]
299#[cfg_attr(feature = "serde", serde(transparent))]
300pub struct MessageNumber(u32);
301
302impl MessageNumber {
303    /// Construct a `MessageNumber`, rejecting a value that does not fit the
304    /// 26-bit field.
305    ///
306    /// # Errors
307    /// [`MessageNumberOutOfRange`] when `value` exceeds [`MESSAGE_NUMBER_MASK`].
308    pub const fn try_new(value: u32) -> Result<Self, MessageNumberOutOfRange> {
309        if value > MESSAGE_NUMBER_MASK {
310            Err(MessageNumberOutOfRange { value })
311        } else {
312            Ok(Self(value))
313        }
314    }
315
316    /// Construct a `MessageNumber` from the low 26 bits of `value`,
317    /// **deliberately** discarding the rest — the parse-site constructor for
318    /// the `word1` Message Number field (§3.1).
319    #[must_use]
320    pub const fn from_wire_masked(value: u32) -> Self {
321        Self(value & MESSAGE_NUMBER_MASK)
322    }
323
324    /// The raw 26-bit value.
325    #[must_use]
326    pub const fn value(self) -> u32 {
327        self.0
328    }
329
330    /// The next Message Number after `self`, wrapping at the 26-bit boundary
331    /// to `1` (never `0` — see the type doc).
332    #[must_use]
333    pub const fn next(self) -> Self {
334        match ((self.0 & MESSAGE_NUMBER_MASK) + 1) & MESSAGE_NUMBER_MASK {
335            0 => Self(1),
336            next => Self(next),
337        }
338    }
339}
340
341/// A message number that does not fit the 26-bit field
342/// (`draft-sharabayko-srt-01` §3.1).
343#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
344#[error("message number {value:#010X} exceeds the 26-bit range")]
345#[non_exhaustive]
346pub struct MessageNumberOutOfRange {
347    /// The rejected value.
348    pub value: u32,
349}
350
351impl TryFrom<u32> for MessageNumber {
352    type Error = MessageNumberOutOfRange;
353    fn try_from(value: u32) -> Result<Self, Self::Error> {
354        Self::try_new(value)
355    }
356}
357
358impl From<MessageNumber> for u32 {
359    fn from(n: MessageNumber) -> Self {
360        n.0
361    }
362}
363
364impl core::fmt::Debug for MessageNumber {
365    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
366        write!(f, "MessageNumber({})", self.0)
367    }
368}
369
370impl core::fmt::Display for MessageNumber {
371    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
372        write!(f, "{}", self.0)
373    }
374}
375
376/// An SRT header Timestamp — the 32-bit field of `draft-sharabayko-srt-01` §3
377/// (Figure 2), carried by every data and control packet.
378///
379/// On a data packet it is a media timestamp in microseconds relative to
380/// connection establishment (§3.1), wrapping every `2^32` µs (~71.58 min,
381/// rule 15 of `private/specs-verified/rules/srt-tsbpd.md`); on a control packet
382/// it is the sender's current time for the packet's purpose (§3.2). It always
383/// fits the 32-bit field, so there is no range rejection — the type keeps a
384/// header timestamp from being confused with a sequence number, a socket id or
385/// a plain count.
386#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
387#[cfg_attr(feature = "serde", derive(serde::Serialize))]
388#[cfg_attr(feature = "serde", serde(transparent))]
389pub struct SrtTimestamp(u32);
390
391impl SrtTimestamp {
392    /// The zero timestamp.
393    pub const ZERO: SrtTimestamp = SrtTimestamp(0);
394
395    /// Construct an `SrtTimestamp` from its 32-bit wire value.
396    #[must_use]
397    pub const fn from_wire(value: u32) -> Self {
398        Self(value)
399    }
400
401    /// The raw 32-bit wire value.
402    #[must_use]
403    pub const fn value(self) -> u32 {
404        self.0
405    }
406}
407
408impl From<u32> for SrtTimestamp {
409    fn from(value: u32) -> Self {
410        SrtTimestamp(value)
411    }
412}
413
414impl From<SrtTimestamp> for u32 {
415    fn from(ts: SrtTimestamp) -> Self {
416        ts.0
417    }
418}
419
420impl core::fmt::Debug for SrtTimestamp {
421    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
422        write!(f, "SrtTimestamp({})", self.0)
423    }
424}
425
426impl core::fmt::Display for SrtTimestamp {
427    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
428        write!(f, "{}", self.0)
429    }
430}
431
432#[cfg(test)]
433mod tests {
434    use super::*;
435
436    /// An ACK/ACKACK Acknowledgement Number is a whole 32-bit word
437    /// (§3.2.4/§3.2.8): no value is out of range, unlike the 31-bit
438    /// [`SeqNo`], so the type never rejects or masks one.
439    #[test]
440    fn ack_number_keeps_every_32_bit_value() {
441        for v in [0, 1, 0x7FFF_FFFF, 0x8000_0000, 0xFFFF_FFFF] {
442            let n = AckNumber::from_wire(v);
443            assert_eq!(n.value(), v);
444            assert_eq!(u32::from(AckNumber::from(v)), v);
445            assert_eq!(alloc::format!("{n:?}"), alloc::format!("AckNumber({v})"));
446            assert_eq!(alloc::format!("{n}"), alloc::format!("{v}"));
447        }
448        assert_eq!(AckNumber::ZERO.value(), 0);
449    }
450
451    #[test]
452    fn seq_space_matches_the_wire_mask() {
453        assert_eq!(SEQ_SPACE.mask().count_ones(), SEQ_SPACE_BITS);
454        assert_eq!(SeqNo::MAX.value().count_ones(), 31);
455        assert_eq!(SeqNo::from_wire_masked(0x8000_0005).value(), 5);
456    }
457
458    #[test]
459    fn seq_try_new_rejects_an_out_of_range_value() {
460        assert_eq!(
461            SeqNo::try_new(0x8000_0000),
462            Err(SeqOutOfRange { value: 0x8000_0000 })
463        );
464        assert_eq!(
465            SeqNo::try_new(SeqNo::MAX.value()).map(SeqNo::value),
466            Ok(0x7FFF_FFFF)
467        );
468    }
469
470    #[test]
471    fn seq_wraps_and_orders_circularly() {
472        assert_eq!(SeqNo::MAX.next(), SeqNo::from_wire_masked(0));
473        assert!(SeqNo::MAX.lt(SeqNo::from_wire_masked(0)));
474        assert_eq!(SeqNo::from_wire_masked(0).diff(SeqNo::MAX), 1);
475        assert!(SeqNo::from_wire_masked(10).lt(SeqNo::from_wire_masked(20)));
476        assert!(SeqNo::from_wire_masked(20).gt(SeqNo::from_wire_masked(10)));
477    }
478
479    #[test]
480    fn seq_closed_range_walks_across_the_wrap() {
481        let lo = SeqNo::MAX.add(SEQ_SPACE.mask()); // (MAX + MAX) mod 2^31 = MAX - 1
482        assert_eq!(lo.value(), constant_max_minus_one());
483        assert!(SeqNo::from_wire_masked(0).in_closed_range(lo, SeqNo::from_wire_masked(1)));
484        assert!(
485            SeqNo::from_wire_masked(SeqNo::MAX.value())
486                .in_closed_range(lo, SeqNo::from_wire_masked(1))
487        );
488        assert!(!SeqNo::from_wire_masked(2).in_closed_range(lo, SeqNo::from_wire_masked(1)));
489    }
490
491    fn constant_max_minus_one() -> u32 {
492        SeqNo::MAX.value() - 1
493    }
494
495    #[test]
496    fn socket_id_round_trips_and_names_the_connection_request() {
497        assert!(SocketId::CONNECTION_REQUEST.is_connection_request());
498        assert!(!SocketId::from_wire(7).is_connection_request());
499        assert_eq!(u32::from(SocketId::from_wire(42)), 42);
500    }
501
502    #[test]
503    fn message_number_wraps_to_one_and_rejects_overwide() {
504        assert_eq!(MessageNumber::from_wire_masked(0).next().value(), 1);
505        assert_eq!(
506            MessageNumber::from_wire_masked(MESSAGE_NUMBER_MASK)
507                .next()
508                .value(),
509            1
510        );
511        assert_eq!(
512            MessageNumber::try_new(1 << MESSAGE_NUMBER_BITS),
513            Err(MessageNumberOutOfRange {
514                value: 1 << MESSAGE_NUMBER_BITS
515            })
516        );
517    }
518
519    #[test]
520    fn message_number_masks_the_wire_word() {
521        assert_eq!(MessageNumber::from_wire_masked(0xFC00_0005).value(), 5);
522    }
523}