Skip to main content

rtmp_runtime/
server.rs

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