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