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