Skip to main content

ChunkAssembler

Struct ChunkAssembler 

Source
pub struct ChunkAssembler { /* private fields */ }
Expand description

Stateful inbound chunk reassembler (§5.3): feed inbound bytes, get back each complete Message as soon as its last chunk arrives.

Maintains per-chunk_stream_id state, so multiple chunk streams may be interleaved on the same connection (as the wire format requires) and are each reassembled independently.

Implementations§

Source§

impl ChunkAssembler

Source

pub fn new(limits: ChunkLimits) -> Self

New assembler, chunk size at the §5.3 default (128 bytes), held to the caller’s limits.

Source

pub fn retained_payload_bytes(&self) -> usize

Bytes held by the payload buffers of in-progress messages, counted by capacity. An aborted, interrupted or discarded message gives its allocation back, so this tracks what a peer can make the connection keep and stays within what ChunkLimits admits (the receive buffer has its own backstop in Self::next_message).

Source

pub fn take_damage(&mut self) -> Vec<Damage>

Reports for the content skipped since the last call: a message an interrupting header or an Abort discarded, a message above the length ceiling consumed without being buffered, and a message the caller’s in-progress budget refused. Each is a broadcast_core::damage::Damage for the session to publish through its event channel.

Source

pub fn with_max_in_progress_bytes(self, max_in_progress_bytes: usize) -> Self

Set the ceiling on total payload bytes buffered across all in-progress messages (#1108/RTMP-W1).

Source

pub fn with_chunk_size(self, chunk_size: ChunkSize) -> Self

Builder form of Self::set_chunk_size.

Source

pub fn set_chunk_size(&mut self, chunk_size: ChunkSize)

Update the chunk size in effect for subsequent chunks (called on receipt of a Set Chunk Size protocol control message, §5.4.1). Per private/specs-verified/rtmp/rtmp-runtime/rtmp.md §3’s transcription of §5.4.1 (“Default max chunk size is 128; SHOULD be ≥ 128, MUST be ≥ 1”), 128 is only a SHOULD for a sender choosing what to announce — a peer that announces (and then frames its own chunks at) a smaller value is still wire-legal, and this side must parse at whatever size the peer actually announced or every later chunk boundary is misparsed. So any validated ChunkSize is adopted verbatim; it is never clamped to a different size, since parsing at any size but the announced one mis-frames the stream silently.

Source

pub fn adopt_peer_chunk_size( &mut self, chunk_size: ChunkSize, ) -> Result<(), RtmpError>

Adopt the chunk size the peer announced with Set Chunk Size (§5.4.1), unless it is above the caller’s ChunkLimits::max_chunk_size.

§Errors

RtmpError::ChunkSizeOutOfRange for an announcement above the ceiling; the size in effect is left unchanged.

Source

pub fn abort(&mut self, csid: ChunkStreamId)

Discard any partially-received message on csid (§5.4.2 Abort Message). A no-op if csid has no in-progress message.

#1108/RTMP-W2: without this, Abort was accepted and silently ignored, so in_progress stayed true and the next Type 3 chunk that actually starts a new message on that csid was instead appended to the aborted payload as a continuation — message_length bytes later, a corrupted merged message came out.

The discarded message is reported through Self::take_damage: the sender told the session to drop it, so the report is informational, but a viewer never sees that content and a host that counts losses must be able to count this one.

Source

pub fn push(&mut self, input: &[u8]) -> Result<Vec<Message>, RtmpError>

Feed inbound bytes; returns each complete Message decoded from the buffer (in arrival order), leaving any trailing partial chunk or partial message buffered internally for the next call.

Callers that need to react to a message’s side effects (e.g. a Set Chunk Size protocol control message, §5.4.1) before parsing the bytes that follow it in the same input — because the sender may switch to the new chunk size for its very next chunk — should use the crate-internal incremental feed/next_message pair instead, dispatching each message immediately. push collects every message from input under a single, unchanging chunk_size, which misparses a buffer that itself contains a Set Chunk Size followed by chunks already framed at the new size (see ServerSession, which uses the incremental form for exactly this reason).

§Errors

RtmpError::Malformed on structurally invalid input (e.g. a Type 1/2/3 chunk on a csid that has never seen a Type 0). Never errors merely because the input ends mid-chunk — that is buffered, not an error.

Source

pub fn feed(&mut self, input: &[u8])

Buffer inbound bytes without parsing them yet. Pair with repeated calls to next_message to parse and dispatch one message at a time (see push’s docs for why this matters for Set Chunk Size).

Nothing is parsed here, so this never fails: an incomplete chunk or message stays buffered until more bytes arrive.

Source

pub fn pending_len(&self) -> usize

Bytes feeded that next_message has not yet consumed. A caller that feeds one input slice at a time pairs this with swap_pending to recover how much of that slice has been parsed.

Source

pub fn swap_pending(&mut self, now: &[u8]) -> Vec<u8> ⓘ

Replace the bytes feeded so far with now, returning what was there: the bytes a caller fed that are still unparsed. A caller that has the original input still in hand (the common case: one on_bytes call) passes what remains after its own offset and gets back exactly the bytes it fed that never formed a chunk — no re-derivation from byte counts, and nothing parsed at a stale chunk size.

Source

pub fn next_message(&mut self) -> Result<Option<Message>, RtmpError>

Parse and return the next complete Message out of the previously-feed bytes, or Ok(None) if what remains buffered isn’t (yet) a complete message. Internally keeps parsing individual chunks — which may belong to other interleaved csids, or be a non-final chunk of the same in-progress message — until either a full message is assembled or the buffered bytes run out.

Each chunk’s payload bytes are appended in place to that csid’s own persistent CsidState::payload buffer (never cloned), and the consumed prefix of pending is only physically dropped once, when this call returns (see Self::compact) — not once per chunk. A message split across many small chunks (e.g. an 8 MiB message at a 1-byte chunk size) used to cost O(message_length^2 / chunk_size) — clone the whole accumulated payload on every continuation chunk, and shift the rest of pending down on every chunk’s drain — and now costs O(message_length).

Because each call stops at one message, the caller can apply that message’s effect on the chunk stream (a Set Chunk Size, §5.4.1) with set_chunk_size before the next call parses the bytes that follow it. When the buffered bytes and the caller’s input overlap (one input buffer carries the control message and the chunks framed after it), swap_pending hands back what was fed but never parsed, so the caller can re-feed exactly those bytes and nothing is parsed twice or at the old size:

use rtmp_runtime::chunk::{ChunkAssembler, ChunkLimits, ChunkWriter, Message};
use rtmp_runtime::ids::{ChunkStreamId, MessageStreamId, Timestamp};
use rtmp_runtime::message::{ChunkSize, MessageTypeId, ProtocolControl};

let mut writer = ChunkWriter::new();
let mut wire = Vec::new();
let control = ProtocolControl::SetChunkSize(ChunkSize::new(4096).unwrap()).to_message();
wire.extend_from_slice(&writer.write(&control)?);
writer.set_chunk_size(ChunkSize::new(4096)?);
let media = Message {
    chunk_stream_id: ChunkStreamId::new(4),
    timestamp: Timestamp::from_millis(0),
    message_type_id: MessageTypeId::Audio,
    message_stream_id: MessageStreamId::new(1),
    payload: vec![0u8; 5000],
};
wire.extend_from_slice(&writer.write(&media)?);

let mut assembler = ChunkAssembler::new(ChunkLimits {
    max_chunk_size: 1 << 20,
    max_message_len: 1 << 20,
    max_csids: 64,
    max_in_progress_bytes: 1 << 22,
});
let mut rest: &[u8] = &wire;
let mut sizes = Vec::new();
assembler.feed(&wire);
loop {
    let message = match assembler.next_message()? {
        Some(message) => message,
        None => break,
    };
    if message.message_type_id == MessageTypeId::SetChunkSize {
        if let Some(ProtocolControl::SetChunkSize(size)) =
            ProtocolControl::from_message(&message)?
        {
            let boundary = rest.len() - assembler.pending_len();
            assembler.set_chunk_size(size);
            rest = rest.get(boundary..).unwrap_or_default();
            assembler.swap_pending(rest);
        }
        continue;
    }
    sizes.push(message.payload.len());
}
§Errors

Same as push.

Source

pub fn compact(&mut self)

Physically drop the front self.cursor bytes of pending (the prefix already consumed by chunks parsed earlier in this call) and reset the cursor to 0. Called once per Self::next_message return, never per chunk inside its loop: a Vec::drain from the front is O(remaining length), so doing it once per chunk while a single message was still being reassembled out of many small chunks was, independently of the payload-clone cost, itself enough to make reassembly quadratic in the chunk count.

A caller that switches chunk size between messages with set_chunk_size calls this once first, so the bytes still buffered at the old size are re-fed and parsed at the new one.

Trait Implementations§

Source§

impl Debug for ChunkAssembler

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl Forget for ChunkAssembler

§

impl Freeze for ChunkAssembler
where *const LeafNode<ChunkStreamId, CsidState> is !null: Freeze, PhantomData<(Owned, LeafOrInternal)>: Freeze, PhantomData<Box<(ChunkStreamId, CsidState)>>: Freeze, *const u8 is !null: Freeze, PhantomData<u8>: Freeze, PhantomData<Damage>: Freeze,

§

impl Move for ChunkAssembler

§

impl RefUnwindSafe for ChunkAssembler

§

impl Send for ChunkAssembler
where NodeRef<Owned, ChunkStreamId, CsidState, LeafOrInternal>: Send, BoxRaw<(ChunkStreamId, CsidState)>: Send, RawVecInner: Send, NonZero<u32>: Send, &'static str: Send,

§

impl Sync for ChunkAssembler
where NodeRef<Owned, ChunkStreamId, CsidState, LeafOrInternal>: Sync, BoxRaw<(ChunkStreamId, CsidState)>: Sync, RawVecInner: Sync, NonZero<u32>: Sync,

§

impl Unpin for ChunkAssembler
where *const LeafNode<ChunkStreamId, CsidState> is !null: Unpin, Box<(ChunkStreamId, CsidState)>: Unpin, *const u8 is !null: Unpin, NonZero<u32>: Unpin, &'static str: Unpin,

§

impl UnsafeUnpin for ChunkAssembler
where *const LeafNode<ChunkStreamId, CsidState> is !null: UnsafeUnpin, PhantomData<(Owned, LeafOrInternal)>: UnsafeUnpin, PhantomData<Box<(ChunkStreamId, CsidState)>>: UnsafeUnpin, *const u8 is !null: UnsafeUnpin, PhantomData<u8>: UnsafeUnpin, PhantomData<Damage>: UnsafeUnpin,

§

impl UnwindSafe for ChunkAssembler
where BTreeMap<ChunkStreamId, CsidState>: UnwindSafe, RawVecInner: UnwindSafe, NonZero<u32>: UnwindSafe, &'static str: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.