Skip to main content

rtmp_runtime/
server.rs

1//! RTMP ingest server session state machine — `connect` → `createStream` →
2//! `publish` (Adobe RTMP 1.0 §7.2, `NetConnection`/`NetStream` commands).
3//!
4//! See `private/specs-verified/rtmp/rtmp-runtime/rtmp.md` §2 (Handshake), §4 (Protocol Control
5//! Messages), §5.3 (User Control Messages), §7 (RTMP Message Types incl.
6//! Command Message), and `private/specs-verified/mpeg/transmux/codec/flv.md`
7//! (FLV header/tag layout, Adobe FLV v10.1 Annex E) for the wire layouts this
8//! module ties together.
9//!
10//! [`ServerSession`] is the sans-IO **publish ingest** engine: feed it
11//! inbound bytes via [`ServerSession::handle_data`], get back outbound bytes
12//! to write plus a list of typed [`ServerEvent`]s. It drives, in order:
13//!
14//! 1. the [`crate::handshake::Handshake`] sub-FSM (C0/C1/C2 → S0/S1/S2),
15//! 2. the [`crate::chunk::ChunkAssembler`]/[`crate::chunk::ChunkWriter`]
16//!    chunk-stream (de)assembly,
17//! 3. [`crate::message::ProtocolControl`]/[`crate::message::UserControl`]
18//!    interpretation and replies,
19//! 4. [`crate::amf0::Command`] routing for the `connect`/`createStream`/
20//!    `publish` command sequence, and
21//! 5. FLV tag emission for Audio(8)/Video(9)/Data-AMF0(18) messages received
22//!    while publishing.
23//!
24//! # Session state
25//!
26//! Internally tracked as `Init → Connected(app) → Publishing(stream_key) →
27//! Closed`. The handshake phase itself is not duplicated in this enum — it
28//! is tracked by `self.handshake.is_done()` (querying
29//! [`crate::handshake::Handshake`] directly), so there is exactly one source
30//! of truth for "has the handshake finished".
31//!
32//! # Ack accounting
33//!
34//! §5.4.3's Acknowledgement sequence number is a plain **modular `u32`**
35//! (truncating the running total byte count) — the spec is silent on
36//! wraparound behaviour for this field, so this is a documented
37//! implementation choice, not a spec requirement.
38//!
39//! Two further implementation choices, not spec requirements:
40//!
41//! - At most **one** Acknowledgement is emitted per
42//!   [`handle_data`](ServerSession::handle_data) call, even if the input
43//!   buffer crossed `window_ack_size` multiple times over (e.g. a single
44//!   call carrying several times the window in bytes). The threshold check
45//!   runs once, after all messages in that call have been dispatched, not
46//!   once per `window_ack_size`-sized increment.
47//! - Handshake bytes are excluded from the Ack byte count: the running
48//!   total only accumulates post-handshake (chunk-stream) bytes — bytes
49//!   consumed while still inside the C0/C1/C2 ↔ S0/S1/S2 handshake exchange
50//!   never reach the counter.
51//!
52//! # Damage reports
53//!
54//! This session never skips content silently. It publishes a
55//! `broadcast_core::damage::Damage` as [`ServerEvent::Damage`] for:
56//!
57//! - a message header that interrupts an in-progress message on the same
58//!   chunk stream, and an `Abort` that discards one (`MediaUnitDropped`);
59//! - a message whose declared length exceeds what this session will buffer,
60//!   consumed without ever being held (`LimitReached`);
61//! - media on a stream id `publish` was not accepted on, or before `publish`
62//!   (`MediaUnitDropped`, informational);
63//! - a message type, user control event or command name this engine does not
64//!   decode, and an AMF0 ECMA-Array whose declared count disagrees with its
65//!   contents (`MetadataUninterpreted`);
66//! - an aggregate sub-message whose framing does not hold, after the good ones
67//!   before it were delivered (`MediaUnitDropped`).
68//!
69//! What stays an error, and why: a chunk stream that cannot be framed at all
70//! (there is no later message to find), a chunk size outside the protocol's
71//! range, a handshake this engine does not speak, and the unparsed-input
72//! backstop. The caller's `RtmpServerConfig::damage_policy` decides whether a
73//! report also ends the session (`RtmpError::Damage`).
74//!
75//! # Reply csid convention
76//!
77//! Protocol control and User Control messages MUST/SHOULD use chunk stream
78//! id 2 ([`crate::message::CONTROL_CHUNK_STREAM_ID`]) — enforced already by
79//! [`crate::message::ProtocolControl::to_message`] and
80//! [`crate::message::UserControl::to_message`]. This module's own outbound
81//! AMF0 command replies (`_result`/`onStatus`) use `COMMAND_CHUNK_STREAM_ID`
82//! (3) — a real-world convention (distinct from the reserved control csid),
83//! not a spec-mandated value: §5.3 leaves csid choice to the sender for
84//! anything other than protocol control/user control traffic.
85
86use broadcast_core::Parse;
87use broadcast_core::error::BufferTooShort;
88
89use crate::RtmpError;
90use crate::amf0::{Amf0Limits, Amf0Value, Command};
91use crate::chunk::{ChunkAssembler, ChunkLimits, ChunkWriter, Message};
92use crate::flv::{FlvTagWriter, unpack_aggregate};
93use crate::handshake::Handshake;
94use crate::ids::{ChunkStreamId, MessageStreamId, SequenceNumber, Timestamp};
95use crate::message::{ChunkSize, LimitType, MessageTypeId, ProtocolControl, UserControl};
96use alloc::boxed::Box;
97use alloc::format;
98use alloc::string::{String, ToString};
99use alloc::vec;
100use alloc::vec::Vec;
101
102type Result<T> = core::result::Result<T, RtmpError>;
103
104// ── Named constants (no magic numbers) ──────────────────────────────────
105
106/// The first message stream id [`ServerSession`] allocates on `createStream`
107/// (§7.2.2). Message stream id 0 is reserved for the `NetConnection`
108/// (control) channel, so allocation starts at 1.
109const FIRST_STREAM_ID: u32 = 1;
110
111/// Chunk stream id this session uses for its own outbound AMF0 command
112/// replies (`_result`/`onStatus`) — see the module doc's "Reply csid
113/// convention" section.
114const COMMAND_CHUNK_STREAM_ID: u32 = 3;
115
116/// `fmsVer` value advertised in the `connect` `_result` Properties object
117/// (§7.2.1). Not spec-mandated — a conventional placeholder value (the
118/// pattern used by reference server implementations), since real clients
119/// only branch on `NetConnection.Connect.Success`/`level`/`code`, not this
120/// string.
121const FMS_VERSION: &str = "FMS/3,0,1,123";
122/// `capabilities` value advertised in the `connect` `_result` Properties
123/// object (§7.2.1). Not spec-mandated (see [`FMS_VERSION`]).
124const CAPABILITIES: f64 = 31.0;
125
126/// The bounds a [`ServerSession`] holds its peer to. The crate supplies none of them.
127#[derive(Debug, Clone, Copy, PartialEq, Eq)]
128#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
129pub struct ServerLimits {
130    /// The chunk reassembly bounds (message length, chunk streams, total in-progress bytes,
131    /// announced chunk size; #1108/RTMP-W1).
132    pub chunk: ChunkLimits,
133    /// The AMF0 depth and value-count bounds command parsing is held to.
134    pub amf0: Amf0Limits,
135    /// Largest inbound Command Message body parsed. A command body is decoded into a full AMF0
136    /// value tree before any state-machine check (including the `connect` stream-key gate), so
137    /// without this bound one reassembled message of one-byte nulls or three-byte empty-key
138    /// pairs expands into millions of allocations. A longer body is rejected with
139    /// [`RtmpError::CommandTooLong`] before any AMF0 parsing.
140    pub max_command_len: usize,
141    /// Number of `publish` attempts with a mismatched stream key tolerated on one connection
142    /// before the session is closed: `expected_stream_key` is the only secret in the ingest
143    /// path, and one TCP connection can otherwise retry `publish` with a new guess indefinitely.
144    pub max_failed_publish_attempts: u32,
145}
146
147/// Configuration for a [`ServerSession`].
148///
149/// `#[non_exhaustive]`: fields may grow (e.g. a future `app` gate alongside
150/// `expected_stream_key`). Construct via [`RtmpServerConfig::new`] plus the
151/// `with_*` builder methods rather than a struct literal.
152#[non_exhaustive]
153#[derive(Clone)]
154#[cfg_attr(feature = "serde", derive(serde::Serialize))]
155pub struct RtmpServerConfig {
156    /// Outbound chunk size advertised (and adopted) on `connect` (§5.4.1).
157    pub chunk_size: u32,
158    /// Window Acknowledgement Size advertised on `connect` (§5.4.4); also
159    /// the initial threshold for this session's own inbound Ack accounting
160    /// (§5.4.3), until a peer `WindowAckSize`/`SetPeerBandwidth` updates it.
161    pub window_ack_size: u32,
162    /// Set Peer Bandwidth value advertised on `connect` (§5.4.5).
163    pub peer_bandwidth: u32,
164    /// If set, `publish`'s stream key (publishing name) must match this
165    /// value exactly or the publish is rejected: `onStatus`
166    /// `NetStream.Publish.BadName`, and no `Publish`/`Media` events are
167    /// emitted for that connection.
168    ///
169    /// **`None` (the default) admits any publisher.** A listener reachable
170    /// from an untrusted network must set a key (or authenticate the
171    /// publisher some other way before handing bytes to this session).
172    pub expected_stream_key: Option<String>,
173    /// The bounds this session holds its peer to.
174    pub limits: ServerLimits,
175    /// What each [`ServerEvent::Damage`] report means: `Report` (the default
176    /// for everything) publishes it and keeps reading; `Fail` ends the
177    /// session with [`RtmpError::Damage`] carrying the same report.
178    pub damage_policy: broadcast_core::damage::DamagePolicy,
179}
180
181/// Manual `Debug`: the expected stream key is the ingest secret and never
182/// renders (issue #1142).
183impl core::fmt::Debug for RtmpServerConfig {
184    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
185        f.debug_struct("RtmpServerConfig")
186            .field("chunk_size", &self.chunk_size)
187            .field("window_ack_size", &self.window_ack_size)
188            .field("peer_bandwidth", &self.peer_bandwidth)
189            .field(
190                "expected_stream_key",
191                &self.expected_stream_key.as_ref().map(|_| "<redacted>"),
192            )
193            .field("limits", &self.limits)
194            .field("damage_policy", &self.damage_policy)
195            .finish()
196    }
197}
198
199impl RtmpServerConfig {
200    /// A configuration advertising `chunk_size`, `window_ack_size` and `peer_bandwidth` on
201    /// `connect`, admitting any publisher and holding its peer to `limits`.
202    #[must_use]
203    pub fn new(
204        limits: ServerLimits,
205        chunk_size: u32,
206        window_ack_size: u32,
207        peer_bandwidth: u32,
208    ) -> Self {
209        Self {
210            chunk_size,
211            window_ack_size,
212            peer_bandwidth,
213            expected_stream_key: None,
214            limits,
215            damage_policy: broadcast_core::damage::DamagePolicy::default(),
216        }
217    }
218
219    /// Set [`RtmpServerConfig::expected_stream_key`]. `#[non_exhaustive]` forbids
220    /// struct-literal construction of this type from outside the crate, so
221    /// this (plus the other `with_*` builders below) is how a caller
222    /// customises a field starting from [`RtmpServerConfig::new`].
223    #[must_use]
224    pub fn with_expected_stream_key(mut self, expected_stream_key: Option<String>) -> Self {
225        self.expected_stream_key = expected_stream_key;
226        self
227    }
228
229    /// Set [`RtmpServerConfig::chunk_size`].
230    #[must_use]
231    pub fn with_chunk_size(mut self, chunk_size: u32) -> Self {
232        self.chunk_size = chunk_size;
233        self
234    }
235
236    /// Set [`RtmpServerConfig::limits`].
237    #[must_use]
238    pub fn with_limits(mut self, limits: ServerLimits) -> Self {
239        self.limits = limits;
240        self
241    }
242
243    /// Set [`RtmpServerConfig::damage_policy`].
244    #[must_use]
245    pub fn with_damage_policy(
246        mut self,
247        damage_policy: broadcast_core::damage::DamagePolicy,
248    ) -> Self {
249        self.damage_policy = damage_policy;
250        self
251    }
252}
253
254/// Typed events [`ServerSession::handle_data`] surfaces to the caller.
255///
256/// Serde-serializable only: a [`ServerEvent::Damage`] carries a
257/// [`broadcast_core::damage::Damage`], whose typed cause wraps the workspace's
258/// shared error kinds and is therefore write-only, so the enum cannot be
259/// reconstructed from JSON.
260#[non_exhaustive]
261#[derive(Clone, PartialEq)]
262#[cfg_attr(feature = "serde", derive(serde::Serialize))]
263pub enum ServerEvent {
264    /// `connect` completed: the publisher's requested `app` name (§7.2.1).
265    Connected {
266        /// The `app` property of the `connect` command object.
267        app: String,
268    },
269    /// `publish` was accepted (stream key matched, or no key was
270    /// configured): the session is now `Publishing`.
271    Publish {
272        /// The `app` name captured at `connect`.
273        app: String,
274        /// The publishing name (stream key) passed to `publish` (§7.2.2.6).
275        stream_key: String,
276        /// The message stream id `publish` was invoked on (allocated by the
277        /// preceding `createStream`).
278        stream_id: u32,
279    },
280    /// One FLV tag run is ready: the payload of a single Audio(8)/Video(9)/
281    /// Data-AMF0(18) message, converted to an FLV tag (+ `PreviousTagSize`).
282    /// The very first `Media` event of a session is prefixed with the FLV
283    /// file header, so concatenating every `Media.flv` in arrival order
284    /// yields a valid FLV byte stream feedable to `transmux::FlvDemux`.
285    Media {
286        /// FLV bytes for this tag (file header prefix on the first event
287        /// only, tag header + payload + `PreviousTagSize` every time).
288        flv: Vec<u8>,
289    },
290    /// The publisher ended the stream (`deleteStream`/`FCUnpublish`).
291    Eof,
292    /// A message type this engine doesn't decode was received and its
293    /// payload was dropped (#1108/RTMP-W6) — Data-AMF3(15), Command-AMF3(17,
294    /// now decoded as AMF0 after its format byte), or Shared Object(16/19).
295    /// Pre-fix, these were silently ignored with no signal at all.
296    /// Aggregate(22) no longer surfaces here: it is unpacked into its
297    /// contained sub-messages (#1108 remainder), and a malformed aggregate
298    /// is an error instead.
299    Unsupported {
300        /// The message type id that was dropped (§6/§7.1).
301        message_type_id: MessageTypeId,
302    },
303    /// Content this session skipped or repaired — the one
304    /// [`broadcast_core::damage::Damage`] report, in wire order with the
305    /// events around it. [`ServerEvent::Unsupported`] names the message type
306    /// of the same drop; this carries the severity and is what the caller's
307    /// [`RtmpServerConfig::damage_policy`] decides on.
308    ///
309    /// Boxed because an unboxed report would enlarge every event and every
310    /// `Result` in the crate.
311    Damage(Box<broadcast_core::damage::Damage>),
312}
313
314/// Manual `Debug`: `Publish` carries the publisher's stream key (the ingest
315/// secret) and `Media` carries whole FLV tag runs; neither renders verbatim
316/// (issue #1142).
317impl core::fmt::Debug for ServerEvent {
318    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
319        match self {
320            ServerEvent::Connected { app } => {
321                f.debug_struct("Connected").field("app", app).finish()
322            }
323            ServerEvent::Publish { app, stream_id, .. } => f
324                .debug_struct("Publish")
325                .field("app", app)
326                .field("stream_key", &"<redacted>")
327                .field("stream_id", stream_id)
328                .finish(),
329            ServerEvent::Media { flv } => f
330                .debug_struct("Media")
331                .field("flv_len", &flv.len())
332                .finish(),
333            ServerEvent::Eof => f.write_str("Eof"),
334            ServerEvent::Unsupported { message_type_id } => f
335                .debug_struct("Unsupported")
336                .field("message_type_id", message_type_id)
337                .finish(),
338            ServerEvent::Damage(damage) => f.debug_tuple("Damage").field(damage).finish(),
339        }
340    }
341}
342
343/// Session state (`connect`/`publish` progress only — the handshake phase
344/// is tracked separately by `self.handshake.is_done()`, see the module doc).
345#[derive(Debug, Clone, Copy, PartialEq, Eq)]
346enum State {
347    /// Handshake done (or not yet started); `connect` not yet received.
348    Init,
349    /// `connect` succeeded; `app` captured. `createStream`/`publish` may
350    /// now proceed.
351    Connected,
352    /// `publish` succeeded; Audio/Video/Data-AMF0 messages now produce
353    /// [`ServerEvent::Media`].
354    Publishing,
355    /// `deleteStream`/`FCUnpublish` was received; the session is done.
356    Closed,
357}
358
359/// The sans-IO RTMP **publish ingest** server session (see the module doc).
360///
361/// No sockets or clocks live here: drive it entirely by feeding inbound
362/// bytes to [`handle_data`](Self::handle_data).
363#[derive(Debug)]
364pub struct ServerSession {
365    config: RtmpServerConfig,
366    handshake: Handshake,
367    /// Raw bytes accumulated across calls while the handshake is still in
368    /// progress (the handshake sub-FSM does not buffer partial input
369    /// itself — see [`crate::handshake::Handshake::read`]).
370    handshake_buf: Vec<u8>,
371    assembler: ChunkAssembler,
372    writer: ChunkWriter,
373    state: State,
374    app: Option<String>,
375    next_stream_id: u32,
376    /// The message stream id allocated by the most recent successful
377    /// `createStream` (§7.2.2), or `None` if none has succeeded yet.
378    /// `publish` requires this to be `Some` (in addition to `state ==
379    /// Connected`) — a stream must actually have been created first.
380    created_stream_id: Option<u32>,
381    /// Threshold (in bytes received) at which an Acknowledgement is due
382    /// (§5.4.3/§5.4.4). Starts at `config.window_ack_size`; updated if the
383    /// peer sends its own `WindowAckSize` (#1108/RTMP-W7: NOT
384    /// `SetPeerBandwidth`, which limits the peer's own output bandwidth
385    /// and has nothing to do with how often we acknowledge — see
386    /// `peer_bandwidth`).
387    ack_threshold: u32,
388    /// The peer's declared limit on OUR outbound bandwidth (§5.4.5's
389    /// `SetPeerBandwidth`), tracked separately from `ack_threshold`.
390    /// Not otherwise enforced by this sans-IO engine.
391    peer_bandwidth: Option<u32>,
392    /// Total bytes received on the chunk stream (post-handshake) so far.
393    bytes_received: u64,
394    /// `bytes_received` value as of the last Acknowledgement sent.
395    bytes_acked: u64,
396    /// Whether the FLV file header has already been prefixed to a `Media`
397    /// event (only the very first one gets it).
398    flv: FlvTagWriter,
399    /// Count of `publish` attempts so far on this connection whose stream
400    /// key did not match `config.expected_stream_key`. Once this reaches
401    /// `ServerLimits::max_failed_publish_attempts`, the session is closed.
402    failed_publish_attempts: u32,
403    /// The message stream id the accepted `publish` was invoked on. Media on
404    /// any other stream id belongs to no published stream and is reported
405    /// rather than delivered.
406    publish_stream_id: Option<u32>,
407}
408
409/// Constant-time byte-slice equality for the `publish` stream-key check.
410/// `expected_stream_key` is the only secret in the ingest path; comparing it
411/// with `==`/`!=` short-circuits at the first differing byte, which leaks the
412/// length of the matching prefix through timing. Lengths themselves are not
413/// secret (RTMP already reveals them on the wire), so only the fixed-width
414/// fold needs to run in constant time.
415fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
416    if a.len() != b.len() {
417        return false;
418    }
419    bool::from(subtle::ConstantTimeEq::ct_eq(a, b))
420}
421
422impl ServerSession {
423    /// A new session with the given configuration.
424    #[must_use]
425    pub fn new(config: RtmpServerConfig) -> Self {
426        let ack_threshold = config.window_ack_size;
427        let chunk_limits = config.limits.chunk;
428        Self {
429            config,
430            handshake: Handshake::new(),
431            handshake_buf: Vec::new(),
432            assembler: ChunkAssembler::new(chunk_limits),
433            writer: ChunkWriter::new(),
434            state: State::Init,
435            app: None,
436            next_stream_id: FIRST_STREAM_ID,
437            created_stream_id: None,
438            ack_threshold,
439            peer_bandwidth: None,
440            bytes_received: 0,
441            bytes_acked: 0,
442            flv: FlvTagWriter::default(),
443            failed_publish_attempts: 0,
444            publish_stream_id: None,
445        }
446    }
447
448    /// Feed inbound bytes to the session. Returns `(bytes to write back,
449    /// events produced)`.
450    ///
451    /// Buffers partial handshake input and partial chunks across calls —
452    /// callers just need to forward whatever bytes arrive off the wire, in
453    /// order, one call per read.
454    ///
455    /// # Errors
456    /// [`RtmpError`] on malformed handshake/chunk/AMF0 input, or a command
457    /// used out of order (e.g. `publish` before `connect`). Never panics on
458    /// truncated or garbage input. On `Err` the session should be considered
459    /// unrecoverable/torn down: internal state may have partially advanced
460    /// past the offending input, so the caller must not keep driving it.
461    pub fn handle_data(&mut self, input: &[u8]) -> Result<(Vec<u8>, Vec<ServerEvent>)> {
462        let mut out = Vec::new();
463        let mut events = Vec::new();
464
465        let chunk_input = match self.drive_handshake(input, &mut out)? {
466            Some(bytes) => bytes,
467            None => return Ok((out, events)),
468        };
469
470        self.bytes_received = self.bytes_received.saturating_add(chunk_input.len() as u64);
471
472        // Dispatch each message as soon as it is parsed (rather than
473        // collecting a full batch from one `push` first): a Set Chunk Size
474        // protocol control message (§5.4.1) must take effect for the very
475        // next chunk that follows it, even when both arrive in the same
476        // `handle_data` call — a real ffmpeg publisher does exactly this
477        // (its own `connect`-time SetChunkSize is immediately followed, in
478        // the same TCP segment, by chunks already framed at the new size).
479        // Collecting the whole batch under one `ChunkAssembler::push` call
480        // would parse those later chunks with the *old* chunk size and
481        // misparse them.
482        self.assembler.feed(&chunk_input);
483        while let Some(msg) = self.assembler.next_message()? {
484            self.publish_chunk_damage(&mut events)?;
485            self.dispatch_message(&msg, &mut out, &mut events)?;
486        }
487        self.publish_chunk_damage(&mut events)?;
488
489        self.maybe_ack(&mut out)?;
490
491        Ok((out, events))
492    }
493
494    /// Bytes buffered from the peer that have not yet formed a complete
495    /// message — a non-zero value at end of input means the stream was cut
496    /// mid-handshake or mid-message, which the session reports as
497    /// `DamageKind::InputTruncated`.
498    #[must_use]
499    pub fn pending_len(&self) -> usize {
500        self.handshake_buf
501            .len()
502            .saturating_add(self.assembler.pending_len())
503    }
504
505    /// Drive the handshake sub-FSM with `input`, appending any handshake
506    /// reply bytes to `out`. Returns `Some(leftover_bytes)` — the
507    /// post-handshake bytes now ready for the chunk assembler — once the
508    /// handshake has completed; `None` if it is still in progress (the
509    /// caller should return early and wait for more input).
510    fn drive_handshake<'a>(
511        &mut self,
512        input: &'a [u8],
513        out: &mut Vec<u8>,
514    ) -> Result<Option<alloc::borrow::Cow<'a, [u8]>>> {
515        if self.handshake.is_done() {
516            // Borrowed: the steady-state path used to copy every inbound
517            // read into a fresh Vec before the assembler copied it again
518            // (r08-RTMP-O1).
519            return Ok(Some(alloc::borrow::Cow::Borrowed(input)));
520        }
521
522        self.handshake_buf.extend_from_slice(input);
523        loop {
524            match self.handshake.read(&self.handshake_buf) {
525                Ok((reply, consumed, done)) => {
526                    out.extend_from_slice(&reply);
527                    self.handshake_buf.drain(..consumed);
528                    if done {
529                        break;
530                    }
531                }
532                Err(RtmpError::BufferTooShort(..)) => break,
533                Err(e) => return Err(e),
534            }
535        }
536
537        if self.handshake.is_done() {
538            Ok(Some(alloc::borrow::Cow::Owned(core::mem::take(
539                &mut self.handshake_buf,
540            ))))
541        } else {
542            Ok(None)
543        }
544    }
545
546    /// Send an Acknowledgement (§5.4.3) if `bytes_received` has crossed
547    /// `ack_threshold` since the last one. Sequence number is a plain
548    /// modular `u32` truncation of the running total (see the module doc).
549    fn maybe_ack(&mut self, out: &mut Vec<u8>) -> Result<()> {
550        let threshold = u64::from(self.ack_threshold.max(1));
551        if self.bytes_received.saturating_sub(self.bytes_acked) >= threshold {
552            self.bytes_acked = self.bytes_received;
553            let seq = SequenceNumber::new(self.bytes_received as u32);
554            let ack_msg = ProtocolControl::Acknowledgement(seq).to_message();
555            out.extend_from_slice(&self.writer.write(&ack_msg)?);
556        }
557        Ok(())
558    }
559
560    /// Dispatch one reassembled [`Message`] by `message_type_id`.
561    fn dispatch_message(
562        &mut self,
563        msg: &Message,
564        out: &mut Vec<u8>,
565        events: &mut Vec<ServerEvent>,
566    ) -> Result<()> {
567        if let Some(pc) = ProtocolControl::from_message(msg)? {
568            self.handle_protocol_control(pc)?;
569            return Ok(());
570        }
571
572        if matches!(
573            msg.message_type_id,
574            MessageTypeId::CommandAmf0 | MessageTypeId::CommandAmf3
575        ) && msg.payload.len() > self.config.limits.max_command_len
576        {
577            return Err(RtmpError::CommandTooLong {
578                len: msg.payload.len(),
579                max: self.config.limits.max_command_len,
580            });
581        }
582
583        match msg.message_type_id {
584            MessageTypeId::UserControl => {
585                // Publish-only ingest: no inbound user control event needs
586                // a reply from us. An event type this engine does not
587                // decode (including a newer one a player may send) is
588                // tolerated rather than aborting the whole session over a
589                // benign/unknown control event; it is reported so a host is
590                // not left guessing, and a structurally malformed one still
591                // fails.
592                match UserControl::parse(&msg.payload) {
593                    Ok(_) => Ok(()),
594                    Err(RtmpError::UnsupportedUserControlEvent { .. }) => {
595                        let damage = crate::damage::uninterpreted("RTMP user control event");
596                        crate::damage::publish(
597                            &self.config.damage_policy,
598                            damage,
599                            events,
600                            ServerEvent::Damage,
601                        )
602                    }
603                    Err(e) => Err(e),
604                }
605            }
606            MessageTypeId::CommandAmf0 => {
607                let (command, diagnostics) =
608                    Command::parse_with_diagnostics(&msg.payload, &self.config.limits.amf0)?;
609                self.publish_amf0_diagnostics(diagnostics, events)?;
610                self.handle_command(&command, msg, out, events)
611            }
612            // #1108/RTMP-W6: an AMF3-encoded command (§7.1, message type
613            // 17) is a single leading "AMF encoding" marker byte followed
614            // by an otherwise-ordinary AMF0-encoded command — not a
615            // different command grammar. Pre-fix, an encoder/CDN front-end
616            // that opens with an AMF3 `connect` (rather than AMF0) got no
617            // reply at all and hung until its own timeout.
618            MessageTypeId::CommandAmf3 => {
619                let body =
620                    msg.payload
621                        .get(1..)
622                        .ok_or(RtmpError::BufferTooShort(BufferTooShort::new(
623                            1,
624                            msg.payload.len(),
625                            "AMF3 command encoding marker byte",
626                        )))?;
627                let (command, diagnostics) =
628                    Command::parse_with_diagnostics(body, &self.config.limits.amf0)?;
629                self.publish_amf0_diagnostics(diagnostics, events)?;
630                self.handle_command(&command, msg, out, events)
631            }
632            MessageTypeId::Audio | MessageTypeId::Video | MessageTypeId::DataAmf0 => self
633                .emit_media_if_publishing(
634                    msg.message_type_id,
635                    msg.timestamp.millis(),
636                    msg.message_stream_id,
637                    &msg.payload,
638                    events,
639                ),
640            // #1108/RTMP-W6 (remainder): Aggregate(22) used to surface as
641            // `Unsupported` — an encoder/relay that bundles media in
642            // aggregates (FMS/Wowza-style relays, some hardware encoders)
643            // still produced zero `Media` events. Now unpacked into its
644            // contained sub-messages per §7.1.6 (see
645            // `deliver_aggregate`).
646            MessageTypeId::Aggregate => self.deliver_aggregate(msg, events),
647            // Data-AMF3(15), Shared Object(16/19), and anything
648            // unrecognised: out of scope for this ingest engine (see the
649            // crate's non-goals) — accepted, not fatal, and surfaced to
650            // the caller instead of silently dropped with no signal at
651            // all. `Unsupported` names the type; the report is what the
652            // caller's policy decides on.
653            other => {
654                events.push(ServerEvent::Unsupported {
655                    message_type_id: other,
656                });
657                let damage = crate::damage::uninterpreted("RTMP message type");
658                crate::damage::publish(
659                    &self.config.damage_policy,
660                    damage,
661                    events,
662                    ServerEvent::Damage,
663                )
664            }
665        }
666    }
667
668    /// Hand every report the chunk assembler collected to the caller's
669    /// policy, in wire order ahead of the message they preceded.
670    fn publish_chunk_damage(&mut self, events: &mut Vec<ServerEvent>) -> Result<()> {
671        for damage in self.assembler.take_damage() {
672            crate::damage::publish(
673                &self.config.damage_policy,
674                damage,
675                events,
676                ServerEvent::Damage,
677            )?;
678        }
679        Ok(())
680    }
681
682    /// Hand the AMF0 reports a command body produced to the caller's policy.
683    fn publish_amf0_diagnostics(
684        &self,
685        diagnostics: Vec<broadcast_core::damage::Damage>,
686        events: &mut Vec<ServerEvent>,
687    ) -> Result<()> {
688        for damage in diagnostics {
689            crate::damage::publish(
690                &self.config.damage_policy,
691                damage,
692                events,
693                ServerEvent::Damage,
694            )?;
695        }
696        Ok(())
697    }
698
699    /// Apply a protocol control message's effect (§5.4). A malformed payload is rejected earlier,
700    /// in [`ProtocolControl::from_message`]; a chunk size above the caller's ceiling is refused.
701    fn handle_protocol_control(&mut self, pc: ProtocolControl) -> Result<()> {
702        match pc {
703            ProtocolControl::SetChunkSize(n) => self.assembler.adopt_peer_chunk_size(n)?,
704            ProtocolControl::WindowAckSize(w) => self.ack_threshold = w,
705            // #1108/RTMP-W7: was `self.ack_threshold = ack_window_size` —
706            // conflated the peer's outbound-bandwidth limit (§5.4.5) with
707            // our own ack threshold (§5.4.4). See `peer_bandwidth`'s doc.
708            ProtocolControl::SetPeerBandwidth {
709                ack_window_size, ..
710            } => self.peer_bandwidth = Some(ack_window_size),
711            // #1108/RTMP-W2: was ignored — see `ChunkAssembler::abort`'s doc.
712            ProtocolControl::Abort { chunk_stream_id } => {
713                self.assembler.abort(ChunkStreamId::new(chunk_stream_id))
714            }
715            ProtocolControl::Acknowledgement(_) => {}
716        }
717        Ok(())
718    }
719
720    /// Route a Command Message (§7.1.1) by `command.name` (§7.2).
721    fn handle_command(
722        &mut self,
723        command: &Command,
724        msg: &Message,
725        out: &mut Vec<u8>,
726        events: &mut Vec<ServerEvent>,
727    ) -> Result<()> {
728        match command.name.as_str() {
729            "connect" => self.handle_connect(command, msg, out, events),
730            "releaseStream" | "FCPublish" => {
731                self.reply_result(command, msg, vec![Amf0Value::Undefined], out)
732            }
733            "createStream" => self.handle_create_stream(command, msg, out),
734            "publish" => self.handle_publish(command, msg, out, events),
735            "deleteStream" | "FCUnpublish" => {
736                self.state = State::Closed;
737                events.push(ServerEvent::Eof);
738                Ok(())
739            }
740            // Unrecognised command name: ignore rather than error, per the
741            // "never error on OBS/extra commands" design goal — and report
742            // it, so a publisher whose command this engine did not act on is
743            // not left believing it was.
744            _ => {
745                let damage = crate::damage::uninterpreted("RTMP command");
746                crate::damage::publish(
747                    &self.config.damage_policy,
748                    damage,
749                    events,
750                    ServerEvent::Damage,
751                )
752            }
753        }
754    }
755
756    /// `connect` (§7.2.1, `NetConnection`): capture `app`, reply
757    /// WindowAckSize + SetPeerBandwidth + SetChunkSize + `_result`, emit
758    /// [`ServerEvent::Connected`].
759    ///
760    /// # Errors
761    /// [`RtmpError::Malformed`] if the command has no command-object
762    /// argument (arg0), or arg0 is not an AMF0 Object, or the object has no
763    /// `app` property of type String — a present-but-empty `app` string
764    /// (`""`) is tolerated (it is a valid, if unhelpful, application name).
765    /// [`RtmpError::UnexpectedState`] if the session has already reached
766    /// [`State::Closed`] or is [`State::Publishing`]: `connect` opens the
767    /// `NetConnection` once (§7.2.1.1), so a repeat during publishing is
768    /// refused and the session keeps publishing.
769    fn handle_connect(
770        &mut self,
771        command: &Command,
772        msg: &Message,
773        out: &mut Vec<u8>,
774        events: &mut Vec<ServerEvent>,
775    ) -> Result<()> {
776        if self.state == State::Closed {
777            return Err(RtmpError::UnexpectedState {
778                what: "connect received after the session was closed",
779            });
780        }
781        if self.state == State::Publishing {
782            return Err(RtmpError::UnexpectedState {
783                what: "connect received while publishing",
784            });
785        }
786
787        let Some(Amf0Value::Object(pairs)) = command.arguments.first() else {
788            return Err(RtmpError::UnexpectedState {
789                what: "connect carries no command object",
790            });
791        };
792        let Some(app) = pairs.iter().find_map(|(k, v)| {
793            if k == "app" {
794                match v {
795                    Amf0Value::String(s) => Some(s.clone()),
796                    _ => None,
797                }
798            } else {
799                None
800            }
801        }) else {
802            return Err(RtmpError::UnexpectedState {
803                what: "connect command object carries no string app",
804            });
805        };
806
807        self.app = Some(app.clone());
808        self.state = State::Connected;
809
810        let window_ack = ProtocolControl::WindowAckSize(self.config.window_ack_size).to_message();
811        out.extend_from_slice(&self.writer.write(&window_ack)?);
812
813        let peer_bandwidth = ProtocolControl::SetPeerBandwidth {
814            ack_window_size: self.config.peer_bandwidth,
815            limit_type: LimitType::Dynamic,
816        }
817        .to_message();
818        out.extend_from_slice(&self.writer.write(&peer_bandwidth)?);
819
820        let chunk_size = ChunkSize::try_new(self.config.chunk_size)?;
821        let set_chunk_size = ProtocolControl::SetChunkSize(chunk_size).to_message();
822        out.extend_from_slice(&self.writer.write(&set_chunk_size)?);
823        self.writer.set_chunk_size(chunk_size);
824
825        let result = Command {
826            name: "_result".to_string(),
827            transaction_id: command.transaction_id,
828            arguments: vec![
829                Amf0Value::Object(vec![
830                    (
831                        "fmsVer".to_string(),
832                        Amf0Value::String(FMS_VERSION.to_string()),
833                    ),
834                    ("capabilities".to_string(), Amf0Value::Number(CAPABILITIES)),
835                ]),
836                Amf0Value::Object(vec![
837                    ("level".to_string(), Amf0Value::String("status".to_string())),
838                    (
839                        "code".to_string(),
840                        Amf0Value::String("NetConnection.Connect.Success".to_string()),
841                    ),
842                    (
843                        "description".to_string(),
844                        Amf0Value::String("Connection succeeded.".to_string()),
845                    ),
846                ]),
847            ],
848        };
849        out.extend_from_slice(&self.writer.write(&self.command_message(msg, &result)?)?);
850
851        events.push(ServerEvent::Connected { app });
852        Ok(())
853    }
854
855    /// `createStream` (§7.2.2, `NetConnection`): allocate a message stream
856    /// id, reply `_result` with it.
857    ///
858    /// # Errors
859    /// [`RtmpError::UnexpectedState`] unless `state == State::Connected` —
860    /// this rejects `createStream` before a successful `connect`, and also
861    /// after [`State::Closed`] (post-`deleteStream`/`FCUnpublish`).
862    fn handle_create_stream(
863        &mut self,
864        command: &Command,
865        msg: &Message,
866        out: &mut Vec<u8>,
867    ) -> Result<()> {
868        if self.state != State::Connected {
869            return Err(RtmpError::UnexpectedState {
870                what: "createStream received before a successful connect (or after the session was closed)",
871            });
872        }
873
874        let stream_id = self.next_stream_id;
875        self.next_stream_id = self.next_stream_id.saturating_add(1);
876        self.created_stream_id = Some(stream_id);
877
878        let result = Command {
879            name: "_result".to_string(),
880            transaction_id: command.transaction_id,
881            arguments: vec![Amf0Value::Null, Amf0Value::Number(f64::from(stream_id))],
882        };
883        out.extend_from_slice(&self.writer.write(&self.command_message(msg, &result)?)?);
884        Ok(())
885    }
886
887    /// `publish` (§7.2.2.6, `NetStream`): capture the stream key, enforce
888    /// `expected_stream_key` if configured, reply StreamBegin + `onStatus`,
889    /// transition to [`State::Publishing`], emit [`ServerEvent::Publish`].
890    ///
891    /// # Errors
892    /// [`RtmpError::UnexpectedState`] unless `state == State::Connected`
893    /// *and* a stream was actually allocated by a preceding `createStream`
894    /// (`created_stream_id.is_some()`) — this rejects `publish` before
895    /// `connect`, `publish` before `createStream`, and `publish` after
896    /// [`State::Closed`]. Also [`RtmpError::UnexpectedState`] once this
897    /// connection has already exhausted `ServerLimits::max_failed_publish_attempts`
898    /// mismatched-key attempts — the session is closed at that point and the
899    /// caller must not keep driving it (see [`ServerSession::handle_data`]).
900    fn handle_publish(
901        &mut self,
902        command: &Command,
903        msg: &Message,
904        out: &mut Vec<u8>,
905        events: &mut Vec<ServerEvent>,
906    ) -> Result<()> {
907        if self.state != State::Connected || self.created_stream_id.is_none() {
908            return Err(RtmpError::UnexpectedState {
909                what: "publish received before a successful connect+createStream (or after the session was closed)",
910            });
911        }
912        if self.failed_publish_attempts >= self.config.limits.max_failed_publish_attempts {
913            self.state = State::Closed;
914            return Err(RtmpError::UnexpectedState {
915                what: "publish rejected too many times on this connection (stream key mismatch); session closed",
916            });
917        }
918        let Some(app) = self.app.clone() else {
919            return Err(RtmpError::UnexpectedState {
920                what: "publish received in Connected state without a captured app",
921            });
922        };
923
924        let stream_key = match command.arguments.get(1) {
925            Some(Amf0Value::String(s)) => s.clone(),
926            _ => {
927                return Err(RtmpError::UnexpectedState {
928                    what: "publish carries no publishing-name (string) argument",
929                });
930            }
931        };
932        let stream_id = msg.message_stream_id.get();
933
934        if let Some(expected) = &self.config.expected_stream_key
935            && !constant_time_eq(expected.as_bytes(), stream_key.as_bytes())
936        {
937            self.failed_publish_attempts += 1;
938            let on_status = Command {
939                name: "onStatus".to_string(),
940                transaction_id: 0.0,
941                arguments: vec![
942                    Amf0Value::Null,
943                    Amf0Value::Object(vec![
944                        ("level".to_string(), Amf0Value::String("error".to_string())),
945                        (
946                            "code".to_string(),
947                            Amf0Value::String("NetStream.Publish.BadName".to_string()),
948                        ),
949                        (
950                            "description".to_string(),
951                            Amf0Value::String("Stream key mismatch.".to_string()),
952                        ),
953                    ]),
954                ],
955            };
956            out.extend_from_slice(&self.writer.write(&self.command_message(msg, &on_status)?)?);
957            // No Publish/Media events; state unchanged (not Publishing).
958            return Ok(());
959        }
960
961        let stream_begin = UserControl::StreamBegin(stream_id).to_message()?;
962        out.extend_from_slice(&self.writer.write(&stream_begin)?);
963
964        let on_status = Command {
965            name: "onStatus".to_string(),
966            transaction_id: 0.0,
967            arguments: vec![
968                Amf0Value::Null,
969                Amf0Value::Object(vec![
970                    ("level".to_string(), Amf0Value::String("status".to_string())),
971                    (
972                        "code".to_string(),
973                        Amf0Value::String("NetStream.Publish.Start".to_string()),
974                    ),
975                    (
976                        "description".to_string(),
977                        Amf0Value::String(format!("{stream_key} is now published.")),
978                    ),
979                ]),
980            ],
981        };
982        out.extend_from_slice(&self.writer.write(&self.command_message(msg, &on_status)?)?);
983
984        self.state = State::Publishing;
985        self.publish_stream_id = Some(stream_id);
986        events.push(ServerEvent::Publish {
987            app,
988            stream_key,
989            stream_id,
990        });
991        Ok(())
992    }
993
994    /// Reply a benign `_result` command echoing `command`'s transaction id
995    /// (used for the OBS extras `releaseStream`/`FCPublish`, which never
996    /// error even when tolerated rather than fully implemented).
997    fn reply_result(
998        &mut self,
999        command: &Command,
1000        msg: &Message,
1001        arguments: Vec<Amf0Value>,
1002        out: &mut Vec<u8>,
1003    ) -> Result<()> {
1004        let result = Command {
1005            name: "_result".to_string(),
1006            transaction_id: command.transaction_id,
1007            arguments,
1008        };
1009        out.extend_from_slice(&self.writer.write(&self.command_message(msg, &result)?)?);
1010        Ok(())
1011    }
1012
1013    /// Wrap `command` in a [`Message`] on [`COMMAND_CHUNK_STREAM_ID`],
1014    /// echoing `request`'s message stream id (replies travel back on the
1015    /// same `NetConnection`/`NetStream` channel the request arrived on).
1016    fn command_message(&self, request: &Message, command: &Command) -> Result<Message> {
1017        Ok(Message {
1018            chunk_stream_id: ChunkStreamId::new(COMMAND_CHUNK_STREAM_ID),
1019            timestamp: Timestamp::ZERO,
1020            message_type_id: MessageTypeId::CommandAmf0,
1021            message_stream_id: request.message_stream_id,
1022            payload: command.to_body()?,
1023        })
1024    }
1025
1026    /// Convert an Audio(8)/Video(9)/Data-AMF0(18) message to an FLV tag and
1027    /// emit it as [`ServerEvent::Media`], but only while
1028    /// [`State::Publishing`] and only on the stream id `publish` was accepted
1029    /// on (§7.2.2.6). Media outside a published stream belongs to no output
1030    /// and is dropped, which is reported rather than done silently: a
1031    /// publisher whose stream id is wrong would otherwise look healthy while
1032    /// producing nothing.
1033    fn emit_media_if_publishing(
1034        &mut self,
1035        tag_type: MessageTypeId,
1036        timestamp: u32,
1037        message_stream_id: MessageStreamId,
1038        payload: &[u8],
1039        events: &mut Vec<ServerEvent>,
1040    ) -> Result<()> {
1041        let inside_stream = self.state == State::Publishing
1042            && self.publish_stream_id == Some(message_stream_id.get());
1043        if !inside_stream {
1044            let what = if self.state == State::Publishing {
1045                "RTMP media on an unknown stream id"
1046            } else {
1047                "RTMP media before publish"
1048            };
1049            let damage = crate::damage::outside_stream(what, timestamp);
1050            return crate::damage::publish(
1051                &self.config.damage_policy,
1052                damage,
1053                events,
1054                ServerEvent::Damage,
1055            );
1056        }
1057
1058        let flv = self.flv.tag(tag_type, timestamp, payload)?;
1059        events.push(ServerEvent::Media { flv });
1060        Ok(())
1061    }
1062
1063    /// Unpack an Aggregate Message (22, §7.1.6) and deliver each contained
1064    /// sub-message exactly as an ordinary Audio/Video/Data-AMF0 message
1065    /// would be delivered; see [`crate::flv::unpack_aggregate`].
1066    ///
1067    /// A sub-message whose framing does not hold ends the aggregate (the
1068    /// good ones before it are already delivered) and is reported; the
1069    /// connection continues.
1070    fn deliver_aggregate(&mut self, msg: &Message, events: &mut Vec<ServerEvent>) -> Result<()> {
1071        let message_stream_id = msg.message_stream_id;
1072        let mut damage = Vec::new();
1073        unpack_aggregate(msg, &mut damage, |tag_type, timestamp, payload| {
1074            self.emit_media_if_publishing(tag_type, timestamp, message_stream_id, payload, events)
1075        })?;
1076        for report in damage {
1077            crate::damage::publish(
1078                &self.config.damage_policy,
1079                report,
1080                events,
1081                ServerEvent::Damage,
1082            )?;
1083        }
1084        Ok(())
1085    }
1086}
1087
1088#[cfg(test)]
1089mod tests {
1090    use super::*;
1091    use crate::flv::{FLV_HEADER_LEN, FLV_PREV_TAG_SIZE_LEN, FLV_TAG_HEADER_LEN, FlvHeader};
1092    use crate::handshake::{HANDSHAKE_PACKET_LEN, RTMP_VERSION};
1093    use crate::ids::MessageStreamId;
1094    use crate::message::CONTROL_CHUNK_STREAM_ID as CTRL_CSID;
1095    use crate::test_support::{
1096        DEFAULT_AMF0_LIMITS, MAX_CHUNK_SIZE, MAX_COMMAND_LEN, MAX_FAILED_PUBLISH_ATTEMPTS,
1097        TEST_CHUNK_LIMITS,
1098    };
1099    use broadcast_core::ParseWith;
1100    use broadcast_core::Serialize;
1101
1102    // ── Test-only wire builders (this crate's own encoders) ─────────────
1103
1104    const CLIENT_CSID: u32 = 3;
1105
1106    fn build_c0_c1() -> Vec<u8> {
1107        let mut v = vec![0u8; 1 + HANDSHAKE_PACKET_LEN];
1108        v[0] = RTMP_VERSION;
1109        v
1110    }
1111
1112    fn build_c2() -> Vec<u8> {
1113        vec![0u8; HANDSHAKE_PACKET_LEN]
1114    }
1115
1116    fn command_message(
1117        csid: u32,
1118        stream_id: u32,
1119        name: &str,
1120        txn: f64,
1121        args: Vec<Amf0Value>,
1122    ) -> Message {
1123        let body = Command {
1124            name: name.to_string(),
1125            transaction_id: txn,
1126            arguments: args,
1127        }
1128        .to_body()
1129        .unwrap();
1130        Message {
1131            chunk_stream_id: ChunkStreamId::new(csid),
1132            timestamp: Timestamp::ZERO,
1133            message_type_id: MessageTypeId::CommandAmf0,
1134            message_stream_id: MessageStreamId::new(stream_id),
1135            payload: body,
1136        }
1137    }
1138
1139    fn connect_bytes(app: &str) -> Vec<u8> {
1140        let args = vec![Amf0Value::Object(vec![
1141            ("app".to_string(), Amf0Value::String(app.to_string())),
1142            (
1143                "type".to_string(),
1144                Amf0Value::String("nonprivate".to_string()),
1145            ),
1146        ])];
1147        let msg = command_message(CLIENT_CSID, 0, "connect", 1.0, args);
1148        ChunkWriter::new().write(&msg).unwrap()
1149    }
1150
1151    fn connect_bytes_no_args() -> Vec<u8> {
1152        let msg = command_message(CLIENT_CSID, 0, "connect", 1.0, vec![]);
1153        ChunkWriter::new().write(&msg).unwrap()
1154    }
1155
1156    fn create_stream_bytes() -> Vec<u8> {
1157        let msg = command_message(CLIENT_CSID, 0, "createStream", 2.0, vec![Amf0Value::Null]);
1158        ChunkWriter::new().write(&msg).unwrap()
1159    }
1160
1161    fn publish_bytes(stream_id: u32, stream_key: &str) -> Vec<u8> {
1162        let args = vec![
1163            Amf0Value::Null,
1164            Amf0Value::String(stream_key.to_string()),
1165            Amf0Value::String("live".to_string()),
1166        ];
1167        let msg = command_message(CLIENT_CSID, stream_id, "publish", 3.0, args);
1168        ChunkWriter::new().write(&msg).unwrap()
1169    }
1170
1171    fn av_bytes(
1172        stream_id: u32,
1173        message_type_id: MessageTypeId,
1174        csid: u32,
1175        timestamp: u32,
1176        payload: Vec<u8>,
1177    ) -> Vec<u8> {
1178        let msg = Message {
1179            chunk_stream_id: ChunkStreamId::new(csid),
1180            timestamp: Timestamp::from_millis(timestamp),
1181            message_type_id,
1182            message_stream_id: MessageStreamId::new(stream_id),
1183            payload,
1184        };
1185        ChunkWriter::new().write(&msg).unwrap()
1186    }
1187
1188    /// Decode every reassembled [`Message`] out of a reply byte stream.
1189    /// Pre-sets a generous chunk size: this session's own `_result`/
1190    /// `onStatus` replies are always written with the writer's *current*
1191    /// chunk size (128 until `connect`'s `SetChunkSize` control message is
1192    /// sent, `config.chunk_size` after) but every individual message in
1193    /// these tests fits in a single chunk either way, so decoding under a
1194    /// single generous assumption reproduces the same framing without
1195    /// needing to replay `SetChunkSize` mid-decode.
1196    fn decode_messages(bytes: &[u8]) -> Vec<Message> {
1197        let mut assembler = ChunkAssembler::new(TEST_CHUNK_LIMITS);
1198        assembler.set_chunk_size(ChunkSize::new(65536).expect("a valid chunk size"));
1199        assembler.push(bytes).expect("well-formed reply stream")
1200    }
1201
1202    fn decode_commands(bytes: &[u8]) -> Vec<Command> {
1203        decode_messages(bytes)
1204            .iter()
1205            .filter(|m| m.message_type_id == MessageTypeId::CommandAmf0)
1206            .map(|m| {
1207                Command::parse_with(&m.payload, &DEFAULT_AMF0_LIMITS)
1208                    .expect("well-formed command reply")
1209            })
1210            .collect()
1211    }
1212
1213    fn onstatus_code(cmd: &Command) -> Option<String> {
1214        cmd.arguments.iter().find_map(|v| match v {
1215            Amf0Value::Object(pairs) => pairs.iter().find_map(|(k, v)| {
1216                if k == "code" {
1217                    match v {
1218                        Amf0Value::String(s) => Some(s.clone()),
1219                        _ => None,
1220                    }
1221                } else {
1222                    None
1223                }
1224            }),
1225            _ => None,
1226        })
1227    }
1228
1229    /// Drive a session through handshake → connect → createStream →
1230    /// publish, returning `(session, all reply bytes, all events)`.
1231    fn publish_flow(
1232        config: RtmpServerConfig,
1233        stream_key: &str,
1234    ) -> (ServerSession, Vec<u8>, Vec<ServerEvent>) {
1235        let mut session = ServerSession::new(config);
1236        // `all_out` accumulates only *post-handshake* (chunk-encoded) reply
1237        // bytes: the handshake reply (S0+S1+S2) is a raw fixed-length
1238        // packet, not chunk-stream framing, so it must not be fed into a
1239        // `ChunkAssembler` alongside the chunk-encoded command replies.
1240        let mut all_out = Vec::new();
1241        let mut all_events = Vec::new();
1242
1243        session.handle_data(&build_c0_c1()).unwrap();
1244        session.handle_data(&build_c2()).unwrap();
1245
1246        let (out, events) = session.handle_data(&connect_bytes("live")).unwrap();
1247        all_out.extend(out);
1248        all_events.extend(events);
1249
1250        let (out, events) = session.handle_data(&create_stream_bytes()).unwrap();
1251        all_out.extend(out);
1252        all_events.extend(events);
1253
1254        // ServerSession always allocates stream ids starting at 1.
1255        let (out, events) = session.handle_data(&publish_bytes(1, stream_key)).unwrap();
1256        all_out.extend(out);
1257        all_events.extend(events);
1258
1259        (session, all_out, all_events)
1260    }
1261
1262    // ── Handshake ─────────────────────────────────────────────────────────
1263
1264    #[test]
1265    fn handshake_completes_and_reply_contains_s0_s1_s2() {
1266        let mut session = ServerSession::new(RtmpServerConfig::default());
1267        let (out1, events1) = session.handle_data(&build_c0_c1()).unwrap();
1268        assert_eq!(
1269            out1.len(),
1270            1 + HANDSHAKE_PACKET_LEN + HANDSHAKE_PACKET_LEN,
1271            "S0+S1+S2 must be a single 3073-byte reply"
1272        );
1273        assert!(events1.is_empty());
1274
1275        let (out2, events2) = session.handle_data(&build_c2()).unwrap();
1276        assert!(out2.is_empty(), "C2 receipt produces no reply bytes itself");
1277        assert!(events2.is_empty());
1278    }
1279
1280    #[test]
1281    fn handshake_split_across_calls_still_completes() {
1282        let mut session = ServerSession::new(RtmpServerConfig::default());
1283        let c0c1 = build_c0_c1();
1284        let (out1, _) = session.handle_data(&c0c1[..500]).unwrap();
1285        assert!(out1.is_empty(), "partial C0+C1 produces no reply yet");
1286        let (out2, _) = session.handle_data(&c0c1[500..]).unwrap();
1287        assert_eq!(out2.len(), 1 + 2 * HANDSHAKE_PACKET_LEN);
1288        let (_out3, _) = session.handle_data(&build_c2()).unwrap();
1289    }
1290
1291    #[test]
1292    fn c2_pipelined_with_connect_chunk_in_one_call_still_parses_connect() {
1293        // Real clients commonly send C2 back-to-back with the very next
1294        // chunk-encoded message (e.g. `connect`) in the same TCP segment,
1295        // so both arrive together in a single `handle_data` call. The
1296        // post-handshake leftover bytes from that call must be handed to
1297        // the chunk assembler within the SAME call, not merely buffered
1298        // for a subsequent one.
1299        let mut session = ServerSession::new(RtmpServerConfig::default());
1300        session.handle_data(&build_c0_c1()).unwrap();
1301
1302        let mut pipelined = build_c2();
1303        pipelined.extend_from_slice(&connect_bytes("live"));
1304
1305        let (_out, events) = session.handle_data(&pipelined).unwrap();
1306        assert_eq!(
1307            events,
1308            vec![ServerEvent::Connected {
1309                app: "live".to_string()
1310            }],
1311            "C2 pipelined with the connect chunk in one handle_data call must \
1312             still yield Connected from that call (leftover bytes must not be dropped)"
1313        );
1314    }
1315
1316    // ── connect ───────────────────────────────────────────────────────────
1317
1318    #[test]
1319    fn connect_emits_connected_event_and_result_reply() {
1320        let mut session = ServerSession::new(RtmpServerConfig::default());
1321        session.handle_data(&build_c0_c1()).unwrap();
1322        session.handle_data(&build_c2()).unwrap();
1323
1324        let (out, events) = session.handle_data(&connect_bytes("live")).unwrap();
1325        assert_eq!(
1326            events,
1327            vec![ServerEvent::Connected {
1328                app: "live".to_string()
1329            }]
1330        );
1331
1332        let commands = decode_commands(&out);
1333        assert!(
1334            commands.iter().any(|c| c.name == "_result"),
1335            "connect reply must contain a _result command"
1336        );
1337    }
1338
1339    /// T12/T15: a configured `chunk_size` of 0 is not a valid Set Chunk Size
1340    /// value (§5.4.1); the connect reply must return `Err`, not panic.
1341    #[test]
1342    fn connect_with_invalid_configured_chunk_size_errors_not_panics() {
1343        let mut session = ServerSession::new(RtmpServerConfig::default().with_chunk_size(0));
1344        session.handle_data(&build_c0_c1()).unwrap();
1345        session.handle_data(&build_c2()).unwrap();
1346        let err = session.handle_data(&connect_bytes("live")).unwrap_err();
1347        assert!(
1348            matches!(err, RtmpError::ChunkSizeOutOfRange { value: 0 }),
1349            "{err:?}"
1350        );
1351    }
1352
1353    /// RTMP-W6 (#1108): an AMF3-encoded `connect` (message type 17) is a
1354    /// leading format-marker byte + an otherwise-ordinary AMF0 command
1355    /// body — not a distinct grammar. Pre-fix, this hit the catch-all and
1356    /// got no reply at all (the client would hang until its own timeout).
1357    #[test]
1358    fn amf3_connect_is_answered_like_amf0() {
1359        let mut session = ServerSession::new(RtmpServerConfig::default());
1360        session.handle_data(&build_c0_c1()).unwrap();
1361        session.handle_data(&build_c2()).unwrap();
1362
1363        let args = vec![Amf0Value::Object(vec![(
1364            "app".to_string(),
1365            Amf0Value::String("live".to_string()),
1366        )])];
1367        let amf0_body = Command {
1368            name: "connect".to_string(),
1369            transaction_id: 1.0,
1370            arguments: args,
1371        }
1372        .to_body()
1373        .unwrap();
1374        let mut amf3_body = vec![0x00]; // AMF3 encoding marker byte
1375        amf3_body.extend(amf0_body);
1376        let msg = Message {
1377            chunk_stream_id: ChunkStreamId::new(CLIENT_CSID),
1378            timestamp: Timestamp::ZERO,
1379            message_type_id: MessageTypeId::CommandAmf3,
1380            message_stream_id: MessageStreamId::new(0),
1381            payload: amf3_body,
1382        };
1383        let bytes = ChunkWriter::new().write(&msg).unwrap();
1384
1385        let (out, events) = session.handle_data(&bytes).unwrap();
1386        assert_eq!(
1387            events,
1388            vec![ServerEvent::Connected {
1389                app: "live".to_string()
1390            }]
1391        );
1392        let commands = decode_commands(&out);
1393        assert!(
1394            commands.iter().any(|c| c.name == "_result"),
1395            "AMF3 connect must still get a _result reply"
1396        );
1397    }
1398
1399    /// RTMP-W6 (#1108): an Aggregate (22) message used to be silently
1400    /// dropped with no signal at all (then, briefly, surfaced as
1401    /// `ServerEvent::Unsupported`). It is now unpacked into its contained
1402    /// sub-messages; a *malformed* one is a `Malformed` error, and the
1403    /// opaque `0xAA` filler below is exactly that (a bogus `DataSize`/
1404    /// `Back Pointer`), so this exercises the reject side of the new
1405    /// behaviour.
1406    #[test]
1407    fn aggregate_message_surfaces_unsupported_event() {
1408        let mut session = ServerSession::new(RtmpServerConfig::default());
1409        session.handle_data(&build_c0_c1()).unwrap();
1410        session.handle_data(&build_c2()).unwrap();
1411        session.handle_data(&connect_bytes("live")).unwrap();
1412
1413        let msg = Message {
1414            chunk_stream_id: ChunkStreamId::new(CLIENT_CSID),
1415            timestamp: Timestamp::ZERO,
1416            message_type_id: MessageTypeId::Aggregate,
1417            message_stream_id: MessageStreamId::new(0),
1418            payload: vec![0xAA; 20], // opaque; not a valid aggregate body
1419        };
1420        let bytes = ChunkWriter::new().write(&msg).unwrap();
1421
1422        let (_out, events) = session
1423            .handle_data(&bytes)
1424            .expect("a garbage aggregate body must not end the session");
1425        assert!(
1426            events.iter().any(|e| matches!(
1427                e,
1428                ServerEvent::Damage(d) if d.kind() == broadcast_core::damage::DamageKind::MediaUnitDropped
1429            )),
1430            "a garbage aggregate body must be reported, got {events:?}"
1431        );
1432    }
1433
1434    /// Builds one Aggregate (22) body from `(tag type, timestamp, data)`
1435    /// sub-messages, writing the timestamps in FLV layout (24-bit high +
1436    /// extended low byte) and each `Back Pointer` as "size of this message
1437    /// including its header" (§7.1.6).
1438    fn aggregate_body(subs: &[(MessageTypeId, u32, &[u8])]) -> Vec<u8> {
1439        let mut body = Vec::new();
1440        for &(tag_type, timestamp, data) in subs {
1441            let data_size = data.len() as u32;
1442            body.push(tag_type.to_u8());
1443            body.push((data_size >> 16) as u8);
1444            body.push((data_size >> 8) as u8);
1445            body.push(data_size as u8);
1446            body.push((timestamp >> 16) as u8);
1447            body.push((timestamp >> 8) as u8);
1448            body.push(timestamp as u8);
1449            body.push((timestamp >> 24) as u8);
1450            body.extend_from_slice(&[0, 0, 0]); // StreamID, always 0.
1451            body.extend_from_slice(data);
1452            let back_pointer = (11 + data.len()) as u32;
1453            body.extend_from_slice(&back_pointer.to_be_bytes());
1454        }
1455        body
1456    }
1457
1458    /// Pulls the `(tag_type, timestamp)` out of one `Media` event's FLV
1459    /// bytes (the tag starts after the one-time FLV file header).
1460    fn first_flv_tag_header(flv: &[u8]) -> (MessageTypeId, u32) {
1461        let tag = if flv.len() > 13 && flv.starts_with(b"FLV") {
1462            &flv[13..]
1463        } else {
1464            flv
1465        };
1466        let ts_low24 = u32::from_be_bytes([0, tag[4], tag[5], tag[6]]);
1467        (
1468            MessageTypeId::from_u8(tag[0]),
1469            ts_low24 | (u32::from(tag[7]) << 24),
1470        )
1471    }
1472
1473    /// Publishes through the full handshake/connect/createStream/publish
1474    /// sequence so subsequent media is actually emitted.
1475    fn publishing_session() -> ServerSession {
1476        let mut session = ServerSession::new(RtmpServerConfig::default());
1477        session.handle_data(&build_c0_c1()).unwrap();
1478        session.handle_data(&build_c2()).unwrap();
1479        session.handle_data(&connect_bytes("live")).unwrap();
1480        session.handle_data(&create_stream_bytes()).unwrap();
1481        session.handle_data(&publish_bytes(1, "mystream")).unwrap();
1482        session
1483    }
1484
1485    /// RTMP-W6 remainder (#1108): a well-formed aggregate of two video +
1486    /// one audio sub-message must be delivered as three ordinary `Media`
1487    /// events with the sub-message timestamps preserved.
1488    #[test]
1489    fn aggregate_message_is_unpacked_into_media_events() {
1490        let mut session = publishing_session();
1491        let body = aggregate_body(&[
1492            (MessageTypeId::Video, 1000, &[0x17, 0x01, 0xAA, 0xBB]),
1493            (MessageTypeId::Video, 1040, &[0x27, 0x01, 0xCC]),
1494            (MessageTypeId::Audio, 1005, &[0xAF, 0x01, 0xDD, 0xEE]),
1495        ]);
1496        let msg = Message {
1497            chunk_stream_id: ChunkStreamId::new(CLIENT_CSID),
1498            timestamp: Timestamp::from_millis(1000), // == first sub-message ts, so offset is 0
1499            message_type_id: MessageTypeId::Aggregate,
1500            message_stream_id: MessageStreamId::new(1),
1501            payload: body,
1502        };
1503        let bytes = ChunkWriter::new().write(&msg).unwrap();
1504        let (_out, events) = session.handle_data(&bytes).unwrap();
1505        let tags: Vec<(MessageTypeId, u32)> = events
1506            .iter()
1507            .map(|e| match e {
1508                ServerEvent::Media { flv } => first_flv_tag_header(flv),
1509                other => panic!("expected only Media events, got {other:?}"),
1510            })
1511            .collect();
1512        assert_eq!(
1513            tags,
1514            vec![
1515                (MessageTypeId::Video, 1000),
1516                (MessageTypeId::Video, 1040),
1517                (MessageTypeId::Audio, 1005),
1518            ]
1519        );
1520    }
1521
1522    /// §7.1.6 timestamp renormalization: when the first sub-message's ts
1523    /// differs from the aggregate's own, offset = (aggregate ts − first
1524    /// sub ts) is added to every sub-message ts.
1525    #[test]
1526    fn aggregate_timestamps_are_renormalized_against_the_aggregate() {
1527        let mut session = publishing_session();
1528        let body = aggregate_body(&[
1529            (MessageTypeId::Video, 50, &[0x17, 0x01]),
1530            (MessageTypeId::Audio, 60, &[0xAF, 0x01]),
1531        ]);
1532        let msg = Message {
1533            chunk_stream_id: ChunkStreamId::new(CLIENT_CSID),
1534            timestamp: Timestamp::from_millis(100),
1535            message_type_id: MessageTypeId::Aggregate,
1536            message_stream_id: MessageStreamId::new(1),
1537            payload: body,
1538        };
1539        let bytes = ChunkWriter::new().write(&msg).unwrap();
1540        let (_out, events) = session.handle_data(&bytes).unwrap();
1541        let tags: Vec<(MessageTypeId, u32)> = events
1542            .iter()
1543            .map(|e| match e {
1544                ServerEvent::Media { flv } => first_flv_tag_header(flv),
1545                other => panic!("expected only Media events, got {other:?}"),
1546            })
1547            .collect();
1548        // offset = 100 − 50 = 50 added to each.
1549        assert_eq!(
1550            tags,
1551            vec![(MessageTypeId::Video, 100), (MessageTypeId::Audio, 110)]
1552        );
1553    }
1554
1555    /// RTMP-W6 remainder (#1108): a truncated aggregate (last sub-message
1556    /// claims more data than the body actually carries) must error, not
1557    /// partially deliver or silently drop.
1558    #[test]
1559    fn truncated_aggregate_message_errors() {
1560        let mut session = publishing_session();
1561        let mut body = aggregate_body(&[(MessageTypeId::Video, 0, &[0x17, 0x01, 0xAA])]);
1562        // Chop off the last sub-message's data + back pointer: its header
1563        // now claims 3 data bytes the body no longer has.
1564        body.truncate(body.len() - 5);
1565        let msg = Message {
1566            chunk_stream_id: ChunkStreamId::new(CLIENT_CSID),
1567            timestamp: Timestamp::ZERO,
1568            message_type_id: MessageTypeId::Aggregate,
1569            message_stream_id: MessageStreamId::new(1),
1570            payload: body,
1571        };
1572        let bytes = ChunkWriter::new().write(&msg).unwrap();
1573        let (_out, events) = session
1574            .handle_data(&bytes)
1575            .expect("a truncated aggregate must not end the session");
1576        assert!(
1577            events.iter().any(|e| matches!(
1578                e,
1579                ServerEvent::Damage(d) if d.kind() == broadcast_core::damage::DamageKind::MediaUnitDropped
1580            )),
1581            "a truncated aggregate must be reported, got {events:?}"
1582        );
1583    }
1584
1585    /// A `Back Pointer` that disagrees with the sub-message's actual size
1586    /// is corruption — reject rather than trust it for framing.
1587    #[test]
1588    fn aggregate_with_bad_back_pointer_errors() {
1589        let mut session = publishing_session();
1590        let mut body = aggregate_body(&[(MessageTypeId::Video, 0, &[0x17, 0x01, 0xAA])]);
1591        let back_at = body.len() - 4;
1592        body[back_at] = 0xFF; // corrupt the back pointer
1593        let msg = Message {
1594            chunk_stream_id: ChunkStreamId::new(CLIENT_CSID),
1595            timestamp: Timestamp::ZERO,
1596            message_type_id: MessageTypeId::Aggregate,
1597            message_stream_id: MessageStreamId::new(1),
1598            payload: body,
1599        };
1600        let bytes = ChunkWriter::new().write(&msg).unwrap();
1601        let (_out, events) = session
1602            .handle_data(&bytes)
1603            .expect("a lying Back Pointer must not end the session");
1604        assert!(
1605            events.iter().any(|e| matches!(
1606                e,
1607                ServerEvent::Damage(d) if d.kind() == broadcast_core::damage::DamageKind::MediaUnitDropped
1608            )),
1609            "a lying Back Pointer must be reported, got {events:?}"
1610        );
1611    }
1612
1613    #[test]
1614    fn connect_without_command_object_is_malformed() {
1615        let mut session = ServerSession::new(RtmpServerConfig::default());
1616        session.handle_data(&build_c0_c1()).unwrap();
1617        session.handle_data(&build_c2()).unwrap();
1618
1619        // No arguments at all: arg0 (the command object) is missing.
1620        let err = session.handle_data(&connect_bytes_no_args()).unwrap_err();
1621        assert!(
1622            matches!(err, RtmpError::UnexpectedState { .. }),
1623            "connect with no command-object argument must error, not default app to \"\""
1624        );
1625    }
1626
1627    /// Gap 3 regression test (#738): connect with a command object present
1628    /// but missing the `app` key must be rejected.
1629    #[test]
1630    fn connect_with_object_missing_app_key_is_malformed() {
1631        let mut session = ServerSession::new(RtmpServerConfig::default());
1632        session.handle_data(&build_c0_c1()).unwrap();
1633        session.handle_data(&build_c2()).unwrap();
1634
1635        // Object is present but has no `app` key.
1636        let args = vec![Amf0Value::Object(vec![(
1637            "type".to_string(),
1638            Amf0Value::String("nonprivate".to_string()),
1639        )])];
1640        let msg = command_message(CLIENT_CSID, 0, "connect", 1.0, args);
1641        let bytes = ChunkWriter::new().write(&msg).unwrap();
1642
1643        let err = session.handle_data(&bytes).unwrap_err();
1644        assert!(
1645            matches!(err, RtmpError::UnexpectedState { .. }),
1646            "connect with object missing 'app' key must error"
1647        );
1648    }
1649
1650    /// Gap 3 regression test (#738): connect with a command object present
1651    /// but `app` value is not a String must be rejected.
1652    #[test]
1653    fn connect_with_app_as_number_is_malformed() {
1654        let mut session = ServerSession::new(RtmpServerConfig::default());
1655        session.handle_data(&build_c0_c1()).unwrap();
1656        session.handle_data(&build_c2()).unwrap();
1657
1658        // Object has `app` key but value is a Number, not a String.
1659        let args = vec![Amf0Value::Object(vec![
1660            ("app".to_string(), Amf0Value::Number(123.0)),
1661            (
1662                "type".to_string(),
1663                Amf0Value::String("nonprivate".to_string()),
1664            ),
1665        ])];
1666        let msg = command_message(CLIENT_CSID, 0, "connect", 1.0, args);
1667        let bytes = ChunkWriter::new().write(&msg).unwrap();
1668
1669        let err = session.handle_data(&bytes).unwrap_err();
1670        assert!(
1671            matches!(err, RtmpError::UnexpectedState { .. }),
1672            "connect with app as Number must error, not accept numeric value"
1673        );
1674    }
1675
1676    // ── createStream ──────────────────────────────────────────────────────
1677
1678    #[test]
1679    fn create_stream_replies_result_with_stream_id() {
1680        let mut session = ServerSession::new(RtmpServerConfig::default());
1681        session.handle_data(&build_c0_c1()).unwrap();
1682        session.handle_data(&build_c2()).unwrap();
1683        session.handle_data(&connect_bytes("live")).unwrap();
1684
1685        let (out, _events) = session.handle_data(&create_stream_bytes()).unwrap();
1686        let commands = decode_commands(&out);
1687        let result = commands
1688            .iter()
1689            .find(|c| c.name == "_result")
1690            .expect("createStream _result reply");
1691        assert_eq!(
1692            result.arguments.get(1),
1693            Some(&Amf0Value::Number(1.0)),
1694            "first allocated stream id must be 1"
1695        );
1696    }
1697
1698    #[test]
1699    fn create_stream_before_connect_is_unexpected_state() {
1700        let mut session = ServerSession::new(RtmpServerConfig::default());
1701        session.handle_data(&build_c0_c1()).unwrap();
1702        session.handle_data(&build_c2()).unwrap();
1703
1704        let err = session.handle_data(&create_stream_bytes()).unwrap_err();
1705        assert!(matches!(err, RtmpError::UnexpectedState { .. }));
1706    }
1707
1708    // ── publish ───────────────────────────────────────────────────────────
1709
1710    /// Release audit (CRITICAL): a peer-chosen publishing name of 65 518..=65 535
1711    /// bytes fits the request's AMF0 u16 string prefix but, echoed into the
1712    /// `"<key> is now published."` onStatus description, overflows it. That
1713    /// used to hit `to_bytes().expect(..)` and panic the server remotely.
1714    /// Such a `publish` body is now longer than `ServerLimits::max_command_len` and is
1715    /// rejected before parsing (#2813), so the remote path ends in a typed
1716    /// error even earlier.
1717    #[test]
1718    fn oversized_publish_name_errors_instead_of_panicking() {
1719        for len in [65_518usize, 65_530, 65_535] {
1720            let mut session = ServerSession::new(RtmpServerConfig::default());
1721            session.handle_data(&build_c0_c1()).unwrap();
1722            session.handle_data(&build_c2()).unwrap();
1723            session.handle_data(&connect_bytes("live")).unwrap();
1724            session.handle_data(&create_stream_bytes()).unwrap();
1725            let key = "k".repeat(len);
1726            let err = session
1727                .handle_data(&publish_bytes(1, &key))
1728                .expect_err("an oversized publish command must be an Err");
1729            assert!(
1730                matches!(err, RtmpError::CommandTooLong { .. }),
1731                "len {len}: {err:?}"
1732            );
1733        }
1734    }
1735
1736    #[test]
1737    fn publish_reaches_publishing_emits_event_and_stream_begin_plus_onstatus() {
1738        let (_session, out, events) = publish_flow(RtmpServerConfig::default(), "testkey");
1739
1740        assert!(events.contains(&ServerEvent::Publish {
1741            app: "live".to_string(),
1742            stream_key: "testkey".to_string(),
1743            stream_id: 1,
1744        }));
1745
1746        let messages = decode_messages(&out);
1747        let has_stream_begin = messages.iter().any(|m| {
1748            m.message_type_id == MessageTypeId::UserControl
1749                && matches!(
1750                    UserControl::parse(&m.payload),
1751                    Ok(UserControl::StreamBegin(1))
1752                )
1753        });
1754        assert!(
1755            has_stream_begin,
1756            "publish reply must include StreamBegin(1)"
1757        );
1758
1759        let commands = decode_commands(&out);
1760        let on_status = commands
1761            .iter()
1762            .find(|c| c.name == "onStatus")
1763            .expect("onStatus reply to publish");
1764        assert_eq!(
1765            onstatus_code(on_status).as_deref(),
1766            Some("NetStream.Publish.Start")
1767        );
1768    }
1769
1770    #[test]
1771    fn publish_before_connect_is_unexpected_state() {
1772        let mut session = ServerSession::new(RtmpServerConfig::default());
1773        session.handle_data(&build_c0_c1()).unwrap();
1774        session.handle_data(&build_c2()).unwrap();
1775
1776        let err = session
1777            .handle_data(&publish_bytes(1, "testkey"))
1778            .unwrap_err();
1779        assert!(matches!(err, RtmpError::UnexpectedState { .. }));
1780    }
1781
1782    #[test]
1783    fn publish_without_create_stream_is_unexpected_state() {
1784        let mut session = ServerSession::new(RtmpServerConfig::default());
1785        session.handle_data(&build_c0_c1()).unwrap();
1786        session.handle_data(&build_c2()).unwrap();
1787        session.handle_data(&connect_bytes("live")).unwrap();
1788
1789        // createStream never called: publish must not succeed on app-only.
1790        let err = session
1791            .handle_data(&publish_bytes(1, "testkey"))
1792            .unwrap_err();
1793        assert!(matches!(err, RtmpError::UnexpectedState { .. }));
1794    }
1795
1796    #[test]
1797    fn create_stream_after_closed_is_unexpected_state() {
1798        let mut session = ServerSession::new(RtmpServerConfig::default());
1799        session.handle_data(&build_c0_c1()).unwrap();
1800        session.handle_data(&build_c2()).unwrap();
1801        session.handle_data(&connect_bytes("live")).unwrap();
1802        session.handle_data(&create_stream_bytes()).unwrap();
1803        session.handle_data(&publish_bytes(1, "testkey")).unwrap();
1804
1805        let delete_stream = command_message(
1806            CLIENT_CSID,
1807            1,
1808            "deleteStream",
1809            4.0,
1810            vec![Amf0Value::Null, Amf0Value::Number(1.0)],
1811        );
1812        let (_out, events) = session
1813            .handle_data(&ChunkWriter::new().write(&delete_stream).unwrap())
1814            .unwrap();
1815        assert_eq!(events, vec![ServerEvent::Eof]);
1816
1817        let err = session.handle_data(&create_stream_bytes()).unwrap_err();
1818        assert!(
1819            matches!(err, RtmpError::UnexpectedState { .. }),
1820            "createStream after State::Closed must be rejected, not silently re-allowed"
1821        );
1822    }
1823
1824    // ── Audio/Video → Media / FLV ─────────────────────────────────────────
1825
1826    #[test]
1827    fn audio_and_video_emit_media_first_carries_flv_file_header() {
1828        let (mut session, _out, _events) = publish_flow(RtmpServerConfig::default(), "testkey");
1829
1830        let (_out1, events1) = session
1831            .handle_data(&av_bytes(
1832                1,
1833                MessageTypeId::Audio,
1834                4,
1835                0,
1836                vec![0xAF, 0x01, 0xDE, 0xAD],
1837            ))
1838            .unwrap();
1839        assert_eq!(events1.len(), 1);
1840        let ServerEvent::Media { flv } = &events1[0] else {
1841            panic!("expected Media event");
1842        };
1843        assert!(
1844            flv.starts_with(b"FLV"),
1845            "the first Media event must carry the FLV file header"
1846        );
1847
1848        let (_out2, events2) = session
1849            .handle_data(&av_bytes(
1850                1,
1851                MessageTypeId::Video,
1852                6,
1853                40,
1854                vec![0x17, 0x01, 0x00, 0x00, 0x00, 0xDE, 0xAD, 0xBE, 0xEF],
1855            ))
1856            .unwrap();
1857        assert_eq!(events2.len(), 1);
1858        let ServerEvent::Media { flv } = &events2[0] else {
1859            panic!("expected Media event");
1860        };
1861        assert!(
1862            !flv.starts_with(b"FLV"),
1863            "only the first Media event carries the file header"
1864        );
1865    }
1866
1867    #[test]
1868    fn second_connect_while_publishing_is_rejected_and_media_keeps_flowing() {
1869        let (mut session, _out, _events) = publish_flow(RtmpServerConfig::default(), "testkey");
1870
1871        let err = session.handle_data(&connect_bytes("live")).unwrap_err();
1872        assert!(matches!(err, RtmpError::UnexpectedState { .. }));
1873
1874        let (_out, events) = session
1875            .handle_data(&av_bytes(
1876                1,
1877                MessageTypeId::Audio,
1878                4,
1879                0,
1880                vec![0xAF, 0x01, 0xDE, 0xAD],
1881            ))
1882            .unwrap();
1883        assert!(
1884            events
1885                .iter()
1886                .any(|e| matches!(e, ServerEvent::Media { .. })),
1887            "the rejected connect must not demote the session out of Publishing"
1888        );
1889    }
1890
1891    #[test]
1892    fn concatenated_media_forms_structurally_valid_flv() {
1893        let (mut session, _out, _events) = publish_flow(RtmpServerConfig::default(), "testkey");
1894
1895        let mut flv_stream = Vec::new();
1896        let (_out1, events1) = session
1897            .handle_data(&av_bytes(
1898                1,
1899                MessageTypeId::Audio,
1900                4,
1901                0,
1902                vec![0xAF, 0x01, 1, 2, 3],
1903            ))
1904            .unwrap();
1905        let (_out2, events2) = session
1906            .handle_data(&av_bytes(
1907                1,
1908                MessageTypeId::Video,
1909                6,
1910                33,
1911                vec![0x17, 0x01, 0, 0, 0, 4, 5, 6],
1912            ))
1913            .unwrap();
1914        for e in events1.into_iter().chain(events2) {
1915            if let ServerEvent::Media { flv } = e {
1916                flv_stream.extend(flv);
1917            }
1918        }
1919
1920        // File header (13 bytes): signature/version/flags/data-offset/prevTagSize0.
1921        assert_eq!(&flv_stream[0..3], b"FLV");
1922        assert_eq!(flv_stream[3], 1, "FLV version");
1923        assert_eq!(flv_stream[4], 0b0000_0101, "audio+video TypeFlags");
1924        assert_eq!(
1925            u32::from_be_bytes(flv_stream[5..9].try_into().unwrap()),
1926            9,
1927            "DataOffset (header size)"
1928        );
1929        assert_eq!(
1930            u32::from_be_bytes(flv_stream[9..13].try_into().unwrap()),
1931            0,
1932            "PreviousTagSize0"
1933        );
1934
1935        // First tag (audio): TagType=8, DataSize=5.
1936        let tag1 = &flv_stream[13..];
1937        assert_eq!(tag1[0], MessageTypeId::Audio.to_u8());
1938        let data_size1 =
1939            (u32::from(tag1[1]) << 16) | (u32::from(tag1[2]) << 8) | u32::from(tag1[3]);
1940        assert_eq!(data_size1, 5);
1941        let tag1_total = FLV_TAG_HEADER_LEN + 5 + FLV_PREV_TAG_SIZE_LEN;
1942        let prev_tag_size1 = u32::from_be_bytes(
1943            flv_stream[13 + tag1_total - 4..13 + tag1_total]
1944                .try_into()
1945                .unwrap(),
1946        );
1947        assert_eq!(prev_tag_size1 as usize, FLV_TAG_HEADER_LEN + 5);
1948
1949        // Second tag (video) immediately follows.
1950        let tag2 = &flv_stream[13 + tag1_total..];
1951        assert_eq!(tag2[0], MessageTypeId::Video.to_u8());
1952        let data_size2 =
1953            (u32::from(tag2[1]) << 16) | (u32::from(tag2[2]) << 8) | u32::from(tag2[3]);
1954        assert_eq!(data_size2, 8);
1955        assert_eq!(
1956            flv_stream.len(),
1957            13 + tag1_total + FLV_TAG_HEADER_LEN + 8 + FLV_PREV_TAG_SIZE_LEN
1958        );
1959    }
1960
1961    #[test]
1962    fn data_amf0_onmetadata_emits_media_with_script_tag_type() {
1963        let (mut session, _out, _events) = publish_flow(RtmpServerConfig::default(), "testkey");
1964
1965        // A representative onMetadata Data-AMF0 payload: handler-name
1966        // string followed by a properties object (§7.1's Data Message
1967        // shape), same as e.g. width/height/framerate metadata a real
1968        // encoder sends.
1969        let mut payload = Amf0Value::String("onMetaData".to_string())
1970            .try_to_bytes()
1971            .unwrap();
1972        payload.extend(
1973            Amf0Value::Object(vec![
1974                ("width".to_string(), Amf0Value::Number(1920.0)),
1975                ("height".to_string(), Amf0Value::Number(1080.0)),
1976            ])
1977            .try_to_bytes()
1978            .unwrap(),
1979        );
1980
1981        let (_out, events) = session
1982            .handle_data(&av_bytes(1, MessageTypeId::DataAmf0, 4, 0, payload))
1983            .unwrap();
1984
1985        assert_eq!(events.len(), 1);
1986        let ServerEvent::Media { flv } = &events[0] else {
1987            panic!("expected Media event");
1988        };
1989        assert!(
1990            flv.starts_with(b"FLV"),
1991            "the first Media event must carry the FLV file header"
1992        );
1993        let tag_type = flv[FLV_HEADER_LEN + FLV_PREV_TAG_SIZE_LEN];
1994        assert_eq!(
1995            tag_type,
1996            MessageTypeId::DataAmf0.to_u8(),
1997            "Data-AMF0 message must produce a script(18) FLV tag"
1998        );
1999    }
2000
2001    #[test]
2002    fn set_data_frame_prefix_is_stripped_from_the_script_tag() {
2003        let (mut session, _out, _events) = publish_flow(RtmpServerConfig::default(), "testkey");
2004        let mut payload = Amf0Value::String("@setDataFrame".to_string())
2005            .try_to_bytes()
2006            .unwrap();
2007        let metadata = Amf0Value::String("onMetaData".to_string())
2008            .try_to_bytes()
2009            .unwrap();
2010        payload.extend(&metadata);
2011        payload.extend(
2012            Amf0Value::Object(vec![("width".to_string(), Amf0Value::Number(1920.0))])
2013                .try_to_bytes()
2014                .unwrap(),
2015        );
2016
2017        let (_out, events) = session
2018            .handle_data(&av_bytes(1, MessageTypeId::DataAmf0, 4, 0, payload))
2019            .unwrap();
2020        let ServerEvent::Media { flv } = &events[0] else {
2021            panic!("expected Media event");
2022        };
2023        let body_at = FLV_HEADER_LEN + FLV_PREV_TAG_SIZE_LEN + FLV_TAG_HEADER_LEN;
2024        assert_eq!(
2025            &flv[body_at..body_at + metadata.len()],
2026            metadata.as_slice(),
2027            "the script tag must start with the onMetaData name, not @setDataFrame"
2028        );
2029    }
2030
2031    #[test]
2032    fn media_before_publishing_is_silently_dropped() {
2033        let mut session = ServerSession::new(RtmpServerConfig::default());
2034        session.handle_data(&build_c0_c1()).unwrap();
2035        session.handle_data(&build_c2()).unwrap();
2036        session.handle_data(&connect_bytes("live")).unwrap();
2037        session.handle_data(&create_stream_bytes()).unwrap();
2038
2039        // publish never called: state is Connected, not Publishing. The
2040        // media belongs to no published stream, so it is dropped — and
2041        // reported, so a publisher is not left believing it went out.
2042        let (_out, events) = session
2043            .handle_data(&av_bytes(1, MessageTypeId::Audio, 4, 0, vec![0xAF, 0x01]))
2044            .unwrap();
2045        assert_eq!(events.len(), 1, "{events:?}");
2046        assert!(matches!(
2047            &events[0],
2048            ServerEvent::Damage(d)
2049                if d.kind() == broadcast_core::damage::DamageKind::MediaUnitDropped
2050                    && d.severity() == broadcast_core::damage::Severity::Informational
2051        ));
2052    }
2053
2054    // ── expected_stream_key mismatch ──────────────────────────────────────
2055
2056    #[test]
2057    fn stream_key_mismatch_suppresses_publish_and_media_events() {
2058        let config = RtmpServerConfig {
2059            expected_stream_key: Some("rightkey".to_string()),
2060            ..RtmpServerConfig::default()
2061        };
2062        let (mut session, out, events) = publish_flow(config, "wrongkey");
2063
2064        assert!(
2065            !events
2066                .iter()
2067                .any(|e| matches!(e, ServerEvent::Publish { .. })),
2068            "mismatched stream key must not emit Publish"
2069        );
2070
2071        let commands = decode_commands(&out);
2072        let on_status = commands
2073            .iter()
2074            .find(|c| c.name == "onStatus")
2075            .expect("onStatus reply on mismatch");
2076        assert_eq!(
2077            onstatus_code(on_status).as_deref(),
2078            Some("NetStream.Publish.BadName")
2079        );
2080
2081        // Session never entered Publishing: subsequent A/V produces no Media,
2082        // only the report that it was dropped.
2083        let (_out2, events2) = session
2084            .handle_data(&av_bytes(1, MessageTypeId::Audio, 4, 0, vec![0xAF, 0x01]))
2085            .unwrap();
2086        assert!(
2087            !events2
2088                .iter()
2089                .any(|e| matches!(e, ServerEvent::Media { .. })),
2090            "no Media may be emitted after a rejected publish"
2091        );
2092        assert_eq!(events2.len(), 1, "{events2:?}");
2093        assert!(matches!(&events2[0], ServerEvent::Damage(_)));
2094    }
2095
2096    #[test]
2097    fn stream_key_match_still_publishes_with_key_configured() {
2098        let config = RtmpServerConfig {
2099            expected_stream_key: Some("rightkey".to_string()),
2100            ..RtmpServerConfig::default()
2101        };
2102        let (_session, _out, events) = publish_flow(config, "rightkey");
2103        assert!(
2104            events.contains(&ServerEvent::Publish {
2105                app: "live".to_string(),
2106                stream_key: "rightkey".to_string(),
2107                stream_id: 1,
2108            }),
2109            "a stream key matching expected_stream_key must still publish"
2110        );
2111    }
2112
2113    #[test]
2114    fn too_many_failed_publish_attempts_closes_the_session() {
2115        let config = RtmpServerConfig {
2116            expected_stream_key: Some("rightkey".to_string()),
2117            ..RtmpServerConfig::default()
2118        };
2119        let mut session = ServerSession::new(config);
2120        session.handle_data(&build_c0_c1()).unwrap();
2121        session.handle_data(&build_c2()).unwrap();
2122        session.handle_data(&connect_bytes("live")).unwrap();
2123        session.handle_data(&create_stream_bytes()).unwrap();
2124
2125        for attempt in 1..=MAX_FAILED_PUBLISH_ATTEMPTS {
2126            let (_out, events) = session.handle_data(&publish_bytes(1, "wrongkey")).unwrap_or_else(|e| {
2127                panic!("attempt {attempt} of {MAX_FAILED_PUBLISH_ATTEMPTS} must still be rejected, not error out: {e}")
2128            });
2129            assert!(
2130                !events
2131                    .iter()
2132                    .any(|e| matches!(e, ServerEvent::Publish { .. })),
2133                "attempt {attempt} must not publish"
2134            );
2135        }
2136
2137        // The attempt beyond MAX_FAILED_PUBLISH_ATTEMPTS must end the
2138        // session instead of replying BadName again.
2139        let err = session
2140            .handle_data(&publish_bytes(1, "wrongkey"))
2141            .expect_err("the attempt beyond MAX_FAILED_PUBLISH_ATTEMPTS must close the session");
2142        assert!(matches!(err, RtmpError::UnexpectedState { .. }));
2143
2144        // The session stays closed even for the correct key.
2145        let err = session
2146            .handle_data(&publish_bytes(1, "rightkey"))
2147            .expect_err(
2148                "publish must be rejected once the session was closed for too many failures",
2149            );
2150        assert!(matches!(err, RtmpError::UnexpectedState { .. }));
2151    }
2152
2153    #[test]
2154    fn constant_time_eq_matches_naive_equality() {
2155        assert!(constant_time_eq(b"rightkey", b"rightkey"));
2156        assert!(!constant_time_eq(b"rightkey", b"wrongkey"));
2157        assert!(!constant_time_eq(b"short", b"muchlonger"));
2158        assert!(constant_time_eq(b"", b""));
2159    }
2160
2161    // ── Ack accounting ────────────────────────────────────────────────────
2162
2163    #[test]
2164    fn ack_written_once_window_ack_size_is_crossed() {
2165        let config = RtmpServerConfig {
2166            window_ack_size: 32,
2167            ..RtmpServerConfig::default()
2168        };
2169        let mut session = ServerSession::new(config);
2170        session.handle_data(&build_c0_c1()).unwrap();
2171        session.handle_data(&build_c2()).unwrap();
2172
2173        // connect's chunk-encoded bytes comfortably exceed 32 bytes.
2174        let (out, _events) = session.handle_data(&connect_bytes("live")).unwrap();
2175        let messages = decode_messages(&out);
2176        let has_ack = messages.iter().any(|m| {
2177            matches!(
2178                ProtocolControl::from_message(m),
2179                Ok(Some(ProtocolControl::Acknowledgement(_)))
2180            )
2181        });
2182        assert!(
2183            has_ack,
2184            "crossing window_ack_size must produce an Acknowledgement"
2185        );
2186    }
2187
2188    #[test]
2189    fn no_ack_below_window_ack_size() {
2190        let config = RtmpServerConfig {
2191            window_ack_size: 10_000_000,
2192            ..RtmpServerConfig::default()
2193        };
2194        let mut session = ServerSession::new(config);
2195        session.handle_data(&build_c0_c1()).unwrap();
2196        let (out, _events) = session.handle_data(&build_c2()).unwrap();
2197        let messages = decode_messages(&out);
2198        assert!(
2199            !messages.iter().any(|m| matches!(
2200                ProtocolControl::from_message(m),
2201                Ok(Some(ProtocolControl::Acknowledgement(_)))
2202            )),
2203            "no Acknowledgement should be due yet"
2204        );
2205    }
2206
2207    // ── Garbage / truncated input never panics ────────────────────────────
2208
2209    #[test]
2210    fn garbage_command_payload_after_handshake_is_error_not_panic() {
2211        let mut session = ServerSession::new(RtmpServerConfig::default());
2212        session.handle_data(&build_c0_c1()).unwrap();
2213        session.handle_data(&build_c2()).unwrap();
2214
2215        // A structurally valid chunk envelope (Type0 header, Command-AMF0
2216        // type id) whose payload is not valid AMF0 (0xFF is not a defined
2217        // AMF0 marker) — Command::parse must reject this, not panic.
2218        let bogus = Message {
2219            chunk_stream_id: ChunkStreamId::new(CLIENT_CSID),
2220            timestamp: Timestamp::ZERO,
2221            message_type_id: MessageTypeId::CommandAmf0,
2222            message_stream_id: MessageStreamId::new(0),
2223            payload: vec![0xFF, 0xFF, 0xFF, 0xFF],
2224        };
2225        let bytes = ChunkWriter::new().write(&bogus).unwrap();
2226        let err = session.handle_data(&bytes).unwrap_err();
2227        assert!(matches!(
2228            err,
2229            RtmpError::UnsupportedAmf0Marker { .. }
2230                | RtmpError::Malformed { .. }
2231                | RtmpError::BufferTooShort(..)
2232        ));
2233    }
2234
2235    /// #2813: a Command Message body is decoded into a full AMF0 value tree
2236    /// before any state-machine check (including the `connect` stream-key
2237    /// gate), on any connection, before authentication. A body over
2238    /// `ServerLimits::max_command_len` is now rejected before that parse.
2239    #[test]
2240    fn command_body_over_the_length_cap_is_rejected_before_amf0_parsing() {
2241        for message_type_id in [MessageTypeId::CommandAmf0, MessageTypeId::CommandAmf3] {
2242            let mut session = ServerSession::new(RtmpServerConfig::default());
2243            session.handle_data(&build_c0_c1()).unwrap();
2244            session.handle_data(&build_c2()).unwrap();
2245
2246            let oversized = Message {
2247                chunk_stream_id: ChunkStreamId::new(CLIENT_CSID),
2248                timestamp: Timestamp::ZERO,
2249                message_type_id,
2250                message_stream_id: MessageStreamId::new(0),
2251                payload: vec![crate::amf0::marker::NULL; MAX_COMMAND_LEN + 1],
2252            };
2253            let bytes = ChunkWriter::new().write(&oversized).unwrap();
2254            let err = session.handle_data(&bytes).unwrap_err();
2255            assert!(matches!(
2256                err,
2257                RtmpError::CommandTooLong { len, max }
2258                    if len == MAX_COMMAND_LEN + 1 && max == MAX_COMMAND_LEN
2259            ));
2260        }
2261    }
2262
2263    #[test]
2264    fn truncated_post_handshake_bytes_do_not_panic() {
2265        let mut session = ServerSession::new(RtmpServerConfig::default());
2266        session.handle_data(&build_c0_c1()).unwrap();
2267        session.handle_data(&build_c2()).unwrap();
2268
2269        // A handful of arbitrary bytes with no complete chunk in them.
2270        let (out, events) = session.handle_data(&[0x03, 0x01, 0x02]).unwrap();
2271        assert!(out.is_empty());
2272        assert!(events.is_empty());
2273    }
2274
2275    // ── Mutation-check sentinels ──────────────────────────────────────────
2276
2277    #[test]
2278    fn mutation_check_publish_event_must_echo_actual_stream_key() {
2279        let (_session, _out, events) =
2280            publish_flow(RtmpServerConfig::default(), "specific-key-xyz");
2281        let publish_event = events
2282            .iter()
2283            .find_map(|e| match e {
2284                ServerEvent::Publish { stream_key, .. } => Some(stream_key.clone()),
2285                _ => None,
2286            })
2287            .expect("Publish event");
2288        assert_eq!(
2289            publish_event, "specific-key-xyz",
2290            "a hardcoded/ignored stream_key would fail this"
2291        );
2292    }
2293
2294    #[test]
2295    fn mutation_check_flv_file_header_bytes_are_exact() {
2296        let header = FlvHeader::new(true, true).try_to_bytes().unwrap();
2297        assert_eq!(
2298            header,
2299            vec![
2300                b'F',
2301                b'L',
2302                b'V',        // Signature
2303                1,           // Version
2304                0b0000_0101, // TypeFlags: audio + video
2305                0,
2306                0,
2307                0,
2308                9, // DataOffset = 9
2309                0,
2310                0,
2311                0,
2312                0, // PreviousTagSize0 = 0
2313            ]
2314        );
2315    }
2316
2317    // ── Regression: client Set Chunk Size mid-buffer (#738 Task 8) ────────
2318
2319    #[test]
2320    fn client_set_chunk_size_takes_effect_before_next_message_in_same_call() {
2321        // Reproduces the exact bug a real `ffmpeg` publish surfaced: the
2322        // client sends its own SetChunkSize (as ffmpeg does, right after
2323        // `connect`) and, in the very same TCP segment / `handle_data` call,
2324        // the next message is already framed at the *new* chunk size. If
2325        // `ServerSession` collected a whole batch of messages from one
2326        // `ChunkAssembler::push` before dispatching any of them (applying
2327        // SetChunkSize's effect only afterwards), that next message would
2328        // be misparsed under the *old* chunk size.
2329        let (mut session, _out, _events) = publish_flow(RtmpServerConfig::default(), "testkey");
2330
2331        let new_chunk_size = ChunkSize::new(4096).expect("a valid chunk size");
2332        let set_chunk_size_bytes = ChunkWriter::new()
2333            .write(&ProtocolControl::SetChunkSize(new_chunk_size).to_message())
2334            .unwrap();
2335
2336        // A video payload bigger than the *default* 128-byte chunk size but
2337        // written by a client-side writer already using the new size, so it
2338        // lands as a single physical chunk — the shape a real client
2339        // produces immediately after raising its chunk size.
2340        let big_payload = vec![0x17u8; 300];
2341        let mut client_writer = ChunkWriter::new();
2342        client_writer.set_chunk_size(new_chunk_size);
2343        let video_bytes = client_writer
2344            .write(&Message {
2345                chunk_stream_id: ChunkStreamId::new(6),
2346                timestamp: Timestamp::ZERO,
2347                message_type_id: MessageTypeId::Video,
2348                message_stream_id: MessageStreamId::new(1),
2349                payload: big_payload.clone(),
2350            })
2351            .unwrap();
2352
2353        let mut combined = set_chunk_size_bytes;
2354        combined.extend_from_slice(&video_bytes);
2355
2356        // Both messages arrive in a single `handle_data` call: this is the
2357        // exact shape that broke before the incremental-dispatch fix.
2358        let (_out, events) = session.handle_data(&combined).expect(
2359            "SetChunkSize must take effect before parsing the message that follows it \
2360                     in the same handle_data call, not only on a subsequent call",
2361        );
2362
2363        let media = events
2364            .iter()
2365            .find_map(|e| match e {
2366                ServerEvent::Media { flv } => Some(flv.clone()),
2367                _ => None,
2368            })
2369            .expect("the video message must still be parsed into a Media event");
2370        assert!(
2371            media
2372                .windows(big_payload.len())
2373                .any(|w| w == big_payload.as_slice()),
2374            "the video payload must survive intact through the chunk-size change"
2375        );
2376    }
2377
2378    /// #2741: a peer that announces a chunk size above the caller's ceiling
2379    /// used to be accepted with the size silently clamped to
2380    /// the ceiling; the session then parsed the peer's next chunks at a
2381    /// size the peer never used, mis-framing the rest of the stream with no
2382    /// signal. The announcement is now refused, so the session closes with
2383    /// an error naming the field instead of corrupting what follows.
2384    #[test]
2385    fn an_announced_chunk_size_above_the_engine_ceiling_is_refused_not_clamped() {
2386        let (mut session, _out, _events) = publish_flow(RtmpServerConfig::default(), "testkey");
2387        let above_ceiling = MAX_CHUNK_SIZE + 1;
2388        assert!(
2389            ChunkSize::new(above_ceiling).is_ok(),
2390            "the announced value must be a legal wire size the caller's ceiling refuses"
2391        );
2392        let payload = above_ceiling.to_be_bytes().to_vec();
2393        let announcement = Message {
2394            chunk_stream_id: CTRL_CSID,
2395            timestamp: Timestamp::ZERO,
2396            message_type_id: MessageTypeId::SetChunkSize,
2397            message_stream_id: MessageStreamId::new(0),
2398            payload,
2399        };
2400        let bytes = ChunkWriter::new().write(&announcement).unwrap();
2401        let err = session
2402            .handle_data(&bytes)
2403            .expect_err("a chunk size above the engine ceiling must be refused");
2404        assert!(
2405            matches!(
2406                err,
2407                RtmpError::ChunkSizeOutOfRange { value } if value == MAX_CHUNK_SIZE + 1
2408            ),
2409            "{err:?}"
2410        );
2411    }
2412
2413    /// #1108 incremental dispatch, carried over once the announcement is its
2414    /// own message: a Set Chunk Size and the chunks framed at the new size in
2415    /// the same `handle_data` call must be parsed at the new size, with
2416    /// nothing parsed twice on either side of the change.
2417    #[test]
2418    fn a_chunk_size_announced_at_the_ceiling_takes_effect_within_the_same_call() {
2419        let (mut session, _out, _events) = publish_flow(RtmpServerConfig::default(), "testkey");
2420        let ceiling = ChunkSize::new(MAX_CHUNK_SIZE).expect("the ceiling is a valid size");
2421        let announcement = ProtocolControl::SetChunkSize(ceiling).to_message();
2422        let mut combined = ChunkWriter::new().write(&announcement).unwrap();
2423
2424        let payload = vec![0x17u8; 300];
2425        let mut client_writer = ChunkWriter::new();
2426        client_writer.set_chunk_size(ceiling);
2427        combined.extend_from_slice(
2428            &client_writer
2429                .write(&Message {
2430                    chunk_stream_id: ChunkStreamId::new(6),
2431                    timestamp: Timestamp::ZERO,
2432                    message_type_id: MessageTypeId::Video,
2433                    message_stream_id: MessageStreamId::new(1),
2434                    payload: payload.clone(),
2435                })
2436                .unwrap(),
2437        );
2438
2439        let (_out, events) = session
2440            .handle_data(&combined)
2441            .expect("the announcement and the chunks framed after it parse in one call");
2442        let media = events
2443            .iter()
2444            .find_map(|e| match e {
2445                ServerEvent::Media { flv } => Some(flv.clone()),
2446                _ => None,
2447            })
2448            .expect("the video message is parsed into a Media event exactly once");
2449        assert!(media.windows(payload.len()).any(|w| w == payload));
2450    }
2451
2452    #[test]
2453    fn control_chunk_stream_id_constant_matches_message_module() {
2454        // Sanity: our reply csid choice for command messages must not
2455        // collide with the reserved control/user-control csid.
2456        assert_ne!(COMMAND_CHUNK_STREAM_ID, CTRL_CSID.get());
2457    }
2458
2459    #[test]
2460    fn next_stream_id_saturates_instead_of_overflowing() {
2461        // Mutation check: with `next_stream_id` already at `u32::MAX`, a
2462        // bare `+= 1` panics (debug-mode overflow check) or wraps to 0
2463        // (release mode) — either way, the wrong behaviour. `saturating_add`
2464        // must instead keep it pinned at `u32::MAX`.
2465        let mut session = ServerSession::new(RtmpServerConfig::default());
2466        session.handle_data(&build_c0_c1()).unwrap();
2467        session.handle_data(&build_c2()).unwrap();
2468        session.handle_data(&connect_bytes("live")).unwrap();
2469
2470        session.next_stream_id = u32::MAX;
2471        let (out, _events) = session
2472            .handle_data(&create_stream_bytes())
2473            .expect("createStream must not panic when next_stream_id is already u32::MAX");
2474
2475        let commands = decode_commands(&out);
2476        let result = commands
2477            .iter()
2478            .find(|c| c.name == "_result")
2479            .expect("createStream _result reply");
2480        assert_eq!(
2481            result.arguments.get(1),
2482            Some(&Amf0Value::Number(f64::from(u32::MAX))),
2483            "the stream id allocated at the u32::MAX boundary must still be u32::MAX"
2484        );
2485        assert_eq!(
2486            session.next_stream_id,
2487            u32::MAX,
2488            "next_stream_id must saturate at u32::MAX, not wrap to 0"
2489        );
2490    }
2491
2492    // ── serde (feature "serde") ────────────────────────────────────────────
2493
2494    #[cfg(feature = "serde")]
2495    #[test]
2496    fn server_config_and_server_event_serde_round_trip() {
2497        let config = RtmpServerConfig::default()
2498            .with_chunk_size(8192)
2499            .with_expected_stream_key(Some("k".to_string()));
2500        let json = serde_json::to_string(&config).expect("serialize RtmpServerConfig");
2501        let value: serde_json::Value = serde_json::from_str(&json).expect("valid JSON");
2502        assert_eq!(value["chunk_size"], serde_json::json!(8192));
2503        assert_eq!(value["expected_stream_key"], serde_json::json!("k"));
2504
2505        // The event itself is write-only (see `ServerEvent`'s doc): its
2506        // `Damage` arm cannot be reconstructed, so the shape is what is
2507        // asserted rather than a round trip.
2508        let event = ServerEvent::Publish {
2509            app: "live".to_string(),
2510            stream_key: "testkey".to_string(),
2511            stream_id: 1,
2512        };
2513        let json = serde_json::to_string(&event).expect("serialize ServerEvent");
2514        let shape: serde_json::Value = serde_json::from_str(&json).expect("valid JSON");
2515        assert_eq!(shape["Publish"]["app"], serde_json::json!("live"));
2516        assert_eq!(shape["Publish"]["stream_id"], serde_json::json!(1));
2517    }
2518}