Skip to main content

rtmp_runtime/
chunk.rs

1//! RTMP chunk stream — basic header, message header, extended timestamp
2//! (Adobe RTMP 1.0 §5.3).
3//!
4//! See `private/specs-verified/rtmp/rtmp-runtime/rtmp.md` §3 (RTMP Chunk Stream) for the wire
5//! layout: chunk format (§5.3.1), basic header (§5.3.1.1), the four message
6//! header `fmt` variants (§5.3.1.2), and extended timestamp (§5.3.1.3).
7//!
8//! This module implements the chunk **header** wire types (`BasicHeader`,
9//! `MessageHeader`) and the stateful reassembly engine built on top of them:
10//! [`ChunkAssembler`] (inbound, tracks prior-chunk state per csid so `fmt`
11//! 1/2/3 headers can inherit the fields they omit, and reassembles chunked
12//! payload back into whole [`Message`]s) and [`ChunkWriter`] (outbound,
13//! splits a [`Message`] into `fmt` 0 + 3 chunks at the configured chunk
14//! size).
15
16use alloc::collections::BTreeMap;
17use broadcast_common::len::{need_in, need_out};
18use core::time::Duration;
19
20use broadcast_common::{Parse, Serialize};
21
22use crate::RtmpError;
23use crate::ids::{ChunkStreamId, MessageStreamId, Timestamp};
24use crate::message::ChunkSize;
25use crate::message::MessageTypeId;
26use alloc::vec::Vec;
27
28type Result<T> = core::result::Result<T, RtmpError>;
29
30/// Default chunk size (§5.3, §5.4.1): 128 bytes, in effect until a Set Chunk
31/// Size protocol control message changes it.
32pub const DEFAULT_CHUNK_SIZE_VALUE: u32 = 128;
33/// [`DEFAULT_CHUNK_SIZE_VALUE`] as an adopted size.
34pub const DEFAULT_CHUNK_SIZE: ChunkSize = ChunkSize::new_unchecked(DEFAULT_CHUNK_SIZE_VALUE);
35
36/// Largest chunk size this engine will adopt: 16 MiB. The wire field is a
37/// 31-bit value (up to ~2 GiB), but no real publisher/player needs a chunk
38/// size anywhere near that — a single chunk this large would already hold
39/// many seconds of encoded audio/video — so this is a defensive ceiling,
40/// not a spec limit. It is enforced at construction, never by silently
41/// adopting a smaller size than was announced: a size above it is rejected
42/// (see [`ChunkSize::try_new`]'s ceiling note), because parsing chunks at
43/// any size but the announced one mis-frames every later chunk boundary.
44pub const MAX_CHUNK_SIZE: u32 = 16 * 1024 * 1024;
45
46/// Largest total `message_length` (§5.3.1.2) [`ChunkAssembler`] will begin
47/// buffering for a single reassembled message: 8 MiB. `message_length` is a
48/// fully peer-supplied 24-bit wire field (max ~16 MiB); real RTMP
49/// audio/video/command messages are always far smaller than this (a single
50/// compressed video frame, even a keyframe, is normally well under 1 MiB),
51/// so this is a generous ceiling that still bounds worst-case allocation
52/// per in-progress message. A Type 0/1 header declaring a larger
53/// `message_length` is rejected by [`ChunkAssembler`] before any buffer for
54/// it is allocated.
55pub const MAX_MESSAGE_LEN: u32 = 8 * 1024 * 1024;
56
57/// Largest number of distinct chunk stream ids [`ChunkAssembler`] will track
58/// reassembly state for concurrently. A well-behaved publisher uses only a
59/// handful of chunk streams (2/3 for control/command traffic, plus a few
60/// more for audio/video) — this bound is generous headroom above that, not
61/// a spec limit — so a flood of chunks opening many distinct (and mostly
62/// bogus) csids is rejected rather than growing the per-csid state map
63/// without bound.
64pub const MAX_CSIDS: usize = 64;
65
66/// Default aggregate ceiling on the total payload bytes [`ChunkAssembler`]
67/// will buffer across **all** in-progress messages on one connection
68/// (#1108/RTMP-W1). Per-message [`MAX_MESSAGE_LEN`] (8 MiB) and per-
69/// connection [`MAX_CSIDS`] (64) each bound their own dimension, but their
70/// product — 512 MiB per TCP connection, reachable before `connect` even
71/// completes by opening one partially-filled maximum-size message on each
72/// csid — is not a bound anyone intended. This is a generous figure far
73/// above any real publisher's interleaved in-flight media (a few concurrent
74/// audio/video frames is a few hundred KB), so it does not threaten
75/// interoperability, while capping a hostile peer's buffered-but-never-
76/// completed bytes at a predictable number.
77pub const DEFAULT_MAX_IN_PROGRESS_BYTES: usize = 16 * 1024 * 1024;
78
79/// The 24-bit sentinel value that, in a Type 0/1/2 message header's
80/// `timestamp`/`timestamp delta` field, signals that the field does not carry
81/// the real value: the full 32-bit value instead follows in a 4-byte
82/// Extended Timestamp (§5.3.1.3). Per §5.3.1.2.1, any real timestamp/delta
83/// `>= EXTENDED_TIMESTAMP_MARKER` is encoded this way.
84pub const EXTENDED_TIMESTAMP_MARKER: u32 = 0x00FF_FFFF;
85
86/// Byte width of a 24-bit (`u24`) wire field (`timestamp`, `timestamp delta`,
87/// `message length`).
88const U24_LEN: usize = 3;
89/// Byte width of the Extended Timestamp field (§5.3.1.3).
90const EXTENDED_TIMESTAMP_LEN: usize = 4;
91
92/// Byte width of a Type 0 message header (§5.3.1.2.1), excluding any
93/// Extended Timestamp.
94const TYPE0_LEN: usize = 11;
95/// Byte width of a Type 1 message header (§5.3.1.2.2), excluding any
96/// Extended Timestamp.
97const TYPE1_LEN: usize = 7;
98/// Byte width of a Type 2 message header (§5.3.1.2.3), excluding any
99/// Extended Timestamp.
100const TYPE2_LEN: usize = 3;
101/// Byte width of a Type 3 message header (§5.3.1.2.4): always empty.
102const TYPE3_LEN: usize = 0;
103
104/// Chunk stream id (csid) offset added back on the 2-/3-byte basic header
105/// forms (§5.3.1.1): both forms carry `csid - 64`.
106const BASIC_HEADER_CSID_OFFSET: u32 = 64;
107/// The 2-byte basic header form's marker value in byte 0's low 6 bits.
108const BASIC_HEADER_2BYTE_MARKER: u8 = 0;
109/// The 3-byte basic header form's marker value in byte 0's low 6 bits.
110const BASIC_HEADER_3BYTE_MARKER: u8 = 1;
111/// Bit shift of the 2-bit `fmt` field within basic header byte 0.
112const BASIC_HEADER_FMT_SHIFT: u8 = 6;
113/// Mask for the low 6 bits of basic header byte 0 (the 1-byte csid, or the
114/// 2-/3-byte form marker).
115const BASIC_HEADER_MARKER_MASK: u8 = 0x3F;
116
117/// Smallest csid encodable in the basic header's 1-byte form (§5.3.1.1).
118/// Csid values 0 and 1 are reserved as the 2-/3-byte form markers and so can
119/// never appear as a literal 1-byte-form csid; csid 2 is additionally
120/// reserved by the spec for low-level protocol control messages/commands but
121/// remains structurally encodable.
122const BASIC_HEADER_1BYTE_MIN_CSID: u32 = 2;
123/// Largest csid encodable in the basic header's 1-byte form.
124const BASIC_HEADER_1BYTE_MAX_CSID: u32 = 63;
125/// Smallest csid encodable in the basic header's 2-byte form.
126const BASIC_HEADER_2BYTE_MIN_CSID: u32 = 64;
127/// Largest csid encodable in the basic header's 2-byte form (csids 64-319
128/// are also representable in the 3-byte form; 2-byte is the minimal one).
129const BASIC_HEADER_2BYTE_MAX_CSID: u32 = 319;
130/// Smallest csid that requires the basic header's 3-byte form.
131const BASIC_HEADER_3BYTE_MIN_CSID: u32 = 320;
132/// Largest csid the protocol supports at all (§5.3.1.1: "up to 65597 chunk
133/// streams, IDs 3-65599" — the 3-byte form's 16-bit `csid - 64` field tops
134/// out here).
135const BASIC_HEADER_3BYTE_MAX_CSID: u32 = 65599;
136
137// ── u24 helpers ─────────────────────────────────────────────────────────
138
139/// Read a 3-byte big-endian unsigned integer. `b` must have at least
140/// [`U24_LEN`] bytes (caller-checked).
141fn read_u24_be(b: &[u8]) -> u32 {
142    (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2])
143}
144
145/// Write `v` as a big-endian 24-bit field into `buf`. `buf` must have at
146/// least [`U24_LEN`] bytes (caller-checked). A value that does not fit 24
147/// bits is [`RtmpError::FieldOverflow`], never silently masked (#1129):
148/// `message length` is a caller-supplied `u32`, so it really can overflow.
149fn write_u24_be(v: u32, buf: &mut [u8], field: &'static str) -> Result<()> {
150    let v = broadcast_common::len::fit_bits(u64::from(v), 24, field)? as u32;
151    buf[0] = (v >> 16) as u8;
152    buf[1] = (v >> 8) as u8;
153    buf[2] = v as u8;
154    Ok(())
155}
156
157// ── fmt (chunk type) ────────────────────────────────────────────────────
158
159/// The 2-bit `fmt` field selecting one of the 4 Chunk Message Header formats
160/// (§5.3.1.1, §5.3.1.2).
161#[derive(Debug, Clone, Copy, PartialEq, Eq)]
162#[non_exhaustive]
163pub enum Fmt {
164    /// Type 0 (§5.3.1.2.1): the full 11-byte header.
165    Type0,
166    /// Type 1 (§5.3.1.2.2): 7-byte header, inherits `message stream id`.
167    Type1,
168    /// Type 2 (§5.3.1.2.3): 3-byte header, inherits length/type/stream id.
169    Type2,
170    /// Type 3 (§5.3.1.2.4): no header, inherits everything.
171    Type3,
172}
173
174impl Fmt {
175    /// The spec token for this `fmt` value.
176    #[must_use]
177    pub fn name(&self) -> &'static str {
178        match self {
179            Fmt::Type0 => "type 0",
180            Fmt::Type1 => "type 1",
181            Fmt::Type2 => "type 2",
182            Fmt::Type3 => "type 3",
183        }
184    }
185
186    /// Decode the 2-bit wire value (0..=3) into a [`Fmt`].
187    ///
188    /// # Errors
189    /// [`RtmpError::ChunkStreamState`] if `bits` is not in `0..=3`.
190    pub const fn from_bits(bits: u8) -> core::result::Result<Self, RtmpError> {
191        match bits {
192            0 => Ok(Fmt::Type0),
193            1 => Ok(Fmt::Type1),
194            2 => Ok(Fmt::Type2),
195            3 => Ok(Fmt::Type3),
196            _ => Err(RtmpError::Malformed {
197                what: "chunk fmt (must be 0..=3)",
198            }),
199        }
200    }
201
202    /// Encode this `fmt` back to its 2-bit wire value (0..=3).
203    #[must_use]
204    pub const fn to_bits(self) -> u8 {
205        match self {
206            Fmt::Type0 => 0,
207            Fmt::Type1 => 1,
208            Fmt::Type2 => 2,
209            Fmt::Type3 => 3,
210        }
211    }
212}
213
214broadcast_common::impl_spec_display!(Fmt);
215
216// ── Basic Header (§5.3.1.1) ─────────────────────────────────────────────
217
218/// One of the three basic header forms, chosen purely by csid range
219/// (§5.3.1.1).
220#[derive(Debug, Clone, Copy, PartialEq, Eq)]
221enum BasicHeaderForm {
222    One,
223    Two,
224    Three,
225}
226
227/// The minimal basic-header form that can encode `csid`.
228fn basic_header_form(csid: u32) -> Result<BasicHeaderForm> {
229    match csid {
230        BASIC_HEADER_1BYTE_MIN_CSID..=BASIC_HEADER_1BYTE_MAX_CSID => Ok(BasicHeaderForm::One),
231        BASIC_HEADER_2BYTE_MIN_CSID..=BASIC_HEADER_2BYTE_MAX_CSID => Ok(BasicHeaderForm::Two),
232        BASIC_HEADER_3BYTE_MIN_CSID..=BASIC_HEADER_3BYTE_MAX_CSID => Ok(BasicHeaderForm::Three),
233        _ => Err(RtmpError::Malformed {
234            what: "chunk stream id (must be 2..=65599)",
235        }),
236    }
237}
238
239/// Chunk Basic Header (§5.3.1.1): 1 to 3 bytes encoding the 2-bit `fmt` and
240/// the chunk stream id (csid). Length depends only on the csid value; the
241/// implementation SHOULD (and this [`Serialize`] impl does) use the smallest
242/// form that holds the id.
243#[derive(Debug, Clone, Copy, PartialEq, Eq)]
244pub struct BasicHeader {
245    /// Selects which of the 4 Chunk Message Header formats follows.
246    pub fmt: Fmt,
247    /// Chunk stream id. Valid range 2..=65599 on the wire (0/1 are the
248    /// 2-/3-byte form markers, not real ids; 2 is further reserved by the
249    /// spec for low-level protocol control messages/commands but is still a
250    /// structurally valid basic-header value).
251    pub chunk_stream_id: ChunkStreamId,
252}
253
254impl<'a> Parse<'a> for BasicHeader {
255    type Error = RtmpError;
256
257    fn parse(bytes: &'a [u8]) -> Result<Self> {
258        need_in(bytes, 1, "chunk basic header")?;
259        let byte0 = bytes[0];
260        let fmt = Fmt::from_bits((byte0 >> BASIC_HEADER_FMT_SHIFT) & 0x03)?;
261        let marker = byte0 & BASIC_HEADER_MARKER_MASK;
262
263        let chunk_stream_id = ChunkStreamId::new(match marker {
264            BASIC_HEADER_2BYTE_MARKER => {
265                need_in(bytes, 2, "chunk basic header (2-byte form)")?;
266                u32::from(bytes[1]) + BASIC_HEADER_CSID_OFFSET
267            }
268            BASIC_HEADER_3BYTE_MARKER => {
269                need_in(bytes, 3, "chunk basic header (3-byte form)")?;
270                // §5.3.1.1: csid = (byte2 * 256) + byte1 + 64 — byte 1 is
271                // the low byte, byte 2 the high byte (little-endian).
272                u32::from(bytes[1]) + u32::from(bytes[2]) * 256 + BASIC_HEADER_CSID_OFFSET
273            }
274            literal => u32::from(literal),
275        });
276
277        Ok(BasicHeader {
278            fmt,
279            chunk_stream_id,
280        })
281    }
282}
283
284impl Serialize for BasicHeader {
285    type Error = RtmpError;
286
287    fn serialized_len(&self) -> usize {
288        match basic_header_form(self.chunk_stream_id.get()) {
289            Ok(BasicHeaderForm::One) => 1,
290            Ok(BasicHeaderForm::Two) => 2,
291            Ok(BasicHeaderForm::Three) => 3,
292            // Out-of-range csid: nominal upper bound. `serialize_into`
293            // performs the real validation and returns the error.
294            Err(_) => 3,
295        }
296    }
297
298    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
299        let form = basic_header_form(self.chunk_stream_id.get())?;
300        let fmt_bits = self.fmt.to_bits() << BASIC_HEADER_FMT_SHIFT;
301
302        match form {
303            BasicHeaderForm::One => {
304                need_out(buf, 1)?;
305                buf[0] = fmt_bits | (self.chunk_stream_id.get() as u8);
306                Ok(1)
307            }
308            BasicHeaderForm::Two => {
309                need_out(buf, 2)?;
310                buf[0] = fmt_bits | BASIC_HEADER_2BYTE_MARKER;
311                buf[1] = (self.chunk_stream_id.get() - BASIC_HEADER_CSID_OFFSET) as u8;
312                Ok(2)
313            }
314            BasicHeaderForm::Three => {
315                need_out(buf, 3)?;
316                buf[0] = fmt_bits | BASIC_HEADER_3BYTE_MARKER;
317                let rel = self.chunk_stream_id.get() - BASIC_HEADER_CSID_OFFSET;
318                buf[1] = rel as u8;
319                buf[2] = (rel >> 8) as u8;
320                Ok(3)
321            }
322        }
323    }
324}
325
326// ── Message Header (§5.3.1.2) ───────────────────────────────────────────
327
328/// Whether `field` (a 24-bit `timestamp`/`timestamp delta`) needs the 4-byte
329/// Extended Timestamp (§5.3.1.3): any value `>= EXTENDED_TIMESTAMP_MARKER`.
330fn needs_extended_timestamp(field: u32) -> bool {
331    field >= EXTENDED_TIMESTAMP_MARKER
332}
333
334/// Chunk Message Header: one of 4 formats selected by [`Fmt`] (§5.3.1.2),
335/// carrying decreasing field sets — each format after Type 0 inherits the
336/// fields it omits from the preceding chunk on the same chunk stream.
337///
338/// Reassembling that "preceding chunk" state (so Type 1/2/3 headers can be
339/// resolved to absolute values) is a stateful job for the chunk-stream
340/// reassembler (#738 Task 4), not this header type. In particular, a Type 3
341/// header carrying zero bytes here does *not* by itself tell you whether an
342/// Extended Timestamp follows it on the wire: per §5.3.1.3, a Type 3 chunk
343/// carries the 4-byte Extended Timestamp when — and only when — the most
344/// recent Type 0/1/2 chunk on the same csid itself used one. Deciding that
345/// requires exactly that per-csid state, so [`MessageHeader::parse`] never
346/// consumes an Extended Timestamp for `Fmt::Type3`; the reassembler must
347/// apply this rule itself once it is tracking that state.
348#[derive(Debug, Clone, Copy, PartialEq, Eq)]
349#[non_exhaustive]
350pub enum MessageHeader {
351    /// Type 0 (§5.3.1.2.1, 11 bytes on the wire before any Extended
352    /// Timestamp). MUST be used at the start of a chunk stream and whenever
353    /// the stream timestamp goes backward.
354    Type0 {
355        /// Absolute timestamp of the message (already resolved from any
356        /// Extended Timestamp).
357        timestamp: Timestamp,
358        /// Length in bytes of the whole message (not the chunk payload).
359        message_length: u32,
360        /// Message type id (§6/§7.1).
361        message_type_id: MessageTypeId,
362        /// Message stream id. The wire encoding of this field alone is
363        /// little-endian (§5.3.1.2.1).
364        message_stream_id: MessageStreamId,
365    },
366    /// Type 1 (§5.3.1.2.2, 7 bytes before any Extended Timestamp). No
367    /// message stream id — inherits the preceding chunk's.
368    Type1 {
369        /// Delta from the previous chunk's timestamp on this csid (already
370        /// resolved from any Extended Timestamp).
371        timestamp_delta: Duration,
372        /// Length in bytes of the whole message.
373        message_length: u32,
374        /// Message type id (§6/§7.1).
375        message_type_id: MessageTypeId,
376    },
377    /// Type 2 (§5.3.1.2.3, 3 bytes before any Extended Timestamp). Neither
378    /// stream id nor message length included — both inherited.
379    Type2 {
380        /// Delta from the previous chunk's timestamp on this csid (already
381        /// resolved from any Extended Timestamp).
382        timestamp_delta: Duration,
383    },
384    /// Type 3 (§5.3.1.2.4, 0 bytes). Stream id, message length, message type
385    /// id, and timestamp delta are all inherited from the preceding chunk on
386    /// the same csid.
387    Type3,
388}
389
390impl MessageHeader {
391    /// Parse the message header that follows a [`BasicHeader`] carrying
392    /// `fmt`. Returns the parsed variant and the number of bytes consumed
393    /// from `bytes` — the fixed per-`fmt` header length, plus 4 more if a
394    /// Type 0/1/2 field's 24-bit value read exactly [`EXTENDED_TIMESTAMP_MARKER`]
395    /// (in which case the real, unresolved value is read from the following
396    /// 4-byte big-endian Extended Timestamp — see §5.3.1.3).
397    ///
398    /// # Errors
399    /// [`RtmpError::BufferTooShort`] if `bytes` does not hold the full fixed
400    /// header (and, when signalled, the Extended Timestamp).
401    pub fn parse(fmt: Fmt, bytes: &[u8]) -> Result<(Self, usize)> {
402        match fmt {
403            Fmt::Type0 => {
404                need_in(bytes, TYPE0_LEN, "type 0 message header")?;
405                let raw_timestamp = read_u24_be(&bytes[0..U24_LEN]);
406                let message_length = read_u24_be(&bytes[U24_LEN..2 * U24_LEN]);
407                let message_type_id = MessageTypeId::from_u8(bytes[2 * U24_LEN]);
408                let message_stream_id = MessageStreamId::new(u32::from_le_bytes([
409                    bytes[7], bytes[8], bytes[9], bytes[10],
410                ]));
411
412                let (timestamp, consumed) = resolve_extended(raw_timestamp, bytes, TYPE0_LEN)?;
413
414                Ok((
415                    MessageHeader::Type0 {
416                        timestamp,
417                        message_length,
418                        message_type_id,
419                        message_stream_id,
420                    },
421                    consumed,
422                ))
423            }
424            Fmt::Type1 => {
425                need_in(bytes, TYPE1_LEN, "type 1 message header")?;
426                let raw_delta = read_u24_be(&bytes[0..U24_LEN]);
427                let message_length = read_u24_be(&bytes[U24_LEN..2 * U24_LEN]);
428                let message_type_id = MessageTypeId::from_u8(bytes[2 * U24_LEN]);
429
430                let (timestamp_delta, consumed) = resolve_delta(raw_delta, bytes, TYPE1_LEN)?;
431
432                Ok((
433                    MessageHeader::Type1 {
434                        timestamp_delta,
435                        message_length,
436                        message_type_id,
437                    },
438                    consumed,
439                ))
440            }
441            Fmt::Type2 => {
442                need_in(bytes, TYPE2_LEN, "type 2 message header")?;
443                let raw_delta = read_u24_be(&bytes[0..U24_LEN]);
444                let (timestamp_delta, consumed) = resolve_delta(raw_delta, bytes, TYPE2_LEN)?;
445
446                Ok((MessageHeader::Type2 { timestamp_delta }, consumed))
447            }
448            Fmt::Type3 => Ok((MessageHeader::Type3, TYPE3_LEN)),
449        }
450    }
451}
452
453/// Shared tail of Type 0/1/2 parsing: given the 24-bit field already read at
454/// `bytes[..3]`, resolve it to its real value (reading the trailing 4-byte
455/// Extended Timestamp if the field read the sentinel), and return
456/// `(value, total_consumed)` where `total_consumed = fixed_len (+4)`.
457fn resolve_extended(raw: u32, bytes: &[u8], fixed_len: usize) -> Result<(Timestamp, usize)> {
458    if raw == EXTENDED_TIMESTAMP_MARKER {
459        let need = fixed_len + EXTENDED_TIMESTAMP_LEN;
460        need_in(bytes, need, "extended timestamp")?;
461        let ext = u32::from_be_bytes([
462            bytes[fixed_len],
463            bytes[fixed_len + 1],
464            bytes[fixed_len + 2],
465            bytes[fixed_len + 3],
466        ]);
467        Ok((Timestamp::from_millis(ext), need))
468    } else {
469        Ok((Timestamp::from_millis(raw), fixed_len))
470    }
471}
472
473/// Shared tail of Type 1/2 parsing: resolve the 24-bit `timestamp delta`
474/// field (plus its Extended Timestamp when the field read the sentinel) into
475/// the span it stands for.
476fn resolve_delta(raw: u32, bytes: &[u8], fixed_len: usize) -> Result<(Duration, usize)> {
477    resolve_extended(raw, bytes, fixed_len).map(|(ts, n)| (ts.span(), n))
478}
479
480impl Serialize for MessageHeader {
481    type Error = RtmpError;
482
483    fn serialized_len(&self) -> usize {
484        match self {
485            MessageHeader::Type0 { timestamp, .. } => TYPE0_LEN + extended_len(timestamp.millis()),
486            MessageHeader::Type1 {
487                timestamp_delta, ..
488            } => TYPE1_LEN + extended_len(delta_millis(*timestamp_delta)),
489            MessageHeader::Type2 { timestamp_delta } => {
490                TYPE2_LEN + extended_len(delta_millis(*timestamp_delta))
491            }
492            MessageHeader::Type3 => TYPE3_LEN,
493        }
494    }
495
496    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
497        match *self {
498            MessageHeader::Type0 {
499                timestamp,
500                message_length,
501                message_type_id,
502                message_stream_id,
503            } => {
504                let millis = timestamp.millis();
505                let extended = needs_extended_timestamp(millis);
506                let written = TYPE0_LEN + if extended { EXTENDED_TIMESTAMP_LEN } else { 0 };
507                need_out(buf, written)?;
508                let field = if extended {
509                    EXTENDED_TIMESTAMP_MARKER
510                } else {
511                    millis
512                };
513                write_u24_be(field, &mut buf[0..U24_LEN], "timestamp")?;
514                write_u24_be(
515                    message_length,
516                    &mut buf[U24_LEN..2 * U24_LEN],
517                    "message length",
518                )?;
519                buf[2 * U24_LEN] = message_type_id.to_u8();
520                buf[7..11].copy_from_slice(&message_stream_id.get().to_le_bytes());
521                if extended {
522                    buf[11..15].copy_from_slice(&millis.to_be_bytes());
523                }
524                Ok(written)
525            }
526            MessageHeader::Type1 {
527                timestamp_delta,
528                message_length,
529                message_type_id,
530            } => {
531                let millis = delta_millis(timestamp_delta);
532                let extended = needs_extended_timestamp(millis);
533                let written = TYPE1_LEN + if extended { EXTENDED_TIMESTAMP_LEN } else { 0 };
534                need_out(buf, written)?;
535                let field = if extended {
536                    EXTENDED_TIMESTAMP_MARKER
537                } else {
538                    millis
539                };
540                write_u24_be(field, &mut buf[0..U24_LEN], "timestamp")?;
541                write_u24_be(
542                    message_length,
543                    &mut buf[U24_LEN..2 * U24_LEN],
544                    "message length",
545                )?;
546                buf[2 * U24_LEN] = message_type_id.to_u8();
547                if extended {
548                    buf[7..11].copy_from_slice(&millis.to_be_bytes());
549                }
550                Ok(written)
551            }
552            MessageHeader::Type2 { timestamp_delta } => {
553                let millis = delta_millis(timestamp_delta);
554                let extended = needs_extended_timestamp(millis);
555                let written = TYPE2_LEN + if extended { EXTENDED_TIMESTAMP_LEN } else { 0 };
556                need_out(buf, written)?;
557                let field = if extended {
558                    EXTENDED_TIMESTAMP_MARKER
559                } else {
560                    millis
561                };
562                write_u24_be(field, &mut buf[0..U24_LEN], "timestamp")?;
563                if extended {
564                    buf[3..7].copy_from_slice(&millis.to_be_bytes());
565                }
566                Ok(written)
567            }
568            MessageHeader::Type3 => Ok(0),
569        }
570    }
571}
572
573/// The 32-bit wire value a timestamp delta stands for (a span is rounded down
574/// to the whole millisecond the field carries, §5.3.1.2).
575fn delta_millis(delta: Duration) -> u32 {
576    u32::try_from(delta.as_millis()).unwrap_or(u32::MAX)
577}
578
579/// Extra bytes (0 or 4) [`Serialize`] will write for a 24-bit
580/// `timestamp`/`timestamp delta` value.
581fn extended_len(field: u32) -> usize {
582    if needs_extended_timestamp(field) {
583        EXTENDED_TIMESTAMP_LEN
584    } else {
585        0
586    }
587}
588
589// ── Message (the assembled unit) ────────────────────────────────────────
590
591/// One fully reassembled RTMP message: the payload of a single message
592/// stream at a single (resolved, absolute) timestamp (§6.1). Produced by
593/// [`ChunkAssembler::push`] and consumed by [`ChunkWriter::write`].
594///
595/// The message type id is the typed [`MessageTypeId`] (`message.rs`); the
596/// payload stays opaque here.
597#[derive(Debug, Clone, PartialEq, Eq)]
598pub struct Message {
599    /// Chunk stream id this message was carried on.
600    pub chunk_stream_id: ChunkStreamId,
601    /// Absolute timestamp (already resolved from any timestamp delta /
602    /// Extended Timestamp — never a delta).
603    pub timestamp: Timestamp,
604    /// Message type id (§6/§7.1).
605    pub message_type_id: MessageTypeId,
606    /// Message stream id.
607    pub message_stream_id: MessageStreamId,
608    /// The whole message payload (reassembled across every chunk it was
609    /// split into).
610    pub payload: Vec<u8>,
611}
612
613// ── ChunkAssembler (stateful inbound reassembly, §5.3) ──────────────────
614
615/// Per-csid reassembly state: the most recently resolved header fields (used
616/// by `fmt` 1/2/3 to inherit the fields they omit) plus the payload
617/// accumulated so far for the message currently in progress on this csid.
618#[derive(Debug, Clone, Default)]
619struct CsidState {
620    /// Absolute timestamp of the current/most recent message on this csid.
621    timestamp: Timestamp,
622    /// Delta most recently applied to reach `timestamp` — re-applied
623    /// unchanged when a Type 3 chunk begins a new message (inherits the
624    /// prior delta). Per §3.1.2 Type 3: when a Type 3 chunk immediately
625    /// follows a Type 0 chunk with no intervening Type 1/2, its implied
626    /// delta equals the Type 0 chunk's own absolute timestamp — so a Type 0
627    /// chunk seeds this field with its `timestamp`, not `0`.
628    timestamp_delta: Duration,
629    /// Total length in bytes of the current/most recent message.
630    message_length: u32,
631    /// Message type id of the current/most recent message. `None` until the
632    /// first Type 0/1 header on this csid, since a Type 3 chunk inherits it.
633    message_type_id: Option<MessageTypeId>,
634    /// Message stream id of the current/most recent message.
635    message_stream_id: MessageStreamId,
636    /// Whether the most recent Type 0/1/2 header on this csid used the
637    /// Extended Timestamp (§5.3.1.3) — a Type 3 chunk then also carries (and
638    /// must consume) that 4-byte field, per csid, until the next Type 0/1/2
639    /// changes the flag.
640    extended: bool,
641    /// Whether a Type 0/1/2 header has ever been seen on this csid (Type
642    /// 1/2/3 headers inherit from it; nothing to inherit before the first
643    /// Type 0).
644    initialized: bool,
645    /// Whether a message is currently mid-accumulation on this csid (a
646    /// prior chunk started it but its `message_length` bytes are not all
647    /// in yet). Distinguishes, for a Type 3 chunk, a **continuation** of
648    /// that in-progress message (`true`) from the **start of a new**
649    /// message reusing the prior header (`false`, at a message boundary) —
650    /// `payload.len()` alone can't tell them apart once a message has
651    /// completed and `payload` was reset to empty for the next one.
652    in_progress: bool,
653    /// Payload bytes accumulated so far for the message in progress
654    /// (`message_length` total once complete). Reset to empty once a
655    /// message completes.
656    payload: Vec<u8>,
657    /// The #1108/RTMP-W1 aggregate-budget reservation currently held by
658    /// this csid's in-progress message (its full declared
659    /// `message_length`, charged when the message opened — see
660    /// [`ChunkAssembler::in_progress_bytes`]). `None` when no message is
661    /// in progress on this csid (the reservation was released when the
662    /// message completed, or there never was one). The authoritative copy
663    /// of the amount to credit back on completion, overwrite, or abort.
664    reserved: Option<u32>,
665}
666
667/// Stateful inbound chunk reassembler (§5.3): feed inbound bytes, get back
668/// each complete [`Message`] as soon as its last chunk arrives.
669///
670/// Maintains per-`chunk_stream_id` state, so multiple chunk streams may be
671/// interleaved on the same connection (as the wire format requires) and are
672/// each reassembled independently.
673#[derive(Debug)]
674pub struct ChunkAssembler {
675    chunk_size: ChunkSize,
676    csids: BTreeMap<ChunkStreamId, CsidState>,
677    /// Bytes carried over from a previous `push` call that did not yet form
678    /// a complete chunk (partial basic header, message header, extended
679    /// timestamp, or payload slice).
680    pending: Vec<u8>,
681    /// How many bytes at the front of `pending` have already been consumed
682    /// by chunks parsed earlier in the current [`Self::next_message`] call,
683    /// but not yet physically dropped. Dropping them is deferred to one
684    /// [`Self::compact`] per `next_message` return rather than done per
685    /// chunk — see `compact`'s doc for why that matters.
686    cursor: usize,
687    /// Total payload bytes currently reserved across all in-progress
688    /// (incomplete) messages — #1108/RTMP-W1. A new message reserves its
689    /// full declared `message_length` the moment its header validates, so
690    /// the ceiling bounds what a peer can *hold open*, not just what it
691    /// has paid for in bytes sent (a header alone can declare 8 MiB).
692    /// Maintained incrementally (updated in [`Self::try_parse_one`]
693    /// wherever a message opens, completes, or aborts) rather than
694    /// recomputed per chunk, and checked against `max_in_progress_bytes`
695    /// before any reservation is made.
696    in_progress_bytes: usize,
697    /// Ceiling for `in_progress_bytes` — see
698    /// [`DEFAULT_MAX_IN_PROGRESS_BYTES`].
699    max_in_progress_bytes: usize,
700}
701
702impl Default for ChunkAssembler {
703    fn default() -> Self {
704        Self::new()
705    }
706}
707
708impl ChunkAssembler {
709    /// New assembler, chunk size at the §5.3 default (128 bytes).
710    #[must_use]
711    pub fn new() -> Self {
712        Self {
713            chunk_size: DEFAULT_CHUNK_SIZE,
714            csids: BTreeMap::new(),
715            pending: Vec::new(),
716            cursor: 0,
717            in_progress_bytes: 0,
718            max_in_progress_bytes: DEFAULT_MAX_IN_PROGRESS_BYTES,
719        }
720    }
721
722    /// Set the ceiling on total payload bytes buffered across all
723    /// in-progress messages (#1108/RTMP-W1); see
724    /// [`DEFAULT_MAX_IN_PROGRESS_BYTES`] for the default and its rationale.
725    #[must_use]
726    pub fn with_max_in_progress_bytes(mut self, max_in_progress_bytes: usize) -> Self {
727        self.max_in_progress_bytes = max_in_progress_bytes;
728        self
729    }
730
731    /// Builder form of [`Self::set_chunk_size`].
732    #[must_use]
733    pub fn with_chunk_size(mut self, chunk_size: ChunkSize) -> Self {
734        self.set_chunk_size(chunk_size);
735        self
736    }
737
738    /// Update the chunk size in effect for subsequent chunks (called on
739    /// receipt of a Set Chunk Size protocol control message, §5.4.1). Per
740    /// `private/specs-verified/rtmp/rtmp-runtime/rtmp.md` §3's transcription of §5.4.1 ("Default max chunk size
741    /// is 128; SHOULD be ≥ 128, MUST be ≥ 1"), 128 is only a `SHOULD` for a
742    /// *sender* choosing what to announce — a peer that announces (and
743    /// then frames its own chunks at) a smaller value is still wire-legal,
744    /// and this side must parse at whatever size the peer actually
745    /// announced or every later chunk boundary is misparsed. So any
746    /// validated [`ChunkSize`] is adopted verbatim; it is never clamped to
747    /// a different size, since parsing at any size but the announced one
748    /// mis-frames the stream silently.
749    pub fn set_chunk_size(&mut self, chunk_size: ChunkSize) {
750        self.chunk_size = chunk_size;
751    }
752
753    /// Discard any partially-received message on `csid` (§5.4.2 Abort
754    /// Message). A no-op if `csid` has no in-progress message.
755    ///
756    /// #1108/RTMP-W2: without this, `Abort` was accepted and silently
757    /// ignored, so `in_progress` stayed `true` and the next Type 3 chunk
758    /// that actually starts a *new* message on that csid was instead
759    /// appended to the aborted payload as a continuation — `message_length`
760    /// bytes later, a corrupted merged message came out.
761    pub fn abort(&mut self, csid: ChunkStreamId) {
762        if let Some(state) = self.csids.get_mut(&csid) {
763            if state.in_progress {
764                let released = state.reserved.take().unwrap_or(0) as usize;
765                self.in_progress_bytes = self.in_progress_bytes.saturating_sub(released);
766            }
767            state.payload.clear();
768            state.in_progress = false;
769        }
770    }
771
772    /// Feed inbound bytes; returns each complete [`Message`] decoded from
773    /// the buffer (in arrival order), leaving any trailing partial chunk or
774    /// partial message buffered internally for the next call.
775    ///
776    /// Callers that need to react to a message's side effects (e.g. a Set
777    /// Chunk Size protocol control message, §5.4.1) **before** parsing the
778    /// bytes that follow it in the same input — because the sender may
779    /// switch to the new chunk size for its very next chunk — should use the
780    /// crate-internal incremental `feed`/`next_message` pair instead,
781    /// dispatching each message immediately. `push` collects every message
782    /// from `input` under a single, unchanging `chunk_size`, which
783    /// misparses a buffer that itself contains a Set Chunk Size followed by
784    /// chunks already framed at the new size (see
785    /// [`ServerSession`](crate::server::ServerSession), which uses the
786    /// incremental form for exactly this reason).
787    ///
788    /// # Errors
789    /// [`RtmpError::Malformed`] on structurally invalid input (e.g. a Type
790    /// 1/2/3 chunk on a csid that has never seen a Type 0). Never errors
791    /// merely because the input ends mid-chunk — that is buffered, not an
792    /// error.
793    pub fn push(&mut self, input: &[u8]) -> Result<Vec<Message>> {
794        self.feed(input);
795        let mut out = Vec::new();
796        while let Some(msg) = match self.next_message() {
797            Ok(Some(msg)) => Some(msg),
798            Ok(None) => return Ok(out),
799            Err(e) => return Err(e),
800        } {
801            out.push(msg);
802        }
803        Ok(out)
804    }
805
806    /// Buffer inbound bytes without parsing them yet. Pair with repeated
807    /// calls to [`next_message`](Self::next_message) to parse and dispatch
808    /// one message at a time (see [`push`](Self::push)'s docs for why this
809    /// matters for Set Chunk Size).
810    ///
811    /// Nothing is parsed here, so this never fails: an incomplete chunk or
812    /// message stays buffered until more bytes arrive.
813    pub fn feed(&mut self, input: &[u8]) {
814        self.pending.extend_from_slice(input);
815    }
816
817    /// Bytes [`feed`](Self::feed)ed that [`next_message`](Self::next_message)
818    /// has not yet consumed. A caller that feeds one input slice at a time
819    /// pairs this with [`swap_pending`](Self::swap_pending) to recover how
820    /// much of that slice has been parsed.
821    #[must_use]
822    pub fn pending_len(&self) -> usize {
823        self.pending.len()
824    }
825
826    /// Replace the bytes [`feed`](Self::feed)ed so far with `now`, returning
827    /// what was there: the bytes a caller fed that are still unparsed. A
828    /// caller that has the original input still in hand (the common case:
829    /// one `on_bytes` call) passes what remains after its own offset and
830    /// gets back exactly the bytes it fed that never formed a chunk — no
831    /// re-derivation from byte counts, and nothing parsed at a stale chunk
832    /// size.
833    pub fn swap_pending(&mut self, now: &[u8]) -> Vec<u8> {
834        let consumed = self.cursor;
835        let previous = core::mem::replace(&mut self.pending, Vec::from(now));
836        self.cursor = 0;
837        previous.get(consumed..).unwrap_or_default().to_vec()
838    }
839
840    /// Parse and return the next complete [`Message`] out of the
841    /// previously-[`feed`](Self::feed) bytes, or `Ok(None)` if what remains
842    /// buffered isn't (yet) a complete message. Internally keeps parsing
843    /// individual chunks — which may belong to other interleaved csids, or
844    /// be a non-final chunk of the same in-progress message — until either a
845    /// full message is assembled or the buffered bytes run out.
846    ///
847    /// Each chunk's payload bytes are appended in place to that csid's own
848    /// persistent `CsidState::payload` buffer (never cloned), and the
849    /// consumed prefix of `pending` is only physically dropped once, when
850    /// this call returns (see `Self::compact`) — not once per chunk. A
851    /// message split across many small chunks (e.g. an 8 MiB message at a
852    /// 1-byte chunk size) used to cost O(`message_length`^2 /
853    /// `chunk_size`) — clone the whole accumulated payload on every
854    /// continuation chunk, and shift the rest of `pending` down on every
855    /// chunk's drain — and now costs O(`message_length`).
856    ///
857    /// Because each call stops at one message, the caller can apply that
858    /// message's effect on the chunk stream (a Set Chunk Size, §5.4.1) with
859    /// [`set_chunk_size`](Self::set_chunk_size) before the next call parses
860    /// the bytes that follow it. When the buffered bytes and the caller's
861    /// input overlap (one input buffer carries the control message and the
862    /// chunks framed after it), [`swap_pending`](Self::swap_pending) hands
863    /// back what was fed but never parsed, so the caller can re-feed exactly
864    /// those bytes and nothing is parsed twice or at the old size:
865    ///
866    /// ```
867    /// use rtmp_runtime::chunk::{ChunkAssembler, ChunkWriter, Message};
868    /// use rtmp_runtime::ids::{ChunkStreamId, MessageStreamId, Timestamp};
869    /// use rtmp_runtime::message::{ChunkSize, MessageTypeId, ProtocolControl};
870    ///
871    /// let mut writer = ChunkWriter::new();
872    /// let mut wire = Vec::new();
873    /// let control = ProtocolControl::SetChunkSize(ChunkSize::new(4096).unwrap()).to_message();
874    /// wire.extend_from_slice(&writer.write(&control)?);
875    /// writer.set_chunk_size(ChunkSize::new(4096)?);
876    /// let media = Message {
877    ///     chunk_stream_id: ChunkStreamId::new(4),
878    ///     timestamp: Timestamp::from_millis(0),
879    ///     message_type_id: MessageTypeId::Audio,
880    ///     message_stream_id: MessageStreamId::new(1),
881    ///     payload: vec![0u8; 5000],
882    /// };
883    /// wire.extend_from_slice(&writer.write(&media)?);
884    ///
885    /// let mut assembler = ChunkAssembler::new();
886    /// let mut rest: &[u8] = &wire;
887    /// let mut sizes = Vec::new();
888    /// assembler.feed(&wire);
889    /// loop {
890    ///     let message = match assembler.next_message()? {
891    ///         Some(message) => message,
892    ///         None => break,
893    ///     };
894    ///     if message.message_type_id == MessageTypeId::SetChunkSize {
895    ///         if let Some(ProtocolControl::SetChunkSize(size)) =
896    ///             ProtocolControl::from_message(&message)?
897    ///         {
898    ///             let boundary = rest.len() - assembler.pending_len();
899    ///             assembler.set_chunk_size(size);
900    ///             rest = rest.get(boundary..).unwrap_or_default();
901    ///             assembler.swap_pending(rest);
902    ///         }
903    ///         continue;
904    ///     }
905    ///     sizes.push(message.payload.len());
906    /// }
907    /// # assert_eq!(sizes, vec![5000]);
908    /// # Ok::<(), rtmp_runtime::RtmpError>(())
909    /// ```
910    ///
911    /// # Errors
912    /// Same as [`push`](Self::push).
913    pub fn next_message(&mut self) -> Result<Option<Message>> {
914        let max_in_progress_bytes = self.max_in_progress_bytes;
915        // #1108/RTMP-W1 defence-in-depth: cap the not-yet-parsed `pending`
916        // receive buffer at twice the in-progress budget. The primary
917        // bound is the declared-length reservation enforced in
918        // `try_parse_one` below (which holds whether or not the message's
919        // bytes have committed); this backstop covers the residual slack
920        // of bytes that belong to no reserved message (a caller that keeps
921        // feeding unparsed input despite errors) plus at most one
922        // unreserved in-flight header's worth.
923        if self.pending.len() - self.cursor > max_in_progress_bytes * 2 {
924            return Err(RtmpError::InputBudgetExceeded {
925                max: max_in_progress_bytes * 2,
926            });
927        }
928        {
929            // Disjoint field borrows: the parse input is a slice of
930            // `pending` while the commit target is `csids`, so `pending`
931            // is briefly moved out to satisfy the borrow checker. Every
932            // return path below restores it (with the consumed prefix
933            // still in place — compaction happens in `compact`, once per
934            // return, not per chunk).
935            let pending = core::mem::take(&mut self.pending);
936            let mut cursor = self.cursor;
937            let outcome = loop {
938                let rest = &pending[cursor..];
939                match Self::try_parse_one(
940                    rest,
941                    &mut self.csids,
942                    self.chunk_size,
943                    &mut self.in_progress_bytes,
944                    max_in_progress_bytes,
945                ) {
946                    Ok(Some(parsed)) => {
947                        cursor += parsed.consumed;
948                        // `try_parse_one` commits (inserts or updates)
949                        // `parsed.csid`'s entry before returning `Ok(Some(_))`,
950                        // so the entry exists; guard the borrow the same way
951                        // the message-type-id field is below.
952                        let state = self.csids.get_mut(&parsed.csid).ok_or(
953                            RtmpError::ChunkStreamState {
954                                chunk_stream_id: parsed.csid.get(),
955                                what: "chunk committed but its csid entry is missing",
956                            },
957                        )?;
958                        if state.payload.len() as u32 != state.message_length {
959                            // This chunk only partially filled its message
960                            // (or belongs to a different, interleaved csid)
961                            // — keep looping to try the next chunk already
962                            // in `pending`.
963                            continue;
964                        }
965                        state.in_progress = false;
966                        // #1108/RTMP-W1: a completed message's reservation
967                        // (its declared length, charged when it opened)
968                        // leaves the budget the moment it is handed over.
969                        let released = state.reserved.take().unwrap_or(0) as usize;
970                        self.in_progress_bytes = self.in_progress_bytes.saturating_sub(released);
971                        let msg = Message {
972                            chunk_stream_id: parsed.csid,
973                            timestamp: state.timestamp,
974                            message_type_id: state.message_type_id.ok_or(
975                                RtmpError::ChunkStreamState {
976                                    chunk_stream_id: parsed.csid.get(),
977                                    what: "completed message has no message type id",
978                                },
979                            )?,
980                            message_stream_id: state.message_stream_id,
981                            payload: core::mem::take(&mut state.payload),
982                        };
983                        break Ok(Some((msg, cursor)));
984                    }
985                    Ok(None) => break Ok(None),
986                    Err(e) => break Err(e),
987                }
988            };
989            self.pending = pending;
990            self.cursor = cursor;
991            match outcome {
992                Ok(Some((msg, cursor))) => {
993                    self.cursor = 0;
994                    self.pending.drain(..cursor);
995                    Ok(Some(msg))
996                }
997                Ok(None) => {
998                    self.compact();
999                    Ok(None)
1000                }
1001                Err(e) => {
1002                    // A budget error was produced by a header that
1003                    // validated but whose chunk did not commit: re-parsing
1004                    // the same bytes would count the declaration again, so
1005                    // never resume consuming after one — the caller must
1006                    // treat it as terminal (the error is unrecoverable for
1007                    // this connection anyway).
1008                    self.compact();
1009                    Err(e)
1010                }
1011            }
1012        }
1013    }
1014
1015    /// Physically drop the front `self.cursor` bytes of `pending` (the
1016    /// prefix already consumed by chunks parsed earlier in this call) and
1017    /// reset the cursor to 0. Called once per [`Self::next_message`]
1018    /// return, never per chunk inside its loop: a `Vec::drain` from the
1019    /// front is O(remaining length), so doing it once per *chunk* while a
1020    /// single message was still being reassembled out of many small chunks
1021    /// was, independently of the payload-clone cost, itself enough to make
1022    /// reassembly quadratic in the chunk count.
1023    ///
1024    /// A caller that switches chunk size between messages with
1025    /// [`set_chunk_size`](Self::set_chunk_size) calls this once first, so
1026    /// the bytes still buffered at the old size are re-fed and parsed at
1027    /// the new one.
1028    pub fn compact(&mut self) {
1029        if self.cursor > 0 {
1030            self.pending.drain(..self.cursor);
1031            self.cursor = 0;
1032        }
1033    }
1034
1035    /// Attempt to parse exactly one chunk (basic header + message header +
1036    /// any extended timestamp + its payload slice) from the front of `buf`,
1037    /// committing its resolved header fields and payload bytes directly into
1038    /// the owning csid's entry in `states`. Returns:
1039    /// - `Ok(Some(_))` — a full chunk was parsed and committed; `consumed`
1040    ///   bytes should be dropped from the front of the caller's buffer
1041    ///   (batched — see [`Self::compact`] — not per chunk).
1042    /// - `Ok(None)` — not enough bytes yet for a full chunk (structurally
1043    ///   plausible so far); caller should wait for more input. `states` is
1044    ///   left untouched.
1045    /// - `Err(_)` — structurally invalid input. `states` is left untouched.
1046    fn try_parse_one(
1047        buf: &[u8],
1048        states: &mut BTreeMap<ChunkStreamId, CsidState>,
1049        chunk_size: ChunkSize,
1050        in_progress_bytes: &mut usize,
1051        max_in_progress_bytes: usize,
1052    ) -> Result<Option<ParsedChunk>> {
1053        let bh = match BasicHeader::parse(buf) {
1054            Ok(bh) => bh,
1055            Err(RtmpError::BufferTooShort(..)) => return Ok(None),
1056            Err(e) => return Err(e),
1057        };
1058        // `BasicHeader::parse` having succeeded means `buf` holds at least
1059        // as many bytes as this form needs; re-derive that count from the
1060        // marker bits actually on the wire (not from `basic_header_form`,
1061        // which reflects the *minimal* form for the csid and may disagree
1062        // with a wire that legally used a longer form for a csid in the
1063        // 64..=319 overlap range).
1064        let marker = buf[0] & BASIC_HEADER_MARKER_MASK;
1065        let header_len = match marker {
1066            BASIC_HEADER_2BYTE_MARKER => 2,
1067            BASIC_HEADER_3BYTE_MARKER => 3,
1068            _ => 1,
1069        };
1070
1071        // Extract just the small, `Copy` header-inheritance fields (never
1072        // the payload itself — that would clone the whole accumulated
1073        // buffer just to *read* it) so this immutable peek at `states` ends
1074        // before the mutable commit further down needs it.
1075        let existing = states.get(&bh.chunk_stream_id).map(|s| ExistingHeader {
1076            timestamp: s.timestamp,
1077            timestamp_delta: s.timestamp_delta,
1078            message_length: s.message_length,
1079            message_type_id: s.message_type_id,
1080            message_stream_id: s.message_stream_id,
1081            extended: s.extended,
1082            in_progress: s.in_progress,
1083            accumulated_len: s.payload.len(),
1084        });
1085
1086        // Remote-DoS guard: a flood of chunks opening distinct, previously
1087        // unseen csids would otherwise grow `states` without bound (one
1088        // `CsidState`, each with its own payload buffer, per bogus csid).
1089        // Reject before the caller ever inserts a new entry for this csid.
1090        if existing.is_none() && states.len() >= MAX_CSIDS {
1091            return Err(RtmpError::TooManyChunkStreams { max: MAX_CSIDS });
1092        }
1093
1094        let rest = &buf[header_len..];
1095        let (mh, mh_consumed) = match MessageHeader::parse(bh.fmt, rest) {
1096            Ok(v) => v,
1097            Err(RtmpError::BufferTooShort(..)) => return Ok(None),
1098            Err(e) => return Err(e),
1099        };
1100        let mut consumed = header_len + mh_consumed;
1101
1102        // Resolve this chunk's header fields (timestamp/length/type/stream
1103        // id/extended-flag) and whether it begins a new message or
1104        // continues the one already in progress on this csid.
1105        let (resolved, starts_new) = match (bh.fmt, mh) {
1106            (
1107                Fmt::Type0,
1108                MessageHeader::Type0 {
1109                    timestamp,
1110                    message_length,
1111                    message_type_id,
1112                    message_stream_id,
1113                },
1114            ) => {
1115                let used_extended = mh_consumed > TYPE0_LEN;
1116                (
1117                    ResolvedHeader {
1118                        // §3.1.2: a Type 3 immediately following this Type 0
1119                        // (no intervening Type 1/2) implies a delta equal to
1120                        // this Type 0's own absolute timestamp.
1121                        timestamp_delta: timestamp.span(),
1122                        timestamp,
1123                        message_length,
1124                        message_type_id,
1125                        message_stream_id,
1126                        extended: used_extended,
1127                    },
1128                    true,
1129                )
1130            }
1131            // #1108/RTMP-W3 (was TODO #738 follow-up): a Type 1/2 header
1132            // arriving while a message is already `in_progress` on this
1133            // csid (a header interleaved mid-message, rather than at a
1134            // message boundary) used to go undetected here — it silently
1135            // reset `payload`/state and dropped the in-flight bytes rather
1136            // than erroring. Real streams shouldn't do this, but a
1137            // malformed/desynced one could, and (combined with RTMP-W2's
1138            // Abort bug) the two resync paths disagreed with each other.
1139            (
1140                Fmt::Type1,
1141                MessageHeader::Type1 {
1142                    timestamp_delta,
1143                    message_length,
1144                    message_type_id,
1145                },
1146            ) => {
1147                let existing = existing.ok_or(RtmpError::ChunkStreamState {
1148                    chunk_stream_id: bh.chunk_stream_id.get(),
1149                    what: "type 1 header with no prior chunk to inherit from",
1150                })?;
1151                if existing.in_progress {
1152                    return Err(RtmpError::ChunkStreamState {
1153                        chunk_stream_id: bh.chunk_stream_id.get(),
1154                        what: "type 1 header mid-message",
1155                    });
1156                }
1157                let used_extended = mh_consumed > TYPE1_LEN;
1158                (
1159                    ResolvedHeader {
1160                        timestamp: existing.timestamp.checked_add(timestamp_delta).ok_or(
1161                            RtmpError::FieldOverflow(broadcast_common::len::FieldOverflow {
1162                                field: "timestamp",
1163                                value: existing.timestamp.millis() as u64
1164                                    + delta_millis(timestamp_delta) as u64,
1165                                max: u64::from(u32::MAX),
1166                            }),
1167                        )?,
1168                        timestamp_delta,
1169                        message_length,
1170                        message_type_id,
1171                        message_stream_id: existing.message_stream_id,
1172                        extended: used_extended,
1173                    },
1174                    true,
1175                )
1176            }
1177            (Fmt::Type2, MessageHeader::Type2 { timestamp_delta }) => {
1178                let existing = existing.ok_or(RtmpError::ChunkStreamState {
1179                    chunk_stream_id: bh.chunk_stream_id.get(),
1180                    what: "type 2 header with no prior chunk to inherit from",
1181                })?;
1182                if existing.in_progress {
1183                    return Err(RtmpError::ChunkStreamState {
1184                        chunk_stream_id: bh.chunk_stream_id.get(),
1185                        what: "type 2 header mid-message",
1186                    });
1187                }
1188                let used_extended = mh_consumed > TYPE2_LEN;
1189                let message_type_id =
1190                    existing
1191                        .message_type_id
1192                        .ok_or(RtmpError::ChunkStreamState {
1193                            chunk_stream_id: bh.chunk_stream_id.get(),
1194                            what: "type 2 header with no message type id to inherit",
1195                        })?;
1196                (
1197                    ResolvedHeader {
1198                        timestamp: existing.timestamp.checked_add(timestamp_delta).ok_or(
1199                            RtmpError::FieldOverflow(broadcast_common::len::FieldOverflow {
1200                                field: "timestamp",
1201                                value: existing.timestamp.millis() as u64
1202                                    + delta_millis(timestamp_delta) as u64,
1203                                max: u64::from(u32::MAX),
1204                            }),
1205                        )?,
1206                        timestamp_delta,
1207                        message_length: existing.message_length,
1208                        message_type_id,
1209                        message_stream_id: existing.message_stream_id,
1210                        extended: used_extended,
1211                    },
1212                    true,
1213                )
1214            }
1215            (Fmt::Type3, MessageHeader::Type3) => {
1216                let existing = existing.ok_or(RtmpError::ChunkStreamState {
1217                    chunk_stream_id: bh.chunk_stream_id.get(),
1218                    what: "type 3 header with no prior chunk to inherit from",
1219                })?;
1220                let continuation = existing.in_progress;
1221                let message_type_id =
1222                    existing
1223                        .message_type_id
1224                        .ok_or(RtmpError::ChunkStreamState {
1225                            chunk_stream_id: bh.chunk_stream_id.get(),
1226                            what: "type 3 header with no message type id to inherit",
1227                        })?;
1228                if existing.extended {
1229                    if buf.len() < consumed + EXTENDED_TIMESTAMP_LEN {
1230                        return Ok(None);
1231                    }
1232                    // Present per §3.1.3 whenever the most recent Type 0/1/2
1233                    // on this csid used one. A continuation chunk's message
1234                    // timestamp is already fixed (ignore the value); a
1235                    // new-message Type 3 re-applies the inherited delta
1236                    // (also ignoring the value: Type 3 has nothing of its
1237                    // own to contribute, by definition it inherits).
1238                    consumed += EXTENDED_TIMESTAMP_LEN;
1239                }
1240                if continuation {
1241                    (
1242                        ResolvedHeader {
1243                            timestamp: existing.timestamp,
1244                            timestamp_delta: existing.timestamp_delta,
1245                            message_length: existing.message_length,
1246                            message_type_id,
1247                            message_stream_id: existing.message_stream_id,
1248                            extended: existing.extended,
1249                        },
1250                        false,
1251                    )
1252                } else {
1253                    (
1254                        ResolvedHeader {
1255                            timestamp: existing
1256                                .timestamp
1257                                .checked_add(existing.timestamp_delta)
1258                                .ok_or(RtmpError::FieldOverflow(
1259                                    broadcast_common::len::FieldOverflow {
1260                                        field: "timestamp",
1261                                        value: existing.timestamp.millis() as u64
1262                                            + delta_millis(existing.timestamp_delta) as u64,
1263                                        max: u64::from(u32::MAX),
1264                                    },
1265                                ))?,
1266                            timestamp_delta: existing.timestamp_delta,
1267                            message_length: existing.message_length,
1268                            message_type_id,
1269                            message_stream_id: existing.message_stream_id,
1270                            extended: existing.extended,
1271                        },
1272                        true,
1273                    )
1274                }
1275            }
1276            // `MessageHeader::parse` is called with `bh.fmt` above, so it
1277            // returns the variant that matches that `Fmt`; any other pairing
1278            // is a programming error, surfaced as a typed state error rather
1279            // than a panic.
1280            _ => {
1281                return Err(RtmpError::ChunkStreamState {
1282                    chunk_stream_id: bh.chunk_stream_id.get(),
1283                    what: "message header variant does not match its fmt",
1284                });
1285            }
1286        };
1287
1288        // Remote-DoS guard: `message_length` is a fully peer-supplied
1289        // 24-bit wire field (Type 0/1 headers set it directly; Type 2/3
1290        // inherit an already-checked value). Reject before any payload
1291        // buffer for this message is allocated — see `MAX_MESSAGE_LEN`'s
1292        // doc for why this bound is safe for real RTMP traffic.
1293        if resolved.message_length > MAX_MESSAGE_LEN {
1294            return Err(RtmpError::FieldOverflow(
1295                broadcast_common::len::FieldOverflow {
1296                    field: "message_length",
1297                    value: u64::from(resolved.message_length),
1298                    max: u64::from(MAX_MESSAGE_LEN),
1299                },
1300            ));
1301        }
1302
1303        let already_accumulated = if starts_new {
1304            0
1305        } else {
1306            existing.map(|s| s.accumulated_len).unwrap_or(0)
1307        };
1308        let remaining_needed =
1309            (resolved.message_length as usize).saturating_sub(already_accumulated);
1310        let take = usize::try_from(chunk_size.value())
1311            .unwrap_or(usize::MAX)
1312            .min(remaining_needed);
1313
1314        // #1108/RTMP-W1 aggregate budget. A new message reserves its full
1315        // declared length when its header validates (before the payload
1316        // arrives: hoarding hides in bytes that never come); the
1317        // reservation is released on completion or abort. Continuation
1318        // chunks never re-reserve. Idempotent: a header re-parsed because
1319        // its payload was incomplete finds `reserved` equal to its own
1320        // declaration and nets zero. A rejected header records nothing.
1321        if starts_new {
1322            let prior = states
1323                .get(&bh.chunk_stream_id)
1324                .and_then(|s| s.reserved)
1325                .unwrap_or(0) as usize;
1326            let new_total = in_progress_bytes
1327                .saturating_sub(prior)
1328                .saturating_add(resolved.message_length as usize);
1329            if new_total > max_in_progress_bytes {
1330                return Err(RtmpError::InputBudgetExceeded {
1331                    max: max_in_progress_bytes,
1332                });
1333            }
1334            *in_progress_bytes = new_total;
1335            states.entry(bh.chunk_stream_id).or_default().reserved = Some(resolved.message_length);
1336        }
1337
1338        if buf.len() < consumed + take {
1339            return Ok(None);
1340        }
1341
1342        // Commit: append this chunk's bytes directly into the owning
1343        // csid's own persistent payload buffer — no
1344        // `Vec::with_capacity(resolved.message_length)` (that would
1345        // pre-reserve up to `MAX_MESSAGE_LEN` bytes off a single peer-
1346        // supplied header field before a single payload byte has actually
1347        // arrived) and, critically, no clone of the bytes already
1348        // accumulated (the previous version built a brand-new Vec by
1349        // cloning the whole in-progress payload on every continuation
1350        // chunk, which is what made reassembly O(`message_length`^2 /
1351        // `chunk_size`)).
1352        let state = states.entry(bh.chunk_stream_id).or_default();
1353        state.timestamp = resolved.timestamp;
1354        state.timestamp_delta = resolved.timestamp_delta;
1355        state.message_length = resolved.message_length;
1356        state.message_type_id = Some(resolved.message_type_id);
1357        state.message_stream_id = resolved.message_stream_id;
1358        state.extended = resolved.extended;
1359        state.initialized = true;
1360        if starts_new {
1361            state.payload.clear();
1362        }
1363        state
1364            .payload
1365            .extend_from_slice(&buf[consumed..consumed + take]);
1366        #[cfg(test)]
1367        record_payload_bytes_copied_for_test(take);
1368        state.in_progress = state.payload.len() as u32 != state.message_length;
1369        consumed += take;
1370
1371        Ok(Some(ParsedChunk {
1372            csid: bh.chunk_stream_id,
1373            consumed,
1374        }))
1375    }
1376}
1377
1378/// The small, `Copy` subset of [`CsidState`] a chunk's header-inheritance
1379/// resolution needs to read — deliberately excludes `payload` itself
1380/// (`accumulated_len` carries only its *length*) so reading it never clones
1381/// the accumulated buffer.
1382#[derive(Clone, Copy)]
1383struct ExistingHeader {
1384    timestamp: Timestamp,
1385    timestamp_delta: Duration,
1386    message_length: u32,
1387    message_type_id: Option<MessageTypeId>,
1388    message_stream_id: MessageStreamId,
1389    extended: bool,
1390    in_progress: bool,
1391    accumulated_len: usize,
1392}
1393
1394/// Header fields resolved for one chunk, after applying `fmt`-specific
1395/// inheritance from the csid's prior state.
1396struct ResolvedHeader {
1397    timestamp: Timestamp,
1398    timestamp_delta: Duration,
1399    message_length: u32,
1400    message_type_id: MessageTypeId,
1401    message_stream_id: MessageStreamId,
1402    extended: bool,
1403}
1404
1405/// Outcome of one [`ChunkAssembler::try_parse_one`] call: its header fields
1406/// and payload bytes have already been committed to the owning csid's
1407/// [`CsidState`] by the time this is returned — the caller only needs
1408/// `consumed` (to advance its read cursor) and `csid` (to look the state
1409/// back up and check for message completion).
1410struct ParsedChunk {
1411    csid: ChunkStreamId,
1412    consumed: usize,
1413}
1414
1415// ── ChunkWriter (outbound, §5.3) ─────────────────────────────────────────
1416
1417/// Stateless-per-message outbound chunk writer (§5.3): serializes a
1418/// [`Message`] into chunk bytes at the current chunk size.
1419///
1420/// Simple, always-correct strategy: the first chunk is always Type 0 (full
1421/// absolute-timestamp header) and every continuation chunk is Type 3
1422/// (0-byte header, inheriting everything). This is spec-valid — Type 1/2's
1423/// more compact delta-based headers are a size optimisation this writer
1424/// does not perform.
1425#[derive(Debug, Clone)]
1426pub struct ChunkWriter {
1427    chunk_size: ChunkSize,
1428}
1429
1430impl Default for ChunkWriter {
1431    fn default() -> Self {
1432        Self::new()
1433    }
1434}
1435
1436impl ChunkWriter {
1437    /// New writer, chunk size at the §5.3 default (128 bytes).
1438    #[must_use]
1439    pub fn new() -> Self {
1440        Self {
1441            chunk_size: DEFAULT_CHUNK_SIZE,
1442        }
1443    }
1444
1445    /// Update the chunk size used for subsequent [`ChunkWriter::write`]
1446    /// calls (called on sending a Set Chunk Size protocol control message,
1447    /// §5.4.1). The value is adopted verbatim — a validated [`ChunkSize`]
1448    /// is never clamped — so the framing always matches the size the
1449    /// matching Set Chunk Size message announced.
1450    pub fn set_chunk_size(&mut self, chunk_size: ChunkSize) {
1451        self.chunk_size = chunk_size;
1452    }
1453
1454    /// Serialize `msg` into chunk bytes at the current chunk size: a Type 0
1455    /// first chunk carrying up to `chunk_size` payload bytes, then Type 3
1456    /// continuation chunks for the remainder.
1457    ///
1458    /// # Errors
1459    /// Returns [`RtmpError::FieldOverflow`] if `msg.payload` is 16 MiB
1460    /// (2^24) or larger — `message_length` is a UI24 field (§5.3.1.2) and
1461    /// cannot represent it (#1129: unfixed, `payload.len() as u32` then the
1462    /// UI24 writer silently kept only the low 24 bits, misframing every
1463    /// later message on the chunk stream).
1464    ///
1465    /// Returns [`RtmpError::InvalidChunkStreamId`] if `msg.chunk_stream_id`
1466    /// is outside the basic header's encodable range (2..=65599). Every
1467    /// `chunk_stream_id` produced by [`ChunkAssembler::push`] satisfies this
1468    /// (`BasicHeader::parse` never yields one outside the range); callers
1469    /// building a `Message` from scratch must respect it.
1470    pub fn write(&mut self, msg: &Message) -> Result<Vec<u8>> {
1471        if !msg.chunk_stream_id.basic_header_encodable() {
1472            return Err(RtmpError::InvalidChunkStreamId {
1473                chunk_stream_id: msg.chunk_stream_id.get(),
1474            });
1475        }
1476        let chunk_size = usize::try_from(self.chunk_size.value()).unwrap_or(usize::MAX);
1477        let message_length = broadcast_common::len::fit_u24(msg.payload.len(), "message_length")?;
1478        let extended = needs_extended_timestamp(msg.timestamp.millis());
1479
1480        let mut out = Vec::with_capacity(TYPE0_LEN + msg.payload.len() + 16);
1481
1482        let bh0 = BasicHeader {
1483            fmt: Fmt::Type0,
1484            chunk_stream_id: msg.chunk_stream_id,
1485        };
1486        let mh0 = MessageHeader::Type0 {
1487            timestamp: msg.timestamp,
1488            message_length,
1489            message_type_id: msg.message_type_id,
1490            message_stream_id: msg.message_stream_id,
1491        };
1492        write_serialized(&mut out, &bh0)?;
1493        write_serialized(&mut out, &mh0)?;
1494
1495        let mut offset = 0usize;
1496        let take0 = chunk_size.min(msg.payload.len());
1497        out.extend_from_slice(&msg.payload[offset..offset + take0]);
1498        offset += take0;
1499
1500        while offset < msg.payload.len() {
1501            let bh = BasicHeader {
1502                fmt: Fmt::Type3,
1503                chunk_stream_id: msg.chunk_stream_id,
1504            };
1505            write_serialized(&mut out, &bh)?;
1506            if extended {
1507                out.extend_from_slice(&msg.timestamp.millis().to_be_bytes());
1508            }
1509            let take = chunk_size.min(msg.payload.len() - offset);
1510            out.extend_from_slice(&msg.payload[offset..offset + take]);
1511            offset += take;
1512        }
1513
1514        Ok(out)
1515    }
1516}
1517
1518/// Serialize `item` and append the bytes to `out`.
1519///
1520/// # Errors
1521/// Propagates `item.serialize_into`'s error (for the [`BasicHeader`]s this is
1522/// used with, a `chunk_stream_id` outside the encodable range).
1523fn write_serialized<T: Serialize<Error = RtmpError>>(out: &mut Vec<u8>, item: &T) -> Result<()> {
1524    let len = item.serialized_len();
1525    let start = out.len();
1526    out.resize(start + len, 0);
1527    match item.serialize_into(&mut out[start..]) {
1528        Ok(n) => {
1529            out.truncate(start + n);
1530            Ok(())
1531        }
1532        Err(e) => {
1533            out.truncate(start);
1534            Err(e)
1535        }
1536    }
1537}
1538
1539/// Test-only infallible wrapper over [`write_serialized`].
1540#[cfg(test)]
1541fn write_serialized_ok<T: Serialize<Error = RtmpError>>(out: &mut Vec<u8>, item: &T) {
1542    write_serialized(out, item).expect("valid chunk_stream_id in test fixture");
1543}
1544
1545#[cfg(test)]
1546thread_local! {
1547    /// Total payload bytes [`ChunkAssembler::try_parse_one`] has appended
1548    /// via `extend_from_slice` on this thread since the last reset — a
1549    /// test-only instrumentation hook so a regression test can assert
1550    /// reassembly does O(message length) work directly, rather than
1551    /// inferring it from wall-clock time (see
1552    /// `reassembling_an_8mib_message_at_the_floor_chunk_size_is_linear_not_quadratic`).
1553    static PAYLOAD_BYTES_COPIED_FOR_TEST: core::cell::Cell<usize> = const { core::cell::Cell::new(0) };
1554}
1555
1556#[cfg(test)]
1557fn record_payload_bytes_copied_for_test(n: usize) {
1558    PAYLOAD_BYTES_COPIED_FOR_TEST.with(|c| c.set(c.get() + n));
1559}
1560
1561#[cfg(test)]
1562fn reset_payload_bytes_copied_for_test() {
1563    PAYLOAD_BYTES_COPIED_FOR_TEST.with(|c| c.set(0));
1564}
1565
1566#[cfg(test)]
1567fn payload_bytes_copied_for_test() -> usize {
1568    PAYLOAD_BYTES_COPIED_FOR_TEST.with(core::cell::Cell::get)
1569}
1570
1571#[cfg(test)]
1572mod tests {
1573    use broadcast_common::error::BufferTooShort;
1574
1575    use super::*;
1576
1577    // ── u24 helper ───────────────────────────────────────────────────────
1578
1579    #[test]
1580    fn u24_round_trip_zero() {
1581        let mut buf = [0xFFu8; U24_LEN];
1582        write_u24_be(0, &mut buf, "t").unwrap();
1583        assert_eq!(buf, [0, 0, 0]);
1584        assert_eq!(read_u24_be(&buf), 0);
1585    }
1586
1587    #[test]
1588    fn u24_round_trip_max() {
1589        let mut buf = [0u8; U24_LEN];
1590        write_u24_be(0x00FF_FFFF, &mut buf, "t").unwrap();
1591        assert_eq!(buf, [0xFF, 0xFF, 0xFF]);
1592        assert_eq!(read_u24_be(&buf), 0x00FF_FFFF);
1593    }
1594
1595    /// #2269: a too-small output buffer is an output-buffer error, not a
1596    /// parse-side input-truncation error.
1597    #[test]
1598    fn serialize_into_too_small_output_reports_output_buffer_error() {
1599        let basic = BasicHeader {
1600            fmt: Fmt::Type0,
1601            chunk_stream_id: ChunkStreamId::new(9),
1602        };
1603        let mut buf = [0u8; 0];
1604        assert!(matches!(
1605            basic.serialize_into(&mut buf),
1606            Err(RtmpError::OutputBufferTooSmall(_))
1607        ));
1608
1609        let hdr = MessageHeader::Type0 {
1610            timestamp: Timestamp::from_millis(0),
1611            message_length: 16,
1612            message_type_id: MessageTypeId::Video,
1613            message_stream_id: MessageStreamId::new(1),
1614        };
1615        let mut buf = [0u8; TYPE0_LEN - 1];
1616        assert!(matches!(
1617            hdr.serialize_into(&mut buf),
1618            Err(RtmpError::OutputBufferTooSmall(_))
1619        ));
1620
1621        let hdr = MessageHeader::Type1 {
1622            timestamp_delta: Duration::from_millis(0),
1623            message_length: 16,
1624            message_type_id: MessageTypeId::Video,
1625        };
1626        let mut buf = [0u8; TYPE1_LEN - 1];
1627        assert!(matches!(
1628            hdr.serialize_into(&mut buf),
1629            Err(RtmpError::OutputBufferTooSmall(_))
1630        ));
1631
1632        let hdr = MessageHeader::Type2 {
1633            timestamp_delta: Duration::ZERO,
1634        };
1635        let mut buf = [0u8; TYPE2_LEN - 1];
1636        assert!(matches!(
1637            hdr.serialize_into(&mut buf),
1638            Err(RtmpError::OutputBufferTooSmall(_))
1639        ));
1640    }
1641
1642    /// #1129: a `message_length` above 24 bits is an error, not masked.
1643    #[test]
1644    fn message_length_over_24_bits_is_rejected_not_masked() {
1645        let mut buf = [0u8; 16];
1646        for hdr in [
1647            MessageHeader::Type0 {
1648                timestamp: Timestamp::from_millis(0),
1649                message_length: 0x0100_0000,
1650                message_type_id: MessageTypeId::Video,
1651                message_stream_id: MessageStreamId::new(1),
1652            },
1653            MessageHeader::Type1 {
1654                timestamp_delta: Duration::from_millis(0),
1655                message_length: 0x0100_0000,
1656                message_type_id: MessageTypeId::Video,
1657            },
1658        ] {
1659            assert!(matches!(
1660                hdr.serialize_into(&mut buf),
1661                Err(RtmpError::FieldOverflow(_))
1662            ));
1663        }
1664        let ok = MessageHeader::Type1 {
1665            timestamp_delta: Duration::from_millis(0),
1666            message_length: 0x00FF_FFFF,
1667            message_type_id: MessageTypeId::Video,
1668        };
1669        assert!(ok.serialize_into(&mut buf).is_ok());
1670    }
1671
1672    #[test]
1673    fn u24_round_trip_mid_value() {
1674        let mut buf = [0u8; U24_LEN];
1675        write_u24_be(0x0012_3456, &mut buf, "t").unwrap();
1676        assert_eq!(buf, [0x12, 0x34, 0x56]);
1677        assert_eq!(read_u24_be(&buf), 0x0012_3456);
1678    }
1679
1680    // ── Fmt ──────────────────────────────────────────────────────────────
1681
1682    #[test]
1683    fn fmt_from_bits_round_trip() {
1684        for (bits, fmt) in [
1685            (0u8, Fmt::Type0),
1686            (1, Fmt::Type1),
1687            (2, Fmt::Type2),
1688            (3, Fmt::Type3),
1689        ] {
1690            let parsed = Fmt::from_bits(bits).unwrap();
1691            assert_eq!(parsed, fmt);
1692            assert_eq!(parsed.to_bits(), bits);
1693        }
1694    }
1695
1696    #[test]
1697    fn fmt_from_bits_out_of_range_is_malformed() {
1698        assert!(matches!(
1699            Fmt::from_bits(4),
1700            Err(RtmpError::Malformed { .. })
1701        ));
1702    }
1703
1704    #[test]
1705    fn fmt_display_matches_name() {
1706        assert_eq!(Fmt::Type0.to_string(), "type 0");
1707        assert_eq!(Fmt::Type3.to_string(), "type 3");
1708    }
1709
1710    // ── BasicHeader: 1-byte form ─────────────────────────────────────────
1711
1712    #[test]
1713    fn basic_header_one_byte_form_round_trip_build_serialize_parse() {
1714        for csid in [BASIC_HEADER_1BYTE_MIN_CSID, 5, BASIC_HEADER_1BYTE_MAX_CSID] {
1715            let bh = BasicHeader {
1716                fmt: Fmt::Type1,
1717                chunk_stream_id: ChunkStreamId::new(csid),
1718            };
1719            let mut buf = [0u8; 1];
1720            let n = bh.serialize_into(&mut buf).unwrap();
1721            assert_eq!(n, 1, "csid {csid} must use the 1-byte form");
1722            let parsed = BasicHeader::parse(&buf).unwrap();
1723            assert_eq!(parsed, bh);
1724        }
1725    }
1726
1727    #[test]
1728    fn basic_header_one_byte_form_parse_serialize_byte_identical() {
1729        // fmt=1 (bits 01), csid=5: byte0 = 0b01_000101 = 0x45.
1730        let bytes = [0x45u8];
1731        let bh = BasicHeader::parse(&bytes).unwrap();
1732        assert_eq!(bh.fmt, Fmt::Type1);
1733        assert_eq!(bh.chunk_stream_id.get(), 5);
1734        let mut buf = [0u8; 1];
1735        bh.serialize_into(&mut buf).unwrap();
1736        assert_eq!(buf, bytes);
1737    }
1738
1739    // ── BasicHeader: 2-byte form ─────────────────────────────────────────
1740
1741    #[test]
1742    fn basic_header_two_byte_form_round_trip_boundaries() {
1743        for csid in [
1744            BASIC_HEADER_2BYTE_MIN_CSID,
1745            200,
1746            BASIC_HEADER_2BYTE_MAX_CSID,
1747        ] {
1748            let bh = BasicHeader {
1749                fmt: Fmt::Type2,
1750                chunk_stream_id: ChunkStreamId::new(csid),
1751            };
1752            let mut buf = [0u8; 2];
1753            let n = bh.serialize_into(&mut buf).unwrap();
1754            assert_eq!(n, 2, "csid {csid} must use the minimal 2-byte form");
1755            let parsed = BasicHeader::parse(&buf).unwrap();
1756            assert_eq!(parsed, bh);
1757        }
1758    }
1759
1760    #[test]
1761    fn basic_header_two_byte_form_parse_serialize_byte_identical() {
1762        // fmt=2 (bits 10), marker 0, csid-64 = 0 => csid 64.
1763        let bytes = [0b10_000000u8, 0x00];
1764        let bh = BasicHeader::parse(&bytes).unwrap();
1765        assert_eq!(bh.fmt, Fmt::Type2);
1766        assert_eq!(bh.chunk_stream_id.get(), 64);
1767        let mut buf = [0u8; 2];
1768        bh.serialize_into(&mut buf).unwrap();
1769        assert_eq!(buf, bytes);
1770    }
1771
1772    // ── BasicHeader: 3-byte form ─────────────────────────────────────────
1773
1774    #[test]
1775    fn basic_header_three_byte_form_round_trip_boundaries() {
1776        for csid in [
1777            BASIC_HEADER_3BYTE_MIN_CSID,
1778            40000,
1779            BASIC_HEADER_3BYTE_MAX_CSID,
1780        ] {
1781            let bh = BasicHeader {
1782                fmt: Fmt::Type3,
1783                chunk_stream_id: ChunkStreamId::new(csid),
1784            };
1785            let mut buf = [0u8; 3];
1786            let n = bh.serialize_into(&mut buf).unwrap();
1787            assert_eq!(n, 3, "csid {csid} must use the 3-byte form");
1788            let parsed = BasicHeader::parse(&buf).unwrap();
1789            assert_eq!(parsed, bh);
1790        }
1791    }
1792
1793    #[test]
1794    fn basic_header_three_byte_form_parse_serialize_byte_identical() {
1795        // fmt=0, marker 1, csid-64 = 0xFFFF (LE: byte1=0xFF, byte2=0xFF) => csid 65599.
1796        let bytes = [0b00_000001u8, 0xFF, 0xFF];
1797        let bh = BasicHeader::parse(&bytes).unwrap();
1798        assert_eq!(bh.fmt, Fmt::Type0);
1799        assert_eq!(bh.chunk_stream_id.get(), BASIC_HEADER_3BYTE_MAX_CSID);
1800        let mut buf = [0u8; 3];
1801        bh.serialize_into(&mut buf).unwrap();
1802        assert_eq!(buf, bytes);
1803    }
1804
1805    #[test]
1806    fn basic_header_2byte_and_3byte_csid_are_little_endian() {
1807        // csid = 64 + 0x0102 = 0x0142 = 322. 3-byte form: byte1=low=0x02, byte2=high=0x01.
1808        let bh = BasicHeader {
1809            fmt: Fmt::Type0,
1810            chunk_stream_id: ChunkStreamId::new(64 + 0x0102),
1811        };
1812        let mut buf = [0u8; 3];
1813        bh.serialize_into(&mut buf).unwrap();
1814        assert_eq!(buf[1], 0x02, "low byte of csid-64 must come first");
1815        assert_eq!(buf[2], 0x01, "high byte of csid-64 must come second");
1816        assert_eq!(BasicHeader::parse(&buf).unwrap(), bh);
1817    }
1818
1819    // ── BasicHeader: errors ──────────────────────────────────────────────
1820
1821    #[test]
1822    fn basic_header_csid_zero_is_malformed_on_serialize() {
1823        let bh = BasicHeader {
1824            fmt: Fmt::Type0,
1825            chunk_stream_id: ChunkStreamId::new(0),
1826        };
1827        let mut buf = [0u8; 3];
1828        assert!(matches!(
1829            bh.serialize_into(&mut buf),
1830            Err(RtmpError::Malformed { .. })
1831        ));
1832    }
1833
1834    #[test]
1835    fn basic_header_csid_one_is_malformed_on_serialize() {
1836        let bh = BasicHeader {
1837            fmt: Fmt::Type0,
1838            chunk_stream_id: ChunkStreamId::new(1),
1839        };
1840        let mut buf = [0u8; 3];
1841        assert!(matches!(
1842            bh.serialize_into(&mut buf),
1843            Err(RtmpError::Malformed { .. })
1844        ));
1845    }
1846
1847    #[test]
1848    fn basic_header_csid_above_max_is_malformed_on_serialize() {
1849        let bh = BasicHeader {
1850            fmt: Fmt::Type0,
1851            chunk_stream_id: ChunkStreamId::new(BASIC_HEADER_3BYTE_MAX_CSID + 1),
1852        };
1853        let mut buf = [0u8; 3];
1854        assert!(matches!(
1855            bh.serialize_into(&mut buf),
1856            Err(RtmpError::Malformed { .. })
1857        ));
1858    }
1859
1860    #[test]
1861    fn basic_header_empty_input_is_buffer_too_short() {
1862        assert!(matches!(
1863            BasicHeader::parse(&[]),
1864            Err(RtmpError::BufferTooShort(BufferTooShort {
1865                need: 1,
1866                have: 0,
1867                ..
1868            }))
1869        ));
1870    }
1871
1872    #[test]
1873    fn basic_header_truncated_two_byte_form_is_buffer_too_short() {
1874        let bytes = [0b00_000000u8]; // marker=0 (2-byte form) but only 1 byte given.
1875        assert!(matches!(
1876            BasicHeader::parse(&bytes),
1877            Err(RtmpError::BufferTooShort(BufferTooShort {
1878                need: 2,
1879                have: 1,
1880                ..
1881            }))
1882        ));
1883    }
1884
1885    #[test]
1886    fn basic_header_truncated_three_byte_form_is_buffer_too_short() {
1887        let bytes = [0b00_000001u8, 0xAB]; // marker=1 (3-byte form) but only 2 bytes given.
1888        assert!(matches!(
1889            BasicHeader::parse(&bytes),
1890            Err(RtmpError::BufferTooShort(BufferTooShort {
1891                need: 3,
1892                have: 2,
1893                ..
1894            }))
1895        ));
1896    }
1897
1898    // ── MessageHeader: Type 0 ────────────────────────────────────────────
1899
1900    #[test]
1901    fn type0_round_trip_build_serialize_parse_no_extended() {
1902        let mh = MessageHeader::Type0 {
1903            timestamp: Timestamp::from_millis(0x0011_2233),
1904            message_length: 0x0004_5566,
1905            message_type_id: MessageTypeId::Video,
1906            message_stream_id: MessageStreamId::new(0xAABB_CCDD),
1907        };
1908        let mut buf = [0u8; TYPE0_LEN];
1909        let n = mh.serialize_into(&mut buf).unwrap();
1910        assert_eq!(n, TYPE0_LEN);
1911        let (parsed, consumed) = MessageHeader::parse(Fmt::Type0, &buf).unwrap();
1912        assert_eq!(consumed, TYPE0_LEN);
1913        assert_eq!(parsed, mh);
1914    }
1915
1916    #[test]
1917    fn type0_parse_serialize_byte_identical_no_extended_and_le_stream_id() {
1918        // timestamp = 0x001122 (< marker, no extension).
1919        // message_length = 0x334455.
1920        // message_type_id = 0x09.
1921        // message_stream_id = 0xAABBCCDD, wire LE => DD CC BB AA.
1922        let bytes: [u8; TYPE0_LEN] = [
1923            0x00, 0x11, 0x22, // timestamp
1924            0x33, 0x44, 0x55, // message_length
1925            0x09, // message_type_id
1926            0xDD, 0xCC, 0xBB, 0xAA, // message_stream_id, little-endian
1927        ];
1928        let (mh, consumed) = MessageHeader::parse(Fmt::Type0, &bytes).unwrap();
1929        assert_eq!(consumed, TYPE0_LEN);
1930        assert_eq!(
1931            mh,
1932            MessageHeader::Type0 {
1933                timestamp: Timestamp::from_millis(0x0000_1122),
1934                message_length: 0x0033_4455,
1935                message_type_id: MessageTypeId::Video,
1936                message_stream_id: MessageStreamId::new(0xAABB_CCDD),
1937            }
1938        );
1939        let mut buf = [0u8; TYPE0_LEN];
1940        mh.serialize_into(&mut buf).unwrap();
1941        assert_eq!(
1942            buf, bytes,
1943            "byte-identical round trip, LE stream id included"
1944        );
1945    }
1946
1947    #[test]
1948    fn type0_extended_timestamp_parse_serialize_byte_identical() {
1949        // 24-bit timestamp field = sentinel 0xFFFFFF => extended 4-byte BE
1950        // timestamp follows, value 0x01020304 (chosen so BE != LE, catching
1951        // an endianness bug in the extended field).
1952        let bytes: [u8; TYPE0_LEN + 4] = [
1953            0xFF, 0xFF, 0xFF, // timestamp sentinel
1954            0x00, 0x00, 0x10, // message_length
1955            0x08, // message_type_id
1956            0x01, 0x00, 0x00, 0x00, // message_stream_id = 1, LE
1957            0x01, 0x02, 0x03, 0x04, // extended timestamp, big-endian
1958        ];
1959        let (mh, consumed) = MessageHeader::parse(Fmt::Type0, &bytes).unwrap();
1960        assert_eq!(consumed, TYPE0_LEN + 4);
1961        assert_eq!(
1962            mh,
1963            MessageHeader::Type0 {
1964                timestamp: Timestamp::from_millis(0x0102_0304),
1965                message_length: 0x0000_0010,
1966                message_type_id: MessageTypeId::Audio,
1967                message_stream_id: MessageStreamId::new(1),
1968            }
1969        );
1970        let mut buf = [0u8; TYPE0_LEN + 4];
1971        let n = mh.serialize_into(&mut buf).unwrap();
1972        assert_eq!(n, TYPE0_LEN + 4);
1973        assert_eq!(
1974            buf, bytes,
1975            "extended timestamp path must round-trip byte-identically"
1976        );
1977    }
1978
1979    #[test]
1980    fn type0_timestamp_exactly_at_marker_boundary_uses_extended_path() {
1981        // timestamp == EXTENDED_TIMESTAMP_MARKER exactly: per spec this MUST
1982        // still go through the extended-timestamp path (">=", not ">").
1983        let mh = MessageHeader::Type0 {
1984            timestamp: Timestamp::from_millis(EXTENDED_TIMESTAMP_MARKER),
1985            message_length: 10,
1986            message_type_id: MessageTypeId::SetChunkSize,
1987            message_stream_id: MessageStreamId::new(0),
1988        };
1989        assert_eq!(mh.serialized_len(), TYPE0_LEN + 4);
1990        let mut buf = [0u8; TYPE0_LEN + 4];
1991        let n = mh.serialize_into(&mut buf).unwrap();
1992        assert_eq!(n, TYPE0_LEN + 4);
1993        assert_eq!(
1994            &buf[0..3],
1995            [0xFF, 0xFF, 0xFF],
1996            "24-bit field must be the sentinel"
1997        );
1998        assert_eq!(
1999            &buf[11..15],
2000            &EXTENDED_TIMESTAMP_MARKER.to_be_bytes()[..],
2001            "extended field carries the real value"
2002        );
2003        let (parsed, consumed) = MessageHeader::parse(Fmt::Type0, &buf).unwrap();
2004        assert_eq!(consumed, TYPE0_LEN + 4);
2005        assert_eq!(parsed, mh);
2006    }
2007
2008    // ── MessageHeader: Type 1 ────────────────────────────────────────────
2009
2010    #[test]
2011    fn type1_round_trip_build_serialize_parse_no_extended() {
2012        let mh = MessageHeader::Type1 {
2013            timestamp_delta: Duration::from_millis(20),
2014            message_length: 32,
2015            message_type_id: MessageTypeId::Audio,
2016        };
2017        let mut buf = [0u8; TYPE1_LEN];
2018        let n = mh.serialize_into(&mut buf).unwrap();
2019        assert_eq!(n, TYPE1_LEN);
2020        let (parsed, consumed) = MessageHeader::parse(Fmt::Type1, &buf).unwrap();
2021        assert_eq!(consumed, TYPE1_LEN);
2022        assert_eq!(parsed, mh);
2023    }
2024
2025    #[test]
2026    fn type1_extended_timestamp_parse_serialize_byte_identical() {
2027        let bytes: [u8; TYPE1_LEN + 4] = [
2028            0xFF, 0xFF, 0xFF, // timestamp_delta sentinel
2029            0x00, 0x00, 0x20, // message_length
2030            0x09, // message_type_id
2031            0x0A, 0x0B, 0x0C, 0x0D, // extended timestamp delta, big-endian
2032        ];
2033        let (mh, consumed) = MessageHeader::parse(Fmt::Type1, &bytes).unwrap();
2034        assert_eq!(consumed, TYPE1_LEN + 4);
2035        assert_eq!(
2036            mh,
2037            MessageHeader::Type1 {
2038                timestamp_delta: Duration::from_millis(0x0A0B_0C0D),
2039                message_length: 0x0000_0020,
2040                message_type_id: MessageTypeId::Video,
2041            }
2042        );
2043        let mut buf = [0u8; TYPE1_LEN + 4];
2044        mh.serialize_into(&mut buf).unwrap();
2045        assert_eq!(buf, bytes);
2046    }
2047
2048    // ── MessageHeader: Type 2 ────────────────────────────────────────────
2049
2050    #[test]
2051    fn type2_round_trip_build_serialize_parse_no_extended() {
2052        let mh = MessageHeader::Type2 {
2053            timestamp_delta: Duration::from_millis(20),
2054        };
2055        let mut buf = [0u8; TYPE2_LEN];
2056        let n = mh.serialize_into(&mut buf).unwrap();
2057        assert_eq!(n, TYPE2_LEN);
2058        let (parsed, consumed) = MessageHeader::parse(Fmt::Type2, &buf).unwrap();
2059        assert_eq!(consumed, TYPE2_LEN);
2060        assert_eq!(parsed, mh);
2061    }
2062
2063    #[test]
2064    fn type2_extended_timestamp_parse_serialize_byte_identical() {
2065        let bytes: [u8; TYPE2_LEN + 4] = [
2066            0xFF, 0xFF, 0xFF, // timestamp_delta sentinel
2067            0x11, 0x22, 0x33, 0x44, // extended timestamp delta, big-endian
2068        ];
2069        let (mh, consumed) = MessageHeader::parse(Fmt::Type2, &bytes).unwrap();
2070        assert_eq!(consumed, TYPE2_LEN + 4);
2071        assert_eq!(
2072            mh,
2073            MessageHeader::Type2 {
2074                timestamp_delta: Duration::from_millis(0x1122_3344),
2075            }
2076        );
2077        let mut buf = [0u8; TYPE2_LEN + 4];
2078        mh.serialize_into(&mut buf).unwrap();
2079        assert_eq!(buf, bytes);
2080    }
2081
2082    // ── MessageHeader: Type 3 ────────────────────────────────────────────
2083
2084    #[test]
2085    fn type3_round_trip_is_zero_bytes() {
2086        let mh = MessageHeader::Type3;
2087        assert_eq!(mh.serialized_len(), 0);
2088        let mut buf: [u8; 0] = [];
2089        let n = mh.serialize_into(&mut buf).unwrap();
2090        assert_eq!(n, 0);
2091        let (parsed, consumed) = MessageHeader::parse(Fmt::Type3, &[]).unwrap();
2092        assert_eq!(consumed, 0);
2093        assert_eq!(parsed, MessageHeader::Type3);
2094    }
2095
2096    // ── MessageHeader: errors ────────────────────────────────────────────
2097
2098    #[test]
2099    fn type0_truncated_input_is_buffer_too_short() {
2100        let bytes = [0u8; TYPE0_LEN - 1];
2101        assert!(matches!(
2102            MessageHeader::parse(Fmt::Type0, &bytes),
2103            Err(RtmpError::BufferTooShort(BufferTooShort {
2104                need: TYPE0_LEN,
2105                ..
2106            }))
2107        ));
2108    }
2109
2110    #[test]
2111    fn type0_extended_marker_but_truncated_extended_field_is_buffer_too_short() {
2112        let mut bytes = [0u8; TYPE0_LEN + 2]; // only 2 of the 4 extended bytes.
2113        bytes[0] = 0xFF;
2114        bytes[1] = 0xFF;
2115        bytes[2] = 0xFF;
2116        assert!(matches!(
2117            MessageHeader::parse(Fmt::Type0, &bytes),
2118            Err(RtmpError::BufferTooShort(BufferTooShort {
2119                need,
2120                ..
2121            })) if need == TYPE0_LEN + 4
2122        ));
2123    }
2124
2125    // ── Mutation-check sentinels ─────────────────────────────────────────
2126    // These pin exact wire-byte expectations (not just self-round-trip),
2127    // so a serializer that silently drops the extended-timestamp tail, or
2128    // mis-orders the little-endian message_stream_id, fails a test above:
2129    // `type0_parse_serialize_byte_identical_no_extended_and_le_stream_id`
2130    // hand-builds its expected bytes with the stream id reversed from host
2131    // order, and `type0_extended_timestamp_parse_serialize_byte_identical`
2132    // hand-builds a 15-byte fixture whose length alone (`TYPE0_LEN + 4`)
2133    // fails if the extended tail is ever omitted.
2134
2135    #[test]
2136    fn message_stream_id_le_differs_from_be_for_asymmetric_value() {
2137        // Sanity check that our fixture value's LE and BE encodings differ,
2138        // so the byte-identical test above truly exercises endianness (a
2139        // palindromic value like 0x01010101 would pass either order).
2140        let v: u32 = 0xAABB_CCDD;
2141        assert_ne!(v.to_le_bytes(), v.to_be_bytes());
2142    }
2143
2144    // ── ChunkAssembler / ChunkWriter ─────────────────────────────────────
2145
2146    fn msg(
2147        csid: u32,
2148        timestamp_millis: u32,
2149        type_id: MessageTypeId,
2150        stream_id: u32,
2151        payload: Vec<u8>,
2152    ) -> Message {
2153        Message {
2154            chunk_stream_id: ChunkStreamId::new(csid),
2155            timestamp: Timestamp::from_millis(timestamp_millis),
2156            message_type_id: type_id,
2157            message_stream_id: MessageStreamId::new(stream_id),
2158            payload,
2159        }
2160    }
2161
2162    #[test]
2163    fn writer_assembler_round_trip_small_message_single_chunk() {
2164        let original = msg(4, 1000, MessageTypeId::Video, 1, vec![0xAB; 50]);
2165        let mut writer = ChunkWriter::new();
2166        let bytes = writer.write(&original).unwrap();
2167
2168        let mut assembler = ChunkAssembler::new();
2169        let out = assembler.push(&bytes).unwrap();
2170        assert_eq!(out.len(), 1, "one message must come back out");
2171        assert_eq!(out[0], original);
2172    }
2173
2174    /// A 16 MiB (2^24) payload cannot fit the 24-bit `message_length` field
2175    /// (#1129): unfixed, `payload.len() as u32` then the UI24 writer kept
2176    /// only the low 24 bits, silently misframing the chunk stream with `Ok`.
2177    #[test]
2178    fn write_oversized_payload_errors() {
2179        let original = msg(4, 0, MessageTypeId::Video, 1, vec![0xABu8; 1 << 24]);
2180        let err = ChunkWriter::new().write(&original).unwrap_err();
2181        assert!(
2182            matches!(
2183                err,
2184                RtmpError::FieldOverflow(broadcast_common::len::FieldOverflow {
2185                    field: "message_length",
2186                    ..
2187                })
2188            ),
2189            "expected FieldOverflow for message_length, got {err:?}"
2190        );
2191    }
2192
2193    /// The boundary: exactly (2^24 - 1) bytes still writes and reassembles.
2194    #[test]
2195    fn write_max_payload_message_length_field_is_exact() {
2196        // ChunkAssembler has its own, separate 8 MiB reassembly cap
2197        // (MAX_MESSAGE_LEN) below this field's 16 MiB wire max, so this
2198        // checks the written header bytes directly rather than
2199        // round-tripping through the assembler.
2200        let payload = vec![0xCDu8; (1 << 24) - 1];
2201        let original = msg(4, 0, MessageTypeId::Video, 1, payload.clone());
2202        let bytes = ChunkWriter::new().write(&original).unwrap();
2203
2204        // BasicHeader (1 byte, csid 4) + timestamp (3 bytes) precede
2205        // message_length (3 bytes, §5.3.1.2.1).
2206        let message_length = read_u24_be(&bytes[4..7]);
2207        assert_eq!(message_length, (1 << 24) - 1);
2208    }
2209
2210    #[test]
2211    fn writer_assembler_round_trip_message_larger_than_chunk_size() {
2212        // 300-byte payload at the default 128-byte chunk size => 3 chunks
2213        // (128 + 128 + 44): Type 0 first chunk, two Type 3 continuations.
2214        let original = msg(
2215            6,
2216            5000,
2217            MessageTypeId::Video,
2218            42,
2219            (0u8..=255).cycle().take(300).collect(),
2220        );
2221        let mut writer = ChunkWriter::new();
2222        let bytes = writer.write(&original).unwrap();
2223
2224        // Sanity: verify the byte stream really contains 3 chunks (1 basic
2225        // header for csid 6 is 1 byte; Type 0 header is TYPE0_LEN; then 128
2226        // payload bytes; then two Type 3 (1-byte basic header, 0-byte
2227        // message header) + payload chunks of 128 and 44).
2228        let expected_len = 1 + TYPE0_LEN + 128 + (1 + 128) + (1 + 44);
2229        assert_eq!(bytes.len(), expected_len);
2230
2231        let mut assembler = ChunkAssembler::new();
2232        let out = assembler.push(&bytes).unwrap();
2233        assert_eq!(
2234            out.len(),
2235            1,
2236            "the 3 chunks must reassemble into ONE message"
2237        );
2238        assert_eq!(out[0], original);
2239        assert_eq!(out[0].payload.len(), 300);
2240    }
2241
2242    #[test]
2243    fn assembler_multi_chunk_payload_reassembled_in_order() {
2244        // Hand-built stream: Type 0 header (csid 3, len 10, type 8, stream
2245        // 0, timestamp 0) with 4 payload bytes, chunk size forced to 4, then
2246        // two Type 3 continuations of 4 and 2 bytes — assert the payload
2247        // comes back concatenated in the right order, not reordered.
2248        let mut assembler = ChunkAssembler::new();
2249        assembler.set_chunk_size(ChunkSize::new(4).expect("a valid chunk size"));
2250
2251        let bh0 = BasicHeader {
2252            fmt: Fmt::Type0,
2253            chunk_stream_id: ChunkStreamId::new(9),
2254        };
2255        let mh0 = MessageHeader::Type0 {
2256            timestamp: Timestamp::from_millis(0),
2257            message_length: 10,
2258            message_type_id: MessageTypeId::Audio,
2259            message_stream_id: MessageStreamId::new(0),
2260        };
2261        let mut input = Vec::new();
2262        write_serialized_ok(&mut input, &bh0);
2263        write_serialized_ok(&mut input, &mh0);
2264        input.extend_from_slice(&[1, 2, 3, 4]);
2265
2266        let bh3 = BasicHeader {
2267            fmt: Fmt::Type3,
2268            chunk_stream_id: ChunkStreamId::new(9),
2269        };
2270        write_serialized_ok(&mut input, &bh3);
2271        input.extend_from_slice(&[5, 6, 7, 8]);
2272        write_serialized_ok(&mut input, &bh3);
2273        input.extend_from_slice(&[9, 10]);
2274
2275        let out = assembler.push(&input).unwrap();
2276        assert_eq!(out.len(), 1);
2277        assert_eq!(out[0].payload, vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
2278    }
2279
2280    #[test]
2281    fn assembler_header_inheritance_type0_type1_type2_type3() {
2282        // fmt0 (ts=1000, len=5, type=8, stream=7) -> fmt1 (delta=20) ->
2283        // fmt2 (delta=30) -> fmt3 (inherits fmt2's delta=30). Each chunk's
2284        // message completes in one go (message_length == chunk_size == 5)
2285        // so every header starts a fresh message on this csid.
2286        let mut assembler = ChunkAssembler::new();
2287        assembler.set_chunk_size(ChunkSize::new(5).expect("a valid chunk size"));
2288        let csid = 5;
2289
2290        let mut input = Vec::new();
2291        write_serialized_ok(
2292            &mut input,
2293            &BasicHeader {
2294                fmt: Fmt::Type0,
2295                chunk_stream_id: ChunkStreamId::new(csid),
2296            },
2297        );
2298        write_serialized_ok(
2299            &mut input,
2300            &MessageHeader::Type0 {
2301                timestamp: Timestamp::from_millis(1000),
2302                message_length: 5,
2303                message_type_id: MessageTypeId::Audio,
2304                message_stream_id: MessageStreamId::new(7),
2305            },
2306        );
2307        input.extend_from_slice(&[0; 5]);
2308
2309        write_serialized_ok(
2310            &mut input,
2311            &BasicHeader {
2312                fmt: Fmt::Type1,
2313                chunk_stream_id: ChunkStreamId::new(csid),
2314            },
2315        );
2316        write_serialized_ok(
2317            &mut input,
2318            &MessageHeader::Type1 {
2319                timestamp_delta: Duration::from_millis(20),
2320                message_length: 5,
2321                message_type_id: MessageTypeId::Audio,
2322            },
2323        );
2324        input.extend_from_slice(&[1; 5]);
2325
2326        write_serialized_ok(
2327            &mut input,
2328            &BasicHeader {
2329                fmt: Fmt::Type2,
2330                chunk_stream_id: ChunkStreamId::new(csid),
2331            },
2332        );
2333        write_serialized_ok(
2334            &mut input,
2335            &MessageHeader::Type2 {
2336                timestamp_delta: Duration::from_millis(30),
2337            },
2338        );
2339        input.extend_from_slice(&[2; 5]);
2340
2341        write_serialized_ok(
2342            &mut input,
2343            &BasicHeader {
2344                fmt: Fmt::Type3,
2345                chunk_stream_id: ChunkStreamId::new(csid),
2346            },
2347        );
2348        input.extend_from_slice(&[3; 5]);
2349
2350        let out = assembler.push(&input).unwrap();
2351        assert_eq!(out.len(), 4);
2352
2353        assert_eq!(out[0].timestamp.millis(), 1000);
2354        assert_eq!(out[0].message_stream_id.get(), 7);
2355        assert_eq!(out[0].message_type_id, MessageTypeId::Audio);
2356        assert_eq!(out[0].payload, vec![0; 5]);
2357
2358        assert_eq!(out[1].timestamp.millis(), 1020, "fmt1: 1000 + delta 20");
2359        assert_eq!(out[1].message_stream_id.get(), 7, "fmt1 inherits stream id");
2360        assert_eq!(out[1].message_type_id, MessageTypeId::Audio);
2361        assert_eq!(out[1].payload, vec![1; 5]);
2362
2363        assert_eq!(out[2].timestamp.millis(), 1050, "fmt2: 1020 + delta 30");
2364        assert_eq!(out[2].message_stream_id.get(), 7, "fmt2 inherits stream id");
2365        assert_eq!(
2366            out[2].message_type_id,
2367            MessageTypeId::Audio,
2368            "fmt2 inherits type id"
2369        );
2370        assert_eq!(out[2].payload, vec![2; 5], "fmt2 inherits message length");
2371
2372        assert_eq!(
2373            out[3].timestamp.millis(),
2374            1080,
2375            "fmt3 (new message) inherits fmt2's delta 30: 1050 + 30"
2376        );
2377        assert_eq!(out[3].message_stream_id.get(), 7, "fmt3 inherits stream id");
2378        assert_eq!(
2379            out[3].message_type_id,
2380            MessageTypeId::Audio,
2381            "fmt3 inherits type id"
2382        );
2383        assert_eq!(out[3].payload, vec![3; 5], "fmt3 inherits message length");
2384    }
2385
2386    #[test]
2387    fn assembler_mid_stream_set_chunk_size_changes_split_boundary() {
2388        // First message at chunk_size 128 (default): a 10-byte message on
2389        // csid 7 fits in one chunk. Then shrink chunk_size to 4 and send a
2390        // second 10-byte message on the same csid (fresh Type 0): it must
2391        // now arrive in 3 physical chunks (4 + 4 + 2), and pushing only the
2392        // first two must NOT complete the message yet.
2393        let mut assembler = ChunkAssembler::new();
2394        let csid = 7;
2395
2396        let first = msg(csid, 100, MessageTypeId::Audio, 1, vec![0xAA; 10]);
2397        let mut writer = ChunkWriter::new();
2398        let first_bytes = writer.write(&first).unwrap();
2399        let out = assembler.push(&first_bytes).unwrap();
2400        assert_eq!(out, vec![first]);
2401
2402        assembler.set_chunk_size(ChunkSize::new(4).expect("a valid chunk size"));
2403        let bh0 = BasicHeader {
2404            fmt: Fmt::Type0,
2405            chunk_stream_id: ChunkStreamId::new(csid),
2406        };
2407        let mh0 = MessageHeader::Type0 {
2408            timestamp: Timestamp::from_millis(200),
2409            message_length: 10,
2410            message_type_id: MessageTypeId::Audio,
2411            message_stream_id: MessageStreamId::new(1),
2412        };
2413        let mut chunk1 = Vec::new();
2414        write_serialized_ok(&mut chunk1, &bh0);
2415        write_serialized_ok(&mut chunk1, &mh0);
2416        chunk1.extend_from_slice(&[1, 2, 3, 4]);
2417        let out = assembler.push(&chunk1).unwrap();
2418        assert!(
2419            out.is_empty(),
2420            "only 4 of 10 payload bytes arrived, message must not complete yet"
2421        );
2422
2423        let bh3 = BasicHeader {
2424            fmt: Fmt::Type3,
2425            chunk_stream_id: ChunkStreamId::new(csid),
2426        };
2427        let mut chunk2 = Vec::new();
2428        write_serialized_ok(&mut chunk2, &bh3);
2429        chunk2.extend_from_slice(&[5, 6, 7, 8]);
2430        let out = assembler.push(&chunk2).unwrap();
2431        assert!(out.is_empty(), "8 of 10 payload bytes, still incomplete");
2432
2433        let mut chunk3 = Vec::new();
2434        write_serialized_ok(&mut chunk3, &bh3);
2435        chunk3.extend_from_slice(&[9, 10]);
2436        let out = assembler.push(&chunk3).unwrap();
2437        assert_eq!(out.len(), 1);
2438        assert_eq!(out[0].payload, vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
2439    }
2440
2441    #[test]
2442    fn writer_assembler_round_trip_extended_timestamp_split_across_chunks() {
2443        // timestamp >= EXTENDED_TIMESTAMP_MARKER forces the Type 0 header
2444        // (and every Type 3 continuation) to carry the 4-byte Extended
2445        // Timestamp (§3.1.3) — payload longer than chunk_size so at least
2446        // one Type 3 continuation chunk exercises the "fmt3 also carries
2447        // extended timestamp" edge.
2448        let original = msg(
2449            8,
2450            EXTENDED_TIMESTAMP_MARKER + 12345,
2451            MessageTypeId::Video,
2452            2,
2453            vec![0x7E; 300],
2454        );
2455        let mut writer = ChunkWriter::new();
2456        let bytes = writer.write(&original).unwrap();
2457
2458        // Sanity: the first chunk's basic header + Type0 header must be
2459        // TYPE0_LEN + 4 (extended) bytes, and each Type 3 continuation
2460        // basic header must be immediately followed by 4 extended bytes
2461        // before its payload slice.
2462        let bh_len = 1; // csid 8 fits the 1-byte basic header form.
2463        let first_header_len = bh_len + TYPE0_LEN + EXTENDED_TIMESTAMP_LEN;
2464        assert_eq!(&bytes[bh_len..bh_len + 3], [0xFF, 0xFF, 0xFF]);
2465        let ext_offset = bh_len + TYPE0_LEN;
2466        assert_eq!(
2467            &bytes[ext_offset..ext_offset + 4],
2468            &original.timestamp.millis().to_be_bytes()
2469        );
2470        let first_payload_take = 128usize;
2471        let second_chunk_start = first_header_len + first_payload_take;
2472        // second chunk: 1-byte Type 3 basic header + 4-byte extended ts.
2473        assert_eq!(bytes[second_chunk_start] >> 6, Fmt::Type3.to_bits());
2474        let second_ext_offset = second_chunk_start + 1;
2475        assert_eq!(
2476            &bytes[second_ext_offset..second_ext_offset + 4],
2477            &original.timestamp.millis().to_be_bytes(),
2478            "fmt3 continuation must carry the same extended timestamp"
2479        );
2480
2481        let mut assembler = ChunkAssembler::new();
2482        let out = assembler.push(&bytes).unwrap();
2483        assert_eq!(out.len(), 1);
2484        assert_eq!(out[0], original);
2485        assert_eq!(out[0].timestamp.millis(), EXTENDED_TIMESTAMP_MARKER + 12345);
2486    }
2487
2488    #[test]
2489    fn assembler_partial_feed_split_mid_header_no_drop_or_duplicate() {
2490        let original = msg(9, 42, MessageTypeId::Audio, 3, vec![0x11; 200]);
2491        let mut writer = ChunkWriter::new();
2492        let bytes = writer.write(&original).unwrap();
2493
2494        // Split at an arbitrary offset that lands inside the Type 0 header
2495        // (byte 3 of 11), well before any payload.
2496        let split_at = 4;
2497        assert!(split_at < 1 + TYPE0_LEN);
2498
2499        let mut assembler = ChunkAssembler::new();
2500        let out1 = assembler.push(&bytes[..split_at]).unwrap();
2501        assert!(out1.is_empty(), "partial header must not error or complete");
2502        let out2 = assembler.push(&bytes[split_at..]).unwrap();
2503        assert_eq!(out2.len(), 1, "message must complete exactly once");
2504        assert_eq!(out2[0], original);
2505    }
2506
2507    #[test]
2508    fn assembler_partial_feed_split_mid_payload_no_drop_or_duplicate() {
2509        let original = msg(10, 42, MessageTypeId::Audio, 3, vec![0x22; 300]);
2510        let mut writer = ChunkWriter::new();
2511        let bytes = writer.write(&original).unwrap();
2512
2513        // Split partway through the first (128-byte) payload chunk.
2514        let split_at = 1 + TYPE0_LEN + 60;
2515        let mut assembler = ChunkAssembler::new();
2516        let out1 = assembler.push(&bytes[..split_at]).unwrap();
2517        assert!(out1.is_empty());
2518        let out2 = assembler.push(&bytes[split_at..]).unwrap();
2519        assert_eq!(out2.len(), 1);
2520        assert_eq!(out2[0], original);
2521    }
2522
2523    /// RTMP-W2 (#1108): `Abort` on a csid with an in-progress message must
2524    /// discard it, so the next Type 0 message on that csid parses cleanly
2525    /// instead of the following chunk being read as a continuation of the
2526    /// aborted (never-completed) payload.
2527    #[test]
2528    fn abort_discards_in_progress_message_on_csid() {
2529        let aborted = msg(12, 1, MessageTypeId::Audio, 3, vec![0xAA; 300]); // spans 3 chunks at default 128
2530        let mut writer = ChunkWriter::new();
2531        let aborted_bytes = writer.write(&aborted).unwrap();
2532
2533        // Feed only the first chunk (Type 0 header + 128 bytes) — the
2534        // message is left in-progress on csid 12.
2535        let split_at = 1 + TYPE0_LEN + 128;
2536        let mut assembler = ChunkAssembler::new();
2537        let out = assembler.push(&aborted_bytes[..split_at]).unwrap();
2538        assert!(out.is_empty(), "message must still be in progress");
2539
2540        assembler.abort(ChunkStreamId::new(12));
2541
2542        // A brand-new, independent Type 0 message on the SAME csid must
2543        // now parse as itself.
2544        let fresh = msg(12, 2, MessageTypeId::Audio, 3, vec![0xBB; 50]);
2545        let fresh_bytes = writer.write(&fresh).unwrap();
2546        let out2 = assembler.push(&fresh_bytes).unwrap();
2547        assert_eq!(out2.len(), 1);
2548        assert_eq!(out2[0], fresh);
2549    }
2550
2551    /// RTMP-W2 (#1108): the precise corruption mechanism the finding
2552    /// describes — after `Abort`, a Type 3 chunk that the SENDER means as
2553    /// the start of a fresh message (inheriting the prior Type 0 header,
2554    /// same `message_length`) must NOT be read as a continuation of the
2555    /// aborted payload. Pre-fix, `in_progress` stayed `true` after Abort,
2556    /// so this Type 3 chunk's bytes were appended onto the old (partial,
2557    /// stale) payload instead of starting a clean new accumulation.
2558    #[test]
2559    fn abort_makes_next_type3_chunk_start_fresh_not_continue() {
2560        let aborted = msg(12, 1, MessageTypeId::Audio, 3, vec![0xAA; 300]); // message_length=300, no extended ts
2561        let mut writer = ChunkWriter::new();
2562        let aborted_bytes = writer.write(&aborted).unwrap();
2563
2564        let split_at = 1 + TYPE0_LEN + 128;
2565        let mut assembler = ChunkAssembler::new();
2566        let out = assembler.push(&aborted_bytes[..split_at]).unwrap();
2567        assert!(out.is_empty());
2568
2569        assembler.abort(ChunkStreamId::new(12));
2570
2571        // Bare Type 3 chunks (fmt=3, csid=12 -> (3<<6)|12 = 0xCC), a
2572        // DIFFERENT fill value, completing a fresh 300-byte message that
2573        // inherits message_length/type/stream_id from the last Type 0
2574        // header on this csid (§3.1.2) — 128 + 128 + 44 = 300.
2575        let mut rest = Vec::new();
2576        for chunk_len in [128, 128, 44] {
2577            rest.push(0xCC);
2578            rest.extend(core::iter::repeat_n(0xEEu8, chunk_len));
2579        }
2580        let completed = assembler.push(&rest).unwrap();
2581        assert_eq!(
2582            completed.len(),
2583            1,
2584            "the 300-byte message must complete exactly once"
2585        );
2586        assert_eq!(
2587            completed[0].payload,
2588            vec![0xEE; 300],
2589            "must be entirely the fresh fill value, with none of the aborted 0xAA bytes leaked in"
2590        );
2591    }
2592
2593    /// RTMP-W3 (#1108): a Type 1 chunk header arriving mid-message (the
2594    /// csid already has an in-progress, incomplete message) must be
2595    /// rejected, not silently reset the csid's state and discard the
2596    /// in-flight bytes.
2597    #[test]
2598    fn type1_header_mid_message_is_rejected() {
2599        let in_progress = msg(12, 1, MessageTypeId::Audio, 3, vec![0xAA; 300]); // 3 chunks at default 128
2600        let mut writer = ChunkWriter::new();
2601        let bytes = writer.write(&in_progress).unwrap();
2602
2603        // Feed only the first chunk — csid 12 is left in-progress.
2604        let split_at = 1 + TYPE0_LEN + 128;
2605        let mut assembler = ChunkAssembler::new();
2606        let out = assembler.push(&bytes[..split_at]).unwrap();
2607        assert!(out.is_empty());
2608
2609        // A hand-built Type 1 chunk header on the SAME csid (fmt=1, csid=12
2610        // fits the 1-byte basic header form: (1 << 6) | 12 = 0x4C).
2611        let type1_chunk = [
2612            0x4C, // basic header: fmt=1, csid=12
2613            0x00, 0x00, 0x05, // timestamp_delta = 5
2614            0x00, 0x00, 0x32, // message_length = 50
2615            0x08, // message_type_id
2616        ];
2617        let err = assembler.push(&type1_chunk).unwrap_err();
2618        assert!(matches!(
2619            err,
2620            RtmpError::ChunkStreamState {
2621                chunk_stream_id: 12,
2622                ..
2623            }
2624        ));
2625    }
2626
2627    #[test]
2628    fn assembler_partial_feed_byte_at_a_time_never_drops_or_duplicates() {
2629        let original = msg(11, 7, MessageTypeId::Video, 4, vec![0x33; 260]);
2630        let mut writer = ChunkWriter::new();
2631        let bytes = writer.write(&original).unwrap();
2632
2633        let mut assembler = ChunkAssembler::new();
2634        let mut collected = Vec::new();
2635        for b in &bytes {
2636            collected.extend(assembler.push(core::slice::from_ref(b)).unwrap());
2637        }
2638        assert_eq!(collected.len(), 1);
2639        assert_eq!(collected[0], original);
2640    }
2641
2642    #[test]
2643    fn assembler_type1_on_unseen_csid_is_malformed() {
2644        let mut assembler = ChunkAssembler::new();
2645        let mut input = Vec::new();
2646        write_serialized_ok(
2647            &mut input,
2648            &BasicHeader {
2649                fmt: Fmt::Type1,
2650                chunk_stream_id: ChunkStreamId::new(9),
2651            },
2652        );
2653        write_serialized_ok(
2654            &mut input,
2655            &MessageHeader::Type1 {
2656                timestamp_delta: Duration::from_millis(5),
2657                message_length: 3,
2658                message_type_id: MessageTypeId::SetChunkSize,
2659            },
2660        );
2661        input.extend_from_slice(&[0, 0, 0]);
2662        assert!(matches!(
2663            assembler.push(&input),
2664            Err(RtmpError::ChunkStreamState {
2665                chunk_stream_id: 9,
2666                ..
2667            })
2668        ));
2669    }
2670
2671    #[test]
2672    fn assembler_type3_on_unseen_csid_is_malformed() {
2673        let mut assembler = ChunkAssembler::new();
2674        let mut input = Vec::new();
2675        write_serialized_ok(
2676            &mut input,
2677            &BasicHeader {
2678                fmt: Fmt::Type3,
2679                chunk_stream_id: ChunkStreamId::new(9),
2680            },
2681        );
2682        assert!(matches!(
2683            assembler.push(&input),
2684            Err(RtmpError::ChunkStreamState {
2685                chunk_stream_id: 9,
2686                ..
2687            })
2688        ));
2689    }
2690
2691    #[test]
2692    fn assembler_truncated_input_never_panics_across_many_split_points() {
2693        let original = msg(12, 99, MessageTypeId::Audio, 5, vec![0x44; 400]);
2694        let mut writer = ChunkWriter::new();
2695        let bytes = writer.write(&original).unwrap();
2696
2697        // Feed every possible byte-prefix of the stream to a fresh
2698        // assembler each time: none may panic, and any that do parse fully
2699        // must reproduce the original message exactly.
2700        for split in 0..=bytes.len() {
2701            let mut assembler = ChunkAssembler::new();
2702            let first = assembler.push(&bytes[..split]);
2703            let Ok(first_msgs) = first else {
2704                continue;
2705            };
2706            let second = assembler.push(&bytes[split..]).unwrap();
2707            let mut all = first_msgs;
2708            all.extend(second);
2709            assert_eq!(all, vec![original.clone()]);
2710        }
2711    }
2712
2713    #[test]
2714    fn writer_default_chunk_size_matches_assembler_default() {
2715        assert_eq!(ChunkWriter::new().chunk_size, DEFAULT_CHUNK_SIZE);
2716        assert_eq!(ChunkAssembler::new().chunk_size, DEFAULT_CHUNK_SIZE);
2717    }
2718
2719    #[test]
2720    fn assembler_type3_immediately_after_type0_uses_type0_timestamp_as_implied_delta() {
2721        // §3.1.2: a Type 3 chunk that starts a NEW message immediately after
2722        // a Type 0 (nothing intervening) has an implied `timestamp_delta`
2723        // equal to that Type 0's own absolute timestamp — NOT 0. Every other
2724        // existing test intervenes a Type 1/2 before the fmt3, so this is
2725        // the only test that reaches this resolution path directly (bites a
2726        // mutation of `timestamp_delta: timestamp` -> `timestamp_delta: 0`
2727        // in the Type 0 arm).
2728        let mut assembler = ChunkAssembler::new();
2729        let csid = 40;
2730
2731        let mut input = Vec::new();
2732        write_serialized_ok(
2733            &mut input,
2734            &BasicHeader {
2735                fmt: Fmt::Type0,
2736                chunk_stream_id: ChunkStreamId::new(csid),
2737            },
2738        );
2739        write_serialized_ok(
2740            &mut input,
2741            &MessageHeader::Type0 {
2742                timestamp: Timestamp::from_millis(1000),
2743                message_length: 5,
2744                message_type_id: MessageTypeId::Audio,
2745                message_stream_id: MessageStreamId::new(2),
2746            },
2747        );
2748        input.extend_from_slice(&[1, 2, 3, 4, 5]);
2749
2750        // Immediately (same csid, nothing between) a fmt3 chunk starting a
2751        // new message, inheriting message_length 5 from the Type 0 above.
2752        write_serialized_ok(
2753            &mut input,
2754            &BasicHeader {
2755                fmt: Fmt::Type3,
2756                chunk_stream_id: ChunkStreamId::new(csid),
2757            },
2758        );
2759        input.extend_from_slice(&[9, 9, 9, 9, 9]);
2760
2761        let out = assembler.push(&input).unwrap();
2762        assert_eq!(out.len(), 2);
2763        assert_eq!(out[0].timestamp.millis(), 1000);
2764        assert_eq!(
2765            out[1].timestamp.millis(),
2766            2000,
2767            "fmt3 immediately after fmt0 implies delta == the fmt0's own timestamp (1000), not 0: 1000 + 1000"
2768        );
2769    }
2770
2771    #[test]
2772    fn assembler_type2_on_unseen_csid_is_malformed() {
2773        let mut assembler = ChunkAssembler::new();
2774        let mut input = Vec::new();
2775        write_serialized_ok(
2776            &mut input,
2777            &BasicHeader {
2778                fmt: Fmt::Type2,
2779                chunk_stream_id: ChunkStreamId::new(9),
2780            },
2781        );
2782        write_serialized_ok(
2783            &mut input,
2784            &MessageHeader::Type2 {
2785                timestamp_delta: Duration::from_millis(5),
2786            },
2787        );
2788        assert!(matches!(
2789            assembler.push(&input),
2790            Err(RtmpError::ChunkStreamState {
2791                chunk_stream_id: 9,
2792                ..
2793            })
2794        ));
2795    }
2796
2797    /// A peer that announces a chunk size below 128 (wire-legal — §5.4.1
2798    /// only recommends `SHOULD >= 128` for a *sender* choosing what to
2799    /// announce, the hard floor is `MUST >= 1`) must be parsed at exactly
2800    /// that size: this crate does not get to unilaterally decide the peer
2801    /// under-chunked and reinterpret its bytes at a larger boundary,
2802    /// because the peer already framed every subsequent chunk at the size
2803    /// it announced. Regression for a prior version of this fix that
2804    /// clamped an incoming announcement up to a 128-byte floor, which would
2805    /// have misparsed exactly this stream.
2806    #[test]
2807    fn assembler_honours_a_peer_announced_chunk_size_below_128() {
2808        let mut assembler = ChunkAssembler::new();
2809        assembler.set_chunk_size(ChunkSize::new(64).expect("a valid chunk size"));
2810        assert_eq!(
2811            assembler.chunk_size,
2812            ChunkSize::new(64).expect("a valid chunk size"),
2813            "the announced size must not be clamped up"
2814        );
2815
2816        let payload: Vec<u8> = (0u32..150).map(|i| (i % 251) as u8).collect();
2817        let mut input = Vec::new();
2818        write_serialized_ok(
2819            &mut input,
2820            &BasicHeader {
2821                fmt: Fmt::Type0,
2822                chunk_stream_id: ChunkStreamId::new(9),
2823            },
2824        );
2825        write_serialized_ok(
2826            &mut input,
2827            &MessageHeader::Type0 {
2828                timestamp: Timestamp::from_millis(0),
2829                message_length: payload.len() as u32,
2830                message_type_id: MessageTypeId::Audio,
2831                message_stream_id: MessageStreamId::new(0),
2832            },
2833        );
2834        input.extend_from_slice(&payload[0..64]);
2835        write_serialized_ok(
2836            &mut input,
2837            &BasicHeader {
2838                fmt: Fmt::Type3,
2839                chunk_stream_id: ChunkStreamId::new(9),
2840            },
2841        );
2842        input.extend_from_slice(&payload[64..128]);
2843        write_serialized_ok(
2844            &mut input,
2845            &BasicHeader {
2846                fmt: Fmt::Type3,
2847                chunk_stream_id: ChunkStreamId::new(9),
2848            },
2849        );
2850        input.extend_from_slice(&payload[128..]);
2851
2852        let out = assembler.push(&input).unwrap();
2853        assert_eq!(out.len(), 1);
2854        assert_eq!(out[0].payload, payload);
2855    }
2856
2857    #[test]
2858    fn assembler_set_chunk_size_zero_is_floored_to_one() {
2859        let mut assembler = ChunkAssembler::new();
2860        assert!(ChunkSize::new(0).is_err(), "a chunk size of 0 is rejected");
2861        assembler.set_chunk_size(ChunkSize::MIN);
2862
2863        // A message chunked consistently with the floored size (1 payload
2864        // byte per physical chunk) still assembles correctly — the floor
2865        // makes progress possible rather than wedging on every push.
2866        let csid = 41;
2867        let mut input = Vec::new();
2868        write_serialized_ok(
2869            &mut input,
2870            &BasicHeader {
2871                fmt: Fmt::Type0,
2872                chunk_stream_id: ChunkStreamId::new(csid),
2873            },
2874        );
2875        write_serialized_ok(
2876            &mut input,
2877            &MessageHeader::Type0 {
2878                timestamp: Timestamp::from_millis(1),
2879                message_length: 3,
2880                message_type_id: MessageTypeId::Audio,
2881                message_stream_id: MessageStreamId::new(0),
2882            },
2883        );
2884        input.push(0xAA);
2885        write_serialized_ok(
2886            &mut input,
2887            &BasicHeader {
2888                fmt: Fmt::Type3,
2889                chunk_stream_id: ChunkStreamId::new(csid),
2890            },
2891        );
2892        input.push(0xBB);
2893        write_serialized_ok(
2894            &mut input,
2895            &BasicHeader {
2896                fmt: Fmt::Type3,
2897                chunk_stream_id: ChunkStreamId::new(csid),
2898            },
2899        );
2900        input.push(0xCC);
2901
2902        let out = assembler.push(&input).unwrap();
2903        assert_eq!(out.len(), 1);
2904        assert_eq!(out[0].payload, vec![0xAA, 0xBB, 0xCC]);
2905    }
2906
2907    // ── Remote-DoS caps (excessive-allocation guard) ────────────────────
2908
2909    /// A complete, well-formed one-chunk message on `csid`: a Type 0 header
2910    /// declaring `message_length == payload.len()`, immediately followed by
2911    /// `payload` (so it fits in the default 128-byte chunk size and
2912    /// completes in a single chunk).
2913    fn single_chunk(csid: u32, payload: &[u8]) -> Vec<u8> {
2914        let mut input = Vec::new();
2915        write_serialized_ok(
2916            &mut input,
2917            &BasicHeader {
2918                fmt: Fmt::Type0,
2919                chunk_stream_id: ChunkStreamId::new(csid),
2920            },
2921        );
2922        write_serialized_ok(
2923            &mut input,
2924            &MessageHeader::Type0 {
2925                timestamp: Timestamp::from_millis(0),
2926                message_length: payload.len() as u32,
2927                message_type_id: MessageTypeId::Video,
2928                message_stream_id: MessageStreamId::new(1),
2929            },
2930        );
2931        input.extend_from_slice(payload);
2932        input
2933    }
2934
2935    #[test]
2936    fn oversized_message_length_header_is_rejected_without_allocating() {
2937        // Mutation check: a Type 0 header claims a ~16 MiB message_length
2938        // (the max a 24-bit field can encode) but only ever supplies a
2939        // single default-chunk-size (128-byte) slice of payload after it —
2940        // exactly the shape of the excessive-allocation DoS (the peer never
2941        // has to send anywhere near the claimed length). Without the
2942        // MAX_MESSAGE_LEN cap this used to `Vec::with_capacity(message_length)`
2943        // (~16 MiB) right here and return `Ok(vec![])` (message merely
2944        // in-progress, no error) — this test would then fail, since it
2945        // asserts an `Err` instead.
2946        let mut assembler = ChunkAssembler::new();
2947        let mut input = Vec::new();
2948        write_serialized_ok(
2949            &mut input,
2950            &BasicHeader {
2951                fmt: Fmt::Type0,
2952                chunk_stream_id: ChunkStreamId::new(9),
2953            },
2954        );
2955        write_serialized_ok(
2956            &mut input,
2957            &MessageHeader::Type0 {
2958                timestamp: Timestamp::from_millis(0),
2959                message_length: 0x00FF_FFFF, // ~16 MiB: the largest 24-bit value.
2960                message_type_id: MessageTypeId::Video,
2961                message_stream_id: MessageStreamId::new(1),
2962            },
2963        );
2964        input.extend(core::iter::repeat_n(0u8, DEFAULT_CHUNK_SIZE_VALUE as usize));
2965
2966        let err = assembler.push(&input).expect_err(
2967            "a message_length beyond MAX_MESSAGE_LEN must be rejected before any \
2968             message_length-sized buffer is allocated",
2969        );
2970        assert!(matches!(
2971            err,
2972            RtmpError::FieldOverflow(broadcast_common::len::FieldOverflow {
2973                field: "message_length",
2974                ..
2975            })
2976        ));
2977    }
2978
2979    #[test]
2980    fn message_length_at_the_cap_is_accepted() {
2981        // Boundary check: exactly MAX_MESSAGE_LEN must still be accepted
2982        // (only values strictly above the cap are rejected).
2983        let mut assembler = ChunkAssembler::new();
2984        let mut input = Vec::new();
2985        write_serialized_ok(
2986            &mut input,
2987            &BasicHeader {
2988                fmt: Fmt::Type0,
2989                chunk_stream_id: ChunkStreamId::new(9),
2990            },
2991        );
2992        write_serialized_ok(
2993            &mut input,
2994            &MessageHeader::Type0 {
2995                timestamp: Timestamp::from_millis(0),
2996                message_length: MAX_MESSAGE_LEN,
2997                message_type_id: MessageTypeId::Video,
2998                message_stream_id: MessageStreamId::new(1),
2999            },
3000        );
3001        input.extend(core::iter::repeat_n(0u8, DEFAULT_CHUNK_SIZE_VALUE as usize));
3002
3003        // Not yet complete (only one chunk of a much larger message has
3004        // arrived) but must not be rejected outright.
3005        assert!(assembler.push(&input).is_ok());
3006    }
3007
3008    #[test]
3009    fn csid_flood_beyond_max_csids_is_rejected() {
3010        // Mutation check: fill the bound with MAX_CSIDS distinct,
3011        // well-formed chunk streams first (none of these may error — the
3012        // cap must not reject legitimate, moderate csid usage), then assert
3013        // that one more previously-unseen csid is rejected rather than
3014        // silently growing the per-csid state map without bound. Without
3015        // the MAX_CSIDS cap this last `push` would also return `Ok(_)`,
3016        // failing this test's `Err` assertion.
3017        let mut assembler = ChunkAssembler::new();
3018        for i in 0..MAX_CSIDS {
3019            let csid = BASIC_HEADER_1BYTE_MIN_CSID + i as u32;
3020            let out = assembler
3021                .push(&single_chunk(csid, &[0xAB]))
3022                .unwrap_or_else(|e| panic!("csid {csid} (#{i}, within the bound) rejected: {e}"));
3023            assert_eq!(out.len(), 1);
3024        }
3025
3026        let flood_csid = BASIC_HEADER_1BYTE_MIN_CSID + MAX_CSIDS as u32;
3027        let err = assembler
3028            .push(&single_chunk(flood_csid, &[0xCD]))
3029            .expect_err("a new csid beyond MAX_CSIDS must be rejected, not silently accepted");
3030        assert!(matches!(
3031            err,
3032            RtmpError::TooManyChunkStreams { max } if max == MAX_CSIDS
3033        ));
3034    }
3035
3036    #[test]
3037    fn csid_flood_cap_does_not_count_repeats_of_the_same_csid() {
3038        // A single csid reused for many messages must never itself trip the
3039        // MAX_CSIDS cap (the bound is on distinct concurrent csids, not on
3040        // total message count).
3041        let mut assembler = ChunkAssembler::new();
3042        for i in 0..(MAX_CSIDS * 4) {
3043            let out = assembler
3044                .push(&single_chunk(BASIC_HEADER_1BYTE_MIN_CSID, &[i as u8]))
3045                .expect("repeated use of a single already-known csid must never be rejected");
3046            assert_eq!(out.len(), 1);
3047        }
3048    }
3049
3050    /// A peer that announces a size above the engine ceiling is rejected at
3051    /// construction rather than adopted partly: pre-fix the assembler and
3052    /// writer clamped it to [`MAX_CHUNK_SIZE`] and parsed/framed every later
3053    /// chunk at a size the peer never announced, silently mis-framing the
3054    /// rest of the stream.
3055    #[test]
3056    fn a_chunk_size_above_the_engine_ceiling_is_rejected_not_clamped() {
3057        let announced = crate::message::ChunkSize::MAX;
3058        assert!(
3059            announced > MAX_CHUNK_SIZE,
3060            "the case under test needs a legal wire size above the ceiling"
3061        );
3062        assert!(crate::message::ChunkSize::try_new(announced).is_err());
3063        assert_eq!(
3064            crate::message::ChunkSize::try_new(MAX_CHUNK_SIZE)
3065                .expect("the ceiling itself is accepted")
3066                .value(),
3067            MAX_CHUNK_SIZE
3068        );
3069    }
3070
3071    /// #1108/RTMP-W1: a fresh message opened on `csid` declaring
3072    /// `declared_len` (> one chunk) payload bytes, with exactly its first
3073    /// full chunk delivered so it commits and stays in progress. The full
3074    /// declared length is reserved against the aggregate budget when the
3075    /// header validates.
3076    fn open_partial_chunk(csid: u32, declared_len: u32) -> Vec<u8> {
3077        let sent_len = DEFAULT_CHUNK_SIZE_VALUE as usize;
3078        assert!(sent_len < declared_len as usize);
3079        let mut input = Vec::new();
3080        write_serialized_ok(
3081            &mut input,
3082            &BasicHeader {
3083                fmt: Fmt::Type0,
3084                chunk_stream_id: ChunkStreamId::new(csid),
3085            },
3086        );
3087        write_serialized_ok(
3088            &mut input,
3089            &MessageHeader::Type0 {
3090                timestamp: Timestamp::from_millis(0),
3091                message_length: declared_len,
3092                message_type_id: MessageTypeId::Video,
3093                message_stream_id: MessageStreamId::new(1),
3094            },
3095        );
3096        input.extend_from_slice(&vec![0x5Au8; sent_len]);
3097        input
3098    }
3099
3100    #[test]
3101    fn aggregate_in_progress_bytes_across_csids_is_capped() {
3102        // Mutation check: MAX_MESSAGE_LEN bounds ONE message and MAX_CSIDS
3103        // bounds HOW MANY csids, but neither bounds the *product* — the
3104        // hoarder does not even have to send the bytes; N csids each with
3105        // a 24 KiB declaration cost one header each. Without the aggregate
3106        // budget every push below returns Ok and the assembler accepts
3107        // (MAX_MESSAGE_LEN x MAX_CSIDS) = 512 MiB of declarations per
3108        // connection.
3109        const BUDGET: usize = 64 * 1024;
3110        const DECL: u32 = 24 * 1024;
3111        let mut assembler = ChunkAssembler::new().with_max_in_progress_bytes(BUDGET);
3112        // First prove the normal-traffic path: complete messages cycling
3113        // every legal csid must never trip the budget (reservations are
3114        // released on delivery), and the csid space really is reachable.
3115        for i in 0..MAX_CSIDS as u32 {
3116            let out = assembler
3117                .push(&single_chunk(
3118                    BASIC_HEADER_1BYTE_MIN_CSID + i,
3119                    &[0x5Au8; 100],
3120                ))
3121                .expect("complete messages must never trip the budget");
3122            assert_eq!(out.len(), 1);
3123            assert_eq!(assembler.in_progress_bytes, 0);
3124        }
3125        // Now the hoarding shape: one permanently-partial 24 KiB
3126        // declaration per csid, each costing the hoarder only a 16-byte
3127        // payload fragment. 64 KiB / 24 KiB = 2 fit, so the budget must
3128        // trip on the third push.
3129        let mut hoarded = 0;
3130        for i in 0..MAX_CSIDS as u32 {
3131            let csid = BASIC_HEADER_1BYTE_MIN_CSID + i;
3132            match assembler.push(&open_partial_chunk(csid, DECL)) {
3133                Ok(msgs) => {
3134                    assert!(msgs.is_empty(), "a partial message must not complete");
3135                    assert_eq!(
3136                        assembler.in_progress_bytes,
3137                        (hoarded + 1) * DECL as usize,
3138                        "each accepted declaration must reserve its full length"
3139                    );
3140                    hoarded += 1;
3141                }
3142                Err(err) => {
3143                    assert!(
3144                        matches!(&err, RtmpError::InputBudgetExceeded { .. }),
3145                        "budget overrun must be InputBudgetExceeded (push #{hoarded}), got {err:?}"
3146                    );
3147                    break;
3148                }
3149            }
3150        }
3151        // 64 KiB / 24 KiB = 2 partials fit: the budget trips on the third
3152        // push — long before the MAX_CSIDS cap could (only 3 csids exist
3153        // on this connection, far below the 64-csid ceiling).
3154        assert_eq!(
3155            hoarded, 2,
3156            "the budget must be what stops the flood, not the csid cap"
3157        );
3158        assert!(
3159            assembler.in_progress_bytes <= BUDGET,
3160            "held bytes must never exceed the budget"
3161        );
3162    }
3163
3164    #[test]
3165    fn aggregate_in_progress_budget_trips_mid_message_and_recovers_on_completion() {
3166        const DECL: u32 = 200;
3167        let mut assembler = ChunkAssembler::new().with_max_in_progress_bytes(DECL as usize);
3168        assert!(
3169            assembler
3170                .push(&open_partial_chunk(3, DECL))
3171                .unwrap()
3172                .is_empty()
3173        );
3174        assert_eq!(assembler.in_progress_bytes, DECL as usize);
3175        // A second declaration would need 2x DECL: fatal, and the rejected
3176        // message leaves no reservation behind.
3177        assembler
3178            .push(&open_partial_chunk(4, DECL))
3179            .expect_err("a second declaration trips the cap");
3180        assert_eq!(assembler.in_progress_bytes, DECL as usize);
3181        // Recovery is checked on a fresh assembler (the error is fatal for
3182        // the connection): completing the message releases its reservation.
3183        let mut assembler = ChunkAssembler::new().with_max_in_progress_bytes(DECL as usize);
3184        assembler.push(&open_partial_chunk(3, DECL)).unwrap();
3185        let mut tail = Vec::new();
3186        write_serialized_ok(
3187            &mut tail,
3188            &BasicHeader {
3189                fmt: Fmt::Type3,
3190                chunk_stream_id: ChunkStreamId::new(3),
3191            },
3192        );
3193        tail.extend_from_slice(&vec![
3194            0x11u8;
3195            DECL as usize - DEFAULT_CHUNK_SIZE_VALUE as usize
3196        ]);
3197        let out = assembler.push(&tail).unwrap();
3198        assert_eq!(out.len(), 1);
3199        assert_eq!(out[0].payload.len(), DECL as usize);
3200        assert_eq!(assembler.in_progress_bytes, 0);
3201        assembler
3202            .push(&open_partial_chunk(5, DECL))
3203            .expect("freed budget must be reusable");
3204        assert_eq!(assembler.in_progress_bytes, DECL as usize);
3205    }
3206
3207    #[test]
3208    fn aggregate_in_progress_budget_unchanged_by_completed_messages() {
3209        // Many complete messages through a tight budget must never trip
3210        // the cap (payload leaves the budget the moment it is delivered),
3211        // proving the cap bounds *stuck* bytes, not throughput.
3212        let mut assembler = ChunkAssembler::new().with_max_in_progress_bytes(16);
3213        for i in 0..50u32 {
3214            let out = assembler
3215                .push(&single_chunk(BASIC_HEADER_1BYTE_MIN_CSID, &[i as u8; 15]))
3216                .expect("completed messages must not count toward the budget");
3217            assert_eq!(out.len(), 1);
3218        }
3219        assert_eq!(assembler.in_progress_bytes, 0);
3220    }
3221
3222    /// r08-RTMP-C1 regression: reassembling a large message split into many
3223    /// small physical chunks (here, chunk size 1 — the wire's own hard
3224    /// floor, `MUST >= 1`, and the shape the original finding used) must do
3225    /// O(`message_length`) total payload-copying work, not
3226    /// O(`message_length`^2 / `chunk_size`). Measured directly via the
3227    /// `#[cfg(test)]` byte-copy hook rather than a wall-clock bound (a
3228    /// wall-clock bound is inherently flaky under load; this one instead
3229    /// asserts the exact quantity the fix changes).
3230    ///
3231    /// Pre-fix, at `MAX_MESSAGE_LEN` (8 MiB) split into 1-byte chunks
3232    /// (~8.4 million of them), the old "clone the whole accumulated payload
3233    /// on every continuation chunk" code would have copied on the order of
3234    /// `sum(1, 2, ..., 8 MiB) ~= 8MiB^2 / 2` bytes — many terabytes, not
3235    /// safely runnable here (would allocate far beyond a reasonable test
3236    /// budget). A *smaller*-scale version of this same shape was run
3237    /// directly against the pre-fix code (64 KiB / 256 KiB at chunk size 1)
3238    /// and confirmed the quadratic blowup (wall-clock time scaled ~11x for
3239    /// a 4x size increase) before this fix landed; see brief/PR notes.
3240    #[test]
3241    fn reassembling_an_8mib_message_at_chunk_size_one_is_linear_not_quadratic() {
3242        let payload: Vec<u8> = (0..MAX_MESSAGE_LEN).map(|i| (i % 251) as u8).collect();
3243        let original = msg(10, 0, MessageTypeId::Video, 1, payload.clone());
3244
3245        let mut writer = ChunkWriter::new();
3246        writer.set_chunk_size(ChunkSize::MIN);
3247        let bytes = writer.write(&original).unwrap();
3248
3249        let mut assembler = ChunkAssembler::new().with_chunk_size(ChunkSize::MIN);
3250
3251        reset_payload_bytes_copied_for_test();
3252        let out = assembler.push(&bytes).unwrap();
3253        let copied = payload_bytes_copied_for_test();
3254
3255        assert_eq!(out.len(), 1);
3256        assert_eq!(out[0].payload, payload);
3257
3258        // Generous (4x message length) but already far below what the old
3259        // quadratic code would have copied (~4 million x message length at
3260        // this size/chunk_size) — this bound is only reachable by O(n)
3261        // reassembly.
3262        assert!(
3263            copied <= payload.len() * 4,
3264            "copied {copied} bytes reassembling a {}-byte message at chunk \
3265             size 1 — quadratic behaviour crept back in",
3266            payload.len()
3267        );
3268    }
3269}
3270
3271#[cfg(test)]
3272mod typed_id_tests {
3273    use super::*;
3274    use crate::ids::{MessageStreamId, Timestamp};
3275
3276    /// A SetBufferLength buffer span and a message timestamp are typed
3277    /// values that reach the wire as whole milliseconds, and a chunk stream
3278    /// id is a `ChunkStreamId` everywhere it is carried.
3279    #[test]
3280    fn typed_spans_are_carried_as_whole_milliseconds() {
3281        let msg = Message {
3282            chunk_stream_id: ChunkStreamId::new(4),
3283            timestamp: Timestamp::try_new(Duration::from_millis(1234)).expect("in range"),
3284            message_type_id: MessageTypeId::Audio,
3285            message_stream_id: MessageStreamId::new(7),
3286            payload: vec![0x01, 0x02],
3287        };
3288        let bytes = ChunkWriter::new().write(&msg).expect("write");
3289        let parsed = ChunkAssembler::new().push(&bytes).expect("parse");
3290        assert_eq!(parsed.len(), 1);
3291        assert_eq!(parsed[0].timestamp, msg.timestamp);
3292        assert_eq!(parsed[0].timestamp.millis(), 1234);
3293        assert_eq!(parsed[0].chunk_stream_id, ChunkStreamId::new(4));
3294        assert_eq!(parsed[0].message_stream_id.get(), 7);
3295    }
3296
3297    #[test]
3298    fn a_timestamp_past_the_wire_width_is_refused_before_serializing() {
3299        assert!(Timestamp::try_new(Duration::from_millis(u64::from(u32::MAX) + 1)).is_err());
3300    }
3301}
3302
3303#[cfg(test)]
3304mod invalid_csid_tests {
3305    use super::*;
3306
3307    fn msg(csid: u32) -> Message {
3308        Message {
3309            chunk_stream_id: ChunkStreamId::new(csid),
3310            timestamp: Timestamp::from_millis(0),
3311            message_type_id: MessageTypeId::CommandAmf0,
3312            message_stream_id: MessageStreamId::new(1),
3313            payload: vec![1, 2, 3],
3314        }
3315    }
3316
3317    #[test]
3318    fn write_rejects_out_of_range_chunk_stream_id_without_panicking() {
3319        let mut w = ChunkWriter::new();
3320        for bad in [0u32, 1, 65600, u32::MAX] {
3321            match w.write(&msg(bad)) {
3322                Err(RtmpError::InvalidChunkStreamId { chunk_stream_id }) => {
3323                    assert_eq!(chunk_stream_id, bad);
3324                }
3325                other => panic!("csid {bad}: expected InvalidChunkStreamId, got {other:?}"),
3326            }
3327        }
3328        for ok in [2u32, 63, 64, 319, 320, 65599] {
3329            assert!(w.write(&msg(ok)).is_ok(), "csid {ok} must be accepted");
3330        }
3331    }
3332
3333    #[test]
3334    fn denial_of_service_ceilings_are_pinned_by_value() {
3335        assert_eq!(MAX_CHUNK_SIZE, 16_777_216);
3336        assert_eq!(MAX_MESSAGE_LEN, 8_388_608);
3337    }
3338
3339    /// csid 320 needs the three-byte basic header form; the assembler derives
3340    /// the header length from the wire marker.
3341    #[test]
3342    fn csid_320_three_byte_basic_header_reassembles() {
3343        let mut writer = ChunkWriter::new();
3344        let original = Message {
3345            chunk_stream_id: ChunkStreamId::new(320),
3346            timestamp: Timestamp::from_millis(5),
3347            message_type_id: MessageTypeId::Video,
3348            message_stream_id: MessageStreamId::new(1),
3349            payload: vec![0xAB; 300],
3350        };
3351        let bytes = writer.write(&original).unwrap();
3352        let rel = 320 - BASIC_HEADER_CSID_OFFSET;
3353        assert_eq!(bytes[0], BASIC_HEADER_3BYTE_MARKER);
3354        assert_eq!(bytes[1], rel as u8);
3355        assert_eq!(bytes[2], (rel >> 8) as u8);
3356
3357        let mut assembler = ChunkAssembler::new();
3358        let out = assembler.push(&bytes).unwrap();
3359        assert_eq!(out, vec![original]);
3360    }
3361
3362    /// Type 1/2 headers that used the Extended Timestamp must make their
3363    /// Type 3 continuation consume it too, or every later byte mis-frames.
3364    #[test]
3365    fn type1_type2_and_type3_extended_timestamp_chunks_reassemble() {
3366        const EXT: u32 = 0x0100_0000;
3367
3368        let mut a = Vec::new();
3369        a.push(0x04);
3370        a.extend_from_slice(&[0xFF, 0xFF, 0xFF, 0x00, 0x00, 200, 9, 1, 0, 0, 0]);
3371        a.extend_from_slice(&EXT.to_be_bytes());
3372        a.extend_from_slice(&[0xAAu8; 128]);
3373        a.push(0xC4);
3374        a.extend_from_slice(&EXT.to_be_bytes());
3375        a.extend_from_slice(&[0xABu8; 72]);
3376
3377        let mut b = Vec::new();
3378        b.push(0x44);
3379        b.extend_from_slice(&[0xFF, 0xFF, 0xFF, 0x00, 0x00, 200, 8]);
3380        b.extend_from_slice(&EXT.to_be_bytes());
3381        b.extend_from_slice(&[0xB0u8; 128]);
3382        b.push(0xC4);
3383        b.extend_from_slice(&EXT.to_be_bytes());
3384        b.extend_from_slice(&[0xB1u8; 72]);
3385
3386        let mut c = Vec::new();
3387        c.push(0x84);
3388        c.extend_from_slice(&[0xFF, 0xFF, 0xFF]);
3389        c.extend_from_slice(&EXT.to_be_bytes());
3390        c.extend_from_slice(&[0xC0u8; 128]);
3391        c.push(0xC4);
3392        c.extend_from_slice(&EXT.to_be_bytes());
3393        c.extend_from_slice(&[0xC1u8; 72]);
3394
3395        let mut wire = Vec::new();
3396        wire.extend_from_slice(&a);
3397        wire.extend_from_slice(&b);
3398        wire.extend_from_slice(&c);
3399
3400        let mut assembler = ChunkAssembler::new();
3401        let out = assembler.push(&wire).unwrap();
3402        assert_eq!(out.len(), 3);
3403        assert_eq!(out[0].chunk_stream_id, ChunkStreamId::new(4));
3404        assert_eq!(out[0].timestamp.millis(), 0x0100_0000);
3405        assert_eq!(out[0].message_type_id, MessageTypeId::Video);
3406        assert_eq!(out[0].message_stream_id, MessageStreamId::new(1));
3407        assert_eq!(&out[0].payload[..128], &vec![0xAAu8; 128][..]);
3408        assert_eq!(&out[0].payload[128..], &vec![0xABu8; 72][..]);
3409
3410        assert_eq!(out[1].timestamp.millis(), 0x0200_0000);
3411        assert_eq!(out[1].message_type_id, MessageTypeId::Audio);
3412        assert_eq!(out[1].payload.len(), 200);
3413        assert_eq!(&out[1].payload[128..], &vec![0xB1u8; 72][..]);
3414
3415        assert_eq!(out[2].timestamp.millis(), 0x0300_0000);
3416        assert_eq!(out[2].message_type_id, MessageTypeId::Audio);
3417        assert_eq!(out[2].message_stream_id, MessageStreamId::new(1));
3418        assert_eq!(&out[2].payload[128..], &vec![0xC1u8; 72][..]);
3419
3420        // The writer's Type 0 + Type 3 framing for the first message is
3421        // byte-for-byte the hand-written chunk stream above.
3422        let mut writer = ChunkWriter::new();
3423        assert_eq!(writer.write(&out[0]).unwrap(), a);
3424    }
3425
3426    #[test]
3427    fn message_header_serialized_len_counts_the_extended_timestamp() {
3428        let type0_ext = MessageHeader::Type0 {
3429            timestamp: Timestamp::from_millis(EXTENDED_TIMESTAMP_MARKER),
3430            message_length: 1,
3431            message_type_id: MessageTypeId::Video,
3432            message_stream_id: MessageStreamId::new(1),
3433        };
3434        assert_eq!(type0_ext.serialized_len(), 15);
3435        let type0 = MessageHeader::Type0 {
3436            timestamp: Timestamp::from_millis(EXTENDED_TIMESTAMP_MARKER - 1),
3437            message_length: 1,
3438            message_type_id: MessageTypeId::Video,
3439            message_stream_id: MessageStreamId::new(1),
3440        };
3441        assert_eq!(type0.serialized_len(), 11);
3442
3443        let type1_ext = MessageHeader::Type1 {
3444            timestamp_delta: Duration::from_millis(u64::from(EXTENDED_TIMESTAMP_MARKER)),
3445            message_length: 1,
3446            message_type_id: MessageTypeId::Audio,
3447        };
3448        assert_eq!(type1_ext.serialized_len(), 11);
3449        let type1 = MessageHeader::Type1 {
3450            timestamp_delta: Duration::from_millis(u64::from(EXTENDED_TIMESTAMP_MARKER - 1)),
3451            message_length: 1,
3452            message_type_id: MessageTypeId::Audio,
3453        };
3454        assert_eq!(type1.serialized_len(), 7);
3455
3456        let type2_ext = MessageHeader::Type2 {
3457            timestamp_delta: Duration::from_millis(u64::from(EXTENDED_TIMESTAMP_MARKER)),
3458        };
3459        assert_eq!(type2_ext.serialized_len(), 7);
3460        let type2 = MessageHeader::Type2 {
3461            timestamp_delta: Duration::from_millis(u64::from(EXTENDED_TIMESTAMP_MARKER - 1)),
3462        };
3463        assert_eq!(type2.serialized_len(), 3);
3464
3465        let mut buf = [0u8; 11];
3466        assert_eq!(type1_ext.serialize_into(&mut buf).unwrap(), 11);
3467        let mut buf = [0u8; 7];
3468        assert_eq!(type2_ext.serialize_into(&mut buf).unwrap(), 7);
3469    }
3470
3471    /// A Type 1/2 header whose delta overflows the 32-bit timestamp reports
3472    /// the exact summed value in the error.
3473    #[test]
3474    fn timestamp_overflow_reports_the_exact_sum_for_type1_and_type2() {
3475        const MAX_MS: u32 = u32::MAX;
3476        let type0 = |length: u32| {
3477            let mut bytes = Vec::new();
3478            bytes.push(0x04);
3479            bytes.extend_from_slice(&[0xFF, 0xFF, 0xFF]);
3480            bytes.extend_from_slice(&[0, 0, length as u8]);
3481            bytes.push(9);
3482            bytes.extend_from_slice(&1u32.to_le_bytes());
3483            bytes.extend_from_slice(&MAX_MS.to_be_bytes());
3484            bytes
3485        };
3486        let mut base = type0(1);
3487        base.push(0x00); // one payload byte completes the message
3488
3489        let mut type1 = base.clone();
3490        type1.push(0x44);
3491        type1.extend_from_slice(&[0x00, 0x00, 0x02, 0x00, 0x00, 0x01, 0x09]);
3492        match ChunkAssembler::new().push(&type1) {
3493            Err(RtmpError::FieldOverflow(e)) => {
3494                assert_eq!(e.field, "timestamp");
3495                assert_eq!(e.value, u64::from(MAX_MS) + 2);
3496            }
3497            other => panic!("expected FieldOverflow, got {other:?}"),
3498        }
3499
3500        let mut type2 = base;
3501        type2.push(0x84);
3502        type2.extend_from_slice(&[0x00, 0x00, 0x02]);
3503        match ChunkAssembler::new().push(&type2) {
3504            Err(RtmpError::FieldOverflow(e)) => {
3505                assert_eq!(e.field, "timestamp");
3506                assert_eq!(e.value, u64::from(MAX_MS) + 2);
3507            }
3508            other => panic!("expected FieldOverflow, got {other:?}"),
3509        }
3510    }
3511
3512    /// A Type 3 chunk that starts a new message re-applies the inherited
3513    /// delta; its overflow reports the exact summed value.
3514    #[test]
3515    fn type3_new_message_timestamp_overflow_reports_the_exact_sum() {
3516        const MAX_MS: u32 = u32::MAX;
3517        let mut wire = Vec::new();
3518        wire.push(0x04);
3519        wire.extend_from_slice(&[0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x01, 0x09, 1, 0, 0, 0]);
3520        wire.extend_from_slice(&MAX_MS.to_be_bytes());
3521        wire.push(0x00); // completes the one-byte message
3522        wire.push(0xC4);
3523        wire.extend_from_slice(&MAX_MS.to_be_bytes()); // inherited extended field
3524        match ChunkAssembler::new().push(&wire) {
3525            Err(RtmpError::FieldOverflow(e)) => {
3526                assert_eq!(e.field, "timestamp");
3527                assert_eq!(e.value, u64::from(MAX_MS) + u64::from(MAX_MS));
3528            }
3529            other => panic!("expected FieldOverflow, got {other:?}"),
3530        }
3531    }
3532
3533    /// The receive-buffer backstop trips one byte past twice the
3534    /// in-progress budget.
3535    #[test]
3536    fn receive_buffer_backstop_is_twice_the_in_progress_budget() {
3537        let mut assembler = ChunkAssembler::new().with_max_in_progress_bytes(8);
3538        assembler.feed(&[0u8; 16]);
3539        assert!(assembler.next_message().is_ok());
3540
3541        let mut assembler = ChunkAssembler::new().with_max_in_progress_bytes(8);
3542        assembler.feed(&[0u8; 17]);
3543        match assembler.next_message() {
3544            Err(RtmpError::InputBudgetExceeded { max }) => assert_eq!(max, 16),
3545            other => panic!("expected InputBudgetExceeded, got {other:?}"),
3546        }
3547    }
3548
3549    #[test]
3550    fn compact_drops_only_the_consumed_prefix() {
3551        let mut assembler = ChunkAssembler::new();
3552        assembler.pending.extend_from_slice(b"abcdef");
3553        assembler.cursor = 4;
3554        assembler.compact();
3555        assert_eq!(assembler.pending.as_slice(), b"ef");
3556        assert_eq!(assembler.cursor, 0);
3557    }
3558
3559    #[test]
3560    fn swap_pending_returns_only_the_unconsumed_bytes() {
3561        let mut assembler = ChunkAssembler::new();
3562        assembler.pending.extend_from_slice(b"abcde");
3563        assembler.cursor = 2;
3564        let restored = assembler.swap_pending(b"xyz");
3565        assert_eq!(restored.as_slice(), b"cde");
3566        assert_eq!(assembler.pending.as_slice(), b"xyz");
3567        assert_eq!(assembler.cursor, 0);
3568    }
3569
3570    #[test]
3571    fn pending_len_counts_the_unparsed_bytes() {
3572        let mut assembler = ChunkAssembler::new();
3573        assembler.feed(b"abc");
3574        assert_eq!(assembler.pending_len(), 3);
3575        assembler.feed(b"de");
3576        assert_eq!(assembler.pending_len(), 5);
3577    }
3578}