Skip to main content

rtmp_runtime/
chunk.rs

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