Skip to main content

srt_runtime/packet/
control.rs

1//! SRT control packet dispatch — `draft-sharabayko-srt-01` §3.2, Figure 4,
2//! Table 1.
3//!
4//! ```text
5//! word0  1|         Control Type (15)   |          Subtype (16)         |
6//! word1                   Type-specific Information (32)
7//! word2                          Timestamp (32)
8//! word3                    Destination Socket ID (32)
9//! rest                              CIF (variable, per Control Type)
10//! ```
11//!
12//! `Subtype` is `0x0` for every Control Type in Table 1 except
13//! `User-Defined Type` (`0x7FFF`), where it carries `SRT_CMD_KMREQ` /
14//! `SRT_CMD_KMRSP` (Table 5) when the CIF is a Key Material message (§3.2.2).
15//! `Subtype` and the `Type-specific Information` word (where a given packet
16//! type does not use it) are validated as reserved-must-be-zero and are not
17//! stored in the typed per-type structs — see the crate root's reserved-bit
18//! policy.
19
20use super::ack::AckPacket;
21use super::handshake::HandshakePacket;
22use super::misc::{
23    AckAckPacket, CongestionWarningPacket, DropReqPacket, KeepAlivePacket, PeerErrorPacket,
24    ShutdownPacket,
25};
26use super::nak::NakPacket;
27use super::{Error, Result, SRT_HEADER_LEN, be32, put_be32};
28
29/// `Control Type` wire values (`draft-sharabayko-srt-01` §3.2, Table 1).
30pub const CONTROL_TYPE_HANDSHAKE: u16 = 0x0000;
31/// Keep-Alive (§3.2.3).
32pub const CONTROL_TYPE_KEEPALIVE: u16 = 0x0001;
33/// ACK (§3.2.4).
34pub const CONTROL_TYPE_ACK: u16 = 0x0002;
35/// NAK / Loss Report (§3.2.5).
36pub const CONTROL_TYPE_NAK: u16 = 0x0003;
37/// Congestion Warning (§3.2.6).
38pub const CONTROL_TYPE_CONGESTION_WARNING: u16 = 0x0004;
39/// Shutdown (§3.2.7).
40pub const CONTROL_TYPE_SHUTDOWN: u16 = 0x0005;
41/// ACKACK (§3.2.8).
42pub const CONTROL_TYPE_ACKACK: u16 = 0x0006;
43/// Message Drop Request (§3.2.9).
44pub const CONTROL_TYPE_DROPREQ: u16 = 0x0007;
45/// Peer Error (§3.2.10).
46pub const CONTROL_TYPE_PEERERROR: u16 = 0x0008;
47/// User-Defined Type (reserved value; also carries the Key Material message
48/// per §3.2.2 via `Subtype` `SRT_CMD_KMREQ`/`SRT_CMD_KMRSP`).
49pub const CONTROL_TYPE_USER_DEFINED: u16 = 0x7FFF;
50
51/// The `Control Type` field (`draft-sharabayko-srt-01` §3.2, Table 1) — 15
52/// bits.
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
54#[cfg_attr(feature = "serde", derive(serde::Serialize))]
55#[non_exhaustive]
56pub enum ControlType {
57    /// `0x0000` — Handshake (§3.2.1).
58    Handshake,
59    /// `0x0001` — Keep-Alive (§3.2.3).
60    KeepAlive,
61    /// `0x0002` — ACK (§3.2.4).
62    Ack,
63    /// `0x0003` — NAK / Loss Report (§3.2.5).
64    Nak,
65    /// `0x0004` — Congestion Warning (§3.2.6).
66    CongestionWarning,
67    /// `0x0005` — Shutdown (§3.2.7).
68    Shutdown,
69    /// `0x0006` — ACKACK (§3.2.8).
70    AckAck,
71    /// `0x0007` — Message Drop Request (§3.2.9).
72    DropReq,
73    /// `0x0008` — Peer Error (§3.2.10).
74    PeerError,
75    /// `0x7FFF` — User-Defined Type (also the Key Material control-packet
76    /// delivery form, §3.2.2).
77    UserDefined,
78    /// A Control Type value Table 1 does not define.
79    Reserved(u16),
80}
81
82impl ControlType {
83    /// Decode a 15-bit `Control Type` value.
84    pub fn from_bits(v: u16) -> Self {
85        match v {
86            CONTROL_TYPE_HANDSHAKE => ControlType::Handshake,
87            CONTROL_TYPE_KEEPALIVE => ControlType::KeepAlive,
88            CONTROL_TYPE_ACK => ControlType::Ack,
89            CONTROL_TYPE_NAK => ControlType::Nak,
90            CONTROL_TYPE_CONGESTION_WARNING => ControlType::CongestionWarning,
91            CONTROL_TYPE_SHUTDOWN => ControlType::Shutdown,
92            CONTROL_TYPE_ACKACK => ControlType::AckAck,
93            CONTROL_TYPE_DROPREQ => ControlType::DropReq,
94            CONTROL_TYPE_PEERERROR => ControlType::PeerError,
95            CONTROL_TYPE_USER_DEFINED => ControlType::UserDefined,
96            other => ControlType::Reserved(other),
97        }
98    }
99
100    /// The wire value.
101    pub fn to_bits(self) -> u16 {
102        match self {
103            ControlType::Handshake => CONTROL_TYPE_HANDSHAKE,
104            ControlType::KeepAlive => CONTROL_TYPE_KEEPALIVE,
105            ControlType::Ack => CONTROL_TYPE_ACK,
106            ControlType::Nak => CONTROL_TYPE_NAK,
107            ControlType::CongestionWarning => CONTROL_TYPE_CONGESTION_WARNING,
108            ControlType::Shutdown => CONTROL_TYPE_SHUTDOWN,
109            ControlType::AckAck => CONTROL_TYPE_ACKACK,
110            ControlType::DropReq => CONTROL_TYPE_DROPREQ,
111            ControlType::PeerError => CONTROL_TYPE_PEERERROR,
112            ControlType::UserDefined => CONTROL_TYPE_USER_DEFINED,
113            ControlType::Reserved(v) => v,
114        }
115    }
116
117    /// Spec label.
118    pub fn name(&self) -> &'static str {
119        match self {
120            ControlType::Handshake => "handshake",
121            ControlType::KeepAlive => "keep-alive",
122            ControlType::Ack => "ACK",
123            ControlType::Nak => "NAK",
124            ControlType::CongestionWarning => "congestion warning",
125            ControlType::Shutdown => "shutdown",
126            ControlType::AckAck => "ACKACK",
127            ControlType::DropReq => "message drop request",
128            ControlType::PeerError => "peer error",
129            ControlType::UserDefined => "user-defined",
130            ControlType::Reserved(_) => "reserved",
131        }
132    }
133}
134
135broadcast_common::impl_spec_display!(ControlType, Reserved);
136
137/// A Control Type = User-Defined (`0x7FFF`) packet, or a Control Type not
138/// defined by Table 1. The CIF is genuinely opaque here — the only defined
139/// use is the Key Material message (§3.2.2) via `Subtype`
140/// `SRT_CMD_KMREQ`/`SRT_CMD_KMRSP` — see [`Self::as_key_material`].
141#[derive(Debug, Clone, PartialEq)]
142#[cfg_attr(feature = "serde", derive(serde::Serialize))]
143pub struct UserDefinedPacket<'a> {
144    /// The raw 15-bit Control Type value.
145    pub control_type: u16,
146    /// The 16-bit Subtype — `SRT_CMD_KMREQ`/`SRT_CMD_KMRSP` when the CIF is
147    /// Key Material (Table 5), otherwise vendor-defined.
148    pub subtype: u16,
149    /// The header `Type-specific Information` word.
150    pub type_specific_info: u32,
151    /// Timestamp (§3).
152    pub timestamp: u32,
153    /// Destination Socket ID (§3).
154    pub dest_socket_id: u32,
155    /// The raw CIF bytes.
156    pub cif: &'a [u8],
157}
158
159impl<'a> UserDefinedPacket<'a> {
160    /// Attempt to decode [`Self::cif`] as a Key Material message (§3.2.2).
161    /// Valid regardless of [`Self::subtype`] — callers that care should check
162    /// `subtype` against `SRT_CMD_KMREQ`/`SRT_CMD_KMRSP` (Table 5) first.
163    pub fn as_key_material(&self) -> Result<super::KeyMaterial<'a>> {
164        super::KeyMaterial::parse(self.cif)
165    }
166}
167
168/// An SRT control packet (`draft-sharabayko-srt-01` §3.2).
169#[derive(Debug, Clone, PartialEq)]
170#[cfg_attr(feature = "serde", derive(serde::Serialize))]
171#[non_exhaustive]
172pub enum ControlPacket<'a> {
173    /// Handshake (§3.2.1).
174    Handshake(HandshakePacket<'a>),
175    /// Keep-Alive (§3.2.3).
176    KeepAlive(KeepAlivePacket),
177    /// ACK (§3.2.4).
178    Ack(AckPacket),
179    /// NAK / Loss Report (§3.2.5).
180    Nak(NakPacket<'a>),
181    /// Congestion Warning (§3.2.6).
182    CongestionWarning(CongestionWarningPacket),
183    /// Shutdown (§3.2.7).
184    Shutdown(ShutdownPacket),
185    /// ACKACK (§3.2.8).
186    AckAck(AckAckPacket),
187    /// Message Drop Request (§3.2.9).
188    DropReq(DropReqPacket),
189    /// Peer Error (§3.2.10).
190    PeerError(PeerErrorPacket),
191    /// User-Defined Type, or a Control Type Table 1 does not define.
192    UserDefined(UserDefinedPacket<'a>),
193}
194
195fn check_reserved_u16(what: &'static str, v: u16) -> Result<()> {
196    if v != 0 {
197        return Err(Error::ReservedFieldNotZero {
198            what,
199            value: u64::from(v),
200        });
201    }
202    Ok(())
203}
204
205fn check_reserved_u32(what: &'static str, v: u32) -> Result<()> {
206    if v != 0 {
207        return Err(Error::ReservedFieldNotZero {
208            what,
209            value: u64::from(v),
210        });
211    }
212    Ok(())
213}
214
215/// Bytes libsrt appends to a control packet type whose CIF the spec documents
216/// as absent (Keep-Alive §3.2.3, Congestion Warning §3.2.6, Shutdown §3.2.7,
217/// ACKACK §3.2.8, Peer Error §3.2.10). libsrt's `CPacket::pack` always calls
218/// `m_PacketVector[PV_DATA].set(&m_extra_pad, 4)` for these types — its own
219/// comment says why: "control info field should be none but writev does not
220/// allow this" (`packet.cpp`, `CPacket::pack`, e.g. the `UMSG_KEEPALIVE` arm)
221/// — and `m_extra_pad` is a zero-initialized member, so the 4 bytes are
222/// always zero on the wire. Confirmed against a real `srt-live-transmit`
223/// 1.5.5 KEEPALIVE/ACKACK capture (`tests/fixtures/libsrt_*.bin`).
224const LIBSRT_CIF_PAD_LEN: usize = 4;
225
226/// Accept either the pure-spec empty CIF or libsrt's 4-byte zero pad (see
227/// [`LIBSRT_CIF_PAD_LEN`]); reject anything else. A non-zero 4-byte value is
228/// rejected the same way a defined reserved field is (`ReservedFieldNotZero`)
229/// — nothing defines those bits, so a peer setting them to something else is
230/// not a shape this crate recognizes. Returns `true` if the 4-byte pad was
231/// present, `false` for the empty CIF.
232fn check_no_cif_or_libsrt_pad(what: &'static str, cif: &[u8]) -> Result<bool> {
233    match cif.len() {
234        0 => Ok(false),
235        LIBSRT_CIF_PAD_LEN => {
236            let value = be32(cif, 0);
237            if value != 0 {
238                return Err(Error::ReservedFieldNotZero {
239                    what,
240                    value: u64::from(value),
241                });
242            }
243            Ok(true)
244        }
245        extra => Err(Error::UnexpectedTrailingBytes { what, extra }),
246    }
247}
248
249impl<'a> ControlPacket<'a> {
250    /// Parse a control packet from `bytes` (the full SRT packet).
251    ///
252    /// # Errors
253    /// [`Error::BufferTooShort`] if shorter than the 16-byte header;
254    /// [`Error::WrongPacketKind`] if the `F` bit is clear (this is a data
255    /// packet); type-specific errors from the dispatched CIF parser.
256    pub fn parse(bytes: &'a [u8]) -> Result<Self> {
257        if bytes.len() < SRT_HEADER_LEN {
258            return Err(Error::BufferTooShort {
259                need: SRT_HEADER_LEN,
260                have: bytes.len(),
261                what: "SRT control packet header",
262            });
263        }
264        let word0 = be32(bytes, 0);
265        if word0 & super::F_BIT == 0 {
266            return Err(Error::WrongPacketKind {
267                expected: "control packet (F=1)",
268            });
269        }
270        let control_type_bits = ((word0 >> 16) & 0x7FFF) as u16;
271        let subtype = (word0 & 0xFFFF) as u16;
272        let type_specific_info = be32(bytes, 4);
273        let timestamp = be32(bytes, 8);
274        let dest_socket_id = be32(bytes, 12);
275        let cif = &bytes[SRT_HEADER_LEN..];
276        let control_type = ControlType::from_bits(control_type_bits);
277
278        Ok(match control_type {
279            ControlType::Handshake => {
280                check_reserved_u16("Subtype", subtype)?;
281                check_reserved_u32("Type-specific Information", type_specific_info)?;
282                ControlPacket::Handshake(HandshakePacket::parse_cif(
283                    timestamp,
284                    dest_socket_id,
285                    cif,
286                )?)
287            }
288            ControlType::KeepAlive => {
289                check_reserved_u16("Subtype", subtype)?;
290                check_reserved_u32("Type-specific Information", type_specific_info)?;
291                let libsrt_pad = check_no_cif_or_libsrt_pad("keep-alive CIF", cif)?;
292                ControlPacket::KeepAlive(KeepAlivePacket {
293                    timestamp,
294                    dest_socket_id,
295                    libsrt_pad,
296                })
297            }
298            ControlType::Ack => {
299                check_reserved_u16("Subtype", subtype)?;
300                ControlPacket::Ack(AckPacket::parse_cif(
301                    type_specific_info,
302                    timestamp,
303                    dest_socket_id,
304                    cif,
305                )?)
306            }
307            ControlType::Nak => {
308                check_reserved_u16("Subtype", subtype)?;
309                check_reserved_u32("Type-specific Information", type_specific_info)?;
310                ControlPacket::Nak(NakPacket::parse_cif(timestamp, dest_socket_id, cif))
311            }
312            ControlType::CongestionWarning => {
313                check_reserved_u16("Subtype", subtype)?;
314                check_reserved_u32("Type-specific Information", type_specific_info)?;
315                let libsrt_pad = check_no_cif_or_libsrt_pad("congestion warning CIF", cif)?;
316                ControlPacket::CongestionWarning(CongestionWarningPacket {
317                    timestamp,
318                    dest_socket_id,
319                    libsrt_pad,
320                })
321            }
322            ControlType::Shutdown => {
323                check_reserved_u16("Subtype", subtype)?;
324                check_reserved_u32("Type-specific Information", type_specific_info)?;
325                let libsrt_pad = check_no_cif_or_libsrt_pad("shutdown CIF", cif)?;
326                ControlPacket::Shutdown(ShutdownPacket {
327                    timestamp,
328                    dest_socket_id,
329                    libsrt_pad,
330                })
331            }
332            ControlType::AckAck => {
333                check_reserved_u16("Subtype", subtype)?;
334                let libsrt_pad = check_no_cif_or_libsrt_pad("ACKACK CIF", cif)?;
335                ControlPacket::AckAck(AckAckPacket {
336                    ack_number: type_specific_info,
337                    timestamp,
338                    dest_socket_id,
339                    libsrt_pad,
340                })
341            }
342            ControlType::DropReq => {
343                check_reserved_u16("Subtype", subtype)?;
344                ControlPacket::DropReq(DropReqPacket::parse_cif(
345                    type_specific_info,
346                    timestamp,
347                    dest_socket_id,
348                    cif,
349                )?)
350            }
351            ControlType::PeerError => {
352                check_reserved_u16("Subtype", subtype)?;
353                let libsrt_pad = check_no_cif_or_libsrt_pad("peer error CIF", cif)?;
354                ControlPacket::PeerError(PeerErrorPacket {
355                    error_code: type_specific_info,
356                    timestamp,
357                    dest_socket_id,
358                    libsrt_pad,
359                })
360            }
361            ControlType::UserDefined | ControlType::Reserved(_) => {
362                ControlPacket::UserDefined(UserDefinedPacket {
363                    control_type: control_type_bits,
364                    subtype,
365                    type_specific_info,
366                    timestamp,
367                    dest_socket_id,
368                    cif,
369                })
370            }
371        })
372    }
373
374    /// The `Control Type` this packet carries.
375    pub fn control_type(&self) -> ControlType {
376        match self {
377            ControlPacket::Handshake(_) => ControlType::Handshake,
378            ControlPacket::KeepAlive(_) => ControlType::KeepAlive,
379            ControlPacket::Ack(_) => ControlType::Ack,
380            ControlPacket::Nak(_) => ControlType::Nak,
381            ControlPacket::CongestionWarning(_) => ControlType::CongestionWarning,
382            ControlPacket::Shutdown(_) => ControlType::Shutdown,
383            ControlPacket::AckAck(_) => ControlType::AckAck,
384            ControlPacket::DropReq(_) => ControlType::DropReq,
385            ControlPacket::PeerError(_) => ControlType::PeerError,
386            ControlPacket::UserDefined(u) => ControlType::from_bits(u.control_type),
387        }
388    }
389
390    fn subtype(&self) -> u16 {
391        match self {
392            ControlPacket::UserDefined(u) => u.subtype,
393            _ => 0,
394        }
395    }
396
397    fn word1(&self) -> u32 {
398        match self {
399            ControlPacket::Handshake(_)
400            | ControlPacket::KeepAlive(_)
401            | ControlPacket::Nak(_)
402            | ControlPacket::CongestionWarning(_)
403            | ControlPacket::Shutdown(_) => 0,
404            ControlPacket::Ack(a) => a.ack_number,
405            ControlPacket::AckAck(a) => a.ack_number,
406            ControlPacket::DropReq(d) => d.message_number,
407            ControlPacket::PeerError(p) => p.error_code,
408            ControlPacket::UserDefined(u) => u.type_specific_info,
409        }
410    }
411
412    fn timestamp(&self) -> u32 {
413        match self {
414            ControlPacket::Handshake(h) => h.timestamp,
415            ControlPacket::KeepAlive(k) => k.timestamp,
416            ControlPacket::Ack(a) => a.timestamp,
417            ControlPacket::Nak(n) => n.timestamp,
418            ControlPacket::CongestionWarning(c) => c.timestamp,
419            ControlPacket::Shutdown(s) => s.timestamp,
420            ControlPacket::AckAck(a) => a.timestamp,
421            ControlPacket::DropReq(d) => d.timestamp,
422            ControlPacket::PeerError(p) => p.timestamp,
423            ControlPacket::UserDefined(u) => u.timestamp,
424        }
425    }
426
427    fn dest_socket_id(&self) -> u32 {
428        match self {
429            ControlPacket::Handshake(h) => h.dest_socket_id,
430            ControlPacket::KeepAlive(k) => k.dest_socket_id,
431            ControlPacket::Ack(a) => a.dest_socket_id,
432            ControlPacket::Nak(n) => n.dest_socket_id,
433            ControlPacket::CongestionWarning(c) => c.dest_socket_id,
434            ControlPacket::Shutdown(s) => s.dest_socket_id,
435            ControlPacket::AckAck(a) => a.dest_socket_id,
436            ControlPacket::DropReq(d) => d.dest_socket_id,
437            ControlPacket::PeerError(p) => p.dest_socket_id,
438            ControlPacket::UserDefined(u) => u.dest_socket_id,
439        }
440    }
441
442    fn cif_len(&self) -> usize {
443        match self {
444            ControlPacket::Handshake(h) => h.cif_len(),
445            // Emit libsrt's 4-byte zero pad (see `LIBSRT_CIF_PAD_LEN`) when
446            // requested, or empty CIF otherwise, so packets round-trip
447            // byte-identically regardless of which spec-legal shape they parsed.
448            ControlPacket::KeepAlive(k) => {
449                if k.libsrt_pad {
450                    LIBSRT_CIF_PAD_LEN
451                } else {
452                    0
453                }
454            }
455            ControlPacket::CongestionWarning(c) => {
456                if c.libsrt_pad {
457                    LIBSRT_CIF_PAD_LEN
458                } else {
459                    0
460                }
461            }
462            ControlPacket::Shutdown(s) => {
463                if s.libsrt_pad {
464                    LIBSRT_CIF_PAD_LEN
465                } else {
466                    0
467                }
468            }
469            ControlPacket::AckAck(a) => {
470                if a.libsrt_pad {
471                    LIBSRT_CIF_PAD_LEN
472                } else {
473                    0
474                }
475            }
476            ControlPacket::PeerError(p) => {
477                if p.libsrt_pad {
478                    LIBSRT_CIF_PAD_LEN
479                } else {
480                    0
481                }
482            }
483            ControlPacket::Ack(a) => a.cif_len(),
484            ControlPacket::Nak(n) => n.cif_len(),
485            ControlPacket::DropReq(d) => d.cif_len(),
486            ControlPacket::UserDefined(u) => u.cif.len(),
487        }
488    }
489
490    /// Number of bytes [`Self::serialize_into`] will write.
491    pub fn serialized_len(&self) -> usize {
492        SRT_HEADER_LEN + self.cif_len()
493    }
494
495    /// Serialize this control packet into `buf`.
496    pub fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
497        let len = self.serialized_len();
498        if buf.len() < len {
499            return Err(Error::OutputBufferTooSmall {
500                need: len,
501                have: buf.len(),
502            });
503        }
504        let control_type_bits = self.control_type().to_bits();
505        if control_type_bits > 0x7FFF {
506            return Err(Error::FieldTooWide {
507                what: "Control Type",
508                value: u64::from(control_type_bits),
509                bits: 15,
510            });
511        }
512        let word0 = super::F_BIT | (u32::from(control_type_bits) << 16) | u32::from(self.subtype());
513        put_be32(buf, 0, word0);
514        put_be32(buf, 4, self.word1());
515        put_be32(buf, 8, self.timestamp());
516        put_be32(buf, 12, self.dest_socket_id());
517        let cif = &mut buf[SRT_HEADER_LEN..len];
518        match self {
519            ControlPacket::Handshake(h) => {
520                h.write_cif(cif)?;
521            }
522            ControlPacket::KeepAlive(_)
523            | ControlPacket::CongestionWarning(_)
524            | ControlPacket::Shutdown(_)
525            | ControlPacket::AckAck(_)
526            | ControlPacket::PeerError(_) => {
527                cif.fill(0);
528            }
529            ControlPacket::Ack(a) => {
530                a.write_cif(cif)?;
531            }
532            ControlPacket::Nak(n) => {
533                n.write_cif(cif);
534            }
535            ControlPacket::DropReq(d) => {
536                d.write_cif(cif);
537            }
538            ControlPacket::UserDefined(u) => {
539                cif.copy_from_slice(u.cif);
540            }
541        }
542        Ok(len)
543    }
544}