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