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 catalogue ([`msg_type`]), the Chunk-Stream-layer
10//! protocol control messages ([`ProtocolControl`], §4/§5.4), and the
11//! streaming-layer user control events ([`UserControl`], §5.3/§6.2/§6.7).
12
13use broadcast_common::error::BufferTooShort;
14use broadcast_common::len::need_in;
15use broadcast_common::{Parse, Serialize};
16
17use crate::RtmpError;
18use crate::chunk::Message;
19
20type Result<T> = core::result::Result<T, RtmpError>;
21
22// ── Message type ids (§6 / §7.1) ────────────────────────────────────────
23
24/// RTMP message type id catalogue (§6, RTMP Message Types §7.1). Type ids
25/// `1..=6` are Chunk-Stream-layer protocol control (this doc's §4, spec
26/// §5.4); the rest are streaming-layer message types (§6/§7.1).
27pub mod msg_type {
28    /// Set Chunk Size (§5.4.1).
29    pub const SET_CHUNK_SIZE: u8 = 1;
30    /// Abort Message (§5.4.2).
31    pub const ABORT: u8 = 2;
32    /// Acknowledgement (§5.4.3).
33    pub const ACKNOWLEDGEMENT: u8 = 3;
34    /// User Control Message (§6.2/§7.1.7).
35    pub const USER_CONTROL: u8 = 4;
36    /// Window Acknowledgement Size (§5.4.4).
37    pub const WINDOW_ACK_SIZE: u8 = 5;
38    /// Set Peer Bandwidth (§5.4.5).
39    pub const SET_PEER_BANDWIDTH: u8 = 6;
40    /// Audio Message (§7.1.4).
41    pub const AUDIO: u8 = 8;
42    /// Video Message (§7.1.5).
43    pub const VIDEO: u8 = 9;
44    /// Data Message, AMF3-encoded (§7.1.2).
45    pub const DATA_AMF3: u8 = 15;
46    /// Command Message, AMF3-encoded (§7.1.1).
47    pub const COMMAND_AMF3: u8 = 17;
48    /// Data Message, AMF0-encoded (§7.1.2).
49    pub const DATA_AMF0: u8 = 18;
50    /// Command Message, AMF0-encoded (§7.1.1).
51    pub const COMMAND_AMF0: u8 = 20;
52    /// Aggregate Message (§7.1.6).
53    pub const AGGREGATE: u8 = 22;
54}
55
56/// Chunk stream id protocol control messages and user control messages
57/// MUST/SHOULD be sent on (§4, §5.3).
58pub const CONTROL_CHUNK_STREAM_ID: u32 = 2;
59/// Message stream id protocol control messages MUST use, and user control
60/// messages SHOULD use (§4, §5.3): the control stream.
61pub const CONTROL_MESSAGE_STREAM_ID: u32 = 0;
62
63/// Byte width of a `u32` protocol control field (chunk size, chunk stream
64/// id, sequence number, window ack size).
65const U32_LEN: usize = 4;
66/// Byte width of the Set Peer Bandwidth payload: window size (4) + limit
67/// type (1).
68const SET_PEER_BANDWIDTH_LEN: usize = U32_LEN + 1;
69
70/// Bit mask isolating the reserved top bit of the Set Chunk Size payload
71/// (§5.4.1: 1 reserved bit, MUST be 0, + 31-bit chunk size).
72const SET_CHUNK_SIZE_RESERVED_MASK: u32 = 0x8000_0000;
73/// Bit mask isolating the 31-bit chunk size field of the Set Chunk Size
74/// payload.
75const SET_CHUNK_SIZE_VALUE_MASK: u32 = 0x7FFF_FFFF;
76
77fn read_u32_be(b: &[u8]) -> u32 {
78    u32::from_be_bytes([b[0], b[1], b[2], b[3]])
79}
80
81fn need_u32(bytes: &[u8], what: &'static str) -> Result<u32> {
82    if bytes.len() < U32_LEN {
83        return Err(RtmpError::BufferTooShort(BufferTooShort {
84            need: U32_LEN,
85            have: bytes.len(),
86            what,
87        }));
88    }
89    Ok(read_u32_be(bytes))
90}
91
92// ── Set Peer Bandwidth Limit Type (§5.4.5) ──────────────────────────────
93
94/// Set Peer Bandwidth's `Limit Type` byte (§5.4.5).
95#[derive(Debug, Clone, Copy, PartialEq, Eq)]
96#[non_exhaustive]
97pub enum LimitType {
98    /// Peer SHOULD limit output to exactly the indicated window.
99    Hard,
100    /// Peer SHOULD limit output to the indicated window or its current
101    /// limit, whichever is smaller.
102    Soft,
103    /// If the previous Limit Type was Hard, treat as Hard; otherwise
104    /// ignore this message.
105    Dynamic,
106}
107
108impl LimitType {
109    /// The spec token for this limit type.
110    #[must_use]
111    pub fn name(&self) -> &'static str {
112        match self {
113            LimitType::Hard => "hard",
114            LimitType::Soft => "soft",
115            LimitType::Dynamic => "dynamic",
116        }
117    }
118
119    /// Decode the wire byte (0..=2) into a [`LimitType`].
120    ///
121    /// # Errors
122    /// [`RtmpError::Malformed`] if `v` is not in `0..=2`.
123    pub const fn from_u8(v: u8) -> core::result::Result<Self, RtmpError> {
124        match v {
125            0 => Ok(LimitType::Hard),
126            1 => Ok(LimitType::Soft),
127            2 => Ok(LimitType::Dynamic),
128            _ => Err(RtmpError::Malformed {
129                what: "set peer bandwidth limit type (must be 0..=2)",
130            }),
131        }
132    }
133
134    /// Encode this limit type back to its wire byte (0..=2).
135    #[must_use]
136    pub const fn to_u8(self) -> u8 {
137        match self {
138            LimitType::Hard => 0,
139            LimitType::Soft => 1,
140            LimitType::Dynamic => 2,
141        }
142    }
143}
144
145broadcast_common::impl_spec_display!(LimitType);
146
147// ── Protocol control messages (§4 / §5.4) ───────────────────────────────
148
149/// A Chunk-Stream-layer protocol control message (§4, spec §5.4):
150/// message type ids `1`, `2`, `3`, `5`, `6`. MUST use message stream id 0
151/// and chunk stream id 2 ([`CONTROL_MESSAGE_STREAM_ID`] /
152/// [`CONTROL_CHUNK_STREAM_ID`]); effective immediately on receipt.
153///
154/// `#[non_exhaustive]`: `§4`'s protocol control catalogue is closed today,
155/// but this mirrors [`UserControl`]/[`crate::amf0::Amf0Value`] so a future
156/// addition never breaks an existing `match`.
157#[non_exhaustive]
158#[derive(Debug, Clone, Copy, PartialEq, Eq)]
159pub enum ProtocolControl {
160    /// Set Chunk Size (§5.4.1): the new maximum chunk size (`1..=0x7FFF_FFFF`).
161    SetChunkSize(u32),
162    /// Abort Message (§5.4.2): discard any partially-received message on
163    /// this chunk stream id.
164    Abort {
165        /// The chunk stream id whose in-progress message should be
166        /// discarded.
167        chunk_stream_id: u32,
168    },
169    /// Acknowledgement (§5.4.3): total bytes received so far.
170    Acknowledgement(u32),
171    /// Window Acknowledgement Size (§5.4.4): the sender's advertised
172    /// window size.
173    WindowAckSize(u32),
174    /// Set Peer Bandwidth (§5.4.5): limit the peer's output bandwidth.
175    SetPeerBandwidth {
176        /// The acknowledgement window size to limit the peer to.
177        ack_window_size: u32,
178        /// How strictly the peer should observe the limit.
179        limit_type: LimitType,
180    },
181}
182
183impl ProtocolControl {
184    /// The spec token for this protocol control message.
185    #[must_use]
186    pub fn name(&self) -> &'static str {
187        match self {
188            ProtocolControl::SetChunkSize(_) => "set chunk size",
189            ProtocolControl::Abort { .. } => "abort message",
190            ProtocolControl::Acknowledgement(_) => "acknowledgement",
191            ProtocolControl::WindowAckSize(_) => "window acknowledgement size",
192            ProtocolControl::SetPeerBandwidth { .. } => "set peer bandwidth",
193        }
194    }
195
196    /// This variant's message type id (§6/§7.1).
197    #[must_use]
198    pub fn message_type_id(&self) -> u8 {
199        match self {
200            ProtocolControl::SetChunkSize(_) => msg_type::SET_CHUNK_SIZE,
201            ProtocolControl::Abort { .. } => msg_type::ABORT,
202            ProtocolControl::Acknowledgement(_) => msg_type::ACKNOWLEDGEMENT,
203            ProtocolControl::WindowAckSize(_) => msg_type::WINDOW_ACK_SIZE,
204            ProtocolControl::SetPeerBandwidth { .. } => msg_type::SET_PEER_BANDWIDTH,
205        }
206    }
207
208    /// Interpret an already-reassembled [`Message`] as a protocol control
209    /// message, dispatching on `message.message_type_id`.
210    ///
211    /// Returns `Ok(None)` if `message.message_type_id` is not one of the
212    /// protocol control ids (`1`, `2`, `3`, `5`, `6`) — the caller should
213    /// then dispatch it elsewhere (user control, audio/video, command, …).
214    ///
215    /// # Errors
216    /// [`RtmpError::BufferTooShort`] if the payload is shorter than the
217    /// message type requires; [`RtmpError::Malformed`] if a field violates
218    /// its wire constraint (reserved bit set, out-of-range limit type).
219    pub fn from_message(message: &Message) -> Result<Option<Self>> {
220        Self::from_payload(message.message_type_id, &message.payload)
221    }
222
223    /// Parse a protocol control payload given its message type id. Not a
224    /// [`Parse`] impl: unlike every other wire type in this crate, a
225    /// protocol control payload alone is ambiguous (e.g. a bare 4-byte
226    /// payload is `SetChunkSize`, `Abort`, `Acknowledgement`, or
227    /// `WindowAckSize` depending on the message type id carried alongside
228    /// it in the [`Message`] header) — the type id is required context.
229    ///
230    /// # Errors
231    /// See [`ProtocolControl::from_message`].
232    pub fn from_payload(message_type_id: u8, payload: &[u8]) -> Result<Option<Self>> {
233        match message_type_id {
234            msg_type::SET_CHUNK_SIZE => {
235                let raw = need_u32(payload, "set chunk size payload")?;
236                if raw & SET_CHUNK_SIZE_RESERVED_MASK != 0 {
237                    return Err(RtmpError::Malformed {
238                        what: "set chunk size reserved top bit (must be 0)",
239                    });
240                }
241                let size = raw & SET_CHUNK_SIZE_VALUE_MASK;
242                if size == 0 {
243                    return Err(RtmpError::Malformed {
244                        what: "set chunk size value (must be >= 1)",
245                    });
246                }
247                Ok(Some(ProtocolControl::SetChunkSize(size)))
248            }
249            msg_type::ABORT => {
250                let chunk_stream_id = need_u32(payload, "abort message payload")?;
251                Ok(Some(ProtocolControl::Abort { chunk_stream_id }))
252            }
253            msg_type::ACKNOWLEDGEMENT => {
254                let sequence_number = need_u32(payload, "acknowledgement payload")?;
255                Ok(Some(ProtocolControl::Acknowledgement(sequence_number)))
256            }
257            msg_type::WINDOW_ACK_SIZE => {
258                let window = need_u32(payload, "window acknowledgement size payload")?;
259                Ok(Some(ProtocolControl::WindowAckSize(window)))
260            }
261            msg_type::SET_PEER_BANDWIDTH => {
262                need_in(
263                    payload,
264                    SET_PEER_BANDWIDTH_LEN,
265                    "set peer bandwidth payload",
266                )?;
267                let ack_window_size = read_u32_be(&payload[0..U32_LEN]);
268                let limit_type = LimitType::from_u8(payload[U32_LEN])?;
269                Ok(Some(ProtocolControl::SetPeerBandwidth {
270                    ack_window_size,
271                    limit_type,
272                }))
273            }
274            _ => Ok(None),
275        }
276    }
277
278    /// Wrap this protocol control message in a [`Message`] ready to hand to
279    /// [`crate::chunk::ChunkWriter`] — chunk stream id
280    /// [`CONTROL_CHUNK_STREAM_ID`], message stream id
281    /// [`CONTROL_MESSAGE_STREAM_ID`], timestamp `0` (protocol control
282    /// messages take effect immediately; timestamps are not meaningful).
283    ///
284    /// # Panics
285    ///
286    /// On a value `serialize_into` rejects (`SetChunkSize` of 0 or with the
287    /// top bit set); use [`try_to_message`](Self::try_to_message) for
288    /// untrusted values.
289    #[must_use]
290    pub fn to_message(&self) -> Message {
291        Message {
292            chunk_stream_id: CONTROL_CHUNK_STREAM_ID,
293            timestamp: 0,
294            message_type_id: self.message_type_id(),
295            message_stream_id: CONTROL_MESSAGE_STREAM_ID,
296            payload: self
297                .try_to_bytes()
298                .expect("documented panic: see `# Panics`; use try_to_message"),
299        }
300    }
301
302    /// Like [`to_message`](Self::to_message) but returns the serializer's
303    /// error instead of panicking — e.g. `SetChunkSize(0)` or a size with
304    /// the reserved top bit set is not a valid wire value (§5.4.1).
305    ///
306    /// # Errors
307    ///
308    /// [`RtmpError::Malformed`] for an out-of-range chunk size.
309    pub fn try_to_message(&self) -> Result<Message> {
310        Ok(Message {
311            chunk_stream_id: CONTROL_CHUNK_STREAM_ID,
312            timestamp: 0,
313            message_type_id: self.message_type_id(),
314            message_stream_id: CONTROL_MESSAGE_STREAM_ID,
315            payload: self.try_to_bytes()?,
316        })
317    }
318}
319
320broadcast_common::impl_spec_display!(ProtocolControl);
321
322impl Serialize for ProtocolControl {
323    type Error = RtmpError;
324
325    fn serialized_len(&self) -> usize {
326        match self {
327            ProtocolControl::SetChunkSize(_)
328            | ProtocolControl::Abort { .. }
329            | ProtocolControl::Acknowledgement(_)
330            | ProtocolControl::WindowAckSize(_) => U32_LEN,
331            ProtocolControl::SetPeerBandwidth { .. } => SET_PEER_BANDWIDTH_LEN,
332        }
333    }
334
335    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
336        let written = self.serialized_len();
337        need_in(buf, written, "protocol control payload output")?;
338        match *self {
339            ProtocolControl::SetChunkSize(size) => {
340                if size == 0 || size & SET_CHUNK_SIZE_RESERVED_MASK != 0 {
341                    return Err(RtmpError::Malformed {
342                        what: "set chunk size value (must be 1..=0x7FFF_FFFF)",
343                    });
344                }
345                buf[0..U32_LEN].copy_from_slice(&size.to_be_bytes());
346            }
347            ProtocolControl::Abort { chunk_stream_id } => {
348                buf[0..U32_LEN].copy_from_slice(&chunk_stream_id.to_be_bytes());
349            }
350            ProtocolControl::Acknowledgement(sequence_number) => {
351                buf[0..U32_LEN].copy_from_slice(&sequence_number.to_be_bytes());
352            }
353            ProtocolControl::WindowAckSize(window) => {
354                buf[0..U32_LEN].copy_from_slice(&window.to_be_bytes());
355            }
356            ProtocolControl::SetPeerBandwidth {
357                ack_window_size,
358                limit_type,
359            } => {
360                buf[0..U32_LEN].copy_from_slice(&ack_window_size.to_be_bytes());
361                buf[U32_LEN] = limit_type.to_u8();
362            }
363        }
364        Ok(written)
365    }
366}
367
368// ── User control messages (§5.3 / §6.2 / §6.7) ──────────────────────────
369
370/// Byte width of the User Control Message's 16-bit `Event Type` field.
371const EVENT_TYPE_LEN: usize = 2;
372
373/// User Control Message event types (§6.7, spec §7.1.7).
374mod event_type {
375    pub const STREAM_BEGIN: u16 = 0;
376    pub const STREAM_EOF: u16 = 1;
377    pub const STREAM_DRY: u16 = 2;
378    pub const SET_BUFFER_LENGTH: u16 = 3;
379    pub const STREAM_IS_RECORDED: u16 = 4;
380    // Event value 5 is not defined by the spec.
381    pub const PING_REQUEST: u16 = 6;
382    pub const PING_RESPONSE: u16 = 7;
383}
384
385/// A User Control Message event (§5.3, message type id 4; event-data
386/// formats per §6.7, spec §7.1.7). SHOULD use message stream id 0 and,
387/// over the chunk stream, csid 2. Effective on receipt; timestamps
388/// ignored.
389///
390/// `#[non_exhaustive]`: §6.7's event-type catalogue (event value 5 is
391/// already an unassigned gap) can grow; a new event type must not be a
392/// breaking change for existing `match` callers.
393#[non_exhaustive]
394#[derive(Debug, Clone, Copy, PartialEq, Eq)]
395pub enum UserControl {
396    /// Stream Begin (event 0, server→client): the stream is now
397    /// functional/usable. By default sent on stream id 0 right after a
398    /// successful `connect`.
399    StreamBegin(u32),
400    /// Stream EOF (event 1, server→client): playback requested on this
401    /// stream has ended.
402    StreamEof(u32),
403    /// StreamDry (event 2, server→client): no more data on the stream
404    /// (server-detected idle).
405    StreamDry(u32),
406    /// SetBufferLength (event 3, client→server): the client's playback
407    /// buffer size, sent before the server starts sending the stream.
408    SetBufferLength {
409        /// The stream this buffer length applies to.
410        stream_id: u32,
411        /// The client's buffer length, in milliseconds.
412        buffer_ms: u32,
413    },
414    /// StreamIsRecorded (event 4, server→client): the stream is a
415    /// recorded (not live) stream.
416    StreamIsRecorded(u32),
417    /// PingRequest (event 6, server→client): test reachability; the
418    /// client MUST reply with PingResponse.
419    PingRequest(u32),
420    /// PingResponse (event 7, client→server): reply to PingRequest,
421    /// echoing its timestamp.
422    PingResponse(u32),
423}
424
425impl UserControl {
426    /// The spec token for this user control event.
427    #[must_use]
428    pub fn name(&self) -> &'static str {
429        match self {
430            UserControl::StreamBegin(_) => "stream begin",
431            UserControl::StreamEof(_) => "stream eof",
432            UserControl::StreamDry(_) => "stream dry",
433            UserControl::SetBufferLength { .. } => "set buffer length",
434            UserControl::StreamIsRecorded(_) => "stream is recorded",
435            UserControl::PingRequest(_) => "ping request",
436            UserControl::PingResponse(_) => "ping response",
437        }
438    }
439
440    /// This event's 16-bit event type value (§6.7).
441    #[must_use]
442    pub fn event_type(&self) -> u16 {
443        match self {
444            UserControl::StreamBegin(_) => event_type::STREAM_BEGIN,
445            UserControl::StreamEof(_) => event_type::STREAM_EOF,
446            UserControl::StreamDry(_) => event_type::STREAM_DRY,
447            UserControl::SetBufferLength { .. } => event_type::SET_BUFFER_LENGTH,
448            UserControl::StreamIsRecorded(_) => event_type::STREAM_IS_RECORDED,
449            UserControl::PingRequest(_) => event_type::PING_REQUEST,
450            UserControl::PingResponse(_) => event_type::PING_RESPONSE,
451        }
452    }
453
454    /// Wrap this user control event in a [`Message`] ready to hand to
455    /// [`crate::chunk::ChunkWriter`] — chunk stream id
456    /// [`CONTROL_CHUNK_STREAM_ID`], message stream id
457    /// [`CONTROL_MESSAGE_STREAM_ID`], timestamp `0` (effective on receipt;
458    /// timestamps are not meaningful).
459    #[must_use]
460    pub fn to_message(&self) -> Message {
461        Message {
462            chunk_stream_id: CONTROL_CHUNK_STREAM_ID,
463            timestamp: 0,
464            message_type_id: msg_type::USER_CONTROL,
465            message_stream_id: CONTROL_MESSAGE_STREAM_ID,
466            payload: self
467                .try_to_bytes()
468                .expect("UserControl serialize_into only fails on a short buffer; try_to_bytes sizes it exactly"),
469        }
470    }
471}
472
473broadcast_common::impl_spec_display!(UserControl);
474
475impl<'a> Parse<'a> for UserControl {
476    type Error = RtmpError;
477
478    fn parse(bytes: &'a [u8]) -> Result<Self> {
479        need_in(bytes, EVENT_TYPE_LEN, "user control event type")?;
480        let event = u16::from_be_bytes([bytes[0], bytes[1]]);
481        let data = &bytes[EVENT_TYPE_LEN..];
482        match event {
483            event_type::STREAM_BEGIN => Ok(UserControl::StreamBegin(need_u32(
484                data,
485                "stream begin event data",
486            )?)),
487            event_type::STREAM_EOF => Ok(UserControl::StreamEof(need_u32(
488                data,
489                "stream eof event data",
490            )?)),
491            event_type::STREAM_DRY => Ok(UserControl::StreamDry(need_u32(
492                data,
493                "stream dry event data",
494            )?)),
495            event_type::SET_BUFFER_LENGTH => {
496                need_in(data, 2 * U32_LEN, "set buffer length event data")?;
497                Ok(UserControl::SetBufferLength {
498                    stream_id: read_u32_be(&data[0..U32_LEN]),
499                    buffer_ms: read_u32_be(&data[U32_LEN..2 * U32_LEN]),
500                })
501            }
502            event_type::STREAM_IS_RECORDED => Ok(UserControl::StreamIsRecorded(need_u32(
503                data,
504                "stream is recorded event data",
505            )?)),
506            event_type::PING_REQUEST => Ok(UserControl::PingRequest(need_u32(
507                data,
508                "ping request event data",
509            )?)),
510            event_type::PING_RESPONSE => Ok(UserControl::PingResponse(need_u32(
511                data,
512                "ping response event data",
513            )?)),
514            _ => Err(RtmpError::Unsupported {
515                what: "user control event type (unrecognised)",
516            }),
517        }
518    }
519}
520
521impl Serialize for UserControl {
522    type Error = RtmpError;
523
524    fn serialized_len(&self) -> usize {
525        let data_len = match self {
526            UserControl::SetBufferLength { .. } => 2 * U32_LEN,
527            _ => U32_LEN,
528        };
529        EVENT_TYPE_LEN + data_len
530    }
531
532    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
533        let written = self.serialized_len();
534        need_in(buf, written, "user control event output")?;
535        buf[0..EVENT_TYPE_LEN].copy_from_slice(&self.event_type().to_be_bytes());
536        let data = &mut buf[EVENT_TYPE_LEN..written];
537        match *self {
538            UserControl::StreamBegin(stream_id)
539            | UserControl::StreamEof(stream_id)
540            | UserControl::StreamDry(stream_id)
541            | UserControl::StreamIsRecorded(stream_id)
542            | UserControl::PingRequest(stream_id)
543            | UserControl::PingResponse(stream_id) => {
544                data[0..U32_LEN].copy_from_slice(&stream_id.to_be_bytes());
545            }
546            UserControl::SetBufferLength {
547                stream_id,
548                buffer_ms,
549            } => {
550                data[0..U32_LEN].copy_from_slice(&stream_id.to_be_bytes());
551                data[U32_LEN..2 * U32_LEN].copy_from_slice(&buffer_ms.to_be_bytes());
552            }
553        }
554        Ok(written)
555    }
556}
557
558#[cfg(test)]
559mod tests {
560    use super::*;
561
562    fn message(message_type_id: u8, payload: Vec<u8>) -> Message {
563        Message {
564            chunk_stream_id: CONTROL_CHUNK_STREAM_ID,
565            timestamp: 0,
566            message_type_id,
567            message_stream_id: CONTROL_MESSAGE_STREAM_ID,
568            payload,
569        }
570    }
571
572    // ── LimitType ────────────────────────────────────────────────────────
573
574    #[test]
575    fn try_to_message_rejects_invalid_chunk_size() {
576        assert!(matches!(
577            ProtocolControl::SetChunkSize(0).try_to_message(),
578            Err(RtmpError::Malformed { .. })
579        ));
580        assert!(
581            ProtocolControl::SetChunkSize(0x8000_0000)
582                .try_to_message()
583                .is_err()
584        );
585        assert_eq!(
586            ProtocolControl::SetChunkSize(4096)
587                .try_to_message()
588                .unwrap(),
589            ProtocolControl::SetChunkSize(4096).to_message()
590        );
591    }
592
593    #[test]
594    fn limit_type_round_trip_and_name() {
595        for (byte, lt, name) in [
596            (0u8, LimitType::Hard, "hard"),
597            (1, LimitType::Soft, "soft"),
598            (2, LimitType::Dynamic, "dynamic"),
599        ] {
600            let parsed = LimitType::from_u8(byte).unwrap();
601            assert_eq!(parsed, lt);
602            assert_eq!(parsed.to_u8(), byte);
603            assert_eq!(parsed.name(), name);
604            assert_eq!(parsed.to_string(), name);
605        }
606    }
607
608    #[test]
609    fn limit_type_out_of_range_is_malformed() {
610        assert!(matches!(
611            LimitType::from_u8(3),
612            Err(RtmpError::Malformed { .. })
613        ));
614    }
615
616    // ── ProtocolControl round-trips ──────────────────────────────────────
617
618    fn protocol_control_round_trip(pc: ProtocolControl) {
619        let bytes = pc.try_to_bytes().unwrap();
620        let parsed = ProtocolControl::from_payload(pc.message_type_id(), &bytes)
621            .unwrap()
622            .expect("known protocol control type id");
623        assert_eq!(parsed, pc);
624
625        // parse -> serialize -> byte-identical
626        let msg = message(pc.message_type_id(), bytes.clone());
627        let via_message = ProtocolControl::from_message(&msg).unwrap().unwrap();
628        assert_eq!(via_message, pc);
629        assert_eq!(via_message.try_to_bytes().unwrap(), bytes);
630    }
631
632    #[test]
633    fn set_chunk_size_round_trips() {
634        protocol_control_round_trip(ProtocolControl::SetChunkSize(4096));
635    }
636
637    #[test]
638    fn abort_round_trips() {
639        protocol_control_round_trip(ProtocolControl::Abort { chunk_stream_id: 7 });
640    }
641
642    #[test]
643    fn acknowledgement_round_trips() {
644        protocol_control_round_trip(ProtocolControl::Acknowledgement(1_048_576));
645    }
646
647    #[test]
648    fn window_ack_size_round_trips() {
649        protocol_control_round_trip(ProtocolControl::WindowAckSize(2_500_000));
650    }
651
652    #[test]
653    fn set_peer_bandwidth_round_trips_every_limit_type() {
654        for limit_type in [LimitType::Hard, LimitType::Soft, LimitType::Dynamic] {
655            protocol_control_round_trip(ProtocolControl::SetPeerBandwidth {
656                ack_window_size: 2_500_000,
657                limit_type,
658            });
659        }
660    }
661
662    #[test]
663    fn set_chunk_size_reserved_top_bit_rejected_on_parse() {
664        let bytes = 0x8000_1000u32.to_be_bytes().to_vec();
665        assert!(matches!(
666            ProtocolControl::from_payload(msg_type::SET_CHUNK_SIZE, &bytes),
667            Err(RtmpError::Malformed { .. })
668        ));
669    }
670
671    #[test]
672    fn set_chunk_size_zero_rejected() {
673        let bytes = 0u32.to_be_bytes().to_vec();
674        assert!(matches!(
675            ProtocolControl::from_payload(msg_type::SET_CHUNK_SIZE, &bytes),
676            Err(RtmpError::Malformed { .. })
677        ));
678        assert!(matches!(
679            ProtocolControl::SetChunkSize(0).serialize_into(&mut [0u8; 4]),
680            Err(RtmpError::Malformed { .. })
681        ));
682    }
683
684    #[test]
685    fn set_chunk_size_serialize_layout_matches_spec() {
686        // §5.4.1: reserved bit 0, 31-bit chunk size, big-endian.
687        let bytes = ProtocolControl::SetChunkSize(1).try_to_bytes().unwrap();
688        assert_eq!(bytes, vec![0x00, 0x00, 0x00, 0x01]);
689    }
690
691    #[test]
692    fn set_peer_bandwidth_serialize_layout_matches_spec() {
693        let bytes = ProtocolControl::SetPeerBandwidth {
694            ack_window_size: 0x0002_5000,
695            limit_type: LimitType::Dynamic,
696        }
697        .try_to_bytes()
698        .unwrap();
699        assert_eq!(bytes, vec![0x00, 0x02, 0x50, 0x00, 0x02]);
700    }
701
702    #[test]
703    fn set_peer_bandwidth_wrong_limit_type_mapping_would_fail() {
704        // Mutation check: swapping Hard/Dynamic's wire values would break this.
705        assert_eq!(LimitType::Hard.to_u8(), 0);
706        assert_eq!(LimitType::Dynamic.to_u8(), 2);
707        assert_ne!(LimitType::Hard.to_u8(), LimitType::Dynamic.to_u8());
708    }
709
710    #[test]
711    fn from_message_none_for_non_control_type_id() {
712        let msg = message(msg_type::AUDIO, vec![0u8; 4]);
713        assert!(ProtocolControl::from_message(&msg).unwrap().is_none());
714    }
715
716    #[test]
717    fn from_message_some_for_control_type_id() {
718        let msg = message(
719            msg_type::WINDOW_ACK_SIZE,
720            1_000_000u32.to_be_bytes().to_vec(),
721        );
722        assert!(ProtocolControl::from_message(&msg).unwrap().is_some());
723    }
724
725    #[test]
726    fn to_message_uses_control_csid_and_stream_id() {
727        let msg = ProtocolControl::SetChunkSize(4096).to_message();
728        assert_eq!(msg.chunk_stream_id, CONTROL_CHUNK_STREAM_ID);
729        assert_eq!(msg.message_stream_id, CONTROL_MESSAGE_STREAM_ID);
730        assert_eq!(msg.message_type_id, msg_type::SET_CHUNK_SIZE);
731    }
732
733    #[test]
734    fn protocol_control_display_matches_name() {
735        assert_eq!(
736            ProtocolControl::Acknowledgement(1).to_string(),
737            ProtocolControl::Acknowledgement(1).name()
738        );
739    }
740
741    // ── UserControl round-trips ──────────────────────────────────────────
742
743    fn user_control_round_trip(uc: UserControl) {
744        let bytes = uc.try_to_bytes().unwrap();
745        let parsed = UserControl::parse(&bytes).unwrap();
746        assert_eq!(parsed, uc);
747        assert_eq!(parsed.try_to_bytes().unwrap(), bytes);
748    }
749
750    #[test]
751    fn stream_begin_round_trips() {
752        user_control_round_trip(UserControl::StreamBegin(1));
753    }
754
755    #[test]
756    fn stream_begin_serialize_layout_matches_spec() {
757        // §6.7: event type 0x0000 + 4-byte stream id, big-endian.
758        let bytes = UserControl::StreamBegin(1).try_to_bytes().unwrap();
759        assert_eq!(bytes, vec![0x00, 0x00, 0x00, 0x00, 0x00, 0x01]);
760    }
761
762    #[test]
763    fn stream_eof_round_trips() {
764        user_control_round_trip(UserControl::StreamEof(1));
765    }
766
767    #[test]
768    fn stream_dry_round_trips() {
769        user_control_round_trip(UserControl::StreamDry(1));
770    }
771
772    #[test]
773    fn set_buffer_length_round_trips() {
774        user_control_round_trip(UserControl::SetBufferLength {
775            stream_id: 1,
776            buffer_ms: 3000,
777        });
778    }
779
780    #[test]
781    fn stream_is_recorded_round_trips() {
782        user_control_round_trip(UserControl::StreamIsRecorded(1));
783    }
784
785    #[test]
786    fn ping_request_round_trips() {
787        user_control_round_trip(UserControl::PingRequest(0x1234_5678));
788    }
789
790    #[test]
791    fn ping_response_round_trips() {
792        user_control_round_trip(UserControl::PingResponse(0x1234_5678));
793    }
794
795    #[test]
796    fn unrecognised_event_type_is_unsupported() {
797        // Event value 5 is not defined by the spec.
798        let bytes = [0x00, 0x05, 0x00, 0x00, 0x00, 0x01];
799        assert!(matches!(
800            UserControl::parse(&bytes),
801            Err(RtmpError::Unsupported { .. })
802        ));
803    }
804
805    #[test]
806    fn user_control_event_type_wrong_mapping_would_fail() {
807        // Mutation check: swapping StreamBegin/StreamEof's event-type
808        // values would break this.
809        assert_eq!(UserControl::StreamBegin(0).event_type(), 0);
810        assert_eq!(UserControl::StreamEof(0).event_type(), 1);
811    }
812
813    #[test]
814    fn user_control_display_matches_name() {
815        assert_eq!(
816            UserControl::StreamBegin(1).to_string(),
817            UserControl::StreamBegin(1).name()
818        );
819    }
820
821    #[test]
822    fn to_message_uses_control_csid_and_user_control_type_id() {
823        let msg = UserControl::StreamBegin(1).to_message();
824        assert_eq!(msg.chunk_stream_id, CONTROL_CHUNK_STREAM_ID);
825        assert_eq!(msg.message_stream_id, CONTROL_MESSAGE_STREAM_ID);
826        assert_eq!(msg.message_type_id, msg_type::USER_CONTROL);
827    }
828}