Skip to main content

srt_runtime/packet/
misc.rs

1//! The CIF-less / single-scalar-CIF control packets: Keep-Alive (§3.2.3),
2//! Congestion Warning (§3.2.6), Shutdown (§3.2.7), ACKACK (§3.2.8), Message
3//! Drop Request (§3.2.9), and Peer Error (§3.2.10).
4
5use super::{Error, Result, be32, put_be32};
6
7/// Peer error code for a file-system error — the only value
8/// `draft-sharabayko-srt-01` §3.2.10 currently defines.
9pub const PEER_ERROR_FILE_SYSTEM: u32 = 4000;
10
11/// Keep-Alive control packet (§3.2.3, Figure 12). No CIF.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
13#[cfg_attr(feature = "serde", derive(serde::Serialize))]
14pub struct KeepAlivePacket {
15    /// Timestamp (§3).
16    pub timestamp: u32,
17    /// Destination Socket ID (§3).
18    pub dest_socket_id: u32,
19    /// `true` when the CIF carries libsrt's 4-byte zero pad; `false` for the
20    /// empty CIF of draft-sharabayko-srt-01.
21    pub libsrt_pad: bool,
22}
23
24/// Congestion Warning control packet (§3.2.6, Figure 15). Reserved for future
25/// use; no CIF.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
27#[cfg_attr(feature = "serde", derive(serde::Serialize))]
28pub struct CongestionWarningPacket {
29    /// Timestamp (§3).
30    pub timestamp: u32,
31    /// Destination Socket ID (§3).
32    pub dest_socket_id: u32,
33    /// `true` when the CIF carries libsrt's 4-byte zero pad; `false` for the
34    /// empty CIF of draft-sharabayko-srt-01.
35    pub libsrt_pad: bool,
36}
37
38/// Shutdown control packet (§3.2.7, Figure 16). No CIF.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
40#[cfg_attr(feature = "serde", derive(serde::Serialize))]
41pub struct ShutdownPacket {
42    /// Timestamp (§3).
43    pub timestamp: u32,
44    /// Destination Socket ID (§3).
45    pub dest_socket_id: u32,
46    /// `true` when the CIF carries libsrt's 4-byte zero pad; `false` for the
47    /// empty CIF of draft-sharabayko-srt-01.
48    pub libsrt_pad: bool,
49}
50
51/// ACKACK control packet (§3.2.8, Figure 17). No CIF.
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
53#[cfg_attr(feature = "serde", derive(serde::Serialize))]
54pub struct AckAckPacket {
55    /// Acknowledgement Number of the Full ACK being acknowledged.
56    pub ack_number: u32,
57    /// Timestamp (§3).
58    pub timestamp: u32,
59    /// Destination Socket ID (§3).
60    pub dest_socket_id: u32,
61    /// `true` when the CIF carries libsrt's 4-byte zero pad; `false` for the
62    /// empty CIF of draft-sharabayko-srt-01.
63    pub libsrt_pad: bool,
64}
65
66/// Message Drop Request control packet (§3.2.9, Figure 18).
67#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
68#[cfg_attr(feature = "serde", derive(serde::Serialize))]
69pub struct DropReqPacket {
70    /// The message number requested to be dropped (`0` if the sender no
71    /// longer has the packets and cannot restore it).
72    pub message_number: u32,
73    /// Timestamp (§3).
74    pub timestamp: u32,
75    /// Destination Socket ID (§3).
76    pub dest_socket_id: u32,
77    /// First Packet Sequence Number of the range to drop.
78    pub first_seq: u32,
79    /// Last Packet Sequence Number of the range to drop.
80    pub last_seq: u32,
81}
82
83impl DropReqPacket {
84    pub(crate) fn parse_cif(
85        message_number: u32,
86        timestamp: u32,
87        dest_socket_id: u32,
88        cif: &[u8],
89    ) -> Result<Self> {
90        if cif.len() != 8 {
91            return Err(Error::BufferTooShort {
92                need: 8,
93                have: cif.len(),
94                what: "drop request CIF",
95            });
96        }
97        Ok(DropReqPacket {
98            message_number,
99            timestamp,
100            dest_socket_id,
101            first_seq: be32(cif, 0),
102            last_seq: be32(cif, 4),
103        })
104    }
105
106    pub(crate) fn cif_len(&self) -> usize {
107        8
108    }
109
110    pub(crate) fn write_cif(&self, buf: &mut [u8]) {
111        put_be32(buf, 0, self.first_seq);
112        put_be32(buf, 4, self.last_seq);
113    }
114}
115
116/// Peer Error control packet (§3.2.10, Figure 19). No CIF.
117#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
118#[cfg_attr(feature = "serde", derive(serde::Serialize))]
119pub struct PeerErrorPacket {
120    /// Peer error code (see [`PEER_ERROR_FILE_SYSTEM`]).
121    pub error_code: u32,
122    /// Timestamp (§3).
123    pub timestamp: u32,
124    /// Destination Socket ID (§3).
125    pub dest_socket_id: u32,
126    /// `true` when the CIF carries libsrt's 4-byte zero pad; `false` for the
127    /// empty CIF of draft-sharabayko-srt-01.
128    pub libsrt_pad: bool,
129}
130
131#[cfg(test)]
132mod tests {
133    use alloc::vec::Vec;
134
135    use super::super::control::ControlPacket;
136    use super::*;
137
138    #[test]
139    fn drop_req_round_trips() {
140        let d = DropReqPacket {
141            message_number: 7,
142            timestamp: 100,
143            dest_socket_id: 200,
144            first_seq: 10,
145            last_seq: 20,
146        };
147        let pkt = ControlPacket::DropReq(d);
148        let mut buf = [0u8; 24];
149        let n = pkt.serialize_into(&mut buf).unwrap();
150        assert_eq!(n, 24);
151        assert_eq!(&buf[4..8], &7u32.to_be_bytes()); // message number in word1
152        assert_eq!(&buf[16..20], &10u32.to_be_bytes());
153        assert_eq!(&buf[20..24], &20u32.to_be_bytes());
154        let parsed = ControlPacket::parse(&buf).unwrap();
155        assert_eq!(parsed, pkt);
156    }
157
158    #[test]
159    fn keepalive_congestion_shutdown_ackack_peererror_round_trip() {
160        let cases: Vec<ControlPacket> = alloc::vec![
161            ControlPacket::KeepAlive(KeepAlivePacket {
162                timestamp: 1,
163                dest_socket_id: 2,
164                libsrt_pad: true,
165            }),
166            ControlPacket::CongestionWarning(CongestionWarningPacket {
167                timestamp: 3,
168                dest_socket_id: 4,
169                libsrt_pad: true,
170            }),
171            ControlPacket::Shutdown(ShutdownPacket {
172                timestamp: 5,
173                dest_socket_id: 6,
174                libsrt_pad: true,
175            }),
176            ControlPacket::AckAck(AckAckPacket {
177                ack_number: 9,
178                timestamp: 7,
179                dest_socket_id: 8,
180                libsrt_pad: true,
181            }),
182            ControlPacket::PeerError(PeerErrorPacket {
183                error_code: PEER_ERROR_FILE_SYSTEM,
184                timestamp: 11,
185                dest_socket_id: 12,
186                libsrt_pad: true,
187            }),
188        ];
189        for pkt in cases {
190            // 20 bytes when libsrt_pad is true: serializes with the 4-byte
191            // zero pad (see `control::LIBSRT_CIF_PAD_LEN`).
192            let mut buf = [0u8; 20];
193            let n = pkt.serialize_into(&mut buf).unwrap();
194            assert_eq!(n, 20);
195            assert_eq!(&buf[16..20], &[0, 0, 0, 0]);
196            let parsed = ControlPacket::parse(&buf).unwrap();
197            assert_eq!(parsed, pkt);
198        }
199    }
200
201    /// A peer (e.g. real libsrt — see `tests/it/libsrt_fixtures.rs`) may also
202    /// send these types with the pure-spec empty CIF instead of the pad.
203    /// Both 16-byte (no-pad) and 20-byte (with-pad) wire shapes parse correctly.
204    #[test]
205    fn keepalive_congestion_shutdown_ackack_peererror_accept_empty_cif() {
206        let cases: Vec<ControlPacket> = alloc::vec![
207            ControlPacket::KeepAlive(KeepAlivePacket {
208                timestamp: 1,
209                dest_socket_id: 2,
210                libsrt_pad: false,
211            }),
212            ControlPacket::CongestionWarning(CongestionWarningPacket {
213                timestamp: 3,
214                dest_socket_id: 4,
215                libsrt_pad: false,
216            }),
217            ControlPacket::Shutdown(ShutdownPacket {
218                timestamp: 5,
219                dest_socket_id: 6,
220                libsrt_pad: false,
221            }),
222            ControlPacket::AckAck(AckAckPacket {
223                ack_number: 9,
224                timestamp: 7,
225                dest_socket_id: 8,
226                libsrt_pad: false,
227            }),
228            ControlPacket::PeerError(PeerErrorPacket {
229                error_code: PEER_ERROR_FILE_SYSTEM,
230                timestamp: 11,
231                dest_socket_id: 12,
232                libsrt_pad: false,
233            }),
234        ];
235        for pkt in cases {
236            // Serialize with libsrt_pad: false -> 16 bytes
237            let mut buf = [0u8; 16];
238            let n = pkt.serialized_len();
239            assert_eq!(n, 16, "16-byte packets with libsrt_pad: false");
240            pkt.serialize_into(&mut buf).unwrap();
241
242            // Parse the 16-byte form back
243            let parsed = ControlPacket::parse(&buf).unwrap();
244            assert_eq!(parsed, pkt);
245        }
246    }
247
248    /// A 16-byte (pure-spec empty CIF) KEEPALIVE packet parses and
249    /// round-trips byte-identically.
250    #[test]
251    fn sixteen_byte_keepalive_round_trip_byte_identical() {
252        let pkt = ControlPacket::KeepAlive(KeepAlivePacket {
253            timestamp: 0x1234,
254            dest_socket_id: 0x5678,
255            libsrt_pad: false,
256        });
257        let mut buf = [0u8; 16];
258        let n = pkt.serialize_into(&mut buf).unwrap();
259        assert_eq!(n, 16, "16-byte packet with libsrt_pad: false");
260
261        let parsed = ControlPacket::parse(&buf).unwrap();
262        assert_eq!(parsed, pkt);
263
264        let mut reserialized = [0u8; 16];
265        let n = parsed.serialize_into(&mut reserialized).unwrap();
266        assert_eq!(n, 16);
267        assert_eq!(&reserialized[..], &buf[..], "round-trip is byte-identical");
268    }
269
270    /// A 20-byte (libsrt's 4-byte zero pad) KEEPALIVE packet parses and
271    /// round-trips byte-identically.
272    #[test]
273    fn twenty_byte_keepalive_round_trip_byte_identical() {
274        let pkt = ControlPacket::KeepAlive(KeepAlivePacket {
275            timestamp: 0x1234,
276            dest_socket_id: 0x5678,
277            libsrt_pad: true,
278        });
279        let mut buf = [0u8; 20];
280        let n = pkt.serialize_into(&mut buf).unwrap();
281        assert_eq!(n, 20, "20-byte packet with libsrt_pad: true");
282        assert_eq!(&buf[16..20], &[0, 0, 0, 0], "CIF is 4-byte zero pad");
283
284        let parsed = ControlPacket::parse(&buf).unwrap();
285        assert_eq!(parsed, pkt);
286
287        let mut reserialized = [0u8; 20];
288        let n = parsed.serialize_into(&mut reserialized).unwrap();
289        assert_eq!(n, 20);
290        assert_eq!(&reserialized[..], &buf[..], "round-trip is byte-identical");
291    }
292
293    #[test]
294    fn keepalive_rejects_trailing_bytes() {
295        // Neither 0 (pure spec) nor 4 (libsrt's pad, §control::LIBSRT_CIF_PAD_LEN):
296        // 1 stray byte must still be rejected.
297        let mut buf = [0u8; 17];
298        buf[0] = 0x80; // F=1
299        buf[1] = 0x01; // control type = 1 (KEEPALIVE)
300        assert!(matches!(
301            ControlPacket::parse(&buf),
302            Err(Error::UnexpectedTrailingBytes { .. })
303        ));
304    }
305
306    #[test]
307    fn keepalive_rejects_nonzero_pad() {
308        let mut buf = [0u8; 20];
309        buf[0] = 0x80; // F=1
310        buf[1] = 0x01; // control type = 1 (KEEPALIVE)
311        buf[19] = 0x01; // non-zero byte in the 4-byte pad
312        assert!(matches!(
313            ControlPacket::parse(&buf),
314            Err(Error::ReservedFieldNotZero { .. })
315        ));
316    }
317}