srt-runtime 0.12.0

SRT (Secure Reliable Transport, draft-sharabayko-srt-01) packet codecs + sans-IO HSv5 Caller-Listener and Rendezvous handshake state machines, an ARQ reliability engine, a TSBPD delivery scheduler, LiveCC packet pacing, FileCC window-based congestion control, optional (crypto feature) payload encryption, and an optional (tokio feature) async UDP socket adapter; no_std core.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
//! SRT control packet dispatch — `draft-sharabayko-srt-01` §3.2, Figure 4,
//! Table 1.
//!
//! ```text
//! word0  1|         Control Type (15)   |          Subtype (16)         |
//! word1                   Type-specific Information (32)
//! word2                          Timestamp (32)
//! word3                    Destination Socket ID (32)
//! rest                              CIF (variable, per Control Type)
//! ```
//!
//! `Subtype` is `0x0` for every Control Type in Table 1 except
//! `User-Defined Type` (`0x7FFF`), where it carries `SRT_CMD_KMREQ` /
//! `SRT_CMD_KMRSP` (Table 5) when the CIF is a Key Material message (§3.2.2).
//! `Subtype` and the `Type-specific Information` word (where a given packet
//! type does not use it) are validated as reserved-must-be-zero and are not
//! stored in the typed per-type structs — see the crate root's reserved-bit
//! policy.

use super::ack::AckPacket;
use super::handshake::HandshakePacket;
use super::misc::{
    AckAckPacket, CongestionWarningPacket, DropReqPacket, KeepAlivePacket, PeerErrorPacket,
    ShutdownPacket,
};
use super::nak::NakPacket;
use super::number::{AckNumber, SocketId, SrtTimestamp};
use super::{Error, Result, SRT_HEADER_LEN, be32, put_be32};
use broadcast_common::error::ReservedBits;
use broadcast_common::len::{need_in, need_out};

/// `Control Type` wire values (`draft-sharabayko-srt-01` §3.2, Table 1).
/// Crate-private: they back [`ControlType::from_bits`]/[`ControlType::to_bits`],
/// and [`ControlType`] is how a caller names a control type.
pub(crate) const CONTROL_TYPE_HANDSHAKE: u16 = 0x0000;
/// Keep-Alive (§3.2.3).
pub(crate) const CONTROL_TYPE_KEEPALIVE: u16 = 0x0001;
/// ACK (§3.2.4).
pub(crate) const CONTROL_TYPE_ACK: u16 = 0x0002;
/// NAK / Loss Report (§3.2.5).
pub(crate) const CONTROL_TYPE_NAK: u16 = 0x0003;
/// Congestion Warning (§3.2.6).
pub(crate) const CONTROL_TYPE_CONGESTION_WARNING: u16 = 0x0004;
/// Shutdown (§3.2.7).
pub(crate) const CONTROL_TYPE_SHUTDOWN: u16 = 0x0005;
/// ACKACK (§3.2.8).
pub(crate) const CONTROL_TYPE_ACKACK: u16 = 0x0006;
/// Message Drop Request (§3.2.9).
pub(crate) const CONTROL_TYPE_DROPREQ: u16 = 0x0007;
/// Peer Error (§3.2.10).
pub(crate) const CONTROL_TYPE_PEERERROR: u16 = 0x0008;
/// User-Defined Type (reserved value; also carries the Key Material message
/// per §3.2.2 via `Subtype` `SRT_CMD_KMREQ`/`SRT_CMD_KMRSP`).
pub(crate) const CONTROL_TYPE_USER_DEFINED: u16 = 0x7FFF;

/// The `Control Type` field (`draft-sharabayko-srt-01` §3.2, Table 1) — 15
/// bits.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum ControlType {
    /// `0x0000` — Handshake (§3.2.1).
    Handshake,
    /// `0x0001` — Keep-Alive (§3.2.3).
    KeepAlive,
    /// `0x0002` — ACK (§3.2.4).
    Ack,
    /// `0x0003` — NAK / Loss Report (§3.2.5).
    Nak,
    /// `0x0004` — Congestion Warning (§3.2.6).
    CongestionWarning,
    /// `0x0005` — Shutdown (§3.2.7).
    Shutdown,
    /// `0x0006` — ACKACK (§3.2.8).
    AckAck,
    /// `0x0007` — Message Drop Request (§3.2.9).
    DropReq,
    /// `0x0008` — Peer Error (§3.2.10).
    PeerError,
    /// `0x7FFF` — User-Defined Type (also the Key Material control-packet
    /// delivery form, §3.2.2).
    UserDefined,
    /// A Control Type value Table 1 does not define.
    Reserved(u16),
}

impl ControlType {
    /// Decode a 15-bit `Control Type` value.
    pub fn from_bits(v: u16) -> Self {
        match v {
            CONTROL_TYPE_HANDSHAKE => ControlType::Handshake,
            CONTROL_TYPE_KEEPALIVE => ControlType::KeepAlive,
            CONTROL_TYPE_ACK => ControlType::Ack,
            CONTROL_TYPE_NAK => ControlType::Nak,
            CONTROL_TYPE_CONGESTION_WARNING => ControlType::CongestionWarning,
            CONTROL_TYPE_SHUTDOWN => ControlType::Shutdown,
            CONTROL_TYPE_ACKACK => ControlType::AckAck,
            CONTROL_TYPE_DROPREQ => ControlType::DropReq,
            CONTROL_TYPE_PEERERROR => ControlType::PeerError,
            CONTROL_TYPE_USER_DEFINED => ControlType::UserDefined,
            other => ControlType::Reserved(other),
        }
    }

    /// The wire value.
    pub fn to_bits(self) -> u16 {
        match self {
            ControlType::Handshake => CONTROL_TYPE_HANDSHAKE,
            ControlType::KeepAlive => CONTROL_TYPE_KEEPALIVE,
            ControlType::Ack => CONTROL_TYPE_ACK,
            ControlType::Nak => CONTROL_TYPE_NAK,
            ControlType::CongestionWarning => CONTROL_TYPE_CONGESTION_WARNING,
            ControlType::Shutdown => CONTROL_TYPE_SHUTDOWN,
            ControlType::AckAck => CONTROL_TYPE_ACKACK,
            ControlType::DropReq => CONTROL_TYPE_DROPREQ,
            ControlType::PeerError => CONTROL_TYPE_PEERERROR,
            ControlType::UserDefined => CONTROL_TYPE_USER_DEFINED,
            ControlType::Reserved(v) => v,
        }
    }

    /// Spec label.
    pub fn name(&self) -> &'static str {
        match self {
            ControlType::Handshake => "handshake",
            ControlType::KeepAlive => "keep-alive",
            ControlType::Ack => "ACK",
            ControlType::Nak => "NAK",
            ControlType::CongestionWarning => "congestion warning",
            ControlType::Shutdown => "shutdown",
            ControlType::AckAck => "ACKACK",
            ControlType::DropReq => "message drop request",
            ControlType::PeerError => "peer error",
            ControlType::UserDefined => "user-defined",
            ControlType::Reserved(_) => "reserved",
        }
    }
}

broadcast_common::impl_spec_display!(ControlType, Reserved);

/// A Control Type = User-Defined (`0x7FFF`) packet, or a Control Type not
/// defined by Table 1. The CIF is genuinely opaque here — the only defined
/// use is the Key Material message (§3.2.2) via `Subtype`
/// `SRT_CMD_KMREQ`/`SRT_CMD_KMRSP` — see [`Self::as_key_material`].
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct UserDefinedPacket<'a> {
    /// The raw 15-bit Control Type value.
    pub control_type: u16,
    /// The 16-bit Subtype — `SRT_CMD_KMREQ`/`SRT_CMD_KMRSP` when the CIF is
    /// Key Material (Table 5), otherwise vendor-defined.
    pub subtype: u16,
    /// The header `Type-specific Information` word.
    pub type_specific_info: u32,
    /// Timestamp (§3).
    pub timestamp: SrtTimestamp,
    /// Destination Socket ID (§3).
    pub dest_socket_id: SocketId,
    /// The raw CIF bytes.
    pub cif: &'a [u8],
}

impl<'a> UserDefinedPacket<'a> {
    /// Attempt to decode [`Self::cif`] as a Key Material message (§3.2.2).
    /// Valid regardless of [`Self::subtype`] — callers that care should check
    /// `subtype` against `SRT_CMD_KMREQ`/`SRT_CMD_KMRSP` (Table 5) first.
    pub fn as_key_material(&self) -> Result<super::KeyMaterial<'a>> {
        super::KeyMaterial::parse(self.cif)
    }
}

/// An SRT control packet (`draft-sharabayko-srt-01` §3.2).
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum ControlPacket<'a> {
    /// Handshake (§3.2.1).
    Handshake(HandshakePacket<'a>),
    /// Keep-Alive (§3.2.3).
    KeepAlive(KeepAlivePacket),
    /// ACK (§3.2.4).
    Ack(AckPacket),
    /// NAK / Loss Report (§3.2.5).
    Nak(NakPacket),
    /// Congestion Warning (§3.2.6).
    CongestionWarning(CongestionWarningPacket),
    /// Shutdown (§3.2.7).
    Shutdown(ShutdownPacket),
    /// ACKACK (§3.2.8).
    AckAck(AckAckPacket),
    /// Message Drop Request (§3.2.9).
    DropReq(DropReqPacket),
    /// Peer Error (§3.2.10).
    PeerError(PeerErrorPacket),
    /// User-Defined Type, or a Control Type Table 1 does not define.
    UserDefined(UserDefinedPacket<'a>),
}

fn check_reserved_u16(what: &'static str, v: u16) -> Result<()> {
    if v != 0 {
        return Err(Error::ReservedBits(ReservedBits {
            field: what,
            expected: 0,
            found: u64::from(v),
        }));
    }
    Ok(())
}

fn check_reserved_u32(what: &'static str, v: u32) -> Result<()> {
    if v != 0 {
        return Err(Error::ReservedBits(ReservedBits {
            field: what,
            expected: 0,
            found: u64::from(v),
        }));
    }
    Ok(())
}

/// Bytes libsrt appends to a control packet type whose CIF the spec documents
/// as absent (Keep-Alive §3.2.3, Congestion Warning §3.2.6, Shutdown §3.2.7,
/// ACKACK §3.2.8, Peer Error §3.2.10). libsrt's `CPacket::pack` always calls
/// `m_PacketVector[PV_DATA].set(&m_extra_pad, 4)` for these types — its own
/// comment says why: "control info field should be none but writev does not
/// allow this" (`packet.cpp`, `CPacket::pack`, e.g. the `UMSG_KEEPALIVE` arm)
/// — and `m_extra_pad` is a zero-initialized member, so the 4 bytes are
/// always zero on the wire. Confirmed against a real `srt-live-transmit`
/// 1.5.5 KEEPALIVE/ACKACK capture (`../fixtures/srt/libsrt-*.bin`).
const LIBSRT_CIF_PAD_LEN: usize = 4;

/// Accept either the pure-spec empty CIF or libsrt's 4-byte zero pad (see
/// [`LIBSRT_CIF_PAD_LEN`]); reject anything else. A non-zero 4-byte value is
/// rejected the same way a defined reserved field is (`ReservedFieldNotZero`)
/// — nothing defines those bits, so a peer setting them to something else is
/// not a shape this crate recognizes. Returns `true` if the 4-byte pad was
/// present, `false` for the empty CIF.
fn check_no_cif_or_libsrt_pad(what: &'static str, cif: &[u8]) -> Result<bool> {
    match cif.len() {
        0 => Ok(false),
        LIBSRT_CIF_PAD_LEN => {
            let value = be32(cif, 0);
            if value != 0 {
                return Err(Error::ReservedBits(ReservedBits {
                    field: what,
                    expected: 0,
                    found: u64::from(value),
                }));
            }
            Ok(true)
        }
        extra => Err(Error::UnexpectedTrailingBytes { what, extra }),
    }
}

impl<'a> ControlPacket<'a> {
    /// Parse a control packet from `bytes` (the full SRT packet).
    ///
    /// # Errors
    /// [`Error::BufferTooShort`] if shorter than the 16-byte header;
    /// [`Error::WrongPacketKind`] if the `F` bit is clear (this is a data
    /// packet); type-specific errors from the dispatched CIF parser.
    pub fn parse(bytes: &'a [u8]) -> Result<Self> {
        need_in(bytes, SRT_HEADER_LEN, "SRT control packet header")?;
        let word0 = be32(bytes, 0);
        if word0 & super::F_BIT == 0 {
            return Err(Error::WrongPacketKind {
                expected: "control packet (F=1)",
            });
        }
        let control_type_bits = ((word0 >> 16) & 0x7FFF) as u16;
        let subtype = (word0 & 0xFFFF) as u16;
        let type_specific_info = be32(bytes, 4);
        let timestamp = SrtTimestamp::from_wire(be32(bytes, 8));
        let dest_socket_id = SocketId::from_wire(be32(bytes, 12));
        let cif = &bytes[SRT_HEADER_LEN..];
        let control_type = ControlType::from_bits(control_type_bits);

        Ok(match control_type {
            ControlType::Handshake => {
                check_reserved_u16("Subtype", subtype)?;
                check_reserved_u32("Type-specific Information", type_specific_info)?;
                ControlPacket::Handshake(HandshakePacket::parse_cif(
                    timestamp,
                    dest_socket_id,
                    cif,
                )?)
            }
            ControlType::KeepAlive => {
                check_reserved_u16("Subtype", subtype)?;
                check_reserved_u32("Type-specific Information", type_specific_info)?;
                let libsrt_pad = check_no_cif_or_libsrt_pad("keep-alive CIF", cif)?;
                ControlPacket::KeepAlive(KeepAlivePacket {
                    timestamp,
                    dest_socket_id,
                    libsrt_pad,
                })
            }
            ControlType::Ack => {
                check_reserved_u16("Subtype", subtype)?;
                ControlPacket::Ack(AckPacket::parse_cif(
                    type_specific_info,
                    timestamp,
                    dest_socket_id,
                    cif,
                )?)
            }
            ControlType::Nak => {
                check_reserved_u16("Subtype", subtype)?;
                check_reserved_u32("Type-specific Information", type_specific_info)?;
                ControlPacket::Nak(NakPacket::parse_cif(timestamp, dest_socket_id, cif)?)
            }
            ControlType::CongestionWarning => {
                check_reserved_u16("Subtype", subtype)?;
                check_reserved_u32("Type-specific Information", type_specific_info)?;
                let libsrt_pad = check_no_cif_or_libsrt_pad("congestion warning CIF", cif)?;
                ControlPacket::CongestionWarning(CongestionWarningPacket {
                    timestamp,
                    dest_socket_id,
                    libsrt_pad,
                })
            }
            ControlType::Shutdown => {
                check_reserved_u16("Subtype", subtype)?;
                check_reserved_u32("Type-specific Information", type_specific_info)?;
                let libsrt_pad = check_no_cif_or_libsrt_pad("shutdown CIF", cif)?;
                ControlPacket::Shutdown(ShutdownPacket {
                    timestamp,
                    dest_socket_id,
                    libsrt_pad,
                })
            }
            ControlType::AckAck => {
                check_reserved_u16("Subtype", subtype)?;
                let libsrt_pad = check_no_cif_or_libsrt_pad("ACKACK CIF", cif)?;
                ControlPacket::AckAck(AckAckPacket {
                    ack_number: AckNumber::from_wire(type_specific_info),
                    timestamp,
                    dest_socket_id,
                    libsrt_pad,
                })
            }
            ControlType::DropReq => {
                check_reserved_u16("Subtype", subtype)?;
                ControlPacket::DropReq(DropReqPacket::parse_cif(
                    type_specific_info,
                    timestamp,
                    dest_socket_id,
                    cif,
                )?)
            }
            ControlType::PeerError => {
                check_reserved_u16("Subtype", subtype)?;
                let libsrt_pad = check_no_cif_or_libsrt_pad("peer error CIF", cif)?;
                ControlPacket::PeerError(PeerErrorPacket {
                    error_code: type_specific_info,
                    timestamp,
                    dest_socket_id,
                    libsrt_pad,
                })
            }
            ControlType::UserDefined | ControlType::Reserved(_) => {
                ControlPacket::UserDefined(UserDefinedPacket {
                    control_type: control_type_bits,
                    subtype,
                    type_specific_info,
                    timestamp,
                    dest_socket_id,
                    cif,
                })
            }
        })
    }

    /// The `Control Type` this packet carries.
    pub fn control_type(&self) -> ControlType {
        match self {
            ControlPacket::Handshake(_) => ControlType::Handshake,
            ControlPacket::KeepAlive(_) => ControlType::KeepAlive,
            ControlPacket::Ack(_) => ControlType::Ack,
            ControlPacket::Nak(_) => ControlType::Nak,
            ControlPacket::CongestionWarning(_) => ControlType::CongestionWarning,
            ControlPacket::Shutdown(_) => ControlType::Shutdown,
            ControlPacket::AckAck(_) => ControlType::AckAck,
            ControlPacket::DropReq(_) => ControlType::DropReq,
            ControlPacket::PeerError(_) => ControlType::PeerError,
            ControlPacket::UserDefined(u) => ControlType::from_bits(u.control_type),
        }
    }

    fn subtype(&self) -> u16 {
        match self {
            ControlPacket::UserDefined(u) => u.subtype,
            _ => 0,
        }
    }

    fn word1(&self) -> Result<u32> {
        Ok(match self {
            ControlPacket::Handshake(_)
            | ControlPacket::KeepAlive(_)
            | ControlPacket::Nak(_)
            | ControlPacket::CongestionWarning(_)
            | ControlPacket::Shutdown(_) => 0,
            // An ACK's and an ACKACK's Acknowledgement Number fill their
            // whole `Type-specific Information` word (§3.2.4, §3.2.8): every
            // `u32` is a legal value, so nothing is bounded here (it was, to
            // 31 bits, which made serialize refuse a packet parse accepted).
            ControlPacket::Ack(a) => a.ack_number.value(),
            ControlPacket::AckAck(a) => a.ack_number.value(),
            ControlPacket::DropReq(d) => d.message_number.value(),
            ControlPacket::PeerError(p) => p.error_code,
            ControlPacket::UserDefined(u) => u.type_specific_info,
        })
    }

    fn timestamp(&self) -> SrtTimestamp {
        match self {
            ControlPacket::Handshake(h) => h.timestamp,
            ControlPacket::KeepAlive(k) => k.timestamp,
            ControlPacket::Ack(a) => a.timestamp,
            ControlPacket::Nak(n) => n.timestamp,
            ControlPacket::CongestionWarning(c) => c.timestamp,
            ControlPacket::Shutdown(s) => s.timestamp,
            ControlPacket::AckAck(a) => a.timestamp,
            ControlPacket::DropReq(d) => d.timestamp,
            ControlPacket::PeerError(p) => p.timestamp,
            ControlPacket::UserDefined(u) => u.timestamp,
        }
    }

    fn dest_socket_id(&self) -> SocketId {
        match self {
            ControlPacket::Handshake(h) => h.dest_socket_id,
            ControlPacket::KeepAlive(k) => k.dest_socket_id,
            ControlPacket::Ack(a) => a.dest_socket_id,
            ControlPacket::Nak(n) => n.dest_socket_id,
            ControlPacket::CongestionWarning(c) => c.dest_socket_id,
            ControlPacket::Shutdown(s) => s.dest_socket_id,
            ControlPacket::AckAck(a) => a.dest_socket_id,
            ControlPacket::DropReq(d) => d.dest_socket_id,
            ControlPacket::PeerError(p) => p.dest_socket_id,
            ControlPacket::UserDefined(u) => u.dest_socket_id,
        }
    }

    fn cif_len(&self) -> usize {
        match self {
            ControlPacket::Handshake(h) => h.cif_len(),
            // Emit libsrt's 4-byte zero pad (see `LIBSRT_CIF_PAD_LEN`) when
            // requested, or empty CIF otherwise, so packets round-trip
            // byte-identically regardless of which spec-legal shape they parsed.
            ControlPacket::KeepAlive(k) => {
                if k.libsrt_pad {
                    LIBSRT_CIF_PAD_LEN
                } else {
                    0
                }
            }
            ControlPacket::CongestionWarning(c) => {
                if c.libsrt_pad {
                    LIBSRT_CIF_PAD_LEN
                } else {
                    0
                }
            }
            ControlPacket::Shutdown(s) => {
                if s.libsrt_pad {
                    LIBSRT_CIF_PAD_LEN
                } else {
                    0
                }
            }
            ControlPacket::AckAck(a) => {
                if a.libsrt_pad {
                    LIBSRT_CIF_PAD_LEN
                } else {
                    0
                }
            }
            ControlPacket::PeerError(p) => {
                if p.libsrt_pad {
                    LIBSRT_CIF_PAD_LEN
                } else {
                    0
                }
            }
            ControlPacket::Ack(a) => a.cif_len(),
            ControlPacket::Nak(n) => n.cif_len(),
            ControlPacket::DropReq(d) => d.cif_len(),
            ControlPacket::UserDefined(u) => u.cif.len(),
        }
    }

    /// Number of bytes [`Self::serialize_into`] will write.
    pub fn serialized_len(&self) -> usize {
        SRT_HEADER_LEN + self.cif_len()
    }

    /// Serialize this control packet into `buf`.
    pub fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        let len = self.serialized_len();
        need_out(buf, len)?;
        let control_type_bits = self.control_type().to_bits();
        broadcast_common::len::fit_bits(u64::from(control_type_bits), 15, "Control Type")?;
        let word0 = super::F_BIT | (u32::from(control_type_bits) << 16) | u32::from(self.subtype());
        put_be32(buf, 0, word0);
        put_be32(buf, 4, self.word1()?);
        put_be32(buf, 8, self.timestamp().value());
        put_be32(buf, 12, self.dest_socket_id().value());
        let cif = &mut buf[SRT_HEADER_LEN..len];
        match self {
            ControlPacket::Handshake(h) => {
                h.write_cif(cif)?;
            }
            ControlPacket::KeepAlive(_)
            | ControlPacket::CongestionWarning(_)
            | ControlPacket::Shutdown(_)
            | ControlPacket::AckAck(_)
            | ControlPacket::PeerError(_) => {
                cif.fill(0);
            }
            ControlPacket::Ack(a) => {
                a.write_cif(cif)?;
            }
            ControlPacket::Nak(n) => {
                n.write_cif(cif);
            }
            ControlPacket::DropReq(d) => {
                d.write_cif(cif)?;
            }
            ControlPacket::UserDefined(u) => {
                cif.copy_from_slice(u.cif);
            }
        }
        Ok(len)
    }
}

impl<'a> broadcast_common::Parse<'a> for ControlPacket<'a> {
    type Error = crate::Error;

    fn parse(bytes: &'a [u8]) -> core::result::Result<Self, Self::Error> {
        ControlPacket::parse(bytes)
    }
}

impl broadcast_common::Serialize for ControlPacket<'_> {
    type Error = crate::Error;

    fn serialized_len(&self) -> usize {
        ControlPacket::serialized_len(self)
    }

    fn serialize_into(&self, buf: &mut [u8]) -> core::result::Result<usize, Self::Error> {
        ControlPacket::serialize_into(self, buf)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn every_control_type_round_trips_its_table_1_wire_value() {
        for (ty, value) in [
            (ControlType::Handshake, 0x0000u16),
            (ControlType::KeepAlive, 0x0001),
            (ControlType::Ack, 0x0002),
            (ControlType::Nak, 0x0003),
            (ControlType::CongestionWarning, 0x0004),
            (ControlType::Shutdown, 0x0005),
            (ControlType::AckAck, 0x0006),
            (ControlType::DropReq, 0x0007),
            (ControlType::PeerError, 0x0008),
            (ControlType::UserDefined, 0x7FFF),
        ] {
            assert_eq!(ty.to_bits(), value, "{}", ty.name());
            assert_eq!(ControlType::from_bits(value), ty);
        }
    }

    #[test]
    fn a_control_type_off_table_1_is_reserved_and_keeps_its_value() {
        // 0x0009..=0x7FFE are not in Table 1; the enum, not a raw constant,
        // is the public way to name and recover them.
        for value in [0x0009u16, 0x0010, 0x7FFE] {
            assert_eq!(ControlType::from_bits(value), ControlType::Reserved(value));
            assert_eq!(ControlType::from_bits(value).to_bits(), value);
        }
        assert_eq!(ControlType::Reserved(0x0010).name(), "reserved");
    }
}