Skip to main content

rtmp_runtime/
server.rs

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