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