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