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    /// Returns [`RtmpError::InvalidChunkStreamId`] if `msg.chunk_stream_id`
1366    /// is outside the basic header's encodable range (2..=65599). Every
1367    /// `chunk_stream_id` produced by [`ChunkAssembler::push`] satisfies this
1368    /// (`BasicHeader::parse` never yields one outside the range); callers
1369    /// building a `Message` from scratch must respect it.
1370    pub fn write(&mut self, msg: &Message) -> Result<Vec<u8>> {
1371        if !(BASIC_HEADER_1BYTE_MIN_CSID..=BASIC_HEADER_3BYTE_MAX_CSID)
1372            .contains(&msg.chunk_stream_id)
1373        {
1374            return Err(RtmpError::InvalidChunkStreamId {
1375                chunk_stream_id: msg.chunk_stream_id,
1376            });
1377        }
1378        let chunk_size = (self.chunk_size as usize).max(1);
1379        let message_length = broadcast_common::len::fit_u24(msg.payload.len(), "message_length")?;
1380        let extended = needs_extended_timestamp(msg.timestamp);
1381
1382        let mut out = Vec::with_capacity(TYPE0_LEN + msg.payload.len() + 16);
1383
1384        let bh0 = BasicHeader {
1385            fmt: Fmt::Type0,
1386            chunk_stream_id: msg.chunk_stream_id,
1387        };
1388        let mh0 = MessageHeader::Type0 {
1389            timestamp: msg.timestamp,
1390            message_length,
1391            message_type_id: msg.message_type_id,
1392            message_stream_id: msg.message_stream_id,
1393        };
1394        write_serialized(&mut out, &bh0)?;
1395        write_serialized(&mut out, &mh0)?;
1396
1397        let mut offset = 0usize;
1398        let take0 = chunk_size.min(msg.payload.len());
1399        out.extend_from_slice(&msg.payload[offset..offset + take0]);
1400        offset += take0;
1401
1402        while offset < msg.payload.len() {
1403            let bh = BasicHeader {
1404                fmt: Fmt::Type3,
1405                chunk_stream_id: msg.chunk_stream_id,
1406            };
1407            write_serialized(&mut out, &bh)?;
1408            if extended {
1409                out.extend_from_slice(&msg.timestamp.to_be_bytes());
1410            }
1411            let take = chunk_size.min(msg.payload.len() - offset);
1412            out.extend_from_slice(&msg.payload[offset..offset + take]);
1413            offset += take;
1414        }
1415
1416        Ok(out)
1417    }
1418}
1419
1420/// Serialize `item` and append the bytes to `out`.
1421///
1422/// # Errors
1423/// Propagates `item.serialize_into`'s error (for the [`BasicHeader`]s this is
1424/// used with, a `chunk_stream_id` outside the encodable range).
1425fn write_serialized<T: Serialize<Error = RtmpError>>(out: &mut Vec<u8>, item: &T) -> Result<()> {
1426    let len = item.serialized_len();
1427    let start = out.len();
1428    out.resize(start + len, 0);
1429    match item.serialize_into(&mut out[start..]) {
1430        Ok(n) => {
1431            out.truncate(start + n);
1432            Ok(())
1433        }
1434        Err(e) => {
1435            out.truncate(start);
1436            Err(e)
1437        }
1438    }
1439}
1440
1441/// Test-only infallible wrapper over [`write_serialized`].
1442#[cfg(test)]
1443fn write_serialized_ok<T: Serialize<Error = RtmpError>>(out: &mut Vec<u8>, item: &T) {
1444    write_serialized(out, item).expect("valid chunk_stream_id in test fixture");
1445}
1446
1447#[cfg(test)]
1448thread_local! {
1449    /// Total payload bytes [`ChunkAssembler::try_parse_one`] has appended
1450    /// via `extend_from_slice` on this thread since the last reset — a
1451    /// test-only instrumentation hook so a regression test can assert
1452    /// reassembly does O(message length) work directly, rather than
1453    /// inferring it from wall-clock time (see
1454    /// `reassembling_an_8mib_message_at_the_floor_chunk_size_is_linear_not_quadratic`).
1455    static PAYLOAD_BYTES_COPIED_FOR_TEST: core::cell::Cell<usize> = const { core::cell::Cell::new(0) };
1456}
1457
1458#[cfg(test)]
1459fn record_payload_bytes_copied_for_test(n: usize) {
1460    PAYLOAD_BYTES_COPIED_FOR_TEST.with(|c| c.set(c.get() + n));
1461}
1462
1463#[cfg(test)]
1464fn reset_payload_bytes_copied_for_test() {
1465    PAYLOAD_BYTES_COPIED_FOR_TEST.with(|c| c.set(0));
1466}
1467
1468#[cfg(test)]
1469fn payload_bytes_copied_for_test() -> usize {
1470    PAYLOAD_BYTES_COPIED_FOR_TEST.with(core::cell::Cell::get)
1471}
1472
1473#[cfg(test)]
1474mod tests {
1475    use super::*;
1476
1477    // ── u24 helper ───────────────────────────────────────────────────────
1478
1479    #[test]
1480    fn u24_round_trip_zero() {
1481        let mut buf = [0xFFu8; U24_LEN];
1482        write_u24_be(0, &mut buf);
1483        assert_eq!(buf, [0, 0, 0]);
1484        assert_eq!(read_u24_be(&buf), 0);
1485    }
1486
1487    #[test]
1488    fn u24_round_trip_max() {
1489        let mut buf = [0u8; U24_LEN];
1490        write_u24_be(0x00FF_FFFF, &mut buf);
1491        assert_eq!(buf, [0xFF, 0xFF, 0xFF]);
1492        assert_eq!(read_u24_be(&buf), 0x00FF_FFFF);
1493    }
1494
1495    #[test]
1496    fn u24_round_trip_mid_value() {
1497        let mut buf = [0u8; U24_LEN];
1498        write_u24_be(0x0012_3456, &mut buf);
1499        assert_eq!(buf, [0x12, 0x34, 0x56]);
1500        assert_eq!(read_u24_be(&buf), 0x0012_3456);
1501    }
1502
1503    // ── Fmt ──────────────────────────────────────────────────────────────
1504
1505    #[test]
1506    fn fmt_from_bits_round_trip() {
1507        for (bits, fmt) in [
1508            (0u8, Fmt::Type0),
1509            (1, Fmt::Type1),
1510            (2, Fmt::Type2),
1511            (3, Fmt::Type3),
1512        ] {
1513            let parsed = Fmt::from_bits(bits).unwrap();
1514            assert_eq!(parsed, fmt);
1515            assert_eq!(parsed.to_bits(), bits);
1516        }
1517    }
1518
1519    #[test]
1520    fn fmt_from_bits_out_of_range_is_malformed() {
1521        assert!(matches!(
1522            Fmt::from_bits(4),
1523            Err(RtmpError::Malformed { .. })
1524        ));
1525    }
1526
1527    #[test]
1528    fn fmt_display_matches_name() {
1529        assert_eq!(Fmt::Type0.to_string(), "type 0");
1530        assert_eq!(Fmt::Type3.to_string(), "type 3");
1531    }
1532
1533    // ── BasicHeader: 1-byte form ─────────────────────────────────────────
1534
1535    #[test]
1536    fn basic_header_one_byte_form_round_trip_build_serialize_parse() {
1537        for csid in [BASIC_HEADER_1BYTE_MIN_CSID, 5, BASIC_HEADER_1BYTE_MAX_CSID] {
1538            let bh = BasicHeader {
1539                fmt: Fmt::Type1,
1540                chunk_stream_id: csid,
1541            };
1542            let mut buf = [0u8; 1];
1543            let n = bh.serialize_into(&mut buf).unwrap();
1544            assert_eq!(n, 1, "csid {csid} must use the 1-byte form");
1545            let parsed = BasicHeader::parse(&buf).unwrap();
1546            assert_eq!(parsed, bh);
1547        }
1548    }
1549
1550    #[test]
1551    fn basic_header_one_byte_form_parse_serialize_byte_identical() {
1552        // fmt=1 (bits 01), csid=5: byte0 = 0b01_000101 = 0x45.
1553        let bytes = [0x45u8];
1554        let bh = BasicHeader::parse(&bytes).unwrap();
1555        assert_eq!(bh.fmt, Fmt::Type1);
1556        assert_eq!(bh.chunk_stream_id, 5);
1557        let mut buf = [0u8; 1];
1558        bh.serialize_into(&mut buf).unwrap();
1559        assert_eq!(buf, bytes);
1560    }
1561
1562    // ── BasicHeader: 2-byte form ─────────────────────────────────────────
1563
1564    #[test]
1565    fn basic_header_two_byte_form_round_trip_boundaries() {
1566        for csid in [
1567            BASIC_HEADER_2BYTE_MIN_CSID,
1568            200,
1569            BASIC_HEADER_2BYTE_MAX_CSID,
1570        ] {
1571            let bh = BasicHeader {
1572                fmt: Fmt::Type2,
1573                chunk_stream_id: csid,
1574            };
1575            let mut buf = [0u8; 2];
1576            let n = bh.serialize_into(&mut buf).unwrap();
1577            assert_eq!(n, 2, "csid {csid} must use the minimal 2-byte form");
1578            let parsed = BasicHeader::parse(&buf).unwrap();
1579            assert_eq!(parsed, bh);
1580        }
1581    }
1582
1583    #[test]
1584    fn basic_header_two_byte_form_parse_serialize_byte_identical() {
1585        // fmt=2 (bits 10), marker 0, csid-64 = 0 => csid 64.
1586        let bytes = [0b10_000000u8, 0x00];
1587        let bh = BasicHeader::parse(&bytes).unwrap();
1588        assert_eq!(bh.fmt, Fmt::Type2);
1589        assert_eq!(bh.chunk_stream_id, 64);
1590        let mut buf = [0u8; 2];
1591        bh.serialize_into(&mut buf).unwrap();
1592        assert_eq!(buf, bytes);
1593    }
1594
1595    // ── BasicHeader: 3-byte form ─────────────────────────────────────────
1596
1597    #[test]
1598    fn basic_header_three_byte_form_round_trip_boundaries() {
1599        for csid in [
1600            BASIC_HEADER_3BYTE_MIN_CSID,
1601            40000,
1602            BASIC_HEADER_3BYTE_MAX_CSID,
1603        ] {
1604            let bh = BasicHeader {
1605                fmt: Fmt::Type3,
1606                chunk_stream_id: csid,
1607            };
1608            let mut buf = [0u8; 3];
1609            let n = bh.serialize_into(&mut buf).unwrap();
1610            assert_eq!(n, 3, "csid {csid} must use the 3-byte form");
1611            let parsed = BasicHeader::parse(&buf).unwrap();
1612            assert_eq!(parsed, bh);
1613        }
1614    }
1615
1616    #[test]
1617    fn basic_header_three_byte_form_parse_serialize_byte_identical() {
1618        // fmt=0, marker 1, csid-64 = 0xFFFF (LE: byte1=0xFF, byte2=0xFF) => csid 65599.
1619        let bytes = [0b00_000001u8, 0xFF, 0xFF];
1620        let bh = BasicHeader::parse(&bytes).unwrap();
1621        assert_eq!(bh.fmt, Fmt::Type0);
1622        assert_eq!(bh.chunk_stream_id, BASIC_HEADER_3BYTE_MAX_CSID);
1623        let mut buf = [0u8; 3];
1624        bh.serialize_into(&mut buf).unwrap();
1625        assert_eq!(buf, bytes);
1626    }
1627
1628    #[test]
1629    fn basic_header_2byte_and_3byte_csid_are_little_endian() {
1630        // csid = 64 + 0x0102 = 0x0142 = 322. 3-byte form: byte1=low=0x02, byte2=high=0x01.
1631        let bh = BasicHeader {
1632            fmt: Fmt::Type0,
1633            chunk_stream_id: 64 + 0x0102,
1634        };
1635        let mut buf = [0u8; 3];
1636        bh.serialize_into(&mut buf).unwrap();
1637        assert_eq!(buf[1], 0x02, "low byte of csid-64 must come first");
1638        assert_eq!(buf[2], 0x01, "high byte of csid-64 must come second");
1639        assert_eq!(BasicHeader::parse(&buf).unwrap(), bh);
1640    }
1641
1642    // ── BasicHeader: errors ──────────────────────────────────────────────
1643
1644    #[test]
1645    fn basic_header_csid_zero_is_malformed_on_serialize() {
1646        let bh = BasicHeader {
1647            fmt: Fmt::Type0,
1648            chunk_stream_id: 0,
1649        };
1650        let mut buf = [0u8; 3];
1651        assert!(matches!(
1652            bh.serialize_into(&mut buf),
1653            Err(RtmpError::Malformed { .. })
1654        ));
1655    }
1656
1657    #[test]
1658    fn basic_header_csid_one_is_malformed_on_serialize() {
1659        let bh = BasicHeader {
1660            fmt: Fmt::Type0,
1661            chunk_stream_id: 1,
1662        };
1663        let mut buf = [0u8; 3];
1664        assert!(matches!(
1665            bh.serialize_into(&mut buf),
1666            Err(RtmpError::Malformed { .. })
1667        ));
1668    }
1669
1670    #[test]
1671    fn basic_header_csid_above_max_is_malformed_on_serialize() {
1672        let bh = BasicHeader {
1673            fmt: Fmt::Type0,
1674            chunk_stream_id: BASIC_HEADER_3BYTE_MAX_CSID + 1,
1675        };
1676        let mut buf = [0u8; 3];
1677        assert!(matches!(
1678            bh.serialize_into(&mut buf),
1679            Err(RtmpError::Malformed { .. })
1680        ));
1681    }
1682
1683    #[test]
1684    fn basic_header_empty_input_is_buffer_too_short() {
1685        assert!(matches!(
1686            BasicHeader::parse(&[]),
1687            Err(RtmpError::BufferTooShort {
1688                need: 1,
1689                have: 0,
1690                ..
1691            })
1692        ));
1693    }
1694
1695    #[test]
1696    fn basic_header_truncated_two_byte_form_is_buffer_too_short() {
1697        let bytes = [0b00_000000u8]; // marker=0 (2-byte form) but only 1 byte given.
1698        assert!(matches!(
1699            BasicHeader::parse(&bytes),
1700            Err(RtmpError::BufferTooShort {
1701                need: 2,
1702                have: 1,
1703                ..
1704            })
1705        ));
1706    }
1707
1708    #[test]
1709    fn basic_header_truncated_three_byte_form_is_buffer_too_short() {
1710        let bytes = [0b00_000001u8, 0xAB]; // marker=1 (3-byte form) but only 2 bytes given.
1711        assert!(matches!(
1712            BasicHeader::parse(&bytes),
1713            Err(RtmpError::BufferTooShort {
1714                need: 3,
1715                have: 2,
1716                ..
1717            })
1718        ));
1719    }
1720
1721    // ── MessageHeader: Type 0 ────────────────────────────────────────────
1722
1723    #[test]
1724    fn type0_round_trip_build_serialize_parse_no_extended() {
1725        let mh = MessageHeader::Type0 {
1726            timestamp: 0x0011_2233,
1727            message_length: 0x0004_5566,
1728            message_type_id: 0x09,
1729            message_stream_id: 0xAABB_CCDD,
1730        };
1731        let mut buf = [0u8; TYPE0_LEN];
1732        let n = mh.serialize_into(&mut buf).unwrap();
1733        assert_eq!(n, TYPE0_LEN);
1734        let (parsed, consumed) = MessageHeader::parse(Fmt::Type0, &buf).unwrap();
1735        assert_eq!(consumed, TYPE0_LEN);
1736        assert_eq!(parsed, mh);
1737    }
1738
1739    #[test]
1740    fn type0_parse_serialize_byte_identical_no_extended_and_le_stream_id() {
1741        // timestamp = 0x001122 (< marker, no extension).
1742        // message_length = 0x334455.
1743        // message_type_id = 0x09.
1744        // message_stream_id = 0xAABBCCDD, wire LE => DD CC BB AA.
1745        let bytes: [u8; TYPE0_LEN] = [
1746            0x00, 0x11, 0x22, // timestamp
1747            0x33, 0x44, 0x55, // message_length
1748            0x09, // message_type_id
1749            0xDD, 0xCC, 0xBB, 0xAA, // message_stream_id, little-endian
1750        ];
1751        let (mh, consumed) = MessageHeader::parse(Fmt::Type0, &bytes).unwrap();
1752        assert_eq!(consumed, TYPE0_LEN);
1753        assert_eq!(
1754            mh,
1755            MessageHeader::Type0 {
1756                timestamp: 0x0000_1122,
1757                message_length: 0x0033_4455,
1758                message_type_id: 0x09,
1759                message_stream_id: 0xAABB_CCDD,
1760            }
1761        );
1762        let mut buf = [0u8; TYPE0_LEN];
1763        mh.serialize_into(&mut buf).unwrap();
1764        assert_eq!(
1765            buf, bytes,
1766            "byte-identical round trip, LE stream id included"
1767        );
1768    }
1769
1770    #[test]
1771    fn type0_extended_timestamp_parse_serialize_byte_identical() {
1772        // 24-bit timestamp field = sentinel 0xFFFFFF => extended 4-byte BE
1773        // timestamp follows, value 0x01020304 (chosen so BE != LE, catching
1774        // an endianness bug in the extended field).
1775        let bytes: [u8; TYPE0_LEN + 4] = [
1776            0xFF, 0xFF, 0xFF, // timestamp sentinel
1777            0x00, 0x00, 0x10, // message_length
1778            0x08, // message_type_id
1779            0x01, 0x00, 0x00, 0x00, // message_stream_id = 1, LE
1780            0x01, 0x02, 0x03, 0x04, // extended timestamp, big-endian
1781        ];
1782        let (mh, consumed) = MessageHeader::parse(Fmt::Type0, &bytes).unwrap();
1783        assert_eq!(consumed, TYPE0_LEN + 4);
1784        assert_eq!(
1785            mh,
1786            MessageHeader::Type0 {
1787                timestamp: 0x0102_0304,
1788                message_length: 0x0000_0010,
1789                message_type_id: 0x08,
1790                message_stream_id: 1,
1791            }
1792        );
1793        let mut buf = [0u8; TYPE0_LEN + 4];
1794        let n = mh.serialize_into(&mut buf).unwrap();
1795        assert_eq!(n, TYPE0_LEN + 4);
1796        assert_eq!(
1797            buf, bytes,
1798            "extended timestamp path must round-trip byte-identically"
1799        );
1800    }
1801
1802    #[test]
1803    fn type0_timestamp_exactly_at_marker_boundary_uses_extended_path() {
1804        // timestamp == EXTENDED_TIMESTAMP_MARKER exactly: per spec this MUST
1805        // still go through the extended-timestamp path (">=", not ">").
1806        let mh = MessageHeader::Type0 {
1807            timestamp: EXTENDED_TIMESTAMP_MARKER,
1808            message_length: 10,
1809            message_type_id: 1,
1810            message_stream_id: 0,
1811        };
1812        assert_eq!(mh.serialized_len(), TYPE0_LEN + 4);
1813        let mut buf = [0u8; TYPE0_LEN + 4];
1814        let n = mh.serialize_into(&mut buf).unwrap();
1815        assert_eq!(n, TYPE0_LEN + 4);
1816        assert_eq!(
1817            &buf[0..3],
1818            [0xFF, 0xFF, 0xFF],
1819            "24-bit field must be the sentinel"
1820        );
1821        assert_eq!(
1822            &buf[11..15],
1823            &EXTENDED_TIMESTAMP_MARKER.to_be_bytes()[..],
1824            "extended field carries the real value"
1825        );
1826        let (parsed, consumed) = MessageHeader::parse(Fmt::Type0, &buf).unwrap();
1827        assert_eq!(consumed, TYPE0_LEN + 4);
1828        assert_eq!(parsed, mh);
1829    }
1830
1831    // ── MessageHeader: Type 1 ────────────────────────────────────────────
1832
1833    #[test]
1834    fn type1_round_trip_build_serialize_parse_no_extended() {
1835        let mh = MessageHeader::Type1 {
1836            timestamp_delta: 20,
1837            message_length: 32,
1838            message_type_id: 8,
1839        };
1840        let mut buf = [0u8; TYPE1_LEN];
1841        let n = mh.serialize_into(&mut buf).unwrap();
1842        assert_eq!(n, TYPE1_LEN);
1843        let (parsed, consumed) = MessageHeader::parse(Fmt::Type1, &buf).unwrap();
1844        assert_eq!(consumed, TYPE1_LEN);
1845        assert_eq!(parsed, mh);
1846    }
1847
1848    #[test]
1849    fn type1_extended_timestamp_parse_serialize_byte_identical() {
1850        let bytes: [u8; TYPE1_LEN + 4] = [
1851            0xFF, 0xFF, 0xFF, // timestamp_delta sentinel
1852            0x00, 0x00, 0x20, // message_length
1853            0x09, // message_type_id
1854            0x0A, 0x0B, 0x0C, 0x0D, // extended timestamp delta, big-endian
1855        ];
1856        let (mh, consumed) = MessageHeader::parse(Fmt::Type1, &bytes).unwrap();
1857        assert_eq!(consumed, TYPE1_LEN + 4);
1858        assert_eq!(
1859            mh,
1860            MessageHeader::Type1 {
1861                timestamp_delta: 0x0A0B_0C0D,
1862                message_length: 0x0000_0020,
1863                message_type_id: 0x09,
1864            }
1865        );
1866        let mut buf = [0u8; TYPE1_LEN + 4];
1867        mh.serialize_into(&mut buf).unwrap();
1868        assert_eq!(buf, bytes);
1869    }
1870
1871    // ── MessageHeader: Type 2 ────────────────────────────────────────────
1872
1873    #[test]
1874    fn type2_round_trip_build_serialize_parse_no_extended() {
1875        let mh = MessageHeader::Type2 {
1876            timestamp_delta: 20,
1877        };
1878        let mut buf = [0u8; TYPE2_LEN];
1879        let n = mh.serialize_into(&mut buf).unwrap();
1880        assert_eq!(n, TYPE2_LEN);
1881        let (parsed, consumed) = MessageHeader::parse(Fmt::Type2, &buf).unwrap();
1882        assert_eq!(consumed, TYPE2_LEN);
1883        assert_eq!(parsed, mh);
1884    }
1885
1886    #[test]
1887    fn type2_extended_timestamp_parse_serialize_byte_identical() {
1888        let bytes: [u8; TYPE2_LEN + 4] = [
1889            0xFF, 0xFF, 0xFF, // timestamp_delta sentinel
1890            0x11, 0x22, 0x33, 0x44, // extended timestamp delta, big-endian
1891        ];
1892        let (mh, consumed) = MessageHeader::parse(Fmt::Type2, &bytes).unwrap();
1893        assert_eq!(consumed, TYPE2_LEN + 4);
1894        assert_eq!(
1895            mh,
1896            MessageHeader::Type2 {
1897                timestamp_delta: 0x1122_3344,
1898            }
1899        );
1900        let mut buf = [0u8; TYPE2_LEN + 4];
1901        mh.serialize_into(&mut buf).unwrap();
1902        assert_eq!(buf, bytes);
1903    }
1904
1905    // ── MessageHeader: Type 3 ────────────────────────────────────────────
1906
1907    #[test]
1908    fn type3_round_trip_is_zero_bytes() {
1909        let mh = MessageHeader::Type3;
1910        assert_eq!(mh.serialized_len(), 0);
1911        let mut buf: [u8; 0] = [];
1912        let n = mh.serialize_into(&mut buf).unwrap();
1913        assert_eq!(n, 0);
1914        let (parsed, consumed) = MessageHeader::parse(Fmt::Type3, &[]).unwrap();
1915        assert_eq!(consumed, 0);
1916        assert_eq!(parsed, MessageHeader::Type3);
1917    }
1918
1919    // ── MessageHeader: errors ────────────────────────────────────────────
1920
1921    #[test]
1922    fn type0_truncated_input_is_buffer_too_short() {
1923        let bytes = [0u8; TYPE0_LEN - 1];
1924        assert!(matches!(
1925            MessageHeader::parse(Fmt::Type0, &bytes),
1926            Err(RtmpError::BufferTooShort {
1927                need: TYPE0_LEN,
1928                ..
1929            })
1930        ));
1931    }
1932
1933    #[test]
1934    fn type0_extended_marker_but_truncated_extended_field_is_buffer_too_short() {
1935        let mut bytes = [0u8; TYPE0_LEN + 2]; // only 2 of the 4 extended bytes.
1936        bytes[0] = 0xFF;
1937        bytes[1] = 0xFF;
1938        bytes[2] = 0xFF;
1939        assert!(matches!(
1940            MessageHeader::parse(Fmt::Type0, &bytes),
1941            Err(RtmpError::BufferTooShort {
1942                need,
1943                ..
1944            }) if need == TYPE0_LEN + 4
1945        ));
1946    }
1947
1948    // ── Mutation-check sentinels ─────────────────────────────────────────
1949    // These pin exact wire-byte expectations (not just self-round-trip),
1950    // so a serializer that silently drops the extended-timestamp tail, or
1951    // mis-orders the little-endian message_stream_id, fails a test above:
1952    // `type0_parse_serialize_byte_identical_no_extended_and_le_stream_id`
1953    // hand-builds its expected bytes with the stream id reversed from host
1954    // order, and `type0_extended_timestamp_parse_serialize_byte_identical`
1955    // hand-builds a 15-byte fixture whose length alone (`TYPE0_LEN + 4`)
1956    // fails if the extended tail is ever omitted.
1957
1958    #[test]
1959    fn message_stream_id_le_differs_from_be_for_asymmetric_value() {
1960        // Sanity check that our fixture value's LE and BE encodings differ,
1961        // so the byte-identical test above truly exercises endianness (a
1962        // palindromic value like 0x01010101 would pass either order).
1963        let v: u32 = 0xAABB_CCDD;
1964        assert_ne!(v.to_le_bytes(), v.to_be_bytes());
1965    }
1966
1967    // ── ChunkAssembler / ChunkWriter ─────────────────────────────────────
1968
1969    fn msg(csid: u32, timestamp: u32, type_id: u8, stream_id: u32, payload: Vec<u8>) -> Message {
1970        Message {
1971            chunk_stream_id: csid,
1972            timestamp,
1973            message_type_id: type_id,
1974            message_stream_id: stream_id,
1975            payload,
1976        }
1977    }
1978
1979    #[test]
1980    fn writer_assembler_round_trip_small_message_single_chunk() {
1981        let original = msg(4, 1000, 9, 1, vec![0xAB; 50]);
1982        let mut writer = ChunkWriter::new();
1983        let bytes = writer.write(&original).unwrap();
1984
1985        let mut assembler = ChunkAssembler::new();
1986        let out = assembler.push(&bytes).unwrap();
1987        assert_eq!(out.len(), 1, "one message must come back out");
1988        assert_eq!(out[0], original);
1989    }
1990
1991    /// A 16 MiB (2^24) payload cannot fit the 24-bit `message_length` field
1992    /// (#1129): unfixed, `payload.len() as u32` then the UI24 writer kept
1993    /// only the low 24 bits, silently misframing the chunk stream with `Ok`.
1994    #[test]
1995    fn write_oversized_payload_errors() {
1996        let original = msg(4, 0, 9, 1, vec![0xABu8; 1 << 24]);
1997        let err = ChunkWriter::new().write(&original).unwrap_err();
1998        assert!(
1999            matches!(
2000                err,
2001                RtmpError::FieldOverflow(broadcast_common::len::FieldOverflow {
2002                    field: "message_length",
2003                    ..
2004                })
2005            ),
2006            "expected FieldOverflow for message_length, got {err:?}"
2007        );
2008    }
2009
2010    /// The boundary: exactly (2^24 - 1) bytes still writes and reassembles.
2011    #[test]
2012    fn write_max_payload_message_length_field_is_exact() {
2013        // ChunkAssembler has its own, separate 8 MiB reassembly cap
2014        // (MAX_MESSAGE_LEN) below this field's 16 MiB wire max, so this
2015        // checks the written header bytes directly rather than
2016        // round-tripping through the assembler.
2017        let payload = vec![0xCDu8; (1 << 24) - 1];
2018        let original = msg(4, 0, 9, 1, payload.clone());
2019        let bytes = ChunkWriter::new().write(&original).unwrap();
2020
2021        // BasicHeader (1 byte, csid 4) + timestamp (3 bytes) precede
2022        // message_length (3 bytes, §5.3.1.2.1).
2023        let message_length = read_u24_be(&bytes[4..7]);
2024        assert_eq!(message_length, (1 << 24) - 1);
2025    }
2026
2027    #[test]
2028    fn writer_assembler_round_trip_message_larger_than_chunk_size() {
2029        // 300-byte payload at the default 128-byte chunk size => 3 chunks
2030        // (128 + 128 + 44): Type 0 first chunk, two Type 3 continuations.
2031        let original = msg(6, 5000, 9, 42, (0u8..=255).cycle().take(300).collect());
2032        let mut writer = ChunkWriter::new();
2033        let bytes = writer.write(&original).unwrap();
2034
2035        // Sanity: verify the byte stream really contains 3 chunks (1 basic
2036        // header for csid 6 is 1 byte; Type 0 header is TYPE0_LEN; then 128
2037        // payload bytes; then two Type 3 (1-byte basic header, 0-byte
2038        // message header) + payload chunks of 128 and 44).
2039        let expected_len = 1 + TYPE0_LEN + 128 + (1 + 128) + (1 + 44);
2040        assert_eq!(bytes.len(), expected_len);
2041
2042        let mut assembler = ChunkAssembler::new();
2043        let out = assembler.push(&bytes).unwrap();
2044        assert_eq!(
2045            out.len(),
2046            1,
2047            "the 3 chunks must reassemble into ONE message"
2048        );
2049        assert_eq!(out[0], original);
2050        assert_eq!(out[0].payload.len(), 300);
2051    }
2052
2053    #[test]
2054    fn assembler_multi_chunk_payload_reassembled_in_order() {
2055        // Hand-built stream: Type 0 header (csid 3, len 10, type 8, stream
2056        // 0, timestamp 0) with 4 payload bytes, chunk size forced to 4, then
2057        // two Type 3 continuations of 4 and 2 bytes — assert the payload
2058        // comes back concatenated in the right order, not reordered.
2059        let mut assembler = ChunkAssembler::new();
2060        assembler.set_chunk_size(4);
2061
2062        let bh0 = BasicHeader {
2063            fmt: Fmt::Type0,
2064            chunk_stream_id: 3,
2065        };
2066        let mh0 = MessageHeader::Type0 {
2067            timestamp: 0,
2068            message_length: 10,
2069            message_type_id: 8,
2070            message_stream_id: 0,
2071        };
2072        let mut input = Vec::new();
2073        write_serialized_ok(&mut input, &bh0);
2074        write_serialized_ok(&mut input, &mh0);
2075        input.extend_from_slice(&[1, 2, 3, 4]);
2076
2077        let bh3 = BasicHeader {
2078            fmt: Fmt::Type3,
2079            chunk_stream_id: 3,
2080        };
2081        write_serialized_ok(&mut input, &bh3);
2082        input.extend_from_slice(&[5, 6, 7, 8]);
2083        write_serialized_ok(&mut input, &bh3);
2084        input.extend_from_slice(&[9, 10]);
2085
2086        let out = assembler.push(&input).unwrap();
2087        assert_eq!(out.len(), 1);
2088        assert_eq!(out[0].payload, vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
2089    }
2090
2091    #[test]
2092    fn assembler_header_inheritance_type0_type1_type2_type3() {
2093        // fmt0 (ts=1000, len=5, type=8, stream=7) -> fmt1 (delta=20) ->
2094        // fmt2 (delta=30) -> fmt3 (inherits fmt2's delta=30). Each chunk's
2095        // message completes in one go (message_length == chunk_size == 5)
2096        // so every header starts a fresh message on this csid.
2097        let mut assembler = ChunkAssembler::new();
2098        assembler.set_chunk_size(5);
2099        let csid = 5;
2100
2101        let mut input = Vec::new();
2102        write_serialized_ok(
2103            &mut input,
2104            &BasicHeader {
2105                fmt: Fmt::Type0,
2106                chunk_stream_id: csid,
2107            },
2108        );
2109        write_serialized_ok(
2110            &mut input,
2111            &MessageHeader::Type0 {
2112                timestamp: 1000,
2113                message_length: 5,
2114                message_type_id: 8,
2115                message_stream_id: 7,
2116            },
2117        );
2118        input.extend_from_slice(&[0; 5]);
2119
2120        write_serialized_ok(
2121            &mut input,
2122            &BasicHeader {
2123                fmt: Fmt::Type1,
2124                chunk_stream_id: csid,
2125            },
2126        );
2127        write_serialized_ok(
2128            &mut input,
2129            &MessageHeader::Type1 {
2130                timestamp_delta: 20,
2131                message_length: 5,
2132                message_type_id: 8,
2133            },
2134        );
2135        input.extend_from_slice(&[1; 5]);
2136
2137        write_serialized_ok(
2138            &mut input,
2139            &BasicHeader {
2140                fmt: Fmt::Type2,
2141                chunk_stream_id: csid,
2142            },
2143        );
2144        write_serialized_ok(
2145            &mut input,
2146            &MessageHeader::Type2 {
2147                timestamp_delta: 30,
2148            },
2149        );
2150        input.extend_from_slice(&[2; 5]);
2151
2152        write_serialized_ok(
2153            &mut input,
2154            &BasicHeader {
2155                fmt: Fmt::Type3,
2156                chunk_stream_id: csid,
2157            },
2158        );
2159        input.extend_from_slice(&[3; 5]);
2160
2161        let out = assembler.push(&input).unwrap();
2162        assert_eq!(out.len(), 4);
2163
2164        assert_eq!(out[0].timestamp, 1000);
2165        assert_eq!(out[0].message_stream_id, 7);
2166        assert_eq!(out[0].message_type_id, 8);
2167        assert_eq!(out[0].payload, vec![0; 5]);
2168
2169        assert_eq!(out[1].timestamp, 1020, "fmt1: 1000 + delta 20");
2170        assert_eq!(out[1].message_stream_id, 7, "fmt1 inherits stream id");
2171        assert_eq!(out[1].message_type_id, 8);
2172        assert_eq!(out[1].payload, vec![1; 5]);
2173
2174        assert_eq!(out[2].timestamp, 1050, "fmt2: 1020 + delta 30");
2175        assert_eq!(out[2].message_stream_id, 7, "fmt2 inherits stream id");
2176        assert_eq!(out[2].message_type_id, 8, "fmt2 inherits type id");
2177        assert_eq!(out[2].payload, vec![2; 5], "fmt2 inherits message length");
2178
2179        assert_eq!(
2180            out[3].timestamp, 1080,
2181            "fmt3 (new message) inherits fmt2's delta 30: 1050 + 30"
2182        );
2183        assert_eq!(out[3].message_stream_id, 7, "fmt3 inherits stream id");
2184        assert_eq!(out[3].message_type_id, 8, "fmt3 inherits type id");
2185        assert_eq!(out[3].payload, vec![3; 5], "fmt3 inherits message length");
2186    }
2187
2188    #[test]
2189    fn assembler_mid_stream_set_chunk_size_changes_split_boundary() {
2190        // First message at chunk_size 128 (default): a 10-byte message on
2191        // csid 7 fits in one chunk. Then shrink chunk_size to 4 and send a
2192        // second 10-byte message on the same csid (fresh Type 0): it must
2193        // now arrive in 3 physical chunks (4 + 4 + 2), and pushing only the
2194        // first two must NOT complete the message yet.
2195        let mut assembler = ChunkAssembler::new();
2196        let csid = 7;
2197
2198        let first = msg(csid, 100, 8, 1, vec![0xAA; 10]);
2199        let mut writer = ChunkWriter::new();
2200        let first_bytes = writer.write(&first).unwrap();
2201        let out = assembler.push(&first_bytes).unwrap();
2202        assert_eq!(out, vec![first]);
2203
2204        assembler.set_chunk_size(4);
2205        let bh0 = BasicHeader {
2206            fmt: Fmt::Type0,
2207            chunk_stream_id: csid,
2208        };
2209        let mh0 = MessageHeader::Type0 {
2210            timestamp: 200,
2211            message_length: 10,
2212            message_type_id: 8,
2213            message_stream_id: 1,
2214        };
2215        let mut chunk1 = Vec::new();
2216        write_serialized_ok(&mut chunk1, &bh0);
2217        write_serialized_ok(&mut chunk1, &mh0);
2218        chunk1.extend_from_slice(&[1, 2, 3, 4]);
2219        let out = assembler.push(&chunk1).unwrap();
2220        assert!(
2221            out.is_empty(),
2222            "only 4 of 10 payload bytes arrived, message must not complete yet"
2223        );
2224
2225        let bh3 = BasicHeader {
2226            fmt: Fmt::Type3,
2227            chunk_stream_id: csid,
2228        };
2229        let mut chunk2 = Vec::new();
2230        write_serialized_ok(&mut chunk2, &bh3);
2231        chunk2.extend_from_slice(&[5, 6, 7, 8]);
2232        let out = assembler.push(&chunk2).unwrap();
2233        assert!(out.is_empty(), "8 of 10 payload bytes, still incomplete");
2234
2235        let mut chunk3 = Vec::new();
2236        write_serialized_ok(&mut chunk3, &bh3);
2237        chunk3.extend_from_slice(&[9, 10]);
2238        let out = assembler.push(&chunk3).unwrap();
2239        assert_eq!(out.len(), 1);
2240        assert_eq!(out[0].payload, vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
2241    }
2242
2243    #[test]
2244    fn writer_assembler_round_trip_extended_timestamp_split_across_chunks() {
2245        // timestamp >= EXTENDED_TIMESTAMP_MARKER forces the Type 0 header
2246        // (and every Type 3 continuation) to carry the 4-byte Extended
2247        // Timestamp (§3.1.3) — payload longer than chunk_size so at least
2248        // one Type 3 continuation chunk exercises the "fmt3 also carries
2249        // extended timestamp" edge.
2250        let original = msg(8, EXTENDED_TIMESTAMP_MARKER + 12345, 9, 2, vec![0x7E; 300]);
2251        let mut writer = ChunkWriter::new();
2252        let bytes = writer.write(&original).unwrap();
2253
2254        // Sanity: the first chunk's basic header + Type0 header must be
2255        // TYPE0_LEN + 4 (extended) bytes, and each Type 3 continuation
2256        // basic header must be immediately followed by 4 extended bytes
2257        // before its payload slice.
2258        let bh_len = 1; // csid 8 fits the 1-byte basic header form.
2259        let first_header_len = bh_len + TYPE0_LEN + EXTENDED_TIMESTAMP_LEN;
2260        assert_eq!(&bytes[bh_len..bh_len + 3], [0xFF, 0xFF, 0xFF]);
2261        let ext_offset = bh_len + TYPE0_LEN;
2262        assert_eq!(
2263            &bytes[ext_offset..ext_offset + 4],
2264            &original.timestamp.to_be_bytes()
2265        );
2266        let first_payload_take = 128usize;
2267        let second_chunk_start = first_header_len + first_payload_take;
2268        // second chunk: 1-byte Type 3 basic header + 4-byte extended ts.
2269        assert_eq!(bytes[second_chunk_start] >> 6, Fmt::Type3.to_bits());
2270        let second_ext_offset = second_chunk_start + 1;
2271        assert_eq!(
2272            &bytes[second_ext_offset..second_ext_offset + 4],
2273            &original.timestamp.to_be_bytes(),
2274            "fmt3 continuation must carry the same extended timestamp"
2275        );
2276
2277        let mut assembler = ChunkAssembler::new();
2278        let out = assembler.push(&bytes).unwrap();
2279        assert_eq!(out.len(), 1);
2280        assert_eq!(out[0], original);
2281        assert_eq!(out[0].timestamp, EXTENDED_TIMESTAMP_MARKER + 12345);
2282    }
2283
2284    #[test]
2285    fn assembler_partial_feed_split_mid_header_no_drop_or_duplicate() {
2286        let original = msg(9, 42, 8, 3, vec![0x11; 200]);
2287        let mut writer = ChunkWriter::new();
2288        let bytes = writer.write(&original).unwrap();
2289
2290        // Split at an arbitrary offset that lands inside the Type 0 header
2291        // (byte 3 of 11), well before any payload.
2292        let split_at = 4;
2293        assert!(split_at < 1 + TYPE0_LEN);
2294
2295        let mut assembler = ChunkAssembler::new();
2296        let out1 = assembler.push(&bytes[..split_at]).unwrap();
2297        assert!(out1.is_empty(), "partial header must not error or complete");
2298        let out2 = assembler.push(&bytes[split_at..]).unwrap();
2299        assert_eq!(out2.len(), 1, "message must complete exactly once");
2300        assert_eq!(out2[0], original);
2301    }
2302
2303    #[test]
2304    fn assembler_partial_feed_split_mid_payload_no_drop_or_duplicate() {
2305        let original = msg(10, 42, 8, 3, vec![0x22; 300]);
2306        let mut writer = ChunkWriter::new();
2307        let bytes = writer.write(&original).unwrap();
2308
2309        // Split partway through the first (128-byte) payload chunk.
2310        let split_at = 1 + TYPE0_LEN + 60;
2311        let mut assembler = ChunkAssembler::new();
2312        let out1 = assembler.push(&bytes[..split_at]).unwrap();
2313        assert!(out1.is_empty());
2314        let out2 = assembler.push(&bytes[split_at..]).unwrap();
2315        assert_eq!(out2.len(), 1);
2316        assert_eq!(out2[0], original);
2317    }
2318
2319    /// RTMP-W2 (#1108): `Abort` on a csid with an in-progress message must
2320    /// discard it, so the next Type 0 message on that csid parses cleanly
2321    /// instead of the following chunk being read as a continuation of the
2322    /// aborted (never-completed) payload.
2323    #[test]
2324    fn abort_discards_in_progress_message_on_csid() {
2325        let aborted = msg(12, 1, 8, 3, vec![0xAA; 300]); // spans 3 chunks at default 128
2326        let mut writer = ChunkWriter::new();
2327        let aborted_bytes = writer.write(&aborted).unwrap();
2328
2329        // Feed only the first chunk (Type 0 header + 128 bytes) — the
2330        // message is left in-progress on csid 12.
2331        let split_at = 1 + TYPE0_LEN + 128;
2332        let mut assembler = ChunkAssembler::new();
2333        let out = assembler.push(&aborted_bytes[..split_at]).unwrap();
2334        assert!(out.is_empty(), "message must still be in progress");
2335
2336        assembler.abort(12);
2337
2338        // A brand-new, independent Type 0 message on the SAME csid must
2339        // now parse as itself.
2340        let fresh = msg(12, 2, 8, 3, vec![0xBB; 50]);
2341        let fresh_bytes = writer.write(&fresh).unwrap();
2342        let out2 = assembler.push(&fresh_bytes).unwrap();
2343        assert_eq!(out2.len(), 1);
2344        assert_eq!(out2[0], fresh);
2345    }
2346
2347    /// RTMP-W2 (#1108): the precise corruption mechanism the finding
2348    /// describes — after `Abort`, a Type 3 chunk that the SENDER means as
2349    /// the start of a fresh message (inheriting the prior Type 0 header,
2350    /// same `message_length`) must NOT be read as a continuation of the
2351    /// aborted payload. Pre-fix, `in_progress` stayed `true` after Abort,
2352    /// so this Type 3 chunk's bytes were appended onto the old (partial,
2353    /// stale) payload instead of starting a clean new accumulation.
2354    #[test]
2355    fn abort_makes_next_type3_chunk_start_fresh_not_continue() {
2356        let aborted = msg(12, 1, 8, 3, vec![0xAA; 300]); // message_length=300, no extended ts
2357        let mut writer = ChunkWriter::new();
2358        let aborted_bytes = writer.write(&aborted).unwrap();
2359
2360        let split_at = 1 + TYPE0_LEN + 128;
2361        let mut assembler = ChunkAssembler::new();
2362        let out = assembler.push(&aborted_bytes[..split_at]).unwrap();
2363        assert!(out.is_empty());
2364
2365        assembler.abort(12);
2366
2367        // Bare Type 3 chunks (fmt=3, csid=12 -> (3<<6)|12 = 0xCC), a
2368        // DIFFERENT fill value, completing a fresh 300-byte message that
2369        // inherits message_length/type/stream_id from the last Type 0
2370        // header on this csid (§3.1.2) — 128 + 128 + 44 = 300.
2371        let mut rest = Vec::new();
2372        for chunk_len in [128, 128, 44] {
2373            rest.push(0xCC);
2374            rest.extend(core::iter::repeat_n(0xEEu8, chunk_len));
2375        }
2376        let completed = assembler.push(&rest).unwrap();
2377        assert_eq!(
2378            completed.len(),
2379            1,
2380            "the 300-byte message must complete exactly once"
2381        );
2382        assert_eq!(
2383            completed[0].payload,
2384            vec![0xEE; 300],
2385            "must be entirely the fresh fill value, with none of the aborted 0xAA bytes leaked in"
2386        );
2387    }
2388
2389    /// RTMP-W3 (#1108): a Type 1 chunk header arriving mid-message (the
2390    /// csid already has an in-progress, incomplete message) must be
2391    /// rejected, not silently reset the csid's state and discard the
2392    /// in-flight bytes.
2393    #[test]
2394    fn type1_header_mid_message_is_rejected() {
2395        let in_progress = msg(12, 1, 8, 3, vec![0xAA; 300]); // 3 chunks at default 128
2396        let mut writer = ChunkWriter::new();
2397        let bytes = writer.write(&in_progress).unwrap();
2398
2399        // Feed only the first chunk — csid 12 is left in-progress.
2400        let split_at = 1 + TYPE0_LEN + 128;
2401        let mut assembler = ChunkAssembler::new();
2402        let out = assembler.push(&bytes[..split_at]).unwrap();
2403        assert!(out.is_empty());
2404
2405        // A hand-built Type 1 chunk header on the SAME csid (fmt=1, csid=12
2406        // fits the 1-byte basic header form: (1 << 6) | 12 = 0x4C).
2407        let type1_chunk = [
2408            0x4C, // basic header: fmt=1, csid=12
2409            0x00, 0x00, 0x05, // timestamp_delta = 5
2410            0x00, 0x00, 0x32, // message_length = 50
2411            0x08, // message_type_id
2412        ];
2413        let err = assembler.push(&type1_chunk).unwrap_err();
2414        assert!(matches!(err, RtmpError::Malformed { .. }));
2415    }
2416
2417    #[test]
2418    fn assembler_partial_feed_byte_at_a_time_never_drops_or_duplicates() {
2419        let original = msg(11, 7, 9, 4, vec![0x33; 260]);
2420        let mut writer = ChunkWriter::new();
2421        let bytes = writer.write(&original).unwrap();
2422
2423        let mut assembler = ChunkAssembler::new();
2424        let mut collected = Vec::new();
2425        for b in &bytes {
2426            collected.extend(assembler.push(std::slice::from_ref(b)).unwrap());
2427        }
2428        assert_eq!(collected.len(), 1);
2429        assert_eq!(collected[0], original);
2430    }
2431
2432    #[test]
2433    fn assembler_type1_on_unseen_csid_is_malformed() {
2434        let mut assembler = ChunkAssembler::new();
2435        let mut input = Vec::new();
2436        write_serialized_ok(
2437            &mut input,
2438            &BasicHeader {
2439                fmt: Fmt::Type1,
2440                chunk_stream_id: 20,
2441            },
2442        );
2443        write_serialized_ok(
2444            &mut input,
2445            &MessageHeader::Type1 {
2446                timestamp_delta: 5,
2447                message_length: 3,
2448                message_type_id: 1,
2449            },
2450        );
2451        input.extend_from_slice(&[0, 0, 0]);
2452        assert!(matches!(
2453            assembler.push(&input),
2454            Err(RtmpError::Malformed { .. })
2455        ));
2456    }
2457
2458    #[test]
2459    fn assembler_type3_on_unseen_csid_is_malformed() {
2460        let mut assembler = ChunkAssembler::new();
2461        let mut input = Vec::new();
2462        write_serialized_ok(
2463            &mut input,
2464            &BasicHeader {
2465                fmt: Fmt::Type3,
2466                chunk_stream_id: 21,
2467            },
2468        );
2469        assert!(matches!(
2470            assembler.push(&input),
2471            Err(RtmpError::Malformed { .. })
2472        ));
2473    }
2474
2475    #[test]
2476    fn assembler_truncated_input_never_panics_across_many_split_points() {
2477        let original = msg(12, 99, 8, 5, vec![0x44; 400]);
2478        let mut writer = ChunkWriter::new();
2479        let bytes = writer.write(&original).unwrap();
2480
2481        // Feed every possible byte-prefix of the stream to a fresh
2482        // assembler each time: none may panic, and any that do parse fully
2483        // must reproduce the original message exactly.
2484        for split in 0..=bytes.len() {
2485            let mut assembler = ChunkAssembler::new();
2486            let first = assembler.push(&bytes[..split]);
2487            let Ok(first_msgs) = first else {
2488                continue;
2489            };
2490            let second = assembler.push(&bytes[split..]).unwrap();
2491            let mut all = first_msgs;
2492            all.extend(second);
2493            assert_eq!(all, vec![original.clone()]);
2494        }
2495    }
2496
2497    #[test]
2498    fn writer_default_chunk_size_matches_assembler_default() {
2499        assert_eq!(ChunkWriter::new().chunk_size, DEFAULT_CHUNK_SIZE);
2500        assert_eq!(ChunkAssembler::new().chunk_size, DEFAULT_CHUNK_SIZE);
2501    }
2502
2503    #[test]
2504    fn assembler_type3_immediately_after_type0_uses_type0_timestamp_as_implied_delta() {
2505        // §3.1.2: a Type 3 chunk that starts a NEW message immediately after
2506        // a Type 0 (nothing intervening) has an implied `timestamp_delta`
2507        // equal to that Type 0's own absolute timestamp — NOT 0. Every other
2508        // existing test intervenes a Type 1/2 before the fmt3, so this is
2509        // the only test that reaches this resolution path directly (bites a
2510        // mutation of `timestamp_delta: timestamp` -> `timestamp_delta: 0`
2511        // in the Type 0 arm).
2512        let mut assembler = ChunkAssembler::new();
2513        let csid = 40;
2514
2515        let mut input = Vec::new();
2516        write_serialized_ok(
2517            &mut input,
2518            &BasicHeader {
2519                fmt: Fmt::Type0,
2520                chunk_stream_id: csid,
2521            },
2522        );
2523        write_serialized_ok(
2524            &mut input,
2525            &MessageHeader::Type0 {
2526                timestamp: 1000,
2527                message_length: 5,
2528                message_type_id: 8,
2529                message_stream_id: 2,
2530            },
2531        );
2532        input.extend_from_slice(&[1, 2, 3, 4, 5]);
2533
2534        // Immediately (same csid, nothing between) a fmt3 chunk starting a
2535        // new message, inheriting message_length 5 from the Type 0 above.
2536        write_serialized_ok(
2537            &mut input,
2538            &BasicHeader {
2539                fmt: Fmt::Type3,
2540                chunk_stream_id: csid,
2541            },
2542        );
2543        input.extend_from_slice(&[9, 9, 9, 9, 9]);
2544
2545        let out = assembler.push(&input).unwrap();
2546        assert_eq!(out.len(), 2);
2547        assert_eq!(out[0].timestamp, 1000);
2548        assert_eq!(
2549            out[1].timestamp, 2000,
2550            "fmt3 immediately after fmt0 implies delta == the fmt0's own timestamp (1000), not 0: 1000 + 1000"
2551        );
2552    }
2553
2554    #[test]
2555    fn assembler_type2_on_unseen_csid_is_malformed() {
2556        let mut assembler = ChunkAssembler::new();
2557        let mut input = Vec::new();
2558        write_serialized_ok(
2559            &mut input,
2560            &BasicHeader {
2561                fmt: Fmt::Type2,
2562                chunk_stream_id: 22,
2563            },
2564        );
2565        write_serialized_ok(&mut input, &MessageHeader::Type2 { timestamp_delta: 5 });
2566        assert!(matches!(
2567            assembler.push(&input),
2568            Err(RtmpError::Malformed { .. })
2569        ));
2570    }
2571
2572    /// A peer that announces a chunk size below 128 (wire-legal — §5.4.1
2573    /// only recommends `SHOULD >= 128` for a *sender* choosing what to
2574    /// announce, the hard floor is `MUST >= 1`) must be parsed at exactly
2575    /// that size: this crate does not get to unilaterally decide the peer
2576    /// under-chunked and reinterpret its bytes at a larger boundary,
2577    /// because the peer already framed every subsequent chunk at the size
2578    /// it announced. Regression for a prior version of this fix that
2579    /// clamped an incoming announcement up to a 128-byte floor, which would
2580    /// have misparsed exactly this stream.
2581    #[test]
2582    fn assembler_honours_a_peer_announced_chunk_size_below_128() {
2583        let mut assembler = ChunkAssembler::new();
2584        assembler.set_chunk_size(64);
2585        assert_eq!(
2586            assembler.chunk_size, 64,
2587            "the announced size must not be clamped up"
2588        );
2589
2590        let payload: Vec<u8> = (0u32..150).map(|i| (i % 251) as u8).collect();
2591        let mut input = Vec::new();
2592        write_serialized_ok(
2593            &mut input,
2594            &BasicHeader {
2595                fmt: Fmt::Type0,
2596                chunk_stream_id: 12,
2597            },
2598        );
2599        write_serialized_ok(
2600            &mut input,
2601            &MessageHeader::Type0 {
2602                timestamp: 0,
2603                message_length: payload.len() as u32,
2604                message_type_id: 8,
2605                message_stream_id: 0,
2606            },
2607        );
2608        input.extend_from_slice(&payload[0..64]);
2609        write_serialized_ok(
2610            &mut input,
2611            &BasicHeader {
2612                fmt: Fmt::Type3,
2613                chunk_stream_id: 12,
2614            },
2615        );
2616        input.extend_from_slice(&payload[64..128]);
2617        write_serialized_ok(
2618            &mut input,
2619            &BasicHeader {
2620                fmt: Fmt::Type3,
2621                chunk_stream_id: 12,
2622            },
2623        );
2624        input.extend_from_slice(&payload[128..]);
2625
2626        let out = assembler.push(&input).unwrap();
2627        assert_eq!(out.len(), 1);
2628        assert_eq!(out[0].payload, payload);
2629    }
2630
2631    #[test]
2632    fn assembler_set_chunk_size_zero_is_floored_to_one() {
2633        let mut assembler = ChunkAssembler::new();
2634        assembler.set_chunk_size(0);
2635        assert_eq!(assembler.chunk_size, 1, "floored at 1, not stuck at 0");
2636
2637        // A message chunked consistently with the floored size (1 payload
2638        // byte per physical chunk) still assembles correctly — the floor
2639        // makes progress possible rather than wedging on every push.
2640        let csid = 41;
2641        let mut input = Vec::new();
2642        write_serialized_ok(
2643            &mut input,
2644            &BasicHeader {
2645                fmt: Fmt::Type0,
2646                chunk_stream_id: csid,
2647            },
2648        );
2649        write_serialized_ok(
2650            &mut input,
2651            &MessageHeader::Type0 {
2652                timestamp: 1,
2653                message_length: 3,
2654                message_type_id: 8,
2655                message_stream_id: 0,
2656            },
2657        );
2658        input.push(0xAA);
2659        write_serialized_ok(
2660            &mut input,
2661            &BasicHeader {
2662                fmt: Fmt::Type3,
2663                chunk_stream_id: csid,
2664            },
2665        );
2666        input.push(0xBB);
2667        write_serialized_ok(
2668            &mut input,
2669            &BasicHeader {
2670                fmt: Fmt::Type3,
2671                chunk_stream_id: csid,
2672            },
2673        );
2674        input.push(0xCC);
2675
2676        let out = assembler.push(&input).unwrap();
2677        assert_eq!(out.len(), 1);
2678        assert_eq!(out[0].payload, vec![0xAA, 0xBB, 0xCC]);
2679    }
2680
2681    // ── Remote-DoS caps (excessive-allocation guard) ────────────────────
2682
2683    /// A complete, well-formed one-chunk message on `csid`: a Type 0 header
2684    /// declaring `message_length == payload.len()`, immediately followed by
2685    /// `payload` (so it fits in the default 128-byte chunk size and
2686    /// completes in a single chunk).
2687    fn single_chunk(csid: u32, payload: &[u8]) -> Vec<u8> {
2688        let mut input = Vec::new();
2689        write_serialized_ok(
2690            &mut input,
2691            &BasicHeader {
2692                fmt: Fmt::Type0,
2693                chunk_stream_id: csid,
2694            },
2695        );
2696        write_serialized_ok(
2697            &mut input,
2698            &MessageHeader::Type0 {
2699                timestamp: 0,
2700                message_length: payload.len() as u32,
2701                message_type_id: 9,
2702                message_stream_id: 1,
2703            },
2704        );
2705        input.extend_from_slice(payload);
2706        input
2707    }
2708
2709    #[test]
2710    fn oversized_message_length_header_is_rejected_without_allocating() {
2711        // Mutation check: a Type 0 header claims a ~16 MiB message_length
2712        // (the max a 24-bit field can encode) but only ever supplies a
2713        // single default-chunk-size (128-byte) slice of payload after it —
2714        // exactly the shape of the excessive-allocation DoS (the peer never
2715        // has to send anywhere near the claimed length). Without the
2716        // MAX_MESSAGE_LEN cap this used to `Vec::with_capacity(message_length)`
2717        // (~16 MiB) right here and return `Ok(vec![])` (message merely
2718        // in-progress, no error) — this test would then fail, since it
2719        // asserts an `Err` instead.
2720        let mut assembler = ChunkAssembler::new();
2721        let mut input = Vec::new();
2722        write_serialized_ok(
2723            &mut input,
2724            &BasicHeader {
2725                fmt: Fmt::Type0,
2726                chunk_stream_id: 4,
2727            },
2728        );
2729        write_serialized_ok(
2730            &mut input,
2731            &MessageHeader::Type0 {
2732                timestamp: 0,
2733                message_length: 0x00FF_FFFF, // ~16 MiB: the largest 24-bit value.
2734                message_type_id: 9,
2735                message_stream_id: 1,
2736            },
2737        );
2738        input.extend(std::iter::repeat_n(0u8, DEFAULT_CHUNK_SIZE as usize));
2739
2740        let err = assembler.push(&input).expect_err(
2741            "a message_length beyond MAX_MESSAGE_LEN must be rejected before any \
2742             message_length-sized buffer is allocated",
2743        );
2744        assert!(matches!(err, RtmpError::Malformed { .. }));
2745    }
2746
2747    #[test]
2748    fn message_length_at_the_cap_is_accepted() {
2749        // Boundary check: exactly MAX_MESSAGE_LEN must still be accepted
2750        // (only values strictly above the cap are rejected).
2751        let mut assembler = ChunkAssembler::new();
2752        let mut input = Vec::new();
2753        write_serialized_ok(
2754            &mut input,
2755            &BasicHeader {
2756                fmt: Fmt::Type0,
2757                chunk_stream_id: 4,
2758            },
2759        );
2760        write_serialized_ok(
2761            &mut input,
2762            &MessageHeader::Type0 {
2763                timestamp: 0,
2764                message_length: MAX_MESSAGE_LEN,
2765                message_type_id: 9,
2766                message_stream_id: 1,
2767            },
2768        );
2769        input.extend(std::iter::repeat_n(0u8, DEFAULT_CHUNK_SIZE as usize));
2770
2771        // Not yet complete (only one chunk of a much larger message has
2772        // arrived) but must not be rejected outright.
2773        assert!(assembler.push(&input).is_ok());
2774    }
2775
2776    #[test]
2777    fn csid_flood_beyond_max_csids_is_rejected() {
2778        // Mutation check: fill the bound with MAX_CSIDS distinct,
2779        // well-formed chunk streams first (none of these may error — the
2780        // cap must not reject legitimate, moderate csid usage), then assert
2781        // that one more previously-unseen csid is rejected rather than
2782        // silently growing the per-csid state map without bound. Without
2783        // the MAX_CSIDS cap this last `push` would also return `Ok(_)`,
2784        // failing this test's `Err` assertion.
2785        let mut assembler = ChunkAssembler::new();
2786        for i in 0..MAX_CSIDS {
2787            let csid = BASIC_HEADER_1BYTE_MIN_CSID + i as u32;
2788            let out = assembler
2789                .push(&single_chunk(csid, &[0xAB]))
2790                .unwrap_or_else(|e| panic!("csid {csid} (#{i}, within the bound) rejected: {e}"));
2791            assert_eq!(out.len(), 1);
2792        }
2793
2794        let flood_csid = BASIC_HEADER_1BYTE_MIN_CSID + MAX_CSIDS as u32;
2795        let err = assembler
2796            .push(&single_chunk(flood_csid, &[0xCD]))
2797            .expect_err("a new csid beyond MAX_CSIDS must be rejected, not silently accepted");
2798        assert!(matches!(err, RtmpError::Malformed { .. }));
2799    }
2800
2801    #[test]
2802    fn csid_flood_cap_does_not_count_repeats_of_the_same_csid() {
2803        // A single csid reused for many messages must never itself trip the
2804        // MAX_CSIDS cap (the bound is on distinct concurrent csids, not on
2805        // total message count).
2806        let mut assembler = ChunkAssembler::new();
2807        for i in 0..(MAX_CSIDS * 4) {
2808            let out = assembler
2809                .push(&single_chunk(BASIC_HEADER_1BYTE_MIN_CSID, &[i as u8]))
2810                .expect("repeated use of a single already-known csid must never be rejected");
2811            assert_eq!(out.len(), 1);
2812        }
2813    }
2814
2815    #[test]
2816    fn set_chunk_size_is_capped_at_max_chunk_size() {
2817        let mut assembler = ChunkAssembler::new();
2818        assembler.set_chunk_size(u32::MAX);
2819        assert_eq!(assembler.chunk_size, MAX_CHUNK_SIZE);
2820
2821        let mut writer = ChunkWriter::new();
2822        writer.set_chunk_size(u32::MAX);
2823        assert_eq!(writer.chunk_size, MAX_CHUNK_SIZE);
2824    }
2825
2826    /// #1108/RTMP-W1: a fresh message opened on `csid` declaring
2827    /// `declared_len` (> one chunk) payload bytes, with exactly its first
2828    /// full chunk delivered so it commits and stays in progress. The full
2829    /// declared length is reserved against the aggregate budget when the
2830    /// header validates.
2831    fn open_partial_chunk(csid: u32, declared_len: u32) -> Vec<u8> {
2832        let sent_len = DEFAULT_CHUNK_SIZE as usize;
2833        assert!(sent_len < declared_len as usize);
2834        let mut input = Vec::new();
2835        write_serialized_ok(
2836            &mut input,
2837            &BasicHeader {
2838                fmt: Fmt::Type0,
2839                chunk_stream_id: csid,
2840            },
2841        );
2842        write_serialized_ok(
2843            &mut input,
2844            &MessageHeader::Type0 {
2845                timestamp: 0,
2846                message_length: declared_len,
2847                message_type_id: 9,
2848                message_stream_id: 1,
2849            },
2850        );
2851        input.extend_from_slice(&vec![0x5Au8; sent_len]);
2852        input
2853    }
2854
2855    #[test]
2856    fn aggregate_in_progress_bytes_across_csids_is_capped() {
2857        // Mutation check: MAX_MESSAGE_LEN bounds ONE message and MAX_CSIDS
2858        // bounds HOW MANY csids, but neither bounds the *product* — the
2859        // hoarder does not even have to send the bytes; N csids each with
2860        // a 24 KiB declaration cost one header each. Without the aggregate
2861        // budget every push below returns Ok and the assembler accepts
2862        // (MAX_MESSAGE_LEN x MAX_CSIDS) = 512 MiB of declarations per
2863        // connection.
2864        const BUDGET: usize = 64 * 1024;
2865        const DECL: u32 = 24 * 1024;
2866        let mut assembler = ChunkAssembler::new().with_max_in_progress_bytes(BUDGET);
2867        // First prove the normal-traffic path: complete messages cycling
2868        // every legal csid must never trip the budget (reservations are
2869        // released on delivery), and the csid space really is reachable.
2870        for i in 0..MAX_CSIDS as u32 {
2871            let out = assembler
2872                .push(&single_chunk(
2873                    BASIC_HEADER_1BYTE_MIN_CSID + i,
2874                    &[0x5Au8; 100],
2875                ))
2876                .expect("complete messages must never trip the budget");
2877            assert_eq!(out.len(), 1);
2878            assert_eq!(assembler.in_progress_bytes, 0);
2879        }
2880        // Now the hoarding shape: one permanently-partial 24 KiB
2881        // declaration per csid, each costing the hoarder only a 16-byte
2882        // payload fragment. 64 KiB / 24 KiB = 2 fit, so the budget must
2883        // trip on the third push.
2884        let mut hoarded = 0;
2885        for i in 0..MAX_CSIDS as u32 {
2886            let csid = BASIC_HEADER_1BYTE_MIN_CSID + i;
2887            match assembler.push(&open_partial_chunk(csid, DECL)) {
2888                Ok(msgs) => {
2889                    assert!(msgs.is_empty(), "a partial message must not complete");
2890                    assert_eq!(
2891                        assembler.in_progress_bytes,
2892                        (hoarded + 1) * DECL as usize,
2893                        "each accepted declaration must reserve its full length"
2894                    );
2895                    hoarded += 1;
2896                }
2897                Err(err) => {
2898                    assert!(
2899                        matches!(&err, RtmpError::Malformed { .. }),
2900                        "budget overrun must be Malformed (push #{hoarded}), got {err:?}"
2901                    );
2902                    break;
2903                }
2904            }
2905        }
2906        // 64 KiB / 24 KiB = 2 partials fit: the budget trips on the third
2907        // push — long before the MAX_CSIDS cap could (only 3 csids exist
2908        // on this connection, far below the 64-csid ceiling).
2909        assert_eq!(
2910            hoarded, 2,
2911            "the budget must be what stops the flood, not the csid cap"
2912        );
2913        assert!(
2914            assembler.in_progress_bytes <= BUDGET,
2915            "held bytes must never exceed the budget"
2916        );
2917    }
2918
2919    #[test]
2920    fn aggregate_in_progress_budget_trips_mid_message_and_recovers_on_completion() {
2921        const DECL: u32 = 200;
2922        let mut assembler = ChunkAssembler::new().with_max_in_progress_bytes(DECL as usize);
2923        assert!(
2924            assembler
2925                .push(&open_partial_chunk(3, DECL))
2926                .unwrap()
2927                .is_empty()
2928        );
2929        assert_eq!(assembler.in_progress_bytes, DECL as usize);
2930        // A second declaration would need 2x DECL: fatal, and the rejected
2931        // message leaves no reservation behind.
2932        assembler
2933            .push(&open_partial_chunk(4, DECL))
2934            .expect_err("a second declaration trips the cap");
2935        assert_eq!(assembler.in_progress_bytes, DECL as usize);
2936        // Recovery is checked on a fresh assembler (the error is fatal for
2937        // the connection): completing the message releases its reservation.
2938        let mut assembler = ChunkAssembler::new().with_max_in_progress_bytes(DECL as usize);
2939        assembler.push(&open_partial_chunk(3, DECL)).unwrap();
2940        let mut tail = Vec::new();
2941        write_serialized_ok(
2942            &mut tail,
2943            &BasicHeader {
2944                fmt: Fmt::Type3,
2945                chunk_stream_id: 3,
2946            },
2947        );
2948        tail.extend_from_slice(&vec![0x11u8; DECL as usize - DEFAULT_CHUNK_SIZE as usize]);
2949        let out = assembler.push(&tail).unwrap();
2950        assert_eq!(out.len(), 1);
2951        assert_eq!(out[0].payload.len(), DECL as usize);
2952        assert_eq!(assembler.in_progress_bytes, 0);
2953        assembler
2954            .push(&open_partial_chunk(5, DECL))
2955            .expect("freed budget must be reusable");
2956        assert_eq!(assembler.in_progress_bytes, DECL as usize);
2957    }
2958
2959    #[test]
2960    fn aggregate_in_progress_budget_unchanged_by_completed_messages() {
2961        // Many complete messages through a tight budget must never trip
2962        // the cap (payload leaves the budget the moment it is delivered),
2963        // proving the cap bounds *stuck* bytes, not throughput.
2964        let mut assembler = ChunkAssembler::new().with_max_in_progress_bytes(16);
2965        for i in 0..50u32 {
2966            let out = assembler
2967                .push(&single_chunk(BASIC_HEADER_1BYTE_MIN_CSID, &[i as u8; 15]))
2968                .expect("completed messages must not count toward the budget");
2969            assert_eq!(out.len(), 1);
2970        }
2971        assert_eq!(assembler.in_progress_bytes, 0);
2972    }
2973
2974    /// r08-RTMP-C1 regression: reassembling a large message split into many
2975    /// small physical chunks (here, chunk size 1 — the wire's own hard
2976    /// floor, `MUST >= 1`, and the shape the original finding used) must do
2977    /// O(`message_length`) total payload-copying work, not
2978    /// O(`message_length`^2 / `chunk_size`). Measured directly via the
2979    /// `#[cfg(test)]` byte-copy hook rather than a wall-clock bound (a
2980    /// wall-clock bound is inherently flaky under load; this one instead
2981    /// asserts the exact quantity the fix changes).
2982    ///
2983    /// Pre-fix, at `MAX_MESSAGE_LEN` (8 MiB) split into 1-byte chunks
2984    /// (~8.4 million of them), the old "clone the whole accumulated payload
2985    /// on every continuation chunk" code would have copied on the order of
2986    /// `sum(1, 2, ..., 8 MiB) ~= 8MiB^2 / 2` bytes — many terabytes, not
2987    /// safely runnable here (would allocate far beyond a reasonable test
2988    /// budget). A *smaller*-scale version of this same shape was run
2989    /// directly against the pre-fix code (64 KiB / 256 KiB at chunk size 1)
2990    /// and confirmed the quadratic blowup (wall-clock time scaled ~11x for
2991    /// a 4x size increase) before this fix landed; see brief/PR notes.
2992    #[test]
2993    fn reassembling_an_8mib_message_at_chunk_size_one_is_linear_not_quadratic() {
2994        let payload: Vec<u8> = (0..MAX_MESSAGE_LEN).map(|i| (i % 251) as u8).collect();
2995        let original = msg(10, 0, 9, 1, payload.clone());
2996
2997        let mut writer = ChunkWriter::new();
2998        writer.set_chunk_size(1);
2999        let bytes = writer.write(&original).unwrap();
3000
3001        let mut assembler = ChunkAssembler::new().with_chunk_size(1);
3002
3003        reset_payload_bytes_copied_for_test();
3004        let out = assembler.push(&bytes).unwrap();
3005        let copied = payload_bytes_copied_for_test();
3006
3007        assert_eq!(out.len(), 1);
3008        assert_eq!(out[0].payload, payload);
3009
3010        // Generous (4x message length) but already far below what the old
3011        // quadratic code would have copied (~4 million x message length at
3012        // this size/chunk_size) — this bound is only reachable by O(n)
3013        // reassembly.
3014        assert!(
3015            copied <= payload.len() * 4,
3016            "copied {copied} bytes reassembling a {}-byte message at chunk \
3017             size 1 — quadratic behaviour crept back in",
3018            payload.len()
3019        );
3020    }
3021}
3022
3023#[cfg(test)]
3024mod invalid_csid_tests {
3025    use super::*;
3026
3027    fn msg(csid: u32) -> Message {
3028        Message {
3029            chunk_stream_id: csid,
3030            timestamp: 0,
3031            message_type_id: 20,
3032            message_stream_id: 1,
3033            payload: vec![1, 2, 3],
3034        }
3035    }
3036
3037    #[test]
3038    fn write_rejects_out_of_range_chunk_stream_id_without_panicking() {
3039        let mut w = ChunkWriter::new();
3040        for bad in [0u32, 1, 65600, u32::MAX] {
3041            match w.write(&msg(bad)) {
3042                Err(RtmpError::InvalidChunkStreamId { chunk_stream_id }) => {
3043                    assert_eq!(chunk_stream_id, bad);
3044                }
3045                other => panic!("csid {bad}: expected InvalidChunkStreamId, got {other:?}"),
3046            }
3047        }
3048        for ok in [2u32, 63, 64, 319, 320, 65599] {
3049            assert!(w.write(&msg(ok)).is_ok(), "csid {ok} must be accepted");
3050        }
3051    }
3052}