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