Skip to main content

rtmp_runtime/
message.rs

1//! RTMP message assembly from chunks, protocol control messages, and the
2//! message type catalogue (Adobe RTMP 1.0 §5.4, §6, §7.1).
3//!
4//! See `private/specs-verified/rtmp/rtmp-runtime/rtmp.md` §4 (Protocol Control Messages), §5
5//! (RTMP Message Format + User Control, §6.1/§6.2), and §6 (RTMP Message
6//! Types, §7.1) for the wire layout.
7//!
8//! This module adds typed interpretation on top of the [`crate::chunk::Message`]
9//! carrier: the message type id ([`crate::chunk::Message::message_type_id`], a
10//! [`MessageTypeId`]), the Chunk-Stream-layer protocol control messages
11//! ([`ProtocolControl`], §4/§5.4), and the streaming-layer user control events
12//! ([`UserControl`], §5.3/§6.2/§6.7).
13
14use broadcast_common::error::BufferTooShort;
15use broadcast_common::len::need_in;
16use broadcast_common::{Parse, Serialize};
17use core::time::Duration;
18
19use crate::RtmpError;
20use crate::chunk::{MAX_CHUNK_SIZE, Message};
21use crate::ids::{ChunkStreamId, MessageStreamId, SequenceNumber, Timestamp};
22use alloc::vec::Vec;
23
24type Result<T> = core::result::Result<T, RtmpError>;
25
26// ── Message type ids (§6 / §7.1) ────────────────────────────────────────
27
28/// RTMP message type id (§6, RTMP Message Types §7.1; the `Message Type ID`
29/// field of the chunk message header, §5.3.1). Ids `1..=6` are
30/// Chunk-Stream-layer protocol control (§5.4); the rest are streaming-layer
31/// message types (§6/§7.1). A value §7.1 does not define is kept in
32/// [`MessageTypeId::Other`], since a peer may send one and the payload is
33/// still carried.
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
35#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
36#[non_exhaustive]
37pub enum MessageTypeId {
38    /// `1` — Set Chunk Size (§5.4.1).
39    SetChunkSize,
40    /// `2` — Abort Message (§5.4.2).
41    Abort,
42    /// `3` — Acknowledgement (§5.4.3).
43    Acknowledgement,
44    /// `4` — User Control Message (§6.2/§7.1.7).
45    UserControl,
46    /// `5` — Window Acknowledgement Size (§5.4.4).
47    WindowAckSize,
48    /// `6` — Set Peer Bandwidth (§5.4.5).
49    SetPeerBandwidth,
50    /// `8` — Audio Message (§7.1.4).
51    Audio,
52    /// `9` — Video Message (§7.1.5).
53    Video,
54    /// `15` — Data Message, AMF3-encoded (§7.1.2).
55    DataAmf3,
56    /// `17` — Command Message, AMF3-encoded (§7.1.1).
57    CommandAmf3,
58    /// `18` — Data Message, AMF0-encoded (§7.1.2).
59    DataAmf0,
60    /// `20` — Command Message, AMF0-encoded (§7.1.1).
61    CommandAmf0,
62    /// `22` — Aggregate Message (§7.1.6).
63    Aggregate,
64    /// A message type id §7.1 does not define.
65    Other(u8),
66}
67
68impl MessageTypeId {
69    /// Decode a wire message type id (lossless: an undefined id becomes
70    /// [`MessageTypeId::Other`]).
71    #[must_use]
72    pub fn from_u8(v: u8) -> Self {
73        match v {
74            1 => MessageTypeId::SetChunkSize,
75            2 => MessageTypeId::Abort,
76            3 => MessageTypeId::Acknowledgement,
77            4 => MessageTypeId::UserControl,
78            5 => MessageTypeId::WindowAckSize,
79            6 => MessageTypeId::SetPeerBandwidth,
80            8 => MessageTypeId::Audio,
81            9 => MessageTypeId::Video,
82            15 => MessageTypeId::DataAmf3,
83            17 => MessageTypeId::CommandAmf3,
84            18 => MessageTypeId::DataAmf0,
85            20 => MessageTypeId::CommandAmf0,
86            22 => MessageTypeId::Aggregate,
87            other => MessageTypeId::Other(other),
88        }
89    }
90
91    /// The wire value.
92    #[must_use]
93    pub fn to_u8(self) -> u8 {
94        match self {
95            MessageTypeId::SetChunkSize => 1,
96            MessageTypeId::Abort => 2,
97            MessageTypeId::Acknowledgement => 3,
98            MessageTypeId::UserControl => 4,
99            MessageTypeId::WindowAckSize => 5,
100            MessageTypeId::SetPeerBandwidth => 6,
101            MessageTypeId::Audio => 8,
102            MessageTypeId::Video => 9,
103            MessageTypeId::DataAmf3 => 15,
104            MessageTypeId::CommandAmf3 => 17,
105            MessageTypeId::DataAmf0 => 18,
106            MessageTypeId::CommandAmf0 => 20,
107            MessageTypeId::Aggregate => 22,
108            MessageTypeId::Other(v) => v,
109        }
110    }
111
112    /// Spec label.
113    #[must_use]
114    pub fn name(&self) -> &'static str {
115        match self {
116            MessageTypeId::SetChunkSize => "set chunk size",
117            MessageTypeId::Abort => "abort",
118            MessageTypeId::Acknowledgement => "acknowledgement",
119            MessageTypeId::UserControl => "user control",
120            MessageTypeId::WindowAckSize => "window acknowledgement size",
121            MessageTypeId::SetPeerBandwidth => "set peer bandwidth",
122            MessageTypeId::Audio => "audio",
123            MessageTypeId::Video => "video",
124            MessageTypeId::DataAmf3 => "data (AMF3)",
125            MessageTypeId::CommandAmf3 => "command (AMF3)",
126            MessageTypeId::DataAmf0 => "data (AMF0)",
127            MessageTypeId::CommandAmf0 => "command (AMF0)",
128            MessageTypeId::Aggregate => "aggregate",
129            MessageTypeId::Other(_) => "other",
130        }
131    }
132}
133
134impl From<u8> for MessageTypeId {
135    fn from(v: u8) -> Self {
136        MessageTypeId::from_u8(v)
137    }
138}
139
140impl From<MessageTypeId> for u8 {
141    fn from(id: MessageTypeId) -> Self {
142        id.to_u8()
143    }
144}
145
146broadcast_common::impl_spec_display!(MessageTypeId, Other);
147
148/// Chunk stream id protocol control messages and user control messages
149/// MUST/SHOULD be sent on (§4, §5.3).
150pub const CONTROL_CHUNK_STREAM_ID: ChunkStreamId = ChunkStreamId::new(2);
151/// Message stream id protocol control messages MUST use, and user control
152/// messages SHOULD use (§4, §5.3): the control stream.
153pub const CONTROL_MESSAGE_STREAM_ID: MessageStreamId = MessageStreamId::new(0);
154
155/// Byte width of a `u32` protocol control field (chunk size, chunk stream
156/// id, sequence number, window ack size).
157const U32_LEN: usize = 4;
158/// Byte width of the Set Peer Bandwidth payload: window size (4) + limit
159/// type (1).
160const SET_PEER_BANDWIDTH_LEN: usize = U32_LEN + 1;
161
162/// Bit mask isolating the reserved top bit of the Set Chunk Size payload
163/// (§5.4.1: 1 reserved bit, MUST be 0, + 31-bit chunk size).
164const SET_CHUNK_SIZE_RESERVED_MASK: u32 = 0x8000_0000;
165/// Bit mask isolating the 31-bit chunk size field of the Set Chunk Size
166/// payload.
167const SET_CHUNK_SIZE_VALUE_MASK: u32 = 0x7FFF_FFFF;
168
169fn read_u32_be(b: &[u8]) -> u32 {
170    u32::from_be_bytes([b[0], b[1], b[2], b[3]])
171}
172
173fn need_u32(bytes: &[u8], what: &'static str) -> Result<u32> {
174    if bytes.len() < U32_LEN {
175        return Err(RtmpError::BufferTooShort(BufferTooShort {
176            need: U32_LEN,
177            have: bytes.len(),
178            what,
179        }));
180    }
181    Ok(read_u32_be(bytes))
182}
183
184// ── Set Peer Bandwidth Limit Type (§5.4.5) ──────────────────────────────
185
186/// Set Peer Bandwidth's `Limit Type` byte (§5.4.5).
187#[derive(Debug, Clone, Copy, PartialEq, Eq)]
188#[non_exhaustive]
189pub enum LimitType {
190    /// Peer SHOULD limit output to exactly the indicated window.
191    Hard,
192    /// Peer SHOULD limit output to the indicated window or its current
193    /// limit, whichever is smaller.
194    Soft,
195    /// If the previous Limit Type was Hard, treat as Hard; otherwise
196    /// ignore this message.
197    Dynamic,
198}
199
200impl LimitType {
201    /// The spec token for this limit type.
202    #[must_use]
203    pub fn name(&self) -> &'static str {
204        match self {
205            LimitType::Hard => "hard",
206            LimitType::Soft => "soft",
207            LimitType::Dynamic => "dynamic",
208        }
209    }
210
211    /// Decode the wire byte (0..=2) into a [`LimitType`].
212    ///
213    /// # Errors
214    /// [`RtmpError::InvalidLimitType`] if `v` is not in `0..=2`.
215    pub const fn from_u8(v: u8) -> core::result::Result<Self, RtmpError> {
216        match v {
217            0 => Ok(LimitType::Hard),
218            1 => Ok(LimitType::Soft),
219            2 => Ok(LimitType::Dynamic),
220            value => Err(RtmpError::InvalidLimitType { value }),
221        }
222    }
223
224    /// Encode this limit type back to its wire byte (0..=2).
225    #[must_use]
226    pub const fn to_u8(self) -> u8 {
227        match self {
228            LimitType::Hard => 0,
229            LimitType::Soft => 1,
230            LimitType::Dynamic => 2,
231        }
232    }
233}
234
235broadcast_common::impl_spec_display!(LimitType);
236
237/// A validated RTMP chunk size (§5.4.1): `1..=0x7FFF_FFFF`.
238#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
239pub struct ChunkSize(u32);
240
241impl ChunkSize {
242    /// Minimum valid chunk size.
243    pub const MIN: ChunkSize = ChunkSize(1);
244
245    /// A size this crate's own constants already validated. Never called with
246    /// an unchecked value.
247    pub(crate) const fn new_unchecked(value: u32) -> Self {
248        Self(value)
249    }
250    /// Maximum valid chunk size.
251    pub const MAX: u32 = 0x7FFF_FFFF;
252
253    /// Construct a validated chunk size.
254    pub fn new(value: u32) -> Result<Self> {
255        Self::try_new(value)
256    }
257
258    /// Construct a validated chunk size: `1..=0x7FFF_FFFF` (the 31-bit wire
259    /// field, §5.4.1) and within this engine's [`MAX_CHUNK_SIZE`] ceiling.
260    ///
261    /// The ceiling is enforced here rather than by clamping later, so the
262    /// engine never adopts a chunk size other than the one announced.
263    pub const fn try_new(value: u32) -> Result<Self> {
264        if value == 0 || value & SET_CHUNK_SIZE_RESERVED_MASK != 0 {
265            return Err(RtmpError::chunk_size_out_of_range(value));
266        }
267        if value > MAX_CHUNK_SIZE {
268            return Err(RtmpError::chunk_size_out_of_range(value));
269        }
270        Ok(Self(value))
271    }
272
273    #[must_use]
274    /// The raw chunk size.
275    pub const fn value(self) -> u32 {
276        self.0
277    }
278}
279
280impl TryFrom<u32> for ChunkSize {
281    type Error = RtmpError;
282    fn try_from(value: u32) -> Result<Self> {
283        Self::new(value)
284    }
285}
286
287impl From<ChunkSize> for u32 {
288    fn from(c: ChunkSize) -> Self {
289        c.0
290    }
291}
292
293// ── Protocol control messages (§4 / §5.4) ───────────────────────────────
294
295/// A Chunk-Stream-layer protocol control message (§4, spec §5.4):
296/// message type ids `1`, `2`, `3`, `5`, `6`. MUST use message stream id 0
297/// and chunk stream id 2 ([`CONTROL_MESSAGE_STREAM_ID`] /
298/// [`CONTROL_CHUNK_STREAM_ID`]); effective immediately on receipt.
299///
300/// `#[non_exhaustive]`: `§4`'s protocol control catalogue is closed today,
301/// but this mirrors [`UserControl`]/[`crate::amf0::Amf0Value`] so a future
302/// addition never breaks an existing `match`.
303#[non_exhaustive]
304#[derive(Debug, Clone, Copy, PartialEq, Eq)]
305pub enum ProtocolControl {
306    /// Set Chunk Size (§5.4.1): the new maximum chunk size (`1..=0x7FFF_FFFF`).
307    SetChunkSize(ChunkSize),
308    /// Abort Message (§5.4.2): discard any partially-received message on
309    /// this chunk stream id.
310    Abort {
311        /// The chunk stream id whose in-progress message should be
312        /// discarded.
313        chunk_stream_id: u32,
314    },
315    /// Acknowledgement (§5.4.3): total bytes received so far.
316    Acknowledgement(SequenceNumber),
317    /// Window Acknowledgement Size (§5.4.4): the sender's advertised
318    /// window size.
319    WindowAckSize(u32),
320    /// Set Peer Bandwidth (§5.4.5): limit the peer's output bandwidth.
321    SetPeerBandwidth {
322        /// The acknowledgement window size to limit the peer to.
323        ack_window_size: u32,
324        /// How strictly the peer should observe the limit.
325        limit_type: LimitType,
326    },
327}
328
329impl ProtocolControl {
330    /// The spec token for this protocol control message.
331    #[must_use]
332    pub fn name(&self) -> &'static str {
333        match self {
334            ProtocolControl::SetChunkSize(_) => "set chunk size",
335            ProtocolControl::Abort { .. } => "abort message",
336            ProtocolControl::Acknowledgement(_) => "acknowledgement",
337            ProtocolControl::WindowAckSize(_) => "window acknowledgement size",
338            ProtocolControl::SetPeerBandwidth { .. } => "set peer bandwidth",
339        }
340    }
341
342    /// This variant's message type id (§6/§7.1).
343    #[must_use]
344    pub fn message_type_id(&self) -> MessageTypeId {
345        match self {
346            ProtocolControl::SetChunkSize(_) => MessageTypeId::SetChunkSize,
347            ProtocolControl::Abort { .. } => MessageTypeId::Abort,
348            ProtocolControl::Acknowledgement(_) => MessageTypeId::Acknowledgement,
349            ProtocolControl::WindowAckSize(_) => MessageTypeId::WindowAckSize,
350            ProtocolControl::SetPeerBandwidth { .. } => MessageTypeId::SetPeerBandwidth,
351        }
352    }
353
354    /// Interpret an already-reassembled [`Message`] as a protocol control
355    /// message, dispatching on `message.message_type_id`.
356    ///
357    /// Returns `Ok(None)` if `message.message_type_id` is not one of the
358    /// protocol control ids (`1`, `2`, `3`, `5`, `6`) — the caller should
359    /// then dispatch it elsewhere (user control, audio/video, command, …).
360    ///
361    /// # Errors
362    /// [`RtmpError::BufferTooShort`] if the payload is shorter than the
363    /// message type requires; [`RtmpError::Malformed`] if a field violates
364    /// its wire constraint (reserved bit set, out-of-range limit type).
365    pub fn from_message(message: &Message) -> Result<Option<Self>> {
366        Self::from_payload(message.message_type_id, &message.payload)
367    }
368
369    /// Parse a protocol control payload given its message type id. Not a
370    /// [`Parse`] impl: unlike every other wire type in this crate, a
371    /// protocol control payload alone is ambiguous (e.g. a bare 4-byte
372    /// payload is `SetChunkSize`, `Abort`, `Acknowledgement`, or
373    /// `WindowAckSize` depending on the message type id carried alongside
374    /// it in the [`Message`] header) — the type id is required context.
375    ///
376    /// # Errors
377    /// See [`ProtocolControl::from_message`].
378    pub fn from_payload(message_type_id: MessageTypeId, payload: &[u8]) -> Result<Option<Self>> {
379        match message_type_id {
380            MessageTypeId::SetChunkSize => {
381                let raw = need_u32(payload, "set chunk size payload")?;
382                if raw & SET_CHUNK_SIZE_RESERVED_MASK != 0 {
383                    return Err(RtmpError::chunk_size_out_of_range(raw));
384                }
385                Ok(Some(ProtocolControl::SetChunkSize(ChunkSize::try_new(
386                    raw & SET_CHUNK_SIZE_VALUE_MASK,
387                )?)))
388            }
389            MessageTypeId::Abort => {
390                let chunk_stream_id = need_u32(payload, "abort message payload")?;
391                Ok(Some(ProtocolControl::Abort { chunk_stream_id }))
392            }
393            MessageTypeId::Acknowledgement => {
394                let sequence_number = need_u32(payload, "acknowledgement payload")?;
395                Ok(Some(ProtocolControl::Acknowledgement(SequenceNumber::new(
396                    sequence_number,
397                ))))
398            }
399            MessageTypeId::WindowAckSize => {
400                let window = need_u32(payload, "window acknowledgement size payload")?;
401                Ok(Some(ProtocolControl::WindowAckSize(window)))
402            }
403            MessageTypeId::SetPeerBandwidth => {
404                need_in(
405                    payload,
406                    SET_PEER_BANDWIDTH_LEN,
407                    "set peer bandwidth payload",
408                )?;
409                let ack_window_size = read_u32_be(&payload[0..U32_LEN]);
410                let limit_type = LimitType::from_u8(payload[U32_LEN])?;
411                Ok(Some(ProtocolControl::SetPeerBandwidth {
412                    ack_window_size,
413                    limit_type,
414                }))
415            }
416            _ => Ok(None),
417        }
418    }
419
420    /// The message payload, built without a fallible length check: the
421    /// result length is the type's own [`Serialize::serialized_len`].
422    #[must_use]
423    pub fn to_bytes(&self) -> Vec<u8> {
424        let mut buf = alloc::vec![0u8; self.serialized_len()];
425        match *self {
426            ProtocolControl::SetChunkSize(size) => {
427                buf[0..U32_LEN].copy_from_slice(&size.value().to_be_bytes());
428            }
429            ProtocolControl::Abort { chunk_stream_id } => {
430                buf[0..U32_LEN].copy_from_slice(&chunk_stream_id.to_be_bytes());
431            }
432            ProtocolControl::Acknowledgement(sequence_number) => {
433                buf[0..U32_LEN].copy_from_slice(&sequence_number.get().to_be_bytes());
434            }
435            ProtocolControl::WindowAckSize(window) => {
436                buf[0..U32_LEN].copy_from_slice(&window.to_be_bytes());
437            }
438            ProtocolControl::SetPeerBandwidth {
439                ack_window_size,
440                limit_type,
441            } => {
442                buf[0..U32_LEN].copy_from_slice(&ack_window_size.to_be_bytes());
443                buf[U32_LEN] = limit_type.to_u8();
444            }
445        }
446        buf
447    }
448
449    /// Wrap this protocol control message in a [`Message`] ready to hand to
450    /// [`crate::chunk::ChunkWriter`] — chunk stream id
451    /// [`CONTROL_CHUNK_STREAM_ID`], message stream id
452    /// [`CONTROL_MESSAGE_STREAM_ID`], timestamp `0` (protocol control
453    /// messages take effect immediately; timestamps are not meaningful).
454    #[must_use]
455    pub fn to_message(&self) -> Message {
456        let payload = self.to_bytes();
457        Message {
458            chunk_stream_id: CONTROL_CHUNK_STREAM_ID,
459            timestamp: Timestamp::ZERO,
460            message_type_id: self.message_type_id(),
461            message_stream_id: CONTROL_MESSAGE_STREAM_ID,
462            payload,
463        }
464    }
465}
466
467broadcast_common::impl_spec_display!(ProtocolControl);
468
469impl Serialize for ProtocolControl {
470    type Error = RtmpError;
471
472    fn serialized_len(&self) -> usize {
473        match self {
474            ProtocolControl::SetChunkSize(_)
475            | ProtocolControl::Abort { .. }
476            | ProtocolControl::Acknowledgement(_)
477            | ProtocolControl::WindowAckSize(_) => U32_LEN,
478            ProtocolControl::SetPeerBandwidth { .. } => SET_PEER_BANDWIDTH_LEN,
479        }
480    }
481
482    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
483        let written = self.serialized_len();
484        need_in(buf, written, "protocol control payload output")?;
485        match *self {
486            ProtocolControl::SetChunkSize(size) => {
487                buf[0..U32_LEN].copy_from_slice(&size.value().to_be_bytes());
488            }
489            ProtocolControl::Abort { chunk_stream_id } => {
490                buf[0..U32_LEN].copy_from_slice(&chunk_stream_id.to_be_bytes());
491            }
492            ProtocolControl::Acknowledgement(sequence_number) => {
493                buf[0..U32_LEN].copy_from_slice(&sequence_number.get().to_be_bytes());
494            }
495            ProtocolControl::WindowAckSize(window) => {
496                buf[0..U32_LEN].copy_from_slice(&window.to_be_bytes());
497            }
498            ProtocolControl::SetPeerBandwidth {
499                ack_window_size,
500                limit_type,
501            } => {
502                buf[0..U32_LEN].copy_from_slice(&ack_window_size.to_be_bytes());
503                buf[U32_LEN] = limit_type.to_u8();
504            }
505        }
506        Ok(written)
507    }
508}
509
510// ── User control messages (§5.3 / §6.2 / §6.7) ──────────────────────────
511
512/// Byte width of the User Control Message's 16-bit `Event Type` field.
513const EVENT_TYPE_LEN: usize = 2;
514
515/// User Control Message event types (§6.7, spec §7.1.7).
516mod event_type {
517    pub const STREAM_BEGIN: u16 = 0;
518    pub const STREAM_EOF: u16 = 1;
519    pub const STREAM_DRY: u16 = 2;
520    pub const SET_BUFFER_LENGTH: u16 = 3;
521    pub const STREAM_IS_RECORDED: u16 = 4;
522    // Event value 5 is not defined by the spec.
523    pub const PING_REQUEST: u16 = 6;
524    pub const PING_RESPONSE: u16 = 7;
525}
526
527/// A User Control Message event (§5.3, message type id 4; event-data
528/// formats per §6.7, spec §7.1.7). SHOULD use message stream id 0 and,
529/// over the chunk stream, csid 2. Effective on receipt; timestamps
530/// ignored.
531///
532/// `#[non_exhaustive]`: §6.7's event-type catalogue (event value 5 is
533/// already an unassigned gap) can grow; a new event type must not be a
534/// breaking change for existing `match` callers.
535#[non_exhaustive]
536#[derive(Debug, Clone, Copy, PartialEq, Eq)]
537pub enum UserControl {
538    /// Stream Begin (event 0, server→client): the stream is now
539    /// functional/usable. By default sent on stream id 0 right after a
540    /// successful `connect`.
541    StreamBegin(u32),
542    /// Stream EOF (event 1, server→client): playback requested on this
543    /// stream has ended.
544    StreamEof(u32),
545    /// StreamDry (event 2, server→client): no more data on the stream
546    /// (server-detected idle).
547    StreamDry(u32),
548    /// SetBufferLength (event 3, client→server): the client's playback
549    /// buffer size, sent before the server starts sending the stream.
550    SetBufferLength {
551        /// The stream this buffer length applies to.
552        stream_id: u32,
553        /// The client's buffer length, a span carried on the wire as whole
554        /// milliseconds.
555        buffer: Duration,
556    },
557    /// StreamIsRecorded (event 4, server→client): the stream is a
558    /// recorded (not live) stream.
559    StreamIsRecorded(u32),
560    /// PingRequest (event 6, server→client): test reachability; the
561    /// client MUST reply with PingResponse.
562    PingRequest(u32),
563    /// PingResponse (event 7, client→server): reply to PingRequest,
564    /// echoing its timestamp.
565    PingResponse(u32),
566}
567
568impl UserControl {
569    /// The spec token for this user control event.
570    #[must_use]
571    pub fn name(&self) -> &'static str {
572        match self {
573            UserControl::StreamBegin(_) => "stream begin",
574            UserControl::StreamEof(_) => "stream eof",
575            UserControl::StreamDry(_) => "stream dry",
576            UserControl::SetBufferLength { .. } => "set buffer length",
577            UserControl::StreamIsRecorded(_) => "stream is recorded",
578            UserControl::PingRequest(_) => "ping request",
579            UserControl::PingResponse(_) => "ping response",
580        }
581    }
582
583    /// This event's 16-bit event type value (§6.7).
584    #[must_use]
585    pub fn event_type(&self) -> u16 {
586        match self {
587            UserControl::StreamBegin(_) => event_type::STREAM_BEGIN,
588            UserControl::StreamEof(_) => event_type::STREAM_EOF,
589            UserControl::StreamDry(_) => event_type::STREAM_DRY,
590            UserControl::SetBufferLength { .. } => event_type::SET_BUFFER_LENGTH,
591            UserControl::StreamIsRecorded(_) => event_type::STREAM_IS_RECORDED,
592            UserControl::PingRequest(_) => event_type::PING_REQUEST,
593            UserControl::PingResponse(_) => event_type::PING_RESPONSE,
594        }
595    }
596
597    /// The message payload, built without a fallible length check: the
598    /// result length is the type's own [`Serialize::serialized_len`].
599    ///
600    /// # Errors
601    /// [`RtmpError::FieldOverflow`] if a `SetBufferLength` span is longer
602    /// than the message's 32-bit millisecond field.
603    pub fn to_bytes(&self) -> Result<Vec<u8>> {
604        let mut buf = alloc::vec![0u8; self.serialized_len()];
605        buf[0..EVENT_TYPE_LEN].copy_from_slice(&self.event_type().to_be_bytes());
606        let data = &mut buf[EVENT_TYPE_LEN..];
607        match *self {
608            UserControl::StreamBegin(stream_id)
609            | UserControl::StreamEof(stream_id)
610            | UserControl::StreamDry(stream_id)
611            | UserControl::StreamIsRecorded(stream_id)
612            | UserControl::PingRequest(stream_id)
613            | UserControl::PingResponse(stream_id) => {
614                data[0..U32_LEN].copy_from_slice(&stream_id.to_be_bytes());
615            }
616            UserControl::SetBufferLength { stream_id, buffer } => {
617                data[0..U32_LEN].copy_from_slice(&stream_id.to_be_bytes());
618                let millis = u32::try_from(buffer.as_millis()).map_err(|_| {
619                    RtmpError::FieldOverflow(broadcast_common::len::FieldOverflow {
620                        field: "set_buffer_length.buffer",
621                        value: buffer.as_millis() as u64,
622                        max: u64::from(u32::MAX),
623                    })
624                })?;
625                data[U32_LEN..2 * U32_LEN].copy_from_slice(&millis.to_be_bytes());
626            }
627        }
628        Ok(buf)
629    }
630
631    /// Wrap this user control event in a [`Message`] ready to hand to
632    /// [`crate::chunk::ChunkWriter`] — chunk stream id
633    /// [`CONTROL_CHUNK_STREAM_ID`], message stream id
634    /// [`CONTROL_MESSAGE_STREAM_ID`], timestamp `0` (effective on receipt;
635    /// timestamps are not meaningful).
636    ///
637    /// # Errors
638    /// See [`UserControl::to_bytes`].
639    pub fn to_message(&self) -> Result<Message> {
640        Ok(Message {
641            chunk_stream_id: CONTROL_CHUNK_STREAM_ID,
642            timestamp: Timestamp::ZERO,
643            message_type_id: MessageTypeId::UserControl,
644            message_stream_id: CONTROL_MESSAGE_STREAM_ID,
645            payload: self.to_bytes()?,
646        })
647    }
648}
649
650broadcast_common::impl_spec_display!(UserControl);
651
652impl<'a> Parse<'a> for UserControl {
653    type Error = RtmpError;
654
655    fn parse(bytes: &'a [u8]) -> Result<Self> {
656        need_in(bytes, EVENT_TYPE_LEN, "user control event type")?;
657        let event = u16::from_be_bytes([bytes[0], bytes[1]]);
658        let data = &bytes[EVENT_TYPE_LEN..];
659        match event {
660            event_type::STREAM_BEGIN => Ok(UserControl::StreamBegin(need_u32(
661                data,
662                "stream begin event data",
663            )?)),
664            event_type::STREAM_EOF => Ok(UserControl::StreamEof(need_u32(
665                data,
666                "stream eof event data",
667            )?)),
668            event_type::STREAM_DRY => Ok(UserControl::StreamDry(need_u32(
669                data,
670                "stream dry event data",
671            )?)),
672            event_type::SET_BUFFER_LENGTH => {
673                need_in(data, 2 * U32_LEN, "set buffer length event data")?;
674                Ok(UserControl::SetBufferLength {
675                    stream_id: read_u32_be(&data[0..U32_LEN]),
676                    buffer: Duration::from_millis(u64::from(read_u32_be(
677                        &data[U32_LEN..2 * U32_LEN],
678                    ))),
679                })
680            }
681            event_type::STREAM_IS_RECORDED => Ok(UserControl::StreamIsRecorded(need_u32(
682                data,
683                "stream is recorded event data",
684            )?)),
685            event_type::PING_REQUEST => Ok(UserControl::PingRequest(need_u32(
686                data,
687                "ping request event data",
688            )?)),
689            event_type::PING_RESPONSE => Ok(UserControl::PingResponse(need_u32(
690                data,
691                "ping response event data",
692            )?)),
693            other => Err(RtmpError::UnsupportedUserControlEvent { value: other }),
694        }
695    }
696}
697
698impl Serialize for UserControl {
699    type Error = RtmpError;
700
701    fn serialized_len(&self) -> usize {
702        let data_len = match self {
703            UserControl::SetBufferLength { .. } => 2 * U32_LEN,
704            _ => U32_LEN,
705        };
706        EVENT_TYPE_LEN + data_len
707    }
708
709    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
710        let written = self.serialized_len();
711        need_in(buf, written, "user control event output")?;
712        buf[0..EVENT_TYPE_LEN].copy_from_slice(&self.event_type().to_be_bytes());
713        let data = &mut buf[EVENT_TYPE_LEN..written];
714        match *self {
715            UserControl::StreamBegin(stream_id)
716            | UserControl::StreamEof(stream_id)
717            | UserControl::StreamDry(stream_id)
718            | UserControl::StreamIsRecorded(stream_id)
719            | UserControl::PingRequest(stream_id)
720            | UserControl::PingResponse(stream_id) => {
721                data[0..U32_LEN].copy_from_slice(&stream_id.to_be_bytes());
722            }
723            UserControl::SetBufferLength { stream_id, buffer } => {
724                let millis = u32::try_from(buffer.as_millis()).map_err(|_| {
725                    RtmpError::FieldOverflow(broadcast_common::len::FieldOverflow {
726                        field: "set_buffer_length.buffer",
727                        value: buffer.as_millis() as u64,
728                        max: u64::from(u32::MAX),
729                    })
730                })?;
731                data[0..U32_LEN].copy_from_slice(&stream_id.to_be_bytes());
732                data[U32_LEN..2 * U32_LEN].copy_from_slice(&millis.to_be_bytes());
733            }
734        }
735        Ok(written)
736    }
737}
738
739#[cfg(test)]
740mod tests {
741    use super::*;
742
743    fn message(message_type_id: MessageTypeId, payload: Vec<u8>) -> Message {
744        Message {
745            chunk_stream_id: CONTROL_CHUNK_STREAM_ID,
746            timestamp: Timestamp::ZERO,
747            message_type_id,
748            message_stream_id: CONTROL_MESSAGE_STREAM_ID,
749            payload,
750        }
751    }
752
753    // ── LimitType ────────────────────────────────────────────────────────
754
755    /// An invalid chunk size can no longer reach a [`Message`]: the
756    /// `ChunkSize` constructor is the only way in (§5.4.1), and once built
757    /// `to_message` is total — so this asserts both halves end to end, the
758    /// rejection and then the framed bytes of a valid size.
759    #[test]
760    fn invalid_chunk_size_never_reaches_a_message() {
761        assert!(matches!(
762            ChunkSize::try_new(0),
763            Err(RtmpError::ChunkSizeOutOfRange { value: 0 })
764        ));
765        assert!(matches!(
766            ChunkSize::try_new(0x8000_0000),
767            Err(RtmpError::ChunkSizeOutOfRange { value: 0x8000_0000 })
768        ));
769        let msg = ProtocolControl::SetChunkSize(ChunkSize::try_new(4096).unwrap()).to_message();
770        assert_eq!(msg.message_type_id, MessageTypeId::SetChunkSize);
771        assert_eq!(msg.payload, vec![0x00, 0x00, 0x10, 0x00]);
772    }
773
774    #[test]
775    fn limit_type_round_trip_and_name() {
776        for (byte, lt, name) in [
777            (0u8, LimitType::Hard, "hard"),
778            (1, LimitType::Soft, "soft"),
779            (2, LimitType::Dynamic, "dynamic"),
780        ] {
781            let parsed = LimitType::from_u8(byte).unwrap();
782            assert_eq!(parsed, lt);
783            assert_eq!(parsed.to_u8(), byte);
784            assert_eq!(parsed.name(), name);
785            assert_eq!(parsed.to_string(), name);
786        }
787    }
788
789    #[test]
790    fn limit_type_out_of_range_is_malformed() {
791        assert!(matches!(
792            LimitType::from_u8(3),
793            Err(RtmpError::InvalidLimitType { value: 3 })
794        ));
795    }
796
797    // ── ProtocolControl round-trips ──────────────────────────────────────
798
799    fn protocol_control_round_trip(pc: ProtocolControl) {
800        let bytes = pc.try_to_bytes().unwrap();
801        let parsed = ProtocolControl::from_payload(pc.message_type_id(), &bytes)
802            .unwrap()
803            .expect("known protocol control type id");
804        assert_eq!(parsed, pc);
805
806        // parse -> serialize -> byte-identical
807        let msg = message(pc.message_type_id(), bytes.clone());
808        let via_message = ProtocolControl::from_message(&msg).unwrap().unwrap();
809        assert_eq!(via_message, pc);
810        assert_eq!(via_message.try_to_bytes().unwrap(), bytes);
811    }
812
813    #[test]
814    fn set_chunk_size_round_trips() {
815        protocol_control_round_trip(ProtocolControl::SetChunkSize(
816            ChunkSize::try_new(4096).unwrap(),
817        ));
818    }
819
820    #[test]
821    fn abort_round_trips() {
822        protocol_control_round_trip(ProtocolControl::Abort { chunk_stream_id: 7 });
823    }
824
825    #[test]
826    fn acknowledgement_round_trips() {
827        protocol_control_round_trip(ProtocolControl::Acknowledgement(SequenceNumber::new(
828            1_048_576,
829        )));
830    }
831
832    #[test]
833    fn window_ack_size_round_trips() {
834        protocol_control_round_trip(ProtocolControl::WindowAckSize(2_500_000));
835    }
836
837    #[test]
838    fn set_peer_bandwidth_round_trips_every_limit_type() {
839        for limit_type in [LimitType::Hard, LimitType::Soft, LimitType::Dynamic] {
840            protocol_control_round_trip(ProtocolControl::SetPeerBandwidth {
841                ack_window_size: 2_500_000,
842                limit_type,
843            });
844        }
845    }
846
847    #[test]
848    fn protocol_control_to_bytes_matches_the_serializer() {
849        for pc in [
850            ProtocolControl::SetChunkSize(ChunkSize::try_new(4096).unwrap()),
851            ProtocolControl::Abort { chunk_stream_id: 7 },
852            ProtocolControl::Acknowledgement(SequenceNumber::new(1_048_576)),
853            ProtocolControl::WindowAckSize(2_500_000),
854            ProtocolControl::SetPeerBandwidth {
855                ack_window_size: 2_500_000,
856                limit_type: LimitType::Hard,
857            },
858            ProtocolControl::SetPeerBandwidth {
859                ack_window_size: 2_500_000,
860                limit_type: LimitType::Soft,
861            },
862            ProtocolControl::SetPeerBandwidth {
863                ack_window_size: 2_500_000,
864                limit_type: LimitType::Dynamic,
865            },
866        ] {
867            assert_eq!(pc.to_bytes(), pc.try_to_bytes().unwrap());
868            assert_eq!(pc.to_message().payload, pc.to_bytes());
869        }
870    }
871
872    #[test]
873    fn set_chunk_size_reserved_top_bit_rejected_on_parse() {
874        let bytes = 0x8000_1000u32.to_be_bytes().to_vec();
875        assert!(matches!(
876            ProtocolControl::from_payload(MessageTypeId::SetChunkSize, &bytes),
877            Err(RtmpError::ChunkSizeOutOfRange { value: 0x8000_1000 })
878        ));
879    }
880
881    #[test]
882    fn set_chunk_size_zero_rejected() {
883        let bytes = 0u32.to_be_bytes().to_vec();
884        assert!(matches!(
885            ProtocolControl::from_payload(MessageTypeId::SetChunkSize, &bytes),
886            Err(RtmpError::ChunkSizeOutOfRange { value: 0 })
887        ));
888        assert!(ChunkSize::try_new(0).is_err());
889    }
890
891    #[test]
892    fn set_chunk_size_serialize_layout_matches_spec() {
893        // §5.4.1: reserved bit 0, 31-bit chunk size, big-endian.
894        let bytes = ProtocolControl::SetChunkSize(ChunkSize::try_new(1).unwrap())
895            .try_to_bytes()
896            .unwrap();
897        assert_eq!(bytes, vec![0x00, 0x00, 0x00, 0x01]);
898    }
899
900    #[test]
901    fn set_peer_bandwidth_serialize_layout_matches_spec() {
902        let bytes = ProtocolControl::SetPeerBandwidth {
903            ack_window_size: 0x0002_5000,
904            limit_type: LimitType::Dynamic,
905        }
906        .try_to_bytes()
907        .unwrap();
908        assert_eq!(bytes, vec![0x00, 0x02, 0x50, 0x00, 0x02]);
909    }
910
911    #[test]
912    fn set_peer_bandwidth_wrong_limit_type_mapping_would_fail() {
913        // Mutation check: swapping Hard/Dynamic's wire values would break this.
914        assert_eq!(LimitType::Hard.to_u8(), 0);
915        assert_eq!(LimitType::Dynamic.to_u8(), 2);
916        assert_ne!(LimitType::Hard.to_u8(), LimitType::Dynamic.to_u8());
917    }
918
919    #[test]
920    fn from_message_none_for_non_control_type_id() {
921        let msg = message(MessageTypeId::Audio, vec![0u8; 4]);
922        assert!(ProtocolControl::from_message(&msg).unwrap().is_none());
923    }
924
925    #[test]
926    fn from_message_some_for_control_type_id() {
927        let msg = message(
928            MessageTypeId::WindowAckSize,
929            1_000_000u32.to_be_bytes().to_vec(),
930        );
931        assert!(ProtocolControl::from_message(&msg).unwrap().is_some());
932    }
933
934    #[test]
935    fn to_message_uses_control_csid_and_stream_id() {
936        let msg = ProtocolControl::SetChunkSize(ChunkSize::try_new(4096).unwrap()).to_message();
937        assert_eq!(msg.chunk_stream_id, CONTROL_CHUNK_STREAM_ID);
938        assert_eq!(msg.message_stream_id, CONTROL_MESSAGE_STREAM_ID);
939        assert_eq!(msg.message_type_id, MessageTypeId::SetChunkSize);
940    }
941
942    #[test]
943    fn protocol_control_display_matches_name() {
944        assert_eq!(
945            ProtocolControl::Acknowledgement(SequenceNumber::new(1)).to_string(),
946            ProtocolControl::Acknowledgement(SequenceNumber::new(1)).name()
947        );
948    }
949
950    // ── UserControl round-trips ──────────────────────────────────────────
951
952    fn user_control_round_trip(uc: UserControl) {
953        let bytes = uc.try_to_bytes().unwrap();
954        let parsed = UserControl::parse(&bytes).unwrap();
955        assert_eq!(parsed, uc);
956        assert_eq!(parsed.try_to_bytes().unwrap(), bytes);
957    }
958
959    #[test]
960    fn stream_begin_round_trips() {
961        user_control_round_trip(UserControl::StreamBegin(1));
962    }
963
964    #[test]
965    fn stream_begin_serialize_layout_matches_spec() {
966        // §6.7: event type 0x0000 + 4-byte stream id, big-endian.
967        let bytes = UserControl::StreamBegin(1).try_to_bytes().unwrap();
968        assert_eq!(bytes, vec![0x00, 0x00, 0x00, 0x00, 0x00, 0x01]);
969    }
970
971    #[test]
972    fn user_control_to_bytes_matches_the_serializer() {
973        for uc in [
974            UserControl::StreamBegin(1),
975            UserControl::StreamEof(1),
976            UserControl::StreamDry(1),
977            UserControl::StreamIsRecorded(1),
978            UserControl::PingRequest(1),
979            UserControl::PingResponse(1),
980            UserControl::SetBufferLength {
981                stream_id: 1,
982                buffer: Duration::from_millis(3_000),
983            },
984        ] {
985            assert_eq!(uc.to_bytes().unwrap(), uc.try_to_bytes().unwrap());
986            assert_eq!(uc.to_message().unwrap().payload, uc.to_bytes().unwrap());
987        }
988    }
989
990    #[test]
991    fn stream_eof_round_trips() {
992        user_control_round_trip(UserControl::StreamEof(1));
993    }
994
995    #[test]
996    fn stream_dry_round_trips() {
997        user_control_round_trip(UserControl::StreamDry(1));
998    }
999
1000    #[test]
1001    fn set_buffer_length_round_trips() {
1002        user_control_round_trip(UserControl::SetBufferLength {
1003            stream_id: 1,
1004            buffer: Duration::from_millis(3000),
1005        });
1006    }
1007
1008    #[test]
1009    fn stream_is_recorded_round_trips() {
1010        user_control_round_trip(UserControl::StreamIsRecorded(1));
1011    }
1012
1013    #[test]
1014    fn ping_request_round_trips() {
1015        user_control_round_trip(UserControl::PingRequest(0x1234_5678));
1016    }
1017
1018    #[test]
1019    fn ping_response_round_trips() {
1020        user_control_round_trip(UserControl::PingResponse(0x1234_5678));
1021    }
1022
1023    #[test]
1024    fn unrecognised_event_type_is_unsupported() {
1025        // Event value 5 is not defined by the spec.
1026        let bytes = [0x00, 0x05, 0x00, 0x00, 0x00, 0x01];
1027        assert!(matches!(
1028            UserControl::parse(&bytes),
1029            Err(RtmpError::UnsupportedUserControlEvent { value: 5 })
1030        ));
1031    }
1032
1033    #[test]
1034    fn user_control_event_type_wrong_mapping_would_fail() {
1035        // Mutation check: swapping StreamBegin/StreamEof's event-type
1036        // values would break this.
1037        assert_eq!(UserControl::StreamBegin(0).event_type(), 0);
1038        assert_eq!(UserControl::StreamEof(0).event_type(), 1);
1039    }
1040
1041    #[test]
1042    fn user_control_display_matches_name() {
1043        assert_eq!(
1044            UserControl::StreamBegin(1).to_string(),
1045            UserControl::StreamBegin(1).name()
1046        );
1047    }
1048
1049    #[test]
1050    fn to_message_uses_control_csid_and_user_control_type_id() {
1051        let msg = UserControl::StreamBegin(1).to_message().unwrap();
1052        assert_eq!(msg.chunk_stream_id, CONTROL_CHUNK_STREAM_ID);
1053        assert_eq!(msg.message_stream_id, CONTROL_MESSAGE_STREAM_ID);
1054        assert_eq!(msg.message_type_id, MessageTypeId::UserControl);
1055    }
1056
1057    #[test]
1058    fn message_type_ids_round_trip_every_defined_value() {
1059        for (id, value) in [
1060            (MessageTypeId::SetChunkSize, 1u8),
1061            (MessageTypeId::Abort, 2),
1062            (MessageTypeId::Acknowledgement, 3),
1063            (MessageTypeId::UserControl, 4),
1064            (MessageTypeId::WindowAckSize, 5),
1065            (MessageTypeId::SetPeerBandwidth, 6),
1066            (MessageTypeId::Audio, 8),
1067            (MessageTypeId::Video, 9),
1068            (MessageTypeId::DataAmf3, 15),
1069            (MessageTypeId::CommandAmf3, 17),
1070            (MessageTypeId::DataAmf0, 18),
1071            (MessageTypeId::CommandAmf0, 20),
1072            (MessageTypeId::Aggregate, 22),
1073        ] {
1074            assert_eq!(id.to_u8(), value, "{}", id.name());
1075            assert_eq!(MessageTypeId::from_u8(value), id);
1076            assert_eq!(id.to_string(), id.name());
1077        }
1078    }
1079
1080    #[test]
1081    fn an_undefined_message_type_id_is_kept_as_other_and_displays_its_byte() {
1082        // 7, 10..=14, 16, 19 and 21 are not in §7.1's table.
1083        for value in [0u8, 7, 10, 16, 19, 21, 200] {
1084            assert_eq!(
1085                MessageTypeId::from_u8(value),
1086                MessageTypeId::Other(value),
1087                "type id {value}"
1088            );
1089            assert_eq!(MessageTypeId::from_u8(value).to_u8(), value);
1090        }
1091        assert_eq!(MessageTypeId::Other(7).name(), "other");
1092        assert_eq!(MessageTypeId::Other(7).to_string(), "other(0x07)");
1093    }
1094
1095    // ── Truncated User Control payloads (audit 22) ────────────────────────
1096
1097    #[test]
1098    fn truncated_four_byte_user_control_data_is_rejected() {
1099        for event in [
1100            event_type::STREAM_BEGIN,
1101            event_type::STREAM_EOF,
1102            event_type::STREAM_DRY,
1103            event_type::STREAM_IS_RECORDED,
1104            event_type::PING_REQUEST,
1105            event_type::PING_RESPONSE,
1106        ] {
1107            for data_len in 0..4usize {
1108                let mut bytes = event.to_be_bytes().to_vec();
1109                bytes.extend(core::iter::repeat_n(0u8, data_len));
1110                assert!(
1111                    matches!(
1112                        UserControl::parse(&bytes),
1113                        Err(RtmpError::BufferTooShort(BufferTooShort {
1114                            need: 4,
1115                            have,
1116                            ..
1117                        })) if have == data_len
1118                    ),
1119                    "event 0x{event:04X} with {data_len} data bytes must be rejected"
1120                );
1121            }
1122        }
1123    }
1124
1125    #[test]
1126    fn set_buffer_length_requires_both_four_byte_fields() {
1127        for data_len in 0..8usize {
1128            let mut bytes = event_type::SET_BUFFER_LENGTH.to_be_bytes().to_vec();
1129            bytes.extend(core::iter::repeat_n(0u8, data_len));
1130            assert!(
1131                matches!(
1132                    UserControl::parse(&bytes),
1133                    Err(RtmpError::BufferTooShort(BufferTooShort {
1134                        need: 8,
1135                        have,
1136                        ..
1137                    })) if have == data_len
1138                ),
1139                "set buffer length with {data_len} data bytes must be rejected"
1140            );
1141        }
1142        // §6.7: event type 0x0003, stream id 9, buffer 0x000003E8 ms.
1143        let bytes = [0x00, 0x03, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x03, 0xE8];
1144        assert_eq!(
1145            UserControl::parse(&bytes).unwrap(),
1146            UserControl::SetBufferLength {
1147                stream_id: 9,
1148                buffer: Duration::from_millis(1_000),
1149            }
1150        );
1151    }
1152
1153    #[test]
1154    fn protocol_control_names_are_pinned() {
1155        for (pc, name) in [
1156            (
1157                ProtocolControl::SetChunkSize(ChunkSize::try_new(4096).unwrap()),
1158                "set chunk size",
1159            ),
1160            (
1161                ProtocolControl::Abort { chunk_stream_id: 7 },
1162                "abort message",
1163            ),
1164            (
1165                ProtocolControl::Acknowledgement(SequenceNumber::new(1)),
1166                "acknowledgement",
1167            ),
1168            (
1169                ProtocolControl::WindowAckSize(2_500_000),
1170                "window acknowledgement size",
1171            ),
1172            (
1173                ProtocolControl::SetPeerBandwidth {
1174                    ack_window_size: 2_500_000,
1175                    limit_type: LimitType::Hard,
1176                },
1177                "set peer bandwidth",
1178            ),
1179        ] {
1180            assert_eq!(pc.name(), name);
1181            assert_eq!(pc.to_string(), name);
1182        }
1183    }
1184
1185    #[test]
1186    fn user_control_names_are_pinned() {
1187        for (uc, name) in [
1188            (UserControl::StreamBegin(1), "stream begin"),
1189            (UserControl::StreamEof(1), "stream eof"),
1190            (UserControl::StreamDry(1), "stream dry"),
1191            (
1192                UserControl::SetBufferLength {
1193                    stream_id: 1,
1194                    buffer: Duration::from_millis(3_000),
1195                },
1196                "set buffer length",
1197            ),
1198            (UserControl::StreamIsRecorded(1), "stream is recorded"),
1199            (UserControl::PingRequest(1), "ping request"),
1200            (UserControl::PingResponse(1), "ping response"),
1201        ] {
1202            assert_eq!(uc.name(), name);
1203            assert_eq!(uc.to_string(), name);
1204        }
1205    }
1206
1207    #[test]
1208    fn conversions_expose_the_spec_values() {
1209        // §7.1: Audio(8) and Video(9).
1210        assert_eq!(u8::from(MessageTypeId::Audio), 8);
1211        assert_eq!(u8::from(MessageTypeId::Video), 9);
1212        assert_eq!(u32::from(ChunkSize::new(4096).unwrap()), 4096);
1213    }
1214
1215    #[test]
1216    fn a_header_and_a_message_carry_the_undecoded_message_type_id() {
1217        use crate::chunk::{ChunkWriter, MessageHeader};
1218
1219        let header = MessageHeader::Type0 {
1220            timestamp: Timestamp::ZERO,
1221            message_length: 4,
1222            message_type_id: MessageTypeId::Other(99),
1223            message_stream_id: MessageStreamId::new(1),
1224        };
1225        let bytes = header.try_to_bytes().expect("header");
1226        let (back, consumed) =
1227            MessageHeader::parse(crate::chunk::Fmt::Type0, &bytes).expect("parse");
1228        assert_eq!(consumed, bytes.len());
1229        assert_eq!(back, header);
1230
1231        let message = message(MessageTypeId::Other(99), vec![0; 4]);
1232        let wire = ChunkWriter::new().write(&message).expect("write");
1233        // Basic header (1) + three 24-bit header fields before the type id.
1234        assert_eq!(wire[7], 99, "the wire carries the raw message type id");
1235        let mut assembler = crate::chunk::ChunkAssembler::new();
1236        assert_eq!(assembler.push(&wire).expect("push"), vec![message]);
1237    }
1238}