Skip to main content

rtmp_runtime/
chunk.rs

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