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