Skip to main content

rtmp_runtime/
server.rs

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