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 = ProtocolControl::SetChunkSize(self.config.chunk_size).to_message();
647        out.extend_from_slice(&self.writer.write(&set_chunk_size)?);
648        self.writer.set_chunk_size(self.config.chunk_size);
649
650        let result = Command {
651            name: "_result".to_string(),
652            transaction_id: command.transaction_id,
653            arguments: vec![
654                Amf0Value::Object(vec![
655                    (
656                        "fmsVer".to_string(),
657                        Amf0Value::String(FMS_VERSION.to_string()),
658                    ),
659                    ("capabilities".to_string(), Amf0Value::Number(CAPABILITIES)),
660                ]),
661                Amf0Value::Object(vec![
662                    ("level".to_string(), Amf0Value::String("status".to_string())),
663                    (
664                        "code".to_string(),
665                        Amf0Value::String("NetConnection.Connect.Success".to_string()),
666                    ),
667                    (
668                        "description".to_string(),
669                        Amf0Value::String("Connection succeeded.".to_string()),
670                    ),
671                ]),
672            ],
673        };
674        out.extend_from_slice(&self.writer.write(&self.command_message(msg, &result)?)?);
675
676        events.push(ServerEvent::Connected { app });
677        Ok(())
678    }
679
680    /// `createStream` (§7.2.2, `NetConnection`): allocate a message stream
681    /// id, reply `_result` with it.
682    ///
683    /// # Errors
684    /// [`RtmpError::UnexpectedState`] unless `state == State::Connected` —
685    /// this rejects `createStream` before a successful `connect`, and also
686    /// after [`State::Closed`] (post-`deleteStream`/`FCUnpublish`).
687    fn handle_create_stream(
688        &mut self,
689        command: &Command,
690        msg: &Message,
691        out: &mut Vec<u8>,
692    ) -> Result<()> {
693        if self.state != State::Connected {
694            return Err(RtmpError::UnexpectedState {
695                what: "createStream received before a successful connect (or after the session was closed)",
696            });
697        }
698
699        let stream_id = self.next_stream_id;
700        self.next_stream_id = self.next_stream_id.saturating_add(1);
701        self.created_stream_id = Some(stream_id);
702
703        let result = Command {
704            name: "_result".to_string(),
705            transaction_id: command.transaction_id,
706            arguments: vec![Amf0Value::Null, Amf0Value::Number(f64::from(stream_id))],
707        };
708        out.extend_from_slice(&self.writer.write(&self.command_message(msg, &result)?)?);
709        Ok(())
710    }
711
712    /// `publish` (§7.2.2.6, `NetStream`): capture the stream key, enforce
713    /// `expected_stream_key` if configured, reply StreamBegin + `onStatus`,
714    /// transition to [`State::Publishing`], emit [`ServerEvent::Publish`].
715    ///
716    /// # Errors
717    /// [`RtmpError::UnexpectedState`] unless `state == State::Connected`
718    /// *and* a stream was actually allocated by a preceding `createStream`
719    /// (`created_stream_id.is_some()`) — this rejects `publish` before
720    /// `connect`, `publish` before `createStream`, and `publish` after
721    /// [`State::Closed`]. Also [`RtmpError::UnexpectedState`] once this
722    /// connection has already exhausted [`MAX_FAILED_PUBLISH_ATTEMPTS`]
723    /// mismatched-key attempts — the session is closed at that point and the
724    /// caller must not keep driving it (see [`ServerSession::handle_data`]).
725    fn handle_publish(
726        &mut self,
727        command: &Command,
728        msg: &Message,
729        out: &mut Vec<u8>,
730        events: &mut Vec<ServerEvent>,
731    ) -> Result<()> {
732        if self.state != State::Connected || self.created_stream_id.is_none() {
733            return Err(RtmpError::UnexpectedState {
734                what: "publish received before a successful connect+createStream (or after the session was closed)",
735            });
736        }
737        if self.failed_publish_attempts >= MAX_FAILED_PUBLISH_ATTEMPTS {
738            self.state = State::Closed;
739            return Err(RtmpError::UnexpectedState {
740                what: "publish rejected too many times on this connection (stream key mismatch); session closed",
741            });
742        }
743        let app = self
744            .app
745            .clone()
746            .expect("state == Connected implies app was captured by connect");
747
748        let stream_key = match command.arguments.get(1) {
749            Some(Amf0Value::String(s)) => s.clone(),
750            _ => {
751                return Err(RtmpError::Malformed {
752                    what: "publish command missing its publishing-name (string) argument",
753                });
754            }
755        };
756        let stream_id = msg.message_stream_id;
757
758        if let Some(expected) = &self.config.expected_stream_key
759            && !constant_time_eq(expected.as_bytes(), stream_key.as_bytes())
760        {
761            self.failed_publish_attempts += 1;
762            let on_status = Command {
763                name: "onStatus".to_string(),
764                transaction_id: 0.0,
765                arguments: vec![
766                    Amf0Value::Null,
767                    Amf0Value::Object(vec![
768                        ("level".to_string(), Amf0Value::String("error".to_string())),
769                        (
770                            "code".to_string(),
771                            Amf0Value::String("NetStream.Publish.BadName".to_string()),
772                        ),
773                        (
774                            "description".to_string(),
775                            Amf0Value::String("Stream key mismatch.".to_string()),
776                        ),
777                    ]),
778                ],
779            };
780            out.extend_from_slice(&self.writer.write(&self.command_message(msg, &on_status)?)?);
781            // No Publish/Media events; state unchanged (not Publishing).
782            return Ok(());
783        }
784
785        let stream_begin = UserControl::StreamBegin(stream_id).to_message();
786        out.extend_from_slice(&self.writer.write(&stream_begin)?);
787
788        let on_status = Command {
789            name: "onStatus".to_string(),
790            transaction_id: 0.0,
791            arguments: vec![
792                Amf0Value::Null,
793                Amf0Value::Object(vec![
794                    ("level".to_string(), Amf0Value::String("status".to_string())),
795                    (
796                        "code".to_string(),
797                        Amf0Value::String("NetStream.Publish.Start".to_string()),
798                    ),
799                    (
800                        "description".to_string(),
801                        Amf0Value::String(format!("{stream_key} is now published.")),
802                    ),
803                ]),
804            ],
805        };
806        out.extend_from_slice(&self.writer.write(&self.command_message(msg, &on_status)?)?);
807
808        self.state = State::Publishing;
809        events.push(ServerEvent::Publish {
810            app,
811            stream_key,
812            stream_id,
813        });
814        Ok(())
815    }
816
817    /// Reply a benign `_result` command echoing `command`'s transaction id
818    /// (used for the OBS extras `releaseStream`/`FCPublish`, which never
819    /// error even when tolerated rather than fully implemented).
820    fn reply_result(
821        &mut self,
822        command: &Command,
823        msg: &Message,
824        arguments: Vec<Amf0Value>,
825        out: &mut Vec<u8>,
826    ) -> Result<()> {
827        let result = Command {
828            name: "_result".to_string(),
829            transaction_id: command.transaction_id,
830            arguments,
831        };
832        out.extend_from_slice(&self.writer.write(&self.command_message(msg, &result)?)?);
833        Ok(())
834    }
835
836    /// Wrap `command` in a [`Message`] on [`COMMAND_CHUNK_STREAM_ID`],
837    /// echoing `request`'s message stream id (replies travel back on the
838    /// same `NetConnection`/`NetStream` channel the request arrived on).
839    fn command_message(&self, request: &Message, command: &Command) -> Result<Message> {
840        Ok(Message {
841            chunk_stream_id: COMMAND_CHUNK_STREAM_ID,
842            timestamp: 0,
843            message_type_id: msg_type::COMMAND_AMF0,
844            message_stream_id: request.message_stream_id,
845            payload: command.to_body()?,
846        })
847    }
848
849    /// Convert an Audio(8)/Video(9)/Data-AMF0(18) message to an FLV tag and
850    /// emit it as [`ServerEvent::Media`], but only while
851    /// [`State::Publishing`] (messages arriving before `publish` succeeds,
852    /// or after a stream-key mismatch, are silently dropped — no event).
853    fn emit_media_if_publishing(
854        &mut self,
855        tag_type: u8,
856        timestamp: u32,
857        payload: &[u8],
858        events: &mut Vec<ServerEvent>,
859    ) -> Result<()> {
860        if self.state != State::Publishing {
861            return Ok(());
862        }
863
864        let mut flv = if self.flv_header_sent {
865            Vec::new()
866        } else {
867            self.flv_header_sent = true;
868            flv_file_header()
869        };
870        flv.extend(flv_tag(tag_type, timestamp, payload)?);
871        events.push(ServerEvent::Media { flv });
872        Ok(())
873    }
874
875    /// Unpack an Aggregate Message (22, §7.1.6) and deliver each contained
876    /// sub-message exactly as an ordinary Audio/Video/Data-AMF0 message
877    /// would be delivered.
878    ///
879    /// Sub-message layout (§7.1.6, identical to the FLV tag layout of
880    /// Adobe FLV v10.1 Annex E.4.1/E.5): `Type`(1) + `DataSize`(3) +
881    /// `Timestamp`(3) + `TimestampExtended`(1) + `StreamID`(3, always 0) +
882    /// `Data` + `Back Pointer`(4). Per §7.1.6 the aggregate's own message
883    /// stream id overrides every sub-message's, and sub-message timestamps
884    /// are renormalized by `offset = aggregate ts − first sub-message ts`
885    /// added to each sub-message timestamp (the first sub-message's
886    /// timestamp SHOULD equal the aggregate's, making the offset 0).
887    ///
888    /// A sub-message header or `DataSize`-claimed data run reaching past
889    /// the end of the aggregate body is rejected with `Malformed` rather
890    /// than partially delivered.
891    ///
892    /// # Errors
893    /// [`RtmpError::Malformed`] on a truncated header/data/`Back Pointer`,
894    /// or a `Back Pointer` that disagrees with the sub-message's actual
895    /// size. [`RtmpError::Unsupported`] (via [`flv_tag`]) for a
896    /// sub-message payload too large for the FLV tag's 24-bit `DataSize`.
897    fn deliver_aggregate(&mut self, msg: &Message, events: &mut Vec<ServerEvent>) -> Result<()> {
898        let body = &msg.payload;
899        let mut first_ts: Option<u32> = None;
900        let mut offset = 0usize;
901        while offset < body.len() {
902            if body.len() - offset < AGG_SUB_MESSAGE_HEADER_LEN {
903                return Err(RtmpError::Malformed {
904                    what: "aggregate sub-message header truncated",
905                });
906            }
907            let header = &body[offset..offset + AGG_SUB_MESSAGE_HEADER_LEN];
908            let tag_type = header[0];
909            let data_size = u32::from_be_bytes([0, header[1], header[2], header[3]]) as usize;
910            let ts_low24 = u32::from_be_bytes([0, header[4], header[5], header[6]]);
911            // Same layout `flv_tag` writes (Annex E.4.1): the 24-bit
912            // `Timestamp` field holds bits 0..=23, `TimestampExtended`
913            // holds the top 8.
914            let raw_ts = ts_low24 | (u32::from(header[7]) << AGG_TIMESTAMP_EXTENDED_SHIFT);
915            // header[8..11] is the sub-message `StreamID` (always 0):
916            // §7.1.6 says the aggregate's own message stream id overrides
917            // every sub-message's stream id anyway, so it is ignored.
918            let data_start = offset + AGG_SUB_MESSAGE_HEADER_LEN;
919            let Some(data_end) = data_size.checked_add(data_start) else {
920                return Err(RtmpError::Malformed {
921                    what: "aggregate sub-message DataSize overflows",
922                });
923            };
924            let back_end = match data_end.checked_add(AGG_BACK_POINTER_LEN) {
925                Some(end) if end <= body.len() => end,
926                _ => {
927                    return Err(RtmpError::Malformed {
928                        what: "aggregate sub-message data or Back Pointer runs past the end",
929                    });
930                }
931            };
932            let back_pointer = u32::from_be_bytes([
933                body[back_end - AGG_BACK_POINTER_LEN],
934                body[back_end - AGG_BACK_POINTER_LEN + 1],
935                body[back_end - AGG_BACK_POINTER_LEN + 2],
936                body[back_end - AGG_BACK_POINTER_LEN + 3],
937            ]);
938            let expected_back_pointer = match broadcast_common::len::fit_u32(
939                AGG_SUB_MESSAGE_HEADER_LEN + data_size,
940                "Back Pointer",
941            ) {
942                Ok(v) => v,
943                Err(_) => {
944                    return Err(RtmpError::Malformed {
945                        what: "aggregate sub-message exceeds the 32-bit Back Pointer field",
946                    });
947                }
948            };
949            if back_pointer != expected_back_pointer {
950                return Err(RtmpError::Malformed {
951                    what: "aggregate sub-message Back Pointer disagrees with its actual size",
952                });
953            }
954
955            let ts_offset = *first_ts.get_or_insert(raw_ts);
956            // §7.1.6: offset = (aggregate ts − first sub-message ts), added
957            // to each sub-message ts.
958            let adjusted = raw_ts.wrapping_add(msg.timestamp.wrapping_sub(ts_offset));
959            self.emit_media_if_publishing(tag_type, adjusted, &body[data_start..data_end], events)?;
960            offset = back_end;
961        }
962        Ok(())
963    }
964}
965
966/// Build the 13-byte FLV file header: 9-byte header (Annex E.2) + the first
967/// `PreviousTagSize0` (always `0`).
968fn flv_file_header() -> Vec<u8> {
969    let mut v = Vec::with_capacity(FLV_HEADER_SIZE as usize + FLV_PREV_TAG_SIZE_LEN);
970    v.extend_from_slice(&FLV_SIGNATURE);
971    v.push(FLV_VERSION);
972    v.push(FLV_TYPE_FLAGS_AUDIO_VIDEO);
973    v.extend_from_slice(&FLV_HEADER_SIZE.to_be_bytes());
974    v.extend_from_slice(&0u32.to_be_bytes());
975    v
976}
977
978/// Build one FLV tag (Annex E.4.1): `TagType` + `DataSize` + `Timestamp` +
979/// `TimestampExtended` + `StreamID`(always 0) + `Data` + `PreviousTagSize`.
980///
981/// # Errors
982/// [`RtmpError::Unsupported`] if `payload` is too large for the tag's
983/// 24-bit `DataSize` field.
984fn flv_tag(tag_type: u8, timestamp: u32, payload: &[u8]) -> Result<Vec<u8>> {
985    if payload.len() > FLV_MAX_DATA_SIZE {
986        return Err(RtmpError::Unsupported {
987            what: "flv tag payload exceeds the 24-bit DataSize field",
988        });
989    }
990    let data_size = payload.len() as u32;
991
992    let mut v = Vec::with_capacity(FLV_TAG_HEADER_LEN + payload.len() + FLV_PREV_TAG_SIZE_LEN);
993    v.push(tag_type);
994    v.push((data_size >> 16) as u8);
995    v.push((data_size >> 8) as u8);
996    v.push(data_size as u8);
997    v.push((timestamp >> 16) as u8);
998    v.push((timestamp >> 8) as u8);
999    v.push(timestamp as u8);
1000    v.push((timestamp >> 24) as u8);
1001    v.extend_from_slice(&[0, 0, 0]); // StreamID, always 0.
1002    v.extend_from_slice(payload);
1003    let prev_tag_size = (FLV_TAG_HEADER_LEN + payload.len()) as u32;
1004    v.extend_from_slice(&prev_tag_size.to_be_bytes());
1005    Ok(v)
1006}
1007
1008#[cfg(test)]
1009mod tests {
1010    use super::*;
1011    use crate::handshake::{HANDSHAKE_PACKET_LEN, RTMP_VERSION};
1012    use crate::message::CONTROL_CHUNK_STREAM_ID as CTRL_CSID;
1013    use broadcast_common::Serialize;
1014
1015    // ── Test-only wire builders (this crate's own encoders) ─────────────
1016
1017    const CLIENT_CSID: u32 = 3;
1018
1019    fn build_c0_c1() -> Vec<u8> {
1020        let mut v = vec![0u8; 1 + HANDSHAKE_PACKET_LEN];
1021        v[0] = RTMP_VERSION;
1022        v
1023    }
1024
1025    fn build_c2() -> Vec<u8> {
1026        vec![0u8; HANDSHAKE_PACKET_LEN]
1027    }
1028
1029    fn command_message(
1030        csid: u32,
1031        stream_id: u32,
1032        name: &str,
1033        txn: f64,
1034        args: Vec<Amf0Value>,
1035    ) -> Message {
1036        let body = Command {
1037            name: name.to_string(),
1038            transaction_id: txn,
1039            arguments: args,
1040        }
1041        .to_body()
1042        .unwrap();
1043        Message {
1044            chunk_stream_id: csid,
1045            timestamp: 0,
1046            message_type_id: msg_type::COMMAND_AMF0,
1047            message_stream_id: stream_id,
1048            payload: body,
1049        }
1050    }
1051
1052    fn connect_bytes(app: &str) -> Vec<u8> {
1053        let args = vec![Amf0Value::Object(vec![
1054            ("app".to_string(), Amf0Value::String(app.to_string())),
1055            (
1056                "type".to_string(),
1057                Amf0Value::String("nonprivate".to_string()),
1058            ),
1059        ])];
1060        let msg = command_message(CLIENT_CSID, 0, "connect", 1.0, args);
1061        ChunkWriter::new().write(&msg).unwrap()
1062    }
1063
1064    fn connect_bytes_no_args() -> Vec<u8> {
1065        let msg = command_message(CLIENT_CSID, 0, "connect", 1.0, vec![]);
1066        ChunkWriter::new().write(&msg).unwrap()
1067    }
1068
1069    fn create_stream_bytes() -> Vec<u8> {
1070        let msg = command_message(CLIENT_CSID, 0, "createStream", 2.0, vec![Amf0Value::Null]);
1071        ChunkWriter::new().write(&msg).unwrap()
1072    }
1073
1074    fn publish_bytes(stream_id: u32, stream_key: &str) -> Vec<u8> {
1075        let args = vec![
1076            Amf0Value::Null,
1077            Amf0Value::String(stream_key.to_string()),
1078            Amf0Value::String("live".to_string()),
1079        ];
1080        let msg = command_message(CLIENT_CSID, stream_id, "publish", 3.0, args);
1081        ChunkWriter::new().write(&msg).unwrap()
1082    }
1083
1084    fn av_bytes(
1085        stream_id: u32,
1086        message_type_id: u8,
1087        csid: u32,
1088        timestamp: u32,
1089        payload: Vec<u8>,
1090    ) -> Vec<u8> {
1091        let msg = Message {
1092            chunk_stream_id: csid,
1093            timestamp,
1094            message_type_id,
1095            message_stream_id: stream_id,
1096            payload,
1097        };
1098        ChunkWriter::new().write(&msg).unwrap()
1099    }
1100
1101    /// Decode every reassembled [`Message`] out of a reply byte stream.
1102    /// Pre-sets a generous chunk size: this session's own `_result`/
1103    /// `onStatus` replies are always written with the writer's *current*
1104    /// chunk size (128 until `connect`'s `SetChunkSize` control message is
1105    /// sent, `config.chunk_size` after) but every individual message in
1106    /// these tests fits in a single chunk either way, so decoding under a
1107    /// single generous assumption reproduces the same framing without
1108    /// needing to replay `SetChunkSize` mid-decode.
1109    fn decode_messages(bytes: &[u8]) -> Vec<Message> {
1110        let mut assembler = ChunkAssembler::new();
1111        assembler.set_chunk_size(65536);
1112        assembler.push(bytes).expect("well-formed reply stream")
1113    }
1114
1115    fn decode_commands(bytes: &[u8]) -> Vec<Command> {
1116        decode_messages(bytes)
1117            .iter()
1118            .filter(|m| m.message_type_id == msg_type::COMMAND_AMF0)
1119            .map(|m| Command::parse(&m.payload).expect("well-formed command reply"))
1120            .collect()
1121    }
1122
1123    fn onstatus_code(cmd: &Command) -> Option<String> {
1124        cmd.arguments.iter().find_map(|v| match v {
1125            Amf0Value::Object(pairs) => pairs.iter().find_map(|(k, v)| {
1126                if k == "code" {
1127                    match v {
1128                        Amf0Value::String(s) => Some(s.clone()),
1129                        _ => None,
1130                    }
1131                } else {
1132                    None
1133                }
1134            }),
1135            _ => None,
1136        })
1137    }
1138
1139    /// Drive a session through handshake → connect → createStream →
1140    /// publish, returning `(session, all reply bytes, all events)`.
1141    fn publish_flow(
1142        config: ServerConfig,
1143        stream_key: &str,
1144    ) -> (ServerSession, Vec<u8>, Vec<ServerEvent>) {
1145        let mut session = ServerSession::new(config);
1146        // `all_out` accumulates only *post-handshake* (chunk-encoded) reply
1147        // bytes: the handshake reply (S0+S1+S2) is a raw fixed-length
1148        // packet, not chunk-stream framing, so it must not be fed into a
1149        // `ChunkAssembler` alongside the chunk-encoded command replies.
1150        let mut all_out = Vec::new();
1151        let mut all_events = Vec::new();
1152
1153        session.handle_data(&build_c0_c1()).unwrap();
1154        session.handle_data(&build_c2()).unwrap();
1155
1156        let (out, events) = session.handle_data(&connect_bytes("live")).unwrap();
1157        all_out.extend(out);
1158        all_events.extend(events);
1159
1160        let (out, events) = session.handle_data(&create_stream_bytes()).unwrap();
1161        all_out.extend(out);
1162        all_events.extend(events);
1163
1164        // ServerSession always allocates stream ids starting at 1.
1165        let (out, events) = session.handle_data(&publish_bytes(1, stream_key)).unwrap();
1166        all_out.extend(out);
1167        all_events.extend(events);
1168
1169        (session, all_out, all_events)
1170    }
1171
1172    // ── Handshake ─────────────────────────────────────────────────────────
1173
1174    #[test]
1175    fn handshake_completes_and_reply_contains_s0_s1_s2() {
1176        let mut session = ServerSession::with_defaults();
1177        let (out1, events1) = session.handle_data(&build_c0_c1()).unwrap();
1178        assert_eq!(
1179            out1.len(),
1180            1 + HANDSHAKE_PACKET_LEN + HANDSHAKE_PACKET_LEN,
1181            "S0+S1+S2 must be a single 3073-byte reply"
1182        );
1183        assert!(events1.is_empty());
1184
1185        let (out2, events2) = session.handle_data(&build_c2()).unwrap();
1186        assert!(out2.is_empty(), "C2 receipt produces no reply bytes itself");
1187        assert!(events2.is_empty());
1188    }
1189
1190    #[test]
1191    fn handshake_split_across_calls_still_completes() {
1192        let mut session = ServerSession::with_defaults();
1193        let c0c1 = build_c0_c1();
1194        let (out1, _) = session.handle_data(&c0c1[..500]).unwrap();
1195        assert!(out1.is_empty(), "partial C0+C1 produces no reply yet");
1196        let (out2, _) = session.handle_data(&c0c1[500..]).unwrap();
1197        assert_eq!(out2.len(), 1 + 2 * HANDSHAKE_PACKET_LEN);
1198        let (_out3, _) = session.handle_data(&build_c2()).unwrap();
1199    }
1200
1201    #[test]
1202    fn c2_pipelined_with_connect_chunk_in_one_call_still_parses_connect() {
1203        // Real clients commonly send C2 back-to-back with the very next
1204        // chunk-encoded message (e.g. `connect`) in the same TCP segment,
1205        // so both arrive together in a single `handle_data` call. The
1206        // post-handshake leftover bytes from that call must be handed to
1207        // the chunk assembler within the SAME call, not merely buffered
1208        // for a subsequent one.
1209        let mut session = ServerSession::with_defaults();
1210        session.handle_data(&build_c0_c1()).unwrap();
1211
1212        let mut pipelined = build_c2();
1213        pipelined.extend_from_slice(&connect_bytes("live"));
1214
1215        let (_out, events) = session.handle_data(&pipelined).unwrap();
1216        assert_eq!(
1217            events,
1218            vec![ServerEvent::Connected {
1219                app: "live".to_string()
1220            }],
1221            "C2 pipelined with the connect chunk in one handle_data call must \
1222             still yield Connected from that call (leftover bytes must not be dropped)"
1223        );
1224    }
1225
1226    // ── connect ───────────────────────────────────────────────────────────
1227
1228    #[test]
1229    fn connect_emits_connected_event_and_result_reply() {
1230        let mut session = ServerSession::with_defaults();
1231        session.handle_data(&build_c0_c1()).unwrap();
1232        session.handle_data(&build_c2()).unwrap();
1233
1234        let (out, events) = session.handle_data(&connect_bytes("live")).unwrap();
1235        assert_eq!(
1236            events,
1237            vec![ServerEvent::Connected {
1238                app: "live".to_string()
1239            }]
1240        );
1241
1242        let commands = decode_commands(&out);
1243        assert!(
1244            commands.iter().any(|c| c.name == "_result"),
1245            "connect reply must contain a _result command"
1246        );
1247    }
1248
1249    /// RTMP-W6 (#1108): an AMF3-encoded `connect` (message type 17) is a
1250    /// leading format-marker byte + an otherwise-ordinary AMF0 command
1251    /// body — not a distinct grammar. Pre-fix, this hit the catch-all and
1252    /// got no reply at all (the client would hang until its own timeout).
1253    #[test]
1254    fn amf3_connect_is_answered_like_amf0() {
1255        let mut session = ServerSession::with_defaults();
1256        session.handle_data(&build_c0_c1()).unwrap();
1257        session.handle_data(&build_c2()).unwrap();
1258
1259        let args = vec![Amf0Value::Object(vec![(
1260            "app".to_string(),
1261            Amf0Value::String("live".to_string()),
1262        )])];
1263        let amf0_body = Command {
1264            name: "connect".to_string(),
1265            transaction_id: 1.0,
1266            arguments: args,
1267        }
1268        .to_body()
1269        .unwrap();
1270        let mut amf3_body = vec![0x00]; // AMF3 encoding marker byte
1271        amf3_body.extend(amf0_body);
1272        let msg = Message {
1273            chunk_stream_id: CLIENT_CSID,
1274            timestamp: 0,
1275            message_type_id: msg_type::COMMAND_AMF3,
1276            message_stream_id: 0,
1277            payload: amf3_body,
1278        };
1279        let bytes = ChunkWriter::new().write(&msg).unwrap();
1280
1281        let (out, events) = session.handle_data(&bytes).unwrap();
1282        assert_eq!(
1283            events,
1284            vec![ServerEvent::Connected {
1285                app: "live".to_string()
1286            }]
1287        );
1288        let commands = decode_commands(&out);
1289        assert!(
1290            commands.iter().any(|c| c.name == "_result"),
1291            "AMF3 connect must still get a _result reply"
1292        );
1293    }
1294
1295    /// RTMP-W6 (#1108): an Aggregate (22) message used to be silently
1296    /// dropped with no signal at all (then, briefly, surfaced as
1297    /// `ServerEvent::Unsupported`). It is now unpacked into its contained
1298    /// sub-messages; a *malformed* one is a `Malformed` error, and the
1299    /// opaque `0xAA` filler below is exactly that (a bogus `DataSize`/
1300    /// `Back Pointer`), so this exercises the reject side of the new
1301    /// behaviour.
1302    #[test]
1303    fn aggregate_message_surfaces_unsupported_event() {
1304        let mut session = ServerSession::with_defaults();
1305        session.handle_data(&build_c0_c1()).unwrap();
1306        session.handle_data(&build_c2()).unwrap();
1307        session.handle_data(&connect_bytes("live")).unwrap();
1308
1309        let msg = Message {
1310            chunk_stream_id: CLIENT_CSID,
1311            timestamp: 0,
1312            message_type_id: msg_type::AGGREGATE,
1313            message_stream_id: 0,
1314            payload: vec![0xAA; 20], // opaque; not a valid aggregate body
1315        };
1316        let bytes = ChunkWriter::new().write(&msg).unwrap();
1317
1318        let err = session.handle_data(&bytes).unwrap_err();
1319        assert!(
1320            matches!(err, RtmpError::Malformed { .. }),
1321            "a garbage aggregate body must now be a Malformed error, got {err:?}"
1322        );
1323    }
1324
1325    /// Builds one Aggregate (22) body from `(tag type, timestamp, data)`
1326    /// sub-messages, writing the timestamps in FLV layout (24-bit high +
1327    /// extended low byte) and each `Back Pointer` as "size of this message
1328    /// including its header" (§7.1.6).
1329    fn aggregate_body(subs: &[(u8, u32, &[u8])]) -> Vec<u8> {
1330        let mut body = Vec::new();
1331        for &(tag_type, timestamp, data) in subs {
1332            let data_size = data.len() as u32;
1333            body.push(tag_type);
1334            body.push((data_size >> 16) as u8);
1335            body.push((data_size >> 8) as u8);
1336            body.push(data_size as u8);
1337            body.push((timestamp >> 16) as u8);
1338            body.push((timestamp >> 8) as u8);
1339            body.push(timestamp as u8);
1340            body.push((timestamp >> 24) as u8);
1341            body.extend_from_slice(&[0, 0, 0]); // StreamID, always 0.
1342            body.extend_from_slice(data);
1343            let back_pointer = (11 + data.len()) as u32;
1344            body.extend_from_slice(&back_pointer.to_be_bytes());
1345        }
1346        body
1347    }
1348
1349    /// Pulls the `(tag_type, timestamp)` out of one `Media` event's FLV
1350    /// bytes (the tag starts after the one-time FLV file header).
1351    fn first_flv_tag_header(flv: &[u8]) -> (u8, u32) {
1352        let tag = if flv.len() > 13 && flv.starts_with(b"FLV") {
1353            &flv[13..]
1354        } else {
1355            flv
1356        };
1357        let ts_low24 = u32::from_be_bytes([0, tag[4], tag[5], tag[6]]);
1358        (tag[0], ts_low24 | (u32::from(tag[7]) << 24))
1359    }
1360
1361    /// Publishes through the full handshake/connect/createStream/publish
1362    /// sequence so subsequent media is actually emitted.
1363    fn publishing_session() -> ServerSession {
1364        let mut session = ServerSession::new(ServerConfig::default());
1365        session.handle_data(&build_c0_c1()).unwrap();
1366        session.handle_data(&build_c2()).unwrap();
1367        session.handle_data(&connect_bytes("live")).unwrap();
1368        session.handle_data(&create_stream_bytes()).unwrap();
1369        session.handle_data(&publish_bytes(1, "mystream")).unwrap();
1370        session
1371    }
1372
1373    /// RTMP-W6 remainder (#1108): a well-formed aggregate of two video +
1374    /// one audio sub-message must be delivered as three ordinary `Media`
1375    /// events with the sub-message timestamps preserved.
1376    #[test]
1377    fn aggregate_message_is_unpacked_into_media_events() {
1378        let mut session = publishing_session();
1379        let body = aggregate_body(&[
1380            (msg_type::VIDEO, 1000, &[0x17, 0x01, 0xAA, 0xBB]),
1381            (msg_type::VIDEO, 1040, &[0x27, 0x01, 0xCC]),
1382            (msg_type::AUDIO, 1005, &[0xAF, 0x01, 0xDD, 0xEE]),
1383        ]);
1384        let msg = Message {
1385            chunk_stream_id: CLIENT_CSID,
1386            timestamp: 1000, // == first sub-message ts, so offset is 0
1387            message_type_id: msg_type::AGGREGATE,
1388            message_stream_id: 1,
1389            payload: body,
1390        };
1391        let bytes = ChunkWriter::new().write(&msg).unwrap();
1392        let (_out, events) = session.handle_data(&bytes).unwrap();
1393        let tags: Vec<(u8, u32)> = events
1394            .iter()
1395            .map(|e| match e {
1396                ServerEvent::Media { flv } => first_flv_tag_header(flv),
1397                other => panic!("expected only Media events, got {other:?}"),
1398            })
1399            .collect();
1400        assert_eq!(
1401            tags,
1402            vec![
1403                (msg_type::VIDEO, 1000),
1404                (msg_type::VIDEO, 1040),
1405                (msg_type::AUDIO, 1005),
1406            ]
1407        );
1408    }
1409
1410    /// §7.1.6 timestamp renormalization: when the first sub-message's ts
1411    /// differs from the aggregate's own, offset = (aggregate ts − first
1412    /// sub ts) is added to every sub-message ts.
1413    #[test]
1414    fn aggregate_timestamps_are_renormalized_against_the_aggregate() {
1415        let mut session = publishing_session();
1416        let body = aggregate_body(&[
1417            (msg_type::VIDEO, 50, &[0x17, 0x01]),
1418            (msg_type::AUDIO, 60, &[0xAF, 0x01]),
1419        ]);
1420        let msg = Message {
1421            chunk_stream_id: CLIENT_CSID,
1422            timestamp: 100,
1423            message_type_id: msg_type::AGGREGATE,
1424            message_stream_id: 1,
1425            payload: body,
1426        };
1427        let bytes = ChunkWriter::new().write(&msg).unwrap();
1428        let (_out, events) = session.handle_data(&bytes).unwrap();
1429        let tags: Vec<(u8, u32)> = events
1430            .iter()
1431            .map(|e| match e {
1432                ServerEvent::Media { flv } => first_flv_tag_header(flv),
1433                other => panic!("expected only Media events, got {other:?}"),
1434            })
1435            .collect();
1436        // offset = 100 − 50 = 50 added to each.
1437        assert_eq!(tags, vec![(msg_type::VIDEO, 100), (msg_type::AUDIO, 110)]);
1438    }
1439
1440    /// RTMP-W6 remainder (#1108): a truncated aggregate (last sub-message
1441    /// claims more data than the body actually carries) must error, not
1442    /// partially deliver or silently drop.
1443    #[test]
1444    fn truncated_aggregate_message_errors() {
1445        let mut session = publishing_session();
1446        let mut body = aggregate_body(&[(msg_type::VIDEO, 0, &[0x17, 0x01, 0xAA])]);
1447        // Chop off the last sub-message's data + back pointer: its header
1448        // now claims 3 data bytes the body no longer has.
1449        body.truncate(body.len() - 5);
1450        let msg = Message {
1451            chunk_stream_id: CLIENT_CSID,
1452            timestamp: 0,
1453            message_type_id: msg_type::AGGREGATE,
1454            message_stream_id: 1,
1455            payload: body,
1456        };
1457        let bytes = ChunkWriter::new().write(&msg).unwrap();
1458        let err = session.handle_data(&bytes).unwrap_err();
1459        assert!(
1460            matches!(err, RtmpError::Malformed { .. }),
1461            "a truncated aggregate must be Malformed, got {err:?}"
1462        );
1463    }
1464
1465    /// A `Back Pointer` that disagrees with the sub-message's actual size
1466    /// is corruption — reject rather than trust it for framing.
1467    #[test]
1468    fn aggregate_with_bad_back_pointer_errors() {
1469        let mut session = publishing_session();
1470        let mut body = aggregate_body(&[(msg_type::VIDEO, 0, &[0x17, 0x01, 0xAA])]);
1471        let back_at = body.len() - 4;
1472        body[back_at] = 0xFF; // corrupt the back pointer
1473        let msg = Message {
1474            chunk_stream_id: CLIENT_CSID,
1475            timestamp: 0,
1476            message_type_id: msg_type::AGGREGATE,
1477            message_stream_id: 1,
1478            payload: body,
1479        };
1480        let bytes = ChunkWriter::new().write(&msg).unwrap();
1481        let err = session.handle_data(&bytes).unwrap_err();
1482        assert!(
1483            matches!(err, RtmpError::Malformed { .. }),
1484            "a lying Back Pointer must be Malformed, got {err:?}"
1485        );
1486    }
1487
1488    #[test]
1489    fn connect_without_command_object_is_malformed() {
1490        let mut session = ServerSession::with_defaults();
1491        session.handle_data(&build_c0_c1()).unwrap();
1492        session.handle_data(&build_c2()).unwrap();
1493
1494        // No arguments at all: arg0 (the command object) is missing.
1495        let err = session.handle_data(&connect_bytes_no_args()).unwrap_err();
1496        assert!(
1497            matches!(err, RtmpError::Malformed { .. }),
1498            "connect with no command-object argument must error, not default app to \"\""
1499        );
1500    }
1501
1502    /// Gap 3 regression test (#738): connect with a command object present
1503    /// but missing the `app` key must be rejected.
1504    #[test]
1505    fn connect_with_object_missing_app_key_is_malformed() {
1506        let mut session = ServerSession::with_defaults();
1507        session.handle_data(&build_c0_c1()).unwrap();
1508        session.handle_data(&build_c2()).unwrap();
1509
1510        // Object is present but has no `app` key.
1511        let args = vec![Amf0Value::Object(vec![(
1512            "type".to_string(),
1513            Amf0Value::String("nonprivate".to_string()),
1514        )])];
1515        let msg = command_message(CLIENT_CSID, 0, "connect", 1.0, args);
1516        let bytes = ChunkWriter::new().write(&msg).unwrap();
1517
1518        let err = session.handle_data(&bytes).unwrap_err();
1519        assert!(
1520            matches!(err, RtmpError::Malformed { .. }),
1521            "connect with object missing 'app' key must error"
1522        );
1523    }
1524
1525    /// Gap 3 regression test (#738): connect with a command object present
1526    /// but `app` value is not a String must be rejected.
1527    #[test]
1528    fn connect_with_app_as_number_is_malformed() {
1529        let mut session = ServerSession::with_defaults();
1530        session.handle_data(&build_c0_c1()).unwrap();
1531        session.handle_data(&build_c2()).unwrap();
1532
1533        // Object has `app` key but value is a Number, not a String.
1534        let args = vec![Amf0Value::Object(vec![
1535            ("app".to_string(), Amf0Value::Number(123.0)),
1536            (
1537                "type".to_string(),
1538                Amf0Value::String("nonprivate".to_string()),
1539            ),
1540        ])];
1541        let msg = command_message(CLIENT_CSID, 0, "connect", 1.0, args);
1542        let bytes = ChunkWriter::new().write(&msg).unwrap();
1543
1544        let err = session.handle_data(&bytes).unwrap_err();
1545        assert!(
1546            matches!(err, RtmpError::Malformed { .. }),
1547            "connect with app as Number must error, not accept numeric value"
1548        );
1549    }
1550
1551    // ── createStream ──────────────────────────────────────────────────────
1552
1553    #[test]
1554    fn create_stream_replies_result_with_stream_id() {
1555        let mut session = ServerSession::with_defaults();
1556        session.handle_data(&build_c0_c1()).unwrap();
1557        session.handle_data(&build_c2()).unwrap();
1558        session.handle_data(&connect_bytes("live")).unwrap();
1559
1560        let (out, _events) = session.handle_data(&create_stream_bytes()).unwrap();
1561        let commands = decode_commands(&out);
1562        let result = commands
1563            .iter()
1564            .find(|c| c.name == "_result")
1565            .expect("createStream _result reply");
1566        assert_eq!(
1567            result.arguments.get(1),
1568            Some(&Amf0Value::Number(1.0)),
1569            "first allocated stream id must be 1"
1570        );
1571    }
1572
1573    #[test]
1574    fn create_stream_before_connect_is_unexpected_state() {
1575        let mut session = ServerSession::with_defaults();
1576        session.handle_data(&build_c0_c1()).unwrap();
1577        session.handle_data(&build_c2()).unwrap();
1578
1579        let err = session.handle_data(&create_stream_bytes()).unwrap_err();
1580        assert!(matches!(err, RtmpError::UnexpectedState { .. }));
1581    }
1582
1583    // ── publish ───────────────────────────────────────────────────────────
1584
1585    /// Release audit (CRITICAL): a peer-chosen publishing name of 65 518..=65 535
1586    /// bytes fits the request's AMF0 u16 string prefix but, echoed into the
1587    /// `"<key> is now published."` onStatus description, overflows it. That
1588    /// used to hit `to_bytes().expect(..)` and panic the server remotely.
1589    #[test]
1590    fn oversized_publish_name_errors_instead_of_panicking() {
1591        for len in [65_518usize, 65_530, 65_535] {
1592            let mut session = ServerSession::new(ServerConfig::default());
1593            session.handle_data(&build_c0_c1()).unwrap();
1594            session.handle_data(&build_c2()).unwrap();
1595            session.handle_data(&connect_bytes("live")).unwrap();
1596            session.handle_data(&create_stream_bytes()).unwrap();
1597            let key = "k".repeat(len);
1598            let err = session
1599                .handle_data(&publish_bytes(1, &key))
1600                .expect_err("overflowing onStatus description must be an Err");
1601            assert!(
1602                matches!(err, RtmpError::Unsupported { .. }),
1603                "len {len}: {err:?}"
1604            );
1605        }
1606    }
1607
1608    #[test]
1609    fn publish_reaches_publishing_emits_event_and_stream_begin_plus_onstatus() {
1610        let (_session, out, events) = publish_flow(ServerConfig::default(), "testkey");
1611
1612        assert!(events.contains(&ServerEvent::Publish {
1613            app: "live".to_string(),
1614            stream_key: "testkey".to_string(),
1615            stream_id: 1,
1616        }));
1617
1618        let messages = decode_messages(&out);
1619        let has_stream_begin = messages.iter().any(|m| {
1620            m.message_type_id == msg_type::USER_CONTROL
1621                && matches!(
1622                    UserControl::parse(&m.payload),
1623                    Ok(UserControl::StreamBegin(1))
1624                )
1625        });
1626        assert!(
1627            has_stream_begin,
1628            "publish reply must include StreamBegin(1)"
1629        );
1630
1631        let commands = decode_commands(&out);
1632        let on_status = commands
1633            .iter()
1634            .find(|c| c.name == "onStatus")
1635            .expect("onStatus reply to publish");
1636        assert_eq!(
1637            onstatus_code(on_status).as_deref(),
1638            Some("NetStream.Publish.Start")
1639        );
1640    }
1641
1642    #[test]
1643    fn publish_before_connect_is_unexpected_state() {
1644        let mut session = ServerSession::with_defaults();
1645        session.handle_data(&build_c0_c1()).unwrap();
1646        session.handle_data(&build_c2()).unwrap();
1647
1648        let err = session
1649            .handle_data(&publish_bytes(1, "testkey"))
1650            .unwrap_err();
1651        assert!(matches!(err, RtmpError::UnexpectedState { .. }));
1652    }
1653
1654    #[test]
1655    fn publish_without_create_stream_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        session.handle_data(&connect_bytes("live")).unwrap();
1660
1661        // createStream never called: publish must not succeed on app-only.
1662        let err = session
1663            .handle_data(&publish_bytes(1, "testkey"))
1664            .unwrap_err();
1665        assert!(matches!(err, RtmpError::UnexpectedState { .. }));
1666    }
1667
1668    #[test]
1669    fn create_stream_after_closed_is_unexpected_state() {
1670        let mut session = ServerSession::with_defaults();
1671        session.handle_data(&build_c0_c1()).unwrap();
1672        session.handle_data(&build_c2()).unwrap();
1673        session.handle_data(&connect_bytes("live")).unwrap();
1674        session.handle_data(&create_stream_bytes()).unwrap();
1675        session.handle_data(&publish_bytes(1, "testkey")).unwrap();
1676
1677        let delete_stream = command_message(
1678            CLIENT_CSID,
1679            1,
1680            "deleteStream",
1681            4.0,
1682            vec![Amf0Value::Null, Amf0Value::Number(1.0)],
1683        );
1684        let (_out, events) = session
1685            .handle_data(&ChunkWriter::new().write(&delete_stream).unwrap())
1686            .unwrap();
1687        assert_eq!(events, vec![ServerEvent::Eof]);
1688
1689        let err = session.handle_data(&create_stream_bytes()).unwrap_err();
1690        assert!(
1691            matches!(err, RtmpError::UnexpectedState { .. }),
1692            "createStream after State::Closed must be rejected, not silently re-allowed"
1693        );
1694    }
1695
1696    // ── Audio/Video → Media / FLV ─────────────────────────────────────────
1697
1698    #[test]
1699    fn audio_and_video_emit_media_first_carries_flv_file_header() {
1700        let (mut session, _out, _events) = publish_flow(ServerConfig::default(), "testkey");
1701
1702        let (_out1, events1) = session
1703            .handle_data(&av_bytes(
1704                1,
1705                msg_type::AUDIO,
1706                4,
1707                0,
1708                vec![0xAF, 0x01, 0xDE, 0xAD],
1709            ))
1710            .unwrap();
1711        assert_eq!(events1.len(), 1);
1712        let ServerEvent::Media { flv } = &events1[0] else {
1713            panic!("expected Media event");
1714        };
1715        assert!(
1716            flv.starts_with(b"FLV"),
1717            "the first Media event must carry the FLV file header"
1718        );
1719
1720        let (_out2, events2) = session
1721            .handle_data(&av_bytes(
1722                1,
1723                msg_type::VIDEO,
1724                6,
1725                40,
1726                vec![0x17, 0x01, 0x00, 0x00, 0x00, 0xDE, 0xAD, 0xBE, 0xEF],
1727            ))
1728            .unwrap();
1729        assert_eq!(events2.len(), 1);
1730        let ServerEvent::Media { flv } = &events2[0] else {
1731            panic!("expected Media event");
1732        };
1733        assert!(
1734            !flv.starts_with(b"FLV"),
1735            "only the first Media event carries the file header"
1736        );
1737    }
1738
1739    #[test]
1740    fn concatenated_media_forms_structurally_valid_flv() {
1741        let (mut session, _out, _events) = publish_flow(ServerConfig::default(), "testkey");
1742
1743        let mut flv_stream = Vec::new();
1744        let (_out1, events1) = session
1745            .handle_data(&av_bytes(
1746                1,
1747                msg_type::AUDIO,
1748                4,
1749                0,
1750                vec![0xAF, 0x01, 1, 2, 3],
1751            ))
1752            .unwrap();
1753        let (_out2, events2) = session
1754            .handle_data(&av_bytes(
1755                1,
1756                msg_type::VIDEO,
1757                6,
1758                33,
1759                vec![0x17, 0x01, 0, 0, 0, 4, 5, 6],
1760            ))
1761            .unwrap();
1762        for e in events1.into_iter().chain(events2) {
1763            if let ServerEvent::Media { flv } = e {
1764                flv_stream.extend(flv);
1765            }
1766        }
1767
1768        // File header (13 bytes): signature/version/flags/data-offset/prevTagSize0.
1769        assert_eq!(&flv_stream[0..3], b"FLV");
1770        assert_eq!(flv_stream[3], 1, "FLV version");
1771        assert_eq!(flv_stream[4], 0b0000_0101, "audio+video TypeFlags");
1772        assert_eq!(
1773            u32::from_be_bytes(flv_stream[5..9].try_into().unwrap()),
1774            9,
1775            "DataOffset (header size)"
1776        );
1777        assert_eq!(
1778            u32::from_be_bytes(flv_stream[9..13].try_into().unwrap()),
1779            0,
1780            "PreviousTagSize0"
1781        );
1782
1783        // First tag (audio): TagType=8, DataSize=5.
1784        let tag1 = &flv_stream[13..];
1785        assert_eq!(tag1[0], msg_type::AUDIO);
1786        let data_size1 =
1787            (u32::from(tag1[1]) << 16) | (u32::from(tag1[2]) << 8) | u32::from(tag1[3]);
1788        assert_eq!(data_size1, 5);
1789        let tag1_total = FLV_TAG_HEADER_LEN + 5 + FLV_PREV_TAG_SIZE_LEN;
1790        let prev_tag_size1 = u32::from_be_bytes(
1791            flv_stream[13 + tag1_total - 4..13 + tag1_total]
1792                .try_into()
1793                .unwrap(),
1794        );
1795        assert_eq!(prev_tag_size1 as usize, FLV_TAG_HEADER_LEN + 5);
1796
1797        // Second tag (video) immediately follows.
1798        let tag2 = &flv_stream[13 + tag1_total..];
1799        assert_eq!(tag2[0], msg_type::VIDEO);
1800        let data_size2 =
1801            (u32::from(tag2[1]) << 16) | (u32::from(tag2[2]) << 8) | u32::from(tag2[3]);
1802        assert_eq!(data_size2, 8);
1803        assert_eq!(
1804            flv_stream.len(),
1805            13 + tag1_total + FLV_TAG_HEADER_LEN + 8 + FLV_PREV_TAG_SIZE_LEN
1806        );
1807    }
1808
1809    #[test]
1810    fn data_amf0_onmetadata_emits_media_with_script_tag_type() {
1811        let (mut session, _out, _events) = publish_flow(ServerConfig::default(), "testkey");
1812
1813        // A representative onMetadata Data-AMF0 payload: handler-name
1814        // string followed by a properties object (§7.1's Data Message
1815        // shape), same as e.g. width/height/framerate metadata a real
1816        // encoder sends.
1817        let mut payload = Amf0Value::String("onMetaData".to_string()).to_bytes();
1818        payload.extend(
1819            Amf0Value::Object(vec![
1820                ("width".to_string(), Amf0Value::Number(1920.0)),
1821                ("height".to_string(), Amf0Value::Number(1080.0)),
1822            ])
1823            .to_bytes(),
1824        );
1825
1826        let (_out, events) = session
1827            .handle_data(&av_bytes(1, msg_type::DATA_AMF0, 4, 0, payload))
1828            .unwrap();
1829
1830        assert_eq!(events.len(), 1);
1831        let ServerEvent::Media { flv } = &events[0] else {
1832            panic!("expected Media event");
1833        };
1834        assert!(
1835            flv.starts_with(b"FLV"),
1836            "the first Media event must carry the FLV file header"
1837        );
1838        let tag_type = flv[FLV_HEADER_SIZE as usize + FLV_PREV_TAG_SIZE_LEN];
1839        assert_eq!(
1840            tag_type,
1841            msg_type::DATA_AMF0,
1842            "Data-AMF0 message must produce a script(18) FLV tag"
1843        );
1844    }
1845
1846    #[test]
1847    fn media_before_publishing_is_silently_dropped() {
1848        let mut session = ServerSession::with_defaults();
1849        session.handle_data(&build_c0_c1()).unwrap();
1850        session.handle_data(&build_c2()).unwrap();
1851        session.handle_data(&connect_bytes("live")).unwrap();
1852        session.handle_data(&create_stream_bytes()).unwrap();
1853
1854        // publish never called: state is Connected, not Publishing.
1855        let (_out, events) = session
1856            .handle_data(&av_bytes(1, msg_type::AUDIO, 4, 0, vec![0xAF, 0x01]))
1857            .unwrap();
1858        assert!(events.is_empty());
1859    }
1860
1861    // ── expected_stream_key mismatch ──────────────────────────────────────
1862
1863    #[test]
1864    fn stream_key_mismatch_suppresses_publish_and_media_events() {
1865        let config = ServerConfig {
1866            expected_stream_key: Some("rightkey".to_string()),
1867            ..ServerConfig::default()
1868        };
1869        let (mut session, out, events) = publish_flow(config, "wrongkey");
1870
1871        assert!(
1872            !events
1873                .iter()
1874                .any(|e| matches!(e, ServerEvent::Publish { .. })),
1875            "mismatched stream key must not emit Publish"
1876        );
1877
1878        let commands = decode_commands(&out);
1879        let on_status = commands
1880            .iter()
1881            .find(|c| c.name == "onStatus")
1882            .expect("onStatus reply on mismatch");
1883        assert_eq!(
1884            onstatus_code(on_status).as_deref(),
1885            Some("NetStream.Publish.BadName")
1886        );
1887
1888        // Session never entered Publishing: subsequent A/V produces no Media.
1889        let (_out2, events2) = session
1890            .handle_data(&av_bytes(1, msg_type::AUDIO, 4, 0, vec![0xAF, 0x01]))
1891            .unwrap();
1892        assert!(
1893            events2.is_empty(),
1894            "no Media may be emitted after a rejected publish"
1895        );
1896    }
1897
1898    #[test]
1899    fn stream_key_match_still_publishes_with_key_configured() {
1900        let config = ServerConfig {
1901            expected_stream_key: Some("rightkey".to_string()),
1902            ..ServerConfig::default()
1903        };
1904        let (_session, _out, events) = publish_flow(config, "rightkey");
1905        assert!(
1906            events.contains(&ServerEvent::Publish {
1907                app: "live".to_string(),
1908                stream_key: "rightkey".to_string(),
1909                stream_id: 1,
1910            }),
1911            "a stream key matching expected_stream_key must still publish"
1912        );
1913    }
1914
1915    #[test]
1916    fn too_many_failed_publish_attempts_closes_the_session() {
1917        let config = ServerConfig {
1918            expected_stream_key: Some("rightkey".to_string()),
1919            ..ServerConfig::default()
1920        };
1921        let mut session = ServerSession::new(config);
1922        session.handle_data(&build_c0_c1()).unwrap();
1923        session.handle_data(&build_c2()).unwrap();
1924        session.handle_data(&connect_bytes("live")).unwrap();
1925        session.handle_data(&create_stream_bytes()).unwrap();
1926
1927        for attempt in 1..=MAX_FAILED_PUBLISH_ATTEMPTS {
1928            let (_out, events) = session.handle_data(&publish_bytes(1, "wrongkey")).unwrap_or_else(|e| {
1929                panic!("attempt {attempt} of {MAX_FAILED_PUBLISH_ATTEMPTS} must still be rejected, not error out: {e}")
1930            });
1931            assert!(
1932                !events
1933                    .iter()
1934                    .any(|e| matches!(e, ServerEvent::Publish { .. })),
1935                "attempt {attempt} must not publish"
1936            );
1937        }
1938
1939        // The attempt beyond MAX_FAILED_PUBLISH_ATTEMPTS must end the
1940        // session instead of replying BadName again.
1941        let err = session
1942            .handle_data(&publish_bytes(1, "wrongkey"))
1943            .expect_err("the attempt beyond MAX_FAILED_PUBLISH_ATTEMPTS must close the session");
1944        assert!(matches!(err, RtmpError::UnexpectedState { .. }));
1945
1946        // The session stays closed even for the correct key.
1947        let err = session
1948            .handle_data(&publish_bytes(1, "rightkey"))
1949            .expect_err(
1950                "publish must be rejected once the session was closed for too many failures",
1951            );
1952        assert!(matches!(err, RtmpError::UnexpectedState { .. }));
1953    }
1954
1955    #[test]
1956    fn constant_time_eq_matches_naive_equality() {
1957        assert!(constant_time_eq(b"rightkey", b"rightkey"));
1958        assert!(!constant_time_eq(b"rightkey", b"wrongkey"));
1959        assert!(!constant_time_eq(b"short", b"muchlonger"));
1960        assert!(constant_time_eq(b"", b""));
1961    }
1962
1963    // ── Ack accounting ────────────────────────────────────────────────────
1964
1965    #[test]
1966    fn ack_written_once_window_ack_size_is_crossed() {
1967        let config = ServerConfig {
1968            window_ack_size: 32,
1969            ..ServerConfig::default()
1970        };
1971        let mut session = ServerSession::new(config);
1972        session.handle_data(&build_c0_c1()).unwrap();
1973        session.handle_data(&build_c2()).unwrap();
1974
1975        // connect's chunk-encoded bytes comfortably exceed 32 bytes.
1976        let (out, _events) = session.handle_data(&connect_bytes("live")).unwrap();
1977        let messages = decode_messages(&out);
1978        let has_ack = messages.iter().any(|m| {
1979            matches!(
1980                ProtocolControl::from_message(m),
1981                Ok(Some(ProtocolControl::Acknowledgement(_)))
1982            )
1983        });
1984        assert!(
1985            has_ack,
1986            "crossing window_ack_size must produce an Acknowledgement"
1987        );
1988    }
1989
1990    #[test]
1991    fn no_ack_below_window_ack_size() {
1992        let config = ServerConfig {
1993            window_ack_size: 10_000_000,
1994            ..ServerConfig::default()
1995        };
1996        let mut session = ServerSession::new(config);
1997        session.handle_data(&build_c0_c1()).unwrap();
1998        let (out, _events) = session.handle_data(&build_c2()).unwrap();
1999        let messages = decode_messages(&out);
2000        assert!(
2001            !messages.iter().any(|m| matches!(
2002                ProtocolControl::from_message(m),
2003                Ok(Some(ProtocolControl::Acknowledgement(_)))
2004            )),
2005            "no Acknowledgement should be due yet"
2006        );
2007    }
2008
2009    // ── Garbage / truncated input never panics ────────────────────────────
2010
2011    #[test]
2012    fn garbage_command_payload_after_handshake_is_error_not_panic() {
2013        let mut session = ServerSession::with_defaults();
2014        session.handle_data(&build_c0_c1()).unwrap();
2015        session.handle_data(&build_c2()).unwrap();
2016
2017        // A structurally valid chunk envelope (Type0 header, Command-AMF0
2018        // type id) whose payload is not valid AMF0 (0xFF is not a defined
2019        // AMF0 marker) — Command::parse must reject this, not panic.
2020        let bogus = Message {
2021            chunk_stream_id: CLIENT_CSID,
2022            timestamp: 0,
2023            message_type_id: msg_type::COMMAND_AMF0,
2024            message_stream_id: 0,
2025            payload: vec![0xFF, 0xFF, 0xFF, 0xFF],
2026        };
2027        let bytes = ChunkWriter::new().write(&bogus).unwrap();
2028        let err = session.handle_data(&bytes).unwrap_err();
2029        assert!(matches!(
2030            err,
2031            RtmpError::Unsupported { .. }
2032                | RtmpError::Malformed { .. }
2033                | RtmpError::BufferTooShort { .. }
2034        ));
2035    }
2036
2037    #[test]
2038    fn truncated_post_handshake_bytes_do_not_panic() {
2039        let mut session = ServerSession::with_defaults();
2040        session.handle_data(&build_c0_c1()).unwrap();
2041        session.handle_data(&build_c2()).unwrap();
2042
2043        // A handful of arbitrary bytes with no complete chunk in them.
2044        let (out, events) = session.handle_data(&[0x03, 0x01, 0x02]).unwrap();
2045        assert!(out.is_empty());
2046        assert!(events.is_empty());
2047    }
2048
2049    // ── Mutation-check sentinels ──────────────────────────────────────────
2050
2051    #[test]
2052    fn mutation_check_publish_event_must_echo_actual_stream_key() {
2053        let (_session, _out, events) = publish_flow(ServerConfig::default(), "specific-key-xyz");
2054        let publish_event = events
2055            .iter()
2056            .find_map(|e| match e {
2057                ServerEvent::Publish { stream_key, .. } => Some(stream_key.clone()),
2058                _ => None,
2059            })
2060            .expect("Publish event");
2061        assert_eq!(
2062            publish_event, "specific-key-xyz",
2063            "a hardcoded/ignored stream_key would fail this"
2064        );
2065    }
2066
2067    #[test]
2068    fn mutation_check_flv_file_header_bytes_are_exact() {
2069        let header = flv_file_header();
2070        assert_eq!(
2071            header,
2072            vec![
2073                b'F',
2074                b'L',
2075                b'V',        // Signature
2076                1,           // Version
2077                0b0000_0101, // TypeFlags: audio + video
2078                0,
2079                0,
2080                0,
2081                9, // DataOffset = 9
2082                0,
2083                0,
2084                0,
2085                0, // PreviousTagSize0 = 0
2086            ]
2087        );
2088    }
2089
2090    // ── Regression: client Set Chunk Size mid-buffer (#738 Task 8) ────────
2091
2092    #[test]
2093    fn client_set_chunk_size_takes_effect_before_next_message_in_same_call() {
2094        // Reproduces the exact bug a real `ffmpeg` publish surfaced: the
2095        // client sends its own SetChunkSize (as ffmpeg does, right after
2096        // `connect`) and, in the very same TCP segment / `handle_data` call,
2097        // the next message is already framed at the *new* chunk size. If
2098        // `ServerSession` collected a whole batch of messages from one
2099        // `ChunkAssembler::push` before dispatching any of them (applying
2100        // SetChunkSize's effect only afterwards), that next message would
2101        // be misparsed under the *old* chunk size.
2102        let (mut session, _out, _events) = publish_flow(ServerConfig::default(), "testkey");
2103
2104        const NEW_CHUNK_SIZE: u32 = 4096;
2105        let set_chunk_size_bytes = ChunkWriter::new()
2106            .write(&ProtocolControl::SetChunkSize(NEW_CHUNK_SIZE).to_message())
2107            .unwrap();
2108
2109        // A video payload bigger than the *default* 128-byte chunk size but
2110        // written by a client-side writer already using the new size, so it
2111        // lands as a single physical chunk — the shape a real client
2112        // produces immediately after raising its chunk size.
2113        let big_payload = vec![0x17u8; 300];
2114        let mut client_writer = ChunkWriter::new();
2115        client_writer.set_chunk_size(NEW_CHUNK_SIZE);
2116        let video_bytes = client_writer
2117            .write(&Message {
2118                chunk_stream_id: 6,
2119                timestamp: 0,
2120                message_type_id: msg_type::VIDEO,
2121                message_stream_id: 1,
2122                payload: big_payload.clone(),
2123            })
2124            .unwrap();
2125
2126        let mut combined = set_chunk_size_bytes;
2127        combined.extend_from_slice(&video_bytes);
2128
2129        // Both messages arrive in a single `handle_data` call: this is the
2130        // exact shape that broke before the incremental-dispatch fix.
2131        let (_out, events) = session.handle_data(&combined).expect(
2132            "SetChunkSize must take effect before parsing the message that follows it \
2133                     in the same handle_data call, not only on a subsequent call",
2134        );
2135
2136        let media = events
2137            .iter()
2138            .find_map(|e| match e {
2139                ServerEvent::Media { flv } => Some(flv.clone()),
2140                _ => None,
2141            })
2142            .expect("the video message must still be parsed into a Media event");
2143        assert!(
2144            media
2145                .windows(big_payload.len())
2146                .any(|w| w == big_payload.as_slice()),
2147            "the video payload must survive intact through the chunk-size change"
2148        );
2149    }
2150
2151    #[test]
2152    fn control_chunk_stream_id_constant_matches_message_module() {
2153        // Sanity: our reply csid choice for command messages must not
2154        // collide with the reserved control/user-control csid.
2155        assert_ne!(COMMAND_CHUNK_STREAM_ID, CTRL_CSID);
2156    }
2157
2158    #[test]
2159    fn next_stream_id_saturates_instead_of_overflowing() {
2160        // Mutation check: with `next_stream_id` already at `u32::MAX`, a
2161        // bare `+= 1` panics (debug-mode overflow check) or wraps to 0
2162        // (release mode) — either way, the wrong behaviour. `saturating_add`
2163        // must instead keep it pinned at `u32::MAX`.
2164        let mut session = ServerSession::with_defaults();
2165        session.handle_data(&build_c0_c1()).unwrap();
2166        session.handle_data(&build_c2()).unwrap();
2167        session.handle_data(&connect_bytes("live")).unwrap();
2168
2169        session.next_stream_id = u32::MAX;
2170        let (out, _events) = session
2171            .handle_data(&create_stream_bytes())
2172            .expect("createStream must not panic when next_stream_id is already u32::MAX");
2173
2174        let commands = decode_commands(&out);
2175        let result = commands
2176            .iter()
2177            .find(|c| c.name == "_result")
2178            .expect("createStream _result reply");
2179        assert_eq!(
2180            result.arguments.get(1),
2181            Some(&Amf0Value::Number(f64::from(u32::MAX))),
2182            "the stream id allocated at the u32::MAX boundary must still be u32::MAX"
2183        );
2184        assert_eq!(
2185            session.next_stream_id,
2186            u32::MAX,
2187            "next_stream_id must saturate at u32::MAX, not wrap to 0"
2188        );
2189    }
2190
2191    // ── serde (feature "serde") ────────────────────────────────────────────
2192
2193    #[cfg(feature = "serde")]
2194    #[test]
2195    fn server_config_and_server_event_serde_round_trip() {
2196        let config = ServerConfig::default()
2197            .with_chunk_size(8192)
2198            .with_expected_stream_key(Some("k".to_string()));
2199        let json = serde_json::to_string(&config).expect("serialize ServerConfig");
2200        let back: ServerConfig = serde_json::from_str(&json).expect("deserialize ServerConfig");
2201        assert_eq!(back.chunk_size, config.chunk_size);
2202        assert_eq!(back.expected_stream_key, config.expected_stream_key);
2203
2204        let event = ServerEvent::Publish {
2205            app: "live".to_string(),
2206            stream_key: "testkey".to_string(),
2207            stream_id: 1,
2208        };
2209        let json = serde_json::to_string(&event).expect("serialize ServerEvent");
2210        let back: ServerEvent = serde_json::from_str(&json).expect("deserialize ServerEvent");
2211        assert_eq!(back, event);
2212    }
2213}