Skip to main content

rtmp_runtime/
amf0.rs

1//! AMF0 (Action Message Format 0) value encoding/decoding, used by RTMP
2//! command and data messages.
3//!
4//! See `private/specs-verified/rtmp/rtmp-runtime/rtmp.md` §8 (AMF0) for the full transcription
5//! of `[AMF0]` (the companion spec this doc cites): §8.1 for the type marker
6//! table, §8.2 for the wire encoding of each data type needed by RTMP command
7//! messages.
8//!
9//! RTMP does not wrap command/data message bodies in AMF0's own
10//! `amf-packet` framing — a message body is simply a sequence of AMF0
11//! `value-type`s (marker + body) concatenated one after another (§8.2). This
12//! module implements that sequence-of-values contract via [`Amf0Value`]
13//! (single value parse/serialize) and [`Command`] (the `name` +
14//! `transaction_id` + `arguments` sequence carried by Command Messages,
15//! §7.1.1).
16//!
17//! # Scope
18//!
19//! Implements the markers actually needed to decode/encode the ingest
20//! command set (`connect`/`createStream`/`publish`/`_result`/`onStatus`/…):
21//! Number, Boolean, String, Object, Null, Undefined, ECMA Array, Strict
22//! Array, plus Date and Long String (trivial once String/Number exist).
23//!
24//! Out of scope, and rejected as [`RtmpError::UnsupportedAmf0Marker`] rather than
25//! panicking or silently misparsing: `movieclip-marker` (`0x04`, reserved),
26//! `reference-marker` (`0x07`), `unsupported-marker` (`0x0D`),
27//! `recordset-marker` (`0x0E`, reserved), `xml-document-marker` (`0x0F`),
28//! `typed-object-marker` (`0x10`), and `avmplus-object-marker` (`0x11`, the
29//! AMF3 switch — AMF3 itself, `[AMF3]`, is a separate spec and explicitly
30//! out of scope for this ingest engine per private/specs-verified/rtmp/rtmp-runtime/rtmp.md §8.3).
31//!
32//! [`Amf0Value`] is a data-carrying ADT (like `Fmt`/`MessageHeader`'s payload
33//! variants), not a closed label enum, so it is a `#204` `label_coverage`
34//! SKIP-list candidate rather than a `name()`/`impl_spec_display!` target
35//! (tracked for the crate's Task 10 label-coverage pass).
36
37use broadcast_common::error::BufferTooShort;
38use broadcast_common::{Parse, Serialize};
39
40use crate::RtmpError;
41use alloc::string::String;
42use alloc::vec::Vec;
43
44type Result<T> = core::result::Result<T, RtmpError>;
45
46/// AMF0 type markers (`[AMF0]` §2.1, private/specs-verified/rtmp/rtmp-runtime/rtmp.md §8.1) — 1 byte.
47pub mod marker {
48    /// Number (§2.2): `DOUBLE`, 8-byte big-endian IEEE-754.
49    pub const NUMBER: u8 = 0x00;
50    /// Boolean (§2.3): 1 byte, `0` = false, nonzero = true.
51    pub const BOOLEAN: u8 = 0x01;
52    /// String (§2.4): `U16` length + UTF-8 bytes.
53    pub const STRING: u8 = 0x02;
54    /// Object (§2.5): key/value pairs terminated by [`OBJECT_END`].
55    pub const OBJECT: u8 = 0x03;
56    /// null (§2.7): no payload.
57    pub const NULL: u8 = 0x05;
58    /// undefined (§2.8): no payload.
59    pub const UNDEFINED: u8 = 0x06;
60    /// ECMA Array (§2.10): `U32` associative-count + key/value pairs
61    /// terminated by [`OBJECT_END`].
62    pub const ECMA_ARRAY: u8 = 0x08;
63    /// Object End (§2.11): always preceded by an empty (`U16` = 0) key — the
64    /// 3-byte sequence `00 00 09`.
65    pub const OBJECT_END: u8 = 0x09;
66    /// Strict Array (§2.12): `U32` count + that many values, ordinal only.
67    pub const STRICT_ARRAY: u8 = 0x0A;
68    /// Date (§2.13): `DOUBLE` (ms since Unix epoch, UTC) + reserved `S16`
69    /// time zone (MUST be `0x0000`).
70    pub const DATE: u8 = 0x0B;
71    /// Long String (§2.14): `U32` length + UTF-8 bytes, for strings over
72    /// 65535 bytes.
73    pub const LONG_STRING: u8 = 0x0C;
74}
75
76/// Maximum AMF0 container nesting depth (Object/ECMA Array/Strict Array)
77/// [`Amf0Value::parse`] will descend into. Bounds recursion so a
78/// pathologically nested input returns [`RtmpError::Amf0DepthExceeded`] instead of
79/// overflowing the native call stack — the guard is checked on *entering*
80/// each nested container, so recursion never actually reaches an
81/// attacker-chosen depth, only this constant.
82pub const MAX_AMF0_DEPTH: usize = 32;
83
84const MARKER_LEN: usize = 1;
85const NUMBER_LEN: usize = 8;
86const BOOLEAN_LEN: usize = 1;
87const U16_LEN: usize = 2;
88const U32_LEN: usize = 4;
89const DATE_RESERVED_LEN: usize = 2;
90/// `00 00 09`: empty key + [`marker::OBJECT_END`].
91const OBJECT_END_LEN: usize = 3;
92
93/// A single AMF0 value (`[AMF0]` §2, private/specs-verified/rtmp/rtmp-runtime/rtmp.md §8.2).
94///
95/// AMF3 (`avmplus-object-marker`, `0x11`) and the reserved/legacy markers
96/// (`movieclip`, `reference`, `unsupported`, `recordset`, `xml-document`,
97/// `typed-object`) are out of scope — see the module doc.
98///
99/// `#[non_exhaustive]`: this models a documented subset of `[AMF0]` §2's
100/// value types (see the module doc's Scope section); a future release may
101/// add a variant for one of the currently-`Unsupported` markers (e.g. a
102/// typed AMF3 bridge) without that being a breaking change for existing
103/// `match` callers.
104#[non_exhaustive]
105#[derive(Debug, Clone, PartialEq)]
106#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
107pub enum Amf0Value {
108    /// Number (§2.2).
109    Number(f64),
110    /// Boolean (§2.3).
111    Boolean(bool),
112    /// String (§2.4): `U16`-length UTF-8, at most 65535 bytes.
113    String(String),
114    /// Object (§2.5): ordered key/value pairs.
115    Object(Vec<(String, Amf0Value)>),
116    /// null (§2.7).
117    Null,
118    /// undefined (§2.8).
119    Undefined,
120    /// ECMA Array (§2.10): an associative array, encoded like Object plus a
121    /// leading (informational) `U32` count.
122    EcmaArray(Vec<(String, Amf0Value)>),
123    /// Strict Array (§2.12): an ordinal array of values.
124    StrictArray(Vec<Amf0Value>),
125    /// Date (§2.13): milliseconds since the Unix epoch, UTC.
126    Date(f64),
127    /// Long String (§2.14): `U32`-length UTF-8, for strings over 65535
128    /// bytes.
129    LongString(String),
130}
131
132fn buffer_too_short(need: usize, have: usize, what: &'static str) -> RtmpError {
133    RtmpError::BufferTooShort(BufferTooShort { need, have, what })
134}
135
136/// Read a `U16`-length-prefixed UTF-8 string from the front of `bytes`.
137/// Returns the decoded string and the total bytes consumed (`2 + len`).
138/// Used for both the String value body and Object/ECMA-Array keys, which
139/// share this exact encoding (§2.4 / §2.5).
140fn read_utf8_short(bytes: &[u8]) -> Result<(String, usize)> {
141    if bytes.len() < U16_LEN {
142        return Err(buffer_too_short(U16_LEN, bytes.len(), "AMF0 string length"));
143    }
144    let len = u16::from_be_bytes([bytes[0], bytes[1]]) as usize;
145    // `len` is at most `u16::MAX`, so `U16_LEN + len` cannot actually
146    // overflow `usize` on any real target, but guard it anyway (rather than
147    // a bare `+`) so this stays correct even on a hypothetical narrow
148    // `usize` platform, and matches the same guard on `read_utf8_long`
149    // below where the addend genuinely can overflow.
150    let total = U16_LEN.checked_add(len).ok_or(RtmpError::FieldOverflow(
151        broadcast_common::len::FieldOverflow {
152            field: "AMF0 string length",
153            value: u64::from(u16::MAX),
154            max: u64::try_from(usize::MAX).unwrap_or(u64::MAX),
155        },
156    ))?;
157    if bytes.len() < total {
158        return Err(buffer_too_short(total, bytes.len(), "AMF0 string"));
159    }
160    let s = String::from_utf8(bytes[U16_LEN..total].to_vec())
161        .map_err(|_| RtmpError::Amf0Utf8 { what: "string" })?;
162    Ok((s, total))
163}
164
165/// Read a `U32`-length-prefixed UTF-8 string (Long String, §2.14).
166fn read_utf8_long(bytes: &[u8]) -> Result<(String, usize)> {
167    if bytes.len() < U32_LEN {
168        return Err(buffer_too_short(
169            U32_LEN,
170            bytes.len(),
171            "AMF0 long string length",
172        ));
173    }
174    let len = u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) as usize;
175    // `len` can be up to `u32::MAX`: on a 32-bit target, `U32_LEN + len`
176    // wraps `usize` (e.g. `len == usize::MAX - 1`), which would make
177    // `bytes.len() < total` compare against a garbage-small wrapped value
178    // and misparse a length claim that should instead be rejected as too
179    // short. `checked_add` catches that instead of wrapping.
180    let total = U32_LEN.checked_add(len).ok_or(RtmpError::FieldOverflow(
181        broadcast_common::len::FieldOverflow {
182            field: "AMF0 long string length",
183            value: u64::from(u32::MAX),
184            max: u64::try_from(usize::MAX).unwrap_or(u64::MAX),
185        },
186    ))?;
187    if bytes.len() < total {
188        return Err(buffer_too_short(total, bytes.len(), "AMF0 long string"));
189    }
190    let s = String::from_utf8(bytes[U32_LEN..total].to_vec()).map_err(|_| RtmpError::Amf0Utf8 {
191        what: "long string",
192    })?;
193    Ok((s, total))
194}
195
196/// Parse the key/value pairs of an Object or ECMA Array body (§2.5/§2.10),
197/// starting right after any leading count field. Terminates on an empty key
198/// followed by [`marker::OBJECT_END`] (§2.11). `depth` is the nesting depth
199/// of the *values* in this container (already incremented past the
200/// container itself by the caller).
201fn parse_pairs(bytes: &[u8], depth: usize) -> Result<(Vec<(String, Amf0Value)>, usize)> {
202    let mut consumed = 0;
203    let mut pairs = Vec::new();
204    loop {
205        let (key, key_len) = read_utf8_short(&bytes[consumed..])?;
206        let after_key = consumed + key_len;
207        if key.is_empty() {
208            if bytes.len() < after_key + MARKER_LEN {
209                return Err(buffer_too_short(
210                    after_key + MARKER_LEN,
211                    bytes.len(),
212                    "amf0 object-end marker",
213                ));
214            }
215            if bytes[after_key] == marker::OBJECT_END {
216                return Ok((pairs, after_key + MARKER_LEN));
217            }
218        }
219        let (value, value_len) = parse_value(&bytes[after_key..], depth)?;
220        pairs.push((key, value));
221        consumed = after_key
222            .checked_add(value_len)
223            .ok_or(RtmpError::FieldOverflow(
224                broadcast_common::len::FieldOverflow {
225                    field: "AMF0 object pair length",
226                    value: u64::from(u32::try_from(after_key).unwrap_or(u32::MAX))
227                        + u64::from(u32::try_from(value_len).unwrap_or(u32::MAX)),
228                    max: u64::try_from(usize::MAX).unwrap_or(u64::MAX),
229                },
230            ))?;
231    }
232}
233
234/// Parse one AMF0 value (marker + body) from the front of `bytes`, ignoring
235/// any surplus trailing bytes, and return it with the number of bytes its
236/// encoding occupied. That count comes from the parser itself, so a caller
237/// walking a sequence of values advances by what was actually read rather
238/// than by a re-serialized length, which only agrees while every encoding is
239/// canonical. `depth` counts container nesting already
240/// entered (0 at the top level); checked *before* descending into a nested
241/// Object/ECMA-Array/Strict-Array so recursion is bounded by
242/// [`MAX_AMF0_DEPTH`] regardless of how deeply the input is (adversarially)
243/// nested.
244fn parse_value(bytes: &[u8], depth: usize) -> Result<(Amf0Value, usize)> {
245    if bytes.is_empty() {
246        return Err(buffer_too_short(MARKER_LEN, 0, "amf0 value marker"));
247    }
248    let body = &bytes[MARKER_LEN..];
249    match bytes[0] {
250        marker::NUMBER => {
251            if body.len() < NUMBER_LEN {
252                return Err(buffer_too_short(NUMBER_LEN, body.len(), "amf0 number"));
253            }
254            let mut b = [0u8; NUMBER_LEN];
255            b.copy_from_slice(&body[..NUMBER_LEN]);
256            Ok((
257                Amf0Value::Number(f64::from_be_bytes(b)),
258                MARKER_LEN + NUMBER_LEN,
259            ))
260        }
261        marker::BOOLEAN => {
262            if body.is_empty() {
263                return Err(buffer_too_short(BOOLEAN_LEN, 0, "amf0 boolean"));
264            }
265            Ok((Amf0Value::Boolean(body[0] != 0), MARKER_LEN + BOOLEAN_LEN))
266        }
267        marker::STRING => {
268            let (s, len) = read_utf8_short(body)?;
269            Ok((Amf0Value::String(s), MARKER_LEN + len))
270        }
271        marker::OBJECT => {
272            if depth >= MAX_AMF0_DEPTH {
273                return Err(RtmpError::Amf0DepthExceeded {
274                    max: MAX_AMF0_DEPTH,
275                });
276            }
277            let (pairs, len) = parse_pairs(body, depth + 1)?;
278            Ok((Amf0Value::Object(pairs), MARKER_LEN + len))
279        }
280        marker::NULL => Ok((Amf0Value::Null, MARKER_LEN)),
281        marker::UNDEFINED => Ok((Amf0Value::Undefined, MARKER_LEN)),
282        marker::ECMA_ARRAY => {
283            if depth >= MAX_AMF0_DEPTH {
284                return Err(RtmpError::Amf0DepthExceeded {
285                    max: MAX_AMF0_DEPTH,
286                });
287            }
288            if body.len() < U32_LEN {
289                return Err(buffer_too_short(
290                    U32_LEN,
291                    body.len(),
292                    "amf0 ecma array count",
293                ));
294            }
295            // The associative-count is informational only (§2.10); the
296            // object-end terminator is authoritative, so it is read and
297            // discarded rather than cross-checked against the parsed pair
298            // count.
299            let (pairs, len) = parse_pairs(&body[U32_LEN..], depth + 1)?;
300            Ok((Amf0Value::EcmaArray(pairs), MARKER_LEN + U32_LEN + len))
301        }
302        marker::STRICT_ARRAY => {
303            if depth >= MAX_AMF0_DEPTH {
304                return Err(RtmpError::Amf0DepthExceeded {
305                    max: MAX_AMF0_DEPTH,
306                });
307            }
308            if body.len() < U32_LEN {
309                return Err(buffer_too_short(
310                    U32_LEN,
311                    body.len(),
312                    "amf0 strict array count",
313                ));
314            }
315            let count = u32::from_be_bytes([body[0], body[1], body[2], body[3]]);
316            let mut rest = &body[U32_LEN..];
317            let mut values = Vec::new();
318            for _ in 0..count {
319                let (value, consumed) = parse_value(rest, depth + 1)?;
320                values.push(value);
321                rest = rest.get(consumed..).ok_or(RtmpError::FieldOverflow(
322                    broadcast_common::len::FieldOverflow {
323                        field: "AMF0 strict array element length",
324                        value: u64::try_from(consumed).unwrap_or(u64::MAX),
325                        max: u64::try_from(rest.len()).unwrap_or(u64::MAX),
326                    },
327                ))?;
328            }
329            let elements_len =
330                body[U32_LEN..]
331                    .len()
332                    .checked_sub(rest.len())
333                    .ok_or(RtmpError::Malformed {
334                        what: "AMF0 strict array body",
335                    })?;
336            Ok((
337                Amf0Value::StrictArray(values),
338                MARKER_LEN + U32_LEN + elements_len,
339            ))
340        }
341        marker::DATE => {
342            if body.len() < NUMBER_LEN + DATE_RESERVED_LEN {
343                return Err(buffer_too_short(
344                    NUMBER_LEN + DATE_RESERVED_LEN,
345                    body.len(),
346                    "amf0 date",
347                ));
348            }
349            let mut b = [0u8; NUMBER_LEN];
350            b.copy_from_slice(&body[..NUMBER_LEN]);
351            let tz = u16::from_be_bytes([body[NUMBER_LEN], body[NUMBER_LEN + 1]]);
352            if tz != 0 {
353                return Err(RtmpError::Amf0DateTimeZone { value: tz });
354            }
355            Ok((
356                Amf0Value::Date(f64::from_be_bytes(b)),
357                MARKER_LEN + NUMBER_LEN + DATE_RESERVED_LEN,
358            ))
359        }
360        marker::LONG_STRING => {
361            let (s, len) = read_utf8_long(body)?;
362            Ok((Amf0Value::LongString(s), MARKER_LEN + len))
363        }
364        other => Err(RtmpError::UnsupportedAmf0Marker { marker: other }),
365    }
366}
367
368/// The `FieldOverflow` for a value sequence whose total length does not fit a
369/// `usize`: the sum of real element lengths against the addressable maximum.
370fn sequence_length_overflow(so_far: usize, next: usize) -> RtmpError {
371    RtmpError::FieldOverflow(broadcast_common::len::FieldOverflow {
372        field: "amf0 value sequence length",
373        value: u64::from(u32::try_from(so_far).unwrap_or(u32::MAX))
374            + u64::from(u32::try_from(next).unwrap_or(u32::MAX)),
375        max: u64::try_from(usize::MAX).unwrap_or(u64::MAX),
376    })
377}
378
379fn pairs_body_len(pairs: &[(String, Amf0Value)]) -> usize {
380    pairs
381        .iter()
382        .map(|(k, v)| U16_LEN + k.len() + v.serialized_len())
383        .sum::<usize>()
384        + OBJECT_END_LEN
385}
386
387fn write_pairs(pairs: &[(String, Amf0Value)], buf: &mut [u8]) -> Result<usize> {
388    let mut offset = 0;
389    for (k, v) in pairs {
390        let key_total = U16_LEN + k.len();
391        if buf.len() < offset + key_total {
392            return Err(buffer_too_short(
393                offset + key_total,
394                buf.len(),
395                "amf0 object key output",
396            ));
397        }
398        let key_len = broadcast_common::len::fit_u16(k.len(), "amf0 object key length")?;
399        buf[offset..offset + U16_LEN].copy_from_slice(&key_len.to_be_bytes());
400        buf[offset + U16_LEN..offset + key_total].copy_from_slice(k.as_bytes());
401        offset += key_total;
402        offset += v.serialize_into(&mut buf[offset..])?;
403    }
404    if buf.len() < offset + OBJECT_END_LEN {
405        return Err(buffer_too_short(
406            offset + OBJECT_END_LEN,
407            buf.len(),
408            "amf0 object-end output",
409        ));
410    }
411    buf[offset] = 0;
412    buf[offset + 1] = 0;
413    buf[offset + 2] = marker::OBJECT_END;
414    Ok(offset + OBJECT_END_LEN)
415}
416
417impl<'a> Parse<'a> for Amf0Value {
418    type Error = RtmpError;
419
420    fn parse(bytes: &'a [u8]) -> Result<Self> {
421        let (value, _) = parse_value(bytes, 0)?;
422        Ok(value)
423    }
424}
425
426impl Serialize for Amf0Value {
427    type Error = RtmpError;
428
429    fn serialized_len(&self) -> usize {
430        MARKER_LEN
431            + match self {
432                Amf0Value::Number(_) | Amf0Value::Date(_) => NUMBER_LEN,
433                Amf0Value::Boolean(_) => BOOLEAN_LEN,
434                Amf0Value::String(s) => U16_LEN + s.len(),
435                Amf0Value::LongString(s) => U32_LEN + s.len(),
436                Amf0Value::Object(pairs) => pairs_body_len(pairs),
437                Amf0Value::Null | Amf0Value::Undefined => 0,
438                Amf0Value::EcmaArray(pairs) => U32_LEN + pairs_body_len(pairs),
439                Amf0Value::StrictArray(values) => {
440                    U32_LEN + values.iter().map(Serialize::serialized_len).sum::<usize>()
441                }
442            }
443            + match self {
444                Amf0Value::Date(_) => DATE_RESERVED_LEN,
445                _ => 0,
446            }
447    }
448
449    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
450        let written = self.serialized_len();
451        if buf.len() < written {
452            return Err(buffer_too_short(written, buf.len(), "amf0 value output"));
453        }
454        let (marker_byte, body) = buf[..written].split_at_mut(MARKER_LEN);
455        match self {
456            Amf0Value::Number(v) => {
457                marker_byte[0] = marker::NUMBER;
458                body[..NUMBER_LEN].copy_from_slice(&v.to_be_bytes());
459            }
460            Amf0Value::Boolean(v) => {
461                marker_byte[0] = marker::BOOLEAN;
462                body[0] = u8::from(*v);
463            }
464            Amf0Value::String(s) => {
465                if s.len() > usize::from(u16::MAX) {
466                    return Err(RtmpError::Amf0StringTooLong { len: s.len() });
467                }
468                marker_byte[0] = marker::STRING;
469                body[..U16_LEN].copy_from_slice(&(s.len() as u16).to_be_bytes());
470                body[U16_LEN..].copy_from_slice(s.as_bytes());
471            }
472            Amf0Value::LongString(s) => {
473                marker_byte[0] = marker::LONG_STRING;
474                let len = broadcast_common::len::fit_u32(s.len(), "amf0 long string length")?;
475                body[..U32_LEN].copy_from_slice(&len.to_be_bytes());
476                body[U32_LEN..].copy_from_slice(s.as_bytes());
477            }
478            Amf0Value::Object(pairs) => {
479                marker_byte[0] = marker::OBJECT;
480                write_pairs(pairs, body)?;
481            }
482            Amf0Value::Null => marker_byte[0] = marker::NULL,
483            Amf0Value::Undefined => marker_byte[0] = marker::UNDEFINED,
484            Amf0Value::EcmaArray(pairs) => {
485                marker_byte[0] = marker::ECMA_ARRAY;
486                let count = broadcast_common::len::fit_u32(pairs.len(), "amf0 ECMA array count")?;
487                body[..U32_LEN].copy_from_slice(&count.to_be_bytes());
488                write_pairs(pairs, &mut body[U32_LEN..])?;
489            }
490            Amf0Value::StrictArray(values) => {
491                marker_byte[0] = marker::STRICT_ARRAY;
492                let count =
493                    broadcast_common::len::fit_u32(values.len(), "amf0 strict array count")?;
494                body[..U32_LEN].copy_from_slice(&count.to_be_bytes());
495                let mut offset = U32_LEN;
496                for v in values {
497                    offset += v.serialize_into(&mut body[offset..])?;
498                }
499            }
500            Amf0Value::Date(v) => {
501                marker_byte[0] = marker::DATE;
502                body[..NUMBER_LEN].copy_from_slice(&v.to_be_bytes());
503                body[NUMBER_LEN..NUMBER_LEN + DATE_RESERVED_LEN].copy_from_slice(&[0, 0]);
504            }
505        }
506        Ok(written)
507    }
508}
509
510/// An RTMP Command Message body (§7.1.1): `name` (AMF0 String) + AMF0
511/// `transaction_id` (AMF0 Number) + zero or more argument values (typically
512/// a Command Object, then optional trailing arguments) — see private/specs-verified/rtmp/rtmp-runtime/rtmp.md
513/// §8.2's closing note and §6.1 (Command Message).
514///
515/// This is the message-body-level container: unlike [`Amf0Value`] it is not
516/// itself a single AMF0 `value-type`, so it uses inherent `parse`/`to_body`
517/// methods rather than the [`Parse`]/[`Serialize`] traits.
518#[derive(Debug, Clone, PartialEq)]
519#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
520pub struct Command {
521    /// The command name, e.g. `"connect"`, `"createStream"`, `"publish"`,
522    /// `"_result"`.
523    pub name: String,
524    /// The transaction id correlating a response to its request (`0` for
525    /// commands that expect no response, e.g. `onStatus`).
526    pub transaction_id: f64,
527    /// The remaining AMF0 values in the command body, in wire order
528    /// (conventionally: Command Object, then any further arguments).
529    pub arguments: Vec<Amf0Value>,
530}
531
532impl Command {
533    /// Parse a Command Message body: AMF0 String (`name`) + AMF0 Number
534    /// (`transaction_id`) + the remaining AMF0 values (`arguments`), read
535    /// until `payload` is exhausted.
536    ///
537    /// # Errors
538    /// [`RtmpError::CommandNameNotString`] if the first value is not a
539    /// String, [`RtmpError::CommandTransactionIdNotNumber`] if the second is
540    /// not a Number; the remaining variants are propagated from
541    /// [`Amf0Value::parse`].
542    pub fn parse(payload: &[u8]) -> Result<Self> {
543        let (name_value, name_len) = parse_value(payload, 0)?;
544        let mut offset = name_len;
545        let name = match name_value {
546            Amf0Value::String(s) => s,
547            value => return Err(RtmpError::CommandNameNotString { value }),
548        };
549
550        let (txn_value, txn_len) = parse_value(payload.get(offset..).unwrap_or_default(), 0)?;
551        offset = offset.checked_add(txn_len).ok_or(RtmpError::FieldOverflow(
552            broadcast_common::len::FieldOverflow {
553                field: "RTMP command transaction id offset",
554                value: u64::try_from(offset).unwrap_or(u64::MAX),
555                max: u64::try_from(usize::MAX).unwrap_or(u64::MAX),
556            },
557        ))?;
558        let transaction_id = match txn_value {
559            Amf0Value::Number(n) => n,
560            value => return Err(RtmpError::CommandTransactionIdNotNumber { value }),
561        };
562
563        let mut arguments = Vec::new();
564        while offset < payload.len() {
565            let (value, len) = parse_value(&payload[offset..], 0)?;
566            offset = offset.checked_add(len).ok_or(RtmpError::FieldOverflow(
567                broadcast_common::len::FieldOverflow {
568                    field: "RTMP command argument offset",
569                    value: u64::try_from(offset).unwrap_or(u64::MAX),
570                    max: u64::try_from(usize::MAX).unwrap_or(u64::MAX),
571                },
572            ))?;
573            arguments.push(value);
574        }
575
576        Ok(Command {
577            name,
578            transaction_id,
579            arguments,
580        })
581    }
582
583    /// Serialize this command back to an AMF0 command payload: `name` +
584    /// `transaction_id` + `arguments`, in that order.
585    ///
586    /// # Errors
587    ///
588    /// [`RtmpError::FieldOverflow`] when any string, key or array exceeds the
589    /// AMF0 16/32-bit length prefix (a peer-chosen publish name echoed into an
590    /// `onStatus` description can reach this).
591    pub fn to_body(&self) -> Result<Vec<u8>> {
592        let mut out = Amf0Value::String(self.name.clone()).try_to_bytes()?;
593        out.extend(Amf0Value::Number(self.transaction_id).try_to_bytes()?);
594        for arg in &self.arguments {
595            out.extend(arg.try_to_bytes()?);
596        }
597        Ok(out)
598    }
599}
600
601/// Encode `values` in order as one AMF0 byte sequence: what a message body
602/// carrying several bare values is (`onMetaData` is a String followed by an
603/// ECMA Array, §2 of the AMF0 spec).
604///
605/// # Errors
606///
607/// [`RtmpError::FieldOverflow`] when a string, key or array exceeds its AMF0
608/// length prefix (see [`Amf0Value`]'s own serializer).
609pub fn amf0_values(values: &[Amf0Value]) -> Result<Vec<u8>> {
610    let len = values.iter().try_fold(0usize, |acc, value| {
611        let value_len = value.serialized_len();
612        acc.checked_add(value_len)
613            .ok_or_else(|| sequence_length_overflow(acc, value_len))
614    })?;
615    let mut out = alloc::vec![0u8; len];
616    let mut written = 0usize;
617    for value in values {
618        written += value.serialize_into(&mut out[written..])?;
619    }
620    Ok(out)
621}
622
623#[cfg(test)]
624mod tests {
625    use super::*;
626
627    fn round_trip(v: &Amf0Value) {
628        let bytes = v.try_to_bytes().unwrap();
629        assert_eq!(bytes.len(), v.serialized_len());
630        let parsed = Amf0Value::parse(&bytes).expect("parse");
631        assert_eq!(&parsed, v);
632        // parse -> serialize -> byte-identical
633        assert_eq!(parsed.try_to_bytes().unwrap(), bytes);
634    }
635
636    #[test]
637    fn a_value_sequence_encodes_each_value_in_order() {
638        let values = [
639            Amf0Value::String("onMetaData".to_string()),
640            Amf0Value::EcmaArray(vec![("duration".to_string(), Amf0Value::Number(1.5))]),
641        ];
642        let body = amf0_values(&values).expect("encode");
643        let mut expected = values[0].try_to_bytes().unwrap();
644        expected.extend(values[1].try_to_bytes().unwrap());
645        assert_eq!(body, expected);
646    }
647
648    /// #2761: the overflow error carried `value = u64::MAX, max = u64::MAX`,
649    /// telling a caller nothing. It now carries the real current length and
650    /// the addressable maximum.
651    #[test]
652    fn a_sequence_length_overflow_reports_the_real_lengths() {
653        let err = sequence_length_overflow(6, 8);
654        let RtmpError::FieldOverflow(overflow) = err else {
655            panic!("expected FieldOverflow, got {err:?}");
656        };
657        assert_eq!(overflow.value, 14);
658        assert_eq!(
659            overflow.max,
660            u64::try_from(usize::MAX).expect("usize fits u64 on every supported target")
661        );
662    }
663
664    /// #2761: `Command::parse` advanced by each parsed value's re-serialized
665    /// length. The parser now reports what it consumed, so a value whose
666    /// encoding is not its canonical form (here AMF0 permits any non-zero
667    /// Boolean byte, and `0x02` re-serializes as `0x01`) no longer shifts the
668    /// boundary of the following argument.
669    #[test]
670    fn command_argument_boundaries_come_from_the_parse_not_a_re_derived_length() {
671        let mut payload = Amf0Value::String("connect".to_string())
672            .try_to_bytes()
673            .unwrap();
674        payload.extend(Amf0Value::Number(1.0).try_to_bytes().unwrap());
675        for i in 0..8u8 {
676            payload.extend([marker::BOOLEAN, i]);
677        }
678
679        let command = Command::parse(&payload).expect("any boolean byte is legal AMF0");
680        assert_eq!(
681            command.arguments,
682            (0..8u8)
683                .map(|i| Amf0Value::Boolean(i != 0))
684                .collect::<Vec<_>>()
685        );
686    }
687
688    #[test]
689    fn number_round_trips() {
690        round_trip(&Amf0Value::Number(0.0));
691        round_trip(&Amf0Value::Number(-1.5));
692        round_trip(&Amf0Value::Number(1_000_000.25));
693    }
694
695    #[test]
696    fn boolean_round_trips() {
697        round_trip(&Amf0Value::Boolean(true));
698        round_trip(&Amf0Value::Boolean(false));
699    }
700
701    /// An Object key of 65 536 bytes cannot fit its 16-bit length prefix
702    /// (#1129): unfixed, `(k.len() as u16)` silently wrapped 65536 to 0
703    /// while the full key bytes were still written, misframing the object.
704    #[test]
705    fn object_oversized_key_length_errors() {
706        let key = "k".repeat(65536);
707        let value = Amf0Value::Object(vec![(key, Amf0Value::Null)]);
708        let err = value.try_to_bytes().unwrap_err();
709        assert!(
710            matches!(
711                err,
712                RtmpError::FieldOverflow(broadcast_common::len::FieldOverflow {
713                    field: "amf0 object key length",
714                    ..
715                })
716            ),
717            "expected FieldOverflow for amf0 object key length, got {err:?}"
718        );
719    }
720
721    /// The AMF0 String marker carries a 16-bit length prefix, so a longer
722    /// value is rejected rather than written with a wrapped length.
723    #[test]
724    fn string_beyond_the_16_bit_prefix_is_rejected() {
725        let value = Amf0Value::String("x".repeat(0x1_0000));
726        let err = value.try_to_bytes().unwrap_err();
727        assert!(
728            matches!(err, RtmpError::Amf0StringTooLong { len } if len == 0x1_0000),
729            "expected Amf0StringTooLong for a 65 536-byte string, got {err:?}"
730        );
731        let boundary = Amf0Value::String("x".repeat(usize::from(u16::MAX)));
732        round_trip(&boundary);
733    }
734
735    /// The boundary: exactly 65 535 bytes (u16::MAX) still round-trips.
736    #[test]
737    fn object_max_key_length_round_trips() {
738        let key = "k".repeat(65535);
739        round_trip(&Amf0Value::Object(vec![(key, Amf0Value::Null)]));
740    }
741
742    #[test]
743    fn string_round_trips_including_empty_and_multibyte() {
744        round_trip(&Amf0Value::String(String::new()));
745        round_trip(&Amf0Value::String("live".to_string()));
746        round_trip(&Amf0Value::String("héllo wörld 日本語".to_string()));
747    }
748
749    #[test]
750    fn null_and_undefined_round_trip() {
751        round_trip(&Amf0Value::Null);
752        round_trip(&Amf0Value::Undefined);
753    }
754
755    #[test]
756    fn date_round_trips() {
757        round_trip(&Amf0Value::Date(1_700_000_000_000.0));
758    }
759
760    #[test]
761    fn long_string_round_trips() {
762        round_trip(&Amf0Value::LongString("x".repeat(70_000)));
763    }
764
765    #[test]
766    fn object_round_trips_including_nested_object() {
767        round_trip(&Amf0Value::Object(vec![]));
768        round_trip(&Amf0Value::Object(vec![
769            ("app".to_string(), Amf0Value::String("live".to_string())),
770            ("audioSampleRate".to_string(), Amf0Value::Number(44100.0)),
771            ("live".to_string(), Amf0Value::Boolean(true)),
772        ]));
773        // Nested Object (the `connect` command object has string/number/
774        // boolean fields, and encoders may nest e.g. a capabilities object).
775        round_trip(&Amf0Value::Object(vec![(
776            "capabilities".to_string(),
777            Amf0Value::Object(vec![("videoCodecs".to_string(), Amf0Value::Number(252.0))]),
778        )]));
779    }
780
781    #[test]
782    fn ecma_array_round_trips() {
783        round_trip(&Amf0Value::EcmaArray(vec![]));
784        round_trip(&Amf0Value::EcmaArray(vec![
785            ("duration".to_string(), Amf0Value::Number(0.0)),
786            ("width".to_string(), Amf0Value::Number(1920.0)),
787        ]));
788    }
789
790    #[test]
791    fn strict_array_round_trips() {
792        round_trip(&Amf0Value::StrictArray(vec![]));
793        round_trip(&Amf0Value::StrictArray(vec![
794            Amf0Value::Number(1.0),
795            Amf0Value::String("two".to_string()),
796            Amf0Value::Boolean(false),
797            Amf0Value::Object(vec![("k".to_string(), Amf0Value::Null)]),
798        ]));
799    }
800
801    #[test]
802    fn ecma_array_count_is_informational_not_cross_checked() {
803        // A real encoder writes the true pair count, but §2.10 makes the
804        // object-end terminator authoritative — a lying count must still
805        // parse correctly off the terminator, not the count field.
806        let mut bytes = vec![marker::ECMA_ARRAY];
807        bytes.extend_from_slice(&999u32.to_be_bytes()); // lying count
808        bytes.extend_from_slice(&1u16.to_be_bytes());
809        bytes.extend_from_slice(b"k");
810        bytes.push(marker::NULL);
811        bytes.extend_from_slice(&[0, 0, marker::OBJECT_END]);
812
813        let parsed = Amf0Value::parse(&bytes).expect("parse");
814        assert_eq!(
815            parsed,
816            Amf0Value::EcmaArray(vec![("k".to_string(), Amf0Value::Null)])
817        );
818    }
819
820    #[test]
821    fn depth_guard_rejects_pathological_nesting_without_stack_overflow() {
822        // Build a deeply-nested Object payload by pure byte manipulation
823        // (no recursive construction/serialization of our own types), so
824        // the test itself can never stack-overflow regardless of the depth
825        // guard's correctness.
826        let mut inner = vec![marker::NULL];
827        for _ in 0..(MAX_AMF0_DEPTH * 4) {
828            let mut wrapped = vec![marker::OBJECT];
829            wrapped.extend_from_slice(&1u16.to_be_bytes());
830            wrapped.push(b'a');
831            wrapped.extend_from_slice(&inner);
832            wrapped.extend_from_slice(&[0, 0, marker::OBJECT_END]);
833            inner = wrapped;
834        }
835
836        let result = Amf0Value::parse(&inner);
837        assert!(matches!(
838            result,
839            Err(RtmpError::Amf0DepthExceeded { max }) if max == MAX_AMF0_DEPTH
840        ));
841    }
842
843    #[test]
844    fn depth_guard_allows_nesting_at_the_limit() {
845        let mut inner = vec![marker::NULL];
846        for _ in 0..(MAX_AMF0_DEPTH - 1) {
847            let mut wrapped = vec![marker::OBJECT];
848            wrapped.extend_from_slice(&1u16.to_be_bytes());
849            wrapped.push(b'a');
850            wrapped.extend_from_slice(&inner);
851            wrapped.extend_from_slice(&[0, 0, marker::OBJECT_END]);
852            inner = wrapped;
853        }
854        assert!(Amf0Value::parse(&inner).is_ok());
855    }
856
857    #[test]
858    fn dropping_object_end_marker_is_rejected() {
859        // Mutation check: an Object with its `00 00 09` terminator dropped
860        // must fail to parse (BufferTooShort), not silently succeed.
861        let full = Amf0Value::Object(vec![("k".to_string(), Amf0Value::Null)])
862            .try_to_bytes()
863            .unwrap();
864        let truncated = &full[..full.len() - 3];
865        assert!(matches!(
866            Amf0Value::parse(truncated),
867            Err(RtmpError::BufferTooShort(..))
868        ));
869    }
870
871    #[test]
872    fn mis_sized_string_length_is_rejected() {
873        // Mutation check: claiming a longer string length than the buffer
874        // actually holds must fail (BufferTooShort), not read garbage.
875        let mut bytes = vec![marker::STRING];
876        bytes.extend_from_slice(&100u16.to_be_bytes()); // claims 100 bytes
877        bytes.extend_from_slice(b"short"); // only 5 present
878        assert!(matches!(
879            Amf0Value::parse(&bytes),
880            Err(RtmpError::BufferTooShort(..))
881        ));
882    }
883
884    #[test]
885    fn invalid_utf8_string_is_malformed() {
886        let mut bytes = vec![marker::STRING];
887        bytes.extend_from_slice(&2u16.to_be_bytes());
888        bytes.extend_from_slice(&[0xFF, 0xFE]); // invalid UTF-8
889        assert!(matches!(
890            Amf0Value::parse(&bytes),
891            Err(RtmpError::Amf0Utf8 { what: "string" })
892        ));
893    }
894
895    #[test]
896    fn unsupported_marker_is_rejected_not_panicking() {
897        assert!(matches!(
898            Amf0Value::parse(&[0x11]), // avmplus-object-marker (AMF3 switch)
899            Err(RtmpError::UnsupportedAmf0Marker { marker: 0x11 })
900        ));
901        assert!(matches!(
902            Amf0Value::parse(&[0x07]), // reference-marker
903            Err(RtmpError::UnsupportedAmf0Marker { marker: 0x07 })
904        ));
905    }
906
907    #[test]
908    fn date_rejects_nonzero_reserved_timezone() {
909        let mut bytes = vec![marker::DATE];
910        bytes.extend_from_slice(&0.0f64.to_be_bytes());
911        bytes.extend_from_slice(&1u16.to_be_bytes()); // reserved must be 0
912        assert!(matches!(
913            Amf0Value::parse(&bytes),
914            Err(RtmpError::Amf0DateTimeZone { value: 1 })
915        ));
916    }
917
918    #[test]
919    fn empty_buffer_and_truncated_marker_are_buffer_too_short_not_panics() {
920        assert!(matches!(
921            Amf0Value::parse(&[]),
922            Err(RtmpError::BufferTooShort(..))
923        ));
924        assert!(matches!(
925            Amf0Value::parse(&[marker::NUMBER, 0, 0, 0]),
926            Err(RtmpError::BufferTooShort(..))
927        ));
928    }
929
930    // ── Command ──────────────────────────────────────────────────────────
931
932    fn connect_command() -> Command {
933        Command {
934            name: "connect".to_string(),
935            transaction_id: 1.0,
936            arguments: vec![Amf0Value::Object(vec![
937                ("app".to_string(), Amf0Value::String("live".to_string())),
938                (
939                    "flashVer".to_string(),
940                    Amf0Value::String("FMLE/3.0".to_string()),
941                ),
942                (
943                    "tcUrl".to_string(),
944                    Amf0Value::String("rtmp://example.test/live".to_string()),
945                ),
946                ("fpad".to_string(), Amf0Value::Boolean(false)),
947            ])],
948        }
949    }
950
951    fn publish_command() -> Command {
952        Command {
953            name: "publish".to_string(),
954            transaction_id: 5.0,
955            arguments: vec![
956                Amf0Value::Null,
957                Amf0Value::String("stream_key_123".to_string()),
958                Amf0Value::String("live".to_string()),
959            ],
960        }
961    }
962
963    #[test]
964    fn connect_command_round_trips_byte_identically() {
965        let cmd = connect_command();
966        let bytes = cmd.to_body().unwrap();
967        let parsed = Command::parse(&bytes).expect("parse connect");
968        assert_eq!(parsed, cmd);
969        assert_eq!(parsed.to_body().unwrap(), bytes);
970    }
971
972    #[test]
973    fn publish_command_round_trips_byte_identically() {
974        let cmd = publish_command();
975        let bytes = cmd.to_body().unwrap();
976        let parsed = Command::parse(&bytes).expect("parse publish");
977        assert_eq!(parsed, cmd);
978        assert_eq!(parsed.to_body().unwrap(), bytes);
979    }
980
981    #[test]
982    fn command_name_must_be_string() {
983        let bytes = Amf0Value::Number(1.0).try_to_bytes().unwrap();
984        assert!(matches!(
985            Command::parse(&bytes),
986            Err(RtmpError::CommandNameNotString { .. })
987        ));
988    }
989
990    #[test]
991    fn command_transaction_id_must_be_number() {
992        let mut bytes = Amf0Value::String("connect".to_string())
993            .try_to_bytes()
994            .unwrap();
995        bytes.extend(
996            Amf0Value::String("not a number".to_string())
997                .try_to_bytes()
998                .unwrap(),
999        );
1000        assert!(matches!(
1001            Command::parse(&bytes),
1002            Err(RtmpError::CommandTransactionIdNotNumber { .. })
1003        ));
1004    }
1005
1006    // ── 32-bit overflow guards (mutation checks) ─────────────────────────
1007
1008    #[test]
1009    fn long_string_length_overflowing_usize_is_rejected_not_wrapped() {
1010        // Mutation check: a Long String claiming `usize::MAX - 1` bytes must
1011        // be rejected as too-short/malformed, not silently wrap `U32_LEN +
1012        // len` into a small `total` that then compares as if the string
1013        // were actually present.
1014        let mut bytes = vec![marker::LONG_STRING];
1015        bytes.extend_from_slice(&(u32::MAX - 1).to_be_bytes());
1016        bytes.extend_from_slice(b"short");
1017        let err = Amf0Value::parse(&bytes).unwrap_err();
1018        assert!(matches!(
1019            err,
1020            RtmpError::Malformed { .. } | RtmpError::BufferTooShort(..)
1021        ));
1022    }
1023
1024    // ── serde (feature "serde") ───────────────────────────────────────────
1025
1026    #[cfg(feature = "serde")]
1027    #[test]
1028    fn amf0_value_and_command_serde_round_trip() {
1029        let value = Amf0Value::Object(vec![
1030            ("app".to_string(), Amf0Value::String("live".to_string())),
1031            ("live".to_string(), Amf0Value::Boolean(true)),
1032            ("duration".to_string(), Amf0Value::Number(0.0)),
1033            (
1034                "items".to_string(),
1035                Amf0Value::StrictArray(vec![Amf0Value::Null, Amf0Value::Undefined]),
1036            ),
1037        ]);
1038        let json = serde_json::to_string(&value).expect("serialize Amf0Value");
1039        let back: Amf0Value = serde_json::from_str(&json).expect("deserialize Amf0Value");
1040        assert_eq!(back, value);
1041
1042        let cmd = publish_command();
1043        let json = serde_json::to_string(&cmd).expect("serialize Command");
1044        let back: Command = serde_json::from_str(&json).expect("deserialize Command");
1045        assert_eq!(back, cmd);
1046    }
1047}