Skip to main content

rtmp_runtime/
chunk.rs

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