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