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