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