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