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::Unsupported`] 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::Unsupported`] 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], what: &'static str) -> Result<(String, usize)> {
141    if bytes.len() < U16_LEN {
142        return Err(buffer_too_short(U16_LEN, bytes.len(), what));
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
151        .checked_add(len)
152        .ok_or(RtmpError::Malformed { what })?;
153    if bytes.len() < total {
154        return Err(buffer_too_short(total, bytes.len(), what));
155    }
156    let s = String::from_utf8(bytes[U16_LEN..total].to_vec())
157        .map_err(|_| RtmpError::Malformed { what })?;
158    Ok((s, total))
159}
160
161/// Read a `U32`-length-prefixed UTF-8 string (Long String, §2.14).
162fn read_utf8_long(bytes: &[u8], what: &'static str) -> Result<(String, usize)> {
163    if bytes.len() < U32_LEN {
164        return Err(buffer_too_short(U32_LEN, bytes.len(), what));
165    }
166    let len = u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) as usize;
167    // `len` can be up to `u32::MAX`: on a 32-bit target, `U32_LEN + len`
168    // wraps `usize` (e.g. `len == usize::MAX - 1`), which would make
169    // `bytes.len() < total` compare against a garbage-small wrapped value
170    // and misparse a length claim that should instead be rejected as too
171    // short. `checked_add` catches that instead of wrapping.
172    let total = U32_LEN
173        .checked_add(len)
174        .ok_or(RtmpError::Malformed { what })?;
175    if bytes.len() < total {
176        return Err(buffer_too_short(total, bytes.len(), what));
177    }
178    let s = String::from_utf8(bytes[U32_LEN..total].to_vec())
179        .map_err(|_| RtmpError::Malformed { what })?;
180    Ok((s, total))
181}
182
183/// Parse the key/value pairs of an Object or ECMA Array body (§2.5/§2.10),
184/// starting right after any leading count field. Terminates on an empty key
185/// followed by [`marker::OBJECT_END`] (§2.11). `depth` is the nesting depth
186/// of the *values* in this container (already incremented past the
187/// container itself by the caller).
188fn parse_pairs(bytes: &[u8], depth: usize) -> Result<(Vec<(String, Amf0Value)>, usize)> {
189    let mut consumed = 0;
190    let mut pairs = Vec::new();
191    loop {
192        let (key, key_len) = read_utf8_short(&bytes[consumed..], "amf0 object key")?;
193        let after_key = consumed + key_len;
194        if key.is_empty() {
195            if bytes.len() < after_key + MARKER_LEN {
196                return Err(buffer_too_short(
197                    after_key + MARKER_LEN,
198                    bytes.len(),
199                    "amf0 object-end marker",
200                ));
201            }
202            if bytes[after_key] == marker::OBJECT_END {
203                return Ok((pairs, after_key + MARKER_LEN));
204            }
205        }
206        let value = parse_value(&bytes[after_key..], depth)?;
207        let value_len = value.serialized_len();
208        pairs.push((key, value));
209        consumed = after_key + value_len;
210    }
211}
212
213/// Parse one AMF0 value (marker + body) from the front of `bytes`, ignoring
214/// any surplus trailing bytes. `depth` counts container nesting already
215/// entered (0 at the top level); checked *before* descending into a nested
216/// Object/ECMA-Array/Strict-Array so recursion is bounded by
217/// [`MAX_AMF0_DEPTH`] regardless of how deeply the input is (adversarially)
218/// nested.
219fn parse_value(bytes: &[u8], depth: usize) -> Result<Amf0Value> {
220    if bytes.is_empty() {
221        return Err(buffer_too_short(MARKER_LEN, 0, "amf0 value marker"));
222    }
223    let body = &bytes[MARKER_LEN..];
224    match bytes[0] {
225        marker::NUMBER => {
226            if body.len() < NUMBER_LEN {
227                return Err(buffer_too_short(NUMBER_LEN, body.len(), "amf0 number"));
228            }
229            let mut b = [0u8; NUMBER_LEN];
230            b.copy_from_slice(&body[..NUMBER_LEN]);
231            Ok(Amf0Value::Number(f64::from_be_bytes(b)))
232        }
233        marker::BOOLEAN => {
234            if body.is_empty() {
235                return Err(buffer_too_short(BOOLEAN_LEN, 0, "amf0 boolean"));
236            }
237            Ok(Amf0Value::Boolean(body[0] != 0))
238        }
239        marker::STRING => {
240            let (s, _) = read_utf8_short(body, "amf0 string")?;
241            Ok(Amf0Value::String(s))
242        }
243        marker::OBJECT => {
244            if depth >= MAX_AMF0_DEPTH {
245                return Err(RtmpError::Unsupported {
246                    what: "amf0 nesting depth exceeded",
247                });
248            }
249            let (pairs, _) = parse_pairs(body, depth + 1)?;
250            Ok(Amf0Value::Object(pairs))
251        }
252        marker::NULL => Ok(Amf0Value::Null),
253        marker::UNDEFINED => Ok(Amf0Value::Undefined),
254        marker::ECMA_ARRAY => {
255            if depth >= MAX_AMF0_DEPTH {
256                return Err(RtmpError::Unsupported {
257                    what: "amf0 nesting depth exceeded",
258                });
259            }
260            if body.len() < U32_LEN {
261                return Err(buffer_too_short(
262                    U32_LEN,
263                    body.len(),
264                    "amf0 ecma array count",
265                ));
266            }
267            // The associative-count is informational only (§2.10); the
268            // object-end terminator is authoritative, so it is read and
269            // discarded rather than cross-checked against the parsed pair
270            // count.
271            let (pairs, _) = parse_pairs(&body[U32_LEN..], depth + 1)?;
272            Ok(Amf0Value::EcmaArray(pairs))
273        }
274        marker::STRICT_ARRAY => {
275            if depth >= MAX_AMF0_DEPTH {
276                return Err(RtmpError::Unsupported {
277                    what: "amf0 nesting depth exceeded",
278                });
279            }
280            if body.len() < U32_LEN {
281                return Err(buffer_too_short(
282                    U32_LEN,
283                    body.len(),
284                    "amf0 strict array count",
285                ));
286            }
287            let count = u32::from_be_bytes([body[0], body[1], body[2], body[3]]);
288            let mut rest = &body[U32_LEN..];
289            let mut values = Vec::new();
290            for _ in 0..count {
291                let value = parse_value(rest, depth + 1)?;
292                let consumed = value.serialized_len();
293                values.push(value);
294                rest = &rest[consumed..];
295            }
296            Ok(Amf0Value::StrictArray(values))
297        }
298        marker::DATE => {
299            if body.len() < NUMBER_LEN + DATE_RESERVED_LEN {
300                return Err(buffer_too_short(
301                    NUMBER_LEN + DATE_RESERVED_LEN,
302                    body.len(),
303                    "amf0 date",
304                ));
305            }
306            let mut b = [0u8; NUMBER_LEN];
307            b.copy_from_slice(&body[..NUMBER_LEN]);
308            let tz = u16::from_be_bytes([body[NUMBER_LEN], body[NUMBER_LEN + 1]]);
309            if tz != 0 {
310                return Err(RtmpError::Malformed {
311                    what: "amf0 date reserved time zone (must be 0x0000)",
312                });
313            }
314            Ok(Amf0Value::Date(f64::from_be_bytes(b)))
315        }
316        marker::LONG_STRING => {
317            let (s, _) = read_utf8_long(body, "amf0 long string")?;
318            Ok(Amf0Value::LongString(s))
319        }
320        _ => Err(RtmpError::Unsupported {
321            what: "amf0 value marker (reserved, legacy, or amf3-switch)",
322        }),
323    }
324}
325
326fn pairs_body_len(pairs: &[(String, Amf0Value)]) -> usize {
327    pairs
328        .iter()
329        .map(|(k, v)| U16_LEN + k.len() + v.serialized_len())
330        .sum::<usize>()
331        + OBJECT_END_LEN
332}
333
334fn write_pairs(pairs: &[(String, Amf0Value)], buf: &mut [u8]) -> Result<usize> {
335    let mut offset = 0;
336    for (k, v) in pairs {
337        let key_total = U16_LEN + k.len();
338        if buf.len() < offset + key_total {
339            return Err(buffer_too_short(
340                offset + key_total,
341                buf.len(),
342                "amf0 object key output",
343            ));
344        }
345        let key_len = broadcast_common::len::fit_u16(k.len(), "amf0 object key length")?;
346        buf[offset..offset + U16_LEN].copy_from_slice(&key_len.to_be_bytes());
347        buf[offset + U16_LEN..offset + key_total].copy_from_slice(k.as_bytes());
348        offset += key_total;
349        offset += v.serialize_into(&mut buf[offset..])?;
350    }
351    if buf.len() < offset + OBJECT_END_LEN {
352        return Err(buffer_too_short(
353            offset + OBJECT_END_LEN,
354            buf.len(),
355            "amf0 object-end output",
356        ));
357    }
358    buf[offset] = 0;
359    buf[offset + 1] = 0;
360    buf[offset + 2] = marker::OBJECT_END;
361    Ok(offset + OBJECT_END_LEN)
362}
363
364impl<'a> Parse<'a> for Amf0Value {
365    type Error = RtmpError;
366
367    fn parse(bytes: &'a [u8]) -> Result<Self> {
368        parse_value(bytes, 0)
369    }
370}
371
372impl Serialize for Amf0Value {
373    type Error = RtmpError;
374
375    fn serialized_len(&self) -> usize {
376        MARKER_LEN
377            + match self {
378                Amf0Value::Number(_) | Amf0Value::Date(_) => NUMBER_LEN,
379                Amf0Value::Boolean(_) => BOOLEAN_LEN,
380                Amf0Value::String(s) => U16_LEN + s.len(),
381                Amf0Value::LongString(s) => U32_LEN + s.len(),
382                Amf0Value::Object(pairs) => pairs_body_len(pairs),
383                Amf0Value::Null | Amf0Value::Undefined => 0,
384                Amf0Value::EcmaArray(pairs) => U32_LEN + pairs_body_len(pairs),
385                Amf0Value::StrictArray(values) => {
386                    U32_LEN + values.iter().map(Serialize::serialized_len).sum::<usize>()
387                }
388            }
389            + match self {
390                Amf0Value::Date(_) => DATE_RESERVED_LEN,
391                _ => 0,
392            }
393    }
394
395    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
396        let written = self.serialized_len();
397        if buf.len() < written {
398            return Err(buffer_too_short(written, buf.len(), "amf0 value output"));
399        }
400        let (marker_byte, body) = buf[..written].split_at_mut(MARKER_LEN);
401        match self {
402            Amf0Value::Number(v) => {
403                marker_byte[0] = marker::NUMBER;
404                body[..NUMBER_LEN].copy_from_slice(&v.to_be_bytes());
405            }
406            Amf0Value::Boolean(v) => {
407                marker_byte[0] = marker::BOOLEAN;
408                body[0] = u8::from(*v);
409            }
410            Amf0Value::String(s) => {
411                if s.len() > usize::from(u16::MAX) {
412                    return Err(RtmpError::Unsupported {
413                        what: "amf0 string exceeds u16 length (use long string)",
414                    });
415                }
416                marker_byte[0] = marker::STRING;
417                body[..U16_LEN].copy_from_slice(&(s.len() as u16).to_be_bytes());
418                body[U16_LEN..].copy_from_slice(s.as_bytes());
419            }
420            Amf0Value::LongString(s) => {
421                marker_byte[0] = marker::LONG_STRING;
422                let len = broadcast_common::len::fit_u32(s.len(), "amf0 long string length")?;
423                body[..U32_LEN].copy_from_slice(&len.to_be_bytes());
424                body[U32_LEN..].copy_from_slice(s.as_bytes());
425            }
426            Amf0Value::Object(pairs) => {
427                marker_byte[0] = marker::OBJECT;
428                write_pairs(pairs, body)?;
429            }
430            Amf0Value::Null => marker_byte[0] = marker::NULL,
431            Amf0Value::Undefined => marker_byte[0] = marker::UNDEFINED,
432            Amf0Value::EcmaArray(pairs) => {
433                marker_byte[0] = marker::ECMA_ARRAY;
434                let count = broadcast_common::len::fit_u32(pairs.len(), "amf0 ECMA array count")?;
435                body[..U32_LEN].copy_from_slice(&count.to_be_bytes());
436                write_pairs(pairs, &mut body[U32_LEN..])?;
437            }
438            Amf0Value::StrictArray(values) => {
439                marker_byte[0] = marker::STRICT_ARRAY;
440                let count =
441                    broadcast_common::len::fit_u32(values.len(), "amf0 strict array count")?;
442                body[..U32_LEN].copy_from_slice(&count.to_be_bytes());
443                let mut offset = U32_LEN;
444                for v in values {
445                    offset += v.serialize_into(&mut body[offset..])?;
446                }
447            }
448            Amf0Value::Date(v) => {
449                marker_byte[0] = marker::DATE;
450                body[..NUMBER_LEN].copy_from_slice(&v.to_be_bytes());
451                body[NUMBER_LEN..NUMBER_LEN + DATE_RESERVED_LEN].copy_from_slice(&[0, 0]);
452            }
453        }
454        Ok(written)
455    }
456}
457
458/// An RTMP Command Message body (§7.1.1): `name` (AMF0 String) + AMF0
459/// `transaction_id` (AMF0 Number) + zero or more argument values (typically
460/// a Command Object, then optional trailing arguments) — see private/specs-verified/rtmp/rtmp-runtime/rtmp.md
461/// §8.2's closing note and §6.1 (Command Message).
462///
463/// This is the message-body-level container: unlike [`Amf0Value`] it is not
464/// itself a single AMF0 `value-type`, so it uses inherent `parse`/`to_body`
465/// methods rather than the [`Parse`]/[`Serialize`] traits.
466#[derive(Debug, Clone, PartialEq)]
467#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
468pub struct Command {
469    /// The command name, e.g. `"connect"`, `"createStream"`, `"publish"`,
470    /// `"_result"`.
471    pub name: String,
472    /// The transaction id correlating a response to its request (`0` for
473    /// commands that expect no response, e.g. `onStatus`).
474    pub transaction_id: f64,
475    /// The remaining AMF0 values in the command body, in wire order
476    /// (conventionally: Command Object, then any further arguments).
477    pub arguments: Vec<Amf0Value>,
478}
479
480impl Command {
481    /// Parse a Command Message body: AMF0 String (`name`) + AMF0 Number
482    /// (`transaction_id`) + the remaining AMF0 values (`arguments`), read
483    /// until `payload` is exhausted.
484    ///
485    /// # Errors
486    /// [`RtmpError::Malformed`] if the first value is not a String or the
487    /// second is not a Number; [`RtmpError::BufferTooShort`] /
488    /// [`RtmpError::Unsupported`] propagated from [`Amf0Value::parse`].
489    pub fn parse(payload: &[u8]) -> Result<Self> {
490        let name_value = Amf0Value::parse(payload)?;
491        let mut offset = name_value.serialized_len();
492        let name = match name_value {
493            Amf0Value::String(s) => s,
494            _ => {
495                return Err(RtmpError::Malformed {
496                    what: "rtmp command name (expected amf0 string)",
497                });
498            }
499        };
500
501        let txn_value = Amf0Value::parse(&payload[offset..])?;
502        offset += txn_value.serialized_len();
503        let transaction_id = match txn_value {
504            Amf0Value::Number(n) => n,
505            _ => {
506                return Err(RtmpError::Malformed {
507                    what: "rtmp command transaction id (expected amf0 number)",
508                });
509            }
510        };
511
512        let mut arguments = Vec::new();
513        while offset < payload.len() {
514            let value = Amf0Value::parse(&payload[offset..])?;
515            offset += value.serialized_len();
516            arguments.push(value);
517        }
518
519        Ok(Command {
520            name,
521            transaction_id,
522            arguments,
523        })
524    }
525
526    /// Serialize this command back to an AMF0 command payload: `name` +
527    /// `transaction_id` + `arguments`, in that order.
528    ///
529    /// # Errors
530    ///
531    /// [`RtmpError::FieldOverflow`] when any string, key or array exceeds the
532    /// AMF0 16/32-bit length prefix (a peer-chosen publish name echoed into an
533    /// `onStatus` description can reach this).
534    pub fn to_body(&self) -> Result<Vec<u8>> {
535        let mut out = Amf0Value::String(self.name.clone()).try_to_bytes()?;
536        out.extend(Amf0Value::Number(self.transaction_id).try_to_bytes()?);
537        for arg in &self.arguments {
538            out.extend(arg.try_to_bytes()?);
539        }
540        Ok(out)
541    }
542}
543
544/// Encode `values` in order as one AMF0 byte sequence: what a message body
545/// carrying several bare values is (`onMetaData` is a String followed by an
546/// ECMA Array, §2 of the AMF0 spec).
547///
548/// # Errors
549///
550/// [`RtmpError::FieldOverflow`] when a string, key or array exceeds its AMF0
551/// length prefix (see [`Amf0Value`]'s own serializer).
552pub fn amf0_values(values: &[Amf0Value]) -> Result<Vec<u8>> {
553    let len = values.iter().try_fold(0usize, |acc, value| {
554        acc.checked_add(value.serialized_len())
555            .ok_or(RtmpError::FieldOverflow(
556                broadcast_common::len::FieldOverflow {
557                    field: "amf0 value sequence length",
558                    value: u64::MAX,
559                    max: u64::MAX,
560                },
561            ))
562    })?;
563    let mut out = alloc::vec![0u8; len];
564    let mut written = 0usize;
565    for value in values {
566        written += value.serialize_into(&mut out[written..])?;
567    }
568    Ok(out)
569}
570
571#[cfg(test)]
572mod tests {
573    use super::*;
574
575    fn round_trip(v: &Amf0Value) {
576        let bytes = v.try_to_bytes().unwrap();
577        assert_eq!(bytes.len(), v.serialized_len());
578        let parsed = Amf0Value::parse(&bytes).expect("parse");
579        assert_eq!(&parsed, v);
580        // parse -> serialize -> byte-identical
581        assert_eq!(parsed.try_to_bytes().unwrap(), bytes);
582    }
583
584    #[test]
585    fn a_value_sequence_encodes_each_value_in_order() {
586        let values = [
587            Amf0Value::String("onMetaData".to_string()),
588            Amf0Value::EcmaArray(vec![("duration".to_string(), Amf0Value::Number(1.5))]),
589        ];
590        let body = amf0_values(&values).expect("encode");
591        let mut expected = values[0].try_to_bytes().unwrap();
592        expected.extend(values[1].try_to_bytes().unwrap());
593        assert_eq!(body, expected);
594    }
595
596    #[test]
597    fn number_round_trips() {
598        round_trip(&Amf0Value::Number(0.0));
599        round_trip(&Amf0Value::Number(-1.5));
600        round_trip(&Amf0Value::Number(1_000_000.25));
601    }
602
603    #[test]
604    fn boolean_round_trips() {
605        round_trip(&Amf0Value::Boolean(true));
606        round_trip(&Amf0Value::Boolean(false));
607    }
608
609    /// An Object key of 65 536 bytes cannot fit its 16-bit length prefix
610    /// (#1129): unfixed, `(k.len() as u16)` silently wrapped 65536 to 0
611    /// while the full key bytes were still written, misframing the object.
612    #[test]
613    fn object_oversized_key_length_errors() {
614        let key = "k".repeat(65536);
615        let value = Amf0Value::Object(vec![(key, Amf0Value::Null)]);
616        let err = value.try_to_bytes().unwrap_err();
617        assert!(
618            matches!(
619                err,
620                RtmpError::FieldOverflow(broadcast_common::len::FieldOverflow {
621                    field: "amf0 object key length",
622                    ..
623                })
624            ),
625            "expected FieldOverflow for amf0 object key length, got {err:?}"
626        );
627    }
628
629    /// The AMF0 String marker carries a 16-bit length prefix, so a longer
630    /// value is rejected (`Unsupported`, pointing at the Long String marker)
631    /// rather than written with a wrapped length.
632    #[test]
633    fn string_beyond_the_16_bit_prefix_is_rejected() {
634        let value = Amf0Value::String("x".repeat(0x1_0000));
635        let err = value.try_to_bytes().unwrap_err();
636        assert!(
637            matches!(err, RtmpError::Unsupported { .. }),
638            "expected Unsupported for a 65 536-byte string, got {err:?}"
639        );
640        let boundary = Amf0Value::String("x".repeat(usize::from(u16::MAX)));
641        round_trip(&boundary);
642    }
643
644    /// The boundary: exactly 65 535 bytes (u16::MAX) still round-trips.
645    #[test]
646    fn object_max_key_length_round_trips() {
647        let key = "k".repeat(65535);
648        round_trip(&Amf0Value::Object(vec![(key, Amf0Value::Null)]));
649    }
650
651    #[test]
652    fn string_round_trips_including_empty_and_multibyte() {
653        round_trip(&Amf0Value::String(String::new()));
654        round_trip(&Amf0Value::String("live".to_string()));
655        round_trip(&Amf0Value::String("héllo wörld 日本語".to_string()));
656    }
657
658    #[test]
659    fn null_and_undefined_round_trip() {
660        round_trip(&Amf0Value::Null);
661        round_trip(&Amf0Value::Undefined);
662    }
663
664    #[test]
665    fn date_round_trips() {
666        round_trip(&Amf0Value::Date(1_700_000_000_000.0));
667    }
668
669    #[test]
670    fn long_string_round_trips() {
671        round_trip(&Amf0Value::LongString("x".repeat(70_000)));
672    }
673
674    #[test]
675    fn object_round_trips_including_nested_object() {
676        round_trip(&Amf0Value::Object(vec![]));
677        round_trip(&Amf0Value::Object(vec![
678            ("app".to_string(), Amf0Value::String("live".to_string())),
679            ("audioSampleRate".to_string(), Amf0Value::Number(44100.0)),
680            ("live".to_string(), Amf0Value::Boolean(true)),
681        ]));
682        // Nested Object (the `connect` command object has string/number/
683        // boolean fields, and encoders may nest e.g. a capabilities object).
684        round_trip(&Amf0Value::Object(vec![(
685            "capabilities".to_string(),
686            Amf0Value::Object(vec![("videoCodecs".to_string(), Amf0Value::Number(252.0))]),
687        )]));
688    }
689
690    #[test]
691    fn ecma_array_round_trips() {
692        round_trip(&Amf0Value::EcmaArray(vec![]));
693        round_trip(&Amf0Value::EcmaArray(vec![
694            ("duration".to_string(), Amf0Value::Number(0.0)),
695            ("width".to_string(), Amf0Value::Number(1920.0)),
696        ]));
697    }
698
699    #[test]
700    fn strict_array_round_trips() {
701        round_trip(&Amf0Value::StrictArray(vec![]));
702        round_trip(&Amf0Value::StrictArray(vec![
703            Amf0Value::Number(1.0),
704            Amf0Value::String("two".to_string()),
705            Amf0Value::Boolean(false),
706            Amf0Value::Object(vec![("k".to_string(), Amf0Value::Null)]),
707        ]));
708    }
709
710    #[test]
711    fn ecma_array_count_is_informational_not_cross_checked() {
712        // A real encoder writes the true pair count, but §2.10 makes the
713        // object-end terminator authoritative — a lying count must still
714        // parse correctly off the terminator, not the count field.
715        let mut bytes = vec![marker::ECMA_ARRAY];
716        bytes.extend_from_slice(&999u32.to_be_bytes()); // lying count
717        bytes.extend_from_slice(&1u16.to_be_bytes());
718        bytes.extend_from_slice(b"k");
719        bytes.push(marker::NULL);
720        bytes.extend_from_slice(&[0, 0, marker::OBJECT_END]);
721
722        let parsed = Amf0Value::parse(&bytes).expect("parse");
723        assert_eq!(
724            parsed,
725            Amf0Value::EcmaArray(vec![("k".to_string(), Amf0Value::Null)])
726        );
727    }
728
729    #[test]
730    fn depth_guard_rejects_pathological_nesting_without_stack_overflow() {
731        // Build a deeply-nested Object payload by pure byte manipulation
732        // (no recursive construction/serialization of our own types), so
733        // the test itself can never stack-overflow regardless of the depth
734        // guard's correctness.
735        let mut inner = vec![marker::NULL];
736        for _ in 0..(MAX_AMF0_DEPTH * 4) {
737            let mut wrapped = vec![marker::OBJECT];
738            wrapped.extend_from_slice(&1u16.to_be_bytes());
739            wrapped.push(b'a');
740            wrapped.extend_from_slice(&inner);
741            wrapped.extend_from_slice(&[0, 0, marker::OBJECT_END]);
742            inner = wrapped;
743        }
744
745        let result = Amf0Value::parse(&inner);
746        assert!(matches!(result, Err(RtmpError::Unsupported { .. })));
747    }
748
749    #[test]
750    fn depth_guard_allows_nesting_at_the_limit() {
751        let mut inner = vec![marker::NULL];
752        for _ in 0..(MAX_AMF0_DEPTH - 1) {
753            let mut wrapped = vec![marker::OBJECT];
754            wrapped.extend_from_slice(&1u16.to_be_bytes());
755            wrapped.push(b'a');
756            wrapped.extend_from_slice(&inner);
757            wrapped.extend_from_slice(&[0, 0, marker::OBJECT_END]);
758            inner = wrapped;
759        }
760        assert!(Amf0Value::parse(&inner).is_ok());
761    }
762
763    #[test]
764    fn dropping_object_end_marker_is_rejected() {
765        // Mutation check: an Object with its `00 00 09` terminator dropped
766        // must fail to parse (BufferTooShort), not silently succeed.
767        let full = Amf0Value::Object(vec![("k".to_string(), Amf0Value::Null)])
768            .try_to_bytes()
769            .unwrap();
770        let truncated = &full[..full.len() - 3];
771        assert!(matches!(
772            Amf0Value::parse(truncated),
773            Err(RtmpError::BufferTooShort(..))
774        ));
775    }
776
777    #[test]
778    fn mis_sized_string_length_is_rejected() {
779        // Mutation check: claiming a longer string length than the buffer
780        // actually holds must fail (BufferTooShort), not read garbage.
781        let mut bytes = vec![marker::STRING];
782        bytes.extend_from_slice(&100u16.to_be_bytes()); // claims 100 bytes
783        bytes.extend_from_slice(b"short"); // only 5 present
784        assert!(matches!(
785            Amf0Value::parse(&bytes),
786            Err(RtmpError::BufferTooShort(..))
787        ));
788    }
789
790    #[test]
791    fn invalid_utf8_string_is_malformed() {
792        let mut bytes = vec![marker::STRING];
793        bytes.extend_from_slice(&2u16.to_be_bytes());
794        bytes.extend_from_slice(&[0xFF, 0xFE]); // invalid UTF-8
795        assert!(matches!(
796            Amf0Value::parse(&bytes),
797            Err(RtmpError::Malformed { .. })
798        ));
799    }
800
801    #[test]
802    fn unsupported_marker_is_rejected_not_panicking() {
803        assert!(matches!(
804            Amf0Value::parse(&[0x11]), // avmplus-object-marker (AMF3 switch)
805            Err(RtmpError::Unsupported { .. })
806        ));
807        assert!(matches!(
808            Amf0Value::parse(&[0x07]), // reference-marker
809            Err(RtmpError::Unsupported { .. })
810        ));
811    }
812
813    #[test]
814    fn date_rejects_nonzero_reserved_timezone() {
815        let mut bytes = vec![marker::DATE];
816        bytes.extend_from_slice(&0.0f64.to_be_bytes());
817        bytes.extend_from_slice(&1u16.to_be_bytes()); // reserved must be 0
818        assert!(matches!(
819            Amf0Value::parse(&bytes),
820            Err(RtmpError::Malformed { .. })
821        ));
822    }
823
824    #[test]
825    fn empty_buffer_and_truncated_marker_are_buffer_too_short_not_panics() {
826        assert!(matches!(
827            Amf0Value::parse(&[]),
828            Err(RtmpError::BufferTooShort(..))
829        ));
830        assert!(matches!(
831            Amf0Value::parse(&[marker::NUMBER, 0, 0, 0]),
832            Err(RtmpError::BufferTooShort(..))
833        ));
834    }
835
836    // ── Command ──────────────────────────────────────────────────────────
837
838    fn connect_command() -> Command {
839        Command {
840            name: "connect".to_string(),
841            transaction_id: 1.0,
842            arguments: vec![Amf0Value::Object(vec![
843                ("app".to_string(), Amf0Value::String("live".to_string())),
844                (
845                    "flashVer".to_string(),
846                    Amf0Value::String("FMLE/3.0".to_string()),
847                ),
848                (
849                    "tcUrl".to_string(),
850                    Amf0Value::String("rtmp://example.test/live".to_string()),
851                ),
852                ("fpad".to_string(), Amf0Value::Boolean(false)),
853            ])],
854        }
855    }
856
857    fn publish_command() -> Command {
858        Command {
859            name: "publish".to_string(),
860            transaction_id: 5.0,
861            arguments: vec![
862                Amf0Value::Null,
863                Amf0Value::String("stream_key_123".to_string()),
864                Amf0Value::String("live".to_string()),
865            ],
866        }
867    }
868
869    #[test]
870    fn connect_command_round_trips_byte_identically() {
871        let cmd = connect_command();
872        let bytes = cmd.to_body().unwrap();
873        let parsed = Command::parse(&bytes).expect("parse connect");
874        assert_eq!(parsed, cmd);
875        assert_eq!(parsed.to_body().unwrap(), bytes);
876    }
877
878    #[test]
879    fn publish_command_round_trips_byte_identically() {
880        let cmd = publish_command();
881        let bytes = cmd.to_body().unwrap();
882        let parsed = Command::parse(&bytes).expect("parse publish");
883        assert_eq!(parsed, cmd);
884        assert_eq!(parsed.to_body().unwrap(), bytes);
885    }
886
887    #[test]
888    fn command_name_must_be_string() {
889        let bytes = Amf0Value::Number(1.0).try_to_bytes().unwrap();
890        assert!(matches!(
891            Command::parse(&bytes),
892            Err(RtmpError::Malformed { .. })
893        ));
894    }
895
896    #[test]
897    fn command_transaction_id_must_be_number() {
898        let mut bytes = Amf0Value::String("connect".to_string())
899            .try_to_bytes()
900            .unwrap();
901        bytes.extend(
902            Amf0Value::String("not a number".to_string())
903                .try_to_bytes()
904                .unwrap(),
905        );
906        assert!(matches!(
907            Command::parse(&bytes),
908            Err(RtmpError::Malformed { .. })
909        ));
910    }
911
912    // ── 32-bit overflow guards (mutation checks) ─────────────────────────
913
914    #[test]
915    fn long_string_length_overflowing_usize_is_rejected_not_wrapped() {
916        // Mutation check: a Long String claiming `usize::MAX - 1` bytes must
917        // be rejected as too-short/malformed, not silently wrap `U32_LEN +
918        // len` into a small `total` that then compares as if the string
919        // were actually present.
920        let mut bytes = vec![marker::LONG_STRING];
921        bytes.extend_from_slice(&(u32::MAX - 1).to_be_bytes());
922        bytes.extend_from_slice(b"short");
923        let err = Amf0Value::parse(&bytes).unwrap_err();
924        assert!(matches!(
925            err,
926            RtmpError::Malformed { .. } | RtmpError::BufferTooShort(..)
927        ));
928    }
929
930    // ── serde (feature "serde") ───────────────────────────────────────────
931
932    #[cfg(feature = "serde")]
933    #[test]
934    fn amf0_value_and_command_serde_round_trip() {
935        let value = Amf0Value::Object(vec![
936            ("app".to_string(), Amf0Value::String("live".to_string())),
937            ("live".to_string(), Amf0Value::Boolean(true)),
938            ("duration".to_string(), Amf0Value::Number(0.0)),
939            (
940                "items".to_string(),
941                Amf0Value::StrictArray(vec![Amf0Value::Null, Amf0Value::Undefined]),
942            ),
943        ]);
944        let json = serde_json::to_string(&value).expect("serialize Amf0Value");
945        let back: Amf0Value = serde_json::from_str(&json).expect("deserialize Amf0Value");
946        assert_eq!(back, value);
947
948        let cmd = publish_command();
949        let json = serde_json::to_string(&cmd).expect("serialize Command");
950        let back: Command = serde_json::from_str(&json).expect("deserialize Command");
951        assert_eq!(back, cmd);
952    }
953}