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_core::error::BufferTooShort;
38use broadcast_core::wire::Reader;
39use broadcast_core::{ParseWith, Serialize};
40
41use crate::RtmpError;
42use alloc::string::String;
43use alloc::vec::Vec;
44
45type Result<T> = core::result::Result<T, RtmpError>;
46
47/// AMF0 type markers (`[AMF0]` §2.1, private/specs-verified/rtmp/rtmp-runtime/rtmp.md §8.1) — 1 byte.
48pub mod marker {
49    /// Number (§2.2): `DOUBLE`, 8-byte big-endian IEEE-754.
50    pub const NUMBER: u8 = 0x00;
51    /// Boolean (§2.3): 1 byte, `0` = false, nonzero = true.
52    pub const BOOLEAN: u8 = 0x01;
53    /// String (§2.4): `U16` length + UTF-8 bytes.
54    pub const STRING: u8 = 0x02;
55    /// Object (§2.5): key/value pairs terminated by [`OBJECT_END`].
56    pub const OBJECT: u8 = 0x03;
57    /// null (§2.7): no payload.
58    pub const NULL: u8 = 0x05;
59    /// undefined (§2.8): no payload.
60    pub const UNDEFINED: u8 = 0x06;
61    /// ECMA Array (§2.10): `U32` associative-count + key/value pairs
62    /// terminated by [`OBJECT_END`].
63    pub const ECMA_ARRAY: u8 = 0x08;
64    /// Object End (§2.11): always preceded by an empty (`U16` = 0) key — the
65    /// 3-byte sequence `00 00 09`.
66    pub const OBJECT_END: u8 = 0x09;
67    /// Strict Array (§2.12): `U32` count + that many values, ordinal only.
68    pub const STRICT_ARRAY: u8 = 0x0A;
69    /// Date (§2.13): `DOUBLE` (ms since Unix epoch, UTC) + reserved `S16`
70    /// time zone (MUST be `0x0000`).
71    pub const DATE: u8 = 0x0B;
72    /// Long String (§2.14): `U32` length + UTF-8 bytes, for strings over
73    /// 65535 bytes.
74    pub const LONG_STRING: u8 = 0x0C;
75}
76
77/// The two bounds AMF0 decoding needs, both chosen by the caller: the crate supplies neither.
78///
79/// `max_depth` bounds container nesting (Object/ECMA Array/Strict Array) so a pathologically
80/// nested input returns [`RtmpError::Amf0DepthExceeded`] instead of overflowing the native call
81/// stack; the guard is checked on entering each nested container. `max_values` bounds *width*:
82/// millions of one-byte nulls inside a Strict Array, or three-byte empty-key pairs inside an
83/// Object, otherwise expand into millions of `Amf0Value`s from a single message; a decode past it
84/// returns [`RtmpError::Amf0TooManyValues`].
85#[derive(Debug, Clone, Copy, PartialEq, Eq)]
86#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
87pub struct Amf0Limits {
88    /// Deepest container nesting a decode descends into.
89    pub max_depth: usize,
90    /// Most values one byte sequence may decode into, at any nesting level.
91    pub max_values: usize,
92}
93
94/// The running value count of one decode, with the limits it is held to.
95pub(crate) struct Budget {
96    count: usize,
97    limits: Amf0Limits,
98}
99
100impl Budget {
101    pub(crate) fn new(limits: Amf0Limits) -> Self {
102        Budget { count: 0, limits }
103    }
104}
105
106/// Count one more decoded value against `values`, rejecting the sequence once
107/// it passes the caller's `max_values`.
108fn count_value(values: &mut Budget) -> Result<()> {
109    let max = values.limits.max_values;
110    values.count = values
111        .count
112        .checked_add(1)
113        .ok_or(RtmpError::Amf0TooManyValues { max })?;
114    if values.count > max {
115        return Err(RtmpError::Amf0TooManyValues { max });
116    }
117    Ok(())
118}
119
120const MARKER_LEN: usize = 1;
121const NUMBER_LEN: usize = 8;
122const BOOLEAN_LEN: usize = 1;
123const U16_LEN: usize = 2;
124const U32_LEN: usize = core::mem::size_of::<u32>();
125const DATE_RESERVED_LEN: usize = 2;
126/// `00 00 09`: empty key + [`marker::OBJECT_END`].
127const OBJECT_END_LEN: usize = 3;
128/// Offset of the [`marker::OBJECT_END`] byte within that three-byte sequence.
129const OBJECT_END_MARKER_OFFSET: usize = 2;
130
131/// A single AMF0 value (`[AMF0]` §2, private/specs-verified/rtmp/rtmp-runtime/rtmp.md §8.2).
132///
133/// AMF3 (`avmplus-object-marker`, `0x11`) and the reserved/legacy markers
134/// (`movieclip`, `reference`, `unsupported`, `recordset`, `xml-document`,
135/// `typed-object`) are out of scope — see the module doc.
136///
137/// `#[non_exhaustive]`: this models a documented subset of `[AMF0]` §2's
138/// value types (see the module doc's Scope section); a future release may
139/// add a variant for one of the currently-`Unsupported` markers (e.g. a
140/// typed AMF3 bridge) without that being a breaking change for existing
141/// `match` callers.
142#[non_exhaustive]
143#[derive(Debug, Clone, PartialEq)]
144#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
145pub enum Amf0Value {
146    /// Number (§2.2).
147    Number(f64),
148    /// Boolean (§2.3).
149    Boolean(bool),
150    /// String (§2.4): `U16`-length UTF-8, at most 65535 bytes.
151    String(String),
152    /// Object (§2.5): ordered key/value pairs.
153    Object(Vec<(String, Amf0Value)>),
154    /// null (§2.7).
155    Null,
156    /// undefined (§2.8).
157    Undefined,
158    /// ECMA Array (§2.10): an associative array, encoded like Object plus a
159    /// leading (informational) `U32` count.
160    EcmaArray(Vec<(String, Amf0Value)>),
161    /// Strict Array (§2.12): an ordinal array of values.
162    StrictArray(Vec<Amf0Value>),
163    /// Date (§2.13): milliseconds since the Unix epoch, UTC.
164    Date(f64),
165    /// A Date whose reserved time-zone field is not `0x0000` (§2.13 says it SHOULD be zero, but
166    /// older encoders wrote their offset there): the value is kept with the field as the wire
167    /// carried it, so it round-trips.
168    ZonedDate {
169        /// Milliseconds since the Unix epoch.
170        millis: f64,
171        /// The reserved field, big-endian, as read.
172        time_zone: u16,
173    },
174    /// Long String (§2.14): `U32`-length UTF-8, for strings over 65535
175    /// bytes.
176    LongString(String),
177}
178
179fn buffer_too_short(need: usize, have: usize, what: &'static str) -> RtmpError {
180    RtmpError::BufferTooShort(BufferTooShort::new(need, have, what))
181}
182
183/// Read a `U16`-length-prefixed UTF-8 string from the front of `bytes`.
184/// Returns the decoded string and the total bytes consumed (`2 + len`).
185/// Used for both the String value body and Object/ECMA-Array keys, which
186/// share this exact encoding (§2.4 / §2.5).
187fn read_utf8_short(bytes: &[u8]) -> Result<(String, usize)> {
188    if bytes.len() < U16_LEN {
189        return Err(buffer_too_short(U16_LEN, bytes.len(), "AMF0 string length"));
190    }
191    let len = u16::from_be_bytes([bytes[0], bytes[1]]) as usize;
192    // `len` is at most `u16::MAX`, so `U16_LEN + len` cannot actually
193    // overflow `usize` on any real target, but guard it anyway (rather than
194    // a bare `+`) so this stays correct even on a hypothetical narrow
195    // `usize` platform, and matches the same guard on `read_utf8_long`
196    // below where the addend genuinely can overflow.
197    let total = U16_LEN.checked_add(len).ok_or(RtmpError::FieldOverflow(
198        broadcast_core::error::FieldOverflow::new(
199            "AMF0 string length",
200            u64::from(u16::MAX),
201            u64::try_from(usize::MAX).unwrap_or(u64::MAX),
202        ),
203    ))?;
204    if bytes.len() < total {
205        return Err(buffer_too_short(total, bytes.len(), "AMF0 string"));
206    }
207    let s = String::from_utf8(bytes[U16_LEN..total].to_vec())
208        .map_err(|_| RtmpError::Amf0Utf8 { what: "string" })?;
209    Ok((s, total))
210}
211
212/// Read a `U32`-length-prefixed UTF-8 string (Long String, §2.14).
213fn read_utf8_long(bytes: &[u8]) -> Result<(String, usize)> {
214    if bytes.len() < U32_LEN {
215        return Err(buffer_too_short(
216            U32_LEN,
217            bytes.len(),
218            "AMF0 long string length",
219        ));
220    }
221    let len = Reader::new(bytes).u32("AMF0 long string length")? as usize;
222    // `len` can be up to `u32::MAX`: on a 32-bit target, `U32_LEN + len`
223    // wraps `usize` (e.g. `len == usize::MAX - 1`), which would make
224    // `bytes.len() < total` compare against a garbage-small wrapped value
225    // and misparse a length claim that should instead be rejected as too
226    // short. `checked_add` catches that instead of wrapping.
227    let total = U32_LEN.checked_add(len).ok_or(RtmpError::FieldOverflow(
228        broadcast_core::error::FieldOverflow::new(
229            "AMF0 long string length",
230            u64::from(u32::MAX),
231            u64::try_from(usize::MAX).unwrap_or(u64::MAX),
232        ),
233    ))?;
234    if bytes.len() < total {
235        return Err(buffer_too_short(total, bytes.len(), "AMF0 long string"));
236    }
237    let s = String::from_utf8(bytes[U32_LEN..total].to_vec()).map_err(|_| RtmpError::Amf0Utf8 {
238        what: "long string",
239    })?;
240    Ok((s, total))
241}
242
243/// Parse the key/value pairs of an Object or ECMA Array body (§2.5/§2.10),
244/// starting right after any leading count field. Terminates on an empty key
245/// followed by [`marker::OBJECT_END`] (§2.11). `depth` is the nesting depth
246/// of the *values* in this container (already incremented past the
247/// container itself by the caller). `values` counts every value decoded so
248/// far, shared across the whole top-level sequence.
249fn parse_pairs(
250    bytes: &[u8],
251    depth: usize,
252    values: &mut Budget,
253    diagnostics: &mut Vec<broadcast_core::damage::Damage>,
254) -> Result<(Vec<(String, Amf0Value)>, usize)> {
255    let mut consumed = 0;
256    let mut pairs = Vec::new();
257    loop {
258        let (key, key_len) = read_utf8_short(&bytes[consumed..])?;
259        let after_key = consumed + key_len;
260        if key.is_empty() {
261            if bytes.len() < after_key + MARKER_LEN {
262                return Err(buffer_too_short(
263                    after_key + MARKER_LEN,
264                    bytes.len(),
265                    "amf0 object-end marker",
266                ));
267            }
268            if bytes[after_key] == marker::OBJECT_END {
269                return Ok((pairs, after_key + MARKER_LEN));
270            }
271        }
272        let (value, value_len) = parse_value(&bytes[after_key..], depth, values, diagnostics)?;
273        pairs.push((key, value));
274        consumed = after_key
275            .checked_add(value_len)
276            .ok_or(RtmpError::FieldOverflow(
277                broadcast_core::error::FieldOverflow::new(
278                    "AMF0 object pair length",
279                    u64::from(u32::try_from(after_key).unwrap_or(u32::MAX))
280                        + u64::from(u32::try_from(value_len).unwrap_or(u32::MAX)),
281                    u64::try_from(usize::MAX).unwrap_or(u64::MAX),
282                ),
283            ))?;
284    }
285}
286
287/// Parse one AMF0 value (marker + body) from the front of `bytes`, ignoring
288/// any surplus trailing bytes, and return it with the number of bytes its
289/// encoding occupied. That count comes from the parser itself, so a caller
290/// walking a sequence of values advances by what was actually read rather
291/// than by a re-serialized length, which only agrees while every encoding is
292/// canonical. `depth` counts container nesting already
293/// entered (0 at the top level); checked *before* descending into a nested
294/// Object/ECMA-Array/Strict-Array so recursion is bounded by
295/// `limits.max_depth` regardless of how deeply the input is (adversarially)
296/// nested. `values` counts every value decoded across the whole top-level
297/// sequence, bounded by `limits.max_values`. `diagnostics` collects one
298/// report per AMF0 metadata defect the value carries but that does not stop
299/// it being usable (an ECMA-Array whose declared count disagrees with its
300/// contents).
301fn parse_value(
302    bytes: &[u8],
303    depth: usize,
304    values: &mut Budget,
305    diagnostics: &mut Vec<broadcast_core::damage::Damage>,
306) -> Result<(Amf0Value, usize)> {
307    if bytes.is_empty() {
308        return Err(buffer_too_short(MARKER_LEN, 0, "amf0 value marker"));
309    }
310    count_value(values)?;
311    let body = &bytes[MARKER_LEN..];
312    match bytes[0] {
313        marker::NUMBER => {
314            if body.len() < NUMBER_LEN {
315                return Err(buffer_too_short(NUMBER_LEN, body.len(), "amf0 number"));
316            }
317            let mut b = [0u8; NUMBER_LEN];
318            b.copy_from_slice(&body[..NUMBER_LEN]);
319            Ok((
320                Amf0Value::Number(f64::from_be_bytes(b)),
321                MARKER_LEN + NUMBER_LEN,
322            ))
323        }
324        marker::BOOLEAN => {
325            if body.is_empty() {
326                return Err(buffer_too_short(BOOLEAN_LEN, 0, "amf0 boolean"));
327            }
328            Ok((Amf0Value::Boolean(body[0] != 0), MARKER_LEN + BOOLEAN_LEN))
329        }
330        marker::STRING => {
331            let (s, len) = read_utf8_short(body)?;
332            Ok((Amf0Value::String(s), MARKER_LEN + len))
333        }
334        marker::OBJECT => {
335            if depth >= values.limits.max_depth {
336                return Err(RtmpError::Amf0DepthExceeded {
337                    max: values.limits.max_depth,
338                });
339            }
340            let (pairs, len) = parse_pairs(body, depth + 1, values, diagnostics)?;
341            Ok((Amf0Value::Object(pairs), MARKER_LEN + len))
342        }
343        marker::NULL => Ok((Amf0Value::Null, MARKER_LEN)),
344        marker::UNDEFINED => Ok((Amf0Value::Undefined, MARKER_LEN)),
345        marker::ECMA_ARRAY => {
346            if depth >= values.limits.max_depth {
347                return Err(RtmpError::Amf0DepthExceeded {
348                    max: values.limits.max_depth,
349                });
350            }
351            if body.len() < U32_LEN {
352                return Err(buffer_too_short(
353                    U32_LEN,
354                    body.len(),
355                    "amf0 ecma array count",
356                ));
357            }
358            // The object-end terminator is authoritative (§2.10), so the
359            // associative count never bounds the walk. It is still a claim
360            // about the content: a non-zero count that disagrees with what
361            // the terminator closes is reported, and a zero count states
362            // nothing (several encoders write it that way).
363            let declared = Reader::new(body).u32("amf0 ecma array count")? as usize;
364            let (pairs, len) = parse_pairs(&body[U32_LEN..], depth + 1, values, diagnostics)?;
365            if declared != 0 && declared != pairs.len() {
366                diagnostics.push(crate::damage::uninterpreted("AMF0 ECMA-Array count"));
367            }
368            Ok((Amf0Value::EcmaArray(pairs), MARKER_LEN + U32_LEN + len))
369        }
370        marker::STRICT_ARRAY => {
371            if depth >= values.limits.max_depth {
372                return Err(RtmpError::Amf0DepthExceeded {
373                    max: values.limits.max_depth,
374                });
375            }
376            if body.len() < U32_LEN {
377                return Err(buffer_too_short(
378                    U32_LEN,
379                    body.len(),
380                    "amf0 strict array count",
381                ));
382            }
383            let count = Reader::new(body).u32("amf0 strict array count")?;
384            let mut rest = &body[U32_LEN..];
385            let mut elements = Vec::new();
386            for _ in 0..count {
387                let (value, consumed) = parse_value(rest, depth + 1, values, diagnostics)?;
388                elements.push(value);
389                rest = rest.get(consumed..).ok_or(RtmpError::FieldOverflow(
390                    broadcast_core::error::FieldOverflow::new(
391                        "AMF0 strict array element length",
392                        u64::try_from(consumed).unwrap_or(u64::MAX),
393                        u64::try_from(rest.len()).unwrap_or(u64::MAX),
394                    ),
395                ))?;
396            }
397            let elements_len =
398                body[U32_LEN..]
399                    .len()
400                    .checked_sub(rest.len())
401                    .ok_or(RtmpError::Malformed {
402                        what: "AMF0 strict array body",
403                    })?;
404            Ok((
405                Amf0Value::StrictArray(elements),
406                MARKER_LEN + U32_LEN + elements_len,
407            ))
408        }
409        marker::DATE => {
410            if body.len() < NUMBER_LEN + DATE_RESERVED_LEN {
411                return Err(buffer_too_short(
412                    NUMBER_LEN + DATE_RESERVED_LEN,
413                    body.len(),
414                    "amf0 date",
415                ));
416            }
417            let mut b = [0u8; NUMBER_LEN];
418            b.copy_from_slice(&body[..NUMBER_LEN]);
419            let tz = u16::from_be_bytes([body[NUMBER_LEN], body[NUMBER_LEN + 1]]);
420            let millis = f64::from_be_bytes(b);
421            let value = if tz == 0 {
422                Amf0Value::Date(millis)
423            } else {
424                diagnostics.push(crate::damage::uninterpreted("AMF0 Date time zone"));
425                Amf0Value::ZonedDate {
426                    millis,
427                    time_zone: tz,
428                }
429            };
430            Ok((value, MARKER_LEN + NUMBER_LEN + DATE_RESERVED_LEN))
431        }
432        marker::LONG_STRING => {
433            let (s, len) = read_utf8_long(body)?;
434            Ok((Amf0Value::LongString(s), MARKER_LEN + len))
435        }
436        other => Err(RtmpError::UnsupportedAmf0Marker { marker: other }),
437    }
438}
439
440/// The `FieldOverflow` for a value sequence whose total length does not fit a
441/// `usize`: the sum of real element lengths against the addressable maximum.
442fn sequence_length_overflow(so_far: usize, next: usize) -> RtmpError {
443    RtmpError::FieldOverflow(broadcast_core::error::FieldOverflow::new(
444        "amf0 value sequence length",
445        u64::from(u32::try_from(so_far).unwrap_or(u32::MAX))
446            + u64::from(u32::try_from(next).unwrap_or(u32::MAX)),
447        u64::try_from(usize::MAX).unwrap_or(u64::MAX),
448    ))
449}
450
451fn pairs_body_len(pairs: &[(String, Amf0Value)]) -> usize {
452    pairs
453        .iter()
454        .map(|(k, v)| U16_LEN + k.len() + v.serialized_len())
455        .sum::<usize>()
456        + OBJECT_END_LEN
457}
458
459fn write_pairs(pairs: &[(String, Amf0Value)], buf: &mut [u8]) -> Result<usize> {
460    let mut offset = 0;
461    for (k, v) in pairs {
462        let key_total = U16_LEN + k.len();
463        if buf.len() < offset + key_total {
464            return Err(buffer_too_short(
465                offset + key_total,
466                buf.len(),
467                "amf0 object key output",
468            ));
469        }
470        let key_len = broadcast_core::len::fit_u16(k.len(), "amf0 object key length")?;
471        buf[offset..offset + U16_LEN].copy_from_slice(&key_len.to_be_bytes());
472        buf[offset + U16_LEN..offset + key_total].copy_from_slice(k.as_bytes());
473        offset += key_total;
474        offset += v.serialize_into(&mut buf[offset..])?;
475    }
476    if buf.len() < offset + OBJECT_END_LEN {
477        return Err(buffer_too_short(
478            offset + OBJECT_END_LEN,
479            buf.len(),
480            "amf0 object-end output",
481        ));
482    }
483    buf[offset] = 0;
484    buf[offset + 1] = 0;
485    buf[offset + OBJECT_END_MARKER_OFFSET] = marker::OBJECT_END;
486    Ok(offset + OBJECT_END_LEN)
487}
488
489impl ParseWith<'_> for Amf0Value {
490    type Limits = Amf0Limits;
491    type Error = RtmpError;
492
493    /// Parse one value from `bytes` under the caller's `limits`.
494    ///
495    /// # Errors
496    /// [`RtmpError::BufferTooShort`] or [`RtmpError::Malformed`] for input that is not AMF0,
497    /// [`RtmpError::Amf0DepthExceeded`] and [`RtmpError::Amf0TooManyValues`] naming `limits`.
498    fn parse_with(bytes: &[u8], limits: &Amf0Limits) -> Result<Self> {
499        Self::parse_with_diagnostics(bytes, limits).map(|(value, _)| value)
500    }
501}
502
503impl Amf0Value {
504    /// [`Amf0Value::parse_with`], also returning every defect the value carried that did not
505    /// stop it being usable (an ECMA Array whose count disagrees with its entries, a Date with
506    /// a time-zone field), as reports the caller can publish.
507    ///
508    /// # Errors
509    /// Exactly as [`Amf0Value::parse_with`].
510    pub fn parse_with_diagnostics(
511        bytes: &[u8],
512        limits: &Amf0Limits,
513    ) -> Result<(Self, Vec<broadcast_core::damage::Damage>)> {
514        let mut values = Budget::new(*limits);
515        let mut diagnostics = Vec::new();
516        let (value, _) = parse_value(bytes, 0, &mut values, &mut diagnostics)?;
517        Ok((value, diagnostics))
518    }
519}
520
521impl Serialize for Amf0Value {
522    type Error = RtmpError;
523
524    fn serialized_len(&self) -> usize {
525        MARKER_LEN
526            + match self {
527                Amf0Value::Number(_) | Amf0Value::Date(_) | Amf0Value::ZonedDate { .. } => {
528                    NUMBER_LEN
529                }
530                Amf0Value::Boolean(_) => BOOLEAN_LEN,
531                Amf0Value::String(s) => U16_LEN + s.len(),
532                Amf0Value::LongString(s) => U32_LEN + s.len(),
533                Amf0Value::Object(pairs) => pairs_body_len(pairs),
534                Amf0Value::Null | Amf0Value::Undefined => 0,
535                Amf0Value::EcmaArray(pairs) => U32_LEN + pairs_body_len(pairs),
536                Amf0Value::StrictArray(values) => {
537                    U32_LEN + values.iter().map(Serialize::serialized_len).sum::<usize>()
538                }
539            }
540            + match self {
541                Amf0Value::Date(_) | Amf0Value::ZonedDate { .. } => DATE_RESERVED_LEN,
542                _ => 0,
543            }
544    }
545
546    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
547        let written = self.serialized_len();
548        if buf.len() < written {
549            return Err(buffer_too_short(written, buf.len(), "amf0 value output"));
550        }
551        let (marker_byte, body) = buf[..written].split_at_mut(MARKER_LEN);
552        match self {
553            Amf0Value::Number(v) => {
554                marker_byte[0] = marker::NUMBER;
555                body[..NUMBER_LEN].copy_from_slice(&v.to_be_bytes());
556            }
557            Amf0Value::Boolean(v) => {
558                marker_byte[0] = marker::BOOLEAN;
559                body[0] = u8::from(*v);
560            }
561            Amf0Value::String(s) => {
562                if s.len() > usize::from(u16::MAX) {
563                    return Err(RtmpError::Amf0StringTooLong { len: s.len() });
564                }
565                marker_byte[0] = marker::STRING;
566                body[..U16_LEN].copy_from_slice(&(s.len() as u16).to_be_bytes());
567                body[U16_LEN..].copy_from_slice(s.as_bytes());
568            }
569            Amf0Value::LongString(s) => {
570                marker_byte[0] = marker::LONG_STRING;
571                let len = broadcast_core::len::fit_u32(s.len(), "amf0 long string length")?;
572                body[..U32_LEN].copy_from_slice(&len.to_be_bytes());
573                body[U32_LEN..].copy_from_slice(s.as_bytes());
574            }
575            Amf0Value::Object(pairs) => {
576                marker_byte[0] = marker::OBJECT;
577                write_pairs(pairs, body)?;
578            }
579            Amf0Value::Null => marker_byte[0] = marker::NULL,
580            Amf0Value::Undefined => marker_byte[0] = marker::UNDEFINED,
581            Amf0Value::EcmaArray(pairs) => {
582                marker_byte[0] = marker::ECMA_ARRAY;
583                let count = broadcast_core::len::fit_u32(pairs.len(), "amf0 ECMA array count")?;
584                body[..U32_LEN].copy_from_slice(&count.to_be_bytes());
585                write_pairs(pairs, &mut body[U32_LEN..])?;
586            }
587            Amf0Value::StrictArray(values) => {
588                marker_byte[0] = marker::STRICT_ARRAY;
589                let count = broadcast_core::len::fit_u32(values.len(), "amf0 strict array count")?;
590                body[..U32_LEN].copy_from_slice(&count.to_be_bytes());
591                let mut offset = U32_LEN;
592                for v in values {
593                    offset += v.serialize_into(&mut body[offset..])?;
594                }
595            }
596            Amf0Value::Date(v) => {
597                marker_byte[0] = marker::DATE;
598                body[..NUMBER_LEN].copy_from_slice(&v.to_be_bytes());
599                body[NUMBER_LEN..NUMBER_LEN + DATE_RESERVED_LEN].copy_from_slice(&[0, 0]);
600            }
601            Amf0Value::ZonedDate { millis, time_zone } => {
602                marker_byte[0] = marker::DATE;
603                body[..NUMBER_LEN].copy_from_slice(&millis.to_be_bytes());
604                body[NUMBER_LEN..NUMBER_LEN + DATE_RESERVED_LEN]
605                    .copy_from_slice(&time_zone.to_be_bytes());
606            }
607        }
608        Ok(written)
609    }
610}
611
612/// An RTMP Command Message body (§7.1.1): `name` (AMF0 String) + AMF0
613/// `transaction_id` (AMF0 Number) + zero or more argument values (typically
614/// a Command Object, then optional trailing arguments) — see private/specs-verified/rtmp/rtmp-runtime/rtmp.md
615/// §8.2's closing note and §6.1 (Command Message).
616///
617/// This is the message-body-level container: unlike [`Amf0Value`] it is not
618/// itself a single AMF0 `value-type`, so it uses inherent `parse`/`to_body`
619/// methods rather than the [`Serialize`] trait.
620#[derive(Debug, Clone, PartialEq)]
621#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
622pub struct Command {
623    /// The command name, e.g. `"connect"`, `"createStream"`, `"publish"`,
624    /// `"_result"`.
625    pub name: String,
626    /// The transaction id correlating a response to its request (`0` for
627    /// commands that expect no response, e.g. `onStatus`).
628    pub transaction_id: f64,
629    /// The remaining AMF0 values in the command body, in wire order
630    /// (conventionally: Command Object, then any further arguments).
631    pub arguments: Vec<Amf0Value>,
632}
633
634impl ParseWith<'_> for Command {
635    type Limits = Amf0Limits;
636    type Error = RtmpError;
637
638    /// Parse a Command Message body: AMF0 String (`name`) + AMF0 Number
639    /// (`transaction_id`) + the remaining AMF0 values (`arguments`), read
640    /// until `payload` is exhausted.
641    ///
642    /// # Errors
643    /// [`RtmpError::CommandNameNotString`] if the first value is not a
644    /// String, [`RtmpError::CommandTransactionIdNotNumber`] if the second is
645    /// not a Number; the remaining variants are propagated from
646    /// [`Amf0Value::parse_with`].
647    fn parse_with(payload: &[u8], limits: &Amf0Limits) -> Result<Self> {
648        Self::parse_with_diagnostics(payload, limits).map(|(command, _)| command)
649    }
650}
651
652impl Command {
653    /// Parse a Command Message body, also returning every AMF0 metadata
654    /// defect it carried but that did not stop it being usable — the same
655    /// values [`Command::parse_with`] accepts, with the reports a caller needs to
656    /// publish them.
657    ///
658    /// # Errors
659    /// Exactly as [`Command::parse_with`].
660    pub fn parse_with_diagnostics(
661        payload: &[u8],
662        limits: &Amf0Limits,
663    ) -> Result<(Self, Vec<broadcast_core::damage::Damage>)> {
664        let mut values = Budget::new(*limits);
665        let mut diagnostics = Vec::new();
666        let (name_value, name_len) = parse_value(payload, 0, &mut values, &mut diagnostics)?;
667        let mut offset = name_len;
668        let name = match name_value {
669            Amf0Value::String(s) => s,
670            value => return Err(RtmpError::CommandNameNotString { value }),
671        };
672
673        let (txn_value, txn_len) = parse_value(
674            payload.get(offset..).unwrap_or_default(),
675            0,
676            &mut values,
677            &mut diagnostics,
678        )?;
679        offset = offset.checked_add(txn_len).ok_or(RtmpError::FieldOverflow(
680            broadcast_core::error::FieldOverflow::new(
681                "RTMP command transaction id offset",
682                u64::try_from(offset).unwrap_or(u64::MAX),
683                u64::try_from(usize::MAX).unwrap_or(u64::MAX),
684            ),
685        ))?;
686        let transaction_id = match txn_value {
687            Amf0Value::Number(n) => n,
688            value => return Err(RtmpError::CommandTransactionIdNotNumber { value }),
689        };
690
691        let mut arguments = Vec::new();
692        while offset < payload.len() {
693            let (value, len) = parse_value(&payload[offset..], 0, &mut values, &mut diagnostics)?;
694            offset = offset.checked_add(len).ok_or(RtmpError::FieldOverflow(
695                broadcast_core::error::FieldOverflow::new(
696                    "RTMP command argument offset",
697                    u64::try_from(offset).unwrap_or(u64::MAX),
698                    u64::try_from(usize::MAX).unwrap_or(u64::MAX),
699                ),
700            ))?;
701            arguments.push(value);
702        }
703
704        Ok((
705            Command {
706                name,
707                transaction_id,
708                arguments,
709            },
710            diagnostics,
711        ))
712    }
713
714    /// Serialize this command back to an AMF0 command payload: `name` +
715    /// `transaction_id` + `arguments`, in that order.
716    ///
717    /// # Errors
718    ///
719    /// [`RtmpError::FieldOverflow`] when any string, key or array exceeds the
720    /// AMF0 16/32-bit length prefix (a peer-chosen publish name echoed into an
721    /// `onStatus` description can reach this).
722    pub fn to_body(&self) -> Result<Vec<u8>> {
723        let mut out = Amf0Value::String(self.name.clone()).try_to_bytes()?;
724        out.extend(Amf0Value::Number(self.transaction_id).try_to_bytes()?);
725        for arg in &self.arguments {
726            out.extend(arg.try_to_bytes()?);
727        }
728        Ok(out)
729    }
730}
731/// Parse a sequence of AMF0 values that fill `body` under the caller's `limits`, the inverse of
732/// [`amf0_values`].
733///
734/// A script-data body is such a sequence: the handler name, then one or more
735/// values (Adobe FLV v10.1 §E.4.1).
736///
737/// # Errors
738///
739/// [`RtmpError::BufferTooShort`] when a value runs past `body`, and the limits of
740/// [`Amf0Value::parse_with`].
741///
742/// The defects the values carried that did not stop them being usable come back beside them (see
743/// [`Amf0Value::parse_with_diagnostics`]).
744pub fn amf0_parse_values_with(
745    body: &[u8],
746    limits: Amf0Limits,
747) -> Result<(Vec<Amf0Value>, Vec<broadcast_core::damage::Damage>)> {
748    let mut values_out = Vec::new();
749    let mut offset = 0usize;
750    let mut count = Budget::new(limits);
751    let mut diagnostics = Vec::new();
752    while offset < body.len() {
753        let (value, used) = parse_value(&body[offset..], 0, &mut count, &mut diagnostics)?;
754        values_out.push(value);
755        offset = offset.checked_add(used).ok_or(RtmpError::FieldOverflow(
756            broadcast_core::error::FieldOverflow::new(
757                "AMF0 value offset",
758                u64::try_from(offset).unwrap_or(u64::MAX),
759                u64::try_from(usize::MAX).unwrap_or(u64::MAX),
760            ),
761        ))?;
762    }
763    Ok((values_out, diagnostics))
764}
765
766/// Encode `values` in order as one AMF0 byte sequence: what a message body
767/// carrying several bare values is (`onMetaData` is a String followed by an
768/// ECMA Array, §2 of the AMF0 spec).
769///
770/// # Errors
771///
772/// [`RtmpError::FieldOverflow`] when a string, key or array exceeds its AMF0
773/// length prefix (see [`Amf0Value`]'s own serializer).
774pub fn amf0_values(values: &[Amf0Value]) -> Result<Vec<u8>> {
775    let len = values.iter().try_fold(0usize, |acc, value| {
776        let value_len = value.serialized_len();
777        acc.checked_add(value_len)
778            .ok_or_else(|| sequence_length_overflow(acc, value_len))
779    })?;
780    let mut out = alloc::vec![0u8; len];
781    let mut written = 0usize;
782    for value in values {
783        written += value.serialize_into(&mut out[written..])?;
784    }
785    Ok(out)
786}
787
788#[cfg(test)]
789mod tests {
790    use super::*;
791
792    const MAX_AMF0_DEPTH: usize = 32;
793    const MAX_AMF0_VALUES: usize = 4096;
794    const DEFAULT_AMF0_LIMITS: Amf0Limits = Amf0Limits {
795        max_depth: MAX_AMF0_DEPTH,
796        max_values: MAX_AMF0_VALUES,
797    };
798
799    fn parse_value_default(bytes: &[u8]) -> Result<Amf0Value> {
800        Amf0Value::parse_with(bytes, &DEFAULT_AMF0_LIMITS)
801    }
802
803    fn round_trip(v: &Amf0Value) {
804        let bytes = v.try_to_bytes().unwrap();
805        assert_eq!(bytes.len(), v.serialized_len());
806        let parsed = parse_value_default(&bytes).expect("parse");
807        assert_eq!(&parsed, v);
808        // parse -> serialize -> byte-identical
809        assert_eq!(parsed.try_to_bytes().unwrap(), bytes);
810    }
811
812    #[test]
813    fn a_value_sequence_encodes_each_value_in_order() {
814        let values = [
815            Amf0Value::String("onMetaData".to_string()),
816            Amf0Value::EcmaArray(vec![("duration".to_string(), Amf0Value::Number(1.5))]),
817        ];
818        let body = amf0_values(&values).expect("encode");
819        let mut expected = values[0].try_to_bytes().unwrap();
820        expected.extend(values[1].try_to_bytes().unwrap());
821        assert_eq!(body, expected);
822    }
823
824    #[test]
825    fn a_value_sequence_parses_back_what_it_encoded() {
826        let values = [
827            Amf0Value::String("onMetaData".to_string()),
828            Amf0Value::EcmaArray(vec![
829                ("duration".to_string(), Amf0Value::Number(1.5)),
830                ("stereo".to_string(), Amf0Value::Boolean(false)),
831            ]),
832        ];
833        let body = amf0_values(&values).expect("encode");
834        assert_eq!(
835            amf0_parse_values_with(&body, DEFAULT_AMF0_LIMITS)
836                .expect("parse")
837                .0,
838            values
839        );
840    }
841
842    #[test]
843    fn a_truncated_value_sequence_is_an_error_not_a_partial_list() {
844        let values = [Amf0Value::String("onMetaData".to_string())];
845        let mut body = amf0_values(&values).expect("encode");
846        body.pop();
847        assert!(amf0_parse_values_with(&body, DEFAULT_AMF0_LIMITS).is_err());
848    }
849
850    /// #2761: the overflow error carried `value = u64::MAX, max = u64::MAX`,
851    /// telling a caller nothing. It now carries the real current length and
852    /// the addressable maximum.
853    #[test]
854    fn a_sequence_length_overflow_reports_the_real_lengths() {
855        let err = sequence_length_overflow(6, 8);
856        let RtmpError::FieldOverflow(overflow) = err else {
857            panic!("expected FieldOverflow, got {err:?}");
858        };
859        assert_eq!(overflow.value, 14);
860        assert_eq!(
861            overflow.max,
862            u64::try_from(usize::MAX).expect("usize fits u64 on every supported target")
863        );
864    }
865
866    /// #2761: `Command::parse` advanced by each parsed value's re-serialized
867    /// length. The parser now reports what it consumed, so a value whose
868    /// encoding is not its canonical form (here AMF0 permits any non-zero
869    /// Boolean byte, and `0x02` re-serializes as `0x01`) no longer shifts the
870    /// boundary of the following argument.
871    #[test]
872    fn command_argument_boundaries_come_from_the_parse_not_a_re_derived_length() {
873        let mut payload = Amf0Value::String("connect".to_string())
874            .try_to_bytes()
875            .unwrap();
876        payload.extend(Amf0Value::Number(1.0).try_to_bytes().unwrap());
877        for i in 0..8u8 {
878            payload.extend([marker::BOOLEAN, i]);
879        }
880
881        let command = Command::parse_with(&payload, &DEFAULT_AMF0_LIMITS)
882            .expect("any boolean byte is legal AMF0");
883        assert_eq!(
884            command.arguments,
885            (0..8u8)
886                .map(|i| Amf0Value::Boolean(i != 0))
887                .collect::<Vec<_>>()
888        );
889    }
890
891    #[test]
892    fn number_round_trips() {
893        round_trip(&Amf0Value::Number(0.0));
894        round_trip(&Amf0Value::Number(-1.5));
895        round_trip(&Amf0Value::Number(1_000_000.25));
896    }
897
898    #[test]
899    fn boolean_round_trips() {
900        round_trip(&Amf0Value::Boolean(true));
901        round_trip(&Amf0Value::Boolean(false));
902    }
903
904    /// An Object key of 65 536 bytes cannot fit its 16-bit length prefix
905    /// (#1129): unfixed, `(k.len() as u16)` silently wrapped 65536 to 0
906    /// while the full key bytes were still written, misframing the object.
907    #[test]
908    fn object_oversized_key_length_errors() {
909        let key = "k".repeat(65536);
910        let value = Amf0Value::Object(vec![(key, Amf0Value::Null)]);
911        let err = value.try_to_bytes().unwrap_err();
912        assert!(
913            matches!(
914                err,
915                RtmpError::FieldOverflow(broadcast_core::error::FieldOverflow {
916                    field: "amf0 object key length",
917                    ..
918                })
919            ),
920            "expected FieldOverflow for amf0 object key length, got {err:?}"
921        );
922    }
923
924    /// The AMF0 String marker carries a 16-bit length prefix, so a longer
925    /// value is rejected rather than written with a wrapped length.
926    #[test]
927    fn string_beyond_the_16_bit_prefix_is_rejected() {
928        let value = Amf0Value::String("x".repeat(0x1_0000));
929        let err = value.try_to_bytes().unwrap_err();
930        assert!(
931            matches!(err, RtmpError::Amf0StringTooLong { len } if len == 0x1_0000),
932            "expected Amf0StringTooLong for a 65 536-byte string, got {err:?}"
933        );
934        let boundary = Amf0Value::String("x".repeat(usize::from(u16::MAX)));
935        round_trip(&boundary);
936    }
937
938    /// The boundary: exactly 65 535 bytes (u16::MAX) still round-trips.
939    #[test]
940    fn object_max_key_length_round_trips() {
941        let key = "k".repeat(65535);
942        round_trip(&Amf0Value::Object(vec![(key, Amf0Value::Null)]));
943    }
944
945    #[test]
946    fn string_round_trips_including_empty_and_multibyte() {
947        round_trip(&Amf0Value::String(String::new()));
948        round_trip(&Amf0Value::String("live".to_string()));
949        round_trip(&Amf0Value::String("héllo wörld 日本語".to_string()));
950    }
951
952    #[test]
953    fn null_and_undefined_round_trip() {
954        round_trip(&Amf0Value::Null);
955        round_trip(&Amf0Value::Undefined);
956    }
957
958    #[test]
959    fn date_round_trips() {
960        round_trip(&Amf0Value::Date(1_700_000_000_000.0));
961    }
962
963    #[test]
964    fn long_string_round_trips() {
965        round_trip(&Amf0Value::LongString("x".repeat(70_000)));
966    }
967
968    #[test]
969    fn object_round_trips_including_nested_object() {
970        round_trip(&Amf0Value::Object(vec![]));
971        round_trip(&Amf0Value::Object(vec![
972            ("app".to_string(), Amf0Value::String("live".to_string())),
973            ("audioSampleRate".to_string(), Amf0Value::Number(44100.0)),
974            ("live".to_string(), Amf0Value::Boolean(true)),
975        ]));
976        // Nested Object (the `connect` command object has string/number/
977        // boolean fields, and encoders may nest e.g. a capabilities object).
978        round_trip(&Amf0Value::Object(vec![(
979            "capabilities".to_string(),
980            Amf0Value::Object(vec![("videoCodecs".to_string(), Amf0Value::Number(252.0))]),
981        )]));
982    }
983
984    #[test]
985    fn ecma_array_round_trips() {
986        round_trip(&Amf0Value::EcmaArray(vec![]));
987        round_trip(&Amf0Value::EcmaArray(vec![
988            ("duration".to_string(), Amf0Value::Number(0.0)),
989            ("width".to_string(), Amf0Value::Number(1920.0)),
990        ]));
991    }
992
993    #[test]
994    fn strict_array_round_trips() {
995        round_trip(&Amf0Value::StrictArray(vec![]));
996        round_trip(&Amf0Value::StrictArray(vec![
997            Amf0Value::Number(1.0),
998            Amf0Value::String("two".to_string()),
999            Amf0Value::Boolean(false),
1000            Amf0Value::Object(vec![("k".to_string(), Amf0Value::Null)]),
1001        ]));
1002    }
1003
1004    #[test]
1005    fn ecma_array_count_is_informational_not_cross_checked() {
1006        // A real encoder writes the true pair count, but §2.10 makes the
1007        // object-end terminator authoritative — a lying count must still
1008        // parse correctly off the terminator, not the count field.
1009        let mut bytes = vec![marker::ECMA_ARRAY];
1010        bytes.extend_from_slice(&999u32.to_be_bytes()); // lying count
1011        bytes.extend_from_slice(&1u16.to_be_bytes());
1012        bytes.extend_from_slice(b"k");
1013        bytes.push(marker::NULL);
1014        bytes.extend_from_slice(&[0, 0, marker::OBJECT_END]);
1015
1016        let parsed = parse_value_default(&bytes).expect("parse");
1017        assert_eq!(
1018            parsed,
1019            Amf0Value::EcmaArray(vec![("k".to_string(), Amf0Value::Null)])
1020        );
1021    }
1022
1023    #[test]
1024    fn depth_guard_rejects_pathological_nesting_without_stack_overflow() {
1025        // Build a deeply-nested Object payload by pure byte manipulation
1026        // (no recursive construction/serialization of our own types), so
1027        // the test itself can never stack-overflow regardless of the depth
1028        // guard's correctness.
1029        let mut inner = vec![marker::NULL];
1030        for _ in 0..(MAX_AMF0_DEPTH * 4) {
1031            let mut wrapped = vec![marker::OBJECT];
1032            wrapped.extend_from_slice(&1u16.to_be_bytes());
1033            wrapped.push(b'a');
1034            wrapped.extend_from_slice(&inner);
1035            wrapped.extend_from_slice(&[0, 0, marker::OBJECT_END]);
1036            inner = wrapped;
1037        }
1038
1039        let result = parse_value_default(&inner);
1040        assert!(matches!(
1041            result,
1042            Err(RtmpError::Amf0DepthExceeded { max }) if max == MAX_AMF0_DEPTH
1043        ));
1044    }
1045
1046    #[test]
1047    fn depth_guard_allows_nesting_at_the_limit() {
1048        let mut inner = vec![marker::NULL];
1049        for _ in 0..(MAX_AMF0_DEPTH - 1) {
1050            let mut wrapped = vec![marker::OBJECT];
1051            wrapped.extend_from_slice(&1u16.to_be_bytes());
1052            wrapped.push(b'a');
1053            wrapped.extend_from_slice(&inner);
1054            wrapped.extend_from_slice(&[0, 0, marker::OBJECT_END]);
1055            inner = wrapped;
1056        }
1057        assert!(parse_value_default(&inner).is_ok());
1058    }
1059
1060    /// #2813: width was unbounded — an 8 MiB Strict Array of one-byte nulls
1061    /// decoded into millions of `Amf0Value`s, and an Object of three-byte
1062    /// empty-key pairs into millions of `(String, Amf0Value)` pairs. The
1063    /// value counter now rejects the element that crosses
1064    /// `limits.max_values`.
1065    #[test]
1066    fn value_count_guard_rejects_wide_containers() {
1067        let count = u32::try_from(MAX_AMF0_VALUES + 1).expect("limit fits u32");
1068        let mut bytes = vec![marker::STRICT_ARRAY];
1069        bytes.extend_from_slice(&count.to_be_bytes());
1070        bytes.extend(core::iter::repeat_n(marker::NULL, MAX_AMF0_VALUES + 1));
1071
1072        let result = parse_value_default(&bytes);
1073        assert!(matches!(
1074            result,
1075            Err(RtmpError::Amf0TooManyValues { max }) if max == MAX_AMF0_VALUES
1076        ));
1077    }
1078
1079    #[test]
1080    fn value_count_guard_allows_a_container_at_the_limit() {
1081        let count = u32::try_from(MAX_AMF0_VALUES - 1).expect("limit fits u32");
1082        let mut bytes = vec![marker::STRICT_ARRAY];
1083        bytes.extend_from_slice(&count.to_be_bytes());
1084        bytes.extend(core::iter::repeat_n(marker::NULL, MAX_AMF0_VALUES - 1));
1085
1086        let parsed =
1087            parse_value_default(&bytes).expect("the array itself plus its elements is the limit");
1088        assert_eq!(
1089            parsed,
1090            Amf0Value::StrictArray(vec![Amf0Value::Null; MAX_AMF0_VALUES - 1])
1091        );
1092    }
1093
1094    /// #2813: the counter spans the whole top-level value sequence, so a
1095    /// Command Message cannot dodge it by spreading its values over several
1096    /// arguments.
1097    #[test]
1098    fn command_parse_counts_values_across_every_argument() {
1099        let mut payload = Amf0Value::String("connect".to_string())
1100            .try_to_bytes()
1101            .expect("encode name");
1102        payload.extend(
1103            Amf0Value::Number(1.0)
1104                .try_to_bytes()
1105                .expect("encode transaction id"),
1106        );
1107        payload.extend(core::iter::repeat_n(marker::NULL, MAX_AMF0_VALUES));
1108
1109        let result = Command::parse_with(&payload, &DEFAULT_AMF0_LIMITS);
1110        assert!(matches!(
1111            result,
1112            Err(RtmpError::Amf0TooManyValues { max }) if max == MAX_AMF0_VALUES
1113        ));
1114    }
1115
1116    #[test]
1117    fn dropping_object_end_marker_is_rejected() {
1118        // Mutation check: an Object with its `00 00 09` terminator dropped
1119        // must fail to parse (BufferTooShort), not silently succeed.
1120        let full = Amf0Value::Object(vec![("k".to_string(), Amf0Value::Null)])
1121            .try_to_bytes()
1122            .unwrap();
1123        let truncated = &full[..full.len() - 3];
1124        assert!(matches!(
1125            parse_value_default(truncated),
1126            Err(RtmpError::BufferTooShort(..))
1127        ));
1128    }
1129
1130    #[test]
1131    fn mis_sized_string_length_is_rejected() {
1132        // Mutation check: claiming a longer string length than the buffer
1133        // actually holds must fail (BufferTooShort), not read garbage.
1134        let mut bytes = vec![marker::STRING];
1135        bytes.extend_from_slice(&100u16.to_be_bytes()); // claims 100 bytes
1136        bytes.extend_from_slice(b"short"); // only 5 present
1137        assert!(matches!(
1138            parse_value_default(&bytes),
1139            Err(RtmpError::BufferTooShort(..))
1140        ));
1141    }
1142
1143    #[test]
1144    fn invalid_utf8_string_is_malformed() {
1145        let mut bytes = vec![marker::STRING];
1146        bytes.extend_from_slice(&2u16.to_be_bytes());
1147        bytes.extend_from_slice(&[0xFF, 0xFE]); // invalid UTF-8
1148        assert!(matches!(
1149            parse_value_default(&bytes),
1150            Err(RtmpError::Amf0Utf8 { what: "string" })
1151        ));
1152    }
1153
1154    #[test]
1155    fn unsupported_marker_is_rejected_not_panicking() {
1156        assert!(matches!(
1157            parse_value_default(&[0x11]), // avmplus-object-marker (AMF3 switch)
1158            Err(RtmpError::UnsupportedAmf0Marker { marker: 0x11 })
1159        ));
1160        assert!(matches!(
1161            parse_value_default(&[0x07]), // reference-marker
1162            Err(RtmpError::UnsupportedAmf0Marker { marker: 0x07 })
1163        ));
1164    }
1165
1166    #[test]
1167    fn date_with_a_nonzero_reserved_timezone_is_kept_reported_and_round_trips() {
1168        let mut bytes = vec![marker::DATE];
1169        bytes.extend_from_slice(&1.0e12f64.to_be_bytes());
1170        bytes.extend_from_slice(&0xFFC4u16.to_be_bytes());
1171        let (value, diagnostics) =
1172            Amf0Value::parse_with_diagnostics(&bytes, &DEFAULT_AMF0_LIMITS).unwrap();
1173        assert_eq!(
1174            value,
1175            Amf0Value::ZonedDate {
1176                millis: 1.0e12,
1177                time_zone: 0xFFC4
1178            }
1179        );
1180        assert_eq!(diagnostics.len(), 1);
1181        assert_eq!(value.try_to_bytes().unwrap(), bytes);
1182    }
1183
1184    #[test]
1185    fn a_command_carrying_a_zoned_date_still_parses_and_reports() {
1186        let mut payload = Amf0Value::String("onStatus".into()).try_to_bytes().unwrap();
1187        payload.extend(Amf0Value::Number(0.0).try_to_bytes().unwrap());
1188        payload.push(marker::DATE);
1189        payload.extend_from_slice(&2.0e12f64.to_be_bytes());
1190        payload.extend_from_slice(&60u16.to_be_bytes());
1191        let (command, diagnostics) =
1192            Command::parse_with_diagnostics(&payload, &DEFAULT_AMF0_LIMITS).unwrap();
1193        assert_eq!(command.arguments.len(), 1);
1194        assert_eq!(diagnostics.len(), 1);
1195    }
1196
1197    #[test]
1198    fn an_ecma_array_count_mismatch_in_a_value_sequence_is_returned_not_dropped() {
1199        let mut body = Amf0Value::String("onMetaData".into())
1200            .try_to_bytes()
1201            .unwrap();
1202        body.push(marker::ECMA_ARRAY);
1203        body.extend_from_slice(&5u32.to_be_bytes());
1204        body.extend_from_slice(&[0, 1, b'k']);
1205        body.extend(Amf0Value::Number(1.0).try_to_bytes().unwrap());
1206        body.extend_from_slice(&[0, 0, marker::OBJECT_END]);
1207        let (values, diagnostics) = amf0_parse_values_with(&body, DEFAULT_AMF0_LIMITS).unwrap();
1208        assert_eq!(values.len(), 2);
1209        assert_eq!(diagnostics.len(), 1);
1210    }
1211
1212    #[test]
1213    fn empty_buffer_and_truncated_marker_are_buffer_too_short_not_panics() {
1214        assert!(matches!(
1215            parse_value_default(&[]),
1216            Err(RtmpError::BufferTooShort(..))
1217        ));
1218        assert!(matches!(
1219            parse_value_default(&[marker::NUMBER, 0, 0, 0]),
1220            Err(RtmpError::BufferTooShort(..))
1221        ));
1222    }
1223
1224    // ── Command ──────────────────────────────────────────────────────────
1225
1226    fn connect_command() -> Command {
1227        Command {
1228            name: "connect".to_string(),
1229            transaction_id: 1.0,
1230            arguments: vec![Amf0Value::Object(vec![
1231                ("app".to_string(), Amf0Value::String("live".to_string())),
1232                (
1233                    "flashVer".to_string(),
1234                    Amf0Value::String("FMLE/3.0".to_string()),
1235                ),
1236                (
1237                    "tcUrl".to_string(),
1238                    Amf0Value::String("rtmp://example.test/live".to_string()),
1239                ),
1240                ("fpad".to_string(), Amf0Value::Boolean(false)),
1241            ])],
1242        }
1243    }
1244
1245    fn publish_command() -> Command {
1246        Command {
1247            name: "publish".to_string(),
1248            transaction_id: 5.0,
1249            arguments: vec![
1250                Amf0Value::Null,
1251                Amf0Value::String("stream_key_123".to_string()),
1252                Amf0Value::String("live".to_string()),
1253            ],
1254        }
1255    }
1256
1257    #[test]
1258    fn connect_command_round_trips_byte_identically() {
1259        let cmd = connect_command();
1260        let bytes = cmd.to_body().unwrap();
1261        let parsed = Command::parse_with(&bytes, &DEFAULT_AMF0_LIMITS).expect("parse connect");
1262        assert_eq!(parsed, cmd);
1263        assert_eq!(parsed.to_body().unwrap(), bytes);
1264    }
1265
1266    #[test]
1267    fn publish_command_round_trips_byte_identically() {
1268        let cmd = publish_command();
1269        let bytes = cmd.to_body().unwrap();
1270        let parsed = Command::parse_with(&bytes, &DEFAULT_AMF0_LIMITS).expect("parse publish");
1271        assert_eq!(parsed, cmd);
1272        assert_eq!(parsed.to_body().unwrap(), bytes);
1273    }
1274
1275    #[test]
1276    fn command_name_must_be_string() {
1277        let bytes = Amf0Value::Number(1.0).try_to_bytes().unwrap();
1278        assert!(matches!(
1279            Command::parse_with(&bytes, &DEFAULT_AMF0_LIMITS),
1280            Err(RtmpError::CommandNameNotString { .. })
1281        ));
1282    }
1283
1284    #[test]
1285    fn command_transaction_id_must_be_number() {
1286        let mut bytes = Amf0Value::String("connect".to_string())
1287            .try_to_bytes()
1288            .unwrap();
1289        bytes.extend(
1290            Amf0Value::String("not a number".to_string())
1291                .try_to_bytes()
1292                .unwrap(),
1293        );
1294        assert!(matches!(
1295            Command::parse_with(&bytes, &DEFAULT_AMF0_LIMITS),
1296            Err(RtmpError::CommandTransactionIdNotNumber { .. })
1297        ));
1298    }
1299
1300    // ── 32-bit overflow guards (mutation checks) ─────────────────────────
1301
1302    #[test]
1303    fn long_string_length_overflowing_usize_is_rejected_not_wrapped() {
1304        // Mutation check: a Long String claiming `usize::MAX - 1` bytes must
1305        // be rejected as too-short/malformed, not silently wrap `U32_LEN +
1306        // len` into a small `total` that then compares as if the string
1307        // were actually present.
1308        let mut bytes = vec![marker::LONG_STRING];
1309        bytes.extend_from_slice(&(u32::MAX - 1).to_be_bytes());
1310        bytes.extend_from_slice(b"short");
1311        let err = parse_value_default(&bytes).unwrap_err();
1312        assert!(matches!(
1313            err,
1314            RtmpError::Malformed { .. } | RtmpError::BufferTooShort(..)
1315        ));
1316    }
1317
1318    // ── serde (feature "serde") ───────────────────────────────────────────
1319
1320    #[cfg(feature = "serde")]
1321    #[test]
1322    fn amf0_value_and_command_serde_round_trip() {
1323        let value = Amf0Value::Object(vec![
1324            ("app".to_string(), Amf0Value::String("live".to_string())),
1325            ("live".to_string(), Amf0Value::Boolean(true)),
1326            ("duration".to_string(), Amf0Value::Number(0.0)),
1327            (
1328                "items".to_string(),
1329                Amf0Value::StrictArray(vec![Amf0Value::Null, Amf0Value::Undefined]),
1330            ),
1331        ]);
1332        let json = serde_json::to_string(&value).expect("serialize Amf0Value");
1333        let back: Amf0Value = serde_json::from_str(&json).expect("deserialize Amf0Value");
1334        assert_eq!(back, value);
1335
1336        let cmd = publish_command();
1337        let json = serde_json::to_string(&cmd).expect("serialize Command");
1338        let back: Command = serde_json::from_str(&json).expect("deserialize Command");
1339        assert_eq!(back, cmd);
1340    }
1341
1342    /// Offsets through nested containers (an object holding an ECMA array
1343    /// holding a >65535-byte Long String, then a Date) are exact in both
1344    /// directions.
1345    #[test]
1346    fn nested_container_offsets_pin_parse_and_serialize() {
1347        let long = "L".repeat(70_000);
1348        let nested = Amf0Value::StrictArray(vec![
1349            Amf0Value::Object(vec![
1350                ("a".to_string(), Amf0Value::Number(1.5)),
1351                (
1352                    "b".to_string(),
1353                    Amf0Value::EcmaArray(vec![
1354                        ("x".to_string(), Amf0Value::LongString(long)),
1355                        ("y".to_string(), Amf0Value::Null),
1356                    ]),
1357                ),
1358            ]),
1359            Amf0Value::Date(1.0e12),
1360            Amf0Value::Boolean(true),
1361            Amf0Value::Undefined,
1362        ]);
1363        let bytes = nested.try_to_bytes().expect("serialize");
1364        assert_eq!(bytes.len(), nested.serialized_len());
1365
1366        assert_eq!(
1367            &bytes[..10],
1368            &[
1369                marker::STRICT_ARRAY,
1370                0,
1371                0,
1372                0,
1373                4,
1374                marker::OBJECT,
1375                0,
1376                1,
1377                b'a',
1378                marker::NUMBER
1379            ]
1380        );
1381        assert_eq!(&bytes[10..18], &1.5f64.to_be_bytes());
1382        assert_eq!(
1383            &bytes[18..26],
1384            &[0, 1, b'b', marker::ECMA_ARRAY, 0, 0, 0, 2]
1385        );
1386        assert_eq!(&bytes[26..30], &[0, 1, b'x', marker::LONG_STRING]);
1387        assert_eq!(&bytes[30..34], &70_000u32.to_be_bytes());
1388        assert_eq!(&bytes[34..36], b"LL");
1389
1390        let long_end = 34 + 70_000;
1391        assert_eq!(&bytes[long_end..long_end + 4], &[0, 1, b'y', marker::NULL]);
1392        assert_eq!(
1393            &bytes[long_end + 4..long_end + 10],
1394            &[0, 0, marker::OBJECT_END, 0, 0, marker::OBJECT_END]
1395        );
1396        assert_eq!(bytes[long_end + 10], marker::DATE);
1397        assert_eq!(
1398            &bytes[long_end + 11..long_end + 19],
1399            &1.0e12f64.to_be_bytes()
1400        );
1401        assert_eq!(&bytes[long_end + 19..long_end + 21], &[0, 0]);
1402        assert_eq!(
1403            &bytes[long_end + 21..long_end + 24],
1404            &[marker::BOOLEAN, 1, marker::UNDEFINED]
1405        );
1406        assert_eq!(bytes.len(), long_end + 24);
1407
1408        let mut values = Budget::new(DEFAULT_AMF0_LIMITS);
1409        let mut diagnostics = Vec::new();
1410        let (parsed, consumed) =
1411            parse_value(&bytes, 0, &mut values, &mut diagnostics).expect("parse");
1412        assert_eq!(parsed, nested);
1413        assert_eq!(consumed, bytes.len());
1414    }
1415
1416    /// Every AMF0 variant writes exactly the byte count it declares.
1417    #[test]
1418    fn every_variant_writes_its_declared_length() {
1419        let variants = vec![
1420            Amf0Value::Number(-1.5),
1421            Amf0Value::Boolean(false),
1422            Amf0Value::String("hello".to_string()),
1423            Amf0Value::Object(vec![("k".to_string(), Amf0Value::Null)]),
1424            Amf0Value::Null,
1425            Amf0Value::Undefined,
1426            Amf0Value::EcmaArray(vec![("k".to_string(), Amf0Value::Date(0.0))]),
1427            Amf0Value::StrictArray(vec![Amf0Value::Boolean(true), Amf0Value::Null]),
1428            Amf0Value::Date(1.0e12),
1429            Amf0Value::LongString("x".repeat(70_000)),
1430        ];
1431        for value in variants {
1432            let mut buf = vec![0u8; value.serialized_len()];
1433            assert_eq!(
1434                value.serialize_into(&mut buf).unwrap(),
1435                value.serialized_len()
1436            );
1437            let mut values = Budget::new(DEFAULT_AMF0_LIMITS);
1438            let mut diagnostics = Vec::new();
1439            let (parsed, consumed) = parse_value(&buf, 0, &mut values, &mut diagnostics).unwrap();
1440            assert_eq!(consumed, buf.len());
1441            assert_eq!(parsed, value);
1442        }
1443    }
1444
1445    /// The Long String length prefix accepts exactly that many bytes, rejects
1446    /// one fewer, and an empty long string is valid.
1447    #[test]
1448    fn long_string_length_prefix_boundaries() {
1449        assert_eq!(
1450            parse_value_default(&[marker::LONG_STRING, 0, 0, 0, 0]).unwrap(),
1451            Amf0Value::LongString(String::new())
1452        );
1453        let mut ok = vec![marker::LONG_STRING, 0, 0, 0, 3];
1454        ok.extend_from_slice(b"abc");
1455        assert_eq!(
1456            parse_value_default(&ok).unwrap(),
1457            Amf0Value::LongString("abc".to_string())
1458        );
1459        assert!(matches!(
1460            parse_value_default(&ok[..ok.len() - 1]),
1461            Err(RtmpError::BufferTooShort(_))
1462        ));
1463    }
1464
1465    /// Truncating the encoding at any point inside a nested value is a
1466    /// BufferTooShort, never a mis-framed shorter value.
1467    #[test]
1468    fn truncating_a_nested_encoding_is_always_buffer_too_short() {
1469        let value = Amf0Value::StrictArray(vec![
1470            Amf0Value::Object(vec![("k".to_string(), Amf0Value::Date(1.0e12))]),
1471            Amf0Value::EcmaArray(vec![("s".to_string(), Amf0Value::String("v".to_string()))]),
1472        ]);
1473        let bytes = value.try_to_bytes().unwrap();
1474        for cut in 1..bytes.len() {
1475            assert!(
1476                matches!(
1477                    parse_value_default(&bytes[..cut]),
1478                    Err(RtmpError::BufferTooShort(_))
1479                ),
1480                "cut at {cut} must be BufferTooShort"
1481            );
1482        }
1483    }
1484
1485    /// A truncated container reports the exact byte count its next field
1486    /// needs.
1487    #[test]
1488    fn truncated_containers_report_the_exact_need() {
1489        let bytes = [marker::ECMA_ARRAY, 0, 0, 0, 0];
1490        match parse_value_default(&bytes) {
1491            Err(RtmpError::BufferTooShort(b)) => {
1492                assert_eq!(b.need, 2);
1493                assert_eq!(b.have, 0);
1494            }
1495            other => panic!("expected BufferTooShort, got {other:?}"),
1496        }
1497
1498        let bytes = [marker::DATE, 0, 0, 0, 0, 0, 0];
1499        match parse_value_default(&bytes) {
1500            Err(RtmpError::BufferTooShort(b)) => {
1501                assert_eq!(b.need, 10);
1502                assert_eq!(b.have, 6);
1503            }
1504            other => panic!("expected BufferTooShort, got {other:?}"),
1505        }
1506
1507        let bytes = [marker::OBJECT, 0, 0];
1508        match parse_value_default(&bytes) {
1509            Err(RtmpError::BufferTooShort(b)) => {
1510                assert_eq!(b.need, 3);
1511                assert_eq!(b.have, 2);
1512            }
1513            other => panic!("expected BufferTooShort, got {other:?}"),
1514        }
1515    }
1516
1517    /// Serializing an object into a pre-filled buffer writes every byte of
1518    /// its range, including both object-end zeroes.
1519    #[test]
1520    fn object_serialize_overwrites_every_byte_of_its_range() {
1521        let value = Amf0Value::Object(vec![("k".to_string(), Amf0Value::Null)]);
1522        let mut buf = vec![0xFFu8; value.serialized_len()];
1523        assert_eq!(
1524            value.serialize_into(&mut buf).unwrap(),
1525            value.serialized_len()
1526        );
1527        assert_eq!(
1528            buf,
1529            vec![
1530                marker::OBJECT,
1531                0,
1532                1,
1533                b'k',
1534                marker::NULL,
1535                0,
1536                0,
1537                marker::OBJECT_END
1538            ]
1539        );
1540    }
1541
1542    /// The depth guard counts ECMA-array and strict-array nesting too.
1543    #[test]
1544    fn depth_guard_counts_every_container_kind() {
1545        let mut inner = vec![marker::NULL];
1546        for _ in 0..(MAX_AMF0_DEPTH + 1) {
1547            let mut wrapped = vec![marker::ECMA_ARRAY, 0, 0, 0, 1];
1548            wrapped.extend_from_slice(&1u16.to_be_bytes());
1549            wrapped.push(b'a');
1550            wrapped.extend_from_slice(&inner);
1551            wrapped.extend_from_slice(&[0, 0, marker::OBJECT_END]);
1552            inner = wrapped;
1553        }
1554        assert!(matches!(
1555            parse_value_default(&inner),
1556            Err(RtmpError::Amf0DepthExceeded { .. })
1557        ));
1558
1559        let mut inner = vec![marker::NULL];
1560        for _ in 0..(MAX_AMF0_DEPTH + 1) {
1561            let mut wrapped = vec![marker::STRICT_ARRAY, 0, 0, 0, 1];
1562            wrapped.extend_from_slice(&inner);
1563            inner = wrapped;
1564        }
1565        assert!(matches!(
1566            parse_value_default(&inner),
1567            Err(RtmpError::Amf0DepthExceeded { .. })
1568        ));
1569    }
1570}